Skip to content

SHADER-423: 64-bit buffer addresses as 32-bit pairs, without Int64 - #2463

Open
c4k3ss wants to merge 6 commits into
ItsNotRexed:mainfrom
c4k3ss:shader/addr-no-int64
Open

c4k3ss wants to merge 6 commits into
ItsNotRexed:mainfrom
c4k3ss:shader/addr-no-int64

Conversation

@c4k3ss

@c4k3ss c4k3ss commented Nov 22, 2026 •

Copy link
Copy Markdown

Claim: #2300 (comment) (new SHADER item, from @richardsenra's finding in #313, #313 (comment))

What

Every PhysicalStorageBuffer address the translator builds is one idiom: widen a dword (OpUConvert), shift the high word by 32, OR, add or subtract (64-bit constants included), AND a mask, take a word back (narrow, or shift right by 32), sign-extend a dword (the signed offset of a global_* access) and shift it right arithmetically by 32; the NUM_RECORDS bound of a buffer access compares two such values. Until now that made every shader that touches memory declare OpCapability Int64, so index.json listed shaderInt64 for it and the runtime required the feature, which Intel's Vulkan drivers don't offer although they have bufferDeviceAddress (#313, #1825's ps_m3_post failure).

lower_addr64 (tools/rdna2spirv.py) runs on the assembled module. When a shader's only 64-bit integers are that idiom, each 64-bit value becomes a (low, high) pair of 32-bit words: OpIAddCarry / OpISubBorrow carry into the high word, a sign-extended dword is (value, value >> 31), compares go high word first, and the pair is built into a uvec2 and bitcast to the pointer, as GL_EXT_buffer_reference_uvec2 does. The module drops OpCapability Int64 (and the unused %ulong/%long types and 64-bit constants); PhysicalStorageBufferAddresses and the PhysicalStorageBuffer64 memory model stay. A shader with any other 64-bit integer use (64-bit multiplies, shifts by other amounts, a 64-bit OpPhi or variable) is left exactly as it was and keeps Int64. --int64-addresses turns the lowering off.

tests/semantic/spirv_mini_interp.py learns the one new form, OpBitcast of two 32-bit words to a PhysicalStorageBuffer pointer.

Tests

  • tests/semantic/test_addr64_lowering.py (new, 7 tests; the seventh: global_load with negative and positive offsets reads the same word in both forms, no Int64 or %long in the lowered module): the lowered module has no Int64, %ulong or OpConvertUToPtr; --int64-addresses keeps the old form; both forms read the same word in the interpreter for a plain sum, a low-word carry (heap 0x1_FFFF_FFF0 + pointer 0x20) and a 64-bit wrap; dropping the carry from the lowered module is caught (negative control); a program with s_lshl_b64 keeps Int64 and still runs; the pass is idempotent and leaves modules without 64-bit types alone.
  • python -I -m unittest discover -s tests/semantic: 2,574 tests OK (3 skipped); pytest tests/test_translate.py: 526 passed, 2 skipped
  • python -I scripts/run_gpu_tests.py on an NVIDIA GeForce RTX 5070 Ti (621.24, Vulkan 1.4.357, Windows 11 26200): 190 shaders translated, 190 pass spirv-val; 139/185 passed, 46 skipped (wave64 tests and fixtures run by the d3d12_* tests), 0 failed; with LEONIDA_W64_EMULATE=1: 170/185 passed, 15 skipped, 0 failed
  • The same suite with LEONIDA_VK_DEVICE="AMD Radeon" on the RDNA2 gfx1036 iGPU (AMD 25.10.34, native wave64): 170/185 passed, 15 skipped, 0 failed
  • Of the 190 test shaders the suite translates, 117 touch memory: 104 of those now carry no Int64 (cs_global_neg_offset included, since 65e64c2) and 13 keep it (cs_w32_salu64, cs_oob_tail, cs_bvh*, the typed-format fixtures, cs_smem_soffset_imm, ps_vcc_x2, ps_vcmpx_forms, ps_fnan_*: 64-bit multiplies and shifts by other amounts); all 190 pass spirv-val.
  • ctest --test-dir runtime/build -C RelWithDebInfo after a rebuild (the M2/M3/M4 and translated-draw fixtures are re-translated by the build): 124/124 passed, 8 skipped (game-file and validation-layer tests); d3d12_translated_draw, d3d12_m2_textured, d3d12_m2_formats, d3d12_m3_frame, d3d12_m3_first_pass and d3d12_m4_compute all pass with their 12 re-translated shaders, none of which declares Int64 any more (ps_m3_post included, the one that failed on Intel in Runtime tests: separate M3 occlusion counting from MRT exports (D3D-209) #1825)
  • docs/design.md: one contract row, "64-bit addresses without Int64".

Not covered: the retail corpus (no game files here: a count of modules still declaring Int64 at this head from someone with the package would settle how much of it this reaches), and shaders that use 64-bit data arithmetic, which keep Int64 as before.

History: c550d53 the pass; 8b38800 review fixes (test_translate accepts the pair bitcast, interpreter type check, docs wording); 65e64c2 the signed-offset idiom. Follow-up if wanted: have make_game.py save --int64-addresses next to the translated shaders like its other fallback flags.

No game files. AI-assisted (Claude Code); built and tested on the hardware above.

Known: tests/test_docs_design_rows.py fails 3 subtests on main 4947579 too (duplicate topic rows in design.md, README.md, testing.md); this PR adds one row and does not change that count.

🤖 Generated with Claude Code

…HADER-423)

Every PhysicalStorageBuffer address the generator builds is one idiom:
widen a dword, shift the high word by 32, OR, add or subtract, AND,
narrow or shift right by 32, compare two such values, convert to a
pointer. lower_addr64 runs on the assembled module: when a shader's only
64-bit integers are that idiom, each value becomes a (low, high) pair of
uints with OpIAddCarry / OpISubBorrow into the high word, compares go
high word first, and the pair is a uvec2 bitcast to the pointer (as
GL_EXT_buffer_reference_uvec2). The module drops OpCapability Int64, so
index.json stops listing shaderInt64 for it; devices with buffer device
addresses but no shaderInt64 (Intel) can run those modules. A shader
with any other 64-bit integer use keeps Int64. --int64-addresses opts
out. spirv_mini_interp learns the uint-pair-to-pointer bitcast.

Tests: tests/semantic/test_addr64_lowering.py (both forms read the same
word with a plain sum, a low-word carry and a 64-bit wrap; dropping the
carry is caught; a 64-bit data op keeps Int64). run_gpu_tests.py: 190
shaders pass spirv-val; RTX 5070 Ti 139/185 native, 170/185 emulated;
RDNA2 gfx1036 iGPU 170/185; 0 failures. 103 of the 117 shaders that
touch memory no longer declare Int64.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@richardsenra

Copy link
Copy Markdown
Contributor

Independent Intel + NVIDIA verification at c550d5334f66b4af234b45fb0e9a8b27170650cc. The requested full M3 check passes on Intel without shaderInt64, as do the other five targeted layer tests. The standalone Intel suite still encounters old test-tool feature gates and reporting/selection problems, detailed below. AI-assisted.

Windows 11 Pro 26300; Intel UHD 31.0.101.4146, shaderInt64 absent; NVIDIA RTX 3050 6GB Laptop 617.14 / 32.0.16.1714. MSVC 19.44.35230, SDK NuGet 10.0.26100.9457 (include/lib directories named 10.0.26100.0), Vulkan headers 1.4.363, native AMDGPU LLVM 23.1.6, SPIRV-Tools 2026.4.

Layer and lowering checks

ctest -R '^(d3d12_translated_draw|d3d12_m2_textured|d3d12_m2_formats|d3d12_m3_frame|d3d12_m3_first_pass|d3d12_m4_compute)$' -V: 6/6 pass on both GPUs. Validation, including synchronization validation, is enabled in these runtime tests; zero validation warnings/errors.

  • Full M3: all 73,728 pixel comparisons match and 3,555 exact samples on both devices. The default full second pass runs.
  • M4: 1,924 words match its CPU oracle on both devices, including cross-queue copy/compute/fence behavior.
  • All 15 generated module entries for these targets are spirv-val-valid and contain no Int64 capability/type. Their metadata retains bufferDeviceAddress/runtimeDescriptorArray where used and omits shaderInt64 consistently.
  • Six test_addr64_lowering.py tests pass. In the standalone fixture index, the 14 shaders with remaining Int64 use also retain shaderInt64 metadata.
  • Re-translated the synthetic post shader with --int64-addresses: Intel full M3 fails with the original Int64 capability validation error, while NVIDIA passes. The default module is byte-identical to the normal CMake output and passes on both. The generated post module was restored in finally, byte-for-byte; no runtime/oracle/source changes.
  • An additional hand-written GPU arithmetic fixture goes through this PR's actual lower_addr64, not our earlier private rewriter. 512 input pairs cover add/carry, subtract/borrow, AND/OR, shifts by 32, narrowing and all six unsigned/equality comparisons. Both GPUs match an independent Python integer oracle for 9,728 result words, plus preserved inputs and sentinels (12,320 checked words total), with zero validation errors. The native Int64 form passes on NVIDIA and skips on Intel; a valid-SPIR-V negative control dropping the borrow produces 253 mismatches on both GPUs. Reproducer below.

Standalone suite: useful limitations to address

Unmodified scripts/run_gpu_tests.py, native mode, with all helper binaries built:

Requested adapter Translation / spirv-val Raw suite result
NVIDIA 190/190 139/185 pass, 46 skip, 0 fail
Intel 189/190 (the computed-I/J shader is excluded by the automatic f16 interpolation fallback) 65/185 pass, 63 skip, 57 fail

The raw Intel aggregate includes two NVIDIA runs, so it must not be read as 65 Intel passes. I traced the problems rather than treating the table as evidence of a lowering regression:

  1. 52 failing cases stop at device creation (VK_ERROR_FEATURE_NOT_PRESENT). runtime/test/vk_compute_test.cpp:163 and vk_texture_test.cpp:178 still request shaderInt64 unconditionally. A scratch diagnostic copy of the compute helper, changing only f2.features.shaderInt64 to the queried physical-device value, makes the same Int64-free cs_bounds.spv run correctly on Intel: 0x12345678, 0x12345678, 0, 0xEEEEEEEE, also correct on NVIDIA. Stock helper fails before that shader executes. This diagnostic is not a production fix or part of the reported suite run.
  2. Four FAILs are actually unsupported returns (77): cs_imgstore, cs_imgload, cs_imgload_d16, cs_sample_lz_int_d16. The store helper reports shaderInt64=0, but scripts/run_gpu_tests.py:999-1004 treats their nonzero return as FAIL and shows only the last stderr line, hiding the unsupported reason. Other branches already handle 77 as SKIP.
  3. The remaining pixel mismatch is ps_ops8 (first two integer channels). Its module is byte-identical with --int64-addresses, so the new lowering does not modify the mismatching module. I am not reporting a root cause for that separate mismatch.
  4. vk_bindless_test.cpp:181-195 ignores LEONIDA_VK_DEVICE in its manual rank loop. With LEONIDA_VK_DEVICE=Intel, ps_tex and ps_imgatomic printed device: NVIDIA GeForce RTX 3050... and passed. Restricting the process to the installed Intel ICD makes both correctly select Intel and return 77 from their old shaderInt64 gate. The raw 65-pass count above includes those two NVIDIA passes. The other traced failures and the six layer tests print the selected Intel device.

Also relevant: vk_store_test.cpp:101, vk_harness.cpp:379 and vk_bindless_test.cpp:207 still gate address-using shaders on shaderInt64. These files are unchanged from main 4947579 by this PR. A follow-up should inspect the module's actual Int64 requirement and query feature support, preserving 77 for modules that really need unavailable Int64. The adapter selector and 77 reporting should be honored as well. I would not describe the full Intel standalone suite as green yet.

Scope: synthetic fixtures only, without source changes or game/corpus tests. The core Intel/M3 result is positive; the standalone tool limitations above remain visible for the maintainer's decision.

Independent arithmetic/comparison GPU reproducer (synthetic only)

Save these two files in the repository root at the reviewed SHA. In a developer PowerShell with Vulkan SDK tools and validation installed:

python -I generate_arithmetic_oracle.py --repo .
spirv-as --target-env vulkan1.2 arithmetic-lowered.spvasm -o arithmetic-lowered.spv
spirv-val --target-env vulkan1.2 arithmetic-lowered.spv
cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I runtime/test /I "$env:VULKAN_SDK/Include" arithmetic_gpu.cpp /Fe:arithmetic_gpu.exe
$env:LEONIDA_VK_DEVICE = "Intel"
$env:LEONIDA_VK_VALIDATION = "1"
.\arithmetic_gpu.exe arithmetic-lowered.spv arithmetic-initial.bin arithmetic-expected.bin

Also assemble/validate/run arithmetic-original (native NVIDIA pass, Intel 77) and arithmetic-bad-borrow (both devices exit 1 with 253 mismatches). Run the lowered variant on NVIDIA as a control. This runner uses the repository device helper and compares the entire buffer, including input words and untouched sentinel slots.

generate_arithmetic_oracle.py

"""Hand-written SPIR-V and Python integer oracle for the PR's actual lowering pass."""
import argparse
from pathlib import Path
import random
import struct
import sys

ROOT = Path(__file__).resolve().parent
p = argparse.ArgumentParser()
p.add_argument("--repo", type=Path, required=True)
TOOLS = p.parse_args().repo.resolve() / "tools"
sys.path.insert(0, str(TOOLS))
import rdna2spirv

M32, M64 = (1 << 32) - 1, (1 << 64) - 1
pairs = [(0, 0), (M32, 1), (M64, 1), (0, 1), (1, M64), (M32, 1 << 32),
         (1 << 32, M32), (M64, M64), (1 << 63, (1 << 63) - 1),
         (0x12345678FFFFFFFF, 0x1234567800000000), (0x1234567800000000, 0x12345678FFFFFFFF),
         (0xFFFFFFFF00000000, 0x100000000), (0x7FFFFFFFFFFFFFFF, 1),
         (0x9ABCDEF012345678, 0x76543210FEDCBA98), (0x10FFFFFFF0, 0x200000020), (123, 123)]
rng = random.Random(2463)
while len(pairs) < 512:
    a, b = rng.getrandbits(64), rng.getrandbits(64)
    if len(pairs) % 4 == 0:
        b = (a & (M32 << 32)) | rng.getrandbits(32)
    pairs.append((a, b))
initial = [word for a, b in pairs for word in (a & M32, a >> 32, b & M32, b >> 32)]
input_words = len(initial)
initial += [0xCDCDCDCD] * (512 * 20 + 32)
expected = initial.copy()
for i, (a, b) in enumerate(pairs):
    values = []
    for value in ((a + b) & M64, (a - b) & M64, a & b, a | b, (a << 32) & M64, a >> 32):
        values.extend((value & M32, value >> 32))
    values += [a & M32] + [int(v) for v in (a < b, a <= b, a > b, a >= b, a == b, a != b)]
    expected[input_words + i * 20:input_words + i * 20 + 19] = values
for filename, words in (("arithmetic-initial.bin", initial), ("arithmetic-expected.bin", expected)):
    (ROOT / filename).write_bytes(struct.pack("<" + "I" * len(words), *words))
lines = [
    "OpCapability Shader", "OpCapability Int64", "OpMemoryModel Logical GLSL450",
    'OpEntryPoint GLCompute %main "main" %data %gid', "OpExecutionMode %main LocalSize 32 1 1",
    "OpDecorate %gid BuiltIn GlobalInvocationId", "OpDecorate %rarr ArrayStride 4",
    "OpMemberDecorate %Data 0 Offset 0", "OpDecorate %Data Block",
    "OpDecorate %data DescriptorSet 0", "OpDecorate %data Binding 0",
    "%void = OpTypeVoid", "%function = OpTypeFunction %void", "%bool = OpTypeBool",
    "%uint = OpTypeInt 32 0", "%ulong = OpTypeInt 64 0", "%long = OpTypeInt 64 1",
    "%umul = OpTypeStruct %uint %uint", "%v3uint = OpTypeVector %uint 3",
    "%pin = OpTypePointer Input %v3uint", "%rarr = OpTypeRuntimeArray %uint",
    "%Data = OpTypeStruct %rarr", "%pdata = OpTypePointer StorageBuffer %Data",
    "%pword = OpTypePointer StorageBuffer %uint",
]
lines += [f"%u{v} = OpConstant %uint {v}" for v in sorted(set(range(20)) | {32, input_words})]
lines += ["%z64 = OpConstant %ulong 0", "%s32 = OpConstant %ulong 32",
          "%data = OpVariable %pdata StorageBuffer", "%gid = OpVariable %pin Input",
          "%main = OpFunction %void None %function", "%entry = OpLabel",
          "%id = OpLoad %v3uint %gid", "%idx = OpCompositeExtract %uint %id 0",
          "%ib = OpIMul %uint %idx %u4"]
for j in range(4):
    lines += [f"%ii{j} = OpIAdd %uint %ib %u{j}", f"%ip{j} = OpAccessChain %pword %data %u0 %ii{j}",
              f"%word{j} = OpLoad %uint %ip{j}", f"%wide{j} = OpUConvert %ulong %word{j}"]
lines += ["%ah = OpShiftLeftLogical %ulong %wide1 %s32", "%av = OpBitwiseOr %ulong %ah %wide0",
          "%bh = OpShiftLeftLogical %ulong %wide3 %s32", "%bv = OpBitwiseOr %ulong %bh %wide2",
          "%ob = OpIMul %uint %idx %u20", f"%obase = OpIAdd %uint %ob %u{input_words}"]
# u20 is used for the stride, declared before the entry point.
at = lines.index("%z64 = OpConstant %ulong 0")
lines.insert(at, "%u20 = OpConstant %uint 20")
results = []
for name, op, rhs in (("add", "OpIAdd", "%bv"), ("sub", "OpISub", "%bv"),
                      ("and", "OpBitwiseAnd", "%bv"), ("or", "OpBitwiseOr", "%bv"),
                      ("left", "OpShiftLeftLogical", "%s32"), ("right", "OpShiftRightLogical", "%s32")):
    lines += [f"%{name} = {op} %ulong %av {rhs}", f"%{name}_lo = OpUConvert %uint %{name}",
              f"%{name}_shifted = OpShiftRightLogical %ulong %{name} %s32",
              f"%{name}_hi = OpUConvert %uint %{name}_shifted"]
    results += [f"%{name}_lo", f"%{name}_hi"]
lines.append("%narrow = OpUConvert %uint %av")
results.append("%narrow")
for name, op in (("lt", "OpULessThan"), ("le", "OpULessThanEqual"), ("gt", "OpUGreaterThan"),
                 ("ge", "OpUGreaterThanEqual"), ("eq", "OpIEqual"), ("ne", "OpINotEqual")):
    lines += [f"%{name} = {op} %bool %av %bv", f"%{name}_word = OpSelect %uint %{name} %u1 %u0"]
    results.append(f"%{name}_word")
for j, result in enumerate(results):
    lines += [f"%oi{j} = OpIAdd %uint %obase %u{j}", f"%op{j} = OpAccessChain %pword %data %u0 %oi{j}",
              f"OpStore %op{j} {result}"]
lines += ["OpReturn", "OpFunctionEnd"]
text = "\n".join(lines) + "\n"
lowered = rdna2spirv.lower_addr64(text)
assert "OpCapability Int64" not in lowered and "OpTypeInt 64" not in lowered
assert rdna2spirv.lower_addr64(lowered) == lowered
(ROOT / "arithmetic-original.spvasm").write_text(text, encoding="utf-8", newline="\n")
(ROOT / "arithmetic-lowered.spvasm").write_text(lowered, encoding="utf-8", newline="\n")
# Corrupt the borrow specifically; this tests the high-word subtraction edge cases.
import re
bad, count = re.subn(r"(OpISub %uint %a64_\d+g) %a64_\d+c", r"\1 %a64c_0", lowered)
assert count == 1
(ROOT / "arithmetic-bad-borrow.spvasm").write_text(bad, encoding="utf-8", newline="\n")
print(f"Generated {len(pairs)} input pairs, 19 arithmetic/comparison words each; independent Python integer oracle.")

arithmetic_gpu.cpp

// Independent GPU word oracle for the real PR lowering pass. Synthetic inputs only. AI-assisted.
#include "vk_test_device.h"
#include <fstream>
#include <vector>
#include <cstdint>
#include <cstring>

#define EXPECT(c) do { if (!(c)) { std::printf("failure at line %d\n", __LINE__); return 1; } } while (0)

int main(int argc, char** argv) {
    EXPECT(argc == 4);
    std::ifstream input(argv[1], std::ios::binary | std::ios::ate);
    const auto bytes = input.tellg();
    EXPECT(bytes > 0 && bytes % 4 == 0);
    std::vector<std::uint32_t> code(std::size_t(bytes) / 4);
    input.seekg(0);
    EXPECT(bool(input.read(reinterpret_cast<char*>(code.data()), bytes)));
    auto read_words = [](const char* path) {
        std::ifstream f(path, std::ios::binary | std::ios::ate);
        const auto n = f.tellg();
        if (n <= 0 || n % 4) return std::vector<std::uint32_t>{};
        std::vector<std::uint32_t> data(std::size_t(n) / 4);
        f.seekg(0);
        if (!f.read(reinterpret_cast<char*>(data.data()), n)) data.clear();
        return data;
    };
    const auto initial = read_words(argv[2]), expected = read_words(argv[3]);
    EXPECT(!initial.empty() && initial.size() == expected.size());
    const auto output_bytes = initial.size() * sizeof(std::uint32_t);
    bool needs_int64 = false;
    for (std::size_t at = 5; at < code.size();) {
        const auto words = code[at] >> 16, op = code[at] & 0xffff;
        EXPECT(words && at + words <= code.size());
        needs_int64 |= op == 17 && words == 2 && code[at + 1] == 11;
        at += words;
    }
    vktest::Device d;
    const auto state = d.initialize();
    if (state == vktest::DeviceStatus::unavailable) return 77;
    EXPECT(state == vktest::DeviceStatus::ready);
    if (needs_int64 && !d.enabled.shaderInt64) {
        std::puts("SKIP: original module needs shaderInt64");
        return 77;
    }
    VkShaderModuleCreateInfo si{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
    si.codeSize = code.size() * 4; si.pCode = code.data();
    VkShaderModule shader{};
    EXPECT(d.fn<PFN_vkCreateShaderModule>("vkCreateShaderModule")(d.device, &si, nullptr, &shader) == VK_SUCCESS);
    VkDescriptorSetLayoutBinding binding{0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT};
    VkDescriptorSetLayoutCreateInfo di{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
    di.bindingCount = 1; di.pBindings = &binding;
    VkDescriptorSetLayout descriptor_layout{};
    EXPECT(d.fn<PFN_vkCreateDescriptorSetLayout>("vkCreateDescriptorSetLayout")(d.device, &di, nullptr, &descriptor_layout) == VK_SUCCESS);
    VkPipelineLayoutCreateInfo li{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
    li.setLayoutCount = 1; li.pSetLayouts = &descriptor_layout;
    VkPipelineLayout layout{};
    EXPECT(d.fn<PFN_vkCreatePipelineLayout>("vkCreatePipelineLayout")(d.device, &li, nullptr, &layout) == VK_SUCCESS);
    VkComputePipelineCreateInfo pi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
    pi.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, VK_SHADER_STAGE_COMPUTE_BIT, shader, "main"};
    pi.layout = layout;
    VkPipeline pipeline{};
    EXPECT(d.fn<PFN_vkCreateComputePipelines>("vkCreateComputePipelines")(d.device, VK_NULL_HANDLE, 1, &pi, nullptr, &pipeline) == VK_SUCCESS);
    VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1};
    VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
    pool_info.maxSets = 1; pool_info.poolSizeCount = 1; pool_info.pPoolSizes = &size;
    VkDescriptorPool pool{};
    EXPECT(d.fn<PFN_vkCreateDescriptorPool>("vkCreateDescriptorPool")(d.device, &pool_info, nullptr, &pool) == VK_SUCCESS);
    VkDescriptorSetAllocateInfo allocation{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO};
    allocation.descriptorPool = pool; allocation.descriptorSetCount = 1; allocation.pSetLayouts = &descriptor_layout;
    VkDescriptorSet set{};
    EXPECT(d.fn<PFN_vkAllocateDescriptorSets>("vkAllocateDescriptorSets")(d.device, &allocation, &set) == VK_SUCCESS);
    void* mapped{};
    const auto output = d.buffer(output_bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &mapped);
    EXPECT(output && mapped);
    std::memcpy(mapped, initial.data(), output_bytes);
    VkDescriptorBufferInfo buffer_info{output, 0, output_bytes};
    VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET};
    write.dstSet = set; write.descriptorCount = 1; write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; write.pBufferInfo = &buffer_info;
    d.fn<PFN_vkUpdateDescriptorSets>("vkUpdateDescriptorSets")(d.device, 1, &write, 0, nullptr);
    EXPECT(d.run([&](VkCommandBuffer cb) {
        d.fn<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
        d.fn<PFN_vkCmdBindDescriptorSets>("vkCmdBindDescriptorSets")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout, 0, 1, &set, 0, nullptr);
        d.fn<PFN_vkCmdDispatch>("vkCmdDispatch")(cb, 16, 1, 1);
        VkBufferMemoryBarrier2 barrier{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER_2};
        barrier.srcStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT; barrier.srcAccessMask = VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT;
        barrier.dstStageMask = VK_PIPELINE_STAGE_2_HOST_BIT; barrier.dstAccessMask = VK_ACCESS_2_HOST_READ_BIT;
        barrier.srcQueueFamilyIndex = barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.buffer = output; barrier.size = VK_WHOLE_SIZE;
        VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; dependency.bufferMemoryBarrierCount = 1; dependency.pBufferMemoryBarriers = &barrier;
        d.fn<PFN_vkCmdPipelineBarrier2>("vkCmdPipelineBarrier2")(cb, &dependency);
        return true;
    }));
    const auto* words = static_cast<const std::uint32_t*>(mapped);
    unsigned failures = 0;
    for (std::size_t i = 0; i < expected.size(); ++i) {
        if (words[i] != expected[i]) {
            if (failures < 4) std::printf("word %zu: got %08x expected %08x\n", i, words[i], expected[i]);
            ++failures;
        }
    }
    d.fn<PFN_vkDestroyDescriptorPool>("vkDestroyDescriptorPool")(d.device, pool, nullptr);
    d.fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(d.device, pipeline, nullptr);
    d.fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(d.device, layout, nullptr);
    d.fn<PFN_vkDestroyDescriptorSetLayout>("vkDestroyDescriptorSetLayout")(d.device, descriptor_layout, nullptr);
    d.fn<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(d.device, shader, nullptr);
    std::printf("%zu expected words (512 pairs plus inputs/sentinels): %u mismatches; %u validation errors\n", expected.size(), failures, d.validation_errors());
    return failures || d.validation_errors() ? 1 : 0;
}

@BrossGamer

BrossGamer commented Nov 22, 2026 •

Copy link
Copy Markdown

Arc A770 16 GB run of c550d5334f66b4af234b45fb0e9a8b27170650cc, the check you asked for. shaderInt64 is absent on this driver (32.0.101.9033, Vulkan 1.4.356, Windows 10 19044, subgroup 8..32). maxPushConstantsSize is 256.

run_gpu_tests.py: 190 shaders, 189 translated, 189 pass spirv-val. The one not translated is ps_ij_computed (computed I/J pair under --f16-interp-fallback: no PerVertexKHR inputs). Native 129/185 passed, 56 skipped, 0 failed. With LEONIDA_W64_EMULATE=1: 159/185 passed, 25 skipped, 1 failed.

d3d12_m3_frame and d3d12_m3_first_pass both passed.

The one failure is ms_w64x_ballot on the emulated mesh path: vk_harness enables VK_EXT_mesh_shader and exits non-zero (same three-line symptom as main 4eb6155, where the exit was 0xC0000409). Native skips it. The other emulated wave64 compute tests passed. Counts are also on #166.

@sperm

sperm commented Nov 22, 2026

Copy link
Copy Markdown

Tested c550d53 on AMD Radeon RX 9070 XT (RADV GFX1201) and the Ryzen 7 9800X3D iGPU (RADV RAPHAEL_MENDOCINO, gfx1036), Mesa 26.2.6, Linux 7.3.4: pass, no regressions.

  • Full python -I scripts/run_gpu_tests.py (Linux build of this branch's runtime/, LEONIDA_VK_DEVICE per GPU): 170/185 passed, 15 skipped, 0 failed on both GPUs. Compared with the same suite at the merge base 4947579 on the same machine, every test has the same result.
  • python -m unittest discover -s tests/semantic: 2573 OK

No game files. AI-assisted.

@UNYTIX

UNYTIX commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Read the pass and ran it end to end on an AMD GPU (Windows 11, RX 7800 XT, gfx1101, driver 32.0.32029.2010, Vulkan 1.4.363, spirv-val 2026.x).

Local results

  • test_addr64_lowering.py → Ran 6 tests ... OK.
  • runtime/test/shaders/cs_buf_tail.asm (address adds, a V# NUM_RECORDS compare, buffer device addresses) translated with the pass, header-only FSSM, straight through tools/rdna2spirv.py:
caps: Shader, PhysicalStorageBufferAddresses        (no Int64)
Int64 mentions in the module: 0 | OpConvertUToPtr: 0 | OpBitcast (uvec2 -> ptr): 20
spirv-val --target-env vulkan1.2: ok
vk_compute_test ... 1 dump -> 0x00000000 0x5eed000c 0x5eed0008 0x5eed000c 0x00000000 0x00000000 0x5eed0010 0x00000000

That is exactly check.py's BOUNDS expectation for the shader, and --int64-addresses gives the same eight words (with OpCapability Int64 and 20 OpConvertUToPtr). So on RDNA3 the carry into the high word, the high-word-first compare and the uvec2 bitcast all behave; spirv-val accepts the bitcast for Vulkan 1.2 as well.

Two things I would want before this merges

  1. How much of the corpus still gets Int64? The motivation is Intel (shaderInt64 false, bufferDeviceAddress true), but the pass bails on any other 64-bit use and there is no count of how often that happens. The project's rule is counts over the whole corpus, not a sample: grep -l "OpCapability Int64" over the 26,503 translated modules, with index.json's shaderInt64 as the cross-check, would say whether this fixes most Intel shaders or a minority. cs_global_neg_offset.asm is a small example of the gap:
caps: Shader, Int64, PhysicalStorageBufferAddresses   (pass kept the old form)
413 lines mention %ulong/%long, starting with %long = OpTypeInt 64 1
  1. The signed %long path. That shader's negative offsets sign-extend through %long, and the pass does not handle OpSConvert / OpShiftRightArithmetic (by design, per the header). If those exist only to sign-extend the 12-bit global_* offset, handling OpSConvert %long %int would cover them and make the negative-offset test exercise the lowered form too — worth a look, because "negative offset in a global access" is not a rare shader shape. If it stays unsupported, the row should say that shaders with signed 64-bit address arithmetic still declare shaderInt64, so Intel still fails on them.

Nit: _A64_CMP maps only the unsigned compares; a signed address compare falls into the "any other mention" bail rather than being lowered wrongly, which is the right default — just noting it so it stays deliberate.

@richardsenra

Copy link
Copy Markdown
Contributor

Supplementary CPU/type review at c550d5334f66b4af234b45fb0e9a8b27170650cc, followed by real SPIRV-Tools 2026.4 validation (vulkan1.2). AI-assisted.

  • 10/10 CLI-generated modules validate: five hand-written RDNA2 programs, default and --int64-addresses. The scalar-load/store address cases drop Int64 by default; dynamic-V# s_buffer_load, signed-offset global_load, and the data-shift case retain it and shaderInt64 metadata. BDA stays where needed.
  • 6/6 additional modules validate: cs_bounds and cs_barrier_loop in structured, forced --dispatch-loop, and forced dispatch + --int64-addresses modes. The lowered modes contain no Int64; opt-out retains it. This is static validity coverage, not a new GPU claim.
  • Eligible hand-written SPIR-V cases validate after conversion; a valid 64-bit OpPhi case is preserved byte-for-byte. The deliberately out-of-contract preamble/type variants produce validator-rejected output or an exception; I have not found a route in the current generator that emits those inputs.

Two small review points would improve the final contribution:

  1. Interpreter type guard (tests/semantic/spirv_mini_interp.py:715): the pointer-bitcast branch checks runtime tuple values, not their declared source type. I constructed a well-typed u64vec2 using OpUConvert for both uint32 components, with Int64 capability present. Its 128-bit-to-PSB-pointer bitcast is rejected by spirv-val, but the interpreter runs it and reads the expected word because it masks each component to uint32. The normal generated uvec2 module validates. Checking id_type for a two-component 32-bit integer vector would make this test oracle reject the invalid form. This is a confirmed test-oracle limitation; no matching generated-shader failure was found.
  2. Wording: docs/design.md:228 says right shifts and narrowing retain Int64, but the pass supports logical shift by 32 and low-word narrowing. Its opening "Every PhysicalStorageBuffer address..." and the analogous comment at rdna2spirv.py:10498 could describe the handled idiom instead: dynamic V# scalar-buffer loads and signed-offset global accesses can remain ineligible. The startup warning at d3d12_vulkan_device.cpp:6648 also still says all translated shaders declare Int64, which these successful modules no longer do.

The absence of --int64-addresses forwarding in make_game.py is already acknowledged in the PR body; I am not treating that as a new defect. These are synthetic test-suite observations, not retail-corpus coverage or a global approval.

Minimal reproduction of the interpreter source-type gap

Run from the repository root, with SPIRV-Tools on PATH. This uses the existing test fixture to make the original input, then gives the vector proper uint64 components so the validation error is specifically the pointer bitcast rather than mismatched constructor types.

import sys
from pathlib import Path
import subprocess

sys.path[:0] = [str(Path("tools").resolve()), str(Path("tests/semantic").resolve())]
import test_addr64_lowering as T

heap, base = 0x1_FFFF_FFF0, 0x20
text = T.translate("cs_probe", T.load_program(base))
original = text
text = text.replace("OpCapability Shader", "OpCapability Shader\nOpCapability Int64", 1)
uint_line = next(x for x in text.splitlines() if x.strip() == "%uint = OpTypeInt 32 0")
text = text.replace(uint_line, uint_line +
                    "\n%probe_ul = OpTypeInt 64 0\n%probe_v2ul = OpTypeVector %probe_ul 2", 1)
for i, line in enumerate(x for x in original.splitlines()
                         if "OpCompositeConstruct" in x and "%a64_" in x):
    w = line.split()
    text = text.replace(line,
        f"%probe_l{i} = OpUConvert %probe_ul {w[4]}\n"
        f"%probe_h{i} = OpUConvert %probe_ul {w[5]}\n"
        f"{w[0]} = OpCompositeConstruct %probe_v2ul %probe_l{i} %probe_h{i}")
scratch = Path("runtime/build/review-pointer-width")
scratch.mkdir(parents=True, exist_ok=True)
asm, spv = scratch / "invalid-width.spvasm", scratch / "invalid-width.spv"
asm.write_text(text, encoding="utf-8", newline="\n")
subprocess.run(["spirv-as", "--target-env", "vulkan1.2", str(asm), "-o", str(spv)], check=True)
assert subprocess.run(["spirv-val", "--target-env", "vulkan1.2", str(spv)]).returncode != 0
memory = {(heap + base) & T.M64: T.MAGIC}
assert T.run(text, heap, memory).get(heap & T.M64) == T.MAGIC
print("validator rejects pointer width; interpreter accepts it")

@carlcdx

carlcdx commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Tested c550d533 on Windows 11 (26300, Windows SDK 10.0.26100.0, Vulkan SDK 1.4.363.0, RelWithDebInfo, VK_LOADER_LAYERS_DISABLE=~implicit~): pass on AMD RDNA 4 and RDNA 2 Windows drivers, 0 regressions and 0 validation errors.

GPUs:

  • AMD Radeon RX 9070 XT (RDNA 4, Windows driver, subgroup 32..64)
  • AMD Radeon(TM) Graphics (Ryzen 7 9800X3D RDNA 2 iGPU, Windows driver, subgroup 32..64)

Unit & SPIR-V capability checks:

  • python -m unittest tests/semantic/test_addr64_lowering.py -v: 6/6 OK.
  • spirv-dis check on the 193 standalone .spv files built by run_gpu_tests.py: 117 declare PhysicalStorageBufferAddresses; 103 have no OpCapability Int64, and 14 retain it (cs_buf_typed, cs_bvh, cs_bvh32, cs_fmt_1010102, cs_fmt_sint32, cs_fmt_xy_xyz, cs_global_neg_offset, cs_oob_tail, cs_smem_soffset_imm, cs_w32_salu64, ps_fnan_fract, ps_fnan_med3, ps_vcc_x2, ps_vcmpx_forms).
  • spirv-dis check on the 30 generated M1.5/M2/M3/M4 .spv files under runtime/build: 0/30 declare OpCapability Int64.

Standalone GPU suite (scripts/run_gpu_tests.py, AMD Radeon RX 9070 XT):

  • Native wave64: 190/190 translated & spirv-val clean → 170/185 passed, 15 skipped, 0 failed.
  • LEONIDA_W64_EMULATE=1: 190/190 translated & spirv-val clean → 170/185 passed, 15 skipped, 0 failed.

Rebuilt D3D12 translated-shader CTest suite (LEONIDA_VK_VALIDATION=1):
ctest -R "^(d3d12_translated_draw|d3d12_m2_textured|d3d12_m2_formats|d3d12_m3_frame|d3d12_m3_first_pass|d3d12_m4_compute|d3d12_buffer_uav)$" (all re-translated shaders passed spirv-val):

  • AMD Radeon RX 9070 XT: 7/7 passed (2.42s, validation on, 0 validation errors — M2 formats 12/12 cases, M3 3555 exact samples / error 0, M4 1924/1924 words, buffer UAV 21394/21394 values).
  • AMD Radeon(TM) Graphics (RDNA 2 iGPU): 7/7 passed (1.81s, validation on, 0 validation errors, identical exact counts).

Not tested here: a device lacking shaderInt64 (both AMD adapters advertise it; already verified on Intel by @richardsenra and @BrossGamer), or the retail shader corpus.

Synthetic tests only; no game files. AI-assisted.

@Ingenioeren

Copy link
Copy Markdown

128-byte SwiftShader integration check of c550d533 on Windows 11 with Vulkan validation 1.4.341.1. I combined the translator changes from this PR with #2046 (8d89bfa), the tail-block compute harness from #2048 (0ec464b), and the compute capability check from #2647 (f834525). This was a local stack on 49475796, with the translator CLI context and harness include list reconciled.

  • SwiftShader with --pc-tail-ubo: cs_workgroup_yz matched all 24 dispatch origins and the combined histogram, cs_buf_tail matched all eight buffer words, and cs_user_sgprs matched all four input words. Their SPIR-V and index metadata omit Int64/shaderInt64. The signed-offset control cs_global_neg_offset retains Int64 and cleanly returns 77.
  • Repeating the translation with --int64-addresses restored the capability in all four modules. SwiftShader then cleanly returned 77 for all four, using the same harness and 128-byte layout.
  • RX 6750 XT matched all four cases in 144-byte and 128-byte lowered modes and in the 128-byte opt-out control. All 12 generated modules passed spirv-val, the six targeted semantic tests passed, and no run emitted Vulkan validation errors.

This verifies the combination on a software device with both constraints. It covers the standalone compute path and uses only synthetic fixtures. AI-assisted.

@umnitus

umnitus commented Nov 22, 2026

Copy link
Copy Markdown

Independent check at c550d53 on Windows 11, RTX 3060 12 GB, driver 621.14. All six targeted runtime checks passed: translated draw, M2 textured, M2 formats, M3 frame, M3 first pass and M4 compute.

run_gpu_tests.py validated all 190 modules in both modes. Native wave32: 139 passed, 46 skipped, 0 failed. Wave64 emulation: 170 passed, 15 skipped, 0 failed. The ms_w64x_ballot case reported failing on Arc A770 matched all 4,096 pixels here in wave64 emulation.

AI-assisted testing and write-up.

@zneel

zneel commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Tested c550d533 on AMD Radeon RX 9070 XT (RDNA4, subgroup 32..64), AMD 26.11.2, Windows 11 Pro 10.0.26300, AMD Ryzen 7 9800X3D CPU (64 GB RAM), Python 3.12.10. GPU: pass. One CPU test fails.

Runtime and test programs built from this head (MSVC 14.51, Ninja, RelWithDebInfo), native Windows llvm-mc 21.1.8, Vulkan SDK 1.4.363.0. No game files.

run result
run_gpu_tests.py (whole suite, native wave64) 170/185, 15 skipped, 0 failed (main 49475796: 170/185)
same with LEONIDA_W64_EMULATE=1 170/185, 15 skipped, 0 failed
unittest discover -s tests/semantic -p test_addr64_lowering.py 6 OK
pytest tests/test_translate.py 1 failed, 525 passed, 2 skipped

On the GPU side, 103 of the 193 modules differ from main's, the same count you give for memory-touching shaders without Int64. All of them run exactly as before, native and emulated. That's a first RDNA4 data point for the lowered form.

The failure is test_cs_store_packed_atomic_pointers (tests/test_translate.py:213), from 3a9e32e on main. It passes on 49475796 and fails on this head:

assert defs[base].startswith("OpConvertUToPtr %_ptr_PSB_arr ")
AssertionError: ... 'OpBitcast %_ptr_PSB_arr %a64_49v'

That looks like the test pinning the old address form. The atomics still go through the dword array element as it intends, so it probably needs to accept the OpBitcast of the uvec2 pair, or run with --int64-addresses. I didn't run ctest here.

AI-assisted (Claude Code); I checked the results.

…eck it in the interpreter, docs wording

- tests/test_translate.py test_cs_store_packed_atomic_pointers pinned the
  OpConvertUToPtr form of the atomics' array pointer; it is the uvec2
  OpBitcast since lower_addr64 (OpConvertUToPtr with --int64-addresses),
  so it accepts both (reported by @zneel on ItsNotRexed#2463).
- spirv_mini_interp's pointer bitcast checks the source's declared type
  (a 2-component 32-bit integer vector), not only the runtime tuple, so
  an invalid 64-bit pair cannot pass the test oracle (@richardsenra).
- docs/design.md: the contract row describes the idiom the pass handles
  (narrowing and the logical shift by 32 included) and what keeps Int64
  (@richardsenra).

pytest tests/test_translate.py: 526 passed, 2 skipped. tests/semantic:
2,573 OK.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@c4k3ss

c4k3ss commented Nov 22, 2026

Copy link
Copy Markdown
Author

Pushed 8b388002 with the review points so far:

  • @zneel: test_cs_store_packed_atomic_pointers pinned the OpConvertUToPtr form; it now accepts the uvec2 OpBitcast (the lowered form) as well as OpConvertUToPtr (--int64-addresses). pytest tests/test_translate.py: 526 passed, 2 skipped. Thanks for running the pytest file, it isn't in the plain python -I loop here.
  • @richardsenra: (1) spirv_mini_interp's pointer bitcast now checks the source's declared type, a 2-component 32-bit integer vector, before the runtime tuple, so the u64vec2 form you built is rejected. (2) docs/design.md row rewritten to describe the handled idiom (narrowing and the logical shift by 32 included) and what keeps Int64 (signed widening of negative global_* offsets, dynamic-V# scalar-buffer loads, 64-bit data ops), with the hardware coverage from this thread.
  • @UNYTIX: (1) the corpus count needs the package, which I don't have; if someone with it can run grep -L 'OpCapability Int64' over the translated modules at this head and post the two numbers (and index.json's shaderInt64 count as the cross-check), that settles the Intel question. (2) The signed path (OpSConvert %long, OpBitcast between the 64-bit types, OpShiftRightArithmetic by 32) is a reasonable extension: sign-extend as (x, x >> 31), shift as (high, high >> 31). I'll do it as the next commit with a negative-offset case in test_addr64_lowering.py and GPU runs, later tonight.

tests/semantic: 2,573 OK at this head. AI-assisted.

@JRamos1993

Copy link
Copy Markdown
Contributor

Tested c550d53 on an RTX 5090 (driver 616.92), Windows 11, Vulkan SDK 1.4.363. The GPU test programs were built from the same tree:

  • scripts/run_gpu_tests.py: 139/185 passed, 46 skipped, 0 failed. main 4947579 gives 139/185, 46 skipped, 0 failed. All 190 test shaders translate and pass spirv-val.
  • tests/semantic/test_addr64_lowering.py: ran 6 tests in 0.514s; OK.

AI-assisted (Claude Code).

…s, arithmetic shift by 32)

A global_* access with a negative instruction offset sign-extends it
through a 64-bit signed integer (OpSConvert %long, OpBitcast %ulong)
before the add, and a few paths shift a 64-bit value right
arithmetically by 32. The pass now lowers those as well: the
sign-extended dword is (value, value >> 31 arithmetic), the shift by 32
is (high, high >> 31), and a bitcast between the 64-bit integer types is
the same word pair. The rewrite's 32-bit constants are declared once the
body is done (they are made while it is rewritten). Review point from
@UNYTIX on ItsNotRexed#2463.

tests/semantic/test_addr64_lowering.py: three global_load cases with
negative and positive offsets read the same word in both forms, and the
lowered module has no Int64 or %long. cs_global_neg_offset now runs
without Int64 (RDNA2 gfx1036 iGPU: 170/185, 190/190 spirv-val); 13 of
the 117 memory-touching test shaders keep Int64 (was 14). tests/semantic
2,573 OK; pytest tests/test_translate.py 526 passed.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@c4k3ss

c4k3ss commented Nov 22, 2026

Copy link
Copy Markdown
Author

Pushed 65e64c2a: the signed-offset idiom is lowered too (@UNYTIX's point 2). OpSConvert %long of a dword becomes (value, value >> 31 arithmetic), the arithmetic shift by 32 (high, high >> 31), and a bitcast between the 64-bit integer types is the same word pair. cs_global_neg_offset now carries no Int64; 13 of the 117 memory-touching test shaders keep it (64-bit multiplies and shifts by other amounts).

Tested at this head: test_addr64_lowering.py 7/7 (three new global_load cases with offsets -4, -2048 and 2044 read the same word in both forms); tests/semantic 2,574 OK; pytest tests/test_translate.py 526 passed; run_gpu_tests.py 190/190 spirv-val, RTX 5070 Ti 139/185 native and 170/185 emulated, RDNA2 gfx1036 iGPU 170/185, 0 failed everywhere, same counts as before. The PR description is updated. AI-assisted.

@davidesidoti

Copy link
Copy Markdown

Tested 8b38800 on AMD Radeon RX 9070 XT (RDNA4), Adrenalin 26.11.2 (LLPC, Vulkan 1.4.359), Windows 11 build 26300, LLVM 21.1.8, SPIRV-Tools v2026.4.

  • PR head alone: python -I -m unittest discover -s tests/semantic: 2,573 OK (3 skipped).
  • Merged locally onto current main (ec8ec4c, 593 commits ahead of the PR base; merges without conflicts):
    • scripts/run_gpu_tests.py: 194 translated, 194 pass spirv-val; 175/189 passed, 14 skipped, the same outcome per test as main. OpCapability Int64 drops from 120 to 17 test modules.
    • tests/semantic: 1 failure, 23 errors (main alone: 4,137 OK):

Needs a rebase that teaches both tests the pair form (or pins --int64-addresses there).

(AI-assisted test run.)

@richardsenra

Copy link
Copy Markdown
Contributor

Re-tested 65e64c2aa2346c24c2affd42aa7bbcd538e5c3ae on Intel UHD 31.0.101.4146 (no shaderInt64) and RTX 3050 6GB Laptop 617.14. AI-assisted.

  • Confirmed the interpreter fix: the earlier well-typed u64vec2-to-PSB-pointer reproduction now raises UnsupportedConstruct for its declared source type. The invalid module is no longer accepted by the semantic interpreter.
  • test_addr64_lowering.py: 7/7 pass. pytest tests/test_translate.py: 526 pass, 2 skip, with real SPIRV-Tools on PATH.
  • Rebuilt/re-translated the layer fixtures: 15/15 module entries spirv-val-valid. The same six targeted layer CTests pass 6/6 on both GPUs, validation including synchronization enabled, zero validation warnings/errors. Full M3 still matches 73,728 pixel comparisons and 3,555 exact samples; M4 matches 1,924 words.
  • New signed-offset GPU check: translated the existing hand-written cs_global_neg_offset fixture at this head, default and opt-out; both pass spirv-val. The default module and metadata have no Int64/shaderInt64; BDA remains. Using a private validation-only runner based on vk_test_device.h (BDA requested, unchanged 144-byte user-data layout, 40 workgroups), the entire 0x2800-byte heap matches on Intel and NVIDIA: 2,560/2,560 words, zero validation errors. This checks the eight expected load/store outputs, all seeded locations and the untouched remainder. The opt-out form matches on NVIDIA and cleanly skips (77) on Intel, where it still needs Int64.

The signed-offset results are from the actual freshly translated fixture, with no shader/oracle weakening. Production source is unchanged by this verification. This refresh covers the checks above; I did not rerun the entire standalone GPU suite or the retail corpus at the new head. The suite/helper findings in the earlier review are separate from these positive layer results.

@edubox

edubox commented Nov 22, 2026

Copy link
Copy Markdown

Tested 65e64c2a on an NVIDIA GeForce RTX 4080 SUPER (Ada), driver 620.70.06, Vulkan 1.4.357, Linux x86-64: pass.
Tested 65e64c2a on an AMD Radeon 610M iGPU (RDNA2, gfx1036), RADV Mesa 26.2.6, Vulkan 1.4.354, same host: pass.

Since this changes the default address lowering, the question is whether the modules it now emits still run. Full run_gpu_tests.py, per-test compared against main 49475796:

Device Result vs main
RTX 4080 SUPER 139/185 passed, 46 skipped, 0 failed identical line by line
Radeon 610M (RADV) 170/185 passed, 15 skipped, 0 failed identical line by line

Every buffer, global, texture and descriptor fixture gives the same words with the 32-bit-pair idiom as with Int64. (The PR is Python-only and its base is our main, so the harness binaries are the same build.)

Real corpus, shard 0/12 of my own copy (--shard 0/12 --wave64-emulate, LLVM 23.1.5): 2,209 shaders, 2,209 translated, 2,209 pass spirv-val — the same set and the same count as main's shard 0. What changes is what the modules require: entries declaring Int64/shaderInt64 in the index drop from 2,151 to 2,069 of 2,209 (82 shaders no longer need Int64). On the first 250 shaders it goes 244 → 222. Total module size is unchanged (83.4 MB for those 250 in both runs).

--int64-addresses still works as the opt-out: 250/250 translate with it.

Tests: tests/semantic 2,574 OK (incl. test_addr64_lowering 7 OK), tests/test_translate.py 526 passed / 2 skipped under pytest (identical on main).

Limit, stated plainly: both devices here have shaderInt64, so this does not exercise the reason for the change (Intel); it shows the new default is correct on two drivers and that it does drop the capability where the idiom was the only 64-bit use.

AI-assisted.

@MiguelMatMar

Copy link
Copy Markdown

Tested 65e64c2 on RTX 4080 SUPER (Ada, subgroup 32), NVIDIA 621.24 (Vulkan 1.4.357), Windows 11 Pro build 26300; MSVC 14.44, Vulkan SDK 1.4.363.0, llvm-mc 21.1.8 built with scripts/build_llvm_mc.ps1, Python 3.14: pass

  • Runtime built from this PR (scripts/build_runtime.ps1). python -I scripts/run_gpu_tests.py: 139/185 passed, 46 skipped, 0 failed. 190/190 translated, 190 pass spirv-val. Same as the base 49475796 on this GPU.
  • LEONIDA_W64_EMULATE=1 ... --filter w64: 25/26 passed, 1 skipped, 0 failed.
  • tests/test_translate.py + tests/semantic/test_addr64_lowering.py (with llvm-mc + SPIRV-Tools on PATH): 533 passed, 2 skipped. python -m unittest discover -s tests/semantic: OK.

(I had also run c550d53 and 8b38800 earlier, with the same results.)

test_buffer_store_format's emission check accepts the uvec2 OpBitcast of
the store's address as well as OpConvertUToPtr (--int64-addresses), and
test_loop_ballot_barrier's local interpreter turns a (low, high) uint
pair bitcast to a PhysicalStorageBuffer pointer into the same "phys"
address OpConvertUToPtr gives (its OpBitcast was the identity, so the
pair reached OpAccessChain as a list). Both were added to main after
this branch's base (reported by @davidesidoti on ItsNotRexed#2463).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@c4k3ss

c4k3ss commented Nov 22, 2026

Copy link
Copy Markdown
Author

@davidesidoti thanks, both were tests main gained after this branch's base. Main 16282101 is now merged into the branch (0c3c791b), and 6e2414e2 teaches the two tests the pair form: test_buffer_store_format's emission check accepts the uvec2 OpBitcast (or OpConvertUToPtr under --int64-addresses), and test_loop_ballot_barrier's local interpreter turns a pair bitcast to a PhysicalStorageBuffer pointer into the same phys address its OpConvertUToPtr case gives (its OpBitcast was the identity, so the pair reached OpAccessChain as a list). The resulting tree is byte-identical to a rebase onto 16282101; I merged rather than force-pushed to keep the reviewed commits in place.

At this head: tests/semantic 4,149 OK (4 skipped), pytest tests/test_translate.py 541 passed, run_gpu_tests.py 194/194 spirv-val, RTX 5070 Ti 143/189 native and 174/189 emulated, RDNA2 gfx1036 iGPU 174/189, 0 failed; 16 of the 120 memory-touching test shaders keep Int64 (your 17 at 8b388002, minus cs_global_neg_offset since the signed-offset commit). AI-assisted.

@edubox

edubox commented Nov 22, 2026

Copy link
Copy Markdown

Re-tested after the rebase, head 6ed0f368 (main 16282101 merged in):

Device run_gpu_tests.py at 6ed0f368 main 16282101 (same build config, same host)
RTX 4080 SUPER, 620.70.06, Linux 143/189 passed, 46 skipped, 0 failed 143/189 passed, 46 skipped, 0 failed
Radeon 610M, RADV Mesa 26.2.6 175/189 passed, 14 skipped, 0 failed 175/189 passed, 14 skipped, 0 failed

Identical line by line, not just in totals, so the new default (32-bit-pair address) still gives the same words as main's Int64 form on all 189 fixtures of the newer corpus on both drivers. tests/semantic at this head: 4,149 tests OK.

The Int64 accounting from my earlier comment was on 65e64c2a and I did not repeat the corpus shard here; nothing in the rebase touches the lowering.

AI-assisted.

@Thatters

Thatters commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Whole-corpus count at 6ed0f368, the numbers @UNYTIX asked for and @c4k3ss asked someone with the package to run. 1.0.2.1 copy, all 26,503 modules, --wave64-emulate (as the shaders stage runs on a 32-wide GPU), PR head vs the main it merged (16282101). RTX 5070 Ti / 621.24 host, Windows 11, SPIRV-Tools from Vulkan SDK 1.4.363.

main 16282101 PR 6ed0f368
translated, pass spirv-val 26,501 / 26,503 26,501 / 26,503 (the #881 pair, as on main)
declare Int64 25,863 24,874
index.json shaderInt64 25,863 24,874 (agrees with the capability, module for module)
no longer need Int64 989 (3.8%): 655 ps, 233 vs, 101 cs

The other 25,511 modules are byte-identical to main's, and total size goes up 0.02%. (One shard of the batch run dropped a pixel shader with a garbled log while the disk was nearly full; rerun alone at the same head, it translates and passes spirv-val. I count it with the 24,874.) This agrees with @edubox's shard 0/12 (82 of 2,151 lowered).

So on the retail corpus this covers few Intel shaders yet. On a 10% sample (shards 0, 10, 20, 30, 40, 50 of 60: 2,651 modules, 2,585 with Int64) I tagged each place lower_addr64 gives up. At 6ed0f368, 2,479 of the 2,486 modules that keep Int64 stop at the same compare: the dynamic-V# scalar-buffer bound (rdna2spirv.py:7904-7906). It builds limit = NUM_RECORDS * stride as OpIMul %ulong of two widened words plus OpSelect %ulong, so the OpUGreaterThanEqual sees a 64-bit value from outside the idiom. Once that is lowered, the next blocker is norm_bits (:1545-1556, the UNORM typed-load quotient): OpIMul %ulong by a 64-bit constant, then two OpShiftRightLogical %ulong by a variable amount. Three more variable 64-bit shifts are at :1481, :6576 and :7049.

Three more rules cover all of it on the sample. I prototyped them on top of 6ed0f368 (diff below):

  • OpIMul where the first factor is a widened word and the second is a widened word or a 64-bit constant: OpUMulExtended gives the 32×32→64 product, plus x * y.hi into the high word when the constant has one.
  • OpSelect %ulong of two pairs: one OpSelect %uint per word.
  • OpShiftLeftLogical / OpShiftRightLogical by a variable amount (a widened word or a constant below 64): 32-bit shifts by amount & 31. The bits that cross words shift by 1 and then by 31 - (amount & 31), so no shift is ever by 32. amount < 32 selects between the two cases.
sample, 2,585 modules with Int64 still need Int64 spirv-val
6ed0f368 2,486 (96%) 2,651 / 2,651
6ed0f368 + the three rules 0 2,651 / 2,651

Edit, the whole corpus with the three rules (same head, same settings): 26,501 / 26,503 translate and pass spirv-val (the #881 pair, as on main), and 0 modules declare Int64 or shaderInt64, from 25,863 on main and 24,874 at 6ed0f368.

Checks of the prototype: tests/semantic at the merged head (4,149 tests) all pass apart from one. The failure is test_a_64bit_data_op_keeps_int64, whose 64-bit data op the new rules now lower, so that negative case would need another construct. The seeded v_lshrrev_b64 / v_lshlrev_b64 tests pass through the new shift rule. Separately, the word formulas match exact 64-bit shifts on 200,000 random value/amount pairs (amounts 0-63). I haven't run the prototype on a GPU.

Prototype diff on 6ed0f368 (67 lines, git apply clean)
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py
index c0248462..7de7002e 100644
--- a/tools/rdna2spirv.py
+++ b/tools/rdna2spirv.py
@@ -10886,3 +10886,3 @@ def assemble(gen):
 _A64_PRODUCERS = ("OpUConvert", "OpShiftLeftLogical", "OpShiftRightLogical", "OpBitwiseOr", "OpBitwiseAnd", "OpIAdd",
-                  "OpISub", "OpSConvert", "OpBitcast", "OpShiftRightArithmetic")
+                  "OpISub", "OpSConvert", "OpBitcast", "OpShiftRightArithmetic", "OpIMul", "OpSelect")
 # 64-bit compares of two addresses: high words first, then the low words.
@@ -10931,4 +10931,9 @@ def lower_addr64(text):
               a[0] in v64 and c64.get(a[1]) == 32) or \
+             (op in ("OpShiftLeftLogical", "OpShiftRightLogical") and len(a) == 2 and a[0] in v64 and
+              (c64.get(a[1], 64) < 64 or prod.get(a[1], ("",))[0] == "OpUConvert")) or \
              (op in ("OpBitwiseOr", "OpBitwiseAnd", "OpIAdd", "OpISub") and len(a) == 2 and a[0] in v64 and
-              a[1] in v64)
+              a[1] in v64) or \
+             (op == "OpIMul" and len(a) == 2 and prod.get(a[0], ("",))[0] == "OpUConvert" and
+              (prod.get(a[1], ("",))[0] == "OpUConvert" or a[1] in c64)) or \
+             (op == "OpSelect" and len(a) == 3 and a[0] not in v64 and a[1] in v64 and a[2] in v64)
         if not ok:
@@ -10961,2 +10966,46 @@ def lower_addr64(text):
                 pair[res] = pair[a[0]]
+            elif op == "OpIMul":     # x is a widened word (high 0): x * y = x * y.lo (32x32 -> 64) + (x * y.hi) << 32
+                n += 1
+                p = f"%a64_{n}"
+                (xl, _), (yl, yh) = pair[a[0]], pair[a[1]]
+                out += [f"         {p}m = OpUMulExtended %umul {xl} {yl}",
+                        f"         {p}l = OpCompositeExtract %uint {p}m 0",
+                        f"         {p}h = OpCompositeExtract %uint {p}m 1"]
+                if yh != const(0):
+                    out += [f"         {p}x = OpIMul %uint {xl} {yh}", f"         {p}g = OpIAdd %uint {p}h {p}x"]
+                    pair[res] = (p + "l", p + "g")
+                else:
+                    pair[res] = (p + "l", p + "h")
+            elif op == "OpSelect":
+                n += 1
+                p = f"%a64_{n}"
+                (xl, xh), (yl, yh) = pair[a[1]], pair[a[2]]
+                out += [f"         {p}l = OpSelect %uint {a[0]} {xl} {yl}", f"         {p}h = OpSelect %uint {a[0]} {xh} {yh}"]
+                pair[res] = (p + "l", p + "h")
+            elif op in ("OpShiftLeftLogical", "OpShiftRightLogical") and c64.get(a[1]) != 32:
+                # by a variable (or other constant) amount 0..63: 32-bit shifts by amount & 31; the bits that cross
+                # words shift in two steps (1, then 31 - amount & 31) so no shift is by 32; a select handles >= 32
+                n += 1
+                p = f"%a64_{n}"
+                (xl, xh), sa = pair[a[0]], pair[a[1]][0]
+                out += [f"         {p}k = OpBitwiseAnd %uint {sa} {const(31)}",
+                        f"         {p}t = OpULessThan %bool {sa} {const(32)}",
+                        f"         {p}i = OpISub %uint {const(31)} {p}k"]
+                if op == "OpShiftRightLogical":
+                    out += [f"         {p}a = OpShiftLeftLogical %uint {xh} {const(1)}",
+                            f"         {p}b = OpShiftLeftLogical %uint {p}a {p}i",
+                            f"         {p}c = OpShiftRightLogical %uint {xl} {p}k",
+                            f"         {p}d = OpBitwiseOr %uint {p}c {p}b",
+                            f"         {p}e = OpShiftRightLogical %uint {xh} {p}k",
+                            f"         {p}l = OpSelect %uint {p}t {p}d {p}e",
+                            f"         {p}h = OpSelect %uint {p}t {p}e {const(0)}"]
+                else:
+                    out += [f"         {p}a = OpShiftRightLogical %uint {xl} {const(1)}",
+                            f"         {p}b = OpShiftRightLogical %uint {p}a {p}i",
+                            f"         {p}c = OpShiftLeftLogical %uint {xh} {p}k",
+                            f"         {p}d = OpBitwiseOr %uint {p}c {p}b",
+                            f"         {p}e = OpShiftLeftLogical %uint {xl} {p}k",
+                            f"         {p}h = OpSelect %uint {p}t {p}d {p}e",
+                            f"         {p}l = OpSelect %uint {p}t {p}e {const(0)}"]
+                pair[res] = (p + "l", p + "h")
             elif op == "OpShiftLeftLogical":

Counts only, no shader names or contents. AI-assisted (Claude Code), run on the hardware above.

@c4k3ss

c4k3ss commented Nov 22, 2026

Copy link
Copy Markdown
Author

Round 41 landed a flag on the same CLI line (global ... PC_TAIL_UBO), so main f847748c is merged in as 3de4f0fb with both declared; nothing else conflicted and the lowering is untouched.

At this head: tests/semantic 7,329 OK (4 skipped, 1 expected failure, as on main), pytest tests/test_translate.py 562 passed, test_addr64_lowering.py 7/7, run_gpu_tests.py on the RDNA2 gfx1036 iGPU: 204/204 spirv-val, 183/199 passed, 15 skipped, 1 failed. That one, ps_array_resinfo, fails identically with unmodified main f847748c on both GPUs here, because my vk_texture_test binary predates the array-view fixture #1606 added for it (the helper changed in #2048 / #2313); a rebuilt helper is needed, not a translator change. AI-assisted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.