fix(shader): publish prepared stage groups atomically + preserve snapshot lifetime

This commit is contained in:
boykopovar
2026-10-06 18:36:08 +03:00
parent b157046640
commit d21c4b737b
11 changed files with 404 additions and 26 deletions
+2 -1
View File
@@ -361,12 +361,13 @@ endif()
add_test_executable(agc_shader_helpers_tests EXCLUDE_FROM_ALL
tests/ShaderHelpers.cpp
Shader/src/LinkShaders.cpp
Shader/src/PrimState.cpp
Shader/src/InterpolantMapping.cpp
Shader/src/ShaderUtils.cpp
)
target_include_directories(agc_shader_helpers_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_shader_helpers_tests PRIVATE libc)
target_link_libraries(agc_shader_helpers_tests PRIVATE libc libSceAgcDriver)
configure_windows_unwind(agc_shader_helpers_tests)
if(BUILD_TESTING)
set_target_properties(agc_shader_helpers_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
@@ -1,10 +1,13 @@
#include "prx/libSceAgc/Shader/include/InterpolantMapping.hpp"
#include <cstdio>
#include <array>
#include <algorithm>
#include <stdexcept>
#include <prx/libc/include/General.hpp>
#include "SceShaders.hpp"
#include "prx/libSceAgcDriver/Execution/include/ShaderPreparation.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver.hpp"
#include "prx/libSceAgc/Shader/include/ShaderUtils.hpp"
#include "prx/libSceAgc/Shader/include/ShaderConstants.hpp"
@@ -54,13 +57,22 @@ int CreateInterpolantMapping(const char* fn, ShaderRegister* regs, const Shader*
if (regs == nullptr) {
throw std::runtime_error(std::string(fn) + ": regs is null");
}
if (ps != nullptr && ps->num_input_semantics > 32) {
throw std::runtime_error(std::string(fn) + ": input semantic count exceeds 32");
}
AgcDriver::DriverDetail::ShaderPreparationTransaction transaction;
std::array<ShaderRegister, 32> values{};
auto* output = regs;
regs = values.data();
if (ps == nullptr || ps->num_input_semantics == 0) {
FillIdentityInterpolants(regs, 0);
if (ps != nullptr) {
AgcDriverResolveShaderAbi_nid_postfix(ps, {regs, 32}, {});
if (gs != nullptr) AgcDriverResolveGraphicsAbi_nid_postfix(gs, ps, 0);
}
transaction.Commit();
std::copy(values.begin(), values.end(), output);
return 0;
}
@@ -89,6 +101,8 @@ int CreateInterpolantMapping(const char* fn, ShaderRegister* regs, const Shader*
FillIdentityInterpolants(regs, ps->num_input_semantics);
AgcDriverResolveShaderAbi_nid_postfix(ps, {regs, 32}, {});
AgcDriverResolveGraphicsAbi_nid_postfix(gs, ps, 0);
transaction.Commit();
std::copy(values.begin(), values.end(), output);
return 0;
}
@@ -1,4 +1,5 @@
#include "SceShaders.hpp"
#include "prx/libSceAgcDriver/Execution/include/ShaderPreparation.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver.hpp"
#include "prx/libc/include/general/VabiMacros.hpp"
#include "prx/libSceAgc/Shader/include/ShaderConstants.hpp"
@@ -21,11 +22,13 @@ extern "C" int APS5_VABI sceAgcLinkShaders(ShaderRegister* context, ShaderRegist
// The simple vertex/pixel pipeline combines two primitive context registers
// and 32 interpolant registers. Publish only after both helpers succeed.
AgcDriver::DriverDetail::ShaderPreparationTransaction transaction;
std::array<ShaderRegister, 34> contextValues{};
std::array<ShaderRegister, 3> primitiveValues{};
sceAgcCreatePrimState(contextValues.data(), primitiveValues.data(), nullptr, vertex, primitiveType);
sceAgcCreateInterpolantMapping(contextValues.data() + 2, vertex, pixel);
AgcDriverResolveGraphicsAbi_nid_postfix(vertex, pixel, primitiveType);
transaction.Commit();
std::copy(contextValues.begin(), contextValues.end(), context);
std::copy(primitiveValues.begin(), primitiveValues.end(), primitive);
return 0;
@@ -9,6 +9,7 @@
#include <stdexcept>
#include <iostream>
extern "C" int APS5_VABI sceAgcLinkShaders(ShaderRegister*, ShaderRegister*, const void*, const Shader*, const Shader*, std::uint32_t);
extern "C" int APS5_VABI sceAgcCreatePrimState(ShaderRegister*, ShaderRegister*, const Shader*, const Shader*, std::uint32_t);
extern "C" int APS5_VABI sceAgcCreateInterpolantMapping(ShaderRegister*, const Shader*, const Shader*);
@@ -19,6 +20,7 @@ std::size_t stageCount = 0;
unsigned preparations = 0;
unsigned mappings = 0;
unsigned links = 0;
bool rejectLink = false;
const Shader* mappedPixel = nullptr;
void Require(bool condition) {
@@ -41,7 +43,8 @@ extern "C" void AgcDriverResolveShaderAbi_nid_postfix(const Shader* shader, std:
}
extern "C" void AgcDriverResolveGraphicsAbi_nid_postfix(const Shader* vertex, const Shader* pixel, std::uint32_t primitiveType) {
Require(vertex != nullptr && pixel == mappedPixel && primitiveType == 0);
if (rejectLink) throw std::runtime_error("injected link failure");
Require(vertex != nullptr && pixel == mappedPixel && (primitiveType == 0 || primitiveType == 7));
++links;
}
@@ -88,6 +91,32 @@ int main() {
}
}
}
std::array<ShaderRegister, 34> linkedContext{};
std::array<ShaderRegister, 3> linkedPrimitive{};
for (auto& value : linkedContext) value.value = 0xdeadbeef;
for (auto& value : linkedPrimitive) value.value = 0xdeadbeef;
for (auto& value : interpolants) value.value = 0xdeadbeef;
rejectLink = true;
bool rejected = false;
try { sceAgcLinkShaders(linkedContext.data(), linkedPrimitive.data(), nullptr, &vertex, &pixel, 7); }
catch (const std::runtime_error&) { rejected = true; }
Require(rejected);
for (const auto value : linkedContext) Require(value.value == 0xdeadbeef);
for (const auto value : linkedPrimitive) Require(value.value == 0xdeadbeef);
rejected = false;
try { sceAgcCreateInterpolantMapping(interpolants.data(), &vertex, &pixel); }
catch (const std::runtime_error&) { rejected = true; }
Require(rejected);
for (const auto value : interpolants) Require(value.value == 0xdeadbeef);
rejectLink = false;
pixel.num_input_semantics = 33;
rejected = false;
try { sceAgcCreateInterpolantMapping(interpolants.data(), &vertex, &pixel); }
catch (const std::runtime_error&) { rejected = true; }
Require(rejected);
for (const auto value : interpolants) Require(value.value == 0xdeadbeef);
pixel.num_input_semantics = 1;
Require(sceAgcLinkShaders(linkedContext.data(), linkedPrimitive.data(), nullptr, &vertex, &pixel, 7) == 0);
preparations = mappings = links = 0;
Require(sceAgcCreatePrimState(nullptr, nullptr, nullptr, nullptr, 7) == 0);
Require(sceAgcCreateInterpolantMapping(interpolants.data(), &vertex, nullptr) == 0);
@@ -608,6 +608,8 @@ endforeach()
target_include_directories(agc_driver_prepared_exports_tests PRIVATE $<TARGET_PROPERTY:shader_recompiler_agc_driver,INTERFACE_INCLUDE_DIRECTORIES>)
target_include_directories(agc_driver_prepared_publication_tests PRIVATE $<TARGET_PROPERTY:shader_recompiler_agc_driver,INTERFACE_INCLUDE_DIRECTORIES>)
target_include_directories(agc_driver_prepared_graphics_tests PRIVATE $<TARGET_PROPERTY:shader_recompiler_agc_driver,INTERFACE_INCLUDE_DIRECTORIES>)
target_include_directories(agc_driver_prepared_shaders_tests PRIVATE
@@ -16,7 +16,7 @@ namespace AgcDriver::DriverDetail {
struct ShaderSnapshot;
struct PreparedShaders {
struct PreparedShaderState {
struct Entry {
std::size_t codeOffset;
std::shared_ptr<const ShaderRecompiler::SourceHandle> handle;
@@ -26,19 +26,22 @@ struct PreparedShaders {
std::uint64_t fragmentId;
ShaderRecompiler::RectListShaders shaders;
};
std::mutex mutex;
std::vector<Entry> entries;
std::vector<Rectangle> rectangles;
std::vector<std::weak_ptr<const ShaderSnapshot>> fragments;
bool rectangleRequested = false;
};
struct PreparedShaders : PreparedShaderState {
std::mutex mutex;
};
struct ShaderSnapshot {
std::uint64_t codeAddress;
std::uint64_t headerAddress;
std::uint8_t type;
std::vector<std::uint32_t> code;
std::vector<std::byte> header;
std::unique_ptr<PreparedShaders> prepared = std::make_unique<PreparedShaders>();
std::shared_ptr<PreparedShaders> prepared = std::make_shared<PreparedShaders>();
};
using ShaderRegistry = std::map<std::uint64_t, std::shared_ptr<const ShaderSnapshot>>;
@@ -46,6 +49,8 @@ using ShaderRegistry = std::map<std::uint64_t, std::shared_ptr<const ShaderSnaps
std::shared_ptr<const ShaderSnapshot> ReadRawComputeShader(std::uint64_t address);
std::uint64_t NullPixelProgramAddress();
void PublishRegisteredShader(std::shared_ptr<ShaderRegistry>& registry, const std::shared_ptr<const ShaderSnapshot>& snapshot);
void ResolvePreparedGraphics(const ShaderSnapshot& front, const std::shared_ptr<const ShaderSnapshot>& fragment, std::uint32_t primitiveType, const ShaderRecompiler::SpirvTarget& target);
ShaderRecompiler::RectListShaders PreparedRectangle(const ShaderSnapshot& snapshot, std::uint64_t vertexId, std::uint64_t fragmentId);
@@ -0,0 +1,27 @@
#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_SHADERPREPARATION_HPP
#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_SHADERPREPARATION_HPP
#include <memory>
namespace AgcDriver::DriverDetail {
struct ShaderSnapshot;
struct PreparedShaderState;
class ShaderPreparationTransaction {
public:
ShaderPreparationTransaction();
~ShaderPreparationTransaction();
ShaderPreparationTransaction(const ShaderPreparationTransaction&) = delete;
ShaderPreparationTransaction& operator=(const ShaderPreparationTransaction&) = delete;
PreparedShaderState& Edit(const ShaderSnapshot& snapshot);
void Commit();
private:
struct State;
std::unique_ptr<State> state;
};
}
#endif
@@ -6,6 +6,7 @@
#include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "CacheKey.hpp"
#include "prx/libSceAgcDriver/Execution/include/ShaderPreparation.hpp"
#include "CompiledVariant.hpp"
#include "Optimization/ResourceProgram.hpp"
#include <cstdlib>
@@ -83,6 +84,76 @@ std::shared_ptr<const ShaderSnapshot> ReadRawComputeShader(std::uint64_t address
}
struct ShaderPreparationTransaction::State {
struct Change {
std::shared_ptr<PreparedShaders> destination;
PreparedShaderState prepared;
};
static std::recursive_mutex writers;
static thread_local State* active;
std::unique_lock<std::recursive_mutex> lock{writers};
State* parent = active;
State* root = parent == nullptr ? this : parent->root;
std::map<PreparedShaders*, Change> changes;
bool committed = false;
bool failed = false;
};
std::recursive_mutex ShaderPreparationTransaction::State::writers;
thread_local ShaderPreparationTransaction::State* ShaderPreparationTransaction::State::active = nullptr;
ShaderPreparationTransaction::ShaderPreparationTransaction() : state(std::make_unique<State>()) {
State::active = state.get();
}
ShaderPreparationTransaction::~ShaderPreparationTransaction() {
if (!state->committed) state->root->failed = true;
State::active = state->parent;
}
PreparedShaderState& ShaderPreparationTransaction::Edit(const ShaderSnapshot& snapshot) {
require(!state->committed, "shader preparation transaction is already committed");
auto& changes = state->root->changes;
const auto found = changes.find(snapshot.prepared.get());
if (found != changes.end()) return found->second.prepared;
std::lock_guard lock(snapshot.prepared->mutex);
return changes.emplace(snapshot.prepared.get(), State::Change{snapshot.prepared, *snapshot.prepared}).first->second.prepared;
}
void ShaderPreparationTransaction::Commit() {
require(!state->committed && !state->root->failed, "shader preparation transaction was aborted");
if (state->parent == nullptr) {
std::vector<std::unique_lock<std::mutex>> locks;
locks.reserve(state->changes.size());
for (const auto& [key, change] : state->changes) locks.emplace_back(change.destination->mutex);
for (auto& [key, change] : state->changes) {
auto& destination = *change.destination;
destination.entries.swap(change.prepared.entries);
destination.rectangles.swap(change.prepared.rectangles);
destination.fragments.swap(change.prepared.fragments);
std::swap(destination.rectangleRequested, change.prepared.rectangleRequested);
}
}
state->committed = true;
}
void PublishRegisteredShader(std::shared_ptr<ShaderRegistry>& registry, const std::shared_ptr<const ShaderSnapshot>& snapshot) {
ShaderPreparationTransaction transaction;
if (registry != nullptr) {
const auto found = registry->find(snapshot->codeAddress);
if (found != registry->end()) {
const auto& current = *found->second;
if (current.headerAddress == snapshot->headerAddress && current.type == snapshot->type && current.code == snapshot->code && current.header == snapshot->header) {
transaction.Commit();
return;
}
}
}
auto next = registry != nullptr ? std::make_shared<ShaderRegistry>(*registry) : std::make_shared<ShaderRegistry>();
next->insert_or_assign(snapshot->codeAddress, snapshot);
registry = std::move(next);
transaction.Commit();
}
std::shared_ptr<const ShaderRecompiler::SourceHandle> SourceHandleFor(const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request) {
std::lock_guard lock(snapshot.prepared->mutex);
@@ -285,6 +356,7 @@ std::vector<PreparedGraphicsStage> PrepareGraphicsStages(const DrawDecode& decod
}
void Driver::ResolveGraphicsStagesAbi(std::span<const Shader* const> stages, std::span<const ShaderRegister> context, std::span<const ShaderRegister> primitive) {
ShaderPreparationTransaction transaction;
CheckFailure();
require(!stages.empty(), "graphics ABI has no shader headers");
QueueState state{};
@@ -313,8 +385,7 @@ void Driver::ResolveGraphicsStagesAbi(std::span<const Shader* const> stages, std
require(localDevice != nullptr, "graphics ABI device is missing");
auto prepared = PrepareGraphicsStages(decoded, localDevice->Target());
for (auto& stage : prepared) {
std::lock_guard lock(stage.snapshot->prepared->mutex);
auto& entries = stage.snapshot->prepared->entries;
auto& entries = transaction.Edit(*stage.snapshot).entries;
const auto duplicate = std::ranges::any_of(entries, [&](const auto& existing) { return existing.codeOffset == stage.entry.codeOffset && existing.handle->artifact == stage.entry.handle->artifact; });
if (!duplicate) entries.push_back(std::move(stage.entry));
}
@@ -323,14 +394,17 @@ void Driver::ResolveGraphicsStagesAbi(std::span<const Shader* const> stages, std
if (stage.snapshot->type == 1) continue;
ResolvePreparedGraphics(*stage.snapshot, {}, primitiveType == state.userConfig.end() ? 0u : primitiveType->second, localDevice->Target());
}
transaction.Commit();
}
void Driver::ResolveShaderAbi(const Shader* shader, std::span<const ShaderRegister> context, std::span<const ShaderRegister> primitive) {
ShaderPreparationTransaction transaction;
CheckFailure();
GuestMemory::CheckRange(shader, sizeof(Shader), alignof(Shader));
if (shader->type != 0 && shader->type != 1) {
const std::array<const Shader*, 1> stages{shader};
ResolveGraphicsStagesAbi(stages, context, primitive);
transaction.Commit();
return;
}
std::shared_ptr<const ShaderSnapshot> snapshot;
@@ -347,11 +421,12 @@ void Driver::ResolveShaderAbi(const Shader* shader, std::span<const ShaderRegist
const auto localDevice = device.Load();
require(localDevice != nullptr, "shader registration device is missing");
auto entries = PrepareRegistered(*snapshot, *localDevice, state, false);
std::lock_guard lock(snapshot->prepared->mutex);
auto& prepared = transaction.Edit(*snapshot);
for (auto& entry : entries) {
const auto duplicate = std::ranges::any_of(snapshot->prepared->entries, [&](const auto& existing) { return existing.handle->artifact == entry.handle->artifact; });
if (!duplicate) snapshot->prepared->entries.push_back(std::move(entry));
const auto duplicate = std::ranges::any_of(prepared.entries, [&](const auto& existing) { return existing.handle->artifact == entry.handle->artifact; });
if (!duplicate) prepared.entries.push_back(std::move(entry));
}
transaction.Commit();
}
alignas(256) static const std::uint32_t NullPixelCode[64] = {0xbf810000u};
@@ -371,8 +446,12 @@ std::uint64_t NullPixelProgramAddress() {
}
void Driver::ResolveGraphicsAbi(const Shader* vertex, const Shader* pixel, std::uint32_t primitiveType) {
ShaderPreparationTransaction transaction;
CheckFailure();
if (primitiveType != 0 && primitiveType != 7 && primitiveType != 17) return;
if (primitiveType != 0 && primitiveType != 7 && primitiveType != 17) {
transaction.Commit();
return;
}
require(vertex != nullptr && pixel != nullptr, "rectangle ABI requires vertex and fragment shaders");
std::shared_ptr<const ShaderSnapshot> front;
std::shared_ptr<const ShaderSnapshot> fragment;
@@ -394,32 +473,37 @@ void Driver::ResolveGraphicsAbi(const Shader* vertex, const Shader* pixel, std::
const auto localDevice = device.Load();
require(localDevice != nullptr, "shader registration device is missing");
ResolvePreparedGraphics(*front, fragment, primitiveType, localDevice->Target());
transaction.Commit();
}
void ResolvePreparedGraphics(const ShaderSnapshot& front, const std::shared_ptr<const ShaderSnapshot>& fragment, std::uint32_t primitiveType, const ShaderRecompiler::SpirvTarget& target) {
ShaderPreparationTransaction transaction;
require(fragment.get() != &front, "rectangle stages refer to the same shader");
std::vector<std::shared_ptr<const ShaderSnapshot>> fragments;
{
std::lock_guard lock(front.prepared->mutex);
auto& prepared = *front.prepared;
auto& prepared = transaction.Edit(front);
std::erase_if(prepared.fragments, [](const auto& entry) { return entry.expired(); });
if (fragment && !std::ranges::any_of(prepared.fragments, [&](const auto& entry) { return entry.lock() == fragment; })) prepared.fragments.push_back(fragment);
prepared.rectangleRequested |= primitiveType == 7 || primitiveType == 17;
if (!prepared.rectangleRequested) return;
if (!prepared.rectangleRequested) {
transaction.Commit();
return;
}
for (const auto& entry : prepared.fragments) {
if (auto snapshot = entry.lock()) fragments.push_back(std::move(snapshot));
}
}
for (const auto& pixel : fragments) {
std::scoped_lock lock(front.prepared->mutex, pixel->prepared->mutex);
require(!front.prepared->entries.empty() && !pixel->prepared->entries.empty(), "rectangle ABI has missing stage artifacts");
auto& prepared = transaction.Edit(front);
auto& pixelPrepared = transaction.Edit(*pixel);
require(!prepared.entries.empty() && !pixelPrepared.entries.empty(), "rectangle ABI has missing stage artifacts");
std::vector<PreparedShaders::Rectangle> rectangles;
for (const auto& vertexEntry : front.prepared->entries) {
for (const auto& fragmentEntry : pixel->prepared->entries) {
for (const auto& vertexEntry : prepared.entries) {
for (const auto& fragmentEntry : pixelPrepared.entries) {
const auto& vertexArtifact = ShaderRecompiler::GetPreparedArtifact(*vertexEntry.handle);
const auto& fragmentArtifact = ShaderRecompiler::GetPreparedArtifact(*fragmentEntry.handle);
const auto exists = [&](const auto& entry) { return entry.vertexId == vertexArtifact.variantId && entry.fragmentId == fragmentArtifact.variantId; };
if (std::ranges::any_of(front.prepared->rectangles, exists) || std::ranges::any_of(rectangles, exists)) continue;
if (std::ranges::any_of(prepared.rectangles, exists) || std::ranges::any_of(rectangles, exists)) continue;
ShaderRecompiler::RecompileResult vertexResult;
ShaderRecompiler::RecompileResult fragmentResult;
static_cast<ShaderRecompiler::CompiledShaderArtifact&>(vertexResult) = vertexArtifact;
@@ -427,11 +511,13 @@ void ResolvePreparedGraphics(const ShaderSnapshot& front, const std::shared_ptr<
rectangles.push_back({vertexArtifact.variantId, fragmentArtifact.variantId, ShaderRecompiler::BuildRectListShaders(vertexResult, fragmentResult, target)});
}
}
front.prepared->rectangles.insert(front.prepared->rectangles.end(), std::make_move_iterator(rectangles.begin()), std::make_move_iterator(rectangles.end()));
prepared.rectangles.insert(prepared.rectangles.end(), std::make_move_iterator(rectangles.begin()), std::make_move_iterator(rectangles.end()));
}
transaction.Commit();
}
void Driver::RegisterShader(const Shader* shader) {
ShaderPreparationTransaction transaction;
CheckFailure();
GuestMemory::CheckRange(shader, sizeof(Shader), 1);
Shader fields;
@@ -472,19 +558,16 @@ void Driver::RegisterShader(const Shader* shader) {
}
std::lock_guard lock(mutex);
rethrowFailure();
const auto address = snapshot.codeAddress;
if (shaders == nullptr) shaders = std::make_shared<ShaderRegistry>();
else if (shaders.use_count() != 1) shaders = std::make_shared<ShaderRegistry>(*shaders);
shaders->insert_or_assign(address, std::make_shared<const ShaderSnapshot>(std::move(snapshot)));
PublishRegisteredShader(shaders, std::make_shared<const ShaderSnapshot>(std::move(snapshot)));
if (shaders->find(NullPixelProgramAddress()) == shaders->end()) {
ShaderSnapshot null{NullPixelProgramAddress(), reinterpret_cast<std::uintptr_t>(&NullPixelShader), NullPixelShader.type, {}, {}};
null.code.assign(std::begin(NullPixelCode), std::end(NullPixelCode));
null.header.resize(sizeof(Shader));
std::memcpy(null.header.data(), &NullPixelShader, sizeof(Shader));
null.prepared->entries = PrepareRegistered(null, *localDevice, RegisteredState(null), true);
shaders->insert_or_assign(NullPixelProgramAddress(), std::make_shared<const ShaderSnapshot>(std::move(null)));
PublishRegisteredShader(shaders, std::make_shared<const ShaderSnapshot>(std::move(null)));
}
transaction.Commit();
}
}
@@ -1,4 +1,5 @@
#include "VulkanTestDevice.hpp"
#include "prx/libSceAgcDriver/Execution/include/ShaderPreparation.hpp"
#include "SceShaders.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp"
#include "prx/libSceAgcDriver/Graphics/include/ShaderInputState.hpp"
@@ -129,6 +130,18 @@ void Check(AgcDriver::VulkanDevice& device, AgcDriver::Graphics::ShaderPath path
const auto& pixelArtifact = GetPreparedArtifact(*stages.back().entry.handle);
Require(!pixelArtifact.fragmentParameters.empty() && pixelArtifact.fragmentParameters.front().sourceLocation == 3u, "prepared fragment lost interpolant mapping");
if (!mesh && !tessellation) {
const auto frontCount = front.snapshot->prepared->entries.size();
const auto pixelCount = fragment.snapshot->prepared->entries.size();
Reject([&] {
ShaderPreparationTransaction transaction;
transaction.Edit(*front.snapshot).entries.push_back(stages.front().entry);
transaction.Edit(*fragment.snapshot).entries.push_back(stages.back().entry);
auto unsupported = target;
unsupported.tessellation.reset();
ResolvePreparedGraphics(*front.snapshot, fragment.snapshot, 7, unsupported);
transaction.Commit();
}, "tessellation shaders are unavailable");
Require(front.snapshot->prepared->entries.size() == frontCount && fragment.snapshot->prepared->entries.size() == pixelCount && front.snapshot->prepared->rectangles.empty() && front.snapshot->prepared->fragments.empty() && !front.snapshot->prepared->rectangleRequested, "failed rectangle compilation published part of the stage group");
for (const bool primitiveFirst : {false, true}) {
front.snapshot->prepared->rectangles.clear();
front.snapshot->prepared->fragments.clear();
@@ -0,0 +1,187 @@
#include "VulkanTestDevice.hpp"
#include "prx/libSceAgcDriver/Execution/include/ShaderPreparation.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp"
#include "Optimization/ResourceProgram.hpp"
#include <atomic>
#include <barrier>
#include <chrono>
#include <future>
#include <iostream>
#include <thread>
namespace {
using namespace AgcDriver::DriverDetail;
using namespace ShaderRecompiler;
void Require(bool condition, const char* message) {
if (!condition) throw std::runtime_error(message);
}
template<typename TAction>
void Reject(TAction action) {
bool failed = false;
try { action(); } catch (const std::runtime_error&) { failed = true; }
Require(failed, "failed shader transaction was accepted");
}
void Transactions() {
ShaderSnapshot front{};
auto pixel = std::make_shared<ShaderSnapshot>();
{
ShaderPreparationTransaction transaction;
transaction.Edit(front).entries.push_back({1, {}});
{
ShaderPreparationTransaction nested;
nested.Edit(*pixel).entries.push_back({2, {}});
nested.Commit();
}
Require(front.prepared->entries.empty() && pixel->prepared->entries.empty(), "nested preparation published a partial group");
}
Require(front.prepared->entries.empty() && pixel->prepared->entries.empty(), "aborted preparation published artifacts");
{
ShaderPreparationTransaction transaction;
transaction.Edit(front).rectangleRequested = true;
{
ShaderPreparationTransaction nested;
nested.Edit(*pixel).rectangleRequested = true;
}
Reject([&] { transaction.Commit(); });
}
Require(!front.prepared->rectangleRequested && !pixel->prepared->rectangleRequested, "nested abort did not roll back the group");
Reject([&] { ResolvePreparedGraphics(front, pixel, 7, {}); });
Require(!front.prepared->rectangleRequested && front.prepared->fragments.empty(), "failed rectangle preparation published a link");
std::weak_ptr<PreparedShaders> staged;
{
auto temporary = std::make_shared<ShaderSnapshot>();
staged = temporary->prepared;
ShaderPreparationTransaction transaction;
transaction.Edit(*temporary).rectangleRequested = true;
temporary.reset();
Require(!staged.expired(), "pending publication released its destination");
transaction.Commit();
}
Require(staged.expired(), "completed publication retained its destination");
std::barrier start(3);
std::atomic<bool> partial = false;
std::jthread reader([&](std::stop_token stop) {
start.arrive_and_wait();
while (!stop.stop_requested()) {
std::scoped_lock lock(front.prepared->mutex, pixel->prepared->mutex);
if (front.prepared->entries.size() != pixel->prepared->entries.size()) partial = true;
}
});
const auto write = [&] {
start.arrive_and_wait();
for (unsigned i = 0; i < 100; ++i) {
ShaderPreparationTransaction transaction;
transaction.Edit(front).entries.push_back({i, {}});
std::this_thread::yield();
transaction.Edit(*pixel).entries.push_back({i, {}});
transaction.Commit();
}
};
auto first = std::async(std::launch::async, write);
auto second = std::async(std::launch::async, write);
first.get();
second.get();
reader.request_stop();
reader.join();
Require(!partial && front.prepared->entries.size() == 200 && pixel->prepared->entries.size() == 200, "concurrent group publication was partial or lost an update");
}
void Registration(AgcDriver::VulkanDevice& device) {
const std::array<std::uint32_t, 1> code{0xbf810000u};
RecompileRequest request{{ShaderStage::Compute, 0x10000, code, 0, {}}, {32, 0, {}, ShaderComputeStageInfo{{1, 1, 1}, 0, {false, false, false}, false, 0, {}}, {}, {}, {}}, device.ComputeTarget(32), {0, 0, 0, 128}};
const auto handle = PrepareShader(request);
const auto makeSnapshot = [&] {
auto snapshot = std::make_shared<ShaderSnapshot>();
snapshot->codeAddress = 0x10000;
snapshot->headerAddress = 0x20000;
snapshot->code.assign(code.begin(), code.end());
return snapshot;
};
auto original = makeSnapshot();
original->prepared->entries.push_back({0, handle});
original->prepared->rectangleRequested = true;
std::shared_ptr<ShaderRegistry> registry;
PublishRegisteredShader(registry, original);
std::barrier start(4);
std::vector<std::future<void>> workers;
for (unsigned i = 0; i < 4; ++i) {
workers.push_back(std::async(std::launch::async, [&] {
start.arrive_and_wait();
for (unsigned iteration = 0; iteration < 40; ++iteration) {
ShaderPreparationTransaction transaction;
PublishRegisteredShader(registry, makeSnapshot());
const auto current = registry->at(0x10000);
Require(current == original && current->prepared->rectangleRequested, "identical registration replaced a prepared snapshot");
auto& entries = transaction.Edit(*current).entries;
entries.push_back({iteration + 1, handle});
transaction.Commit();
}
}));
}
for (auto& worker : workers) worker.get();
Require(original->prepared->entries.size() == 161, "re-registration lost prepared artifacts");
std::shared_ptr<const ShaderRegistry> submission = registry;
std::weak_ptr<const ShaderSnapshot> old = original;
auto replacement = makeSnapshot();
replacement->headerAddress += 256;
std::promise<void> registering;
auto started = registering.get_future();
std::future<void> replacementWriter;
{
ShaderPreparationTransaction transaction;
transaction.Edit(*original).entries.push_back({999, handle});
replacementWriter = std::async(std::launch::async, [&] {
registering.set_value();
PublishRegisteredShader(registry, replacement);
});
started.get();
Require(replacementWriter.wait_for(std::chrono::milliseconds(0)) == std::future_status::timeout, "replacement interleaved with an unfinished preparation");
Require(original->prepared->entries.size() == 161, "unfinished preparation changed a live snapshot");
transaction.Commit();
}
replacementWriter.get();
Require(registry->at(0x10000) == replacement && submission->at(0x10000) == original, "replacement modified an in-flight registry");
Require(original->prepared->entries.size() == 162 && replacement->prepared->entries.empty(), "stale preparation was published into a replacement snapshot");
original.reset();
request.shader.code = submission->at(0x10000)->code;
const auto invocation = InvocationFor(*submission->at(0x10000), 0, request);
const auto capture = invocation.Capture({});
const auto result = invocation.Materialize(*capture);
Require(result->variantId == GetPreparedArtifact(*handle).variantId, "old submission lost its prepared artifact");
device.Dispatch(*result, 1, 1, 1);
device.WaitIdle();
Require(!old.expired(), "in-flight submission released its snapshot early");
submission.reset();
Require(old.expired(), "completed submission retained an obsolete snapshot");
Require(invocation.Materialize(*capture)->spirv.data() == result->spirv.data(), "prepared handle did not retain its artifact");
auto changed = makeSnapshot();
changed->headerAddress = replacement->headerAddress;
changed->code[0] ^= 1;
PublishRegisteredShader(registry, changed);
Require(registry->at(0x10000) == changed, "changed shader code was treated as identical");
auto metadata = makeSnapshot();
metadata->headerAddress = changed->headerAddress;
metadata->code = changed->code;
metadata->header.push_back(std::byte{1});
PublishRegisteredShader(registry, metadata);
Require(registry->at(0x10000) == metadata, "changed shader metadata was treated as identical");
}
}
int main() {
try {
Transactions();
auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
Registration(*device);
std::cout << "shader publication and lifetime tests passed\n";
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
@@ -11,6 +11,8 @@
#include <string>
#include <string_view>
#include <vector>
#include <future>
#include <barrier>
namespace {
@@ -178,6 +180,18 @@ void Registration(bool indirect) {
header.registers = {{{0x20c, static_cast<std::uint32_t>(address >> 8u)}, {0x20d, static_cast<std::uint32_t>(address >> 40u)}, {0x207, 2}, {0x208, 1}, {0x209, 1}, {0x212, 0}, {0x213, 0}, {0x207, 1}, {0x207, 1}}};
const auto threadRegisterIndex = header.registers.size() - 1;
AgcDriverRegisterShader_nid_postfix(&header.shader);
std::barrier start(4);
std::vector<std::future<void>> registrations;
for (unsigned worker = 0; worker < 4; ++worker) {
registrations.push_back(std::async(std::launch::async, [&] {
start.arrive_and_wait();
for (unsigned iteration = 0; iteration < 8; ++iteration) {
AgcDriverRegisterShader_nid_postfix(&header.shader);
AgcDriverResolveShaderAbi_nid_postfix(&header.shader, {}, {});
}
}));
}
for (auto& registration : registrations) registration.get();
header.registers[1].value |= 0x100u;
ExpectFailure([&] { AgcDriverRegisterShader_nid_postfix(&header.shader); }, "invalid registered program address");
header.registers[1].value &= 0xffu;