diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/ShaderDeviceProfile.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/ShaderDeviceProfile.hpp index 47a154e17..a390c288e 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/ShaderDeviceProfile.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/ShaderDeviceProfile.hpp @@ -15,6 +15,7 @@ public: ShaderDeviceProfile& operator=(const ShaderDeviceProfile&) = delete; ShaderRecompiler::SpirvTarget Target() const { return target; } const VkPhysicalDeviceLimits& Limits() const { return limits; } + bool NullDescriptors() const { return nullDescriptors; } private: ShaderRecompiler::SpirvTarget target; @@ -22,6 +23,7 @@ private: std::vector capabilities; std::vector extensions; std::vector extensionViews; + bool nullDescriptors = false; }; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/ShaderDeviceProfile.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/ShaderDeviceProfile.cpp index 6777cf37b..8db336c80 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/ShaderDeviceProfile.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/ShaderDeviceProfile.cpp @@ -22,6 +22,8 @@ ShaderDeviceProfile::ShaderDeviceProfile(const ShaderRecompiler::SpirvTarget& ta using Graphics::Require; Require(deviceInfo.pEnabledFeatures != nullptr, "shader device profile requires enabled core features"); const auto& core = *deviceInfo.pEnabledFeatures; + const auto* robustness = findFeatures(deviceInfo.pNext, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT); + nullDescriptors = robustness != nullptr && robustness->nullDescriptor == VK_TRUE; const auto* bda = findFeatures(deviceInfo.pNext, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES); const auto* bytes = findFeatures(deviceInfo.pNext, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES); const auto* indexing = findFeatures(deviceInfo.pNext, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES); @@ -32,8 +34,10 @@ ShaderDeviceProfile::ShaderDeviceProfile(const ShaderRecompiler::SpirvTarget& ta Require(target.bdaAbiVersion == ShaderRecompiler::BdaAbi::Version, "shader device profile has an incompatible BDA ABI"); Require(bda != nullptr && bda->bufferDeviceAddress == VK_TRUE && core.shaderInt64 == VK_TRUE, "shader runtime requires enabled bufferDeviceAddress and shaderInt64"); Require(bytes != nullptr && bytes->storageBuffer8BitAccess == VK_TRUE, "shader runtime requires enabled storageBuffer8BitAccess"); + Require(nullDescriptors, "shader runtime requires enabled nullDescriptor"); Require(core.vertexPipelineStoresAndAtomics == VK_TRUE && core.fragmentStoresAndAtomics == VK_TRUE, "shader runtime requires enabled graphics stores and atomics"); Require(limits.maxPushConstantsSize >= ShaderRecompiler::RuntimeAbi::PushConstantDwords * sizeof(std::uint32_t) && limits.maxBoundDescriptorSets > ShaderRecompiler::RuntimeAbi::DescriptorSet, "shader runtime ABI exceeds device limits"); + Require(limits.maxStorageBufferRange >= sizeof(ShaderRecompiler::RuntimeAbi::ShaderData), "shader runtime ShaderData exceeds device limits"); std::ranges::sort(capabilities); capabilities.erase(std::unique(capabilities.begin(), capabilities.end()), capabilities.end()); const auto hasCapability = [&](spv::Capability capability) { return std::ranges::binary_search(capabilities, static_cast(capability)); }; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 9fc9e6434..ff8f0b964 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -1107,6 +1107,18 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window) : state(std::make_u byteFeatures.pNext = &pipelineFeatures; } bdaFeatures.pNext = &byteFeatures; + VkPhysicalDeviceRobustness2FeaturesEXT robustness2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT}; + Graphics::Require(hasExtension(VK_EXT_ROBUSTNESS_2_EXTENSION_NAME), "shader runtime requires VK_EXT_robustness2"); + VkPhysicalDeviceFeatures2 queried{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &robustness2}; + state->InstanceFunction("vkGetPhysicalDeviceFeatures2")(selected, &queried); + Graphics::Require(robustness2.nullDescriptor == VK_TRUE, "shader runtime requires nullDescriptor"); + robustness2 = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT}; + robustness2.nullDescriptor = VK_TRUE; + robustness2.pNext = bdaFeatures.pNext; + bdaFeatures.pNext = &robustness2; + deviceExtensions.push_back(VK_EXT_ROBUSTNESS_2_EXTENSION_NAME); + deviceInfo.enabledExtensionCount = static_cast(deviceExtensions.size()); + deviceInfo.ppEnabledExtensionNames = deviceExtensions.data(); deviceInfo.pNext = &bdaFeatures; auto shaderProfile = std::make_unique(buildTarget(), deviceInfo, state->properties.limits); check(state->InstanceFunction("vkCreateDevice")(selected, &deviceInfo, nullptr, &state->device), "vkCreateDevice"); @@ -2518,6 +2530,7 @@ Graphics::Context VulkanDevice::buildContext() const { context.imageInt64Atomics = state->imageInt64Atomics; context.geometryShader = state->geometryShader; context.sampleRateShading = state->sampleRateShading; + context.nullDescriptors = state->shaderProfile != nullptr && state->shaderProfile->NullDescriptors(); context.primitiveListRestart = state->primitiveListRestart; context.imageViewMinLod = state->imageViewMinLod; context.pipelineExecutableInfo = state->pipelineExecutableInfo; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp index 9d0a82ec3..c31f7f470 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp @@ -139,6 +139,7 @@ struct Context { bool imageInt64Atomics = false; bool geometryShader = false; bool sampleRateShading = false; + bool nullDescriptors = false; bool primitiveListRestart = false; bool imageViewMinLod = false; bool pipelineExecutableInfo = false; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 40b73eccd..1902efa11 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -412,6 +412,7 @@ private: std::vector storageAtomic; std::vector storageAtomic64; std::vector> samplers; + std::shared_ptr paddingSampler; bool reusable = false; std::vector directRegions; std::vector validatedTextures; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index e9eb5b444..a01286df9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -958,6 +958,10 @@ void ShaderResources::buildPrepare(std::span shaders, cons } else { Require(binding.count == 1, "shader data and flattened SRT descriptors must not be arrays"); Require(!binding.guestDescriptor.empty(), "empty shader data descriptor"); + if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) { + Require(binding.guestDescriptor.size() == ShaderRecompiler::RuntimeAbi::ShaderDataDwords, "shader data does not match the fixed runtime ABI"); + ShaderRecompiler::RuntimeAbi::RequireVersion(binding.guestDescriptor[0]); + } item.allocations.push_back(addDataBuffer(binding.guestDescriptor)); if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) shaderData = static_cast(item.allocations.back()); } @@ -970,6 +974,24 @@ void ShaderResources::buildPrepare(std::span shaders, cons } } Require(storageBuffers <= context.limits.maxDescriptorSetStorageBuffers, "pipeline descriptors exceed device limits"); + std::map heapTotals; + std::map, std::uint64_t> stageTotals; + std::map stageResources; + for (const auto& binding : bindings) { + const auto& layout = binding.layout; + heapTotals[layout.descriptorType] += layout.descriptorCount; + for (std::uint32_t bit = 0u; bit < 32u; ++bit) { + const auto stage = VkShaderStageFlags{1u} << bit; + if ((layout.stageFlags & stage) == 0u) continue; + const auto count = stageTotals[{stage, layout.descriptorType}] += layout.descriptorCount; + const auto all = stageResources[stage] += layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER ? 0u : layout.descriptorCount; + Require(all <= context.limits.maxPerStageResources, "typed heaps exceed per-stage resource capacity"); + if (layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) Require(count <= context.limits.maxPerStageDescriptorSampledImages, "typed heaps exceed per-stage sampled image capacity"); + if (layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) Require(count <= context.limits.maxPerStageDescriptorStorageImages, "typed heaps exceed per-stage storage image capacity"); + if (layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) Require(count <= context.limits.maxPerStageDescriptorSamplers, "typed heaps exceed per-stage sampler capacity"); + } + } + Require(heapTotals[VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE] <= context.limits.maxDescriptorSetSampledImages && heapTotals[VK_DESCRIPTOR_TYPE_STORAGE_IMAGE] <= context.limits.maxDescriptorSetStorageImages && heapTotals[VK_DESCRIPTOR_TYPE_SAMPLER] <= context.limits.maxDescriptorSetSamplers, "typed heaps exceed descriptor set capacity"); timing.bindingsMs = phase(BuildPhase::Bindings); // For every build, locked ones included: their stage B then takes the fast path too, and the // collects cost the same wherever they run. @@ -1030,6 +1052,7 @@ void ShaderResources::buildPrepare(std::span shaders, cons } void ShaderResources::buildComplete() { + Require(!completed, "cannot update a published descriptor heap"); const auto stageStart = std::chrono::steady_clock::now(); phaseStart = stageStart; try { @@ -1057,7 +1080,7 @@ void ShaderResources::buildComplete() { std::size_t imageCount = 0; for (const auto& binding : bindings) { bufferCount += binding.allocations.size(); - imageCount += binding.imageAllocations.size(); + if (binding.layout.descriptorType != VK_DESCRIPTOR_TYPE_STORAGE_BUFFER) imageCount += binding.layout.descriptorCount; } std::vector buffers; std::vector images; @@ -1078,15 +1101,24 @@ void ShaderResources::buildComplete() { break; case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: write.pImageInfo = images.data() + images.size(); - for (const auto index : binding.imageAllocations) images.push_back({VK_NULL_HANDLE, textureFirstLayer[index] ? textures[index]->FirstLayerView() : textures[index]->View(), textures[index]->Layout()}); + for (const auto index : binding.imageAllocations) { + if (index == std::numeric_limits::max()) images.push_back({VK_NULL_HANDLE, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL}); + else images.push_back({VK_NULL_HANDLE, textureFirstLayer[index] ? textures[index]->FirstLayerView() : textures[index]->View(), textures[index]->Layout()}); + } + for (auto slot = binding.imageAllocations.size(); slot < binding.layout.descriptorCount; ++slot) images.push_back({VK_NULL_HANDLE, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL}); break; case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: write.pImageInfo = images.data() + images.size(); - for (const auto index : binding.imageAllocations) images.push_back({VK_NULL_HANDLE, storageAtomic64[index] ? storageTextures[index]->Atomic64View(storageMips[index], storageFirstLayer[index]) : storageAtomic[index] ? storageTextures[index]->AtomicView(storageMips[index], storageFirstLayer[index]) : storageTextures[index]->StorageView(storageMips[index], storageFirstLayer[index]), VK_IMAGE_LAYOUT_GENERAL}); + for (const auto index : binding.imageAllocations) { + if (index == std::numeric_limits::max()) images.push_back({VK_NULL_HANDLE, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL}); + else images.push_back({VK_NULL_HANDLE, storageAtomic64[index] ? storageTextures[index]->Atomic64View(storageMips[index], storageFirstLayer[index]) : storageAtomic[index] ? storageTextures[index]->AtomicView(storageMips[index], storageFirstLayer[index]) : storageTextures[index]->StorageView(storageMips[index], storageFirstLayer[index]), VK_IMAGE_LAYOUT_GENERAL}); + } + for (auto slot = binding.imageAllocations.size(); slot < binding.layout.descriptorCount; ++slot) images.push_back({VK_NULL_HANDLE, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL}); break; case VK_DESCRIPTOR_TYPE_SAMPLER: write.pImageInfo = images.data() + images.size(); for (const auto index : binding.imageAllocations) images.push_back({samplers[index]->Handle(), VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}); + for (auto slot = binding.imageAllocations.size(); slot < binding.layout.descriptorCount; ++slot) images.push_back({paddingSampler->Handle(), VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}); break; default: throw std::runtime_error("AGC graphics: ShaderResources encountered an unknown descriptor type while writing the descriptor set"); } @@ -1676,17 +1708,23 @@ ShaderResources::OwnRefreshFallback ShaderResources::refreshOwnObjects(std::span for (const auto& binding : shader.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestImages) continue; if (binding.kind == ShaderRecompiler::DescriptorKind::SampledImage) { - for (std::uint32_t element = 0; element < binding.count; ++element, ++textureIndex) { + for (std::uint32_t element = 0; element < binding.count; ++element) { + const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); + if (words[0] == 0u && (words[1] & 0xffu) == 0u) continue; if (textureIndex >= textures.size()) return OwnRefreshFallback::Uncached; - const auto overlap = listed(textureIndex, false); + const auto index = textureIndex++; + const auto overlap = listed(index, false); if (overlap == overlapping.end()) continue; - if (const auto fallback = refreshView(textureIndex, *overlap); fallback != OwnRefreshFallback::Count) return fallback; + if (const auto fallback = refreshView(index, *overlap); fallback != OwnRefreshFallback::Count) return fallback; } } else if (binding.kind == ShaderRecompiler::DescriptorKind::StorageImage) { - for (std::uint32_t element = 0; element < binding.count; ++element, ++storageIndex) { + for (std::uint32_t element = 0; element < binding.count; ++element) { + const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); + if (words[0] == 0u && (words[1] & 0xffu) == 0u) continue; if (storageIndex >= storageTextures.size()) return OwnRefreshFallback::Uncached; - if (listed(storageIndex, true) == overlapping.end()) continue; - if (const auto fallback = refreshStorage(storageIndex); fallback != OwnRefreshFallback::Count) return fallback; + const auto index = storageIndex++; + if (listed(index, true) == overlapping.end()) continue; + if (const auto fallback = refreshStorage(index); fallback != OwnRefreshFallback::Count) return fallback; } } } @@ -1725,6 +1763,7 @@ bool ShaderResources::Revalidate(std::span shaders, ProofR const auto elementWords = binding.count != 0 ? binding.guestDescriptor.size() / binding.count : 0; for (std::uint32_t element = 0; element < binding.count; ++element) { const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * elementWords, elementWords); + if (words[0] == 0u && (words[1] & 0xffu) == 0u) continue; const auto resource = DecodeTextureResource(words); const VkComponentMapping components = ViewComponents(resource); if (textureIndex >= textures.size() || cachedTexture(context, words, resource, components, 0, !binding.imageDepthCompare.empty() && binding.imageDepthCompare.at(element)) != textures[textureIndex]) return false; @@ -1733,6 +1772,7 @@ bool ShaderResources::Revalidate(std::span shaders, ProofR } else if (binding.kind == ShaderRecompiler::DescriptorKind::StorageImage) { for (std::uint32_t element = 0; element < binding.count; ++element) { const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); + if (words[0] == 0u && (words[1] & 0xffu) == 0u) continue; if (storageIndex >= storageTextures.size()) return false; std::shared_ptr expected; if (SameAsPreviousStorageElement(binding, element) && StorageDedupeEnabled()) expected = storageTextures[storageIndex - 1]; @@ -2404,13 +2444,21 @@ void ShaderResources::PrecollectSurfaces() const { void ShaderResources::addImageBinding(const ShaderRecompiler::DescriptorBinding& binding, VkShaderStageFlags flags) { Require(binding.count != 0, "empty descriptor binding"); + const auto heap = static_cast(binding.binding % static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count)); + const auto capacity = ShaderRecompiler::RuntimeAbi::HeapCapacity(heap); + Require(binding.count <= capacity, "typed descriptor heap capacity exceeded"); + const auto localBinding = static_cast(heap); + const bool sampledHeap = localBinding >= ShaderRecompiler::RuntimeAbi::FirstImageBinding && localBinding < ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding; + const bool storageHeap = localBinding >= ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding && localBinding < static_cast(ShaderRecompiler::RuntimeAbi::Binding::Samplers); + Require((binding.kind == ShaderRecompiler::DescriptorKind::SampledImage && sampledHeap) || (binding.kind == ShaderRecompiler::DescriptorKind::StorageImage && storageHeap) || (binding.kind == ShaderRecompiler::DescriptorKind::Sampler && heap == ShaderRecompiler::RuntimeAbi::Binding::Samplers), "resource class disagrees with typed descriptor heap"); + Require(binding.kind == ShaderRecompiler::DescriptorKind::Sampler || context.nullDescriptors, "typed image heaps require enabled nullDescriptor"); if (binding.kind == ShaderRecompiler::DescriptorKind::StorageImage) { // Storage images are guest textures the shader writes (looked up in stage B). Require(binding.role == ShaderRecompiler::DescriptorRole::GuestImages, "storage image binding has a non-image role"); Require(binding.guestDescriptor.size() == static_cast(binding.count) * 8u, "guest storage image descriptors must contain 8 dwords each"); Require(context.detiler != nullptr, "device texture detiler is unavailable"); - Require(binding.count <= context.limits.maxPerStageDescriptorStorageImages, "shader storage-image descriptors exceed per-stage limits"); - bindings.push_back({{binding.binding, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, binding.count, flags, nullptr}, {}, {}}); + Require(capacity <= context.limits.maxPerStageDescriptorStorageImages, "shader storage-image descriptors exceed per-stage limits"); + bindings.push_back({{binding.binding, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, capacity, flags, nullptr}, {}, {}}); plannedStorageImages += binding.count; deferredImages.push_back({&binding, bindings.size() - 1}); return; @@ -2422,19 +2470,23 @@ void ShaderResources::addImageBinding(const ShaderRecompiler::DescriptorBinding& Require(binding.guestDescriptor.size() % binding.count == 0, "guest image descriptor size is not a multiple of the binding count"); const auto elementWords = binding.guestDescriptor.size() / binding.count; - Binding item{{binding.binding, sampledImage ? VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE : VK_DESCRIPTOR_TYPE_SAMPLER, binding.count, flags, nullptr}, {}, {}}; + Binding item{{binding.binding, sampledImage ? VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE : VK_DESCRIPTOR_TYPE_SAMPLER, capacity, flags, nullptr}, {}, {}}; if (sampledImage) { Require(elementWords == 8, "guest texture descriptor must contain 8 dwords"); Require(binding.imageShape.has_value(), "guest image binding is missing an image shape"); Require(context.detiler != nullptr, "device texture detiler is unavailable"); Require(context.textureCache != nullptr, "device texture cache is unavailable"); - Require(binding.count <= context.limits.maxPerStageDescriptorSampledImages, "shader sampled-image descriptors exceed per-stage limits"); + Require(capacity <= context.limits.maxPerStageDescriptorSampledImages, "shader sampled-image descriptors exceed per-stage limits"); plannedSampledImages += binding.count; Require(plannedSampledImages <= context.limits.maxDescriptorSetSampledImages, "pipeline sampled-image descriptors exceed device limits"); } else { Require(elementWords == 4, "guest sampler descriptor must contain 4 dwords"); - Require(binding.count <= context.limits.maxPerStageDescriptorSamplers, "shader sampler descriptors exceed per-stage limits"); + Require(capacity <= context.limits.maxPerStageDescriptorSamplers, "shader sampler descriptors exceed per-stage limits"); + if (paddingSampler == nullptr) { + constexpr std::array defaultSampler{}; + paddingSampler = std::make_shared(context, DecodeSamplerResource(defaultSampler)); + } Require(binding.samplerDepthCompare.size() == binding.count, "guest sampler binding is missing depth comparison metadata"); Require(binding.samplerUnnormalized.empty() || binding.samplerUnnormalized.size() == binding.count, "guest sampler binding has unnormalized coordinate metadata of another size"); for (std::uint32_t element = 0; element < binding.count; ++element) { @@ -2501,7 +2553,7 @@ bool ShaderResources::precollectImages() { const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * elementWords, elementWords); ImageRecord record; record.sampled = binding.kind == ShaderRecompiler::DescriptorKind::SampledImage; - try { + if (words[0] != 0u || (words[1] & 0xffu) != 0u) { record.resource = DecodeTextureResource(words); record.guestBytes = DescribeSurface(record.resource).guestBytes; record.generation = GuestMemory::CollectWrites(record.resource.baseAddress, static_cast(record.guestBytes)); @@ -2520,8 +2572,6 @@ bool ShaderResources::precollectImages() { counters.records.fetch_add(1, std::memory_order_relaxed); } } - } catch (const std::exception&) { - record.decoded = false; } imageRecords.push_back(std::move(record)); } @@ -2594,6 +2644,11 @@ void ShaderResources::resolveImageBinding(const ShaderRecompiler::DescriptorBind for (std::uint32_t element = 0; element < binding.count; ++element) { const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * elementWords, elementWords); const auto* record = nextRecord(); + if (words[0] == 0u && (words[1] & 0xffu) == 0u) { + item.imageAllocations.push_back(std::numeric_limits::max()); + --plannedSampledImages; + continue; + } const auto resource = record != nullptr && record->decoded ? record->resource : DecodeTextureResource(words); const bool firstLayer = binding.imageShape == ShaderRecompiler::DescriptorImageShape::Image2D && resource.dimension == TextureDimension::k2DArray; if (!firstLayer && !MatchesGuestDimension(*binding.imageShape, resource.dimension)) throw std::runtime_error("AGC graphics: guest texture dimension disagrees with the shader's declared image shape (shape " + std::to_string(static_cast(*binding.imageShape)) + ", dimension " + std::to_string(static_cast(resource.dimension)) + ")"); @@ -2629,6 +2684,11 @@ void ShaderResources::resolveImageBinding(const ShaderRecompiler::DescriptorBind if (sameAsPrevious) ++mipOffset; else mipOffset = 0; const auto* record = nextRecord(); + if (words[0] == 0u && (words[1] & 0xffu) == 0u) { + item.imageAllocations.push_back(std::numeric_limits::max()); + --plannedStorageImages; + continue; + } const auto resource = record != nullptr && record->decoded ? record->resource : DecodeTextureResource(words); const bool firstLayer = binding.imageShape == ShaderRecompiler::DescriptorImageShape::Image2D && resource.dimension == TextureDimension::k2DArray; if (binding.imageShape.has_value() && !firstLayer && !MatchesGuestDimension(*binding.imageShape, resource.dimension)) throw std::runtime_error("AGC graphics: guest storage texture dimension disagrees with the shader's declared image shape (shape " + std::to_string(static_cast(*binding.imageShape)) + ", dimension " + std::to_string(static_cast(resource.dimension)) + ")"); @@ -2692,12 +2752,9 @@ std::vector> ShaderResources::PresyncSur // Stage A has not run (an address-based build, or the pass is off): decoded from the shader. if (deferredCompute.program == nullptr) return surfaces; forEachImageElement(*deferredCompute.program, [&](const ShaderRecompiler::DescriptorBinding& binding, std::uint32_t, std::span words) { - try { - const auto resource = DecodeTextureResource(words); - consider(resource.format, resource.baseAddress, DescribeSurface(resource).guestBytes, binding.kind == ShaderRecompiler::DescriptorKind::SampledImage); - } catch (const std::exception&) { - // Stage B reports the bad descriptor. - } + if (words[0] == 0u && (words[1] & 0xffu) == 0u) return; + const auto resource = DecodeTextureResource(words); + consider(resource.format, resource.baseAddress, DescribeSurface(resource).guestBytes, binding.kind == ShaderRecompiler::DescriptorKind::SampledImage); }); return surfaces; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp index 65bb90829..82ea177b5 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp @@ -461,6 +461,11 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi const auto binding = std::find_if(shader.bindings.begin(), shader.bindings.end(), [&](const auto& item) { return item.descriptorSet == key.first && item.binding == key.second; }); Require(binding != shader.bindings.end(), "SPIR-V resource is absent from recompiler binding metadata"); Require(binding->kind == ShaderRecompiler::DescriptorKind::Sampler || binding->kind == ShaderRecompiler::DescriptorKind::SampledImage || binding->kind == ShaderRecompiler::DescriptorKind::StorageImage, "SPIR-V descriptor type disagrees with recompiler binding metadata"); + Require(type.size() == 4 && (type[0] & 0xffffu) == spv::OpTypeArray, "typed heap must be declared as a descriptor array"); + const auto heap = static_cast(binding->binding % static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count)); + const auto capacity = ShaderRecompiler::RuntimeAbi::HeapCapacity(heap); + const auto count = module.constants.find(type[3]); + Require(binding->count != 0u && binding->count <= capacity && count != module.constants.end() && count->second == capacity, "typed heap array length disagrees with runtime ABI"); } else { Require(variable.storage == spv::StorageClassStorageBuffer && decoration.set && decoration.binding, "unsupported or unbound shader resource"); const auto key = std::make_pair(*decoration.set, *decoration.binding); diff --git a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp index 220231386..b1e55e42c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp @@ -1407,7 +1407,8 @@ AgcDriver::Graphics::Context mockContext() { context.memory.memoryTypes[0].propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; context.limits.minStorageBufferOffsetAlignment = 1; context.limits.maxBoundDescriptorSets = 1; - context.limits.maxStorageBufferRange = 4096; + context.limits.maxStorageBufferRange = 16384; + context.nullDescriptors = true; context.limits.maxPerStageDescriptorStorageBuffers = 16; context.limits.maxPerStageResources = 128; context.limits.maxDescriptorSetStorageBuffers = 32; @@ -1442,6 +1443,13 @@ ShaderRecompiler::DescriptorBinding makeBinding(Role role, std::uint32_t binding return result; } +std::vector ShaderDataWords(std::initializer_list userData) { + std::vector words(ShaderRecompiler::RuntimeAbi::ShaderDataDwords); + words[0] = ShaderRecompiler::RuntimeAbi::Version; + std::copy(userData.begin(), userData.end(), words.begin() + ShaderRecompiler::RuntimeAbi::UserDataDword); + return words; +} + bool sameBytes(const std::vector& memory, const void* expected, std::size_t bytes) { return memory.size() >= bytes && std::memcmp(memory.data(), expected, bytes) == 0; } @@ -1525,7 +1533,7 @@ void resourceTests() { ShaderRecompiler::RecompileResult vertex; ShaderRecompiler::RecompileResult fragment; vertex.bindings.push_back(makeBinding(Role::GuestBuffers, 0, 2, join(vsharp(guestFirst.data(), 16), vsharp(guestSecond.data(), 32)))); - vertex.bindings.push_back(makeBinding(Role::ShaderData, 5, 1, {7, 8, 9})); + vertex.bindings.push_back(makeBinding(Role::ShaderData, 5, 1, ShaderDataWords({7, 8, 9}))); fragment.bindings.push_back(makeBinding(Role::FlattenedSrt, 43, 1, {1, 2})); fragment.bindings.push_back(makeBinding(Role::GuestBuffers, 44, 1, vsharp(guestThird.data(), 8))); AgcDriver::Graphics::ShaderResources resources(context, vertex, fragment, state.color, 0, 0); @@ -1540,8 +1548,8 @@ void resourceTests() { Require(array.count == 2 && array.buffers.size() == 2 && array.type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, "guest buffer array write is incorrect"); Require(array.buffers[0].offset == 0 && array.buffers[0].range == 16 && array.buffers[1].offset == 0 && array.buffers[1].range == 32, "guest buffers must be bound at zero offset with their descriptor size"); Require(sameBytes(bufferBytes(array.buffers[0].buffer), guestFirst.data(), 16) && sameBytes(bufferBytes(array.buffers[1].buffer), guestSecond.data(), 32), "guest buffer contents were not uploaded"); - const std::array data{7, 8, 9}; - Require(findWrite(5).buffers.size() == 1 && findWrite(5).buffers[0].range == 12 && sameBytes(bufferBytes(findWrite(5).buffers[0].buffer), data.data(), 12), "shader data buffer is incorrect"); + const auto data = ShaderDataWords({7, 8, 9}); + Require(findWrite(5).buffers.size() == 1 && findWrite(5).buffers[0].range == data.size() * 4u && sameBytes(bufferBytes(findWrite(5).buffers[0].buffer), data.data(), data.size() * 4u), "shader data buffer is incorrect"); const std::array srt{1, 2}; Require(findWrite(43).buffers.size() == 1 && findWrite(43).buffers[0].range == 8 && sameBytes(bufferBytes(findWrite(43).buffers[0].buffer), srt.data(), 8), "flattened SRT buffer is incorrect"); Require(findWrite(44).buffers.size() == 1 && findWrite(44).buffers[0].range == 8 && sameBytes(bufferBytes(findWrite(44).buffers[0].buffer), guestThird.data(), 8), "fragment guest buffer is incorrect"); @@ -1614,9 +1622,10 @@ void resourceTests() { mutate(binding); return binding; }; - expectSingleFailure(changed([](auto& binding) { binding.role = Role::GuestImages; binding.kind = Kind::SampledImage; }), "guest texture descriptor must contain 8 dwords"); - expectSingleFailure(changed([](auto& binding) { binding.role = Role::GuestImages; binding.kind = Kind::StorageImage; }), "guest storage image descriptors must contain 8 dwords"); - expectSingleFailure(changed([](auto& binding) { binding.role = Role::GuestSamplers; binding.kind = Kind::Sampler; }), "shader sampler descriptors exceed per-stage limits"); + expectSingleFailure(changed([](auto& binding) { binding.role = Role::GuestImages; binding.kind = Kind::SampledImage; binding.binding = 1u; }), "guest texture descriptor must contain 8 dwords"); + expectSingleFailure(changed([](auto& binding) { binding.role = Role::GuestImages; binding.kind = Kind::StorageImage; binding.binding = 29u; }), "guest storage image descriptors must contain 8 dwords"); + expectSingleFailure(changed([](auto& binding) { binding.role = Role::GuestSamplers; binding.kind = Kind::Sampler; binding.binding = 44u; }), "shader sampler descriptors exceed per-stage limits"); + expectSingleFailure(changed([](auto& binding) { binding.role = Role::GuestImages; binding.kind = Kind::SampledImage; binding.binding = 29u; }), "resource class disagrees"); expectSingleFailure(changed([](auto& binding) { binding.role = Role::Gds; }), "invalid GDS descriptor contract"); expectSingleFailure(changed([](auto& binding) { binding.role = Role::BdaPagetable; binding.guestDescriptor.clear(); }), "BDA table and fault descriptors"); expectSingleFailure(changed([](auto& binding) { binding.role = Role::FaultBuffer; binding.guestDescriptor.clear(); }), "BDA table and fault descriptors"); @@ -1630,11 +1639,13 @@ void resourceTests() { expectSingleFailure(changed([](auto& binding) { binding.count = 2; }), "four DWORDs per array element"); expectSingleFailure(changed([](auto& binding) { binding.role = Role::ShaderData; binding.count = 2; binding.guestDescriptor = {1, 2}; }), "must not be arrays"); expectSingleFailure(changed([](auto& binding) { binding.role = Role::ShaderData; binding.guestDescriptor.clear(); }), "empty shader data descriptor"); + expectSingleFailure(changed([](auto& binding) { binding.role = Role::ShaderData; }), "fixed runtime ABI"); + expectSingleFailure(changed([](auto& binding) { binding.role = Role::ShaderData; binding.guestDescriptor = ShaderDataWords({}); binding.guestDescriptor[0] = 0u; }), "incompatible version"); expectSingleFailure(changed([](auto& binding) { binding.role = Role::FlattenedSrt; binding.guestDescriptor.clear(); }), "empty shader data descriptor"); expectSingleFailure(changed([](auto& binding) { binding.guestDescriptor[1] |= 0x40000000u; }), "reserved bits"); expectSingleFailure(changed([](auto& binding) { binding.guestDescriptor[3] |= 0x40000000u; }), "unsupported type"); expectSingleFailure(changed([](auto& binding) { binding.guestDescriptor[1] |= 0x3fffu << 16u; binding.guestDescriptor[2] = 0xffffffffu; }), "descriptor range limit"); - expectSingleFailure(changed([](auto& binding) { binding.guestDescriptor[2] = 8192; }), "descriptor range limit"); + expectSingleFailure(changed([](auto& binding) { binding.guestDescriptor[2] = 32768; }), "descriptor range limit"); expectSingleAccepted(changed([](auto& binding) { binding.guestDescriptor = vsharp(reinterpret_cast(0x1000), 8); }), "an unmapped V#"); expectSingleFailure(changed([&](auto& binding) { binding.guestDescriptor = vsharp(reinterpret_cast(state.color.address), 64); }), "aliases the render target"); expectSingleAccepted(changed([](auto& binding) { binding.count = 3; binding.guestDescriptor = join(join(vsharp(guestFirst.data(), 16), vsharp(guestSecond.data(), 32)), vsharp(reinterpret_cast(0x1000), 8)); }), "an unmapped V# element"); @@ -1718,21 +1729,23 @@ void misalignedShaderDataTests() { { ShaderRecompiler::RecompileResult compute; compute.bindings.push_back(makeBinding(Role::GuestBuffers, 0, 2, join(vsharp(guest.data(), 32), vsharp(guest.data() + 1, 8)))); - compute.bindings.push_back(makeBinding(Role::ShaderData, 1, 1, {0x11, 0x22, 0})); - compute.memoryOffsetDword = 2; + compute.bindings.push_back(makeBinding(Role::ShaderData, 1, 1, ShaderDataWords({0x11, 0x22}))); + compute.memoryOffsetDword = ShaderRecompiler::RuntimeAbi::BufferOffsetsDword; auto live = compute; - live.bindings[1].guestDescriptor = {0x33, 0x44, 0}; + live.bindings[1].guestDescriptor = ShaderDataWords({0x33, 0x44}); const AgcDriver::Graphics::CompiledShader shader{ShaderRecompiler::ShaderStage::Compute, &compute, 0}; const AgcDriver::Graphics::CompiledShader liveShader{ShaderRecompiler::ShaderStage::Compute, &live, 0}; AgcDriver::Graphics::ShaderResources resources(context, shader); const auto& views = findWrite(0); Require(views.buffers.size() == 2 && views.buffers[0].range == 32 && views.buffers[1].range == 12 && views.buffers[1].offset == views.buffers[0].offset, "the misaligned view is not bound from the aligned offset below it"); const auto data = findWrite(1).buffers.at(0).buffer; - const std::array patched{0x11, 0x22, 0x400}; - Require(sameBytes(bufferBytes(data), patched.data(), sizeof(patched)), "the shader data buffer does not hold the misaligned view's offset"); + auto patched = ShaderDataWords({0x11, 0x22}); + patched[ShaderRecompiler::RuntimeAbi::BufferOffsetsDword] = 0x400u; + Require(sameBytes(bufferBytes(data), patched.data(), patched.size() * 4u), "the shader data buffer does not hold the misaligned view's offset"); Require(resources.RefreshData(commands, liveShader), "a refresh with different words recorded nothing"); - const std::array refreshed{0x33, 0x44, 0x400}; - Require(sameBytes(bufferBytes(data), refreshed.data(), sizeof(refreshed)), "a data refresh dropped the misaligned view's offset"); + auto refreshed = ShaderDataWords({0x33, 0x44}); + refreshed[ShaderRecompiler::RuntimeAbi::BufferOffsetsDword] = 0x400u; + Require(sameBytes(bufferBytes(data), refreshed.data(), refreshed.size() * 4u), "a data refresh dropped the misaligned view's offset"); Require(!resources.DataWordsDiffer(liveShader) && resources.DataWordsHash() == AgcDriver::Graphics::ShaderResources::DataWordsHash(liveShader), "the refreshed template's words are not the dispatch's"); } Require(mock.live == 0, "misaligned shader data resources leaked Vulkan objects"); diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderDeviceProfile.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderDeviceProfile.cpp index cfe9f52de..885da9e85 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderDeviceProfile.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderDeviceProfile.cpp @@ -1,5 +1,6 @@ #include "prx/libSceAgcDriver/Execution/include/ShaderDeviceProfile.hpp" #include "BdaAbi.hpp" +#include "Optimization/BindingAllocator.hpp" #include #include #include @@ -17,7 +18,8 @@ struct ProfileInput { std::vector capabilities{spv::CapabilityShader, spv::CapabilityInt64, spv::CapabilityPhysicalStorageBufferAddresses, spv::CapabilityStorageBuffer8BitAccess}; std::array extensionStrings{"SPV_KHR_physical_storage_buffer", "SPV_KHR_8bit_storage"}; std::array extensions{extensionStrings[0], extensionStrings[1]}; - VkPhysicalDeviceDescriptorIndexingFeatures indexing{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES}; + VkPhysicalDeviceRobustness2FeaturesEXT robustness{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT, nullptr, VK_FALSE, VK_FALSE, VK_TRUE}; + VkPhysicalDeviceDescriptorIndexingFeatures indexing{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES, &robustness}; VkPhysicalDevice8BitStorageFeatures bytes{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES, &indexing, VK_TRUE}; VkPhysicalDeviceBufferDeviceAddressFeatures bda{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES, &bytes, VK_TRUE}; VkPhysicalDeviceFeatures core{}; @@ -32,6 +34,7 @@ struct ProfileInput { device.pNext = &bda; limits.maxPushConstantsSize = 128u; limits.maxBoundDescriptorSets = 1u; + limits.maxStorageBufferRange = sizeof(ShaderRecompiler::RuntimeAbi::ShaderData); } ShaderRecompiler::SpirvTarget Target() const { @@ -60,11 +63,13 @@ void CheckProfile() { input.capabilities.clear(); input.extensionStrings[0] = "changed"; input.core.shaderInt64 = VK_FALSE; + input.robustness.nullDescriptor = VK_FALSE; input.limits.maxPushConstantsSize = 0u; const auto target = profile.Target(); Require(target.supportedCapabilities.size() == 4u && std::ranges::is_sorted(target.supportedCapabilities), "profile capabilities were not frozen"); Require(std::ranges::find(target.supportedExtensions, "SPV_KHR_physical_storage_buffer") != target.supportedExtensions.end(), "profile extension storage is borrowed"); Require(profile.Limits().maxPushConstantsSize == 128u, "profile limits were not frozen"); + Require(profile.NullDescriptors(), "profile null descriptor support was not frozen"); static_assert(!std::is_copy_constructible_v && !std::is_move_constructible_v); const auto invalid = [](auto mutate, const char* expected) { ProfileInput candidate; @@ -76,9 +81,12 @@ void CheckProfile() { invalid([](auto& value) { value.device.pNext = nullptr; }, "bufferDeviceAddress"); invalid([](auto& value) { value.core.shaderInt64 = VK_FALSE; }, "shaderInt64"); invalid([](auto& value) { value.bytes.storageBuffer8BitAccess = VK_FALSE; }, "storageBuffer8BitAccess"); + invalid([](auto& value) { value.robustness.nullDescriptor = VK_FALSE; }, "nullDescriptor"); + invalid([](auto& value) { value.indexing.pNext = nullptr; }, "nullDescriptor"); invalid([](auto& value) { value.core.fragmentStoresAndAtomics = VK_FALSE; }, "graphics stores and atomics"); invalid([](auto& value) { value.limits.maxPushConstantsSize = 127u; }, "exceeds device limits"); invalid([](auto& value) { value.limits.maxBoundDescriptorSets = 0u; }, "exceeds device limits"); + invalid([](auto& value) { --value.limits.maxStorageBufferRange; }, "ShaderData exceeds device limits"); invalid([](auto& value) { value.capabilities.clear(); }, "missing runtime capabilities"); invalid([](auto& value) { value.extensions[0] = "missing"; }, "missing runtime extensions"); invalid([](auto& value) { value.capabilities.push_back(spv::CapabilitySampledImageArrayDynamicIndexing); }, "shaderSampledImageArrayDynamicIndexing"); @@ -112,11 +120,61 @@ void CheckAbi() { ShaderRecompiler::RuntimeAbi::RequireVersion(ShaderRecompiler::RuntimeAbi::Version); } +void CheckHeaps() { + using namespace ShaderRecompiler; + const auto allocate = [](const ImageResource& image, std::uint32_t count, std::uint32_t samplers = 0u) { + IrProgram program; + program.Metadata().shaderInfoComplete = true; + program.Resources().info.images.assign(count, image); + program.Resources().info.samplers.resize(samplers); + return BindingAllocator{}.Allocate(program, {0u, 0u, 0u, 128u}); + }; + ImageResource image; + image.resourceClass = ImageResourceClass::Sampled; + image.numericClass = IrTextureNumericClass::Float; + image.dimension = RdnaImageDimension::Dim2D; + const auto single = allocate(image, 1u); + const auto full = allocate(image, RuntimeAbi::SampledHeapCapacity, RuntimeAbi::SamplerHeapCapacity); + Require(single.layout.ShaderDataDwords() == full.layout.ShaderDataDwords() && single.layout.memoryOffsetDword == full.layout.memoryOffsetDword && !full.layout.UsesPushData(), "runtime layout depends on resource count"); + Require(full.layout.memoryOffsetDword == 132u && full.layout.DispatchThreadLimitDword() == 164u && full.layout.ShaderDataDwords() == 3432u, "runtime layout offsets changed"); + Reject([&] { allocate(image, RuntimeAbi::SampledHeapCapacity + 1u); }, "heap capacity exceeded"); + Reject([&] { allocate(image, 1u, RuntimeAbi::SamplerHeapCapacity + 1u); }, "metadata capacity"); + image.resourceClass = ImageResourceClass::Storage; + image.mipMode = ImageMipMode::DynamicStorage; + image.mipCount = RuntimeAbi::StorageHeapCapacity; + const auto storage = allocate(image, 1u); + Require(BindingAllocator{}.FindBinding(storage.layout, DescriptorBindingForImage(image)).resources.size() == image.mipCount, "storage heap did not reserve each mip"); + ++image.mipCount; + Reject([&] { allocate(image, 1u); }, "heap capacity exceeded"); + const std::array dimensions{RdnaImageDimension::Dim1D, RdnaImageDimension::Dim1DArray, RdnaImageDimension::Dim2D, RdnaImageDimension::Dim2DArray, RdnaImageDimension::Dim3D, RdnaImageDimension::Dim2DMsaa, RdnaImageDimension::Dim2DMsaaArray}; + std::set classes; + for (std::uint32_t group = 0u; group < 7u; ++group) { + for (const auto dimension : dimensions) { + image = {}; + image.resourceClass = group < 4u ? ImageResourceClass::Sampled : ImageResourceClass::Storage; + image.numericClass = group == 1u || group >= 5u ? IrTextureNumericClass::Uint : group == 2u ? IrTextureNumericClass::Sint : IrTextureNumericClass::Float; + image.depthCompare = group == 3u; + image.atomic = group == 6u; + image.dimension = dimension; + if (group >= 4u && (dimension == RdnaImageDimension::Dim2DMsaa || dimension == RdnaImageDimension::Dim2DMsaaArray)) { + Reject([&] { DescriptorBindingForImage(image); }, "cannot be multisampled"); + continue; + } + const auto binding = DescriptorBindingForImage(image); + Require(classes.insert(static_cast(binding)).second, "typed image classes overlap"); + Require(RuntimeAbi::HeapCapacity(binding) == (group < 4u ? RuntimeAbi::SampledHeapCapacity : RuntimeAbi::StorageHeapCapacity), "typed image class has an invalid capacity"); + } + } + Require(classes.size() == RuntimeAbi::ImageBindingCount && *classes.begin() == 1u && *classes.rbegin() == 43u, "typed image class mapping is incomplete"); + Reject([] { RuntimeAbi::HeapCapacity(RuntimeAbi::Binding::ShaderData); }, "not a typed heap"); +} + } int main() { try { CheckAbi(); + CheckHeaps(); CheckProfile(); std::cout << "shader runtime ABI and device profile tests passed\n"; return 0; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageLoadPacked.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageLoadPacked.cpp index b0612df8b..e1d3193d0 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageLoadPacked.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageLoadPacked.cpp @@ -107,7 +107,7 @@ std::array RawTexel(const Format& format, std::uint32_t level, std::array BufferDescriptor(const void* data, std::uint32_t bytes) { const auto address = reinterpret_cast(data); - return {static_cast(address), static_cast((address >> 32u) & 0xffffu), bytes, 0x01016facu}; + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), bytes, 0x31016facu}; } std::array TextureDescriptor(const void* data, std::uint32_t format, std::uint32_t swizzle) { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/TypedHeaps.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/TypedHeaps.cpp new file mode 100644 index 000000000..b6602eee8 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/TypedHeaps.cpp @@ -0,0 +1,73 @@ +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +alignas(256) std::array, 4> texels{}; +alignas(256) std::array, 4> outputs{}; +constexpr std::array code{0x7e3c0300u, 0x7e3e0280u, 0xf0001108u, 0x00010a1eu, 0x34060082u, 0xe0701000u, 0x80000a03u, 0xbf810000u}; +constexpr std::array storeCode{0x7e3c0300u, 0x7e3e0280u, 0x7e1402ffu, 123u, 0xf0201108u, 0x00010a1eu, 0x34060082u, 0xe0701000u, 0x80000a03u, 0xbf810000u}; + +ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, std::uint32_t index, bool nullImage, bool store) { + const auto output = reinterpret_cast(outputs[index].data()); + const auto image = reinterpret_cast(texels[index].data()); + std::array userData{static_cast(output), static_cast(output >> 32u), 256u, 0x31016facu}; + if (!nullImage) { + const std::array descriptor{static_cast(image >> 8u), static_cast(image >> 40u) | (20u << 20u) | (3u << 30u), 7u, 0x90000facu, 0u, 0u, 0u, 0u}; + std::copy(descriptor.begin(), descriptor.end(), userData.begin() + 4u); + } + const ShaderRecompiler::ShaderComputeStageInfo compute{{32u, 1u, 1u}, 0u, {false, false, false}, false, 1u}; + const auto instructions = store ? std::span(storeCode) : std::span(code); + ShaderRecompiler::RecompileRequest request{{ShaderStage::Compute, reinterpret_cast(instructions.data()), instructions, 0u, {}}, {32u, 0u, userData, compute, std::nullopt, std::nullopt, {}}, device.Target(), {0u, 0u, 0u, 128u}}; + auto result = ShaderRecompiler::Recompile(request); + Require(result.pushConstants.empty(), "ShaderData unexpectedly uses a variable push layout"); + const auto dataBinding = std::ranges::find_if(result.bindings, [](const auto& binding) { return binding.role == ShaderRecompiler::DescriptorRole::ShaderData; }); + Require(dataBinding != result.bindings.end() && dataBinding->guestDescriptor.size() == ShaderRecompiler::RuntimeAbi::ShaderDataDwords, "ShaderData does not match the fixed ABI"); + ShaderRecompiler::RuntimeAbi::ShaderData data{}; + std::memcpy(&data, dataBinding->guestDescriptor.data(), sizeof(data)); + Require(data.version == ShaderRecompiler::RuntimeAbi::Version && data.imageCount == 1u, "resource metadata header is invalid"); + Require(data.images[0].elementCount == 1u && data.images[0].firstElement == 0u && data.images[0].flags == (nullImage ? 1u : 0u), "image heap metadata is invalid"); + return result; +} + +void Run(AgcDriver::VulkanDevice& device) { + std::vector shaders; + for (std::uint32_t batch = 0u; batch < outputs.size(); ++batch) { + outputs[batch].fill(0xdeadbeefu); + for (std::uint32_t pixel = 0u; pixel < 32u; ++pixel) texels[batch][pixel] = 1000u * (batch + 1u) + pixel; + const bool nullImage = batch >= 2u; + shaders.push_back(Compile(device, batch, nullImage, batch == 3u)); + device.Dispatch(shaders.back(), 1u, 1u, 1u); + device.SubmitRecorded(); + } + shaders.clear(); + device.WaitIdle(); + for (std::uint32_t batch = 0u; batch < outputs.size(); ++batch) { + for (std::uint32_t pixel = 0u; pixel < 32u; ++pixel) Require(outputs[batch][pixel] == (batch == 3u ? 123u : batch == 2u ? 0u : texels[batch][pixel]), "descriptor heap lifetime or null image semantics failed: batch=" + std::to_string(batch) + " pixel=" + std::to_string(pixel) + " value=" + std::to_string(outputs[batch][pixel])); + } +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + Run(*device); + std::cout << "typed heap execution tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/shader/recompiler/CMakeLists.txt b/core/shader/recompiler/CMakeLists.txt index eb2a95b22..a637e8c61 100644 --- a/core/shader/recompiler/CMakeLists.txt +++ b/core/shader/recompiler/CMakeLists.txt @@ -219,6 +219,7 @@ function(add_shader_recompiler target runtimeTarget) ResolveSource ResourceMaterializer::SpecializationNanoseconds RuntimeAbi::RequireVersion + RuntimeAbi::HeapCapacity SetDebugProbeActive ShaderCacheDirectory SrgbDecodeBit diff --git a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp index 6f2ea6d90..de719aa26 100644 --- a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp +++ b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp @@ -46,10 +46,10 @@ struct IrBindingLayout { std::vector descriptors; [[nodiscard]] std::uint32_t DispatchThreadLimitDword() const { - return memoryOffsetDword + (memoryOffsetCount + 3u) / 4u; + return RuntimeAbi::DispatchThreadLimitDword; } [[nodiscard]] std::uint32_t ShaderDataDwords() const { - return DispatchThreadLimitDword() + (dispatchThreadLimit ? 3u : 0u); + return RuntimeAbi::ShaderDataDwords; } [[nodiscard]] bool UsesPushData() const { return pushDataStartDword != PushData::NoStart; diff --git a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp index 96a917dad..ee80bda0e 100644 --- a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp +++ b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp @@ -93,13 +93,12 @@ BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const Bin IrBindingLayout next; next.userDataRegisters = collectUserData(program); - next.memoryOffsetDword = static_cast(next.userDataRegisters.size()); + next.memoryOffsetDword = RuntimeAbi::BufferOffsetsDword; next.memoryOffsetCount = static_cast(info.buffers.size()); next.dispatchThreadLimit = info.dispatchThreadLimit; - const std::uint32_t pushDataStartDword = layout.pushConstantOffsetBytes / 4u; - const std::uint32_t pushConstantSizeDwords = layout.pushConstantSizeBytes / 4u; - const bool usesPushData = next.ShaderDataDwords() != 0u && next.ShaderDataDwords() <= pushConstantSizeDwords; - next.pushDataStartDword = usesPushData ? pushDataStartDword : PushData::NoStart; + if (info.buffers.size() > RuntimeAbi::BufferCapacity || info.images.size() > RuntimeAbi::ImageCapacity || info.samplers.size() > RuntimeAbi::SamplerHeapCapacity) fail("shader binding layout exceeds runtime metadata capacity"); + if (std::ranges::any_of(next.userDataRegisters, [](auto reg) { return reg >= RuntimeAbi::UserDataCapacity; })) fail("shader user data exceeds runtime ABI capacity"); + next.pushDataStartDword = PushData::NoStart; if (!info.buffers.empty()) { std::vector resources(info.buffers.size()); @@ -145,6 +144,7 @@ BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const Bin } for (std::uint32_t i = 0; i < imageGroups.size(); i++) { if (!imageGroups[i].empty()) { + if (imageGroups[i].size() > RuntimeAbi::HeapCapacity(static_cast(FirstImageBinding + i))) fail("shader image heap capacity exceeded"); addBinding(next, static_cast(FirstImageBinding + i), std::move(imageGroups[i])); } } diff --git a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp index 3a5664747..0242ed6a0 100644 --- a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp +++ b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp @@ -267,20 +267,45 @@ std::uint32_t ImageSamplerMask(const ShaderInfo& info, const std::vector ShaderDataDwordsFor(const IrBindingLayout& layout, std::uint32_t userDataBase, const ResourceSnapshot& snapshot, const std::array& partialThreads) { - std::vector result(layout.ShaderDataDwords(), 0u); + RuntimeAbi::ShaderData data{}; + data.version = RuntimeAbi::Version; + if (snapshot.images.size() > data.images.size() || snapshot.samplers.size() > data.samplers.size()) fail("runtime resource metadata capacity exceeded"); + data.imageCount = static_cast(snapshot.images.size()); + data.samplerCount = static_cast(snapshot.samplers.size()); for (std::size_t i = 0; i < layout.userDataRegisters.size(); i++) { const std::uint32_t reg = layout.userDataRegisters[i]; if (reg < userDataBase || reg - userDataBase >= snapshot.userData.size()) { fail("DescriptorBindingBuilder::Populate user-data register is out of range"); } - result[i] = snapshot.userData[reg - userDataBase]; + if (reg >= data.userData.size()) fail("runtime user-data capacity exceeded"); + data.userData[reg] = snapshot.userData[reg - userDataBase]; } if (layout.dispatchThreadLimit) { if (partialThreads == std::array{}) { fail("DescriptorBindingBuilder::Populate partial-group shader has no dispatch size"); } - std::copy(partialThreads.begin(), partialThreads.end(), result.begin() + layout.DispatchThreadLimitDword()); + std::copy(partialThreads.begin(), partialThreads.end(), data.dispatchThreadLimit.begin()); } + for (const auto& binding : layout.descriptors) { + const bool image = ImageBindingResourceClass(binding.kind) != ImageResourceClass::None; + if (!image && binding.kind != DescriptorBindingKind::Samplers) continue; + if (binding.resources.size() > RuntimeAbi::HeapCapacity(binding.kind)) fail("runtime typed heap capacity exceeded"); + for (std::size_t element = 0; element < binding.resources.size(); ++element) { + const auto resource = binding.resources[element]; + auto& metadata = image ? data.images.at(resource) : data.samplers.at(resource); + const auto& descriptor = image ? snapshot.images.at(resource) : snapshot.samplers.at(resource); + if (metadata.elementCount == 0u) { + metadata.binding = static_cast(binding.kind); + metadata.firstElement = static_cast(element); + if (descriptor.dwordCount > metadata.descriptor.size()) fail("runtime resource descriptor width exceeded"); + std::copy_n(descriptor.dwords.begin(), descriptor.dwordCount, metadata.descriptor.begin()); + metadata.flags = image && descriptor.dwords[0] == 0u && (descriptor.dwords[1] & 0xffu) == 0u ? 1u : 0u; + } + ++metadata.elementCount; + } + } + std::vector result(RuntimeAbi::ShaderDataDwords); + std::memcpy(result.data(), &data, sizeof(data)); return result; } diff --git a/core/shader/recompiler/RuntimeAbi.hpp b/core/shader/recompiler/RuntimeAbi.hpp index 1f3dcbfa9..455d0412e 100644 --- a/core/shader/recompiler/RuntimeAbi.hpp +++ b/core/shader/recompiler/RuntimeAbi.hpp @@ -1,33 +1,81 @@ #ifndef CORE_SHADER_RECOMPILER_RUNTIMEABI_HPP #define CORE_SHADER_RECOMPILER_RUNTIMEABI_HPP +#include +#include #include +#include #include namespace ShaderRecompiler::RuntimeAbi { -inline constexpr std::uint32_t Version = 1u; +inline constexpr std::uint32_t Version = 2u; inline constexpr std::uint32_t DescriptorSet = 0u; inline constexpr std::uint32_t StageCount = 4u; inline constexpr std::uint32_t PushConstantDwords = 32u; inline constexpr std::uint32_t FirstImageBinding = 1u; inline constexpr std::uint32_t FirstComparisonImageBinding = 22u; inline constexpr std::uint32_t FirstStorageImageBinding = 29u; -inline constexpr std::uint32_t ImageBindingCount = 43u; +inline constexpr std::uint32_t ImageBindingCount = 48u; enum class Binding : std::uint32_t { Buffers = 0u, - Samplers = 44u, - Gds = 45u, - BdaPagetable = 46u, - FaultBuffer = 47u, - FlattenedSrt = 48u, - ShaderData = 49u, - Count = 50u + Samplers = 49u, + Gds = 50u, + BdaPagetable = 51u, + FaultBuffer = 52u, + FlattenedSrt = 53u, + ShaderData = 54u, + Count = 55u }; enum class Stage : std::uint32_t { Main, Fragment, TessellationControl, TessellationEvaluation }; +inline constexpr std::uint32_t UserDataCapacity = 128u; +inline constexpr std::uint32_t BufferCapacity = 128u; +inline constexpr std::uint32_t ImageCapacity = 256u; +inline constexpr std::uint32_t SampledHeapCapacity = 16u; +inline constexpr std::uint32_t StorageHeapCapacity = 4u; +inline constexpr std::uint32_t SamplerHeapCapacity = 16u; + +struct ResourceMetadata { + std::uint32_t binding; + std::uint32_t firstElement; + std::uint32_t elementCount; + std::uint32_t flags; + std::array descriptor; +}; + +struct ShaderData { + std::uint32_t version; + std::uint32_t imageCount; + std::uint32_t samplerCount; + std::uint32_t reserved; + std::array userData; + std::array bufferOffsets; + std::array dispatchThreadLimit; + std::array images; + std::array samplers; +}; + +inline constexpr std::uint32_t UserDataDword = offsetof(ShaderData, userData) / sizeof(std::uint32_t); +inline constexpr std::uint32_t BufferOffsetsDword = offsetof(ShaderData, bufferOffsets) / sizeof(std::uint32_t); +inline constexpr std::uint32_t DispatchThreadLimitDword = offsetof(ShaderData, dispatchThreadLimit) / sizeof(std::uint32_t); +inline constexpr std::uint32_t ShaderDataDwords = sizeof(ShaderData) / sizeof(std::uint32_t); + +inline std::uint32_t HeapCapacity(Binding binding) { + const auto value = static_cast(binding); + if (value >= FirstImageBinding && value < FirstStorageImageBinding) return SampledHeapCapacity; + if (value >= FirstStorageImageBinding && value < static_cast(Binding::Samplers)) return StorageHeapCapacity; + if (binding == Binding::Samplers) return SamplerHeapCapacity; + throw std::runtime_error("Shader runtime ABI: binding is not a typed heap"); +} + +static_assert(std::is_standard_layout_v && std::is_trivially_copyable_v && sizeof(ResourceMetadata) == 48u); +static_assert(std::is_standard_layout_v && std::is_trivially_copyable_v && sizeof(ShaderData) == 13728u); +static_assert(UserDataDword == 4u && BufferOffsetsDword == 132u && DispatchThreadLimitDword == 164u); +static_assert(offsetof(ResourceMetadata, descriptor) == 16u && offsetof(ShaderData, images) == 672u && offsetof(ShaderData, samplers) == 12960u); + inline void RequireVersion(std::uint32_t version) { if (version != Version) throw std::runtime_error("Shader runtime ABI: incompatible version"); } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index 28a7bdf07..5df277b99 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -393,7 +393,10 @@ void DefineDescriptors(SpirvEmitterState& state) { return variable; }; const auto ArrayType = [&](std::uint32_t type) { - return state.module.Type(spv::OpTypeArray, type, ConstantU32(state, static_cast(binding.resources.size()))); + const bool heap = binding.kind == DescriptorBindingKind::Samplers || ImageBindingResourceClass(binding.kind) != ImageResourceClass::None; + const auto count = heap ? RuntimeAbi::HeapCapacity(binding.kind) : static_cast(binding.resources.size()); + if (binding.resources.size() > count) FailEmit("typed descriptor heap capacity exceeded"); + return state.module.Type(spv::OpTypeArray, type, ConstantU32(state, count)); }; switch (binding.kind) { case DescriptorBindingKind::Buffers: diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp index acf202be8..0f3e3532b 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp @@ -21,7 +21,7 @@ bool UserDataDwordIndex(const SpirvEmitterState& state, ScalarReg reg, std::uint if (found == registers.end() || *found != registerIndex) { return false; } - dwordIndex = static_cast(found - registers.begin()); + dwordIndex = RuntimeAbi::UserDataDword + registerIndex; return true; }