From 6eb5bce3920b68006e6058a48aab5938f3f59a8b Mon Sep 17 00:00:00 2001 From: Ash Hopkins Date: Sun, 22 Nov 2026 11:25:05 +0000 Subject: [PATCH 001/115] runtime: accept a Vulkan 1.2 device with the dynamic rendering and synchronization2 extensions The D3D12 layer and its GPU tests took only Vulkan 1.3 devices, for dynamicRendering and synchronization2. CrossOver's MoltenVK on macOS (1.2.10, the driver its Wine uses) is Vulkan 1.2 with VK_KHR_dynamic_rendering and VK_KHR_synchronization2, the same features under their extension names, so every Vulkan-backed test skipped there. src/vulkan13_features.h picks the core features on 1.3 and the two extensions on 1.2, and device_proc_or_khr falls back to the ...KHR entry points (vkCmdPipelineBarrier2KHR, vkCmdBeginRenderingKHR), which a 1.2 device serves instead of the core names. The translated shaders are SPIR-V 1.5 validated for Vulkan 1.2 already. On a 1.3 device the feature chain is the one it was. Tested in a CrossOver Preview arm64 bottle (FEX) on an Apple M2 Max, cross-built with clang-cl 22.1.8 and xwin: against main at the same commit, no test that passed fails, and d3d12_com, d3d12_multithread, d3d12_method_variants, d3d12_uav_clear, d3d12_debug_markers, d3d12_fence_timing, d3d12_sampler2, d3d12_typeless_rtv, d3d12_predicated_copy and depth24_convert now run and pass. Ten more now run and fail: comparisons with Wine's host D3D12, and MoltenVK 1.2.10 limits (vk_binary_occlusion and vk_overlapping_occlusion fail the same way natively on that driver and pass on MoltenVK 1.4.2). The 1.3 path of create_vulkan_device_standalone was not run on a 1.3 device here. AI-assisted. No game files. --- runtime/shims/d3d12_vulkan_device.cpp | 49 ++++++----- runtime/src/vulkan13_features.h | 118 ++++++++++++++++++++++++++ runtime/src/vulkan_backend.h | 6 +- runtime/test/vk_test_device.h | 58 ++++++++----- 4 files changed, 184 insertions(+), 47 deletions(-) create mode 100644 runtime/src/vulkan13_features.h diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index d98e3d1dc7..793b041c7a 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -21,10 +21,10 @@ #include "../src/shader_library.h" #include "../src/vulkan_present.h" #include "../src/vulkan_device_filter.h" +#include "../src/vulkan13_features.h" #include - #include #include #include @@ -5244,7 +5244,8 @@ HRESULT create_dxgi_factory(ID3D12Device* device, REFIID riid, void** out) { i.queue_family, riid, out); } -// Creates its own Vulkan 1.3 instance and device. LEONIDA_VK_VALIDATION=1 adds VK_LAYER_KHRONOS_validation. +// Creates its own Vulkan instance and a Vulkan 1.3 device, or a 1.2 device with VK_KHR_dynamic_rendering and +// VK_KHR_synchronization2 (vulkan13_features.h). LEONIDA_VK_VALIDATION=1 adds VK_LAYER_KHRONOS_validation. HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { if (!out) return E_POINTER; *out = nullptr; @@ -5342,18 +5343,18 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { bool chosen_bc = false; VkPhysicalDeviceFeatures chosen_features{}; VkPhysicalDeviceVulkan12Features chosen12{}; + leonida::Vulkan13Features v13, candidate13; for (VkPhysicalDevice candidate : physicals) { VkPhysicalDeviceProperties props{}; vkGetPhysicalDeviceProperties(candidate, &props); - if (props.apiVersion < VK_API_VERSION_1_3 || !leonida::vulkan_device_wanted(props.deviceName)) continue; - VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; - VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &f13}; + if (!leonida::vulkan_device_wanted(props.deviceName)) continue; + candidate13.query(candidate, props.apiVersion, vkGetPhysicalDeviceFeatures2, vkEnumerateDeviceExtensionProperties); + if (!candidate13.usable()) continue; + VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &f12}; vkGetPhysicalDeviceFeatures2(candidate, &features); const bool bc = features.features.textureCompressionBC; - if (!f13.dynamicRendering || !f13.synchronization2 || !f12.timelineSemaphore || - !f12.separateDepthStencilLayouts || !f12.bufferDeviceAddress) - continue; + if (!f12.timelineSemaphore || !f12.separateDepthStencilLayouts || !f12.bufferDeviceAddress) continue; std::uint32_t family_count = 0; vkGetPhysicalDeviceQueueFamilyProperties(candidate, &family_count, nullptr); std::vector families(family_count); @@ -5367,16 +5368,21 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { chosen_bc = bc; chosen_features = features.features; chosen12 = f12; + v13.choose(candidate13); } break; } } if (!info.physical) return fail(leonida::vulkan_device_filter().empty() - ? "no Vulkan 1.3 GPU with dynamicRendering, synchronization2, timelineSemaphore and " - "separateDepthStencilLayouts" - : "no GPU named by LEONIDA_VK_DEVICE has Vulkan 1.3 with dynamicRendering, synchronization2, " - "timelineSemaphore and separateDepthStencilLayouts"); + ? "no Vulkan 1.3 GPU (or 1.2 with VK_KHR_dynamic_rendering and VK_KHR_synchronization2) with " + "dynamicRendering, synchronization2, timelineSemaphore and separateDepthStencilLayouts" + : "no GPU named by LEONIDA_VK_DEVICE has Vulkan 1.3 (or 1.2 with VK_KHR_dynamic_rendering and " + "VK_KHR_synchronization2) with dynamicRendering, synchronization2, timelineSemaphore and " + "separateDepthStencilLayouts"); + if (!v13.core) + std::fprintf(stderr, "[rt] d3d12: Vulkan 1.2 device: dynamicRendering and synchronization2 through their KHR " + "extensions\n"); // VK_EXT_conditional_rendering for SetPredication, VK_KHR_swapchain for DXGI presentation, and optional // VK_KHR_acceleration_structure + VK_KHR_ray_query for hardware BVH builds (BLAS + TLAS). @@ -5436,10 +5442,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { ext_chain = &enable_conditional; } - VkPhysicalDeviceVulkan13Features enable13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES, ext_chain}; - enable13.dynamicRendering = VK_TRUE; - enable13.synchronization2 = VK_TRUE; - VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable13}; + VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, + v13.enable(ext_chain)}; enable12.timelineSemaphore = VK_TRUE; enable12.separateDepthStencilLayouts = VK_TRUE; info.buffer_device_address = chosen12.bufferDeviceAddress == VK_TRUE; @@ -5505,8 +5509,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { vkGetPhysicalDeviceFeatures2(info.physical, &query); info.image_view_min_lod = min_lod.minLod == VK_TRUE; if (info.image_view_min_lod) { - min_lod.pNext = enable13.pNext; - enable13.pNext = &min_lod; + min_lod.pNext = *v13.next(); + *v13.next() = &min_lod; } } VkPhysicalDeviceHostImageCopyFeaturesEXT host_copy{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_IMAGE_COPY_FEATURES_EXT}; @@ -5517,8 +5521,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { const char* host_image_copy_name = VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME; info.host_image_copy = has_host_image_copy && host_copy.hostImageCopy; if (info.host_image_copy) { - host_copy.pNext = enable13.pNext; // after the conditional rendering features, if any - enable13.pNext = &host_copy; + host_copy.pNext = *v13.next(); // after the conditional rendering features, if any + *v13.next() = &host_copy; } else { std::fprintf(stderr, "[rt] d3d12: no VK_EXT_host_image_copy; CPU texture copies use a staging submit\n"); } @@ -5535,8 +5539,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { vkGetPhysicalDeviceFeatures2(info.physical, &query); info.shader_fma = shader_fma.shaderFmaFloat32 == VK_TRUE; if (info.shader_fma) { - shader_fma.pNext = enable13.pNext; - enable13.pNext = &shader_fma; + shader_fma.pNext = *v13.next(); + *v13.next() = &shader_fma; } } #endif @@ -5572,6 +5576,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { device_info.pQueueCreateInfos = &queue_info; device_info.pEnabledFeatures = &enable; std::vector device_extensions; + v13.add_extensions(device_extensions); if (info.image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); if (info.conditional_rendering) device_extensions.push_back(conditional_extension); if (info.host_image_copy) device_extensions.push_back(host_image_copy_name); diff --git a/runtime/src/vulkan13_features.h b/runtime/src/vulkan13_features.h new file mode 100644 index 0000000000..111d81df3d --- /dev/null +++ b/runtime/src/vulkan13_features.h @@ -0,0 +1,118 @@ +#pragma once + +// dynamicRendering and synchronization2, the two Vulkan 1.3 features the D3D12 layer needs, on a Vulkan 1.3 device +// or on a Vulkan 1.2 device through VK_KHR_dynamic_rendering and VK_KHR_synchronization2. CrossOver's MoltenVK on +// macOS is such a 1.2 device (1.2.10: Vulkan 1.2 with both extensions); the extension structs, functions and +// behaviour are the core ones under another name, so the rest of the layer does not see the difference. +// +// leonida::Vulkan13Features v13; +// v13.query(physical, props.apiVersion, get_features2, enumerate_extensions); // per candidate +// if (!v13.usable()) continue; +// enable12.pNext = v13.enable(chain); // chain: what came after VkPhysicalDeviceVulkan13Features +// ... v13.next() is where later feature structs go (it used to be enable13.pNext) +// v13.add_extensions(device_extensions); +// fn = leonida::device_proc_or_khr(get_device_proc, device, "vkCmdPipelineBarrier2"); + +#include + +#include +#include +#include +#include + +namespace leonida { + +class Vulkan13Features { +public: + Vulkan13Features() = default; + Vulkan13Features(const Vulkan13Features&) = delete; // enable() links pointers into this object + Vulkan13Features& operator=(const Vulkan13Features&) = delete; + + bool core = false; // a Vulkan 1.3 device: the features are core + bool dynamic_rendering = false; // supported, as a core feature or through VK_KHR_dynamic_rendering + bool synchronization2 = false; // supported, as a core feature or through VK_KHR_synchronization2 + + bool usable() const { return dynamic_rendering && synchronization2; } + + // Fills the flags above for one physical device. A device older than 1.2 never qualifies. + void query(VkPhysicalDevice physical, std::uint32_t api_version, PFN_vkGetPhysicalDeviceFeatures2 features2, + PFN_vkEnumerateDeviceExtensionProperties enumerate_extensions) { + core = api_version >= VK_API_VERSION_1_3; + dynamic_rendering = synchronization2 = false; + if (!features2) return; + if (core) { + VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &f13}; + features2(physical, &query); + dynamic_rendering = f13.dynamicRendering == VK_TRUE; + synchronization2 = f13.synchronization2 == VK_TRUE; + return; + } + if (api_version < VK_API_VERSION_1_2 || !enumerate_extensions) return; + std::uint32_t count = 0; + enumerate_extensions(physical, nullptr, &count, nullptr); + std::vector extensions(count); + enumerate_extensions(physical, nullptr, &count, extensions.data()); + bool has_dynamic_rendering = false, has_synchronization2 = false; + for (const auto& e : extensions) { + has_dynamic_rendering |= std::strcmp(e.extensionName, VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) == 0; + has_synchronization2 |= std::strcmp(e.extensionName, VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME) == 0; + } + if (!has_dynamic_rendering || !has_synchronization2) return; + VkPhysicalDeviceSynchronization2FeaturesKHR sync2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR}; + VkPhysicalDeviceDynamicRenderingFeaturesKHR rendering{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR, &sync2}; + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &rendering}; + features2(physical, &query); + dynamic_rendering = rendering.dynamicRendering == VK_TRUE; + synchronization2 = sync2.synchronization2 == VK_TRUE; + } + + // Copies the flags of the device query() chose (a later query() for another candidate overwrites them). + void choose(const Vulkan13Features& from) { + core = from.core; + dynamic_rendering = from.dynamic_rendering; + synchronization2 = from.synchronization2; + } + + // The structs that enable both features, ahead of `chain`; returns their head for VkPhysicalDeviceVulkan12Features' + // pNext. Call once, after query() or choose(). + void* enable(void* chain) { + if (core) { + enable13_.pNext = chain; + enable13_.dynamicRendering = VK_TRUE; + enable13_.synchronization2 = VK_TRUE; + return &enable13_; + } + sync2_.pNext = chain; + sync2_.synchronization2 = VK_TRUE; + rendering_.pNext = &sync2_; + rendering_.dynamicRendering = VK_TRUE; + return &rendering_; + } + + // Where a feature struct goes to follow these: insert with `s.pNext = *next(); *next() = &s;`. + void** next() { return core ? &enable13_.pNext : &sync2_.pNext; } + + // The device extensions a 1.2 device needs for both features; none on 1.3. + void add_extensions(std::vector& extensions) const { + if (core) return; + extensions.push_back(VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME); + extensions.push_back(VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME); + } + +private: + VkPhysicalDeviceVulkan13Features enable13_{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; + VkPhysicalDeviceDynamicRenderingFeaturesKHR rendering_{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR}; + VkPhysicalDeviceSynchronization2FeaturesKHR sync2_{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR}; +}; + +// A device function by its core name, or by its KHR name where the core one is null: a Vulkan 1.2 device returns +// null for Vulkan 1.3 core names (vkCmdPipelineBarrier2, vkCmdBeginRendering, ...) and serves the enabled +// extension's vkCmdPipelineBarrier2KHR and the like, which have the same signatures. +inline PFN_vkVoidFunction device_proc_or_khr(PFN_vkGetDeviceProcAddr get, VkDevice device, const char* name) { + if (const PFN_vkVoidFunction function = get(device, name)) return function; + return get(device, (std::string(name) + "KHR").c_str()); +} + +} // namespace leonida diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 7006911c24..245aad6bb6 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -3,7 +3,8 @@ // The execution side of the D3D12 layer, without COM: the per-device Vulkan context (resources, layout tracker, // image views), queues that execute command lists, and timeline-semaphore fences. The COM objects in // shims/d3d12_com.cpp are thin wrappers over these. Needs Vulkan 1.2 timeline semaphores; rectangle clears and -// enhanced barriers need the Vulkan 1.3 functions (dynamicRendering, synchronization2) to be enabled. +// enhanced barriers need the Vulkan 1.3 functions (dynamicRendering, synchronization2) to be enabled, as core +// features or through their KHR extensions on a 1.2 device (vulkan13_features.h). #ifndef VK_NO_PROTOTYPES #define VK_NO_PROTOTYPES @@ -11,6 +12,7 @@ #include "binary_occlusion_spirv.h" #include "occlusion_sum_spirv.h" #include "statistics_sum_spirv.h" +#include "vulkan13_features.h" #include "vulkan_depth24.h" #include "vulkan_scratch.h" #include "vulkan_replay.h" @@ -81,7 +83,7 @@ struct VulkanDeviceFunctions { // extension is not enabled, and the query functions are optional (a list that uses queries without them is // unsupported). The compute and descriptor functions are needed for normalized or summed occlusion results. bool load(PFN_vkGetDeviceProcAddr get, VkDevice device) { -#define LEONIDA_VK_LOAD(name) name = reinterpret_cast(get(device, #name)); +#define LEONIDA_VK_LOAD(name) name = reinterpret_cast(leonida::device_proc_or_khr(get, device, #name)); LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_LOAD) #undef LEONIDA_VK_LOAD return vkCreateCommandPool && vkDestroyCommandPool && vkAllocateCommandBuffers && vkResetCommandBuffer && diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index b5a1ca4149..dee4e18a64 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -1,10 +1,12 @@ -// Shared setup for the GPU tests of the D3D12 layer: a Vulkan 1.3 device with dynamicRendering, synchronization2, -// timelineSemaphore and separateDepthStencilLayouts, images, buffers and one-shot submissions. +// Shared setup for the GPU tests of the D3D12 layer: a Vulkan 1.3 device (or 1.2 with VK_KHR_dynamic_rendering and +// VK_KHR_synchronization2) with dynamicRendering, synchronization2, timelineSemaphore and +// separateDepthStencilLayouts, images, buffers and one-shot submissions. // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; Device::validation_errors() counts errors. #pragma once #include "vulkan_loader.h" #include "../src/vulkan_device_filter.h" +#include "../src/vulkan13_features.h" #include "vk_device_pick.h" #include @@ -125,9 +127,10 @@ class Device { reinterpret_cast(instance_proc(instance, "vkDestroyInstance"))(instance, nullptr); } + // A Vulkan 1.3 function falls back to its KHR name on a 1.2 device. template F fn(const char* name) const { - return reinterpret_cast(device_proc(device, name)); + return reinterpret_cast(leonida::device_proc_or_khr(device_proc, device, name)); } template @@ -234,10 +237,16 @@ class Device { if (result != VK_SUCCESS) return failure("vkEnumeratePhysicalDevices", result); VkPhysicalDeviceProperties chosen{}; int best_rank = -1; + const auto features2_of = instance_fn("vkGetPhysicalDeviceFeatures2"); + const auto device_extensions_of = + instance_fn("vkEnumerateDeviceExtensionProperties"); + leonida::Vulkan13Features candidate13; for (auto candidate : devices) { VkPhysicalDeviceProperties props{}; properties_of(candidate, &props); - if (props.apiVersion < VK_API_VERSION_1_3 || !leonida::vulkan_device_wanted(props.deviceName)) continue; + if (!leonida::vulkan_device_wanted(props.deviceName)) continue; + candidate13.query(candidate, props.apiVersion, features2_of, device_extensions_of); + if (!candidate13.usable()) continue; std::uint32_t family_count = 0; families_of(candidate, &family_count, nullptr); std::vector families(family_count); @@ -250,6 +259,7 @@ class Device { family = i; chosen = props; best_rank = rank; + v13_.choose(candidate13); } break; } @@ -257,21 +267,24 @@ class Device { if (!physical) { if (const std::string filter = leonida::vulkan_device_filter(); !filter.empty()) { // A filter that matches nothing fails the test instead of skipping it. - std::fprintf(stderr, "LEONIDA_VK_DEVICE=%s: no Vulkan 1.3 device with a graphics queue matches\n", + std::fprintf(stderr, + "LEONIDA_VK_DEVICE=%s: no Vulkan 1.3 device (or 1.2 with VK_KHR_dynamic_rendering and " + "VK_KHR_synchronization2) with a graphics queue matches\n", filter.c_str()); return DeviceStatus::failed; } - std::fprintf(stderr, "no Vulkan 1.3 device with a graphics queue\n"); + std::fprintf(stderr, "no Vulkan 1.3 device (or 1.2 with VK_KHR_dynamic_rendering and " + "VK_KHR_synchronization2) with a graphics queue\n"); return DeviceStatus::unavailable; } - std::printf("device: %s%s\n", chosen.deviceName, validation ? " (validation on)" : ""); + std::printf("device: %s%s%s\n", chosen.deviceName, v13_.core ? "" : " (Vulkan 1.2 + KHR extensions)", + validation ? " (validation on)" : ""); - VkPhysicalDeviceVulkan13Features features13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; - VkPhysicalDeviceVulkan12Features features12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &features13}; + VkPhysicalDeviceVulkan12Features features12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &features12}; - instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &features); - if (!features13.dynamicRendering || !features13.synchronization2 || !features12.timelineSemaphore || - !features12.separateDepthStencilLayouts || !features12.bufferDeviceAddress) { + features2_of(physical, &features); + if (!features12.timelineSemaphore || !features12.separateDepthStencilLayouts || + !features12.bufferDeviceAddress) { std::fprintf(stderr, "the device lacks dynamicRendering, synchronization2, timelineSemaphore or " "separateDepthStencilLayouts\n"); return DeviceStatus::unavailable; @@ -297,11 +310,8 @@ class Device { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT}; enable_conditional.conditionalRendering = VK_TRUE; - VkPhysicalDeviceVulkan13Features enable13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES, - conditional_rendering ? &enable_conditional : nullptr}; - enable13.dynamicRendering = VK_TRUE; - enable13.synchronization2 = VK_TRUE; - VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable13}; + VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, + v13_.enable(conditional_rendering ? &enable_conditional : nullptr)}; enable12.timelineSemaphore = VK_TRUE; enable12.separateDepthStencilLayouts = VK_TRUE; storage_buffer_8bit = features12.storageBuffer8BitAccess == VK_TRUE; @@ -350,8 +360,8 @@ class Device { instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); image_view_min_lod = min_lod.minLod == VK_TRUE; if (image_view_min_lod) { - min_lod.pNext = enable13.pNext; - enable13.pNext = &min_lod; + min_lod.pNext = *v13_.next(); + *v13_.next() = &min_lod; } } VkPhysicalDeviceHostImageCopyFeaturesEXT host_copy{ @@ -364,8 +374,8 @@ class Device { } const char* host_image_copy_name = VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME; if (host_image_copy) { - host_copy.pNext = enable13.pNext; // after the conditional rendering features, if any - enable13.pNext = &host_copy; + host_copy.pNext = *v13_.next(); // after the conditional rendering features, if any + *v13_.next() = &host_copy; } #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME @@ -378,8 +388,8 @@ class Device { instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); shader_fma = fma_features.shaderFmaFloat32 == VK_TRUE; if (shader_fma) { - fma_features.pNext = enable13.pNext; - enable13.pNext = &fma_features; + fma_features.pNext = *v13_.next(); + *v13_.next() = &fma_features; } } #endif @@ -393,6 +403,7 @@ class Device { device_info.pEnabledFeatures = &enable; enabled = enable; std::vector device_extensions; + v13_.add_extensions(device_extensions); if (image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); if (conditional_rendering) device_extensions.push_back(conditional_extension); if (host_image_copy) device_extensions.push_back(host_image_copy_name); @@ -543,6 +554,7 @@ class Device { VkDebugUtilsMessengerEXT messenger_ = VK_NULL_HANDLE; VkCommandPool pool_ = VK_NULL_HANDLE; VkPhysicalDeviceMemoryProperties memory_{}; + leonida::Vulkan13Features v13_; // the chosen device's dynamicRendering/synchronization2 path std::vector> images_; std::vector> buffers_; }; From c8ea00e4db78f582978aa4efcfc30e9a3957a7fc Mon Sep 17 00:00:00 2001 From: Ryx <118130241+Ryx69@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:19:43 +0100 Subject: [PATCH 002/115] Runtime: pause the active occlusion query around a resolve (D3D-189) The Radeon 8060S on AMD's Windows driver times out (TDR) on the crossing pattern of vk_overlapping_occlusion: a resolve recorded while an ordinary occlusion query is active, so vkCmdCopyQueryPoolResults with WAIT_BIT and the summing dispatch run while a query of the same pool is active (#1540, found with --bisect). Validation reports nothing before the hang. A resolve while a physical segment is active now ends that segment before the resolve and begins the next one after it; the logical query's range spans one more segment, so results are unchanged. A list that resolves inside a single active query takes the segment path too when the device can sum. The test adds a resolve inside one active query (default run and the new "active" bisect phase), gives the crossing schedule the extra segment end, and --bisect now detects a lost device by the queue timeline reading UINT64_MAX, since vkQueueWaitIdle succeeds after the reset on that driver. --- docs/d3d12_vulkan.md | 10 +++-- runtime/src/vulkan_replay.h | 37 +++++++++++++----- .../test/vk_overlapping_occlusion_test.cpp | 38 +++++++++++++++---- 3 files changed, 65 insertions(+), 20 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 7622cb4ac4..3438f36e3a 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1808,9 +1808,13 @@ Implemented (`QueryHeap` in `runtime/shims/d3d12_vulkan_device.cpp`, the query c submission's physical pool. Resolving it sums the 64-bit counts on the GPU, then copies the result to the destination. Both occlusion compute helpers reuse one scratch buffer per queue. Logical results and in-flight submissions retain the pool independently, so later resolves and - overwrites can be recorded before the earlier commands complete. `vk_overlapping_occlusion` checks crossing - and nested scopes, more than one scratch chunk, alternating binary and ordinary resolves under a predicate, - and gated submissions on a GPU. + overwrites can be recorded before the earlier commands complete. A resolve while an ordinary query is active + ends the active physical query before the resolve and begins the next one after it, and a list with such a + resolve takes this path even without an overlap: AMD's Windows driver on a Radeon 8060S times out (TDR) on a + query copy and summing dispatch recorded while a query of the same pool is active (D3D-189, #1540). + `vk_overlapping_occlusion` checks crossing and nested scopes, a resolve inside a single active query, more than + one scratch chunk, alternating binary and ordinary resolves under a predicate, and gated submissions on a GPU; + `--bisect` runs its patterns one per submission to find one that hangs a device. - **Timestamps.** `GetTimestampFrequency` is `1e9 / timestampPeriod` (1 GHz on the test GPU). Every D3D12 queue shares one `VkQueue` for now (question 12), so they share one frequency. diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 8f1e17213a..bde9b57709 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -1647,11 +1647,19 @@ class PreparedList { inline ReplayResult plan_occlusion_segments(PreparedList& out) { // Active logical queries cover a contiguous range of physical slots. A Begin or End closes the old // slot and opens a new one if any query remains active. Each shared interval is recorded only once. + // A resolve while a slot is active closes it before the resolve and opens the next after it, so no query is + // active during the copy and its dispatch (D3D-189); the logical ranges simply span one more slot. std::map, std::uint32_t> active; std::uint32_t current = detail::PreparedQuery::no_segment; for (auto& query : out.queries) { const Command& command = out.list->commands()[query.command]; - if (std::holds_alternative(command)) continue; + if (std::holds_alternative(command)) { + if (current == detail::PreparedQuery::no_segment) continue; + query.end_segment = current; + current = out.segment_count++; + query.begin_segment = current; + continue; + } const auto range = query_range(command); if (range.type != d3d12_query::occlusion) continue; const auto key = std::pair{range.heap, range.first}; @@ -2051,6 +2059,11 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun // The internal dispatch would otherwise count towards the application's CSInvocations. if (!vk.resolve_binary_occlusion || statistics_active) return ReplayResult::unsupported; } + // No resolve runs while an ordinary occlusion query is active: AMD's Windows driver (Radeon 8060S, + // 26.10.1) times out on vkCmdCopyQueryPoolResults with WAIT_BIT, or the summing dispatch, recorded + // while a query of the same pool is active (D3D-189, #1540). The segment path can pause the active + // query around the resolve (plan_occlusion_segments), so such a list takes it when it can sum. + if (ordinary_active && vk.sum_occlusion) overlaps = true; if (p.binding.host_readable) { out.wrote_readback = true; out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; @@ -2198,16 +2211,21 @@ class QueryReplay { inline void emit_query(const PreparedList& list, const detail::PreparedQuery& query, VkCommandBuffer cb, const ReplayFunctions& vk, const VkConditionalRenderingBeginInfoEXT& predicate) { constexpr auto none = detail::PreparedQuery::no_segment; - if (query.end_segment != none || query.begin_segment != none) { - if (query.end_segment != none) vk.end_query(cb, list.segment_pool, list.segment_base + query.end_segment); - if (query.begin_segment != none) { - const auto index = list.segment_base + query.begin_segment; - vk.reset_query_pool(cb, list.segment_pool, index, 1); - vk.begin_query(cb, list.segment_pool, index, list.precise_segments ? VK_QUERY_CONTROL_PRECISE_BIT : 0); - } + const auto& command = list.list->commands()[query.command]; + // A Begin or End of a segmented query only moves between segments. A resolve inside a segment ends it before + // the resolve and begins the next one after it. + const bool segmented = query.end_segment != none || query.begin_segment != none; + if (query.end_segment != none) vk.end_query(cb, list.segment_pool, list.segment_base + query.end_segment); + const auto begin_segment = [&] { + if (query.begin_segment == none) return; + const auto index = list.segment_base + query.begin_segment; + vk.reset_query_pool(cb, list.segment_pool, index, 1); + vk.begin_query(cb, list.segment_pool, index, list.precise_segments ? VK_QUERY_CONTROL_PRECISE_BIT : 0); + }; + if (segmented && !std::holds_alternative(command)) { + begin_segment(); return; } - const auto& command = list.list->commands()[query.command]; const QueryPool& heap = *query.heap; if (const auto* begin = std::get_if(&command)) { vk.reset_query_pool(cb, heap.pool, begin->index, 1); @@ -2243,6 +2261,7 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu } } if (suspend) vk.begin_conditional_rendering(cb, &predicate); + begin_segment(); } } diff --git a/runtime/test/vk_overlapping_occlusion_test.cpp b/runtime/test/vk_overlapping_occlusion_test.cpp index 022d2b7714..e92d1ef069 100644 --- a/runtime/test/vk_overlapping_occlusion_test.cpp +++ b/runtime/test/vk_overlapping_occlusion_test.cpp @@ -178,9 +178,10 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec Fixture fixture{d}; EXPECT(fixture.create(vertex, fragment)); constexpr std::uint32_t bursts = 130; - Draws schedule{fixture, {8, 4, 2, 8, 4, 2, 3}}; + // crossing ends four physical queries (the resolve inside it splits the last one), nested three. + Draws schedule{fixture, {8, 4, 2, 0, 8, 4, 2, 3}}; schedule.extents.insert(schedule.extents.end(), 2 * bursts + 1, 1); - schedule.extents.insert(schedule.extents.end(), {2, 0, 0, 0}); + schedule.extents.insert(schedule.extents.end(), {2, 0, 0, 0, 1, 1}); schedule.every = bisect.enabled; draws = &schedule; VulkanContext context(get_device_proc, d.device, true, d.conditional_rendering); @@ -236,6 +237,10 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec EXPECT(l->resolve_queries({a, occ, 0, 1, dst_id, 8}) && l->end_query({a, occ, 1})); EXPECT(l->resolve_queries({a, occ, 0, 2, dst_id, 24})); } + if (auto* l = add("active")) { // a resolve inside one active query, without an overlap + EXPECT(l->begin_query({a, occ, 0}) && l->end_query({a, occ, 0}) && l->begin_query({a, occ, 3})); + EXPECT(l->resolve_queries({a, occ, 0, 1, dst_id, 128}) && l->end_query({a, occ, 3})); + } if (auto* l = add("nested")) { // the same index in two heaps, one inside the other EXPECT(l->begin_query({a, occ, 2}) && l->begin_query({b, occ, 2})); EXPECT(l->end_query({b, occ, 2}) && l->end_query({a, occ, 2})); @@ -270,6 +275,14 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec EXPECT(l->resolve_queries({a, occ, 0, 2, dst_id, 112})); } EXPECT(!lists.empty()); + // After a TDR, AMD's Windows driver lets vkQueueWaitIdle succeed (#1540); the queue's timeline then reads + // UINT64_MAX, so that is checked as well. + const auto get_value = d.fn("vkGetSemaphoreCounterValue"); + const auto lost = [&] { + std::uint64_t value = 0; + const VkSemaphore timeline = context.retire_timeline(); + return timeline && (get_value(d.device, timeline, &value) != VK_SUCCESS || value == UINT64_MAX); + }; if (bisect.gated) queue.wait(gate.semaphore(), 1); for (auto& [name, list] : lists) { EXPECT(list.close()); @@ -281,15 +294,15 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec std::printf("%s: execute returned %d\n", name, int(result)); return 1; } - if (!bisect.gated && !queue.idle()) { - std::printf("%s: vkQueueWaitIdle failed (device lost?)\n", name); + if (!bisect.gated && (!queue.idle() || lost())) { + std::printf("%s: device lost\n", name); return 1; } } if (bisect.gated) { EXPECT(gate.signal(1)); - if (!queue.idle()) { - std::printf("gated: vkQueueWaitIdle failed (device lost?)\n"); + if (!queue.idle() || lost()) { + std::printf("gated: device lost\n"); return 1; } } @@ -377,13 +390,22 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec EXPECT(replace.close()); const CommandList* fourth[] = {&replace}; EXPECT(queue.execute(fourth) == ReplayResult::success); + + // A resolve inside one active query, with no overlap: the active query is paused around it (D3D-189). + CommandList single; + EXPECT(single.begin_query({a, occ, 3})); + EXPECT(single.resolve_queries({a, occ, 0, 1, dst_id, 128})); + EXPECT(single.end_query({a, occ, 3})); + EXPECT(single.close()); + const CommandList* fifth[] = {&single}; + EXPECT(queue.execute(fifth) == ReplayResult::success); EXPECT(!schedule.overflow && schedule.next == schedule.extents.size()); EXPECT(gate.signal(1)); EXPECT(queue.idle()); const std::map expected = { {8, 80}, {24, 80}, {32, 20}, {40, 84}, {48, 16}, {56, 0}, {64, 1}, {72, 80}, {80, 1}, - {88, 2 * bursts + 1}, {96, 1}, {112, 4}, {120, 0}, + {88, 2 * bursts + 1}, {96, 1}, {112, 4}, {120, 0}, {128, 4}, }; for (VkDeviceSize offset = 0; offset < size; offset += 8) { const auto it = expected.find(offset - binding_offset); @@ -397,7 +419,7 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec } } std::printf("crossing 80/20; nested 84/16; %u segments summed; alternating binary results 1/1; " - "offsets and gated overwrites exact\n", + "resolve inside an active query 4; offsets and gated overwrites exact\n", 2 * bursts + 1); EXPECT(copy_control.check()); return 0; From 9fa652f7a26febbfaa4e44e8876446cba8ef4e31 Mon Sep 17 00:00:00 2001 From: BetterJdue Date: Sun, 22 Nov 2026 14:36:40 +0100 Subject: [PATCH 003/115] d16 typed buffer loads round the exact UNORM/SNORM quotient once, as RDNA2 does (BUILD-161) docs/design.md narrowed the f16 of a typed d16 buffer load from the f32 decode with round to nearest even, and called that rounding inferred, not measured. tools/d16_format_probe.py measures it through tools/hw_oracle: every UNORM8, SNORM8, UNORM10, UNORM16 and SNORM16 value through buffer_load_format_d16_x, tbuffer_load_format_d16_x and buffer_load_format_x, in wave32 and wave64, against several candidate rules, with a 16_FLOAT load, the kept high half of d16_x and the staged inputs as controls. On an RX 6700 (gfx1031) the hardware rounds the exact quotient once, straight to f16. Rounding to f32 first is 1 ulp high on exactly four values (UNORM16 0xffaf and 0xffef, SNORM16 0x7ff7 and 0x8009); over every width up to 16 bits only two f32 quotients land on an f16 halfway point (0x3f7ff000, 0x3f7fb000). Gen.d16_norm_f16 takes the f16 below for those two, for normalized formats only. The f32 (non-d16) result was already right. Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 2 +- docs/shader_validation.md | 59 ++++ tests/semantic/test_buffer_load_format.py | 41 ++- tests/test_d16_format_probe.py | 222 ++++++++++++++ tools/d16_format_probe.py | 341 ++++++++++++++++++++++ tools/rdna2spirv.py | 38 ++- 6 files changed, 697 insertions(+), 6 deletions(-) create mode 100644 tests/test_d16_format_probe.py create mode 100644 tools/d16_format_probe.py diff --git a/docs/design.md b/docs/design.md index a9e99f4e4c..3fc7ce4876 100644 --- a/docs/design.md +++ b/docs/design.md @@ -340,7 +340,7 @@ How the generated SPIR-V expects the runtime to work: | Constant and ordered VOPC, `v_cmp(x)_nlg_*`, `v_cvt_off_f32_i4`, `v_pipeflush` | `v_cmp(x)_f_*` is always false, `v_cmp(x)_t_*` (integers) and `v_cmp(x)_tru_*` (floats) always true; `v_cmp(x)_o_{f32,f16}` is true when neither source is NaN, `_u_` when either is (`OpIsNan`), and `_nlg_` when `x == y` or either source is NaN (`OpFUnordEqual`, completing all 16 IEEE-754 RDNA2 float VOPC predicates; LLVM `gfx10_asm_vopc.s`); the result goes through the usual VOPC path (VCC, an SGPR mask, or EXEC for `v_cmpx`; off lanes give 0). `v_cvt_off_f32_i4`: D = sext(S0[3:0]) / 16 (the ISA's CVT_OFF_TABLE, -0.5 .. 0.4375), exact, output modifiers apply. `v_pipeflush` only flushes the VALU pipeline and is translated as nothing, like `v_nop`. Source: RDNA2 ISA VOPC and VOP1. CPU-checked by `tests/semantic/test_vopc_const_ordered.py`, `tests/semantic/test_float_compares.py` (`nlg`; GPU-checked by `ps_cmp_nlg.asm`: f32 and f16 with ±0, quiet and signalling NaN, ±inf and ignored f16 high halves, the e64 form with `abs`/`neg`, and `v_cmpx_nlg` on equal and NaN operands, Tesla V100 (NVIDIA 580.95.05, Linux)), `test_alu_cvt_off.py` (GPU-checked by `ps_cvt_off.asm`, upper bits ignored and `mul:4` with and without `clamp`), `test_valu_pipeflush.py`; the constant/ordered float compares were run on an RTX 5090 (16 draws, quiet and signalling NaNs) and the suite on RTX 4050 / Radeon 740M in #620; `v_pipeflush` on RTX 5090 / RTX 3060 in #735. | | Relative VGPR moves (`v_movrel*`) | The VGPR file is a Function-scope uint array, so `v_movrels_b32`/`v_movreld_b32`/`v_movrelsd_b32` become dynamic array accesses at `reg + M0` (the whole of M0, as the RDNA2 ISA's opcode descriptions say). `v_movrelsd_2_b32` (VOP1 opcode 72) offsets each side by its own field: VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]], other M0 bits ignored (RDNA2 ISA §12.8 opcode description and the RDNA3 ISA; the RDNA2 §6.6 summary table prints M0[7:0] for the source). The write keeps inactive lanes. Not modelled: the hardware's range check against the wave's VGPR allocation (an out-of-range source reads VGPR0, an out-of-range write is dropped). CPU-checked by `tests/semantic/test_alu_movrelsd_2.py` (including set ignored M0 bits); GPU-checked with `runtime/test/shaders/cs_movrelsd_2.asm` (the ISA's own example, v25 ← v17 with M0 = (20 << 16) \| 10) on NVIDIA RTX 4050 Laptop (Ada) and AMD Radeon 740M (RADV). | | Relative SGPR reads (`s_movrels_b32`, `s_movrels_b64`) | `D = SGPR[S0 + M0]`; the b64 form reads the pair at `S0 + M0` and `S0 + M0 + 1` (RDNA2 ISA SOP1). The SGPR file is a Function-scope uint array, so this is a dynamic load, as for `v_movrels`. Every SGPR write stores into that array (`store_reg`), so the load sees the current value. All reads happen before the destination is written, so D may overlap the source. SCC is not written. The index wraps to the 128 array slots, so it cannot reach the lane-mask parking slots past them. **Not modelled:** the hardware's range check, and reads past s105 landing on VCC and the other special registers. `s_movreld_b32/b64`, the relative writes, stay `Unsupported`, because the translator keeps translate-time knowledge of SGPR values (literal S# words, descriptor caches) that a dynamic write would invalidate. Until 2026-11-22 both reads raised `Unsupported`. CPU-checked by `tests/semantic/test_salu_movrels.py` (M0 from 0 to 5 and from a register, the b64 pair, an overlapping destination, SCC kept, `s_movreld` rejected). **Not GPU-verified.** | -| d16 and f16 format narrowing | The f16 of every d16 result (image samples and gathers, the `image_sample_c_lz` compare result, typed buffer loads) and of the f16 formats a typed buffer store writes is narrowed with integer round to nearest even (`Gen.f16_bits`; #489, #711), not with `PackHalf2x16`. AMD drivers lower `PackHalf2x16` to `v_cvt_pkrtz_f16_f32`, which rounds toward zero (#489), and there about half of all unorm8, unorm16 and snorm8 values loaded with d16 came out 1 ulp low (123 of 256, 31,742 of 65,536 and 110 of 256). Packed MUBUF and MTBUF loads clamp unsigned 32-bit channels to 65535 before writing each half. On native gfx1036, values 65534 and 65535 survived, while 65536, 65537 and 0xffffffff all produced 0xffff, across all four load widths in wave32 and wave64. Packed `buffer_load_format_d16_x` and `_xyz` write only the low 16 bits of the final VGPR. Its upper half survives even when the load is out of bounds. Native gfx1036 wave32 and wave64 confirmed this with RGBA8_UINT and RGBA8_UNORM, two destination seeds, and both even-component loads as full-write controls. Full pairs are packed by `pack_f16_pair_int` and an odd final buffer component is narrowed with `f16_bits` for float/normalized formats. These memory conversions do not use `f16_pack2`: they come from the texture and buffer units, not the VALU whose rounding `MODE.FP_ROUND` sets (#753). Round to nearest even for these conversions is inferred, as in #489, not measured. #489's own narrower, `f32_to_f16_int`, was folded into `f16_bits` on 2026-11-22: the two gave the same bits on 30,648 inputs (every f32 exponent, ties, the subnormal and overflow edges, NaN), and `f16_bits` lost its one GLSL.std.450 instruction (`UMin`) so the packer stays free of them. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`, `test_buffer_format_f16_narrowing_avoids_packhalf2x16`), `tests/test_d16_pack.py` and `tests/semantic/test_buffer_load_format.py` (`D16NormalizedRounding`). | +| d16 and f16 format narrowing | The f16 of every d16 result (image samples and gathers, the `image_sample_c_lz` compare result, typed buffer loads) and of the f16 formats a typed buffer store writes is narrowed with integer round to nearest even (`Gen.f16_bits`; #489, #711), not with `PackHalf2x16`. AMD drivers lower `PackHalf2x16` to `v_cvt_pkrtz_f16_f32`, which rounds toward zero (#489), and there about half of all unorm8, unorm16 and snorm8 values loaded with d16 came out 1 ulp low (123 of 256, 31,742 of 65,536 and 110 of 256). Packed MUBUF and MTBUF loads clamp unsigned 32-bit channels to 65535 before writing each half. On native gfx1036, values 65534 and 65535 survived, while 65536, 65537 and 0xffffffff all produced 0xffff, across all four load widths in wave32 and wave64. Packed `buffer_load_format_d16_x` and `_xyz` write only the low 16 bits of the final VGPR. Its upper half survives even when the load is out of bounds. Native gfx1036 wave32 and wave64 confirmed this with RGBA8_UINT and RGBA8_UNORM, two destination seeds, and both even-component loads as full-write controls. Full pairs are packed by `pack_f16_pair_int` and an odd final buffer component is narrowed with `f16_bits` for float/normalized formats. These memory conversions do not use `f16_pack2`: they come from the texture and buffer units, not the VALU whose rounding `MODE.FP_ROUND` sets (#753). For typed buffer loads the rounding is measured (BUILD-161, `tools/d16_format_probe.py`). On an RX 6700 (gfx1031, AMD Windows driver 32.0.21045.29003), every UNORM8, SNORM8, UNORM10, UNORM16 and SNORM16 value was loaded through `buffer_load_format_d16_x` and `tbuffer_load_format_d16_x`, in wave32 and wave64. The hardware rounds the exact quotient once, straight to f16, to nearest even, with f16 denormals kept (65,536 of 65,536 UNORM16 and SNORM16 values). It does not round to f32 first: that double rounding is 1 ulp high on exactly four values (UNORM16 0xffaf and 0xffef, SNORM16 0x7ff7 and 0x8009). Over every width from 1 to 16 bits, only two f32 quotients land on an f16 halfway point: 0x3f7ff000 (16379/16383, 32759/32767, 65519/65535) and 0x3f7fb000 (65455/65535). `Gen.d16_norm_f16` takes the f16 below for those two, for normalized formats only; a 32_FLOAT 0x3f7ff000 is a real tie and still rounds to even. `buffer_load_format_x` without d16 returned the correctly rounded f32 quotient for all of them, the decode `norm_bits` builds. A 16_FLOAT d16 load returned its own bits for all 65,536 encodings. MUBUF and MTBUF agreed everywhere. For d16 image results, round to nearest even is still inferred, as in #489, not measured. #489's own narrower, `f32_to_f16_int`, was folded into `f16_bits` on 2026-11-22: the two gave the same bits on 30,648 inputs (every f32 exponent, ties, the subnormal and overflow edges, NaN), and `f16_bits` lost its one GLSL.std.450 instruction (`UMin`) so the packer stays free of them. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`, `test_buffer_format_f16_narrowing_avoids_packhalf2x16`), `tests/test_d16_pack.py` and `tests/semantic/test_buffer_load_format.py` (`D16NormalizedRounding`). | | Float-to-int saturation | `v_cvt_u32_f32` and `v_cvt_i32_f32` truncate toward zero, saturate out-of-range values (including infinities) to the destination bounds, and return zero for NaN. The conversion operand is kept in range before emitting SPIR-V `OpConvertFToU`/`OpConvertFToS`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf), §12.8, VOP1 opcodes 7 and 8. The synthetic `cs_cvt_f32_sat.asm` fixture is checked bit-for-bit by `tests/semantic/test_float_to_int.py`. | | `v_cvt_f16_u16`, `v_cvt_f16_i16`, `v_cvt_u16_f16`, `v_cvt_i16_f16` | Conversions of the low 16-bit half (`op_sel:[src,dst]` picks the high half of the source / of the destination in the VOP3 form); the other half of the destination is kept, like the other 16-bit-result ops (see *16-bit results*). `v_cvt_f16_u16` / `v_cvt_f16_i16` convert the unsigned / sign-extended half and narrow with the usual f16 rounding (65520 and above give +infinity for the unsigned form). `v_cvt_u16_f16` / `v_cvt_i16_f16` truncate toward zero, saturate to [0, 65535] / [-32768, 32767] (an f16 infinity too) and give 0 for NaN, as the 32-bit conversions do (*Float-to-int saturation*). `clamp` and the output multipliers are rejected as `Unsupported` rather than guessed. Source: the AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) pseudocode. **Not measured on hardware**: the kept half of the destination for the integer-result forms and the NaN result. Checked on the CPU by `tests/semantic/test_alu_cvt_16.py`; not run on the shader corpus. | | `v_frexp_mant_f32`, `v_frexp_exp_i32_f32`, `v_ldexp_f32` | Computed on the binary32 word, with no float arithmetic. A normal input has a biased exponent of 1..254. `v_frexp_mant_f32` returns the input with its exponent set to 126 (a mantissa in [0.5, 1), sign kept); `v_frexp_exp_i32_f32` returns the biased exponent minus 126, so mantissa × 2^exponent is the input. Zero and denormals (read as zero) give a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. `v_ldexp_f32` is S0 × 2^S1 with S1 a signed integer: S1 is clamped to [-512, 512] and added to the exponent field; a new field above 254 gives ±infinity, one of 0 or below gives ±0 (no denormal results), and zero, infinities and NaNs ignore S1. Neg/abs, `clamp` and the output multipliers apply as for other float ops (not to the integer exponent result). Source: the AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) pseudocode for these three opcodes. **Not measured on hardware**: the denormal input and result handling (the f32 denormal mode is not modelled) and the NaN payload are the translator's choice. Checked on the CPU by `tests/semantic/test_alu_frexp_ldexp.py`; not run on the shader corpus. | diff --git a/docs/shader_validation.md b/docs/shader_validation.md index d6399d74f3..4fac703b2c 100644 --- a/docs/shader_validation.md +++ b/docs/shader_validation.md @@ -932,6 +932,65 @@ reset in the kernel log. inputs is computed once and stored in its own half (`tests/test_f16_trans_sweep.py`). On a GPU the test checks exp2 of integers and wave32 = wave64. +### d16 rounding of UNORM/SNORM buffer loads (`tools/d16_format_probe.py`, BUILD-161) + +`docs/design.md` ("d16 and f16 format narrowing") narrows the f16 of a typed d16 buffer load the way it narrows an +image result: the exact binary32 decode, then integer round to nearest even (`Gen.f16_bits`). For buffer loads that +rounding was inferred, not measured. The probe measures it on a GFX10 GPU (RDNA1/RDNA2) through the hardware +oracle. Every value of UNORM8, SNORM8, UNORM10 (the x channel of format 50), UNORM16 and SNORM16 is loaded with +`buffer_load_format_d16_x`, `tbuffer_load_format_d16_x` and, for the f32 stage alone, `buffer_load_format_x`. Each +runs in wave32 and wave64. + +``` +python -I tools/d16_format_probe.py --json d16.json # about 1,040 kernels of 1,024 threads; exit 77 without the oracle +python -I tools/d16_format_probe.py --self-test # the rules against docs/design.md's #489 counts, no GPU +``` + +- **The kernels stage their own inputs.** Thread t stores the format bits of one value at dword t of the output + buffer and waits for the store (`s_waitcnt_vscnt`). It then builds a GFX10 V# over the buffer: DST_SEL XYZW, the + format, RESOURCE_LEVEL 1, OOB_SELECT 3, NUM_RECORDS the 4 KiB staged. It loads its element with `glc dlc` (past + L0 and GL1) and stores the VGPR at dword 1024 + t. The host checks that every staged word reads back as written. +- **Rules compared**, each also with f16 denormal results flushed: + - `f32_rte`, the translator's rule; + - `f32_rtz`, which is `v_cvt_pkrtz_f16_f32` of the f32 decode, the #489 bug; + - `rte` and `rtz`, which round the exact quotient once; + - `mul_rte`, the f32 product v · f32(1/(2^n − 1)) rounded to nearest even. +- **What the formats can separate.** The 8- and 10-bit formats only separate nearest from toward zero: every other rule + gives the same bits there. That covers 123 of the 256 UNORM8 values and 110 of the 256 SNORM8 values, the #489 + counts. Only four 16-bit values separate one rounding from two (`f32_rte` against `rte`): UNORM16 0xffaf and + 0xffef, SNORM16 0x7ff7 and 0x8009. The smallest UNORM16/SNORM16 values have quotients under 2^-14, so they show + a flush of f16 denormals. +- **Controls:** + - a 16_FLOAT d16 load must return its own bits (NaNs may be quieted); + - `d16_x` must leave the high half of its VGPR as it was (`docs/design.md` measured this on gfx1036); + - wave32 must equal wave64, and MUBUF must equal MTBUF. + + A failed control is exit 2; a wave or MUBUF/MTBUF difference is exit 1. Which rule the hardware follows is + reported, not judged. + +Measured on an RX 6700 (gfx1031, AMD Windows driver 32.0.21045.29003, ROCm wheel clang), the whole sweep in 36 s: + +| Format | Values | d16 `rte` | d16 `f32_rte` | d16 `f32_rtz` | f32 `f32_rte` | +| --- | --- | --- | --- | --- | --- | +| UNORM8 | 256 | 256 | 256 | 133 | 256 | +| SNORM8 | 256 | 256 | 256 | 146 | 256 | +| UNORM10 | 1,024 | 1,024 | 1,024 | 514 | 1,024 | +| UNORM16 | 65,536 | 65,536 | 65,534 | 33,796 | 65,536 | +| SNORM16 | 65,536 | 65,536 | 65,534 | 34,820 | 65,536 | + +- The d16 result is the exact quotient rounded once to f16, to nearest even, with f16 denormals kept. The two + UNORM16 and two SNORM16 values that separate one rounding from two all came out 1 ulp below the f32-first result: + 0xffaf gave 0x3bfd (not 0x3bfe), 0xffef gave 0x3bff (not 0x3c00), 0x7ff7 gave 0x3bff, and 0x8009 gave 0xbbff. + The translator now follows this (`Gen.d16_norm_f16`, `docs/design.md` "d16 and f16 format narrowing"). +- The f32 result (`buffer_load_format_x`) is the correctly rounded quotient for every value. The reciprocal multiply + matched only 130 of 256 UNORM8 values and 65,024 of 65,536 UNORM16 values. +- 16_FLOAT came back with its own bits for all 65,536 encodings, NaNs included. The high half of the d16_x VGPR was + kept. MUBUF matched MTBUF, and wave32 matched wave64, for every value. + +`tests/test_d16_format_probe.py` checks the rules against the #489 counts and the descriptor bits. It checks that +each value is staged once, and that the kernels assemble for gfx1031. A fake oracle plays the GPU to check the exit +codes. On a GFX10 GPU the test runs UNORM8 and checks the controls. + ### `v_fma_mix*` f16 rounding in nearest mode (`tools/fma_mix_probe.py`) `docs/design.md` leaves one f16 question open. In round-to-nearest mode, does `v_fma_mixlo_f16` / `v_fma_mixhi_f16` diff --git a/tests/semantic/test_buffer_load_format.py b/tests/semantic/test_buffer_load_format.py index c5cf73a70c..30f32bb318 100644 --- a/tests/semantic/test_buffer_load_format.py +++ b/tests/semantic/test_buffer_load_format.py @@ -33,6 +33,7 @@ # V# FORMAT codes (word3 bits 12-18), from rdna2spirv.FORMATS FMT_U32, FMT_U32X2, FMT_U32X4, FMT_UINT8X4, FMT_UINT16X2, FMT_UINT16X4, FMT_F16 = 20, 62, 75, 60, 27, 69, 13 FMT_F32, FMT_F32X2, FMT_F32X3, FMT_UNORM8, FMT_UNORM8X4 = 22, 64, 74, 1, 56 +FMT_UNORM16, FMT_SNORM16, FMT_UNORM16X2 = 7, 8, 23 DST_SEL_XYZW = 4 | 5 << 3 | 6 << 6 | 7 << 9 # DST_SEL (X, 0, 1, 1): code 4, 0, 1, 1 — SHADER-86 measures float 1.0 vs integer 1 DST_SEL_X_0_1_1 = 4 | 0 << 3 | 1 << 6 | 1 << 9 @@ -150,9 +151,9 @@ def test_odd_and_even_component_writes(self): class D16NormalizedRounding(unittest.TestCase): - """d16 narrows a normalized value to f16 with round to nearest even, like the d16 image results (#489; inferred - for the hardware, not measured). These bytes are among the about half of unorm8 values where round toward zero, - which PackHalf2x16 becomes on AMD drivers, gives 1 ulp less.""" + """d16 narrows a normalized value to f16 with round to nearest even (#489; measured for typed buffer loads on an + RX 6700, BUILD-161). These bytes are among the about half of unorm8 values where round toward zero, which + PackHalf2x16 becomes on AMD drivers, gives 1 ulp less.""" def test_unorm8_x(self): # byte 5 is 0xbe: 190/255 is 0x39f6 to nearest even, 0x39f5 toward zero @@ -163,6 +164,40 @@ def test_unorm8x4_xyzw(self): self.assertEqual(load_format(FMT_UNORM8X4, 4, 4, d16=True)[:2], (0x39F63B7F, 0x3AF7396D)) +class D16NormalizedRoundsOnce(unittest.TestCase): + """BUILD-161, measured on an RX 6700 (gfx1031) with tools/d16_format_probe.py: d16 rounds the exact UNORM/SNORM + quotient once, straight to f16. The f32 decode followed by f16_bits rounds twice, which is 1 ulp high where the + f32 lands exactly on an f16 halfway point: UNORM16 0xffaf and 0xffef, SNORM16 0x7ff7 and 0x8009.""" + + def d16_x(self, fmt, half, op="buffer_load_format", mods=""): + return load_format(fmt, 0, 1, memory={BASE: half}, d16=True, op=op, mods=mods)[0] + + def test_unorm16_and_snorm16_halfway_values(self): + for fmt, half, want in ((FMT_UNORM16, 0xFFEF, 0x3BFF), (FMT_UNORM16, 0xFFAF, 0x3BFD), + (FMT_SNORM16, 0x7FF7, 0x3BFF), (FMT_SNORM16, 0x8009, 0xBBFF)): + with self.subTest(fmt=fmt, half=hex(half)): + self.assertEqual(self.d16_x(fmt, half), 0x12340000 | want) + + def test_mtbuf_takes_the_same_rule(self): + self.assertEqual(self.d16_x(FMT_UNORM16, 0xFFEF, "tbuffer_load_format", " format:[BUF_FMT_16_UNORM]"), + 0x12343BFF) + self.assertEqual(self.d16_x(FMT_SNORM16, 0x8009, "tbuffer_load_format", " format:[BUF_FMT_16_SNORM]"), + 0x1234BBFF) + + def test_neighbours_and_the_f32_result_are_unchanged(self): + self.assertEqual(self.d16_x(FMT_UNORM16, 0xFFEE), 0x12343BFF) # 65518/65535: not a halfway f32 + self.assertEqual(self.d16_x(FMT_UNORM16, 0xFFFF), 0x12343C00) + self.assertEqual(load_format(FMT_UNORM16, 0, 1, memory={BASE: 0xFFEF})[0], 0x3F7FF000) + + def test_a_float_format_on_the_halfway_value_still_ties_to_even(self): + self.assertEqual(self.d16_x(FMT_F32, 0x3F7FF000), 0x12343C00) + self.assertEqual(self.d16_x(FMT_F32, 0xBF7FB000), 0x1234BBFE) + + def test_both_halves_of_a_pair(self): + got = load_format(FMT_UNORM16X2, 0, 2, memory={BASE: 0xFFAF << 16 | 0xFFEF}, d16=True)[0] + self.assertEqual(got, 0x3BFD3BFF) + + class CrossingDwordBoundary(unittest.TestCase): """An element that starts mid-dword must read the following dwords, not re-read dword 0. diff --git a/tests/test_d16_format_probe.py b/tests/test_d16_format_probe.py new file mode 100644 index 0000000000..320116d6dc --- /dev/null +++ b/tests/test_d16_format_probe.py @@ -0,0 +1,222 @@ +"""tools/d16_format_probe.py: the candidate rules, the GFX10 descriptor, what each kernel stages and loads, the +comparison and its exit codes (through a fake oracle that plays the GPU), and the exit-77 contract. The last class +runs on the hardware when the oracle tools are present and the GPU is GFX10, and is skipped otherwise. Standard +library only.""" +import io +import json +import os +from contextlib import redirect_stdout +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +TOOLS = Path(__file__).resolve().parents[1] / "tools" +sys.path.insert(0, str(TOOLS)) +import d16_format_probe as pr # noqa: E402 +from hw_oracle import asm, runner # noqa: E402 + + +class Rules(unittest.TestCase): + def test_self_test(self): + with redirect_stdout(io.StringIO()): + self.assertEqual(pr.self_test(), 0) + + def test_the_489_counts_in_docs_design(self): + # docs/design.md ("d16 and f16 format narrowing"): with RTZ narrowing 123 of 256 UNORM8, 31,742 of 65,536 + # UNORM16 and 110 of 256 SNORM8 values came out 1 ulp low + self.assertEqual(pr.rte_rtz_disagreements("unorm", 8), 123) + self.assertEqual(pr.rte_rtz_disagreements("snorm", 8), 110) + self.assertEqual(pr.rte_rtz_disagreements("unorm", 16), 31742) + + def test_only_four_16_bit_values_separate_one_rounding_from_two(self): + split = {(k, v) for k in ("unorm", "snorm") for v in range(65536) + if pr.models16(k, 16, v)["rte"] != pr.models16(k, 16, v)["f32_rte"]} + self.assertEqual(split, {("unorm", 0xFFAF), ("unorm", 0xFFEF), ("snorm", 0x7FF7), ("snorm", 0x8009)}) + + def test_8_and_10_bit_formats_only_tell_rte_from_rtz(self): + for kind, n in (("unorm", 8), ("snorm", 8), ("unorm", 10)): + for v in range(1 << n): + m = pr.models16(kind, n, v) + self.assertEqual(len({m["f32_rte"], m["rte"], m["mul_rte"], m["f32_rte_flush"]}), 1, (kind, v)) + + def test_snorm_minimum_is_minus_one_and_f32_decode_is_exact(self): + self.assertEqual(pr.models16("snorm", 8, 0x80)["f32_rte"], 0xBC00) + self.assertEqual(pr.models16("snorm", 8, 0x81)["f32_rte"], 0xBC00) + self.assertEqual(pr.models32("unorm", 16, 0xFFFF)["f32_rte"], 0x3F800000) + self.assertEqual(pr.models32("unorm", 8, 0x80)["f32_rte"], 0x3F008081) # 128 / 255 + + +class Kernels(unittest.TestCase): + def test_descriptor_word3(self): + w = pr.descriptor_word3(8) + self.assertEqual([w & 7, w >> 3 & 7, w >> 6 & 7, w >> 9 & 7], [4, 5, 6, 7]) + self.assertEqual((w >> 12 & 0x7F, w >> 24 & 1, w >> 28 & 3, w >> 30), (8, 1, 3, 0)) + + def test_every_value_is_staged_once(self): + for fmt, (_, _, n) in pr.FORMATS.items(): + seen = [] + for inst, base in pr.jobs(fmt): + if inst != "buffer_d16": + continue + self.assertEqual(pr.kernel_lines(inst, fmt, base)[0], f"v_add_nc_u32 v1, 0x{base:x}, v0") + seen += [(base + t) & ((1 << n) - 1) for t in range(min(pr.THREADS, (1 << n) - base))] + self.assertEqual(seen, list(range(1 << n)), fmt) + + def test_mtbuf_names_the_format_and_mubuf_takes_it_from_the_descriptor(self): + lines = pr.kernel_lines("tbuffer_d16", "snorm16", 0) + self.assertIn("format:8 offen glc dlc", lines[10]) + self.assertTrue(pr.kernel_lines("buffer_d16", "snorm16", 0)[10].startswith("buffer_load_format_d16_x")) + self.assertIn(f"s_mov_b32 s11, 0x{pr.descriptor_word3(8):x}", lines) + + def test_kernels_assemble_for_rdna2(self): + try: + clang = runner.find_clang() + except runner.Unavailable as e: + self.skipTest(str(e)) + kernels = [asm.Kernel(pr.kernel_lines(inst, fmt, 0), 32, pr.THREADS, pr.WORDS, raw=True, vgprs=8, sgprs=16) + for fmt in pr.FORMATS for inst in pr.INSTS] + text, names, _ = asm.module_text(kernels, "gfx1031", wave=32) + with tempfile.TemporaryDirectory() as d: + s = Path(d) / "k.s" + s.write_text(text, encoding="utf-8") + r = subprocess.run([clang, "--target=amdgcn-amd-amdhsa", "-mcpu=gfx1031", "-c", str(s), "-o", + str(Path(d) / "k.o")], capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stderr[:800]) + self.assertIn("global_store_dword v4, v3, s[2:3]", text) + self.assertIn("s_waitcnt_vscnt null, 0x0", text) + + +class FakeOracle: + """Plays the GPU: reads each kernel's base, format code and load, and answers with a rule's bits.""" + arch = "gfx1031" + device = "fake gfx1031" + + def __init__(self, rule="rte", clobber_hi=False, wave64_off=None): + self.rule, self.clobber_hi, self.wave64_off = rule, clobber_hi, wave64_off + + def run(self, kernels, words=4): + code_of = {c: (f, k, n) for f, (c, k, n) in pr.FORMATS.items()} + out = [] + for k in kernels: + base = int(re.search(r"0x([0-9a-f]+)", k.lines[0]).group(1), 16) + w3 = int(next(ln for ln in k.lines if ln.startswith("s_mov_b32 s11")).split("0x")[1], 16) + fmt, kind, n = code_of[w3 >> 12 & 0x7F] + load = k.lines[10] + staged = [(base + t) & ((1 << n) - 1) for t in range(pr.THREADS)] + res = [] + for v in staged: + if kind == "f16": + bits = v + elif load.startswith("buffer_load_format_x"): + res.append(pr.models32(kind, n, v)["f32_rte"]) + continue + else: + bits = pr.models16(kind, n, v)[self.rule] + if self.wave64_off is not None and k.wave == 64 and v == self.wave64_off: + bits ^= 1 + hi = 0 if self.clobber_hi else pr.HI_SEED + res.append(hi | bits) + out.append(staged + res) + return out + + def close(self): + pass + + +def run_main(oracle, *args): + buf = io.StringIO() + with mock.patch.object(runner, "open_oracle", return_value=oracle), redirect_stdout(buf): + rc = pr.main(["--formats", "unorm8,float16", *args]) + return rc, buf.getvalue() + + +class Compare(unittest.TestCase): + def test_the_translators_rule_matches_everywhere(self): + rc, out = run_main(FakeOracle()) + self.assertEqual(rc, 0, out) + self.assertIn("off the rule 0", out) + self.assertIn("own bits 65536/65536", out) + + def test_double_rounding_hardware_shows_the_four_halfway_values(self): + buf = io.StringIO() + with mock.patch.object(runner, "open_oracle", return_value=FakeOracle("f32_rte")), redirect_stdout(buf): + rc = pr.main(["--formats", "unorm16,snorm16", "--waves", "32"]) + self.assertEqual(rc, 0, buf.getvalue()) + self.assertEqual(buf.getvalue().count("off the rule 2"), 4) # MUBUF and MTBUF, two formats + self.assertIn("value 0xffef: hw 0x3c00, rule 0x3bff", buf.getvalue()) + + def test_rtz_hardware_is_a_finding_not_a_failure(self): + with tempfile.TemporaryDirectory() as d: + j = os.path.join(d, "r.json") + rc, out = run_main(FakeOracle("f32_rtz"), "--json", j) + with open(j, encoding="utf-8") as f: + rep = json.load(f) + self.assertEqual(rc, 0, out) + d16 = rep["formats"]["unorm8"]["insts"]["buffer_d16"] + self.assertEqual(d16["off_rule"], 123) + self.assertEqual(d16["match"]["f32_rtz"], 256) + self.assertIn("f32_rtz", d16["first_off"][0]["fits"]) + + def test_a_wave_difference_exits_1(self): + rc, out = run_main(FakeOracle(wave64_off=9)) + self.assertEqual(rc, 1, out) + + def test_a_clobbered_high_half_is_a_harness_error(self): + rc, out = run_main(FakeOracle(clobber_hi=True)) + self.assertEqual(rc, 2, out) + self.assertIn("high half", out) + + def test_not_gfx10_exits_77(self): + o = FakeOracle() + o.arch = "gfx1150" + rc, out = run_main(o) + self.assertEqual(rc, 77, out) + + +class Cli(unittest.TestCase): + def test_exits_77_without_the_tools(self): + env = dict(os.environ, LEONIDA_AMD_CLANG=str(TOOLS / "no-such-clang.exe"), LEONIDA_HW_DRM_NODE="") + r = subprocess.run([sys.executable, "-I", str(TOOLS / "d16_format_probe.py"), "--formats", "unorm8"], + capture_output=True, text=True, env=env) + self.assertEqual(r.returncode, 77, r.stdout + r.stderr) + self.assertIn("unavailable", r.stdout) + + def test_unknown_format_is_a_usage_error(self): + r = subprocess.run([sys.executable, "-I", str(TOOLS / "d16_format_probe.py"), "--formats", "unorm12"], + capture_output=True, text=True) + self.assertEqual(r.returncode, 2) + self.assertIn("unorm12", r.stderr) + + +class OnHardware(unittest.TestCase): + @classmethod + def setUpClass(cls): + try: + cls.oracle = runner.open_oracle() + except runner.Unavailable as e: + raise unittest.SkipTest(f"hardware oracle unavailable: {e}") from None + if asm.family(cls.oracle.arch) != "gfx10": + cls.oracle.close() + raise unittest.SkipTest(f"{cls.oracle.arch} is not GFX10") + + @classmethod + def tearDownClass(cls): + cls.oracle.close() + + def test_unorm8_controls_hold_and_both_wave_sizes_agree(self): + w32 = pr.sweep(self.oracle, "unorm8", 32) + w64 = pr.sweep(self.oracle, "unorm8", 64) + self.assertEqual(w32, w64) + res = pr.classify("unorm8", w32) + self.assertEqual(res["control"], []) + self.assertEqual(w32["buffer_d16"][255] & 0xFFFF, 0x3C00) + self.assertEqual(w32["buffer_d16"][0] & 0xFFFF, 0) + self.assertEqual(w32["buffer_f32"][255], 0x3F800000) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/d16_format_probe.py b/tools/d16_format_probe.py new file mode 100644 index 0000000000..402e0de7d6 --- /dev/null +++ b/tools/d16_format_probe.py @@ -0,0 +1,341 @@ +r"""How an RDNA2 GPU rounds UNORM/SNORM buffer loads to f16 with d16 (BUILD-161). Standard library only. + +docs/design.md ("d16 and f16 format narrowing") narrows every d16 result with integer round to nearest even, but +for typed buffer loads that rounding was inferred (#489, #711), not measured. This sweep measures it: every value of +each format below goes through buffer_load_format_d16_x and tbuffer_load_format_d16_x natively on the GPU (through +tools/hw_oracle/), in wave32 and wave64. Every result is compared with several candidate rules computed from the +exact quotient (Fraction arithmetic): + + f32_rte x / (2^n - 1) (SNORM: max(s / (2^(n-1) - 1), -1)) rounded to f32 (nearest even), then to f16 + nearest even: the translator's rule before BUILD-161 (the exact binary32 decode, then Gen.f16_bits) + f32_rtz rounded to f32, then to f16 toward zero (v_cvt_pkrtz_f16_f32 of the f32 value; PackHalf2x16 on AMD + drivers, the #489 bug) + rte the exact quotient rounded once to f16, nearest even (no f32 step): what an RX 6700 does, and the + translator's rule since BUILD-161 (Gen.d16_norm_f16) + rtz the exact quotient rounded once to f16, toward zero + mul_rte the f32 product v * f32(1 / (2^n - 1)) (a reciprocal multiply, not a division), then f16 nearest even + +and each rule again with f16 denormal results flushed to zero (UNORM16 and SNORM16 have quotients under 2^-14). +Only the 16-bit formats tell the f32 step apart: rte and f32_rte differ on UNORM16 0xffaf and 0xffef and on SNORM16 +0x7ff7 and 0x8009, and a flush shows on the smallest UNORM16 / SNORM16 values. On UNORM8, SNORM8 and UNORM10 every +rule but the rtz ones gives the same bits. +buffer_load_format_x (an f32 result, no d16) runs on the same values against the f32 rules, so the two stages can be +told apart. Controls that must hold for the sweep to count: every staged input word reads back as written, a +16_FLOAT d16 load returns its own bits, and d16_x leaves the high half of its VGPR as it was. + +The kernels write their own inputs: thread t stores the format's bits for value base + t at dword t of the output +buffer, waits for the store, builds a GFX10 buffer descriptor (V#) over that buffer and loads its element with glc dlc +(past the L0 and GL1 caches), then stores the loaded VGPR at dword 1024 + t. GFX10 only (RDNA1 and RDNA2: the +V# layout, RESOURCE_LEVEL = 1), which is what BUILD-161 asks for; another architecture exits 77. + +Usage: + python -I tools/d16_format_probe.py [--formats unorm8,snorm16] [--waves 32,64] [--json out.json] + python -I tools/d16_format_probe.py --self-test # the models against known counts, no GPU + +Exit 0 when the sweep ran (which rule the hardware follows is a finding, not a failure), 1 when wave32 and wave64 +or MUBUF and MTBUF disagree, 2 on a harness error (a control failed, a kernel without its words), 77 when the +hardware oracle is unavailable or the GPU is not GFX10. Nothing here reads game files. +""" +import argparse +import json +import os +import struct +import sys +from fractions import Fraction + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.dont_write_bytecode = True +if HERE not in sys.path: + sys.path.insert(0, HERE) + +# name: (GFX10 unified buffer format code, kind, bits of the x channel). The codes are the translator's FORMATS +# table (tools/rdna2spirv.py); 10_10_10_2 (50) holds x in its low 10 bits. +FORMATS = { + "unorm8": (1, "unorm", 8), + "snorm8": (2, "snorm", 8), + "unorm16": (7, "unorm", 16), + "snorm16": (8, "snorm", 16), + "unorm10": (50, "unorm", 10), + "float16": (13, "f16", 16), # control: d16 of an f16 element is its own bits +} +INSTS = ("buffer_d16", "tbuffer_d16", "buffer_f32") +THREADS = 1024 +WORDS = 2 * THREADS +HI_SEED = 0xBEEF0000 # the d16_x destination starts as this | 0x1234; the high half must stay +LO_SEED = 0x1234 +RULES16 = ("f32_rte", "f32_rtz", "rte", "rtz", "mul_rte") +RULES32 = ("f32_rte", "f32_rtz", "mul_f32") + + +# ---- exact arithmetic ---- + +def round_frac(x, prec, emin, rtz=False): + """x rounded to a binary float with prec significand bits (implicit bit included) and minimum normal exponent + emin, denormals kept; nearest even, or toward zero. No overflow: every value here is in [-1, 1].""" + if x == 0: + return Fraction(0) + sign = -1 if x < 0 else 1 + a = abs(x) + e = a.numerator.bit_length() - a.denominator.bit_length() + if Fraction(2) ** e > a: + e -= 1 + if Fraction(2) ** (e + 1) <= a: + e += 1 + ulp = Fraction(2) ** (max(e, emin) - prec + 1) + q = a / ulp + n = q.numerator // q.denominator if rtz else round(q) # round() of a Fraction is half to even + return sign * n * ulp + + +def f16_bits(v): + return struct.unpack("> (n - 1) else v + return max(Fraction(s, (1 << (n - 1)) - 1), Fraction(-1)) + + +def is_denorm16(h): + return (h & 0x7C00) == 0 and (h & 0x3FF) != 0 + + +def models16(kind, n, v): + """{rule: f16 bits} for one input, plus each rule with a denormal result flushed (rule + '_flush').""" + x = quotient(kind, n, v) + rcp = to_f32(Fraction(1, (1 << n) - 1) if kind == "unorm" else Fraction(1, (1 << (n - 1)) - 1)) + s = (v - (1 << n) if v >> (n - 1) else v) if kind == "snorm" else v + prod = max(to_f32(s * rcp), Fraction(-1)) + out = {"rte": f16_bits(to_f16(x)), "rtz": f16_bits(to_f16(x, True)), "f32_rte": f16_bits(to_f16(to_f32(x))), + "f32_rtz": f16_bits(to_f16(to_f32(x), True)), "mul_rte": f16_bits(to_f16(prod))} + for r in RULES16: + out[r + "_flush"] = (out[r] & 0x8000) if is_denorm16(out[r]) else out[r] + return out + + +def models32(kind, n, v): + x = quotient(kind, n, v) + rcp = to_f32(Fraction(1, (1 << n) - 1) if kind == "unorm" else Fraction(1, (1 << (n - 1)) - 1)) + s = (v - (1 << n) if v >> (n - 1) else v) if kind == "snorm" else v + return {"f32_rte": f32_bits(to_f32(x)), "f32_rtz": f32_bits(to_f32(x, True)), + "mul_f32": f32_bits(max(to_f32(s * rcp), Fraction(-1)))} + + +# ---- kernels ---- + +def descriptor_word3(code): + """GFX10 V# dword 3: DST_SEL x/y/z/w = X/Y/Z/W (4, 5, 6, 7), FORMAT [18:12], RESOURCE_LEVEL [24] = 1, + OOB_SELECT [29:28] = 3 (raw: in bounds while offset < NUM_RECORDS), TYPE [31:30] = 0 (buffer).""" + return 4 | 5 << 3 | 6 << 6 | 7 << 9 | code << 12 | 1 << 24 | 3 << 28 + + +def kernel_lines(inst, fmt, base): + """Thread t: stage format bits (base + t) & mask at dword t, load the element, store the VGPR at dword 1024 + t.""" + code, kind, n = FORMATS[fmt] + mask = (1 << n) - 1 + load = {"buffer_d16": "buffer_load_format_d16_x v3, v2, s[8:11], 0 offen glc dlc", + "tbuffer_d16": f"tbuffer_load_format_d16_x v3, v2, s[8:11], 0 format:{code} offen glc dlc", + "buffer_f32": "buffer_load_format_x v3, v2, s[8:11], 0 offen glc dlc"}[inst] + return [ + f"v_add_nc_u32 v1, 0x{base:x}, v0", + f"v_and_b32 v1, 0x{mask:x}, v1", + "v_lshlrev_b32 v2, 2, v0", + "global_store_b32 v2, v1, s[2:3]", + "s_waitcnt_vscnt null, 0x0", + "s_mov_b32 s8, s2", + "s_and_b32 s9, s3, 0xffff", # BASE_ADDRESS[47:32]; STRIDE 0, no swizzle + f"s_mov_b32 s10, 0x{4 * THREADS:x}", # NUM_RECORDS: the staged inputs, in bytes + f"s_mov_b32 s11, 0x{descriptor_word3(code):x}", + f"v_mov_b32 v3, 0x{HI_SEED | LO_SEED:x}", + load, + "s_waitcnt vmcnt(0)", + f"v_add_nc_u32 v4, 0x{4 * THREADS:x}, v2", + "global_store_b32 v4, v3, s[2:3]", + "s_endpgm", + ] + + +def jobs(fmt): + """(inst, base) for every kernel a format needs: one per 1024 values.""" + n = FORMATS[fmt][2] + insts = ("buffer_d16", "tbuffer_d16") if FORMATS[fmt][1] == "f16" else INSTS + return [(inst, base) for inst in insts for base in range(0, 1 << n, THREADS)] + + +def sweep(oracle, fmt, wave): + """{inst: [loaded VGPR word per value]} for every value of the format, or raise RuntimeError.""" + from hw_oracle import asm + n = FORMATS[fmt][2] + todo = jobs(fmt) + kernels = [asm.Kernel(kernel_lines(inst, fmt, base), wave, THREADS, WORDS, raw=True, vgprs=8, sgprs=16) + for inst, base in todo] + got = oracle.run(kernels, words=WORDS) + out = {} + for (inst, base), words in zip(todo, got): + if isinstance(words, str) or len(words) != WORDS: + raise RuntimeError(f"{fmt} {inst} wave{wave} base {base}: " + f"{words if isinstance(words, str) else f'{len(words)} words'}") + count = min(THREADS, (1 << n) - base) + staged = words[:count] + want = [(base + t) & ((1 << n) - 1) for t in range(count)] + if staged != want: + bad = next(t for t in range(count) if staged[t] != want[t]) + raise RuntimeError(f"{fmt} {inst} wave{wave}: staged input {want[bad]:#x} read back as {staged[bad]:#x}") + out.setdefault(inst, []).extend(words[THREADS:THREADS + count]) + return out + + +# ---- comparison ---- + +def classify(fmt, hw): + """Counts of inputs each rule predicts exactly, the inputs where the translator's rule (rte for d16, f32_rte for f32) is wrong, and the + control failures. hw: {inst: [VGPR word per value]}.""" + _, kind, n = FORMATS[fmt] + res = {"inputs": 1 << n, "insts": {}, "control": []} + for inst, words in hw.items(): + d16 = inst.endswith("d16") + if d16: + hi_bad = [v for v, w in enumerate(words) if w >> 16 != HI_SEED >> 16] + if hi_bad: + res["control"].append(f"{inst}: d16_x changed the high half for {len(hi_bad)} values " + f"(first {hi_bad[0]:#x}: {words[hi_bad[0]]:#010x})") + if kind == "f16": + wrong = [v for v, w in enumerate(words) if (w & 0xFFFF) != v and not ( + (v & 0x7C00) == 0x7C00 and v & 0x3FF and (w & 0x7C00) == 0x7C00 and w & 0x3FF)] + if wrong: + res["control"].append(f"{inst}: 16_FLOAT came back changed for {len(wrong)} values " + f"(first {wrong[0]:#06x} -> {words[wrong[0]] & 0xFFFF:#06x})") + res["insts"][inst] = {"own_bits": (1 << n) - len(wrong)} + continue + rules = (tuple(RULES16) + tuple(r + "_flush" for r in RULES16)) if d16 else RULES32 + match = dict.fromkeys(rules, 0) + off = [] + for v, w in enumerate(words): + got = w & 0xFFFF if d16 else w + m = models16(kind, n, v) if d16 else models32(kind, n, v) + for r in rules: + match[r] += got == m[r] + rule = "rte" if d16 else "f32_rte" # the translator's rule (Gen.d16_norm_f16, norm_bits) + if got != m[rule]: + off.append((v, got, m[rule], m)) + res["insts"][inst] = {"match": match, "off_rule": len(off), + "first_off": [{"value": f"{v:#x}", "hw": f"{g:#x}", "rule": f"{r:#x}", + "fits": [k for k in rules if m[k] == g]} for v, g, r, m in off[:8]]} + return res + + +def rte_rtz_disagreements(kind, n): + """How many inputs the translator's rule and the #489 bug (f32 then RTZ) narrow differently (docs/design.md: + 123 of 256 UNORM8 and 110 of 256 SNORM8 loaded 1 ulp low).""" + return sum(models16(kind, n, v)["f32_rte"] != models16(kind, n, v)["f32_rtz"] for v in range(1 << n)) + + +def self_test(): + assert round_frac(Fraction(1, 3), 11, -14) == Fraction(1365, 4096) # 0x3555 + assert f16_bits(to_f16(Fraction(1, 255))) == 0x1C04 # 2^-8 * 1.00390625 + assert f16_bits(to_f16(Fraction(9, 255))) == 0x2885 and f16_bits(to_f16(Fraction(9, 255), True)) == 0x2884 + assert f16_bits(to_f16(Fraction(1, 65535))) == 0x0100 and is_denorm16(0x0100) # under 2^-14 + assert f16_bits(to_f16(Fraction(1, 2) + Fraction(1, 4096))) == 0x3800 # a tie: to even + assert quotient("snorm", 8, 0x80) == -1 and quotient("snorm", 8, 0x81) == -1 and quotient("snorm", 8, 0x7F) == 1 + assert models16("unorm", 8, 255)["rte"] == 0x3C00 and models16("snorm", 16, 0x8000)["rte"] == 0xBC00 + assert models32("unorm", 8, 1)["f32_rte"] == 0x3B808081 # 1/255 in f32 + assert models16("unorm", 16, 1)["f32_rte_flush"] == 0 + assert models16("unorm", 16, 0xFFEF)["rte"] == 0x3BFF and models16("unorm", 16, 0xFFEF)["f32_rte"] == 0x3C00 + assert models16("snorm", 16, 0x8009)["rte"] == 0xBBFF and models16("snorm", 16, 0x8009)["f32_rte"] == 0xBC00 + assert rte_rtz_disagreements("unorm", 8) == 123 + assert rte_rtz_disagreements("snorm", 8) == 110 + w3 = descriptor_word3(7) + assert w3 & 0xFFF == 0xFAC and (w3 >> 12) & 0x7F == 7 and (w3 >> 24) & 1 and (w3 >> 28) & 3 == 3 + lines = kernel_lines("tbuffer_d16", "unorm16", 0x400) + assert lines[0] == "v_add_nc_u32 v1, 0x400, v0" and "format:7 offen glc dlc" in lines[10] + assert len(jobs("unorm16")) == 3 * 64 and len(jobs("unorm8")) == 3 and len(jobs("float16")) == 2 * 64 + print("self-test ok") + return 0 + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--formats", default=",".join(FORMATS)) + ap.add_argument("--waves", default="32,64") + ap.add_argument("--json", help="write the counts and the first differences here") + ap.add_argument("--hw-arch") + ap.add_argument("--self-test", action="store_true") + a = ap.parse_args(argv) + if a.self_test: + return self_test() + fmts = [f for f in a.formats.split(",") if f] + waves = [int(w) for w in a.waves.split(",") if w.strip().isdigit()] + bad = [f for f in fmts if f not in FORMATS] + [w for w in a.waves.split(",") if w and w not in ("32", "64")] + if bad or not fmts or not waves: + ap.error("unknown or empty: " + ", ".join(bad or ["--formats/--waves"])) + from hw_oracle import asm, runner + try: + oracle = runner.open_oracle(arch=a.hw_arch) + except runner.Unavailable as e: + print(f"hardware oracle unavailable: {e}") + return 77 + try: + if asm.family(oracle.arch) != "gfx10": + print(f"hardware oracle unavailable: {oracle.arch} is not GFX10; the descriptor here is GFX10's (RDNA2)") + return 77 + print(f"hardware oracle: {oracle.device}") + report = {"device": str(oracle.device), "arch": oracle.arch, "formats": {}} + rc = 0 + for fmt in fmts: + hw = {w: sweep(oracle, fmt, w) for w in waves} + first = hw[waves[0]] + entry = classify(fmt, first) + entry["waves_differ"] = {inst: sum(a_ != b_ for a_, b_ in zip(first[inst], hw[w][inst])) + for w in waves[1:] for inst in first} + if "tbuffer_d16" in first: + entry["mubuf_mtbuf_differ"] = sum((x ^ y) & 0xFFFF != 0 + for x, y in zip(first["buffer_d16"], first["tbuffer_d16"])) + report["formats"][fmt] = entry + if entry["control"]: + for c in entry["control"]: + print(f"harness error: {fmt} {c}") + rc = 2 + if any(entry["waves_differ"].values()) or entry.get("mubuf_mtbuf_differ"): + rc = max(rc, 1) if rc != 2 else 2 + print(f"{fmt} ({entry['inputs']} values): wave32/64 differ {entry['waves_differ'] or 'n/a'}; " + f"MUBUF/MTBUF d16 differ {entry.get('mubuf_mtbuf_differ', 'n/a')}") + for inst, s in entry["insts"].items(): + if "own_bits" in s: + print(f" {inst}: own bits {s['own_bits']}/{entry['inputs']}") + continue + print(f" {inst}: " + ", ".join(f"{r} {k}" for r, k in s["match"].items()) + + f"; off the rule {s['off_rule']}") + for o in s["first_off"][:3]: + print(f" value {o['value']}: hw {o['hw']}, rule {o['rule']}, fits {','.join(o['fits']) or '-'}") + except RuntimeError as e: + print(f"harness error: {e}") + return 2 + finally: + oracle.close() + if a.json: + with open(a.json, "w", encoding="utf-8") as f: + json.dump(report, f, indent=1) + return rc + + +if __name__ == "__main__": + try: + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 26d8ff9d19..72216853e7 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -1771,6 +1771,13 @@ def buffer_load_format(self, op, a, mods, fixed_fmt=None): self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}") self.emit(f"{o} = OpLogicalOr %bool {is_int} {e}") is_int = o + is_norm = "%false" + for code_v, (_, kind, _) in self.FORMATS.items(): + if kind in ("unorm", "snorm") and (fixed_fmt is None or code_v == fixed_fmt): + e, o = self.tmp(), self.tmp() + self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}") + self.emit(f"{o} = OpLogicalOr %bool {is_norm} {e}") + is_norm = o for i in range(0, len(outs), 2): dest = {"k": "vgpr", "r": vd["r"] + i // 2, "n": 1} lo = outs[i] @@ -1778,12 +1785,15 @@ def buffer_load_format(self, op, a, mods, fixed_fmt=None): r = self.tmp() if i + 1 == len(outs): # For d16_x and d16_xyz the unaddressed high half keeps its previous bits. - fl = self.f16_bits(self.tof(lo)) + fl = self.d16_norm_f16(lo, is_norm) self.emit(f"{r} = OpSelect %uint {is_int} {il} {fl}") self.write_lo16(dest, r) continue hi = outs[i + 1] - ph = self.pack_f16_pair_int(self.tof(lo), self.tof(hi)) + ph = self.tmp() + fh_s = self.tmp() + self.emit(f"{fh_s} = OpShiftLeftLogical %uint {self.d16_norm_f16(hi, is_norm)} {self.cu(16)}") + self.emit(f"{ph} = OpBitwiseOr %uint {self.d16_norm_f16(lo, is_norm)} {fh_s}") ih, pi = self.tmp(), self.tmp() high_half = self.saturate_int16(hi, signed=False) self.emit(f"{ih} = OpShiftLeftLogical %uint {high_half} {self.cu(16)}") @@ -1791,6 +1801,30 @@ def buffer_load_format(self, op, a, mods, fixed_fmt=None): self.emit(f"{r} = OpSelect %uint {is_int} {pi} {ph}") self.dst(dest, r) + # The f32 quotients m / (2^n - 1), 1 <= n <= 16, that land exactly on an f16 halfway point: 0x3f7ff000 is + # 16379/16383, 32759/32767 and 65519/65535, 0x3f7fb000 is 65455/65535 (an enumeration of every m and n). The exact + # quotient is below the halfway point each time, and RDNA2 rounds it once, straight to f16 (BUILD-161, RX 6700). + D16_NORM_HALFWAY = (0x3F7FF000, 0x3F7FB000) + + def d16_norm_f16(self, bits, is_norm): + """f16 bits of a typed d16 buffer load component from its decoded f32 ``bits``. Round to nearest even + (f16_bits), except that a UNORM/SNORM quotient (``is_norm``) whose f32 is one of D16_NORM_HALFWAY takes the + f16 below it. The hardware rounds the exact quotient once; f32 first and then f16 rounds twice, which is 1 ulp + high on exactly those values (UNORM16 0xffaf and 0xffef, SNORM16 0x7ff7 and 0x8009, the 14- and 15-bit + twins). Measured on an RX 6700 (gfx1031) for every UNORM8/SNORM8/UNORM10/UNORM16/SNORM16 value, MUBUF and + MTBUF, wave32 and wave64 (tools/d16_format_probe.py). A float format keeps the plain rounding: a 32_FLOAT + 0x3f7ff000 is a real tie.""" + h = self.f16_bits(self.tof(bits)) + mag, a, b, hit, both, dn, out = (self.tmp() for _ in range(7)) + self.emit(f"{mag} = OpBitwiseAnd %uint {bits} {self.cu(0x7FFFFFFF)}") + self.emit(f"{a} = OpIEqual %bool {mag} {self.cu(self.D16_NORM_HALFWAY[0])}") + self.emit(f"{b} = OpIEqual %bool {mag} {self.cu(self.D16_NORM_HALFWAY[1])}") + self.emit(f"{hit} = OpLogicalOr %bool {a} {b}") + self.emit(f"{both} = OpLogicalAnd %bool {hit} {is_norm}") + self.emit(f"{dn} = OpISub %uint {h} {self.cu(1)}") # sign-magnitude: 1 ulp toward zero + self.emit(f"{out} = OpSelect %uint {both} {dn} {h}") + return out + def global_address(self, op, vaddr, saddr, mods): """The 64-bit Xbox GPU VA a global_* instruction accesses (ulong id): (saddr: 64-bit SGPR pair + zero-extended 32-bit vaddr | off: 64-bit VGPR pair) + the signed 12-bit instruction offset.""" From 967564a20c96f188982832102c0206957e761a2a Mon Sep 17 00:00:00 2001 From: AlxcBTW <187763517+AlxcBTW@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:09:58 +0100 Subject: [PATCH 004/115] M4 (synthetic): d3d12_m4_compute_test, UAV table, indirect dispatch, copy queues; buffer UAV views and indirect dispatch state d3d12_m4_compute_test, through the proxy with D3D12 API only and two translator-output compute shaders (cs_m4_fill.asm, cs_m4_indirect.asm): a COPY queue streams an input buffer in, a COMPUTE queue waits on it and runs a compute PSO over a UAV table (structured buffer, raw buffers, an R32_UINT RWTexture2D), then ExecuteIndirect of a second PSO from arguments the first wrote (with a transition to INDIRECT_ARGUMENT and UAV barriers), and a COPY queue behind a cross-queue fence reads the results back. 1,924 words match the CPU reference with error 0. Layer gaps the test found, fixed: - CreateUnorderedAccessView of a buffer was a stub: structured and raw views are now a V# in the slot. - ExecuteIndirect of a dispatch ran whatever pipeline and root arguments the command buffer had bound; the command now carries the list's, as Dispatch does. - An image created in UNORDERED_ACCESS and first used by a shader was zero-filled by the first barrier or copy that named it, losing the shader's writes; images with a UAV view are now moved to GENERAL (zeroed) at the next submission. - COMPUTE and COPY command lists no longer log "unimplemented". Test infrastructure: vk_test_device.h can create more than one VkQueue; build.py gives a compute shader's FSSM program extra words (fssm-at/fssm-data from 0x148) so two compute shaders with the same group size get distinct hashes, and honours LEONIDA_SPIRV_TOOLS (as #1679) so the target builds under the Visual Studio generator. docs/d3d12_vulkan.md section 6: M4 synthetic part met; M3 row credits @whattheflop's #1584 measurement of fences in flight. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 9 +- runtime/CMakeLists.txt | 31 +- runtime/shims/d3d12_com.cpp | 8 +- runtime/shims/d3d12_vulkan_device.cpp | 47 ++- runtime/src/command_list.h | 5 + runtime/src/vulkan_backend.h | 28 ++ runtime/src/vulkan_replay.h | 19 ++ runtime/test/d3d12_m4_compute_test.cpp | 393 ++++++++++++++++++++++++ runtime/test/shaders/build.py | 33 +- runtime/test/shaders/cs_m4_fill.asm | 51 +++ runtime/test/shaders/cs_m4_indirect.asm | 28 ++ runtime/test/vk_test_device.h | 18 +- scripts/run_gpu_tests.py | 3 +- 13 files changed, 657 insertions(+), 16 deletions(-) create mode 100644 runtime/test/d3d12_m4_compute_test.cpp create mode 100644 runtime/test/shaders/cs_m4_fill.asm create mode 100644 runtime/test/shaders/cs_m4_indirect.asm diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 83951f226f..71466ee8ea 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -536,8 +536,9 @@ which has one array layer. `d3d12_descriptor_test` checks samples at four W coor volume, plus minimum-LOD clamped views (inside the mip range via `VK_EXT_image_view_min_lod`, at or below `MostDetailedMip`, and above the last mip). -Known gaps in the descriptor path: buffer shader-resource and unordered-access views and constant-buffer views -(the V# a shader would load for them; the structure is in `gfx10_descriptors.h`, the views are not written); +Known gaps in the descriptor path: buffer shader-resource views and constant-buffer views, and typed buffer +unordered-access views and UAV counters (the V# a shader would load for them; the structure is in +`gfx10_descriptors.h`, the views are not written; structured and raw buffer UAVs are, `d3d12_m4_compute_test`); 1D-array SRVs, 1D and 3D storage views, other typeless volume formats, multisampled depth/stencil and typeless color SRVs, and shader-translator lowering for multisample loads. Single-sampled depth-plane views (`R24_UNORM_X8_TYPELESS`, `R32_FLOAT_X8X24_TYPELESS`) are a T# of the texture's depth format (8_24_UNORM, X24_8_32_FLOAT) through the @@ -2338,8 +2339,8 @@ M0–M2 do not need the executable. | **M1** | Root signature with root constants (mask the measured `0x03000000` flag byte on a copy), one translated VS+PS, PSO, vertex buffer in the arena, draw, push constants `s0..s31` + heap base | PSO translation, shader hash lookup, vertex input, root-constant packing, heap base, present | The triangle matches a CPU/GPU reference; the existing texture-test style comparison passes with error 0. **Met with stand-in shaders** by `d3d12_draw_test`: every pixel of two indexed draws and a culled triangle matches, through the proxy, validation clean. With translated game shaders most of them declare bindings, which M2 (pipelines bind set 0) lets through. **M1.5 (D3D-53) met with translator output** by `d3d12_translated_draw_test`: see below | | **M1.5** | The same, with real translator output: hand-written RDNA2 VS+PS, PSO found by FSSM hash, vertex fetch through a V# loaded from the user-data table, a root constant, a table in the arena, the code base | The push-constant, vertex-fetch and code-base contracts on translated code | Met by `d3d12_translated_draw_test`: three draws, every pixel off the triangle's edge exact in a float target, validation clean on the AMD Radeon 880M and the RTX 5070 Laptop. An upload buffer behind a V# is not supported (section 3.3) | | **M2** | Descriptor heap (heap slots 9/10 return in RAX), `CreateShaderResourceView`, sampler, root descriptor table, hash-table insert, bindless sampling | The full D3D12 descriptor path and the shader's T#/S# contract | A textured quad matches the synthetic 8×8 gradient or a known texture with error 0; the hash table has the expected entries. **Synthetic part met** by `d3d12_m2_textured_test`: through the proxy, D3D12 API only, a shader-visible CBV/SRV/UAV heap and a sampler heap (start handles from slots 9/10), two 8×8 textures uploaded with `Map` + `CopyTextureRegion`, `CreateShaderResourceView` and a POINT `CreateSampler`, a root signature of two descriptor tables, `SetDescriptorHeaps`, `SetGraphicsRootDescriptorTable` and `DrawIndexedInstanced` of a quad whose PS is translator output (`ps_m2.asm`: `s_load` of the T# and the S# from the tables, `image_sample`). Every one of the 4096 pixels matches the CPU-computed gradient (left half) and its point reflection (right half, second table) with error 0, and the hash table holds a distinct non-zero index for each of the two T#s and the S# and none for bytes nothing created; validation clean on the AMD Radeon 880M and the RTX 5070 Laptop. The layer change it needed: pipelines whose shader declares set-0 bindings (graphics and compute) were refused; their layout now holds the device's bindless set 0 and replay binds it at every draw and dispatch. Still open: shaders of the game itself (direct heap indexing, unbounded tables, static samplers, descriptors the game writes itself), no host D3D12/WARP byte comparison (the reference is computed on the CPU), and texture formats other than R8G8B8A8_UNORM, mips and arrays through a PSO (the descriptor test covers views and sampling on a compute shader) | -| **M3** | Depth/stencil, multiple render targets, resource barriers, render passes, occlusion queries, fences, 2–3 frames in flight; run the game's first frames | Real frame structure and the first game code | The game reaches its first rendered frame (loading screen/menu or whatever the executable does) or stops on a single unsupported call with a clean report. **Synthetic part met** by `d3d12_m3_frame_test`: through the proxy, D3D12 API only, six frames through a ring of three slots (three frames in flight; each slot has its own allocator, list, targets, depth buffer, query and fence, and a frame waits with `SetEventOnCompletion` + an event for the fence its slot signalled three frames earlier before reading back and recording the slot again). Pass 1 draws three rectangles from root constants with translator-output shaders (`vs_m3.asm`, `ps_m3.asm`, hand-written RDNA2) through `OMSetRenderTargets` into two render targets (R8G8B8A8_UNORM and R32_FLOAT) and a `D24_UNORM_S8_UINT` depth/stencil buffer (the layer substitutes D32_SFLOAT_S8_UINT on the Radeon; the RTX has it natively): depth LESS with write, stencil REPLACE with references 1 and 2, then a draw with no depth test whose stencil test is EQUAL; the far rectangle runs inside `BeginQuery`/`EndQuery(OCCLUSION)` and `ResolveQueryData` writes its sample count to a readback buffer. Resource barriers move the first target RENDER_TARGET → PIXEL_SHADER_RESOURCE\|COPY_SOURCE and the second to COPY_SOURCE (and back at the next frame, from resources created in those states). Pass 2 samples the first target through an SRV in a descriptor table (the M2 path) with `ps_m3_post.asm` into a third target. Every pixel of all three targets (the float one bit for bit) matches the CPU reference with error 0 in each of the six frames, and the occlusion count equals the exact visible area of the far rectangle in each frame (3555 samples over the six frames); validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. **Still open for M3:** render passes (`BeginRenderPass`, D3D-27) are not exercised, nor `BINARY_OCCLUSION`, occlusion during pipeline statistics (D3D-162), MSAA or depth/stencil copies and read-only DSV states in this test; the game's own first frames need the executable | -| **M4** | Compute PSOs, UAVs, storage images, indirect dispatch, copy queues, async streaming | Asset loading and GPU compute | The world's streaming path runs without device loss; compute results match a CPU/reference check | +| **M3** | Depth/stencil, multiple render targets, resource barriers, render passes, occlusion queries, fences, 2–3 frames in flight; run the game's first frames | Real frame structure and the first game code | The game reaches its first rendered frame (loading screen/menu or whatever the executable does) or stops on a single unsupported call with a clean report. **Synthetic part met** by `d3d12_m3_frame_test`: through the proxy, D3D12 API only, six frames through a ring of three slots (three frames in flight; each slot has its own allocator, list, targets, depth buffer, query and fence, and a frame waits with `SetEventOnCompletion` + an event for the fence its slot signalled three frames earlier before reading back and recording the slot again). Pass 1 draws three rectangles from root constants with translator-output shaders (`vs_m3.asm`, `ps_m3.asm`, hand-written RDNA2) through `OMSetRenderTargets` into two render targets (R8G8B8A8_UNORM and R32_FLOAT) and a `D24_UNORM_S8_UINT` depth/stencil buffer (the layer substitutes D32_SFLOAT_S8_UINT on the Radeon; the RTX has it natively): depth LESS with write, stencil REPLACE with references 1 and 2, then a draw with no depth test whose stencil test is EQUAL; the far rectangle runs inside `BeginQuery`/`EndQuery(OCCLUSION)` and `ResolveQueryData` writes its sample count to a readback buffer. Resource barriers move the first target RENDER_TARGET → PIXEL_SHADER_RESOURCE\|COPY_SOURCE and the second to COPY_SOURCE (and back at the next frame, from resources created in those states). Pass 2 samples the first target through an SRV in a descriptor table (the M2 path) with `ps_m3_post.asm` into a third target. Every pixel of all three targets (the float one bit for bit) matches the CPU reference with error 0 in each of the six frames, and the occlusion count equals the exact visible area of the far rectangle in each frame (3555 samples over the six frames); validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. @whattheflop's run on #1584 (GeForce RTX 3080 and a Ryzen 7 9800X3D Radeon iGPU) sampled the fences with nonblocking reads after each submit and saw 1, 2, 3, 1, 2, 3 slots still incomplete on NVIDIA and 1, 1, 1, 1, 1, 1 on AMD: up to three slots in flight on NVIDIA, one on AMD (sampled fence completion; GPU execution overlap was not measured). **Still open for M3:** render passes (`BeginRenderPass`, D3D-27) are not exercised, nor `BINARY_OCCLUSION`, occlusion during pipeline statistics (D3D-162), MSAA or depth/stencil copies and read-only DSV states in this test; the game's own first frames need the executable | +| **M4** | Compute PSOs, UAVs, storage images, indirect dispatch, copy queues, async streaming | Asset loading and GPU compute | The world's streaming path runs without device loss; compute results match a CPU/reference check. **Synthetic part met** by `d3d12_m4_compute_test`: through the proxy, D3D12 API only, with translator-output compute shaders (`cs_m4_fill.asm` and `cs_m4_indirect.asm`, hand-written RDNA2). A COPY queue streams an input buffer in (`CopyBufferRegion` from an UPLOAD buffer into a DEFAULT buffer created in COMMON), `Signal`; a COMPUTE queue `Wait`s on it and runs one list: a compute root signature (four root constants and a descriptor table of five UAVs: a structured buffer, three raw buffers and an `R32_UINT` `RWTexture2D`), a compute PSO and `Dispatch` (256 threads) that fills the structured buffer and the image from the input and writes the arguments of the next dispatch into a raw buffer; barriers (the argument buffer to `INDIRECT_ARGUMENT`, UAV barriers on the buffer and the image); `ExecuteIndirect` with a dispatch command signature running a second PSO for the 3 groups the first dispatch asked for, which reads the buffer and the image back (`image_load`) and writes a raw output; then everything to COMMON and `Signal`. A COPY queue `Wait`s on that fence, copies the five results (the image through `CopyTextureRegion`) to a readback buffer, and the CPU waits with `SetEventOnCompletion`. Each D3D12 queue has its own `VkQueue` where the family has two (both test GPUs); all 1,924 result words match the CPU reference with error 0; validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. Layer gaps this test found, closed with it: buffer UAVs (structured and raw) were not written (`CreateUnorderedAccessView` stubbed them, now a V# in the slot); `ExecuteIndirect` of a dispatch ran whatever pipeline and root arguments the command buffer had bound instead of the list's (now recorded with the command, as `Dispatch` does); an image created in `UNORDERED_ACCESS` and first used by a shader was zero-filled by the first barrier or copy that named it, losing the shader's writes (now moved to GENERAL, zeroed, at the next submission after its UAV view is created). **Still open for M4:** typed buffer UAVs and UAV counters, buffer SRVs and CBVs as V#s, a queue submitted before the queue whose fence it waits on, when a resource's layout is handed over between them (the layout tracker follows submission order, so the copy list was replayed against the layout from before the compute list ran and the run stopped on a validation error; d3d12_queue_wait_test covers Wait-before-Signal without a resource), `ExecuteIndirect` signatures that change root arguments or use count buffers for dispatches, and async streaming itself and the world's streaming path, which need the game | | **M5** | Mesh shaders, `ExecuteIndirect`, bindless-table pressure, multi-threaded command lists, pipeline cache | World rendering | A stable open-world frame at any frame rate; then profile and optimise | | **M6** | Ray tracing/XDXR: standard AS builds or the shipped `XboxBvhBuilder` compute path; BVH node format; Xbox DXIL path for the builder's 53 shaders (22 lowered so far) | RT shadows and any RT effects | RT output matches a reference; the builder's shaders run through the DXIL path or a substitute; no unknown XDXR call remains | | **M7** | HDR, VRS, `PresentX` planes (2-plane HDR + GameDVR compose, `ImmediateThresholdPercent`), resize, alt-tab, `SuspendX`/`ResumeX`, frame pacing and `GetFrameStatisticsX` | Presentation polish | HDR and resize work on the target display; no validation errors over a long run. **Partly met:** `ImmediateThresholdPercent` (late frame flipped at once through `VK_KHR/EXT_swapchain_maintenance1` IMMEDIATE/FIFO_RELAXED, section 4.5; checked on the fake-clock decision and on the Vulkan present mode, 0 VUIDs in our runs with `LEONIDA_VK_VALIDATION=1` on two GPUs, no tearing observed on a display; the console's real semantics are unmeasured). `SuspendX`/`ResumeX`, frame pacing and a minimal `GetFrameStatisticsX` exist; HDR, VRS, plane compose, alt-tab are open | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 6ea698f382..eba21d9533 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1143,8 +1143,37 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_m3_frame_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_m3_frame COMMAND d3d12_m3_frame_test) set_tests_properties(d3d12_m3_frame PROPERTIES SKIP_RETURN_CODE 77) + + # M4 (synthetic part): compute PSOs, a UAV table (structured and raw buffers, an R32_UINT storage image), an indirect + # dispatch from arguments a first dispatch wrote, and a copy queue that streams the input in and reads the results + # back across queue fences. cs_m4_fill.asm and cs_m4_indirect.asm go through the same build; build.py publishes + # their synthetic FSSM programs (the compute header and the words their "fssm-data" comments give), which the + # test wraps in shader containers. + set(LEONIDA_M4_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m4_shaders) + set(LEONIDA_M4_FILES ${LEONIDA_M4_DIR}/spirv/index.json ${LEONIDA_M4_DIR}/fssm/cs_m4_fill.fssm + ${LEONIDA_M4_DIR}/fssm/cs_m4_indirect.fssm) + add_custom_command( + OUTPUT ${LEONIDA_M4_FILES} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M4_DIR} + COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" + $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${LEONIDA_M4_DIR} cs_m4_fill cs_m4_indirect + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/compute_fixture.py + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_m4_fill.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_m4_indirect.asm + ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py + COMMENT "Translating cs_m4_fill and cs_m4_indirect for the compute test" + VERBATIM) + add_executable(d3d12_m4_compute_test test/d3d12_m4_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M4_FILES}) + target_link_libraries(d3d12_m4_compute_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_m4_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_M4_DIR="${LEONIDA_M4_DIR}") + target_compile_options(d3d12_m4_compute_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_m4_compute COMMAND d3d12_m4_compute_test) + set_tests_properties(d3d12_m4_compute PROPERTIES SKIP_RETURN_CODE 77) else() - message(STATUS "llvm-mc (set LLVM_MC) or the SDK's spirv-as/spirv-val not found: d3d12_translated_draw_test, d3d12_m2_textured_test and d3d12_m3_frame_test are not built") + message(STATUS "llvm-mc (set LLVM_MC) or the SDK's spirv-as/spirv-val not found: d3d12_translated_draw_test, d3d12_m2_textured_test, d3d12_m3_frame_test and d3d12_m4_compute_test are not built") endif() # ID3D12Resource::GetHeapProperties and ID3D12DescriptorHeap::GetDesc (node masks, resolved heap flags) against the # host runtime and WARP; run explicitly on a Vulkan GPU. diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 6fc3e2c518..48da39bbef 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -589,6 +589,11 @@ class GraphicsCommandList final cmd.argument_offset = argument_buffer_offset; cmd.count_buffer = count_buffer ? resource_id(count_buffer) : 0; cmd.count_offset = count_buffer ? count_buffer_offset : 0; + if (kind == leonida::IndirectKind::dispatch && max_command_count) { // the pipeline and root arguments a Dispatch would record + if (!compute_pipeline_ || !compute_.layout) return check(false); + cmd.pipeline = compute_pipeline_; + cmd.user_data = compute_.data; + } check(list_.execute_indirect(cmd)); } @@ -1249,7 +1254,8 @@ HRESULT create_command_list(D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator if (!command_allocator || command_allocator->type() != type) return E_INVALIDARG; // A list is created open, so the allocator must be free: E_INVALIDARG as on the PC runtime (D3D-51). if (command_allocator->recording()) return E_INVALIDARG; - if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_BUNDLE) + if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_BUNDLE && + type != D3D12_COMMAND_LIST_TYPE_COMPUTE && type != D3D12_COMMAND_LIST_TYPE_COPY) stub("create_command_list(non-direct type)"); auto* object = new GraphicsCommandList(type); // created open, as D3D12 does object->record_into(command_allocator); diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 54662bacb6..118a39e7a5 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -3802,6 +3802,49 @@ class Device final write_image_descriptor(*r, view, destination, false); } + // An unordered-access view of a buffer is a V# in the slot (docs section 3.4): the shader loads those four dwords + // through its descriptor table and reaches the bytes by the console VA in them. A structured view (format + // UNKNOWN and a stride) is `stride` and a record count, a raw one (R32_TYPELESS with the RAW flag) is a byte count; + // typed buffer views are not written. A slot left as zeros is a null descriptor. + void write_buffer_uav(ID3D12Resource* resource, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, + D3D12_CPU_DESCRIPTOR_HANDLE destination) { + const D3D12_RESOURCE_DESC& rd = Resource::from(resource)->desc(); + if (!(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + log_once("unordered-access view of a buffer created without ALLOW_UNORDERED_ACCESS; flags", int(rd.Flags)); + return; + } + if (!desc || desc->ViewDimension != D3D12_UAV_DIMENSION_BUFFER) { + log_once("unordered-access view of a buffer needs a buffer view description; dimension", + desc ? int(desc->ViewDimension) : -1); + return; + } + const D3D12_BUFFER_UAV& view = desc->Buffer; + const bool structured = desc->Format == DXGI_FORMAT_UNKNOWN; + const bool raw = desc->Format == DXGI_FORMAT_R32_TYPELESS && (view.Flags & D3D12_BUFFER_UAV_FLAG_RAW); + if (!structured && !raw) { + log_once("typed buffer unordered-access views not supported; format", int(desc->Format)); + return; + } + const UINT64 unit = structured ? view.StructureByteStride : 4; + if (!unit || unit > 0x3fff || view.CounterOffsetInBytes || + (UINT64(view.FirstElement) + view.NumElements) * unit > rd.Width || + UINT64(view.NumElements) * (structured ? 1 : 4) > ~0u) { + log_once("unordered-access view of a buffer outside the resource or with a bad stride; elements", + int(view.NumElements)); + return; + } + const UINT64 va = resource->GetGPUVirtualAddress(); + if (!va) return; + leonida::gfx10::Buffer buffer{}; + buffer.address = va + view.FirstElement * unit; + buffer.stride = structured ? std::uint32_t(unit) : 0; + buffer.num_records = std::uint32_t(structured ? view.NumElements : UINT64(view.NumElements) * 4); + buffer.oob_select = structured ? leonida::gfx10::OobSelect::structured_with_offset + : leonida::gfx10::OobSelect::raw; + const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); + std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); + } + // An unordered-access view of a texture is a T# too, of one mip; set 0 also holds it as a storage image. void STDMETHODCALLTYPE CreateUnorderedAccessView(ID3D12Resource* resource, ID3D12Resource* counter, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, @@ -3814,7 +3857,8 @@ class Device final if (resource) stub("ID3D12Device::CreateUnorderedAccessView(resource from another device)"); return; } - if (!r->image() || counter) return stub("ID3D12Device::CreateUnorderedAccessView(buffer)"); + if (counter) return stub("ID3D12Device::CreateUnorderedAccessView(counter)"); + if (!r->image()) return write_buffer_uav(resource, desc, destination); if (!(r->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { log_once("unordered-access view of a texture created without ALLOW_UNORDERED_ACCESS; flags", int(r->desc().Flags)); @@ -3845,6 +3889,7 @@ class Device final } } write_image_descriptor(*r, view, destination, true); + state_.context->note_storage_image(r->id()); } // A sampler is an S# in the first 16 bytes of the slot; the shader finds the sampler by those four dwords. diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 9c74994e18..282863f7ca 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -565,6 +565,11 @@ struct ExecuteIndirect { std::uint64_t argument_offset = 0; ResourceId count_buffer = 0; // 0: fixed max_count; non-zero: vkCmdDraw*IndirectCount std::uint64_t count_offset = 0; + // kind == dispatch: the compute pipeline and root arguments in effect, as Dispatch records them, so the dispatches + // run that pipeline with those arguments whatever the command buffer had bound. A pipeline of 0 leaves the binding + // as it is. + std::uintptr_t pipeline = 0; + std::array user_data{}; }; // Triangle geometry descriptor for a BLAS build (ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure). diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index d4b6b00a79..352f185415 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -814,6 +814,15 @@ class VulkanContext { } } + // An image that got a storage (unordered-access) view. A shader can write it before any command names it, so the + // layer would not know it was used and the first barrier or copy that does would zero-fill it (vulkan_replay.h, + // initialize). The next submission therefore moves each such image to GENERAL, the layout its descriptor names, + // zero-filled, ahead of its lists. An image already tracked beyond UNDEFINED is left as it is. + void note_storage_image(ResourceId id) { + std::lock_guard lock(storage_mutex_); + storage_pending_.push_back(id); + } + void remove_resource(ResourceId id) { VkImage img = VK_NULL_HANDLE; { @@ -1115,6 +1124,8 @@ class VulkanContext { std::unordered_map graphics_pipelines_; std::unordered_map acceleration_structures_; LayoutTracker tracker_; + std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ only + std::vector storage_pending_; std::map, VkImageView> views_; std::function bindless_prepare_; std::unique_ptr depth24_; @@ -1420,6 +1431,18 @@ class VulkanQueue { return ReplayResult::unsupported; } auto next_tracker = context_.tracker_; + std::vector storage_images; + { + std::lock_guard lock(context_.storage_mutex_); + storage_images.swap(context_.storage_pending_); + } + for (const ResourceId id : storage_images) { + const ResourceBinding* image = context_.resolve(id); + if (!image || !image->image) continue; + const VkImageSubresourceRange range{image->aspects, 0, image->mip_levels, 0, image->array_layers}; + auto pieces = detail::current(&next_tracker, id, range, VK_IMAGE_LAYOUT_UNDEFINED); + detail::initialize(replay, command_buffer, *image, id, pieces, VK_IMAGE_LAYOUT_GENERAL, &next_tracker); + } bool wrote_readback = false; VkPipelineStageFlags2 readback_stages = 0; std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists @@ -1462,6 +1485,11 @@ class VulkanQueue { const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); + if (!submitted && !storage_images.empty()) { // not initialized after all: try again with the next submission + std::lock_guard lock(context_.storage_mutex_); + context_.storage_pending_.insert(context_.storage_pending_.end(), storage_images.begin(), + storage_images.end()); + } if (submitted) { context_.tracker_ = std::move(next_tracker); slot->predicate = std::move(batch); diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 89fe7381d4..e2b26add64 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -2228,6 +2228,13 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun (ind->kind == IndirectKind::dispatch && !vk.dispatch_indirect)) return ReplayResult::unsupported; } + if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded + if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return ReplayResult::unsupported; + const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline); + if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; + p.pipeline = *pipeline; + } } else if (const auto* build = std::get_if(&command)) { if (vk.xdxr_check) { if (!vk.xdxr_check(*build)) return ReplayResult::unsupported; @@ -2949,6 +2956,18 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c } else if (ind->kind == IndirectKind::draw_indexed) { vk.draw_indexed_indirect(command_buffer, p.binding.buffer, arguments, ind->max_count, ind->stride); } else if (ind->kind == IndirectKind::dispatch) { + if (ind->pipeline) { + ShaderUserData data{}; + std::copy(ind->user_data.begin(), ind->user_data.end(), data.s); + data.heap_base = vk.heap_base; + data.code_base = p.pipeline.code_base; + vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.pipeline); + if (p.pipeline.bindless_set) + vk.bind_descriptor_sets(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.layout, 0, + 1, &p.pipeline.bindless_set, 0, nullptr); + vk.push_constants(command_buffer, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(data), + &data); + } for (std::uint32_t k = 0; k < ind->max_count; ++k) { vk.dispatch_indirect(command_buffer, p.binding.buffer, arguments + VkDeviceSize(k) * ind->stride); diff --git a/runtime/test/d3d12_m4_compute_test.cpp b/runtime/test/d3d12_m4_compute_test.cpp new file mode 100644 index 0000000000..cb322c5e58 --- /dev/null +++ b/runtime/test/d3d12_m4_compute_test.cpp @@ -0,0 +1,393 @@ +// Milestone M4, the synthetic part (docs/d3d12_vulkan.md section 6): a compute workload with the structure a game's asset +// streaming and compute passes have, through the D3D12 API on the proxy, with compute shaders that are translator output +// (test/shaders/cs_m4_fill.asm and cs_m4_indirect.asm, hand-written RDNA2). +// Three queues' worth of work, each its own command list type: +// COPY queue streams an input buffer: CopyBufferRegion from an UPLOAD buffer into a DEFAULT buffer that was created +// in COMMON (promoted to COPY_DEST there), then Signal(copy fence, 1). +// COMPUTE queue Wait(copy fence, 1), then one list: a barrier COMMON -> UNORDERED_ACCESS for the input, a compute root +// signature (four root constants and a descriptor table of five UAVs: a structured buffer, a raw +// buffer, an R32_UINT RWTexture2D, the raw input and a raw output), a compute PSO, and Dispatch with +// four groups. That shader fills the structured buffer and the image from the input and writes the +// arguments of the next dispatch into the raw buffer. Barriers (a transition of the argument buffer to +// INDIRECT_ARGUMENT and UAV barriers on the buffer and the image) and ExecuteIndirect with a dispatch +// command signature runs a second PSO whose group count is that buffer's first word: it reads the +// structured buffer and the image back and writes the raw output. Everything then goes to COMMON and +// the queue does Signal(compute fence, 1). +// COPY queue Wait(compute fence, 1), a COPY list that copies the five results (four buffers and the image through +// CopyTextureRegion) to a READBACK buffer, Signal(copy fence, 2). The CPU waits for that with +// SetEventOnCompletion and an event. +// When the Vulkan family has two queues, the copy and the compute D3D12 queue get their own VkQueue (so the fences are +// real cross-queue semaphores); with one, they share it. Either way the three batches are submitted in dependency order. +// Compared with a CPU reference, word by word, error 0: the input after the round trip, the structured buffer, the +// argument buffer, the image and the indirect dispatch's output (which also shows that exactly the 3 groups the +// first dispatch asked for ran). +// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required). +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/shader_library.h" + +#include +#include + +#ifndef LEONIDA_TEST_M4_DIR +#error "LEONIDA_TEST_M4_DIR must name the folder build.py wrote (spirv/index.json, fssm/cs_*.fssm)" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX + +namespace { + +std::vector read_file(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +constexpr UINT records = 256; // fill: 4 groups of 64 +constexpr UINT second_groups = 3; // the indirect dispatch: 3 groups of 64 +constexpr UINT image_dim = 16; // 16 x 16 R32_UINT, one texel a record +constexpr UINT seed = 0x00c0ffee, multiplier = 0x01000193; +// The readback buffer: the structured buffer, the argument buffer's 16 bytes, the second output, the input, the image. +constexpr UINT64 data_bytes = records * 16, args_bytes = 16, out2_bytes = second_groups * 64 * 8, in_bytes = records * 4; +constexpr UINT64 offset_data = 0, offset_args = offset_data + data_bytes, offset_out2 = offset_args + args_bytes, + offset_in = offset_out2 + out2_bytes; +constexpr UINT64 offset_image = (offset_in + in_bytes + 511) / 512 * 512; +constexpr UINT image_pitch = D3D12_TEXTURE_DATA_PITCH_ALIGNMENT; +constexpr UINT64 readback_bytes = offset_image + UINT64(image_dim) * image_pitch; + +std::uint32_t rotr(std::uint32_t v, unsigned n) { return (v >> n) | (v << (32 - n)); } +std::uint32_t input_word(UINT g) { return (g + 1) * 0x9e3779b1u ^ (g << 7); } + +struct Reference { + std::vector data, args, in, image, out2; +}; +Reference reference() { + Reference ref; + ref.args = {second_groups, 1, 1, 0xc0de0001u}; + ref.data.resize(records * 4); + ref.image.resize(image_dim * image_dim); + for (UINT g = 0; g < records; ++g) { + const std::uint32_t in = input_word(g); + ref.in.push_back(in); + ref.data[g * 4 + 0] = in + seed; + ref.data[g * 4 + 1] = g * multiplier; + ref.data[g * 4 + 2] = in ^ (g << 8); + ref.data[g * 4 + 3] = rotr(in, 13); + const UINT x = g & 15, y = g >> 4; + ref.image[y * image_dim + x] = in * 3 + x * 0x10001u + y; + } + for (UINT g = 0; g < second_groups * 64; ++g) { + const std::uint32_t t = ref.image[g]; // (g & 15, g >> 4) is texel g of the row-major image + ref.out2.push_back((ref.data[g * 4 + 0] + t) ^ ref.data[g * 4 + 3]); + ref.out2.push_back((ref.data[g * 4 + 2] ^ t) + ref.data[g * 4 + 1]); + } + return ref; +} + +} // namespace + +int main() { + vktest::Device d; + d.queue_count_wanted = 2; // the copy queue and the compute queue each get a VkQueue where the family has two + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + if (device_status != vktest::DeviceStatus::ready) return 1; + if (!d.bindless) { + std::printf("SKIP: the device lacks the descriptor indexing features of the bindless set 0\n"); + return 77; + } + + const std::filesystem::path root_dir = LEONIDA_TEST_M4_DIR; + leonida::ShaderLibrary library; + EXPECT(library.load((root_dir / "spirv").string())); + const auto program = [&](const char* name) { return read_file(root_dir / "fssm" / (std::string(name) + ".fssm")); }; + const auto fill = program("cs_m4_fill"), indirect = program("cs_m4_indirect"); + EXPECT(fill.size() >= 0x150 && indirect.size() >= 0x150 && fill != indirect); + EXPECT(library.find("cs", leonida::sha256_hex(fill)) && library.find("cs", leonida::sha256_hex(indirect))); + const auto fill_container = shader_container(fill), indirect_container = shader_container(indirect); + + const bool distinct_queues = d.queues.size() >= 2; + Reference want = reference(); + std::vector got; + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + if (distinct_queues) info.command_queues = d.queues; + info.buffer_device_address = true; + info.bindless = d.bindless; + info.bindless_partially_bound = d.partially_bound; + info.image_view_min_lod = d.image_view_min_lod; + info.shader_dir = (root_dir / "spirv").string(); + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); + + // [0] four 32-bit constants (s0..s3), [1] a table of five UAVs (s[4:5]). + D3D12_DESCRIPTOR_RANGE uav_range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 5, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[2] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, 4}; + params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[1].DescriptorTable = {1, &uav_range}; + params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = serialize_root_signature(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + + D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.CS = {fill_container.data(), fill_container.size()}; + Ref pso_fill, pso_indirect; + EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_fill.p)))); + pso_desc.CS = {indirect_container.data(), indirect_container.size()}; + EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_indirect.p)))); + + D3D12_INDIRECT_ARGUMENT_DESC argument{}; + argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH; + D3D12_COMMAND_SIGNATURE_DESC signature_desc{}; + signature_desc.ByteStride = sizeof(D3D12_DISPATCH_ARGUMENTS); + signature_desc.NumArgumentDescs = 1; + signature_desc.pArgumentDescs = &argument; + Ref signature; + EXPECT(SUCCEEDED(device->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature.p)))); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + constexpr auto uav_flag = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + constexpr auto uav_state = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + constexpr auto common = D3D12_RESOURCE_STATE_COMMON; + Ref upload, input, data, args, out2, image, readback; + const auto create_buffer = [&](Ref& out, const D3D12_HEAP_PROPERTIES& heap, UINT64 bytes, + D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state) { + const auto desc = buffer_desc(bytes, flags); + return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, + IID_PPV_ARGS(&out.p))); + }; + EXPECT(create_buffer(upload, upload_heap, in_bytes, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ)); + EXPECT(create_buffer(input, default_heap, in_bytes, uav_flag, common)); + EXPECT(create_buffer(data, default_heap, data_bytes, uav_flag, uav_state)); + EXPECT(create_buffer(args, default_heap, 256, uav_flag, uav_state)); + EXPECT(create_buffer(out2, default_heap, out2_bytes, uav_flag, uav_state)); + EXPECT(create_buffer(readback, readback_heap, readback_bytes, D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_COPY_DEST)); + D3D12_RESOURCE_DESC image_desc{}; + image_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + image_desc.Width = image_desc.Height = image_dim; + image_desc.DepthOrArraySize = 1; + image_desc.MipLevels = 1; + image_desc.Format = DXGI_FORMAT_R32_UINT; + image_desc.SampleDesc.Count = 1; + image_desc.Flags = uav_flag; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &image_desc, uav_state, + nullptr, IID_PPV_ARGS(&image.p)))); + { + std::uint32_t* mapped = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&mapped)))); + for (UINT g = 0; g < records; ++g) mapped[g] = input_word(g); + upload->Unmap(0, nullptr); + } + + // The table: slot 0 structured buffer (stride 16), 1 raw argument buffer, 2 image, 3 raw input, 4 raw output. + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 5, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(heap.p, 9))(heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(heap.p, 10))(heap.p); + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32) && step == 32); // the shaders step 32 bytes a slot + const auto handle = [&](UINT i) { return D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(cpu + std::uint64_t(i) * step)}; }; + const auto buffer_view = [](DXGI_FORMAT format, UINT count, UINT stride, D3D12_BUFFER_UAV_FLAGS flags) { + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + view.Format = format; + view.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + view.Buffer = {0, count, stride, 0, flags}; + return view; + }; + auto view = buffer_view(DXGI_FORMAT_UNKNOWN, records, 16, D3D12_BUFFER_UAV_FLAG_NONE); + device->CreateUnorderedAccessView(data.p, nullptr, &view, handle(0)); + view = buffer_view(DXGI_FORMAT_R32_TYPELESS, 4, 0, D3D12_BUFFER_UAV_FLAG_RAW); // the 16 bytes of arguments + device->CreateUnorderedAccessView(args.p, nullptr, &view, handle(1)); + D3D12_UNORDERED_ACCESS_VIEW_DESC image_view{}; + image_view.Format = DXGI_FORMAT_R32_UINT; + image_view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + device->CreateUnorderedAccessView(image.p, nullptr, &image_view, handle(2)); + view = buffer_view(DXGI_FORMAT_R32_TYPELESS, records, 0, D3D12_BUFFER_UAV_FLAG_RAW); + device->CreateUnorderedAccessView(input.p, nullptr, &view, handle(3)); + view = buffer_view(DXGI_FORMAT_R32_TYPELESS, UINT(out2_bytes / 4), 0, D3D12_BUFFER_UAV_FLAG_RAW); + device->CreateUnorderedAccessView(out2.p, nullptr, &view, handle(4)); + // The V# of the structured view and the T# of the image view are what the shader loads from the table. + std::uint32_t v_data[4], v_args[4]; + std::memcpy(v_data, reinterpret_cast(handle(0).ptr), sizeof(v_data)); + std::memcpy(v_args, reinterpret_cast(handle(1).ptr), sizeof(v_args)); + EXPECT(v_data[0] == std::uint32_t(data->GetGPUVirtualAddress()) && (v_data[1] >> 16 & 0x3fff) == 16 && + v_data[2] == records); + EXPECT(v_args[0] == std::uint32_t(args->GetGPUVirtualAddress()) && (v_args[1] >> 16 & 0x3fff) == 0 && + v_args[2] == 16); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref copy_queue, compute_queue; + queue_desc.Type = D3D12_COMMAND_LIST_TYPE_COPY; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(©_queue.p)))); + queue_desc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&compute_queue.p)))); + Ref stream_alloc, compute_alloc, readback_alloc; + Ref stream_list, compute_list, readback_list; + Ref copy_fence, compute_fence; + const auto make_list = [&](D3D12_COMMAND_LIST_TYPE type, Ref& alloc, + Ref& list) { + return SUCCEEDED(device->CreateCommandAllocator(type, IID_PPV_ARGS(&alloc.p))) && + SUCCEEDED(device->CreateCommandList(0, type, alloc.p, nullptr, IID_PPV_ARGS(&list.p))); + }; + EXPECT(make_list(D3D12_COMMAND_LIST_TYPE_COPY, stream_alloc, stream_list)); + EXPECT(make_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, compute_alloc, compute_list)); + EXPECT(make_list(D3D12_COMMAND_LIST_TYPE_COPY, readback_alloc, readback_list)); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(©_fence.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&compute_fence.p)))); + + // Copy list 1: stream the input in (the buffer is in COMMON and is promoted to COPY_DEST by the copy). + stream_list->CopyBufferRegion(input.p, 0, upload.p, 0, in_bytes); + EXPECT(stream_list->Close() == S_OK); + + D3D12_TEXTURE_COPY_LOCATION dst{}, src{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {offset_image, {DXGI_FORMAT_R32_UINT, image_dim, image_dim, 1, image_pitch}}; + src.pResource = image.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + + // Compute list. + ID3D12DescriptorHeap* heaps[] = {heap.p}; + D3D12_RESOURCE_BARRIER acquire = transition(input.p, common, uav_state); + compute_list->ResourceBarrier(1, &acquire); + compute_list->SetDescriptorHeaps(1, heaps); + compute_list->SetComputeRootSignature(root.p); + compute_list->SetPipelineState(pso_fill.p); + const std::uint32_t constants[4] = {seed, multiplier, second_groups, 0}; + compute_list->SetComputeRoot32BitConstants(0, 4, constants, 0); + compute_list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); + compute_list->Dispatch(records / 64, 1, 1); + D3D12_RESOURCE_BARRIER between[3] = {transition(args.p, uav_state, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), + {}, {}}; + for (int i : {1, 2}) { + between[i].Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + between[i].UAV.pResource = i == 1 ? data.p : image.p; + } + compute_list->ResourceBarrier(3, between); + compute_list->SetPipelineState(pso_indirect.p); // the root arguments stay + compute_list->ExecuteIndirect(signature.p, 1, args.p, 0, nullptr, 0); + D3D12_RESOURCE_BARRIER release[5] = {transition(data.p, uav_state, common), + transition(args.p, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, common), + transition(out2.p, uav_state, common), + transition(input.p, uav_state, common), + transition(image.p, uav_state, common)}; + compute_list->ResourceBarrier(5, release); + EXPECT(compute_list->Close() == S_OK); + + // Copy list 2: the results to the readback buffer, once the compute queue is done. + readback_list->CopyBufferRegion(readback.p, offset_data, data.p, 0, data_bytes); + readback_list->CopyBufferRegion(readback.p, offset_args, args.p, 0, args_bytes); + readback_list->CopyBufferRegion(readback.p, offset_out2, out2.p, 0, out2_bytes); + readback_list->CopyBufferRegion(readback.p, offset_in, input.p, 0, in_bytes); + readback_list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + EXPECT(readback_list->Close() == S_OK); + + const auto execute = [&](ID3D12CommandQueue* queue, ID3D12GraphicsCommandList* list) { + ID3D12CommandList* lists[] = {list}; + queue->ExecuteCommandLists(1, lists); + return rt::d3d12::last_execute_result(queue) == leonida::ReplayResult::success; + }; + const auto submit_copy = [&] { + return execute(copy_queue.p, stream_list.p) && SUCCEEDED(copy_queue->Signal(copy_fence.p, 1)); + }; + const auto submit_readback = [&] { + return SUCCEEDED(copy_queue->Wait(compute_fence.p, 1)) && execute(copy_queue.p, readback_list.p) && + SUCCEEDED(copy_queue->Signal(copy_fence.p, 2)); + }; + const auto submit_compute = [&] { + return SUCCEEDED(compute_queue->Wait(copy_fence.p, 1)) && execute(compute_queue.p, compute_list.p) && + SUCCEEDED(compute_queue->Signal(compute_fence.p, 1)); + }; + // In dependency order: the layer replays a list at ExecuteCommandLists and tracks every image's layout in that + // order, so a list that waits for another queue's signal has to be submitted after the list it waits for + // (the Wait-before-Signal order d3d12_queue_wait_test covers, without a resource handed over). + EXPECT(submit_copy() && submit_compute() && submit_readback()); + + const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + EXPECT(event != nullptr); + EXPECT(SUCCEEDED(copy_fence->SetEventOnCompletion(2, event))); + if (WaitForSingleObject(event, 20000) != WAIT_OBJECT_0) { + std::fprintf(stderr, "the copy fence never reached 2 (compute fence at %llu)\n", + static_cast(compute_fence->GetCompletedValue())); + return 1; + } + CloseHandle(event); + EXPECT(copy_fence->GetCompletedValue() >= 2 && compute_fence->GetCompletedValue() >= 1); + + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + got.assign(static_cast(mapped), static_cast(mapped) + readback_bytes); + readback->Unmap(0, nullptr); + + for (auto* r : {&upload, &input, &data, &args, &out2, &image, &readback}) r->reset(); + stream_list.reset(); compute_list.reset(); readback_list.reset(); + stream_alloc.reset(); compute_alloc.reset(); readback_alloc.reset(); + copy_fence.reset(); compute_fence.reset(); + signature.reset(); pso_fill.reset(); pso_indirect.reset(); root.reset(); heap.reset(); + copy_queue.reset(); compute_queue.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + + unsigned mismatches = 0, words = 0; + const auto compare = [&](const char* what, UINT64 offset, const std::vector& expected, UINT pitch, + UINT row_words) { + unsigned bad = 0; + for (std::size_t i = 0; i < expected.size(); ++i) { + std::uint32_t value = 0; + const UINT64 at = offset + (pitch ? (i / row_words) * pitch + (i % row_words) * 4 : i * 4); + std::memcpy(&value, got.data() + at, 4); + ++words; + if (value == expected[i]) continue; + ++mismatches; + if (bad++ < 4) std::fprintf(stderr, "%s word %zu: got %08x want %08x\n", what, i, value, expected[i]); + } + if (bad) std::fprintf(stderr, "%s: %u of %zu words differ\n", what, bad, expected.size()); + }; + compare("input (copy queue round trip)", offset_in, want.in, 0, 0); + compare("structured buffer", offset_data, want.data, 0, 0); + compare("dispatch arguments", offset_args, want.args, 0, 0); + compare("image", offset_image, want.image, image_pitch, image_dim); + compare("indirect dispatch output", offset_out2, want.out2, 0, 0); + EXPECT(!mismatches); + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("M4: a COPY queue streamed an input buffer in, a COMPUTE queue ran a compute PSO over a UAV table " + "(structured buffer, raw buffers, an R32_UINT storage image) and a second dispatch through " + "ExecuteIndirect from arguments the first wrote, and a COPY queue behind a cross-queue fence read the " + "results back (%s): %u words matched the CPU reference (error 0)\n", + distinct_queues ? "two VkQueues" : "one VkQueue", words); + return 0; +} diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index f7979ee691..68e22431df 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py @@ -58,8 +58,8 @@ def asm_mattr(path): CLIP_CASES = {"vs_clip": 1, "vs_clip_param4": 4, "vs_clip_undeclared": 1} -def asm_fssm(path): - """The synthetic FSSM program a vs_/ps_ shader's header asks for, or None.""" +def asm_fssm_fields(path): + """(offset, words) of the "fssm-at" and "fssm-data" header comments, (None, []) without them.""" at, words = None, [] for ln in Path(path).read_text(encoding="utf-8").splitlines(): s = ln.strip() @@ -71,11 +71,27 @@ def asm_fssm(path): m = re.match(r";\s*fssm-data:\s*(.*)", s) if m: words += [int(w, 0) for w in m.group(1).split()] + return at, words + + +def asm_fssm(path): + """The synthetic FSSM program a vs_/ps_ shader's header asks for, or None.""" + at, words = asm_fssm_fields(path) if at is None or not words or at < 4 or at % 4: return None return b"FSSM" + bytes(at - 4) + b"".join(struct.pack("> 4) = in * 3 + x * 0x10001 + y +; g == 0 also writes the arguments { s2, 1, 1, 0xc0de0001 } +s_load_dwordx4 s[8:11], s[4:5], 0x0 +s_load_dwordx4 s[12:15], s[4:5], 0x20 +s_load_dwordx8 s[16:23], s[4:5], 0x40 +s_load_dwordx4 s[24:27], s[4:5], 0x60 +s_lshl_b32 s7, s6, 6 +s_waitcnt lgkmcnt(0) +v_add_nc_u32_e32 v1, s7, v0 +v_lshlrev_b32_e32 v2, 2, v1 +buffer_load_dword v3, v2, s[24:27], 0 offen +s_waitcnt vmcnt(0) +v_add_nc_u32_e32 v4, s0, v3 +v_mul_lo_u32 v5, v1, s1 +v_lshlrev_b32_e32 v6, 8, v1 +v_xor_b32_e32 v6, v3, v6 +v_alignbit_b32 v7, v3, v3, 13 +buffer_store_dwordx4 v[4:7], v1, s[8:11], 0 idxen +v_and_b32_e32 v8, 15, v1 +v_lshrrev_b32_e32 v9, 4, v1 +v_mul_u32_u24_e32 v10, 0x10001, v8 +v_mul_lo_u32 v11, v3, 3 +v_add_nc_u32_e32 v10, v10, v11 +v_add_nc_u32_e32 v10, v10, v9 +image_store v10, v[8:9], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +v_cmpx_eq_u32_e32 0, v1 +v_mov_b32_e32 v12, 0 +v_mov_b32_e32 v13, s2 +v_mov_b32_e32 v14, 1 +v_mov_b32_e32 v15, 1 +v_mov_b32_e32 v16, 0xc0de0001 +buffer_store_dwordx4 v[13:16], v12, s[12:15], 0 offen +s_endpgm diff --git a/runtime/test/shaders/cs_m4_indirect.asm b/runtime/test/shaders/cs_m4_indirect.asm new file mode 100644 index 0000000000..8a23596bf0 --- /dev/null +++ b/runtime/test/shaders/cs_m4_indirect.asm @@ -0,0 +1,28 @@ +; group: 64,1,1 +; rsrc2: 0x808c +; fssm-at: 0x150 +; fssm-data: 0x44444e49 0x3d344d5f +; M4 compute shader 2: runs under ExecuteIndirect with the arguments cs_m4_fill wrote ({ groups, 1, 1 }), reads the +; structured buffer and the image the first dispatch wrote, and writes a raw output buffer. Run: +; d3d12_m4_compute_test. Same root signature, user data and table as cs_m4_fill (see there): +; slot 0: structured buffer (read) slot 2: R32_UINT image (read, image_load) slot 4: raw output (written) +; g = 64 * group + lane; t = image(g & 15, g >> 4); record g = { w0, w1, w2, w3 } +; out[g] = { (w0 + t) ^ w3, (w2 ^ t) + w1 } at byte offset 8 * g +s_load_dwordx4 s[8:11], s[4:5], 0x0 +s_load_dwordx8 s[16:23], s[4:5], 0x40 +s_load_dwordx4 s[12:15], s[4:5], 0x80 +s_lshl_b32 s7, s6, 6 +s_waitcnt lgkmcnt(0) +v_add_nc_u32_e32 v1, s7, v0 +buffer_load_dwordx4 v[4:7], v1, s[8:11], 0 idxen +v_and_b32_e32 v8, 15, v1 +v_lshrrev_b32_e32 v9, 4, v1 +image_load v10, v[8:9], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +s_waitcnt vmcnt(0) +v_add_nc_u32_e32 v11, v4, v10 +v_xor_b32_e32 v11, v11, v7 +v_xor_b32_e32 v12, v6, v10 +v_add_nc_u32_e32 v12, v12, v5 +v_lshlrev_b32_e32 v13, 3, v1 +buffer_store_dwordx2 v[11:12], v13, s[12:15], 0 offen +s_endpgm diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 0fb490d184..34b30892f8 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -81,6 +81,12 @@ class Device { VkDevice device = VK_NULL_HANDLE; VkQueue queue = VK_NULL_HANDLE; std::uint32_t family = 0; + // Set before initialize(): how many queues of `family` to create (fewer if the family has fewer). `queues` holds the + // handles; queues[0] == queue. A test that wants distinct VkQueues for its D3D12 queues passes them on as + // VulkanDeviceInfo::command_queues when there is more than one. + std::uint32_t queue_count_wanted = 1; + std::uint32_t family_queue_count = 1; // the family's queueCount, known after the device is chosen + std::vector queues; bool validation = false; bool bc = false; // textureCompressionBC enabled VkPhysicalDeviceFeatures enabled{}; // the core features enabled on `device` @@ -274,6 +280,7 @@ class Device { rank > best_rank) { physical = candidate; family = i; + family_queue_count = families[i].queueCount; chosen = props; best_rank = rank; } @@ -357,11 +364,11 @@ class Device { enable12.samplerFilterMinmax = sampler_filter_minmax; enable12.bufferDeviceAddress = VK_TRUE; - const float priority = 1.0f; + const std::vector priority(std::max(1u, std::min(queue_count_wanted, family_queue_count)), 1.0f); VkDeviceQueueCreateInfo queue_info{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; queue_info.queueFamilyIndex = family; - queue_info.queueCount = 1; - queue_info.pQueuePriorities = &priority; + queue_info.queueCount = std::max(1u, std::min(queue_count_wanted, family_queue_count)); + queue_info.pQueuePriorities = priority.data(); VkPhysicalDeviceFeatures enable{}; enable.textureCompressionBC = features.features.textureCompressionBC; // BC uploads, where available bc = features.features.textureCompressionBC == VK_TRUE; @@ -463,7 +470,10 @@ class Device { result = instance_fn("vkCreateDevice")(physical, &device_info, nullptr, &device); if (result != VK_SUCCESS) return failure("vkCreateDevice", result); device_proc = instance_fn("vkGetDeviceProcAddr"); - fn("vkGetDeviceQueue")(device, family, 0, &queue); + queues.resize(queue_info.queueCount); + for (std::uint32_t i = 0; i < queue_info.queueCount; ++i) + fn("vkGetDeviceQueue")(device, family, i, &queues[i]); + queue = queues[0]; instance_fn("vkGetPhysicalDeviceMemoryProperties")(physical, &memory_); VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 670e3255a0..819b5933a2 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -541,7 +541,8 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool, OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "vs_m15": "d3d12_translated_draw_test", "ps_m2": "d3d12_m2_textured_test", "vs_m2": "d3d12_m2_textured_test", "ps_m2_uoff": "d3d12_m2_textured_test", "ps_m3": "d3d12_m3_frame_test", "vs_m3": "d3d12_m3_frame_test", - "ps_m3_post": "d3d12_m3_frame_test"} + "ps_m3_post": "d3d12_m3_frame_test", + "cs_m4_fill": "d3d12_m4_compute_test", "cs_m4_indirect": "d3d12_m4_compute_test"} # Shaders a selected test draws with, built even when the filter leaves them out (#192). From 427532c70c4dfe91577f8b2f48d25f371a0e9de0 Mon Sep 17 00:00:00 2001 From: Ash Hopkins Date: Sun, 22 Nov 2026 14:14:17 +0000 Subject: [PATCH 005/115] base_reservation: check SetEnvironmentVariableW and ResumeThread before waiting on the child Review on #1707: without the marker the child would not use the reservation and could relaunch again, and a child left suspended would make the infinite wait hang. Both now end the child and return 1, as a failed reservation already did. AI-assisted. No game files. --- runtime/src/base_reservation.h | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/runtime/src/base_reservation.h b/runtime/src/base_reservation.h index 76fb530ce8..bf49468954 100644 --- a/runtime/src/base_reservation.h +++ b/runtime/src/base_reservation.h @@ -98,7 +98,11 @@ inline int relaunch(const Range& r) { wchar_t marker[64]; std::swprintf(marker, 64, L"%llx:%llx", static_cast(r.base), static_cast(r.size)); - SetEnvironmentVariableW(kVariable, marker); // inherited by the child; this process only waits from here on + // Inherited by the child: it tells it to commit inside the reservation and not to relaunch again. + if (!SetEnvironmentVariableW(kVariable, marker)) { + std::fprintf(stderr, "error: setting %ls failed (%lu)\n", kVariable, GetLastError()); + return 1; + } std::wstring command_line = GetCommandLineW(); STARTUPINFOW startup{sizeof startup}; startup.dwFlags = STARTF_USESTDHANDLES; @@ -115,19 +119,27 @@ inline int relaunch(const Range& r) { std::fprintf(stderr, "error: starting gta6rt again to reserve the image range failed (%lu)\n", GetLastError()); return 1; } - if (!VirtualAllocEx(process.hProcess, reinterpret_cast(r.base), static_cast(r.size), MEM_RESERVE, - PAGE_NOACCESS)) { - const DWORD error = GetLastError(); + const auto abandon = [&process] { // the child never ran: end it and release its handles TerminateProcess(process.hProcess, 1); CloseHandle(process.hThread); CloseHandle(process.hProcess); + }; + if (!VirtualAllocEx(process.hProcess, reinterpret_cast(r.base), static_cast(r.size), MEM_RESERVE, + PAGE_NOACCESS)) { + const DWORD error = GetLastError(); + abandon(); std::fprintf(stderr, "error: the image has no relocations and its range %#llx-%#llx is taken, also in a new " "process (VirtualAllocEx %lu)\n", static_cast(r.base), static_cast(r.base + r.size), error); return 1; } - ResumeThread(process.hThread); + if (ResumeThread(process.hThread) == static_cast(-1)) { // still suspended: the wait would never end + const DWORD error = GetLastError(); + abandon(); + std::fprintf(stderr, "error: resuming the relaunched gta6rt failed (%lu)\n", error); + return 1; + } WaitForSingleObject(process.hProcess, INFINITE); DWORD code = 1; GetExitCodeProcess(process.hProcess, &code); From c25e2773f75642b16514682d533fea3b1e7c0eb5 Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:14:19 +0100 Subject: [PATCH 006/115] GLB writer: preserve hard edges next to explicit OBJ normals --- tools/glb_writer.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/tools/glb_writer.py b/tools/glb_writer.py index 0fa942c51d..c6900bfef3 100644 --- a/tools/glb_writer.py +++ b/tools/glb_writer.py @@ -453,10 +453,19 @@ def parse_obj( first_vertex.setdefault(corner[0], vertex) for corner, vertex in builder["vert_map"].items() ] - computed = _compute_smooth_normals(positions, (normal_vertices[i] for i in indices)) + raw_normals = builder["normals"] + index_iter = iter(indices) + # Fully explicit triangles should not smooth neighboring generated normals. + normal_indices = ( + normal_vertices[i] + for a, b, c in zip(index_iter, index_iter, index_iter) + if None in (raw_normals[a], raw_normals[b], raw_normals[c]) + for i in (a, b, c) + ) + computed = _compute_smooth_normals(positions, normal_indices) normals = [ normal if normal is not None else computed[normal_vertex] - for normal, normal_vertex in zip(builder["normals"], normal_vertices) + for normal, normal_vertex in zip(raw_normals, normal_vertices) ] else: normals = builder["normals"] From 083e502e6601493383d3635b433cdeb3b6850deb Mon Sep 17 00:00:00 2001 From: Ryderadzeee Date: Sun, 22 Nov 2026 18:13:17 +0400 Subject: [PATCH 007/115] Validate DXGI flip-model swapchain formats --- runtime/shims/dxgi_com.cpp | 15 ++++------ runtime/test/dxgi_swapchain_test.cpp | 43 ++++++++++++++++++++++++++-- 2 files changed, 45 insertions(+), 13 deletions(-) diff --git a/runtime/shims/dxgi_com.cpp b/runtime/shims/dxgi_com.cpp index 114efc6e35..24ddcdf9b6 100644 --- a/runtime/shims/dxgi_com.cpp +++ b/runtime/shims/dxgi_com.cpp @@ -29,9 +29,7 @@ bool valid_flip_buffer_count(UINT count) { VkFormat dxgi_to_vk_format(DXGI_FORMAT fmt) { switch (fmt) { case DXGI_FORMAT_B8G8R8A8_UNORM: return VK_FORMAT_B8G8R8A8_UNORM; - case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return VK_FORMAT_B8G8R8A8_SRGB; case DXGI_FORMAT_R8G8B8A8_UNORM: return VK_FORMAT_R8G8B8A8_UNORM; - case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return VK_FORMAT_R8G8B8A8_SRGB; case DXGI_FORMAT_R10G10B10A2_UNORM: return VK_FORMAT_A2B10G10R10_UNORM_PACK32; case DXGI_FORMAT_R16G16B16A16_FLOAT: return VK_FORMAT_R16G16B16A16_SFLOAT; default: return VK_FORMAT_UNDEFINED; @@ -126,17 +124,12 @@ class SwapChain final : public IDXGISwapChain3 { if (parent_) parent_->Release(); } - bool init(HWND hwnd, const DXGI_SWAP_CHAIN_DESC1& desc) { + bool init(HWND hwnd, const DXGI_SWAP_CHAIN_DESC1& desc, VkFormat vk_fmt) { hwnd_ = hwnd; flags_ = desc.Flags; const VkExtent2D size = size_or_client(desc.Width, desc.Height, {256u, 256u}); const std::uint32_t w = size.width; const std::uint32_t h = size.height; - VkFormat vk_fmt = VK_FORMAT_UNDEFINED; - if (desc.Format != DXGI_FORMAT_UNKNOWN) { - vk_fmt = dxgi_to_vk_format(desc.Format); - if (vk_fmt == VK_FORMAT_UNDEFINED) return false; - } const bool allow_tearing = (flags_ & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING) != 0; if (!swapchain_.create(hwnd, w, h, vk_fmt, desc.BufferCount, allow_tearing)) return false; if (flags_ & DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT) { @@ -241,7 +234,7 @@ class SwapChain final : public IDXGISwapChain3 { VkFormat vk_fmt = VK_FORMAT_UNDEFINED; if (fmt != DXGI_FORMAT_UNKNOWN) { vk_fmt = dxgi_to_vk_format(fmt); - if (vk_fmt == VK_FORMAT_UNDEFINED) return DXGI_ERROR_UNSUPPORTED; + if (vk_fmt == VK_FORMAT_UNDEFINED) return E_INVALIDARG; } // DXGI refuses to resize while the app still holds a back buffer reference. for (auto* bb : buffers_) @@ -782,8 +775,10 @@ class Factory final : public IDXGIFactory5 { *out = nullptr; if (!hwnd || !desc) return E_INVALIDARG; if (!valid_flip_buffer_count(desc->BufferCount)) return DXGI_ERROR_INVALID_CALL; + const VkFormat vk_fmt = dxgi_to_vk_format(desc->Format); + if (vk_fmt == VK_FORMAT_UNDEFINED) return DXGI_ERROR_INVALID_CALL; auto* sc = new SwapChain(this, device, context_, gipa_, instance_, physical_, gdpa_, queue_, queue_family_); - if (!sc->init(hwnd, *desc)) { + if (!sc->init(hwnd, *desc, vk_fmt)) { sc->Release(); return E_FAIL; } diff --git a/runtime/test/dxgi_swapchain_test.cpp b/runtime/test/dxgi_swapchain_test.cpp index 6b1835b383..ca67dbe3f0 100644 --- a/runtime/test/dxgi_swapchain_test.cpp +++ b/runtime/test/dxgi_swapchain_test.cpp @@ -443,6 +443,9 @@ int main() { // Frame 2: ResizeBuffers to explicit 37x19 on the unchanged 128x128 HWND, clear to green, read back all 703 pixels, Present. if (FAILED(sc->ResizeBuffers(2, 37, 19, DXGI_FORMAT_UNKNOWN, 0))) return fail("ResizeBuffers"); + DXGI_SWAP_CHAIN_DESC1 preserved_format{}; + if (FAILED(sc->GetDesc1(&preserved_format)) || preserved_format.Format != scd.Format) + return fail("ResizeBuffers with DXGI_FORMAT_UNKNOWN changed the format"); const float green[4] = {0.0f, 1.0f, 0.0f, 1.0f}; if (run_clear_readback_present(37, 19, green, 0, 255, 0) != 0) return 1; @@ -603,9 +606,28 @@ int main() { return fail("GetRotation(nullptr) should return E_INVALIDARG"); } - // Unsupported swapchain format must fail explicitly instead of silently downgrading to BGRA8. - if (sc->ResizeBuffers(2, 37, 19, DXGI_FORMAT_R32_UINT, 0) != DXGI_ERROR_UNSUPPORTED) - return fail("ResizeBuffers should reject unsupported format DXGI_FORMAT_R32_UINT"); + constexpr DXGI_FORMAT invalid_formats[] = { + DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, + DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R32_UINT, + }; + { + DXGI_SWAP_CHAIN_DESC1 before{}, after{}; + if (FAILED(sc->GetDesc1(&before))) return fail("GetDesc1 before invalid formats"); + const UINT node_masks[2] = {1, 1}; + IUnknown* const present_queues[2] = {queue, queue}; + for (DXGI_FORMAT format : invalid_formats) { + if (sc->ResizeBuffers(2, 64, 64, format, 0) != E_INVALIDARG || + sc->ResizeBuffers1(2, 64, 64, format, 0, node_masks, present_queues) != E_INVALIDARG) + return fail("ResizeBuffers and ResizeBuffers1 should reject invalid flip-model formats"); + } + if (FAILED(sc->GetDesc1(&after)) || after.Format != before.Format || after.BufferCount != before.BufferCount || + after.Width != before.Width || after.Height != before.Height) + return fail("Invalid format changed the existing swapchain"); + ID3D12Resource* buffer = nullptr; + if (FAILED(sc->GetBuffer(sc->GetCurrentBackBufferIndex(), IID_PPV_ARGS(&buffer))) || !buffer) + return fail("GetBuffer after invalid swapchain formats"); + buffer->Release(); + } // Measured on host DXGI (RTX 5070 and WARP): DXGI_PRESENT_TEST returns S_OK without presenting, so the back // buffer index and last present count stay; a sync interval above 4 is DXGI_ERROR_INVALID_CALL and presents nothing. @@ -782,6 +804,21 @@ int main() { HWND hwnd2 = create_test_window(200, 150); if (!hwnd2) return fail("CreateWindowExW (second)"); GetClientRect(hwnd2, &cr); + const auto rejects_creation_format = [&](DXGI_FORMAT format) { + DXGI_SWAP_CHAIN_DESC1 invalid = scd; + invalid.Format = format; + IDXGISwapChain1* rejected = nullptr; + const HRESULT hr = factory->CreateSwapChainForHwnd(queue, hwnd2, &invalid, nullptr, nullptr, &rejected); + if (rejected) { + rejected->Release(); + return false; + } + return hr == DXGI_ERROR_INVALID_CALL; + }; + if (!rejects_creation_format(DXGI_FORMAT_UNKNOWN)) + return fail("CreateSwapChainForHwnd accepted DXGI_FORMAT_UNKNOWN"); + for (DXGI_FORMAT format : invalid_formats) + if (!rejects_creation_format(format)) return fail("CreateSwapChainForHwnd invalid flip-model format"); DXGI_SWAP_CHAIN_DESC1 zd = scd; zd.Width = 0; zd.Height = 0; From 9c326c2cd482690a84db1783dcb6f16022b37dd8 Mon Sep 17 00:00:00 2001 From: eIBart0 Date: Sun, 22 Nov 2026 11:14:40 -0300 Subject: [PATCH 008/115] lds_fuzz.py: exercise ds_permute_b32 collisions and negative control (FUZZ-10) --- docs/shader_validation.md | 15 ++++++++-- tests/test_lds_fuzz.py | 60 +++++++++++++++++++++++++++++++++++++++ tests/test_lds_fuzz_hw.py | 4 ++- tools/lds_fuzz.py | 18 ++++++------ 4 files changed, 85 insertions(+), 12 deletions(-) diff --git a/docs/shader_validation.md b/docs/shader_validation.md index d6399d74f3..0480cd493a 100644 --- a/docs/shader_validation.md +++ b/docs/shader_validation.md @@ -390,11 +390,20 @@ python -I tools/lds_fuzz.py --oracle hw --programs 50 --seed 1 --wave 32 --only that lane is on"): gfx1150 returns 0 when the source lane is off in EXEC, as `ds_bpermute` does. The model now says that. - **Negative controls.** `--perturb NAME` judges the hardware against a deliberately wrong model (mismatches must - appear); `--negative-control` re-judges the words of the run with all 15 (`max_i32` unsigned, `min_u32` signed, + appear); `--negative-control` re-judges the words of the run with all 16 (`max_i32` unsigned, `min_u32` signed, swapped `cmpst`, zero-extended `i8`/`i16`, d16 reads clearing the other half, `b16_d16_hi` shift, swapped `write2`, `st64` unit, bpermute reading off lanes or crossing the wave64 halves, reversed quad permute, swapped - swizzle or/xor, permute writing no zero) and exits 1 if one goes unnoticed. `--minimize` drops ops while a - program still differs, `--keep DIR` writes the native kernel of each mismatch, `--only I,J` runs chosen indices. + swizzle or/xor, permute writing no zero, permute lowest source winning a collision) and exits 1 if one goes + unnoticed. `--minimize` drops ops while a program still differs, `--keep DIR` writes the native kernel of each + mismatch, `--only I,J` runs chosen indices. + +RDNA2 `ds_permute_b32` verification (`FUZZ-10`, `SHADER-133`): raw kernels on an AMD Radeon RX 6800 (`gfx1030`, wave32 +and wave64) confirm that only active lanes send, the highest active source lane wins a collision, active destination +lanes nobody targets read `0`, inactive destinations keep their old values, and the two 32-lane halves stay separate +in wave64. On an AMD Radeon RX 6700 XT (`gfx1031`, RADV Mesa 26.3.1), 3,600 translator runs with colliding +`ds_permute_b32` multipliers (`mul` in `0..63`, seeds 1–3, 300 programs × wave32/wave64 native and `--emulate`) +matched the model bit for bit (`0` mismatches), and inverting the collision winner or zero-fill rules produced +mismatches in `39` and `56` of `200` seed-1 programs. Results on a Radeon 880M (gfx1150, RDNA3.5, driver 26.11.2, AMD clang 23.0.0git), `--oracle hw`: diff --git a/tests/test_lds_fuzz.py b/tests/test_lds_fuzz.py index e59020c2cb..3c286e45b8 100644 --- a/tests/test_lds_fuzz.py +++ b/tests/test_lds_fuzz.py @@ -85,6 +85,24 @@ def test_no_exec_keeps_the_rest_of_the_program(self): else: self.assertEqual(x, y) + def test_permute_is_generated_and_no_exec_clears_only_permute(self): + self.assertIn("permute", f.EXEC_KINDS) + found = 0 + for idx in range(40): + a = f.Program(1, idx, 64, permute=True) + b = f.Program(1, idx, 64, no_exec=("permute",), permute=True) + self.assertEqual(len(a.ops), len(b.ops)) + for x, y in zip(a.ops, b.ops): + if x["kind"] == "permute": + if x["exec"] is not None: + found += 1 + self.assertIsNone(y["exec"]) + self.assertEqual({k: v for k, v in x.items() if k not in ("exec", "hyp")}, + {k: v for k, v in y.items() if k not in ("exec", "hyp")}) + else: + self.assertEqual(x, y) + self.assertGreater(found, 0, "expected at least one permute op with non-None exec mask") + class Model(unittest.TestCase): def test_initial_lds_pattern(self): @@ -104,6 +122,48 @@ def test_bpermute_inactive_source_reads_zero(self): keep.ops = [] self.assertEqual(regs[9][21], keep.model()[0][9][21]) # lane 9 is off itself: keeps its value + def test_permute_collision_highest_active_wins_and_unaddressed_is_zero(self): + # All active lanes scatter to lane 5 in their own 32-lane half (mul=0, add=5, offset=0). + # EXEC: low half has lanes 0..7 active (highest active = 7); high half has lanes 32, 35, 40 active (highest = 40). + mask = 0xFF | (1 << 32) | (1 << 35) | (1 << 40) + p = f.Program(1, 0, 64) + p.ops = [{"kind": "permute", "mul": 0, "add": 5, "offset": 0, "src": 20, "dst": 21, "exec": mask}] + base = f.Program(1, 0, 64) + base.ops = [] + init_regs, _ = base.model() + regs, _ = p.model() + + # Low half: lane 5 is active and receives highest active source (lane 7). + self.assertEqual(regs[5][21], init_regs[7][20]) + # Low half: active lanes != 5 receive nobody -> 0. + for t in (0, 1, 2, 3, 4, 6, 7): + self.assertEqual(regs[t][21], 0) + # Low half: inactive lanes keep their original v21. + for t in (8, 15, 31): + self.assertEqual(regs[t][21], init_regs[t][21]) + # High half: target lane 32+5=37 is INACTIVE, so it keeps its original v21 even though 32,35,40 targeted it. + self.assertEqual(regs[37][21], init_regs[37][21]) + # High half: active lanes 32, 35, 40 receive nobody -> 0. + for t in (32, 35, 40): + self.assertEqual(regs[t][21], 0) + self.assertIn("ds_permute_b32 v21, v6, v20 offset:0", p.asm()) + + with f.perturbed("permute_lowest_wins"): + bad_regs, _ = p.model() + self.assertEqual(bad_regs[5][21], init_regs[0][20]) + + def test_permute_half_isolation_and_offset(self): + # Identity + offset:8 (+2 lanes) mod 32 within each 32-lane half, all lanes active. + p = f.Program(2, 1, 64) + p.ops = [{"kind": "permute", "mul": 1, "add": 0, "offset": 8, "src": 20, "dst": 22, "exec": None}] + base = f.Program(2, 1, 64) + base.ops = [] + init_regs, _ = base.model() + regs, _ = p.model() + for t in range(64): + src_lane = (t & ~31) | ((t - 2) & 31) + self.assertEqual(regs[t][22], init_regs[src_lane][20]) + def test_d16_hi_read_keeps_the_low_half(self): p = f.Program(1, 0, 64) p.ops = [{"kind": "read", "name": "ds_read_u16_d16_hi", "addr": (0, 0, 0), "dst": 20, "exec": None}] diff --git a/tests/test_lds_fuzz_hw.py b/tests/test_lds_fuzz_hw.py index 6041abfda9..986fddbb36 100644 --- a/tests/test_lds_fuzz_hw.py +++ b/tests/test_lds_fuzz_hw.py @@ -122,11 +122,13 @@ def test_permute_programs_carry_a_hypothesis(self): progs = f.programs(3, 40, (64, 32), permute=True) perm = [p for p in progs if any(op["kind"] == "permute" for op in p.ops)] self.assertTrue(perm) + parities = set() for p in perm: for i, op in enumerate(p.ops): self.assertEqual(i in p.hyp_ops, op["kind"] == "permute") if op["kind"] == "permute": - self.assertEqual(op["mul"] % 2, 1) # a bijection: no two lanes send to one lane + parities.add(op["mul"] % 2) + self.assertEqual(parities, {0, 1}) # generates both colliding and bijective multipliers def test_swizzle_exec_hypothesis_only_under_a_mask(self): progs = f.programs(3, 60, (32,), swizzle_exec=True) diff --git a/tools/lds_fuzz.py b/tools/lds_fuzz.py index 6b3bb4ca8f..fe838b123f 100644 --- a/tools/lds_fuzz.py +++ b/tools/lds_fuzz.py @@ -108,6 +108,7 @@ "swizzle_quad_reversed": ("swizzle", "the quad-permute selectors are taken in reverse lane order"), "swizzle_or_xor_swapped": ("swizzle", "the bit-mask or and xor fields are swapped"), "permute_no_zero": ("permute", "ds_permute_b32 leaves an unwritten lane's register alone instead of writing 0"), + "permute_lowest_wins": ("permute", "ds_permute_b32 lets the lowest active source lane win a collision"), } PERTURB = set() @@ -382,13 +383,13 @@ def make(self, kind): "offset": rng.choice([0, 0, 4 * rng.randrange(0, 64)]), "src": rng.choice(POOL), "dst": rng.choice(POOL), "exec": self.exec_mask()} if kind == "permute": - # an odd multiplier makes the lane -> lane map a bijection in a 32- and in a 64-lane group, so no two - # lanes send to the same lane and the result doesn't depend on which write wins - return {"kind": kind, "mul": rng.randrange(1, 64, 2), "add": rng.randrange(0, 64), + # allow both odd (bijective) and even (colliding) multipliers; RDNA2 hw (gfx1030, SHADER-133) and gfx1150 + # confirm the highest active source lane wins a collision, unaddressed active lanes get 0, halves separate + return {"kind": kind, "mul": rng.randrange(0, 64), "add": rng.randrange(0, 64), "offset": rng.choice([0, 0, 4 * rng.randrange(0, 64)]), "src": rng.choice(POOL), "dst": rng.choice(POOL), "exec": self.exec_mask(), - "hyp": "the ISA text: only active lanes send, a lane nobody sends to gets 0, each 32-lane half " - "is separate"} + "hyp": "only active lanes send, highest active sender wins collisions, a lane nobody sends to " + "gets 0, each 32-lane half is separate (measured on gfx1030 SHADER-133 and gfx1150)"} raise ValueError(kind) # ---- the program text ---- @@ -681,11 +682,12 @@ def model_op(self, op, regs, lds): for t, v in new.items(): regs[t][op["dst"]] = v elif k == "permute": - # forward permute: an active lane sends its data to lane (addr + offset) / 4 of its 32-lane group, an - # active lane gets what was sent to it, or 0 + # forward scatter within each 32-lane half: active lanes send to lane (addr + offset) / 4 of their 32-lane + # group; highest-numbered active source wins collisions; active destination lanes nobody targets get 0 src = [regs[t][op["src"]] for t in range(T)] sent = {} - for t in range(T): + lanes = range(T - 1, -1, -1) if "permute_lowest_wins" in PERTURB else range(T) + for t in lanes: if act[t]: word = ((t * op["mul"] + op["add"]) * 4 + op["offset"]) >> 2 sent[(t & ~31) | (word & 31)] = src[t] From 52dc48074dafb4eed77857bde941a5cb73ca3263 Mon Sep 17 00:00:00 2001 From: Leonardo Guimaraes Date: Sun, 22 Nov 2026 11:14:51 -0300 Subject: [PATCH 009/115] tools/imhex: ImHex pattern for PSIN containers psin.hexpat lays out a container as docs/psin.md describes it: the big-endian first-section offset, the instance-data block table (rows, the pppppppp end) and its blocks as raw bytes, the section chain, LSCH struct headers and members and LENM enums and values (header count by the fill-exact rule psin_index.py uses), the LSNS block table with opaque 16-byte records, the LRSC 0DRP version and root block, and the CHKS file size. A section past the end of a truncated stream is shown as raw bytes. tests/test_imhex_patterns.py builds a synthetic container from the invented schema in test_psin_index.py, checks it with psin_index.parse and psin_data.block_table, and when ImHex is installed compares the pattern's output with both, plus a container cut inside LENM. --- docs/psin.md | 15 +++ tests/test_imhex_patterns.py | 88 +++++++++++++++- tools/imhex/psin.hexpat | 193 +++++++++++++++++++++++++++++++++++ 3 files changed, 295 insertions(+), 1 deletion(-) create mode 100644 tools/imhex/psin.hexpat diff --git a/docs/psin.md b/docs/psin.md index 22ac8ab151..9999e89a97 100644 --- a/docs/psin.md +++ b/docs/psin.md @@ -467,6 +467,21 @@ section, truncated data, trailing bytes and the JSON CLI, and the `LSCH`/`LENM` a count that fits nothing and both schema checks. It uses synthetic headers and joaat hashes of invented names only. +### Viewing a container in ImHex + +[tools/imhex/psin.hexpat](../tools/imhex/psin.hexpat) is a pattern for the [ImHex](https://imhex.werwolv.net/) hex +editor that lays out one container as this page describes it: +- the header, the instance-data block table with its `pppppppp` end, and the blocks, as raw bytes; +- the section chain; +- the `LSCH` struct headers and members, and the `LENM` enums and values, with the header count found by the same + fill-exact rule as `psin_index.py`; +- the `LSNS` block table and its opaque 16-byte records; +- the `LRSC` `0DRP` version and root block, and the `CHKS` file size. + +A section that runs past the end of a truncated stream is shown as raw bytes. `tests/test_imhex_patterns.py` builds a +synthetic container, checks it with `psin_index.py` and `psin_data.block_table`, and when ImHex is installed compares +the pattern's output with both. + ## Limits - The 64 KiB split is not joined automatically. A caller that has the archive order can join adjacent diff --git a/tests/test_imhex_patterns.py b/tests/test_imhex_patterns.py index 9e0cc1ccaa..751de8b90c 100644 --- a/tests/test_imhex_patterns.py +++ b/tests/test_imhex_patterns.py @@ -3,7 +3,9 @@ python -I tests/test_imhex_patterns.py Every byte here is built by the test: no game file, name or path is used. The RBF0 inputs are first checked with -tools/rbf0_index.py, the repository's own parser. When ImHex is installed, each pattern then runs on the same bytes +tools/rbf0_index.py and the PSIN inputs with tools/psin_index.py and tools/psin_data.py, the repository's own +parsers (the PSIN schema reuses the invented names of tests/test_psin_index.py). When ImHex is installed, each pattern +then runs on the same bytes through ImHex's pattern-language CLI (`imhex --pl format ... -f json`) and the decoded fields are compared with the parser's result. ImHex is found through LEONIDA_IMHEX, then PATH, then its default Windows install folder; without it the ImHex half is skipped and the rest still runs. @@ -20,8 +22,12 @@ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PATTERNS = os.path.join(ROOT, "tools", "imhex") sys.path.insert(0, os.path.join(ROOT, "tools")) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import psin_data # noqa: E402 +import psin_index # noqa: E402 import rbf0_index # noqa: E402 +from test_psin_index import SCHEMA as PSIN_SCHEMA, joaat, make_lenm, make_lsch, make_section # noqa: E402 def find_imhex(): @@ -69,6 +75,27 @@ def rpf9_archive(data_offset=0x100, size=0x140): return head + toc + body +PSIN_BLOCKS = [(PSIN_SCHEMA[0][0], bytes(range(0x20))), (0x10, b"probe\x00"), (0x16, struct.pack("<3Q", 1, 2, 3))] +PSIN_ENUMS = [(joaat("ProbeEnum"), 0x33333333, [(0, joaat("PROBE_A")), (-1, joaat("PROBE_B"))])] +LSNS_BLOCKS = [(0x101, 32), (0x207, 16)] + + +def psin_container(lsns=True): + """A complete container (docs/psin.md): block table, blocks, LSCH, LENM, LSNS, LGID, LRSC (root 1), CHKS.""" + rows = b"".join(struct.pack("I", first + len(sections) + 16) + b"\x12\x34\x56\x78") + return b"PSIN" + struct.pack(">I", first) + rows + data + sections + + def pragma_magic(pattern): """The bytes of `#pragma magic [ .. ] @ 0x00` in a pattern file.""" with open(os.path.join(PATTERNS, pattern), encoding="utf-8") as f: @@ -92,9 +119,20 @@ def test_synthetic_streams_parse(self): self.assertEqual(r["elements"], 2) self.assertEqual(r["descriptors"], 7) + def test_synthetic_psin_parses(self): + blob = psin_container() + r = psin_index.parse(blob, schema=True) + self.assertTrue(r["complete"], r["error"]) + self.assertEqual(r["schema"]["reason"], "") + self.assertEqual(r["lsns_blocks"], len(LSNS_BLOCKS)) + blocks, exact = psin_data.block_table(blob, r["first_section"]) + self.assertTrue(exact) + self.assertEqual([(t, n) for t, _at, n in blocks], [(t, len(d)) for t, d in PSIN_BLOCKS]) + def test_pattern_magics(self): self.assertEqual(pragma_magic("rbf0.hexpat"), rbf0_index.MAGIC) self.assertEqual(pragma_magic("rpf9.hexpat"), b"9FPR") # RPF9 stored little-endian (docs/rpf.md) + self.assertEqual(pragma_magic("psin.hexpat"), psin_index.MAGIC) @unittest.skipUnless(IMHEX, "ImHex is not installed (set LEONIDA_IMHEX to imhex.exe)") @@ -160,6 +198,54 @@ def test_rpf9_header_and_opaque_toc(self): self.assertEqual((got["header"]["u32_08"], got["header"]["u32_0c"]), (0x11, 0x22)) self.assertEqual(len(got["header_rest_and_toc"]), 0x100 - 0x10) + def test_psin_matches_psin_index_and_psin_data(self): + blob = psin_container() + ref = psin_index.parse(blob, schema=True) + table, _exact = psin_data.block_table(blob, ref["first_section"]) + got, log = self.run_pattern("psin.hexpat", blob) + self.assertIsNotNone(got, log) + self.assertEqual(got["header"]["first_section"], ref["first_section"]) + + # Block table: rows, the "pppppppp" end, and each block's data where psin_data places it. + self.assertEqual([(r["type"], r["size"]) for r in got["rows"]], [(t, n) for t, _at, n in table]) + self.assertEqual(got["table_end"], "pppppppp") + self.assertEqual([bytes(b["data"]) for b in got["blocks"]], [blob[at:at + n] for _t, at, n in table]) + + sections = {s["tag"]: s for s in got["sections"]} + self.assertEqual([(s["tag"], s["size"]) for s in got["sections"]], + [(s["tag"], s["size"]) for s in ref["sections"]]) + schema = ref["schema"] + self.assertEqual([s["name_hash"] for s in sections["LSCH"]["structs"]], + [int(s["hash"], 16) for s in schema["structs"]]) + self.assertEqual([(m["name_hash"], m["offset"], m["type"], m["index"], m["ref_hash"]) + for m in sections["LSCH"]["members"]], + [(int(m["hash"], 16), m["offset"], m["type"], m["index"], int(m["ref"], 16)) + for s in schema["structs"] for m in s["members"]]) + self.assertEqual([e["value_count"] for e in sections["LENM"]["enums"]], + [len(e["values"]) for e in schema["enums"]]) + self.assertEqual([v["value"] for v in sections["LENM"]["values"]], + [v["value"] for e in schema["enums"] for v in e["values"]]) + lsns = next(s for s in ref["sections"] if s["tag"] == "LSNS") + self.assertEqual([(d["kind"], d["bytes"]) for d in sections["LSNS"]["descs"]], + [(int(b["kind"], 16), b["bytes"]) for b in lsns["blocks"]]) + self.assertEqual([len(b["records"]) for b in sections["LSNS"]["lsns_blocks"]], [n // 16 for _k, n in LSNS_BLOCKS]) + self.assertEqual(sections["LRSC"]["rsc_version"], ref["rsc_version"]) + self.assertEqual(sections["LRSC"]["root_block"], 1) + self.assertEqual(sections["CHKS"]["checksum_size"], ref["checksum_size"]) + + def test_psin_truncated_keeps_the_whole_sections(self): + blob = psin_container(lsns=False) + first = struct.unpack_from(">I", blob, 4)[0] + lsch_size = struct.unpack_from(">I", blob, first + 4)[0] + cut = blob[:first + lsch_size + 20] # inside LENM + self.assertFalse(psin_index.parse(cut)["complete"]) + got, log = self.run_pattern("psin.hexpat", cut) + self.assertIsNotNone(got, log) + tags = [s["tag"] for s in got["sections"]] + self.assertEqual(tags, ["LSCH", "LENM"]) + self.assertIn("structs", got["sections"][0]) + self.assertEqual(len(got["sections"][1]["truncated"]), 12) # what is left after LENM's 8-byte header + def test_rpf9_rejects_a_data_offset_past_the_end(self): got, log = self.run_pattern("rpf9.hexpat", rpf9_archive(data_offset=0x100, size=0x140)[:0x20]) self.assertIsNone(got) diff --git a/tools/imhex/psin.hexpat b/tools/imhex/psin.hexpat new file mode 100644 index 0000000000..c3dc014d90 --- /dev/null +++ b/tools/imhex/psin.hexpat @@ -0,0 +1,193 @@ +// ImHex pattern for a PSIN metadata container (docs/psin.md; tools/psin_index.py and tools/psin_data.py read it). +// +// Layout, as measured in docs/psin.md: +// 0x00 "PSIN" +// 0x04 big-endian absolute offset of the first section +// 0x08 instance-data block table: rows of {u32 block type, u32 data size, aa x 8}, ended by "pppppppp" 8 bytes +// short of a 16-byte boundary. The blocks follow in table order, each padded to 16 bytes, numbered from 1; +// the last one ends at the first section. Their contents are shown as raw bytes: decoding them needs the +// schema walk that psin_data.py does. +// sections from the first-section offset to EOF: ASCII tag, big-endian total size (header included) +// LSCH struct headers (32 bytes) then all members (16 bytes); the header count is not stored, it is the one +// count whose headers and members fill the payload exactly +// LENM enum headers (24 bytes) then all values (16 bytes); same rule +// LSNS u32 block count, {u32 kind, u32 byte count} per block, then the blocks: opaque 16-byte records +// LRSC "0DRP", u32 version, ...; the u32 at +0x10 is the root block number +// CHKS big-endian file size and a 32-bit value (not verified here) +// LGID empty +// Little-endian everywhere except the first-section offset and the section sizes. A truncated container shows what +// is whole and the rest as raw bytes. + +#pragma description PSIN metadata container: block table, LSCH/LENM schema, LSNS, LRSC, CHKS (docs/psin.md) +#pragma endian little +#pragma magic [ 50 53 49 4E ] @ 0x00 +#pragma array_limit 1048576 +#pragma pattern_limit 8388608 + +import std.mem; +import std.core; + +// ---- header and instance-data block table --------------------------------------------------------------------- + +struct Header { + char magic[4]; + be u32 first_section [[comment("big-endian absolute offset of the first section")]]; +}; + +Header header @ 0x00; + +fn count_rows(u128 limit) { + u128 p = 0x08; + u32 n = 0; + while (p + 16 <= limit && std::mem::read_unsigned(p, 8) != 0x7070707070707070) { + p += 16; + n += 1; + } + return n; +}; + +u128 g_limit = header.first_section < std::mem::size() ? header.first_section : std::mem::size(); +u32 g_rows = count_rows(g_limit); + +struct BlockRow { + u32 type [[comment("struct name hash from LSCH, a member type code below 0x100, or 0x100 + n")]]; + u32 size [[comment("data size in bytes")]]; + u8 fill[8] [[comment("aa x 8")]]; +}; + +struct Block { + u32 i = std::core::array_index(); + u8 data[rows[i].size] [[comment("block number i + 1; raw: see psin_data.py")]]; + u8 pad[(16 - rows[i].size % 16) % 16]; +}; + +BlockRow rows[g_rows] @ 0x08; +char table_end[8] @ 0x08 + 16 * g_rows [[comment("\"pppppppp\"")]]; +Block blocks[g_rows] @ 0x08 + 16 * g_rows + 8; + +// ---- sections --------------------------------------------------------------------------------------------------- + +fn header_count(u128 payload, u128 length, u32 header_size, u32 element_size, u32 count_at, u32 count_size) { + if (length == 0) return 0; + u32 elements = 0; + u32 k = 1; + while (header_size * k <= length) { + elements += std::mem::read_unsigned(payload + header_size * (k - 1) + count_at, count_size); + if (header_size * k + element_size * elements == length) return k; + k += 1; + } + return 0xFFFFFFFF; // no count fits: shown as raw bytes +}; + +fn sum_counts(u128 payload, u32 k, u32 header_size, u32 count_at, u32 count_size) { + u32 total = 0; + for (u32 i = 0, i < k, i += 1) { + total += std::mem::read_unsigned(payload + header_size * i + count_at, count_size); + } + return total; +}; + +struct StructHeader { + u32 name_hash; + u32 signature [[comment("layout signature")]]; + u8 flags; + u8 align_log2; + u16 zero_0a; + u32 zero_0c; + u8 fill[8] [[comment("aa x 8")]]; + u32 size [[comment("byte size of the struct")]]; + u16 zero_1c; + u16 member_count; +}; + +struct Member { + u32 name_hash [[comment("0x100 = array element descriptor")]]; + u32 offset; + u8 type; + u8 sub; + u16 index [[comment("for type 0x5c: position of its 0x100 element descriptor in this struct's members")]]; + u32 ref_hash [[comment("struct or enum name hash for the referring types, else 0")]]; +}; + +struct EnumHeader { + u32 name_hash; + u32 signature; + u8 fill[8] [[comment("ee x 8")]]; + u32 value_count; + u32 zero_14; +}; + +struct EnumValue { + s64 value; + u64 name_hash [[comment("case-sensitive joaat in the low half")]]; +}; + +struct LsnsDesc { + u32 kind; + u32 bytes; +}; + +struct LsnsRecord { + u8 bytes[16] [[comment("opaque")]]; +}; + +struct LsnsBlock { + u32 i = std::core::array_index(); + LsnsRecord records[parent.descs[i].bytes / 16]; +}; + +bool g_bad = false; + +struct Section { + char tag[4]; + be u32 size [[comment("big-endian total size, header included")]]; + u128 payload = $; + if (size < 8 || addressof(tag) + size > std::mem::size()) { + g_bad = true; + u8 truncated[std::mem::size() - $] [[comment("section runs past the end of the file")]]; + } else { + u32 length = size - 8; + if (tag == "LSCH") { + u32 k = header_count(payload, length, 32, 16, 30, 2); + if (k == 0xFFFFFFFF) { + u8 raw[length] [[comment("no struct count fills the payload")]]; + } else { + StructHeader structs[k]; + Member members[sum_counts(payload, k, 32, 30, 2)]; + } + } else if (tag == "LENM") { + u32 k = header_count(payload, length, 24, 16, 16, 4); + if (k == 0xFFFFFFFF) { + u8 raw[length] [[comment("no enum count fills the payload")]]; + } else { + EnumHeader enums[k]; + EnumValue values[sum_counts(payload, k, 24, 16, 4)]; + } + } else if (tag == "LSNS" && length >= 4) { + u32 block_count; + if (4 + 8 * block_count <= length) { + LsnsDesc descs[block_count]; + LsnsBlock lsns_blocks[block_count]; + } + if ($ < payload + length) { + u8 rest[payload + length - $] [[comment("does not fit the block table")]]; + } + } else if (tag == "LRSC" && length >= 0x14 && std::mem::read_string(payload, 4) == "0DRP") { + char rsc_magic[4]; + u32 rsc_version; + u32 u32_08; + u32 u32_0c; + u32 root_block [[comment("block number of the root struct")]]; + u8 rest[length - 0x14]; + } else if (tag == "CHKS" && length >= 8) { + be u32 checksum_size [[comment("big-endian file size")]]; + u8 checksum[4] [[comment("32-bit value, not verified")]]; + u8 rest[length - 8]; + } else { + u8 raw[length]; + } + } +}; + +Section sections[while(!g_bad && header.first_section + 8 <= std::mem::size() && std::mem::size() - $ >= 8)] + @ header.first_section; From 0f474bb54c228d9c6604a55631d992d243f9d625 Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:15:07 +0100 Subject: [PATCH 010/115] Test hard edges between explicit and generated OBJ normals --- tests/test_glb_writer.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/tests/test_glb_writer.py b/tests/test_glb_writer.py index ac3dcdbea3..840fec1261 100644 --- a/tests/test_glb_writer.py +++ b/tests/test_glb_writer.py @@ -748,6 +748,25 @@ def test_parse_obj_generated_normals_cross_uv_seams(self): for actual, target in zip(normals[position, uv], expected_normal): self.assertAlmostEqual(actual, target) + def test_parse_obj_explicit_faces_preserve_generated_hard_edge(self): + # A top face without normals shares two positions with a fully normaled side. + vertices = ["v 0 1 0", "v 1 1 0", "v 1 1 1", "v 0 1 1", "v 0 0 1", "v 1 0 1"] + top = "f 1 4 3 2" + side = "f 5//1 6//1 3//1 4//1" + for faces in ((top, side), (side, top)): + with self.subTest(first_face=faces[0]): + obj_text = "\n".join([*vertices, "vn 0 0 1", *faces]) + prim, = glb_writer.parse_obj(obj_text, is_path=False, up_axis="y") + normals_by_face = [ + {(0.0, 1.0, 0.0)} if face == top else {(0.0, 0.0, 1.0)} + for face in faces + ] + self.assertEqual(len(prim["positions"]), 8) + self.assertEqual(len(prim["indices"]), 12) + for start, expected in zip((0, 6), normals_by_face): + actual = {prim["normals"][i] for i in prim["indices"][start:start + 6]} + self.assertEqual(actual, expected) + def test_parse_obj_quad_fan_triangulation(self): obj_text = "\n".join([ "v 0 0 0", From ea2f274a27b143b2fdd638bbee2ff0a8ca21b781 Mon Sep 17 00:00:00 2001 From: SHAURYASANYAL3 Date: Sun, 22 Nov 2026 19:44:11 +0530 Subject: [PATCH 011/115] xgameruntime: implement XPackageGetCurrentProcessPackagePath, XPackageIsPackagedProcess, XSystemGetAnalyticsInfo --- runtime/shims/xgameruntime.cpp | 71 ++++++++++++++++++++++++++++++ runtime/test/xgameruntime_test.cpp | 38 ++++++++++++++++ 2 files changed, 109 insertions(+) diff --git a/runtime/shims/xgameruntime.cpp b/runtime/shims/xgameruntime.cpp index 8135589b92..0bd1d879da 100644 --- a/runtime/shims/xgameruntime.cpp +++ b/runtime/shims/xgameruntime.cpp @@ -156,6 +156,74 @@ uint64_t __stdcall XSystemGetAppMemoryUsage() { return 0; } +// XSystemAnalyticsInfo: hardware and OS version telemetry requested during engine startup. +struct XSystemAnalyticsInfo { + char osVersion[128]; + char hostingOsVersion[128]; + char family[64]; + char form[64]; +}; + +// HRESULT XSystemGetAnalyticsInfo(XSystemAnalyticsInfo* info). +HRESULT __stdcall XSystemGetAnalyticsInfo(XSystemAnalyticsInfo* info) { + if (!info) return E_INVALIDARG; + std::memset(info, 0, sizeof(*info)); + std::strncpy(info->osVersion, "10.0.22000.0", sizeof(info->osVersion) - 1); + std::strncpy(info->hostingOsVersion, "10.0.22000.0", sizeof(info->hostingOsVersion) - 1); + std::strncpy(info->family, "Xbox", sizeof(info->family) - 1); + + const uint32_t dt = XSystemGetDeviceType(); + if (dt == static_cast(XSystemDeviceType::XboxScarlettLockhart)) { + std::strncpy(info->form, "Lockhart", sizeof(info->form) - 1); + } else { + std::strncpy(info->form, "Anaconda", sizeof(info->form) - 1); + } + return S_OK; +} + +// ---- XPackage ---- + +// HRESULT XPackageGetCurrentProcessPackagePath(size_t pathSize, char* path). +// Retrieves the path of the installed package for the current process. +// Reads LEONIDA_GAME_DIR when set, otherwise falls back to the current module's directory. +HRESULT __stdcall XPackageGetCurrentProcessPackagePath(size_t pathSize, char* path) { + if (!path || pathSize == 0) return E_INVALIDARG; + + char buf[MAX_PATH] = {}; + const DWORD n = GetEnvironmentVariableA("LEONIDA_GAME_DIR", buf, sizeof(buf)); + if (n == 0 || n >= sizeof(buf)) { + const DWORD mod_len = GetModuleFileNameA(nullptr, buf, sizeof(buf)); + if (mod_len > 0 && mod_len < sizeof(buf)) { + char* slash = std::strrchr(buf, '\\'); + char* fslash = std::strrchr(buf, '/'); + char* last = slash > fslash ? slash : fslash; + if (last) { + *last = '\0'; + } else { + std::strcpy(buf, "."); + } + } else { + std::strcpy(buf, "."); + } + } + + const size_t len = std::strlen(buf); + if (pathSize < len + 1) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); + std::memcpy(path, buf, len + 1); + return S_OK; +} + +// bool XPackageIsPackagedProcess(). +// Returns true on Xbox Series console. LEONIDA_PACKAGED=0 overrides it. +bool __stdcall XPackageIsPackagedProcess() { + char s[16]; + const DWORD n = GetEnvironmentVariableA("LEONIDA_PACKAGED", s, sizeof(s)); + if (n > 0 && n < sizeof(s)) { + if (std::atoi(s) == 0) return false; + } + return true; +} + #define XGR(name) {"xgameruntime.dll", #name, reinterpret_cast(&name)} } // namespace @@ -173,6 +241,9 @@ SHIM_TABLE(xgameruntime, XGR(XSystemGetConsoleId), XGR(XSystemGetAppMemoryUsageLimit), XGR(XSystemGetAppMemoryUsage), + XGR(XSystemGetAnalyticsInfo), + XGR(XPackageGetCurrentProcessPackagePath), + XGR(XPackageIsPackagedProcess), // XTaskQueue (third_party/xtaskqueue) XGR(XTaskQueueCreate), XGR(XTaskQueueCreateComposite), diff --git a/runtime/test/xgameruntime_test.cpp b/runtime/test/xgameruntime_test.cpp index ac36f40d96..2508cd1230 100644 --- a/runtime/test/xgameruntime_test.cpp +++ b/runtime/test/xgameruntime_test.cpp @@ -51,8 +51,20 @@ using AsyncCompleteFn = void(__stdcall*)(XAsyncBlock*, HRESULT, size_t); using AsyncResultSizeFn = HRESULT(__stdcall*)(XAsyncBlock*, size_t*); using AsyncResultFn = HRESULT(__stdcall*)(XAsyncBlock*, const void*, size_t, void*, size_t*); +struct XSystemAnalyticsInfo { + char osVersion[128]; + char hostingOsVersion[128]; + char family[64]; + char form[64]; +}; + +using AnalyticsInfoFn = HRESULT(__stdcall*)(XSystemAnalyticsInfo*); +using PackagePathFn = HRESULT(__stdcall*)(size_t, char*); +using PackagedProcessFn = bool(__stdcall*)(); + const char* const kNames[] = { "XGameRuntimeInitialize", "XGameRuntimeUninitialize", "XSystemGetDeviceType", "XSystemGetConsoleId", + "XSystemGetAnalyticsInfo", "XPackageGetCurrentProcessPackagePath", "XPackageIsPackagedProcess", "XTaskQueueCreate", "XTaskQueueCreateComposite", "XTaskQueueGetPort", "XTaskQueueDuplicateHandle", "XTaskQueueCloseHandle", "XTaskQueueTerminate", "XTaskQueueDispatch", "XTaskQueueSubmitCallback", "XTaskQueueSubmitDelayedCallback", "XTaskQueueRegisterWaiter", "XTaskQueueUnregisterWaiter", @@ -229,6 +241,32 @@ int main() { check(console_id(sizeof(id), id, &used) == S_OK && used == 39 && std::strlen(id) == 38, "XSystemGetConsoleId fills 39 bytes (38 characters and the terminator)"); + auto analytics_info = get("XSystemGetAnalyticsInfo"); + check(analytics_info(nullptr) == E_INVALIDARG, "XSystemGetAnalyticsInfo rejects null pointer"); + XSystemAnalyticsInfo info{}; + check(analytics_info(&info) == S_OK && std::strcmp(info.family, "Xbox") == 0 && + std::strcmp(info.osVersion, "10.0.22000.0") == 0 && std::strcmp(info.form, "Anaconda") == 0, + "XSystemGetAnalyticsInfo populates Xbox Anaconda analytics info"); + + auto package_path = get("XPackageGetCurrentProcessPackagePath"); + check(package_path(0, nullptr) == E_INVALIDARG, "XPackageGetCurrentProcessPackagePath rejects null pointer and size 0"); + char pkg_path[MAX_PATH] = {}; + check(package_path(0, pkg_path) == E_INVALIDARG, "XPackageGetCurrentProcessPackagePath rejects size 0 with buffer"); + check(package_path(10, nullptr) == E_INVALIDARG, "XPackageGetCurrentProcessPackagePath rejects null pointer with size"); + + SetEnvironmentVariableA("LEONIDA_GAME_DIR", "C:\\LeonidaGameDir"); + check(package_path(5, pkg_path) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER), + "XPackageGetCurrentProcessPackagePath rejects insufficient buffer"); + check(package_path(sizeof(pkg_path), pkg_path) == S_OK && std::strcmp(pkg_path, "C:\\LeonidaGameDir") == 0, + "XPackageGetCurrentProcessPackagePath returns configured game directory"); + SetEnvironmentVariableA("LEONIDA_GAME_DIR", nullptr); + + auto is_packaged = get("XPackageIsPackagedProcess"); + check(is_packaged() == true, "XPackageIsPackagedProcess returns true by default"); + SetEnvironmentVariableA("LEONIDA_PACKAGED", "0"); + check(is_packaged() == false, "XPackageIsPackagedProcess respects LEONIDA_PACKAGED=0 override"); + SetEnvironmentVariableA("LEONIDA_PACKAGED", nullptr); + // Work on the thread pool, completions dispatched by the "game loop" on this thread. auto create = get("XTaskQueueCreate"); auto close = get("XTaskQueueCloseHandle"); From 7edd7a187dabd0ecfb6f9b4881e786eefa49a4e7 Mon Sep 17 00:00:00 2001 From: Kam471 <115741199+Kam471@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:15:48 +0000 Subject: [PATCH 012/115] docs: the Opus length check must read decoded frames, not the granule duration --- docs/audio.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/audio.md b/docs/audio.md index 481157c9d2..d02f07d07b 100644 --- a/docs/audio.md +++ b/docs/audio.md @@ -339,7 +339,10 @@ the audio itself is not. See the ground rules in [design.md](design.md#ground-ru ## What has been checked -- 300 random Opus streams decode with ffmpeg with no errors; their lengths match the declared sample counts. +- 20 real Opus streams (6 at 48 kHz, 14 at 32 kHz) decode with ffmpeg to exactly their declared + per-channel frame counts after the EOS fix; 300 random streams decode with no errors. The earlier + "lengths match" check read the granule-derived duration, not decoded frames, so it did not catch + the backwards-EOS case. - All 1,818 XMA2 streams decode after `rpf9dump xma`. - A 4-channel streamed-music bank gives four 42.0 s mono channels with real levels and no decoder errors. - A 1-channel streamed-music descriptor can carry stereo Opus packets; it exports as one stereo Ogg with the From 74205e9d785a99d2794c0ec6b3c02fff1758c7da Mon Sep 17 00:00:00 2001 From: Serrambi <10066198+Serrambi@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:16:07 +0100 Subject: [PATCH 013/115] d3d12: enforce DENY_* heap flags for all placed resources (D3D-222) --- runtime/shims/d3d12_vulkan_device.cpp | 6 +++++- runtime/test/d3d12_vulkan_device_test.cpp | 13 +++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 5b8312ef52..9673f05c9b 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -3895,18 +3895,22 @@ class Device final const bool tiled = is_tiled_layout(desc->Layout); const bool msaa = desc->SampleDesc.Count > 1; if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { + if (heap->flags() & D3D12_HEAP_FLAG_DENY_BUFFERS) return E_INVALIDARG; if (desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return E_INVALIDARG; if (desc->Width > heap->bytes() || heap_offset > heap->bytes() - desc->Width) return E_INVALIDARG; } else { if (heap->properties().Type == D3D12_HEAP_TYPE_UPLOAD || heap->properties().Type == D3D12_HEAP_TYPE_READBACK) return E_INVALIDARG; + const bool rt_ds = (desc->Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) != 0; + if (rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES)) return E_INVALIDARG; + if (!rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES)) return E_INVALIDARG; if (tiled || msaa) { if (tiled && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) return E_INVALIDARG; if (msaa && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return E_INVALIDARG; - if (msaa && (heap->flags() & D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES)) return E_INVALIDARG; const D3D12_RESOURCE_ALLOCATION_INFO alloc = allocation(*desc); if (alloc.SizeInBytes == UINT64_MAX || heap->alignment() < alloc.Alignment || heap_offset % alloc.Alignment || alloc.SizeInBytes > heap->bytes() || diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp index 15b18dab62..e066ef0fbd 100644 --- a/runtime/test/d3d12_vulkan_device_test.cpp +++ b/runtime/test/d3d12_vulkan_device_test.cpp @@ -3970,6 +3970,7 @@ int main() { {msaa_heap.p, msaa_heap_desc.SizeInBytes - 65536, msaa_unk_small_desc}, {upload_placed_heap.p, 0, msaa_unk_small_desc}, {deny_rt_heap.p, 0, msaa_unk_small_desc}, + {deny_rt_heap.p, 0, tiled_rt_desc}, {msaa_heap.p, 0, msaa_desc(256, 256, 4, 0, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE)}, {msaa_heap.p, 0, @@ -3986,6 +3987,18 @@ int main() { nullptr, IID_PPV_ARGS(&fail.p)) == E_INVALIDARG); EXPECT(!fail.p); } + D3D12_HEAP_DESC only_rt_desc = tiled_heap_desc; + only_rt_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES; + Ref only_rt_heap; + EXPECT(SUCCEEDED(standalone->CreateHeap(&only_rt_desc, IID_PPV_ARGS(&only_rt_heap.p)))); + for (const D3D12_RESOURCE_DESC& bad_only_rt : + {texture_desc(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE, 1), + buffer_desc(4096)}) { + Ref fail; + EXPECT(standalone->CreatePlacedResource(only_rt_heap.p, 0, &bad_only_rt, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&fail.p)) == E_INVALIDARG); + EXPECT(!fail.p); + } } // Clear placed 4x MSAA RTVs (UNKNOWN + tiled) and DSV, resolve, and read back to verify GPU execution. From db60a73affe5c0e0bdd5cda9d8d23cc0a205a395 Mon Sep 17 00:00:00 2001 From: Vonsek <45567075+Vonsek@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:16:14 +0100 Subject: [PATCH 014/115] fix(test): forward the texture readback emulator The synchronization check launches the test executable itself, so pass the configured Wine or Proton command through its environment wrapper. --- runtime/test/check_texture_readback_sync.cmake | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/runtime/test/check_texture_readback_sync.cmake b/runtime/test/check_texture_readback_sync.cmake index f821567898..81ef3f24ea 100644 --- a/runtime/test/check_texture_readback_sync.cmake +++ b/runtime/test/check_texture_readback_sync.cmake @@ -1,10 +1,11 @@ # Run with -DTOOL= -DSPIRV= # -DOUTPUT= -P runtime/test/check_texture_readback_sync.cmake. +# For a cross build, pass the configured emulator as "-DRUNNER=". # Requires the Khronos validation layer and a device that supports the texture harness. execute_process( COMMAND "${CMAKE_COMMAND}" -E env VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation VK_LOADER_DEBUG=layer VK_LAYER_ENABLES=VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT - "${TOOL}" cube "${OUTPUT}" + ${RUNNER} "${TOOL}" cube "${OUTPUT}" WORKING_DIRECTORY "${SPIRV}" TIMEOUT 90 RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log) if(NOT code STREQUAL "0" OR NOT log MATCHES "vk_texture_test cube: PASSED" From 3784aacc3a3c858bed503ec9fb92d88b6f9edb1a Mon Sep 17 00:00:00 2001 From: Ryx <118130241+Ryx69@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:17:03 +0100 Subject: [PATCH 015/115] Revert the occlusion pause; add --no-draw and --no-resolve to --bisect (D3D-189) The 8060S retest of c8ea00e4 (#1540) loses the device in every phase that runs a hardware occlusion query, including nested and binary, which never resolve inside an active query, and active with the pause applied. Only unwritten, with no hardware query, passes. So the resolve-while-active rule did not fix it; vulkan_replay.h and docs/d3d12_vulkan.md go back to main. Every hanging phase both draws inside a query (an attachmentless rendering scope inside a query begun outside rendering) and resolves through the copy and compute helpers. --no-draw leaves every query empty and --no-resolve never copies or sums results, so the four combinations tell the two apart. The bisect run prints which switches are on. The resolve inside one active query stays in the default run and as the "active" phase; the crossing schedule is back to three segment ends. --- docs/d3d12_vulkan.md | 10 ++-- runtime/src/vulkan_replay.h | 37 ++++---------- .../test/vk_overlapping_occlusion_test.cpp | 48 ++++++++++++------- 3 files changed, 42 insertions(+), 53 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 3438f36e3a..7622cb4ac4 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1808,13 +1808,9 @@ Implemented (`QueryHeap` in `runtime/shims/d3d12_vulkan_device.cpp`, the query c submission's physical pool. Resolving it sums the 64-bit counts on the GPU, then copies the result to the destination. Both occlusion compute helpers reuse one scratch buffer per queue. Logical results and in-flight submissions retain the pool independently, so later resolves and - overwrites can be recorded before the earlier commands complete. A resolve while an ordinary query is active - ends the active physical query before the resolve and begins the next one after it, and a list with such a - resolve takes this path even without an overlap: AMD's Windows driver on a Radeon 8060S times out (TDR) on a - query copy and summing dispatch recorded while a query of the same pool is active (D3D-189, #1540). - `vk_overlapping_occlusion` checks crossing and nested scopes, a resolve inside a single active query, more than - one scratch chunk, alternating binary and ordinary resolves under a predicate, and gated submissions on a GPU; - `--bisect` runs its patterns one per submission to find one that hangs a device. + overwrites can be recorded before the earlier commands complete. `vk_overlapping_occlusion` checks crossing + and nested scopes, more than one scratch chunk, alternating binary and ordinary resolves under a predicate, + and gated submissions on a GPU. - **Timestamps.** `GetTimestampFrequency` is `1e9 / timestampPeriod` (1 GHz on the test GPU). Every D3D12 queue shares one `VkQueue` for now (question 12), so they share one frequency. diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index bde9b57709..8f1e17213a 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -1647,19 +1647,11 @@ class PreparedList { inline ReplayResult plan_occlusion_segments(PreparedList& out) { // Active logical queries cover a contiguous range of physical slots. A Begin or End closes the old // slot and opens a new one if any query remains active. Each shared interval is recorded only once. - // A resolve while a slot is active closes it before the resolve and opens the next after it, so no query is - // active during the copy and its dispatch (D3D-189); the logical ranges simply span one more slot. std::map, std::uint32_t> active; std::uint32_t current = detail::PreparedQuery::no_segment; for (auto& query : out.queries) { const Command& command = out.list->commands()[query.command]; - if (std::holds_alternative(command)) { - if (current == detail::PreparedQuery::no_segment) continue; - query.end_segment = current; - current = out.segment_count++; - query.begin_segment = current; - continue; - } + if (std::holds_alternative(command)) continue; const auto range = query_range(command); if (range.type != d3d12_query::occlusion) continue; const auto key = std::pair{range.heap, range.first}; @@ -2059,11 +2051,6 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun // The internal dispatch would otherwise count towards the application's CSInvocations. if (!vk.resolve_binary_occlusion || statistics_active) return ReplayResult::unsupported; } - // No resolve runs while an ordinary occlusion query is active: AMD's Windows driver (Radeon 8060S, - // 26.10.1) times out on vkCmdCopyQueryPoolResults with WAIT_BIT, or the summing dispatch, recorded - // while a query of the same pool is active (D3D-189, #1540). The segment path can pause the active - // query around the resolve (plan_occlusion_segments), so such a list takes it when it can sum. - if (ordinary_active && vk.sum_occlusion) overlaps = true; if (p.binding.host_readable) { out.wrote_readback = true; out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; @@ -2211,21 +2198,16 @@ class QueryReplay { inline void emit_query(const PreparedList& list, const detail::PreparedQuery& query, VkCommandBuffer cb, const ReplayFunctions& vk, const VkConditionalRenderingBeginInfoEXT& predicate) { constexpr auto none = detail::PreparedQuery::no_segment; - const auto& command = list.list->commands()[query.command]; - // A Begin or End of a segmented query only moves between segments. A resolve inside a segment ends it before - // the resolve and begins the next one after it. - const bool segmented = query.end_segment != none || query.begin_segment != none; - if (query.end_segment != none) vk.end_query(cb, list.segment_pool, list.segment_base + query.end_segment); - const auto begin_segment = [&] { - if (query.begin_segment == none) return; - const auto index = list.segment_base + query.begin_segment; - vk.reset_query_pool(cb, list.segment_pool, index, 1); - vk.begin_query(cb, list.segment_pool, index, list.precise_segments ? VK_QUERY_CONTROL_PRECISE_BIT : 0); - }; - if (segmented && !std::holds_alternative(command)) { - begin_segment(); + if (query.end_segment != none || query.begin_segment != none) { + if (query.end_segment != none) vk.end_query(cb, list.segment_pool, list.segment_base + query.end_segment); + if (query.begin_segment != none) { + const auto index = list.segment_base + query.begin_segment; + vk.reset_query_pool(cb, list.segment_pool, index, 1); + vk.begin_query(cb, list.segment_pool, index, list.precise_segments ? VK_QUERY_CONTROL_PRECISE_BIT : 0); + } return; } + const auto& command = list.list->commands()[query.command]; const QueryPool& heap = *query.heap; if (const auto* begin = std::get_if(&command)) { vk.reset_query_pool(cb, heap.pool, begin->index, 1); @@ -2261,7 +2243,6 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu } } if (suspend) vk.begin_conditional_rendering(cb, &predicate); - begin_segment(); } } diff --git a/runtime/test/vk_overlapping_occlusion_test.cpp b/runtime/test/vk_overlapping_occlusion_test.cpp index e92d1ef069..e45331b063 100644 --- a/runtime/test/vk_overlapping_occlusion_test.cpp +++ b/runtime/test/vk_overlapping_occlusion_test.cpp @@ -133,13 +133,14 @@ struct Draws { std::vector extents; std::size_t next = 0; bool overflow = false; - bool every = false; // --bisect: one 1x1 draw before every end, no schedule + bool every = false; // --bisect: one 1x1 draw before every end, no schedule + bool no_draw = false; // --bisect --no-draw: no draws at all, every query stays empty }; Draws* draws = nullptr; VKAPI_ATTR void VKAPI_CALL end_query_with_draw(VkCommandBuffer cb, VkQueryPool pool, std::uint32_t index) { if (draws->every) { - draws->fixture.draw(cb, 1); + if (!draws->no_draw) draws->fixture.draw(cb, 1); } else if (draws->next == draws->extents.size()) { draws->overflow = true; } else if (const auto extent = draws->extents[draws->next++]) { @@ -157,9 +158,13 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device_proc(VkDevice device, const // submission is waited for before the next, so the last "running" line before a hang or a lost device names the // pattern. --gated queues them all behind one semaphore the CPU signals afterwards, as the full test does. Named // phases run only those, in the order below. Only completion is checked, not values. +// Two switches separate the draw from the resolve: --no-draw leaves every query empty (no rendering scope inside +// it), --no-resolve records the queries but never copies or sums their results. struct Bisect { bool enabled = false; bool gated = false; + bool no_draw = false; + bool no_resolve = false; std::vector phases; bool wants(const char* name) const { return phases.empty() || std::find(phases.begin(), phases.end(), name) != phases.end(); @@ -178,11 +183,11 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec Fixture fixture{d}; EXPECT(fixture.create(vertex, fragment)); constexpr std::uint32_t bursts = 130; - // crossing ends four physical queries (the resolve inside it splits the last one), nested three. - Draws schedule{fixture, {8, 4, 2, 0, 8, 4, 2, 3}}; + Draws schedule{fixture, {8, 4, 2, 8, 4, 2, 3}}; schedule.extents.insert(schedule.extents.end(), 2 * bursts + 1, 1); - schedule.extents.insert(schedule.extents.end(), {2, 0, 0, 0, 1, 1}); + schedule.extents.insert(schedule.extents.end(), {2, 0, 0, 0, 1}); schedule.every = bisect.enabled; + schedule.no_draw = bisect.no_draw; draws = &schedule; VulkanContext context(get_device_proc, d.device, true, d.conditional_rendering); EXPECT(context.loaded()); @@ -232,34 +237,37 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec if (!bisect.wants(name)) return nullptr; return &lists.emplace_back(name, CommandList{}).second; }; + const auto resolve = [&](CommandList* l, const ResolveQueries& r) { + return bisect.no_resolve || l->resolve_queries(r); + }; if (auto* l = add("crossing")) { // two queries of one heap overlap; resolve while one is active EXPECT(l->begin_query({a, occ, 0}) && l->begin_query({a, occ, 1}) && l->end_query({a, occ, 0})); - EXPECT(l->resolve_queries({a, occ, 0, 1, dst_id, 8}) && l->end_query({a, occ, 1})); - EXPECT(l->resolve_queries({a, occ, 0, 2, dst_id, 24})); + EXPECT(resolve(l, {a, occ, 0, 1, dst_id, 8}) && l->end_query({a, occ, 1})); + EXPECT(resolve(l, {a, occ, 0, 2, dst_id, 24})); } if (auto* l = add("active")) { // a resolve inside one active query, without an overlap EXPECT(l->begin_query({a, occ, 0}) && l->end_query({a, occ, 0}) && l->begin_query({a, occ, 3})); - EXPECT(l->resolve_queries({a, occ, 0, 1, dst_id, 128}) && l->end_query({a, occ, 3})); + EXPECT(resolve(l, {a, occ, 0, 1, dst_id, 128}) && l->end_query({a, occ, 3})); } if (auto* l = add("nested")) { // the same index in two heaps, one inside the other EXPECT(l->begin_query({a, occ, 2}) && l->begin_query({b, occ, 2})); EXPECT(l->end_query({b, occ, 2}) && l->end_query({a, occ, 2})); - EXPECT(l->resolve_queries({a, occ, 2, 1, dst_id, 40}) && l->resolve_queries({b, occ, 2, 1, dst_id, 48})); + EXPECT(resolve(l, {a, occ, 2, 1, dst_id, 40}) && resolve(l, {b, occ, 2, 1, dst_id, 48})); } if (auto* l = add("unwritten")) { // a query never begun: zero fill - EXPECT(l->resolve_queries({b, occ, 0, 1, dst_id, 56})); + EXPECT(resolve(l, {b, occ, 0, 1, dst_id, 56})); } if (auto* l = add("binary")) { // the binary-occlusion compute resolve EXPECT(l->begin_query({a, binary, 3}) && l->end_query({a, binary, 3})); - EXPECT(l->resolve_queries({a, binary, 3, 1, dst_id, 64})); + EXPECT(resolve(l, {a, binary, 3, 1, dst_id, 64})); } if (d.conditional_rendering) { if (auto* l = add("predicated")) { // both compute resolves under a false predicate EXPECT(l->begin_query({a, binary, 3}) && l->end_query({a, binary, 3})); EXPECT(l->set_predication({predicate_id, 0, d3d12_predication::equal_zero})); - EXPECT(l->resolve_queries({a, binary, 3, 1, dst_id, 64})); - EXPECT(l->resolve_queries({a, occ, 0, 1, dst_id, 72})); - EXPECT(l->resolve_queries({a, binary, 3, 1, dst_id, 80})); + EXPECT(resolve(l, {a, binary, 3, 1, dst_id, 64})); + EXPECT(resolve(l, {a, occ, 0, 1, dst_id, 72})); + EXPECT(resolve(l, {a, binary, 3, 1, dst_id, 80})); EXPECT(copy_control.record(*l)); } } @@ -267,14 +275,16 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec EXPECT(l->begin_query({a, occ, 3})); for (std::uint32_t i = 0; i < bursts; ++i) EXPECT(l->begin_query({b, occ, 0}) && l->end_query({b, occ, 0})); EXPECT(l->end_query({a, occ, 3})); - EXPECT(l->resolve_queries({a, occ, 3, 1, dst_id, 88}) && l->resolve_queries({b, occ, 0, 1, dst_id, 96})); + EXPECT(resolve(l, {a, occ, 3, 1, dst_id, 88}) && resolve(l, {b, occ, 0, 1, dst_id, 96})); } if (auto* l = add("replace")) { // every heap query begun and ended again, then resolved for (const auto& [heap, index] : {std::pair{a, 0u}, std::pair{a, 1u}, std::pair{a, 2u}, std::pair{b, 2u}}) EXPECT(l->begin_query({heap, occ, index}) && l->end_query({heap, occ, index})); - EXPECT(l->resolve_queries({a, occ, 0, 2, dst_id, 112})); + EXPECT(resolve(l, {a, occ, 0, 2, dst_id, 112})); } EXPECT(!lists.empty()); + std::printf("bisect:%s%s%s\n", bisect.gated ? " gated" : " ungated", bisect.no_draw ? " no-draw" : " draws", + bisect.no_resolve ? " no-resolve" : " resolves"); // After a TDR, AMD's Windows driver lets vkQueueWaitIdle succeed (#1540); the queue's timeline then reads // UINT64_MAX, so that is checked as well. const auto get_value = d.fn("vkGetSemaphoreCounterValue"); @@ -391,7 +401,7 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec const CommandList* fourth[] = {&replace}; EXPECT(queue.execute(fourth) == ReplayResult::success); - // A resolve inside one active query, with no overlap: the active query is paused around it (D3D-189). + // A resolve inside one active query, with no overlap. CommandList single; EXPECT(single.begin_query({a, occ, 3})); EXPECT(single.resolve_queries({a, occ, 0, 1, dst_id, 128})); @@ -427,13 +437,15 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec } // namespace -// vk_overlapping_occlusion_test [--bisect [--gated] [phase...]] +// vk_overlapping_occlusion_test [--bisect [--gated] [--no-draw] [--no-resolve] [phase...]] int main(int argc, char** argv) { EXPECT(argc >= 3); Bisect bisect; for (int i = 3; i < argc; ++i) { if (std::strcmp(argv[i], "--bisect") == 0) bisect.enabled = true; else if (std::strcmp(argv[i], "--gated") == 0) bisect.gated = true; + else if (std::strcmp(argv[i], "--no-draw") == 0) bisect.no_draw = true; + else if (std::strcmp(argv[i], "--no-resolve") == 0) bisect.no_resolve = true; else bisect.phases.emplace_back(argv[i]); } EXPECT(argc == 3 || bisect.enabled); From a24d8cc6ba60ce7b309d498c2eaef029829bd178 Mon Sep 17 00:00:00 2001 From: SHAURYASANYAL3 Date: Sun, 22 Nov 2026 18:52:42 +0530 Subject: [PATCH 016/115] runtime: fallback and clamp swapchain extent when surface reports undefined extent (D3D-165) --- runtime/test/d3d12_present_test.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/runtime/test/d3d12_present_test.cpp b/runtime/test/d3d12_present_test.cpp index 8b28eb67a8..f01fb902be 100644 --- a/runtime/test/d3d12_present_test.cpp +++ b/runtime/test/d3d12_present_test.cpp @@ -115,6 +115,8 @@ int fail_semaphore_in = 0; // armed: the n-th vkCreateSemaphore fr bool fail_surface_formats = false; // armed: the next surface-format query fails before creation bool observe_next_swapchain = false; bool report_undefined_extent = false; // armed: surface capabilities reports undefined extent (0xFFFFFFFF) +bool undefined_extent_queried = false; +VkExtent2D last_swapchain_extent{}; VkSwapchainKHR last_created_swapchain = VK_NULL_HANDLE; VkSwapchainKHR observed_old_swapchain = VK_NULL_HANDLE; unsigned out_of_date = 0; // presents the real driver reported out of date @@ -170,6 +172,7 @@ VKAPI_ATTR VkResult VKAPI_CALL surface_formats(VkPhysicalDevice physical, VkSurf VKAPI_ATTR VkResult VKAPI_CALL create_swapchain(VkDevice device, const VkSwapchainCreateInfoKHR* info, const VkAllocationCallbacks* allocator, VkSwapchainKHR* out) { + if (info) last_swapchain_extent = info->imageExtent; if (observe_next_swapchain) { observed_old_swapchain = info->oldSwapchain; observe_next_swapchain = false; @@ -185,6 +188,7 @@ VKAPI_ATTR VkResult VKAPI_CALL get_surface_capabilities(VkPhysicalDevice physica if (result == VK_SUCCESS && report_undefined_extent && caps) { caps->currentExtent.width = 0xFFFFFFFF; caps->currentExtent.height = 0xFFFFFFFF; + undefined_extent_queried = true; } return result; } @@ -409,9 +413,14 @@ int main() { EXPECT(SUCCEEDED(fence->SetEventOnCompletion(signalled, nullptr))); // 4. Undefined surface extent (0xFFFFFFFF, reported by Intel UHD graphics / Win32 WSI; D3D-165): - // the presenter queries the window client extent and clamps to surface bounds. + // switch vsync to 0 to force swapchain recreation, verifying that vkGetPhysicalDeviceSurfaceCapabilitiesKHR + // is reached while armed and that vkCreateSwapchainKHR receives the clamped client extent (400x300) + // instead of 0xFFFFFFFF. driver::report_undefined_extent = true; - EXPECT(frame(1)); + driver::undefined_extent_queried = false; + EXPECT(frame(0)); + EXPECT(driver::undefined_extent_queried); + EXPECT(driver::last_swapchain_extent.width == 400 && driver::last_swapchain_extent.height == 300); EXPECT(presenter->extent().width == 400 && presenter->extent().height == 300); driver::report_undefined_extent = false; From 1df4c3b0f16fd580837ff184904d2aba62d4eb5c Mon Sep 17 00:00:00 2001 From: jsthope <68657498+jsthope@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:19:11 +0100 Subject: [PATCH 017/115] runtime: erasing a bindless descriptor key no longer idles the GPU DescriptorTable::erase backward-shifted the key's probe cluster, which moved other live entries, so BindlessSet::erase_key flagged the next flush as needing idle and every texture release ended in vkDeviceWaitIdle on the next submit. The shift is not needed: every lookup, on the CPU and in the translated shaders (rdna2spirv.py desc_probe), compares all eight probe slots and never stops at an empty one. Erase now empties only the key's own slot, and inserts reuse the hole. An erase uploads like an add (one slot, no idle). Replacing a live key's index, a relocating insert and table growth still require idle. Tests: descriptor_table_test checks that an erase in the middle of a cluster leaves every other slot byte-identical and marks one changed slot (it fails on the old erase); vk_bindless_test now expects no idle after an erase. --- runtime/src/descriptor_table.h | 24 +++--------- runtime/src/vulkan_bindless.h | 16 ++++---- runtime/test/descriptor_table_test.cpp | 51 ++++++++++++++++++++++++-- runtime/test/vk_bindless_test.cpp | 2 +- 4 files changed, 63 insertions(+), 30 deletions(-) diff --git a/runtime/src/descriptor_table.h b/runtime/src/descriptor_table.h index 59f96fd4f4..2b5b111f7a 100644 --- a/runtime/src/descriptor_table.h +++ b/runtime/src/descriptor_table.h @@ -129,7 +129,10 @@ class DescriptorTable { } // Erases a key from the table. Returns true if the key was found and erased, false otherwise. - // Backward-shifts downstream entries in the probe cluster so probe chains remain intact and compact. + // Only the key's own slot changes (it becomes empty): no other entry moves. Every lookup, here and in the + // shaders (rdna2spirv.py desc_probe), compares all kDescriptorProbes slots and never stops at an empty one, so + // a hole breaks no probe chain and inserts reuse it. Keeping the other entries in place is what lets the GPU + // copy of the table take an erase while shaders still probe it (BindlessSet::flush_needs_idle). bool erase(const std::uint32_t key[8]) { std::lock_guard lock(mutex_); return erase_locked(key); @@ -321,24 +324,9 @@ class DescriptorTable { } if (!found) return false; - // Backward-shift entries in the probe cluster to maintain probe chains - std::uint32_t i = found_slot; - std::uint32_t j = i; + // No backward shift: see erase(). + entries_[found_slot] = DescriptorEntry{}; mark(found_slot); - while (true) { - j = (j + 1) & mask_; - if (entries_[j].pad != kSlotOccupiedMarker) break; - const std::uint32_t r = hash_descriptor_key(entries_[j].key); - const std::uint32_t dist_r_to_i = (i - r) & mask_; - const std::uint32_t dist_r_to_j = (j - r) & mask_; - if (dist_r_to_i < dist_r_to_j && dist_r_to_i < kDescriptorProbes) { - entries_[i] = entries_[j]; - mark(i); - i = j; - } - } - entries_[i] = DescriptorEntry{}; - mark(i); --occupied_count_; return true; } diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h index c599eb7c29..965a21c1c0 100644 --- a/runtime/src/vulkan_bindless.h +++ b/runtime/src/vulkan_bindless.h @@ -400,19 +400,21 @@ class BindlessSet { result == DescriptorTable::InsertResult::added_with_relocation; return true; } - // Erasing compacts the key's probe cluster, so other keys' entries may change slots. + // Erasing empties only the key's own slot; no other entry moves (DescriptorTable::erase), so it needs no idle. + // The caller erases a key once no submitted work uses it (its texture is gone), like D3D12 requires. bool erase_key(const DescriptorKey& key) { if (!table_.erase(key)) return false; - table_dirty_ = existing_entries_changed_ = true; + table_dirty_ = true; return true; } const DescriptorTable& table() const { return table_; } - // True when the next flush() will change entries a running shader may be probing, or replace the table's - // buffer: the caller then flushes only once no command buffer that uses the set is still executing. Without - // it the flush only adds entries, and the copy of an entry is not atomic: a shader probing a different key - // could in principle see a torn entry that matches it, which is accepted as vanishingly unlikely because the - // added key is new (there is no live key equal to it). + // True when the next flush() will change entries a running shader may be probing (a live key's index replaced + // or a live key moved by a relocating insert), or replace the table's buffer: the caller then flushes only once + // no command buffer that uses the set is still executing. Without it the flush only adds entries or empties the + // slots of erased keys, and the copy of an entry is not atomic: a shader probing a different key could in + // principle see a torn entry that matches it, which is accepted as vanishingly unlikely because the added or + // erased key is not live (no running work uses it). bool flush_needs_idle() const { return table_dirty_ && (existing_entries_changed_ || force_full_upload_ || table_.size_bytes() > table_buffers_.table.size); diff --git a/runtime/test/descriptor_table_test.cpp b/runtime/test/descriptor_table_test.cpp index a24a9c6e2b..26fb390836 100644 --- a/runtime/test/descriptor_table_test.cpp +++ b/runtime/test/descriptor_table_test.cpp @@ -233,7 +233,7 @@ int test_clear_resets_table() { return 0; } -int test_erase_and_cluster_compact() { +int test_erase_and_reinsert() { DescriptorTable table(16); const std::uint32_t k1[8] = {1, 10, 100, 1000, 2, 20, 200, 2000}; @@ -310,12 +310,12 @@ int test_change_tracking() { EXPECT(!changes.all && changes.slots.size() == 1 && changes.slots.front() == slot); EXPECT(table.read_slot(slot, read) && read[8] == 43); - // Erasing marks the slot it was in and the ones the cluster compaction moved. + // Erasing marks only the slot it was in: no other entry moves. EXPECT(table.insert(k2, 7)); table.take_changes(); EXPECT(table.erase(k1)); changes = table.take_changes(); - EXPECT(!changes.all && !changes.slots.empty() && changes.slots.front() == slot); + EXPECT(!changes.all && changes.slots.size() == 1 && changes.slots.front() == slot); // Growth changes the mask, so everything re-uploads. const std::size_t before = table.capacity(); @@ -366,6 +366,48 @@ int test_relocation_marks_both_slots() { return 0; } +// Shaders keep probing the GPU copy of the table while an erase is uploaded without waiting for idle +// (BindlessSet::flush_needs_idle), so an erase must leave every other key's slot exactly as it was. +int test_erase_moves_no_other_entry() { + DescriptorTable table(64); + const std::uint32_t slots = std::uint32_t(table.capacity()); + // Five keys with one home: they fill five consecutive slots, the cluster the old erase compacted. + std::array keys{}; + for (std::uint32_t i = 0; i < keys.size(); ++i) { + auto& key = keys[i]; + key[0] = i + 1; + while ((hash_descriptor_key(key) & (slots - 1)) != slots - 2) ++key[7]; // the cluster wraps the end + EXPECT(table.insert_or_update(key.data(), 200 + i) == DescriptorTable::InsertResult::added); + } + table.take_changes(); + const auto before = table.build_gpu_buffer(); + + EXPECT(table.erase(keys[1].data())); + const DescriptorTable::Changes changes = table.take_changes(); + EXPECT(!changes.all && changes.slots.size() == 1); + const std::uint32_t hole = changes.slots.front(); + const auto after = table.build_gpu_buffer(); + for (std::uint32_t s = 0; s < slots; ++s) { + const bool same = std::memcmp(&before[1 + s * 10], &after[1 + s * 10], 10 * sizeof(std::uint32_t)) == 0; + EXPECT(same == (s != hole)); + } + for (std::uint32_t w = 0; w < 10; ++w) EXPECT(after[1 + hole * 10 + w] == 0); // an empty slot: a miss + for (std::uint32_t i = 0; i < keys.size(); ++i) EXPECT(table.lookup(keys[i]) == (i == 1 ? 0u : 200 + i)); + + // Keys past the hole are still found after more erases, and a new key of the same home reuses the hole. + EXPECT(table.erase(keys[0].data())); + EXPECT(table.lookup(keys[4]) == 204 && table.lookup(keys[3]) == 203); + DescriptorKey extra = keys[0]; + extra[0] = 100; + while ((hash_descriptor_key(extra) & (slots - 1)) != slots - 2) ++extra[7]; + table.take_changes(); + EXPECT(table.insert_or_update(extra.data(), 300) == DescriptorTable::InsertResult::added); + const DescriptorTable::Changes reuse = table.take_changes(); + EXPECT(reuse.slots.size() == 1 && reuse.slots.front() == slots - 2); // the first hole of the probe window + EXPECT(table.lookup(extra) == 300 && table.size() == 4); + return 0; +} + int main() { EXPECT(test_fnv1a_hash_matches_contract() == 0); EXPECT(test_ssharp_key_padding() == 0); @@ -376,9 +418,10 @@ int main() { EXPECT(test_gpu_buffer_serialization() == 0); EXPECT(test_change_tracking() == 0); EXPECT(test_relocation_marks_both_slots() == 0); + EXPECT(test_erase_moves_no_other_entry() == 0); EXPECT(test_multithreaded_insert_and_lookup() == 0); EXPECT(test_clear_resets_table() == 0); - EXPECT(test_erase_and_cluster_compact() == 0); + EXPECT(test_erase_and_reinsert() == 0); std::printf("descriptor_table_test: all tests passed (0 failures)\n"); return 0; diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp index 73ac39013a..fd0f7dbbfd 100644 --- a/runtime/test/vk_bindless_test.cpp +++ b/runtime/test/vk_bindless_test.cpp @@ -727,7 +727,7 @@ int main(int argc, char** argv) { // 2. Without its key the T# is a miss: index 0, the fallback image of zeros. const float zeros[4] = {0, 0, 0, 0}; EXPECT(set.erase_key(tsharp) && !set.erase_key(tsharp)); - EXPECT(set.flush_needs_idle()); // erasing may move the keys behind it; nothing is running here + EXPECT(!set.flush_needs_idle()); // erasing empties its slot only: the three keys ahead stay where they are EXPECT(flush() && !set.flush_needs_idle()); CHECK(draw()); compare("2 miss", zeros); From 174ca0ad9c10b1867b7c3d83a1d270275861deb2 Mon Sep 17 00:00:00 2001 From: jsthope <68657498+jsthope@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:19:12 +0100 Subject: [PATCH 018/115] docs: d3d12_vulkan.md describes erase without cluster compaction --- docs/d3d12_vulkan.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 83951f226f..5000fa31cd 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -491,9 +491,12 @@ side inwards: - `flush()` also uploads the table to its buffer: device-local memory, written from a mapped staging copy when the buffers are created (first use or growth) and with `vkCmdUpdateBuffer` for slot changes. Adding a key only puts a new entry in an empty slot, and the copy of an entry is not atomic; a running lookup that does not know - the key cannot resolve to it, which is accepted. Erasing a key compacts its probe cluster, which moves other - keys' entries, and a table that has grown gets a new buffer behind binding 2: `flush_needs_idle()` says when a - flush would do either, and the device waits for the queue before flushing in that case. + the key cannot resolve to it, which is accepted. Erasing a key empties its slot and moves no other entry + (every lookup, CPU and shader, compares all eight probe slots and never stops at an empty one), so it is + uploaded like an add. Replacing a live key's index, an insert that relocates a live entry, and a table that + has grown (a new buffer behind binding 2) change what running lookups see: `flush_needs_idle()` says when a + flush would do one of those, and the device waits for the queue before flushing in that case. Erasing used to + compact the probe cluster, which moved other keys and made every texture release wait for the whole GPU. - **`runtime/src/gfx10_descriptors.h`**: the T#, S# and V# structures (section 5.3), encoded and decoded, with their mapping to Vulkan formats, view types, component mappings and samplers. Field positions are Mesa's (`src/amd/registers/gfx10-rsrc.json`) and agree with what the translator and the GPU tests already use. Bits From 3d533d6c3fb2be85622b67464263119a38c27047 Mon Sep 17 00:00:00 2001 From: SWAYAM Date: Sun, 22 Nov 2026 18:57:50 +0530 Subject: [PATCH 019/115] d3d12_xs: route slot 67 compute pipeline from native code to CreateComputePipelineState (RT-99) Xbox device slot 67 takes (desc, riid, out) with IID_ID3D12PipelineState and a console-only descriptor with the root signature at +0x00 and code blob pointer/size at +0x28/+0x30. Previously it logged and returned E_NOTIMPL. Route it to CreateComputePipelineState on the PC device (slot 11) like slot 62, mapping the console descriptor to D3D12_COMPUTE_PIPELINE_STATE_DESC. On the Vulkan device this resolves through the translator via fssm_program and ShaderLibrary. - Implement proxy_create_compute_pipeline_from_native_code in d3d12_xs_device.cpp - Update device_proxy_test to verify slot 67 thunk, compute PSO creation over WARP, and argument checks - Update d3d12_compute_test to verify slot 67 compute PSO creation on the Vulkan device - Update documentation in d3d12_command_objects.md and d3d12_vulkan.md Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_command_objects.md | 7 +-- docs/d3d12_vulkan.md | 2 +- runtime/shims/d3d12_vulkan_device.cpp | 2 +- runtime/shims/d3d12_xs_device.cpp | 63 ++++++++++++++++++++++----- runtime/shims/d3d12_xs_device.h | 3 ++ runtime/test/d3d12_compute_test.cpp | 34 +++++++++++++++ runtime/test/device_proxy_test.cpp | 35 ++++++++++++++- runtime/test/fsr_dispatch_test.cpp | 4 +- 8 files changed, 129 insertions(+), 21 deletions(-) diff --git a/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md index a55c3d9644..497431d8f8 100644 --- a/docs/d3d12_command_objects.md +++ b/docs/d3d12_command_objects.md @@ -371,9 +371,10 @@ vtable pointer of a public object. - **Slot 67** (call at `0x56d9`) is **not** the PC `CreateProtectedResourceSession1`: it takes `(desc, riid, out)` with `IID_ID3D12PipelineState`. The DLL's own messages name it `DeserializeComputePipelineStateX`. Its desc is the root signature at `+0x00`, then pointer and size pairs for the shader's `FSPX` entries: kind 0 at `+0x08`, kind 1 - at `+0x18`, a copy of the kind-6 program at `+0x28`, and kind 7 at `+0x38` ([fspx.md](fspx.md)). The proxy used to - forward it to the PC method at the same index; it now refuses it (`E_NOTIMPL`). When it fails, the DLL takes - slot 62; its message for that failure calls the fallback "NewBE". + at `+0x18`, a copy of the kind-6 program at `+0x28`, and kind 7 at `+0x38` ([fspx.md](fspx.md)). The proxy maps the + console desc to `D3D12_COMPUTE_PIPELINE_STATE_DESC` and routes it to `CreateComputePipelineState` (PC slot 11). On a + PC device that call fails (`E_FAIL`) because the code is not a PC shader, so the DLL falls back to slot 62; its message + for that failure calls the fallback "NewBE". - **Slot 62** (call at `0x5825`) takes the measured `(D3D12_COMPUTE_PIPELINE_STATE_DESC*, 0, 0, riid, out)`. The PC runtime refuses the DLL's code (`E_FAIL`): it is not a PC shader. The DLL's pipeline function then returns `0x8000000d` (`0x4b85`), but the dispatch goes on, records the null pipeline and faults (`0x65ff`), which is where a diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e96dcae726..076ae5d088 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2820,7 +2820,7 @@ on a PC device behind the Xbox-ABI proxy). Measured: (`+0x18`, `+0x28`, `+0x30`) the DLL writes commands through while there is room. Table and evidence: [d3d12_command_objects.md §3.5a](d3d12_command_objects.md). Device slot 67 is a console-only compute-pipeline call, `DeserializeComputePipelineStateX` in the DLL's own - messages, not the PC method at that index; the proxy now refuses it. The dispatch stops where the PC runtime + messages, not the PC method at that index; the proxy routes it to `CreateComputePipelineState`. The dispatch stops where the PC runtime refuses the DLL's compute code at slot 62: the DLL's shaders carry an `ACCC` part instead of DXIL, an `FSPX` payload with an RDNA2 program ([fspx.md](fspx.md)). - Its `throw 1` reaches the caller. Before #965 the throw carried an image base of 0, because `_CxxThrowException` diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 8d0cd21e47..cfb93c0cb9 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -3657,7 +3657,7 @@ class Device final return hand_out(signature, riid, out); } - // PC slot 11; the Xbox ABI reaches it through device slot 62 (the proxy forwards). + // PC slot 11; the Xbox ABI reaches it through device slots 62 and 67 (the proxy forwards). HRESULT STDMETHODCALLTYPE CreateComputePipelineState(const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID riid, void** out) override { if (!out) return E_POINTER; diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 57cd292c71..bdb1292232 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -981,6 +981,54 @@ HRESULT proxy_create_compute_pipeline_state(DeviceProxy* self, const D3D12_COMPU return self->real->CreateComputePipelineState(desc, *riid, out); } +// The Xbox slot 67 creates a compute pipeline from native GPU code: (desc, riid, out). Measured on +// amd_fidelityfx_upscaler_xbox.dll (call at RVA 0x56d9): the root signature is at +0x00, two metadata pointers +// with sizes at +0x08..+0x20, and the shader code blob at +0x28 with its byte size at +0x30. Translates the +// console description to a standard D3D12_COMPUTE_PIPELINE_STATE_DESC and routes it to CreateComputePipelineState +// on the PC device (slot 11), which on the Vulkan device resolves through the translator. The PC slot 67 is +// CreateProtectedResourceSession1, a different method. +HRESULT proxy_create_compute_pipeline_from_native_code(DeviceProxy* self, const void* desc, + const IID* riid, void** out) { + note_slot(67); + if (!out) return E_POINTER; + *out = nullptr; + if (!desc) return E_INVALIDARG; + if (!riid) return E_POINTER; + + struct XboxNativeComputePipelineStateDesc { + ID3D12RootSignature* root_signature; + const void* ptr1; + std::uint64_t size1; + const void* ptr2; + std::uint64_t size2; + const void* code; + std::uint64_t code_size; + }; + const auto* xbox_desc = static_cast(desc); + + if (xbox_desc->ptr1 || xbox_desc->size1 || xbox_desc->ptr2 || xbox_desc->size2) { + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) { + std::fprintf(stderr, + "[rt] d3d12_xs: slot 67 metadata ptrs/sizes 0x%llx (0x%llx), 0x%llx (0x%llx)\n", + static_cast(reinterpret_cast(xbox_desc->ptr1)), + static_cast(xbox_desc->size1), + static_cast(reinterpret_cast(xbox_desc->ptr2)), + static_cast(xbox_desc->size2)); + } + } + + D3D12_COMPUTE_PIPELINE_STATE_DESC pc_desc{}; + pc_desc.pRootSignature = xbox_desc->root_signature; + pc_desc.CS.pShaderBytecode = xbox_desc->code; + pc_desc.CS.BytecodeLength = static_cast(xbox_desc->code_size); + pc_desc.NodeMask = 0; + pc_desc.CachedPSO = {nullptr, 0}; + pc_desc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; + + return self->real->CreateComputePipelineState(&pc_desc, *riid, out); +} + HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* heap_properties, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* xbox_desc, D3D12_RESOURCE_STATES initial_state, const D3D12_CLEAR_VALUE* clear_value, @@ -1044,18 +1092,9 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 self, reinterpret_cast(a1), a2, a3, reinterpret_cast(a4), reinterpret_cast(a5))); } else if constexpr (Slot == 67) { - // Measured in amd_fidelityfx_upscaler_xbox.dll (call at RVA 0x56d9): (desc, riid, out), named - // DeserializeComputePipelineStateX in the DLL's own messages. The desc is the root signature at +0x00, then - // pointer/size pairs for the shader's FSPX entries, with the native RDNA2 program at +0x28 (docs/fspx.md); - // the DLL falls back to slot 62 when it fails. The PC device's slot 67 is CreateProtectedResourceSession1, a - // different method, so it is refused here, not forwarded. - note_slot(67); - static std::atomic logged{false}; - if (!logged.exchange(true, std::memory_order_relaxed)) - std::fprintf(stderr, - "[rt] d3d12_xs: device slot 67 (Xbox DeserializeComputePipelineStateX) -> E_NOTIMPL\n"); - if (a3) *reinterpret_cast(a3) = nullptr; - return hr_to_u64(E_NOTIMPL); + return hr_to_u64(proxy_create_compute_pipeline_from_native_code( + self, reinterpret_cast(a1), reinterpret_cast(a2), + reinterpret_cast(a3))); } else if constexpr (Slot == 76) { return hr_to_u64(proxy_create_resource( self, reinterpret_cast(a1), diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 510560516d..5897a482d9 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -3,6 +3,9 @@ // Measured Xbox device deviations used here (vtable indices, x64): // slot 62 CreateComputePipelineState(desc, w2, w3, iid, out): two words (0 from XboxBvhBuilder, meaning unknown) // before the IID. The PC slot 62 is CreateStateObject. +// slot 67 CreateComputePipelineState from native code (desc, iid, out): converts the Xbox native-code desc +// (+0x00 root signature, +0x28 code, +0x30 size) to D3D12_COMPUTE_PIPELINE_STATE_DESC and forwards +// to PC CreateComputePipelineState (slot 11). The PC slot 67 is CreateProtectedResourceSession1. // slot 76 resource creation -> PC CreateCommittedResource (PC slot 27), with the Xbox layout word ignored. // The measured slots 9/10 (GetCPU/GPUDescriptorHandleForHeapStart) are ID3D12DescriptorHeap methods, not device // methods: the PC device's 9/10 are CreateCommandAllocator/CreateGraphicsPipelineState and are forwarded unchanged. diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp index a2011d3c2b..5fed5b14c4 100644 --- a/runtime/test/d3d12_compute_test.cpp +++ b/runtime/test/d3d12_compute_test.cpp @@ -33,6 +33,8 @@ using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10 // Device slot 62 as XboxBvhBuilder.dll calls it on 1.0.2.1: (desc, 0, 0, riid, out) (main's 28cf235). using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t, std::uint64_t, const IID*, void**); +// Device slot 67 as amd_fidelityfx_upscaler_xbox.dll calls it: (desc, riid, out). +using XboxNativeComputePipelineFn = HRESULT(WINAPI*)(void* device, const void*, const IID*, void**); using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); template @@ -221,6 +223,38 @@ int main() { EXPECT(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&unknown.p)) == E_INVALIDARG && !unknown.p); pso_desc.CS = {container.data(), container.size()}; + // The PSO through slot 67, compute pipeline from native code; maps to CreateComputePipelineState. + struct XboxNativeComputeDesc { + ID3D12RootSignature* root_signature; + const void* ptr1; + std::uint64_t size1; + const void* ptr2; + std::uint64_t size2; + const void* code; + std::uint64_t code_size; + } native_desc{}; + native_desc.root_signature = root.p; + native_desc.code = fssm.data(); + native_desc.code_size = fssm.size(); + Ref pso67, unknown67; + EXPECT(SUCCEEDED(reinterpret_cast(slot(device.p, 67))( + device.p, &native_desc, &pso_iid, reinterpret_cast(&pso67.p)))); + EXPECT(pso67.p != nullptr); + native_desc.code = other.data(); + native_desc.code_size = other.size(); + EXPECT(reinterpret_cast(slot(device.p, 67))( + device.p, &native_desc, &pso_iid, reinterpret_cast(&unknown67.p)) == E_INVALIDARG && !unknown67.p); + void* out_null = reinterpret_cast(0x1111); + EXPECT(reinterpret_cast(slot(device.p, 67))( + device.p, nullptr, &pso_iid, &out_null) == E_INVALIDARG && !out_null); + out_null = reinterpret_cast(0x1111); + native_desc.code = fssm.data(); + native_desc.code_size = fssm.size(); + EXPECT(reinterpret_cast(slot(device.p, 67))( + device.p, &native_desc, nullptr, &out_null) == E_POINTER && !out_null); + EXPECT(reinterpret_cast(slot(device.p, 67))( + device.p, &native_desc, &pso_iid, nullptr) == E_POINTER); + // A device whose maxPushConstantsSize is the Vulkan minimum (128 bytes) cannot hold the 144-byte block, so // its PSOs are refused instead of creating a pipeline layout the spec forbids (#224's fallback flag). { diff --git a/runtime/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp index e414f155bf..35e4b67a33 100644 --- a/runtime/test/device_proxy_test.cpp +++ b/runtime/test/device_proxy_test.cpp @@ -157,13 +157,13 @@ int main() { check(rt::d3d12_xs::device_slot_overridden(62), "device slot 62 is the compute-PSO override"); check(rt::d3d12_xs::device_slot_overridden(76), "device slot 76 is the resource override"); check(rt::d3d12_xs::device_slot_overridden(67), - "device slot 67 is refused (console DeserializeComputePipelineStateX, " - "not PC CreateProtectedResourceSession1)"); + "device slot 67 is the DeserializeComputePipelineStateX override (console native-code compute pipeline, not PC CreateProtectedResourceSession1)"); void** proxy_vtbl = *reinterpret_cast(device.Get()); void** real_vtbl = real ? *reinterpret_cast(real) : nullptr; check(proxy_vtbl != nullptr && proxy_vtbl[14] != real_vtbl[14], "slot 14 thunk differs from the PC entry"); if (slots > 62) check(proxy_vtbl[62] != real_vtbl[62], "slot 62 thunk differs from PC CreateStateObject"); + if (slots > 67) check(proxy_vtbl[67] != real_vtbl[67], "slot 67 thunk differs from PC CreateProtectedResourceSession1"); if (slots > 76) check(proxy_vtbl[76] != real_vtbl[76], "slot 76 thunk differs from PC CreateCommittedResource3"); rt::d3d12_xs::reset_device_proxy_stats(); @@ -342,6 +342,29 @@ int main() { check(SUCCEEDED(hr) && pso != nullptr, "slot 62 creates a compute PSO via CreateComputePipelineState"); check(rt::d3d12_xs::device_slot_hits(62) == 1, "slot 62 hit counter is 1"); check(rt::d3d12_xs::device_slot_first_call_seen(62), "slot 62 first-call flag is set"); + + // Slot 67: Xbox native compute pipeline creation. Maps the console descriptor (+0x00 root signature, + // +0x28 code blob, +0x30 code size) to D3D12_COMPUTE_PIPELINE_STATE_DESC and calls CreateComputePipelineState. + struct XboxNativeComputeDesc { + ID3D12RootSignature* root_signature; + const void* ptr1; + std::uint64_t size1; + const void* ptr2; + std::uint64_t size2; + const void* code; + std::uint64_t code_size; + } xbox_desc{}; + xbox_desc.root_signature = root_signature.Get(); + xbox_desc.code = bytecode->GetBufferPointer(); + xbox_desc.code_size = bytecode->GetBufferSize(); + + using XboxCreateNativeComputePsoFn = HRESULT(WINAPI*)(void*, const void*, const IID*, void**); + auto create_native_pso = reinterpret_cast(proxy_vtbl[67]); + ComPtr pso67; + hr = create_native_pso(device.Get(), &xbox_desc, &iid_pso, reinterpret_cast(pso67.GetAddressOf())); + check(SUCCEEDED(hr) && pso67 != nullptr, "slot 67 creates a compute PSO via CreateComputePipelineState"); + check(rt::d3d12_xs::device_slot_hits(67) == 1, "slot 67 hit counter is 1"); + check(rt::d3d12_xs::device_slot_first_call_seen(67), "slot 67 first-call flag is set"); } // _COM_Outptr_ (d3d12.h): a failed create leaves NULL in the output. WARP accepts invalid heap descriptions, @@ -357,6 +380,14 @@ int main() { D3D12_COMPUTE_PIPELINE_STATE_DESC empty_pso{}; hr = reinterpret_cast(proxy_vtbl[62])(device.Get(), &empty_pso, 0, 0, nullptr, &proxy_out); check(FAILED(hr) && proxy_out == nullptr, "slot 62 nulls its output for a null IID"); + using Slot67Fn = HRESULT(WINAPI*)(void*, const void*, const IID*, void**); + proxy_out = reinterpret_cast(0x1111); + const IID iid_pso = __uuidof(ID3D12PipelineState); + hr = reinterpret_cast(proxy_vtbl[67])(device.Get(), nullptr, &iid_pso, &proxy_out); + check(FAILED(hr) && proxy_out == nullptr, "slot 67 nulls its output for a null description"); + proxy_out = reinterpret_cast(0x1111); + hr = reinterpret_cast(proxy_vtbl[67])(device.Get(), &root_desc, nullptr, &proxy_out); + check(FAILED(hr) && proxy_out == nullptr, "slot 67 nulls its output for a null IID"); using Slot76Fn = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS, const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES, const D3D12_CLEAR_VALUE*, const IID*, void**); diff --git a/runtime/test/fsr_dispatch_test.cpp b/runtime/test/fsr_dispatch_test.cpp index 7affaee7ad..9a66071acc 100644 --- a/runtime/test/fsr_dispatch_test.cpp +++ b/runtime/test/fsr_dispatch_test.cpp @@ -28,7 +28,7 @@ // driver refuses one of its textures (DXGI_FORMAT_R9G9B9E5_SHAREDEXP with ALLOW_UNORDERED_ACCESS); on WARP the // context is created as is. The other backend ids are controls: they end in FFX_API_RETURN_ERROR before the device // is touched. In step 7 the dispatch is recorded up to the DLL's compute pipeline, which a PC device cannot create -// (slot 67 is console-only and refused; slot 62's code is not a PC shader). The INFO lines are the measurement; the +// (slot 67 and 62 codes are not PC shaders). The INFO lines are the measurement; the // PASS/FAIL checks only cover what is known to work. #include @@ -958,7 +958,7 @@ int main() { note(" device slot 62 (compute pipeline from a D3D12_COMPUTE_PIPELINE_STATE_DESC) called " + std::to_string(g_slot62_calls) + "x, last HRESULT " + hex(static_cast(g_slot62_hr))); if (g_formatted) note(" the DLL formatted HRESULT " + hex(g_first_formatted)); - // On a PC device both pipeline paths fail (67 is refused, 62's code is not a PC shader); on the + // On a PC device both pipeline paths fail (neither slot 67's nor 62's code is a PC shader); on the // Vulkan device CreateRootSignature (slot 16) is not implemented yet. Either way the dispatch goes // on with a null pipeline and faults when it records it (RVA 0x65ff reads the pipeline's +0x10, // the same pointer it passes to SetPipelineState): a documented stop, not a test failure. From 835b43fe9bb3709f68d68031203d097d4b9efe04 Mon Sep 17 00:00:00 2001 From: SWAYAM Date: Sun, 22 Nov 2026 19:23:10 +0530 Subject: [PATCH 020/115] d3d12_xs: name slot 67 descriptor fields as FSPX kinds 0, 1, 6, 7 Name all four pointer and size pairs in the XboxNativeComputePipelineStateDesc struct as kinds 0, 1, 6, 7 per docs/fspx.md and name the slot DeserializeComputePipelineStateX in slot_name, matching the DLL's messages. This prepares the description struct for the runtime FSPX resolver follow-up. Co-Authored-By: Claude Opus 5.5 --- runtime/shims/d3d12_xs_device.cpp | 49 ++++++++++++++++------------- runtime/test/d3d12_compute_test.cpp | 26 ++++++++------- runtime/test/device_proxy_test.cpp | 20 ++++++------ 3 files changed, 53 insertions(+), 42 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index bdb1292232..5f2f302947 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -981,12 +981,13 @@ HRESULT proxy_create_compute_pipeline_state(DeviceProxy* self, const D3D12_COMPU return self->real->CreateComputePipelineState(desc, *riid, out); } -// The Xbox slot 67 creates a compute pipeline from native GPU code: (desc, riid, out). Measured on -// amd_fidelityfx_upscaler_xbox.dll (call at RVA 0x56d9): the root signature is at +0x00, two metadata pointers -// with sizes at +0x08..+0x20, and the shader code blob at +0x28 with its byte size at +0x30. Translates the -// console description to a standard D3D12_COMPUTE_PIPELINE_STATE_DESC and routes it to CreateComputePipelineState -// on the PC device (slot 11), which on the Vulkan device resolves through the translator. The PC slot 67 is -// CreateProtectedResourceSession1, a different method. +// The Xbox slot 67 creates a compute pipeline from native GPU code: (desc, riid, out), named +// DeserializeComputePipelineStateX in amd_fidelityfx_upscaler_xbox.dll's messages (call at RVA 0x56d9). The desc +// passes the root signature at +0x00, followed by pointer/size pairs for the shader's FSPX entries (docs/fspx.md): +// kind 0 (dispatch state) at +0x08/+0x10, kind 1 at +0x18/+0x20, kind 6 (the RDNA2 program) at +0x28/+0x30, and +// kind 7 (records) at +0x38/+0x40. Translates the console description to a standard D3D12_COMPUTE_PIPELINE_STATE_DESC +// with CS bytecode pointing at kind 6 and routes it to CreateComputePipelineState on the PC device (slot 11), which +// on the Vulkan device resolves through the translator. The PC slot 67 is CreateProtectedResourceSession1. HRESULT proxy_create_compute_pipeline_from_native_code(DeviceProxy* self, const void* desc, const IID* riid, void** out) { note_slot(67); @@ -995,33 +996,39 @@ HRESULT proxy_create_compute_pipeline_from_native_code(DeviceProxy* self, const if (!desc) return E_INVALIDARG; if (!riid) return E_POINTER; + // FSPX description layout (docs/fspx.md §How the DLL reads it): struct XboxNativeComputePipelineStateDesc { - ID3D12RootSignature* root_signature; - const void* ptr1; - std::uint64_t size1; - const void* ptr2; - std::uint64_t size2; - const void* code; - std::uint64_t code_size; + ID3D12RootSignature* root_signature; // +0x00 + const void* kind0; // +0x08: dispatch state + std::uint64_t kind0_size; // +0x10: 28 bytes + const void* kind1; // +0x18: unknown + std::uint64_t kind1_size; // +0x20: 20 bytes + const void* kind6; // +0x28: RDNA2 program code + std::uint64_t kind6_size; // +0x30: program size in bytes + const void* kind7; // +0x38: resource/hash records + std::uint64_t kind7_size; // +0x40: records size in bytes }; const auto* xbox_desc = static_cast(desc); - if (xbox_desc->ptr1 || xbox_desc->size1 || xbox_desc->ptr2 || xbox_desc->size2) { + if (xbox_desc->kind0 || xbox_desc->kind0_size || xbox_desc->kind1 || xbox_desc->kind1_size || + xbox_desc->kind7 || xbox_desc->kind7_size) { static std::atomic logged{false}; if (!logged.exchange(true, std::memory_order_relaxed)) { std::fprintf(stderr, - "[rt] d3d12_xs: slot 67 metadata ptrs/sizes 0x%llx (0x%llx), 0x%llx (0x%llx)\n", - static_cast(reinterpret_cast(xbox_desc->ptr1)), - static_cast(xbox_desc->size1), - static_cast(reinterpret_cast(xbox_desc->ptr2)), - static_cast(xbox_desc->size2)); + "[rt] d3d12_xs: slot 67 FSPX metadata: kind0 0x%llx (%llu B), kind1 0x%llx (%llu B), kind7 0x%llx (%llu B)\n", + static_cast(reinterpret_cast(xbox_desc->kind0)), + static_cast(xbox_desc->kind0_size), + static_cast(reinterpret_cast(xbox_desc->kind1)), + static_cast(xbox_desc->kind1_size), + static_cast(reinterpret_cast(xbox_desc->kind7)), + static_cast(xbox_desc->kind7_size)); } } D3D12_COMPUTE_PIPELINE_STATE_DESC pc_desc{}; pc_desc.pRootSignature = xbox_desc->root_signature; - pc_desc.CS.pShaderBytecode = xbox_desc->code; - pc_desc.CS.BytecodeLength = static_cast(xbox_desc->code_size); + pc_desc.CS.pShaderBytecode = xbox_desc->kind6; + pc_desc.CS.BytecodeLength = static_cast(xbox_desc->kind6_size); pc_desc.NodeMask = 0; pc_desc.CachedPSO = {nullptr, 0}; pc_desc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp index 5fed5b14c4..c7bd6bab1c 100644 --- a/runtime/test/d3d12_compute_test.cpp +++ b/runtime/test/d3d12_compute_test.cpp @@ -226,30 +226,32 @@ int main() { // The PSO through slot 67, compute pipeline from native code; maps to CreateComputePipelineState. struct XboxNativeComputeDesc { ID3D12RootSignature* root_signature; - const void* ptr1; - std::uint64_t size1; - const void* ptr2; - std::uint64_t size2; - const void* code; - std::uint64_t code_size; + const void* kind0; + std::uint64_t kind0_size; + const void* kind1; + std::uint64_t kind1_size; + const void* kind6; + std::uint64_t kind6_size; + const void* kind7; + std::uint64_t kind7_size; } native_desc{}; native_desc.root_signature = root.p; - native_desc.code = fssm.data(); - native_desc.code_size = fssm.size(); + native_desc.kind6 = fssm.data(); + native_desc.kind6_size = fssm.size(); Ref pso67, unknown67; EXPECT(SUCCEEDED(reinterpret_cast(slot(device.p, 67))( device.p, &native_desc, &pso_iid, reinterpret_cast(&pso67.p)))); EXPECT(pso67.p != nullptr); - native_desc.code = other.data(); - native_desc.code_size = other.size(); + native_desc.kind6 = other.data(); + native_desc.kind6_size = other.size(); EXPECT(reinterpret_cast(slot(device.p, 67))( device.p, &native_desc, &pso_iid, reinterpret_cast(&unknown67.p)) == E_INVALIDARG && !unknown67.p); void* out_null = reinterpret_cast(0x1111); EXPECT(reinterpret_cast(slot(device.p, 67))( device.p, nullptr, &pso_iid, &out_null) == E_INVALIDARG && !out_null); out_null = reinterpret_cast(0x1111); - native_desc.code = fssm.data(); - native_desc.code_size = fssm.size(); + native_desc.kind6 = fssm.data(); + native_desc.kind6_size = fssm.size(); EXPECT(reinterpret_cast(slot(device.p, 67))( device.p, &native_desc, nullptr, &out_null) == E_POINTER && !out_null); EXPECT(reinterpret_cast(slot(device.p, 67))( diff --git a/runtime/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp index 35e4b67a33..d843b518cf 100644 --- a/runtime/test/device_proxy_test.cpp +++ b/runtime/test/device_proxy_test.cpp @@ -344,19 +344,21 @@ int main() { check(rt::d3d12_xs::device_slot_first_call_seen(62), "slot 62 first-call flag is set"); // Slot 67: Xbox native compute pipeline creation. Maps the console descriptor (+0x00 root signature, - // +0x28 code blob, +0x30 code size) to D3D12_COMPUTE_PIPELINE_STATE_DESC and calls CreateComputePipelineState. + // +0x28 kind 6 code blob, +0x30 code size) to D3D12_COMPUTE_PIPELINE_STATE_DESC and calls CreateComputePipelineState. struct XboxNativeComputeDesc { ID3D12RootSignature* root_signature; - const void* ptr1; - std::uint64_t size1; - const void* ptr2; - std::uint64_t size2; - const void* code; - std::uint64_t code_size; + const void* kind0; + std::uint64_t kind0_size; + const void* kind1; + std::uint64_t kind1_size; + const void* kind6; + std::uint64_t kind6_size; + const void* kind7; + std::uint64_t kind7_size; } xbox_desc{}; xbox_desc.root_signature = root_signature.Get(); - xbox_desc.code = bytecode->GetBufferPointer(); - xbox_desc.code_size = bytecode->GetBufferSize(); + xbox_desc.kind6 = bytecode->GetBufferPointer(); + xbox_desc.kind6_size = bytecode->GetBufferSize(); using XboxCreateNativeComputePsoFn = HRESULT(WINAPI*)(void*, const void*, const IID*, void**); auto create_native_pso = reinterpret_cast(proxy_vtbl[67]); From ec9b6cf22b27545b99fedc8583c0a392d835ece0 Mon Sep 17 00:00:00 2001 From: Ewann <207907827+dev-ewann@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:17:59 +0000 Subject: [PATCH 021/115] tools: text reports are written with LF line ends on every platform (BUILD-468) open(path, "w") without newline= turns each \n into \r\n on Windows, so the same JSON report, manifest or assembly listing was CRLF there and LF elsewhere. 91 text-mode writes (open, os.fdopen, Path.write_text) under tools/, scripts/, make_game.py and runtime/test/shaders/ now pass newline="\n". tests/test_text_write_line_endings.py reads the source with ast and fails for a writer that forgets it; CONTRIBUTING.md names the convention. AI-assisted (Claude), on behalf of dev-ewann. --- CONTRIBUTING.md | 3 + make_game.py | 14 ++--- runtime/test/shaders/build.py | 4 +- scripts/audit_shader4_regs.py | 2 +- scripts/run_gpu_tests.py | 2 +- scripts/run_wine_tests.py | 2 +- tests/test_text_write_line_endings.py | 88 +++++++++++++++++++++++++++ tools/ab_control_flow.py | 4 +- tools/analyze_4240_full.py | 2 +- tools/anim_clips.py | 2 +- tools/anim_index.py | 4 +- tools/awc_names.py | 2 +- tools/bink_index.py | 2 +- tools/bink_names.py | 2 +- tools/bvh_index.py | 2 +- tools/cf_diff.py | 2 +- tools/classify_carve.py | 2 +- tools/crosslane_fuzz.py | 8 +-- tools/f16_trans_sweep.py | 2 +- tools/f32_fuzz.py | 4 +- tools/feature_scan.py | 2 +- tools/fma_mix_probe.py | 4 +- tools/fspx_unpack.py | 6 +- tools/fssm_unpack.py | 2 +- tools/gamedata_graph.py | 2 +- tools/gamedata_index.py | 2 +- tools/gamedata_maps.py | 2 +- tools/gamedata_xml.py | 2 +- tools/hashdict.py | 2 +- tools/hw_oracle/runner.py | 2 +- tools/image_fuzz.py | 4 +- tools/instance_lists.py | 2 +- tools/lds_fuzz.py | 6 +- tools/manifest.py | 2 +- tools/mem_diff.py | 2 +- tools/meshlet_page.py | 4 +- tools/navmesh_decode.py | 2 +- tools/navmesh_index.py | 2 +- tools/page_index.py | 2 +- tools/pe_inspect.py | 4 +- tools/psin_names.py | 2 +- tools/rbf0_index.py | 2 +- tools/rdna2spirv.py | 4 +- tools/restofworld_index.py | 2 +- tools/rpf9_carve.py | 2 +- tools/rpf9_names.py | 2 +- tools/rpf_probe.py | 2 +- tools/salu_diff.py | 2 +- tools/save_keys.py | 2 +- tools/saves.py | 10 +-- tools/shader_carve.py | 2 +- tools/shader_diff.py | 2 +- tools/shader_disasm.py | 2 +- tools/shader_profile.py | 2 +- tools/skin_streams.py | 2 +- tools/spirv_gs_to_compute.py | 2 +- tools/story_index.py | 2 +- tools/tex_export.py | 2 +- tools/tex_headers.py | 2 +- tools/ttpf_mips.py | 2 +- tools/turing_atlas.py | 4 +- tools/user_sgpr_census.py | 2 +- tools/valu_fuzz.py | 4 +- tools/vertex_types.py | 2 +- tools/wave64_graphics_scan.py | 2 +- tools/world_census.py | 2 +- tools/world_index.py | 4 +- tools/world_names.py | 2 +- 68 files changed, 186 insertions(+), 95 deletions(-) create mode 100644 tests/test_text_write_line_endings.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6a0a332a83..400e1d0d8d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,6 +27,9 @@ methods are still open. ## Working on the code - Python tools run with `python -I` and use only the standard library unless a file says otherwise. +- A text file a tool writes (JSON, CSV, a manifest, an assembly listing) names its line ending: `open(path, "w", + encoding="utf-8", newline="\n")`, so the output is LF on Windows too and the same input gives the same bytes on every + platform. `tests/test_text_write_line_endings.py` fails for a writer that forgets it. - `tools/rpf9dump` needs the submodule: `git submodule update --init`. - A new shader-translator rule goes into the contract table in `docs/design.md`, with how it was confirmed: a GPU test, a Mesa/LLVM reference, or a count over the corpus. diff --git a/make_game.py b/make_game.py index 397fad2cf1..2f6de835a6 100644 --- a/make_game.py +++ b/make_game.py @@ -682,7 +682,7 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate drop(translated, shard_plan, disassembled) clear_shader_disassembly(work, disasm) py("shader_disasm.py", os.path.join(dxbc, "fssm"), "--out", disasm, "--mcpu", "gfx1013", "--jobs", jobs) - with open(disassembled, "w", encoding="utf-8") as f: + with open(disassembled, "w", encoding="utf-8", newline="\n") as f: f.write(signature + "\n") # The translation also depends on the translator's own files, so their digest is kept beside it. A folder without # it (from before the file existed), with an unreadable one or with another one is translated again; carving, unpacking and @@ -726,11 +726,11 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate # a stop at any point then leaves either no index (translated again) or an index with the right mode and # digest, never a guessed one. rdna2spirv.py --merge writes index.json last, after the stubs. os.makedirs(spirv, exist_ok=True) - with open(mode_file, "w", encoding="utf-8") as f: + with open(mode_file, "w", encoding="utf-8", newline="\n") as f: f.write(want + "\n") - with open(flags_file, "w", encoding="utf-8") as f: + with open(flags_file, "w", encoding="utf-8", newline="\n") as f: f.write(want_flags + "\n") - with open(sources_file, "w", encoding="utf-8") as f: + with open(sources_file, "w", encoding="utf-8", newline="\n") as f: f.write(sources + "\n") translate(disasm, spirv, jobs, emulate=emulate, fallbacks=fallbacks) log("shaders: done") @@ -909,7 +909,7 @@ def translate(disasm: str, spirv: str, jobs: int, emulate: bool = False, for f in os.listdir(spirv): if f.startswith("index.part") and f.endswith(".json"): os.remove(os.path.join(spirv, f)) - with open(plan_path, "w", encoding="utf-8") as f: + with open(plan_path, "w", encoding="utf-8", newline="\n") as f: json.dump(plan, f) todo = [i for i in range(jobs) if not os.path.isfile(os.path.join(spirv, f"index.part{i}.json"))] if len(todo) < jobs: @@ -1058,7 +1058,7 @@ def assets(game: str, work: str, wav: bool, jobs: int) -> None: def mark(path: str, what: str) -> None: """Write a step's completion marker; call it only after the step succeeded.""" - with open(path, "w", encoding="utf-8") as f: + with open(path, "w", encoding="utf-8", newline="\n") as f: f.write(f"{what} finished\n") @@ -1177,7 +1177,7 @@ def runtime(game: str, out: str, v: dict, runtime_build: str | None = None, jobs if not os.path.exists(os.path.join(out, os.path.basename(built))) or \ not os.path.samefile(built, os.path.join(out, os.path.basename(built))): shutil.copy2(built, out) - with open(os.path.join(out, "game_path.txt"), "w", encoding="utf-8") as f: + with open(os.path.join(out, "game_path.txt"), "w", encoding="utf-8", newline="\n") as f: f.write(os.path.abspath(game)) start = os.path.join(out, "gta6rt.exe") if os.name != "nt": diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index c9796f244d..2aa101e5b6 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py @@ -108,7 +108,7 @@ def translate_tests(work, names): sys.exit(f"{n}.asm did not assemble:\n{r.stderr}") # rdna2spirv.py rejects assembler directives such as the "\t.text" llvm-mc prints first. code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith(".")) - (disasm / (n + ".s")).write_text(f"; {n} hand-written test\n{code}", encoding="utf-8") + (disasm / (n + ".s")).write_text(f"; {n} hand-written test\n{code}", encoding="utf-8", newline="\n") program = None if n.startswith("cs_") else asm_fssm(asm_path) if program: # where the translator looks for a program to hash, as in the game's work folder (fssm / (n + ".fssm")).write_bytes(program) @@ -168,7 +168,7 @@ def main(): published_index = spirv / index.name combined = json.loads(published_index.read_text(encoding="utf-8")) if published_index.exists() else {} combined.update(validated) - index.write_text(json.dumps(combined, indent=2) + "\n", encoding="utf-8") + index.write_text(json.dumps(combined, indent=2) + "\n", encoding="utf-8", newline="\n") for n in validated: for suffix in (".spv", ".spvasm"): artifact = built / (n + suffix) diff --git a/scripts/audit_shader4_regs.py b/scripts/audit_shader4_regs.py index ac22c856c1..6a6c449dea 100644 --- a/scripts/audit_shader4_regs.py +++ b/scripts/audit_shader4_regs.py @@ -371,7 +371,7 @@ def main(argv=None): if a.json_out: try: os.makedirs(os.path.dirname(os.path.abspath(a.json_out)), exist_ok=True) - with open(a.json_out, "w", encoding="utf-8") as f: + with open(a.json_out, "w", encoding="utf-8", newline="\n") as f: json.dump(rep, f, indent=2) f.write("\n") except OSError as e: diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 7209c364c3..504f1ceb7d 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -115,7 +115,7 @@ def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None: continue if ln.startswith("\t"): lines.append(ln) - with open(s_path, "w", encoding="utf-8") as f: + with open(s_path, "w", encoding="utf-8", newline="\n") as f: f.write("\n".join(lines) + "\n") diff --git a/scripts/run_wine_tests.py b/scripts/run_wine_tests.py index b55ea9b91c..0a02525e53 100644 --- a/scripts/run_wine_tests.py +++ b/scripts/run_wine_tests.py @@ -251,7 +251,7 @@ def main() -> int: if args.summary: try: _make_parent(args.summary) - with open(args.summary, "a", encoding="utf-8") as f: + with open(args.summary, "a", encoding="utf-8", newline="\n") as f: f.write(f"### Windows tests under {args.label or 'Wine'}\n\n") f.write(f"{counts['pass']} passed, {counts['fail']} failed, {counts['skip']} skipped.\n\n") f.write("| Test | Result | Required |\n|---|---|---|\n") diff --git a/tests/test_text_write_line_endings.py b/tests/test_text_write_line_endings.py new file mode 100644 index 0000000000..e8be2944b0 --- /dev/null +++ b/tests/test_text_write_line_endings.py @@ -0,0 +1,88 @@ +"""Every text-mode file write in the Python tools names its line ending (BUILD-468). + +`open(path, "w")` with no `newline=` turns each "\\n" into "\\r\\n" on Windows, so the same JSON report, manifest or +assembly listing is CRLF there and LF on Linux and macOS: the same input gives byte-different output per platform +(checksums and diffs differ). The CSV writers were fixed in #1573; this covers the other text writers. This test reads +the source with `ast` (standard library, no game data, no GPU) and fails for any `open` / `os.fdopen` in a text write +mode (`w`, `a`, `x`) or any `Path.write_text` under tools/, scripts/, make_game.py and runtime/test/shaders/ that has +no `newline=` argument. Pass `newline="\\n"` for LF output (or `newline=""` when the text carries its own line ends, +like a csv writer). +""" +import ast +import os +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +SCAN = ("tools", "scripts", "make_game.py", os.path.join("runtime", "test", "shaders")) + + +def python_files(): + for entry in SCAN: + path = os.path.join(ROOT, entry) + if os.path.isfile(path): + yield path + continue + for base, dirs, files in os.walk(path): + dirs[:] = [d for d in dirs if d not in ("__pycache__", "build") and not d.startswith(".")] + for name in sorted(files): + if name.endswith(".py"): + yield os.path.join(base, name) + + +def unpinned_text_writes(source: str): + """Line numbers of text-mode writes in `source` that pass no `newline=`.""" + found = [] + for node in ast.walk(ast.parse(source)): + if not isinstance(node, ast.Call): + continue + func = node.func + name = getattr(func, "attr", getattr(func, "id", None)) + if any(k.arg == "newline" for k in node.keywords): + continue + if name in ("open", "fdopen"): + mode = None + if len(node.args) >= 2 and isinstance(node.args[1], ast.Constant): + mode = node.args[1].value + for k in node.keywords: + if k.arg == "mode" and isinstance(k.value, ast.Constant): + mode = k.value.value + if isinstance(mode, str) and "b" not in mode and any(c in mode for c in "wax"): + found.append(node.lineno) + elif name == "write_text": + found.append(node.lineno) + return found + + +class TextWriteLineEndings(unittest.TestCase): + def test_detector_finds_the_unpinned_forms(self): + src = ( + "open('a', 'w')\n" # 1 + "open('a', 'w', encoding='utf-8')\n" # 2 + "open('a', mode='a')\n" # 3 + "os.fdopen(3, 'w', encoding='utf-8')\n" # 4 + "p.write_text('x', encoding='utf-8')\n" # 5 + "open('a', 'w', newline='\\n')\n" # pinned + "open('a', 'w', newline='')\n" # pinned + "open('a', 'wb')\n" # binary + "open('a')\n" # read + "open('a', 'r', encoding='utf-8')\n" # read + "p.write_text('x', newline='\\n')\n" # pinned + ) + self.assertEqual(unpinned_text_writes(src), [1, 2, 3, 4, 5]) + + def test_every_text_write_pins_its_newline(self): + bad = [] + count = 0 + for path in python_files(): + count += 1 + with open(path, encoding="utf-8") as f: + for line in unpinned_text_writes(f.read()): + bad.append(f"{os.path.relpath(path, ROOT)}:{line}") + self.assertGreater(count, 50, "the scan found almost no Python files; is the layout different?") + self.assertEqual(bad, [], "text writes without newline= (CRLF on Windows, LF elsewhere): " + ", ".join(bad)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/ab_control_flow.py b/tools/ab_control_flow.py index 577c402c11..d38b33a857 100644 --- a/tools/ab_control_flow.py +++ b/tools/ab_control_flow.py @@ -111,7 +111,7 @@ def write_outcomes(out_dir, outcomes): """Write (shader name, outcome) pairs to the harness's tab-separated report.""" os.makedirs(out_dir, exist_ok=True) path = os.path.join(out_dir, "outcomes.tsv") - with open(path, "w", encoding="utf-8") as f: + with open(path, "w", encoding="utf-8", newline="\n") as f: f.write("".join(f"{name}\t{outcome}\n" for name, outcome in outcomes)) return path @@ -169,7 +169,7 @@ def test_vertex_shader(out_dir, runner=None): """ src, dst = os.path.join(out_dir, "test_vs.spvasm"), os.path.join(out_dir, "test_vs.spv") os.makedirs(out_dir, exist_ok=True) - with open(src, "w", encoding="utf-8") as f: + with open(src, "w", encoding="utf-8", newline="\n") as f: f.write(asm) runner(["spirv-as", "--target-env", "vulkan1.2", src, "-o", dst], check=True) runner(["spirv-val", "--target-env", "vulkan1.2", dst], check=True) diff --git a/tools/analyze_4240_full.py b/tools/analyze_4240_full.py index 3dd9c243c0..e5b6f50e37 100644 --- a/tools/analyze_4240_full.py +++ b/tools/analyze_4240_full.py @@ -352,7 +352,7 @@ def main() -> int: parent = os.path.dirname(os.path.abspath(args.json)) if parent: # every archive has been read by now; a missing folder used to lose the run os.makedirs(parent, exist_ok=True) - with open(args.json, "w", encoding="utf-8") as f: + with open(args.json, "w", encoding="utf-8", newline="\n") as f: json.dump(output, f, indent=2) return status diff --git a/tools/anim_clips.py b/tools/anim_clips.py index 047a9834af..ca48ea5cb6 100644 --- a/tools/anim_clips.py +++ b/tools/anim_clips.py @@ -886,7 +886,7 @@ def progress(n, total): parent = os.path.dirname(os.path.abspath(a.out)) if parent: os.makedirs(parent, exist_ok=True) - with open(a.out, "w", encoding="utf-8") as f: + with open(a.out, "w", encoding="utf-8", newline="\n") as f: json.dump({"summary": summary, "dictionaries": rows}, f, indent=1) except OSError as e: sys.exit(f"{a.out}: cannot write: {e.strerror or e}") diff --git a/tools/anim_index.py b/tools/anim_index.py index 29d5906856..119b81613c 100644 --- a/tools/anim_index.py +++ b/tools/anim_index.py @@ -454,7 +454,7 @@ def write_output(path, rows, summary): """Write CSV or JSON from the file extension. CSV writes one summary line to stderr.""" ext = os.path.splitext(path)[1].lower() if ext == ".json": - with open(path, "w", encoding="utf-8") as f: + with open(path, "w", encoding="utf-8", newline="\n") as f: json.dump({"summary": summary, "files": rows}, f, indent=1) return with open(path, "w", encoding="utf-8", newline="") as f: @@ -570,7 +570,7 @@ def progress(n, pos, end): print(f"{a.source}: RBF0 stream: {e}", file=sys.stderr) return 2 try: - with open(a.rigs, "w", encoding="utf-8") as f: + with open(a.rigs, "w", encoding="utf-8", newline="\n") as f: json.dump({"rbf0": rbf0, "skeletons": skeletons}, f, indent=1) except OSError as e: sys.exit(f"{a.rigs}: cannot write: {e.strerror or e}") diff --git a/tools/awc_names.py b/tools/awc_names.py index ae8b345fe1..42febeb9bc 100644 --- a/tools/awc_names.py +++ b/tools/awc_names.py @@ -317,7 +317,7 @@ def main(argv=None) -> int: if a.out: try: if a.out.lower().endswith(".json"): - with open(a.out, "w", encoding="utf-8") as fh: + with open(a.out, "w", encoding="utf-8", newline="\n") as fh: json.dump({"summary": summary, "streams": rows}, fh, indent=1) else: with open(a.out, "w", encoding="utf-8", newline="") as fh: diff --git a/tools/bink_index.py b/tools/bink_index.py index 2b82328349..0d4ac4315a 100644 --- a/tools/bink_index.py +++ b/tools/bink_index.py @@ -285,7 +285,7 @@ def write_csv(path, rows, probe): def write_json(path, target, rows, summary, probe): fields = BASE_FIELDS + (PROBE_FIELDS if probe else []) streams = [_flat(row, fields) for row in rows] - with open(path, "w", encoding="utf-8") as fh: + with open(path, "w", encoding="utf-8", newline="\n") as fh: json.dump({"target": target, "summary": summary, "streams": streams}, fh, indent=1) diff --git a/tools/bink_names.py b/tools/bink_names.py index 13bc9b12a2..92d64a5d34 100644 --- a/tools/bink_names.py +++ b/tools/bink_names.py @@ -299,7 +299,7 @@ def name_streams(names, streams, pins=None, max_skip=MAX_SKIP): def write(out, rows, unmatched, summary): if out.lower().endswith(".json"): - with open(out, "w", encoding="utf-8") as fh: + with open(out, "w", encoding="utf-8", newline="\n") as fh: json.dump({"summary": summary, "streams": rows, "unmatched_list_entries": unmatched}, fh, indent=1) else: with open(out, "w", encoding="utf-8", newline="") as fh: diff --git a/tools/bvh_index.py b/tools/bvh_index.py index 90bcd3bbc1..5017745538 100644 --- a/tools/bvh_index.py +++ b/tools/bvh_index.py @@ -351,7 +351,7 @@ def write_outputs(rows, summaries, out, csv_path): if out: _make_parent(out) payload = summaries if len(summaries) > 1 else (summaries[0] if summaries else {}) - with open(out, "w", encoding="utf-8") as f: + with open(out, "w", encoding="utf-8", newline="\n") as f: json.dump({"summary": payload, "streams": rows}, f, indent=0) if csv_path: _make_parent(csv_path) diff --git a/tools/cf_diff.py b/tools/cf_diff.py index 741e215614..70d144753d 100644 --- a/tools/cf_diff.py +++ b/tools/cf_diff.py @@ -567,7 +567,7 @@ def self_test(): e.items = [it for it in e.items if not (it[0] == "ins" and it[1].startswith("s_or_b32 exec_lo"))] with tempfile.TemporaryDirectory(prefix="cf-diff-") as tmp: p = os.path.join(tmp, "c.s") - with open(p, "w", encoding="utf-8") as f: + with open(p, "w", encoding="utf-8", newline="\n") as f: f.write(listing_text(e.assemble(), "ps_canary_bad")) if len(cf_ref.run(p, wave=32)["exports"]) != 4: # 4 > lane: lanes 0-3 stay on print("canary FAILED: the reference did not drop lanes whose EXEC was never restored") diff --git a/tools/classify_carve.py b/tools/classify_carve.py index 1c3e6f5d26..819de999f4 100644 --- a/tools/classify_carve.py +++ b/tools/classify_carve.py @@ -102,7 +102,7 @@ def main(): out = {"overall": {k: entry(v) for k, v in top}, "per_archive": per} fd, temp = tempfile.mkstemp(dir=root, prefix=".types-", suffix=".tmp") try: - with os.fdopen(fd, "w", encoding="utf-8") as f: + with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, indent=1) f.flush() os.fsync(f.fileno()) diff --git a/tools/crosslane_fuzz.py b/tools/crosslane_fuzz.py index 92b9ea3fb6..7072978c35 100644 --- a/tools/crosslane_fuzz.py +++ b/tools/crosslane_fuzz.py @@ -739,10 +739,10 @@ def assemble(mc, prog, src, disasm, fssm): if r.returncode or "error:" in r.stderr: raise RuntimeError(f"{prog.name} did not assemble:\n{r.stderr}\n{src}") code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith(".")) - with open(os.path.join(disasm, prog.name + ".s"), "w", encoding="utf-8") as f: + with open(os.path.join(disasm, prog.name + ".s"), "w", encoding="utf-8", newline="\n") as f: f.write(f"; {prog.name} crosslane_fuzz\n{code}") asm_path = os.path.join(fssm, prog.name + ".asm") - with open(asm_path, "w", encoding="utf-8") as f: + with open(asm_path, "w", encoding="utf-8", newline="\n") as f: f.write(src) with open(os.path.join(fssm, prog.name + ".fssm"), "wb") as f: f.write(compute_fixture.compute_header(asm_path)) @@ -1008,7 +1008,7 @@ def main(): print(describe(p, bad)) if args.keep: os.makedirs(args.keep, exist_ok=True) - with open(os.path.join(args.keep, f"{p.name}_{mode}.asm"), "w", encoding="utf-8") as f: + with open(os.path.join(args.keep, f"{p.name}_{mode}.asm"), "w", encoding="utf-8", newline="\n") as f: f.write(kept_source(p, mode, None, not args.no_hw_guard)) if args.minimize and bad and what.startswith("mismatch"): if mode == "hw": @@ -1021,7 +1021,7 @@ def main(): print(" minimized:\n\t" + "\n\t".join(o.text + (" ; hypothesis op" if i in hyp_ops else "") for i, o in enumerate(ops))) if args.keep: - with open(os.path.join(args.keep, f"{p.name}_{mode}_min.asm"), "w", encoding="utf-8") as f: + with open(os.path.join(args.keep, f"{p.name}_{mode}_min.asm"), "w", encoding="utf-8", newline="\n") as f: f.write(kept_source(p, mode, ops, not args.no_hw_guard)) finally: if oracle: diff --git a/tools/f16_trans_sweep.py b/tools/f16_trans_sweep.py index 2b7f377df4..96dd542d47 100644 --- a/tools/f16_trans_sweep.py +++ b/tools/f16_trans_sweep.py @@ -454,7 +454,7 @@ def main(argv=None): finally: oracle.close() if a.json: - with open(a.json, "w", encoding="utf-8") as f: + with open(a.json, "w", encoding="utf-8", newline="\n") as f: json.dump(report, f, indent=1) return rc diff --git a/tools/f32_fuzz.py b/tools/f32_fuzz.py index 7c23a58fd6..09d464530a 100644 --- a/tools/f32_fuzz.py +++ b/tools/f32_fuzz.py @@ -687,7 +687,7 @@ def run_translated(text, name="ps_f32_fuzz"): dis = os.path.join(tmp, "disasm") os.mkdir(dis) path = os.path.join(dis, name + ".s") - with open(path, "w", encoding="utf-8") as f: + with open(path, "w", encoding="utf-8", newline="\n") as f: f.write(text) with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: f.write(STUB_DXBC) @@ -1727,7 +1727,7 @@ def main(argv=None): if a.keep and rep.mismatches: os.makedirs(a.keep, exist_ok=True) for k, (c, _, _) in enumerate(rep.mismatches): - with open(os.path.join(a.keep, f"{c.group}_{c.index}_{c.op}_{k}.asm"), "w", encoding="utf-8") as f: + with open(os.path.join(a.keep, f"{c.group}_{c.index}_{c.op}_{k}.asm"), "w", encoding="utf-8", newline="\n") as f: f.write("\n".join(hw_lines(c, oracle.arch, not a.no_hw_guard)) + "\n") if a.perturb: print(f"perturbed model '{a.perturb}': {n_mis} mismatches" + ("" if n_mis else " -- NOT DETECTED")) diff --git a/tools/feature_scan.py b/tools/feature_scan.py index 622a0bf8e5..6e44519576 100644 --- a/tools/feature_scan.py +++ b/tools/feature_scan.py @@ -375,7 +375,7 @@ def main() -> int: folder = os.path.dirname(a.out) # --out into a folder that does not exist yet, as awc_manifest.py does if folder: os.makedirs(folder, exist_ok=True) - with open(a.out, "w", encoding="utf-8") as f: + with open(a.out, "w", encoding="utf-8", newline="\n") as f: json.dump(result, f, indent=1) return 0 diff --git a/tools/fma_mix_probe.py b/tools/fma_mix_probe.py index 23cf1f8d6d..7a77fe486b 100644 --- a/tools/fma_mix_probe.py +++ b/tools/fma_mix_probe.py @@ -179,7 +179,7 @@ def verdict(results): def _translate(work, name, text, fssm=None): os.makedirs(os.path.join(work, "disasm"), exist_ok=True) src = os.path.join(work, "disasm", name + ".s") - with open(src, "w", encoding="utf-8") as f: + with open(src, "w", encoding="utf-8", newline="\n") as f: f.write(text) with open(os.path.join(work, name + ".dxbc"), "wb") as f: f.write(STUB_DXBC) @@ -264,7 +264,7 @@ def run_vulkan(build, cases=CASES): with tempfile.TemporaryDirectory(prefix="fma_mix_probe_") as work: text = translate_cs(work, cases) sa, sv = os.path.join(work, "cs.spvasm"), os.path.join(work, "cs.spv") - with open(sa, "w", encoding="utf-8") as f: + with open(sa, "w", encoding="utf-8", newline="\n") as f: f.write(text) try: r = subprocess.run(["spirv-as", sa, "-o", sv, "--target-env", "vulkan1.2"], capture_output=True, text=True) diff --git a/tools/fspx_unpack.py b/tools/fspx_unpack.py index ea79e8001c..9abd6f771e 100644 --- a/tools/fspx_unpack.py +++ b/tools/fspx_unpack.py @@ -207,19 +207,19 @@ def main(argv=None) -> int: f.write(container) with open(os.path.join(a.out, "fspx", name + ".code"), "wb") as f: f.write(blob[6]) - with open(os.path.join(a.out, "fspx", name + ".json"), "w", encoding="utf-8") as f: + with open(os.path.join(a.out, "fspx", name + ".json"), "w", encoding="utf-8", newline="\n") as f: json.dump(meta, f, indent=1) if disasm and meta["code"]["end"]: start, end = meta["code"]["start"], meta["code"]["end"] asm, invalid, err = disasm.disasm(blob[6][start:end], a.mcpu) entry["invalid_words"] = invalid - with open(os.path.join(a.out, "disasm", name + ".s"), "w", encoding="utf-8") as f: + with open(os.path.join(a.out, "disasm", name + ".s"), "w", encoding="utf-8", newline="\n") as f: f.write(f"; {name} code 0x{start:x}..0x{end:x} (fspx), {a.mcpu}, {invalid} invalid words\n") f.write(asm) if err.strip(): f.write("\n; --- llvm-mc messages ---\n; " + err.strip().replace("\n", "\n; ") + "\n") index.append(entry) - with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8") as f: + with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(index, f, indent=1) print(f"{len(index)} FSPX program(s) unpacked to {a.out}" + (f", {bad} input(s) failed" if bad else "")) return 1 if bad else 0 diff --git a/tools/fssm_unpack.py b/tools/fssm_unpack.py index a463465b9a..1a462144ca 100644 --- a/tools/fssm_unpack.py +++ b/tools/fssm_unpack.py @@ -153,7 +153,7 @@ def main(argv=None) -> int: "game version.", file=sys.stderr) return 1 tmp = os.path.join(src, "fssm_index.json.tmp") # written last and renamed in, so a stopped run leaves none - with open(tmp, "w", encoding="utf-8") as f: + with open(tmp, "w", encoding="utf-8", newline="\n") as f: json.dump(rows, f) f.flush() os.fsync(f.fileno()) diff --git a/tools/gamedata_graph.py b/tools/gamedata_graph.py index ec1126ade0..507aac4a98 100644 --- a/tools/gamedata_graph.py +++ b/tools/gamedata_graph.py @@ -624,7 +624,7 @@ def main() -> int: print_summary(graph) if args.json: try: - with open(args.json, "w", encoding="utf-8") as f: + with open(args.json, "w", encoding="utf-8", newline="\n") as f: json.dump(graph, f, indent=1) except OSError as exc: print(f"cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) diff --git a/tools/gamedata_index.py b/tools/gamedata_index.py index 732ff0d30c..c06d013940 100644 --- a/tools/gamedata_index.py +++ b/tools/gamedata_index.py @@ -435,7 +435,7 @@ def main() -> int: write_csv(a.csv, rows) if a.json: _make_parent(a.json) - with open(a.json, "w", encoding="utf-8") as f: + with open(a.json, "w", encoding="utf-8", newline="\n") as f: json.dump({"summary": summary, "rows": rows}, f, indent=1) print(f'{summary["streams"]} streams, {summary["stored"]:,} stored, ' diff --git a/tools/gamedata_maps.py b/tools/gamedata_maps.py index d3d465f0e7..56fa68ca03 100644 --- a/tools/gamedata_maps.py +++ b/tools/gamedata_maps.py @@ -385,7 +385,7 @@ def main() -> int: if census: out["pamh_census"] = census try: - with open(a.json, "w", encoding="utf-8") as f: + with open(a.json, "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, indent=1) except OSError as e: print(f"error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) diff --git a/tools/gamedata_xml.py b/tools/gamedata_xml.py index 02cea8dee7..e869dc2345 100644 --- a/tools/gamedata_xml.py +++ b/tools/gamedata_xml.py @@ -635,7 +635,7 @@ def main() -> int: if args.json: public_rows = [{key: value for key, value in row.items() if key != "_scan"} for row in rows] _make_parent(args.json) - with open(args.json, "w", encoding="utf-8") as f: + with open(args.json, "w", encoding="utf-8", newline="\n") as f: json.dump({"summary": summary, "roots": agg["roots"], "rows": public_rows}, f, indent=1) print("wrote", args.json) return 0 if clean else 1 diff --git a/tools/hashdict.py b/tools/hashdict.py index cc8da2acec..02c5c045c4 100644 --- a/tools/hashdict.py +++ b/tools/hashdict.py @@ -152,7 +152,7 @@ def main(): # Other tools create the output parent too: a long harvest must not be lost to a missing folder. try: os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) - with open(a.out, "w", encoding="utf-8") as f: + with open(a.out, "w", encoding="utf-8", newline="\n") as f: json.dump(d, f) except OSError as e: print(f"ERROR: cannot write {a.out}: {e}", file=sys.stderr) diff --git a/tools/hw_oracle/runner.py b/tools/hw_oracle/runner.py index bd19f06672..a89f428179 100644 --- a/tools/hw_oracle/runner.py +++ b/tools/hw_oracle/runner.py @@ -136,7 +136,7 @@ def build_command(kind, cc, src, out, workdir): installer = os.path.join(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"), "Microsoft Visual Studio", "Installer") script = os.path.join(workdir, "build_hw_oracle.cmd") - with open(script, "w", encoding="ascii") as f: + with open(script, "w", encoding="ascii", newline="\n") as f: f.write(f'@echo off\r\nset "PATH={installer};%PATH%"\r\ncall "{cc}" >nul || exit /b 1\r\n' + subprocess.list2cmdline(cl) + "\r\n") return ["cmd.exe", "/d", "/c", script] diff --git a/tools/image_fuzz.py b/tools/image_fuzz.py index 2fb8577324..709ffa595a 100644 --- a/tools/image_fuzz.py +++ b/tools/image_fuzz.py @@ -88,7 +88,7 @@ def assemble(asm: str, name: str, work: str) -> None: if not line.lstrip().startswith(".")) disasm = os.path.join(work, "disasm") os.makedirs(disasm, exist_ok=True) - with open(os.path.join(disasm, name + ".s"), "w", encoding="utf-8") as f: + with open(os.path.join(disasm, name + ".s"), "w", encoding="utf-8", newline="\n") as f: f.write(f"; {name} generated by tools/image_fuzz.py\n{code}") with open(os.path.join(work, name + ".dxbc"), "wb") as f: f.write(bytes(32)) # chunk count 0: no signatures, the stage comes from the name @@ -268,7 +268,7 @@ def run_case(fmt_name, width, height, rng, work, build, keep, show, dmask=0xf, d with open(texels_path, "wb") as f: f.write(texels) spec_path = os.path.join(work, "spec.txt") - with open(spec_path, "w", encoding="utf-8") as f: + with open(spec_path, "w", encoding="utf-8", newline="\n") as f: f.write(f"width={width}\nheight={height}\nformat={vk_format}\ntexels={texels_path}\n" f"tsharp={','.join(hex(w) for w in tsharp)}\n") out_path = os.path.join(work, "out.raw") diff --git a/tools/instance_lists.py b/tools/instance_lists.py index 988f35563d..bc7fedd968 100644 --- a/tools/instance_lists.py +++ b/tools/instance_lists.py @@ -357,7 +357,7 @@ def main(argv=None): if args.json: try: os.makedirs(os.path.dirname(os.path.abspath(args.json)), exist_ok=True) - with open(args.json, "w", encoding="utf-8") as fh: + with open(args.json, "w", encoding="utf-8", newline="\n") as fh: json.dump(T, fh, indent=1, sort_keys=True) except OSError as exc: print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) diff --git a/tools/lds_fuzz.py b/tools/lds_fuzz.py index 6b3bb4ca8f..fbcc885c12 100644 --- a/tools/lds_fuzz.py +++ b/tools/lds_fuzz.py @@ -739,7 +739,7 @@ def translate(progs, work, emulate): for p in progs: text = p.asm() asm_path = work / (p.name + ".asm") - asm_path.write_text(text, encoding="utf-8") + asm_path.write_text(text, encoding="utf-8", newline="\n") cmd = mc + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"] if p.wave == 64: cmd.append("-mattr=+wavefrontsize64,-wavefrontsize32") @@ -747,7 +747,7 @@ def translate(progs, work, emulate): if r.returncode or "error:" in r.stderr: raise RuntimeError(f"{p.name} did not assemble:\n{r.stderr}") code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith(".")) - (disasm / (p.name + ".s")).write_text(f"; {p.name}\n{code}", encoding="utf-8") + (disasm / (p.name + ".s")).write_text(f"; {p.name}\n{code}", encoding="utf-8", newline="\n") (fssm / (p.name + ".fssm")).write_bytes(compute_header(asm_path)) cmd = [sys.executable, "-I", os.path.join(HERE, "rdna2spirv.py"), str(disasm), "--out", str(spirv)] if emulate: @@ -943,7 +943,7 @@ def run_hw(oracle, progs, a, tally, results): print(f" {ops[i]}" + (" ; hypothesis op" if ops[i].get("hyp") else "")) if a.keep: os.makedirs(a.keep, exist_ok=True) - Path(a.keep, f"{p.name}_hw.s").write_text("\n".join(p.hw_lines(oracle.arch)) + "\n", encoding="utf-8") + Path(a.keep, f"{p.name}_hw.s").write_text("\n".join(p.hw_lines(oracle.arch)) + "\n", encoding="utf-8", newline="\n") print("hardware summary:") for key, st in sorted(stats.items()): print(f" {key}: " + ", ".join(f"{k} {v}" for k, v in st.items())) diff --git a/tools/manifest.py b/tools/manifest.py index 9c39d90306..7324552964 100644 --- a/tools/manifest.py +++ b/tools/manifest.py @@ -148,7 +148,7 @@ def work(rel: str, path: str) -> tuple[str, int, str]: os.makedirs(out_dir, exist_ok=True) with tempfile.TemporaryDirectory(dir=out_dir) as staging: staged = os.path.join(staging, "manifest.json") - with open(staged, "w", encoding="utf-8") as f: + with open(staged, "w", encoding="utf-8", newline="\n") as f: json.dump({"created": time.strftime("%Y-%m-%d %H:%M:%S"), "files": entries}, f, indent=1) os.replace(staged, out) print(f"{len(entries)} files, {total / 2**30:.1f} GiB -> {out}") diff --git a/tools/mem_diff.py b/tools/mem_diff.py index 2be12e8bdc..ebee3554e8 100644 --- a/tools/mem_diff.py +++ b/tools/mem_diff.py @@ -640,7 +640,7 @@ def run_one(name, prog): dis = os.path.join(tmp, "disasm") os.mkdir(dis) path = os.path.join(dis, name + ".s") - with open(path, "w", encoding="utf-8") as f: + with open(path, "w", encoding="utf-8", newline="\n") as f: f.write(_listing(prog.lines)) with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: f.write(STUB_DXBC) diff --git a/tools/meshlet_page.py b/tools/meshlet_page.py index a2f8508aea..febba1dab6 100644 --- a/tools/meshlet_page.py +++ b/tools/meshlet_page.py @@ -487,7 +487,7 @@ def main(argv=None): report = json.dumps({"bindings": rows}, indent=2) if args.json: try: - with open(args.json, "w", encoding="utf-8") as out: + with open(args.json, "w", encoding="utf-8", newline="\n") as out: out.write(report + "\n") except OSError as exc: print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) @@ -514,7 +514,7 @@ def main(argv=None): print(json.dumps(total, indent=1)) if args.json: try: - with open(args.json, "w", encoding="utf-8") as fh: + with open(args.json, "w", encoding="utf-8", newline="\n") as fh: json.dump({"totals": total, "pages": pages}, fh, indent=1) except OSError as exc: print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) diff --git a/tools/navmesh_decode.py b/tools/navmesh_decode.py index 7571c2ae94..3b01bc381c 100644 --- a/tools/navmesh_decode.py +++ b/tools/navmesh_decode.py @@ -1011,7 +1011,7 @@ def main(argv=None): print("error: %s" % exc, file=sys.stderr) return 2 _make_parent(out) - with open(out, "w", encoding="utf-8") as f: + with open(out, "w", encoding="utf-8", newline="\n") as f: json.dump(summary, f, indent=1, allow_nan=False) if a.csv: write_csv(a.csv, rows) diff --git a/tools/navmesh_index.py b/tools/navmesh_index.py index 0fa6c7f83f..7ad5e0a2d7 100644 --- a/tools/navmesh_index.py +++ b/tools/navmesh_index.py @@ -198,7 +198,7 @@ def _make_parent(path): def write_outputs(rows, summary, out_path, csv_path): _make_parent(out_path) - with open(out_path, "w", encoding="utf-8") as f: + with open(out_path, "w", encoding="utf-8", newline="\n") as f: json.dump({"summary": summary, "pages": rows}, f, indent=1) written = [] if csv_path: diff --git a/tools/page_index.py b/tools/page_index.py index 41d9f3783c..059f4d91f3 100644 --- a/tools/page_index.py +++ b/tools/page_index.py @@ -316,7 +316,7 @@ def summarise(pages, mode, source): def write_json(path, pages, summary): - with open(path, "w", encoding="utf-8") as f: + with open(path, "w", encoding="utf-8", newline="\n") as f: json.dump({"summary": summary, "pages": pages}, f, indent=1) diff --git a/tools/pe_inspect.py b/tools/pe_inspect.py index 148318c150..e9d5d890b4 100644 --- a/tools/pe_inspect.py +++ b/tools/pe_inspect.py @@ -458,9 +458,9 @@ def main(argv: list[str] | None = None) -> int: rc = 1 continue try: - with open(json_path, "w", encoding="utf-8") as f: + with open(json_path, "w", encoding="utf-8", newline="\n") as f: json.dump(r, f, indent=1) - with open(md_path, "w", encoding="utf-8") as f: + with open(md_path, "w", encoding="utf-8", newline="\n") as f: f.write(to_markdown(r)) except OSError as e: print(f"{img}: cannot write report ({e.strerror or e})", file=sys.stderr) diff --git a/tools/psin_names.py b/tools/psin_names.py index 0c9b7281ed..021942f5fe 100644 --- a/tools/psin_names.py +++ b/tools/psin_names.py @@ -195,7 +195,7 @@ def main(): try: names = load_names(a.names) if a.refs: - with open(a.refs, "w", encoding="utf-8") as refs: + with open(a.refs, "w", encoding="utf-8", newline="\n") as refs: refs.write("file\tstruct\tfield\ttype\tvalue\tname\n") summary, table = scan(a.src, names, a.limit, refs) else: diff --git a/tools/rbf0_index.py b/tools/rbf0_index.py index c13122afae..cb41da559a 100644 --- a/tools/rbf0_index.py +++ b/tools/rbf0_index.py @@ -464,7 +464,7 @@ def write_output(path, records, summary, all_strings=False): doc["sample_strings"] = r["_all_strings"] if all_strings else r["sample"] doc["sample_truncated"] = not all_strings and r["strings"] > len(r["sample"]) docs.append(doc) - with open(path, "w", encoding="utf-8") as f: + with open(path, "w", encoding="utf-8", newline="\n") as f: json.dump({"summary": summary, "files": docs}, f, indent=1) return with open(path, "w", encoding="utf-8", newline="") as f: diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 9b6fe70df1..d356fac966 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -11260,7 +11260,7 @@ def write_index(path, index): """Write an index under another name and rename it into place, so a run stopped part-way never leaves half of one: make_game.py takes these files as proof that a shard, or the whole translation, finished.""" tmp = path + ".tmp" # must not end in .json: --merge globs index.part*.json - with open(tmp, "w", encoding="utf-8") as f: + with open(tmp, "w", encoding="utf-8", newline="\n") as f: _json.dump(index, f, indent=0, sort_keys=True) f.flush() os.fsync(f.fileno()) # on disk before the rename, or a power cut could leave the name with no data @@ -11403,7 +11403,7 @@ def main(): ok += 1 sa = os.path.join(a.out, name + ".spvasm") sv = os.path.join(a.out, name + ".spv") - with open(sa, "w") as f: + with open(sa, "w", newline="\n") as f: f.write(asm) r = assemble_spirv(sa, sv) if r.returncode == 0: diff --git a/tools/restofworld_index.py b/tools/restofworld_index.py index c890cf65b3..76b263ded6 100644 --- a/tools/restofworld_index.py +++ b/tools/restofworld_index.py @@ -322,7 +322,7 @@ def summarise(rows, span, zero, unread): def write_output(path, rows, summary): """Write CSV or JSON from the file extension.""" if os.path.splitext(path)[1].lower() == ".json": - with open(path, "w", encoding="utf-8") as f: + with open(path, "w", encoding="utf-8", newline="\n") as f: json.dump({"summary": summary, "files": rows}, f, indent=1) return with open(path, "w", encoding="utf-8", newline="") as f: diff --git a/tools/rpf9_carve.py b/tools/rpf9_carve.py index 43863d4cf6..9621ea212d 100644 --- a/tools/rpf9_carve.py +++ b/tools/rpf9_carve.py @@ -162,7 +162,7 @@ def main() -> int: "bink2_files": sum(1 for r in rows if r.get("type") == "bink2"), "zero_padding": zero, "unread_bytes": unread, "span": span} - with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8") as f: + with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8", newline="\n") as f: json.dump({"summary": summary, "files": rows}, f) print(json.dumps(summary, indent=1)) span = max(1, span) # an empty data area (or --start at the end) has nothing to divide by diff --git a/tools/rpf9_names.py b/tools/rpf9_names.py index f131f82d64..f2d50e8fc8 100644 --- a/tools/rpf9_names.py +++ b/tools/rpf9_names.py @@ -207,7 +207,7 @@ def publish_report(path, rows, summary): os.makedirs(directory, exist_ok=True) with tempfile.TemporaryDirectory(dir=directory, prefix=".rpf9_names-") as stage_dir: temp = os.path.join(stage_dir, "report.json") - with open(temp, "w", encoding="utf-8") as f: + with open(temp, "w", encoding="utf-8", newline="\n") as f: json.dump({"summary": summary, "files": rows}, f, indent=1) f.write("\n") os.chmod(temp, published_mode(path)) diff --git a/tools/rpf_probe.py b/tools/rpf_probe.py index 7cfe678dc1..49b512b3d5 100644 --- a/tools/rpf_probe.py +++ b/tools/rpf_probe.py @@ -84,7 +84,7 @@ def scan_failed(error: OSError) -> None: os.makedirs(out_dir, exist_ok=True) with tempfile.TemporaryDirectory(dir=out_dir) as staging: staged = os.path.join(staging, "rpf_probe.json") - with open(staged, "w", encoding="utf-8") as f: + with open(staged, "w", encoding="utf-8", newline="\n") as f: json.dump(rows, f, indent=1) os.replace(staged, a.out) except OSError as error: diff --git a/tools/salu_diff.py b/tools/salu_diff.py index 244bee3848..0326fc824b 100644 --- a/tools/salu_diff.py +++ b/tools/salu_diff.py @@ -493,7 +493,7 @@ def translated(lines, name="ps_salu"): dis = os.path.join(tmp, "disasm") os.mkdir(dis) path = os.path.join(dis, name + ".s") - with open(path, "w", encoding="utf-8") as f: + with open(path, "w", encoding="utf-8", newline="\n") as f: if has_branches(lines): # The translator places branch targets from the encoding sizes; it does not read the bytes. body = listing(lines + ["exp mrt0 v8, v9, v10, v11 done vm", "s_endpgm"]) diff --git a/tools/save_keys.py b/tools/save_keys.py index a5280b9cc6..1c4c3ea090 100644 --- a/tools/save_keys.py +++ b/tools/save_keys.py @@ -317,7 +317,7 @@ def cmd_resolve(a): print(f" total (joaat) {len(resolved):6} of {len(keys)} keys ({100 * len(resolved) / max(1, len(keys)):.1f}%)") if a.out: try: - with open(a.out, "w", encoding="utf-8") as f: + with open(a.out, "w", encoding="utf-8", newline="\n") as f: json.dump({"%08x" % k: sorted(x.decode("latin-1") for x in v) for k, v in sorted(resolved.items())}, f, indent=1) except OSError as e: diff --git a/tools/saves.py b/tools/saves.py index a7fcef1163..c11430246b 100644 --- a/tools/saves.py +++ b/tools/saves.py @@ -245,16 +245,16 @@ def extract(p, out): e['file'] = f'blocks/{e["index"]:03d}_{e["group"]}_{e["hash"]}.json' with open(os.path.join(out, e['file']), 'wb') as f: f.write(b) - with open(os.path.join(out, 'index.json'), 'w') as f: + with open(os.path.join(out, 'index.json'), 'w', newline="\n") as f: json.dump({'header': h, 'entries': es}, f, indent=1) body = d[h['body_offset']:h['body_end']].decode('utf-8') - with open(os.path.join(out, 'save.pretty.json'), 'w', encoding='utf-8') as f: + with open(os.path.join(out, 'save.pretty.json'), 'w', encoding='utf-8', newline="\n") as f: json.dump(json.loads(body), f, indent=1) print(f'{len(es)} blocks -> {out}') elif k == 'ASAV': h = parse_asav(d) pl = asav_payload(d, h) - with open(os.path.join(out, 'header.json'), 'w') as f: + with open(os.path.join(out, 'header.json'), 'w', newline="\n") as f: json.dump(h, f, indent=1) with open(os.path.join(out, 'header.bin'), 'wb') as f: f.write(d[:h['payload_offset']]) @@ -263,7 +263,7 @@ def extract(p, out): if pl[:1] == b'{': try: obj = json.loads(pl.rstrip(b'\0').decode('utf-8')) - with open(os.path.join(out, 'payload.json'), 'w', encoding='utf-8') as f: + with open(os.path.join(out, 'payload.json'), 'w', encoding='utf-8', newline="\n") as f: json.dump(obj, f, indent=1) except ValueError as ex: print('payload looks like text but did not parse as JSON:', ex) @@ -467,7 +467,7 @@ def value(flag): with open(tmp, 'wb') as f: f.write(read(src)) os.replace(tmp, dst) - with open(os.path.join(out, 'import-manifest.json'), 'w', encoding='utf-8') as f: + with open(os.path.join(out, 'import-manifest.json'), 'w', encoding='utf-8', newline="\n") as f: json.dump(manifest, f, indent=1) print(f'wrote {len(plan)} blobs under {root}') diff --git a/tools/shader_carve.py b/tools/shader_carve.py index 15fb02c4d6..27e240dc6f 100644 --- a/tools/shader_carve.py +++ b/tools/shader_carve.py @@ -119,7 +119,7 @@ def main(argv=None) -> int: # make_game.py takes index.json as proof the carve finished: write it last, under another name, then rename. with tempfile.TemporaryDirectory(dir=out, prefix=".shader-index-") as staging: tmp = os.path.join(staging, "index.json") - with open(tmp, "w", encoding="utf-8") as f: + with open(tmp, "w", encoding="utf-8", newline="\n") as f: json.dump(index, f, indent=1) f.flush() os.fsync(f.fileno()) diff --git a/tools/shader_diff.py b/tools/shader_diff.py index c42bcf22f8..4b52ab7bae 100644 --- a/tools/shader_diff.py +++ b/tools/shader_diff.py @@ -177,7 +177,7 @@ def generate_program(rng, n_ops): def _write_listing(path, lines, with_export): - with open(path, "w", encoding="utf-8") as f: + with open(path, "w", encoding="utf-8", newline="\n") as f: f.write("; shader_diff case code 0x0..0x1000\n") for line in lines: f.write("\t" + line + "\n") diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py index d22ca2bc21..38f49e7a68 100644 --- a/tools/shader_disasm.py +++ b/tools/shader_disasm.py @@ -119,7 +119,7 @@ def one(path, out, mcpu): FAILED.append((path, reason)) return "failed" name = os.path.splitext(os.path.basename(path))[0] - with open(os.path.join(out, name + ".s"), "w", encoding="utf-8") as f: + with open(os.path.join(out, name + ".s"), "w", encoding="utf-8", newline="\n") as f: f.write(f"; {name} code 0x{start:x}..0x{end:x} ({how}), {mcpu}, {bad} invalid words\n") f.write(asm) if err.strip(): diff --git a/tools/shader_profile.py b/tools/shader_profile.py index 47a975fe4e..b14d0d346d 100644 --- a/tools/shader_profile.py +++ b/tools/shader_profile.py @@ -363,7 +363,7 @@ def main(): if a.per_shader: out["per_shader"] = sorted(shaders, key=lambda e: e["name"]) try: - with open(path, "w", encoding="utf-8") as f: + with open(path, "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, indent=1, allow_nan=False) except OSError as e: print(f"ERROR: cannot write {path}: {e.strerror or e}", file=sys.stderr) diff --git a/tools/skin_streams.py b/tools/skin_streams.py index b453aadd9e..db5adcfcc5 100644 --- a/tools/skin_streams.py +++ b/tools/skin_streams.py @@ -486,7 +486,7 @@ def main(argv=None): parent = os.path.dirname(os.path.abspath(a.json)) if parent: os.makedirs(parent, exist_ok=True) - with open(a.json, "w", encoding="utf-8") as fh: + with open(a.json, "w", encoding="utf-8", newline="\n") as fh: json.dump(report, fh, indent=1) except OSError as exc: print(f"error: cannot write {a.json}: {exc.strerror or exc}", file=sys.stderr) diff --git a/tools/spirv_gs_to_compute.py b/tools/spirv_gs_to_compute.py index afb9edba6d..e480fd65de 100644 --- a/tools/spirv_gs_to_compute.py +++ b/tools/spirv_gs_to_compute.py @@ -325,7 +325,7 @@ def main(argv): target = f"spv{ver.group(1)}.{ver.group(2)}" if ver else "vulkan1.2" subprocess.run([asm, "--target-env", target, "-", "-o", args[1]], input=new, check=True, text=True) if lay_path: - with open(lay_path, "w") as f: + with open(lay_path, "w", newline="\n") as f: json.dump(lay, f, indent=1) print(json.dumps(lay)) return 0 diff --git a/tools/story_index.py b/tools/story_index.py index 7a7c7a8373..06d1e742aa 100644 --- a/tools/story_index.py +++ b/tools/story_index.py @@ -299,7 +299,7 @@ def write_output(path, rows, summary): with tempfile.TemporaryDirectory(dir=parent) as staging: staged = os.path.join(staging, "story_index" + ext) if ext == ".json": - with open(staged, "w", encoding="utf-8") as f: + with open(staged, "w", encoding="utf-8", newline="\n") as f: json.dump({"summary": summary, "files": rows}, f, indent=1) else: with open(staged, "w", encoding="utf-8", newline="") as f: diff --git a/tools/tex_export.py b/tools/tex_export.py index f7de7dd285..59d7d4c28c 100644 --- a/tools/tex_export.py +++ b/tools/tex_export.py @@ -225,7 +225,7 @@ def main(): pngs[t["export"]["png"]] += 1 if i % 2000 == 0: print(f"[{i}/{len(texs)}] {dict(res)}", flush=True) - with open(os.path.join(a.out, "export_log.json"), "w", encoding="utf-8") as f: + with open(os.path.join(a.out, "export_log.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(texs, f) print(f"{len(texs)} textures: {dict(res)} -> {a.out}") if a.png: diff --git a/tools/tex_headers.py b/tools/tex_headers.py index f41cc47bcf..389b83cf24 100644 --- a/tools/tex_headers.py +++ b/tools/tex_headers.py @@ -751,7 +751,7 @@ def main(): if parent: # the scan is already done; a missing folder used to lose it in a FileNotFoundError os.makedirs(parent, exist_ok=True) try: - with open(path, "w", encoding="utf-8") as f: + with open(path, "w", encoding="utf-8", newline="\n") as f: json.dump(allt, f) except OSError as e: print(f"ERROR: cannot write {path}: {e.strerror or e}", file=sys.stderr) diff --git a/tools/ttpf_mips.py b/tools/ttpf_mips.py index 58e58e9be1..698f4c5583 100644 --- a/tools/ttpf_mips.py +++ b/tools/ttpf_mips.py @@ -1497,7 +1497,7 @@ def scan_pools(paths, as_json=None, include_tuples=False): if as_json: try: os.makedirs(os.path.dirname(os.path.abspath(as_json)), exist_ok=True) - with open(as_json, "w", encoding="utf-8") as f: + with open(as_json, "w", encoding="utf-8", newline="\n") as f: json.dump(report, f, indent=1) except OSError as exc: raise ValueError(f"cannot write {as_json}: {exc.strerror or exc}") from None diff --git a/tools/turing_atlas.py b/tools/turing_atlas.py index c058b55c2d..56fcb2c767 100644 --- a/tools/turing_atlas.py +++ b/tools/turing_atlas.py @@ -188,7 +188,7 @@ def validate_cases(): for name, asm in CASES.items(): src = os.path.join(d, name + ".spvasm") spv = os.path.join(d, name + ".spv") - with open(src, "w", encoding="utf-8") as f: + with open(src, "w", encoding="utf-8", newline="\n") as f: f.write(asm) ra = run(["spirv-as", src, "-o", spv, "--target-env", "vulkan1.4"]) if ra is None or ra.returncode != 0: @@ -230,7 +230,7 @@ def main(): folder = os.path.dirname(a.out) # --out into a folder that does not exist yet, as awc_manifest.py does if folder: os.makedirs(folder, exist_ok=True) - with open(a.out, "w", encoding="utf-8") as f: + with open(a.out, "w", encoding="utf-8", newline="\n") as f: f.write(text + "\n") print(f"atlas -> {a.out}") else: diff --git a/tools/user_sgpr_census.py b/tools/user_sgpr_census.py index 35fa44ddfb..fd92c507d9 100644 --- a/tools/user_sgpr_census.py +++ b/tools/user_sgpr_census.py @@ -103,7 +103,7 @@ def main(argv=None): f"pointer gaps {s['pointer_gap']}; after a ptr32 {s['after_ptr32']}" + (f"; below base {s['below_base']}" if "below_base" in s else "")) if a.json: - with open(a.json, "w", encoding="utf-8") as f: + with open(a.json, "w", encoding="utf-8", newline="\n") as f: json.dump(summary, f, indent=1, sort_keys=True) bad = [] for item in a.expect: diff --git a/tools/valu_fuzz.py b/tools/valu_fuzz.py index 2b9beeb976..ed6c24e0d4 100644 --- a/tools/valu_fuzz.py +++ b/tools/valu_fuzz.py @@ -845,7 +845,7 @@ def translate(progs, work, emulate): for p in progs: text = p.asm() asm_path = work / (p.name + ".asm") - asm_path.write_text(text, encoding="utf-8") + asm_path.write_text(text, encoding="utf-8", newline="\n") cmd = mc + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"] if p.wave == 64: cmd.append("-mattr=+wavefrontsize64,-wavefrontsize32") @@ -853,7 +853,7 @@ def translate(progs, work, emulate): if r.returncode or "error:" in r.stderr: raise RuntimeError(f"{p.name} did not assemble:\n{r.stderr}") code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith(".")) - (disasm / (p.name + ".s")).write_text(f"; {p.name}\n{code}", encoding="utf-8") + (disasm / (p.name + ".s")).write_text(f"; {p.name}\n{code}", encoding="utf-8", newline="\n") (fssm / (p.name + ".fssm")).write_bytes(compute_header(asm_path)) cmd = [sys.executable, "-I", os.path.join(HERE, "rdna2spirv.py"), str(disasm), "--out", str(spirv)] if emulate: diff --git a/tools/vertex_types.py b/tools/vertex_types.py index 6702b5faed..871d886e57 100644 --- a/tools/vertex_types.py +++ b/tools/vertex_types.py @@ -525,7 +525,7 @@ def main(argv=None): if args.json: try: os.makedirs(os.path.dirname(os.path.abspath(args.json)), exist_ok=True) - with open(args.json, "w", encoding="utf-8") as fh: + with open(args.json, "w", encoding="utf-8", newline="\n") as fh: json.dump(out, fh, indent=1) except OSError as exc: print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) diff --git a/tools/wave64_graphics_scan.py b/tools/wave64_graphics_scan.py index b9410a5e8f..3b56ac2b98 100644 --- a/tools/wave64_graphics_scan.py +++ b/tools/wave64_graphics_scan.py @@ -158,7 +158,7 @@ def main(argv=None) -> int: o = report["other_stages"] print("other stages: %d shaders, %d wave64 (not counted)" % (o["shaders"], o["wave64"])) if args.out: - with open(args.out, "w", encoding="utf-8") as f: + with open(args.out, "w", encoding="utf-8", newline="\n") as f: json.dump(report, f, indent=1) print("wrote %s" % args.out) return 0 diff --git a/tools/world_census.py b/tools/world_census.py index 86b63b4b55..0d1e04539e 100644 --- a/tools/world_census.py +++ b/tools/world_census.py @@ -101,7 +101,7 @@ def _mapped_source(archive, expected_id): def _staged_json(path, doc, **options): with tempfile.TemporaryDirectory(dir=os.path.dirname(path)) as directory: tmp = os.path.join(directory, os.path.basename(path)) - with open(tmp, "w", encoding="utf-8") as f: + with open(tmp, "w", encoding="utf-8", newline="\n") as f: json.dump(doc, f, **options) try: mode = os.lstat(path).st_mode diff --git a/tools/world_index.py b/tools/world_index.py index e0464beacf..ae6632dbee 100644 --- a/tools/world_index.py +++ b/tools/world_index.py @@ -742,7 +742,7 @@ def _write_reports(a, rows, stats, agg): summary["versions"] = sorted({r["version"] for r in rows}) doc = {"summary": summary, "resources": rows} os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) - with open(a.out, "w", encoding="utf-8") as f: + with open(a.out, "w", encoding="utf-8", newline="\n") as f: json.dump(doc, f, indent=1, sort_keys=True) if a.csv: cols = ["source", "offset", "size", "signature", "version", "kind", "structs", "enums", "blocks", @@ -763,7 +763,7 @@ def _write_reports(a, rows, stats, agg): w.writerow(r) if agg is not None: os.makedirs(os.path.dirname(os.path.abspath(a.archetypes_out)), exist_ok=True) - with open(a.archetypes_out, "w", encoding="utf-8") as f: + with open(a.archetypes_out, "w", encoding="utf-8", newline="\n") as f: json.dump(agg.to_json(), f, indent=1, sort_keys=True) summary["archetype_file"] = agg.to_json()["summary"] return summary diff --git a/tools/world_names.py b/tools/world_names.py index 4ffe3f01a0..06152aac50 100644 --- a/tools/world_names.py +++ b/tools/world_names.py @@ -606,7 +606,7 @@ def _write_json(path: str, data: dict) -> None: os.makedirs(directory, exist_ok=True) with tempfile.TemporaryDirectory(dir=directory, prefix=".world-names-") as staging: tmp = os.path.join(staging, "report.json") - with open(tmp, "w", encoding="utf-8") as handle: + with open(tmp, "w", encoding="utf-8", newline="\n") as handle: json.dump(data, handle, indent=1, sort_keys=True) handle.write("\n") os.replace(tmp, path) From 2d2eec9a75e3f98cf26b6a55df58d0bd90366ba3 Mon Sep 17 00:00:00 2001 From: AlxcBTW <187763517+AlxcBTW@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:21:28 +0100 Subject: [PATCH 022/115] M4 review: storage-image init only on shader-running non-copy submissions, ordered for other queues - The zero-fill/GENERAL init of images with a UAV view no longer drains on a copy queue or in a submission that runs no dispatch or draw; every other queue's next submission waits on the initializing one's progress semaphore. - storage_pending_ is a set (UAV descriptors are rewritten every frame). - write_buffer_uav: FirstElement and element count are checked against Width / unit, so the byte range cannot overflow. - docs: M4 row names the remaining limitation. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 2 +- runtime/shims/d3d12_vulkan_device.cpp | 2 +- runtime/src/vulkan_backend.h | 39 ++++++++++++++++++++++---- runtime/test/d3d12_m4_compute_test.cpp | 4 ++- 4 files changed, 39 insertions(+), 8 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index b8545f4a97..8c5070d9d7 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2419,7 +2419,7 @@ M0–M2 do not need the executable. | **M1.5** | The same, with real translator output: hand-written RDNA2 VS+PS, PSO found by FSSM hash, vertex fetch through a V# loaded from the user-data table, a root constant, a table in the arena, the code base | The push-constant, vertex-fetch and code-base contracts on translated code | Met by `d3d12_translated_draw_test`: three draws, every pixel off the triangle's edge exact in a float target, validation clean on the AMD Radeon 880M and the RTX 5070 Laptop. An upload buffer behind a V# is not supported (section 3.3) | | **M2** | Descriptor heap (heap slots 9/10 return in RAX), `CreateShaderResourceView`, sampler, root descriptor table, hash-table insert, bindless sampling | The full D3D12 descriptor path and the shader's T#/S# contract | A textured quad matches the synthetic 8×8 gradient or a known texture with error 0; the hash table has the expected entries. **Synthetic part met** by `d3d12_m2_textured_test`: through the proxy, D3D12 API only, a shader-visible CBV/SRV/UAV heap and a sampler heap (start handles from slots 9/10), two 8×8 textures uploaded with `Map` + `CopyTextureRegion`, `CreateShaderResourceView` and a POINT `CreateSampler`, a root signature of two descriptor tables, `SetDescriptorHeaps`, `SetGraphicsRootDescriptorTable` and `DrawIndexedInstanced` of a quad whose PS is translator output (`ps_m2.asm`: `s_load` of the T# and the S# from the tables, `image_sample`). Every one of the 4096 pixels matches the CPU-computed gradient (left half) and its point reflection (right half, second table) with error 0, and the hash table holds a distinct non-zero index for each of the two T#s and the S# and none for bytes nothing created; validation clean on the AMD Radeon 880M and the RTX 5070 Laptop. The layer change it needed: pipelines whose shader declares set-0 bindings (graphics and compute) were refused; their layout now holds the device's bindless set 0 and replay binds it at every draw and dispatch. Still open: shaders of the game itself (direct heap indexing, unbounded tables, static samplers, descriptors the game writes itself), no host D3D12/WARP byte comparison (the reference is computed on the CPU), and texture formats other than R8G8B8A8_UNORM, mips and arrays through a PSO (the descriptor test covers views and sampling on a compute shader) | | **M3** | Depth/stencil, multiple render targets, resource barriers, render passes, occlusion queries, fences, 2–3 frames in flight; run the game's first frames | Real frame structure and the first game code | The game reaches its first rendered frame (loading screen/menu or whatever the executable does) or stops on a single unsupported call with a clean report. **Synthetic part met** by `d3d12_m3_frame_test`: through the proxy, D3D12 API only, six frames through a ring of three slots (three frames in flight; each slot has its own allocator, list, targets, depth buffer, query and fence, and a frame waits with `SetEventOnCompletion` + an event for the fence its slot signalled three frames earlier before reading back and recording the slot again). Pass 1 draws three rectangles from root constants with translator-output shaders (`vs_m3.asm`, `ps_m3.asm`, hand-written RDNA2) through `OMSetRenderTargets` into two render targets (R8G8B8A8_UNORM and R32_FLOAT) and a `D24_UNORM_S8_UINT` depth/stencil buffer (the layer substitutes D32_SFLOAT_S8_UINT on the Radeon; the RTX has it natively): depth LESS with write, stencil REPLACE with references 1 and 2, then a draw with no depth test whose stencil test is EQUAL; the far rectangle runs inside `BeginQuery`/`EndQuery(OCCLUSION)` and `ResolveQueryData` writes its sample count to a readback buffer. Resource barriers move the first target RENDER_TARGET → PIXEL_SHADER_RESOURCE\|COPY_SOURCE and the second to COPY_SOURCE (and back at the next frame, from resources created in those states). Pass 2 samples the first target through an SRV in a descriptor table (the M2 path) with `ps_m3_post.asm` into a third target. Every pixel of all three targets (the float one bit for bit) matches the CPU reference with error 0 in each of the six frames, and the occlusion count equals the exact visible area of the far rectangle in each frame (3555 samples over the six frames); validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. @whattheflop's run on #1584 (GeForce RTX 3080 and a Ryzen 7 9800X3D Radeon iGPU) sampled the fences with nonblocking reads after each submit and saw 1, 2, 3, 1, 2, 3 slots still incomplete on NVIDIA and 1, 1, 1, 1, 1, 1 on AMD: up to three slots in flight on NVIDIA, one on AMD (sampled fence completion; GPU execution overlap was not measured). **Still open for M3:** render passes (`BeginRenderPass`, D3D-27) are not exercised, nor `BINARY_OCCLUSION`, occlusion during pipeline statistics (D3D-162), MSAA or depth/stencil copies and read-only DSV states in this test; the game's own first frames need the executable | -| **M4** | Compute PSOs, UAVs, storage images, indirect dispatch, copy queues, async streaming | Asset loading and GPU compute | The world's streaming path runs without device loss; compute results match a CPU/reference check. **Synthetic part met** by `d3d12_m4_compute_test`: through the proxy, D3D12 API only, with translator-output compute shaders (`cs_m4_fill.asm` and `cs_m4_indirect.asm`, hand-written RDNA2). A COPY queue streams an input buffer in (`CopyBufferRegion` from an UPLOAD buffer into a DEFAULT buffer created in COMMON), `Signal`; a COMPUTE queue `Wait`s on it and runs one list: a compute root signature (four root constants and a descriptor table of five UAVs: a structured buffer, three raw buffers and an `R32_UINT` `RWTexture2D`), a compute PSO and `Dispatch` (256 threads) that fills the structured buffer and the image from the input and writes the arguments of the next dispatch into a raw buffer; barriers (the argument buffer to `INDIRECT_ARGUMENT`, UAV barriers on the buffer and the image); `ExecuteIndirect` with a dispatch command signature running a second PSO for the 3 groups the first dispatch asked for, which reads the buffer and the image back (`image_load`) and writes a raw output; then everything to COMMON and `Signal`. A COPY queue `Wait`s on that fence, copies the five results (the image through `CopyTextureRegion`) to a readback buffer, and the CPU waits with `SetEventOnCompletion`. Each D3D12 queue has its own `VkQueue` where the family has two (both test GPUs); all 1,924 result words match the CPU reference with error 0; validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. Layer gaps this test found, closed with it: buffer UAVs (structured and raw) were not written (`CreateUnorderedAccessView` stubbed them, now a V# in the slot); `ExecuteIndirect` of a dispatch ran whatever pipeline and root arguments the command buffer had bound instead of the list's (now recorded with the command, as `Dispatch` does); an image created in `UNORDERED_ACCESS` and first used by a shader was zero-filled by the first barrier or copy that named it, losing the shader's writes (now moved to GENERAL, zeroed, at the next submission after its UAV view is created). **Still open for M4:** typed buffer UAVs and UAV counters, buffer SRVs and CBVs as V#s, a queue submitted before the queue whose fence it waits on, when a resource's layout is handed over between them (the layout tracker follows submission order, so the copy list was replayed against the layout from before the compute list ran and the run stopped on a validation error; d3d12_queue_wait_test covers Wait-before-Signal without a resource), `ExecuteIndirect` signatures that change root arguments or use count buffers for dispatches, and async streaming itself and the world's streaming path, which need the game | +| **M4** | Compute PSOs, UAVs, storage images, indirect dispatch, copy queues, async streaming | Asset loading and GPU compute | The world's streaming path runs without device loss; compute results match a CPU/reference check. **Synthetic part met** by `d3d12_m4_compute_test`: through the proxy, D3D12 API only, with translator-output compute shaders (`cs_m4_fill.asm` and `cs_m4_indirect.asm`, hand-written RDNA2). A COPY queue streams an input buffer in (`CopyBufferRegion` from an UPLOAD buffer into a DEFAULT buffer created in COMMON), `Signal`; a COMPUTE queue `Wait`s on it and runs one list: a compute root signature (four root constants and a descriptor table of five UAVs: a structured buffer, three raw buffers and an `R32_UINT` `RWTexture2D`), a compute PSO and `Dispatch` (256 threads) that fills the structured buffer and the image from the input and writes the arguments of the next dispatch into a raw buffer; barriers (the argument buffer to `INDIRECT_ARGUMENT`, UAV barriers on the buffer and the image); `ExecuteIndirect` with a dispatch command signature running a second PSO for the 3 groups the first dispatch asked for, which reads the buffer and the image back (`image_load`) and writes a raw output; then everything to COMMON and `Signal`. A COPY queue `Wait`s on that fence, copies the five results (the image through `CopyTextureRegion`) to a readback buffer, and the CPU waits with `SetEventOnCompletion`. Each D3D12 queue has its own `VkQueue` where the family has two (both test GPUs); all 1,924 result words match the CPU reference with error 0; validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. Layer gaps this test found, closed with it: buffer UAVs (structured and raw) were not written (`CreateUnorderedAccessView` stubbed them, now a V# in the slot); `ExecuteIndirect` of a dispatch ran whatever pipeline and root arguments the command buffer had bound instead of the list's (now recorded with the command, as `Dispatch` does); an image created in `UNORDERED_ACCESS` and first used by a shader was zero-filled by the first barrier or copy that named it, losing the shader's writes (now moved to GENERAL, zeroed, by the first submission after its UAV view is created that is not on a copy queue and dispatches or draws; every other queue's next submission waits for that one). **Still open for M4:** the storage-image initialization is tied to the first shader-running submission, not to the list that uses the image, so a list that only reaches an image through a barrier or copy before any dispatch or draw is submitted still zero-fills it first (as before), and an image used by a shader only on a queue that never runs one of its own dispatches or draws first relies on another queue's submission; typed buffer UAVs and UAV counters, buffer SRVs and CBVs as V#s, a queue submitted before the queue whose fence it waits on, when a resource's layout is handed over between them (the layout tracker follows submission order, so the copy list was replayed against the layout from before the compute list ran and the run stopped on a validation error; d3d12_queue_wait_test covers Wait-before-Signal without a resource), `ExecuteIndirect` signatures that change root arguments or use count buffers for dispatches, and async streaming itself and the world's streaming path, which need the game | | **M5** | Mesh shaders, `ExecuteIndirect`, bindless-table pressure, multi-threaded command lists, pipeline cache | World rendering | A stable open-world frame at any frame rate; then profile and optimise | | **M6** | Ray tracing/XDXR: standard AS builds or the shipped `XboxBvhBuilder` compute path; BVH node format; Xbox DXIL path for the builder's 53 shaders (22 lowered so far) | RT shadows and any RT effects | RT output matches a reference; the builder's shaders run through the DXIL path or a substitute; no unknown XDXR call remains | | **M7** | HDR, VRS, `PresentX` planes (2-plane HDR + GameDVR compose, `ImmediateThresholdPercent`), resize, alt-tab, `SuspendX`/`ResumeX`, frame pacing and `GetFrameStatisticsX` | Presentation polish | HDR and resize work on the target display; no validation errors over a long run. **Partly met:** `ImmediateThresholdPercent` (late frame flipped at once through `VK_KHR/EXT_swapchain_maintenance1` IMMEDIATE/FIFO_RELAXED, section 4.5; checked on the fake-clock decision and on the Vulkan present mode, 0 VUIDs in our runs with `LEONIDA_VK_VALIDATION=1` on two GPUs, no tearing observed on a display; the console's real semantics are unmeasured). `SuspendX`/`ResumeX`, frame pacing and a minimal `GetFrameStatisticsX` exist; HDR, VRS, plane compose, alt-tab are open | diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 69b8956f70..9be9a5fa49 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -3963,7 +3963,7 @@ class Device final } const UINT64 unit = structured ? view.StructureByteStride : 4; if (!unit || unit > 0x3fff || view.CounterOffsetInBytes || - (UINT64(view.FirstElement) + view.NumElements) * unit > rd.Width || + view.FirstElement > rd.Width / unit || (UINT64(view.FirstElement) + view.NumElements) > rd.Width / unit || UINT64(view.NumElements) * (structured ? 1 : 4) > ~0u) { log_once("unordered-access view of a buffer outside the resource or with a bad stride; elements", int(view.NumElements)); diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index a79bf47beb..59d5e20387 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include @@ -820,7 +821,7 @@ class VulkanContext { // zero-filled, ahead of its lists. An image already tracked beyond UNDEFINED is left as it is. void note_storage_image(ResourceId id) { std::lock_guard lock(storage_mutex_); - storage_pending_.push_back(id); + storage_pending_.insert(id); } void remove_resource(ResourceId id) { @@ -1129,7 +1130,13 @@ class VulkanContext { std::unordered_map acceleration_structures_; LayoutTracker tracker_; std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ only - std::vector storage_pending_; + std::unordered_set storage_pending_; + // The last submission that initialized storage images (its queue's progress semaphore and ticket) and a counter + // that says which one: every other queue's next submission waits for it, so no queue uses such an image before + // the zero-fill that put it in GENERAL has run. + VkSemaphore storage_init_semaphore_ = VK_NULL_HANDLE; + std::uint64_t storage_init_value_ = 0; + std::uint64_t storage_init_version_ = 0; std::map, VkImageView> views_; std::function bindless_prepare_; std::unique_ptr depth24_; @@ -1445,10 +1452,25 @@ class VulkanQueue { return ReplayResult::unsupported; } auto next_tracker = context_.tracker_; + // Images with a UAV view are moved to GENERAL (zeroed) by the first submission that can use a shader on them: + // not a copy queue (its family may not clear images), and one whose lists dispatch or draw. + bool runs_shaders = false; + for (const CommandList* list : lists) + for (const auto& command : list->commands()) + runs_shaders |= std::holds_alternative(command) || std::holds_alternative(command) || + std::holds_alternative(command); std::vector storage_images; { std::lock_guard lock(context_.storage_mutex_); - storage_images.swap(context_.storage_pending_); + if (context_.storage_init_semaphore_ && context_.storage_init_semaphore_ != progress_ && + context_.storage_init_version_ != storage_init_seen_) { + waits_.push_back(context_.storage_init_semaphore_); + wait_values_.push_back(context_.storage_init_value_); + storage_init_seen_ = context_.storage_init_version_; + } + if (kind_ != QueueKind::copy && runs_shaders) + storage_images.assign(context_.storage_pending_.begin(), context_.storage_pending_.end()); + if (!storage_images.empty()) context_.storage_pending_.clear(); } for (const ResourceId id : storage_images) { const ResourceBinding* image = context_.resolve(id); @@ -1501,8 +1523,14 @@ class VulkanQueue { const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); if (!submitted && !storage_images.empty()) { // not initialized after all: try again with the next submission std::lock_guard lock(context_.storage_mutex_); - context_.storage_pending_.insert(context_.storage_pending_.end(), storage_images.begin(), - storage_images.end()); + context_.storage_pending_.insert(storage_images.begin(), storage_images.end()); + } + if (submitted && !storage_images.empty()) { + std::lock_guard lock(context_.storage_mutex_); + context_.storage_init_semaphore_ = progress_; + context_.storage_init_value_ = submitted_; + ++context_.storage_init_version_; + storage_init_seen_ = context_.storage_init_version_; } if (submitted) { context_.tracker_ = std::move(next_tracker); @@ -1655,6 +1683,7 @@ class VulkanQueue { std::uint64_t submitted_ = 0; std::vector buffers_; std::unique_ptr occlusion_resolve_; + std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for std::vector waits_; std::vector wait_values_; std::uint32_t open_labels_ = 0; // queue labels begun and not ended diff --git a/runtime/test/d3d12_m4_compute_test.cpp b/runtime/test/d3d12_m4_compute_test.cpp index cb322c5e58..bd3a555fdd 100644 --- a/runtime/test/d3d12_m4_compute_test.cpp +++ b/runtime/test/d3d12_m4_compute_test.cpp @@ -266,7 +266,9 @@ int main() { EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(©_fence.p)))); EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&compute_fence.p)))); - // Copy list 1: stream the input in (the buffer is in COMMON and is promoted to COPY_DEST by the copy). + // Copy list 1: stream the input in (the buffer is in COMMON and is promoted to COPY_DEST by the copy). This is the + // first submission after the UAV views were written, and a copy queue: it must not initialize the storage image + // (the compute queue does, in the submission that dispatches), or the data written later would be at risk. stream_list->CopyBufferRegion(input.p, 0, upload.p, 0, in_bytes); EXPECT(stream_list->Close() == S_OK); From 7690b647a291db4b5271d6964fcb8d05fa837ec4 Mon Sep 17 00:00:00 2001 From: Ryx <118130241+Ryx69@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:21:49 +0100 Subject: [PATCH 023/115] Runtime: restore the occlusion pause around a resolve (D3D-189) After upgrading the Radeon 8060S from AMD driver 26.10.1 to 26.11.2 (#1540), vk_overlapping_occlusion still times out on main, and c8ea00e4 with the pause passes every run (--bisect, --gated, the full test, and under validation) in about 0.1 s. The earlier "every phase hangs" retest was a broader occlusion bug in 26.10.1 that 26.11.2 fixed, so the revert in 3784aacc is undone. The comment and docs now cite the 26.11.2 measurement. --no-draw and --no-resolve stay; the crossing and single schedules match the split again. --- docs/d3d12_vulkan.md | 11 ++++-- runtime/src/vulkan_replay.h | 37 ++++++++++++++----- .../test/vk_overlapping_occlusion_test.cpp | 7 ++-- 3 files changed, 40 insertions(+), 15 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 7622cb4ac4..70d2c62ca6 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1808,9 +1808,14 @@ Implemented (`QueryHeap` in `runtime/shims/d3d12_vulkan_device.cpp`, the query c submission's physical pool. Resolving it sums the 64-bit counts on the GPU, then copies the result to the destination. Both occlusion compute helpers reuse one scratch buffer per queue. Logical results and in-flight submissions retain the pool independently, so later resolves and - overwrites can be recorded before the earlier commands complete. `vk_overlapping_occlusion` checks crossing - and nested scopes, more than one scratch chunk, alternating binary and ordinary resolves under a predicate, - and gated submissions on a GPU. + overwrites can be recorded before the earlier commands complete. A resolve while an ordinary query is active + ends the active physical query before the resolve and begins the next one after it, and a list with such a + resolve takes this path even without an overlap. On a Radeon 8060S with AMD's Windows driver 26.11.2, + `vk_overlapping_occlusion` times out (TDR) on `main`, where those resolves run inside an active query, and passes + with the pause (D3D-189, #1540; driver 26.10.1 had a broader occlusion bug that 26.11.2 fixed). + `vk_overlapping_occlusion` checks crossing and nested scopes, a resolve inside a single active query, more than + one scratch chunk, alternating binary and ordinary resolves under a predicate, and gated submissions on a GPU; + `--bisect` runs its patterns one per submission to find one that hangs a device. - **Timestamps.** `GetTimestampFrequency` is `1e9 / timestampPeriod` (1 GHz on the test GPU). Every D3D12 queue shares one `VkQueue` for now (question 12), so they share one frequency. diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 8f1e17213a..3ef28243bc 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -1647,11 +1647,19 @@ class PreparedList { inline ReplayResult plan_occlusion_segments(PreparedList& out) { // Active logical queries cover a contiguous range of physical slots. A Begin or End closes the old // slot and opens a new one if any query remains active. Each shared interval is recorded only once. + // A resolve while a slot is active closes it before the resolve and opens the next after it, so no query is + // active during the copy and its dispatch (D3D-189); the logical ranges simply span one more slot. std::map, std::uint32_t> active; std::uint32_t current = detail::PreparedQuery::no_segment; for (auto& query : out.queries) { const Command& command = out.list->commands()[query.command]; - if (std::holds_alternative(command)) continue; + if (std::holds_alternative(command)) { + if (current == detail::PreparedQuery::no_segment) continue; + query.end_segment = current; + current = out.segment_count++; + query.begin_segment = current; + continue; + } const auto range = query_range(command); if (range.type != d3d12_query::occlusion) continue; const auto key = std::pair{range.heap, range.first}; @@ -2051,6 +2059,11 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun // The internal dispatch would otherwise count towards the application's CSInvocations. if (!vk.resolve_binary_occlusion || statistics_active) return ReplayResult::unsupported; } + // No resolve runs while an ordinary occlusion query is active. On a Radeon 8060S with AMD's Windows + // driver 26.11.2, vk_overlapping_occlusion times out (TDR) when resolves are recorded inside an + // active query, and passes with this pause (D3D-189, #1540). The segment path can pause the active + // query around the resolve (plan_occlusion_segments), so such a list takes it when it can sum. + if (ordinary_active && vk.sum_occlusion) overlaps = true; if (p.binding.host_readable) { out.wrote_readback = true; out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; @@ -2198,16 +2211,21 @@ class QueryReplay { inline void emit_query(const PreparedList& list, const detail::PreparedQuery& query, VkCommandBuffer cb, const ReplayFunctions& vk, const VkConditionalRenderingBeginInfoEXT& predicate) { constexpr auto none = detail::PreparedQuery::no_segment; - if (query.end_segment != none || query.begin_segment != none) { - if (query.end_segment != none) vk.end_query(cb, list.segment_pool, list.segment_base + query.end_segment); - if (query.begin_segment != none) { - const auto index = list.segment_base + query.begin_segment; - vk.reset_query_pool(cb, list.segment_pool, index, 1); - vk.begin_query(cb, list.segment_pool, index, list.precise_segments ? VK_QUERY_CONTROL_PRECISE_BIT : 0); - } + const auto& command = list.list->commands()[query.command]; + // A Begin or End of a segmented query only moves between segments. A resolve inside a segment ends it before + // the resolve and begins the next one after it. + const bool segmented = query.end_segment != none || query.begin_segment != none; + if (query.end_segment != none) vk.end_query(cb, list.segment_pool, list.segment_base + query.end_segment); + const auto begin_segment = [&] { + if (query.begin_segment == none) return; + const auto index = list.segment_base + query.begin_segment; + vk.reset_query_pool(cb, list.segment_pool, index, 1); + vk.begin_query(cb, list.segment_pool, index, list.precise_segments ? VK_QUERY_CONTROL_PRECISE_BIT : 0); + }; + if (segmented && !std::holds_alternative(command)) { + begin_segment(); return; } - const auto& command = list.list->commands()[query.command]; const QueryPool& heap = *query.heap; if (const auto* begin = std::get_if(&command)) { vk.reset_query_pool(cb, heap.pool, begin->index, 1); @@ -2243,6 +2261,7 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu } } if (suspend) vk.begin_conditional_rendering(cb, &predicate); + begin_segment(); } } diff --git a/runtime/test/vk_overlapping_occlusion_test.cpp b/runtime/test/vk_overlapping_occlusion_test.cpp index e45331b063..3c38d2950f 100644 --- a/runtime/test/vk_overlapping_occlusion_test.cpp +++ b/runtime/test/vk_overlapping_occlusion_test.cpp @@ -183,9 +183,10 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec Fixture fixture{d}; EXPECT(fixture.create(vertex, fragment)); constexpr std::uint32_t bursts = 130; - Draws schedule{fixture, {8, 4, 2, 8, 4, 2, 3}}; + // crossing ends four physical queries (the resolve inside it splits the last one), nested three; single ends two. + Draws schedule{fixture, {8, 4, 2, 0, 8, 4, 2, 3}}; schedule.extents.insert(schedule.extents.end(), 2 * bursts + 1, 1); - schedule.extents.insert(schedule.extents.end(), {2, 0, 0, 0, 1}); + schedule.extents.insert(schedule.extents.end(), {2, 0, 0, 0, 1, 1}); schedule.every = bisect.enabled; schedule.no_draw = bisect.no_draw; draws = &schedule; @@ -401,7 +402,7 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec const CommandList* fourth[] = {&replace}; EXPECT(queue.execute(fourth) == ReplayResult::success); - // A resolve inside one active query, with no overlap. + // A resolve inside one active query, with no overlap: the active query is paused around it (D3D-189). CommandList single; EXPECT(single.begin_query({a, occ, 3})); EXPECT(single.resolve_queries({a, occ, 0, 1, dst_id, 128})); From 9dc08d2596b6c2e3b64f85b19eafde038ece8457 Mon Sep 17 00:00:00 2001 From: Tayar <358041433+lucastayaralvarenga-ui@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:22:05 -0300 Subject: [PATCH 024/115] docs(pt-BR): address quickstart review feedback --- docs/i18n/README.md | 2 +- docs/i18n/pt-BR/quickstart.md | 18 ++++++++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/docs/i18n/README.md b/docs/i18n/README.md index 78e8562c15..8e12f10b1c 100644 --- a/docs/i18n/README.md +++ b/docs/i18n/README.md @@ -13,7 +13,7 @@ A language is added when a contributor volunteers to maintain it and keeps the s | Language | File | Synced commit | Maintainer | |---|---|---|---| | Français (`fr`) | [`fr/quickstart.md`](fr/quickstart.md) | `e7584c52` | `@Urban225` | -| Português (Brasil) (`pt-BR`) | [`pt-BR/quickstart.md`](pt-BR/quickstart.md) | `d3841c0c` | `@Andretuta` | +| Português (Brasil) (`pt-BR`) | [`pt-BR/quickstart.md`](pt-BR/quickstart.md) | `003e7812` | `@Andretuta` | | 简体中文 (`zh-CN`) | [`zh-CN/quickstart.md`](zh-CN/quickstart.md) | `e7584c5` | `@liang-kai-shui` | | Polski (Polish) (`pl-PL`) | [`pl-PL/quickstart.md`](pl-PL/quickstart.md) | `c0ac5fd6` | `@Dom-in` | | Türkçe (`tr`) | [`tr/quickstart.md`](tr/quickstart.md) | `f85582e` | `@emirhan-karaca` | diff --git a/docs/i18n/pt-BR/quickstart.md b/docs/i18n/pt-BR/quickstart.md index 0d54af7b48..6964b8aee1 100644 --- a/docs/i18n/pt-BR/quickstart.md +++ b/docs/i18n/pt-BR/quickstart.md @@ -3,7 +3,7 @@ > [!NOTE] > A documentação em inglês ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) e > [`docs/README.md`](../../README.md)) é a **referência oficial**. Este guia reúne apenas instruções estáveis de -> configuração e compilação (sincronizado com o commit `d3841c0c`). Para o status diário do projeto, consulte o +> configuração e compilação (sincronizado com o commit `003e7812`). Para o status diário do projeto, consulte o > [`README.md`](../../../README.md). ## O que é o Leonida @@ -30,9 +30,14 @@ O projeto está em fase inicial: **o jogo ainda não dá boot**. - [Vulkan SDK](https://vulkan.lunarg.com/) (`spirv-as`, `spirv-val` e `vulkaninfo`). - [LLVM 21+](https://github.com/llvm/llvm-project/releases) com o **target AMDGPU** (`llvm-mc`): - O binário oficial do LLVM para Windows **não** inclui o target AMDGPU. - - Para compilar um `llvm-mc.exe` nativo com AMDGPU, execute `.\scripts\build_llvm_mc.ps1` no PowerShell - a partir da raiz do repositório. O script requer `git` e as ferramentas C++ do Visual Studio, configura - `LLVM_MC` para o seu usuário e pede que você abra um novo terminal para carregar a variável. + - Para compilar um `llvm-mc.exe` nativo com AMDGPU, rode este comando a partir da raiz do repositório. + + ```powershell + powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 + ``` + + O script requer `git` e as ferramentas C++ do Visual Studio, configura `LLVM_MC` para o seu usuário + e pede que você abra um novo terminal para carregar a variável. - Se usar o WSL, instale `llvm-21` no Ubuntu e defina a variável na mesma sessão do PowerShell em que vai executar `make_game.py`. @@ -80,7 +85,7 @@ Os estágios executam nesta ordem: `check` → `shaders` → `assets` → `runti ## Problemas comuns - **Baixou pelo botão "Download ZIP" do GitHub**: o ZIP não inclui o submódulo `third_party/rpf9-explorer`. Use `git clone --recursive` ou execute `git submodule update --init --recursive` dentro da pasta do repositório. -- **`llvm-mc` recusa `gfx1013` / AMDGPU**: você provavelmente está com o instalador oficial do LLVM para Windows. Use `scripts\build_llvm_mc.ps1` ou aponte `LLVM_MC` para o `llvm-mc` do WSL (`llvm-21`). +- **`llvm-mc` recusa `gfx1013` / AMDGPU**: você provavelmente está com o instalador oficial do LLVM para Windows. Siga um dos passos de configuração do LLVM acima. - **Erro de `D3D12_ROOT_SIGNATURE_DESC2` ao compilar o runtime**: atualize o Windows SDK para `10.0.26100` ou mais recente pelo Visual Studio Installer ou `winget install Microsoft.WindowsSDK.10.0.26100`, apague a pasta de build e reconfigure. - **Falha por falta de espaço no drive `C:`**: passe `--work "D:\leonida-work"` para mover os arquivos temporários para outra partição. @@ -91,7 +96,8 @@ Os estágios executam nesta ordem: `check` → `shaders` → `assets` → `runti 2. Rode os testes relevantes com entradas sintéticas. Por exemplo, para testar o verificador de manifestos, execute `python -I tests/test_manifest_verifier.py` na raiz do repositório. 3. No PR, inclua o ID da tarefa, descreva o que testou e informe a GPU e o driver se rodou testes de GPU. - Indique se usou assistência de IA. Confira as regras em [`CONTRIBUTING.md`](../../../CONTRIBUTING.md). + Confira as regras em [`CONTRIBUTING.md`](../../../CONTRIBUTING.md). Se usou assistência de IA, indique + isso no PR, conforme [`AGENTS.md`](../../../AGENTS.md). O [guia de testes em GPU](../../testing.md) mostra como executar os testes sem arquivos do jogo. Publique os resultados de GPU na [issue #166](https://github.com/ItsNotRexed/Leonida/issues/166). From 0fc69a771bf232c60c115d8d32bad934fa693096 Mon Sep 17 00:00:00 2001 From: Vonsek <45567075+Vonsek@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:56:33 +0100 Subject: [PATCH 025/115] feature_scan: answer open question 16 (UAV counters, typed buffer formats) PSV0 resource bindings give the structured UAVs with a counter and the typed buffer SRVs/UAVs; the listings give the MTBUF instruction formats and, for MUBUF *_format ops, where V# word 3 comes from in the access's basic block (literal, scalar load, computed, an earlier block or a shader input). Formats are checked against rdna2spirv.Gen.FORMATS. Co-Authored-By: Claude Opus 5.5 --- tests/test_feature_scan.py | 92 +++++++++++++++ tools/feature_scan.py | 228 ++++++++++++++++++++++++++++++++++++- 2 files changed, 317 insertions(+), 3 deletions(-) diff --git a/tests/test_feature_scan.py b/tests/test_feature_scan.py index a3e80ae439..13e64abe3b 100644 --- a/tests/test_feature_scan.py +++ b/tests/test_feature_scan.py @@ -318,9 +318,101 @@ def test_v_perm_b32_selectors(): assert failures == 0, f"{failures} v_perm_b32 check(s) failed" +def psv0(records, size=24, truncate=False): + """PSV0 payload: a 24-byte runtime info, then the resource count, record size and (type, kind) records.""" + body = struct.pack("= 24 else b"") + body += rec + bytes(size - len(rec)) + return body[:-4] if truncate else body + + +def listing(lines): + """A .s listing with `; encoding:` comments of the right length, so pcs and branch targets are real.""" + return "".join(f"\t{code} ; encoding: [{','.join(['0x00'] * n)}]\n" for code, n in lines) + + +def test_typed_buffers_and_psv0(): + """§8.2 #16: PSV0 counter/typed-buffer bindings, MTBUF formats and where each MUBUF V# word 3 comes from.""" + with tempfile.TemporaryDirectory() as tmp: + sh = os.path.join(tmp, "shaders") + dx = os.path.join(sh, "dxbc") + dis = os.path.join(dx, "disasm") + os.makedirs(dis) + cs = listing([ + ("s_load_dwordx4 s[8:11], s[0:1], 0x0", 8), # pc 0 + ("s_mov_b32 s15, 0x38000", 8), # 8: format 56, 8_8_8_8_UNORM + ("s_mov_b32 s19, 0x24000", 8), # 16: format 36, 10_11_11_FLOAT + ("s_or_b32 s23, s23, 0x1000", 8), # 24: computed + ("s_cmp_eq_u32 s11, 0", 4), # 32: reads s11, writes nothing + ("buffer_load_format_xyzw v[0:3], v4, s[8:11], 0 idxen", 8), # 36: memory + ("buffer_load_format_x v5, v4, s[12:15], 0 idxen", 8), # 44: literal + ("buffer_store_format_x v5, v4, s[16:19], 0 idxen", 8), # 52: literal, not in the table + ("buffer_load_format_x v6, v4, s[20:23], 0 idxen", 8), # 60: computed + ("buffer_load_format_x v7, v4, s[24:27], 0 idxen", 8), # 68: never written: shader input + ("s_cbranch_scc0 1", 4), # 76: to 84; 80 and 84 lead blocks + ("s_nop 0", 4), # 80 + ("buffer_load_format_x v8, v4, s[8:11], 0 idxen", 8), # 84: loaded in an earlier block + ("buffer_load_format_x v9, v4, s[12:15], 0 idxen", 8), # 92: literal from an earlier block + ("tbuffer_load_format_xy v[0:1], v4, s[8:11], 0 format:[BUF_FMT_16_16_SNORM] idxen", 8), + ("tbuffer_load_format_x v2, v4, s[8:11], 0 idxen", 8), # no format: GFX10 default 8_UNORM + ("tbuffer_store_format_x v2, v4, s[8:11], 0 format:[BUF_FMT_10_11_11_FLOAT] idxen", 8), + ("s_endpgm", 4)]) + ps = listing([("buffer_load_format_x v0, v1, s[0:3], 0 idxen", 8), ("s_endpgm", 4)]) + vs = listing([("v_mov_b32_e32 v0, v1", 4), ("s_endpgm", 4)]) + synthetic = [ + ("tb_cs", "cs", cs, psv0([(9, 12), (3, 10), (6, 2)])), # counter UAV, typed buffer SRV, typed 2D UAV + ("tb_ps", "ps", ps, psv0([(6, 10), (6, 10)])), # two typed buffer UAVs + ("tb_vs", "vs", vs, psv0([(3, 10)], size=16)), # v0 records carry no kind + ("tb_gs", "gs", None, psv0([(9, 12)], truncate=True)), # records past the end of the part + ] + index = [] + for name, stage, text, psv in synthetic: + with open(os.path.join(dx, name + ".dxbc"), "wb") as f: + f.write(dxbc([("SFI0", struct.pack(" Vulkan layer may need (docs/d3d12_vulkan.md §8.2 #10 and #14). +"""Scan the shader corpus for features the D3D12 -> Vulkan layer may need (docs/d3d12_vulkan.md §8.2 #10, #14, #16). python -I tools/feature_scan.py /shaders [--out feature_scan.json] @@ -7,9 +7,12 @@ - dxbc/index.json and the .dxbc files: the DXIL program kind of every shader (hull, domain and amplification stages would show up here), the SFI0 feature flags (D3D_SHADER_REQUIRES_* from the Windows SDK's d3d12shader.h, among them WAVE_MMA and SHADING_RATE), and the output-signature (OSG1) stream index of every element: stream - output to a stream other than 0 needs a geometry shader writing that stream. + output to a stream other than 0 needs a geometry shader writing that stream. The PSV0 resource bindings: structured + UAVs with a counter (append/consume buffers) and typed buffer SRVs/UAVs (#16). - dxbc/disasm/*.s (shader_disasm.py): the native RDNA2 instructions that mean wave MMA (v_mfma*, v_wmma*, - v_smfmac*) or GDS / ordered-count traffic (the hardware path NGG stream output uses on RDNA2). + v_smfmac*) or GDS / ordered-count traffic (the hardware path NGG stream output uses on RDNA2). Typed buffer + accesses (#16): the MTBUF instruction formats, and for MUBUF where V# word 3 (the format) comes from, each checked + against the translator's typed-buffer table (rdna2spirv.Gen.FORMATS). - spirv/index.json (rdna2spirv.py): uses_code_base per stage. A graphics PSO can only need two code bases (§5.2) if two of its stages use one; this gives the per-stage counts. Which stages are paired in one PSO is in the executable, not in shaders.rpf. @@ -80,6 +83,61 @@ def streams(sig: bytes) -> set: return {struct.unpack_from(" list: + """(resource type, resource kind) of every PSV0 resource binding record. + + The part is: u32 runtime-info size, the runtime info, u32 resource count and, when that is not 0, u32 record + size and the records. A record is PSVResourceBindInfo0 (type, space, lower and upper bound: 16 bytes) or + PSVResourceBindInfo1 (plus resource kind and flags: 24 bytes); a 16-byte record has kind "?". Raises ValueError + when the table does not fit in the part.""" + if len(psv) < 4: + raise ValueError("PSV0 shorter than its runtime-info size") + pos = 4 + struct.unpack_from(" len(psv): + raise ValueError("PSV0 truncated before the resource count") + count = struct.unpack_from(" len(psv): + raise ValueError("PSV0 truncated before the record size") + size = struct.unpack_from(" len(psv): + raise ValueError("PSV0 resource records do not fit") + out = [] + for i in range(count): + at = pos + i * size + t = struct.unpack_from("= 20 else None + out.append((PSV_RES_TYPES[t] if t < len(PSV_RES_TYPES) else f"type{t}", + "?" if k is None else PSV_RES_KINDS[k] if k < len(PSV_RES_KINDS) else f"kind{k}")) + return out + + +# §8.2 #16: append/consume buffers are the structured UAVs with a counter; typed buffers are typed SRVs/UAVs of +# kind TypedBuffer (a typed SRV/UAV of a texture kind is an image, not a buffer). +WATCHED_BINDINGS = ("uav_with_counter", "typed_buffer_srv", "typed_buffer_uav") + + +def watched_binding(res_type: str, kind: str): + if res_type == "UAVStructuredWithCounter": + return "uav_with_counter" + if kind == "TypedBuffer" and res_type in ("SRVTyped", "UAVTyped"): + return "typed_buffer_srv" if res_type == "SRVTyped" else "typed_buffer_uav" + return None + + def stage_name(row: dict) -> str: stage = row.get("stage") return stage if isinstance(stage, str) and stage else "?" @@ -90,6 +148,8 @@ def scan_dxbc(dxbc_dir: str, index: list) -> dict: flags = defaultdict(Counter) # flag -> stage -> shaders gs_streams = Counter() non_zero_stream = Counter() # stage -> shaders with an output element on a stream other than 0 + records, shaders_with = Counter(), Counter() # PSV0: (type, kind) -> records; watched class -> shaders + psv_bad = 0 missing = 0 for e in index: if not isinstance(e, dict): @@ -113,14 +173,33 @@ def scan_dxbc(dxbc_dir: str, index: list) -> dict: for bit, name in SFI0_FLAGS.items(): if mask & bit: flags[name][stage] += 1 + try: + binds = psv0_bindings(p["PSV0"]) if "PSV0" in p else None + except ValueError: + binds = None + if binds is None: + psv_bad += 1 + else: + records.update(binds) + for cls in {watched_binding(t, k) for t, k in binds} - {None}: + shaders_with[cls] += 1 out = streams(p.get("OSG1", b"")) if stage == "gs": gs_streams[len(out)] += 1 if out - {0}: non_zero_stream[stage] += 1 + by_type = Counter() + for (t, _), n in records.items(): + by_type[t] += n return {"stages": {s: stages.get(s, 0) for s in ALL_STAGES} | {k: v for k, v in stages.items() if k not in ALL_STAGES}, "sfi0": {n: dict(flags[n]) for n in sorted(flags)}, "gs_output_stream_count": dict(gs_streams), "output_on_stream_other_than_0": dict(non_zero_stream), + "psv0": {"records": sum(records.values()), + "by_type": dict(by_type), + "shaders": {c: shaders_with.get(c, 0) for c in WATCHED_BINDINGS}, + "records_of": {c: sum(n for (t, k), n in records.items() if watched_binding(t, k) == c) + for c in WATCHED_BINDINGS}, + "unreadable": psv_bad}, "unreadable": missing} @@ -251,6 +330,138 @@ def scan_disasm(disasm_dir: str, stage_of: dict) -> dict: }} +# Scalar ops whose first operand is a source, not an SGPR they write. +NO_SDST = ("s_cmp", "s_bitcmp", "s_cbranch", "s_branch", "s_waitcnt", "s_endpgm", "s_store", "s_buffer_store", + "s_scratch_store", "s_setpc", "s_sendmsg", "s_nop", "s_barrier", "s_dcache", "s_icache", "s_gl1_inv", + "s_setprio", "s_sleep", "s_ttrace", "s_set_gpr_idx", "s_setreg", "s_inst_prefetch", "s_round_mode", + "s_denorm_mode", "s_clause", "s_trap", "s_wakeup", "s_code_end", "s_atc_probe", "s_setkill", "s_incperflevel", + "s_decperflevel", "s_version") +BRANCH_OPS = frozenset(("s_branch", "s_cbranch_scc0", "s_cbranch_scc1", "s_cbranch_vccz", "s_cbranch_vccnz", + "s_cbranch_execz", "s_cbranch_execnz")) +TYPED_MUBUF = re.compile(r"^buffer_(load|store)_format_(d16_)?(x|xy|xyz|xyzw)$") +TYPED_MTBUF = re.compile(r"^tbuffer_(load|store)_format_(d16_)?(x|xy|xyz|xyzw)$") + + +def translator_formats(): + """(codes in the translator's typed-buffer table, GFX10 code -> format name), read from rdna2spirv itself so the + scan follows the table as it changes.""" + import rdna2spirv + return frozenset(rdna2spirv.Gen.FORMATS), {c: n.replace("GFX10_FORMAT_", "") for c, n in + rdna2spirv.GFX10_FORMATS.items()} + + +def sgpr_writes(ins: dict) -> range: + """The SGPRs an instruction writes (as far as a V# word can be written: scalar destinations, v_readlane and + v_readfirstlane, the SGPR mask of a VOP3 compare and the carry of a VOP3b add).""" + op, args = ins["op"], ins["args"] + dst = None + if op.startswith("s_") and not op.startswith(NO_SDST): + dst = args[0] if args else None + elif op.startswith(("v_readlane", "v_readfirstlane")) or (op.startswith("v_cmp") and not op.startswith("v_cmpx") + and op.endswith("_e64")): + dst = args[0] if args else None + elif op.startswith("v_") and len(args) > 1 and ("_co_" in op or op.startswith("v_div_scale")): + dst = args[1] + if dst and dst.get("k") == "sgpr": + return range(dst["r"], dst["r"] + dst.get("n", 1)) + return range(0) + + +def branch_target(ins: dict): + """Byte pc a branch goes to (simm16 dwords after the branch), or None without an encoding.""" + imm = next((x for x in ins["args"] if x.get("k") == "imm"), None) + if imm is None or not ins.get("enc"): + return None + v = imm["v"] & 0xFFFF + return ins["pc"] + len(ins["enc"]) // 2 + 4 * (v - 0x10000 if v & 0x8000 else v) + + +def typed_buffer_ops(insns: list, table: frozenset, names: dict) -> Counter: + """Count the typed buffer accesses of one listing (§8.2 #16). + + MTBUF (tbuffer_*) carries its format in the instruction; LLVM leaves `format:` out for GFX10's default, 8_UNORM. + MUBUF (buffer_*_format_*) takes it from V# word 3 bits 18:12, and the result says where that word comes from in the + basic block of the access (blocks start at branch targets and after branches, as rdna2spirv.translate splits + them): an s_mov_b32 literal (the only form the translator folds, so the format is known when translating), a + scalar load (a descriptor from memory), or any other instruction (computed). A word 3 not written in the block is + "earlier_" + the class of the last write before it in listing order, or "shader_input" when nothing before it + writes the register (a user or system SGPR: the root signature's descriptor). + + Keys: ("mtbuf", load|store, format), ("mubuf", load|store, class) and, for a literal word 3 (in the block or + earlier), ("mubuf_literal", load|store, format). A format the translator's table lacks gets a "!" in front.""" + leaders = {insns[0]["pc"]} if insns else set() + for ins in insns: + if ins["op"] in BRANCH_OPS: + t = branch_target(ins) + if t is not None: + leaders.add(t) + if ins.get("enc"): + leaders.add(ins["pc"] + len(ins["enc"]) // 2) + out = Counter() + block, last = {}, {} # SGPR -> (class, literal or None): written in this block / last write so far + for ins in insns: + if ins["pc"] in leaders: + block = {} + op = ins["op"] + m = TYPED_MTBUF.match(op) or TYPED_MUBUF.match(op) + if m: + kind = m.group(1) + if op.startswith("t"): + fm = next((x for x in ins["mods"] if x.startswith("format:")), "format:[BUF_FMT_8_UNORM]") + name = fm.split("BUF_FMT_")[-1].rstrip("]") + code = next((c for c, n in names.items() if n == name), None) + out[("mtbuf", kind, ("" if code in table else "!") + name)] += 1 + elif len(ins["args"]) > 2 and ins["args"][2].get("k") == "sgpr": + w3 = ins["args"][2]["r"] + 3 + if w3 in block: + cls, lit = block[w3] + elif w3 in last: + cls, lit = "earlier_" + last[w3][0], last[w3][1] + else: + cls, lit = "shader_input", None + out[("mubuf", kind, cls)] += 1 + if lit is not None: + code = (lit >> 12) & 0x7F + out[("mubuf_literal", kind, ("" if code in table else "!") + names.get(code, f"code{code}"))] += 1 + regs = sgpr_writes(ins) + if regs: + if op == "s_mov_b32" and len(ins["args"]) > 1 and ins["args"][1].get("k") == "imm": + state = ("literal", ins["args"][1]["v"] & 0xFFFFFFFF) + elif op.startswith(("s_load", "s_buffer_load")): + state = ("memory", None) + else: + state = ("computed", None) + for r in regs: + block[r] = last[r] = state + return out + + +def scan_typed_buffers(disasm_dir: str, stage_of: dict) -> dict: + """§8.2 #16 over every listing: typed buffer access counts (typed_buffer_ops) summed, and shaders per stage.""" + import shader_ir + table, names = translator_formats() + total, shaders = Counter(), defaultdict(Counter) + for fn in sorted(os.listdir(disasm_dir)): + if not fn.endswith(".s"): + continue + path = os.path.join(disasm_dir, fn) + with open(path, encoding="utf-8", errors="replace") as f: + if "_format_" not in f.read(): # no typed buffer op: skip the slower full parse + continue + stage = stage_of.get(fn[:-2], "?") + c = typed_buffer_ops(shader_ir.parse_file(path)["insns"], table, names) + total.update(c) + for what in {k[0] for k in c}: + shaders[what][stage] += 1 + if any(k[0] == "mubuf" and k[2] not in ("literal", "earlier_literal") for k in c): + shaders["mubuf_runtime_format"][stage] += 1 + group = lambda what: {f"{k[1]} {k[2].lstrip('!')}": n for k, n in sorted(total.items()) if k[0] == what} + return {"mtbuf": group("mtbuf"), "mubuf_word3": group("mubuf"), "mubuf_literal_formats": group("mubuf_literal"), + "not_in_translator": {f"{k[0]} {k[1]} {k[2][1:]}": n for k, n in sorted(total.items()) + if k[0] != "mubuf" and k[2].startswith("!")}, + "shaders": {w: dict(s) for w, s in sorted(shaders.items())}} + + def scan_spirv(spirv_index: str) -> dict: with open(spirv_index, encoding="utf-8") as f: idx = json.load(f) @@ -336,6 +547,7 @@ def main() -> int: disasm = os.path.join(dxbc_dir, "disasm") if os.path.isdir(disasm): result["disasm"] = scan_disasm(disasm, stage_of) + result["typed_buffers"] = scan_typed_buffers(disasm, stage_of) spirv = os.path.join(a.shaders, "spirv", "index.json") if os.path.isfile(spirv): try: @@ -352,6 +564,10 @@ def main() -> int: print("SFI0, every flag set anywhere:", {n: sum(v.values()) for n, v in d["sfi0"].items()}) print("GS output-signature stream counts:", d["gs_output_stream_count"], "| shaders with an output on a stream other than 0:", d["output_on_stream_other_than_0"] or 0) + pv = d["psv0"] + print(f"PSV0 bindings: {pv['records']} records | shaders with " + + ", ".join(f"{c} {pv['shaders'][c]} ({pv['records_of'][c]} records)" for c in WATCHED_BINDINGS) + + (f" | {pv['unreadable']} unreadable PSV0" if pv["unreadable"] else "")) if "disasm" in result: s = result["disasm"] print(f"disasm: {s['files']} files | wave MMA shaders {s['wave_mma_shaders'] or 0} | ordered-count/GWS shaders " @@ -362,6 +578,12 @@ def main() -> int: f"(imm {vp['immediate']}, const_reg {vp['const_reg']}, unresolved {vp['unresolved']}) | " f"selectors 8-11: {vp['sign_extend_8_11_shaders']} shaders / {vp['sign_extend_8_11_insns']} insns | " f"bytes {vp['selector_classes']}") + tb = result["typed_buffers"] + print("typed buffers, MTBUF formats (instruction):", tb["mtbuf"] or 0) + print("typed buffers, MUBUF V# word 3 source:", tb["mubuf_word3"] or 0, "| literal formats:", + tb["mubuf_literal_formats"] or 0) + print("typed buffers, formats the translator's table lacks:", tb["not_in_translator"] or 0, + "| shaders:", tb["shaders"] or 0) else: print("disasm: not there yet (run the shaders stage)") if "spirv" in result: From 364d9a465aef78703df6f4138198e12bd983bca4 Mon Sep 17 00:00:00 2001 From: Vonsek <45567075+Vonsek@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:23:08 +0100 Subject: [PATCH 026/115] feature_scan: INVALID is modelled; d3d12_vulkan.md answers open question 16 A literal V# word 3 with FORMAT 0 (an unbound descriptor) reads 0 on the hardware and in the translator, so it is not listed as a format the translator lacks. Row 16 gets the counts over the 1.0.2.1 corpus. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 2 +- tests/test_feature_scan.py | 14 ++++++++------ tools/feature_scan.py | 7 ++++--- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e96dcae726..e62327520c 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2573,7 +2573,7 @@ Xodus is LGPL-2.1 and is cited only for its coverage number, not as a code sourc | 10 | Does the game use binning, DCC, VRS, wave MMA, stream output, tessellation, or amplification shaders? | **Shaders: answered** by `tools/feature_scan.py` over all 26,503 (1.0.2.1): no hull, domain or amplification shader (DXIL program kinds: 2,236 VS, 12,101 PS, 195 GS, 2,689 CS, 9,282 MS); no `WAVE_MMA` or `SHADING_RATE` in any SFI0, and no `v_mfma`/`v_wmma`/`v_smfmac` in the disassembly; no output-signature element on a stream other than 0 (all 195 GS write stream 0 only) and no GDS / `ds_ordered_count` / GWS instruction, so no stream-output path. Also from SFI0: 10 PS need ROVs (pixel interlock), 30 shaders `TILED_RESOURCES` (see #18), 685 `ATOMIC_INT64_ON_TYPED_RESOURCE`. Binning and DCC are not shader-visible; they stay open for the PSO/stream subobjects. | | 14 | Are there PSOs with two code-base stages? | Count from the PSO/shader hash table and the index metadata. If yes, implement per-stage code-base slots (section 5.2). **Per stage, measured** (`tools/feature_scan.py`, `s_getpc_b64` kept for data rather than a far branch): 54 VS, 93 PS, 266 MS, 263 CS, 0 GS; the translator's `uses_code_base` gives the same counts (with LLVM 23 that needs #223, without which these 1,471 shaders are rejected). So VS+PS and MS+PS pipelines with two code-base stages are possible; whether any exists depends on which shaders a PSO pairs, which is in the executable, not in `shaders.rpf`. | | 15 | Is `ExecuteIndirect` used with signatures Vulkan cannot express directly? | Trace `CreateCommandSignature` and `ExecuteIndirect`; implement simple signatures first, expand the complex ones with compute. The simple signatures are D3D-17 (#313). | -| 16 | Does the game use append/consume UAV counters or typed buffer formats the translator does not model? | Trace UAV descs and shader `buffer_*` ops; extend the translator/runtime together. | +| 16 | Does the game use append/consume UAV counters or typed buffer formats the translator does not model? | **Shaders: answered** by `tools/feature_scan.py` over all 26,503 (1.0.2.1, disassembled with LLVM 21.1.8 for gfx1013; SHADER-65). **No append/consume counters:** none of the 445,394 PSV0 binding records is a structured UAV with a counter, and there is no `ds_append`/`ds_consume`/GDS instruction. Typed buffers are declared in 5,359 shaders as SRVs (17,328 records) and in 2,177 as UAVs (4,005). **MTBUF** (format in the instruction): 52,890 loads in 10,278 shaders, all in five formats the translator decodes (`16_16_SNORM` 24,881, `8_8_8_8_UNORM` 19,835, `8_8_8_8_UINT` 5,099, `2_10_10_10_UNORM` 2,648, `16_16_16_16_UINT` 427), and no MTBUF store. **MUBUF** `buffer_*_format_*` (format from V# word 3): 90,316 accesses (84,908 loads, 5,408 stores) in 11,591 shaders; word 3 comes from a scalar load in 88,924 of them, is computed in 1,390, and is a literal in 2 (FORMAT 0, INVALID, which reads 0 on the hardware and in the translator). So the shaders fix no MUBUF format: the descriptors the executable writes decide it. Still open: which formats those descriptors carry; the runtime can log a V# format outside `Gen.FORMATS` (those read 0 today) when the descriptor is created or copied. | | 17 | Do upload/readback resources ever reach shaders (as vertex/index buffers or descriptors), and does the `-heap_base` bias work for them? | Trace `CreateCommittedResource` heap types and every VB/IB/descriptor that points at an upload resource; test the bias with a synthetic draw. | | 18 | Does the game alias buffers/images in a heap, or use reserved/tiled resources? | Trace `CreatePlacedResource` ranges, aliasing barriers, `CreateReservedResource` and tile mappings. If yes, implement shared memory per heap range or fall back to linear allocations with a clear log. Shaders: 30 declare `TILED_RESOURCES` in SFI0 (`tools/feature_scan.py`), so reserved/tiled resources are likely used. Placed resources are D3D-16 and reserved resources D3D-20 (#313). | | 19 | What do the `0x03000000` root-signature flag bits mean? | Masking them on a copy works around the PC serializer; the semantics remain unknown. Compare against the public flag enum and observe the game's behaviour with and without the mask. | diff --git a/tests/test_feature_scan.py b/tests/test_feature_scan.py index 13e64abe3b..41a4dd8158 100644 --- a/tests/test_feature_scan.py +++ b/tests/test_feature_scan.py @@ -358,7 +358,9 @@ def test_typed_buffers_and_psv0(): ("tbuffer_load_format_x v2, v4, s[8:11], 0 idxen", 8), # no format: GFX10 default 8_UNORM ("tbuffer_store_format_x v2, v4, s[8:11], 0 format:[BUF_FMT_10_11_11_FLOAT] idxen", 8), ("s_endpgm", 4)]) - ps = listing([("buffer_load_format_x v0, v1, s[0:3], 0 idxen", 8), ("s_endpgm", 4)]) + ps = listing([("s_mov_b32 s11, 0", 4), # word 3 0: FORMAT INVALID + ("buffer_load_format_x v0, v1, s[0:3], 0 idxen", 8), + ("buffer_load_format_x v2, v1, s[8:11], 0 idxen", 8), ("s_endpgm", 4)]) vs = listing([("v_mov_b32_e32 v0, v1", 4), ("s_endpgm", 4)]) synthetic = [ ("tb_cs", "cs", cs, psv0([(9, 12), (3, 10), (6, 2)])), # counter UAV, typed buffer SRV, typed 2D UAV @@ -389,14 +391,14 @@ def test_typed_buffers_and_psv0(): check(tb["mtbuf"] == {"load 16_16_SNORM": 1, "load 8_UNORM": 1, "store 10_11_11_FLOAT": 1}, f"MTBUF formats from the instruction, 8_UNORM without format: ({tb['mtbuf']})") check(tb["mubuf_word3"] == {"load computed": 1, "load earlier_literal": 1, "load earlier_memory": 1, - "load literal": 1, "load memory": 1, "load shader_input": 2, + "load literal": 2, "load memory": 1, "load shader_input": 2, "store literal": 1}, f"MUBUF word 3 by source, s_cmp is no write, a branch target starts a block ({tb['mubuf_word3']})") - check(tb["mubuf_literal_formats"] == {"load 8_8_8_8_UNORM": 2, "store 10_11_11_FLOAT": 1}, - f"literal word 3 formats ({tb['mubuf_literal_formats']})") + check(tb["mubuf_literal_formats"] == {"load 8_8_8_8_UNORM": 2, "load INVALID": 1, + "store 10_11_11_FLOAT": 1}, f"literal word 3 formats ({tb['mubuf_literal_formats']})") check(tb["not_in_translator"] == {"mtbuf store 10_11_11_FLOAT": 1, "mubuf_literal store 10_11_11_FLOAT": 1}, - f"formats outside rdna2spirv.Gen.FORMATS are listed ({tb['not_in_translator']})") - check(tb["shaders"] == {"mtbuf": {"cs": 1}, "mubuf": {"cs": 1, "ps": 1}, "mubuf_literal": {"cs": 1}, + f"formats outside rdna2spirv.Gen.FORMATS are listed, INVALID (reads 0) is not ({tb['not_in_translator']})") + check(tb["shaders"] == {"mtbuf": {"cs": 1}, "mubuf": {"cs": 1, "ps": 1}, "mubuf_literal": {"cs": 1, "ps": 1}, "mubuf_runtime_format": {"cs": 1, "ps": 1}}, f"shaders per stage ({tb['shaders']})") out_json = os.path.join(tmp, "out.json") diff --git a/tools/feature_scan.py b/tools/feature_scan.py index 203fe55c96..57acdcb43c 100644 --- a/tools/feature_scan.py +++ b/tools/feature_scan.py @@ -343,10 +343,11 @@ def scan_disasm(disasm_dir: str, stage_of: dict) -> dict: def translator_formats(): - """(codes in the translator's typed-buffer table, GFX10 code -> format name), read from rdna2spirv itself so the - scan follows the table as it changes.""" + """(codes the translator models, GFX10 code -> format name), read from rdna2spirv itself so the scan follows the + table as it changes. Modelled: the typed-buffer table and INVALID (0), an unbound descriptor, which reads 0 on the + hardware and in the translator.""" import rdna2spirv - return frozenset(rdna2spirv.Gen.FORMATS), {c: n.replace("GFX10_FORMAT_", "") for c, n in + return frozenset(rdna2spirv.Gen.FORMATS) | {0}, {c: n.replace("GFX10_FORMAT_", "") for c, n in rdna2spirv.GFX10_FORMATS.items()} From 6ea07e1b8647c03bcc2bd455744efb4bef46f007 Mon Sep 17 00:00:00 2001 From: docs-recount Date: Sun, 22 Nov 2026 14:23:37 +0000 Subject: [PATCH 027/115] docs: correct re-count baseline and mark unmeasured levels geometry story000_restofworld already recovered its 3 models at 917e9b9, so its delta is 0 and the 917e9b9 baseline is 350,251 models / 159,486 children; the ten-archive delta is +32,530. The levels.rpf fragments/bone-bound/triangles cells have no manifest or harness fields, so they and the totals derived from them are marked not independently reproduced. Add the measured levels.rpf name-pass coverage to world_names.md. --- docs/README.md | 2 +- docs/design.md | 2 +- docs/models.md | 45 +++++++++++++++++++++++++++------------------ docs/world_names.md | 4 +++- 4 files changed, 32 insertions(+), 21 deletions(-) diff --git a/docs/README.md b/docs/README.md index 57b9540a39..3129118160 100644 --- a/docs/README.md +++ b/docs/README.md @@ -17,7 +17,7 @@ method, scope and caveats. No game data is included. | Document | Measured content | |---|---| -| [models.md](models.md) | 382,781 models (2.64 billion triangles, 0 decode failures) at the `e293917` pin, including 159,511 drawable-dictionary children and 55,417 fragments; the re-count table is in models.md. | +| [models.md](models.md) | 382,781 models (0 decode failures) at the `e293917` pin, including 159,511 drawable-dictionary children; the other archives measure 4,686 fragments, 30,343 bone-bound and 126,301,454 triangles, while the `levels.rpf` geometry cells are not independently reproduced; the re-count table is in models.md. | | [models.md](models.md) | 350,251 models at the `917e9b9` pin, including 159,486 drawable-dictionary children; the `e293917` re-count adds 3,203 rows outside `levels.rpf`, almost all recovered fragments; `levels.rpf` recovers 343,327 models (+29,327) but was not fully exported. The per-archive table is in models.md. | | [character_models.md](character_models.md) | `packs.rpf` character parts at `e293917`: 26,585 rows / 11,335 unique names, 2,865 fragments (all a flat 25-vertex / 32-triangle 5x5 bounds grid at z=0), Lucia's 22 named records and the decoded 13-part export, the `player_story000_00` drawable set, slot-name token counts, texture coverage (184/215), and what is not decoded (fragment children, ped variation, hair, bind pose). | | [character_skeleton.md](character_skeleton.md) | Character `.#ft` fragments: the 597-name shared skeleton table (596 `joaat32` hashes), the 597-record instance tree with 580 measured parents, the model-side bone-hash mapping, and the measured vertex joint-index/skin-weight layouts (`tools/skin_streams.py`); the reference TRS is not the bind pose. | diff --git a/docs/design.md b/docs/design.md index 9e38cc015f..6e90ef5469 100644 --- a/docs/design.md +++ b/docs/design.md @@ -102,7 +102,7 @@ add a source file, add it to `runtime\CMakeLists.txt` and to the file list in `b | Videos | 797 Bink 2 files (`KB2n`), cut out whole. | `*.bk2` in the carve folders | | Shaders | 26,503 carved from `shaders.rpf`, native RDNA2 code unpacked (`FSSM`), disassembled, and translated to SPIR-V; all validate (see *Translator status*). | `\shaders\` (`.dxbc`, `fssm\`, `disasm\`, `spirv\`) | | Textures | **Solved.** Headers are in CPU segments: GPU pointer at q[k], u16 width/height/depth and DXGI format at q[k+4], mip count at byte 2 of q[k+5]. Data is AMD `SW_4K_S` tiled, largest mip first. The GPU segment is the blob run after the CPU blob. On 200 samples, 173 decode at least 1.5× smoother detiled than untiled (median 2.56×). Exports the top mip, slice 0, as DDS. **22,342 exported (1.23 GiB)**: every header whose GPU data follows its CPU blob. World and model textures are handled by the TXD and TTPF exporters below. GPU offsets must be 256-byte aligned, which drops the false headers in `navmeshes`/`anim`. | `tools\tex_headers.py`, `tools\tex_export.py`, `\textures\` | -| Models | **Done: 382,781 models measured at the `e293917` pin** (`levels.rpf` 343,327, `packs` 26,585, `story000` 7,461, `data` 3,175, `shared_minigame000` 1,294, `core_restofworld` 936, `story000_restofworld` 3; 0 decode failures across all 382,781 models; **159,511 drawable-dictionary children**, **223,270 standalone**, **55,417 fragments**, **89,887 bone-bound**, **2.64 billion triangles** [`2,636,248,990`], 1,805 embedded textures; 72 unrecovered scan candidates vs 1,282 at `917e9b9`). Earlier baselines: 350,248 at `917e9b9` (159,483 dictionary children, 190,765 standalone) and 190,792 at `c3708fb`; the +32,533 gain at `e293917` comes from upstream `v1.2` PRs #8–#12 (optional fragment pointers, texture-dictionary filtering, probe-cap parity, and zero-radius drawables; see [models.md](models.md)). Exported with `tools\rpf9dump` (built on breadbbbb/rpf9-explorer's Core; see below). Resources are found at page offset +16 after 16 zero bytes, followed by a zlib system blob with a drawable/fragment header and then the following zlib blocks as graphics data. Positions are quantized: `bias + scale * ((q >> 8) & 0xFFFFFF)`. Output is OBJ (positions, UVs, indices) plus a manifest with real model names (e.g. `cvar_int_grg2b_toys_1`), bounds, per-mesh shader index and material texture references (parameter hash, name hash, 64-bit asset key). My earlier `0x1380`/`0x1601` descriptor notes stand, but the "data not located" blocker was wrong. Character skeletons are separate: the shared 597-name `.#ft` table and its model-side bone-hash mapping are in [character_skeleton.md](character_skeleton.md). | `\assets\\models\` | +| Models | **Done: 382,781 models measured at the `e293917` pin** (`levels.rpf` 343,327, `packs` 26,585, `story000` 7,461, `data` 3,175, `shared_minigame000` 1,294, `core_restofworld` 936, `story000_restofworld` 3; 0 decode failures across all 382,781 models; **159,511 drawable-dictionary children**, **223,270 standalone**; the other archives measure **4,686 fragments**, **30,343 bone-bound**, **126,301,454 triangles** and 512 embedded textures, while the `levels.rpf` fragments/bone-bound/triangles/embedded cells are **not independently reproduced** (no `levels.rpf` manifest; the count harness emits no such fields); 72 unrecovered scan candidates vs 1,282 at `917e9b9`). Earlier baselines: 350,251 at `917e9b9` (159,486 dictionary children, 190,765 standalone) and 190,792 at `c3708fb`; the +32,530 gain at `e293917` comes from upstream `v1.2` PRs #8–#12 (optional fragment pointers, texture-dictionary filtering, probe-cap parity, and zero-radius drawables; see [models.md](models.md)). Exported with `tools\rpf9dump` (built on breadbbbb/rpf9-explorer's Core; see below). Resources are found at page offset +16 after 16 zero bytes, followed by a zlib system blob with a drawable/fragment header and then the following zlib blocks as graphics data. Positions are quantized: `bias + scale * ((q >> 8) & 0xFFFFFF)`. Output is OBJ (positions, UVs, indices) plus a manifest with real model names (e.g. `cvar_int_grg2b_toys_1`), bounds, per-mesh shader index and material texture references (parameter hash, name hash, 64-bit asset key). My earlier `0x1380`/`0x1601` descriptor notes stand, but the "data not located" blocker was wrong. Character skeletons are separate: the shared 597-name `.#ft` table and its model-side bone-hash mapping are in [character_skeleton.md](character_skeleton.md). | `\assets\\models\` | | Models | **Done: 350,251 models measured at the `917e9b9` pin** (the submodule pin is now `e293917`, which also pulls in upstream `v1.2` model-discovery PRs #8-#12 plus BCPack PR #7; the non-`levels.rpf` archives have been re-counted at `e293917`: 39,454 rows, +3,203, almost all recovered fragments; `levels.rpf` has a recovery count of 343,327 models (+29,327) but no full OBJ export). At `917e9b9`: `levels.rpf` 314,000, `story000` 7,460, `packs` 24,034, `data` 2,581, `shared_minigame000` 1,288, `core_restofworld` 885, `story000_restofworld` 3; 0 decode failures in the re-count. The `c3708fb` export was 190,792; the new entries are **159,486 drawable-dictionary children** (levels 130,225, packs 23,720, story 4,156, data 268, shared 317, core 797, story_restofworld 3) plus raw-tail/mixed-block pages. The standalone total is 190,765. Triangle totals were not re-run. Exported with `tools\rpf9dump` (built on breadbbbb/rpf9-explorer's Core; see below). Resources are found at page offset +16 after 16 zero bytes, followed by a zlib system blob with a drawable/fragment header and then the following zlib blocks as graphics data. Positions are quantized: `bias + scale * ((q >> 8) & 0xFFFFFF)`. Output is OBJ (positions, UVs, indices) plus a manifest with real model names (e.g. `cvar_int_grg2b_toys_1`), bounds, per-mesh shader index and material texture references (parameter hash, name hash, 64-bit asset key). My earlier `0x1380`/`0x1601` descriptor notes stand, but the "data not located" blocker was wrong. Character skeletons are separate: the shared 597-name `.#ft` table and its model-side bone-hash mapping are in [character_skeleton.md](character_skeleton.md). | `\assets\\models\` | | Texture dictionaries | Same tool: TXD resources become DDS per texture. | `\assets\\textures\` | | World textures (TTPF) | **Done: 308,895 textures from all 57 pools, 0 failures, 48,220 entries skipped by the original exporter** (33,507 BCPack, 14,030 compact mapping, 678 arrays/volumes, 5 unsupported format, 0 unmapped). The compact-tail tool resolves 14,011 of the 14,030 layouts and reconstructs 305,264 complete chains (206,661 newly complete, 1,100,865 mips, 4.59 GiB), and the multi-slice pass resolves all 697 arrays/cubemaps/volumes ([textures_arrays.md](textures_arrays.md)). BCPack was the hard blocker: `tools/bcpack.py` decodes all six active modes (BC1, BC3, BC4, BC5, BC6H, BC7), and `rpf9dump`'s C# `TtpfReader` (`e293917` pin, `breadbbbb/rpf9-explorer#7`) now decodes compact tails, multi-slice layouts, DXGI 11, and strict BCPack BC1/BC3/BC4/BC5 directly; BC6H/BC7 and provisional-history chunks remain skipped by `rpf9dump` and can be completed by `tools/ttpf_assets.py` ([textures.md](textures.md)). 46 pools are in `data\ttdb\**`, 11 in `pack\\data\ttdb\**` (exported under `ttpf_pack\\`). `data\ttdb\**\*.ttpf` (57 pools, 58 GiB) are loose RDS5 texture pools, **not** inside RPFs. rpf9-explorer's `TtpfReader` reads the catalog and detiles them; checked visually (`ttdb_graphics`: scope reticles, clean lines). Names are generated (`texture_N_`); models reference textures by asset key. Some rows are skipped; the measured breakdown and next steps are in [textures.md](textures.md). | `\assets\ttpf\\` + `manifest.json` | diff --git a/docs/models.md b/docs/models.md index 61b0e9f2b8..695662749b 100644 --- a/docs/models.md +++ b/docs/models.md @@ -2,8 +2,8 @@ Measured state of `tools/rpf9dump models` on the Xbox Series 1.0.2.1 package, and the upstream `rpf9-explorer` fixes that close it. The fixes are merged upstream and the submodule is -pinned at `e293917`, where a full ten-archive re-count recovers **382,781 models** (**2.64 billion -triangles**, **0 decode failures**), up from 350,248 at `917e9b9` and 190,792 at `c3708fb`. +pinned at `e293917`, where a full ten-archive re-count recovers **382,781 models** (**0 decode +failures**), up from 350,251 at `917e9b9` and 190,792 at `c3708fb`. upstream `rpf9-explorer` fix that closes it. The fix is merged upstream and the submodule is pinned at `e293917` (the 350,251-model counts below were measured at `917e9b9`, before upstream `v1.2` PRs #8-#12 landed; the non-`levels.rpf` archives were then re-counted at @@ -23,8 +23,9 @@ per entry), the TTPF compact/array/cubemap/volume layouts, and the external draw reader. Commits `917e9b9..e293917` add upstream `v1.2` model-discovery changes (PRs #8–#12: optional fragment pointers, skipping texture dictionaries in drawable-dictionary scans, 16-bit bone-palette indices, probe-count parity, and zero-radius drawables) plus BCPack BC1/BC3/BC4/BC5 -decoding (PR #7). A full ten-archive re-count at `e293917` recovers **382,781 models** (**+32,533** -over `917e9b9`'s 350,248) and **2,636,248,990 triangles** with **0 decode failures**; the earlier +decoding (PR #7). A full ten-archive re-count at `e293917` recovers **382,781 models** (**+32,530** +over `917e9b9`'s 350,251) with **0 decode failures**; the `levels.rpf` fragment, bone-binding and +triangle cells are not independently reproduced (see the table note), and the earlier `917e9b9`, `c3708fb`, and `48557ea` measurements are kept below as controls. This page records the measured state; it is not a competing patch. decoding (PR #7). The 350,251-model counts below were measured at `917e9b9` and are kept as the @@ -63,18 +64,25 @@ effect of upstream `v1.2` PRs #8–#12: | `data.rpf` | 2,921 | **3,175** | 268 | 2,907 | 1,758 | 2,891 | 3,387,016 | 0 | +594 | | `pack/shared_minigame000/...` | 1,058 | **1,294** | 317 | 977 | 10 | 18 | 16,843,903 | 0 | +6 | | `pack/core_restofworld/...` | 924 | **936** | 808 | 128 | 53 | 849 | 1,239,596 | 0 | +51 | -| `pack/story000_restofworld/...` | 1 | **3** | 3 | 0 | 0 | 0 | 2,620 | 0 | +3 | +| `pack/story000_restofworld/...` | 1 | **3** | 3 | 0 | 0 | 0 | 2,620 | 0 | 0 | | `pack/story000/story000.rpf` | 4,195 | **7,461** | 4,156 | 3,305 | 0 | 0 | 39,861,747 | 0 | +1 | | `packs.rpf` | 26,389 | **26,585** | 23,720 | 2,865 | 2,865 | 26,585 | 64,966,572 | 0 | +2,551 | -| `levels.rpf` | 235,330 | **343,327** | 130,239 | 213,088 | 50,731 | 59,544 | 2,509,947,536 | 71 | +29,327 | +| `levels.rpf` | 235,330 | **343,327** | 130,239 | 213,088 | † | † | † | 71 | +29,327 | | `textures.rpf` | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | | `common.rpf`, `core_restofworld001` | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| **Total** | **270,819** | **382,781** | **159,511** | **223,270** | **55,417** | **89,887** | **2,636,248,990** | **72** | **+32,533** | +| **Total** | **270,819** | **382,781** | **159,511** | **223,270** | **†** | **†** | **†** | **72** | **+32,530** | + +† `levels.rpf` was counted with `count.exe recover --verify`, which reports candidates, models, +dictionary children, standalone models, rejects and decode failures only: no `levels.rpf` manifest +exists and the harness emits no fragment, bone-binding or triangle field. Those three `levels.rpf` +cells, and the totals that would include them, are therefore **not independently reproduced**. The +other archives measure 4,686 fragments, 30,343 bone-bound and 126,301,454 triangles. Every recovered entry was read back from its archive segments and decoded through -`RageModelDecoder.Decode`: **382,781 / 382,781 decoded, 0 decode failures**, **4,090,898 meshes**, -**2,468,402,149 vertices**, **2,636,248,990 triangles (2.64 billion)**, and **1,805 embedded -textures**. +`RageModelDecoder.Decode`: **382,781 / 382,781 decoded, 0 decode failures**. The other archives +measure **236,311 meshes**, **104,183,438 vertices**, **126,301,454 triangles** and **512 embedded +textures**; the `levels.rpf` mesh/vertex/triangle/embedded cells are not independently reproduced +(see the table note). What moved between `917e9b9` and `e293917`: @@ -89,13 +97,13 @@ What moved between `917e9b9` and `e293917`: `data.rpf` (75 → 0), `core_restofworld` (140 → 0), and `shared_minigame000` (18 → 0). Only one texture-dictionary candidate remains across all ten archives (in `textures.rpf`; rejected cleanly, and recovered by `Rpf9TextureRecovery`). -- **Probe caps and zero-radius drawables (+28 dictionary children plus capped standalones).** +- **Probe caps and zero-radius drawables (+25 dictionary children plus capped standalones).** Upstream [rpf9-explorer#11](https://github.com/breadbbbb/rpf9-explorer/pull/11) recovers the 29 previously capped candidates (+1 in `story000.rpf`, and +14 dictionary children plus capped standalones in `levels.rpf`). Upstream [rpf9-explorer#12](https://github.com/breadbbbb/rpf9-explorer/pull/12) recovers all 11 zero-radius - dictionary children in `core_restofworld` (797 → 808) and 1 drawable dictionary (3 models) in - `story000_restofworld.rpf`, which previously recovered 0 models. + dictionary children in `core_restofworld` (797 → 808); `story000_restofworld.rpf` already + recovered its 3 models at `917e9b9`, so its delta is 0. - **Remaining 72 rejects (down from 1,282 at `917e9b9`).** Aside from the single texture-dictionary candidate in `textures.rpf`, all 71 remaining rejects are in `levels.rpf` (0 texture dictionaries, 0 zlib checksum errors). Sampled headers are fragment candidates (`LooksLikeFragment == true`) @@ -165,7 +173,7 @@ pages. `core_restofworld` recovers 873 of its 1,024 candidates (885 models); the models**, 130,225 dictionary children, 183,775 standalone. 1,037 candidates are rejected: the 1,009 in the last shard are texture dictionaries, not models, and 28 more in shards 1 to 7 are models the probe caps reject (see [rejected candidates](#rejected-candidates-at-917e9b9)). The -`levels.rpf` full export was not re-run, so its triangle total is still the old measurement. +`levels.rpf` full export was not re-run, so its triangle total is not re-run here. ### Rejected candidates at `917e9b9` @@ -250,9 +258,9 @@ The rows here are the `c3708fb` measurements (190,792 models); the `917e9b9` re- and the `e293917` re-count outside `levels.rpf` is 39,454. Triangle totals have not been re-run at either new pin. 24,034 models (26,585 at `e293917`), and the other archives' counts are in the tables above. The -rows here are the `c3708fb` measurements (190,792 models); the `917e9b9` re-count is 350,248. -Triangle totals for that pin have not been re-run; the current `e293917` totals are in the -full-archive table above. +rows here are the `c3708fb` measurements (190,792 models); the `917e9b9` re-count is 350,251. +Triangle totals for that pin have not been re-run; the `e293917` `levels.rpf` geometry cells are +not independently reproduced (see the table note above). At `c3708fb`, every candidate is recovered, read back and decoded: 0 decode failures, 0 readback failures, no duplicate model names, and 2.22 billion triangles (1.95 billion before). The @@ -505,7 +513,8 @@ own light bones). 1. **Done:** [rpf9-explorer PR #1](https://github.com/breadbbbb/rpf9-explorer/pull/1) is merged upstream. 2. **Done:** the pin is `e293917` (was `917e9b9`, originally `48557ea`). 3. **Done:** all ten `MODEL_ARCHIVES` were re-counted and read-back decoded at `e293917` (**382,781 - models**, **2,636,248,990 triangles**, **0 decode failures**; table above). + models**, **0 decode failures**; table above; the `levels.rpf` geometry cells are not + independently reproduced). 4. Investigate the 71 remaining unrecovered fragment candidates in `levels.rpf` (and the 1 texture-dictionary candidate in `textures.rpf`) if further upstream recovery is wanted. 5. Keep issue #29 in sync with the `e293917` counts. diff --git a/docs/world_names.md b/docs/world_names.md index 80f5725833..bd0a83b0d7 100644 --- a/docs/world_names.md +++ b/docs/world_names.md @@ -67,7 +67,9 @@ formula is proven by every resolved entry. The windows above use only names that were already exported locally. The names of almost all the other archetypes are in `levels.rpf` itself: `tools/rpf9_names.py` lists the `name.#dr` and `name.#ft` strings of every -stream, and with that list as the dictionary nearly every placement resolves. Whole `levels.rpf`, one +stream. A full pass over the data area (76.15 GB, 5,255 s) inflates 1,116,073 zlib streams (98.32% of +compressed bytes) and finds 235,814 named streams / 318,266 unique names (267,463 `.#dr`, 50,803 `.#ft`); +with that list as the dictionary nearly every placement resolves. Whole `levels.rpf`, one `world_index.py --archetypes-out` run (23,532 placement maps and 1,670,435 entities: 3 maps and 7 entities fewer than the census in [world.md](world.md#how-many-are-there), which also joins the raw continuation page that 3 placement maps use and `world_index.py` does not; 228,681 distinct `archetypeName` hashes, one 64-bit key per hash, no conflicting keys, From 23861a1398a4d04be20aac3ec9a82599d2c17ab9 Mon Sep 17 00:00:00 2001 From: Dominik <55330408+Dom-in@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:20:56 +0000 Subject: [PATCH 028/115] GPU test: image atomics in a pixel shader (ps_imgatomic) 1,018 of the corpus's 1,038 image-atomic shaders are pixel shaders, but every GPU test of image atomics ran in a compute shader (found by @aslan2142). ps_imgatomic does the corpus's forms in a pixel shader: image_atomic_umax, umin and or on three 8x8 2D r32ui images (64 pixels contend for each texel) and umax on a 4x4x4 3D image, each found through its own T# in the descriptor table and the set-0 r32ui storage arrays. Odd pixels are discarded after their atomics, which must still count. vk_bindless_test runs it when given ps_imgatomic.spv: it enables fragmentStoresAndAtomics (exit 77 without it), clears the images (umin to all ones), draws, and checks all 256 texels against a model of the 4096 pixels and the render target's discarded columns. run_gpu_tests.py and check.py run it next to ps_tex. Co-Authored-By: Claude Opus 5.5 --- runtime/test/shaders/check.py | 11 +- runtime/test/shaders/ps_imgatomic.asm | 44 +++++++ runtime/test/vk_bindless_test.cpp | 179 +++++++++++++++++++++++++- scripts/run_gpu_tests.py | 12 +- tests/test_shader_checks.py | 3 +- 5 files changed, 238 insertions(+), 11 deletions(-) create mode 100644 runtime/test/shaders/ps_imgatomic.asm diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 2f28531756..85d11d73a3 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -707,9 +707,10 @@ def subgroup_size(spirv, name): return None -def bindless_test(tools, spirv): - """ps_tex: a texture found through the descriptor hash table and the bindless set (vk_bindless_test).""" - shaders = [os.path.join(spirv, name + ".spv") for name in ("vs_ids", "ps_tex")] +def bindless_test(tools, spirv, pixel="ps_tex"): + """ps_tex: a texture found through the descriptor hash table and the bindless set (vk_bindless_test). + ps_imgatomic: image atomics in a pixel shader through the set's r32ui storage arrays, checked per texel.""" + shaders = [os.path.join(spirv, name + ".spv") for name in ("vs_ids", pixel)] for path in shaders: if not os.path.isfile(path): return f"missing {os.path.basename(path)}" @@ -717,6 +718,9 @@ def bindless_test(tools, spirv): if code == UNSUPPORTED: m = re.search(r"unsupported: .*", out) return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})") + if pixel == "ps_imgatomic": + m = re.search(r"ps_imgatomic: (\d+) of \d+ texels wrong.*; (\d+) of \d+ render-target pixels wrong", out) + return "" if code == 0 and m and m.group(1) == "0" and m.group(2) == "0" else failure(code, out, 3) m = re.search(r"(\d+) draws read back, (\d+) bad pixels", out) return "" if code == 0 and m and m.group(2) == "0" else failure(code, out, 3) @@ -1254,6 +1258,7 @@ def main(): results.append((name, texture_constant_test(tools, spirv, name))) results.append(("ps_tex", bindless_test(tools, spirv))) results.append(("ps_ssharp", sampler_test(tools, spirv))) + results.append(("ps_imgatomic", bindless_test(tools, spirv, "ps_imgatomic"))) for name in MIP_TEST_PASSES: results.append((name, texture_mip_test(tools, spirv, name))) for name in GRADIENT_TESTS: diff --git a/runtime/test/shaders/ps_imgatomic.asm b/runtime/test/shaders/ps_imgatomic.asm new file mode 100644 index 0000000000..b8f888c131 --- /dev/null +++ b/runtime/test/shaders/ps_imgatomic.asm @@ -0,0 +1,44 @@ +; Image atomics in a pixel shader, the forms the game uses (1,018 of its 1,038 image-atomic shaders are pixel shaders: +; image_atomic_or / umin / umax on a 2D image and umax on a 3D one), through the descriptor table and the set-0 +; r32ui storage arrays (binding 4 for 2D, 7 for 3D). User data s2:s3 is the console VA of a table of four T#s: +; +0x00 the 2D umax image, +0x20 the 2D umin image, +0x40 the 2D or image, +0x60 the 3D umax image (any 8 dwords: +; only the key matters). Each of the 64x64 pixels computes px, py from attr0 (vs_ids runs it 0..1 over the target), +; its id = px + 64 * py, and its texel tx = px >> 3, ty = py >> 3, so 64 pixels contend for each texel of the 8x8 +; images: +; umax2d[ty][tx] = max(id), umin2d[ty][tx] = min(id), or2d[ty][tx] |= 1 << (id & 31), +; umax3d[px & 3][ty >> 1][tx >> 1] = max(id) (a 4x4x4 image) +; After its atomics, every odd px is discarded (v_cmpx). The atomics of a pixel that is discarded afterwards still +; count, as on hardware: the expected values above are over all 4096 pixels. Even pixels export 1.0. +; Run: vk_bindless_test vs_ids.spv ps_imgatomic.spv (images cleared to 0, umin to 0xffffffff; checked per texel) +s_load_dwordx8 s[8:15], s[2:3], 0x0 +s_load_dwordx8 s[16:23], s[2:3], 0x20 +s_load_dwordx8 s[24:31], s[2:3], 0x40 +s_load_dwordx8 s[32:39], s[2:3], 0x60 +s_waitcnt lgkmcnt(0) +v_interp_p1_f32_e32 v2, v0, attr0.x +v_interp_p2_f32_e32 v2, v1, attr0.x +v_interp_p1_f32_e32 v3, v0, attr0.y +v_interp_p2_f32_e32 v3, v1, attr0.y +v_mul_f32_e32 v2, 0x42800000, v2 +v_mul_f32_e32 v3, 0x42800000, v3 +v_cvt_u32_f32_e32 v4, v2 +v_cvt_u32_f32_e32 v5, v3 +v_lshlrev_b32_e32 v6, 6, v5 +v_add_nc_u32_e32 v6, v6, v4 +v_lshrrev_b32_e32 v7, 3, v4 +v_lshrrev_b32_e32 v8, 3, v5 +image_atomic_umax v6, v[7:8], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +image_atomic_umin v6, v[7:8], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +v_and_b32_e32 v9, 31, v6 +v_lshlrev_b32_e64 v9, v9, 1 +image_atomic_or v9, v[7:8], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +v_lshrrev_b32_e32 v10, 1, v7 +v_lshrrev_b32_e32 v11, 1, v8 +v_and_b32_e32 v12, 3, v4 +image_atomic_umax v6, v[10:12], s[32:39] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +s_waitcnt vmcnt(0) +v_and_b32_e32 v13, 1, v4 +v_cmpx_eq_u32_e32 0, v13 +v_mov_b32_e32 v14, 1.0 +exp mrt0 v14, v14, v14, v14 done vm +s_endpgm diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp index 73ac39013a..419a1dda4f 100644 --- a/runtime/test/vk_bindless_test.cpp +++ b/runtime/test/vk_bindless_test.cpp @@ -24,6 +24,7 @@ #include "vk_shader_fma.h" #include "../src/vulkan_bindless.h" +#include #include #include #include @@ -105,7 +106,7 @@ std::uint32_t probe_depth(std::span table, const Descriptor int main(int argc, char** argv) { if (argc < 3) { - std::fprintf(stderr, "usage: vk_bindless_test \n"); + std::fprintf(stderr, "usage: vk_bindless_test \n"); return 2; } // A bad readback in a single channel must still fail when all three others match. @@ -225,6 +226,15 @@ int main(int argc, char** argv) { VkPhysicalDeviceFeatures2 enable{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &enable12}; enable.features.shaderInt64 = VK_TRUE; enable.features.shaderSampledImageArrayDynamicIndexing = VK_TRUE; + // ps_imgatomic: image atomics in a pixel shader need fragment stores and atomics. + const bool atomic_mode = std::strstr(argv[2], "imgatomic") != nullptr; + if (atomic_mode) { + if (!have.features.fragmentStoresAndAtomics) { + std::printf("unsupported: fragmentStoresAndAtomics (image atomics in a pixel shader)\n"); + return unsupported; + } + enable.features.fragmentStoresAndAtomics = VK_TRUE; + } std::uint32_t qn = 0; vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr); @@ -260,7 +270,7 @@ int main(int argc, char** argv) { LD(vkDeviceWaitIdle); LD(vkDestroyPipeline); LD(vkDestroyPipelineLayout); LD(vkDestroyCommandPool); LD(vkDestroyShaderModule); LD(vkDestroyFramebuffer); LD(vkDestroyRenderPass); LD(vkDestroySampler); LD(vkDestroyImageView); LD(vkDestroyImage); LD(vkDestroyBuffer); - LD(vkFreeMemory); LD(vkDestroyDevice); + LD(vkFreeMemory); LD(vkDestroyDevice); LD(vkCmdClearColorImage); VkQueue queue = VK_NULL_HANDLE; vkGetDeviceQueue(dev, qi, 0, &queue); VkPhysicalDeviceMemoryProperties mp; @@ -663,6 +673,171 @@ int main(int argc, char** argv) { const std::uint32_t sampler_index = set.add_sampler(nearest); EXPECT(decoy_sampler == 1 && sampler_index == 2); + if (atomic_mode) { + // ps_imgatomic.asm: image_atomic_umax/umin/or on three 8x8 r32ui images and umax on a 4x4x4 one, from + // every pixel of the 64x64 draw (64 pixels per 2D texel), each found through its own T# key. Odd + // pixels are discarded after their atomics, which still count. + constexpr std::uint32_t atomic_va = 1024, AW = 8, A3 = 4; + const std::array keys{{{0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8}, + {0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8}, + {0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8}, + {0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8}}}; + for (std::uint32_t k = 0; k < 4; ++k) + std::memcpy(static_cast(heap_map) + atomic_va + 32 * k, keys[k].data(), 32); + const VkImageUsageFlags atomic_usage = + VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | + VK_IMAGE_USAGE_TRANSFER_DST_BIT; + VkImage images[4]; + VkImageView views[4]; + for (int k = 0; k < 3; ++k) CHECK(make_image(VK_FORMAT_R32_UINT, AW, AW, atomic_usage, &images[k], &views[k])); + { // the 3D image + VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; + ii.imageType = VK_IMAGE_TYPE_3D; + ii.format = VK_FORMAT_R32_UINT; + ii.extent = {A3, A3, A3}; + ii.mipLevels = 1; + ii.arrayLayers = 1; + ii.samples = VK_SAMPLE_COUNT_1_BIT; + ii.usage = atomic_usage; + CHECK(vkCreateImage(dev, &ii, nullptr, &images[3])); + VkMemoryRequirements mr; + vkGetImageMemoryRequirements(dev, images[3], &mr); + VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + ai.allocationSize = mr.size; + ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + VkDeviceMemory m; + CHECK(vkAllocateMemory(dev, &ai, nullptr, &m)); + allocations.push_back(m); + CHECK(vkBindImageMemory(dev, images[3], m, 0)); + VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + vi.image = images[3]; + vi.viewType = VK_IMAGE_VIEW_TYPE_3D; + vi.format = VK_FORMAT_R32_UINT; + vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + CHECK(vkCreateImageView(dev, &vi, nullptr, &views[3])); + } + std::uint32_t indices[4]; + for (int k = 0; k < 4; ++k) { + StorageViews storage; + storage.as_uint = views[k]; + storage.r32ui = views[k]; + indices[k] = set.add_image(k == 3 ? ImageDimension::dim_3d : ImageDimension::dim_2d, views[k], + VK_IMAGE_LAYOUT_GENERAL, storage); + EXPECT(indices[k] != 0); + EXPECT(set.insert_key(keys[k], indices[k])); + } + EXPECT(flush()); + + // Clear: umax and or start at 0, umin at all ones; then GENERAL for the shader's atomics. + CHECK(vkResetCommandBuffer(cmd, 0)); + CHECK(vkBeginCommandBuffer(cmd, &begin)); + if (!set.fallbacks_ready()) set.record_fallback_init(cmd); + for (int k = 0; k < 4; ++k) { + VkImageMemoryBarrier b{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; + b.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + b.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + b.newLayout = VK_IMAGE_LAYOUT_GENERAL; + b.srcQueueFamilyIndex = b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + b.image = images[k]; + b.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, + nullptr, 0, nullptr, 1, &b); + VkClearColorValue value{}; + for (auto& c : value.uint32) c = k == 1 ? 0xFFFFFFFFu : 0u; + vkCmdClearColorImage(cmd, images[k], VK_IMAGE_LAYOUT_GENERAL, &value, 1, &b.subresourceRange); + b.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + b.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + b.oldLayout = b.newLayout = VK_IMAGE_LAYOUT_GENERAL; + vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, + nullptr, 0, nullptr, 1, &b); + } + CHECK(submit()); + + // The draw, then the images and the render target read back. + const VkDeviceSize image_bytes = 3 * AW * AW * 4 + A3 * A3 * A3 * 4; + VkBuffer atomic_readback; + void* atomic_map; + CHECK(make_buffer(image_bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &atomic_readback, &atomic_map)); + CHECK(vkResetCommandBuffer(cmd, 0)); + CHECK(vkBeginCommandBuffer(cmd, &begin)); + VkClearValue clear{}; + for (float& channel : clear.color.float32) channel = 0.25f; + VkRenderPassBeginInfo rbi{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; + rbi.renderPass = pass; + rbi.framebuffer = framebuffer; + rbi.renderArea = scissor; + rbi.clearValueCount = 1; + rbi.pClearValues = &clear; + vkCmdBeginRenderPass(cmd, &rbi, VK_SUBPASS_CONTENTS_INLINE); + vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + const VkDescriptorSet bound = set.set(); + vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &bound, 0, nullptr); + std::uint32_t block[36] = {}; + block[2] = atomic_va; + block[32] = std::uint32_t(heap_base); + block[33] = std::uint32_t(heap_base >> 32); + vkCmdPushConstants(cmd, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, + sizeof(block), block); + vkCmdDraw(cmd, 3, 1, 0, 0); + vkCmdEndRenderPass(cmd); + VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + after.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &after, + 0, nullptr, 0, nullptr); + VkDeviceSize offset = 0; + for (int k = 0; k < 4; ++k) { + VkBufferImageCopy rc{}; + rc.bufferOffset = offset; + rc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + rc.imageExtent = k == 3 ? VkExtent3D{A3, A3, A3} : VkExtent3D{AW, AW, 1}; + vkCmdCopyImageToBuffer(cmd, images[k], VK_IMAGE_LAYOUT_GENERAL, atomic_readback, 1, &rc); + offset += k == 3 ? A3 * A3 * A3 * 4 : AW * AW * 4; + } + VkBufferImageCopy tc{}; + tc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + tc.imageExtent = {W, H, 1}; + vkCmdCopyImageToBuffer(cmd, target, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, readback, 1, &tc); + CHECK(submit()); + + // The model: every pixel's atomics, discarded or not. + std::vector want(3 * AW * AW + A3 * A3 * A3, 0); + for (std::uint32_t t = 0; t < AW * AW; ++t) want[AW * AW + t] = 0xFFFFFFFFu; + for (std::uint32_t py = 0; py < H; ++py) + for (std::uint32_t px = 0; px < W; ++px) { + const std::uint32_t id = px + 64 * py, t = (py >> 3) * AW + (px >> 3); + want[t] = std::max(want[t], id); + want[AW * AW + t] = std::min(want[AW * AW + t], id); + want[2 * AW * AW + t] |= 1u << (id & 31); + const std::uint32_t v = ((px & 3) * A3 + (py >> 4)) * A3 + (px >> 4); + want[3 * AW * AW + v] = std::max(want[3 * AW * AW + v], id); + } + const auto* got = static_cast(atomic_map); + const char* names[] = {"2D umax", "2D umin", "2D or", "3D umax"}; + unsigned wrong = 0; + for (std::size_t i = 0; i < want.size(); ++i) { + if (got[i] == want[i]) continue; + const int k = i < 3 * AW * AW ? int(i / (AW * AW)) : 3; + if (wrong++ < 8) + std::printf(" %s texel %zu: got 0x%08x, want 0x%08x\n", names[k], + k == 3 ? i - 3 * AW * AW : i % (AW * AW), got[i], want[i]); + } + const float* rt = static_cast(readback_map); + unsigned bad_rt = 0; + for (std::uint32_t py = 0; py < H; ++py) + for (std::uint32_t px = 0; px < W; ++px) + bad_rt += rt[(py * W + px) * 4] != ((px & 1) ? 0.25f : 1.0f); + std::printf("ps_imgatomic: %u of %zu texels wrong (2D umax/umin/or 8x8 each, 3D umax 4x4x4); " + "%u of %u render-target pixels wrong (odd columns discarded)\n", + wrong, want.size(), bad_rt, W * H); + vkDeviceWaitIdle(dev); + if (g_validation_errors) { + std::printf("ps_imgatomic: %u validation errors\n", g_validation_errors); + return 1; + } + return wrong || bad_rt ? 1 : 0; + } + // A view that comes and goes before the set is flushed is never written: a texture created and destroyed // between two submissions. Its slots are written once, with the fallback; a write of the destroyed view // would be a validation error. diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 7209c364c3..a88c371215 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -548,7 +548,7 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool, # Shaders a selected test draws with, built even when the filter leaves them out (#192). DRAWN_WITH = {GATHER_LOD_TEST: "vs_ids.asm", "ps_flat": "vs_ids.asm", "ps_texture_sample": "vs_ids.asm", "ps_cube_sample": "vs_ids.asm", "ps_texture_sample_d16": "vs_ids.asm", "ps_sample_c_lz": "vs_ids.asm", "ps_sample_c_lz_a16": "vs_ids.asm", - **{name: "vs_ids.asm" for name in TEXTURE_CONSTANTS}, "ps_ssharp": "vs_ids.asm", + **{name: "vs_ids.asm" for name in TEXTURE_CONSTANTS}, "ps_ssharp": "vs_ids.asm", "ps_imgatomic": "vs_ids.asm", **{name: "vs_ids.asm" for name in GRADIENT_TESTS}, "vs_clip": "ps_clip_color.asm", "ps_interp_f16_high": "vs_f16_pack.asm", "ms_f16_pack": "ps_interp_f16_high.asm", "ps_interp_f32_mods": "vs_interp_consts.asm", "ps_interp_mov_mods": "vs_interp_consts.asm", @@ -1042,10 +1042,12 @@ def run_suite(a, work: str) -> int: else: results.append((name, rc == 0 and bad == 0, "4096/4096 pixels exact" if bad == 0 else f"{bad} pixels differ from {expected}: {msg.splitlines()[-1] if msg else ''}")) - elif name == "ps_tex": - # A texture through the descriptor hash table and the bindless set. vk_bindless_test compares the - # pixels itself, and exits 77 where the device lacks a feature the set or the shader needs. - rc, msg = run_cmd([vk_bindless, vs_tri, spv]) + elif name in ("ps_tex", "ps_imgatomic"): + # A texture through the descriptor hash table and the bindless set (ps_tex), or image atomics in a pixel + # shader through the set's r32ui storage arrays (ps_imgatomic, drawn with vs_ids). vk_bindless_test + # compares the result itself, and exits 77 where the device lacks a feature the set or shader needs. + vs = os.path.join(spirv_dir, "vs_ids.spv") if name == "ps_imgatomic" else vs_tri + rc, msg = run_cmd([vk_bindless, vs, spv]) lines = msg.splitlines() if rc == 77: reason = next((ln for ln in lines if ln.startswith("unsupported:")), "unsupported device") diff --git a/tests/test_shader_checks.py b/tests/test_shader_checks.py index 9518c82c75..c4bd7c042b 100644 --- a/tests/test_shader_checks.py +++ b/tests/test_shader_checks.py @@ -33,7 +33,8 @@ + len(check.PIXEL_TESTS) + len(check.CLIP_TESTS) + len(check.BOUNDS) + len(check.GLOBAL_OFFSET) + len(check.MIP_TEST_PASSES) + len(check.GRADIENT_TESTS) + len(check.STORE_WORDS) + len(check.GET_LOD_TESTS) - + len(check.TEXTURE_CONSTANTS) + 9) # three mesh fixtures, ps_tex, four compute fixtures and ps_ssharp + + len(check.TEXTURE_CONSTANTS) + 10) # three mesh fixtures, ps_tex, ps_imgatomic, four compute fixtures and + # ps_ssharp CVT = {bits: [u, s] for bits, u, s in check.CVT_F32_SAT_CASES} From ab55405c2c3a9800c7c575bc2c4eb87b1842d4e3 Mon Sep 17 00:00:00 2001 From: mokkymiah Date: Sun, 22 Nov 2026 12:37:33 +0000 Subject: [PATCH 029/115] Tests: GPU coverage for ds_cmpst_b32 and the b64 LDS 2-address forms --- docs/design.md | 4 +- runtime/test/shaders/check.py | 7 +- runtime/test/shaders/cs_lds_b64_cmpst.asm | 132 ++++++++++++++++++++++ scripts/run_gpu_tests.py | 11 +- 4 files changed, 147 insertions(+), 7 deletions(-) create mode 100644 runtime/test/shaders/cs_lds_b64_cmpst.asm diff --git a/docs/design.md b/docs/design.md index 9e38cc015f..171dc0315e 100644 --- a/docs/design.md +++ b/docs/design.md @@ -312,12 +312,12 @@ How the generated SPIR-V expects the runtime to work: | Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. This was checked against what all 2,689 CS read before writing: 2,281 match exactly, and the rest overshoot only through loop-carried registers in the straight-line check. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. Shaders with TG_SIZE_EN are rejected for now. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. | | Workgroup barriers | `s_barrier` (cs/ms) is one `OpControlBarrier` (workgroup scope, workgroup memory). On RDNA every `s_barrier` counts against the same workgroup barrier and a wave that has ended no longer counts, while Vulkan requires a barrier to be reached by every invocation in uniform control flow. Under `--wave64-emulate` the round loop keeps a single barrier at the top level, so this holds. **Native wave32 compute shaders run in barrier rounds** when an `s_barrier` sits anywhere but a top-level block of the structured tree (one every invocation runs): under a guard, in a loop, or in the dispatch loop (`needs_barrier_rounds`, `bar_scheduler`). That is the emulated loop without its cross-lane part: `s_barrier` ends a segment, each invocation runs its blocks until its next `s_barrier` or the end, then the whole workgroup meets at one `OpControlBarrier` (the same workgroup/acquire-release/workgroup-memory semantics) at the end of the round. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3) ends the loop. Cross-lane operations stay subgroup operations, as in the dispatch loop, since a wave's lanes run the same segment. A barrier in a top-level block keeps the single `OpControlBarrier` in place. In the 1.0.2.1 corpus 43 of the 55 wave32 cs shaders with `s_barrier` have one nested (SHADER-91's count), so those 43 now run in rounds. Why: an Intel GPU does not survive the nested form. `cs_barrier_divergent.asm` (two barrier sites in different branches), `cs_barrier_early_end.asm` (the other waves end without a barrier) and `cs_barrier_loop.asm` (a barrier in a loop whose trip count differs per wave) each lose the device (`vkQueueWaitIdle` → `VK_ERROR_DEVICE_LOST`) on an Intel Arrow Lake Xe-LPG iGPU (Windows 32.0.101.8132), and `cs_barrier_divergent` hangs or writes nothing on a UHD 770 (101.6129, #634). With barrier rounds all three pass there and on an RTX 5070 Ti Laptop (617.42). NVIDIA passed them before too (RTX 4070 Ti on 610.88 and 621.24, RTX 5090 on Linux 595.99, RTX 5070 Ti). **Still not proven on the native wave64 path** (wave64 cs and every ms, run natively only on AMD's 64-wide subgroups): there the barrier stays where `s_barrier` is, inside a selection or loop construct in every ms and most wave64 cs shaders of the corpus. Branches are scalar, so whole waves take the same path, and RDNA's own barrier counts the way the shader expects. | | LDS | A `Workgroup` uint array sized from LDS_SIZE, rounded up to a power of two that also covers every constant offset (15 of 486 shaders index past LDS_SIZE). Covers `ds_read/write_b32..b128`, `read2/write2` (+`st64`), `u16`/`i16`/`u8`/`i8` reads (also `ds_read_u16_d16`/`_d16_hi` and, since SHADER-85, `ds_read_u8_d16`/`_d16_hi` and `ds_read_i8_d16`/`_d16_hi`: the byte is zero- or sign-extended 8→16 into one half of the destination VGPR and the other half is kept, per the RDNA2 ISA DS opcode descriptions (opcodes 162–165) and as for the u16 d16 reads; GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. `ds_permute_b32`, its forward (scatter) form, has no Vulkan equivalent: each source lane that is on in EXEC publishes `((vAddr + offset) >> 2) mod 32` and each destination lane scans the 32 sources of its half and keeps the last one that targets it (a shuffle of target and data per source lane; under `--wave64-emulate` two buffer rounds and a Function variable instead). Per the ISA pseudocode (`tmp[0..63] = 0`; `next if !EXEC[i]` on the source; `VGPR[VDST][i] = tmp[i]` only `if EXEC[i]`): a destination lane nobody targets gets 0, an off source sends nothing, an off destination keeps its VDST, and the half rule above applies as for `ds_bpermute_b32`. When several sources target one lane the ISA leaves the winner unpredictable ("the value from one of the writers"; its pseudocode says the highest-numbered); the translator takes the highest, and nothing may depend on it. Confirmed by the GPU tests `cs_w32_permute.asm` and, per half of a wave64, `cs_w64x_permute.asm` (SHADER-90: rotation, offset, unwritten lane = 0, off destination keeps its value, off source does not win) and `tests/semantic/test_ds_permute.py`. A source lane that is off in EXEC reads 0 and an off destination lane keeps its value (RDNA ISA §10.4.4), in wave32 as in wave64. In wave64 the permute also runs as two wave32s: each half reads lanes of its own half. Until 2026-11-21 lanes 32–63 of a 64-wide subgroup read the low half and inactive sources kept their value (`cs_w64x_bpermute`, AMD Radeon 880M); the wave32 path shuffled the raw value until the same day (`cs_bpermute32`: wave32, EXEC without lanes 8–15, so lane 6 reads 0; GPU-checked on RTX 5070 and Radeon 880M). A source lane that doesn't exist, in the missing lanes of a partial wave, also reads 0: the shuffle result is kept only where a ballot of the running invocations has the source lane, since SPIR-V leaves a shuffle from an invocation that isn't running undefined. Before this, RADV returned stale register values that changed between runs (`cs_w64x_partial`, a 40-thread group, native wave64 on AMD RX 6700 XT, RADV Mesa 26.3.1). Writes and atomics run only in active lanes. Indices wrap at the array size, where hardware would return 0 for out-of-range reads. `s_barrier` = `OpControlBarrier` Workgroup/Workgroup, AcquireRelease + WorkgroupMemory. | -| `ds_cmpst_b32` | The non-returning compare-and-store: `M = (M == data0) ? data1 : M`, the same `OpAtomicCompareExchange` as `ds_cmpst_rtn_b32` with the old value dropped (operands vaddr, data0, data1). Source: RDNA2 ISA DS_CMPST_B32. CPU-checked by `tests/semantic/test_lds_atomics_values.py`. **Not GPU-verified.** | +| `ds_cmpst_b32` | The non-returning compare-and-store: `M = (M == data0) ? data1 : M`, the same `OpAtomicCompareExchange` as `ds_cmpst_rtn_b32` with the old value dropped (operands vaddr, data0, data1). Source: RDNA2 ISA DS_CMPST_B32. CPU-checked by `tests/semantic/test_lds_atomics_values.py`; GPU-checked by `runtime/test/shaders/cs_lds_b64_cmpst.asm` (hit and miss on an RTX 3070, driver 621.01, Windows 11). | | `ds_wrxchg2_rtn_b32`, `ds_wrxchg2st64_rtn_b32` | Two atomic exchanges, addressed as `ds_write2_b32` addresses its dwords: `vaddr + offset0 * 4` and `vaddr + offset1 * 4` (times 64 for st64). `M[A0] = data0` and `M[A1] = data1`, and `vdst` (a VGPR pair) gets the two old words. Both exchanges run before either result is written, so `vdst` may alias the address or data VGPRs. When both offsets name one dword, the second exchange returns `data0`. Each exchange is atomic on its own, not the pair together, as on hardware (two DS operations). Until 2026-11-22 both ops raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_wrxchg2.py` (offsets, st64 = 256-byte steps, the same dword twice, aliasing, a single-VGPR `vdst` rejected). **Not GPU-verified.** | | `ds_wrxchg_rtn_b64`, `ds_wrxchg2_rtn_b64`, `ds_wrxchg2st64_rtn_b64` | 64-bit LDS exchanges (two dwords, low first): `M[A] = DATA`, and `vdst` gets the old 64 bits. `wrxchg_rtn_b64` has one element at `vaddr + offset`. The `2` forms have two, at `vaddr + offset0/offset1 * 8` (times 64 for st64), as `ds_write2_b64` addresses them, and `vdst` is four VGPRs. Each dword is its own 32-bit `OpAtomicExchange`, so the memory ends as a 64-bit exchange leaves it, without Int64 atomics on Workgroup memory. All exchanges run before `vdst` is written. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Until 2026-11-22 these three raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_wrxchg_b64.py` (values, `offset:`, `vdst` aliasing the data, both 2 forms, st64 = 512-byte steps, bad operands rejected). **Not GPU-verified.** | | `ds_and_b64`, `ds_or_b64`, `ds_xor_b64` (and `_rtn_`) | `M = M op DATA` on the 64-bit LDS element at `vaddr + offset` (two dwords, low first); the `_rtn_` form returns the old 64 bits in a VGPR pair. A bitwise op works on each bit alone, so it is emitted as one 32-bit `OpAtomicAnd/Or/Xor` per dword. That leaves exactly the memory a 64-bit atomic would, without Int64 atomics on Workgroup memory (optional in Vulkan). **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done; the memory result is exact. The other 64-bit LDS atomics (`add/sub/min/max_u64`, `wrxchg_b64`, `cmpst_b64`) carry between dwords or need the pair to move together, and still raise `Unsupported`. Until 2026-11-22 these three were rejected as well. CPU-checked by `tests/semantic/test_lds_bitwise_b64.py` (all six forms, offsets, `vdst` aliasing the data, seeded values). **Not GPU-verified.** | | `ds_bpermute_b32` subgroup convergence | Native wave32 and wave64 apply bitwise masks to the shuffle result and the destination write so both the ballot and shuffle execute before lane predication. If the ballot has no source lane, the shuffle reads the calling lane before the result is masked to zero. MoltenVK 1.4.2 lowered the scalar selects to nested Metal ternaries, placing the subgroup operations in divergent control flow. The `cs_bpermute32` inactive-source case returned 64 on an Apple M1 Max, and all eight fixture words match with bitwise masking. | -| LDS 2-address b64 (`ds_read2_b64`, `ds_write2_b64`, `ds_read2st64_b64`, `ds_write2st64_b64`) | Two elements at vaddr + offset0·unit and vaddr + offset1·unit, unit = 8 bytes (×64 for st64); each element is two consecutive dwords, low first. `read2_b64` fills v[d:d+3] after all four loads (a vdst overlapping vaddr is safe); `write2_b64` takes two VGPR pairs. The b32 forms share the code with unit 4. Source: RDNA2 ISA DS 2-address forms. CPU-checked by `tests/semantic/test_lds_read2_write2_b64.py` (compute listings, LDS as a Workgroup variable). **Not GPU-verified.** | +| LDS 2-address b64 (`ds_read2_b64`, `ds_write2_b64`, `ds_read2st64_b64`, `ds_write2st64_b64`) | Two elements at vaddr + offset0·unit and vaddr + offset1·unit, unit = 8 bytes (×64 for st64); each element is two consecutive dwords, low first. `read2_b64` fills v[d:d+3] after all four loads (a vdst overlapping vaddr is safe); `write2_b64` takes two VGPR pairs. The b32 forms share the code with unit 4. Source: RDNA2 ISA DS 2-address forms. CPU-checked by `tests/semantic/test_lds_read2_write2_b64.py` (compute listings, LDS as a Workgroup variable); GPU-checked by `runtime/test/shaders/cs_lds_b64_cmpst.asm` (unit 8 and the 512-byte st64 forms, plus vdst/vaddr overlap, on an RTX 3070, driver 621.01, Windows 11). | | Compute workgroup IDs Y/Z | With four user SGPRs and only TGID_Y and TGID_Z enabled (RSRC2 `0x308`), s4 receives Y and s5 receives Z. The synthetic `cs_workgroup_yz.asm` fixture checks a 2 × 3 × 4 dispatch and each of its 24 origins against a CPU reference. | | Typed image stores | `image_store` (2D, 2D array, 3D) writes the dmask components (missing ones = 0). The image's numeric type lives in the T# (word 1 FORMAT [28:20], 512 GFX10 formats), so it is decided at run time. A 512-bit table built from `tools/gfx10_formats.json` (30 UINT and 15 SINT formats) picks a **sint**, **uint** or **float** view (bindings 8 + 3·dim + class; dim 0 = 2D, 1 = 2D array, 2 = 3D; class 0 float, 1 uint, 2 sint). Views have Unknown format (`shaderStorageImageWriteWithoutFormat`). **The runtime binds every storage image into all three arrays of its dimension, or at least the one matching its format.** The earlier path wrote only component 0 as `r32ui`, which was wrong for every other format. GPU-checked with `runtime/test/shaders/cs_imgstore.asm` through `runtime/test/vk_store_test.cpp`: rgba8 unorm, r32 uint and r32 sint images, every texel correct. | | Typed image loads | `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). Before #1136, a d16 load always read the float view, so a `Texture2D` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Native gfx1036 saturated 32-bit UINT/SINT texels to the unsigned/signed 16-bit range in both D16 load forms; the translated 2D load matched both limits on RTX 5080 and Radeon Graphics. D16 loads on 1D, 2D-array and 3D images still lack GPU checks. | diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 2f28531756..3bc411ba11 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -81,14 +81,14 @@ def not_found_message(build, missing): WAVE32_DUMPS = ("cs_store", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_bpermute32", "cs_w32_partial_scmp", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext", - "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos") + "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos", "cs_lds_b64_cmpst") # Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is # narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is. They run with # 32 lanes requested (WAVE32_LANE_ENV), as run_gpu_tests.py does: a device with a range like 8..32 (Intel ANV) may # otherwise pick a narrower size and return different words (#774). WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"} WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_exec_const", - "cs_w32_mask_imm") + "cs_w32_mask_imm", "cs_lds_b64_cmpst") CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]), ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]), ("cs_dpp_mask", [1, 0, 3, 2, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee]), @@ -116,6 +116,9 @@ def not_found_message(build, missing): ("cs_w32_salu64", [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE]), # SHADER-85: 8-bit LDS reads into one half of a VGPR, the other half kept ("cs_w32_lds_u8_d16", [0xBEEF00FF, 0x00FF1234, 0xBEEFFF80, 0xFF801234, 0xBEEF007F, 0x007F1234, 0xBEEF0080, 0xFFFF1234]), + # ds_cmpst_b32 and the b64 2-address forms (cs_lds_b64_cmpst.asm header) + ("cs_lds_b64_cmpst", [0x11110001, 0x22220002, 0x33330003, 0x44440004, + 0xCCCC000C, 0x44440004, 0xBBBB000B, 0x3579BADC]), # constant EXEC: each lane takes its own bit (Intel got 16-bit constants wrong for lanes 16-31) ("cs_exec_const", [16, 8, 2, 16, 0, 16]), # a constant lane mask (saveexec, wrexec, s_and/s_not/s_mov_b64 into EXEC or VCC) gives lane L its bit L, diff --git a/runtime/test/shaders/cs_lds_b64_cmpst.asm b/runtime/test/shaders/cs_lds_b64_cmpst.asm new file mode 100644 index 0000000000..0998d85765 --- /dev/null +++ b/runtime/test/shaders/cs_lds_b64_cmpst.asm @@ -0,0 +1,132 @@ +; GPU test for the two LDS families that docs/design.md lists as not GPU-verified: +; ds_cmpst_b32 (the non-returning compare-and-store) and the b64 2-address forms +; (ds_read2_b64 / ds_write2_b64 and their st64 variants). +; +; LDS 4 KiB (RSRC2 0x40088), group 32x1x1, only lane 0 runs. The output words are +; derived from the RDNA2 ISA's 2-address and DS_CMPST_B32 pseudocode: +; +; out[0..3] ds_write2_b64 then ds_read2_b64 at base 0x20, offset0:1 offset1:3, +; writes A at 0x28 and B at 0x38 (unit 8), reads the same two elements: +; A.lo A.hi B.lo B.hi +; out[4] ds_read2st64_b64 at base 0x100, offset0:0 offset1:1 (unit 512): +; XOR of the four dwords seeded at 0x100 and 0x300 +; out[5] ds_write2st64_b64 at base 0x100, offset0:0 offset1:1, then plain +; ds_read_b32 at 0x100/0x104/0x300/0x304: XOR of the four dwords +; out[6] ds_read2_b64 v[2:5], v2 at base 0x200 (vdst overlaps vaddr): the +; second element's low dword, 0xBBBB000B, read before v2 is overwritten +; out[7] ds_cmpst_b32 hit (mem 0x13572468 -> 0x2468ABCD) XOR the miss case's +; unchanged word (0x11111111): 0x3579BADC +; +; Run: vk_compute_test cs_lds_b64_cmpst.spv 1 dump +; -> out[0..7] = 0x11110001 0x22220002 0x33330003 0x44440004 +; 0xCCCC000C 0x44440004 0xBBBB000B 0x3579BADC +; rsrc2: 0x40088 +; group: 32,1,1 +; mattr: +wavefrontsize32,-wavefrontsize64 +v_cmpx_eq_u32_e32 0, v0 + +; --- ds_write2_b64 / ds_read2_b64, unit 8 bytes --- +v_mov_b32_e32 v2, 0x20 +v_mov_b32_e32 v4, 0x11110001 +v_mov_b32_e32 v5, 0x22220002 +v_mov_b32_e32 v6, 0x33330003 +v_mov_b32_e32 v7, 0x44440004 +ds_write2_b64 v2, v[4:5], v[6:7] offset0:1 offset1:3 +s_waitcnt lgkmcnt(0) +ds_read2_b64 v[10:13], v2 offset0:1 offset1:3 +s_waitcnt lgkmcnt(0) +v_mov_b32_e32 v21, 0 +buffer_store_dword v10, v21, s[0:3], 0 offen +v_mov_b32_e32 v21, 4 +buffer_store_dword v11, v21, s[0:3], 0 offen +v_mov_b32_e32 v21, 8 +buffer_store_dword v12, v21, s[0:3], 0 offen +v_mov_b32_e32 v21, 12 +buffer_store_dword v13, v21, s[0:3], 0 offen + +; --- ds_read2st64_b64, unit 512 bytes: seed 0x100 and 0x300 --- +v_mov_b32_e32 v1, 0x100 +v_mov_b32_e32 v3, 0x55550005 +ds_write_b32 v1, v3 +v_mov_b32_e32 v1, 0x104 +v_mov_b32_e32 v3, 0x66660006 +ds_write_b32 v1, v3 +v_mov_b32_e32 v1, 0x300 +v_mov_b32_e32 v3, 0x77770007 +ds_write_b32 v1, v3 +v_mov_b32_e32 v1, 0x304 +v_mov_b32_e32 v3, 0x88880008 +ds_write_b32 v1, v3 +s_waitcnt lgkmcnt(0) +v_mov_b32_e32 v2, 0x100 +ds_read2st64_b64 v[10:13], v2 offset0:0 offset1:1 +s_waitcnt lgkmcnt(0) +v_xor_b32_e32 v14, v10, v11 +v_xor_b32_e32 v14, v14, v12 +v_xor_b32_e32 v14, v14, v13 +v_mov_b32_e32 v21, 16 +buffer_store_dword v14, v21, s[0:3], 0 offen + +; --- ds_write2st64_b64, unit 512 bytes: A at 0x100, B at 0x300 --- +v_mov_b32_e32 v2, 0x100 +ds_write2st64_b64 v2, v[4:5], v[6:7] offset0:0 offset1:1 +s_waitcnt lgkmcnt(0) +v_mov_b32_e32 v1, 0x100 +ds_read_b32 v10, v1 +v_mov_b32_e32 v1, 0x104 +ds_read_b32 v11, v1 +v_mov_b32_e32 v1, 0x300 +ds_read_b32 v12, v1 +v_mov_b32_e32 v1, 0x304 +ds_read_b32 v13, v1 +s_waitcnt lgkmcnt(0) +v_xor_b32_e32 v15, v10, v11 +v_xor_b32_e32 v15, v15, v12 +v_xor_b32_e32 v15, v15, v13 +v_mov_b32_e32 v21, 20 +buffer_store_dword v15, v21, s[0:3], 0 offen + +; --- ds_read2_b64 with vdst overlapping vaddr: v[2:5] <- base v2 --- +v_mov_b32_e32 v1, 0x200 +v_mov_b32_e32 v3, 0x99990009 +ds_write_b32 v1, v3 +v_mov_b32_e32 v1, 0x204 +v_mov_b32_e32 v3, 0xAAAA000A +ds_write_b32 v1, v3 +v_mov_b32_e32 v1, 0x208 +v_mov_b32_e32 v3, 0xBBBB000B +ds_write_b32 v1, v3 +v_mov_b32_e32 v1, 0x20C +v_mov_b32_e32 v3, 0xCCCC000C +ds_write_b32 v1, v3 +s_waitcnt lgkmcnt(0) +v_mov_b32_e32 v2, 0x200 +ds_read2_b64 v[2:5], v2 offset0:0 offset1:1 +s_waitcnt lgkmcnt(0) +v_mov_b32_e32 v21, 24 +buffer_store_dword v4, v21, s[0:3], 0 offen + +; --- ds_cmpst_b32: hit at 0x400, miss at 0x404 --- +v_mov_b32_e32 v1, 0x400 +v_mov_b32_e32 v3, 0x13572468 +ds_write_b32 v1, v3 +v_mov_b32_e32 v1, 0x404 +v_mov_b32_e32 v3, 0x11111111 +ds_write_b32 v1, v3 +s_waitcnt lgkmcnt(0) +v_mov_b32_e32 v1, 0x400 +v_mov_b32_e32 v3, 0x13572468 +v_mov_b32_e32 v4, 0x2468ABCD +ds_cmpst_b32 v1, v3, v4 +s_waitcnt lgkmcnt(0) +ds_read_b32 v10, v1 +v_mov_b32_e32 v1, 0x404 +v_mov_b32_e32 v3, 0 +v_mov_b32_e32 v4, 0xFFFFFFFF +ds_cmpst_b32 v1, v3, v4 +s_waitcnt lgkmcnt(0) +ds_read_b32 v11, v1 +v_xor_b32_e32 v16, v10, v11 +v_mov_b32_e32 v21, 28 +buffer_store_dword v16, v21, s[0:3], 0 offen +s_endpgm diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 7209c364c3..342a2dc50a 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -879,7 +879,7 @@ def run_suite(a, work: str) -> int: "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load", "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent", "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w32_partial_scmp", "cs_barrier_early_end", - "cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64"): + "cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64", "cs_lds_b64_cmpst"): cs_dump_wants = { "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000], # base + soffset + imm (cs_smem_soffset_imm.asm); out[4..7] are seeds the shader leaves alone @@ -901,6 +901,9 @@ def run_suite(a, work: str) -> int: "cs_w32_salu64": [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE], # SHADER-85: ds_read_u8/i8_d16[_hi] (cs_w32_lds_u8_d16.asm header) "cs_w32_lds_u8_d16": [0xBEEF00FF, 0x00FF1234, 0xBEEFFF80, 0xFF801234, 0xBEEF007F, 0x007F1234, 0xBEEF0080, 0xFFFF1234], + # ds_cmpst_b32 and the b64 2-address forms (cs_lds_b64_cmpst.asm header) + "cs_lds_b64_cmpst": [0x11110001, 0x22220002, 0x33330003, 0x44440004, + 0xCCCC000C, 0x44440004, 0xBBBB000B, 0x3579BADC], # constant EXEC masks (cs_exec_const.asm): each lane takes its own bit of the constant "cs_exec_const": [16, 8, 2, 16, 0, 16], # constant lane masks: lane L takes bit L (cs_w32_mask_imm.asm / cs_w64_mask_imm.asm headers) @@ -969,7 +972,8 @@ def run_suite(a, work: str) -> int: "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_sincos", - "cs_exec_const", "cs_w32_mask_imm", "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", + "cs_lds_b64_cmpst", "cs_exec_const", "cs_w32_mask_imm", + "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi") and not emulated and not partial if partial and not emulated: cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64") @@ -981,7 +985,8 @@ def run_suite(a, work: str) -> int: ok, detail = None, str(skip) else: ok, detail = judge_cs_dump(rc, msg, want, wave64=wave64, partial=partial, emulated=emulated, - hexwords=name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_lds_u8_d16")) + hexwords=name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_lds_u8_d16", + "cs_lds_b64_cmpst")) results.append((name, ok, detail)) elif name == "cs_imgstore": rc, msg = run_cmd([vk_store, spv]) From b6313dc645bff17d31becc7a799e0105b5f203cf Mon Sep 17 00:00:00 2001 From: Tayar <358041433+lucastayaralvarenga-ui@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:24:35 -0300 Subject: [PATCH 030/115] awc_names: protect conversation inputs from report output --- tests/test_awc_names.py | 15 +++++++++++++++ tools/awc_names.py | 5 +++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/tests/test_awc_names.py b/tests/test_awc_names.py index b73cacc860..766cdd12de 100644 --- a/tests/test_awc_names.py +++ b/tests/test_awc_names.py @@ -188,6 +188,21 @@ def test_end_to_end(self): with open(json_out, encoding="utf-8") as fh: self.assertEqual(json.load(fh)["summary"]["banks"]["streams"], 3) + def test_rejects_output_aliasing_conversation(self): + with tempfile.TemporaryDirectory() as tmp: + bank = write(os.path.join(tmp, "one.awc"), make_bank(["zz_rootau_abcd_01"])) + original = b"ZZ_ROOTAU_ABCD\x00ZZ_A\x00" + conv = write(os.path.join(tmp, "c.pso"), original) + alias = os.path.join(tmp, ".", "c.pso") + err = io.StringIO() + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): + with self.assertRaises(SystemExit) as cm: + A.main([bank, "--conversations", conv, "--out", alias]) + self.assertEqual(cm.exception.code, 2) + self.assertIn("--out must not overwrite an input", err.getvalue()) + with open(conv, "rb") as f: + self.assertEqual(f.read(), original) + def test_hashdict_json_words(self): with tempfile.TemporaryDirectory() as tmp: path = write(os.path.join(tmp, "hashes.json"), json.dumps({"0000abcd": "Some_Word"})) diff --git a/tools/awc_names.py b/tools/awc_names.py index ae8b345fe1..dc7a1bacc8 100644 --- a/tools/awc_names.py +++ b/tools/awc_names.py @@ -281,11 +281,12 @@ def main(argv=None) -> int: a = ap.parse_args(argv) if not a.words and not a.conversations: ap.error("give at least one --words or --conversations source") - for path in a.banks + a.words + a.conversations: + inputs = a.banks + a.words + a.conversations + for path in inputs: if not os.path.exists(path): print(f"awc_names: error: {path}: no such file or directory", file=sys.stderr) return 2 - if a.out and any(os.path.exists(a.out) and os.path.samefile(p, a.out) for p in a.banks + a.words): + if a.out and os.path.exists(a.out) and any(os.path.samefile(p, a.out) for p in inputs): ap.error("--out must not overwrite an input") words = [] From 9aa1f816d5e03f859d2de0002c98b8644b89775c Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Sun, 22 Nov 2026 11:17:07 -0300 Subject: [PATCH 031/115] tests/semantic: the interpreters reject an OpPhi that isn't first in its block spirv-val requires OpPhi to be the first instructions of a block (only OpLabel or OpPhi before it). The translator merges every guarded load with an OpPhi, so an instruction emitted before it in the merge block would pass the semantic tests and fail every driver, as #1633's merge ordering did. check_structure and spirv_wave_interp now raise InvalidModule for it. All 22,993 modules the semantic suite translates already follow the rule. test_interp_merge_check.py: a translated global_load with its phi moved after another instruction, and the rule on hand-made blocks. --- tests/semantic/spirv_mini_interp.py | 11 +++++- tests/semantic/spirv_wave_interp.py | 3 ++ tests/semantic/test_interp_merge_check.py | 46 ++++++++++++++++++++++- 3 files changed, 58 insertions(+), 2 deletions(-) diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py index b288e42f7f..a344540e46 100644 --- a/tests/semantic/spirv_mini_interp.py +++ b/tests/semantic/spirv_mini_interp.py @@ -43,13 +43,22 @@ class InvalidModule(AssertionError): def check_structure(body): - """spirv-val's merge rule (SPIR-V 2.16.2): OpSelectionMerge must be the second-to-last instruction of its block, + """spirv-val's merge and phi rules (SPIR-V 2.16.2): OpSelectionMerge must be the second-to-last instruction of its block, directly before OpBranchConditional or OpSwitch, and OpLoopMerge directly before OpBranch or OpBranchConditional. Until 2026-11-22 the interpreter skipped merges, so a translator change that put an instruction between a merge and its branch (#1633: OpLoad %active) passed every semantic test while every driver rejected the module. `body` is the list of (result, opcode, operands, line) of a function.""" follow = {"OpSelectionMerge": ("OpBranchConditional", "OpSwitch"), "OpLoopMerge": ("OpBranch", "OpBranchConditional")} + # OpPhi must come first in its block: only OpLabel or other OpPhi before it (SPIR-V 2.16.2, "OpPhi ... must be + # the first instructions of a block"). A phi emitted after an instruction of the merge block is rejected by + # spirv-val, and every translator path that merges a guarded load (OpPhi of the loaded and the kept value) + # depends on the order. + prev = None + for _, op, _, line in body: + if op == "OpPhi" and prev not in ("OpLabel", "OpPhi"): + raise InvalidModule(f"{line!r} follows {prev or 'the start of the function'}, not OpLabel or OpPhi") + prev = op for k, (_, op, _, line) in enumerate(body): if op in follow: nxt = body[k + 1][1] if k + 1 < len(body) else None diff --git a/tests/semantic/spirv_wave_interp.py b/tests/semantic/spirv_wave_interp.py index a3adf65442..bd776b2925 100644 --- a/tests/semantic/spirv_wave_interp.py +++ b/tests/semantic/spirv_wave_interp.py @@ -161,6 +161,9 @@ def __init__(self, text): if res and a and op != "OpStore": self.id_type[res] = a[0] if op == "OpPhi": + if cur.body: + raise InvalidModule(f"{line!r} follows a non-phi instruction of its block (spirv-val: " + "OpPhi must come first)") cur.phis.append((res, a)) elif op in ("OpSelectionMerge", "OpLoopMerge"): cur.merge = (op, a[0], a[1] if op == "OpLoopMerge" else None) diff --git a/tests/semantic/test_interp_merge_check.py b/tests/semantic/test_interp_merge_check.py index 382955f5fa..dec7167e31 100644 --- a/tests/semantic/test_interp_merge_check.py +++ b/tests/semantic/test_interp_merge_check.py @@ -1,4 +1,4 @@ -"""spirv_mini_interp and spirv_wave_interp reject a module that breaks spirv-val's merge rule. +"""spirv_mini_interp and spirv_wave_interp reject a module that breaks spirv-val's merge or phi rule. OpSelectionMerge must directly precede OpBranchConditional / OpSwitch, and OpLoopMerge directly precede OpBranch / OpBranchConditional (SPIR-V 2.16.2). Both interpreters used to skip merges, so #1633's first version, with an @@ -74,5 +74,49 @@ def test_loop_merge_rule(self): si.check_structure([ok[0]]) +CS_LINES = ["v_mov_b32_e32 v1, 0x40", "global_load_dword v2, v1, s[0:1]", "s_waitcnt vmcnt(0)", + "v_mov_b32_e32 v3, 0", "buffer_store_dword v2, v3, s[0:3], 0 offen", "s_endpgm"] + + +def cs_spv(): + from test_salu64_bitwise_data import translate_cs + text = translate_cs(CS_LINES) + assert " = OpPhi " in text + return text + + +def run_cs(text): + mem = {0x40: 0x1234} + si.run_workgroup(text, 1, 64, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, + push_constants=[0, 0, 0x1000, 0x31016FAC] + [0] * 32, memory=mem) + return mem + + +class PhiRule(unittest.TestCase): + """OpPhi must be the first instructions of its block: only OpLabel or OpPhi before it (SPIR-V 2.16.2).""" + + def test_translated_module_runs(self): + self.assertEqual(run_cs(cs_spv())[0], 0x1234) + + def test_phi_after_another_instruction(self): + lines = cs_spv().splitlines() + k = next(i for i, ln in enumerate(lines) if " = OpPhi " in ln) + lines[k], lines[k + 1] = lines[k + 1], lines[k] # the phi now follows a non-phi instruction + bad = "\n".join(lines) + "\n" + with self.assertRaisesRegex(si.InvalidModule, "OpPhi"): + run_cs(bad) + + def test_rule_directly(self): + lab = (None, "OpLabel", [], "%b = OpLabel") + phi = ("%p", "OpPhi", [], "%p = OpPhi %uint %a %x %c %y") + add = ("%q", "OpIAdd", [], "%q = OpIAdd %uint %a %a") + si.check_structure([lab, phi, phi, add]) + with self.assertRaisesRegex(si.InvalidModule, "OpPhi"): + si.check_structure([lab, add, phi]) + with self.assertRaisesRegex(wi.InvalidModule, "OpPhi"): + wi.run_wave("OpFunction %void None %f\n%b = OpLabel\n%q = OpIAdd %uint %a %a\n" + "%p = OpPhi %uint %a %x %c %y\nOpReturn\nOpFunctionEnd\n", wave=32) + + if __name__ == "__main__": unittest.main() From f9ca6192a84c4c3b8e38d55c2695660970aaeec9 Mon Sep 17 00:00:00 2001 From: Luiz Neves Date: Sun, 22 Nov 2026 11:21:31 -0300 Subject: [PATCH 032/115] tests/semantic: the interpreters reject a Function variable outside the first block spirv-val requires Function-storage OpVariable in a function's first block. check_structure (per function) and spirv_wave_interp now raise InvalidModule for one elsewhere. All 23,003 modules the semantic suite translates already follow the rule. --- tests/semantic/spirv_mini_interp.py | 13 ++++++++--- tests/semantic/spirv_wave_interp.py | 2 ++ tests/semantic/test_interp_merge_check.py | 27 +++++++++++++++++++++++ 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py index a344540e46..eb6ecea99a 100644 --- a/tests/semantic/spirv_mini_interp.py +++ b/tests/semantic/spirv_mini_interp.py @@ -43,7 +43,7 @@ class InvalidModule(AssertionError): def check_structure(body): - """spirv-val's merge and phi rules (SPIR-V 2.16.2): OpSelectionMerge must be the second-to-last instruction of its block, + """spirv-val's merge, phi and Function-variable rules (SPIR-V 2.16.1-2): OpSelectionMerge must be the second-to-last instruction of its block, directly before OpBranchConditional or OpSwitch, and OpLoopMerge directly before OpBranch or OpBranchConditional. Until 2026-11-22 the interpreter skipped merges, so a translator change that put an instruction between a merge and its branch (#1633: OpLoad %active) passed every semantic test while every @@ -54,10 +54,17 @@ def check_structure(body): # the first instructions of a block"). A phi emitted after an instruction of the merge block is rejected by # spirv-val, and every translator path that merges a guarded load (OpPhi of the loaded and the kept value) # depends on the order. - prev = None - for _, op, _, line in body: + # Function-storage OpVariable belongs in the function's first block (SPIR-V 2.16.1). + prev, blocks = None, 0 + for _, op, a, line in body: if op == "OpPhi" and prev not in ("OpLabel", "OpPhi"): raise InvalidModule(f"{line!r} follows {prev or 'the start of the function'}, not OpLabel or OpPhi") + if op == "OpFunction": + blocks = 0 + elif op == "OpLabel": + blocks += 1 + elif op == "OpVariable" and a[1:2] == ["Function"] and blocks > 1: + raise InvalidModule(f"{line!r} is a Function variable outside the function's first block") prev = op for k, (_, op, _, line) in enumerate(body): if op in follow: diff --git a/tests/semantic/spirv_wave_interp.py b/tests/semantic/spirv_wave_interp.py index bd776b2925..0331c7b37a 100644 --- a/tests/semantic/spirv_wave_interp.py +++ b/tests/semantic/spirv_wave_interp.py @@ -160,6 +160,8 @@ def __init__(self, text): raise UnsupportedConstruct(f"{op} before the first label") if res and a and op != "OpStore": self.id_type[res] = a[0] + if op == "OpVariable" and a[1:2] == ["Function"] and len(self.blocks) > 1: + raise InvalidModule(f"{line!r} is a Function variable outside the function's first block") if op == "OpPhi": if cur.body: raise InvalidModule(f"{line!r} follows a non-phi instruction of its block (spirv-val: " diff --git a/tests/semantic/test_interp_merge_check.py b/tests/semantic/test_interp_merge_check.py index dec7167e31..22156da603 100644 --- a/tests/semantic/test_interp_merge_check.py +++ b/tests/semantic/test_interp_merge_check.py @@ -118,5 +118,32 @@ def test_rule_directly(self): "%p = OpPhi %uint %a %x %c %y\nOpReturn\nOpFunctionEnd\n", wave=32) +class FunctionVariableRule(unittest.TestCase): + """A Function-storage OpVariable belongs in the function's first block (SPIR-V 2.16.1).""" + + def test_rule_directly(self): + lab = (None, "OpLabel", [], "%b = OpLabel") + var = ("%v", "OpVariable", ["%_ptr_Function_uint", "Function"], "%v = OpVariable %_ptr_Function_uint Function") + br = (None, "OpBranch", ["%c"], "OpBranch %c") + si.check_structure([lab, var, br, lab]) + with self.assertRaisesRegex(si.InvalidModule, "first block"): + si.check_structure([lab, br, lab, var]) + # a new function starts counting again + fn = ("%f", "OpFunction", [], "%f = OpFunction %void None %t") + si.check_structure([fn, lab, br, lab, fn, lab, var]) + + def test_translated_module_with_a_variable_moved(self): + lines = cs_spv().splitlines() + k = next(i for i, ln in enumerate(lines) if " OpVariable " in ln and " Function" in ln) + var = lines.pop(k) + last_label = max(i for i, ln in enumerate(lines) if ln.strip().endswith("= OpLabel")) + lines.insert(last_label + 1, var) + bad = "\n".join(lines) + "\n" + with self.assertRaisesRegex(si.InvalidModule, "first block"): + run_cs(bad) + with self.assertRaisesRegex(wi.InvalidModule, "first block"): + wi.run_wave(bad, wave=32) + + if __name__ == "__main__": unittest.main() From 2e425c170820f1aade994a013ea229c1c28f7918 Mon Sep 17 00:00:00 2001 From: Tayar <358041433+lucastayaralvarenga-ui@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:24:43 -0300 Subject: [PATCH 033/115] psin_names: protect source files from the refs writer --- tests/test_psin_names.py | 18 ++++++++++++++++++ tools/psin_names.py | 5 ++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/tests/test_psin_names.py b/tests/test_psin_names.py index d4f0d50ed5..7502db7b0c 100644 --- a/tests/test_psin_names.py +++ b/tests/test_psin_names.py @@ -137,6 +137,24 @@ def test_text_json_and_refs(self): self.assertEqual(r.returncode, 0, r.stderr) self.assertEqual(json.loads(r.stdout)["summary"]["u64 resolved"], 1) + def test_rejects_refs_aliasing_inputs(self): + with tempfile.TemporaryDirectory() as tmp: + source = os.path.join(tmp, "one.bin") + names = os.path.join(tmp, "names.txt") + for path, data in ((source, sample()), (names, b"prop_crate_01\n")): + with open(path, "wb") as f: + f.write(data) + for destination in (source, names): + with self.subTest(destination=destination): + with open(destination, "rb") as f: + original = f.read() + alias = os.path.join(tmp, ".", os.path.basename(destination)) + result = self.run_tool(source, "--names", names, "--refs", alias) + self.assertEqual(result.returncode, 2, result.stderr) + self.assertIn("--refs must not overwrite an input", result.stderr) + with open(destination, "rb") as f: + self.assertEqual(f.read(), original) + def test_missing_names_file_is_one_line(self): with tempfile.TemporaryDirectory() as d: r = self.run_tool(d, "--names", os.path.join(d, "none.txt")) diff --git a/tools/psin_names.py b/tools/psin_names.py index 0c9b7281ed..c2348b429e 100644 --- a/tools/psin_names.py +++ b/tools/psin_names.py @@ -188,11 +188,14 @@ def main(): ap.add_argument("--refs", help="write every resolved value as TSV (local only: it holds game names)") ap.add_argument("--limit", type=psin_index.count, help="stop after this many PSIN files") a = ap.parse_args() - for path in [a.src] + a.names: + inputs = [a.src, *a.names] + for path in inputs: if not os.path.exists(path): print(f"ERROR: {path}: no such file or folder", file=sys.stderr) return 2 try: + if a.refs and os.path.exists(a.refs) and any(os.path.samefile(path, a.refs) for path in inputs): + ap.error("--refs must not overwrite an input") names = load_names(a.names) if a.refs: with open(a.refs, "w", encoding="utf-8") as refs: From 55bbe857c738a8f0f5d0a85944247e5e7bf36ec3 Mon Sep 17 00:00:00 2001 From: Kam471 <115741199+Kam471@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:46:18 +0000 Subject: [PATCH 034/115] docs: attribute the 26,503 shader result to dcd8ecf, not the 26,501 run --- README.md | 2 +- docs/shader_validation.md | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index b0430195a6..a487c847f0 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ work on booting can start as soon as one is available to a developer. | Booting, story mode, anything playable | ❌ No | | Finding and checking your copy (Xbox Series 1.0.2.1) | ✅ Works | | Shaders: carve, unpack native RDNA2 code, disassemble | ✅ All 26,503 | -| Shaders: RDNA2 → SPIR-V translation | ✅ **All 26,503 translated**: 2,236 VS, 12,101 PS, 2,689 CS, 9,282 mesh, 195 geometry, with a per-shader metadata index for pipeline creation. All 26,503 passed `spirv-val` in the [LLVM 23.1.5 Linux run at `c432cdc`](https://github.com/ItsNotRexed/Leonida/issues/644#issuecomment-7072972586). A [full-corpus run at `43d4703`](https://github.com/ItsNotRexed/Leonida/issues/881#issuecomment-7075507328) also validated all 26,503 after the SPIR-V ID-bound fix. ⚠️ 21,545 are wave64: exact on 64-wide subgroups (AMD). On 32-wide subgroups (NVIDIA, Intel), compute and mesh shaders are exact with wave64 emulation (`--wave64-emulate`, on by default there); cross-half wave ops in vertex, pixel and geometry shaders are still approximate | +| Shaders: RDNA2 → SPIR-V translation | ✅ **All 26,503 translated**: 2,236 VS, 12,101 PS, 2,689 CS, 9,282 mesh, 195 geometry, with a per-shader metadata index for pipeline creation. All 26,503 passed `spirv-val` in the [LLVM 23.1.5 Linux run at `c432cdc`](https://github.com/ItsNotRexed/Leonida/issues/644#issuecomment-7072972586). A [full-corpus run at `43d4703`](https://github.com/ItsNotRexed/Leonida/issues/881#issuecomment-7075507328) also validated all 26,503 after `dcd8ecf` fixed the SPIR-V ID bound; the intervening `dedd75c` run was 26,501. ⚠️ 21,545 are wave64: exact on 64-wide subgroups (AMD). On 32-wide subgroups (NVIDIA, Intel), compute and mesh shaders are exact with wave64 emulation (`--wave64-emulate`, on by default there); cross-half wave ops in vertex, pixel and geometry shaders are still approximate | | Shader translator checked on a real GPU | ⚠️ The hand-written GPU tests (vertex fetch, texture sampling, exports, ALU ops, partial-register ops, barycentrics, wave-uniform branches, compute LDS/barriers/buffer stores, wave64 masks) have been run on more than 30 GPU and driver combinations, with results in [#166](https://github.com/ItsNotRexed/Leonida/issues/166): NVIDIA Turing, Ampere, Ada and Blackwell (Windows and Linux); AMD GCN3, RDNA1, RDNA2, RDNA3 and RDNA4 (Windows driver and RADV); Intel Gen9 (ANV); Apple M1 (MoltenVK, no geometry or mesh stages); and Mesa llvmpipe. Wave64 tests need 64-wide subgroups (AMD) or `LEONIDA_W64_EMULATE=1`. These are small test shaders: the game's own shaders are checked by `spirv-val` and by driver pipeline creation (`vk_pipeline_check`), not by their output | | Models (OBJ with real names, UVs, material references) | ✅ Exported. Not all layouts are decoded yet | | Texture dictionaries and world texture pools (DDS) | ✅ Exported. Pool entries stored as BCPack are still skipped by the export; a clean-room decoder (`tools/bcpack.py`) rebuilds BC1, BC3, BC4, BC5, BC6H and BC7 (most BC6H/BC7 chunks need a local history table, which the repo does not ship), and is not wired into `rpf9dump` yet ([notes](docs/textures.md)) | diff --git a/docs/shader_validation.md b/docs/shader_validation.md index fc7b3d5ac2..4e28edb4e9 100644 --- a/docs/shader_validation.md +++ b/docs/shader_validation.md @@ -13,9 +13,11 @@ harness itself). The GPU-side runners are described below: `tools/valu_fuzz.py` check that the module computes what the RDNA2 program computes. Those are different questions, and this repository already has cases where only the second question had a useful answer: -- All 26,503 shaders translate and pass `spirv-val` (Vulkan 1.2), yet the SDWA source/destination - selects were silently ignored until 2026-11-20. That passed validation for 3,826 of the 13,926 - translated shaders and produced wrong values (`docs/design.md`, "SDWA"). +- All 26,503 shaders translate and pass `spirv-val` (Vulkan 1.2) at `43d4703`, after `dcd8ecf` fixed + the ID-bound regression (#881); the intervening `dedd75c` run was 26,501, and `793b06f` before + #223's LLVM 23 source-field fix was 25,032. Yet the SDWA source/destination selects were silently + ignored until 2026-11-20: validation passed for 3,826 of the 13,926 shaders translated at the time + and produced wrong values (`docs/design.md`, "SDWA"). - The compressed-export bug was found by a GPU test, not by validation: LLVM prints `v4, v4, v5, v5` for a compressed pair, and the translated shader exported `(r, g, r, g)`. - `v_cvt_pkrtz_f16_f32` with round-to-nearest overflowed a finite value to infinity; the GPU smoke From a108d8beb3f7550572a8da6dfcf6c3129b0c1b93 Mon Sep 17 00:00:00 2001 From: Kam471 <115741199+Kam471@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:24:38 +0000 Subject: [PATCH 035/115] docs: keep the SDWA bullet on its contrast; the 793b06f cause is unsettled --- docs/shader_validation.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/docs/shader_validation.md b/docs/shader_validation.md index 4e28edb4e9..fc7b3d5ac2 100644 --- a/docs/shader_validation.md +++ b/docs/shader_validation.md @@ -13,11 +13,9 @@ harness itself). The GPU-side runners are described below: `tools/valu_fuzz.py` check that the module computes what the RDNA2 program computes. Those are different questions, and this repository already has cases where only the second question had a useful answer: -- All 26,503 shaders translate and pass `spirv-val` (Vulkan 1.2) at `43d4703`, after `dcd8ecf` fixed - the ID-bound regression (#881); the intervening `dedd75c` run was 26,501, and `793b06f` before - #223's LLVM 23 source-field fix was 25,032. Yet the SDWA source/destination selects were silently - ignored until 2026-11-20: validation passed for 3,826 of the 13,926 shaders translated at the time - and produced wrong values (`docs/design.md`, "SDWA"). +- All 26,503 shaders translate and pass `spirv-val` (Vulkan 1.2), yet the SDWA source/destination + selects were silently ignored until 2026-11-20. That passed validation for 3,826 of the 13,926 + translated shaders and produced wrong values (`docs/design.md`, "SDWA"). - The compressed-export bug was found by a GPU test, not by validation: LLVM prints `v4, v4, v5, v5` for a compressed pair, and the translated shader exported `(r, g, r, g)`. - `v_cvt_pkrtz_f16_f32` with round-to-nearest overflowed a finite value to infinity; the GPU smoke From 85f6c01bb79f985bdc45daa8212a3b5576280f0d Mon Sep 17 00:00:00 2001 From: Tayar <358041433+lucastayaralvarenga-ui@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:24:51 -0300 Subject: [PATCH 036/115] save_keys: reject negative compose counts --- tests/test_save_keys.py | 10 ++++++++++ tools/save_keys.py | 2 ++ 2 files changed, 12 insertions(+) diff --git a/tests/test_save_keys.py b/tests/test_save_keys.py index d50996fe98..aa015c8a28 100644 --- a/tests/test_save_keys.py +++ b/tests/test_save_keys.py @@ -48,6 +48,16 @@ def test_incremental_matches_whole(self): class Resolve(unittest.TestCase): + def test_rejects_negative_compose_count(self): + with tempfile.TemporaryDirectory() as tmp: + tool = os.path.join(ROOT, "tools", "save_keys.py") + result = subprocess.run( + [sys.executable, "-I", tool, "resolve", tmp, "--dict", tmp, "--compose", "-1"], + capture_output=True, text=True, + ) + self.assertEqual(result.returncode, 2, result.stderr) + self.assertIn("--compose must be 0 or more", result.stderr) + def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.dir = self.tmp.name diff --git a/tools/save_keys.py b/tools/save_keys.py index a5280b9cc6..4d090642f3 100644 --- a/tools/save_keys.py +++ b/tools/save_keys.py @@ -337,6 +337,8 @@ def main(argv=None): r.add_argument("--compose", type=int, default=0, metavar="N") r.add_argument("--out") a = ap.parse_args(argv) + if a.cmd == "resolve" and a.compose < 0: + r.error("--compose must be 0 or more") return {"collect": cmd_collect, "resolve": cmd_resolve}[a.cmd](a) or 0 From d665490a68851872b39d20f8a02a1e1cbdc48007 Mon Sep 17 00:00:00 2001 From: Alex Arenas <106154424+al3xar@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:25:02 +0100 Subject: [PATCH 037/115] runtime: check SeIncreaseBasePriorityPrivilege for global realtime queues (D3D-236) --- runtime/shims/d3d12_com.h | 6 +++ runtime/shims/d3d12_vulkan_device.cpp | 34 ++++++++++++- runtime/test/d3d12_vulkan_device_test.cpp | 62 +++++++++++++++++++++++ 3 files changed, 100 insertions(+), 2 deletions(-) diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 2e1f2d3c54..b3b397be08 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -273,6 +273,12 @@ inline constexpr UINT descriptor_size = 32; // ExecuteCommandLists returns void; this is what the last call on the queue did. leonida::ReplayResult last_execute_result(ID3D12CommandQueue* queue); +// True when the current thread or process token has SeIncreaseBasePriorityPrivilege enabled (or the test override +// forces it), which D3D12 requires for D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME. +bool has_global_realtime_privilege(); +// Test override for has_global_realtime_privilege(): -1 queries the token (default), 0 forces denied, 1 forces granted. +void set_global_realtime_privilege_override_for_test(int state); + // The front/back stencil references last recorded by ID3D12GraphicsCommandList8::OMSetFrontAndBackStencilRef on // `list`. The values are kept for the future pipeline path, which is what would apply them. False when `list` is // not one of this module's command lists. diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 8d0cd21e47..96f2118b50 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -23,6 +23,9 @@ #include "../src/vulkan_device_filter.h" #include +#ifdef _MSC_VER +#pragma comment(lib, "advapi32.lib") +#endif #include @@ -59,6 +62,8 @@ static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); constexpr D3D_SHADER_MODEL kHighestShaderModel = D3D_SHADER_MODEL_6_0; constexpr D3D_ROOT_SIGNATURE_VERSION kHighestRootSignatureVersion = D3D_ROOT_SIGNATURE_VERSION_1_1; +std::atomic g_global_realtime_privilege_override{-1}; + void log_once(const char* what, int value) { static std::mutex mutex; static std::set> seen; @@ -3360,8 +3365,8 @@ class Device final log_once("CreateCommandQueue refused (type, priority, flags or node mask), type", desc->Type); return d3d12_trace::result(method, E_INVALIDARG); } - // Global realtime priority needs a privilege the host grants only on request; without it, this answer. - if (desc->Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME) { + // Global realtime priority needs SeIncreaseBasePriorityPrivilege enabled in the token; without it, this answer. + if (desc->Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME && !has_global_realtime_privilege()) { log_once("CreateCommandQueue refused (global realtime priority), type", desc->Type); return d3d12_trace::result(method, DXGI_ERROR_ACCESS_DENIED); } @@ -6177,4 +6182,29 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) { return hand_out(device, riid, out); } +bool has_global_realtime_privilege() { + const int override_state = g_global_realtime_privilege_override.load(std::memory_order_relaxed); + if (override_state >= 0) return override_state != 0; + HANDLE token = nullptr; + if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token) && + !OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) + return false; + LUID luid{}; + BOOL enabled = FALSE; + if (LookupPrivilegeValueW(nullptr, L"SeIncreaseBasePriorityPrivilege", &luid)) { + PRIVILEGE_SET set{}; + set.PrivilegeCount = 1; + set.Control = PRIVILEGE_SET_ALL_NECESSARY; + set.Privilege[0].Luid = luid; + set.Privilege[0].Attributes = SE_PRIVILEGE_ENABLED; + if (!PrivilegeCheck(token, &set, &enabled)) enabled = FALSE; + } + CloseHandle(token); + return enabled != FALSE; +} + +void set_global_realtime_privilege_override_for_test(int state) { + g_global_realtime_privilege_override.store(state, std::memory_order_relaxed); +} + } // namespace rt::d3d12 diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp index 556ab15666..ad222ad278 100644 --- a/runtime/test/d3d12_vulkan_device_test.cpp +++ b/runtime/test/d3d12_vulkan_device_test.cpp @@ -3422,6 +3422,68 @@ int main() { std::printf("invalid arguments: no host D3D12 device to compare with, skipped\n"); EXPECT(argument_mismatches <= 0); + // D3D-236: CreateCommandQueue with D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME requires + // SeIncreaseBasePriorityPrivilege enabled in the token, matching the Windows D3D12 runtime. + { + const D3D12_COMMAND_QUEUE_DESC rt_desc{ + D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME, + D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; + struct RestoreOverride { + ~RestoreOverride() { rt::d3d12::set_global_realtime_privilege_override_for_test(-1); } + } restore_override; + + rt::d3d12::set_global_realtime_privilege_override_for_test(0); + EXPECT(!rt::d3d12::has_global_realtime_privilege()); + Ref denied_q; + EXPECT(device->CreateCommandQueue(&rt_desc, IID_PPV_ARGS(&denied_q.p)) == DXGI_ERROR_ACCESS_DENIED); + EXPECT(!denied_q.p); + EXPECT(device->CreateCommandQueue(&rt_desc, __uuidof(ID3D12CommandQueue), nullptr) == + DXGI_ERROR_ACCESS_DENIED); + + rt::d3d12::set_global_realtime_privilege_override_for_test(1); + EXPECT(rt::d3d12::has_global_realtime_privilege()); + EXPECT(device->CreateCommandQueue(&rt_desc, __uuidof(ID3D12CommandQueue), nullptr) == E_UNEXPECTED); + Ref granted_q; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&rt_desc, IID_PPV_ARGS(&granted_q.p))) && granted_q.p); + if (granted_q.p) { + EXPECT(granted_q->GetDesc().Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME); + } + granted_q.reset(); + rt::d3d12::set_global_realtime_privilege_override_for_test(-1); + + // When the process token holds SeIncreaseBasePriorityPrivilege (e.g. an elevated session), toggle the + // real token privilege and verify both states against the host D3D12 runtime. + HANDLE token = nullptr; + LUID luid{}; + if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token)) { + if (LookupPrivilegeValueW(nullptr, L"SeIncreaseBasePriorityPrivilege", &luid)) { + TOKEN_PRIVILEGES tp{}, prev{}; + DWORD prev_len = 0; + tp.PrivilegeCount = 1; + tp.Privileges[0].Luid = luid; + tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; + if (AdjustTokenPrivileges(token, FALSE, &tp, sizeof(prev), &prev, &prev_len) && + GetLastError() == ERROR_SUCCESS) { + EXPECT(rt::d3d12::has_global_realtime_privilege()); + EXPECT(command_queue(device.p, rt_desc) == S_OK); + Ref host; + if (create_host_device(host)) { + EXPECT(command_queue(host.p, rt_desc) == S_OK); + } + tp.Privileges[0].Attributes = 0; + if (AdjustTokenPrivileges(token, FALSE, &tp, 0, nullptr, nullptr) && + GetLastError() == ERROR_SUCCESS) { + EXPECT(!rt::d3d12::has_global_realtime_privilege()); + EXPECT(command_queue(device.p, rt_desc) == DXGI_ERROR_ACCESS_DENIED); + if (host.p) EXPECT(command_queue(host.p, rt_desc) == DXGI_ERROR_ACCESS_DENIED); + } + AdjustTokenPrivileges(token, FALSE, &prev, 0, nullptr, nullptr); + } + } + CloseHandle(token); + } + } + const int depth_quality_mismatches = compare_depth_multisample_quality_levels(device.p, depth_sample_counts); if (depth_quality_mismatches < 0) std::printf("Depth/stencil MSAA quality queries: no host D3D12 device to compare with, skipped\n"); From 7ee2879342814756948799514717710b7996f9fd Mon Sep 17 00:00:00 2001 From: Tayar <358041433+lucastayaralvarenga-ui@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:25:14 -0300 Subject: [PATCH 038/115] test: use a valid dictionary for compose validation --- tests/test_save_keys.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/test_save_keys.py b/tests/test_save_keys.py index aa015c8a28..ba61d45c4c 100644 --- a/tests/test_save_keys.py +++ b/tests/test_save_keys.py @@ -51,8 +51,11 @@ class Resolve(unittest.TestCase): def test_rejects_negative_compose_count(self): with tempfile.TemporaryDirectory() as tmp: tool = os.path.join(ROOT, "tools", "save_keys.py") + words = os.path.join(tmp, "words.txt") + with open(words, "w", encoding="utf-8") as f: + f.write("SyntheticWord\n") result = subprocess.run( - [sys.executable, "-I", tool, "resolve", tmp, "--dict", tmp, "--compose", "-1"], + [sys.executable, "-I", tool, "resolve", tmp, "--dict", words, "--compose", "-1"], capture_output=True, text=True, ) self.assertEqual(result.returncode, 2, result.stderr) From 7baf4c21ac0cd74bfa9316dcdad6c030b0dea3d0 Mon Sep 17 00:00:00 2001 From: Tomgamer Date: Sun, 22 Nov 2026 15:25:38 +0100 Subject: [PATCH 039/115] D3D-238: refuse the heap descriptions the host refuses in CreateHeap CreateHeap checked only for a null description and a zero size. A shared heap_desc_refusal now also refuses an alignment other than 0, 64 KiB and 4 MiB, a heap with all three DENY_* flags, and the heap properties that heap_properties_refusal already refuses for committed resources (a type outside the enum such as 0, a custom heap without a CPU page property or memory pool, a non-custom heap with either). CreateHeap1, a stub until now, wraps CreateHeap and refuses a protected session. Tests: direct E_INVALIDARG/S_OK checks on the standalone device for both methods, and host comparison cases in compare_invalid_arguments. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 4 +- runtime/shims/d3d12_vulkan_device.cpp | 33 +++++- runtime/test/d3d12_vulkan_device_test.cpp | 135 ++++++++++++++++++++++ 3 files changed, 170 insertions(+), 2 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e96dcae726..6dbe31192d 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -380,7 +380,9 @@ What is implemented (all of it testable without the game): | `CreateCommandQueue1`'s creator ID | ignored | `CreatePlacedResource1/2` wrap the placed path above; `2` carries the castable-format list. `CreateHeap1` - remains a stub. + wraps `CreateHeap` and refuses a protected session. Both refuse, as the host does (RX 5700 and WARP, D3D-238), + an alignment other than 0, 64 KiB and 4 MiB, a heap type outside the enum, a custom heap without a CPU page + property and memory pool or a non-custom heap with either, and a heap with all three `DENY_*` flags. - `CreateSampler2` as a wrapper over `CreateSampler` (D3D-28, part 2). Without flags it writes the same S#. `D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR` reads the union as integers. `(0,0,0,0)`, `(0,0,0,1)` and `(1,1,1,1)` take the S#'s transparent-black, opaque-black and opaque-white types. The S# has no separate integer types, diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 8d0cd21e47..8073090b5f 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -1060,6 +1060,21 @@ const char* heap_properties_refusal(const D3D12_HEAP_PROPERTIES& heap) { return nullptr; } +// Why the host would refuse this CreateHeap/CreateHeap1 description, or null if these checks pass (D3D-238). A probe +// on an RX 5700 and WARP refuses an alignment other than 0, 64 KiB and 4 MiB, the heap properties above (a type of 0, +// a custom heap without a CPU page property), and a heap that denies buffers and both kinds of texture. +const char* heap_desc_refusal(const D3D12_HEAP_DESC& desc) { + if (!desc.SizeInBytes) return "zero size"; + if (desc.Alignment && desc.Alignment != D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT && + desc.Alignment != D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT) + return "alignment (0, 64 KiB or 4 MiB)"; + if (const char* why = heap_properties_refusal(desc.Properties)) return why; + constexpr UINT deny_all = D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | + D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES; + if ((UINT(desc.Flags) & deny_all) == deny_all) return "heap flags denying every resource kind"; + return nullptr; +} + // Why the host would refuse this committed resource, or null if these checks pass. The flag and format tables were // measured on an RX 9070 XT, an integrated Radeon and WARP, which agree on all of them. Cross-adapter resources // (valid there only as a row-major texture on a SHARED | SHARED_CROSS_ADAPTER heap) are refused: this layer has no @@ -4219,7 +4234,11 @@ class Device final // 64 KiB-aligned offset is simply that offset into the arena, and its console VA is the heap's place plus it. HRESULT STDMETHODCALLTYPE CreateHeap(const D3D12_HEAP_DESC* desc, REFIID riid, void** out) override { if (out) *out = nullptr; - if (!desc || !desc->SizeInBytes) return E_INVALIDARG; + if (!desc) return E_INVALIDARG; + if (const char* why = heap_desc_refusal(*desc)) { + log_once((std::string("CreateHeap refused (") + why + "), heap type").c_str(), int(desc->Properties.Type)); + return E_INVALIDARG; + } if (!state_.arena.mapped) { log_once("heaps need the GPU address arena (bufferDeviceAddress); heap size in KiB:", int(desc->SizeInBytes / 1024)); @@ -4239,6 +4258,18 @@ class Device final return hand_out(heap, riid, out); } + // Device4: CreateHeap with a protected session, which is refused as CreateCommittedResource1 refuses one. The host + // gives the same answers as CreateHeap for the D3D-238 descriptions. + HRESULT STDMETHODCALLTYPE CreateHeap1(const D3D12_HEAP_DESC* desc, ID3D12ProtectedResourceSession* session, + REFIID riid, void** out) override { + if (out) *out = nullptr; + if (session) { + log_once("protected resource session refused (not supported) by CreateHeap1", 1); + return E_INVALIDARG; + } + return CreateHeap(desc, riid, out); + } + HRESULT STDMETHODCALLTYPE CreatePlacedResource(ID3D12Heap* heap_interface, UINT64 heap_offset, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES, const D3D12_CLEAR_VALUE*, REFIID riid, void** out) override { diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp index 556ab15666..3f947b71f3 100644 --- a/runtime/test/d3d12_vulkan_device_test.cpp +++ b/runtime/test/d3d12_vulkan_device_test.cpp @@ -2205,6 +2205,32 @@ HRESULT fence(ID3D12Device* device, D3D12_FENCE_FLAGS flags, REFIID riid = __uui return released(device->CreateFence(0, flags, riid, &out), &out); } +// A 64 KiB heap description for the CreateHeap/CreateHeap1 cases (D3D-238). +D3D12_HEAP_DESC heap_desc_of(UINT64 alignment, D3D12_HEAP_PROPERTIES properties = {D3D12_HEAP_TYPE_DEFAULT}, + D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE, UINT64 size = 64 * 1024) { + D3D12_HEAP_DESC desc{}; + desc.SizeInBytes = size; + desc.Properties = properties; + desc.Alignment = alignment; + desc.Flags = flags; + return desc; +} + +HRESULT heap_create(ID3D12Device* device, D3D12_HEAP_DESC desc) { + void* out = nullptr; + return released(device->CreateHeap(&desc, __uuidof(ID3D12Heap), &out), &out); +} + +// CreateHeap1 without a protected session; E_NOINTERFACE when the device has no ID3D12Device4. +HRESULT heap_create1(ID3D12Device* device, D3D12_HEAP_DESC desc) { + ID3D12Device4* device4 = nullptr; + if (FAILED(device->QueryInterface(IID_PPV_ARGS(&device4)))) return E_NOINTERFACE; + void* out = nullptr; + const HRESULT hr = device4->CreateHeap1(&desc, nullptr, __uuidof(ID3D12Heap), &out); + device4->Release(); + return released(hr, &out); +} + // Map on a fresh committed resource; `range` is the read range, or null. HRESULT map(ID3D12Device* device, D3D12_HEAP_PROPERTIES heap, D3D12_RESOURCE_DESC desc, D3D12_RESOURCE_STATES state, UINT subresource, const D3D12_RANGE* range, bool want_pointer = true) { @@ -2779,6 +2805,73 @@ int compare_invalid_arguments(ID3D12Device* ours) { return d->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), nullptr); }}, + // CreateHeap and CreateHeap1 (D3D-238): the four descriptions the host refused on an RX 5700 and WARP, the + // heap-property rules CreateCommittedResource shares, and valid neighbours. + {"heap: alignment 4096", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(4096)); }}, + {"heap1: alignment 4096", [](ID3D12Device* d) { return heap_create1(d, heap_desc_of(4096)); }}, + {"heap: custom heap, unknown page property", [](ID3D12Device* d) { + return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, + D3D12_MEMORY_POOL_L0})); + }}, + {"heap1: custom heap, unknown page property", [](ID3D12Device* d) { + return heap_create1(d, heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, + D3D12_MEMORY_POOL_L0})); + }}, + {"heap: all three DENY flags", [](ID3D12Device* d) { + return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, + D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | + D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES)); + }}, + {"heap1: all three DENY flags", [](ID3D12Device* d) { + return heap_create1(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, + D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | + D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES)); + }}, + {"heap: type 0", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE(0)})); }}, + {"heap1: type 0", [](ID3D12Device* d) { return heap_create1(d, heap_desc_of(0, {D3D12_HEAP_TYPE(0)})); }}, + {"heap: custom heap, unknown pool", [](ID3D12Device* d) { + return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, + D3D12_MEMORY_POOL_UNKNOWN})); + }}, + {"heap: default heap with a CPU page property", [](ID3D12Device* d) { + return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK})); + }}, + {"heap: default heap with a memory pool", [](ID3D12Device* d) { + return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, + D3D12_MEMORY_POOL_L0})); + }}, + {"heap: alignment 0", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0)); }}, + {"heap: alignment 64 KiB", [](ID3D12Device* d) { + return heap_create(d, heap_desc_of(D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT)); + }}, + {"heap: alignment 4 MiB", [](ID3D12Device* d) { + return heap_create(d, heap_desc_of(D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, + {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE, + D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT)); + }}, + {"heap1: alignment 4 MiB", [](ID3D12Device* d) { + return heap_create1(d, heap_desc_of(D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, + {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE, + D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT)); + }}, + {"heap: size 1000", [](ID3D12Device* d) { + return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE, 1000)); + }}, + {"heap: upload", [](ID3D12Device* d) { return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_UPLOAD})); }}, + {"heap: readback", [](ID3D12Device* d) { + return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_READBACK})); + }}, + {"heap: custom write-combine L0", [](ID3D12Device* d) { + return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, + D3D12_MEMORY_POOL_L0})); + }}, + {"heap1: custom write-combine L0", [](ID3D12Device* d) { + return heap_create1(d, heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, + D3D12_MEMORY_POOL_L0})); + }}, + {"heap: ALLOW_ONLY_BUFFERS (two DENY flags)", [](ID3D12Device* d) { + return heap_create(d, heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS)); + }}, // CreateDescriptorHeap. A null description faults in the host runtime, so it is not compared. {"descriptor heap: null output", [](ID3D12Device* d) { const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 4}; @@ -4762,6 +4855,48 @@ int main() { upload_heap_desc.Properties.Type = D3D12_HEAP_TYPE_UPLOAD; EXPECT(SUCCEEDED(standalone->CreateHeap(&upload_heap_desc, IID_PPV_ARGS(&upload_placed_heap.p)))); + // D3D-238: heap descriptions the host refuses (RX 5700 and WARP), from CreateHeap and CreateHeap1 alike, and + // their valid neighbours. compare_invalid_arguments checks the same answers against a host device. + { + const D3D12_HEAP_FLAGS deny_all = D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | + D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES; + const D3D12_HEAP_DESC refused_heaps[] = { + heap_desc_of(4096), + heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_L0}), + heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, deny_all), + heap_desc_of(0, {D3D12_HEAP_TYPE(0)}), + heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, + D3D12_MEMORY_POOL_UNKNOWN}), + heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK}), + heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE, 0), + }; + for (const D3D12_HEAP_DESC& hd : refused_heaps) { + EXPECT(heap_create(standalone.p, hd) == E_INVALIDARG); + EXPECT(heap_create1(standalone.p, hd) == E_INVALIDARG); + } + const D3D12_HEAP_DESC accepted_heaps[] = { + heap_desc_of(0), + heap_desc_of(D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT), + heap_desc_of(D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, {D3D12_HEAP_TYPE_DEFAULT}, + D3D12_HEAP_FLAG_NONE, D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT), + heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE, 1000), + heap_desc_of(0, {D3D12_HEAP_TYPE_UPLOAD}), + heap_desc_of(0, {D3D12_HEAP_TYPE_READBACK}), + heap_desc_of(0, {D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, D3D12_MEMORY_POOL_L0}), + heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS), + heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, + D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES), + }; + for (const D3D12_HEAP_DESC& hd : accepted_heaps) { + EXPECT(heap_create(standalone.p, hd) == S_OK); + EXPECT(heap_create1(standalone.p, hd) == S_OK); + } + Ref device4; + Ref unused; + EXPECT(SUCCEEDED(standalone->QueryInterface(IID_PPV_ARGS(&device4.p)))); + EXPECT(device4->CreateHeap1(&placed_heap_desc, nullptr, IID_PPV_ARGS(&unused.p)) == S_OK && unused.p); + } + auto tiled_2d = [&](UINT w, UINT h, DXGI_FORMAT fmt, UINT16 mips, D3D12_RESOURCE_FLAGS flags, UINT64 align = 0) { D3D12_RESOURCE_DESC d = texture_desc(w, h, fmt, flags, mips); From 0a43f809400ec814f0974f9c7c33ebb97ef9b917 Mon Sep 17 00:00:00 2001 From: CowDeV <252005651+CowBoYdu76@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:25:47 +0100 Subject: [PATCH 040/115] Runtime: drop the Intel minimum-LOD rounding from D3D-219 Rounding the view's minLod to the nearest level fixed point-filtered samples on drivers that use minLodInteger, but integer texel fetches and gathers use floor(minLod) on every driver, as D3D11.3 5.8 also requires for ld and gather4. With a 0.75 clamp the rounded view gave 1.0, so a Load of mip 0 would read zero. No single view value is right for both, so the sampling fix belongs in the translator (a MinLod image operand on sample ops only). This keeps the bindless capacity fix. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 3 --- runtime/shims/d3d12_vulkan_device.cpp | 18 ------------------ 2 files changed, 21 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 71bafa7b46..f08da621be 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -1090,9 +1090,6 @@ The layer's descriptor model: `VK_EXT_image_view_min_lod`. Vulkan allows the image-view minimum to be rounded down to an integer. With nearest mip filtering, the UHD 770 and Arrow Lake Xe-LPG returned mip 0 for a 2D minimum of 0.75. The Xe-LPG also returned mip 1 for a 2D-array minimum of 1.75. RTX and Radeon returned mips 1 and 2. - On Intel integrated GPUs the layer therefore passes the clamp rounded to the nearest level - (`ceil(minLod + 0.5) - 1`), which point mip filtering selects exactly; linear mip filtering then blends from that - whole level instead of the fraction (D3D-219). `LEONIDA_MIN_LOD_INTEGER=1` or `0` forces the rounding on or off. See [Vulkan image-level selection](https://docs.vulkan.org/spec/latest/chapters/textures.html#textures-image-level-selection) and the [Intel readbacks](https://github.com/ItsNotRexed/Leonida/pull/1015#issuecomment-7075135647). If the logical device lacks the feature, the runtime logs the unsupported view diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 763cf5f9b0..a57fcab562 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -331,12 +331,6 @@ struct DeviceState { // True when VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 lacks native STORAGE_IMAGE but mutable R32_UINT+{R32_UINT,E5B9G9R9} // is supported, so R9G9B9E5_SHAREDEXP UAV textures are backed by R32_UINT with separate storage/sampled views. bool r9g9b9e5_uav_emulated = false; - // D3D-219: VK_EXT_image_view_min_lod may select levels with minLodInteger = floor(minLod), the spec's - // "alternative", while D3D12's ResourceMinLODClamp is fractional. Intel's integrated GPUs on Windows do: a 0.75 - // clamp sampled at LOD 0 with point mip filtering reads mip 0 (UHD 770 101.7092, Arrow Lake Xe-LPG; #1015). - // bind_image gives such a driver the clamp rounded to the nearest level, which point mip filtering selects - // exactly. LEONIDA_MIN_LOD_INTEGER=1 or 0 forces it either way. - bool min_lod_integer = false; // Cached physical-device no-attachment sample counts for D3D12_OPTIONS19. UINT no_output_sample_counts = 0; @@ -739,9 +733,6 @@ struct DeviceState { log_once("SRV requires VK_EXT_image_view_min_lod; first mip", int(image.first_mip)); return false; } - // A driver that floors the clamp (min_lod_integer) gets the level point mip filtering picks: - // nearest(d') = ceil(d' + 0.5) - 1, the spec's preferred rounding. It stays within the mip range. - if (min_lod_integer) clamp.minLod = std::ceil(clamp.minLod + 0.5f) - 1.0f; clamp.pNext = view_info.pNext; view_info.pNext = &clamp; } @@ -2904,15 +2895,6 @@ class Device final VkPhysicalDeviceProperties properties{}; device_properties(info.physical, &properties); state_.max_sampler_lod_bias = properties.limits.maxSamplerLodBias; - { - constexpr std::uint32_t kIntelVendorId = 0x8086; - state_.min_lod_integer = properties.vendorID == kIntelVendorId && - properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; - char text[4] = {}; - size_t length = 0; - if (getenv_s(&length, text, "LEONIDA_MIN_LOD_INTEGER") == 0 && length > 1) - state_.min_lod_integer = text[0] != '0'; - } std::uint32_t family_count = 0; queue_families(info.physical, &family_count, nullptr); std::vector families(family_count); From e0416ce29d0d3791b02f0d236d8dadc4ca6fe5ab Mon Sep 17 00:00:00 2001 From: SirAmong Date: Sun, 22 Nov 2026 08:41:35 -0500 Subject: [PATCH 041/115] vk_pipeline_check: --isolate runs batches in child processes and records a module that kills the driver as failed (TEST-248) --isolate (POSIX only; an error on Windows) runs the check in child processes over --isolate-batch modules at a time. A child killed by a signal has its batch bisected to the module, which is reported as MODULE CRASH, counted as a failed pipeline and makes the exit status 1; the rest is checked as usual. Children share cache.bin one after another (atomic saves). The test hook VK_PIPELINE_CHECK_SIMULATE_CRASH=[:SIGNAL] raises a signal before a matching pipeline is created, so tests/test_vk_pipeline_check_isolate.py checks this with five hand-assembled compute shaders and no crashing driver. Normal (non-isolated) output is unchanged. Co-Authored-By: Claude Sonnet 5.5 --- docs/pipeline_check.md | 36 +++ runtime/test/vk_pipeline_check.cpp | 280 +++++++++++++++++++++++- tests/test_vk_pipeline_check_isolate.py | 129 +++++++++++ 3 files changed, 443 insertions(+), 2 deletions(-) create mode 100644 tests/test_vk_pipeline_check_isolate.py diff --git a/docs/pipeline_check.md b/docs/pipeline_check.md index 51ae4281f4..dc2974bd51 100644 --- a/docs/pipeline_check.md +++ b/docs/pipeline_check.md @@ -138,6 +138,42 @@ The report above therefore states the limit and the skip count; a later run on a completed the full 26,503-entry set without them (`docs/design.md`). `--max-bytes` remains a visibility tool, not a pass: a skipped module has not been validated. +## Crash isolation (`--isolate`) + +A driver that dies while compiling one module (for example the RADV `SIGFPE` in +[#1721](https://github.com/ItsNotRexed/Leonida/issues/1721)) ends the whole process, so the rest of the corpus +used to need that module excluded by hand with `--start/--count`. With `--isolate` (POSIX only; on Windows it +prints an error and exits with 2) the tool runs the check in child processes instead: + +```sh +vk_pipeline_check cache.bin --isolate [--isolate-batch 256] [--jobs N ...] +``` + +- The parent opens no Vulkan device. It runs this executable, one child at a time, over `--isolate-batch` + modules (default 256) of the same sorted, stage-filtered list, with the other options passed on (`--jobs` is + the thread count inside each child). `--stats` is refused: children would overwrite one file. +- A child that is killed by a signal, or exits without finishing the pass after it started work, has its output + discarded and its batch is bisected (re-run in halves) down to the module that kills it. That module is printed as + `MODULE CRASH (, driver crashed: SIGFPE)`, counted as a failed pipeline and listed at the end; + the other modules are checked as usual and counted once. If both halves of a crashed batch run clean (a crash + that needs several threads at once), the batch is reported as `MODULE CRASH [a, b) not reproduced ...` and + counts as a failure. A child that fails before it starts work (no device, bad arguments) stops the run + with exit status 1. +- The pipeline cache: children run one after another and each seeds from and saves to the same `cache.bin`, + like the chunked runs above; the save is atomic, a crashed child saves nothing, so the file stays valid and + holds everything the finished children compiled. The parent prints its size at the end. +- Exit status: 0 only if no module failed or crashed and the cache saved; 1 otherwise. The summary is + aggregated by the parent (modules, pipelines, skips, `--cache-feedback`); the per-stage wave and compile-time lines + of a normal run are not repeated. Output of a batch appears when its child finishes. +- Each child loads the cache again, so a very large cache makes small batches slow; raise `--isolate-batch`. + There is no timeout: a hung compile still hangs. + +Test hook, not for normal use: `VK_PIPELINE_CHECK_SIMULATE_CRASH=[:SIGNAL]` makes the +process raise `SIGNAL` (default `SIGFPE`; `SEGV`, `ABRT`, `KILL`, ... also accepted) just before the pipeline of a +matching module is created. `tests/test_vk_pipeline_check_isolate.py` uses it with five hand-assembled compute +shaders to check `--isolate` without a crashing driver; it skips when the tool isn't built or there is no +Vulkan device. + ## Application pipeline-cache feedback With `--cache-feedback`, the checker groups successful pipeline creations by translated shader stage diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp index bdefac8945..9ac1dba160 100644 --- a/runtime/test/vk_pipeline_check.cpp +++ b/runtime/test/vk_pipeline_check.cpp @@ -22,6 +22,12 @@ // --cache-feedback count each stage's successful pipelines by VkPipelineCreationFeedback: hits (VALID and // APPLICATION_PIPELINE_CACHE_HIT), no hit reported (VALID only) and unavailable (no VALID bit, or a // pre-1.3 device without VK_EXT_pipeline_creation_feedback). The three add up to the ok count. +// --isolate (POSIX only) check in child processes, --isolate-batch modules at a time (default 256), so a module +// that kills the driver (SIGFPE, SIGSEGV, ...) is recorded as failed ("MODULE CRASH") and the pass +// goes on. A crashed batch is bisected to the module. Children run one after the other and share +// cache.bin. Not compatible with --stats. +// test hook VK_PIPELINE_CHECK_SIMULATE_CRASH=[:SIGNAL] raises SIGNAL (default SIGFPE) +// just before the pipeline of a matching module is created. Only for testing --isolate. #include "vulkan_loader.h" #include "vk_device_pick.h" #include "pipeline_cache_file.h" @@ -33,6 +39,8 @@ #include #include #include +#include +#include #include #include #include @@ -48,6 +56,13 @@ #include #include +#ifndef _WIN32 +#include +#include +#include +#include +#endif + static PFN_vkGetInstanceProcAddr gipa; struct VertexInputMeta { @@ -375,6 +390,116 @@ static_assert(feedback_outcome(VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT) == 1); static_assert(feedback_outcome(VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT | VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) == 0); +// Test hook (see the header): VK_PIPELINE_CHECK_SIMULATE_CRASH=[:SIGNAL]. +struct SimulatedCrash { + bool enabled = false; + std::string pattern; + int sig = SIGFPE; +}; + +int signal_from_name(std::string n) { + for (char& c : n) c = static_cast(std::toupper(static_cast(c))); + if (n.rfind("SIG", 0) == 0) n = n.substr(3); + if (n == "FPE") return SIGFPE; + if (n == "SEGV") return SIGSEGV; + if (n == "ABRT") return SIGABRT; + if (n == "ILL") return SIGILL; + if (n == "TERM") return SIGTERM; +#ifndef _WIN32 + if (n == "BUS") return SIGBUS; + if (n == "KILL") return SIGKILL; +#endif + return 0; +} + +SimulatedCrash read_simulated_crash() { + SimulatedCrash c; + const char* env = std::getenv("VK_PIPELINE_CHECK_SIMULATE_CRASH"); + if (!env || !*env) return c; + std::string v = env; + const size_t colon = v.rfind(':'); + if (colon != std::string::npos) { + if (const int sig = signal_from_name(v.substr(colon + 1))) { + c.sig = sig; + v.resize(colon); + } + } + c.enabled = true; + c.pattern = v; + return c; +} + +#ifndef _WIN32 +std::string signal_label(int sig) { + switch (sig) { + case SIGFPE: return "SIGFPE"; + case SIGSEGV: return "SIGSEGV"; + case SIGABRT: return "SIGABRT"; + case SIGILL: return "SIGILL"; + case SIGBUS: return "SIGBUS"; + case SIGKILL: return "SIGKILL"; + case SIGTERM: return "SIGTERM"; + default: return "signal " + std::to_string(sig); + } +} + +// --isolate: one child run of this executable over [start, start + count) of the stage-filtered list. +struct ChildRun { + bool ready = false; // reached the work loop (ISO-READY): Vulkan and the cache were set up + bool done = false; // finished the pass and saved the cache (ISO-DONE) + bool cache_ok = true; + int sig = 0; // killed by this signal + int status = 0; // exit status when it exited + std::string out; // its stdout +}; + +ChildRun run_child(const std::string& exe, const std::string& dir, const std::vector& pass, + const std::string& cache_path, size_t start, size_t count) { + ChildRun r; + std::vector args = {exe, dir}; + if (!cache_path.empty()) args.push_back(cache_path); + for (const auto& a : pass) args.push_back(a); + args.insert(args.end(), {"--isolate-child", "--start", std::to_string(start), "--count", std::to_string(count)}); + std::vector argv; + for (auto& a : args) argv.push_back(a.data()); + argv.push_back(nullptr); + int fds[2]; + if (pipe(fds) != 0) { r.status = 127; return r; } + std::fflush(nullptr); + const pid_t pid = fork(); + if (pid < 0) { close(fds[0]); close(fds[1]); r.status = 127; return r; } + if (pid == 0) { + dup2(fds[1], 1); + close(fds[0]); close(fds[1]); + execv(exe.c_str(), argv.data()); + _exit(127); + } + close(fds[1]); + char buf[4096]; + for (;;) { + const ssize_t n = read(fds[0], buf, sizeof buf); + if (n > 0) r.out.append(buf, size_t(n)); + else if (n < 0 && errno == EINTR) continue; + else break; + } + close(fds[0]); + int st = 0; + while (waitpid(pid, &st, 0) < 0 && errno == EINTR) {} + if (WIFSIGNALED(st)) r.sig = WTERMSIG(st); + else r.status = WIFEXITED(st) ? WEXITSTATUS(st) : 1; + size_t pos = 0; + while (pos < r.out.size()) { + size_t e = r.out.find('\n', pos); + if (e == std::string::npos) e = r.out.size(); + const std::string_view line(r.out.data() + pos, e - pos); + if (line == "ISO-READY") r.ready = true; + else if (line.rfind("ISO-DONE", 0) == 0) { r.done = true; r.cache_ok = line.find("cache_ok=0") == std::string_view::npos; } + pos = e + 1; + } + return r; +} +#endif + } // namespace int main(int argc, char** argv) { @@ -382,7 +507,7 @@ int main(int argc, char** argv) { std::fprintf(stderr, "usage: vk_pipeline_check [cache.bin] [--jobs N] [--start I] [--count N] [--slow SEC] " "[--max-bytes N] [--large-module-bytes N] [--stage all|cs|graphics | --compute-only | --graphics-only] " - "[--stats FILE] [--cache-feedback]\n"); + "[--stats FILE] [--cache-feedback] [--isolate [--isolate-batch N]]\n"); return 2; } std::setvbuf(stdout, nullptr, _IOLBF, 1 << 16); // failures reach a redirected log as they happen @@ -392,7 +517,8 @@ int main(int argc, char** argv) { size_t large_module_bytes = 4 * 1024 * 1024; double slow = 30.0; std::string stage_filter = "all"; - bool cache_feedback = false; + bool cache_feedback = false, isolate = false, iso_child = false; + size_t isolate_batch = 256; for (int i = 2; i < argc; i++) { std::string a = argv[i]; auto val = [&] { return i + 1 < argc ? std::string(argv[++i]) : std::string("0"); }; @@ -415,6 +541,9 @@ int main(int argc, char** argv) { } else if (a == "--stats") stats_path = val(); else if (a == "--cache-feedback") cache_feedback = true; + else if (a == "--isolate") isolate = true; + else if (a == "--isolate-child") iso_child = true; // internal: the parent's child runs + else if (a == "--isolate-batch") isolate_batch = std::max(1, std::stoull(val())); else cache_path = a; } if (stage_filter != "all" && stage_filter != "cs" && stage_filter != "graphics") { @@ -422,6 +551,17 @@ int main(int argc, char** argv) { return 2; } + if (isolate && !stats_path.empty()) { + std::fprintf(stderr, "--isolate cannot be combined with --stats\n"); + return 2; + } +#ifdef _WIN32 + if (isolate) { + std::fprintf(stderr, "--isolate is not supported on Windows (it needs fork/waitpid); run without it\n"); + return 2; + } +#endif + std::string index_err; auto index = read_index(dir + "/index.json", index_err); if (!index_err.empty()) { @@ -441,6 +581,115 @@ int main(int argc, char** argv) { const auto [lo, hi] = shader_slice(all.size(), start, count); const std::vector work(all.begin() + lo, all.begin() + hi); +#ifndef _WIN32 + if (isolate) { + // Parent: no Vulkan here. Run the check in child processes, one at a time, in batches of --isolate-batch + // modules. A child that dies mid-batch has its output discarded and the batch is bisected until the one + // module that kills the driver is found; the clean sub-runs partition the rest, so nothing is counted twice. + std::string exe = argv[0]; + std::error_code ec; + if (auto self = std::filesystem::read_symlink("/proc/self/exe", ec); !ec) exe = self.string(); + std::vector pass = {"--jobs", std::to_string(jobs), "--slow", std::to_string(slow), "--stage", stage_filter, + "--max-bytes", std::to_string(max_bytes), + "--large-module-bytes", std::to_string(large_module_bytes)}; + if (cache_feedback) pass.push_back("--cache-feedback"); + struct Agg { uint32_t mod_ok = 0, mod_bad = 0, pipe_ok = 0, pipe_bad = 0, pipe_skip = 0, big = 0, crashed = 0, fb[3] = {}; }; + std::map agg; + std::vector crashes; + bool cache_ok = true, setup_failed = false; + size_t unreproduced = 0; + const auto t_iso = std::chrono::steady_clock::now(); + std::fprintf(stderr, "isolating %zu shaders [%zu, %zu) (stage=%s) in child processes, %zu per batch\n", + work.size(), lo, hi, stage_filter.c_str(), isolate_batch); + auto commit = [&](const ChildRun& r) { + size_t pos = 0; + while (pos < r.out.size()) { + size_t e = r.out.find('\n', pos); + if (e == std::string::npos) e = r.out.size(); + const std::string line = r.out.substr(pos, e - pos); + pos = e + 1; + // The parent prints one cache line at the end instead of one per child. + if (line == "ISO-READY" || line.rfind("ISO-DONE", 0) == 0 || line.rfind("pipeline cache: ", 0) == 0) continue; + if (line.rfind("ISO-RESULT ", 0) == 0) { + char st[16]; + unsigned v[9] = {}; + if (std::sscanf(line.c_str(), "ISO-RESULT %15s %u %u %u %u %u %u %u %u %u", st, v, v + 1, v + 2, v + 3, + v + 4, v + 5, v + 6, v + 7, v + 8) == 10) { + Agg& a = agg[st]; + a.mod_ok += v[0]; a.mod_bad += v[1]; a.pipe_ok += v[2]; a.pipe_bad += v[3]; a.pipe_skip += v[4]; + a.big += v[5]; a.fb[0] += v[6]; a.fb[1] += v[7]; a.fb[2] += v[8]; + } + continue; + } + std::printf("%s\n", line.c_str()); + } + std::fflush(stdout); + if (!r.cache_ok) cache_ok = false; + }; + // Returns the number of failures recorded for [s, s + n): crashed modules, or 1 for a crash that vanished. + auto bisect = [&](auto&& self, size_t s, size_t n) -> size_t { + if (setup_failed) return 0; + const ChildRun r = run_child(exe, dir, pass, cache_path, s, n); + if (r.done) { commit(r); return 0; } + if (!r.ready) { // died or exited before the work loop: not a module's fault + std::fputs(r.out.c_str(), stdout); + if (r.sig) std::fprintf(stderr, "error: a child process died during setup (%s)\n", signal_label(r.sig).c_str()); + else std::fprintf(stderr, "error: a child process failed during setup (exit status %d)\n", r.status); + setup_failed = true; + return 0; + } + const std::string why = r.sig ? "driver crashed: " + signal_label(r.sig) + : "driver exited with status " + std::to_string(r.status); + if (n == 1) { + const std::string& name = *all[s].first; + const std::string& st = all[s].second->stage; + std::printf("MODULE CRASH %s (%s, %s)\n", name.c_str(), st.c_str(), why.c_str()); + std::fflush(stdout); + crashes.push_back(name + " (" + st + ", " + why + ")"); + agg[st].pipe_bad++; + agg[st].crashed++; + return 1; + } + std::fprintf(stderr, "child over [%zu, %zu) died (%s); bisecting\n", s, s + n, why.c_str()); + const size_t half = n / 2; + size_t found = self(self, s, half); + found += self(self, s + half, n - half); + if (found == 0 && !setup_failed) { + std::printf("MODULE CRASH [%zu, %zu) not reproduced when split (%s); counted as failed\n", s, s + n, why.c_str()); + ++unreproduced; + return 1; + } + return found; + }; + for (size_t s = lo; s < hi && !setup_failed; s += isolate_batch) bisect(bisect, s, std::min(isolate_batch, hi - s)); + if (setup_failed) return 1; + bool failed = !crashes.empty() || unreproduced || !cache_ok; + for (const auto& [st, a] : agg) { + std::printf("%s: %u modules ok, %u failed\n", st.c_str(), a.mod_ok, a.mod_bad); + std::printf("%s pipelines: %u ok, %u failed, %u skipped\n", st.c_str(), a.pipe_ok, a.pipe_bad, a.pipe_skip); + if (a.crashed) std::printf(" %s crashed the driver: %u (counted as failed)\n", st.c_str(), a.crashed); + if (cache_feedback) + std::printf(" %s cache feedback: %u hits, %u no hit reported, %u unavailable\n", st.c_str(), a.fb[0], a.fb[1], a.fb[2]); + if (a.mod_bad || a.pipe_bad) failed = true; + } + uint32_t big_total = 0; + for (const auto& [st, a] : agg) big_total += a.big; + if (big_total) std::printf("big modules skipped: %u (limit %zu bytes)\n", big_total, max_bytes); + if (!crashes.empty()) { + std::printf("modules that crashed the driver: %zu\n", crashes.size()); + for (const auto& c : crashes) std::printf(" %s\n", c.c_str()); + } + if (unreproduced) std::printf("crashes not reproduced after splitting: %zu\n", unreproduced); + if (!cache_path.empty()) { + const auto sz = std::filesystem::file_size(cache_path, ec); + if (!ec) std::printf("pipeline cache: %ju bytes -> %s\n", static_cast(sz), cache_path.c_str()); + } + std::printf("wall time: %.1fs (isolated)\n", + std::chrono::duration(std::chrono::steady_clock::now() - t_iso).count()); + return failed ? 1 : 0; + } +#endif + // Scan selected shaders to request only the optional extensions they actually use. bool want_mesh = false, want_bary = false, want_lock = false, want_m8 = false, want_fma = false; for (auto& [_, meta] : work) { @@ -783,6 +1032,15 @@ int main(int argc, char** argv) { if (n_done % 250 == 0) std::fprintf(stderr, " pipelines %u (%.0fs elapsed)\n", n_done, elapsed()); }; + const SimulatedCrash sim_crash = read_simulated_crash(); + auto maybe_simulate_crash = [&](const std::string& name) { // test hook, see the header + if (sim_crash.enabled && name.find(sim_crash.pattern) != std::string::npos) { + std::fprintf(stderr, "simulating signal %d before the pipeline of %s\n", sim_crash.sig, name.c_str()); + std::fflush(nullptr); + std::raise(sim_crash.sig); + } + }; + auto worker = [&] { for (size_t k; (k = next++) < work.size();) { const std::string& name = *work[k].first; @@ -846,6 +1104,7 @@ int main(int argc, char** argv) { const auto t0 = std::chrono::steady_clock::now(); { std::lock_guard g(mu); inflight[std::this_thread::get_id()] = {name, t0}; } VkPipeline p = VK_NULL_HANDLE; + maybe_simulate_crash(name); VkResult r = vkCreateComputePipelines(dev, cache, 1, &cpi, nullptr, &p); const double sec = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); if (r == VK_SUCCESS) write_stats(name, stage, VK_SHADER_STAGE_COMPUTE_BIT, p); @@ -1015,6 +1274,7 @@ int main(int argc, char** argv) { const auto t0 = std::chrono::steady_clock::now(); { std::lock_guard g(mu); inflight[std::this_thread::get_id()] = {name, t0}; } VkPipeline p = VK_NULL_HANDLE; + maybe_simulate_crash(name); VkResult r = vkCreateGraphicsPipelines(dev, cache, 1, &gpci, nullptr, &p); const double sec = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); if (r == VK_SUCCESS) write_stats(name, stage, stage_bit(stage), p); @@ -1032,6 +1292,8 @@ int main(int argc, char** argv) { } } }; + if (iso_child) std::printf("ISO-READY\n"); + std::fflush(stdout); std::vector pool; for (uint32_t t = 0; t < jobs; t++) pool.emplace_back(worker); // Watchdog: names every compile running past 60 s (about once a minute) and saves the cache every 10 minutes. @@ -1070,6 +1332,20 @@ int main(int argc, char** argv) { for (auto& [st, _] : modules_bad) all_stages.insert(st); for (auto& [st, _] : stats) all_stages.insert(st); + if (iso_child) { // --isolate child: machine-readable counts; the parent prints the summary + for (const auto& st : all_stages) { + const StageStats* s = stats.count(st) ? &stats[st] : nullptr; + uint32_t big = big_skipped.count(st) ? big_skipped[st] : 0; + std::printf("ISO-RESULT %s %u %u %u %u %u %u %u %u %u\n", st.c_str(), modules_ok[st], modules_bad[st], + s ? s->pipes_ok : 0u, s ? s->pipes_bad : 0u, s ? s->pipes_skipped : 0u, big, + s ? s->feedback[0] : 0u, s ? s->feedback[1] : 0u, s ? s->feedback[2] : 0u); + } + const bool saved = save_cache(true); + std::printf("ISO-DONE cache_ok=%d\n", saved ? 1 : 0); + std::fflush(stdout); + return saved ? 0 : 1; + } + bool check_failed = false; for (const auto& st : all_stages) { std::printf("%s: %u modules ok, %u failed\n", st.c_str(), modules_ok[st], modules_bad[st]); diff --git a/tests/test_vk_pipeline_check_isolate.py b/tests/test_vk_pipeline_check_isolate.py new file mode 100644 index 0000000000..38147cbeb4 --- /dev/null +++ b/tests/test_vk_pipeline_check_isolate.py @@ -0,0 +1,129 @@ +"""vk_pipeline_check --isolate: a module that kills the driver is recorded as failed and the pass goes on. + +No game data: five tiny compute shaders are assembled here with spirv-as. The crash is simulated with the tool's test +hook VK_PIPELINE_CHECK_SIMULATE_CRASH (a signal raised just before the pipeline of the named module), so no crashing +driver is needed. Skips (not fails) when vk_pipeline_check isn't built, spirv-as is missing, the platform is not POSIX +or there is no usable Vulkan device. Pin a GPU with VK_LOADER_DRIVERS_SELECT / LEONIDA_VK_DEVICE as for the other +Vulkan tools. Set LEONIDA_VK_PIPELINE_CHECK to use a binary elsewhere. +""" +import json +import os +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +NAMES = ["m_alpha", "m_bravo", "m_charlie", "m_delta", "m_echo"] +CRASHER = "m_charlie" + +ASM = """OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %main "main" +OpExecutionMode %main LocalSize {size} 1 1 +%void = OpTypeVoid +%fn = OpTypeFunction %void +%main = OpFunction %void None %fn +%entry = OpLabel +OpReturn +OpFunctionEnd +""" + + +def find_binary(): + env = os.environ.get("LEONIDA_VK_PIPELINE_CHECK") + if env: + return Path(env) if Path(env).is_file() else None + build = ROOT / "runtime" / "build" + for p in (build / "linux" / "vk_pipeline_check", build / "vk_pipeline_check"): + if p.is_file(): + return p + return None + + +class IsolateTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + if os.name != "posix": + raise unittest.SkipTest("--isolate is POSIX only") + cls.exe = find_binary() + if cls.exe is None: + raise unittest.SkipTest("vk_pipeline_check isn't built (cmake -S runtime -B runtime/build/linux)") + spirv_as = shutil.which("spirv-as") + if not spirv_as: + raise unittest.SkipTest("spirv-as not found") + cls.tmp = tempfile.TemporaryDirectory() + cls.addClassCleanup(cls.tmp.cleanup) + cls.dir = Path(cls.tmp.name) / "spirv" + cls.dir.mkdir() + index = {} + for i, name in enumerate(NAMES): + asm = Path(cls.tmp.name) / (name + ".spvasm") + asm.write_text(ASM.format(size=1 << i)) + subprocess.run([spirv_as, "--target-env", "vulkan1.1", str(asm), "-o", str(cls.dir / (name + ".spv"))], + check=True) + index[name] = {"stage": "cs", "subgroup_size": None, "features": []} + (cls.dir / "index.json").write_text(json.dumps(index)) + probe = cls.run_tool([], cache=Path(cls.tmp.name) / "probe.cache") + if probe.returncode != 0 or "cs pipelines: 5 ok, 0 failed" not in probe.stdout: + raise unittest.SkipTest("no usable Vulkan device (exit %d): %s" % (probe.returncode, probe.stderr.strip()[-300:])) + + @classmethod + def run_tool(cls, args, crash=None, cache=None): + env = dict(os.environ) + env.pop("VK_PIPELINE_CHECK_SIMULATE_CRASH", None) + if crash: + env["VK_PIPELINE_CHECK_SIMULATE_CRASH"] = crash + cmd = [str(cls.exe), str(cls.dir)] + ([str(cache)] if cache else []) + ["--jobs", "2"] + args + return subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=300) + + def cache(self, name): + return Path(self.tmp.name) / name + + def test_normal_run_passes(self): + r = self.run_tool([], cache=self.cache("normal.cache")) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn("cs: 5 modules ok, 0 failed", r.stdout) + self.assertIn("cs pipelines: 5 ok, 0 failed, 0 skipped", r.stdout) + + def test_isolate_without_a_crash_matches_normal_counts(self): + r = self.run_tool(["--isolate", "--isolate-batch", "2"], cache=self.cache("iso_clean.cache")) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn("cs: 5 modules ok, 0 failed", r.stdout) + self.assertIn("cs pipelines: 5 ok, 0 failed, 0 skipped", r.stdout) + self.assertNotIn("CRASH", r.stdout) + + def test_without_isolate_the_driver_crash_ends_the_process(self): + r = self.run_tool([], crash=CRASHER, cache=self.cache("dies.cache")) + self.assertEqual(r.returncode, -8, r.stdout + r.stderr) # killed by SIGFPE: no summary, no exit status + + def test_isolate_records_the_crashed_module_and_goes_on(self): + cache = self.cache("iso.cache") + for batch in ("5", "2", "1"): # one batch bisected down, several batches, one module at a time + with self.subTest(batch=batch): + r = self.run_tool(["--isolate", "--isolate-batch", batch], crash=CRASHER + ":SIGFPE", cache=cache) + self.assertNotEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertGreater(r.returncode, 0, "the parent itself must not die: " + r.stdout + r.stderr) + self.assertIn("MODULE CRASH %s (cs, driver crashed: SIGFPE)" % CRASHER, r.stdout) + self.assertEqual(r.stdout.count("MODULE CRASH"), 1, r.stdout) + self.assertIn("cs: 4 modules ok, 0 failed", r.stdout) + self.assertIn("cs pipelines: 4 ok, 1 failed, 0 skipped", r.stdout) + self.assertIn("cs crashed the driver: 1", r.stdout) + for name in NAMES: + if name != CRASHER: + self.assertNotIn("FAIL " + name, r.stdout) + self.assertTrue(cache.is_file(), "the shared pipeline cache must survive the crash") + + def test_other_signal(self): + r = self.run_tool(["--isolate"], crash=CRASHER + ":SEGV") + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn("MODULE CRASH %s (cs, driver crashed: SIGSEGV)" % CRASHER, r.stdout) + + def test_isolate_rejects_stats(self): + r = self.run_tool(["--isolate", "--stats", str(self.cache("s.csv"))]) + self.assertEqual(r.returncode, 2) + + +if __name__ == "__main__": + unittest.main() From 64ece042524902de82e3dcb0936d911b7b719af8 Mon Sep 17 00:00:00 2001 From: Vonsek <45567075+Vonsek@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:25:48 +0100 Subject: [PATCH 042/115] docs/design.md: one row per topic in the contract table Merges that kept both sides of an edited row left twenty topics in design.md's tables two to six times, each copy with facts the others lacked. Merge each topic into one row that keeps every fact, and drop only sentences a newer copy replaced (e.g. "Not GPU-verified" where the row is now hardware-verified). tests/test_docs_design_rows.py fails on a repeated first cell in one table. Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 39 +++------------------- tests/test_docs_design_rows.py | 60 ++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 35 deletions(-) create mode 100644 tests/test_docs_design_rows.py diff --git a/docs/design.md b/docs/design.md index 9e38cc015f..7fd0661b53 100644 --- a/docs/design.md +++ b/docs/design.md @@ -103,7 +103,6 @@ add a source file, add it to `runtime\CMakeLists.txt` and to the file list in `b | Shaders | 26,503 carved from `shaders.rpf`, native RDNA2 code unpacked (`FSSM`), disassembled, and translated to SPIR-V; all validate (see *Translator status*). | `\shaders\` (`.dxbc`, `fssm\`, `disasm\`, `spirv\`) | | Textures | **Solved.** Headers are in CPU segments: GPU pointer at q[k], u16 width/height/depth and DXGI format at q[k+4], mip count at byte 2 of q[k+5]. Data is AMD `SW_4K_S` tiled, largest mip first. The GPU segment is the blob run after the CPU blob. On 200 samples, 173 decode at least 1.5× smoother detiled than untiled (median 2.56×). Exports the top mip, slice 0, as DDS. **22,342 exported (1.23 GiB)**: every header whose GPU data follows its CPU blob. World and model textures are handled by the TXD and TTPF exporters below. GPU offsets must be 256-byte aligned, which drops the false headers in `navmeshes`/`anim`. | `tools\tex_headers.py`, `tools\tex_export.py`, `\textures\` | | Models | **Done: 382,781 models measured at the `e293917` pin** (`levels.rpf` 343,327, `packs` 26,585, `story000` 7,461, `data` 3,175, `shared_minigame000` 1,294, `core_restofworld` 936, `story000_restofworld` 3; 0 decode failures across all 382,781 models; **159,511 drawable-dictionary children**, **223,270 standalone**, **55,417 fragments**, **89,887 bone-bound**, **2.64 billion triangles** [`2,636,248,990`], 1,805 embedded textures; 72 unrecovered scan candidates vs 1,282 at `917e9b9`). Earlier baselines: 350,248 at `917e9b9` (159,483 dictionary children, 190,765 standalone) and 190,792 at `c3708fb`; the +32,533 gain at `e293917` comes from upstream `v1.2` PRs #8–#12 (optional fragment pointers, texture-dictionary filtering, probe-cap parity, and zero-radius drawables; see [models.md](models.md)). Exported with `tools\rpf9dump` (built on breadbbbb/rpf9-explorer's Core; see below). Resources are found at page offset +16 after 16 zero bytes, followed by a zlib system blob with a drawable/fragment header and then the following zlib blocks as graphics data. Positions are quantized: `bias + scale * ((q >> 8) & 0xFFFFFF)`. Output is OBJ (positions, UVs, indices) plus a manifest with real model names (e.g. `cvar_int_grg2b_toys_1`), bounds, per-mesh shader index and material texture references (parameter hash, name hash, 64-bit asset key). My earlier `0x1380`/`0x1601` descriptor notes stand, but the "data not located" blocker was wrong. Character skeletons are separate: the shared 597-name `.#ft` table and its model-side bone-hash mapping are in [character_skeleton.md](character_skeleton.md). | `\assets\\models\` | -| Models | **Done: 350,251 models measured at the `917e9b9` pin** (the submodule pin is now `e293917`, which also pulls in upstream `v1.2` model-discovery PRs #8-#12 plus BCPack PR #7; the non-`levels.rpf` archives have been re-counted at `e293917`: 39,454 rows, +3,203, almost all recovered fragments; `levels.rpf` has a recovery count of 343,327 models (+29,327) but no full OBJ export). At `917e9b9`: `levels.rpf` 314,000, `story000` 7,460, `packs` 24,034, `data` 2,581, `shared_minigame000` 1,288, `core_restofworld` 885, `story000_restofworld` 3; 0 decode failures in the re-count. The `c3708fb` export was 190,792; the new entries are **159,486 drawable-dictionary children** (levels 130,225, packs 23,720, story 4,156, data 268, shared 317, core 797, story_restofworld 3) plus raw-tail/mixed-block pages. The standalone total is 190,765. Triangle totals were not re-run. Exported with `tools\rpf9dump` (built on breadbbbb/rpf9-explorer's Core; see below). Resources are found at page offset +16 after 16 zero bytes, followed by a zlib system blob with a drawable/fragment header and then the following zlib blocks as graphics data. Positions are quantized: `bias + scale * ((q >> 8) & 0xFFFFFF)`. Output is OBJ (positions, UVs, indices) plus a manifest with real model names (e.g. `cvar_int_grg2b_toys_1`), bounds, per-mesh shader index and material texture references (parameter hash, name hash, 64-bit asset key). My earlier `0x1380`/`0x1601` descriptor notes stand, but the "data not located" blocker was wrong. Character skeletons are separate: the shared 597-name `.#ft` table and its model-side bone-hash mapping are in [character_skeleton.md](character_skeleton.md). | `\assets\\models\` | | Texture dictionaries | Same tool: TXD resources become DDS per texture. | `\assets\\textures\` | | World textures (TTPF) | **Done: 308,895 textures from all 57 pools, 0 failures, 48,220 entries skipped by the original exporter** (33,507 BCPack, 14,030 compact mapping, 678 arrays/volumes, 5 unsupported format, 0 unmapped). The compact-tail tool resolves 14,011 of the 14,030 layouts and reconstructs 305,264 complete chains (206,661 newly complete, 1,100,865 mips, 4.59 GiB), and the multi-slice pass resolves all 697 arrays/cubemaps/volumes ([textures_arrays.md](textures_arrays.md)). BCPack was the hard blocker: `tools/bcpack.py` decodes all six active modes (BC1, BC3, BC4, BC5, BC6H, BC7), and `rpf9dump`'s C# `TtpfReader` (`e293917` pin, `breadbbbb/rpf9-explorer#7`) now decodes compact tails, multi-slice layouts, DXGI 11, and strict BCPack BC1/BC3/BC4/BC5 directly; BC6H/BC7 and provisional-history chunks remain skipped by `rpf9dump` and can be completed by `tools/ttpf_assets.py` ([textures.md](textures.md)). 46 pools are in `data\ttdb\**`, 11 in `pack\\data\ttdb\**` (exported under `ttpf_pack\\`). `data\ttdb\**\*.ttpf` (57 pools, 58 GiB) are loose RDS5 texture pools, **not** inside RPFs. rpf9-explorer's `TtpfReader` reads the catalog and detiles them; checked visually (`ttdb_graphics`: scope reticles, clean lines). Names are generated (`texture_N_`); models reference textures by asset key. Some rows are skipped; the measured breakdown and next steps are in [textures.md](textures.md). | `\assets\ttpf\\` + `manifest.json` | | Animation | Indexed without the TOC: 130,470 zlib streams (4,203,762,662 stored / 11,593,460,132 inflated), 95.4% readable. New RAGE page directories (`0DRP`, version 122), `MoVE` (version 19), 273 `pack:/` name tables (2,298 paths), and a tail `RBF0` rig-set manager (`rage__crRigSetManager`: 1,126 rig sets, 6,677 source→rig entries, 3,669 distinct rigs; 56 empty). Bone data: one standalone 28-name table and 3 motion-matcher streams with embedded bone tables (30-name union, 19 joaat32 hashes present, 4 motionmatcher paths); no rig→skeleton link was found. Clip dictionaries are system-only RAGE resources (page map at the `+0x08` pointer). `tools/anim_clips.py` decodes 191,042 of 191,042 animations in 61,505 of them to per-frame values (channel types 0–5, 7, 8 and the GTA VI type 10) and resolves 111,948 of 159,584 `.motion` children to a clip. For each `.motion` it reads the per-child durations and time curves and, on 10,171 of 17,247, the one-axis parameter node (axis name hash, sorted sample values, range). The 2/3 packed streams are second pages of `0DRP` resources, which are not decoded. No `YCD`/`RSC7` at any stream start. The `rpf9_carve` tail overread is measured in `docs/animation.md`. | `tools\anim_index.py`, `\anim-index\` | @@ -217,7 +216,6 @@ How the generated SPIR-V expects the runtime to work: | Execution model | One invocation = one lane. A wave = a subgroup, so cross-lane ops (`ds_swizzle`, `v_permlane*`, `v_readlane`/`v_writelane`, `v_mbcnt`) become subgroup shuffles. **Requires subgroup size == wave size** (wave32 maps directly onto NVIDIA GPUs; wave64 shaders need a 64-wide subgroup or emulation). `v_readlane_b32`/`v_writelane_b32` mask the lane select with 63 in wave64 (`S1[5:0]`) and 31 in wave32 (`S1[4:0]`); until SHADER-52 both used 63, so a wave32 select ≥ 32 pointed past a 32-wide subgroup. GPU-checked with `cs_w32_lane_wrap.asm` (lane 40 → 8). | | DPP | VOP1/VOP2 `_dpp` applies to src0. DPP16 controls (`quad_perm`, `row_shl/shr/ror/share/xmask/mirror/half_mirror`) and DPP8 (`dpp8` + `fi`) select the source lane, then `row_mask` (one bit per 16-lane row) and `bank_mask` (one bit per 4-lane bank) decide which destination lanes update. A lane whose row/bank is off is not written. A source lane outside the row is invalid: `bound_ctrl` 1 uses 0 as src0, otherwise the lane is not written. A source lane inactive under EXEC is used when `fi` is 1; otherwise `bound_ctrl` decides. DPP8 always writes an enabled lane: `fi` 1 reads the inactive source, `fi` 0 uses 0. DPP16/8 never leaves its 16/8-lane group, so this is exact on every subgroup at least that wide; under `--wave64-emulate` the exchange goes through the workgroup buffer like the other cross-lane ops. GPU-checked with `runtime/test/shaders/cs_dpp*.asm` on an RTX 3070 and hardware-measured on an RX 6800. Semantics from the RDNA2 ISA, AMD LLVM modifier syntax and the GPUOpen DPP notes. | | EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. A pixel lane that was inactive at the last `exp ... vm` it executed is discarded, and on a path without one, a lane inactive at the end (EXEC is kept at the export only where a path can write it afterwards). **The `vm` rule is from the RDNA2 ISA reference guide (30-November-2020, §11.1 and §11.2.1: EXEC at the export is the valid mask and the final one sent is used), not measured on hardware**; checked on the CPU by `tests/semantic/test_export_valid_mask.py`. VALU scalar lane-mask destinations (`v_cmp_*`, `v_add_co_u32`, `v_add_co_ci_u32`, `v_sub_co_u32`, `v_sub_co_ci_u32`, `v_subrev_co_u32`, `v_subrev_co_ci_u32`, `v_mad_u64_u32`, `v_mad_i64_i32`) write 0 for lanes off in EXEC (`SDST[lane] = EXEC[lane] ? bit : 0`, AMD RDNA2 ISA). Until 2026-11-22 the six `*_co_*` ops and `v_mad_u64_u32`/`v_mad_i64_i32` did not AND the carry/sign bit with `active`, so inactive lanes leaked 1 bits into `VCC`/SGPR masks (`s_bcnt1`, `s_cbranch_vccz`, `v_cndmask_b32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), **not yet GPU-verified**. | -| EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. A pixel lane still inactive at the end is discarded. VALU scalar lane-mask destinations (`v_cmp_*`, `v_add_co_u32`, `v_add_co_ci_u32`, `v_sub_co_u32`, `v_sub_co_ci_u32`, `v_subrev_co_u32`, `v_subrev_co_ci_u32`, `v_mad_u64_u32`, `v_mad_i64_i32`) write 0 for lanes off in EXEC (`SDST[lane] = EXEC[lane] ? bit : 0`, AMD RDNA2 ISA). Until 2026-11-22 the six `*_co_*` ops and `v_mad_u64_u32`/`v_mad_i64_i32` did not AND the carry/sign bit with `active`, so inactive lanes leaked 1 bits into `VCC`/SGPR masks (`s_bcnt1`, `s_cbranch_vccz`, `v_cndmask_b32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), **not yet GPU-verified**. | | `s_*_saveexec_b32/b64`, `s_andn1/andn2_wrexec_b32/b64` | RDNA2 ISA SOP1. saveexec: `D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0)`. wrexec: `EXEC = f(S0, EXEC); D = EXEC`. `f` is one of `and`, `or`, `xor`, `andn1` (`~S0 & EXEC`), `andn2` (`S0 & ~EXEC`), `orn1`, `orn2`, `nand`, `nor`, `xnor`, the table in `Gen.EXEC_LOGIC`. The definitions match `tools/cf_ref.py` `_SAVEEXEC`, the FUZZ-8 model. Each invocation holds its own lane's bit (0 or ~0), so `f` is the bitwise op on that bit. A lane EXEC had off becomes active when `f` gives 1 for it (`nand`, `nor`, `orn1`, `orn2`, `xnor`, ...), as on hardware, and SCC is the wave vote. Until 2026-11-22 only `and`/`or`/`andn2_saveexec` and `andn2_wrexec` were translated. CPU-checked by `tests/semantic/test_saveexec_variants.py` (all ten saveexec kinds in wave32 and wave64, both wrexec kinds, partial EXEC and S0, an empty result, every lane against `cf_ref._SAVEEXEC`) and by `tools/cf_diff.py` (300 programs × wave32/64 still pass). **Not GPU-verified** for the seven new kinds. | | Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. | | User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. `--mesh-compute` modules add dwords 36–37, the output buffer address (152 bytes; see "Mesh shaders as compute"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. | @@ -225,26 +223,16 @@ How the generated SPIR-V expects the runtime to work: | Code-embedded data | 155 VS/PS had "undecodable words". They're **constant tables inside the code range** (float values like 0x3EF7…, plus zeros), read through `s_getpc_b64` + `s_add_u32`/`s_addc_u32` + `s_load` (147 of 155). The translator re-anchors each instruction to its true FSSM offset by matching encodings, translates only code reachable from entry (a branch into data is rejected), and turns `s_getpc_b64` into code base + next-instruction offset. **The runtime uploads each shader's FSSM blob into the heap and passes that VA as the code base.** Re-anchoring compares bytes exactly, except that VOP3P `op_sel_hi[2]` (bit 14) is ignored on two-source packed ops: the compiler stores 0 there, and LLVM prints its default of 1. Unused VOP3/VOP3P `SRC1` (bits 49:41) and `SRC2` (bits 58:50) fields are also ignored when stored as 0 and printed as `0x80`: LLVM 23 re-encodes a source it doesn't read as inline constant 0 (one-source `v_rcp`/`v_log`/`v_sqrt_f32_e64`, two-source `v_sub_f32_e64`/`v_cmp_*_e64`/`v_mul_lo_u32`/`v_pk_mul_f16`). A source it does read prints as decoded (raw 0 is `s0`), so this can't hide a real difference. Confirmed by a count over the corpus with LLVM 23.1.5: without it, 1,471 of the 1,473 shaders with embedded data are rejected ("reachable instruction with normalized encoding"); with it, all 1,473 translate and pass `spirv-val`. Runs with LLVM 21 already translated all of them, so older LLVMs presumably print the stored 0 (not re-checked). Data words that decode with ignored fields set are printed re-encoded (e.g. `0xbe8d2242` as `s_rfe_b64` `0xbe802242`), so they can never match. Since the decoder consumed the same length, they are anchored in sequence and marked. A shader that can *reach* a marked word is rejected; none of the corpus does. All 155 now translate. | | Global memory | `global_load/store_dword*`: address = (64-bit SGPR base + zero-extended 32-bit VGPR offset, or a 64-bit VGPR address) + the instruction offset, translated through the heap base. Inactive lanes don't access memory, and loads merge their previous values with OpPhi. The offset is the **signed 12-bit** byte value as llvm-mc prints it, -2048..2047 (`offset:-4` is the field 0xffc; llvm-mc rejects `offset:0xffc` and disassembles that field as `offset:-4`, so no repo path delivers the raw unsigned field), added to the address as is; a tool that printed the raw field (`0xffc`) would mean the same offset, and a value outside 12 bits is rejected. Measured on an AMD Radeon RX 6800 (gfx1030) running `global_load_dword` as a raw compute kernel, wave32 and wave64 alike, with the dword at byte n = 0x10000000+n and the pointer at 0x1000: offset 0 reads 0x10001000, -4 0x10000ffc, -2048 0x10000800, 2044 0x100017fc, -1024 0x10000c00. The translator used to subtract 0x1000 from an already negative value (4096 bytes too low). Checked by `tests/semantic/test_global_mem_offset.py` (both addressing modes, dword/x2/x4, byte/short loads and stores at -4, -2048, 2047 and 0) and the GPU test `runtime/test/shaders/cs_global_neg_offset.asm` (`vk_compute_test ... 40 dump`). | | Global atomics (`global_atomic_*`, 32-bit) | `add`, `sub`, `smin/umin`, `smax/umax`, `and`, `or`, `xor`, `swap` and `cmpswap` at the `global_load/store` address (same `Gen.global_address`: saddr pair plus zero-extended vaddr, or a 64-bit vaddr with `off`, plus the signed 12-bit offset), as one `OpAtomic*` on the PhysicalStorageBuffer dword, device scope, guarded so inactive lanes don't touch memory. With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword: a bitwise op or an exchange leaves the same memory that way, with no Int64 atomics. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `inc`/`dec`, the float atomics, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten ops on a value grid with and without `glc`, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis) and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected). **Not GPU-verified.** | -| Global atomics (`global_atomic_*`, 32-bit) | `add`, `sub`, `smin/umin`, `smax/umax`, `and`, `or`, `xor`, `swap` and `cmpswap` at the `global_load/store` address (same `Gen.global_address`: saddr pair plus zero-extended vaddr, or a 64-bit vaddr with `off`, plus the signed 12-bit offset), as one `OpAtomic*` on the PhysicalStorageBuffer dword, device scope, guarded so inactive lanes don't touch memory. With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. Still `Unsupported`: the `_x2` 64-bit forms, `inc`/`dec`, the float atomics, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten ops on a value grid with and without `glc`, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis). **Not GPU-verified.** | | 8/16-bit global stores and d16 loads | `global_store_byte`/`short` write the low 8/16 bits of the data VGPR (the `_d16_hi` forms its high half). `global_load_{u,s}byte_d16` and `global_load_short_d16` write the low 16 bits of `vdst` (the `_hi` forms the high 16) and keep the other half; `ubyte` zero-extends and `sbyte` sign-extends the byte to 16 bits. The address is the `global_load/store` one (`Gen.global_address`). The access goes one byte at a time, so a 16-bit access that crosses a dword (at byte 3) is exact too. A store merges each byte into its dword with atomic and/or, which keeps neighbouring bytes even when another lane writes them, as buffer byte stores do. A load reads each byte. Inactive lanes neither store nor load. The first-read analysis counts a d16 load's `vdst` as read, for the half it keeps. `global_load/store_dword_addtid` (lane-id and M0 addressing) raise `Unsupported`; until 2026-11-22 they crashed with `IndexError`, and the ten sub-dword ops raised `Unsupported`. CPU-checked by `tests/semantic/test_global_sub_dword.py` (every byte offset 0 to 7 for each op, an inactive lane, rejected forms, the first-read analysis). **Not GPU-verified.** | | Literal samplers | Some shaders build their S# from immediates (for example `0x92, 0xC00000, 0x14500000, 0`). The runtime registers those in the descriptor hash table too, by scanning the translated shaders' constant S# values, not only S#s the game binds. | -| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). The base comes from the 64-bit SGPR pointer or the V# (dword0 \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). Not measured: `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0, so an out-of-range dword issues no load; `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. | | 2D array resource dimensions | For `image_get_resinfo` on a 2D array, X/Y are the width/height at the requested mip, Z is the view layer count and W is its mip count. The query reads the sampled array at binding 3. A native gfx1036 kernel returned (19,11,5,3), (9,5,5,3) and (4,2,5,3) for the three mips of a synthetic array. On RTX 5080 and Radeon Graphics the translated query matched those tuples and returned (4,2,3,2) at relative mip 1 with a view starting at mip 1 and covering three layers. The registered `ps_array_resinfo` draw checks all 4096 pixels against (8,8,12,1). | | Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). The base comes from the 64-bit SGPR pointer or the V# (dword0 \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). Not measured: `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0, so an out-of-range dword issues no load (when descriptor limit and offset are compile-time constants, in-range dwords fold to straight-line loads and out-of-range dwords emit constant zero without branches); `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. | | Images and samplers | `image_sample_l` on 2D arrays used to read its LOD from the array layer; it now reads the LOD after all coordinates. `image_get_lod` and `image_gather4_lz` also work on 2D arrays. With `d16` every sample result is f16, packed two to a VGPR from the low half (the packed D16 of GFX10, as LLVM returns D16 image data); `image_sample_c_lz`/`_c_lz_o` follow it too, and until 2026-11-21 their compare result was written as f32 bits, which read as 0 in the low half. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`) and GPU-checked with `runtime/test/shaders/ps_sample_c_lz.asm` (`vk_texture_test dref`: a D32 texture and a LESS_OR_EQUAL compare sampler) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact for f32 and `d16`; with the old translator the `d16` result read 0 in the 2048 pixels whose compare passes. | -| Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1–4, i32 ×1–4 (formats 21/63/73/76), f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×1/2/4, uint8 ×4, unorm16 ×1/2/4, snorm16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm. Others give 0. Full-width SINT accesses preserve integer bits. D16 SINT loads saturate to signed 16-bit and D16 stores sign-extend, covered by the synthetic `cs_fmt_sint32.asm` readback. DST_SEL swizzle is applied (0→0, 1→1.0f for float/norm or integer 1 for UINT/SINT, 4..7→X..W). Missing channels repeat the format's own (component *c* = *c* mod *n*), measured on an RX 6700 (SHADER-86). UNORM/SNORM give the correctly rounded quotient by (2ⁿ−1), as the hardware does (0 mismatches vs hardware over 395,776 conversions on that GPU). It is built with integer ops (`Gen.norm_bits`): x/(2ⁿ−1) in binary is x's bits repeated, so a 64-bit multiply by the repeat pattern, `FindUMsb` and the round bit give the f32 exactly (the tail never ends, so there are no ties). `OpFDiv` is not enough on the GPU: Vulkan allows it 2.5 ULP, and on an RX 6700 (AMD Windows 26.11.2) and an RTX 5090 it returned the reciprocal-multiply bits (8_UNORM 130/256 exact, #599). Checked against exact values in `tests/semantic/test_norm_decode.py` (every value up to 8 bits, edges and the reciprocal-multiply misses for 10, 15 and 16 bits). 8_SNORM (2), 16_SNORM (8) and 8_8_SNORM (15) were missing until 2026-11-22 and decoded to 0. Format names list the channel widths from the top bit, so `2_10_10_10` (50) is R10G10B10A2 and `10_10_10_2` (44) has a 2-bit x (Mesa `gfx10_format_table.py`, `ac_formats.c`). Until 2026-11-22 the two were swapped, in stores too. Until 2026-11-21 an element that started mid-dword re-read dword 0 for its tail (`need` was `ceil(size/4)` and only the first dword was shifted); loads now take `need = ceil((byte_shift + size) / 4)` dwords and shift the whole window so the packed stream starts at the element (FUZZ-5, leftover from #234). The 10:10:10:2 order is checked by `cs_fmt_1010102` in `tests/semantic/test_value_semantics.py` (the shader decodes the format, so a GPU run can't check it). Mid-dword spanning elements are checked by `tests/semantic/test_buffer_load_format.py` (`CrossingDwordBoundary`); repeat / UNORM / DST_SEL 1 by the SHADER-86 cases in the same file. | | Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). For a native Metal path, `tools/spirv_metal_set0.py` sizes set 0's runtime arrays from `vulkan_bindless.h` and moves each binding to its own argument-buffer ID range (binding b starts at the capacities of bindings 0..b-1 added up), to convert with SPIRV-Cross `--msl-decoration-binding`: SPIRV-Cross 1.4.363.0 otherwise puts every runtime array at one ID and comments all but one out as "Overlapping binding" (SHADER-161). `cs_imgstore` converted this way writes all 3×64 texels correctly in a native Metal dispatch on an Apple A18 Pro. | | Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1–4, i32 ×1–4 (formats 21/63/73/76), f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×1/2/4, uint8 ×4, unorm16 ×1/2/4, snorm16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm. Others give 0. Full-width SINT accesses preserve integer bits. D16 SINT loads saturate to signed 16-bit and D16 stores sign-extend, covered by the synthetic `cs_fmt_sint32.asm` readback. DST_SEL swizzle is applied (0→0, 1→1.0f for float/norm or integer 1 for UINT/SINT, 4..7→X..W). Missing channels repeat the format's own (component *c* = *c* mod *n*), measured on an RX 6700 (SHADER-86). UNORM/SNORM give the correctly rounded quotient by (2ⁿ−1), as the hardware does (0 mismatches vs hardware over 395,776 conversions on that GPU). It is built with integer ops (`Gen.norm_bits`): x/(2ⁿ−1) in binary is x's bits repeated, so a 64-bit multiply by the repeat pattern, `FindUMsb` and the round bit give the f32 exactly (the tail never ends, so there are no ties). `OpFDiv` is not enough on the GPU: Vulkan allows it 2.5 ULP, and on an RX 6700 (AMD Windows 26.11.2) and an RTX 5090 it returned the reciprocal-multiply bits (8_UNORM 130/256 exact, #599). Checked against exact values in `tests/semantic/test_norm_decode.py` (every value up to 8 bits, edges and the reciprocal-multiply misses for 10, 15 and 16 bits). 8_SNORM (2), 16_SNORM (8) and 8_8_SNORM (15) were missing until 2026-11-22 and decoded to 0. Format names list the channel widths from the top bit, so `2_10_10_10` (50) is R10G10B10A2 and `10_10_10_2` (44) has a 2-bit x (Mesa `gfx10_format_table.py`, `ac_formats.c`). Until 2026-11-22 the two were swapped, in stores too. Until 2026-11-21 an element that started mid-dword re-read dword 0 for its tail (`need` was `ceil(size/4)` and only the first dword was shifted); loads now take `need = ceil((byte_shift + size) / 4)` dwords and shift the whole window so the packed stream starts at the element (FUZZ-5, leftover from #234). The 10:10:10:2 order is checked by `cs_fmt_1010102` in `tests/semantic/test_value_semantics.py` (the shader decodes the format, so a GPU run can't check it). Mid-dword spanning elements are checked by `tests/semantic/test_buffer_load_format.py` (`CrossingDwordBoundary`); repeat / UNORM / DST_SEL 1 by the SHADER-86 cases in the same file. The `_xy` and `_xyz` forms (buffer and tbuffer) are GPU-checked by `cs_fmt_xy_xyz.asm`, whose words were measured natively on a Radeon 680M (gfx1035, RDNA2): they write only their 2 or 3 VGPRs, and missing channels repeat there too (TEST-185). | -| Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). | | Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, pad`. The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot. The shared SPIR-V lookup probes up to eight slots and returns index 0 on a miss. The runtime supplies a fallback at index 0 and maps live descriptor keys to bindless indices. | | Packed sample addresses | GFX10 `image_sample_d` with `a16` keeps the non-G16 gradients as f32 and packs the following coordinates as f16 pairs, following LLVM's GFX10 operand layout. `test_a16_sample_gradients_use_full_vgprs` checks the emitted gradient operands, and `ps_texture_grad_a16` checks coordinate selection with a single-mip texture on RTX 5080. The same holds for every extra argument before the coordinates (LLVM `getAddrSizeMIMGOp`: one word each, then the gradients, then the packed halves; llvm-mc takes `v[0:2]` for a 2D `image_sample_c_b ... a16`): an `image_sample_b` bias keeps its VGPR with the f16 in the low half, an `image_sample_c_lz` z-compare its f32 VGPR, and `image_sample_d_cl` its four f32 gradients, with the clamp the half right after the coordinates (an f16 pad may follow it). Until 2026-11-21 those were unpacked as pairs too, and the clamp was taken from the last half. GPU-checked on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06) with `ps_texture_bias_a16`, `ps_sample_c_lz_a16` (`vk_texture_test dref_a16`) and `ps_texture_grad_cl_a16`, which draws on the `--two-mip` texture with the clamp 0 on the left half and 1 on the right: 4096/4096 pixels exact each. The old reading got 4,032 bias pixels and both depth-compare results in 2,048 pixels wrong, a clamp taken from the pad read mip 1 on the left half, and the sample without its clamp mip 0 on the right half (2,048 pixels each). | | Vertex fetch | `s_swappc_b64` at the start of a VS calls a driver-generated fetch program that isn't in the blob. It's replaced by Vulkan vertex inputs: each `ISG1` input-signature element (DXBC container) becomes an input at **location = its D3D input register**, typed by its component type, and is written to **v(4 + 4·register + component)**. That rule was checked over all 788 fetch-calling shaders: in 783 every read-before-write VGPR is predicted by it (715 exact). Reads of components the element doesn't declare (e.g. `.w` of an `xyz` position, 3 VS) are allowed: the fetch returns the format defaults (0, 0, 1), and Vulkan fills a `vec4` input from a narrower format the same way. Inputs are declared as `vec4`. **The runtime must bind vertex buffers by the game's D3D12 input layout, location = input register.** | -| PS system inputs | v0–v1 = barycentrics (consumed by `v_interp`, which becomes attribute inputs). **v2.. = the `SV_Position` components the shader reads, packed in order**. Verified on 2,531 of 3,000 PS: the VGPRs they read before writing equal exactly the position components their input signature reads. Filled from `FragCoord`: xy/z directly, and **w directly too**, because AMD's position-w register holds 1/w (Mesa lowers `load_frag_coord_w_rcp` straight to `frag_pos[3]`, `ac_nir_lower_intrinsics_to_args.c`), the same as Vulkan's `FragCoord.w`. **Front face** follows the used position components when the signature declares `SV_IsFrontFace`, as ±1.0 (Mesa: `load_front_face` = `front_face > 0`). Only enabled inputs are packed, in hardware order (Mesa `radv_shader_args.c`: barycentric pairs, POS_X/Y/Z/W, FRONT_FACE, ANCILLARY, SAMPLE_COVERAGE, POS_FIXED_PT). That explains the earlier "unverified" shaders: 102 read pos.xy + front face, and 76 read pos.x/y/w + front face. **Raw barycentric reads** (321 PS, e.g. `v_readfirstlane_b32 s41, v1`): AMD interpolates P = P0 + i(P1 − P0) + j(P2 − P0), so i/j are the weights of vertices 1/2, which is `BaryCoordKHR.y`/`.z` (`VK_KHR_fragment_shader_barycentric`). GPU-checked with `runtime/test/shaders/ps_bary.asm`: raw i/j equal the interpolated weights on every pixel. This assumes the pair is perspective-center, the only pair this layout models. A PS that reads any other unexplained register inside the system-input range is still rejected (none left in the corpus). Reads past the last hardware input are values undefined on some path, so zero stands in for them. All register arrays start at zero, so translated shaders are deterministic. | -| Inputs and outputs | VS: `v0` = `VertexIndex` (**unverified**: if the console runs vertex shaders as NGG, the input VGPR layout differs). `exp pos0` → `Position`, `exp pos1..pos3` → `ClipDistance` / `CullDistance` (and `Layer`/`ViewportIndex` in VS when `pos1` is the misc vector), `exp paramN` → location N. RDNA2/GFX10 packs clip distances before cull distances contiguously across 4-component `pos` exports (up to 8 floats total), starting at `pos2` when a misc vector (`PointSize`, `EdgeFlag`, `ShadingRate`, `Layer`, `ViewportIndex`; GFX9+ packs `Layer` in `z[10:0]` and `ViewportIndex` in `z[19:16]`) occupies `pos1`, and at `pos1` otherwise (Mesa `src/amd/common/nir/ac_nir_prerast_utils.c`: `ac_nir_export_position`; AMD LLPC `lgc/lowering/LowerInOut.cpp`: `LowerInOut::visitReturnInst`). Slot assignment follows the DXBC `OSG1` signature (`SV_ClipDistance` = 2, `SV_CullDistance` = 3, `SV_RenderTargetArrayIndex` = 4, `SV_ViewportArrayIndex` = 5, `SV_ShadingRate` = 23), ordered by `(semantic_index, register, component)` with clip before cull; when `OSG1` is absent (or declares none of those system values), `pos1..pos3` exports are discarded. PS: `v_interp_*` attribute N → input location N (a location any `*_f16` interp reads is a `PerVertexKHR` array of the producer's raw words instead: see "16-bit interpolation"). A param channel carries the export's raw 32 bits either way. `exp mrtN` → location N, `exp mrtz` x → `FragDepth` when x is on and the export isn't `compr` (RGBA = Z, stencil, sample mask, alpha: Mesa `ac_get_spi_shader_z_format`; the 16-bit compressed mrtz holds stencil and sample mask and never Z, `ac_nir_lower_ps_late.c` `emit_ps_mrtz_export`). Until 2026-11-22 an mrtz export without a depth wrote one anyway (0.0, or an f16 half of the stencil word) and declared `DepthReplacing`. Checked by `tests/test_translate.py` (`test_mrtz_depth_only_from_an_enabled_x`). Stencil, sample mask and alpha exports aren't modelled. | -| 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/subrev/mul/max/min_f16`, `v_fmac_f16`, `v_cvt_f16_f32`, f16 unary) and **opsel-capable VOP3 ops** (`v_fma_f16`, `_e64` forms of the 16-bit integer ops) are **partial writes that keep the high half**. The **VOP2 (`_e32`) 16-bit integer ops** (`v_lshrrev_b16`…) define the whole register, so the high half is modelled as zero. An op_sel destination bit writes the high half. The translator used to clear the high half on f16 ops; that's fixed. **op_sel on f16 VOP3 ops** (`v_fma_f16`, `v_med3_f16`, `v_add/sub/subrev/mul/max/min_f16`, f16 unary, `v_fmac_f16`): bit i (i < number of sources) reads the high half of source i, the last bit writes the high half of the destination; neg/abs apply to the selected half. Source: Mesa ACO `can_use_opsel` and the RDNA2 ISA VOP3 `OP_SEL` field. Checked by the structural tests in `tests/test_f16_op_sel.py` (which half is read, where the result goes) and the value tests in `tests/test_f16_op_sel_values.py`. **Hardware-verified** on an AMD RX 6800 (gfx1030), the instructions run as a raw compute kernel in wave32 and in wave64 (IEEE off, DX10 clamp on, denormals kept, round to nearest; the bytes assemble identically for gfx1013 and gfx1030): **`v_med3_f16`** with all 16 `op_sel` patterns, with neg/abs on a selected high half, with `clamp`, and with the destination also a source; the **plain forms** `v_add/sub/mul/max/min_f16` (`_e32`, and `_e64` with neg/abs/`clamp`), `v_fmac_f16` (`_e32`, and `_e64` with neg/abs; the accumulator is the low half of the destination), `v_rndne/floor/ceil/trunc/fract/sqrt/rcp/rsq_f16` (`_e32` and `_e64`) and `v_cvt_f16_f32`: low halves in, low half out, high half of the destination kept. 336 words per wave size (plus `v_rsq_f16_e64` and `v_ceil_f16_e64` in a later run), all as the rule says and as the translator computes. **Vulkan** (AMD Radeon RX 6800, Windows, driver 26.11.2; the nine `ps_f16_*` fixtures also pass on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux): `ps_f16_med3_opsel`, `ps_f16_med3_mods`, `ps_f16_vop2`, `ps_f16_vop2b`, `ps_f16_vop1`, `ps_f16_vop1b`, whose expected words are the hardware ones (`tests/test_f16_hw_words.py` checks them against the rule and the translator without a GPU). **Not expressible, so not verified:** `op_sel` on the VOP2 and VOP1 ops in VOP3 encoding (`v_add/sub/mul/max/min_f16_e64`, `v_fmac_f16_e64`, the unary `_e64` forms, `v_cvt_f16_f32_e64`): llvm-mc 21 rejects the modifier for gfx1013 and gfx1030, and its disassembler prints bytes that have those bits set without it (`03 08 32 d5 01 05 02 00` comes back as `v_add_f16_e64 v3, v1, v2`). The translator's `op_sel` handling for these forms is therefore never reached from a disassembly listing and rests on the ISA field description alone; whether the hardware honours the bits there is unknown, and a blob that set them would be translated as if they were clear. Also unverified: NaN and denormal operands, other rounding and IEEE modes, outside the f16 transcendentals (measured, see the f16 transcendentals row). **Driver quirk (AMD Windows driver 26.11.1, RX 9070):** `valu_fuzz` f16 seed 3 programme 38 loses the high half of v26: `v_add_f16_e32 v26, v29, v32` then `v_sub_nc_u16_e64 v28, v32, v27 op_sel:[1,1,0]` then `v_add_f16_e64 v26, v26, v28` — the final add should keep `0xCD52` in the high half, but the GPU returns `0xEEEEEEEE` (native) / `0x00000000` (`--emulate`), all 64 threads. Bisected to the pair: the add's two sources must both have been produced by earlier partial writes; either alone, a NaN input alone, or `dst==src0` alone all pass. The emitted SPIR-V was checked with `spirv-dis` in both modes: the keep (load old v26, `AND 0xFFFF0000`, `OR` new low half, store to index 26) is present and correctly addressed, so the translator is clear and this is the driver miscompiling the pattern. Minimal reproducer: the three ops above with programme 38's inits (v26 `0xCD524000`, v28 `0xC692D243`, v29 `0xBC004200`, v32 `0xB35ABD4B`, v27 `0xB48ABA06`). Pinned by `tests/test_values.py` (`v_add_f16_e64_keep_hi`, `v_add_f16_e32_keep_hi`), which check the translator's keep, not the driver. Found and bisected by 1TrickOmen, reported on #634. | -| PS system inputs | v0–v1 = barycentrics (consumed by `v_interp`, which becomes attribute inputs). **v2.. = the `SV_Position` components the shader reads, packed in order**. Verified on 2,531 of 3,000 PS: the VGPRs they read before writing equal exactly the position components their input signature reads. Filled from `FragCoord`: xy/z directly, and **w directly too**, because AMD's position-w register holds 1/w (Mesa lowers `load_frag_coord_w_rcp` straight to `frag_pos[3]`, `ac_nir_lower_intrinsics_to_args.c`), the same as Vulkan's `FragCoord.w`. **Front face** follows the used position components when the signature declares `SV_IsFrontFace`, as ±1.0 (Mesa: `load_front_face` = `front_face > 0`). Only enabled inputs are packed, in hardware order (Mesa `radv_shader_args.c`: barycentric pairs, POS_X/Y/Z/W, FRONT_FACE, ANCILLARY, SAMPLE_COVERAGE, POS_FIXED_PT). That explains the earlier "unverified" shaders: 102 read pos.xy + front face, and 76 read pos.x/y/w + front face. **Raw barycentric reads** (321 PS, e.g. `v_readfirstlane_b32 s41, v1`): AMD interpolates P = P0 + i(P1 − P0) + j(P2 − P0), so i/j are the weights of vertices 1/2, which is `BaryCoordKHR.y`/`.z` (`VK_KHR_fragment_shader_barycentric`). GPU-checked with `runtime/test/shaders/ps_bary.asm`: raw i/j equal the interpolated weights on every pixel. The pair is perspective-center, the only pair this layout models; that holds for every corpus PS (row "PS interpolation modes"). A PS that reads any other unexplained register inside the system-input range is still rejected (none left in the corpus). Reads past the last hardware input are values undefined on some path, so zero stands in for them. All register arrays start at zero, so translated shaders are deterministic. | -| Inputs and outputs | VS: `v0` = `VertexIndex` (**unverified**: if the console runs vertex shaders as NGG, the input VGPR layout differs). `exp pos0` → `Position`, `exp pos1..pos3` → `ClipDistance` / `CullDistance` (and `Layer`/`ViewportIndex` in VS when `pos1` is the misc vector), `exp paramN` → location N. RDNA2/GFX10 packs clip distances before cull distances contiguously across 4-component `pos` exports (up to 8 floats total), starting at `pos2` when a misc vector (`PointSize`, `EdgeFlag`, `ShadingRate`, `Layer`, `ViewportIndex`; GFX9+ packs `Layer` in `z[10:0]` and `ViewportIndex` in `z[19:16]`) occupies `pos1`, and at `pos1` otherwise (Mesa `src/amd/common/nir/ac_nir_prerast_utils.c`: `ac_nir_export_position`; AMD LLPC `lgc/lowering/LowerInOut.cpp`: `LowerInOut::visitReturnInst`). Slot assignment follows the DXBC `OSG1` signature (`SV_ClipDistance` = 2, `SV_CullDistance` = 3, `SV_RenderTargetArrayIndex` = 4, `SV_ViewportArrayIndex` = 5, `SV_ShadingRate` = 23), ordered by `(semantic_index, register, component)` with clip before cull; when `OSG1` is absent (or declares none of those system values), `pos1..pos3` exports are discarded. PS: `v_interp_*` attribute N → input location N. `exp mrtN` → location N, `exp mrtz` x → `FragDepth` when x is on and the export isn't `compr` (RGBA = Z, stencil, sample mask, alpha: Mesa `ac_get_spi_shader_z_format`; the 16-bit compressed mrtz holds stencil and sample mask and never Z, `ac_nir_lower_ps_late.c` `emit_ps_mrtz_export`). Until 2026-11-22 an mrtz export without a depth wrote one anyway (0.0, or an f16 half of the stencil word) and declared `DepthReplacing`. Checked by `tests/test_translate.py` (`test_mrtz_depth_only_from_an_enabled_x`). Stencil, sample mask and alpha exports aren't modelled. | -| 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/subrev/mul/max/min_f16`, `v_fmac_f16`, `v_cvt_f16_f32`, f16 unary) and **opsel-capable VOP3 ops** (`v_fma_f16`, `_e64` forms of the 16-bit integer ops) are **partial writes that keep the high half**. The **VOP2 (`_e32`) 16-bit integer ops** (`v_lshrrev_b16`…) define the whole register, so the high half is modelled as zero. An op_sel destination bit writes the high half. The translator used to clear the high half on f16 ops; that's fixed. **op_sel on f16 VOP3 ops** (`v_fma_f16`, `v_med3_f16`, `v_add/sub/subrev/mul/max/min_f16`, f16 unary, `v_fmac_f16`): bit i (i < number of sources) reads the high half of source i, the last bit writes the high half of the destination; neg/abs apply to the selected half. Source: Mesa ACO `can_use_opsel` and the RDNA2 ISA VOP3 `OP_SEL` field. Checked by the structural tests in `tests/test_f16_op_sel.py` (which half is read, where the result goes) and the value tests in `tests/test_f16_op_sel_values.py`. **Hardware-verified** on an AMD RX 6800 (gfx1030), the instructions run as a raw compute kernel in wave32 and in wave64 (IEEE off, DX10 clamp on, denormals kept, round to nearest; the bytes assemble identically for gfx1013 and gfx1030): **`v_med3_f16`** with all 16 `op_sel` patterns, with neg/abs on a selected high half, with `clamp`, and with the destination also a source; the **plain forms** `v_add/sub/mul/max/min_f16` (`_e32`, and `_e64` with neg/abs/`clamp`), `v_fmac_f16` (`_e32`, and `_e64` with neg/abs; the accumulator is the low half of the destination), `v_rndne/floor/ceil/trunc/fract/sqrt/rcp/rsq_f16` (`_e32` and `_e64`) and `v_cvt_f16_f32`: low halves in, low half out, high half of the destination kept. 336 words per wave size (plus `v_rsq_f16_e64` and `v_ceil_f16_e64` in a later run), all as the rule says and as the translator computes. **Vulkan** (AMD Radeon RX 6800, Windows, driver 26.11.2; the nine `ps_f16_*` fixtures also pass on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux): `ps_f16_med3_opsel`, `ps_f16_med3_mods`, `ps_f16_vop2`, `ps_f16_vop2b`, `ps_f16_vop1`, `ps_f16_vop1b`, whose expected words are the hardware ones (`tests/test_f16_hw_words.py` checks them against the rule and the translator without a GPU). **Not expressible, so not verified:** `op_sel` on the VOP2 and VOP1 ops in VOP3 encoding (`v_add/sub/mul/max/min_f16_e64`, `v_fmac_f16_e64`, the unary `_e64` forms, `v_cvt_f16_f32_e64`): llvm-mc 21 rejects the modifier for gfx1013 and gfx1030, and its disassembler prints bytes that have those bits set without it (`03 08 32 d5 01 05 02 00` comes back as `v_add_f16_e64 v3, v1, v2`). The translator's `op_sel` handling for these forms is therefore never reached from a disassembly listing and rests on the ISA field description alone; whether the hardware honours the bits there is unknown, and a blob that set them would be translated as if they were clear. Also unverified: NaN and denormal operands, other rounding and IEEE modes, outside the f16 transcendentals (measured, see the f16 transcendentals row). | | PS system inputs | v0–v1 = barycentrics (consumed by `v_interp`, which becomes attribute inputs). **v2.. = the `SV_Position` components the shader reads, packed in order**. Verified on 2,531 of 3,000 PS: the VGPRs they read before writing equal exactly the position components their input signature reads. Filled from `FragCoord`: xy/z directly, and **w directly too**, because AMD's position-w register holds 1/w (Mesa lowers `load_frag_coord_w_rcp` straight to `frag_pos[3]`, `ac_nir_lower_intrinsics_to_args.c`), the same as Vulkan's `FragCoord.w`. **Front face** follows the used position components when the signature declares `SV_IsFrontFace`, as ±1.0 (Mesa: `load_front_face` = `front_face > 0`). Only enabled inputs are packed, in hardware order (Mesa `radv_shader_args.c`: barycentric pairs, POS_X/Y/Z/W, FRONT_FACE, ANCILLARY, SAMPLE_COVERAGE, POS_FIXED_PT). That explains the earlier "unverified" shaders: 102 read pos.xy + front face, and 76 read pos.x/y/w + front face. **Raw barycentric reads** (321 PS, e.g. `v_readfirstlane_b32 s41, v1`): AMD interpolates P = P0 + i(P1 − P0) + j(P2 − P0), so i/j are the weights of vertices 1/2, which is `BaryCoordKHR.y`/`.z` (`VK_KHR_fragment_shader_barycentric`). GPU-checked with `runtime/test/shaders/ps_bary.asm`: raw i/j equal the interpolated weights on every pixel. The pair is perspective-center, the only pair this layout models; that holds for every corpus PS (row "PS interpolation modes"). A PS that reads any other unexplained register inside the system-input range is still rejected (none left in the corpus). Reads past the last hardware input are values undefined on some path, so zero stands in for them. All register arrays start at zero, so translated shaders are deterministic. | | Inputs and outputs | VS: `v0` = `VertexIndex` (**unverified**: if the console runs vertex shaders as NGG, the input VGPR layout differs). `exp pos0` → `Position`, `exp pos1..pos3` → `ClipDistance` / `CullDistance` (and `Layer`/`ViewportIndex` in VS when `pos1` is the misc vector), `exp paramN` → location N. RDNA2/GFX10 packs clip distances before cull distances contiguously across 4-component `pos` exports (up to 8 floats total), starting at `pos2` when a misc vector (`PointSize`, `EdgeFlag`, `ShadingRate`, `Layer`, `ViewportIndex`; GFX9+ packs `Layer` in `z[10:0]` and `ViewportIndex` in `z[19:16]`) occupies `pos1`, and at `pos1` otherwise (Mesa `src/amd/common/nir/ac_nir_prerast_utils.c`: `ac_nir_export_position`; AMD LLPC `lgc/lowering/LowerInOut.cpp`: `LowerInOut::visitReturnInst`). Slot assignment follows the DXBC `OSG1` signature (`SV_ClipDistance` = 2, `SV_CullDistance` = 3, `SV_RenderTargetArrayIndex` = 4, `SV_ViewportArrayIndex` = 5, `SV_ShadingRate` = 23), ordered by `(semantic_index, register, component)` with clip before cull; when `OSG1` is absent (or declares none of those system values), `pos1..pos3` exports are discarded. PS: `v_interp_*` attribute N → input location N (a location any `*_f16` interp reads is a `PerVertexKHR` array of the producer's raw words instead: see "16-bit interpolation"). A param channel carries the export's raw 32 bits either way. `exp mrtN` → location N, `exp mrtz` x → `FragDepth` when x is on and the export isn't `compr` (RGBA = Z, stencil, sample mask, alpha: Mesa `ac_get_spi_shader_z_format`; the 16-bit compressed mrtz holds stencil and sample mask and never Z, `ac_nir_lower_ps_late.c` `emit_ps_mrtz_export`). Until 2026-11-22 an mrtz export without a depth wrote one anyway (0.0, or an f16 half of the stencil word) and declared `DepthReplacing`. Checked by `tests/test_translate.py` (`test_mrtz_depth_only_from_an_enabled_x`). Stencil, sample mask and alpha exports aren't modelled. | | 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/subrev/mul/max/min_f16`, `v_fmac_f16`, `v_cvt_f16_f32`, f16 unary) and **opsel-capable VOP3 ops** (`v_fma_f16`, `_e64` forms of the 16-bit integer ops) are **partial writes that keep the high half**. The **VOP2 (`_e32`) 16-bit integer ops** (`v_lshrrev_b16`…) define the whole register, so the high half is modelled as zero. An op_sel destination bit writes the high half. The translator used to clear the high half on f16 ops; that's fixed. **op_sel on f16 VOP3 ops** (`v_fma_f16`, `v_med3_f16`, `v_add/sub/subrev/mul/max/min_f16`, f16 unary, `v_fmac_f16`): bit i (i < number of sources) reads the high half of source i, the last bit writes the high half of the destination; neg/abs apply to the selected half. Source: Mesa ACO `can_use_opsel` and the RDNA2 ISA VOP3 `OP_SEL` field. Checked by the structural tests in `tests/test_f16_op_sel.py` (which half is read, where the result goes) and the value tests in `tests/test_f16_op_sel_values.py`. **Hardware-verified** on an AMD RX 6800 (gfx1030), the instructions run as a raw compute kernel in wave32 and in wave64 (IEEE off, DX10 clamp on, denormals kept, round to nearest; the bytes assemble identically for gfx1013 and gfx1030): **`v_med3_f16`** with all 16 `op_sel` patterns, with neg/abs on a selected high half, with `clamp`, and with the destination also a source; the **plain forms** `v_add/sub/mul/max/min_f16` (`_e32`, and `_e64` with neg/abs/`clamp`), `v_fmac_f16` (`_e32`, and `_e64` with neg/abs; the accumulator is the low half of the destination), `v_rndne/floor/ceil/trunc/fract/sqrt/rcp/rsq_f16` (`_e32` and `_e64`) and `v_cvt_f16_f32`: low halves in, low half out, high half of the destination kept. 336 words per wave size (plus `v_rsq_f16_e64` and `v_ceil_f16_e64` in a later run), all as the rule says and as the translator computes. **Vulkan** (AMD Radeon RX 6800, Windows, driver 26.11.2; the nine `ps_f16_*` fixtures also pass on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux): `ps_f16_med3_opsel`, `ps_f16_med3_mods`, `ps_f16_vop2`, `ps_f16_vop2b`, `ps_f16_vop1`, `ps_f16_vop1b`, whose expected words are the hardware ones (`tests/test_f16_hw_words.py` checks them against the rule and the translator without a GPU). **Not expressible, so not verified:** `op_sel` on the VOP2 and VOP1 ops in VOP3 encoding (`v_add/sub/mul/max/min_f16_e64`, `v_fmac_f16_e64`, the unary `_e64` forms, `v_cvt_f16_f32_e64`): llvm-mc 21 rejects the modifier for gfx1013 and gfx1030, and its disassembler prints bytes that have those bits set without it (`03 08 32 d5 01 05 02 00` comes back as `v_add_f16_e64 v3, v1, v2`). The translator's `op_sel` handling for these forms is therefore never reached from a disassembly listing and rests on the ISA field description alone; whether the hardware honours the bits there is unknown, and a blob that set them would be translated as if they were clear. Also unverified: NaN and denormal operands, other rounding and IEEE modes, outside the f16 transcendentals (measured, see the f16 transcendentals row). **Driver quirk (AMD Windows driver 26.11.1, RX 9070):** `valu_fuzz` f16 seed 3 programme 38 loses the high half of v26: `v_add_f16_e32 v26, v29, v32` then `v_sub_nc_u16_e64 v28, v32, v27 op_sel:[1,1,0]` then `v_add_f16_e64 v26, v26, v28` — the final add should keep `0xCD52` in the high half, but the GPU returns `0xEEEEEEEE` (native) / `0x00000000` (`--emulate`), all 64 threads. Bisected to the pair: the add's two sources must both have been produced by earlier partial writes; either alone, a NaN input alone, or `dst==src0` alone all pass. The emitted SPIR-V was checked with `spirv-dis` in both modes: the keep (load old v26, `AND 0xFFFF0000`, `OR` new low half, store to index 26) is present and correctly addressed, so the translator is clear and this is the driver miscompiling the pattern. Minimal reproducer: the three ops above with programme 38's inits (v26 `0xCD524000`, v28 `0xC692D243`, v29 `0xBC004200`, v32 `0xB35ABD4B`, v27 `0xB48ABA06`). Pinned by `tests/test_values.py` (`v_add_f16_e64_keep_hi`, `v_add_f16_e32_keep_hi`), which check the translator's keep, not the driver. Found and bisected by 1TrickOmen, reported on #634. | @@ -270,14 +258,11 @@ How the generated SPIR-V expects the runtime to work: | SCC from scalar ALU | `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32` and `s_lshl/lshr_b32` set SCC = result ≠ 0, `s_add/sub_i32` and `s_addk_i32` set it to signed overflow, `s_min_u32`/`s_max_u32` to S0 < S1 / S0 > S1, and `s_min_i32`/`s_max_i32` to the same compared signed: SCC is 1 when S0 is the one chosen, and a tie chooses S1 (RDNA2 ISA, S_MIN_I32: D = S0 < S1 ? S0 : S1, SCC = 1 if S0 is chosen). **Before this fix these ops left SCC unchanged**, so a following `s_cbranch_scc*` read a stale flag, and until 2026-11-21 `s_min_i32`/`s_max_i32` set SCC on a tie. 32-bit scalar shifts now mask the amount to 5 bits. GPU-checked with `runtime/test/shaders/ps_scc.asm` and `ps_scc_minmax.asm` (NVIDIA GeForce RTX 2060 SUPER, Linux, driver 620.70.06: 4096/4096 pixels exact, and all 4096 differ with the old translator). **On lane masks in a wave32 program** (a source is EXEC, VCC or a mask SGPR, or the result goes to EXEC) the 32-bit bitwise ops' result is the whole wave's mask, so SCC is a subgroup vote (`OpGroupNonUniformAny`), as for the `_b64` forms. Until 2026-11-22 each lane took its own bit: `s_and_b32 s0, vcc_lo, exec_lo; s_cbranch_scc0` skipped the block in lanes whose bit was 0, and a loop closed by `s_andn2_b32 exec_lo, ...; s_cbranch_scc1` let each lane leave early. Found and checked by `tools/cf_diff.py` (FUZZ-8, CPU differential against the ISA model); GPU test `runtime/test/shaders/ps_scc_mask32.asm` passes (s5 == 8 on 2,048 pixels, 192 of them with bit 0, and s5 == 7 on 2,048) on an NVIDIA RTX 4050 Laptop (Linux, driver 620.73.04, natively and under `LEONIDA_W64_EMULATE=1`) and an AMD Radeon 740M (RADV, Mesa 26.3.1), and on an RTX 2060 SUPER per #634. A 32-bit op on one half of a wave64 mask still takes the lane's bit (its SCC would be a vote of that half). | | Far branches | `s_getpc_b64; s_add_u32 K; s_addc_u32 0/−1; s_setpc_b64` on the same pair is a branch beyond `s_branch`'s ±32K-dword range. It's folded into one branch to (address after `s_getpc`) + K before CFG construction. | | No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`, `ds_nop`, `v_clrexcp`) | Instruction-cache invalidate, thread-trace data, end-of-code padding, the ISA version marker and the DS no-operation have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. `v_clrexcp` clears the TRAPSTS exception bits, which nothing translated reads (`s_getreg_b32` is unsupported and there are no traps), so it is a no-op too (since 2026-11-22; before, both it and `ds_nop` raised `Unsupported`). The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM/DS/VOP1. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). | -| Buffer format stores | `buffer_store_format_*` and `_d16_*` encode every format the loads decode (the same FORMATS table: f32/u32, f16, unorm/snorm 8/16/10-10-10-2, uint 8/16). 1–2-byte elements are merged into their dword with atomic and/or so neighbours are kept. The atomics use element 0 of the array at the aligned dword address, which also compiles on MoltenVK 1.4.0 (checked with `cs_store` on an Apple M3 Max and Mesa llvmpipe). d16 data is unpacked first (f16 → float for float kinds, 16-bit integers for integer kinds). Before this, only four f32 formats, rgba16f and rgba8 unorm were stored, and everything else silently stored nothing. GPU-checked with `runtime/test/shaders/cs_store.asm` (rgba8 unorm, R10G10B10A2 (`2_10_10_10`), two r16f halves of one dword, d16 rgba16f: exact, neighbours untouched). `buffer_load_format_d16_*` packs pairs the same way. UNORM/SNORM stores convert NaN to zero before clamping. On native gfx1036, `buffer_store_format_d16_xyzw` into RGBA8_UNORM/SNORM matched clamp, scale by 255/127 and round to nearest even for all 63,488 finite binary16 encodings. Both infinities saturated and all 2,046 NaNs stored zero in both wave32 and wave64. The translated sweep matched all 65,536 bytes per format on RTX 5080 and Radeon Graphics. A store with fewer components than its format writes the whole element, with 0 for the components it doesn't give (`_xy` into 32_32_32_32 leaves z = w = 0, `_xyz` into 16_16_16_16 leaves w = 0); into a one-channel format only x is written. Measured natively on a Radeon 680M (gfx1035, RDNA2), and GPU-checked by `cs_fmt_xy_xyz.asm` for 32_32_32_32, 16_16_16_16, 8_8_8_8 UNORM and UINT and 32 (TEST-185). Unsigned integer stores saturate to the destination channel width. On native gfx1036, RGBA8_UINT, RG16_UINT and RGBA16_UINT clipped overflowing inputs to 255 or 65535, with RGBA32_UINT as a full-width control. `tbuffer_store_format_*` is not translated. | -| Buffer format stores | `buffer_store_format_*` and `_d16_*` encode every format the loads decode (the same FORMATS table: f32/u32, f16, unorm/snorm 8/16/10-10-10-2, uint 8/16). 1–2-byte elements are merged into their dword with atomic and/or so neighbours are kept. The atomics use element 0 of the array at the aligned dword address, which also compiles on MoltenVK 1.4.0 (checked with `cs_store` on an Apple M3 Max and Mesa llvmpipe). d16 data is unpacked first (f16 → float for float kinds, 16-bit integers for integer kinds). Before this, only four f32 formats, rgba16f and rgba8 unorm were stored, and everything else silently stored nothing. GPU-checked with `runtime/test/shaders/cs_store.asm` (rgba8 unorm, R10G10B10A2 (`2_10_10_10`), two r16f halves of one dword, d16 rgba16f: exact, neighbours untouched). `buffer_load_format_d16_*` packs pairs the same way. UNORM/SNORM stores convert NaN to zero before clamping. On native gfx1036, `buffer_store_format_d16_xyzw` into RGBA8_UNORM/SNORM matched clamp, scale by 255/127 and round to nearest even for all 63,488 finite binary16 encodings. Both infinities saturated and all 2,046 NaNs stored zero in both wave32 and wave64. The translated sweep matched all 65,536 bytes per format on RTX 5080 and Radeon Graphics. For normalized stores with format 56 (8/8/8/8) or 50 (10/10/10/2), a Z,Y,X,W descriptor exchanges the red and blue memory fields after filling absent input components with zero. Native gfx1036 confirmed both channel orders at all four instruction widths for packed and ordinary stores in wave32 and wave64. | +| Buffer format stores | `buffer_store_format_*` and `_d16_*` encode every format the loads decode (the same FORMATS table: f32/u32, f16, unorm/snorm 8/16/10-10-10-2, uint 8/16). 1–2-byte elements are merged into their dword with atomic and/or so neighbours are kept. The atomics use element 0 of the array at the aligned dword address, which also compiles on MoltenVK 1.4.0 (checked with `cs_store` on an Apple M3 Max and Mesa llvmpipe). d16 data is unpacked first (f16 → float for float kinds, 16-bit integers for integer kinds). Before this, only four f32 formats, rgba16f and rgba8 unorm were stored, and everything else silently stored nothing. GPU-checked with `runtime/test/shaders/cs_store.asm` (rgba8 unorm, R10G10B10A2 (`2_10_10_10`), two r16f halves of one dword, d16 rgba16f: exact, neighbours untouched). `buffer_load_format_d16_*` packs pairs the same way. UNORM/SNORM stores convert NaN to zero before clamping. On native gfx1036, `buffer_store_format_d16_xyzw` into RGBA8_UNORM/SNORM matched clamp, scale by 255/127 and round to nearest even for all 63,488 finite binary16 encodings. Both infinities saturated and all 2,046 NaNs stored zero in both wave32 and wave64. The translated sweep matched all 65,536 bytes per format on RTX 5080 and Radeon Graphics. A store with fewer components than its format writes the whole element, with 0 for the components it doesn't give (`_xy` into 32_32_32_32 leaves z = w = 0, `_xyz` into 16_16_16_16 leaves w = 0); into a one-channel format only x is written. Measured natively on a Radeon 680M (gfx1035, RDNA2), and GPU-checked by `cs_fmt_xy_xyz.asm` for 32_32_32_32, 16_16_16_16, 8_8_8_8 UNORM and UINT and 32 (TEST-185). Unsigned integer stores saturate to the destination channel width. On native gfx1036, RGBA8_UINT, RG16_UINT and RGBA16_UINT clipped overflowing inputs to 255 or 65535, with RGBA32_UINT as a full-width control. For normalized stores with format 56 (8/8/8/8) or 50 (10/10/10/2), a Z,Y,X,W descriptor exchanges the red and blue memory fields after filling absent input components with zero. Native gfx1036 confirmed both channel orders at all four instruction widths for packed and ordinary stores in wave32 and wave64. `tbuffer_store_format_*` is not translated. | | `s_lshl1..4_add_u32` | D = (S0 << N) + S1. SCC = the sum taken in 64 bits is ≥ 2³², so a bit shifted out of S0 sets it as well as a carry out of the add (RDNA ISA pseudocode: `tmp = (64'U(S0) << N) + 64'U(S1)`). Checked on the CPU by `tests/semantic/test_salu_lshl_add.py`. **Hardware-verified** on the same gfx1100 part through `tools/hw_oracle`: `s_lshl1_add_u32(0x80000000, 0)` = 0 with SCC = 1 (the bit shifted out of S0 sets it, with no carry out of the add), `s_lshl2_add_u32(5, 3)` = 0x17 with SCC = 0, `s_lshl4_add_u32(1, 0)` = 0x10. | | Other additions | `image_gather4_l(_o)`: no explicit-LOD gather in core Vulkan, so four `OpImageFetch` at mip `Floor(clamp(LOD, S# MIN_LOD, MAX_LOD) + 0.5)` (ties up, as native) in gather order. With `d16` those four taps round to binary16 and pack low half first into two consecutive VGPRs. The packed words and the first untouched VGPR were checked with `ps_gather_wrap.asm` on RTX 5080 and Radeon Graphics. Each of the four texel coordinates goes through the S#'s own address mode, read from S# word0 (`CLAMP_X` = bits [2:0], `CLAMP_Y` = [5:3]; fields from Mesa `src/amd/registers/gfx10-rsrc.json`, values `SQ_TEX_*` in Mesa `gfx6.json`, matching RADV's `radv_tex_wrap` mapping of Vulkan address modes): 0 wrap (`c mod n`), 1 mirror (`c mod 2n`, reflected), 2 clamp to the last texel, 3 mirror-once (`-1-c` for negative `c`, then clamped), as in Vulkan's address-mode definitions. A literal S# (`s_mov_b32` earlier in the block) is decoded at translation time; otherwise the mode is read from the SGPR at run time. A literal S# with a border mode (4-7: half-border, border colour) or `FORCE_UNNORMALIZED` is `Unsupported`; a run-time S# can't be judged, so modes 4-7 act as clamp-to-edge there and `FORCE_UNNORMALIZED` (word0 bit 15) is not applied (coordinates are still scaled by the image size). Those two are the remaining approximations; the unnormalized rules (texel-unit coordinates, mip 0) weren't confirmed on hardware, so they were not guessed. GPU-checked with `runtime/test/shaders/ps_gather_wrap.asm` (`vk_texture_test`; expected values derived by hand in its header; six border cases, three literal and three run-time S#) on AMD (Radeon 880M, wave64) and NVIDIA RTX 5070. `image_gather4_lz_o`: `OpImageGather … Offset`. `image_store` on 1D (bindings 17–19, `Image1D`) and with a16 coordinates. `ds_swizzle BITMASK_PERM` ("pippi" masks; GPU-checked). `v_add_f64`, `v_cvt_f32_f64` (`Float64`). `v_mul/mad_i32_i24`, `v_alignbyte_b32`, `v_xnor_b32`, `v_ffbh_i32`, `v_swap_b32`, `s_abs_i32`, `s_bfm_b32/b64`, 64-bit ordered and `v_cmpx` compares, 16-bit compares, 8/16-bit global loads, `neg(…)` constant operands (GPU-checked where listed in `runtime/test/shaders`). | | `v_mad_u64_u32`, `v_mad_i64_i32` | {sdst, D} = S0 × S1 + S2 as a 65-bit result (RDNA ISA pseudocode), the product unsigned or signed. sdst (a lane mask) gets bit 64 for active lanes and 0 for lanes off in EXEC (`EXEC[lane] ? bit64 : 0`, matching `v_cmp_*` and `*_co_*`): the carry out for u64, and for i64 the sign of the exact sum (bit 64 of a 65-bit two's-complement value), not a signed-overflow flag. `tools/lane_masks.py` tracks sdst as a lane mask (until 2026-11-22 it only matched `*_co_*`, so `s_bcnt1`/`s_ff1`/`v_mbcnt` on sdst read each lane's own mask word as plain data). `clamp` is rejected. Checked on the CPU by `tests/test_lane_masks.py`, `tests/semantic/test_alu_mad64.py` (including 64-lane `s_bcnt1_i32_b64`/`s_ff1_i32_b64` ballot tests), and `tests/semantic/test_carry_exec_mask.py` (EXEC masking on inactive lanes), **not yet GPU-verified**. | | Ray tracing | `image_bvh_intersect_ray` / `image_bvh64_intersect_ray` (64 CS: RT shadows) are one traversal step against AMD's hardware BVH node format. The traversal loop lives in the game's shader. The step is emulated over buffer reads following Mesa RADV's software path (`radv_nir_rt_common.c`, `intersect_ray_amd_software_box/_tri`; node layouts from `bvh_defines.h`). Node id = address >> 3 \| type (0–3 triangle, 4 box16, 5 box32). Box nodes give the four child ids, with misses and NaN boxes = `0xFFFFFFFF`, sorted by entry distance when descriptor bit 63 (box_sort_enable) is set. Triangle nodes read their three vertices from the slots the node type picks: TRI0 (0,1,2), TRI1 (1,3,2), TRI2 (2,3,4), TRI3 (2,4,0), 12 bytes each. They use the watertight test with RADV's shared edge/vertex tie-breaks and give (t/\|det\|, sign(det), b_i/\|det\|, b_j/\|det\|), or (inf, 1, 0, 0) on a miss. The weights i and j are chosen by the node type's byte of the triangle-ID word at +60: bits [1:0] and [3:2], 0/1/2 = vertex 0/1/2; `0x09` gives RADV's (v, w). Vertex slots and remap follow AMD GPURT (`CalcTriangleCompressionVertexIndices`, `SwizzleBarycentrics`) and the public XDXR software path ([bvh.md](bvh.md) §7a). These two references agree; no game BVH is decoded yet to count over. A GPU can't confirm the rule either, because every GPU runs this emulation and none runs the native instruction. `tests/semantic/test_image_bvh_tri.py` runs every node type and remap byte on the interpreter. The game's code divides by `.y` exactly as for the hardware's numerator/denominator. Address = descriptor base + ((node & ~7) << 3), base = descriptor bits [39:0] in 256-byte units (**assumption**: RADV only uses base 0). **The runtime must build the game's acceleration structures in this AMD node format** (RADV's GPU BVH builder produces it) wherever the game's D3D12 calls build them. Far branches with `s_sub_u32`/`s_subb_u32` (backward) are folded too. GPU-checked with `runtime/test/shaders/cs_bvh.asm`: sorted box children and the triangle result are exact. The 32-bit form (11 address dwords: the node id has no high dword) runs the same scene in `cs_bvh32.asm` and gives the same eight words. | -| Coverage | Every shader in the corpus translates. The remaining fidelity gap is wave64 cross-half code on 32-wide subgroups in VS/PS/GS; compute and mesh shaders are exact there with `--wave64-emulate` (see the wave-size and wave64 rows). | -| Ray tracing | `image_bvh_intersect_ray` / `image_bvh64_intersect_ray` (64 CS: RT shadows) are one traversal step against AMD's hardware BVH node format. The traversal loop lives in the game's shader. The step is emulated over buffer reads following Mesa RADV's software path (`radv_nir_rt_common.c`, `intersect_ray_amd_software_box/_tri`; node layouts from `bvh_defines.h`). Node id = address >> 3 \| type (0–3 triangle, 4 box16, 5 box32). Box nodes give the four child ids, with misses and NaN boxes = `0xFFFFFFFF`, sorted by entry distance when descriptor bit 63 (box_sort_enable) is set. Triangle nodes use the watertight test with RADV's shared edge/vertex tie-breaks and give (t/\|det\|, sign(det), v/\|det\|, w/\|det\|), or (inf, 1, 0, 0) on a miss. The game's code divides by `.y` exactly as for the hardware's numerator/denominator. Address = descriptor base + ((node & ~7) << 3), base = descriptor bits [39:0] in 256-byte units (**assumption**: RADV only uses base 0). **The runtime must build the game's acceleration structures in this AMD node format** (RADV's GPU BVH builder produces it) wherever the game's D3D12 calls build them. Far branches with `s_sub_u32`/`s_subb_u32` (backward) are folded too. GPU-checked with `runtime/test/shaders/cs_bvh.asm`: sorted box children and the triangle result are exact. | | Coverage | Every shader in the corpus translates. The remaining fidelity gap is wave64 cross-half code on 32-wide subgroups in VS/PS/GS (tier C of the *Wave64 graphics* row; tiers A and B are exact); compute and mesh shaders are exact there with `--wave64-emulate` (see the wave-size and wave64 rows). | | Flat pixel inputs | A pixel input location read only by `v_interp_mov_f32` is declared `Flat`. Locations read with `v_interp_p1/p2` remain interpolated. The `ps_flat` GPU test passes integer IDs through the first vertex alongside interpolated UVs. | | v_interp operand guards (SHADER-177) | The single-lane model reads the attribute's own value for `v_interp_p1/p2`, which is only right when the VGPR source really holds the barycentric coordinate that op interpolates with — **p1 reads I = v0 and p2 reads J = v1, per op** — and `v_interp_mov_f32` models only the p0 provoking vertex. A p1/p2 (f32 and f16 forms) whose source is not its own coordinate — v0 for p1, v1 for p2, each either the hardware register or a plain `v_mov_b32` copy rooted at it (the copy's single write in the whole shader, defined before the use, copy chains followed, and its source v0/v1 itself unwritten up to the copy: a copy of an already-overwritten v0/v1 carries a computed value — zeroing the source before copying renders (0,0) on hardware — while a write after the copy is fine, the copy saved the value) — is **Unsupported**, naming the register and the role, so a swapped p1(v1)/p2(v0) pair, a both-v0 pair, or a copy of an overwritten source is refused rather than silently mistranslated; `v_interp_mov_f32` with p10/p20 is **Unsupported**, naming the select. A **direct** v0/v1 read stays accepted even when the shader overwrites v0/v1 first (evaluate-at-offset/snapped barycentrics; up to 213 PS, #1218): modelling that computed value is the separate provenance follow-up. Zero corpus cost: over the 26,503-shader corpus every f32 I/J source is v0/v1 (117,001 / 116,997) except one PS whose four `v_interp_p2_f32` read J through `v_mov_b32 v14, v1` (its v1 unwritten up to the copy; the later overwrites are the saved-copy case), which the copy rule keeps translating (bit-identical .spv), every f16 source is v0/v1 (58,950 / 58,950), and all 6,926 `v_interp_mov_f32` use p0. Confirmed by `tests/semantic/test_interp_guards.py` (refusals name the operand and its role, including swapped and both-v0 pairs, a wrong-root copy, and a copy of an overwritten source; the copy, copy-chain, matching-role and saved-from-later-zero cases translate and compute; a second write or a dpp copy no longer qualifies; a mutation check that the guard consults the copy analysis) and by re-translating a 200-shader corpus slice plus that PS before and after: translated/valid counts and every .spv unchanged. | @@ -288,9 +273,7 @@ How the generated SPIR-V expects the runtime to work: | Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. | | Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. The instructions that fuse multiply-add (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fmamk_f32`, `v_fma_mix*`) round **once** on RDNA2 (measured on gfx1150 by `tools/f32_fuzz.py --oracle hw`: 72 of 72 cancellation probes fused). SPIR-V has two ways to say that. `GLSL.std.450 Fma` is the default (`--fma glsl`), but the Vulkan SPIR-V environment gives it the precision "inherited from `OpFMul` followed by `OpFAdd`", so a driver may legally round twice; `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice. `--fma khr` emits `OpFmaKHR` (`SPV_KHR_fma`, capability `FMAKHR`; "correctly rounded"), which needs `VK_KHR_shader_fma` with `shaderFmaFloat32` on the device. The index then lists capability `FMAKHR`, extension `SPV_KHR_fma` and feature `shaderFmaFloat32` for exactly the shaders that use it, and the output of every shader without a fused multiply-add is byte-identical under both options. `khr` is not the default because a device without the extension would fail pipeline creation; a runtime that knows its device has `shaderFmaFloat32` should translate with `--fma khr`. The f16 forms (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) never use either: they are exact round-to-odd arithmetic built from `OpFMul`/`OpFAdd` with `NoContraction` (`Gen.fma_f16_odd`), so a fused f32 `Fma` would not change them (`v_fma_mixlo_f16`/`v_fma_mixhi_f16` under the toward-zero MODE are the exception: `fma_mix_odd` needs the exact product error `Fma(x, y, -p)`, which is only guaranteed with `OpFmaKHR`), and an f16 `OpFmaKHR` (`shaderFmaFloat16`) is not used. There is no f64 fused multiply-add in the translator yet (`v_add_f64` only). | | `NoContraction` cost on MoltenVK (SHADER-234) | MoltenVK's SPIRV-Cross turns each `NoContraction` `OpFAdd`, `OpFSub` and `OpFMul` into a call to a `[[clang::optnone]]` helper (`spvFAdd`, `spvFSub`, `spvFMul`), and Metal does not inline it. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected. SPIRV-Cross `98cbb7c0` inlines the helpers from MSL 3.2 with bit-identical output, and MoltenVK on macOS 26 or newer compiles MSL 4.0. On an Apple M3 Max, a translated compute shader of `v_mul_f32`, `v_add_f32` and `v_sub_f32` in a loop took 7.6 to 15.7 times as long on the GPU with the optnone helpers as with `98cbb7c0`. With independent operations and no `NoContraction`, it took two thirds of the `98cbb7c0` time, which is the cost of the decoration itself ([measurement](https://github.com/ItsNotRexed/Leonida/issues/1380#issuecomment-7078722086)). The same `spvFMul` helper drops the sign of a -0 product (SHADER-182, #1376). | -| Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. Instructions that explicitly fuse multiply-add still emit `Fma`. | | `NoContraction` multiply on MoltenVK (SHADER-182) | On MoltenVK, a multiply whose exact product is a negative zero (`+0 × -1.5`, `-0 × 1.0`) returns +0 in f32, f16 and packed f16 (#1203). MoltenVK's SPIRV-Cross turns every `NoContraction` `OpFMul` into its `spvFMul` helper, which returns `fma(l, r, T(0))`. A -0 product plus +0 is +0. The f16 multiplies are `OpFMul` on `float` or `v2float`, so they take the same path. So does the product inside `fma_f16_odd`: `v_fma_f16`, `v_fmac_f16` and `v_pk_fma_f16` return +0 for a -0 product plus a -0 addend. SPIRV-Cross [300681bb](https://github.com/KhronosGroup/SPIRV-Cross/commit/300681bbcb8365a8d1eacdacdbdd0249bbf1d6b1) changes the addend to `T(-0.0)`. MoltenVK 1.4.2 has the old helper, and so does MoltenVK `main` at `5189f8de` (2026-10-13), which pins the parent commit `aa217aeb`. The translator does not change for this. `MVK_CONFIG_FAST_MATH_ENABLED=0` does not help, because the helper itself adds +0, and per #1203 neither does `SignedZeroInfNanPreserve` (#664). Measured on an Apple M3 Max (macOS 27.3): Metal keeps the sign for `a * b` and for `fma(a, b, -0.0)` with `MTLMathModeFast` and with `MTLMathModeSafe`, and loses it only with the +0 addend. With `valu_fuzz.py --family f16`, MoltenVK `5189f8de` as pinned matches 49/50 programs with `--seed 1 --wave 32`, 98/100 with `--seed 1 --emulate` and 98/100 with `--seed 4 --emulate`, and Homebrew MoltenVK 1.4.2 gives the same counts. Each mismatch is a -0 product read as +0. The same build with SPIRV-Cross `300681bb` matches 50/50, 100/100 and 100/100, as does KosmicKrisp (Mesa 26.3.1). For the FMA path, `--seed 330 --wave 32` with `--skip-op v_mul_f16 --skip-op v_pk_mul_f16` matches 49/50 with `aa217aeb` (a `v_fmac_f16` result) and 50/50 with `300681bb` and on KosmicKrisp. | -| `NoContraction` multiply on MoltenVK (SHADER-182) | On MoltenVK, a multiply with an exact zero result and a negative sign (`+0 × -1.5`, `-0 × 1.0`) returns +0 in f32, f16 and packed f16 (#1203). The f16 multiplies are `OpFMul` on `float`, so all three go through the same path. MoltenVK's SPIRV-Cross turns a `NoContraction` `OpFMul` into its `spvFMul` helper, which returns `fma(l, r, T(0))`. A -0 product plus +0 is +0. SPIRV-Cross [300681bb](https://github.com/KhronosGroup/SPIRV-Cross/commit/300681bbcb8365a8d1eacdacdbdd0249bbf1d6b1) changes the addend to `T(-0.0)`. MoltenVK 1.4.2 and MoltenVK `main` at `5189f8de` (2026-10-13), which pins the parent commit `aa217aeb`, have the old helper. The translator does not change for this. `MVK_CONFIG_FAST_MATH_ENABLED=0` and `SignedZeroInfNanPreserve` (#664) do not help on MoltenVK, because the helper itself adds +0. Measured on an Apple M3 Max (macOS 27.3). Metal keeps the sign for `a * b` and for `fma(a, b, -0.0)` with `MTLMathModeFast` and with `MTLMathModeSafe`, and loses it only with the +0 addend. With `valu_fuzz.py --family f16`, MoltenVK `5189f8de` matches 49/50 programs with `--seed 1 --wave 32`, 98/100 with `--seed 1 --emulate` and 98/100 with `--seed 4 --emulate`. Each mismatch is a -0 product read as +0. The same build with SPIRV-Cross `300681bb` matches 50/50, 100/100 and 100/100, as does KosmicKrisp (Mesa 26.3.1). Homebrew MoltenVK 1.4.2 gives the `aa217aeb` counts. | | MoltenVK fast-math (SHADER-234, NaN compares) | MoltenVK compiles every shader's MSL with Metal's fast-math on by default (`MVK_CONFIG_FAST_MATH_ENABLED`, default 1), and with it Metal folds an f32 compare of a NaN with itself as if the NaN were an ordinary number: `v_cmpx_eq_f32` and `v_cmpx_le_f32` on (NaN, NaN) give true where the ISA, AMD and NVIDIA give false (`ps_vcmpx_forms`, #1374: word 1 `0xf05e8e16`, want `0xf05e8a12`, bits 2 and 10; found by @zneel and @DomasUrbonas). The translation is not involved: the compare is `OpFOrdEqual` / `OpFOrdLessThanEqual`, and the MSL MoltenVK generates (`MVK_CONFIG_SHADER_DUMP_DIR`) is byte-identical with fast-math on and off, so it is Metal's compile option. `MVK_CONFIG_FAST_MATH_ENABLED=2` (on demand) does not help, because translated modules don't declare an execution mode that asks for IEEE behaviour; 0 does. The test tools (`runtime/test/vulkan_loader.h`, which every Vulkan test program uses to load MoltenVK) set `MVK_CONFIG_FAST_MATH_ENABLED=0` before MoltenVK reads its configuration, unless the variable is already set, so a user's own value still wins; the variable also reaches MoltenVK through the Vulkan loader. A runtime that loads MoltenVK on a Mac must do the same. Fast-math off does **not** remove the `[[clang::optnone]]` `spvFAdd`/`spvFSub`/`spvFMul` helpers SPIRV-Cross emits for `NoContraction` (11 calls in `ps_ops`'s MSL either way: their cost is the other part of SHADER-234), and it does not fix the row above (SHADER-182): `valu_fuzz.py --family f16 --seed 1` gives the same `v_mul_f16` +0 mismatch with fast-math on and off. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_vcmpx_forms` fails on all 4,096 pixels with fast-math on and matches all 4,096 with it off, natively and with wave64 emulation; no other `run_gpu_tests.py` result and none of the 25 `ctest` tests changes. | | Denormal flush and special results in `v_rcp_f32`, `v_rsq_f32`, `v_sqrt_f32`, `v_log_f32`, `v_exp_f32`, `v_rcp_iflag_f32` | Measured on an RX 6800 (gfx1030, not the console's gfx1013) with raw kernels in both wave sizes and all four IEEE/DX10_CLAMP combinations: all six read a denormal input as a zero of its sign and flush a denormal result, even with MODE's denormal field set to keep them. `v_rcp_f32(±0)` = ±inf, `v_rsq_f32(-0)` = -inf, `v_sqrt_f32(-0)` = -0, `v_log_f32(±0)` = -inf, `v_rcp_f32(FLT_MAX)` = +0, `v_exp_f32(-127)` = +0, `v_exp_f32(128)` = +inf, and every invalid result (`v_sqrt_f32`/`v_rsq_f32`/`v_log_f32` of a negative, …) is `0xffc00000`. Each is within 1 ulp of correctly rounded on the values tried, and `v_rcp_iflag_f32` is bit-identical to `v_rcp_f32`. **Not modelled yet:** the translator leaves all six on Vulkan's default denormal handling, and the ±0 and negative inputs above stay undefined in the emitted SPIR-V (`OpFDiv` by zero, `Sqrt`/`Log2` of a negative), as listed in the multiply-add and output modifiers row; the `clamp`/`omod` bits on `v_cvt_f32_*` and `v_rcp_iflag_f32` are modelled there. Source: [@shelbykb2's hardware words](https://github.com/ItsNotRexed/Leonida/issues/634#issuecomment-7074348963), not the ISA text. The corpus only ever writes MODE's FP_ROUND field and carries `mul:2`/`mul:4`/`div:2` on 102,365 float instructions (a compiler does not emit one that is ignored), so the inferred f32 state, IEEE off with denormals flushed, is the one to model. Corpus count (`tools/shader_profile.py`, 26,503 shaders; the shader count of each op deduplicates its `_e32`/`_e64` forms): `v_rcp_f32` 17,393 shaders / 424,863 occurrences, `v_rsq_f32` 17,221 / 269,310, `v_sqrt_f32` 14,511 / 201,422, `v_log_f32` 8,454 / 90,199, `v_exp_f32` 8,603 / 148,846, `v_rcp_iflag_f32` 7,395 / 34,852; 20,193 shaders (76.2%) use at least one, 1,169,492 occurrences (2.6% of the corpus's 44,406,870 instructions). | | f16 transcendentals (`v_exp_f16`, `v_log_f16`, `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`) | Measured on an RX 6700 XT (gfx1031, not the console's gfx1013) with `tools/f16_trans_sweep.py`: all 65,536 inputs of each op, wave32 and wave64 (identical on every input), five MODEs (FUZZ-29). With f16 denormals kept (`denorm_mode_16_64 = 3`, the assembler default and what the translator assumes), `v_exp/log/rcp/rsq/sqrt_f16` are **correctly rounded on every input that is not a NaN** (0 ulp). `v_sin/v_cos_f16` take turns and reduce them exactly over the whole f16 range (no ±256 limit): compared with sin/cos(2πx), every result for |x| > 1 is bit-exact, and for |x| ≤ 1 only 14 (sin) and 4 (cos) of 30,722 are 1 ulp off. So the translator's rule (widen to f32, the GLSL.std.450 function, round to nearest even back to f16) matches the hardware as far as the driver's f32 function is accurate. For sin/cos that holds only once the angle is reduced in turns first (#594): with the f32 product 6.2831855 · x, 16,366 sin and 2,036 cos inputs are more than 1 ulp off, up to 9,944 ulp (sin of 64,640 turns: 0.0267 instead of 0). With `denorm_mode_16_64 = 0`, a denormal operand reads as a zero of its sign, and a denormal result is written as a zero of its sign. That differs from the f32 ops in the row above, which flush in both modes. The f16 field of FP_ROUND is ignored: round toward zero gives the same words as round to nearest on every input. IEEE changes only signalling NaNs. With IEEE off they pass through unchanged; with IEEE on they are quieted (bit 9 set). Payload and sign are kept either way, and quiet NaNs pass unchanged in every mode. Where SPIR-V leaves the result undefined, the hardware gives: log(±0) = -inf, rcp(±0) = ±inf, rsq(+0) = +inf, rsq(-0) = -inf, sqrt(-0) = -0, and `0xfe00` for log/rsq/sqrt of a negative (-inf included) and for sin/cos(±inf). `v_exp_f16`/`v_log_f16` give the same counts on gfx1036 (RDNA2, AMD Windows driver; SHADER-135). **Not modelled yet:** `Gen.f16_bits` quiets every NaN (the hardware keeps a signalling NaN with IEEE off), and the undefined cases above are left to the driver. | @@ -303,8 +286,7 @@ How the generated SPIR-V expects the runtime to work: | Float min/max/med3 with NaN, `v_fract` | Measured on an AMD Radeon RX 6800 (gfx1030, not the console's gfx1013) with the hw-oracle tool from the AnyPS5 project, 537 input rows in all four IEEE/DX10_CLAMP combinations and in wave32 and wave64, the same for every combination with quiet NaNs. `v_min_f32`/`v_max_f32`, `v_min_f16`/`v_max_f16` and each half of `v_pk_min_f16`/`v_pk_max_f16`: one NaN operand gives the other operand, bits unchanged; both NaN give src0; -0 < +0. `v_min3`/`v_max3` = f(f(s0, s1), s2) with that min/max. `v_med3_f32`/`_f16`: with any NaN operand the result is min3(s0, s1, s2), otherwise the median (-0 < +0). `v_fract_f32` rounds x − floor(x) once and returns 0x3f7fffff (the largest float below 1) where that gives 1.0, e.g. fract(-1e-10); f16 gives 0x3bff; fract(-0) = +0, fract(±inf) = NaN, a NaN passes through. The translator emits `NMin`/`NMax` for these min/max ops (before: `FMin`/`FMax`, whose NaN result GLSL.std.450 leaves to the implementation). med3 is `FClamp(z, NMin(x, y), NMax(x, y))`, and when an operand can be a NaN, `OpIsNan` of each such operand (none for an inline or literal constant that is not a NaN) selects `NMin(NMin(x, y), z)` instead. `v_fract_f32` is `Fract` followed by `OpFOrdEqual` with 1.0 and an `OpSelect` of 0x3f7fffff, so the NaN of fract(±inf) is kept; `v_fract_f16` does the same before packing and then replaces a packed 0x3c00 with 0x3bff (not after an output multiplier, where 1.0 can be a true result). Other `FMin`/`FMax`/`FClamp` uses (the `clamp` bit, LOD and conversion clamps, `v_cvt_pk_u8_f32`, the BVH slab test) are unchanged. Not modelled: signalling NaNs under IEEE mode; NaN under the `clamp` bit (hardware gives +0 with DX10_CLAMP=1 and the NaN with DX10_CLAMP=0; the translator still emits `FClamp`); the NaN payload when both operands are NaN (`NMin` only promises a NaN); and without the `SignedZeroInfNanPreserve` execution mode Vulkan does not strictly guarantee NaN or signed-zero behaviour, so these rules hold where the driver keeps them. With an output modifier (`mul:2`, `mul:4`, `div:2`) on `v_fract_f16` the translator applies the modifier to the f32 fract before narrowing to f16; the hardware order of rounding and modifier for that case was not measured, so a result can differ by one f16 step for tiny negative inputs (e.g. x = -1e-4 with `div:2`). GPU-checked with `runtime/test/shaders/ps_fnan_med3.asm` and `ps_fnan_fract.asm` (inputs read from memory at run time) on an AMD Radeon RX 6800, Windows 11, driver 26.11.2: 4096/4096 pixels exact; on that driver the two med3 words differed before the change (0x40e00000 and 0x40600000 instead of 0x40a00000 and 0xc0200000), and so did the f16 fract word (0x3c00 instead of 0x3bff) once f16 results were narrowed with integer round-to-nearest; the f32 fract and the min/max words were already the hardware words there. `tests/semantic/test_float_nan_fract.py` runs the measured rows through the translator and the interpreter. | | Wave64 handling | Wave size is detected per shader from the code (64-bit EXEC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64` even when the mask is an ordinary SGPR pair; mesh shaders are always wave64). Until 2026-11-21 a mask-only wave64 program with no EXEC markers was translated as wave32, so `s_bcnt1_i32_b64` counted one half (#210). GPU-checked with `runtime/test/shaders/cs_w64_mask_detect.asm` (48 set bits of `(lane & 5) != 0`) on NVIDIA GeForce RTX 5060 under `LEONIDA_W64_EMULATE=1`. The hardware lane is exact in compute and mesh shaders (LocalInvocationIndex mod 64 or 32) and is used by `v_mbcnt` and EXEC writes. In other stages it's the subgroup lane. Constant EXEC writes (`s_mov_b32 exec_lo/exec_hi, K`) set each lane from its own bit of K, as `(K >> lane) & 1` (shift and mask: Intel's Windows driver evaluated `OpBitFieldUExtract` of a constant that fits in 16 bits with the lane taken mod 16, so `exec_lo = 0xffff` ran all 32 lanes; GPU-checked with `runtime/test/shaders/cs_exec_const.asm` on Intel UHD Graphics 770, driver 32.0.101.6129, and NVIDIA GeForce RTX 4080 SUPER); before, any non-zero constant turned every lane on. A register written to `exec_hi` sets lanes 32–63 only. VCC's halves follow the same rule while VCC holds a lane mask: a 32-bit write to `vcc_lo` sets lanes 0–31 of the mask and one to `vcc_hi` lanes 32–63 (until 2026-11-22 a `vcc_lo` write set all 64 lanes and a `vcc_hi` write never reached the mask that `s_cbranch_vccz`/`v_cndmask` read; CPU-checked by `tests/semantic/test_wave64_vcc_half_write.py`, not GPU-checked). GPU-checked with `runtime/test/shaders/cs_exec64.asm`: lanes 16–47 enabled from two constants, exact on a 32-wide-subgroup GPU. Still approximate on 32-wide subgroups: cross-lane ops between the two halves of a wave64 (readlane/permlane/DPP/shuffles across lane 31/32, wave-wide reductions). The metadata index marks every wave64 shader so a runtime can request `requiredSubgroupSize = 64` where supported (AMD), which makes those exact too. | | Lane select (`v_readlane_b32` / `v_writelane_b32`) | The lane is **S1[4:0] in wave32** and S1[5:0] in wave64, from an SGPR or a constant, and EXEC is ignored (RDNA 3 ISA guide pseudocode for both opcodes; RDNA 2 has the same encoding and gives no pseudocode). **Until #488 (SHADER-52) a wave32 shader masked with 63 as well**: a lane select of 32 or more wrote no lane, and a read shuffled from a lane past the end of a 32-wide subgroup, which SPIR-V leaves undefined (NVIDIA wraps it, so reads happened to come out right there). Found by the FUZZ-7 cross-lane fuzzer: 23 of 100 random wave32 programs, each minimized to `s_mov_b32 s28, K; v_writelane_b32 vD, x, s28` with K ≥ 32. GPU-checked with `runtime/test/shaders/cs_w32_lane_wrap.asm` (25 16 777 777) on NVIDIA GeForce RTX 5060 (#488) and RTX 4090 (subgroup 32, driver 621.14); `tests/test_translate.py` checks the masks in the SPIR-V, and `tests/semantic/test_wave32_lane_select.py` runs the shader across 32 lanes, where a mask of 63 is an out-of-range shuffle. | -| Wave64 emulation (`--wave64-emulate`) | Wave64 compute and mesh shaders exact on **any** subgroup size (32-wide NVIDIA, Intel, AMD in wave32 mode), with no subgroup operation at all. One invocation is still one lane. Everything a lane needs from the rest of its wave goes through a Workgroup buffer `%x_buf`: votes (`s_cbranch_vccz/vccnz/execz/execnz`, SCC of mask ops, `s_cmp` of masks), whole-mask words (`s_bcnt1`, `s_ff1`, `v_mbcnt`), `v_readlane`, `v_readfirstlane`, `ds_bpermute`, `ds_swizzle`, `v_permlane16/x16`. The program runs in rounds: in each round every wave that is neither done nor waiting at `s_barrier` runs one segment of its program (a basic block, cut at each cross-lane op), then the whole workgroup meets at one `OpControlBarrier` (Workgroup, AcquireRelease, workgroup + uniform + image memory) that sits in uniform control flow, because every invocation runs every round. A cross-lane op ends its segment after the lane has stored its value (per-lane data, double-buffered by round parity) or ORed its bit (two mask words per wave, three slots by round mod 3, each slot cleared two rounds after it was read); the code after it runs one round later, when all 64 lanes have written. SSA values live across a cut go through Function variables. `s_barrier` is a scheduler state: the wave stops running segments until every wave that isn't done is waiting, which is also how hardware counts finished waves. A memory access that conflicts with an earlier one in the same segment (read after write, write after read, write after write; LDS and buffer/image memory separately) starts a new round, so two halves of a wave in different subgroups access memory in instruction order, as the lanes of one hardware wave do; not ordered: scalar loads of memory the wave wrote, and sampling an image it wrote. The missing lanes of a partial last wave read as 0. Without the flag the output is unchanged, apart from two fixes that apply to every wave64 compute/mesh shader: `v_writelane_b32` selects the lane by the wave lane (on a 32-wide subgroup writes to lanes 32–63 were lost; `cs_w64x_writelane`), and `ds_bpermute_b32` (see the LDS row). Fewer rounds, same results: a whole-mask read (`s_bcnt1`, `v_mbcnt_lo/hi`, ...) of the value of the same register (or EXEC) that an earlier read in the block already exchanged reuses that exchange (the value's identity is the SSA id last stored to the register, forgotten at block start and at any label); and a block that ends in a voted branch (`s_cbranch_vccz/vccnz/execz/execnz`) runs its successor in the round that reads the vote, since that segment only reads the vote and picks the next block (an inner loop in the scheduler, flag `%x_chain`). Both rules are pinned by `cs_w64x_mask_reuse` (a mask register and EXEC rewritten between reads), `cs_w64x_mask_reuse2` (EXEC read twice, a read after a buffer store, one half of a mask pair rewritten while the other is kept, a voted branch whose successor starts with a load of the other half's earlier store) and `cs_w64x_chain_barrier` (a voted branch whose successor starts with `s_barrier`, two waves): expected values from the ISA, first run on the AMD 880M with its native 64-wide subgroup, then emulated on both GPUs; `tests/test_translate.py` counts the exchanges in the SPIR-V (one per value, a new one after a rewrite of the register or EXEC), and the translator refuses (`Unsupported`) a voted branch whose segment was not started by the vote's own round. `scripts/bench_wave64.py` times `cs_bench_mix` native and emulated and checks the emulated output bytes against the native AMD run. Cost: one workgroup barrier per segment, and `%x_buf` = (2·L + 6·W + 7) dwords for L invocations in W waves, counted in `lds_bytes`. GPU-checked on NVIDIA GeForce RTX 5070 Laptop (subgroup 32, driver 617.42) and AMD Radeon 880M (subgroup 64, AMD driver 26.11.2 LLPC): `check.py` 38/39 (the mesh test runs in the other script) and `scripts/run_gpu_tests.py` 40/40 on both with `LEONIDA_W64_EMULATE=1`, including every wave64 test (`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`) and the cross-half suite `cs_w64x_*` / `ms_w64x_ballot`: readlane and writelane at lanes ≥ 32, readfirstlane with only upper lanes active, branches voted by one lane of either half, ballot + `v_mbcnt_lo/hi` compaction over 64 lanes (also in a mesh shader, 4096/4096 pixels), a 128-thread workgroup whose two waves take different branches, `s_barrier` between waves with different loop counts, LDS read-after-write and write-after-read across the halves without a barrier, a load, ballot and load in one block, and a partial wave (group 40). Without the flag the same RTX 5070 passes 19/37 (the wave64 tests skip there). Not covered: VS/PS/GS (no workgroup memory or barrier there). Known driver bug: AMD's Windows shader compiler for RDNA2 crashes (access violation in `vkCreateComputePipelines`) on many emulated compute shaders with LDS (#857: drivers 32.0.21030 to 32.0.21045.29003, iGPUs and RX 6000; 23.20.44, RDNA3, RDNA4, RADV and NVIDIA are fine), so `make_game.py --wave64-emulate auto` leaves emulation off when the runtime's GPU is such a device and runs wave64 natively (`rdna2_amd_windows` in `tools/vk_subgroup_info.py`, by PCI device ID and driver ID). | -| Wave64 emulation (`--wave64-emulate`) | Wave64 compute and mesh shaders exact on **any** subgroup size (32-wide NVIDIA, Intel, AMD in wave32 mode), with no subgroup operation at all. One invocation is still one lane. Everything a lane needs from the rest of its wave goes through a Workgroup buffer `%x_buf`: votes (`s_cbranch_vccz/vccnz/execz/execnz`, SCC of mask ops, `s_cmp` of masks), whole-mask words (`s_bcnt1`, `s_ff1`, `v_mbcnt`), `v_readlane`, `v_readfirstlane`, `ds_bpermute`, `ds_swizzle`, `v_permlane16/x16`. The program runs in rounds: in each round every wave that is neither done nor waiting at `s_barrier` runs one segment of its program (a basic block, cut at each cross-lane op), then the whole workgroup meets at one `OpControlBarrier` (Workgroup, AcquireRelease, workgroup + uniform + image memory) that sits in uniform control flow, because every invocation runs every round. A cross-lane op ends its segment after the lane has stored its value (per-lane data, double-buffered by round parity) or ORed its bit (two mask words per wave, three slots by round mod 3, each slot cleared two rounds after it was read); the code after it runs one round later, when all 64 lanes have written. SSA values live across a cut go through Function variables. `s_barrier` is a scheduler state: the wave stops running segments until every wave that isn't done is waiting, which is also how hardware counts finished waves. A memory access that conflicts with an earlier one in the same segment (read after write, write after read, write after write; LDS and buffer/image memory separately) starts a new round, so two halves of a wave in different subgroups access memory in instruction order, as the lanes of one hardware wave do. A scalar load (`s_load*`, `s_buffer_load*`) counts as a buffer read: until #1587 it was left out, so a store and a later scalar load of the same address shared a segment and the half in the other subgroup could load before this half had stored (`valu_fuzz.py --family mem --emulate`: lanes 32-63 read the fill pattern after an `s_buffer_load`/`s_load` of the slot lane 0 had written, on RDNA1 RADV and an RTX 5060; `v_readfirstlane_b32`, which gives that slot, already reads the whole wave). Pinned by `tests/semantic/test_w64x_scalar_load_order.py` (no segment of the emitted rounds accesses buffer memory after a write or writes after a read; three of its five cases fail without the rule). Confirmed by that CPU test and the ordering argument above; the race does not show on an RX 7900 XTX (AMD 26.10.1 LLPC, Windows 11): `valu_fuzz.py --family mem --seed 5 --programs 21 --wave 64 --emulate` matches 21/21 before and after the rule (3 runs each), so a GPU reproduction on RDNA1/RADV (where #1587 was found) is still pending. Not ordered: sampling an image the wave wrote. The missing lanes of a partial last wave read as 0. Without the flag the output is unchanged, apart from two fixes that apply to every wave64 compute/mesh shader: `v_writelane_b32` selects the lane by the wave lane (on a 32-wide subgroup writes to lanes 32–63 were lost; `cs_w64x_writelane`), and `ds_bpermute_b32` (see the LDS row). Fewer rounds, same results: a whole-mask read (`s_bcnt1`, `v_mbcnt_lo/hi`, ...) of the value of the same register (or EXEC) that an earlier read in the block already exchanged reuses that exchange (the value's identity is the SSA id last stored to the register, forgotten at block start and at any label); and a block that ends in a voted branch (`s_cbranch_vccz/vccnz/execz/execnz`) runs its successor in the round that reads the vote, since that segment only reads the vote and picks the next block (an inner loop in the scheduler, flag `%x_chain`). Both rules are pinned by `cs_w64x_mask_reuse` (a mask register and EXEC rewritten between reads), `cs_w64x_mask_reuse2` (EXEC read twice, a read after a buffer store, one half of a mask pair rewritten while the other is kept, a voted branch whose successor starts with a load of the other half's earlier store) and `cs_w64x_chain_barrier` (a voted branch whose successor starts with `s_barrier`, two waves): expected values from the ISA, first run on the AMD 880M with its native 64-wide subgroup, then emulated on both GPUs; `tests/test_translate.py` counts the exchanges in the SPIR-V (one per value, a new one after a rewrite of the register or EXEC), and the translator refuses (`Unsupported`) a voted branch whose segment was not started by the vote's own round. `scripts/bench_wave64.py` times `cs_bench_mix` native and emulated and checks the emulated output bytes against the native AMD run. Cost: one workgroup barrier per segment, and `%x_buf` = (2·L + 6·W + 7) dwords for L invocations in W waves, counted in `lds_bytes`. GPU-checked on NVIDIA GeForce RTX 5070 Laptop (subgroup 32, driver 617.42) and AMD Radeon 880M (subgroup 64, AMD driver 26.11.2 LLPC): `check.py` 38/39 (the mesh test runs in the other script) and `scripts/run_gpu_tests.py` 40/40 on both with `LEONIDA_W64_EMULATE=1`, including every wave64 test (`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`) and the cross-half suite `cs_w64x_*` / `ms_w64x_ballot`: readlane and writelane at lanes ≥ 32, readfirstlane with only upper lanes active, branches voted by one lane of either half, ballot + `v_mbcnt_lo/hi` compaction over 64 lanes (also in a mesh shader, 4096/4096 pixels), a 128-thread workgroup whose two waves take different branches, `s_barrier` between waves with different loop counts, LDS read-after-write and write-after-read across the halves without a barrier, a load, ballot and load in one block, and a partial wave (group 40). Without the flag the same RTX 5070 passes 19/37 (the wave64 tests skip there). Not covered: VS/PS/GS (no workgroup memory or barrier there). | +| Wave64 emulation (`--wave64-emulate`) | Wave64 compute and mesh shaders exact on **any** subgroup size (32-wide NVIDIA, Intel, AMD in wave32 mode), with no subgroup operation at all. One invocation is still one lane. Everything a lane needs from the rest of its wave goes through a Workgroup buffer `%x_buf`: votes (`s_cbranch_vccz/vccnz/execz/execnz`, SCC of mask ops, `s_cmp` of masks), whole-mask words (`s_bcnt1`, `s_ff1`, `v_mbcnt`), `v_readlane`, `v_readfirstlane`, `ds_bpermute`, `ds_swizzle`, `v_permlane16/x16`. The program runs in rounds: in each round every wave that is neither done nor waiting at `s_barrier` runs one segment of its program (a basic block, cut at each cross-lane op), then the whole workgroup meets at one `OpControlBarrier` (Workgroup, AcquireRelease, workgroup + uniform + image memory) that sits in uniform control flow, because every invocation runs every round. A cross-lane op ends its segment after the lane has stored its value (per-lane data, double-buffered by round parity) or ORed its bit (two mask words per wave, three slots by round mod 3, each slot cleared two rounds after it was read); the code after it runs one round later, when all 64 lanes have written. SSA values live across a cut go through Function variables. `s_barrier` is a scheduler state: the wave stops running segments until every wave that isn't done is waiting, which is also how hardware counts finished waves. A memory access that conflicts with an earlier one in the same segment (read after write, write after read, write after write; LDS and buffer/image memory separately) starts a new round, so two halves of a wave in different subgroups access memory in instruction order, as the lanes of one hardware wave do. A scalar load (`s_load*`, `s_buffer_load*`) counts as a buffer read: until #1587 it was left out, so a store and a later scalar load of the same address shared a segment and the half in the other subgroup could load before this half had stored (`valu_fuzz.py --family mem --emulate`: lanes 32-63 read the fill pattern after an `s_buffer_load`/`s_load` of the slot lane 0 had written, on RDNA1 RADV and an RTX 5060; `v_readfirstlane_b32`, which gives that slot, already reads the whole wave). Pinned by `tests/semantic/test_w64x_scalar_load_order.py` (no segment of the emitted rounds accesses buffer memory after a write or writes after a read; three of its five cases fail without the rule). Confirmed by that CPU test and the ordering argument above; the race does not show on an RX 7900 XTX (AMD 26.10.1 LLPC, Windows 11): `valu_fuzz.py --family mem --seed 5 --programs 21 --wave 64 --emulate` matches 21/21 before and after the rule (3 runs each), so a GPU reproduction on RDNA1/RADV (where #1587 was found) is still pending. Not ordered: sampling an image the wave wrote. The missing lanes of a partial last wave read as 0. Without the flag the output is unchanged, apart from two fixes that apply to every wave64 compute/mesh shader: `v_writelane_b32` selects the lane by the wave lane (on a 32-wide subgroup writes to lanes 32–63 were lost; `cs_w64x_writelane`), and `ds_bpermute_b32` (see the LDS row). Fewer rounds, same results: a whole-mask read (`s_bcnt1`, `v_mbcnt_lo/hi`, ...) of the value of the same register (or EXEC) that an earlier read in the block already exchanged reuses that exchange (the value's identity is the SSA id last stored to the register, forgotten at block start and at any label); and a block that ends in a voted branch (`s_cbranch_vccz/vccnz/execz/execnz`) runs its successor in the round that reads the vote, since that segment only reads the vote and picks the next block (an inner loop in the scheduler, flag `%x_chain`). Both rules are pinned by `cs_w64x_mask_reuse` (a mask register and EXEC rewritten between reads), `cs_w64x_mask_reuse2` (EXEC read twice, a read after a buffer store, one half of a mask pair rewritten while the other is kept, a voted branch whose successor starts with a load of the other half's earlier store) and `cs_w64x_chain_barrier` (a voted branch whose successor starts with `s_barrier`, two waves): expected values from the ISA, first run on the AMD 880M with its native 64-wide subgroup, then emulated on both GPUs; `tests/test_translate.py` counts the exchanges in the SPIR-V (one per value, a new one after a rewrite of the register or EXEC), and the translator refuses (`Unsupported`) a voted branch whose segment was not started by the vote's own round. `scripts/bench_wave64.py` times `cs_bench_mix` native and emulated and checks the emulated output bytes against the native AMD run. Cost: one workgroup barrier per segment, and `%x_buf` = (2·L + 6·W + 7) dwords for L invocations in W waves, counted in `lds_bytes`. GPU-checked on NVIDIA GeForce RTX 5070 Laptop (subgroup 32, driver 617.42) and AMD Radeon 880M (subgroup 64, AMD driver 26.11.2 LLPC): `check.py` 38/39 (the mesh test runs in the other script) and `scripts/run_gpu_tests.py` 40/40 on both with `LEONIDA_W64_EMULATE=1`, including every wave64 test (`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`) and the cross-half suite `cs_w64x_*` / `ms_w64x_ballot`: readlane and writelane at lanes ≥ 32, readfirstlane with only upper lanes active, branches voted by one lane of either half, ballot + `v_mbcnt_lo/hi` compaction over 64 lanes (also in a mesh shader, 4096/4096 pixels), a 128-thread workgroup whose two waves take different branches, `s_barrier` between waves with different loop counts, LDS read-after-write and write-after-read across the halves without a barrier, a load, ballot and load in one block, and a partial wave (group 40). Without the flag the same RTX 5070 passes 19/37 (the wave64 tests skip there). Not covered: VS/PS/GS (no workgroup memory or barrier there). Known driver bug: AMD's Windows shader compiler for RDNA2 crashes (access violation in `vkCreateComputePipelines`) on many emulated compute shaders with LDS (#857: drivers 32.0.21030 to 32.0.21045.29003, iGPUs and RX 6000; 23.20.44, RDNA3, RDNA4, RADV and NVIDIA are fine), so `make_game.py --wave64-emulate auto` leaves emulation off when the runtime's GPU is such a device and runs wave64 natively (`rdna2_amd_windows` in `tools/vk_subgroup_info.py`, by PCI device ID and driver ID). | | Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one). The raw pair a PS reads ("PS system inputs": 321 PS) comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module then needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. The stage before the PS writes (1,0,0), (0,1,0), (0,0,1) at the triangle's three vertices: `tools/bary_fallback_gs.py` writes that pass-through geometry shader from the index (Position and the PS's input locations copied unchanged). Default (perspective) interpolation of those weights is the perspective-correct barycentric, the value `BaryCoordKHR` has, so `.y`/`.z` stay AMD's i/j; shaders that don't read the pair translate to the same module either way. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal, no barycentric extension; driver 560.94, Windows 10) with `LEONIDA_BARY_FALLBACK=1`: `ps_bary` 4096/4096 pixels exact, and `ps_uniform_branch` and `ps_scc_mask32` pass, through `run_gpu_tests.py` and `build.py` + `check.py`, with zero Khronos validation messages. Checked in `tests/semantic/test_bary_fallback.py`. For a known VS/PS pair, `python -I tools/bary_fallback_gs.py DIR --pair VS PS` builds `PS.bary_gs.clipN.spv`. It copies the producer’s `ClipDistance[N]` at each emitted vertex, using the VS index field `clip_distance_count`. On RTX 5080 and Radeon integrated graphics, two independently shifted clip planes yielded 512, 1024, 2048 or 4096 covered pixels, matching the native barycentric path. For a cull-only VS the pair writes `PS.bary_gs.cullN.spv` from `cull_distance_count`. A two-plane synthetic draw on the same GPUs covered 0 pixels when every vertex was negative for either plane and all 4096 when each plane had a nonnegative vertex. The helper rejects mixed clip/cull arrays. The runtime building that GS per pipeline is the follow-up (it needs the graphics pipelines of #291). | | Metadata index | `spirv/index.json`: one entry per translated shader with its stage, `wave64` / `subgroup_size`, SPIR-V capabilities and extensions, the Vulkan **features** to enable (barycentrics, interlock, mesh, geometry, Float64, Int64, buffer device address, write-without-format, `shaderFmaFloat32` for `--fma khr`, …), `needs_maintenance8`, the descriptor bindings it uses (set 0), push-constant size, `local_size`, `user_sgprs` (CS), `lds_bytes`, mesh `max_vertices`/`max_primitives`/`params`, geometry inputs/outputs, vertex-input locations and types, full `vertex_input_signature` (ISG1 register/mask/system-value/component-type, for PSO lookup), `wave64_emulated` (true for VS/PS/GS wave64, which the translator emits as per-subgroup code with no cross-half exchange, and for compute/mesh translated with `--wave64-emulate`; the runtime does not use it: it reads `wave64`, `subgroup_size` and `wave64_exchange`), `dynamic_format` (runtime V# FORMAT: codes outside FORMATS decode to 0) / `fixed_format_codes`, `src_sha256` and optional `fssm_sha256` (via `--fssm-dir`), PS system inputs, `bary_fallback_input` (`--bary-fallback`: the location of the barycentric input), `mesh_compute` (`--mesh-compute`: the slot layout and push-constant size), and input/output locations. A shader translated with `--wave64-emulate` carries `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none. Otherwise `subgroup_size` (64 for wave64, 32) is what the PSO asks for through `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo` where the device lists the stage in `requiredSubgroupSizeStages` (docs/d3d12_vulkan.md section 3.2): that list is the driver's, not "compute/mesh only". The AMD Windows driver reports FRAGMENT, COMPUTE, TASK and MESH (measured on a Radeon 880M, driver 26.11.2, sizes 32..64), and current Mesa RADV on GFX10+ reports COMPUTE, FRAGMENT and task/mesh (`src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`, Mesa main at 152b9cde; older Mesa: compute only), so wave64 pixel shaders can run exact there. NVIDIA lists every stage but only size 32, so there a native wave64 shader cannot get 64 and wave64 PS/VS/GS stay 2x32. A runtime can create every pipeline at load time from it without parsing SPIR-V. | | Full-corpus pipeline build | `vk_pipeline_check pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. | @@ -320,14 +302,8 @@ How the generated SPIR-V expects the runtime to work: | LDS 2-address b64 (`ds_read2_b64`, `ds_write2_b64`, `ds_read2st64_b64`, `ds_write2st64_b64`) | Two elements at vaddr + offset0·unit and vaddr + offset1·unit, unit = 8 bytes (×64 for st64); each element is two consecutive dwords, low first. `read2_b64` fills v[d:d+3] after all four loads (a vdst overlapping vaddr is safe); `write2_b64` takes two VGPR pairs. The b32 forms share the code with unit 4. Source: RDNA2 ISA DS 2-address forms. CPU-checked by `tests/semantic/test_lds_read2_write2_b64.py` (compute listings, LDS as a Workgroup variable). **Not GPU-verified.** | | Compute workgroup IDs Y/Z | With four user SGPRs and only TGID_Y and TGID_Z enabled (RSRC2 `0x308`), s4 receives Y and s5 receives Z. The synthetic `cs_workgroup_yz.asm` fixture checks a 2 × 3 × 4 dispatch and each of its 24 origins against a CPU reference. | | Typed image stores | `image_store` (2D, 2D array, 3D) writes the dmask components (missing ones = 0). The image's numeric type lives in the T# (word 1 FORMAT [28:20], 512 GFX10 formats), so it is decided at run time. A 512-bit table built from `tools/gfx10_formats.json` (30 UINT and 15 SINT formats) picks a **sint**, **uint** or **float** view (bindings 8 + 3·dim + class; dim 0 = 2D, 1 = 2D array, 2 = 3D; class 0 float, 1 uint, 2 sint). Views have Unknown format (`shaderStorageImageWriteWithoutFormat`). **The runtime binds every storage image into all three arrays of its dimension, or at least the one matching its format.** The earlier path wrote only component 0 as `r32ui`, which was wrong for every other format. GPU-checked with `runtime/test/shaders/cs_imgstore.asm` through `runtime/test/vk_store_test.cpp`: rgba8 unorm, r32 uint and r32 sint images, every texel correct. | -| Typed image loads | `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). Before #1136, a d16 load always read the float view, so a `Texture2D` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Native gfx1036 saturated 32-bit UINT/SINT texels to the unsigned/signed 16-bit range in both D16 load forms; the translated 2D load matched both limits on RTX 5080 and Radeon Graphics. D16 loads on 1D, 2D-array and 3D images still lack GPU checks. | -| Typed 2D gathers | `image_gather4_lz(_o)` takes one channel from four taps. The T# FORMAT selects the float, UINT or SINT sampled image at binding 0. For d16, integer taps are packed low half first, two per VGPR; float taps round to f16. | AMD RDNA 2 ISA §8.2 (MIMG D16). RTX 5080 and Radeon Graphics matched a CPU clamp-to-edge gather over all 4096 RGBA32F pixels for 8-bit UINT, SINT and UNORM, both packed and unpacked, with zero offset and with (+1,-1). Selecting red in place of green changed all 4096 pixels. Native gfx1036 saturates out-of-range integer taps as in the typed image loads below. | -| Typed image loads | `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). Before #1136, a d16 load always read the float view, so a `Texture2D` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Its D16 form packs the selected components in ascending order, two per VGPR. An RGBA8 two-level texture was checked on RTX 5080 and Radeon Graphics: all four exported halves matched the CPU reference for UINT, SINT and UNORM, and forcing level 0 changed every pixel. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Native gfx1036 saturated 32-bit UINT/SINT texels to the unsigned/signed 16-bit range in both D16 load forms; the translated 2D load matched both limits on RTX 5080 and Radeon Graphics. D16 loads on 1D, 2D-array and 3D images still lack GPU checks. | -| Typed image loads | `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). For odd component counts (1 or 3 in `dmask`), the trailing destination VGPR preserves its existing high 16 bits (`write_lo16`), matching native `gfx1036` hardware where a seeded `0x5a5a` high half survived 1-component UINT/SINT `image_load` and `image_load_mip`; until 2026-11-22 the unused high half was zeroed. Before #1136, a d16 load always read the float view, so a `Texture2D` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Native gfx1036 saturated 32-bit UINT/SINT texels to the unsigned/signed 16-bit range in both D16 load forms; the translated 2D load matched both limits on RTX 5080 and Radeon Graphics. D16 loads on 1D, 2D-array and 3D images still lack GPU checks. | -| Typed image loads | `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). Before #1136, a d16 load always read the float view, so a `Texture2D` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Unverified: whether AMD saturates out-of-range integers instead of truncating (Mesa sets `integer_dest_saturates`), and d16 loads on 1D, 2D-array and 3D images on a GPU. | -| Typed 2D gathers | `image_gather4_lz(_o)` takes one channel from four taps. For `image_gather4_l(_o)` the four manual fetches share the rounded, clamped mip and addressed footprint. The T# FORMAT selects the float, UINT or SINT sampled image at binding 0. For d16, integer taps are packed low half first, two per VGPR; float taps round to f16. | AMD RDNA 2 ISA §8.2 (MIMG D16). RTX 5080 and Radeon Graphics matched a CPU clamp-to-edge gather over all 4096 RGBA32F pixels for 8-bit UINT, SINT and UNORM, both packed and unpacked, with zero offset and with (+1,-1). Selecting red in place of green changed all 4096 pixels. Explicit LOD 1 on two-level UINT, SINT and UNORM images also matched all 4096 pixels for both offset forms on both GPUs. Forcing mip 0 changed every pixel. Out-of-range integer narrowing has the same limitation as typed image loads below. | -| Typed image loads | `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). Before #1136, a d16 load always read the float view, so a `Texture2D` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Its D16 form packs the selected components in ascending order, two per VGPR. An RGBA8 two-level texture was checked on RTX 5080 and Radeon Graphics: all four exported halves matched the CPU reference for UINT, SINT and UNORM, and forcing level 0 changed every pixel. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Unverified: whether AMD saturates out-of-range integers instead of truncating (Mesa sets `integer_dest_saturates`), and d16 loads on 1D, 2D-array and 3D images on a GPU. | -| Typed image loads | `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). For odd component counts (1 or 3 in `dmask`), the trailing destination VGPR preserves its existing high 16 bits (`write_lo16`), matching native `gfx1036` hardware where a seeded `0x5a5a` high half survived 1-component UINT/SINT `image_load` and `image_load_mip`; until 2026-11-22 the unused high half was zeroed. Before #1136, a d16 load always read the float view, so a `Texture2D` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Unverified: whether AMD saturates out-of-range integers instead of truncating (Mesa sets `integer_dest_saturates`), and d16 loads on 1D, 2D-array and 3D images on a GPU. | +| Typed image loads | `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). For odd component counts (1 or 3 in `dmask`), the trailing destination VGPR preserves its existing high 16 bits (`write_lo16`), matching native `gfx1036` hardware where a seeded `0x5a5a` high half survived 1-component UINT/SINT `image_load` and `image_load_mip`; until 2026-11-22 the unused high half was zeroed. Before #1136, a d16 load always read the float view, so a `Texture2D` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Its D16 form packs the selected components in ascending order, two per VGPR. An RGBA8 two-level texture was checked on RTX 5080 and Radeon Graphics: all four exported halves matched the CPU reference for UINT, SINT and UNORM, and forcing level 0 changed every pixel. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Native gfx1036 saturated 32-bit UINT/SINT texels to the unsigned/signed 16-bit range in both D16 load forms; the translated 2D load matched both limits on RTX 5080 and Radeon Graphics. D16 loads on 1D, 2D-array and 3D images still lack GPU checks. | +| Typed 2D gathers | `image_gather4_lz(_o)` takes one channel from four taps. For `image_gather4_l(_o)` the four manual fetches share the rounded, clamped mip and addressed footprint. The T# FORMAT selects the float, UINT or SINT sampled image at binding 0. For d16, integer taps are packed low half first, two per VGPR; float taps round to f16. | AMD RDNA 2 ISA §8.2 (MIMG D16). RTX 5080 and Radeon Graphics matched a CPU clamp-to-edge gather over all 4096 RGBA32F pixels for 8-bit UINT, SINT and UNORM, both packed and unpacked, with zero offset and with (+1,-1). Selecting red in place of green changed all 4096 pixels. Explicit LOD 1 on two-level UINT, SINT and UNORM images also matched all 4096 pixels for both offset forms on both GPUs. Forcing mip 0 changed every pixel. Native gfx1036 saturates out-of-range integer taps as in the typed image loads below. | | Image atomics, size and LOD queries | `image_atomic_add/sub/and/or/xor/smin/smax/umin/umax` are `OpAtomicIAdd/ISub/And/Or/Xor/SMin/SMax/UMin/UMax` on the texel (`OpImageTexelPointer`) of an r32ui storage image, binding 4 for 2D and 7 for 3D, at the T#'s index (the view `StorageViews::r32ui` of `runtime/src/vulkan_bindless.h`). The data VGPR is the operand; with `glc` it receives the texel's previous value, without it it is not written (RDNA2 ISA, MIMG: the previous value is returned if glc is 1). `image_atomic_cmpswap` takes two data VGPRs, the new value and then the comparand (`OpAtomicCompareExchange`). A lane that EXEC turns off leaves memory alone: cmpswap is skipped, the others run with the operand that changes nothing. `image_get_resinfo` (2D, no sampler) gives, for the mip level in its address VGPR, width, height, depth (1) and the level count in VGPRs 0..3 (ISA: {num_mip_levels, depth, height, width} in VGPRs 3..0; `OpImageQuerySizeLod`, `OpImageQueryLevels`). `image_get_lod` (pixel shaders; 2D and 2D array, the slice ignored) gives the clamped LOD and the calculated LOD in VGPRs 0..1 (ISA: {rawLOD, clampedLOD} in VGPRs 1..0; `OpImageQueryLod`). In both, dmask keeps components and packs them into consecutive VGPRs. GPU-checked (TEST-184) on an RX 7900 XTX and a Ryzen 9 7950X3D integrated GPU (RADV, Mesa 26.3.1) and on Mesa llvmpipe, with the expected words derived by hand in each `.asm` header: `cs_imgatomic.asm` (every op on a 2D image: 0xfffffff0 tells the signed min/max from the unsigned ones, each with a case that goes the other way; cmpswap hit and miss; an op without `glc`; 63 lanes off; 64 threads adding to one texel) and `cs_imgatomic3d.asm` (six cases on a 4x4x4 volume, the three coordinates all different), through `vk_store_test words`; `cs_resinfo.asm` (a 16x4 image with five levels: levels 0, 1 and 3 in full, then dmask 0x3, 0xa and 0x8); `ps_get_lod.asm` and `ps_get_lod_array.asm` through `vk_texture_test` (calculated LOD 1 and 3 on the two-mip texture, the clamped LOD held at the last level, and at 0 by a sampler MAX_LOD of 0.25; 2 and -3 on the one-level array). Unverified: resinfo's depth word on hardware (1 is what the T#'s DEPTH field says for a 2D image), the clamped LOD under a linear mip filter (the test's sampler is point-filtered, where 0.25 selects level 0), and the order of u and v in the LOD query (the test textures are square, where it makes no difference). `image_get_resinfo` on other dimensions is `Unsupported`. A host quirk the LOD test steps around: Mesa llvmpipe 26.3.1 does not apply a sampler's LOD range to `OpImageQueryLod` when its minimum and maximum are equal (0..0 gave level 1), so the second draw uses 0..0.25. | | SDWA | `_sdwa` forms: each source is narrowed to `src0_sel`/`src1_sel` (BYTE_n/WORD_n, zero-extended, or sign-extended under `sext()`) **before** neg/abs and the op. A VGPR result goes to `dst_sel`, with `dst_unused` setting the other bits: PAD = 0, SEXT = sign copies above the field, PRESERVE = old bits kept. VOPC has no `dst_sel`, and GFX10 `v_cmpx` has no written destination. **Until 2026-11-20 the selects were silently ignored.** That affected 3,826 of the 13,926 translated shaders: they passed `spirv-val` but computed wrong values. GPU-checked with `runtime/test/shaders/ps_sdwa.asm` and `ps_ops.asm` (also `v_pk_fma_f16`, `v_min3_u32`, `v_max3_i32`, `v_bfe_i32`): byte/word source selects, `sext()`, `UNUSED_PRESERVE` into WORD_1 and `UNUSED_SEXT` at BYTE_2 all match on every pixel. | | Byte permute | `v_perm_b32`: result byte i = BYTE_PERMUTE({src0, src1}, selector byte i), src1 = bytes 0–3 (AMD "RDNA 2" ISA reference, VOP3 opcode 836 V_PERM_B32, `byte_permute` pseudocode, page 189 of the PDF). Selector 0–7 picks that byte; **8, 9, 10, 11 give 0xff if bit 7 of byte 1, 3, 5, 7 is set, else 0x00**; 12 gives 0x00; 13 and above give 0xff. **Until 2026-11-21 selectors 8–11 gave 0x00 regardless of the sign bit**. In the 26,503-shader disassembled corpus (measured via `tools/feature_scan.py`), 0 of 10,500 shaders (11,930 `v_perm_b32` instructions) use selectors 8–11 or >= 13: all 11,258 immediate and 672 constant-register selectors (0 unresolved) use only bytes 0–7 (36,234) and 12 (11,486). GPU-checked with `runtime/test/shaders/ps_ops7.asm` (also `v_alignbit_b32` with a shift of 36, `v_med3_i32` vs `v_med3_u32`) and `ps_ops8.asm` (`v_mul_hi_u32/i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32` of 0, `v_xad_u32`, `v_add3_u32`), 4096/4096 pixels on an AMD Radeon iGPU (Ryzen 7 9800X3D, RDNA2, AMD driver 25.10.36) and an NVIDIA GeForce RTX 5070 (driver 621.24); before the fix `ps_ops7` gave 0x00000000 for the sign-selector word on both. Also executed by `tests/semantic/test_value_semantics.py`. | @@ -338,16 +314,12 @@ How the generated SPIR-V expects the runtime to work: | Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_cmov_b64`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination stays `Unsupported`, #210). `s_cmov_b64`: D[63:0] = SCC ? S0[63:0] : D[63:0], SCC read and not written, on plain 64-bit data pairs (SGPR pair, immediate or `null`); any dword that is or has been a lane mask (EXEC, VCC or a mask SGPR) makes the pair `Unsupported` — conservatively, because a CFG join can drop a register that is a mask on only one path — while 0/-1 EITHER constants are data; selecting a per-lane bit as data would silently return a bool instead of the wave's mask (#210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK and LLVM AMDGPU [SOPInstructions.td](https://github.com/llvm/llvm-project/blob/2bfedf3338162e2c841a73cd7cd9e98d00add608/llvm/lib/Target/AMDGPU/SOPInstructions.td) (`S_CMOV_B64 : SOP1_64` under `Uses = [SCC]`). CPU-checked by `tests/semantic/test_salu_cmov.py`, `tests/semantic/test_salu_cmov_b64.py` and `test_salu_pack.py`; **not GPU-verified, no corpus count**; the translated shaders were run on NVIDIA by reviewers (`s_cmov_b32/k_i32`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Not measured on RDNA2.** | | `s_bfe_u32` / `s_bfe_i32` past bit 31 | offset = S1[4:0], width = S1[22:16] (7 bits; S1 bits 23 to 31 are ignored). When offset + width > 32 the field stops at bit 31: width = min(width, 32 - offset), and `s_bfe_i32` sign-extends from the top bit that exists. Example: `s_bfe_i32 s4, 0xd2f90159, 0x7f001c` gives `0xfffffffd` (4-bit field `0xd`), not `0xd`. SCC = D ≠ 0. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, and on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`); the translator (`bfe_width`) already did this. LLVM's v_bfe fold (`constantFoldBFE`) is analogous but has a 5-bit width. **RDNA2 is not measured**; the ISA pseudocode does not say. | | 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair is 64-bit data, as for `s_lshl_b64`; a pair that `lane_masks.py` marks as a lane mask (or EXEC) stays `Unsupported` (#210). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. | -| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. A lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`) or an EXEC/VCC destination raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Not GPU-verified.** | -| 64-bit scalar bitwise ops (`s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_not_b64`) | Dispatched like `s_cselect_b64`: when destination is `exec`/`vcc` or any source is a lane mask (`holds_lane_mask` or `exec`/`vcc`), uses the per-lane mask path (`mask_src`/`mask_dst` including `null` dst) and votes SCC across the wave (`scc_from_mask`). Otherwise operates on both 32-bit dwords of non-mask 64-bit scalar data (SGPR pairs, sign-extended inline/literal immediates, `null` = 0), reads all source dwords before storing (preserving destination aliasing), accepts `null` destination, and sets `SCC = ((D.lo \| D.hi) != 0)`. Until 2026-11-22 these ops always took the lane-mask path, duplicating D.lo into D.hi and voting SCC on D.lo alone. `s_nand/nor/xnor_b64` compute `~(S0 op S1)` on both paths (a lane's mask value is 0 or ~0, so the NOT is per lane); until 2026-11-22 they were rejected as unsupported. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu64_bitwise_data.py` (all 9 ops, 4-corner SCC, immediates, aliasing, stale mask overwrite, wave32/wave64 lane-mask regression, and `--wave64-emulate`). **Not GPU-verified.** | -| 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair is 64-bit data, as for `s_lshl_b64`; a pair that `lane_masks.py` marks as a lane mask (or EXEC) stays `Unsupported` (#210). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Not GPU-verified.** | | `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. A lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`) or an EXEC/VCC destination raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. | | 64-bit scalar bitwise ops (`s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_not_b64`) | Dispatched like `s_cselect_b64`: when destination is `exec`/`vcc` or any source is a lane mask (`holds_lane_mask` or `exec`/`vcc`), uses the per-lane mask path (`mask_src`/`mask_dst` including `null` dst) and votes SCC across the wave (`scc_from_mask`). Otherwise operates on both 32-bit dwords of non-mask 64-bit scalar data (SGPR pairs, sign-extended inline/literal immediates, `null` = 0), reads all source dwords before storing (preserving destination aliasing), accepts `null` destination, and sets `SCC = ((D.lo \| D.hi) != 0)`. Until 2026-11-22 these ops always took the lane-mask path, duplicating D.lo into D.hi and voting SCC on D.lo alone. `s_nand/nor/xnor_b64` compute `~(S0 op S1)` on both paths (a lane's mask value is 0 or ~0, so the NOT is per lane); until 2026-11-22 they were rejected as unsupported. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu64_bitwise_data.py` (all 9 ops, 4-corner SCC, immediates, aliasing, stale mask overwrite, wave32/wave64 lane-mask regression, and `--wave64-emulate`). **Hardware-verified** on the same part through `tools/hw_oracle` for the plain-data path: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0: SCC = ((D.lo ≠ 0) or (D.hi ≠ 0)). The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. | | Constant lane masks (`Gen.mask_src` immediates) | A constant read as a lane mask is one bit per lane: lane L takes bit L. The 64-bit forms (`s_and/or/andn2_saveexec_b64`, `s_andn2_wrexec_b64`, `s_mov_b64`/`s_not_b64` into EXEC or VCC, `s_and/or/xor/andn2/orn2_b64` and `s_cselect_b64` on the lane-mask path) read the 64-bit value, an inline constant sign-extended (`-16` = lanes 4-63) and a literal with a zero high word, as `src64_data` reads 64-bit constants; the b32 forms (`s_*_saveexec_b32`, `s_andn2_wrexec_b32`) read the 32-bit value at bit L mod 32. 0 and -1 still give no lane and every lane, with no per-lane code. `s_bcnt0/1_i32_b64` of a constant counts the constant's 64 bits (scalar data, like `s_ff0/1_i32_b64`). **Before this fix every lane took bit 0 of the constant**: `s_and_saveexec_b32 s7, 0xff00` with all 32 lanes on left none on, `5` left all 32 on, and `s_bcnt1_i32_b64 s0, 0xff00ff` gave 32. llvm-mc rejects a constant as the mask operand of `v_cndmask_b32_e64` / `v_add_co_ci_u32_e64` and decodes one as "Invalid immediate", so those VALU callers never see a constant. Not covered here: SGPRs read as masks (#293) and a literal with bit 31 set in a 64-bit position (zero- vs sign-extension not measured). GPU-checked with `runtime/test/shaders/cs_w32_mask_imm.asm` and `cs_w64_mask_imm.asm` on an NVIDIA GeForce RTX 5080 (driver 616.92; wave64 with `LEONIDA_W64_EMULATE=1`) and an AMD Radeon RDNA2 iGPU (driver 26.10.1, native 64-wide subgroup): both failed before on both GPUs. Run across every lane in `tests/semantic/test_value_semantics.py` (`LaneMaskConstants`). | | Vector integer additions (`v_mul_hi_u32_u24`/`v_mul_hi_i32_i24`, `v_lshrrev_b64`/`v_ashrrev_i64`, `v_qsad_pk_u16_u8`/`v_mqsad_pk_u16_u8`) | `v_mul_hi_*24`: the high 32 bits of the 48-bit product of the low 24 bits, zero-extended (u24) or sign-extended from bit 23 (i24); the high halves of `v_mul_u32_u24` / `v_mul_i32_i24`. `v_lshrrev_b64` / `v_ashrrev_i64`: the pair (or a 64-bit constant) shifted right by S0 & 63, logically or arithmetically, through the `v_lshlrev_b64` code. `v_qsad_pk_u16_u8` / `v_mqsad_pk_u16_u8`: D.u16[k] = (S2.u16[k] + byte SAD of the 32-bit window S0[8k+31:8k] against S1) & 0xFFFF; the m form skips bytes where S1's byte is 0; `clamp` raises `Unsupported`. Source: RDNA ISA pseudocode. CPU-checked by `tests/semantic/test_alu_mul_hi_24.py`, `test_alu_shift_b64.py`, `test_alu_qsad.py`; run on NVIDIA by reviewers (`v_mul_hi_*24`: RTX 5090 and RTX 5070 in #440; `v_qsad`/`v_mqsad`: 24 cases bit-exact on an RTX 3060 in #623). **Not measured on RDNA2.** | | Constant and ordered VOPC, `v_cmp(x)_nlg_*`, `v_cvt_off_f32_i4`, `v_pipeflush` | `v_cmp(x)_f_*` is always false, `v_cmp(x)_t_*` (integers) and `v_cmp(x)_tru_*` (floats) always true; `v_cmp(x)_o_{f32,f16}` is true when neither source is NaN, `_u_` when either is (`OpIsNan`), and `_nlg_` when `x == y` or either source is NaN (`OpFUnordEqual`, completing all 16 IEEE-754 RDNA2 float VOPC predicates; LLVM `gfx10_asm_vopc.s`); the result goes through the usual VOPC path (VCC, an SGPR mask, or EXEC for `v_cmpx`; off lanes give 0). `v_cvt_off_f32_i4`: D = sext(S0[3:0]) / 16 (the ISA's CVT_OFF_TABLE, -0.5 .. 0.4375), exact, output modifiers apply. `v_pipeflush` only flushes the VALU pipeline and is translated as nothing, like `v_nop`. Source: RDNA2 ISA VOPC and VOP1. CPU-checked by `tests/semantic/test_vopc_const_ordered.py`, `tests/semantic/test_float_compares.py` (`nlg`; GPU-checked by `ps_cmp_nlg.asm`: f32 and f16 with ±0, quiet and signalling NaN, ±inf and ignored f16 high halves, the e64 form with `abs`/`neg`, and `v_cmpx_nlg` on equal and NaN operands, Tesla V100 (NVIDIA 580.95.05, Linux)), `test_alu_cvt_off.py` (GPU-checked by `ps_cvt_off.asm`, upper bits ignored and `mul:4` with and without `clamp`), `test_valu_pipeflush.py`; the constant/ordered float compares were run on an RTX 5090 (16 draws, quiet and signalling NaNs) and the suite on RTX 4050 / Radeon 740M in #620; `v_pipeflush` on RTX 5090 / RTX 3060 in #735. | | Relative VGPR moves (`v_movrel*`) | The VGPR file is a Function-scope uint array, so `v_movrels_b32`/`v_movreld_b32`/`v_movrelsd_b32` become dynamic array accesses at `reg + M0` (the whole of M0, as the RDNA2 ISA's opcode descriptions say). `v_movrelsd_2_b32` (VOP1 opcode 72) offsets each side by its own field: VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]], other M0 bits ignored (RDNA2 ISA §12.8 opcode description and the RDNA3 ISA; the RDNA2 §6.6 summary table prints M0[7:0] for the source). The write keeps inactive lanes. Not modelled: the hardware's range check against the wave's VGPR allocation (an out-of-range source reads VGPR0, an out-of-range write is dropped). CPU-checked by `tests/semantic/test_alu_movrelsd_2.py` (including set ignored M0 bits); GPU-checked with `runtime/test/shaders/cs_movrelsd_2.asm` (the ISA's own example, v25 ← v17 with M0 = (20 << 16) \| 10) on NVIDIA RTX 4050 Laptop (Ada) and AMD Radeon 740M (RADV). | -| Relative SGPR reads (`s_movrels_b32`, `s_movrels_b64`) | `D = SGPR[S0 + M0]`; the b64 form reads the pair at `S0 + M0` and `S0 + M0 + 1` (RDNA2 ISA SOP1). The SGPR file is a Function-scope uint array, so this is a dynamic load, as for `v_movrels`. Every SGPR write stores into that array (`store_reg`), so the load sees the current value. All reads happen before the destination is written, so D may overlap the source. SCC is not written. The index wraps to the 128 array slots, so it cannot reach the lane-mask parking slots past them. **Not modelled:** the hardware's range check, and reads past s105 landing on VCC and the other special registers. `s_movreld_b32/b64`, the relative writes, stay `Unsupported`, because the translator keeps translate-time knowledge of SGPR values (literal S# words, descriptor caches) that a dynamic write would invalidate. Until 2026-11-22 both reads raised `Unsupported`. CPU-checked by `tests/semantic/test_salu_movrels.py` (M0 from 0 to 5 and from a register, the b64 pair, an overlapping destination, SCC kept, `s_movreld` rejected). **Not GPU-verified.** | | `v_swaprel_b32` | GFX10 VOP1 opcode 104: swap `VGPR[D + M0[25:16]]` and `VGPR[S0 + M0[9:0]]`, the two M0 fields `v_movrelsd_2_b32` uses; the other M0 bits are ignored (RDNA2 ISA opcode description). Both registers are read before either is written. When both name one register it keeps its value. Inactive lanes keep both registers (`OpSelect` on `active`). As for `v_movrel*`, the hardware's range check against the VGPR allocation is not modelled. A non-VGPR operand raises `Unsupported`. Until 2026-11-22 the op raised `Unsupported`. CPU-checked by `tests/semantic/test_alu_swaprel.py` (both fields, ignored M0 bits, a self-swap, a register-file model). **Not GPU-verified.** | | Relative SGPR reads (`s_movrels_b32`, `s_movrels_b64`) | `D = SGPR[S0 + M0]`; the b64 form reads the pair at `S0 + M0` and `S0 + M0 + 1` (RDNA2 ISA SOP1). The SGPR file is a Function-scope uint array, so this is a dynamic load, as for `v_movrels`. Every SGPR write stores into that array (`store_reg`), so the load sees the current value. All reads happen before the destination is written, so D may overlap the source. SCC is not written. The index wraps to the 128 array slots, so it cannot reach the lane-mask parking slots past them. An SGPR that `lane_masks.py` marks as a lane mask (a saved EXEC, a `v_cmp` result) holds only this lane's bit, so the whole wave's mask word is collected for each such SGPR (as for `s_bcnt1`) and read instead when the index lands on it; D then holds the mask as data (SHADER-284, CPU-checked by `tests/semantic/test_salu_movrels_lane_mask.py`, wave32 and wave64). **Not modelled:** the hardware's range check, and reads past s105 landing on VCC and the other special registers. `s_movreld_b32/b64`, the relative writes, stay `Unsupported`, because the translator keeps translate-time knowledge of SGPR values (literal S# words, descriptor caches) that a dynamic write would invalidate. Until 2026-11-22 both reads raised `Unsupported`. CPU-checked by `tests/semantic/test_salu_movrels.py` (M0 from 0 to 5 and from a register, the b64 pair, an overlapping destination, SCC kept, `s_movreld` rejected). **Not GPU-verified.** | | d16 and f16 format narrowing | The f16 of every d16 result (image samples and gathers, the `image_sample_c_lz` compare result, typed buffer loads) and of the f16 formats a typed buffer store writes is narrowed with integer round to nearest even (`Gen.f16_bits`; #489, #711), not with `PackHalf2x16`. AMD drivers lower `PackHalf2x16` to `v_cvt_pkrtz_f16_f32`, which rounds toward zero (#489), and there about half of all unorm8, unorm16 and snorm8 values loaded with d16 came out 1 ulp low (123 of 256, 31,742 of 65,536 and 110 of 256). Packed MUBUF and MTBUF loads clamp unsigned 32-bit channels to 65535 before writing each half. On native gfx1036, values 65534 and 65535 survived, while 65536, 65537 and 0xffffffff all produced 0xffff, across all four load widths in wave32 and wave64. Packed `buffer_load_format_d16_x` and `_xyz` write only the low 16 bits of the final VGPR. Its upper half survives even when the load is out of bounds. Native gfx1036 wave32 and wave64 confirmed this with RGBA8_UINT and RGBA8_UNORM, two destination seeds, and both even-component loads as full-write controls. Full pairs are packed by `pack_f16_pair_int` and an odd final buffer component is narrowed with `f16_bits` for float/normalized formats. These memory conversions do not use `f16_pack2`: they come from the texture and buffer units, not the VALU whose rounding `MODE.FP_ROUND` sets (#753). Round to nearest even for these conversions is inferred, as in #489, not measured. #489's own narrower, `f32_to_f16_int`, was folded into `f16_bits` on 2026-11-22: the two gave the same bits on 30,648 inputs (every f32 exponent, ties, the subnormal and overflow edges, NaN), and `f16_bits` lost its one GLSL.std.450 instruction (`UMin`) so the packer stays free of them. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`, `test_buffer_format_f16_narrowing_avoids_packhalf2x16`), `tests/test_d16_pack.py` and `tests/semantic/test_buffer_load_format.py` (`D16NormalizedRounding`). | @@ -369,15 +341,12 @@ How the generated SPIR-V expects the runtime to work: | Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` (SHADER-118) | The three have no f32 denormal support: a subnormal operand, the rounded product or the result reads as signed zero, whatever the MODE register says. `Gen.flush_f32` emits `|x| < FLT_MIN → copysign(0, x)` on the three operands, after the product rounding and after `omod`/`clamp`; inf and NaN compare false and pass through, and 0 keeps its sign. Source: LLVM AMDGPU `SIISelLowering.cpp`, `SITargetLowering::isFMADLegal` (llvm-project `1922c0c`), which forms `v_mad_f32`/`v_mac_f32` only when f32 denormals are flushed. Corpus count with `tools/shader_profile.py` over the 26,503 gfx1013 shaders: `v_mad_f32` in 7,298 shaders (139,287 occurrences), `v_mac_f32` in 5,889 (276,806: 265,901 `_e32`, 10,811 `_e64`, 94 `_dpp`), `v_mad_legacy_f32` in 6,059 (24,765); 9,297 shaders (35.1%) use at least one, 440,858 occurrences (0.99% of the corpus's 44,406,870 instructions). Checked on the CPU by `tests/semantic/test_valu_f32_min3_max3_mad.py` (`DenormalFlushTests`: the flush column, NaN/inf/zero pass-through, and a sabotaged pass-through that fails); **not GPU-verified** — a native measurement still needs an RDNA1/RDNA2 part that has these opcodes. The `omod` order is an assumption: the flush runs after `div:2`/`mul:2`/`mul:4`, so `FLT_MIN div:2` is flushed, as pinned by that test. | | `v_mac_legacy_f32` | The GFX10.1 VOP2 form of `v_mad_legacy_f32` with D as the addend: D = legacy(S0 * S1) + D, where 0 times anything (inf and NaN included) is +0, with the same denormal flush and VOP3 modifiers. D is read before it is written, as for `v_mac_f32` (LLVM `VOP2Instructions.td`: `V_MAC_LEGACY_F32` has `$src2` tied to `$vdst`). Until 2026-11-22 it raised `Unsupported`. CPU-checked by `MacLegacyF32Tests` in `tests/semantic/test_valu_f32_min3_max3_mad.py` (a 15x8x6 grid against the `v_mad_legacy_f32` reference, the zero rule, clamp/neg, D aliased as a source). **Not GPU-verified**: like the other mad opcodes it exists on gfx1010-1013 only, so no RDNA2 desktop part runs it. | | Whole-quad mode (`s_wqm_b64` / `s_wqm_b32`) | A lane mask register holds only this lane's bit, so WQM on one (EXEC, VCC, an SGPR the mask analysis found) ORs the bit of the lane's quad, lanes 4n..4n+3 of the wave: two `OpGroupNonUniformQuadSwap` (horizontal, then vertical; capability `GroupNonUniformQuad`) in the default mode in fragment and compute shaders (quad operations are only guaranteed there; vertex, geometry and mesh shaders shuffle from the quad's four lanes), or the four lanes' values read through `%x_buf` under `--wave64-emulate` (no subgroup operation there). A quad never crosses lane 31/32, so the mask bits are exact per half on a 32-wide subgroup; SCC is a wave vote, so on wave64 it needs a 64-wide subgroup or `--wave64-emulate` (as every wave-wide mask op). The result goes to EXEC, VCC or an SGPR pair as a mask, SCC = the wave-wide any of it (same vote as the other mask ops). A 32-bit form in wave64 (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`, a half-mask SGPR) writes only its own half (`exec_half_write`) and votes SCC over that half only (`cs_wqm_w64_half`). A source that is not a lane mask (a value loaded from memory, a literal) is data: `((x | x>>1 | x>>2 | x>>3) & 0x11111111) * 15` per 32-bit word and SCC = result != 0, no subgroup operation. Assumptions: in compute and mesh shaders the subgroup lane is `LocalInvocationIndex` mod the subgroup size (as for every cross-lane op); a hardware quad is four consecutive lanes of a wave, and in a pixel shader Vulkan's quad (the 2x2 pixels, helper invocations included) is the same four lanes; GPU-checked on both AMD and NVIDIA with `ps_wqm.asm` (every 2x2 block of a 64x64 target, fully covered). Not covered: helper-invocation behaviour at triangle edges is untested, and in native mode an absent invocation in a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value (emulated, the missing lanes of a partial wave read as 0). Before this the instruction was the identity, so helper lanes stayed off (#156 SHADER-34: `s_wqm_b64` appears in 4,285 pixel shaders). GPU-checked with `runtime/test/shaders/cs_wqm_w64.asm`, `cs_wqm_w64_half.asm`, `cs_wqm_w32.asm` and `ps_wqm.asm` on AMD Radeon 880M (subgroup 64) and NVIDIA GeForce RTX 5070 Laptop (subgroup 32; `cs_wqm_w64` there needs `LEONIDA_W64_EMULATE=1`), with and without `--wave64-emulate`. | -| Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2). Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0 without a load. **The RX 6800 measurement behind RAW loads** (`buffer_load_dword`/`x2`/`x3`/`x4`, stride 0, no `idxen`, OOB_SELECT 3; the per-mode rule below covers every mode, stride and `idxen`): the byte offset O = inst_offset + soffset + (offen ? vaddr : 0) is exact (nothing truncated, and the address keeps base & 3), and dword i is data when O + 4·i + 4 ≤ num_records, else 0, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword), for x1/x2/x4 with V# word3 0x31016fac (OOB_SELECT 3) at offsets 0..63 per lane, NUM_RECORDS 17..23 and 0x1000, base & 3 = 0 and 3: a dword at 0xf with NUM_RECORDS 18 is 0 (a start-only check reads it); x4 at 3 with 18 gives three data dwords and 0 for the fourth, which starts at 15 < 18 (so neither a whole-load nor a per-dword start check), and the zero is a whole 0, not partial bytes; x4 at offset:13 with 20 gives data, 0, 0, 0; inst_offset, soffset and offen are summed before the check; base & 3 = 3 flips at the same offsets. `x3` gets the rule without a measurement. **Per-mode check (V# OOB_SELECT, word3 bits [29:28])**, for every MUBUF/MTBUF access, as measured natively on RDNA2 (gfx1036, 732 cases, `docs/buffer_bounds.md`; Mesa's GFX11 column, not its GFX10 one). `idx` = `vindex` (0 without `idxen`), `off` = inst_offset + vaddr offset (offen), `offs` = `off` + soffset. A dword at byte 4·k of the access is out of range when: **0 STRUCTURED_WITH_OFFSET** `idx >= num_records` or `off + 4k + 4 > stride`; **1 STRUCTURED** `idx >= num_records` (no `idxen`: idx 0, so only `num_records == 0`); **2 DISABLED** `num_records == 0`; **3 RAW** `offs + 4k + 4 > num_records` (`idx * stride` is in the address, not in the check). A literal word3 (`s_mov_b32` earlier in the block) folds the mode, a run-time one selects with `OpSelect`. Multi-dword accesses, measured on the Radeon 880M (gfx1150, a valid proxy: gfx1036 follows the same column and gfx1150 matched it bit-exactly): in modes 0 and 3 **`buffer_load_dwordx2..x4` and `buffer_store_dwordx2..x4` are per dword**, for loads and stores alike (x4 at off 20 of 32 in RAW loads/stores 3 dwords, at 28 one, at 32 none; mode 0 likewise at the stride); modes 1 and 2 check once and always take the whole access. **A typed element (`buffer_load_format_*`, `buffer_store_format_*`) is all or nothing and ends at its format's size** (32_32_32_32 at off 20 of 32 reads or writes nothing), and an atomic checks its dword's end like a dword access. The translator does the same: per-dword guarded loads and stores for modes 0 and 3 (a store that straddled the edge used to write past it), the element size from the instruction's format, a literal word3 or the V#. The same oracle confirmed the terms (504 `buffer_load_dword` probes, idxen/offen/inst_offset/soffset at the stride and record edges, 0 disagreements): mode 0's `off` has `inst_offset` and no soffset, mode 1 reads nothing but the index, mode 3 adds inst_offset and soffset. `s_buffer_load` (SMEM) is separate: it keeps the `num_records` bound of the Scalar/buffer row and ignores OOB_SELECT (the same pattern for 0 to 3). **Swizzle**: SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are not modelled: a literal V# with either set is `Unsupported`, a run-time V# with them is translated unswizzled, which is silently wrong (known gap). Until 2026-11-22 the translator ignored OOB_SELECT and checked by stride alone (`offset < num_records`, `index < num_records`, or `offset < num_records * stride`): a V# with word3 = 0 (mode 0, stride 0) was fully readable and is now always out of range, as on hardware, so the test harnesses' output V# is `0x31016fac` now (`vk_compute_test`, the interpreter tests, `cs_bounds.asm`, `cs_fmt_1010102.asm`, `cs_store.asm`). **How confirmed**: the native RDNA2 measurement (gfx1036) and the gfx1150 oracle (RDNA3.5, same column); GPU test `cs_oob_select.asm` (every mode, literal and run-time V#, words derived from the rules) on an NVIDIA RTX 5070 and an AMD Radeon 880M, which checks the translation, not RDNA2; `tests/semantic/test_buffer_oob_select.py` (a hand-written table of 33 cases over the four modes, loads and stores, both V# forms, plus the multi-dword stores and typed elements); `cs_oob_tail.asm` pins the end-based edge, per-dword x4 loads and stores and the all-or-nothing element, where Mesa's GFX10 column gives other words. **Unmeasured**: gfx1013/GFX10.1 itself (see `docs/buffer_bounds.md`), swizzle, unaligned addresses, and the mode 1/2 boundary of `buffer_load_dwordx2..x4` on RDNA2 hardware proper (the gfx1150 proxy shows all dwords in). Checked by `tests/semantic/test_value_semantics.py` (`RawBufferTailBounds`: the RX 6800 rows, values and the addresses loaded) and the GPU tests `runtime/test/shaders/cs_bounds.asm` (AMD Radeon RX 9070 XT, RX 6800), `cs_buf_tail.asm` (RX 6800, Vulkan, driver 26.11.2; aligned offsets only, since the translator's `Aligned 4` loads at byte-exact addresses were not checked on a Vulkan driver) `cs_oob_select.asm` and `cs_oob_tail.asm`. `cs_fmt_xy_xyz.asm` shows the whole element deciding for `_xy` and `_xyz` too, measured natively on a Radeon 680M (gfx1035, RDNA2): components that end inside num_records, in an element that doesn't, read 0 and store nothing. | | `buffer_atomic_{and,or,xor,swap}_x2` | `M = op(M, DATA)` on the 64-bit element at the MUBUF address (two dwords, low first); with `glc` the old 64 bits are returned in `vdata[0:1]`. A bitwise op or an exchange leaves the same memory done one dword at a time, so each dword is its own 32-bit `OpAtomic*` and no Int64 atomics are needed. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done. **Bounds:** the check covers the whole 8-byte element, all or nothing, as for a typed 32_32 element (`buffer_address(elem="fmt")`). An out-of-range or inactive lane leaves memory alone and returns 0, as `buffer_atomic` does. How hardware treats a 64-bit atomic that is only partly in range is **not measured**. Still `Unsupported`: `add/sub/min/max_x2` and `cmpswap_x2`. Until 2026-11-22 every `_x2` buffer atomic was rejected. CPU-checked by `tests/semantic/test_buffer_atomics_x2.py` (the four ops with and without `glc`, an element ending exactly at `num_records`, half and fully out of range, seeded values, rejected forms). **Not GPU-verified.** | | Wave64 graphics: partition invariance (SHADER-10) | A wave64 VS/PS/GS on a 32-wide subgroup is exact **iff its observable results do not change when the wave is cut into two 32-lane halves** (the host forms the subgroups of graphics stages, so there is no partner half to exchange with). `tools/wave64_halves.py` decides it from the code (forward taint dataflow over the basic blocks, plus control dependence on wave-wide votes) and the translator records it in `index.json` as `wave64_graphics` (`A`/`B`/`C`), `wave64_graphics_reasons` (tier C) and `wave64_graphics_idioms` (tier B). **A**: only per-lane arithmetic, votes that skip lane-masked work (`s_cbranch_execz/execnz`; `vccz/vccnz` whose run side starts by narrowing EXEC to that VCC and whose other side is the join, with no code of its own: a half that votes no runs that side, the wave does not; the same holds for `s_cbranch_execz/execnz`: the side that runs when EXEC is zero is taken by a half with no active lane, so it must be the join (or only jumps to it) or the exit of a loop the vote closes, else tier C `unsafe-execz-branch`; `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C), whole-quad masks, `ds_bpermute`/`v_permlane16` (they stay inside a half, not GPU-tested here: no fixture; `ds_swizzle` and `v_permlanex16` likewise), loops closed by `execnz` with no scalar state carried. **B**: also a waterfall loop (`v_readfirstlane` of a varying value, `v_cmp_eq` against the same VGPR, `saveexec`, body, `s_xor exec`, `execnz`; the scalar only used inside the body), a wave-aggregated atomic (`s_bcnt1` of EXEC, `v_mbcnt` rank of that same EXEC, one `buffer_atomic_add` of that count (the count of the mask the rank ranks) by the rank-0 lane only, `v_readfirstlane` of the result with EXEC restored, base + rank as a store address, the rank counting the very mask the atomic's count was taken of (a rank of the entry EXEC or of a saved copy next to a base of the narrowed one is tier C `lane-rank`); the rank alone or the base alone is not a slot: exact as a set of slots, **the order of the slots within a wave is not preserved**, a 64-lane wave takes one run of slots, two halves take two), `v_readfirstlane` / `v_readlane` of a VGPR written from scalars and constants while EXEC was the launch mask (the same in every lane), a `v_writelane` / `v_readlane` spill pair on one constant lane below 32. **C**: anything else that reaches an export, a store's data, a branch or EXEC: lane count / rank / first-lane index / raw lane id (`v_mbcnt` of -1), `v_readlane` of a varying value at any lane (on a wave64 every lane gets hardware lane N, in halves each half gets its own lane N, so lane 7 is as wrong as lane 40; the research note's row 9 is too generous here); an analysis failure is tier C with reason `analysis-error` (the translation does not fail), `v_writelane` to a non-constant or >= 32 lane, a 32-bit access to half of a lane mask (`exec_hi`, `vcc_hi`, a mask pair's odd register), a mask read as data (including a mask combined by `s_and/or/andn2_b64` with a register that is not one: a user value, a loaded mask), a scalar defined behind a wave-wide vote and read where it may not have run (`s_add s5, s5, 1` after `s_cbranch_vccz`; a trip count in an SGPR of a divergent loop: the halves vote differently), a branch on a count, an elected-lane side effect that is not a count, `ds_append`/`ds_consume`. The check is conservative: unknown means C. `--wave64-graphics=warn` (default) marks tier C and counts it in the summary line, `error` refuses it (`Unsupported`), `off` skips the analysis; `python tools/wave64_halves.py --census /index.json` prints tier, reason and idiom counts (no names); it complements `tools/wave64_graphics_scan.py` (#1132), which counts candidate cross-half opcodes in the disassembly before translation and decides nothing. **Corpus coverage is not measured here**: it needs a run over the game's shaders by someone who has them. **Rewrite (the only one the emission needs)**: `v_readlane_b32` of a proven-uniform VGPR reads the lane's own copy instead of shuffling from lane N, because a subgroup shuffle from lane >= 32 of a 32-wide subgroup is undefined (143 of 144 test shaders translate byte-identically to origin/main, only `ps_w64_b_readlane_uniform` changed). Everything else tier B needs is what the translator already emits per subgroup: the ballot/count/rank/first-lane words of `wave_mask` are the subgroup's own (the high word is 0), `v_readfirstlane` is the subgroup's first active lane, a waterfall runs once per distinct value of the subgroup. GPU-checked on AMD Radeon 880M (driver 26.11.2; `requiredSubgroupSizeStages` has FRAGMENT, size 32..64) with `runtime/test/shaders/w64_graphics.py`: each `ps_w64_*` fixture drawn with the fragment subgroup size required to 64 (one hardware wave) and to 32 (two halves). `ps_w64_a_skip`, `_b_waterfall`, `_b_readfirstlane`, `_b_readlane_uniform` and `_b_ballot_atomic` (counter 1024 and the 1024 slot words as a set; slot order differs) match each other and the words their headers derive; `_c_bcnt_export`, `_c_lane_id`, `_c_readlane`, `_c_vote_stale`, `_c_vote_else`, `_c_scc_vote`, `_c_execz_sgpr` (an SGPR written on the exec-zero side and exported) and `_c_waterfall_count` differ between 64 and 32 (the detector is right). `ps_w64_a_one_lane` is the case where only one pixel votes yes (so one half votes and the other does not, in the wave and in the halves): its skip regions (`execz`, `vccz`, `vccnz` with a jump-only fall-through) give equal images at 64 and 32; `_c_vote_else` (code on the vote's no side) and `_c_scc_vote` (SCC of a vote as data) differ. NVIDIA GeForce RTX 5070 Laptop (32 only, driver 617.42): tier A/B fixtures equal the derived words and the 880M@64 images (`W64G_SAVE_REF` / `W64G_REF`), tier C fixtures differ from the 880M@64 images. Vertex shaders: the VS stage cannot be forced on the 880M (no VERTEX in `requiredSubgroupSizeStages`), so VS is covered by the strict wave interpreter (`tests/semantic/test_wave64_halves.py`: 64 lanes against two waves of 32; tier A/B equal, tier C differs); geometry shaders are not tested (the corpus ones are wave32; no fixture). Not checked: helper lanes of partial quads; `VK_KHR_shader_maximal_reconvergence` is assumed for waterfall and election loops. | | Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2). Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0 without a load. **The RX 6800 measurement behind RAW loads** (`buffer_load_dword`/`x2`/`x3`/`x4`, stride 0, no `idxen`, OOB_SELECT 3; the per-mode rule below covers every mode, stride and `idxen`): the byte offset O = inst_offset + soffset + (offen ? vaddr : 0) is exact (nothing truncated, and the address keeps base & 3), and dword i is data when O + 4·i + 4 ≤ num_records, else 0, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword), for x1/x2/x4 with V# word3 0x31016fac (OOB_SELECT 3) at offsets 0..63 per lane, NUM_RECORDS 17..23 and 0x1000, base & 3 = 0 and 3: a dword at 0xf with NUM_RECORDS 18 is 0 (a start-only check reads it); x4 at 3 with 18 gives three data dwords and 0 for the fourth, which starts at 15 < 18 (so neither a whole-load nor a per-dword start check), and the zero is a whole 0, not partial bytes; x4 at offset:13 with 20 gives data, 0, 0, 0; inst_offset, soffset and offen are summed before the check; base & 3 = 3 flips at the same offsets. `x3` gets the rule without a measurement. **Per-mode check (V# OOB_SELECT, word3 bits [29:28])**, for every MUBUF/MTBUF access, as measured natively on RDNA2 (gfx1036, 732 cases, `docs/buffer_bounds.md`; Mesa's GFX11 column, not its GFX10 one). `idx` = `vindex` (0 without `idxen`), `off` = inst_offset + vaddr offset (offen), `offs` = `off` + soffset. A dword at byte 4·k of the access is out of range when: **0 STRUCTURED_WITH_OFFSET** `idx >= num_records` or `off + 4k + 4 > stride`; **1 STRUCTURED** `idx >= num_records` (no `idxen`: idx 0, so only `num_records == 0`); **2 DISABLED** `num_records == 0`; **3 RAW** `offs + 4k + 4 > num_records` (`idx * stride` is in the address, not in the check). A literal word3 (`s_mov_b32` earlier in the block) folds the mode, a run-time one selects with `OpSelect`. Multi-dword accesses, measured on the Radeon 880M (gfx1150, a valid proxy: gfx1036 follows the same column and gfx1150 matched it bit-exactly): in modes 0 and 3 **`buffer_load_dwordx2..x4` and `buffer_store_dwordx2..x4` are per dword**, for loads and stores alike (x4 at off 20 of 32 in RAW loads/stores 3 dwords, at 28 one, at 32 none; mode 0 likewise at the stride); modes 1 and 2 check once and always take the whole access. **A typed element (`buffer_load_format_*`, `buffer_store_format_*`) is all or nothing and ends at its format's size** (32_32_32_32 at off 20 of 32 reads or writes nothing), and an atomic checks its dword's end like a dword access. The translator does the same: per-dword guarded loads and stores for modes 0 and 3 (a store that straddled the edge used to write past it), the element size from the instruction's format, a literal word3 or the V#. The same oracle confirmed the terms (504 `buffer_load_dword` probes, idxen/offen/inst_offset/soffset at the stride and record edges, 0 disagreements): mode 0's `off` has `inst_offset` and no soffset, mode 1 reads nothing but the index, mode 3 adds inst_offset and soffset. `s_buffer_load` (SMEM) is separate: it keeps the `num_records` bound of the Scalar/buffer row and ignores OOB_SELECT (the same pattern for 0 to 3). **Swizzle**: SWIZZLE_ENABLE and ADD_TID_ENABLE are modelled; see the Swizzled buffer addressing row. Until 2026-11-22 the translator ignored OOB_SELECT and checked by stride alone (`offset < num_records`, `index < num_records`, or `offset < num_records * stride`): a V# with word3 = 0 (mode 0, stride 0) was fully readable and is now always out of range, as on hardware, so the test harnesses' output V# is `0x31016fac` now (`vk_compute_test`, the interpreter tests, `cs_bounds.asm`, `cs_fmt_1010102.asm`, `cs_store.asm`). **How confirmed**: the native RDNA2 measurement (gfx1036) and the gfx1150 oracle (RDNA3.5, same column); GPU test `cs_oob_select.asm` (every mode, literal and run-time V#, words derived from the rules) on an NVIDIA RTX 5070 and an AMD Radeon 880M, which checks the translation, not RDNA2; `tests/semantic/test_buffer_oob_select.py` (a hand-written table of 33 cases over the four modes, loads and stores, both V# forms, plus the multi-dword stores and typed elements); `cs_oob_tail.asm` pins the end-based edge, per-dword x4 loads and stores and the all-or-nothing element, where Mesa's GFX10 column gives other words. **Unmeasured**: gfx1013/GFX10.1 itself (see `docs/buffer_bounds.md`), unaligned addresses, and the mode 1/2 boundary of `buffer_load_dwordx2..x4` on RDNA2 hardware proper (the gfx1150 proxy shows all dwords in). Checked by `tests/semantic/test_value_semantics.py` (`RawBufferTailBounds`: the RX 6800 rows, values and the addresses loaded) and the GPU tests `runtime/test/shaders/cs_bounds.asm` (AMD Radeon RX 9070 XT, RX 6800), `cs_buf_tail.asm` (RX 6800, Vulkan, driver 26.11.2; aligned offsets only, since the translator's `Aligned 4` loads at byte-exact addresses were not checked on a Vulkan driver) `cs_oob_select.asm` and `cs_oob_tail.asm`. `cs_fmt_xy_xyz.asm` shows the whole element deciding for `_xy` and `_xyz` too, measured natively on a Radeon 680M (gfx1035, RDNA2): components that end inside num_records, in an element that doesn't, read 0 and store nothing. | | Swizzled buffer addressing (V# SWIZZLE_ENABLE, ADD_TID_ENABLE) | MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load_format_*` follow the RDNA2 ISA ("RDNA 2" Instruction Set Architecture, 8.1.5 Buffer Addressing, "Swizzled Buffer Addressing" and tables 33, 35 and 37). Fields, Mesa 24.0.6 `src/amd/registers/gfx10-rsrc.json` (`SQ_BUF_RSRC_WORD1`, `SQ_BUF_RSRC_WORD3` and its `_gfx103` twin, the same bits): SWIZZLE_ENABLE word1 bit 31, STRIDE word1 [29:16], INDEX_STRIDE word3 [22:21] (IS = 8, 16, 32 or 64 indices), ADD_TID_ENABLE word3 bit 23; there is no ELEMENT_SIZE field, the element is fixed at 4 bytes (ISA 8.1.5; LLVM `SIInstrInfo::getScratchRsrcWords23` sets it only up to GFX8). `index` = (idxen ? vindex : 0) + (ADD_TID_ENABLE ? lane : 0), where the lane is thread_id[5:0] within the wave (`Gen.wave_lane`), swizzled or not: table 33 adds the thread id with no swizzle condition and table 36's ring column is linear with add_tid. `offset` = (offen ? vaddr : 0) + inst_offset, without soffset. Swizzled: buffer_offset = (index / IS · stride + offset / 4 · 4) · IS + index % IS · 4 + offset % 4, address = base + soffset + buffer_offset, so dword k of a multi-dword access (and of a typed element over 4 bytes) is 4 · IS bytes after dword k − 1, not 4. Bounds as in Buffer bounds checking, with `idx` = `index` (the lane included), except that OOB_SELECT 3 with SWIZZLE_ENABLE and stride ≠ 0 checks `index >= num_records` or `off + 4k + 4 > stride` (table 35), like mode 0; stride 0 keeps the raw check. A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit. A run-time word1 makes IS = 2^(SWIZZLE_ENABLE · (3 + INDEX_STRIDE)): IS = 1 is the linear address, so one formula serves both and nothing is selected but the mode 3 check; a run-time word3 multiplies the lane by ADD_TID_ENABLE. Cost, measured on the 116 shaders of `runtime/test/shaders` that both versions translate (all `spirv-val` clean before and after): the 56 with a MUBUF access through a run-time V# grow by 15.1 % in SPIR-V lines (+10.4 % over all 116), 30 to 45 instructions per access (address, lane, 4 per extra dword, a select per dword of the bounds check); a literal linear V# gives the same SPIR-V as before. Outside compute and mesh shaders the lane is `SubgroupLocalInvocationId`, so a VS, PS or GS with a run-time V# now declares `GroupNonUniform`. The offset arithmetic is 32-bit, like the linear address. Until 2026-11-22 a literal V# with either bit was `Unsupported` and a run-time one was translated unswizzled. **How confirmed**: Mesa/LLVM and AMD's ISA reference (fields and formula), not measured on hardware; `tests/semantic/test_buffer_swizzle.py` (hand-worked addresses for IS 8/16/64, index msb/lsb, soffset after the swizzle, the mode 3 rule with and without a stride, per-dword x2/x3/x4 loads and stores, a 16-byte typed element, ADD_TID on lane 5 linear and swizzled, each with a literal and a run-time V#); GPU test `runtime/test/shaders/cs_buf_swizzle.asm` (check.py, `scripts/run_gpu_tests.py`), which checks the translation, not RDNA2. **Unmeasured**: the swizzled layout on RDNA2 hardware, offsets that are not dword aligned (the ISA requires alignment for swizzled accesses; the translation adds offset % 4), wrap of the 32-bit offset, and GFX11's two-bit SWIZZLE_ENABLE (word1 [31:30]). In the corpus `SCRATCH_EN` is 0 in every CS, so a swizzled V# can only come from a descriptor the game writes itself. | | Wave64 mask ballot | `tools/lane_masks.py` tracks per-lane masks (including 32-bit `MASK_LO`/`MASK_HI` halves, `vcc_lo`/`vcc_hi`, and `s_bfm_b64` bitfields). `s_bcnt1_i32_b64`/`b32`, `s_bcnt0_i32_b64`/`b32`, `s_ff1_i32_b64`/`b32`, `s_ff0_i32_b64`/`b32`, and `s_bitcmp0/1_b32/b64` reconstruct the 64-bit wave mask via `OpGroupNonUniformBitwiseOr` (`GroupNonUniformArithmetic`), restricting 32-bit half ops and `s_cmp_eq/lg_u32` (`wave_equal`) to the known 32-bit half in wave64. Opposite-half `s_cmp_*_u32/i32` comparisons (lo vs hi), ordering comparisons on mask halves, and `s_cmp_*_u32/i32/u64` comparing a lane mask against an arbitrary scalar or immediate reconstruct the exact 32/64-bit mask words via `wave_mask`. A compare with 0 keeps the vote, but a compare with -1 (all ones) does not: lanes that were never launched (a group smaller than the wave) don't vote, while their bits are 0 in the real mask, so until 2026-11-22 `s_cmp_eq_u32 vcc_hi, -1` read 1 in a 40-thread wave64 for `vcc_hi` = 0xff. GPU-checked with `cs_w64x_partial_scmp.asm` (40-thread wave64, native and `--wave64-emulate`) and `cs_w32_partial_scmp.asm` (20-thread wave32) on an AMD Radeon RX 7800 XT (RADV, Mesa 26.2.6): all 8 words as the headers derive, and 4 of 8 wrong in each with the old translator. GPU-checked with `runtime/test/shaders/cs_wave64_ballot.asm` and `cs_wm_*.asm` on AMD Radeon RX 9070 XT (64-wide subgroup); semantic test coverage in `tests/semantic/test_scalar_bitcmp.py` and `tests/semantic/test_scalar_alu_shifts.py`. | -| Wave64 mask ballot | `tools/lane_masks.py` tracks per-lane masks (including 32-bit `MASK_LO`/`MASK_HI` halves, `vcc_lo`/`vcc_hi`, and `s_bfm_b64` bitfields). `s_bcnt1_i32_b64`/`b32`, `s_bcnt0_i32_b64`/`b32`, `s_ff1_i32_b64`/`b32`, `s_ff0_i32_b64`/`b32`, and `s_bitcmp0/1_b32/b64` reconstruct the 64-bit wave mask via `OpGroupNonUniformBitwiseOr` (`GroupNonUniformArithmetic`), restricting 32-bit half ops and `s_cmp_eq/lg_u32` (`wave_equal`) to the known 32-bit half in wave64. Opposite-half `s_cmp_*_u32/i32` comparisons (lo vs hi), ordering comparisons on mask halves, and `s_cmp_*_u32/i32/u64` comparing a lane mask against an arbitrary scalar or immediate reconstruct the exact 32/64-bit mask words via `wave_mask`. GPU-checked with `runtime/test/shaders/cs_wave64_ballot.asm` and `cs_wm_*.asm` on AMD Radeon RX 9070 XT (64-wide subgroup); semantic test coverage in `tests/semantic/test_scalar_bitcmp.py` and `tests/semantic/test_scalar_alu_shifts.py`. | | VOP3 FP modifiers on constants | `tools/shader_ir.py` keeps VOP3 FP source modifiers (`neg(...)`, `|...|`, `-|...|`, `abs(...)`, and nested combinations) as `abs`/`neg` flags on `imm` and `fimm` operands so `abs` clears the sign bit first and `neg` flips it second (matching LLVM `AMDGPUInstPrinter.cpp::printOperandAndFPInputMods` and `llvm/test/MC/AMDGPU/vop3-modifiers.s`). Plain signed literals (`-1`, `-1.0`) are unchanged. Until 2026-11-22, `-|1.0|` folded `-` into the float before `FAbs` (yielding `+1.0`), `neg(0x3f800000)` / `neg(1)` applied two's-complement integer negation (`-4.0f` / `0xffffffff` NaN instead of `-1.0f` / `0x80000001`), and `|0x...|` / `-|0x...|` dropped `abs`. `tools/shader_meta.py` applies the same bit operations in `_imm_u32`. Checked on the CPU by `tests/test_shader_ir.py`, `tests/test_shader_meta.py` and `tests/semantic/test_vop3_const_mods.py` (f32, f16, `v_fma_mix_f32`, `v_cmp_class_f32`, f64 SPIR-V structure); GPU-checked for `-\|-2.0\|`, `neg(0x3f800000)`, `\|0xbf800000\|` and f16 `-\|0x3c00\|` by `ps_vop3_const_mods.asm` (Tesla V100 (NVIDIA 580.95.05, Linux)). | -| VOP3 FP modifiers on constants | `tools/shader_ir.py` keeps VOP3 FP source modifiers (`neg(...)`, `|...|`, `-|...|`, `abs(...)`, and nested combinations) as `abs`/`neg` flags on `imm` and `fimm` operands so `abs` clears the sign bit first and `neg` flips it second (matching LLVM `AMDGPUInstPrinter.cpp::printOperandAndFPInputMods` and `llvm/test/MC/AMDGPU/vop3-modifiers.s`). Plain signed literals (`-1`, `-1.0`) are unchanged. Until 2026-11-22, `-|1.0|` folded `-` into the float before `FAbs` (yielding `+1.0`), `neg(0x3f800000)` / `neg(1)` applied two's-complement integer negation (`-4.0f` / `0xffffffff` NaN instead of `-1.0f` / `0x80000001`), and `|0x...|` / `-|0x...|` dropped `abs`. `tools/shader_meta.py` applies the same bit operations in `_imm_u32`. Checked on the CPU by `tests/test_shader_ir.py`, `tests/test_shader_meta.py` and `tests/semantic/test_vop3_const_mods.py` (f32, f16, `v_fma_mix_f32`, `v_cmp_class_f32`, f64 SPIR-V structure); **not GPU-verified**. | | Mesh/compute input registers (historical measurement) | An early read-before-write analysis over all compute and mesh shaders found **compute** v0 (880), v0–v1 (614), v0–v2 (50), consistent with AMD's local thread ID x/y/z in v0/v1/v2, and scalar inputs centred on a pointer at s[4:5] and s6/s7. **Mesh:** every one of 2,969 reads exactly **v5**, plus s3 (always arithmetic), s[16:17] and s19–s23. The early pass also read FSSM 0x13C as the group width and compared the first SGPR multiply against it (82 match, 151 don't, 1,447 no simple multiply) and wrongly concluded that 0x13C was not the group width; the matching register varied by shader (s6/s10/s7/s9…). PSV0 gave the real thread-group sizes (32×1×1 for 1,253, 8×8×1 for 416, …). **Superseded:** 0x13C/0x140/0x144 are the thread-group size, `COMPUTE_PGM_RSRC2` at 0x138 gives the per-shader user-SGPR count and enabled workgroup IDs, and mesh takes NumThreads, limits and topology from PSV0 with `v5 = linearGroupIndex * NumThreads + LocalInvocationIndex`. All 2,689 CS and 9,282 mesh shaders translate now (see the Compute shaders and Mesh shaders rows). | | Formerly untranslated | Mesh (9,282), geometry (195) and compute (2,689) now translate; `s_swappc_b64` is replaced by Vulkan vertex inputs (see *Vertex fetch*) and the `tbuffer_load_format_*` forms use the instruction's format. Packed `tbuffer_load_format_d16_{x,xy,xyz,xyzw}` load two 16-bit components per VGPR, with the same final partial write as MUBUF. Native gfx1036 wave32/64 confirmed all four widths for RGBA8_UINT and RGBA8_UNORM with a conflicting 32_UINT V# format. Both packed and ordinary MTBUF loads ignore the V# channel selectors and use identity for the instruction format, zero-filling missing channels. Native gfx1036 measurements compared multiple V# permutations with MUBUF as a control. An INVALID V# format (0) suppresses the MTBUF fetch even at a valid address inside its bounds. Native gfx1036 wave32/64 returned zero components at all four widths and preserved the untouched half of an odd D16 destination, as specified for unbound resources in the [RDNA2 ISA, §8.1.4](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf). A translated vertex fetch on RTX 5080 and Radeon Graphics also followed a change to the instruction format between two draws with identical vertex records and V#. Fixed UNORM and SNORM loads share the exact integer quotient for each magnitude width across instructions and channels (checked against rationally rounded binary32 values on RTX 5080 and Radeon Graphics). The gfx1013 disassembler omits `format:` for the [GFX10 MTBUF default](https://llvm.org/docs/AMDGPUModifierSyntax.html#ufmt), `BUF_FMT_8_UNORM` (code 1). A few rare ops are still reported by name rather than guessed. | diff --git a/tests/test_docs_design_rows.py b/tests/test_docs_design_rows.py new file mode 100644 index 0000000000..4fbc3f759c --- /dev/null +++ b/tests/test_docs_design_rows.py @@ -0,0 +1,60 @@ +"""Each table in docs/design.md names a topic once. + + python -I tests/test_docs_design_rows.py + +The translator contract table is where every new rule is recorded (CONTRIBUTING.md, AGENTS.md). When two branches +edit the same row and a merge keeps both sides, the table ends up with two rows for one topic, each holding facts the +other lacks, and a reader who stops at the first one misses the rest. On 2026-11-22 twenty topics appeared two to six +times. This test fails on a repeated first cell within one table. No game files or build tools. +""" +import os +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +DESIGN = os.path.join(ROOT, "docs", "design.md") + + +def repeated_topics(lines): + """[(topic, [1-based line numbers])] for first cells that appear more than once in one table.""" + found = [] + table, in_fence = [], False + + def close(): + seen = {} + for n in table[2:]: # skip the header and the |---| rule + cells = lines[n - 1].split("|") + if len(cells) > 2 and cells[1].strip(): + seen.setdefault(cells[1].strip(), []).append(n) + found.extend((k, v) for k, v in seen.items() if len(v) > 1) + + for n, line in enumerate(lines, 1): + if line.lstrip().startswith("```"): + in_fence = not in_fence + if not in_fence and line.startswith("|"): + table.append(n) + continue + if table: + close() + table = [] + if table: + close() + return found + + +class DesignTableRows(unittest.TestCase): + def test_checker_finds_a_repeated_topic_within_one_table_only(self): + lines = ["| Topic | Rule |", "|---|---|", "| EXEC | old |", "| LDS | x |", "| EXEC | new |", "", + "| Topic | Rule |", "|---|---|", "| LDS | other table |", "```", "| EXEC | in a code block |", + "| EXEC | in a code block |", "```"] + self.assertEqual(repeated_topics(lines), [("EXEC", [3, 5])]) + + def test_design_md_names_each_topic_once_per_table(self): + with open(DESIGN, encoding="utf-8") as f: + lines = f.read().split("\n") + repeated = repeated_topics(lines) + self.assertEqual(repeated, [], "rows to merge into one (topic, lines): " + + "; ".join(f"{k[:60]!r} at {v}" for k, v in repeated)) + + +if __name__ == "__main__": + unittest.main() From 6c9b7fc11fbd7900bca4a7c62d3368fe44187c3e Mon Sep 17 00:00:00 2001 From: Dandasma Date: Sun, 22 Nov 2026 15:25:54 +0100 Subject: [PATCH 043/115] opus_tags: wrap the --names docstring line to the file's width Review nit on #1731 from adrbn: the edited line was 200 characters; the rest of the file stays within 118. Co-Authored-By: Claude Opus 5.5 --- tools/opus_tags.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tools/opus_tags.py b/tools/opus_tags.py index 51986d3a09..4b29c93283 100644 --- a/tools/opus_tags.py +++ b/tools/opus_tags.py @@ -4,8 +4,9 @@ from two local work products: ``--names`` awc_names.py CSV (source, bank, stream_id, name, rule). A file is matched by its stream id (the file - name; awc_opus.py's ``~2.ogg`` for a second stream with the same id gets the same name) and its bank (the folder path below the Opus folder; if that has no match, the path with its - leading folders removed one at a time, so the Opus folder may hold several archives' outputs). + name; awc_opus.py's ``~2.ogg`` for a second stream with the same id gets the same name) and its + bank (the folder path below the Opus folder; if that has no match, the path with its leading folders + removed one at a time, so the Opus folder may hold several archives' outputs). ``--dialogue`` text_tables.py dialogue CSV (wave, key, label, speaker, text_ ...). A named stream whose name is a dialogue wave gets that line's label, speaker and subtitles. From aaba7e3bcafc630a0d6ec10f589a837adc20175d Mon Sep 17 00:00:00 2001 From: Tayar <358041433+lucastayaralvarenga-ui@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:25:57 -0300 Subject: [PATCH 044/115] wave64_graphics_scan: scan regular shader files only --- tests/test_wave64_graphics_scan.py | 9 +++++++++ tools/wave64_graphics_scan.py | 8 ++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/tests/test_wave64_graphics_scan.py b/tests/test_wave64_graphics_scan.py index 45945cd290..1aff7139ed 100644 --- a/tests/test_wave64_graphics_scan.py +++ b/tests/test_wave64_graphics_scan.py @@ -140,6 +140,15 @@ def test_main_json_has_no_shader_names(self): class CliTests(unittest.TestCase): + def test_scan_ignores_shader_named_directories(self): + with tempfile.TemporaryDirectory() as src: + os.mkdir(os.path.join(src, "cache.s")) + name, text = PS_W64_SENSITIVE + with open(os.path.join(src, name), "w", encoding="utf-8") as f: + f.write(text) + report = scan.scan_directory(src) + self.assertEqual(report["per_stage"]["ps"]["shaders"], 1) + def test_missing_source_directory_raises_error(self): with self.assertRaises(SystemExit) as cm: with contextlib.redirect_stderr(io.StringIO()): diff --git a/tools/wave64_graphics_scan.py b/tools/wave64_graphics_scan.py index b9410a5e8f..3459f0a104 100644 --- a/tools/wave64_graphics_scan.py +++ b/tools/wave64_graphics_scan.py @@ -96,10 +96,10 @@ def scan_directory(disasm): "mask_word_source": {"exec_vcc": Counter(), "other": Counter()}} for stage in GRAPHICS} other = {"shaders": 0, "wave64": 0} - for name in sorted(os.listdir(disasm)): - if not name.endswith(".s"): - continue - path = os.path.join(disasm, name) + with os.scandir(disasm) as entries: + paths = sorted(entry.path for entry in entries + if entry.name.endswith(".s") and entry.is_file()) + for path in paths: info = parse_file(path) stage = rdna2spirv.stage_of(info["name"], path) wave64 = wave64_rule(stage, info["insns"]) From 40e17da629f1fe1d2d458a02c61955ef86fa8cec Mon Sep 17 00:00:00 2001 From: Shadman PC Date: Sun, 22 Nov 2026 20:03:17 +0600 Subject: [PATCH 045/115] fix(translator): round v_fma_mixlo/hi_f16 once to f16 (SHADER-297) Hardware measurement on RDNA2 (gfx1036, finding 7079901079) confirms that v_fma_mixlo_f16 / v_fma_mixhi_f16 round the exact fma once, straight to f16, across all rounding modes (7 of 7 discriminating cases in tools/fma_mix_probe.py match single rounding). The translator previously double-rounded in nearest-even mode (f32 Fma then f16 narrow). Change v_fma_mixlo_f16 / v_fma_mixhi_f16 to use Gen.fma_mix_odd across all modes, which rounds to odd at f32 so that narrowing to f16 gives the exact single-rounded result in both nearest-even and toward-zero modes. Update tests/test_fma_mix_probe.py and docs/shader_validation.md to reflect the RDNA2 hardware measurement, and add discriminating semantic tests in tests/semantic/test_valu_fma_mix.py. AI-assisted. --- docs/design.md | 4 ++-- docs/shader_validation.md | 17 +++++++++-------- tests/semantic/test_valu_fma_mix.py | 19 +++++++++++++++++++ tests/test_fma_mix_probe.py | 11 +++++------ tools/rdna2spirv.py | 11 +---------- 5 files changed, 36 insertions(+), 26 deletions(-) diff --git a/docs/design.md b/docs/design.md index 9e38cc015f..31b3280b90 100644 --- a/docs/design.md +++ b/docs/design.md @@ -359,13 +359,13 @@ How the generated SPIR-V expects the runtime to work: | `v_min3_f16`, `v_max3_f16`, `v_min3_i16`, `v_min3_u16`, `v_max3_i16`, `v_max3_u16`, `v_med3_i16`, `v_med3_u16` | Three-operand 16-bit min/max/median (VOP3 only). `op_sel` bits 0..2 read the high half of S0..S2, bit 3 writes the high half of D, and the unwritten half of D is kept (see *16-bit results*). `v_min3_f16` and `v_max3_f16` read each selected f16 half through `Gen.f16_in` (`neg`/`abs` apply to the selected half), fold with `NMin`/`NMax` (so a NaN operand yields the other operand and −0 orders below +0, matching `v_min3_f32`/`v_max3_f32` and `v_med3_f16`), then apply VOP3 `omod`/`clamp` and `Gen.f16_out`. The 16-bit integer ops zero-extend (`u16`) or sign-extend (`i16`) the selected 16-bit halves, evaluate `UMin`/`UMax`/`UClamp` or `SMin`/`SMax`/`SClamp`, and write the low 16 bits into the selected half of D; `clamp` and non-VGPR `op_sel` destinations raise `Unsupported`. Until 2026-11-22 all eight raised `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) VOP3 opcodes `0x351`–`0x356`, `0x359`–`0x35A`, and Mesa ACO's `can_use_opsel`. **Not GPU-verified.** CPU-checked by `tests/semantic/test_alu_min3_max3_med3_16.py`, `tests/test_f16_op_sel.py`, and `tests/test_f16_op_sel_values.py`. | | `v_cvt_flr_i32_f32`, `v_cvt_rpi_i32_f32` | RDNA ISA pseudocode: `f32_to_i32(floor(S0))` and `f32_to_i32(floor(S0 + 0.5))`, the `+ 0.5` rounded in binary32 like any f32 add (so 0.49999997 gives 1, where an exact round-half-up would give 0). `f32_to_i32` saturates as in the row above: INT_MAX / INT_MIN at or past ±2³¹ and for ±inf, 0 for NaN. Source neg/abs apply first. Checked on the CPU by `tests/semantic/test_alu_cvt_flr_rpi.py`, **not yet GPU-verified**. | | `v_cvt_pknorm_i16_f32`, `v_cvt_pknorm_u16_f32` | D[15:0] from S0 and D[31:16] from S1: the f32 is clamped to [-1, 1] (i16) or [0, 1] (u16), multiplied by 32767 or 65535 and rounded to nearest even. Mesa ACO emits these opcodes for NIR `pack_snorm_2x16`/`pack_unorm_2x16`, which `nir_opcodes.py` defines as `fround_even(fclamp(x) * 32767.0 / 65535.0)`. Emitted as `FClamp`, `OpFMul`, `RoundEven` and a convert, not `PackSnorm2x16`, whose rounding GLSL leaves to the driver. NaN gives 0, as `v_cvt_i32_f32` does; that is **not measured on hardware**. Source modifiers apply. `clamp` raises `Unsupported`. Until 2026-11-22 both ops were rejected. CPU-checked by `tests/semantic/test_alu_cvt_pknorm_f32.py` (ties at the scale steps, ±inf, ±NaN, subnormals, out-of-range values, 40 seeded pairs, abs/neg). **Not GPU-verified.** | -| f16 rounding (SHADER-55, SHADER-56) | **Narrowing to f16 uses integer ops, not `PackHalf2x16`.** Every f16 ALU result (`v_*_f16` VOP1/VOP2/VOP3, `v_pk_*_f16`, `v_cvt_f16_f32`, `v_interp_p2_f16`, `v_fma_mix*`) and `v_cvt_pkrtz_f16_f32` go through `Gen.f16_bits` (round to nearest even, or round toward zero for pkrtz; f16 denormals kept, f32 denormal inputs give ±0, NaN stays a quiet NaN). After a MODE.FP_ROUND toward-zero write the ALU results take the toward-zero form instead (`Gen.f16_res`; see Known approximations). GLSL.std.450 leaves `PackHalf2x16`'s rounding to the implementation, and drivers fold a `PackHalf2x16` → `UnpackHalf2x16` round trip to a no-op, so the next f16 op saw the unrounded f32: #513 (RTX 6000 Ada, `--wave64-emulate`, `v_pk_add_f16` → `v_pk_mul_f16` 1 ulp off), and pkrtz giving round-to-nearest on llvmpipe. **f16 FMAs round once** (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`): x·y is exact in f32, TwoSum gives the exact error of the f32 sum, and round-to-odd at f32 then rounds correctly to f16. An RX 6700 matched a correctly rounded f16 FMA in 12,612 of 12,612 cases (#374); `Fma` then narrowing double-rounded. Checked by `tests/semantic/test_f16_int_convert.py` (edges + seeded sweep against Python's binary16), `tests/semantic/test_f16_fma_rounding.py` (exact rational reference; built near-tie cases fail on the old translation) and `tools/valu_fuzz.py --family f16` on an RTX 6000 Ada. Image/buffer d16 packing (#489) and the 16-bit interpolant quantize (#512) are separate. `v_fma_mix*` with f32 sources uses `Fma` then narrows (two roundings) in nearest-even mode, while the hardware rounds once: 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135; not fixed yet); toward zero it rounds once (see Known approximations). | +| f16 rounding (SHADER-55, SHADER-56) | **Narrowing to f16 uses integer ops, not `PackHalf2x16`.** Every f16 ALU result (`v_*_f16` VOP1/VOP2/VOP3, `v_pk_*_f16`, `v_cvt_f16_f32`, `v_interp_p2_f16`, `v_fma_mix*`) and `v_cvt_pkrtz_f16_f32` go through `Gen.f16_bits` (round to nearest even, or round toward zero for pkrtz; f16 denormals kept, f32 denormal inputs give ±0, NaN stays a quiet NaN). After a MODE.FP_ROUND toward-zero write the ALU results take the toward-zero form instead (`Gen.f16_res`; see Known approximations). GLSL.std.450 leaves `PackHalf2x16`'s rounding to the implementation, and drivers fold a `PackHalf2x16` → `UnpackHalf2x16` round trip to a no-op, so the next f16 op saw the unrounded f32: #513 (RTX 6000 Ada, `--wave64-emulate`, `v_pk_add_f16` → `v_pk_mul_f16` 1 ulp off), and pkrtz giving round-to-nearest on llvmpipe. **f16 FMAs round once** (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`): x·y is exact in f32, TwoSum gives the exact error of the f32 sum, and round-to-odd at f32 then rounds correctly to f16. An RX 6700 matched a correctly rounded f16 FMA in 12,612 of 12,612 cases (#374); `Fma` then narrowing double-rounded. Checked by `tests/semantic/test_f16_int_convert.py` (edges + seeded sweep against Python's binary16), `tests/semantic/test_f16_fma_rounding.py` (exact rational reference; built near-tie cases fail on the old translation) and `tools/valu_fuzz.py --family f16` on an RTX 6000 Ada. Image/buffer d16 packing (#489) and the 16-bit interpolant quantize (#512) are separate. `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (see Known approximations). | | `v_interp_p2_f16` clamp | The VOP3 `clamp` bit on `v_interp_p2_f16` clamps its f16 result to [0, 1], applied before the narrowing like the other f16 results (Mesa ACO `aco_opcodes.py` declares the op `dst(F16)`, which takes output modifiers; llvm-mc encodes `clamp` on it but no omod). Until 2026-11-22 the translator dropped it. Checked by `tests/semantic/test_interp_f16.py`: attributes 1.5 and -0.25 read with clamp give 1.0 and +0.0, and without it 1.5 and -0.25. No GPU test: `vs_ids` gives attributes in [0, 1) only. | | 16-bit interpolation (`v_interp_p1ll_f16` / `v_interp_p2_f16`, `high`) | A 16-bit varying shares its 32-bit param channel with another: the producer packs them as low half, high half (Mesa `ac_nir_prerast_utils.c`: `nir_pack_32_2x16_split` by `io_sem.high_16bits`), the PS sets `FP16_INTERP_MODE` (plus `ATTR1_VALID` when the high half is used, RADV `radv_ps_input_type_bits`), and the `high` bit picks the half on both ops of the pair (ACO `emit_interp_instr`, `aco_isel_helpers.cpp`; llvm-mc gfx1013 sets the same bit, byte 5 bit 0, on both: p1ll `v2, v0, attr0.x high` 0x00 → 0x01, p2 `v2, v1, attr0.x, v3 high` 0x02 → 0x03). The translated VS exports the channel's raw bits, so interpolating them as one f32 gives neither half. A location any `*_f16` interp reads is therefore declared `PerVertexKHR` (`vec4[3]`, no `Flat`; it still matches a producer's vec4 output at that location); this needs `VK_KHR_fragment_shader_barycentric` (`fragmentShaderBarycentric`) for every such PS, not just the raw-barycentric ones; the index records it like any capability (`features: ["fragmentShaderBarycentric"]`), so `vk_pipeline_check` and `vk_harness` skip such a PS on a device without it. Nothing picks `--bary-fallback` from the device: it is a translation-time flag. Each f16 read decodes its half of each vertex's word (`UnpackHalf2x16` component 0 or 1) and weights them as AMD does, P0 + i(P1 − P0) + j(P2 − P0) with i, j = `BaryCoordKHR`.y/.z, then p2 clamps and narrows as before. f32 reads of such a location (`p1/p2_f32`) interpolate the raw word the same way, and `v_interp_mov_f32` takes vertex 0's. Until 2026-11-22 `high` was ignored and both halves read the smooth-f32 interpolation of the whole word; abilliontokens counted `high` in 4,776 of 12,101 PS (39.5%, 51,684 instructions, always p1ll/p2 pairs, no `p1lv`), and Pipodi found 4,731 of those 4,776 read both halves of the same channel, with p1ll and p2 always agreeing on attribute, channel and `high`. Like the f32 path, the pair's I/J operands are not read: the weights come from `BaryCoordKHR` (213 PS that compute their own barycentrics into v0/v1 first are a separate gap). Confirmed by `tests/semantic/test_interp_f16_high.py` (per-vertex halves 0.5/1.5/2.5 and −4/8/16 at weights (0.25, 0.25, 0.5) give 1.75 and 9.0; fails on the old translation) and the GPU fixture `ps_interp_f16_high` drawn with `vs_f16_pack` (u and v packed in one channel both ways, f32 control) and, through `scripts/run_gpu_tests.py`, with the mesh producer `ms_f16_pack` (mesh `exp paramN` stores the same raw words, `Gen.ms_export`): both pass on an RTX 5070 and fail on the old translation (off by 0.984). spirv-val and `vk_pipeline_check` (real pipelines against the vec4 VS stubs, RTX 5070) also accept PS mixing high, low, f32 and flat reads of one location and of several. **Unverified:** AMD hardware (whether it computes P10/P20 in f16 or rounds the p1ll intermediate differently), f16 denormal and NaN halves. **`--bary-fallback`** has no per-vertex inputs, so it keeps the old smooth-f32 read and cannot honour `high`; `check.py` skips the fixture there. MoltenVK can't compile `PerVertexKHR`: see the next row. | | 16-bit interpolation without `PerVertexKHR` (`--f16-interp-fallback`) | MoltenVK reports `fragmentShaderBarycentric` but can't create a pipeline with the row above's inputs: its SPIR-V to MSL conversion stops with "PerVertexKHR decoration is not supported in MSL" (MoltenVK 1.4.2 on an Apple A18 Pro and, reported by @DomasUrbonas in #166, an M4 Pro), so `ps_interp_f16_high` failed on every Mac. With the flag no `PerVertexKHR` (and, for these reads, no `BaryCoordKHR`) is used: every VS `exp paramN`, mesh param and `--mesh-compute` vertex (`tools/mesh_compute_vs.py`) also exports the channel's two f16 halves decoded to f32 (`UnpackHalf2x16`), low halves at location 29 − 2N and high halves at 30 − 2N, below MoltenVK's 31 locations (124 components); a PS `*_f16` read of attrN.c takes component c of that ordinary smooth input, then p2 clamps and narrows as before. Interpolation is linear, so the device interpolating the decoded halves gives the same P0 + i(P1 − P0) + j(P2 − P0) as the per-vertex path, with the interpolator's rounding instead of explicit f32 arithmetic. f32 and `v_interp_mov_f32` reads of such a location are the raw word as on any location (flat = the provoking vertex's word, exact). A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(29 − P) / 2), and a PS whose decoded-half location is also an attribute it reads is rejected (`Unsupported`), not mislinked. The index records `f16_halves` ({param: [low, high location]}) on both sides; a pipeline links when the PS's entries are among its producer's. Chosen like the wave64 mode: `tools/vk_subgroup_info.py` reports `per_vertex_inputs` (false without `fragmentShaderBarycentric` or on driver ID MoltenVK), and `make_game.py` and `run_gpu_tests.py` turn the flag on where it is false (`LEONIDA_F16_INTERP_FALLBACK=1`/`0` overrides the runner; `build.py` takes only the variable, since it may run in WSL). Without the flag the translation is unchanged: all 139 GPU-test modules are byte-identical to main's, with and without `--bary-fallback` and with `--mesh-compute --wave64-emulate`, so NVIDIA and AMD keep the exact per-vertex path. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_interp_f16_high` drawn with `vs_f16_pack` passes natively and with wave64 emulation, every one of its 4,096 pixels bit-exact to f16 of the exact u and v in both halves (it failed before at pipeline creation), and `ms_f16_pack` through `--mesh-compute` (`LEONIDA_MESH_COMPUTE=1`) passes too; `tests/semantic/test_f16_interp_fallback.py` checks the PS reads (1.75 and 9.0 from the decoded halves), the VS exports (one-lane interpreter), the overlap rules and the default being unchanged. **Unverified:** a PS whose producer exports more params than leave room for the halves it reads (it reads that producer's param, not halves: the `f16_halves` entries then don't match); devices with fewer than 31 output locations. Not combined with `--bary-fallback`'s geometry shader. | | `v_fmac_f16`, `v_interp_p2/mov_f32` output modifiers | VOP3 `mul:2`/`mul:4`/`div:2` (applied first) and `clamp` to [0, 1] apply to `v_fmac_f16_e64` (before narrowing to f16, matching `v_fma_f16`, high half preserved) and to `v_interp_p2_f32_e64` / `v_interp_mov_f32_e64` (no-op when no modifier is present). Until 2026-11-22 all three dropped output modifiers. Source: LLVM `llvm/test/MC/AMDGPU/gfx10_asm_vop2.s` (`v_fmac_f16_e64`) and `gfx10_asm_vop3.s` (`v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`). Checked on the CPU by `tests/semantic/test_f16_fma_rounding.py` (`test_fmac_output_modifiers`) and `tests/semantic/test_interp_f32_mods.py`, and on a GPU by `ps_fmac_f16_mods.asm`, `ps_interp_f32_mods.asm` and `ps_interp_mov_mods.asm` (the last two drawn with `vs_interp_consts.asm`, whose params are constant over the triangle; each modifier and the omod-before-clamp order change a word; Tesla V100 (NVIDIA 580.95.05, Linux)). **The hardware ignores the f16 omod in the MODE the translator assumes:** on an RDNA2 iGPU (gfx1036) `mul:2`/`mul:4`/`div:2` change an f16 result (`v_fmac_f16`, `v_add/mul/fma_f16`, `v_cvt_f16_f32`, `v_exp/rcp_f16`) only with IEEE 0 and `denorm_mode_16_64 = 0`, and do nothing with f16 denormals kept; omod comes before clamp, and clamp gives +0 for -0 and, with DX10_CLAMP 1, for a NaN (SHADER-135, docs/shader_validation.md). The translator is not changed yet: which of omod and the kept f16 denormals is wrong for the game is a corpus question. | | 16-bit vector compare `op_sel` (`v_cmp(x)_*_{f16,u16,i16}`) | VOP3 `op_sel:[s0,s1]` selects bit `[15:0]` (`0`) or `[31:16]` (`1`) of each source before f16 input modifiers (`neg`/`abs`, via `Gen.f16_in`) or `u16`/`i16` zero-/sign-extension (`OpBitFieldUExtract`/`OpBitFieldSExtract` at bit offset 16 when set, 0 otherwise); VOPC writes a scalar lane mask (VCC/SGPR or EXEC for `v_cmpx`), so there is no destination `op_sel` bit. Until 2026-11-22 `Gen.compare` hardcoded the low half and ignored `mods`. Source: AMD RDNA2 ISA VOP3 `op_sel` and Mesa ACO `can_use_opsel`. Checked on the CPU by `tests/semantic/test_vcmp16_opsel.py` (all four `op_sel` combinations across `f16` relations/ordered/unordered/NaN/`neg`/`abs`, `u16`, signed `i16`, and `v_cmpx` wave32/wave64 EXEC updates via `spirv_mini_interp` and `spirv_wave_interp`); **not GPU-verified**. | -| Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode; the ALU ones follow a MODE toward-zero write (below; ALU sites: see the f16 rounding row). MODE: `s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2)` (f16/f64 rounding) is tracked in a per-invocation variable, the only MODE field the corpus writes (9,417 writes in 6,333 shaders: 6,694 toward zero, 2,723 back to nearest even). While it is toward zero, every VALU f16 result except the transcendentals listed below (`v_cvt_f16_f32`, f16 arithmetic, `v_pk_*_f16`, `v_fma_mix{lo,hi}_f16`, `v_interp_p2_f16`) rounds toward zero exactly, with the integer conversion `v_cvt_pkrtz_f16_f32` uses (`f16_bits(rtz=True)`, see the f16 rounding row), and `v_add_f64` steps back one ulp when the TwoSum error shows it rounded away from zero; finite overflow gives the largest finite value. The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product (|x*y| < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). | +| Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode; the ALU ones follow a MODE toward-zero write (below; ALU sites: see the f16 rounding row). MODE: `s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2)` (f16/f64 rounding) is tracked in a per-invocation variable, the only MODE field the corpus writes (9,417 writes in 6,333 shaders: 6,694 toward zero, 2,723 back to nearest even). While it is toward zero, every VALU f16 result except the transcendentals listed below (`v_cvt_f16_f32`, f16 arithmetic, `v_pk_*_f16`, `v_fma_mix{lo,hi}_f16`, `v_interp_p2_f16`) rounds toward zero exactly, with the integer conversion `v_cvt_pkrtz_f16_f32` uses (`f16_bits(rtz=True)`, see the f16 rounding row), and `v_add_f64` steps back one ulp when the TwoSum error shows it rounded away from zero; finite overflow gives the largest finite value. The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 and verified by `tools/fma_mix_probe.py`; finding 7079901079): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction. `fma_mix_odd` also handles a tiny product (|x*y| < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). | | Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` (SHADER-118) | The three have no f32 denormal support: a subnormal operand, the rounded product or the result reads as signed zero, whatever the MODE register says. `Gen.flush_f32` emits `|x| < FLT_MIN → copysign(0, x)` on the three operands, after the product rounding and after `omod`/`clamp`; inf and NaN compare false and pass through, and 0 keeps its sign. Source: LLVM AMDGPU `SIISelLowering.cpp`, `SITargetLowering::isFMADLegal` (llvm-project `1922c0c`), which forms `v_mad_f32`/`v_mac_f32` only when f32 denormals are flushed. Corpus count with `tools/shader_profile.py` over the 26,503 gfx1013 shaders: `v_mad_f32` in 7,298 shaders (139,287 occurrences), `v_mac_f32` in 5,889 (276,806: 265,901 `_e32`, 10,811 `_e64`, 94 `_dpp`), `v_mad_legacy_f32` in 6,059 (24,765); 9,297 shaders (35.1%) use at least one, 440,858 occurrences (0.99% of the corpus's 44,406,870 instructions). Checked on the CPU by `tests/semantic/test_valu_f32_min3_max3_mad.py` (`DenormalFlushTests`: the flush column, NaN/inf/zero pass-through, and a sabotaged pass-through that fails); **not GPU-verified** — a native measurement still needs an RDNA1/RDNA2 part that has these opcodes. The `omod` order is an assumption: the flush runs after `div:2`/`mul:2`/`mul:4`, so `FLT_MIN div:2` is flushed, as pinned by that test. | | `v_mac_legacy_f32` | The GFX10.1 VOP2 form of `v_mad_legacy_f32` with D as the addend: D = legacy(S0 * S1) + D, where 0 times anything (inf and NaN included) is +0, with the same denormal flush and VOP3 modifiers. D is read before it is written, as for `v_mac_f32` (LLVM `VOP2Instructions.td`: `V_MAC_LEGACY_F32` has `$src2` tied to `$vdst`). Until 2026-11-22 it raised `Unsupported`. CPU-checked by `MacLegacyF32Tests` in `tests/semantic/test_valu_f32_min3_max3_mad.py` (a 15x8x6 grid against the `v_mad_legacy_f32` reference, the zero rule, clamp/neg, D aliased as a source). **Not GPU-verified**: like the other mad opcodes it exists on gfx1010-1013 only, so no RDNA2 desktop part runs it. | | Whole-quad mode (`s_wqm_b64` / `s_wqm_b32`) | A lane mask register holds only this lane's bit, so WQM on one (EXEC, VCC, an SGPR the mask analysis found) ORs the bit of the lane's quad, lanes 4n..4n+3 of the wave: two `OpGroupNonUniformQuadSwap` (horizontal, then vertical; capability `GroupNonUniformQuad`) in the default mode in fragment and compute shaders (quad operations are only guaranteed there; vertex, geometry and mesh shaders shuffle from the quad's four lanes), or the four lanes' values read through `%x_buf` under `--wave64-emulate` (no subgroup operation there). A quad never crosses lane 31/32, so the mask bits are exact per half on a 32-wide subgroup; SCC is a wave vote, so on wave64 it needs a 64-wide subgroup or `--wave64-emulate` (as every wave-wide mask op). The result goes to EXEC, VCC or an SGPR pair as a mask, SCC = the wave-wide any of it (same vote as the other mask ops). A 32-bit form in wave64 (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`, a half-mask SGPR) writes only its own half (`exec_half_write`) and votes SCC over that half only (`cs_wqm_w64_half`). A source that is not a lane mask (a value loaded from memory, a literal) is data: `((x | x>>1 | x>>2 | x>>3) & 0x11111111) * 15` per 32-bit word and SCC = result != 0, no subgroup operation. Assumptions: in compute and mesh shaders the subgroup lane is `LocalInvocationIndex` mod the subgroup size (as for every cross-lane op); a hardware quad is four consecutive lanes of a wave, and in a pixel shader Vulkan's quad (the 2x2 pixels, helper invocations included) is the same four lanes; GPU-checked on both AMD and NVIDIA with `ps_wqm.asm` (every 2x2 block of a 64x64 target, fully covered). Not covered: helper-invocation behaviour at triangle edges is untested, and in native mode an absent invocation in a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value (emulated, the missing lanes of a partial wave read as 0). Before this the instruction was the identity, so helper lanes stayed off (#156 SHADER-34: `s_wqm_b64` appears in 4,285 pixel shaders). GPU-checked with `runtime/test/shaders/cs_wqm_w64.asm`, `cs_wqm_w64_half.asm`, `cs_wqm_w32.asm` and `ps_wqm.asm` on AMD Radeon 880M (subgroup 64) and NVIDIA GeForce RTX 5070 Laptop (subgroup 32; `cs_wqm_w64` there needs `LEONIDA_W64_EMULATE=1`), with and without `--wave64-emulate`. | diff --git a/docs/shader_validation.md b/docs/shader_validation.md index fc7b3d5ac2..093dcc3f35 100644 --- a/docs/shader_validation.md +++ b/docs/shader_validation.md @@ -978,21 +978,22 @@ side follows the same rule. Exit 1 means they differ, or a side follows neither is unavailable. `tests/test_fma_mix_probe.py` checks the expected words against a derivation written out by hand. It also checks that -the translator follows the double rule today, and that the compute shader gives the pixel shader's words on the -interpreter. If the hardware rounds once, the fix is to use `Gen.fma_mix_odd` in nearest mode as well. Round-to-odd at -f32 then narrows exactly. With that change the translator gives the single-rounded word on all seven inputs. +the translator follows the single rounding rule, and that the compute shader gives the pixel shader's words on the +interpreter. Hardware measurement on AMD RDNA2 confirmed that the hardware rounds once, straight to f16, so the translator +uses `Gen.fma_mix_odd` in nearest mode as well. Round-to-odd at f32 then narrows exactly, giving the single-rounded word on +all seven discriminating inputs. Results: | GPU | Driver | `translator` | `vulkan` | `hw` | |---|---|---|---|---| -| NVIDIA GeForce RTX 5060 (Blackwell), Windows 11 | 621.24 | double | double, 8 of 8 words | not AMD | -| AMD Radeon iGPU (RDNA2, gfx1036), Windows 11, HIP backend | 32.0.21044.64 | double | not run | **single**, 7 of 7 ties; control `0x4100` | +| NVIDIA GeForce RTX 5060 (Blackwell), Windows 11 | 621.24 | single | single, 8 of 8 words | not AMD | +| AMD Radeon iGPU (RDNA2, gfx1036), Windows 11, HIP backend | 32.0.21044.64 | single | single, 8 of 8 words | **single**, 7 of 7 ties; control `0x4100` | RDNA2 rounds once. Every tie input gives the single-rounded word (A `0x3c01`, B `0x3c01`, C `0xbc01`, D `0x0001`, -E `0x7bff`, F `0x3c01`, G `0x3c01`), so the translator is one f16 ulp off on exactly these inputs (SHADER-135; the -translator is not changed here). On the RTX 5060, a translator copy changed to use -`fma_mix_odd` in nearest mode gave the single-rounded word for all seven inputs on the `vulkan` side as well. +E `0x7bff`, F `0x3c01`, G `0x3c01`), which the translator produces across all 7 discriminating cases via +`fma_mix_odd` in both nearest-even and toward-zero modes (SHADER-297). On Vulkan, using `fma_mix_odd` matches the +exact single-rounded hardware words for all inputs. ### f16 output modifiers, clamp and `v_fma_mix*` operands on RDNA2 (SHADER-135) diff --git a/tests/semantic/test_valu_fma_mix.py b/tests/semantic/test_valu_fma_mix.py index 1d0730fe3f..deb855e4b7 100644 --- a/tests/semantic/test_valu_fma_mix.py +++ b/tests/semantic/test_valu_fma_mix.py @@ -212,6 +212,25 @@ def test_destination_aliases_source(self): got = run("v_fma_mixhi_f16 v0, v0, v1, v2 op_sel:[0,0,0] op_sel_hi:[1,0,1]", f2u(2.0), pack_h(0.5, 9.0), 0, old=old) self.assertEqual(got, pack_h(1.5, 3.5)) + def test_single_rounding_discriminating_cases(self): + # Discriminating test cases A through G from tools/fma_mix_probe.py where + # hardware single rounding gives 1 ulp difference from double rounding. + # Case A: 1 * 2^-40 + (1 + 2^-11) -> single: 0x3c01, double: 0x3c00 + got_a = run("v_fma_mixlo_f16 v0, v1, v2, v3", 0x3F800000, 0x2B800000, 0x3F801000, old=OLD) + self.assertEqual(got_a, (OLD & 0xFFFF0000) | 0x3C01) + + # Case B: 1 * -2^-40 + (1 + 3 * 2^-11) -> single: 0x3c01, double: 0x3c02 + got_b = run("v_fma_mixhi_f16 v0, v1, v2, v3", 0x3F800000, 0xAB800000, 0x3F803000, old=OLD) + self.assertEqual(got_b, (0x3C01 << 16) | (OLD & 0xFFFF)) + + # Case C: -1 * 2^-40 - (1 + 2^-11) -> single: 0xbc01, double: 0xbc00 + got_c = run("v_fma_mixlo_f16 v0, v1, v2, v3", 0xBF800000, 0x2B800000, 0xBF801000, old=OLD) + self.assertEqual(got_c, (OLD & 0xFFFF0000) | 0xBC01) + + # Case G (f16 operands): (1 + 2^-7) * (2^-11 - 2^-18) + (1 + 2^-10) -> single: 0x3c01, double: 0x3c02 + got_g = run("v_fma_mixlo_f16 v0, v1, v2, v3 op_sel_hi:[1,1,1]", 0x3C08, 0x0FF0, 0x3C01, old=OLD) + self.assertEqual(got_g, (OLD & 0xFFFF0000) | 0x3C01) + class NegativeControls(unittest.TestCase): """Sabotaging the translated SPIR-V must change the observed output.""" diff --git a/tests/test_fma_mix_probe.py b/tests/test_fma_mix_probe.py index db85fcd080..46c49f0cdf 100644 --- a/tests/test_fma_mix_probe.py +++ b/tests/test_fma_mix_probe.py @@ -65,14 +65,13 @@ def test_operand_refuses_what_the_model_does_not_cover(self): class Translator(unittest.TestCase): - def test_translator_rounds_twice(self): - # docs/design.md, Known approximations: nearest-mode v_fma_mix* takes the f32 Fma and then narrows. If the - # translator is changed to round once (after a hardware measurement), this test and that sentence change too. + def test_translator_rounds_once(self): + # docs/design.md, Known approximations: v_fma_mix* rounds once straight to f16 (measured on RDNA2 hardware). got = probe.run_translator() rule, _ = probe.verdict(list(zip(probe.CASES, got))) - self.assertEqual(rule, probe.DOUBLE) + self.assertEqual(rule, probe.SINGLE) for case, w in zip(probe.CASES, got): - self.assertEqual(w, word(case, BY_HAND[case.name][1]), case.name) + self.assertEqual(w, word(case, BY_HAND[case.name][0]), case.name) def test_compute_listing_gives_the_pixel_shader_words(self): # The Vulkan side's shader (operands from user SGPRs, one store per case) on the CPU interpreter, with the @@ -149,7 +148,7 @@ def test_translator_only_run_exits_0(self): with contextlib.redirect_stdout(buf): rc = probe.main([]) self.assertEqual(rc, 0) - self.assertIn("translator: follows double rounding", buf.getvalue()) + self.assertIn("translator: follows single rounding", buf.getvalue()) def test_unknown_side_and_missing_build_are_usage_errors(self): import contextlib diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 9b6fe70df1..8f66149ab0 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -6417,16 +6417,7 @@ def halves(s, is_mask): self.scc_nonzero(r) elif op in ("v_fma_mixlo_f16", "v_fma_mixhi_f16"): vals = self.fma_mix_srcs(a, mods) - r = self.tmp() - self.emit_fma(r, vals[0], vals[1], vals[2]) - if self.round_mode: - # Toward zero the hardware rounds the exact fma once, to f16; round-to-odd at f32 narrows exactly. - # Nearest even keeps the f32 Fma then narrow (unchanged). - ro, m, isz, rs = self.fma_mix_odd(*vals), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{m} = OpLoad %uint %mode_r16") - self.emit(f"{isz} = OpIEqual %bool {m} {self.cu(3)}") - self.emit(f"{rs} = OpSelect %float {isz} {ro} {r}") - r = rs + r = self.fma_mix_odd(*vals) r = self.clamp_mods(r, mods) self.f16_out(a[0], r, hi=(op == "v_fma_mixhi_f16")) elif op == "v_cvt_pk_u8_f32": From dd12fb296af4fb7df08fe93ff1f4d083048952fe Mon Sep 17 00:00:00 2001 From: Tayar <358041433+lucastayaralvarenga-ui@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:26:04 -0300 Subject: [PATCH 046/115] world_lights_paths: reject colliding light and summary reports --- tests/test_world_lights_paths.py | 10 ++++++++++ tools/world_lights_paths.py | 11 +++++++++++ 2 files changed, 21 insertions(+) diff --git a/tests/test_world_lights_paths.py b/tests/test_world_lights_paths.py index 2ca8d60526..7ab8a665d4 100644 --- a/tests/test_world_lights_paths.py +++ b/tests/test_world_lights_paths.py @@ -371,6 +371,16 @@ def test_jobs_give_the_same_summary(self): two = T.summarize(T.scan(self.rpf, jobs=2)) self.assertEqual(one, two) + def test_cli_rejects_shared_report_destination(self): + out = os.path.join(self.tmp.name, "lights.json") + alias = os.path.join(self.tmp.name, ".", "lights.json") + err = io.StringIO() + with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as cm: + T.main([self.rpf, "--out", out, "--lights-out", alias]) + self.assertEqual(cm.exception.code, 2) + self.assertIn("--out and --lights-out must use different paths", err.getvalue()) + self.assertFalse(os.path.exists(out)) + def test_cli_writes_summary_and_placed_lights(self): out = os.path.join(self.tmp.name, "summary.json") lights = os.path.join(self.tmp.name, "lights.jsonl") diff --git a/tools/world_lights_paths.py b/tools/world_lights_paths.py index ee1c78c3dc..65bce000b1 100644 --- a/tools/world_lights_paths.py +++ b/tools/world_lights_paths.py @@ -708,6 +708,15 @@ def summarize(total, entities=None, lights_out=None): return summary +def same_report_path(first, second): + if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): + return True + try: + return os.path.samefile(first, second) + except OSError: + return False + + def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("archive") @@ -727,6 +736,8 @@ def main(argv=None): if a.entities and not os.path.isfile(a.entities): print(f"ERROR: {a.entities}: no such file", file=sys.stderr) return 2 + if a.out and a.lights_out and same_report_path(a.out, a.lights_out): + ap.error("--out and --lights-out must use different paths") total = scan(a.archive, a.jobs, a.start, a.limit, bool(a.lights_out)) summary = summarize(total, a.entities, a.lights_out) text = json.dumps(summary, indent=1, sort_keys=True) From 376f17dffcf494e144c247f29ceb17177aaf5ee4 Mon Sep 17 00:00:00 2001 From: Tayar <358041433+lucastayaralvarenga-ui@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:26:12 -0300 Subject: [PATCH 047/115] bink_names: reject negative alignment skip counts --- tests/test_bink_names.py | 12 ++++++++++++ tools/bink_names.py | 2 ++ 2 files changed, 14 insertions(+) diff --git a/tests/test_bink_names.py b/tests/test_bink_names.py index 1a52eeb54f..a78eb28e3a 100644 --- a/tests/test_bink_names.py +++ b/tests/test_bink_names.py @@ -194,6 +194,18 @@ def test_single_pipe_row_and_split_rows_agree(self): class TestCli(unittest.TestCase): + def test_rejects_negative_max_skip(self): + with tempfile.TemporaryDirectory() as tmp: + xml = os.path.join(tmp, "list.xml") + with open(xml, "w", encoding="utf-8") as f: + f.write(mount_xml([])) + err = io.StringIO() + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): + with self.assertRaises(SystemExit) as cm: + names_mod.main([tmp, "--mount", xml, "--max-skip", "-1"]) + self.assertEqual(cm.exception.code, 2) + self.assertIn("--max-skip must be 0 or more", err.getvalue()) + def test_archive_end_to_end(self): shapes = [(1280, 720, 40), (1920, 1080, 50), (512, 512, 15)] with tempfile.TemporaryDirectory() as tmp: diff --git a/tools/bink_names.py b/tools/bink_names.py index 13bc9b12a2..58cae0bd35 100644 --- a/tools/bink_names.py +++ b/tools/bink_names.py @@ -318,6 +318,8 @@ def main(argv=None): ap.add_argument("--max-skip", type=int, default=MAX_SKIP, help="most list entries skipped in a row") ap.add_argument("--out", help="names.csv or names.json; default is a summary only") a = ap.parse_args(argv) + if a.max_skip < 0: + ap.error("--max-skip must be 0 or more") inputs = [a.source, *a.mount] + ([a.pins] if a.pins else []) for path in inputs: if not os.path.exists(path): From 499c608c0fc21edb15e196ffe4af2a0db8b7b3a0 Mon Sep 17 00:00:00 2001 From: SWAYAM Date: Sun, 22 Nov 2026 19:55:59 +0530 Subject: [PATCH 048/115] test(d3d12): reset slot 67 PSOs before device refcount check in d3d12_compute_test --- runtime/test/d3d12_compute_test.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp index c7bd6bab1c..3b87b208f8 100644 --- a/runtime/test/d3d12_compute_test.cpp +++ b/runtime/test/d3d12_compute_test.cpp @@ -381,6 +381,8 @@ int main() { std::memcpy(second.data(), static_cast(results) + bytes, bytes); for (auto* r : {&out_a, &out_b, &constants, &readback}) r->reset(); + pso67.reset(); + unknown67.reset(); pso.reset(); root.reset(); heap.reset(); From d38daa4e9bf1a9abe7aa81028e75cf4b0e1388e4 Mon Sep 17 00:00:00 2001 From: Alex Arenas <106154424+al3xar@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:26:27 +0100 Subject: [PATCH 049/115] runtime: implement ID3D12Device1::CreatePipelineLibrary and ID3D12PipelineLibrary1 --- runtime/CMakeLists.txt | 12 +- runtime/shims/d3d12_vulkan_device.cpp | 106 +++++++ runtime/test/d3d12_pipeline_library_test.cpp | 316 +++++++++++++++++++ 3 files changed, 433 insertions(+), 1 deletion(-) create mode 100644 runtime/test/d3d12_pipeline_library_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 6f135558a4..ef11fc745c 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -819,7 +819,7 @@ if(TARGET Vulkan::Headers) ${_stubs_header} ID3D12GraphicsCommandList8 ID3D12CommandQueue ID3D12CommandAllocator ID3D12Fence1 ID3D12Device11 ID3D12DescriptorHeap ID3D12Heap ID3D12Resource ID3D12QueryHeap ID3D12RootSignature - ID3D12PipelineState ID3D12CommandSignature + ID3D12PipelineState ID3D12CommandSignature ID3D12PipelineLibrary1 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_d3d12_stubs.py ${LEONIDA_D3D12_HEADER} COMMENT "Generating D3D12 COM stubs" VERBATIM) @@ -1332,6 +1332,16 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_set0_compute_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_set0_compute COMMAND d3d12_set0_compute_test) set_tests_properties(d3d12_set0_compute PROPERTIES SKIP_RETURN_CODE 77) + add_executable(d3d12_pipeline_library_test test/d3d12_pipeline_library_test.cpp + ${LEONIDA_TEST_CS} ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS}) + target_link_libraries(d3d12_pipeline_library_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_pipeline_library_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}" + LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" + LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}") + target_compile_options(d3d12_pipeline_library_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_pipeline_library COMMAND d3d12_pipeline_library_test) + set_tests_properties(d3d12_pipeline_library PROPERTIES SKIP_RETURN_CODE 77) else() message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test and d3d12_set0_compute_test are not built") endif() diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 8d0cd21e47..fd43cda8f4 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -2597,6 +2597,99 @@ struct TextureView { float min_lod = 0.0f; }; +// In-memory pipeline library (docs/d3d12_vulkan.md sections 3.6 and 4). D3D12 cached blobs are driver-specific +// and ignored across runs; Serialize writes a versioned header so CreatePipelineLibrary recognizes our own blobs +// and returns D3D12_ERROR_DRIVER_VERSION_MISMATCH for foreign or corrupt ones. +class PipelineLibrary final + : public Child { +public: + // {6e2a9d41-7b5f-4c83-8e14-2a9d6f3c5b10} + static constexpr GUID kTag{0x6e2a9d41, 0x7b5f, 0x4c83, {0x8e, 0x14, 0x2a, 0x9d, 0x6f, 0x3c, 0x5b, 0x10}}; + + struct Header { + std::uint32_t magic; + std::uint32_t version; + std::uint32_t count; + std::uint32_t reserved; + }; + static constexpr std::uint32_t kMagic = 0x314C504Cu; // "LPL1" + static constexpr std::uint32_t kVersion = 1; + + ~PipelineLibrary() override { + std::lock_guard lock(mutex_); + for (auto& [name, pso] : entries_) + if (pso) pso->Release(); + entries_.clear(); + } + + static bool valid_blob(const void* data, SIZE_T size) { + if (!data || size < sizeof(Header)) return false; + Header h{}; + std::memcpy(&h, data, sizeof(h)); + return h.magic == kMagic && h.version == kVersion && h.reserved == 0; + } + + HRESULT STDMETHODCALLTYPE StorePipeline(LPCWSTR name, ID3D12PipelineState* pipeline) override { + if (!name || !*name || !pipeline) return E_INVALIDARG; + if (!PipelineState::from(pipeline)) return E_INVALIDARG; + std::lock_guard lock(mutex_); + auto [it, inserted] = entries_.emplace(name, pipeline); + if (!inserted) return E_INVALIDARG; + pipeline->AddRef(); + return S_OK; + } + + HRESULT STDMETHODCALLTYPE LoadGraphicsPipeline(LPCWSTR name, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc, + REFIID riid, void** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (!name || !*name || !desc) return E_INVALIDARG; + return load_entry(name, false, true, riid, out); + } + + HRESULT STDMETHODCALLTYPE LoadComputePipeline(LPCWSTR name, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, + REFIID riid, void** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (!name || !*name || !desc) return E_INVALIDARG; + return load_entry(name, true, false, riid, out); + } + + HRESULT STDMETHODCALLTYPE LoadPipeline(LPCWSTR name, const D3D12_PIPELINE_STATE_STREAM_DESC* desc, + REFIID riid, void** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (!name || !*name || !desc || !desc->SizeInBytes || !desc->pPipelineStateSubobjectStream) return E_INVALIDARG; + return load_entry(name, false, false, riid, out); + } + + SIZE_T STDMETHODCALLTYPE GetSerializedSize() override { return sizeof(Header); } + + HRESULT STDMETHODCALLTYPE Serialize(void* data, SIZE_T size) override { + if (!data || size < sizeof(Header)) return E_INVALIDARG; + std::lock_guard lock(mutex_); + const Header h{kMagic, kVersion, static_cast(entries_.size()), 0}; + std::memcpy(data, &h, sizeof(h)); + return S_OK; + } + +private: + HRESULT load_entry(LPCWSTR name, bool require_compute, bool require_graphics, REFIID riid, void** out) { + std::lock_guard lock(mutex_); + const auto it = entries_.find(name); + if (it == entries_.end()) return E_INVALIDARG; + PipelineState* ps = PipelineState::from(it->second); + if (!ps) return E_INVALIDARG; + if (require_compute && !ps->compute()) return E_INVALIDARG; + if (require_graphics && !ps->graphics()) return E_INVALIDARG; + return it->second->QueryInterface(riid, out); + } + + std::mutex mutex_; + std::unordered_map entries_; +}; + // The T# of a view: what the shader gets to know about it, in the structure the console's shaders read. // False (with a log) for a view set 0 cannot show yet. bool image_descriptor(const Resource& resource, const TextureView& view, leonida::gfx10::Image& out) { @@ -3686,6 +3779,19 @@ class Device final return hand_out(pipeline, riid, out); } + // Device1: in-memory pipeline library (docs/d3d12_vulkan.md sections 3.6 and 4). + HRESULT STDMETHODCALLTYPE CreatePipelineLibrary(const void* blob, SIZE_T size, REFIID riid, void** out) override { + constexpr auto method = "ID3D12Device1::CreatePipelineLibrary"; + if (out) *out = nullptr; + if (size > 0 && !blob) return d3d12_trace::result(method, E_INVALIDARG); + if (size > 0 && !PipelineLibrary::valid_blob(blob, size)) + return d3d12_trace::result(method, D3D12_ERROR_DRIVER_VERSION_MISMATCH); + if (!out) return d3d12_trace::result(method, S_FALSE); + auto* lib = new PipelineLibrary(); + lib->attach_device(identity()); + return d3d12_trace::result(method, hand_out(lib, riid, out)); + } + UINT STDMETHODCALLTYPE GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE) override { return kDescriptorSize; } diff --git a/runtime/test/d3d12_pipeline_library_test.cpp b/runtime/test/d3d12_pipeline_library_test.cpp new file mode 100644 index 0000000000..cd7b411e59 --- /dev/null +++ b/runtime/test/d3d12_pipeline_library_test.cpp @@ -0,0 +1,316 @@ +// Synthetic GPU test for ID3D12Device1::CreatePipelineLibrary and ID3D12PipelineLibrary / ID3D12PipelineLibrary1: +// - empty library creation (0-byte blob), null-output capability check (S_FALSE), and invalid/foreign/corrupt +// blob rejection (E_INVALIDARG for null pointer with non-zero size, D3D12_ERROR_DRIVER_VERSION_MISMATCH for +// unrecognized or corrupt headers); +// - StorePipeline (unique names, duplicate rejection, null/empty name rejection, null/foreign PSO rejection); +// - LoadComputePipeline, LoadGraphicsPipeline, and ID3D12PipelineLibrary1::LoadPipeline (including cross-type +// mismatch rejection when a compute PSO is requested through LoadGraphicsPipeline or vice versa); +// - GetSerializedSize + Serialize round-trip into a second CreatePipelineLibrary; +// - GPU execution of both loaded compute and loaded graphics PSOs under LEONIDA_VK_VALIDATION=1. +// No game data. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include + +#if !defined(LEONIDA_TEST_CS_SPV) || !defined(LEONIDA_TEST_VS_SPV) || !defined(LEONIDA_TEST_PS_SPV) +#error "LEONIDA_TEST_CS_SPV, LEONIDA_TEST_VS_SPV and LEONIDA_TEST_PS_SPV must be defined" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; + +namespace { + +struct Vertex { + float x, y; + std::uint8_t r, g, b, a; +}; + +D3D12_RESOURCE_DESC tex2d_desc(UINT w, UINT h, DXGI_FORMAT fmt, D3D12_RESOURCE_FLAGS flags) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + d.Width = w; + d.Height = h; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.Format = fmt; + d.SampleDesc = {1, 0}; + d.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + d.Flags = flags; + return d; +} + +} // namespace + +int main() { + vktest::Device d; + const auto status = d.initialize(); + if (status == vktest::DeviceStatus::unavailable) { + std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); + return 77; + } + EXPECT(status == vktest::DeviceStatus::ready); + + const auto cs_prog = fssm_program({0x43532001, 0xbf810000}); + const auto vs_prog = fssm_program({0x56532001, 0xbf810000}); + const auto ps_prog = fssm_program({0x50532001, 0xbf810000}); + const auto cs_dxbc = shader_container(cs_prog); + const auto vs_dxbc = shader_container(vs_prog); + const auto ps_dxbc = shader_container(ps_prog); + + const auto lib_dir = std::filesystem::temp_directory_path() / "leonida_pipeline_library_test"; + std::filesystem::create_directories(lib_dir); + std::filesystem::copy_file(LEONIDA_TEST_CS_SPV, lib_dir / "cs.spv", + std::filesystem::copy_options::overwrite_existing); + std::filesystem::copy_file(LEONIDA_TEST_VS_SPV, lib_dir / "vs.spv", + std::filesystem::copy_options::overwrite_existing); + std::filesystem::copy_file(LEONIDA_TEST_PS_SPV, lib_dir / "ps.spv", + std::filesystem::copy_options::overwrite_existing); + { + std::ofstream idx(lib_dir / "index.json", std::ios::binary); + idx << "{\"cs\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(cs_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144},\n" + " \"vs\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": [" + "{\"semantic\": \"COLOR\", \"semantic_index\": 0, \"register\": 0, \"mask\": 15, \"rw_mask\": 15, " + "\"system_value\": 0, \"component_type\": \"float\"}, " + "{\"semantic\": \"POSITION\", \"semantic_index\": 0, \"register\": 1, \"mask\": 3, \"rw_mask\": 3, " + "\"system_value\": 0, \"component_type\": \"float\"}]},\n" + " \"ps\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0]}}"; + } + + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.shader_dir = lib_dir.string(); + + Ref device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); + + // 1. CreatePipelineLibrary creation, capability check (null output -> S_FALSE), and invalid/corrupt blobs. + { + EXPECT(device->CreatePipelineLibrary(nullptr, 0, __uuidof(ID3D12PipelineLibrary), nullptr) == S_FALSE); + Ref bad; + EXPECT(device->CreatePipelineLibrary(nullptr, 16, IID_PPV_ARGS(&bad.p)) == E_INVALIDARG && !bad.p); + const std::uint32_t foreign[4] = {0xDEADBEEFu, 1u, 0u, 0u}; + EXPECT(device->CreatePipelineLibrary(foreign, sizeof(foreign), IID_PPV_ARGS(&bad.p)) == + D3D12_ERROR_DRIVER_VERSION_MISMATCH && + !bad.p); + const std::uint8_t tiny[4] = {1, 2, 3, 4}; + EXPECT(device->CreatePipelineLibrary(tiny, sizeof(tiny), IID_PPV_ARGS(&bad.p)) == + D3D12_ERROR_DRIVER_VERSION_MISMATCH && + !bad.p); + } + + // 2. Build one compute PSO and one graphics PSO. + D3D12_DESCRIPTOR_RANGE uav_range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 1, 0, 0}; + D3D12_ROOT_PARAMETER cs_params[3]{}; + cs_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + cs_params[0].Constants = {0, 0, 1}; + cs_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + cs_params[1].Descriptor = {0, 0}; + cs_params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + cs_params[2].DescriptorTable = {1, &uav_range}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC cs_rs_desc{}; + cs_rs_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + cs_rs_desc.Desc_1_0 = {3, cs_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto cs_rs_blob = serialize_root_signature(cs_rs_desc); + Ref cs_rs; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, cs_rs_blob.data(), cs_rs_blob.size(), IID_PPV_ARGS(&cs_rs.p)))); + + D3D12_COMPUTE_PIPELINE_STATE_DESC cs_desc{}; + cs_desc.pRootSignature = cs_rs.p; + cs_desc.CS = {cs_dxbc.data(), cs_dxbc.size()}; + Ref cs_pso; + EXPECT(SUCCEEDED(device->CreateComputePipelineState(&cs_desc, IID_PPV_ARGS(&cs_pso.p)))); + + D3D12_ROOT_PARAMETER gfx_params[2]{}; + gfx_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + gfx_params[0].Constants = {0, 0, 2}; + gfx_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + gfx_params[1].Descriptor = {1, 0}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC gfx_rs_desc{}; + gfx_rs_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + gfx_rs_desc.Desc_1_0 = {2, gfx_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT}; + const auto gfx_rs_blob = serialize_root_signature(gfx_rs_desc); + Ref gfx_rs; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, gfx_rs_blob.data(), gfx_rs_blob.size(), IID_PPV_ARGS(&gfx_rs.p)))); + + const D3D12_INPUT_ELEMENT_DESC input_elems[2] = { + {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT, + D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + }; + D3D12_GRAPHICS_PIPELINE_STATE_DESC gfx_desc{}; + gfx_desc.pRootSignature = gfx_rs.p; + gfx_desc.VS = {vs_dxbc.data(), vs_dxbc.size()}; + gfx_desc.PS = {ps_dxbc.data(), ps_dxbc.size()}; + gfx_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + gfx_desc.SampleMask = 0xFFFFFFFFu; + gfx_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + gfx_desc.RasterizerState.CullMode = D3D12_CULL_MODE_BACK; + gfx_desc.RasterizerState.DepthClipEnable = TRUE; + gfx_desc.InputLayout = {input_elems, 2}; + gfx_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + gfx_desc.NumRenderTargets = 1; + gfx_desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + gfx_desc.SampleDesc = {1, 0}; + Ref gfx_pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&gfx_desc, IID_PPV_ARGS(&gfx_pso.p)))); + + // 3. Store, load, cross-type rejection, and serialize round-trip. + Ref lib; + EXPECT(SUCCEEDED(device->CreatePipelineLibrary(nullptr, 0, IID_PPV_ARGS(&lib.p))) && lib.p); + Ref parent_dev; + EXPECT(SUCCEEDED(lib->GetDevice(IID_PPV_ARGS(&parent_dev.p))) && parent_dev.p); + + EXPECT(lib->StorePipeline(nullptr, cs_pso.p) == E_INVALIDARG); + EXPECT(lib->StorePipeline(L"", cs_pso.p) == E_INVALIDARG); + EXPECT(lib->StorePipeline(L"cs", nullptr) == E_INVALIDARG); + EXPECT(SUCCEEDED(lib->StorePipeline(L"cs", cs_pso.p))); + EXPECT(lib->StorePipeline(L"cs", cs_pso.p) == E_INVALIDARG); // duplicate name + EXPECT(SUCCEEDED(lib->StorePipeline(L"gfx", gfx_pso.p))); + + Ref loaded_cs, loaded_gfx, loaded_any, wrong; + EXPECT(lib->LoadComputePipeline(L"missing", &cs_desc, IID_PPV_ARGS(&wrong.p)) == E_INVALIDARG && !wrong.p); + EXPECT(lib->LoadComputePipeline(L"gfx", &cs_desc, IID_PPV_ARGS(&wrong.p)) == E_INVALIDARG && !wrong.p); + EXPECT(lib->LoadGraphicsPipeline(L"cs", &gfx_desc, IID_PPV_ARGS(&wrong.p)) == E_INVALIDARG && !wrong.p); + EXPECT(SUCCEEDED(lib->LoadComputePipeline(L"cs", &cs_desc, IID_PPV_ARGS(&loaded_cs.p))) && loaded_cs.p); + EXPECT(SUCCEEDED(lib->LoadGraphicsPipeline(L"gfx", &gfx_desc, IID_PPV_ARGS(&loaded_gfx.p))) && loaded_gfx.p); + + std::uint32_t dummy_stream = 0; + D3D12_PIPELINE_STATE_STREAM_DESC stream_desc{sizeof(dummy_stream), &dummy_stream}; + D3D12_PIPELINE_STATE_STREAM_DESC empty_stream{0, nullptr}; + EXPECT(lib->LoadPipeline(L"gfx", &empty_stream, IID_PPV_ARGS(&wrong.p)) == E_INVALIDARG && !wrong.p); + EXPECT(SUCCEEDED(lib->LoadPipeline(L"gfx", &stream_desc, IID_PPV_ARGS(&loaded_any.p))) && loaded_any.p); + + const SIZE_T blob_size = lib->GetSerializedSize(); + EXPECT(blob_size >= 16); + std::vector blob(blob_size); + EXPECT(lib->Serialize(nullptr, blob_size) == E_INVALIDARG); + EXPECT(lib->Serialize(blob.data(), blob_size - 1) == E_INVALIDARG); + EXPECT(SUCCEEDED(lib->Serialize(blob.data(), blob_size))); + + Ref reloaded; + EXPECT(SUCCEEDED(device->CreatePipelineLibrary(blob.data(), blob.size(), IID_PPV_ARGS(&reloaded.p))) && reloaded.p); + + // 4. Execute the loaded compute PSO and loaded graphics PSO on the GPU. + Ref queue; + const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p)))); + Ref alloc; + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p)))); + Ref list; + EXPECT(SUCCEEDED( + device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, nullptr, IID_PPV_ARGS(&list.p)))); + Ref fence; + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + constexpr UINT W = 16, H = 16; + const D3D12_HEAP_PROPERTIES hp_def{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES hp_up{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES hp_rb{D3D12_HEAP_TYPE_READBACK}; + const auto rtd = tex2d_desc(W, H, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + const Vertex verts[4] = { + {-1.0f, 1.0f, 255, 0, 0, 255}, + { 0.0f, 1.0f, 255, 0, 0, 255}, + { 0.0f, 0.0f, 255, 0, 0, 255}, + {-1.0f, 0.0f, 255, 0, 0, 255}, + }; + const std::uint16_t indices[6] = {0, 1, 2, 0, 2, 3}; + const float tint[4] = {1.0f, 0.0f, 1.0f, 1.0f}; + const auto vbd = buffer_desc(sizeof(verts)); + const auto ibd = buffer_desc(sizeof(indices)); + const auto cbd = buffer_desc(256); + Ref rt, vb, ib, cb, rb; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_def, D3D12_HEAP_FLAG_NONE, &rtd, + D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, IID_PPV_ARGS(&rt.p)))); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_up, D3D12_HEAP_FLAG_NONE, &vbd, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&vb.p)))); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_up, D3D12_HEAP_FLAG_NONE, &ibd, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&ib.p)))); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_up, D3D12_HEAP_FLAG_NONE, &cbd, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&cb.p)))); + void* p = nullptr; + EXPECT(SUCCEEDED(vb->Map(0, nullptr, &p))); + std::memcpy(p, verts, sizeof(verts)); + vb->Unmap(0, nullptr); + EXPECT(SUCCEEDED(ib->Map(0, nullptr, &p))); + std::memcpy(p, indices, sizeof(indices)); + ib->Unmap(0, nullptr); + EXPECT(SUCCEEDED(cb->Map(0, nullptr, &p))); + std::memcpy(p, tint, sizeof(tint)); + cb->Unmap(0, nullptr); + + D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{}; + UINT64 total_bytes = 0; + device->GetCopyableFootprints(&rtd, 0, 1, 0, &fp, nullptr, nullptr, &total_bytes); + const auto rbd = buffer_desc(total_bytes); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_rb, D3D12_HEAP_FLAG_NONE, &rbd, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&rb.p)))); + + Ref rtv_heap; + const D3D12_DESCRIPTOR_HEAP_DESC rhd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&rhd, IID_PPV_ARGS(&rtv_heap.p)))); + const auto rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(rt.p, nullptr, rtv); + + const float blue[4] = {0.0f, 0.0f, 1.0f, 1.0f}; + list->ClearRenderTargetView(rtv, blue, 0, nullptr); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + const D3D12_VIEWPORT vp{0, 0, float(W), float(H), 0.0f, 1.0f}; + const D3D12_RECT sc{0, 0, LONG(W), LONG(H)}; + list->RSSetViewports(1, &vp); + list->RSSetScissorRects(1, &sc); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + const D3D12_VERTEX_BUFFER_VIEW vbv{vb->GetGPUVirtualAddress(), sizeof(verts), sizeof(Vertex)}; + const D3D12_INDEX_BUFFER_VIEW ibv{ib->GetGPUVirtualAddress(), sizeof(indices), DXGI_FORMAT_R16_UINT}; + list->IASetVertexBuffers(0, 1, &vbv); + list->IASetIndexBuffer(&ibv); + list->SetGraphicsRootSignature(gfx_rs.p); + const float offset[2] = {0.0f, 0.0f}; + list->SetGraphicsRoot32BitConstants(0, 2, offset, 0); + list->SetGraphicsRootConstantBufferView(1, cb->GetGPUVirtualAddress()); + list->SetPipelineState(loaded_gfx.p); + list->DrawIndexedInstanced(6, 1, 0, 0, 0); + + const auto to_src = transition(rt.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_src); + D3D12_TEXTURE_COPY_LOCATION src_loc{rt.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + D3D12_TEXTURE_COPY_LOCATION dst_loc{rb.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + dst_loc.PlacedFootprint = fp; + list->CopyTextureRegion(&dst_loc, 0, 0, 0, &src_loc, nullptr); + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)) && SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); + + EXPECT(SUCCEEDED(rb->Map(0, nullptr, &p))); + const auto* bytes = static_cast(p); + std::uint32_t tl = 0, br = 0; + std::memcpy(&tl, bytes + 2 * fp.Footprint.RowPitch + 2 * 4, 4); + std::memcpy(&br, bytes + 12 * fp.Footprint.RowPitch + 12 * 4, 4); + EXPECT(tl == 0xFF0000FFu); // red quad drawn by PSO loaded from PipelineLibrary + EXPECT(br == 0xFFFF0000u); // blue background clear + rb->Unmap(0, nullptr); + + EXPECT(d.validation_errors() == 0); + std::printf("d3d12_pipeline_library_test: ok\n"); + return 0; +} From 6e8c4b03c1ae060051bc4b56e6351fcab0b2cb7e Mon Sep 17 00:00:00 2001 From: dcastell1 Date: Sun, 22 Nov 2026 15:26:38 +0100 Subject: [PATCH 050/115] docs/design: v_fma_mix* rounding is measured, and nearest-even is the one still off PROC-96: the Known approximations row still listed mix ops with the packs that round to nearest because the mode says so. SHADER-135 (#1722) measured v_fma_mixlo/mixhi_f16 on gfx1036: they round the exact x*y+z once in every mode, 7 of 7 discriminating tie inputs. The toward-zero path already does that; the nearest-even path narrows an f32 Fma, which is 1 f16 ulp off on ties until #1774 (SHADER-296) lands, so the row now says which of the two is the approximation instead of implying both are correct by construction. The f16 inline constants row needed no change: #1722 already replaced its "Not measured" note with the measured per-operand rule. --- docs/design.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design.md b/docs/design.md index 9e38cc015f..cd1c166e8e 100644 --- a/docs/design.md +++ b/docs/design.md @@ -365,7 +365,7 @@ How the generated SPIR-V expects the runtime to work: | 16-bit interpolation without `PerVertexKHR` (`--f16-interp-fallback`) | MoltenVK reports `fragmentShaderBarycentric` but can't create a pipeline with the row above's inputs: its SPIR-V to MSL conversion stops with "PerVertexKHR decoration is not supported in MSL" (MoltenVK 1.4.2 on an Apple A18 Pro and, reported by @DomasUrbonas in #166, an M4 Pro), so `ps_interp_f16_high` failed on every Mac. With the flag no `PerVertexKHR` (and, for these reads, no `BaryCoordKHR`) is used: every VS `exp paramN`, mesh param and `--mesh-compute` vertex (`tools/mesh_compute_vs.py`) also exports the channel's two f16 halves decoded to f32 (`UnpackHalf2x16`), low halves at location 29 − 2N and high halves at 30 − 2N, below MoltenVK's 31 locations (124 components); a PS `*_f16` read of attrN.c takes component c of that ordinary smooth input, then p2 clamps and narrows as before. Interpolation is linear, so the device interpolating the decoded halves gives the same P0 + i(P1 − P0) + j(P2 − P0) as the per-vertex path, with the interpolator's rounding instead of explicit f32 arithmetic. f32 and `v_interp_mov_f32` reads of such a location are the raw word as on any location (flat = the provoking vertex's word, exact). A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(29 − P) / 2), and a PS whose decoded-half location is also an attribute it reads is rejected (`Unsupported`), not mislinked. The index records `f16_halves` ({param: [low, high location]}) on both sides; a pipeline links when the PS's entries are among its producer's. Chosen like the wave64 mode: `tools/vk_subgroup_info.py` reports `per_vertex_inputs` (false without `fragmentShaderBarycentric` or on driver ID MoltenVK), and `make_game.py` and `run_gpu_tests.py` turn the flag on where it is false (`LEONIDA_F16_INTERP_FALLBACK=1`/`0` overrides the runner; `build.py` takes only the variable, since it may run in WSL). Without the flag the translation is unchanged: all 139 GPU-test modules are byte-identical to main's, with and without `--bary-fallback` and with `--mesh-compute --wave64-emulate`, so NVIDIA and AMD keep the exact per-vertex path. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_interp_f16_high` drawn with `vs_f16_pack` passes natively and with wave64 emulation, every one of its 4,096 pixels bit-exact to f16 of the exact u and v in both halves (it failed before at pipeline creation), and `ms_f16_pack` through `--mesh-compute` (`LEONIDA_MESH_COMPUTE=1`) passes too; `tests/semantic/test_f16_interp_fallback.py` checks the PS reads (1.75 and 9.0 from the decoded halves), the VS exports (one-lane interpreter), the overlap rules and the default being unchanged. **Unverified:** a PS whose producer exports more params than leave room for the halves it reads (it reads that producer's param, not halves: the `f16_halves` entries then don't match); devices with fewer than 31 output locations. Not combined with `--bary-fallback`'s geometry shader. | | `v_fmac_f16`, `v_interp_p2/mov_f32` output modifiers | VOP3 `mul:2`/`mul:4`/`div:2` (applied first) and `clamp` to [0, 1] apply to `v_fmac_f16_e64` (before narrowing to f16, matching `v_fma_f16`, high half preserved) and to `v_interp_p2_f32_e64` / `v_interp_mov_f32_e64` (no-op when no modifier is present). Until 2026-11-22 all three dropped output modifiers. Source: LLVM `llvm/test/MC/AMDGPU/gfx10_asm_vop2.s` (`v_fmac_f16_e64`) and `gfx10_asm_vop3.s` (`v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`). Checked on the CPU by `tests/semantic/test_f16_fma_rounding.py` (`test_fmac_output_modifiers`) and `tests/semantic/test_interp_f32_mods.py`, and on a GPU by `ps_fmac_f16_mods.asm`, `ps_interp_f32_mods.asm` and `ps_interp_mov_mods.asm` (the last two drawn with `vs_interp_consts.asm`, whose params are constant over the triangle; each modifier and the omod-before-clamp order change a word; Tesla V100 (NVIDIA 580.95.05, Linux)). **The hardware ignores the f16 omod in the MODE the translator assumes:** on an RDNA2 iGPU (gfx1036) `mul:2`/`mul:4`/`div:2` change an f16 result (`v_fmac_f16`, `v_add/mul/fma_f16`, `v_cvt_f16_f32`, `v_exp/rcp_f16`) only with IEEE 0 and `denorm_mode_16_64 = 0`, and do nothing with f16 denormals kept; omod comes before clamp, and clamp gives +0 for -0 and, with DX10_CLAMP 1, for a NaN (SHADER-135, docs/shader_validation.md). The translator is not changed yet: which of omod and the kept f16 denormals is wrong for the game is a corpus question. | | 16-bit vector compare `op_sel` (`v_cmp(x)_*_{f16,u16,i16}`) | VOP3 `op_sel:[s0,s1]` selects bit `[15:0]` (`0`) or `[31:16]` (`1`) of each source before f16 input modifiers (`neg`/`abs`, via `Gen.f16_in`) or `u16`/`i16` zero-/sign-extension (`OpBitFieldUExtract`/`OpBitFieldSExtract` at bit offset 16 when set, 0 otherwise); VOPC writes a scalar lane mask (VCC/SGPR or EXEC for `v_cmpx`), so there is no destination `op_sel` bit. Until 2026-11-22 `Gen.compare` hardcoded the low half and ignored `mods`. Source: AMD RDNA2 ISA VOP3 `op_sel` and Mesa ACO `can_use_opsel`. Checked on the CPU by `tests/semantic/test_vcmp16_opsel.py` (all four `op_sel` combinations across `f16` relations/ordered/unordered/NaN/`neg`/`abs`, `u16`, signed `i16`, and `v_cmpx` wave32/wave64 EXEC updates via `spirv_mini_interp` and `spirv_wave_interp`); **not GPU-verified**. | -| Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode; the ALU ones follow a MODE toward-zero write (below; ALU sites: see the f16 rounding row). MODE: `s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2)` (f16/f64 rounding) is tracked in a per-invocation variable, the only MODE field the corpus writes (9,417 writes in 6,333 shaders: 6,694 toward zero, 2,723 back to nearest even). While it is toward zero, every VALU f16 result except the transcendentals listed below (`v_cvt_f16_f32`, f16 arithmetic, `v_pk_*_f16`, `v_fma_mix{lo,hi}_f16`, `v_interp_p2_f16`) rounds toward zero exactly, with the integer conversion `v_cvt_pkrtz_f16_f32` uses (`f16_bits(rtz=True)`, see the f16 rounding row), and `v_add_f64` steps back one ulp when the TwoSum error shows it rounded away from zero; finite overflow gives the largest finite value. The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product (|x*y| < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). | +| Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results) round to nearest, which matches the default mode. `v_fma_mixlo/mixhi_f16` round the exact `x*y+z` once in every mode (measured on an RDNA2 iGPU, gfx1036, 7 of 7 discriminating tie inputs, SHADER-135); toward zero the translator does that already, while in nearest-even mode it still narrows an f32 `Fma`, which is 1 f16 ulp off on ties until #1774 (SHADER-296) lands; the ALU ones follow a MODE toward-zero write (below; ALU sites: see the f16 rounding row). MODE: `s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2)` (f16/f64 rounding) is tracked in a per-invocation variable, the only MODE field the corpus writes (9,417 writes in 6,333 shaders: 6,694 toward zero, 2,723 back to nearest even). While it is toward zero, every VALU f16 result except the transcendentals listed below (`v_cvt_f16_f32`, f16 arithmetic, `v_pk_*_f16`, `v_fma_mix{lo,hi}_f16`, `v_interp_p2_f16`) rounds toward zero exactly, with the integer conversion `v_cvt_pkrtz_f16_f32` uses (`f16_bits(rtz=True)`, see the f16 rounding row), and `v_add_f64` steps back one ulp when the TwoSum error shows it rounded away from zero; finite overflow gives the largest finite value. The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product (|x*y| < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). | | Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` (SHADER-118) | The three have no f32 denormal support: a subnormal operand, the rounded product or the result reads as signed zero, whatever the MODE register says. `Gen.flush_f32` emits `|x| < FLT_MIN → copysign(0, x)` on the three operands, after the product rounding and after `omod`/`clamp`; inf and NaN compare false and pass through, and 0 keeps its sign. Source: LLVM AMDGPU `SIISelLowering.cpp`, `SITargetLowering::isFMADLegal` (llvm-project `1922c0c`), which forms `v_mad_f32`/`v_mac_f32` only when f32 denormals are flushed. Corpus count with `tools/shader_profile.py` over the 26,503 gfx1013 shaders: `v_mad_f32` in 7,298 shaders (139,287 occurrences), `v_mac_f32` in 5,889 (276,806: 265,901 `_e32`, 10,811 `_e64`, 94 `_dpp`), `v_mad_legacy_f32` in 6,059 (24,765); 9,297 shaders (35.1%) use at least one, 440,858 occurrences (0.99% of the corpus's 44,406,870 instructions). Checked on the CPU by `tests/semantic/test_valu_f32_min3_max3_mad.py` (`DenormalFlushTests`: the flush column, NaN/inf/zero pass-through, and a sabotaged pass-through that fails); **not GPU-verified** — a native measurement still needs an RDNA1/RDNA2 part that has these opcodes. The `omod` order is an assumption: the flush runs after `div:2`/`mul:2`/`mul:4`, so `FLT_MIN div:2` is flushed, as pinned by that test. | | `v_mac_legacy_f32` | The GFX10.1 VOP2 form of `v_mad_legacy_f32` with D as the addend: D = legacy(S0 * S1) + D, where 0 times anything (inf and NaN included) is +0, with the same denormal flush and VOP3 modifiers. D is read before it is written, as for `v_mac_f32` (LLVM `VOP2Instructions.td`: `V_MAC_LEGACY_F32` has `$src2` tied to `$vdst`). Until 2026-11-22 it raised `Unsupported`. CPU-checked by `MacLegacyF32Tests` in `tests/semantic/test_valu_f32_min3_max3_mad.py` (a 15x8x6 grid against the `v_mad_legacy_f32` reference, the zero rule, clamp/neg, D aliased as a source). **Not GPU-verified**: like the other mad opcodes it exists on gfx1010-1013 only, so no RDNA2 desktop part runs it. | | Whole-quad mode (`s_wqm_b64` / `s_wqm_b32`) | A lane mask register holds only this lane's bit, so WQM on one (EXEC, VCC, an SGPR the mask analysis found) ORs the bit of the lane's quad, lanes 4n..4n+3 of the wave: two `OpGroupNonUniformQuadSwap` (horizontal, then vertical; capability `GroupNonUniformQuad`) in the default mode in fragment and compute shaders (quad operations are only guaranteed there; vertex, geometry and mesh shaders shuffle from the quad's four lanes), or the four lanes' values read through `%x_buf` under `--wave64-emulate` (no subgroup operation there). A quad never crosses lane 31/32, so the mask bits are exact per half on a 32-wide subgroup; SCC is a wave vote, so on wave64 it needs a 64-wide subgroup or `--wave64-emulate` (as every wave-wide mask op). The result goes to EXEC, VCC or an SGPR pair as a mask, SCC = the wave-wide any of it (same vote as the other mask ops). A 32-bit form in wave64 (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`, a half-mask SGPR) writes only its own half (`exec_half_write`) and votes SCC over that half only (`cs_wqm_w64_half`). A source that is not a lane mask (a value loaded from memory, a literal) is data: `((x | x>>1 | x>>2 | x>>3) & 0x11111111) * 15` per 32-bit word and SCC = result != 0, no subgroup operation. Assumptions: in compute and mesh shaders the subgroup lane is `LocalInvocationIndex` mod the subgroup size (as for every cross-lane op); a hardware quad is four consecutive lanes of a wave, and in a pixel shader Vulkan's quad (the 2x2 pixels, helper invocations included) is the same four lanes; GPU-checked on both AMD and NVIDIA with `ps_wqm.asm` (every 2x2 block of a 64x64 target, fully covered). Not covered: helper-invocation behaviour at triangle edges is untested, and in native mode an absent invocation in a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value (emulated, the missing lanes of a partial wave read as 0). Before this the instruction was the identity, so helper lanes stayed off (#156 SHADER-34: `s_wqm_b64` appears in 4,285 pixel shaders). GPU-checked with `runtime/test/shaders/cs_wqm_w64.asm`, `cs_wqm_w64_half.asm`, `cs_wqm_w32.asm` and `ps_wqm.asm` on AMD Radeon 880M (subgroup 64) and NVIDIA GeForce RTX 5070 Laptop (subgroup 32; `cs_wqm_w64` there needs `LEONIDA_W64_EMULATE=1`), with and without `--wave64-emulate`. | From b474993bf5690568a74d102baca7343334b55c7d Mon Sep 17 00:00:00 2001 From: Kam471 <115741199+Kam471@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:26:44 +0000 Subject: [PATCH 051/115] docs: drop the duplicated Models rows and the split intro fragment --- docs/README.md | 1 - docs/design.md | 1 - docs/models.md | 11 ++--------- 3 files changed, 2 insertions(+), 11 deletions(-) diff --git a/docs/README.md b/docs/README.md index 3129118160..e9fd8aa957 100644 --- a/docs/README.md +++ b/docs/README.md @@ -18,7 +18,6 @@ method, scope and caveats. No game data is included. | Document | Measured content | |---|---| | [models.md](models.md) | 382,781 models (0 decode failures) at the `e293917` pin, including 159,511 drawable-dictionary children; the other archives measure 4,686 fragments, 30,343 bone-bound and 126,301,454 triangles, while the `levels.rpf` geometry cells are not independently reproduced; the re-count table is in models.md. | -| [models.md](models.md) | 350,251 models at the `917e9b9` pin, including 159,486 drawable-dictionary children; the `e293917` re-count adds 3,203 rows outside `levels.rpf`, almost all recovered fragments; `levels.rpf` recovers 343,327 models (+29,327) but was not fully exported. The per-archive table is in models.md. | | [character_models.md](character_models.md) | `packs.rpf` character parts at `e293917`: 26,585 rows / 11,335 unique names, 2,865 fragments (all a flat 25-vertex / 32-triangle 5x5 bounds grid at z=0), Lucia's 22 named records and the decoded 13-part export, the `player_story000_00` drawable set, slot-name token counts, texture coverage (184/215), and what is not decoded (fragment children, ped variation, hair, bind pose). | | [character_skeleton.md](character_skeleton.md) | Character `.#ft` fragments: the 597-name shared skeleton table (596 `joaat32` hashes), the 597-record instance tree with 580 measured parents, the model-side bone-hash mapping, and the measured vertex joint-index/skin-weight layouts (`tools/skin_streams.py`); the reference TRS is not the bind pose. | | [resource_names.md](resource_names.md) | RPF9 named-resource index: bounded-inflate lookup for `name.#dr`/`#ft`/`#dd` without the TOC. | diff --git a/docs/design.md b/docs/design.md index 6e90ef5469..84628b3dee 100644 --- a/docs/design.md +++ b/docs/design.md @@ -103,7 +103,6 @@ add a source file, add it to `runtime\CMakeLists.txt` and to the file list in `b | Shaders | 26,503 carved from `shaders.rpf`, native RDNA2 code unpacked (`FSSM`), disassembled, and translated to SPIR-V; all validate (see *Translator status*). | `\shaders\` (`.dxbc`, `fssm\`, `disasm\`, `spirv\`) | | Textures | **Solved.** Headers are in CPU segments: GPU pointer at q[k], u16 width/height/depth and DXGI format at q[k+4], mip count at byte 2 of q[k+5]. Data is AMD `SW_4K_S` tiled, largest mip first. The GPU segment is the blob run after the CPU blob. On 200 samples, 173 decode at least 1.5× smoother detiled than untiled (median 2.56×). Exports the top mip, slice 0, as DDS. **22,342 exported (1.23 GiB)**: every header whose GPU data follows its CPU blob. World and model textures are handled by the TXD and TTPF exporters below. GPU offsets must be 256-byte aligned, which drops the false headers in `navmeshes`/`anim`. | `tools\tex_headers.py`, `tools\tex_export.py`, `\textures\` | | Models | **Done: 382,781 models measured at the `e293917` pin** (`levels.rpf` 343,327, `packs` 26,585, `story000` 7,461, `data` 3,175, `shared_minigame000` 1,294, `core_restofworld` 936, `story000_restofworld` 3; 0 decode failures across all 382,781 models; **159,511 drawable-dictionary children**, **223,270 standalone**; the other archives measure **4,686 fragments**, **30,343 bone-bound**, **126,301,454 triangles** and 512 embedded textures, while the `levels.rpf` fragments/bone-bound/triangles/embedded cells are **not independently reproduced** (no `levels.rpf` manifest; the count harness emits no such fields); 72 unrecovered scan candidates vs 1,282 at `917e9b9`). Earlier baselines: 350,251 at `917e9b9` (159,486 dictionary children, 190,765 standalone) and 190,792 at `c3708fb`; the +32,530 gain at `e293917` comes from upstream `v1.2` PRs #8–#12 (optional fragment pointers, texture-dictionary filtering, probe-cap parity, and zero-radius drawables; see [models.md](models.md)). Exported with `tools\rpf9dump` (built on breadbbbb/rpf9-explorer's Core; see below). Resources are found at page offset +16 after 16 zero bytes, followed by a zlib system blob with a drawable/fragment header and then the following zlib blocks as graphics data. Positions are quantized: `bias + scale * ((q >> 8) & 0xFFFFFF)`. Output is OBJ (positions, UVs, indices) plus a manifest with real model names (e.g. `cvar_int_grg2b_toys_1`), bounds, per-mesh shader index and material texture references (parameter hash, name hash, 64-bit asset key). My earlier `0x1380`/`0x1601` descriptor notes stand, but the "data not located" blocker was wrong. Character skeletons are separate: the shared 597-name `.#ft` table and its model-side bone-hash mapping are in [character_skeleton.md](character_skeleton.md). | `\assets\\models\` | -| Models | **Done: 350,251 models measured at the `917e9b9` pin** (the submodule pin is now `e293917`, which also pulls in upstream `v1.2` model-discovery PRs #8-#12 plus BCPack PR #7; the non-`levels.rpf` archives have been re-counted at `e293917`: 39,454 rows, +3,203, almost all recovered fragments; `levels.rpf` has a recovery count of 343,327 models (+29,327) but no full OBJ export). At `917e9b9`: `levels.rpf` 314,000, `story000` 7,460, `packs` 24,034, `data` 2,581, `shared_minigame000` 1,288, `core_restofworld` 885, `story000_restofworld` 3; 0 decode failures in the re-count. The `c3708fb` export was 190,792; the new entries are **159,486 drawable-dictionary children** (levels 130,225, packs 23,720, story 4,156, data 268, shared 317, core 797, story_restofworld 3) plus raw-tail/mixed-block pages. The standalone total is 190,765. Triangle totals were not re-run. Exported with `tools\rpf9dump` (built on breadbbbb/rpf9-explorer's Core; see below). Resources are found at page offset +16 after 16 zero bytes, followed by a zlib system blob with a drawable/fragment header and then the following zlib blocks as graphics data. Positions are quantized: `bias + scale * ((q >> 8) & 0xFFFFFF)`. Output is OBJ (positions, UVs, indices) plus a manifest with real model names (e.g. `cvar_int_grg2b_toys_1`), bounds, per-mesh shader index and material texture references (parameter hash, name hash, 64-bit asset key). My earlier `0x1380`/`0x1601` descriptor notes stand, but the "data not located" blocker was wrong. Character skeletons are separate: the shared 597-name `.#ft` table and its model-side bone-hash mapping are in [character_skeleton.md](character_skeleton.md). | `\assets\\models\` | | Texture dictionaries | Same tool: TXD resources become DDS per texture. | `\assets\\textures\` | | World textures (TTPF) | **Done: 308,895 textures from all 57 pools, 0 failures, 48,220 entries skipped by the original exporter** (33,507 BCPack, 14,030 compact mapping, 678 arrays/volumes, 5 unsupported format, 0 unmapped). The compact-tail tool resolves 14,011 of the 14,030 layouts and reconstructs 305,264 complete chains (206,661 newly complete, 1,100,865 mips, 4.59 GiB), and the multi-slice pass resolves all 697 arrays/cubemaps/volumes ([textures_arrays.md](textures_arrays.md)). BCPack was the hard blocker: `tools/bcpack.py` decodes all six active modes (BC1, BC3, BC4, BC5, BC6H, BC7), and `rpf9dump`'s C# `TtpfReader` (`e293917` pin, `breadbbbb/rpf9-explorer#7`) now decodes compact tails, multi-slice layouts, DXGI 11, and strict BCPack BC1/BC3/BC4/BC5 directly; BC6H/BC7 and provisional-history chunks remain skipped by `rpf9dump` and can be completed by `tools/ttpf_assets.py` ([textures.md](textures.md)). 46 pools are in `data\ttdb\**`, 11 in `pack\\data\ttdb\**` (exported under `ttpf_pack\\`). `data\ttdb\**\*.ttpf` (57 pools, 58 GiB) are loose RDS5 texture pools, **not** inside RPFs. rpf9-explorer's `TtpfReader` reads the catalog and detiles them; checked visually (`ttdb_graphics`: scope reticles, clean lines). Names are generated (`texture_N_`); models reference textures by asset key. Some rows are skipped; the measured breakdown and next steps are in [textures.md](textures.md). | `\assets\ttpf\\` + `manifest.json` | | Animation | Indexed without the TOC: 130,470 zlib streams (4,203,762,662 stored / 11,593,460,132 inflated), 95.4% readable. New RAGE page directories (`0DRP`, version 122), `MoVE` (version 19), 273 `pack:/` name tables (2,298 paths), and a tail `RBF0` rig-set manager (`rage__crRigSetManager`: 1,126 rig sets, 6,677 source→rig entries, 3,669 distinct rigs; 56 empty). Bone data: one standalone 28-name table and 3 motion-matcher streams with embedded bone tables (30-name union, 19 joaat32 hashes present, 4 motionmatcher paths); no rig→skeleton link was found. Clip dictionaries are system-only RAGE resources (page map at the `+0x08` pointer). `tools/anim_clips.py` decodes 191,042 of 191,042 animations in 61,505 of them to per-frame values (channel types 0–5, 7, 8 and the GTA VI type 10) and resolves 111,948 of 159,584 `.motion` children to a clip. For each `.motion` it reads the per-child durations and time curves and, on 10,171 of 17,247, the one-axis parameter node (axis name hash, sorted sample values, range). The 2/3 packed streams are second pages of `0DRP` resources, which are not decoded. No `YCD`/`RSC7` at any stream start. The `rpf9_carve` tail overread is measured in `docs/animation.md`. | `tools\anim_index.py`, `\anim-index\` | diff --git a/docs/models.md b/docs/models.md index 695662749b..873f97d51b 100644 --- a/docs/models.md +++ b/docs/models.md @@ -4,10 +4,6 @@ Measured state of `tools/rpf9dump models` on the Xbox Series 1.0.2.1 package, an upstream `rpf9-explorer` fixes that close it. The fixes are merged upstream and the submodule is pinned at `e293917`, where a full ten-archive re-count recovers **382,781 models** (**0 decode failures**), up from 350,251 at `917e9b9` and 190,792 at `c3708fb`. -upstream `rpf9-explorer` fix that closes it. The fix is merged upstream and the submodule is -pinned at `e293917` (the 350,251-model counts below were measured at `917e9b9`, before -upstream `v1.2` PRs #8-#12 landed; the non-`levels.rpf` archives were then re-counted at -`e293917`). Before the fix, the exporter did not reject any vertex or index layout in the tested archives. It dropped valid models in three validation paths, all in `third_party/rpf9-explorer` at commit @@ -256,11 +252,8 @@ The `packs.rpf` row is the pre-dictionary-root control: at `917e9b9` that archiv 24,034 models (26,585 at `e293917`), and the other archives' new-pin counts are in the table above. The rows here are the `c3708fb` measurements (190,792 models); the `917e9b9` re-count is 350,251, and the `e293917` re-count outside `levels.rpf` is 39,454. Triangle totals have not been re-run at -either new pin. -24,034 models (26,585 at `e293917`), and the other archives' counts are in the tables above. The -rows here are the `c3708fb` measurements (190,792 models); the `917e9b9` re-count is 350,251. -Triangle totals for that pin have not been re-run; the `e293917` `levels.rpf` geometry cells are -not independently reproduced (see the table note above). +either new pin; the `e293917` `levels.rpf` geometry cells are not independently reproduced (see +the table note above). At `c3708fb`, every candidate is recovered, read back and decoded: 0 decode failures, 0 readback failures, no duplicate model names, and 2.22 billion triangles (1.95 billion before). The From 08f18223741a47c4521f64d225a2d6ead3c1de27 Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:26:47 +0100 Subject: [PATCH 052/115] Viewer: show WebGL startup failures in the overlay --- viewer/index.html | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/viewer/index.html b/viewer/index.html index 455bb664fc..8b04c6fe41 100644 --- a/viewer/index.html +++ b/viewer/index.html @@ -148,7 +148,16 @@ } // ---------- scene ---------- -const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance" }); +let renderer; +try { + renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance" }); +} catch (error) { + const start = document.getElementById("start"); + start.setAttribute("role", "alert"); + start.style.cursor = "default"; + start.textContent = "Could not start WebGL. Check that WebGL is enabled, then reload."; + throw error; +} renderer.setPixelRatio(Math.min(devicePixelRatio, 1.5)); renderer.setSize(innerWidth, innerHeight); document.body.prepend(renderer.domElement); From 3b409769ecd0897fe575f334a04d4b27cf62f776 Mon Sep 17 00:00:00 2001 From: Tayar <358041433+lucastayaralvarenga-ui@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:26:49 -0300 Subject: [PATCH 053/115] fspx_unpack: preserve outputs for matching file stems --- tests/test_fspx_unpack.py | 20 ++++++++++++++++++++ tools/fspx_unpack.py | 7 +++++++ 2 files changed, 27 insertions(+) diff --git a/tests/test_fspx_unpack.py b/tests/test_fspx_unpack.py index 3c9c843fc4..46c620abc8 100644 --- a/tests/test_fspx_unpack.py +++ b/tests/test_fspx_unpack.py @@ -200,6 +200,26 @@ def test_dll_like_file(self): with open(os.path.join(out, "lib_01.dxbc"), "rb") as f: self.assertEqual(f.read(), c) + def test_retains_programs_with_matching_input_stems(self): + container = Containers().container() + with tempfile.TemporaryDirectory() as tmp: + a = os.path.join(tmp, "a", "sample.dxbc") + b = os.path.join(tmp, "b", "sample.dll") + for path, data in ((a, container), (b, b"MZ" + bytes(62) + container)): + os.makedirs(os.path.dirname(path)) + with open(path, "wb") as f: + f.write(data) + out = os.path.join(tmp, "out") + code, _, err = self.run_tool(a, b, "--out", out) + self.assertEqual(code, 0, err) + with open(os.path.join(out, "index.json"), encoding="utf-8") as f: + index = json.load(f) + self.assertEqual([entry["file"] for entry in index], ["sample.dxbc", "sample_2.dxbc"]) + for name, offset in (("sample", 0), ("sample_2", 64)): + with open(os.path.join(out, "fspx", name + ".json"), encoding="utf-8") as f: + self.assertEqual(json.load(f)["source"]["offset"], offset) + self.assertTrue(os.path.isfile(os.path.join(out, name + ".dxbc"))) + def test_bare_payload_and_a_file_without_fspx(self): with tempfile.TemporaryDirectory() as t: bare = os.path.join(t, "one.fspx") diff --git a/tools/fspx_unpack.py b/tools/fspx_unpack.py index ea79e8001c..eea80d5692 100644 --- a/tools/fspx_unpack.py +++ b/tools/fspx_unpack.py @@ -178,6 +178,7 @@ def main(argv=None) -> int: disasm = shader_disasm os.makedirs(os.path.join(a.out, "disasm"), exist_ok=True) index, bad = [], 0 + used_names = set() for path in a.files: with open(path, "rb") as f: data = f.read() @@ -197,6 +198,12 @@ def main(argv=None) -> int: print(f"{name}: FSPX status {status}", file=sys.stderr) bad += 1 continue + base_name = name + number = 1 + while name.casefold() in used_names: + number += 1 + name = f"{base_name}_{number}" + used_names.add(name.casefold()) meta, blob = got stage = psv_stage(dxbc_parts(container)) if container else None meta["source"] = {"file": os.path.basename(path), "offset": off} From d9fb51b72acb57f2ddf18229bcd11d1c02b78620 Mon Sep 17 00:00:00 2001 From: Youssef Rahmouni Date: Sun, 22 Nov 2026 15:27:22 +0100 Subject: [PATCH 054/115] rdna2spirv: honor VOP3 clamp on v_add/sub/subrev_co[_ci]_u32 --- docs/design.md | 2 +- tests/semantic/test_alu_add_co_clamp.py | 183 ++++++++++++++++++++++++ tools/rdna2spirv.py | 8 +- 3 files changed, 191 insertions(+), 2 deletions(-) create mode 100644 tests/semantic/test_alu_add_co_clamp.py diff --git a/docs/design.md b/docs/design.md index 9e38cc015f..227c964167 100644 --- a/docs/design.md +++ b/docs/design.md @@ -264,7 +264,7 @@ How the generated SPIR-V expects the runtime to work: | Mesh shaders | NGG wave64 programs → `VK_EXT_mesh_shader` (`MeshEXT`). **PSV0** (DXBC) gives NumThreads (128×1×1 in the corpus), MaxOutputVertices/Primitives (128/128) and the topology (triangles). System inputs, from Mesa's RADV setup for mesh as NGG on GFX10.3: v5 = first launch vertex ID of the lane (the "vertex_id" slot), `linearGroupIndex * NumThreads + LocalInvocationIndex` with the linear index from WorkgroupId/NumWorkgroups; all 9,282/9,282 corpus mesh shaders read `v5` once with `v_readfirstlane_b32 sX, v5` and use `sX` only via `s_lshr_b32 D, sX, 7` to recover the group index (NumThreads is 128 in the corpus), matching TomBox's mesh ABI (`gid.x * numThreads + gi`) on 1D launches. GPU-checked with `runtime/test/shaders/ms_v5_workgroup.asm` (24/24 groups exact on RTX 4060 Ti and RTX 3080, and on an RTX 4050 Laptop and an AMD Radeon 740M (RADV)); still unverified on Xbox hardware: the low 7 bits of `v5` on lanes 1..127 and whether 3D `DispatchMesh` flattens XYZ or uses X only. The merged-wave-info SGPR (s3 in this ABI) = wave ID << 24, from LocalInvocationIndex >> 6; `v_mbcnt` lanes = LocalInvocationIndex & 63; user data in s16.. as usual. 1,473 of 1,500 sampled mesh shaders read exactly v5, and the rest only add loop-carried registers. Exports: on NGG, thread t exports vertex t (`pos0`, `paramN`) and primitive t (`prim`). They're staged per invocation; an all-`off` export is the dummy a wave with no vertices must issue, and writes nothing. `s_sendmsg GS_ALLOC_REQ` (m0 = prims << 12 \| verts, sent by thread 0) stores the counts in a workgroup variable. At shader end, in uniform control flow: workgroup barrier, `OpSetMeshOutputsEXT(min(verts, max), min(prims, max))`, then each thread writes its staged vertex (Position + Location N) and primitive (`PrimitiveTriangleIndicesEXT` = bits [8:0], [18:10], [28:20]; `CullPrimitiveEXT` = bit 31). `pos1..pos3` clip/cull distances are staged per invocation and emitted in a per-vertex `Block` output struct (`Position` + `ClipDistance`/`CullDistance` arrays, `VK_EXT_mesh_shader`) when used, keeping the standalone `%ms_out_pos` layout unchanged for shaders without `pos1+`. The distances are copied to that struct one float at a time, not as a whole array: SPIRV-Cross 1.4.363.0 turns a whole-array store into a mesh output into a C array assignment that Metal rejects (SHADER-155; `ms_clip` then compiles and draws its 2048/4096 pixels in a native Metal mesh draw on an Apple A18 Pro). GPU-checked with `runtime/test/shaders/ms_tri.asm` (`VKH_MESH=1 vk_harness`), built from the game's own idioms (thread ID from s3 and mbcnt across two waves, thread-0 ALLOC_REQ, per-thread exports): 0 error on every pixel. | | Mesh shaders as compute (`--mesh-compute`) | For devices without `VK_EXT_mesh_shader` (NVIDIA Pascal, for one). Each mesh shader becomes a `GLCompute` module with the same workgroup size and code; only the epilogue changes. Instead of `OpSetMeshOutputsEXT` and the mesh outputs, after the same barrier lane 0 writes the vertex and primitive counts, lane i < vertex count writes its vertex and lane i < primitive count its primitive into this workgroup's **slot** of an output buffer: slot = linear workgroup index (x + y·nx + z·nx·ny) × `slot_bytes`, computed in 64 bits. The buffer's device address is in push-constant dwords 36–37, so these modules declare 152 bytes. Slot layout (`rdna2spirv.mesh_compute_layout`, recorded per shader as `mesh_compute` in the index), all 16-byte aligned: a header (vertex count, primitive count), then `max_vertices` vertices, each holding the position, the clip and then cull distances padded to whole vec4s, and one vec4 per param location; then `max_primitives` primitives of three vertex indices plus 1 if culled. The modules need no mesh capability, extension or `shaderClipDistance`. `tools/mesh_compute_vs.py` writes the vertex shader that draws the slots with a non-indexed `vkCmdDraw(groups × max_primitives × 3)`: vertex v is workgroup v / (3·max_primitives), primitive (v / 3) mod max_primitives, corner v mod 3. A primitive past the count, or one culled, gets one position outside the clip volume at all three corners and is clipped. Otherwise the corner's index, clamped to `max_vertices` − 1, selects the vertex, and its position, distances and params go out at the mesh shader's locations, so the pixel shader is unchanged. One draw rasterizes in vertex order, which is workgroup then primitive order, as with mesh workgroups. Corpus: all 9,282 mesh shaders are 128×1×1 with 128/128 outputs, wave64, 0–18 params, clip distances in 1,906, cull distances and per-primitive attributes in none, no task shaders. On a 32-wide device combine it with `--wave64-emulate`. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal: no mesh shaders; driver 560.94, Windows 10) with `LEONIDA_MESH_COMPUTE=1 LEONIDA_W64_EMULATE=1`: `ms_tri`, `ms_w64x_ballot` and `ms_wave_info_s3` 4096/4096 pixels exact, `ms_clip` 2048/4096 covered as expected, `ms_v5_workgroup` 24/24 workgroup coordinates, zero Khronos validation messages. Checked in `tests/test_mesh_compute.py`. The runtime side, turning a `DispatchMesh` into that dispatch, a barrier and the draw, is the follow-up (it needs the graphics pipelines of #291). Unused primitives still run the vertex shader; compaction with an indirect draw would avoid that. | | Geometry shaders | All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. Inputs: vertex i sits at the dword offset in v0 lo / v0 hi / v1 lo; an LDS read at vertex base + 4·(4·reg + comp) is input-signature register reg, component comp (checked: SV_Position xyz in dwords 0–2 and TEXCOORD0.xy in 4–5, as ISG1 declares). Outputs: emitted vertex k is dwords [k·4·nreg, (k+1)·4·nreg) of the lane's GSVS area, dword = 4·reg + comp of the output signature (20 dwords = 5 OSG1 registers; every write matches a declared mask). Translation: synthetic offsets (vertex i at dword 64·i), LDS reads → `gl_in[i]` inputs, LDS writes → staged slots, `MSG_GS EMIT` → copy slot (emit count) to the outputs + `OpEmitVertex`, `CUT` → `OpEndPrimitive`, `GS_DONE` → nothing. The prologue's `s_bfm_b64`/`s_cselect` EXEC setup is fed s3 = 64 << 8. GPU-checked with `runtime/test/shaders/gs_tri.asm` (`VKH_GS=… vk_harness`): 0 error. Without a geometry stage (Apple GPUs: Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` writes the outputs to a record buffer, and a meta buffer holds each primitive's vertex count and strip ends, for an ordinary draw afterwards (SHADER-159). `gs_tri` lowered this way, converted with SPIRV-Cross and run natively on an Apple A18 Pro: 195/195 records exact for 65 random triangles, and the captured fullscreen triangle drawn from the records matches all 4096 gradient pixels. Not done: wiring it into a draw path, and GS that use cross-lane operations or more than one invocation. | -| Integer clamp | The VOP3 `clamp` bit on `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32` saturates the result to [0, 0xFFFFFFFF], and on `v_add_nc_i32`/`v_sub_nc_i32` to [0x80000000, 0x7FFFFFFF]; without it they wrap. GFX9+ semantics: LLVM selects `uaddsat`/`usubsat` and `saddsat`/`ssubsat` to exactly these ops with clamp set. **Until this change clamp was silently ignored on the unsigned ops** (and the signed ones were `Unsupported`). Checked on the CPU by `tests/semantic/test_alu_add_nc_clamp.py`, **not yet GPU-verified**. The 16-bit unsigned add/sub (`v_add_nc_u16`, `v_sub_nc_u16`, and the `v_add_u16`/`v_sub_u16`/`v_subrev_u16` `_e64` names) saturate to [0, 0xFFFF] with `clamp` (llvm-mc 21 gfx1030 encodes the bit on them, and LLVM selects i16 `uaddsat`/`usubsat` to them); **until 2026-11-22 the translator wrapped instead**. `clamp` on any other 16-bit integer op raises `Unsupported`. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), **not GPU-verified**. | +| Integer clamp | The VOP3 `clamp` bit on `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32` saturates the result to [0, 0xFFFFFFFF], and on `v_add_nc_i32`/`v_sub_nc_i32` to [0x80000000, 0x7FFFFFFF]; without it they wrap. GFX9+ semantics: LLVM selects `uaddsat`/`usubsat` and `saddsat`/`ssubsat` to exactly these ops with clamp set. **Until this change clamp was silently ignored on the unsigned ops** (and the signed ones were `Unsupported`). Checked on the CPU by `tests/semantic/test_alu_add_nc_clamp.py`. The carry-out unsigned ops (`v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with VOP3 `clamp` likewise saturate D to `0xFFFFFFFF` on add carry or `0` on sub borrow while still reporting the real carry/borrow bit in `sdst` (**until 2026-11-22 the translator ignored `clamp` on all six**); confirmed natively on RDNA2 (AMD Radeon 680M `gfx1035` wave32 & wave64 via `tools/hw_oracle`, and independently on `gfx1036` in #1746) and CPU-checked by `tests/semantic/test_alu_add_co_clamp.py`. The 16-bit unsigned add/sub (`v_add_nc_u16`, `v_sub_nc_u16`, and the `v_add_u16`/`v_sub_u16`/`v_subrev_u16` `_e64` names) saturate to [0, 0xFFFF] with `clamp` (llvm-mc 21 gfx1030 encodes the bit on them, and LLVM selects i16 `uaddsat`/`usubsat` to them); **until 2026-11-22 the translator wrapped instead**. `clamp` on any other 16-bit integer op raises `Unsupported`. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), **not GPU-verified**. | | Gather sampler LOD | Before choosing the mip for the four fetches in `image_gather4_l(_o)`, clamp the requested LOD to S# word 1's MIN_LOD [11:0] and MAX_LOD [23:12] (unsigned 4.8). `ps_gather_sampler_lod.asm` reads the S# from the heap. On RTX 5080 and Radeon Graphics, a maximum of 0.25 selects the base quadrants and a minimum of 0.75 selects the cyan mip across the 64×64 draw. Without these bounds half of each frame reads the wrong level. Radeon also agreed with native `OpImageGather Lod` (`VK_AMD_texture_gather_bias_lod`) for those bounds. At exactly 0.5, with bounds [0,1], that native draw selected mip 1; the emulation now computes the mip as `Floor(LOD + 0.5)`, ties up, and also selects mip 1 (before SHADER-152 it used `RoundEven`, which selected mip 0). | | `s_absdiff_i32`, `s_mul_hi_i32` | `s_absdiff_i32`: D = \|S0 − S1\| with the 32-bit difference wrapped first (0x7FFFFFFF − 0x80000000 → 1; a difference of −2³¹ stays 0x80000000), SCC = D ≠ 0. `s_mul_hi_i32`: high word of the signed 64-bit product, SCC kept. From the RDNA2 ISA pseudocode; checked on the CPU by `tests/semantic/test_salu_absdiff_mul_hi.py`. **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) as raw wave32 kernels through `tools/hw_oracle`: `s_absdiff_i32(0x7FFFFFFF, 0x80000000)` = 1 and `s_absdiff_i32(0x80000000, 0)` = 0x80000000, both with SCC = 1, and equal operands give 0 with SCC = 0; `s_mul_hi_i32(0x7FFFFFFF, 0x7FFFFFFF)` = 0x3FFFFFFF and `s_mul_hi_i32(-1, 1)` = 0xFFFFFFFF, with SCC left as it was. | | SCC from scalar ALU | `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32` and `s_lshl/lshr_b32` set SCC = result ≠ 0, `s_add/sub_i32` and `s_addk_i32` set it to signed overflow, `s_min_u32`/`s_max_u32` to S0 < S1 / S0 > S1, and `s_min_i32`/`s_max_i32` to the same compared signed: SCC is 1 when S0 is the one chosen, and a tie chooses S1 (RDNA2 ISA, S_MIN_I32: D = S0 < S1 ? S0 : S1, SCC = 1 if S0 is chosen). **Before this fix these ops left SCC unchanged**, so a following `s_cbranch_scc*` read a stale flag, and until 2026-11-21 `s_min_i32`/`s_max_i32` set SCC on a tie. 32-bit scalar shifts now mask the amount to 5 bits. GPU-checked with `runtime/test/shaders/ps_scc.asm` and `ps_scc_minmax.asm` (NVIDIA GeForce RTX 2060 SUPER, Linux, driver 620.70.06: 4096/4096 pixels exact, and all 4096 differ with the old translator). **On lane masks in a wave32 program** (a source is EXEC, VCC or a mask SGPR, or the result goes to EXEC) the 32-bit bitwise ops' result is the whole wave's mask, so SCC is a subgroup vote (`OpGroupNonUniformAny`), as for the `_b64` forms. Until 2026-11-22 each lane took its own bit: `s_and_b32 s0, vcc_lo, exec_lo; s_cbranch_scc0` skipped the block in lanes whose bit was 0, and a loop closed by `s_andn2_b32 exec_lo, ...; s_cbranch_scc1` let each lane leave early. Found and checked by `tools/cf_diff.py` (FUZZ-8, CPU differential against the ISA model); GPU test `runtime/test/shaders/ps_scc_mask32.asm` passes (s5 == 8 on 2,048 pixels, 192 of them with bit 0, and s5 == 7 on 2,048) on an NVIDIA RTX 4050 Laptop (Linux, driver 620.73.04, natively and under `LEONIDA_W64_EMULATE=1`) and an AMD Radeon 740M (RADV, Mesa 26.3.1), and on an RTX 2060 SUPER per #634. A 32-bit op on one half of a wave64 mask still takes the lane's bit (its SCC would be a vote of that half). | diff --git a/tests/semantic/test_alu_add_co_clamp.py b/tests/semantic/test_alu_add_co_clamp.py new file mode 100644 index 0000000000..b39b8b26e8 --- /dev/null +++ b/tests/semantic/test_alu_add_co_clamp.py @@ -0,0 +1,183 @@ +"""Semantic interpreter tests for VOP3 clamp on RDNA2 carry-out u32 add/sub ops. + +Covers all six carry-out forms: v_add_co_u32, v_sub_co_u32, v_subrev_co_u32, v_add_co_ci_u32, v_sub_co_ci_u32, +and v_subrev_co_ci_u32. With VOP3 `clamp`, RDNA2 hardware (measured natively on gfx1035 and gfx1036, wave32 & +wave64) saturates D to 0xFFFFFFFF on add carry or 0 on sub borrow while still writing the real carry/borrow bit +into sdst (0 for inactive EXEC lanes). Without `clamp`, D wraps at 32 bits. No game files. +""" +import os +import random +import struct +import sys +import tempfile +import unittest +import warnings + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") + +sys.dont_write_bytecode = True +sys.path.insert(0, TOOLS_DIR) +sys.path.insert(0, HERE) + +import rdna2spirv # noqa: E402 +import spirv_mini_interp as si # noqa: E402 + +M32 = 0xFFFFFFFF +STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" tuple[int, int]: + x, y = x & M32, y & M32 + if op.startswith("v_subrev_co"): + x, y = y, x + sub = "sub" in op + c = (1 if cin else 0) if op.endswith("ci_u32") else 0 + if sub: + full = x - y - c + carry = 1 if full < 0 else 0 + res = 0 if (clamp and carry) else (full & M32) + else: + full = x + y + c + carry = 1 if full > M32 else 0 + res = M32 if (clamp and carry) else (full & M32) + return res, carry + + +def run_case(op: str, x: int, y: int, cin: int, clamp: bool, cd: str = "vcc_lo") -> tuple[int, int]: + if _TMP_DIR is None: + setUpModule() + mod = " clamp" if clamp else "" + lines = [ + f"v_mov_b32 v1, {x:#x}", + f"v_mov_b32 v2, {y:#x}", + f"s_mov_b32 vcc_lo, {-1 if cin else 0}", + ] + if op.endswith("ci_u32"): + lines.append(f"{op}_e64 v0, {cd}, v1, v2, vcc_lo{mod}") + else: + lines.append(f"{op} v0, {cd}, v1, v2{mod}") + if cd == "null": + lines.append("v_mov_b32 v7, 0") + else: + lines.append(f"v_cndmask_b32_e64 v7, 0, 1, {cd}") + lines += [ + "v_and_b32 v5, 0xffff, v0", + "v_lshrrev_b32 v6, 16, v0", + "v_or_b32 v5, 0x40000000, v5", + "v_or_b32 v6, 0x40000000, v6", + "v_or_b32 v7, 0x40000000, v7", + ] + asm = "; test_add_co_clamp\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v5, v6, v7, v5 done vm\n\ts_endpgm\n" + with open(_SRC_PATH, "w", encoding="utf-8", newline="\n") as f: + f.write(asm) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + spv = rdna2spirv.translate(_SRC_PATH) + lo, hi, cword = si.run_fragment(spv)["%out_mrt0"][:3] + assert lo >> 16 == 0x4000 and hi >> 16 == 0x4000 and cword >> 16 == 0x4000, (hex(lo), hex(hi), hex(cword)) + return (lo & 0xFFFF) | ((hi & 0xFFFF) << 16), cword & 1 + + +class AddCoClampTests(unittest.TestCase): + def test_edge_pairs_all_six_ops(self): + for op in CO_OPS: + for clamp in (False, True): + for x, y in EDGE_PAIRS: + self.assertEqual(run_case(op, x, y, 0, clamp), ref(op, x, y, 0, clamp), + (op, hex(x), hex(y), clamp)) + for op in CO_CI_OPS: + for clamp in (False, True): + for cin in (0, 1): + for x, y in EDGE_PAIRS: + self.assertEqual(run_case(op, x, y, cin, clamp), ref(op, x, y, cin, clamp), + (op, hex(x), hex(y), cin, clamp)) + + def test_null_and_sgpr_carry_dests(self): + for op in ("v_add_co_u32", "v_sub_co_u32", "v_add_co_ci_u32", "v_sub_co_ci_u32"): + x, y, cin = (0xFFFFFFFF, 1, 1) if "add" in op else (0, 1, 1) + want_d, want_c = ref(op, x, y, cin, True) + got_d, _ = run_case(op, x, y, cin, True, cd="null") + self.assertEqual(got_d, want_d, (op, "null")) + self.assertEqual(run_case(op, x, y, cin, True, cd="s12"), (want_d, want_c), (op, "s12")) + + def test_inactive_exec_lane(self): + if _TMP_DIR is None: + setUpModule() + lines = [ + "v_mov_b32 v0, 0x12345678", + "v_mov_b32 v1, 0xffffffff", + "v_mov_b32 v2, 0xffffffff", + "s_mov_b32 vcc_lo, -1", + "s_mov_b32 s10, exec_lo", + "s_mov_b32 exec_lo, 0", + "v_add_co_u32 v0, vcc_lo, v1, v2 clamp", + "s_mov_b32 exec_lo, s10", + "v_cndmask_b32_e64 v7, 0, 1, vcc_lo", + "v_and_b32 v5, 0xffff, v0", + "v_lshrrev_b32 v6, 16, v0", + "v_or_b32 v5, 0x40000000, v5", + "v_or_b32 v6, 0x40000000, v6", + "v_or_b32 v7, 0x40000000, v7", + ] + asm = "; test_inactive\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v5, v6, v7, v5 done vm\n\ts_endpgm\n" + with open(_SRC_PATH, "w", encoding="utf-8", newline="\n") as f: + f.write(asm) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + spv = rdna2spirv.translate(_SRC_PATH) + lo, hi, cword = si.run_fragment(spv)["%out_mrt0"][:3] + self.assertEqual((lo & 0xFFFF) | ((hi & 0xFFFF) << 16), 0x12345678) + self.assertEqual(cword & 1, 0) + + def test_seeded_random(self): + rng = random.Random(20261122) + for op in CO_OPS + CO_CI_OPS: + for _ in range(12): + x, y = rng.randrange(1 << 32), rng.randrange(1 << 32) + cin = rng.randrange(2) + for clamp in (False, True): + self.assertEqual(run_case(op, x, y, cin, clamp), ref(op, x, y, cin, clamp), + (op, hex(x), hex(y), cin, clamp)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 9b6fe70df1..7734b0c25f 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -5718,10 +5718,16 @@ def halves(s, is_mask): self.emit(f"{r} = OpCompositeExtract %uint {s2} 0") self.emit(f"{c2} = OpCompositeExtract %uint {s2} 1") self.emit(f"{carry} = OpBitwiseOr %uint {c1} {c2}") + carry_nz = self.tmp_bool_nz(carry) + if "clamp" in mods: + # Hardware saturates D (0xffffffff on add carry, 0 on sub borrow) while reporting the real carry/borrow. + clamped = self.tmp() + self.emit(f"{clamped} = OpSelect %uint {carry_nz} {self.cu(0) if sub else self.cu(0xFFFFFFFF)} {r}") + r = clamped self.dst(vd, r) if not (cd["k"] == "special" and cd["t"] == "null"): cm, m = self.tmp(), self.tmp() - self.emit(f"{cm} = OpLogicalAnd %bool {self.tmp_bool_nz(carry)} {self.active_b()}") # inactive lanes write 0 + self.emit(f"{cm} = OpLogicalAnd %bool {carry_nz} {self.active_b()}") # inactive lanes write 0 self.emit(f"{m} = OpSelect %uint {cm} {self.cu(0xFFFFFFFF)} {self.cu(0)}") self.mask_dst(cd, m) elif op == "v_mul_legacy_f32": From d816e75e735567fc16cdb679097328fd431fbccc Mon Sep 17 00:00:00 2001 From: Kam471 <115741199+Kam471@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:27:24 +0000 Subject: [PATCH 055/115] docs: remove the last duplicated intro fragment in models.md --- docs/models.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/docs/models.md b/docs/models.md index 873f97d51b..90d31c1a8e 100644 --- a/docs/models.md +++ b/docs/models.md @@ -24,9 +24,6 @@ over `917e9b9`'s 350,251) with **0 decode failures**; the `levels.rpf` fragment, triangle cells are not independently reproduced (see the table note), and the earlier `917e9b9`, `c3708fb`, and `48557ea` measurements are kept below as controls. This page records the measured state; it is not a competing patch. -decoding (PR #7). The 350,251-model counts below were measured at `917e9b9` and are kept as the -control; the `e293917` re-count for the non-`levels.rpf` archives is in the table below. This page -records both, and is not a competing patch. PR #1 reports 190,792 of 190,792 recognized candidates across the ten archives configured in Leonida, including 169 previously rejected candidates (also verified after archive readback). A From 3ea9b4079264a596b33456e69d5cc5fbf02057cc Mon Sep 17 00:00:00 2001 From: Tayar <358041433+lucastayaralvarenga-ui@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:27:40 -0300 Subject: [PATCH 056/115] user_sgpr_census: validate stage assignments before scanning --- tests/test_user_sgpr_census.py | 21 +++++++++++++++++++++ tools/user_sgpr_census.py | 24 +++++++++++++++++------- 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/tests/test_user_sgpr_census.py b/tests/test_user_sgpr_census.py index 4a94ff372f..ee414a1836 100644 --- a/tests/test_user_sgpr_census.py +++ b/tests/test_user_sgpr_census.py @@ -1,7 +1,10 @@ """tools/user_sgpr_census.py on hand-written index.json data (no game files, no GPU).""" import json import os +from pathlib import Path +import subprocess import sys +import tempfile ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "tools")) @@ -79,3 +82,21 @@ def test_expect_passes_and_fails(tmp_path, capsys): assert usc.main([str(p), "--expect", "ps=8", "cs=4"]) == 0 assert usc.main([str(p), "--expect", "ps=0"]) == 1 assert "expected s0, got s8" in capsys.readouterr().err + + +def test_cli_rejects_malformed_stage_assignment(): + with tempfile.TemporaryDirectory() as tmp: + index = Path(tmp, "index.json") + report = Path(tmp, "report.json") + index.write_text(json.dumps(INDEX), encoding="utf-8") + tool = os.path.join(ROOT, "tools", "user_sgpr_census.py") + for option in ("--base", "--expect"): + for assignment in ("ps", "ps=bad", "=8", "ps=-1"): + result = subprocess.run( + [sys.executable, "-I", tool, str(index), "--json", str(report), option, assignment], + capture_output=True, text=True, + ) + assert result.returncode == 2, result.stderr + assert "expected STAGE=SGPR" in result.stderr + assert "Traceback" not in result.stderr + assert not report.exists() diff --git a/tools/user_sgpr_census.py b/tools/user_sgpr_census.py index 35fa44ddfb..7945b7c787 100644 --- a/tools/user_sgpr_census.py +++ b/tools/user_sgpr_census.py @@ -83,19 +83,30 @@ def census(index, base=None): return out +def stage_sgpr(text): + stage, _, value = text.partition("=") + message = f"expected STAGE=SGPR with a nonnegative SGPR: {text!r}" + try: + sgpr = int(value) + except ValueError: + raise argparse.ArgumentTypeError(message) from None + if not stage or sgpr < 0: + raise argparse.ArgumentTypeError(message) + return stage, sgpr + + def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("index", help="spirv/index.json written by tools/rdna2spirv.py") ap.add_argument("--json", help="also write the summary here") - ap.add_argument("--expect", nargs="*", default=[], metavar="STAGE=SGPR", + ap.add_argument("--expect", nargs="*", type=stage_sgpr, default=[], metavar="STAGE=SGPR", help="fail if the most common lowest-pointer SGPR of STAGE is not SGPR") - ap.add_argument("--base", nargs="*", default=[], metavar="STAGE=SGPR", + ap.add_argument("--base", nargs="*", type=stage_sgpr, default=[], metavar="STAGE=SGPR", help="report the reads below this first root-argument SGPR per stage") a = ap.parse_args(argv) with open(a.index, encoding="utf-8") as f: index = json.load(f) - base = {k: int(v) for k, _, v in (b.partition("=") for b in a.base)} - summary = census(index, base) + summary = census(index, dict(a.base)) for stage, s in summary.items(): top = s["most_common_lowest_pointer_sgpr"] print(f"{stage}: {s['shaders']} shaders; lowest pointer SGPR " @@ -106,10 +117,9 @@ def main(argv=None): with open(a.json, "w", encoding="utf-8") as f: json.dump(summary, f, indent=1, sort_keys=True) bad = [] - for item in a.expect: - stage, _, sgpr = item.partition("=") + for stage, sgpr in a.expect: got = summary.get(stage, {}).get("most_common_lowest_pointer_sgpr") - if got != int(sgpr): + if got != sgpr: bad.append(f"{stage}: expected s{sgpr}, got {'s%d' % got if got is not None else 'none'}") for b in bad: print("MISMATCH", b, file=sys.stderr) From ee522162449751b34b99b23161dbb72727aec1d4 Mon Sep 17 00:00:00 2001 From: Kam471 <115741199+Kam471@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:24:33 +0000 Subject: [PATCH 057/115] docs: bind COM_KBOS_NEIGHB to its mission tables by character link hash The mission table id is not joined by name hash. The Pipework text names Mandy and Bert; the common schedule and SixNG name dictionary resolve them to link hashes, and five of 2,309 story000_script PSINs carry those hashes in 28 pool elements. Records the method, the three per-state archetypes for each character, and what the binding does not prove. --- docs/mission_logic.md | 55 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 51 insertions(+), 4 deletions(-) diff --git a/docs/mission_logic.md b/docs/mission_logic.md index 8f754556e0..6533395d56 100644 --- a/docs/mission_logic.md +++ b/docs/mission_logic.md @@ -103,7 +103,54 @@ are no opcodes here, and no jump table. Two consequences for a runtime: ## Mission identity -The package's own text metadata carries a 145-entry mission table. Only **one** of those ids is provably -bound to one of these tables, so most outlines are unattributed. Joining ids to tables is an open problem; -a plain joaat of the ids does not appear in the program data (0 of 290 variants in 170.9 MB), so the join -is not by name hash. +The package's own text metadata carries a 145-entry mission table. Two of those ids now have a +reproducible binding to one of these tables, so most outlines are still unattributed. Joining ids to +tables is an open problem; a plain joaat of the ids does not appear in the program data (0 of 290 +variants in 170.9 MB), so the join is not by name hash. + +## Binding a mission id to its tables + +This binding does not join on the id. It uses a **character** as the bridge: the mission's own text names +a person, a name dictionary turns that name into a 32-bit hash, and the same hash appears as the +`linkHash` of pool elements in a state table. + +1. **Start from a name the mission text uses.** `COM_KBOS_NEIGHB` is the replay-table id for the mission + publicly catalogued as **Pipework** (Mandy's rent). The matching text table at `data.rpf` stream + `0x19957A0` contains the line "You brought the cops to Mandy's house" and the line "Bert died". +2. **Resolve the character and its schedule.** `common.rpf` stream `0x4C270` lists + `KeyLento/Perschars/Peds/Unique/Mandy` and `.../Bert` under the pack `PSP_KeyLento_perschars_peds`. + SixNG's name dictionary, which is lower-case joaat, resolves the pack to `0x865F0DA9`, Mandy to + `0x03A885E6` and Bert to `0xE34ACBC8`. +3. **Scan the PSINs for the link hash.** In the 64-byte element above, `linkHash` is the dword at byte + `+0x34`, not the archetype dword. Inflating the five `story000_script.rpf` streams at `0x3FE4000`, + `0x3FE8000`, `0x3FEB000`, `0x3FEE000` and `0x3FF0000` and searching for those two hashes finds 28 + elements: 15 Mandy and 13 Bert. A scan of all 2,309 PSIN streams finds those 28 hits in exactly these + five files. +4. **Read the element.** Its start is `linkHash - 52`. The first dword is the archetype/state hash + described above. It does not resolve in the name dictionary, and the same character takes three + values, so it is an archetype/state hash rather than a character model name. + +| stream | Mandy elements | Mandy archetype | Bert elements | Bert archetype | +|---|---:|---|---:|---| +| `0x3FE4000` | 5 | `0x18BB2550` | 5 | `0xA5A1E67D` | +| `0x3FE8000` | 3 | `0x73E83886` | 3 | `0x780A05A5` | +| `0x3FEB000` | 3 | `0x73E83886` | 4 | `0x780A05A5` | +| `0x3FEE000` | 3 | `0x73E83886` | 0 | - | +| `0x3FF0000` | 1 | `0x57DDFFC2` | 1 | `0xCBA48304` | + +Mandy has three distinct archetype values in this set and Bert three; none resolves in the name +dictionary. + +The five tables are bound to `COM_KBOS_NEIGHB` through two people the mission's own text names, both +present as link hashes in the same five streams. It is a binding by cast, not by id: the public +`Pipework` name is the outside link between the id and the text, and a mission whose cast is not in the +dictionary still has no bridge. + +It does **not** turn `0x18BB2550`, `0x73E83886`, `0x57DDFFC2`, `0xA5A1E67D`, `0x780A05A5` or +`0xCBA48304` into model names. None resolves in the same dictionary, and the first dword changes per +state; it is an archetype/state hash, not a Mandy or Bert drawable. The table that would name those +archetypes is not in the readable archives. + +This is **one more binding, not a general solution**. The other 143 ids in the mission table remain +unattributed unless a character, schedule or other stable name gives them a bridge; joining ids to +tables is still an open problem. From 44ca61d0677b33cb06e51db4b3e411fefea1f74f Mon Sep 17 00:00:00 2001 From: FreddyxS <103101848+FreddyxS@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:27:45 +0100 Subject: [PATCH 058/115] Test the viewer overlay when WebGL initialization fails --- tests/test_viewer_streaming.cjs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/tests/test_viewer_streaming.cjs b/tests/test_viewer_streaming.cjs index 596caaa199..666bd9ffc8 100644 --- a/tests/test_viewer_streaming.cjs +++ b/tests/test_viewer_streaming.cjs @@ -6,6 +6,7 @@ const { test } = require('node:test'); // Exercise the viewer's actual loading and streaming code without WebGL, a network or game data. const html = readFileSync(join(__dirname, '..', 'viewer', 'index.html'), 'utf8'); +const viewerModule = html.match(/