diff --git a/scripts/bundle_moltenvk_macos.sh b/scripts/bundle_moltenvk_macos.sh index b1054450..39ff143e 100644 --- a/scripts/bundle_moltenvk_macos.sh +++ b/scripts/bundle_moltenvk_macos.sh @@ -1,60 +1,60 @@ -#!/usr/bin/env bash -# Bundle the released fallback and the pinned mesh-capable MoltenVK driver. -set -euo pipefail -cd "$(git rev-parse --show-toplevel)" -: "${RUNNER_TEMP:?RUNNER_TEMP must be set}" -: "${MOLTENVK_VERSION:?MOLTENVK_VERSION must be set}" -: "${MOLTENVK_SHA256:?MOLTENVK_SHA256 must be set}" - -archive="$RUNNER_TEMP/MoltenVK-macos.tar" -package="$RUNNER_TEMP/MoltenVK" -curl --fail --location --retry 3 \ - --output "$archive" \ - "https://github.com/KhronosGroup/MoltenVK/releases/download/$MOLTENVK_VERSION/MoltenVK-macos.tar" -echo "$MOLTENVK_SHA256 $archive" | shasum -a 256 --check -tar -xf "$archive" -C "$RUNNER_TEMP" -install -m 755 \ - "$package/MoltenVK/dynamic/dylib/macOS/libMoltenVK.dylib" \ - _Build/macos/install/libMoltenVK.dylib -install -m 644 "$package/LICENSE" _Build/macos/install/LICENSE.MoltenVK -codesign --force --sign - --timestamp=none _Build/macos/install/libMoltenVK.dylib - -revision=b93bdef3e3a218a2a670c9a25f65682967ebdc85 -mesh_dir="$RUNNER_TEMP/MoltenVK-mesh-$revision" -mkdir "$mesh_dir" -git -C "$mesh_dir" init -git -C "$mesh_dir" remote add origin https://github.com/KhronosGroup/MoltenVK.git -git -C "$mesh_dir" fetch --no-tags --depth=1 origin "$revision" -git -C "$mesh_dir" checkout --detach FETCH_HEAD -if [[ "$(git -C "$mesh_dir" rev-parse HEAD)" != "$revision" ]]; then - echo "Unexpected MoltenVK revision" >&2 - exit 1 -fi -python3 scripts/patch_moltenvk_mesh_budget.py "$mesh_dir" -git -C "$mesh_dir" diff --check -( - cd "$mesh_dir" - ./fetchDependencies --macos - make macos -) - -install_dir="_Build/macos/install" -app="$install_dir/KytyPlus.app" -frameworks="$app/Contents/Frameworks" -driver="$mesh_dir/Package/Latest/MoltenVK/dynamic/dylib/macOS/libMoltenVK.dylib" -test -f "$driver" -lipo "$driver" -verify_arch x86_64 -mv "$install_dir/libMoltenVK.dylib" "$install_dir/libMoltenVK-1.4.2.dylib" -install -m 755 "$driver" "$install_dir/libMoltenVK.dylib" -install -m 644 "$mesh_dir/LICENSE" "$install_dir/LICENSE.MoltenVK-mesh" -codesign --force --sign - --timestamp=none "$install_dir/libMoltenVK.dylib" -mkdir -p "$frameworks" -install -m 755 "$install_dir/libMoltenVK.dylib" "$frameworks/libMoltenVK.dylib" -install -m 755 "$install_dir/libMoltenVK-1.4.2.dylib" "$frameworks/libMoltenVK-1.4.2.dylib" -codesign --force --sign - --options runtime --entitlements src/macos_jit.entitlements "$app/Contents/MacOS/kyty_emulator" -codesign --force --sign - --timestamp=none --preserve-metadata=entitlements,requirements,flags "$app" -codesign --verify --strict "$app/Contents/MacOS/kyty_emulator" -codesign --verify --strict "$frameworks/libMoltenVK.dylib" -codesign --verify --strict "$install_dir/libMoltenVK-1.4.2.dylib" -printf '%s\n' 'MoltenVK mesh PR #2842 b93bdef3e3a218a2a670c9a25f65682967ebdc85; M4 Pro tester verified 12288-byte LDS and first real frame. Upstream development driver; 1.4.2 fallback included.' > "$install_dir/MOLTENVK_VERSION.txt" - +#!/usr/bin/env bash +# Bundle the released fallback and the pinned mesh-capable MoltenVK driver. +set -euo pipefail +cd "$(git rev-parse --show-toplevel)" +: "${RUNNER_TEMP:?RUNNER_TEMP must be set}" +: "${MOLTENVK_VERSION:?MOLTENVK_VERSION must be set}" +: "${MOLTENVK_SHA256:?MOLTENVK_SHA256 must be set}" + +archive="$RUNNER_TEMP/MoltenVK-macos.tar" +package="$RUNNER_TEMP/MoltenVK" +curl --fail --location --retry 3 \ + --output "$archive" \ + "https://github.com/KhronosGroup/MoltenVK/releases/download/$MOLTENVK_VERSION/MoltenVK-macos.tar" +echo "$MOLTENVK_SHA256 $archive" | shasum -a 256 --check +tar -xf "$archive" -C "$RUNNER_TEMP" +install -m 755 \ + "$package/MoltenVK/dynamic/dylib/macOS/libMoltenVK.dylib" \ + _Build/macos/install/libMoltenVK.dylib +install -m 644 "$package/LICENSE" _Build/macos/install/LICENSE.MoltenVK +codesign --force --sign - --timestamp=none _Build/macos/install/libMoltenVK.dylib + +revision=b93bdef3e3a218a2a670c9a25f65682967ebdc85 +mesh_dir="$RUNNER_TEMP/MoltenVK-mesh-$revision" +mkdir "$mesh_dir" +git -C "$mesh_dir" init +git -C "$mesh_dir" remote add origin https://github.com/KhronosGroup/MoltenVK.git +git -C "$mesh_dir" fetch --no-tags --depth=1 origin "$revision" +git -C "$mesh_dir" checkout --detach FETCH_HEAD +if [[ "$(git -C "$mesh_dir" rev-parse HEAD)" != "$revision" ]]; then + echo "Unexpected MoltenVK revision" >&2 + exit 1 +fi +python3 scripts/patch_moltenvk_mesh_budget.py "$mesh_dir" +git -C "$mesh_dir" diff --check +( + cd "$mesh_dir" + ./fetchDependencies --macos + make macos +) + +install_dir="_Build/macos/install" +app="$install_dir/KytyPlus.app" +frameworks="$app/Contents/Frameworks" +driver="$mesh_dir/Package/Latest/MoltenVK/dynamic/dylib/macOS/libMoltenVK.dylib" +test -f "$driver" +lipo "$driver" -verify_arch x86_64 +mv "$install_dir/libMoltenVK.dylib" "$install_dir/libMoltenVK-1.4.2.dylib" +install -m 755 "$driver" "$install_dir/libMoltenVK.dylib" +install -m 644 "$mesh_dir/LICENSE" "$install_dir/LICENSE.MoltenVK-mesh" +codesign --force --sign - --timestamp=none "$install_dir/libMoltenVK.dylib" +mkdir -p "$frameworks" +install -m 755 "$install_dir/libMoltenVK.dylib" "$frameworks/libMoltenVK.dylib" +install -m 755 "$install_dir/libMoltenVK-1.4.2.dylib" "$frameworks/libMoltenVK-1.4.2.dylib" +codesign --force --sign - --options runtime --entitlements src/macos_jit.entitlements "$app/Contents/MacOS/kyty_emulator" +codesign --force --sign - --timestamp=none --preserve-metadata=entitlements,requirements,flags "$app" +codesign --verify --strict "$app/Contents/MacOS/kyty_emulator" +codesign --verify --strict "$frameworks/libMoltenVK.dylib" +codesign --verify --strict "$install_dir/libMoltenVK-1.4.2.dylib" +printf '%s\n' 'MoltenVK mesh PR #2842 b93bdef3e3a218a2a670c9a25f65682967ebdc85; 32 KiB profile: 16384-byte LDS, 8184-byte output, 8200-byte staging. Experimental; M4 Pro validation pending. Upstream development driver; 1.4.2 fallback included.' > "$install_dir/MOLTENVK_VERSION.txt" + diff --git a/scripts/patch_moltenvk_mesh_budget.py b/scripts/patch_moltenvk_mesh_budget.py index 89051ef1..4464e238 100644 --- a/scripts/patch_moltenvk_mesh_budget.py +++ b/scripts/patch_moltenvk_mesh_budget.py @@ -1,47 +1,75 @@ -#!/usr/bin/env python3 -"""Apply a narrowly scoped experimental MoltenVK mesh-memory budget rebalance.""" -import argparse -import hashlib -from pathlib import Path -import subprocess -import sys - -REVISION = "b93bdef3e3a218a2a670c9a25f65682967ebdc85" -SOURCE = "MoltenVK/MoltenVK/GPUObjects/MVKDevice.mm" -BLOB = "b6dea714037baea257f7dab2fd3b8edd92fb64e9" -REPLACEMENTS = ( - ("\t\t\t\tuint32_t meshShared = (lim.maxComputeSharedMemorySize - sizeof(uint32_t[2]) - meshPrims * sizeof(uint32_t[4])) / 2;", "\t\t\t\t// Keep the upstream staging reservation. Rebalance exactly one dword\n\t\t\t\t// from the output budget to LDS on the 32 KiB threadgroup-memory tier.\n\t\t\t\t// Astro Bot requests a full 12 KiB of LDS. The total budget is unchanged.\n\t\t\t\tconst uint32_t meshStaging = sizeof(uint32_t[2]) + meshPrims * sizeof(uint32_t[4]);\n\t\t\t\tconst uint32_t meshBudget = lim.maxComputeSharedMemorySize > meshStaging\n\t\t\t\t\t? lim.maxComputeSharedMemorySize - meshStaging : 0;\n\t\t\t\tuint32_t meshShared = meshBudget / 2;\n\t\t\t\tuint32_t meshOutput = meshShared;\n\t\t\t\tif (lim.maxComputeSharedMemorySize == 32u * KIBI &&\n\t\t\t\t\tmeshShared == 12u * KIBI - sizeof(uint32_t)) {\n\t\t\t\t\tmeshShared += sizeof(uint32_t);\n\t\t\t\t\tmeshOutput -= sizeof(uint32_t);\n\t\t\t\t}"), - ("\t\t\t\tmeshProps->maxMeshSharedMemorySize = meshProps->maxMeshOutputMemorySize = meshShared;", "\t\t\t\tmeshProps->maxMeshSharedMemorySize = meshShared;\n\t\t\t\tmeshProps->maxMeshOutputMemorySize = meshOutput;"), - ("\t\t\t\tmeshProps->maxMeshPayloadAndSharedMemorySize = meshProps->maxMeshPayloadAndOutputMemorySize = payload + meshShared;", "\t\t\t\tmeshProps->maxMeshPayloadAndSharedMemorySize = payload + meshShared;\n\t\t\t\tmeshProps->maxMeshPayloadAndOutputMemorySize = payload + meshOutput;"), -) - -def patched_source(source: str) -> str: - for old, new in REPLACEMENTS: - if source.count(old) != 1: - raise ValueError("Expected exactly one upstream mesh-budget anchor: " + old) - source = source.replace(old, new, 1) - return source - -def git_blob(data: bytes) -> str: - return hashlib.sha1(b"blob " + str(len(data)).encode("ascii") + b"\0" + data).hexdigest() - -def main() -> None: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("checkout", type=Path) - args = parser.parse_args() - root = args.checkout.resolve() - revision = subprocess.check_output( - ["git", "-C", str(root), "rev-parse", "HEAD"], text=True - ).strip() - if revision != REVISION: - sys.exit("Refusing to patch a different MoltenVK revision: " + revision) - path = root / SOURCE - source = path.read_bytes() - if git_blob(source) != BLOB: - sys.exit("Refusing to patch a changed MoltenVK source file") - result = patched_source(source.decode("utf-8")).encode("utf-8") - path.write_bytes(result) - print("MoltenVK mesh budget: 32768 - 8200 = 24568 bytes; LDS 12288, output 12280.") - -if __name__ == "__main__": - main() +#!/usr/bin/env python3 +"""Apply the experimental MoltenVK mesh-memory budget profile for Apple GPUs.""" +import argparse +import hashlib +from pathlib import Path +import subprocess +import sys + +REVISION = "b93bdef3e3a218a2a670c9a25f65682967ebdc85" +SOURCE = "MoltenVK/MoltenVK/GPUObjects/MVKDevice.mm" +BLOB = "b6dea714037baea257f7dab2fd3b8edd92fb64e9" +OLD_MESH = " uint32_t meshShared = (lim.maxComputeSharedMemorySize - sizeof(uint32_t[2]) - meshPrims * sizeof(uint32_t[4])) / 2;" +NEW_MESH = ( + " // Preserve the guest mesh shader's full 16 KiB LDS requirement on 32 KiB Apple GPUs.\n" + " // The remaining 8,184 bytes are available for staged mesh outputs after\n" + " // reserving the two counters and 512 triangle indices.\n" + " const uint32_t meshStaging = sizeof(uint32_t[2]) + meshPrims * sizeof(uint32_t[4]);\n" + " const uint32_t meshBudget = lim.maxComputeSharedMemorySize > meshStaging\n" + " ? lim.maxComputeSharedMemorySize - meshStaging : 0;\n" + " uint32_t meshShared = meshBudget / 2;\n" + " uint32_t meshOutput = meshBudget - meshShared;\n" + " if (lim.maxComputeSharedMemorySize == 32u * KIBI &&\n" + " meshBudget >= 16u * KIBI) {\n" + " meshShared = 16u * KIBI;\n" + " meshOutput = meshBudget - meshShared;\n" + " }" +) +REPLACEMENTS = ( + (OLD_MESH, NEW_MESH), + ( + " meshProps->maxMeshSharedMemorySize = meshProps->maxMeshOutputMemorySize = meshShared;", + " meshProps->maxMeshSharedMemorySize = meshShared;\n" + " meshProps->maxMeshOutputMemorySize = meshOutput;" + ), + ( + " meshProps->maxMeshPayloadAndSharedMemorySize = meshProps->maxMeshPayloadAndOutputMemorySize = payload + meshShared;", + " meshProps->maxMeshPayloadAndSharedMemorySize = payload + meshShared;\n" + " meshProps->maxMeshPayloadAndOutputMemorySize = payload + meshOutput;" + ), +) + + +def patched_source(source: str) -> str: + for old, new in REPLACEMENTS: + if source.count(old) != 1: + raise ValueError("Expected exactly one upstream mesh-budget anchor: " + old) + source = source.replace(old, new, 1) + return source + + +def git_blob(data: bytes) -> str: + return hashlib.sha1(b"blob " + str(len(data)).encode("ascii") + bytes([0]) + data).hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("checkout", type=Path) + args = parser.parse_args() + root = args.checkout.resolve() + revision = subprocess.check_output( + ["git", "-C", str(root), "rev-parse", "HEAD"], text=True + ).strip() + if revision != REVISION: + sys.exit("Refusing to patch a different MoltenVK revision: " + revision) + path = root / SOURCE + source = path.read_bytes() + if git_blob(source) != BLOB: + sys.exit("Refusing to patch a changed MoltenVK source file") + result = patched_source(source.decode("utf-8")).encode("utf-8") + path.write_bytes(result) + print("MoltenVK mesh budget: 32768 - 8200 = 24568 bytes; LDS 16384, output 8184.") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp b/src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp index e39e282e..4a094535 100644 --- a/src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp +++ b/src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp @@ -1,1040 +1,1058 @@ -#include "graphics/host_gpu/renderer/pipeline/pipelineCache.h" - -#include "common/assert.h" -#include "common/emulatorConfig.h" -#include "common/file.h" -#include "common/logging/log.h" -#include "common/profiler.h" -#include "common/threads.h" -#include "graphics/guest_gpu/gpu_format.h" -#include "graphics/guest_gpu/hardwareContext.h" -#include "graphics/host_gpu/renderer/colorRenderTarget.h" -#include "graphics/host_gpu/renderer/debug.h" -#include "graphics/host_gpu/renderer/depthRenderTarget.h" -#include "graphics/host_gpu/renderer/image/imageView.h" -#include "graphics/host_gpu/renderer/pipeline/blendMapping.h" -#include "graphics/host_gpu/renderer/render.h" -#include "graphics/host_gpu/renderer/renderContext.h" -#include "graphics/shader/recompiler/ShaderRecompiler.h" -#include "graphics/shader/shaderCompiler.h" -#include "graphics/presentation/performanceHud.h" -#include "kernel/memory.h" -#include "loader/systemContent.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Libs::Graphics { - -namespace { - -constexpr auto DriverCacheSaveInterval = std::chrono::minutes {5}; - -uint8_t RemapSourceAlphaFactor(uint8_t factor) { - switch (static_cast(factor)) { - case Prospero::BlendFactor::kSrcAlpha: - return static_cast(Prospero::BlendFactor::kSrc1Alpha); - case Prospero::BlendFactor::kOneMinusSrcAlpha: - return static_cast(Prospero::BlendFactor::kOneMinusSrc1Alpha); - default: return factor; - } -} - -vk::PolygonMode ResolvePolygonMode(const HW::ModeControl& mode, bool cull_front, bool cull_back) { - // CxPrimitiveSetup::PolygonMode disables both per-face modes when it is zero. - if (mode.poly_mode == 0) { - return vk::PolygonMode::eFill; - } - EXIT_NOT_IMPLEMENTED(mode.poly_mode != 1); - if (cull_front && cull_back) { - return vk::PolygonMode::eFill; - } - if (!cull_front && !cull_back && mode.polymode_front_ptype != mode.polymode_back_ptype) { - EXIT("Pipeline: different polygon modes for two visible faces are unsupported\n"); - } - // Vulkan has one polygon mode. A culled face does not constrain that mode. - const auto polygon_mode = cull_front ? mode.polymode_back_ptype : mode.polymode_front_ptype; - switch (polygon_mode) { - case 0: return vk::PolygonMode::ePoint; - case 1: return vk::PolygonMode::eLine; - case 2: return vk::PolygonMode::eFill; - default: EXIT("Pipeline: invalid polygon mode %u\n", polygon_mode); - } -} - -std::string DriverCacheSignature(const vk::PhysicalDeviceProperties& properties) { - constexpr char hex[] = "0123456789abcdef"; - std::string uuid(VK_UUID_SIZE * 2, '0'); - for (size_t i = 0; i < VK_UUID_SIZE; i++) { - uuid[i * 2] = hex[properties.pipelineCacheUUID[i] >> 4u]; - uuid[i * 2 + 1] = hex[properties.pipelineCacheUUID[i] & 0xfu]; - } - // Driver cache entries already distinguish shader code and pipeline state across builds. - return fmt::format("KytyPC2:{:08x}:{:08x}:{:08x}:{}\n", - properties.vendorID, properties.deviceID, properties.driverVersion, uuid); -} - -std::string PipelineCacheTitleId() { - std::string title_id; - if ((!Loader::SystemContentParamSfoGetString("TITLE_ID", &title_id) || title_id.empty()) && - (!Loader::SystemContentParamSfoGetString("CONTENT_ID", &title_id) || title_id.empty())) { - return {}; - } - if (!std::ranges::all_of(title_id, [](unsigned char c) { - return std::isalnum(c) != 0 || c == '-' || c == '_'; - })) { - return {}; - } - return title_id; -} - -template -void PipelineCacheLog(fmt::format_string format, Args&&... args) { - auto message = fmt::format(format, std::forward(args)...); - message += '\n'; - Log::WriteToConsoleAndLog(message); -} - -bool ReadShaderGuestMemory(void*, uint64_t address, std::span values) { - // Scalar and unformatted buffer dependencies use the same backing as native raw loads. - // Image synchronization belongs to formatted buffer bindings, not these reads. - return !values.empty() && - Libs::LibKernel::Memory::TryReadBufferBacking(address, values.data(), values.size_bytes()); -} - -void DumpShaderSpirv(const char* stage_name, uint64_t shader_hash, - const std::vector& spirv) { - if (!Config::GraphicsDebugDumpEnabled()) { - return; - } - static std::atomic_int id = 0; - const auto path = Config::GetShaderLogFolder() / fmt::format("{:04d}_new_shader_{}_{:016x}.spv", - id++, stage_name, shader_hash); - Common::File::CreateDirectories(path.parent_path()); - Common::File file(path); - if (file.IsInvalid()) { - const auto path_text = Common::PathToString(path); - LOGF_COLOR(Log::Color::BrightRed, "Can't create file: %s\n", path_text.c_str()); - return; - } - file.Write(spirv.data(), spirv.size() * sizeof(uint32_t)); -} - -void DumpShaderOriginal(const char* stage_name, uint64_t shader_hash, - std::span code) { - if (!Config::GraphicsDebugDumpEnabled()) { - return; - } - EXIT_IF(code.empty()); - static std::atomic_int id = 0; - const auto path = Config::GetShaderLogFolder() / "original" / - fmt::format("{:04d}_new_shader_{}_{:016x}.bin", id++, stage_name, shader_hash); - Common::File::CreateDirectories(path.parent_path()); - Common::File file(path); - if (file.IsInvalid()) { - const auto path_text = Common::PathToString(path); - LOGF_COLOR(Log::Color::BrightRed, "Can't create file: %s\n", path_text.c_str()); - return; - } - file.Write(code.data(), code.size_bytes()); -} - -bool ValidateShaderSpirv(const char* label, uint64_t shader_hash, - const std::vector& spirv, bool maintenance8_enabled) { - if (!Config::ShaderValidationEnabled()) { - return true; - } - spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_3); - std::string messages; - tools.SetMessageConsumer([&messages](spv_message_level_t, const char*, - const spv_position_t& position, const char* message) { - messages += fmt::format("{}: {} ({}) {}\n", static_cast(position.line), - static_cast(position.column), static_cast(position.index), - message); - }); - spvtools::ValidatorOptions validator_options; - validator_options.SetAllowOffsetTextureOperand(maintenance8_enabled); - if (tools.Validate(spirv.data(), spirv.size(), validator_options)) { - return true; - } - spvtools::SpirvTools disassembler(SPV_ENV_VULKAN_1_2); - std::string text; - disassembler.Disassemble(spirv, &text, - static_cast(SPV_BINARY_TO_TEXT_OPTION_NO_HEADER) | - static_cast(SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES) | - static_cast(SPV_BINARY_TO_TEXT_OPTION_COMMENT) | - static_cast(SPV_BINARY_TO_TEXT_OPTION_INDENT) | - static_cast(SPV_BINARY_TO_TEXT_OPTION_COLOR)); - LOGF_COLOR(Log::Color::BrightRed, "%s SPIR-V validation failed hash=0x%016" PRIx64 ":\n%s", - label, shader_hash, messages.c_str()); - LOGF("%s\n", text.c_str()); - return false; -} - -} // namespace - -std::size_t PipelineCache::GraphicsPipelineKeyHash::operator()(const GraphicsPipelineKey& key) const { - std::size_t hash = 0; - PipelineKeyHash::Mix(hash, key.rendering.color_count); - for (uint32_t i = 0; i < key.rendering.color_count; i++) { - PipelineKeyHash::Mix(hash, static_cast(key.rendering.color_formats[i])); - } - PipelineKeyHash::Mix(hash, static_cast(key.rendering.depth_format)); - PipelineKeyHash::Mix(hash, static_cast(key.rendering.stencil_format)); - for (const auto id: key.vertex_shader_ids) { - PipelineKeyHash::Mix(hash, id); - } - PipelineKeyHash::Mix(hash, key.ps_shader_id); - PipelineKeyHash::Mix(hash, key.vertex_input.binding_count); - for (uint32_t i = 0; i < key.vertex_input.binding_count; i++) { - PipelineKeyHash::Mix(hash, key.vertex_input.bindings[i].stride); - PipelineKeyHash::Mix(hash, key.vertex_input.bindings[i].instance); - } - PipelineKeyHash::Mix(hash, key.vertex_input.attribute_count); - for (uint32_t i = 0; i < key.vertex_input.attribute_count; i++) { - PipelineKeyHash::Mix(hash, key.vertex_input.attributes[i].offset); - PipelineKeyHash::Mix(hash, key.vertex_input.attributes[i].binding); - } - PipelineKeyHash::Mix(hash, XXH3_64bits(&key.static_params, sizeof(key.static_params))); - return hash; -} - -struct PipelineCache::ProgramCache { - struct ProgramKey { - ShaderType stage = ShaderType::Unknown; - uint64_t hash = 0; - uint32_t user_data_count = 0; - uint32_t code_size = 0; - std::vector static_state; - - bool operator==(const ProgramKey&) const = default; - }; - - struct Permutation { - std::vector function_code; - ShaderRecompiler::IR::ResourceSpecialization specialization; - ShaderRecompiler::IR::CompiledShaderInfo program; - ShaderProgram handle; - }; - - struct SourceEntry { - SourceEntry(ShaderRecompiler::IR::ResourcePlan plan, - std::unique_ptr call_source) - : call_source(std::move(call_source)), resource_plan(std::move(plan)) { - permutations.reserve(8); - } - - std::span FunctionCode() const { - return call_source - ? std::span(call_source->linked->code).subspan(call_source->code.size()) - : std::span{}; - } - - bool RefreshCallSource(const ShaderRecompiler::IR::SrtRuntime& runtime) { - const auto revision = call_source->revision; - ShaderRecompiler::RefreshShaderSource(*call_source, runtime); - resource_plan.source_reads = call_source->reads; - return revision != call_source->revision; - } - - template - Permutation* FindPermutation(const ShaderRecompiler::IR::SrtRuntime& runtime, - uint32_t push_data_cursor) { - EXIT_IF(!ShaderRecompiler::IR::MaterializeResources( - resource_plan, runtime, resources, specialization)); - for (auto& candidate: permutations) { - const auto& layout = candidate.program.bindings; - if (layout.push_data_start_dword != ShaderRecompiler::IR::PushData::StartFor( - push_data_cursor, layout.ShaderDataDwords()) || - candidate.specialization != specialization) { - continue; - } - if constexpr (HasCalls) { - if (!std::ranges::equal(candidate.function_code, FunctionCode())) continue; - } - return &candidate; - } - return nullptr; - } - - std::unique_ptr call_source; - ShaderRecompiler::IR::ResourcePlan resource_plan; - ShaderRecompiler::IR::ResourceSnapshot resources; - ShaderRecompiler::IR::ResourceSpecialization specialization; - std::vector permutations; - }; - - struct ProgramKeyHash { - std::size_t operator()(const ProgramKey& key) const { - std::size_t hash = static_cast(key.stage); - PipelineKeyHash::Mix(hash, static_cast(key.hash)); - if constexpr (sizeof(std::size_t) < sizeof(uint64_t)) { - PipelineKeyHash::Mix(hash, static_cast(key.hash >> 32u)); - } - PipelineKeyHash::Mix(hash, key.user_data_count); - PipelineKeyHash::Mix(hash, key.code_size); - PipelineKeyHash::Mix(hash, key.static_state.size()); - // Bucket same-shape static variants by source. ProgramKey equality performs the one - // exact state comparison needed on a stable hit without hashing the full state first. - return hash; - } - }; - - static constexpr std::size_t MaxStaticKeyWords = 32 + ShaderVertexInputInfo::RES_MAX * 6; - - Permutation CompilePermutation(const char* stage_name, - const ShaderRecompiler::CompileOptions& options, - ShaderRecompiler::TranslateResult translated, - ShaderRecompiler::IR::ResourceSpecialization specialization, - uint32_t push_data_start_dword, - std::span function_code) { - auto result = ShaderRecompiler::CompileProgram(std::move(translated), options, - specialization, push_data_start_dword); - if (!ValidateShaderSpirv(options.dump_label, options.shader_hash, result.spirv, - options.maintenance8_enabled)) { - DumpShaderSpirv(stage_name, options.shader_hash, result.spirv); - EXIT("%s failed hash=0x%016" PRIx64 ": SPIR-V validation failed\n", options.dump_label, - options.shader_hash); - } - DumpShaderSpirv(stage_name, options.shader_hash, result.spirv); - - const auto module = CompileSPV(result.spirv, graphics.device); - EXIT_IF(module == nullptr); - if (options.dump_ir) { - LOGF("%s SPIR-V words=%" PRIu64 " wave_size=%u\n", options.dump_label, - static_cast(result.spirv.size()), options.wave_size); - } - return { - .function_code = {function_code.begin(), function_code.end()}, - .specialization = std::move(specialization), - .program = std::move(result.program).TakeCompiledInfo(), - .handle = {.id = ++next_shader_id, .module = module}, - }; - } - - template - ShaderProgram Get(const ShaderParams& params, InputInfo& input_info, - uint32_t& push_data_cursor) { - ShaderType stage; - if constexpr (std::is_same_v) { - stage = input_info.logical_stage; - } else if constexpr (std::is_same_v) { - stage = ShaderType::Pixel; - } else { - static_assert(std::is_same_v); - stage = ShaderType::Compute; - } - - const auto user_data = std::span(params.user_data).first(params.user_data_count); - lookup_key.stage = stage; - lookup_key.hash = params.hash; - lookup_key.user_data_count = params.user_data_count; - lookup_key.code_size = static_cast(params.code.size()); - BuildStageStaticKey(input_info, lookup_key.static_state); - auto entry = programs.find(lookup_key); - ShaderRecompiler::IR::SrtRuntime runtime { - .user_data = user_data, - .shader_base = params.Base(), - .read_specialization_memory = ReadShaderGuestMemory, - }; - if constexpr (std::is_same_v) { - runtime.workgroup_counts = input_info.workgroup_counts; - runtime.indirect_args_address = input_info.indirect_args_address; - } - bool source_changed = false; - if (entry != programs.end()) { - auto& cached = entry->second; - Permutation* permutation = nullptr; - if (cached.call_source) { - source_changed = cached.RefreshCallSource(runtime); - if (!source_changed) permutation = cached.FindPermutation(runtime, push_data_cursor); - } else { - permutation = cached.FindPermutation(runtime, push_data_cursor); - } - if (permutation != nullptr) { - input_info.stage = {.program = &permutation->program, .resources = &entry->second.resources}; - permutation->program.bindings.AdvancePushData(push_data_cursor); - return permutation->handle; - } - } - - ShaderStageInputInfo stage_input {}; - if constexpr (std::is_same_v) { - stage_input.vertex = &input_info; - } else if constexpr (std::is_same_v) { - stage_input.pixel = &input_info; - } else { - stage_input.compute = &input_info; - } - const char* label = nullptr; - const char* stage_name = nullptr; - switch (stage) { - case ShaderType::Vertex: label = "ShaderRecompiler VS"; stage_name = "vs"; break; - case ShaderType::Mesh: label = "ShaderRecompiler MS"; stage_name = "ms"; break; - case ShaderType::Local: label = "ShaderRecompiler LS"; stage_name = "ls"; break; - case ShaderType::TessellationControl: label = "ShaderRecompiler HS"; stage_name = "hs"; break; - case ShaderType::TessellationEvaluation: label = "ShaderRecompiler DS"; stage_name = "ds"; break; - case ShaderType::Pixel: label = "ShaderRecompiler PS"; stage_name = "ps"; break; - case ShaderType::Compute: label = "ShaderRecompiler CS"; stage_name = "cs"; break; - default: EXIT("invalid pipeline shader stage\n"); - } - ShaderRecompiler::CompileOptions options; - options.stage = stage; - options.maintenance8_enabled = graphics.maintenance8_enabled; - options.shader_hash = params.hash; - options.user_data = user_data; - options.back_code = params.back_code; - options.dump_ir = Config::GetShaderLogDirection() != Config::LogDirection::Silent; - options.early_dump = options.dump_ir; - options.emit_debug_info = Config::GraphicsDebugDumpEnabled(); - options.dump_label = label; - options.input_info = stage_input; - - if constexpr (std::is_same_v) { - options.user_data_base = 8; - options.wave_size = input_info.wave_size; - if (stage == ShaderType::Mesh || stage == ShaderType::TessellationControl) { - options.user_data_base = 0; - options.wave_size = stage == ShaderType::Mesh ? input_info.mesh.wave_size : 64u; - } - } else { - options.wave_size = input_info.wave_size; - } - DumpShaderOriginal(stage_name, options.shader_hash, params.code); - ShaderRecompiler::ShaderSource source; - if (entry == programs.end()) source = ShaderRecompiler::PrepareShaderSource(params.code, options); - auto* current = entry == programs.end() ? &source : entry->second.call_source.get(); - ShaderRecompiler::TranslateResult translated; - if (current != nullptr) { - if (current->call) { - if (entry == programs.end()) ShaderRecompiler::RefreshShaderSource(*current, runtime); - translated = ShaderRecompiler::TranslateProgram(current->linked->decoded, options); - translated.program.source_reads = current->reads; - } else { - translated = ShaderRecompiler::TranslateProgram(current->decoded, options); - } - } else { - translated = ShaderRecompiler::TranslateProgram(params.code, options); - } - if (entry == programs.end()) { - auto retained = source.call ? std::make_unique(std::move(source)) : nullptr; - entry = programs.try_emplace(lookup_key, - ShaderRecompiler::IR::ExtractResourcePlan(translated.program), std::move(retained)).first; - EXIT_IF(!ShaderRecompiler::IR::MaterializeResources( - entry->second.resource_plan, runtime, entry->second.resources, - entry->second.specialization)); - } else if (source_changed) { - entry->second.resource_plan = ShaderRecompiler::IR::ExtractResourcePlan(translated.program); - if (const auto* permutation = entry->second.FindPermutation(runtime, push_data_cursor)) { - input_info.stage = {.program = &permutation->program, .resources = &entry->second.resources}; - permutation->program.bindings.AdvancePushData(push_data_cursor); - return permutation->handle; - } - } - entry->second.permutations.push_back(CompilePermutation( - stage_name, options, std::move(translated), entry->second.specialization, push_data_cursor, - entry->second.FunctionCode())); - g_shader_permutations.fetch_add(1, std::memory_order_relaxed); - const auto& permutation = entry->second.permutations.back(); - input_info.stage = {.program = &permutation.program, .resources = &entry->second.resources}; - permutation.program.bindings.AdvancePushData(push_data_cursor); - - std::array(ShaderType::TessellationEvaluation) + 1> counts {}; - for (const auto& [key, source]: programs) { - counts[static_cast(key.stage)] += source.permutations.size(); - } - // Guest geometry shaders are compiled through the host mesh stage. - std::printf("Shaders: VS %zu | PS %zu | CS %zu | GS %zu | LS %zu | HS %zu | TES %zu\n", - counts[static_cast(ShaderType::Vertex)], - counts[static_cast(ShaderType::Pixel)], - counts[static_cast(ShaderType::Compute)], - counts[static_cast(ShaderType::Mesh)], - counts[static_cast(ShaderType::Local)], - counts[static_cast(ShaderType::TessellationControl)], - counts[static_cast(ShaderType::TessellationEvaluation)]); - return permutation.handle; - } - - explicit ProgramCache(GraphicContext& graphics): graphics(graphics) { - lookup_key.static_state.reserve(MaxStaticKeyWords); - } - ~ProgramCache() { - for (const auto& [key, entry]: programs) { - (void)key; - for (const auto& permutation: entry.permutations) { - graphics.device.destroyShaderModule(permutation.handle.module, nullptr); - } - } - } - - std::unordered_map programs; - ProgramKey lookup_key; - GraphicContext& graphics; - uint64_t next_shader_id = 0; -}; - -PipelineCache::PipelineCache(GraphicContext& graphics) - : m_graphics(graphics), m_program_cache(std::make_unique(graphics)), - m_next_driver_cache_save(std::chrono::steady_clock::now() + DriverCacheSaveInterval) { - EXIT_NOT_IMPLEMENTED(!Common::Thread::IsMainThread()); - InitializeDriverCache(); -} - -PipelineCache::~PipelineCache() { - Save(); - auto destroy = [this](const auto& pipelines) { - for (const auto& [key, pipeline]: pipelines) { - (void)key; - m_graphics.device.destroyPipeline(pipeline->pipeline, nullptr); - m_graphics.device.destroyPipelineLayout(pipeline->pipeline_layout, nullptr); - m_graphics.device.destroyDescriptorSetLayout(pipeline->descriptor_set_layout, nullptr); - } - }; - destroy(m_graphics_pipelines); - destroy(m_compute_pipelines); - if (m_driver_cache != nullptr) { - m_graphics.device.destroyPipelineCache(m_driver_cache, nullptr); - } -} - -void PipelineCache::InitializeDriverCache() { - const auto title_id = PipelineCacheTitleId(); - if (title_id.empty()) { - return; - } - if (KYTY_BUILD != KYTY_BUILD_RELEASE) { - PipelineCacheLog("Vulkan pipeline cache: disabled (non-Release build)"); - return; - } - m_driver_cache_path = std::filesystem::path("_PipelineCache") / (title_id + ".bin"); - const auto path = Common::PathToString(m_driver_cache_path); - const bool cache_exists = Common::File::IsFileExisting(m_driver_cache_path); - if (cache_exists) { - PipelineCacheLog("Vulkan pipeline cache: loading {}", path); - } else { - PipelineCacheLog("Vulkan pipeline cache: initializing {}", path); - } - std::vector initial_data; - if (cache_exists) { - Common::File file(m_driver_cache_path, Common::File::Mode::Read); - const auto file_size = file.IsInvalid() ? 0 : file.Size(); - const auto signature = DriverCacheSignature(m_graphics.GetPhysicalDeviceProperties()); - if (file_size >= signature.size() + sizeof(uint64_t) && - file_size <= std::numeric_limits::max()) { - std::string cached_signature(signature.size(), '\0'); - uint64_t payload_hash = 0; - initial_data.resize(file_size - signature.size() - sizeof(payload_hash)); - uint32_t signature_read = 0; - uint32_t hash_read = 0; - uint32_t payload_read = 0; - file.Read(cached_signature.data(), static_cast(cached_signature.size()), - &signature_read); - file.Read(&payload_hash, sizeof(payload_hash), &hash_read); - file.Read(initial_data.data(), static_cast(initial_data.size()), - &payload_read); - file.Close(); - if (signature_read != cached_signature.size() || hash_read != sizeof(payload_hash) || - payload_read != initial_data.size() || cached_signature != signature || - XXH3_64bits(initial_data.data(), initial_data.size()) != payload_hash) { - initial_data.clear(); - PipelineCacheLog( - "Vulkan pipeline cache: invalidating {} (driver or data mismatch)", - path); - } - } else { - file.Close(); - PipelineCacheLog("Vulkan pipeline cache: invalidating {} (invalid file size)", path); - } - } - - vk::PipelineCacheCreateInfo create {}; - create.initialDataSize = initial_data.size(); - create.pInitialData = initial_data.empty() ? nullptr : initial_data.data(); - auto result = m_graphics.device.createPipelineCache(&create, nullptr, &m_driver_cache); - if (result != vk::Result::eSuccess && !initial_data.empty()) { - PipelineCacheLog("Vulkan pipeline cache: driver rejected {} ({}); starting empty", path, - vk::to_string(result)); - initial_data.clear(); - create.initialDataSize = 0; - create.pInitialData = nullptr; - result = m_graphics.device.createPipelineCache(&create, nullptr, &m_driver_cache); - } - if (result != vk::Result::eSuccess) { - PipelineCacheLog("Vulkan pipeline cache: disabled ({})", vk::to_string(result)); - m_driver_cache = nullptr; - return; - } - if (!initial_data.empty()) { - PipelineCacheLog("Vulkan pipeline cache: loaded {} bytes from {}", initial_data.size(), - path); - } else { - PipelineCacheLog("Vulkan pipeline cache: initialized empty"); - } -} - -void PipelineCache::CheckpointDriverCache() { - if (m_driver_cache == nullptr) { - return; - } - m_driver_cache_dirty = true; - if (std::chrono::steady_clock::now() >= m_next_driver_cache_save) { - Save(); - } -} - -void PipelineCache::Save() { - if (m_driver_cache == nullptr || !m_driver_cache_dirty) { - return; - } - m_next_driver_cache_save = std::chrono::steady_clock::now() + DriverCacheSaveInterval; - - size_t size = 0; - vk::Result result; - std::vector payload; - for (uint32_t attempt = 0; attempt < 3; attempt++) { - size = 0; - result = m_graphics.device.getPipelineCacheData(m_driver_cache, &size, nullptr); - if (result != vk::Result::eSuccess || size == 0 || - size > std::numeric_limits::max()) { - break; - } - payload.resize(size); - result = m_graphics.device.getPipelineCacheData(m_driver_cache, &size, payload.data()); - if (result != vk::Result::eIncomplete) { - break; - } - } - if (result != vk::Result::eSuccess || size == 0 || - size > std::numeric_limits::max()) { - PipelineCacheLog("Vulkan pipeline cache: save failed ({}, {} bytes)", - vk::to_string(result), size); - return; - } - payload.resize(size); - auto prefix = DriverCacheSignature(m_graphics.GetPhysicalDeviceProperties()); - const auto payload_hash = XXH3_64bits(payload.data(), payload.size()); - prefix.append(reinterpret_cast(&payload_hash), sizeof(payload_hash)); - if (!Common::File::CreateDirectories(m_driver_cache_path.parent_path())) { - PipelineCacheLog("Vulkan pipeline cache: failed to create cache directory"); - return; - } - auto temp_path = m_driver_cache_path; - temp_path += ".tmp"; - Common::File file; - uint32_t prefix_written = 0; - uint32_t payload_written = 0; - if (file.Create(temp_path)) { - file.Write(prefix.data(), static_cast(prefix.size()), &prefix_written); - file.Write(payload.data(), static_cast(payload.size()), &payload_written); - } - const bool flushed = !file.IsInvalid() && file.Flush(); - file.Close(); - const bool written = prefix_written == prefix.size() && payload_written == payload.size() && flushed; - std::error_code error; - if (written) { - std::filesystem::rename(temp_path, m_driver_cache_path, error); - } - if (!written || error) { - PipelineCacheLog("Vulkan pipeline cache: failed to write {}", - Common::PathToString(m_driver_cache_path)); - return; - } - PipelineCacheLog("Vulkan pipeline cache: saved {} bytes to {}", payload.size(), - Common::PathToString(m_driver_cache_path)); - m_driver_cache_dirty = false; -} - -PipelineCache::GraphicsPrograms PipelineCache::GetGraphicsPrograms( - const HW::VertexShaderInfo& vertex_regs, const HW::PixelShaderInfo& pixel_regs, - const HW::ShaderRegisters& sh, const HW::Context& context, const HW::UserConfig& user_config, - std::span target_export_mapping, bool pixel_active, - std::array& vertex_info, ShaderPixelInputInfo& pixel_info) { - const bool tess_active = user_config.GetPrimType() == Prospero::PrimitiveType::kPatch; - std::array vertex_params; - if (tess_active) { - vertex_params = PrepareTessellationPrograms(vertex_regs, context, vertex_info); - } else { - vertex_params[0] = PrepareProgram(vertex_regs, context, user_config, vertex_info[0]); - } - const bool mesh_active = vertex_info[0].logical_stage == ShaderType::Mesh; - const bool object_primitive_id = context.HasObjectPrimitiveIdOutput(); - if (object_primitive_id) { - // CxObjectIdMode: register source plus a 32-bit pipelined primitive-ID addition. - EXIT_NOT_IMPLEMENTED(sh.m_paClObjprimIdCntl != 2u || mesh_active || tess_active || - !pixel_active || (sh.m_vgtDrawPayloadCntl & 8u) == 0 || - user_config.GetPrimType() != Prospero::PrimitiveType::kTriList); - const auto& target = context.GetRenderTarget(7); - EXIT_NOT_IMPLEMENTED(Prospero::ResolveRenderTargetFormat(target.info.format, - target.info.channel_type) - .buffer_format != Prospero::BufferFormat::k32UInt); - } - if (mesh_active) { - EXIT_NOT_IMPLEMENTED(!m_graphics.mesh_shader_enabled); - auto& mesh = vertex_info[0].mesh; - mesh.host_subgroup_size = m_graphics.subgroup_size; - const auto& limits = m_graphics.mesh_shader_properties; - const auto logical_threads = - mesh.threads_num[0] * mesh.threads_num[1] * mesh.threads_num[2]; - const auto host_threads = ((logical_threads + mesh.wave_size - 1u) / mesh.wave_size) * - std::min(mesh.host_subgroup_size, mesh.wave_size); - if (host_threads > limits.maxMeshWorkGroupInvocations || - host_threads > limits.maxMeshWorkGroupSize[0] || - mesh.max_vertices > limits.maxMeshOutputVertices || - mesh.max_primitives > limits.maxMeshOutputPrimitives || - mesh.lds_size_dwords * sizeof(uint32_t) > limits.maxMeshSharedMemorySize) { - EXIT("mesh shader exceeds host limits: threads=%u vertices=%u primitives=%u LDS=%u\n", - host_threads, mesh.max_vertices, mesh.max_primitives, mesh.lds_size_dwords); - } - } - ShaderParams pixel_params; - if (pixel_active) { - pixel_params = PrepareProgram(pixel_regs, sh, target_export_mapping, pixel_info); - pixel_info.object_primitive_id = object_primitive_id; - for (uint32_t export_index = 0; export_index < 8u; export_index++) { - const auto slot = ShaderPixelExportTarget(pixel_info.target_shader_mask, export_index); - if (slot >= 8u || pixel_info.target_output_mode[export_index] == 0u) continue; - const auto& rt = context.GetRenderTarget(slot); - const auto target_mask = render_target_mask_slot(context.GetRenderTargetMask(), slot); - if (rt.base.addr == 0 || target_mask == 0u) continue; - const auto format = Prospero::ResolveRenderTargetFormat(rt.info.format, rt.info.channel_type); - if (format.buffer_format != Prospero::BufferFormat::k11_11_10UNorm) continue; - const auto mapping = pixel_info.target_export_mapping[export_index]; - const auto shader_mask = render_target_mask_slot(pixel_info.target_shader_mask, slot); - const bool blend = context.GetBlendControl(slot).enable && !rt.info.blend_bypass; - if (blend || (mapping.ApplyMask(target_mask) & 7u) != 7u || - (mapping.ApplyMask(shader_mask) & 7u) != 7u || - pixel_info.target_output_mode[export_index] != 9u) { - EXIT("unsupported packed UNorm render-target export: slot=%u export=%u mode=%u " - "target_mask=0x%x shader_mask=0x%x mapping=0x%02x blend=%u\n", - slot, export_index, pixel_info.target_output_mode[export_index], target_mask, - shader_mask, mapping.packed, static_cast(blend)); - } - pixel_info.target_packed_unorm_mask |= 1u << export_index; - pixel_info.target_round_mode |= static_cast(rt.info.round_mode) << export_index; - } - if (!mesh_active && !tess_active && Prospero::IsRectList(user_config.GetPrimType())) { - pixel_info.parameter_mode = ShaderPixelParameterMode::Rectangle; - } else if (context.GetModeControl().provoking_vtx_last) { - pixel_info.parameter_mode = ShaderPixelParameterMode::LastVertex; - } else { - pixel_info.parameter_mode = ShaderPixelParameterMode::FirstVertex; - } - const auto& blend = context.GetBlendControl(0); - pixel_info.dual_source_blending = - blend.enable && !context.GetRenderTarget(0).info.blend_bypass && - (BlendFactorIsDualSource(blend.color_srcblend) || - BlendFactorIsDualSource(blend.color_destblend) || - (blend.separate_alpha_blend && (BlendFactorIsDualSource(blend.alpha_srcblend) || - BlendFactorIsDualSource(blend.alpha_destblend)))); - if (pixel_info.dual_source_blending) { - // MRT1 supplies the second blend source for target 0. - pixel_info.target_output_mode[1] = pixel_info.target_output_mode[0]; - pixel_info.target_export_mapping[1] = pixel_info.target_export_mapping[0]; - } else if (blend.enable && !context.GetRenderTarget(0).info.blend_bypass && - pixel_info.target_output_mode[0] != 0 && pixel_info.target_output_mode[0] != 7 && - std::all_of(std::begin(pixel_info.target_output_mode) + 1, - std::end(pixel_info.target_output_mode), - [](uint8_t mode) { return mode == 0; })) { - switch (ClassifyBlendMapping(blend, pixel_info.target_export_mapping[0])) { - case BlendMappingSupport::SourceAlpha: - pixel_info.alpha_blend_source = ShaderAlphaBlendSource::SourceAlpha; - break; - case BlendMappingSupport::SourceAlphaOne: - pixel_info.alpha_blend_source = ShaderAlphaBlendSource::SourceAlphaOne; - break; - case BlendMappingSupport::SourceAlphaZero: - pixel_info.alpha_blend_source = ShaderAlphaBlendSource::SourceAlphaZero; - break; - default: break; - } - if (pixel_info.alpha_blend_source != ShaderAlphaBlendSource::None) { - pixel_info.dual_source_blending = true; - pixel_info.target_output_mode[1] = pixel_info.target_output_mode[0]; - pixel_info.target_export_mapping[1] = {}; - } - } - } - if (context.GetClipControl().clip_disable) { - const auto& viewport = context.GetScreenViewport().viewports[0]; - const auto& limits = m_graphics.GetPhysicalDeviceProperties().limits; - auto& clip = vertex_info[tess_active ? 2u : 0u].clip_space; - clip.scale[0] = viewport.xscale; - clip.scale[1] = viewport.yscale; - clip.offset[0] = viewport.xoffset; - clip.offset[1] = viewport.yoffset; - clip.half_extent[0] = - static_cast(std::min(limits.maxViewportDimensions[0], 16384u)) * 0.5f; - clip.half_extent[1] = - static_cast(std::min(limits.maxViewportDimensions[1], 16384u)) * 0.5f; - clip.enabled = true; - } - uint32_t push_data_cursor = ShaderRecompiler::IR::PushData::GraphicsDrawDwords( - mesh_active, object_primitive_id); - GraphicsPrograms result; - if (pixel_active) { - result.pixel = m_program_cache->Get(pixel_params, pixel_info, push_data_cursor); - } - for (uint32_t i = 0; i < (tess_active ? 3u : 1u); i++) { - result.vertex[i] = m_program_cache->Get(vertex_params[i], vertex_info[i], push_data_cursor); - } - return result; -} - -ShaderProgram PipelineCache::GetComputeProgram(const HW::ComputeShaderInfo& regs, - const HW::ShaderRegisters& sh, - ShaderComputeInputInfo& input_info) { - input_info.host_subgroup_size = m_graphics.SupportsComputeWave64() ? 64u : 32u; - const auto params = PrepareProgram(regs, sh, input_info); - input_info.lds_storage = input_info.lds_size_dwords * 4u > - m_graphics.GetPhysicalDeviceProperties().limits.maxComputeSharedMemorySize; - uint32_t push_data_cursor = 0; - return m_program_cache->Get(params, input_info, push_data_cursor); -} - -bool PipelineStaticParameters::operator==(const PipelineStaticParameters& other) const noexcept { - return std::memcmp(this, &other, sizeof(*this)) == 0; -} - -PipelineCache::Pipeline& PipelineCache::GetGraphicsPipeline( - std::span colors, const RenderDepthInfo& depth, - std::span vertex_info, CommandBuffer& command, - const ShaderPixelInputInfo* ps_input_info, vk::PrimitiveTopology topology, - bool primitive_restart_enable, const GraphicsPrograms& programs) { - const auto& vs_input_info = vertex_info.front(); - const auto& vertex_program = programs.vertex[0]; - const auto& pixel_program = programs.pixel; - KYTY_PROFILER_BLOCK("PipelineCache::CreatePipeline(Gfx)", profiler::colors::DeepOrangeA200); - - EXIT_IF(colors.size() > RENDER_COLOR_ATTACHMENTS_MAX); - EXIT_IF(!vertex_program); - const bool ps_active = ps_input_info != nullptr; - EXIT_IF(ps_active && !pixel_program); - const auto color_count = static_cast(colors.size()); - - auto& ctx = command.GetRegisters(); - - const HW::ModeControl& mc = ctx.GetModeControl(); - - const auto vs_id = vertex_program.id; - const auto ps_id = ps_active ? pixel_program.id : 0; - - GraphicsPipelineKey key {}; - for (uint32_t i = 0; i < programs.vertex.size(); i++) { - key.vertex_shader_ids[i] = programs.vertex[i].id; - } - key.ps_shader_id = ps_id; - auto& static_params = key.static_params; - auto& rendering = key.rendering; - rendering.color_count = 0; - uint32_t attachment_samples = 0; - for (uint32_t i = 0; i < color_count; i++) { - const auto slot = colors[i].target_slot; - EXIT_IF(slot >= RENDER_COLOR_ATTACHMENTS_MAX); - rendering.color_count = std::max(rendering.color_count, slot + 1); - EXIT_IF(!colors[i].image_id || colors[i].desc.view_info.format == vk::Format::eUndefined); - static_params.color_mask[slot] = colors[i].export_mapping.ApplyMask( - render_target_mask_slot(ctx.GetRenderTargetMask(), colors[i].target_slot)); - if (colors[i].desc.info.guest_format == Prospero::BufferFormat::k11_11_10UNorm) { - static_params.color_mask[slot] = 1u; - } - rendering.color_formats[slot] = colors[i].desc.view_info.format; - if (attachment_samples == 0) { - attachment_samples = colors[i].desc.info.samples; - } else if (attachment_samples != colors[i].desc.info.samples) { - EXIT("mixed color attachment sample counts are unsupported: %u and %u\n", - attachment_samples, colors[i].desc.info.samples); - } - const auto& rt = ctx.GetRenderTarget(colors[i].target_slot); - const auto& bc = ctx.GetBlendControl(colors[i].target_slot); - auto alpha_source = ShaderAlphaBlendSource::None; - if (slot == 0 && ps_input_info != nullptr) { - alpha_source = ps_input_info->alpha_blend_source; - } - static_params.blend_enable[slot] = bc.enable && !rt.info.blend_bypass; - if (static_params.blend_enable[slot] && alpha_source == ShaderAlphaBlendSource::None && - ClassifyBlendMapping(bc, colors[i].export_mapping) != BlendMappingSupport::Direct) { - static_params.blend_enable[slot] = false; - static std::atomic_bool warned = false; - if (!warned.exchange(true, std::memory_order_relaxed)) { - Log::WriteToConsoleAndLog(fmt::format( - "Warning: blending disabled for unsupported color mapping " - "(slot={} mapping=0x{:02x} color={}/{} alpha={}/{} separate={}).\n", - slot, colors[i].export_mapping.packed, bc.color_srcblend, bc.color_destblend, - bc.alpha_srcblend, bc.alpha_destblend, bc.separate_alpha_blend ? 1 : 0)); - } - } - if (static_params.blend_enable[slot]) { - auto blend = bc; - switch (alpha_source) { - case ShaderAlphaBlendSource::SourceAlpha: - blend.color_srcblend = RemapSourceAlphaFactor(blend.color_srcblend); - blend.color_destblend = RemapSourceAlphaFactor(blend.color_destblend); - blend.separate_alpha_blend = false; - break; - case ShaderAlphaBlendSource::SourceAlphaOne: - case ShaderAlphaBlendSource::SourceAlphaZero: - // The second source carries the mapped source factor; its alpha stays logical Sa. - blend.color_srcblend = static_cast(Prospero::BlendFactor::kSrc1Color); - blend.color_destblend = - static_cast(Prospero::BlendFactor::kOneMinusSrc1Alpha); - blend.separate_alpha_blend = false; - break; - case ShaderAlphaBlendSource::None: break; - } - static_params.color_srcblend[slot] = blend.color_srcblend; - static_params.color_comb_fcn[slot] = blend.color_comb_fcn; - static_params.color_destblend[slot] = blend.color_destblend; - static_params.separate_alpha_blend[slot] = blend.separate_alpha_blend; - if (blend.separate_alpha_blend) { - static_params.alpha_srcblend[slot] = blend.alpha_srcblend; - static_params.alpha_comb_fcn[slot] = blend.alpha_comb_fcn; - static_params.alpha_destblend[slot] = blend.alpha_destblend; - } - } - } - const bool with_depth = - depth.desc.view_info.format != vk::Format::eUndefined && static_cast(depth.image_id); - if (with_depth) { - const auto aspects = ImageViewOps::DepthAspectMask(depth.desc.view_info.format); - rendering.depth_format = aspects & vk::ImageAspectFlagBits::eDepth - ? depth.desc.view_info.format - : vk::Format::eUndefined; - rendering.stencil_format = aspects & vk::ImageAspectFlagBits::eStencil - ? depth.desc.view_info.format - : vk::Format::eUndefined; - if (attachment_samples == 0) { - attachment_samples = depth.desc.info.samples; - } else if (attachment_samples != depth.desc.info.samples) { - EXIT("mixed color/depth sample counts are unsupported: %u and %u\n", attachment_samples, - depth.desc.info.samples); - } - } - if (color_count == 0 && !with_depth) { - attachment_samples = render_sample_count(ctx.GetAaConfig().msaa_num_samples); - EXIT_IF(!static_cast( - m_graphics.GetPhysicalDeviceProperties().limits.framebufferNoAttachmentsSampleCounts & - vulkan_sample_count(attachment_samples))); - } - EXIT_IF(attachment_samples == 0 || - vulkan_sample_count(attachment_samples) == vk::SampleCountFlagBits {}); - - if (ps_active && depth.depth_test_enable && ps_input_info->ps_execute_on_noop) { - static std::atomic log_count {0}; - if (log_count.fetch_add(1, std::memory_order_relaxed) < 16) { - LOGF("Pipeline: temporary: accepting EXEC_ON_NOOP with depth test enabled\n"); - } - } - - const auto& clip_control = ctx.GetClipControl(); - static_params.negative_one_to_one = !clip_control.dx_clip_space; - static_params.depth_clip_enable = clip_control.IsZClipEnabled(); - static_params.topology = topology; - static_params.primitive_restart_enable = primitive_restart_enable; - static_params.samples = attachment_samples; - static_params.sample_shading_enable = - ps_active && attachment_samples > 1 && ps_input_info->ps_sample_shading; - if (static_params.sample_shading_enable && !m_graphics.sample_rate_shading_enabled) { - EXIT("Pipeline: sample-rate shading is required but unsupported by the host\n"); - } - const bool rect_list = Prospero::IsRectList(command.GetUserConfig().GetPrimType()); - static_params.cull_back = !rect_list && mc.cull_back; - static_params.cull_front = !rect_list && mc.cull_front; - static_params.face = mc.face; - static_params.provoking_vtx_last = mc.provoking_vtx_last; - static_params.polygon_mode = - ResolvePolygonMode(mc, static_params.cull_front, static_params.cull_back); - - if (vs_input_info.stage.program->stage != ShaderType::Mesh) { - EXIT_IF(vs_input_info.buffers_num < 0 || - vs_input_info.buffers_num > ShaderVertexInputInfo::RES_MAX || - vs_input_info.resources_num < 0 || - vs_input_info.resources_num > ShaderVertexInputInfo::RES_MAX); - key.vertex_input.binding_count = static_cast(vs_input_info.buffers_num); - key.vertex_input.attribute_count = static_cast(vs_input_info.resources_num); - for (int binding = 0; binding < vs_input_info.buffers_num; binding++) { - const auto& buffer = vs_input_info.buffers[binding]; - key.vertex_input.bindings[binding] = {.stride = buffer.stride, - .instance = buffer.fetch_index != 0}; - } - for (int attribute = 0; attribute < vs_input_info.resources_num; attribute++) { - const auto binding = vs_input_info.resources_dst[attribute].buffer_index; - EXIT_IF(binding < 0 || binding >= vs_input_info.buffers_num); - key.vertex_input.attributes[attribute] = { - .offset = static_cast(vs_input_info.resources[attribute].Base48() - - vs_input_info.buffers[binding].addr), - .binding = static_cast(binding), - }; - } - } - - if (auto iter = m_graphics_pipelines.find(key); iter != m_graphics_pipelines.end()) { - return *iter->second; - } - - if (graphics_debug_dump_enabled()) { - ShaderDbgDumpInputInfo(vs_input_info); - if (ps_active) { - ShaderDbgDumpInputInfo(*ps_input_info); - } - LOGF("PipelineTrace: shader modules VS=%" PRIu64 " module=%p PS=%" PRIu64 " module=%p\n", - vs_id, static_cast(vertex_program.module), ps_id, - static_cast(pixel_program.module)); - } - - auto cached = std::make_unique(); - LogPipelineTrace("CreatePipelineInternal begin", vs_id, ps_id); - CreatePipelineInternal(m_graphics, *cached, rendering, key.vertex_input, vertex_info, - ps_input_info, programs, static_params, m_driver_cache); - LogPipelineTrace("CreatePipelineInternal done", vs_id, ps_id); - - EXIT_NOT_IMPLEMENTED(cached->pipeline == nullptr); - EXIT_NOT_IMPLEMENTED(cached->pipeline_layout == nullptr); - - auto [iter, inserted] = m_graphics_pipelines.emplace(std::move(key), std::move(cached)); - EXIT_IF(!inserted); - CheckpointDriverCache(); - - return *iter->second; -} - -PipelineCache::Pipeline& -PipelineCache::GetComputePipeline(const ShaderComputeInputInfo& input_info, - const ShaderProgram& compute_program) { - KYTY_PROFILER_BLOCK("PipelineCache::CreatePipeline(Compute)", profiler::colors::RedA100); - - EXIT_IF(!compute_program); - - if (auto iter = m_compute_pipelines.find(compute_program.id); - iter != m_compute_pipelines.end()) { - return *iter->second; - } - - if (graphics_debug_dump_enabled()) { - ShaderDbgDumpInputInfo(input_info); - } - - auto cached = std::make_unique(); - CreatePipelineInternal(m_graphics, *cached, input_info, compute_program.module, m_driver_cache); - - EXIT_NOT_IMPLEMENTED(cached->pipeline == nullptr); - EXIT_NOT_IMPLEMENTED(cached->pipeline_layout == nullptr); - - auto [iter, inserted] = m_compute_pipelines.emplace(compute_program.id, std::move(cached)); - EXIT_IF(!inserted); - CheckpointDriverCache(); - - return *iter->second; -} -} // namespace Libs::Graphics +#include "graphics/host_gpu/renderer/pipeline/pipelineCache.h" + +#include "common/assert.h" +#include "common/emulatorConfig.h" +#include "common/file.h" +#include "common/logging/log.h" +#include "common/profiler.h" +#include "common/threads.h" +#include "graphics/guest_gpu/gpu_format.h" +#include "graphics/guest_gpu/hardwareContext.h" +#include "graphics/host_gpu/renderer/colorRenderTarget.h" +#include "graphics/host_gpu/renderer/debug.h" +#include "graphics/host_gpu/renderer/depthRenderTarget.h" +#include "graphics/host_gpu/renderer/image/imageView.h" +#include "graphics/host_gpu/renderer/pipeline/blendMapping.h" +#include "graphics/host_gpu/renderer/render.h" +#include "graphics/host_gpu/renderer/renderContext.h" +#include "graphics/shader/recompiler/ShaderRecompiler.h" +#include "graphics/shader/shaderCompiler.h" +#include "graphics/presentation/performanceHud.h" +#include "kernel/memory.h" +#include "loader/systemContent.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Libs::Graphics { + +namespace { + +constexpr auto DriverCacheSaveInterval = std::chrono::minutes {5}; + +uint8_t RemapSourceAlphaFactor(uint8_t factor) { + switch (static_cast(factor)) { + case Prospero::BlendFactor::kSrcAlpha: + return static_cast(Prospero::BlendFactor::kSrc1Alpha); + case Prospero::BlendFactor::kOneMinusSrcAlpha: + return static_cast(Prospero::BlendFactor::kOneMinusSrc1Alpha); + default: return factor; + } +} + +vk::PolygonMode ResolvePolygonMode(const HW::ModeControl& mode, bool cull_front, bool cull_back) { + // CxPrimitiveSetup::PolygonMode disables both per-face modes when it is zero. + if (mode.poly_mode == 0) { + return vk::PolygonMode::eFill; + } + EXIT_NOT_IMPLEMENTED(mode.poly_mode != 1); + if (cull_front && cull_back) { + return vk::PolygonMode::eFill; + } + if (!cull_front && !cull_back && mode.polymode_front_ptype != mode.polymode_back_ptype) { + EXIT("Pipeline: different polygon modes for two visible faces are unsupported\n"); + } + // Vulkan has one polygon mode. A culled face does not constrain that mode. + const auto polygon_mode = cull_front ? mode.polymode_back_ptype : mode.polymode_front_ptype; + switch (polygon_mode) { + case 0: return vk::PolygonMode::ePoint; + case 1: return vk::PolygonMode::eLine; + case 2: return vk::PolygonMode::eFill; + default: EXIT("Pipeline: invalid polygon mode %u\n", polygon_mode); + } +} + +std::string DriverCacheSignature(const vk::PhysicalDeviceProperties& properties) { + constexpr char hex[] = "0123456789abcdef"; + std::string uuid(VK_UUID_SIZE * 2, '0'); + for (size_t i = 0; i < VK_UUID_SIZE; i++) { + uuid[i * 2] = hex[properties.pipelineCacheUUID[i] >> 4u]; + uuid[i * 2 + 1] = hex[properties.pipelineCacheUUID[i] & 0xfu]; + } + // Driver cache entries already distinguish shader code and pipeline state across builds. + return fmt::format("KytyPC2:{:08x}:{:08x}:{:08x}:{}\n", + properties.vendorID, properties.deviceID, properties.driverVersion, uuid); +} + +std::string PipelineCacheTitleId() { + std::string title_id; + if ((!Loader::SystemContentParamSfoGetString("TITLE_ID", &title_id) || title_id.empty()) && + (!Loader::SystemContentParamSfoGetString("CONTENT_ID", &title_id) || title_id.empty())) { + return {}; + } + if (!std::ranges::all_of(title_id, [](unsigned char c) { + return std::isalnum(c) != 0 || c == '-' || c == '_'; + })) { + return {}; + } + return title_id; +} + +template +void PipelineCacheLog(fmt::format_string format, Args&&... args) { + auto message = fmt::format(format, std::forward(args)...); + message += '\n'; + Log::WriteToConsoleAndLog(message); +} + +bool ReadShaderGuestMemory(void*, uint64_t address, std::span values) { + // Scalar and unformatted buffer dependencies use the same backing as native raw loads. + // Image synchronization belongs to formatted buffer bindings, not these reads. + return !values.empty() && + Libs::LibKernel::Memory::TryReadBufferBacking(address, values.data(), values.size_bytes()); +} + +void DumpShaderSpirv(const char* stage_name, uint64_t shader_hash, + const std::vector& spirv) { + if (!Config::GraphicsDebugDumpEnabled()) { + return; + } + static std::atomic_int id = 0; + const auto path = Config::GetShaderLogFolder() / fmt::format("{:04d}_new_shader_{}_{:016x}.spv", + id++, stage_name, shader_hash); + Common::File::CreateDirectories(path.parent_path()); + Common::File file(path); + if (file.IsInvalid()) { + const auto path_text = Common::PathToString(path); + LOGF_COLOR(Log::Color::BrightRed, "Can't create file: %s\n", path_text.c_str()); + return; + } + file.Write(spirv.data(), spirv.size() * sizeof(uint32_t)); +} + +void DumpShaderOriginal(const char* stage_name, uint64_t shader_hash, + std::span code) { + if (!Config::GraphicsDebugDumpEnabled()) { + return; + } + EXIT_IF(code.empty()); + static std::atomic_int id = 0; + const auto path = Config::GetShaderLogFolder() / "original" / + fmt::format("{:04d}_new_shader_{}_{:016x}.bin", id++, stage_name, shader_hash); + Common::File::CreateDirectories(path.parent_path()); + Common::File file(path); + if (file.IsInvalid()) { + const auto path_text = Common::PathToString(path); + LOGF_COLOR(Log::Color::BrightRed, "Can't create file: %s\n", path_text.c_str()); + return; + } + file.Write(code.data(), code.size_bytes()); +} + +bool ValidateShaderSpirv(const char* label, uint64_t shader_hash, + const std::vector& spirv, bool maintenance8_enabled) { + if (!Config::ShaderValidationEnabled()) { + return true; + } + spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_3); + std::string messages; + tools.SetMessageConsumer([&messages](spv_message_level_t, const char*, + const spv_position_t& position, const char* message) { + messages += fmt::format("{}: {} ({}) {}\n", static_cast(position.line), + static_cast(position.column), static_cast(position.index), + message); + }); + spvtools::ValidatorOptions validator_options; + validator_options.SetAllowOffsetTextureOperand(maintenance8_enabled); + if (tools.Validate(spirv.data(), spirv.size(), validator_options)) { + return true; + } + spvtools::SpirvTools disassembler(SPV_ENV_VULKAN_1_2); + std::string text; + disassembler.Disassemble(spirv, &text, + static_cast(SPV_BINARY_TO_TEXT_OPTION_NO_HEADER) | + static_cast(SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES) | + static_cast(SPV_BINARY_TO_TEXT_OPTION_COMMENT) | + static_cast(SPV_BINARY_TO_TEXT_OPTION_INDENT) | + static_cast(SPV_BINARY_TO_TEXT_OPTION_COLOR)); + LOGF_COLOR(Log::Color::BrightRed, "%s SPIR-V validation failed hash=0x%016" PRIx64 ":\n%s", + label, shader_hash, messages.c_str()); + LOGF("%s\n", text.c_str()); + return false; +} + +} // namespace + +std::size_t PipelineCache::GraphicsPipelineKeyHash::operator()(const GraphicsPipelineKey& key) const { + std::size_t hash = 0; + PipelineKeyHash::Mix(hash, key.rendering.color_count); + for (uint32_t i = 0; i < key.rendering.color_count; i++) { + PipelineKeyHash::Mix(hash, static_cast(key.rendering.color_formats[i])); + } + PipelineKeyHash::Mix(hash, static_cast(key.rendering.depth_format)); + PipelineKeyHash::Mix(hash, static_cast(key.rendering.stencil_format)); + for (const auto id: key.vertex_shader_ids) { + PipelineKeyHash::Mix(hash, id); + } + PipelineKeyHash::Mix(hash, key.ps_shader_id); + PipelineKeyHash::Mix(hash, key.vertex_input.binding_count); + for (uint32_t i = 0; i < key.vertex_input.binding_count; i++) { + PipelineKeyHash::Mix(hash, key.vertex_input.bindings[i].stride); + PipelineKeyHash::Mix(hash, key.vertex_input.bindings[i].instance); + } + PipelineKeyHash::Mix(hash, key.vertex_input.attribute_count); + for (uint32_t i = 0; i < key.vertex_input.attribute_count; i++) { + PipelineKeyHash::Mix(hash, key.vertex_input.attributes[i].offset); + PipelineKeyHash::Mix(hash, key.vertex_input.attributes[i].binding); + } + PipelineKeyHash::Mix(hash, XXH3_64bits(&key.static_params, sizeof(key.static_params))); + return hash; +} + +struct PipelineCache::ProgramCache { + struct ProgramKey { + ShaderType stage = ShaderType::Unknown; + uint64_t hash = 0; + uint32_t user_data_count = 0; + uint32_t code_size = 0; + std::vector static_state; + + bool operator==(const ProgramKey&) const = default; + }; + + struct Permutation { + std::vector function_code; + ShaderRecompiler::IR::ResourceSpecialization specialization; + ShaderRecompiler::IR::CompiledShaderInfo program; + ShaderProgram handle; + }; + + struct SourceEntry { + SourceEntry(ShaderRecompiler::IR::ResourcePlan plan, + std::unique_ptr call_source) + : call_source(std::move(call_source)), resource_plan(std::move(plan)) { + permutations.reserve(8); + } + + std::span FunctionCode() const { + return call_source + ? std::span(call_source->linked->code).subspan(call_source->code.size()) + : std::span{}; + } + + bool RefreshCallSource(const ShaderRecompiler::IR::SrtRuntime& runtime) { + const auto revision = call_source->revision; + ShaderRecompiler::RefreshShaderSource(*call_source, runtime); + resource_plan.source_reads = call_source->reads; + return revision != call_source->revision; + } + + template + Permutation* FindPermutation(const ShaderRecompiler::IR::SrtRuntime& runtime, + uint32_t push_data_cursor) { + EXIT_IF(!ShaderRecompiler::IR::MaterializeResources( + resource_plan, runtime, resources, specialization)); + for (auto& candidate: permutations) { + const auto& layout = candidate.program.bindings; + if (layout.push_data_start_dword != ShaderRecompiler::IR::PushData::StartFor( + push_data_cursor, layout.ShaderDataDwords()) || + candidate.specialization != specialization) { + continue; + } + if constexpr (HasCalls) { + if (!std::ranges::equal(candidate.function_code, FunctionCode())) continue; + } + return &candidate; + } + return nullptr; + } + + std::unique_ptr call_source; + ShaderRecompiler::IR::ResourcePlan resource_plan; + ShaderRecompiler::IR::ResourceSnapshot resources; + ShaderRecompiler::IR::ResourceSpecialization specialization; + std::vector permutations; + }; + + struct ProgramKeyHash { + std::size_t operator()(const ProgramKey& key) const { + std::size_t hash = static_cast(key.stage); + PipelineKeyHash::Mix(hash, static_cast(key.hash)); + if constexpr (sizeof(std::size_t) < sizeof(uint64_t)) { + PipelineKeyHash::Mix(hash, static_cast(key.hash >> 32u)); + } + PipelineKeyHash::Mix(hash, key.user_data_count); + PipelineKeyHash::Mix(hash, key.code_size); + PipelineKeyHash::Mix(hash, key.static_state.size()); + // Bucket same-shape static variants by source. ProgramKey equality performs the one + // exact state comparison needed on a stable hit without hashing the full state first. + return hash; + } + }; + + static constexpr std::size_t MaxStaticKeyWords = 32 + ShaderVertexInputInfo::RES_MAX * 6; + + Permutation CompilePermutation(const char* stage_name, + const ShaderRecompiler::CompileOptions& options, + ShaderRecompiler::TranslateResult translated, + ShaderRecompiler::IR::ResourceSpecialization specialization, + uint32_t push_data_start_dword, + std::span function_code) { + auto result = ShaderRecompiler::CompileProgram(std::move(translated), options, + specialization, push_data_start_dword); + if (!ValidateShaderSpirv(options.dump_label, options.shader_hash, result.spirv, + options.maintenance8_enabled)) { + DumpShaderSpirv(stage_name, options.shader_hash, result.spirv); + EXIT("%s failed hash=0x%016" PRIx64 ": SPIR-V validation failed\n", options.dump_label, + options.shader_hash); + } + DumpShaderSpirv(stage_name, options.shader_hash, result.spirv); + + const auto module = CompileSPV(result.spirv, graphics.device); + EXIT_IF(module == nullptr); + if (options.dump_ir) { + LOGF("%s SPIR-V words=%" PRIu64 " wave_size=%u\n", options.dump_label, + static_cast(result.spirv.size()), options.wave_size); + } + return { + .function_code = {function_code.begin(), function_code.end()}, + .specialization = std::move(specialization), + .program = std::move(result.program).TakeCompiledInfo(), + .handle = {.id = ++next_shader_id, .module = module}, + }; + } + + template + ShaderProgram Get(const ShaderParams& params, InputInfo& input_info, + uint32_t& push_data_cursor) { + ShaderType stage; + if constexpr (std::is_same_v) { + stage = input_info.logical_stage; + } else if constexpr (std::is_same_v) { + stage = ShaderType::Pixel; + } else { + static_assert(std::is_same_v); + stage = ShaderType::Compute; + } + + const auto user_data = std::span(params.user_data).first(params.user_data_count); + lookup_key.stage = stage; + lookup_key.hash = params.hash; + lookup_key.user_data_count = params.user_data_count; + lookup_key.code_size = static_cast(params.code.size()); + BuildStageStaticKey(input_info, lookup_key.static_state); + auto entry = programs.find(lookup_key); + ShaderRecompiler::IR::SrtRuntime runtime { + .user_data = user_data, + .shader_base = params.Base(), + .read_specialization_memory = ReadShaderGuestMemory, + }; + if constexpr (std::is_same_v) { + runtime.workgroup_counts = input_info.workgroup_counts; + runtime.indirect_args_address = input_info.indirect_args_address; + } + bool source_changed = false; + if (entry != programs.end()) { + auto& cached = entry->second; + Permutation* permutation = nullptr; + if (cached.call_source) { + source_changed = cached.RefreshCallSource(runtime); + if (!source_changed) permutation = cached.FindPermutation(runtime, push_data_cursor); + } else { + permutation = cached.FindPermutation(runtime, push_data_cursor); + } + if (permutation != nullptr) { + input_info.stage = {.program = &permutation->program, .resources = &entry->second.resources}; + permutation->program.bindings.AdvancePushData(push_data_cursor); + return permutation->handle; + } + } + + ShaderStageInputInfo stage_input {}; + if constexpr (std::is_same_v) { + stage_input.vertex = &input_info; + } else if constexpr (std::is_same_v) { + stage_input.pixel = &input_info; + } else { + stage_input.compute = &input_info; + } + const char* label = nullptr; + const char* stage_name = nullptr; + switch (stage) { + case ShaderType::Vertex: label = "ShaderRecompiler VS"; stage_name = "vs"; break; + case ShaderType::Mesh: label = "ShaderRecompiler MS"; stage_name = "ms"; break; + case ShaderType::Local: label = "ShaderRecompiler LS"; stage_name = "ls"; break; + case ShaderType::TessellationControl: label = "ShaderRecompiler HS"; stage_name = "hs"; break; + case ShaderType::TessellationEvaluation: label = "ShaderRecompiler DS"; stage_name = "ds"; break; + case ShaderType::Pixel: label = "ShaderRecompiler PS"; stage_name = "ps"; break; + case ShaderType::Compute: label = "ShaderRecompiler CS"; stage_name = "cs"; break; + default: EXIT("invalid pipeline shader stage\n"); + } + ShaderRecompiler::CompileOptions options; + options.stage = stage; + options.maintenance8_enabled = graphics.maintenance8_enabled; + options.shader_hash = params.hash; + options.user_data = user_data; + options.back_code = params.back_code; + options.dump_ir = Config::GetShaderLogDirection() != Config::LogDirection::Silent; + options.early_dump = options.dump_ir; + options.emit_debug_info = Config::GraphicsDebugDumpEnabled(); + options.dump_label = label; + options.input_info = stage_input; + + if constexpr (std::is_same_v) { + options.user_data_base = 8; + options.wave_size = input_info.wave_size; + if (stage == ShaderType::Mesh || stage == ShaderType::TessellationControl) { + options.user_data_base = 0; + options.wave_size = stage == ShaderType::Mesh ? input_info.mesh.wave_size : 64u; + } + } else { + options.wave_size = input_info.wave_size; + } + DumpShaderOriginal(stage_name, options.shader_hash, params.code); + ShaderRecompiler::ShaderSource source; + if (entry == programs.end()) source = ShaderRecompiler::PrepareShaderSource(params.code, options); + auto* current = entry == programs.end() ? &source : entry->second.call_source.get(); + ShaderRecompiler::TranslateResult translated; + if (current != nullptr) { + if (current->call) { + if (entry == programs.end()) ShaderRecompiler::RefreshShaderSource(*current, runtime); + translated = ShaderRecompiler::TranslateProgram(current->linked->decoded, options); + translated.program.source_reads = current->reads; + } else { + translated = ShaderRecompiler::TranslateProgram(current->decoded, options); + } + } else { + translated = ShaderRecompiler::TranslateProgram(params.code, options); + } + if (entry == programs.end()) { + auto retained = source.call ? std::make_unique(std::move(source)) : nullptr; + entry = programs.try_emplace(lookup_key, + ShaderRecompiler::IR::ExtractResourcePlan(translated.program), std::move(retained)).first; + EXIT_IF(!ShaderRecompiler::IR::MaterializeResources( + entry->second.resource_plan, runtime, entry->second.resources, + entry->second.specialization)); + } else if (source_changed) { + entry->second.resource_plan = ShaderRecompiler::IR::ExtractResourcePlan(translated.program); + if (const auto* permutation = entry->second.FindPermutation(runtime, push_data_cursor)) { + input_info.stage = {.program = &permutation->program, .resources = &entry->second.resources}; + permutation->program.bindings.AdvancePushData(push_data_cursor); + return permutation->handle; + } + } + entry->second.permutations.push_back(CompilePermutation( + stage_name, options, std::move(translated), entry->second.specialization, push_data_cursor, + entry->second.FunctionCode())); + g_shader_permutations.fetch_add(1, std::memory_order_relaxed); + const auto& permutation = entry->second.permutations.back(); + input_info.stage = {.program = &permutation.program, .resources = &entry->second.resources}; + permutation.program.bindings.AdvancePushData(push_data_cursor); + + std::array(ShaderType::TessellationEvaluation) + 1> counts {}; + for (const auto& [key, source]: programs) { + counts[static_cast(key.stage)] += source.permutations.size(); + } + // Guest geometry shaders are compiled through the host mesh stage. + std::printf("Shaders: VS %zu | PS %zu | CS %zu | GS %zu | LS %zu | HS %zu | TES %zu\n", + counts[static_cast(ShaderType::Vertex)], + counts[static_cast(ShaderType::Pixel)], + counts[static_cast(ShaderType::Compute)], + counts[static_cast(ShaderType::Mesh)], + counts[static_cast(ShaderType::Local)], + counts[static_cast(ShaderType::TessellationControl)], + counts[static_cast(ShaderType::TessellationEvaluation)]); + return permutation.handle; + } + + explicit ProgramCache(GraphicContext& graphics): graphics(graphics) { + lookup_key.static_state.reserve(MaxStaticKeyWords); + } + ~ProgramCache() { + for (const auto& [key, entry]: programs) { + (void)key; + for (const auto& permutation: entry.permutations) { + graphics.device.destroyShaderModule(permutation.handle.module, nullptr); + } + } + } + + std::unordered_map programs; + ProgramKey lookup_key; + GraphicContext& graphics; + uint64_t next_shader_id = 0; +}; + +PipelineCache::PipelineCache(GraphicContext& graphics) + : m_graphics(graphics), m_program_cache(std::make_unique(graphics)), + m_next_driver_cache_save(std::chrono::steady_clock::now() + DriverCacheSaveInterval) { + EXIT_NOT_IMPLEMENTED(!Common::Thread::IsMainThread()); + InitializeDriverCache(); +} + +PipelineCache::~PipelineCache() { + Save(); + auto destroy = [this](const auto& pipelines) { + for (const auto& [key, pipeline]: pipelines) { + (void)key; + m_graphics.device.destroyPipeline(pipeline->pipeline, nullptr); + m_graphics.device.destroyPipelineLayout(pipeline->pipeline_layout, nullptr); + m_graphics.device.destroyDescriptorSetLayout(pipeline->descriptor_set_layout, nullptr); + } + }; + destroy(m_graphics_pipelines); + destroy(m_compute_pipelines); + if (m_driver_cache != nullptr) { + m_graphics.device.destroyPipelineCache(m_driver_cache, nullptr); + } +} + +void PipelineCache::InitializeDriverCache() { + const auto title_id = PipelineCacheTitleId(); + if (title_id.empty()) { + return; + } + if (KYTY_BUILD != KYTY_BUILD_RELEASE) { + PipelineCacheLog("Vulkan pipeline cache: disabled (non-Release build)"); + return; + } + m_driver_cache_path = std::filesystem::path("_PipelineCache") / (title_id + ".bin"); + const auto path = Common::PathToString(m_driver_cache_path); + const bool cache_exists = Common::File::IsFileExisting(m_driver_cache_path); + if (cache_exists) { + PipelineCacheLog("Vulkan pipeline cache: loading {}", path); + } else { + PipelineCacheLog("Vulkan pipeline cache: initializing {}", path); + } + std::vector initial_data; + if (cache_exists) { + Common::File file(m_driver_cache_path, Common::File::Mode::Read); + const auto file_size = file.IsInvalid() ? 0 : file.Size(); + const auto signature = DriverCacheSignature(m_graphics.GetPhysicalDeviceProperties()); + if (file_size >= signature.size() + sizeof(uint64_t) && + file_size <= std::numeric_limits::max()) { + std::string cached_signature(signature.size(), '\0'); + uint64_t payload_hash = 0; + initial_data.resize(file_size - signature.size() - sizeof(payload_hash)); + uint32_t signature_read = 0; + uint32_t hash_read = 0; + uint32_t payload_read = 0; + file.Read(cached_signature.data(), static_cast(cached_signature.size()), + &signature_read); + file.Read(&payload_hash, sizeof(payload_hash), &hash_read); + file.Read(initial_data.data(), static_cast(initial_data.size()), + &payload_read); + file.Close(); + if (signature_read != cached_signature.size() || hash_read != sizeof(payload_hash) || + payload_read != initial_data.size() || cached_signature != signature || + XXH3_64bits(initial_data.data(), initial_data.size()) != payload_hash) { + initial_data.clear(); + PipelineCacheLog( + "Vulkan pipeline cache: invalidating {} (driver or data mismatch)", + path); + } + } else { + file.Close(); + PipelineCacheLog("Vulkan pipeline cache: invalidating {} (invalid file size)", path); + } + } + + vk::PipelineCacheCreateInfo create {}; + create.initialDataSize = initial_data.size(); + create.pInitialData = initial_data.empty() ? nullptr : initial_data.data(); + auto result = m_graphics.device.createPipelineCache(&create, nullptr, &m_driver_cache); + if (result != vk::Result::eSuccess && !initial_data.empty()) { + PipelineCacheLog("Vulkan pipeline cache: driver rejected {} ({}); starting empty", path, + vk::to_string(result)); + initial_data.clear(); + create.initialDataSize = 0; + create.pInitialData = nullptr; + result = m_graphics.device.createPipelineCache(&create, nullptr, &m_driver_cache); + } + if (result != vk::Result::eSuccess) { + PipelineCacheLog("Vulkan pipeline cache: disabled ({})", vk::to_string(result)); + m_driver_cache = nullptr; + return; + } + if (!initial_data.empty()) { + PipelineCacheLog("Vulkan pipeline cache: loaded {} bytes from {}", initial_data.size(), + path); + } else { + PipelineCacheLog("Vulkan pipeline cache: initialized empty"); + } +} + +void PipelineCache::CheckpointDriverCache() { + if (m_driver_cache == nullptr) { + return; + } + m_driver_cache_dirty = true; + if (std::chrono::steady_clock::now() >= m_next_driver_cache_save) { + Save(); + } +} + +void PipelineCache::Save() { + if (m_driver_cache == nullptr || !m_driver_cache_dirty) { + return; + } + m_next_driver_cache_save = std::chrono::steady_clock::now() + DriverCacheSaveInterval; + + size_t size = 0; + vk::Result result; + std::vector payload; + for (uint32_t attempt = 0; attempt < 3; attempt++) { + size = 0; + result = m_graphics.device.getPipelineCacheData(m_driver_cache, &size, nullptr); + if (result != vk::Result::eSuccess || size == 0 || + size > std::numeric_limits::max()) { + break; + } + payload.resize(size); + result = m_graphics.device.getPipelineCacheData(m_driver_cache, &size, payload.data()); + if (result != vk::Result::eIncomplete) { + break; + } + } + if (result != vk::Result::eSuccess || size == 0 || + size > std::numeric_limits::max()) { + PipelineCacheLog("Vulkan pipeline cache: save failed ({}, {} bytes)", + vk::to_string(result), size); + return; + } + payload.resize(size); + auto prefix = DriverCacheSignature(m_graphics.GetPhysicalDeviceProperties()); + const auto payload_hash = XXH3_64bits(payload.data(), payload.size()); + prefix.append(reinterpret_cast(&payload_hash), sizeof(payload_hash)); + if (!Common::File::CreateDirectories(m_driver_cache_path.parent_path())) { + PipelineCacheLog("Vulkan pipeline cache: failed to create cache directory"); + return; + } + auto temp_path = m_driver_cache_path; + temp_path += ".tmp"; + Common::File file; + uint32_t prefix_written = 0; + uint32_t payload_written = 0; + if (file.Create(temp_path)) { + file.Write(prefix.data(), static_cast(prefix.size()), &prefix_written); + file.Write(payload.data(), static_cast(payload.size()), &payload_written); + } + const bool flushed = !file.IsInvalid() && file.Flush(); + file.Close(); + const bool written = prefix_written == prefix.size() && payload_written == payload.size() && flushed; + std::error_code error; + if (written) { + std::filesystem::rename(temp_path, m_driver_cache_path, error); + } + if (!written || error) { + PipelineCacheLog("Vulkan pipeline cache: failed to write {}", + Common::PathToString(m_driver_cache_path)); + return; + } + PipelineCacheLog("Vulkan pipeline cache: saved {} bytes to {}", payload.size(), + Common::PathToString(m_driver_cache_path)); + m_driver_cache_dirty = false; +} + +PipelineCache::GraphicsPrograms PipelineCache::GetGraphicsPrograms( + const HW::VertexShaderInfo& vertex_regs, const HW::PixelShaderInfo& pixel_regs, + const HW::ShaderRegisters& sh, const HW::Context& context, const HW::UserConfig& user_config, + std::span target_export_mapping, bool pixel_active, + std::array& vertex_info, ShaderPixelInputInfo& pixel_info) { + const bool tess_active = user_config.GetPrimType() == Prospero::PrimitiveType::kPatch; + std::array vertex_params; + if (tess_active) { + vertex_params = PrepareTessellationPrograms(vertex_regs, context, vertex_info); + } else { + vertex_params[0] = PrepareProgram(vertex_regs, context, user_config, vertex_info[0]); + } + const bool mesh_active = vertex_info[0].logical_stage == ShaderType::Mesh; + const bool object_primitive_id = context.HasObjectPrimitiveIdOutput(); + if (object_primitive_id) { + // CxObjectIdMode: register source plus a 32-bit pipelined primitive-ID addition. + EXIT_NOT_IMPLEMENTED(sh.m_paClObjprimIdCntl != 2u || mesh_active || tess_active || + !pixel_active || (sh.m_vgtDrawPayloadCntl & 8u) == 0 || + user_config.GetPrimType() != Prospero::PrimitiveType::kTriList); + const auto& target = context.GetRenderTarget(7); + EXIT_NOT_IMPLEMENTED(Prospero::ResolveRenderTargetFormat(target.info.format, + target.info.channel_type) + .buffer_format != Prospero::BufferFormat::k32UInt); + } + if (mesh_active) { + EXIT_NOT_IMPLEMENTED(!m_graphics.mesh_shader_enabled); + auto& mesh = vertex_info[0].mesh; + mesh.host_subgroup_size = m_graphics.subgroup_size; + const auto& limits = m_graphics.mesh_shader_properties; + const auto logical_threads = + mesh.threads_num[0] * mesh.threads_num[1] * mesh.threads_num[2]; + const auto host_threads = ((logical_threads + mesh.wave_size - 1u) / mesh.wave_size) * + std::min(mesh.host_subgroup_size, mesh.wave_size); + if (host_threads > limits.maxMeshWorkGroupInvocations || + host_threads > limits.maxMeshWorkGroupSize[0] || + mesh.max_vertices > limits.maxMeshOutputVertices || + mesh.max_primitives > limits.maxMeshOutputPrimitives || + mesh.lds_size_dwords * sizeof(uint32_t) > limits.maxMeshSharedMemorySize) { + EXIT("mesh shader exceeds host limits: threads=%u vertices=%u primitives=%u LDS=%u\n", + host_threads, mesh.max_vertices, mesh.max_primitives, mesh.lds_size_dwords); + } + } + ShaderParams pixel_params; + if (pixel_active) { + pixel_params = PrepareProgram(pixel_regs, sh, target_export_mapping, pixel_info); + pixel_info.mesh_stage = mesh_active; + pixel_info.object_primitive_id = object_primitive_id; + for (uint32_t export_index = 0; export_index < 8u; export_index++) { + const auto slot = ShaderPixelExportTarget(pixel_info.target_shader_mask, export_index); + if (slot >= 8u || pixel_info.target_output_mode[export_index] == 0u) continue; + const auto& rt = context.GetRenderTarget(slot); + const auto target_mask = render_target_mask_slot(context.GetRenderTargetMask(), slot); + if (rt.base.addr == 0 || target_mask == 0u) continue; + const auto format = Prospero::ResolveRenderTargetFormat(rt.info.format, rt.info.channel_type); + if (format.buffer_format != Prospero::BufferFormat::k11_11_10UNorm) continue; + const auto mapping = pixel_info.target_export_mapping[export_index]; + const auto shader_mask = render_target_mask_slot(pixel_info.target_shader_mask, slot); + const bool blend = context.GetBlendControl(slot).enable && !rt.info.blend_bypass; + if (blend || (mapping.ApplyMask(target_mask) & 7u) != 7u || + (mapping.ApplyMask(shader_mask) & 7u) != 7u || + pixel_info.target_output_mode[export_index] != 9u) { + EXIT("unsupported packed UNorm render-target export: slot=%u export=%u mode=%u " + "target_mask=0x%x shader_mask=0x%x mapping=0x%02x blend=%u\n", + slot, export_index, pixel_info.target_output_mode[export_index], target_mask, + shader_mask, mapping.packed, static_cast(blend)); + } + pixel_info.target_packed_unorm_mask |= 1u << export_index; + pixel_info.target_round_mode |= static_cast(rt.info.round_mode) << export_index; + } + if (!mesh_active && !tess_active && Prospero::IsRectList(user_config.GetPrimType())) { + pixel_info.parameter_mode = ShaderPixelParameterMode::Rectangle; + } else if (context.GetModeControl().provoking_vtx_last) { + pixel_info.parameter_mode = ShaderPixelParameterMode::LastVertex; + } else { + pixel_info.parameter_mode = ShaderPixelParameterMode::FirstVertex; + } + const auto& blend = context.GetBlendControl(0); + pixel_info.dual_source_blending = + blend.enable && !context.GetRenderTarget(0).info.blend_bypass && + (BlendFactorIsDualSource(blend.color_srcblend) || + BlendFactorIsDualSource(blend.color_destblend) || + (blend.separate_alpha_blend && (BlendFactorIsDualSource(blend.alpha_srcblend) || + BlendFactorIsDualSource(blend.alpha_destblend)))); + if (pixel_info.dual_source_blending) { + // MRT1 supplies the second blend source for target 0. + pixel_info.target_output_mode[1] = pixel_info.target_output_mode[0]; + pixel_info.target_export_mapping[1] = pixel_info.target_export_mapping[0]; + } else if (blend.enable && !context.GetRenderTarget(0).info.blend_bypass && + pixel_info.target_output_mode[0] != 0 && pixel_info.target_output_mode[0] != 7 && + std::all_of(std::begin(pixel_info.target_output_mode) + 1, + std::end(pixel_info.target_output_mode), + [](uint8_t mode) { return mode == 0; })) { + switch (ClassifyBlendMapping(blend, pixel_info.target_export_mapping[0])) { + case BlendMappingSupport::SourceAlpha: + pixel_info.alpha_blend_source = ShaderAlphaBlendSource::SourceAlpha; + break; + case BlendMappingSupport::SourceAlphaOne: + pixel_info.alpha_blend_source = ShaderAlphaBlendSource::SourceAlphaOne; + break; + case BlendMappingSupport::SourceAlphaZero: + pixel_info.alpha_blend_source = ShaderAlphaBlendSource::SourceAlphaZero; + break; + default: break; + } + if (pixel_info.alpha_blend_source != ShaderAlphaBlendSource::None) { + pixel_info.dual_source_blending = true; + pixel_info.target_output_mode[1] = pixel_info.target_output_mode[0]; + pixel_info.target_export_mapping[1] = {}; + } + } + } + if (context.GetClipControl().clip_disable) { + const auto& viewport = context.GetScreenViewport().viewports[0]; + const auto& limits = m_graphics.GetPhysicalDeviceProperties().limits; + auto& clip = vertex_info[tess_active ? 2u : 0u].clip_space; + clip.scale[0] = viewport.xscale; + clip.scale[1] = viewport.yscale; + clip.offset[0] = viewport.xoffset; + clip.offset[1] = viewport.yoffset; + clip.half_extent[0] = + static_cast(std::min(limits.maxViewportDimensions[0], 16384u)) * 0.5f; + clip.half_extent[1] = + static_cast(std::min(limits.maxViewportDimensions[1], 16384u)) * 0.5f; + clip.enabled = true; + } + uint32_t push_data_cursor = ShaderRecompiler::IR::PushData::GraphicsDrawDwords( + mesh_active, object_primitive_id); + GraphicsPrograms result; + if (pixel_active) { + result.pixel = m_program_cache->Get(pixel_params, pixel_info, push_data_cursor); + } + if (mesh_active) { + auto& output_components = vertex_info[0].mesh.output_component_count; + output_components.fill(pixel_active ? 1u : 4u); + if (pixel_active && pixel_info.stage.program != nullptr) { + for (const auto& input: pixel_info.stage.program->info.inputs) { + if (input.kind != ShaderRecompiler::IR::StageInputKind::Parameter) { + continue; + } + const auto location = ShaderPixelParameterMappedLocation(pixel_info, input.location); + if (location < output_components.size()) { + const auto components = + static_cast(std::clamp(input.component_count, 1u, 4u)); + output_components[location] = std::max(output_components[location], components); + } + } + } + } + for (uint32_t i = 0; i < (tess_active ? 3u : 1u); i++) { + result.vertex[i] = m_program_cache->Get(vertex_params[i], vertex_info[i], push_data_cursor); + } + return result; +} + +ShaderProgram PipelineCache::GetComputeProgram(const HW::ComputeShaderInfo& regs, + const HW::ShaderRegisters& sh, + ShaderComputeInputInfo& input_info) { + input_info.host_subgroup_size = m_graphics.SupportsComputeWave64() ? 64u : 32u; + const auto params = PrepareProgram(regs, sh, input_info); + input_info.lds_storage = input_info.lds_size_dwords * 4u > + m_graphics.GetPhysicalDeviceProperties().limits.maxComputeSharedMemorySize; + uint32_t push_data_cursor = 0; + return m_program_cache->Get(params, input_info, push_data_cursor); +} + +bool PipelineStaticParameters::operator==(const PipelineStaticParameters& other) const noexcept { + return std::memcmp(this, &other, sizeof(*this)) == 0; +} + +PipelineCache::Pipeline& PipelineCache::GetGraphicsPipeline( + std::span colors, const RenderDepthInfo& depth, + std::span vertex_info, CommandBuffer& command, + const ShaderPixelInputInfo* ps_input_info, vk::PrimitiveTopology topology, + bool primitive_restart_enable, const GraphicsPrograms& programs) { + const auto& vs_input_info = vertex_info.front(); + const auto& vertex_program = programs.vertex[0]; + const auto& pixel_program = programs.pixel; + KYTY_PROFILER_BLOCK("PipelineCache::CreatePipeline(Gfx)", profiler::colors::DeepOrangeA200); + + EXIT_IF(colors.size() > RENDER_COLOR_ATTACHMENTS_MAX); + EXIT_IF(!vertex_program); + const bool ps_active = ps_input_info != nullptr; + EXIT_IF(ps_active && !pixel_program); + const auto color_count = static_cast(colors.size()); + + auto& ctx = command.GetRegisters(); + + const HW::ModeControl& mc = ctx.GetModeControl(); + + const auto vs_id = vertex_program.id; + const auto ps_id = ps_active ? pixel_program.id : 0; + + GraphicsPipelineKey key {}; + for (uint32_t i = 0; i < programs.vertex.size(); i++) { + key.vertex_shader_ids[i] = programs.vertex[i].id; + } + key.ps_shader_id = ps_id; + auto& static_params = key.static_params; + auto& rendering = key.rendering; + rendering.color_count = 0; + uint32_t attachment_samples = 0; + for (uint32_t i = 0; i < color_count; i++) { + const auto slot = colors[i].target_slot; + EXIT_IF(slot >= RENDER_COLOR_ATTACHMENTS_MAX); + rendering.color_count = std::max(rendering.color_count, slot + 1); + EXIT_IF(!colors[i].image_id || colors[i].desc.view_info.format == vk::Format::eUndefined); + static_params.color_mask[slot] = colors[i].export_mapping.ApplyMask( + render_target_mask_slot(ctx.GetRenderTargetMask(), colors[i].target_slot)); + if (colors[i].desc.info.guest_format == Prospero::BufferFormat::k11_11_10UNorm) { + static_params.color_mask[slot] = 1u; + } + rendering.color_formats[slot] = colors[i].desc.view_info.format; + if (attachment_samples == 0) { + attachment_samples = colors[i].desc.info.samples; + } else if (attachment_samples != colors[i].desc.info.samples) { + EXIT("mixed color attachment sample counts are unsupported: %u and %u\n", + attachment_samples, colors[i].desc.info.samples); + } + const auto& rt = ctx.GetRenderTarget(colors[i].target_slot); + const auto& bc = ctx.GetBlendControl(colors[i].target_slot); + auto alpha_source = ShaderAlphaBlendSource::None; + if (slot == 0 && ps_input_info != nullptr) { + alpha_source = ps_input_info->alpha_blend_source; + } + static_params.blend_enable[slot] = bc.enable && !rt.info.blend_bypass; + if (static_params.blend_enable[slot] && alpha_source == ShaderAlphaBlendSource::None && + ClassifyBlendMapping(bc, colors[i].export_mapping) != BlendMappingSupport::Direct) { + static_params.blend_enable[slot] = false; + static std::atomic_bool warned = false; + if (!warned.exchange(true, std::memory_order_relaxed)) { + Log::WriteToConsoleAndLog(fmt::format( + "Warning: blending disabled for unsupported color mapping " + "(slot={} mapping=0x{:02x} color={}/{} alpha={}/{} separate={}).\n", + slot, colors[i].export_mapping.packed, bc.color_srcblend, bc.color_destblend, + bc.alpha_srcblend, bc.alpha_destblend, bc.separate_alpha_blend ? 1 : 0)); + } + } + if (static_params.blend_enable[slot]) { + auto blend = bc; + switch (alpha_source) { + case ShaderAlphaBlendSource::SourceAlpha: + blend.color_srcblend = RemapSourceAlphaFactor(blend.color_srcblend); + blend.color_destblend = RemapSourceAlphaFactor(blend.color_destblend); + blend.separate_alpha_blend = false; + break; + case ShaderAlphaBlendSource::SourceAlphaOne: + case ShaderAlphaBlendSource::SourceAlphaZero: + // The second source carries the mapped source factor; its alpha stays logical Sa. + blend.color_srcblend = static_cast(Prospero::BlendFactor::kSrc1Color); + blend.color_destblend = + static_cast(Prospero::BlendFactor::kOneMinusSrc1Alpha); + blend.separate_alpha_blend = false; + break; + case ShaderAlphaBlendSource::None: break; + } + static_params.color_srcblend[slot] = blend.color_srcblend; + static_params.color_comb_fcn[slot] = blend.color_comb_fcn; + static_params.color_destblend[slot] = blend.color_destblend; + static_params.separate_alpha_blend[slot] = blend.separate_alpha_blend; + if (blend.separate_alpha_blend) { + static_params.alpha_srcblend[slot] = blend.alpha_srcblend; + static_params.alpha_comb_fcn[slot] = blend.alpha_comb_fcn; + static_params.alpha_destblend[slot] = blend.alpha_destblend; + } + } + } + const bool with_depth = + depth.desc.view_info.format != vk::Format::eUndefined && static_cast(depth.image_id); + if (with_depth) { + const auto aspects = ImageViewOps::DepthAspectMask(depth.desc.view_info.format); + rendering.depth_format = aspects & vk::ImageAspectFlagBits::eDepth + ? depth.desc.view_info.format + : vk::Format::eUndefined; + rendering.stencil_format = aspects & vk::ImageAspectFlagBits::eStencil + ? depth.desc.view_info.format + : vk::Format::eUndefined; + if (attachment_samples == 0) { + attachment_samples = depth.desc.info.samples; + } else if (attachment_samples != depth.desc.info.samples) { + EXIT("mixed color/depth sample counts are unsupported: %u and %u\n", attachment_samples, + depth.desc.info.samples); + } + } + if (color_count == 0 && !with_depth) { + attachment_samples = render_sample_count(ctx.GetAaConfig().msaa_num_samples); + EXIT_IF(!static_cast( + m_graphics.GetPhysicalDeviceProperties().limits.framebufferNoAttachmentsSampleCounts & + vulkan_sample_count(attachment_samples))); + } + EXIT_IF(attachment_samples == 0 || + vulkan_sample_count(attachment_samples) == vk::SampleCountFlagBits {}); + + if (ps_active && depth.depth_test_enable && ps_input_info->ps_execute_on_noop) { + static std::atomic log_count {0}; + if (log_count.fetch_add(1, std::memory_order_relaxed) < 16) { + LOGF("Pipeline: temporary: accepting EXEC_ON_NOOP with depth test enabled\n"); + } + } + + const auto& clip_control = ctx.GetClipControl(); + static_params.negative_one_to_one = !clip_control.dx_clip_space; + static_params.depth_clip_enable = clip_control.IsZClipEnabled(); + static_params.topology = topology; + static_params.primitive_restart_enable = primitive_restart_enable; + static_params.samples = attachment_samples; + static_params.sample_shading_enable = + ps_active && attachment_samples > 1 && ps_input_info->ps_sample_shading; + if (static_params.sample_shading_enable && !m_graphics.sample_rate_shading_enabled) { + EXIT("Pipeline: sample-rate shading is required but unsupported by the host\n"); + } + const bool rect_list = Prospero::IsRectList(command.GetUserConfig().GetPrimType()); + static_params.cull_back = !rect_list && mc.cull_back; + static_params.cull_front = !rect_list && mc.cull_front; + static_params.face = mc.face; + static_params.provoking_vtx_last = mc.provoking_vtx_last; + static_params.polygon_mode = + ResolvePolygonMode(mc, static_params.cull_front, static_params.cull_back); + + if (vs_input_info.stage.program->stage != ShaderType::Mesh) { + EXIT_IF(vs_input_info.buffers_num < 0 || + vs_input_info.buffers_num > ShaderVertexInputInfo::RES_MAX || + vs_input_info.resources_num < 0 || + vs_input_info.resources_num > ShaderVertexInputInfo::RES_MAX); + key.vertex_input.binding_count = static_cast(vs_input_info.buffers_num); + key.vertex_input.attribute_count = static_cast(vs_input_info.resources_num); + for (int binding = 0; binding < vs_input_info.buffers_num; binding++) { + const auto& buffer = vs_input_info.buffers[binding]; + key.vertex_input.bindings[binding] = {.stride = buffer.stride, + .instance = buffer.fetch_index != 0}; + } + for (int attribute = 0; attribute < vs_input_info.resources_num; attribute++) { + const auto binding = vs_input_info.resources_dst[attribute].buffer_index; + EXIT_IF(binding < 0 || binding >= vs_input_info.buffers_num); + key.vertex_input.attributes[attribute] = { + .offset = static_cast(vs_input_info.resources[attribute].Base48() - + vs_input_info.buffers[binding].addr), + .binding = static_cast(binding), + }; + } + } + + if (auto iter = m_graphics_pipelines.find(key); iter != m_graphics_pipelines.end()) { + return *iter->second; + } + + if (graphics_debug_dump_enabled()) { + ShaderDbgDumpInputInfo(vs_input_info); + if (ps_active) { + ShaderDbgDumpInputInfo(*ps_input_info); + } + LOGF("PipelineTrace: shader modules VS=%" PRIu64 " module=%p PS=%" PRIu64 " module=%p\n", + vs_id, static_cast(vertex_program.module), ps_id, + static_cast(pixel_program.module)); + } + + auto cached = std::make_unique(); + LogPipelineTrace("CreatePipelineInternal begin", vs_id, ps_id); + CreatePipelineInternal(m_graphics, *cached, rendering, key.vertex_input, vertex_info, + ps_input_info, programs, static_params, m_driver_cache); + LogPipelineTrace("CreatePipelineInternal done", vs_id, ps_id); + + EXIT_NOT_IMPLEMENTED(cached->pipeline == nullptr); + EXIT_NOT_IMPLEMENTED(cached->pipeline_layout == nullptr); + + auto [iter, inserted] = m_graphics_pipelines.emplace(std::move(key), std::move(cached)); + EXIT_IF(!inserted); + CheckpointDriverCache(); + + return *iter->second; +} + +PipelineCache::Pipeline& +PipelineCache::GetComputePipeline(const ShaderComputeInputInfo& input_info, + const ShaderProgram& compute_program) { + KYTY_PROFILER_BLOCK("PipelineCache::CreatePipeline(Compute)", profiler::colors::RedA100); + + EXIT_IF(!compute_program); + + if (auto iter = m_compute_pipelines.find(compute_program.id); + iter != m_compute_pipelines.end()) { + return *iter->second; + } + + if (graphics_debug_dump_enabled()) { + ShaderDbgDumpInputInfo(input_info); + } + + auto cached = std::make_unique(); + CreatePipelineInternal(m_graphics, *cached, input_info, compute_program.module, m_driver_cache); + + EXIT_NOT_IMPLEMENTED(cached->pipeline == nullptr); + EXIT_NOT_IMPLEMENTED(cached->pipeline_layout == nullptr); + + auto [iter, inserted] = m_compute_pipelines.emplace(compute_program.id, std::move(cached)); + EXIT_IF(!inserted); + CheckpointDriverCache(); + + return *iter->second; +} +} // namespace Libs::Graphics diff --git a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp index 567ea276..05d51a5b 100644 --- a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp +++ b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp @@ -1,953 +1,972 @@ -#include "graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h" - -#include "common/logging/log.h" - -#include -#include - -namespace Libs::Graphics::ShaderRecompiler::Spirv::Emitter { -namespace { - -bool UserDataDwordIndex(const EmitterState& state, IR::ScalarReg reg, uint32_t& dword_index) { - const auto register_index = IR::RegIndex(reg); - const auto& registers = state.program.info.user_data_registers; - const auto found = std::lower_bound(registers.begin(), registers.end(), register_index); - if (found == registers.end() || *found != register_index) { - return false; - } - dword_index = static_cast(found - registers.begin()); - return true; -} - -uint32_t EmitBuiltinU32(EmitterState& state, IR::StageInputKind kind, uint32_t component) { - if (kind == IR::StageInputKind::LocalInvocationIndex) { - return EmitLocalInvocationIndex(state); - } - if (state.lane_count == 2 && (kind == IR::StageInputKind::LocalInvocationId || - kind == IR::StageInputKind::GlobalInvocationId)) { - const auto* cs = ShaderWorkgroupInput(state.program.stage, state.input_info); - uint32_t divisor = 1; - for (uint32_t axis = 0; axis < component; axis++) { - divisor *= std::max(cs->threads_num[axis], 1u); - } - const auto size = std::max(cs->threads_num[component], 1u); - const auto divided = EmitBinaryU32(state, spv::OpUDiv, EmitLocalInvocationIndex(state), - ConstantU32(state, divisor)); - const auto local = EmitBinaryU32(state, spv::OpUMod, divided, ConstantU32(state, size)); - if (kind == IR::StageInputKind::LocalInvocationId) { - return local; - } - const auto group = EmitInputComponentU32(state, IR::StageInputKind::WorkgroupId, component); - return EmitAddU32(state, local, - EmitBinaryU32(state, spv::OpIMul, group, ConstantU32(state, size))); - } - const bool centroid = kind == IR::StageInputKind::BaryCoordSmoothCentroid; - const bool sample = kind == IR::StageInputKind::BaryCoordSmoothSample; - const auto variable = InputVariableForKind( - state, centroid || sample ? IR::StageInputKind::BaryCoordSmooth : kind); - if (variable == 0) { - return ConstantU32(state, 0); - } - if (kind == IR::StageInputKind::FrontFacing) { - const auto value = state.builder.AllocateId(); - const auto bits = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpLoad, TypeBool(state), value, variable); - // SPI_BARYC_CNTL.FRONT_FACE_ALL_BITS selects uint masks or float +/-1. - const bool all_bits = - state.input_info.pixel != nullptr && state.input_info.pixel->ps_front_face_all_bits; - const auto front = ConstantU32(state, all_bits ? 0xffffffffu : 0x3f800000u); - const auto back = ConstantU32(state, all_bits ? 0u : 0xbf800000u); - state.builder.AddFunction(spv::OpSelect, TypeU32(state), bits, value, front, back); - return bits; - } - if (kind == IR::StageInputKind::VertexIndex || kind == IR::StageInputKind::InstanceIndex || - kind == IR::StageInputKind::InvocationId || kind == IR::StageInputKind::PrimitiveId || - kind == IR::StageInputKind::Layer || kind == IR::StageInputKind::SampleId) { - const auto value = state.builder.AllocateId(); - const auto bits = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpLoad, TypeI32(state), value, variable); - state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, value); - return bits; - } - if (kind == IR::StageInputKind::FragCoord || kind == IR::StageInputKind::TessCoord) { - const auto pointer = state.builder.AllocateId(); - const auto value = state.builder.AllocateId(); - const auto bits = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpAccessChain, - TypePointer(state, spv::StorageClassInput, TypeF32(state)), - pointer, variable, ConstantU32(state, component)); - state.builder.AddFunction(spv::OpLoad, TypeF32(state), value, pointer); - state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, value); - return bits; - } - if (centroid || sample || kind == IR::StageInputKind::BaryCoordSmooth || - kind == IR::StageInputKind::BaryCoordNoPerspective) { - const auto value = state.builder.AllocateId(); - const auto bits = state.builder.AllocateId(); - if (centroid || sample) { - const auto coordinates = state.builder.AllocateId(); - state.builder.RequireCapability(spv::CapabilityInterpolationFunction); - if (sample) { - const auto sample_id = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpLoad, TypeI32(state), sample_id, - InputVariableForKind(state, IR::StageInputKind::SampleId)); - state.builder.AddFunction(spv::OpExtInst, TypeF32Vector(state, 3), coordinates, - GlslStd450(state), GLSLstd450InterpolateAtSample, - variable, sample_id); - } else { - state.builder.AddFunction(spv::OpExtInst, TypeF32Vector(state, 3), coordinates, - GlslStd450(state), GLSLstd450InterpolateAtCentroid, variable); - } - state.builder.AddFunction(spv::OpCompositeExtract, TypeF32(state), value, - coordinates, component + 1u); - } else { - const auto pointer = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpAccessChain, - TypePointer(state, spv::StorageClassInput, TypeF32(state)), - pointer, variable, ConstantU32(state, component + 1u)); - state.builder.AddFunction(spv::OpLoad, TypeF32(state), value, pointer); - } - state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, value); - return bits; - } - return EmitInputComponentU32(state, kind, component); -} - -uint32_t EmitDppWriteCondition(ValueEmitContext& ctx, const IR::DppMoveFlags& flags, - uint32_t exec) { - auto& state = ctx.state; - const auto lane = EmitSubgroupLocalInvocationId(state); - const auto bank_shift = state.builder.AllocateId(); - const auto row_shift = state.builder.AllocateId(); - const auto bank = state.builder.AllocateId(); - const auto row = state.builder.AllocateId(); - const auto bank_bit = state.builder.AllocateId(); - const auto row_bit = state.builder.AllocateId(); - const auto bank_hit = state.builder.AllocateId(); - const auto row_hit = state.builder.AllocateId(); - const auto bank_ok = state.builder.AllocateId(); - const auto row_ok = state.builder.AllocateId(); - const auto masks_ok = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpShiftRightLogical, TypeU32(state), bank_shift, lane, - ConstantU32(state, 2)); - state.builder.AddFunction(spv::OpShiftRightLogical, TypeU32(state), row_shift, lane, - ConstantU32(state, 4)); - state.builder.AddFunction(spv::OpBitwiseAnd, TypeU32(state), bank, bank_shift, - ConstantU32(state, 3)); - state.builder.AddFunction(spv::OpBitwiseAnd, TypeU32(state), row, row_shift, - ConstantU32(state, 3)); - state.builder.AddFunction(spv::OpShiftLeftLogical, TypeU32(state), bank_bit, - ConstantU32(state, 1), bank); - state.builder.AddFunction(spv::OpShiftLeftLogical, TypeU32(state), row_bit, - ConstantU32(state, 1), row); - state.builder.AddFunction(spv::OpBitwiseAnd, TypeU32(state), bank_hit, - ConstantU32(state, flags.bank_mask), bank_bit); - state.builder.AddFunction(spv::OpBitwiseAnd, TypeU32(state), row_hit, - ConstantU32(state, flags.row_mask), row_bit); - state.builder.AddFunction(spv::OpINotEqual, TypeBool(state), bank_ok, bank_hit, - ConstantU32(state, 0)); - state.builder.AddFunction(spv::OpINotEqual, TypeBool(state), row_ok, row_hit, - ConstantU32(state, 0)); - state.builder.AddFunction(spv::OpLogicalAnd, TypeBool(state), masks_ok, bank_ok, row_ok); - uint32_t writable = masks_ok; - if (!flags.bound_control) { - const auto target = EmitDppTargetLane(state, flags); - const auto bounded = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpLogicalAnd, TypeBool(state), bounded, writable, - target.valid); - writable = bounded; - } - const auto result = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpLogicalAnd, TypeBool(state), result, exec, writable); - return result; -} - -uint32_t EmitAttribute(EmitterState& state, uint32_t attr, uint32_t chan) { - const auto* input = InputBindingForParameter(state, attr); - if (input == nullptr || input->variable_id == 0) { - return ConstantU32(state, 0); - } - if (state.program.stage == ShaderType::Vertex || state.program.stage == ShaderType::Local) { - return EmitVertexParameterComponentU32(state, *input, chan & 3u); - } - const auto load_per_vertex = [&](uint32_t vertex) { - const auto pointer = state.builder.AllocateId(); - const auto value = state.builder.AllocateId(); - state.builder.AddFunction( - spv::OpAccessChain, TypePointer(state, spv::StorageClassInput, TypeF32(state)), pointer, - input->variable_id, ConstantU32(state, vertex), ConstantU32(state, chan & 3u)); - state.builder.AddFunction(spv::OpLoad, TypeF32(state), value, pointer); - return value; - }; - if (input->per_vertex) { - if (PixelParameterIsFlat(state, attr)) { - const auto value = load_per_vertex( - state.input_info.pixel->parameter_mode == ShaderPixelParameterMode::LastVertex ? 2u : 0u); - const auto bits = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, value); - return bits; - } - const auto barycentric_kind = state.input_info.pixel->ps_no_perspective - ? IR::StageInputKind::BaryCoordNoPerspective - : IR::StageInputKind::BaryCoordSmooth; - const auto barycentric = InputVariableForKind(state, barycentric_kind); - uint32_t sum = 0; - for (uint32_t vertex = 0; vertex < 3u; vertex++) { - const auto pointer = state.builder.AllocateId(); - const auto weight = state.builder.AllocateId(); - const auto product = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpAccessChain, - TypePointer(state, spv::StorageClassInput, TypeF32(state)), - pointer, barycentric, ConstantU32(state, vertex)); - state.builder.AddFunction(spv::OpLoad, TypeF32(state), weight, pointer); - state.builder.AddFunction(spv::OpFMul, TypeF32(state), product, load_per_vertex(vertex), - weight); - if (vertex == 0u) { - sum = product; - } else { - const auto next = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpFAdd, TypeF32(state), next, sum, product); - sum = next; - } - } - const auto bits = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, sum); - return bits; - } - const auto vector = state.builder.AllocateId(); - const auto component = state.builder.AllocateId(); - const auto bits = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpLoad, TypeF32Vector(state, 4), vector, input->variable_id); - state.builder.AddFunction(spv::OpCompositeExtract, TypeF32(state), component, vector, - chan & 3u); - state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, component); - return bits; -} - -uint32_t EmitInterpolationParameter(ValueEmitContext& ctx, uint32_t attr, uint32_t chan, - uint32_t mode) { - auto& state = ctx.state; - const auto* input = InputBindingForParameter(state, attr); - if (!input->per_vertex) { - return EmitAttribute(ctx.state, attr, chan); - } - const auto load_vertex = [&](uint32_t vertex) { - const auto pointer = state.builder.AllocateId(); - const auto value = state.builder.AllocateId(); - state.builder.AddFunction( - spv::OpAccessChain, TypePointer(state, spv::StorageClassInput, TypeF32(state)), pointer, - input->variable_id, ConstantU32(state, vertex), ConstantU32(state, chan & 3u)); - state.builder.AddFunction(spv::OpLoad, TypeF32(state), value, pointer); - return value; - }; - - uint32_t selected_vertex = (mode + 1u) % 3u; - if (mode == 2u && PixelParameterIsFlat(state, attr)) { - selected_vertex = - state.input_info.pixel->parameter_mode == ShaderPixelParameterMode::LastVertex ? 2u : 0u; - } - uint32_t value = load_vertex(selected_vertex); - if (!PixelParameterIsCustom(state, attr) && mode < 2u) { - const auto delta = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpFSub, TypeF32(state), delta, value, load_vertex(0)); - value = delta; - } - const auto bits = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, value); - return bits; -} - -uint32_t MrtOutputMode(const EmitterState& state, const IR::ExportInfo& exp) { - if (state.program.stage != ShaderType::Pixel || exp.kind != IR::ExportTargetKind::Mrt || - exp.index >= std::size(state.input_info.pixel->target_output_mode)) { - return 0; - } - return state.input_info.pixel->target_output_mode[exp.index]; -} - -uint32_t ExportRawComponent(ValueEmitContext& ctx, uint32_t vector, uint32_t component) { - const auto value = ctx.state.builder.AllocateId(); - ctx.state.builder.AddFunction(spv::OpCompositeExtract, TypeU32(ctx.state), value, vector, - component); - return value; -} - -uint32_t ExportVector(ValueEmitContext& ctx, uint32_t data, const IR::ExportInfo& exp, - bool uint_output) { - auto& state = ctx.state; - if (exp.compr && !uint_output) { - auto unpack = GLSLstd450UnpackHalf2x16; - switch (MrtOutputMode(state, exp)) { - case 5: unpack = GLSLstd450UnpackUnorm2x16; break; - case 6: unpack = GLSLstd450UnpackSnorm2x16; break; - default: break; - } - uint32_t f32[4] = {ConstantF32(state, 0), ConstantF32(state, 0), ConstantF32(state, 0), - ConstantF32(state, 0x3f800000u)}; - for (uint32_t pair = 0; pair < 2u; pair++) { - if ((exp.en & (3u << (pair * 2u))) == 0u) { - continue; - } - const auto packed = state.builder.AllocateId(); - const auto unpacked = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpCompositeExtract, TypeU32(state), packed, data, pair); - state.builder.AddFunction(spv::OpExtInst, TypeF32Vector(state, 2), unpacked, - GlslStd450(state), unpack, packed); - for (uint32_t lane = 0; lane < 2u; lane++) { - const auto component = pair * 2u + lane; - if (((exp.en >> component) & 1u) != 0u) { - f32[component] = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpCompositeExtract, TypeF32(state), - f32[component], unpacked, lane); - } - } - } - const auto vector = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpCompositeConstruct, TypeF32Vector(state, 4), vector, - f32[0], f32[1], f32[2], f32[3]); - return vector; - } - if (exp.compr || exp.en != 0xfu) { - uint32_t raw[4] = { - ConstantU32(state, 0), - ConstantU32(state, 0), - ConstantU32(state, 0), - ConstantU32(state, uint_output ? 1u : 0x3f800000u), - }; - if (exp.compr) { - for (uint32_t pair = 0; pair < 2u; pair++) { - if ((exp.en & (3u << (pair * 2u))) == 0u) { - continue; - } - const auto packed = ExportRawComponent(ctx, data, pair); - for (uint32_t lane = 0; lane < 2u; lane++) { - const auto component = pair * 2u + lane; - if (((exp.en >> component) & 1u) == 0u) { - continue; - } - raw[component] = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpBitFieldUExtract, TypeU32(state), raw[component], - packed, ConstantU32(state, lane * 16u), - ConstantU32(state, 16)); - } - } - } else { - for (uint32_t component = 0; component < 4u; component++) { - if (((exp.en >> component) & 1u) != 0u) { - raw[component] = ExportRawComponent(ctx, data, component); - } - } - } - data = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4), data, - raw[0], raw[1], raw[2], raw[3]); - } - if (uint_output) { - return data; - } - const auto vector = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpBitcast, TypeF32Vector(state, 4), vector, data); - return vector; -} - -void EmitAuxPositionExport(ValueEmitContext& ctx, uint32_t data, const IR::ExportInfo& exp) { - auto& state = ctx.state; - for (uint32_t component = 0; component < 4; component++) { - if ((exp.en & (1u << component)) == 0) { - continue; - } - const auto output = IR::DecodePositionExportComponent( - state.input_info.vertex->pa_cl_vs_out_cntl, exp.index, component); - if (output.layer || output.viewport) { - const auto raw = ExportRawComponent(ctx, data, component); - if (output.layer) { - const auto layer = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpBitwiseAnd, TypeU32(state), layer, raw, - ConstantU32(state, 0x7ffu)); - const auto pointer = state.program.stage == ShaderType::Mesh - ? MeshOutputPointer(state, IR::StageOutputKind::Layer) - : state.layer_variable; - state.builder.AddFunction(spv::OpStore, pointer, layer); - } - if (output.viewport) { - // GFX10 MISC.z packs the viewport index in bits 16..19 alongside the layer. - const auto viewport = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpBitFieldUExtract, TypeU32(state), viewport, raw, - ConstantU32(state, 16), ConstantU32(state, 4)); - state.builder.AddFunction(spv::OpStore, state.viewport_index_variable, viewport); - } - continue; - } - if (!output.point_size && output.clip_distance == UINT32_MAX && - output.cull_distance == UINT32_MAX) { - continue; - } - - const auto raw = ExportRawComponent(ctx, data, component); - const auto f32 = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpBitcast, TypeF32(state), f32, raw); - if (output.point_size) { - state.builder.AddFunction(spv::OpStore, state.point_size_variable, f32); - continue; - } - auto StoreDistance = [&](IR::StageOutputKind kind, uint32_t variable, uint32_t index) { - if (index == UINT32_MAX) { - return; - } - uint32_t pointer; - if (state.program.stage == ShaderType::Mesh) { - pointer = MeshOutputPointer(state, kind, index); - } else { - pointer = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpAccessChain, - TypePointer(state, spv::StorageClassOutput, TypeF32(state)), - pointer, variable, ConstantU32(state, index)); - } - state.builder.AddFunction(spv::OpStore, pointer, f32); - }; - StoreDistance(IR::StageOutputKind::ClipDistance, state.clip_distance_variable, output.clip_distance); - StoreDistance(IR::StageOutputKind::CullDistance, state.cull_distance_variable, output.cull_distance); - } -} - -uint32_t ConvertClipCoordinate(EmitterState& state, uint32_t coordinate, float scale, - float offset, float half_extent) { - const auto window = state.builder.AllocateId(); - const auto biased = state.builder.AllocateId(); - const auto divided = state.builder.AllocateId(); - const auto ndc = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpFMul, TypeF32(state), window, coordinate, - ConstantF32Value(state, scale)); - state.builder.AddFunction(spv::OpFAdd, TypeF32(state), biased, window, - ConstantF32Value(state, offset)); - state.builder.AddFunction(spv::OpFDiv, TypeF32(state), divided, biased, - ConstantF32Value(state, half_extent)); - state.builder.AddFunction(spv::OpFSub, TypeF32(state), ndc, divided, - ConstantF32Value(state, 1.0f)); - return ndc; -} - -uint32_t ConvertPositionToClipSpace(EmitterState& state, uint32_t position) { - const auto& transform = state.input_info.vertex->clip_space; - uint32_t components[4] {}; - for (uint32_t i = 0; i < 4; i++) { - components[i] = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpCompositeExtract, TypeF32(state), components[i], position, - i); - } - components[0] = ConvertClipCoordinate(state, components[0], transform.scale[0], - transform.offset[0], transform.half_extent[0]); - components[1] = ConvertClipCoordinate(state, components[1], transform.scale[1], - transform.offset[1], transform.half_extent[1]); - const auto converted = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpCompositeConstruct, TypeF32Vector(state, 4), converted, - components[0], components[1], components[2], components[3]); - return converted; -} - -} // namespace -uint32_t EmitWqmU64(EmitterState& state, uint32_t value) { - const auto shifted_one = state.builder.AllocateId(); - const auto merged_one = state.builder.AllocateId(); - const auto shifted_two = state.builder.AllocateId(); - const auto merged_two = state.builder.AllocateId(); - const auto quad_bits = state.builder.AllocateId(); - const auto result = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpShiftRightLogical, TypeU64(state), shifted_one, value, - ConstantU32(state, 1)); - state.builder.AddFunction(spv::OpBitwiseOr, TypeU64(state), merged_one, value, shifted_one); - state.builder.AddFunction(spv::OpShiftRightLogical, TypeU64(state), shifted_two, merged_one, - ConstantU32(state, 2)); - state.builder.AddFunction(spv::OpBitwiseOr, TypeU64(state), merged_two, merged_one, - shifted_two); - state.builder.AddFunction(spv::OpBitwiseAnd, TypeU64(state), quad_bits, merged_two, - ConstantU64(state, 0x1111111111111111ull)); - state.builder.AddFunction(spv::OpIMul, TypeU64(state), result, quad_bits, - ConstantU64(state, 15)); - return result; -} - -void EmitSetAttribute(ValueEmitContext& ctx, const IR::Inst& inst) { - auto& state = ctx.state; - const auto& exp = ctx.Export(inst); - const auto exec = ctx.Arg(inst, 1); - if (state.program.stage == ShaderType::Pixel && exp.vm && state.program.info.pixel_valid_mask && - state.pixel_valid_mask_variable != 0) { - const auto value = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpSelect, TypeU32(state), value, exec, ConstantU32(state, 1), - ConstantU32(state, 0)); - state.builder.AddFunction(spv::OpStore, state.pixel_valid_mask_variable, value); - } - if (exp.kind == IR::ExportTargetKind::Null || exp.en == 0u) { - return; - } - // Skip dormant color exports after their valid mask; MRT1 is reserved for logical alpha. - if (state.program.stage == ShaderType::Pixel && exp.kind == IR::ExportTargetKind::Mrt && - exp.index != 0 && state.input_info.pixel->alpha_blend_source != ShaderAlphaBlendSource::None) { - return; - } - EmitIfCondition(state, exec, [&]() { - const auto data = ctx.Arg(inst, 0); - if (exp.kind == IR::ExportTargetKind::Primitive) { - if (state.program.stage == ShaderType::Mesh) { - state.builder.AddFunction(spv::OpStore, MeshPrimitivePointer(state), - ExportRawComponent(ctx, data, 0)); - } - return; - } - if (exp.kind == IR::ExportTargetKind::Position && exp.index != 0) { - EmitAuxPositionExport(ctx, data, exp); - return; - } - if (exp.kind == IR::ExportTargetKind::MrtZ) { - if ((exp.en & 1u) != 0u && state.depth_variable != 0) { - const auto raw = ExportRawComponent(ctx, data, 0); - const auto f32 = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpBitcast, TypeF32(state), f32, raw); - state.builder.AddFunction(spv::OpStore, state.depth_variable, f32); - } - if ((exp.en & 4u) != 0u && state.sample_mask_variable != 0) { - const auto raw = ExportRawComponent(ctx, data, 2); - const auto value = state.builder.AllocateId(); - const auto pointer = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpBitcast, TypeI32(state), value, raw); - state.builder.AddFunction( - spv::OpAccessChain, TypePointer(state, spv::StorageClassOutput, TypeI32(state)), - pointer, state.sample_mask_variable, ConstantU32(state, 0)); - state.builder.AddFunction(spv::OpStore, pointer, value); - } - return; - } - const auto variable = - state.program.stage == ShaderType::Mesh ? 0u : OutputVariableForExport(state, exp); - if (state.program.stage != ShaderType::Mesh && variable == 0) { - return; - } - const bool uint_output = MrtOutputMode(state, exp) == 7u; - const auto vector_type = uint_output ? TypeU32Vector(state, 4) : TypeF32Vector(state, 4); - auto value = ExportVector(ctx, data, exp, uint_output); - if (state.program.stage == ShaderType::Pixel && exp.kind == IR::ExportTargetKind::Mrt && - exp.index == 0 && !uint_output && - state.input_info.pixel->alpha_blend_source != ShaderAlphaBlendSource::None) { - // Broadcast logical alpha before swizzling the primary output. - const auto blend_output = - OutputVariableForExport(state, {.kind = IR::ExportTargetKind::Mrt, .index = 1}); - if (blend_output != 0) { - auto alpha = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpVectorShuffle, vector_type, alpha, value, value, - 3u, 3u, 3u, 3u); - uint32_t alpha_factor = 0; - switch (state.input_info.pixel->alpha_blend_source) { - case ShaderAlphaBlendSource::SourceAlphaOne: - alpha_factor = ConstantF32Value(state, 1.0f); - break; - case ShaderAlphaBlendSource::SourceAlphaZero: - alpha_factor = ConstantF32Value(state, 0.0f); - break; - default: break; - } - if (alpha_factor != 0) { - const auto mapping = state.input_info.pixel->target_export_mapping[0]; - for (uint32_t component = 0; component < 4; component++) { - if (mapping.Map(component) != 3u) continue; - const auto factors = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpCompositeInsert, vector_type, factors, - alpha_factor, alpha, component); - alpha = factors; - break; - } - } - state.builder.AddFunction(spv::OpStore, blend_output, alpha); - } - } - if (state.program.stage == ShaderType::Pixel && exp.kind == IR::ExportTargetKind::Mrt && - exp.index < state.input_info.pixel->target_export_mapping.size()) { - const auto mapping = state.input_info.pixel->target_export_mapping[exp.index]; - if (!mapping.IsIdentity()) { - const auto mapped = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpVectorShuffle, vector_type, mapped, value, value, - mapping.Map(0), mapping.Map(1), mapping.Map(2), - mapping.Map(3)); - value = mapped; - } - if ((state.input_info.pixel->target_packed_unorm_mask & (1u << exp.index)) != 0u) { - if (exp.compr || MrtOutputMode(state, exp) != 9u || - (mapping.ApplyMask(exp.en) & 7u) != 7u) { - EXIT("unsupported packed UNorm EXP: export=%u mode=%u en=0x%x compr=%u\n", - exp.index, MrtOutputMode(state, exp), exp.en, static_cast(exp.compr)); - } - const auto info = Format::GetFormatInfo(Prospero::BufferFormat::k11_11_10UNorm); - const auto rounding = (state.input_info.pixel->target_round_mode & (1u << exp.index)) != 0 - ? UnormRounding::Truncate : UnormRounding::HalfUp; - const auto raw = Unary(state, spv::OpBitcast, TypeU32Vector(state, 4), value); - auto packed = ConstantU32(state, 0); - for (uint32_t component = 0; component < info.component_count; component++) { - const auto encoded = EncodePackedColorComponent( - state, info, component, ExportRawComponent(ctx, raw, component), 32u, rounding); - packed = component == 0u ? encoded - : Binary(state, spv::OpBitwiseOr, TypeU32(state), packed, encoded); - } - value = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4), value, - packed, ConstantU32(state, 0), ConstantU32(state, 0), - ConstantU32(state, 0)); - } - } - if (exp.kind == IR::ExportTargetKind::Position && - state.input_info.vertex->clip_space.enabled) { - value = ConvertPositionToClipSpace(state, value); - } - if (state.program.stage == ShaderType::Mesh) { - const auto kind = exp.kind == IR::ExportTargetKind::Position - ? IR::StageOutputKind::Position - : IR::StageOutputKind::Parameter; - state.builder.AddFunction(spv::OpStore, MeshOutputPointer(state, kind, exp.index), - value); - } else if (exp.kind == IR::ExportTargetKind::Position) { - if (state.invalid_position_clip_distance != UINT32_MAX) { - const auto zero = state.builder.Constant(spv::OpConstantNull, TypeF32Vector(state, 4)); - const auto equal = state.builder.AllocateId(); - const auto invalid = state.builder.AllocateId(); - const auto distance = state.builder.AllocateId(); - const auto distance_pointer = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpFOrdEqual, TypeBoolVector(state, 4), equal, - value, zero); - state.builder.AddFunction(spv::OpAll, TypeBool(state), invalid, equal); - // Zero at valid vertices makes a primitive containing an invalid position - // collapse to its remaining edge, before the undefined 0/0 perspective divide. - state.builder.AddFunction(spv::OpSelect, TypeF32(state), distance, invalid, - ConstantF32Value(state, -1.0f), - ConstantF32Value(state, 0.0f)); - state.builder.AddFunction( - spv::OpAccessChain, TypePointer(state, spv::StorageClassOutput, TypeF32(state)), - distance_pointer, state.clip_distance_variable, - ConstantU32(state, state.invalid_position_clip_distance)); - state.builder.AddFunction(spv::OpStore, distance_pointer, distance); - static std::atomic_bool logged = false; - if (!logged.exchange(true, std::memory_order_relaxed)) { - Log::WriteToConsoleAndLog( - "Shader: emitted zero-position clip guard\n"); - } - } - const auto pointer = state.builder.AllocateId(); - state.builder.AddFunction( - spv::OpAccessChain, - TypePointer(state, spv::StorageClassOutput, TypeF32Vector(state, 4)), pointer, - variable, ConstantU32(state, 0)); - state.builder.AddFunction(spv::OpStore, pointer, value); - } else { - state.builder.AddFunction(spv::OpStore, variable, value); - } - }); -} - -uint32_t EmitIdentity(ValueEmitContext&, uint32_t value) { - return value; -} - -void EmitVoid(ValueEmitContext&) {} - -void EmitStoreCompletion(EmitterState& state) { - if (state.scalar_subgroups) { - return; // Nothing else in the wave can observe these stores. - } - state.builder.AddFunction( - spv::OpControlBarrier, ConstantU32(state, spv::ScopeSubgroup), - ConstantU32(state, spv::ScopeDevice), - ConstantU32(state, spv::MemorySemanticsReleaseMask | spv::MemorySemanticsUniformMemoryMask | - spv::MemorySemanticsImageMemoryMask)); -} - -void EmitBarrier(EmitterState& state) { - const auto tessellation = state.program.stage == ShaderType::TessellationControl; - if (!tessellation && ShaderWorkgroupInput(state.program.stage, state.input_info) == nullptr) { - // Independent graphics invocations have no native workgroup left to synchronize. - return; - } - const auto memory_scope = tessellation ? spv::ScopeInvocation : spv::ScopeWorkgroup; - const auto memory = state.lds_storage_class == spv::StorageClassStorageBuffer - ? spv::MemorySemanticsUniformMemoryMask - : spv::MemorySemanticsWorkgroupMemoryMask; - const auto semantics = tessellation ? spv::MemorySemanticsMaskNone - : spv::MemorySemanticsAcquireReleaseMask | memory; - state.builder.AddFunction(spv::OpControlBarrier, ConstantU32(state, spv::ScopeWorkgroup), - ConstantU32(state, memory_scope), ConstantU32(state, semantics)); -} - -uint32_t EmitLaneId(EmitterState& state) { - return state.program.stage == ShaderType::TessellationControl - ? EmitBuiltinU32(state, IR::StageInputKind::InvocationId, 0) - : EmitSubgroupLocalInvocationId(state); -} - -uint32_t EmitMeshDrawParameter(ValueEmitContext& ctx, const IR::Inst& inst) { - auto& state = ctx.state; - const auto index = inst.Arg(0).U32(); - if (state.program.stage != ShaderType::Mesh || index >= IR::PushData::MeshDrawDwordCount) { - ctx.Fail(inst, "invalid mesh draw parameter"); - } - return EmitPushDataLoad(state, ConstantU32(state, index)); -} - -uint32_t EmitGetUserData(EmitterState& state, IR::ScalarReg reg) { - - uint32_t dword = 0; - if (!UserDataDwordIndex(state, reg, dword)) { - return ConstantU32(state, 0); - } else { - return EmitShaderDataDwordLoad(state, dword); - } -} - -uint32_t EmitGetBuiltin(ValueEmitContext& ctx, IR::Value kind, IR::Value index) { - return EmitBuiltinU32(ctx.state, static_cast(kind.U32()), index.U32()); -} - -uint32_t EmitGetDispatchThreadExtent(ValueEmitContext& ctx, const IR::Inst& inst) { - const auto start = ctx.state.program.bindings.dispatch_thread_dword; - if (start == IR::PushData::NoStart || !inst.Arg(0).IsImmediate() || inst.Arg(0).U32() >= 3u) { - ctx.Fail(inst, "invalid dispatch thread extent"); - } - return EmitShaderDataDwordLoad(ctx.state, start + inst.Arg(0).U32()); -} - -uint32_t EmitUndefU1(EmitterState& state, const IR::Inst& inst) { - const auto result = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpUndef, TypeId(state, inst.GetType()), result); - return result; -} - -uint32_t EmitDppMoveU32(ValueEmitContext& ctx, const IR::Inst& inst) { - auto& state = ctx.state; - const auto flags = inst.Flags(); - const auto target = EmitDppTargetLane(state, flags); - const auto shuffled = ctx.Shuffle(inst, 0, target.lane); - if (flags.fetch_inactive) { - return shuffled; - } - const auto ballot = ctx.Ballot(inst.Arg(1)); - const auto source_active = EmitBallotLaneActiveBool(state, ballot, target.lane); - const auto can_fetch = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpLogicalAnd, TypeBool(state), can_fetch, target.valid, - source_active); - return EmitNative(ctx.state, can_fetch, shuffled, - ConstantU32(state, 0)); -} - -uint32_t EmitDppUpdateU32(ValueEmitContext& ctx, const IR::Inst& inst) { - const auto flags = inst.Flags(); - const auto write = EmitDppWriteCondition(ctx, flags, ctx.Arg(inst, 2)); - return EmitNative(ctx.state, write, ctx.Arg(inst, 0), - ctx.Arg(inst, 1)); -} - -uint32_t EmitConditionRef(ValueEmitContext& ctx, const IR::Inst& inst) { - // Scalar branches include lanes disabled by EXEC, which the branch body may restore. - if (ctx.other_half != nullptr && ctx.half != 0) return ctx.other_half->Result(inst); - const auto kind = inst.Flags(); - if (kind == CFG::BranchCondition::ScalarInstruction) return ctx.Arg(inst, 0); - const bool zero = kind == CFG::BranchCondition::ExecZero || - kind == CFG::BranchCondition::VccZero || kind == CFG::BranchCondition::SccZero; - // Zero-kind predicates are already inverted by translation. - auto predicate = ctx.Arg(inst, 0); - if (ctx.other_half != nullptr) { - predicate = Binary(ctx.state, zero ? spv::OpLogicalAnd : spv::OpLogicalOr, - TypeBool(ctx.state), predicate, ctx.HalfArg(inst, 0, 1)); - } - if (ctx.state.scalar_subgroups) { - return predicate; - } - auto& state = ctx.state; - if (WaveHalvesInHostSubgroup(state)) { - const auto ballot = state.builder.AllocateId(); - const auto tested = zero ? EmitLogicalNotBool(state, predicate) : predicate; - state.builder.AddFunction(spv::OpGroupNonUniformBallot, TypeU32Vector(state, 4), ballot, - ConstantU32(state, spv::ScopeSubgroup), tested); - const auto word = EmitOwnWaveHalfWord(state, ballot); - const auto result = state.builder.AllocateId(); - state.builder.AddFunction(zero ? spv::OpIEqual : spv::OpINotEqual, TypeBool(state), result, - word, ConstantU32(state, 0)); - return result; - } - // Exclude helper invocations from both Any and All without changing the - // identity of the reduction (false for Any, true for All). - if (state.helper_invocation_variable != 0) { - const auto tested = zero ? EmitLogicalNotBool(state, predicate) : predicate; - predicate = EmitLiveInvocationPredicate(state, tested); - if (zero) predicate = EmitLogicalNotBool(state, predicate); - } - const auto result = state.builder.AllocateId(); - state.builder.AddFunction(zero ? spv::OpGroupNonUniformAll : spv::OpGroupNonUniformAny, - TypeBool(state), result, - ConstantU32(state, spv::ScopeSubgroup), predicate); - return result; -} - -uint32_t EmitBallot(ValueEmitContext& ctx, IR::Value predicate) { - return ctx.Ballot(predicate); -} - -uint32_t EmitReadFirstLane(ValueEmitContext& ctx, const IR::Inst& inst) { - if (ctx.state.scalar_subgroups) { - return ctx.Arg(inst, 0); - } - const auto ballot = ctx.Ballot(inst.Arg(1)); - const auto lane = ctx.FirstLane(ballot); - const auto shuffled = ctx.Shuffle(inst, 0, lane); - if (WaveHalvesInHostSubgroup(ctx.state)) { - // Each half is its own guest wave: the value is uniform per half only. - return shuffled; - } - // Every lane now holds the same value, so reading the first active lane changes nothing but - // tells the driver the result is uniform. AMD compiles the shuffle alone to ds_bpermute and - // treats its result as per-lane, which turned everything derived from a waterfall key - // (scalar loads, address math, loop exits) into vector code. - auto& state = ctx.state; - const auto result = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpGroupNonUniformBroadcastFirst, - TypeId(state, inst.Arg(0).GetType()), result, - ConstantU32(state, spv::ScopeSubgroup), shuffled); - return result; -} - -uint32_t EmitReadLane(ValueEmitContext& ctx, const IR::Inst& inst) { - if (ctx.state.scalar_subgroups) { - return ctx.Arg(inst, 0); - } - // V_READLANE's lane is an SGPR or a constant, so the result is uniform too; see - // EmitReadFirstLane. - auto& state = ctx.state; - if (WaveHalvesInHostSubgroup(state)) { - // The lane is the guest wave's (wave32 reads its low 5 bits): offset it into the - // invocation's own half. - const auto lane = - EmitBinaryU32(state, spv::OpBitwiseAnd, ctx.Arg(inst, 1), ConstantU32(state, 31)); - return ctx.Shuffle(inst, 0, - EmitAddU32(state, EmitLaunchedLaneAtOrBelow(state, lane), - EmitOwnWaveHalfBase(state))); - } - const auto shuffled = ctx.Shuffle(inst, 0, EmitLaunchedLaneAtOrBelow(state, ctx.Arg(inst, 1))); - const auto result = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpGroupNonUniformBroadcastFirst, - TypeId(state, inst.Arg(0).GetType()), result, - ConstantU32(state, spv::ScopeSubgroup), shuffled); - return result; -} - -uint32_t EmitSubgroupUMinU32(ValueEmitContext& ctx, const IR::Inst& inst) { - auto& state = ctx.state; - auto value = ctx.Arg(inst, 0); - if (ctx.other_half != nullptr) { - value = EmitUMin32(state, ctx.HalfArg(inst, 0, 0), ctx.HalfArg(inst, 0, 1)); - } - if (state.scalar_subgroups) { - return value; - } - const auto result = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpGroupNonUniformUMin, TypeU32(state), result, - ConstantU32(state, spv::ScopeSubgroup), spv::GroupOperationReduce, value); - return result; -} - -uint32_t EmitWriteLane(ValueEmitContext& ctx, const IR::Inst& inst) { - auto& state = ctx.state; - const auto hit = state.builder.AllocateId(); - const auto lane = WaveHalvesInHostSubgroup(state) - ? EmitBinaryU32(state, spv::OpBitwiseAnd, - EmitSubgroupLocalInvocationId(state), - ConstantU32(state, 31)) - : EmitSubgroupLocalInvocationId(state); - state.builder.AddFunction(spv::OpIEqual, TypeBool(state), hit, lane, ctx.Arg(inst, 2)); - return EmitNative(ctx.state, hit, ctx.Arg(inst, 1), - ctx.Arg(inst, 0)); -} - -uint32_t EmitPermlane16U32(ValueEmitContext& ctx, const IR::Inst& inst) { - auto& state = ctx.state; - const auto flags = inst.Flags(); - const auto subid = EmitSubgroupLocalInvocationId(state); - const auto row = state.builder.AllocateId(); - const auto row_value = state.builder.AllocateId(); - const auto lane = state.builder.AllocateId(); - const auto lane8 = state.builder.AllocateId(); - const auto shift = state.builder.AllocateId(); - const auto upper = state.builder.AllocateId(); - const auto selected = state.builder.AllocateId(); - const auto shifted = state.builder.AllocateId(); - const auto index = state.builder.AllocateId(); - const auto target = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpBitwiseAnd, TypeU32(state), row, subid, - ConstantU32(state, 0xfffffff0u)); - if (flags.x16) { - state.builder.AddFunction(spv::OpBitwiseXor, TypeU32(state), row_value, row, - ConstantU32(state, 16)); - } else { - state.builder.AddFunction(spv::OpCopyObject, TypeU32(state), row_value, row); - } - state.builder.AddFunction(spv::OpBitwiseAnd, TypeU32(state), lane, subid, - ConstantU32(state, 15)); - state.builder.AddFunction(spv::OpBitwiseAnd, TypeU32(state), lane8, lane, - ConstantU32(state, 7)); - state.builder.AddFunction(spv::OpShiftLeftLogical, TypeU32(state), shift, lane8, - ConstantU32(state, 2)); - state.builder.AddFunction(spv::OpUGreaterThanEqual, TypeBool(state), upper, lane, - ConstantU32(state, 8)); - state.builder.AddFunction(spv::OpSelect, TypeU32(state), selected, upper, ctx.Arg(inst, 2), - ctx.Arg(inst, 1)); - state.builder.AddFunction(spv::OpShiftRightLogical, TypeU32(state), shifted, selected, shift); - state.builder.AddFunction(spv::OpBitwiseAnd, TypeU32(state), index, shifted, - ConstantU32(state, 15)); - state.builder.AddFunction(spv::OpBitwiseOr, TypeU32(state), target, row_value, index); - const auto launched = EmitLaunchedLaneAtOrBelow(state, target); - const auto shuffled = ctx.Shuffle(inst, 0, launched); - uint32_t result = shuffled; - if (!flags.fetch_inactive) { - // A lane the host did not launch is active if the guest switched it on, which only the - // scalar EXEC copy records. - const auto in_high = state.builder.AllocateId(); - state.builder.AddFunction( - spv::OpLogicalAnd, TypeBool(state), in_high, - ConstantBool(state, state.program.wave_size == 64u), - Binary(state, spv::OpINotEqual, TypeBool(state), - EmitBinaryU32(state, spv::OpBitwiseAnd, target, ConstantU32(state, 32)), - ConstantU32(state, 0))); - const auto exec_word = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpSelect, TypeU32(state), exec_word, in_high, - ctx.Arg(inst, 5), ctx.Arg(inst, 4)); - const auto exec_bit = EmitBinaryU32( - state, spv::OpBitwiseAnd, - EmitBinaryU32(state, spv::OpShiftRightLogical, exec_word, - EmitBinaryU32(state, spv::OpBitwiseAnd, target, ConstantU32(state, 31))), - ConstantU32(state, 1)); - const auto was_launched = state.builder.AllocateId(); - const auto source_exec = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpIEqual, TypeBool(state), was_launched, launched, target); - state.builder.AddFunction( - spv::OpSelect, TypeBool(state), source_exec, was_launched, ctx.Shuffle(inst, 3, launched), - Binary(state, spv::OpINotEqual, TypeBool(state), exec_bit, ConstantU32(state, 0))); - result = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpSelect, TypeU32(state), result, source_exec, shuffled, - ConstantU32(state, 0)); - } - return result; -} - -uint32_t EmitGetAttribute(ValueEmitContext& ctx, const IR::Inst& inst) { - return EmitAttribute(ctx.state, inst.Arg(0).U32(), inst.Arg(1).U32()); -} - -uint32_t EmitGetInterpolationParameter(ValueEmitContext& ctx, const IR::Inst& inst) { - return EmitInterpolationParameter(ctx, inst.Arg(0).U32(), inst.Arg(1).U32(), inst.Arg(2).U32()); -} - -uint32_t EmitGetShaderBase(ValueEmitContext& ctx) { - // Guest S_GETPC values stay shader-relative in SPIR-V, matching the runtime ABI. The - // runtime descriptor evaluator supplies the mapped shader base for host-side planning. - return ctx.Def(IR::Value(uint64_t {0})); -} - -void EmitUnreachable(ValueEmitContext& ctx, const IR::Inst& inst) { - ctx.Fail(inst, "must be lowered before SPIR-V emission"); -} - -} // namespace Libs::Graphics::ShaderRecompiler::Spirv::Emitter +#include "graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h" + +#include "common/logging/log.h" + +#include +#include + +namespace Libs::Graphics::ShaderRecompiler::Spirv::Emitter { +namespace { + +bool UserDataDwordIndex(const EmitterState& state, IR::ScalarReg reg, uint32_t& dword_index) { + const auto register_index = IR::RegIndex(reg); + const auto& registers = state.program.info.user_data_registers; + const auto found = std::lower_bound(registers.begin(), registers.end(), register_index); + if (found == registers.end() || *found != register_index) { + return false; + } + dword_index = static_cast(found - registers.begin()); + return true; +} + +uint32_t EmitBuiltinU32(EmitterState& state, IR::StageInputKind kind, uint32_t component) { + if (kind == IR::StageInputKind::LocalInvocationIndex) { + return EmitLocalInvocationIndex(state); + } + if (state.lane_count == 2 && (kind == IR::StageInputKind::LocalInvocationId || + kind == IR::StageInputKind::GlobalInvocationId)) { + const auto* cs = ShaderWorkgroupInput(state.program.stage, state.input_info); + uint32_t divisor = 1; + for (uint32_t axis = 0; axis < component; axis++) { + divisor *= std::max(cs->threads_num[axis], 1u); + } + const auto size = std::max(cs->threads_num[component], 1u); + const auto divided = EmitBinaryU32(state, spv::OpUDiv, EmitLocalInvocationIndex(state), + ConstantU32(state, divisor)); + const auto local = EmitBinaryU32(state, spv::OpUMod, divided, ConstantU32(state, size)); + if (kind == IR::StageInputKind::LocalInvocationId) { + return local; + } + const auto group = EmitInputComponentU32(state, IR::StageInputKind::WorkgroupId, component); + return EmitAddU32(state, local, + EmitBinaryU32(state, spv::OpIMul, group, ConstantU32(state, size))); + } + const bool centroid = kind == IR::StageInputKind::BaryCoordSmoothCentroid; + const bool sample = kind == IR::StageInputKind::BaryCoordSmoothSample; + const auto variable = InputVariableForKind( + state, centroid || sample ? IR::StageInputKind::BaryCoordSmooth : kind); + if (variable == 0) { + return ConstantU32(state, 0); + } + if (kind == IR::StageInputKind::FrontFacing) { + const auto value = state.builder.AllocateId(); + const auto bits = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLoad, TypeBool(state), value, variable); + // SPI_BARYC_CNTL.FRONT_FACE_ALL_BITS selects uint masks or float +/-1. + const bool all_bits = + state.input_info.pixel != nullptr && state.input_info.pixel->ps_front_face_all_bits; + const auto front = ConstantU32(state, all_bits ? 0xffffffffu : 0x3f800000u); + const auto back = ConstantU32(state, all_bits ? 0u : 0xbf800000u); + state.builder.AddFunction(spv::OpSelect, TypeU32(state), bits, value, front, back); + return bits; + } + if (kind == IR::StageInputKind::VertexIndex || kind == IR::StageInputKind::InstanceIndex || + kind == IR::StageInputKind::InvocationId || kind == IR::StageInputKind::PrimitiveId || + kind == IR::StageInputKind::Layer || kind == IR::StageInputKind::SampleId) { + const auto value = state.builder.AllocateId(); + const auto bits = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLoad, TypeI32(state), value, variable); + state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, value); + return bits; + } + if (kind == IR::StageInputKind::FragCoord || kind == IR::StageInputKind::TessCoord) { + const auto pointer = state.builder.AllocateId(); + const auto value = state.builder.AllocateId(); + const auto bits = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpAccessChain, + TypePointer(state, spv::StorageClassInput, TypeF32(state)), + pointer, variable, ConstantU32(state, component)); + state.builder.AddFunction(spv::OpLoad, TypeF32(state), value, pointer); + state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, value); + return bits; + } + if (centroid || sample || kind == IR::StageInputKind::BaryCoordSmooth || + kind == IR::StageInputKind::BaryCoordNoPerspective) { + const auto value = state.builder.AllocateId(); + const auto bits = state.builder.AllocateId(); + if (centroid || sample) { + const auto coordinates = state.builder.AllocateId(); + state.builder.RequireCapability(spv::CapabilityInterpolationFunction); + if (sample) { + const auto sample_id = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLoad, TypeI32(state), sample_id, + InputVariableForKind(state, IR::StageInputKind::SampleId)); + state.builder.AddFunction(spv::OpExtInst, TypeF32Vector(state, 3), coordinates, + GlslStd450(state), GLSLstd450InterpolateAtSample, + variable, sample_id); + } else { + state.builder.AddFunction(spv::OpExtInst, TypeF32Vector(state, 3), coordinates, + GlslStd450(state), GLSLstd450InterpolateAtCentroid, variable); + } + state.builder.AddFunction(spv::OpCompositeExtract, TypeF32(state), value, + coordinates, component + 1u); + } else { + const auto pointer = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpAccessChain, + TypePointer(state, spv::StorageClassInput, TypeF32(state)), + pointer, variable, ConstantU32(state, component + 1u)); + state.builder.AddFunction(spv::OpLoad, TypeF32(state), value, pointer); + } + state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, value); + return bits; + } + return EmitInputComponentU32(state, kind, component); +} + +uint32_t EmitDppWriteCondition(ValueEmitContext& ctx, const IR::DppMoveFlags& flags, + uint32_t exec) { + auto& state = ctx.state; + const auto lane = EmitSubgroupLocalInvocationId(state); + const auto bank_shift = state.builder.AllocateId(); + const auto row_shift = state.builder.AllocateId(); + const auto bank = state.builder.AllocateId(); + const auto row = state.builder.AllocateId(); + const auto bank_bit = state.builder.AllocateId(); + const auto row_bit = state.builder.AllocateId(); + const auto bank_hit = state.builder.AllocateId(); + const auto row_hit = state.builder.AllocateId(); + const auto bank_ok = state.builder.AllocateId(); + const auto row_ok = state.builder.AllocateId(); + const auto masks_ok = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpShiftRightLogical, TypeU32(state), bank_shift, lane, + ConstantU32(state, 2)); + state.builder.AddFunction(spv::OpShiftRightLogical, TypeU32(state), row_shift, lane, + ConstantU32(state, 4)); + state.builder.AddFunction(spv::OpBitwiseAnd, TypeU32(state), bank, bank_shift, + ConstantU32(state, 3)); + state.builder.AddFunction(spv::OpBitwiseAnd, TypeU32(state), row, row_shift, + ConstantU32(state, 3)); + state.builder.AddFunction(spv::OpShiftLeftLogical, TypeU32(state), bank_bit, + ConstantU32(state, 1), bank); + state.builder.AddFunction(spv::OpShiftLeftLogical, TypeU32(state), row_bit, + ConstantU32(state, 1), row); + state.builder.AddFunction(spv::OpBitwiseAnd, TypeU32(state), bank_hit, + ConstantU32(state, flags.bank_mask), bank_bit); + state.builder.AddFunction(spv::OpBitwiseAnd, TypeU32(state), row_hit, + ConstantU32(state, flags.row_mask), row_bit); + state.builder.AddFunction(spv::OpINotEqual, TypeBool(state), bank_ok, bank_hit, + ConstantU32(state, 0)); + state.builder.AddFunction(spv::OpINotEqual, TypeBool(state), row_ok, row_hit, + ConstantU32(state, 0)); + state.builder.AddFunction(spv::OpLogicalAnd, TypeBool(state), masks_ok, bank_ok, row_ok); + uint32_t writable = masks_ok; + if (!flags.bound_control) { + const auto target = EmitDppTargetLane(state, flags); + const auto bounded = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLogicalAnd, TypeBool(state), bounded, writable, + target.valid); + writable = bounded; + } + const auto result = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLogicalAnd, TypeBool(state), result, exec, writable); + return result; +} + +uint32_t EmitAttribute(EmitterState& state, uint32_t attr, uint32_t chan) { + const auto* input = InputBindingForParameter(state, attr); + if (input == nullptr || input->variable_id == 0) { + return ConstantU32(state, 0); + } + if (state.program.stage == ShaderType::Vertex || state.program.stage == ShaderType::Local) { + return EmitVertexParameterComponentU32(state, *input, chan & 3u); + } + const auto load_per_vertex = [&](uint32_t vertex) { + const auto pointer = state.builder.AllocateId(); + const auto value = state.builder.AllocateId(); + if (input->component_count == 1u) { + state.builder.AddFunction( + spv::OpAccessChain, TypePointer(state, spv::StorageClassInput, TypeF32(state)), + pointer, input->variable_id, ConstantU32(state, vertex)); + } else { + state.builder.AddFunction( + spv::OpAccessChain, TypePointer(state, spv::StorageClassInput, TypeF32(state)), + pointer, input->variable_id, ConstantU32(state, vertex), + ConstantU32(state, chan & 3u)); + } + state.builder.AddFunction(spv::OpLoad, TypeF32(state), value, pointer); + return value; + }; + if (input->per_vertex) { + if (PixelParameterIsFlat(state, attr)) { + const auto value = load_per_vertex( + state.input_info.pixel->parameter_mode == ShaderPixelParameterMode::LastVertex ? 2u : 0u); + const auto bits = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, value); + return bits; + } + const auto barycentric_kind = state.input_info.pixel->ps_no_perspective + ? IR::StageInputKind::BaryCoordNoPerspective + : IR::StageInputKind::BaryCoordSmooth; + const auto barycentric = InputVariableForKind(state, barycentric_kind); + uint32_t sum = 0; + for (uint32_t vertex = 0; vertex < 3u; vertex++) { + const auto pointer = state.builder.AllocateId(); + const auto weight = state.builder.AllocateId(); + const auto product = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpAccessChain, + TypePointer(state, spv::StorageClassInput, TypeF32(state)), + pointer, barycentric, ConstantU32(state, vertex)); + state.builder.AddFunction(spv::OpLoad, TypeF32(state), weight, pointer); + state.builder.AddFunction(spv::OpFMul, TypeF32(state), product, load_per_vertex(vertex), + weight); + if (vertex == 0u) { + sum = product; + } else { + const auto next = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpFAdd, TypeF32(state), next, sum, product); + sum = next; + } + } + const auto bits = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, sum); + return bits; + } + const auto component = state.builder.AllocateId(); + const auto bits = state.builder.AllocateId(); + if (input->component_count == 1u) { + state.builder.AddFunction(spv::OpLoad, TypeF32(state), component, input->variable_id); + } else { + const auto vector = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLoad, TypeF32Vector(state, input->component_count), vector, + input->variable_id); + state.builder.AddFunction(spv::OpCompositeExtract, TypeF32(state), component, vector, + chan & 3u); + } + state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, component); + return bits; +} + +uint32_t EmitInterpolationParameter(ValueEmitContext& ctx, uint32_t attr, uint32_t chan, + uint32_t mode) { + auto& state = ctx.state; + const auto* input = InputBindingForParameter(state, attr); + if (!input->per_vertex) { + return EmitAttribute(ctx.state, attr, chan); + } + const auto load_vertex = [&](uint32_t vertex) { + const auto pointer = state.builder.AllocateId(); + const auto value = state.builder.AllocateId(); + if (input->component_count == 1u) { + state.builder.AddFunction( + spv::OpAccessChain, TypePointer(state, spv::StorageClassInput, TypeF32(state)), + pointer, input->variable_id, ConstantU32(state, vertex)); + } else { + state.builder.AddFunction( + spv::OpAccessChain, TypePointer(state, spv::StorageClassInput, TypeF32(state)), + pointer, input->variable_id, ConstantU32(state, vertex), + ConstantU32(state, chan & 3u)); + } + state.builder.AddFunction(spv::OpLoad, TypeF32(state), value, pointer); + return value; + }; + + uint32_t selected_vertex = (mode + 1u) % 3u; + if (mode == 2u && PixelParameterIsFlat(state, attr)) { + selected_vertex = + state.input_info.pixel->parameter_mode == ShaderPixelParameterMode::LastVertex ? 2u : 0u; + } + uint32_t value = load_vertex(selected_vertex); + if (!PixelParameterIsCustom(state, attr) && mode < 2u) { + const auto delta = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpFSub, TypeF32(state), delta, value, load_vertex(0)); + value = delta; + } + const auto bits = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpBitcast, TypeU32(state), bits, value); + return bits; +} + +uint32_t MrtOutputMode(const EmitterState& state, const IR::ExportInfo& exp) { + if (state.program.stage != ShaderType::Pixel || exp.kind != IR::ExportTargetKind::Mrt || + exp.index >= std::size(state.input_info.pixel->target_output_mode)) { + return 0; + } + return state.input_info.pixel->target_output_mode[exp.index]; +} + +uint32_t ExportRawComponent(ValueEmitContext& ctx, uint32_t vector, uint32_t component) { + const auto value = ctx.state.builder.AllocateId(); + ctx.state.builder.AddFunction(spv::OpCompositeExtract, TypeU32(ctx.state), value, vector, + component); + return value; +} + +uint32_t ExportVector(ValueEmitContext& ctx, uint32_t data, const IR::ExportInfo& exp, + bool uint_output) { + auto& state = ctx.state; + if (exp.compr && !uint_output) { + auto unpack = GLSLstd450UnpackHalf2x16; + switch (MrtOutputMode(state, exp)) { + case 5: unpack = GLSLstd450UnpackUnorm2x16; break; + case 6: unpack = GLSLstd450UnpackSnorm2x16; break; + default: break; + } + uint32_t f32[4] = {ConstantF32(state, 0), ConstantF32(state, 0), ConstantF32(state, 0), + ConstantF32(state, 0x3f800000u)}; + for (uint32_t pair = 0; pair < 2u; pair++) { + if ((exp.en & (3u << (pair * 2u))) == 0u) { + continue; + } + const auto packed = state.builder.AllocateId(); + const auto unpacked = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeExtract, TypeU32(state), packed, data, pair); + state.builder.AddFunction(spv::OpExtInst, TypeF32Vector(state, 2), unpacked, + GlslStd450(state), unpack, packed); + for (uint32_t lane = 0; lane < 2u; lane++) { + const auto component = pair * 2u + lane; + if (((exp.en >> component) & 1u) != 0u) { + f32[component] = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeExtract, TypeF32(state), + f32[component], unpacked, lane); + } + } + } + const auto vector = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeConstruct, TypeF32Vector(state, 4), vector, + f32[0], f32[1], f32[2], f32[3]); + return vector; + } + if (exp.compr || exp.en != 0xfu) { + uint32_t raw[4] = { + ConstantU32(state, 0), + ConstantU32(state, 0), + ConstantU32(state, 0), + ConstantU32(state, uint_output ? 1u : 0x3f800000u), + }; + if (exp.compr) { + for (uint32_t pair = 0; pair < 2u; pair++) { + if ((exp.en & (3u << (pair * 2u))) == 0u) { + continue; + } + const auto packed = ExportRawComponent(ctx, data, pair); + for (uint32_t lane = 0; lane < 2u; lane++) { + const auto component = pair * 2u + lane; + if (((exp.en >> component) & 1u) == 0u) { + continue; + } + raw[component] = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpBitFieldUExtract, TypeU32(state), raw[component], + packed, ConstantU32(state, lane * 16u), + ConstantU32(state, 16)); + } + } + } else { + for (uint32_t component = 0; component < 4u; component++) { + if (((exp.en >> component) & 1u) != 0u) { + raw[component] = ExportRawComponent(ctx, data, component); + } + } + } + data = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4), data, + raw[0], raw[1], raw[2], raw[3]); + } + if (uint_output) { + return data; + } + const auto vector = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpBitcast, TypeF32Vector(state, 4), vector, data); + return vector; +} + +void EmitAuxPositionExport(ValueEmitContext& ctx, uint32_t data, const IR::ExportInfo& exp) { + auto& state = ctx.state; + for (uint32_t component = 0; component < 4; component++) { + if ((exp.en & (1u << component)) == 0) { + continue; + } + const auto output = IR::DecodePositionExportComponent( + state.input_info.vertex->pa_cl_vs_out_cntl, exp.index, component); + if (output.layer || output.viewport) { + const auto raw = ExportRawComponent(ctx, data, component); + if (output.layer) { + const auto layer = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpBitwiseAnd, TypeU32(state), layer, raw, + ConstantU32(state, 0x7ffu)); + const auto pointer = state.program.stage == ShaderType::Mesh + ? MeshOutputPointer(state, IR::StageOutputKind::Layer) + : state.layer_variable; + state.builder.AddFunction(spv::OpStore, pointer, layer); + } + if (output.viewport) { + // GFX10 MISC.z packs the viewport index in bits 16..19 alongside the layer. + const auto viewport = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpBitFieldUExtract, TypeU32(state), viewport, raw, + ConstantU32(state, 16), ConstantU32(state, 4)); + state.builder.AddFunction(spv::OpStore, state.viewport_index_variable, viewport); + } + continue; + } + if (!output.point_size && output.clip_distance == UINT32_MAX && + output.cull_distance == UINT32_MAX) { + continue; + } + + const auto raw = ExportRawComponent(ctx, data, component); + const auto f32 = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpBitcast, TypeF32(state), f32, raw); + if (output.point_size) { + state.builder.AddFunction(spv::OpStore, state.point_size_variable, f32); + continue; + } + auto StoreDistance = [&](IR::StageOutputKind kind, uint32_t variable, uint32_t index) { + if (index == UINT32_MAX) { + return; + } + uint32_t pointer; + if (state.program.stage == ShaderType::Mesh) { + pointer = MeshOutputPointer(state, kind, index); + } else { + pointer = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpAccessChain, + TypePointer(state, spv::StorageClassOutput, TypeF32(state)), + pointer, variable, ConstantU32(state, index)); + } + state.builder.AddFunction(spv::OpStore, pointer, f32); + }; + StoreDistance(IR::StageOutputKind::ClipDistance, state.clip_distance_variable, output.clip_distance); + StoreDistance(IR::StageOutputKind::CullDistance, state.cull_distance_variable, output.cull_distance); + } +} + +uint32_t ConvertClipCoordinate(EmitterState& state, uint32_t coordinate, float scale, + float offset, float half_extent) { + const auto window = state.builder.AllocateId(); + const auto biased = state.builder.AllocateId(); + const auto divided = state.builder.AllocateId(); + const auto ndc = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpFMul, TypeF32(state), window, coordinate, + ConstantF32Value(state, scale)); + state.builder.AddFunction(spv::OpFAdd, TypeF32(state), biased, window, + ConstantF32Value(state, offset)); + state.builder.AddFunction(spv::OpFDiv, TypeF32(state), divided, biased, + ConstantF32Value(state, half_extent)); + state.builder.AddFunction(spv::OpFSub, TypeF32(state), ndc, divided, + ConstantF32Value(state, 1.0f)); + return ndc; +} + +uint32_t ConvertPositionToClipSpace(EmitterState& state, uint32_t position) { + const auto& transform = state.input_info.vertex->clip_space; + uint32_t components[4] {}; + for (uint32_t i = 0; i < 4; i++) { + components[i] = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeExtract, TypeF32(state), components[i], position, + i); + } + components[0] = ConvertClipCoordinate(state, components[0], transform.scale[0], + transform.offset[0], transform.half_extent[0]); + components[1] = ConvertClipCoordinate(state, components[1], transform.scale[1], + transform.offset[1], transform.half_extent[1]); + const auto converted = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeConstruct, TypeF32Vector(state, 4), converted, + components[0], components[1], components[2], components[3]); + return converted; +} + +} // namespace +uint32_t EmitWqmU64(EmitterState& state, uint32_t value) { + const auto shifted_one = state.builder.AllocateId(); + const auto merged_one = state.builder.AllocateId(); + const auto shifted_two = state.builder.AllocateId(); + const auto merged_two = state.builder.AllocateId(); + const auto quad_bits = state.builder.AllocateId(); + const auto result = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpShiftRightLogical, TypeU64(state), shifted_one, value, + ConstantU32(state, 1)); + state.builder.AddFunction(spv::OpBitwiseOr, TypeU64(state), merged_one, value, shifted_one); + state.builder.AddFunction(spv::OpShiftRightLogical, TypeU64(state), shifted_two, merged_one, + ConstantU32(state, 2)); + state.builder.AddFunction(spv::OpBitwiseOr, TypeU64(state), merged_two, merged_one, + shifted_two); + state.builder.AddFunction(spv::OpBitwiseAnd, TypeU64(state), quad_bits, merged_two, + ConstantU64(state, 0x1111111111111111ull)); + state.builder.AddFunction(spv::OpIMul, TypeU64(state), result, quad_bits, + ConstantU64(state, 15)); + return result; +} + +void EmitSetAttribute(ValueEmitContext& ctx, const IR::Inst& inst) { + auto& state = ctx.state; + const auto& exp = ctx.Export(inst); + const auto exec = ctx.Arg(inst, 1); + if (state.program.stage == ShaderType::Pixel && exp.vm && state.program.info.pixel_valid_mask && + state.pixel_valid_mask_variable != 0) { + const auto value = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpSelect, TypeU32(state), value, exec, ConstantU32(state, 1), + ConstantU32(state, 0)); + state.builder.AddFunction(spv::OpStore, state.pixel_valid_mask_variable, value); + } + if (exp.kind == IR::ExportTargetKind::Null || exp.en == 0u) { + return; + } + // Skip dormant color exports after their valid mask; MRT1 is reserved for logical alpha. + if (state.program.stage == ShaderType::Pixel && exp.kind == IR::ExportTargetKind::Mrt && + exp.index != 0 && state.input_info.pixel->alpha_blend_source != ShaderAlphaBlendSource::None) { + return; + } + EmitIfCondition(state, exec, [&]() { + const auto data = ctx.Arg(inst, 0); + if (exp.kind == IR::ExportTargetKind::Primitive) { + if (state.program.stage == ShaderType::Mesh) { + state.builder.AddFunction(spv::OpStore, MeshPrimitivePointer(state), + ExportRawComponent(ctx, data, 0)); + } + return; + } + if (exp.kind == IR::ExportTargetKind::Position && exp.index != 0) { + EmitAuxPositionExport(ctx, data, exp); + return; + } + if (exp.kind == IR::ExportTargetKind::MrtZ) { + if ((exp.en & 1u) != 0u && state.depth_variable != 0) { + const auto raw = ExportRawComponent(ctx, data, 0); + const auto f32 = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpBitcast, TypeF32(state), f32, raw); + state.builder.AddFunction(spv::OpStore, state.depth_variable, f32); + } + if ((exp.en & 4u) != 0u && state.sample_mask_variable != 0) { + const auto raw = ExportRawComponent(ctx, data, 2); + const auto value = state.builder.AllocateId(); + const auto pointer = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpBitcast, TypeI32(state), value, raw); + state.builder.AddFunction( + spv::OpAccessChain, TypePointer(state, spv::StorageClassOutput, TypeI32(state)), + pointer, state.sample_mask_variable, ConstantU32(state, 0)); + state.builder.AddFunction(spv::OpStore, pointer, value); + } + return; + } + const auto variable = + state.program.stage == ShaderType::Mesh ? 0u : OutputVariableForExport(state, exp); + if (state.program.stage != ShaderType::Mesh && variable == 0) { + return; + } + const bool uint_output = MrtOutputMode(state, exp) == 7u; + const auto vector_type = uint_output ? TypeU32Vector(state, 4) : TypeF32Vector(state, 4); + auto value = ExportVector(ctx, data, exp, uint_output); + if (state.program.stage == ShaderType::Pixel && exp.kind == IR::ExportTargetKind::Mrt && + exp.index == 0 && !uint_output && + state.input_info.pixel->alpha_blend_source != ShaderAlphaBlendSource::None) { + // Broadcast logical alpha before swizzling the primary output. + const auto blend_output = + OutputVariableForExport(state, {.kind = IR::ExportTargetKind::Mrt, .index = 1}); + if (blend_output != 0) { + auto alpha = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpVectorShuffle, vector_type, alpha, value, value, + 3u, 3u, 3u, 3u); + uint32_t alpha_factor = 0; + switch (state.input_info.pixel->alpha_blend_source) { + case ShaderAlphaBlendSource::SourceAlphaOne: + alpha_factor = ConstantF32Value(state, 1.0f); + break; + case ShaderAlphaBlendSource::SourceAlphaZero: + alpha_factor = ConstantF32Value(state, 0.0f); + break; + default: break; + } + if (alpha_factor != 0) { + const auto mapping = state.input_info.pixel->target_export_mapping[0]; + for (uint32_t component = 0; component < 4; component++) { + if (mapping.Map(component) != 3u) continue; + const auto factors = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeInsert, vector_type, factors, + alpha_factor, alpha, component); + alpha = factors; + break; + } + } + state.builder.AddFunction(spv::OpStore, blend_output, alpha); + } + } + if (state.program.stage == ShaderType::Pixel && exp.kind == IR::ExportTargetKind::Mrt && + exp.index < state.input_info.pixel->target_export_mapping.size()) { + const auto mapping = state.input_info.pixel->target_export_mapping[exp.index]; + if (!mapping.IsIdentity()) { + const auto mapped = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpVectorShuffle, vector_type, mapped, value, value, + mapping.Map(0), mapping.Map(1), mapping.Map(2), + mapping.Map(3)); + value = mapped; + } + if ((state.input_info.pixel->target_packed_unorm_mask & (1u << exp.index)) != 0u) { + if (exp.compr || MrtOutputMode(state, exp) != 9u || + (mapping.ApplyMask(exp.en) & 7u) != 7u) { + EXIT("unsupported packed UNorm EXP: export=%u mode=%u en=0x%x compr=%u\n", + exp.index, MrtOutputMode(state, exp), exp.en, static_cast(exp.compr)); + } + const auto info = Format::GetFormatInfo(Prospero::BufferFormat::k11_11_10UNorm); + const auto rounding = (state.input_info.pixel->target_round_mode & (1u << exp.index)) != 0 + ? UnormRounding::Truncate : UnormRounding::HalfUp; + const auto raw = Unary(state, spv::OpBitcast, TypeU32Vector(state, 4), value); + auto packed = ConstantU32(state, 0); + for (uint32_t component = 0; component < info.component_count; component++) { + const auto encoded = EncodePackedColorComponent( + state, info, component, ExportRawComponent(ctx, raw, component), 32u, rounding); + packed = component == 0u ? encoded + : Binary(state, spv::OpBitwiseOr, TypeU32(state), packed, encoded); + } + value = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 4), value, + packed, ConstantU32(state, 0), ConstantU32(state, 0), + ConstantU32(state, 0)); + } + } + if (exp.kind == IR::ExportTargetKind::Position && + state.input_info.vertex->clip_space.enabled) { + value = ConvertPositionToClipSpace(state, value); + } + if (state.program.stage == ShaderType::Mesh) { + const auto kind = exp.kind == IR::ExportTargetKind::Position + ? IR::StageOutputKind::Position + : IR::StageOutputKind::Parameter; + state.builder.AddFunction(spv::OpStore, MeshOutputPointer(state, kind, exp.index), + value); + } else if (exp.kind == IR::ExportTargetKind::Position) { + if (state.invalid_position_clip_distance != UINT32_MAX) { + const auto zero = state.builder.Constant(spv::OpConstantNull, TypeF32Vector(state, 4)); + const auto equal = state.builder.AllocateId(); + const auto invalid = state.builder.AllocateId(); + const auto distance = state.builder.AllocateId(); + const auto distance_pointer = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpFOrdEqual, TypeBoolVector(state, 4), equal, + value, zero); + state.builder.AddFunction(spv::OpAll, TypeBool(state), invalid, equal); + // Zero at valid vertices makes a primitive containing an invalid position + // collapse to its remaining edge, before the undefined 0/0 perspective divide. + state.builder.AddFunction(spv::OpSelect, TypeF32(state), distance, invalid, + ConstantF32Value(state, -1.0f), + ConstantF32Value(state, 0.0f)); + state.builder.AddFunction( + spv::OpAccessChain, TypePointer(state, spv::StorageClassOutput, TypeF32(state)), + distance_pointer, state.clip_distance_variable, + ConstantU32(state, state.invalid_position_clip_distance)); + state.builder.AddFunction(spv::OpStore, distance_pointer, distance); + static std::atomic_bool logged = false; + if (!logged.exchange(true, std::memory_order_relaxed)) { + Log::WriteToConsoleAndLog( + "Shader: emitted zero-position clip guard\n"); + } + } + const auto pointer = state.builder.AllocateId(); + state.builder.AddFunction( + spv::OpAccessChain, + TypePointer(state, spv::StorageClassOutput, TypeF32Vector(state, 4)), pointer, + variable, ConstantU32(state, 0)); + state.builder.AddFunction(spv::OpStore, pointer, value); + } else { + state.builder.AddFunction(spv::OpStore, variable, value); + } + }); +} + +uint32_t EmitIdentity(ValueEmitContext&, uint32_t value) { + return value; +} + +void EmitVoid(ValueEmitContext&) {} + +void EmitStoreCompletion(EmitterState& state) { + if (state.scalar_subgroups) { + return; // Nothing else in the wave can observe these stores. + } + state.builder.AddFunction( + spv::OpControlBarrier, ConstantU32(state, spv::ScopeSubgroup), + ConstantU32(state, spv::ScopeDevice), + ConstantU32(state, spv::MemorySemanticsReleaseMask | spv::MemorySemanticsUniformMemoryMask | + spv::MemorySemanticsImageMemoryMask)); +} + +void EmitBarrier(EmitterState& state) { + const auto tessellation = state.program.stage == ShaderType::TessellationControl; + if (!tessellation && ShaderWorkgroupInput(state.program.stage, state.input_info) == nullptr) { + // Independent graphics invocations have no native workgroup left to synchronize. + return; + } + const auto memory_scope = tessellation ? spv::ScopeInvocation : spv::ScopeWorkgroup; + const auto memory = state.lds_storage_class == spv::StorageClassStorageBuffer + ? spv::MemorySemanticsUniformMemoryMask + : spv::MemorySemanticsWorkgroupMemoryMask; + const auto semantics = tessellation ? spv::MemorySemanticsMaskNone + : spv::MemorySemanticsAcquireReleaseMask | memory; + state.builder.AddFunction(spv::OpControlBarrier, ConstantU32(state, spv::ScopeWorkgroup), + ConstantU32(state, memory_scope), ConstantU32(state, semantics)); +} + +uint32_t EmitLaneId(EmitterState& state) { + return state.program.stage == ShaderType::TessellationControl + ? EmitBuiltinU32(state, IR::StageInputKind::InvocationId, 0) + : EmitSubgroupLocalInvocationId(state); +} + +uint32_t EmitMeshDrawParameter(ValueEmitContext& ctx, const IR::Inst& inst) { + auto& state = ctx.state; + const auto index = inst.Arg(0).U32(); + if (state.program.stage != ShaderType::Mesh || index >= IR::PushData::MeshDrawDwordCount) { + ctx.Fail(inst, "invalid mesh draw parameter"); + } + return EmitPushDataLoad(state, ConstantU32(state, index)); +} + +uint32_t EmitGetUserData(EmitterState& state, IR::ScalarReg reg) { + + uint32_t dword = 0; + if (!UserDataDwordIndex(state, reg, dword)) { + return ConstantU32(state, 0); + } else { + return EmitShaderDataDwordLoad(state, dword); + } +} + +uint32_t EmitGetBuiltin(ValueEmitContext& ctx, IR::Value kind, IR::Value index) { + return EmitBuiltinU32(ctx.state, static_cast(kind.U32()), index.U32()); +} + +uint32_t EmitGetDispatchThreadExtent(ValueEmitContext& ctx, const IR::Inst& inst) { + const auto start = ctx.state.program.bindings.dispatch_thread_dword; + if (start == IR::PushData::NoStart || !inst.Arg(0).IsImmediate() || inst.Arg(0).U32() >= 3u) { + ctx.Fail(inst, "invalid dispatch thread extent"); + } + return EmitShaderDataDwordLoad(ctx.state, start + inst.Arg(0).U32()); +} + +uint32_t EmitUndefU1(EmitterState& state, const IR::Inst& inst) { + const auto result = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpUndef, TypeId(state, inst.GetType()), result); + return result; +} + +uint32_t EmitDppMoveU32(ValueEmitContext& ctx, const IR::Inst& inst) { + auto& state = ctx.state; + const auto flags = inst.Flags(); + const auto target = EmitDppTargetLane(state, flags); + const auto shuffled = ctx.Shuffle(inst, 0, target.lane); + if (flags.fetch_inactive) { + return shuffled; + } + const auto ballot = ctx.Ballot(inst.Arg(1)); + const auto source_active = EmitBallotLaneActiveBool(state, ballot, target.lane); + const auto can_fetch = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLogicalAnd, TypeBool(state), can_fetch, target.valid, + source_active); + return EmitNative(ctx.state, can_fetch, shuffled, + ConstantU32(state, 0)); +} + +uint32_t EmitDppUpdateU32(ValueEmitContext& ctx, const IR::Inst& inst) { + const auto flags = inst.Flags(); + const auto write = EmitDppWriteCondition(ctx, flags, ctx.Arg(inst, 2)); + return EmitNative(ctx.state, write, ctx.Arg(inst, 0), + ctx.Arg(inst, 1)); +} + +uint32_t EmitConditionRef(ValueEmitContext& ctx, const IR::Inst& inst) { + // Scalar branches include lanes disabled by EXEC, which the branch body may restore. + if (ctx.other_half != nullptr && ctx.half != 0) return ctx.other_half->Result(inst); + const auto kind = inst.Flags(); + if (kind == CFG::BranchCondition::ScalarInstruction) return ctx.Arg(inst, 0); + const bool zero = kind == CFG::BranchCondition::ExecZero || + kind == CFG::BranchCondition::VccZero || kind == CFG::BranchCondition::SccZero; + // Zero-kind predicates are already inverted by translation. + auto predicate = ctx.Arg(inst, 0); + if (ctx.other_half != nullptr) { + predicate = Binary(ctx.state, zero ? spv::OpLogicalAnd : spv::OpLogicalOr, + TypeBool(ctx.state), predicate, ctx.HalfArg(inst, 0, 1)); + } + if (ctx.state.scalar_subgroups) { + return predicate; + } + auto& state = ctx.state; + if (WaveHalvesInHostSubgroup(state)) { + const auto ballot = state.builder.AllocateId(); + const auto tested = zero ? EmitLogicalNotBool(state, predicate) : predicate; + state.builder.AddFunction(spv::OpGroupNonUniformBallot, TypeU32Vector(state, 4), ballot, + ConstantU32(state, spv::ScopeSubgroup), tested); + const auto word = EmitOwnWaveHalfWord(state, ballot); + const auto result = state.builder.AllocateId(); + state.builder.AddFunction(zero ? spv::OpIEqual : spv::OpINotEqual, TypeBool(state), result, + word, ConstantU32(state, 0)); + return result; + } + // Exclude helper invocations from both Any and All without changing the + // identity of the reduction (false for Any, true for All). + if (state.helper_invocation_variable != 0) { + const auto tested = zero ? EmitLogicalNotBool(state, predicate) : predicate; + predicate = EmitLiveInvocationPredicate(state, tested); + if (zero) predicate = EmitLogicalNotBool(state, predicate); + } + const auto result = state.builder.AllocateId(); + state.builder.AddFunction(zero ? spv::OpGroupNonUniformAll : spv::OpGroupNonUniformAny, + TypeBool(state), result, + ConstantU32(state, spv::ScopeSubgroup), predicate); + return result; +} + +uint32_t EmitBallot(ValueEmitContext& ctx, IR::Value predicate) { + return ctx.Ballot(predicate); +} + +uint32_t EmitReadFirstLane(ValueEmitContext& ctx, const IR::Inst& inst) { + if (ctx.state.scalar_subgroups) { + return ctx.Arg(inst, 0); + } + const auto ballot = ctx.Ballot(inst.Arg(1)); + const auto lane = ctx.FirstLane(ballot); + const auto shuffled = ctx.Shuffle(inst, 0, lane); + if (WaveHalvesInHostSubgroup(ctx.state)) { + // Each half is its own guest wave: the value is uniform per half only. + return shuffled; + } + // Every lane now holds the same value, so reading the first active lane changes nothing but + // tells the driver the result is uniform. AMD compiles the shuffle alone to ds_bpermute and + // treats its result as per-lane, which turned everything derived from a waterfall key + // (scalar loads, address math, loop exits) into vector code. + auto& state = ctx.state; + const auto result = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpGroupNonUniformBroadcastFirst, + TypeId(state, inst.Arg(0).GetType()), result, + ConstantU32(state, spv::ScopeSubgroup), shuffled); + return result; +} + +uint32_t EmitReadLane(ValueEmitContext& ctx, const IR::Inst& inst) { + if (ctx.state.scalar_subgroups) { + return ctx.Arg(inst, 0); + } + // V_READLANE's lane is an SGPR or a constant, so the result is uniform too; see + // EmitReadFirstLane. + auto& state = ctx.state; + if (WaveHalvesInHostSubgroup(state)) { + // The lane is the guest wave's (wave32 reads its low 5 bits): offset it into the + // invocation's own half. + const auto lane = + EmitBinaryU32(state, spv::OpBitwiseAnd, ctx.Arg(inst, 1), ConstantU32(state, 31)); + return ctx.Shuffle(inst, 0, + EmitAddU32(state, EmitLaunchedLaneAtOrBelow(state, lane), + EmitOwnWaveHalfBase(state))); + } + const auto shuffled = ctx.Shuffle(inst, 0, EmitLaunchedLaneAtOrBelow(state, ctx.Arg(inst, 1))); + const auto result = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpGroupNonUniformBroadcastFirst, + TypeId(state, inst.Arg(0).GetType()), result, + ConstantU32(state, spv::ScopeSubgroup), shuffled); + return result; +} + +uint32_t EmitSubgroupUMinU32(ValueEmitContext& ctx, const IR::Inst& inst) { + auto& state = ctx.state; + auto value = ctx.Arg(inst, 0); + if (ctx.other_half != nullptr) { + value = EmitUMin32(state, ctx.HalfArg(inst, 0, 0), ctx.HalfArg(inst, 0, 1)); + } + if (state.scalar_subgroups) { + return value; + } + const auto result = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpGroupNonUniformUMin, TypeU32(state), result, + ConstantU32(state, spv::ScopeSubgroup), spv::GroupOperationReduce, value); + return result; +} + +uint32_t EmitWriteLane(ValueEmitContext& ctx, const IR::Inst& inst) { + auto& state = ctx.state; + const auto hit = state.builder.AllocateId(); + const auto lane = WaveHalvesInHostSubgroup(state) + ? EmitBinaryU32(state, spv::OpBitwiseAnd, + EmitSubgroupLocalInvocationId(state), + ConstantU32(state, 31)) + : EmitSubgroupLocalInvocationId(state); + state.builder.AddFunction(spv::OpIEqual, TypeBool(state), hit, lane, ctx.Arg(inst, 2)); + return EmitNative(ctx.state, hit, ctx.Arg(inst, 1), + ctx.Arg(inst, 0)); +} + +uint32_t EmitPermlane16U32(ValueEmitContext& ctx, const IR::Inst& inst) { + auto& state = ctx.state; + const auto flags = inst.Flags(); + const auto subid = EmitSubgroupLocalInvocationId(state); + const auto row = state.builder.AllocateId(); + const auto row_value = state.builder.AllocateId(); + const auto lane = state.builder.AllocateId(); + const auto lane8 = state.builder.AllocateId(); + const auto shift = state.builder.AllocateId(); + const auto upper = state.builder.AllocateId(); + const auto selected = state.builder.AllocateId(); + const auto shifted = state.builder.AllocateId(); + const auto index = state.builder.AllocateId(); + const auto target = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpBitwiseAnd, TypeU32(state), row, subid, + ConstantU32(state, 0xfffffff0u)); + if (flags.x16) { + state.builder.AddFunction(spv::OpBitwiseXor, TypeU32(state), row_value, row, + ConstantU32(state, 16)); + } else { + state.builder.AddFunction(spv::OpCopyObject, TypeU32(state), row_value, row); + } + state.builder.AddFunction(spv::OpBitwiseAnd, TypeU32(state), lane, subid, + ConstantU32(state, 15)); + state.builder.AddFunction(spv::OpBitwiseAnd, TypeU32(state), lane8, lane, + ConstantU32(state, 7)); + state.builder.AddFunction(spv::OpShiftLeftLogical, TypeU32(state), shift, lane8, + ConstantU32(state, 2)); + state.builder.AddFunction(spv::OpUGreaterThanEqual, TypeBool(state), upper, lane, + ConstantU32(state, 8)); + state.builder.AddFunction(spv::OpSelect, TypeU32(state), selected, upper, ctx.Arg(inst, 2), + ctx.Arg(inst, 1)); + state.builder.AddFunction(spv::OpShiftRightLogical, TypeU32(state), shifted, selected, shift); + state.builder.AddFunction(spv::OpBitwiseAnd, TypeU32(state), index, shifted, + ConstantU32(state, 15)); + state.builder.AddFunction(spv::OpBitwiseOr, TypeU32(state), target, row_value, index); + const auto launched = EmitLaunchedLaneAtOrBelow(state, target); + const auto shuffled = ctx.Shuffle(inst, 0, launched); + uint32_t result = shuffled; + if (!flags.fetch_inactive) { + // A lane the host did not launch is active if the guest switched it on, which only the + // scalar EXEC copy records. + const auto in_high = state.builder.AllocateId(); + state.builder.AddFunction( + spv::OpLogicalAnd, TypeBool(state), in_high, + ConstantBool(state, state.program.wave_size == 64u), + Binary(state, spv::OpINotEqual, TypeBool(state), + EmitBinaryU32(state, spv::OpBitwiseAnd, target, ConstantU32(state, 32)), + ConstantU32(state, 0))); + const auto exec_word = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpSelect, TypeU32(state), exec_word, in_high, + ctx.Arg(inst, 5), ctx.Arg(inst, 4)); + const auto exec_bit = EmitBinaryU32( + state, spv::OpBitwiseAnd, + EmitBinaryU32(state, spv::OpShiftRightLogical, exec_word, + EmitBinaryU32(state, spv::OpBitwiseAnd, target, ConstantU32(state, 31))), + ConstantU32(state, 1)); + const auto was_launched = state.builder.AllocateId(); + const auto source_exec = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpIEqual, TypeBool(state), was_launched, launched, target); + state.builder.AddFunction( + spv::OpSelect, TypeBool(state), source_exec, was_launched, ctx.Shuffle(inst, 3, launched), + Binary(state, spv::OpINotEqual, TypeBool(state), exec_bit, ConstantU32(state, 0))); + result = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpSelect, TypeU32(state), result, source_exec, shuffled, + ConstantU32(state, 0)); + } + return result; +} + +uint32_t EmitGetAttribute(ValueEmitContext& ctx, const IR::Inst& inst) { + return EmitAttribute(ctx.state, inst.Arg(0).U32(), inst.Arg(1).U32()); +} + +uint32_t EmitGetInterpolationParameter(ValueEmitContext& ctx, const IR::Inst& inst) { + return EmitInterpolationParameter(ctx, inst.Arg(0).U32(), inst.Arg(1).U32(), inst.Arg(2).U32()); +} + +uint32_t EmitGetShaderBase(ValueEmitContext& ctx) { + // Guest S_GETPC values stay shader-relative in SPIR-V, matching the runtime ABI. The + // runtime descriptor evaluator supplies the mapped shader base for host-side planning. + return ctx.Def(IR::Value(uint64_t {0})); +} + +void EmitUnreachable(ValueEmitContext& ctx, const IR::Inst& inst) { + ctx.Fail(inst, "must be lowered before SPIR-V emission"); +} + +} // namespace Libs::Graphics::ShaderRecompiler::Spirv::Emitter diff --git a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterMesh.cpp b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterMesh.cpp index 2c8f210b..5a280a43 100644 --- a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterMesh.cpp +++ b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterMesh.cpp @@ -1,226 +1,265 @@ -#include "graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h" - -namespace Libs::Graphics::ShaderRecompiler::Spirv::Emitter { -namespace { - -uint32_t MeshArray(EmitterState& state, spv::StorageClass storage, uint32_t type, uint32_t count) { - const auto array = state.builder.Type(spv::OpTypeArray, type, ConstantU32(state, count)); - return state.builder.DefineGlobalVariable(TypePointer(state, storage, array), storage); -} - -uint32_t MeshElement(EmitterState& state, uint32_t variable, spv::StorageClass storage, - uint32_t type, uint32_t index) { - const auto pointer = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpAccessChain, TypePointer(state, storage, type), pointer, - variable, index); - return pointer; -} - -uint32_t MeshLoad(EmitterState& state, uint32_t variable, spv::StorageClass storage, uint32_t type, - uint32_t index) { - const auto pointer = MeshElement(state, variable, storage, type, index); - const auto value = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpLoad, type, value, pointer); - return value; -} - -uint32_t MeshOutputType(EmitterState& state, IR::StageOutputKind kind) { - switch (kind) { - case IR::StageOutputKind::Layer: return TypeU32(state); - case IR::StageOutputKind::ClipDistance: - case IR::StageOutputKind::CullDistance: return TypeF32(state); - case IR::StageOutputKind::Position: - case IR::StageOutputKind::Parameter: return TypeF32Vector(state, 4); - default: EXIT("unsupported mesh output kind=%u\n", static_cast(kind)); - } -} - -} // namespace - -void DefineMeshOutputs(EmitterState& state, uint32_t clip_distance_count, - uint32_t cull_distance_count) { - const auto& mesh = state.input_info.vertex->mesh; - for (auto& output: state.outputs) { - const auto type = MeshOutputType(state, output.kind); - const bool clip = output.kind == IR::StageOutputKind::ClipDistance; - const bool cull = output.kind == IR::StageOutputKind::CullDistance; - auto& variable = clip ? state.clip_distance_variable - : cull ? state.cull_distance_variable : output.variable_id; - if (variable == 0) { - const auto element_type = clip || cull - ? state.builder.Type(spv::OpTypeArray, type, - ConstantU32(state, clip ? clip_distance_count - : cull_distance_count)) - : type; - variable = MeshArray(state, spv::StorageClassOutput, element_type, - output.kind == IR::StageOutputKind::Layer ? mesh.max_primitives - : mesh.max_vertices); - state.interface_variables.push_back(variable); - state.builder.AddName(variable, output.debug_name.c_str()); - if (output.kind == IR::StageOutputKind::Parameter) { - state.builder.AddAnnotation(spv::OpDecorate, variable, - spv::DecorationLocation, output.location); - } else { - const auto builtin = clip ? spv::BuiltInClipDistance - : cull ? spv::BuiltInCullDistance - : output.kind == IR::StageOutputKind::Layer ? spv::BuiltInLayer - : spv::BuiltInPosition; - state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBuiltIn, builtin); - } - if (output.kind == IR::StageOutputKind::Layer) { - state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationPerPrimitiveEXT); - } - } - output.variable_id = variable; - // Only Layer is read by another invocation, through the primitive's provoking vertex. - const bool shared = output.kind == IR::StageOutputKind::Layer; - output.mesh_data_variable = - MeshArray(state, shared ? spv::StorageClassWorkgroup : spv::StorageClassPrivate, type, - shared ? mesh.max_vertices : state.lane_count); - } - state.mesh_allocation = MeshArray(state, spv::StorageClassWorkgroup, TypeU32(state), 2); - state.mesh_primitive_data = - MeshArray(state, spv::StorageClassPrivate, TypeU32(state), state.lane_count); - state.mesh_primitives = - MeshArray(state, spv::StorageClassOutput, TypeU32Vector(state, 3), mesh.max_primitives); - state.mesh_cull = - MeshArray(state, spv::StorageClassOutput, TypeBool(state), mesh.max_primitives); - state.interface_variables.push_back(state.mesh_primitives); - state.interface_variables.push_back(state.mesh_cull); - state.builder.AddAnnotation( - spv::OpDecorate, state.mesh_primitives, spv::DecorationBuiltIn, - spv::BuiltInPrimitiveTriangleIndicesEXT); // PrimitiveTriangleIndicesEXT - state.builder.AddAnnotation(spv::OpDecorate, state.mesh_cull, spv::DecorationBuiltIn, - spv::BuiltInCullPrimitiveEXT); // CullPrimitiveEXT - state.builder.AddAnnotation(spv::OpDecorate, state.mesh_cull, spv::DecorationPerPrimitiveEXT); -} - -uint32_t MeshOutputPointer(EmitterState& state, IR::StageOutputKind kind, uint32_t index) { - const auto output = std::ranges::find_if(state.outputs, [=](const OutputBinding& binding) { - return binding.kind == kind && binding.index == index; - }); - if (output == state.outputs.end()) { - EXIT("mesh export has no output binding: kind=%u index=%u\n", static_cast(kind), - index); - } - const bool shared = kind == IR::StageOutputKind::Layer; - return MeshElement( - state, output->mesh_data_variable, - shared ? spv::StorageClassWorkgroup : spv::StorageClassPrivate, MeshOutputType(state, kind), - shared ? EmitLocalInvocationIndex(state) : ConstantU32(state, state.lane_half)); -} - -uint32_t MeshPrimitivePointer(EmitterState& state) { - return MeshElement(state, state.mesh_primitive_data, spv::StorageClassPrivate, TypeU32(state), - ConstantU32(state, state.lane_half)); -} - -void EmitMeshAllocate(ValueEmitContext& ctx, const IR::Inst& inst) { - auto& state = ctx.state; - const auto first = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpIEqual, TypeBool(state), first, - EmitLocalInvocationIndex(state), ConstantU32(state, 0)); - EmitIfCondition(state, first, [&] { - const auto allocation = ctx.Arg(inst, 0); - for (uint32_t field = 0; field < 2; field++) { - const auto value = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpBitFieldUExtract, TypeU32(state), value, allocation, - ConstantU32(state, field * 12u), - ConstantU32(state, field == 0 ? 10u : 11u)); - const auto pointer = - MeshElement(state, state.mesh_allocation, spv::StorageClassWorkgroup, - TypeU32(state), ConstantU32(state, field)); - state.builder.AddFunction(spv::OpStore, pointer, value); - } - }); -} - -void EmitMeshEntryPoint(EmitterState& state) { - state.builder.AddFunction(spv::OpFunction, TypeVoid(state), state.main_func, - spv::FunctionControlMaskNone, TypeFunction(state)); - EmitLabel(state, state.builder.AllocateId()); - state.builder.AddFunction(spv::OpFunctionCall, TypeVoid(state), state.builder.AllocateId(), - state.mesh_guest_func); - // All guest waves finish before the uniform Vulkan allocation and output stores. - EmitBarrier(state); - const auto vertices = MeshLoad(state, state.mesh_allocation, spv::StorageClassWorkgroup, - TypeU32(state), ConstantU32(state, 0)); - const auto primitives = MeshLoad(state, state.mesh_allocation, spv::StorageClassWorkgroup, - TypeU32(state), ConstantU32(state, 1)); - state.builder.AddFunction(spv::OpSetMeshOutputsEXT, vertices, - primitives); // OpSetMeshOutputsEXT - for (uint32_t half = 0; half < state.lane_count; half++) { - state.lane_half = half; - const auto index = EmitLocalInvocationIndex(state); - const auto is_vertex = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpULessThan, TypeBool(state), is_vertex, index, vertices); - EmitIfCondition(state, is_vertex, [&] { - for (const auto& output: state.outputs) { - if (output.kind == IR::StageOutputKind::Layer) { - continue; - } - const auto type = MeshOutputType(state, output.kind); - const auto value = - MeshLoad(state, output.mesh_data_variable, spv::StorageClassPrivate, type, - ConstantU32(state, half)); - uint32_t pointer; - if (output.kind == IR::StageOutputKind::ClipDistance || - output.kind == IR::StageOutputKind::CullDistance) { - pointer = state.builder.AllocateId(); - state.builder.AddFunction( - spv::OpAccessChain, TypePointer(state, spv::StorageClassOutput, type), pointer, - output.variable_id, index, ConstantU32(state, output.index)); - } else { - pointer = MeshElement(state, output.variable_id, spv::StorageClassOutput, type, index); - } - state.builder.AddFunction(spv::OpStore, pointer, value); - } - }); - const auto is_primitive = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpULessThan, TypeBool(state), is_primitive, index, - primitives); - EmitIfCondition(state, is_primitive, [&] { - const auto packed = MeshLoad(state, state.mesh_primitive_data, spv::StorageClassPrivate, - TypeU32(state), ConstantU32(state, half)); - uint32_t vertex[3] {}; - for (uint32_t component = 0; component < 3; component++) { - vertex[component] = state.builder.AllocateId(); - state.builder.AddFunction( - spv::OpBitFieldUExtract, TypeU32(state), vertex[component], packed, - ConstantU32(state, component * 10u), ConstantU32(state, 10)); - } - const auto triangle = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 3), triangle, - vertex[0], vertex[1], vertex[2]); - const auto triangle_pointer = - MeshElement(state, state.mesh_primitives, spv::StorageClassOutput, - TypeU32Vector(state, 3), index); - state.builder.AddFunction(spv::OpStore, triangle_pointer, triangle); - const auto null_bit = - EmitBinaryU32(state, spv::OpBitwiseAnd, packed, ConstantU32(state, 0x80000000u)); - const auto culled = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpINotEqual, TypeBool(state), culled, null_bit, - ConstantU32(state, 0)); - state.builder.AddFunction(spv::OpStore, - MeshElement(state, state.mesh_cull, spv::StorageClassOutput, - TypeBool(state), index), - culled); - for (const auto& output: state.outputs) { - if (output.kind != IR::StageOutputKind::Layer) { - continue; - } - const auto layer = MeshLoad(state, output.mesh_data_variable, - spv::StorageClassWorkgroup, TypeU32(state), - vertex[state.input_info.vertex->mesh.provoking_vertex]); - const auto pointer = MeshElement(state, output.variable_id, spv::StorageClassOutput, - TypeU32(state), index); - state.builder.AddFunction(spv::OpStore, pointer, layer); - } - }); - } - state.lane_half = 0; - state.builder.AddFunction(spv::OpReturn); - state.builder.AddFunction(spv::OpFunctionEnd); -} - -} // namespace Libs::Graphics::ShaderRecompiler::Spirv::Emitter +#include "graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h" + +namespace Libs::Graphics::ShaderRecompiler::Spirv::Emitter { +namespace { + +uint32_t MeshArray(EmitterState& state, spv::StorageClass storage, uint32_t type, uint32_t count) { + const auto array = state.builder.Type(spv::OpTypeArray, type, ConstantU32(state, count)); + return state.builder.DefineGlobalVariable(TypePointer(state, storage, array), storage); +} + +uint32_t MeshElement(EmitterState& state, uint32_t variable, spv::StorageClass storage, + uint32_t type, uint32_t index) { + const auto pointer = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpAccessChain, TypePointer(state, storage, type), pointer, + variable, index); + return pointer; +} + +uint32_t MeshLoad(EmitterState& state, uint32_t variable, spv::StorageClass storage, uint32_t type, + uint32_t index) { + const auto pointer = MeshElement(state, variable, storage, type, index); + const auto value = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpLoad, type, value, pointer); + return value; +} + +uint32_t MeshOutputType(EmitterState& state, IR::StageOutputKind kind) { + switch (kind) { + case IR::StageOutputKind::Layer: return TypeU32(state); + case IR::StageOutputKind::ClipDistance: + case IR::StageOutputKind::CullDistance: return TypeF32(state); + case IR::StageOutputKind::Position: + case IR::StageOutputKind::Parameter: return TypeF32Vector(state, 4); + default: EXIT("unsupported mesh output kind=%u\n", static_cast(kind)); + } +} + +uint32_t MeshOutputInterfaceComponentCount(const EmitterState& state, + const OutputBinding& output) { + if (output.kind != IR::StageOutputKind::Parameter || + output.index >= state.input_info.vertex->mesh.output_component_count.size()) { + return 4u; + } + const auto components = state.input_info.vertex->mesh.output_component_count[output.index]; + return components >= 1u && components <= 4u ? components : 4u; +} + +uint32_t MeshOutputInterfaceType(EmitterState& state, const OutputBinding& output) { + if (output.kind != IR::StageOutputKind::Parameter) { + return MeshOutputType(state, output.kind); + } + const auto components = MeshOutputInterfaceComponentCount(state, output); + return components == 1u ? TypeF32(state) : TypeF32Vector(state, components); +} + +} // namespace + +void DefineMeshOutputs(EmitterState& state, uint32_t clip_distance_count, + uint32_t cull_distance_count) { + const auto& mesh = state.input_info.vertex->mesh; + for (auto& output: state.outputs) { + const auto type = MeshOutputType(state, output.kind); + const auto interface_type = MeshOutputInterfaceType(state, output); + const bool clip = output.kind == IR::StageOutputKind::ClipDistance; + const bool cull = output.kind == IR::StageOutputKind::CullDistance; + auto& variable = clip ? state.clip_distance_variable + : cull ? state.cull_distance_variable : output.variable_id; + if (variable == 0) { + const auto element_type = clip || cull + ? state.builder.Type(spv::OpTypeArray, type, + ConstantU32(state, clip ? clip_distance_count + : cull_distance_count)) + : interface_type; + variable = MeshArray(state, spv::StorageClassOutput, element_type, + output.kind == IR::StageOutputKind::Layer ? mesh.max_primitives + : mesh.max_vertices); + state.interface_variables.push_back(variable); + state.builder.AddName(variable, output.debug_name.c_str()); + if (output.kind == IR::StageOutputKind::Parameter) { + state.builder.AddAnnotation(spv::OpDecorate, variable, + spv::DecorationLocation, output.location); + } else { + const auto builtin = clip ? spv::BuiltInClipDistance + : cull ? spv::BuiltInCullDistance + : output.kind == IR::StageOutputKind::Layer ? spv::BuiltInLayer + : spv::BuiltInPosition; + state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBuiltIn, builtin); + } + if (output.kind == IR::StageOutputKind::Layer) { + state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationPerPrimitiveEXT); + } + } + output.variable_id = variable; + // Only Layer is read by another invocation, through the primitive's provoking vertex. + const bool shared = output.kind == IR::StageOutputKind::Layer; + output.mesh_data_variable = + MeshArray(state, shared ? spv::StorageClassWorkgroup : spv::StorageClassPrivate, type, + shared ? mesh.max_vertices : state.lane_count); + } + state.mesh_allocation = MeshArray(state, spv::StorageClassWorkgroup, TypeU32(state), 2); + state.mesh_primitive_data = + MeshArray(state, spv::StorageClassPrivate, TypeU32(state), state.lane_count); + state.mesh_primitives = + MeshArray(state, spv::StorageClassOutput, TypeU32Vector(state, 3), mesh.max_primitives); + state.mesh_cull = + MeshArray(state, spv::StorageClassOutput, TypeBool(state), mesh.max_primitives); + state.interface_variables.push_back(state.mesh_primitives); + state.interface_variables.push_back(state.mesh_cull); + state.builder.AddAnnotation( + spv::OpDecorate, state.mesh_primitives, spv::DecorationBuiltIn, + spv::BuiltInPrimitiveTriangleIndicesEXT); // PrimitiveTriangleIndicesEXT + state.builder.AddAnnotation(spv::OpDecorate, state.mesh_cull, spv::DecorationBuiltIn, + spv::BuiltInCullPrimitiveEXT); // CullPrimitiveEXT + state.builder.AddAnnotation(spv::OpDecorate, state.mesh_cull, spv::DecorationPerPrimitiveEXT); +} + +uint32_t MeshOutputPointer(EmitterState& state, IR::StageOutputKind kind, uint32_t index) { + const auto output = std::ranges::find_if(state.outputs, [=](const OutputBinding& binding) { + return binding.kind == kind && binding.index == index; + }); + if (output == state.outputs.end()) { + EXIT("mesh export has no output binding: kind=%u index=%u\n", static_cast(kind), + index); + } + const bool shared = kind == IR::StageOutputKind::Layer; + return MeshElement( + state, output->mesh_data_variable, + shared ? spv::StorageClassWorkgroup : spv::StorageClassPrivate, MeshOutputType(state, kind), + shared ? EmitLocalInvocationIndex(state) : ConstantU32(state, state.lane_half)); +} + +uint32_t MeshPrimitivePointer(EmitterState& state) { + return MeshElement(state, state.mesh_primitive_data, spv::StorageClassPrivate, TypeU32(state), + ConstantU32(state, state.lane_half)); +} + +void EmitMeshAllocate(ValueEmitContext& ctx, const IR::Inst& inst) { + auto& state = ctx.state; + const auto first = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpIEqual, TypeBool(state), first, + EmitLocalInvocationIndex(state), ConstantU32(state, 0)); + EmitIfCondition(state, first, [&] { + const auto allocation = ctx.Arg(inst, 0); + for (uint32_t field = 0; field < 2; field++) { + const auto value = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpBitFieldUExtract, TypeU32(state), value, allocation, + ConstantU32(state, field * 12u), + ConstantU32(state, field == 0 ? 10u : 11u)); + const auto pointer = + MeshElement(state, state.mesh_allocation, spv::StorageClassWorkgroup, + TypeU32(state), ConstantU32(state, field)); + state.builder.AddFunction(spv::OpStore, pointer, value); + } + }); +} + +void EmitMeshEntryPoint(EmitterState& state) { + state.builder.AddFunction(spv::OpFunction, TypeVoid(state), state.main_func, + spv::FunctionControlMaskNone, TypeFunction(state)); + EmitLabel(state, state.builder.AllocateId()); + state.builder.AddFunction(spv::OpFunctionCall, TypeVoid(state), state.builder.AllocateId(), + state.mesh_guest_func); + // All guest waves finish before the uniform Vulkan allocation and output stores. + EmitBarrier(state); + const auto vertices = MeshLoad(state, state.mesh_allocation, spv::StorageClassWorkgroup, + TypeU32(state), ConstantU32(state, 0)); + const auto primitives = MeshLoad(state, state.mesh_allocation, spv::StorageClassWorkgroup, + TypeU32(state), ConstantU32(state, 1)); + state.builder.AddFunction(spv::OpSetMeshOutputsEXT, vertices, + primitives); // OpSetMeshOutputsEXT + for (uint32_t half = 0; half < state.lane_count; half++) { + state.lane_half = half; + const auto index = EmitLocalInvocationIndex(state); + const auto is_vertex = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpULessThan, TypeBool(state), is_vertex, index, vertices); + EmitIfCondition(state, is_vertex, [&] { + for (const auto& output: state.outputs) { + if (output.kind == IR::StageOutputKind::Layer) { + continue; + } + const auto type = MeshOutputType(state, output.kind); + const auto interface_type = MeshOutputInterfaceType(state, output); + const auto value = MeshLoad(state, output.mesh_data_variable, + spv::StorageClassPrivate, type, + ConstantU32(state, half)); + uint32_t output_value = value; + if (output.kind == IR::StageOutputKind::Parameter) { + const auto components = MeshOutputInterfaceComponentCount(state, output); + if (components == 1u) { + output_value = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeExtract, TypeF32(state), + output_value, value, 0u); + } else if (components == 2u) { + output_value = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpVectorShuffle, interface_type, + output_value, value, value, 0u, 1u); + } else if (components == 3u) { + output_value = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpVectorShuffle, interface_type, + output_value, value, value, 0u, 1u, 2u); + } + } + uint32_t pointer; + if (output.kind == IR::StageOutputKind::ClipDistance || + output.kind == IR::StageOutputKind::CullDistance) { + pointer = state.builder.AllocateId(); + state.builder.AddFunction( + spv::OpAccessChain, + TypePointer(state, spv::StorageClassOutput, interface_type), pointer, + output.variable_id, index, ConstantU32(state, output.index)); + } else { + pointer = MeshElement(state, output.variable_id, spv::StorageClassOutput, + interface_type, index); + } + state.builder.AddFunction(spv::OpStore, pointer, output_value); + } + }); + const auto is_primitive = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpULessThan, TypeBool(state), is_primitive, index, + primitives); + EmitIfCondition(state, is_primitive, [&] { + const auto packed = MeshLoad(state, state.mesh_primitive_data, spv::StorageClassPrivate, + TypeU32(state), ConstantU32(state, half)); + uint32_t vertex[3] {}; + for (uint32_t component = 0; component < 3; component++) { + vertex[component] = state.builder.AllocateId(); + state.builder.AddFunction( + spv::OpBitFieldUExtract, TypeU32(state), vertex[component], packed, + ConstantU32(state, component * 10u), ConstantU32(state, 10)); + } + const auto triangle = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpCompositeConstruct, TypeU32Vector(state, 3), triangle, + vertex[0], vertex[1], vertex[2]); + const auto triangle_pointer = + MeshElement(state, state.mesh_primitives, spv::StorageClassOutput, + TypeU32Vector(state, 3), index); + state.builder.AddFunction(spv::OpStore, triangle_pointer, triangle); + const auto null_bit = + EmitBinaryU32(state, spv::OpBitwiseAnd, packed, ConstantU32(state, 0x80000000u)); + const auto culled = state.builder.AllocateId(); + state.builder.AddFunction(spv::OpINotEqual, TypeBool(state), culled, null_bit, + ConstantU32(state, 0)); + state.builder.AddFunction(spv::OpStore, + MeshElement(state, state.mesh_cull, spv::StorageClassOutput, + TypeBool(state), index), + culled); + for (const auto& output: state.outputs) { + if (output.kind != IR::StageOutputKind::Layer) { + continue; + } + const auto layer = MeshLoad(state, output.mesh_data_variable, + spv::StorageClassWorkgroup, TypeU32(state), + vertex[state.input_info.vertex->mesh.provoking_vertex]); + const auto pointer = MeshElement(state, output.variable_id, spv::StorageClassOutput, + TypeU32(state), index); + state.builder.AddFunction(spv::OpStore, pointer, layer); + } + }); + } + state.lane_half = 0; + state.builder.AddFunction(spv::OpReturn); + state.builder.AddFunction(spv::OpFunctionEnd); +} + +} // namespace Libs::Graphics::ShaderRecompiler::Spirv::Emitter diff --git a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp index 1ea88e72..31c849a3 100644 --- a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp +++ b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp @@ -1,883 +1,886 @@ -#include "graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h" - -#include -#include - -namespace Libs::Graphics::ShaderRecompiler::Spirv::Emitter { - -uint32_t TypeVoid(EmitterState& state) { - if (state.void_type == 0) { - state.void_type = state.builder.Type(spv::OpTypeVoid); - } - return state.void_type; -} - -uint32_t TypeBool(EmitterState& state) { - if (state.bool_type == 0) { - state.bool_type = state.builder.Type(spv::OpTypeBool); - } - return state.bool_type; -} - -uint32_t TypeBoolVector(EmitterState& state, uint32_t components) { - auto& type = state.bool_vector_types[components - 2u]; - if (type == 0) { - type = state.builder.Type(spv::OpTypeVector, TypeBool(state), components); - } - return type; -} - -uint32_t TypeU32(EmitterState& state) { - if (state.u32_type == 0) { - state.u32_type = state.builder.Type(spv::OpTypeInt, 32, 0); - } - return state.u32_type; -} - -uint32_t TypeU64(EmitterState& state) { - if (state.u64_type == 0) { - state.builder.RequireCapability(spv::CapabilityInt64); - state.u64_type = state.builder.Type(spv::OpTypeInt, 64, 0); - } - return state.u64_type; -} - -uint32_t TypeU32Pair(EmitterState& state) { - if (state.u32_pair_type == 0) { - const auto element = TypeU32(state); - state.u32_pair_type = state.builder.Type(spv::OpTypeStruct, element, element); - } - return state.u32_pair_type; -} - -uint32_t TypeI32(EmitterState& state) { - if (state.i32_type == 0) { - state.i32_type = state.builder.Type(spv::OpTypeInt, 32, 1); - } - return state.i32_type; -} - -uint32_t TypeI32Pair(EmitterState& state) { - if (state.i32_pair_type == 0) { - const auto element = TypeI32(state); - state.i32_pair_type = state.builder.Type(spv::OpTypeStruct, element, element); - } - return state.i32_pair_type; -} - -uint32_t TypeF32(EmitterState& state) { - if (state.f32_type == 0) { - state.f32_type = state.builder.Type(spv::OpTypeFloat, 32); - } - return state.f32_type; -} - -uint32_t TypeF64(EmitterState& state) { - if (state.f64_type == 0) { - state.f64_type = state.builder.Type(spv::OpTypeFloat, 64); - } - return state.f64_type; -} - -uint32_t TypeU32Vector(EmitterState& state, uint32_t components) { - auto& type = state.u32_vector_types[components - 2u]; - if (type == 0) { - type = state.builder.Type(spv::OpTypeVector, TypeU32(state), components); - } - return type; -} - -uint32_t TypeU32Composite(EmitterState& state, uint32_t components) { - EXIT_IF(components < 1u || components > 4u); - if (components == 1u) return TypeU32(state); - return components == 2u ? TypeU32Pair(state) : TypeU32Vector(state, components); -} - -uint32_t TypeI32Vector(EmitterState& state, uint32_t components) { - auto& type = state.i32_vector_types[components - 2u]; - if (type == 0) { - type = state.builder.Type(spv::OpTypeVector, TypeI32(state), components); - } - return type; -} - -uint32_t TypeF32Vector(EmitterState& state, uint32_t components) { - auto& type = state.f32_vector_types[components - 2u]; - if (type == 0) { - type = state.builder.Type(spv::OpTypeVector, TypeF32(state), components); - } - return type; -} - -uint32_t TypePointer(EmitterState& state, spv::StorageClass storage_class, uint32_t pointee) { - return state.builder.Type(spv::OpTypePointer, storage_class, pointee); -} - -uint32_t TypeFunction(EmitterState& state) { - if (state.function_type == 0) { - state.function_type = state.builder.Type(spv::OpTypeFunction, TypeVoid(state)); - } - return state.function_type; -} - -uint32_t StorageBufferType(EmitterState& state, BufferDefinition& buffer, uint32_t bits = 32) { - if (buffer.type == 0) { - if (bits == 32u) { - buffer.element_type = TypeU32(state); - } else if (bits == 64u) { - buffer.element_type = TypeU64(state); - } else { - buffer.element_type = state.builder.Type(spv::OpTypeInt, bits, 0); - } - const auto array = state.builder.DecoratedType( - spv::OpTypeRuntimeArray, - {{spv::OpDecorate, {spv::DecorationArrayStride, bits / 8u}}}, buffer.element_type); - buffer.type = state.builder.DecoratedType( - spv::OpTypeStruct, {{spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}, - {spv::OpDecorate, {spv::DecorationBlock}}}, array); - } - return buffer.type; -} - -uint32_t TypeStorageBufferElementPointer(EmitterState& state, uint32_t bits) { - auto* buffer = &state.storage_buffers[2]; - if (bits == 8u) { - buffer = &state.storage_buffers[0]; - } else if (bits == 16u) { - buffer = &state.storage_buffers[1]; - } else if (bits == 64u) { - buffer = &state.storage_buffers[3]; - } - if (buffer->element_pointer_type == 0) { - buffer->element_pointer_type = - TypePointer(state, spv::StorageClassStorageBuffer, buffer->element_type); - } - return buffer->element_pointer_type; -} - -uint32_t TypePhysicalU32Pointer(EmitterState& state) { - return TypePointer(state, spv::StorageClassPhysicalStorageBuffer, TypeU32(state)); -} - -uint32_t TypePushConstantElementPointer(EmitterState& state) { - return TypePointer(state, spv::StorageClassPushConstant, TypeU32(state)); -} - -uint32_t TypeU32ArrayPointer(EmitterState& state, spv::StorageClass storage_class, - uint32_t dwords) { - const auto count = ConstantU32(state, std::max(dwords, 1u)); - const auto array = state.builder.Type(spv::OpTypeArray, TypeU32(state), count); - return TypePointer(state, storage_class, array); -} - -uint32_t TypeU32ElementPointer(EmitterState& state, spv::StorageClass storage_class) { - return TypePointer(state, storage_class, TypeU32(state)); -} - -namespace { - -uint32_t PushConstantArrayType(EmitterState& state) { - const auto count = ConstantU32(state, IR::PushData::DwordCount); - return state.builder.DecoratedType( - spv::OpTypeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, sizeof(uint32_t)}}}, - TypeU32(state), count); -} - -uint32_t PushConstantBlockType(EmitterState& state) { - return state.builder.DecoratedType(spv::OpTypeStruct, - {{spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}, - {spv::OpDecorate, {spv::DecorationBlock}}}, - PushConstantArrayType(state)); -} - -uint32_t PerVertexType(EmitterState& state) { - return state.builder.DecoratedType( - spv::OpTypeStruct, - {{spv::OpMemberDecorate, {0, spv::DecorationBuiltIn, spv::BuiltInPosition}}, - {spv::OpDecorate, {spv::DecorationBlock}}}, - TypeF32Vector(state, 4)); -} - -uint32_t SampleMaskArrayType(EmitterState& state) { - return state.builder.Type(spv::OpTypeArray, TypeI32(state), ConstantU32(state, 1)); -} - -uint32_t F32ArrayType(EmitterState& state, uint32_t count) { - return state.builder.Type(spv::OpTypeArray, TypeF32(state), ConstantU32(state, count)); -} - -void DefineDescriptors(EmitterState& state) { - using Kind = IR::DescriptorBindingKind; - auto& info = state.program.info; - auto& bindings = state.program.bindings; - auto& counts = bindings.descriptor_counts; - auto& buffer_count = counts[static_cast(Kind::Buffers)]; - for (auto& buffer: info.buffers) { - buffer.descriptor_index = buffer.live ? buffer_count++ : UINT32_MAX; - } - std::array image_types {}; - for (auto& image: info.images) { - const auto kind = IR::DescriptorBindingForImage(image); - if (!kind.has_value() || image.mip_count == 0u || - (image.mip_mode != IR::ImageMipMode::Dynamic && image.mip_count != 1u)) { - EXIT("shader image has an invalid descriptor type or mip count"); - } - auto& count = counts[static_cast(*kind)]; - image.descriptor_index = count; - if (count == 0) image_types[IR::ImageBindingIndex(*kind)] = ℑ - count += image.mip_count; - } - counts[static_cast(Kind::Samplers)] = static_cast(info.samplers.size()); - counts[static_cast(Kind::Gds)] = info.uses_gds; - counts[static_cast(Kind::SharedMemory)] = - info.uses_lds && state.lds_storage_class == spv::StorageClassStorageBuffer; - counts[static_cast(Kind::BdaPagetable)] = info.uses_dma; - counts[static_cast(Kind::FaultBuffer)] = info.uses_dma; - counts[static_cast(Kind::FlattenedSrt)] = info.uses_flattened_srt; - bindings.memory_offset_dword = static_cast(info.user_data_registers.size()); - if (info.uses_dispatch_threads) { - bindings.dispatch_thread_dword = bindings.memory_offset_dword; - bindings.memory_offset_dword += 3u; - } - bindings.push_data_start_dword = - IR::PushData::StartFor(bindings.push_data_start_dword, bindings.ShaderDataDwords()); - counts[static_cast(Kind::ShaderData)] = - bindings.ShaderDataDwords() != 0 && !bindings.UsesPushData(); - if (state.program.bindings.UsesPushData() || state.program.stage == ShaderType::Mesh || - state.object_primitive_id_variable != 0) { - const auto type = PushConstantBlockType(state); - state.push_constant_variable = state.builder.DefineGlobalVariable( - TypePointer(state, spv::StorageClassPushConstant, type), spv::StorageClassPushConstant); - state.builder.AddName(type, "BufferResource"); - state.builder.AddName(state.push_constant_variable, "vsharp"); - } - for (uint32_t index = 0; index < counts.size(); ++index) { - if (counts[index] == 0) continue; - bindings.descriptor_mask |= uint64_t{1} << index; - const auto kind = static_cast(index); - const auto Define = [&](uint32_t type, const char* name, - spv::StorageClass storage = spv::StorageClassStorageBuffer) { - const auto variable = - state.builder.DefineGlobalVariable(TypePointer(state, storage, type), storage); - state.builder.AddName(variable, name); - state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, 0); - state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, - IR::NativeBinding(state.program.stage, kind)); - return variable; - }; - const auto ArrayType = [&](uint32_t type) { - return state.builder.Type( - spv::OpTypeArray, type, - ConstantU32(state, counts[index])); - }; - switch (kind) { - case IR::DescriptorBindingKind::Buffers: { - const std::array used {info.buffer_u8, info.buffer_u16, true, info.buffer_int64_atomics}; - constexpr std::array names {"buffers_u8", "buffers_u16", "buffers", "buffers_u64"}; - for (uint32_t alias = 0; alias < used.size(); ++alias) { - if (!used[alias]) continue; - auto& buffer = state.storage_buffers[alias]; - const auto type = StorageBufferType(state, buffer, 8u << alias); - buffer.variable = Define(ArrayType(type), names[alias]); - if (info.buffer_u8 || info.buffer_u16 || info.buffer_int64_atomics) { - state.builder.AddAnnotation(spv::OpDecorate, buffer.variable, spv::DecorationAliased); - } - // RDNA2 stores publish to L2 even without GLC; every alias of the buffer - // must participate in visibility for cache-bypassing polling loads. - if (info.coherent_buffers) { - state.builder.AddAnnotation(spv::OpDecorate, buffer.variable, spv::DecorationCoherent); - } - } - break; - } - case IR::DescriptorBindingKind::BdaPagetable: - state.bda_pagetable_variable = - Define(StorageBufferType(state, state.storage_buffers[3], 64), "bda_pagetable"); - break; - case IR::DescriptorBindingKind::FaultBuffer: - state.fault_buffer_variable = - Define(StorageBufferType(state, state.storage_buffers[2]), "fault_buffer"); - break; - case IR::DescriptorBindingKind::ShaderData: - state.shader_data_storage_variable = - Define(StorageBufferType(state, state.storage_buffers[2]), "shader_data"); - break; - case IR::DescriptorBindingKind::FlattenedSrt: - state.flattened_srt_variable = - Define(StorageBufferType(state, state.storage_buffers[2]), "flattened_srt"); - break; - case IR::DescriptorBindingKind::Samplers: - state.sampler_type = state.builder.Type(spv::OpTypeSampler); - state.sampler_pointer_type = TypePointer( - state, spv::StorageClassUniformConstant, state.sampler_type); - state.sampler_variable = Define(ArrayType(state.sampler_type), "samplers", - spv::StorageClassUniformConstant); - break; - case IR::DescriptorBindingKind::Gds: - state.gds_variable = Define(StorageBufferType(state, state.storage_buffers[2]), "gds"); - break; - case IR::DescriptorBindingKind::SharedMemory: - state.lds_variable = Define(StorageBufferType(state, state.storage_buffers[2]), "lds_dwords"); - state.builder.AddAnnotation(spv::OpDecorate, state.lds_variable, spv::DecorationCoherent); - if (state.program.info.shared_int64_atomics) { - state.lds_u64_variable = - Define(StorageBufferType(state, state.storage_buffers[3], 64), "lds_qwords"); - state.builder.AddAnnotation(spv::OpDecorate, state.lds_u64_variable, spv::DecorationCoherent); - for (const auto variable: {state.lds_variable, state.lds_u64_variable}) { - state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationAliased); - } - } - break; - default: { - EXIT_IF(IR::ImageBindingResourceClass(kind) == - IR::ImageResourceClass::None); - const auto& image = *image_types[IR::ImageBindingIndex(kind)]; - const auto name = "image_" + std::to_string(static_cast(kind)); - auto& definition = state.images[IR::ImageBindingIndex(kind)]; - definition.type = ImageType(state, image); - definition.variable = Define(ArrayType(definition.type), name.c_str(), - spv::StorageClassUniformConstant); - definition.pointer_type = TypePointer( - state, spv::StorageClassUniformConstant, definition.type); - if (image.dimension == ImageDimension::Dim1D || - image.dimension == ImageDimension::Dim1DArray) { - state.builder.RequireCapability(image.resource_class == - IR::ImageResourceClass::Sampled - ? spv::CapabilitySampled1D - : spv::CapabilityImage1D); - } - break; - } - } - } -} - -} // namespace - -uint32_t ConstantU32(EmitterState& state, uint32_t value) { - return state.builder.Constant(spv::OpConstant, TypeU32(state), value); -} - -uint32_t ConstantI32(EmitterState& state, int32_t value) { - return state.builder.Constant(spv::OpConstant, TypeI32(state), static_cast(value)); -} - -uint32_t ConstantF32(EmitterState& state, uint32_t bits) { - return state.builder.Constant(spv::OpConstant, TypeF32(state), bits); -} - -uint32_t ConstantF32Value(EmitterState& state, float value) { - return ConstantF32(state, std::bit_cast(value)); -} - -uint32_t ConstantBool(EmitterState& state, bool value) { - return state.builder.Constant(value ? spv::OpConstantTrue : spv::OpConstantFalse, - TypeBool(state)); -} - -uint32_t ConstantU64(EmitterState& state, uint64_t value) { - return state.builder.Constant(spv::OpConstant, TypeU64(state), static_cast(value), - static_cast(value >> 32u)); -} - -uint32_t ConstantU32CompositeZero(EmitterState& state, uint32_t components) { - EXIT_IF(components < 1u || components > 4u); - const auto zero = ConstantU32(state, 0); - if (components == 1u) return zero; - const std::array values {zero, zero, zero, zero}; - return state.builder.Constant(spv::OpConstantComposite, TypeU32Composite(state, components), - std::span(values).first(components)); -} - -uint32_t GlslStd450(EmitterState& state) { - return state.builder.Import("GLSL.std.450"); -} - -VertexInputScalarKind VertexParameterScalarKind(const EmitterState& state, uint32_t location) { - if ((state.program.stage != ShaderType::Vertex && state.program.stage != ShaderType::Local) || - location >= ShaderVertexInputInfo::RES_MAX || - location >= static_cast(state.input_info.vertex->resources_num)) { - return VertexInputScalarKind::Float; - } - - switch (state.input_info.vertex->resources[location].Format()) { - case Prospero::BufferFormat::k8UInt: - case Prospero::BufferFormat::k16UInt: - case Prospero::BufferFormat::k8_8UInt: - case Prospero::BufferFormat::k32UInt: - case Prospero::BufferFormat::k16_16UInt: - case Prospero::BufferFormat::k8_8_8_8UInt: - case Prospero::BufferFormat::k32_32UInt: - case Prospero::BufferFormat::k16_16_16_16UInt: - case Prospero::BufferFormat::k32_32_32UInt: - case Prospero::BufferFormat::k32_32_32_32UInt: return VertexInputScalarKind::Uint; - case Prospero::BufferFormat::k8SInt: - case Prospero::BufferFormat::k16SInt: - case Prospero::BufferFormat::k8_8SInt: - case Prospero::BufferFormat::k32SInt: - case Prospero::BufferFormat::k16_16SInt: - case Prospero::BufferFormat::k8_8_8_8SInt: - case Prospero::BufferFormat::k32_32SInt: - case Prospero::BufferFormat::k16_16_16_16SInt: - case Prospero::BufferFormat::k32_32_32SInt: - case Prospero::BufferFormat::k32_32_32_32SInt: return VertexInputScalarKind::Sint; - default: return VertexInputScalarKind::Float; - } -} - -uint32_t VertexParameterComponentCount(const InputBinding& input) { - return std::clamp(input.component_count, 1u, 4u); -} - -uint32_t VertexParameterScalarType(EmitterState& state, VertexInputScalarKind kind) { - switch (kind) { - case VertexInputScalarKind::Sint: return TypeI32(state); - case VertexInputScalarKind::Uint: return TypeU32(state); - case VertexInputScalarKind::Float: - default: return TypeF32(state); - } -} - -uint32_t DefineInterfaceVariable(EmitterState& state, uint32_t type, spv::StorageClass storage, - const char* name) { - const auto variable = - state.builder.DefineGlobalVariable(TypePointer(state, storage, type), storage); - state.interface_variables.push_back(variable); - state.builder.AddName(variable, name); - return variable; -} - -namespace { - -uint32_t BuiltInForInput(IR::StageInputKind kind) { - switch (kind) { - case IR::StageInputKind::VertexIndex: return spv::BuiltInVertexIndex; - case IR::StageInputKind::InvocationId: return spv::BuiltInInvocationId; - case IR::StageInputKind::PrimitiveId: return spv::BuiltInPrimitiveId; - case IR::StageInputKind::TessCoord: return spv::BuiltInTessCoord; - case IR::StageInputKind::InstanceIndex: return spv::BuiltInInstanceIndex; - case IR::StageInputKind::FragCoord: return spv::BuiltInFragCoord; - case IR::StageInputKind::FrontFacing: return spv::BuiltInFrontFacing; - case IR::StageInputKind::Layer: return spv::BuiltInLayer; - case IR::StageInputKind::SampleId: return spv::BuiltInSampleId; - case IR::StageInputKind::BaryCoordSmooth: return spv::BuiltInBaryCoordKHR; - case IR::StageInputKind::BaryCoordNoPerspective: return spv::BuiltInBaryCoordNoPerspKHR; - case IR::StageInputKind::WorkgroupId: return spv::BuiltInWorkgroupId; - case IR::StageInputKind::NumWorkgroups: return spv::BuiltInNumWorkgroups; - case IR::StageInputKind::LocalInvocationId: return spv::BuiltInLocalInvocationId; - case IR::StageInputKind::LocalInvocationIndex: return spv::BuiltInLocalInvocationIndex; - case IR::StageInputKind::GlobalInvocationId: return spv::BuiltInGlobalInvocationId; - default: return UINT32_MAX; - } -} - -void DefineInputs(EmitterState& state) { - state.inputs.reserve(state.program.info.inputs.size()); - for (const auto& input: state.program.info.inputs) { - state.inputs.push_back({input}); - } - const auto add_builtin = [&](IR::StageInputKind kind, uint32_t components, - const char* name) { - if (std::ranges::none_of(state.inputs, [kind](const InputBinding& input) { - return input.kind == kind; - })) { - state.inputs.push_back({{kind, 0, components, name}}); - } - }; - if (state.program.info.uses_lds && state.lds_storage_class == spv::StorageClassStorageBuffer) { - add_builtin(IR::StageInputKind::WorkgroupId, 3, "gl_WorkGroupID"); - add_builtin(IR::StageInputKind::NumWorkgroups, 3, "gl_NumWorkGroups"); - } - if (state.lane_count == 2) { - add_builtin(IR::StageInputKind::LocalInvocationIndex, 1, "gl_LocalInvocationIndex"); - if (std::ranges::any_of(state.inputs, [](const InputBinding& input) { - return input.kind == IR::StageInputKind::GlobalInvocationId; - })) { - add_builtin(IR::StageInputKind::WorkgroupId, 3, "gl_WorkGroupID"); - } - } - for (auto& input: state.inputs) { - if (state.program.stage == ShaderType::Pixel && - input.kind == IR::StageInputKind::Parameter) { - const auto location = PixelParameterLocation(state, input.location); - const auto alias = std::ranges::find_if(state.inputs, [&](const InputBinding& other) { - return other.kind == IR::StageInputKind::Parameter && other.variable_id != 0 && - PixelParameterLocation(state, other.location) == location; - }); - if (alias != state.inputs.end()) { - EXIT_IF(alias->per_vertex != input.per_vertex); - input.variable_id = alias->variable_id; - continue; - } - } - uint32_t type = TypeU32(state); - switch (input.kind) { - case IR::StageInputKind::VertexIndex: - case IR::StageInputKind::InvocationId: - case IR::StageInputKind::PrimitiveId: - case IR::StageInputKind::InstanceIndex: - case IR::StageInputKind::Layer: - case IR::StageInputKind::SampleId: type = TypeI32(state); break; - case IR::StageInputKind::WorkgroupId: - case IR::StageInputKind::NumWorkgroups: - case IR::StageInputKind::LocalInvocationId: - case IR::StageInputKind::GlobalInvocationId: type = TypeU32Vector(state, 3); break; - case IR::StageInputKind::FragCoord: type = TypeF32Vector(state, 4); break; - case IR::StageInputKind::TessCoord: - case IR::StageInputKind::BaryCoordSmooth: - case IR::StageInputKind::BaryCoordNoPerspective: type = TypeF32Vector(state, 3); break; - case IR::StageInputKind::FrontFacing: type = TypeBool(state); break; - case IR::StageInputKind::Parameter: - if (state.program.stage == ShaderType::Vertex || - state.program.stage == ShaderType::Local) { - type = VertexParameterScalarType( - state, VertexParameterScalarKind(state, input.location)); - const auto components = VertexParameterComponentCount(input); - if (components > 1u) { - type = state.builder.Type(spv::OpTypeVector, type, components); - } - } else if (input.per_vertex) { - type = state.builder.Type(spv::OpTypeArray, TypeF32Vector(state, 4), - ConstantU32(state, 3)); - } else { - type = TypeF32Vector(state, 4); - } - break; - default: break; - } - input.variable_id = - DefineInterfaceVariable(state, type, spv::StorageClassInput, input.debug_name.c_str()); - if (state.program.stage == ShaderType::Pixel && input.kind == IR::StageInputKind::PrimitiveId) { - // Fragment PrimitiveId accepts Tessellation, which the device already enables. - state.builder.RequireCapability(spv::CapabilityTessellation); - state.builder.AddAnnotation(spv::OpDecorate, input.variable_id, spv::DecorationFlat); - } - if (input.kind == IR::StageInputKind::Layer || input.kind == IR::StageInputKind::SampleId) { - state.builder.AddAnnotation(spv::OpDecorate, input.variable_id, spv::DecorationFlat); - } - if (input.kind == IR::StageInputKind::Parameter) { - const auto flat = PixelParameterIsFlat(state, input.location); - if (input.per_vertex) { - state.builder.AddAnnotation(spv::OpDecorate, input.variable_id, - spv::DecorationPerVertexKHR); - } else if (flat) { - state.builder.AddAnnotation(spv::OpDecorate, input.variable_id, - spv::DecorationFlat); - } - if (state.program.stage == ShaderType::Pixel && - state.input_info.pixel->ps_no_perspective && !flat && !input.per_vertex) { - state.builder.AddAnnotation(spv::OpDecorate, input.variable_id, - spv::DecorationNoPerspective); - } - state.builder.AddAnnotation(spv::OpDecorate, input.variable_id, spv::DecorationLocation, - PixelParameterLocation(state, input.location)); - } else if (const auto builtin = BuiltInForInput(input.kind); builtin != UINT32_MAX) { - state.builder.AddAnnotation(spv::OpDecorate, input.variable_id, spv::DecorationBuiltIn, - builtin); - } - } - if (state.program.info.subgroup_local_invocation_id && !state.scalar_subgroups) { - const auto variable = DefineInterfaceVariable(state, TypeU32(state), spv::StorageClassInput, - "gl_SubgroupInvocationID"); - state.subgroup_local_invocation_id_variable = variable; - state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBuiltIn, - spv::BuiltInSubgroupLocalInvocationId); - if (state.program.stage == ShaderType::Pixel) { - state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationFlat); - } - } - if (state.program.stage == ShaderType::Pixel && - (state.program.info.subgroup_ballot || state.program.info.subgroup_vote)) { - const auto variable = DefineInterfaceVariable( - state, TypeBool(state), spv::StorageClassInput, "gl_HelperInvocation"); - state.helper_invocation_variable = variable; - state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBuiltIn, - spv::BuiltInHelperInvocation); - } -} - -void DefineOutputs(EmitterState& state) { - state.outputs.reserve(state.program.info.outputs.size()); - uint32_t clip_distance_count = 0; - uint32_t cull_distance_count = 0; - for (const auto& output: state.program.info.outputs) { - state.outputs.push_back({output}); - if (output.kind == IR::StageOutputKind::ClipDistance) { - clip_distance_count = std::max(clip_distance_count, output.index + 1); - } else if (output.kind == IR::StageOutputKind::CullDistance) { - cull_distance_count = std::max(cull_distance_count, output.index + 1); - } - } - if (state.program.stage == ShaderType::Mesh) { - DefineMeshOutputs(state, clip_distance_count, cull_distance_count); - return; - } - if (state.program.stage == ShaderType::Vertex && clip_distance_count + cull_distance_count < 8u && - std::ranges::any_of(state.outputs, [](const OutputBinding& output) { - return output.kind == IR::StageOutputKind::Position; - })) { - // Reserve one plane for the enabled PA_CL_CLIP_CNTL clipping-error cull. - state.invalid_position_clip_distance = clip_distance_count++; - state.outputs.push_back({{IR::StageOutputKind::ClipDistance, - state.invalid_position_clip_distance, 0, "gl_ClipDistance"}}); - } - const auto BuiltIn = [&](uint32_t& variable, uint32_t type, const char* name, - spv::BuiltIn builtin) { - if (variable == 0) { - variable = DefineInterfaceVariable(state, type, spv::StorageClassOutput, name); - state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBuiltIn, builtin); - } - return variable; - }; - for (auto& binding: state.outputs) { - switch (binding.kind) { - case IR::StageOutputKind::Position: - if (state.per_vertex_variable == 0) { - const auto type = PerVertexType(state); - state.builder.AddName(type, "gl_PerVertex"); - state.per_vertex_variable = DefineInterfaceVariable( - state, type, spv::StorageClassOutput, "outPerVertex"); - } - binding.variable_id = state.per_vertex_variable; - break; - case IR::StageOutputKind::PointSize: - binding.variable_id = BuiltIn(state.point_size_variable, TypeF32(state), - "gl_PointSize", spv::BuiltInPointSize); - break; - case IR::StageOutputKind::ClipDistance: - binding.variable_id = - BuiltIn(state.clip_distance_variable, F32ArrayType(state, clip_distance_count), - "gl_ClipDistance", spv::BuiltInClipDistance); - break; - case IR::StageOutputKind::CullDistance: - binding.variable_id = - BuiltIn(state.cull_distance_variable, F32ArrayType(state, cull_distance_count), - "gl_CullDistance", spv::BuiltInCullDistance); - break; - case IR::StageOutputKind::Layer: - binding.variable_id = - BuiltIn(state.layer_variable, TypeU32(state), "gl_Layer", spv::BuiltInLayer); - break; - case IR::StageOutputKind::ViewportIndex: - binding.variable_id = BuiltIn(state.viewport_index_variable, TypeU32(state), - "gl_ViewportIndex", spv::BuiltInViewportIndex); - break; - case IR::StageOutputKind::Depth: - binding.variable_id = BuiltIn(state.depth_variable, TypeF32(state), "gl_FragDepth", - spv::BuiltInFragDepth); - break; - case IR::StageOutputKind::SampleMask: - binding.variable_id = - BuiltIn(state.sample_mask_variable, SampleMaskArrayType(state), "gl_SampleMask", - spv::BuiltInSampleMask); - break; - case IR::StageOutputKind::ObjectPrimitiveId: - binding.variable_id = DefineInterfaceVariable( - state, TypeU32(state), spv::StorageClassOutput, binding.debug_name.c_str()); - state.object_primitive_id_variable = binding.variable_id; - state.builder.AddAnnotation(spv::OpDecorate, binding.variable_id, - spv::DecorationLocation, binding.location); - break; - case IR::StageOutputKind::Parameter: - case IR::StageOutputKind::Mrt: { - const bool uint_output = - binding.kind == IR::StageOutputKind::Mrt && - state.program.stage == ShaderType::Pixel && - binding.index < std::size(state.input_info.pixel->target_output_mode) && - (state.input_info.pixel->target_output_mode[binding.index] == 7u || - (state.input_info.pixel->target_packed_unorm_mask & (1u << binding.index)) != 0u); - const auto type = uint_output ? TypeU32Vector(state, 4) : TypeF32Vector(state, 4); - binding.variable_id = DefineInterfaceVariable(state, type, spv::StorageClassOutput, - binding.debug_name.c_str()); - const bool dual_source = binding.kind == IR::StageOutputKind::Mrt && - state.program.stage == ShaderType::Pixel && - state.input_info.pixel->dual_source_blending; - EXIT_NOT_IMPLEMENTED(dual_source && binding.index > 1); - state.builder.AddAnnotation(spv::OpDecorate, binding.variable_id, - spv::DecorationLocation, - dual_source ? 0u : binding.location); - if (dual_source) { - state.builder.AddAnnotation(spv::OpDecorate, binding.variable_id, - spv::DecorationIndex, binding.index); - } - break; - } - } - } -} - -} // namespace - -void DefineModule(EmitterState& state) { - state.interface_variables.reserve(state.program.info.inputs.size() + - state.program.info.outputs.size()); - DefineInputs(state); - DefineOutputs(state); - DefineTessellationInterfaces(state); - DefineDescriptors(state); - if (state.program.info.function_lds) { - state.lds_variable = state.builder.AllocateId(); - } - if (state.program.info.function_scratch) { - for (uint32_t half = 0; half < state.lane_count; half++) { - state.scratch_variable[half] = state.builder.AllocateId(); - } - } - state.main_func = state.builder.AllocateId(); - if (state.program.stage == ShaderType::Mesh) { - state.mesh_guest_func = state.builder.AllocateId(); - state.builder.RequireCapability(spv::CapabilityMeshShadingEXT); // MeshShadingEXT - state.builder.RequireExtension("SPV_EXT_mesh_shader"); - state.builder.AddExecutionMode(state.main_func, - spv::ExecutionModeOutputTrianglesEXT); // OutputTrianglesEXT - state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeOutputVertices, - state.input_info.vertex->mesh.max_vertices); - state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeOutputPrimitivesEXT, - state.input_info.vertex->mesh.max_primitives); - } - if (state.program.stage == ShaderType::TessellationControl || - state.program.stage == ShaderType::TessellationEvaluation) { - DefineTessellationExecutionModes(state); - } - state.entry_label = state.builder.AllocateId(); - - state.builder.RequireCapability(spv::CapabilityShader); - state.builder.RequireCapability(spv::CapabilitySignedZeroInfNanPreserve); - if (state.program.info.buffer_u8) { - state.builder.RequireExtension("SPV_KHR_8bit_storage"); - state.builder.RequireCapability(spv::CapabilityStorageBuffer8BitAccess); - } - if (state.program.info.buffer_u16) { - state.builder.RequireCapability(spv::CapabilityStorageBuffer16BitAccess); - } - if (state.program.info.uses_dma) { - state.builder.RequireCapability(spv::CapabilityInt64); - state.builder.RequireCapability(spv::CapabilityPhysicalStorageBufferAddresses); - state.builder.RequireExtension("SPV_KHR_physical_storage_buffer"); - } - if (state.program.info.buffer_int64_atomics || state.program.info.shared_int64_atomics) { - state.builder.RequireCapability(spv::CapabilityInt64); - state.builder.RequireCapability(spv::CapabilityInt64Atomics); - } - if (state.program.info.shared_int64_atomics && - state.lds_storage_class == spv::StorageClassWorkgroup) { - state.builder.RequireVersion(0x00010400u); - state.builder.RequireExtension("SPV_KHR_workgroup_memory_explicit_layout"); - state.builder.RequireCapability(spv::CapabilityWorkgroupMemoryExplicitLayoutKHR); - } - if (state.clip_distance_variable != 0) { - state.builder.RequireCapability(spv::CapabilityClipDistance); - } - if (state.cull_distance_variable != 0) { - state.builder.RequireCapability(spv::CapabilityCullDistance); - } - if (state.layer_variable != 0 || InputVariableForKind(state, IR::StageInputKind::Layer) != 0) { - state.builder.RequireVersion(0x00010500u); - state.builder.RequireCapability(spv::CapabilityShaderLayer); - } - if (state.viewport_index_variable != 0) { - state.builder.RequireVersion(0x00010500u); - state.builder.RequireCapability(spv::CapabilityShaderViewportIndex); - } - if (InputVariableForKind(state, IR::StageInputKind::SampleId) != 0) { - state.builder.RequireCapability(spv::CapabilitySampleRateShading); - } - if (state.program.info.image_gather_extended) { - state.builder.RequireCapability(spv::CapabilityImageGatherExtended); - } - if (state.lane_count == 2 || state.program.info.subgroup_barrier || - state.program.info.subgroup_ballot || state.program.info.subgroup_vote || - state.program.info.subgroup_shuffle || - state.program.info.subgroup_arithmetic || state.program.info.subgroup_local_invocation_id) { - state.builder.RequireCapability(spv::CapabilityGroupNonUniform); - } - if (state.lane_count == 2 || state.program.info.subgroup_ballot) { - state.builder.RequireCapability(spv::CapabilityGroupNonUniformBallot); - } - if (state.program.info.subgroup_vote) { - state.builder.RequireCapability(spv::CapabilityGroupNonUniformVote); - } - if (state.program.info.subgroup_shuffle) { - state.builder.RequireCapability(spv::CapabilityGroupNonUniformShuffle); - } - if (state.program.info.subgroup_arithmetic) { - state.builder.RequireCapability(spv::CapabilityGroupNonUniformArithmetic); - } - if (state.program.info.compute_derivatives && state.program.stage == ShaderType::Compute) { - state.builder.RequireCapability(spv::CapabilityComputeDerivativeGroupQuadsKHR); - state.builder.RequireExtension("SPV_KHR_compute_shader_derivatives"); - } - const bool fragment_barycentric = - state.program.stage == ShaderType::Pixel && - std::any_of(state.inputs.begin(), state.inputs.end(), [](const InputBinding& input) { - return input.per_vertex || input.kind == IR::StageInputKind::BaryCoordSmooth || - input.kind == IR::StageInputKind::BaryCoordNoPerspective; - }); - if (fragment_barycentric) { - state.builder.RequireCapability(spv::CapabilityFragmentBarycentricKHR); - state.builder.RequireExtension("SPV_KHR_fragment_shader_barycentric"); - } - state.builder.RequireExtension("SPV_KHR_float_controls"); - state.builder.AddMemoryModel(state.program.info.uses_dma - ? spv::AddressingModelPhysicalStorageBuffer64 - : spv::AddressingModelLogical, - spv::MemoryModelGLSL450); - // GCN/RDNA arithmetic preserves 32-bit signed zero, infinity, and NaN. Declaring that - // contract prevents host compilers from treating synthesized IEEE values as finite. - state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeSignedZeroInfNanPreserve, - 32u); - if (state.program.info.float64) { - EXIT_NOT_IMPLEMENTED(state.program.stage == ShaderType::Compute && - state.input_info.compute->float_mode != 0xc0); - // Use native rounding for MODE=0xc0, consistent with ordinary FP32 arithmetic. - state.builder.RequireCapability(spv::CapabilityFloat64); - state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeSignedZeroInfNanPreserve, - 64u); - // FP64 denormal preservation is temporarily disabled. - // state.builder.RequireCapability(spv::CapabilityDenormPreserve); - // state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeDenormPreserve, 64u); - } - if (const auto* cs = ShaderWorkgroupInput(state.program.stage, state.input_info)) { - uint32_t local_x = state.program.info.compute_derivatives ? 2u : 1u; - uint32_t local_y = state.program.info.compute_derivatives ? 2u : 1u; - uint32_t local_z = 1u; - local_x = cs->threads_num[0] != 0u ? cs->threads_num[0] : local_x; - local_y = cs->threads_num[1] != 0u ? cs->threads_num[1] : local_y; - local_z = cs->threads_num[2] != 0u ? cs->threads_num[2] : local_z; - if (state.lane_count == 2) { - local_x = ((local_x * local_y * local_z + 63u) / 64u) * 32u; - local_y = local_z = 1u; - if (state.program.info.compute_derivatives) { - local_y = local_x / 2u; - local_x = 2u; - } - } - state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeLocalSize, local_x, - local_y, local_z); - } - if (state.program.stage == ShaderType::Pixel) { - state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeOriginUpperLeft); - if (state.depth_variable != 0) { - state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeDepthReplacing); - } - if (state.input_info.pixel->ps_early_z && !state.input_info.pixel->ps_pixel_kill_enable && - !state.input_info.pixel->ps_depth_export_enable && - !state.input_info.pixel->ps_sample_mask_export_enable) { - state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeEarlyFragmentTests); - } - } - if (state.program.info.compute_derivatives && state.program.stage == ShaderType::Compute) { - state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeDerivativeGroupQuadsKHR); - } - state.builder.AddName(state.main_func, "main"); - if (state.program.info.function_lds) { - state.builder.AddName(state.lds_variable, "lds_dwords"); - } - if (state.program.info.function_scratch) { - for (uint32_t half = 0; half < state.lane_count; half++) { - state.builder.AddName(state.scratch_variable[half], "scratch_dwords"); - } - } -} - -} // namespace Libs::Graphics::ShaderRecompiler::Spirv::Emitter +#include "graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h" + +#include +#include + +namespace Libs::Graphics::ShaderRecompiler::Spirv::Emitter { + +uint32_t TypeVoid(EmitterState& state) { + if (state.void_type == 0) { + state.void_type = state.builder.Type(spv::OpTypeVoid); + } + return state.void_type; +} + +uint32_t TypeBool(EmitterState& state) { + if (state.bool_type == 0) { + state.bool_type = state.builder.Type(spv::OpTypeBool); + } + return state.bool_type; +} + +uint32_t TypeBoolVector(EmitterState& state, uint32_t components) { + auto& type = state.bool_vector_types[components - 2u]; + if (type == 0) { + type = state.builder.Type(spv::OpTypeVector, TypeBool(state), components); + } + return type; +} + +uint32_t TypeU32(EmitterState& state) { + if (state.u32_type == 0) { + state.u32_type = state.builder.Type(spv::OpTypeInt, 32, 0); + } + return state.u32_type; +} + +uint32_t TypeU64(EmitterState& state) { + if (state.u64_type == 0) { + state.builder.RequireCapability(spv::CapabilityInt64); + state.u64_type = state.builder.Type(spv::OpTypeInt, 64, 0); + } + return state.u64_type; +} + +uint32_t TypeU32Pair(EmitterState& state) { + if (state.u32_pair_type == 0) { + const auto element = TypeU32(state); + state.u32_pair_type = state.builder.Type(spv::OpTypeStruct, element, element); + } + return state.u32_pair_type; +} + +uint32_t TypeI32(EmitterState& state) { + if (state.i32_type == 0) { + state.i32_type = state.builder.Type(spv::OpTypeInt, 32, 1); + } + return state.i32_type; +} + +uint32_t TypeI32Pair(EmitterState& state) { + if (state.i32_pair_type == 0) { + const auto element = TypeI32(state); + state.i32_pair_type = state.builder.Type(spv::OpTypeStruct, element, element); + } + return state.i32_pair_type; +} + +uint32_t TypeF32(EmitterState& state) { + if (state.f32_type == 0) { + state.f32_type = state.builder.Type(spv::OpTypeFloat, 32); + } + return state.f32_type; +} + +uint32_t TypeF64(EmitterState& state) { + if (state.f64_type == 0) { + state.f64_type = state.builder.Type(spv::OpTypeFloat, 64); + } + return state.f64_type; +} + +uint32_t TypeU32Vector(EmitterState& state, uint32_t components) { + auto& type = state.u32_vector_types[components - 2u]; + if (type == 0) { + type = state.builder.Type(spv::OpTypeVector, TypeU32(state), components); + } + return type; +} + +uint32_t TypeU32Composite(EmitterState& state, uint32_t components) { + EXIT_IF(components < 1u || components > 4u); + if (components == 1u) return TypeU32(state); + return components == 2u ? TypeU32Pair(state) : TypeU32Vector(state, components); +} + +uint32_t TypeI32Vector(EmitterState& state, uint32_t components) { + auto& type = state.i32_vector_types[components - 2u]; + if (type == 0) { + type = state.builder.Type(spv::OpTypeVector, TypeI32(state), components); + } + return type; +} + +uint32_t TypeF32Vector(EmitterState& state, uint32_t components) { + auto& type = state.f32_vector_types[components - 2u]; + if (type == 0) { + type = state.builder.Type(spv::OpTypeVector, TypeF32(state), components); + } + return type; +} + +uint32_t TypePointer(EmitterState& state, spv::StorageClass storage_class, uint32_t pointee) { + return state.builder.Type(spv::OpTypePointer, storage_class, pointee); +} + +uint32_t TypeFunction(EmitterState& state) { + if (state.function_type == 0) { + state.function_type = state.builder.Type(spv::OpTypeFunction, TypeVoid(state)); + } + return state.function_type; +} + +uint32_t StorageBufferType(EmitterState& state, BufferDefinition& buffer, uint32_t bits = 32) { + if (buffer.type == 0) { + if (bits == 32u) { + buffer.element_type = TypeU32(state); + } else if (bits == 64u) { + buffer.element_type = TypeU64(state); + } else { + buffer.element_type = state.builder.Type(spv::OpTypeInt, bits, 0); + } + const auto array = state.builder.DecoratedType( + spv::OpTypeRuntimeArray, + {{spv::OpDecorate, {spv::DecorationArrayStride, bits / 8u}}}, buffer.element_type); + buffer.type = state.builder.DecoratedType( + spv::OpTypeStruct, {{spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}, + {spv::OpDecorate, {spv::DecorationBlock}}}, array); + } + return buffer.type; +} + +uint32_t TypeStorageBufferElementPointer(EmitterState& state, uint32_t bits) { + auto* buffer = &state.storage_buffers[2]; + if (bits == 8u) { + buffer = &state.storage_buffers[0]; + } else if (bits == 16u) { + buffer = &state.storage_buffers[1]; + } else if (bits == 64u) { + buffer = &state.storage_buffers[3]; + } + if (buffer->element_pointer_type == 0) { + buffer->element_pointer_type = + TypePointer(state, spv::StorageClassStorageBuffer, buffer->element_type); + } + return buffer->element_pointer_type; +} + +uint32_t TypePhysicalU32Pointer(EmitterState& state) { + return TypePointer(state, spv::StorageClassPhysicalStorageBuffer, TypeU32(state)); +} + +uint32_t TypePushConstantElementPointer(EmitterState& state) { + return TypePointer(state, spv::StorageClassPushConstant, TypeU32(state)); +} + +uint32_t TypeU32ArrayPointer(EmitterState& state, spv::StorageClass storage_class, + uint32_t dwords) { + const auto count = ConstantU32(state, std::max(dwords, 1u)); + const auto array = state.builder.Type(spv::OpTypeArray, TypeU32(state), count); + return TypePointer(state, storage_class, array); +} + +uint32_t TypeU32ElementPointer(EmitterState& state, spv::StorageClass storage_class) { + return TypePointer(state, storage_class, TypeU32(state)); +} + +namespace { + +uint32_t PushConstantArrayType(EmitterState& state) { + const auto count = ConstantU32(state, IR::PushData::DwordCount); + return state.builder.DecoratedType( + spv::OpTypeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, sizeof(uint32_t)}}}, + TypeU32(state), count); +} + +uint32_t PushConstantBlockType(EmitterState& state) { + return state.builder.DecoratedType(spv::OpTypeStruct, + {{spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}, + {spv::OpDecorate, {spv::DecorationBlock}}}, + PushConstantArrayType(state)); +} + +uint32_t PerVertexType(EmitterState& state) { + return state.builder.DecoratedType( + spv::OpTypeStruct, + {{spv::OpMemberDecorate, {0, spv::DecorationBuiltIn, spv::BuiltInPosition}}, + {spv::OpDecorate, {spv::DecorationBlock}}}, + TypeF32Vector(state, 4)); +} + +uint32_t SampleMaskArrayType(EmitterState& state) { + return state.builder.Type(spv::OpTypeArray, TypeI32(state), ConstantU32(state, 1)); +} + +uint32_t F32ArrayType(EmitterState& state, uint32_t count) { + return state.builder.Type(spv::OpTypeArray, TypeF32(state), ConstantU32(state, count)); +} + +void DefineDescriptors(EmitterState& state) { + using Kind = IR::DescriptorBindingKind; + auto& info = state.program.info; + auto& bindings = state.program.bindings; + auto& counts = bindings.descriptor_counts; + auto& buffer_count = counts[static_cast(Kind::Buffers)]; + for (auto& buffer: info.buffers) { + buffer.descriptor_index = buffer.live ? buffer_count++ : UINT32_MAX; + } + std::array image_types {}; + for (auto& image: info.images) { + const auto kind = IR::DescriptorBindingForImage(image); + if (!kind.has_value() || image.mip_count == 0u || + (image.mip_mode != IR::ImageMipMode::Dynamic && image.mip_count != 1u)) { + EXIT("shader image has an invalid descriptor type or mip count"); + } + auto& count = counts[static_cast(*kind)]; + image.descriptor_index = count; + if (count == 0) image_types[IR::ImageBindingIndex(*kind)] = ℑ + count += image.mip_count; + } + counts[static_cast(Kind::Samplers)] = static_cast(info.samplers.size()); + counts[static_cast(Kind::Gds)] = info.uses_gds; + counts[static_cast(Kind::SharedMemory)] = + info.uses_lds && state.lds_storage_class == spv::StorageClassStorageBuffer; + counts[static_cast(Kind::BdaPagetable)] = info.uses_dma; + counts[static_cast(Kind::FaultBuffer)] = info.uses_dma; + counts[static_cast(Kind::FlattenedSrt)] = info.uses_flattened_srt; + bindings.memory_offset_dword = static_cast(info.user_data_registers.size()); + if (info.uses_dispatch_threads) { + bindings.dispatch_thread_dword = bindings.memory_offset_dword; + bindings.memory_offset_dword += 3u; + } + bindings.push_data_start_dword = + IR::PushData::StartFor(bindings.push_data_start_dword, bindings.ShaderDataDwords()); + counts[static_cast(Kind::ShaderData)] = + bindings.ShaderDataDwords() != 0 && !bindings.UsesPushData(); + if (state.program.bindings.UsesPushData() || state.program.stage == ShaderType::Mesh || + state.object_primitive_id_variable != 0) { + const auto type = PushConstantBlockType(state); + state.push_constant_variable = state.builder.DefineGlobalVariable( + TypePointer(state, spv::StorageClassPushConstant, type), spv::StorageClassPushConstant); + state.builder.AddName(type, "BufferResource"); + state.builder.AddName(state.push_constant_variable, "vsharp"); + } + for (uint32_t index = 0; index < counts.size(); ++index) { + if (counts[index] == 0) continue; + bindings.descriptor_mask |= uint64_t{1} << index; + const auto kind = static_cast(index); + const auto Define = [&](uint32_t type, const char* name, + spv::StorageClass storage = spv::StorageClassStorageBuffer) { + const auto variable = + state.builder.DefineGlobalVariable(TypePointer(state, storage, type), storage); + state.builder.AddName(variable, name); + state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, 0); + state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, + IR::NativeBinding(state.program.stage, kind)); + return variable; + }; + const auto ArrayType = [&](uint32_t type) { + return state.builder.Type( + spv::OpTypeArray, type, + ConstantU32(state, counts[index])); + }; + switch (kind) { + case IR::DescriptorBindingKind::Buffers: { + const std::array used {info.buffer_u8, info.buffer_u16, true, info.buffer_int64_atomics}; + constexpr std::array names {"buffers_u8", "buffers_u16", "buffers", "buffers_u64"}; + for (uint32_t alias = 0; alias < used.size(); ++alias) { + if (!used[alias]) continue; + auto& buffer = state.storage_buffers[alias]; + const auto type = StorageBufferType(state, buffer, 8u << alias); + buffer.variable = Define(ArrayType(type), names[alias]); + if (info.buffer_u8 || info.buffer_u16 || info.buffer_int64_atomics) { + state.builder.AddAnnotation(spv::OpDecorate, buffer.variable, spv::DecorationAliased); + } + // RDNA2 stores publish to L2 even without GLC; every alias of the buffer + // must participate in visibility for cache-bypassing polling loads. + if (info.coherent_buffers) { + state.builder.AddAnnotation(spv::OpDecorate, buffer.variable, spv::DecorationCoherent); + } + } + break; + } + case IR::DescriptorBindingKind::BdaPagetable: + state.bda_pagetable_variable = + Define(StorageBufferType(state, state.storage_buffers[3], 64), "bda_pagetable"); + break; + case IR::DescriptorBindingKind::FaultBuffer: + state.fault_buffer_variable = + Define(StorageBufferType(state, state.storage_buffers[2]), "fault_buffer"); + break; + case IR::DescriptorBindingKind::ShaderData: + state.shader_data_storage_variable = + Define(StorageBufferType(state, state.storage_buffers[2]), "shader_data"); + break; + case IR::DescriptorBindingKind::FlattenedSrt: + state.flattened_srt_variable = + Define(StorageBufferType(state, state.storage_buffers[2]), "flattened_srt"); + break; + case IR::DescriptorBindingKind::Samplers: + state.sampler_type = state.builder.Type(spv::OpTypeSampler); + state.sampler_pointer_type = TypePointer( + state, spv::StorageClassUniformConstant, state.sampler_type); + state.sampler_variable = Define(ArrayType(state.sampler_type), "samplers", + spv::StorageClassUniformConstant); + break; + case IR::DescriptorBindingKind::Gds: + state.gds_variable = Define(StorageBufferType(state, state.storage_buffers[2]), "gds"); + break; + case IR::DescriptorBindingKind::SharedMemory: + state.lds_variable = Define(StorageBufferType(state, state.storage_buffers[2]), "lds_dwords"); + state.builder.AddAnnotation(spv::OpDecorate, state.lds_variable, spv::DecorationCoherent); + if (state.program.info.shared_int64_atomics) { + state.lds_u64_variable = + Define(StorageBufferType(state, state.storage_buffers[3], 64), "lds_qwords"); + state.builder.AddAnnotation(spv::OpDecorate, state.lds_u64_variable, spv::DecorationCoherent); + for (const auto variable: {state.lds_variable, state.lds_u64_variable}) { + state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationAliased); + } + } + break; + default: { + EXIT_IF(IR::ImageBindingResourceClass(kind) == + IR::ImageResourceClass::None); + const auto& image = *image_types[IR::ImageBindingIndex(kind)]; + const auto name = "image_" + std::to_string(static_cast(kind)); + auto& definition = state.images[IR::ImageBindingIndex(kind)]; + definition.type = ImageType(state, image); + definition.variable = Define(ArrayType(definition.type), name.c_str(), + spv::StorageClassUniformConstant); + definition.pointer_type = TypePointer( + state, spv::StorageClassUniformConstant, definition.type); + if (image.dimension == ImageDimension::Dim1D || + image.dimension == ImageDimension::Dim1DArray) { + state.builder.RequireCapability(image.resource_class == + IR::ImageResourceClass::Sampled + ? spv::CapabilitySampled1D + : spv::CapabilityImage1D); + } + break; + } + } + } +} + +} // namespace + +uint32_t ConstantU32(EmitterState& state, uint32_t value) { + return state.builder.Constant(spv::OpConstant, TypeU32(state), value); +} + +uint32_t ConstantI32(EmitterState& state, int32_t value) { + return state.builder.Constant(spv::OpConstant, TypeI32(state), static_cast(value)); +} + +uint32_t ConstantF32(EmitterState& state, uint32_t bits) { + return state.builder.Constant(spv::OpConstant, TypeF32(state), bits); +} + +uint32_t ConstantF32Value(EmitterState& state, float value) { + return ConstantF32(state, std::bit_cast(value)); +} + +uint32_t ConstantBool(EmitterState& state, bool value) { + return state.builder.Constant(value ? spv::OpConstantTrue : spv::OpConstantFalse, + TypeBool(state)); +} + +uint32_t ConstantU64(EmitterState& state, uint64_t value) { + return state.builder.Constant(spv::OpConstant, TypeU64(state), static_cast(value), + static_cast(value >> 32u)); +} + +uint32_t ConstantU32CompositeZero(EmitterState& state, uint32_t components) { + EXIT_IF(components < 1u || components > 4u); + const auto zero = ConstantU32(state, 0); + if (components == 1u) return zero; + const std::array values {zero, zero, zero, zero}; + return state.builder.Constant(spv::OpConstantComposite, TypeU32Composite(state, components), + std::span(values).first(components)); +} + +uint32_t GlslStd450(EmitterState& state) { + return state.builder.Import("GLSL.std.450"); +} + +VertexInputScalarKind VertexParameterScalarKind(const EmitterState& state, uint32_t location) { + if ((state.program.stage != ShaderType::Vertex && state.program.stage != ShaderType::Local) || + location >= ShaderVertexInputInfo::RES_MAX || + location >= static_cast(state.input_info.vertex->resources_num)) { + return VertexInputScalarKind::Float; + } + + switch (state.input_info.vertex->resources[location].Format()) { + case Prospero::BufferFormat::k8UInt: + case Prospero::BufferFormat::k16UInt: + case Prospero::BufferFormat::k8_8UInt: + case Prospero::BufferFormat::k32UInt: + case Prospero::BufferFormat::k16_16UInt: + case Prospero::BufferFormat::k8_8_8_8UInt: + case Prospero::BufferFormat::k32_32UInt: + case Prospero::BufferFormat::k16_16_16_16UInt: + case Prospero::BufferFormat::k32_32_32UInt: + case Prospero::BufferFormat::k32_32_32_32UInt: return VertexInputScalarKind::Uint; + case Prospero::BufferFormat::k8SInt: + case Prospero::BufferFormat::k16SInt: + case Prospero::BufferFormat::k8_8SInt: + case Prospero::BufferFormat::k32SInt: + case Prospero::BufferFormat::k16_16SInt: + case Prospero::BufferFormat::k8_8_8_8SInt: + case Prospero::BufferFormat::k32_32SInt: + case Prospero::BufferFormat::k16_16_16_16SInt: + case Prospero::BufferFormat::k32_32_32SInt: + case Prospero::BufferFormat::k32_32_32_32SInt: return VertexInputScalarKind::Sint; + default: return VertexInputScalarKind::Float; + } +} + +uint32_t VertexParameterComponentCount(const InputBinding& input) { + return std::clamp(input.component_count, 1u, 4u); +} + +uint32_t VertexParameterScalarType(EmitterState& state, VertexInputScalarKind kind) { + switch (kind) { + case VertexInputScalarKind::Sint: return TypeI32(state); + case VertexInputScalarKind::Uint: return TypeU32(state); + case VertexInputScalarKind::Float: + default: return TypeF32(state); + } +} + +uint32_t DefineInterfaceVariable(EmitterState& state, uint32_t type, spv::StorageClass storage, + const char* name) { + const auto variable = + state.builder.DefineGlobalVariable(TypePointer(state, storage, type), storage); + state.interface_variables.push_back(variable); + state.builder.AddName(variable, name); + return variable; +} + +namespace { + +uint32_t BuiltInForInput(IR::StageInputKind kind) { + switch (kind) { + case IR::StageInputKind::VertexIndex: return spv::BuiltInVertexIndex; + case IR::StageInputKind::InvocationId: return spv::BuiltInInvocationId; + case IR::StageInputKind::PrimitiveId: return spv::BuiltInPrimitiveId; + case IR::StageInputKind::TessCoord: return spv::BuiltInTessCoord; + case IR::StageInputKind::InstanceIndex: return spv::BuiltInInstanceIndex; + case IR::StageInputKind::FragCoord: return spv::BuiltInFragCoord; + case IR::StageInputKind::FrontFacing: return spv::BuiltInFrontFacing; + case IR::StageInputKind::Layer: return spv::BuiltInLayer; + case IR::StageInputKind::SampleId: return spv::BuiltInSampleId; + case IR::StageInputKind::BaryCoordSmooth: return spv::BuiltInBaryCoordKHR; + case IR::StageInputKind::BaryCoordNoPerspective: return spv::BuiltInBaryCoordNoPerspKHR; + case IR::StageInputKind::WorkgroupId: return spv::BuiltInWorkgroupId; + case IR::StageInputKind::NumWorkgroups: return spv::BuiltInNumWorkgroups; + case IR::StageInputKind::LocalInvocationId: return spv::BuiltInLocalInvocationId; + case IR::StageInputKind::LocalInvocationIndex: return spv::BuiltInLocalInvocationIndex; + case IR::StageInputKind::GlobalInvocationId: return spv::BuiltInGlobalInvocationId; + default: return UINT32_MAX; + } +} + +void DefineInputs(EmitterState& state) { + state.inputs.reserve(state.program.info.inputs.size()); + for (const auto& input: state.program.info.inputs) { + state.inputs.push_back({input}); + } + const auto add_builtin = [&](IR::StageInputKind kind, uint32_t components, + const char* name) { + if (std::ranges::none_of(state.inputs, [kind](const InputBinding& input) { + return input.kind == kind; + })) { + state.inputs.push_back({{kind, 0, components, name}}); + } + }; + if (state.program.info.uses_lds && state.lds_storage_class == spv::StorageClassStorageBuffer) { + add_builtin(IR::StageInputKind::WorkgroupId, 3, "gl_WorkGroupID"); + add_builtin(IR::StageInputKind::NumWorkgroups, 3, "gl_NumWorkGroups"); + } + if (state.lane_count == 2) { + add_builtin(IR::StageInputKind::LocalInvocationIndex, 1, "gl_LocalInvocationIndex"); + if (std::ranges::any_of(state.inputs, [](const InputBinding& input) { + return input.kind == IR::StageInputKind::GlobalInvocationId; + })) { + add_builtin(IR::StageInputKind::WorkgroupId, 3, "gl_WorkGroupID"); + } + } + for (auto& input: state.inputs) { + if (state.program.stage == ShaderType::Pixel && + input.kind == IR::StageInputKind::Parameter) { + const auto location = PixelParameterLocation(state, input.location); + const auto alias = std::ranges::find_if(state.inputs, [&](const InputBinding& other) { + return other.kind == IR::StageInputKind::Parameter && other.variable_id != 0 && + PixelParameterLocation(state, other.location) == location; + }); + if (alias != state.inputs.end()) { + EXIT_IF(alias->per_vertex != input.per_vertex); + input.variable_id = alias->variable_id; + continue; + } + } + uint32_t type = TypeU32(state); + switch (input.kind) { + case IR::StageInputKind::VertexIndex: + case IR::StageInputKind::InvocationId: + case IR::StageInputKind::PrimitiveId: + case IR::StageInputKind::InstanceIndex: + case IR::StageInputKind::Layer: + case IR::StageInputKind::SampleId: type = TypeI32(state); break; + case IR::StageInputKind::WorkgroupId: + case IR::StageInputKind::NumWorkgroups: + case IR::StageInputKind::LocalInvocationId: + case IR::StageInputKind::GlobalInvocationId: type = TypeU32Vector(state, 3); break; + case IR::StageInputKind::FragCoord: type = TypeF32Vector(state, 4); break; + case IR::StageInputKind::TessCoord: + case IR::StageInputKind::BaryCoordSmooth: + case IR::StageInputKind::BaryCoordNoPerspective: type = TypeF32Vector(state, 3); break; + case IR::StageInputKind::FrontFacing: type = TypeBool(state); break; + case IR::StageInputKind::Parameter: + if (state.program.stage == ShaderType::Vertex || + state.program.stage == ShaderType::Local) { + type = VertexParameterScalarType( + state, VertexParameterScalarKind(state, input.location)); + const auto components = VertexParameterComponentCount(input); + if (components > 1u) { + type = state.builder.Type(spv::OpTypeVector, type, components); + } + } else { + const auto components = std::clamp(input.component_count, 1u, 4u); + const auto parameter_type = + components == 1u ? TypeF32(state) : TypeF32Vector(state, components); + type = input.per_vertex + ? state.builder.Type(spv::OpTypeArray, parameter_type, + ConstantU32(state, 3)) + : parameter_type; + } + break; + default: break; + } + input.variable_id = + DefineInterfaceVariable(state, type, spv::StorageClassInput, input.debug_name.c_str()); + if (state.program.stage == ShaderType::Pixel && input.kind == IR::StageInputKind::PrimitiveId) { + // Fragment PrimitiveId accepts Tessellation, which the device already enables. + state.builder.RequireCapability(spv::CapabilityTessellation); + state.builder.AddAnnotation(spv::OpDecorate, input.variable_id, spv::DecorationFlat); + } + if (input.kind == IR::StageInputKind::Layer || input.kind == IR::StageInputKind::SampleId) { + state.builder.AddAnnotation(spv::OpDecorate, input.variable_id, spv::DecorationFlat); + } + if (input.kind == IR::StageInputKind::Parameter) { + const auto flat = PixelParameterIsFlat(state, input.location); + if (input.per_vertex) { + state.builder.AddAnnotation(spv::OpDecorate, input.variable_id, + spv::DecorationPerVertexKHR); + } else if (flat) { + state.builder.AddAnnotation(spv::OpDecorate, input.variable_id, + spv::DecorationFlat); + } + if (state.program.stage == ShaderType::Pixel && + state.input_info.pixel->ps_no_perspective && !flat && !input.per_vertex) { + state.builder.AddAnnotation(spv::OpDecorate, input.variable_id, + spv::DecorationNoPerspective); + } + state.builder.AddAnnotation(spv::OpDecorate, input.variable_id, spv::DecorationLocation, + PixelParameterLocation(state, input.location)); + } else if (const auto builtin = BuiltInForInput(input.kind); builtin != UINT32_MAX) { + state.builder.AddAnnotation(spv::OpDecorate, input.variable_id, spv::DecorationBuiltIn, + builtin); + } + } + if (state.program.info.subgroup_local_invocation_id && !state.scalar_subgroups) { + const auto variable = DefineInterfaceVariable(state, TypeU32(state), spv::StorageClassInput, + "gl_SubgroupInvocationID"); + state.subgroup_local_invocation_id_variable = variable; + state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBuiltIn, + spv::BuiltInSubgroupLocalInvocationId); + if (state.program.stage == ShaderType::Pixel) { + state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationFlat); + } + } + if (state.program.stage == ShaderType::Pixel && + (state.program.info.subgroup_ballot || state.program.info.subgroup_vote)) { + const auto variable = DefineInterfaceVariable( + state, TypeBool(state), spv::StorageClassInput, "gl_HelperInvocation"); + state.helper_invocation_variable = variable; + state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBuiltIn, + spv::BuiltInHelperInvocation); + } +} + +void DefineOutputs(EmitterState& state) { + state.outputs.reserve(state.program.info.outputs.size()); + uint32_t clip_distance_count = 0; + uint32_t cull_distance_count = 0; + for (const auto& output: state.program.info.outputs) { + state.outputs.push_back({output}); + if (output.kind == IR::StageOutputKind::ClipDistance) { + clip_distance_count = std::max(clip_distance_count, output.index + 1); + } else if (output.kind == IR::StageOutputKind::CullDistance) { + cull_distance_count = std::max(cull_distance_count, output.index + 1); + } + } + if (state.program.stage == ShaderType::Mesh) { + DefineMeshOutputs(state, clip_distance_count, cull_distance_count); + return; + } + if (state.program.stage == ShaderType::Vertex && clip_distance_count + cull_distance_count < 8u && + std::ranges::any_of(state.outputs, [](const OutputBinding& output) { + return output.kind == IR::StageOutputKind::Position; + })) { + // Reserve one plane for the enabled PA_CL_CLIP_CNTL clipping-error cull. + state.invalid_position_clip_distance = clip_distance_count++; + state.outputs.push_back({{IR::StageOutputKind::ClipDistance, + state.invalid_position_clip_distance, 0, "gl_ClipDistance"}}); + } + const auto BuiltIn = [&](uint32_t& variable, uint32_t type, const char* name, + spv::BuiltIn builtin) { + if (variable == 0) { + variable = DefineInterfaceVariable(state, type, spv::StorageClassOutput, name); + state.builder.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBuiltIn, builtin); + } + return variable; + }; + for (auto& binding: state.outputs) { + switch (binding.kind) { + case IR::StageOutputKind::Position: + if (state.per_vertex_variable == 0) { + const auto type = PerVertexType(state); + state.builder.AddName(type, "gl_PerVertex"); + state.per_vertex_variable = DefineInterfaceVariable( + state, type, spv::StorageClassOutput, "outPerVertex"); + } + binding.variable_id = state.per_vertex_variable; + break; + case IR::StageOutputKind::PointSize: + binding.variable_id = BuiltIn(state.point_size_variable, TypeF32(state), + "gl_PointSize", spv::BuiltInPointSize); + break; + case IR::StageOutputKind::ClipDistance: + binding.variable_id = + BuiltIn(state.clip_distance_variable, F32ArrayType(state, clip_distance_count), + "gl_ClipDistance", spv::BuiltInClipDistance); + break; + case IR::StageOutputKind::CullDistance: + binding.variable_id = + BuiltIn(state.cull_distance_variable, F32ArrayType(state, cull_distance_count), + "gl_CullDistance", spv::BuiltInCullDistance); + break; + case IR::StageOutputKind::Layer: + binding.variable_id = + BuiltIn(state.layer_variable, TypeU32(state), "gl_Layer", spv::BuiltInLayer); + break; + case IR::StageOutputKind::ViewportIndex: + binding.variable_id = BuiltIn(state.viewport_index_variable, TypeU32(state), + "gl_ViewportIndex", spv::BuiltInViewportIndex); + break; + case IR::StageOutputKind::Depth: + binding.variable_id = BuiltIn(state.depth_variable, TypeF32(state), "gl_FragDepth", + spv::BuiltInFragDepth); + break; + case IR::StageOutputKind::SampleMask: + binding.variable_id = + BuiltIn(state.sample_mask_variable, SampleMaskArrayType(state), "gl_SampleMask", + spv::BuiltInSampleMask); + break; + case IR::StageOutputKind::ObjectPrimitiveId: + binding.variable_id = DefineInterfaceVariable( + state, TypeU32(state), spv::StorageClassOutput, binding.debug_name.c_str()); + state.object_primitive_id_variable = binding.variable_id; + state.builder.AddAnnotation(spv::OpDecorate, binding.variable_id, + spv::DecorationLocation, binding.location); + break; + case IR::StageOutputKind::Parameter: + case IR::StageOutputKind::Mrt: { + const bool uint_output = + binding.kind == IR::StageOutputKind::Mrt && + state.program.stage == ShaderType::Pixel && + binding.index < std::size(state.input_info.pixel->target_output_mode) && + (state.input_info.pixel->target_output_mode[binding.index] == 7u || + (state.input_info.pixel->target_packed_unorm_mask & (1u << binding.index)) != 0u); + const auto type = uint_output ? TypeU32Vector(state, 4) : TypeF32Vector(state, 4); + binding.variable_id = DefineInterfaceVariable(state, type, spv::StorageClassOutput, + binding.debug_name.c_str()); + const bool dual_source = binding.kind == IR::StageOutputKind::Mrt && + state.program.stage == ShaderType::Pixel && + state.input_info.pixel->dual_source_blending; + EXIT_NOT_IMPLEMENTED(dual_source && binding.index > 1); + state.builder.AddAnnotation(spv::OpDecorate, binding.variable_id, + spv::DecorationLocation, + dual_source ? 0u : binding.location); + if (dual_source) { + state.builder.AddAnnotation(spv::OpDecorate, binding.variable_id, + spv::DecorationIndex, binding.index); + } + break; + } + } + } +} + +} // namespace + +void DefineModule(EmitterState& state) { + state.interface_variables.reserve(state.program.info.inputs.size() + + state.program.info.outputs.size()); + DefineInputs(state); + DefineOutputs(state); + DefineTessellationInterfaces(state); + DefineDescriptors(state); + if (state.program.info.function_lds) { + state.lds_variable = state.builder.AllocateId(); + } + if (state.program.info.function_scratch) { + for (uint32_t half = 0; half < state.lane_count; half++) { + state.scratch_variable[half] = state.builder.AllocateId(); + } + } + state.main_func = state.builder.AllocateId(); + if (state.program.stage == ShaderType::Mesh) { + state.mesh_guest_func = state.builder.AllocateId(); + state.builder.RequireCapability(spv::CapabilityMeshShadingEXT); // MeshShadingEXT + state.builder.RequireExtension("SPV_EXT_mesh_shader"); + state.builder.AddExecutionMode(state.main_func, + spv::ExecutionModeOutputTrianglesEXT); // OutputTrianglesEXT + state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeOutputVertices, + state.input_info.vertex->mesh.max_vertices); + state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeOutputPrimitivesEXT, + state.input_info.vertex->mesh.max_primitives); + } + if (state.program.stage == ShaderType::TessellationControl || + state.program.stage == ShaderType::TessellationEvaluation) { + DefineTessellationExecutionModes(state); + } + state.entry_label = state.builder.AllocateId(); + + state.builder.RequireCapability(spv::CapabilityShader); + state.builder.RequireCapability(spv::CapabilitySignedZeroInfNanPreserve); + if (state.program.info.buffer_u8) { + state.builder.RequireExtension("SPV_KHR_8bit_storage"); + state.builder.RequireCapability(spv::CapabilityStorageBuffer8BitAccess); + } + if (state.program.info.buffer_u16) { + state.builder.RequireCapability(spv::CapabilityStorageBuffer16BitAccess); + } + if (state.program.info.uses_dma) { + state.builder.RequireCapability(spv::CapabilityInt64); + state.builder.RequireCapability(spv::CapabilityPhysicalStorageBufferAddresses); + state.builder.RequireExtension("SPV_KHR_physical_storage_buffer"); + } + if (state.program.info.buffer_int64_atomics || state.program.info.shared_int64_atomics) { + state.builder.RequireCapability(spv::CapabilityInt64); + state.builder.RequireCapability(spv::CapabilityInt64Atomics); + } + if (state.program.info.shared_int64_atomics && + state.lds_storage_class == spv::StorageClassWorkgroup) { + state.builder.RequireVersion(0x00010400u); + state.builder.RequireExtension("SPV_KHR_workgroup_memory_explicit_layout"); + state.builder.RequireCapability(spv::CapabilityWorkgroupMemoryExplicitLayoutKHR); + } + if (state.clip_distance_variable != 0) { + state.builder.RequireCapability(spv::CapabilityClipDistance); + } + if (state.cull_distance_variable != 0) { + state.builder.RequireCapability(spv::CapabilityCullDistance); + } + if (state.layer_variable != 0 || InputVariableForKind(state, IR::StageInputKind::Layer) != 0) { + state.builder.RequireVersion(0x00010500u); + state.builder.RequireCapability(spv::CapabilityShaderLayer); + } + if (state.viewport_index_variable != 0) { + state.builder.RequireVersion(0x00010500u); + state.builder.RequireCapability(spv::CapabilityShaderViewportIndex); + } + if (InputVariableForKind(state, IR::StageInputKind::SampleId) != 0) { + state.builder.RequireCapability(spv::CapabilitySampleRateShading); + } + if (state.program.info.image_gather_extended) { + state.builder.RequireCapability(spv::CapabilityImageGatherExtended); + } + if (state.lane_count == 2 || state.program.info.subgroup_barrier || + state.program.info.subgroup_ballot || state.program.info.subgroup_vote || + state.program.info.subgroup_shuffle || + state.program.info.subgroup_arithmetic || state.program.info.subgroup_local_invocation_id) { + state.builder.RequireCapability(spv::CapabilityGroupNonUniform); + } + if (state.lane_count == 2 || state.program.info.subgroup_ballot) { + state.builder.RequireCapability(spv::CapabilityGroupNonUniformBallot); + } + if (state.program.info.subgroup_vote) { + state.builder.RequireCapability(spv::CapabilityGroupNonUniformVote); + } + if (state.program.info.subgroup_shuffle) { + state.builder.RequireCapability(spv::CapabilityGroupNonUniformShuffle); + } + if (state.program.info.subgroup_arithmetic) { + state.builder.RequireCapability(spv::CapabilityGroupNonUniformArithmetic); + } + if (state.program.info.compute_derivatives && state.program.stage == ShaderType::Compute) { + state.builder.RequireCapability(spv::CapabilityComputeDerivativeGroupQuadsKHR); + state.builder.RequireExtension("SPV_KHR_compute_shader_derivatives"); + } + const bool fragment_barycentric = + state.program.stage == ShaderType::Pixel && + std::any_of(state.inputs.begin(), state.inputs.end(), [](const InputBinding& input) { + return input.per_vertex || input.kind == IR::StageInputKind::BaryCoordSmooth || + input.kind == IR::StageInputKind::BaryCoordNoPerspective; + }); + if (fragment_barycentric) { + state.builder.RequireCapability(spv::CapabilityFragmentBarycentricKHR); + state.builder.RequireExtension("SPV_KHR_fragment_shader_barycentric"); + } + state.builder.RequireExtension("SPV_KHR_float_controls"); + state.builder.AddMemoryModel(state.program.info.uses_dma + ? spv::AddressingModelPhysicalStorageBuffer64 + : spv::AddressingModelLogical, + spv::MemoryModelGLSL450); + // GCN/RDNA arithmetic preserves 32-bit signed zero, infinity, and NaN. Declaring that + // contract prevents host compilers from treating synthesized IEEE values as finite. + state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeSignedZeroInfNanPreserve, + 32u); + if (state.program.info.float64) { + EXIT_NOT_IMPLEMENTED(state.program.stage == ShaderType::Compute && + state.input_info.compute->float_mode != 0xc0); + // Use native rounding for MODE=0xc0, consistent with ordinary FP32 arithmetic. + state.builder.RequireCapability(spv::CapabilityFloat64); + state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeSignedZeroInfNanPreserve, + 64u); + // FP64 denormal preservation is temporarily disabled. + // state.builder.RequireCapability(spv::CapabilityDenormPreserve); + // state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeDenormPreserve, 64u); + } + if (const auto* cs = ShaderWorkgroupInput(state.program.stage, state.input_info)) { + uint32_t local_x = state.program.info.compute_derivatives ? 2u : 1u; + uint32_t local_y = state.program.info.compute_derivatives ? 2u : 1u; + uint32_t local_z = 1u; + local_x = cs->threads_num[0] != 0u ? cs->threads_num[0] : local_x; + local_y = cs->threads_num[1] != 0u ? cs->threads_num[1] : local_y; + local_z = cs->threads_num[2] != 0u ? cs->threads_num[2] : local_z; + if (state.lane_count == 2) { + local_x = ((local_x * local_y * local_z + 63u) / 64u) * 32u; + local_y = local_z = 1u; + if (state.program.info.compute_derivatives) { + local_y = local_x / 2u; + local_x = 2u; + } + } + state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeLocalSize, local_x, + local_y, local_z); + } + if (state.program.stage == ShaderType::Pixel) { + state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeOriginUpperLeft); + if (state.depth_variable != 0) { + state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeDepthReplacing); + } + if (state.input_info.pixel->ps_early_z && !state.input_info.pixel->ps_pixel_kill_enable && + !state.input_info.pixel->ps_depth_export_enable && + !state.input_info.pixel->ps_sample_mask_export_enable) { + state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeEarlyFragmentTests); + } + } + if (state.program.info.compute_derivatives && state.program.stage == ShaderType::Compute) { + state.builder.AddExecutionMode(state.main_func, spv::ExecutionModeDerivativeGroupQuadsKHR); + } + state.builder.AddName(state.main_func, "main"); + if (state.program.info.function_lds) { + state.builder.AddName(state.lds_variable, "lds_dwords"); + } + if (state.program.info.function_scratch) { + for (uint32_t half = 0; half < state.lane_count; half++) { + state.builder.AddName(state.scratch_variable[half], "scratch_dwords"); + } + } +} + +} // namespace Libs::Graphics::ShaderRecompiler::Spirv::Emitter diff --git a/src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp b/src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp index e40dc505..2c60f9d7 100644 --- a/src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp +++ b/src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp @@ -1,628 +1,642 @@ -#include "graphics/shader/recompiler/ir/passes/ShaderInfoCollection.h" - -#include "common/assert.h" -#include "graphics/shader/recompiler/ir/ShaderIR.h" - -#include -#include - -namespace Libs::Graphics::ShaderRecompiler::IR { -namespace { - -[[noreturn]] void Fail(std::string_view message) { - EXIT("shader info collection failed: %s", std::string(message).c_str()); - std::abort(); -} - -void AddInput(ShaderInfo& info, StageInputKind kind, uint32_t location, uint32_t components, - std::string name, bool per_vertex = false) { - const auto input = std::find_if(info.inputs.begin(), info.inputs.end(), [=](const auto& value) { - return value.kind == kind && value.location == location; - }); - if (input == info.inputs.end()) { - info.inputs.push_back({kind, location, components, std::move(name), per_vertex}); - } else { - input->component_count = std::max(input->component_count, components); - input->per_vertex = input->per_vertex || per_vertex; - } -} - -bool HasOutput(const ShaderInfo& info, StageOutputKind kind, uint32_t index) { - return std::any_of(info.outputs.begin(), info.outputs.end(), [=](const auto& output) { - return output.kind == kind && output.index == index; - }); -} - -void AddOutput(ShaderInfo& info, StageOutputKind kind, uint32_t index, uint32_t location, - std::string name) { - if (!HasOutput(info, kind, index)) { - info.outputs.push_back({kind, index, location, std::move(name)}); - } -} - -void ValidateOptions(const Program& program, ShaderStageInputInfo input_info) { - switch (program.stage) { - case ShaderType::Vertex: - case ShaderType::Local: - case ShaderType::TessellationControl: - case ShaderType::TessellationEvaluation: - case ShaderType::Mesh: - if (input_info.vertex == nullptr) { - return Fail("vertex shader has no input metadata"); - } - if (input_info.vertex->resources_num < 0 || - input_info.vertex->resources_num > ShaderVertexInputInfo::RES_MAX) { - return Fail("vertex resource count is out of range"); - } - return; - case ShaderType::Pixel: - if (input_info.pixel == nullptr) { - return Fail("pixel shader has no input metadata"); - } - if (input_info.pixel->input_num > std::size(input_info.pixel->interpolator_settings)) { - return Fail("pixel input count is out of range"); - } - return; - case ShaderType::Compute: - if (input_info.compute == nullptr) { - return Fail("compute shader has no input metadata"); - } - if (input_info.compute->thread_ids_num < 0 || input_info.compute->thread_ids_num > 3) { - return Fail("compute thread ID count is out of range"); - } - return; - default: return Fail("unsupported shader stage for info collection"); - } -} - - -void CollectVertexInputs(const ShaderVertexInputInfo* vertex, ShaderInfo& info, - const std::array& used_components) { - AddInput(info, StageInputKind::VertexIndex, 0, 1, "gl_VertexIndex"); - AddInput(info, StageInputKind::InstanceIndex, 0, 1, "gl_InstanceIndex"); - for (uint32_t attr = 0; attr < static_cast(vertex->resources_num); attr++) { - if (used_components[attr] != 0) { - AddInput(info, StageInputKind::Parameter, attr, used_components[attr], - fmt::format("in_attr_{}", attr)); - } - } -} - -void CollectPixelInputs(const ShaderPixelInputInfo* pixel, ShaderInfo& info, - std::array& per_vertex, - const std::array& used_components) { - if (pixel->HasPositionInput()) { - AddInput(info, StageInputKind::FragCoord, 0, 4, "gl_FragCoord"); - } - if (pixel->ps_front_face) { - AddInput(info, StageInputKind::FrontFacing, 0, 1, "gl_FrontFacing"); - } - // Mixed interpolation modes share raw vertices at their guest export slot. - // Rectangle expansion alone supplies separate flat and smooth outputs. - for (uint32_t input = 0; input < pixel->input_num; input++) { - for (uint32_t alias = 0; alias < pixel->input_num; alias++) { - const bool same_mode = ShaderPixelParameterIsFlat(*pixel, input) == - ShaderPixelParameterIsFlat(*pixel, alias); - if (ShaderPixelParameterMappedLocation(*pixel, input) == - ShaderPixelParameterMappedLocation(*pixel, alias) && - (pixel->parameter_mode != ShaderPixelParameterMode::Rectangle || same_mode)) { - per_vertex[input] = per_vertex[input] || per_vertex[alias] || !same_mode; - } - } - } - for (uint32_t input = 0; input < pixel->input_num; input++) { - AddInput(info, StageInputKind::Parameter, input, 4, fmt::format("in_param_{}", input), - per_vertex[input]); - } - for (uint32_t input = 0; input < pixel->input_num; input++) { - if (used_components[input] != 0 && per_vertex[input] && - !ShaderPixelParameterIsFlat(*pixel, input)) { - const auto kind = pixel->ps_no_perspective ? StageInputKind::BaryCoordNoPerspective - : StageInputKind::BaryCoordSmooth; - AddInput(info, kind, 0, 3, - pixel->ps_no_perspective ? "gl_BaryCoordNoPerspKHR" : "gl_BaryCoordKHR"); - break; - } - } -} - -void CollectComputeInputs(const ShaderComputeInputInfo* compute, ShaderInfo& info) { - if (compute->group_id[0] || compute->group_id[1] || compute->group_id[2]) { - AddInput(info, StageInputKind::WorkgroupId, 0, 3, "gl_WorkGroupID"); - } - if (compute->thread_ids_num > 0) { - AddInput(info, StageInputKind::LocalInvocationId, 0, 3, "gl_LocalInvocationID"); - } - if (compute->thread_ids_num > 0 || compute->tg_size_en) { - AddInput(info, StageInputKind::LocalInvocationIndex, 0, 1, "gl_LocalInvocationIndex"); - } - if (compute->dispatch_thread_dimensions) { - AddInput(info, StageInputKind::GlobalInvocationId, 0, 3, "gl_GlobalInvocationID"); - } -} - -void AddBuiltinInput(ShaderInfo& info, StageInputKind kind) { - switch (kind) { - case StageInputKind::VertexIndex: - AddInput(info, kind, 0, 1, "gl_VertexIndex"); - break; - case StageInputKind::InstanceIndex: - AddInput(info, kind, 0, 1, "gl_InstanceIndex"); - break; - case StageInputKind::InvocationId: - AddInput(info, kind, 0, 1, "gl_InvocationID"); - break; - case StageInputKind::PrimitiveId: - AddInput(info, kind, 0, 1, "gl_PrimitiveID"); - break; - case StageInputKind::TessCoord: AddInput(info, kind, 0, 3, "gl_TessCoord"); break; - case StageInputKind::FragCoord: AddInput(info, kind, 0, 4, "gl_FragCoord"); break; - case StageInputKind::FrontFacing: - AddInput(info, kind, 0, 1, "gl_FrontFacing"); - break; - case StageInputKind::Layer: AddInput(info, kind, 0, 1, "gl_Layer"); break; - case StageInputKind::SampleId: AddInput(info, kind, 0, 1, "gl_SampleID"); break; - case StageInputKind::BaryCoordSmoothSample: - AddInput(info, StageInputKind::SampleId, 0, 1, "gl_SampleID"); - [[fallthrough]]; - case StageInputKind::BaryCoordSmooth: - case StageInputKind::BaryCoordSmoothCentroid: - AddInput(info, StageInputKind::BaryCoordSmooth, 0, 3, "gl_BaryCoordKHR"); - break; - case StageInputKind::BaryCoordNoPerspective: - AddInput(info, kind, 0, 3, "gl_BaryCoordNoPerspKHR"); - break; - case StageInputKind::WorkgroupId: - AddInput(info, kind, 0, 3, "gl_WorkGroupID"); - break; - case StageInputKind::LocalInvocationId: - AddInput(info, kind, 0, 3, "gl_LocalInvocationID"); - break; - case StageInputKind::LocalInvocationIndex: - AddInput(info, kind, 0, 1, "gl_LocalInvocationIndex"); - break; - case StageInputKind::GlobalInvocationId: - AddInput(info, kind, 0, 3, "gl_GlobalInvocationID"); - break; - case StageInputKind::PackedAncillary: - case StageInputKind::Parameter: break; - } -} - -void CollectOutput(const Program& program, ShaderStageInputInfo input_info, - ShaderInfo& info, const Inst& inst) { - const bool alpha_remap = program.stage == ShaderType::Pixel && input_info.pixel != nullptr && - input_info.pixel->alpha_blend_source != ShaderAlphaBlendSource::None; - const auto& export_info = program.export_info[inst.Flags().index]; - if (export_info.kind == ExportTargetKind::MrtZ) { - if (program.stage == ShaderType::Pixel && (export_info.en & 0x1u) != 0 && - input_info.pixel->ps_depth_export_enable) { - AddOutput(info, StageOutputKind::Depth, 0, 0, "gl_FragDepth"); - } - if (program.stage == ShaderType::Pixel && (export_info.en & 0x4u) != 0 && - input_info.pixel->ps_sample_mask_export_enable) { - AddOutput(info, StageOutputKind::SampleMask, 0, 0, "gl_SampleMask"); - } - return; - } - if (export_info.en == 0) { - return; - } - switch (export_info.kind) { - case ExportTargetKind::Position: - if (export_info.index == 0) { - AddOutput(info, StageOutputKind::Position, 0, 0, "out_position"); - break; - } - if (export_info.compr) { - return Fail("compressed auxiliary position export is unsupported"); - } - for (uint32_t component = 0; component < 4; component++) { - if ((export_info.en & (1u << component)) == 0) { - continue; - } - const auto output = DecodePositionExportComponent( - input_info.vertex->pa_cl_vs_out_cntl, export_info.index, component); - if (output.viewport) { - AddOutput(info, StageOutputKind::ViewportIndex, 0, 0, "gl_ViewportIndex"); - } - if (output.point_size) { - AddOutput(info, StageOutputKind::PointSize, 0, 0, "gl_PointSize"); - } - if (output.layer) { - AddOutput(info, StageOutputKind::Layer, 0, 0, "gl_Layer"); - } - if (output.clip_distance != UINT32_MAX) { - AddOutput(info, StageOutputKind::ClipDistance, output.clip_distance, 0, - "gl_ClipDistance"); - } - if (output.cull_distance != UINT32_MAX) { - AddOutput(info, StageOutputKind::CullDistance, output.cull_distance, 0, - "gl_CullDistance"); - } - } - break; - case ExportTargetKind::Parameter: - AddOutput(info, StageOutputKind::Parameter, export_info.index, - export_info.index, fmt::format("out_param_{}", export_info.index)); - break; - case ExportTargetKind::Mrt: { - if (alpha_remap && export_info.index != 0) { - break; - } - const auto slot = input_info.pixel->dual_source_blending - ? 0u : ShaderPixelExportTarget(input_info.pixel->target_shader_mask, - export_info.index); - if (slot >= 8) { - break; - } - AddOutput(info, StageOutputKind::Mrt, export_info.index, slot, - fmt::format("out_mrt_{}", export_info.index)); - if (alpha_remap) { - AddOutput(info, StageOutputKind::Mrt, 1, 0, "out_mrt_1"); - } - break; - } - default: break; - } -} - -struct InputUsage { - std::array components {}; - std::array per_vertex {}; - std::array user_data {}; - std::array(StageInputKind::Parameter)> builtins {}; - uint32_t builtin_mask = 0; - uint32_t builtin_count = 0; - - void AddBuiltin(StageInputKind kind) { - const auto bit = 1u << static_cast(kind); - if ((builtin_mask & bit) == 0) { - builtin_mask |= bit; - builtins[builtin_count++] = kind; - } - } -}; - -void Visit(Program& program, ShaderStageInputInfo input_info, InputUsage& inputs, - const Inst& inst) { - auto& info = program.info; - const auto op = inst.GetOpcode(); - const auto buffer_access = BufferAccessOf(op); - const auto address_access = AddressOpcodeInfoOf(op).access; - const auto shared_access = SharedAccessOf(op); - info.float64 |= inst.GetType() == Type::F64; - info.buffer_int64_atomics |= buffer_access == BufferAccess::Atomic && - inst.GetType() == Type::U64; - if (buffer_access != BufferAccess::None || address_access != AddressAccess::None || - shared_access != SharedAccess::None) { - const auto index = inst.Flags().index; - if (index >= program.memory_info.size()) { - return Fail("typed shader contains invalid memory metadata"); - } - const auto& memory = program.memory_info[index]; - const auto kind = memory.kind; - if (!memory.planning_only) { - info.uses_lds |= kind == ResourceKind::FlatLocal; - if (shared_access != SharedAccess::None) { - info.uses_lds |= kind == ResourceKind::Lds; - info.uses_gds |= kind == ResourceKind::Gds; - } else if (kind == ResourceKind::Buffer || kind == ResourceKind::ScalarBuffer) { - if (memory.resource >= info.buffers.size()) { - return Fail("buffer operation has invalid resource metadata"); - } - info.buffers[memory.resource].live = true; - for (const auto child: info.buffers[memory.resource].indirect_resources) { - if (child >= info.buffers.size()) { - return Fail("indirect buffer operation has invalid resource metadata"); - } - info.buffers[child].live = true; - } - } - } - if (address_access != AddressAccess::None) { - if (kind == ResourceKind::Scratch || kind == ResourceKind::FlatLocal) { - if (program.scratch_dwords == 0) { - return Fail("scratch operation has no per-thread storage"); - } - info.function_scratch = true; - info.function_lds |= kind == ResourceKind::FlatLocal && - program.stage != ShaderType::Compute && program.stage != ShaderType::Mesh; - } else if (address_access == AddressAccess::Write) { - return Fail("writable FLAT/GLOBAL addresses require GPU ownership tracking"); - } else { - info.coherent_buffers |= memory.coherent; - } - } - if (buffer_access != BufferAccess::None) { - if (kind == ResourceKind::IndirectBuffer && op != ValueOpcode::ReadConstBuffer) { - info.subgroup_local_invocation_id = true; - } - if (kind == ResourceKind::Buffer) { - info.coherent_buffers |= memory.coherent; - if (memory.resource >= info.buffers.size()) { - return Fail("buffer operation has invalid resource metadata"); - } - const auto collect_element = [&](uint32_t resource) { - auto selected = memory; - selected.resource = resource; - const auto bits = StorageBufferElementBits(program, selected); - info.buffer_u8 |= bits == 8u; - info.buffer_u16 |= bits == 16u; - }; - collect_element(memory.resource); - for (const auto child: info.buffers[memory.resource].indirect_resources) - collect_element(child); - if ((info.buffers[memory.resource].packed_stride & (1u << 20u)) != 0u) { - if (program.stage != ShaderType::Compute) { - return Fail("buffer ADD_TID is only valid for compute shaders"); - } - info.subgroup_local_invocation_id = true; - } - } - } - if (shared_access != SharedAccess::None) { - if (kind != ResourceKind::Lds && kind != ResourceKind::Gds) { - return Fail("shared operation has invalid resource kind"); - } - if (shared_access == SharedAccess::Atomic && SharedComponentCount(op) == 2u) { - if (kind != ResourceKind::Lds || program.stage != ShaderType::Compute) { - return Fail("64-bit shared atomics require compute LDS"); - } - info.shared_int64_atomics = true; - } - info.function_lds |= kind == ResourceKind::Lds && - program.stage != ShaderType::Compute && program.stage != ShaderType::Mesh; - if (shared_access == SharedAccess::Append || shared_access == SharedAccess::Consume) { - info.subgroup_ballot = true; - info.subgroup_shuffle = true; - info.subgroup_local_invocation_id = true; - } - } - } - switch (inst.GetOpcode()) { - case ValueOpcode::GetAttribute: { - if (!inst.Arg(0).IsImmediate() || inst.Arg(0).GetType() != Type::U32 || - !inst.Arg(1).IsImmediate() || inst.Arg(1).GetType() != Type::U32) { - return Fail("typed attribute reference is not constant"); - } - if ((program.stage == ShaderType::Vertex || - program.stage == ShaderType::Local) && - (inst.Arg(1).U32() >= 4u || - inst.Arg(0).U32() >= - static_cast(input_info.vertex->resources_num))) { - return Fail("vertex input reference is out of range"); - } - if (program.stage == ShaderType::Pixel && - (inst.Arg(1).U32() >= 4u || - inst.Arg(0).U32() >= input_info.pixel->input_num)) { - return Fail("pixel input reference is out of range"); - } - if (program.stage == ShaderType::Vertex || program.stage == ShaderType::Local || - program.stage == ShaderType::Pixel) { - auto& components = inputs.components[inst.Arg(0).U32()]; - components = std::max(components, static_cast(inst.Arg(1).U32() + 1u)); - } - break; - } - case ValueOpcode::GetInterpolationParameter: { - if (program.stage != ShaderType::Pixel || !inst.Arg(0).IsImmediate() || - inst.Arg(0).GetType() != Type::U32 || !inst.Arg(1).IsImmediate() || - inst.Arg(1).GetType() != Type::U32 || !inst.Arg(2).IsImmediate() || - inst.Arg(2).GetType() != Type::U32) { - return Fail("interpolation parameter reference is invalid"); - } - if (inst.Arg(0).U32() >= input_info.pixel->input_num || - inst.Arg(1).U32() >= 4u || inst.Arg(2).U32() >= 3u) { - return Fail("interpolation parameter reference is out of range"); - } - const auto input = inst.Arg(0).U32(); - inputs.per_vertex[input] |= inst.Arg(2).U32() < 2u || - !ShaderPixelParameterIsFlat(*input_info.pixel, input); - break; - } - case ValueOpcode::GetBuiltin: { - if (!inst.Arg(0).IsImmediate() || inst.Arg(0).GetType() != Type::U32 || - !inst.Arg(1).IsImmediate() || inst.Arg(1).GetType() != Type::U32) { - return Fail("typed builtin reference is not constant"); - } - const auto kind = static_cast(inst.Arg(0).U32()); - const auto component = inst.Arg(1).U32(); - switch (kind) { - case StageInputKind::PackedAncillary: - return Fail("packed pixel ancillary input has an unsupported live use"); - case StageInputKind::Layer: - case StageInputKind::SampleId: - if (program.stage != ShaderType::Pixel || component != 0u) { - return Fail("typed pixel scalar input is invalid"); - } - break; - case StageInputKind::VertexIndex: - case StageInputKind::InvocationId: - case StageInputKind::PrimitiveId: - case StageInputKind::InstanceIndex: - case StageInputKind::FrontFacing: - case StageInputKind::LocalInvocationIndex: - if (component != 0u) { - return Fail("typed scalar builtin component is out of range"); - } - break; - case StageInputKind::FragCoord: - if (component >= 4u) { - return Fail("typed fragment-coordinate component is out of range"); - } - break; - case StageInputKind::BaryCoordSmooth: - case StageInputKind::BaryCoordSmoothSample: - case StageInputKind::BaryCoordSmoothCentroid: - case StageInputKind::BaryCoordNoPerspective: - if (component >= 2u) { - return Fail("typed barycentric component is out of range"); - } - break; - case StageInputKind::TessCoord: - case StageInputKind::WorkgroupId: - case StageInputKind::LocalInvocationId: - case StageInputKind::GlobalInvocationId: - if (component >= 3u) { - return Fail("typed invocation builtin component is out of range"); - } - break; - case StageInputKind::Parameter: - default: return Fail("typed builtin kind is invalid"); - } - inputs.AddBuiltin(kind); - break; - } - case ValueOpcode::SetAttribute: { - const auto index = inst.Flags().index; - if (index >= program.export_info.size()) { - return Fail("typed export metadata index is out of range"); - } - const auto& exp = program.export_info[index]; - if (exp.kind == ExportTargetKind::Position && exp.index != 0 && exp.en != 0 && - program.stage != ShaderType::Vertex && program.stage != ShaderType::Mesh && - program.stage != ShaderType::TessellationEvaluation) { - return Fail("auxiliary position export requires a vertex, mesh, or " - "tessellation evaluation shader"); - } - info.pixel_valid_mask |= program.stage == ShaderType::Pixel && exp.vm; - CollectOutput(program, input_info, info, inst); - break; - } - case ValueOpcode::GetUserData: { - if (!inst.HasUses()) break; - if (inst.Arg(0).GetType() != Type::ScalarReg) { - return Fail("typed shader contains an invalid user-data register"); - } - const auto index = RegIndex(inst.Arg(0).ScalarRegister()); - if (index >= NumScalarRegs) { - return Fail("typed shader contains an invalid user-data register"); - } - inputs.user_data[index] = true; - break; - } - case ValueOpcode::GetDispatchThreadExtent: - info.uses_dispatch_threads |= inst.HasUses(); - break; - case ValueOpcode::ReadConst: info.uses_flattened_srt = true; break; - case ValueOpcode::BitwiseXor32: info.has_bitwise_xor = true; break; - case ValueOpcode::StoreCompletion: info.subgroup_barrier = true; break; - case ValueOpcode::BvhIntersect: info.bvh = true; break; - case ValueOpcode::ConditionRef: - if (inst.Flags() != CFG::BranchCondition::ScalarInstruction) { - info.subgroup_vote = true; - if (program.wave_size == 32u && - (program.stage == ShaderType::Vertex || program.stage == ShaderType::Local || - program.stage == ShaderType::TessellationEvaluation)) { - info.subgroup_ballot = true; - info.subgroup_local_invocation_id = true; - } - } - break; - case ValueOpcode::Ballot: info.subgroup_ballot = true; break; - case ValueOpcode::SubgroupUMinU32: info.subgroup_arithmetic = true; break; - case ValueOpcode::DppMoveU32: - case ValueOpcode::ReadFirstLane: - case ValueOpcode::ReadLane: { - info.subgroup_ballot = true; - info.subgroup_shuffle = true; - if (inst.GetOpcode() == ValueOpcode::DppMoveU32) { - info.subgroup_local_invocation_id = true; - } - break; - } - case ValueOpcode::DppUpdateU32: - case ValueOpcode::WriteLane: { - info.subgroup_ballot = true; - info.subgroup_local_invocation_id = true; - break; - } - case ValueOpcode::SwizzleU32: - info.uses_swizzle = true; - [[fallthrough]]; - case ValueOpcode::Permlane16U32: - case ValueOpcode::PermuteU32: - case ValueOpcode::BpermuteU32: { - info.subgroup_ballot = true; - info.subgroup_shuffle = true; - info.subgroup_local_invocation_id = true; - break; - } - case ValueOpcode::LaneId: - if (program.stage == ShaderType::TessellationControl) { - inputs.AddBuiltin(StageInputKind::InvocationId); - } else { - info.subgroup_local_invocation_id = true; - } - break; - case ValueOpcode::ImageQueryLod: info.compute_derivatives = true; break; - case ValueOpcode::ImageGatherRaw: - info.image_gather_extended = true; - break; - default: break; - } -} - -} // namespace - -void CollectShaderInfo(Program& program, ShaderStageInputInfo input_info) { - if (!program.resource_tracking_complete || program.shader_info_complete) { - return Fail(!program.resource_tracking_complete ? "shader resources were not tracked" - : "shader info already collected"); - } - ValidateOptions(program, input_info); - auto& info = program.info; - info.inputs.clear(); - info.outputs.clear(); - info.user_data_registers.clear(); - for (auto& buffer: info.buffers) buffer.live = false; - info.has_bitwise_xor = info.uses_lds = info.uses_gds = info.uses_flattened_srt = - info.uses_dispatch_threads = info.uses_swizzle = false; - info.bvh = info.subgroup_ballot = info.subgroup_vote = info.subgroup_barrier = - info.subgroup_shuffle = info.subgroup_arithmetic = - info.subgroup_local_invocation_id = info.compute_derivatives = info.image_gather_extended = - info.function_lds = info.function_scratch = info.pixel_valid_mask = info.buffer_int64_atomics = - info.buffer_u8 = info.buffer_u16 = info.shared_int64_atomics = info.coherent_buffers = info.float64 = false; - InputUsage inputs; - for (const auto* block: program.blocks) { - for (const auto& inst: *block) { - Visit(program, input_info, inputs, inst); - } - } - for (uint32_t index = 0; index < inputs.user_data.size(); index++) { - if (inputs.user_data[index]) info.user_data_registers.push_back(index); - } - const auto uses_mapping = [](const auto& resource) { - return resource.indirect_root != UINT32_MAX; - }; - info.uses_flattened_srt |= std::ranges::any_of(info.buffers, uses_mapping) || - std::ranges::any_of(info.images, uses_mapping); - switch (program.stage) { - case ShaderType::Vertex: - case ShaderType::Local: CollectVertexInputs(input_info.vertex, info, inputs.components); break; - case ShaderType::TessellationControl: - case ShaderType::TessellationEvaluation: - case ShaderType::Mesh: break; - case ShaderType::Pixel: - CollectPixelInputs(input_info.pixel, info, inputs.per_vertex, inputs.components); - if (input_info.pixel->object_primitive_id) { - if (std::ranges::any_of(info.outputs, [](const StageOutput& output) { - return output.kind == StageOutputKind::Mrt && output.location == 7u; - })) { - return Fail("explicit MRT7 export overlaps automatic object/primitive ID"); - } - AddBuiltinInput(info, StageInputKind::PrimitiveId); - AddOutput(info, StageOutputKind::ObjectPrimitiveId, 0, 7, "out_object_primitive_id"); - } - break; - case ShaderType::Compute: CollectComputeInputs(input_info.compute, info); break; - default: return Fail("unsupported shader stage for info collection"); - } - for (uint32_t i = 0; i < inputs.builtin_count; i++) { - AddBuiltinInput(info, inputs.builtins[i]); - } - program.shader_info_complete = true; -} - -} // namespace Libs::Graphics::ShaderRecompiler::IR +#include "graphics/shader/recompiler/ir/passes/ShaderInfoCollection.h" + +#include "common/assert.h" +#include "graphics/shader/recompiler/ir/ShaderIR.h" + +#include +#include + +namespace Libs::Graphics::ShaderRecompiler::IR { +namespace { + +[[noreturn]] void Fail(std::string_view message) { + EXIT("shader info collection failed: %s", std::string(message).c_str()); + std::abort(); +} + +void AddInput(ShaderInfo& info, StageInputKind kind, uint32_t location, uint32_t components, + std::string name, bool per_vertex = false) { + const auto input = std::find_if(info.inputs.begin(), info.inputs.end(), [=](const auto& value) { + return value.kind == kind && value.location == location; + }); + if (input == info.inputs.end()) { + info.inputs.push_back({kind, location, components, std::move(name), per_vertex}); + } else { + input->component_count = std::max(input->component_count, components); + input->per_vertex = input->per_vertex || per_vertex; + } +} + +bool HasOutput(const ShaderInfo& info, StageOutputKind kind, uint32_t index) { + return std::any_of(info.outputs.begin(), info.outputs.end(), [=](const auto& output) { + return output.kind == kind && output.index == index; + }); +} + +void AddOutput(ShaderInfo& info, StageOutputKind kind, uint32_t index, uint32_t location, + std::string name) { + if (!HasOutput(info, kind, index)) { + info.outputs.push_back({kind, index, location, std::move(name)}); + } +} + +void ValidateOptions(const Program& program, ShaderStageInputInfo input_info) { + switch (program.stage) { + case ShaderType::Vertex: + case ShaderType::Local: + case ShaderType::TessellationControl: + case ShaderType::TessellationEvaluation: + case ShaderType::Mesh: + if (input_info.vertex == nullptr) { + return Fail("vertex shader has no input metadata"); + } + if (input_info.vertex->resources_num < 0 || + input_info.vertex->resources_num > ShaderVertexInputInfo::RES_MAX) { + return Fail("vertex resource count is out of range"); + } + return; + case ShaderType::Pixel: + if (input_info.pixel == nullptr) { + return Fail("pixel shader has no input metadata"); + } + if (input_info.pixel->input_num > std::size(input_info.pixel->interpolator_settings)) { + return Fail("pixel input count is out of range"); + } + return; + case ShaderType::Compute: + if (input_info.compute == nullptr) { + return Fail("compute shader has no input metadata"); + } + if (input_info.compute->thread_ids_num < 0 || input_info.compute->thread_ids_num > 3) { + return Fail("compute thread ID count is out of range"); + } + return; + default: return Fail("unsupported shader stage for info collection"); + } +} + + +void CollectVertexInputs(const ShaderVertexInputInfo* vertex, ShaderInfo& info, + const std::array& used_components) { + AddInput(info, StageInputKind::VertexIndex, 0, 1, "gl_VertexIndex"); + AddInput(info, StageInputKind::InstanceIndex, 0, 1, "gl_InstanceIndex"); + for (uint32_t attr = 0; attr < static_cast(vertex->resources_num); attr++) { + if (used_components[attr] != 0) { + AddInput(info, StageInputKind::Parameter, attr, used_components[attr], + fmt::format("in_attr_{}", attr)); + } + } +} + +void CollectPixelInputs(const ShaderPixelInputInfo* pixel, ShaderInfo& info, + std::array& per_vertex, + const std::array& used_components) { + if (pixel->HasPositionInput()) { + AddInput(info, StageInputKind::FragCoord, 0, 4, "gl_FragCoord"); + } + if (pixel->ps_front_face) { + AddInput(info, StageInputKind::FrontFacing, 0, 1, "gl_FrontFacing"); + } + // Mixed interpolation modes share raw vertices at their guest export slot. + // Rectangle expansion alone supplies separate flat and smooth outputs. + for (uint32_t input = 0; input < pixel->input_num; input++) { + for (uint32_t alias = 0; alias < pixel->input_num; alias++) { + const bool same_mode = ShaderPixelParameterIsFlat(*pixel, input) == + ShaderPixelParameterIsFlat(*pixel, alias); + if (ShaderPixelParameterMappedLocation(*pixel, input) == + ShaderPixelParameterMappedLocation(*pixel, alias) && + (pixel->parameter_mode != ShaderPixelParameterMode::Rectangle || same_mode)) { + per_vertex[input] = per_vertex[input] || per_vertex[alias] || !same_mode; + } + } + } + for (uint32_t input = 0; input < pixel->input_num; input++) { + uint32_t components = 4; + if (pixel->mesh_stage) { + components = 0; + for (uint32_t alias = 0; alias < pixel->input_num; alias++) { + const bool same_mode = ShaderPixelParameterIsFlat(*pixel, input) == + ShaderPixelParameterIsFlat(*pixel, alias); + if (ShaderPixelParameterMappedLocation(*pixel, input) == + ShaderPixelParameterMappedLocation(*pixel, alias) && + (pixel->parameter_mode != ShaderPixelParameterMode::Rectangle || same_mode)) { + components = std::max(components, static_cast(used_components[alias])); + } + } + components = std::clamp(components, 1u, 4u); + } + AddInput(info, StageInputKind::Parameter, input, components, + fmt::format("in_param_{}", input), per_vertex[input]); + } + for (uint32_t input = 0; input < pixel->input_num; input++) { + if (used_components[input] != 0 && per_vertex[input] && + !ShaderPixelParameterIsFlat(*pixel, input)) { + const auto kind = pixel->ps_no_perspective ? StageInputKind::BaryCoordNoPerspective + : StageInputKind::BaryCoordSmooth; + AddInput(info, kind, 0, 3, + pixel->ps_no_perspective ? "gl_BaryCoordNoPerspKHR" : "gl_BaryCoordKHR"); + break; + } + } +} + +void CollectComputeInputs(const ShaderComputeInputInfo* compute, ShaderInfo& info) { + if (compute->group_id[0] || compute->group_id[1] || compute->group_id[2]) { + AddInput(info, StageInputKind::WorkgroupId, 0, 3, "gl_WorkGroupID"); + } + if (compute->thread_ids_num > 0) { + AddInput(info, StageInputKind::LocalInvocationId, 0, 3, "gl_LocalInvocationID"); + } + if (compute->thread_ids_num > 0 || compute->tg_size_en) { + AddInput(info, StageInputKind::LocalInvocationIndex, 0, 1, "gl_LocalInvocationIndex"); + } + if (compute->dispatch_thread_dimensions) { + AddInput(info, StageInputKind::GlobalInvocationId, 0, 3, "gl_GlobalInvocationID"); + } +} + +void AddBuiltinInput(ShaderInfo& info, StageInputKind kind) { + switch (kind) { + case StageInputKind::VertexIndex: + AddInput(info, kind, 0, 1, "gl_VertexIndex"); + break; + case StageInputKind::InstanceIndex: + AddInput(info, kind, 0, 1, "gl_InstanceIndex"); + break; + case StageInputKind::InvocationId: + AddInput(info, kind, 0, 1, "gl_InvocationID"); + break; + case StageInputKind::PrimitiveId: + AddInput(info, kind, 0, 1, "gl_PrimitiveID"); + break; + case StageInputKind::TessCoord: AddInput(info, kind, 0, 3, "gl_TessCoord"); break; + case StageInputKind::FragCoord: AddInput(info, kind, 0, 4, "gl_FragCoord"); break; + case StageInputKind::FrontFacing: + AddInput(info, kind, 0, 1, "gl_FrontFacing"); + break; + case StageInputKind::Layer: AddInput(info, kind, 0, 1, "gl_Layer"); break; + case StageInputKind::SampleId: AddInput(info, kind, 0, 1, "gl_SampleID"); break; + case StageInputKind::BaryCoordSmoothSample: + AddInput(info, StageInputKind::SampleId, 0, 1, "gl_SampleID"); + [[fallthrough]]; + case StageInputKind::BaryCoordSmooth: + case StageInputKind::BaryCoordSmoothCentroid: + AddInput(info, StageInputKind::BaryCoordSmooth, 0, 3, "gl_BaryCoordKHR"); + break; + case StageInputKind::BaryCoordNoPerspective: + AddInput(info, kind, 0, 3, "gl_BaryCoordNoPerspKHR"); + break; + case StageInputKind::WorkgroupId: + AddInput(info, kind, 0, 3, "gl_WorkGroupID"); + break; + case StageInputKind::LocalInvocationId: + AddInput(info, kind, 0, 3, "gl_LocalInvocationID"); + break; + case StageInputKind::LocalInvocationIndex: + AddInput(info, kind, 0, 1, "gl_LocalInvocationIndex"); + break; + case StageInputKind::GlobalInvocationId: + AddInput(info, kind, 0, 3, "gl_GlobalInvocationID"); + break; + case StageInputKind::PackedAncillary: + case StageInputKind::Parameter: break; + } +} + +void CollectOutput(const Program& program, ShaderStageInputInfo input_info, + ShaderInfo& info, const Inst& inst) { + const bool alpha_remap = program.stage == ShaderType::Pixel && input_info.pixel != nullptr && + input_info.pixel->alpha_blend_source != ShaderAlphaBlendSource::None; + const auto& export_info = program.export_info[inst.Flags().index]; + if (export_info.kind == ExportTargetKind::MrtZ) { + if (program.stage == ShaderType::Pixel && (export_info.en & 0x1u) != 0 && + input_info.pixel->ps_depth_export_enable) { + AddOutput(info, StageOutputKind::Depth, 0, 0, "gl_FragDepth"); + } + if (program.stage == ShaderType::Pixel && (export_info.en & 0x4u) != 0 && + input_info.pixel->ps_sample_mask_export_enable) { + AddOutput(info, StageOutputKind::SampleMask, 0, 0, "gl_SampleMask"); + } + return; + } + if (export_info.en == 0) { + return; + } + switch (export_info.kind) { + case ExportTargetKind::Position: + if (export_info.index == 0) { + AddOutput(info, StageOutputKind::Position, 0, 0, "out_position"); + break; + } + if (export_info.compr) { + return Fail("compressed auxiliary position export is unsupported"); + } + for (uint32_t component = 0; component < 4; component++) { + if ((export_info.en & (1u << component)) == 0) { + continue; + } + const auto output = DecodePositionExportComponent( + input_info.vertex->pa_cl_vs_out_cntl, export_info.index, component); + if (output.viewport) { + AddOutput(info, StageOutputKind::ViewportIndex, 0, 0, "gl_ViewportIndex"); + } + if (output.point_size) { + AddOutput(info, StageOutputKind::PointSize, 0, 0, "gl_PointSize"); + } + if (output.layer) { + AddOutput(info, StageOutputKind::Layer, 0, 0, "gl_Layer"); + } + if (output.clip_distance != UINT32_MAX) { + AddOutput(info, StageOutputKind::ClipDistance, output.clip_distance, 0, + "gl_ClipDistance"); + } + if (output.cull_distance != UINT32_MAX) { + AddOutput(info, StageOutputKind::CullDistance, output.cull_distance, 0, + "gl_CullDistance"); + } + } + break; + case ExportTargetKind::Parameter: + AddOutput(info, StageOutputKind::Parameter, export_info.index, + export_info.index, fmt::format("out_param_{}", export_info.index)); + break; + case ExportTargetKind::Mrt: { + if (alpha_remap && export_info.index != 0) { + break; + } + const auto slot = input_info.pixel->dual_source_blending + ? 0u : ShaderPixelExportTarget(input_info.pixel->target_shader_mask, + export_info.index); + if (slot >= 8) { + break; + } + AddOutput(info, StageOutputKind::Mrt, export_info.index, slot, + fmt::format("out_mrt_{}", export_info.index)); + if (alpha_remap) { + AddOutput(info, StageOutputKind::Mrt, 1, 0, "out_mrt_1"); + } + break; + } + default: break; + } +} + +struct InputUsage { + std::array components {}; + std::array per_vertex {}; + std::array user_data {}; + std::array(StageInputKind::Parameter)> builtins {}; + uint32_t builtin_mask = 0; + uint32_t builtin_count = 0; + + void AddBuiltin(StageInputKind kind) { + const auto bit = 1u << static_cast(kind); + if ((builtin_mask & bit) == 0) { + builtin_mask |= bit; + builtins[builtin_count++] = kind; + } + } +}; + +void Visit(Program& program, ShaderStageInputInfo input_info, InputUsage& inputs, + const Inst& inst) { + auto& info = program.info; + const auto op = inst.GetOpcode(); + const auto buffer_access = BufferAccessOf(op); + const auto address_access = AddressOpcodeInfoOf(op).access; + const auto shared_access = SharedAccessOf(op); + info.float64 |= inst.GetType() == Type::F64; + info.buffer_int64_atomics |= buffer_access == BufferAccess::Atomic && + inst.GetType() == Type::U64; + if (buffer_access != BufferAccess::None || address_access != AddressAccess::None || + shared_access != SharedAccess::None) { + const auto index = inst.Flags().index; + if (index >= program.memory_info.size()) { + return Fail("typed shader contains invalid memory metadata"); + } + const auto& memory = program.memory_info[index]; + const auto kind = memory.kind; + if (!memory.planning_only) { + info.uses_lds |= kind == ResourceKind::FlatLocal; + if (shared_access != SharedAccess::None) { + info.uses_lds |= kind == ResourceKind::Lds; + info.uses_gds |= kind == ResourceKind::Gds; + } else if (kind == ResourceKind::Buffer || kind == ResourceKind::ScalarBuffer) { + if (memory.resource >= info.buffers.size()) { + return Fail("buffer operation has invalid resource metadata"); + } + info.buffers[memory.resource].live = true; + for (const auto child: info.buffers[memory.resource].indirect_resources) { + if (child >= info.buffers.size()) { + return Fail("indirect buffer operation has invalid resource metadata"); + } + info.buffers[child].live = true; + } + } + } + if (address_access != AddressAccess::None) { + if (kind == ResourceKind::Scratch || kind == ResourceKind::FlatLocal) { + if (program.scratch_dwords == 0) { + return Fail("scratch operation has no per-thread storage"); + } + info.function_scratch = true; + info.function_lds |= kind == ResourceKind::FlatLocal && + program.stage != ShaderType::Compute && program.stage != ShaderType::Mesh; + } else if (address_access == AddressAccess::Write) { + return Fail("writable FLAT/GLOBAL addresses require GPU ownership tracking"); + } else { + info.coherent_buffers |= memory.coherent; + } + } + if (buffer_access != BufferAccess::None) { + if (kind == ResourceKind::IndirectBuffer && op != ValueOpcode::ReadConstBuffer) { + info.subgroup_local_invocation_id = true; + } + if (kind == ResourceKind::Buffer) { + info.coherent_buffers |= memory.coherent; + if (memory.resource >= info.buffers.size()) { + return Fail("buffer operation has invalid resource metadata"); + } + const auto collect_element = [&](uint32_t resource) { + auto selected = memory; + selected.resource = resource; + const auto bits = StorageBufferElementBits(program, selected); + info.buffer_u8 |= bits == 8u; + info.buffer_u16 |= bits == 16u; + }; + collect_element(memory.resource); + for (const auto child: info.buffers[memory.resource].indirect_resources) + collect_element(child); + if ((info.buffers[memory.resource].packed_stride & (1u << 20u)) != 0u) { + if (program.stage != ShaderType::Compute) { + return Fail("buffer ADD_TID is only valid for compute shaders"); + } + info.subgroup_local_invocation_id = true; + } + } + } + if (shared_access != SharedAccess::None) { + if (kind != ResourceKind::Lds && kind != ResourceKind::Gds) { + return Fail("shared operation has invalid resource kind"); + } + if (shared_access == SharedAccess::Atomic && SharedComponentCount(op) == 2u) { + if (kind != ResourceKind::Lds || program.stage != ShaderType::Compute) { + return Fail("64-bit shared atomics require compute LDS"); + } + info.shared_int64_atomics = true; + } + info.function_lds |= kind == ResourceKind::Lds && + program.stage != ShaderType::Compute && program.stage != ShaderType::Mesh; + if (shared_access == SharedAccess::Append || shared_access == SharedAccess::Consume) { + info.subgroup_ballot = true; + info.subgroup_shuffle = true; + info.subgroup_local_invocation_id = true; + } + } + } + switch (inst.GetOpcode()) { + case ValueOpcode::GetAttribute: { + if (!inst.Arg(0).IsImmediate() || inst.Arg(0).GetType() != Type::U32 || + !inst.Arg(1).IsImmediate() || inst.Arg(1).GetType() != Type::U32) { + return Fail("typed attribute reference is not constant"); + } + if ((program.stage == ShaderType::Vertex || + program.stage == ShaderType::Local) && + (inst.Arg(1).U32() >= 4u || + inst.Arg(0).U32() >= + static_cast(input_info.vertex->resources_num))) { + return Fail("vertex input reference is out of range"); + } + if (program.stage == ShaderType::Pixel && + (inst.Arg(1).U32() >= 4u || + inst.Arg(0).U32() >= input_info.pixel->input_num)) { + return Fail("pixel input reference is out of range"); + } + if (program.stage == ShaderType::Vertex || program.stage == ShaderType::Local || + program.stage == ShaderType::Pixel) { + auto& components = inputs.components[inst.Arg(0).U32()]; + components = std::max(components, static_cast(inst.Arg(1).U32() + 1u)); + } + break; + } + case ValueOpcode::GetInterpolationParameter: { + if (program.stage != ShaderType::Pixel || !inst.Arg(0).IsImmediate() || + inst.Arg(0).GetType() != Type::U32 || !inst.Arg(1).IsImmediate() || + inst.Arg(1).GetType() != Type::U32 || !inst.Arg(2).IsImmediate() || + inst.Arg(2).GetType() != Type::U32) { + return Fail("interpolation parameter reference is invalid"); + } + if (inst.Arg(0).U32() >= input_info.pixel->input_num || + inst.Arg(1).U32() >= 4u || inst.Arg(2).U32() >= 3u) { + return Fail("interpolation parameter reference is out of range"); + } + const auto input = inst.Arg(0).U32(); + inputs.per_vertex[input] |= inst.Arg(2).U32() < 2u || + !ShaderPixelParameterIsFlat(*input_info.pixel, input); + break; + } + case ValueOpcode::GetBuiltin: { + if (!inst.Arg(0).IsImmediate() || inst.Arg(0).GetType() != Type::U32 || + !inst.Arg(1).IsImmediate() || inst.Arg(1).GetType() != Type::U32) { + return Fail("typed builtin reference is not constant"); + } + const auto kind = static_cast(inst.Arg(0).U32()); + const auto component = inst.Arg(1).U32(); + switch (kind) { + case StageInputKind::PackedAncillary: + return Fail("packed pixel ancillary input has an unsupported live use"); + case StageInputKind::Layer: + case StageInputKind::SampleId: + if (program.stage != ShaderType::Pixel || component != 0u) { + return Fail("typed pixel scalar input is invalid"); + } + break; + case StageInputKind::VertexIndex: + case StageInputKind::InvocationId: + case StageInputKind::PrimitiveId: + case StageInputKind::InstanceIndex: + case StageInputKind::FrontFacing: + case StageInputKind::LocalInvocationIndex: + if (component != 0u) { + return Fail("typed scalar builtin component is out of range"); + } + break; + case StageInputKind::FragCoord: + if (component >= 4u) { + return Fail("typed fragment-coordinate component is out of range"); + } + break; + case StageInputKind::BaryCoordSmooth: + case StageInputKind::BaryCoordSmoothSample: + case StageInputKind::BaryCoordSmoothCentroid: + case StageInputKind::BaryCoordNoPerspective: + if (component >= 2u) { + return Fail("typed barycentric component is out of range"); + } + break; + case StageInputKind::TessCoord: + case StageInputKind::WorkgroupId: + case StageInputKind::LocalInvocationId: + case StageInputKind::GlobalInvocationId: + if (component >= 3u) { + return Fail("typed invocation builtin component is out of range"); + } + break; + case StageInputKind::Parameter: + default: return Fail("typed builtin kind is invalid"); + } + inputs.AddBuiltin(kind); + break; + } + case ValueOpcode::SetAttribute: { + const auto index = inst.Flags().index; + if (index >= program.export_info.size()) { + return Fail("typed export metadata index is out of range"); + } + const auto& exp = program.export_info[index]; + if (exp.kind == ExportTargetKind::Position && exp.index != 0 && exp.en != 0 && + program.stage != ShaderType::Vertex && program.stage != ShaderType::Mesh && + program.stage != ShaderType::TessellationEvaluation) { + return Fail("auxiliary position export requires a vertex, mesh, or " + "tessellation evaluation shader"); + } + info.pixel_valid_mask |= program.stage == ShaderType::Pixel && exp.vm; + CollectOutput(program, input_info, info, inst); + break; + } + case ValueOpcode::GetUserData: { + if (!inst.HasUses()) break; + if (inst.Arg(0).GetType() != Type::ScalarReg) { + return Fail("typed shader contains an invalid user-data register"); + } + const auto index = RegIndex(inst.Arg(0).ScalarRegister()); + if (index >= NumScalarRegs) { + return Fail("typed shader contains an invalid user-data register"); + } + inputs.user_data[index] = true; + break; + } + case ValueOpcode::GetDispatchThreadExtent: + info.uses_dispatch_threads |= inst.HasUses(); + break; + case ValueOpcode::ReadConst: info.uses_flattened_srt = true; break; + case ValueOpcode::BitwiseXor32: info.has_bitwise_xor = true; break; + case ValueOpcode::StoreCompletion: info.subgroup_barrier = true; break; + case ValueOpcode::BvhIntersect: info.bvh = true; break; + case ValueOpcode::ConditionRef: + if (inst.Flags() != CFG::BranchCondition::ScalarInstruction) { + info.subgroup_vote = true; + if (program.wave_size == 32u && + (program.stage == ShaderType::Vertex || program.stage == ShaderType::Local || + program.stage == ShaderType::TessellationEvaluation)) { + info.subgroup_ballot = true; + info.subgroup_local_invocation_id = true; + } + } + break; + case ValueOpcode::Ballot: info.subgroup_ballot = true; break; + case ValueOpcode::SubgroupUMinU32: info.subgroup_arithmetic = true; break; + case ValueOpcode::DppMoveU32: + case ValueOpcode::ReadFirstLane: + case ValueOpcode::ReadLane: { + info.subgroup_ballot = true; + info.subgroup_shuffle = true; + if (inst.GetOpcode() == ValueOpcode::DppMoveU32) { + info.subgroup_local_invocation_id = true; + } + break; + } + case ValueOpcode::DppUpdateU32: + case ValueOpcode::WriteLane: { + info.subgroup_ballot = true; + info.subgroup_local_invocation_id = true; + break; + } + case ValueOpcode::SwizzleU32: + info.uses_swizzle = true; + [[fallthrough]]; + case ValueOpcode::Permlane16U32: + case ValueOpcode::PermuteU32: + case ValueOpcode::BpermuteU32: { + info.subgroup_ballot = true; + info.subgroup_shuffle = true; + info.subgroup_local_invocation_id = true; + break; + } + case ValueOpcode::LaneId: + if (program.stage == ShaderType::TessellationControl) { + inputs.AddBuiltin(StageInputKind::InvocationId); + } else { + info.subgroup_local_invocation_id = true; + } + break; + case ValueOpcode::ImageQueryLod: info.compute_derivatives = true; break; + case ValueOpcode::ImageGatherRaw: + info.image_gather_extended = true; + break; + default: break; + } +} + +} // namespace + +void CollectShaderInfo(Program& program, ShaderStageInputInfo input_info) { + if (!program.resource_tracking_complete || program.shader_info_complete) { + return Fail(!program.resource_tracking_complete ? "shader resources were not tracked" + : "shader info already collected"); + } + ValidateOptions(program, input_info); + auto& info = program.info; + info.inputs.clear(); + info.outputs.clear(); + info.user_data_registers.clear(); + for (auto& buffer: info.buffers) buffer.live = false; + info.has_bitwise_xor = info.uses_lds = info.uses_gds = info.uses_flattened_srt = + info.uses_dispatch_threads = info.uses_swizzle = false; + info.bvh = info.subgroup_ballot = info.subgroup_vote = info.subgroup_barrier = + info.subgroup_shuffle = info.subgroup_arithmetic = + info.subgroup_local_invocation_id = info.compute_derivatives = info.image_gather_extended = + info.function_lds = info.function_scratch = info.pixel_valid_mask = info.buffer_int64_atomics = + info.buffer_u8 = info.buffer_u16 = info.shared_int64_atomics = info.coherent_buffers = info.float64 = false; + InputUsage inputs; + for (const auto* block: program.blocks) { + for (const auto& inst: *block) { + Visit(program, input_info, inputs, inst); + } + } + for (uint32_t index = 0; index < inputs.user_data.size(); index++) { + if (inputs.user_data[index]) info.user_data_registers.push_back(index); + } + const auto uses_mapping = [](const auto& resource) { + return resource.indirect_root != UINT32_MAX; + }; + info.uses_flattened_srt |= std::ranges::any_of(info.buffers, uses_mapping) || + std::ranges::any_of(info.images, uses_mapping); + switch (program.stage) { + case ShaderType::Vertex: + case ShaderType::Local: CollectVertexInputs(input_info.vertex, info, inputs.components); break; + case ShaderType::TessellationControl: + case ShaderType::TessellationEvaluation: + case ShaderType::Mesh: break; + case ShaderType::Pixel: + CollectPixelInputs(input_info.pixel, info, inputs.per_vertex, inputs.components); + if (input_info.pixel->object_primitive_id) { + if (std::ranges::any_of(info.outputs, [](const StageOutput& output) { + return output.kind == StageOutputKind::Mrt && output.location == 7u; + })) { + return Fail("explicit MRT7 export overlaps automatic object/primitive ID"); + } + AddBuiltinInput(info, StageInputKind::PrimitiveId); + AddOutput(info, StageOutputKind::ObjectPrimitiveId, 0, 7, "out_object_primitive_id"); + } + break; + case ShaderType::Compute: CollectComputeInputs(input_info.compute, info); break; + default: return Fail("unsupported shader stage for info collection"); + } + for (uint32_t i = 0; i < inputs.builtin_count; i++) { + AddBuiltinInput(info, inputs.builtins[i]); + } + program.shader_info_complete = true; +} + +} // namespace Libs::Graphics::ShaderRecompiler::IR diff --git a/src/graphics/shader/shader.cpp b/src/graphics/shader/shader.cpp index b78d6e74..1ef54177 100644 --- a/src/graphics/shader/shader.cpp +++ b/src/graphics/shader/shader.cpp @@ -1,781 +1,784 @@ -#include "graphics/shader/shader.h" - -#include "common/assert.h" -#include "common/common.h" -#include "common/emulatorConfig.h" -#include "common/logging/log.h" -#include "common/profiler.h" -#include "common/stringUtils.h" -#include "graphics/guest_gpu/gpu_defs.h" -#include "graphics/guest_gpu/graphicsRun.h" -#include "graphics/guest_gpu/hardwareContext.h" -#include "graphics/host_gpu/renderer/renderContext.h" -#include "graphics/shader/recompiler/ShaderRecompiler.h" -#include "graphics/shader/recompiler/Tessellation.h" -#include "graphics/shader/recompiler/frontend/decode/ShaderDecoder.h" -#include "graphics/shader/shaderCompiler.h" -#include "graphics/shader/shaderVertexMetadata.h" -#include "libs/errno.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include -#undef min -#undef max -#endif - -namespace Libs::Graphics { - -struct ShaderMapEntry { - ShaderMappedData data; - uint64_t hash; -}; - -static std::unique_ptr> g_shader_map; -static std::mutex g_shader_map_mutex; - -void ShaderInit() { - EXIT_IF(g_shader_map != nullptr); - - g_shader_map = std::make_unique>(); -} - -void ShaderMapUserData(uint64_t addr, const ShaderMappedData& data) { - EXIT_IF(g_shader_map == nullptr); - - if (addr == 0 || data.code_size_bytes == 0 || data.code_size_bytes % sizeof(uint32_t) != 0) { - EXIT("ShaderMapUserData shader=0x%016" PRIx64 " has invalid AGC shader_size=0x%08" PRIx32 "\n", - addr, data.code_size_bytes); - } - const auto hash = XXH3_64bits(reinterpret_cast(addr), data.code_size_bytes); - std::scoped_lock lock(g_shader_map_mutex); - (*g_shader_map)[addr] = {data, hash}; -} - -static ShaderMapEntry ShaderGetMappedData(uint64_t addr, const char* label) { - EXIT_IF(g_shader_map == nullptr); - - std::scoped_lock lock(g_shader_map_mutex); - - if (auto iter = g_shader_map->find(addr); iter != g_shader_map->end()) { - return iter->second; - } - - EXIT("%s shader=0x%016" PRIx64 " is missing from ShaderMap\n", label, addr); -} - -static ShaderParams GetShaderParams(uint64_t shader_addr, uint64_t hash, - std::span user_data, - const ShaderMappedData& data, uint32_t user_data_base = 0) { - const auto code_words = data.code_size_bytes / sizeof(uint32_t); - const auto code = std::span {reinterpret_cast(shader_addr), code_words}; - ShaderParams params { - .code = code, - .user_data_count = static_cast(user_data.size()) + user_data_base, - .hash = hash, - }; - EXIT_IF(user_data.size() > HW::UserSgprInfo::SGPRS_MAX || - params.user_data_count > params.user_data.size()); - std::copy(user_data.begin(), user_data.end(), params.user_data.begin() + user_data_base); - return params; -} - -static void ShaderDetectBuffers(ShaderVertexInputInfo& info) { - KYTY_PROFILER_FUNCTION(); - - info.buffers_num = 0; - - for (int ri = 0; ri < info.resources_num; ri++) { - const auto& r = info.resources[ri]; - - auto& destination = info.resources_dst[ri]; - int bi = 0; - for (; bi < info.buffers_num; bi++) { - auto& b = info.buffers[bi]; - - uint64_t stride = b.stride; - - if (stride == r.Stride() && - b.fetch_index == destination.fetch_index) { - uint64_t rbase = r.Base48(); - uint64_t base = std::min(rbase, b.addr); - uint64_t offset1 = rbase - base; - uint64_t offset2 = b.addr - base; - - if (offset1 < stride && offset2 < stride) { - EXIT_NOT_IMPLEMENTED(b.num_records != r.NumRecords()); - b.addr = base; - break; - } - } - } - - if (bi == info.buffers_num) { - EXIT_NOT_IMPLEMENTED(info.buffers_num >= ShaderVertexInputInfo::RES_MAX); - info.buffers[bi] = {.addr = r.Base48(), - .stride = r.Stride(), - .num_records = r.NumRecords(), - .fetch_index = destination.fetch_index}; - info.buffers_num++; - } - destination.buffer_index = bi; - } -} - -static void ShaderApplyAttribSemantics(ShaderVertexInputInfo& info, - std::span input_semantics, - const uint32_t* attrib, const uint32_t* buffer) { - KYTY_PROFILER_FUNCTION(); - - EXIT_IF(attrib == nullptr || buffer == nullptr); - - const bool debug_dump = Config::GraphicsDebugDumpEnabled(); - - for (uint32_t i = 0; i < input_semantics.size(); i++) { - const auto& in = input_semantics[i]; - - EXIT_NOT_IMPLEMENTED(in.static_vb_index == 1 || in.static_attribute == 1); - - uint32_t reg = in.hardware_mapping; - uint32_t size = in.size_in_elements; - - if (debug_dump) { - LOGF("reg = %u, size = %u, va[%u] = 0x%08" PRIx32 "\n", reg, size, i, - attrib[in.semantic]); - } - - size_t index = attrib[in.semantic] & 0x1fu; - auto format = - static_cast((attrib[in.semantic] >> 5u) & 0x1ffu); - uint32_t offset = (attrib[in.semantic] >> 14u) & 0xfffu; - uint32_t fetch_index = (attrib[in.semantic] >> 26u) & 0x1u; - - EXIT_NOT_IMPLEMENTED(index >= ShaderVertexInputInfo::RES_MAX); - - const auto* sharp = &buffer[index * 4]; - - EXIT_NOT_IMPLEMENTED(info.resources_num >= ShaderVertexInputInfo::RES_MAX); - - auto& r = info.resources[info.resources_num]; - auto& rd = info.resources_dst[info.resources_num]; - rd.register_start = static_cast(reg); - rd.registers_num = static_cast(size); - rd.attr_id = static_cast(in.semantic); - rd.fetch_index = fetch_index; - r.fields[0] = sharp[0]; - r.fields[1] = sharp[1]; - r.fields[2] = sharp[2]; - r.fields[3] = sharp[3]; - EXIT_NOT_IMPLEMENTED(r.AddTid()); - EXIT_NOT_IMPLEMENTED(r.SwizzleEnabled()); - if (format != Prospero::VertexAttribFormat::kInvalid) { - const auto format_raw = static_cast(format); - const auto buffer_format = format_raw >> 2u; - const auto channels = (format_raw & 3u) + 1u; - // AGC vertex formats encode the buffer format above the two channel-count bits. - // The fetch prolog selects X001, XY01, XYZ1, or XYZW from that count. - r.fields[3] = (r.fields[3] & ~((0x7fu << 12u) | 0xfffu)) | - (buffer_format << 12u) | - DstSel(4, channels > 1u ? 5u : 0u, channels > 2u ? 6u : 0u, - channels > 3u ? 7u : 1u); - } - if (offset != 0) { - r.UpdateAddress48(r.Base48() + offset); - } - - info.resources_num++; - } -} - -static uint32_t ShaderCalcPsSystemInputBase(const HW::ShaderRegisters& regs) { - constexpr uint32_t ps_input_persp_sample = 0x00000001u; - constexpr uint32_t ps_input_persp_center = 0x00000002u; - constexpr uint32_t ps_input_persp_centroid = 0x00000004u; - constexpr uint32_t ps_input_persp_pull = 0x00000008u; - constexpr uint32_t ps_input_linear_sample = 0x00000010u; - constexpr uint32_t ps_input_linear_center = 0x00000020u; - constexpr uint32_t ps_input_linear_centroid = 0x00000040u; - constexpr uint32_t ps_input_line_stipple = 0x00000080u; - constexpr uint32_t ps_input_pos_xy = 0x00000300u; - constexpr uint32_t ps_input_pos_z = 0x00000400u; - constexpr uint32_t ps_input_pos_w = 0x00000800u; - constexpr uint32_t ps_input_front_face = 0x00001000u; - constexpr uint32_t ps_input_ancillary = 0x00002000u; - constexpr uint32_t ps_input_sample_coverage = 0x00004000u; - constexpr uint32_t ps_input_pos_fixed_pt = 0x00008000u; - constexpr uint32_t supported_ps_input_bits = - ps_input_persp_sample | ps_input_persp_center | ps_input_persp_centroid | - ps_input_persp_pull | ps_input_linear_sample | ps_input_linear_center | - ps_input_linear_centroid | ps_input_line_stipple | ps_input_pos_xy | ps_input_pos_z | - ps_input_pos_w | ps_input_front_face | ps_input_ancillary | ps_input_sample_coverage | - ps_input_pos_fixed_pt; - - EXIT_NOT_IMPLEMENTED((regs.ps_input_ena & ~supported_ps_input_bits) != 0); - EXIT_NOT_IMPLEMENTED((regs.ps_input_addr & ~supported_ps_input_bits) != 0); - EXIT_NOT_IMPLEMENTED(regs.ps_input_ena != regs.ps_input_addr); - - const uint32_t inputs = regs.ps_input_addr; - uint32_t reg = 0; - if ((inputs & ps_input_persp_sample) != 0) { - reg += 2; - } - if ((inputs & ps_input_persp_center) != 0) { - reg += 2; - } - if ((inputs & ps_input_persp_centroid) != 0) { - reg += 2; - } - if ((inputs & ps_input_persp_pull) != 0) { - reg += 3; - } - if ((inputs & ps_input_linear_sample) != 0) { - reg += 2; - } - if ((inputs & ps_input_linear_center) != 0) { - reg += 2; - } - if ((inputs & ps_input_linear_centroid) != 0) { - reg += 2; - } - if ((inputs & ps_input_line_stipple) != 0) { - reg += 1; - } - return reg; -} - -static bool ShaderGetStaticVertexInputInfo(uint64_t shader_addr, const HW::UserSgprInfo& user_sgpr, - uint32_t user_sgpr_num, const HW::ShaderRegisters& sh, - const ShaderMappedData& data, - ShaderVertexInputInfo& info) { - KYTY_PROFILER_FUNCTION(); - - info = {}; - - info.pa_cl_vs_out_cntl = sh.m_paClVsOutCntl; - - EXIT_NOT_IMPLEMENTED(shader_addr == 0); - info.scratch_size_dwords = data.scratch_size_dwords; - - if (data.user_data == nullptr) { - LOGF("ShaderGetVertexInputInfo(): no AGC user data for shader=0x%016" PRIx64 - " user_sgpr_num=%u\n", - shader_addr, user_sgpr_num); - } - ShaderVertexMetadata metadata; - std::string metadata_error; - if (!ShaderReadVertexMetadata(data, HW::UserSgprInfo::SGPRS_MAX, metadata, &metadata_error)) { - LOGF("ShaderGetVertexInputInfo(): invalid AGC metadata shader=0x%016" PRIx64 ": %s\n", - shader_addr, metadata_error.c_str()); - return false; - } - - if (metadata.vertex_attrib_reg >= 0) { - info.fetch_external = false; - info.fetch_embedded = true; - info.fetch_attrib_reg = metadata.vertex_attrib_reg; - info.fetch_buffer_reg = metadata.vertex_buffer_reg; - - const auto* attrib = reinterpret_cast( - static_cast(user_sgpr.value[metadata.vertex_attrib_reg]) | - (static_cast(user_sgpr.value[metadata.vertex_attrib_reg + 1]) << 32u)); - const auto* buffer = reinterpret_cast( - static_cast(user_sgpr.value[metadata.vertex_buffer_reg]) | - (static_cast(user_sgpr.value[metadata.vertex_buffer_reg + 1]) << 32u)); - - if (attrib == nullptr || buffer == nullptr) { - LOGF("ShaderGetVertexInputInfo(): null vertex table pointer shader=0x%016" PRIx64 "\n", - shader_addr); - return false; - } - ShaderApplyAttribSemantics(info, metadata.input_semantics, attrib, buffer); - ShaderDetectBuffers(info); - } - return true; -} - -static void ShaderGetStaticInputInfoPS( - const HW::PixelShaderInfo& regs, const HW::ShaderRegisters& sh, - std::span target_export_mapping, - const ShaderMappedData& data, ShaderPixelInputInfo& ps_info) { - KYTY_PROFILER_FUNCTION(); - - ps_info = {}; - ps_info.scratch_size_dwords = data.scratch_size_dwords; - - // SPI_PS_IN_CONTROL: NUM_INTERP occupies bits 5:0 and PS_W32_EN is bit 15. - ps_info.input_num = sh.ps_in_control & 0x3fu; - if ((sh.ps_in_control & 0x8000u) != 0) { - ps_info.wave_size = 32; - } - EXIT_NOT_IMPLEMENTED(ps_info.input_num > std::size(ps_info.interpolator_settings)); - ps_info.ps_system_input_base = ShaderCalcPsSystemInputBase(sh); - const uint32_t active_inputs = sh.ps_input_ena & sh.ps_input_addr; - if ((active_inputs & 0x00000001u) != 0) { - ps_info.ps_perspective_sample_vgpr = 0; - } - if ((active_inputs & 0x00000002u) != 0) { - ps_info.ps_perspective_center_vgpr = (active_inputs & 0x00000001u) != 0 ? 2u : 0u; - } - if ((active_inputs & 0x00000004u) != 0) { - ps_info.ps_perspective_centroid_vgpr = 2u * std::popcount(active_inputs & 0x3u); - } - for (uint32_t i = 0; i < data.num_input_semantics && i < ps_info.input_num && i < 32u; i++) { - const auto& semantic = data.input_semantics[i]; - if (semantic.is_custom != 0 && semantic.is_f16 == 0) { - ps_info.custom_interpolation_mask |= 1u << i; - } - } - ps_info.ps_pos_x = (active_inputs & 0x00000100u) != 0; - ps_info.ps_pos_y = (active_inputs & 0x00000200u) != 0; - ps_info.ps_pos_z = (active_inputs & 0x00000400u) != 0; - ps_info.ps_pos_w = (active_inputs & 0x00000800u) != 0; - ps_info.ps_front_face = (active_inputs & 0x00001000u) != 0; - // SPI_BARYC_CNTL.FRONT_FACE_ALL_BITS selects integer masks instead of float +/-1. - ps_info.ps_front_face_all_bits = (sh.baryc_cntl & 0x01000000u) != 0; - ps_info.ps_ancillary = (active_inputs & 0x00002000u) != 0; - ps_info.ps_sample_shading = (active_inputs & 0x00000011u) != 0; - ps_info.ps_no_perspective = (sh.ps_input_ena & sh.ps_input_addr & 0x00000020u) != 0; - ps_info.ps_pixel_kill_enable = sh.db_shader_control.shader_kill_enable; - ps_info.ps_depth_export_enable = sh.db_shader_control.shader_z_export_enable; - ps_info.ps_sample_mask_export_enable = sh.db_shader_control.shader_mask_export_enable; - ps_info.ps_early_z = - (sh.db_shader_control.shader_z_behavior == 1 && !sh.db_shader_control.shader_kill_enable && - !sh.db_shader_control.shader_z_export_enable && - !sh.db_shader_control.shader_mask_export_enable); - ps_info.ps_execute_on_noop = sh.db_shader_control.shader_execute_on_noop; - - for (uint32_t i = 0; i < ps_info.input_num; i++) { - ps_info.interpolator_settings[i] = sh.ps_interpolator_settings[i]; - } - - ps_info.target_shader_mask = sh.m_cbShaderMask; - for (int i = 0; i < 8; i++) { - const auto slot = ShaderPixelExportTarget(ps_info.target_shader_mask, i); - ps_info.target_output_mode[i] = sh.target_output_mode[i]; - ps_info.target_export_mapping[i] = sh.target_output_mode[i] != 0 && slot < 8 - ? target_export_mapping[slot] - : Prospero::ColorComponentMapping {}; - } -} - -static void ShaderGetStaticInputInfoCS(const HW::ComputeShaderInfo& regs, - const HW::ShaderRegisters& /*sh*/, - const ShaderMappedData& data, ShaderComputeInputInfo& info) { - const bool async_compute = info.async_compute; - const bool dispatch_thread_dimensions = info.dispatch_thread_dimensions; - const auto host_subgroup_size = info.host_subgroup_size; - const auto workgroup_counts = std::to_array(info.workgroup_counts); - const auto indirect_args_address = info.indirect_args_address; - info = {}; - info.async_compute = async_compute; - info.dispatch_thread_dimensions = dispatch_thread_dimensions; - info.host_subgroup_size = host_subgroup_size; - std::ranges::copy(workgroup_counts, info.workgroup_counts); - info.indirect_args_address = indirect_args_address; - info.threads_num[0] = regs.cs_regs.num_thread_x; - info.threads_num[1] = regs.cs_regs.num_thread_y; - info.threads_num[2] = regs.cs_regs.num_thread_z; - info.lds_size_dwords = static_cast(regs.cs_regs.lds_size) * 128u; - info.scratch_size_dwords = data.scratch_size_dwords; - info.float_mode = regs.cs_regs.float_mode; - info.group_id[0] = regs.cs_regs.tgid_x_en != 0; - info.group_id[1] = regs.cs_regs.tgid_y_en != 0; - info.group_id[2] = regs.cs_regs.tgid_z_en != 0; - info.wave_size = regs.cs_regs.wave_size; - info.thread_ids_num = regs.cs_regs.tidig_comp_cnt + 1; - info.tg_size_en = regs.cs_regs.tg_size_en != 0; - - info.workgroup_register = regs.cs_regs.user_sgpr; -} - -void BuildStageStaticKey(const ShaderVertexInputInfo& info, std::vector& key) { - EXIT_IF(info.resources_num < 0 || info.resources_num > ShaderVertexInputInfo::RES_MAX); - key.clear(); - key.push_back(static_cast(info.fetch_embedded)); - key.push_back(static_cast(info.fetch_attrib_reg)); - key.push_back(static_cast(info.fetch_buffer_reg)); - key.push_back(info.resources_num); - key.push_back(info.wave_size); - key.push_back(info.scratch_size_dwords); - key.push_back(info.pa_cl_vs_out_cntl); - key.push_back(static_cast(info.clip_space.enabled)); - if (info.clip_space.enabled) { - for (const float value: info.clip_space.scale) { - key.push_back(std::bit_cast(value)); - } - for (const float value: info.clip_space.offset) { - key.push_back(std::bit_cast(value)); - } - for (const float value: info.clip_space.half_extent) { - key.push_back(std::bit_cast(value)); - } - } - - key.push_back(info.mesh.threads_num[0]); - if (info.mesh.threads_num[0] != 0) { - const auto& mesh = info.mesh; - key.insert(key.end(), {mesh.wave_size, mesh.host_subgroup_size, mesh.lds_size_dwords, - mesh.scratch_size_dwords, mesh.input_primitive, - mesh.primitives_per_group, mesh.vertices_per_group, - mesh.max_vertices, mesh.max_primitives, mesh.provoking_vertex, - static_cast(mesh.fast_launch)}); - } - key.push_back(info.tess.input_control_points); - if (info.tess.input_control_points != 0) { - const auto& tess = info.tess; - key.insert(key.end(), {tess.output_control_points, tess.ls_stride, tess.hs_stride, - tess.domain, tess.partitioning, tess.output_topology}); - } - - for (int i = 0; i < info.resources_num; i++) { - const auto& resource = info.resources[i]; - const auto& destination = info.resources_dst[i]; - key.push_back(destination.registers_num); - key.push_back(static_cast(destination.attr_id)); - key.push_back(resource.fields[3] & 0x7ffffu); // Channels and format used by embedded fetch. - } -} - -void BuildStageStaticKey(const ShaderPixelInputInfo& info, std::vector& key) { - EXIT_IF(info.input_num > std::size(info.interpolator_settings)); - key.clear(); - key.push_back(info.scratch_size_dwords); - key.push_back(info.input_num); - key.push_back(info.wave_size); - key.push_back(info.ps_system_input_base); - key.push_back(info.custom_interpolation_mask); - key.push_back(info.ps_perspective_center_vgpr); - key.push_back(info.ps_perspective_sample_vgpr); - key.push_back(info.ps_perspective_centroid_vgpr); - key.push_back(static_cast(info.ps_pos_x)); - key.push_back(static_cast(info.ps_pos_y)); - key.push_back(static_cast(info.ps_pos_z)); - key.push_back(static_cast(info.ps_pos_w)); - key.push_back(static_cast(info.ps_front_face)); - key.push_back(static_cast(info.ps_front_face_all_bits)); - key.push_back(static_cast(info.ps_ancillary)); - key.push_back(static_cast(info.ps_no_perspective)); - key.push_back(static_cast(info.parameter_mode)); - key.push_back(static_cast(info.ps_pixel_kill_enable)); - key.push_back(static_cast(info.ps_depth_export_enable)); - key.push_back(static_cast(info.ps_sample_mask_export_enable)); - key.push_back(static_cast(info.ps_early_z)); - key.push_back(static_cast(info.dual_source_blending)); - key.push_back(static_cast(info.object_primitive_id)); - key.push_back(static_cast(info.alpha_blend_source)); - key.insert(key.end(), std::begin(info.target_output_mode), std::end(info.target_output_mode)); - key.push_back(info.target_packed_unorm_mask | (uint32_t {info.target_round_mode} << 8u)); - const auto mask = info.target_shader_mask; - key.push_back((mask | (mask >> 1u) | (mask >> 2u) | (mask >> 3u)) & 0x11111111u); - for (uint32_t base = 0; base < info.target_export_mapping.size(); base += 4u) { - uint32_t packed = 0; - for (uint32_t i = 0; i < 4u; i++) { - packed |= static_cast(info.target_export_mapping[base + i].packed) - << (i * 8u); - } - key.push_back(packed); - } - key.insert(key.end(), std::begin(info.interpolator_settings), - std::begin(info.interpolator_settings) + info.input_num); -} - -void BuildStageStaticKey(const ShaderComputeInputInfo& info, std::vector& key) { - key.clear(); - key.push_back(info.workgroup_register); - key.push_back(info.wave_size | (static_cast(info.float_mode) << 8u)); - key.push_back(info.host_subgroup_size); - key.push_back(info.thread_ids_num); - key.push_back(info.lds_size_dwords); - key.push_back(info.scratch_size_dwords); - key.push_back(static_cast(info.dispatch_thread_dimensions) | - (static_cast(info.async_compute) << 1u)); - for (int i = 0; i < 3; i++) { - key.push_back(info.threads_num[i]); - key.push_back(static_cast(info.group_id[i])); - } - key.push_back(static_cast(info.tg_size_en)); -} - -ShaderParams PrepareProgram(const HW::VertexShaderInfo& regs, const HW::Context& context, - const HW::UserConfig& user_config, ShaderVertexInputInfo& info) { - const auto& sh = context.GetShaderRegisters(); - const auto [data, hash] = ShaderGetMappedData(regs.es_regs.data_addr, "ShaderGetInputInfoVS():"); - const bool merged = (context.GetShaderStages() & 0x20u) != 0; - // GS_EN controls amplification, not whether an NGG shader uses a workgroup. - const bool native_ngg = !merged && data.type == Prospero::ShaderBinaryType::kGs && - regs.gs_regs.rsrc2.lds_size != 0; - auto params = GetShaderParams( - regs.es_regs.data_addr, hash, - std::span(regs.gs_user_sgpr.value, regs.gs_regs.rsrc2.user_sgpr), data, - merged || native_ngg ? 8u : 0u); - if (!merged && !native_ngg) { - if (!ShaderGetStaticVertexInputInfo(regs.es_regs.data_addr, regs.gs_user_sgpr, - regs.gs_regs.rsrc2.user_sgpr, sh, data, info)) { - EXIT("failed to prepare vertex shader program\n"); - } - info.wave_size = (context.GetShaderStages() & 0x00400000u) != 0 ? 32u : 64u; - return params; - } - // NGG user SGPRs start at s8; a separately compiled GS back half also receives - // its user-data pointer in s0:s1. - info = {}; - info.logical_stage = ShaderType::Mesh; - info.pa_cl_vs_out_cntl = sh.m_paClVsOutCntl; - auto& mesh = info.mesh; - mesh.input_primitive = static_cast(user_config.GetPrimType()); - mesh.wave_size = (context.GetShaderStages() & 0x00400000u) != 0 ? 32u : 64u; - mesh.max_vertices = sh.m_geMaxOutputPerSubgroup; - mesh.provoking_vertex = context.GetModeControl().provoking_vtx_last ? 2u : 0u; - mesh.lds_size_dwords = static_cast(regs.gs_regs.rsrc2.lds_size) * 128u; - mesh.scratch_size_dwords = data.scratch_size_dwords; - const auto fast_launch = (context.GetShaderStages() >> 19u) & 3u; - EXIT_NOT_IMPLEMENTED(fast_launch > 1u); - mesh.fast_launch = fast_launch != 0; - if (data.type == Prospero::ShaderBinaryType::kGsFront) { - EXIT_IF(regs.gs_regs.data_addr == 0); - const auto [back, back_hash] = ShaderGetMappedData(regs.gs_regs.data_addr, "ShaderGetInputInfoGS():"); - const auto back_params = - GetShaderParams(regs.gs_regs.data_addr, back_hash, {}, back); - params.back_code = back_params.code; - params.user_data[0] = static_cast(regs.gs_regs.user_data_addr); - params.user_data[1] = static_cast(regs.gs_regs.user_data_addr >> 32u); - const uint64_t hashes[] = {params.hash, back_params.hash}; - params.hash = XXH3_64bits(hashes, sizeof(hashes)); - mesh.scratch_size_dwords = std::max(mesh.scratch_size_dwords, back.scratch_size_dwords); - } - const auto& group = user_config.GetGeControl(); - if (mesh.fast_launch) { - const auto& user_vgpr = user_config.GetGeUserVgprEn(); - EXIT_NOT_IMPLEMENTED(data.type != Prospero::ShaderBinaryType::kGs || - regs.gs_regs.rsrc1.gs_vgpr_component_count != 0u || - regs.gs_regs.rsrc2.es_vgpr_component_count != 1u || - user_config.GetPrimType() != Prospero::PrimitiveType::kPointList || - group.primitive_group_size != 1u || group.vertex_group_size != 1u || - user_vgpr.vgpr1 || user_vgpr.vgpr2 || user_vgpr.vgpr3 || - mesh.max_vertices != sh.m_vgtGsMaxVertOut); - } else if (merged) { - EXIT_NOT_IMPLEMENTED(regs.gs_regs.rsrc1.gs_vgpr_component_count != 3u || - regs.gs_regs.rsrc2.es_vgpr_component_count != 3u); - } - if ((user_config.GetPrimType() != Prospero::PrimitiveType::kPointList && - user_config.GetPrimType() != Prospero::PrimitiveType::kLineList && - user_config.GetPrimType() != Prospero::PrimitiveType::kTriFan && - user_config.GetPrimType() != Prospero::PrimitiveType::kTriStrip && - user_config.GetPrimType() != Prospero::PrimitiveType::kTriList) || - sh.m_vgtGsOutPrimType != 2u || (!native_ngg && sh.m_vgtGsMaxVertOut < 3u) || - group.vertex_group_size < mesh.InputPrimitiveSize() || - mesh.max_vertices == 0u) { - EXIT("unsupported GS assembly: input=%u output=%u vertices=%u GE=%u/%u max_output=%u\n", - mesh.input_primitive, sh.m_vgtGsOutPrimType, sh.m_vgtGsMaxVertOut, - group.primitive_group_size, group.vertex_group_size, mesh.max_vertices); - } - mesh.max_primitives = mesh.fast_launch ? mesh.max_vertices : - native_ngg ? mesh.InputPrimitiveCount(mesh.max_vertices) : - group.primitive_group_size * (sh.m_vgtGsMaxVertOut - 2u); - mesh.primitives_per_group = std::min({static_cast(group.primitive_group_size), - mesh.InputPrimitiveCount(group.vertex_group_size), - native_ngg ? mesh.max_primitives : - mesh.max_vertices / sh.m_vgtGsMaxVertOut}); - EXIT_IF(mesh.primitives_per_group == 0u); - mesh.vertices_per_group = mesh.InputVertexCount(mesh.primitives_per_group); - const auto threads = native_ngg && !mesh.fast_launch ? mesh.vertices_per_group : mesh.max_vertices; - mesh.threads_num[0] = ((threads + mesh.wave_size - 1u) / mesh.wave_size) * mesh.wave_size; - mesh.threads_num[1] = mesh.threads_num[2] = 1u; - return params; -} - -std::array -PrepareTessellationPrograms(const HW::VertexShaderInfo& regs, const HW::Context& context, - std::array& input_info) { - const auto& sh = context.GetShaderRegisters(); - const auto [local, local_hash] = ShaderGetMappedData(regs.ls_regs.data_addr, "ShaderGetInputInfoLS():"); - const auto [control, control_hash] = ShaderGetMappedData(regs.hs_regs.data_addr, "ShaderGetInputInfoHS():"); - const auto [evaluation, evaluation_hash] = ShaderGetMappedData(regs.es_regs.data_addr, "ShaderGetInputInfoTES():"); - EXIT_NOT_IMPLEMENTED(local.type != Prospero::ShaderBinaryType::kHsFront || - control.type != Prospero::ShaderBinaryType::kHsBack || - evaluation.type != Prospero::ShaderBinaryType::kGs); - EXIT_NOT_IMPLEMENTED((context.GetShaderStages() & 0x4u) == 0 || - (context.GetShaderStages() & 0x00600020u) != 0); - EXIT_IF(regs.hs_regs.user_data_addr == 0); - - const auto local_users = std::span(regs.hs_user_sgpr.value, regs.hs_regs.rsrc2.user_sgpr); - const auto evaluation_users = std::span(regs.gs_user_sgpr.value, regs.gs_regs.rsrc2.user_sgpr); - std::array params { - GetShaderParams(regs.ls_regs.data_addr, local_hash, local_users, local), - GetShaderParams(regs.hs_regs.data_addr, control_hash, local_users, control, 8u), - GetShaderParams(regs.es_regs.data_addr, evaluation_hash, evaluation_users, - evaluation), - }; - // The fused HS back half receives its separate user-data address in s0:s1. - // RDNA2 reserves s0:s7 before the native HS user SGPRs. - params[1].user_data[0] = static_cast(regs.hs_regs.user_data_addr); - params[1].user_data[1] = static_cast(regs.hs_regs.user_data_addr >> 32u); - - input_info = {}; - if (!ShaderGetStaticVertexInputInfo(regs.ls_regs.data_addr, regs.hs_user_sgpr, - regs.hs_regs.rsrc2.user_sgpr, sh, local, input_info[0])) { - EXIT("failed to prepare local shader program\n"); - } - input_info[0].logical_stage = ShaderType::Local; - input_info[1].logical_stage = ShaderType::TessellationControl; - input_info[1].scratch_size_dwords = control.scratch_size_dwords; - input_info[2].logical_stage = ShaderType::TessellationEvaluation; - input_info[2].scratch_size_dwords = evaluation.scratch_size_dwords; - input_info[2].pa_cl_vs_out_cntl = sh.m_paClVsOutCntl; - - ShaderTessellationInputInfo tess { - .input_control_points = (sh.m_vgtLsHsConfig >> 8u) & 0x3fu, - .output_control_points = (sh.m_vgtLsHsConfig >> 14u) & 0x3fu, - .domain = sh.m_vgtTfParam & 0x3u, - .partitioning = (sh.m_vgtTfParam >> 2u) & 0x3u, - .output_topology = (sh.m_vgtTfParam >> 5u) & 0x3u, - }; - EXIT_IF(tess.input_control_points == 0 || tess.input_control_points > 32 || - tess.output_control_points == 0 || tess.output_control_points > 32); - ShaderRecompiler::AnalyzeTessellationPrograms(params[0].code, params[1].code, tess); - for (auto& stage: input_info) { - stage.tess = tess; - } - return params; -} - -ShaderParams PrepareProgram( - const HW::PixelShaderInfo& regs, const HW::ShaderRegisters& sh, - std::span target_export_mapping, - ShaderPixelInputInfo& ps_info) { - const auto [data, hash] = ShaderGetMappedData(regs.ps_regs.data_addr, "ShaderGetInputInfoPS():"); - ShaderGetStaticInputInfoPS(regs, sh, target_export_mapping, data, ps_info); - return GetShaderParams( - regs.ps_regs.data_addr, hash, - std::span(regs.ps_user_sgpr.value, regs.ps_regs.rsrc2.user_sgpr), data); -} - -ShaderParams PrepareProgram(const HW::ComputeShaderInfo& regs, const HW::ShaderRegisters& sh, - ShaderComputeInputInfo& info) { - const auto [data, hash] = ShaderGetMappedData(regs.cs_regs.data_addr, "ShaderGetInputInfoCS():"); - ShaderGetStaticInputInfoCS(regs, sh, data, info); - return GetShaderParams( - regs.cs_regs.data_addr, hash, - std::span(regs.cs_user_sgpr.value, regs.cs_regs.user_sgpr), data); -} - -// NOLINTNEXTLINE(readability-function-cognitive-complexity) -void ShaderDbgDumpInputInfo(const ShaderVertexInputInfo& info) { - KYTY_PROFILER_BLOCK("ShaderDbgDumpInputInfo(Vs)"); - - LOGF("ShaderDbgDumpInputInfo()\n"); - - LOGF("\t fetch_external = %s\n" - "\t fetch_embedded = %s\n", - info.fetch_external ? "true" : "false", info.fetch_embedded ? "true" : "false"); - - for (int i = 0; i < info.resources_num; i++) { - LOGF("\t input %d\n", i); - - const auto& r = info.resources[i]; - const auto& rd = info.resources_dst[i]; - - LOGF("\t\t register_start = %d\n" - "\t\t registers_num = %d\n" - "\t\t fetch_index = %" PRIu32 "\n" - "\t\t buffer_index = %d\n", - rd.register_start, rd.registers_num, rd.fetch_index, rd.buffer_index); - LOGF("\t\t fields = %08" PRIx32 "%08" PRIx32 "%08" PRIx32 "%08" PRIx32 "\n", - r.fields[3], r.fields[2], r.fields[1], r.fields[0]); - LOGF("\t\t Base() = %" PRIx64 "\n" - "\t\t Stride() = %" PRIu16 "\n" - "\t\t SwizzleEnabled() = %s\n" - "\t\t NumRecords() = %" PRIu32 "\n" - "\t\t DstSelX() = %" PRIu8 "\n" - "\t\t DstSelY() = %" PRIu8 "\n" - "\t\t DstSelZ() = %" PRIu8 "\n" - "\t\t DstSelW() = %" PRIu8 "\n", - r.Base48(), r.Stride(), r.SwizzleEnabled() ? "true" : "false", r.NumRecords(), - r.DstSelX(), r.DstSelY(), r.DstSelZ(), r.DstSelW()); - LOGF("\t\t Format() = %" PRIu8 "\n" - "\t\t OutOfBounds() = %" PRIu8 "\n", - r.RawFormat(), r.OutOfBounds()); - LOGF("\t\t AddTid() = %s\n", r.AddTid() ? "true" : "false"); - } - - for (int i = 0; i < info.buffers_num; i++) { - LOGF("\t buffer %d\n", i); - - const auto& r = info.buffers[i]; - LOGF("\t\t addr = %" PRIx64 "\n" - "\t\t stride = %" PRIu32 "\n" - "\t\t num_records = %" PRIu32 "\n" - "\t\t fetch_index = %" PRIu32 "\n", - r.addr, r.stride, r.num_records, r.fetch_index); - } -} - -void ShaderDbgDumpInputInfo(const ShaderPixelInputInfo& info) { - KYTY_PROFILER_BLOCK("ShaderDbgDumpInputInfo(Ps)"); - - LOGF("ShaderDbgDumpInputInfo()\n"); - - LOGF("\t input_num = %u\n" - "\t ps_system_input_base = %u\n" - "\t custom_interpolation_mask = 0x%08" PRIx32 "\n" - "\t ps_perspective_center_vgpr = %" PRIu32 "\n" - "\t ps_perspective_sample_vgpr = %" PRIu32 "\n" - "\t ps_perspective_centroid_vgpr = %" PRIu32 "\n" - "\t ps_pos_x = %s\n" - "\t ps_pos_y = %s\n" - "\t ps_pos_z = %s\n" - "\t ps_pos_w = %s\n" - "\t ps_front_face = %s\n" - "\t ps_front_face_all_bits = %s\n" - "\t ps_ancillary = %s\n" - "\t ps_sample_shading = %s\n" - "\t ps_no_perspective = %s\n" - "\t ps_pixel_kill_enable = %s\n" - "\t ps_early_z = %s\n" - "\t ps_execute_on_noop = %s\n", - info.input_num, info.ps_system_input_base, info.custom_interpolation_mask, - info.ps_perspective_center_vgpr, info.ps_perspective_sample_vgpr, - info.ps_perspective_centroid_vgpr, info.ps_pos_x ? "true" : "false", - info.ps_pos_y ? "true" : "false", info.ps_pos_z ? "true" : "false", - info.ps_pos_w ? "true" : "false", info.ps_front_face ? "true" : "false", - info.ps_front_face_all_bits ? "true" : "false", info.ps_ancillary ? "true" : "false", - info.ps_sample_shading ? "true" : "false", info.ps_no_perspective ? "true" : "false", - info.ps_pixel_kill_enable ? "true" : "false", info.ps_early_z ? "true" : "false", - info.ps_execute_on_noop ? "true" : "false"); - - for (uint32_t i = 0; i < info.input_num; i++) { - LOGF("\t interpolator_settings[%u] = %u\n", i, info.interpolator_settings[i]); - } -} - -void ShaderDbgDumpInputInfo(const ShaderComputeInputInfo& info) { - LOGF("ShaderDbgDumpInputInfo()\n"); - - LOGF("\t workgroup_register = %d\n" - "\t thread_ids_num = %d\n" - "\t wave_size = %u\n" - "\t lds_size_dwords = %u\n" - "\t threads_num = {%u, %u, %u}\n" - "\t tg_size_en = %s\n", - info.workgroup_register, info.thread_ids_num, info.wave_size, info.lds_size_dwords, - info.threads_num[0], info.threads_num[1], info.threads_num[2], - info.tg_size_en ? "true" : "false"); - LOGF("\t threadgroup_id = {%s, %s, %s}\n", info.group_id[0] ? "true" : "false", - info.group_id[1] ? "true" : "false", info.group_id[2] ? "true" : "false"); -} - -} // namespace Libs::Graphics +#include "graphics/shader/shader.h" + +#include "common/assert.h" +#include "common/common.h" +#include "common/emulatorConfig.h" +#include "common/logging/log.h" +#include "common/profiler.h" +#include "common/stringUtils.h" +#include "graphics/guest_gpu/gpu_defs.h" +#include "graphics/guest_gpu/graphicsRun.h" +#include "graphics/guest_gpu/hardwareContext.h" +#include "graphics/host_gpu/renderer/renderContext.h" +#include "graphics/shader/recompiler/ShaderRecompiler.h" +#include "graphics/shader/recompiler/Tessellation.h" +#include "graphics/shader/recompiler/frontend/decode/ShaderDecoder.h" +#include "graphics/shader/shaderCompiler.h" +#include "graphics/shader/shaderVertexMetadata.h" +#include "libs/errno.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#undef min +#undef max +#endif + +namespace Libs::Graphics { + +struct ShaderMapEntry { + ShaderMappedData data; + uint64_t hash; +}; + +static std::unique_ptr> g_shader_map; +static std::mutex g_shader_map_mutex; + +void ShaderInit() { + EXIT_IF(g_shader_map != nullptr); + + g_shader_map = std::make_unique>(); +} + +void ShaderMapUserData(uint64_t addr, const ShaderMappedData& data) { + EXIT_IF(g_shader_map == nullptr); + + if (addr == 0 || data.code_size_bytes == 0 || data.code_size_bytes % sizeof(uint32_t) != 0) { + EXIT("ShaderMapUserData shader=0x%016" PRIx64 " has invalid AGC shader_size=0x%08" PRIx32 "\n", + addr, data.code_size_bytes); + } + const auto hash = XXH3_64bits(reinterpret_cast(addr), data.code_size_bytes); + std::scoped_lock lock(g_shader_map_mutex); + (*g_shader_map)[addr] = {data, hash}; +} + +static ShaderMapEntry ShaderGetMappedData(uint64_t addr, const char* label) { + EXIT_IF(g_shader_map == nullptr); + + std::scoped_lock lock(g_shader_map_mutex); + + if (auto iter = g_shader_map->find(addr); iter != g_shader_map->end()) { + return iter->second; + } + + EXIT("%s shader=0x%016" PRIx64 " is missing from ShaderMap\n", label, addr); +} + +static ShaderParams GetShaderParams(uint64_t shader_addr, uint64_t hash, + std::span user_data, + const ShaderMappedData& data, uint32_t user_data_base = 0) { + const auto code_words = data.code_size_bytes / sizeof(uint32_t); + const auto code = std::span {reinterpret_cast(shader_addr), code_words}; + ShaderParams params { + .code = code, + .user_data_count = static_cast(user_data.size()) + user_data_base, + .hash = hash, + }; + EXIT_IF(user_data.size() > HW::UserSgprInfo::SGPRS_MAX || + params.user_data_count > params.user_data.size()); + std::copy(user_data.begin(), user_data.end(), params.user_data.begin() + user_data_base); + return params; +} + +static void ShaderDetectBuffers(ShaderVertexInputInfo& info) { + KYTY_PROFILER_FUNCTION(); + + info.buffers_num = 0; + + for (int ri = 0; ri < info.resources_num; ri++) { + const auto& r = info.resources[ri]; + + auto& destination = info.resources_dst[ri]; + int bi = 0; + for (; bi < info.buffers_num; bi++) { + auto& b = info.buffers[bi]; + + uint64_t stride = b.stride; + + if (stride == r.Stride() && + b.fetch_index == destination.fetch_index) { + uint64_t rbase = r.Base48(); + uint64_t base = std::min(rbase, b.addr); + uint64_t offset1 = rbase - base; + uint64_t offset2 = b.addr - base; + + if (offset1 < stride && offset2 < stride) { + EXIT_NOT_IMPLEMENTED(b.num_records != r.NumRecords()); + b.addr = base; + break; + } + } + } + + if (bi == info.buffers_num) { + EXIT_NOT_IMPLEMENTED(info.buffers_num >= ShaderVertexInputInfo::RES_MAX); + info.buffers[bi] = {.addr = r.Base48(), + .stride = r.Stride(), + .num_records = r.NumRecords(), + .fetch_index = destination.fetch_index}; + info.buffers_num++; + } + destination.buffer_index = bi; + } +} + +static void ShaderApplyAttribSemantics(ShaderVertexInputInfo& info, + std::span input_semantics, + const uint32_t* attrib, const uint32_t* buffer) { + KYTY_PROFILER_FUNCTION(); + + EXIT_IF(attrib == nullptr || buffer == nullptr); + + const bool debug_dump = Config::GraphicsDebugDumpEnabled(); + + for (uint32_t i = 0; i < input_semantics.size(); i++) { + const auto& in = input_semantics[i]; + + EXIT_NOT_IMPLEMENTED(in.static_vb_index == 1 || in.static_attribute == 1); + + uint32_t reg = in.hardware_mapping; + uint32_t size = in.size_in_elements; + + if (debug_dump) { + LOGF("reg = %u, size = %u, va[%u] = 0x%08" PRIx32 "\n", reg, size, i, + attrib[in.semantic]); + } + + size_t index = attrib[in.semantic] & 0x1fu; + auto format = + static_cast((attrib[in.semantic] >> 5u) & 0x1ffu); + uint32_t offset = (attrib[in.semantic] >> 14u) & 0xfffu; + uint32_t fetch_index = (attrib[in.semantic] >> 26u) & 0x1u; + + EXIT_NOT_IMPLEMENTED(index >= ShaderVertexInputInfo::RES_MAX); + + const auto* sharp = &buffer[index * 4]; + + EXIT_NOT_IMPLEMENTED(info.resources_num >= ShaderVertexInputInfo::RES_MAX); + + auto& r = info.resources[info.resources_num]; + auto& rd = info.resources_dst[info.resources_num]; + rd.register_start = static_cast(reg); + rd.registers_num = static_cast(size); + rd.attr_id = static_cast(in.semantic); + rd.fetch_index = fetch_index; + r.fields[0] = sharp[0]; + r.fields[1] = sharp[1]; + r.fields[2] = sharp[2]; + r.fields[3] = sharp[3]; + EXIT_NOT_IMPLEMENTED(r.AddTid()); + EXIT_NOT_IMPLEMENTED(r.SwizzleEnabled()); + if (format != Prospero::VertexAttribFormat::kInvalid) { + const auto format_raw = static_cast(format); + const auto buffer_format = format_raw >> 2u; + const auto channels = (format_raw & 3u) + 1u; + // AGC vertex formats encode the buffer format above the two channel-count bits. + // The fetch prolog selects X001, XY01, XYZ1, or XYZW from that count. + r.fields[3] = (r.fields[3] & ~((0x7fu << 12u) | 0xfffu)) | + (buffer_format << 12u) | + DstSel(4, channels > 1u ? 5u : 0u, channels > 2u ? 6u : 0u, + channels > 3u ? 7u : 1u); + } + if (offset != 0) { + r.UpdateAddress48(r.Base48() + offset); + } + + info.resources_num++; + } +} + +static uint32_t ShaderCalcPsSystemInputBase(const HW::ShaderRegisters& regs) { + constexpr uint32_t ps_input_persp_sample = 0x00000001u; + constexpr uint32_t ps_input_persp_center = 0x00000002u; + constexpr uint32_t ps_input_persp_centroid = 0x00000004u; + constexpr uint32_t ps_input_persp_pull = 0x00000008u; + constexpr uint32_t ps_input_linear_sample = 0x00000010u; + constexpr uint32_t ps_input_linear_center = 0x00000020u; + constexpr uint32_t ps_input_linear_centroid = 0x00000040u; + constexpr uint32_t ps_input_line_stipple = 0x00000080u; + constexpr uint32_t ps_input_pos_xy = 0x00000300u; + constexpr uint32_t ps_input_pos_z = 0x00000400u; + constexpr uint32_t ps_input_pos_w = 0x00000800u; + constexpr uint32_t ps_input_front_face = 0x00001000u; + constexpr uint32_t ps_input_ancillary = 0x00002000u; + constexpr uint32_t ps_input_sample_coverage = 0x00004000u; + constexpr uint32_t ps_input_pos_fixed_pt = 0x00008000u; + constexpr uint32_t supported_ps_input_bits = + ps_input_persp_sample | ps_input_persp_center | ps_input_persp_centroid | + ps_input_persp_pull | ps_input_linear_sample | ps_input_linear_center | + ps_input_linear_centroid | ps_input_line_stipple | ps_input_pos_xy | ps_input_pos_z | + ps_input_pos_w | ps_input_front_face | ps_input_ancillary | ps_input_sample_coverage | + ps_input_pos_fixed_pt; + + EXIT_NOT_IMPLEMENTED((regs.ps_input_ena & ~supported_ps_input_bits) != 0); + EXIT_NOT_IMPLEMENTED((regs.ps_input_addr & ~supported_ps_input_bits) != 0); + EXIT_NOT_IMPLEMENTED(regs.ps_input_ena != regs.ps_input_addr); + + const uint32_t inputs = regs.ps_input_addr; + uint32_t reg = 0; + if ((inputs & ps_input_persp_sample) != 0) { + reg += 2; + } + if ((inputs & ps_input_persp_center) != 0) { + reg += 2; + } + if ((inputs & ps_input_persp_centroid) != 0) { + reg += 2; + } + if ((inputs & ps_input_persp_pull) != 0) { + reg += 3; + } + if ((inputs & ps_input_linear_sample) != 0) { + reg += 2; + } + if ((inputs & ps_input_linear_center) != 0) { + reg += 2; + } + if ((inputs & ps_input_linear_centroid) != 0) { + reg += 2; + } + if ((inputs & ps_input_line_stipple) != 0) { + reg += 1; + } + return reg; +} + +static bool ShaderGetStaticVertexInputInfo(uint64_t shader_addr, const HW::UserSgprInfo& user_sgpr, + uint32_t user_sgpr_num, const HW::ShaderRegisters& sh, + const ShaderMappedData& data, + ShaderVertexInputInfo& info) { + KYTY_PROFILER_FUNCTION(); + + info = {}; + + info.pa_cl_vs_out_cntl = sh.m_paClVsOutCntl; + + EXIT_NOT_IMPLEMENTED(shader_addr == 0); + info.scratch_size_dwords = data.scratch_size_dwords; + + if (data.user_data == nullptr) { + LOGF("ShaderGetVertexInputInfo(): no AGC user data for shader=0x%016" PRIx64 + " user_sgpr_num=%u\n", + shader_addr, user_sgpr_num); + } + ShaderVertexMetadata metadata; + std::string metadata_error; + if (!ShaderReadVertexMetadata(data, HW::UserSgprInfo::SGPRS_MAX, metadata, &metadata_error)) { + LOGF("ShaderGetVertexInputInfo(): invalid AGC metadata shader=0x%016" PRIx64 ": %s\n", + shader_addr, metadata_error.c_str()); + return false; + } + + if (metadata.vertex_attrib_reg >= 0) { + info.fetch_external = false; + info.fetch_embedded = true; + info.fetch_attrib_reg = metadata.vertex_attrib_reg; + info.fetch_buffer_reg = metadata.vertex_buffer_reg; + + const auto* attrib = reinterpret_cast( + static_cast(user_sgpr.value[metadata.vertex_attrib_reg]) | + (static_cast(user_sgpr.value[metadata.vertex_attrib_reg + 1]) << 32u)); + const auto* buffer = reinterpret_cast( + static_cast(user_sgpr.value[metadata.vertex_buffer_reg]) | + (static_cast(user_sgpr.value[metadata.vertex_buffer_reg + 1]) << 32u)); + + if (attrib == nullptr || buffer == nullptr) { + LOGF("ShaderGetVertexInputInfo(): null vertex table pointer shader=0x%016" PRIx64 "\n", + shader_addr); + return false; + } + ShaderApplyAttribSemantics(info, metadata.input_semantics, attrib, buffer); + ShaderDetectBuffers(info); + } + return true; +} + +static void ShaderGetStaticInputInfoPS( + const HW::PixelShaderInfo& regs, const HW::ShaderRegisters& sh, + std::span target_export_mapping, + const ShaderMappedData& data, ShaderPixelInputInfo& ps_info) { + KYTY_PROFILER_FUNCTION(); + + ps_info = {}; + ps_info.scratch_size_dwords = data.scratch_size_dwords; + + // SPI_PS_IN_CONTROL: NUM_INTERP occupies bits 5:0 and PS_W32_EN is bit 15. + ps_info.input_num = sh.ps_in_control & 0x3fu; + if ((sh.ps_in_control & 0x8000u) != 0) { + ps_info.wave_size = 32; + } + EXIT_NOT_IMPLEMENTED(ps_info.input_num > std::size(ps_info.interpolator_settings)); + ps_info.ps_system_input_base = ShaderCalcPsSystemInputBase(sh); + const uint32_t active_inputs = sh.ps_input_ena & sh.ps_input_addr; + if ((active_inputs & 0x00000001u) != 0) { + ps_info.ps_perspective_sample_vgpr = 0; + } + if ((active_inputs & 0x00000002u) != 0) { + ps_info.ps_perspective_center_vgpr = (active_inputs & 0x00000001u) != 0 ? 2u : 0u; + } + if ((active_inputs & 0x00000004u) != 0) { + ps_info.ps_perspective_centroid_vgpr = 2u * std::popcount(active_inputs & 0x3u); + } + for (uint32_t i = 0; i < data.num_input_semantics && i < ps_info.input_num && i < 32u; i++) { + const auto& semantic = data.input_semantics[i]; + if (semantic.is_custom != 0 && semantic.is_f16 == 0) { + ps_info.custom_interpolation_mask |= 1u << i; + } + } + ps_info.ps_pos_x = (active_inputs & 0x00000100u) != 0; + ps_info.ps_pos_y = (active_inputs & 0x00000200u) != 0; + ps_info.ps_pos_z = (active_inputs & 0x00000400u) != 0; + ps_info.ps_pos_w = (active_inputs & 0x00000800u) != 0; + ps_info.ps_front_face = (active_inputs & 0x00001000u) != 0; + // SPI_BARYC_CNTL.FRONT_FACE_ALL_BITS selects integer masks instead of float +/-1. + ps_info.ps_front_face_all_bits = (sh.baryc_cntl & 0x01000000u) != 0; + ps_info.ps_ancillary = (active_inputs & 0x00002000u) != 0; + ps_info.ps_sample_shading = (active_inputs & 0x00000011u) != 0; + ps_info.ps_no_perspective = (sh.ps_input_ena & sh.ps_input_addr & 0x00000020u) != 0; + ps_info.ps_pixel_kill_enable = sh.db_shader_control.shader_kill_enable; + ps_info.ps_depth_export_enable = sh.db_shader_control.shader_z_export_enable; + ps_info.ps_sample_mask_export_enable = sh.db_shader_control.shader_mask_export_enable; + ps_info.ps_early_z = + (sh.db_shader_control.shader_z_behavior == 1 && !sh.db_shader_control.shader_kill_enable && + !sh.db_shader_control.shader_z_export_enable && + !sh.db_shader_control.shader_mask_export_enable); + ps_info.ps_execute_on_noop = sh.db_shader_control.shader_execute_on_noop; + + for (uint32_t i = 0; i < ps_info.input_num; i++) { + ps_info.interpolator_settings[i] = sh.ps_interpolator_settings[i]; + } + + ps_info.target_shader_mask = sh.m_cbShaderMask; + for (int i = 0; i < 8; i++) { + const auto slot = ShaderPixelExportTarget(ps_info.target_shader_mask, i); + ps_info.target_output_mode[i] = sh.target_output_mode[i]; + ps_info.target_export_mapping[i] = sh.target_output_mode[i] != 0 && slot < 8 + ? target_export_mapping[slot] + : Prospero::ColorComponentMapping {}; + } +} + +static void ShaderGetStaticInputInfoCS(const HW::ComputeShaderInfo& regs, + const HW::ShaderRegisters& /*sh*/, + const ShaderMappedData& data, ShaderComputeInputInfo& info) { + const bool async_compute = info.async_compute; + const bool dispatch_thread_dimensions = info.dispatch_thread_dimensions; + const auto host_subgroup_size = info.host_subgroup_size; + const auto workgroup_counts = std::to_array(info.workgroup_counts); + const auto indirect_args_address = info.indirect_args_address; + info = {}; + info.async_compute = async_compute; + info.dispatch_thread_dimensions = dispatch_thread_dimensions; + info.host_subgroup_size = host_subgroup_size; + std::ranges::copy(workgroup_counts, info.workgroup_counts); + info.indirect_args_address = indirect_args_address; + info.threads_num[0] = regs.cs_regs.num_thread_x; + info.threads_num[1] = regs.cs_regs.num_thread_y; + info.threads_num[2] = regs.cs_regs.num_thread_z; + info.lds_size_dwords = static_cast(regs.cs_regs.lds_size) * 128u; + info.scratch_size_dwords = data.scratch_size_dwords; + info.float_mode = regs.cs_regs.float_mode; + info.group_id[0] = regs.cs_regs.tgid_x_en != 0; + info.group_id[1] = regs.cs_regs.tgid_y_en != 0; + info.group_id[2] = regs.cs_regs.tgid_z_en != 0; + info.wave_size = regs.cs_regs.wave_size; + info.thread_ids_num = regs.cs_regs.tidig_comp_cnt + 1; + info.tg_size_en = regs.cs_regs.tg_size_en != 0; + + info.workgroup_register = regs.cs_regs.user_sgpr; +} + +void BuildStageStaticKey(const ShaderVertexInputInfo& info, std::vector& key) { + EXIT_IF(info.resources_num < 0 || info.resources_num > ShaderVertexInputInfo::RES_MAX); + key.clear(); + key.push_back(static_cast(info.fetch_embedded)); + key.push_back(static_cast(info.fetch_attrib_reg)); + key.push_back(static_cast(info.fetch_buffer_reg)); + key.push_back(info.resources_num); + key.push_back(info.wave_size); + key.push_back(info.scratch_size_dwords); + key.push_back(info.pa_cl_vs_out_cntl); + key.push_back(static_cast(info.clip_space.enabled)); + if (info.clip_space.enabled) { + for (const float value: info.clip_space.scale) { + key.push_back(std::bit_cast(value)); + } + for (const float value: info.clip_space.offset) { + key.push_back(std::bit_cast(value)); + } + for (const float value: info.clip_space.half_extent) { + key.push_back(std::bit_cast(value)); + } + } + + key.push_back(info.mesh.threads_num[0]); + if (info.mesh.threads_num[0] != 0) { + const auto& mesh = info.mesh; + key.insert(key.end(), {mesh.wave_size, mesh.host_subgroup_size, mesh.lds_size_dwords, + mesh.scratch_size_dwords, mesh.input_primitive, + mesh.primitives_per_group, mesh.vertices_per_group, + mesh.max_vertices, mesh.max_primitives, mesh.provoking_vertex, + static_cast(mesh.fast_launch)}); + key.insert(key.end(), mesh.output_component_count.begin(), + mesh.output_component_count.end()); + } + key.push_back(info.tess.input_control_points); + if (info.tess.input_control_points != 0) { + const auto& tess = info.tess; + key.insert(key.end(), {tess.output_control_points, tess.ls_stride, tess.hs_stride, + tess.domain, tess.partitioning, tess.output_topology}); + } + + for (int i = 0; i < info.resources_num; i++) { + const auto& resource = info.resources[i]; + const auto& destination = info.resources_dst[i]; + key.push_back(destination.registers_num); + key.push_back(static_cast(destination.attr_id)); + key.push_back(resource.fields[3] & 0x7ffffu); // Channels and format used by embedded fetch. + } +} + +void BuildStageStaticKey(const ShaderPixelInputInfo& info, std::vector& key) { + EXIT_IF(info.input_num > std::size(info.interpolator_settings)); + key.clear(); + key.push_back(info.scratch_size_dwords); + key.push_back(info.input_num); + key.push_back(info.wave_size); + key.push_back(info.ps_system_input_base); + key.push_back(info.custom_interpolation_mask); + key.push_back(info.ps_perspective_center_vgpr); + key.push_back(info.ps_perspective_sample_vgpr); + key.push_back(info.ps_perspective_centroid_vgpr); + key.push_back(static_cast(info.ps_pos_x)); + key.push_back(static_cast(info.ps_pos_y)); + key.push_back(static_cast(info.ps_pos_z)); + key.push_back(static_cast(info.ps_pos_w)); + key.push_back(static_cast(info.ps_front_face)); + key.push_back(static_cast(info.ps_front_face_all_bits)); + key.push_back(static_cast(info.ps_ancillary)); + key.push_back(static_cast(info.ps_no_perspective)); + key.push_back(static_cast(info.parameter_mode)); + key.push_back(static_cast(info.mesh_stage)); + key.push_back(static_cast(info.ps_pixel_kill_enable)); + key.push_back(static_cast(info.ps_depth_export_enable)); + key.push_back(static_cast(info.ps_sample_mask_export_enable)); + key.push_back(static_cast(info.ps_early_z)); + key.push_back(static_cast(info.dual_source_blending)); + key.push_back(static_cast(info.object_primitive_id)); + key.push_back(static_cast(info.alpha_blend_source)); + key.insert(key.end(), std::begin(info.target_output_mode), std::end(info.target_output_mode)); + key.push_back(info.target_packed_unorm_mask | (uint32_t {info.target_round_mode} << 8u)); + const auto mask = info.target_shader_mask; + key.push_back((mask | (mask >> 1u) | (mask >> 2u) | (mask >> 3u)) & 0x11111111u); + for (uint32_t base = 0; base < info.target_export_mapping.size(); base += 4u) { + uint32_t packed = 0; + for (uint32_t i = 0; i < 4u; i++) { + packed |= static_cast(info.target_export_mapping[base + i].packed) + << (i * 8u); + } + key.push_back(packed); + } + key.insert(key.end(), std::begin(info.interpolator_settings), + std::begin(info.interpolator_settings) + info.input_num); +} + +void BuildStageStaticKey(const ShaderComputeInputInfo& info, std::vector& key) { + key.clear(); + key.push_back(info.workgroup_register); + key.push_back(info.wave_size | (static_cast(info.float_mode) << 8u)); + key.push_back(info.host_subgroup_size); + key.push_back(info.thread_ids_num); + key.push_back(info.lds_size_dwords); + key.push_back(info.scratch_size_dwords); + key.push_back(static_cast(info.dispatch_thread_dimensions) | + (static_cast(info.async_compute) << 1u)); + for (int i = 0; i < 3; i++) { + key.push_back(info.threads_num[i]); + key.push_back(static_cast(info.group_id[i])); + } + key.push_back(static_cast(info.tg_size_en)); +} + +ShaderParams PrepareProgram(const HW::VertexShaderInfo& regs, const HW::Context& context, + const HW::UserConfig& user_config, ShaderVertexInputInfo& info) { + const auto& sh = context.GetShaderRegisters(); + const auto [data, hash] = ShaderGetMappedData(regs.es_regs.data_addr, "ShaderGetInputInfoVS():"); + const bool merged = (context.GetShaderStages() & 0x20u) != 0; + // GS_EN controls amplification, not whether an NGG shader uses a workgroup. + const bool native_ngg = !merged && data.type == Prospero::ShaderBinaryType::kGs && + regs.gs_regs.rsrc2.lds_size != 0; + auto params = GetShaderParams( + regs.es_regs.data_addr, hash, + std::span(regs.gs_user_sgpr.value, regs.gs_regs.rsrc2.user_sgpr), data, + merged || native_ngg ? 8u : 0u); + if (!merged && !native_ngg) { + if (!ShaderGetStaticVertexInputInfo(regs.es_regs.data_addr, regs.gs_user_sgpr, + regs.gs_regs.rsrc2.user_sgpr, sh, data, info)) { + EXIT("failed to prepare vertex shader program\n"); + } + info.wave_size = (context.GetShaderStages() & 0x00400000u) != 0 ? 32u : 64u; + return params; + } + // NGG user SGPRs start at s8; a separately compiled GS back half also receives + // its user-data pointer in s0:s1. + info = {}; + info.logical_stage = ShaderType::Mesh; + info.pa_cl_vs_out_cntl = sh.m_paClVsOutCntl; + auto& mesh = info.mesh; + mesh.input_primitive = static_cast(user_config.GetPrimType()); + mesh.wave_size = (context.GetShaderStages() & 0x00400000u) != 0 ? 32u : 64u; + mesh.max_vertices = sh.m_geMaxOutputPerSubgroup; + mesh.provoking_vertex = context.GetModeControl().provoking_vtx_last ? 2u : 0u; + mesh.lds_size_dwords = static_cast(regs.gs_regs.rsrc2.lds_size) * 128u; + mesh.scratch_size_dwords = data.scratch_size_dwords; + const auto fast_launch = (context.GetShaderStages() >> 19u) & 3u; + EXIT_NOT_IMPLEMENTED(fast_launch > 1u); + mesh.fast_launch = fast_launch != 0; + if (data.type == Prospero::ShaderBinaryType::kGsFront) { + EXIT_IF(regs.gs_regs.data_addr == 0); + const auto [back, back_hash] = ShaderGetMappedData(regs.gs_regs.data_addr, "ShaderGetInputInfoGS():"); + const auto back_params = + GetShaderParams(regs.gs_regs.data_addr, back_hash, {}, back); + params.back_code = back_params.code; + params.user_data[0] = static_cast(regs.gs_regs.user_data_addr); + params.user_data[1] = static_cast(regs.gs_regs.user_data_addr >> 32u); + const uint64_t hashes[] = {params.hash, back_params.hash}; + params.hash = XXH3_64bits(hashes, sizeof(hashes)); + mesh.scratch_size_dwords = std::max(mesh.scratch_size_dwords, back.scratch_size_dwords); + } + const auto& group = user_config.GetGeControl(); + if (mesh.fast_launch) { + const auto& user_vgpr = user_config.GetGeUserVgprEn(); + EXIT_NOT_IMPLEMENTED(data.type != Prospero::ShaderBinaryType::kGs || + regs.gs_regs.rsrc1.gs_vgpr_component_count != 0u || + regs.gs_regs.rsrc2.es_vgpr_component_count != 1u || + user_config.GetPrimType() != Prospero::PrimitiveType::kPointList || + group.primitive_group_size != 1u || group.vertex_group_size != 1u || + user_vgpr.vgpr1 || user_vgpr.vgpr2 || user_vgpr.vgpr3 || + mesh.max_vertices != sh.m_vgtGsMaxVertOut); + } else if (merged) { + EXIT_NOT_IMPLEMENTED(regs.gs_regs.rsrc1.gs_vgpr_component_count != 3u || + regs.gs_regs.rsrc2.es_vgpr_component_count != 3u); + } + if ((user_config.GetPrimType() != Prospero::PrimitiveType::kPointList && + user_config.GetPrimType() != Prospero::PrimitiveType::kLineList && + user_config.GetPrimType() != Prospero::PrimitiveType::kTriFan && + user_config.GetPrimType() != Prospero::PrimitiveType::kTriStrip && + user_config.GetPrimType() != Prospero::PrimitiveType::kTriList) || + sh.m_vgtGsOutPrimType != 2u || (!native_ngg && sh.m_vgtGsMaxVertOut < 3u) || + group.vertex_group_size < mesh.InputPrimitiveSize() || + mesh.max_vertices == 0u) { + EXIT("unsupported GS assembly: input=%u output=%u vertices=%u GE=%u/%u max_output=%u\n", + mesh.input_primitive, sh.m_vgtGsOutPrimType, sh.m_vgtGsMaxVertOut, + group.primitive_group_size, group.vertex_group_size, mesh.max_vertices); + } + mesh.max_primitives = mesh.fast_launch ? mesh.max_vertices : + native_ngg ? mesh.InputPrimitiveCount(mesh.max_vertices) : + group.primitive_group_size * (sh.m_vgtGsMaxVertOut - 2u); + mesh.primitives_per_group = std::min({static_cast(group.primitive_group_size), + mesh.InputPrimitiveCount(group.vertex_group_size), + native_ngg ? mesh.max_primitives : + mesh.max_vertices / sh.m_vgtGsMaxVertOut}); + EXIT_IF(mesh.primitives_per_group == 0u); + mesh.vertices_per_group = mesh.InputVertexCount(mesh.primitives_per_group); + const auto threads = native_ngg && !mesh.fast_launch ? mesh.vertices_per_group : mesh.max_vertices; + mesh.threads_num[0] = ((threads + mesh.wave_size - 1u) / mesh.wave_size) * mesh.wave_size; + mesh.threads_num[1] = mesh.threads_num[2] = 1u; + return params; +} + +std::array +PrepareTessellationPrograms(const HW::VertexShaderInfo& regs, const HW::Context& context, + std::array& input_info) { + const auto& sh = context.GetShaderRegisters(); + const auto [local, local_hash] = ShaderGetMappedData(regs.ls_regs.data_addr, "ShaderGetInputInfoLS():"); + const auto [control, control_hash] = ShaderGetMappedData(regs.hs_regs.data_addr, "ShaderGetInputInfoHS():"); + const auto [evaluation, evaluation_hash] = ShaderGetMappedData(regs.es_regs.data_addr, "ShaderGetInputInfoTES():"); + EXIT_NOT_IMPLEMENTED(local.type != Prospero::ShaderBinaryType::kHsFront || + control.type != Prospero::ShaderBinaryType::kHsBack || + evaluation.type != Prospero::ShaderBinaryType::kGs); + EXIT_NOT_IMPLEMENTED((context.GetShaderStages() & 0x4u) == 0 || + (context.GetShaderStages() & 0x00600020u) != 0); + EXIT_IF(regs.hs_regs.user_data_addr == 0); + + const auto local_users = std::span(regs.hs_user_sgpr.value, regs.hs_regs.rsrc2.user_sgpr); + const auto evaluation_users = std::span(regs.gs_user_sgpr.value, regs.gs_regs.rsrc2.user_sgpr); + std::array params { + GetShaderParams(regs.ls_regs.data_addr, local_hash, local_users, local), + GetShaderParams(regs.hs_regs.data_addr, control_hash, local_users, control, 8u), + GetShaderParams(regs.es_regs.data_addr, evaluation_hash, evaluation_users, + evaluation), + }; + // The fused HS back half receives its separate user-data address in s0:s1. + // RDNA2 reserves s0:s7 before the native HS user SGPRs. + params[1].user_data[0] = static_cast(regs.hs_regs.user_data_addr); + params[1].user_data[1] = static_cast(regs.hs_regs.user_data_addr >> 32u); + + input_info = {}; + if (!ShaderGetStaticVertexInputInfo(regs.ls_regs.data_addr, regs.hs_user_sgpr, + regs.hs_regs.rsrc2.user_sgpr, sh, local, input_info[0])) { + EXIT("failed to prepare local shader program\n"); + } + input_info[0].logical_stage = ShaderType::Local; + input_info[1].logical_stage = ShaderType::TessellationControl; + input_info[1].scratch_size_dwords = control.scratch_size_dwords; + input_info[2].logical_stage = ShaderType::TessellationEvaluation; + input_info[2].scratch_size_dwords = evaluation.scratch_size_dwords; + input_info[2].pa_cl_vs_out_cntl = sh.m_paClVsOutCntl; + + ShaderTessellationInputInfo tess { + .input_control_points = (sh.m_vgtLsHsConfig >> 8u) & 0x3fu, + .output_control_points = (sh.m_vgtLsHsConfig >> 14u) & 0x3fu, + .domain = sh.m_vgtTfParam & 0x3u, + .partitioning = (sh.m_vgtTfParam >> 2u) & 0x3u, + .output_topology = (sh.m_vgtTfParam >> 5u) & 0x3u, + }; + EXIT_IF(tess.input_control_points == 0 || tess.input_control_points > 32 || + tess.output_control_points == 0 || tess.output_control_points > 32); + ShaderRecompiler::AnalyzeTessellationPrograms(params[0].code, params[1].code, tess); + for (auto& stage: input_info) { + stage.tess = tess; + } + return params; +} + +ShaderParams PrepareProgram( + const HW::PixelShaderInfo& regs, const HW::ShaderRegisters& sh, + std::span target_export_mapping, + ShaderPixelInputInfo& ps_info) { + const auto [data, hash] = ShaderGetMappedData(regs.ps_regs.data_addr, "ShaderGetInputInfoPS():"); + ShaderGetStaticInputInfoPS(regs, sh, target_export_mapping, data, ps_info); + return GetShaderParams( + regs.ps_regs.data_addr, hash, + std::span(regs.ps_user_sgpr.value, regs.ps_regs.rsrc2.user_sgpr), data); +} + +ShaderParams PrepareProgram(const HW::ComputeShaderInfo& regs, const HW::ShaderRegisters& sh, + ShaderComputeInputInfo& info) { + const auto [data, hash] = ShaderGetMappedData(regs.cs_regs.data_addr, "ShaderGetInputInfoCS():"); + ShaderGetStaticInputInfoCS(regs, sh, data, info); + return GetShaderParams( + regs.cs_regs.data_addr, hash, + std::span(regs.cs_user_sgpr.value, regs.cs_regs.user_sgpr), data); +} + +// NOLINTNEXTLINE(readability-function-cognitive-complexity) +void ShaderDbgDumpInputInfo(const ShaderVertexInputInfo& info) { + KYTY_PROFILER_BLOCK("ShaderDbgDumpInputInfo(Vs)"); + + LOGF("ShaderDbgDumpInputInfo()\n"); + + LOGF("\t fetch_external = %s\n" + "\t fetch_embedded = %s\n", + info.fetch_external ? "true" : "false", info.fetch_embedded ? "true" : "false"); + + for (int i = 0; i < info.resources_num; i++) { + LOGF("\t input %d\n", i); + + const auto& r = info.resources[i]; + const auto& rd = info.resources_dst[i]; + + LOGF("\t\t register_start = %d\n" + "\t\t registers_num = %d\n" + "\t\t fetch_index = %" PRIu32 "\n" + "\t\t buffer_index = %d\n", + rd.register_start, rd.registers_num, rd.fetch_index, rd.buffer_index); + LOGF("\t\t fields = %08" PRIx32 "%08" PRIx32 "%08" PRIx32 "%08" PRIx32 "\n", + r.fields[3], r.fields[2], r.fields[1], r.fields[0]); + LOGF("\t\t Base() = %" PRIx64 "\n" + "\t\t Stride() = %" PRIu16 "\n" + "\t\t SwizzleEnabled() = %s\n" + "\t\t NumRecords() = %" PRIu32 "\n" + "\t\t DstSelX() = %" PRIu8 "\n" + "\t\t DstSelY() = %" PRIu8 "\n" + "\t\t DstSelZ() = %" PRIu8 "\n" + "\t\t DstSelW() = %" PRIu8 "\n", + r.Base48(), r.Stride(), r.SwizzleEnabled() ? "true" : "false", r.NumRecords(), + r.DstSelX(), r.DstSelY(), r.DstSelZ(), r.DstSelW()); + LOGF("\t\t Format() = %" PRIu8 "\n" + "\t\t OutOfBounds() = %" PRIu8 "\n", + r.RawFormat(), r.OutOfBounds()); + LOGF("\t\t AddTid() = %s\n", r.AddTid() ? "true" : "false"); + } + + for (int i = 0; i < info.buffers_num; i++) { + LOGF("\t buffer %d\n", i); + + const auto& r = info.buffers[i]; + LOGF("\t\t addr = %" PRIx64 "\n" + "\t\t stride = %" PRIu32 "\n" + "\t\t num_records = %" PRIu32 "\n" + "\t\t fetch_index = %" PRIu32 "\n", + r.addr, r.stride, r.num_records, r.fetch_index); + } +} + +void ShaderDbgDumpInputInfo(const ShaderPixelInputInfo& info) { + KYTY_PROFILER_BLOCK("ShaderDbgDumpInputInfo(Ps)"); + + LOGF("ShaderDbgDumpInputInfo()\n"); + + LOGF("\t input_num = %u\n" + "\t ps_system_input_base = %u\n" + "\t custom_interpolation_mask = 0x%08" PRIx32 "\n" + "\t ps_perspective_center_vgpr = %" PRIu32 "\n" + "\t ps_perspective_sample_vgpr = %" PRIu32 "\n" + "\t ps_perspective_centroid_vgpr = %" PRIu32 "\n" + "\t ps_pos_x = %s\n" + "\t ps_pos_y = %s\n" + "\t ps_pos_z = %s\n" + "\t ps_pos_w = %s\n" + "\t ps_front_face = %s\n" + "\t ps_front_face_all_bits = %s\n" + "\t ps_ancillary = %s\n" + "\t ps_sample_shading = %s\n" + "\t ps_no_perspective = %s\n" + "\t ps_pixel_kill_enable = %s\n" + "\t ps_early_z = %s\n" + "\t ps_execute_on_noop = %s\n", + info.input_num, info.ps_system_input_base, info.custom_interpolation_mask, + info.ps_perspective_center_vgpr, info.ps_perspective_sample_vgpr, + info.ps_perspective_centroid_vgpr, info.ps_pos_x ? "true" : "false", + info.ps_pos_y ? "true" : "false", info.ps_pos_z ? "true" : "false", + info.ps_pos_w ? "true" : "false", info.ps_front_face ? "true" : "false", + info.ps_front_face_all_bits ? "true" : "false", info.ps_ancillary ? "true" : "false", + info.ps_sample_shading ? "true" : "false", info.ps_no_perspective ? "true" : "false", + info.ps_pixel_kill_enable ? "true" : "false", info.ps_early_z ? "true" : "false", + info.ps_execute_on_noop ? "true" : "false"); + + for (uint32_t i = 0; i < info.input_num; i++) { + LOGF("\t interpolator_settings[%u] = %u\n", i, info.interpolator_settings[i]); + } +} + +void ShaderDbgDumpInputInfo(const ShaderComputeInputInfo& info) { + LOGF("ShaderDbgDumpInputInfo()\n"); + + LOGF("\t workgroup_register = %d\n" + "\t thread_ids_num = %d\n" + "\t wave_size = %u\n" + "\t lds_size_dwords = %u\n" + "\t threads_num = {%u, %u, %u}\n" + "\t tg_size_en = %s\n", + info.workgroup_register, info.thread_ids_num, info.wave_size, info.lds_size_dwords, + info.threads_num[0], info.threads_num[1], info.threads_num[2], + info.tg_size_en ? "true" : "false"); + LOGF("\t threadgroup_id = {%s, %s, %s}\n", info.group_id[0] ? "true" : "false", + info.group_id[1] ? "true" : "false", info.group_id[2] ? "true" : "false"); +} + +} // namespace Libs::Graphics diff --git a/src/graphics/shader/shader.h b/src/graphics/shader/shader.h index 17a00bfb..aa10c3cd 100644 --- a/src/graphics/shader/shader.h +++ b/src/graphics/shader/shader.h @@ -1,343 +1,345 @@ -#ifndef EMULATOR_INCLUDE_EMULATOR_GRAPHICS_SHADER_H_ -#define EMULATOR_INCLUDE_EMULATOR_GRAPHICS_SHADER_H_ - -#include "common/abi.h" -#include "common/common.h" -#include "graphics/guest_gpu/gpu_defs.h" -#include "graphics/shader/recompiler/ir/ResourceSnapshot.h" -#include "graphics/shader/shaderBindings.h" - -#include -#include -#include -#include -#include - -namespace Libs::Graphics { - -namespace ShaderError { - -[[nodiscard]] inline bool Fail(std::string* error, std::string_view message) { - if (error != nullptr) { - error->assign(message.data(), message.size()); - } - return false; -} - -} // namespace ShaderError - -namespace HW { -struct VertexShaderInfo; -struct PixelShaderInfo; -struct ComputeShaderInfo; -struct ShaderRegisters; -} // namespace HW - -enum class ShaderType { - Unknown, - Vertex, - Pixel, - Fetch, - Compute, - Mesh, - Local, - TessellationControl, - TessellationEvaluation -}; - -namespace ShaderRecompiler::IR { -struct CompiledShaderInfo; -} // namespace ShaderRecompiler::IR - -struct ShaderStageRuntime { - const ShaderRecompiler::IR::CompiledShaderInfo* program = nullptr; - const ShaderRecompiler::IR::ResourceSnapshot* resources = nullptr; - - [[nodiscard]] explicit operator bool() const { - return program != nullptr && resources != nullptr; - } -}; - -constexpr uint32_t DstSel(uint32_t x, uint32_t y = 0, uint32_t z = 0, uint32_t w = 0) { - return x | (y << 3u) | (z << 6u) | (w << 9u); -} - -inline uint8_t GetDstSel(uint32_t swizzle, uint32_t channel) { - return (swizzle >> (channel * 3u)) & 0x7u; -} - -[[nodiscard]] inline bool IsValidImageSwizzle(uint32_t swizzle, - uint32_t component_count = 4) noexcept { - if ((swizzle & ~0xfffu) != 0) { - return false; - } - for (uint32_t channel = 0; channel < 4; channel++) { - const auto selector = GetDstSel(swizzle, channel); - if (selector > 1 && (selector < 4 || selector >= 4 + component_count)) return false; - } - return true; -} - -struct ShaderClipSpaceTransform { - float scale[2] = {}; - float offset[2] = {}; - float half_extent[2] = {}; - bool enabled = false; -}; - -struct ShaderWorkgroupInputInfo { - uint32_t threads_num[3] = {0, 0, 0}; - uint32_t lds_size_dwords = 0; - uint32_t scratch_size_dwords = 0; - uint32_t host_subgroup_size = 64; - uint32_t wave_size = 64; -}; - -struct ShaderMeshInputInfo: ShaderWorkgroupInputInfo { - uint32_t input_primitive = 0; - uint32_t primitives_per_group = 0; - uint32_t vertices_per_group = 0; - uint32_t max_vertices = 0; - uint32_t max_primitives = 0; - uint32_t provoking_vertex = 0; - bool fast_launch = false; - - [[nodiscard]] constexpr uint32_t InputPrimitiveSize() const { - switch (static_cast(input_primitive)) { - case Prospero::PrimitiveType::kPointList: return 1u; - case Prospero::PrimitiveType::kLineList: return 2u; - default: return 3u; - } - } - [[nodiscard]] constexpr uint32_t InputPrimitiveStep() const { - switch (static_cast(input_primitive)) { - case Prospero::PrimitiveType::kTriFan: - case Prospero::PrimitiveType::kTriStrip: return 1u; - default: return InputPrimitiveSize(); - } - } - [[nodiscard]] constexpr uint32_t InputPrimitiveCount(uint32_t vertices) const { - const auto size = InputPrimitiveSize(); - return vertices < size ? 0u : (vertices - size) / InputPrimitiveStep() + 1u; - } - [[nodiscard]] constexpr uint32_t InputVertexCount(uint32_t primitives) const { - return primitives == 0u ? 0u : (primitives - 1u) * InputPrimitiveStep() + InputPrimitiveSize(); - } -}; - -struct ShaderTessellationInputInfo { - uint32_t input_control_points = 0; - uint32_t output_control_points = 0; - uint32_t ls_stride = 0; - uint32_t hs_stride = 0; - uint32_t domain = 0; - uint32_t partitioning = 0; - uint32_t output_topology = 0; -}; - -struct ShaderVertexInputInfo { - static constexpr int RES_MAX = 32; - - ShaderBufferResource resources[RES_MAX]; - ShaderVertexDestination resources_dst[RES_MAX]; - ShaderVertexInputBuffer buffers[RES_MAX]; - ShaderStageRuntime stage; - ShaderType logical_stage = ShaderType::Vertex; - int resources_num = 0; - int fetch_attrib_reg = 0; - int fetch_buffer_reg = 0; - int buffers_num = 0; - uint32_t wave_size = 64; - uint32_t scratch_size_dwords = 0; - uint32_t pa_cl_vs_out_cntl = 0; - ShaderClipSpaceTransform clip_space; - ShaderMeshInputInfo mesh; - ShaderTessellationInputInfo tess; - bool fetch_external = false; - bool fetch_embedded = false; -}; - -struct ShaderComputeInputInfo: ShaderWorkgroupInputInfo { - bool async_compute = false; - uint8_t float_mode = 0xc0; - uint32_t dispatch_threads_num[3] = {0, 0, 0}; - uint32_t workgroup_counts[3] = {0, 0, 0}; - uint64_t indirect_args_address = 0; - bool group_id[3] = {false, false, false}; - bool dispatch_thread_dimensions = false; - bool lds_storage = false; - int thread_ids_num = 0; - int workgroup_register = 0; - bool tg_size_en = false; - ShaderStageRuntime stage; -}; - -enum class ShaderAlphaBlendSource : uint8_t { None, SourceAlpha, SourceAlphaOne, SourceAlphaZero }; -enum class ShaderPixelParameterMode : uint8_t { FirstVertex, LastVertex, Rectangle }; - -struct ShaderPixelInputInfo { - uint32_t interpolator_settings[32] = {0}; - uint32_t input_num = 0; - uint32_t wave_size = 64; - uint32_t ps_system_input_base = 0; - uint32_t custom_interpolation_mask = 0; - uint32_t ps_perspective_center_vgpr = UINT32_MAX; - uint32_t ps_perspective_sample_vgpr = UINT32_MAX; - uint32_t ps_perspective_centroid_vgpr = UINT32_MAX; - uint8_t target_output_mode[8] = {}; - uint32_t target_shader_mask = UINT32_MAX; - std::array target_export_mapping = {}; - uint8_t target_packed_unorm_mask = 0; - // CB round mode per converted export: zero adds half an LSB, one truncates. - uint8_t target_round_mode = 0; - uint32_t scratch_size_dwords = 0; - bool ps_pos_x = false; - bool ps_pos_y = false; - bool ps_pos_z = false; - bool ps_pos_w = false; - bool ps_front_face = false; - bool ps_front_face_all_bits = false; - bool ps_ancillary = false; - bool ps_no_perspective = false; - ShaderPixelParameterMode parameter_mode = ShaderPixelParameterMode::FirstVertex; - bool ps_pixel_kill_enable = false; - bool ps_depth_export_enable = false; - bool ps_sample_mask_export_enable = false; - bool ps_sample_shading = false; - bool dual_source_blending = false; - bool object_primitive_id = false; - // Export logical alpha or per-channel source factors through MRT1 after channel swizzling. - ShaderAlphaBlendSource alpha_blend_source = ShaderAlphaBlendSource::None; - bool ps_early_z = false; - bool ps_execute_on_noop = false; - ShaderStageRuntime stage; - - bool HasPositionInput() const { return ps_pos_x || ps_pos_y || ps_pos_z || ps_pos_w; } -}; - -union ShaderStageInputInfo { - const ShaderVertexInputInfo* vertex; - const ShaderPixelInputInfo* pixel; - const ShaderComputeInputInfo* compute = nullptr; -}; - -inline const ShaderWorkgroupInputInfo* ShaderWorkgroupInput(ShaderType stage, - ShaderStageInputInfo input) { - switch (stage) { - case ShaderType::Compute: return input.compute; - case ShaderType::Mesh: return &input.vertex->mesh; - default: return nullptr; - } -} - -uint32_t ShaderPixelParameterMappedLocation(const ShaderPixelInputInfo& info, uint32_t input); -uint32_t ShaderPixelParameterLocation(const ShaderPixelInputInfo& info, - std::span active_inputs, uint32_t input); -bool ShaderPixelParameterIsFlat(const ShaderPixelInputInfo& info, uint32_t input); -bool ShaderPixelParameterIsCustom(const ShaderPixelInputInfo& info, uint32_t input); - -struct ShaderSharp { - uint16_t offset_dw : 15; - uint16_t size : 1; -}; - -struct ShaderUserData { - uint16_t* direct_resource_offset; - ShaderSharp* sharp_resource_offset[4]; - uint16_t eud_size_dw; - uint16_t srt_size_dw; - uint16_t direct_resource_count; - uint16_t sharp_resource_count[4]; -}; - -struct ShaderRegisterRange { - uint16_t start; - uint16_t end; -}; - -struct ShaderDrawModifier { - uint32_t enbl_start_vertex_offset : 1; - uint32_t enbl_start_index_offset : 1; - uint32_t enbl_start_instance_offset : 1; - uint32_t enbl_draw_index : 1; - uint32_t enbl_user_vgprs : 1; - uint32_t render_target_slice_offset : 3; - uint32_t fuse_draws : 1; - uint32_t compiler_flags : 23; - uint32_t is_default : 1; - uint32_t reserved : 31; -}; - -struct ShaderRegister { - uint32_t offset; - uint32_t value; -}; - -struct ShaderSpecialRegs { - ShaderRegister ge_cntl; - ShaderRegister vgt_shader_stages_en; - uint32_t dispatch_modifier; - ShaderRegisterRange user_data_range; - ShaderDrawModifier draw_modifier; - ShaderRegister vgt_gs_out_prim_type; - ShaderRegister ge_user_vgpr_en; -}; - -struct ShaderSemantic { - uint32_t semantic : 8; - uint32_t hardware_mapping : 8; - uint32_t size_in_elements : 4; - uint32_t is_f16 : 2; - uint32_t is_flat_shaded : 1; - uint32_t is_linear : 1; - uint32_t is_custom : 1; - uint32_t static_vb_index : 1; - uint32_t static_attribute : 1; - uint32_t reserved : 1; - uint32_t default_value : 2; - uint32_t default_value_hi : 2; -}; - -struct Shader { - uint32_t file_header; - uint32_t version; - ShaderUserData* user_data; - const volatile void* code; - ShaderRegister* cx_registers; - ShaderRegister* sh_registers; - ShaderSpecialRegs* specials; - ShaderSemantic* input_semantics; - ShaderSemantic* output_semantics; - uint32_t header_size; - uint32_t shader_size; - uint32_t embedded_constant_buffer_size_dqw; - uint32_t target; - uint32_t num_input_semantics; - uint16_t scratch_size_dw_per_thread; - uint16_t num_output_semantics; - uint16_t special_sizes_bytes; - uint8_t type; - uint8_t num_cx_registers; - uint8_t num_sh_registers; -}; - -struct ShaderMappedData { - Prospero::ShaderBinaryType type {}; - ShaderUserData* user_data = nullptr; - ShaderSemantic* input_semantics = nullptr; - uint32_t num_input_semantics = 0; - uint32_t code_size_bytes = 0; - uint32_t scratch_size_dwords = 0; -}; - -void ShaderInit(); -void ShaderMapUserData(uint64_t addr, const ShaderMappedData& data); -uint32_t ShaderPixelExportTarget(uint32_t shader_mask, uint32_t export_index); - -void ShaderDbgDumpInputInfo(const ShaderVertexInputInfo& info); -void ShaderDbgDumpInputInfo(const ShaderPixelInputInfo& info); -void ShaderDbgDumpInputInfo(const ShaderComputeInputInfo& info); - -} // namespace Libs::Graphics - -#endif /* EMULATOR_INCLUDE_EMULATOR_GRAPHICS_SHADER_H_ */ +#ifndef EMULATOR_INCLUDE_EMULATOR_GRAPHICS_SHADER_H_ +#define EMULATOR_INCLUDE_EMULATOR_GRAPHICS_SHADER_H_ + +#include "common/abi.h" +#include "common/common.h" +#include "graphics/guest_gpu/gpu_defs.h" +#include "graphics/shader/recompiler/ir/ResourceSnapshot.h" +#include "graphics/shader/shaderBindings.h" + +#include +#include +#include +#include +#include + +namespace Libs::Graphics { + +namespace ShaderError { + +[[nodiscard]] inline bool Fail(std::string* error, std::string_view message) { + if (error != nullptr) { + error->assign(message.data(), message.size()); + } + return false; +} + +} // namespace ShaderError + +namespace HW { +struct VertexShaderInfo; +struct PixelShaderInfo; +struct ComputeShaderInfo; +struct ShaderRegisters; +} // namespace HW + +enum class ShaderType { + Unknown, + Vertex, + Pixel, + Fetch, + Compute, + Mesh, + Local, + TessellationControl, + TessellationEvaluation +}; + +namespace ShaderRecompiler::IR { +struct CompiledShaderInfo; +} // namespace ShaderRecompiler::IR + +struct ShaderStageRuntime { + const ShaderRecompiler::IR::CompiledShaderInfo* program = nullptr; + const ShaderRecompiler::IR::ResourceSnapshot* resources = nullptr; + + [[nodiscard]] explicit operator bool() const { + return program != nullptr && resources != nullptr; + } +}; + +constexpr uint32_t DstSel(uint32_t x, uint32_t y = 0, uint32_t z = 0, uint32_t w = 0) { + return x | (y << 3u) | (z << 6u) | (w << 9u); +} + +inline uint8_t GetDstSel(uint32_t swizzle, uint32_t channel) { + return (swizzle >> (channel * 3u)) & 0x7u; +} + +[[nodiscard]] inline bool IsValidImageSwizzle(uint32_t swizzle, + uint32_t component_count = 4) noexcept { + if ((swizzle & ~0xfffu) != 0) { + return false; + } + for (uint32_t channel = 0; channel < 4; channel++) { + const auto selector = GetDstSel(swizzle, channel); + if (selector > 1 && (selector < 4 || selector >= 4 + component_count)) return false; + } + return true; +} + +struct ShaderClipSpaceTransform { + float scale[2] = {}; + float offset[2] = {}; + float half_extent[2] = {}; + bool enabled = false; +}; + +struct ShaderWorkgroupInputInfo { + uint32_t threads_num[3] = {0, 0, 0}; + uint32_t lds_size_dwords = 0; + uint32_t scratch_size_dwords = 0; + uint32_t host_subgroup_size = 64; + uint32_t wave_size = 64; +}; + +struct ShaderMeshInputInfo: ShaderWorkgroupInputInfo { + uint32_t input_primitive = 0; + uint32_t primitives_per_group = 0; + uint32_t vertices_per_group = 0; + uint32_t max_vertices = 0; + uint32_t max_primitives = 0; + uint32_t provoking_vertex = 0; + std::array output_component_count = {}; + bool fast_launch = false; + + [[nodiscard]] constexpr uint32_t InputPrimitiveSize() const { + switch (static_cast(input_primitive)) { + case Prospero::PrimitiveType::kPointList: return 1u; + case Prospero::PrimitiveType::kLineList: return 2u; + default: return 3u; + } + } + [[nodiscard]] constexpr uint32_t InputPrimitiveStep() const { + switch (static_cast(input_primitive)) { + case Prospero::PrimitiveType::kTriFan: + case Prospero::PrimitiveType::kTriStrip: return 1u; + default: return InputPrimitiveSize(); + } + } + [[nodiscard]] constexpr uint32_t InputPrimitiveCount(uint32_t vertices) const { + const auto size = InputPrimitiveSize(); + return vertices < size ? 0u : (vertices - size) / InputPrimitiveStep() + 1u; + } + [[nodiscard]] constexpr uint32_t InputVertexCount(uint32_t primitives) const { + return primitives == 0u ? 0u : (primitives - 1u) * InputPrimitiveStep() + InputPrimitiveSize(); + } +}; + +struct ShaderTessellationInputInfo { + uint32_t input_control_points = 0; + uint32_t output_control_points = 0; + uint32_t ls_stride = 0; + uint32_t hs_stride = 0; + uint32_t domain = 0; + uint32_t partitioning = 0; + uint32_t output_topology = 0; +}; + +struct ShaderVertexInputInfo { + static constexpr int RES_MAX = 32; + + ShaderBufferResource resources[RES_MAX]; + ShaderVertexDestination resources_dst[RES_MAX]; + ShaderVertexInputBuffer buffers[RES_MAX]; + ShaderStageRuntime stage; + ShaderType logical_stage = ShaderType::Vertex; + int resources_num = 0; + int fetch_attrib_reg = 0; + int fetch_buffer_reg = 0; + int buffers_num = 0; + uint32_t wave_size = 64; + uint32_t scratch_size_dwords = 0; + uint32_t pa_cl_vs_out_cntl = 0; + ShaderClipSpaceTransform clip_space; + ShaderMeshInputInfo mesh; + ShaderTessellationInputInfo tess; + bool fetch_external = false; + bool fetch_embedded = false; +}; + +struct ShaderComputeInputInfo: ShaderWorkgroupInputInfo { + bool async_compute = false; + uint8_t float_mode = 0xc0; + uint32_t dispatch_threads_num[3] = {0, 0, 0}; + uint32_t workgroup_counts[3] = {0, 0, 0}; + uint64_t indirect_args_address = 0; + bool group_id[3] = {false, false, false}; + bool dispatch_thread_dimensions = false; + bool lds_storage = false; + int thread_ids_num = 0; + int workgroup_register = 0; + bool tg_size_en = false; + ShaderStageRuntime stage; +}; + +enum class ShaderAlphaBlendSource : uint8_t { None, SourceAlpha, SourceAlphaOne, SourceAlphaZero }; +enum class ShaderPixelParameterMode : uint8_t { FirstVertex, LastVertex, Rectangle }; + +struct ShaderPixelInputInfo { + uint32_t interpolator_settings[32] = {0}; + uint32_t input_num = 0; + uint32_t wave_size = 64; + uint32_t ps_system_input_base = 0; + uint32_t custom_interpolation_mask = 0; + uint32_t ps_perspective_center_vgpr = UINT32_MAX; + uint32_t ps_perspective_sample_vgpr = UINT32_MAX; + uint32_t ps_perspective_centroid_vgpr = UINT32_MAX; + uint8_t target_output_mode[8] = {}; + uint32_t target_shader_mask = UINT32_MAX; + std::array target_export_mapping = {}; + uint8_t target_packed_unorm_mask = 0; + // CB round mode per converted export: zero adds half an LSB, one truncates. + uint8_t target_round_mode = 0; + uint32_t scratch_size_dwords = 0; + bool ps_pos_x = false; + bool ps_pos_y = false; + bool ps_pos_z = false; + bool ps_pos_w = false; + bool ps_front_face = false; + bool ps_front_face_all_bits = false; + bool ps_ancillary = false; + bool ps_no_perspective = false; + ShaderPixelParameterMode parameter_mode = ShaderPixelParameterMode::FirstVertex; + bool mesh_stage = false; + bool ps_pixel_kill_enable = false; + bool ps_depth_export_enable = false; + bool ps_sample_mask_export_enable = false; + bool ps_sample_shading = false; + bool dual_source_blending = false; + bool object_primitive_id = false; + // Export logical alpha or per-channel source factors through MRT1 after channel swizzling. + ShaderAlphaBlendSource alpha_blend_source = ShaderAlphaBlendSource::None; + bool ps_early_z = false; + bool ps_execute_on_noop = false; + ShaderStageRuntime stage; + + bool HasPositionInput() const { return ps_pos_x || ps_pos_y || ps_pos_z || ps_pos_w; } +}; + +union ShaderStageInputInfo { + const ShaderVertexInputInfo* vertex; + const ShaderPixelInputInfo* pixel; + const ShaderComputeInputInfo* compute = nullptr; +}; + +inline const ShaderWorkgroupInputInfo* ShaderWorkgroupInput(ShaderType stage, + ShaderStageInputInfo input) { + switch (stage) { + case ShaderType::Compute: return input.compute; + case ShaderType::Mesh: return &input.vertex->mesh; + default: return nullptr; + } +} + +uint32_t ShaderPixelParameterMappedLocation(const ShaderPixelInputInfo& info, uint32_t input); +uint32_t ShaderPixelParameterLocation(const ShaderPixelInputInfo& info, + std::span active_inputs, uint32_t input); +bool ShaderPixelParameterIsFlat(const ShaderPixelInputInfo& info, uint32_t input); +bool ShaderPixelParameterIsCustom(const ShaderPixelInputInfo& info, uint32_t input); + +struct ShaderSharp { + uint16_t offset_dw : 15; + uint16_t size : 1; +}; + +struct ShaderUserData { + uint16_t* direct_resource_offset; + ShaderSharp* sharp_resource_offset[4]; + uint16_t eud_size_dw; + uint16_t srt_size_dw; + uint16_t direct_resource_count; + uint16_t sharp_resource_count[4]; +}; + +struct ShaderRegisterRange { + uint16_t start; + uint16_t end; +}; + +struct ShaderDrawModifier { + uint32_t enbl_start_vertex_offset : 1; + uint32_t enbl_start_index_offset : 1; + uint32_t enbl_start_instance_offset : 1; + uint32_t enbl_draw_index : 1; + uint32_t enbl_user_vgprs : 1; + uint32_t render_target_slice_offset : 3; + uint32_t fuse_draws : 1; + uint32_t compiler_flags : 23; + uint32_t is_default : 1; + uint32_t reserved : 31; +}; + +struct ShaderRegister { + uint32_t offset; + uint32_t value; +}; + +struct ShaderSpecialRegs { + ShaderRegister ge_cntl; + ShaderRegister vgt_shader_stages_en; + uint32_t dispatch_modifier; + ShaderRegisterRange user_data_range; + ShaderDrawModifier draw_modifier; + ShaderRegister vgt_gs_out_prim_type; + ShaderRegister ge_user_vgpr_en; +}; + +struct ShaderSemantic { + uint32_t semantic : 8; + uint32_t hardware_mapping : 8; + uint32_t size_in_elements : 4; + uint32_t is_f16 : 2; + uint32_t is_flat_shaded : 1; + uint32_t is_linear : 1; + uint32_t is_custom : 1; + uint32_t static_vb_index : 1; + uint32_t static_attribute : 1; + uint32_t reserved : 1; + uint32_t default_value : 2; + uint32_t default_value_hi : 2; +}; + +struct Shader { + uint32_t file_header; + uint32_t version; + ShaderUserData* user_data; + const volatile void* code; + ShaderRegister* cx_registers; + ShaderRegister* sh_registers; + ShaderSpecialRegs* specials; + ShaderSemantic* input_semantics; + ShaderSemantic* output_semantics; + uint32_t header_size; + uint32_t shader_size; + uint32_t embedded_constant_buffer_size_dqw; + uint32_t target; + uint32_t num_input_semantics; + uint16_t scratch_size_dw_per_thread; + uint16_t num_output_semantics; + uint16_t special_sizes_bytes; + uint8_t type; + uint8_t num_cx_registers; + uint8_t num_sh_registers; +}; + +struct ShaderMappedData { + Prospero::ShaderBinaryType type {}; + ShaderUserData* user_data = nullptr; + ShaderSemantic* input_semantics = nullptr; + uint32_t num_input_semantics = 0; + uint32_t code_size_bytes = 0; + uint32_t scratch_size_dwords = 0; +}; + +void ShaderInit(); +void ShaderMapUserData(uint64_t addr, const ShaderMappedData& data); +uint32_t ShaderPixelExportTarget(uint32_t shader_mask, uint32_t export_index); + +void ShaderDbgDumpInputInfo(const ShaderVertexInputInfo& info); +void ShaderDbgDumpInputInfo(const ShaderPixelInputInfo& info); +void ShaderDbgDumpInputInfo(const ShaderComputeInputInfo& info); + +} // namespace Libs::Graphics + +#endif /* EMULATOR_INCLUDE_EMULATOR_GRAPHICS_SHADER_H_ */ diff --git a/tests/test_moltenvk_mesh_budget.py b/tests/test_moltenvk_mesh_budget.py index 58971e92..640fc7f3 100644 --- a/tests/test_moltenvk_mesh_budget.py +++ b/tests/test_moltenvk_mesh_budget.py @@ -1,54 +1,54 @@ -#!/usr/bin/env python3 -"""Test exact upstream source anchors and compile the patched arithmetic.""" -import importlib.util -from pathlib import Path -import sys -import tempfile -import subprocess - -root = Path(__file__).resolve().parents[1] -spec = importlib.util.spec_from_file_location("mesh_budget", root / "scripts/patch_moltenvk_mesh_budget.py") -module = importlib.util.module_from_spec(spec) -spec.loader.exec_module(module) -fixture = "\t\t\tcase VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_EXT: {\n\t\t\t\tauto* meshProps = (VkPhysicalDeviceMeshShaderPropertiesEXT*)next;\n\t\t\t\tauto& lim = _properties.limits;\n\t\t\t\t// object grids are unbounded, mesh grids are bounded per GPU family by the Metal feature set tables,\n\t\t\t\t// and each mesh grid dimension is 16 bits. payload is object memory.\n\t\t\t\tuint32_t meshGrid = _gpuCapabilities.supportsApple10 ? (1u << 22) - 1 : _gpuCapabilities.supportsApple9 ? (1u << 20) - 1 : 1024;\n\t\t\t\tuint32_t payload = 16 * KIBI;\n\t\t\t\tuint32_t meshVerts = 256, meshPrims = 512;\t\t// metal::mesh limits\n\t\t\t\t// SPIRV-Cross stages mesh outputs, their counts (a uint2) and triangle indices (a 16-byte uint3 each) in threadgroup\n\t\t\t\t// memory next to shared variables, so shared and output memory split the rest. Metal takes 16 bytes of object\n\t\t\t\t// threadgroup memory (measured).\n\t\t\t\tuint32_t meshShared = (lim.maxComputeSharedMemorySize - sizeof(uint32_t[2]) - meshPrims * sizeof(uint32_t[4])) / 2;\n\t\t\t\tuint32_t taskShared = lim.maxComputeSharedMemorySize - 16;\n\t\t\t\tfor (uint32_t i = 0; i < 3; i++) {\n\t\t\t\t\tmeshProps->maxTaskWorkGroupCount[i] = lim.maxComputeWorkGroupCount[i];\n\t\t\t\t\tmeshProps->maxTaskWorkGroupSize[i] = meshProps->maxMeshWorkGroupSize[i] = lim.maxComputeWorkGroupSize[i];\n\t\t\t\t\tmeshProps->maxMeshWorkGroupCount[i] = std::min(meshGrid, numeric_limits::max());\n\t\t\t\t}\n\t\t\t\tmeshProps->maxTaskWorkGroupTotalCount = kMVKUndefinedLargeUInt32;\n\t\t\t\tmeshProps->maxTaskWorkGroupInvocations = meshProps->maxMeshWorkGroupInvocations = lim.maxComputeWorkGroupInvocations;\n\t\t\t\tmeshProps->maxTaskPayloadSize = payload;\n\t\t\t\tmeshProps->maxTaskSharedMemorySize = taskShared;\n\t\t\t\tmeshProps->maxTaskPayloadAndSharedMemorySize = payload + taskShared;\n\t\t\t\tmeshProps->maxMeshSharedMemorySize = meshProps->maxMeshOutputMemorySize = meshShared;\n\t\t\t\tmeshProps->maxMeshPayloadAndSharedMemorySize = meshProps->maxMeshPayloadAndOutputMemorySize = payload + meshShared;\n\t\t\t\tmeshProps->maxMeshWorkGroupTotalCount = meshGrid;\n\t\t\t\tmeshProps->maxMeshOutputComponents = lim.maxVertexOutputComponents;\n\t\t\t\tmeshProps->maxMeshOutputVertices = meshVerts;\n\t\t\t\tmeshProps->maxMeshOutputPrimitives = meshPrims;\n\t\t\t\tmeshProps->maxMeshOutputLayers = lim.maxFramebufferLayers;\n\t\t\t\tmeshProps->maxMeshMultiviewViewCount = 1;\n\t\t\t\tmeshProps->meshOutputPerVertexGranularity = meshProps->meshOutputPerPrimitiveGranularity = 1;\n\t\t\t\tmeshProps->maxPreferredTaskWorkGroupInvocations = meshProps->maxPreferredMeshWorkGroupInvocations = _metalFeatures.maxSubgroupSize;\n\t\t\t\tmeshProps->prefersLocalInvocationVertexOutput = meshProps->prefersLocalInvocationPrimitiveOutput = false;\n\t\t\t\tmeshProps->prefersCompactVertexOutput = meshProps->prefersCompactPrimitiveOutput = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTI_DRAW_PROPERTIES_EXT: {\n\t\t\t\tauto* multiDrawProps = (VkPhysicalDeviceMultiDrawPropertiesEXT*)next;\n\t\t\t\t// Each draw is encoded as a separate command, so no limit is imposed.\n" -patched = module.patched_source(fixture) -assert "meshOutput -= sizeof(uint32_t);" in patched -assert "maxMeshOutputMemorySize = meshOutput;" in patched -assert "maxMeshPayloadAndOutputMemorySize = payload + meshOutput;" in patched -try: - module.patched_source(patched) -except ValueError: - pass -else: - raise AssertionError("Double application must fail") - -start = patched.index("const uint32_t meshStaging =") -end = patched.index("uint32_t taskShared", start) -arithmetic = patched[start:end] -code = """#include -#include -#include -constexpr uint32_t KIBI = 1024; -std::pair budget(uint32_t available, uint32_t meshPrims) { - struct { uint32_t maxComputeSharedMemorySize; } lim{available}; -""" + arithmetic + """ - return {meshShared, meshOutput}; -} -int main() { - const auto [lds, output] = budget(32768, 512); - assert(lds == 12288 && output == 12280); - assert(lds + output + 8200 == 32768); - const auto [otherLds, otherOutput] = budget(65536, 512); - assert(otherLds == 28668 && otherOutput == 28668); - const auto [smallLds, smallOutput] = budget(8192, 512); - assert(smallLds == 0 && smallOutput == 0); - return 0; -} -""" -with tempfile.TemporaryDirectory() as work: - path = Path(work) - (path / "test.cpp").write_text(code, encoding="utf-8") - executable = path / ("test.exe" if sys.platform == "win32" else "test") - subprocess.run([sys.argv[1], "-std=c++17", "-Wall", "-Wextra", "-Werror", str(path / "test.cpp"), "-o", str(executable)], check=True) - subprocess.run([str(executable)], check=True) -print("MoltenVK mesh-budget source and arithmetic checks passed") +#!/usr/bin/env python3 +"""Test exact upstream source anchors and compile the patched arithmetic.""" +import importlib.util +from pathlib import Path +import sys +import tempfile +import subprocess + +root = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location("mesh_budget", root / "scripts/patch_moltenvk_mesh_budget.py") +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) +fixture = "\t\t\tcase VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_EXT: {\n\t\t\t\tauto* meshProps = (VkPhysicalDeviceMeshShaderPropertiesEXT*)next;\n\t\t\t\tauto& lim = _properties.limits;\n\t\t\t\t// object grids are unbounded, mesh grids are bounded per GPU family by the Metal feature set tables,\n\t\t\t\t// and each mesh grid dimension is 16 bits. payload is object memory.\n\t\t\t\tuint32_t meshGrid = _gpuCapabilities.supportsApple10 ? (1u << 22) - 1 : _gpuCapabilities.supportsApple9 ? (1u << 20) - 1 : 1024;\n\t\t\t\tuint32_t payload = 16 * KIBI;\n\t\t\t\tuint32_t meshVerts = 256, meshPrims = 512;\t\t// metal::mesh limits\n\t\t\t\t// SPIRV-Cross stages mesh outputs, their counts (a uint2) and triangle indices (a 16-byte uint3 each) in threadgroup\n\t\t\t\t// memory next to shared variables, so shared and output memory split the rest. Metal takes 16 bytes of object\n\t\t\t\t// threadgroup memory (measured).\n\t\t\t\tuint32_t meshShared = (lim.maxComputeSharedMemorySize - sizeof(uint32_t[2]) - meshPrims * sizeof(uint32_t[4])) / 2;\n\t\t\t\tuint32_t taskShared = lim.maxComputeSharedMemorySize - 16;\n\t\t\t\tfor (uint32_t i = 0; i < 3; i++) {\n\t\t\t\t\tmeshProps->maxTaskWorkGroupCount[i] = lim.maxComputeWorkGroupCount[i];\n\t\t\t\t\tmeshProps->maxTaskWorkGroupSize[i] = meshProps->maxMeshWorkGroupSize[i] = lim.maxComputeWorkGroupSize[i];\n\t\t\t\t\tmeshProps->maxMeshWorkGroupCount[i] = std::min(meshGrid, numeric_limits::max());\n\t\t\t\t}\n\t\t\t\tmeshProps->maxTaskWorkGroupTotalCount = kMVKUndefinedLargeUInt32;\n\t\t\t\tmeshProps->maxTaskWorkGroupInvocations = meshProps->maxMeshWorkGroupInvocations = lim.maxComputeWorkGroupInvocations;\n\t\t\t\tmeshProps->maxTaskPayloadSize = payload;\n\t\t\t\tmeshProps->maxTaskSharedMemorySize = taskShared;\n\t\t\t\tmeshProps->maxTaskPayloadAndSharedMemorySize = payload + taskShared;\n\t\t\t\tmeshProps->maxMeshSharedMemorySize = meshProps->maxMeshOutputMemorySize = meshShared;\n\t\t\t\tmeshProps->maxMeshPayloadAndSharedMemorySize = meshProps->maxMeshPayloadAndOutputMemorySize = payload + meshShared;\n\t\t\t\tmeshProps->maxMeshWorkGroupTotalCount = meshGrid;\n\t\t\t\tmeshProps->maxMeshOutputComponents = lim.maxVertexOutputComponents;\n\t\t\t\tmeshProps->maxMeshOutputVertices = meshVerts;\n\t\t\t\tmeshProps->maxMeshOutputPrimitives = meshPrims;\n\t\t\t\tmeshProps->maxMeshOutputLayers = lim.maxFramebufferLayers;\n\t\t\t\tmeshProps->maxMeshMultiviewViewCount = 1;\n\t\t\t\tmeshProps->meshOutputPerVertexGranularity = meshProps->meshOutputPerPrimitiveGranularity = 1;\n\t\t\t\tmeshProps->maxPreferredTaskWorkGroupInvocations = meshProps->maxPreferredMeshWorkGroupInvocations = _metalFeatures.maxSubgroupSize;\n\t\t\t\tmeshProps->prefersLocalInvocationVertexOutput = meshProps->prefersLocalInvocationPrimitiveOutput = false;\n\t\t\t\tmeshProps->prefersCompactVertexOutput = meshProps->prefersCompactPrimitiveOutput = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTI_DRAW_PROPERTIES_EXT: {\n\t\t\t\tauto* multiDrawProps = (VkPhysicalDeviceMultiDrawPropertiesEXT*)next;\n\t\t\t\t// Each draw is encoded as a separate command, so no limit is imposed.\n" +patched = module.patched_source(fixture) +assert "meshShared = 16u * KIBI;" in patched +assert "maxMeshOutputMemorySize = meshOutput;" in patched +assert "maxMeshPayloadAndOutputMemorySize = payload + meshOutput;" in patched +try: + module.patched_source(patched) +except ValueError: + pass +else: + raise AssertionError("Double application must fail") + +start = patched.index("const uint32_t meshStaging =") +end = patched.index("uint32_t taskShared", start) +arithmetic = patched[start:end] +code = """#include +#include +#include +constexpr uint32_t KIBI = 1024; +std::pair budget(uint32_t available, uint32_t meshPrims) { + struct { uint32_t maxComputeSharedMemorySize; } lim{available}; +""" + arithmetic + """ + return {meshShared, meshOutput}; +} +int main() { + const auto [lds, output] = budget(32768, 512); + assert(lds == 16384 && output == 8184); + assert(lds + output + 8200 == 32768); + const auto [otherLds, otherOutput] = budget(65536, 512); + assert(otherLds == 28668 && otherOutput == 28668); + const auto [smallLds, smallOutput] = budget(8192, 512); + assert(smallLds == 0 && smallOutput == 0); + return 0; +} +""" +with tempfile.TemporaryDirectory() as work: + path = Path(work) + (path / "test.cpp").write_text(code, encoding="utf-8") + executable = path / ("test.exe" if sys.platform == "win32" else "test") + subprocess.run([sys.argv[1], "-std=c++17", "-Wall", "-Wextra", "-Werror", str(path / "test.cpp"), "-o", str(executable)], check=True) + subprocess.run([str(executable)], check=True) +print("MoltenVK mesh-budget source and arithmetic checks passed")