"""RDNA2 (gfx10) shader -> SPIR-V assembly. Model: one SPIR-V invocation runs one lane. VGPRs and SGPRs are Function-scope uint arrays; float ops bitcast, so register contents keep exact bit patterns. EXEC is a per-invocation active flag, and a lane mask keeps only this lane's bit; the few instructions that read a whole mask (s_bcnt1, s_ff1, v_mbcnt, ...) collect the other lanes with subgroup operations (lane_masks.py, and wave64_halves.py for wave64). Control flow is structured by cfg_structure.py, with a loop around a switch where it can't be (or for every shader with --dispatch-loop). Anything not modelled raises Unsupported and is reported, never guessed. The contract table in docs/design.md ("Translator status and runtime contract") lists what each instruction family does and how it was confirmed. Vertex inputs: v0 = VertexIndex - BaseVertex and v3 = InstanceIndex - BaseInstance (the hardware's ids are zero-based). Usage (needs spirv-val on PATH, from the Vulkan SDK or spirv-tools; spirv-as too unless --assembler python): python3 -I rdna2spirv.py --out DIR [--limit N] [--shard i/n] Writes .spvasm for each translated shader and .spv only for validated modules. Prints coverage and validation results. """ import argparse import bisect import hashlib import math import os import re import signal import struct import subprocess import sys import tempfile import time import zlib from collections import Counter, defaultdict from pathlib import Path sys.path.insert(0, os.path.dirname(__file__)) from report_paths import path_key, same_report_path # noqa: E402 from shader_ir import HDR, parse_file # noqa: E402 from replace_retry import replace as replace_retry # noqa: E402 from file_mode import published_mode # noqa: E402 import cfg_structure # noqa: E402 import descriptor_sources # noqa: E402 import fssm_header # noqa: E402 import fssm_unpack # noqa: E402 import lane_masks # noqa: E402 import shader_meta as _shader_meta # noqa: E402 import wave64_emulate_opt # noqa: E402 import wave64_halves # noqa: E402 import spirv_loop_guard # noqa: E402 STRUCTURED = True # False (--dispatch-loop): every shader with branches as one loop around a switch # Deeper structured trees are emitted in the flat dispatch-loop form instead (--max-structured-depth, 0 = never). # `spirv-val`'s selection/loop checking cost grows with the nesting depth, and before cfg_structure hoisted tails # (#1904) the 1.0.2.1 corpus nested up to 118 deep, where the flat form validates 2.3x (depth 50-64) to 10x (118) # faster (SHADER-299). Since #1904 the corpus's deepest tree is 29 and the flat form saves only 12% of `spirv-val` # time on the modules deeper than 16, while NVIDIA compiles it 1.7-2x slower (SHADER-427). The bound sits above # the corpus, as a guard for depths where validation really grows. Both forms are equivalent; only the routing # differs. docs/design.md "Control flow" has the numbers. MAX_STRUCTURED_DEPTH = 64 LOOP_LIMIT = spirv_loop_guard.DEFAULT_LIMIT DESCRIPTOR_HASHES = ("fnv1a", "fnv1a_fmix32") DESCRIPTOR_HASH = "fnv1a" # --descriptor-table: how the table's entries are read. "plain" is what every module read until the T# dimension # became part of the contract: key[8], index, and a pad word nothing reads. "tagged" puts the descriptor's kind in # that word: one bit per array (ImageDimension) the index is bound in, sampled at bits 0..5 and storage at bits # 8..11, so a shader can tell whether the index belongs to the array its instruction reads. A plain library keeps # the old modules' code byte for byte (docs/design.md, "Images and samplers (T# dimension)"). DESCRIPTOR_TABLES = ("plain", "tagged") DESCRIPTOR_TABLE = "tagged" # The kind word's bit positions, shared with runtime/src/descriptor_table.h. DESC_SAMPLED_BIT = 0 # bit i: the index is bound in dimension i's sampled array DESC_STORAGE_BIT = 8 # bit 8 + i: ... in its storage arrays (dimensions 0..4 have them) # The bindless index in the T# (docs/design.md, "Bindless index in the T#"): the layer writes dword 6 of every T# in # the heaps it keeps (runtime/src/gfx10_descriptors.h, tsharp_index_word) as TAG << 28 | storage kind << 23 | # sampled kind << 16 | index, the kind being the table's kind bits 8..12 and 0..6. A module reads it, without the # hash table, where tools/descriptor_sources.py shows the T#'s dword 6 was loaded from such a heap, and records # TSHARP_INDEX in its meta, which tells the runtime to write the word. TSHARP_INDEX = "dword6" TSHARP_INDEX_DWORD = 6 TSHARP_INDEX_TAG = 0xA WAVE64_EMULATE = False # --wave64-emulate: wave64 compute/mesh shaders exact on any subgroup size (Gen.x_round) # --wave64-emulate: use wave64_emulate_opt's inline structured form when it does not put an exchange barrier # under control flow only some invocations take (translate() re-runs this module without it when it does). WAVE64_PLAN = True # --max-shared-memory: a cap on a compute shader's Workgroup variables, LDS plus %x_buf (SHADER-309, #1721). The # default is the hard cap: 64 KiB, RDNA2's LDS per workgroup and the largest maxComputeSharedMemorySize drivers # report (RADV, NVIDIA). It is not the device limit: the AMD Windows (RDNA4) and Intel drivers report 32768, the # Vulkan minimum is 16384. The translator runs offline, so it records the exact total as lds_bytes in index.json and # the runtime compares that with the device's limit before it creates the pipeline. spirv-val checks neither. MAX_SHARED_BYTES = 65536 WAVE64_GRAPHICS = "warn" # --wave64-graphics: tier C wave64 VS/PS/GS (not exact on 32-wide subgroups): warn | error | off W64G_COUNTS = Counter() # tiers of the wave64 VS/PS/GS translated so far, for the summary line # --bary-fallback: raw barycentric reads come from an ordinary perspective-interpolated vec3 input (the location is # in the metadata as "bary_fallback_input") instead of BuiltIn BaryCoordKHR, for devices without # VK_KHR_fragment_shader_barycentric. Whatever feeds the stage before the PS (a pass-through geometry shader) writes # (1,0,0), (0,1,0), (0,0,1) at the triangle's three vertices; interpolating those gives the perspective-correct # barycentrics, so .y/.z are AMD's i/j as with BaryCoordKHR. BARY_FALLBACK = False # --integer-dot-fallback: the 4x8-bit dot products (v_dot4_i32_i8, v_dot4c_i32_i8, v_dot4_u32_u8, v_dot4c_u32_u8) are # four extracts, multiplies and adds, as before, instead of SPV_KHR_integer_dot_product's OpSDot / OpUDot and their # saturating-accumulate forms (Gen.packed_dot4). For devices without shaderIntegerDotProduct (a Vulkan 1.2 device # without VK_KHR_shader_integer_dot_product); Vulkan 1.3 requires the feature. docs/design.md, "Signed-byte dot # products". INTEGER_DOT_FALLBACK = False SHADER_CLOCK = False # --int64-addresses: keep 64-bit integer address arithmetic (Int64) instead of lowering it to 32-bit pairs; see # lower_addr64. ADDR_PAIR = True FMA_KHR = False # --fma khr: fused multiply-adds are OpFmaKHR (SPV_KHR_fma, VK_KHR_shader_fma), not GLSL Fma FMA_EXACT = False # --fma exact: fused multiply-adds are emulated from single-rounded f32 ops (Gen.fma_exact) # --texel-offset-fallback: image_sample*_o without VK_KHR_maintenance8. The run-time texel offset is folded into the # coordinate (coordinate + offset / size of the sampled mip level) instead of the SPIR-V Offset operand, which needs # maintenance8 outside gather. Implicit-LOD samples become Grad samples with the derivatives of the original # coordinate, so a per-pixel offset doesn't change the LOD. Gathers keep their Offset (shaderImageGatherExtended). TEXEL_OFFSET_FALLBACK = False # --explicit-lod-bias: MoltenVK 1.4.2 on an Apple M3 drops VkSamplerCreateInfo::mipLodBias (ps_ssharp: neither # image_sample_lz with a +1 S# LOD_BIAS nor the derivative-LOD image_sample with -1 moves a level); on an Apple M5 Pro # the same MoltenVK applies it, so tools/lod_bias_probe.py measures it per device. With this flag the shader applies the # S#'s signed 5.8 LOD_BIAS (word 2 [13:0]) itself: added to the Lod of explicit-LOD samples and to the bias of # _b / _c_b, as a Bias operand on implicit samples, and as a 2^bias scale of Grad derivatives (lambda = log2 of # their length). The sampler still clamps the result to MIN_LOD..MAX_LOD. Only for a driver that drops the # sampler's bias: elsewhere it would count twice. EXPLICIT_LOD_BIAS = False FLOAT_CONTROLS = True # False (--no-float-controls): no SignedZeroInfNanPreserve, for drivers without the property FTZ32 = True # False (--no-ftz32): keep software flush_f32() instead of DenormFlushToZero 32 LDS_BOUNDS = True # False (--no-lds-bounds): restore wrapped power-of-two LDS array when constant offsets stay in range EARLY_DEPTH = True # False (--no-early-depth): omit EarlyFragmentTests even when DB_SHADER_CONTROL bit 12 is set # --mesh-compute: mesh shaders become compute shaders (same workgroup size and code) for devices without # VK_EXT_mesh_shader. Instead of SetMeshOutputs and the mesh outputs, the epilogue writes the vertex and primitive # counts, each lane's vertex and each lane's primitive into this workgroup's slot of a buffer whose device address is # in push-constant dwords 36..37 (the block grows from 144 to 152 bytes). The slot layout is mesh_compute_layout(); # the index records it as "mesh_compute". tools/mesh_compute_vs.py writes the vertex shader that draws the slots. MESH_COMPUTE = False # --mesh-serial-waves (with --wave64-emulate): a mesh shader of more than 64 threads whose waves do not share LDS # runs its waves one after the other in 64 invocations, one pass per wave, so each pass is a single wave (the # inline_all structured form) instead of several waves side by side under mini-schedulers. See assemble(). MESH_SERIAL_WAVES = False # --compute-serial-waves (with --wave64-emulate): the same for a compute shader of more than 64 threads with no LDS # access, s_barrier or atomic: its waves are not ordered against each other, so they run one after the other in 64 # invocations, one pass per wave, turning 2-wave OpSwitch schedulers into single-wave inline_all structured SPIR-V. COMPUTE_SERIAL_WAVES = False # --mesh-native-wave32 (with --wave64-emulate): a partition-invariant mesh shader (no LDS, store, atomic, # cross-lane shuffle/ballot/reduction, and only constant -1 v_mbcnt for lane ID) skips --wave64-emulate and runs # all threads natively in 1 pass at LocalSize (e.g. 128) on 32-wide subgroups (zero %x_buf LDS/barriers). MESH_NATIVE_WAVE32 = False # --pc-tail-ubo: for devices with 128 bytes of push constants, Vulkan's minimum (AMD's Windows driver on RDNA2 iGPUs, # some Intel Arc drivers; D3D-14's push_constants_need_fallback). The push-constant block keeps s0..s31 (128 bytes). # The tail that follows them by default (dwords 32..35: heap base, code base; 36..37: the --mesh-compute output # address) moves, in the same order and at the same relative offsets, to a uniform block at set PC_TAIL_SET, binding # PC_TAIL_BINDING. It is declared only when the shader reads it; the index records it as "pc_tail", and # "push_constant_bytes" is 128. Set 1 is unused otherwise, so set 0's update-after-bind table is unchanged. PC_TAIL_UBO = False PC_TAIL_SET, PC_TAIL_BINDING = 1, 0 # --f16-interp-fallback: *_f16 interps without PerVertexKHR, for devices that have VK_KHR_fragment_shader_barycentric # but can't use its per-vertex inputs (MoltenVK: SPIRV-Cross has no MSL form of PerVertexKHR). Every VS and mesh # `exp paramN` also exports the channel's two f16 halves decoded to f32, low halves at f16_half_location(N, 0) and high # halves at f16_half_location(N, 1), and a PS *_f16 read of attrN.c takes component c of that smooth input. The # interpolation is linear, so this is the same P0 + i(P1 - P0) + j(P2 - P0) of the decoded halves, rounded by the # device's interpolator instead of by explicit arithmetic. The halves count down from location F16_HALF_TOP (param 0's # high halves, its low halves one below), so a producer with params 0..P-1 has room for the halves of params # 0..(28 - P) / 2; Gen.export skips the ones that would land on its own params. The top is 29, not 30 (SHADER-291): # MoltenVK's maxVertexOutputComponents is 124 because Metal counts gl_Position in its 128 vertex-output scalars, and # the validation layer counts it too (VUID-RuntimeSpirv-Location-06272), so (29 + 1) * 4 + 4 = 124 is the most a VS # can use there. F16_HALVES = False F16_HALF_TOP = 29 OPT_SPIRV = False # --opt: run tools/spirv_opt.py basic-block peephole pass on emitted SPIR-V (#884) # --address-guard: every access through heap_base + VA is checked against what the runtime backs (docs/d3d12_vulkan.md, # "Address guard"); one that fails reads 0 and drops its store. The runtime (LEONIDA_ADDRESS_GUARD=1) writes a header # at arena offset GUARD_HEADER: GUARD_MAGIC (u64), the arena's size (u64, offsets below it pass without a lookup), the # page table's address minus heap_base (u64), a count of refused accesses (u32, the shaders add to it) and the last # refused offset (u64). Without the magic every access passes, so a guarded module runs unchanged on a runtime with # the guard off. A refused load reads the zero area, a refused store or atomic writes the dump area; both are in the # arena's reserved first 512 KiB. Shared with runtime/src/address_guard.h. ADDRESS_GUARD = False # --address-guard (diagnostics): the module's id, FNV-1a of its file stem, which a refused access stores in the header # (+28) next to its offset, so the runtime's refusal line names the module. Set by _translate for each file. GUARD_MODULE_ID = 0 def fnv1a32(text): """32-bit FNV-1a of a UTF-8 string (the address guard's module id; tools/address_guard.py --module maps names).""" h = 0x811C9DC5 for b in text.encode("utf-8"): h = ((h ^ b) * 0x01000193) & 0xFFFFFFFF return h GUARD_HEADER = 0x70000 GUARD_ZERO = 0x71000 GUARD_DUMP = 0x78000 GUARD_MAGIC = int.from_bytes(b"LGUARD01", "little") GUARD_L1 = 1 << 16 # level-1 entries: bits 47..32 of the 48-bit offset (4 GiB each) GUARD_BLOCK_WORDS = 1 << 15 # level-2 block: one bit per 4 KiB page of a 4 GiB chunk # The heap base as one %ulong, in the entry block of %main: the push constants don't change during the invocation, and # the entry block dominates every use. Gen.host_addr adds an address to it. HEAP_BASE_ENTRY = ["%heap_base_lo = OpLoad %uint %ud_base_lo_p", "%heap_base_hi = OpLoad %uint %ud_base_hi_p", "%heap_base_lo64 = OpUConvert %ulong %heap_base_lo", "%heap_base_hi64 = OpUConvert %ulong %heap_base_hi", "%heap_base_hi_sh = OpShiftLeftLogical %ulong %heap_base_hi64 %c64_32", "%heap_base = OpBitwiseOr %ulong %heap_base_hi_sh %heap_base_lo64"] def guard_entry(cl, cu): """--address-guard: the entry-block lines that read the runtime's guard header at heap_base + GUARD_HEADER once per invocation: %gd_on (the magic is there), %gd_limit (the arena's size) and %gd_table (the page table's address minus heap_base). The header is in the arena's reserved range, so the read itself is always backed.""" L = [f"%gd_hp = OpIAdd %ulong %heap_base {cl(GUARD_HEADER)}", "%gd_p = OpConvertUToPtr %_ptr_PSB_arr %gd_hp"] for i in range(6): L += [f"%gd_w{i}p = OpAccessChain %_ptr_PSB_uint %gd_p {cu(i)}", f"%gd_w{i} = OpLoad %uint %gd_w{i}p Aligned 4"] for name, lo, hi in (("magic", 0, 1), ("limit", 2, 3), ("table", 4, 5)): L += [f"%gd_{name}_l = OpUConvert %ulong %gd_w{lo}", f"%gd_{name}_h = OpUConvert %ulong %gd_w{hi}", f"%gd_{name}_s = OpShiftLeftLogical %ulong %gd_{name}_h %c64_32", f"%gd_{name} = OpBitwiseOr %ulong %gd_{name}_s %gd_{name}_l"] L.append(f"%gd_on = OpIEqual %bool %gd_magic {cl(GUARD_MAGIC)}") return L def guard_function(cl, cu): """--address-guard: %guard_fn(heap_base, on, limit, table, offset, delta, sink) -> host address. `offset` is the access's sign-extended 48-bit heap offset and `delta` its span minus one. Without the runtime's guard (`on` false), or when [offset, offset + delta] is below `limit` (the arena, all of it backed), the result is heap_base + offset after one compare. Otherwise the page table at heap_base + table decides, per 4 KiB page of the first and the last byte: level 1 is GUARD_L1 words indexed by offset bits 47..32 (the level-2 block of that 4 GiB chunk: 0 none backed, 1 all), level 2 is one bit per page (bits 31..12), GUARD_BLOCK_WORDS words a block, after level 1. A refused access counts itself in the header and goes to heap_base + sink + (offset & 0xFFF).""" ul = "%ulong" L = ["%guard_fn = OpFunction %ulong None %fn_guard", "%ga_hb = OpFunctionParameter %ulong", "%ga_on = OpFunctionParameter %bool", "%ga_lim = OpFunctionParameter %ulong", "%ga_tab = OpFunctionParameter %ulong", "%ga_off = OpFunctionParameter %ulong", "%ga_delta = OpFunctionParameter %ulong", "%ga_sink = OpFunctionParameter %ulong", "%ga_entry = OpLabel", f"%ga_end = OpIAdd {ul} %ga_off %ga_delta", f"%ga_a = OpULessThan %bool %ga_off %ga_lim", f"%ga_b = OpULessThan %bool %ga_end %ga_lim", "%ga_in = OpLogicalAnd %bool %ga_a %ga_b", "%ga_off_n = OpLogicalNot %bool %ga_on", "%ga_pass = OpLogicalOr %bool %ga_in %ga_off_n", "OpSelectionMerge %ga_m None", "OpBranchConditional %ga_pass %ga_m %ga_slow", "%ga_slow = OpLabel", f"%ga_tb = OpIAdd {ul} %ga_hb %ga_tab"] def bit(k, o): """Lines for %ga_bit{k}: the page-table bit of heap offset id `o`.""" return [f"%ga_c{k} = OpShiftRightLogical {ul} {o} %c64_32", f"%ga_ci{k} = OpBitwiseAnd {ul} %ga_c{k} {cl(GUARD_L1 - 1)}", f"%ga_ca{k} = OpShiftLeftLogical {ul} %ga_ci{k} {cl(2)}", f"%ga_cp{k} = OpIAdd {ul} %ga_tb %ga_ca{k}", f"%ga_cq{k} = OpConvertUToPtr %_ptr_PSB_uint %ga_cp{k}", f"%ga_e{k} = OpLoad %uint %ga_cq{k} Aligned 4", f"%ga_e64{k} = OpUConvert {ul} %ga_e{k}", f"%ga_pg{k} = OpShiftRightLogical {ul} {o} {cl(12)}", f"%ga_pm{k} = OpBitwiseAnd {ul} %ga_pg{k} {cl(0xFFFFF)}", f"%ga_pw{k} = OpShiftRightLogical {ul} %ga_pm{k} {cl(5)}", f"%ga_eb{k} = OpIMul {ul} %ga_e64{k} {cl(GUARD_BLOCK_WORDS)}", f"%ga_wi0{k} = OpIAdd {ul} %ga_eb{k} %ga_pw{k}", f"%ga_wi{k} = OpIAdd {ul} %ga_wi0{k} {cl(GUARD_L1)}", f"%ga_wa{k} = OpShiftLeftLogical {ul} %ga_wi{k} {cl(2)}", f"%ga_wp{k} = OpIAdd {ul} %ga_tb %ga_wa{k}", f"%ga_wq{k} = OpConvertUToPtr %_ptr_PSB_uint %ga_wp{k}", f"%ga_w{k} = OpLoad %uint %ga_wq{k} Aligned 4", f"%ga_pl{k} = OpUConvert %uint %ga_pm{k}", f"%ga_sh{k} = OpBitwiseAnd %uint %ga_pl{k} {cu(31)}", f"%ga_bs{k} = OpShiftRightLogical %uint %ga_w{k} %ga_sh{k}", f"%ga_b1{k} = OpBitwiseAnd %uint %ga_bs{k} {cu(1)}", f"%ga_bit{k} = OpINotEqual %bool %ga_b1{k} {cu(0)}"] L += bit(0, "%ga_off") + bit(1, "%ga_end") hdr = cl(GUARD_HEADER) L += ["%ga_ok = OpLogicalAnd %bool %ga_bit0 %ga_bit1", "OpSelectionMerge %ga_rm None", "OpBranchConditional %ga_ok %ga_rm %ga_ref", "%ga_ref = OpLabel", # The refusal count (header +24) and the last refused offset (+32, low dword first): what the runtime logs. f"%ga_h = OpIAdd {ul} %ga_hb {hdr}", "%ga_hp = OpConvertUToPtr %_ptr_PSB_arr %ga_h", f"%ga_cnt = OpAccessChain %_ptr_PSB_uint %ga_hp {cu(6)}", f"%ga_old = OpAtomicIAdd %uint %ga_cnt {cu(1)} {cu(0)} {cu(1)}", "%ga_lo = OpUConvert %uint %ga_off", "%ga_hs = OpShiftRightLogical %ulong %ga_off %c64_32", "%ga_hi = OpUConvert %uint %ga_hs", f"%ga_lp = OpAccessChain %_ptr_PSB_uint %ga_hp {cu(8)}", "OpStore %ga_lp %ga_lo Aligned 4", f"%ga_hq = OpAccessChain %_ptr_PSB_uint %ga_hp {cu(9)}", "OpStore %ga_hq %ga_hi Aligned 4", # The refusing module's id (+28, diagnostics): GUARD_MODULE_ID, FNV-1a of the translated file's stem. f"%ga_ip = OpAccessChain %_ptr_PSB_uint %ga_hp {cu(7)}", f"OpStore %ga_ip {cu(GUARD_MODULE_ID)} Aligned 4", "OpBranch %ga_rm", "%ga_rm = OpLabel", "OpBranch %ga_m", "%ga_m = OpLabel", "%ga_okp = OpPhi %bool %true %ga_entry %ga_ok %ga_rm", f"%ga_good = OpIAdd {ul} %ga_hb %ga_off", f"%ga_po = OpBitwiseAnd {ul} %ga_off {cl(0xFFF)}", f"%ga_sb = OpIAdd {ul} %ga_hb %ga_sink", f"%ga_bad = OpIAdd {ul} %ga_sb %ga_po", f"%ga_r = OpSelect {ul} %ga_okp %ga_good %ga_bad", "OpReturnValue %ga_r", "OpFunctionEnd"] return L def pc_tail_chain(name, member, c): """`name` = pointer to push-constant tail member `member`, numbered as in %UserData (1-2 heap base, 3-4 code base, 5-6 --mesh-compute output address): a member of the push-constant block by default, member - 1 of the uniform block %pc_tail with --pc-tail-ubo. `c` maps an integer to its constant's id.""" if PC_TAIL_UBO: return f"{name} = OpAccessChain %_ptr_Uniform_uint_tail %pc_tail {c(member - 1)}" return f"{name} = OpAccessChain %_ptr_PC_uint %user_data {c(member)}" def f16_half_location(n, half): """--f16-interp-fallback: the canonical location of param n's decoded low (half 0) or high (half 1) f16 halves.""" return F16_HALF_TOP - 2 * n - 1 + half def assign_f16_half_locations(f16_attrs, raw_locs, top=F16_HALF_TOP): """--f16-interp-fallback: map each attribute in `f16_attrs` to `(low_loc, high_loc)` in `0..top` (SHADER-378). Keeps the canonical `28 - 2n` / `29 - 2n` slots whenever every pair fits in `0..top` without colliding with `raw_locs` (preserving byte-identical output for non-colliding shaders). Otherwise packs all pairs downward from `top` into free locations disjoint from `raw_locs`, raising `Unsupported` only when `0..top` has fewer than `2 * len(f16_attrs)` free locations left. """ attrs = sorted(f16_attrs) if not attrs: return {} raw = set(raw_locs) fixed = {n: (f16_half_location(n, 0), f16_half_location(n, 1)) for n in attrs} if all(0 <= lo and hi <= top and lo not in raw and hi not in raw for lo, hi in fixed.values()): return fixed free = [loc for loc in range(top, -1, -1) if loc not in raw] need = 2 * len(attrs) if len(free) < need: raise Unsupported( f"--f16-interp-fallback: need {need} decoded-half locations, only {len(free)} free in 0..{top}" ) return {n: (free[2 * k + 1], free[2 * k]) for k, n in enumerate(attrs)} def mesh_compute_layout(maxv, maxp, clip_count, cull_count, params): """Byte layout of one workgroup's slot in the --mesh-compute output buffer. Everything is 16-byte aligned: header (vertex count, primitive count, 2 unused dwords), then maxv vertices of `vertex_stride` bytes (position xyzw; the clip distances, then the cull distances, each padded to whole vec4s; one vec4 per param location in ascending order), then maxp primitives of 16 bytes (three vertex indices, then 1 if culled).""" clip_vec4 = -(-clip_count // 4) cull_vec4 = -(-cull_count // 4) params = sorted(params) stride = 16 * (1 + clip_vec4 + cull_vec4 + len(params)) vertices = 16 primitives = vertices + maxv * stride lay = {"slot_bytes": primitives + maxp * 16, "vertices": vertices, "vertex_stride": stride, "primitives": primitives, "primitive_stride": 16, "max_vertices": maxv, "max_primitives": maxp, "clip_count": clip_count, "clip_offset": 16, "cull_count": cull_count, "cull_offset": 16 * (1 + clip_vec4), "params": {n: 16 * (1 + clip_vec4 + cull_vec4 + k) for k, n in enumerate(params)}, "push_constant_bytes": 4 * USER_SGPRS + 24, "address_dwords": [USER_SGPRS + 4, USER_SGPRS + 5]} if PC_TAIL_UBO: # the address is dwords 4..5 of the --pc-tail-ubo block, not a push constant lay.update(push_constant_bytes=4 * USER_SGPRS, address_dwords=None, pc_tail_address_dwords=[4, 5]) return lay # GFX10 buffer format codes (Mesa src/amd/registers/gfx10-rsrc.json, enum GFX10_FORMAT). import json as _json # noqa: E402 with open(os.path.join(os.path.dirname(__file__), "gfx10_formats.json"), encoding="utf-8") as _f: GFX10_FORMATS = {int(k): v for k, v in _json.load(_f).items()} # Measured natively on RDNA2 (gfx1036, all 128 7-bit V# FORMAT codes): MUBUF DST_SEL=1 produces 1.0 (0x3F800000 / d16 # 0x3C00) iff FORMAT[6:0] is a valid float/normalized/scaled code (1..77 ending in _UNORM/_SNORM/_USCALED/_SSCALED/ # _FLOAT), and integer 1 (0x00000001 / d16 0x0001) for UINT/SINT, INVALID (0), and reserved codes (78..127). _FLOAT_FMT_MASKS = tuple( sum( 1 << (code - 32 * grp) for code in range(32 * grp, 32 * grp + 32) if GFX10_FORMATS.get(code, "").endswith(("_UNORM", "_SNORM", "_USCALED", "_SSCALED", "_FLOAT")) ) for grp in range(3) ) # User SGPRs s0..s(USER_SGPRS-1) are initialised from push constants (128 bytes = Vulkan's guaranteed minimum). USER_SGPRS = 32 # Graphics root arguments (D3D-448 follow-up, docs/d3d12_vulkan.md section 3.5). The runtime lays a graphics root # signature out once, in root order, with root dword k at push dword GRAPHICS_ROOT_DWORD + k: where a VS, PS or GS # reads it (their root arguments start at s8, so their SGPR i is push dword i, as before). A mesh shader's start at # MS_ROOT_SGPR (s16), so it reads s16.. from push dwords 8.. and a mesh and a pixel shader of one pipeline find the # same argument in the same dword. Its s8..s15, below its base and not root data, read 0; s0..s7 stay push dwords # 0..7 for every stage. index.json records the window as "root_window" so the runtime can refuse a mesh shader # translated before it. GRAPHICS_ROOT_DWORD = 8 MS_ROOT_SGPR = 16 def user_data_dword(stage, sgpr): """The push-constant dword the translated `stage` loads into user SGPR `sgpr` at entry, or None for 0.""" if stage != "ms" or sgpr < GRAPHICS_ROOT_DWORD: return sgpr if sgpr < MS_ROOT_SGPR: return None return sgpr - (MS_ROOT_SGPR - GRAPHICS_ROOT_DWORD) # POPS: the hardware gives a pixel shader with an ordered section its collision word in the SGPR after its user # SGPRs and the primitive mask (Mesa's pops_collision_wave_id argument, GFX9-10.3): the collision wave id in bits # 0-9, this wave's id in bits 16-25, the overlap flag in bit 31. The program takes the wave id out with s_bfe_u32 # and this field (offset 16, width 10). POPS_WAVE_ID_FIELD = 0x000A0010 # What the translator puts in that SGPR at entry: no overlap, wave id 1, collision id 0. The program's wait loop # leaves once wave_id + ~collision_id is below src_pops_exiting_wave_id + ~collision_id, unsigned. With the exiting # id read as 0 (Gen.src_u) that is 0 < 0xFFFFFFFF, true at the first test. A word with wave id == collision id # (0, what the push constants usually hold) gives 0xFFFFFFFF < 0xFFFFFFFF, never true: a wave that reaches the loop # runs it to the loop guard. The overlap test before the loop skips it whenever a lane is on, so only a subgroup # with EXEC all off there entered it. POPS_COLLISION_SEED = 1 << 16 def pops_collision_sgpr(insns, entry_reads): """The SGPR a pixel shader's POPS collision word arrives in: the source of the s_bfe_u32 that takes out the word's wave id (POPS_WAVE_ID_FIELD), when the program reads that SGPR's entry value (`entry_reads`, from shader_meta's user_sgpr_reads). None when no such read is found: the word is then left as the push constants give it, as before.""" for ins in insns: a = ins["args"] if (base_op(ins["op"]) == "s_bfe_u32" and len(a) == 3 and a[1]["k"] == "sgpr" and a[1].get("n", 1) == 1 and a[2]["k"] == "imm" and a[2]["v"] & 0xFFFFFFFF == POPS_WAVE_ID_FIELD and a[1]["r"] in entry_reads): return a[1]["r"] return None # v_pipeflush (GFX10 VOP1) only flushes the VALU pipeline: no register, memory or EXEC effect to translate. # s_icache_inv invalidates the instruction cache; s_ttracedata / s_ttracedata_imm send thread-trace data; # s_code_end pads the end of a code object; s_version records the ISA version. None of them has a register, memory, # SCC or EXEC effect. (Data-cache invalidations such as buffer_gl0_inv are about cross-wave coherence and are not # here.) ds_nop is the DS unit's no-operation (no address, data or result). v_clrexcp clears the exception bits of # TRAPSTS, which nothing translated reads (s_getreg_b32 is unsupported and there are no traps). # s_atc_probe / s_atc_probe_buffer probe (prefetch) an address in the address translation cache: no data comes back # and nothing is written (RDNA2 ISA, SMEM). s_incperflevel / s_decperflevel step a performance counter and s_wakeup # pings the other waves of the threadgroup out of an s_sleep (itself a no-op here): neither touches a register, # memory, SCC, VCC or EXEC (RDNA2 ISA, SOPP). NOOPS = {"s_sleep", "v_nop", "v_pipeflush", "s_nop", "s_inst_prefetch", "s_endpgm", "s_setprio", "s_clause", "s_delay_alu", "s_waitcnt", "s_waitcnt_vscnt", "s_waitcnt_vmcnt", "s_waitcnt_expcnt", "s_waitcnt_lgkmcnt", "s_waitcnt_depctr", "s_icache_inv", "s_ttracedata", "s_ttracedata_imm", "s_code_end", "s_version", "ds_nop", "v_clrexcp", "s_atc_probe", "s_atc_probe_buffer", "s_incperflevel", "s_decperflevel", "s_wakeup"} F2 = {"v_add_f32": "OpFAdd", "v_sub_f32": "OpFSub", "v_mul_f32": "OpFMul", "v_max_f32": "max", "v_min_f32": "min"} U2 = {"v_add_nc_u32": "OpIAdd", "v_sub_nc_u32": "OpISub", "v_and_b32": "OpBitwiseAnd", "v_or_b32": "OpBitwiseOr", "v_xor_b32": "OpBitwiseXor", "v_mul_u32_u24": "mul24"} SHIFT_REV = {"v_lshlrev_b32": "OpShiftLeftLogical", "v_lshrrev_b32": "OpShiftRightLogical", "v_ashrrev_i32": "OpShiftRightArithmetic"} F1 = {"v_rcp_f32": "rcp", "v_rsq_f32": "InverseSqrt", "v_sqrt_f32": "Sqrt", "v_exp_f32": "Exp2", "v_log_f32": "Log2", "v_floor_f32": "Floor", "v_fract_f32": "Fract", "v_ceil_f32": "Ceil", "v_trunc_f32": "Trunc"} S2 = {"s_and_b32": "OpBitwiseAnd", "s_or_b32": "OpBitwiseOr", "s_lshl_b32": "OpShiftLeftLogical", "s_lshr_b32": "OpShiftRightLogical", "s_mul_i32": "OpIMul"} # RDNA2 ISA SOPC scalar compare (14 ops) and bit-test (4 ops) exact mnemonic sets (tools/rdna2_isa_tables.py SOPC). SOPC_CMP32_OPS = frozenset({ "s_cmp_eq_i32", "s_cmp_lg_i32", "s_cmp_gt_i32", "s_cmp_ge_i32", "s_cmp_lt_i32", "s_cmp_le_i32", "s_cmp_eq_u32", "s_cmp_lg_u32", "s_cmp_gt_u32", "s_cmp_ge_u32", "s_cmp_lt_u32", "s_cmp_le_u32", }) SOPC_CMP64_OPS = frozenset({"s_cmp_eq_u64", "s_cmp_lg_u64"}) SOPC_BITCMP_OPS = frozenset({"s_bitcmp0_b32", "s_bitcmp1_b32", "s_bitcmp0_b64", "s_bitcmp1_b64"}) SOPC_SRC32_SPECIALS = frozenset({ "null", "m0", "vcc_lo", "vcc_hi", "exec_lo", "exec_hi", "scc", "src_scc", "src_pops_exiting_wave_id", }) SOPC_SRC64_SPECIALS = frozenset({"vcc", "exec", "null"}) # Ops that read a lane-mask operand as a plain number even though the destination is not a VGPR # (the scalar ALU set; the v_* entries already qualify through their VGPR destinations). Ported from # PR #1043's lane_masks.NUMBER_READERS so scalar readers (s_add_u32 s20, s10, K after v_cmp wrote s10) # see the wave's mask word, not this lane's 0 / ~0 bit. Mask-preserving ops (s_mov_b32, the MASK_SOP2 # logic ops, saveexec/wrexec) are deliberately absent: a mask moving or combining as a mask keeps the # per-lane bit mask_src readers rely on. _sdwa / _dpp / _dpp8 forms are excluded at the check site. MASK_NUMBER_READERS = frozenset(( "s_add_u32", "s_add_i32", "s_sub_u32", "s_sub_i32", "s_addc_u32", "s_subb_u32", "s_mul_i32", "s_mul_hi_u32", "s_mul_hi_i32", "s_lshl_b32", "s_lshr_b32", "s_ashr_i32", "s_bfe_u32", "s_bfe_i32", "s_min_u32", "s_min_i32", "s_max_u32", "s_max_i32", "s_brev_b32", "s_lshl1_add_u32", "s_lshl2_add_u32", "s_lshl3_add_u32", "s_lshl4_add_u32", "v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32", "v_lshlrev_b32", "v_lshrrev_b32", "v_ashrrev_i32", "v_mul_lo_u32", "v_mul_hi_u32", "v_min_u32", "v_max_u32", "v_min_i32", "v_max_i32", "v_bfe_u32", "v_bfe_i32", "v_add3_u32", "v_lshl_add_u32", "v_add_lshl_u32", "v_bcnt_u32_b32", )) # Runs of lane-local VALU instructions share one `if (active)` instead of an OpSelect per VGPR write (Gen.insns). # VALU ops that are not lane-local: they read other lanes, write a lane mask, SCC or EXEC, or write a carry or # other scalar result in every lane (v_add_co_u32's mask goes to inactive lanes too). NOT_LANE_LOCAL = ("v_cmp", "v_readlane", "v_readfirstlane", "v_writelane", "v_permlane", "v_mbcnt", "v_interp", "v_div_scale", "v_mad_u64_u32", "v_mad_i64_i32") DPP_MODS = ("quad_perm", "row_", "wave_", "dpp8", "bank_mask", "bound_ctrl", "fi:") # A single lane-local instruction keeps its select: on an RX 5700 XT wrapping it bought nothing measurable # (64 divergent if/else of 1-4 ops: within 1%), and it adds labels. Long runs are where the time goes. MIN_ACTIVE_RUN = 2 def base_op(op): for suf in ("_e32", "_e64", "_sdwa", "_dpp"): if op.endswith(suf): return op[: -len(suf)] return op class Unsupported(Exception): pass class Gen: def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.stage = stage self.descriptor_hash = DESCRIPTOR_HASH self.descriptor_table = DESCRIPTOR_TABLE self.hoist_reg_ptrs = hoist_reg_ptrs self.reg_ptrs = {} self.cache_active = cache_active self.exec_static_true = False self._active_ssa = None self.body = [] self.consts = {} self.fconsts = {0: "%f0", 0x3F800000: "%f1"} # fconst: f32 bits -> its OpConstant %float (these two # are declared with the types) self.fconst_of = {v: k for k, v in self.fconsts.items()} # and back: the id -> its bits # tof/tou results -> the id they were bitcast from. A bitcast of a bitcast gives the original id back: wherever # the key is valid its source is too (the key's own definition uses it), so no dominance is lost. self.bitcast_from = {} self.n = 0 self.outputs = {} self.partial_color_outputs: set[str] = set() self.inputs = {} self.interpolated = set() # inputs read through v_interp_p1/p2; the rest are flat (v_interp_mov only) self.per_vertex = set() # PS: attribute numbers read by a *_f16 interp: PerVertexKHR, decoded per half self.f16_halves = set() # PS, --f16-interp-fallback: the same attributes, read from decoded-half inputs self.f16_half_locs = {} # PS/VS/MS, --f16-interp-fallback: attr/param n -> (low_loc, high_loc) self.param_max = -1 # VS/MS: the highest exp paramN (--f16-interp-fallback keeps halves above it) self.f16_half_outs = {} # VS/MS, --f16-interp-fallback: param n -> its two decoded-half output names self.ij_capture = {} # computed-I/J pairs: pair key -> the I float id the p1 loaded (SHADER-177) self.ij_deriv = {} # PS without PerVertexKHR: (input_name, comp) -> tag for quad-derivative IJ self.uses_psb = False self.uses_active = False self.vm_latch = False # PS: EXEC can change after a `vm` or color export, so EXEC at those is kept self.col_latched = [] # PS with vm_latch: the color targets (mrtN) whose export EXEC is kept self.uses_perm = False # emulate: ds_permute_b32 parks its winning source lane in %x_perm self.uses_tex = False self.uses_dynamic_sampled_index = False self.uses_dynamic_storage_index = False self.uses_subgroup = False self.uses_tex_array = False self.uses_storage = False self.uses_query = False self.uses_tex_1d = False self.uses_tex_3d = False self.uses_v4uint = False self.uses_store_views = set() # image_store dims used (index into STORE_DIMS) self.uses_int_sampler = False # 2D typed sampled-image types for sampling and gathering self.uses_int_fetch = set() # typed image_load dims (index into STORE_DIMS): uint/sint sampled aliases self.uses_d16_image = False # d16 normalized/f32 conversion masks self.uses_fmt_size = False # buffer FORMAT -> size table self.uses_store_reads = set() # formatless reads for coherent/storage-only dimensions self.atomic_volume_tsharps = set() # SGPR descriptor groups also used for 3D atomics self.reads_store_views = False # reserved for compatibility with main self.coherent_images = False # a glc image_load/image_store: the storage views are decorated Coherent self.uses_vmm = False # glc/dlc or intra-workgroup barrier coherency: VulkanMemoryModel + DeviceScope self.uses_barrier = False # s_barrier or wave64-emulate ordering barrier executed in cs/ms self.uses_s_barrier = False # explicit RDNA2 s_barrier executed in cs/ms self.reads_glc_buffer = False # glc/dlc buffer/global/scalar load: runtime pre-dispatch barrier hint self.writes_depth = False self.db_shader_control = None # PS: DB_SHADER_CONTROL register from FSSM header (E + 0x138) self.osg1_depth_stencil = False # PS: OSG1 declares SV_Depth* or SV_StencilRef self.early_depth = False # PS: OpExecutionMode %main EarlyFragmentTests emitted self.uses_smul = False self.uses_minlod = False self.uses_img_offset = False self.uses_pops = False self.pops_word_sgpr = None # PS: the SGPR the POPS collision word arrives in (pops_collision_sgpr) self.round_mode = False # the program writes MODE.FP_ROUND[3:2] (f16/f64 rounding): kept in %mode_r16 self.uses_fhalf = False # %fhalf_g (0.5) constant self.uses_f64 = False self.uses_psb_vec = False # scalar_load's read-only wide loads: uvec2/uvec4 NonWritable Block pointers self.uses_psb_vec_rw = False # scalar_load's mutable wide loads: uvec2/uvec4 Block pointers without NonWritable self.uses_psb_scalar_ro = False # scalar_load's read-only single-dword loads: uint NonWritable Block pointers self.ftz32 = bool(FLOAT_CONTROLS and FTZ32) # DenormFlushToZero 32 active for this module self.scalar_load_ro = None # None (unanalysed), True (all RO), or frozenset of id(ins) safe for NonWritable self.sbuf_slow_fns: dict[tuple[int, bool], list[str]] = {} # (width, ro) -> %sbuf_slow_{ro|rw}_x{n} helper lines self.uses_int_dot = False # packed_dot4 emitted OpSDot/OpUDot(AccSat): SPV_KHR_integer_dot_product self.uses_fma_khr = False # an OpFmaKHR was emitted: capability FMAKHR + extension SPV_KHR_fma self.uses_fma_khr32 = False # ... on f32 (feature shaderFmaFloat32) self.uses_fma_khr64 = False # ... on f64 (feature shaderFmaFloat64) # The --fma option this module is translated under, for the index: a caller that changes the option before # shader_meta (translation and indexing in separate steps) must not relabel it. self.fma_mode = "exact" if FMA_EXACT else "khr" if FMA_KHR else "glsl" self.uses_clock = set() self.uses_bvh = False self.lconsts = {} # 64-bit constants: value -> id self.uses_vote = False # wave-uniform branches (OpGroupNonUniformAny) self.uses_ballot = False # wave mask ballot (OpGroupNonUniformBallot) self.uses_bcast_first = False # OpGroupNonUniformBroadcastFirst (desc_lookup): Ballot capability only self.uses_wave_bits = False # a whole lane mask gathered from the wave (OpGroupNonUniformBitwiseOr) self.uses_quad = False # s_wqm on a lane mask (OpGroupNonUniformQuadSwap) self.lane_masks = {} # id(instruction) -> registers holding a lane mask there (lane_masks.py) self.ever_mask = set() # SGPRs that held a lane mask anywhere in the shader (conservative) self.cur_masks = {} self.vcc_scalar_pointer = False self.cur_ins = None self.wave32_vcc_pointer = False self.mask_writes = set() # id(instruction) of the ones that write a lane mask to a VGPR self.write_all_lanes = False self.dpp_guard = None # per-lane bool: a DPP instruction's row/bank/valid write mask self.active_run = False # inside insns' `if (active)` around a run of lane-local VALU instructions self.exec_changes = False # some instruction may write EXEC (may_write_exec): only then are runs worth it self.parked = {} # (vgpr, lane) a mask is parked in -> the spare SGPR slot that keeps it per lane self.uses_lds = False self.lds_dwords = 16384 # CS: set from RSRC2 LDS_SIZE (power of two, covers every offset used) self.lds_need = 0 # CS: dwords the program needs (LDS_SIZE, largest constant offset) self.lds_declared = 0 # CS: dwords RSRC2 LDS_SIZE allocates (the hardware allocation, unclipped) self.lds_bound = None # CS: bounds-checked LDS (dwords): out of range reads 0, writes are dropped self.cs = None # CS: user SGPR count, enabled workgroup ids, thread-id VGPR count, group size self.ms = None # MS: {"maxv", "maxp", "threads"} from PSV0 self.ms_params = set() # MS: param export indices used self.ms_alloc = False # MS: s_sendmsg GS_ALLOC_REQ seen self.pos_map = {} # VS/MS: pos index (1..3) -> {comp: ("clip"|"cull", idx)} from OSG1 self.mrt_targets = [] # PS: the declared SV_Target indices in order (OSG1); export k goes to the k-th self.mrt_types = {} # PS: render target index -> OSG1 component type (1=UINT, 2=SINT) for integer targets self.mrt_masks = {} # PS: render target index -> OSG1 declared component mask (0x1..0xF) self.output_ctypes = {} # PS: output variable name -> OSG1 component type (1=UINT, 2=SINT) self.pos_misc = set() # VS: misc system values in pos1 (4=Layer, 5=ViewportIndex) from OSG1 self.clip_count = 0 # ClipDistance array length (1..8) self.cull_count = 0 # CullDistance array length (1..8) self.uses_clip = False # True once a pos1+ export writes a ClipDistance slot self.uses_cull = False # True once a pos1+ export writes a CullDistance slot self.uses_layer = False # VS: True once pos1 misc writes BuiltIn Layer self.uses_viewport = False # VS: True once pos1 misc writes BuiltIn ViewportIndex self.gs = None # GS: {"in": [(reg, sv)], "out": [(reg, sv)], "nreg": n, "maxv": n} self.wave64 = False # compiled for 64-lane waves (64-bit EXEC writes, exec_hi, v_mbcnt_hi, ...) self.cur_uniform_readlane = False self.w64g = None # wave64 VS/PS/GS: wave64_halves.analyse() result (tier, reasons, rewrite sites) self.scalar_spills = set() # (vgpr, lane) pure scalar spill slots lowered to self.parked (all waves/stages) self.spill_readlanes = set() # id(ins) of mixed-VGPR v_readlane_b32 proven to reload a parked spill slot self.emulate = False # --wave64-emulate: exact wave64 on any subgroup size (cs/ms; see x_round) self.ms_native_wave32 = False # --mesh-native-wave32: partition-invariant MS skipped wave64 emulation self.emulate_inline = False # emulate: current block emits direct inline barriers (no x_split) self.emulate_plan = None # emulate: structured plan from wave64_emulate_opt.plan_structured_emulation self.x_one_lane = False # emulate: emitting a fold that at most one lane of the wave runs ("one_lane") self.mini_segs = defaultdict(list) # emulate_plan: mini_idx -> continuation segment ids self.tail_segs = [] # emulate_plan: continuation segment ids belonging to tail_scheduler self.x_seg = 0 # emulate: number of the next continuation segment (past the block numbers) self.x_marks = [] # emulate: (index into body, segment) where a segment of the current block ends self.x_segs = {} # emulate: continuation segment -> its SPIR-V lines self.x_spills = [] # emulate: (Function variable, pointer type) carrying a value across a round self.eager_vars = [] # (Function variable, pointer type) a subgroup op's result is stored to (see eager) self.x_ptr_types = {} # emulate: value type -> Function pointer type declared for spills self.x_dirty = set() # emulate: (memory kind "lds"/"mem", "r"/"w") accessed since the last round self.x_tok = {} # emulate: register -> the SSA id last stored to it in this block (its value's identity) self.x_gen = 0 # emulate: bumped at every label (control flow inside a block): forgets x_tok self.x_mcache = {} # emulate: wave_mask key -> (lo, hi) already exchanged in this block self.lane_either = {} # id(instruction) -> SGPRs holding constant 0/-1 (EITHER) there self.cur_either = () self.x_lanes = 64 # emulate: workgroup invocations rounded up to whole waves self.ms_serial = 0 # --mesh-serial-waves: number of passes (waves run one after the other), or 0 self.cs_serial = 0 # --compute-serial-waves: the same for a compute shader self.scc_live = None # emulate: set of id(ins) whose SCC write is live-out (wave64_emulate_opt) self.cur_scc_live = True # emulate: whether the current instruction's SCC result is live-out self.bar_rounds = False # native wave32 cs with an s_barrier outside uniform control flow (bar_scheduler) self.uses_storage3d = False self.uses_storage64 = False # 2D 64-bit R64ui image atomics (set 0 binding 29, Int64ImageEXT) self.uses_heap = False self.uses_guard = False # --address-guard: an access called %guard_fn (the entry block reads the header) self.uses_codebase = False self.uses_pc_tail = False # --pc-tail-ubo and the shader reads the tail (set in assemble) self.uses_long = False self.vertex_inputs = [] # (D3D input register, component type 1=uint 2=sint 3=float) for fetch-calling VS self.vertex_signature = [] # full ISG1: (register, mask, system value, component type) for PSO lookup self.dynamic_format = False # True when a buffer_load used a runtime V# FORMAT (unknown codes -> 0 at runtime) self.fixed_format_codes = set() # static tbuffer/fixed format codes seen (validated against FORMATS) self.frag_inputs = {} # PS: VGPR -> gl_FragCoord component, from the verified system-VGPR layout self.pixel_interpolants = None # PS: (count, fp16_mask) from the FSSM pixel-input table; None = no table self.v_interp_copy = {} # PS: vgpr -> (root barycentric register v0/v1, program-order index of its # single defining plain v_mov of it); valid I/J sources (SHADER-177) self.blocks = [] # per basic block: list of SPIR-V lines (dispatch-loop form), empty = straight-line self.succ = [] # per basic block: the blocks it can go to next (none = the program ends there) self.out_pcs = None # per basic block: exact set of %pc values written (including cfg_structure.END) self.desc_fn = None # lines of the descriptor-lookup function, once an instruction needs it self.tbuffer_norm_fns: dict[int, list[str]] = {} # one exact quotient per used magnitude width self.fmt_fn = None # lines of the typed-buffer format-decode function, once a dynamic-format load needs it self.fmt_norm_fn = None # lines of the shared exact norm quotient for a run-time width (SHADER-849) self.fmt_enc_fn = None # shared format encoder for stores through a dynamic V# self.guard_fn = None # --address-guard: lines of %guard_fn, once an access needs it self.guard_last = None # --address-guard: (guarded address, unguarded address) of the last host_addr self.uses_fmt_tables = False # %fmt_desc_tab / %fmt_norm_rep_tab: a format's kind and channel widths self.uses_fmt_enc_table = False # %fmt_enc_desc_tab: table-driven dynamic-format buffer store encoder self.float_only_images = set() # id(ins) of image_load/image_sample ops provably float-only self.x_round_fns: dict[str, list[str]] = {} # emulate_inline: helper functions for x_round pre-barrier setup self.x_round_fn_types: dict[int, str] = {} # emulate_inline: arity -> OpTypeFunction id for x_round_fns self.sgpr_imm = {} # SGPR -> literal an s_mov_b32 put there earlier in this basic block (see gather_addr_modes) self.desc_cache = {} # (first SGPR, dwords) -> id of the %desc_lookup_fn result in the current basic block # id(instruction) -> True when its T#'s dword 6 comes from a heap slot the layer writes (descriptor_sources) self.tsharp_from_heap = {} self.tsharp_index_reads = 0 # image instructions that take the T#'s index from dword 6 alone self.tsharp_lookups = 0 # ... that also look the T# up in the hash table (its source is not known) self._scan = (None, 0, []) # (body list, lines already seen, open merge labels): see desc_cache_ok self.block_label = "%entry" # label of the SPIR-V block the current instruction starts in self.build_meta = {} # runtime build metadata from tools/shader_meta.py self.literal_samplers = [] # ordered 4-dword literal S# tuples (matches meta["literal_samplers"]) self.literal_sampler_index = {} # 4-dword tuple -> SpecId index (0..N-1) self.literal_sampler_sites = {} # id(ins) -> 4-dword literal S# tuple self.uses_lit_sampler_spec = False # emitted OpSpecConstant literal sampler bypass def tmp(self): self.n += 1 return f"%t{self.n}" def cu(self, v): v &= 0xFFFFFFFF if v not in self.consts: self.consts[v] = f"%c{v:x}" return self.consts[v] def emit(self, s): self.body.append(" " + s) if s.startswith("OpStore %active "): if self.exec_static_true: raise RuntimeError(f"OpStore %active emitted with exec_static_true: {s}") self._active_ssa = s.split()[2] elif s.endswith("= OpLabel"): self._active_ssa = None if self.emulate: if s.startswith(("OpStore %vcc ", "OpStore %active ")): reg, val = s.split()[1:3] self.x_tok[reg] = val elif s.endswith("= OpLabel"): self.x_gen += 1 # ---- register access ---- def reg_ptr(self, kind, r): """Return a pointer to element `r` of `%vgpr` or `%sgpr`. When `hoist_reg_ptrs` is enabled (the default for `translate()`), emit one `OpAccessChain` per distinct register in `%entry` (in `assemble()`) instead of repeating it at every load/store; direct `Gen()` callers keep inline chains.""" arr = "%vgpr" if kind == "vgpr" else "%sgpr" if self.hoist_reg_ptrs: key = (kind, r) p = self.reg_ptrs.get(key) if p is None: self.cu(r) p = f"%reg_{'v' if kind == 'vgpr' else 's'}{r}" self.reg_ptrs[key] = p return p p = self.tmp() self.emit(f"{p} = OpAccessChain %_ptr_Function_uint {arr} {self.cu(r)}") return p def load_reg(self, kind, r): p = self.reg_ptr(kind, r) t = self.tmp() self.emit(f"{t} = OpLoad %uint {p}") return t def store_reg(self, kind, r, val): if kind == "sgpr": self.sgpr_imm.pop(r, None) self.x_tok[("sgpr", r)] = val if self.desc_cache: # every write to the %sgpr array comes through here (see desc_lookup_sgpr) self.desc_cache = {k: v for k, v in self.desc_cache.items() if not (k[0] <= r < k[0] + k[1])} p = self.reg_ptr(kind, r) self.emit(f"OpStore {p} {val}") def imm_val(self, a): """Integer literal value if 'a' is an immediate or known SGPR constant, else None.""" if a.get("abs") or a.get("neg"): return None k = a.get("k") if k == "imm": return a["v"] & 0xFFFFFFFF if k == "sgpr" and a.get("n", 1) == 1 and a.get("r") in self.sgpr_imm: return self.sgpr_imm[a["r"]] & 0xFFFFFFFF if k == "special" and a.get("t") == "null": return 0 return None def src_u(self, a): k = a["k"] if ((k == "sgpr" and a.get("n", 1) == 1) or (k == "special" and a.get("t") in ("exec_lo", "exec_hi", "vcc", "vcc_lo", "vcc_hi"))) \ and self.holds_lane_mask(a) and self.mask_read_is_data(): # The operand holds this lane's 0 / ~0 bit of a lane mask; a data read wants the whole wave's # mask word (the same in every lane), as the SOP ops that read a mask as a number already do # (lane_mask_word). Until now a VALU read (v_mov_b32 v6, s16 after v_cmp wrote s16) gave each # lane its own bit where hardware gives the mask itself (found by tools/crosslane_fuzz.py). # Only when the destination is a VGPR: a mask moving into an SGPR, EXEC or VCC keeps this # lane's bit, which mask_src readers rely on. A VGPR that stays a mask keeps the word too — # mask_src extracts this lane's bit back out when a mask consumer reads one. # The gather itself is eager (wave_mask): EXEC narrowing is a per-lane value in this # model, not SPIR-V control flow, and mask-data readers are kept out of lane-local # `if (active)` runs, so lanes off in EXEC still contribute their mask bits. v = self.lane_mask_word(a) elif k in ("vgpr", "sgpr"): if a.get("n", 1) != 1: raise Unsupported("64-bit operand") v = self.load_reg(k, a["r"]) elif k == "special" and a["t"] == "null": v = self.cu(0) # RDNA 'null' source reads as zero (e.g. soffset) elif k == "special" and a["t"] in ("exec_lo", "exec", "exec_hi"): v = self.exec_value() elif k == "special" and a["t"] == "m0": v = self.tmp() self.emit(f"{v} = OpLoad %uint %m0") elif k == "special" and a["t"] == "vcc_hi": # wave64: vcc_hi is the upper half of VCC when VCC holds a lane mask (each lane's bit lives in %vcc). # wave32 (or plain data): vcc_hi is an ordinary SGPR. v = self.tmp() self.emit(f"{v} = OpLoad %uint {'%vcc' if (self.wave64 and 'vcc' in self.cur_masks) else '%vcc_hi'}") elif k == "special" and a["t"] in ("scc", "src_scc"): v = self.tmp() self.emit(f"{v} = OpLoad %uint %scc") elif k == "special" and a["t"] == "src_pops_exiting_wave_id": # POPS (primitive-ordered pixel shading): the hardware wait loop compares this against the # collision word. Ordering comes from fragment-shader interlock around the whole shader instead # (see assemble), so the id reads as 0 and the collision word is seeded at entry with # POPS_COLLISION_SEED, which ends the wait loop at its first test. v = self.cu(0) self.uses_pops = True elif k == "imm": v = self.cu(a["v"]) elif k == "fimm": v = self.cu(struct.unpack(" (source selects, dst bit). A select bit of 1 reads the high half of that source; the last bit sends the result to the high half. No modifier means all zeros.""" sel = next((m for m in mods if m.startswith("op_sel:")), None) if sel is None: return [0] * nsrc, 0 bits = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] + [0] * (nsrc + 1) return bits[:nsrc], bits[nsrc] def u16_half(self, u, hi=0): """Zero-extended 16-bit half of u32 ``u`` (high half when ``hi`` is truthy). Do not follow ``OpShiftRightLogical %uint u 16`` with a redundant ``OpBitwiseAnd ... 0xFFFF``: AMD's Windows LLPC driver (measured on RDNA2, drivers 22.40.84.06 in #1506 and 24.10.24) drops the ``>> 16`` when ``(u >> 16) & 0xFFFF`` follows two partial-half writes and feeds ``OpIAdd``, ``OpIMul``, or ``OpShiftLeftLogical``.""" h = self.tmp() if hi: self.emit(f"{h} = OpShiftRightLogical %uint {u} {self.cu(16)}") else: self.emit(f"{h} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}") return h def i16_half(self, u, hi=0): """Sign-extended 16-bit half of u32 ``u`` as ``%int`` (high half when ``hi`` is truthy). Avoids ``OpBitFieldSExtract (OpShiftRightLogical u 16) 0 16``, which hits the same AMD Windows LLPC bug as ``(u >> 16) & 0xFFFF`` (#1506) and drops the shift.""" h = self.tmp() if hi: self.emit(f"{h} = OpShiftRightArithmetic %int {self.as_int(u)} {self.cu(16)}") else: self.emit(f"{h} = OpBitFieldSExtract %int {self.as_int(u)} {self.cu(0)} {self.cu(16)}") return h def src_h(self, s): """Raw 32 bits of an operand of a 16-bit float op, before its neg/abs. An inline float constant (0.5, 1.0, -2.0, ...) is the f16 value in the low half over a zero high half, not f32 bits. Measured on an RX 6800 (gfx1030, raw kernel, wave32 and wave64): v_add_f16 d, 1.0, v with v.lo = 0.25 gives 1.25, v_cvt_f32_f16 d, 0.5 gives 0x3f000000, v_pack_b32_f16 d, 1.0, v puts 0x3c00 in the low half, and op_sel's high half of the constant reads +0.0. Under SDWA, src_sel then narrows those 32 bits like a register's (gfx1036: v_add_f16_sdwa d, 1.0, v src0_sel:WORD_1 reads +0.0).""" if s["k"] == "fimm": try: v = self.cu(struct.unpack(" f16 bits as RDNA2's buffer unit narrows a float: toward zero, a finite value past the range -> +-65504, an f32 denormal -> +-0 (f16_bits(rtz=True)), and a NaN keeps its sign and the top 10 bits of its payload without being quieted, 1 if those are all 0 (0x7fa00000 -> 0x7d00, 0x7f800001 -> 0x7c01). Measured natively on gfx1036 for 16_FLOAT stores and 32_FLOAT d16 loads (SHADER-358).""" h = self.f16_bits(f, rtz=True) x, mag, nan, top, one, keep, sg, nb, out = (self.tmp() for _ in range(9)) self.emit(f"{x} = OpBitcast %uint {f}") self.emit(f"{mag} = OpBitwiseAnd %uint {x} {self.cu(0x7FFFFFFF)}") self.emit(f"{nan} = OpUGreaterThan %bool {mag} {self.cu(0x7F800000)}") self.emit(f"{top} = OpBitFieldUExtract %uint {x} {self.cu(13)} {self.cu(10)}") self.emit(f"{one} = OpIEqual %bool {top} {self.cu(0)}") self.emit(f"{keep} = OpSelect %uint {one} {self.cu(1)} {top}") self.emit(f"{sg} = OpShiftRightLogical %uint {x} {self.cu(16)}") sgm = self.tmp() self.emit(f"{sgm} = OpBitwiseAnd %uint {sg} {self.cu(0x8000)}") kn = self.tmp() self.emit(f"{kn} = OpBitwiseOr %uint {keep} {self.cu(0x7C00)}") self.emit(f"{nb} = OpBitwiseOr %uint {sgm} {kn}") self.emit(f"{out} = OpSelect %uint {nan} {nb} {h}") return out def pack_f16_pair_int(self, f0, f1): """Two f32 values -> one u32 (lo f16 | hi f16 << 16), each narrowed by f16_bits: integer ops only, no GLSL.std.450 at all (#489: an amdvlk64 pipeline-creation crash came from PackHalf2x16 on a d16 image_sample result feeding a structured loop with OpGroupNonUniformAny). For d16 memory results (image samples and gathers, typed buffer loads): those are converted outside the VALU, so they stay round to nearest even and don't go through f16_pack2. f16_bits replaced #489's own f32_to_f16_int on 2026-11-22; the two gave the same bits on 30,648 inputs (every f32 exponent, ties, the subnormal and overflow edges, NaN).""" lo = self.f16_bits(f0) hi = self.f16_bits(f1) hi_s, out = self.tmp(), self.tmp() self.emit(f"{hi_s} = OpShiftLeftLogical %uint {hi} {self.cu(16)}") self.emit(f"{out} = OpBitwiseOr %uint {lo} {hi_s}") return out def f16_in(self, s, hi=0): """Read operand ``s`` as an f16 (low half, or high half when ``hi``) widened to f32, then apply its neg/abs. RDNA2's f16 MODE keeps denormals, but on NVIDIA (RTX 5060 Ti, 610.88) UnpackHalf2x16 gives 0 for a denormal that an SDWA BYTE_1 select produced, from an inline constant or a VGPR alike (ps_sdwa_f16_const), while the same denormal in a register or a literal widens right. A half with a zero exponent field is therefore widened exactly with integer ops: sign * mantissa * 2^-24.""" return self.f16_in_bits(s, hi, apply_mods=False)[0] @staticmethod def _f16_const_nan(s, hi=0): """Return True/False when ``s`` (with half ``hi``) is statically NaN/non-NaN, or None at run time.""" if not s or "sdwa_sel" in s: return None if s["k"] == "fimm": return s["v"] != s["v"] if s["k"] == "imm": hv = ((s["v"] & 0xFFFFFFFF) >> (16 if hi else 0)) & 0xFFFF return (hv & 0x7FFF) > 0x7C00 return None def _f16_half_nan(self, h): ab, cond = self.tmp(), self.tmp() self.emit(f"{ab} = OpBitwiseAnd %uint {h} {self.cu(0x7FFF)}") self.emit(f"{cond} = OpUGreaterThan %bool {ab} {self.cu(0x7C00)}") return cond def all_f16_nan_cond(self, half_pairs): """Given ``[(h_uint, const_status), ...]``, return True (all const NaN), None (impossible), or %bool ID.""" if any(st is False for _, st in half_pairs): return None checks = [self._f16_half_nan(h) for h, st in half_pairs if st is None] if not checks: return True cond = checks[0] for c in checks[1:]: nxt = self.tmp() self.emit(f"{nxt} = OpLogicalAnd %bool {cond} {c}") cond = nxt return cond def _f16_half_word(self, u, hi=0): """Extract the selected 16-bit half of ``u`` into ``%uint[15:0]`` (high half shifts cleanly without redundant & 0xFFFF).""" h = self.tmp() if hi: self.emit(f"{h} = OpShiftRightLogical %uint {u} {self.cu(16)}") else: self.emit(f"{h} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}") return h def f16_in_bits(self, s, hi=0, apply_mods=True): """Like ``f16_in``, also returning ``(h_bits, const_nan_status)``; ``h_bits`` keeps abs/neg if ``apply_mods``.""" u = self.src_h(s) v2, f = self.tmp(), self.tmp() self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") self.emit(f"{f} = OpCompositeExtract %float {v2} {1 if hi else 0}") ex, small, mant, mf, den, neg, isneg, sden, out = (self.tmp() for _ in range(9)) h = self._f16_half_word(u, hi) self.emit(f"{ex} = OpBitwiseAnd %uint {h} {self.cu(0x7C00)}") self.emit(f"{small} = OpIEqual %bool {ex} {self.cu(0)}") self.emit(f"{mant} = OpBitwiseAnd %uint {h} {self.cu(0x3FF)}") self.emit(f"{mf} = OpConvertUToF %float {mant}") self.emit(f"{den} = OpFMul %float {mf} {self.fconst(2.0 ** -24)}") self.emit(f"{neg} = OpFNegate %float {den}") self.emit(f"{isneg} = OpUGreaterThanEqual %bool {h} {self.cu(0x8000)}") self.emit(f"{sden} = OpSelect %float {isneg} {neg} {den}") self.emit(f"{out} = OpSelect %float {small} {sden} {f}") h_mod = h if apply_mods: if s.get("abs"): ha = self.tmp() self.emit(f"{ha} = OpBitwiseAnd %uint {h_mod} {self.cu(0x7FFF)}") h_mod = ha if s.get("neg"): hn = self.tmp() self.emit(f"{hn} = OpBitwiseXor %uint {h_mod} {self.cu(0x8000)}") h_mod = hn return self.modify_f(out, s), h_mod, self._f16_const_nan(s, hi) def fma_mix_srcs(self, a, mods): """Read the 3 operands of v_fma_mix*: f16 at op_sel[i] when op_sel_hi[i] is set (via src_h so fimm is binary16), else f32.""" sel = next((m for m in mods if m.startswith("op_sel:")), "op_sel:[0,0,0]") selhi = next((m for m in mods if m.startswith("op_sel_hi:")), "op_sel_hi:[0,0,0]") # A hand-written list shorter than the three operands (op_sel_hi:[0,0]) is padded with 0, as llvm-mc prints it. sb = ([int(x) for x in sel.split("[")[1].rstrip("]").split(",")] + [0, 0, 0])[:3] hb = ([int(x) for x in selhi.split("[")[1].rstrip("]").split(",")] + [0, 0, 0])[:3] # An f32 operand reads as a zero of its sign when it is denormal: the game's MODE flushes f32 denormals # (denorm_mode_32 = 0), measured on gfx1036 for 0x00000001, 0x807fffff and the integer inline constants 1 and # 64 used as f32 operands (@Sanonymous01, SHADER-298). The f16 operands widen to normal f32 values. return [self.f16_in(src, sb[i]) if hb[i] else self.flush_f32(self.src_f(src)) for i, src in enumerate(a[1:4])] def f16_bits(self, f, rtz=False, exact_tiny=False, is_z=None): """f32 ``f`` -> f16 bits in the low 16 bits of a %uint, computed with integer ops only (SHADER-56). GLSL.std.450 PackHalf2x16 leaves the rounding mode to the implementation, and drivers fold a PackHalf2x16 -> UnpackHalf2x16 round trip to a no-op (#513: NVIDIA under --wave64-emulate; #512: RTX 5080), so a following f16 op would see the unrounded f32. Integer ops can't be folded through. ``rtz=False``: round to nearest even, |x| >= 65520 -> inf (v_cvt_f16_f32 and every f16 ALU result). ``rtz=True``: round toward zero, finite values above the range -> +-65504 (v_cvt_pkrtz_f16_f32). f16 denormals are produced (RDNA2's default FP16 denorm mode keeps them); f32 denormal inputs give +-0. NaN -> quiet NaN with the top payload bits kept; +-inf -> +-inf. ``exact_tiny``: the caller guarantees that every ``f`` below 2^-14 in magnitude is already an f16 value (a sum of two f16 values, without omod: a multiple of 2^-24), so that range needs no rounding.""" t = self.tmp x, sgn, sg, a = t(), t(), t(), t() self.emit(f"{x} = OpBitcast %uint {f}") self.emit(f"{sgn} = OpShiftRightLogical %uint {x} {self.cu(16)}") self.emit(f"{sg} = OpBitwiseAnd %uint {sgn} {self.cu(0x8000)}") self.emit(f"{a} = OpBitwiseAnd %uint {x} {self.cu(0x7FFFFFFF)}") # normal range: rebias the exponent (127 -> 15) and drop 13 mantissa bits m, nh = t(), t() self.emit(f"{m} = OpISub %uint {a} {self.cu(0x38000000)}") if rtz: self.emit(f"{nh} = OpShiftRightLogical %uint {m} {self.cu(13)}") else: lsb, bias, mb, = t(), t(), t() self.emit(f"{lsb} = OpBitFieldUExtract %uint {m} {self.cu(13)} {self.cu(1)}") self.emit(f"{bias} = OpIAdd %uint {lsb} {self.cu(0xFFF)}") if is_z: bias = self.unless_rtz(is_z, bias) self.emit(f"{mb} = OpIAdd %uint {m} {bias}") self.emit(f"{nh} = OpShiftRightLogical %uint {mb} {self.cu(13)}") # subnormal range (2^-25 <= |x| < 2^-14): shift the full mantissa right by 126 - e (14..25) e, man, sh, short, shc, sub = t(), t(), t(), t(), t(), t() self.emit(f"{e} = OpShiftRightLogical %uint {a} {self.cu(23)}") self.emit(f"{man} = OpBitwiseOr %uint {self.cu(0x800000)} {self.emit_and(a, 0x7FFFFF)}") self.emit(f"{sh} = OpISub %uint {self.cu(126)} {e}") # min(sh, 25) without GLSL.std.450, so the d16 memory results can use this too (see pack_f16_pair_int) self.emit(f"{short} = OpULessThan %bool {sh} {self.cu(25)}") self.emit(f"{shc} = OpSelect %uint {short} {sh} {self.cu(25)}") self.emit(f"{sub} = OpShiftRightLogical %uint {man} {shc}") # |x| < 2^-25 needs no test of its own: there shc is 25, and man (plus the bias below) shifts out to 0 if not rtz and not exact_tiny: # nearest even, as in the normal range: add half - 1 + the kept low bit, then shift one, half, below, odd, bias2, mb2, sub2 = (t() for _ in range(7)) self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {shc}") self.emit(f"{half} = OpShiftRightLogical %uint {one} {self.cu(1)}") self.emit(f"{below} = OpISub %uint {half} {self.cu(1)}") self.emit(f"{odd} = OpBitwiseAnd %uint {sub} {self.cu(1)}") self.emit(f"{bias2} = OpIAdd %uint {below} {odd}") if is_z: bias2 = self.unless_rtz(is_z, bias2) self.emit(f"{mb2} = OpIAdd %uint {man} {bias2}") self.emit(f"{sub2} = OpShiftRightLogical %uint {mb2} {shc}") sub = sub2 # pick the range isn, big, isinf, isnan = t(), t(), t(), t() self.emit(f"{isn} = OpUGreaterThanEqual %bool {a} {self.cu(0x38800000)}") r1, r2, r3, r4, r5, nanb, res = t(), t(), t(), t(), t(), t(), t() self.emit(f"{r1} = OpSelect %uint {isn} {nh} {sub}") r2 = r1 if rtz: self.emit(f"{big} = OpUGreaterThanEqual %bool {a} {self.cu(0x47800000)}") self.emit(f"{r3} = OpSelect %uint {big} {self.cu(0x7BFF)} {r2}") elif is_z: limit, top = t(), t() self.emit(f"{limit} = OpSelect %uint {is_z} {self.cu(0x47800000)} {self.cu(0x477FF000)}") self.emit(f"{top} = OpSelect %uint {is_z} {self.cu(0x7BFF)} {self.cu(0x7C00)}") self.emit(f"{big} = OpUGreaterThanEqual %bool {a} {limit}") self.emit(f"{r3} = OpSelect %uint {big} {top} {r2}") else: self.emit(f"{big} = OpUGreaterThanEqual %bool {a} {self.cu(0x477FF000)}") self.emit(f"{r3} = OpSelect %uint {big} {self.cu(0x7C00)} {r2}") if rtz or is_z: self.emit(f"{isinf} = OpIEqual %bool {a} {self.cu(0x7F800000)}") self.emit(f"{r4} = OpSelect %uint {isinf} {self.cu(0x7C00)} {r3}") else: r4 = r3 # inf is >= 65520, so the overflow select already gave 0x7C00 pay = t() self.emit(f"{pay} = OpShiftRightLogical %uint {a} {self.cu(13)}") self.emit(f"{nanb} = OpBitwiseOr %uint {self.emit_and(pay, 0x3FF)} {self.cu(0x7E00)}") self.emit(f"{isnan} = OpUGreaterThan %bool {a} {self.cu(0x7F800000)}") self.emit(f"{r5} = OpSelect %uint {isnan} {nanb} {r4}") self.emit(f"{res} = OpBitwiseOr %uint {r5} {sg}") return res def emit_and(self, v, k): r = self.tmp() self.emit(f"{r} = OpBitwiseAnd %uint {v} {self.cu(k)}") return r def f16_res(self, f, exact_tiny=False): """f32 ``f`` -> f16 bits (low 16) as a VALU f16 result rounds it: to nearest even (f16_bits), or, when the program writes MODE.FP_ROUND[3:2], by the current mode in %mode_r16 (0 nearest even, 3 toward zero with f16_bits(rtz=True); 1 and 2 are refused when the setreg is translated). Shaders that never write the field get exactly f16_bits. Integer ops only either way (SHADER-56).""" if not self.round_mode: return self.f16_bits(f, exact_tiny=exact_tiny) m, is_z = self.tmp(), self.tmp() self.emit(f"{m} = OpLoad %uint %mode_r16") self.emit(f"{is_z} = OpIEqual %bool {m} {self.cu(3)}") return self.f16_bits(f, exact_tiny=exact_tiny, is_z=is_z) def unless_rtz(self, is_z, v): r = self.tmp() self.emit(f"{r} = OpSelect %uint {is_z} {self.cu(0)} {v}") return r def f16_round(self, f): """f32 ``f`` -> the f32 nearest f16 value (round to nearest even), i.e. the value an f16 word holds. Used for the interpolation's P10/P20 deltas, which the SPI rounds to f16 (SHADER-468). The bits come from f16_bits, so no driver can fold the round trip away (#512, #513), and UnpackHalf2x16 of integer-built bits is exact for every f16 including the denormals and inf.""" v2, r = self.tmp(), self.tmp() self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {self.f16_bits(f)}") self.emit(f"{r} = OpCompositeExtract %float {v2} 0") return r def f16_omod(self, h, mods): """VOP3 mul:2 / mul:4 / div:2 on the rounded f16 bits ``h`` (low 16) of v_cvt_f16_f32, as measured on RDNA2 (RX 6800 on #718; gfx1036 across wave32/wave64 and MODE RNE/RTZ): after rounding and before clamp, so 65520 div:2 is inf in nearest mode and 32752 (0x77ff) toward zero. The hardware applies an omod to an f16 result only with IEEE off and f16 denormals flushed, and a compiler emits one only for that mode (the corpus argument of the f32 output modifier rows in docs/design.md), so this models that mode: a zero or denormal f16 before the omod (e == 0, including -0.0) gives +0 (0x0000), div:2 underflowing a smallest normal (e == 1) flushes to signed zero (h & 0x8000, so -2^-14 div:2 gives 0x8000), inf and NaN pass through, and finite mul:2/mul:4 overflow gives +-inf in nearest mode and +-65504 (0x7bff / 0xfbff) under MODE toward zero.""" k = next((m for m in mods if m in ("mul:2", "mul:4", "div:2")), None) if k is None: return h d = {"mul:2": 1, "mul:4": 2, "div:2": -1}[k] t = self.tmp sh, e, special, tiny, scaled, r = t(), t(), t(), t(), t(), t() self.emit(f"{sh} = OpShiftRightLogical %uint {h} {self.cu(10)}") self.emit(f"{e} = OpBitwiseAnd %uint {sh} {self.cu(31)}") self.emit(f"{special} = OpIEqual %bool {e} {self.cu(31)}") # Zero and denormal inputs (e == 0) flush to +0 (including -0 -> +0). For div:2, underflowing a # smallest normal (e == 1) flushes to signed zero (h & 0x8000: -2^-14 div:2 -> -0.0 on gfx1036). self.emit(f"{tiny} = OpIEqual %bool {e} {self.cu(0)}") if d < 0: sub_one, under, sign = t(), t(), t() self.emit(f"{sub_one} = OpISub %uint {h} {self.cu(1 << 10)}") self.emit(f"{under} = OpIEqual %bool {e} {self.cu(1)}") self.emit(f"{sign} = OpBitwiseAnd %uint {h} {self.cu(0x8000)}") self.emit(f"{scaled} = OpSelect %uint {under} {sign} {sub_one}") else: add, sign, over, inf, big = t(), t(), t(), t(), t() self.emit(f"{add} = OpIAdd %uint {h} {self.cu(d << 10)}") self.emit(f"{sign} = OpBitwiseAnd %uint {h} {self.cu(0x8000)}") self.emit(f"{over} = OpUGreaterThanEqual %bool {e} {self.cu(31 - d)}") self.emit(f"{inf} = OpBitwiseOr %uint {sign} {self.cu(0x7C00)}") if self.round_mode: m, is_z, top, sel = t(), t(), t(), t() self.emit(f"{m} = OpLoad %uint %mode_r16") self.emit(f"{is_z} = OpIEqual %bool {m} {self.cu(3)}") self.emit(f"{top} = OpBitwiseOr %uint {sign} {self.cu(0x7BFF)}") self.emit(f"{sel} = OpSelect %uint {is_z} {top} {inf}") inf = sel self.emit(f"{big} = OpSelect %uint {over} {inf} {add}") scaled = big z = t() self.emit(f"{z} = OpSelect %uint {tiny} {self.cu(0)} {scaled}") self.emit(f"{r} = OpSelect %uint {special} {h} {z}") return r def sum_toward_zero(self, x, y, r): """f32 ``r`` = x + y (nearest even) for an f16 add/sub that will be narrowed by f16_res. Under MODE toward zero the f32 rounding must not decide the f16 result: x + y = 2 - 2^-24 rounds to 2.0 in f32, but toward zero it is 0x3FFF in f16. When the exact TwoSum error shows r rounded away from zero, step r one f32 ulp toward zero: the exact sum then lies strictly between r and the stepped value, with no f16 value between them, so the toward-zero narrowing gives the exact result. (f16 FMAs don't need this: fma_f16_odd's round-to-odd f32 value narrows exactly in any direction.) The sums here (f16 operands) never overflow or reach f32 subnormals. Returns r unchanged when the program never writes MODE.""" if not self.round_mode: return r bb, t1, t2, t3, e = (self.tmp() for _ in range(5)) self.emit(f"{bb} = OpFSub %float {r} {x}") self.emit(f"{t1} = OpFSub %float {r} {bb}") self.emit(f"{t2} = OpFSub %float {x} {t1}") self.emit(f"{t3} = OpFSub %float {y} {bb}") self.emit(f"{e} = OpFAdd %float {t2} {t3}") rp, rn, ep, en, a1, a2, away, m, isz, step = (self.tmp() for _ in range(10)) self.emit(f"{rp} = OpFOrdGreaterThan %bool {r} %f0") self.emit(f"{rn} = OpFOrdLessThan %bool {r} %f0") self.emit(f"{ep} = OpFOrdGreaterThan %bool {e} %f0") self.emit(f"{en} = OpFOrdLessThan %bool {e} %f0") self.emit(f"{a1} = OpLogicalAnd %bool {rp} {en}") self.emit(f"{a2} = OpLogicalAnd %bool {rn} {ep}") self.emit(f"{away} = OpLogicalOr %bool {a1} {a2}") self.emit(f"{m} = OpLoad %uint %mode_r16") self.emit(f"{isz} = OpIEqual %bool {m} {self.cu(3)}") self.emit(f"{step} = OpLogicalAnd %bool {away} {isz}") u, dec, su = self.tou(r), self.tmp(), self.tmp() self.emit(f"{dec} = OpISub %uint {u} {self.cu(1)}") self.emit(f"{su} = OpSelect %uint {step} {dec} {u}") return self.tof(su) def sum_toward_zero2(self, x, y, r): """sum_toward_zero on each half of v2float operands; returns a v2float.""" if not self.round_mode: return r out = [] for i in (0, 1): xi, yi, ri = self.tmp(), self.tmp(), self.tmp() self.emit(f"{xi} = OpCompositeExtract %float {x} {i}") self.emit(f"{yi} = OpCompositeExtract %float {y} {i}") self.emit(f"{ri} = OpCompositeExtract %float {r} {i}") out.append(self.sum_toward_zero(xi, yi, ri)) v = self.tmp() self.emit(f"{v} = OpCompositeConstruct %v2float {out[0]} {out[1]}") return v def _f32_step_toward_zero(self, r, step): rb, nb, sb, out = (self.tmp() for _ in range(4)) self.emit(f"{rb} = OpBitcast %uint {r}") self.emit(f"{nb} = OpISub %uint {rb} {self.cu(1)}") self.emit(f"{sb} = OpSelect %uint {step} {nb} {rb}") self.emit(f"{out} = OpBitcast %float {sb}") return out def _f32_finite(self, x): i, n, o, f = (self.tmp() for _ in range(4)) self.emit(f"{i} = OpIsInf %bool {x}") self.emit(f"{n} = OpIsNan %bool {x}") self.emit(f"{o} = OpLogicalOr %bool {i} {n}") self.emit(f"{f} = OpLogicalNot %bool {o}") return f def _f32_overflowed(self, r, x, y): ri, fx, fy, both, of = (self.tmp() for _ in range(5)) self.emit(f"{ri} = OpIsInf %bool {r}") fx, fy = self._f32_finite(x), self._f32_finite(y) self.emit(f"{both} = OpLogicalAnd %bool {fx} {fy}") self.emit(f"{of} = OpLogicalAnd %bool {ri} {both}") return of def _f32_away(self, r, e): rp, rn, ep, en, a1, a2, away = (self.tmp() for _ in range(7)) self.emit(f"{rp} = OpFOrdGreaterThan %bool {r} %f0") self.emit(f"{rn} = OpFOrdLessThan %bool {r} %f0") self.emit(f"{ep} = OpFOrdGreaterThan %bool {e} %f0") self.emit(f"{en} = OpFOrdLessThan %bool {e} %f0") self.emit(f"{a1} = OpLogicalAnd %bool {rp} {en}") self.emit(f"{a2} = OpLogicalAnd %bool {rn} {ep}") self.emit(f"{away} = OpLogicalOr %bool {a1} {a2}") return away def f32_sub_rtz(self, x, y): r, bb, t1, t2, t3, e = (self.tmp() for _ in range(6)) self.emit(f"{r} = OpFSub %float {x} {y}") self.emit(f"{bb} = OpFSub %float {r} {x}") self.emit(f"{t1} = OpFSub %float {r} {bb}") self.emit(f"{t2} = OpFSub %float {x} {t1}") self.emit(f"{t3} = OpFAdd %float {y} {bb}") self.emit(f"{e} = OpFSub %float {t2} {t3}") step = self.tmp() self.emit(f"{step} = OpLogicalOr %bool {self._f32_away(r, e)} {self._f32_overflowed(r, x, y)}") return self._f32_step_toward_zero(r, step) def f32_mul_rtz(self, x, y): m = self.tmp() self.emit(f"{m} = OpFMul %float {x} {y}") def mant(v): b, k, s, f, ex, nz, nm, ok = (self.tmp() for _ in range(8)) self.emit(f"{b} = OpBitcast %uint {v}") self.emit(f"{k} = OpBitwiseAnd %uint {b} {self.cu(0x007FFFFF)}") self.emit(f"{s} = OpBitwiseOr %uint {k} {self.cu(0x3F800000)}") self.emit(f"{f} = OpBitcast %float {s}") self.emit(f"{ex} = OpBitFieldUExtract %uint {b} {self.cu(23)} {self.cu(8)}") self.emit(f"{nz} = OpINotEqual %bool {ex} {self.cu(0)}") self.emit(f"{nm} = OpINotEqual %bool {ex} {self.cu(0xFF)}") self.emit(f"{ok} = OpLogicalAnd %bool {nz} {nm}") return f, ok def split(v): c, d, hi_, lo_ = (self.tmp() for _ in range(4)) self.emit(f"{c} = OpFMul %float {self.tof(self.cu(0x45801000))} {v}") self.emit(f"{d} = OpFSub %float {c} {v}") self.emit(f"{hi_} = OpFSub %float {c} {d}") self.emit(f"{lo_} = OpFSub %float {v} {hi_}") return hi_, lo_ xm, xok = mant(x) ym, yok = mant(y) p = self.tmp() self.emit(f"{p} = OpFMul %float {xm} {ym}") (xh, xl), (yh, yl) = split(xm), split(ym) hh, hl, lh, ll, e1, e2, e3, e = (self.tmp() for _ in range(8)) self.emit(f"{hh} = OpFMul %float {xh} {yh}") self.emit(f"{hl} = OpFMul %float {xh} {yl}") self.emit(f"{lh} = OpFMul %float {xl} {yh}") self.emit(f"{ll} = OpFMul %float {xl} {yl}") self.emit(f"{e1} = OpFSub %float {hh} {p}") self.emit(f"{e2} = OpFAdd %float {e1} {hl}") self.emit(f"{e3} = OpFAdd %float {e2} {lh}") self.emit(f"{e} = OpFAdd %float {e3} {ll}") over, normals, mfin, valid, step = (self.tmp() for _ in range(5)) self.emit(f"{over} = OpFOrdLessThan %bool {e} %f0") self.emit(f"{normals} = OpLogicalAnd %bool {xok} {yok}") mf = self._f32_finite(m) self.emit(f"{mfin} = OpLogicalAnd %bool {normals} {mf}") self.emit(f"{valid} = OpLogicalAnd %bool {mfin} {over}") self.emit(f"{step} = OpLogicalOr %bool {valid} {self._f32_overflowed(m, x, y)}") return self._f32_step_toward_zero(m, step) def f64_add_mode(self, x, y, r, lo, hi): """v_add_f64 under MODE.FP_ROUND[3:2]: ``r`` = x + y rounded to nearest (bits lo/hi). When the mode is toward zero (3) and the nearest result rounded away from zero, step one ulp back. Ordering the operands so |a| >= |b| keeps FastTwoSum (bb = r - a, e = b - bb; every float op is NoContraction) inside +-DBL_MAX whenever ``r`` is finite (``|r - a| <= max(|r|, |a|) <= DBL_MAX``), whereas unordered TwoSum ``r - x`` can overflow to +-inf and turn ``e`` into NaN when |x| < |y| with opposite signs near +-DBL_MAX; r was rounded away from zero when e and r have opposite signs. A finite sum that overflowed to inf becomes +-DBL_MAX. Returns the new (lo, hi).""" xv, xlo, xhi, yv, ylo, yhi, axhi, ayhi = (self.tmp() for _ in range(8)) self.emit(f"{xv} = OpBitcast %v2uint_d {x}") self.emit(f"{xlo} = OpCompositeExtract %uint {xv} 0") self.emit(f"{xhi} = OpCompositeExtract %uint {xv} 1") self.emit(f"{yv} = OpBitcast %v2uint_d {y}") self.emit(f"{ylo} = OpCompositeExtract %uint {yv} 0") self.emit(f"{yhi} = OpCompositeExtract %uint {yv} 1") mask = self.cu(0x7FFFFFFF) self.emit(f"{axhi} = OpBitwiseAnd %uint {xhi} {mask}") self.emit(f"{ayhi} = OpBitwiseAnd %uint {yhi} {mask}") hlt, heq, llt, tie, swap, a, b = (self.tmp() for _ in range(7)) self.emit(f"{hlt} = OpULessThan %bool {axhi} {ayhi}") self.emit(f"{heq} = OpIEqual %bool {axhi} {ayhi}") self.emit(f"{llt} = OpULessThan %bool {xlo} {ylo}") self.emit(f"{tie} = OpLogicalAnd %bool {heq} {llt}") self.emit(f"{swap} = OpLogicalOr %bool {hlt} {tie}") self.emit(f"{a} = OpSelect %double {swap} {y} {x}") self.emit(f"{b} = OpSelect %double {swap} {x} {y}") bb, e = self.tmp(), self.tmp() self.emit(f"{bb} = OpFSub %double {r} {a}") self.emit(f"{e} = OpFSub %double {b} {bb}") z2, zd = self.tmp(), self.tmp() self.emit(f"{z2} = OpCompositeConstruct %v2uint_d {self.cu(0)} {self.cu(0)}") self.emit(f"{zd} = OpBitcast %double {z2}") en, rp, ep, rn, a1, a2, away = (self.tmp() for _ in range(7)) self.emit(f"{rp} = OpFOrdGreaterThan %bool {r} {zd}") self.emit(f"{rn} = OpFOrdLessThan %bool {r} {zd}") self.emit(f"{en} = OpFOrdLessThan %bool {e} {zd}") self.emit(f"{ep} = OpFOrdGreaterThan %bool {e} {zd}") self.emit(f"{a1} = OpLogicalAnd %bool {rp} {en}") self.emit(f"{a2} = OpLogicalAnd %bool {rn} {ep}") self.emit(f"{away} = OpLogicalOr %bool {a1} {a2}") # overflow: r is inf while x and y are finite ri, xi, yi, xn, yn, xs, ys, xf, of = (self.tmp() for _ in range(9)) self.emit(f"{ri} = OpIsInf %bool {r}") self.emit(f"{xi} = OpIsInf %bool {x}") self.emit(f"{yi} = OpIsInf %bool {y}") self.emit(f"{xn} = OpIsNan %bool {x}") self.emit(f"{yn} = OpIsNan %bool {y}") self.emit(f"{xs} = OpLogicalOr %bool {xi} {xn}") self.emit(f"{ys} = OpLogicalOr %bool {yi} {yn}") self.emit(f"{xf} = OpLogicalOr %bool {xs} {ys}") nf = self.tmp() self.emit(f"{nf} = OpLogicalNot %bool {xf}") self.emit(f"{of} = OpLogicalAnd %bool {ri} {nf}") step, any_, m, isz = (self.tmp() for _ in range(4)) self.emit(f"{any_} = OpLogicalOr %bool {away} {of}") self.emit(f"{m} = OpLoad %uint %mode_r16") self.emit(f"{isz} = OpIEqual %bool {m} {self.cu(3)}") self.emit(f"{step} = OpLogicalAnd %bool {any_} {isz}") # one ulp toward zero on the magnitude bits: (hi:lo) - 1 (inf - 1 = DBL_MAX) nlo, bor, bu, nhi, rlo, rhi = (self.tmp() for _ in range(6)) self.emit(f"{nlo} = OpISub %uint {lo} {self.cu(1)}") self.emit(f"{bor} = OpIEqual %bool {lo} {self.cu(0)}") self.emit(f"{bu} = OpSelect %uint {bor} {self.cu(1)} {self.cu(0)}") self.emit(f"{nhi} = OpISub %uint {hi} {bu}") self.emit(f"{rlo} = OpSelect %uint {step} {nlo} {lo}") self.emit(f"{rhi} = OpSelect %uint {step} {nhi} {hi}") return rlo, rhi def mode_write(self, op, a): """s_setreg* on HW_REG_MODE. Only FP_ROUND[3:2] (f16/f64 rounding) is modelled, the one MODE field the corpus writes (9,417 writes: value 3 = toward zero 6,694, value 0 = nearest even 2,723). A write that reaches another MODE bit or only part of the field, sets directed rounding (+inf/-inf), or takes its value from an SGPR is refused, so nothing changes silently. Other hardware registers (FLAT_SCR, POPS packer) are not MODE: ignored.""" t = a[0].get("t", "") if a and a[0]["k"] == "special" else "" m = re.match(r"hwreg\((\w+)(?:,\s*(\d+),\s*(\d+))?\)", t) if not m or m.group(1) != "HW_REG_MODE": return off, size = (int(m.group(2)), int(m.group(3))) if m.group(2) else (0, 32) if (off, size) != (2, 2): raise Unsupported(f"{op} on MODE bits {off}..{off + size - 1} (only FP_ROUND[3:2] as a whole is modelled)") if op != "s_setreg_imm32_b32" or a[1]["k"] != "imm": raise Unsupported(f"{op} with a register value on MODE.FP_ROUND") self.write_half_round_mode(op, a[1]["v"] & 3) def write_half_round_mode(self, op: str, mode: int) -> None: if mode in (1, 2): raise Unsupported(f"{op}: MODE.FP_ROUND[3:2] directed rounding (+inf/-inf)") self.emit(f"OpStore %mode_r16 {self.cu(mode)}") def emit_ne0(self, v): r = self.tmp() self.emit(f"{r} = OpINotEqual %bool {v} {self.cu(0)}") return r def emit_fma(self, r, x, y, z): """r = x * y + z as an f32 multiply-add with ONE rounding, which is what RDNA2's v_fma_* do. GLSL.std.450 Fma is specified in the Vulkan environment as "inherited from OpFMul followed by OpFAdd", so a driver may round twice. With --fma khr it is OpFmaKHR instead: "correctly rounded" (SPV_KHR_fma), which needs VK_KHR_shader_fma + shaderFmaFloat32 and is recorded in the index as capability FMAKHR.""" if FMA_KHR: self.uses_fma_khr = self.uses_fma_khr32 = True self.emit(f"{r} = OpFmaKHR %float {x} {y} {z}") elif FMA_EXACT: self.fma_exact(r, x, y, z) else: self.emit(f"{r} = OpExtInst %float %glsl Fma {x} {y} {z}") def emit_fma64(self, r, x, y, z): """r = x * y + z on doubles with ONE rounding, as RDNA2's f64 multiply-adds do. GLSL.std.450 Fma may round twice here as for f32, and NVIDIA's driver does when it folds an all-constant Fma at pipeline compile time (run-time operands are fused there) (RTX 4090, 621.24: the fma(a, a, c) cancellation probe with a = 1 + 2^-30 gives 0, not 2^-60). With --fma khr it is OpFmaKHR on doubles, which needs VK_KHR_shader_fma + shaderFmaFloat64 (feature shaderFmaFloat64 in the index). --fma exact has no f64 form and keeps Fma.""" if FMA_KHR: self.uses_fma_khr = self.uses_fma_khr64 = True self.emit(f"{r} = OpFmaKHR %double {x} {y} {z}") else: self.emit(f"{r} = OpExtInst %double %glsl Fma {x} {y} {z}") def fma_exact(self, r, x, y, z): """r = x * y + z rounded once to f32, built from single-rounded NoContraction f32 operations (--fma exact, SHADER-497): for a device whose driver splits GLSL Fma into two roundings and that has no VK_KHR_shader_fma (Intel UHD Graphics, Xe-LP, Windows driver 101.7088: cs_fma_fused words 0, 2, 3 and 5 split). Boldo and Melquiond's emulated FMA ("Emulation of a FMA and correctly-rounded sums: proved algorithms using rounding to odd", IEEE Transactions on Computers 57(4), 2008): p + pe = x * y exactly (Dekker's product; the factors are split into 12-bit halves by masking the low 12 mantissa bits, so the split cannot overflow), th + tl = z + p exactly (TwoSum), v = tl + pe rounded to odd (as fma_f16_odd), and r = th + v rounded to nearest, or th when v is zero (th + 0 would turn a -0 sum into +0). That needs every intermediate in the f32 normal range, so the operands are first scaled by powers of two, which is exact, and the result scaled back: by 2^-64 when the product or z is at least 2^126 (the product may overflow while z brings the sum back into range; a z below 2^-62 there, which would scale out of the normal range, becomes a signed 2^-126, see below), by 2^96 when both are tiny (|x*y| < 2^-76 and |z| < 2^-46), and a factor below 2^-100 is traded 2^64 against one above 2^-20, so the low split halves stay normal on a driver that flushes f32 denormals. Infinite or NaN operands, and finite ones whose product is beyond even the scaled range (the result is +-inf), take the plain Fma, except that finite x and y with an infinite z give z (a split Fma turns an overflowing x*y and the other infinity into a NaN), and normal x and y with a zero z give the rounded x*y (the split path turns an underflowing negative product plus +0 into +0, not -0). Exact (checked against an exact rational reference in tests/semantic/test_fma_exact.py) for finite operands with a normal or zero result, with f32 denormals kept or flushed; a result in the denormal range is scaled back with a second rounding, and a denormal operand follows the driver's denormal mode, as for every f32 operation here.""" t = self.tmp one = "%f1" def op(name, *args, ty="%float"): o = t() self.emit(f"{o} = {name} {ty} {' '.join(args)}") return o def mag(v): return op("OpBitwiseAnd", op("OpBitcast", v, ty="%uint"), self.cu(0x7FFFFFFF), ty="%uint") def below(m, k): return op("OpULessThan", m, self.cu(k), ty="%bool") def above(m, k): return op("OpUGreaterThan", m, self.cu(k), ty="%bool") def sel(c, a, b): return op("OpSelect", c, a, b) up64, dn64, up96, dn96 = (self.fconst(2.0 ** e) for e in (64, -64, 96, -96)) mx, my, mz = mag(x), mag(y), mag(z) p0 = op("OpFMul", x, y) mp0 = mag(p0) big = op("OpLogicalOr", above(mp0, 0x7E7FFFFF), above(mz, 0x7E7FFFFF), ty="%bool") # >= 2^126 (or inf) tiny = self.emit_land(below(mp0, 0x19800000), below(mz, 0x28800000)) # < 2^-76, < 2^-46 xsm = op("OpULessThan", mx, my, ty="%bool") # big: the larger factor and z down by 2^64; tiny: the smaller factor and z up by 2^96; the result back. fx = sel(big, sel(xsm, one, dn64), sel(tiny, sel(xsm, up96, one), one)) fy = sel(big, sel(xsm, dn64, one), sel(tiny, sel(xsm, one, up96), one)) fz = sel(big, dn64, sel(tiny, up96, one)) fr = sel(big, up64, sel(tiny, dn96, one)) x1, y1 = op("OpFMul", x, fx), op("OpFMul", y, fy) # big and 0 < |z| < 2^-62: z * 2^-64 would drop below 2^-126 (to 0, or to a denormal a flushing driver drops). # The product is at least 2^126, so its last bit is at least 2^79 and z can only break a tie of it; a signed # 2^-126 keeps that, as v_div_fmas_f32 does for its own pre-scaling. lost = self.emit_land(big, self.emit_land(above(mz, 0), below(mz, 0x20800000))) zst = op("OpBitcast", op("OpBitwiseOr", op("OpBitwiseAnd", op("OpBitcast", z, ty="%uint"), self.cu(0x80000000), ty="%uint"), self.cu(0x00800000), ty="%uint")) z1 = sel(lost, zst, op("OpFMul", z, fz)) # A factor below 2^-100 next to one above 2^-20: trade 2^64 between them (the product is unchanged). mx1, my1 = mag(x1), mag(y1) bx = self.emit_land(below(mx1, 0x0D800000), above(my1, 0x35800000)) by = self.emit_land(below(my1, 0x0D800000), above(mx1, 0x35800000)) xa = op("OpFMul", x1, sel(bx, up64, sel(by, dn64, one))) ya = op("OpFMul", y1, sel(bx, dn64, sel(by, up64, one))) # Dekker's product: p + pe = xa * ya, every partial product exact (12 x 12 bits). p = op("OpFMul", xa, ya) halves = [] for v in (xa, ya): hi = op("OpBitcast", op("OpBitwiseAnd", op("OpBitcast", v, ty="%uint"), self.cu(0xFFFFF000), ty="%uint")) halves += [hi, op("OpFSub", v, hi)] xh, xl, yh, yl = halves t1 = op("OpFSub", op("OpFMul", xh, yh), p) t2 = op("OpFAdd", t1, op("OpFMul", xh, yl)) t3 = op("OpFAdd", t2, op("OpFMul", xl, yh)) pe = op("OpFAdd", t3, op("OpFMul", xl, yl)) def two_sum(a, b): s = op("OpFAdd", a, b) bb = op("OpFSub", s, a) e = op("OpFAdd", op("OpFSub", a, op("OpFSub", s, bb)), op("OpFSub", b, bb)) return s, e th, tl = two_sum(p, z1) # v = tl + pe rounded to odd: the nearest sum, moved one ulp towards its error when inexact and even. s, e = two_sum(tl, pe) sbits, ebits = op("OpBitcast", s, ty="%uint"), op("OpBitcast", e, ty="%uint") even = op("OpIEqual", op("OpBitwiseAnd", sbits, self.cu(1), ty="%uint"), self.cu(0), ty="%bool") inexact = self.emit_land(op("OpFUnordNotEqual", e, "%f0", ty="%bool"), op("OpFOrdEqual", e, e, ty="%bool")) same = below(op("OpBitwiseXor", sbits, ebits, ty="%uint"), 0x80000000) # same sign: away from zero adj = op("OpSelect", same, op("OpIAdd", sbits, self.cu(1), ty="%uint"), op("OpISub", sbits, self.cu(1), ty="%uint"), ty="%uint") v = op("OpBitcast", op("OpSelect", self.emit_land(even, inexact), adj, sbits, ty="%uint")) rs = sel(op("OpFOrdEqual", v, "%f0", ty="%bool"), th, op("OpFAdd", th, v)) # z = +-0 with normal x and y: the exact x*y + z is x*y, which is not zero, so the one rounding of x*y is the # result. The split path loses the sign of a product that underflows even after the 2^96 scale: p rounds to # -0, th = p + z1 is -0 + +0 = +0, and so is the result where the exact one is -0. xy_normal = self.emit_land(above(mx, 0x007FFFFF), above(my, 0x007FFFFF)) times = self.emit_land(op("OpIEqual", mz, self.cu(0), ty="%bool"), xy_normal) rr = sel(times, p0, op("OpFMul", rs, fr)) special = op("OpLogicalOr", op("OpLogicalOr", above(mx, 0x7F7FFFFF), above(my, 0x7F7FFFFF), ty="%bool"), op("OpLogicalOr", above(mz, 0x7F7FFFFF), op("OpIsNan", rr, ty="%bool"), ty="%bool"), ty="%bool") g = op("OpExtInst", "%glsl Fma", x, y, z) # Finite x and y with an infinite z give z. A split Fma would round x*y first, and when that overflows to the # other infinity the sum is a NaN. xyfin = op("OpLogicalNot", op("OpLogicalOr", above(mx, 0x7F7FFFFF), above(my, 0x7F7FFFFF), ty="%bool"), ty="%bool") g = sel(self.emit_land(xyfin, op("OpIEqual", mz, self.cu(0x7F800000), ty="%bool")), z, g) self.emit(f"{r} = OpSelect %float {special} {g} {rr}") def fma_f16_odd(self, x, y, z): """fma(x, y, z) for f16 inputs (widened to f32), rounded to f32 with round-to-odd (SHADER-55). RDNA2's v_fma_f16 / v_fmac_f16 / v_pk_fma_f16 round once, to f16 (measured: 0 of 12,612 mismatches against a correctly rounded f16 FMA on an RX 6700, #374). GLSL Fma rounds to f32 first, so narrowing it to f16 is a double rounding that can be 1 ulp off. Here: x*y is exact in f32 (11-bit significands give 22 bits, and the f16 range squared stays inside the f32 normal range), TwoSum splits p + z into the rounded sum s and its exact error, and when the error is non-zero and s is even, s moves one f32 ulp towards the error. That makes s the round-to-odd f32 value of the exact result, and round-to-odd at 24 bits then rounds correctly to any format with at most 22 bits, so f16_bits gives the single-rounded f16. The FAdd/FMul carry NoContraction (no_contraction), so the driver can't fuse or reorder TwoSum.""" t = self.tmp pr, s_, bb, sb, da, db, err = (t() for _ in range(7)) self.emit(f"{pr} = OpFMul %float {x} {y}") self.emit(f"{s_} = OpFAdd %float {pr} {z}") self.emit(f"{bb} = OpFSub %float {s_} {pr}") self.emit(f"{sb} = OpFSub %float {s_} {bb}") self.emit(f"{da} = OpFSub %float {pr} {sb}") self.emit(f"{db} = OpFSub %float {z} {bb}") self.emit(f"{err} = OpFAdd %float {da} {db}") sbits, ebits, lsb, even, nz, fin, need, same, xs, up, dn, adj, res, r = (t() for _ in range(14)) self.emit(f"{sbits} = OpBitcast %uint {s_}") self.emit(f"{ebits} = OpBitcast %uint {err}") self.emit(f"{lsb} = OpBitwiseAnd %uint {sbits} {self.cu(1)}") self.emit(f"{even} = OpIEqual %bool {lsb} {self.cu(0)}") self.emit(f"{nz} = OpFUnordNotEqual %bool {err} %f0") # true for a NaN error too... self.emit(f"{fin} = OpFOrdEqual %bool {err} {err}") # ...so require a non-NaN error self.emit(f"{need} = OpLogicalAnd %bool {even} {self.emit_land(nz, fin)}") self.emit(f"{xs} = OpBitwiseXor %uint {sbits} {ebits}") self.emit(f"{same} = OpULessThan %bool {xs} {self.cu(0x80000000)}") # same sign: away from zero self.emit(f"{up} = OpIAdd %uint {sbits} {self.cu(1)}") self.emit(f"{dn} = OpISub %uint {sbits} {self.cu(1)}") self.emit(f"{adj} = OpSelect %uint {same} {up} {dn}") self.emit(f"{res} = OpSelect %uint {need} {adj} {sbits}") self.emit(f"{r} = OpBitcast %float {res}") return r def fma_mix_odd(self, x, y, z): """fma(x, y, z) for f32 operands rounded to f32 with round-to-odd, so that narrowing it to f16 in any direction gives the exactly rounded f16 (the hardware rounds v_fma_mix once, straight to f16, under MODE toward zero). Unlike fma_f16_odd the product is not exact in f32: r = Fma (nearest) is corrected by the sign of exact - r = (s - r) + (se + pe), where p = x*y, pe = Fma(x, y, -p) is the exact product error, s = p + z and se the TwoSum error of that sum. When that is non-zero and r is even, r moves one f32 ulp towards it (the exact value lies between r and its neighbour, so the neighbour is the odd one). A zero, infinite or NaN r is left alone (an f32 subnormal narrows to +-0 either way), except that a finite exact value whose f32 Fma overflowed to +-inf becomes +-FLT_MAX (toward zero it is 65504 in f16). A tiny product takes the residual sign from its operands (below). Sign-exact except where se + pe itself rounds to the opposite side of s - r, which needs an f32-ulp-level cancellation, or where x*y overflows while z cancels it.""" t = self.tmp r, p, np_, pe, s_, bb, sb, da, db, se = (t() for _ in range(10)) self.emit_fma(r, x, y, z) self.emit(f"{p} = OpFMul %float {x} {y}") self.emit(f"{np_} = OpFNegate %float {p}") self.emit_fma(pe, x, y, np_) self.emit(f"{s_} = OpFAdd %float {p} {z}") self.emit(f"{bb} = OpFSub %float {s_} {p}") self.emit(f"{sb} = OpFSub %float {s_} {bb}") self.emit(f"{da} = OpFSub %float {p} {sb}") self.emit(f"{db} = OpFSub %float {z} {bb}") self.emit(f"{se} = OpFAdd %float {da} {db}") tt, d0, res = t(), t(), t() self.emit(f"{tt} = OpFAdd %float {se} {pe}") self.emit(f"{d0} = OpFSub %float {s_} {r}") self.emit(f"{res} = OpFAdd %float {d0} {tt}") rbits, mag, lsb, even, nzr, ok, need = (t() for _ in range(7)) self.emit(f"{rbits} = OpBitcast %uint {r}") self.emit(f"{mag} = OpBitwiseAnd %uint {rbits} {self.cu(0x7FFFFFFF)}") self.emit(f"{lsb} = OpBitwiseAnd %uint {rbits} {self.cu(1)}") self.emit(f"{even} = OpIEqual %bool {lsb} {self.cu(0)}") self.emit(f"{nzr} = OpULessThan %bool {self.cu(0)} {mag}") self.emit(f"{ok} = OpULessThan %bool {mag} {self.cu(0x7F800000)}") # finite rnz, rfin = t(), t() self.emit(f"{rnz} = OpFUnordNotEqual %bool {res} %f0") # true for a NaN residual too... self.emit(f"{rfin} = OpFOrdEqual %bool {res} {res}") # ...so require a non-NaN one inexact = self.emit_land(rnz, rfin) # A tiny product (|x*y| < 2^-64, or flushed to 0) has its error pe below the f32 normal range (pe's lowest bit is # 2^-47 of p's), so pe and the residual can underflow or be flushed and read as exact. z dominates there # (anything the f16 result can see has an f32 ulp far above 2^-64), so the residual's sign is the # product's: sign(x) xor sign(y), whatever the driver does with denormals. xb, yb, pb, pmag, ptiny, xnz, ynz, tiny, tsign, ebits0 = (t() for _ in range(10)) self.emit(f"{pb} = OpBitcast %uint {p}") self.emit(f"{pmag} = OpBitwiseAnd %uint {pb} {self.cu(0x7FFFFFFF)}") self.emit(f"{ptiny} = OpULessThan %bool {pmag} {self.cu(0x1F800000)}") self.emit(f"{xnz} = OpFUnordNotEqual %bool {x} %f0") self.emit(f"{ynz} = OpFUnordNotEqual %bool {y} %f0") self.emit(f"{tiny} = OpLogicalAnd %bool {ptiny} {self.emit_land(xnz, ynz)}") self.emit(f"{xb} = OpBitcast %uint {x}") self.emit(f"{yb} = OpBitcast %uint {y}") self.emit(f"{tsign} = OpBitwiseXor %uint {xb} {yb}") inexact2, ebits = t(), t() self.emit(f"{inexact2} = OpLogicalOr %bool {inexact} {tiny}") self.emit(f"{need} = OpLogicalAnd %bool {self.emit_land(even, inexact2)} {self.emit_land(nzr, ok)}") self.emit(f"{ebits0} = OpBitcast %uint {res}") self.emit(f"{ebits} = OpSelect %uint {tiny} {tsign} {ebits0}") xs, same, up, dn, adj, out, rr = (t() for _ in range(7)) self.emit(f"{xs} = OpBitwiseXor %uint {rbits} {ebits}") self.emit(f"{same} = OpULessThan %bool {xs} {self.cu(0x80000000)}") # same sign: away from zero self.emit(f"{up} = OpIAdd %uint {rbits} {self.cu(1)}") self.emit(f"{dn} = OpISub %uint {rbits} {self.cu(1)}") self.emit(f"{adj} = OpSelect %uint {same} {up} {dn}") self.emit(f"{out} = OpSelect %uint {need} {adj} {rbits}") self.emit(f"{rr} = OpBitcast %float {out}") # Fma overflowed to +-inf with finite operands: the exact value is finite, so toward zero it is +-FLT_MAX. ri, xi, yi, zi, anyi, ovf, sg, mx, fin, rfl = (t() for _ in range(10)) self.emit(f"{ri} = OpIsInf %bool {r}") self.emit(f"{xi} = OpIsInf %bool {x}") self.emit(f"{yi} = OpIsInf %bool {y}") self.emit(f"{zi} = OpIsInf %bool {z}") xyi, nai = t(), t() self.emit(f"{xyi} = OpLogicalOr %bool {xi} {yi}") self.emit(f"{anyi} = OpLogicalOr %bool {xyi} {zi}") self.emit(f"{nai} = OpLogicalNot %bool {anyi}") self.emit(f"{ovf} = OpLogicalAnd %bool {ri} {nai}") self.emit(f"{sg} = OpBitwiseAnd %uint {rbits} {self.cu(0x80000000)}") self.emit(f"{mx} = OpBitwiseOr %uint {sg} {self.cu(0x7F7FFFFF)}") self.emit(f"{fin} = OpSelect %uint {ovf} {mx} {out}") self.emit(f"{rfl} = OpBitcast %float {fin}") return rfl def emit_land(self, a, b): r = self.tmp() self.emit(f"{r} = OpLogicalAnd %bool {a} {b}") return r def eager(self, ty, val): """val (a %uint or %bool), stored to a Function variable of its own and loaded back (SHADER-529). SPIRV-Cross (MoltenVK) inlines a result used once into the expression that uses it. On the right of an OpLogicalAnd/OpLogicalOr that is a short-circuiting && / ||, and in an arm of a scalar OpSelect a ternary, so a subgroup op there runs only in the lanes that get that far: a ballot misses the other lanes' bits and a shuffle reads from lanes that never ran it. A store is a statement, which every lane runs.""" ptr = {"%uint": "%_ptr_Function_uint", "%bool": "%_ptr_Function_bool"}[ty] var = f"%eager{len(self.eager_vars)}" self.eager_vars.append((var, ptr)) self.emit(f"OpStore {var} {val}") r = self.tmp() self.emit(f"{r} = OpLoad {ty} {var}") return r def f16_pack2(self, lo, hi, exact_tiny=False): """Two f32 values -> one %uint of two f16 halves (lo | hi << 16), each rounded as f16_res, without PackHalf2x16.""" a, b, sh, r = self.f16_res(lo, exact_tiny), self.f16_res(hi, exact_tiny), self.tmp(), self.tmp() self.emit(f"{sh} = OpShiftLeftLogical %uint {b} {self.cu(16)}") self.emit(f"{r} = OpBitwiseOr %uint {a} {sh}") return r def put_f16_bits(self, d, lo, hi=0): """Write 16-bit %uint ``lo`` into the low half of ``d``, or to the high half when ``hi``, keeping the other half.""" if not hi: self.write_lo16(d, lo) return if d["k"] != "vgpr": raise Unsupported("op_sel destination") old, keep, sh16, v = (self.tmp() for _ in range(4)) self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', d['r'])}") self.emit(f"{keep} = OpBitwiseAnd %uint {old} {self.cu(0xFFFF)}") self.emit(f"{sh16} = OpShiftLeftLogical %uint {lo} {self.cu(16)}") self.emit(f"{v} = OpBitwiseOr %uint {keep} {sh16}") self.dst(d, v) def f16_out(self, d, r, hi=0, fract=False, mode=True, exact_tiny=False): """Narrow f32 ``r`` to f16 (f16_res: nearest even, or toward zero under MODE) and write it to the low half of ``d``, or to the high half when ``hi`` (op_sel destination bit). Either way the other half is kept (see write_lo16). ``fract`` (v_fract_f16): a result that rounded up to 1.0 (0x3c00) becomes 0x3bff, the largest f16 below 1, as on hardware (docs/design.md, float min/max/med3 with NaN and v_fract).""" lo = self.f16_res(r, exact_tiny) if mode else self.f16_bits(r) # mode=False: the op ignores MODE rounding (rcp/rsq/sqrt) if fract: one, below = self.tmp(), self.tmp() self.emit(f"{one} = OpIEqual %bool {lo} {self.cu(0x3C00)}") self.emit(f"{below} = OpSelect %uint {one} {self.cu(0x3BFF)} {lo}") lo = below self.put_f16_bits(d, lo, hi) def f16_roundtrip(self, f): """f32 -> f16 -> f32 (round to nearest; f16 denormals flushed to signed zero), modelling a 32-bit v_interp read of a 16-bit interpolant (FSSM pixel-input table flag bit 4 marks the position; see the PS input path in translate). OpQuantizeToF16 returns +0 or -0 when the magnitude is too small for a normal f16, and the spec pins no rounding mode (round-to-nearest is measured on hardware, not guaranteed). Do not reuse this helper where f16 denormals or a specific rounding mode matter. Single OpQuantizeToF16 instruction on purpose: a PackHalf2x16/UnpackHalf2x16 round-trip is observably folded to a no-op by at least one Vulkan driver (RTX 5080, validated), while a lone OpQuantizeToF16 is implemented as a real conversion.""" r = self.tmp() self.emit(f"{r} = OpQuantizeToF16 %float {f}") return r def f16_rtz(self, f): """f32 -> f16 bits (low 16) with round-toward-zero, as v_cvt_pkrtz does. Finite values above the f16 range become +-65504, never inf; inf/NaN stay inf/NaN. Integer-only (f16_bits): the earlier PackHalf2x16 -> UnpackHalf2x16 -> compare version relied on the round trip not being folded, and on llvmpipe and NVIDIA it was (FUZZ-2: v_cvt_pkrtz_f16_f32 gave the nearest value, one ulp above RTZ).""" return self.f16_bits(f, rtz=True) def modify_f(self, f, a): return self.tof(self.modify(self.tou(f), a)) def host_addr(self, xbox_va, kind="load", extent=4): """Add the sign-extended 48-bit effective VA to the heap base built in the entry block. --address-guard: the address is checked against the runtime's page table first (guard_addr). `kind` is "load", "store" or "rmw" (an atomic): a refused load reads the zero area, a refused store or atomic the dump area. `extent` is the bytes the access spans from this address: an int, or for a run-time span a callable that emits it and returns the %ulong id of extent - 1 (guard_delta), called only with the guard so the unguarded module stays byte for byte the same. Its first and last byte are checked.""" # V# truncates device_address - heap_base to 48 bits, including when an import lies below the heap. # Extend after adding byte offsets. Console user VAs and full-width root VAs already fit signed 48 bits. shift = self.cu(16) high, offset, r = (self.tmp() for _ in range(3)) self.emit(f"{high} = OpShiftLeftLogical %ulong {xbox_va} {shift}") self.emit(f"{offset} = OpShiftRightArithmetic %ulong {high} {shift}") self.emit(f"{r} = OpIAdd %ulong %heap_base {offset}") self.uses_heap = True self.cu(1), self.cu(2) # member indices of the push-constant block, declared before assembly if not ADDRESS_GUARD: return r return self.guard_addr(offset, r, kind, extent) def guard_delta(self, n, step): """--address-guard: the %ulong id of (bytes spanned - 1) for n dwords (an int, or a %uint id of at least 1), linear (step None) or each `step` bytes apart (a %uint id: a swizzled buffer access, buf_dword_ptr).""" if isinstance(n, int) and (step is None or n == 1): return self.cl(4 * n - 1) if isinstance(n, int): n1 = self.cu(n - 1) else: zero, dec, n1 = self.tmp(), self.tmp(), self.tmp() self.emit(f"{zero} = OpIEqual %bool {n} {self.cu(0)}") self.emit(f"{dec} = OpISub %uint {n} {self.cu(1)}") self.emit(f"{n1} = OpSelect %uint {zero} {self.cu(0)} {dec}") m, m64, d = self.tmp(), self.tmp(), self.tmp() self.emit(f"{m} = OpIMul %uint {n1} {step if step is not None else self.cu(4)}") self.emit(f"{m64} = OpUConvert %ulong {m}") self.emit(f"{d} = OpIAdd %ulong {m64} {self.cl(3)}") return d def guard_addr(self, offset, unguarded, kind, extent): """--address-guard: the host address of the access at heap offset `offset` (sign-extended 48 bits): itself when the runtime backs its first and last byte (or the runtime's guard is off), else a place in the arena's zero area (a load) or dump area (a store, an atomic) at the same offset within a 4 KiB page, so alignment holds. One call of %guard_fn (an arena offset passes on a compare; any other looks up two page-table bits).""" self.uses_guard = True delta = self.cl(extent - 1) if isinstance(extent, int) else extent() sink = self.cl(GUARD_ZERO if kind == "load" else GUARD_DUMP) if self.guard_fn is None: self.guard_fn = guard_function(self.cl, self.cu) guard_entry(self.cl, self.cu) # registers the entry block's constants while they can still be declared r = self.tmp() self.emit(f"{r} = OpFunctionCall %ulong %guard_fn %heap_base %gd_on %gd_limit %gd_table {offset} {delta} {sink}") self.guard_last = (r, unguarded) return r def sub_dwords(self, nbytes, b3): """--address-guard: the dwords a 1- or 2-byte access at byte `b3` (a %uint id) of a dword reads: 1, or 2 for a 2-byte access at byte 3 (an int or a %uint id).""" if nbytes == 1: return 1 cross, n = self.tmp(), self.tmp() self.emit(f"{cross} = OpIEqual %bool {b3} {self.cu(3)}") self.emit(f"{n} = OpSelect %uint {cross} {self.cu(2)} {self.cu(1)}") return n def store_element_dwords(self, fmt, fixed_fmt): """--address-guard: the whole dwords a typed buffer store of one element writes (at least 1: a 1- or 2-byte element is written through its own guarded dword): from the instruction's format, or the V#'s (`fmt`, a %uint id) at run time.""" if fixed_fmt is not None: return max(1, self.FORMATS.get(fixed_fmt, (4,))[0] // 4) size, q, n = self.fmt_size_of(fmt), self.tmp(), self.tmp() self.emit(f"{q} = OpShiftRightLogical %uint {size} {self.cu(2)}") self.emit(f"{n} = OpExtInst %uint %glsl UMax {q} {self.cu(1)}") return n def guard_zero(self, value, ty="%uint"): """--address-guard: `value` (an atomic's result) or 0 when the last host_addr was refused: a refused atomic ran on the dump area, and what it returned from there means nothing. `value` unchanged without the guard.""" if not ADDRESS_GUARD or self.guard_last is None: return value r, unguarded = self.guard_last ok, out = self.tmp(), self.tmp() zero = self.cu(0) if ty == "%uint" else self.cl(0) self.emit(f"{ok} = OpIEqual %bool {r} {unguarded}") self.emit(f"{out} = OpSelect {ty} {ok} {value} {zero}") return out def tof(self, u): """The %float with the bits of %uint u. Bitcasting a tou result back gives tou's argument (Gen.bitcast_from), so u must be a %uint and tou's argument a %float; an %int's bits go through int_bits.""" if u in self.bitcast_from: return self.bitcast_from[u] if u.startswith("%c"): # A uint constant's bits are the float constant with them (fconst_bits), not a bitcast at every use. try: v = int(u[2:], 16) except ValueError: v = None if v is not None and self.consts.get(v) == u: return self.fconst_bits(v) f = self.tmp() self.emit(f"{f} = OpBitcast %float {u}") self.bitcast_from[f] = u return f def tou(self, f): if f in self.bitcast_from: return self.bitcast_from[f] if f in self.fconst_of: # A float constant's bits are the uint constant with them, as when fconst returned tof's bitcast of it. return self.cu(self.fconst_of[f]) u = self.tmp() self.emit(f"{u} = OpBitcast %uint {f}") self.bitcast_from[u] = f return u def int_bits(self, i): """The %uint bits of %int i. Not tou: tou remembers its argument, which tof would then return as a %float.""" u = self.tmp() self.emit(f"{u} = OpBitcast %uint {i}") return u def src_f(self, a): return self.tof(self.src_u(a)) # ---- EXEC (this lane's active bit) ---- def active_b(self): if self.exec_static_true: return "%true" if self.cache_active: if self._active_ssa is None: b = self.tmp() self.emit(f"{b} = OpLoad %bool %active") self._active_ssa = b return self._active_ssa b = self.tmp() self.emit(f"{b} = OpLoad %bool %active") return b def exec_value(self): """EXEC as a lane mask for this invocation: all-ones if active, else 0.""" if self.exec_static_true: return self.cu(0xFFFFFFFF) r = self.tmp() self.emit(f"{r} = OpSelect %uint {self.active_b()} {self.cu(0xFFFFFFFF)} {self.cu(0)}") return r def exec_bit(self, word): """Bit L of a 32-bit value written to EXEC as data, as this invocation's 0 or 1: a computed value is one bit per lane (`s_lshl_b32 exec_lo, 1, s5` sets lane 3). A value that already holds this lane's bit of a mask (0 or ~0, `lane_masks.py`) gives the same answer, so no caller needs to say which it has.""" sh, shr, bit = self.tmp(), self.tmp(), self.tmp() self.emit(f"{sh} = OpBitwiseAnd %uint {self.wave_lane()} {self.cu(31)}") self.emit(f"{shr} = OpShiftRightLogical %uint {word} {sh}") self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") return bit def set_exec(self, mask_u): self.emit(f"OpStore %active {self.tmp_bool_nz(mask_u)}") self.uses_active = True def vcc_half_keeps_mask(self): """Whether the current wave64 vcc_lo / vcc_hi write keeps VCC as a lane mask (put_mask on that half) rather than replacing it with plain scalar data (s_buffer_load_dword vcc_lo, scalar ALU, non-mask constant, ...).""" if "vcc" not in self.cur_masks: return False if self.cur_ins is None: return True st = dict(self.cur_masks) for x in self.cur_ins["args"][1:]: if x.get("k") == "sgpr" and x.get("n", 1) == 1: r = x["r"] if r not in st and self.sgpr_imm.get(r) in (0, 0xFFFFFFFF): st[r] = lane_masks.EITHER lane_masks.step(st, self.cur_ins, self.wave64) return st.get("vcc") in lane_masks.MASK_KINDS def dst(self, a, val, *, eager=False): if a.get("sdwa_dst") and a["k"] == "vgpr": val = self.sdwa_dst(a, val) if a["k"] == "special" and a["t"] == "null": return # result discarded if self.wave64 and a["k"] == "special" and a["t"] in ("exec_lo", "exec_hi"): self.exec_half_write(1 if a["t"] == "exec_hi" else 0, self.exec_bit(val)) return if a["k"] == "special" and a["t"] in ("exec_lo", "exec"): self.set_exec(self.exec_bit(val)) return if a["k"] == "vgpr" and a.get("n", 1) == 1: # VALU writes only land in active lanes. The exception is a lane mask on its way through a VGPR # (lane_masks.py): every lane works out its own bit of it, active or not. Inside an active run # (insns) the enclosing `if (active)` already leaves inactive lanes out, and when the shader never # modifies EXEC (`exec_static_true`) every lane is always active (DPP is guarded separately). if self.write_all_lanes or ((self.active_run or self.exec_static_true) and self.dpp_guard is None): self.store_reg("vgpr", a["r"], val) return p = self.reg_ptr("vgpr", a["r"]) old, r = self.tmp(), self.tmp() self.emit(f"{old} = OpLoad %uint {p}") if eager: mask = self.exec_value() if self.dpp_guard is not None: guarded = self.tmp() self.emit(f"{guarded} = OpSelect %uint {self.dpp_guard} {mask} {self.cu(0)}") mask = guarded keep, write, preserve = self.tmp(), self.tmp(), self.tmp() self.emit(f"{keep} = OpNot %uint {mask}") self.emit(f"{write} = OpBitwiseAnd %uint {val} {mask}") self.emit(f"{preserve} = OpBitwiseAnd %uint {old} {keep}") self.emit(f"{r} = OpBitwiseOr %uint {write} {preserve}") else: active = self.active_b() if self.dpp_guard is not None: guarded = self.tmp() self.emit(f"{guarded} = OpLogicalAnd %bool {active} {self.dpp_guard}") active = guarded self.emit(f"{r} = OpSelect %uint {active} {val} {old}") self.emit(f"OpStore {p} {r}") elif a["k"] == "sgpr" and a.get("n", 1) == 1: self.store_reg(a["k"], a["r"], val) elif self.wave64 and a["k"] == "special" and a["t"] in ("vcc_lo", "vcc_hi") and self.vcc_half_keeps_mask(): # One half of a wave64 VCC lane mask (VCC_LO = VCC[31:0], VCC_HI = VCC[63:32]): the other half's lanes # keep their bit, as for exec_lo / exec_hi. %vcc_hi still gets the word for a later read as data. self.put_mask(a, val, a["t"][-2:]) if a["t"] == "vcc_hi": self.emit(f"OpStore %vcc_hi {val}") elif a["k"] == "special" and a["t"] in ("vcc_lo", "vcc"): self.emit(f"OpStore %vcc {val}") elif a["k"] == "special" and a["t"] == "m0": self.emit(f"OpStore %m0 {val}") elif a["k"] == "special" and a["t"] == "vcc_hi": self.emit(f"OpStore %vcc_hi {val}") elif a["k"] == "special" and a["t"] == "scc": self.emit(f"OpStore %scc {val}") else: raise Unsupported(f"destination {a.get('t', a['k'])}") # ---- runs of lane-local VALU instructions under one `if (active)` ---- def lane_local(self, ins): """True when ins only reads and writes this invocation's own registers, and its VGPR writes are the only ones EXEC gates. Each invocation is one lane, so skipping it where the lane is inactive is the same as keeping the old value of everything it writes: what dst()'s per-write OpSelect does. A lane mask read as data gathers the whole wave's mask word (mask_data_src keeps such instructions out of the run, since the subgroup op can't sit inside `if (active)`); a mask on its way through a VGPR (mask_writes) is written in every lane, so it stays out.""" op = base_op(ins["op"]) a = ins["args"] return (op.startswith("v_") and op not in NOOPS and not op.startswith(NOT_LANE_LOCAL) and "_co_" not in op and not ins["op"].endswith("_dpp") and not any(m.startswith(DPP_MODS) for m in ins["mods"]) and bool(a) and a[0]["k"] == "vgpr" and id(ins) not in self.mask_writes and not self.mask_data_src(ins)) def mask_data_src(self, ins): """Whether ins reads a lane mask as data through src_u (a mask-holding SGPR, or EXEC/VCC), which materializes the whole wave's mask word with a subgroup op. That can't happen inside an active run (RUN_FORBIDDEN bars OpGroup there, and inactive lanes wouldn't vote), so lane_local keeps the instruction out; dst()'s per-write EXEC select gates the VGPR write instead. A mask-holding VGPR is not listed: it already stores the wave's mask word, so reading it is a plain register load. The mask state is the one lane_masks.py precomputed for this instruction (self.lane_masks), since lane_local runs before the instruction is translated.""" masks = self.lane_masks.get(id(ins)) or {} return any(self._mask_data_operand(x, masks, ins) for x in ins["args"][1:]) def _mask_data_operand(self, x, masks, ins): """Whether src_u will materialize operand `x`'s lane mask as the wave's mask word for `ins` (a subgroup op or, under --wave64-emulate, an exchange round): `masks` is the lane_masks state for ins — self.lane_masks[id(ins)], the same dict self.cur_masks holds while translating.""" if x["k"] == "sgpr": if x.get("n", 1) != 1 or x["r"] not in masks: return False elif x["k"] == "special": t = x.get("t", "") if not (t in ("exec_lo", "exec_hi") or (t in ("vcc", "vcc_lo") and "vcc" in masks) or (t == "vcc_hi" and ("vcc" if self.wave64 else "vcc_hi") in masks)): return False else: return False return self.mask_read_is_data(ins) def insns(self, seq): """Translate seq, a straight run of instructions (no branch among them). A run of at least MIN_ACTIVE_RUN lane-local VALU instructions goes inside one `if (active)` and writes its VGPRs directly: the driver then predicates it with its own EXEC, instead of keeping the old and new value of every register live for an OpSelect per write. Only in a shader that may write EXEC (elsewhere %active stays true and the driver folds the selects away). Under --wave64-emulate a round ends a segment only at a cross-lane exchange, a barrier or a memory-ordering point (x_split), and a lane-local instruction is none of these, so a run sits inside one segment; insns checks that no x_split happened inside it.""" local = [self.exec_changes and self.lane_local(i) for i in seq] i = 0 while i < len(seq): j = i while j < len(seq) and local[j]: j += 1 if j - i < MIN_ACTIVE_RUN: self.insn(seq[i]) i += 1 continue act = self.active_b() do, end = self.tmp() + "_run", self.tmp() + "_end" self.emit(f"OpSelectionMerge {end} None") self.emit(f"OpBranchConditional {act} {do} {end}") self.emit(f"{do} = OpLabel") self.active_run = True marks = len(self.x_marks) for ins in seq[i:j]: start = len(self.body) self.insn(ins) self.check_lane_local(ins, self.body[start:]) if len(self.x_marks) != marks: # a segment boundary would cut the `if (active)` in two # An internal invariant, not an unsupported pattern: lane_local() admitted an instruction that # ends a segment. The corpus loop counts it as a translator error for this one shader. raise AssertionError(f"internal: {ins['op']} split an emulated wave64 round inside an active " "run (lane_local admitted a segment boundary)") self.active_run = False self.emit(f"OpBranch {end}") self.emit(f"{end} = OpLabel") i = j @staticmethod def may_write_exec(ins): """Whether ins can change EXEC: it names EXEC as an operand, or is a v_cmpx or an s_*_saveexec. A wrong guess either way only costs speed (runs where EXEC never changes, or per-write selects where it does).""" op = base_op(ins["op"]) return ("saveexec" in op or op.startswith("v_cmpx") or any(x["k"] == "special" and x.get("t", "").startswith("exec") for x in ins["args"])) # What a lane-local instruction may emit inside an active run: anything but these (other lanes, side effects, # control flow out of the run) and stores to registers other than the VGPR file. RUN_FORBIDDEN = ("OpGroup", "OpControlBarrier", "OpMemoryBarrier", "OpImage", "OpDPd", "OpFwidth", "OpAtomic", "OpKill", "OpTerminateInvocation", "OpDemoteToHelperInvocation", "OpEmit", "OpEndPrimitive", "OpReturn", "OpFunctionCall", "OpLoopMerge") def check_lane_local(self, ins, lines): """Fail loudly if ins, judged lane-local, emitted something an active run can't hold.""" # hoisted register pointers (#4440) are declared once in %entry, so they never appear in these lines vgpr_ptrs = {p for (kind, _), p in self.reg_ptrs.items() if kind == "vgpr"} for line in lines: s = line.strip() words = s.split() if len(words) > 4 and words[2] == "OpAccessChain" and words[4] == "%vgpr": vgpr_ptrs.add(words[0]) bad = (s.split(" = ")[-1].startswith(self.RUN_FORBIDDEN) or (s.startswith("OpStore ") and words[1] not in vgpr_ptrs)) if bad: raise AssertionError(f"{ins['op']} is not lane-local inside an active run: {s}") def vcc_data_pair_op(self, op, args): """VCC is also the scalar register pair 106:107. Preserve both words when used as data.""" def words(arg): halves = ([{"k": "special", "t": t} for t in ("vcc_lo", "vcc_hi")] if arg.get("t") == "vcc" else [{"k": "sgpr", "r": arg["r"] + i, "n": 1} for i in range(2)]) return [self.lane_mask_word(h) if self.holds_lane_mask(h) else self.src_u(h) for h in halves] lo, hi = words(args[1]) if op == "s_xor_b64": x, y = words(args[2]) rlo, rhi, nonzero = self.tmp(), self.tmp(), self.tmp() self.emit(f"{rlo} = OpBitwiseXor %uint {lo} {x}") self.emit(f"{rhi} = OpBitwiseXor %uint {hi} {y}") self.emit(f"{nonzero} = OpBitwiseOr %uint {rlo} {rhi}") self.scc_nonzero(nonzero) lo, hi = rlo, rhi if args[0].get("t") == "vcc": self.emit(f"OpStore %vcc {lo}") self.emit(f"OpStore %vcc_hi {hi}") else: self.dst64_data(args[0], lo, hi, op) def mov64(self, d, s): """64-bit scalar move, including EXEC save/restore (EXEC = this lane's active bit).""" if d["k"] == "special" and d["t"] == "exec": self.set_exec(self.mask_src(s)) return if ((self.vcc_scalar_pointer or not self.wave64) and d["k"] == "special" and d["t"] == "vcc" and s["k"] == "sgpr" and s.get("n") == 2 and not self.holds_lane_mask(s) and (not self.wave64 or not self.any_mask_word(s))): self.emit(f"OpStore %vcc {self.load_reg('sgpr', s['r'])}") self.emit(f"OpStore %vcc_hi {self.load_reg('sgpr', s['r'] + 1)}") return if d["k"] == "special" and d["t"] in ("vcc", "vcc_lo"): m = self.mask_src(s) self.emit(f"OpStore %vcc {m}") if self.wave64 and d["t"] == "vcc": self.emit(f"OpStore %vcc_hi {m}") return if d["k"] != "sgpr" or d.get("n") != 2: raise Unsupported("s_mov_b64 destination") lit_lo = lit_hi = None if s["k"] == "special" and s["t"] == "exec": lo = hi = self.exec_value() elif s["k"] == "sgpr" and s.get("n") == 2: lit_lo = self.sgpr_imm.get(s["r"]) lit_hi = self.sgpr_imm.get(s["r"] + 1) lo, hi = self.load_reg("sgpr", s["r"]), self.load_reg("sgpr", s["r"] + 1) elif s["k"] == "imm": v = s["v"] & 0xFFFFFFFFFFFFFFFF if s["v"] < 0: v = s["v"] & 0xFFFFFFFFFFFFFFFF lit_lo = v & 0xFFFFFFFF lit_hi = (v >> 32) & 0xFFFFFFFF lo, hi = self.cu(lit_lo), self.cu(lit_hi) elif s["k"] == "special" and s["t"] == "vcc": lo = hi = self.tmp() # this lane's bit in both halves, as for EXEC self.emit(f"{lo} = OpLoad %uint %vcc") else: raise Unsupported("s_mov_b64 source") self.store_reg("sgpr", d["r"], lo) self.store_reg("sgpr", d["r"] + 1, hi) if self.desc_cache_ok(): if lit_lo is not None: self.sgpr_imm[d["r"]] = lit_lo if lit_hi is not None: self.sgpr_imm[d["r"] + 1] = lit_hi def compare(self, op, a, scalar, exec_only=False, mods=()): """v_cmp_* / s_cmp_*: lane result into VCC/SGPR mask (vector), SCC (scalar), or EXEC (v_cmpx).""" parts = op.split("_") # v_cmp_lt_f32 / s_cmp_eq_u32 cond, ty = parts[2], parts[3] srcs = a[0:2] if scalar else a[-2:] dst = None if (scalar or exec_only) else a[0] if not scalar and ty in ("f64", "i64", "u64") and cond in ("f", "tru" if ty == "f64" else "t"): # The sources do not affect a constant predicate, even when a double is NaN. self.write_compare_result("%false" if cond == "f" else "%true", dst, scalar, exec_only) return if ty in ("f32", "f16"): if ty == "f32": x, y = self.src_f(srcs[0]), self.src_f(srcs[1]) else: # f16 compare: op_sel selects lo/hi half of each source, compared as f32 (exact for f16 values) sel, _ = self.opsel_bits(mods, 2) x, y = self.f16_in(srcs[0], sel[0]), self.f16_in(srcs[1], sel[1]) ops = {"lt": "OpFOrdLessThan", "le": "OpFOrdLessThanEqual", "gt": "OpFOrdGreaterThan", "ge": "OpFOrdGreaterThanEqual", "eq": "OpFOrdEqual", "neq": "OpFUnordNotEqual", "lg": "OpFOrdNotEqual", "nlg": "OpFUnordEqual", "nlt": "OpFUnordGreaterThanEqual", "ngt": "OpFUnordLessThanEqual", "nle": "OpFUnordGreaterThan", "nge": "OpFUnordLessThan"} elif ty in ("u16", "i16"): sel, _ = self.opsel_bits(mods, 2) x, y = self.src_u(srcs[0]), self.src_u(srcs[1]) if ty == "i16": x, y = self.i16_half(x, sel[0]), self.i16_half(y, sel[1]) else: x, y = self.u16_half(x, sel[0]), self.u16_half(y, sel[1]) s = ty == "i16" ops = {"lt": "OpSLessThan" if s else "OpULessThan", "le": "OpSLessThanEqual" if s else "OpULessThanEqual", "gt": "OpSGreaterThan" if s else "OpUGreaterThan", "ge": "OpSGreaterThanEqual" if s else "OpUGreaterThanEqual", "eq": "OpIEqual", "ne": "OpINotEqual", "lg": "OpINotEqual"} elif ty in ("u32", "i32"): use_wave_equal = False wave_equal_half = None m0, m1 = self.holds_lane_mask(srcs[0]), self.holds_lane_mask(srcs[1]) if scalar and (m0 or m1): h0 = self.mask_half(srcs[0]) if m0 else None h1 = self.mask_half(srcs[1]) if m1 else None def _is_u32_zero_or_all_ones(src): return src["k"] == "imm" and (src["v"] & 0xFFFFFFFF) == 0 can_vote = False if cond in ("eq", "ne", "lg"): if m0 and m1: if not self.wave64: can_vote = h0 != "hi" and h1 != "hi" elif h0 is not None and h0 == h1: can_vote = True wave_equal_half = h0 else: other = srcs[1] if m0 else srcs[0] mh = h0 if m0 else h1 if _is_u32_zero_or_all_ones(other): if not self.wave64: can_vote = mh != "hi" elif mh is not None: can_vote = True wave_equal_half = mh if can_vote: use_wave_equal = True x, y = self.src_u(srcs[0]), self.src_u(srcs[1]) else: def _mask_word(src, is_mask): if not is_mask: return self.src_u(src) lo, hi = self.wave_mask(src) return hi if self.mask_half(src) == "hi" else lo x, y = _mask_word(srcs[0], m0), _mask_word(srcs[1], m1) else: x, y = self.src_u(srcs[0]), self.src_u(srcs[1]) if ty == "i32": x, y = self.as_int(x), self.as_int(y) s = ty == "i32" ops = {"lt": "OpSLessThan" if s else "OpULessThan", "le": "OpSLessThanEqual" if s else "OpULessThanEqual", "gt": "OpSGreaterThan" if s else "OpUGreaterThan", "ge": "OpSGreaterThanEqual" if s else "OpUGreaterThanEqual", "eq": "OpIEqual", "ne": "OpINotEqual", "lg": "OpINotEqual"} elif ty == "f64" and not scalar: b = self.compare_f64_cond(op, cond, srcs, mods) self.write_compare_result(b, dst, False, exec_only) return else: raise Unsupported(op) is_float = ty in ("f32", "f16") b = self.tmp() if cond in (("f", "tru", "o", "u") if is_float else ("f", "t")): # Constant compares: f is always false, t / tru always true. o (ordered) is true when neither source # is NaN, u (unordered) when either is. if cond in ("o", "u"): nx, ny, either = self.tmp(), self.tmp(), self.tmp() self.emit(f"{nx} = OpIsNan %bool {x}") self.emit(f"{ny} = OpIsNan %bool {y}") self.emit(f"{either} = OpLogicalOr %bool {nx} {ny}") if cond == "u": b = either else: self.emit(f"{b} = OpLogicalNot %bool {either}") else: self.emit(f"{b} = OpCopyObject %bool {'%false' if cond == 'f' else '%true'}") elif cond not in ops: raise Unsupported(op) elif is_float and cond == "lg": # LG is ordered (false when either source is NaN), as less-or-greater. Not OpFOrdNotEqual: SPIRV-Cross # (MoltenVK) writes that as `!=`, which is true on a NaN. lt, gt = self.tmp(), self.tmp() self.emit(f"{lt} = OpFOrdLessThan %bool {x} {y}") self.emit(f"{gt} = OpFOrdGreaterThan %bool {x} {y}") self.emit(f"{b} = OpLogicalOr %bool {lt} {gt}") else: self.emit(f"{b} = {ops[cond]} %bool {x} {y}") if scalar and ty in ("u32", "i32") and use_wave_equal: b = self.wave_equal(b, cond == "eq", half=wave_equal_half) self.write_compare_result(b, dst, scalar, exec_only) def write_compare_result(self, b: str, dst: dict | None, scalar: bool, exec_only: bool) -> None: r = self.tmp() # Lane masks are all-ones/zero per invocation (one lane), SCC is 1/0. A VOPC result bit is 0 for lanes # that are off in EXEC (as on hardware), so wave-wide reductions of the mask (s_cbranch_vccz) are exact. bm = b if not scalar and not exec_only: bm = self.tmp() self.emit(f"{bm} = OpLogicalAnd %bool {b} {self.active_b()}") self.emit(f"{r} = OpSelect %uint {bm} {self.cu(1 if scalar else 0xFFFFFFFF)} {self.cu(0)}") if scalar: self.emit(f"OpStore %scc {r}") elif dst is None: # v_cmpx: EXEC &= cond a2 = self.tmp() self.emit(f"{a2} = OpLoad %bool %active") a3 = self.tmp() self.emit(f"{a3} = OpLogicalAnd %bool {a2} {b}") self.emit(f"OpStore %active {a3}") self.uses_active = True else: self.mask_dst(dst, r) def compare_x(self, op, a, mods=()): """v_cmpx_*: like v_cmp but the result ANDs into EXEC. e32 form has only the two sources; e64 also names a destination (vcc/sgpr) which gets the compare result too.""" srcs = a[-2:] self.compare("v_cmp_" + op[len("v_cmpx_"):], [None] + list(srcs), scalar=False, exec_only=True, mods=mods) def compare_f64_cond(self, op, cond, srcs, mods): """Evaluate an IEEE-754 binary64 compare predicate using pure 32-bit integer ops (no Float64 capability, denormal-safe). Supports all 16 RDNA2 float compare conditions (f, lt, eq, le, gt, lg, ge, o, u, nge, nlg, ngt, nle, neq, nlt, tru).""" unord_dual = {"nlt": "lt", "nle": "le", "ngt": "gt", "nge": "ge", "neq": "eq", "nlg": "lg"} if cond not in ("f", "tru", "o", "u", "lt", "le", "gt", "ge", "eq", "lg") and cond not in unord_dual: raise Unsupported(op) if mods: raise Unsupported(op + " modifiers") def emit_b(line): t = self.tmp() self.emit(f"{t} = {line}") return t def read_f64_words(sv): if sv["k"] in ("vgpr", "sgpr") and sv.get("n") == 2: lo, hi = self.load_reg(sv["k"], sv["r"]), self.load_reg(sv["k"], sv["r"] + 1) elif sv["k"] == "fimm": bits = struct.unpack("> 32) elif sv["k"] == "imm": v = sv["v"] if sv.get("literal") or (not (-16 <= v <= 64) and -0x80000000 <= v <= 0xFFFFFFFF): lo, hi = self.cu(0), self.cu(v & 0xFFFFFFFF) else: bits = v & 0xFFFFFFFFFFFFFFFF lo, hi = self.cu(bits & 0xFFFFFFFF), self.cu(bits >> 32) else: raise Unsupported(op + " operand") if sv.get("abs"): hi = emit_b(f"OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}") if sv.get("neg"): hi = emit_b(f"OpBitwiseXor %uint {hi} {self.cu(0x80000000)}") return lo, hi alo, ahi = read_f64_words(srcs[0]) blo, bhi = read_f64_words(srcs[1]) if cond in ("f", "tru"): return emit_b(f"OpCopyObject %bool {'%false' if cond == 'f' else '%true'}") def is_nan_words(lo, hi): exp_m = emit_b(f"OpBitwiseAnd %uint {hi} {self.cu(0x7FF00000)}") expmax = emit_b(f"OpIEqual %bool {exp_m} {self.cu(0x7FF00000)}") man_hi = emit_b(f"OpBitwiseAnd %uint {hi} {self.cu(0x000FFFFF)}") man_or = emit_b(f"OpBitwiseOr %uint {man_hi} {lo}") man_nz = emit_b(f"OpINotEqual %bool {man_or} {self.cu(0)}") return emit_b(f"OpLogicalAnd %bool {expmax} {man_nz}") nan_a, nan_b = is_nan_words(alo, ahi), is_nan_words(blo, bhi) any_nan = emit_b(f"OpLogicalOr %bool {nan_a} {nan_b}") if cond == "u": return any_nan ordered = emit_b(f"OpLogicalNot %bool {any_nan}") if cond == "o": return ordered def order_key(lo, hi): # Canonicalize -0.0 to +0.0, then map IEEE-754 sign-magnitude to a monotonic unsigned 64-bit key. abs_hi = emit_b(f"OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}") mag_or = emit_b(f"OpBitwiseOr %uint {abs_hi} {lo}") is_z = emit_b(f"OpIEqual %bool {mag_or} {self.cu(0)}") c_hi = emit_b(f"OpSelect %uint {is_z} {self.cu(0)} {hi}") sign = emit_b(f"OpShiftRightLogical %uint {c_hi} {self.cu(31)}") is_neg = self.tmp_bool_nz(sign) neg_hi = emit_b(f"OpNot %uint {c_hi}") neg_lo = emit_b(f"OpNot %uint {lo}") pos_hi = emit_b(f"OpBitwiseXor %uint {c_hi} {self.cu(0x80000000)}") khi = emit_b(f"OpSelect %uint {is_neg} {neg_hi} {pos_hi}") klo = emit_b(f"OpSelect %uint {is_neg} {neg_lo} {lo}") return klo, khi aklo, akhi = order_key(alo, ahi) bklo, bkhi = order_key(blo, bhi) invert = cond in unord_dual base = unord_dual.get(cond, cond) hi_eq = emit_b(f"OpIEqual %bool {akhi} {bkhi}") if base in ("eq", "lg"): lo_eq = emit_b(f"OpIEqual %bool {aklo} {bklo}") cmp_res = emit_b(f"OpLogicalAnd %bool {hi_eq} {lo_eq}") if base == "lg": cmp_res = emit_b(f"OpLogicalNot %bool {cmp_res}") else: hi_op = "OpULessThan" if base in ("lt", "le") else "OpUGreaterThan" lo_op = {"lt": "OpULessThan", "le": "OpULessThanEqual", "gt": "OpUGreaterThan", "ge": "OpUGreaterThanEqual"}[base] hi_cmp = emit_b(f"{hi_op} %bool {akhi} {bkhi}") lo_cmp = emit_b(f"{lo_op} %bool {aklo} {bklo}") lo_tie = emit_b(f"OpLogicalAnd %bool {hi_eq} {lo_cmp}") cmp_res = emit_b(f"OpLogicalOr %bool {hi_cmp} {lo_tie}") ord_res = emit_b(f"OpLogicalAnd %bool {ordered} {cmp_res}") return emit_b(f"OpLogicalNot %bool {ord_res}") if invert else ord_res def _validate_sopc_operand(self, op, src, *, is_64): if src.get("neg") or src.get("abs") or src.get("sext"): raise Unsupported(f"{op}: operand modifiers not supported on SOPC") k = src.get("k") if is_64: if k == "sgpr" and src.get("n", 1) == 2: return if k == "imm": return if k == "special" and src.get("t") in SOPC_SRC64_SPECIALS: return raise Unsupported(f"{op}: expected 64-bit scalar operand") if k == "sgpr" and src.get("n", 1) == 1: return if k in ("imm", "fimm"): return if k == "special" and src.get("t") in SOPC_SRC32_SPECIALS: return raise Unsupported(f"{op}: expected 32-bit scalar operand") def _validate_sopc(self, ins, op, a, mods, *, src0_64=False, src1_64=False): if ins["op"] != op: raise Unsupported(f"{ins['op']}: encoding suffix not supported on SOPC") if mods: raise Unsupported(f"{op}: modifiers not supported on SOPC") if len(a) != 2: raise Unsupported(f"{op}: expected 2 operands, got {len(a)}") self._validate_sopc_operand(op, a[0], is_64=src0_64) self._validate_sopc_operand(op, a[1], is_64=src1_64) def bitcmp(self, op, a): """s_bitcmp0/1_b32/b64: test if bit (a[1]) of scalar a[0] is 0 or 1, result in SCC.""" is_64 = op.endswith("b64") test_one = op.startswith("s_bitcmp1") src0 = a[0] if not is_64: lo = self.lane_mask_word(src0) if self.holds_lane_mask(src0) else self.src_u(src0) elif src0["k"] == "sgpr" and src0.get("n") == 2: r = src0["r"] if (self.wave64 and self.cur_masks.get(r) == lane_masks.MASK_LO and self.cur_masks.get(r + 1) == lane_masks.MASK_HI): lo, hi = self.wave_mask(src0) else: words = [] for i in range(2): reg = {"k": "sgpr", "r": r + i, "n": 1} words.append(self.lane_mask_word(reg) if (r + i) in self.cur_masks else self.load_reg("sgpr", r + i)) lo, hi = words[0], words[1] elif not self.wave64 and src0["k"] == "special" and src0.get("t") == "vcc": vlo = {"k": "special", "t": "vcc_lo"} vhi = {"k": "special", "t": "vcc_hi"} lo = self.lane_mask_word(vlo) if self.holds_lane_mask(vlo) else self.src_u(vlo) hi = self.lane_mask_word(vhi) if self.holds_lane_mask(vhi) else self.src_u(vhi) elif self.holds_lane_mask(src0): lo, hi = self.wave_mask(src0) elif src0["k"] == "imm": v = src0["v"] & 0xFFFFFFFFFFFFFFFF lo, hi = self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) elif src0["k"] == "special" and src0.get("t") == "null": lo, hi = self.cu(0), self.cu(0) elif src0["k"] == "special" and src0.get("t") == "vcc": lo, hi = self.tmp(), self.tmp() self.emit(f"{lo} = OpLoad %uint %vcc") self.emit(f"{hi} = OpLoad %uint %vcc_hi") else: lo, hi = self.src_u(src0), self.cu(0) sh = self.lane_mask_word(a[1]) if self.holds_lane_mask(a[1]) else self.src_u(a[1]) mask_bits = 63 if is_64 else 31 m = self.tmp() self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(mask_bits)}") if is_64: is_hi = self.tmp() self.emit(f"{is_hi} = OpUGreaterThanEqual %bool {m} {self.cu(32)}") word = self.tmp() self.emit(f"{word} = OpSelect %uint {is_hi} {hi} {lo}") sh32 = self.tmp() self.emit(f"{sh32} = OpBitwiseAnd %uint {m} {self.cu(31)}") else: word = lo sh32 = m shifted, bit = self.tmp(), self.tmp() self.emit(f"{shifted} = OpShiftRightLogical %uint {word} {sh32}") self.emit(f"{bit} = OpBitwiseAnd %uint {shifted} {self.cu(1)}") cond = self.tmp() self.emit(f"{cond} = {'OpINotEqual' if test_one else 'OpIEqual'} %bool {bit} {self.cu(0)}") res = self.tmp() self.emit(f"{res} = OpSelect %uint {cond} {self.cu(1)} {self.cu(0)}") self.emit(f"OpStore %scc {res}") def swizzle(self, a, mods, ins): """ds_swizzle_b32 vD, vS [offset:swizzle(...) | offset:N]: a subgroup shuffle (one invocation per lane).""" line = " ".join(m for m in mods) + " " + " ".join(x.get("t", "") for x in a if x["k"] in ("special", "raw")) import re as _re text = line + " " + str(ins.get("raw", "")) bm = _re.search(r'swizzle\(BITMASK_PERM,\s*"([01pi]{5})"\)', text) m = _re.search(r"swizzle\((\w+)((?:,\s*\d+)*)\)", text) and_m = or_m = xor_m = 0 if bm: kind, args = "BITMASK_PERM", [] # One character per lane-index bit, bit 4 first: p = keep, i = invert, 0 / 1 = force. # Source lane = ((lane & and_mask) | or_mask) ^ xor_mask, within each group of 32 lanes. for k, ch in enumerate(bm.group(1)): bit = 1 << (4 - k) if ch in "pi": and_m |= bit if ch == "i": xor_m |= bit if ch == "1": or_m |= bit elif m: kind = m.group(1) args = [int(x) for x in m.group(2).split(",")[1:]] if m.group(2) else [] else: # Raw 16-bit DS_SWIZZLE_B32 offset (RDNA2 ISA): llvm-mc prints numeric offset:N when QDMode bits 13:8 # are non-zero (e.g. 0x81e4 -> offset:33252) and omits offset: when it is 0. Measured across all 65,536 # offsets on gfx1036: 0x0000..0x7FFF is bitmask mode, 0x8000..0xBFFF is QDMode (bits 13:8 ignored), and # 0xC000..0xFFFF (bits 15:14 = 11) is a separate hardware mode (not a quad permute) and stays Unsupported. if ("swizzle(" in text or len(mods) > 1 or len(a) != 2 or any(x["k"] in ("special", "raw") for x in a) or any(not mod.startswith("offset:") for mod in mods)): raise Unsupported("ds_swizzle pattern") off = 0 if mods: try: off = int(mods[0][7:], 0) except ValueError: raise Unsupported("ds_swizzle pattern") from None if not 0 <= off <= 0xBFFF: raise Unsupported("ds_swizzle offset") if off & 0x8000: kind = "QUAD_PERM" args = [(off >> (2 * i)) & 3 for i in range(4)] else: kind, args = "BITMASK_PERM", [] and_m, or_m, xor_m = off & 0x1F, (off >> 5) & 0x1F, (off >> 10) & 0x1F qmap = None if kind == "QUAD_PERM": qmap = tuple(args) elif kind == "SWAP" and args and 1 <= args[0] <= 3: qmap = tuple(i ^ args[0] for i in range(4)) elif kind == "REVERSE" and args and args[0] in (2, 4): qmap = tuple(i ^ (args[0] - 1) for i in range(4)) elif kind == "BROADCAST" and len(args) >= 2 and args[0] in (2, 4): qmap = tuple((i & ~(args[0] - 1)) | (args[1] & (args[0] - 1)) for i in range(4)) elif kind == "BITMASK_PERM" and (and_m & 0x1C) == 0x1C and (or_m & 0x1C) == 0 and (xor_m & 0x1C) == 0: qmap = tuple((((i & and_m) | or_m) ^ xor_m) & 3 for i in range(4)) if qmap is not None and self.stage == "ps" and not self.emulate: self.ds_quad_swizzle(a[0], self.src_u(a[1]), qmap) return self.uses_subgroup = True lane = self.tmp() self.sub_lane(lane) if kind == "BITMASK_PERM": t1, t2, src = self.tmp(), self.tmp(), self.tmp() self.emit(f"{t1} = OpBitwiseAnd %uint {lane} {self.cu(and_m | 0xFFFFFFE0)}") self.emit(f"{t2} = OpBitwiseOr %uint {t1} {self.cu(or_m)}") self.emit(f"{src} = OpBitwiseXor %uint {t2} {self.cu(xor_m)}") elif kind == "QUAD_PERM": sel, base, src = self.tmp(), self.tmp(), self.cu(0) self.emit(f"{sel} = OpBitwiseAnd %uint {lane} {self.cu(3)}") self.emit(f"{base} = OpBitwiseAnd %uint {lane} {self.cu(0xFFFFFFFC)}") pick = self.cu(args[0]) for i in (1, 2, 3): e, nxt = self.tmp(), self.tmp() self.emit(f"{e} = OpIEqual %bool {sel} {self.cu(i)}") self.emit(f"{nxt} = OpSelect %uint {e} {self.cu(args[i])} {pick}") pick = nxt src = self.tmp() self.emit(f"{src} = OpBitwiseOr %uint {base} {pick}") elif kind == "SWAP": src = self.tmp() self.emit(f"{src} = OpBitwiseXor %uint {lane} {self.cu(args[0])}") elif kind == "REVERSE": src = self.tmp() self.emit(f"{src} = OpBitwiseXor %uint {lane} {self.cu(args[0] - 1)}") elif kind == "BROADCAST": src, keep = self.tmp(), self.tmp() self.emit(f"{keep} = OpBitwiseAnd %uint {lane} {self.cu(~(args[0] - 1) & 0xFFFFFFFF)}") self.emit(f"{src} = OpBitwiseOr %uint {keep} {self.cu(args[1])}") else: raise Unsupported("ds_swizzle " + kind) self.ds_lane_read(a[0], self.src_u(a[1]), src, lane) # op: (bytes, store?, signed, VGPR half the data comes from / lands in: None = the whole register) BUFFER_SUB16 = { # the plain 8/16-bit loads are buffer_load_sub's (BUFFER_SUB) "buffer_load_ubyte_d16": (1, False, False, 0), "buffer_load_ubyte_d16_hi": (1, False, False, 1), "buffer_load_sbyte_d16": (1, False, True, 0), "buffer_load_sbyte_d16_hi": (1, False, True, 1), "buffer_load_short_d16": (2, False, False, 0), "buffer_load_short_d16_hi": (2, False, False, 1), "buffer_store_byte": (1, True, False, None), "buffer_store_byte_d16_hi": (1, True, False, 1), "buffer_store_short": (2, True, False, None), "buffer_store_short_d16_hi": (2, True, False, 1)} @staticmethod def _is_coherent_mem(mods): return "glc" in mods or "dlc" in mods def _psb_load_op(self, mods): if self._is_coherent_mem(mods): self.uses_vmm = True self.reads_glc_buffer = True return f"Aligned|MakePointerVisible|NonPrivatePointer 4 {self.cu(1)}" return "Aligned 4" def _psb_store_op(self, mods): if self._is_coherent_mem(mods): self.uses_vmm = True return f"Aligned|MakePointerAvailable|NonPrivatePointer 4 {self.cu(1)}" return "Aligned 4" def buffer_sub(self, op, a, mods): """The d16 8/16-bit MUBUF loads and the 8/16-bit stores (RDNA2 ISA); the plain buffer_load_{u,s}byte / {u,s}short are buffer_load_sub's. The _d16 loads write one 16-bit half of vdata (ubyte / sbyte extended to 16 bits) and keep the other; buffer_store_byte / short write the low 8 / 16 bits (the _d16_hi forms the high half). The address is buffer_address's, and the bounds check covers the access's own size (1 or 2 bytes) as for a typed element of that size: a load out of range gives 0 (in the half it writes, for d16), a store out of range writes nothing. Each byte is its own access, so a 16-bit one that crosses a dword is exact (in a swizzled buffer the next dword is `step` bytes on); a store merges each byte into its dword with atomic and / or, as buffer byte format stores do. Inactive lanes neither load nor store.""" if any(m in mods for m in ("lds", "tfe")): raise Unsupported(op + " form") nbytes, store, signed, half = self.BUFFER_SUB16[op] vd = a[0] if vd["k"] != "vgpr" or vd.get("n", 1) != 1: raise Unsupported(op + " data") addr, _, in_b, step = self.buffer_address(a, mods, elem="fmt", fixed_fmt=1 if nbytes == 1 else 7) old = self.load_reg("vgpr", vd["r"]) cond = self.tmp() self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {in_b}") lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" pre = self.current_label_placeholder() self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") if store and self._is_coherent_mem(mods): self.uses_vmm = True load_mem = None if store else self._psb_load_op(mods) value = None for k in range(nbytes): va = addr if k: va = self.tmp() self.emit(f"{va} = OpIAdd %ulong {addr} {self.cl(k)}") if step is not None: # the second byte of an access at byte 3 is in the access's next dword, `step` bytes on lo, b3, cross, s64, far, sel = (self.tmp() for _ in range(6)) self.emit(f"{lo} = OpUConvert %uint {addr}") self.emit(f"{b3} = OpBitwiseAnd %uint {lo} {self.cu(3)}") self.emit(f"{cross} = OpIEqual %bool {b3} {self.cu(3)}") self.emit(f"{s64} = OpUConvert %ulong {step}") self.emit(f"{far} = OpIAdd %ulong {addr} {s64}") f2 = self.tmp() self.emit(f"{f2} = OpISub %ulong {far} {self.cl(3)}") self.emit(f"{sel} = OpSelect %ulong {cross} {f2} {va}") va = sel p, sh = self.global_byte_ptr(va, "store" if store else "load") if store: byte, mk, inv, vs, t1, t2 = (self.tmp() for _ in range(6)) self.emit(f"{byte} = OpBitFieldUExtract %uint {old} {self.cu(16 * (half or 0) + 8 * k)} {self.cu(8)}") self.emit(f"{mk} = OpShiftLeftLogical %uint {self.cu(0xFF)} {sh}") self.emit(f"{inv} = OpNot %uint {mk}") self.emit(f"{vs} = OpShiftLeftLogical %uint {byte} {sh}") self.emit(f"{t1} = OpAtomicAnd %uint {p} {self.cu(1)} {self.cu(0)} {inv}") self.emit(f"{t2} = OpAtomicOr %uint {p} {self.cu(1)} {self.cu(0)} {vs}") else: w, b = self.tmp(), self.tmp() self.emit(f"{w} = OpLoad %uint {p} {load_mem}") self.emit(f"{b} = OpBitFieldUExtract %uint {w} {sh} {self.cu(8)}") if value is None: value = b else: hi8, v2 = self.tmp(), self.tmp() self.emit(f"{hi8} = OpShiftLeftLogical %uint {b} {self.cu(8)}") self.emit(f"{v2} = OpBitwiseOr %uint {value} {hi8}") value = v2 if not store and signed: sx = self.tmp() self.emit(f"{sx} = OpBitFieldSExtract %uint {value} {self.cu(0)} {self.cu(8 * nbytes)}") value = sx self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") if store: return got = self.tmp() self.emit(f"{got} = OpPhi %uint {value} {lbl_do} {self.cu(0)} {pre}") # out of range / inactive: 0 if half is None: # a whole-register load: inactive lanes keep vdata (dst writes active lanes only) self.dst(vd, got) else: new = self.tmp() self.emit(f"{new} = OpBitFieldInsert %uint {old} {got} {self.cu(16 * half)} {self.cu(16)}") self.dst(vd, new) def buffer_load(self, op, a, mods): """buffer_load_dword[xN] vD, vaddr, s[V#], soffset [offen|idxen] offset:N -> buffer-device-address loads. addr = V#.base + soffset + inst_offset + (offen ? vaddr : 0) + (idxen ? vindex * V#.stride : 0), byte exact. Each dword is loaded only when it is in range per the V#'s OOB_SELECT (buffer_address; docs/design.md, Buffer bounds checking): for modes 0 and 3 dword i ends inside the stride / num_records, else it is 0 and memory is not read; modes 1 and 2 check the index / num_records once. Inactive lanes don't load.""" if any(m in mods for m in ("lds", "tfe")) or "format" in op: raise Unsupported(op + " form") n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) vd = a[0] addr, _, in_b, raw_parts, step = self.buffer_address(a, mods, parts=True) act = self.active_b() ptr, host = self.tmp(), self.host_addr(addr, "load", lambda: self.guard_delta(n, step)) self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") load_mem = self._psb_load_op(mods) def guarded(cond, dwords): """One selection construct that loads these dwords when cond holds; the phis give 0 otherwise.""" lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" pre_label = self.current_label_placeholder() self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") loaded = [] for i in dwords: p, v_do = self.buf_dword_ptr(ptr, host, step, i), self.tmp() self.emit(f"{v_do} = OpLoad %uint {p} {load_mem}") loaded.append(v_do) self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") out = [] for v_do in loaded: v = self.tmp() self.emit(f"{v} = OpPhi %uint {v_do} {lbl_do} {self.cu(0)} {pre_label}") out.append(v) return out if raw_parts is None: # literal mode 1/2: one check for the whole load cond = self.tmp() self.emit(f"{cond} = OpLogicalAnd %bool {act} {in_b}") phis = guarded(cond, range(n)) else: # mode 0/3 (or a run-time V#): each dword checks its own end phis = [] for i in range(n): cond = self.tmp() self.emit(f"{cond} = OpLogicalAnd %bool {act} {raw_parts(i)}") phis += guarded(cond, [i]) for i, v in enumerate(phis): self.dst({"k": "vgpr", "r": vd["r"] + i, "n": 1}, v) BUFFER_SUB = { "buffer_load_ubyte": (1, False), "buffer_load_sbyte": (1, True), "buffer_load_ushort": (2, False), "buffer_load_sshort": (2, True), } def buffer_load_sub(self, op, a, mods): """buffer_load_{u,s}byte / buffer_load_{u,s}short vD, vaddr, s[V#], soffset [offen|idxen] offset:N. Loads 1 or 2 bytes from V#.base + offsets, zero- or sign-extended to 32 bits. Out-of-bounds lanes (OOB_SELECT with element size 1 or 2) return 0 without reading memory; inactive lanes keep vD.""" if any(m in mods for m in ("lds", "tfe", "d16")): raise Unsupported(op + " form") nbytes, signed = self.BUFFER_SUB[op] vd = a[0] if vd["k"] != "vgpr" or vd.get("n", 1) != 1: raise Unsupported(op + " destination") addr, _, in_b, step = self.buffer_address(a, mods, elem=nbytes) act = self.active_b() cond = self.tmp() self.emit(f"{cond} = OpLogicalAnd %bool {act} {in_b}") lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" pre_label = self.current_label_placeholder() self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") alo, b3, b64, aligned, sh = (self.tmp() for _ in range(5)) self.emit(f"{alo} = OpUConvert %uint {addr}") self.emit(f"{b3} = OpBitwiseAnd %uint {alo} {self.cu(3)}") self.emit(f"{b64} = OpUConvert %ulong {b3}") self.emit(f"{aligned} = OpISub %ulong {addr} {b64}") self.emit(f"{sh} = OpShiftLeftLogical %uint {b3} {self.cu(3)}") ptr, host = self.tmp(), self.host_addr(aligned, "load", lambda: self.guard_delta(self.sub_dwords(nbytes, b3), step)) self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") load_mem = self._psb_load_op(mods) p0, w0 = self.buf_dword_ptr(ptr, host, step, 0), self.tmp() self.emit(f"{w0} = OpLoad %uint {p0} {load_mem}") ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract" val = self.tmp() if nbytes == 1: self.emit(f"{val} = {ext} %uint {w0} {sh} {self.cu(8)}") else: cross, idx1, w1, lo_part, hi_byte, hi_sh, crossed, raw = (self.tmp() for _ in range(8)) self.emit(f"{cross} = OpIEqual %bool {b3} {self.cu(3)}") self.emit(f"{idx1} = OpSelect %uint {cross} {self.cu(1)} {self.cu(0)}") p1 = self.buf_dword_ptr(ptr, host, step, idx1, same_base=True) # idx1 0: the dword p0 reads self.emit(f"{w1} = OpLoad %uint {p1} {load_mem}") self.emit(f"{lo_part} = OpShiftRightLogical %uint {w0} {sh}") self.emit(f"{hi_byte} = OpBitFieldUExtract %uint {w1} {self.cu(0)} {self.cu(8)}") self.emit(f"{hi_sh} = OpShiftLeftLogical %uint {hi_byte} {self.cu(8)}") self.emit(f"{crossed} = OpBitwiseOr %uint {lo_part} {hi_sh}") self.emit(f"{raw} = OpSelect %uint {cross} {crossed} {lo_part}") self.emit(f"{val} = {ext} %uint {raw} {self.cu(0)} {self.cu(16)}") self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") res = self.tmp() self.emit(f"{res} = OpPhi %uint {val} {lbl_do} {self.cu(0)} {pre_label}") self.dst(vd, res) # GFX10 buffer formats (from Mesa src/amd/registers/gfx10-rsrc.json, GFX10_FORMAT): # code: (bytes, kind, component bit widths from bit 0) # The names list the widths from the top bit down, so 2_10_10_10 (50) is R10G10B10A2. # Full-width SINT and UINT preserve the same raw dwords. Keep separate kinds for signed D16 conversion. # Kinds: unorm/snorm/uint (the first entries), uscaled/sscaled (the integer converted to float, not divided), sint # (sign-extended), ufloat (the unsigned 5-bit-exponent 10/11-bit float). 10_11_11 and 11_11_10 are the FLOAT ones # only on GFX11; GFX10's own UNORM/SNORM/USCALED/SSCALED/UINT/SINT codes of those two (30-35, 37-42) are in the table. FORMATS = {22: (4, "f32", (32,)), 64: (8, "f32", (32, 32)), 74: (12, "f32", (32, 32, 32)), 77: (16, "f32", (32, 32, 32, 32)), 20: (4, "u32", (32,)), 62: (8, "u32", (32, 32)), 72: (12, "u32", (32, 32, 32)), 75: (16, "u32", (32, 32, 32, 32)), 21: (4, "i32", (32,)), 63: (8, "i32", (32, 32)), 73: (12, "i32", (32, 32, 32)), 76: (16, "i32", (32, 32, 32, 32)), 13: (2, "f16", (16,)), 29: (4, "f16", (16, 16)), 71: (8, "f16", (16, 16, 16, 16)), 1: (1, "unorm", (8,)), 5: (1, "uint", (8,)), 14: (2, "unorm", (8, 8)), 56: (4, "unorm", (8, 8, 8, 8)), 57: (4, "snorm", (8, 8, 8, 8)), 60: (4, "uint", (8, 8, 8, 8)), 7: (2, "unorm", (16,)), 23: (4, "unorm", (16, 16)), 24: (4, "snorm", (16, 16)), 65: (8, "unorm", (16, 16, 16, 16)), 66: (8, "snorm", (16, 16, 16, 16)), 44: (4, "unorm", (2, 10, 10, 10)), 50: (4, "unorm", (10, 10, 10, 2)), 69: (8, "uint", (16, 16, 16, 16)), 27: (4, "uint", (16, 16)), 2: (1, "snorm", (8,)), 8: (2, "snorm", (16,)), 15: (2, "snorm", (8, 8)), # Narrow integer formats, measured natively on gfx1036 (wave32 and wave64): UINT loads zero-extend # and stores saturate to the channel; SINT loads sign-extend and stores clamp the 32-bit signed value # to [-2^(w-1), 2^(w-1) - 1]. 3: (1, "uscaled", (8,)), 4: (1, "sscaled", (8,)), 5: (1, "uint", (8,)), 6: (1, "sint", (8,)), 9: (2, "uscaled", (16,)), 10: (2, "sscaled", (16,)), 11: (2, "uint", (16,)), 12: (2, "sint", (16,)), 16: (2, "uscaled", (8, 8)), 17: (2, "sscaled", (8, 8)), 18: (2, "uint", (8, 8)), 19: (2, "sint", (8, 8)), 25: (4, "uscaled", (16, 16)), 26: (4, "sscaled", (16, 16)), 28: (4, "sint", (16, 16)), 36: (4, "ufloat", (11, 11, 10)), 43: (4, "ufloat", (10, 11, 11)), 45: (4, "snorm", (2, 10, 10, 10)), 46: (4, "uscaled", (2, 10, 10, 10)), 47: (4, "sscaled", (2, 10, 10, 10)), 48: (4, "uint", (2, 10, 10, 10)), 49: (4, "sint", (2, 10, 10, 10)), 51: (4, "snorm", (10, 10, 10, 2)), 52: (4, "uscaled", (10, 10, 10, 2)), 53: (4, "sscaled", (10, 10, 10, 2)), 54: (4, "uint", (10, 10, 10, 2)), 55: (4, "sint", (10, 10, 10, 2)), 58: (4, "uscaled", (8, 8, 8, 8)), 59: (4, "sscaled", (8, 8, 8, 8)), 61: (4, "sint", (8, 8, 8, 8)), 67: (8, "uscaled", (16, 16, 16, 16)), 68: (8, "sscaled", (16, 16, 16, 16)), 70: (8, "sint", (16, 16, 16, 16)), # 10_11_11 (x 11 bits, y 11, z 10) and 11_11_10 (x 10, y 11, z 11) with the other numeric formats: GFX11 has none # of them, a real RDNA2 (gfx1036, @AwkGrep256, #2022) validated the layout and conversions of all twelve. 30: (4, "unorm", (11, 11, 10)), 31: (4, "snorm", (11, 11, 10)), 32: (4, "uscaled", (11, 11, 10)), 33: (4, "sscaled", (11, 11, 10)), 34: (4, "uint", (11, 11, 10)), 35: (4, "sint", (11, 11, 10)), 37: (4, "unorm", (10, 11, 11)), 38: (4, "snorm", (10, 11, 11)), 39: (4, "uscaled", (10, 11, 11)), 40: (4, "sscaled", (10, 11, 11)), 41: (4, "uint", (10, 11, 11)), 42: (4, "sint", (10, 11, 11))} # The run-time FORMAT decode (SHADER-849): a format's conversion is one of these kinds, and the tables below # describe them per format code, so that the decode needs no branch and no copy per format. FMT_RAW, FMT_SINT, FMT_USCALED, FMT_SSCALED, FMT_UNORM, FMT_SNORM, FMT_F16, FMT_UFLOAT = range(8) FMT_NONE = 8 # a code outside FORMATS: the decode gives 0 FMT_KINDS = {"f32": FMT_RAW, "u32": FMT_RAW, "i32": FMT_RAW, "uint": FMT_RAW, "sint": FMT_SINT, "uscaled": FMT_USCALED, "sscaled": FMT_SSCALED, "unorm": FMT_UNORM, "snorm": FMT_SNORM, "f16": FMT_F16, "ufloat": FMT_UFLOAT} @classmethod def fmt_desc_table(cls): """One uint per format code: the conversion kind, the channel count and the four channel widths. The bit offset of a channel is the sum of the widths before it, so the table holds the widths only and the offsets follow. A code outside FORMATS gets FMT_NONE.""" table = [] for code in range(128): entry = cls.FORMATS.get(code) kind = cls.FMT_KINDS.get(entry[1], cls.FMT_NONE) if entry else cls.FMT_NONE widths = entry[2] if entry else () word = kind | (len(widths) << 4) for i in range(4): word |= (widths[i] if i < len(widths) else 0) << (7 + 6 * i) table.append(word) return table # The run-time FORMAT encode (3B.6): packed into one 32-bit word per format code: # bits [3:0] enc_kind (0..9), [6:4] ncomp (0..4), [12:7]..[30:25] widths[0..3], bit 31 = BGRA swap (50, 56). ENC_NONE, ENC_F32, ENC_U32, ENC_I32, ENC_UINT, ENC_SINT, ENC_UNORM, ENC_SNORM, ENC_F16, ENC_UFLOAT = range(10) ENC_KINDS = {"f32": ENC_F32, "u32": ENC_U32, "i32": ENC_I32, "uint": ENC_UINT, "sint": ENC_SINT, "unorm": ENC_UNORM, "uscaled": ENC_UNORM, "snorm": ENC_SNORM, "sscaled": ENC_SNORM, "f16": ENC_F16, "ufloat": ENC_UFLOAT} @classmethod def fmt_enc_desc_table(cls): """One uint per format code for table-driven buffer_store_format encoding.""" table = [] for code in range(128): entry = cls.FORMATS.get(code) kind = cls.ENC_KINDS.get(entry[1], cls.ENC_NONE) if entry else cls.ENC_NONE widths = entry[2] if entry else () word = kind | (len(widths) << 4) for i in range(4): word |= (widths[i] if i < len(widths) else 0) << (7 + 6 * i) if code in (50, 56): word |= 1 << 31 table.append(word) return table @classmethod def fmt_norm_reps(cls): """The 64-bit repeat constants of the exact norm quotient, one per width (1..16). The quotient m / (2^n - 1) is m's n bits repeated; the constant holds the first 64 of them.""" return [0] + [sum(1 << (64 - n * (k + 1)) for k in range(64 // n)) for n in range(1, 17)] def encode_norm_bits(self, u, w, signed): """Exact single-rounded UNORM/SNORM channel bits from an f32 bit pattern u (NaN already mapped to 0). RDNA2 (gfx1036, wave32 and wave64, MUBUF and MTBUF) rounds the exact product clamp(x) * scale once with ties away from zero, rather than rounding through an intermediate f32 multiply (which double-rounds e.g. UNORM16(0.3) to 19660 instead of 19661). For |x| < 2^-17 and w <= 16, |x| * scale < 0.5 so the result is 0; for 2^-17 <= |x| < 1.0, exp is in 110..126, shift = 150 - exp is in 24..40, and (m * scale + 2^(shift-1)) >> shift fits in 64-bit unsigned integer arithmetic with no overflow.""" scale = (1 << (w - 1)) - 1 if signed else (1 << w) - 1 sign, neg, a = self.tmp(), self.tmp(), self.tmp() self.emit(f"{sign} = OpShiftRightLogical %uint {u} {self.cu(31)}") self.emit(f"{neg} = OpINotEqual %bool {sign} {self.cu(0)}") self.emit(f"{a} = OpBitwiseAnd %uint {u} {self.cu(0x7FFFFFFF)}") small, ge1, exp_, ec, ec2, shift, sh64, sh1, sh1_64 = (self.tmp() for _ in range(9)) self.emit(f"{small} = OpULessThan %bool {a} {self.cu(0x37000000)}") self.emit(f"{ge1} = OpUGreaterThanEqual %bool {a} {self.cu(0x3F800000)}") self.emit(f"{exp_} = OpShiftRightLogical %uint {a} {self.cu(23)}") self.emit(f"{ec} = OpExtInst %uint %glsl UMax {exp_} {self.cu(110)}") self.emit(f"{ec2} = OpExtInst %uint %glsl UMin {ec} {self.cu(126)}") self.emit(f"{shift} = OpISub %uint {self.cu(150)} {ec2}") self.emit(f"{sh64} = OpUConvert %ulong {shift}") self.emit(f"{sh1} = OpISub %uint {shift} {self.cu(1)}") self.emit(f"{sh1_64} = OpUConvert %ulong {sh1}") mant, m, m64, p, half, ps, q64, q, mag1, mag = (self.tmp() for _ in range(10)) self.emit(f"{mant} = OpBitwiseAnd %uint {a} {self.cu(0x7FFFFF)}") self.emit(f"{m} = OpBitwiseOr %uint {mant} {self.cu(0x800000)}") self.emit(f"{m64} = OpUConvert %ulong {m}") self.emit(f"{p} = OpIMul %ulong {m64} {self.cl(scale)}") self.emit(f"{half} = OpShiftLeftLogical %ulong {self.cl(1)} {sh1_64}") self.emit(f"{ps} = OpIAdd %ulong {p} {half}") self.emit(f"{q64} = OpShiftRightLogical %ulong {ps} {sh64}") self.emit(f"{q} = OpUConvert %uint {q64}") self.emit(f"{mag1} = OpSelect %uint {small} {self.cu(0)} {q}") self.emit(f"{mag} = OpSelect %uint {ge1} {self.cu(scale)} {mag1}") res = self.tmp() if signed: nmag = self.tmp() self.emit(f"{nmag} = OpISub %uint {self.cu(0)} {mag}") self.emit(f"{res} = OpSelect %uint {neg} {nmag} {mag}") else: self.emit(f"{res} = OpSelect %uint {neg} {self.cu(0)} {mag}") return res def encode_format(self, fcomps, icomps, code): """Encode one element of format `code` -> list of uint ids (whole dwords; elements under 4 bytes return one value in the low bits). fcomps are f32 bit patterns (float/normalized kinds), icomps integer bit patterns (u32/i32/uint/sint).""" try: size, kind, widths = self.FORMATS[code] except KeyError: raise Unsupported(f"format {code} (not in FORMATS)") if kind == "f32": return list(fcomps[:len(widths)]) if kind in ("u32", "i32"): return list(icomps[:len(widths)]) words = [self.cu(0)] * max(1, (size + 3) // 4) bit = 0 for c, w in enumerate(widths): if kind == "f16": # f32 -> f16 toward zero, finite values past the range -> +-65504: measured natively on gfx1036 for # 16_FLOAT, 16_16_FLOAT and 16_16_16_16_FLOAT stores (SHADER-358; gfx1150 does the same, #1548). field = self.mem_f16(self.tof(fcomps[c])) elif kind in ("unorm", "uscaled"): # a SCALED store converts as its NORM format field = self.encode_norm_bits(fcomps[c], w, signed=False) elif kind in ("snorm", "sscaled"): field = self.encode_norm_bits(fcomps[c], w, signed=True) elif kind == "sint": # Narrow SINT stores clamp the signed value to the field's range. clamped, field = self.tmp(), self.tmp() lo, hi = self.as_int(self.cu((-(1 << (w - 1))) & 0xFFFFFFFF)), self.as_int(self.cu((1 << (w - 1)) - 1)) self.emit(f"{clamped} = OpExtInst %int %glsl SClamp {self.as_int(icomps[c])} {lo} {hi}") self.emit(f"{field} = OpBitcast %uint {clamped}") elif kind == "ufloat": field = self.ufloat_encode_bits(fcomps[c], w) else: # Narrow UINT stores saturate to the field width before insertion. field = self.tmp() self.emit(f"{field} = OpExtInst %uint %glsl UMin {icomps[c]} {self.cu((1 << w) - 1)}") wi = bit // 32 ins = self.tmp() self.emit(f"{ins} = OpBitFieldInsert %uint {words[wi]} {field} {self.cu(bit % 32)} {self.cu(w)}") words[wi] = ins bit += w return words def ufloat_encode_bits(self, x, w): """The w-bit unsigned float (5 exponent bits, bias 15, w - 5 mantissa bits) of the f32 bits x, integer ops only. Round toward zero; a value past the largest finite one gives that largest finite value; +-0 and every negative number except a NaN give 0; +inf gives infinity; a NaN keeps the top mantissa bits of its payload, or 1 when they are all zero, so it stays a NaN (all measured on gfx1150, tools/buffer_format_fuzz.py).""" mb = w - 5 (a, ex, sg, sig, hid, sh0, sh, shc, dn, nr0, nr, nm, nm1, nz, nmant, nanb, isnan, isinf, big, norm, r0, r1, r2, neg, ng, r3, snan) = (self.tmp() for _ in range(27)) self.emit(f"{a} = OpBitwiseAnd %uint {x} {self.cu(0x7FFFFFFF)}") self.emit(f"{sg} = OpShiftRightLogical %uint {x} {self.cu(31)}") self.emit(f"{ex} = OpShiftRightLogical %uint {a} {self.cu(23)}") self.emit(f"{hid} = OpBitwiseAnd %uint {a} {self.cu(0x7FFFFF)}") self.emit(f"{sig} = OpBitwiseOr %uint {hid} {self.cu(0x800000)}") self.emit(f"{sh0} = OpISub %uint {self.cu(136 - mb)} {ex}") # denormal result: sig >> (136 - mb - e) self.emit(f"{shc} = OpExtInst %uint %glsl UMin {sh0} {self.cu(31)}") self.emit(f"{dn} = OpShiftRightLogical %uint {sig} {shc}") self.emit(f"{nr0} = OpISub %uint {a} {self.cu(112 << 23)}") # normal result: rebias, drop mantissa bits self.emit(f"{nr} = OpShiftRightLogical %uint {nr0} {self.cu(23 - mb)}") self.emit(f"{nm} = OpShiftRightLogical %uint {a} {self.cu(23 - mb)}") self.emit(f"{nm1} = OpBitwiseAnd %uint {nm} {self.cu((1 << mb) - 1)}") self.emit(f"{nz} = OpIEqual %bool {nm1} {self.cu(0)}") self.emit(f"{nmant} = OpSelect %uint {nz} {self.cu(1)} {nm1}") self.emit(f"{nanb} = OpBitwiseOr %uint {nmant} {self.cu(31 << mb)}") self.emit(f"{isnan} = OpUGreaterThan %bool {a} {self.cu(0x7F800000)}") self.emit(f"{isinf} = OpIEqual %bool {a} {self.cu(0x7F800000)}") self.emit(f"{big} = OpUGreaterThanEqual %bool {a} {self.cu(0x47800000)}") self.emit(f"{norm} = OpUGreaterThanEqual %bool {a} {self.cu(0x38800000)}") self.emit(f"{r0} = OpSelect %uint {norm} {nr} {dn}") self.emit(f"{r1} = OpSelect %uint {big} {self.cu((30 << mb) | ((1 << mb) - 1))} {r0}") self.emit(f"{r2} = OpSelect %uint {isinf} {self.cu(31 << mb)} {r1}") self.emit(f"{r3} = OpSelect %uint {isnan} {nanb} {r2}") self.emit(f"{neg} = OpINotEqual %bool {sg} {self.cu(0)}") self.emit(f"{snan} = OpLogicalNot %bool {isnan}") self.emit(f"{ng} = OpLogicalAnd %bool {neg} {snan}") res = self.tmp() self.emit(f"{res} = OpSelect %uint {ng} {self.cu(0)} {r3}") return res def field_extract(self, src, off, width): """(src >> off) & ((1 << width) - 1). off and width are ints (constants) or ids (run-time values).""" if isinstance(off, int) and isinstance(width, int): f = self.tmp() self.emit(f"{f} = OpBitFieldUExtract %uint {src} {self.cu(off)} {self.cu(width)}") return f o = self.cu(off) if isinstance(off, int) else off w = self.cu(width) if isinstance(width, int) else width sh, one, m1, shifted, res = (self.tmp() for _ in range(5)) self.emit(f"{sh} = OpBitwiseAnd %uint {w} {self.cu(31)}") self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {sh}") self.emit(f"{m1} = OpISub %uint {one} {self.cu(1)}") self.emit(f"{shifted} = OpShiftRightLogical %uint {src} {o}") self.emit(f"{res} = OpBitwiseAnd %uint {shifted} {m1}") return res def ufloat_decode_bits(self, f, w): """f32 bits of the w-bit unsigned float in the low bits of f (see ufloat_encode_bits): exact, integer ops only. A NaN keeps its payload shifted up, unquieted; there is no sign. w is an int (a constant width) or an id (a run-time width, SHADER-849).""" if isinstance(w, int): mb = w - 5 else: mb = self.tmp() self.emit(f"{mb} = OpISub %uint {w} {self.cu(5)}") # A width under 5 wraps around, and one over 23 would shift the mantissa out: the candidate is only # used for the two ufloat formats (widths 10 and 11), so any value in range is fine here. hi, mb2 = self.tmp(), self.tmp() self.emit(f"{hi} = OpUGreaterThan %bool {mb} {self.cu(23)}") self.emit(f"{mb2} = OpSelect %uint {hi} {self.cu(23)} {mb}") mb = mb2 eb, es, ms, nrm, p, pi, pb, db, dsh, dm, dmk, dn, nzm, isz, dres, inf, mz, r0, r1, r2 = \ (self.tmp() for _ in range(20)) e = self.field_extract(f, mb, 5) m = self.field_extract(f, 0, mb) self.emit(f"{eb} = OpIAdd %uint {e} {self.cu(112)}") self.emit(f"{es} = OpShiftLeftLogical %uint {eb} {self.cu(23)}") if isinstance(w, int): self.emit(f"{ms} = OpShiftLeftLogical %uint {m} {self.cu(23 - mb)}") else: sh = self.tmp() self.emit(f"{sh} = OpISub %uint {self.cu(23)} {mb}") self.emit(f"{ms} = OpShiftLeftLogical %uint {m} {sh}") self.emit(f"{nrm} = OpBitwiseOr %uint {es} {ms}") # exponent 0: a denormal m * 2^(-14 - mb); its top set bit p gives the f32 exponent p + 113 - mb self.emit(f"{pi} = OpExtInst %int %glsl FindUMsb {m}") self.emit(f"{p} = OpBitcast %uint {pi}") if isinstance(w, int): self.emit(f"{pb} = OpIAdd %uint {p} {self.cu(113 - mb)}") else: pb2 = self.tmp() self.emit(f"{pb2} = OpISub %uint {self.cu(113)} {mb}") self.emit(f"{pb} = OpIAdd %uint {p} {pb2}") self.emit(f"{db} = OpShiftLeftLogical %uint {pb} {self.cu(23)}") self.emit(f"{dsh} = OpISub %uint {self.cu(23)} {p}") self.emit(f"{dm} = OpShiftLeftLogical %uint {m} {dsh}") self.emit(f"{dmk} = OpBitwiseAnd %uint {dm} {self.cu(0x7FFFFF)}") self.emit(f"{dn} = OpBitwiseOr %uint {db} {dmk}") self.emit(f"{mz} = OpIEqual %bool {m} {self.cu(0)}") self.emit(f"{dres} = OpSelect %uint {mz} {self.cu(0)} {dn}") self.emit(f"{isz} = OpIEqual %bool {e} {self.cu(0)}") self.emit(f"{r0} = OpSelect %uint {isz} {dres} {nrm}") self.emit(f"{inf} = OpIEqual %bool {e} {self.cu(31)}") self.emit(f"{r1} = OpBitwiseOr %uint {ms} {self.cu(0x7F800000)}") self.emit(f"{r2} = OpSelect %uint {inf} {r1} {r0}") return r2 def f16_widen_bits(self, f): """The f32 bits of the half in the low 16 bits of f, with the NaN payload the hardware widens to. A half NaN widens by shifting its payload, keeping the sign and the quiet bit as they are: measured natively on RDNA2 (gfx1036, tools/f16_widen_probe.py) 0x7ddb (sNaN) -> 0x7FBB6000 and 0x7FE6 (qNaN) -> 0x7FFCC000, the same words for formats 13, 29 and 71, MUBUF and MTBUF, wave32 and wave64. UnpackHalf2x16 leaves a NaN undefined: the interpreter canonicalises it to 0x7FC00000 and v_cvt_f32_f16 (what a driver lowers it to) sets the quiet bit, which the typed load does not, so the NaN case is built from the bits.""" v2, x = self.tmp(), self.tmp() self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {f}") self.emit(f"{x} = OpCompositeExtract %float {v2} 0") mag, is_nan, sg, sgsh, fr, mant, nan0, nan_bits, xb, res = (self.tmp() for _ in range(10)) self.emit(f"{mag} = OpBitwiseAnd %uint {f} {self.cu(0x7FFF)}") self.emit(f"{is_nan} = OpUGreaterThan %bool {mag} {self.cu(0x7C00)}") self.emit(f"{sg} = OpBitwiseAnd %uint {f} {self.cu(0x8000)}") self.emit(f"{sgsh} = OpShiftLeftLogical %uint {sg} {self.cu(16)}") self.emit(f"{fr} = OpBitwiseAnd %uint {f} {self.cu(0x3FF)}") self.emit(f"{mant} = OpShiftLeftLogical %uint {fr} {self.cu(13)}") self.emit(f"{nan0} = OpBitwiseOr %uint {sgsh} {self.cu(0x7F800000)}") self.emit(f"{nan_bits} = OpBitwiseOr %uint {nan0} {mant}") self.emit(f"{xb} = OpBitcast %uint {x}") self.emit(f"{res} = OpSelect %uint {is_nan} {nan_bits} {xb}") return res def norm_bits(self, m, n): """f32 bits of m / (2^n - 1), correctly rounded, for an n-bit unsigned id m (1 <= n <= 16), integer ops only. In binary, m / (2^n - 1) is m's n bits repeated forever. T = m * sum(2^(64 - n(k+1))) holds the first 64 of them (the partial block at the bottom is dropped, below every bit used here). For 0 < m < 2^n - 1 the top 1 of T is in its high dword (T >= 2^(64-n)), so p = FindUMsb(T >> 32) is 16..31 and the value is in [2^(p-32), 2^(p-31)). The mantissa is T >> (p + 9) (24 bits with the hidden one) and the round bit the one below it. The repeating tail is never all zero, so a tie can't happen: round to nearest is "add the round bit". A carry out of the mantissa moves into the exponent through the plain add. 0 and 2^n - 1 are exact (0 and 1.0).""" rep = sum(1 << (64 - n * (k + 1)) for k in range(64 // n)) m64, t, h64, hi, pi, p, s, s64, q64, q, s1, s164, r64, rb, e, eb, b0, b1, b2, z, one, b3, b4 = \ (self.tmp() for _ in range(23)) self.emit(f"{m64} = OpUConvert %ulong {m}") self.emit(f"{t} = OpIMul %ulong {m64} {self.cl(rep)}") self.emit(f"{h64} = OpShiftRightLogical %ulong {t} {self.cl(32)}") self.emit(f"{hi} = OpUConvert %uint {h64}") self.emit(f"{pi} = OpExtInst %int %glsl FindUMsb {hi}") self.emit(f"{p} = OpBitcast %uint {pi}") self.emit(f"{s} = OpIAdd %uint {p} {self.cu(9)}") # m = 0 gives p = -1: s = 8, result unused self.emit(f"{s64} = OpUConvert %ulong {s}") self.emit(f"{q64} = OpShiftRightLogical %ulong {t} {s64}") self.emit(f"{q} = OpUConvert %uint {q64}") self.emit(f"{s1} = OpISub %uint {s} {self.cu(1)}") self.emit(f"{s164} = OpUConvert %ulong {s1}") self.emit(f"{r64} = OpShiftRightLogical %ulong {t} {s164}") self.emit(f"{rb} = OpUConvert %uint {r64}") self.emit(f"{e} = OpIAdd %uint {p} {self.cu(95)}") # biased exponent p - 32 + 127 self.emit(f"{eb} = OpShiftLeftLogical %uint {e} {self.cu(23)}") self.emit(f"{b0} = OpISub %uint {q} {self.cu(0x800000)}") # drop the hidden one self.emit(f"{b1} = OpIAdd %uint {eb} {b0}") self.emit(f"{b2} = OpBitwiseAnd %uint {rb} {self.cu(1)}") self.emit(f"{b3} = OpIAdd %uint {b1} {b2}") self.emit(f"{z} = OpIEqual %bool {m} {self.cu(0)}") self.emit(f"{one} = OpIEqual %bool {m} {self.cu((1 << n) - 1)}") self.emit(f"{b4} = OpSelect %uint {one} {self.cu(0x3F800000)} {b3}") res = self.tmp() self.emit(f"{res} = OpSelect %uint {z} {self.cu(0)} {b4}") return res def tbuffer_norm_bits(self, magnitude: str, width: int) -> str: """Share the fixed-format quotient across instructions and channels with the same magnitude width.""" function = f"%tbuffer_norm_{width}" if width not in self.tbuffer_norm_fns: parameter = f"{function}_m" outer_body, self.body = self.body, [] result = self.norm_bits(parameter, width) lines, self.body = self.body, outer_body self.tbuffer_norm_fns[width] = [ f"{function} = OpFunction %uint Pure %fn_tbuffer_norm", f"{parameter} = OpFunctionParameter %uint", f"{function}_entry = OpLabel", *lines, f"OpReturnValue {result}", "OpFunctionEnd", ] result = self.tmp() self.emit(f"{result} = OpFunctionCall %uint {function} {magnitude}") return result def decode_format(self, words, code, *, fixed: bool = False): """Decode one element of format `code` from raw dwords -> 4 uint ids holding f32 or integer bits. Missing channels repeat the format's own (component c = c mod n): measured on RX 6700 for SHADER-86. UNORM/SNORM give the correctly rounded quotient, as the RX 6700 does, built with integer ops (norm_bits): OpFDiv is allowed 2.5 ULP and the AMD and NVIDIA drivers return the reciprocal-multiply result for it (#599).""" try: size, kind, widths = self.FORMATS[code] except KeyError: raise Unsupported(f"format {code} (not in FORMATS)") if kind in ("f32", "u32", "i32"): n = len(widths) vals = list(words[:n]) while len(vals) < 4: vals.append(vals[len(vals) % n]) return vals normalize = self.tbuffer_norm_bits if fixed else self.norm_bits out, bit = [], 0 for w in widths: src = words[bit // 32] f = self.tmp() self.emit(f"{f} = OpBitFieldUExtract %uint {src} {self.cu(bit % 32)} {self.cu(w)}") if kind == "f16": out.append(self.f16_widen_bits(f)) elif kind == "unorm": out.append(normalize(f, w)) elif kind == "uscaled": x = self.tmp() self.emit(f"{x} = OpConvertUToF %float {f}") out.append(self.tou(x)) elif kind in ("sscaled", "sint"): si = self.tmp() self.emit(f"{si} = OpBitFieldSExtract %int {self.as_int(src)} {self.cu(bit % 32)} {self.cu(w)}") if kind == "sint": u = self.tmp() self.emit(f"{u} = OpBitcast %uint {si}") out.append(u) else: x = self.tmp() self.emit(f"{x} = OpConvertSToF %float {si}") out.append(self.tou(x)) elif kind == "ufloat": out.append(self.ufloat_decode_bits(f, w)) elif kind == "snorm": # magnitude over 2^(w-1)-1 with the same integer rounding; the most negative code is -1.0 si, neg, ab, au, sg, sel, lo, res = (self.tmp() for _ in range(8)) self.emit(f"{si} = OpBitFieldSExtract %int {self.as_int(src)} {self.cu(bit % 32)} {self.cu(w)}") self.emit(f"{neg} = OpSLessThan %bool {si} {self.as_int(self.cu(0))}") self.emit(f"{ab} = OpExtInst %int %glsl SAbs {si}") self.emit(f"{au} = OpBitcast %uint {ab}") mag = normalize(au, w - 1) self.emit(f"{sg} = OpBitwiseOr %uint {mag} {self.cu(0x80000000)}") self.emit(f"{sel} = OpSelect %uint {neg} {sg} {mag}") self.emit(f"{lo} = OpULessThan %bool {au} {self.cu(1 << (w - 1))}") self.emit(f"{res} = OpSelect %uint {lo} {sel} {self.cu(0xBF800000)}") out.append(res) elif kind == "sint": si, su = self.tmp(), self.tmp() self.emit(f"{si} = OpBitFieldSExtract %int {self.as_int(src)} {self.cu(bit % 32)} {self.cu(w)}") self.emit(f"{su} = OpBitcast %uint {si}") out.append(su) else: # uint: raw integer out.append(f) bit += w n = len(out) while len(out) < 4: out.append(out[len(out) % n]) return out BUF_ATOMICS = {"add": ("OpAtomicIAdd", 0), "sub": ("OpAtomicISub", 0), "umin": ("OpAtomicUMin", 0xFFFFFFFF), "umax": ("OpAtomicUMax", 0), "smin": ("OpAtomicSMin", 0x7FFFFFFF), "smax": ("OpAtomicSMax", 0x80000000), "and": ("OpAtomicAnd", 0xFFFFFFFF), "or": ("OpAtomicOr", 0), "xor": ("OpAtomicXor", 0), "swap": ("OpAtomicExchange", None), "cmpswap": ("OpAtomicCompareExchange", None)} def atomic_inc_dec_cas(self, p, val, kind, lbl_do): """Structured OpAtomicCompareExchange CAS loop on `%_ptr_PSB_uint` pointer `p` for RDNA2 32-bit unsigned wrapping atomic inc/dec (RDNA2 ISA): inc: M = (M >= DATA) ? 0 : M + 1 dec: M = (M == 0 || M > DATA) ? DATA : M - 1 csub: M = (DATA > M) ? 0 : M - DATA, a subtract clamped at 0 (GFX10.3 BUFFER/GLOBAL_ATOMIC_CSUB; measured on gfx1036, #3193) Returns `(old_val, exit_label)` where `old_val` is the pre-op word in memory.""" lbl_hdr, lbl_cont, lbl_exit = (self.tmp() + s for s in ("_hdr", "_cont", "_exit")) init = self.tmp() self.emit(f"{init} = OpAtomicLoad %uint {p} {self.cu(1)} {self.cu(0)}") self.emit(f"OpBranch {lbl_hdr}") self.emit(f"{lbl_hdr} = OpLabel") cur, got = self.tmp(), self.tmp() self.emit(f"{cur} = OpPhi %uint {init} {lbl_do} {got} {lbl_cont}") if kind == "csub": wrap, step, new_u = self.tmp(), self.tmp(), self.tmp() self.emit(f"{wrap} = OpUGreaterThan %bool {val} {cur}") self.emit(f"{step} = OpISub %uint {cur} {val}") self.emit(f"{new_u} = OpSelect %uint {wrap} {self.cu(0)} {step}") elif kind == "inc": wrap, step, new_u = self.tmp(), self.tmp(), self.tmp() self.emit(f"{wrap} = OpUGreaterThanEqual %bool {cur} {val}") self.emit(f"{step} = OpIAdd %uint {cur} {self.cu(1)}") self.emit(f"{new_u} = OpSelect %uint {wrap} {self.cu(0)} {step}") else: is_z, gt, wrap, step, new_u = (self.tmp() for _ in range(5)) self.emit(f"{is_z} = OpIEqual %bool {cur} {self.cu(0)}") self.emit(f"{gt} = OpUGreaterThan %bool {cur} {val}") self.emit(f"{wrap} = OpLogicalOr %bool {is_z} {gt}") self.emit(f"{step} = OpISub %uint {cur} {self.cu(1)}") self.emit(f"{new_u} = OpSelect %uint {wrap} {val} {step}") done = self.tmp() self.emit(f"{got} = OpAtomicCompareExchange %uint {p} {self.cu(1)} {self.cu(0)} {self.cu(0)} {new_u} {cur}") self.emit(f"{done} = OpIEqual %bool {got} {cur}") self.emit(f"OpLoopMerge {lbl_exit} {lbl_cont} None") self.emit(f"OpBranchConditional {done} {lbl_exit} {lbl_cont}") self.emit(f"{lbl_cont} = OpLabel") self.emit(f"OpBranch {lbl_hdr}") self.emit(f"{lbl_exit} = OpLabel") return cur, lbl_exit def atomic_aligned(self, addr, align_bytes): """True iff 64-bit Xbox VA `addr` is naturally aligned to `align_bytes` (4 or 8). Measured natively on RDNA2 (gfx1036, wave32 & wave64): unaligned buffer_atomic* and global_atomic* leave memory untouched and active glc lanes receive 0 / (0, 0), while inactive lanes keep vdst.""" lo, rem, ok = self.tmp(), self.tmp(), self.tmp() self.emit(f"{lo} = OpUConvert %uint {addr}") self.emit(f"{rem} = OpBitwiseAnd %uint {lo} {self.cu(align_bytes - 1)}") self.emit(f"{ok} = OpIEqual %bool {rem} {self.cu(0)}") return ok def _emit_atomic_fminmax_cas(self, kind, addr, val_f, cond): """Shared CAS loop for 32-bit float atomic min/max (global_atomic_{fmin,fmax} and buffer_atomic_{fmin,fmax}). Returns the pre-op uint word on taken lanes and 0 on skipped lanes (caller writes via self.dst so inactive lanes keep their destination VGPR untouched).""" lbl_do, lbl_hdr, lbl_cont, lbl_exit, lbl_end = ( self.tmp() + s for s in ("_do", "_hdr", "_cont", "_exit", "_end")) pre = self.current_label_placeholder() self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") ptr, p, init = self.tmp(), self.tmp(), self.tmp() self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr, 'rmw')}") self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") self.emit(f"{init} = OpAtomicLoad %uint {p} {self.cu(1)} {self.cu(0)}") self.emit(f"OpBranch {lbl_hdr}") self.emit(f"{lbl_hdr} = OpLabel") cur, cur_f, new_f, new_u, got, done = (self.tmp() for _ in range(6)) self.emit(f"{cur} = OpPhi %uint {init} {lbl_do} {got} {lbl_cont}") self.emit(f"{cur_f} = OpBitcast %float {cur}") glsl_op = "NMin" if kind == "fmin" else "NMax" self.emit(f"{new_f} = OpExtInst %float %glsl {glsl_op} {cur_f} {val_f}") self.emit(f"{new_u} = OpBitcast %uint {new_f}") self.emit(f"{got} = OpAtomicCompareExchange %uint {p} {self.cu(1)} {self.cu(0)} {self.cu(0)} {new_u} {cur}") self.emit(f"{done} = OpIEqual %bool {got} {cur}") self.emit(f"OpLoopMerge {lbl_exit} {lbl_cont} None") self.emit(f"OpBranchConditional {done} {lbl_exit} {lbl_cont}") self.emit(f"{lbl_cont} = OpLabel") self.emit(f"OpBranch {lbl_hdr}") self.emit(f"{lbl_exit} = OpLabel") cur = self.guard_zero(cur) self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") old = self.tmp() self.emit(f"{old} = OpPhi %uint {cur} {lbl_exit} {self.cu(0)} {pre}") return old def global_atomic(self, op, a, mods): """global_atomic_ [vdst,] vaddr, vdata, saddr|off [offset:N] [glc]: a 32-bit atomic at the global_* address (RDNA2 ISA, FLAT/GLOBAL). With glc the pre-op value lands in vdst (the first operand); without it there is no vdst. cmpswap takes vdata as a pair {DATA, CMP}: M = (M == CMP) ? DATA : M. Inactive lanes don't touch memory and keep vdst; active unaligned lanes (addr % 4 != 0, or addr % 8 != 0 for _x2) leave memory untouched and write 0 / (0, 0) to vdst (measured natively on gfx1036). and/or/xor/swap_x2 work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword, with no Int64 atomics. That leaves the same memory for a bitwise op, whose bits are independent, but not always for an exchange: two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi). The returned pair is two reads, so another lane's 64-bit op on the same element between them could be seen half done. inc/dec wrap against DATA through a CAS loop (atomic_inc_dec_cas), fmin/fmax through global_atomic_float. The other _x2 forms (add/sub/min/max/inc/dec carry or compare across the dwords, cmpswap_x2 compares all 64 bits) stay Unsupported. fcmpswap compares as binary32 (float_cmpswap_loop).""" kind = op[len("global_atomic_"):] if kind in ("and_x2", "or_x2", "xor_x2", "swap_x2"): return self.global_atomic_x2(op, kind[:-3], a, mods) if kind in ("fmin", "fmax"): return self.global_atomic_float(op, kind, a, mods) is_inc_dec = kind in ("inc", "dec", "csub") fcmp = kind == "fcmpswap" # float compare: see float_cmpswap_loop known = kind in self.BUF_ATOMICS or is_inc_dec or fcmp if not known or any(m in mods for m in ("slc", "dlc", "lds")): raise Unsupported(op if not known else op + " form") rtn = "glc" in mods if len(a) != (4 if rtn else 3): raise Unsupported(op + " operands") vdst, vaddr, vdata, saddr = a if rtn else (None,) + tuple(a) if vdata["k"] != "vgpr" or vdata.get("n", 1) != (2 if kind in ("cmpswap", "fcmpswap") else 1) or \ (vdst is not None and (vdst["k"] != "vgpr" or vdst.get("n", 1) != 1)): raise Unsupported(op + " operands") full = self.global_address(op, vaddr, saddr, mods) val = self.load_reg("vgpr", vdata["r"]) cmp = self.load_reg("vgpr", vdata["r"] + 1) if kind in ("cmpswap", "fcmpswap") else None al = self.atomic_aligned(full, 4) cond = self.tmp() self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {al}") lbl_do, lbl_end, old = self.tmp() + "_do", self.tmp() + "_end", self.tmp() pre = self.current_label_placeholder() self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") ptr, p = self.tmp(), self.tmp() self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full, 'rmw')}") self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") if is_inc_dec: res, done_lbl = self.atomic_inc_dec_cas(p, val, kind, lbl_do) elif fcmp: res = self.float_cmpswap_loop(p, val, cmp, self.cu(1)) done_lbl = self.current_label_placeholder() # the loop's exit block else: res, done_lbl = self.tmp(), lbl_do if kind == "cmpswap": self.emit(f"{res} = OpAtomicCompareExchange %uint {p} {self.cu(1)} {self.cu(0)} {self.cu(0)} {val} {cmp}") else: self.emit(f"{res} = {self.BUF_ATOMICS[kind][0]} %uint {p} {self.cu(1)} {self.cu(0)} {val}") res = self.guard_zero(res) self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") self.emit(f"{old} = OpPhi %uint {res} {done_lbl} {self.cu(0)} {pre}") if vdst is not None: self.dst(vdst, old) def global_atomic_float(self, op, kind, a, mods): """global_atomic_{fmin,fmax} [vdst,] vaddr, vdata, saddr|off [offset:N] [glc]: 32-bit float min/max at the global_* address via a CAS loop (OpAtomicCompareExchange + GLSL.std.450 NMin/NMax, so no shader float atomic extension is needed). Inactive lanes don't touch memory and keep vdst; active unaligned lanes write 0.""" if any(m in mods for m in ("slc", "dlc", "lds")): raise Unsupported(op + " form") rtn = "glc" in mods if len(a) != (4 if rtn else 3): raise Unsupported(op + " operands") vdst, vaddr, vdata, saddr = a if rtn else (None,) + tuple(a) if vdata["k"] != "vgpr" or vdata.get("n", 1) != 1 or \ (vdst is not None and (vdst["k"] != "vgpr" or vdst.get("n", 1) != 1)): raise Unsupported(op + " operands") full = self.global_address(op, vaddr, saddr, mods) val_f = self.tof(self.load_reg("vgpr", vdata["r"])) al = self.atomic_aligned(full, 4) cond = self.tmp() self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {al}") old = self._emit_atomic_fminmax_cas(kind, full, val_f, cond) if vdst is not None: self.dst(vdst, old) def global_atomic_x2(self, op, kind, a, mods): """global_atomic_{and,or,xor,swap}_x2 (see global_atomic): one 32-bit atomic per dword of the element.""" if any(m in mods for m in ("slc", "dlc", "lds")): raise Unsupported(op + " form") rtn = "glc" in mods if len(a) != (4 if rtn else 3): raise Unsupported(op + " operands") vdst, vaddr, vdata, saddr = a if rtn else (None,) + tuple(a) if vdata["k"] != "vgpr" or vdata.get("n", 1) != 2 or \ (vdst is not None and (vdst["k"] != "vgpr" or vdst.get("n", 1) != 2)): raise Unsupported(op + " operands") full = self.global_address(op, vaddr, saddr, mods) vals = [self.load_reg("vgpr", vdata["r"] + w) for w in range(2)] spv = self.BUF_ATOMICS[kind][0] al = self.atomic_aligned(full, 8) cond = self.tmp() self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {al}") lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" pre = self.current_label_placeholder() self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") ptr = self.tmp() self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full, 'rmw', 8)}") res = [] for w in range(2): p, r = self.tmp(), self.tmp() self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(w)}") self.emit(f"{r} = {spv} %uint {p} {self.cu(1)} {self.cu(0)} {vals[w]}") res.append(r) res = [self.guard_zero(r) for r in res] self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") olds = [] for w in range(2): # both OpPhi first: they must open the merge block old = self.tmp() self.emit(f"{old} = OpPhi %uint {res[w]} {lbl_do} {self.cu(0)} {pre}") olds.append(old) if vdst is not None: for w in range(2): self.dst({"k": "vgpr", "r": vdst["r"] + w, "n": 1}, olds[w]) def float_cmpswap_loop(self, p, new, cmp, scope): """tmp = M; M = (tmp == CMP as binary32) ? NEW : tmp; returns tmp (RDNA2 ISA, *_FCMPSWAP / DS_CMPST_F32). A float compare (OpFOrdEqual: -0 == +0, a NaN never matches) is not what OpAtomicCompareExchange compares (the bits), so this is a loop: read M (an atomic load at `scope`, as atomic_inc_dec_cas), pick NEW or M by the float compare, swap that in if M still holds what was read, else retry. Exact under contention. p: a uint pointer (PhysicalStorageBuffer with device scope, or Workgroup).""" lbl_hdr, lbl_cont, lbl_exit = (self.tmp() + t for t in ("_hdr", "_cont", "_exit")) init = self.tmp() self.emit(f"{init} = OpAtomicLoad %uint {p} {scope} {self.cu(0)}") entry = self.current_label_placeholder() self.emit(f"OpBranch {lbl_hdr}") self.emit(f"{lbl_hdr} = OpLabel") cur, cf, kf, eq, st, got, done = (self.tmp() for _ in range(7)) self.emit(f"{cur} = OpPhi %uint {init} {entry} {got} {lbl_cont}") self.emit(f"{cf} = OpBitcast %float {cur}") self.emit(f"{kf} = OpBitcast %float {cmp}") self.emit(f"{eq} = OpFOrdEqual %bool {cf} {kf}") self.emit(f"{st} = OpSelect %uint {eq} {new} {cur}") self.emit(f"{got} = OpAtomicCompareExchange %uint {p} {scope} {self.cu(0)} {self.cu(0)} {st} {cur}") self.emit(f"{done} = OpIEqual %bool {got} {cur}") self.emit(f"OpLoopMerge {lbl_exit} {lbl_cont} None") self.emit(f"OpBranchConditional {done} {lbl_exit} {lbl_cont}") self.emit(f"{lbl_cont} = OpLabel") self.emit(f"OpBranch {lbl_hdr}") self.emit(f"{lbl_exit} = OpLabel") return cur def buffer_atomic(self, op, a, mods): """buffer_atomic_ vdata, vaddr, s[V#], soffset ...: 32-bit atomic at the element address (buffer device address). With 'glc' the pre-op value is returned in vdata. Inactive lanes don't touch memory and keep vdata; active OOB or unaligned (addr % 4 != 0) lanes leave memory untouched and write 0 with glc (measured on gfx1036).""" kind = op[len("buffer_atomic_"):] if kind in ("and_x2", "or_x2", "xor_x2", "swap_x2"): return self.buffer_atomic_x2(op, kind[:-3], a, mods) if kind in ("fmin", "fmax"): return self.buffer_atomic_float(op, kind, a, mods) is_inc_dec = kind in ("inc", "dec", "csub") fcmp = kind == "fcmpswap" # float compare: see float_cmpswap_loop if (kind not in self.BUF_ATOMICS and not is_inc_dec and not fcmp) or "x2" in kind: raise Unsupported(op) vd = a[0] if is_inc_dec and (vd["k"] != "vgpr" or vd.get("n", 1) != 1): raise Unsupported(op + " data") addr, _, in_b, _ = self.buffer_address(a, mods) val = self.load_reg("vgpr", vd["r"]) al = self.atomic_aligned(addr, 4) ok, cond = self.tmp(), self.tmp() self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {al}") self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {ok}") # Guard all atomics with a structured if so inactive, OOB or unaligned lanes never touch memory. lbl_do, lbl_end, old = self.tmp() + "_do", self.tmp() + "_end", self.tmp() pre_label = self.current_label_placeholder() self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") ptr, p = self.tmp(), self.tmp() self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr, 'rmw')}") self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") if is_inc_dec: res_do, done_lbl = self.atomic_inc_dec_cas(p, val, kind, lbl_do) elif fcmp: cmp = self.load_reg("vgpr", vd["r"] + 1) res_do = self.float_cmpswap_loop(p, val, cmp, self.cu(1)) done_lbl = self.current_label_placeholder() # the loop's exit block else: spv, _ = self.BUF_ATOMICS[kind] res_do, done_lbl = self.tmp(), lbl_do if kind == "cmpswap": cmp = self.load_reg("vgpr", vd["r"] + 1) self.emit(f"{res_do} = OpAtomicCompareExchange %uint {p} {self.cu(1)} {self.cu(0)} {self.cu(0)} {val} {cmp}") elif kind == "swap": self.emit(f"{res_do} = OpAtomicExchange %uint {p} {self.cu(1)} {self.cu(0)} {val}") else: self.emit(f"{res_do} = {spv} %uint {p} {self.cu(1)} {self.cu(0)} {val}") res_do = self.guard_zero(res_do) self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") self.emit(f"{old} = OpPhi %uint {res_do} {done_lbl} {self.cu(0)} {pre_label}") if "glc" in mods: self.dst({"k": "vgpr", "r": vd["r"], "n": 1}, old) def buffer_atomic_float(self, op, kind, a, mods): """buffer_atomic_{fmin,fmax} vdata, vaddr, s[V#], soffset ...: 32-bit float min/max at the MUBUF address via the shared OpAtomicCompareExchange + GLSL.std.450 NMin/NMax CAS loop (no float-atomic extension needed). Enforces V# bounds and 4-byte natural alignment; with glc returns the old word (0 when OOB/unaligned, preserved when inactive).""" if "lds" in mods: raise Unsupported(op + " form") vd = a[0] if vd["k"] != "vgpr" or vd.get("n", 1) != 1: raise Unsupported(op + " data") addr, _, in_b, _ = self.buffer_address(a, mods) val_f = self.tof(self.load_reg("vgpr", vd["r"])) al = self.atomic_aligned(addr, 4) ok, cond = self.tmp(), self.tmp() self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {al}") self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {ok}") old = self._emit_atomic_fminmax_cas(kind, addr, val_f, cond) if "glc" in mods: self.dst({"k": "vgpr", "r": vd["r"], "n": 1}, old) def buffer_atomic_x2(self, op, kind, a, mods): """buffer_atomic_{and,or,xor,swap}_x2 vdata[0:1], vaddr, s[V#], soffset: M = op(M, DATA) on the 64-bit element (two dwords, low first); with glc the old 64 bits are returned in vdata. Each dword is its own 32-bit atomic, so no Int64 atomics are needed. That leaves the same memory for a bitwise op, whose bits are independent, but an exchange can tear: two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi). The returned pair is two reads, so another lane's 64-bit op on the same element between them could be seen half done. Measured natively on RDNA2 (gfx1036, wave32 & wave64): the bounds check covers the whole 8-byte element all or nothing (fixed_fmt=62) and addresses with (addr & 7) != 0 are dropped (memory untouched, active glc returns (0, 0), inactive preserves vdata).""" vd = a[0] if vd["k"] != "vgpr" or vd.get("n", 1) != 2: raise Unsupported(op + " data") addr, _, in_b, _ = self.buffer_address(a, mods, elem="fmt", fixed_fmt=62) # step: as buffer_atomic vals = [self.load_reg("vgpr", vd["r"] + w) for w in range(2)] al = self.atomic_aligned(addr, 8) ok, cond = self.tmp(), self.tmp() self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {al}") self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {ok}") lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" pre = self.current_label_placeholder() self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") ptr = self.tmp() self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr, 'rmw', 8)}") res = [] for w in range(2): p, r = self.tmp(), self.tmp() self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(w)}") self.emit(f"{r} = {self.BUF_ATOMICS[kind][0]} %uint {p} {self.cu(1)} {self.cu(0)} {vals[w]}") res.append(r) res = [self.guard_zero(r) for r in res] self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") olds = [] for w in range(2): # both OpPhi first: they must open the merge block old = self.tmp() # an inactive, out-of-range or unaligned lane skips the atomic (active gets 0, inactive keeps vdata via dst) self.emit(f"{old} = OpPhi %uint {res[w]} {lbl_do} {self.cu(0)} {pre}") olds.append(old) if "glc" in mods: for w in range(2): self.dst({"k": "vgpr", "r": vd["r"] + w, "n": 1}, olds[w]) def current_label_placeholder(self): """Label of the block currently being emitted (needed for OpPhi). Blocks are opened by OpLabel lines; under --wave64-emulate only those of the current segment count (an earlier one runs in another round).""" for line in reversed(self.body[self.x_marks[-1][0] if self.x_marks else 0:]): s = line.strip() if s.endswith("= OpLabel"): return s.split(" = ")[0] return self.block_label def image_get_lod(self, a, mods): """image_get_lod vD, vaddr, T#, S#: (clamped lod, unclamped lod) like OpImageQueryLod (2D, 2D array, cube). For arrays the query takes only the 2D coordinate; the layer doesn't affect the LOD. A cube is the same 6-layer 2D-array view image_sample uses (cube_coords): the projected s and t are the texture coordinates, and the 8 * slice + face word takes no part in the LOD.""" dim = next((m for m in mods if m.startswith("dim:")), "dim:SQ_RSRC_IMG_2D") cube = dim == "dim:SQ_RSRC_IMG_CUBE" if dim not in ("dim:SQ_RSRC_IMG_2D", "dim:SQ_RSRC_IMG_2D_ARRAY", "dim:SQ_RSRC_IMG_CUBE") or self.stage != "ps": raise Unsupported("image_get_lod form") a16 = "a16" in mods if a16 and ("tfe" in mods or "lwe" in mods): raise Unsupported("image_get_lod form") if a16 and cube: raise Unsupported("image_get_lod a16 cube") # a16 packs the cube's three coordinates differently arr = dim.endswith("_ARRAY") or cube if arr: self.uses_tex_array = True dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x3") dmask = int(dm.split(":")[1], 0) vdata = a[0] if vdata["k"] != "vgpr": # `off`, an SGPR or a constant where the VGPR range of the result goes raise Unsupported("image_get_lod destination") addr = self.addr_regs(a[1]) img_idx, kind = self.desc_lookup_sgpr(a[2], 8) img_idx = self.desc_sampled_index(img_idx, kind, dim) smp_idx = self.desc_lookup_sgpr(a[3], 4)[0] ip, img, sp, smp, si = (self.tmp() for _ in range(5)) self.dynamic_sampled_access(ip, "%_ptr_UC_imga" if arr else "%_ptr_UC_img", "%images_arr" if arr else "%images", img_idx) self.emit(f"{img} = OpLoad {'%img2da' if arr else '%img2d'} {ip}") self.dynamic_sampled_access(sp, "%_ptr_UC_smp", "%samplers", smp_idx) self.emit(f"{smp} = OpLoad %smp {sp}") self.emit(f"{si} = OpSampledImage {'%simg2da' if arr else '%simg2d'} {img} {smp}") if a16: # U and V occupy the low and high halves of the first address VGPR. The array layer # is a separate address component and does not contribute to the LOD derivatives. packed = self.load_reg("vgpr", addr[0]) uv = self.tmp() self.emit(f"{uv} = OpExtInst %v2float %glsl UnpackHalf2x16 {packed}") elif cube: if len(addr) < 3: raise Unsupported("image_get_lod cube coords") # The hardware cube s and t are sc, tc / |cubema| + 1.5, i.e. the 2D-array view's u and v plus # one; the third word (8 * slice + face) takes no part in the LOD, so it is not read. f = [self.tof(self.load_reg("vgpr", r)) for r in addr[:2]] s, t = self.tmp(), self.tmp() self.emit(f"{s} = OpFSub %float {f[0]} %f1") self.emit(f"{t} = OpFSub %float {f[1]} %f1") uv = self.tmp() self.emit(f"{uv} = OpCompositeConstruct %v2float {s} {t}") else: f = [self.tof(self.load_reg("vgpr", r)) for r in addr[:2]] uv = self.tmp() self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}") lod = self.tmp() self.emit(f"{lod} = OpImageQueryLod %v2float {si} {uv}") self.uses_query = True out = 0 for c in range(2): if dmask >> c & 1: comp = self.tmp() self.emit(f"{comp} = OpCompositeExtract %float {lod} {c}") self.dst({"k": "vgpr", "r": vdata["r"] + out, "n": 1}, self.tou(comp)) out += 1 def fmt_table_get(self, ptr_type, table, index, elem="%uint"): """One element of a module-level table (a Private array indexed by a run-time value). The result type is a pointer to the element, as an OpAccessChain into an array needs.""" p = self.tmp() self.emit(f"{p} = OpAccessChain {ptr_type} {table} {index}") v = self.tmp() self.emit(f"{v} = OpLoad {elem} {p}") return v def fmt_norm_bits_dyn(self, m, n): """The f32 bits of m / (2^n - 1), correctly rounded, with n a run-time width (SHADER-849). The same code as norm_bits, but the 64-bit repeat constant of the width comes from a table and the width is a value: the quotient of a field by 2^n - 1 depends on nothing else.""" rep = self.fmt_table_get("%_ptr_Private_fmt_elem64", "%fmt_norm_rep_tab", n, "%ulong") m64, t, h64, hi, pi, p, s, s64, q64, q, s1, s164, r64, rb = (self.tmp() for _ in range(14)) self.emit(f"{m64} = OpUConvert %ulong {m}") self.emit(f"{t} = OpIMul %ulong {m64} {rep}") self.emit(f"{h64} = OpShiftRightLogical %ulong {t} {self.cu(32)}") self.emit(f"{hi} = OpUConvert %uint {h64}") self.emit(f"{pi} = OpExtInst %int %glsl FindUMsb {hi}") self.emit(f"{p} = OpBitcast %uint {pi}") self.emit(f"{s} = OpIAdd %uint {p} {self.cu(9)}") # m = 0 gives p = -1: s = 8, result unused self.emit(f"{s64} = OpUConvert %ulong {s}") self.emit(f"{q64} = OpShiftRightLogical %ulong {t} {s64}") self.emit(f"{q} = OpUConvert %uint {q64}") self.emit(f"{s1} = OpISub %uint {s} {self.cu(1)}") self.emit(f"{s164} = OpUConvert %ulong {s1}") self.emit(f"{r64} = OpShiftRightLogical %ulong {t} {s164}") self.emit(f"{rb} = OpUConvert %uint {r64}") e, eb, b0, b1, b2, b3 = (self.tmp() for _ in range(6)) self.emit(f"{e} = OpIAdd %uint {p} {self.cu(95)}") # biased exponent p - 32 + 127 self.emit(f"{eb} = OpShiftLeftLogical %uint {e} {self.cu(23)}") self.emit(f"{b0} = OpISub %uint {q} {self.cu(0x800000)}") # drop the hidden one self.emit(f"{b1} = OpIAdd %uint {eb} {b0}") self.emit(f"{b2} = OpBitwiseAnd %uint {rb} {self.cu(1)}") self.emit(f"{b3} = OpIAdd %uint {b1} {b2}") sh, one, m1, is_one, b4, z, res = (self.tmp() for _ in range(7)) self.emit(f"{sh} = OpBitwiseAnd %uint {n} {self.cu(31)}") self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {sh}") self.emit(f"{m1} = OpISub %uint {one} {self.cu(1)}") self.emit(f"{is_one} = OpIEqual %bool {m} {m1}") self.emit(f"{b4} = OpSelect %uint {is_one} {self.cu(0x3F800000)} {b3}") self.emit(f"{z} = OpIEqual %bool {m} {self.cu(0)}") self.emit(f"{res} = OpSelect %uint {z} {self.cu(0)} {b4}") return res def fmt_norm_function(self): """The shared %fmt_norm_bits(m, n): the exact quotient by 2^n - 1 for a run-time width.""" if self.fmt_norm_fn is None: saved, self.body = self.body, [] res = self.fmt_norm_bits_dyn("%fn_m", "%fn_n") lines, self.body = self.body, saved self.fmt_norm_fn = (["%fmt_norm_bits = OpFunction %uint None %fn_fmt_norm", "%fn_m = OpFunctionParameter %uint", "%fn_n = OpFunctionParameter %uint", "%fmt_norm_entry = OpLabel"] + lines + [f"OpReturnValue {res}", "OpFunctionEnd"]) return self.fmt_norm_fn def fmt_dec_component(self, params): """The value of output component k (the uint params[2], 0..3) of an element of the run-time FORMAT, branch-free (SHADER-849). The format's kind, channel count and channel widths come from one table word; the conversion the kind names is chosen with selects, so the decode has no branch and the module carries one copy of it, not one per format. A format with fewer channels repeats its own (component c = c mod n), as the RX 6700 does (SHADER-86).""" fmt, wvec = params[0], params[1] # The four dwords of the element, as a v4uint: the function type must not repeat another one in the module # (SPIR-V forbids two non-aggregate types with the same structure). words = [] for i in range(4): e = self.tmp() self.emit(f"{e} = OpCompositeExtract %uint {wvec} {i}") words.append(e) # The table word: kind | channel count << 4 | the four channel widths. desc = self.fmt_table_get("%_ptr_Private_fmt_elem", "%fmt_desc_tab", fmt) mode = self.tmp() self.emit(f"{mode} = OpBitwiseAnd %uint {desc} {self.cu(15)}") ncomp_raw, ncomp = self.tmp(), self.tmp() self.emit(f"{ncomp_raw} = OpShiftRightLogical %uint {desc} {self.cu(4)}") self.emit(f"{ncomp} = OpBitwiseAnd %uint {ncomp_raw} {self.cu(7)}") widths = [] for i in range(4): raw, w = self.tmp(), self.tmp() self.emit(f"{raw} = OpShiftRightLogical %uint {desc} {self.cu(7 + 6 * i)}") self.emit(f"{w} = OpBitwiseAnd %uint {raw} {self.cu(63)}") widths.append(w) # Select the source channel before extracting its width. With k in 0..3, formats with at least two # channels wrap at most once. A single-channel format repeats channel 0 for every selector. in_range, k, wraps, wrapped, reduced, multiple, channel = (self.tmp() for _ in range(7)) self.emit(f"{in_range} = OpULessThan %bool {params[2]} {self.cu(4)}") self.emit(f"{k} = OpSelect %uint {in_range} {params[2]} {self.cu(0)}") self.emit(f"{wraps} = OpUGreaterThanEqual %bool {k} {ncomp}") self.emit(f"{wrapped} = OpISub %uint {k} {ncomp}") self.emit(f"{reduced} = OpSelect %uint {wraps} {wrapped} {k}") self.emit(f"{multiple} = OpUGreaterThan %bool {ncomp} {self.cu(1)}") self.emit(f"{channel} = OpSelect %uint {multiple} {reduced} {self.cu(0)}") width_bits, start, wid = (self.tmp() for _ in range(3)) self.emit(f"{width_bits} = OpIMul %uint {channel} {self.cu(6)}") self.emit(f"{start} = OpIAdd %uint {width_bits} {self.cu(7)}") self.emit(f"{wid} = OpBitFieldUExtract %uint {desc} {start} {self.cu(6)}") off = self.cu(0) for i, width in enumerate(widths[:3]): earlier, include, total = (self.tmp() for _ in range(3)) self.emit(f"{earlier} = OpUGreaterThan %bool {channel} {self.cu(i)}") self.emit(f"{include} = OpSelect %uint {earlier} {width} {self.cu(0)}") self.emit(f"{total} = OpIAdd %uint {off} {include}") off = total # A code outside FORMATS has no channel: keep the width at 1, so the shifts below stay defined. is0, wid2 = self.tmp(), self.tmp() self.emit(f"{is0} = OpIEqual %bool {wid} {self.cu(0)}") self.emit(f"{wid2} = OpSelect %uint {is0} {self.cu(1)} {wid}") wid = wid2 # The dword the channel starts in, and the field itself. wi = self.tmp() self.emit(f"{wi} = OpShiftRightLogical %uint {off} {self.cu(5)}") word = words[0] for i in (1, 2, 3): eq, sel = self.tmp(), self.tmp() self.emit(f"{eq} = OpIEqual %bool {wi} {self.cu(i)}") self.emit(f"{sel} = OpSelect %uint {eq} {words[i]} {word}") word = sel shift = self.tmp() self.emit(f"{shift} = OpBitwiseAnd %uint {off} {self.cu(31)}") shifted = self.tmp() self.emit(f"{shifted} = OpShiftRightLogical %uint {word} {shift}") wsh, one, m1, is32, mask, raw = (self.tmp() for _ in range(6)) self.emit(f"{wsh} = OpBitwiseAnd %uint {wid} {self.cu(31)}") self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {wsh}") self.emit(f"{m1} = OpISub %uint {one} {self.cu(1)}") self.emit(f"{is32} = OpIEqual %bool {wid} {self.cu(32)}") self.emit(f"{mask} = OpSelect %uint {is32} {self.cu(0xFFFFFFFF)} {m1}") self.emit(f"{raw} = OpBitwiseAnd %uint {shifted} {mask}") # The field as a signed value, for the signed kinds. sw, lsh, si = self.tmp(), self.tmp(), self.tmp() self.emit(f"{sw} = OpISub %uint {self.cu(32)} {wid}") self.emit(f"{lsh} = OpShiftLeftLogical %uint {raw} {sw}") self.emit(f"{si} = OpShiftRightArithmetic %int {self.as_int(lsh)} {sw}") sv = self.int_bits(si) # The candidates of the kinds that convert the field to a float. fr, fs = self.tmp(), self.tmp() self.emit(f"{fr} = OpConvertUToF %float {raw}") self.emit(f"{fs} = OpConvertSToF %float {si}") c_fraw, c_fsv = self.tou(fr), self.tou(fs) # The exact quotient by 2^n - 1: UNORM divides the field by 2^w - 1, SNORM its magnitude by 2^(w-1) - 1. ab, au = self.tmp(), self.tmp() self.emit(f"{ab} = OpExtInst %int %glsl SAbs {si}") self.emit(f"{au} = OpBitcast %uint {ab}") is_snorm, num, w1, n, hi_n, zero_n, n2 = (self.tmp() for _ in range(7)) self.emit(f"{is_snorm} = OpIEqual %bool {mode} {self.cu(self.FMT_SNORM)}") self.emit(f"{num} = OpSelect %uint {is_snorm} {au} {raw}") self.emit(f"{w1} = OpISub %uint {wid} {self.cu(1)}") self.emit(f"{n} = OpSelect %uint {is_snorm} {w1} {wid}") self.emit(f"{hi_n} = OpUGreaterThan %bool {n} {self.cu(16)}") self.emit(f"{n2} = OpSelect %uint {hi_n} {self.cu(16)} {n}") self.emit(f"{zero_n} = OpIEqual %bool {n2} {self.cu(0)}") n3 = self.tmp() self.emit(f"{n3} = OpSelect %uint {zero_n} {self.cu(1)} {n2}") c_norm = self.tmp() self.emit(f"{c_norm} = OpFunctionCall %uint %fmt_norm_bits {num} {n3}") # SNORM: the magnitude's quotient with the sign, and the most negative code as -1.0. neg, sgn, signed_norm, lim, is_min, c_snorm = (self.tmp() for _ in range(6)) self.emit(f"{neg} = OpSLessThan %bool {si} {self.as_int(self.cu(0))}") self.emit(f"{sgn} = OpBitwiseOr %uint {c_norm} {self.cu(0x80000000)}") self.emit(f"{signed_norm} = OpSelect %uint {neg} {sgn} {c_norm}") self.emit(f"{lim} = OpShiftLeftLogical %uint {self.cu(1)} {w1}") self.emit(f"{is_min} = OpULessThan %bool {au} {lim}") self.emit(f"{c_snorm} = OpSelect %uint {is_min} {signed_norm} {self.cu(0xBF800000)}") # The two float kinds with their own layout. c_f16 = self.f16_widen_bits(raw) c_ufloat = self.ufloat_decode_bits(raw, wid) # The kind picks the value: a code outside FORMATS (FMT_NONE) matches none and gives 0. res = self.cu(0) for kind, value in ((self.FMT_UFLOAT, c_ufloat), (self.FMT_F16, c_f16), (self.FMT_SNORM, c_snorm), (self.FMT_UNORM, c_norm), (self.FMT_SSCALED, c_fsv), (self.FMT_USCALED, c_fraw), (self.FMT_SINT, sv), (self.FMT_RAW, raw)): eq, sel = self.tmp(), self.tmp() self.emit(f"{eq} = OpIEqual %bool {mode} {self.cu(kind)}") self.emit(f"{sel} = OpSelect %uint {eq} {value} {res}") res = sel return res def fmt_dec_functions(self): """The shared decode function %fmt_dec(fmt, words, k) (SHADER-849): output component k of the element.""" if self.fmt_fn is None: self.uses_fmt_tables = True # The tables are constants: register them here, while the constant section can still take them. for v in Gen.fmt_desc_table(): self.cu(v) for v in Gen.fmt_norm_reps(): self.cl(v) fns = list(self.fmt_norm_function()) saved, self.body = self.body, [] params = ["%fd_fmt", "%fd_words", "%fd_k"] res = self.fmt_dec_component(params) lines, self.body = self.body, saved fns += (["%fmt_dec = OpFunction %uint None %fn_fmt_dec", f"{params[0]} = OpFunctionParameter %uint", f"{params[1]} = OpFunctionParameter %v4uint_fmt", f"{params[2]} = OpFunctionParameter %uint", "%fmt_dec_entry = OpLabel"] + lines + [f"OpReturnValue {res}", "OpFunctionEnd"]) self.fmt_fn = fns return self.fmt_fn def format_decode_words(self, words): """The element's four dwords as the one v4uint the shared decode function takes.""" self.fmt_dec_functions() wvec = self.tmp() self.emit(f"{wvec} = OpCompositeConstruct %v4uint_fmt " + " ".join(words[:4])) return wvec def format_decode_call(self, fmt, wvec, k): """A uint id: component k (a uint id, 0..3) of the element decoded per the run-time FORMAT. One shared function per module (SHADER-849): the run-time format picks the conversion with selects, so the decode has no branch and the module carries one copy of it, not one copy per format. Before, the shared function held every format's decode and a binary search over the codes: 3,498 instructions and 306 branches in a module, 250 KB for a shader with one dynamic-format load. The component is a parameter, so a load decodes only the components its DST_SEL fields pick for the registers it writes: buffer_load_format_x makes one call, not four (one function per component, all four called at every load, until 2026-11-27).""" r = self.tmp() self.emit(f"{r} = OpFunctionCall %uint %fmt_dec {fmt} {wvec} {k}") return r def fmt_size_of(self, fmt): """Byte size of the 7-bit buffer FORMAT code `fmt` (a uint id), 0 for a code FORMATS does not decode: one load from %fmt_size_tab. Typed loads used to select it through a chain over all of FORMATS per load (about 150 instructions); ScreenProbes_ActivateProbes has 3,281 such loads and its module was 2.5 M ids.""" self.uses_fmt_size = True # The table's length and entries are constants: register them here, while the constant section can still # take them, not at assembly (an OpTypeArray naming a constant declared after it fails spirv-val). for v in {128, 0, *(f[0] for f in self.FORMATS.values())}: self.cu(v) ptr, size = self.tmp(), self.tmp() self.emit(f"{ptr} = OpAccessChain %_ptr_Private_uint %fmt_size_tab {fmt}") self.emit(f"{size} = OpLoad %uint {ptr}") return size def buffer_load_format(self, op, a, mods, fixed_fmt=None): """buffer_load_format_[x|xy|xyz|xyzw]: element at V#.base + offsets, decoded per the V# FORMAT field (word3 bits 12-18), then swizzled by DST_SEL_X/Y/Z/W (word3 bits 0-11: 0=0, 1=1, 4..7 = X..W). Formats outside FORMATS decode to 0. An element that starts mid-dword may spill into later dwords: need = ceil((byte_shift + size) / 4) loaded dwords, then the window is shifted so decode sees a packed stream starting at the element. The bounds check is on the whole element (buffer_address, elem="fmt").""" if fixed_fmt is not None: self.fixed_format_codes.add(fixed_fmt) else: self.dynamic_format = True if any(m in mods for m in ("lds", "tfe", "d16")): raise Unsupported(op + " form") d16 = "_d16_" in op d16_hi = "_d16_hi_" in op # buffer_load_format_d16_hi_x: the one result goes to the high half ncomp = len(op.rsplit("_", 1)[1]) vd = a[0] addr, d3, in_b, step = self.buffer_address(a, mods, elem="fmt", fixed_fmt=fixed_fmt) if fixed_fmt is not None: # An INVALID V# format denotes an unbound resource, even for an explicit MTBUF format. descriptor_format, bound, accessible = (self.tmp() for _ in range(3)) self.emit(f"{descriptor_format} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}") self.emit(f"{bound} = OpINotEqual %bool {descriptor_format} {self.cu(0)}") self.emit(f"{accessible} = OpLogicalAnd %bool {in_b} {bound}") in_b = accessible fmt = self.cu(fixed_fmt) # tbuffer: format from the instruction else: fmt = self.tmp() self.emit(f"{fmt} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}") # Byte address of the element, split into a dword-aligned address and a byte shift (for 1/2-byte formats). alo, bsh, al64, aligned, b3 = (self.tmp() for _ in range(5)) self.emit(f"{alo} = OpUConvert %uint {addr}") self.emit(f"{b3} = OpBitwiseAnd %uint {alo} {self.cu(3)}") self.emit(f"{bsh} = OpIMul %uint {b3} {self.cu(8)}") self.emit(f"{al64} = OpUConvert %ulong {b3}") self.emit(f"{aligned} = OpISub %ulong {addr} {al64}") # How many dwords the element occupies, including a mid-dword start: # need = ceil((byte_shift + size) / 4) = (b3 + size + 3) >> 2. A 16-byte # element that starts at byte 3 spans 5 dwords. Extra unused loads re-read # dword 0 so a load never walks an out-of-range index. # Formats with no decoder have zero data channels and need no memory access. if fixed_fmt is not None: if fixed_fmt in self.FORMATS: sum_, need = self.tmp(), self.tmp() self.emit(f"{sum_} = OpIAdd %uint {b3} {self.cu(self.FORMATS[fixed_fmt][0] + 3)}") self.emit(f"{need} = OpShiftRightLogical %uint {sum_} {self.cu(2)}") else: need = self.cu(1) else: size = self.fmt_size_of(fmt) known, readable, sum_, sum3, need = (self.tmp() for _ in range(5)) self.emit(f"{known} = OpINotEqual %bool {size} {self.cu(0)}") self.emit(f"{readable} = OpLogicalAnd %bool {in_b} {known}") in_b = readable self.emit(f"{sum_} = OpIAdd %uint {b3} {size}") self.emit(f"{sum3} = OpIAdd %uint {sum_} {self.cu(3)}") self.emit(f"{need} = OpShiftRightLogical %uint {sum3} {self.cu(2)}") # Two-byte typed loads at odd effective addresses read like out-of-bounds # loads, including the descriptor's constant channel selectors. if fixed_fmt is None or self.FORMATS.get(fixed_fmt, (0,))[0] == 2: low_bit, even = self.tmp(), self.tmp() self.emit(f"{low_bit} = OpBitwiseAnd %uint {alo} {self.cu(1)}") self.emit(f"{even} = OpIEqual %bool {low_bit} {self.cu(0)}") permitted = even if fixed_fmt is None: other_size, permitted = self.tmp(), self.tmp() self.emit(f"{other_size} = OpINotEqual %bool {size} {self.cu(2)}") self.emit(f"{permitted} = OpLogicalOr %bool {other_size} {even}") accessible = self.tmp() self.emit(f"{accessible} = OpLogicalAnd %bool {in_b} {permitted}") in_b = accessible cond = self.tmp() self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {in_b}") lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" pre_label = self.current_label_placeholder() self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") ptr, host = self.tmp(), self.host_addr(aligned, "load", lambda: self.guard_delta(need, step)) self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") load_mem = self._psb_load_op(mods) loaded = [] for i in range(5): ok, idx, v = self.tmp(), self.tmp(), self.tmp() self.emit(f"{ok} = OpULessThan %bool {self.cu(i)} {need}") self.emit(f"{idx} = OpSelect %uint {ok} {self.cu(i)} {self.cu(0)}") p = self.buf_dword_ptr(ptr, host, step, idx) self.emit(f"{v} = OpLoad %uint {p} {load_mem}") loaded.append(v) self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") words = [] for v_do in loaded: v = self.tmp() self.emit(f"{v} = OpPhi %uint {v_do} {lbl_do} {self.cu(0)} {pre_label}") words.append(v) # Shift the whole window so dword 0 starts at the element. (32 - bsh) & 31 # keeps the left shift below 32 when bsh is 0; that result is discarded. packed = [] for i in range(4): w0s, w1sh0, w1sh, w1s, nz, merged, bw = (self.tmp() for _ in range(7)) self.emit(f"{w0s} = OpShiftRightLogical %uint {words[i]} {bsh}") self.emit(f"{w1sh0} = OpISub %uint {self.cu(32)} {bsh}") self.emit(f"{w1sh} = OpBitwiseAnd %uint {w1sh0} {self.cu(31)}") self.emit(f"{w1s} = OpShiftLeftLogical %uint {words[i + 1]} {w1sh}") self.emit(f"{nz} = OpINotEqual %bool {bsh} {self.cu(0)}") self.emit(f"{merged} = OpBitwiseOr %uint {w0s} {w1s}") self.emit(f"{bw} = OpSelect %uint {nz} {merged} {words[i]}") packed.append(bw) words = packed if fixed_fmt is not None: # MTBUF takes both the format and its identity selectors from the instruction: # X000, XY00, XYZ0 or XYZW. The V# selectors apply only to MUBUF. comps = self.decode_format(words, fixed_fmt, fixed=True) widths = self.FORMATS[fixed_fmt][2] d3 = self.cu(sum((4 + c) << (3 * c) for c in range(len(widths)))) else: # Decoded per register below: only the components the written registers' DST_SEL fields pick. comps, wvec = None, self.format_decode_words(words) # DST_SEL swizzle: 0 -> 0, 1 -> 1.0 (float/norm/scaled) or integer 1 (UINT/SINT, INVALID or reserved; # SHADER-86, SHADER-429), 4..7 -> X..W. On an out-of-bounds MUBUF load `words` are 0 so `comps` decode to 0, # while DST_SEL=1 still produces 1.0f / 1 (MTBUF overrides `d3` above with 4..7 / 0, so OOB and INVALID stay 0). grp, bit, fmask = self.tmp(), self.tmp(), self.cu(0) self.emit(f"{grp} = OpShiftRightLogical %uint {fmt} {self.cu(5)}") self.emit(f"{bit} = OpBitwiseAnd %uint {fmt} {self.cu(31)}") for g_idx, mask_val in enumerate(_FLOAT_FMT_MASKS): eq, nxt = self.tmp(), self.tmp() self.emit(f"{eq} = OpIEqual %bool {grp} {self.cu(g_idx)}") self.emit(f"{nxt} = OpSelect %uint {eq} {self.cu(mask_val)} {fmask}") fmask = nxt fsh, fbit, is_int_fmt = self.tmp(), self.tmp(), self.tmp() self.emit(f"{fsh} = OpShiftRightLogical %uint {fmask} {bit}") self.emit(f"{fbit} = OpBitwiseAnd %uint {fsh} {self.cu(1)}") self.emit(f"{is_int_fmt} = OpIEqual %bool {fbit} {self.cu(0)}") is_signed = "%false" if d16: for code_v, (_, kind, _) in self.FORMATS.items(): if kind in ("i32", "sint"): e, signed = self.tmp(), self.tmp() self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}") self.emit(f"{signed} = OpLogicalOr %bool {is_signed} {e}") is_signed = signed dst1 = self.tmp() self.emit(f"{dst1} = OpSelect %uint {is_int_fmt} {self.cu(1)} {self.cu(0x3F800000)}") # In-bounds gate applies to components read from buffer memory, leaving DST_SEL=1 intact (SHADER-429). bounded_comps = [] for comp in comps or (): cb = self.tmp() self.emit(f"{cb} = OpSelect %uint {in_b} {comp} {self.cu(0)}") bounded_comps.append(cb) outs = [] for c in range(ncomp): sel = self.tmp() self.emit(f"{sel} = OpBitFieldUExtract %uint {d3} {self.cu(3 * c)} {self.cu(3)}") if comps is None: # Run-time format: DST_SEL 4..7 decodes component sel - 4 (one call), 1 is dst1, the rest 0. The # same value as selecting among the four decoded components: a sel below 4 wraps k past 3, and the # decode of such a k is discarded. k = self.tmp() self.emit(f"{k} = OpISub %uint {sel} {self.cu(4)}") dec = self.format_decode_call(fmt, wvec, k) cb, e1, s1, picked, r = (self.tmp() for _ in range(5)) self.emit(f"{cb} = OpSelect %uint {in_b} {dec} {self.cu(0)}") self.emit(f"{e1} = OpIEqual %bool {sel} {self.cu(1)}") self.emit(f"{s1} = OpSelect %uint {e1} {dst1} {self.cu(0)}") self.emit(f"{picked} = OpULessThan %bool {k} {self.cu(4)}") self.emit(f"{r} = OpSelect %uint {picked} {cb} {s1}") else: r = self.cu(0) for code_v, src in ((1, dst1), (4, bounded_comps[0]), (5, bounded_comps[1]), (6, bounded_comps[2]), (7, bounded_comps[3])): e, s = self.tmp(), self.tmp() self.emit(f"{e} = OpIEqual %bool {sel} {self.cu(code_v)}") self.emit(f"{s} = OpSelect %uint {e} {src} {r}") r = s if d16: outs.append(r) else: self.dst({"k": "vgpr", "r": vd["r"] + c, "n": 1}, r) if d16: # D16 packs two results per register, saturating integer formats according to signedness. def int_half(word): unsigned = self.saturate_int16(word, signed=False) signed = self.saturate_int16(word, signed=True) half = self.tmp() self.emit(f"{half} = OpSelect %uint {is_signed} {signed} {unsigned}") return half is_norm, is_f32 = "%false", "%false" for code_v, (_, kind, _) in self.FORMATS.items(): if kind in ("unorm", "snorm", "f32") 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)}") acc = is_f32 if kind == "f32" else is_norm self.emit(f"{o} = OpLogicalOr %bool {acc} {e}") if kind == "f32": is_f32 = o else: is_norm = o for i in range(0, len(outs), 2): dest = {"k": "vgpr", "r": vd["r"] + i // 2, "n": 1} lo = outs[i] il = int_half(lo) r = self.tmp() if i + 1 == len(outs): # For d16_x and d16_xyz the unaddressed high half keeps its previous bits; d16_hi_x writes # the high half and keeps the low one. fl = self.d16_norm_f16(lo, is_norm, is_f32) self.emit(f"{r} = OpSelect %uint {is_int_fmt} {il} {fl}") if d16_hi: ins = self.tmp() self.emit(f"{ins} = OpBitFieldInsert %uint {self.load_reg('vgpr', dest['r'])} {r} " f"{self.cu(16)} {self.cu(16)}") self.dst(dest, ins) else: self.write_lo16(dest, r) continue hi = outs[i + 1] ph = self.tmp() fh_s = self.tmp() self.emit(f"{fh_s} = OpShiftLeftLogical %uint {self.d16_norm_f16(hi, is_norm, is_f32)} {self.cu(16)}") self.emit(f"{ph} = OpBitwiseOr %uint {self.d16_norm_f16(lo, is_norm, is_f32)} {fh_s}") ih, pi = self.tmp(), self.tmp() high_half = int_half(hi) self.emit(f"{ih} = OpShiftLeftLogical %uint {high_half} {self.cu(16)}") self.emit(f"{pi} = OpBitwiseOr %uint {il} {ih}") self.emit(f"{r} = OpSelect %uint {is_int_fmt} {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, is_f32=None): """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 32-bit float format (``is_f32``) is narrowed toward zero instead, finite values past the range giving +-65504: measured natively on gfx1036 for 32_FLOAT, 32_32_FLOAT and 32_32_32_32_FLOAT, d16_x/xy/xyzw, wave32 and wave64 (SHADER-358).""" h = self.f16_bits(self.tof(bits)) if is_f32 is not None: hz, sel = self.tmp(), self.tmp() self.emit(f"{hz} = OpCopyObject %uint {self.mem_f16(self.tof(bits))}") self.emit(f"{sel} = OpSelect %uint {is_f32} {hz} {h}") h = sel 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.""" # The instruction offset is a 12-bit signed byte offset, and llvm-mc prints it signed (offset:-4 for the # field 0xffc; it rejects offset:0xffc and anything outside -2048..2047), which is the only spelling the # disassembler and build.py deliver. RX 6800 (gfx1030): pointer 0x1000, offset:-4 reads byte 0xffc. inst = [m.split(":", 1)[1] for m in mods if m.startswith("offset:")] if len(inst) > 1: raise Unsupported(f"{op} offset form") try: inst = int(inst[0], 0) if inst else 0 except ValueError: raise Unsupported(f"{op} offset:{inst[0]}") from None if 0x800 <= inst <= 0xFFF: inst -= 0x1000 # the raw 12-bit field from a tool that prints it unsigned: same offset if not -0x800 <= inst <= 0x7FF: raise Unsupported(f"{op} offset:{inst}") # not a 12-bit value: don't guess an address if (saddr["k"] == "sgpr" and saddr.get("n") == 2) or (saddr["k"] == "slist" and len(saddr["r"]) == 2): lo, hi = self.sgpr_words(saddr, 2) voff = self.load_reg("vgpr", vaddr["r"]) l64, h64, sh, base, v64, va = (self.tmp() for _ in range(6)) self.emit(f"{l64} = OpUConvert %ulong {lo}") self.emit(f"{h64} = OpUConvert %ulong {hi}") self.emit(f"{sh} = OpShiftLeftLogical %ulong {h64} %c64_32") self.emit(f"{base} = OpBitwiseOr %ulong {sh} {l64}") self.emit(f"{v64} = OpUConvert %ulong {voff}") self.emit(f"{va} = OpIAdd %ulong {base} {v64}") elif saddr["k"] == "special" and saddr["t"] == "off" and vaddr["k"] == "vgpr" and vaddr.get("n") == 2: lo, hi = self.load_reg("vgpr", vaddr["r"]), self.load_reg("vgpr", vaddr["r"] + 1) l64, h64, sh, va = (self.tmp() for _ in range(4)) self.emit(f"{l64} = OpUConvert %ulong {lo}") self.emit(f"{h64} = OpUConvert %ulong {hi}") self.emit(f"{sh} = OpShiftLeftLogical %ulong {h64} %c64_32") self.emit(f"{va} = OpBitwiseOr %ulong {sh} {l64}") else: raise Unsupported(op + " addressing") self.uses_psb = True off64, full = self.tmp(), self.tmp() ioff = self.tmp() self.emit(f"{ioff} = OpBitcast %uint {self.as_int(self.cu(inst & 0xFFFFFFFF))}") self.emit(f"{off64} = OpSConvert %long {self.as_int(ioff)}") o2 = self.tmp() self.emit(f"{o2} = OpBitcast %ulong {off64}") self.emit(f"{full} = OpIAdd %ulong {va} {o2}") self.uses_long = True return full GLOBAL_SUB = { # op: (bytes, store?, signed, VGPR half the data comes from / lands in, or None = whole register) "global_store_byte": (1, True, False, None), "global_store_byte_d16_hi": (1, True, False, 1), "global_store_short": (2, True, False, None), "global_store_short_d16_hi": (2, True, False, 1), "global_load_ubyte_d16": (1, False, False, 0), "global_load_ubyte_d16_hi": (1, False, False, 1), "global_load_sbyte_d16": (1, False, True, 0), "global_load_sbyte_d16_hi": (1, False, True, 1), "global_load_short_d16": (2, False, False, 0), "global_load_short_d16_hi": (2, False, False, 1)} def global_byte_ptr(self, va, kind="load"): """(pointer to the dword holding byte `va`, bit offset of that byte in it) for a ulong Xbox VA.""" lo, b3, b64, al, arr, p, sh = (self.tmp() for _ in range(7)) self.emit(f"{lo} = OpUConvert %uint {va}") self.emit(f"{b3} = OpBitwiseAnd %uint {lo} {self.cu(3)}") self.emit(f"{b64} = OpUConvert %ulong {b3}") self.emit(f"{al} = OpISub %ulong {va} {b64}") # MoltenVK 1.4.0 needs an addressable array element for the Metal atomic operations (as buffer stores). self.emit(f"{arr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al, kind)}") self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {arr} {self.cu(0)}") self.emit(f"{sh} = OpShiftLeftLogical %uint {b3} {self.cu(3)}") return p, sh def global_sub(self, op, a, mods): """8- and 16-bit global stores (global_store_byte/short[_d16_hi]) and the d16 loads (global_load_{u,s}byte_d16[_hi], global_load_short_d16[_hi]). The access is done one byte at a time, so a 16-bit one that crosses a dword boundary is exact too: a store merges each byte into its dword with atomic and / or (neighbouring bytes, maybe another lane's, are kept, as buffer stores do); a load reads each byte. A d16 load writes one 16-bit half of vdst (the u/sbyte forms zero/sign-extend the byte to 16 bits) and keeps the other; a _d16_hi store takes its data from the high half. Inactive lanes neither store nor load.""" if any(m in mods for m in ("lds", "tfe", "slc", "dlc")): raise Unsupported(op + " form") nbytes, store, signed, half = self.GLOBAL_SUB[op] data, vaddr, saddr = (a[1], a[0], a[2]) if store else (a[0], a[1], a[2]) if data["k"] != "vgpr" or data.get("n", 1) != 1: raise Unsupported(op + " data") full = self.global_address(op, vaddr, saddr, mods) act = self.active_b() lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" old = self.load_reg("vgpr", data["r"]) pre = self.current_label_placeholder() self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") if store and self._is_coherent_mem(mods): self.uses_vmm = True load_mem = None if store else self._psb_load_op(mods) value = None for k in range(nbytes): va = full if k: va = self.tmp() self.emit(f"{va} = OpIAdd %ulong {full} {self.cl(k)}") p, sh = self.global_byte_ptr(va, "store" if store else "load") if store: byte, mk, inv, vs, t1, t2 = (self.tmp() for _ in range(6)) self.emit(f"{byte} = OpBitFieldUExtract %uint {old} {self.cu(16 * (half or 0) + 8 * k)} {self.cu(8)}") self.emit(f"{mk} = OpShiftLeftLogical %uint {self.cu(0xFF)} {sh}") self.emit(f"{inv} = OpNot %uint {mk}") self.emit(f"{vs} = OpShiftLeftLogical %uint {byte} {sh}") self.emit(f"{t1} = OpAtomicAnd %uint {p} {self.cu(1)} {self.cu(0)} {inv}") self.emit(f"{t2} = OpAtomicOr %uint {p} {self.cu(1)} {self.cu(0)} {vs}") else: w, b = self.tmp(), self.tmp() self.emit(f"{w} = OpLoad %uint {p} {load_mem}") self.emit(f"{b} = OpBitFieldUExtract %uint {w} {sh} {self.cu(8)}") if value is None: value = b else: hi8, v2 = self.tmp(), self.tmp() self.emit(f"{hi8} = OpShiftLeftLogical %uint {b} {self.cu(8)}") self.emit(f"{v2} = OpBitwiseOr %uint {value} {hi8}") value = v2 if not store: if signed: sx = self.tmp() self.emit(f"{sx} = OpBitFieldSExtract %uint {value} {self.cu(0)} {self.cu(8 * nbytes)}") value = sx new = self.tmp() self.emit(f"{new} = OpBitFieldInsert %uint {old} {value} {self.cu(16 * half)} {self.cu(16)}") self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") if not store: ph = self.tmp() self.emit(f"{ph} = OpPhi %uint {new} {lbl_do} {old} {pre}") self.store_reg("vgpr", data["r"], ph) def global_mem(self, op, a, mods): """global_load_dword[xN] vD, vaddr, saddr|off offset:N / global_store_dword[xN] vaddr, vD, saddr|off. Address = (saddr: 64-bit SGPR pair + zero-extended 32-bit vaddr | off: 64-bit VGPR pair) + offset, an Xbox GPU VA translated through the heap base. Stores and loads only take effect in active lanes.""" load = op.startswith("global_load") if op.endswith("_addtid"): # global_load/store_dword_addtid address by the lane id and M0, not vaddr; until 2026-11-22 it crashed # here with IndexError (no vaddr operand) raise Unsupported(op) if any(m in mods for m in ("lds", "tfe", "d16")): raise Unsupported(op + " form") sub = {"global_load_ushort": (16, False), "global_load_sshort": (16, True), "global_load_ubyte": (8, False), "global_load_sbyte": (8, True)}.get(op) n = 1 if (op.endswith("dword") or sub) else int(op.rsplit("x", 1)[1]) data, vaddr, saddr = (a[0], a[1], a[2]) if load else (a[1], a[0], a[2]) full = self.global_address(op, vaddr, saddr, mods) act = self.active_b() lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" if load: load_mem = self._psb_load_op(mods) # Inactive lanes don't load (and keep their registers): guard the access, merge with OpPhi per dword. olds = [self.load_reg("vgpr", data["r"] + i) for i in range(n)] pre = self.current_label_placeholder() self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") vals = [] if sub: # 8/16-bit load: read the containing dword and extract (zero- or sign-extended); a 16-bit load at # byte offset 3 within a dword merges byte 0 of the next dword without over-reading non-crossing ones. bits, signed = sub lo32, b3, b64, al, ptr, p0, w, shb, v = (self.tmp() for _ in range(9)) self.emit(f"{lo32} = OpUConvert %uint {full}") self.emit(f"{b3} = OpBitwiseAnd %uint {lo32} {self.cu(3)}") self.emit(f"{b64} = OpUConvert %ulong {b3}") self.emit(f"{al} = OpISub %ulong {full} {b64}") self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr " f"{self.host_addr(al, 'load', lambda: self.guard_delta(self.sub_dwords(bits // 8, b3), None))}") self.emit(f"{p0} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") self.emit(f"{w} = OpLoad %uint {p0} {load_mem}") self.emit(f"{shb} = OpShiftLeftLogical %uint {b3} {self.cu(3)}") ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract" if bits == 8: self.emit(f"{v} = {ext} %uint {w} {shb} {self.cu(8)}") else: lo_part, cross, p1, w1, hi_byte, hi_sh, crossed, raw = (self.tmp() for _ in range(8)) lbl_cross, lbl_cend = self.tmp() + "_cross", self.tmp() + "_cend" self.emit(f"{lo_part} = OpShiftRightLogical %uint {w} {shb}") self.emit(f"{cross} = OpIEqual %bool {b3} {self.cu(3)}") self.emit(f"OpSelectionMerge {lbl_cend} None") self.emit(f"OpBranchConditional {cross} {lbl_cross} {lbl_cend}") self.emit(f"{lbl_cross} = OpLabel") self.emit(f"{p1} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(1)}") self.emit(f"{w1} = OpLoad %uint {p1} {load_mem}") self.emit(f"{hi_byte} = OpBitFieldUExtract %uint {w1} {self.cu(0)} {self.cu(8)}") self.emit(f"{hi_sh} = OpShiftLeftLogical %uint {hi_byte} {self.cu(8)}") self.emit(f"{crossed} = OpBitwiseOr %uint {lo_part} {hi_sh}") self.emit(f"OpBranch {lbl_cend}") self.emit(f"{lbl_cend} = OpLabel") self.emit(f"{raw} = OpPhi %uint {crossed} {lbl_cross} {lo_part} {lbl_do}") self.emit(f"{v} = {ext} %uint {raw} {self.cu(0)} {self.cu(16)}") vals.append(v) else: ptr = self.tmp() self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full, 'load', 4 * n)}") for i in range(n): p, v = self.tmp(), self.tmp() self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") self.emit(f"{v} = OpLoad %uint {p} {load_mem}") vals.append(v) done_lbl = self.current_label_placeholder() self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") phis = [] for i in range(n): # all OpPhi first: they must open the merge block ph = self.tmp() self.emit(f"{ph} = OpPhi %uint {vals[i]} {done_lbl} {olds[i]} {pre}") phis.append(ph) for i, ph in enumerate(phis): self.store_reg("vgpr", data["r"] + i, ph) else: store_mem = self._psb_store_op(mods) vals = [self.load_reg("vgpr", data["r"] + i) for i in range(n)] self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") ptr = self.tmp() self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full, 'store', 4 * n)}") for i in range(n): p = self.tmp() self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") self.emit(f"OpStore {p} {vals[i]} {store_mem}") self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") FLAT_GLOBAL_OPS = frozenset( ["global_load_dword", "global_load_dwordx2", "global_load_dwordx3", "global_load_dwordx4", "global_store_dword", "global_store_dwordx2", "global_store_dwordx3", "global_store_dwordx4", "global_load_ubyte", "global_load_sbyte", "global_load_ushort", "global_load_sshort"]) def flat_mem(self, op, a, mods): """flat_load_* vD, v[a:a+1] / flat_store_* v[a:a+1], vD: the FLAT forms of global_mem and global_sub. A FLAT address is a 64-bit VGPR pair with no SADDR. The RDNA2 ISA's flat-memory chapter sends an address inside the LDS or private (scratch) aperture to that memory and any other address to global memory, where it is the same access as GLOBAL with `off`. The aperture bases are per-queue values a program reads as src_shared_base and src_private_base; the translator does not accept those operands, so a program that builds an aperture address from them is refused as a whole, and the FLAT accesses that do translate are global ones. (An aperture address taken from memory or a constant would be read as global memory: not seen, and not detectable here.) The instruction offset must be 0. Its behaviour on the console's GPU is not measured, and LLVM marks GFX10.1 with FeatureFlatSegmentOffsetBug ("inst_offset is ignored when flat instructions access global memory") and then folds no offset into a FLAT access, so a non-zero one is refused rather than guessed.""" rest = op[len("flat_"):] gop = "global_" + rest if gop not in self.GLOBAL_SUB and gop not in self.FLAT_GLOBAL_OPS: raise Unsupported(op) offsets = [m.split(":", 1)[1] for m in mods if m.startswith("offset:")] try: nonzero = any(int(o, 0) != 0 for o in offsets) except ValueError: nonzero = True if nonzero: raise Unsupported(f"{op} instruction offset (FLAT, GFX10)") store = rest.startswith("store_") vaddr = a[0] if store else (a[1] if len(a) > 1 else None) if len(a) != 2 or vaddr["k"] != "vgpr" or vaddr.get("n") != 2: raise Unsupported(op + " addressing") args = [a[0], a[1], {"k": "special", "t": "off", "neg": False, "abs": False}] mods = [m for m in mods if not m.startswith("offset:")] if gop in self.GLOBAL_SUB: self.global_sub(gop, args, mods) else: self.global_mem(gop, args, mods) def buf_dword_ptr(self, arr, host, step, i, same_base=False): """Pointer to dword i (a Python int or a uint id) of a buffer access whose first dword is at host address `host`, `arr` the same address as a PSB array: arr[i] for the linear layout (step None), else host + i * step in scratch-swizzle mode (SWIZZLE_ENABLE=1, idxen=0, ADD_TID_ENABLE=1), where dword k is 4 * index_stride bytes after dword k - 1 (buffer_address). `same_base` indexes `arr` by i * index_stride instead of converting a second address to a pointer: on MoltenVK (Apple M4) a load through a second pointer converted from the same address as one through `arr` returned wrong values (#1864, @sovljanskii: buffer_load_ushort at byte 2 of a dword read 0).""" ix = self.cu(i) if isinstance(i, int) else i p = self.tmp() if step is None or i == 0: self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {arr} {ix}") return p if same_base: # step = 4 * index_stride: dword i is element i * index_stride of arr q, k = self.tmp(), self.tmp() self.emit(f"{q} = OpShiftRightLogical %uint {step} {self.cu(2)}") self.emit(f"{k} = OpIMul %uint {ix} {q}") self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {arr} {k}") return p o, o64, h = self.tmp(), self.tmp(), self.tmp() self.emit(f"{o} = OpIMul %uint {ix} {step}") self.emit(f"{o64} = OpUConvert %ulong {o}") self.emit(f"{h} = OpIAdd %ulong {host} {o64}") self.emit(f"{p} = OpConvertUToPtr %_ptr_PSB_uint {h}") return p def buffer_address(self, a, mods, parts=False, elem=None, fixed_fmt=None): """(64-bit element address id, V# word3 id, in_bounds bool id, ..., step) for a MUBUF/MTBUF instruction: vdata, vaddr, srsrc, soffset. With `idx` = idxen ? vindex : (ADD_TID_ENABLE ? lane : 0) (idxen ignores ADD_TID_ENABLE), `off` = uint32((offen ? vaddr : 0) + inst_offset) (32-bit wrap), `offs` = uint64(off) + uint64(soffset) (64-bit, no wrap), out of range on RDNA2 as measured natively on gfx1036 (docs/buffer_bounds.md, docs/design.md): 0 STRUCTURED_WITH_OFFSET: idx >= num_records or off + 4k + 4 > stride 1 STRUCTURED: idx >= num_records 2 DISABLED: num_records == 0 3 RAW (linear or stride 0): offs + 4k + 4 > num_records 3 SWIZZLED (swz_active and stride != 0): uint64(idx) + uint64(soffset) >= num_records or off + 4k + 4 > stride SWIZZLE_ENABLE (word1[31]) activates only when idxen or ADD_TID_ENABLE is active (`swz_active`); with neither, addressing is linear and mode 3 stays RAW. Two swizzle sub-modes exist on RDNA2 (measured natively on gfx1036, wave32 & wave64): - Scratch swizzle (`SWIZZLE_ENABLE=1, idxen=0, ADD_TID_ENABLE=1`): raw multi-dword accesses step by `4 * index_stride` bytes (`step`), and typed formats > 4 bytes (plus 8-byte `buffer_atomic_*_x2`) are suppressed (even in mode 2). - Indexed swizzle (`SWIZZLE_ENABLE=1, idxen=1`): multi-dword raw, typed, and `_x2` atomic accesses step linearly by `+4` bytes (`step = None`), and typed formats > 4 bytes execute normally. A literal V# word1/word3 (`sgpr_imm`) folds each bit; a run-time one selects dynamically. elem="fmt" checks the whole element's format size; parts=True adds a 4th element `k -> in-range bool id` for per-dword checks.""" vaddr, rsrc = a[1], a[2] soff = a[3] if len(a) > 3 else {"k": "imm", "v": 0} if (rsrc["k"] == "sgpr" and rsrc.get("n") == 4): lit3, lit1 = self.sgpr_imm.get(rsrc["r"] + 3), self.sgpr_imm.get(rsrc["r"] + 1) elif rsrc["k"] == "slist" and len(rsrc["r"]) == 4: lit3 = self.sgpr_imm.get(rsrc["r"][3]) if isinstance(rsrc["r"][3], int) else None lit1 = self.sgpr_imm.get(rsrc["r"][1]) if isinstance(rsrc["r"][1], int) else None else: raise Unsupported("buffer V#") d0, d1, d2, d3 = self.sgpr_words(rsrc, 4) hi, stride = self.tmp(), self.tmp() self.emit(f"{hi} = OpBitwiseAnd %uint {d1} {self.cu(0xFFFF)}") self.emit(f"{stride} = OpBitFieldUExtract %uint {d1} {self.cu(16)} {self.cu(14)}") # Swizzled buffers (docs/design.md, Swizzled buffer addressing; native gfx1036 measurement): SWIZZLE_ENABLE is # word1[31], INDEX_STRIDE word3[22:21] (IS = 8 << n), ADD_TID_ENABLE word3[23], element_size fixed at 4. # A literal word folds its bit (a Python bool); a run-time one is None. swz = bool(lit1 >> 31) if lit1 is not None else None tid = bool(lit3 >> 23 & 1) if lit3 is not None else None has_idx = "idxen" in mods inst = next((int(m.split(":")[1], 0) for m in mods if m.startswith("offset:")), 0) soff_zero = soff["k"] == "imm" and soff["v"] == 0 soff_v = self.src_u(soff) vregs = [] if vaddr["k"] == "special" else [vaddr["r"] + i for i in range(vaddr.get("n", 1))] voff = None if "offen" in mods: voff = self.load_reg("vgpr", vregs[1] if has_idx else vregs[0]) # Effective index: idxen uses vindex alone and ignores ADD_TID_ENABLE; without idxen, ADD_TID_ENABLE supplies # the wave lane (thread_id[5:0]). tid_b = None if has_idx: idx = self.load_reg("vgpr", vregs[0]) elif tid is False: idx = None else: lane = self.wave_lane() if tid is None: # lane * run-time ADD_TID_ENABLE tid_b, idx = self.tmp(), self.tmp() self.emit(f"{tid_b} = OpBitFieldUExtract %uint {d3} {self.cu(23)} {self.cu(1)}") self.emit(f"{idx} = OpIMul %uint {lane} {tid_b}") else: idx = lane # SWIZZLE_ENABLE activates only with idxen or ADD_TID_ENABLE; scratch-swizzle stepping/suppression applies only # when SWIZZLE_ENABLE=1, idxen=0, ADD_TID_ENABLE=1. swz_u = None if has_idx: swz_active = swz scratch_swz = False if swz_active is None: swz_u = self.tmp() self.emit(f"{swz_u} = OpBitFieldUExtract %uint {d1} {self.cu(31)} {self.cu(1)}") elif swz is False or tid is False: swz_active = False scratch_swz = False elif swz is True and tid is True: swz_active = True scratch_swz = True else: swz_active = None scratch_swz = None if swz is True: swz_u = tid_b else: swz_b = self.tmp() self.emit(f"{swz_b} = OpBitFieldUExtract %uint {d1} {self.cu(31)} {self.cu(1)}") if tid is True: swz_u = swz_b else: swz_u = self.tmp() self.emit(f"{swz_u} = OpBitwiseAnd %uint {swz_b} {tid_b}") # off = uint32((offen ? voff : 0) + inst_offset): wraps at 32 bits on RDNA2. if voff is not None: if inst: off = self.tmp() self.emit(f"{off} = OpIAdd %uint {voff} {self.cu(inst)}") else: off = voff else: off = self.cu(inst) # step: bytes between consecutive dwords of a raw access, None for linear +4 (including all idxen=1 and fmt). step = None if swz_active is False: if soff_zero: total = off else: total = self.tmp() self.emit(f"{total} = OpIAdd %uint {soff_v} {off}") if idx is not None: m, t = self.tmp(), self.tmp() self.emit(f"{m} = OpIMul %uint {idx} {stride}") self.emit(f"{t} = OpIAdd %uint {total} {m}") total = t sw3 = False else: # buffer_offset = (index / IS * stride + (off & ~3)) * IS + (index % IS) * 4 + (off & 3), IS = 2^L; # L = 0 (run-time V# with swz_u == 0) reduces to the linear address index * stride + off. if lit3 is not None: Li = 3 + (lit3 >> 21 & 3) L = self.cu(Li) else: f, L, Li = self.tmp(), self.tmp(), None self.emit(f"{f} = OpBitFieldUExtract %uint {d3} {self.cu(21)} {self.cu(2)}") self.emit(f"{L} = OpIAdd %uint {f} {self.cu(3)}") if swz_active is None: # L * swz_u: 0 when not swizzled t = self.tmp() self.emit(f"{t} = OpIMul %uint {L} {swz_u}") L, Li = t, None om4, ol, sh = self.tmp(), self.tmp(), self.tmp() self.emit(f"{om4} = OpBitwiseAnd %uint {off} {self.cu(0xFFFFFFFC)}") self.emit(f"{ol} = OpBitwiseAnd %uint {off} {self.cu(3)}") msb, ms, inner, lsb, l4, im = (self.tmp() for _ in range(6)) self.emit(f"{msb} = OpShiftRightLogical %uint {idx} {L}") self.emit(f"{ms} = OpIMul %uint {msb} {stride}") self.emit(f"{inner} = OpIAdd %uint {ms} {om4}") self.emit(f"{sh} = OpShiftLeftLogical %uint {inner} {L}") if Li is not None: self.emit(f"{lsb} = OpBitwiseAnd %uint {idx} {self.cu((1 << Li) - 1)}") else: # index - (index >> L << L) hi_part = self.tmp() self.emit(f"{hi_part} = OpShiftLeftLogical %uint {msb} {L}") self.emit(f"{lsb} = OpISub %uint {idx} {hi_part}") self.emit(f"{l4} = OpShiftLeftLogical %uint {lsb} {self.cu(2)}") self.emit(f"{im} = OpIAdd %uint {sh} {l4}") b_off = self.tmp() self.emit(f"{b_off} = OpIAdd %uint {im} {ol}") if soff_zero: total = b_off else: total = self.tmp() self.emit(f"{total} = OpIAdd %uint {soff_v} {b_off}") if elem != "fmt" and scratch_swz is not False: if Li is not None: step = self.cu(4 << Li) else: step = self.tmp() self.emit(f"{step} = OpShiftLeftLogical %uint {self.cu(4)} {L}") # OOB_SELECT 3 with active swizzle and stride != 0 checks (idx + soffset) >= num_records or off + payload > stride. if lit1 is not None and (lit1 >> 16 & 0x3FFF) == 0: sw3 = False elif swz_active is True: if lit1 is not None: sw3 = True else: sw3 = self.tmp() self.emit(f"{sw3} = OpINotEqual %bool {stride} {self.cu(0)}") else: # L * stride != 0: swz_u == 1 (L >= 3) and stride != 0 (no overflow) ls, sw3 = self.tmp(), self.tmp() self.emit(f"{ls} = OpIMul %uint {L} {stride}") self.emit(f"{sw3} = OpINotEqual %bool {ls} {self.cu(0)}") mode = None if lit3 is None else lit3 >> 28 & 3 # The hardware adds the offset to the 48-bit base without wrapping at 32 bits: index * stride is a full # product and soffset is added in 64 bits. An index of 0xFFFFFFFF with a 20-byte stride therefore lands tens # of GiB past the base, outside every buffer, and the access has no effect. `total` is that offset modulo # 2^32, which would put the same access 20 bytes below the base: inside a view that covers a whole pool, where # OOB_SELECT 3 does not look at the index and 2 looks at nothing. So an offset that does not fit 32 bits is out # of range in every mode (a load reads 0, a store or atomic is dropped). `fits` is None where the mode's own # check already bounds the index and no soffset is added. The rule and its hardware observation are # five-star-recomp's (ThatRecompDev, GPL-3, commit b9b57e2). fits = None def u64(v): t = self.tmp() self.emit(f"{t} = OpUConvert %ulong {v}") return t def add64(x, y): t = self.tmp() self.emit(f"{t} = OpIAdd %ulong {x} {y}") return t if (idx is not None or not soff_zero) and not (mode in (0, 1) and soff_zero and swz_active is False): if swz_active is False: wide = u64(off) else: # the swizzled offset above, with the same terms in 64 bits inner64, sh64 = self.tmp(), self.tmp() self.emit(f"{inner64} = OpIMul %ulong {u64(msb)} {u64(stride)}") inner64 = add64(inner64, u64(om4)) self.emit(f"{sh64} = OpShiftLeftLogical %ulong {inner64} {L}") wide = add64(add64(sh64, u64(l4)), u64(ol)) if not soff_zero: wide = add64(wide, u64(soff_v)) if idx is not None and swz_active is False: prod = self.tmp() self.emit(f"{prod} = OpIMul %ulong {u64(idx)} {u64(stride)}") wide = add64(wide, prod) # Test the high 32 bits instead of `OpULessThanEqual %bool wide 0xFFFFFFFF` (or # `OpULessThan wide 0x100000000`): NVIDIA 580.82.07 NVVM aborts pipeline creation # (`NVVM compilation failed: 3`, VkResult -13) on that compare when a literal V# folds # `wide` to `0 + idx * stride`. hi_w, fits = self.tmp(), self.tmp() self.emit(f"{hi_w} = OpShiftRightLogical %ulong {wide} %c64_32") self.emit(f"{fits} = OpIEqual %bool {hi_w} {self.cl(0)}") self.uses_long = True # SQ_RSRC_BUF.TYPE is word3[31:30] and must be 0 (uint32(word3) < 0x40000000); non-zero types # (T# image descriptors, S# samplers, etc.) are not valid buffers and are treated as OOB. buf_type_oob = lit3 is not None and (lit3 & 0xFFFFFFFF) >= 0x40000000 if lit3 is None: is_buf = self.tmp() self.emit(f"{is_buf} = OpULessThan %bool {d3} {self.cu(0x40000000)}") if fits is None: fits = is_buf else: ok_fits = self.tmp() self.emit(f"{ok_fits} = OpLogicalAnd %bool {fits} {is_buf}") fits = ok_fits self.uses_psb = True l64, h64, sh, base, o64, addr = (self.tmp() for _ in range(6)) self.emit(f"{l64} = OpUConvert %ulong {d0}") self.emit(f"{h64} = OpUConvert %ulong {hi}") self.emit(f"{sh} = OpShiftLeftLogical %ulong {h64} %c64_32") self.emit(f"{base} = OpBitwiseOr %ulong {sh} {l64}") self.emit(f"{o64} = OpUConvert %ulong {total}") self.emit(f"{addr} = OpIAdd %ulong {base} {o64}") mode0_rule = mode in (None, 0) or (mode == 3 and sw3 is not False) need_raw = mode in (None, 3) and sw3 is not True need_p3 = mode in (None, 3) and sw3 is not False need_p1 = mode in (None, 0, 1) or (need_p3 and soff_zero) p1 = p2 = p3_idx = None if need_p1: p1 = self.tmp() if idx is None: self.emit(f"{p1} = OpINotEqual %bool {d2} {self.cu(0)}") else: self.emit(f"{p1} = OpULessThan %bool {idx} {d2}") if mode in (None, 2): p2 = self.tmp() self.emit(f"{p2} = OpINotEqual %bool {d2} {self.cu(0)}") off64 = d2_64 = soff64 = None if mode0_rule or need_raw: off64 = self.tmp() self.emit(f"{off64} = OpUConvert %ulong {off}") if need_raw or (need_p3 and not soff_zero and idx is not None): d2_64 = self.tmp() self.emit(f"{d2_64} = OpUConvert %ulong {d2}") if not soff_zero and (need_raw or (need_p3 and idx is not None)): soff64 = self.tmp() self.emit(f"{soff64} = OpUConvert %ulong {soff_v}") if need_p3: if soff_zero: p3_idx = p1 elif idx is None: p3_idx = self.tmp() self.emit(f"{p3_idx} = OpULessThan %bool {soff_v} {d2}") else: idx64, idx_s, p3_idx = self.tmp(), self.tmp(), self.tmp() self.emit(f"{idx64} = OpUConvert %ulong {idx}") self.emit(f"{idx_s} = OpIAdd %ulong {idx64} {soff64}") self.emit(f"{p3_idx} = OpULessThan %bool {idx_s} {d2_64}") lim = {} if mode0_rule: st64 = self.tmp() self.emit(f"{st64} = OpUConvert %ulong {stride}") lim[0] = (off64, st64) if need_raw: if soff_zero: offs64 = off64 else: offs64 = self.tmp() self.emit(f"{offs64} = OpIAdd %ulong {off64} {soff64}") lim[3] = (offs64, d2_64) sel = None if mode is None: md, m1, m2, m3 = (self.tmp() for _ in range(4)) self.emit(f"{md} = OpBitFieldUExtract %uint {d3} {self.cu(28)} {self.cu(2)}") self.emit(f"{m1} = OpIEqual %bool {md} {self.cu(1)}") self.emit(f"{m2} = OpIEqual %bool {md} {self.cu(2)}") self.emit(f"{m3} = OpIEqual %bool {md} {self.cu(3)}") sel = (m1, m2, m3) ends = {} # (offset id, end) -> the ulong sum: modes 0 and 3 share it when soffset is 0 def end_ok(which, end_bytes): """The access ends inside its limit: offset + end <= stride (mode 0) or <= num_records (mode 3); end_bytes is a Python int or the id of a ulong.""" x, limit = lim[which] end = ends.get((x, end_bytes)) if end is None: end = ends[(x, end_bytes)] = self.tmp() self.emit(f"{end} = OpIAdd %ulong {x} {self.cl(end_bytes) if isinstance(end_bytes, int) else end_bytes}") ok = self.tmp() self.emit(f"{ok} = OpULessThanEqual %bool {end} {limit}") return ok def raw_or_swizzled(e3_sw, end_bytes): """mode 3: the raw end check, or the swizzled-with-stride check (sw3).""" if sw3 is True: return e3_sw raw = end_ok(3, end_bytes) if sw3 is False: return raw r = self.tmp() self.emit(f"{r} = OpSelect %bool {sw3} {e3_sw} {raw}") return r def check_end(end_bytes): """in-range bool of an access that ends end_bytes after its first byte: the mode's rule, an offset that fits 32 bits, and SQ_RSRC_BUF.TYPE == 0 (word3[31:30] == 0).""" if buf_type_oob: return "%false" ok = mode_check_end(end_bytes) if fits is None: return ok both = self.tmp() self.emit(f"{both} = OpLogicalAnd %bool {ok} {fits}") return both def mode_check_end(end_bytes): if mode == 1: return p1 if mode == 2: return p2 if mode == 3 and sw3 is False: return end_ok(3, end_bytes) off_ok = end_ok(0, end_bytes) if mode == 0: e0 = self.tmp() self.emit(f"{e0} = OpLogicalAnd %bool {p1} {off_ok}") return e0 if mode == 3: e3_sw = self.tmp() self.emit(f"{e3_sw} = OpLogicalAnd %bool {p3_idx} {off_ok}") return raw_or_swizzled(e3_sw, end_bytes) e0 = self.tmp() self.emit(f"{e0} = OpLogicalAnd %bool {p1} {off_ok}") if sw3 is False: e3 = end_ok(3, end_bytes) else: if p3_idx == p1: e3_sw = e0 else: e3_sw = self.tmp() self.emit(f"{e3_sw} = OpLogicalAnd %bool {p3_idx} {off_ok}") e3 = raw_or_swizzled(e3_sw, end_bytes) s12, s3, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{s12} = OpSelect %bool {sel[0]} {p1} {e0}") self.emit(f"{s3} = OpSelect %bool {sel[1]} {p2} {s12}") self.emit(f"{r} = OpSelect %bool {sel[2]} {e3} {s3}") return r def check(k): """in-range bool of dword k of the access (k = 0: the first dword).""" return check_end(4 * k + 4) if isinstance(elem, int): in_b = check_end(elem) return addr, d3, in_b, step if elem == "fmt": # a typed element is all or nothing and ends at its size (measured, gfx1150: 32_32_32_32 at off 20 of 32 # reads 0 entirely): the size of the V#'s (or the instruction's) format code = fixed_fmt if fixed_fmt is not None else (lit3 >> 12 & 0x7F if lit3 is not None else None) if code is not None: size = self.FORMATS.get(code, (4,))[0] else: fc = self.tmp() self.emit(f"{fc} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}") tab, unknown, sz = self.fmt_size_of(fc), self.tmp(), self.tmp() # 4 for a code FORMATS lacks self.emit(f"{unknown} = OpIEqual %bool {tab} {self.cu(0)}") self.emit(f"{sz} = OpSelect %uint {unknown} {self.cu(4)} {tab}") size = self.tmp() self.emit(f"{size} = OpUConvert %ulong {sz}") in_b = check_end(size) if scratch_swz is not False: # Native gfx1036 measurement (wave32 & wave64): in scratch-swizzle mode (SWIZZLE_ENABLE=1, idxen=0, # ADD_TID_ENABLE=1), typed formats > 4 bytes and 8-byte buffer_atomic_*_x2 are suppressed even in # OOB_SELECT 2 (DISABLED). if isinstance(size, int): if size > 4: if scratch_swz is True: in_b = "%false" else: ns, ok = self.tmp(), self.tmp() self.emit(f"{ns} = OpIEqual %bool {swz_u} {self.cu(0)}") self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {ns}") in_b = ok else: le4 = self.tmp() self.emit(f"{le4} = OpULessThanEqual %bool {size} {self.cl(4)}") if scratch_swz is True: ok = self.tmp() self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {le4}") in_b = ok else: ns, allow, ok = self.tmp(), self.tmp(), self.tmp() self.emit(f"{ns} = OpIEqual %bool {swz_u} {self.cu(0)}") self.emit(f"{allow} = OpLogicalOr %bool {ns} {le4}") self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {allow}") in_b = ok return addr, d3, in_b, None in_b = check(0) if parts: # modes 0 and 3 end-check every dword on its own; 1 and 2 (a literal V#) share the first-byte check. # Dword 0's check is in_b itself: computed here, before any of the caller's branches, so it dominates # every use (the loads and stores used to compute it a second time). def part(k): return in_b if k == 0 else check(k) return addr, d3, in_b, (part if not buf_type_oob and mode in (None, 0, 3) else None), step return addr, d3, in_b, step def _fmt_enc_chan_body(self, mode, val, w, is_signed): """Encode one channel of a dynamic-format buffer store (branch-free, shared across all 77 FORMATS).""" # Clamp width 0 (unused channel) to 1 so shifts and (w - 1) stay well-defined. w_is0, w_nz, w_lo, wm1, wm1_lo = (self.tmp() for _ in range(5)) self.emit(f"{w_is0} = OpIEqual %bool {w} {self.cu(0)}") self.emit(f"{w_nz} = OpSelect %uint {w_is0} {self.cu(1)} {w}") self.emit(f"{w_lo} = OpBitwiseAnd %uint {w_nz} {self.cu(31)}") self.emit(f"{wm1} = OpISub %uint {w_nz} {self.cu(1)}") self.emit(f"{wm1_lo} = OpBitwiseAnd %uint {wm1} {self.cu(31)}") # Narrow UINT: saturate to (1 << w) - 1. u_one, u_max, c_uint = (self.tmp() for _ in range(3)) self.emit(f"{u_one} = OpShiftLeftLogical %uint {self.cu(1)} {w_lo}") self.emit(f"{u_max} = OpISub %uint {u_one} {self.cu(1)}") self.emit(f"{c_uint} = OpExtInst %uint %glsl UMin {val} {u_max}") # Narrow SINT: clamp signed 32-bit int to [-2^(w-1), 2^(w-1) - 1]. s_half, s_hi_u, s_lo_u, s_clamped, c_sint = (self.tmp() for _ in range(5)) self.emit(f"{s_half} = OpShiftLeftLogical %uint {self.cu(1)} {wm1_lo}") self.emit(f"{s_hi_u} = OpISub %uint {s_half} {self.cu(1)}") self.emit(f"{s_lo_u} = OpISub %uint {self.cu(0)} {s_half}") self.emit(f"{s_clamped} = OpExtInst %int %glsl SClamp {self.as_int(val)} " f"{self.as_int(s_lo_u)} {self.as_int(s_hi_u)}") self.emit(f"{c_sint} = OpBitcast %uint {s_clamped}") # Exact single-rounded UNORM/SNORM (same 64-bit arithmetic as encode_norm_bits, with run-time scale). nw, n_one, scale, scale64 = (self.tmp() for _ in range(4)) self.emit(f"{nw} = OpSelect %uint {is_signed} {wm1_lo} {w_lo}") self.emit(f"{n_one} = OpShiftLeftLogical %uint {self.cu(1)} {nw}") self.emit(f"{scale} = OpISub %uint {n_one} {self.cu(1)}") self.emit(f"{scale64} = OpUConvert %ulong {scale}") sign, neg, a = self.tmp(), self.tmp(), self.tmp() self.emit(f"{sign} = OpShiftRightLogical %uint {val} {self.cu(31)}") self.emit(f"{neg} = OpINotEqual %bool {sign} {self.cu(0)}") self.emit(f"{a} = OpBitwiseAnd %uint {val} {self.cu(0x7FFFFFFF)}") small, ge1, exp_, ec, ec2, shift, sh64, sh1, sh1_64 = (self.tmp() for _ in range(9)) self.emit(f"{small} = OpULessThan %bool {a} {self.cu(0x37000000)}") self.emit(f"{ge1} = OpUGreaterThanEqual %bool {a} {self.cu(0x3F800000)}") self.emit(f"{exp_} = OpShiftRightLogical %uint {a} {self.cu(23)}") self.emit(f"{ec} = OpExtInst %uint %glsl UMax {exp_} {self.cu(110)}") self.emit(f"{ec2} = OpExtInst %uint %glsl UMin {ec} {self.cu(126)}") self.emit(f"{shift} = OpISub %uint {self.cu(150)} {ec2}") self.emit(f"{sh64} = OpUConvert %ulong {shift}") self.emit(f"{sh1} = OpISub %uint {shift} {self.cu(1)}") self.emit(f"{sh1_64} = OpUConvert %ulong {sh1}") mant, m, m64, p, half, ps, q64, q, mag1, mag, nmag, neg_val, c_norm = (self.tmp() for _ in range(13)) self.emit(f"{mant} = OpBitwiseAnd %uint {a} {self.cu(0x7FFFFF)}") self.emit(f"{m} = OpBitwiseOr %uint {mant} {self.cu(0x800000)}") self.emit(f"{m64} = OpUConvert %ulong {m}") self.emit(f"{p} = OpIMul %ulong {m64} {scale64}") self.emit(f"{half} = OpShiftLeftLogical %ulong {self.cl(1)} {sh1_64}") self.emit(f"{ps} = OpIAdd %ulong {p} {half}") self.emit(f"{q64} = OpShiftRightLogical %ulong {ps} {sh64}") self.emit(f"{q} = OpUConvert %uint {q64}") self.emit(f"{mag1} = OpSelect %uint {small} {self.cu(0)} {q}") self.emit(f"{mag} = OpSelect %uint {ge1} {scale} {mag1}") self.emit(f"{nmag} = OpISub %uint {self.cu(0)} {mag}") self.emit(f"{neg_val} = OpSelect %uint {is_signed} {nmag} {self.cu(0)}") self.emit(f"{c_norm} = OpSelect %uint {neg} {neg_val} {mag}") # F16: round toward zero with finite overflow clamping to +-65504. c_f16 = self.mem_f16(self.tof(val)) # UFLOAT (10- or 11-bit unsigned float, mb = 5 or 6): same integer ops as ufloat_encode_bits. is11, sh_base, sh_m, mmask, max_fin, inf_b = (self.tmp() for _ in range(6)) self.emit(f"{is11} = OpIEqual %bool {w_nz} {self.cu(11)}") self.emit(f"{sh_base} = OpSelect %uint {is11} {self.cu(130)} {self.cu(131)}") self.emit(f"{sh_m} = OpSelect %uint {is11} {self.cu(17)} {self.cu(18)}") self.emit(f"{mmask} = OpSelect %uint {is11} {self.cu(0x3F)} {self.cu(0x1F)}") self.emit(f"{max_fin} = OpSelect %uint {is11} {self.cu((30 << 6) | 0x3F)} {self.cu((30 << 5) | 0x1F)}") self.emit(f"{inf_b} = OpSelect %uint {is11} {self.cu(31 << 6)} {self.cu(31 << 5)}") (sh0, shc, dn, nr0, nr, nm, nm1, nz, nmant, nanb, isnan, isinf, big, norm, r0, r1, r2, snan, ng, r3, c_ufloat) = (self.tmp() for _ in range(21)) self.emit(f"{sh0} = OpISub %uint {sh_base} {exp_}") self.emit(f"{shc} = OpExtInst %uint %glsl UMin {sh0} {self.cu(31)}") self.emit(f"{dn} = OpShiftRightLogical %uint {m} {shc}") self.emit(f"{nr0} = OpISub %uint {a} {self.cu(112 << 23)}") self.emit(f"{nr} = OpShiftRightLogical %uint {nr0} {sh_m}") self.emit(f"{nm} = OpShiftRightLogical %uint {a} {sh_m}") self.emit(f"{nm1} = OpBitwiseAnd %uint {nm} {mmask}") self.emit(f"{nz} = OpIEqual %bool {nm1} {self.cu(0)}") self.emit(f"{nmant} = OpSelect %uint {nz} {self.cu(1)} {nm1}") self.emit(f"{nanb} = OpBitwiseOr %uint {nmant} {inf_b}") self.emit(f"{isnan} = OpUGreaterThan %bool {a} {self.cu(0x7F800000)}") self.emit(f"{isinf} = OpIEqual %bool {a} {self.cu(0x7F800000)}") self.emit(f"{big} = OpUGreaterThanEqual %bool {a} {self.cu(0x47800000)}") self.emit(f"{norm} = OpUGreaterThanEqual %bool {a} {self.cu(0x38800000)}") self.emit(f"{r0} = OpSelect %uint {norm} {nr} {dn}") self.emit(f"{r1} = OpSelect %uint {big} {max_fin} {r0}") self.emit(f"{r2} = OpSelect %uint {isinf} {inf_b} {r1}") self.emit(f"{r3} = OpSelect %uint {isnan} {nanb} {r2}") self.emit(f"{snan} = OpLogicalNot %bool {isnan}") self.emit(f"{ng} = OpLogicalAnd %bool {neg} {snan}") self.emit(f"{c_ufloat} = OpSelect %uint {ng} {self.cu(0)} {r3}") # Pick conversion by mode (ENC_F32/ENC_U32/ENC_I32 pass val through unchanged). res = val for kind, cand in ((self.ENC_UINT, c_uint), (self.ENC_SINT, c_sint), (self.ENC_UNORM, c_norm), (self.ENC_SNORM, c_norm), (self.ENC_F16, c_f16), (self.ENC_UFLOAT, c_ufloat)): eq, sel = self.tmp(), self.tmp() self.emit(f"{eq} = OpIEqual %bool {mode} {self.cu(kind)}") self.emit(f"{sel} = OpSelect %uint {eq} {cand} {res}") res = sel return res def format_encode_call(self, fmt, fc, normalized, unorm_view, ic, signed_ic, two): """The 4 words of the element a typed store writes, per the run-time FORMAT, and its size in bytes (0 for a code outside FORMATS: nothing is stored). Table-driven and branch-free (like format_decode_call / SHADER-849), replacing the old 77-way OpSwitch with a single %fmt_enc_desc_tab lookup and shared %fmt_enc_chan helper. The five lists are 4 uint ids each: the raw float bits, the same with NaN -> 0 (NORM stores), the B/R-swapped view for 50 and 56, the integers and the sign-extended d16 integers; a component the instruction does not give is 0.""" if self.fmt_enc_fn is None: self.uses_fmt_enc_table = True for v in Gen.fmt_enc_desc_table(): self.cu(v) self.cu(128) saved, self.body = self.body, [] chan_res = self._fmt_enc_chan_body("%fec_mode", "%fec_val", "%fec_w", "%fec_signed") chan_lines = self.body self.body = [] chan_fn = (["%fmt_enc_chan = OpFunction %uint None %fn_fmt_enc_chan", "%fec_mode = OpFunctionParameter %uint", "%fec_val = OpFunctionParameter %uint", "%fec_w = OpFunctionParameter %uint", "%fec_signed = OpFunctionParameter %bool", "%fec_entry = OpLabel"] + chan_lines + [f"OpReturnValue {chan_res}", "OpFunctionEnd"]) names = ["%fe_fmt"] + [f"%fe_{g}{i}" for g in "fnvis" for i in range(4)] + [f"%fe_t{i}" for i in range(8)] params = names[1:21] tw = names[21:29] # the channels a two-component V# store takes: norm, float, int, signed int (2 each) lists = [params[4 * g:4 * g + 4] for g in range(5)] desc = self.fmt_table_get("%_ptr_Private_fmt_enc_elem", "%fmt_enc_desc_tab", "%fe_fmt") mode, ncomp_r, ncomp, bgra_b, is_bgra, is_two = (self.tmp() for _ in range(6)) self.emit(f"{mode} = OpBitwiseAnd %uint {desc} {self.cu(15)}") self.emit(f"{ncomp_r} = OpShiftRightLogical %uint {desc} {self.cu(4)}") self.emit(f"{ncomp} = OpBitwiseAnd %uint {ncomp_r} {self.cu(7)}") self.emit(f"{bgra_b} = OpShiftRightLogical %uint {desc} {self.cu(31)}") self.emit(f"{is_bgra} = OpINotEqual %bool {bgra_b} {self.cu(0)}") self.emit(f"{is_two} = OpIEqual %bool {ncomp} {self.cu(2)}") widths = [] for i in range(4): wr, wi = self.tmp(), self.tmp() self.emit(f"{wr} = OpShiftRightLogical %uint {desc} {self.cu(7 + 6 * i)}") self.emit(f"{wi} = OpBitwiseAnd %uint {wr} {self.cu(63)}") widths.append(wi) offsets = [self.cu(0)] for i in range(1, 4): o = self.tmp() self.emit(f"{o} = OpIAdd %uint {offsets[-1]} {widths[i - 1]}") offsets.append(o) is_unorm, is_snorm, is_norm = (self.tmp() for _ in range(3)) self.emit(f"{is_unorm} = OpIEqual %bool {mode} {self.cu(self.ENC_UNORM)}") self.emit(f"{is_snorm} = OpIEqual %bool {mode} {self.cu(self.ENC_SNORM)}") self.emit(f"{is_norm} = OpLogicalOr %bool {is_unorm} {is_snorm}") is_u32, is_uint, is_int_u = (self.tmp() for _ in range(3)) self.emit(f"{is_u32} = OpIEqual %bool {mode} {self.cu(self.ENC_U32)}") self.emit(f"{is_uint} = OpIEqual %bool {mode} {self.cu(self.ENC_UINT)}") self.emit(f"{is_int_u} = OpLogicalOr %bool {is_u32} {is_uint}") is_i32, is_sint, is_int_s = (self.tmp() for _ in range(3)) self.emit(f"{is_i32} = OpIEqual %bool {mode} {self.cu(self.ENC_I32)}") self.emit(f"{is_sint} = OpIEqual %bool {mode} {self.cu(self.ENC_SINT)}") self.emit(f"{is_int_s} = OpLogicalOr %bool {is_i32} {is_sint}") words = [self.cu(0)] * 4 # Channels 0..3 can only land in dwords: 0 -> (0,), 1 -> (0,1), 2 -> (0,1,2), 3 -> (0,1,3). chan_dwords = ((0,), (0, 1), (0, 1, 2), (0, 1, 3)) for c in range(4): ns0 = self.tmp() self.emit(f"{ns0} = OpSelect %uint {is_bgra} {lists[2][c]} {lists[1][c]}") if c < 2: ns, fs, us, ss = (self.tmp() for _ in range(4)) self.emit(f"{ns} = OpSelect %uint {is_two} {tw[c]} {ns0}") self.emit(f"{fs} = OpSelect %uint {is_two} {tw[2 + c]} {lists[0][c]}") self.emit(f"{us} = OpSelect %uint {is_two} {tw[4 + c]} {lists[3][c]}") self.emit(f"{ss} = OpSelect %uint {is_two} {tw[6 + c]} {lists[4][c]}") else: ns, fs, us, ss = ns0, lists[0][c], lists[3][c], lists[4][c] s0, s1, src = (self.tmp() for _ in range(3)) self.emit(f"{s0} = OpSelect %uint {is_norm} {ns} {fs}") self.emit(f"{s1} = OpSelect %uint {is_int_u} {us} {s0}") self.emit(f"{src} = OpSelect %uint {is_int_s} {ss} {s1}") field = self.tmp() self.emit(f"{field} = OpFunctionCall %uint %fmt_enc_chan {mode} {src} {widths[c]} {is_snorm}") active, w32, wlo, one, m1, mask, masked, bo, shifted, contrib = (self.tmp() for _ in range(10)) self.emit(f"{active} = OpULessThan %bool {self.cu(c)} {ncomp}") self.emit(f"{w32} = OpIEqual %bool {widths[c]} {self.cu(32)}") self.emit(f"{wlo} = OpBitwiseAnd %uint {widths[c]} {self.cu(31)}") self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {wlo}") self.emit(f"{m1} = OpISub %uint {one} {self.cu(1)}") self.emit(f"{mask} = OpSelect %uint {w32} {self.cu(0xFFFFFFFF)} {m1}") self.emit(f"{masked} = OpBitwiseAnd %uint {field} {mask}") self.emit(f"{bo} = OpBitwiseAnd %uint {offsets[c]} {self.cu(31)}") self.emit(f"{shifted} = OpShiftLeftLogical %uint {masked} {bo}") self.emit(f"{contrib} = OpSelect %uint {active} {shifted} {self.cu(0)}") if c == 0: words[0] = contrib else: wi = self.tmp() self.emit(f"{wi} = OpShiftRightLogical %uint {offsets[c]} {self.cu(5)}") for j in chan_dwords[c]: hit, part, merged = (self.tmp() for _ in range(3)) self.emit(f"{hit} = OpIEqual %bool {wi} {self.cu(j)}") self.emit(f"{part} = OpSelect %uint {hit} {contrib} {self.cu(0)}") self.emit(f"{merged} = OpBitwiseOr %uint {words[j]} {part}") words[j] = merged res = self.tmp() self.emit(f"{res} = OpCompositeConstruct %v4uint_fmt " + " ".join(words)) self.emit(f"OpReturnValue {res}") lines, self.body = self.body, saved self.fmt_enc_fn = (chan_fn + ["%fmt_encode_fn = OpFunction %v4uint_fmt None %fn_fmt_encode"] + [f"{q} = OpFunctionParameter %uint" for q in names] + ["%fe_entry = OpLabel"] + lines + ["OpFunctionEnd"]) r = self.tmp() args = [fmt] + fc + normalized + unorm_view + ic + signed_ic + two self.emit(f"{r} = OpFunctionCall %v4uint_fmt %fmt_encode_fn " + " ".join(args)) size = self.fmt_size_of(fmt) words = [] for c in range(4): x = self.tmp() self.emit(f"{x} = OpCompositeExtract %uint {r} {c}") words.append(x) return words, size def mtbuf_format(self, op, mods): """The format code an MTBUF instruction (tbuffer_load/store_format_*) encodes for itself, which replaces the V#'s. LLVM omits the modifier for GFX10's default, BUF_FMT_8_UNORM (code 1).""" fm = next((m for m in mods if m.startswith("format:")), "format:[BUF_FMT_8_UNORM]") name = "GFX10_FORMAT_" + fm.split("BUF_FMT_")[-1].rstrip("]") code = next((c for c, n in GFX10_FORMATS.items() if n == name), None) if code is None or code not in self.FORMATS: raise Unsupported(op + " " + name) self.fixed_format_codes.add(code) return code def buffer_store(self, op, a, mods, fixed_fmt=None): """buffer_store_dword[xN] (raw) and buffer_store_format_* (every format in FORMATS, read from the V# at run time). tbuffer_store_format_* comes here with its own format in fixed_fmt: only that one is encoded, and the bounds check uses its element size, whatever the V# says. Only active lanes store, inside a structured if.""" if any(m in mods for m in ("lds", "tfe", "d16")): raise Unsupported(op + " form") store_mem = self._psb_store_op(mods) d16 = "_d16_" in op vd = a[0] dword_store = op.startswith("buffer_store_dword") if dword_store: addr, d3, in_b, per, step = self.buffer_address(a, mods, parts=True) else: addr, d3, in_b, step = self.buffer_address(a, mods, elem="fmt", fixed_fmt=fixed_fmt) per = None if dword_store: n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) words = [self.load_reg("vgpr", vd["r"] + i) for i in range(n)] plans = None else: n = len(op.rsplit("_", 1)[1]) if d16: # two 16-bit values per register: f16 for float kinds, 16-bit integers for integer kinds regs = [self.load_reg("vgpr", vd["r"] + i) for i in range((n + 1) // 2)] comps, icomps = [], [] for i in range(n): r = regs[i // 2] # buffer_store_format_d16_hi_x stores the high half of the one register iv = self.u16_half(r, 1 if "_d16_hi_" in op else i % 2) v2, f = self.tmp(), self.tmp() self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {iv}") self.emit(f"{f} = OpCompositeExtract %float {v2} 0") comps.append(self.tou(f)) icomps.append(iv) else: comps = [self.load_reg("vgpr", vd["r"] + i) for i in range(n)] icomps = comps if fixed_fmt is not None: fmt = None # tbuffer: the instruction's format, so no V# FORMAT to branch on else: fmt = self.tmp() self.emit(f"{fmt} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}") # Encodings for the formats that appear in store-heavy shaders; others store nothing. f32 = {22: 1, 64: 2, 74: 3, 77: 4} # Float views of the components, computed before any branch so every branch can use them. fl = [self.tof(c) for c in comps] + ["%f0"] * (4 - len(comps)) plans = (fmt, comps, f32, fl, icomps) words = None if words is not None and per is not None and len(words) > 1: # modes 0 and 3: every dword is stored only if it ends inside (measured: a store that straddles the edge # writes the dwords before it); a store past the end of the buffer is a host-memory hazard otherwise ptr, host = self.tmp(), self.host_addr(addr, "store", lambda: self.guard_delta(len(words), step)) self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") for i, w in enumerate(words): cond, lbl_do, lbl_end = self.tmp(), self.tmp() + "_do", self.tmp() + "_end" self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {per(i)}") self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") p = self.buf_dword_ptr(ptr, host, step, i) self.emit(f"OpStore {p} {w} {store_mem}") self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") return if fixed_fmt is not None: # A V# whose FORMAT is 0 (INVALID) disables the store, though MTBUF brings its own format (measured natively # on gfx1035, wave32 and wave64, in OOB_SELECT 0, 1 and 3). vf, valid, ok = self.tmp(), self.tmp(), self.tmp() self.emit(f"{vf} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}") self.emit(f"{valid} = OpINotEqual %bool {vf} {self.cu(0)}") self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {valid}") in_b = ok act = self.tmp() self.emit(f"{act} = OpLogicalAnd %bool {self.active_b()} {in_b}") lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") ptr, host = self.tmp(), self.host_addr(addr, "store", lambda: self.guard_delta( len(words) if words is not None else self.store_element_dwords(plans[0], fixed_fmt), step)) self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") if words is not None: for i, w in enumerate(words): p = self.buf_dword_ptr(ptr, host, step, i) self.emit(f"OpStore {p} {w} {store_mem}") else: fmt, comps, f32, fl, icomps = plans # Every format in FORMATS (the same table the loads decode); unknown formats store nothing. fc = comps + [self.cu(0)] * (4 - len(comps)) ic = icomps + [self.cu(0)] * (4 - len(icomps)) # Normalized stores map either sign of NaN to zero before clamping. # Compute this once per source component; float and integer formats use the original bits. normalized = [] for component, float_value in zip(comps, fl): nan, value = self.tmp(), self.tmp() self.emit(f"{nan} = OpIsNan %bool {float_value}") self.emit(f"{value} = OpSelect %uint {nan} {self.cu(0)} {component}") normalized.append(value) # The runtime names B8G8R8A8 and A2R10G10B10 UNORM with V# selectors Z,Y,X,W. # Pad the input first: even store_format_x must put its red value in the third field. unorm_rgba = normalized + [self.cu(0)] * (4 - n) selectors, bgra, red, blue = (self.tmp() for _ in range(4)) self.emit(f"{selectors} = OpBitwiseAnd %uint {d3} {self.cu(0xfff)}") self.emit(f"{bgra} = OpIEqual %bool {selectors} {self.cu(0xf2e)}") self.emit(f"{red} = OpSelect %uint {bgra} {unorm_rgba[2]} {unorm_rgba[0]}") self.emit(f"{blue} = OpSelect %uint {bgra} {unorm_rgba[0]} {unorm_rgba[2]}") unorm_view = [red, unorm_rgba[1], blue, unorm_rgba[3]] signed_ic = ic if d16: signed_ic = [self.int_bits(self.i16_half(regs[i // 2], 1 if "_d16_hi_" in op else i % 2)) for i in range(n)] signed_ic = signed_ic + [self.cu(0)] * (4 - len(signed_ic)) # MUBUF 2-component stores infer COMP_SWAP from V# DST_SEL_X/Y/Z (measured natively on gfx1036 across # all 1,296 valid DST_SEL tuples, wave32 and wave64): XY01 -> (x, y), YX01 -> (y, x), XYZW -> (x, w), # YXZW/ZYXW -> (w, x). MTBUF (fixed_fmt is not None) ignores DST_SEL and always stores (x, y). if fixed_fmt is None: sx, sy, sz = self.tmp(), self.tmp(), self.tmp() self.emit(f"{sx} = OpBitFieldUExtract %uint {d3} {self.cu(0)} {self.cu(3)}") self.emit(f"{sy} = OpBitFieldUExtract %uint {d3} {self.cu(3)} {self.cu(3)}") self.emit(f"{sz} = OpBitFieldUExtract %uint {d3} {self.cu(6)} {self.cu(3)}") sy_reg, sz_reg, sz_const, use_y = (self.tmp() for _ in range(4)) self.emit(f"{sy_reg} = OpUGreaterThanEqual %bool {sy} {self.cu(4)}") self.emit(f"{sz_reg} = OpUGreaterThanEqual %bool {sz} {self.cu(4)}") self.emit(f"{sz_const} = OpLogicalNot %bool {sz_reg}") self.emit(f"{use_y} = OpLogicalAnd %bool {sy_reg} {sz_const}") sx_ne4, yz_reg, rev2 = self.tmp(), self.tmp(), self.tmp() self.emit(f"{sx_ne4} = OpINotEqual %bool {sx} {self.cu(4)}") self.emit(f"{yz_reg} = OpLogicalOr %bool {sy_reg} {sz_reg}") self.emit(f"{rev2} = OpLogicalAnd %bool {sx_ne4} {yz_reg}") def swiz2(arr): sec, c0, c1 = self.tmp(), self.tmp(), self.tmp() self.emit(f"{sec} = OpSelect %uint {use_y} {arr[1]} {arr[3]}") self.emit(f"{c0} = OpSelect %uint {rev2} {sec} {arr[0]}") self.emit(f"{c1} = OpSelect %uint {rev2} {arr[0]} {sec}") return [c0, c1] norm2 = swiz2(unorm_rgba) fc2 = swiz2(fc) ic2 = swiz2(ic) signed_ic2 = swiz2(signed_ic) if d16 else ic2 if fmt is None: # tbuffer_store: its own format, encoded in line code = fixed_fmt size, kind, widths = self.FORMATS[code] if True: ncomp = min(len(widths), n) source = normalized if kind in ("unorm", "snorm", "uscaled", "sscaled") else fc fcs = source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp) if code in (50, 56): fcs = unorm_view integer_source = signed_ic if kind in ("i32", "sint") else ic ics = integer_source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp) words = self.encode_format(fcs + [self.cu(0)] * 4, ics + [self.cu(0)] * 4, code) if size >= 4: for k, w in enumerate(words[:size // 4]): pp = self.buf_dword_ptr(ptr, host, step, k) self.emit(f"OpStore {pp} {w} {store_mem}") else: # 1- or 2-byte element: merge into its dword with atomics so neighbours are kept. al, sh, sh8, ap, mk, mks, inv, val, vs, t1, t2 = (self.tmp() for _ in range(11)) self.emit(f"{sh} = OpUConvert %uint {addr}") lo3, lo64 = self.tmp(), self.tmp() self.emit(f"{lo3} = OpBitwiseAnd %uint {sh} {self.cu(3)}") self.emit(f"{lo64} = OpUConvert %ulong {lo3}") self.emit(f"{al} = OpISub %ulong {addr} {lo64}") self.emit(f"{sh8} = OpShiftLeftLogical %uint {sh} {self.cu(3)}") sh24 = self.tmp() self.emit(f"{sh24} = OpBitwiseAnd %uint {sh8} {self.cu(24)}") # MoltenVK 1.4.0 needs an addressable array element for the Metal atomic operations. dword_arr = self.tmp() self.emit(f"{dword_arr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al, 'store')}") self.emit(f"{ap} = OpAccessChain %_ptr_PSB_uint {dword_arr} {self.cu(0)}") self.emit(f"{mk} = OpCopyObject %uint {self.cu((1 << (8 * size)) - 1)}") self.emit(f"{mks} = OpShiftLeftLogical %uint {mk} {sh24}") self.emit(f"{inv} = OpNot %uint {mks}") self.emit(f"{val} = OpBitwiseAnd %uint {words[0]} {mk}") self.emit(f"{vs} = OpShiftLeftLogical %uint {val} {sh24}") self.emit(f"{t1} = OpAtomicAnd %uint {ap} {self.cu(1)} {self.cu(0)} {inv}") self.emit(f"{t2} = OpAtomicOr %uint {ap} {self.cu(1)} {self.cu(0)} {vs}") else: pad = lambda xs: (list(xs) + [self.cu(0)] * 4)[:4] # noqa: E731 two = norm2 + fc2 + ic2 + signed_ic2 if fixed_fmt is None else [self.cu(0)] * 8 words, size = self.format_encode_call(fmt, pad(fc), pad(normalized), pad(unorm_view), pad(ic), pad(signed_ic), two) # whole dwords: dword k is stored when the element has more than 4k bytes for k in range(4): big, lk, le = self.tmp(), self.tmp() + "_s", self.tmp() + "_se" self.emit(f"{big} = OpUGreaterThanEqual %bool {size} {self.cu(4 * (k + 1))}") self.emit(f"OpSelectionMerge {le} None") self.emit(f"OpBranchConditional {big} {lk} {le}") self.emit(f"{lk} = OpLabel") pp = self.buf_dword_ptr(ptr, host, step, k) self.emit(f"OpStore {pp} {words[k]} {store_mem}") self.emit(f"OpBranch {le}") self.emit(f"{le} = OpLabel") # 1- or 2-byte element: merge into its dword with atomics so neighbours are kept. small, ld, le = self.tmp(), self.tmp() + "_s", self.tmp() + "_se" sm1 = self.tmp() self.emit(f"{sm1} = OpISub %uint {size} {self.cu(1)}") self.emit(f"{small} = OpULessThan %bool {sm1} {self.cu(2)}") # size 1 or 2 (0 wraps to a large value) self.emit(f"OpSelectionMerge {le} None") self.emit(f"OpBranchConditional {small} {ld} {le}") self.emit(f"{ld} = OpLabel") al, sh, sh8, ap, mk, mks, inv, val, vs, t1, t2, one = (self.tmp() for _ in range(12)) self.emit(f"{sh} = OpUConvert %uint {addr}") lo3, lo64 = self.tmp(), self.tmp() self.emit(f"{lo3} = OpBitwiseAnd %uint {sh} {self.cu(3)}") self.emit(f"{lo64} = OpUConvert %ulong {lo3}") self.emit(f"{al} = OpISub %ulong {addr} {lo64}") self.emit(f"{sh8} = OpShiftLeftLogical %uint {sh} {self.cu(3)}") sh24 = self.tmp() self.emit(f"{sh24} = OpBitwiseAnd %uint {sh8} {self.cu(24)}") # MoltenVK 1.4.0 needs an addressable array element for the Metal atomic operations. dword_arr = self.tmp() self.emit(f"{dword_arr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al, 'store')}") self.emit(f"{ap} = OpAccessChain %_ptr_PSB_uint {dword_arr} {self.cu(0)}") self.emit(f"{one} = OpIEqual %bool {size} {self.cu(1)}") self.emit(f"{mk} = OpSelect %uint {one} {self.cu(0xFF)} {self.cu(0xFFFF)}") self.emit(f"{mks} = OpShiftLeftLogical %uint {mk} {sh24}") self.emit(f"{inv} = OpNot %uint {mks}") self.emit(f"{val} = OpBitwiseAnd %uint {words[0]} {mk}") self.emit(f"{vs} = OpShiftLeftLogical %uint {val} {sh24}") self.emit(f"{t1} = OpAtomicAnd %uint {ap} {self.cu(1)} {self.cu(0)} {inv}") self.emit(f"{t2} = OpAtomicOr %uint {ap} {self.cu(1)} {self.cu(0)} {vs}") self.emit(f"OpBranch {le}") self.emit(f"{le} = OpLabel") self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") def cmp_class(self, a, exec_only=False, ty="f32", mods=()): """Test x's class against the mask and write the result to VCC/SGPR or EXEC. Bits: 0 sNaN, 1 qNaN, 2 -inf, 3 -normal, 4 -denormal, 5 -0, 6 +0, 7 +denormal, 8 +normal, 9 +inf. Supports f32, f16 (with op_sel[0], abs/neg on raw 16-bit bits) and f64 (integer bitwise on lo/hi, no OpCapability Float64 needed).""" if ty != "f32" and any(m == "clamp" or m.startswith(("mul:", "div:")) for m in mods): raise Unsupported(f"v_cmp_class_{ty} output modifier") # For f16, the class mask takes float inline constants as 16-bit binary16 (low half over 0) before SDWA selection. mask = self.src_h(a[-1]) if ty == "f16" else self.src_u(a[-1]) def b(cond_line): t = self.tmp() self.emit(f"{t} = {cond_line}") return t if ty == "f32": src = a[-2] # Apply abs/neg as raw sign-bit moves on uint bits: RDNA2 (gfx1036, wave32/64, IEEE=0/1, denorm keep/flush) # never quiets an sNaN or flushes a denormal on v_cmp(x)_class_f32, whereas SPIR-V FAbs/OpFNegate may quiet. u = self.src_u({k: v for k, v in src.items() if k not in ("abs", "neg")}) if src.get("abs"): g = self.tmp() self.emit(f"{g} = OpBitwiseAnd %uint {u} {self.cu(0x7FFFFFFF)}") u = g if src.get("neg"): g = self.tmp() self.emit(f"{g} = OpBitwiseXor %uint {u} {self.cu(0x80000000)}") u = g sign, absu = self.tmp(), self.tmp() self.emit(f"{sign} = OpShiftRightLogical %uint {u} {self.cu(31)}") self.emit(f"{absu} = OpBitwiseAnd %uint {u} {self.cu(0x7FFFFFFF)}") exp_, man = self.tmp(), self.tmp() self.emit(f"{exp_} = OpShiftRightLogical %uint {absu} {self.cu(23)}") self.emit(f"{man} = OpBitwiseAnd %uint {absu} {self.cu(0x7FFFFF)}") neg = self.tmp_bool_nz(sign) is_zero = b(f"OpIEqual %bool {absu} {self.cu(0)}") exp0 = b(f"OpIEqual %bool {exp_} {self.cu(0)}") expmax = b(f"OpIEqual %bool {exp_} {self.cu(255)}") man0 = b(f"OpIEqual %bool {man} {self.cu(0)}") quiet = b(f"OpUGreaterThanEqual %bool {man} {self.cu(0x400000)}") elif ty == "f16": sel, dhi = self.opsel_bits(mods, 2) if sel[1] or dhi: raise Unsupported("v_cmp_class_f16 op_sel") sv = a[-2] u = self.src_h(sv) if sel[0]: t = self.tmp() self.emit(f"{t} = OpShiftRightLogical %uint {u} {self.cu(16)}") u = t h = self.tmp() self.emit(f"{h} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}") if sv.get("abs"): t = self.tmp() self.emit(f"{t} = OpBitwiseAnd %uint {h} {self.cu(0x7FFF)}") h = t if sv.get("neg"): t = self.tmp() self.emit(f"{t} = OpBitwiseXor %uint {h} {self.cu(0x8000)}") h = t sign, absu, exp_, man = (self.tmp() for _ in range(4)) self.emit(f"{sign} = OpShiftRightLogical %uint {h} {self.cu(15)}") self.emit(f"{absu} = OpBitwiseAnd %uint {h} {self.cu(0x7FFF)}") self.emit(f"{exp_} = OpShiftRightLogical %uint {absu} {self.cu(10)}") self.emit(f"{man} = OpBitwiseAnd %uint {absu} {self.cu(0x3FF)}") neg = self.tmp_bool_nz(sign) is_zero = b(f"OpIEqual %bool {absu} {self.cu(0)}") exp0 = b(f"OpIEqual %bool {exp_} {self.cu(0)}") expmax = b(f"OpIEqual %bool {exp_} {self.cu(31)}") man0 = b(f"OpIEqual %bool {man} {self.cu(0)}") quiet = b(f"OpUGreaterThanEqual %bool {man} {self.cu(0x200)}") else: # f64 if any(m.startswith("op_sel") for m in mods): raise Unsupported("v_cmp_class_f64 op_sel") sv = a[-2] if sv["k"] in ("vgpr", "sgpr") and sv.get("n") == 2: lo, hi = self.load_reg(sv["k"], sv["r"]), self.load_reg(sv["k"], sv["r"] + 1) elif sv["k"] == "fimm": bits = struct.unpack("> 32) elif sv["k"] == "imm": v = sv["v"] if -16 <= v <= 64: v64 = v & 0xFFFFFFFFFFFFFFFF lo, hi = self.cu(v64 & 0xFFFFFFFF), self.cu(v64 >> 32) else: # 32-bit literal dword on a 64-bit float operand occupies the upper 32 bits (RDNA2 ISA). lo, hi = self.cu(0), self.cu(v & 0xFFFFFFFF) else: raise Unsupported("v_cmp_class_f64 operand") if sv.get("abs"): t = self.tmp() self.emit(f"{t} = OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}") hi = t if sv.get("neg"): t = self.tmp() self.emit(f"{t} = OpBitwiseXor %uint {hi} {self.cu(0x80000000)}") hi = t sign, absu, exp_, man_hi, man_or, all_or = (self.tmp() for _ in range(6)) self.emit(f"{sign} = OpShiftRightLogical %uint {hi} {self.cu(31)}") self.emit(f"{absu} = OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}") self.emit(f"{exp_} = OpShiftRightLogical %uint {absu} {self.cu(20)}") self.emit(f"{man_hi} = OpBitwiseAnd %uint {absu} {self.cu(0xFFFFF)}") self.emit(f"{man_or} = OpBitwiseOr %uint {man_hi} {lo}") self.emit(f"{all_or} = OpBitwiseOr %uint {absu} {lo}") neg = self.tmp_bool_nz(sign) is_zero = b(f"OpIEqual %bool {all_or} {self.cu(0)}") exp0 = b(f"OpIEqual %bool {exp_} {self.cu(0)}") expmax = b(f"OpIEqual %bool {exp_} {self.cu(2047)}") man0 = b(f"OpIEqual %bool {man_or} {self.cu(0)}") quiet = b(f"OpUGreaterThanEqual %bool {man_hi} {self.cu(0x80000)}") man_nz = b(f"OpLogicalNot %bool {man0}") is_inf = b(f"OpLogicalAnd %bool {expmax} {man0}") is_nan = b(f"OpLogicalAnd %bool {expmax} {man_nz}") snan = b(f"OpLogicalAnd %bool {is_nan} " + b(f"OpLogicalNot %bool {quiet}")) qnan = b(f"OpLogicalAnd %bool {is_nan} {quiet}") denorm = b(f"OpLogicalAnd %bool {exp0} {man_nz}") normal = b(f"OpLogicalAnd %bool " + b(f"OpLogicalNot %bool {exp0}") + " " + b(f"OpLogicalNot %bool {expmax}")) pos = b(f"OpLogicalNot %bool {neg}") classes = [snan, qnan, b(f"OpLogicalAnd %bool {is_inf} {neg}"), b(f"OpLogicalAnd %bool {normal} {neg}"), b(f"OpLogicalAnd %bool {denorm} {neg}"), b(f"OpLogicalAnd %bool {is_zero} {neg}"), b(f"OpLogicalAnd %bool {is_zero} {pos}"), b(f"OpLogicalAnd %bool {denorm} {pos}"), b(f"OpLogicalAnd %bool {normal} {pos}"), b(f"OpLogicalAnd %bool {is_inf} {pos}")] acc = "%false" for i, c in enumerate(classes): bit = b(f"OpBitwiseAnd %uint {mask} {self.cu(1 << i)}") on = b(f"OpINotEqual %bool {bit} {self.cu(0)}") hit = b(f"OpLogicalAnd %bool {on} {c}") acc = b(f"OpLogicalOr %bool {acc} {hit}") acc = b(f"OpLogicalAnd %bool {acc} {self.active_b()}") # inactive lanes write 0 if exec_only: self.emit(f"OpStore %active {acc}") self.uses_active = True return r = b(f"OpSelect %uint {acc} {self.cu(0xFFFFFFFF)} {self.cu(0)}") self.mask_dst({"k": "special", "t": "vcc"} if len(a) == 2 else a[0], r) @staticmethod def mod_int(mods, name, default): m = next((m for m in mods if m.startswith(name + ":")), None) return int(m.split(":", 1)[1], 0) if m else default def cmp_class_f64(self, op, a, exec_only=False, mods=()): """v_cmp_class_f64 / v_cmpx_class_f64: test IEEE-754 binary64 class against the 10-bit mask using pure 32-bit integer ops (no Float64 capability required). Bits: 0 sNaN, 1 qNaN, 2 -inf, 3 -normal, 4 -denormal, 5 -0, 6 +0, 7 +denormal, 8 +normal, 9 +inf.""" if mods: raise Unsupported(op + " modifiers") if exec_only: if not (len(a) == 2 or (len(a) == 3 and a[0]["k"] == "special" and a[0]["t"] in ("exec", "exec_lo"))): raise Unsupported(op + " operands") else: if len(a) not in (2, 3): raise Unsupported(op + " operands") if len(a) == 3 and not self.is_mask_dst(a[0]): raise Unsupported(op + " destination") src0, mask_op = a[-2], a[-1] if mask_op.get("n", 1) != 1 or mask_op.get("abs") or mask_op.get("neg"): raise Unsupported(op + " mask") if src0["k"] in ("vgpr", "sgpr") and src0.get("n") == 2: lo, hi = self.load_reg(src0["k"], src0["r"]), self.load_reg(src0["k"], src0["r"] + 1) elif src0["k"] == "fimm": bits = struct.unpack("> 32) elif src0["k"] == "imm": v = src0["v"] # RDNA2 ISA: inline integers (-16..64) sign-extend to 64 bits; a 32-bit literal occupies bits [63:32]. if src0.get("literal") or (not (-16 <= v <= 64) and -0x80000000 <= v <= 0xFFFFFFFF): lo, hi = self.cu(0), self.cu(v & 0xFFFFFFFF) else: bits = v & 0xFFFFFFFFFFFFFFFF lo, hi = self.cu(bits & 0xFFFFFFFF), self.cu(bits >> 32) else: raise Unsupported(op + " operand") if src0.get("abs"): t = self.tmp() self.emit(f"{t} = OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}") hi = t if src0.get("neg"): t = self.tmp() self.emit(f"{t} = OpBitwiseXor %uint {hi} {self.cu(0x80000000)}") hi = t mask = self.src_u(mask_op) def b(cond_line): t = self.tmp() self.emit(f"{t} = {cond_line}") return t sign = b(f"OpShiftRightLogical %uint {hi} {self.cu(31)}") exp_s = b(f"OpShiftRightLogical %uint {hi} {self.cu(20)}") exp_ = b(f"OpBitwiseAnd %uint {exp_s} {self.cu(0x7FF)}") man_hi = b(f"OpBitwiseAnd %uint {hi} {self.cu(0xFFFFF)}") man_or = b(f"OpBitwiseOr %uint {man_hi} {lo}") neg = self.tmp_bool_nz(sign) pos = b(f"OpLogicalNot %bool {neg}") exp0 = b(f"OpIEqual %bool {exp_} {self.cu(0)}") expmax = b(f"OpIEqual %bool {exp_} {self.cu(0x7FF)}") man0 = b(f"OpIEqual %bool {man_or} {self.cu(0)}") man_nz = b(f"OpLogicalNot %bool {man0}") is_zero = b(f"OpLogicalAnd %bool {exp0} {man0}") denorm = b(f"OpLogicalAnd %bool {exp0} {man_nz}") normal = b(f"OpLogicalAnd %bool " + b(f"OpLogicalNot %bool {exp0}") + " " + b(f"OpLogicalNot %bool {expmax}")) is_inf = b(f"OpLogicalAnd %bool {expmax} {man0}") is_nan = b(f"OpLogicalAnd %bool {expmax} {man_nz}") qbit = b(f"OpBitwiseAnd %uint {man_hi} {self.cu(0x80000)}") quiet = self.tmp_bool_nz(qbit) snan = b(f"OpLogicalAnd %bool {is_nan} " + b(f"OpLogicalNot %bool {quiet}")) qnan = b(f"OpLogicalAnd %bool {is_nan} {quiet}") classes = [ snan, qnan, b(f"OpLogicalAnd %bool {is_inf} {neg}"), b(f"OpLogicalAnd %bool {normal} {neg}"), b(f"OpLogicalAnd %bool {denorm} {neg}"), b(f"OpLogicalAnd %bool {is_zero} {neg}"), b(f"OpLogicalAnd %bool {is_zero} {pos}"), b(f"OpLogicalAnd %bool {denorm} {pos}"), b(f"OpLogicalAnd %bool {normal} {pos}"), b(f"OpLogicalAnd %bool {is_inf} {pos}"), ] acc = "%false" for i, c in enumerate(classes): bit = b(f"OpBitwiseAnd %uint {mask} {self.cu(1 << i)}") on = b(f"OpINotEqual %bool {bit} {self.cu(0)}") hit = b(f"OpLogicalAnd %bool {on} {c}") acc = b(f"OpLogicalOr %bool {acc} {hit}") acc = b(f"OpLogicalAnd %bool {acc} {self.active_b()}") # inactive lanes write 0 if exec_only: self.emit(f"OpStore %active {acc}") self.uses_active = True return r = b(f"OpSelect %uint {acc} {self.cu(0xFFFFFFFF)} {self.cu(0)}") self.mask_dst({"k": "special", "t": "vcc"} if len(a) == 2 else a[0], r) # LDS atomics (non-returning name -> SPIR-V atomic); _rtn_ forms share the entry. LDS_ATOMICS = {"ds_add_u32": "OpAtomicIAdd", "ds_sub_u32": "OpAtomicISub", "ds_min_u32": "OpAtomicUMin", "ds_max_u32": "OpAtomicUMax", "ds_min_i32": "OpAtomicSMin", "ds_max_i32": "OpAtomicSMax", "ds_and_b32": "OpAtomicAnd", "ds_or_b32": "OpAtomicOr", "ds_xor_b32": "OpAtomicXor", "ds_wrxchg_rtn_b32": "OpAtomicExchange"} def lds_ptr(self, addr, byte_off): """Pointer to the LDS dword at (addr + byte_off) / 4, wrapped to the array (LDS is a Workgroup uint array).""" s1, i, m, p = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{s1} = OpIAdd %uint {addr} {self.cu(byte_off)}") self.emit(f"{i} = OpShiftRightLogical %uint {s1} {self.cu(2)}") self.emit(f"{m} = OpBitwiseAnd %uint {i} {self.cu(self.lds_dwords - 1)}") self.emit(f"{p} = OpAccessChain %_ptr_WG_uint %lds {m}") return p def lds_access(self, addr, byte_off, fn, bound=None): """One LDS dword access: fn(pointer) emits it and returns its uint result id (a load, an atomic's old value) or None (a store). Without lds_bound this is fn(lds_ptr(...)), the wrapped access shaders always had. With it (SHADER-309: the program reaches past its RSRC2 allocation, or the array was shrunk to it), the dword index is checked: RDNA2 LDS does not wrap, an access outside the allocation reads 0 and its write is dropped (RDNA2 ISA sections 3.6.1 and 3.6.6), so the access runs only in range and the result is 0 otherwise. `bound` (dwords) checks this one access even when lds_bound is unset.""" bound = self.lds_bound if bound is None else bound if bound is None: return fn(self.lds_ptr(addr, byte_off)) s1, i, ok, p = self.tmp(), self.tmp(), self.tmp(), self.tmp() pre, do, end = self.tmp() + "_lb", self.tmp() + "_lin", self.tmp() + "_lend" self.emit(f"{s1} = OpIAdd %uint {addr} {self.cu(byte_off)}") self.emit(f"{i} = OpShiftRightLogical %uint {s1} {self.cu(2)}") self.emit(f"{ok} = OpULessThan %bool {i} {self.cu(bound)}") self.emit(f"OpBranch {pre}") self.emit(f"{pre} = OpLabel") self.emit(f"OpSelectionMerge {end} None") self.emit(f"OpBranchConditional {ok} {do} {end}") self.emit(f"{do} = OpLabel") self.emit(f"{p} = OpAccessChain %_ptr_WG_uint %lds {i}") r = fn(p) done_lbl = self.current_label_placeholder() self.emit(f"OpBranch {end}") self.emit(f"{end} = OpLabel") if r is None: return None v = self.tmp() self.emit(f"{v} = OpPhi %uint {r} {done_lbl} {self.cu(0)} {pre}") return v def lds_load(self, addr, byte_off, bound=None): # Volatile: another lane's ds_write may come between two accesses of this lane, and the Vulkan memory model # orders nothing between invocations without a barrier, so a driver may otherwise move this read ahead of # the wave's earlier writes or merge it with another read (docs/design.md, "LDS access order within a wave"). def f(p): v = self.tmp() self.emit(f"{v} = OpLoad %uint {p} Volatile") return v return self.lds_access(addr, byte_off, f, bound) def lds_cross_bound(self): """Bound (dwords) for the next dword a dword-crossing access reaches: the allocation, never wrapped to dword 0, even in a shader whose other accesses keep the wrapped power-of-two array.""" if self.lds_bound is not None: return self.lds_bound return min(self.lds_declared, self.lds_dwords) if self.lds_declared else self.lds_dwords def lds_store(self, addr, byte_off, val): self.lds_access(addr, byte_off, lambda p: self.emit(f"OpStore {p} {val} Volatile")) # as lds_load def lds_next_in_bounds(self, addr, byte_off): """Bool: the dword after the one at (addr + byte_off) is inside the allocation (lds_cross_bound).""" s1, i, ok = self.tmp(), self.tmp(), self.tmp() self.emit(f"{s1} = OpIAdd %uint {addr} {self.cu(byte_off + 1)}") self.emit(f"{i} = OpShiftRightLogical %uint {s1} {self.cu(2)}") self.emit(f"{ok} = OpULessThan %bool {i} {self.cu(self.lds_cross_bound())}") return ok def lds_u16_cross_read(self, addr, byte_off, w, sh): """A 16-bit LDS read at byte 3 of a dword (bit offset `sh` 24) also takes byte 0 of the next dword, as RDNA2 LDS reads it in unaligned mode (llc -mcpu=gfx1030 -mattr=+unaligned-access-mode emits one ds_read_u16 at offset 3; gfx1036 hardware agrees). When that byte is past the allocation the whole read returns 0, as on gfx1036. Returns (word, bit offset) for the 16-bit extract; the next dword is only read when crossing.""" cross, lo, hi, both, comb, w2, sh2 = (self.tmp() for _ in range(7)) x_do, x_end = self.tmp() + "_x", self.tmp() + "_xend" self.emit(f"{cross} = OpIEqual %bool {sh} {self.cu(24)}") pre = self.current_label_placeholder() self.emit(f"OpSelectionMerge {x_end} None") self.emit(f"OpBranchConditional {cross} {x_do} {x_end}") self.emit(f"{x_do} = OpLabel") ok = self.lds_next_in_bounds(addr, byte_off) nxt = self.lds_load(addr, byte_off + 1, self.lds_cross_bound()) self.emit(f"{lo} = OpShiftRightLogical %uint {w} {self.cu(24)}") self.emit(f"{hi} = OpShiftLeftLogical %uint {nxt} {self.cu(8)}") self.emit(f"{both} = OpBitwiseOr %uint {lo} {hi}") self.emit(f"{comb} = OpSelect %uint {ok} {both} {self.cu(0)}") last = self.current_label_placeholder() self.emit(f"OpBranch {x_end}") self.emit(f"{x_end} = OpLabel") self.emit(f"{w2} = OpPhi %uint {comb} {last} {w} {pre}") self.emit(f"{sh2} = OpSelect %uint {cross} {self.cu(0)} {sh}") return w2, sh2 def lds_atomic(self, addr, byte_off, rest): """`rest` is the atomic instruction after its result id, with {p} where the pointer goes.""" def f(p): v = self.tmp() self.emit(f"{v} = " + rest.replace("{p}", p)) return v return self.lds_access(addr, byte_off, f) def ds_append(self, op, a, mods): """ds_append / ds_consume vD [offset:N]: one LDS add (append) or subtract (consume) of the number of lanes on in EXEC, for the whole wave, at the byte address N; every active lane gets the value before the op, inactive lanes keep vD. Measured natively on RDNA2 gfx1036 (hunt6 hw_append.py, wave32 and wave64 with EXEC across both halves): the address is the offset field alone, M0 (0x4, 0x100, 0x10000, 0x40000, 0x80000) does not move it. The add is done once, by the first active lane of the wave (the wave's EXEC gathered as for s_bcnt1); the old value reaches the other lanes by a subgroup shuffle from that lane, or an exchange round under --wave64-emulate (a wave64 on 32-wide subgroups without it: right in the half of the first active lane only, the known cross-half approximation). The gds form is refused.""" if "gds" in mods: raise Unsupported(op + " gds") if not a or a[0]["k"] != "vgpr": raise Unsupported(op + " operands") off = self.mod_int(mods, "offset", 0) lo, hi = self.wave_mask({"k": "special", "t": "exec"}) cl, ch, cnt, lz, hz, l, h, h32, fh, first, lane, me, act, do = (self.tmp() for _ in range(14)) self.emit(f"{cl} = OpBitCount %uint {lo}") self.emit(f"{ch} = OpBitCount %uint {hi}") self.emit(f"{cnt} = OpIAdd %uint {cl} {ch}") self.emit(f"{lz} = OpINotEqual %bool {lo} {self.cu(0)}") self.emit(f"{hz} = OpINotEqual %bool {hi} {self.cu(0)}") self.emit(f"{l} = OpExtInst %uint %glsl FindILsb {lo}") self.emit(f"{h} = OpExtInst %uint %glsl FindILsb {hi}") self.emit(f"{h32} = OpIAdd %uint {h} {self.cu(32)}") self.emit(f"{fh} = OpSelect %uint {hz} {h32} {self.cu(64)}") # no lane on: 64, nobody's lane self.emit(f"{first} = OpSelect %uint {lz} {l} {fh}") self.emit(f"{lane} = OpCopyObject %uint {self.wave_lane()}") self.emit(f"{me} = OpIEqual %bool {lane} {first}") self.emit(f"{act} = OpCopyObject %bool {self.active_b()}") self.emit(f"{do} = OpLogicalAnd %bool {me} {act}") lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" pre = self.current_label_placeholder() self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {do} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") spv = "OpAtomicIAdd" if op == "ds_append" else "OpAtomicISub" r = self.lds_atomic(self.cu(0), off, f"{spv} %uint {{p}} {self.cu(2)} {self.cu(0)} {cnt}") done = self.current_label_placeholder() self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") old = self.tmp() self.emit(f"{old} = OpPhi %uint {r} {done} {self.cu(0)} {pre}") if self.emulate: read, _ = self.x_round(data=old) fi = self.tmp() self.emit(f"{fi} = OpBitwiseAnd %uint {first} {self.cu(63)}") val = read(fi) else: self.uses_subgroup = self.uses_ballot = True any_act, fi, bal, present, safe_fi, val = (self.tmp() for _ in range(6)) sgl = self.subgroup_lane() self.emit(f"{any_act} = OpLogicalOr %bool {lz} {hz}") self.emit(f"{fi} = OpSelect %uint {any_act} {first} {sgl}") self.emit(f"{bal} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} %true") self.emit(f"{present} = OpGroupNonUniformBallotBitExtract %bool {self.cu(3)} {bal} {fi}") self.emit(f"{safe_fi} = OpSelect %uint {present} {fi} {sgl}") self.emit(f"{val} = OpGroupNonUniformShuffle %uint {self.cu(3)} {old} {safe_fi}") self.dst(a[0], val) LDS_WORDS = {"b32": 1, "b64": 2, "b96": 3, "b128": 4} def lds_pair_byte_offsets(self, op, mods): words = self.LDS_WORDS[op.rsplit("_", 1)[1]] unit = 4 * words * (64 if "st64" in op else 1) return tuple(self.mod_int(mods, key, 0) * unit for key in ("offset0", "offset1")) def lds_op(self, op, a, mods): """LDS (GFX10 DS encoding). Addresses are bytes. offset:N is bytes; read2/write2 offset0/offset1 count data-size units (x64 for st64). Writes and atomics run only in active lanes; results land in VGPRs through dst (inactive lanes unchanged). Sub-dword writes use atomic and/or so neighbouring lanes don't race.""" if self.stage not in ("cs", "ms"): raise Unsupported(op + " outside compute") self.uses_lds = True if op in ("ds_append", "ds_consume"): return self.ds_append(op, a, mods) # wave-wide: before the per-lane EXEC selection below rtn = "_rtn_" in op name = op if op == "ds_wrxchg_rtn_b32" else op.replace("_rtn_", "_") act = self.active_b() lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") off = self.mod_int(mods, "offset", 0) sc, sem = self.cu(2), self.cu(0) if op in ("ds_read_addtid_b32", "ds_write_addtid_b32"): if "gds" in mods or not 0 <= off <= 0xFFFF: raise Unsupported(op + " addressing") if len(a) != 1 or a[0]["k"] != "vgpr" or a[0].get("n", 1) != 1: raise Unsupported(op + " operand") # RDNA2 ISA: LDS_BASE + offset + M0[15:0] + 4 * lane within the wave. # The Workgroup array makes LDS_BASE implicit. m0, base, lane_bytes, addr = (self.tmp() for _ in range(4)) self.emit(f"{m0} = OpLoad %uint %m0") self.emit(f"{base} = OpBitwiseAnd %uint {m0} {self.cu(0xFFFF)}") self.emit(f"{lane_bytes} = OpShiftLeftLogical %uint {self.wave_lane()} {self.cu(2)}") self.emit(f"{addr} = OpIAdd %uint {base} {lane_bytes}") if op == "ds_read_addtid_b32": self.dst(a[0], self.lds_load(addr, off)) else: self.lds_store(addr, off, self.src_u(a[0])) elif op in ("ds_read_b32", "ds_read_b64", "ds_read_b96", "ds_read_b128"): addr = self.src_u(a[1]) for k in range(self.LDS_WORDS[op.rsplit("_", 1)[1]]): v = self.lds_load(addr, off + 4 * k) self.dst({"k": "vgpr", "r": a[0]["r"] + k, "n": 1}, v) elif op in ("ds_write_b32", "ds_write_b64", "ds_write_b96", "ds_write_b128"): addr = self.src_u(a[0]) for k in range(self.LDS_WORDS[op.rsplit("_", 1)[1]]): v = self.load_reg("vgpr", a[1]["r"] + k) self.lds_store(addr, off + 4 * k, v) elif op in ("ds_read2_b32", "ds_read2st64_b32", "ds_write2_b32", "ds_write2st64_b32", "ds_read2_b64", "ds_read2st64_b64", "ds_write2_b64", "ds_write2st64_b64"): # Two elements at ADDR + offset0 * unit and ADDR + offset1 * unit; unit = element size (4 or 8 bytes), # times 64 for st64. A b64 element is two consecutive dwords (low first): read2_b64 fills # v[d:d+3], write2_b64 takes two VGPR pairs. words = 2 if op.endswith("_b64") else 1 offs = self.lds_pair_byte_offsets(op, mods) if op.startswith("ds_read2"): addr = self.src_u(a[1]) vals = [] for o in offs: for w in range(words): vals.append(self.lds_load(addr, o + 4 * w)) for k, v in enumerate(vals): # every load before the first write (vdst may alias vaddr) self.dst({"k": "vgpr", "r": a[0]["r"] + k, "n": 1}, v) else: if len(a) != 3: raise Unsupported(op + " operands") addr = self.src_u(a[0]) for k, o in enumerate(offs): data = a[1 + k] # Validate both operands. Equal offsets store only DATA0 (RDNA2 ISA §10.4.3). duplicate = k == 1 and o == offs[0] if words == 1: v = self.src_u(data) if not duplicate: self.lds_store(addr, o, v) elif data["k"] != "vgpr" or data.get("n") != 2: raise Unsupported(op + " data") elif not duplicate: for w in range(words): v = self.load_reg("vgpr", data["r"] + w) self.lds_store(addr, o + 4 * w, v) elif op in ("ds_read_u16", "ds_read_i16", "ds_read_u8", "ds_read_i8", "ds_read_u16_d16_hi", "ds_read_u16_d16", "ds_read_u8_d16", "ds_read_u8_d16_hi", "ds_read_i8_d16", "ds_read_i8_d16_hi"): bits = 16 if "16" in op.split("_")[2] else 8 addr = self.src_u(a[1]) s1, sh, sh2, w, v = (self.tmp() for _ in range(5)) self.emit(f"{s1} = OpIAdd %uint {addr} {self.cu(off)}") self.emit(f"{sh} = OpShiftLeftLogical %uint {s1} {self.cu(3)}") # byte address -> bit offset self.emit(f"{sh2} = OpBitwiseAnd %uint {sh} {self.cu(31)}") w = self.lds_load(addr, off) if bits == 16: w, sh2 = self.lds_u16_cross_read(addr, off, w, sh2) f = "OpBitFieldSExtract" if op.split("_")[2].startswith("i") else "OpBitFieldUExtract" self.emit(f"{v} = {f} %uint {w} {sh2} {self.cu(bits)}") d = a[0] if "_d16" in op: # u8/i8: v is the 8-bit field extended to 32 bits; the insert keeps only its low 16 bits, so the # i8 sign extension is 8 -> 16 as the ISA says. The other half of the destination is kept. hi = op.endswith("_hi") r = self.tmp() self.emit(f"{r} = OpBitFieldInsert %uint {self.load_reg('vgpr', d['r'])} {v} " f"{self.cu(16 if hi else 0)} {self.cu(16)}") v = r self.dst(d, v) elif op in ("ds_write_b16", "ds_write_b8", "ds_write_b16_d16_hi", "ds_write_b8_d16_hi"): bits = 16 if "b16" in op else 8 addr = self.src_u(a[0]) val = self.src_u(a[1]) if op.endswith("_d16_hi"): hv = self.tmp() self.emit(f"{hv} = OpShiftRightLogical %uint {val} {self.cu(16)}") val = hv s1, sh, sh2, fld, pos, msk, inv = (self.tmp() for _ in range(7)) self.emit(f"{s1} = OpIAdd %uint {addr} {self.cu(off)}") self.emit(f"{sh} = OpShiftLeftLogical %uint {s1} {self.cu(3)}") self.emit(f"{sh2} = OpBitwiseAnd %uint {sh} {self.cu(31)}") self.emit(f"{fld} = OpBitwiseAnd %uint {val} {self.cu((1 << bits) - 1)}") self.emit(f"{pos} = OpShiftLeftLogical %uint {fld} {sh2}") self.emit(f"{msk} = OpShiftLeftLogical %uint {self.cu((1 << bits) - 1)} {sh2}") self.emit(f"{inv} = OpNot %uint {msk}") def sub_dword(p): t1, t2 = self.tmp(), self.tmp() self.emit(f"{t1} = OpAtomicAnd %uint {p} {sc} {sem} {inv}") self.emit(f"{t2} = OpAtomicOr %uint {p} {sc} {sem} {pos}") if bits != 16: self.lds_access(addr, off, sub_dword) else: # A halfword at byte 3 writes its high byte to byte 0 of the next dword. When that byte is past the # allocation the whole write is dropped, as on gfx1036 (the low byte is not written either). cross, ok, nok, drop, keep, both, hb = (self.tmp() for _ in range(7)) k_do, k_end = self.tmp() + "_k", self.tmp() + "_kend" x_do, x_end = self.tmp() + "_x", self.tmp() + "_xend" self.emit(f"{cross} = OpIEqual %bool {sh2} {self.cu(24)}") ok = self.lds_next_in_bounds(addr, off) self.emit(f"{nok} = OpLogicalNot %bool {ok}") self.emit(f"{drop} = OpLogicalAnd %bool {cross} {nok}") self.emit(f"{keep} = OpLogicalNot %bool {drop}") self.emit(f"{both} = OpLogicalAnd %bool {cross} {ok}") self.emit(f"OpSelectionMerge {k_end} None") self.emit(f"OpBranchConditional {keep} {k_do} {k_end}") self.emit(f"{k_do} = OpLabel") self.lds_access(addr, off, sub_dword) self.emit(f"OpBranch {k_end}") self.emit(f"{k_end} = OpLabel") self.emit(f"OpSelectionMerge {x_end} None") self.emit(f"OpBranchConditional {both} {x_do} {x_end}") self.emit(f"{x_do} = OpLabel") self.emit(f"{hb} = OpShiftRightLogical %uint {fld} {self.cu(8)}") def next_byte0(p): t1, t2 = self.tmp(), self.tmp() self.emit(f"{t1} = OpAtomicAnd %uint {p} {sc} {sem} {self.cu(0xFFFFFF00)}") self.emit(f"{t2} = OpAtomicOr %uint {p} {sc} {sem} {hb}") self.lds_access(addr, off + 1, next_byte0, self.lds_cross_bound()) self.emit(f"OpBranch {x_end}") self.emit(f"{x_end} = OpLabel") elif name in self.LDS_ATOMICS: d, ad, dat = (a[0], a[1], a[2]) if rtn else (None, a[0], a[1]) old = self.lds_atomic(self.src_u(ad), off, f"{self.LDS_ATOMICS[name]} %uint {{p}} {sc} {sem} {self.src_u(dat)}") if d is not None: self.dst(d, old) elif op in ("ds_wrxchg2_rtn_b32", "ds_wrxchg2st64_rtn_b32"): # Two atomic exchanges, at ADDR + offset0 * unit and ADDR + offset1 * unit (unit 4 bytes, x64 for st64), # as ds_write2_b32 addresses them: M[A0] = DATA, M[A1] = DATA2; vdst = {old M[A0], old M[A1]}. d = a[0] if d["k"] != "vgpr" or d.get("n") != 2: raise Unsupported(op + " destination") unit = 4 * (64 if "st64" in op else 1) addr = self.src_u(a[1]) olds = [] for k, name in enumerate(("offset0", "offset1")): old = self.lds_atomic(addr, self.mod_int(mods, name, 0) * unit, f"OpAtomicExchange %uint {{p}} {sc} {sem} {self.src_u(a[2 + k])}") olds.append(old) for k, old in enumerate(olds): # both exchanges before the first write (vdst may alias) self.dst({"k": "vgpr", "r": d["r"] + k, "n": 1}, old) elif op in ("ds_wrxchg_rtn_b64", "ds_wrxchg2_rtn_b64", "ds_wrxchg2st64_rtn_b64"): # 64-bit exchanges: M[A] = DATA (two dwords, low first) and vdst gets the old 64 bits. wrxchg_rtn_b64 has # one element at ADDR + offset; the 2 forms have two, at ADDR + offset0/offset1 * 8 (x64 for st64), as # ds_write2_b64 addresses them, and vdst is four VGPRs. Each dword is its own 32-bit exchange, with no Int64 # atomics on Workgroup memory. That can tear: two lanes exchanging into one element at once can leave one's # low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), which a 64-bit exchange never does. The # returned pair is two reads, so another lane's 64-bit op on the same element between them could be seen # half done (as for ds_and/or/xor_b64). two = op != "ds_wrxchg_rtn_b64" d = a[0] if d["k"] != "vgpr" or d.get("n") != (4 if two else 2): raise Unsupported(op + " destination") datas = a[2:4] if two else a[2:3] if any(x["k"] != "vgpr" or x.get("n") != 2 for x in datas): raise Unsupported(op + " data") unit = 8 * (64 if "st64" in op else 1) offs = ([self.mod_int(mods, f, 0) * unit for f in ("offset0", "offset1")] if two else [off]) addr = self.src_u(a[1]) vals = [[self.load_reg("vgpr", x["r"] + w) for w in range(2)] for x in datas] olds = [] for o, val in zip(offs, vals): for w in range(2): old = self.lds_atomic(addr, o + 4 * w, f"OpAtomicExchange %uint {{p}} {sc} {sem} {val[w]}") olds.append(old) for k, old in enumerate(olds): # every exchange before the first write (vdst may alias) self.dst({"k": "vgpr", "r": d["r"] + k, "n": 1}, old) elif name in ("ds_and_b64", "ds_or_b64", "ds_xor_b64"): # M = M op D on a 64-bit LDS element (the dwords at ADDR and ADDR + 4, low first); the _rtn_ form returns # the old 64 bits in a VGPR pair. A bitwise op works on each bit alone, so one 32-bit atomic per dword # leaves exactly the memory a 64-bit atomic would, with no Int64 atomics on Workgroup memory (optional in # Vulkan). The returned pair is two reads, so a 64-bit op from another lane on the same element between # them could be seen half done; the memory result is exact either way. d, ad, dat = (a[0], a[1], a[2]) if rtn else (None, a[0], a[1]) if dat["k"] != "vgpr" or dat.get("n") != 2 or (d is not None and (d["k"] != "vgpr" or d.get("n") != 2)): raise Unsupported(op + " operands") k = {"ds_and_b64": "OpAtomicAnd", "ds_or_b64": "OpAtomicOr", "ds_xor_b64": "OpAtomicXor"}[name] addr = self.src_u(ad) vals = [self.load_reg("vgpr", dat["r"] + w) for w in range(2)] olds = [] for w in range(2): old = self.lds_atomic(addr, off + 4 * w, f"{k} %uint {{p}} {sc} {sem} {vals[w]}") olds.append(old) if d is not None: for w in range(2): self.dst({"k": "vgpr", "r": d["r"] + w, "n": 1}, olds[w]) elif op in ("ds_mskor_b32", "ds_mskor_rtn_b32"): # tmp = M[A]; M[A] = (tmp & ~DATA) | DATA2; the _rtn_ form returns tmp (RDNA2 ISA, DS). As two atomics: # AND with ~DATA (its result is tmp, exactly), then OR with DATA2. The memory ends as the single op # leaves it unless another lane's op on the same dword lands between the two; the returned value is exact. d, ad, msk, dat = (a[0], a[1], a[2], a[3]) if rtn else (None, a[0], a[1], a[2]) addr = self.src_u(ad) inv = self.tmp() m_val, d_val = self.src_u(msk), self.src_u(dat) self.emit(f"{inv} = OpNot %uint {m_val}") def mskor(p): old, _or = self.tmp(), self.tmp() self.emit(f"{old} = OpAtomicAnd %uint {p} {sc} {sem} {inv}") self.emit(f"{_or} = OpAtomicOr %uint {p} {sc} {sem} {d_val}") return old old = self.lds_access(addr, off, mskor) # bounds-checked when lds_bound is set (SHADER-309) if d is not None: self.dst(d, old) elif op in ("ds_add_f32", "ds_add_rtn_f32"): # M = M + DATA as binary32 (RDNA2 ISA, DS_ADD_F32); the _rtn_ form returns the old M. No core SPIR-V atomic # adds floats on Workgroup memory, so this is an OpAtomicCompareExchange loop with an OpFAdd (round to # nearest even, NoContraction): exact under contention, every update one successful exchange of the # value it read. How the LDS adder treats denormals and NaN payloads is not measured: OpFAdd's IEEE # result is what is computed. d, ad, dat = (a[0], a[1], a[2]) if rtn else (None, a[0], a[1]) addr = self.src_u(ad) x = self.tof(self.src_u(dat)) def add_f32_cas(p): lbl_hdr, lbl_cont, lbl_exit = (self.tmp() + t for t in ("_hdr", "_cont", "_exit")) init = self.tmp() self.emit(f"{init} = OpAtomicLoad %uint {p} {sc} {sem}") entry = self.current_label_placeholder() self.emit(f"OpBranch {lbl_hdr}") self.emit(f"{lbl_hdr} = OpLabel") cur, cur_f, sum_f, new, got, done = (self.tmp() for _ in range(6)) self.emit(f"{cur} = OpPhi %uint {init} {entry} {got} {lbl_cont}") self.emit(f"{cur_f} = OpBitcast %float {cur}") self.emit(f"{sum_f} = OpFAdd %float {cur_f} {x}") self.emit(f"{new} = OpBitcast %uint {sum_f}") self.emit(f"{got} = OpAtomicCompareExchange %uint {p} {sc} {sem} {sem} {new} {cur}") self.emit(f"{done} = OpIEqual %bool {got} {cur}") self.emit(f"OpLoopMerge {lbl_exit} {lbl_cont} None") self.emit(f"OpBranchConditional {done} {lbl_exit} {lbl_cont}") self.emit(f"{lbl_cont} = OpLabel") self.emit(f"OpBranch {lbl_hdr}") self.emit(f"{lbl_exit} = OpLabel") return cur if d is not None else None old = self.lds_access(addr, off, add_f32_cas) # bounds-checked when lds_bound is set (SHADER-309) if d is not None: self.dst(d, old) elif op in ("ds_cmpst_rtn_f32", "ds_cmpst_f32"): # ds_cmpst_b32's operands (DATA = the compare value, DATA2 = the new one), compared as binary32. d, ad, cmp_, src = (a[0], a[1], a[2], a[3]) if rtn else (None, a[0], a[1], a[2]) addr = self.src_u(ad) src_u, cmp_u = self.src_u(src), self.src_u(cmp_) def cmpst_f32_cas(p): old_v = self.float_cmpswap_loop(p, src_u, cmp_u, sc) return old_v if d is not None else None old = self.lds_access(addr, off, cmpst_f32_cas) # bounds-checked when lds_bound is set (SHADER-309) if d is not None: self.dst(d, old) elif op in ("ds_cmpst_rtn_b32", "ds_cmpst_b32"): # tmp = M[A]; M[A] = (tmp == DATA) ? DATA2 : tmp; the _rtn_ form returns tmp, ds_cmpst_b32 drops it. d, ad, cmp_, src = (a[0], a[1], a[2], a[3]) if rtn else (None, a[0], a[1], a[2]) old = self.lds_atomic(self.src_u(ad), off, f"OpAtomicCompareExchange %uint {{p}} {sc} {sem} {sem} " f"{self.src_u(src)} {self.src_u(cmp_)}") if d is not None: self.dst(d, old) elif name in ("ds_inc_u32", "ds_dec_u32", "ds_rsub_u32", "ds_min_f32", "ds_max_f32"): # RDNA2 ISA 32-bit DS atomics via Workgroup-scope OpAtomicCompareExchange CAS loop: # ds_inc_u32: M = (M >= DATA) ? 0 : M + 1 (unsigned compare) # ds_dec_u32: M = (M == 0 || M > DATA) ? DATA : M - 1 (unsigned compare) # ds_rsub_u32: M = DATA - M (32-bit wrapping) # ds_min_f32 / ds_max_f32: GLSL.std.450 NMin / NMax (no shader float atomic extension needed) if len(a) != (3 if rtn else 2): raise Unsupported(op + " operands") d, ad, dat = (a[0], a[1], a[2]) if rtn else (None, a[0], a[1]) if dat["k"] != "vgpr" or dat.get("n", 1) != 1 or \ (d is not None and (d["k"] != "vgpr" or d.get("n", 1) != 1)): raise Unsupported(op + " operands") addr = self.src_u(ad) val = self.src_u(dat) val_f = None if name in ("ds_min_f32", "ds_max_f32"): val_f = self.tmp() self.emit(f"{val_f} = OpBitcast %float {val}") def cas(p): entry_lbl = self.current_label_placeholder() lbl_hdr, lbl_cont, lbl_exit = (self.tmp() + s for s in ("_hdr", "_cont", "_exit")) init = self.tmp() self.emit(f"{init} = OpAtomicLoad %uint {p} {sc} {sem}") self.emit(f"OpBranch {lbl_hdr}") self.emit(f"{lbl_hdr} = OpLabel") cur, got = self.tmp(), self.tmp() self.emit(f"{cur} = OpPhi %uint {init} {entry_lbl} {got} {lbl_cont}") if name == "ds_inc_u32": wrap, step, new_u = self.tmp(), self.tmp(), self.tmp() self.emit(f"{wrap} = OpUGreaterThanEqual %bool {cur} {val}") self.emit(f"{step} = OpIAdd %uint {cur} {self.cu(1)}") self.emit(f"{new_u} = OpSelect %uint {wrap} {self.cu(0)} {step}") elif name == "ds_dec_u32": is_z, gt, wrap, step, new_u = (self.tmp() for _ in range(5)) self.emit(f"{is_z} = OpIEqual %bool {cur} {self.cu(0)}") self.emit(f"{gt} = OpUGreaterThan %bool {cur} {val}") self.emit(f"{wrap} = OpLogicalOr %bool {is_z} {gt}") self.emit(f"{step} = OpISub %uint {cur} {self.cu(1)}") self.emit(f"{new_u} = OpSelect %uint {wrap} {val} {step}") elif name == "ds_rsub_u32": new_u = self.tmp() self.emit(f"{new_u} = OpISub %uint {val} {cur}") else: cur_f, new_f, new_u = self.tmp(), self.tmp(), self.tmp() self.emit(f"{cur_f} = OpBitcast %float {cur}") glsl_op = "NMin" if name == "ds_min_f32" else "NMax" self.emit(f"{new_f} = OpExtInst %float %glsl {glsl_op} {cur_f} {val_f}") self.emit(f"{new_u} = OpBitcast %uint {new_f}") done = self.tmp() self.emit(f"{got} = OpAtomicCompareExchange %uint {p} {sc} {sem} {sem} {new_u} {cur}") self.emit(f"{done} = OpIEqual %bool {got} {cur}") self.emit(f"OpLoopMerge {lbl_exit} {lbl_cont} None") self.emit(f"OpBranchConditional {done} {lbl_exit} {lbl_cont}") self.emit(f"{lbl_cont} = OpLabel") self.emit(f"OpBranch {lbl_hdr}") self.emit(f"{lbl_exit} = OpLabel") return cur if d is not None else None old = self.lds_access(addr, off, cas) # bounds-checked when lds_bound is set (SHADER-309) if d is not None: self.dst(d, old) else: raise Unsupported(op) self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") def cl(self, v): """64-bit unsigned constant id (declared with the PhysicalStorageBuffer types).""" v &= 0xFFFFFFFFFFFFFFFF if v not in self.lconsts: self.lconsts[v] = f"%cl{v:x}" self.uses_psb = True return self.lconsts[v] def local_index(self): """LocalInvocationIndex of a compute or mesh shader invocation (thread i of its workgroup): the mesh shader loads the built-in; a compute shader flattens LocalInvocationId with the group size from its header.""" li = self.tmp() if self.stage == "ms": self.emit(f"{li} = OpLoad %uint %local_index") return li lid, x, y, z, lx, t1, t2 = (self.tmp() for _ in range(7)) sx, sy, _ = self.cs["size"] self.emit(f"{lid} = OpLoad %v3uint %local_id") self.emit(f"{x} = OpCompositeExtract %uint {lid} 0") self.emit(f"{y} = OpCompositeExtract %uint {lid} 1") self.emit(f"{z} = OpCompositeExtract %uint {lid} 2") self.emit(f"{t1} = OpIMul %uint {y} {self.cu(sx)}") self.emit(f"{t2} = OpIMul %uint {z} {self.cu(sx * sy)}") self.emit(f"{lx} = OpIAdd %uint {x} {t1}") self.emit(f"{li} = OpIAdd %uint {lx} {t2}") return li def subgroup_lane(self): """This invocation's lane within its Vulkan subgroup (0..31 or 0..63).""" self.uses_subgroup = True r = self.tmp() self.emit(f"{r} = OpLoad %uint %sg_lane") return r @property def wave32_fragment(self): return self.stage == "ps" and not self.wave64 def wave_lane(self): """This invocation's hardware lane within its wave. Compute and mesh shaders: LocalInvocationIndex mod the wave size (exact: thread i of a group is wave i / W, lane i % W). Other stages: the subgroup lane; wave32 pixel shaders use the lane within either 32-lane half.""" lane = self.tmp() if self.stage in ("cs", "ms"): self.emit(f"{lane} = OpBitwiseAnd %uint {self.local_index()} {self.cu(63 if self.wave64 else 31)}") else: subgroup_lane = self.subgroup_lane() if self.wave32_fragment: self.emit(f"{lane} = OpBitwiseAnd %uint {subgroup_lane} {self.cu(31)}") else: self.emit(f"{lane} = OpCopyObject %uint {subgroup_lane}") return lane def wave_source_lane(self, lane): """Map a logical wave32 lane to this fragment invocation's physical subgroup lane.""" if not self.wave32_fragment: return lane half, local, source = (self.tmp() for _ in range(3)) subgroup_lane = self.subgroup_lane() self.emit(f"{half} = OpBitwiseAnd %uint {subgroup_lane} {self.cu(32)}") self.emit(f"{local} = OpBitwiseAnd %uint {lane} {self.cu(31)}") self.emit(f"{source} = OpBitwiseOr %uint {half} {local}") return source def wave32_ballot_word(self, ballot): """Select this logical wave32's 32-bit word from a physical subgroup ballot.""" lo, hi = self.tmp(), self.tmp() half, upper, word = (self.tmp() for _ in range(3)) self.emit(f"{lo} = OpCompositeExtract %uint {ballot} 0") self.emit(f"{hi} = OpCompositeExtract %uint {ballot} 1") lane = self.subgroup_lane() self.emit(f"{half} = OpBitwiseAnd %uint {lane} {self.cu(32)}") self.emit(f"{upper} = OpINotEqual %bool {half} {self.cu(0)}") self.emit(f"{word} = OpSelect %uint {upper} {hi} {lo}") return word def wave32_first_running_lane(self, ballot=None): """The lowest running lane of this wave32 fragment's 32-lane half (0-31): the lane a uniform value is read from. A fixed lane (0 of the half) need not be running: a quad with no covered sample, or helpers a driver leaves out of subgroup operations, read as undefined (SHADER-1016). When the half's ballot word is empty, fall back to this invocation's own logical lane (never lane 0, which may not be launched).""" if ballot is None: ballot = self.tmp() self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} %true") any_, lsb, first = (self.tmp() for _ in range(3)) word = self.wave32_ballot_word(ballot) self.emit(f"{any_} = OpINotEqual %bool {word} {self.cu(0)}") self.emit(f"{lsb} = OpExtInst %uint %glsl FindILsb {word}") self.emit(f"{first} = OpSelect %uint {any_} {lsb} {self.wave_lane()}") self.uses_subgroup = self.uses_ballot = True return first def subgroup_first_running_lane(self, ballot=None): """The lowest running physical lane in the subgroup (0..SubgroupSize-1), or this invocation's own subgroup lane when the ballot is empty. Never falls back to lane 0, which may not be launched in a partial wave.""" if ballot is None: ballot = self.tmp() self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} %true") if self.stage == "vs": lsb, any_ = self.ballot_lsb_by_words(ballot, with_any=True) else: self.uses_vote = True lsb, any_ = self.tmp(), self.tmp() self.emit(f"{lsb} = OpGroupNonUniformBallotFindLSB %uint {self.cu(3)} {ballot}") self.emit(f"{any_} = OpGroupNonUniformAny %bool {self.cu(3)} %true") first = self.tmp() self.emit(f"{first} = OpSelect %uint {any_} {lsb} {self.subgroup_lane()}") self.uses_subgroup = self.uses_ballot = True return first def ballot_lsb_by_words(self, bal, with_any=False): """The lowest set bit of a subgroup ballot, from its four words with FindILsb: the lane OpGroupNonUniformBallotFindLSB gives (a ballot has no bit at or above the subgroup size), without asking for the subgroup size. MoltenVK lowers BallotFindLSB, like the SubgroupSize built-in, to Metal's threads_per_simdgroup input, which a vertex function can't declare (Apple M4, MoltenVK 1.4.2), so vertex shaders use this form. When `with_any` is True, also returns a %bool that is true iff any word is non-zero.""" r = None any_ = None for k in (3, 2, 1, 0): # the lowest non-zero word wins, so it is selected last w, lsb = self.tmp(), self.tmp() self.emit(f"{w} = OpCompositeExtract %uint {bal} {k}") self.emit(f"{lsb} = OpExtInst %uint %glsl FindILsb {w}") if k: at = self.tmp() self.emit(f"{at} = OpIAdd %uint {lsb} {self.cu(32 * k)}") lsb = at nz = self.tmp() if (r is not None or with_any) else None if nz is not None: self.emit(f"{nz} = OpINotEqual %bool {w} {self.cu(0)}") if r is None: r = lsb any_ = nz else: pick = self.tmp() self.emit(f"{pick} = OpSelect %uint {nz} {lsb} {r}") r = pick if with_any: both = self.tmp() self.emit(f"{both} = OpLogicalOr %bool {any_} {nz}") any_ = both return (r, any_) if with_any else r # ---- wave64 emulation (--wave64-emulate) ---- # A wave64 compute or mesh shader runs exact on any subgroup size. Each lane is one invocation as usual, but no # subgroup operation is used: everything a lane needs from the rest of its wave goes through a Workgroup buffer # (%x_buf). The shader runs in rounds (assemble: the emulated scheduler). In a round every wave that isn't done # or waiting at s_barrier runs one segment of its program; then the whole workgroup meets at one OpControlBarrier # in uniform control flow. A cross-lane operation ends a segment after its lane has written its share, and the # code after it runs in the next round, when every lane of the wave has. Buffer layout, L = x_lanes: # [0, 2L) per-lane data, double-buffered by round parity (written in round r, read in r + 1) # [2L, 2L + 6W) two mask words per wave, ORed atomically, 3 slots by round mod 3 (W = waves) # [2L + 6W, +6) per round slot: lanes not done, lanes neither done nor waiting at s_barrier # last word a sink for the stores of lanes that have nothing to reset # A reset store goes to its own word in one lane and to the sink in all the others, and the prologue's zeroing # clamps its index, so several invocations write one word at once. Those stores are OpAtomicStore: with a plain # OpStore that is a data race, harmless here (the word is never read) but reported by GPU-assisted validation in # every emulated shader, where it would bury a real one. def x_sizes(self): w = self.x_lanes // 64 mask = 2 * self.x_lanes sched = mask + 6 * w return w, mask, sched, sched + 6 def x_buf_bytes(self): """Workgroup bytes of %x_buf: the wave64 exchange (emulate) or the barrier-round counts (bar_rounds).""" if self.emulate: return 4 * (self.x_sizes()[3] + 1) return 12 if self.bar_rounds and not self.bar_counts_in_lds() else 0 def bar_counts_in_lds(self, lds_used=None): """SHADER-579: whether the barrier rounds keep their count in a borrowed LDS word instead of %x_buf. Only when the 12 bytes of %x_buf would take the total past 16384 B, the Vulkan minimum maxComputeSharedMemorySize: a full 32 KiB LDS plus %x_buf is 32,780 B, over the 32,768 B of the AMD Windows and Intel drivers. Under that, %x_buf fits on every device and costs no extra barriers (bar_scheduler). lds_used: before any code is generated (fit_shared_memory), whether the shader will use its LDS is not known yet; assume it does.""" used = self.uses_lds if lds_used is None else lds_used return self.bar_rounds and used and 4 * self.lds_dwords + 12 > 16384 def note_pops_word(self, insns): """PS: the SGPR the POPS collision word arrives in (pops_collision_sgpr), seeded at entry. Called once build_meta, whose user_sgpr_reads says which entry values the program reads, is known.""" if self.stage == "ps": reads = {r["sgpr"] for r in (self.build_meta or {}).get("user_sgpr_reads", ())} self.pops_word_sgpr = pops_collision_sgpr(insns, reads) def fit_shared_memory(self): """SHADER-309: a compute shader's Workgroup memory, the LDS array plus %x_buf, must fit in MAX_SHARED_BYTES (#1721: RADV dies on a module 4 bytes over 64 KiB; the device's own limit is the runtime's check). Called before any code is generated. The LDS array is a power of two at least the program's need; when that plus %x_buf is over the limit but the need still fits, the array shrinks to the RSRC2 allocation and its accesses are bounds-checked (lds_access), as hardware checks them. %x_buf is already sized to the workgroup, so when even the allocation does not fit, assemble refuses the shader.""" if not self.cs: return room = (MAX_SHARED_BYTES - (0 if self.bar_counts_in_lds(lds_used=True) else self.x_buf_bytes())) // 4 if self.lds_bound is None and self.lds_dwords > room >= max(self.lds_declared, 1): self.lds_dwords = self.lds_bound = self.lds_declared self.cu(self.lds_declared) def x_split(self): """End the current segment here: the rest of the block runs as a new segment in the next round.""" seg = self.x_seg self.x_seg += 1 self.emit(f"OpStore %pc {self.cu(seg)}") self.x_marks.append((len(self.body), seg)) self.desc_cache.clear() self.sgpr_imm.clear() self._active_ssa = None self.block_label = f"%blk{seg}" self.x_dirty = set() def x_word(self, idx): p, v = self.tmp(), self.tmp() self.emit(f"{p} = OpAccessChain %_ptr_WG_uint_x %x_buf {idx}") self.emit(f"{v} = OpLoad %uint {p}") return v def x_lane_word(self, idx, lane): """The data slot `idx` of lane `lane` (0-63) of this wave, read in an exchange. A lane of a partial last wave that doesn't exist reads as 0 (as a source that isn't running does for ds_swizzle / ds_bpermute on the hardware): the value is selected by the lane's place in the workgroup, not left to the zeroed slot, because RADV (Mesa 26.3.1) turns a store, barrier and load of another lane's slot into a subgroup swizzle that fetches the missing lane's register instead. Full waves read the slot as before.""" v = self.x_word(idx) size = (self.cs or self.ms)["size"] threads = size[0] * size[1] * size[2] if threads >= self.x_lanes: return v if self.x_lanes == 64: at = lane else: at = self.tmp() self.emit(f"{at} = OpIAdd %uint %x_wbase {lane}") ok, r = self.tmp(), self.tmp() self.emit(f"{ok} = OpULessThan %bool {at} {self.cu(threads)}") self.emit(f"{r} = OpSelect %uint {ok} {v} {self.cu(0)}") return r def x_mask_slot(self, it): """Index of the wave's first mask word in the slot of round `it`.""" s, a, b, c = (self.tmp() for _ in range(4)) w, mask, _, _ = self.x_sizes() self.emit(f"{s} = OpUMod %uint {it} {self.cu(3)}") self.emit(f"{a} = OpIMul %uint {s} {self.cu(w)}") self.emit(f"{b} = OpIAdd %uint {a} %x_wave") self.emit(f"{c} = OpIMul %uint {b} {self.cu(2)}") r = self.tmp() self.emit(f"{r} = OpIAdd %uint {c} {self.cu(mask)}") return r def x_order_barrier(self): """Order pending memory/LDS accesses across both halves of an emulated wave64.""" self.uses_barrier = True if self.emulate_inline: self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(0x948)}") self.x_dirty = set() else: self.x_split() def _ensure_x_pre_fn(self, kind): """Build (once per module) the barrier-free helper OpFunction for an inline wave64 x_round pre-barrier step. Outlines the ~20-30 instructions of ring-buffer slot clearing (`sn = (it + 1) % 3`), mask/data slot indexing, and pre-barrier %x_buf store/OpAtomicOr out of %main while keeping OpControlBarrier directly at the callsite in %main. Returns the helper function's SPIR-V id (`%x_pre_{kind}_fn`). """ fn_key = kind fn_name = f"%x_pre_{kind}_fn" if kind in self.x_round_fns: return fn_name w, mask, sched, sink = self.x_sizes() tail_params = {"vote": ["val"], "data": ["val"], "mask": ["b0", "b1"], "both": ["val", "b0", "b1"]}[kind] if w == 1: p_names = ["it", "li"] + tail_params else: p_names = ["it", "li", "lane", "wave"] + tail_params arity = len(p_names) fn_type = self.x_round_fn_types.setdefault(arity, f"%fn_x_pre{arity}") params = {k: f"%xp_{fn_key}_{k}" for k in p_names} p_it, p_li = params["it"], params["li"] saved, self.body = self.body, [] n1, sn = self.tmp(), self.tmp() self.emit(f"{n1} = OpIAdd %uint {p_it} {self.cu(1)}") self.emit(f"{sn} = OpUMod %uint {n1} {self.cu(3)}") if w == 1: m2, m3, m4, ml, m5, m6, mp5, mp6 = (self.tmp() for _ in range(8)) self.emit(f"{m2} = OpIMul %uint {sn} {self.cu(2)}") self.emit(f"{m3} = OpIAdd %uint {m2} {self.cu(mask)}") self.emit(f"{m4} = OpIAdd %uint {m3} {self.cu(1)}") self.emit(f"{ml} = OpIEqual %bool {p_li} {self.cu(0)}") self.emit(f"{m5} = OpSelect %uint {ml} {m3} {self.cu(sink)}") self.emit(f"{m6} = OpSelect %uint {ml} {m4} {self.cu(sink)}") self.emit(f"{mp5} = OpAccessChain %_ptr_WG_uint_x %x_buf {m5}") self.emit(f"OpAtomicStore {mp5} {self.cu(2)} {self.cu(0)} {self.cu(0)}") self.emit(f"{mp6} = OpAccessChain %_ptr_WG_uint_x %x_buf {m6}") self.emit(f"OpAtomicStore {mp6} {self.cu(2)} {self.cu(0)} {self.cu(0)}") else: p_lane, p_wave = params["lane"], params["wave"] m0, m1, m2, m3, m4, ml, m5, m6, mp5, mp6 = (self.tmp() for _ in range(10)) self.emit(f"{m0} = OpIMul %uint {sn} {self.cu(w)}") self.emit(f"{m1} = OpIAdd %uint {m0} {p_wave}") self.emit(f"{m2} = OpIMul %uint {m1} {self.cu(2)}") self.emit(f"{m3} = OpIAdd %uint {m2} {self.cu(mask)}") self.emit(f"{m4} = OpIAdd %uint {m3} {self.cu(1)}") self.emit(f"{ml} = OpIEqual %bool {p_lane} {self.cu(0)}") self.emit(f"{m5} = OpSelect %uint {ml} {m3} {self.cu(sink)}") self.emit(f"{m6} = OpSelect %uint {ml} {m4} {self.cu(sink)}") self.emit(f"{mp5} = OpAccessChain %_ptr_WG_uint_x %x_buf {m5}") self.emit(f"OpAtomicStore {mp5} {self.cu(2)} {self.cu(0)} {self.cu(0)}") self.emit(f"{mp6} = OpAccessChain %_ptr_WG_uint_x %x_buf {m6}") self.emit(f"OpAtomicStore {mp6} {self.cu(2)} {self.cu(0)} {self.cu(0)}") q0, q1, q2, ql, q3, q4, qp3, qp4 = (self.tmp() for _ in range(8)) self.emit(f"{q0} = OpIMul %uint {sn} {self.cu(2)}") self.emit(f"{q1} = OpIAdd %uint {q0} {self.cu(sched)}") self.emit(f"{q2} = OpIAdd %uint {q1} {self.cu(1)}") self.emit(f"{ql} = OpIEqual %bool {p_li} {self.cu(0)}") self.emit(f"{q3} = OpSelect %uint {ql} {q1} {self.cu(sink)}") self.emit(f"{q4} = OpSelect %uint {ql} {q2} {self.cu(sink)}") self.emit(f"{qp3} = OpAccessChain %_ptr_WG_uint_x %x_buf {q3}") self.emit(f"OpAtomicStore {qp3} {self.cu(2)} {self.cu(0)} {self.cu(0)}") self.emit(f"{qp4} = OpAccessChain %_ptr_WG_uint_x %x_buf {q4}") self.emit(f"OpAtomicStore {qp4} {self.cu(2)} {self.cu(0)} {self.cu(0)}") if kind in ("data", "both"): par, data_base, i, p = (self.tmp() for _ in range(4)) self.emit(f"{par} = OpBitwiseAnd %uint {p_it} {self.cu(1)}") self.emit(f"{data_base} = OpIMul %uint {par} {self.cu(self.x_lanes)}") self.emit(f"{i} = OpIAdd %uint {data_base} {p_li}") self.emit(f"{p} = OpAccessChain %_ptr_WG_uint_x %x_buf {i}") self.emit(f"OpStore {p} {params['val']}") ret_id = data_base if kind in ("vote", "mask", "both"): if w == 1: s, c, rm = self.tmp(), self.tmp(), self.tmp() self.emit(f"{s} = OpUMod %uint {p_it} {self.cu(3)}") self.emit(f"{c} = OpIMul %uint {s} {self.cu(2)}") self.emit(f"{rm} = OpIAdd %uint {c} {self.cu(mask)}") else: s, a, b, c, rm = (self.tmp() for _ in range(5)) self.emit(f"{s} = OpUMod %uint {p_it} {self.cu(3)}") self.emit(f"{a} = OpIMul %uint {s} {self.cu(w)}") self.emit(f"{b} = OpIAdd %uint {a} {params['wave']}") self.emit(f"{c} = OpIMul %uint {b} {self.cu(2)}") self.emit(f"{rm} = OpIAdd %uint {c} {self.cu(mask)}") p0, old0 = self.tmp(), self.tmp() self.emit(f"{p0} = OpAccessChain %_ptr_WG_uint_x %x_buf {rm}") self.emit(f"{old0} = OpAtomicOr %uint {p0} {self.cu(2)} {self.cu(0)} {params['b0' if kind in ('mask', 'both') else 'val']}") if kind in ("mask", "both"): rm1, p1, old1 = self.tmp(), self.tmp(), self.tmp() self.emit(f"{rm1} = OpIAdd %uint {rm} {self.cu(1)}") self.emit(f"{p1} = OpAccessChain %_ptr_WG_uint_x %x_buf {rm1}") self.emit(f"{old1} = OpAtomicOr %uint {p1} {self.cu(2)} {self.cu(0)} {params['b1']}") ret_id = rm lines, self.body = self.body, saved self.x_round_fns[fn_key] = ( [f"{fn_name} = OpFunction %uint None {fn_type}"] + [f"{params[k]} = OpFunctionParameter %uint" for k in p_names] + [f"{fn_name}_entry = OpLabel"] + lines + [f" OpReturnValue {ret_id}", "OpFunctionEnd"] ) return fn_name def x_round(self, data=None, bits=None): """One exchange: this lane's uint `data` goes to its slot, `bits` (lo, hi; None = nothing) are ORed into the wave's two mask words. Returns (read, (lo, hi)): read(lane) loads `data` of a lane (0-63) of this wave, and (lo, hi) is the OR over all 64 lanes. In round-loop mode both are valid in the next segment; in inline structured mode (`emulate_inline`) the barrier runs directly in place with zero x_split.""" if self.emulate_inline: w, _, _, _ = self.x_sizes() it, n1 = self.tmp(), self.tmp() self.emit(f"{it} = OpLoad %uint %x_it") if data is not None and bits is None: fn = self._ensure_x_pre_fn("data") args = f"{it} %x_li {data}" if w == 1 else f"{it} %x_li %x_lane %x_wave {data}" data_base = self.tmp() self.emit(f"{data_base} = OpFunctionCall %uint {fn} {args}") self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(0x948)}") self.emit(f"{n1} = OpIAdd %uint {it} {self.cu(1)}") self.emit(f"OpStore %x_it {n1}") self.x_dirty = set() def read(lane): if w == 1: j = self.tmp() self.emit(f"{j} = OpIAdd %uint {data_base} {lane}") return self.x_lane_word(j, lane) i, j = self.tmp(), self.tmp() self.emit(f"{i} = OpIAdd %uint {data_base} %x_wbase") self.emit(f"{j} = OpIAdd %uint {i} {lane}") return self.x_lane_word(j, lane) return read, None if data is None and bits is not None and bits[0] is not None and bits[1] is None: fn = self._ensure_x_pre_fn("vote") args = f"{it} %x_li {bits[0]}" if w == 1 else f"{it} %x_li %x_lane %x_wave {bits[0]}" rm = self.tmp() self.emit(f"{rm} = OpFunctionCall %uint {fn} {args}") self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(0x948)}") self.emit(f"{n1} = OpIAdd %uint {it} {self.cu(1)}") self.emit(f"OpStore %x_it {n1}") self.x_dirty = set() return None, (self.x_word(rm), None) if data is None and bits is not None: fn = self._ensure_x_pre_fn("mask") b0 = bits[0] if bits[0] is not None else self.cu(0) b1 = bits[1] if bits[1] is not None else self.cu(0) args = f"{it} %x_li {b0} {b1}" if w == 1 else f"{it} %x_li %x_lane %x_wave {b0} {b1}" rm, hi_i = self.tmp(), self.tmp() self.emit(f"{rm} = OpFunctionCall %uint {fn} {args}") self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(0x948)}") self.emit(f"{n1} = OpIAdd %uint {it} {self.cu(1)}") self.emit(f"OpStore %x_it {n1}") self.x_dirty = set() self.emit(f"{hi_i} = OpIAdd %uint {rm} {self.cu(1)}") return None, (self.x_word(rm), self.x_word(hi_i)) fn = self._ensure_x_pre_fn("both") b0 = bits[0] if bits[0] is not None else self.cu(0) b1 = bits[1] if bits[1] is not None else self.cu(0) args = f"{it} %x_li {data} {b0} {b1}" if w == 1 else f"{it} %x_li %x_lane %x_wave {data} {b0} {b1}" rm, hi_i = self.tmp(), self.tmp() self.emit(f"{rm} = OpFunctionCall %uint {fn} {args}") self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(0x948)}") self.emit(f"{n1} = OpIAdd %uint {it} {self.cu(1)}") self.emit(f"OpStore %x_it {n1}") self.x_dirty = set() self.emit(f"{hi_i} = OpIAdd %uint {rm} {self.cu(1)}") res = (self.x_word(rm), self.x_word(hi_i)) def read(lane): par2, base = self.tmp(), self.tmp() self.emit(f"{par2} = OpBitwiseAnd %uint {it} {self.cu(1)}") self.emit(f"{base} = OpIMul %uint {par2} {self.cu(self.x_lanes)}") if w == 1: j = self.tmp() self.emit(f"{j} = OpIAdd %uint {base} {lane}") return self.x_lane_word(j, lane) i, j = self.tmp(), self.tmp() self.emit(f"{i} = OpIAdd %uint {base} %x_wbase") self.emit(f"{j} = OpIAdd %uint {i} {lane}") return self.x_lane_word(j, lane) return read, res it = self.tmp() self.emit(f"{it} = OpLoad %uint %x_it") if data is not None: par, base, i, p = (self.tmp() for _ in range(4)) self.emit(f"{par} = OpBitwiseAnd %uint {it} {self.cu(1)}") self.emit(f"{base} = OpIMul %uint {par} {self.cu(self.x_lanes)}") self.emit(f"{i} = OpIAdd %uint {base} %x_li") self.emit(f"{p} = OpAccessChain %_ptr_WG_uint_x %x_buf {i}") self.emit(f"OpStore {p} {data}") if bits is not None: m = self.x_mask_slot(it) for k, b in enumerate(bits): if b is None: continue i, p, old = self.tmp(), self.tmp(), self.tmp() self.emit(f"{i} = OpIAdd %uint {m} {self.cu(k)}") self.emit(f"{p} = OpAccessChain %_ptr_WG_uint_x %x_buf {i}") self.emit(f"{old} = OpAtomicOr %uint {p} {self.cu(2)} {self.cu(0)} {b}") self.x_split() now, prev = self.tmp(), self.tmp() self.emit(f"{now} = OpLoad %uint %x_it") self.emit(f"{prev} = OpISub %uint {now} {self.cu(1)}") res = None if bits is not None: m = self.x_mask_slot(prev) hi_i = self.tmp() self.emit(f"{hi_i} = OpIAdd %uint {m} {self.cu(1)}") res = (self.x_word(m), self.x_word(hi_i)) def read(lane): par, base, i = self.tmp(), self.tmp(), self.tmp() self.emit(f"{par} = OpBitwiseAnd %uint {prev} {self.cu(1)}") self.emit(f"{base} = OpIMul %uint {par} {self.cu(self.x_lanes)}") self.emit(f"{i} = OpIAdd %uint {base} %x_wbase") j = self.tmp() self.emit(f"{j} = OpIAdd %uint {i} {lane}") return self.x_lane_word(j, lane) return read, res def x_memory_order(self, op): """On hardware a wave's lanes run each instruction together: every lane's access of one instruction comes before every lane's access of the next. Two halves of an emulated wave can be in different subgroups, so an access that conflicts with an earlier one of the same segment (read after write, write after read, write after write, on the same memory) waits for the next round, whose barrier orders the memory. A scalar load (s_load / s_buffer_load) is a read of the same memory as the vector ops: on hardware every lane's earlier store is done before the wave issues it, but here the other half could load before this half has stored (#1587: valu_fuzz --family mem --emulate, lanes 32-63 read the fill pattern). Image samples, gathers, and BVH ray-intersection reads also count as memory reads so they order against earlier/later stores.""" if op in ("ds_swizzle_b32", "ds_bpermute_b32", "ds_permute_b32", "ds_nop"): return if op.startswith("ds_"): kind = "lds" elif op.startswith(("buffer_", "tbuffer_", "global_", "flat_", "image_load", "image_store", "image_atomic", "image_sample", "image_gather4", "image_bvh", "s_load_", "s_buffer_load_")): kind = "mem" else: return store = "store" in op or op.startswith("ds_write") reads = not store writes = store or "atomic" in op or (kind == "lds" and not op.startswith("ds_read")) # In a fold that at most one lane of the wave runs, that lane's own order is the wave's. if not self.x_one_lane and ((kind, "w") in self.x_dirty or (writes and (kind, "r") in self.x_dirty)): self.x_order_barrier() if reads: self.x_dirty.add((kind, "r")) if writes: self.x_dirty.add((kind, "w")) def g_vote(self, r, kind, b): """r = OpGroupNonUniform{Any,All} of bool b over the wave.""" if not self.emulate: if self.wave32_fragment: if kind == "All": inv = self.tmp() self.emit(f"{inv} = OpLogicalNot %bool {b}") b = inv ballot, any_ = self.tmp(), self.tmp() self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} {b}") word = self.wave32_ballot_word(ballot) self.emit(f"{any_} = OpINotEqual %bool {word} {self.cu(0)}") if kind == "Any": self.emit(f"{r} = OpCopyObject %bool {any_}") else: self.emit(f"{r} = OpLogicalNot %bool {any_}") self.uses_subgroup = self.uses_ballot = True return self.emit(f"{r} = OpGroupNonUniform{kind} %bool {self.cu(3)} {b}") return if kind == "All": nb = self.tmp() self.emit(f"{nb} = OpLogicalNot %bool {b}") b = nb bit = self.tmp() self.emit(f"{bit} = OpSelect %uint {b} {self.cu(1)} {self.cu(0)}") lo = self.x_round(bits=(bit, None))[1][0] self.emit(f"{r} = {'OpIEqual' if kind == 'All' else 'OpINotEqual'} %bool {lo} {self.cu(0)}") def g_shuffle(self, r, v, src): """r = v of lane src of this wave (OpGroupNonUniformShuffle, or any emulated lane 0-63).""" if not self.emulate: self.emit(f"{r} = OpGroupNonUniformShuffle %uint %c3 {v} {self.wave_source_lane(src)}") return read = self.x_round(data=v)[0] self.emit(f"{r} = OpCopyObject %uint {read(src)}") def ds_quad_swizzle(self, dst: dict, data: str, qmap: tuple) -> None: """Quad-local ds_swizzle_b32 in a fragment shader: lower via OpGroupNonUniformQuadBroadcast / OpGroupNonUniformQuadSwap so 2x2 helper invocations participate (Vulkan excludes helper lanes from OpGroupNonUniformBallot/Shuffle on AMD RADV, zeroing derivative neighbors, whereas Quad ops include them).""" self.uses_subgroup = self.uses_quad = True value = self.tmp() self.emit(f"{value} = OpSelect %uint {self.active_b()} {data} {self.cu(0)}") if qmap == (0, 1, 2, 3): result = value elif len(set(qmap)) == 1: result = self.tmp() self.emit(f"{result} = OpGroupNonUniformQuadBroadcast %uint {self.cu(3)} {value} {self.cu(qmap[0])}") elif len({qmap[i] ^ i for i in range(4)}) == 1: d = qmap[0] result = self.tmp() self.emit(f"{result} = OpGroupNonUniformQuadSwap %uint {self.cu(3)} {value} {self.cu(d - 1)}") else: diffs = {qmap[i] ^ i for i in range(4)} lane = self.tmp() self.sub_lane(lane) q = self.tmp() self.emit(f"{q} = OpBitwiseAnd %uint {lane} {self.cu(3)}") if len(diffs) == 2 and 0 in diffs: # One swap direction plus self (covers (0,1,0,1), (2,3,2,3), (0,0,2,2), (1,1,3,3) in one quad op). d = next(x for x in diffs if x != 0) sw = self.tmp() self.emit(f"{sw} = OpGroupNonUniformQuadSwap %uint {self.cu(3)} {value} {self.cu(d - 1)}") swapped = {i for i in range(4) if qmap[i] != i} if swapped in ({2, 3}, {0, 1}): bit, cond = self.tmp(), self.tmp() self.emit(f"{bit} = OpBitwiseAnd %uint {q} {self.cu(2)}") op_cmp = "OpINotEqual" if swapped == {2, 3} else "OpIEqual" self.emit(f"{cond} = {op_cmp} %bool {bit} {self.cu(0)}") elif swapped in ({1, 3}, {0, 2}): bit, cond = self.tmp(), self.tmp() self.emit(f"{bit} = OpBitwiseAnd %uint {q} {self.cu(1)}") op_cmp = "OpINotEqual" if swapped == {1, 3} else "OpIEqual" self.emit(f"{cond} = {op_cmp} %bool {bit} {self.cu(0)}") else: cond = None for i in sorted(swapped): eq = self.tmp() self.emit(f"{eq} = OpIEqual %bool {q} {self.cu(i)}") if cond is None: cond = eq else: nxt = self.tmp() self.emit(f"{nxt} = OpLogicalOr %bool {cond} {eq}") cond = nxt result = self.tmp() self.emit(f"{result} = OpSelect %uint {cond} {sw} {value}") else: bcast = {} for k in sorted(set(qmap)): b = self.tmp() self.emit(f"{b} = OpGroupNonUniformQuadBroadcast %uint {self.cu(3)} {value} {self.cu(k)}") bcast[k] = b pick = bcast[qmap[0]] for i in (1, 2, 3): eq, nxt = self.tmp(), self.tmp() self.emit(f"{eq} = OpIEqual %bool {q} {self.cu(i)}") self.emit(f"{nxt} = OpSelect %uint {eq} {bcast[qmap[i]]} {pick}") pick = nxt result = pick self.dst(dst, result, eager=True) def ds_lane_read(self, dst: dict, data: str, src: str, lane: str) -> None: """DS swizzle and backward permute read zero from an inactive or absent source lane.""" value, result = self.tmp(), self.tmp() self.emit(f"{value} = OpSelect %uint {self.active_b()} {data} {self.cu(0)}") if self.emulate: self.g_shuffle(result, value, src) else: # Redirect absent source lanes before the shuffle: even a masked undefined result is undefined. ballot, present, safe_phys, shuffled, mask = (self.tmp() for _ in range(5)) physical_src = self.wave_source_lane(src) physical_self = self.subgroup_lane() self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal %c3 %true") self.emit(f"{present} = OpGroupNonUniformBallotBitExtract %bool %c3 {ballot} {physical_src}") self.emit(f"{safe_phys} = OpSelect %uint {present} {physical_src} {physical_self}") self.emit(f"{shuffled} = OpGroupNonUniformShuffle %uint %c3 {value} {safe_phys}") self.emit(f"{mask} = OpSelect %uint {present} {self.cu(0xFFFFFFFF)} {self.cu(0)}") self.emit(f"{result} = OpBitwiseAnd %uint {shuffled} {mask}") self.uses_subgroup = self.uses_ballot = True # Bitwise masks keep MSL from placing the ballot and shuffle in a short-circuiting ternary. self.dst(dst, result, eager=not self.emulate) def ds_permute(self, a, mods): """ds_permute_b32 vD, vAddr, vData offset:N, the forward (scatter) permute: every source lane that is on in EXEC sends vData to lane ((vAddr + offset) / 4) mod 32 of its own half (as ds_bpermute_b32, RDNA ISA 10.4.4: a wave64 runs it as two wave32s); a destination lane nobody sends to gets 0; EXEC gates only the destination write. Several sources to one lane: the highest-numbered source wins (ISA: "the final value is not predictable but will be the value from one of the writers"). Vulkan has no subgroup scatter, so each destination lane scans the 32 source lanes of its half in order and keeps the last one that targets it. Each source lane publishes its target plus one (0 = off in EXEC, so a lane that doesn't exist in a partial wave reads as "no target" as well).""" d, ad, dat = a[0], self.src_u(a[1]), self.src_u(a[2]) off = self.mod_int(mods, "offset", 0) s1, sh, dl, dp, tp = (self.tmp() for _ in range(5)) self.emit(f"{s1} = OpIAdd %uint {ad} {self.cu(off)}") self.emit(f"{sh} = OpShiftRightLogical %uint {s1} {self.cu(2)}") self.emit(f"{dl} = OpBitwiseAnd %uint {sh} {self.cu(31)}") self.emit(f"{dp} = OpIAdd %uint {dl} {self.cu(1)}") self.emit(f"{tp} = OpSelect %uint {self.active_b()} {dp} {self.cu(0)}") if self.emulate: # Round 1 publishes the targets; the next segment finds each lane's winning source and parks it in # %x_perm; round 2 publishes the data; the segment after that reads the winner's data. self.uses_perm = True read = self.x_round(data=tp)[0] lane, rl, mine, half, win = (self.tmp() for _ in range(5)) self.emit(f"{lane} = OpCopyObject %uint {self.wave_lane()}") self.emit(f"{rl} = OpBitwiseAnd %uint {lane} {self.cu(31)}") self.emit(f"{mine} = OpIAdd %uint {rl} {self.cu(1)}") self.emit(f"{half} = OpBitwiseAnd %uint {lane} {self.cu(32)}") acc = self.cu(32) for j in range(32): src, v, hit, nxt = (self.tmp() for _ in range(4)) self.emit(f"{src} = OpBitwiseOr %uint {half} {self.cu(j)}") self.emit(f"{v} = OpCopyObject %uint {read(src)}") self.emit(f"{hit} = OpIEqual %bool {v} {mine}") self.emit(f"{nxt} = OpSelect %uint {hit} {self.cu(j)} {acc}") acc = nxt self.emit(f"OpStore %x_perm {acc}") dat2 = self.src_u(a[2]) read2 = self.x_round(data=dat2)[0] w, ok, half2, src, got, r, lane2 = (self.tmp() for _ in range(7)) self.emit(f"{w} = OpLoad %uint %x_perm") self.emit(f"{ok} = OpULessThan %bool {w} {self.cu(32)}") self.emit(f"{lane2} = OpCopyObject %uint {self.wave_lane()}") self.emit(f"{half2} = OpBitwiseAnd %uint {lane2} {self.cu(32)}") wc = self.tmp() self.emit(f"{wc} = OpBitwiseAnd %uint {w} {self.cu(31)}") self.emit(f"{src} = OpBitwiseOr %uint {half2} {wc}") self.emit(f"{got} = OpCopyObject %uint {read2(src)}") self.emit(f"{r} = OpSelect %uint {ok} {got} {self.cu(0)}") self.dst(d, r) return self.uses_subgroup = self.uses_ballot = True lane, rl, mine, half = (self.tmp() for _ in range(4)) self.emit(f"{lane} = OpCopyObject %uint {self.wave_lane()}") self.emit(f"{rl} = OpBitwiseAnd %uint {lane} {self.cu(31)}") self.emit(f"{mine} = OpIAdd %uint {rl} {self.cu(1)}") sgl = self.subgroup_lane() if self.wave64 or self.wave32_fragment: self.emit(f"{half} = OpBitwiseAnd %uint {sgl} {self.cu(32)}") self_lane = sgl bal = self.tmp() self.emit(f"{bal} = OpGroupNonUniformBallot %v4uint_bal %c3 %true") acc = self.cu(0) for j in range(32): src = self.cu(j) if self.wave64 or self.wave32_fragment: src = self.tmp() self.emit(f"{src} = OpBitwiseOr %uint {half} {self.cu(j)}") ex, safe_src, shv, v, shd, hit, nxt = (self.tmp() for _ in range(7)) # Redirect absent source lanes before the shuffle: even a masked undefined result is undefined. self.emit(f"{ex} = OpGroupNonUniformBallotBitExtract %bool %c3 {bal} {src}") self.emit(f"{safe_src} = OpSelect %uint {ex} {src} {self_lane}") # Both shuffles are stored (SHADER-PERMUTE-EAGER). Each is used once, and so is every link of the # chain, so SPIRV-Cross would write the 32 steps as one nested ternary, hit31 ? data31 : (hit30 ? ...), # under the EXEC ternary of the write: a lane that takes an outer arm, or is off, would run none of the # shuffles inside it, and the lanes that read from it get 0 or a stale word (Apple M5, MoltenVK 1.4.2). self.emit(f"{shv} = OpGroupNonUniformShuffle %uint %c3 {tp} {safe_src}") shv = self.eager("%uint", shv) self.emit(f"{v} = OpSelect %uint {ex} {shv} {self.cu(0)}") self.emit(f"{shd} = OpGroupNonUniformShuffle %uint %c3 {dat} {safe_src}") shd = self.eager("%uint", shd) self.emit(f"{hit} = OpIEqual %bool {v} {mine}") self.emit(f"{nxt} = OpSelect %uint {hit} {shd} {acc}") acc = nxt self.dst(d, acc) def sub_lane(self, r): """r = the lane the subgroup shuffles above index: the subgroup lane, or the wave lane when emulated.""" if self.emulate or self.wave32_fragment: self.emit(f"{r} = OpCopyObject %uint {self.wave_lane()}") else: self.emit(f"{r} = OpLoad %uint %sg_lane") def exec_half_write(self, half, val, const=None): """Write one 32-bit half of EXEC. In the per-lane model a lane is active iff its bit is set. A constant sets each lane from its own bit; a register value (mask representation: all-ones / zero per lane) sets the lanes of that half from their own copy. Lanes of the other half are unchanged.""" lane = self.wave_lane() rel, inh, bit, on, cur, new = (self.tmp() for _ in range(6)) if half == 0: self.emit(f"{inh} = OpULessThan %bool {lane} {self.cu(32)}") self.emit(f"{rel} = OpCopyObject %uint {lane}") else: self.emit(f"{inh} = OpUGreaterThanEqual %bool {lane} {self.cu(32)}") self.emit(f"{rel} = OpISub %uint {lane} {self.cu(32)}") if const is not None: r31 = self.tmp() self.emit(f"{r31} = OpBitwiseAnd %uint {rel} {self.cu(31)}") # Shift and mask, not OpBitFieldUExtract: Intel's Windows driver (UHD 770 / Xe-LP, 32.0.101.6129; # also seen on Xe-LPG) extracts from a constant that fits in 16 bits with the offset taken mod 16, so # exec_lo = 0xffff turned on all 32 lanes. GPU-checked with cs_exec_const.asm. shr = self.tmp() self.emit(f"{shr} = OpShiftRightLogical %uint {self.cu(const & 0xFFFFFFFF)} {r31}") self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") self.emit(f"{on} = OpINotEqual %bool {bit} {self.cu(0)}") else: self.emit(f"{on} = OpINotEqual %bool {val} {self.cu(0)}") self.emit(f"{cur} = OpLoad %bool %active") self.emit(f"{new} = OpSelect %bool {inh} {on} {cur}") self.emit(f"OpStore %active {new}") self.uses_active = True def set_scc(self, b): """SCC = bool id (1/0).""" r = self.tmp() self.emit(f"{r} = OpSelect %uint {b} {self.cu(1)} {self.cu(0)}") self.emit(f"OpStore %scc {r}") def scc_nonzero(self, v): self.set_scc(self.tmp_bool_nz(v)) def scc_add_overflow(self, x, y, r, sub=False): """Signed overflow of r = x + y (or x - y): SCC for s_add_i32 / s_sub_i32 / s_addk_i32.""" a1, a2, m, sh = self.tmp(), self.tmp(), self.tmp(), self.tmp() if sub: self.emit(f"{a1} = OpBitwiseXor %uint {x} {y}") self.emit(f"{a2} = OpBitwiseXor %uint {x} {r}") else: self.emit(f"{a1} = OpBitwiseXor %uint {x} {r}") self.emit(f"{a2} = OpBitwiseXor %uint {y} {r}") self.emit(f"{m} = OpBitwiseAnd %uint {a1} {a2}") self.emit(f"{sh} = OpShiftRightLogical %uint {m} {self.cu(31)}") self.scc_nonzero(sh) def bfe_width(self, off, wid): """A bitfield-extract width cut to 32 - off (off in 0-31): SPIR-V leaves offset + count > 32 undefined. The field then runs to bit 31: gfx1150 hardware does this for s_bfe (4000 random control words, salu_diff --oracle hw), and LLVM's v_bfe fold (constantFoldBFE in AMDGPUISelLowering.cpp, 5-bit width) is analogous: Src0 >> Offset, logical for the unsigned and arithmetic for the signed extract. On RDNA2 v_bfe_u32/v_bfe_i32 do the same (gfx1036, wave32 and wave64, tools/int_hw_probe.py group valu_bfe_past31), and s_bfe too (gfx1035, SHADER-137).""" room, fits, w = self.tmp(), self.tmp(), self.tmp() self.emit(f"{room} = OpISub %uint {self.cu(32)} {off}") self.emit(f"{fits} = OpULessThan %bool {wid} {room}") self.emit(f"{w} = OpSelect %uint {fits} {wid} {room}") return w def tmp_bool_nz(self, v): b = self.tmp() self.emit(f"{b} = OpINotEqual %bool {v} {self.cu(0)}") return b def scc_from_mask(self, v): """SCC after a lane-mask instruction: 1 if the wave's mask is non-zero. One invocation holds one lane's bit, so that is a vote across the subgroup, as for s_cbranch_vccz. Taken per lane, the lanes of one wave could follow different s_cbranch_scc paths, which a hardware wave never does: it has one SCC.""" if not self.cur_scc_live: return any_, z = self.tmp(), self.tmp() self.g_vote(any_, "Any", self.tmp_bool_nz(v)) self.uses_vote = True self.emit(f"{z} = OpSelect %uint {any_} {self.cu(1)} {self.cu(0)}") self.emit(f"OpStore %scc {z}") MASK_SOP2_B32 = ("s_and_b32", "s_or_b32", "s_xor_b32", "s_andn2_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32", "s_xnor_b32", "s_cselect_b32") @staticmethod def _maskable_b32(x): return x["k"] in ("sgpr", "imm") or ( x["k"] == "special" and (x.get("t", "").startswith(("exec", "vcc")) or x.get("t") in ("null", "m0", "scc", "src_scc")) ) def _mask_b32_dst_half(self, d, srcs): """For a 32-bit bitwise SALU op (s_not_b32 / MASK_SOP2_B32), return (to_mask_dst, half) where to_mask_dst is True when d is EXEC or VCC (each lane holds its own bit) and half is 'lo'/'hi' in wave64 or None.""" if d["k"] != "special": return False, None t = d.get("t", "") if not self.wave64: return t in ("exec_lo", "vcc_lo", "exec", "vcc"), None if t in ("exec_lo", "exec_hi"): return True, "hi" if t == "exec_hi" else "lo" if t in ("vcc_lo", "vcc_hi") and ("vcc" in self.cur_masks or any(self.holds_lane_mask(s) for s in srcs)): return True, "hi" if t == "vcc_hi" else "lo" return False, None def _mask_b32_src(self, s, dst_half): """Read one 32-bit source for a mask-writing bitwise SALU op (wave32, or wave64 half `dst_half`).""" if self.wave64 and dst_half is not None and self.holds_lane_mask(s): sh = self.mask_half(s) if sh is not None and sh != dst_half: # Opposite wave64 half (e.g. exec_lo <- vcc_hi): collect that half's 32-bit mask and take bit lane&31. lo, hi = self.wave_mask(s) word = hi if sh == "hi" else lo lane = self.wave_lane() s5, shr, bit, r = (self.tmp() for _ in range(4)) self.emit(f"{s5} = OpBitwiseAnd %uint {lane} {self.cu(31)}") self.emit(f"{shr} = OpShiftRightLogical %uint {word} {s5}") self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") return r return self.mask_src(s, wide=False) def _store_b32_mask_dst(self, d, val, to_mask_dst, dst_half): """Store a 32-bit bitwise SALU result, preserving the untouched half of EXEC/VCC in wave64.""" if to_mask_dst and self.wave64 and d["k"] == "special" and d.get("t") in ("vcc_lo", "vcc_hi"): self.put_mask(d, val, dst_half) if d["t"] == "vcc_hi": self.emit(f"OpStore %vcc_hi {val}") return self.dst(d, val) def sop2_b32_srcs(self, op, a): """The two sources of a 32-bit SOP2. A bitwise op (or s_cselect) that writes EXEC / VCC reads both through _mask_b32_src / mask_src (in wave32 and on either half of a wave64 mask), so a constant, inline or held in an SGPR, gives each lane its own bit; a mask is read as before. Until 2026-11-22 a constant was used whole: `s_and_b32 exec_lo, exec_lo, 0xff00` (or the same constant in an SGPR) left every lane of EXEC on. An SGPR destination stays a data read, because lane_masks.py classifies it as data when the other operand is a constant (s_and_b32 s20, exec_lo, 1; s_bcnt1_i32_b32 s21, s20 gave 32 and 0 instead of 1, #1792).""" if op in self.MASK_SOP2_B32 and len(a) >= 3: to_mask, dst_half = self._mask_b32_dst_half(a[0], a[1:3]) if to_mask and all(self._maskable_b32(x) for x in a[1:3]): return self._mask_b32_src(a[1], dst_half), self._mask_b32_src(a[2], dst_half) return self.src_u(a[1]), self.src_u(a[2]) def scc_logic(self, a, r): """SCC of a 32-bit bitwise SALU op (s_not_b32 and s_and/or/xor/andn2/orn2/nand/nor/xnor_b32): D != 0. When the op works on a lane mask (writes EXEC/VCC or reads a lane-mask operand), D is the wave's mask (or one 32-lane half of it in wave64), so SCC is a subgroup Any vote over the wave (wave32) or that half (wave64, scc_any_half) rather than this lane's own bit.""" srcs = a[1:] to_mask_dst, dst_half = self._mask_b32_dst_half(a[0], srcs) mask_srcs = [s for s in srcs if self.holds_lane_mask(s)] if to_mask_dst: self.scc_any_half(r, dst_half) elif mask_srcs: if not self.wave64: self.scc_from_mask(r) else: halves = {self.mask_half(s) for s in mask_srcs} - {None} if len(halves) == 1: self.scc_any_half(r, halves.pop()) elif not halves: self.scc_from_mask(r) else: self.scc_nonzero(r) else: self.scc_nonzero(r) SGPRS = 128 # size of the %sgpr array without the parking slots def park_masks(self, blocks): """Run the lane-mask analysis and give every VGPR lane a mask is fetched back from a slot of its own, after the real registers in the %sgpr array (the array grows by as many).""" wave64_emulate_opt.mark_vcc_data_moves(*blocks) self.lane_masks, self.mask_writes, self.lane_either = lane_masks.analyse(*blocks, include_either=True, wave64=self.wave64) # lane_masks merges a mask on one path with plain data on another by dropping the register, # so "not in cur_masks" does not prove it is data on every path. Keep a conservative set. self.ever_mask = {r for m in self.lane_masks.values() for r in m if isinstance(r, int)} slots = lane_masks.parked(blocks[0], self.lane_masks, wave64=self.wave64) self.scalar_spills = set(lane_masks.scalar_spills(blocks[0], blocks[1], wave64=self.wave64)) self.spill_readlanes, spill_read_slots = lane_masks.definite_spill_reads( blocks[0], blocks[1], wave64=self.wave64 ) all_slots = sorted(set(slots) | self.scalar_spills | set(spill_read_slots)) self.parked = {slot: self.SGPRS + i for i, slot in enumerate(all_slots)} # Instructions whose lane-mask data read will gather the wave's mask word (src_u's # lane_mask_word path) are cross-lane exchanges for the # wave64-emulation planner: it must not fold them into a lane-local region or schedule # a barrier beside them (wave64_emulate_opt checks ins["mask_words"]). for blk in blocks[0]: for ins in blk: words = tuple(i for i, x in enumerate(ins["args"]) if i and self._mask_data_operand(x, self.lane_masks.get(id(ins), {}), ins)) if words: ins["mask_words"] = words def mask_half(self, a): """For a 32-bit lane-mask operand in wave64, return 'lo' (lanes 0-31), 'hi' (lanes 32-63), or None.""" if not self.wave64: return None if a["k"] == "special": t = a.get("t", "") if t in ("exec_lo", "vcc_lo"): return "lo" if t in ("exec_hi", "vcc_hi"): return "hi" return None if a["k"] == "sgpr" and a.get("n", 1) == 1: k = self.cur_masks.get(a["r"]) if k == lane_masks.MASK_LO: return "lo" if k == lane_masks.MASK_HI: return "hi" if a["k"] == "vgpr" and a.get("n", 1) == 1: k = self.cur_masks.get(("v", a["r"])) if k == lane_masks.MASK_LO: return "lo" if k == lane_masks.MASK_HI: return "hi" return None def lane_mask_word(self, a): """The 32-bit word of the lane mask in `a` as real bits, for a b32 scalar op that reads it as a number (s_flbit_i32_b32 of vcc_lo): the whole wave's lanes 0-31, or for the high half of a wave64 mask lanes 32-63. A register holds only this lane's 0 / ~0, so reading it as data gave every lane its own answer.""" lo, hi = self.wave_mask(a) if self.wave64: half = self.mask_half(a) if half is not None: return hi if half == "hi" else lo return lo def wave_equal(self, mine, equal, half=None): """s_cmp_eq / s_cmp_lg of a lane mask (with 0, or with another mask): the masks are equal when every lane's bit is, so the lanes vote. `mine` is this lane's result for the comparison asked (equal, or not equal). When `half` is 'lo' or 'hi' (32-bit compare on one half of a wave64 mask), restrict the vote to that half.""" self.uses_vote = True if half is not None: lane = self.wave_lane() in_h = self.tmp() op = "OpULessThan" if half == "lo" else "OpUGreaterThanEqual" self.emit(f"{in_h} = {op} %bool {lane} {self.cu(32)}") eff = self.tmp() if equal: self.emit(f"{eff} = OpSelect %bool {in_h} {mine} %true") else: self.emit(f"{eff} = OpLogicalAnd %bool {in_h} {mine}") mine = eff r = self.tmp() self.g_vote(r, "All" if equal else "Any", mine) return r def holds_lane_mask(self, a): """Whether operand `a` certainly holds a lane mask here: EXEC, or VCC / an SGPR that lane_masks.py found written as a mask on every path. An SGPR pair filled from a buffer (a light mask, say) is data.""" if a["k"] == "special": t = a.get("t", "") if t.startswith("exec"): return True if t in ("vcc", "vcc_lo"): return "vcc" in self.cur_masks if t == "vcc_hi": return ("vcc" if self.wave64 else "vcc_hi") in self.cur_masks return False if a["k"] == "sgpr": n = a.get("n", 1) if n == 2: return any(a["r"] + i in self.cur_masks for i in range(2)) and \ all(a["r"] + i in self.cur_masks or a["r"] + i in self.cur_either for i in range(2)) return all(a["r"] + i in self.cur_masks for i in range(n)) return False def any_mask_word(self, a): """Whether any dword of an SGPR pair is a lane mask (EITHER constants are data here). holds_lane_mask() needs every dword, but a pair with one mask word and one zero/-1 word is a zero-extended mask: selecting it as data would read this lane's bit. """ return a["k"] == "sgpr" and any(a["r"] + i in self.cur_masks for i in range(a.get("n", 1))) def any_ever_mask_word(self, a): """Whether any dword of an SGPR pair held a lane mask on any path, even earlier in the shader.""" return a["k"] == "sgpr" and any(a["r"] + i in self.ever_mask for i in range(a.get("n", 1))) def wave_mask(self, a): """The whole wave's lane mask in operand `a` as real bits: (lanes 0-31, lanes 32-63). A register holds only this lane's bit (all ones or zero), so each lane puts its bit at its own position and the subgroup (= the wave) ORs them together. For the instructions that look at a mask as a whole: until 2026-11-21 they saw the one lane, so the lane count of a wave was 64 or 0 and its first lane 0 or none.""" self.uses_subgroup = True special = a["k"] == "special" and a.get("t", "").startswith("exec") key = None if self.emulate: # The same value of the same register needs no second exchange: the lanes' bits are what they were. # Values are told apart by the SSA id last stored to the register in this block (x_tok, forgotten at # a label); a register not written yet has its value from the start of the block. if special: key = ("exec", self.x_gen, self.x_tok.get("%active", "start")) elif a["k"] == "sgpr": toks = tuple(self.x_tok.get(("sgpr", a["r"] + i), ("start", a["r"] + i)) for i in range(a.get("n", 1))) key = ("v", self.x_gen, toks) elif a["k"] == "special" and a["t"] in ("vcc", "vcc_lo", "vcc_hi"): reg = "%vcc_hi" if (a["t"] == "vcc_hi" and not self.wave64) else "%vcc" key = ("v", self.x_gen, self.x_tok.get(reg, ("start", reg[1:]))) if key in self.x_mcache: return self.x_mcache[key] mine = self.tmp_bool_nz(self.exec_value() if special else self.mask_src(a)) if self.emulate: res = self.x_round(bits=self.lane_bits(mine))[1] if key is not None: self.x_mcache[key] = res return res # The gather is stored to a variable of its own (eager, SHADER-529): a reader that writes a VGPR, v_mbcnt, is # an OpSelect on the lane's EXEC, and SPIRV-Cross (MoltenVK) inlines a single-use gather into that ternary's # taken arm. A lane that is off then never runs the subgroup op, and its bit is missing from the mask the # other lanes count (SHADER-WAVEMASK-EAGER; Apple M5, MoltenVK 1.4.2, tools/crosslane_fuzz.py). if self.wave32_fragment: ballot = self.tmp() self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} {mine}") word = self.wave32_ballot_word(ballot) self.uses_ballot = True return self.eager("%uint", word), self.cu(0) self.uses_wave_bits = True lane = self.wave_lane() low, sh, bit, b, lo_in, hi_in, lo, hi = (self.tmp() for _ in range(8)) self.emit(f"{low} = OpULessThan %bool {lane} {self.cu(32)}") self.emit(f"{sh} = OpBitwiseAnd %uint {lane} {self.cu(31)}") self.emit(f"{bit} = OpShiftLeftLogical %uint {self.cu(1)} {sh}") self.emit(f"{b} = OpSelect %uint {mine} {bit} {self.cu(0)}") self.emit(f"{lo_in} = OpSelect %uint {low} {b} {self.cu(0)}") self.emit(f"{hi_in} = OpSelect %uint {low} {self.cu(0)} {b}") self.emit(f"{lo} = OpGroupNonUniformBitwiseOr %uint {self.cu(3)} Reduce {lo_in}") self.emit(f"{hi} = OpGroupNonUniformBitwiseOr %uint {self.cu(3)} Reduce {hi_in}") return self.eager("%uint", lo), self.eager("%uint", hi) def quad_any(self, v): """This lane's value after whole-quad mode: all ones if any of the 4 lanes of its quad (4n .. 4n+3 of the wave) has `v` non-zero, else 0. A quad never crosses the 32/32 half of a wave64, so a 32-wide subgroup is exact. Without emulation the subgroup's ops do it: in a fragment shader the 2x2 quad, which on hardware is also 4 consecutive lanes; every other stage ballots, so a partial quad (fewer than 4 of the quad's lanes running, e.g. 2 active lanes of a 32-lane subgroup) is exact too, as a lane's bit is set only when it is running with `v` non-zero. Emulated, the four lanes' values are read through the exchange buffer.""" b = self.tmp() self.emit(f"{b} = OpSelect %uint {self.tmp_bool_nz(v)} {self.cu(1)} {self.cu(0)}") if self.emulate: lane, base = self.wave_lane(), self.tmp() self.emit(f"{base} = OpBitwiseAnd %uint {lane} {self.cu(0xFFFFFFFC)}") read = self.x_round(data=b)[0] acc = None for k in range(4): i = self.tmp() self.emit(f"{i} = OpIAdd %uint {base} {self.cu(k)}") w = read(i) if acc is None: acc = w else: o = self.tmp() self.emit(f"{o} = OpBitwiseOr %uint {acc} {w}") acc = o elif self.stage == "ps": # Fragment shaders always launch complete 2x2 pixel quads (including helper invocations), and Vulkan # guarantees OpGroupNonUniformQuadSwap includes helpers in the quad. self.uses_subgroup = self.uses_quad = True acc = b for d in (0, 1): # horizontal, then vertical neighbour sw, o = self.tmp(), self.tmp() self.emit(f"{sw} = OpGroupNonUniformQuadSwap %uint {self.cu(3)} {acc} {self.cu(d)}") self.emit(f"{o} = OpBitwiseOr %uint {acc} {sw}") acc = o else: # Non-fragment stages (CS/VS/GS/MS) can have partial quads (fewer than 4 of the quad's lanes running: a # subgroup or workgroup size not a multiple of 4, or a partial wave, e.g. 2 active lanes of a 32-lane # subgroup), where QuadSwap or unguarded shuffles from absent lanes are undefined in SPIR-V. Ballot sets # bit l iff lane l is running with `v != 0`, so extracting this lane's 4-bit quad nibble is exact on any # partial subgroup up to 128 lanes without needing GroupNonUniformQuad or any shuffle. self.uses_subgroup = self.uses_ballot = True nz = self.tmp_bool_nz(v) bal, widx, word, qoff, shifted, acc = (self.tmp() for _ in range(6)) self.emit(f"{bal} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} {nz}") sgl = self.subgroup_lane() self.emit(f"{widx} = OpShiftRightLogical %uint {sgl} {self.cu(5)}") self.emit(f"{word} = OpCompositeExtract %uint {bal} 0") for k in (1, 2, 3): wk, eq, pick = self.tmp(), self.tmp(), self.tmp() self.emit(f"{wk} = OpCompositeExtract %uint {bal} {k}") self.emit(f"{eq} = OpIEqual %bool {widx} {self.cu(k)}") self.emit(f"{pick} = OpSelect %uint {eq} {wk} {word}") word = pick self.emit(f"{qoff} = OpBitwiseAnd %uint {sgl} {self.cu(28)}") self.emit(f"{shifted} = OpShiftRightLogical %uint {word} {qoff}") self.emit(f"{acc} = OpBitwiseAnd %uint {shifted} {self.cu(0xF)}") r = self.tmp() self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(acc)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") return r def wqm_word(self, w): """s_wqm on 32 bits of plain data: each group of 4 bits becomes 1111 if any of its bits is set.""" acc = w for k in (1, 2, 3): x, o = self.tmp(), self.tmp() self.emit(f"{x} = OpShiftRightLogical %uint {w} {self.cu(k)}") self.emit(f"{o} = OpBitwiseOr %uint {acc} {x}") acc = o m, r = self.tmp(), self.tmp() self.emit(f"{m} = OpBitwiseAnd %uint {acc} {self.cu(0x11111111)}") self.emit(f"{r} = OpIMul %uint {m} {self.cu(15)}") return r def put_mask(self, d, v, half): """mask_dst, except that a 32-bit half of EXEC / VCC in wave64 only changes the lanes of that half.""" if half and d["k"] == "special" and d.get("t") in ("exec_lo", "exec_hi", "vcc_lo", "vcc_hi"): h = 1 if d["t"].endswith("hi") else 0 if d["t"].startswith("exec"): self.exec_half_write(h, v) else: lane, inh, cur, new = (self.tmp() for _ in range(4)) self.emit(f"{lane} = OpCopyObject %uint {self.wave_lane()}") self.emit(f"{inh} = {'OpUGreaterThanEqual' if h else 'OpULessThan'} %bool {lane} {self.cu(32)}") self.emit(f"{cur} = OpLoad %uint %vcc") self.emit(f"{new} = OpSelect %uint {inh} {v} {cur}") self.emit(f"OpStore %vcc {new}") if h: self.emit(f"OpStore %vcc_hi {new}") return self.mask_dst(d, v) def scc_any_half(self, v, half): """SCC = some lane of the wave (of one 32-lane half of a wave64 when `half`) has `v` non-zero.""" if not self.cur_scc_live: return mine = self.tmp_bool_nz(v) if half: lane, inh, both = (self.tmp() for _ in range(3)) self.emit(f"{lane} = OpCopyObject %uint {self.wave_lane()}") self.emit(f"{inh} = {'OpUGreaterThanEqual' if half == 'hi' else 'OpULessThan'} %bool {lane} {self.cu(32)}") self.emit(f"{both} = OpLogicalAnd %bool {inh} {mine}") mine = both any_ = self.tmp() self.g_vote(any_, "Any", mine) self.uses_vote = True z = self.tmp() self.emit(f"{z} = OpSelect %uint {any_} {self.cu(1)} {self.cu(0)}") self.emit(f"OpStore %scc {z}") def _wqm_dst_is_lane_mask(self, d): """True when a plain-data s_wqm write to `d` produces a register tracked as a lane mask.""" if d["k"] != "special": return False t = d.get("t", "") if t.startswith("exec"): return True if t not in ("vcc", "vcc_lo", "vcc_hi") or self.cur_ins is None: return False st = dict(self.cur_masks) for x in self.cur_ins["args"][1:]: if x.get("k") == "sgpr" and x.get("n", 1) == 1: r = x["r"] if r not in st and self.sgpr_imm.get(r) in (0, 0xFFFFFFFF): st[r] = lane_masks.EITHER lane_masks.step(st, self.cur_ins, self.wave64) key = "vcc_hi" if (not self.wave64 and t == "vcc_hi") else "vcc" return st.get(key) in lane_masks.MASK_KINDS def wqm(self, op, a): """s_wqm_b32 / s_wqm_b64: D = every quad (4 consecutive bits) of S0 that has a bit set becomes 1111; SCC = D != 0. A lane mask is one bit per lane here (this lane's), so the quad's bits are gathered with quad_any and SCC is the wave-wide any. Anything else is data and is computed on the bits. A 32-bit form in wave64 (exec_lo / exec_hi, vcc_lo / vcc_hi, a half-mask SGPR) only changes, and only votes over, its own half: it is the half of the source, or of the destination when that is one of the halves.""" half = None if self.wave64 and op.endswith("b32"): half = self.mask_half(a[1]) or self.mask_half(a[0]) if self.holds_lane_mask(a[1]): r = self.quad_any(self.mask_src(a[1])) self.put_mask(a[0], r, half) self.scc_any_half(r, half) return src = a[1] if op.endswith("b64") and src["k"] == "sgpr" and src.get("n") == 2: words = [self.load_reg("sgpr", src["r"]), self.load_reg("sgpr", src["r"] + 1)] elif op.endswith("b64") and src["k"] == "imm": words = [self.cu(src["v"] & 0xFFFFFFFF), self.cu((src["v"] >> 32) & 0xFFFFFFFF)] elif op.endswith("b64") and src["k"] == "special" and src.get("t") == "vcc": lo, hi = self.tmp(), self.tmp() self.emit(f"{lo} = OpLoad %uint %vcc") self.emit(f"{hi} = OpLoad %uint %vcc_hi") words = [lo, hi] elif op.endswith("b64") and src["k"] == "special" and src.get("t") == "null": words = [self.cu(0), self.cu(0)] else: words = [self.src_u(src)] + ([self.cu(0)] if op.endswith("b64") else []) res = [self.wqm_word(w) for w in words] d = a[0] if d["k"] == "sgpr": self.store_reg("sgpr", d["r"], res[0]) if len(res) == 2: self.store_reg("sgpr", d["r"] + 1, res[1]) elif d["k"] == "special" and d.get("t") == "null": pass elif d["k"] == "special" and d.get("t") == "m0": self.emit(f"OpStore %m0 {res[0]}") elif d["k"] == "special" and d.get("t") in ("vcc", "vcc_lo", "vcc_hi") and not self._wqm_dst_is_lane_mask(d): if d["t"] == "vcc_hi": self.emit(f"OpStore %vcc_hi {res[0]}") else: self.emit(f"OpStore %vcc {res[0]}") if len(res) == 2: self.emit(f"OpStore %vcc_hi {res[1]}") else: # EXEC / mask-valued VCC filled from data: this lane takes its own bit of the result. lane = self.wave_lane() word = res[0] if len(res) == 2: hi, word = self.tmp(), self.tmp() self.emit(f"{hi} = OpUGreaterThanEqual %bool {lane} {self.cu(32)}") self.emit(f"{word} = OpSelect %uint {hi} {res[1]} {res[0]}") pick = self._scalar_word_lane_bit(word, lane) self.put_mask(d, pick, half) if self.wave64 and d["k"] == "special" and d.get("t") == "vcc_hi": self.emit(f"OpStore %vcc_hi {res[0]}") nz = res[0] if len(res) == 2: nz = self.tmp() self.emit(f"{nz} = OpBitwiseOr %uint {res[0]} {res[1]}") self.scc_nonzero(nz) def lane_bits(self, b): """This lane's bool as its bit of a 64-lane mask: (lanes 0-31 word, lanes 32-63 word), one of them 0.""" lane = self.wave_lane() low, sh, bit, v, lo_in, hi_in = (self.tmp() for _ in range(6)) self.emit(f"{low} = OpULessThan %bool {lane} {self.cu(32)}") self.emit(f"{sh} = OpBitwiseAnd %uint {lane} {self.cu(31)}") self.emit(f"{bit} = OpShiftLeftLogical %uint {self.cu(1)} {sh}") self.emit(f"{v} = OpSelect %uint {b} {bit} {self.cu(0)}") self.emit(f"{lo_in} = OpSelect %uint {low} {v} {self.cu(0)}") self.emit(f"{hi_in} = OpSelect %uint {low} {self.cu(0)} {v}") return lo_in, hi_in def _scalar_word_lane_bit(self, word, lane=None): """Extract bit (lane & 31) of 32-bit scalar word as 0xFFFFFFFF / 0 for plain-data mask reads.""" if lane is None: lane = self.wave_lane() sh, shr, bit, r = (self.tmp() for _ in range(4)) self.emit(f"{sh} = OpBitwiseAnd %uint {lane} {self.cu(31)}") self.emit(f"{shr} = OpShiftRightLogical %uint {word} {sh}") self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") return r def _vgpr_mask_lane_bit(self, word, a): """This lane's 0 / ~0 bit of the lane-mask word `word` held by mask VGPR operand `a`: its own position of the word — and only when the lane is in the half the register covers (a MASK_LO/MASK_HI word means nothing to the other half).""" half = self.mask_half(a) if half is None: return self._scalar_word_lane_bit(word) lane = self.wave_lane() in_half = self.tmp() self.emit(f"{in_half} = OpULessThan %bool {lane} {self.cu(32)}" if half == "lo" else f"{in_half} = OpUGreaterThanEqual %bool {lane} {self.cu(32)}") bit = self._scalar_word_lane_bit(word, lane) r = self.tmp() self.emit(f"{r} = OpSelect %uint {in_half} {bit} {self.cu(0)}") return r def mask_src(self, a, wide=True): """A lane mask operand (sgpr pair, vcc, exec, imm) as one uint for this lane. A constant is a mask with one bit per lane, so lane L takes its bit L: of the 64-bit value (`wide`, the default: a 64-bit SALU operand or the VALU mask of a wave64; inline constants sign-extended, a literal with a zero high word, as src64_data) or of the 32-bit value with L mod 32 (a b32 op). Until 2026-11-22 every lane took bit 0 (0xff00 was no lane, 5 every lane).""" if a["k"] == "sgpr": if self.holds_lane_mask(a): if self.wave64 and wide and a.get("n") == 2: lo, hi = self.load_reg("sgpr", a["r"]), self.load_reg("sgpr", a["r"] + 1) up, sel = self.tmp(), self.tmp() self.emit(f"{up} = OpUGreaterThanEqual %bool {self.wave_lane()} {self.cu(32)}") self.emit(f"{sel} = OpSelect %uint {up} {hi} {lo}") return sel return self.load_reg("sgpr", a["r"]) # Not known to hold a mask: the SGPR may hold a constant (s_mov_b32 s20, 0x3ffffc00) that is the same in # every invocation, so lane L takes its bit L, as for an immediate. Until 2026-11-22 the raw value was used # and any non-zero constant enabled every lane. A mask the analysis missed is still exact: each # invocation holds 0 or ~0 there, and bit L of that is the same 0 or 1. A pair in a wave64 64-bit # context gives lanes 32..63 their bit from the high SGPR (a mask keeps the same 0 / ~0 in both). lane = self.wave_lane() word = self.load_reg("sgpr", a["r"]) if a.get("n", 1) == 2 and wide and self.wave64: hi, up, sel = self.load_reg("sgpr", a["r"] + 1), self.tmp(), self.tmp() self.emit(f"{up} = OpUGreaterThanEqual %bool {lane} {self.cu(32)}") self.emit(f"{sel} = OpSelect %uint {up} {hi} {word}") word = sel return self._scalar_word_lane_bit(word, lane) if a["k"] == "special" and a["t"] == "null": return self.cu(0) if a["k"] == "vgpr" and a.get("n", 1) == 1 and ("v", a["r"]) in self.cur_masks: return self._vgpr_mask_lane_bit(self.load_reg("vgpr", a["r"]), a) if a["k"] == "special" and a["t"] == "vcc_hi" and not self.wave64: v = self.tmp() self.emit(f"{v} = OpLoad %uint %vcc_hi") return v if self.holds_lane_mask(a) else self._scalar_word_lane_bit(v) if a["k"] == "special" and a["t"] in ("vcc", "vcc_lo", "vcc_hi"): if self.holds_lane_mask(a): v = self.tmp() self.emit(f"{v} = OpLoad %uint %vcc") return v lane = self.wave_lane() if a["t"] == "vcc_hi": # Wave64 32-bit vcc_hi holding plain data: lane L takes bit (L & 31) of %vcc_hi. v = self.tmp() self.emit(f"{v} = OpLoad %uint %vcc_hi") return self._scalar_word_lane_bit(v, lane) word = self.tmp() self.emit(f"{word} = OpLoad %uint %vcc") if a["t"] == "vcc" and wide and self.wave64: # Wave64 64-bit VCC holding plain data: lanes 0..31 read %vcc and 32..63 read %vcc_hi, # matching the SGPR-pair fallback above. A missed lane mask keeps 0 / ~0 in both halves. hi, up, sel = self.tmp(), self.tmp(), self.tmp() self.emit(f"{hi} = OpLoad %uint %vcc_hi") self.emit(f"{up} = OpUGreaterThanEqual %bool {lane} {self.cu(32)}") self.emit(f"{sel} = OpSelect %uint {up} {hi} {word}") word = sel return self._scalar_word_lane_bit(word, lane) if a["k"] == "special" and a["t"] in ("exec", "exec_lo", "exec_hi"): return self.exec_value() if a["k"] == "imm": w64 = wide and self.wave64 v = a["v"] & (0xFFFFFFFFFFFFFFFF if w64 else 0xFFFFFFFF) lo, hi = v & 0xFFFFFFFF, v >> 32 if lo in (0, 0xFFFFFFFF) and (hi == lo or not w64): return self.cu(lo) # 0 or -1: no lane or every lane, as before lane = self.wave_lane() sh, word, shr, bit, r = (self.tmp() for _ in range(5)) self.emit(f"{sh} = OpBitwiseAnd %uint {lane} {self.cu(31)}") if w64 and hi != lo: up = self.tmp() self.emit(f"{up} = OpUGreaterThanEqual %bool {lane} {self.cu(32)}") self.emit(f"{word} = OpSelect %uint {up} {self.cu(hi)} {self.cu(lo)}") else: self.emit(f"{word} = OpCopyObject %uint {self.cu(lo)}") # Shift and mask, not OpBitFieldUExtract (Intel's driver takes the offset mod 16 for a 16-bit constant; # see exec_half_write). self.emit(f"{shr} = OpShiftRightLogical %uint {word} {sh}") self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") return r if a["k"] == "special" and a.get("t") in ("m0", "scc", "src_scc"): v = self.src_u(a) if wide and self.wave64: lane = self.wave_lane() hi = self.tmp() self.emit(f"{hi} = OpUGreaterThanEqual %bool {lane} {self.cu(32)}") bit = self._scalar_word_lane_bit(v, lane) r = self.tmp() self.emit(f"{r} = OpSelect %uint {hi} {self.cu(0)} {bit}") return r return self._scalar_word_lane_bit(v) raise Unsupported("mask operand") def is_mask_op(self, x): return self.holds_lane_mask(x) or ( x["k"] == "special" and x.get("t", "").startswith(("exec", "vcc")) ) def f64_literal_one_dword(self, src: dict) -> bool: """True when a literal source is the one ISA dword that supplies bits 63:32. LLVM prints a value that fits one literal dword without padding, so its hex width is at most 8 digits; a spelling wider than that is the whole binary64 constant (the full-width form `tools/f64_diff.py` writes). A decimal operand has no printed width and falls back to the value, which is also what a padded one-dword spelling cannot survive. """ digits = src.get("literal_hex_digits") if digits is not None: return digits <= 8 return -0x80000000 <= src["v"] <= 0xFFFFFFFF def f64_source_words(self, src: dict, op: str) -> tuple[str, str]: if src["k"] in ("vgpr", "sgpr") and src.get("n") == 2: return self.load_reg(src["k"], src["r"]), self.load_reg(src["k"], src["r"] + 1) if src.get("f64_literal") and self.f64_literal_one_dword(src): # One literal dword: bits 63:32 of the constant (docs/design.md, f64 literal sources). return self.cu(0), self.cu(src["v"] & 0xFFFFFFFF) # A wider literal is the whole constant, so both words of it are the value: fall through. if src["k"] == "fimm": bits = struct.unpack("> 32) def src64_data(self, s, op, *, allow_vgpr: bool = False): kind = s["k"] if s.get("n") == 2 and (kind == "sgpr" or (allow_vgpr and kind == "vgpr")): return self.load_reg(kind, s["r"]), self.load_reg(kind, s["r"] + 1) if s["k"] == "imm": v = s["v"] & 0xFFFFFFFFFFFFFFFF return self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) if s["k"] == "special" and s.get("t") == "null": return self.cu(0), self.cu(0) raise Unsupported(op + " source") @staticmethod def valu_imm_i64(v: int) -> int: """The 64-bit value of an immediate in a signed 64-bit VALU source (v_cmp(x)_*_i64, v_ashrrev_i64 S1, v_mad_i64_i32 S2). LLVM AMDGPU operand syntax, "Conversion of Integer Values": a 32-bit literal used as an i64 operand is sign-extended ({-1, num.i32}), as a u64/b64 operand zero-extended ({0, num.u32}, which src64_data does). llvm-mc prints -100 as 0xffffff9c, so a printed literal with bit 31 set is widened here; inline constants (-16..-1) and decimal literals are parsed as negative already and pass through the mask. The scalar ops do the same (SHADER-SALU-LITERAL-SEXT, #978).""" v &= 0xFFFFFFFFFFFFFFFF if 0x80000000 <= v <= 0xFFFFFFFF: v |= 0xFFFFFFFF00000000 return v def src64_i64(self, s, op): """src64_data for a signed 64-bit VALU source: an immediate is widened by valu_imm_i64.""" if s["k"] == "imm": v = self.valu_imm_i64(s["v"]) return self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) return self.src64_data(s, op) def dst64_data(self, d, rlo, rhi, op, *, allow_null=False): if allow_null and d["k"] == "special" and d.get("t") == "null": return if d["k"] != "sgpr" or d.get("n") != 2: raise Unsupported(op + " destination") self.store_reg("sgpr", d["r"], rlo) self.store_reg("sgpr", d["r"] + 1, rhi) # f(S0, EXEC) of the saveexec / wrexec family (RDNA2 ISA SOP1; tools/cf_ref.py _SAVEEXEC): (op, NOT S0, NOT EXEC, # NOT the result). andn1/orn1 complement S0, andn2/orn2 complement EXEC. EXEC_LOGIC = {"and": ("OpBitwiseAnd", 0, 0, 0), "or": ("OpBitwiseOr", 0, 0, 0), "xor": ("OpBitwiseXor", 0, 0, 0), "andn1": ("OpBitwiseAnd", 1, 0, 0), "andn2": ("OpBitwiseAnd", 0, 1, 0), "orn1": ("OpBitwiseOr", 1, 0, 0), "orn2": ("OpBitwiseOr", 0, 1, 0), "nand": ("OpBitwiseAnd", 0, 0, 1), "nor": ("OpBitwiseOr", 0, 0, 1), "xnor": ("OpBitwiseXor", 0, 0, 1)} def exec_logic(self, kind, s0, exec_): """f(S0, EXEC) for one lane's mask bit (0 or ~0); see EXEC_LOGIC.""" k, n0, ne, nr = self.EXEC_LOGIC[kind] if n0: t = self.tmp() self.emit(f"{t} = OpNot %uint {s0}") s0 = t if ne: t = self.tmp() self.emit(f"{t} = OpNot %uint {exec_}") exec_ = t r = self.tmp() self.emit(f"{r} = {k} %uint {s0} {exec_}") if nr: t = self.tmp() self.emit(f"{t} = OpNot %uint {r}") r = t return r def is_mask_dst(self, d): """Whether `d` is a valid scalar lane-mask destination for VALU mask instructions (e.g. v_cmp_*_e64).""" k, t = d["k"], d.get("t") return ( k == "sgpr" or (k == "special" and ( t in ("exec", "exec_lo", "null", "vcc", "vcc_lo") or (t == "vcc_hi" and not self.wave64) )) ) def mask_dst(self, d, v): if self.wave64 and d["k"] == "special" and d["t"] in ("exec_lo", "exec_hi"): self.exec_half_write(1 if d["t"] == "exec_hi" else 0, v) elif d["k"] == "special" and d["t"] in ("exec", "exec_lo"): self.set_exec(v) elif d["k"] == "special" and d["t"] == "null": return elif d["k"] == "sgpr": self.store_reg("sgpr", d["r"], v) if d.get("n") == 2: self.store_reg("sgpr", d["r"] + 1, v) elif d["k"] == "special" and d["t"] in ("vcc", "vcc_lo"): self.emit(f"OpStore %vcc {v}") if self.wave64 and d["t"] == "vcc": self.emit(f"OpStore %vcc_hi {v}") elif d["k"] == "special" and d["t"] == "vcc_hi" and not self.wave64: self.emit(f"OpStore %vcc_hi {v}") else: raise Unsupported("mask destination") def clamp_mods(self, v, mods, allow_omod=True): # RDNA2 (GFX10.3) VOP3 OMOD applies before clamp iff MODE.ieee == 0 AND output denorms # for the destination precision are flushed. Under default shader MODE (IEEE=0, fp32 # denorms flushed, fp16/fp64 denorms kept), omod scales f32 destinations (including # v_cvt_f32_f16) and is ignored on f16 destinations while clamp still saturates [0, 1]. if allow_omod: for m in mods: if m in ("mul:2", "mul:4", "div:2"): k = {"mul:2": "2", "mul:4": "4", "div:2": "0.5"}[m] c = self.fconst(float(k)) g = self.tmp() self.emit(f"{g} = OpFMul %float {v} {c}") v = g if "clamp" in mods: # The game's MODE has DX10_CLAMP=1, so the clamp bit turns a NaN result into +0 # (docs/shader_validation.md). GLSL.std.450 FClamp leaves a NaN operand undefined, # so select +0 for a NaN first, as the div_fixup and cvt_pknorm clamps do. nan, safe, g = self.tmp(), self.tmp(), self.tmp() self.emit(f"{nan} = OpIsNan %bool {v}") self.emit(f"{safe} = OpSelect %float {nan} %f0 {v}") self.emit(f"{g} = OpExtInst %float %glsl FClamp {safe} %f0 %f1") return g return v def clamp_f16(self, v, mods): # f16 destination under default MODE (denorm16_64=3): omod ignored by silicon, clamp kept. return self.clamp_mods(v, mods, allow_omod=False) def clamp_f16_bits(self, h): """Apply DX10 clamp to an already rounded half in the low 16 bits of a %uint.""" zero, capped, out = self.tmp(), self.tmp(), self.tmp() # As unsigned words, all negative halves (including -0) and all positive NaNs exceed +inf. self.emit(f"{zero} = OpUGreaterThan %bool {h} {self.cu(0x7C00)}") self.emit(f"{capped} = OpExtInst %uint %glsl UMin {h} {self.cu(0x3C00)}") self.emit(f"{out} = OpSelect %uint {zero} {self.cu(0)} {capped}") return out def _validate_unary_f16(self, op, raw_op, a, mods): """Validate operands, encoding suffix, and modifiers for unary f16 VOP1/VOP3/SDWA ops.""" if len(a) != 2: raise Unsupported(f"{op} operands") dst, src = a if (dst.get("k") != "vgpr" or dst.get("n", 1) != 1 or dst.get("neg") or dst.get("abs") or dst.get("sext")): raise Unsupported(f"{op} destination") if src.get("n", 1) != 1 or src.get("sext"): raise Unsupported(f"{op} source") if raw_op.endswith("_dpp"): raise Unsupported(f"{op} _dpp") if raw_op.endswith("_e32"): if src.get("neg") or src.get("abs"): raise Unsupported(f"{op} _e32 source modifier") if mods: raise Unsupported(f"{op} _e32 modifier") return if raw_op.endswith("_sdwa"): seen_clamp = False seen_omod = False seen_keys = set() for m in mods: if m == "clamp": if seen_clamp: raise Unsupported(f"{op} duplicate clamp") seen_clamp = True elif m in ("mul:2", "mul:4", "div:2"): if seen_omod: raise Unsupported(f"{op} duplicate omod") seen_omod = True elif ":" in m: key, val = m.split(":", 1) if key in seen_keys: raise Unsupported(f"{op} duplicate {key}") if key in ("src0_sel", "dst_sel") and val in self.SDWA_SEL: seen_keys.add(key) elif key == "dst_unused" and val in ("UNUSED_PAD", "UNUSED_SEXT", "UNUSED_PRESERVE"): seen_keys.add(key) else: raise Unsupported(f"{op} _sdwa modifier") else: raise Unsupported(f"{op} _sdwa modifier") return # VOP3 (_e64 or bare) seen_clamp = False seen_omod = False seen_opsel = False for m in mods: if m == "clamp": if seen_clamp: raise Unsupported(f"{op} duplicate clamp") seen_clamp = True elif m in ("mul:2", "mul:4", "div:2"): if seen_omod: raise Unsupported(f"{op} duplicate omod") seen_omod = True elif m.startswith("op_sel:"): if seen_opsel or not (m.startswith("op_sel:[") and m.endswith("]")): raise Unsupported(f"{op} op_sel") raw_parts = m[len("op_sel:["):-1].split(",") if not raw_parts or len(raw_parts) > 2 or any(p not in ("0", "1") for p in raw_parts): raise Unsupported(f"{op} op_sel") seen_opsel = True else: raise Unsupported(f"{op} modifier") def flush_f32(self, f, *, force=False): """v_mad_f32, v_mac_f32, v_mad_legacy_f32 and default-mode v_mul_legacy_f32 flush f32 denormals: a subnormal operand or result reads as signed zero, whatever the MODE register says. LLVM's SITargetLowering::isFMADLegal forms v_mad_f32/v_mac_f32 only when f32 denormals are flushed (SIISelLowering.cpp, llvm-project 1922c0c); v_mad_legacy_f32 is the same VALU. When hardware DenormFlushToZero 32 is active (self.ftz32), the f32 arithmetic op itself flushes inputs and output; otherwise (or when force=True for GLSL.std.450 ops like Exp2 where DenormFlushToZero 32 is not guaranteed to flush on all drivers) emulate as |x| < FLT_MIN -> copysign(0, x): inf and NaN compare false and pass through, and 0 keeps its sign. Counted over the corpus before writing this (SHADER-118): 9,297 of the 26,503 shaders use at least one of the three, 440,858 occurrences (0.99% of the corpus).""" if self.ftz32 and not force: return f a, small, sign, z, r = (self.tmp() for _ in range(5)) self.emit(f"{a} = OpExtInst %float %glsl FAbs {f}") self.emit(f"{small} = OpFOrdLessThan %bool {a} {self.fconst(2.0 ** -126)}") self.emit(f"{sign} = OpBitwiseAnd %uint {self.tou(f)} {self.cu(0x80000000)}") self.emit(f"{z} = OpBitcast %float {sign}") self.emit(f"{r} = OpSelect %float {small} {z} {f}") return r def _validate_div_valu(self, ins, op, mods, *, dst_width, src_width=None, allow_opsel=False, strict_omod=True, allow_null_dst=False): """Validate encoding, arity, destination/source widths and modifiers for VOP3 IEEE-754 division ops.""" raw_op = ins["op"] raw_args = self.cur_ins["args"] if raw_op.endswith(("_e32", "_sdwa", "_dpp")): raise Unsupported(op + " encoding") if len(raw_args) != 4: raise Unsupported(op + " operands") dst = raw_args[0] is_null_dst = allow_null_dst and dst.get("k") == "special" and dst.get("t") == "null" if not is_null_dst and (dst.get("k") != "vgpr" or dst.get("n", 1) != dst_width): raise Unsupported(op + " destination") if dst.get("neg") or dst.get("abs") or dst.get("sext"): raise Unsupported(op + " destination modifier") for src in raw_args[1:]: if src.get("sext"): raise Unsupported(op + " operand modifier") if src_width is not None and src.get("n", 1) != src_width: raise Unsupported(op + " operand width") seen_clamp = False seen_omod = False seen_opsel = False for m in mods: if m == "clamp": if seen_clamp: raise Unsupported(op + " modifier") seen_clamp = True elif m in ("mul:2", "mul:4", "div:2"): if strict_omod and seen_omod: raise Unsupported(op + " modifier") seen_omod = True elif allow_opsel and m.startswith("op_sel:"): if seen_opsel or not (m.startswith("op_sel:[") and m.endswith("]")): raise Unsupported(op + " modifier") bits = [p.strip() for p in m[8:-1].split(",")] if not (1 <= len(bits) <= 4) or any(b not in ("0", "1") for b in bits): raise Unsupported(op + " modifier") seen_opsel = True else: raise Unsupported(f"{op} modifier {m}") def _validate_cvt32_valu(self, ins, op, mods, *, float_src, float_dst): """Validate encoding, arity, destination/source widths and modifiers for unary 32-bit float/int conversions.""" raw_op = ins["op"] raw_args = self.cur_ins["args"] if len(raw_args) != 2: raise Unsupported(op + " operands") dst, src = raw_args is_null_dst = dst.get("k") == "special" and dst.get("t") == "null" if not is_null_dst and (dst.get("k") != "vgpr" or dst.get("n", 1) != 1): raise Unsupported(op + " destination") if dst.get("neg") or dst.get("abs") or dst.get("sext"): raise Unsupported(op + " destination modifier") if src.get("n", 1) != 1: raise Unsupported(op + " operand width") is_sdwa = raw_op.endswith("_sdwa") is_dpp = raw_op.endswith("_dpp") is_e32 = raw_op.endswith("_e32") if src.get("sext") and (float_src or not is_sdwa): raise Unsupported(op + " operand modifier") if (src.get("neg") or src.get("abs")) and (not float_src or is_e32): raise Unsupported(op + " operand modifier") if is_e32: if mods: raise Unsupported(op + " modifier") return if is_dpp: if self.non_dpp_mods(raw_op, mods): raise Unsupported(op + " modifier") return seen_sdwa = set() seen_clamp = False seen_omod = False for m in mods: if m == "clamp": if not float_dst or seen_clamp: raise Unsupported(op + " modifier") seen_clamp = True elif m in ("mul:2", "mul:4", "div:2"): if not float_dst or seen_omod: raise Unsupported(op + " modifier") seen_omod = True elif is_sdwa and ":" in m: k, v = m.split(":", 1) if k in seen_sdwa: raise Unsupported(op + " duplicate SDWA modifier") seen_sdwa.add(k) if k in ("src0_sel", "dst_sel"): if v not in self.SDWA_SEL: raise Unsupported(op + " SDWA selector") elif k == "dst_unused": if v not in ("UNUSED_PAD", "UNUSED_SEXT", "UNUSED_PRESERVE"): raise Unsupported(op + " SDWA dst_unused") else: raise Unsupported(op + " modifier") else: raise Unsupported(op + " modifier") def dst_f64(self, d, value, mods, op): if d["k"] != "vgpr" or d.get("n") != 2: raise Unsupported(op + " destination") result = self.clamp_mods_f64(value, mods) pair = self.tmp() self.emit(f"{pair} = OpBitcast %v2uint_d {result}") for i in range(2): word = self.tmp() self.emit(f"{word} = OpCompositeExtract %uint {pair} {i}") self.dst({"k": "vgpr", "r": d["r"] + i, "n": 1}, word) def flush_f32_mods(self, v, mods): """Flush a subnormal sum before output modifiers and flush again after them (SHADER-340, RDNA1 gfx1010).""" v = self.flush_f32(v) if any(m == "clamp" or m.startswith(("mul:", "div:")) for m in mods): v = self.flush_f32(self.clamp_mods(v, mods)) return v def clamp_mods_f64(self, v, mods): """clamp_mods for a %double result: omod scales first, then clamp to [0, 1]. As for f32 the clamp is GLSL.std.450 FClamp, so a NaN result and the sign of a -0 result are left to the driver (the hardware, with DX10_CLAMP set, gives +0 for NaN). The f64 VALU arithmetic and rounding ops hand this only `clamp`: on RDNA2 the omod of those ops does nothing while f64 denormals are kept, the MODE this translator assumes, as the "v_add_f64 output modifiers" row records. A caller whose own row measured an omod keeps passing it.""" for m in mods: if m in ("mul:2", "mul:4", "div:2"): g = self.tmp() self.emit(f"{g} = OpFMul %double {v} {self.dconst({'mul:2': 2.0, 'mul:4': 4.0, 'div:2': 0.5}[m])}") v = g if "clamp" in mods: g = self.tmp() self.emit(f"{g} = OpExtInst %double %glsl FClamp {v} {self.dconst(0.0)} {self.dconst(1.0)}") return g return v def turn_angle(self, x): """Reduce a turn count to [-0.5, 0.5] before scaling by 2*pi (SHADER-88). RDNA's v_sin/v_cos take turns and range-reduce in turns. Scaling first loses the fractional part for large inputs (one f32 ulp at 255 turns is ~1.2e-4 rad) and leaves Sin outside the [-pi, pi] range where Vulkan guarantees its precision. x - RoundEven(x) is exact in binary32 for every finite x, unlike Fract(x) (rounds 1 - |x| for a negative x: -2**-26 became +0, and -0.1 was ~1.7e-7 off). RoundEven rather than Round so +-0.5 reduce symmetrically. A zero keeps its sign (x - RoundEven(x) would turn -0 into +0). NaN and infinity stay NaN through the subtraction. """ rnd, d, zero, t, arg = (self.tmp() for _ in range(5)) self.emit(f"{rnd} = OpExtInst %float %glsl RoundEven {x}") self.emit(f"{d} = OpFSub %float {x} {rnd}") self.emit(f"{zero} = OpFOrdEqual %bool {x} {self.fconst(0.0)}") self.emit(f"{t} = OpSelect %float {zero} {x} {d}") self.emit(f"{arg} = OpFMul %float {t} {self.fconst(6.283185307179586)}") return arg def trig_exact_zero(self, op, x, r): """v_sin/v_cos: +0 where the hardware gives an exact zero, i.e. sin at an odd half turn and cos at an odd quarter turn (|x - RoundEven(x)| is 0.5 or 0.25). Sin(2*pi*0.5) with a rounded 2*pi is about -8.7e-8 instead. Measured natively on gfx1036 for f32 and f16, both signs, from 0.25 up to 2^22 turns (SHADER-134).""" rnd, d, ad, hit, out = (self.tmp() for _ in range(5)) self.emit(f"{rnd} = OpExtInst %float %glsl RoundEven {x}") self.emit(f"{d} = OpFSub %float {x} {rnd}") self.emit(f"{ad} = OpExtInst %float %glsl FAbs {d}") self.emit(f"{hit} = OpFOrdEqual %bool {ad} {self.fconst(0.5 if 'sin' in op else 0.25)}") self.emit(f"{out} = OpSelect %float {hit} %f0 {r}") return out def fconst(self, x): """The %float constant x rounded to f32: one OpConstant %float per value (Gen.fconsts), not an OpBitcast of the uint constant at every use (4.3% of the instructions of a large RaytracingResolve module; tof of a uint constant, a float literal operand for one, takes the same constant). The literal is written so spirv-as and tools/spirv_asm.py give back the same 32 bits (float_literal).""" return self.fconst_bits(struct.unpack("> 32)}") self.emit(f"{d} = OpBitcast %double {v2}") return d def round_f32_flushed(self, fn, x): """v_floor_f32 / v_ceil_f32 / v_fract_f32 of the operand x (source modifiers applied) as RDNA2 computes them in the MODE inferred for the game (IEEE 0, f32 denormals flushed), measured natively on gfx1036: a denormal operand is a zero of its sign (floor(-1e-45) = -0, ceil(+1e-45) = +0, fract of either 0; using the denormal gives -1.0, +1.0 and 0x3f7fffff), and a NaN operand passes through unchanged (signalling ones too). fract(+-inf) is the negative quiet NaN 0xffc00000. Done here rather than left to the driver's f32 denormal handling, which Vulkan does not fix.""" bits, mag, exp, den, sgn, sz, xf, r = (self.tmp() for _ in range(8)) self.emit(f"{bits} = OpBitcast %uint {x}") self.emit(f"{mag} = OpBitwiseAnd %uint {bits} {self.cu(0x7FFFFFFF)}") self.emit(f"{exp} = OpBitwiseAnd %uint {bits} {self.cu(0x7F800000)}") self.emit(f"{den} = OpIEqual %bool {exp} {self.cu(0)}") self.emit(f"{sgn} = OpBitwiseAnd %uint {bits} {self.cu(0x80000000)}") self.emit(f"{sz} = OpSelect %uint {den} {sgn} {bits}") self.emit(f"{xf} = OpBitcast %float {sz}") self.emit(f"{r} = OpExtInst %float %glsl {fn} {xf}") if fn == "Fract": r = self.fract_below_one(r) nan, inf, rb, keep, out = (self.tmp() for _ in range(5)) self.emit(f"{rb} = OpBitcast %uint {r}") self.emit(f"{nan} = OpUGreaterThan %bool {mag} {self.cu(0x7F800000)}") self.emit(f"{keep} = OpSelect %uint {nan} {bits} {rb}") if fn == "Fract": fixed = self.tmp() self.emit(f"{inf} = OpIEqual %bool {mag} {self.cu(0x7F800000)}") self.emit(f"{fixed} = OpSelect %uint {inf} {self.cu(0xFFC00000)} {keep}") keep = fixed self.emit(f"{out} = OpBitcast %float {keep}") return out def fract_below_one(self, r): """v_fract: a Fract(x) that rounded up to 1.0 (x a tiny negative number) becomes 0x3f7fffff, the largest float below 1, as on hardware. A compare and select, not FMin, so the NaN of fract(+-inf) is kept.""" one, below = self.tmp(), self.tmp() self.emit(f"{one} = OpFOrdEqual %bool {r} %f1") self.emit(f"{below} = OpSelect %float {one} {self.tof(self.cu(0x3F7FFFFF))} {r}") return below @staticmethod def _f32_const_nan(s): """Return True/False when ``s`` is statically NaN/non-NaN f32, or None at run time.""" if not s or "sdwa_sel" in s: return None if s["k"] == "fimm": return s["v"] != s["v"] if s["k"] == "imm": u = s["v"] & 0xFFFFFFFF return (u & 0x7F800000) == 0x7F800000 and bool(u & 0x7FFFFF) return None def _select_nan_first(self, res, first, nan_second, second=None, second_src=None): """Return ``first`` when ``second`` is NaN, else ``res`` (RDNA2 S0 priority when both operands are NaN).""" if nan_second is False: return res if nan_second is True: return first if nan_second is None: st = self._f32_const_nan(second_src) if st is False: return res if st is True: return first nan_second = self.tmp() self.emit(f"{nan_second} = OpIsNan %bool {second}") sel = self.tmp() self.emit(f"{sel} = OpSelect %float {nan_second} {first} {res}") return sel def nminmax_f32(self, glsl_op, x, y, y_src=None, nan_y=None): """GLSL.std.450 ``NMin``/``NMax`` returning ``x`` with its bits intact whenever ``y`` is NaN.""" r = self.tmp() self.emit(f"{r} = OpExtInst %float %glsl {glsl_op} {x} {y}") return self._select_nan_first(r, x, nan_y, y, y_src) _SDWA_UNUSED = ("UNUSED_PAD", "UNUSED_SEXT", "UNUSED_PRESERVE") _F16_OMOD_MODS = ("mul:2", "mul:4", "div:2") @staticmethod def _validate_f16_opsel_mod(mod, nsrc, op): if not (mod.startswith("op_sel:[") and mod.endswith("]")): raise Unsupported(op + " op_sel") parts = [p.strip() for p in mod[len("op_sel:["):-1].split(",")] if len(parts) != nsrc + 1 or any(p not in ("0", "1") for p in parts): raise Unsupported(op + " op_sel") def _validate_f16_vop3_mods(self, mods, nsrc, op): seen_clamp = False seen_omod = False seen_opsel = False for m in mods: if m == "clamp": if seen_clamp: raise Unsupported(op + " duplicate clamp") seen_clamp = True elif m in self._F16_OMOD_MODS: if seen_omod: raise Unsupported(op + " duplicate output modifier") seen_omod = True elif m.startswith("op_sel:"): if seen_opsel: raise Unsupported(op + " duplicate op_sel") self._validate_f16_opsel_mod(m, nsrc, op) seen_opsel = True else: raise Unsupported(op + " modifier " + m) def _validate_f16_sdwa_mods(self, mods, op): seen_clamp = False seen_omod = False seen_keys = set() for m in mods: if m == "clamp": if seen_clamp: raise Unsupported(op + " duplicate clamp") seen_clamp = True elif m in self._F16_OMOD_MODS: if seen_omod: raise Unsupported(op + " duplicate output modifier") seen_omod = True elif ":" in m: k, v = m.split(":", 1) if k in ("src0_sel", "src1_sel", "dst_sel"): if k in seen_keys or v not in self.SDWA_SEL: raise Unsupported(op + " sdwa modifier " + m) seen_keys.add(k) elif k == "dst_unused": if k in seen_keys or v not in self._SDWA_UNUSED: raise Unsupported(op + " sdwa modifier " + m) seen_keys.add(k) else: raise Unsupported(op + " modifier " + m) else: raise Unsupported(op + " modifier " + m) def _validate_f16_valu(self, ins, op, nsrc, *, allow_e32=False, allow_e64=True, allow_sdwa=False, allow_dpp=False, int_srcs=()): """Validate encoding suffix, arity, operand kinds/widths/modifiers, and instruction modifiers for f16 VALU ops.""" raw_op, a, mods = ins["op"], ins["args"], ins["mods"] allowed_suffixes = [""] if allow_e32: allowed_suffixes.append("_e32") if allow_e64: allowed_suffixes.append("_e64") if allow_sdwa: allowed_suffixes.append("_sdwa") if allow_dpp: allowed_suffixes.append("_dpp") suf = raw_op[len(op):] if suf not in allowed_suffixes: raise Unsupported(raw_op + " encoding") if len(a) != nsrc + 1: raise Unsupported(op + " arity") dst = a[0] if dst.get("k") != "vgpr" or dst.get("n", 1) != 1 or dst.get("neg") or dst.get("abs") or dst.get("sext"): raise Unsupported(op + " destination") is_vop2_only = not allow_e64 for idx, src in enumerate(a[1:]): if src.get("n", 1) != 1 or src.get("sext"): raise Unsupported(op + " source") if (is_vop2_only or suf == "_e32" or idx in int_srcs) and (src.get("neg") or src.get("abs")): raise Unsupported(op + " source modifier") if is_vop2_only or suf == "_e32": if mods: raise Unsupported(op + " modifier") elif suf == "_sdwa": self._validate_f16_sdwa_mods(mods, op) elif suf == "_dpp": if self.non_dpp_mods(raw_op, mods): raise Unsupported(op + " dpp modifier") else: self._validate_f16_vop3_mods(mods, nsrc, op) def _read_f16_minmax_srcs(self, srcs, sels, mods): """Read f16 min/max/med3 sources and track raw modified ``src0`` half when ``clamp`` is absent.""" if "clamp" in mods: return [self.f16_in(s, sel) for s, sel in zip(srcs, sels)], None, None in_bits = [self.f16_in_bits(s, sel, apply_mods=(i == 0)) for i, (s, sel) in enumerate(zip(srcs, sels))] vals = [v for v, _, _ in in_bits] all_nan = self.all_f16_nan_cond([(raw, st) for _, raw, st in in_bits]) return vals, all_nan, in_bits[0][1] def _finish_f16_minmax_out(self, dst_op, r, mods, dhi, all_nan, h0_mod): r = self.clamp_f16(r, mods) if all_nan is None: self.f16_out(dst_op, r, dhi) return if all_nan is True: lo = h0_mod else: lo = self.f16_res(r) sel_u = self.tmp() self.emit(f"{sel_u} = OpSelect %uint {all_nan} {h0_mod} {lo}") lo = sel_u self.put_f16_bits(dst_op, lo, dhi) def med3_f(self, vals, srcs, sel=None): """v_med3_f32 / v_med3_f16 on the f32 values ``vals`` of operands ``srcs`` (``sel``: the f16 half each one reads). Without NaN: the median, NMin(NMax(z, NMin(x, y)), NMax(x, y)) — using NMax/NMin rather than FClamp so evaluating the median before the NaN select is never GLSL.std.450 undefined when z is NaN or both x and y are NaN. With any NaN operand the hardware returns min3(x, y, z) with the NaN-ignoring min (docs/design.md). An inline or literal constant that is not a NaN gets no OpIsNan; with no operand left to check there is no select.""" x, y, z = vals lo, hi, m1, m = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{lo} = OpExtInst %float %glsl NMin {x} {y}") self.emit(f"{hi} = OpExtInst %float %glsl NMax {x} {y}") self.emit(f"{m1} = OpExtInst %float %glsl NMax {z} {lo}") self.emit(f"{m} = OpExtInst %float %glsl NMin {m1} {hi}") checks = [] preds = [] for i, (v, s) in enumerate(zip(vals, srcs)): bits = None if s["k"] == "imm": bits = s["v"] & 0xFFFFFFFF elif s["k"] == "fimm": bits = struct.unpack("> 16 if sel[i] else bits) & 0xFFFF is_nan = (h & 0x7C00) == 0x7C00 and h & 0x3FF if not is_nan: preds.append(False) continue c = self.tmp() self.emit(f"{c} = OpIsNan %bool {v}") checks.append(c) preds.append(c) if not checks: return m nan = checks[0] for c in checks[1:]: o = self.tmp() self.emit(f"{o} = OpLogicalOr %bool {nan} {c}") nan = o if sel is None: mn1 = self._select_nan_first(lo, x, preds[1]) mn = self.nminmax_f32("NMin", mn1, z, nan_y=preds[2]) else: mn = self.tmp() self.emit(f"{mn} = OpExtInst %float %glsl NMin {lo} {z}") r = self.tmp() self.emit(f"{r} = OpSelect %float {nan} {mn} {m}") return r # ---- instructions ---- SDWA_SEL = {"BYTE_0": (0, 8), "BYTE_1": (8, 8), "BYTE_2": (16, 8), "BYTE_3": (24, 8), "WORD_0": (0, 16), "WORD_1": (16, 16), "DWORD": (0, 32)} def insn(self, ins): """SDWA (sub-dword addressing): each source is narrowed to src_sel (zero-extended, or sign-extended under sext()) before the op and its neg/abs, and a VGPR result is placed at dst_sel with dst_unused deciding the other bits (PAD = zero, SEXT = sign-extend, PRESERVE = keep the old bits). VOPC has no dst_sel; v_cmpx (GFX10) has no written destination operand.""" self.cur_ins = ins self.cur_masks = self.lane_masks.get(id(ins), {}) self.write_all_lanes = id(ins) in self.mask_writes self.cur_uniform_readlane = bool(self.w64g) and id(ins) in self.w64g["uniform_readlane"] self.cur_scc_live = (not self.emulate) or (self.scc_live is None) or (id(ins) in self.scc_live) if self.emulate: self.x_memory_order(base_op(ins["op"])) self.cur_either = self.lane_either.get(id(ins), ()) try: if ins["op"] == lane_masks.TO_DATA: # A lane mask that a merge further on takes as data (lane_masks.insert_data_merges): the # register gets the wave's real bits, the same number in every lane. src = ins["args"][1] val = self.lane_mask_word(src) if self.holds_lane_mask(src) else self.src_u(src) self.dst(ins["args"][0], val) return None if ins["op"].endswith("_dpp"): bop = base_op(ins["op"]) if bop in SOPC_CMP32_OPS or bop in SOPC_CMP64_OPS or bop in SOPC_BITCMP_OPS: raise Unsupported(f"{ins['op']}: encoding suffix not supported on SOPC") return self.dpp_insn(ins) if not ins["op"].endswith("_sdwa"): return self._insn(ins) op, mods = base_op(ins["op"]), ins["mods"] kv = dict(m.split(":", 1) for m in mods if m.split(":", 1)[0] in ("src0_sel", "src1_sel", "dst_sel", "dst_unused")) args = [dict(x) for x in ins["args"]] first = 0 if op.startswith("v_cmpx") else 1 if op in ("v_add_co_ci_u32", "v_sub_co_ci_u32", "v_subrev_co_ci_u32") and len(args) > 3: first = 2 # vdst, carry-out, src0, src1, carry-in; the short form (3 operands) has no carry-out for i, key in enumerate(("src0_sel", "src1_sel")): j = first + i if j < len(args) and (kv.get(key, "DWORD") != "DWORD" or args[j].get("sext")): args[j]["sdwa_sel"] = kv.get(key, "DWORD") if not op.startswith("v_cmp") and args: # DWORD too: a 16-bit result then zeroes the high half (write_lo16) args[0]["sdwa_dst"] = (kv.get("dst_sel", "DWORD"), kv.get("dst_unused", "UNUSED_PAD")) return self._insn({**ins, "args": args}) except (IndexError, TypeError): # A line with no operands (hand-written input only: LLVM always prints them) fails the first # operand read with IndexError, or TypeError where v_cmpx pads the source list with a None that # never met a real operand. Report it as a rejection, not a translator error. With at least one # operand printed either is internal and stays one. if any(a is not None for a in ins["args"]): raise raise Unsupported(ins["op"] + ": no operands") from None def sdwa_src(self, v, a): off, width = self.SDWA_SEL[a["sdwa_sel"]] if width == 32: return v if off == 16 and width == 16: return self.as_uint(self.i16_half(v, 1)) if a.get("sext") else self.u16_half(v, 1) r = self.tmp() if a.get("sext"): # Sign-extend with two shifts, not OpBitFieldSExtract: an NVIDIA driver (RTX 4050 Laptop, 621.01) converts # the extracted field as signed under v_cvt_f32_u32 (docs/design.md, "SDWA sext source"). Same value. up = self.tmp() self.emit(f"{up} = OpShiftLeftLogical %uint {v} {self.cu(32 - off - width)}") self.emit(f"{r} = OpShiftRightArithmetic %uint {up} {self.cu(32 - width)}") return r self.emit(f"{r} = OpBitFieldUExtract %uint {v} {self.cu(off)} {self.cu(width)}") return r def sdwa_dst(self, d, val): sel, unused = d["sdwa_dst"] off, width = self.SDWA_SEL[sel] if width == 32: return val r = self.tmp() if unused == "UNUSED_PRESERVE": self.emit(f"{r} = OpBitFieldInsert %uint {self.load_reg('vgpr', d['r'])} {val} {self.cu(off)} {self.cu(width)}") return r lo = self.tmp() ext = "OpBitFieldSExtract" if unused == "UNUSED_SEXT" else "OpBitFieldUExtract" self.emit(f"{lo} = {ext} %uint {val} {self.cu(0)} {self.cu(width)}") # SEXT: the sign-extended field shifted up leaves sign copies above it; bits below stay zero. self.emit(f"{r} = OpShiftLeftLogical %uint {lo} {self.cu(off)}") return r def dpp_insn(self, ins): """DPP (data-parallel primitives) on a VOP1/VOP2 or full-write f32 VOPC src0. The source lane follows quad_perm/row_* or dpp8, then row_mask (one bit per 16-lane row) and bank_mask (one bit per 4-lane bank) decide which destination lanes update. A source lane that is out of range or inactive under EXEC is invalid: bound_ctrl 1 reads 0, otherwise the destination keeps its old value. dpp8 instead uses fi: fi 0 reads 0 from an inactive lane, fi 1 reads its pre-existing value. DPP16/8 never reaches beyond its 16/8-lane group, so this is exact on every subgroup at least that wide.""" if "_sdwa" in ins["op"]: raise Unsupported("DPP with SDWA") mods = ins["mods"] def number(key, default): for m in mods: if m.startswith(key + ":"): try: return int(m.split(":", 1)[1], 0) except ValueError: raise Unsupported("DPP " + key) return default def selectors(key, count, limit): for m in mods: if m.startswith(key + ":"): try: vals = [int(x, 0) for x in m.split("[", 1)[1].rstrip("]").split(",")] except (IndexError, ValueError): raise Unsupported("DPP " + key) if len(vals) != count or any(not 0 <= v < limit for v in vals): raise Unsupported("DPP " + key) return vals return None dpp8 = selectors("dpp8", 8, 8) quad = selectors("quad_perm", 4, 4) ctrl = None for m in mods: if m in ("row_mirror", "row_half_mirror"): if ctrl is not None: raise Unsupported("DPP controls") ctrl = (m, None) continue for key in ("row_shl", "row_shr", "row_ror", "row_share", "row_xmask"): if m.startswith(key + ":"): if ctrl is not None: raise Unsupported("DPP controls") try: value = int(m.split(":", 1)[1], 0) except ValueError: raise Unsupported("DPP " + key) if not 0 <= value <= 15 or (key not in ("row_share", "row_xmask") and value == 0): raise Unsupported("DPP " + key) ctrl = (key, value) break if dpp8 is not None and (quad is not None or ctrl is not None): raise Unsupported("DPP controls") if quad is not None and ctrl is not None: raise Unsupported("DPP controls") if dpp8 is None and quad is None and ctrl is None: raise Unsupported("DPP control") fi = number("fi", 0) bound = number("bound_ctrl", 0) if fi not in (0, 1) or bound not in (0, 1): raise Unsupported("DPP flag") fi, bound = bool(fi), bool(bound) row_mask = number("row_mask", 0xF) bank_mask = number("bank_mask", 0xF) if not (0 <= row_mask <= 0xF and 0 <= bank_mask <= 0xF): raise Unsupported("DPP mask") args = [dict(a) for a in ins["args"]] if len(args) < 2: raise Unsupported("DPP operands") # A VOPC compare in DPP form (docs/design.md, "DPP on a VOPC compare"): src0 comes through the same lane # selection and the result is a mask bit, not a VGPR. Only the forms where every lane writes its bit are # taken: what a lane that DPP leaves unwritten does to its VCC bit is measured on RDNA3 only (it gets 0), not # on RDNA2. v_cmpx writes EXEC instead and prints no destination, so its src0 is the first operand # (SHADER-VOPCX-DPP). compare = base_op(ins["op"]).startswith("v_cmp") first = 0 if base_op(ins["op"]).startswith("v_cmpx") else 1 if compare: if len(args) != first + 2: raise Unsupported("DPP compare operands") if row_mask != 0xF or bank_mask != 0xF or not (dpp8 is not None or bound): raise Unsupported("DPP compare with lanes DPP leaves unwritten") elif args[0].get("k") != "vgpr" or args[0].get("n", 1) != 1: raise Unsupported("DPP destination") if args[first].get("n", 1) != 1: raise Unsupported("DPP 64-bit source") if args[first].get("sext"): raise Unsupported("DPP sext") src = args[first] raw_src = dict(src) raw_src.pop("neg", None) raw_src.pop("abs", None) src_val = self.src_u(raw_src) lane = self.wave_lane() group_bits = 7 if dpp8 is not None else 15 local = self.tmp() self.emit(f"{local} = OpBitwiseAnd %uint {lane} {self.cu(group_bits)}") in_bounds = None if dpp8 is not None: packed = sum(v << (3 * i) for i, v in enumerate(dpp8)) sh = self.tmp() self.emit(f"{sh} = OpIMul %uint {local} {self.cu(3)}") p = self.tmp() self.emit(f"{p} = OpShiftRightLogical %uint {self.cu(packed)} {sh}") src_local = self.tmp() self.emit(f"{src_local} = OpBitwiseAnd %uint {p} {self.cu(7)}") elif quad is not None: packed = sum(v << (2 * i) for i, v in enumerate(quad)) q = self.tmp() self.emit(f"{q} = OpBitwiseAnd %uint {local} {self.cu(3)}") sh = self.tmp() self.emit(f"{sh} = OpShiftLeftLogical %uint {q} {self.cu(1)}") p = self.tmp() self.emit(f"{p} = OpShiftRightLogical %uint {self.cu(packed)} {sh}") perm = self.tmp() self.emit(f"{perm} = OpBitwiseAnd %uint {p} {self.cu(3)}") base = self.tmp() self.emit(f"{base} = OpBitwiseAnd %uint {local} {self.cu(0xFFFFFFFC)}") src_local = self.tmp() self.emit(f"{src_local} = OpBitwiseOr %uint {base} {perm}") else: kind, value = ctrl if kind == "row_shl": src_local = self.tmp() self.emit(f"{src_local} = OpIAdd %uint {local} {self.cu(value)}") in_bounds = self.tmp() self.emit(f"{in_bounds} = OpULessThan %bool {src_local} {self.cu(16)}") elif kind == "row_shr": in_bounds = self.tmp() self.emit(f"{in_bounds} = OpUGreaterThanEqual %bool {local} {self.cu(value)}") src_local = self.tmp() self.emit(f"{src_local} = OpISub %uint {local} {self.cu(value)}") elif kind == "row_ror": t = self.tmp() self.emit(f"{t} = OpISub %uint {local} {self.cu(value)}") src_local = self.tmp() self.emit(f"{src_local} = OpBitwiseAnd %uint {t} {self.cu(15)}") elif kind == "row_share": src_local = self.cu(value) elif kind == "row_xmask": src_local = self.tmp() self.emit(f"{src_local} = OpBitwiseXor %uint {local} {self.cu(value)}") elif kind == "row_mirror": src_local = self.tmp() self.emit(f"{src_local} = OpISub %uint {self.cu(15)} {local}") else: # row_half_mirror hi = self.tmp() self.emit(f"{hi} = OpBitwiseAnd %uint {local} {self.cu(8)}") lo = self.tmp() self.emit(f"{lo} = OpBitwiseAnd %uint {local} {self.cu(7)}") inv = self.tmp() self.emit(f"{inv} = OpISub %uint {self.cu(7)} {lo}") src_local = self.tmp() self.emit(f"{src_local} = OpBitwiseOr %uint {hi} {inv}") if self.emulate: # One workgroup exchange per DPP: every lane publishes src_val and its active bit, and the next round # reads the selected lane. No subgroup operation is used, so this is exact on any subgroup size. global_group = self.tmp() self.emit(f"{global_group} = OpBitwiseAnd %uint {lane} {self.cu(~group_bits & 0xFFFFFFFF)}") src_g = self.tmp() self.emit(f"{src_g} = OpBitwiseOr %uint {global_group} {src_local}") if in_bounds is not None: safe_g = self.tmp() self.emit(f"{safe_g} = OpSelect %uint {in_bounds} {src_g} {self.cu(0)}") else: safe_g = src_g if fi: # fi:1 fetches the inactive source as well; only an out-of-row lane is still invalid. read, _ = self.x_round(data=src_val) shuffled = read(safe_g) src_ok = in_bounds if in_bounds is not None else "%true" else: lo_bit, hi_bit = self.lane_bits(self.active_b()) read, (lo_word, hi_word) = self.x_round(data=src_val, bits=(lo_bit, hi_bit)) shuffled = read(safe_g) is_low = self.tmp() self.emit(f"{is_low} = OpULessThan %bool {safe_g} {self.cu(32)}") word = self.tmp() self.emit(f"{word} = OpSelect %uint {is_low} {lo_word} {hi_word}") sh = self.tmp() self.emit(f"{sh} = OpBitwiseAnd %uint {safe_g} {self.cu(31)}") bit = self.tmp() self.emit(f"{bit} = OpShiftRightLogical %uint {word} {sh}") one = self.tmp() self.emit(f"{one} = OpBitwiseAnd %uint {bit} {self.cu(1)}") active = self.tmp() self.emit(f"{active} = OpINotEqual %bool {one} {self.cu(0)}") if in_bounds is not None: both = self.tmp() self.emit(f"{both} = OpLogicalAnd %bool {in_bounds} {active}") active = both src_ok = active else: sgl = self.subgroup_lane() sg_group = self.tmp() self.emit(f"{sg_group} = OpBitwiseAnd %uint {sgl} {self.cu(~group_bits & 0xFFFFFFFF)}") src_sg = self.tmp() self.emit(f"{src_sg} = OpBitwiseOr %uint {sg_group} {src_local}") if in_bounds is not None: # Clamp an invalid source lane to own subgroup lane (always running, never lane 0 which may be absent). safe_sg = self.tmp() self.emit(f"{safe_sg} = OpSelect %uint {in_bounds} {src_sg} {sgl}") else: safe_sg = src_sg shuffle_src = safe_sg if fi: # fi:1 fetches an EXEC-off source lane, but an unlaunched/absent lane in a partial subgroup must # still be redirected to sgl before OpGroupNonUniformShuffle and treated as invalid. if src.get("k") == "vgpr": pbal, present = self.tmp(), self.tmp() self.emit(f"{pbal} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} %true") self.uses_ballot = True self.emit(f"{present} = OpGroupNonUniformBallotBitExtract %bool {self.cu(3)} {pbal} {safe_sg}") present_e = self.eager("%bool", present) if in_bounds is not None: both = self.tmp() self.emit(f"{both} = OpLogicalAnd %bool {in_bounds} {present_e}") src_ok = both else: src_ok = present_e shuffle_src = self.tmp() self.emit(f"{shuffle_src} = OpSelect %uint {present} {safe_sg} {sgl}") else: src_ok = in_bounds if in_bounds is not None else "%true" else: ballot = self.tmp() self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} {self.active_b()}") self.uses_ballot = True bit = self.tmp() self.emit(f"{bit} = OpGroupNonUniformBallotBitExtract %bool {self.cu(3)} {ballot} {safe_sg}") # Every lane runs the ballot, also the out-of-row lanes whose bit another lane reads (SHADER-529). active = self.eager("%bool", bit) if in_bounds is not None: both = self.tmp() self.emit(f"{both} = OpLogicalAnd %bool {in_bounds} {active}") active = both src_ok = active if src.get("k") == "vgpr": # A partial subgroup can omit the source lane; redirect it before the shuffle, not only the result. shuffle_src = self.tmp() self.emit(f"{shuffle_src} = OpSelect %uint {bit} {safe_sg} {sgl}") if src.get("k") == "vgpr": self.uses_subgroup = True sh_val = self.tmp() self.emit(f"{sh_val} = OpGroupNonUniformShuffle %uint {self.cu(3)} {src_val} {shuffle_src}") # The shuffle is read in the arms of selects below; every lane must still run it (SHADER-529). shuffled = self.eager("%uint", sh_val) else: shuffled = src_val row = self.tmp() self.emit(f"{row} = OpShiftRightLogical %uint {lane} {self.cu(4)}") row_bit = self.tmp() self.emit(f"{row_bit} = OpShiftRightLogical %uint {self.cu(row_mask)} {row}") row_one = self.tmp() self.emit(f"{row_one} = OpBitwiseAnd %uint {row_bit} {self.cu(1)}") row_on = self.tmp() self.emit(f"{row_on} = OpINotEqual %bool {row_one} {self.cu(0)}") bank_sh = self.tmp() self.emit(f"{bank_sh} = OpShiftRightLogical %uint {lane} {self.cu(2)}") bank = self.tmp() self.emit(f"{bank} = OpBitwiseAnd %uint {bank_sh} {self.cu(3)}") bank_bit = self.tmp() self.emit(f"{bank_bit} = OpShiftRightLogical %uint {self.cu(bank_mask)} {bank}") bank_one = self.tmp() self.emit(f"{bank_one} = OpBitwiseAnd %uint {bank_bit} {self.cu(1)}") bank_on = self.tmp() self.emit(f"{bank_on} = OpINotEqual %bool {bank_one} {self.cu(0)}") enabled = self.tmp() self.emit(f"{enabled} = OpLogicalAnd %bool {row_on} {bank_on}") zero = self.cu(0) src0 = self.tmp() self.emit(f"{src0} = OpSelect %uint {src_ok} {shuffled} {zero}") if base_op(ins["op"]) == "v_cvt_f32_f16": # Pass the modifiers through the lane select so the conversion applies them to the half source. args[first] = {**src, "k": "ssa", "v": src0} else: # neg/abs go to the op's reader (as for a plain VGPR source), not a 32-bit modify of the lane value, so a # 16-bit or packed op applies them to its own width. args[first] = {"k": "ssa", "v": src0} if src.get("neg"): args[first]["neg"] = True if src.get("abs"): args[first]["abs"] = True if dpp8 is not None or bound: write = enabled else: write = self.tmp() self.emit(f"{write} = OpLogicalAnd %bool {enabled} {src_ok}") if compare: # Every lane is enabled and an invalid source reads 0 (checked above), so the compare's own EXEC guard # is the only one: the mask write is the plain compare's (for v_cmpx, EXEC's). return self._insn({**ins, "args": args}) previous = self.dpp_guard self.dpp_guard = write try: return self._insn({**ins, "args": args}) finally: self.dpp_guard = previous def permute_known_selector(self, src0, src1, selector): """Emit only the selected bytes of V_PERM_B32 when S2 is known.""" if selector == 0x03020100: return src1 if selector == 0x07060504: return src0 bytes_ = [(selector >> offset) & 0xFF for offset in range(0, 32, 8)] out = self.cu(sum(0xFF << (8 * i) for i, code in enumerate(bytes_) if code > 12)) for i, code in enumerate(bytes_): if code >= 12: continue # Zero or 0xFF is already in out. byte, result = self.tmp(), self.tmp() if code < 8: src = src1 if code < 4 else src0 self.emit(f"{byte} = OpBitFieldUExtract %uint {src} {self.cu(8 * (code & 3))} {self.cu(8)}") else: src = src1 if code < 10 else src0 sign = 15 + 16 * (code & 1) self.emit(f"{byte} = OpBitFieldSExtract %uint {src} {self.cu(sign)} {self.cu(1)}") self.emit(f"{result} = OpBitFieldInsert %uint {out} {byte} {self.cu(8 * i)} {self.cu(8)}") out = result return out def relative_vgpr_ptr(self, reg, offset): """Use VGPR0 for out-of-range reads; callers also use the validity bit to guard writes.""" index, valid, safe, ptr = (self.tmp() for _ in range(4)) self.emit(f"{index} = OpIAdd %uint {self.cu(reg)} {offset}") self.emit(f"{valid} = OpULessThan %bool {index} %n256") self.emit(f"{safe} = OpSelect %uint {valid} {index} {self.cu(0)}") self.emit(f"{ptr} = OpAccessChain %_ptr_Function_uint %vgpr {safe}") return ptr, valid def _insn(self, ins): op, a, mods = base_op(ins["op"]), ins["args"], ins["mods"] if op in NOOPS or op.startswith("s_waitcnt"): return if op == "s_sendmsg" and a and self.stage == "gs": t = a[0].get("t", "") if "GS_OP_EMIT" in t: self.gs_emit(end_primitive="GS_OP_EMIT_CUT" in t) elif "GS_OP_CUT" in t: self.gs_when_active("OpEndPrimitive") elif "MSG_GS_DONE" not in t: raise Unsupported("gs sendmsg " + t) return if op == "s_sendmsg" and a and "MSG_GS_ALLOC_REQ" in a[0].get("t", "") and self.stage == "ms": # SHADER-766: use an atomic workgroup store so concurrent lanes/waves never cause # SharedMemoryDataRace-RaceOnStore, while still storing %ms_counts when a non-zero # wave (e.g. wave 1 in ms_wave_info_s3, where local_index != 0) sends the alloc. m = self.tmp() self.emit(f"{m} = OpLoad %uint %m0") self.emit(f"OpAtomicStore %ms_counts {self.cu(2)} {self.cu(0)} {m}") self.ms_alloc = True return if op == "s_sendmsg" and a and "MSG_ORDERED_PS_DONE" in a[0].get("t", ""): # End of the POPS ordered section. The fragment-shader interlock already ends at shader exit (a longer # critical section, same ordering), so nothing to do here. return if op in ("s_setreg_imm32_b32", "s_setreg_b32"): self.mode_write(op, a) return if op == "s_round_mode": if len(a) != 1 or a[0]["k"] != "imm": raise Unsupported(op + " requires an immediate") mode = a[0]["v"] if mode & 3: raise Unsupported(op + ": only nearest-even FP32 rounding is modelled") self.write_half_round_mode(op, (mode >> 2) & 3) return if op == "s_denorm_mode": raise Unsupported(op + ": denormal mode writes are not modelled") if ins.get("vcc_data_pair"): self.vcc_data_pair_op(op, a) return if op == "s_mov_b32" and self.wave64: to_mask_dst, dst_half = self._mask_b32_dst_half(a[0], a[1:2]) if to_mask_dst and self.holds_lane_mask(a[1]) and self.mask_half(a[1]) not in (None, dst_half): val = self._mask_b32_src(a[1], dst_half) self._store_b32_mask_dst(a[0], val, True, dst_half) return if op == "s_mov_b32" and a[0]["k"] == "special" and a[0]["t"] in ("exec_lo", "exec_hi") and \ (a[0]["t"] == "exec_hi" or a[1]["k"] in ("imm", "fimm") or (a[1]["k"] == "sgpr" and not self.holds_lane_mask(a[1]))): src = a[1] const = (src["v"] & 0xFFFFFFFF) if src["k"] == "imm" else None if src["k"] == "fimm": const = struct.unpack("> 32) else: raise Unsupported(op + " source") rlo, rhi = self.tmp(), self.tmp() self.emit(f"{rlo} = OpBitReverse %uint {hi}") self.emit(f"{rhi} = OpBitReverse %uint {lo}") self.store_reg("sgpr", d["r"], rlo) self.store_reg("sgpr", d["r"] + 1, rhi) elif op == "s_brev_b32": x = self.src_u(a[1]) r = self.tmp() self.emit(f"{r} = OpBitReverse %uint {x}") self.dst(a[0], r) elif op in ("s_quadmask_b32", "s_quadmask_b64", "s_bitreplicate_b64_b32"): # RDNA2 ISA SOP1, on scalar data (a lane-mask operand stays Unsupported: each invocation holds only its # own lane's bit, and these ops read the other lanes of its quad or move bits between lanes): # s_quadmask_b32: D[i] = OR of S0[4i+3:4i], i in 0..7, D[31:8] = 0; SCC = D != 0. # s_quadmask_b64: the same for 16 quads of the 64-bit S0, D[63:16] = 0; SCC = D != 0. # s_bitreplicate_b64_b32: D[2i+1] = D[2i] = S0[i], i in 0..31; SCC is not written. d, x = a[0], a[1] wide_src = op == "s_quadmask_b64" wide_dst = op != "s_quadmask_b32" mask_words = None if self.is_mask_op(x): # s_bitreplicate_b64_b32 of a 32-bit lane mask into plain scalar data (6 pipeline-library programs of # 1.0.2.1): the wave's mask word as data, then replicated as any scalar (wave_mask, as s_ff1 reads it). if op != "s_bitreplicate_b64_b32" or (d["k"] == "special" and d.get("t", "").startswith(("exec", "vcc"))): raise Unsupported(op + " on a lane mask") lo, hi = self.wave_mask(x) half = self.mask_half(x) if self.wave64 else None mask_words = [hi if half == "hi" else lo] if d["k"] == "special" and d.get("t", "").startswith(("exec", "vcc")): # VCC only in wave64: in wave32 its high word is data, which a lane mask cannot carry. if (op != "s_bitreplicate_b64_b32" or not (d["t"] == "exec" or (self.wave64 and d["t"] == "vcc")) or mask_words is not None): raise Unsupported(op + " on a lane mask") # The mask bit for lane L comes from scalar-source bit L // 2. shift, shifted, bit = (self.tmp() for _ in range(3)) lane = self.wave_lane() word = self.src_u(x) self.emit(f"{shift} = OpShiftRightLogical %uint {lane} {self.cu(1)}") self.emit(f"{shifted} = OpShiftRightLogical %uint {word} {shift}") self.emit(f"{bit} = OpBitwiseAnd %uint {shifted} {self.cu(1)}") mask = self.tmp() self.emit(f"{mask} = OpISub %uint {self.cu(0)} {bit}") self.mask_dst(d, mask) return if mask_words is not None: words = mask_words elif wide_src: lo, hi = self.src64_data(x, op) words = [lo, hi] else: words = [self.src_u(x)] if op == "s_bitreplicate_b64_b32": out = [] for hi in (0, 1): t = self.u16_half(words[0], hi) # Spread the 16 bits to the even positions, then copy each to the odd one above it. for sh, m in ((8, 0x00FF00FF), (4, 0x0F0F0F0F), (2, 0x33333333), (1, 0x55555555)): u, o, n = self.tmp(), self.tmp(), self.tmp() self.emit(f"{u} = OpShiftLeftLogical %uint {t} {self.cu(sh)}") self.emit(f"{o} = OpBitwiseOr %uint {t} {u}") self.emit(f"{n} = OpBitwiseAnd %uint {o} {self.cu(m)}") t = n u, r = self.tmp(), self.tmp() self.emit(f"{u} = OpShiftLeftLogical %uint {t} {self.cu(1)}") self.emit(f"{r} = OpBitwiseOr %uint {t} {u}") out.append(r) self.dst64_data(d, out[0], out[1], op) else: parts = [] for w in words: # Fold each nibble into its low bit, then pack bits 0, 4, ..., 28 into bits 0..7. t = w for sh in (1, 2): u, o = self.tmp(), self.tmp() self.emit(f"{u} = OpShiftRightLogical %uint {t} {self.cu(sh)}") self.emit(f"{o} = OpBitwiseOr %uint {t} {u}") t = o for sh, m in ((None, 0x11111111), (3, 0x03030303), (6, 0x000F000F), (12, 0xFF)): if sh is not None: u, o = self.tmp(), self.tmp() self.emit(f"{u} = OpShiftRightLogical %uint {t} {self.cu(sh)}") self.emit(f"{o} = OpBitwiseOr %uint {t} {u}") t = o n = self.tmp() self.emit(f"{n} = OpBitwiseAnd %uint {t} {self.cu(m)}") t = n parts.append(t) r = parts[0] if wide_src: u, o = self.tmp(), self.tmp() self.emit(f"{u} = OpShiftLeftLogical %uint {parts[1]} {self.cu(8)}") self.emit(f"{o} = OpBitwiseOr %uint {r} {u}") r = o if wide_dst: self.dst64_data(d, r, self.cu(0), op) else: self.dst(d, r) self.scc_nonzero(r) elif op == "v_cvt_f16_f32": # Low 16 bits get the f16; on GFX10 the high half is kept (partial write: Mesa ACO instr_is_16bit lists # v_cvt_f16_f32 as 16-bit for gfx_level >= GFX10). # VOP3 omod and clamp apply to the f16 (ACO: dst(F16)), in the order an RX 6800 applies them: round, omod # (f16_omod), then clamp. They were dropped until 2026-11-22. x = self.src_f(a[1]) h = self.f16_omod(self.f16_res(x), mods) if "clamp" in mods: h = self.clamp_f16_bits(h) self.write_lo16(a[0], h) elif op == "s_mulk_i32": v = a[1]["v"] & 0xFFFF k = v - 0x10000 if v & 0x8000 else v x = self.src_u(a[0]) r = self.tmp() self.emit(f"{r} = OpIMul %uint {x} {self.cu(k)}") self.dst(a[0], r) elif op == "v_readfirstlane_b32": # sD = vS of the first lane that is on in EXEC (lane 0 if none is): one value for the whole wave, so # a ballot of the active lanes, its lowest bit, and a shuffle from that lane. Until 2026-11-21 every # lane took its own value. That is the same thing only when all lanes hold the value, and after a # kill the dead lanes don't: where the result is an address (a loop that picks a descriptor per group # of lanes), they loaded from wherever their stale register pointed. # A VGPR that holds a lane mask keeps the whole wave's mask word, but only in the lanes a write # reached: an EXEC-gated v_mov_b32 leaves the other lanes' old word behind (SHADER-21 part 2), so # this lane's own copy can be a stale half's word. Hardware reads the first active lane's copy — # the broadcast below. A VGPR destination is never mask-tracked (lane_masks.put ignores VGPR # writes), so it gets the broadcast word itself, as hardware leaves it; a mask-tracked SGPR or # special destination gets this lane's bit of that word (_vgpr_mask_lane_bit, half-aware in # wave64), the per-lane value mask_src readers rely on. mask_vgpr = (a[1]["k"] == "vgpr" and a[1].get("n", 1) == 1 and ("v", a[1]["r"]) in self.cur_masks) if self.x_one_lane: # A fold that at most one lane runs and that leaves EXEC alone: this lane is the first in EXEC. self.dst(a[0], self.src_u(a[1])) return if self.wave32_fragment: self.uses_subgroup = self.uses_ballot = True v, act = self.src_u(a[1]), self.active_b() ballot, any_, lsb, first, r = (self.tmp() for _ in range(5)) self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} {act}") word = self.wave32_ballot_word(ballot) self.emit(f"{any_} = OpINotEqual %bool {word} {self.cu(0)}") self.emit(f"{lsb} = OpExtInst %uint %glsl FindILsb {word}") self.emit(f"{first} = OpSelect %uint {any_} {lsb} {self.wave32_first_running_lane()}") self.g_shuffle(r, v, first) res = r if a[0]["k"] == "vgpr" or not mask_vgpr else self._vgpr_mask_lane_bit(r, a[1]) self.dst(a[0], res) return if self.emulate: # The wave's active lanes as two mask words and every lane's value, in one round. v, act = self.src_u(a[1]), self.active_b() lo_in, hi_in = self.lane_bits(act) read, (lo, hi) = self.x_round(data=v, bits=(lo_in, hi_in)) lz, hz, l, h, h32, fh, first = (self.tmp() for _ in range(7)) self.emit(f"{lz} = OpINotEqual %bool {lo} {self.cu(0)}") self.emit(f"{hz} = OpINotEqual %bool {hi} {self.cu(0)}") self.emit(f"{l} = OpExtInst %uint %glsl FindILsb {lo}") self.emit(f"{h} = OpExtInst %uint %glsl FindILsb {hi}") self.emit(f"{h32} = OpIAdd %uint {h} {self.cu(32)}") self.emit(f"{fh} = OpSelect %uint {hz} {h32} {self.cu(0)}") self.emit(f"{first} = OpSelect %uint {lz} {l} {fh}") w = read(first) res = w if a[0]["k"] == "vgpr" or not mask_vgpr else self._vgpr_mask_lane_bit(w, a[1]) self.dst(a[0], res) return self.uses_subgroup = self.uses_ballot = True v, act = self.src_u(a[1]), self.active_b() bal, first, r = (self.tmp() for _ in range(3)) self.emit(f"{bal} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} {act}") if self.stage == "vs": lsb, any_ = self.ballot_lsb_by_words(bal, with_any=True) else: self.uses_vote = True lsb, any_ = self.tmp(), self.tmp() self.emit(f"{lsb} = OpGroupNonUniformBallotFindLSB %uint {self.cu(3)} {bal}") self.emit(f"{any_} = OpGroupNonUniformAny %bool {self.cu(3)} {act}") fallback = self.subgroup_first_running_lane() self.emit(f"{first} = OpSelect %uint {any_} {lsb} {fallback}") self.emit(f"{r} = OpGroupNonUniformShuffle %uint {self.cu(3)} {v} {first}") res = r if a[0]["k"] == "vgpr" or not mask_vgpr else self._vgpr_mask_lane_bit(r, a[1]) self.dst(a[0], res) elif op in ("image_gather4_c_lz", "image_gather4_c_lz_o"): self.image_op(op, a, mods) elif op in ("image_sample_o", "image_sample_lz_o", "image_sample_l_o", "image_sample_b_o", "image_sample_c_lz_o", "image_sample_c_o", "image_sample_c_b_o", "image_sample_cl_o", "image_sample_b_cl_o", "image_sample_c_cl_o", "image_sample_c_b_cl_o") or op in ("image_sample", "image_sample_lz", "image_sample_l", "image_sample_b", "image_sample_c_lz", "image_sample_c_l", "image_sample_c", "image_sample_c_b", "image_sample_cl", "image_sample_b_cl", "image_sample_c_cl", "image_sample_c_b_cl", "image_sample_d", "image_sample_d_cl", "image_sample_d_g16", "image_sample_d_cl_g16", "image_load", "image_gather4_lz", "image_gather4_l", "image_gather4_lz_o", "image_gather4_l_o") or op in self.GATHER4_LOD_OPS: self.image_op(op, a, mods) elif op in ("v_sin_f16", "v_cos_f16"): self._validate_unary_f16(op, ins["op"], a, mods) sel, dhi = self.opsel_bits(mods, 1) f = self.f16_in(a[1], sel[0]) t = self.turn_angle(f) r = self.tmp() self.emit(f"{r} = OpExtInst %float %glsl {'Sin' if 'sin' in op else 'Cos'} {t}") r = self.trig_exact_zero(op, f, r) r = self.clamp_f16(r, mods) self.f16_out(a[0], r, dhi, mode=False) # sin ignores MODE rounding on hardware (RX 6800, SHADER-35); cos is unmeasured, assumed like it elif op in ("v_pk_add_u16", "v_pk_add_i16", "v_pk_sub_u16", "v_pk_sub_i16", "v_pk_mul_lo_u16", "v_pk_mad_u16", "v_pk_mad_i16", "v_pk_max_u16", "v_pk_max_i16", "v_pk_min_u16", "v_pk_min_i16"): # Packed 16-bit integer ops (VOP3P, RDNA2 ISA): result half 0 takes each source's half from op_sel[i], # result half 1 from op_sel_hi[i] (defaults [0,..] and [1,..]); each half is computed on its own and # wraps to 16 bits. clamp saturates on add/sub/mad (the exact value fits in 32 bits: # 0xFFFF * 0xFFFF + 0xFFFF < 2^32, and the i16 forms within int32), whereas on mul_lo/max/min # VOP3P clamp is a hardware no-op (measured on gfx1036: v_pk_mul_lo_u16 clamp wraps modulo 2^16 # rather than saturating to 0xFFFF, and max/min results are unchanged). neg_lo/neg_hi are float-only. # Constant operands are treated as 32-bit dwords: op_sel=0 selects bits [15:0], op_sel=1 selects [31:16] # (measured on gfx1036). Positive inlines zero-extend, negative inlines sign-extend, 32-bit literals # retain their full dword; u16_half/i16_half lowers this without OpBitField{S,U}Extract at offset 16. def bits(name, default): m = next((m for m in mods if m.startswith(name + ":")), None) return [int(v) for v in m.split("[")[1].rstrip("]").split(",")] if m else default ns = 3 if "_mad_" in op else 2 sel, selhi = bits("op_sel", [0] * ns), bits("op_sel_hi", [1] * ns) if (len(sel) != ns or len(selhi) != ns or any(m != "clamp" and not m.startswith(("op_sel:", "op_sel_hi:", "neg_lo:", "neg_hi:")) for m in mods) or any(any(bits(n, [0] * ns)) for n in ("neg_lo", "neg_hi"))): raise Unsupported(op + " modifiers") kind = op[len("v_pk_"):].rsplit("_", 1)[0] # add, sub, mul_lo, mad, max, min signed = op.endswith("i16") clamp = "clamp" in mods and kind in ("add", "sub", "mad") srcs = [self.src_u(t) for t in a[1:1 + ns]] halves = [] for sl in (sel, selhi): v = [self.as_uint(self.i16_half(srcs[i], sl[i])) if signed else self.u16_half(srcs[i], sl[i]) for i in range(ns)] r = self.tmp() if kind in ("add", "sub"): self.emit(f"{r} = {'OpIAdd' if kind == 'add' else 'OpISub'} %uint {v[0]} {v[1]}") elif kind == "mul_lo": # The low 16 bits of the product as ((x << 16) * y) >> 16, not (x * y) & 0xffff: the AMD Windows driver # (26.10.1) dropped that mask when the other half of the result folded to zero (a constant half of 0: # 0x1234 * 0xaaaa came out 0x0c229e88 for 0x00009e88). xs = self.tmp() self.emit(f"{xs} = OpShiftLeftLogical %uint {v[0]} {self.cu(16)}") p16 = self.tmp() self.emit(f"{p16} = OpIMul %uint {xs} {v[1]}") self.emit(f"{r} = OpShiftRightLogical %uint {p16} {self.cu(16)}") elif kind == "mad": m = self.tmp() self.emit(f"{m} = OpIMul %uint {v[0]} {v[1]}") self.emit(f"{r} = OpIAdd %uint {m} {v[2]}") else: f = ("S" if signed else "U") + ("Max" if kind == "max" else "Min") self.emit(f"{r} = OpExtInst %uint %glsl {f} {v[0]} {v[1]}") if clamp: c = self.tmp() if signed: self.emit(f"{c} = OpExtInst %uint %glsl SClamp {r} {self.cu(0xFFFF8000)} {self.cu(0x7FFF)}") elif kind == "sub": # unsigned difference below 0 clamps to 0: compare before the wrap lt = self.tmp() self.emit(f"{lt} = OpULessThan %bool {v[0]} {v[1]}") self.emit(f"{c} = OpSelect %uint {lt} {self.cu(0)} {r}") else: self.emit(f"{c} = OpExtInst %uint %glsl UMin {r} {self.cu(0xFFFF)}") r = c r16 = self.tmp() self.emit(f"{r16} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}") halves.append(r16) hi, r = self.tmp(), self.tmp() self.emit(f"{hi} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}") self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {hi}") self.dst(a[0], r) elif op in ("v_dot2_i32_i16", "v_dot2_u32_u16", "v_dot4_u32_u8", "v_dot8_i32_i4", "v_dot8_u32_u4", "v_dot2c_i32_i16", "v_dot2c_u32_u16", "v_dot4c_u32_u8", "v_dot8c_i32_i4", "v_dot8c_u32_u4"): # Packed integer dot products (RDNA2 ISA VOP3P and VOP2 accumulating v_dot*c_*): # D = sum_{k=0..N-1} (S0.elem[k] * S1.elem[k]) + acc (acc = S2 for VOP3P, old D for VOP2) # Wrapping at 32 bits by default; clamp saturates to [INT32_MIN, INT32_MAX] (signed) or # [0, UINT32_MAX] (unsigned). For VOP3P, hardware default is op_sel:[0,0,0] and op_sel_hi:[1,1,1]; # any other op_sel/op_sel_hi, neg_lo/neg_hi, DPP/SDWA, or source neg/abs are refused. For VOP2 # v_dot*c_*, only optional clamp (VOP3 _e64) is accepted and D must be a VGPR. is_c = op in ("v_dot2c_i32_i16", "v_dot2c_u32_u16", "v_dot4c_u32_u8", "v_dot8c_i32_i4", "v_dot8c_u32_u4") if is_c: if a[0]["k"] != "vgpr": raise Unsupported(op + " destination") if any(m != "clamp" for m in mods) or ins["op"].endswith(("_dpp", "_sdwa")) or any( s.get("neg") or s.get("abs") for s in a): raise Unsupported(op + " modifiers") x, y, acc = self.src_u(a[1]), self.src_u(a[2]), self.src_u(a[0]) else: def bits(name, default): m = next((m for m in mods if m.startswith(name + ":")), None) return [int(v) for v in m.split("[")[1].rstrip("]").split(",")] if m else default other = [m for m in mods if m != "clamp" and not m.startswith(("op_sel:", "op_sel_hi:"))] if (other or ins["op"].endswith(("_dpp", "_sdwa")) or any(s.get("neg") or s.get("abs") for s in a) or bits("op_sel", [0, 0, 0]) != [0, 0, 0] or bits("op_sel_hi", [1, 1, 1]) != [1, 1, 1]): raise Unsupported(op + " modifiers") x, y, acc = self.src_u(a[1]), self.src_u(a[2]), self.src_u(a[3]) width = 16 if ("_dot2_" in op or "_dot2c_" in op) else (8 if "_dot4" in op else 4) signed = op.endswith(("i16", "i4")) clamp = "clamp" in mods if width == 8: packed = self.packed_dot4(x, y, acc, signed=False, clamp=clamp) if packed is not None: self.dst(a[0], packed) return ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract" prods = [] for off in range(0, 32, width): xe, ye, p = self.tmp(), self.tmp(), self.tmp() self.emit(f"{xe} = {ext} %uint {x} {self.cu(off)} {self.cu(width)}") self.emit(f"{ye} = {ext} %uint {y} {self.cu(off)} {self.cu(width)}") self.emit(f"{p} = OpIMul %uint {xe} {ye}") prods.append(p) if not clamp: r = prods[0] for term in prods[1:] + [acc]: nxt = self.tmp() self.emit(f"{nxt} = OpIAdd %uint {r} {term}") r = nxt elif not signed: r = prods[0] for term in prods[1:] + [acc]: w, ovf, s = self.tmp(), self.tmp(), self.tmp() self.emit(f"{w} = OpIAdd %uint {r} {term}") self.emit(f"{ovf} = OpULessThan %bool {w} {r}") self.emit(f"{s} = OpSelect %uint {ovf} {self.cu(0xFFFFFFFF)} {w}") r = s else: def sadd_carry(lhs, rhs, carry_in): w, xw, yw, ob, ov, na, st, d, nc = (self.tmp() for _ in range(9)) self.emit(f"{w} = OpIAdd %uint {lhs} {rhs}") self.emit(f"{xw} = OpBitwiseXor %uint {lhs} {w}") self.emit(f"{yw} = OpBitwiseXor %uint {rhs} {w}") self.emit(f"{ob} = OpBitwiseAnd %uint {xw} {yw}") self.emit(f"{ov} = OpUGreaterThanEqual %bool {ob} {self.cu(0x80000000)}") self.emit(f"{na} = OpUGreaterThanEqual %bool {lhs} {self.cu(0x80000000)}") self.emit(f"{st} = OpSelect %uint {na} {self.cu(0xFFFFFFFF)} {self.cu(1)}") self.emit(f"{d} = OpSelect %uint {ov} {st} {self.cu(0)}") self.emit(f"{nc} = OpIAdd %uint {carry_in} {d}") return w, nc r = prods[0] carry = self.cu(0) for term in prods[1:]: if width == 16: r, carry = sadd_carry(r, term, carry) else: nxt = self.tmp() self.emit(f"{nxt} = OpIAdd %uint {r} {term}") r = nxt r, carry = sadd_carry(r, acc, carry) nz, neg_c, bound, sat = (self.tmp() for _ in range(4)) self.emit(f"{nz} = OpINotEqual %bool {carry} {self.cu(0)}") self.emit(f"{neg_c} = OpUGreaterThanEqual %bool {carry} {self.cu(0x80000000)}") self.emit(f"{bound} = OpSelect %uint {neg_c} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}") self.emit(f"{sat} = OpSelect %uint {nz} {bound} {r}") r = sat self.dst(a[0], r) elif op in ("v_dot2_f32_f16", "v_dot2c_f32_f16"): # Half-to-float dot product (RDNA2 ISA): D = S0.lo*S1.lo + S0.hi*S1.hi + acc (acc = S2 for VOP3P # v_dot2_f32_f16, old D for VOP2 v_dot2c_f32_f16). if a[0]["k"] != "vgpr": raise Unsupported(op + " destination") if ins["op"].endswith(("_dpp", "_sdwa")) or any(s.get("neg") or s.get("abs") for s in a): raise Unsupported(op + " modifiers") if op == "v_dot2_f32_f16": def bits(name, default): m = next((m for m in mods if m.startswith(name + ":")), None) return [int(v) for v in m.split("[")[1].rstrip("]").split(",")] if m else default other = [m for m in mods if m != "clamp" and not m.startswith(("op_sel:", "op_sel_hi:", "neg_lo:", "neg_hi:"))] if other: raise Unsupported(op + " modifiers") sel = bits("op_sel", [0, 0, 0]) selhi = bits("op_sel_hi", [1, 1, 1]) nlo = bits("neg_lo", [0, 0, 0]) nhi = bits("neg_hi", [0, 0, 0]) if any(len(v) != 3 or any(b not in (0, 1) for b in v) for v in (sel, selhi, nlo, nhi)): raise Unsupported(op + " modifiers") if sel[2] != 0 or selhi[2] != 1 or nhi[2] != 0: raise Unsupported(op + " modifiers") a0 = self.f16_in(a[1], sel[0]) a1 = self.f16_in(a[1], selhi[0]) b0 = self.f16_in(a[2], sel[1]) b1 = self.f16_in(a[2], selhi[1]) if nlo[0]: t = self.tmp() self.emit(f"{t} = OpFNegate %float {a0}") a0 = t if nhi[0]: t = self.tmp() self.emit(f"{t} = OpFNegate %float {a1}") a1 = t if nlo[1]: t = self.tmp() self.emit(f"{t} = OpFNegate %float {b0}") b0 = t if nhi[1]: t = self.tmp() self.emit(f"{t} = OpFNegate %float {b1}") b1 = t acc = self.flush_f32(self.src_f(a[3])) if nlo[2]: t = self.tmp() self.emit(f"{t} = OpFNegate %float {acc}") acc = t else: if any(m != "clamp" for m in mods): raise Unsupported(op + " modifiers") a0 = self.f16_in(a[1], 0) a1 = self.f16_in(a[1], 1) b0 = self.f16_in(a[2], 0) b1 = self.f16_in(a[2], 1) acc = self.flush_f32(self.src_f(a[0])) p0, p1, s, r = (self.tmp() for _ in range(4)) self.emit(f"{p0} = OpFMul %float {a0} {b0}") self.emit(f"{p1} = OpFMul %float {a1} {b1}") self.emit(f"{s} = OpFAdd %float {p0} {p1}") self.emit(f"{r} = OpFAdd %float {s} {acc}") # Measured natively on AMD RDNA2 (gfx1036 across all ieee/dx10_clamp/denorm MODEs): # VOP3P v_dot2_f32_f16 ignores its clamp bit (hardware no-op: +3.0, -3.0, +inf, NaN stay unclamped). if op == "v_dot2c_f32_f16" and "clamp" in mods: r = self.clamp_mods(r, ["clamp"]) self.dst(a[0], self.tou(r)) elif op in ("v_pk_lshlrev_b16", "v_pk_lshrrev_b16", "v_pk_ashrrev_i16"): # Packed 16-bit shifts (VOP3P): result half h = src1 half (op_sel / op_sel_hi) shifted by src0 half & 15. # A half of a register is read with a shift and a mask, not with OpBitField{S,U}Extract at offset 16, # as for every other 16-bit half reader (docs/design.md, "16-bit high-half reads", #1506). The field # extract here is what @Dark0rz measured miscompiled on an AMD Windows driver 25.10.36 (gfx1036): the # offset came back taken mod 16, so both result halves read the low half of the source, in 5 of the # 2,000 wave32 programs of `tools/valu_fuzz.py --family f16 --seed 1`. The same programs run clean on # a second gfx1036 with driver 31.0.24002.92 (2000/2000 match), which is why this is a driver-proof # lowering and not a value change: on 200,010 inputs (0, 1, 0xFFFF, 0x10000, 0x80000000, 0xFFFFFFFF, # 0x7FFFFFFF, 0x8000 and random) BitField{S,U}Extract(x, 16, 16) equals x >> 16 with the matching # right shift, and BitFieldUExtract(x, 16, 4) equals (x >> 16) & 15. def bits(name, default): m = next((m for m in mods if m.startswith(name + ":")), None) if m is None: return default try: body = m.split("[", 1)[1] if not body.endswith("]"): raise Unsupported(op + " modifiers") return [int(v) for v in body[:-1].split(",")] except (IndexError, ValueError): raise Unsupported(op + " modifiers") from None if "clamp" in mods: raise Unsupported(op + " clamp") if (any(not m.startswith(("op_sel:", "op_sel_hi:", "neg_lo:", "neg_hi:")) for m in mods) or any(s.get("neg") or s.get("abs") for s in a)): raise Unsupported(op + " modifiers") sel, selhi = bits("op_sel", [0, 0]), bits("op_sel_hi", [1, 1]) neg_lo, neg_hi = bits("neg_lo", [0, 0]), bits("neg_hi", [0, 0]) # a three-entry list (op_sel:[1,0,0], as in tests/semantic/fixtures/disasm/ps_ops6.s) is read by its first # two entries, as before #3853 sel, selhi, neg_lo, neg_hi = (v[:2] if len(v) == 3 else v for v in (sel, selhi, neg_lo, neg_hi)) if (len(sel) != 2 or len(selhi) != 2 or len(neg_lo) != 2 or len(neg_hi) != 2 or any(b not in (0, 1) for b in sel + selhi) or any(neg_lo) or any(neg_hi)): raise Unsupported(op + " modifiers") sh_src, val_src = self.src_u(a[1]), self.src_u(a[2]) signed = op.endswith("i16") halves = [] for h, sl in ((0, sel), (1, selhi)): amt, val, am, r16 = self.tmp(), self.tmp(), self.tmp(), self.tmp() if sl[0]: half = self.tmp() self.emit(f"{half} = OpShiftRightLogical %uint {sh_src} {self.cu(16)}") self.emit(f"{amt} = OpBitwiseAnd %uint {half} {self.cu(15)}") else: self.emit(f"{amt} = OpBitFieldUExtract %uint {sh_src} {self.cu(0)} {self.cu(4)}") if sl[1]: # The high half: x >> 16 already extends it the right way for the shift that follows. right = "OpShiftRightArithmetic" if signed else "OpShiftRightLogical" self.emit(f"{val} = {right} %uint {val_src} {self.cu(16)}") else: ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract" self.emit(f"{val} = {ext} %uint {val_src} {self.cu(0)} {self.cu(16)}") k = {"v_pk_lshlrev_b16": "OpShiftLeftLogical", "v_pk_lshrrev_b16": "OpShiftRightLogical", "v_pk_ashrrev_i16": "OpShiftRightArithmetic"}[op] self.emit(f"{am} = {k} %uint {val} {amt}") self.emit(f"{r16} = OpBitwiseAnd %uint {am} {self.cu(0xFFFF)}") halves.append(r16) hi, r = self.tmp(), self.tmp() self.emit(f"{hi} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}") self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {hi}") self.dst(a[0], r) elif op in ("v_sin_f32", "v_cos_f32"): # RDNA takes the angle in turns: reduce in turns, then sin/cos(x * 2*pi). x = self.src_f(a[1]) t = self.turn_angle(x) r = self.tmp() self.emit(f"{r} = OpExtInst %float %glsl {'Sin' if 'sin' in op else 'Cos'} {t}") r = self.trig_exact_zero(op, x, r) self.dst(a[0], self.tou(self.clamp_mods(r, mods))) elif op == "v_rndne_f32": x = self.src_f(a[1]) r = self.tmp() self.emit(f"{r} = OpExtInst %float %glsl RoundEven {x}") self.dst(a[0], self.tou(self.clamp_mods(r, mods))) elif op in ("v_madak_f32", "v_madmk_f32"): # madak D = S0 * S1 + K, printed `vdst, src0, vsrc1, K`; madmk D = S0 * K + S1, printed # `vdst, src0, K, vsrc1`. In print order both are a[1] * a[2] + a[3]. Until 2026-11-21 madmk read # a[3] as the factor, so it computed S0 * S1 + K. # Like v_mad_f32, literal MAD flushes operands, the rounded product and the final sum # (Mesa ACO aco_ir.h, fp_denorm); host Vulkan denormal handling must not decide the result. x, y, z = (self.src_f(t) for t in a[1:4]) x, y, z = self.flush_f32(x), self.flush_f32(y), self.flush_f32(z) m, r = self.tmp(), self.tmp() self.emit(f"{m} = OpFMul %float {x} {y}") self.emit(f"{r} = OpFAdd %float {self.flush_f32(m)} {z}") self.dst(a[0], self.tou(self.flush_f32(r))) elif op == "v_bfi_b32": mask = None if "sdwa_sel" in a[1] else self.imm_val(a[1]) y, z = (self.src_u(t) for t in a[2:4]) if mask == 0: self.dst(a[0], z) return if mask == 0xFFFFFFFF: self.dst(a[0], y) return if mask is not None: offset = (mask & -mask).bit_length() - 1 width = mask.bit_count() if mask == ((1 << width) - 1) << offset: # RDNA takes the field from its final bit positions; SPIR-V takes its low bits. if offset: shifted = self.tmp() self.emit(f"{shifted} = OpShiftRightLogical %uint {y} {self.cu(offset)}") y = shifted r = self.tmp() self.emit(f"{r} = OpBitFieldInsert %uint {z} {y} {self.cu(offset)} {self.cu(width)}") self.dst(a[0], r) return x, n = self.cu(mask), self.cu(~mask) else: x, n = self.src_u(a[1]), self.tmp() self.emit(f"{n} = OpNot %uint {x}") p, q, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{p} = OpBitwiseAnd %uint {x} {y}") self.emit(f"{q} = OpBitwiseAnd %uint {n} {z}") self.emit(f"{r} = OpBitwiseOr %uint {p} {q}") self.dst(a[0], r) elif op in ("v_lshl_or_b32", "v_lshl_add_u32", "v_add_lshl_u32", "v_or3_b32", "v_xor3_b32", "v_add3_u32", "v_and_or_b32_"): x, y, z = (self.src_u(t) for t in a[1:4]) r = self.tmp() if op in ("v_lshl_or_b32", "v_lshl_add_u32"): s, m = self.tmp(), self.tmp() self.emit(f"{m} = OpBitwiseAnd %uint {y} {self.cu(31)}") self.emit(f"{s} = OpShiftLeftLogical %uint {x} {m}") self.emit(f"{r} = {'OpBitwiseOr' if op == 'v_lshl_or_b32' else 'OpIAdd'} %uint {s} {z}") elif op == "v_add_lshl_u32": s, m = self.tmp(), self.tmp() self.emit(f"{s} = OpIAdd %uint {x} {y}") self.emit(f"{m} = OpBitwiseAnd %uint {z} {self.cu(31)}") self.emit(f"{r} = OpShiftLeftLogical %uint {s} {m}") else: k = {"v_or3_b32": "OpBitwiseOr", "v_xor3_b32": "OpBitwiseXor", "v_add3_u32": "OpIAdd"}[op] s = self.tmp() self.emit(f"{s} = {k} %uint {x} {y}") self.emit(f"{r} = {k} %uint {s} {z}") self.dst(a[0], r) elif op == "v_pack_b32_f16": # dst = f16(src0) | f16(src1) << 16, each taken from the low half (op_sel picks high halves). # neg/abs act on the selected 16-bit half of each source as plain bit moves, abs (clear bit 15) first and # neg (xor bit 15) second: on an AMD Radeon Graphics RDNA2 iGPU (gfx1036) ``-v0``, ``|v0|``, and ``-|v0|`` # were measured with 1,088 raw kernels across wave32 and wave64 (0 mismatches; #1548 SHADER-260). abs clears # bit 15, neg flips it, and -|v0| sets bit 15 across all edge floats and NaNs; under IEEE 0 sNaN payloads are # kept, under IEEE 1 they are quieted (SHADER-190). The translator moves the bits, which is exact under IEEE 0. sel = next((m for m in mods if m.startswith("op_sel:")), "op_sel:[0,0,0]") sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] halves = [] for i, src in enumerate(a[1:3]): u = self.src_h(src) m = self.u16_half(u, sb[i]) if src.get("abs"): # The ISA defines ABS on a float operand as |S|, clearing the sign bit (bit 15), applied before # neg. Measured natively on gfx1036 across 1,088 raw kernels: clears bit 15 on all values. a_ = self.tmp() self.emit(f"{a_} = OpBitwiseAnd %uint {m} {self.cu(0x7FFF)}") m = a_ if src.get("neg"): # SHADER-260, measured on gfx1036: a `neg` on this instruction flips the sign bit of the half it # packs, before any quieting (0x7c01 -> 0xfc01 in IEEE mode 0, -> 0xfe01 in mode 1), in either # half and with op_sel. It used to be refused along with every other modifier. n = self.tmp() self.emit(f"{n} = OpBitwiseXor %uint {m} {self.cu(0x8000)}") m = n halves.append(m) hi, r = self.tmp(), self.tmp() self.emit(f"{hi} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}") self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {hi}") self.dst(a[0], r) elif op in ("v_cmp_class_f32", "v_cmpx_class_f32", "v_cmp_class_f16", "v_cmpx_class_f16"): # f64 goes to cmp_class_f64 below (the operand checks test_cmp_class_f64 pins); cmp_class's own f64 # branch, merged later, has no operand-form checks. self.cmp_class(a, exec_only=op.startswith("v_cmpx_"), ty=op.rsplit("_", 1)[1], mods=mods) elif op in ("v_ffbl_b32", "v_ffbh_u32", "s_flbit_i32_b32") or \ (op == "s_ff1_i32_b32" and not self.holds_lane_mask(a[1])): # of a lane mask: further down x = self.lane_mask_word(a[1]) if op == "s_flbit_i32_b32" and self.holds_lane_mask(a[1]) else self.src_u(a[1]) r = self.tmp() if op in ("v_ffbl_b32", "s_ff1_i32_b32"): # Index of lowest set bit, -1 (0xFFFFFFFF) if none: FindILsb has the same convention. ri = self.tmp() self.emit(f"{ri} = OpExtInst %int %glsl FindILsb {self.as_int(x)}") self.emit(f"{r} = OpBitcast %uint {ri}") else: # Leading-zero count from the MSB side, -1 if zero: 31 - FindUMsb(x), with FindUMsb(0) = -1. m, z, d = self.tmp(), self.tmp(), self.tmp() self.emit(f"{m} = OpExtInst %int %glsl FindUMsb {x}") mu = self.tmp() self.emit(f"{mu} = OpBitcast %uint {m}") self.emit(f"{d} = OpISub %uint {self.cu(31)} {mu}") self.emit(f"{z} = OpIEqual %bool {x} {self.cu(0)}") self.emit(f"{r} = OpSelect %uint {z} {self.cu(0xFFFFFFFF)} {d}") self.dst(a[0], r) elif op in ("image_get_resinfo", "image_load_mip", "image_store", "image_atomic_cmpswap") \ or op in self.IMG_ATOMICS or op in self.IMG_ATOMICS_EXTRA: self.image_misc(op, a, mods) elif op in ("v_cubema_f32", "v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32"): # Cube face selection (standard table): major axis Z if |z|>=|x| and |z|>=|y|, else Y if |y|>=|x|, # else X. face: +X0 -X1 +Y2 -Y3 +Z4 -Z5 # +X: sc=-z tc=-y -X: sc=+z tc=-y +Y: sc=+x tc=+z -Y: sc=+x tc=-z +Z: sc=+x tc=-y -Z: sc=-x tc=-y # cubema = 2 * (signed major-axis coordinate) x, y, z = (self.src_f(t) for t in a[1:4]) ax, ay, az = (self.tmp() for _ in range(3)) for t, s in ((ax, x), (ay, y), (az, z)): self.emit(f"{t} = OpExtInst %float %glsl FAbs {s}") zx, zy, zmaj, yx, ymaj = (self.tmp() for _ in range(5)) self.emit(f"{zx} = OpFOrdGreaterThanEqual %bool {az} {ax}") self.emit(f"{zy} = OpFOrdGreaterThanEqual %bool {az} {ay}") self.emit(f"{zmaj} = OpLogicalAnd %bool {zx} {zy}") self.emit(f"{yx} = OpFOrdGreaterThanEqual %bool {ay} {ax}") nz = self.tmp() self.emit(f"{nz} = OpLogicalNot %bool {zmaj}") self.emit(f"{ymaj} = OpLogicalAnd %bool {nz} {yx}") def neg(v): n = self.tmp() self.emit(f"{n} = OpFNegate %float {v}") return n def lt0(v): b = self.tmp() self.emit(f"{b} = OpFOrdLessThan %bool {v} %f0") return b def pick(zv, yv, xv): t1, t2 = self.tmp(), self.tmp() self.emit(f"{t1} = OpSelect %float {ymaj} {yv} {xv}") self.emit(f"{t2} = OpSelect %float {zmaj} {zv} {t1}") return t2 def sel(c, t, f): r = self.tmp() self.emit(f"{r} = OpSelect %float {c} {t} {f}") return r xn, yn, zn = lt0(x), lt0(y), lt0(z) if op == "v_cubema_f32": # Measured natively on RDNA2 (gfx1036, wave32 & wave64, all 4 IEEE/DX10_CLAMP modes): # v_cubema_f32 returns +0.0 (never -0.0) whenever the selected major axis is ±0.0, # while preserving NaNs and signed non-zero major-axis values. m = pick(z, y, x) is_z, m2, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{is_z} = OpFOrdEqual %bool {m} %f0") self.emit(f"{m2} = OpFMul %float {m} {self.fconst(2.0)}") self.emit(f"{r} = OpSelect %float {is_z} %f0 {m2}") elif op == "v_cubeid_f32": r = pick(sel(zn, self.fconst(5.0), self.fconst(4.0)), sel(yn, self.fconst(3.0), self.fconst(2.0)), sel(xn, self.fconst(1.0), self.fconst(0.0))) elif op == "v_cubesc_f32": r = pick(sel(zn, neg(x), x), x, sel(xn, z, neg(z))) else: r = pick(neg(y), sel(yn, neg(z), z), neg(y)) self.dst(a[0], self.tou(self.clamp_mods(r, mods))) elif op in ("v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32"): # Count of set bits in the mask for lanes below this one (lo: lanes 0-31, hi: lanes 32-63), plus src1. self.uses_subgroup = True if self.holds_lane_mask(a[1]): # a real mask: the lanes below this one that are set in it half = self.mask_half(a[1]) if self.wave64 else None idx = (1 if half == "hi" else 0) if half is not None else (0 if op.endswith("lo_u32_b32") else 1) mask = self.wave_mask(a[1])[idx] acc = self.src_u(a[2]) else: mask, acc = self.src_u(a[1]), self.src_u(a[2]) lane, rel, below, inrange, one, m1, cnt, r = (self.tmp() for _ in range(8)) wl = self.wave_lane() self.emit(f"{lane} = OpCopyObject %uint {wl}") if op.endswith("lo_u32_b32"): self.emit(f"{rel} = OpCopyObject %uint {lane}") else: self.emit(f"{rel} = OpISub %uint {lane} {self.cu(32)}") # bits below `rel`, clamped to [0, 32] (mask shift count to < 32 so OpShiftLeftLogical # never executes SPIR-V UB on the discarded side of OpSelect). rel_s = self.tmp() self.emit(f"{inrange} = OpULessThan %bool {rel} {self.cu(32)}") self.emit(f"{rel_s} = OpBitwiseAnd %uint {rel} {self.cu(31)}") self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {rel_s}") self.emit(f"{m1} = OpISub %uint {one} {self.cu(1)}") big = self.tmp() # lo: lanes >= 32 count all 32 bits; hi: lanes < 32 count none (rel wraps above 32). self.emit(f"{big} = OpSelect %uint {inrange} {m1} " f"{self.cu(0xFFFFFFFF) if op.endswith('lo_u32_b32') else self.cu(0)}") if op.endswith("hi_u32_b32"): lt32, fixed = self.tmp(), self.tmp() self.emit(f"{lt32} = OpULessThan %bool {lane} {self.cu(32)}") self.emit(f"{fixed} = OpSelect %uint {lt32} {self.cu(0)} {big}") big = fixed self.emit(f"{below} = OpBitwiseAnd %uint {mask} {big}") self.emit(f"{cnt} = OpBitCount %uint {below}") self.emit(f"{r} = OpIAdd %uint {cnt} {acc}") self.dst(a[0], r) elif op == "v_bfrev_b32": x = self.src_u(a[1]) r = self.tmp() self.emit(f"{r} = OpBitReverse %uint {x}") self.dst(a[0], r) elif op == "v_bfm_b32": w, o = self.src_u(a[1]), self.src_u(a[2]) width = None if "sdwa_sel" in a[1] else self.imm_val(a[1]) offset = None if "sdwa_sel" in a[2] else self.imm_val(a[2]) if width is not None: bits = (1 << (width & 31)) - 1 if offset is not None: self.dst(a[0], self.cu(bits << (offset & 31))) return if bits == 0: self.dst(a[0], self.cu(0)) return mask = self.cu(bits) else: wm, one, mask = (self.tmp() for _ in range(3)) self.emit(f"{wm} = OpBitwiseAnd %uint {w} {self.cu(31)}") self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {wm}") self.emit(f"{mask} = OpISub %uint {one} {self.cu(1)}") if offset is None: shift = self.tmp() self.emit(f"{shift} = OpBitwiseAnd %uint {o} {self.cu(31)}") elif offset & 31: shift = self.cu(offset & 31) else: self.dst(a[0], mask) return r = self.tmp() self.emit(f"{r} = OpShiftLeftLogical %uint {mask} {shift}") self.dst(a[0], r) elif op in ("s_bcnt1_i32_b64", "s_bcnt1_i32_b32", "s_bcnt0_i32_b64", "s_bcnt0_i32_b32"): if self.holds_lane_mask(a[1]): lo, hi = self.wave_mask(a[1]) if op.endswith("b32") and self.wave64: half = self.mask_half(a[1]) if half is not None: lo, hi = (hi if half == "hi" else lo), self.cu(0) elif op.endswith("b64") and a[1]["k"] == "sgpr" and a[1].get("n") == 2: lo, hi = self.load_reg("sgpr", a[1]["r"]), self.load_reg("sgpr", a[1]["r"] + 1) elif op.endswith("b64") and a[1]["k"] == "imm": lo, hi = self.src64_data(a[1], op) # a constant's own 64 bits, as s_ff1_i32_b64 reads them elif op.endswith("b64") and a[1]["k"] == "special" and a[1].get("t") == "vcc": # Plain 64-bit scalar data in VCC (not a lane mask): read both %vcc and %vcc_hi, as bitcmp does. lo, hi = self.tmp(), self.tmp() self.emit(f"{lo} = OpLoad %uint %vcc") self.emit(f"{hi} = OpLoad %uint %vcc_hi") elif op.endswith("b64") and a[1]["k"] == "special" and a[1].get("t") == "null": lo, hi = self.cu(0), self.cu(0) else: lo, hi = (self.mask_src(a[1]), self.cu(0)) if op.endswith("b64") else (self.src_u(a[1]), self.cu(0)) if "bcnt0" in op: nlo = self.tmp() self.emit(f"{nlo} = OpNot %uint {lo}") lo = nlo if op.endswith("b64"): nhi = self.tmp() self.emit(f"{nhi} = OpNot %uint {hi}") hi = nhi c1, c2, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{c1} = OpBitCount %uint {lo}") if op.endswith("b64") or "bcnt1" in op: # s_bcnt1_i32_b32 counts the high word too: for a lane mask of a wave32 shader running in a 64-lane # subgroup (graphics stages can't request 32) the other lanes' bits are there; otherwise hi is 0. # s_bcnt0_i32_b32 counts zeros of the low word only (~0 in the high word would add 32). self.emit(f"{c2} = OpBitCount %uint {hi}") self.emit(f"{r} = OpIAdd %uint {c1} {c2}") else: r = c1 self.dst(a[0], r) z = self.tmp() self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") self.emit(f"OpStore %scc {z}") elif op in ("v_add_nc_i32", "v_sub_nc_i32") or \ (op in ("v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32") and "clamp" in mods): # 32-bit add/sub without carry out. The VOP3 clamp bit saturates an integer result (GFX9+: LLVM selects # uaddsat/usubsat to v_add/sub_nc_u32 clamp and saddsat/ssubsat to v_add/sub_nc_i32 clamp): unsigned to # [0, 0xFFFFFFFF], signed to [0x80000000, 0x7FFFFFFF]. Without clamp the result wraps. x, y = self.src_u(a[1]), self.src_u(a[2]) if op == "v_subrev_nc_u32": x, y = y, x sub = "_sub" in op r = self.tmp() if op.endswith("_u32"): s_, w, c = self.tmp(), self.tmp(), self.tmp() self.emit(f"{s_} = {'OpISubBorrow' if sub else 'OpIAddCarry'} %umul {x} {y}") self.emit(f"{w} = OpCompositeExtract %uint {s_} 0") self.emit(f"{c} = OpCompositeExtract %uint {s_} 1") sat = self.cu(0) if sub else self.cu(0xFFFFFFFF) self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(c)} {sat} {w}") else: w = self.tmp() self.emit(f"{w} = {'OpISub' if sub else 'OpIAdd'} %uint {x} {y}") if "clamp" in mods: # Signed overflow: add when x and y share a sign that w lacks; sub when x and y differ in sign # and w differs from x. The saturated value follows x's sign. t1, t2, ov, neg, lim = (self.tmp() for _ in range(5)) if sub: self.emit(f"{t1} = OpBitwiseXor %uint {x} {y}") else: self.emit(f"{t1} = OpBitwiseXor %uint {y} {w}") self.emit(f"{t2} = OpBitwiseXor %uint {x} {w}") ovm = self.tmp() self.emit(f"{ovm} = OpBitwiseAnd %uint {t1} {t2}") self.emit(f"{ov} = OpSLessThan %bool {self.as_int(ovm)} {self.as_int(self.cu(0))}") self.emit(f"{neg} = OpSLessThan %bool {self.as_int(x)} {self.as_int(self.cu(0))}") self.emit(f"{lim} = OpSelect %uint {neg} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}") self.emit(f"{r} = OpSelect %uint {ov} {lim} {w}") else: r = w self.dst(a[0], r) elif op == "v_subrev_nc_u32": x, y = self.src_u(a[1]), self.src_u(a[2]) r = self.tmp() self.emit(f"{r} = OpISub %uint {y} {x}") self.dst(a[0], r) elif op in ("s_flbit_i32_b64", "s_flbit_i32_i64"): # Leading-bit count of a 64-bit value, from bit 63 down: b64 counts the zeros before the first 1; i64 # counts the bits before the first one that differs from the sign bit (b64 of ~S0 when S0 < 0). -1 when # there is none (0, and for i64 also -1). SCC is not written. x = a[1] if self.holds_lane_mask(x): if op != "s_flbit_i32_b64" or not self.wave64: raise Unsupported(op + " of a lane mask") lo, hi = self.wave_mask(x) elif x["k"] == "special" and x.get("t") == "vcc": lo, hi = self.tmp(), self.tmp() self.emit(f"{lo} = OpLoad %uint %vcc") self.emit(f"{hi} = OpLoad %uint %vcc_hi") elif x["k"] == "special" and x.get("t") == "null": lo, hi = self.cu(0), self.cu(0) elif x["k"] == "sgpr" and x.get("n") == 2: lo, hi = self.load_reg("sgpr", x["r"]), self.load_reg("sgpr", x["r"] + 1) elif x["k"] == "imm": v = x["v"] & 0xFFFFFFFFFFFFFFFF lo, hi = self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) else: raise Unsupported(op + " source") if op == "s_flbit_i32_i64": neg, nlo, nhi, slo, shi = (self.tmp() for _ in range(5)) self.emit(f"{neg} = OpSLessThan %bool {self.as_int(hi)} {self.as_int(self.cu(0))}") self.emit(f"{nlo} = OpNot %uint {lo}") self.emit(f"{nhi} = OpNot %uint {hi}") self.emit(f"{slo} = OpSelect %uint {neg} {nlo} {lo}") self.emit(f"{shi} = OpSelect %uint {neg} {nhi} {hi}") lo, hi = slo, shi mh, ml, mhu, mlu, ch, cl, hz, lz, r0, r = (self.tmp() for _ in range(10)) self.emit(f"{mh} = OpExtInst %int %glsl FindUMsb {hi}") self.emit(f"{ml} = OpExtInst %int %glsl FindUMsb {lo}") self.emit(f"{mhu} = OpBitcast %uint {mh}") self.emit(f"{mlu} = OpBitcast %uint {ml}") self.emit(f"{ch} = OpISub %uint {self.cu(31)} {mhu}") # zeros above the top 1 of the high half self.emit(f"{cl} = OpISub %uint {self.cu(63)} {mlu}") # 32 + zeros above the top 1 of the low half self.emit(f"{hz} = OpIEqual %bool {hi} {self.cu(0)}") self.emit(f"{lz} = OpIEqual %bool {lo} {self.cu(0)}") self.emit(f"{r0} = OpSelect %uint {lz} {self.cu(0xFFFFFFFF)} {cl}") self.emit(f"{r} = OpSelect %uint {hz} {r0} {ch}") self.dst(a[0], r) elif op in ("s_ff1_i32_b64", "s_ff1_i32_b32", "s_ff0_i32_b64", "s_ff0_i32_b32"): # Lowest set (ff1) or zero (ff0) bit of a mask, -1 if none. For a lane mask that is the wave's first lane. if self.holds_lane_mask(a[1]): lo, hi = self.wave_mask(a[1]) if op.endswith("b32") and self.wave64: half = self.mask_half(a[1]) if half is not None: lo, hi = (hi if half == "hi" else lo), self.cu(0) elif op.endswith("b32"): # A b32 source is a plain scalar value, not a lane mask. lo, hi = self.src_u(a[1]), self.cu(0) elif a[1]["k"] == "imm": # A 64-bit constant's own 64 bits (inline negative constants sign-extend, literals zero-extend), # matching s_bcnt0/1_i32_b64 and src64_data. lo, hi = self.src64_data(a[1], op) elif a[1]["k"] == "special" and a[1].get("t") == "vcc": lo, hi = self.tmp(), self.tmp() self.emit(f"{lo} = OpLoad %uint %vcc") self.emit(f"{hi} = OpLoad %uint %vcc_hi") elif a[1]["k"] == "special" and a[1].get("t") == "null": lo, hi = self.cu(0), self.cu(0) elif a[1]["k"] != "sgpr" or a[1].get("n") != 2: lo, hi = self.mask_src(a[1]), self.cu(0) else: lo, hi = self.load_reg("sgpr", a[1]["r"]), self.load_reg("sgpr", a[1]["r"] + 1) if "ff0" in op: nlo = self.tmp() self.emit(f"{nlo} = OpNot %uint {lo}") lo = nlo if op.endswith("b64"): nhi = self.tmp() self.emit(f"{nhi} = OpNot %uint {hi}") hi = nhi l, h, hp, lz, r = (self.tmp() for _ in range(5)) self.emit(f"{l} = OpExtInst %int %glsl FindILsb {self.as_int(lo)}") if op.endswith("b64"): self.emit(f"{h} = OpExtInst %int %glsl FindILsb {self.as_int(hi)}") hu = self.tmp() self.emit(f"{hu} = OpBitcast %uint {h}") hz = self.tmp() self.emit(f"{hz} = OpIEqual %bool {hi} {self.cu(0)}") self.emit(f"{hp} = OpIAdd %uint {hu} {self.cu(32)}") hsel = self.tmp() self.emit(f"{hsel} = OpSelect %uint {hz} {self.cu(0xFFFFFFFF)} {hp}") self.emit(f"{lz} = OpIEqual %bool {lo} {self.cu(0)}") lu = self.tmp() self.emit(f"{lu} = OpBitcast %uint {l}") self.emit(f"{r} = OpSelect %uint {lz} {hsel} {lu}") else: lu = self.tmp() self.emit(f"{lu} = OpBitcast %uint {l}") r = lu self.dst(a[0], r) elif op == "ds_swizzle_b32": self.swizzle(a, mods, ins) elif op in ("v_cvt_f64_i32", "v_cvt_f64_u32"): self.uses_f64 = True src = self.src_u(a[1]) result = self.tmp() if op == "v_cvt_f64_i32": self.emit(f"{result} = OpConvertSToF %double {self.as_int(src)}") else: self.emit(f"{result} = OpConvertUToF %double {src}") # SHADER-721 follow-up, measured on gfx1036 through tools/hw_oracle (wave32 and wave64 identical on # every case, tools/f64_omod_probe.py): a binary64 destination ignores mul:2/mul:4/div:2 while # denorm_mode_16_64 = 3, which is the game's MODE, and applies them only with IEEE=0 and 16/64-bit # denormals flushed. clamp applies in every MODE, so only it is passed on. self.dst_f64(a[0], result, [m for m in mods if m == "clamp"], op) elif op in ("v_trunc_f64", "v_ceil_f64", "v_rndne_f64", "v_floor_f64"): if len(a) != 2 or a[0]["k"] != "vgpr" or a[0].get("n") != 2: raise Unsupported(op + " operands") dst, src = a if (ins["op"].endswith(("_dpp", "_sdwa")) or any(mod not in ("mul:2", "mul:4", "div:2", "clamp") for mod in mods)): raise Unsupported(op + " modifier") self.uses_f64 = True if src["k"] in ("vgpr", "sgpr") and src.get("n") == 2: low = self.load_reg(src["k"], src["r"]) high = self.load_reg(src["k"], src["r"] + 1) elif src["k"] == "fimm": bits = struct.unpack("> 32) elif src.get("f64_literal") and self.f64_literal_one_dword(src): # One literal dword: bits 63:32 of the constant (docs/design.md, f64 literal sources). low, high = self.cu(0), self.cu(src["v"] & 0xFFFFFFFF) elif src["k"] == "imm" and (-16 <= src["v"] <= 64 or src.get("f64_literal")): # An inline integer is sign-extended; a wider literal is the whole constant. bits = src["v"] & 0xFFFFFFFFFFFFFFFF low, high = self.cu(bits & 0xFFFFFFFF), self.cu(bits >> 32) else: raise Unsupported(op + " source") if src.get("abs"): mag = self.tmp() self.emit(f"{mag} = OpBitwiseAnd %uint {high} {self.cu(0x7FFFFFFF)}") high = mag if src.get("neg"): negated = self.tmp() self.emit(f"{negated} = OpBitwiseXor %uint {high} {self.cu(0x80000000)}") high = negated pair, value, result = self.tmp(), self.tmp(), self.tmp() self.emit(f"{pair} = OpCompositeConstruct %v2uint_d {low} {high}") self.emit(f"{value} = OpBitcast %double {pair}") rounding = {"v_trunc_f64": "Trunc", "v_ceil_f64": "Ceil", "v_rndne_f64": "RoundEven", "v_floor_f64": "Floor"} self.emit(f"{result} = OpExtInst %double %glsl {rounding[op]} {value}") words = self.tmp() self.emit(f"{words} = OpBitcast %v2uint_d {result}") rounded = [] for index in range(2): word = self.tmp() self.emit(f"{word} = OpCompositeExtract %uint {words} {index}") rounded.append(word) # A NaN and a subnormal are not left to the driver's rounding. Vulkan lets it return any NaN for a NaN # operand (NVIDIA 620.70 and llvmpipe quiet a signalling one) and, with no DenormPreserve for 64 bits, # read a subnormal as zero (llvmpipe does); the hardware returns a NaN unchanged and keeps subnormals # (docs/design.md). So a NaN's words pass through, and a subnormal's result is built from its sign and # the op: a zero of its sign, or 1 with its sign where the op rounds that sign away from zero (ceil of a # positive one, floor of a negative one). Every other source takes the driver's result. def emit_u(line): t = self.tmp() self.emit(f"{t} = {line}") return t exponent = emit_u(f"OpBitwiseAnd %uint {high} {self.cu(0x7FF00000)}") fraction_high = emit_u(f"OpBitwiseAnd %uint {high} {self.cu(0x000FFFFF)}") fraction = emit_u(f"OpBitwiseOr %uint {fraction_high} {low}") has_fraction = emit_u(f"OpINotEqual %bool {fraction} {self.cu(0)}") exponent_ones = emit_u(f"OpIEqual %bool {exponent} {self.cu(0x7FF00000)}") exponent_zero = emit_u(f"OpIEqual %bool {exponent} {self.cu(0)}") is_nan = emit_u(f"OpLogicalAnd %bool {exponent_ones} {has_fraction}") is_subnormal = emit_u(f"OpLogicalAnd %bool {exponent_zero} {has_fraction}") sign = emit_u(f"OpBitwiseAnd %uint {high} {self.cu(0x80000000)}") subnormal_high = sign if op in ("v_ceil_f64", "v_floor_f64"): negative = emit_u(f"OpINotEqual %bool {sign} {self.cu(0)}") one, zero = self.cu(0x3FF00000), self.cu(0) magnitude = emit_u(f"OpSelect %uint {negative} " + (f"{zero} {one}" if op == "v_ceil_f64" else f"{one} {zero}")) subnormal_high = emit_u(f"OpBitwiseOr %uint {sign} {magnitude}") special = emit_u(f"OpLogicalOr %bool {is_nan} {is_subnormal}") special_low = emit_u(f"OpSelect %uint {is_nan} {low} {self.cu(0)}") special_high = emit_u(f"OpSelect %uint {is_nan} {high} {subnormal_high}") out = [emit_u(f"OpSelect %uint {special} {special_low} {rounded[0]}"), emit_u(f"OpSelect %uint {special} {special_high} {rounded[1]}")] # Only clamp: measured on the same gfx1036 part, mul:2/mul:4/div:2 on these four do nothing while # f64 denormals are kept, and clamp applies (v_trunc/ceil/rndne_f64 -> 1.0 and -> 0.0). clamp_only = [m for m in mods if m == "clamp"] if clamp_only: # The clamp works on the double: the same path as before, on the selected value. chosen_pair = emit_u(f"OpCompositeConstruct %v2uint_d {out[0]} {out[1]}") chosen = emit_u(f"OpBitcast %double {chosen_pair}") modified = emit_u(f"OpBitcast %v2uint_d {self.clamp_mods_f64(chosen, clamp_only)}") out = [emit_u(f"OpCompositeExtract %uint {modified} {index}") for index in range(2)] for index in range(2): self.dst({"k": "vgpr", "r": dst["r"] + index, "n": 1}, out[index]) elif op in ("v_add_f64", "v_cvt_f32_f64", "v_rcp_f64", "v_rsq_f64", "v_sqrt_f64"): # f64: register pairs as doubles (shaderFloat64). neg/abs modifiers apply to the double. def f64(sv): lo, hi = self.f64_source_words(sv, op) v2, d = self.tmp(), self.tmp() self.emit(f"{v2} = OpCompositeConstruct %v2uint_d {lo} {hi}") self.emit(f"{d} = OpBitcast %double {v2}") if sv.get("abs"): t = self.tmp() self.emit(f"{t} = OpExtInst %double %glsl FAbs {d}") d = t if sv.get("neg"): t = self.tmp() self.emit(f"{t} = OpFNegate %double {d}") d = t return d self.uses_f64 = True if op == "v_cvt_f32_f64": x = f64(a[1]) r = self.tmp() self.emit(f"{r} = OpFConvert %float {x}") self.dst(a[0], self.tou(self.clamp_mods(r, mods))) else: if op == "v_add_f64": x, y = f64(a[1]), f64(a[2]) r = self.tmp() self.emit(f"{r} = OpFAdd %double {x} {y}") if self.round_mode: # MODE rounds the sum itself; the mods are applied to the rounded value at the shared site # below, which passes only `clamp`. m2, mlo, mhi, n2, rd = (self.tmp() for _ in range(5)) self.emit(f"{m2} = OpBitcast %v2uint_d {r}") self.emit(f"{mlo} = OpCompositeExtract %uint {m2} 0") self.emit(f"{mhi} = OpCompositeExtract %uint {m2} 1") mlo, mhi = self.f64_add_mode(x, y, r, mlo, mhi) self.emit(f"{n2} = OpCompositeConstruct %v2uint_d {mlo} {mhi}") self.emit(f"{rd} = OpBitcast %double {n2}") r = rd elif op == "v_rcp_f64": x = f64(a[1]) r = self.tmp() self.emit(f"{r} = OpFDiv %double {self.dconst(1.0)} {x}") elif op == "v_rsq_f64": x = f64(a[1]) r = self.tmp() self.emit(f"{r} = OpExtInst %double %glsl InverseSqrt {x}") else: # v_sqrt_f64 x = f64(a[1]) r = self.tmp() self.emit(f"{r} = OpExtInst %double %glsl Sqrt {x}") # VOP3 f64 ops carry HasClamp and HasOMod (LLVM VOPProfile, f64 is a modifier type). The omod is # dropped here because RDNA2 ignores it: measured with tools/hw_oracle raw wave32 and wave64 # kernels on a gfx1036 iGPU, mul:2/mul:4/div:2 of v_add_f64, v_rcp_f64, v_rsq_f64 and v_sqrt_f64 # apply only with MODE.IEEE off and f64 denormals flushed, and never while denormals are kept # (IEEE on or off); clamp applies in every one of those runs. Same for the four rounding ops # above. The measurements are written up in the "v_add_f64 output modifiers" row of docs/design.md; # this is SHADER-721, the binary64 counterpart of the f16 #1970. self.dst_f64(a[0], r, [m for m in mods if m == "clamp"], op) elif op in ("v_cmp_class_f64", "v_cmpx_class_f64"): self.cmp_class_f64(op, a, exec_only=op == "v_cmpx_class_f64", mods=mods) elif op in ("image_bvh_intersect_ray", "image_bvh64_intersect_ray"): self.image_bvh(op, a, mods) elif op == "s_bfm_b64" and not self.wave64: # In 32-lane waves a 64-bit result can't be a lane mask: D = ((1 << (S0 & 63)) - 1) << (S1 & 63) is 64-bit # data, as for s_lshl_b64 (lane_masks.step leaves it data too). The pipeline library's wave32 compute # programs build the first two words of an S# this way (3,342 times `s_bfm_b64 s[N:N+1], 2, 54`, then # s_mov_b64 of the other two). SCC is not written. Every case seen has constant operands. size, off = self.imm_val(a[1]), self.imm_val(a[2]) if size is None or off is None: raise Unsupported(op + " with a run-time operand in wave32") self.mov64(a[0], {"k": "imm", "v": (((1 << (size & 63)) - 1) << (off & 63)) & 0xFFFFFFFFFFFFFFFF}) elif op == "s_bfm_b64": # D = ((1 << size) - 1) << offset as a lane mask: in the per-lane model this lane's bit is # offset <= lane < offset + size (size/offset taken mod 64). size, off = self.src_u(a[1]), self.src_u(a[2]) lane = self.wave_lane() sz, of, end, ge, lt, on, m = (self.tmp() for _ in range(7)) self.emit(f"{sz} = OpBitwiseAnd %uint {size} {self.cu(63)}") self.emit(f"{of} = OpBitwiseAnd %uint {off} {self.cu(63)}") self.emit(f"{end} = OpIAdd %uint {of} {sz}") self.emit(f"{ge} = OpUGreaterThanEqual %bool {lane} {of}") self.emit(f"{lt} = OpULessThan %bool {lane} {end}") self.emit(f"{on} = OpLogicalAnd %bool {ge} {lt}") self.emit(f"{m} = OpSelect %uint {on} {self.cu(0xFFFFFFFF)} {self.cu(0)}") self.mask_dst(a[0], m) elif op in ("s_pack_ll_b32_b16", "s_pack_lh_b32_b16", "s_pack_hh_b32_b16"): # D = {S1 half, S0 half}: the low result half comes from S0, the high one from S1; the letters name the # half taken from each (l = bits 15:0, h = bits 31:16), S0 first. SCC is not written. val = None x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) if x_val is not None and y_val is not None: lo_v = (x_val >> 16) if op == "s_pack_hh_b32_b16" else (x_val & 0xFFFF) hi_v = ((y_val & 0xFFFF) << 16) if op == "s_pack_ll_b32_b16" else (y_val & 0xFFFF0000) val = (lo_v | hi_v) & 0xFFFFFFFF x, y = self.src_u(a[1]), self.src_u(a[2]) lo, hi, r = self.tmp(), self.tmp(), self.tmp() if op == "s_pack_hh_b32_b16": self.emit(f"{lo} = OpShiftRightLogical %uint {x} {self.cu(16)}") else: self.emit(f"{lo} = OpBitwiseAnd %uint {x} {self.cu(0xFFFF)}") if op == "s_pack_ll_b32_b16": self.emit(f"{hi} = OpShiftLeftLogical %uint {y} {self.cu(16)}") else: self.emit(f"{hi} = OpBitwiseAnd %uint {y} {self.cu(0xFFFF0000)}") self.emit(f"{r} = OpBitwiseOr %uint {lo} {hi}") self.dst(a[0], r) if val is not None and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: self.sgpr_imm[a[0]["r"]] = val elif op == "s_bfm_b32": # D = ((1 << (S0 & 31)) - 1) << (S1 & 31): an ordinary scalar value val = None x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) if x_val is not None and y_val is not None: w_v = x_val & 31 o_v = y_val & 31 val = (((1 << w_v) - 1) << o_v) & 0xFFFFFFFF x, y = self.src_u(a[1]), self.src_u(a[2]) w, o, one, sh, mm, r = (self.tmp() for _ in range(6)) self.emit(f"{w} = OpBitwiseAnd %uint {x} {self.cu(31)}") self.emit(f"{o} = OpBitwiseAnd %uint {y} {self.cu(31)}") self.emit(f"{sh} = OpShiftLeftLogical %uint {self.cu(1)} {w}") self.emit(f"{mm} = OpISub %uint {sh} {self.cu(1)}") self.emit(f"{r} = OpShiftLeftLogical %uint {mm} {o}") self.dst(a[0], r) if val is not None and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: self.sgpr_imm[a[0]["r"]] = val elif op == "ds_bpermute_b32": # vD = vData from lane ((vAddr + offset) / 4) mod 32: a subgroup shuffle (no LDS memory involved). d, ad, dat = a[0], self.src_u(a[1]), self.src_u(a[2]) off = self.mod_int(mods, "offset", 0) s1, ln, src, lane = (self.tmp() for _ in range(4)) self.emit(f"{s1} = OpIAdd %uint {ad} {self.cu(off)}") self.emit(f"{ln} = OpShiftRightLogical %uint {s1} {self.cu(2)}") self.emit(f"{src} = OpBitwiseAnd %uint {ln} {self.cu(31)}") self.sub_lane(lane) if self.wave64: # RDNA2 ISA 10.4.4: each half-wave permutes independently. half, full_src = self.tmp(), self.tmp() self.emit(f"{half} = OpBitwiseAnd %uint {lane} {self.cu(32)}") self.emit(f"{full_src} = OpBitwiseOr %uint {half} {src}") src = full_src self.ds_lane_read(d, dat, src, lane) elif op == "ds_permute_b32": self.ds_permute(a, mods) elif op.startswith("ds_") and self.stage == "gs": self.gs_ds(op, a, mods) elif op.startswith("ds_"): self.lds_op(op, a, mods) elif op == "s_barrier": # Workgroup execution barrier; AMD orders LDS, buffer and image memory across the barrier via s_waitcnt # before it, so include UniformMemory | WorkgroupMemory | ImageMemory (0x948; plus MakeAvailable|MakeVisible # = 0x6948 under VulkanMemoryModel, upgraded in assemble() too if a later glc/dlc op enables VMM). if self.stage not in ("cs", "ms"): raise Unsupported("s_barrier outside compute") self.uses_barrier = True self.uses_s_barrier = True bar_sem = 0x6948 if self.uses_vmm else 0x948 if self.emulate_inline: self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(bar_sem)}") self.x_dirty = set() return if self.emulate or self.bar_rounds: # The wave waits in the scheduler until every wave not done waits too (assemble). self.emit("OpStore %x_bar %true") self.x_split() return self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(bar_sem)}") elif op == "v_readlane_b32": # sD = vS[lane]: a subgroup shuffle from that lane (the result is uniform). if self.cur_uniform_readlane: # SHADER-10: wave64_halves proved the VGPR holds one value in every lane (written from scalars # and constants while EXEC was the launch mask), so any lane has it: this lane's own copy. The # shuffle would index a lane the 32-lane subgroup of a VS/PS/GS may not have (lane >= 32). self.dst(a[0], self.src_u(a[1])) return slot = lane_masks.lane_slot(a[1], a[2], wave64=self.wave64) if slot and (slot[1:] in self.scalar_spills or (id(self.cur_ins) in self.spill_readlanes and slot[1:] in self.parked)): # Pure scalar-spill VGPR or definite mixed-VGPR spill reload: load from the parked scalar slot # instead of shuffling from a lane that may be inactive (small fragment waves, discards, or # wave64 lanes >= 32 on 32-wide subgroups). self.dst(a[0], self.load_reg("sgpr", self.parked[slot[1:]])) return if slot in self.cur_masks: # A lane mask parked there by v_writelane (a saved EXEC, when the shader ran out of SGPRs): this # lane's bit comes back, from the slot the write kept it in. The shuffle would hand every lane # the bit of the one lane the mask was parked in. self.dst(a[0], self.load_reg("sgpr", self.parked[slot[1:]])) return self.uses_subgroup = True v, ln = self.src_u(a[1]), self.src_u(a[2]) m, r = self.tmp(), self.tmp() # RDNA2: wave64 uses S1[5:0] (mod 64); wave32 uses S1[4:0] (mod 32). Masking wave32 with 63 left # lane selects 32..63 pointing past a 32-wide subgroup (SHADER-52 / FUZZ-7). self.emit(f"{m} = OpBitwiseAnd %uint {ln} {self.cu(63 if self.wave64 else 31)}") if self.emulate: self.g_shuffle(r, v, m) else: # Guard against shuffling from an unlaunched/absent lane in a partial subgroup: redirect absent # targets to the wave's first running lane so the result stays wave-uniform and never triggers UB. self.uses_ballot = True phys = self.wave_source_lane(m) bal, present, safe_phys = (self.tmp() for _ in range(3)) self.emit(f"{bal} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} %true") self.emit(f"{present} = OpGroupNonUniformBallotBitExtract %bool {self.cu(3)} {bal} {phys}") if self.wave32_fragment: fallback = self.wave_source_lane(self.wave32_first_running_lane(bal)) else: fallback = self.subgroup_first_running_lane(bal) self.emit(f"{safe_phys} = OpSelect %uint {present} {phys} {fallback}") self.emit(f"{r} = OpGroupNonUniformShuffle %uint {self.cu(3)} {v} {safe_phys}") self.dst(a[0], r) elif op == "v_writelane_b32": # vD[lane] = sS: only the named lane changes (independent of EXEC, as on hardware). slot = lane_masks.lane_slot(a[0], a[2], wave64=self.wave64) if slot and slot[1:] in self.scalar_spills: self.store_reg("sgpr", self.parked[slot[1:]], self.src_u(a[1])) return self.uses_subgroup = True val, ln = self.src_u(a[1]), self.src_u(a[2]) if slot and slot[1:] in self.parked: # somewhere a mask is fetched back from this lane: keep ours self.store_reg("sgpr", self.parked[slot[1:]], val) me, m, eq, old, r = (self.tmp() for _ in range(5)) if self.stage in ("cs", "ms") or self.wave32_fragment: # Wave32 fragments use their lane within either half of a wider Vulkan subgroup. self.emit(f"{me} = OpCopyObject %uint {self.wave_lane()}") else: self.emit(f"{me} = OpLoad %uint %sg_lane") self.emit(f"{m} = OpBitwiseAnd %uint {ln} {self.cu(63 if self.wave64 else 31)}") self.emit(f"{eq} = OpIEqual %bool {me} {m}") p = self.reg_ptr("vgpr", a[0]["r"]) self.emit(f"{old} = OpLoad %uint {p}") self.emit(f"{r} = OpSelect %uint {eq} {val} {old}") self.emit(f"OpStore {p} {r}") elif op in self.BUFFER_SUB16: self.buffer_sub(op, a, mods) elif op.startswith("buffer_store_dword") or op in ("buffer_store_format_x", "buffer_store_format_xy", "buffer_store_format_xyz", "buffer_store_format_xyzw", "buffer_store_format_d16_x", "buffer_store_format_d16_xy", "buffer_store_format_d16_xyz", "buffer_store_format_d16_xyzw", "buffer_store_format_d16_hi_x"): self.buffer_store(op, a, mods) elif op in ("v_permlanex16_b32", "v_permlane16_b32"): # Lane l reads lane sel[l & 15] of (x16: the other 16-lane half of its row; plain: the same half). # The 4-bit selectors for lanes 0-7 are in src1, for lanes 8-15 in src2. self.uses_subgroup = True v, s1, s2 = self.src_u(a[1]), self.src_u(a[2]), self.src_u(a[3]) lane, within, hi8, sh, nib1, nib2, nib, row, src = (self.tmp() for _ in range(9)) self.sub_lane(lane) self.emit(f"{within} = OpBitwiseAnd %uint {lane} {self.cu(15)}") self.emit(f"{hi8} = OpUGreaterThanEqual %bool {within} {self.cu(8)}") w7 = self.tmp() self.emit(f"{w7} = OpBitwiseAnd %uint {within} {self.cu(7)}") self.emit(f"{sh} = OpIMul %uint {w7} {self.cu(4)}") self.emit(f"{nib1} = OpBitFieldUExtract %uint {s1} {sh} {self.cu(4)}") self.emit(f"{nib2} = OpBitFieldUExtract %uint {s2} {sh} {self.cu(4)}") self.emit(f"{nib} = OpSelect %uint {hi8} {nib2} {nib1}") half = self.tmp() self.emit(f"{half} = OpBitwiseAnd %uint {lane} {self.cu(0xFFFFFFF0)}") if op == "v_permlanex16_b32": self.emit(f"{row} = OpBitwiseXor %uint {half} {self.cu(16)}") else: self.emit(f"{row} = OpCopyObject %uint {half}") self.emit(f"{src} = OpBitwiseOr %uint {row} {nib}") # op_sel:[FI, BOUND_CTRL] (LLVM: llvm.amdgcn.permlane16 -> op_sel bits 0, 1). # FI=1 fetches the value of a source lane that is off in EXEC. FI=0 does not: the destination keeps its # old value (BOUND_CTRL=0) or gets 0 (BOUND_CTRL=1). A source lane that is on gives its value either # way. Measured on RDNA2 (issue #374). (fi, bc), _ = self.opsel_bits(mods, 2) if fi: # FI=1 fetches the value of a source lane that is off in EXEC. On a native subgroup, redirect # unlaunched/absent lanes first so OpGroupNonUniformShuffle never targets a non-running lane. if self.emulate: r = self.tmp() self.g_shuffle(r, v, src) self.dst(a[0], r) else: ballot, present, safe_phys, shuf, mask, r = (self.tmp() for _ in range(6)) physical_src = self.wave_source_lane(src) physical_self = self.subgroup_lane() self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal %c3 %true") self.emit(f"{present} = OpGroupNonUniformBallotBitExtract %bool %c3 {ballot} {physical_src}") self.emit(f"{safe_phys} = OpSelect %uint {present} {physical_src} {physical_self}") self.emit(f"{shuf} = OpGroupNonUniformShuffle %uint %c3 {v} {safe_phys}") self.uses_subgroup = self.uses_ballot = True self.emit(f"{mask} = OpSelect %uint {present} {self.cu(0xFFFFFFFF)} {self.cu(0)}") self.emit(f"{r} = OpBitwiseAnd %uint {shuf} {mask}") self.dst(a[0], r, eager=True) elif self.emulate: r = self.tmp() self.g_shuffle(r, v, src) sa, ok, r2 = (self.tmp() for _ in range(3)) self.emit(f"{sa} = OpSelect %uint {self.active_b()} {self.cu(1)} {self.cu(0)}") act = self.tmp() self.g_shuffle(act, sa, src) self.emit(f"{ok} = OpINotEqual %bool {act} {self.cu(0)}") if bc: self.emit(f"{r2} = OpSelect %uint {ok} {r} {self.cu(0)}") else: ptr, old = (self.tmp() for _ in range(2)) # a plain load, as dst() does: a VGPR that nothing has written yet is not an undefined value self.emit(f"{ptr} = OpAccessChain %_ptr_Function_uint %vgpr {self.cu(a[0]['r'])}") self.emit(f"{old} = OpLoad %uint {ptr}") self.emit(f"{r2} = OpSelect %uint {ok} {r} {old}") self.dst(a[0], r2) else: # A source lane that is off in EXEC (or absent from a workgroup smaller than the wave) is off too; # a shuffle from it is undefined, so redirect it first, as ds_lane_read does. The scalar select that # applied FI/BOUND_CTRL can become a short-circuiting ternary in MSL, moving the ballot and both # shuffles into divergent control flow: on MoltenVK 1.4.2 and on MoltenVK main at SPIRV-Cross # aa217aeb the FI=0 lanes then read the source lane's value instead of keeping the old one (#5895). # Combine with bitwise masks instead, as #932 does for ds_bpermute: the ballot and the shuffles run # before lane predication. sa, ballot, present, safe_phys, r, act, got, ok, mask = (self.tmp() for _ in range(9)) self.emit(f"{sa} = OpSelect %uint {self.active_b()} {self.cu(1)} {self.cu(0)}") physical_src = self.wave_source_lane(src) physical_self = self.subgroup_lane() self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal %c3 %true") self.emit(f"{present} = OpGroupNonUniformBallotBitExtract %bool %c3 {ballot} {physical_src}") self.emit(f"{safe_phys} = OpSelect %uint {present} {physical_src} {physical_self}") self.emit(f"{r} = OpGroupNonUniformShuffle %uint %c3 {v} {safe_phys}") self.emit(f"{act} = OpGroupNonUniformShuffle %uint %c3 {sa} {safe_phys}") self.emit(f"{got} = OpINotEqual %bool {act} {self.cu(0)}") self.emit(f"{ok} = OpLogicalAnd %bool {present} {got}") self.uses_subgroup = self.uses_ballot = True self.emit(f"{mask} = OpSelect %uint {ok} {self.cu(0xFFFFFFFF)} {self.cu(0)}") if bc: r2 = self.tmp() self.emit(f"{r2} = OpBitwiseAnd %uint {r} {mask}") else: ptr, old, keep, newv, oldv, r2 = (self.tmp() for _ in range(6)) self.emit(f"{ptr} = OpAccessChain %_ptr_Function_uint %vgpr {self.cu(a[0]['r'])}") # as dst() does self.emit(f"{old} = OpLoad %uint {ptr}") self.emit(f"{keep} = OpNot %uint {mask}") self.emit(f"{newv} = OpBitwiseAnd %uint {r} {mask}") self.emit(f"{oldv} = OpBitwiseAnd %uint {old} {keep}") self.emit(f"{r2} = OpBitwiseOr %uint {newv} {oldv}") self.dst(a[0], r2, eager=True) elif op.startswith("buffer_load_dword"): self.buffer_load(op, a, mods) elif op in self.BUFFER_SUB: self.buffer_load_sub(op, a, mods) elif op in ("buffer_load_format_x", "buffer_load_format_xy", "buffer_load_format_xyz", "buffer_load_format_xyzw", "buffer_load_format_d16_x", "buffer_load_format_d16_xy", "buffer_load_format_d16_xyz", "buffer_load_format_d16_xyzw", "buffer_load_format_d16_hi_x"): self.buffer_load_format(op, a, mods) elif op in ("tbuffer_load_format_x", "tbuffer_load_format_xy", "tbuffer_load_format_xyz", "tbuffer_load_format_xyzw", "tbuffer_load_format_d16_x", "tbuffer_load_format_d16_xy", "tbuffer_load_format_d16_xyz", "tbuffer_load_format_d16_xyzw"): self.buffer_load_format(op[1:], a, mods, fixed_fmt=self.mtbuf_format(op, mods)) elif op in ("tbuffer_store_format_x", "tbuffer_store_format_xy", "tbuffer_store_format_xyz", "tbuffer_store_format_xyzw", "tbuffer_store_format_d16_x", "tbuffer_store_format_d16_xy", "tbuffer_store_format_d16_xyz", "tbuffer_store_format_d16_xyzw"): self.buffer_store(op[1:], a, mods, fixed_fmt=self.mtbuf_format(op, mods)) elif op in ("s_bitset0_b64", "s_bitset1_b64"): # D[S0 & 63] = 0 / 1 in the SGPR pair D (D is both source and destination); SCC is not written. The pair # is 64-bit data (as for s_lshl_b64); a pair that lane_masks.py marks as a lane mask stays Unsupported. d = a[0] if d["k"] != "sgpr" or d.get("n") != 2 or self.holds_lane_mask(d): raise Unsupported(op + " destination") b = self.src_u(a[1]) m, low, bit, sh = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{m} = OpBitwiseAnd %uint {b} {self.cu(63)}") self.emit(f"{low} = OpULessThan %bool {m} {self.cu(32)}") self.emit(f"{bit} = OpBitwiseAnd %uint {m} {self.cu(31)}") self.emit(f"{sh} = OpShiftLeftLogical %uint {self.cu(1)} {bit}") for half in (0, 1): old, want, mk, r = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{old} = OpCopyObject %uint {self.load_reg('sgpr', d['r'] + half)}") # The bit lands in this half when (m < 32) matches (half == 0). if half == 0: self.emit(f"{mk} = OpSelect %uint {low} {sh} {self.cu(0)}") else: self.emit(f"{mk} = OpSelect %uint {low} {self.cu(0)} {sh}") if op == "s_bitset1_b64": self.emit(f"{r} = OpBitwiseOr %uint {old} {mk}") else: self.emit(f"{want} = OpNot %uint {mk}") self.emit(f"{r} = OpBitwiseAnd %uint {old} {want}") self.store_reg("sgpr", d["r"] + half, r) elif op in ("s_bitset0_b32", "s_bitset1_b32"): # sD = sD & ~(1 << (src & 31)) / sD | (1 << (src & 31)); sD is both source and destination, SCC unchanged. # When sD holds a lane mask (exec_lo/hi, vcc_lo/hi, or a mask SGPR), mutate only the addressed lane's bit. b = self.lane_mask_word(a[1]) if self.holds_lane_mask(a[1]) else self.src_u(a[1]) m = self.tmp() self.emit(f"{m} = OpBitwiseAnd %uint {b} {self.cu(31)}") if self.holds_lane_mask(a[0]): half = self.mask_half(a[0]) if self.wave64 else None tgt = m if half == "hi": tgt = self.tmp() self.emit(f"{tgt} = OpIAdd %uint {m} {self.cu(32)}") hit, r = self.tmp(), self.tmp() self.emit(f"{hit} = OpIEqual %bool {self.wave_lane()} {tgt}") old = (self.exec_value() if (a[0]["k"] == "special" and a[0].get("t", "").startswith("exec")) else self.mask_src(a[0], wide=False)) self.emit(f"{r} = OpSelect %uint {hit} {self.cu(0xFFFFFFFF if op == 's_bitset1_b32' else 0)} {old}") self.put_mask(a[0], r, half) if self.wave64 and a[0]["k"] == "special" and a[0].get("t") == "vcc_hi": self.emit(f"OpStore %vcc_hi {r}") else: sh, old, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{sh} = OpShiftLeftLogical %uint {self.cu(1)} {m}") self.emit(f"{old} = OpCopyObject %uint {self.src_u(a[0])}") if op == "s_bitset1_b32": self.emit(f"{r} = OpBitwiseOr %uint {old} {sh}") else: n = self.tmp() self.emit(f"{n} = OpNot %uint {sh}") self.emit(f"{r} = OpBitwiseAnd %uint {old} {n}") self.dst(a[0], r) elif op in ("v_mul_hi_u32_u24", "v_mul_hi_i32_i24"): # High 32 bits of the 48-bit product of the low 24 bits of each source: zero-extended for u24, # sign-extended from bit 23 for i24 (RDNA2 ISA). The low 32 bits are v_mul_u32_u24 / v_mul_i32_i24. x, y = self.src_u(a[1]), self.src_u(a[2]) signed = op == "v_mul_hi_i32_i24" xs, ys, s, r = (self.tmp() for _ in range(4)) ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract" self.emit(f"{xs} = {ext} %uint {x} {self.cu(0)} {self.cu(24)}") self.emit(f"{ys} = {ext} %uint {y} {self.cu(0)} {self.cu(24)}") if signed: xi, yi, hi = self.as_int(xs), self.as_int(ys), self.tmp() self.emit(f"{s} = OpSMulExtended %smul {xi} {yi}") self.emit(f"{hi} = OpCompositeExtract %int {s} 1") self.emit(f"{r} = OpBitcast %uint {hi}") self.uses_smul = True else: self.emit(f"{s} = OpUMulExtended %umul {xs} {ys}") self.emit(f"{r} = OpCompositeExtract %uint {s} 1") self.dst(a[0], r) elif op in ("v_mul_i32_i24", "v_mad_i32_i24"): # signed 24-bit operands (sign-extended from bit 23), low 32 bits of the product (+ src2 for mad) x, y = self.src_u(a[1]), self.src_u(a[2]) xs, ys, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{xs} = OpBitFieldSExtract %uint {x} {self.cu(0)} {self.cu(24)}") self.emit(f"{ys} = OpBitFieldSExtract %uint {y} {self.cu(0)} {self.cu(24)}") self.emit(f"{r} = OpIMul %uint {xs} {ys}") if op == "v_mad_i32_i24": r2 = self.tmp() self.emit(f"{r2} = OpIAdd %uint {r} {self.src_u(a[3])}") r = r2 self.dst(a[0], r) elif op == "v_lerp_u8": if "clamp" in mods: raise Unsupported(op + " clamp") x, y, z = (self.src_u(t) for t in a[1:4]) # Per byte, x + y = 2*(x & y) + (x ^ y). Clear each low bit before the shift so the # next byte cannot leak in. An odd sum rounds up only when the corresponding bit of z is 1. # Both additions fit in each byte: even the rounded average is at most 255. different, shared, even, half, round_bits, rounding, average, r = (self.tmp() for _ in range(8)) self.emit(f"{different} = OpBitwiseXor %uint {x} {y}") self.emit(f"{shared} = OpBitwiseAnd %uint {x} {y}") self.emit(f"{even} = OpBitwiseAnd %uint {different} {self.cu(0xFEFEFEFE)}") self.emit(f"{half} = OpShiftRightLogical %uint {even} {self.cu(1)}") self.emit(f"{round_bits} = OpBitwiseAnd %uint {different} {z}") self.emit(f"{rounding} = OpBitwiseAnd %uint {round_bits} {self.cu(0x01010101)}") self.emit(f"{average} = OpIAdd %uint {shared} {half}") self.emit(f"{r} = OpIAdd %uint {average} {rounding}") self.dst(a[0], r) elif op == "v_xnor_b32": x, y = self.src_u(a[1]), self.src_u(a[2]) t, r = self.tmp(), self.tmp() self.emit(f"{t} = OpBitwiseXor %uint {x} {y}") self.emit(f"{r} = OpNot %uint {t}") self.dst(a[0], r) elif op == "v_alignbyte_b32": # (({src0, src1} as 64 bits) >> (8 * (src2 & 3))) low 32 bits # (32 - b) & 31 keeps the left shift below 32 when b == 0; that result is discarded by the OpSelect. sh_val = self.imm_val(a[3]) if sh_val is not None: sel = sh_val & 3 if sel == 0: self.dst(a[0], self.src_u(a[2])) else: hi_, lo_ = self.src_u(a[1]), self.src_u(a[2]) b = sel * 8 inv = 32 - b a1, b1, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {self.cu(b)}") self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {self.cu(inv)}") self.emit(f"{r} = OpBitwiseOr %uint {a1} {b1}") self.dst(a[0], r) else: hi_, lo_, sh = (self.src_u(t) for t in a[1:4]) m, b, inv0, inv, a1, b1, nz, r0, r = (self.tmp() for _ in range(9)) self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(3)}") self.emit(f"{b} = OpShiftLeftLogical %uint {m} {self.cu(3)}") self.emit(f"{inv0} = OpISub %uint {self.cu(32)} {b}") self.emit(f"{inv} = OpBitwiseAnd %uint {inv0} {self.cu(31)}") self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {b}") self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {inv}") self.emit(f"{r0} = OpBitwiseOr %uint {a1} {b1}") self.emit(f"{nz} = OpINotEqual %bool {b} {self.cu(0)}") self.emit(f"{r} = OpSelect %uint {nz} {r0} {lo_}") self.dst(a[0], r) elif op == "v_swap_b32": # exchange two VGPRs (active lanes only, through dst) x, y = self.src_u(a[0]), self.src_u(a[1]) xc, yc = self.tmp(), self.tmp() self.emit(f"{xc} = OpCopyObject %uint {x}") self.emit(f"{yc} = OpCopyObject %uint {y}") self.dst(a[0], yc) self.dst(a[1], xc) elif op == "s_abs_i32": x_val = self.imm_val(a[1]) if x_val is not None: xi = x_val if x_val < 0x80000000 else x_val - 0x100000000 val = abs(xi) & 0xFFFFFFFF r = self.cu(val) self.dst(a[0], r) if a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: self.sgpr_imm[a[0]["r"]] = val self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}") return x = self.src_u(a[1]) i, ab, r, nz, sc = (self.tmp() for _ in range(5)) self.emit(f"{i} = OpBitcast %int {x}") self.emit(f"{ab} = OpExtInst %int %glsl SAbs {i}") self.emit(f"{r} = OpBitcast %uint {ab}") self.emit(f"{nz} = OpINotEqual %bool {r} {self.cu(0)}") self.emit(f"{sc} = OpSelect %uint {nz} {self.cu(1)} {self.cu(0)}") self.dst(a[0], r) self.emit(f"OpStore %scc {sc}") elif op in ("s_sext_i32_i8", "s_sext_i32_i16"): # D = S0's low byte / half, sign-extended to 32 bits; SCC is not written. x_val = self.imm_val(a[1]) if x_val is not None: if op.endswith("i8"): b = x_val & 0xFF val = ((b ^ 0x80) - 0x80) & 0xFFFFFFFF else: h = x_val & 0xFFFF val = ((h ^ 0x8000) - 0x8000) & 0xFFFFFFFF r = self.cu(val) self.dst(a[0], r) if a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: self.sgpr_imm[a[0]["r"]] = val return x = self.src_u(a[1]) r = self.tmp() self.emit(f"{r} = OpBitFieldSExtract %uint {x} {self.cu(0)} {self.cu(8 if op.endswith('i8') else 16)}") self.dst(a[0], r) elif op in ("v_ffbh_i32", "s_flbit_i32"): # bit position counted from the MSB of the first bit that differs from the sign bit; -1 if none. # s_flbit_i32 is the scalar form (it does not write SCC). x = self.as_int(self.lane_mask_word(a[1]) if op == "s_flbit_i32" and self.holds_lane_mask(a[1]) else self.src_u(a[1])) f, none, sub, r = (self.tmp() for _ in range(4)) self.emit(f"{f} = OpExtInst %int %glsl FindSMsb {x}") self.emit(f"{none} = OpSLessThan %bool {f} {self.as_int(self.cu(0))}") self.emit(f"{sub} = OpISub %int {self.as_int(self.cu(31))} {f}") subu = self.tmp() self.emit(f"{subu} = OpBitcast %uint {sub}") self.emit(f"{r} = OpSelect %uint {none} {self.cu(0xFFFFFFFF)} {subu}") self.dst(a[0], r) elif op.startswith(("v_cmp_", "v_cmpx_")) and op.endswith(("_u64", "_i64")) and \ op.split("_")[2] in ("lt", "le", "gt", "ge"): # 64-bit ordered compare: high words decide (signed for i64), equal high words fall back to the low words. # v_cmpx (GFX10) writes EXEC only. cmpx = op.startswith("v_cmpx_") d, x, y = (None, a[-2], a[-1]) if cmpx else (a[0], a[1], a[2]) cond, signed = op.split("_")[2], op.endswith("_i64") def pair64(sv): if sv["k"] == "vgpr" and sv.get("n") == 2: return self.load_reg(sv["k"], sv["r"]), self.load_reg(sv["k"], sv["r"] + 1) return self.src64_i64(sv, op) if signed else self.src64_data(sv, op) (x0, x1), (y0, y1) = pair64(x), pair64(y) hi_op = {"lt": "LessThan", "le": "LessThan", "gt": "GreaterThan", "ge": "GreaterThan"}[cond] lo_op = {"lt": "ULessThan", "le": "ULessThanEqual", "gt": "UGreaterThan", "ge": "UGreaterThanEqual"}[cond] hx, hy = (self.as_int(x1), self.as_int(y1)) if signed else (x1, y1) hlt, heq, llt, both, res, r = (self.tmp() for _ in range(6)) self.emit(f"{hlt} = Op{'S' if signed else 'U'}{hi_op} %bool {hx} {hy}") self.emit(f"{heq} = OpIEqual %bool {x1} {y1}") self.emit(f"{llt} = Op{lo_op} %bool {x0} {y0}") self.emit(f"{both} = OpLogicalAnd %bool {heq} {llt}") self.emit(f"{res} = OpLogicalOr %bool {hlt} {both}") ra = self.tmp() self.emit(f"{ra} = OpLogicalAnd %bool {res} {self.active_b()}") # inactive lanes write 0 if cmpx: self.emit(f"OpStore %active {ra}") self.uses_active = True return self.emit(f"{r} = OpSelect %uint {ra} {self.cu(0xFFFFFFFF)} {self.cu(0)}") self.mask_dst(d, r) elif op == "v_alignbit_b32": # (({src0, src1} as 64 bits) >> (src2 & 31)) low 32 bits # (32 - m) & 31 keeps the left shift below 32 when m == 0; that result is discarded by the OpSelect. sh_val = self.imm_val(a[3]) if sh_val is not None: m_val = sh_val & 31 if m_val == 0: self.dst(a[0], self.src_u(a[2])) else: hi_, lo_ = self.src_u(a[1]), self.src_u(a[2]) inv_val = 32 - m_val a1, b1, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {self.cu(m_val)}") self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {self.cu(inv_val)}") self.emit(f"{r} = OpBitwiseOr %uint {a1} {b1}") self.dst(a[0], r) else: hi_, lo_, sh = (self.src_u(t) for t in a[1:4]) m, inv0, inv, a1, b1, nz, r0, r = (self.tmp() for _ in range(8)) self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(31)}") self.emit(f"{inv0} = OpISub %uint {self.cu(32)} {m}") self.emit(f"{inv} = OpBitwiseAnd %uint {inv0} {self.cu(31)}") self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {m}") self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {inv}") self.emit(f"{r0} = OpBitwiseOr %uint {a1} {b1}") self.emit(f"{nz} = OpINotEqual %bool {m} {self.cu(0)}") self.emit(f"{r} = OpSelect %uint {nz} {r0} {lo_}") self.dst(a[0], r) elif op in ("v_lshlrev_b64", "v_lshrrev_b64", "v_ashrrev_i64"): # v[d:d+1] = v[s:s+1] << / >> (src0 & 63): logical left, logical right, or arithmetic right (the sign # bit 63 is copied in). sh, src = a[1], a[2] if a[0].get("n") != 2: raise Unsupported(op + " operands") if src["k"] in ("vgpr", "sgpr") and src.get("n") == 2: lo, hi = self.load_reg(src["k"], src["r"]), self.load_reg(src["k"], src["r"] + 1) elif src["k"] == "imm": # 64-bit inline/literal constant: an inline constant is sign-extended; a 32-bit literal is # sign-extended for the i64 shift and zero-extended for the b64 ones (valu_imm_i64). v = self.valu_imm_i64(src["v"]) if op == "v_ashrrev_i64" else src["v"] & 0xFFFFFFFFFFFFFFFF lo, hi = self.cu(v & 0xFFFFFFFF), self.cu((v >> 32) & 0xFFFFFFFF) else: raise Unsupported(op + " operands") s = self.src_u(sh) l64, h64, x, sh64, m, res, rlo, rhi, t = (self.tmp() for _ in range(9)) self.emit(f"{l64} = OpUConvert %ulong {lo}") self.emit(f"{h64} = OpUConvert %ulong {hi}") self.emit(f"{t} = OpShiftLeftLogical %ulong {h64} %c64_32") self.emit(f"{x} = OpBitwiseOr %ulong {t} {l64}") self.emit(f"{m} = OpBitwiseAnd %uint {s} {self.cu(63)}") self.emit(f"{sh64} = OpUConvert %ulong {m}") shop = {"v_lshlrev_b64": "OpShiftLeftLogical", "v_lshrrev_b64": "OpShiftRightLogical", "v_ashrrev_i64": "OpShiftRightArithmetic"}[op] self.emit(f"{res} = {shop} %ulong {x} {sh64}") self.emit(f"{rlo} = OpUConvert %uint {res}") hs = self.tmp() self.emit(f"{hs} = OpShiftRightLogical %ulong {res} %c64_32") self.emit(f"{rhi} = OpUConvert %uint {hs}") self.uses_psb = True # needs Int64 (declared with the PSB types) self.dst({"k": "vgpr", "r": a[0]["r"], "n": 1}, rlo) self.dst({"k": "vgpr", "r": a[0]["r"] + 1, "n": 1}, rhi) elif op == "v_fmac_f16": # dst = fma(src0, src1, dst). The accumulator is dst itself: low half, or high half under op_sel's dst bit. sel, dhi = self.opsel_bits(mods, 3) vals = [self.f16_in(a[1], sel[0]), self.f16_in(a[2], sel[1]), self.f16_in(a[0], sel[2])] r = self.fma_f16_odd(*vals) # one rounding, to f16 (SHADER-55); omod/clamp keep round-to-odd valid r = self.clamp_f16(r, mods) self.f16_out(a[0], r, dhi) # GFX10: f16 ops keep the other half elif op in ("v_fmamk_f16", "v_fmaak_f16"): # VOP2 with a literal K (RDNA2 ISA): fmamk D = S0 * K + S1, printed `vdst, src0, K, vsrc1`; fmaak # D = S0 * S1 + K, printed `vdst, src0, vsrc1, K`. In print order both are a[1] * a[2] + a[3], as for # v_fmamk/fmaak_f32. K is the f16 in the literal's low 16 bits (src_h: a float literal is converted). # One rounding to f16, as v_fmac_f16 (SHADER-55); GFX10 f16 VOP2 writes the low half and keeps the high. self._validate_f16_valu(ins, op, 3, allow_e32=True, allow_e64=False) vals = [self.f16_in(t) for t in a[1:4]] self.f16_out(a[0], self.fma_f16_odd(*vals), 0) elif op in ("v_add_nc_u16", "v_sub_nc_u16", "v_add_nc_i16", "v_sub_nc_i16"): # VOP3-only GFX10 names of the 16-bit add/sub (no carry): opsel-capable, so the high half is kept. The # i16 forms differ only under clamp (signed saturation); v_add_i16 / v_sub_i16 are internal names. self._insn({**ins, "op": {"v_add_nc_u16": "v_add_u16_e64", "v_sub_nc_u16": "v_sub_u16_e64", "v_add_nc_i16": "v_add_i16_e64", "v_sub_nc_i16": "v_sub_i16_e64"}[op]}) elif op in ("v_lshrrev_b16", "v_lshlrev_b16", "v_ashrrev_i16", "v_add_u16", "v_sub_u16", "v_mul_lo_u16", "v_max_u16", "v_min_u16", "v_max_i16", "v_min_i16", "v_add_i16", "v_sub_i16"): # 16-bit integer ops on the low halves (op_sel picks high halves in the VOP3 form). Per Mesa ACO # (can_use_opsel): the opsel-capable VOP3 (_e64) forms are partial writes that keep the high half, # and the VOP2 (_e32) forms define the whole register (high half modelled as zero). # VOP3 has bits [31:26] = 0b110101 (0x35): 8 bytes without a literal or 12 bytes with a 32-bit literal. # VOP2 has bit 31 = 0: 4 bytes or 8 bytes with a literal/SDWA/DPP. LLVM 21 prints VOP3 16-bit integer # ops without the _e64 suffix, so check the VOP3 prefix rather than byte length alone. # v_add_i16 / v_sub_i16 are strictly VOP3. enc = ins.get("enc") e64 = ins["op"].endswith("_e64") or (bool(enc) and len(enc) >= 16 and (int(enc[6:8], 16) >> 2) == 0x35) sel = next((m for m in mods if m.startswith("op_sel:")), "op_sel:[0,0,0]") sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] + [0, 0, 0] if not e64 and sb[:3] != [0, 0, 0]: raise Unsupported(op + " op_sel") r = self.tmp() if op in ("v_lshrrev_b16", "v_lshlrev_b16", "v_ashrrev_i16"): x = self.u16_half(self.src_u(a[1]), sb[0]) sh = self.tmp() # shift amount is src0 (reversed operand order), low 4 bits self.emit(f"{sh} = OpBitwiseAnd %uint {x} {self.cu(15)}") if op == "v_lshrrev_b16": y = self.u16_half(self.src_u(a[2]), sb[1]) self.emit(f"{r} = OpShiftRightLogical %uint {y} {sh}") elif op == "v_lshlrev_b16": y = self.u16_half(self.src_u(a[2]), sb[1]) self.emit(f"{r} = OpShiftLeftLogical %uint {y} {sh}") else: yi = self.i16_half(self.src_u(a[2]), sb[1]) ri = self.tmp() self.emit(f"{ri} = OpShiftRightArithmetic %int {yi} {sh}") self.emit(f"{r} = OpBitcast %uint {ri}") elif op in ("v_add_i16", "v_sub_i16"): # signed 16-bit add / sub (v_add_nc_i16 / v_sub_nc_i16): the exact sum of the sign-extended halves; # its low 16 bits are the wrapped result, clamp below saturates it to [-32768, 32767] xi = self.i16_half(self.src_u(a[1]), sb[0]) yi = self.i16_half(self.src_u(a[2]), sb[1]) ri = self.tmp() self.emit(f"{ri} = {'OpIAdd' if op == 'v_add_i16' else 'OpISub'} %int {xi} {yi}") self.emit(f"{r} = OpBitcast %uint {ri}") elif op in ("v_max_i16", "v_min_i16"): xi = self.i16_half(self.src_u(a[1]), sb[0]) yi = self.i16_half(self.src_u(a[2]), sb[1]) ri = self.tmp() self.emit(f"{ri} = OpExtInst %int %glsl {'SMax' if 'max' in op else 'SMin'} {xi} {yi}") self.emit(f"{r} = OpBitcast %uint {ri}") else: x = self.u16_half(self.src_u(a[1]), sb[0]) y = self.u16_half(self.src_u(a[2]), sb[1]) k = {"v_add_u16": "OpIAdd", "v_sub_u16": "OpISub", "v_mul_lo_u16": "OpIMul"}.get(op) if k: self.emit(f"{r} = {k} %uint {x} {y}") else: self.emit(f"{r} = OpExtInst %uint %glsl {'UMax' if 'max' in op else 'UMin'} {x} {y}") if "clamp" in mods: # VOP3 clamp saturates the unsigned add/sub to [0, 0xFFFF], as for the 32-bit ops (docs/design.md, # "Integer clamp"). The operands are zero-extended, so a result past 0xFFFF is an overflow (add) or a # borrow (sub). Other 16-bit ops: rejected rather than guessed. if op in ("v_add_i16", "v_sub_i16"): sat = self.tmp() self.emit(f"{sat} = OpExtInst %uint %glsl SClamp {r} {self.cu(0xFFFF8000)} {self.cu(0x7FFF)}") r = sat elif op not in ("v_add_u16", "v_sub_u16"): raise Unsupported(op + " clamp") if op in ("v_add_u16", "v_sub_u16"): ov, sat = self.tmp(), self.tmp() self.emit(f"{ov} = OpUGreaterThan %bool {r} {self.cu(0xFFFF)}") self.emit(f"{sat} = OpSelect %uint {ov} {self.cu(0 if 'sub' in op else 0xFFFF)} {r}") r = sat lo = self.tmp() # BitFieldUExtract, not OpBitwiseAnd & 0xFFFF: on NVIDIA's shader compiler an And of a value that # passed through %int ops (the signed i16 add/sub/min/max and ashr paths below) feeding the # preserve-high-half merge miscompiles the KEPT high half (measured on an RTX 4070 SUPER, wave32: # v_add_nc_i16 ... op_sel:[1,1,0] clamp wrote 0x1113AAA8 for 0x0002AAA8). Extract reads the same # low 16 bits and dodges that peephole; AMD and the interpreter are unaffected. self.emit(f"{lo} = OpBitFieldUExtract %uint {r} {self.cu(0)} {self.cu(16)}") if e64 and sb[2]: # op_sel destination bit: the result goes to the high half, the low half is kept. if a[0]["k"] != "vgpr": raise Unsupported("op_sel destination") old, keep, sh16, v = (self.tmp() for _ in range(4)) self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', a[0]['r'])}") self.emit(f"{keep} = OpBitwiseAnd %uint {old} {self.cu(0xFFFF)}") self.emit(f"{sh16} = OpShiftLeftLogical %uint {lo} {self.cu(16)}") self.emit(f"{v} = OpBitwiseOr %uint {keep} {sh16}") self.dst(a[0], v) else: self.write_lo16(a[0], lo, preserve_high=e64) elif op in ("v_mad_u16", "v_mad_i16"): # D.u16 = S0.u16 * S1.u16 + S2.u16 on the low halves (op_sel picks high halves: bits 0..2 the sources, bit 3 the # destination); VOP3-only, so the high half of the destination is kept (RDNA2 ISA; Mesa ACO can_use_opsel). # The product and sum are formed in 32 bits (no overflow possible), then the low 16 bits are kept. With # `clamp` the full-width result saturates to [0, 0xFFFF] (v_mad_u16) or [-32768, 32767] (v_mad_i16). sb, dhi = self.opsel_bits(mods, 3) vals = [] for k, s_ in enumerate(a[1:4]): u = self.src_u(s_) h = self.u16_half(u, sb[k]) if op == "v_mad_u16" else self.int_bits(self.i16_half(u, sb[k])) vals.append(h) x, y, z = vals prod, tot = self.tmp(), self.tmp() self.emit(f"{prod} = OpIMul %uint {x} {y}") self.emit(f"{tot} = OpIAdd %uint {prod} {z}") r = tot if "clamp" in mods: sat = self.tmp() if op == "v_mad_u16": ov = self.tmp() self.emit(f"{ov} = OpUGreaterThan %bool {tot} {self.cu(0xFFFF)}") self.emit(f"{sat} = OpSelect %uint {ov} {self.cu(0xFFFF)} {tot}") else: ti, lo_c, hi_c = self.as_int(tot), self.tmp(), self.tmp() self.emit(f"{lo_c} = OpExtInst %int %glsl SMax {ti} {self.as_int(self.cu(0xFFFF8000))}") self.emit(f"{hi_c} = OpExtInst %int %glsl SMin {lo_c} {self.as_int(self.cu(0x7FFF))}") self.emit(f"{sat} = OpBitcast %uint {hi_c}") r = sat lo = self.tmp() self.emit(f"{lo} = OpBitFieldUExtract %uint {r} {self.cu(0)} {self.cu(16)}") # see the nc_i16 note above: And & 0xFFFF miscompiles on NVIDIA if dhi: old, keep, sh16, v = (self.tmp() for _ in range(4)) self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', a[0]['r'])}") self.emit(f"{keep} = OpBitwiseAnd %uint {old} {self.cu(0xFFFF)}") self.emit(f"{sh16} = OpShiftLeftLogical %uint {lo} {self.cu(16)}") self.emit(f"{v} = OpBitwiseOr %uint {keep} {sh16}") self.dst(a[0], v) else: self.write_lo16(a[0], lo) elif op in ("v_min3_i16", "v_min3_u16", "v_max3_i16", "v_max3_u16", "v_med3_i16", "v_med3_u16"): # Three-operand 16-bit integer min/max/median on the low halves (op_sel bits 0..2 pick the high half of # S0..S2, bit 3 writes the high half of D); VOP3-only, so the other half of D is kept (RDNA2 ISA; Mesa # ACO can_use_opsel). clamp is accepted on hardware and is a no-op on the 16-bit bounded integer word. sb, dhi = self.opsel_bits(mods, 3) if dhi and a[0]["k"] != "vgpr": raise Unsupported("op_sel destination") signed = op.endswith("_i16") vals = [] for k, s_ in enumerate(a[1:4]): u = self.src_u(s_) vals.append(self.i16_half(u, sb[k]) if signed else self.u16_half(u, sb[k])) x, y, z = vals ty, pfx = ("%int", "S") if signed else ("%uint", "U") if "med3" in op: lo_, hi_, m = self.tmp(), self.tmp(), self.tmp() self.emit(f"{lo_} = OpExtInst {ty} %glsl {pfx}Min {x} {y}") self.emit(f"{hi_} = OpExtInst {ty} %glsl {pfx}Max {x} {y}") self.emit(f"{m} = OpExtInst {ty} %glsl {pfx}Clamp {z} {lo_} {hi_}") else: m0, m = self.tmp(), self.tmp() fn = pfx + ("Min" if "min3" in op else "Max") self.emit(f"{m0} = OpExtInst {ty} %glsl {fn} {x} {y}") self.emit(f"{m} = OpExtInst {ty} %glsl {fn} {m0} {z}") if signed: r = self.tmp() self.emit(f"{r} = OpBitcast %uint {m}") else: r = m lo = self.tmp() self.emit(f"{lo} = OpBitFieldUExtract %uint {r} {self.cu(0)} {self.cu(16)}") # same NVIDIA And-&-0xFFFF workaround as above self.write_half16(a[0], lo, dhi) elif op == "v_bcnt_u32_b32": self._check_int32_valu(op, ins["op"], a, mods) x, acc = self.src_u(a[1]), self.src_u(a[2]) c, r = self.tmp(), self.tmp() self.emit(f"{c} = OpBitCount %uint {x}") self.emit(f"{r} = OpIAdd %uint {c} {acc}") self.dst(a[0], r) elif op in ("s_min_i32", "s_max_i32"): x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) if x_val is not None and y_val is not None: xi = x_val if x_val < 0x80000000 else x_val - 0x100000000 yi = y_val if y_val < 0x80000000 else y_val - 0x100000000 if "min" in op: val = (xi if xi < yi else yi) & 0xFFFFFFFF scc = 1 if xi < yi else 0 else: val = (xi if xi > yi else yi) & 0xFFFFFFFF scc = 1 if xi > yi else 0 r = self.cu(val) self.dst(a[0], r) if a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: self.sgpr_imm[a[0]["r"]] = val self.emit(f"OpStore %scc {self.cu(scc)}") return x, y = self.src_u(a[1]), self.src_u(a[2]) r = self.tmp() self.emit(f"{r} = OpExtInst %uint %glsl {'SMin' if 'min' in op else 'SMax'} {x} {y}") self.dst(a[0], r) # SCC = 1 when S0 is the one chosen: the ISA's D = S0 < S1 ? S0 : S1 (min) / S0 > S1 ? S0 : S1 (max) # picks S1 on a tie, so SCC = S0 < S1 / S0 > S1, compared signed (as s_min_u32/s_max_u32 do unsigned). # Until 2026-11-21 equal operands set SCC to 1. c, z = self.tmp(), self.tmp() xi, yi = self.as_int(x), self.as_int(y) self.emit(f"{c} = {'OpSLessThan' if 'min' in op else 'OpSGreaterThan'} %bool {xi} {yi}") self.emit(f"{z} = OpSelect %uint {c} {self.cu(1)} {self.cu(0)}") self.emit(f"OpStore %scc {z}") elif op == "v_fma_f16": self._validate_f16_valu(ins, op, 3) sel, dhi = self.opsel_bits(mods, 3) # op_sel:[src0,src1,src2,dst] vals = [self.f16_in(s, sel[i]) for i, s in enumerate(a[1:4])] r = self.fma_f16_odd(*vals) # one rounding, to f16 (SHADER-55); omod/clamp keep round-to-odd valid r = self.clamp_f16(r, mods) self.f16_out(a[0], r, dhi) # GFX10: f16 ops keep the other half elif op == "v_pk_fmac_f16": # VOP2 packed f16x2 fused multiply-accumulate into vdst: # D.f16[0] = fma(S0.f16[0], S1.f16[0], D.f16[0]) # D.f16[1] = fma(S0.f16[1], S1.f16[1], D.f16[1]) if (self.non_dpp_mods(ins["op"], mods) or ins["op"].endswith("_sdwa") or any(s.get("neg") or s.get("abs") for s in a) or a[0]["k"] != "vgpr"): raise Unsupported("v_pk_fmac_f16 modifiers") vecs = [] for s in (a[1], a[2], a[0]): u = self.src_h(s) v2 = self.tmp() self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") vecs.append(v2) comps = [] for k in (0, 1): ex = [self.tmp() for _ in range(3)] for e_, v_ in zip(ex, vecs): self.emit(f"{e_} = OpCompositeExtract %float {v_} {k}") comps.append(self.fma_f16_odd(*ex)) p = self.tmp() self.emit(f"{p} = OpCopyObject %uint {self.f16_pack2(comps[0], comps[1])}") self.dst(a[0], p) elif op in ("v_pk_add_f16", "v_pk_mul_f16", "v_pk_max_f16", "v_pk_min_f16", "v_pk_fma_f16"): # Packed f16x2 (VOP3P). Result lo: source i takes its half from op_sel[i] (0 = lo, 1 = hi), negated by # neg_lo[i]. Result hi: half from op_sel_hi[i], negated by neg_hi[i]. Defaults: op_sel [0,0], # op_sel_hi [1,1], no negation. def bits(name, default): m = next((m for m in mods if m.startswith(name + ":")), None) if not m: return default # a list shorter than the operands (neg_lo:[1,0] on v_pk_fma_f16) is padded with 0, as llvm-mc prints it return ([int(v) for v in m.split("[")[1].rstrip("]").split(",")] + [0] * len(default))[:len(default)] ns = 3 if op == "v_pk_fma_f16" else 2 sel, selhi = bits("op_sel", [0] * ns), bits("op_sel_hi", [1] * ns) nlo, nhi = bits("neg_lo", [0] * ns), bits("neg_hi", [0] * ns) track_pk_nan = op in ("v_pk_min_f16", "v_pk_max_f16") and "clamp" not in mods pk_raw, pk_st, pk_h0 = ([], []), ([], []), [] srcs = [] for i in range(ns): u = self.src_h(a[1 + i]) v2 = self.tmp() self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") comps = [] extracted = {} for lane, (half_sel, neg) in enumerate(((sel[i], nlo[i]), (selhi[i], nhi[i]))): c = self.tmp() self.emit(f"{c} = OpCompositeExtract %float {v2} {half_sel}") if neg: n2 = self.tmp() self.emit(f"{n2} = OpFNegate %float {c}") c = n2 comps.append(c) if track_pk_nan: if half_sel not in extracted: extracted[half_sel] = self._f16_half_word(u, half_sel) h_bits = extracted[half_sel] pk_raw[i].append(h_bits) pk_st[i].append(self._f16_const_nan(a[1 + i], half_sel)) if i == 0: if neg: hn = self.tmp() self.emit(f"{hn} = OpBitwiseXor %uint {h_bits} {self.cu(0x8000)}") pk_h0.append(hn) else: pk_h0.append(h_bits) vv = self.tmp() self.emit(f"{vv} = OpCompositeConstruct %v2float {comps[0]} {comps[1]}") srcs.append(vv) vx, vy = srcs[:2] r = self.tmp() if op == "v_pk_fma_f16": # one rounding per half, to f16 (SHADER-55) comps = [] for k in (0, 1): ex = [self.tmp() for _ in range(3)] for e_, v_ in zip(ex, (vx, vy, srcs[2])): self.emit(f"{e_} = OpCompositeExtract %float {v_} {k}") comps.append(self.fma_f16_odd(*ex)) self.emit(f"{r} = OpCompositeConstruct %v2float {comps[0]} {comps[1]}") elif op in ("v_pk_add_f16", "v_pk_mul_f16"): self.emit(f"{r} = {'OpFAdd' if 'add' in op else 'OpFMul'} %v2float {vx} {vy}") if "add" in op: r = self.sum_toward_zero2(vx, vy, r) else: self.emit(f"{r} = OpExtInst %v2float %glsl {'NMax' if 'max' in op else 'NMin'} {vx} {vy}") if "clamp" in mods: c = self.tmp() z2, o2 = self.tmp(), self.tmp() self.emit(f"{z2} = OpCompositeConstruct %v2float %f0 %f0") self.emit(f"{o2} = OpCompositeConstruct %v2float %f1 %f1") self.emit(f"{c} = OpExtInst %v2float %glsl FClamp {r} {z2} {o2}") r = c p = self.tmp() c0, c1 = self.tmp(), self.tmp() self.emit(f"{c0} = OpCompositeExtract %float {r} 0") self.emit(f"{c1} = OpCompositeExtract %float {r} 1") if track_pk_nan: lanes = [] for k, c_val in enumerate((c0, c1)): both_nan = self.all_f16_nan_cond([(pk_raw[0][k], pk_st[0][k]), (pk_raw[1][k], pk_st[1][k])]) if both_nan is True: lanes.append(pk_h0[k]) else: hk = self.f16_res(c_val) if both_nan is not None: sel_k = self.tmp() self.emit(f"{sel_k} = OpSelect %uint {both_nan} {pk_h0[k]} {hk}") hk = sel_k lanes.append(hk) sh = self.tmp() self.emit(f"{sh} = OpShiftLeftLogical %uint {lanes[1]} {self.cu(16)}") self.emit(f"{p} = OpBitwiseOr %uint {lanes[0]} {sh}") else: self.emit(f"{p} = OpCopyObject %uint {self.f16_pack2(c0, c1, exact_tiny=op == 'v_pk_add_f16')}") self.dst(a[0], p) elif op in ("s_movrels_b32", "s_movrels_b64"): # Relative SGPR read through M0 (RDNA2 ISA SOP1): D = SGPR[S0 + M0] (the b64 form reads the pair at # S0 + M0 and S0 + M0 + 1). The SGPR file is an array, so this is a dynamic load, as v_movrels is for # VGPRs. The index wraps to the 128 array slots, so it can't reach the lane-mask parking slots past them # (an SGPR that holds a lane mask is handled below); # the hardware's own range check (and reads past s105 landing on VCC and the other specials) is not # modelled. SCC is not written. s_movreld (a dynamic SGPR write) stays Unsupported: the translator keeps # translate-time knowledge of SGPR values (literal S# words, descriptor caches) a dynamic write would # invalidate. n = 2 if op.endswith("_b64") else 1 d, src = a[0], a[1] if d["k"] != "sgpr" or src["k"] != "sgpr" or d.get("n", 1) != n or src.get("n", 1) != n: raise Unsupported(op + " operands") # An SGPR that lane_masks.py marks as a lane mask holds only this lane's bit, so a plain load would copy # that bit as data (a saved EXEC of 5 read back as 0xffffffff in lanes 0 and 2, 0 elsewhere). For each # such SGPR the whole wave's mask word is collected first (wave_mask, as for s_bcnt1) and replaces the # load when the index lands on it. D then holds the mask as data, which is what lane_masks.py assumes # for an s_movrels destination. The index is dynamic, so every mask SGPR here is a candidate (#1548, # SHADER-284). mask_words = [] for r in sorted(k for k in self.cur_masks if isinstance(k, int) and k < self.SGPRS): reg = {"k": "sgpr", "r": r, "n": 1} lo, hi = self.wave_mask(reg) mask_words.append((r, hi if self.mask_half(reg) == "hi" else lo)) m0 = self.tmp() self.emit(f"{m0} = OpLoad %uint %m0") vals = [] for w in range(n): i, j, ptr, v = (self.tmp() for _ in range(4)) self.emit(f"{i} = OpIAdd %uint {self.cu(src['r'] + w)} {m0}") self.emit(f"{j} = OpBitwiseAnd %uint {i} {self.cu(self.SGPRS - 1)}") self.emit(f"{ptr} = OpAccessChain %_ptr_Function_uint %sgpr {j}") self.emit(f"{v} = OpLoad %uint {ptr}") for r, word in mask_words: hit, sel = self.tmp(), self.tmp() self.emit(f"{hit} = OpIEqual %bool {j} {self.cu(r)}") self.emit(f"{sel} = OpSelect %uint {hit} {word} {v}") v = sel vals.append(v) for w, v in enumerate(vals): # every read before the first write (D may overlap the source) self.store_reg("sgpr", d["r"] + w, v) elif op == "v_swaprel_b32": # GFX10 VOP1 (opcode 104): swap VGPR[D + M0[25:16]] and VGPR[S0 + M0[9:0]], the fields v_movrelsd_2_b32 # uses (RDNA2 ISA: tmp = VGPR[D + M0[25:16]]; VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]]; # VGPR[S0 + M0[9:0]] = tmp). Both registers are read before either is written; inactive lanes keep both. # Both operands are destinations. An out-of-range destination suppresses the entire swap. d, s0 = a[0], a[1] if d["k"] != "vgpr" or s0["k"] != "vgpr": raise Unsupported(op + " operands") m0, lo, hi, md = (self.tmp() for _ in range(4)) self.emit(f"{m0} = OpLoad %uint %m0") self.emit(f"{lo} = OpBitwiseAnd %uint {m0} {self.cu(0x3FF)}") self.emit(f"{hi} = OpShiftRightLogical %uint {m0} {self.cu(16)}") self.emit(f"{md} = OpBitwiseAnd %uint {hi} {self.cu(0x3FF)}") dp, d_valid = self.relative_vgpr_ptr(d["r"], md) sp, s_valid = self.relative_vgpr_ptr(s0["r"], lo) d_old, s_old, both_valid, write = (self.tmp() for _ in range(4)) self.emit(f"{d_old} = OpLoad %uint {dp}") self.emit(f"{s_old} = OpLoad %uint {sp}") self.emit(f"{both_valid} = OpLogicalAnd %bool {d_valid} {s_valid}") self.emit(f"{write} = OpLogicalAnd %bool {self.active_b()} {both_valid}") # D's slot gets S0's value, then S0's slot gets D's old value: when both name one register the second # store writes back its own value, so the register is unchanged, as a swap with itself is. for p_, new, old in ((dp, s_old, d_old), (sp, d_old, s_old)): sel = self.tmp() self.emit(f"{sel} = OpSelect %uint {write} {new} {old}") self.emit(f"OpStore {p_} {sel}") elif op in ("v_movrels_b32", "v_movreld_b32", "v_movrelsd_b32", "v_movrelsd_2_b32"): # Relative VGPR indexing through M0: movrels reads VGPR[src + M0], movreld writes VGPR[dst + M0], # movrelsd does both. The register file is an array, so these become dynamic array accesses. # movrelsd_2 (GFX10) offsets each side by its own M0 field: VGPR[dst + M0[25:16]] = # VGPR[src + M0[9:0]] (RDNA2 ISA, VOP1 opcode 72; the RDNA3 ISA gives the same fields). # Only movreld's source is not indexed, so it is any VOP1 source: an SGPR, M0, an inline constant or a # literal too (LLVM VOP_MOVRELD's src0 is VSrc_b32; the other three take VRegSrc_32, a VGPR). d, s = a[0], a[1] if d["k"] != "vgpr" or (s["k"] != "vgpr" and op != "v_movreld_b32"): raise Unsupported(op + " operands") m0 = self.tmp() self.emit(f"{m0} = OpLoad %uint %m0") m0_src = m0_dst = m0 if op == "v_movrelsd_2_b32": m0_src, hi, m0_dst = self.tmp(), self.tmp(), self.tmp() self.emit(f"{m0_src} = OpBitwiseAnd %uint {m0} {self.cu(0x3FF)}") self.emit(f"{hi} = OpShiftRightLogical %uint {m0} {self.cu(16)}") self.emit(f"{m0_dst} = OpBitwiseAnd %uint {hi} {self.cu(0x3FF)}") if op in ("v_movrels_b32", "v_movrelsd_b32", "v_movrelsd_2_b32"): sp, _ = self.relative_vgpr_ptr(s["r"], m0_src) v = self.tmp() self.emit(f"{v} = OpLoad %uint {sp}") else: v = self.src_u(s) if op in ("v_movreld_b32", "v_movrelsd_b32", "v_movrelsd_2_b32"): dp, valid = self.relative_vgpr_ptr(d["r"], m0_dst) old, write, sel = (self.tmp() for _ in range(3)) self.emit(f"{old} = OpLoad %uint {dp}") self.emit(f"{write} = OpLogicalAnd %bool {self.active_b()} {valid}") self.emit(f"{sel} = OpSelect %uint {write} {v} {old}") self.emit(f"OpStore {dp} {sel}") else: self.dst(d, v) elif op in ("v_med3_f16", "v_min3_f16", "v_max3_f16"): self._validate_f16_valu(ins, op, 3) sel, dhi = self.opsel_bits(mods, 3) # op_sel:[src0,src1,src2,dst] vals, all_nan, h0_mod = self._read_f16_minmax_srcs(a[1:4], sel, mods) if op == "v_med3_f16": r = self.med3_f(vals, a[1:4], sel) else: f = "NMax" if "max" in op else "NMin" # a NaN operand gives the other one (docs/design.md) m, r = self.tmp(), self.tmp() self.emit(f"{m} = OpExtInst %float %glsl {f} {vals[0]} {vals[1]}") self.emit(f"{r} = OpExtInst %float %glsl {f} {m} {vals[2]}") self._finish_f16_minmax_out(a[0], r, mods, dhi, all_nan, h0_mod) # opsel-capable VOP3: keeps the other half elif op in ("v_qsad_pk_u16_u8", "v_mqsad_pk_u16_u8"): # Four byte-SADs packed as u16 (RDNA ISA pseudocode): for k = 0..3, D.u16[k] = (S2.u16[k] + SAD of the # 32-bit window S0[8k+31 : 8k] of the 64-bit S0 against S1) & 0xFFFF. The m form is masked: a byte where # S1's byte is 0 is skipped (as v_msad_u8). clamp is not modelled: rejected rather than guessed. if a[0].get("n") != 2 or "clamp" in mods: raise Unsupported(op + " operands") x_lo, x_hi = self.src64_data(a[1], op, allow_vgpr=True) y = self.src_u(a[2]) c_lo, c_hi = self.src64_data(a[3], op, allow_vgpr=True) words = [] for k in range(4): if k == 0: win = x_lo else: t1, t2, win = self.tmp(), self.tmp(), self.tmp() self.emit(f"{t1} = OpShiftRightLogical %uint {x_lo} {self.cu(8 * k)}") self.emit(f"{t2} = OpShiftLeftLogical %uint {x_hi} {self.cu(32 - 8 * k)}") self.emit(f"{win} = OpBitwiseOr %uint {t1} {t2}") acc_w = c_lo if k < 2 else c_hi total = self.u16_half(acc_w, k % 2) for off in (0, 8, 16, 24): xb, yb, hi_, lo_, d, t = (self.tmp() for _ in range(6)) self.emit(f"{xb} = OpBitFieldUExtract %uint {win} {self.cu(off)} {self.cu(8)}") self.emit(f"{yb} = OpBitFieldUExtract %uint {y} {self.cu(off)} {self.cu(8)}") self.emit(f"{hi_} = OpExtInst %uint %glsl UMax {xb} {yb}") self.emit(f"{lo_} = OpExtInst %uint %glsl UMin {xb} {yb}") self.emit(f"{d} = OpISub %uint {hi_} {lo_}") if op == "v_mqsad_pk_u16_u8": md = self.tmp() self.emit(f"{md} = OpSelect %uint {self.tmp_bool_nz(yb)} {d} {self.cu(0)}") d = md self.emit(f"{t} = OpIAdd %uint {total} {d}") total = t w = self.tmp() self.emit(f"{w} = OpBitwiseAnd %uint {total} {self.cu(0xFFFF)}") words.append(w) out = [] for lo16, hi16 in ((words[0], words[1]), (words[2], words[3])): sh, o = self.tmp(), self.tmp() self.emit(f"{sh} = OpShiftLeftLogical %uint {hi16} {self.cu(16)}") self.emit(f"{o} = OpBitwiseOr %uint {lo16} {sh}") out.append(o) self.dst({"k": "vgpr", "r": a[0]["r"], "n": 1}, out[0]) self.dst({"k": "vgpr", "r": a[0]["r"] + 1, "n": 1}, out[1]) elif op in ("v_sad_u8", "v_sad_hi_u8", "v_sad_u16", "v_sad_u32", "v_msad_u8"): # Sums of absolute differences (RDNA ISA pseudocode), all unsigned and wrapping at 32 bits: # v_sad_u8: S2 + sum over the 4 bytes of |S0.b - S1.b| # v_sad_hi_u8: S2 + (that byte sum << 16) # v_sad_u16: S2 + sum over the 2 halves of |S0.h - S1.h| # v_sad_u32: S2 + |S0 - S1| # v_msad_u8: v_sad_u8, skipping each byte where S1's byte is 0 (masked SAD) # clamp is not modelled: rejected rather than guessed. if "clamp" in mods: raise Unsupported(op + " clamp") x, y, acc = (self.src_u(t) for t in a[1:4]) width = {"v_sad_u16": 16, "v_sad_u32": 32}.get(op, 8) total = None for off in range(0, 32, width): if width == 32: xa, ya = x, y elif width == 16: xa, ya = self.u16_half(x, off // 16), self.u16_half(y, off // 16) else: xa, ya = self.tmp(), self.tmp() self.emit(f"{xa} = OpBitFieldUExtract %uint {x} {self.cu(off)} {self.cu(width)}") self.emit(f"{ya} = OpBitFieldUExtract %uint {y} {self.cu(off)} {self.cu(width)}") hi_, lo_, d = self.tmp(), self.tmp(), self.tmp() self.emit(f"{hi_} = OpExtInst %uint %glsl UMax {xa} {ya}") self.emit(f"{lo_} = OpExtInst %uint %glsl UMin {xa} {ya}") self.emit(f"{d} = OpISub %uint {hi_} {lo_}") if op == "v_msad_u8": md = self.tmp() self.emit(f"{md} = OpSelect %uint {self.tmp_bool_nz(ya)} {d} {self.cu(0)}") d = md if total is None: total = d else: t = self.tmp() self.emit(f"{t} = OpIAdd %uint {total} {d}") total = t if op == "v_sad_hi_u8": t = self.tmp() self.emit(f"{t} = OpShiftLeftLogical %uint {total} {self.cu(16)}") total = t r = self.tmp() self.emit(f"{r} = OpIAdd %uint {total} {acc}") self.dst(a[0], r) elif op == "v_mqsad_u32_u8": # Four masked byte-SADs with full 32-bit accumulators (RDNA ISA pseudocode): for k = 0..3, # D[k] = S2[k] + v_msad_u8 of the 32-bit window S0[8k+31 : 8k] of the 64-bit S0 against S1, wrapping at # 32 bits; a byte where S1's byte is 0 adds nothing. S2 and D are 128-bit (four VGPRs). # clamp is not modelled: rejected rather than guessed. if a[0].get("n") != 4 or "clamp" in mods: raise Unsupported(op + " operands") s0, s2 = a[1], a[3] x_lo, x_hi = self.src64_data(s0, op, allow_vgpr=True) if s2["k"] == "vgpr" and s2.get("n") == 4: accs = [self.load_reg("vgpr", s2["r"] + k) for k in range(4)] else: raise Unsupported(op + " operands") y = self.src_u(a[2]) outs = [] for k in range(4): if k == 0: win = x_lo else: t1, t2, win = self.tmp(), self.tmp(), self.tmp() self.emit(f"{t1} = OpShiftRightLogical %uint {x_lo} {self.cu(8 * k)}") self.emit(f"{t2} = OpShiftLeftLogical %uint {x_hi} {self.cu(32 - 8 * k)}") self.emit(f"{win} = OpBitwiseOr %uint {t1} {t2}") total = accs[k] for off in (0, 8, 16, 24): xb, yb, hi_, lo_, d, md, t = (self.tmp() for _ in range(7)) self.emit(f"{xb} = OpBitFieldUExtract %uint {win} {self.cu(off)} {self.cu(8)}") self.emit(f"{yb} = OpBitFieldUExtract %uint {y} {self.cu(off)} {self.cu(8)}") self.emit(f"{hi_} = OpExtInst %uint %glsl UMax {xb} {yb}") self.emit(f"{lo_} = OpExtInst %uint %glsl UMin {xb} {yb}") self.emit(f"{d} = OpISub %uint {hi_} {lo_}") self.emit(f"{md} = OpSelect %uint {self.tmp_bool_nz(yb)} {d} {self.cu(0)}") self.emit(f"{t} = OpIAdd %uint {total} {md}") total = t outs.append(total) for k in range(4): # every source is read before the first write self.dst({"k": "vgpr", "r": a[0]["r"] + k, "n": 1}, outs[k]) elif op == "v_xad_u32": x, y, z = (self.src_u(t) for t in a[1:4]) t, r = self.tmp(), self.tmp() self.emit(f"{t} = OpBitwiseXor %uint {x} {y}") self.emit(f"{r} = OpIAdd %uint {t} {z}") self.dst(a[0], r) elif op == "s_not_b64": if (a[0]["k"] == "special" and a[0].get("t", "").startswith(("exec", "vcc"))) or self.is_mask_op(a[1]): v = self.mask_src(a[1]) r = self.tmp() self.emit(f"{r} = OpNot %uint {v}") self.mask_dst(a[0], r) self.scc_from_mask(r) else: if not ((a[0]["k"] == "sgpr" and a[0].get("n") == 2) or (a[0]["k"] == "special" and a[0].get("t") == "null")): raise Unsupported(op + " destination") vlo, vhi = self.src64_data(a[1], op) rlo, rhi = self.tmp(), self.tmp() self.emit(f"{rlo} = OpNot %uint {vlo}") self.emit(f"{rhi} = OpNot %uint {vhi}") self.dst64_data(a[0], rlo, rhi, op, allow_null=True) orr = self.tmp() self.emit(f"{orr} = OpBitwiseOr %uint {rlo} {rhi}") self.scc_nonzero(orr) elif op in ("v_rsq_f16", "v_rcp_f16", "v_sqrt_f16", "v_exp_f16", "v_log_f16", "v_floor_f16", "v_fract_f16", "v_ceil_f16", "v_trunc_f16", "v_rndne_f16"): # f16 unary on the low half (op_sel:[src,dst] picks the high half of the source / of the destination); # the other half of the destination is kept. self._validate_unary_f16(op, ins["op"], a, mods) sel, dhi = self.opsel_bits(mods, 1) f = self.f16_in(a[1], sel[0]) r = self.tmp() fn = {"v_rsq_f16": "InverseSqrt", "v_sqrt_f16": "Sqrt", "v_exp_f16": "Exp2", "v_log_f16": "Log2", "v_floor_f16": "Floor", "v_fract_f16": "Fract", "v_ceil_f16": "Ceil", "v_trunc_f16": "Trunc", "v_rndne_f16": "RoundEven"}.get(op) if fn == "Fract": inf = self.tmp() self.emit(f"{inf} = OpIsInf %bool {f}") if "clamp" in mods: # DX10_CLAMP maps the infinity result to +0. Give FClamp a defined operand. clamp_input = self.tmp() self.emit(f"{clamp_input} = OpSelect %float {inf} %f0 {f}") f = clamp_input # SPIR-V leaves 1/0, InverseSqrt(x <= 0) and Sqrt(x < 0) undefined, so those operands are replaced by 1.0 # and the hardware's result is selected afterwards (docs/design.md, f16 transcendentals): rcp(+-0) = +-inf, # rsq(+-0) = +-inf, rsq and sqrt of a negative operand (-inf included) = 0xfe00 (a negative quiet NaN). x, edge = f, None if op in ("v_rcp_f16", "v_rsq_f16", "v_sqrt_f16"): sg, zero, below, bad = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{sg} = OpBitwiseAnd %uint {self.tou(f)} {self.cu(0x80000000)}") self.emit(f"{zero} = OpFOrdEqual %bool {f} %f0") self.emit(f"{below} = OpFOrdLessThan %bool {f} %f0") if op == "v_rcp_f16": self.emit(f"{bad} = OpCopyObject %bool {zero}") elif op == "v_rsq_f16": self.emit(f"{bad} = OpFOrdLessThanEqual %bool {f} %f0") else: self.emit(f"{bad} = OpCopyObject %bool {below}") x = self.tmp() self.emit(f"{x} = OpSelect %float {bad} %f1 {f}") edge = (sg, zero, below) if fn: self.emit(f"{r} = OpExtInst %float %glsl {fn} {x}") else: self.emit(f"{r} = OpFDiv %float %f1 {x}") if edge: sg, zero, below = edge ib, inf, nan, t = self.tmp(), self.tmp(), self.tof(self.cu(0xFFC00000)), self.tmp() self.emit(f"{ib} = OpBitwiseOr %uint {sg} {self.cu(0x7F800000)}") self.emit(f"{inf} = OpBitcast %float {ib}") if op != "v_sqrt_f16": self.emit(f"{t} = OpSelect %float {zero} {inf} {r}") r = t if op != "v_rcp_f16": t = self.tmp() self.emit(f"{t} = OpSelect %float {below} {nan} {r}") r = t if fn == "Fract": r = self.fract_below_one(r) r = self.clamp_f16(r, mods) if fn == "Fract" and "clamp" not in mods: # gfx1036 returns 0xfe00 for both infinities. Fract and FMul leave the NaN sign unspecified. result = self.tmp() self.emit(f"{result} = OpSelect %float {inf} {self.tof(self.cu(0xFFC00000))} {r}") r = result # rcp/rsq/sqrt (and sin below) ignore MODE rounding on hardware (RX 6800, SHADER-35); exp, log (and cos # below) are unmeasured, assumed like them: nearest even always. self.f16_out(a[0], r, dhi, fract=fn == "Fract", mode=op not in ("v_rcp_f16", "v_rsq_f16", "v_sqrt_f16", "v_exp_f16", "v_log_f16")) # GFX10: f16 ops keep the other half elif op == "v_not_b32": x = self.src_u(a[1]) r = self.tmp() self.emit(f"{r} = OpNot %uint {x}") self.dst(a[0], r) elif op == "v_mul_hi_i32": self._check_int32_valu(op, ins["op"], a, mods) x, y = self.as_int(self.src_u(a[1])), self.as_int(self.src_u(a[2])) s, hi, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{s} = OpSMulExtended %smul {x} {y}") self.emit(f"{hi} = OpCompositeExtract %int {s} 1") self.emit(f"{r} = OpBitcast %uint {hi}") self.uses_smul = True self.dst(a[0], r) elif op in ("v_add_f16", "v_sub_f16", "v_subrev_f16", "v_mul_f16", "v_max_f16", "v_min_f16"): # f16 math on the low halves (op_sel:[src0,src1,dst] in the VOP3 form); the other half of the destination # is kept. v_subrev_f16 is S1 - S0: op_sel still names src0 and src1, only the subtraction is swapped. self._validate_f16_valu(ins, op, 2, allow_e32=True, allow_e64=True, allow_sdwa=True, allow_dpp=True) sel, dhi = self.opsel_bits(mods, 2) if op in ("v_max_f16", "v_min_f16"): vals, all_nan, h0_mod = self._read_f16_minmax_srcs(a[1:3], sel, mods) else: vals = [self.f16_in(s, sel[i]) for i, s in enumerate(a[1:3])] all_nan = h0_mod = None if op == "v_subrev_f16": vals.reverse() r = self.tmp() k = {"v_add_f16": "OpFAdd", "v_sub_f16": "OpFSub", "v_subrev_f16": "OpFSub", "v_mul_f16": "OpFMul"}.get(op) if k: self.emit(f"{r} = {k} %float {vals[0]} {vals[1]}") if k == "OpFAdd": r = self.sum_toward_zero(vals[0], vals[1], r) elif k == "OpFSub" and self.round_mode: ny = self.tmp() self.emit(f"{ny} = OpFNegate %float {vals[1]}") r = self.sum_toward_zero(vals[0], ny, r) else: self.emit(f"{r} = OpExtInst %float %glsl {'NMax' if 'max' in op else 'NMin'} {vals[0]} {vals[1]}") self._finish_f16_minmax_out(a[0], r, mods, dhi, all_nan, h0_mod) if k: r = self.clamp_f16(r, mods) # an f16 sum is exact below 2^-14; clamp keeps that, omod is ignored on f16 exact = k in ("OpFAdd", "OpFSub") self.f16_out(a[0], r, dhi, exact_tiny=exact) # GFX10: f16 ops keep the other half elif op.startswith(("v_cmp_", "v_cmpx_")) and op.endswith(("_u64", "_i64")) and op.split("_")[2] in ("eq", "ne", "lg"): # 64-bit equality compare: both halves of the register pairs. GFX10 v_cmpx has no destination operand: # it writes EXEC only (inactive lanes stay inactive). cmpx = op.startswith("v_cmpx_") d, x, y = (None, a[-2], a[-1]) if cmpx else (a[0], a[1], a[2]) def pair(s): if s["k"] == "vgpr" and s.get("n") == 2: return self.load_reg(s["k"], s["r"]), self.load_reg(s["k"], s["r"] + 1) return self.src64_i64(s, op) if op.endswith("_i64") else self.src64_data(s, op) (x0, x1), (y0, y1) = pair(x), pair(y) e0, e1, eq, r = (self.tmp() for _ in range(4)) self.emit(f"{e0} = OpIEqual %bool {x0} {y0}") self.emit(f"{e1} = OpIEqual %bool {x1} {y1}") self.emit(f"{eq} = OpLogicalAnd %bool {e0} {e1}") if op.split("_")[2] != "eq": ne = self.tmp() self.emit(f"{ne} = OpLogicalNot %bool {eq}") eq = ne if cmpx: both = self.tmp() self.emit(f"{both} = OpLogicalAnd %bool {eq} {self.active_b()}") self.emit(f"OpStore %active {both}") self.uses_active = True else: eqa = self.tmp() self.emit(f"{eqa} = OpLogicalAnd %bool {eq} {self.active_b()}") # inactive lanes write 0 self.emit(f"{r} = OpSelect %uint {eqa} {self.cu(0xFFFFFFFF)} {self.cu(0)}") self.mask_dst(d, r) elif op == "s_not_b32": to_mask_dst, dst_half = self._mask_b32_dst_half(a[0], a[1:2]) x_val = self.imm_val(a[1]) if x_val is not None and not to_mask_dst and not self.holds_lane_mask(a[1]): val = (~x_val) & 0xFFFFFFFF r = self.cu(val) self.dst(a[0], r) if a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: self.sgpr_imm[a[0]["r"]] = val self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}") else: x = (self._mask_b32_src(a[1], dst_half) if (to_mask_dst and self._maskable_b32(a[1])) else self.src_u(a[1])) r = self.tmp() self.emit(f"{r} = OpNot %uint {x}") self._store_b32_mask_dst(a[0], r, to_mask_dst, dst_half) self.scc_logic(a, r) elif op in SOPC_CMP64_OPS: self._validate_sopc(ins, op, a, mods, src0_64=True, src1_64=True) # 64-bit compare of masks/pointers: equal iff both halves are equal. # Only canonical full-wave masks (exec, mask vcc, or a wave64 (MASK_LO, MASK_HI) pair) can take the # per-lane vote path; pairs with EITHER (0/-1), plain data, swapped/duplicated halves, or wave32 masks # materialize each 32-bit word independently so inactive/unlaunched lanes and data halves stay exact. def _is_full_wave_mask(s): if s["k"] == "special": t = s.get("t", "") return t == "exec" or (t == "vcc" and "vcc" in self.cur_masks) if self.wave64 and s["k"] == "sgpr" and s.get("n") == 2: r = s["r"] return (self.cur_masks.get(r) == lane_masks.MASK_LO and self.cur_masks.get(r + 1) == lane_masks.MASK_HI) return False def _is_u64_zero(src): return src["k"] == "imm" and (src["v"] & 0xFFFFFFFFFFFFFFFF) == 0 f0, f1 = _is_full_wave_mask(a[0]), _is_full_wave_mask(a[1]) use_vote = (f0 and f1) or (f0 and _is_u64_zero(a[1])) or (f1 and _is_u64_zero(a[0])) if use_vote: x = self.mask_src(a[0]) if f0 else self.cu(0) y = self.mask_src(a[1]) if f1 else self.cu(0) eq = self.tmp() self.emit(f"{eq} = OpIEqual %bool {x} {y}") eq = self.wave_equal(eq, True) else: def halves(s, is_full): if is_full: return self.wave_mask(s) if s["k"] == "sgpr" and s.get("n") == 2: words = [] for i in range(2): r = s["r"] + i rk = self.cur_masks.get(r) if rk is not None: lo, hi = self.wave_mask({"k": "sgpr", "r": r, "n": 1}) words.append(hi if (self.wave64 and rk == lane_masks.MASK_HI) else lo) else: words.append(self.load_reg("sgpr", r)) return words[0], words[1] if s["k"] == "imm": v = s["v"] & 0xFFFFFFFFFFFFFFFF return self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) if s["k"] == "special" and s.get("t") == "null": return self.cu(0), self.cu(0) if self.holds_lane_mask(s): return self.wave_mask(s) if s["k"] == "special" and s.get("t") == "vcc": lo, hi = self.tmp(), self.tmp() self.emit(f"{lo} = OpLoad %uint %vcc") self.emit(f"{hi} = OpLoad %uint %vcc_hi") return lo, hi m = self.mask_src(s) return m, m (x0, x1), (y0, y1) = halves(a[0], f0), halves(a[1], f1) e0, e1, eq = self.tmp(), self.tmp(), self.tmp() self.emit(f"{e0} = OpIEqual %bool {x0} {y0}") self.emit(f"{e1} = OpIEqual %bool {x1} {y1}") self.emit(f"{eq} = OpLogicalAnd %bool {e0} {e1}") if op == "s_cmp_lg_u64": ne = self.tmp() self.emit(f"{ne} = OpLogicalNot %bool {eq}") eq = ne r = self.tmp() self.emit(f"{r} = OpSelect %uint {eq} {self.cu(1)} {self.cu(0)}") self.emit(f"OpStore %scc {r}") elif op.startswith("buffer_atomic_"): self.buffer_atomic(op, a, mods) elif op == "image_get_lod": self.image_get_lod(a, mods) elif op == "s_addk_i32": v = a[1]["v"] & 0xFFFF k = v - 0x10000 if v & 0x8000 else v x = self.src_u(a[0]) # the destination can be m0/vcc_hi as well as an SGPR r = self.tmp() self.emit(f"{r} = OpIAdd %uint {x} {self.cu(k)}") self.dst(a[0], r) self.scc_add_overflow(x, self.cu(k & 0xFFFFFFFF), r) elif op in ("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"): # Lane masks are all-ones/zero: carry in = (vcc or the named mask) != 0, carry out stored the same way. # (The short form v_add_co_ci_u32 vD, src0, src1 has its VCC operands from explicit_carry_vcc.) vd, cd = a[0], a[1] srcs = a[2:] x, y = self.src_u(srcs[0]), self.src_u(srcs[1]) if op.startswith("v_subrev_co"): x, y = y, x sub = "sub" in op if op.endswith("ci_u32"): cin_m = self.mask_src(srcs[2]) if len(srcs) > 2 else self.mask_src({"k": "special", "t": "vcc"}) cin = self.tmp() self.emit(f"{cin} = OpSelect %uint {self.tmp_bool_nz(cin_m)} {self.cu(1)} {self.cu(0)}") else: cin = self.cu(0) if sub and srcs[0] == srcs[1]: # x - x: the difference is 0 and there is no borrow, so D = 0 - carry in and the borrow out is the # carry in. Written out instead of OpISubBorrow %x %x: AMD's Windows driver (amdvlk64.dll, # 32.0.21037.1004 and 32.0.21045.29003, gfx1036) dies with an access violation creating a native # wave64 compute pipeline in which that borrow predicates a subgroup shuffle's value # (docs/design.md, "Carry-out subtract of a register from itself"). r = self.tmp() self.emit(f"{r} = OpISub %uint {self.cu(0)} {cin}") carry = cin else: s1, c1, s2, c2, r, carry = (self.tmp() for _ in range(6)) if sub: self.emit(f"{s1} = OpISubBorrow %umul {x} {y}") else: self.emit(f"{s1} = OpIAddCarry %umul {x} {y}") r1 = self.tmp() self.emit(f"{r1} = OpCompositeExtract %uint {s1} 0") self.emit(f"{c1} = OpCompositeExtract %uint {s1} 1") self.emit(f"{s2} = {'OpISubBorrow' if sub else 'OpIAddCarry'} %umul {r1} {cin}") 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 {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": # The inferred game's f32 denorm mode is flush-in/flush-out. Unlike an IEEE multiply, the legacy # zero override gives +0 even when a negative subnormal operand becomes -0 after input flushing. # Flush the product before omod: otherwise FLT_MIN * 0.5 mul:2 becomes FLT_MIN, not zero. x, y = (self.src_f(t) for t in a[1:3]) if self.ftz32: # Under DenormFlushToZero 32, OpFOrdEqual flushes subnormal inputs to 0 and OpFMul flushes # subnormal products to signed zero. Emit the canonical Mesa NIR fmulz pattern so RADV/ACO # lowers it to a single native v_mul_legacy_f32. m, zx, zy, either, r = (self.tmp() for _ in range(5)) self.emit(f"{m} = OpFMul %float {x} {y}") self.emit(f"{zx} = OpFOrdEqual %bool {x} %f0") self.emit(f"{zy} = OpFOrdEqual %bool {y} %f0") self.emit(f"{either} = OpLogicalOr %bool {zx} {zy}") self.emit(f"{r} = OpSelect %float {either} %f0 {m}") else: m, ax, ay, zx, zy, either, r = (self.tmp() for _ in range(7)) self.emit(f"{m} = OpFMul %float {x} {y}") self.emit(f"{ax} = OpExtInst %float %glsl FAbs {x}") self.emit(f"{ay} = OpExtInst %float %glsl FAbs {y}") self.emit(f"{zx} = OpFOrdLessThan %bool {ax} {self.fconst(2.0 ** -126)}") self.emit(f"{zy} = OpFOrdLessThan %bool {ay} {self.fconst(2.0 ** -126)}") self.emit(f"{either} = OpLogicalOr %bool {zx} {zy}") self.emit(f"{r} = OpSelect %float {either} %f0 {self.flush_f32(m)}") r = self.clamp_mods(r, mods) if any(mod in ("mul:2", "mul:4", "div:2") for mod in mods): r = self.flush_f32(r) # With IEEE off, omod makes -0 (including a flushed subnormal result) +0. z, pos = self.tmp(), self.tmp() self.emit(f"{z} = OpFOrdEqual %bool {r} %f0") self.emit(f"{pos} = OpSelect %float {z} %f0 {r}") r = pos self.dst(a[0], self.tou(r)) elif op in ("v_mad_legacy_f32", "v_mac_legacy_f32"): # Legacy multiply treats 0 * anything (inf/NaN included) as 0, after the denormal flush. # v_mac_legacy_f32 is the GFX10.1 VOP2 form with D as the addend, as v_mac_f32 is to v_mad_f32 (LLVM # VOP2Instructions.td: V_MAC_LEGACY_F32 is VOP_F32_F32_F32 with $src2 tied to $vdst). srcs = (a[1], a[2], a[0]) if op == "v_mac_legacy_f32" else a[1:4] x, y, z = (self.flush_f32(self.src_f(t)) for t in srcs) m, zx, zy, either, sel, r = (self.tmp() for _ in range(6)) self.emit(f"{m} = OpFMul %float {x} {y}") self.emit(f"{zx} = OpFOrdEqual %bool {x} %f0") self.emit(f"{zy} = OpFOrdEqual %bool {y} %f0") self.emit(f"{either} = OpLogicalOr %bool {zx} {zy}") self.emit(f"{sel} = OpSelect %float {either} %f0 {self.flush_f32(m)}") self.emit(f"{r} = OpFAdd %float {sel} {z}") self.dst(a[0], self.tou(self.flush_f32_mods(r, mods))) elif op in ("v_min3_i32", "v_min3_u32", "v_max3_i32", "v_max3_u32"): x, y, z = (self.src_u(t) for t in a[1:4]) f = ("S" if op.endswith("i32") else "U") + ("Min" if "min" in op else "Max") m, r = self.tmp(), self.tmp() self.emit(f"{m} = OpExtInst %uint %glsl {f} {x} {y}") self.emit(f"{r} = OpExtInst %uint %glsl {f} {m} {z}") self.dst(a[0], r) elif op in ("v_med3_i32", "v_med3_u32"): x, y, z = (self.src_u(t) for t in a[1:4]) s = "S" if op.endswith("i32") else "U" lo, hi, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{lo} = OpExtInst %uint %glsl {s}Min {x} {y}") self.emit(f"{hi} = OpExtInst %uint %glsl {s}Max {x} {y}") self.emit(f"{r} = OpExtInst %uint %glsl {s}Clamp {z} {lo} {hi}") self.dst(a[0], r) elif op in ("v_div_fixup_f16", "v_div_fixup_f64"): self._validate_div_valu( ins, op, mods, dst_width=1 if op == "v_div_fixup_f16" else 2, src_width=1 if op == "v_div_fixup_f16" else None, allow_opsel=op == "v_div_fixup_f16", strict_omod=False, ) # Final IEEE-754 special-case fixup for division (RDNA2 ISA VOP3, S0=quot, S1=denom, S2=num): # sign_out = sign(S1) ^ sign(S2); NaN(S2) -> quiet(S2); NaN(S1) -> quiet(S1); # (0/0 or inf/inf) -> -qNaN; (x/inf or 0/y) -> +-0; (x/0 or inf/y or NaN(S0)) -> +-inf; # otherwise copysign(S0, sign_out). Computed bit-exact on integer words; Float64 is only needed # when VOP3 output modifiers (omod/clamp) are present on v_div_fixup_f64. # The destination of both forms is a 16-bit or 64-bit float, and hardware ignores mul:/div: on those # results while denorm_mode_16_64 = 3 (the game's MODE): measured with tools/hw_oracle on gfx1036, # wave32 and wave64 identical, in tools/f64_omod_probe.py. clamp applies in every MODE. has_clamp = "clamp" in mods if op == "v_div_fixup_f16": sel, dhi = self.opsel_bits(mods, 3) def h16(sv, hi_half): u = self.src_h(sv) if hi_half: t = self.tmp() self.emit(f"{t} = OpShiftRightLogical %uint {u} {self.cu(16)}") u = t x = self.tmp() self.emit(f"{x} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}") if sv.get("abs"): t = self.tmp() self.emit(f"{t} = OpBitwiseAnd %uint {x} {self.cu(0x7FFF)}") x = t if sv.get("neg"): t = self.tmp() self.emit(f"{t} = OpBitwiseXor %uint {x} {self.cu(0x8000)}") x = t return x s0, s1, s2 = (h16(a[i + 1], sel[i]) for i in range(3)) def cls16(w): mag, iz, iinf, inan = (self.tmp() for _ in range(4)) self.emit(f"{mag} = OpBitwiseAnd %uint {w} {self.cu(0x7FFF)}") self.emit(f"{iz} = OpIEqual %bool {mag} {self.cu(0)}") self.emit(f"{iinf} = OpIEqual %bool {mag} {self.cu(0x7C00)}") self.emit(f"{inan} = OpUGreaterThan %bool {mag} {self.cu(0x7C00)}") return mag, iz, iinf, inan m0, _, _, nan0 = cls16(s0) _, z1, inf1, nan1 = cls16(s1) _, z2, inf2, nan2 = cls16(s2) sx, sgn, inf_out, norm_out = (self.tmp() for _ in range(4)) self.emit(f"{sx} = OpBitwiseXor %uint {s1} {s2}") self.emit(f"{sgn} = OpBitwiseAnd %uint {sx} {self.cu(0x8000)}") self.emit(f"{inf_out} = OpBitwiseOr %uint {sgn} {self.cu(0x7C00)}") self.emit(f"{norm_out} = OpBitwiseOr %uint {sgn} {m0}") b_zz, b_ii, b_ind, b_zero, b_inf1, b_inf = (self.tmp() for _ in range(6)) self.emit(f"{b_zz} = OpLogicalAnd %bool {z1} {z2}") self.emit(f"{b_ii} = OpLogicalAnd %bool {inf1} {inf2}") self.emit(f"{b_ind} = OpLogicalOr %bool {b_zz} {b_ii}") self.emit(f"{b_zero} = OpLogicalOr %bool {inf1} {z2}") self.emit(f"{b_inf1} = OpLogicalOr %bool {z1} {inf2}") self.emit(f"{b_inf} = OpLogicalOr %bool {b_inf1} {nan0}") r1, r2, r3, r4, r5 = (self.tmp() for _ in range(5)) self.emit(f"{r1} = OpSelect %uint {b_inf} {inf_out} {norm_out}") self.emit(f"{r2} = OpSelect %uint {b_zero} {sgn} {r1}") self.emit(f"{r3} = OpSelect %uint {b_ind} {self.cu(0xFE00)} {r2}") self.emit(f"{r4} = OpSelect %uint {nan1} {s1} {r3}") self.emit(f"{r5} = OpSelect %uint {nan2} {s2} {r4}") if has_clamp: r5 = self.clamp_f16_bits(r5) self.write_half16(a[0], r5, dhi) else: d = a[0] if d["k"] != "vgpr" or d.get("n") != 2: raise Unsupported(op + " destination") def d64_words(sv): if sv["k"] in ("vgpr", "sgpr") and sv.get("n") == 2: lo, hi = self.load_reg(sv["k"], sv["r"]), self.load_reg(sv["k"], sv["r"] + 1) elif sv["k"] in ("imm", "fimm"): bits = (struct.unpack("> 32) else: raise Unsupported(op + " operand") if sv.get("abs"): t = self.tmp() self.emit(f"{t} = OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}") hi = t if sv.get("neg"): t = self.tmp() self.emit(f"{t} = OpBitwiseXor %uint {hi} {self.cu(0x80000000)}") hi = t return lo, hi (lo0, hi0), (lo1, hi1), (lo2, hi2) = (d64_words(a[i]) for i in (1, 2, 3)) def cls64(lo, hi): mag, orz, iz, exp_all, loz, iinf, man_hi, man_or, man_nz, inan = (self.tmp() for _ in range(10)) self.emit(f"{mag} = OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}") self.emit(f"{orz} = OpBitwiseOr %uint {mag} {lo}") self.emit(f"{iz} = OpIEqual %bool {orz} {self.cu(0)}") self.emit(f"{exp_all} = OpIEqual %bool {mag} {self.cu(0x7FF00000)}") self.emit(f"{loz} = OpIEqual %bool {lo} {self.cu(0)}") self.emit(f"{iinf} = OpLogicalAnd %bool {exp_all} {loz}") self.emit(f"{man_hi} = OpBitwiseAnd %uint {mag} {self.cu(0x7FF00000)}") exp_max = self.tmp() self.emit(f"{exp_max} = OpIEqual %bool {man_hi} {self.cu(0x7FF00000)}") frac_hi = self.tmp() self.emit(f"{frac_hi} = OpBitwiseAnd %uint {hi} {self.cu(0x000FFFFF)}") self.emit(f"{man_or} = OpBitwiseOr %uint {frac_hi} {lo}") self.emit(f"{man_nz} = OpINotEqual %bool {man_or} {self.cu(0)}") self.emit(f"{inan} = OpLogicalAnd %bool {exp_max} {man_nz}") return mag, iz, iinf, inan m0, _, _, nan0 = cls64(lo0, hi0) _, z1, inf1, nan1 = cls64(lo1, hi1) _, z2, inf2, nan2 = cls64(lo2, hi2) e1, e2, ediff, ediff_i, uf = (self.tmp() for _ in range(5)) self.emit(f"{e1} = OpBitFieldUExtract %uint {hi1} {self.cu(20)} {self.cu(11)}") self.emit(f"{e2} = OpBitFieldUExtract %uint {hi2} {self.cu(20)} {self.cu(11)}") self.emit(f"{ediff} = OpISub %uint {e2} {e1}") self.emit(f"{ediff_i} = OpBitcast %int {ediff}") # Measured natively on RDNA2 gfx1036: underflow cutoff is e2 - e1 <= -1076 (no overflow check). self.emit(f"{uf} = OpSLessThan %bool {ediff_i} {self.as_int(self.cu((-1075) & 0xFFFFFFFF))}") sx, sgn, inf_hi, norm_hi = (self.tmp() for _ in range(4)) self.emit(f"{sx} = OpBitwiseXor %uint {hi1} {hi2}") self.emit(f"{sgn} = OpBitwiseAnd %uint {sx} {self.cu(0x80000000)}") self.emit(f"{inf_hi} = OpBitwiseOr %uint {sgn} {self.cu(0x7FF00000)}") self.emit(f"{norm_hi} = OpBitwiseOr %uint {sgn} {m0}") b_zz, b_ii, b_ind, b_zero1, b_zero, b_inf1, b_inf = (self.tmp() for _ in range(7)) self.emit(f"{b_zz} = OpLogicalAnd %bool {z1} {z2}") self.emit(f"{b_ii} = OpLogicalAnd %bool {inf1} {inf2}") self.emit(f"{b_ind} = OpLogicalOr %bool {b_zz} {b_ii}") self.emit(f"{b_zero1} = OpLogicalOr %bool {inf1} {z2}") self.emit(f"{b_zero} = OpLogicalOr %bool {b_zero1} {uf}") self.emit(f"{b_inf1} = OpLogicalOr %bool {z1} {inf2}") self.emit(f"{b_inf} = OpLogicalOr %bool {b_inf1} {nan0}") z0 = self.cu(0) h1, l1, h2, l2, h3, l3, h4, l4, r_hi, r_lo = (self.tmp() for _ in range(10)) self.emit(f"{h1} = OpSelect %uint {b_inf} {inf_hi} {norm_hi}") self.emit(f"{l1} = OpSelect %uint {b_inf} {z0} {lo0}") self.emit(f"{h2} = OpSelect %uint {b_zero} {sgn} {h1}") self.emit(f"{l2} = OpSelect %uint {b_zero} {z0} {l1}") self.emit(f"{h3} = OpSelect %uint {b_ind} {self.cu(0xFFF80000)} {h2}") self.emit(f"{l3} = OpSelect %uint {b_ind} {z0} {l2}") self.emit(f"{h4} = OpSelect %uint {nan1} {hi1} {h3}") self.emit(f"{l4} = OpSelect %uint {nan1} {lo1} {l3}") self.emit(f"{r_hi} = OpSelect %uint {nan2} {hi2} {h4}") self.emit(f"{r_lo} = OpSelect %uint {nan2} {lo2} {l4}") if has_clamp: self.uses_f64 = True v2, dv, mv2 = self.tmp(), self.tmp(), self.tmp() self.emit(f"{v2} = OpCompositeConstruct %v2uint_d {r_lo} {r_hi}") self.emit(f"{dv} = OpBitcast %double {v2}") dv = self.clamp_mods_f64(dv, [m for m in mods if m == "clamp"]) self.emit(f"{mv2} = OpBitcast %v2uint_d {dv}") r_lo, r_hi = self.tmp(), self.tmp() self.emit(f"{r_lo} = OpCompositeExtract %uint {mv2} 0") self.emit(f"{r_hi} = OpCompositeExtract %uint {mv2} 1") self.dst({"k": "vgpr", "r": d["r"], "n": 1}, r_lo) self.dst({"k": "vgpr", "r": d["r"] + 1, "n": 1}, r_hi) elif op.startswith("s_load_dword") or op.startswith("s_buffer_load_dword"): self.scalar_load(op, a, ins["mods"]) elif op in ("s_memtime", "s_memrealtime"): d = a[0] if d["k"] != "sgpr" or d.get("n") != 2: raise Unsupported(op + " destination") if not SHADER_CLOCK: raise Unsupported(op + " (needs --shader-clock khr)") scope = "subgroup" if op == "s_memtime" else "device" self.uses_clock.add(scope) v, lo, hi = self.tmp(), self.tmp(), self.tmp() self.emit(f"{v} = OpReadClockKHR %v2uint_d {self.cu(3 if scope == 'subgroup' else 1)}") self.emit(f"{lo} = OpCompositeExtract %uint {v} 0") self.emit(f"{hi} = OpCompositeExtract %uint {v} 1") self.store_reg("sgpr", d["r"], lo) self.store_reg("sgpr", d["r"] + 1, hi) elif op in ("s_lshl_b64", "s_lshr_b64", "s_ashr_i64"): # 64-bit shift of an SGPR pair by (src1 & 63); SCC = result != 0. d, x = a[0], a[1] if d["k"] != "sgpr" or d.get("n") != 2: raise Unsupported(op + " destination") if x["k"] == "sgpr" and x.get("n") == 2: lo, hi = self.load_reg("sgpr", x["r"]), self.load_reg("sgpr", x["r"] + 1) elif x["k"] == "imm": v = x["v"] & 0xFFFFFFFFFFFFFFFF lo, hi = self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) else: raise Unsupported(op + " source") sh = self.src_u(a[2]) l64, h64, t, v64, m, s64, r, rlo, rh, rhi = (self.tmp() for _ in range(10)) self.emit(f"{l64} = OpUConvert %ulong {lo}") self.emit(f"{h64} = OpUConvert %ulong {hi}") self.emit(f"{t} = OpShiftLeftLogical %ulong {h64} %c64_32") self.emit(f"{v64} = OpBitwiseOr %ulong {t} {l64}") self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(63)}") self.emit(f"{s64} = OpUConvert %ulong {m}") if op == "s_ashr_i64": vs64, rs64 = self.tmp(), self.tmp() self.emit(f"{vs64} = OpBitcast %long {v64}") self.emit(f"{rs64} = OpShiftRightArithmetic %long {vs64} {s64}") self.emit(f"{r} = OpBitcast %ulong {rs64}") elif op == "s_lshl_b64": self.emit(f"{r} = OpShiftLeftLogical %ulong {v64} {s64}") else: self.emit(f"{r} = OpShiftRightLogical %ulong {v64} {s64}") self.emit(f"{rlo} = OpUConvert %uint {r}") self.emit(f"{rh} = OpShiftRightLogical %ulong {r} %c64_32") self.emit(f"{rhi} = OpUConvert %uint {rh}") self.store_reg("sgpr", d["r"], rlo) self.store_reg("sgpr", d["r"] + 1, rhi) nz, z = self.tmp(), self.tmp() orr = self.tmp() self.emit(f"{orr} = OpBitwiseOr %uint {rlo} {rhi}") self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(orr)} {self.cu(1)} {self.cu(0)}") self.emit(f"OpStore %scc {z}") self.uses_psb = True # Int64 capability and %ulong come with the PSB declarations elif op == "s_ashr_i32": x, sh = self.src_u(a[1]), self.src_u(a[2]) m, xi, ri, r = (self.tmp() for _ in range(4)) self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(31)}") self.emit(f"{xi} = OpBitcast %int {x}") self.emit(f"{ri} = OpShiftRightArithmetic %int {xi} {m}") self.emit(f"{r} = OpBitcast %uint {ri}") self.dst(a[0], r) z = self.tmp() self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") self.emit(f"OpStore %scc {z}") elif op.startswith("global_atomic_"): self.global_atomic(op, a, mods) elif op in self.GLOBAL_SUB: self.global_sub(op, a, mods) elif op.startswith(("global_load_dword", "global_store_dword")) or \ op in ("global_load_ushort", "global_load_sshort", "global_load_ubyte", "global_load_sbyte"): self.global_mem(op, a, mods) elif op.startswith(("flat_load_", "flat_store_")): self.flat_mem(op, a, mods) elif op in ("s_add_u32", "s_addc_u32", "s_sub_u32", "s_subb_u32"): # 32-bit add/sub with carry/borrow through SCC (used for 64-bit address arithmetic, e.g. s_getpc + offset). sub = op.startswith("s_sub") val = None if op in ("s_add_u32", "s_sub_u32"): x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) if x_val is not None and y_val is not None: if sub: val = (x_val - y_val) & 0xFFFFFFFF else: val = (x_val + y_val) & 0xFFFFFFFF x, y = self.src_u(a[1]), self.src_u(a[2]) s1, r1, c1 = self.tmp(), self.tmp(), self.tmp() self.emit(f"{s1} = {'OpISubBorrow' if sub else 'OpIAddCarry'} %umul {x} {y}") self.emit(f"{r1} = OpCompositeExtract %uint {s1} 0") self.emit(f"{c1} = OpCompositeExtract %uint {s1} 1") r, carry = r1, c1 if op in ("s_addc_u32", "s_subb_u32"): cin, s2, r2, c2, cc = (self.tmp() for _ in range(5)) self.emit(f"{cin} = OpLoad %uint %scc") self.emit(f"{s2} = {'OpISubBorrow' if sub else 'OpIAddCarry'} %umul {r1} {cin}") self.emit(f"{r2} = OpCompositeExtract %uint {s2} 0") self.emit(f"{c2} = OpCompositeExtract %uint {s2} 1") self.emit(f"{cc} = OpBitwiseOr %uint {c1} {c2}") r, carry = r2, cc self.dst(a[0], r) self.emit(f"OpStore %scc {carry}") if val is not None and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: self.sgpr_imm[a[0]["r"]] = val elif op in ("s_lshl1_add_u32", "s_lshl2_add_u32", "s_lshl3_add_u32", "s_lshl4_add_u32"): # D = (S0 << N) + S1. SCC = unsigned overflow of the sum taken in 64 bits (RDNA ISA pseudocode: # tmp = (64'U(S0) << N) + 64'U(S1); SCC = tmp >= 2^32), so bits shifted out of S0 count as a carry too. n = int(op[6]) val = None x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) if x_val is not None and y_val is not None: val = ((x_val << n) + y_val) & 0xFFFFFFFF x, y = self.src_u(a[1]), self.src_u(a[2]) sh, out, s, r, c, ovf = (self.tmp() for _ in range(6)) self.emit(f"{sh} = OpShiftLeftLogical %uint {x} {self.cu(n)}") self.emit(f"{out} = OpShiftRightLogical %uint {x} {self.cu(32 - n)}") self.emit(f"{s} = OpIAddCarry %umul {sh} {y}") self.emit(f"{r} = OpCompositeExtract %uint {s} 0") self.emit(f"{c} = OpCompositeExtract %uint {s} 1") self.emit(f"{ovf} = OpBitwiseOr %uint {out} {c}") self.dst(a[0], r) self.scc_nonzero(ovf) if val is not None and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: self.sgpr_imm[a[0]["r"]] = val elif op == "s_get_waveid_in_workgroup": # D = this wave's index in its workgroup: thread i of a group is in wave i / W (W = 64 or 32), the rule # wave_lane uses for the lane. Only compute and mesh shaders have a workgroup. SCC is not written. if self.stage not in ("cs", "ms"): raise Unsupported(op + " outside compute") r = self.tmp() self.emit(f"{r} = OpShiftRightLogical %uint {self.local_index()} {self.cu(6 if self.wave64 else 5)}") self.dst(a[0], r) elif op == "s_getpc_b64": # Address of the next instruction: code base (push constants 34-35: where the runtime put this shader's # FSSM blob in the Xbox VA window) + offset of the next instruction within the blob. if a[0]["k"] != "sgpr" or a[0].get("n") != 2: raise Unsupported("s_getpc_b64 destination") if not ins.get("enc"): # Without the `; encoding:` bytes the instruction's size, and so the next PC, is unknown. raise Unsupported("s_getpc_b64 without encoding") nxt = ins["pc"] + len(ins["enc"]) // 2 lo, hi, s, rlo, c, rhi = (self.tmp() for _ in range(6)) self.emit(f"{lo} = OpLoad %uint %ud_code_lo_p") self.emit(f"{hi} = OpLoad %uint %ud_code_hi_p") self.emit(f"{s} = OpIAddCarry %umul {lo} {self.cu(nxt)}") self.emit(f"{rlo} = OpCompositeExtract %uint {s} 0") self.emit(f"{c} = OpCompositeExtract %uint {s} 1") self.emit(f"{rhi} = OpIAdd %uint {hi} {c}") self.store_reg("sgpr", a[0]["r"], rlo) self.store_reg("sgpr", a[0]["r"] + 1, rhi) self.uses_codebase = True self.cu(3), self.cu(4) elif op in ("s_add_i32", "s_sub_i32", "s_min_u32", "s_max_u32", "s_xor_b32", "s_andn2_b32", "s_cselect_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32", "s_xnor_b32"): val = None to_mask_dst, dst_half = (self._mask_b32_dst_half(a[0], a[1:3]) if op in self.MASK_SOP2_B32 else (False, None)) if op in ("s_xor_b32", "s_andn2_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32", "s_xnor_b32"): x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) is_mask = to_mask_dst or self.holds_lane_mask(a[1]) or self.holds_lane_mask(a[2]) if x_val is not None and y_val is not None and not is_mask: if op == "s_xor_b32": val = (x_val ^ y_val) & 0xFFFFFFFF r = self.cu(val) self.dst(a[0], r) if a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: self.sgpr_imm[a[0]["r"]] = val self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}") return elif op == "s_andn2_b32": val = (x_val & (~y_val)) & 0xFFFFFFFF elif op == "s_orn2_b32": val = (x_val | (~y_val)) & 0xFFFFFFFF elif op == "s_nand_b32": val = (~(x_val & y_val)) & 0xFFFFFFFF elif op == "s_nor_b32": val = (~(x_val | y_val)) & 0xFFFFFFFF elif op == "s_xnor_b32": val = (~(x_val ^ y_val)) & 0xFFFFFFFF elif op in ("s_min_u32", "s_max_u32"): x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) if x_val is not None and y_val is not None: val = min(x_val, y_val) if "min" in op else max(x_val, y_val) elif op in ("s_add_i32", "s_sub_i32"): x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) if x_val is not None and y_val is not None: xi = x_val if x_val < 0x80000000 else x_val - 0x100000000 yi = y_val if y_val < 0x80000000 else y_val - 0x100000000 val = (xi + yi if op == "s_add_i32" else xi - yi) & 0xFFFFFFFF x, y = self.sop2_b32_srcs(op, a) r = self.tmp() if op == "s_cselect_b32": c, b = self.tmp(), self.tmp() self.emit(f"{c} = OpLoad %uint %scc") self.emit(f"{b} = OpINotEqual %bool {c} {self.cu(0)}") self.emit(f"{r} = OpSelect %uint {b} {x} {y}") elif op == "s_andn2_b32": n = self.tmp() self.emit(f"{n} = OpNot %uint {y}") self.emit(f"{r} = OpBitwiseAnd %uint {x} {n}") elif op in ("s_min_u32", "s_max_u32"): self.emit(f"{r} = OpExtInst %uint %glsl {'UMin' if 'min' in op else 'UMax'} {x} {y}") elif op == "s_orn2_b32": n = self.tmp() self.emit(f"{n} = OpNot %uint {y}") self.emit(f"{r} = OpBitwiseOr %uint {x} {n}") elif op in ("s_nand_b32", "s_nor_b32", "s_xnor_b32"): t = self.tmp() k = {"s_nand_b32": "OpBitwiseAnd", "s_nor_b32": "OpBitwiseOr", "s_xnor_b32": "OpBitwiseXor"}[op] self.emit(f"{t} = {k} %uint {x} {y}") self.emit(f"{r} = OpNot %uint {t}") else: k = {"s_add_i32": "OpIAdd", "s_sub_i32": "OpISub", "s_sub_u32": "OpISub", "s_xor_b32": "OpBitwiseXor"}[op] self.emit(f"{r} = {k} %uint {x} {y}") self._store_b32_mask_dst(a[0], r, to_mask_dst, dst_half) # SCC (RDNA ISA): bitwise ops -> result != 0; s_add/sub_i32 -> signed overflow; # s_min_u32 -> S0 < S1, s_max_u32 -> S0 > S1; s_cselect leaves SCC. if op in ("s_xor_b32", "s_andn2_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32", "s_xnor_b32"): self.scc_logic(a, r) elif op in ("s_add_i32", "s_sub_i32"): self.scc_add_overflow(x, y, r, sub=op == "s_sub_i32") elif op in ("s_min_u32", "s_max_u32"): b = self.tmp() self.emit(f"{b} = {'OpULessThan' if 'min' in op else 'OpUGreaterThan'} %bool {x} {y}") self.set_scc(b) if val is not None and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: self.sgpr_imm[a[0]["r"]] = val elif op in ("s_wqm_b64", "s_wqm_b32"): self.wqm(op, a) elif op == "v_fma_mix_f32": # Each source is f32, or (op_sel_hi bit set) an f16 from the low/high half chosen by op_sel. vals = self.fma_mix_srcs(a, mods) r = self.tmp() self.emit_fma(r, vals[0], vals[1], vals[2]) self.dst(a[0], self.tou(self.clamp_mods(r, mods))) elif op in ("v_div_fmas_f32", "v_div_fmas_f64"): self._validate_div_valu( ins, op, mods, dst_width=1 if op == "v_div_fmas_f32" else 2, src_width=1 if op == "v_div_fmas_f32" else None, allow_opsel=False, strict_omod=True, allow_null_dst=op == "v_div_fmas_f32", ) # Scaled FMA for IEEE-754 division (RDNA2 ISA VOP3, measured natively on gfx1036 wave32/wave64): # VCC == 0: fma(S0, S1, S2) # VCC == 1: (exp(S2) > bias ? 2^S : 2^-S) * fma_exact(S0, S1, S2) # where (bias, S) = (127, 64) for f32 and (1023, 128) for f64 (exp(S2) > bias <=> |S2| >= 2.0). # Scale-up (|S2| >= 2.0): any non-zero cancellation residual against |S2| >= 2.0 stays well above # normal minimum, and any intermediate overflow overflows after * 2^S too, so fma(x, y, z) * 2^S is # exact. Scale-down (|S2| < 2.0): pre-scale only when |x*y| can overflow (|x|>=2^S & |y|>=1, or # |y|>=2^S & |x|>=1, or |x|,|y|>=2^(S/2)), preserving a sticky bit when 0 < |z| < 2^(Emin+S); # otherwise post-scale fma(x, y, z) * 2^-S (with f64 subnormal half-ULP tie correction so f64 # subnormal outputs single-round, and f32 output denormal flush matching denorm32=0). vcc_b = self.tmp_bool_nz(self.mask_src({"k": "special", "t": "vcc"})) if op == "v_div_fmas_f32": x, y, z = (self.src_f(t) for t in a[1:4]) ax, ay, az, f_plain, scale_up, f_up = (self.tmp() for _ in range(6)) self.emit(f"{ax} = OpExtInst %float %glsl FAbs {x}") self.emit(f"{ay} = OpExtInst %float %glsl FAbs {y}") self.emit(f"{az} = OpExtInst %float %glsl FAbs {z}") self.emit_fma(f_plain, x, y, z) self.emit(f"{scale_up} = OpFOrdGreaterThanEqual %bool {az} {self.fconst(2.0)}") self.emit(f"{f_up} = OpFMul %float {f_plain} {self.fconst(2.0 ** 64)}") gx64, gy1, bx, gy64, gx1, by, gx32, gy32, bxy, b1, big = (self.tmp() for _ in range(11)) self.emit(f"{gx64} = OpFOrdGreaterThanEqual %bool {ax} {self.fconst(2.0 ** 64)}") self.emit(f"{gy1} = OpFOrdGreaterThanEqual %bool {ay} {self.fconst(1.0)}") self.emit(f"{bx} = OpLogicalAnd %bool {gx64} {gy1}") self.emit(f"{gy64} = OpFOrdGreaterThanEqual %bool {ay} {self.fconst(2.0 ** 64)}") self.emit(f"{gx1} = OpFOrdGreaterThanEqual %bool {ax} {self.fconst(1.0)}") self.emit(f"{by} = OpLogicalAnd %bool {gy64} {gx1}") self.emit(f"{gx32} = OpFOrdGreaterThanEqual %bool {ax} {self.fconst(2.0 ** 32)}") self.emit(f"{gy32} = OpFOrdGreaterThanEqual %bool {ay} {self.fconst(2.0 ** 32)}") self.emit(f"{bxy} = OpLogicalAnd %bool {gx32} {gy32}") self.emit(f"{b1} = OpLogicalOr %bool {bx} {by}") self.emit(f"{big} = OpLogicalOr %bool {b1} {bxy}") xm64, ym64, xm32, ym32, xs1, xs, ys1, ys = (self.tmp() for _ in range(8)) self.emit(f"{xm64} = OpFMul %float {x} {self.fconst(2.0 ** -64)}") self.emit(f"{ym64} = OpFMul %float {y} {self.fconst(2.0 ** -64)}") self.emit(f"{xm32} = OpFMul %float {x} {self.fconst(2.0 ** -32)}") self.emit(f"{ym32} = OpFMul %float {y} {self.fconst(2.0 ** -32)}") self.emit(f"{xs1} = OpSelect %float {by} {x} {xm32}") self.emit(f"{xs} = OpSelect %float {bx} {xm64} {xs1}") self.emit(f"{ys1} = OpSelect %float {by} {ym64} {ym32}") self.emit(f"{ys} = OpSelect %float {bx} {y} {ys1}") zu, zmag, znz, zlt, ztiny, zsgn, zst_u, zst, z_sc, zs = (self.tmp() for _ in range(10)) self.emit(f"{zu} = OpBitcast %uint {z}") self.emit(f"{zmag} = OpBitwiseAnd %uint {zu} {self.cu(0x7FFFFFFF)}") self.emit(f"{znz} = OpINotEqual %bool {zmag} {self.cu(0)}") self.emit(f"{zlt} = OpULessThan %bool {zmag} {self.cu(0x20800000)}") self.emit(f"{ztiny} = OpLogicalAnd %bool {znz} {zlt}") self.emit(f"{zsgn} = OpBitwiseAnd %uint {zu} {self.cu(0x80000000)}") self.emit(f"{zst_u} = OpBitwiseOr %uint {zsgn} {self.cu(0x00800000)}") self.emit(f"{zst} = OpBitcast %float {zst_u}") self.emit(f"{z_sc} = OpFMul %float {z} {self.fconst(2.0 ** -64)}") self.emit(f"{zs} = OpSelect %float {ztiny} {zst} {z_sc}") f_pre, f_post, f_dn, sc, r = (self.tmp() for _ in range(5)) self.emit_fma(f_pre, xs, ys, zs) self.emit(f"{f_post} = OpFMul %float {f_plain} {self.fconst(2.0 ** -64)}") self.emit(f"{f_dn} = OpSelect %float {big} {f_pre} {f_post}") self.emit(f"{sc} = OpSelect %float {scale_up} {f_up} {f_dn}") self.emit(f"{r} = OpSelect %float {vcc_b} {sc} {f_plain}") r = self.flush_f32(r) if mods: r = self.clamp_mods(r, mods) if any(m in ("mul:2", "mul:4", "div:2") for m in mods): r = self.flush_f32(r) self.dst(a[0], self.tou(r)) else: def f64(sv): if sv["k"] in ("vgpr", "sgpr") and sv.get("n") == 2: lo, hi = self.load_reg(sv["k"], sv["r"]), self.load_reg(sv["k"], sv["r"] + 1) elif sv["k"] in ("imm", "fimm"): bits = (struct.unpack("> 32) else: raise Unsupported(op + " operand") v2, d = self.tmp(), self.tmp() self.emit(f"{v2} = OpCompositeConstruct %v2uint_d {lo} {hi}") self.emit(f"{d} = OpBitcast %double {v2}") if sv.get("abs"): t = self.tmp() self.emit(f"{t} = OpExtInst %double %glsl FAbs {d}") d = t if sv.get("neg"): t = self.tmp() self.emit(f"{t} = OpFNegate %double {d}") d = t return d d = a[0] if d["k"] != "vgpr" or d.get("n") != 2: raise Unsupported(op + " destination") self.uses_f64 = True x, y, z = (f64(t) for t in a[1:4]) ax, ay, az, f_plain, scale_up, f_up = (self.tmp() for _ in range(6)) self.emit(f"{ax} = OpExtInst %double %glsl FAbs {x}") self.emit(f"{ay} = OpExtInst %double %glsl FAbs {y}") self.emit(f"{az} = OpExtInst %double %glsl FAbs {z}") self.emit_fma64(f_plain, x, y, z) self.emit(f"{scale_up} = OpFOrdGreaterThanEqual %bool {az} {self.dconst(2.0)}") self.emit(f"{f_up} = OpFMul %double {f_plain} {self.dconst(2.0 ** 128)}") gx128, gy1, bx, gy128, gx1, by, gx64, gy64, bxy, b1, big = (self.tmp() for _ in range(11)) self.emit(f"{gx128} = OpFOrdGreaterThanEqual %bool {ax} {self.dconst(2.0 ** 128)}") self.emit(f"{gy1} = OpFOrdGreaterThanEqual %bool {ay} {self.dconst(1.0)}") self.emit(f"{bx} = OpLogicalAnd %bool {gx128} {gy1}") self.emit(f"{gy128} = OpFOrdGreaterThanEqual %bool {ay} {self.dconst(2.0 ** 128)}") self.emit(f"{gx1} = OpFOrdGreaterThanEqual %bool {ax} {self.dconst(1.0)}") self.emit(f"{by} = OpLogicalAnd %bool {gy128} {gx1}") self.emit(f"{gx64} = OpFOrdGreaterThanEqual %bool {ax} {self.dconst(2.0 ** 64)}") self.emit(f"{gy64} = OpFOrdGreaterThanEqual %bool {ay} {self.dconst(2.0 ** 64)}") self.emit(f"{bxy} = OpLogicalAnd %bool {gx64} {gy64}") self.emit(f"{b1} = OpLogicalOr %bool {bx} {by}") self.emit(f"{big} = OpLogicalOr %bool {b1} {bxy}") xm128, ym128, xm64, ym64, xs1, xs, ys1, ys = (self.tmp() for _ in range(8)) self.emit(f"{xm128} = OpFMul %double {x} {self.dconst(2.0 ** -128)}") self.emit(f"{ym128} = OpFMul %double {y} {self.dconst(2.0 ** -128)}") self.emit(f"{xm64} = OpFMul %double {x} {self.dconst(2.0 ** -64)}") self.emit(f"{ym64} = OpFMul %double {y} {self.dconst(2.0 ** -64)}") self.emit(f"{xs1} = OpSelect %double {by} {x} {xm64}") self.emit(f"{xs} = OpSelect %double {bx} {xm128} {xs1}") self.emit(f"{ys1} = OpSelect %double {by} {ym128} {ym64}") self.emit(f"{ys} = OpSelect %double {bx} {y} {ys1}") zv2, zlo, zhi, zmag_hi, zmag_or, znz, zexp, zlt, ztiny, zsgn, zst_hi, zst_v2, zst, z_sc, zs = ( self.tmp() for _ in range(15) ) self.emit(f"{zv2} = OpBitcast %v2uint_d {z}") self.emit(f"{zlo} = OpCompositeExtract %uint {zv2} 0") self.emit(f"{zhi} = OpCompositeExtract %uint {zv2} 1") self.emit(f"{zmag_hi} = OpBitwiseAnd %uint {zhi} {self.cu(0x7FFFFFFF)}") self.emit(f"{zmag_or} = OpBitwiseOr %uint {zmag_hi} {zlo}") self.emit(f"{znz} = OpINotEqual %bool {zmag_or} {self.cu(0)}") self.emit(f"{zexp} = OpBitwiseAnd %uint {zhi} {self.cu(0x7FF00000)}") self.emit(f"{zlt} = OpULessThan %bool {zexp} {self.cu(129 << 20)}") self.emit(f"{ztiny} = OpLogicalAnd %bool {znz} {zlt}") self.emit(f"{zsgn} = OpBitwiseAnd %uint {zhi} {self.cu(0x80000000)}") self.emit(f"{zst_hi} = OpBitwiseOr %uint {zsgn} {self.cu(0x00100000)}") self.emit(f"{zst_v2} = OpCompositeConstruct %v2uint_d {self.cu(0)} {zst_hi}") self.emit(f"{zst} = OpBitcast %double {zst_v2}") self.emit(f"{z_sc} = OpFMul %double {z} {self.dconst(2.0 ** -128)}") self.emit(f"{zs} = OpSelect %double {ztiny} {zst} {z_sc}") f_pre = self.tmp() self.emit_fma64(f_pre, xs, ys, zs) # Subnormal-output single-rounding tie adjustment when |f_plain| in [2^-947, 2^-894). pv2, plo, phi, pe_shift, pe_exp, e_ge, e_le, in_rng = (self.tmp() for _ in range(8)) self.emit(f"{pv2} = OpBitcast %v2uint_d {f_plain}") self.emit(f"{plo} = OpCompositeExtract %uint {pv2} 0") self.emit(f"{phi} = OpCompositeExtract %uint {pv2} 1") self.emit(f"{pe_shift} = OpShiftRightLogical %uint {phi} {self.cu(20)}") self.emit(f"{pe_exp} = OpBitwiseAnd %uint {pe_shift} {self.cu(0x7FF)}") self.emit(f"{e_ge} = OpUGreaterThanEqual %bool {pe_exp} {self.cu(76)}") self.emit(f"{e_le} = OpULessThanEqual %bool {pe_exp} {self.cu(128)}") self.emit(f"{in_rng} = OpLogicalAnd %bool {e_ge} {e_le}") sh_raw, sh_c, sh_is_hi, sh_lo, lo_shr, lo_mask, lo_m1, lo_half, lo_and, tie_lo = ( self.tmp() for _ in range(10) ) self.emit(f"{sh_raw} = OpISub %uint {self.cu(129)} {pe_exp}") self.emit(f"{sh_c} = OpSelect %uint {in_rng} {sh_raw} {self.cu(1)}") self.emit(f"{sh_is_hi} = OpUGreaterThan %bool {sh_c} {self.cu(32)}") self.emit(f"{sh_lo} = OpSelect %uint {sh_is_hi} {self.cu(1)} {sh_c}") self.emit(f"{lo_shr} = OpISub %uint {self.cu(32)} {sh_lo}") self.emit(f"{lo_mask} = OpShiftRightLogical %uint {self.cu(0xFFFFFFFF)} {lo_shr}") self.emit(f"{lo_m1} = OpISub %uint {sh_lo} {self.cu(1)}") self.emit(f"{lo_half} = OpShiftLeftLogical %uint {self.cu(1)} {lo_m1}") self.emit(f"{lo_and} = OpBitwiseAnd %uint {plo} {lo_mask}") self.emit(f"{tie_lo} = OpIEqual %bool {lo_and} {lo_half}") sh2_raw, sh2, hi_m, hi_sig, hi_shr, hi_mask, hi_m1, hi_half, hi_and, hi_eq, lo_z, tie_hi, is_tie = ( self.tmp() for _ in range(13) ) self.emit(f"{sh2_raw} = OpISub %uint {sh_c} {self.cu(32)}") self.emit(f"{sh2} = OpSelect %uint {sh_is_hi} {sh2_raw} {self.cu(1)}") self.emit(f"{hi_m} = OpBitwiseAnd %uint {phi} {self.cu(0xFFFFF)}") self.emit(f"{hi_sig} = OpBitwiseOr %uint {hi_m} {self.cu(0x100000)}") self.emit(f"{hi_shr} = OpISub %uint {self.cu(32)} {sh2}") self.emit(f"{hi_mask} = OpShiftRightLogical %uint {self.cu(0xFFFFFFFF)} {hi_shr}") self.emit(f"{hi_m1} = OpISub %uint {sh2} {self.cu(1)}") self.emit(f"{hi_half} = OpShiftLeftLogical %uint {self.cu(1)} {hi_m1}") self.emit(f"{hi_and} = OpBitwiseAnd %uint {hi_sig} {hi_mask}") self.emit(f"{hi_eq} = OpIEqual %bool {hi_and} {hi_half}") self.emit(f"{lo_z} = OpIEqual %bool {plo} {self.cu(0)}") self.emit(f"{tie_hi} = OpLogicalAnd %bool {lo_z} {hi_eq}") self.emit(f"{is_tie} = OpSelect %bool {sh_is_hi} {tie_hi} {tie_lo}") # Exact residual rem = (x*y + z) - f_plain via product error + TwoSum. d0 = self.dconst(0.0) pmul, np, pe_raw, p_z, x_nz, y_nz, xy_nz, p_uf = (self.tmp() for _ in range(8)) self.emit(f"{pmul} = OpFMul %double {x} {y}") self.emit(f"{np} = OpFNegate %double {pmul}") self.emit_fma64(pe_raw, x, y, np) self.emit(f"{p_z} = OpFOrdEqual %bool {pmul} {d0}") self.emit(f"{x_nz} = OpFOrdNotEqual %bool {x} {d0}") self.emit(f"{y_nz} = OpFOrdNotEqual %bool {y} {d0}") self.emit(f"{xy_nz} = OpLogicalAnd %bool {x_nz} {y_nz}") self.emit(f"{p_uf} = OpLogicalAnd %bool {p_z} {xy_nz}") xv2, xhi, yv2, yhi, xysgn, psgn, pe_uf_v2, pe_uf, pe = (self.tmp() for _ in range(9)) self.emit(f"{xv2} = OpBitcast %v2uint_d {x}") self.emit(f"{xhi} = OpCompositeExtract %uint {xv2} 1") self.emit(f"{yv2} = OpBitcast %v2uint_d {y}") self.emit(f"{yhi} = OpCompositeExtract %uint {yv2} 1") self.emit(f"{xysgn} = OpBitwiseXor %uint {xhi} {yhi}") self.emit(f"{psgn} = OpBitwiseAnd %uint {xysgn} {self.cu(0x80000000)}") self.emit(f"{pe_uf_v2} = OpCompositeConstruct %v2uint_d {self.cu(1)} {psgn}") self.emit(f"{pe_uf} = OpBitcast %double {pe_uf_v2}") self.emit(f"{pe} = OpSelect %double {p_uf} {pe_uf} {pe_raw}") ssum, sv, s_sv, p_err, z_err, se, s_df, s_df_se, rem = (self.tmp() for _ in range(9)) self.emit(f"{ssum} = OpFAdd %double {pmul} {z}") self.emit(f"{sv} = OpFSub %double {ssum} {pmul}") self.emit(f"{s_sv} = OpFSub %double {ssum} {sv}") self.emit(f"{p_err} = OpFSub %double {pmul} {s_sv}") self.emit(f"{z_err} = OpFSub %double {z} {sv}") self.emit(f"{se} = OpFAdd %double {p_err} {z_err}") self.emit(f"{s_df} = OpFSub %double {ssum} {f_plain}") self.emit(f"{s_df_se} = OpFAdd %double {s_df} {se}") self.emit(f"{rem} = OpFAdd %double {s_df_se} {pe}") rem_nz, rem_pos, phi_pos, same_sgn, adj1, do_adj = (self.tmp() for _ in range(6)) self.emit(f"{rem_nz} = OpFOrdNotEqual %bool {rem} {d0}") self.emit(f"{rem_pos} = OpFOrdGreaterThan %bool {rem} {d0}") self.emit(f"{phi_pos} = OpFOrdGreaterThan %bool {f_plain} {d0}") self.emit(f"{same_sgn} = OpLogicalEqual %bool {rem_pos} {phi_pos}") self.emit(f"{adj1} = OpLogicalAnd %bool {in_rng} {is_tie}") self.emit(f"{do_adj} = OpLogicalAnd %bool {adj1} {rem_nz}") lo_inc, lo_max, c_inc, hi_inc, lo_dec, c_dec, hi_dec = (self.tmp() for _ in range(7)) self.emit(f"{lo_inc} = OpIAdd %uint {plo} {self.cu(1)}") self.emit(f"{lo_max} = OpIEqual %bool {plo} {self.cu(0xFFFFFFFF)}") self.emit(f"{c_inc} = OpSelect %uint {lo_max} {self.cu(1)} {self.cu(0)}") self.emit(f"{hi_inc} = OpIAdd %uint {phi} {c_inc}") self.emit(f"{lo_dec} = OpISub %uint {plo} {self.cu(1)}") self.emit(f"{c_dec} = OpSelect %uint {lo_z} {self.cu(1)} {self.cu(0)}") self.emit(f"{hi_dec} = OpISub %uint {phi} {c_dec}") n_lo, n_hi, adj_lo, adj_hi, adj_v2, p_adj = (self.tmp() for _ in range(6)) self.emit(f"{n_lo} = OpSelect %uint {same_sgn} {lo_inc} {lo_dec}") self.emit(f"{n_hi} = OpSelect %uint {same_sgn} {hi_inc} {hi_dec}") self.emit(f"{adj_lo} = OpSelect %uint {do_adj} {n_lo} {plo}") self.emit(f"{adj_hi} = OpSelect %uint {do_adj} {n_hi} {phi}") self.emit(f"{adj_v2} = OpCompositeConstruct %v2uint_d {adj_lo} {adj_hi}") self.emit(f"{p_adj} = OpBitcast %double {adj_v2}") f_post, f_dn, sc, r, v2, lo, hi = (self.tmp() for _ in range(7)) self.emit(f"{f_post} = OpFMul %double {p_adj} {self.dconst(2.0 ** -128)}") self.emit(f"{f_dn} = OpSelect %double {big} {f_pre} {f_post}") self.emit(f"{sc} = OpSelect %double {scale_up} {f_up} {f_dn}") self.emit(f"{r} = OpSelect %double {vcc_b} {sc} {f_plain}") r = self.clamp_mods_f64(r, mods) self.emit(f"{v2} = OpBitcast %v2uint_d {r}") self.emit(f"{lo} = OpCompositeExtract %uint {v2} 0") self.emit(f"{hi} = OpCompositeExtract %uint {v2} 1") self.dst({"k": "vgpr", "r": d["r"], "n": 1}, lo) self.dst({"k": "vgpr", "r": d["r"] + 1, "n": 1}, hi) elif op in ("v_mad_f32", "v_mac_f32"): # Unfused: the product is rounded before the add. v_mac_f32 is the VOP2 form with D as the addend # (LLVM SIInstrInfo.cpp getNewFMAInst: V_MAC_F32 -> V_MAD_F32_e64, V_FMAC_F32 -> V_FMA_F32_e64). # Neither supports f32 denormals (flush_f32): operands, the rounded product and the sum flush. if op == "v_mac_f32": x, y, z = self.src_f(a[1]), self.src_f(a[2]), self.src_f(a[0]) else: x, y, z = (self.src_f(t) for t in a[1:4]) x, y, z = self.flush_f32(x), self.flush_f32(y), self.flush_f32(z) m, r = self.tmp(), self.tmp() self.emit(f"{m} = OpFMul %float {x} {y}") self.emit(f"{r} = OpFAdd %float {self.flush_f32(m)} {z}") self.dst(a[0], self.tou(self.flush_f32_mods(r, mods))) elif op in ("v_mul_lo_u32", "v_min_u32", "v_max_u32", "v_min_i32", "v_max_i32"): self._check_int32_valu(op, ins["op"], a, mods, allow_sdwa_dpp=(op != "v_mul_lo_u32")) x, y = self.src_u(a[1]), self.src_u(a[2]) r = self.tmp() if op == "v_mul_lo_u32": self.emit(f"{r} = OpIMul %uint {x} {y}") else: f = {"v_min_u32": "UMin", "v_max_u32": "UMax", "v_min_i32": "SMin", "v_max_i32": "SMax"}[op] self.emit(f"{r} = OpExtInst %uint %glsl {f} {x} {y}") self.dst(a[0], r) elif op in ("v_cvt_f16_u16", "v_cvt_f16_i16", "v_cvt_u16_f16", "v_cvt_i16_f16"): # 16-bit <-> f16 conversions of the low half (op_sel:[src,dst] picks the high half of the source / of the # destination); the other half of the destination is kept, as for the other 16-bit-result ops. f16 -> int # truncates toward zero, saturates to the 16-bit range (an f16 infinity too) and gives 0 for NaN, as the # 32-bit conversions do (docs/design.md, "Float-to-int saturation"); clamp and omod are accepted as no-ops (below). # int -> f16 applies clamp_mods (mul:/div: then [0, 1] clamp) and rounds like every f16 result (f16_out). sel, dhi = self.opsel_bits(mods, 1) if op in ("v_cvt_f16_u16", "v_cvt_f16_i16"): u = self.src_u({**a[1], "neg": False, "abs": False}) f = self.tmp() if op == "v_cvt_f16_u16": m = self.u16_half(u, sel[0]) self.emit(f"{f} = OpConvertUToF %float {m}") else: m = self.i16_half(u, sel[0]) self.emit(f"{f} = OpConvertSToF %float {m}") f = self.clamp_f16(f, mods) self.f16_out(a[0], f, dhi) else: # Measured natively on RDNA2 (gfx1036 across all 4 HW_REG_MODE configs 0x1c0/0x100/0x3c0/0x200): # VOP3 clamp and mul:2/mul:4/div:2 (and SDWA clamp) are hardware no-ops on these integer-destination # conversions, matching v_cvt_norm_{i16,u16}_f16. Keep rejecting unknown modifiers and invalid forms. raw_op = ins["op"] if raw_op.endswith("_sdwa"): bad_mod = any( m != "clamp" and m.split(":", 1)[0] not in ("src0_sel", "dst_sel", "dst_unused") for m in mods ) elif raw_op.endswith("_dpp"): bad_mod = bool(self.non_dpp_mods(raw_op, mods)) elif raw_op.endswith("_e32"): bad_mod = bool(mods) else: bad_mod = any( m not in ("clamp", "mul:2", "mul:4", "div:2") and not m.startswith("op_sel:") for m in mods ) if bad_mod: raise Unsupported(op + " output modifier") x = self.f16_in(a[1], sel[0]) nan, xs, tr, cl, conv, lo = (self.tmp() for _ in range(6)) self.emit(f"{nan} = OpIsNan %bool {x}") self.emit(f"{xs} = OpSelect %float {nan} %f0 {x}") # keep the conversion operand representable self.emit(f"{tr} = OpExtInst %float %glsl Trunc {xs}") lo_b, hi_b = (-32768.0, 32767.0) if op == "v_cvt_i16_f16" else (0.0, 65535.0) self.emit(f"{cl} = OpExtInst %float %glsl FClamp {tr} {self.fconst(lo_b)} {self.fconst(hi_b)}") if op == "v_cvt_i16_f16": ci = self.tmp() self.emit(f"{ci} = OpConvertFToS %int {cl}") self.emit(f"{conv} = OpBitcast %uint {ci}") else: self.emit(f"{conv} = OpConvertFToU %uint {cl}") # BitFieldUExtract, not And & 0xFFFF: the signed form's conv is a Bitcast of an %int # ConvertFToS, and NVIDIA's shader compiler miscompiles that And feeding the # preserve-high-half merge (same workaround as the VOP3 16-bit integer ops). self.emit(f"{lo} = OpBitFieldUExtract %uint {conv} {self.cu(0)} {self.cu(16)}") if not dhi: self.write_lo16(a[0], lo) else: if a[0]["k"] != "vgpr": raise Unsupported("op_sel destination") old, keep, sh16, v = (self.tmp() for _ in range(4)) self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', a[0]['r'])}") self.emit(f"{keep} = OpBitwiseAnd %uint {old} {self.cu(0xFFFF)}") self.emit(f"{sh16} = OpShiftLeftLogical %uint {lo} {self.cu(16)}") self.emit(f"{v} = OpBitwiseOr %uint {keep} {sh16}") self.dst(a[0], v) elif op in ("v_cvt_norm_i16_f16", "v_cvt_norm_u16_f16"): # Normalized f16 -> snorm16/unorm16 (RDNA2 ISA VOP1/VOP3): round_even(clamp(S0, lo, 1.0) * scale), # NaN -> 0, preserving the unwritten 16-bit half of the destination (op_sel:[src,dst] supported). # For |cl| >= 0.25, cl * (scale + 1) is an exact even integer in f32 so round_even(cl * scale) == # cl * (scale + 1) - RoundEven(cl), avoiding the f32 double-rounding ties near +-0.5. # Measured natively on RDNA2 (gfx1036, wave32 & wave64, exhaustive 65,536 f16 sweep): VOP3 # clamp and mul:2/mul:4/div:2 (and SDWA clamp) are hardware no-ops on these integer-destination # normalized conversions. Keep rejecting unknown modifiers and invalid form/modifier combinations. raw_op = ins["op"] if raw_op.endswith("_sdwa"): bad_mod = any( m != "clamp" and m.split(":", 1)[0] not in ("src0_sel", "dst_sel", "dst_unused") for m in mods ) elif raw_op.endswith("_dpp"): bad_mod = bool(self.non_dpp_mods(raw_op, mods)) elif raw_op.endswith("_e32"): bad_mod = bool(mods) else: bad_mod = any( m not in ("clamp", "mul:2", "mul:4", "div:2") and not m.startswith("op_sel:") for m in mods ) if bad_mod: raise Unsupported(op + " output modifier") sel, dhi = self.opsel_bits(mods, 1) snorm = op == "v_cvt_norm_i16_f16" x = self.f16_in(a[1], sel[0]) nan, xs, cl, ax, big, hp, rc, rbig, ps, rsm, rn, conv, lo = (self.tmp() for _ in range(13)) self.emit(f"{nan} = OpIsNan %bool {x}") self.emit(f"{xs} = OpSelect %float {nan} %f0 {x}") lo_b = -1.0 if snorm else 0.0 sc, sc1 = (32767.0, 32768.0) if snorm else (65535.0, 65536.0) self.emit(f"{cl} = OpExtInst %float %glsl FClamp {xs} {self.fconst(lo_b)} {self.fconst(1.0)}") self.emit(f"{ax} = OpExtInst %float %glsl FAbs {cl}") self.emit(f"{big} = OpFOrdGreaterThanEqual %bool {ax} {self.fconst(0.25)}") self.emit(f"{hp} = OpFMul %float {cl} {self.fconst(sc1)}") self.emit(f"{rc} = OpExtInst %float %glsl RoundEven {cl}") self.emit(f"{rbig} = OpFSub %float {hp} {rc}") self.emit(f"{ps} = OpFMul %float {cl} {self.fconst(sc)}") self.emit(f"{rsm} = OpExtInst %float %glsl RoundEven {ps}") self.emit(f"{rn} = OpSelect %float {big} {rbig} {rsm}") if snorm: ci = self.tmp() self.emit(f"{ci} = OpConvertFToS %int {rn}") self.emit(f"{conv} = OpBitcast %uint {ci}") else: self.emit(f"{conv} = OpConvertFToU %uint {rn}") # Same NVIDIA And-&-0xFFFF workaround as v_cvt_i16_f16 above. self.emit(f"{lo} = OpBitFieldUExtract %uint {conv} {self.cu(0)} {self.cu(16)}") if not dhi: self.write_lo16(a[0], lo) else: if a[0]["k"] != "vgpr": raise Unsupported("op_sel destination") old, keep, sh16, v = (self.tmp() for _ in range(4)) self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', a[0]['r'])}") self.emit(f"{keep} = OpBitwiseAnd %uint {old} {self.cu(0xFFFF)}") self.emit(f"{sh16} = OpShiftLeftLogical %uint {lo} {self.cu(16)}") self.emit(f"{v} = OpBitwiseOr %uint {keep} {sh16}") self.dst(a[0], v) elif op in ("v_frexp_mant_f16", "v_frexp_exp_i16_f16", "v_ldexp_f16"): # The binary16 version of v_frexp_mant_f32 / v_frexp_exp_i32_f32 / v_ldexp_f32, bit-exact on the f16 word # of the low half (op_sel picks the high half of a source; the last bit sends the result to the high half; # the other half of the destination is kept). A normal f16 has a biased exponent of 1..30 (bias 15); zero # gives a signed zero (exponent 0) and exponent 31 (infinity, NaN) passes through. f16 denormals are kept, # as in the MODE inferred for the game (denorm_mode_16_64 = 3): a denormal operand is normalized, and # v_ldexp_f16 rounds a result below the normal range to nearest even. Measured natively on gfx1036 over # every f16 input (docs/design.md). Under console MODE (0x1c0: IEEE=0, DX10_CLAMP=1, denorm16_64=3), # VOP3 mul:2/mul:4/div:2 are hardware no-ops on v_frexp_mant_f16 and v_ldexp_f16 while clamp clamps to # [0.0, 1.0] alone and combined with mul:*/div:*; on v_frexp_exp_i16_f16 (integer result), clamp and # mul:2/mul:4/div:2 are all hardware no-ops across every MODE (0x1c0, 0x100, 0x3c0). if op == "v_ldexp_f16": self._validate_f16_valu(ins, op, 2, allow_e32=True, allow_e64=True, int_srcs=(1,)) else: bad = [m for m in mods if m not in ("clamp", "mul:2", "mul:4", "div:2") and not m.startswith("op_sel:")] if bad: raise Unsupported(op + " output modifier") nsrc = 2 if op == "v_ldexp_f16" else 1 sel, dhi = self.opsel_bits(mods, nsrc) u = self.src_h(a[1]) x = self.u16_half(u, sel[0]) if a[1].get("abs"): t = self.tmp() self.emit(f"{t} = OpBitwiseAnd %uint {x} {self.cu(0x7FFF)}") x = t if a[1].get("neg"): t = self.tmp() self.emit(f"{t} = OpBitwiseXor %uint {x} {self.cu(0x8000)}") x = t e, em1, isnorm, isden, sgn, other = (self.tmp() for _ in range(6)) self.emit(f"{e} = OpBitFieldUExtract %uint {x} {self.cu(10)} {self.cu(5)}") self.emit(f"{em1} = OpISub %uint {e} {self.cu(1)}") self.emit(f"{isnorm} = OpULessThan %bool {em1} {self.cu(30)}") # exponent field 1..30 self.emit(f"{isden} = OpIEqual %bool {e} {self.cu(0)}") self.emit(f"{sgn} = OpBitwiseAnd %uint {x} {self.cu(0x8000)}") self.emit(f"{other} = OpSelect %uint {isden} {sgn} {x}") # zero -> +-0, inf/NaN -> S0 # The significand with its leading one at bit 10 (sig11), and the exponent field ef that goes with it: e for # a normal operand, 1 - (10 - msb) for a denormal one (2^-24 * frac), which can wrap below 0. frac, nz, sub, fin, wide, sig, msb, msbu, lsh, lshc, sig11, ef0, ef = (self.tmp() for _ in range(13)) self.emit(f"{frac} = OpBitwiseAnd %uint {x} {self.cu(0x3FF)}") self.emit(f"{nz} = OpINotEqual %bool {frac} {self.cu(0)}") self.emit(f"{sub} = OpLogicalAnd %bool {isden} {nz}") # a denormal operand self.emit(f"{fin} = OpLogicalOr %bool {isnorm} {sub}") # finite and not zero self.emit(f"{wide} = OpBitwiseOr %uint {frac} {self.cu(0x400)}") self.emit(f"{sig} = OpSelect %uint {isnorm} {wide} {frac}") self.emit(f"{msb} = OpExtInst %int %glsl FindUMsb {sig}") self.emit(f"{msbu} = OpBitcast %uint {msb}") self.emit(f"{lsh} = OpISub %uint {self.cu(10)} {msbu}") # 0 for a normal operand self.emit(f"{lshc} = OpExtInst %uint %glsl UMin {lsh} {self.cu(10)}") # zero (msb -1) stays in range self.emit(f"{sig11} = OpShiftLeftLogical %uint {sig} {lshc}") self.emit(f"{ef0} = OpSelect %uint {isnorm} {e} {self.cu(1)}") self.emit(f"{ef} = OpISub %uint {ef0} {lshc}") r = self.tmp() if op == "v_frexp_exp_i16_f16": ex = self.tmp() self.emit(f"{ex} = OpISub %uint {ef} {self.cu(14)}") # biased exponent - 15 + 1 self.emit(f"{r} = OpSelect %uint {fin} {ex} {self.cu(0)}") elif op == "v_frexp_mant_f16": lo10, keep, m = self.tmp(), self.tmp(), self.tmp() self.emit(f"{lo10} = OpBitwiseAnd %uint {sig11} {self.cu(0x3FF)}") self.emit(f"{keep} = OpBitwiseOr %uint {sgn} {lo10}") self.emit(f"{m} = OpBitwiseOr %uint {keep} {self.cu(0x3800)}") # biased exponent 14 self.emit(f"{r} = OpSelect %uint {fin} {m} {other}") else: # D = S0 * 2^S1, S1 a signed 16-bit integer clamped to [-64, 64] and added to the exponent field; # above 30 the result is +-inf; at 0 or below it is a denormal: the significand shifted right by # 1 - field and rounded to nearest even (a carry into bit 10 gives the smallest normal). After a # MODE.FP_ROUND[3:2] toward-zero write (%mode_r16 = 3) it rounds like every other VALU f16 result: # overflow gives +-65504 and a denormal is truncated (not measured on hardware for this op). n = self.src_u(a[2]) n16 = self.i16_half(n, sel[1]) nu, nb, small, neg, lim, nc = (self.tmp() for _ in range(6)) self.emit(f"{nu} = OpBitcast %uint {n16}") self.emit(f"{nb} = OpIAdd %uint {nu} {self.cu(64)}") self.emit(f"{small} = OpULessThan %bool {nb} {self.cu(129)}") # -64 <= n <= 64 self.emit(f"{neg} = OpBitFieldUExtract %uint {nu} {self.cu(31)} {self.cu(1)}") self.emit(f"{lim} = OpSelect %uint {self.tmp_bool_nz(neg)} {self.cu(0xFFFFFFC0)} {self.cu(64)}") self.emit(f"{nc} = OpSelect %uint {small} {nu} {lim}") e2, e2m1, valid, pos, posb, over = (self.tmp() for _ in range(6)) self.emit(f"{e2} = OpIAdd %uint {ef} {nc}") self.emit(f"{e2m1} = OpISub %uint {e2} {self.cu(1)}") self.emit(f"{valid} = OpULessThan %bool {e2m1} {self.cu(30)}") # new exponent field 1..30 self.emit(f"{pos} = OpBitFieldUExtract %uint {e2} {self.cu(31)} {self.cu(1)}") self.emit(f"{posb} = OpIEqual %bool {pos} {self.cu(0)}") self.emit(f"{over} = OpLogicalAnd %bool {posb} {self.tmp_bool_nz(e2)}") # field 31 and above sh, lo10, keep, norm, inf = (self.tmp() for _ in range(5)) self.emit(f"{sh} = OpShiftLeftLogical %uint {e2} {self.cu(10)}") self.emit(f"{lo10} = OpBitwiseAnd %uint {sig11} {self.cu(0x3FF)}") self.emit(f"{keep} = OpBitwiseOr %uint {sgn} {lo10}") self.emit(f"{norm} = OpBitwiseOr %uint {keep} {sh}") is_z = None if self.round_mode: m, is_z, big = self.tmp(), self.tmp(), self.tmp() self.emit(f"{m} = OpLoad %uint %mode_r16") self.emit(f"{is_z} = OpIEqual %bool {m} {self.cu(3)}") self.emit(f"{big} = OpSelect %uint {is_z} {self.cu(0x7BFF)} {self.cu(0x7C00)}") self.emit(f"{inf} = OpBitwiseOr %uint {sgn} {big}") else: self.emit(f"{inf} = OpBitwiseOr %uint {sgn} {self.cu(0x7C00)}") # Field 0 or below: shift right by 1 - field (clamped to 1..12; 12 leaves nothing) and round to even # (toward zero: truncate). rs, rsc, rsu, q, hm, half, mask, rem, gt, eq, odd, oddb, tie, up, inc, qd, den = \ (self.tmp() for _ in range(17)) self.emit(f"{rs} = OpISub %int {self.as_int(self.cu(1))} {self.as_int(e2)}") self.emit(f"{rsc} = OpExtInst %int %glsl SClamp {rs} {self.as_int(self.cu(1))} " f"{self.as_int(self.cu(12))}") self.emit(f"{rsu} = OpBitcast %uint {rsc}") self.emit(f"{q} = OpShiftRightLogical %uint {sig11} {rsu}") self.emit(f"{hm} = OpShiftLeftLogical %uint {self.cu(1)} {rsu}") self.emit(f"{half} = OpShiftRightLogical %uint {hm} {self.cu(1)}") self.emit(f"{mask} = OpISub %uint {hm} {self.cu(1)}") self.emit(f"{rem} = OpBitwiseAnd %uint {sig11} {mask}") self.emit(f"{gt} = OpUGreaterThan %bool {rem} {half}") self.emit(f"{eq} = OpIEqual %bool {rem} {half}") self.emit(f"{odd} = OpBitwiseAnd %uint {q} {self.cu(1)}") self.emit(f"{oddb} = OpINotEqual %bool {odd} {self.cu(0)}") self.emit(f"{tie} = OpLogicalAnd %bool {eq} {oddb}") self.emit(f"{up} = OpLogicalOr %bool {gt} {tie}") if is_z is not None: not_z, upn = self.tmp(), self.tmp() self.emit(f"{not_z} = OpLogicalNot %bool {is_z}") self.emit(f"{upn} = OpLogicalAnd %bool {up} {not_z}") up = upn self.emit(f"{inc} = OpSelect %uint {up} {self.cu(1)} {self.cu(0)}") self.emit(f"{qd} = OpIAdd %uint {q} {inc}") self.emit(f"{den} = OpBitwiseOr %uint {sgn} {qd}") ov, scaled = self.tmp(), self.tmp() self.emit(f"{ov} = OpSelect %uint {over} {inf} {den}") self.emit(f"{scaled} = OpSelect %uint {valid} {norm} {ov}") self.emit(f"{r} = OpSelect %uint {fin} {scaled} {other}") lo = self.tmp() self.emit(f"{lo} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}") if "clamp" in mods and op in ("v_frexp_mant_f16", "v_ldexp_f16"): lo = self.clamp_f16_bits(lo) self.write_half16(a[0], lo, dhi) elif op == "v_cvt_f32_f16": f, h, const_nan = self.f16_in_bits(a[1]) v = self.tou(self.clamp_mods(f, mods)) if const_nan is not False: # Under IEEE=0 the conversion preserves the modified sign and full payload, including the # quiet bit (tools/f32_fuzz.py). Keep these bits out of the driver's float arithmetic. nan_bits = self.cu(0) if "clamp" not in mods: sign, sign32, mant, mant32, base, nan_bits = (self.tmp() for _ in range(6)) self.emit(f"{sign} = OpBitwiseAnd %uint {h} {self.cu(0x8000)}") self.emit(f"{sign32} = OpShiftLeftLogical %uint {sign} {self.cu(16)}") self.emit(f"{mant} = OpBitwiseAnd %uint {h} {self.cu(0x3FF)}") self.emit(f"{mant32} = OpShiftLeftLogical %uint {mant} {self.cu(13)}") self.emit(f"{base} = OpBitwiseOr %uint {sign32} {self.cu(0x7F800000)}") self.emit(f"{nan_bits} = OpBitwiseOr %uint {base} {mant32}") if const_nan: v = nan_bits else: is_nan = self._f16_half_nan(h) out = self.tmp() self.emit(f"{out} = OpSelect %uint {is_nan} {nan_bits} {v}") v = out self.dst(a[0], v) elif op in ("v_interp_p1_f32", "v_interp_p2_f32", "v_interp_mov_f32"): # Single-lane model: the barycentric p1/p2 pair yields the interpolated attribute, and the mov of P0 # the provoking vertex's value. An input only ever read through the mov is declared Flat: such # inputs carry integers (instance and material ids, buffer indices), and interpolating their bits # as floats does not return them intact. No shader in this build reads one location both ways. attr = next((x for x in a if x["k"] == "attr"), None) if attr is None or self.stage != "ps": raise Unsupported(op + " form") vsel = "p0" if op == "v_interp_mov_f32": sel = a[1] if len(a) > 1 else None vsel = sel.get("t") if sel is not None and sel.get("k") == "interp" else "operand" if vsel not in ("p0", "p10", "p20"): raise Unsupported(f"v_interp_mov_f32 vertex select {vsel}") else: self.interp_pair_src(op, a, ins) half16 = self.pixel_interpolants is not None and (self.pixel_interpolants[1] >> attr["a"]) & 1 if vsel != "p0": # P10 = P1 - P0 and P20 = P2 - P0, the deltas the hardware keeps beside P0 for the p1/p2 pair # (RDNA2 ISA, VINTRP: D = {P10, P20, P0}[S]): one f32 subtraction of the PerVertexKHR words. if attr["a"] not in self.per_vertex: raise Unsupported(f"v_interp_mov_f32 vertex select {vsel} without per-vertex inputs") if half16: raise Unsupported(f"v_interp_mov_f32 vertex select {vsel} of a 16-bit interpolant") f = self.attribute(attr["a"], attr["c"], vertex_delta=1 if vsel == "p10" else 2) else: f = self.attribute(attr["a"], attr["c"], flat=op == "v_interp_mov_f32", ij=self.interp_weights(ins)) if half16 and vsel == "p0": # 16-bit interpolant (FSSM table flag bit 4) read through a 32-bit op: the stored value only # has f16 precision, so round to nearest f16 and back. Reads through the *_f16 opcodes already # narrow to f16 and are unchanged. f = self.f16_roundtrip(f) if op in ("v_interp_p2_f32", "v_interp_mov_f32"): # VOP3 output modifiers (mul:2 / mul:4 / div:2, clamp) apply to the interpolated result # (LLVM gfx10_asm_vop3.s). No-op when mods has none. f = self.clamp_mods(f, mods) self.dst(a[0], self.tou(f)) elif op == "s_movk_i32": v = a[1]["v"] & 0xFFFF val = (v - 0x10000 if v & 0x8000 else v) & 0xFFFFFFFF self.dst(a[0], self.cu(val)) if a[0]["k"] == "sgpr" and self.desc_cache_ok(): self.sgpr_imm[a[0]["r"]] = val elif op in ("s_cmov_b32", "s_cmovk_i32"): # D = SCC ? S0 : D (s_cmovk_i32: S0 is the 16-bit immediate, sign-extended). SCC is read, not written. if a[0]["k"] != "sgpr": raise Unsupported(op + " destination") if op == "s_cmovk_i32": v = a[1]["v"] & 0xFFFF x = self.cu((v - 0x10000 if v & 0x8000 else v) & 0xFFFFFFFF) else: x = self.src_u(a[1]) old, c, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{old} = OpCopyObject %uint {self.load_reg('sgpr', a[0]['r'])}") self.emit(f"{c} = OpLoad %uint %scc") self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(c)} {x} {old}") self.dst(a[0], r) elif op == "s_cmov_b64": # RDNA2 ISA SOP1: D = SCC ? S0 : D, SCC read and not written (LLVM AMDGPU SOPInstructions.td: # S_CMOV_B64 : SOP1_64 under Uses = [SCC]). Plain 64-bit data only: a lane-mask pair holds one # lane's bit here, so selecting it as data would silently read a bool instead of the wave's mask # (issue #210). Those operands keep failing loudly. if self.is_mask_op(a[1]) or self.any_mask_word(a[1]) or self.any_ever_mask_word(a[1]): raise Unsupported("s_cmov_b64 lane-mask source") if a[0]["k"] != "sgpr" or a[0].get("n") != 2: raise Unsupported("s_cmov_b64 destination") if self.holds_lane_mask(a[0]) or self.any_mask_word(a[0]) or self.any_ever_mask_word(a[0]): raise Unsupported("s_cmov_b64 lane-mask destination") (xlo, xhi) = self.src64_data(a[1], op) # Read both old dwords before any store, so D overlapping S0 stays exact. oldlo, oldhi = self.load_reg("sgpr", a[0]["r"]), self.load_reg("sgpr", a[0]["r"] + 1) c, rlo, rhi = self.tmp(), self.tmp(), self.tmp() self.emit(f"{c} = OpLoad %uint %scc") b = self.tmp_bool_nz(c) self.emit(f"{rlo} = OpSelect %uint {b} {xlo} {oldlo}") self.emit(f"{rhi} = OpSelect %uint {b} {xhi} {oldhi}") self.dst64_data(a[0], rlo, rhi, op) elif op.startswith("v_cmp_") and not op.startswith("v_cmp_class"): self.compare(op, a, scalar=False, mods=mods) elif op.startswith("v_cmpx_") and not op.startswith("v_cmpx_class"): self.compare_x(op, a, mods=mods) elif op.endswith(("_saveexec_b64", "_saveexec_b32")) and op[2:].split("_saveexec")[0] in self.EXEC_LOGIC: # RDNA2 ISA SOP1: D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0). One invocation holds its own lane's bit # (0 or ~0), so f is the bitwise op on that bit, NOT included: a lane EXEC had off becomes active when f # gives 1 for it (nand, nor, orn2, xnor ...), as on hardware. Definitions as tools/cf_ref.py _SAVEEXEC. # In wave64, the _b32 form operates strictly on EXEC_LO (lanes 0..31): EXEC_HI (lanes 32..63) is unchanged # and SCC reflects EXEC_LO != 0 only. kind = op[2:].split("_saveexec")[0] saved = self.exec_value() half32 = self.wave64 and op.endswith("_b32") if half32 and self.holds_lane_mask(a[1]) and self.mask_half(a[1]) == "hi": _, hi_w = self.wave_mask(a[1]) sh, shr, bit, src = (self.tmp() for _ in range(4)) self.emit(f"{sh} = OpBitwiseAnd %uint {self.wave_lane()} {self.cu(31)}") self.emit(f"{shr} = OpShiftRightLogical %uint {hi_w} {sh}") self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") self.emit(f"{src} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") else: src = self.mask_src(a[1], wide=op.endswith("b64")) r = self.exec_logic(kind, src, saved) if half32: if a[0]["k"] == "special" and a[0].get("t") in ("exec_hi", "vcc_hi"): lo_w, _ = self.wave_mask({"k": "special", "t": "exec"}) sh, shr, bit, mapped = (self.tmp() for _ in range(4)) self.emit(f"{sh} = OpBitwiseAnd %uint {self.wave_lane()} {self.cu(31)}") self.emit(f"{shr} = OpShiftRightLogical %uint {lo_w} {sh}") self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") self.emit(f"{mapped} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") self.put_mask(a[0], mapped, "hi") else: self.put_mask(a[0], saved, "lo") self.exec_half_write(0, r) self.scc_any_half(r, "lo") else: self.mask_dst(a[0], saved) self.set_exec(r) self.scc_from_mask(r) elif op in ("s_andn2_wrexec_b64", "s_andn2_wrexec_b32", "s_andn1_wrexec_b64", "s_andn1_wrexec_b32"): # RDNA ISA: andn2: EXEC = S0 & ~EXEC; andn1: EXEC = ~S0 & EXEC; then D = EXEC; SCC = (EXEC != 0). # In wave64, the _b32 form operates strictly on EXEC_LO (lanes 0..31). kind = op[2:].split("_wrexec")[0] half32 = self.wave64 and op.endswith("_b32") if half32 and self.holds_lane_mask(a[1]) and self.mask_half(a[1]) == "hi": _, hi_w = self.wave_mask(a[1]) sh, shr, bit, x = (self.tmp() for _ in range(4)) self.emit(f"{sh} = OpBitwiseAnd %uint {self.wave_lane()} {self.cu(31)}") self.emit(f"{shr} = OpShiftRightLogical %uint {hi_w} {sh}") self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") self.emit(f"{x} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") else: x = self.mask_src(a[1], wide=op.endswith("b64")) y = self.exec_value() r = self.exec_logic(kind, x, y) if half32: self.exec_half_write(0, r) if a[0]["k"] == "special" and a[0].get("t") in ("exec_hi", "vcc_hi"): lo_w, _ = self.wave_mask({"k": "special", "t": "exec"}) sh, shr, bit, mapped = (self.tmp() for _ in range(4)) self.emit(f"{sh} = OpBitwiseAnd %uint {self.wave_lane()} {self.cu(31)}") self.emit(f"{shr} = OpShiftRightLogical %uint {lo_w} {sh}") self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") self.emit(f"{mapped} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") self.put_mask(a[0], mapped, "hi") else: self.put_mask(a[0], r, "lo") self.scc_any_half(r, "lo") else: self.set_exec(r) self.mask_dst(a[0], r) self.scc_from_mask(r) elif op in ("s_bfe_u64", "s_bfe_i64"): # 64-bit bitfield extract: offset = S1[5:0], width = S1[22:16] (0-127). A width of 0 gives 0; a field # running past bit 63 stops there (LLVM constantFoldBFE: Src0 >> Offset, arithmetic for i64), so the # width is cut to 64 - offset. SCC = (D != 0). The pair is 64-bit data (as for s_lshl_b64); a lane-mask # source stays Unsupported (#210). d, x = a[0], a[1] if d["k"] != "sgpr" or d.get("n") != 2 or self.holds_lane_mask(x): raise Unsupported(op + " operands") if x["k"] == "sgpr" and x.get("n") == 2: lo, hi = self.load_reg("sgpr", x["r"]), self.load_reg("sgpr", x["r"] + 1) elif x["k"] == "imm": v = x["v"] & 0xFFFFFFFFFFFFFFFF lo, hi = self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) else: raise Unsupported(op + " source") ctl = self.src_u(a[2]) off, wid, room, fits, w, l64, h64, t, v64 = (self.tmp() for _ in range(9)) self.emit(f"{off} = OpBitwiseAnd %uint {ctl} {self.cu(63)}") self.emit(f"{wid} = OpBitFieldUExtract %uint {ctl} {self.cu(16)} {self.cu(7)}") self.emit(f"{room} = OpISub %uint {self.cu(64)} {off}") self.emit(f"{fits} = OpULessThan %bool {wid} {room}") self.emit(f"{w} = OpSelect %uint {fits} {wid} {room}") # 0..64, and off + w <= 64 self.emit(f"{l64} = OpUConvert %ulong {lo}") self.emit(f"{h64} = OpUConvert %ulong {hi}") self.emit(f"{t} = OpShiftLeftLogical %ulong {h64} %c64_32") self.emit(f"{v64} = OpBitwiseOr %ulong {t} {l64}") # Shift the field to the top, then back down: both amounts stay in 0..63 whenever w >= 1; w = 0 is # handled by the final select, so its (clamped) shifts never decide the result. wz = self.tmp() self.emit(f"{wz} = OpIEqual %bool {w} {self.cu(0)}") w1, up, down, up64, down64, sh, field = (self.tmp() for _ in range(7)) self.emit(f"{w1} = OpSelect %uint {wz} {self.cu(1)} {w}") ow = self.tmp() self.emit(f"{ow} = OpIAdd %uint {off} {w1}") self.emit(f"{up} = OpISub %uint {self.cu(64)} {ow}") self.emit(f"{down} = OpISub %uint {self.cu(64)} {w1}") self.emit(f"{up64} = OpUConvert %ulong {up}") self.emit(f"{down64} = OpUConvert %ulong {down}") self.emit(f"{sh} = OpShiftLeftLogical %ulong {v64} {up64}") if op == "s_bfe_u64": self.emit(f"{field} = OpShiftRightLogical %ulong {sh} {down64}") else: si_, ri = self.tmp(), self.tmp() self.emit(f"{si_} = OpBitcast %long {sh}") self.emit(f"{ri} = OpShiftRightArithmetic %long {si_} {down64}") self.emit(f"{field} = OpBitcast %ulong {ri}") flo, fh, fhi, rlo, rhi = (self.tmp() for _ in range(5)) self.emit(f"{flo} = OpUConvert %uint {field}") self.emit(f"{fh} = OpShiftRightLogical %ulong {field} %c64_32") self.emit(f"{fhi} = OpUConvert %uint {fh}") self.emit(f"{rlo} = OpSelect %uint {wz} {self.cu(0)} {flo}") self.emit(f"{rhi} = OpSelect %uint {wz} {self.cu(0)} {fhi}") self.store_reg("sgpr", d["r"], rlo) self.store_reg("sgpr", d["r"] + 1, rhi) orr = self.tmp() self.emit(f"{orr} = OpBitwiseOr %uint {rlo} {rhi}") self.scc_nonzero(orr) self.uses_psb = True # Int64 capability and %ulong / %long come with the PSB declarations elif op in ("s_bfe_u32", "s_bfe_i32"): # src1 packs offset in bits [4:0] and width in bits [22:16]. ctl_val = self.imm_val(a[2]) if ctl_val is not None: off_c = ctl_val & 31 wid_raw = (ctl_val >> 16) & 0x7F wid_c = min(wid_raw, 32 - off_c) x_val = self.imm_val(a[1]) if x_val is not None: if wid_c == 0: val = 0 elif op == "s_bfe_u32": val = (x_val >> off_c) & ((1 << wid_c) - 1) else: raw = (x_val >> off_c) & ((1 << wid_c) - 1) sign_bit = 1 << (wid_c - 1) val = ((raw ^ sign_bit) - sign_bit) & 0xFFFFFFFF r = self.cu(val) self.dst(a[0], r) if a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: self.sgpr_imm[a[0]["r"]] = val self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}") return off = self.cu(off_c) wid = self.cu(wid_c) x = self.src_u(a[1]) r = self.tmp() if op == "s_bfe_u32": self.emit(f"{r} = OpBitFieldUExtract %uint {x} {off} {wid}") else: xi, ri = self.as_int(x), self.tmp() self.emit(f"{ri} = OpBitFieldSExtract %int {xi} {off} {wid}") self.emit(f"{r} = OpBitcast %uint {ri}") self.dst(a[0], r) z = self.tmp() self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") self.emit(f"OpStore %scc {z}") return x, ctl = self.src_u(a[1]), self.src_u(a[2]) off, wid, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{off} = OpBitwiseAnd %uint {ctl} {self.cu(31)}") self.emit(f"{wid} = OpBitFieldUExtract %uint {ctl} {self.cu(16)} {self.cu(7)}") wid = self.bfe_width(off, wid) if op == "s_bfe_u32": self.emit(f"{r} = OpBitFieldUExtract %uint {x} {off} {wid}") else: xi, ri = self.as_int(x), self.tmp() self.emit(f"{ri} = OpBitFieldSExtract %int {xi} {off} {wid}") self.emit(f"{r} = OpBitcast %uint {ri}") self.dst(a[0], r) z = self.tmp() self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") self.emit(f"OpStore %scc {z}") elif op == "v_perm_b32": # Byte permute: result byte i = selector byte i picks from the 8 bytes {src0, src1} (src1 is low). # Selector values 0-7 pick a byte; 8-11 repeat the sign bit of a 16-bit half (bit 15, 31, 47 or 63 of # {src0, src1}, RDNA2 ISA reference, V_PERM_B32); 12 -> 0x00, >=13 -> 0xFF. # Both candidate shifts are (k & 3) * 8, so every shift stays below 32 (SPIR-V leaves larger ones # undefined, even on the side of the OpSelect that is discarded). s0, s1 = self.src_u(a[1]), self.src_u(a[2]) selector = self.imm_val(a[3]) if selector is not None: self.dst(a[0], self.permute_known_selector(s0, s1, selector)) return sel = self.src_u(a[3]) out = self.cu(0) for i in range(4): sb, lo_pick, hi_pick, k, b, k3, sh, chosen, inrange, val, shifted, acc = \ (self.tmp() for _ in range(12)) self.emit(f"{sb} = OpBitFieldUExtract %uint {sel} {self.cu(8 * i)} {self.cu(8)}") self.emit(f"{k} = OpBitwiseAnd %uint {sb} {self.cu(7)}") self.emit(f"{b} = OpULessThan %bool {k} {self.cu(4)}") self.emit(f"{k3} = OpBitwiseAnd %uint {k} {self.cu(3)}") self.emit(f"{sh} = OpIMul %uint {k3} {self.cu(8)}") self.emit(f"{lo_pick} = OpShiftRightLogical %uint {s1} {sh}") self.emit(f"{hi_pick} = OpShiftRightLogical %uint {s0} {sh}") self.emit(f"{chosen} = OpSelect %uint {b} {lo_pick} {hi_pick}") self.emit(f"{inrange} = OpULessThan %bool {sb} {self.cu(8)}") # 8-11: k3 = sb & 3 picks the half; its sign bit is bit 15 or 31 of src1 (k3 0, 1) or src0 (2, 3). k2, in_s1, sgn_src, sgn_sh, sgn_bit, sgn, sb_hi, is_sgn, const, ff, big = (self.tmp() for _ in range(11)) self.emit(f"{k2} = OpBitwiseAnd %uint {k3} {self.cu(2)}") self.emit(f"{in_s1} = OpIEqual %bool {k2} {self.cu(0)}") self.emit(f"{sgn_src} = OpSelect %uint {in_s1} {s1} {s0}") self.emit(f"{sgn_sh} = OpBitFieldInsert %uint {self.cu(15)} {k3} {self.cu(4)} {self.cu(1)}") self.emit(f"{sgn_bit} = OpBitFieldUExtract %uint {sgn_src} {sgn_sh} {self.cu(1)}") self.emit(f"{sgn} = OpIMul %uint {sgn_bit} {self.cu(0xFF)}") self.emit(f"{sb_hi} = OpBitwiseAnd %uint {sb} {self.cu(0xFC)}") self.emit(f"{is_sgn} = OpIEqual %bool {sb_hi} {self.cu(8)}") self.emit(f"{big} = OpUGreaterThanEqual %bool {sb} {self.cu(13)}") self.emit(f"{const} = OpSelect %uint {big} {self.cu(0xFF)} {self.cu(0)}") self.emit(f"{ff} = OpSelect %uint {is_sgn} {sgn} {const}") self.emit(f"{val} = OpSelect %uint {inrange} {chosen} {ff}") m8 = self.tmp() self.emit(f"{m8} = OpBitwiseAnd %uint {val} {self.cu(0xFF)}") self.emit(f"{shifted} = OpShiftLeftLogical %uint {m8} {self.cu(8 * i)}") self.emit(f"{acc} = OpBitwiseOr %uint {out} {shifted}") out = acc self.dst(a[0], out) elif op in ("s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64", "s_nand_b64", "s_nor_b64", "s_xnor_b64"): k = {"and": "OpBitwiseAnd", "or": "OpBitwiseOr", "xor": "OpBitwiseXor", "andn2": "OpBitwiseAnd", "orn2": "OpBitwiseOr", "nand": "OpBitwiseAnd", "nor": "OpBitwiseOr", "xnor": "OpBitwiseXor"}[op.split("_")[1]] # s_nand/nor/xnor_b64: D = ~(S0 op S1). A lane's mask value is 0 or ~0, so the NOT is per lane too. inv = op in ("s_nand_b64", "s_nor_b64", "s_xnor_b64") if (a[0]["k"] == "special" and a[0].get("t", "").startswith(("exec", "vcc"))) or \ self.is_mask_op(a[1]) or self.is_mask_op(a[2]): x, y = self.mask_src(a[1]), self.mask_src(a[2]) r = self.tmp() if op.endswith("n2_b64"): n = self.tmp() self.emit(f"{n} = OpNot %uint {y}") y = n self.emit(f"{r} = {k} %uint {x} {y}") if inv: t, r = r, self.tmp() self.emit(f"{r} = OpNot %uint {t}") self.mask_dst(a[0], r) self.scc_from_mask(r) else: if not ((a[0]["k"] == "sgpr" and a[0].get("n") == 2) or (a[0]["k"] == "special" and a[0].get("t") == "null")): raise Unsupported(op + " destination") # Load all source dwords before storing to a[0] so destination aliasing stays exact; # lane_masks.py already clears a[0]'s mask state when either source is non-mask. (xlo, xhi), (ylo, yhi) = self.src64_data(a[1], op), self.src64_data(a[2], op) if op.endswith("n2_b64"): nlo, nhi = self.tmp(), self.tmp() self.emit(f"{nlo} = OpNot %uint {ylo}") self.emit(f"{nhi} = OpNot %uint {yhi}") ylo, yhi = nlo, nhi rlo, rhi = self.tmp(), self.tmp() self.emit(f"{rlo} = {k} %uint {xlo} {ylo}") self.emit(f"{rhi} = {k} %uint {xhi} {yhi}") if inv: (tlo, thi), rlo, rhi = (rlo, rhi), self.tmp(), self.tmp() self.emit(f"{rlo} = OpNot %uint {tlo}") self.emit(f"{rhi} = OpNot %uint {thi}") self.dst64_data(a[0], rlo, rhi, op, allow_null=True) orr = self.tmp() self.emit(f"{orr} = OpBitwiseOr %uint {rlo} {rhi}") self.scc_nonzero(orr) elif op == "s_cselect_b64": if (a[0]["k"] == "special" and a[0].get("t", "").startswith(("exec", "vcc"))) or \ self.is_mask_op(a[1]) or self.is_mask_op(a[2]): x, y = self.mask_src(a[1]), self.mask_src(a[2]) c, b, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{c} = OpLoad %uint %scc") self.emit(f"{b} = OpINotEqual %bool {c} {self.cu(0)}") self.emit(f"{r} = OpSelect %uint {b} {x} {y}") self.mask_dst(a[0], r) else: if a[0]["k"] != "sgpr" or a[0].get("n") != 2: raise Unsupported("s_cselect_b64 destination") # Load all source dwords before storing to a[0] so destination aliasing stays exact; # lane_masks.py already clears a[0]'s mask state when either source is non-mask. (lo1, hi1), (lo2, hi2) = self.src64_data(a[1], op), self.src64_data(a[2], op) c, b, rlo, rhi = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{c} = OpLoad %uint %scc") self.emit(f"{b} = OpINotEqual %bool {c} {self.cu(0)}") self.emit(f"{rlo} = OpSelect %uint {b} {lo1} {lo2}") self.emit(f"{rhi} = OpSelect %uint {b} {hi1} {hi2}") self.dst64_data(a[0], rlo, rhi, op) elif op in ("v_interp_p1ll_f16", "v_interp_p1lv_f16", "v_interp_p2_f16"): attr = next((x for x in a if x["k"] == "attr"), None) if attr is None or self.stage != "ps": raise Unsupported(op + " form") self.interp_pair_src(op, a, ins) # `high` (on both ops of the pair) selects the upper f16 of the packed channel (Mesa ACO # emit-interp_instr passes high_16bits to p1ll and p2). Under --bary-fallback there are no per-vertex # inputs, so the old smooth-f32 read stands and `high` cannot be told apart (docs/design.md). f = self.attribute(attr["a"], attr["c"], half=1 if "high" in mods else 0, ij=self.interp_weights(ins)) if op == "v_interp_p2_f16": # VOP3 clamp applies to the f16 result (ACO: dst(F16); llvm-mc takes clamp but no omod on this op). # Until 2026-11-22 it was dropped. A partial write like the other f16 results: the high half of vdst is # kept (SHADER-430, measured on gfx1036 with tools/hw_oracle: a preset 0xdead high half survived every # case). It used to be zeroed. The narrow is always toward zero: MODE.FP_ROUND decides the rounding # of an f16 VALU result, and every AMD compiler sets that field to toward zero around this pair # (LLVM's SIModeRegister: "f16 interpolation instructions need double precision round to zero"; the # Windows driver's ISA shows s_round_mode 0x000c around v_interp_p1ll_f16 / v_interp_p2_f16 on # gfx1036), so f16_res's MODE read is bypassed. Measured: toward zero explains 65,536 of 65,536 # samples, nearest even 39,607 (SHADER-468). self.write_lo16(a[0], self.f16_bits(self.clamp_f16(f, mods), rtz=True)) else: # p1ll/p1lv produce the f32 intermediate consumed by p2_f16 self.dst(a[0], self.tou(f)) elif op in SOPC_CMP32_OPS: self._validate_sopc(ins, op, a, mods) self.compare(op, a, scalar=True) elif op.startswith("s_cmpk_"): # s_cmpk__ sX, imm16: zero-extended for u32, sign-extended for i32. ty = op.rsplit("_", 1)[1] v = a[1]["v"] & 0xFFFF if ty == "i32" and v & 0x8000: v -= 0x10000 self.compare("s_cmp_" + op[len("s_cmpk_"):], [a[0], {"k": "imm", "v": v}], scalar=True) elif op in SOPC_BITCMP_OPS: self._validate_sopc(ins, op, a, mods, src0_64=op.endswith("_b64")) self.bitcmp(op, a) elif op == "s_mul_hi_u32": x, y = self.src_u(a[1]), self.src_u(a[2]) s, r = self.tmp(), self.tmp() self.emit(f"{s} = OpUMulExtended %umul {x} {y}") self.emit(f"{r} = OpCompositeExtract %uint {s} 1") self.dst(a[0], r) elif op == "s_mul_hi_i32": # High 32 bits of the signed 64-bit product; SCC is not written. x, y = self.as_int(self.src_u(a[1])), self.as_int(self.src_u(a[2])) s, hi, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{s} = OpSMulExtended %smul {x} {y}") self.emit(f"{hi} = OpCompositeExtract %int {s} 1") self.emit(f"{r} = OpBitcast %uint {hi}") self.uses_smul = True self.dst(a[0], r) elif op == "s_absdiff_i32": # RDNA2 ISA: D = S0 - S1 as a 32-bit signed value, negated if negative; SCC = (D != 0). The difference # wraps before the absolute value (0x7FFFFFFF - 0x80000000 = -1 -> 1), and SAbs keeps 0x80000000 as is. x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) if x_val is not None and y_val is not None: diff = (x_val - y_val) & 0xFFFFFFFF diff_i = diff if diff < 0x80000000 else diff - 0x100000000 val = abs(diff_i) & 0xFFFFFFFF r = self.cu(val) self.dst(a[0], r) if a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: self.sgpr_imm[a[0]["r"]] = val self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}") return x, y = self.src_u(a[1]), self.src_u(a[2]) d, ab, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{d} = OpISub %uint {x} {y}") self.emit(f"{ab} = OpExtInst %int %glsl SAbs {self.as_int(d)}") self.emit(f"{r} = OpBitcast %uint {ab}") self.dst(a[0], r) self.scc_nonzero(r) elif op in ("v_fma_mixlo_f16", "v_fma_mixhi_f16"): vals = self.fma_mix_srcs(a, mods) r = self.fma_mix_odd(*vals) r = self.clamp_f16(r, mods) self.f16_out(a[0], r, hi=(op == "v_fma_mixhi_f16")) elif op == "v_cvt_pk_u8_f32": # Convert src0 to u8 (round to nearest even, clamp, NaN gives 0) and insert it at byte src1 of src2. # Measured natively on RDNA2 (cs_cvt_pk_u8.asm). A NaN, found from its bits, is replaced by +0 # before FClamp, which is undefined for a NaN operand. x, byte, base = self.src_f(a[1]), self.src_u(a[2]), self.src_u(a[3]) c, rn, u, sh, mask, nmask, keep, ins_, r = (self.tmp() for _ in range(9)) mag, not_nan, safe = self.tmp(), self.tmp(), self.tmp() self.emit(f"{mag} = OpBitwiseAnd %uint {self.tou(x)} {self.cu(0x7FFFFFFF)}") self.emit(f"{not_nan} = OpULessThan %bool {mag} {self.cu(0x7F800001)}") self.emit(f"{safe} = OpSelect %float {not_nan} {x} %f0") self.emit(f"{c} = OpExtInst %float %glsl FClamp {safe} %f0 {self.fconst(255.0)}") self.emit(f"{rn} = OpExtInst %float %glsl RoundEven {c}") self.emit(f"{u} = OpConvertFToU %uint {rn}") b3 = self.tmp() self.emit(f"{b3} = OpBitwiseAnd %uint {byte} {self.cu(3)}") self.emit(f"{sh} = OpIMul %uint {b3} {self.cu(8)}") self.emit(f"{mask} = OpShiftLeftLogical %uint {self.cu(0xFF)} {sh}") self.emit(f"{nmask} = OpNot %uint {mask}") self.emit(f"{keep} = OpBitwiseAnd %uint {base} {nmask}") self.emit(f"{ins_} = OpShiftLeftLogical %uint {u} {sh}") self.emit(f"{r} = OpBitwiseOr %uint {keep} {ins_}") self.dst(a[0], r) elif op == "v_mul_hi_u32": self._check_int32_valu(op, ins["op"], a, mods) x, y = self.src_u(a[1]), self.src_u(a[2]) s, r = self.tmp(), self.tmp() self.emit(f"{s} = OpUMulExtended %umul {x} {y}") self.emit(f"{r} = OpCompositeExtract %uint {s} 1") self.dst(a[0], r) elif op in ("v_cvt_pk_u16_u32", "v_cvt_pk_i16_i32"): # D = {sat16(S1), sat16(S0)} (RDNA ISA pseudocode: u32_to_u16 / i32_to_i16 saturate): the low half from # S0, the high half from S1; u16 clamps to [0, 0xFFFF], i16 to [-32768, 32767]. The whole dword is # written. clamp is not modelled: rejected rather than guessed. if "clamp" in mods: raise Unsupported(op + " clamp") halves = [] for src in a[1:3]: halves.append(self.saturate_int16(self.src_u(src), signed=(op == "v_cvt_pk_i16_i32"))) sh, r = self.tmp(), self.tmp() self.emit(f"{sh} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}") self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {sh}") self.dst(a[0], r) elif op == "v_sat_pk_u8_i16": # D.b16 = {sat_u8(S0.i16 hi), sat_u8(S0.i16 lo)}: each signed 16-bit lane of S0 saturates to # an unsigned byte and packs into the low 16 bits of D (AMD machine-readable ISA semantics). # On GFX10 the 16-bit result keeps the destination's high half, as v_cvt_f16_f32 (Mesa ACO # instr_is_16bit); under _sdwa the dst_sel/dst_unused rule decides instead. neg/abs on the # integer source, clamp and omod are refused rather than guessed. if a[1].get("neg") or a[1].get("abs"): raise Unsupported(op + " modifiers") if ins["op"].endswith("_sdwa"): bad_mod = any( m.split(":", 1)[0] not in ("src0_sel", "dst_sel", "dst_unused") for m in mods) elif ins["op"].endswith("_dpp"): bad_mod = bool(self.non_dpp_mods(ins["op"], mods)) else: bad_mod = bool(mods) if bad_mod: raise Unsupported(op + " modifiers") x = self.src_u(a[1]) bytes_ = [] for half in range(2): s, b = self.tmp(), self.tmp() self.emit(f"{s} = OpExtInst %int %glsl SClamp {self.i16_half(x, half)} " f"{self.as_int(self.cu(0))} {self.as_int(self.cu(0xFF))}") self.emit(f"{b} = OpBitcast %uint {s}") bytes_.append(b) sh, r = self.tmp(), self.tmp() self.emit(f"{sh} = OpShiftLeftLogical %uint {bytes_[1]} {self.cu(8)}") self.emit(f"{r} = OpBitwiseOr %uint {bytes_[0]} {sh}") self.write_lo16(a[0], r) elif op in ("v_cvt_pknorm_i16_f32", "v_cvt_pknorm_u16_f32"): # D = {norm16(S1), norm16(S0)}: each f32 clamped to [-1, 1] (i16) or [0, 1] (u16), scaled by 32767 or # 65535 and rounded to nearest even. Mesa ACO emits these for NIR pack_snorm_2x16 / pack_unorm_2x16, # which nir_opcodes.py defines as fround_even(fclamp(x) * 32767.0 / 65535.0). NaN gives 0, as # v_cvt_i32_f32 does (measured on gfx1036, SHADER-339). The whole dword is written. # RDNA2 rounds the exact product once (SHADER-363): the f32 OpFMul can land exactly on k + 0.5 when the # exact product is just below or above it, and RoundEven then picks the even neighbour. The product's # error e = Fma(c, s, -p) is exact, and on such a tie its sign decides: floor(p) + 1 above, floor(p) # below, RoundEven when e is 0. Away from a tie both roundings agree, since k + 0.5 is an f32 here. # Measured natively on RDNA2 (gfx1036, wave32 & wave64 across 6 HW_REG_MODE configs): VOP3 # clamp is a hardware no-op on v_cvt_pknorm_{i16,u16}_f32 (each lane is already clamped to # [-1, 1] / [0, 1] and packed to 16-bit integer). Reject other unexpected modifiers. if any(m != "clamp" for m in mods): raise Unsupported(op + " modifiers") snorm = op == "v_cvt_pknorm_i16_f32" halves = [] for src in a[1:3]: f = self.src_f(src) nan, z, c, m, rr, i, h = (self.tmp() for _ in range(7)) self.emit(f"{nan} = OpIsNan %bool {f}") self.emit(f"{z} = OpSelect %float {nan} %f0 {f}") self.emit(f"{c} = OpExtInst %float %glsl FClamp {z} {self.fconst(-1.0) if snorm else '%f0'} %f1") scale = self.fconst(32767.0 if snorm else 65535.0) self.emit(f"{m} = OpFMul %float {c} {scale}") re_, nm, e, fl, fr, tie, epos, eneg, up, pick = (self.tmp() for _ in range(10)) self.emit(f"{re_} = OpExtInst %float %glsl RoundEven {m}") self.emit(f"{nm} = OpFNegate %float {m}") self.emit_fma(e, c, scale, nm) self.emit(f"{fl} = OpExtInst %float %glsl Floor {m}") self.emit(f"{fr} = OpFSub %float {m} {fl}") self.emit(f"{tie} = OpFOrdEqual %bool {fr} {self.fconst(0.5)}") self.emit(f"{epos} = OpFOrdGreaterThan %bool {e} %f0") self.emit(f"{eneg} = OpFOrdLessThan %bool {e} %f0") self.emit(f"{up} = OpFAdd %float {fl} %f1") self.emit(f"{pick} = OpSelect %float {epos} {up} {re_}") adj = self.tmp() self.emit(f"{adj} = OpSelect %float {eneg} {fl} {pick}") self.emit(f"{rr} = OpSelect %float {tie} {adj} {re_}") if snorm: si_ = self.tmp() self.emit(f"{si_} = OpConvertFToS %int {rr}") self.emit(f"{i} = OpBitcast %uint {si_}") else: self.emit(f"{i} = OpConvertFToU %uint {rr}") self.emit(f"{h} = OpBitwiseAnd %uint {i} {self.cu(0xFFFF)}") halves.append(h) sh, r = self.tmp(), self.tmp() self.emit(f"{sh} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}") self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {sh}") self.dst(a[0], r) elif op in ("v_cvt_pknorm_i16_f16", "v_cvt_pknorm_u16_f16"): # RDNA2 ISA (VOP3): D[15:0] = norm16(S0.f16), D[31:16] = norm16(S1.f16). Each f16 (selected by # op_sel[0..1], with neg/abs source modifiers) is clamped to [-1, 1] (i16) or [0, 1] (u16), scaled by # 32767 or 65535 and rounded once to nearest even (NaN -> 0). For |cl| >= 0.25, cl * (scale + 1) is an # exact even integer in f32, so cl * (scale + 1) - RoundEven(cl) gives the exact single-rounded result # without binary32 double-rounding at near-tie f16 inputs. Measured exhaustively on gfx1036 across all # 65,536 f16 values (wave32 & wave64): VOP3 clamp is a hardware no-op, and op_sel[2] = 1 shifts the # 32-bit packed result left by 16 bits (D[31:16] = norm16(S0.f16), D[15:0] = 0, overwriting D). # Reserved VOP3 omod bits [60:59] are rejected by llvm-mc (gfx1036) and ignored by silicon, so # mul:*/div:*, VOP3P modifiers, _dpp/_sdwa, and malformed op_sel lists are refused. opsel_mods = [m for m in mods if m.startswith("op_sel:")] if (ins["op"].endswith(("_dpp", "_sdwa")) or len(opsel_mods) > 1 or any(m != "clamp" and not m.startswith("op_sel:") for m in mods)): raise Unsupported(op + " modifier") if opsel_mods: m_sel = opsel_mods[0] if not (m_sel.startswith("op_sel:[") and m_sel.endswith("]")): raise Unsupported(op + " op_sel") try: raw_bits = [int(x) for x in m_sel[len("op_sel:["):-1].split(",")] except ValueError: raise Unsupported(op + " op_sel") from None if not raw_bits or len(raw_bits) > 3 or any(b not in (0, 1) for b in raw_bits): raise Unsupported(op + " op_sel") sel, dhi = self.opsel_bits(mods, 2) snorm = op == "v_cvt_pknorm_i16_f16" lo_f = self.fconst(-1.0) if snorm else "%f0" scale_f = self.fconst(32767.0 if snorm else 65535.0) pow2_f = self.fconst(32768.0 if snorm else 65536.0) qtr_f = self.fconst(0.25) halves = [] for idx, src in enumerate(a[1:3]): f = self.f16_in(src, sel[idx]) nan, z, cl, ab, big, p2, rc, r_big, m, r_sm, rr, i, h = (self.tmp() for _ in range(13)) self.emit(f"{nan} = OpIsNan %bool {f}") self.emit(f"{z} = OpSelect %float {nan} %f0 {f}") self.emit(f"{cl} = OpExtInst %float %glsl FClamp {z} {lo_f} %f1") self.emit(f"{ab} = OpExtInst %float %glsl FAbs {cl}") self.emit(f"{big} = OpFOrdGreaterThanEqual %bool {ab} {qtr_f}") self.emit(f"{p2} = OpFMul %float {cl} {pow2_f}") self.emit(f"{rc} = OpExtInst %float %glsl RoundEven {cl}") self.emit(f"{r_big} = OpFSub %float {p2} {rc}") self.emit(f"{m} = OpFMul %float {cl} {scale_f}") self.emit(f"{r_sm} = OpExtInst %float %glsl RoundEven {m}") self.emit(f"{rr} = OpSelect %float {big} {r_big} {r_sm}") if snorm: si_ = self.tmp() self.emit(f"{si_} = OpConvertFToS %int {rr}") self.emit(f"{i} = OpBitcast %uint {si_}") else: self.emit(f"{i} = OpConvertFToU %uint {rr}") self.emit(f"{h} = OpBitwiseAnd %uint {i} {self.cu(0xFFFF)}") halves.append(h) sh, r = self.tmp(), self.tmp() self.emit(f"{sh} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}") self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {sh}") if dhi: r_hi = self.tmp() self.emit(f"{r_hi} = OpShiftLeftLogical %uint {r} {self.cu(16)}") r = r_hi self.dst(a[0], r) elif op == "v_cvt_pkrtz_f16_f32": # Packs two f32 as f16 into one dword with round-toward-zero (exact, see f16_rtz). The earlier # round-to-nearest version produced inf where hardware gives 65504 (found by the GPU smoke test). x, y = self.src_f(a[1]), self.src_f(a[2]) lo, hi = self.f16_rtz(x), self.f16_rtz(y) sh, r = self.tmp(), self.tmp() self.emit(f"{sh} = OpShiftLeftLogical %uint {hi} {self.cu(16)}") self.emit(f"{r} = OpBitwiseOr %uint {lo} {sh}") self.dst(a[0], r) elif op == "v_cvt_off_f32_i4": # RDNA ISA: D = CVT_OFF_TABLE[S0[3:0]], i.e. the 4-bit signed value / 16 (-0.5 .. 0.4375), exact in f32. # Output modifiers (mul/div, clamp) apply to the result. x = self.src_u(a[1]) i4, fi, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{i4} = OpBitFieldSExtract %uint {x} {self.cu(0)} {self.cu(4)}") self.emit(f"{fi} = OpConvertSToF %float {self.as_int(i4)}") self.emit(f"{r} = OpFMul %float {fi} {self.fconst(0.0625)}") self.dst(a[0], self.tou(self.clamp_mods(r, mods))) elif op == "v_rcp_iflag_f32": x = self.src_f(a[1]) r = self.tmp() self.emit(f"{r} = OpFDiv %float %f1 {x}") self.dst(a[0], self.tou(self.clamp_mods(r, mods))) elif op in F2: read_source = self.src_f_sign_mods if F2[op] in ("max", "min") else self.src_f x, y = read_source(a[1]), read_source(a[2]) r = self.tmp() if F2[op] in ("max", "min"): r = self.nminmax_f32("NMax" if F2[op] == "max" else "NMin", x, y, y_src=a[2]) else: self.emit(f"{r} = {F2[op]} %float {x} {y}") self.dst(a[0], self.tou(self.clamp_mods(r, mods))) elif op == "v_subrev_f32": x, y = self.src_f(a[1]), self.src_f(a[2]) r = self.tmp() self.emit(f"{r} = OpFSub %float {y} {x}") self.dst(a[0], self.tou(self.clamp_mods(r, mods))) elif op in ("v_fma_f32", "v_fmac_f32", "v_fmaak_f32", "v_fmamk_f32", "v_med3_f32"): if op in ("v_fma_f32", "v_fmaak_f32", "v_fmamk_f32"): # fmaak D = S0 * S1 + K, printed `vdst, src0, vsrc1, K`; fmamk D = S0 * K + S1, printed # `vdst, src0, K, vsrc1`. In print order both are fma(a[1], a[2], a[3]), like v_fma_f32. Until # 2026-11-21 fmamk read a[3] as the factor, so it computed S0 * S1 + K. x, y, z = (self.src_f(t) for t in a[1:4]) elif op == "v_fmac_f32": x, y, z = self.src_f(a[1]), self.src_f(a[2]), self.src_f(a[0]) else: r = self.med3_f([self.src_f_sign_mods(t) for t in a[1:4]], a[1:4]) self.dst(a[0], self.tou(self.clamp_mods(r, mods))) return r = self.tmp() self.emit_fma(r, x, y, z) self.dst(a[0], self.tou(self.clamp_mods(r, mods))) elif op in F1: x = self.src_f(a[1]) r = self.tmp() if F1[op] == "rcp": self.emit(f"{r} = OpFDiv %float %f1 {x}") elif F1[op] in ("Floor", "Ceil", "Fract"): r = self.round_f32_flushed(F1[op], x) else: self.emit(f"{r} = OpExtInst %float %glsl {F1[op]} {x}") if op == "v_exp_f32": r = self.flush_f32(r, force=True) self.dst(a[0], self.tou(self.clamp_mods(r, mods))) elif op in ("v_frexp_mant_f32", "v_frexp_exp_i32_f32", "v_ldexp_f32"): # Bit-exact on the binary32 word (no float arithmetic). A normal input has biased exponent 1..254; # zero and denormals are read as zero (the f32 denormal mode is not modelled, as for the other float ops) # and infinities and NaNs (exponent 255) pass through: frexp_mant and ldexp return S0 unchanged, # frexp_exp returns 0 (RDNA2 ISA, V_FREXP_MANT_F32 / V_FREXP_EXP_I32_F32 / V_LDEXP_F32). # The three ops only move bits, so abs/neg move the sign bit of the raw word: through FAbs/OpFNegate a # NaN source came back as the driver's default NaN (0x7fffffff on an RTX 4070 Ti, NVIDIA 620.70.06). x = self.src_u_sign_mods(a[1]) e, em1, isnorm, isden, sgn, r = (self.tmp() for _ in range(6)) self.emit(f"{e} = OpBitFieldUExtract %uint {x} {self.cu(23)} {self.cu(8)}") self.emit(f"{em1} = OpISub %uint {e} {self.cu(1)}") self.emit(f"{isnorm} = OpULessThan %bool {em1} {self.cu(254)}") # exponent field 1..254 self.emit(f"{isden} = OpIEqual %bool {e} {self.cu(0)}") self.emit(f"{sgn} = OpBitwiseAnd %uint {x} {self.cu(0x80000000)}") other = self.tmp() self.emit(f"{other} = OpSelect %uint {isden} {sgn} {x}") # zero/denormal -> +-0, inf/NaN -> S0 if op == "v_frexp_exp_i32_f32": # x = mant * 2^exp with mant in [0.5, 1): exp = biased exponent - 126. ex = self.tmp() self.emit(f"{ex} = OpISub %uint {e} {self.cu(126)}") self.emit(f"{r} = OpSelect %uint {isnorm} {ex} {self.cu(0)}") self.dst(a[0], r) elif op == "v_frexp_mant_f32": keep, m = self.tmp(), self.tmp() self.emit(f"{keep} = OpBitwiseAnd %uint {x} {self.cu(0x807FFFFF)}") self.emit(f"{m} = OpBitwiseOr %uint {keep} {self.cu(0x3F000000)}") # biased exponent 126 self.emit(f"{r} = OpSelect %uint {isnorm} {m} {other}") self.dst(a[0], self.tou(self.clamp_mods(self.tof(r), mods))) else: # D = S0 * 2^S1 with S1 a signed integer. The exponent is added in 32 bits after clamping S1 to # [-512, 512] (enough to overflow or underflow any binary32), then the result saturates: above # 254 it is +-inf, at 0 or below it is +-0 (no denormal results). n = self.src_u(a[2]) nb, small, neg, lim, nc, e2, e2m1, valid, pos, over = (self.tmp() for _ in range(10)) self.emit(f"{nb} = OpIAdd %uint {n} {self.cu(512)}") self.emit(f"{small} = OpULessThan %bool {nb} {self.cu(1025)}") # -512 <= n <= 512 self.emit(f"{neg} = OpBitFieldUExtract %uint {n} {self.cu(31)} {self.cu(1)}") negb = self.tmp_bool_nz(neg) self.emit(f"{lim} = OpSelect %uint {negb} {self.cu(0xFFFFFE00)} {self.cu(512)}") self.emit(f"{nc} = OpSelect %uint {small} {n} {lim}") self.emit(f"{e2} = OpIAdd %uint {e} {nc}") self.emit(f"{e2m1} = OpISub %uint {e2} {self.cu(1)}") self.emit(f"{valid} = OpULessThan %bool {e2m1} {self.cu(254)}") # new exponent field 1..254 self.emit(f"{pos} = OpBitFieldUExtract %uint {e2} {self.cu(31)} {self.cu(1)}") posb = self.tmp() self.emit(f"{posb} = OpIEqual %bool {pos} {self.cu(0)}") self.emit(f"{over} = OpLogicalAnd %bool {posb} {self.tmp_bool_nz(e2)}") sh, keep, norm, inf, ov = (self.tmp() for _ in range(5)) self.emit(f"{sh} = OpShiftLeftLogical %uint {e2} {self.cu(23)}") self.emit(f"{keep} = OpBitwiseAnd %uint {x} {self.cu(0x807FFFFF)}") self.emit(f"{norm} = OpBitwiseOr %uint {keep} {sh}") self.emit(f"{inf} = OpBitwiseOr %uint {sgn} {self.cu(0x7F800000)}") self.emit(f"{ov} = OpSelect %uint {over} {inf} {sgn}") scaled = self.tmp() self.emit(f"{scaled} = OpSelect %uint {valid} {norm} {ov}") self.emit(f"{r} = OpSelect %uint {isnorm} {scaled} {other}") self.dst(a[0], self.tou(self.clamp_mods(self.tof(r), mods))) elif op in ("v_frexp_mant_f64", "v_frexp_exp_i32_f64"): # Binary64 frexp, bit-exact on the (lo, hi) dword pair without requiring Float64/Int64 unless VOP3 output # modifiers are present. Measured natively on gfx1036 (wave32 & wave64, default denorm16_64=3, IEEE=0): # - Normal inputs (biased exponent 1..2046): mant in [0.5, 1) with sign, exp = e - 1022. # - Non-zero subnormals (e == 0, frac != 0): normalized to mant in [0.5, 1) with sign, exp = msb - 1073 # (-1073..-1022), matching v_frexp_mant_f16 / v_frexp_exp_i16_f16. # - Signed zero: +-0 / exp 0. Infinities and NaNs: unchanged / exp 0. sv = a[1] lo, hi = self.f64_source_words(sv, op) if sv.get("abs"): t = self.tmp() self.emit(f"{t} = OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}") hi = t if sv.get("neg"): t = self.tmp() self.emit(f"{t} = OpBitwiseXor %uint {hi} {self.cu(0x80000000)}") hi = t e, em1, isnorm, is_e0, sgn = (self.tmp() for _ in range(5)) self.emit(f"{e} = OpBitFieldUExtract %uint {hi} {self.cu(20)} {self.cu(11)}") self.emit(f"{em1} = OpISub %uint {e} {self.cu(1)}") self.emit(f"{isnorm} = OpULessThan %bool {em1} {self.cu(2046)}") # exponent field 1..2046 self.emit(f"{is_e0} = OpIEqual %bool {e} {self.cu(0)}") self.emit(f"{sgn} = OpBitwiseAnd %uint {hi} {self.cu(0x80000000)}") f_hi, frac_or, nz_frac, is_sub, has_hi = (self.tmp() for _ in range(5)) self.emit(f"{f_hi} = OpBitwiseAnd %uint {hi} {self.cu(0x000FFFFF)}") self.emit(f"{frac_or} = OpBitwiseOr %uint {f_hi} {lo}") self.emit(f"{nz_frac} = OpINotEqual %bool {frac_or} {self.cu(0)}") self.emit(f"{is_sub} = OpLogicalAnd %bool {is_e0} {nz_frac}") # non-zero subnormal self.emit(f"{has_hi} = OpINotEqual %bool {f_hi} {self.cu(0)}") mh, ml, mhu, mlu = (self.tmp() for _ in range(4)) self.emit(f"{mh} = OpExtInst %int %glsl FindUMsb {f_hi}") self.emit(f"{ml} = OpExtInst %int %glsl FindUMsb {lo}") self.emit(f"{mhu} = OpBitcast %uint {mh}") self.emit(f"{mlu} = OpBitcast %uint {ml}") if op == "v_frexp_exp_i32_f64": if any(m in ("clamp", "mul:2", "mul:4", "div:2") for m in mods): raise Unsupported(op + " output modifier") ex_norm, ex_hi, ex_lo, ex_sub, r0, r = (self.tmp() for _ in range(6)) self.emit(f"{ex_norm} = OpISub %uint {e} {self.cu(1022)}") self.emit(f"{ex_hi} = OpISub %uint {mhu} {self.cu(1041)}") # (32 + mhu) - 1073 self.emit(f"{ex_lo} = OpISub %uint {mlu} {self.cu(1073)}") self.emit(f"{ex_sub} = OpSelect %uint {has_hi} {ex_hi} {ex_lo}") self.emit(f"{r0} = OpSelect %uint {is_sub} {ex_sub} {self.cu(0)}") self.emit(f"{r} = OpSelect %uint {isnorm} {ex_norm} {r0}") self.dst(a[0], r) else: d = a[0] if d["k"] != "vgpr" or d.get("n") != 2: raise Unsupported(op + " destination") keep, m_hi = self.tmp(), self.tmp() self.emit(f"{keep} = OpBitwiseAnd %uint {hi} {self.cu(0x800FFFFF)}") self.emit(f"{m_hi} = OpBitwiseOr %uint {keep} {self.cu(0x3FE00000)}") # biased exponent 1022 # Normalize 52-bit subnormal (f_hi, lo) by shifting left (52 - msb) so the leading 1 lands at bit 52. # Mask every shift count with 31 so unselected paths stay strictly in 0..31 (no SPIR-V shift UB). # Case A (f_hi != 0): msb = 32 + mhu (mhu in 0..19), sh = 20 - mhu (1..20), inv = 12 + mhu (12..31). sha0, sha, inva0, inva, a_lo, a_h1, a_h2, a_hi = (self.tmp() for _ in range(8)) self.emit(f"{sha0} = OpISub %uint {self.cu(20)} {mhu}") self.emit(f"{sha} = OpBitwiseAnd %uint {sha0} {self.cu(31)}") self.emit(f"{inva0} = OpIAdd %uint {mhu} {self.cu(12)}") self.emit(f"{inva} = OpBitwiseAnd %uint {inva0} {self.cu(31)}") self.emit(f"{a_lo} = OpShiftLeftLogical %uint {lo} {sha}") self.emit(f"{a_h1} = OpShiftLeftLogical %uint {f_hi} {sha}") self.emit(f"{a_h2} = OpShiftRightLogical %uint {lo} {inva}") self.emit(f"{a_hi} = OpBitwiseOr %uint {a_h1} {a_h2}") # Case B (f_hi == 0): msb = mlu (0..31). # B1 (mlu <= 20): sh >= 32 -> lo = 0, hi_frac = lo << (20 - mlu). # B2 (mlu >= 21): sh = 52 - mlu (21..31), inv = mlu - 20 (1..11) -> lo = lo << sh, hi_frac = lo >> inv. is_b1, shb1_0, shb1, b1_hi = (self.tmp() for _ in range(4)) self.emit(f"{is_b1} = OpULessThanEqual %bool {mlu} {self.cu(20)}") self.emit(f"{shb1_0} = OpISub %uint {self.cu(20)} {mlu}") self.emit(f"{shb1} = OpBitwiseAnd %uint {shb1_0} {self.cu(31)}") self.emit(f"{b1_hi} = OpShiftLeftLogical %uint {lo} {shb1}") shb2_0, shb2, invb2_0, invb2, b2_lo, b2_hi = (self.tmp() for _ in range(6)) self.emit(f"{shb2_0} = OpISub %uint {self.cu(52)} {mlu}") self.emit(f"{shb2} = OpBitwiseAnd %uint {shb2_0} {self.cu(31)}") self.emit(f"{invb2_0} = OpISub %uint {mlu} {self.cu(20)}") self.emit(f"{invb2} = OpBitwiseAnd %uint {invb2_0} {self.cu(31)}") self.emit(f"{b2_lo} = OpShiftLeftLogical %uint {lo} {shb2}") self.emit(f"{b2_hi} = OpShiftRightLogical %uint {lo} {invb2}") b_lo, b_hi, sub_lo, sub_hi_raw, sub_hi_frac, sub_hi_exp, sub_hi = (self.tmp() for _ in range(7)) self.emit(f"{b_lo} = OpSelect %uint {is_b1} {self.cu(0)} {b2_lo}") self.emit(f"{b_hi} = OpSelect %uint {is_b1} {b1_hi} {b2_hi}") self.emit(f"{sub_lo} = OpSelect %uint {has_hi} {a_lo} {b_lo}") self.emit(f"{sub_hi_raw} = OpSelect %uint {has_hi} {a_hi} {b_hi}") self.emit(f"{sub_hi_frac} = OpBitwiseAnd %uint {sub_hi_raw} {self.cu(0x000FFFFF)}") self.emit(f"{sub_hi_exp} = OpBitwiseOr %uint {sub_hi_frac} {self.cu(0x3FE00000)}") self.emit(f"{sub_hi} = OpBitwiseOr %uint {sub_hi_exp} {sgn}") # Signed zeros (+0/-0) and inf/NaN already pass through (lo, hi) unchanged. other_hi, other_lo, r_hi, r_lo = (self.tmp() for _ in range(4)) self.emit(f"{other_hi} = OpSelect %uint {is_sub} {sub_hi} {hi}") self.emit(f"{other_lo} = OpSelect %uint {is_sub} {sub_lo} {lo}") self.emit(f"{r_hi} = OpSelect %uint {isnorm} {m_hi} {other_hi}") self.emit(f"{r_lo} = OpSelect %uint {isnorm} {lo} {other_lo}") # SHADER-721 follow-up, measured with tools/hw_oracle on gfx1036 (wave32 and wave64 identical, # tools/f64_omod_probe.py): a binary64 result ignores mul:2/mul:4/div:2 while denorm_mode_16_64 = 3, # which is the game's MODE. clamp applies in every MODE, so only it needs Float64 here. if "clamp" in mods: self.uses_f64 = True v2, dv, mv2 = self.tmp(), self.tmp(), self.tmp() self.emit(f"{v2} = OpCompositeConstruct %v2uint_d {r_lo} {r_hi}") self.emit(f"{dv} = OpBitcast %double {v2}") dv = self.clamp_mods_f64(dv, [m for m in mods if m == "clamp"]) self.emit(f"{mv2} = OpBitcast %v2uint_d {dv}") r_lo, r_hi = self.tmp(), self.tmp() self.emit(f"{r_lo} = OpCompositeExtract %uint {mv2} 0") self.emit(f"{r_hi} = OpCompositeExtract %uint {mv2} 1") self.dst({"k": "vgpr", "r": d["r"], "n": 1}, r_lo) self.dst({"k": "vgpr", "r": d["r"] + 1, "n": 1}, r_hi) elif op == "v_div_fixup_f32": # IEEE-754 single-precision division fixup: D = div_fixup_f32(S0=quotient, S1=denom, S2=numer). # Measured natively on RDNA2 (gfx1036, wave32 & wave64, 256 triples across 4 MODEs + modifier matrix) # under the game's inferred MODE (IEEE=0, denorm32=0, DX10_CLAMP=1): # - VOP3 abs (clear bit 31) then neg (flip bit 31) apply bitwise to S0/S1/S2 before classification # (including on NaN payloads). # - S1 and S2 subnormals flush to signed zero (exp == 0); S0 subnormals are preserved. # - Priority order (highest first): # 1. NaN(S2) -> S2 (unchanged under IEEE=0) # 2. NaN(S1) -> S1 (unchanged under IEEE=0) # 3. (zero(S1) && zero(S2)) || (inf(S1) && inf(S2)) -> 0xFFC00000 (-qNaN) # 4. zero(S2) || inf(S1) -> sign_out (+-0.0) # 5. zero(S1) || inf(S2) -> sign_out | 0x7F800000 (+-inf) # 6. exp(S2) - exp(S1) <= -151 -> sign_out (+-0.0; pure biased-exponent diff, beats NaN(S0)) # 7. NaN(S0) -> sign_out | 0x7F800000 (+-inf) # 8. otherwise -> copysign(S0, sign_out) # - Output modifiers: mul:2/mul:4/div:2 then clamp (DX10_CLAMP=1 maps NaN to +0.0 before [0, 1]). self._validate_div_valu( ins, op, mods, dst_width=1, src_width=1, allow_opsel=False, strict_omod=True, allow_null_dst=True, ) def _raw_f32_bits(arg): u_val = self.src_u({k: v for k, v in arg.items() if k not in ("abs", "neg")}) if arg.get("abs"): t = self.tmp() self.emit(f"{t} = OpBitwiseAnd %uint {u_val} {self.cu(0x7FFFFFFF)}") u_val = t if arg.get("neg"): t = self.tmp() self.emit(f"{t} = OpBitwiseXor %uint {u_val} {self.cu(0x80000000)}") u_val = t return u_val def _emit(expr): t = self.tmp() self.emit(f"{t} = {expr}") return t s0, s1, s2 = (_raw_f32_bits(arg) for arg in a[1:4]) sign_xor = _emit(f"OpBitwiseXor %uint {s1} {s2}") sign_out = _emit(f"OpBitwiseAnd %uint {sign_xor} {self.cu(0x80000000)}") abs0 = _emit(f"OpBitwiseAnd %uint {s0} {self.cu(0x7FFFFFFF)}") abs1 = _emit(f"OpBitwiseAnd %uint {s1} {self.cu(0x7FFFFFFF)}") abs2 = _emit(f"OpBitwiseAnd %uint {s2} {self.cu(0x7FFFFFFF)}") c_inf = self.cu(0x7F800000) c_min_norm = self.cu(0x00800000) nan0 = _emit(f"OpUGreaterThan %bool {abs0} {c_inf}") nan1 = _emit(f"OpUGreaterThan %bool {abs1} {c_inf}") nan2 = _emit(f"OpUGreaterThan %bool {abs2} {c_inf}") inf1 = _emit(f"OpIEqual %bool {abs1} {c_inf}") inf2 = _emit(f"OpIEqual %bool {abs2} {c_inf}") zero1 = _emit(f"OpULessThan %bool {abs1} {c_min_norm}") zero2 = _emit(f"OpULessThan %bool {abs2} {c_min_norm}") e1 = _emit(f"OpShiftRightLogical %uint {abs1} {self.cu(23)}") e2 = _emit(f"OpShiftRightLogical %uint {abs2} {self.cu(23)}") e1_ge_e2 = _emit(f"OpUGreaterThanEqual %bool {e1} {e2}") ediff = _emit(f"OpISub %uint {e1} {e2}") ediff_ge_151 = _emit(f"OpUGreaterThanEqual %bool {ediff} {self.cu(151)}") exp_uf = _emit(f"OpLogicalAnd %bool {e1_ge_e2} {ediff_ge_151}") signed_inf = _emit(f"OpBitwiseOr %uint {sign_out} {c_inf}") signed_s0 = _emit(f"OpBitwiseOr %uint {sign_out} {abs0}") both_zero = _emit(f"OpLogicalAnd %bool {zero1} {zero2}") both_inf = _emit(f"OpLogicalAnd %bool {inf1} {inf2}") indet = _emit(f"OpLogicalOr %bool {both_zero} {both_inf}") to_zero = _emit(f"OpLogicalOr %bool {zero2} {inf1}") to_inf = _emit(f"OpLogicalOr %bool {zero1} {inf2}") r = _emit(f"OpSelect %uint {nan0} {signed_inf} {signed_s0}") r = _emit(f"OpSelect %uint {exp_uf} {sign_out} {r}") r = _emit(f"OpSelect %uint {to_inf} {signed_inf} {r}") r = _emit(f"OpSelect %uint {to_zero} {sign_out} {r}") r = _emit(f"OpSelect %uint {indet} {self.cu(0xFFC00000)} {r}") r = _emit(f"OpSelect %uint {nan1} {s1} {r}") r = _emit(f"OpSelect %uint {nan2} {s2} {r}") has_omod = any(m in ("mul:2", "mul:4", "div:2") for m in mods) has_clamp = "clamp" in mods if has_omod or has_clamp: f = self.tof(r) for m in mods: if m in ("mul:2", "mul:4", "div:2"): f = _emit(f"OpFMul %float {f} {self.fconst({'mul:2': 2.0, 'mul:4': 4.0, 'div:2': 0.5}[m])}") if has_clamp: is_nan = _emit(f"OpIsNan %bool {f}") safe = _emit(f"OpSelect %float {is_nan} %f0 {f}") f = _emit(f"OpExtInst %float %glsl FClamp {safe} %f0 %f1") r = self.tou(f) self.dst(a[0], r) elif op == "v_ldexp_f64": # Binary64 load-exponent: D.f64 = S0.f64 * 2^(S1.i32), lowered bit-exactly on the (lo, hi) dword pair # using only 32-bit integer ops (no OpCapability Float64 or Int64 required, even with clamp). # Measured natively on gfx1036 (wave32 & wave64, game MODE: ieee=0, dx10_clamp=1, denorm16_64=3): # - +-0, +-inf, and NaNs (both qNaN and sNaN under ieee=0) pass through unchanged (after S0 abs/neg). # - Subnormal inputs are normalized before scaling; subnormal outputs shift right by 1 - e2 (1..53) # and round to nearest even (with carry into bit 52 giving +-min_norm; sh >= 54 flushes to +-0). # - VOP3 clamp applies in both denorm16_64=3 and 0 (dx10_clamp=1: NaN/-0/<0 -> +0.0, >1.0 -> 1.0). # - VOP3 omod (mul:2/mul:4/div:2) is ignored by hardware when denorm16_64=3 and active when 0, so it is # rejected as MODE-dependent rather than guessed. if any(m.startswith(("mul:", "div:")) for m in mods): raise Unsupported(op + " output modifier") d = a[0] if d["k"] != "vgpr" or d.get("n") != 2: raise Unsupported(op + " destination") sv = a[1] if sv["k"] in ("vgpr", "sgpr") and sv.get("n") == 2: lo, hi = self.load_reg(sv["k"], sv["r"]), self.load_reg(sv["k"], sv["r"] + 1) elif sv.get("f64_literal") and self.f64_literal_one_dword(sv): lo, hi = self.cu(0), self.cu(sv["v"] & 0xFFFFFFFF) elif sv["k"] == "fimm": bits = struct.unpack("> 32) elif sv["k"] == "imm": v = sv["v"] if -16 <= v <= 64 or not self.f64_literal_one_dword(sv): bits = v & 0xFFFFFFFFFFFFFFFF lo, hi = self.cu(bits & 0xFFFFFFFF), self.cu(bits >> 32) else: # RDNA2 places a 32-bit literal constant in bits [63:32] of an f64 operand (measured on gfx1036). lo, hi = self.cu(0), self.cu(v & 0xFFFFFFFF) else: raise Unsupported(op + " operand") n = self.src_u(a[2]) if sv.get("abs"): t = self.tmp() self.emit(f"{t} = OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}") hi = t if sv.get("neg"): t = self.tmp() self.emit(f"{t} = OpBitwiseXor %uint {hi} {self.cu(0x80000000)}") hi = t e, em1, isnorm, isden, sgn, m_hi, m_or, m_nz, sub, fin = (self.tmp() for _ in range(10)) self.emit(f"{e} = OpBitFieldUExtract %uint {hi} {self.cu(20)} {self.cu(11)}") self.emit(f"{em1} = OpISub %uint {e} {self.cu(1)}") self.emit(f"{isnorm} = OpULessThan %bool {em1} {self.cu(2046)}") # exponent field 1..2046 self.emit(f"{isden} = OpIEqual %bool {e} {self.cu(0)}") self.emit(f"{sgn} = OpBitwiseAnd %uint {hi} {self.cu(0x80000000)}") self.emit(f"{m_hi} = OpBitwiseAnd %uint {hi} {self.cu(0x000FFFFF)}") self.emit(f"{m_or} = OpBitwiseOr %uint {m_hi} {lo}") self.emit(f"{m_nz} = OpINotEqual %bool {m_or} {self.cu(0)}") self.emit(f"{sub} = OpLogicalAnd %bool {isden} {m_nz}") self.emit(f"{fin} = OpLogicalOr %bool {isnorm} {sub}") # Normalize finite non-zero input into 53-bit significand (sig_hi[20] = 1, sig_lo) and exponent field ef. norm_hi, m_hi_nz, msb_hi_i, msb_hi, lsh_a_raw, lsh_a, rsh_a, a_hi1, a_hi2, a_hi, a_lo = \ (self.tmp() for _ in range(11)) self.emit(f"{norm_hi} = OpBitwiseOr %uint {m_hi} {self.cu(0x00100000)}") self.emit(f"{m_hi_nz} = OpINotEqual %bool {m_hi} {self.cu(0)}") self.emit(f"{msb_hi_i} = OpExtInst %int %glsl FindUMsb {m_hi}") self.emit(f"{msb_hi} = OpBitcast %uint {msb_hi_i}") self.emit(f"{lsh_a_raw} = OpISub %uint {self.cu(20)} {msb_hi}") self.emit(f"{lsh_a} = OpExtInst %uint %glsl UMin {lsh_a_raw} {self.cu(20)}") # 1..20 when m_hi != 0 self.emit(f"{rsh_a} = OpISub %uint {self.cu(32)} {lsh_a}") # 12..31 self.emit(f"{a_hi1} = OpShiftLeftLogical %uint {m_hi} {lsh_a}") self.emit(f"{a_hi2} = OpShiftRightLogical %uint {lo} {rsh_a}") self.emit(f"{a_hi} = OpBitwiseOr %uint {a_hi1} {a_hi2}") self.emit(f"{a_lo} = OpShiftLeftLogical %uint {lo} {lsh_a}") msb_lo_i, msb_lo, msb_lo_c, lsh_b, b_lt32, lsh_b1, rsh_b1, b1_hi, b1_lo, lsh_b2_raw, lsh_b2, b2_hi, b_hi, b_lo = \ (self.tmp() for _ in range(14)) self.emit(f"{msb_lo_i} = OpExtInst %int %glsl FindUMsb {lo}") self.emit(f"{msb_lo} = OpBitcast %uint {msb_lo_i}") self.emit(f"{msb_lo_c} = OpExtInst %uint %glsl UMin {msb_lo} {self.cu(31)}") self.emit(f"{lsh_b} = OpISub %uint {self.cu(52)} {msb_lo_c}") # 21..52 self.emit(f"{b_lt32} = OpULessThan %bool {lsh_b} {self.cu(32)}") self.emit(f"{lsh_b1} = OpExtInst %uint %glsl UMin {lsh_b} {self.cu(31)}") self.emit(f"{rsh_b1} = OpISub %uint {self.cu(32)} {lsh_b1}") self.emit(f"{b1_hi} = OpShiftRightLogical %uint {lo} {rsh_b1}") self.emit(f"{b1_lo} = OpShiftLeftLogical %uint {lo} {lsh_b1}") self.emit(f"{lsh_b2_raw} = OpISub %uint {lsh_b} {self.cu(32)}") self.emit(f"{lsh_b2} = OpExtInst %uint %glsl UMin {lsh_b2_raw} {self.cu(20)}") self.emit(f"{b2_hi} = OpShiftLeftLogical %uint {lo} {lsh_b2}") self.emit(f"{b_hi} = OpSelect %uint {b_lt32} {b1_hi} {b2_hi}") self.emit(f"{b_lo} = OpSelect %uint {b_lt32} {b1_lo} {self.cu(0)}") sub_hi, sub_lo, sub_lsh, sub_ef, sig_hi, sig_lo, ef = (self.tmp() for _ in range(7)) self.emit(f"{sub_hi} = OpSelect %uint {m_hi_nz} {a_hi} {b_hi}") self.emit(f"{sub_lo} = OpSelect %uint {m_hi_nz} {a_lo} {b_lo}") self.emit(f"{sub_lsh} = OpSelect %uint {m_hi_nz} {lsh_a} {lsh_b}") self.emit(f"{sub_ef} = OpISub %uint {self.cu(1)} {sub_lsh}") self.emit(f"{sig_hi} = OpSelect %uint {isnorm} {norm_hi} {sub_hi}") self.emit(f"{sig_lo} = OpSelect %uint {isnorm} {lo} {sub_lo}") self.emit(f"{ef} = OpSelect %uint {isnorm} {e} {sub_ef}") # Clamp S1 to [-4096, 4096] (enough to overflow or underflow any binary64) and add to ef. nc_i, e2_i, e2, e2m1, valid, over = (self.tmp() for _ in range(6)) self.emit(f"{nc_i} = OpExtInst %int %glsl SClamp {self.as_int(n)} " f"{self.as_int(self.cu(0xFFFFF000))} {self.as_int(self.cu(4096))}") self.emit(f"{e2_i} = OpIAdd %int {self.as_int(ef)} {nc_i}") self.emit(f"{e2} = OpBitcast %uint {e2_i}") self.emit(f"{e2m1} = OpISub %uint {e2} {self.cu(1)}") self.emit(f"{valid} = OpULessThan %bool {e2m1} {self.cu(2046)}") # 1..2046 self.emit(f"{over} = OpSGreaterThan %bool {e2_i} {self.as_int(self.cu(2046))}") e2_sh, sig_m, norm_r_hi0, norm_r_hi, inf_hi = (self.tmp() for _ in range(5)) self.emit(f"{e2_sh} = OpShiftLeftLogical %uint {e2} {self.cu(20)}") self.emit(f"{sig_m} = OpBitwiseAnd %uint {sig_hi} {self.cu(0x000FFFFF)}") self.emit(f"{norm_r_hi0} = OpBitwiseOr %uint {sgn} {sig_m}") self.emit(f"{norm_r_hi} = OpBitwiseOr %uint {norm_r_hi0} {e2_sh}") self.emit(f"{inf_hi} = OpBitwiseOr %uint {sgn} {self.cu(0x7FF00000)}") # Subnormal / underflow (e2 <= 0): shift 53-bit significand right by sh = 1 - e2 and round to nearest even. sh_i, under, sh_ci, sh_c, sh_lt32, sh_eq32 = (self.tmp() for _ in range(6)) self.emit(f"{sh_i} = OpISub %int {self.as_int(self.cu(1))} {e2_i}") self.emit(f"{under} = OpSGreaterThan %bool {sh_i} {self.as_int(self.cu(53))}") self.emit(f"{sh_ci} = OpExtInst %int %glsl SClamp {sh_i} {self.as_int(self.cu(1))} " f"{self.as_int(self.cu(53))}") self.emit(f"{sh_c} = OpBitcast %uint {sh_ci}") self.emit(f"{sh_lt32} = OpULessThan %bool {sh_c} {self.cu(32)}") self.emit(f"{sh_eq32} = OpIEqual %bool {sh_c} {self.cu(32)}") # Path 1: 1 <= sh <= 31 s1, rs1, sm1, q1_hi, q1_lo1, q1_lo2, q1_lo, half1, hm1, mask1, rem1, gt1, eq1 = \ (self.tmp() for _ in range(13)) self.emit(f"{s1} = OpExtInst %uint %glsl UMin {sh_c} {self.cu(31)}") self.emit(f"{rs1} = OpISub %uint {self.cu(32)} {s1}") self.emit(f"{sm1} = OpISub %uint {s1} {self.cu(1)}") self.emit(f"{q1_hi} = OpShiftRightLogical %uint {sig_hi} {s1}") self.emit(f"{q1_lo1} = OpShiftRightLogical %uint {sig_lo} {s1}") self.emit(f"{q1_lo2} = OpShiftLeftLogical %uint {sig_hi} {rs1}") self.emit(f"{q1_lo} = OpBitwiseOr %uint {q1_lo1} {q1_lo2}") self.emit(f"{half1} = OpShiftLeftLogical %uint {self.cu(1)} {sm1}") self.emit(f"{hm1} = OpShiftLeftLogical %uint {half1} {self.cu(1)}") self.emit(f"{mask1} = OpISub %uint {hm1} {self.cu(1)}") self.emit(f"{rem1} = OpBitwiseAnd %uint {sig_lo} {mask1}") self.emit(f"{gt1} = OpUGreaterThan %bool {rem1} {half1}") self.emit(f"{eq1} = OpIEqual %bool {rem1} {half1}") # Path 2: sh == 32 gt2, eq2 = self.tmp(), self.tmp() self.emit(f"{gt2} = OpUGreaterThan %bool {sig_lo} {self.cu(0x80000000)}") self.emit(f"{eq2} = OpIEqual %bool {sig_lo} {self.cu(0x80000000)}") # Path 3: 33 <= sh <= 53 s3_raw, s3_ci, s3, s3m1, q3_lo, half3, hm3, mask3, rem3, lo_nz, lo_z, r3_gt, r3_eq, r3_eq_nz, gt3, eq3 = \ (self.tmp() for _ in range(16)) self.emit(f"{s3_raw} = OpISub %int {sh_ci} {self.as_int(self.cu(32))}") self.emit(f"{s3_ci} = OpExtInst %int %glsl SClamp {s3_raw} {self.as_int(self.cu(1))} " f"{self.as_int(self.cu(21))}") self.emit(f"{s3} = OpBitcast %uint {s3_ci}") self.emit(f"{s3m1} = OpISub %uint {s3} {self.cu(1)}") self.emit(f"{q3_lo} = OpShiftRightLogical %uint {sig_hi} {s3}") self.emit(f"{half3} = OpShiftLeftLogical %uint {self.cu(1)} {s3m1}") self.emit(f"{hm3} = OpShiftLeftLogical %uint {half3} {self.cu(1)}") self.emit(f"{mask3} = OpISub %uint {hm3} {self.cu(1)}") self.emit(f"{rem3} = OpBitwiseAnd %uint {sig_hi} {mask3}") self.emit(f"{lo_nz} = OpINotEqual %bool {sig_lo} {self.cu(0)}") self.emit(f"{lo_z} = OpLogicalNot %bool {lo_nz}") self.emit(f"{r3_gt} = OpUGreaterThan %bool {rem3} {half3}") self.emit(f"{r3_eq} = OpIEqual %bool {rem3} {half3}") self.emit(f"{r3_eq_nz} = OpLogicalAnd %bool {r3_eq} {lo_nz}") self.emit(f"{gt3} = OpLogicalOr %bool {r3_gt} {r3_eq_nz}") self.emit(f"{eq3} = OpLogicalAnd %bool {r3_eq} {lo_z}") # Combine paths and round to nearest even. q23_lo, gt23, eq23, q_hi, q_lo, gt, eq, odd_u, odd, tie, up, inc, ql_inc, carry_b, carry, qh_inc = \ (self.tmp() for _ in range(16)) self.emit(f"{q23_lo} = OpSelect %uint {sh_eq32} {sig_hi} {q3_lo}") self.emit(f"{gt23} = OpSelect %bool {sh_eq32} {gt2} {gt3}") self.emit(f"{eq23} = OpSelect %bool {sh_eq32} {eq2} {eq3}") self.emit(f"{q_hi} = OpSelect %uint {sh_lt32} {q1_hi} {self.cu(0)}") self.emit(f"{q_lo} = OpSelect %uint {sh_lt32} {q1_lo} {q23_lo}") self.emit(f"{gt} = OpSelect %bool {sh_lt32} {gt1} {gt23}") self.emit(f"{eq} = OpSelect %bool {sh_lt32} {eq1} {eq23}") self.emit(f"{odd_u} = OpBitwiseAnd %uint {q_lo} {self.cu(1)}") self.emit(f"{odd} = OpINotEqual %bool {odd_u} {self.cu(0)}") self.emit(f"{tie} = OpLogicalAnd %bool {eq} {odd}") self.emit(f"{up} = OpLogicalOr %bool {gt} {tie}") self.emit(f"{inc} = OpSelect %uint {up} {self.cu(1)} {self.cu(0)}") self.emit(f"{ql_inc} = OpIAdd %uint {q_lo} {inc}") self.emit(f"{carry_b} = OpULessThan %bool {ql_inc} {q_lo}") self.emit(f"{carry} = OpSelect %uint {carry_b} {self.cu(1)} {self.cu(0)}") self.emit(f"{qh_inc} = OpIAdd %uint {q_hi} {carry}") den_hi0, den_hi, den_lo, nv_hi, nv_lo, sc_hi, sc_lo, r_hi, r_lo = (self.tmp() for _ in range(9)) self.emit(f"{den_hi0} = OpBitwiseOr %uint {sgn} {qh_inc}") self.emit(f"{den_hi} = OpSelect %uint {under} {sgn} {den_hi0}") self.emit(f"{den_lo} = OpSelect %uint {under} {self.cu(0)} {ql_inc}") self.emit(f"{nv_hi} = OpSelect %uint {over} {inf_hi} {den_hi}") self.emit(f"{nv_lo} = OpSelect %uint {over} {self.cu(0)} {den_lo}") self.emit(f"{sc_hi} = OpSelect %uint {valid} {norm_r_hi} {nv_hi}") self.emit(f"{sc_lo} = OpSelect %uint {valid} {sig_lo} {nv_lo}") self.emit(f"{r_hi} = OpSelect %uint {fin} {sc_hi} {hi}") self.emit(f"{r_lo} = OpSelect %uint {fin} {sc_lo} {lo}") if "clamp" in mods: # DX10 clamp to [+0.0, 1.0]: NaN, -0.0, and negative values -> +0.0; > 1.0 (incl. +inf) -> 1.0. re, re_all, rm_hi, rm_or, rm_nz, r_nan, r_neg, to_zero = (self.tmp() for _ in range(8)) gt_hi, eq_hi, lo_gt0, eq_gt, to_one, c1_hi, c1_lo, c2_hi, c2_lo = (self.tmp() for _ in range(9)) self.emit(f"{re} = OpBitwiseAnd %uint {r_hi} {self.cu(0x7FF00000)}") self.emit(f"{re_all} = OpIEqual %bool {re} {self.cu(0x7FF00000)}") self.emit(f"{rm_hi} = OpBitwiseAnd %uint {r_hi} {self.cu(0x000FFFFF)}") self.emit(f"{rm_or} = OpBitwiseOr %uint {rm_hi} {r_lo}") self.emit(f"{rm_nz} = OpINotEqual %bool {rm_or} {self.cu(0)}") self.emit(f"{r_nan} = OpLogicalAnd %bool {re_all} {rm_nz}") self.emit(f"{r_neg} = OpUGreaterThanEqual %bool {r_hi} {self.cu(0x80000000)}") self.emit(f"{to_zero} = OpLogicalOr %bool {r_neg} {r_nan}") self.emit(f"{gt_hi} = OpUGreaterThan %bool {r_hi} {self.cu(0x3FF00000)}") self.emit(f"{eq_hi} = OpIEqual %bool {r_hi} {self.cu(0x3FF00000)}") self.emit(f"{lo_gt0} = OpINotEqual %bool {r_lo} {self.cu(0)}") self.emit(f"{eq_gt} = OpLogicalAnd %bool {eq_hi} {lo_gt0}") self.emit(f"{to_one} = OpLogicalOr %bool {gt_hi} {eq_gt}") self.emit(f"{c1_hi} = OpSelect %uint {to_one} {self.cu(0x3FF00000)} {r_hi}") self.emit(f"{c1_lo} = OpSelect %uint {to_one} {self.cu(0)} {r_lo}") self.emit(f"{c2_hi} = OpSelect %uint {to_zero} {self.cu(0)} {c1_hi}") self.emit(f"{c2_lo} = OpSelect %uint {to_zero} {self.cu(0)} {c1_lo}") r_hi, r_lo = c2_hi, c2_lo self.dst({"k": "vgpr", "r": d["r"], "n": 1}, r_lo) self.dst({"k": "vgpr", "r": d["r"] + 1, "n": 1}, r_hi) elif op in ("v_cvt_f32_u32", "v_cvt_f32_i32"): self._validate_cvt32_valu(ins, op, mods, float_src=False, float_dst=True) x = self.src_u(a[1]) r = self.tmp() self.emit(f"{r} = {'OpConvertUToF' if op.endswith('u32') else 'OpConvertSToF'} %float " f"{x if op.endswith('u32') else self.as_int(x)}") self.dst(a[0], self.tou(self.clamp_mods(r, mods))) # VOP3: clamp, omod elif op.startswith("v_cvt_f32_ubyte"): n = int(op[-1]) x = self.src_u(a[1]) s, m, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{s} = OpShiftRightLogical %uint {x} {self.cu(8 * n)}") self.emit(f"{m} = OpBitwiseAnd %uint {s} {self.cu(0xFF)}") self.emit(f"{r} = OpConvertUToF %float {m}") self.dst(a[0], self.tou(self.clamp_mods(r, mods))) elif op in ("v_cvt_flr_i32_f32", "v_cvt_rpi_i32_f32"): self._validate_cvt32_valu(ins, op, mods, float_src=True, float_dst=False) # Measured natively on RDNA2 (gfx1035 & gfx1036, wave32 & wave64): # - v_cvt_flr_i32_f32 = sat_i32(floor(S0)). # - v_cvt_rpi_i32_f32 = sat_i32(floor(S0 + 0.5)) computed exactly without binary32 rounding of S0 + 0.5: # with f = Floor(x), frac = x - f is exact in binary32 across all normal ranges (0 for |x| >= 2^23, # and rounds to >= 0.5 iff exact x - f >= 0.5 around -0.5), so (frac >= 0.5) ? (f + 1.0) : f is exact. # - Out-of-range values (|x| >= 2^31, +-inf) and NaNs all saturate by the sign bit of x (+ -> 0x7FFFFFFF, # - -> 0x80000000). Check x's bits before Floor so a driver cannot lose a NaN's sign bit. x = self.src_f(a[1]) x_bits = self.tou(x) x_mag, x_neg, x_in_range, bound, safe_x_u, fl, signed, converted, result = (self.tmp() for _ in range(9)) self.emit(f"{x_mag} = OpBitwiseAnd %uint {x_bits} {self.cu(0x7FFFFFFF)}") self.emit(f"{x_in_range} = OpULessThan %bool {x_mag} {self.cu(0x4F000000)}") # |x| < 2^31 self.emit(f"{x_neg} = OpINotEqual %bool {x_bits} {x_mag}") self.emit(f"{bound} = OpSelect %uint {x_neg} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}") # Guard before Floor/FSub/FToS: -2^31 (0xCF000000) takes `bound` = 0x80000000 directly. A denormal operand # is a zero, as on RDNA2 with f32 denormals flushed (the MODE inferred for the game; gfx1036 gives # flr(-1e-45) = 0, where Floor of the kept denormal gives -1). x_exp, x_norm, keep_x = self.tmp(), self.tmp(), self.tmp() self.emit(f"{x_exp} = OpBitwiseAnd %uint {x_bits} {self.cu(0x7F800000)}") self.emit(f"{x_norm} = OpINotEqual %bool {x_exp} {self.cu(0)}") self.emit(f"{keep_x} = OpLogicalAnd %bool {x_in_range} {x_norm}") self.emit(f"{safe_x_u} = OpSelect %uint {keep_x} {x_bits} {self.cu(0)}") safe_x = self.tof(safe_x_u) self.emit(f"{fl} = OpExtInst %float %glsl Floor {safe_x}") if op == "v_cvt_rpi_i32_f32": frac, ge_half, fl_plus1, rounded = (self.tmp() for _ in range(4)) self.emit(f"{frac} = OpFSub %float {safe_x} {fl}") self.emit(f"{ge_half} = OpFOrdGreaterThanEqual %bool {frac} {self.fconst(0.5)}") self.emit(f"{fl_plus1} = OpFAdd %float {fl} %f1") self.emit(f"{rounded} = OpSelect %float {ge_half} {fl_plus1} {fl}") fl = rounded self.emit(f"{signed} = OpConvertFToS %int {fl}") self.emit(f"{converted} = OpBitcast %uint {signed}") self.emit(f"{result} = OpSelect %uint {x_in_range} {converted} {bound}") self.dst(a[0], result) elif op in ("v_cvt_u32_f32", "v_cvt_i32_f32"): self._validate_cvt32_valu(ins, op, mods, float_src=True, float_dst=False) # Compare binary32 words before converting: the raw SPIR-V conversion # must only see a representable operand, even when its result is discarded. bits = self.src_u(a[1]) zero = self.cu(0) past_inf = self.cu(0x7F800001) in_range, saturated, safe, converted, result = (self.tmp() for _ in range(5)) if op == "v_cvt_u32_f32": positive = self.tmp() self.emit(f"{in_range} = OpULessThan %bool {bits} {self.cu(0x4F800000)}") # +2^32 # Positive overflow through +inf saturates. Negative values and NaNs give zero. self.emit(f"{positive} = OpULessThan %bool {bits} {past_inf}") self.emit(f"{saturated} = OpSelect %uint {positive} {self.cu(0xFFFFFFFF)} {zero}") else: magnitude, negative, not_nan, bound = (self.tmp() for _ in range(4)) self.emit(f"{magnitude} = OpBitwiseAnd %uint {bits} {self.cu(0x7FFFFFFF)}") self.emit(f"{in_range} = OpULessThan %bool {magnitude} {self.cu(0x4F000000)}") # 2^31 self.emit(f"{negative} = OpINotEqual %bool {bits} {magnitude}") self.emit(f"{not_nan} = OpULessThan %bool {magnitude} {past_inf}") self.emit(f"{bound} = OpSelect %uint {negative} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}") self.emit(f"{saturated} = OpSelect %uint {not_nan} {bound} {zero}") self.emit(f"{safe} = OpSelect %uint {in_range} {bits} {zero}") x = self.tof(safe) if op == "v_cvt_u32_f32": self.emit(f"{converted} = OpConvertFToU %uint {x}") else: signed = self.tmp() self.emit(f"{signed} = OpConvertFToS %int {x}") self.emit(f"{converted} = OpBitcast %uint {signed}") self.emit(f"{result} = OpSelect %uint {in_range} {converted} {saturated}") self.dst(a[0], result) elif op in U2 or op in S2: to_mask_dst, dst_half = (self._mask_b32_dst_half(a[0], a[1:3]) if op in self.MASK_SOP2_B32 else (False, None)) if op in S2: x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) is_mask = to_mask_dst or ( op in self.MASK_SOP2_B32 and (self.holds_lane_mask(a[1]) or self.holds_lane_mask(a[2])) ) if x_val is not None and y_val is not None and not is_mask: folded = None if op == "s_and_b32": folded = (x_val & y_val) & 0xFFFFFFFF elif op == "s_or_b32": folded = (x_val | y_val) & 0xFFFFFFFF elif op == "s_lshl_b32": folded = (x_val << (y_val & 31)) & 0xFFFFFFFF elif op == "s_lshr_b32": folded = (x_val >> (y_val & 31)) & 0xFFFFFFFF elif op == "s_mul_i32": folded = (x_val * y_val) & 0xFFFFFFFF if folded is not None: r = self.cu(folded) self.dst(a[0], r) if a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1 and op != "s_or_b32": self.sgpr_imm[a[0]["r"]] = folded if op in ("s_and_b32", "s_or_b32", "s_lshl_b32", "s_lshr_b32"): self.emit(f"OpStore %scc {self.cu(1 if folded != 0 else 0)}") return r = self.tmp() kind = U2.get(op) or S2.get(op) if kind == "mul24": x, y = self.src_u(a[1]), self.src_u(a[2]) xm, ym = self.tmp(), self.tmp() self.emit(f"{xm} = OpBitwiseAnd %uint {x} {self.cu(0xFFFFFF)}") self.emit(f"{ym} = OpBitwiseAnd %uint {y} {self.cu(0xFFFFFF)}") self.emit(f"{r} = OpIMul %uint {xm} {ym}") else: if op in ("s_lshl_b32", "s_lshr_b32"): y_val = self.imm_val(a[2]) if y_val is not None: y = self.cu(y_val & 31) else: y_raw = self.src_u(a[2]) m = self.tmp() self.emit(f"{m} = OpBitwiseAnd %uint {y_raw} {self.cu(31)}") y = m x = self.src_u(a[1]) else: x, y = self.sop2_b32_srcs(op, a) # lane-mask sources as mask_src (s_and/or_b32 on EXEC) self.emit(f"{r} = {kind} %uint {x} {y}") self._store_b32_mask_dst(a[0], r, to_mask_dst, dst_half) if op in ("s_and_b32", "s_or_b32"): self.scc_logic(a, r) elif op in ("s_lshl_b32", "s_lshr_b32"): self.scc_nonzero(r) elif op in SHIFT_REV: sh_val = self.imm_val(a[1]) if sh_val is not None: m = self.cu(sh_val & 31) else: sh = self.src_u(a[1]) m = self.tmp() self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(31)}") x = self.src_u(a[2]) r = self.tmp() self.emit(f"{r} = {SHIFT_REV[op]} %uint {x} {m}") self.dst(a[0], r) elif op in ("v_bfe_u32", "v_bfe_i32"): # offset and width are taken mod 32 (a width of 0 gives 0) o_val, w_val = self.imm_val(a[2]), self.imm_val(a[3]) if o_val is not None and w_val is not None: off = o_val & 31 wid = min(w_val & 31, 32 - off) x_val = self.imm_val(a[1]) if x_val is not None: if wid == 0: val = 0 elif op == "v_bfe_u32": val = (x_val >> off) & ((1 << wid) - 1) else: raw = (x_val >> off) & ((1 << wid) - 1) sign_bit = 1 << (wid - 1) val = ((raw ^ sign_bit) - sign_bit) & 0xFFFFFFFF self.dst(a[0], self.cu(val)) return om = self.cu(off) wc = self.cu(wid) else: if o_val is not None: om = self.cu(o_val & 31) else: o = self.src_u(a[2]) om = self.tmp() self.emit(f"{om} = OpBitwiseAnd %uint {o} {self.cu(31)}") if w_val is not None: wm = self.cu(w_val & 31) else: w = self.src_u(a[3]) wm = self.tmp() self.emit(f"{wm} = OpBitwiseAnd %uint {w} {self.cu(31)}") wc = self.bfe_width(om, wm) x = self.src_u(a[1]) r = self.tmp() f = "OpBitFieldSExtract" if op.endswith("i32") else "OpBitFieldUExtract" self.emit(f"{r} = {f} %uint {x} {om} {wc}") self.dst(a[0], r) elif op in ("v_mad_u64_u32", "v_mad_i64_i32"): # {sdst, v[d:d+1]} = S0 * S1 + S2 as a 65-bit result (RDNA ISA pseudocode): 32 x 32 -> 64-bit product, # unsigned or signed, plus the 64-bit S2. sdst (a lane mask) gets bit 64: the carry out for u64; for i64 # the sign of the exact sum, which a 65-bit two's-complement value always holds. if a[0].get("n") != 2 or "clamp" in mods: raise Unsupported(op + " operands") vd, sd, s0, s1, s2 = a[0], a[1], a[2], a[3], a[4] signed = op == "v_mad_i64_i32" if s2["k"] in ("vgpr", "sgpr") and s2.get("n") == 2: c_lo, c_hi = self.load_reg(s2["k"], s2["r"]), self.load_reg(s2["k"], s2["r"] + 1) elif s2["k"] == "imm": # An inline constant is sign-extended; a 32-bit literal too for the i64 S2, zero-extended for u64. v = self.valu_imm_i64(s2["v"]) if signed else s2["v"] & 0xFFFFFFFFFFFFFFFF c_lo, c_hi = self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) else: raise Unsupported(op + " operands") x, y = self.src_u(s0), self.src_u(s1) pm, p_lo, p_hi = self.tmp(), self.tmp(), self.tmp() if signed: ph = self.tmp() self.emit(f"{pm} = OpSMulExtended %smul {self.as_int(x)} {self.as_int(y)}") pl = self.tmp() self.emit(f"{pl} = OpCompositeExtract %int {pm} 0") self.emit(f"{ph} = OpCompositeExtract %int {pm} 1") self.emit(f"{p_lo} = OpBitcast %uint {pl}") self.emit(f"{p_hi} = OpBitcast %uint {ph}") self.uses_smul = True else: self.emit(f"{pm} = OpUMulExtended %umul {x} {y}") self.emit(f"{p_lo} = OpCompositeExtract %uint {pm} 0") self.emit(f"{p_hi} = OpCompositeExtract %uint {pm} 1") s_lo, r_lo, c0, s_h1, h1, c1, s_h2, r_hi, c2 = (self.tmp() for _ in range(9)) self.emit(f"{s_lo} = OpIAddCarry %umul {p_lo} {c_lo}") self.emit(f"{r_lo} = OpCompositeExtract %uint {s_lo} 0") self.emit(f"{c0} = OpCompositeExtract %uint {s_lo} 1") self.emit(f"{s_h1} = OpIAddCarry %umul {p_hi} {c_hi}") self.emit(f"{h1} = OpCompositeExtract %uint {s_h1} 0") self.emit(f"{c1} = OpCompositeExtract %uint {s_h1} 1") self.emit(f"{s_h2} = OpIAddCarry %umul {h1} {c0}") self.emit(f"{r_hi} = OpCompositeExtract %uint {s_h2} 0") self.emit(f"{c2} = OpCompositeExtract %uint {s_h2} 1") if signed: # Sign of the exact sum: the operands' common sign if they agree, else the wrapped sum's sign. sp, sc, sr, same, neg = (self.tmp() for _ in range(5)) self.emit(f"{sp} = OpShiftRightLogical %uint {p_hi} {self.cu(31)}") self.emit(f"{sc} = OpShiftRightLogical %uint {c_hi} {self.cu(31)}") self.emit(f"{sr} = OpShiftRightLogical %uint {r_hi} {self.cu(31)}") self.emit(f"{same} = OpIEqual %bool {sp} {sc}") self.emit(f"{neg} = OpSelect %uint {same} {sp} {sr}") bit64 = neg else: bit64 = self.tmp() self.emit(f"{bit64} = OpBitwiseOr %uint {c1} {c2}") self.dst({"k": "vgpr", "r": vd["r"], "n": 1}, r_lo) self.dst({"k": "vgpr", "r": vd["r"] + 1, "n": 1}, r_hi) if not (sd["k"] == "special" and sd["t"] == "null"): bm, m = self.tmp(), self.tmp() self.emit(f"{bm} = OpLogicalAnd %bool {self.tmp_bool_nz(bit64)} {self.active_b()}") # inactive lanes write 0 self.emit(f"{m} = OpSelect %uint {bm} {self.cu(0xFFFFFFFF)} {self.cu(0)}") self.mask_dst(sd, m) elif op in ("v_mad_u32_u16", "v_mad_i32_i16"): # D = S0.half * S1.half + S2 (RDNA ISA pseudocode), wrapping at 32 bits: the 16-bit halves zero-extended # (u16) or sign-extended (i16); op_sel bits 0 / 1 read the high half of S0 / S1. Measured on RDNA2 # (gfx1036, raw kernels, wave32 and wave64, EGEN-HW-MAD-U32-U16) for the other bits: op_sel bit 2 adds # S2[31:16] zero-extended, also in the i16 op (S2 = 0xffff8000 adds 0xffff); op_sel bit 3 writes the # result shifted left by 16 (low half 0, the old D not kept); clamp saturates the sum to [0, 0xffffffff] # (u16) or [0x80000000, 0x7fffffff] (i16), before that shift. sel, dhi = self.opsel_bits(mods, 3) signed = op == "v_mad_i32_i16" hs = [self.as_uint(self.i16_half(self.src_u(src), sel[i])) if signed else self.u16_half(self.src_u(src), sel[i]) for i, src in enumerate(a[1:3])] c = self.src_u(a[3]) if sel[2]: c2 = self.tmp() self.emit(f"{c2} = OpShiftRightLogical %uint {c} {self.cu(16)}") c = c2 m, r = self.tmp(), self.tmp() self.emit(f"{m} = OpIMul %uint {hs[0]} {hs[1]}") self.emit(f"{r} = OpIAdd %uint {m} {c}") if "clamp" in mods: # Two 16-bit halves never overflow their 32-bit product, so only the addition can: unsigned when # the sum is below the product, signed when product and addend share a sign the sum lacks. ov, sat, rs = self.tmp(), self.tmp(), self.tmp() if signed: x1, x2, both, neg = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{x1} = OpBitwiseXor %uint {r} {m}") self.emit(f"{x2} = OpBitwiseXor %uint {r} {c}") self.emit(f"{both} = OpBitwiseAnd %uint {x1} {x2}") self.emit(f"{ov} = OpSLessThan %bool {self.as_int(both)} {self.as_int(self.cu(0))}") self.emit(f"{neg} = OpSLessThan %bool {self.as_int(c)} {self.as_int(self.cu(0))}") self.emit(f"{sat} = OpSelect %uint {neg} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}") else: self.emit(f"{ov} = OpULessThan %bool {r} {m}") sat = self.cu(0xFFFFFFFF) self.emit(f"{rs} = OpSelect %uint {ov} {sat} {r}") r = rs if dhi: rd = self.tmp() self.emit(f"{rd} = OpShiftLeftLogical %uint {r} {self.cu(16)}") r = rd self.dst(a[0], r) elif op in ("v_dot4_i32_i8", "v_dot4c_i32_i8"): # The four products of the signed bytes of two dwords, summed, plus an addend: the third source for # v_dot4_i32_i8 (VOP3P), the destination's old value for v_dot4c_i32_i8 (VOP2). The sum wraps at 32 bits, # or saturates to signed 32-bit [-2^31, 2^31-1] with clamp (VOP3P). # Measured on RDNA2 hardware (docs/design.md, "Signed-byte dot products"): op_sel[k] picks the 16-bit half # of source k (0=lo, 1=hi) for byte pairs 0..1, and op_sel_hi[k] picks the 16-bit half for byte pairs 2..3 # (defaults op_sel=[0,0,0], op_sel_hi=[1,1,1]). S2 (addend) is 32-bit; non-default S2 half-select is refused. # neg_lo/neg_hi are not ignored either: measured on v_dot4_i32_i8, they flip bit 15 and bit 31 of a # source dword (and take the addend's absolute value, then negate it), as if the operands were floats. # A set bit is refused; an all-zero field is the plain instruction. def bits(name, default): m = next((m for m in mods if m.startswith(name + ":")), None) return [int(v) for v in m.split("[")[1].rstrip("]").split(",")] if m else default is_vop3p = op == "v_dot4_i32_i8" has_opsel = any(m.startswith("op_sel") for m in mods) has_clamp = "clamp" in mods if not is_vop3p and (has_opsel or has_clamp): raise Unsupported(op + (" clamp" if has_clamp else " op_sel")) if any(m.startswith(("neg_lo", "neg_hi")) and "1" in m.split(":", 1)[-1] for m in mods): raise Unsupported(op + " neg") sel = bits("op_sel", [0, 0, 0]) selhi = bits("op_sel_hi", [1, 1, 1]) if len(sel) != 3 or len(selhi) != 3 or sel[2] != 0 or selhi[2] != 1: raise Unsupported(op + " op_sel") x, y = self.src_u(a[1]), self.src_u(a[2]) acc = self.src_u(a[3]) if is_vop3p else self.src_u(a[0]) packed = self.packed_dot4(self.dot4_halves(x, sel[0], selhi[0]), self.dot4_halves(y, sel[1], selhi[1]), acc, signed=True, clamp=has_clamp) if packed is not None: self.dst(a[0], packed) return x_offs = (16 * sel[0], 16 * sel[0] + 8, 16 * selhi[0], 16 * selhi[0] + 8) y_offs = (16 * sel[1], 16 * sel[1] + 8, 16 * selhi[1], 16 * selhi[1] + 8) dot = None for xo, yo in zip(x_offs, y_offs): xb, yb, prod = self.tmp(), self.tmp(), self.tmp() self.emit(f"{xb} = OpBitFieldSExtract %uint {x} {self.cu(xo)} {self.cu(8)}") self.emit(f"{yb} = OpBitFieldSExtract %uint {y} {self.cu(yo)} {self.cu(8)}") self.emit(f"{prod} = OpIMul %uint {xb} {yb}") if dot is None: dot = prod else: s = self.tmp() self.emit(f"{s} = OpIAdd %uint {dot} {prod}") dot = s total = self.tmp() self.emit(f"{total} = OpIAdd %uint {acc} {dot}") if has_clamp: # dot is in [-65024, 65536], so signed 32-bit overflow can only happen once in acc + dot: # iff acc and dot share a sign bit and total has the opposite sign bit. same_x, not_same, diff_sum, ov_bits, ov_sign, is_ov, acc_neg, sat, clamped = (self.tmp() for _ in range(9)) self.emit(f"{same_x} = OpBitwiseXor %uint {acc} {dot}") self.emit(f"{not_same} = OpNot %uint {same_x}") self.emit(f"{diff_sum} = OpBitwiseXor %uint {acc} {total}") self.emit(f"{ov_bits} = OpBitwiseAnd %uint {not_same} {diff_sum}") self.emit(f"{ov_sign} = OpBitwiseAnd %uint {ov_bits} {self.cu(0x80000000)}") self.emit(f"{is_ov} = OpINotEqual %bool {ov_sign} {self.cu(0)}") self.emit(f"{acc_neg} = OpSLessThan %bool {acc} {self.cu(0)}") self.emit(f"{sat} = OpSelect %uint {acc_neg} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}") self.emit(f"{clamped} = OpSelect %uint {is_ov} {sat} {total}") total = clamped self.dst(a[0], total) elif op == "v_mad_u32_u24": x, y, z = (self.src_u(t) for t in a[1:4]) xm, ym, p, r = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{xm} = OpBitwiseAnd %uint {x} {self.cu(0xFFFFFF)}") self.emit(f"{ym} = OpBitwiseAnd %uint {y} {self.cu(0xFFFFFF)}") self.emit(f"{p} = OpIMul %uint {xm} {ym}") self.emit(f"{r} = OpIAdd %uint {p} {z}") self.dst(a[0], r) elif op == "v_cndmask_b32": # e32: dst, src0, src1 (vcc) ; e64: dst, src0, src1, sN[:N+1]/vcc. A bit move: the e64 abs/neg source # modifiers are sign-bit moves, never float ops (see src_u_sign_mods). x, y = self.src_u_sign_mods(a[1]), self.src_u_sign_mods(a[2]) c = self.mask_src(a[3]) if len(a) > 3 else self.mask_src({"k": "special", "t": "vcc"}) b, r = self.tmp(), self.tmp() self.emit(f"{b} = OpINotEqual %bool {c} {self.cu(0)}") self.emit(f"{r} = OpSelect %uint {b} {y} {x}") self.dst(a[0], r) elif op == "exp": self.export(ins) else: raise Unsupported(op) def dot4_halves(self, x, lo_half, hi_half): """The dword a 4x8-bit dot product reads under op_sel: bytes 0..1 from 16-bit half `lo_half` of `x` and bytes 2..3 from half `hi_half` (0 low, 1 high; the default is 0 and 1, `x` itself).""" if (lo_half, hi_half) == (0, 1): return x lo, hi, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{lo} = OpBitFieldUExtract %uint {x} {self.cu(16 * lo_half)} {self.cu(16)}") self.emit(f"{hi} = OpBitFieldUExtract %uint {x} {self.cu(16 * hi_half)} {self.cu(16)}") self.emit(f"{r} = OpBitFieldInsert %uint {lo} {hi} {self.cu(16)} {self.cu(16)}") return r def packed_dot4(self, x, y, acc, *, signed, clamp): """acc + the dot product of the four bytes of x and y as one SPV_KHR_integer_dot_product instruction, or None under --integer-dot-fallback (the caller expands it). OpSDot / OpUDot give the low 32 bits of the exact sum of the four products of the sign- (zero-) extended bytes (PackedVectorFormat4x8Bit), the sum v_dot4_i32_i8 / v_dot4_u32_u8 form; adding acc wraps at 32 bits as the instructions do without clamp. With clamp the hardware saturates acc + the exact sum (signed 32-bit for i8, unsigned for u8; docs/design.md, "Signed-byte dot products" and "Packed integer dot products"), which is OpSDotAccSat / OpUDotAccSat: "the correct result ... computed with enough precision to avoid overflow", saturated to the result type. The signed forms use %int operands, so the signedness is the type's too.""" if INTEGER_DOT_FALLBACK: return None self.uses_int_dot = True fmt = "PackedVectorFormat4x8BitKHR" if not signed: r = self.tmp() if clamp: self.emit(f"{r} = OpUDotAccSatKHR %uint {x} {y} {acc} {fmt}") else: d = self.tmp() self.emit(f"{d} = OpUDotKHR %uint {x} {y} {fmt}") self.emit(f"{r} = OpIAdd %uint {acc} {d}") return r xi, yi = self.tmp(), self.tmp() self.emit(f"{xi} = OpBitcast %int {x}") self.emit(f"{yi} = OpBitcast %int {y}") if clamp: ai, s, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{ai} = OpBitcast %int {acc}") self.emit(f"{s} = OpSDotAccSatKHR %int {xi} {yi} {ai} {fmt}") self.emit(f"{r} = OpBitcast %uint {s}") return r d, du, r = self.tmp(), self.tmp(), self.tmp() self.emit(f"{d} = OpSDotKHR %int {xi} {yi} {fmt}") self.emit(f"{du} = OpBitcast %uint {d}") self.emit(f"{r} = OpIAdd %uint {acc} {du}") return r def sbuf_slow_function(self, n, ro=False): """Build (once per (width, ro) with n in {2, 4, 8, 16}) the partial-OOB helper %sbuf_slow_{ro|rw}_x{n}. Called from the cold lbl_slow branch of wide s_buffer_load_dwordxN when the last dword is past limit. Uses a compact counted loop (DontUnroll) with ONE OpLoad in the loop body, storing into a zero-initialized Function-scope %arr_sbuf_x{n} and returning OpLoad %arr_sbuf_x{n}: each dword i with off + 4*i + 4 <= lim is loaded at host + 4*i (Aligned 4); out-of-range dwords stay 0 without reading past limit. When ro=True, loads through NonWritable %_ptr_PSB_sl_blk1 so RADV/ACO keeps SMEM s_load_dword even inside the slow path; when ro=False, loads through mutable %_ptr_PSB_arr.""" ro = bool(ro) key = (n, ro) tag = "ro" if ro else "rw" fn = f"%sbuf_slow_{tag}_x{n}" if key not in self.sbuf_slow_fns: p = f"%sbs_{tag}{n}_" arr = f"%arr_sbuf_x{n}" ptr_arr = f"%_ptr_Function_arr_sbuf_x{n}" null_arr = f"%null_sbuf_x{n}" c0 = self.cu(0) c1 = self.cu(1) self.cu(n) cl2 = self.cl(2) cln = self.cl(n) if ro: self.uses_psb_scalar_ro = True lines = [ f"{fn} = OpFunction {arr} None %fn_sbuf_slow_x{n}", f"{p}host = OpFunctionParameter %ulong", f"{p}off = OpFunctionParameter %ulong", f"{p}lim = OpFunctionParameter %ulong", f"{p}entry = OpLabel", f"{p}out = OpVariable {ptr_arr} Function {null_arr}", # Overflow-safe exact in-range dword count: # off + 4*i + 4 <= lim <=> lim >= off and i < min((lim - off) >> 2, n). f"{p}ge = OpUGreaterThanEqual %bool {p}lim {p}off", f"{p}diff = OpISub %ulong {p}lim {p}off", f"{p}avail = OpShiftRightLogical %ulong {p}diff {cl2}", f"{p}lt_n = OpULessThan %bool {p}avail {cln}", f"{p}cnt64 = OpSelect %ulong {p}lt_n {p}avail {cln}", f"{p}cnt_u = OpUConvert %uint {p}cnt64", f"{p}cnt = OpSelect %uint {p}ge {p}cnt_u {c0}", ] if not ro: lines.append(f"{p}ptr = OpConvertUToPtr %_ptr_PSB_arr {p}host") lines += [ f"OpBranch {p}head", f"{p}head = OpLabel", f"{p}i = OpPhi %uint {c0} {p}entry {p}next {p}cont", f"{p}cond = OpULessThan %bool {p}i {p}cnt", f"OpLoopMerge {p}exit {p}cont DontUnroll", f"OpBranchConditional {p}cond {p}body {p}exit", f"{p}body = OpLabel", ] if ro: lines += [ f"{p}i64 = OpUConvert %ulong {p}i", f"{p}boff = OpShiftLeftLogical %ulong {p}i64 {cl2}", f"{p}addr = OpIAdd %ulong {p}host {p}boff", f"{p}bptr = OpConvertUToPtr %_ptr_PSB_sl_blk1 {p}addr", f"{p}qptr = OpAccessChain %_ptr_PSB_uint {p}bptr {c0}", f"{p}val = OpLoad %uint {p}qptr Aligned 4", ] else: lines += [ f"{p}qptr = OpAccessChain %_ptr_PSB_uint {p}ptr {p}i", f"{p}val = OpLoad %uint {p}qptr Aligned 4", ] lines += [ f"{p}slot = OpAccessChain %_ptr_Function_uint {p}out {p}i", f"OpStore {p}slot {p}val", f"OpBranch {p}cont", f"{p}cont = OpLabel", f"{p}next = OpIAdd %uint {p}i {c1}", f"OpBranch {p}head", f"{p}exit = OpLabel", f"{p}res = OpLoad {arr} {p}out", f"OpReturnValue {p}res", "OpFunctionEnd", ] self.sbuf_slow_fns[key] = lines return fn def scalar_load(self, op, a, mods): """s_load_dwordxN sD, s[p:p+1], off -> N dwords from a 64-bit pointer, no bound s_buffer_load_dwordxN sD, s[v:v+3], off -> N dwords from a V#, each checked against NUM_RECORDS Both become PhysicalStorageBuffer loads (Vulkan buffer device address). V# base = dword0 | (dword1 & 0xFFFF) << 32 (AMD RDNA ISA, buffer resource descriptor). off is an immediate or a scalar register. An SMEM load can carry both, which llvm-mc prints as "sOFF offset:IMM" (the immediate arrives in mods); both are added. Measured on an AMD Radeon RX 6800 (gfx1030) as a raw compute kernel, wave32 and wave64 (docs/design.md, Scalar/buffer memory): off = (sOFF & ~3) + (IMM & ~3); dword i is read at (base & ~3) + off + 4*i (base, sOFF, IMM truncated each on its own, then added). s_buffer_load*: dword i is 0, and memory is not read, when off + 4*i + 4 > limit, limit = NUM_RECORDS * stride bytes when the V# stride (dword1[29:16]) is not 0, else NUM_RECORDS bytes (V# dword2). The bound is per dword and does not see base & 3; IMM is unsigned. s_load*: IMM is sign-extended from 21 bits and the sum is formed in 64 bits; no bound. Measured on gfx1036 (RDNA2): x16 is bounded per dword like x8, NUM_RECORDS * stride is 64-bit (2^32 does not wrap to 0), NUM_RECORDS >= 2^31 is unsigned, and an s_load with sOFF + IMM < 0 reads at the 64-bit signed sum. An s_buffer_load immediate with bit 20 set does not follow the bound on hardware and is not modelled (kept as the 32-bit value, as before).""" n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) d, base = a[0], a[1] # A single dword may also land in vcc_lo / m0 / vcc_hi (seen: s_buffer_load_dword vcc_lo, ...), and a wide # load may target an LLVM VCCTuple list ending in vcc_lo,vcc_hi (seen in 6 FSPX shaders: s[100..105]+vcc). single_special = (n == 1 and d["k"] == "special" and d["t"] in ("vcc_lo", "vcc", "m0", "vcc_hi")) or \ (n == 2 and d["k"] == "special" and d["t"] == "vcc") slist_dst = d["k"] == "slist" and len(d["r"]) == n base_slots = (list(range(base["r"], base["r"] + base.get("n", 1))) if base["k"] == "sgpr" else list(base["r"]) if base["k"] == "slist" else ["vcc_lo", "vcc_hi"] if (base["k"] == "special" and base["t"] == "vcc") else None) if (d["k"] != "sgpr" and not single_special and not slist_dst) or base_slots is None: raise Unsupported(f"{op} operands {d.get('t', d['k'])} {base.get('t', base['k'])}") def load_slot(slot): if isinstance(slot, int): return self.load_reg("sgpr", slot) half = {"k": "special", "t": slot} if base.get("t") == "vcc" and self.holds_lane_mask(half): if self.emulate: raise Unsupported(op + " emulated wave64 lane-mask pointer") return self.lane_mask_word(half) t = self.tmp() self.emit(f"{t} = OpLoad %uint {'%vcc' if slot == 'vcc_lo' else '%vcc_hi'}") return t def store_slot(slot, val): if isinstance(slot, int): self.store_reg("sgpr", slot, val) else: self.emit(f"OpStore {'%vcc' if slot == 'vcc_lo' else '%vcc_hi'} {val}") sbuf = op.startswith("s_buffer") if sbuf: if len(base_slots) != 4: raise Unsupported("s_buffer_load without V#") else: if len(base_slots) != 2: raise Unsupported("s_load without 64-bit pointer") lo, hi = load_slot(base_slots[0]), load_slot(base_slots[1]) word1 = hi if sbuf: m = self.tmp() self.emit(f"{m} = OpBitwiseAnd %uint {hi} {self.cu(0xFFFF)}") hi = m off = a[2] if len(a) > 2 else {"k": "imm", "v": 0} inst = [m.split(":", 1)[1] for m in mods if m.startswith("offset:")] if len(a) > 3 or len(inst) > 1 or (inst and off["k"] == "imm"): raise Unsupported(f"{op} offset form") # not something llvm-mc prints: don't guess an address imm = 0 if inst: try: imm = int(inst[0], 0) except ValueError: raise Unsupported(f"{op} offset:{inst[0]}") from None reg = None const_off = None off_val = self.imm_val(off) if off["k"] == "imm": imm = off["v"] # immediate-only form elif off_val is not None: const_off = off_val & 0xFFFFFFFC # an SGPR offset the translator knows: added below else: reg = self.src_u(off) if sbuf: imm &= 0xFFFFFFFF # unsigned (measured up to 0xffffc) else: imm = ((imm & 0x1FFFFF) ^ 0x100000) - 0x100000 # 21-bit signed imm &= ~3 # two's complement: -1 -> -4, -6 -> -8 if const_off is not None: # The same sum as the run-time path below, zext(sOFF & ~3) + imm, kept as a Python int: no 32-bit wrap. # Until 2026-11-22 (#1686) the constant was added before the 32-bit truncation, so s8 = -4 with # offset:20 read byte 16 instead of being out of range (hardware: 0xFFFFFFFC + 20 reads 0, measured by # @Pierre-Kookis on gfx1036; found by @Impre-visible). The address and the s_buffer_load bound use it. imm = const_off + imm # Byte offset from the 4-truncated base, in 64 bits: zext(sOFF & ~3) + imm, or the constant alone. if reg is not None: r4, r64 = self.tmp(), self.tmp() self.emit(f"{r4} = OpBitwiseAnd %uint {reg} {self.cu(0xFFFFFFFC)}") self.emit(f"{r64} = OpUConvert %ulong {r4}") if imm: o64 = self.tmp() self.emit(f"{o64} = OpIAdd %ulong {r64} {self.cl(imm)}") else: o64 = r64 else: o64 = self.cl(imm) lo4, l64, h64, sh, addr, full = (self.tmp() for _ in range(6)) self.emit(f"{lo4} = OpBitwiseAnd %uint {lo} {self.cu(0xFFFFFFFC)}") self.emit(f"{l64} = OpUConvert %ulong {lo4}") self.emit(f"{h64} = OpUConvert %ulong {hi}") self.emit(f"{sh} = OpShiftLeftLogical %ulong {h64} %c64_32") self.emit(f"{addr} = OpBitwiseOr %ulong {sh} {l64}") self.emit(f"{full} = OpIAdd %ulong {addr} {o64}") host = self.host_addr(full, 'load', 4 * n) self.uses_psb = True coherent = self._is_coherent_mem(mods) load_mem = self._psb_load_op(mods) ro = (not coherent) and (self.scalar_load_ro is None or self.scalar_load_ro is True or (self.cur_ins is not None and id(self.cur_ins) in self.scalar_load_ro)) scalar_ro = ro and self.scalar_load_ro is not None ptr_cache = [None] def get_ptr(): if ptr_cache[0] is None: p = self.tmp() self.emit(f"{p} = OpConvertUToPtr %_ptr_PSB_arr {host}") ptr_cache[0] = p return ptr_cache[0] def wide(count): """Dwords 0..count-1 at the load's address as the fewest loads SPIR-V types allow: uvec4, then uvec2, then one uint. Each is Aligned 4, the alignment SMEM has. One instruction's dwords are consecutive in memory, so a driver can fetch them as one scalar or vector load instead of one per dword (RADV gave 6,048 global_load_b32, 5,935 v_readfirstlane and 5,448 64-bit compares for the 365 s_buffer_load_dwordx16 of an FSPX program loaded per dword). Provably non-aliasing scalar loads read through a NonWritable Block (%sl_blk1 / %sl_blk2 / %sl_blk4) so RADV emits SMEM (s_load_b32..b512); loads that may alias a store/atomic in the same module read through a mutable Block (%sl_rw_blk2 / %sl_rw_blk4) or %_ptr_PSB_arr so stores remain visible. Coherent (glc/dlc) loads always use scalar mutable loads carrying MakePointerVisible|NonPrivatePointer.""" got, k = [], 0 while k < count: w = 1 if coherent else (4 if count - k >= 4 else 2 if count - k >= 2 else 1) if w == 1: if scalar_ro: self.uses_psb_scalar_ro = True at = host if k: at = self.tmp() self.emit(f"{at} = OpIAdd %ulong {host} {self.cl(4 * k)}") b, q, v = self.tmp(), self.tmp(), self.tmp() self.emit(f"{b} = OpConvertUToPtr %_ptr_PSB_sl_blk1 {at}") self.emit(f"{q} = OpAccessChain %_ptr_PSB_uint {b} {self.cu(0)}") self.emit(f"{v} = OpLoad %uint {q} Aligned 4") else: q, v = self.tmp(), self.tmp() self.emit(f"{q} = OpAccessChain %_ptr_PSB_uint {get_ptr()} {self.cu(k)}") self.emit(f"{v} = OpLoad %uint {q} {load_mem}") got.append(v) else: if ro: self.uses_psb_vec = True blk_ptr = f"%_ptr_PSB_sl_blk{w}" else: self.uses_psb_vec_rw = True blk_ptr = f"%_ptr_PSB_sl_rw_blk{w}" at = host if k: at = self.tmp() self.emit(f"{at} = OpIAdd %ulong {host} {self.cl(4 * k)}") b, q, v = self.tmp(), self.tmp(), self.tmp() self.emit(f"{b} = OpConvertUToPtr {blk_ptr} {at}") self.emit(f"{q} = OpAccessChain %_ptr_PSB_v{w}uint_sl {b} {self.cu(0)}") self.emit(f"{v} = OpLoad %v{w}uint_sl {q} Aligned 4") for j in range(w): e = self.tmp() self.emit(f"{e} = OpCompositeExtract %uint {v} {j}") got.append(e) k += w return got lim = None lim_val = None if sbuf: # limit = NUM_RECORDS * stride, or NUM_RECORDS when stride is 0 (bytes, 64-bit so the product can't wrap); # SQ_RSRC_BUF.TYPE is word3[31:30] and must be 0 (uint32(word3) < 0x40000000), else limit = 0. lit1 = self.sgpr_imm.get(base_slots[1]) if isinstance(base_slots[1], int) else None lit2 = self.sgpr_imm.get(base_slots[2]) if isinstance(base_slots[2], int) else None lit3 = self.sgpr_imm.get(base_slots[3]) if isinstance(base_slots[3], int) else None if lit3 is not None and (lit3 & 0xFFFFFFFF) >= 0x40000000: lim_val = 0 lim = self.cl(0) else: if lit1 is not None and lit2 is not None: stride = (lit1 >> 16) & 0x3FFF lim_val = lit2 if stride == 0 else lit2 * stride lim = self.cl(lim_val) else: stride, nr64, st64, prod, raw, lim = (self.tmp() for _ in range(6)) nr = load_slot(base_slots[2]) self.emit(f"{stride} = OpBitFieldUExtract %uint {word1} {self.cu(16)} {self.cu(14)}") self.emit(f"{nr64} = OpUConvert %ulong {nr}") self.emit(f"{st64} = OpUConvert %ulong {stride}") self.emit(f"{prod} = OpIMul %ulong {nr64} {st64}") self.emit(f"{raw} = OpIEqual %bool {stride} {self.cu(0)}") self.emit(f"{lim} = OpSelect %ulong {raw} {nr64} {prod}") if lit3 is None: w3 = load_slot(base_slots[3]) is_buf, gated_lim = self.tmp(), self.tmp() self.emit(f"{is_buf} = OpULessThan %bool {w3} {self.cu(0x40000000)}") self.emit(f"{gated_lim} = OpSelect %ulong {is_buf} {lim} {self.cl(0)}") lim = gated_lim lim_val = None guarded = {} if lim is not None and not (lim_val is not None and reg is None) and n > 1: # Every dword in range (the last one is, so all are): one wide load, the common case. Otherwise call # the shared per-width partial-OOB loop helper %sbuf_slow_{ro|rw}_x{n}. last_end, all_ok = self.tmp(), self.tmp() if reg is not None: self.emit(f"{last_end} = OpIAdd %ulong {o64} {self.cl(4 * n)}") else: last_end = self.cl(imm + 4 * n) self.emit(f"{all_ok} = OpUGreaterThanEqual %bool {lim} {last_end}") if coherent: get_ptr() lbl_fast, lbl_slow, lbl_join = self.tmp() + "_all", self.tmp() + "_part", self.tmp() + "_join" self.emit(f"OpSelectionMerge {lbl_join} None") self.emit(f"OpBranchConditional {all_ok} {lbl_fast} {lbl_slow}") self.emit(f"{lbl_fast} = OpLabel") fast = wide(n) fast_exit = self.current_label_placeholder() self.emit(f"OpBranch {lbl_join}") self.emit(f"{lbl_slow} = OpLabel") if not coherent: slow_fn = self.sbuf_slow_function(n, ro=ro) slow_arr = self.tmp() self.emit(f"{slow_arr} = OpFunctionCall %arr_sbuf_x{n} {slow_fn} {host} {o64} {lim}") slow_vals = [] for i in range(n): e = self.tmp() self.emit(f"{e} = OpCompositeExtract %uint {slow_arr} {i}") slow_vals.append(e) else: oks = [] for i in range(n): end, ok = self.tmp(), self.tmp() if reg is not None: self.emit(f"{end} = OpIAdd %ulong {o64} {self.cl(4 * i + 4)}") else: end = self.cl(imm + 4 * i + 4) self.emit(f"{ok} = OpUGreaterThanEqual %bool {lim} {end}") oks.append(ok) lbl_cdo, lbl_cend = self.tmp() + "_cdo", self.tmp() + "_cend" cpre = self.current_label_placeholder() self.emit(f"OpSelectionMerge {lbl_cend} None") self.emit(f"OpBranchConditional {oks[0]} {lbl_cdo} {lbl_cend}") self.emit(f"{lbl_cdo} = OpLabel") got_in = [] for i in range(n): idx, p, got, val = (self.tmp() for _ in range(4)) if i == 0: idx = self.cu(0) else: self.emit(f"{idx} = OpSelect %uint {oks[i]} {self.cu(i)} {self.cu(0)}") self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {get_ptr()} {idx}") self.emit(f"{got} = OpLoad %uint {p} {load_mem}") if i == 0: val = got else: self.emit(f"{val} = OpSelect %uint {oks[i]} {got} {self.cu(0)}") got_in.append(val) self.emit(f"OpBranch {lbl_cend}") self.emit(f"{lbl_cend} = OpLabel") slow_vals = [] for i in range(n): sv = self.tmp() self.emit(f"{sv} = OpPhi %uint {got_in[i]} {lbl_cdo} {self.cu(0)} {cpre}") slow_vals.append(sv) slow_exit = self.current_label_placeholder() self.emit(f"OpBranch {lbl_join}") self.emit(f"{lbl_join} = OpLabel") for i in range(n): v = self.tmp() self.emit(f"{v} = OpPhi %uint {fast[i]} {fast_exit} {slow_vals[i]} {slow_exit}") guarded[i] = v elif lim is not None and not (lim_val is not None and reg is None): # Single-dword run-time bound: 0 without reading memory when off + 4 > limit. end, ok = self.tmp(), self.tmp() if reg is not None: self.emit(f"{end} = OpIAdd %ulong {o64} {self.cl(4)}") else: end = self.cl(imm + 4) self.emit(f"{ok} = OpUGreaterThanEqual %bool {lim} {end}") lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" pre = self.current_label_placeholder() self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {ok} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") got = wide(1)[0] self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") v = self.tmp() self.emit(f"{v} = OpPhi %uint {got} {lbl_do} {self.cu(0)} {pre}") guarded[0] = v if guarded: vals = [guarded[i] for i in range(n)] elif lim is None: vals = wide(n) else: # A bound known at translate time (lim_val, constant offset). The dwords in range are a prefix (their # ends grow with i): one wide load for them, 0 for the rest. count = sum(lim_val >= imm + 4 * i + 4 for i in range(n)) vals = wide(count) + [self.cu(0)] * (n - count) for i in range(n): v = vals[i] if single_special: if n == 2: # vcc pair: low dword -> vcc_lo, high dword -> vcc_hi (data, not a lane mask) self.emit(f"OpStore {'%vcc' if i == 0 else '%vcc_hi'} {v}") else: self.dst(d, v) elif slist_dst: store_slot(d["r"][i], v) else: self.store_reg("sgpr", d["r"] + i, v) # ---- images: T#/S# -> bindless index through a runtime-filled hash table ---- # Table layout (storage buffer, set 0 binding 2): uint mask; then entries of 10 uints: # key[0..7] (descriptor dwords; S# uses key[0..3] and key[4..7] = 0xFFFFFFFF), index, kind. # Probes 8 slots from hash(key) & mask; a miss yields index 0 (the runtime puts a fallback there). # The last word is the pad word a plain module never reads; --descriptor-table tagged fills it with the kind. PROBES = 8 def desc_lookup(self, words, uniform=True): """words: 8 uint ids. Returns (bindless index, kind), kind being None with --descriptor-table plain. The probe is about 400 instructions, so it is one function in the module (%desc_lookup_fn) that every image instruction calls. Inlined at each use it was most of the code of texture-heavy shaders: 194 image instructions made over half of a 7 MB module.""" self.uses_tex = True tagged = self.descriptor_table != "plain" if self.desc_fn is None: params = [f"%dl_w{i}" for i in range(8)] saved, self.body = self.body, [] result = self.desc_probe(params) lines, self.body = self.body, saved ret = "%desc_hit" if tagged else "%uint" self.desc_fn = ([f"%desc_lookup_fn = OpFunction {ret} None %fn_desc_lookup"] + [f"{p} = OpFunctionParameter %uint" for p in params] + ["%dl_entry = OpLabel"] + lines + [f" OpReturnValue {result}", "OpFunctionEnd"]) r = self.tmp() self.emit(f"{r} = OpFunctionCall {'%desc_hit' if tagged else '%uint'} %desc_lookup_fn " + " ".join(words)) if tagged: idx, kind = self.tmp(), self.tmp() self.emit(f"{idx} = OpCompositeExtract %uint {r} 0") self.emit(f"{kind} = OpCompositeExtract %uint {r} 1") else: idx, kind = r, None return self.desc_uniform(idx, kind) if uniform else (idx, kind) def tsharp_index_word(self, words): """(index, kind, tagged) from the T#'s dword 6 as the layer writes it (TSHARP_INDEX): the bool `tagged` is whether the word carries the tag and dword 3 names an image (TYPE >= 8, bit 31); index and kind are 0 when it does not, index 0's fallback, which is what a T# that names no image reads. The words are SGPRs, so this is a handful of scalar operations and no memory access beyond the T# the shader loaded anyway.""" w3, w6 = words[3], words[TSHARP_INDEX_DWORD] tag, tag_ok, img, img_ok, ok = (self.tmp() for _ in range(5)) self.emit(f"{tag} = OpShiftRightLogical %uint {w6} {self.cu(28)}") self.emit(f"{tag_ok} = OpIEqual %bool {tag} {self.cu(TSHARP_INDEX_TAG)}") self.emit(f"{img} = OpShiftRightLogical %uint {w3} {self.cu(31)}") self.emit(f"{img_ok} = OpINotEqual %bool {img} {self.cu(0)}") self.emit(f"{ok} = OpLogicalAnd %bool {tag_ok} {img_ok}") raw, idx, sampled, storage, storage_hi, both, kind = (self.tmp() for _ in range(7)) self.emit(f"{raw} = OpBitwiseAnd %uint {w6} {self.cu(0xFFFF)}") self.emit(f"{idx} = OpSelect %uint {ok} {raw} {self.cu(0)}") self.emit(f"{sampled} = OpBitFieldUExtract %uint {w6} {self.cu(16)} {self.cu(7)}") self.emit(f"{storage} = OpBitFieldUExtract %uint {w6} {self.cu(23)} {self.cu(5)}") self.emit(f"{storage_hi} = OpShiftLeftLogical %uint {storage} {self.cu(DESC_STORAGE_BIT)}") self.emit(f"{both} = OpBitwiseOr %uint {sampled} {storage_hi}") self.emit(f"{kind} = OpSelect %uint {ok} {both} {self.cu(0)}") return idx, kind, ok def desc_uniform(self, idx, kind): """The index (and the kind, or None) made explicitly uniform, as the hash lookup's result always was.""" if self.emulate: return idx, kind if self.wave32_fragment: # Each 32-lane half of a wider subgroup is its own wave with its own SGPRs: broadcast from the half's # first running lane, as OpGroupNonUniformBroadcastFirst does for the whole subgroup below. first = self.wave32_first_running_lane() b = self.tmp() self.g_shuffle(b, idx, first) if kind is not None: k = self.tmp() self.g_shuffle(k, kind, first) kind = k return b, kind # The descriptor words are SGPRs, so the index is the same in every invocation of the subgroup; the # broadcast is an identity on every driver and makes that uniformity explicit to the compiler. Mesa ANV # (26.2.7, Alder Lake Xe-LP) segfaults compiling a sampler index straight from the probe loop when one # sampler serves both a float and integer image; the broadcast avoids it. The wave64 emulation keeps no # subgroup operation (x_round), so it is left out there. Track this separately from uses_subgroup: this # operation needs GroupNonUniform + GroupNonUniformBallot, but no Shuffle capability or lane input. b = self.tmp() self.emit(f"{b} = OpGroupNonUniformBroadcastFirst %uint {self.cu(3)} {idx}") self.uses_bcast_first = True if kind is not None: k = self.tmp() self.emit(f"{k} = OpGroupNonUniformBroadcastFirst %uint {self.cu(3)} {kind}") kind = k return b, kind def desc_hash(self, words): """Hash a T# or padded S# exactly as the runtime descriptor table does.""" h = self.cu(2166136261) for word in words: xor, product = self.tmp(), self.tmp() self.emit(f"{xor} = OpBitwiseXor %uint {h} {word}") self.emit(f"{product} = OpIMul %uint {xor} {self.cu(16777619)}") h = product if self.descriptor_hash == "fnv1a_fmix32": # MurmurHash3 fmix32, shared with plaaasma's runtime descriptor table. for shift, multiplier in ((16, 0x85ebca6b), (13, 0xc2b2ae35)): upper, folded, product = self.tmp(), self.tmp(), self.tmp() self.emit(f"{upper} = OpShiftRightLogical %uint {h} {self.cu(shift)}") self.emit(f"{folded} = OpBitwiseXor %uint {h} {upper}") self.emit(f"{product} = OpIMul %uint {folded} {self.cu(multiplier)}") h = product upper, folded = self.tmp(), self.tmp() self.emit(f"{upper} = OpShiftRightLogical %uint {h} {self.cu(16)}") self.emit(f"{folded} = OpBitwiseXor %uint {h} {upper}") h = folded return h def desc_probe(self, words): """Probe up to eight slots for the full descriptor key.""" tagged = self.descriptor_table != "plain" h = self.desc_hash(words) mp, mask = self.tmp(), self.tmp() self.emit(f"{mp} = OpAccessChain %_ptr_SB_uint %desc_map %c0 %c0") self.emit(f"{mask} = OpLoad %uint {mp}") # One slot per turn of a loop that stops at the first match, not PROBES copies of the comparison. A shader # compiler inlines this function at every use, and the unrolled copies were 95% of its work on a shader # with 330 lookups (117 s to compile with 8 slots unrolled, 14 s with one, 6 s with none). Break directly # to %dl_end on a hit with DontUnroll: overwriting %dl_k to fall out of a single-exit loop leaves %dl_idx # on the loop header's phi, which Mesa ANV 26.1.6 (Intel UHD 630, CFL GT2) miscompiles in ps_table_fetch # by hoisting the binding-table-index add above the loop (reading slot 0 / magenta before %dl_idx is set). kv, iv = "%dl_k", "%dl_idx" # slot number, and the result (0 until a slot matches) kvars = [f" {kv} = OpVariable %_ptr_Function_uint Function %c0", f" {iv} = OpVariable %_ptr_Function_uint Function %c0"] if tagged: kvars.append(" %dl_kind = OpVariable %_ptr_Function_uint Function %c0") self.body[0:0] = kvars self.emit("OpBranch %dl_head") self.body.append("%dl_head = OpLabel") self.emit("OpLoopMerge %dl_end %dl_cont DontUnroll") self.emit("OpBranch %dl_body") self.body.append("%dl_body = OpLabel") k, s, slot, base = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{k} = OpLoad %uint {kv}") self.emit(f"{s} = OpIAdd %uint {h} {k}") self.emit(f"{slot} = OpBitwiseAnd %uint {s} {mask}") self.emit(f"{base} = OpIMul %uint {slot} {self.cu(10)}") match = "%true" for j, w in enumerate(words): o, p, v, e, m2 = self.tmp(), self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{o} = OpIAdd %uint {base} {self.cu(1 + j)}") self.emit(f"{p} = OpAccessChain %_ptr_SB_uint %desc_map %c0 {o}") self.emit(f"{v} = OpLoad %uint {p}") self.emit(f"{e} = OpIEqual %bool {v} {w}") self.emit(f"{m2} = OpLogicalAnd %bool {match} {e}") match = m2 self.emit("OpSelectionMerge %dl_next None") self.emit(f"OpBranchConditional {match} %dl_hit %dl_next") self.body.append("%dl_hit = OpLabel") o, p, v = self.tmp(), self.tmp(), self.tmp() self.emit(f"{o} = OpIAdd %uint {base} {self.cu(9)}") self.emit(f"{p} = OpAccessChain %_ptr_SB_uint %desc_map %c0 {o}") self.emit(f"{v} = OpLoad %uint {p}") self.emit(f"OpStore {iv} {v}") if tagged: # The entry's last word: the arrays this index is bound in (the pad word a plain table leaves alone). ko, kp, kk = self.tmp(), self.tmp(), self.tmp() self.emit(f"{ko} = OpIAdd %uint {base} {self.cu(10)}") self.emit(f"{kp} = OpAccessChain %_ptr_SB_uint %desc_map %c0 {ko}") self.emit(f"{kk} = OpLoad %uint {kp}") self.emit(f"OpStore %dl_kind {kk}") self.emit("OpBranch %dl_end") # the first match breaks out of the probe loop directly self.body.append("%dl_next = OpLabel") self.emit("OpBranch %dl_cont") self.body.append("%dl_cont = OpLabel") k2, k3, more, r = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{k2} = OpLoad %uint {kv}") self.emit(f"{k3} = OpIAdd %uint {k2} {self.cu(1)}") self.emit(f"OpStore {kv} {k3}") self.emit(f"{more} = OpULessThan %bool {k3} {self.cu(self.PROBES)}") self.emit(f"OpBranchConditional {more} %dl_head %dl_end") self.body.append("%dl_end = OpLabel") self.emit(f"{r} = OpLoad %uint {iv}") if not tagged: return r hit, kind = self.tmp(), self.tmp() self.emit(f"{kind} = OpLoad %uint %dl_kind") self.emit(f"{hit} = OpCompositeConstruct %desc_hit {r} {kind}") return hit def desc_cache_ok(self): """True when the next instruction is emitted at the top level of the basic block, outside any selection or loop construct an earlier instruction opened and has not yet reached the merge label of. An id defined there dominates everything after it in the block. One defined inside a construct would not dominate the code after the merge, so lookups made there are not cached. The body is append-only within a block, so this only reads the lines added since the last call.""" body, seen, open_ = self._scan if body is not self.body: body, seen, open_ = self.body, 0, [] for line in body[seen:]: s = line.strip() if s.startswith(("OpSelectionMerge ", "OpLoopMerge ")): open_.append(s.split()[1]) elif s.endswith("= OpLabel"): name = s.split()[0] if name in open_: del open_[open_.index(name):] self._scan = (body, len(body), open_) return not open_ def store_gather_taps(self, first_vgpr: int, taps: list[str], d16: bool) -> None: """Write four taps in gather order, two per destination VGPR for d16.""" if d16: words = [self.pack_f16_pair_int(taps[0], taps[1]), self.pack_f16_pair_int(taps[2], taps[3])] else: words = [self.tou(tap) for tap in taps] for i, word in enumerate(words): self.dst({"k": "vgpr", "r": first_vgpr + i, "n": 1}, word) GATHER4_LOD_OPS = ( "image_gather4_c_l", "image_gather4_c_l_o", "image_gather4_cl", "image_gather4_cl_o", "image_gather4_c_cl", "image_gather4_c_cl_o", "image_gather4_b", "image_gather4_b_o", "image_gather4_b_cl", "image_gather4_b_cl_o", "image_gather4_c_b", "image_gather4_c_b_o", "image_gather4_c_b_cl", "image_gather4_c_b_cl_o", ) # SQ_IMG_SAMP_WORD0 address modes (Mesa src/amd/registers/gfx10-rsrc.json: CLAMP_X = bits [2:0], CLAMP_Y = [5:3]; # values: SQ_TEX_* in Mesa's gfx6.json, as RADV's radv_tex_wrap maps VkSamplerAddressMode onto them): 0 wrap, 1 mirror, 2 clamp last texel, 3 mirror once last texel, # 4 clamp half border, 5 mirror once half border, 6 clamp border, 7 mirror once border. def gather_addr_modes(self, s_op, unorm: bool = False): """(x, y) address modes of an S# for the gather emulation, each either a Python int (the S# word 0 is a literal an s_mov_b32 wrote earlier in this basic block) or the id of a uint computed from the S# at run time. Modes 6 (clamp border) and 7 (mirror once border) map a tap outside the image to the border colour (see gather_border); a literal S# with a half-border mode (4, 5), or that sets FORCE_UNNORMALIZED, is Unsupported: the four fetches can't reproduce it. A run-time S# can't be judged at translation time, so modes 4 and 5 are treated as clamp-to-edge there, and FORCE_UNNORMALIZED (bit 15) is not applied (the two remaining approximations, with gather_border_one's table colour at run time).""" if s_op["k"] != "sgpr" or s_op.get("n", 1) < 4: raise Unsupported("descriptor operand") lit = self.sgpr_imm.get(s_op["r"]) if lit is not None: if not unorm and (lit & 0x8000): raise Unsupported("image_gather4_l with FORCE_UNNORMALIZED") m = (lit & 7, lit >> 3 & 7) for mode in m: if mode in (4, 5): raise Unsupported(f"image_gather4_l address mode {mode} (half border)") return m w0 = self.load_reg("sgpr", s_op["r"]) out = [] for k in range(2): m = self.tmp() self.emit(f"{m} = OpBitFieldUExtract %uint {w0} {self.cu(3 * k)} {self.cu(3)}") out.append(m) return tuple(out) def gather_border_one(self, s_op, ch: int): """Whether channel ch of the S#'s border colour is 1 (else 0), for a tap that a border mode (6, 7) puts outside the image: a Python bool for a literal S# word 3, else a bool id. BORDER_COLOR_TYPE is word 3 [31:30] (Mesa gfx10-rsrc.json SQ_IMG_SAMP_WORD3; SQ_TEX_BORDER_COLOR_* in gfx6.json): 0 transparent black (0,0,0,0), 1 opaque black (0,0,0,1), 2 opaque white (1,1,1,1), 3 a colour from the border-colour table (BORDER_COLOR_PTR), which the translator can't read: Unsupported on a literal S#, transparent black at run time.""" lit = self.sgpr_imm.get(s_op["r"] + 3) if lit is not None: kind = lit >> 30 & 3 if kind == 3: raise Unsupported("image_gather4_l border colour from the table (BORDER_COLOR_TYPE 3)") return kind == 2 or (kind == 1 and ch == 3) kind, white = self.tmp(), self.tmp() self.emit(f"{kind} = OpShiftRightLogical %uint {self.load_reg('sgpr', s_op['r'] + 3)} {self.cu(30)}") self.emit(f"{white} = OpIEqual %bool {kind} {self.cu(2)}") if ch != 3: return white black, one = self.tmp(), self.tmp() self.emit(f"{black} = OpIEqual %bool {kind} {self.cu(1)}") self.emit(f"{one} = OpLogicalOr %bool {white} {black}") return one def ssharp_lod_bias(self, word_reg: int): """--explicit-lod-bias: the S#'s LOD_BIAS (word 2 [13:0], signed 5.8 fixed point, -32..31 in steps of 1/256) as a float id, or None when a literal S# has a zero bias.""" literal = self.sgpr_imm.get(word_reg) if literal is not None: bias = ((literal & 0x3fff) ^ 0x2000) - 0x2000 return self.fconst(bias / 256.0) if bias else None word = self.load_reg("sgpr", word_reg) raw, signed, value, scaled = (self.tmp() for _ in range(4)) self.emit(f"{raw} = OpBitFieldSExtract %uint {word} {self.cu(0)} {self.cu(14)}") self.emit(f"{signed} = OpBitcast %int {raw}") self.emit(f"{value} = OpConvertSToF %float {signed}") self.emit(f"{scaled} = OpFMul %float {value} {self.fconst(1.0 / 256.0)}") return scaled def add_ssharp_lod_bias(self, lod: str, word_reg: int) -> str: """--explicit-lod-bias: lod + the S#'s LOD_BIAS.""" b = self.ssharp_lod_bias(word_reg) if b is None: return lod out = self.tmp() self.emit(f"{out} = OpFAdd %float {lod} {b}") return out def scale_grads_by_ssharp_bias(self, grads, width: int, word_reg: int): """--explicit-lod-bias: (dx, dy) * 2^LOD_BIAS, which adds the bias to the LOD the derivatives give.""" b = self.ssharp_lod_bias(word_reg) if b is None: return grads k = self.tmp() self.emit(f"{k} = OpExtInst %float %glsl Exp2 {b}") out = [] for g in grads: t = self.tmp() if width == 1: self.emit(f"{t} = OpFMul %float {g} {k}") else: self.emit(f"{t} = OpVectorTimesScalar %v{width}float {g} {k}") out.append(t) return tuple(out) def clamp_gather_lod(self, lod: str, word_reg: int) -> str: """Clamp to S# word 1's unsigned 4.8 MIN_LOD and MAX_LOD before choosing the fetch mip. A literal S# uses FClamp. A run-time S# clamps with FMax then FMin: LLPC 26.10.1 (32.0.32015.7029) miscompiles the run-time FClamp here and leaves the gather at mip 0 when MIN_LOD should raise it (#1032). The two-instruction form is the FClamp result for min <= max and passes on that driver.""" literal = self.sgpr_imm.get(word_reg) if literal is not None: limits = [self.fconst(((literal >> bit) & 0xfff) / 256.0) for bit in (0, 12)] clamped = self.tmp() self.emit(f"{clamped} = OpExtInst %float %glsl FClamp {lod} {limits[0]} {limits[1]}") return clamped word = self.load_reg("sgpr", word_reg) scale = self.fconst(1.0 / 256.0) limits = [] for bit in (0, 12): raw, value, scaled = self.tmp(), self.tmp(), self.tmp() self.emit(f"{raw} = OpBitFieldUExtract %uint {word} {self.cu(bit)} {self.cu(12)}") self.emit(f"{value} = OpConvertUToF %float {raw}") self.emit(f"{scaled} = OpFMul %float {value} {scale}") limits.append(scaled) lower = self.tmp() self.emit(f"{lower} = OpExtInst %float %glsl FMax {lod} {limits[0]}") clamped = self.tmp() self.emit(f"{clamped} = OpExtInst %float %glsl FMin {lower} {limits[1]}") return clamped def gather_addr(self, c, n, mode): """Texel coordinate c (int id) after the address mode (int, or a uint id) for an axis of n texels (int id): wrap: c mod n; mirror: c mod 2n, reflected in the upper half; mirror once: the negative side reflected (-1 - c), then clamped; otherwise (clamp, and half-border modes at run time) clamped to [0, n-1]. As in the Vulkan address-mode definitions (and RADV's radv_tex_wrap mapping of them onto SQ_TEX_*). A literal mode emits only the code it needs; a run-time one emits all four and selects. Returns (coordinate, outside): outside is a bool id that is true when a border mode (6 clamp border, 7 mirror once border) puts the tap outside [0, n-1] before the clamp, so it takes the border colour, or None when the literal mode has no border. The modulo is OpSRem plus the period when the remainder is negative, not OpSMod: AMD's Windows driver (24.10.24, RDNA2 iGPU) gave OpSMod of a negative coordinate the dividend's sign, so ps_gather_wrap's wrap and mirror cases fetched outside the image and read zeros. The two are the same for a positive period.""" zero, one = self.as_int(self.cu(0)), self.as_int(self.cu(1)) static = isinstance(mode, int) base = {6: 2, 7: 3}.get(mode, mode if mode <= 3 else 2) if static else None want = {base} if static else {0, 1, 2, 3} nm1 = self.tmp() self.emit(f"{nm1} = OpISub %int {n} {one}") pre = {} # the coordinate a border test sees: before the clamp def modulo(x, m): """x mod m for m > 0, in [0, m).""" r, neg, up, out = (self.tmp() for _ in range(4)) self.emit(f"{r} = OpSRem %int {x} {m}") self.emit(f"{neg} = OpSLessThan %bool {r} {zero}") self.emit(f"{up} = OpIAdd %int {r} {m}") self.emit(f"{out} = OpSelect %int {neg} {up} {r}") return out res = {} if 2 in want: res[2] = self.tmp() self.emit(f"{res[2]} = OpExtInst %int %glsl SClamp {c} {zero} {nm1}") if 0 in want: res[0] = modulo(c, n) if 1 in want: n2, hi, rf, lt, res[1] = (self.tmp() for _ in range(5)) self.emit(f"{n2} = OpIAdd %int {n} {n}") p = modulo(c, n2) self.emit(f"{hi} = OpISub %int {n2} {one}") self.emit(f"{rf} = OpISub %int {hi} {p}") self.emit(f"{lt} = OpSLessThan %bool {p} {n}") self.emit(f"{res[1]} = OpSelect %int {lt} {p} {rf}") if 3 in want: neg, refl, ge, mo, res[3] = (self.tmp() for _ in range(5)) self.emit(f"{neg} = OpISub %int {zero} {c}") self.emit(f"{refl} = OpISub %int {neg} {one}") self.emit(f"{ge} = OpSGreaterThanEqual %bool {c} {zero}") self.emit(f"{mo} = OpSelect %int {ge} {c} {refl}") self.emit(f"{res[3]} = OpExtInst %int %glsl SClamp {mo} {zero} {nm1}") pre[3] = mo pre[2] = c def outside(v): lo, hi, out = self.tmp(), self.tmp(), self.tmp() self.emit(f"{lo} = OpSLessThan %bool {v} {zero}") self.emit(f"{hi} = OpSGreaterThan %bool {v} {nm1}") self.emit(f"{out} = OpLogicalOr %bool {lo} {hi}") return out if static: return res[base], (outside(pre[base]) if mode in (6, 7) else None) r = res[2] for val in (3, 1, 0): eq, nr = self.tmp(), self.tmp() self.emit(f"{eq} = OpIEqual %bool {mode} {self.cu(val)}") self.emit(f"{nr} = OpSelect %int {eq} {res[val]} {r}") r = nr # Mode 7 is mirror once in range; modes 6 and 7 send a tap outside the image to the border colour. eq7, r7 = self.tmp(), self.tmp() self.emit(f"{eq7} = OpIEqual %bool {mode} {self.cu(7)}") self.emit(f"{r7} = OpSelect %int {eq7} {res[3]} {r}") is6, b6, b7, out = (self.tmp() for _ in range(4)) o6, o7 = outside(pre[2]), outside(pre[3]) self.emit(f"{is6} = OpIEqual %bool {mode} {self.cu(6)}") self.emit(f"{b6} = OpLogicalAnd %bool {is6} {o6}") self.emit(f"{b7} = OpLogicalAnd %bool {eq7} {o7}") self.emit(f"{out} = OpLogicalOr %bool {b6} {b7}") return r7, out # SQ_IMG_SAMP_WORD0 DEPTH_COMPARE_FUNC [14:12] (SQ_TEX_DEPTH_COMPARE, same numbering as VkCompareOp): # 0 NEVER, 1 LESS, 2 EQUAL, 3 LESS_EQUAL, 4 GREATER, 5 NOT_EQUAL, 6 GREATER_EQUAL, 7 ALWAYS. _DEPTH_CMP_OPS = { 1: "OpFOrdLessThan", 2: "OpFOrdEqual", 3: "OpFOrdLessThanEqual", 4: "OpFOrdGreaterThan", 5: "OpFUnordNotEqual", 6: "OpFOrdGreaterThanEqual", } def gather_depth_compare_prep(self, s_op): """Decode S# word 0 DEPTH_COMPARE_FUNC [14:12] once per depth-compare gather4. Returns ('const', func) for a literal S#, or ('dyn', b0, b1, b2, b02) for a run-time S#.""" lit = self.sgpr_imm.get(s_op["r"]) if s_op["k"] == "sgpr" else None if lit is not None: return ("const", (lit >> 12) & 7) w0 = self.sgpr_word(s_op, 0) fn = self.tmp() self.emit(f"{fn} = OpBitFieldUExtract %uint {w0} {self.cu(12)} {self.cu(3)}") bits = [] for mask in (1, 2, 4): bu, bb = self.tmp(), self.tmp() self.emit(f"{bu} = OpBitwiseAnd %uint {fn} {self.cu(mask)}") self.emit(f"{bb} = OpINotEqual %bool {bu} {self.cu(0)}") bits.append(bb) b02 = self.tmp() self.emit(f"{b02} = OpLogicalAnd %bool {bits[0]} {bits[2]}") return ("dyn", bits[0], bits[1], bits[2], b02) def gather_depth_compare(self, cmp_state, ref: str, texel: str) -> str: """Compare ref texel and return %float (%f1 if pass, else %f0).""" if cmp_state[0] == "const": func = cmp_state[1] if func == 0: return "%f0" if func == 7: return "%f1" c, res = self.tmp(), self.tmp() self.emit(f"{c} = {self._DEPTH_CMP_OPS[func]} %bool {ref} {texel}") self.emit(f"{res} = OpSelect %float {c} %f1 %f0") return res _, b0, b1, b2, b02 = cmp_state lt, eq, gt = self.tmp(), self.tmp(), self.tmp() self.emit(f"{lt} = OpFOrdLessThan %bool {ref} {texel}") self.emit(f"{eq} = OpFOrdEqual %bool {ref} {texel}") self.emit(f"{gt} = OpFOrdGreaterThan %bool {ref} {texel}") lt_m, eq_m, gt_m = self.tmp(), self.tmp(), self.tmp() self.emit(f"{lt_m} = OpLogicalAnd %bool {b0} {lt}") self.emit(f"{eq_m} = OpLogicalAnd %bool {b1} {eq}") self.emit(f"{gt_m} = OpLogicalAnd %bool {b2} {gt}") ord1, any_ord, unord, unord_m = (self.tmp() for _ in range(4)) self.emit(f"{ord1} = OpLogicalOr %bool {lt} {eq}") self.emit(f"{any_ord} = OpLogicalOr %bool {ord1} {gt}") self.emit(f"{unord} = OpLogicalNot %bool {any_ord}") self.emit(f"{unord_m} = OpLogicalAnd %bool {b02} {unord}") m1, m2, passed, res = (self.tmp() for _ in range(4)) self.emit(f"{m1} = OpLogicalOr %bool {lt_m} {eq_m}") self.emit(f"{m2} = OpLogicalOr %bool {gt_m} {unord_m}") self.emit(f"{passed} = OpLogicalOr %bool {m1} {m2}") self.emit(f"{res} = OpSelect %float {passed} %f1 %f0") return res def emit_gather4_c_lz(self, op, mods, dim, si, coords, f, ncoord, is3d, dmask, vdata, d16): """image_gather4_c_lz[_o]: the depth-compare gather at the base level, as OpImageDrefGather (docs/design.md, "image_gather4_c_lz"). Address order after the optional offset dword: z-compare, s, t, [slice] (GFX10 MIMG: offset, bias, zcompare, derivatives, coordinates, LOD; there is no LOD here). The four results are the four comparisons in gather order, the compare function comes from the sampler as for image_sample_c_lz. Sources agree (docs/design.md): LLVM's AMDGPUSampleVariant address order and llvm-mc's dword counts; Mesa ACO's visit_tex selects exactly these two opcodes for a shadow tg4 at level zero, pushes offset, compare, coordinates, keeps the compare whole under a16, and sets dmask 1 for every shadow gather (hence the dmask refusal).""" if is3d or dim not in ("dim:SQ_RSRC_IMG_2D", "dim:SQ_RSRC_IMG_2D_ARRAY", "dim:SQ_RSRC_IMG_CUBE"): raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1]) if dmask != 1: # A Dref gather compares the depth channel only; another component mask would need the view's swizzle. raise Unsupported(op + " dmask other than 0x1") if any(m not in (dim, "dmask:0x1", "dmask:1", "a16", "d16") for m in mods): raise Unsupported(op + " modifier (only dim, dmask:0x1, a16 and d16 are translated)") offset = "" if op.endswith("_o"): # first address dword: signed 6-bit texel offsets x [5:0], y [13:8], as for image_gather4_lz_o parts = [] for k in range(2): u, i = self.tmp(), self.tmp() self.emit(f"{u} = OpBitFieldSExtract %uint {coords[0]} {self.cu(8 * k)} {self.cu(6)}") self.emit(f"{i} = OpBitcast %int {u}") parts.append(i) goff = self.tmp() self.emit(f"{goff} = OpCompositeConstruct %v2int {parts[0]} {parts[1]}") f = f[1:] offset = f" Offset {goff}" self.uses_img_offset = True if len(f) < 1 + ncoord: raise Unsupported(op + " coords") ref, f = f[0], f[1:] if dim == "dim:SQ_RSRC_IMG_CUBE": f = self.cube_coords(f) uv = self.tmp() if ncoord == 3: # 2D array (or cube as a 6-layer array): the layer is the third coordinate self.emit(f"{uv} = OpCompositeConstruct %v3float {f[0]} {f[1]} {f[2]}") else: self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}") res = self.tmp() self.emit(f"{res} = OpImageDrefGather %v4float {si} {uv} {ref}{offset}") taps = [] for c in range(4): tap = self.tmp() self.emit(f"{tap} = OpCompositeExtract %float {res} {c}") taps.append(tap) self.store_gather_taps(vdata["r"], taps, d16) def emit_gather4_lod(self, op, a, mods, dim, img, img_idx, si, coords, f, ncoord, is3d, dmask, vdata, a16, d16): """Translate image_gather4_{c_l,cl,c_cl,b,b_cl,c_b,c_b_cl}[_o] via 2x2 OpImageFetch footprint. Address order: [offset (_o)], [bias (_b)], [z_compare (_c)], s, t, [slice (2D_ARRAY)], [lod (_l) | clamp (_cl)].""" kind = op[len("image_gather4"):] goff = None if kind.endswith("_o"): if a16 and ("tfe" in mods or "lwe" in mods): raise Unsupported(op + " a16 status") parts = [] for k in range(2): u, i = self.tmp(), self.tmp() self.emit(f"{u} = OpBitFieldSExtract %uint {coords[0]} {self.cu(8 * k)} {self.cu(6)}") self.emit(f"{i} = OpBitcast %int {u}") parts.append(i) goff = self.tmp() self.emit(f"{goff} = OpCompositeConstruct %v2int {parts[0]} {parts[1]}") f = f[1:] kind = kind[:-2] has_clamp = kind.endswith("_cl") if has_clamp: kind = kind[:-3] has_l = kind.endswith("_l") if has_l: kind = kind[:-2] has_b = kind.endswith("_b") if has_b: kind = kind[:-2] has_c = kind == "_c" if not has_c and kind != "": raise Unsupported(op) if bin(dmask).count("1") != 1 or dim not in ("dim:SQ_RSRC_IMG_2D", "dim:SQ_RSRC_IMG_2D_ARRAY") or is3d: raise Unsupported(op + " form") if has_b and self.stage != "ps": raise Unsupported(op) bias = None if has_b: if not f: raise Unsupported(op + " coords") bias, f = f[0], f[1:] ref = None if has_c: if not f: raise Unsupported(op + " coords") ref, f = f[0], f[1:] need = ncoord + (1 if (has_l or has_clamp) else 0) if len(f) < need: raise Unsupported(op + " coords") raw_lod_arg = f[ncoord] if has_l else None minlod = f[ncoord] if has_clamp else None unorm = "unorm" in mods modes = self.gather_addr_modes(a[3], unorm=unorm) self.uses_query = True self.uses_fhalf = True ch = 0 if has_c else (dmask.bit_length() - 1) uvf = self.tmp() self.emit(f"{uvf} = OpCompositeConstruct %v2float {f[0]} {f[1]}") qtype = "%v3int" if ncoord == 3 else "%v2int" if has_l: raw_lod = raw_lod_arg else: if self.stage == "ps": uv_q = uvf if unorm: sz0 = self.tmp() self.emit(f"{sz0} = OpImageQuerySizeLod {qtype} {img} {self.as_int(self.cu(0))}") if ncoord == 3: sz0_2 = self.tmp() self.emit(f"{sz0_2} = OpVectorShuffle %v2int {sz0} {sz0} 0 1") sz0 = sz0_2 sz0f, uv_q = self.tmp(), self.tmp() self.emit(f"{sz0f} = OpConvertSToF %v2float {sz0}") self.emit(f"{uv_q} = OpFDiv %v2float {uvf} {sz0f}") q, qy = self.tmp(), self.tmp() self.emit(f"{q} = OpImageQueryLod %v2float {si} {uv_q}") self.emit(f"{qy} = OpCompositeExtract %float {q} 1") raw_lod = qy else: raw_lod = "%f0" if bias is not None: lb = self.tmp() self.emit(f"{lb} = OpFAdd %float {raw_lod} {bias}") raw_lod = lb if minlod is not None: lc = self.tmp() self.emit(f"{lc} = OpExtInst %float %glsl FMax {raw_lod} {minlod}") raw_lod = lc lv, lvm, mi, mc, mz = (self.tmp() for _ in range(5)) self.emit(f"{lv} = OpImageQueryLevels %int {img}") self.emit(f"{lvm} = OpISub %int {lv} {self.as_int(self.cu(1))}") lod = self.clamp_gather_lod(raw_lod, a[3]["r"] + 1) # Share #4321's RDNA2 8-fraction-bit LOD rounding so ordinary and depth-compare gathers agree at # mip boundaries such as 0x3eff0000 (127.5/256) and 0x3eff0001: mip = (RoundEven(lod * 256) + 128) >> 8. sc, q, qi, b = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{sc} = OpFMul %float {lod} {self.fconst(256.0)}") self.emit(f"{q} = OpExtInst %float %glsl RoundEven {sc}") self.emit(f"{qi} = OpConvertFToS %int {q}") self.emit(f"{b} = OpIAdd %int {qi} {self.as_int(self.cu(128))}") self.emit(f"{mi} = OpShiftRightArithmetic %int {b} {self.cu(8)}") self.emit(f"{mz} = OpExtInst %int %glsl SMax {mi} {self.as_int(self.cu(0))}") self.emit(f"{mc} = OpExtInst %int %glsl SMin {mz} {lvm}") sz = self.tmp() self.emit(f"{sz} = OpImageQuerySizeLod {qtype} {img} {mc}") layer = None if ncoord == 3: sz2, szl, lmax, rlayer, ilayer, layer = (self.tmp() for _ in range(6)) self.emit(f"{sz2} = OpVectorShuffle %v2int {sz} {sz} 0 1") self.emit(f"{szl} = OpCompositeExtract %int {sz} 2") self.emit(f"{lmax} = OpISub %int {szl} {self.as_int(self.cu(1))}") self.emit(f"{rlayer} = OpExtInst %float %glsl RoundEven {f[2]}") self.emit(f"{ilayer} = OpConvertFToS %int {rlayer}") self.emit(f"{layer} = OpExtInst %int %glsl SClamp {ilayer} {self.as_int(self.cu(0))} {lmax}") else: sz2 = sz if unorm: st = uvf else: szf, st = self.tmp(), self.tmp() self.emit(f"{szf} = OpConvertSToF %v2float {sz2}") self.emit(f"{st} = OpFMul %v2float {uvf} {szf}") half, sub, flo, i0, one2, i1 = (self.tmp() for _ in range(6)) self.emit(f"{half} = OpCompositeConstruct %v2float %fhalf_g %fhalf_g") self.emit(f"{sub} = OpFSub %v2float {st} {half}") self.emit(f"{flo} = OpExtInst %v2float %glsl Floor {sub}") self.emit(f"{i0} = OpConvertFToS %v2int {flo}") if goff is not None: i0o = self.tmp() self.emit(f"{i0o} = OpIAdd %v2int {i0} {goff}") i0 = i0o c1 = self.as_int(self.cu(1)) self.emit(f"{one2} = OpCompositeConstruct %v2int {c1} {c1}") self.emit(f"{i1} = OpIAdd %v2int {i0} {one2}") x0, y0, x1, y1, szx, szy = (self.tmp() for _ in range(6)) self.emit(f"{x0} = OpCompositeExtract %int {i0} 0") self.emit(f"{y0} = OpCompositeExtract %int {i0} 1") self.emit(f"{x1} = OpCompositeExtract %int {i1} 0") self.emit(f"{y1} = OpCompositeExtract %int {i1} 1") self.emit(f"{szx} = OpCompositeExtract %int {sz2} 0") self.emit(f"{szy} = OpCompositeExtract %int {sz2} 1") ax = [self.gather_addr(c, szx, modes[0]) for c in (x0, x1)] ay = [self.gather_addr(c, szy, modes[1]) for c in (y0, y1)] texels, outs = [], [] for (xx, ox), (yy, oy) in ((ax[0], ay[1]), (ax[1], ay[1]), (ax[1], ay[0]), (ax[0], ay[0])): cc = self.tmp() if ncoord == 3: self.emit(f"{cc} = OpCompositeConstruct %v3int {xx} {yy} {layer}") else: self.emit(f"{cc} = OpCompositeConstruct %v2int {xx} {yy}") texels.append(cc) if ox is not None and oy is not None: both = self.tmp() self.emit(f"{both} = OpLogicalOr %bool {ox} {oy}") outs.append(both) else: outs.append(ox if ox is not None else oy) border_one = self.gather_border_one(a[3], ch) if any(o is not None for o in outs) else None if has_c: cmp_state = self.gather_depth_compare_prep(a[3]) if border_one is not None: if isinstance(border_one, bool): border_v = "%f1" if border_one else "%f0" else: border_v = self.tmp() self.emit(f"{border_v} = OpSelect %float {border_one} %f1 %f0") taps = [] for cc, out in zip(texels, outs): tx, comp = self.tmp(), self.tmp() self.emit(f"{tx} = OpImageFetch %v4float {img} {cc} Lod {mc}") self.emit(f"{comp} = OpCompositeExtract %float {tx} 0") if out is not None: sel = self.tmp() self.emit(f"{sel} = OpSelect %float {out} {border_v} {comp}") comp = sel taps.append(self.gather_depth_compare(cmp_state, ref, comp)) self.store_gather_taps(vdata["r"], taps, d16) return def gather_mip(image: str, cls: int, ty: str) -> str: scalar = ("%float", "%uint", "%int")[cls] if border_one is not None: zero_v, one_v = (self.fconst(0.0), self.fconst(1.0)) if cls == 0 else \ (self.cu(0), self.cu(1)) if cls == 1 else (self.as_int(self.cu(0)), self.as_int(self.cu(1))) if isinstance(border_one, bool): border_v = one_v if border_one else zero_v else: border_v = self.tmp() self.emit(f"{border_v} = OpSelect {scalar} {border_one} {one_v} {zero_v}") taps = [] for cc, out in zip(texels, outs): tx, comp = self.tmp(), self.tmp() self.emit(f"{tx} = OpImageFetch {ty} {image} {cc} Lod {mc}") self.emit(f"{comp} = OpCompositeExtract {scalar} {tx} {ch}") if out is not None: sel = self.tmp() self.emit(f"{sel} = OpSelect {scalar} {out} {border_v} {comp}") comp = sel taps.append(comp) result = self.tmp() self.emit(f"{result} = OpCompositeConstruct {ty} {' '.join(taps)}") return result self.image_read_typed(dim, self.sgpr_word(a[2], 1), img, img_idx, 0xf, vdata, d16, gather_mip) def tsharp_index_sgpr(self, a): """(index, kind) of the current instruction's T# operand `a` when the dataflow showed its dword 6 is a heap slot's (Gen.tsharp_from_heap, tools/descriptor_sources.py), else None.""" ins = self.cur_ins if ins is None or not self.tsharp_from_heap.get(id(ins)): return None regs = descriptor_sources.tsharp_operand(ins) if regs is None or tuple(regs) != self.tsharp_regs(a): return None self.uses_tex = True # set 0's image arrays, which the index reads, as desc_lookup declares them idx, kind, _ = self.tsharp_index_word(self.sgpr_words(a, 8)) self.tsharp_index_reads += 1 return self.desc_uniform(idx, kind) def literal_sampler_lookup(self, a, slot): """Sampler bindless index for compile-time literal S# `slot`: when OpSpecConstant %lit_smp_ is specialized (!= 0xFFFFFFFF), use it directly without probing %desc_map; when unspecialized (0xFFFFFFFF), fall back to the existing bindless hash-table probe.""" self.uses_tex = True self.uses_lit_sampler_spec = True spec_id = f"%lit_smp_{slot}" use_spec = self.tmp() self.emit(f"{use_spec} = OpINotEqual %bool {spec_id} {self.cu(0xFFFFFFFF)}") pre = self.current_label_placeholder() lbl_probe, lbl_end = self.tmp() + "_sprobe", self.tmp() + "_send" self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {use_spec} {lbl_end} {lbl_probe}") self.emit(f"{lbl_probe} = OpLabel") words = self.sgpr_words(a, 4) + [self.cu(0xFFFFFFFF)] * 4 probe_idx, _ = self.desc_lookup(words, uniform=False) probe_exit = self.current_label_placeholder() self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") out = self.tmp() self.emit(f"{out} = OpPhi %uint {spec_id} {pre} {probe_idx} {probe_exit}") return self.desc_uniform(out, None) def _literal_sampler_slot(self, a): if not self.literal_sampler_index: return None words = self.literal_sampler_sites.get(id(self.cur_ins)) if self.cur_ins is not None else None if words is None and a["k"] == "sgpr" and a.get("n", 1) >= 4: if all((a["r"] + i) in self.sgpr_imm for i in range(4)): words = tuple(self.sgpr_imm[a["r"] + i] & 0xFFFFFFFF for i in range(4)) return self.literal_sampler_index.get(words) if words is not None else None def desc_lookup_sgpr(self, a, n): """desc_lookup for an SGPR descriptor range (n=8: T#, n=4: S#), cached for the rest of the basic block. The cache holds the ids of the call's result per (first SGPR, n): the index and, with --descriptor-table tagged, the kind. It is dropped by store_reg when any SGPR of the range is written (all writes to the %sgpr array go through store_reg, including the 64-bit ones, which are two calls, s_load results, v_readlane/v_readfirstlane results and the spare slots lane masks are parked in) and cleared when a basic block starts. Only lookups made at the block's top level are remembered, see desc_cache_ok. Returns (bindless index, kind), kind being None with --descriptor-table plain. A T# (n=8) whose dword 6 the dataflow traced to a heap slot takes its index from that word alone (tsharp_index_sgpr). Any other T# is looked up, and the dword-6 index wins where the word carries it: such a T# may still come from a heap the layer writes, along a path the dataflow did not follow, and there its words are not the key the table holds (the key is the descriptor as the title wrote it).""" if n == 8: direct = self.tsharp_index_sgpr(a) if direct is not None: return direct if a["k"] == "slist" and len(a["r"]) >= n: if n == 4: slot = self._literal_sampler_slot(a) if slot is not None: return self.literal_sampler_lookup(a, slot) words = self.sgpr_words(a, n) if n < 8: words = words + [self.cu(0xFFFFFFFF)] * (8 - n) return self.desc_lookup(words) if n < 8 else self.tsharp_lookup(words) if a["k"] != "sgpr" or a.get("n", 1) < n: raise Unsupported("descriptor operand") key = (a["r"], n) hit = self.desc_cache.get(key) if hit is not None: return hit top = self.desc_cache_ok() if n == 4: slot = self._literal_sampler_slot(a) if slot is not None: idx = self.literal_sampler_lookup(a, slot) if top: self.desc_cache[key] = idx return idx words = self.sgpr_words(a, n) if n < 8: words = words + [self.cu(0xFFFFFFFF)] * (8 - n) idx = self.desc_lookup(words) if n < 8 else self.tsharp_lookup(words) if top: self.desc_cache[key] = idx return idx def tsharp_lookup(self, words): """A T# of unknown source: its dword-6 index where the word carries one, else the hash table's answer for its words. The lookup sits in the branch taken only without the word: `ok` comes from SGPRs, so the branch is uniform, and a T# from a heap the layer writes, along a path the dataflow did not follow, costs no probe.""" self.tsharp_lookups += 1 direct, direct_kind, ok = self.tsharp_index_word(words) pre = self.current_label_placeholder() probe, end = self.tmp() + "_probe", self.tmp() + "_tsharp" self.emit(f"OpSelectionMerge {end} None") self.emit(f"OpBranchConditional {ok} {end} {probe}") self.emit(f"{probe} = OpLabel") idx, kind = self.desc_lookup(words, uniform=False) self.emit(f"OpBranch {end}") self.emit(f"{end} = OpLabel") out = self.tmp() self.emit(f"{out} = OpPhi %uint {direct} {pre} {idx} {probe}") out_kind = None if kind is not None: out_kind = self.tmp() self.emit(f"{out_kind} = OpPhi %uint {direct_kind} {pre} {kind} {probe}") return self.desc_uniform(out, out_kind) # The dimension of an instruction's image array, indexed by STORE_DIMS' index (0 2D, 1 2D array, 2 3D, 3 1D). # A cube instruction reads the 2D-array binding: a cube is six layers of a 2D array. DIM_TAGS = {"dim:SQ_RSRC_IMG_2D": 0, "dim:SQ_RSRC_IMG_2D_ARRAY": 1, "dim:SQ_RSRC_IMG_CUBE": 1, "dim:SQ_RSRC_IMG_3D": 2, "dim:SQ_RSRC_IMG_1D": 3, "dim:SQ_RSRC_IMG_1D_ARRAY": 4} def desc_array_bit(self, kind, dim, base): """A bool id: is bit `base + dim` of the descriptor's kind set (the index is bound in that array)?""" bit = self.tmp() self.emit(f"{bit} = OpBitFieldUExtract %uint {kind} {self.cu(base + self.DIM_TAGS[dim])} {self.cu(1)}") out = self.tmp() self.emit(f"{out} = OpINotEqual %bool {bit} {self.cu(0)}") return out def desc_sampled_index(self, idx, kind, dim): """The bindless index for the sampled array of `dim`: the lookup's index when the entry says it is bound there, else 0 (that array's fallback, a 1x1 image of zeros). With --descriptor-table plain nothing is emitted and the index is used as before.""" if kind is None: return idx ok = self.desc_array_bit(kind, dim, DESC_SAMPLED_BIT) out = self.tmp() self.emit(f"{out} = OpSelect %uint {ok} {idx} {self.cu(0)}") return out def desc_storage_index(self, idx, kind, dim): """The bindless index for the storage array of `dim`, or 0 (its fallback, where stores land and are dropped) when the entry says the index is not bound in it: an image whose T# is of another dimension, or one with a sampled view only.""" if kind is None: return idx ok = self.desc_array_bit(kind, dim, DESC_STORAGE_BIT) out = self.tmp() self.emit(f"{out} = OpSelect %uint {ok} {idx} {self.cu(0)}") return out def sgpr_word(self, a, i): if a["k"] == "sgpr": return self.load_reg("sgpr", a["r"] + i) if a["k"] == "slist": slot = a["r"][i] if isinstance(slot, int): return self.load_reg("sgpr", slot) t = self.tmp() self.emit(f"{t} = OpLoad %uint {'%vcc' if slot == 'vcc_lo' else '%vcc_hi'}") return t raise Unsupported("descriptor operand") def sgpr_words(self, a, n): if a["k"] == "sgpr" and a.get("n", 1) >= n: return [self.load_reg("sgpr", a["r"] + i) for i in range(n)] if a["k"] == "slist" and len(a["r"]) >= n: return [self.sgpr_word(a, i) for i in range(n)] raise Unsupported("descriptor operand") def addr_regs(self, a): """Image address operand: contiguous v[x:y] or an NSA list.""" if a["k"] == "vgpr": return [a["r"] + i for i in range(a.get("n", 1))] if a["k"] == "vlist": return a["r"] raise Unsupported("image address operand") def dynamic_sampled_access(self, ptr, ptr_type, array, index): """Index a sampled image or sampler array with the runtime descriptor lookup result.""" self.uses_dynamic_sampled_index = True self.emit(f"{ptr} = OpAccessChain {ptr_type} {array} {index}") def dynamic_storage_access(self, ptr, ptr_type, array, index): """Index a storage image array with the runtime descriptor lookup result.""" self.uses_dynamic_storage_index = True self.emit(f"{ptr} = OpAccessChain {ptr_type} {array} {index}") def cube_coords(self, f): """(s, t, face) of a cube sample -> the 6-layer 2D-array view. The hardware takes s and t in [1, 2] (sc / |cubema| + 1.5) and the third coordinate as 8 * slice + face.""" s, t, q, fl, d, layer = (self.tmp() for _ in range(6)) self.emit(f"{s} = OpFSub %float {f[0]} %f1") self.emit(f"{t} = OpFSub %float {f[1]} %f1") self.emit(f"{q} = OpFMul %float {f[2]} {self.fconst(0.125)}") self.emit(f"{fl} = OpExtInst %float %glsl Floor {q}") self.emit(f"{d} = OpFMul %float {fl} {self.fconst(2.0)}") self.emit(f"{layer} = OpFSub %float {f[2]} {d}") return [s, t, layer] + f[3:] def g16_gradients(self, op, words, grad_width): """The address words of a _g16 sample with its packed f16 gradients widened to one f32 word per component. GFX10 G16 packs dP/dx and dP/dy separately, two halves per VGPR, low half first, each axis padded to a whole VGPR: 1D (dx/dh, -), (dx/dv, -); 2D (dx/dh, dy/dh), (dx/dv, dy/dv); 3D (dx/dh, dy/dh), (dz/dh, -), (dx/dv, dy/dv), (dz/dv, -). That is LLVM's layout (SIISelLowering.cpp packImage16bitOpsToDwords, its comment and code) and Mesa ACO's (aco_select_nir.cpp packs ddx and ddy with one emit_pack_v1 call each, aco_isel_helpers.cpp emit_pack_v1 pairs halves low first and pads the last). Each half is widened with UnpackHalf2x16, as the a16 coordinates are. Only the gradients change: the words before them and the coordinates after them are returned as they are.""" if op not in ("image_sample_d", "image_sample_d_cl"): raise Unsupported(op + "_g16") per_axis = (grad_width + 1) // 2 if len(words) < 2 * per_axis: raise Unsupported(op + "_g16 coords") grads = [] for axis in range(2): halves = [] for w in words[axis * per_axis:(axis + 1) * per_axis]: v2 = self.tmp() self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {w}") for k in (0, 1): h = self.tmp() self.emit(f"{h} = OpCompositeExtract %float {v2} {k}") halves.append(self.tou(h)) grads += halves[:grad_width] # the pad half of an odd component count is dropped return grads + words[2 * per_axis:] def image_op(self, op, a, mods): # _g16 (SHADER-SAMPLE-G16): the same sample as the form without the suffix, with 16-bit gradients packed two # per VGPR (expanded by g16_gradients below); everything else, a16 included, is decided independently. g16 = op.endswith("_g16") if g16: op = op[:-4] a16 = "a16" in mods d16 = "d16" in mods dim = next((m for m in mods if m.startswith("dim:")), "dim:SQ_RSRC_IMG_2D") storage_only = dim == "dim:SQ_RSRC_IMG_1D_ARRAY" if storage_only and (op != "image_load" or d16): raise Unsupported(op + " 1D_ARRAY") kinds = {"dim:SQ_RSRC_IMG_2D": ("img2d", "%images", "simg2d", 2, "_ptr_UC_img"), "dim:SQ_RSRC_IMG_2D_ARRAY": ("img2da", "%images_arr", "simg2da", 3, "_ptr_UC_imga"), # Cube: the shader already did face selection (v_cube*), and cube_coords maps (s, t, face) onto a # 6-layer 2D array view of the cube. The runtime binds cube textures as 2D-array views. "dim:SQ_RSRC_IMG_CUBE": ("img2da", "%images_arr", "simg2da", 3, "_ptr_UC_imga"), "dim:SQ_RSRC_IMG_1D": ("img1d", "%images_1d", "simg1d", 1, "_ptr_UC_img1"), "dim:SQ_RSRC_IMG_3D": ("img3d", "%images_3d", "simg3d", -3, "_ptr_UC_img3")} if not storage_only and dim not in kinds: raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1]) if storage_only: ncoord, is3d = 2, False else: itype, iarr, stype, ncoord, iptr = kinds[dim] is3d = ncoord == -3 # 3D: three real coordinates (and 3-component gradients) if is3d: ncoord = 3 self.uses_tex_3d = True elif ncoord == 3: self.uses_tex_array = True if ncoord == 1: self.uses_tex_1d = True if is3d and op in ("image_sample_d", "image_sample_d_cl") and ("tfe" in mods or "lwe" in mods): raise Unsupported(op + " 3D gradient status") grad_width = 3 if is3d else min(ncoord, 2) # an array layer has no derivative # Cube loads use the same 2D-array view (sampled or storage) and integer layer as array loads. view_dim = "dim:SQ_RSRC_IMG_2D_ARRAY" if dim == "dim:SQ_RSRC_IMG_CUBE" else dim # glc makes the access coherent (see image_load_coherent). Only image_load can be: a sampled read has no # coherent form in SPIR-V, so it is refused rather than read stale. coherent = "glc" in mods if coherent and (op != "image_load" or view_dim not in self.STORE_DIMS): raise Unsupported(op + " glc " + dim.split("SQ_RSRC_IMG_")[-1]) dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1") dmask = int(dm.split(":")[1], 0) vdata = a[0] if vdata["k"] != "vgpr": # `off`, an SGPR or a constant where the VGPR range of the result goes raise Unsupported(op + " destination") addr = self.addr_regs(a[1]) if op == "image_sample_c_l": # Vulkan Dref returns one scalar. Other component masks require the depth view's swizzle. if (dim != "dim:SQ_RSRC_IMG_2D" or dmask != 1 or len(addr) != (3 if a16 else 4) or any(m not in (dim, dm, "a16", "d16") for m in mods)): raise Unsupported(op + " needs scalar 2D depth comparison") img_idx, kind = self.desc_lookup_sgpr(a[2], 8) # The T#'s own type decides which array holds this index. A read through another dimension's array (a # slice-0 view of a 2D-array or cube T#, which the runtime binds in the 2D array) is valid only when the # entry says so; otherwise the read is that array's fallback. A coherent read goes through the storage # view the stores write, so it follows the storage arrays' rule instead. img_idx = (self.desc_storage_index(img_idx, kind, view_dim) if coherent else self.desc_sampled_index(img_idx, kind, dim)) img = None # a coherent image_load reads the storage view, not this sampled one if not (coherent or storage_only): ip, img = self.tmp(), self.tmp() self.dynamic_sampled_access(ip, f"%{iptr}", iarr, img_idx) self.emit(f"{img} = OpLoad %{itype} {ip}") coords = [self.load_reg("vgpr", r) for r in addr] if g16: coords = self.g16_gradients(op, coords, grad_width) if a16: # GFX10 A16 packs only the coordinates, and the LOD or clamp after them, as f16 pairs (low half first). # The extra arguments before them keep a whole VGPR each, and so do non-G16 gradients (LLVM AMDGPU # getAddrSizeMIMGOp: the extra arguments' words, the gradients, then the packed halves; llvm-mc wants # v[0:2] for a 2D image_sample_c_b ... a16). A bias is an f16 in the low half of its VGPR, a z-compare # an f32. Until 2026-11-21 those were unpacked as pairs too, and the coordinates after them were read a # half early. A texel offset comes first and keeps its full dword under a16. if op.startswith("image_sample"): extras = op[len("image_sample"):] elif op.startswith("image_gather4"): extras = op[len("image_gather4"):] else: extras = "" w_off = 1 if op.endswith("_o") else 0 extras = extras[:-2] if w_off else extras extras = extras[:-3] if extras.endswith("_cl") else extras # the clamp is packed with the coordinates w_bias = 1 if extras in ("_b", "_c_b") else 0 w_grad = 2 * grad_width if extras in ("_d", "_d_cl") else 0 whole = w_off + w_bias + (1 if extras.startswith("_c") else 0) + w_grad unpacked = [] for i, c in enumerate(coords): if i < whole and not w_off <= i < w_off + w_bias: unpacked.append(c) # offset, z-compare or gradient: the whole word continue v2 = self.tmp() self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {c}") for k in ((0,) if i < whole else (0, 1)): # a bias is the low half only f = self.tmp() self.emit(f"{f} = OpCompositeExtract %float {v2} {k}") unpacked.append(self.tou(f)) coords = unpacked if op == "image_load": # 16-bit integer coordinates: each half is an unsigned 16-bit int, not an f16. coords = self.unpack_image_a16_uints([self.load_reg("vgpr", r) for r in addr]) if op == "image_load": if len(coords) < ncoord: raise Unsupported("image_load coords") ints = [self.as_int(c) for c in coords[:ncoord]] if ncoord == 1: iv = ints[0] else: iv = self.tmp() self.emit(f"{iv} = OpCompositeConstruct {'%v2int' if ncoord == 2 else '%v3int'} {' '.join(ints)}") if coherent: self.image_load_coherent(view_dim, a[2], iv, img_idx, dmask, vdata, d16) return self.image_load_typed(view_dim, a[2], iv, img, img_idx, dmask, vdata, lod=self.cu(0), d16=d16) return else: smp_idx = self.desc_lookup_sgpr(a[3], 4)[0] sp, smp, si = self.tmp(), self.tmp(), self.tmp() self.dynamic_sampled_access(sp, "%_ptr_UC_smp", "%samplers", smp_idx) self.emit(f"{smp} = OpLoad %smp {sp}") typed_implicit = op == "image_sample" and self.stage == "ps" and dim == "dim:SQ_RSRC_IMG_2D" # An explicit-LOD sample has the same shape in every dimension, so it takes the typed read too: # image_read_typed picks the UINT/SINT alias of the dimension's sampled binding (image_load does). typed_sample = typed_implicit or op in ("image_sample_l", "image_sample_lz") def sampled_image(image, cls, di=0): sampled = self.tmp() sampler_type = f"itxsamp{cls}_{di}" if cls else stype self.emit(f"{sampled} = OpSampledImage %{sampler_type} {image} {smp}") return sampled no_sampled_img = op in ("image_gather4_lz", "image_gather4_lz_o", "image_gather4_l", "image_gather4_l_o", "image_gather4_c_l", "image_gather4_c_l_o") or ( op in ("image_gather4_cl", "image_gather4_cl_o", "image_gather4_c_cl", "image_gather4_c_cl_o") and self.stage != "ps" ) if not typed_sample and not no_sampled_img: self.emit(f"{si} = OpSampledImage %{stype} {img} {smp}") f = [self.tof(c) for c in coords] if op in self.GATHER4_LOD_OPS: self.emit_gather4_lod(op, a, mods, dim, img, img_idx, si, coords, f, ncoord, is3d, dmask, vdata, a16, d16) return if op in ("image_gather4_c_lz", "image_gather4_c_lz_o"): self.emit_gather4_c_lz(op, mods, dim, si, coords, f, ncoord, is3d, dmask, vdata, d16) return goff = None if op in ("image_gather4_lz_o", "image_gather4_l_o"): # first address dword: signed 6-bit texel offsets x [5:0], y [13:8] if a16 and ("tfe" in mods or "lwe" in mods): raise Unsupported(op + " a16 status") parts = [] for k in range(2): u, i = self.tmp(), self.tmp() self.emit(f"{u} = OpBitFieldSExtract %uint {coords[0]} {self.cu(8 * k)} {self.cu(6)}") self.emit(f"{i} = OpBitcast %int {u}") parts.append(i) goff = self.tmp() self.emit(f"{goff} = OpCompositeConstruct %v2int {parts[0]} {parts[1]}") f = f[1:] op = op[:-2] self.uses_img_offset = True if op == "image_gather4_l": # Gather at an explicit LOD: Vulkan gathers have no Lod operand without an AMD extension, so fetch # the 2x2 footprint at mip round(lod) (clamped to the mip range) in gather order # (u0,v1) (u1,v1) (u1,v0) (u0,v0). Each texel coordinate goes through the S#'s own address mode # (CLAMP_X/CLAMP_Y, see gather_addr_modes / gather_addr). if bin(dmask).count("1") != 1 or ncoord != 2 or len(f) < 3: raise Unsupported("image_gather4_l form") modes = self.gather_addr_modes(a[3]) self.uses_query = True ch = dmask.bit_length() - 1 lv, lvm, rl, mi, mc, mz, sz, uvf, szf, st, half, flo, i0, one2, i1 = (self.tmp() for _ in range(15)) # Size and level-count queries read view properties; only the texel fetches need a typed alias. self.emit(f"{lv} = OpImageQueryLevels %int {img}") self.emit(f"{lvm} = OpISub %int {lv} {self.as_int(self.cu(1))}") lod = self.clamp_gather_lod(f[2], a[3]["r"] + 1) # Native gather rounds the LOD to the nearest mip with ties up, not to even (SHADER-152: on # Radeon Graphics 26.10.1, LOD 0.5 with bounds [0,1] selected mip 1, where RoundEven selected 0). # floor + (fraction >= 0.5), not Floor(lod + 0.5): lod - floor(lod) is exact in binary32, the sum is # not (0x3effffff + 0.5 rounds to 1.0, which picked mip 1 where native sampling reads mip 0). fr, up, fl, inc = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{rl} = OpExtInst %float %glsl Floor {lod}") self.emit(f"{fr} = OpFSub %float {lod} {rl}") self.emit(f"{up} = OpFOrdGreaterThanEqual %bool {fr} %fhalf_g") self.emit(f"{fl} = OpConvertFToS %int {rl}") self.emit(f"{inc} = OpSelect %int {up} {self.as_int(self.cu(1))} {self.as_int(self.cu(0))}") self.emit(f"{mi} = OpIAdd %int {fl} {inc}") self.emit(f"{mz} = OpExtInst %int %glsl SMax {mi} {self.as_int(self.cu(0))}") self.emit(f"{mc} = OpExtInst %int %glsl SMin {mz} {lvm}") self.emit(f"{sz} = OpImageQuerySizeLod %v2int {img} {mc}") self.emit(f"{uvf} = OpCompositeConstruct %v2float {f[0]} {f[1]}") self.emit(f"{szf} = OpConvertSToF %v2float {sz}") self.emit(f"{st} = OpFMul %v2float {uvf} {szf}") self.emit(f"{half} = OpCompositeConstruct %v2float %fhalf_g %fhalf_g") sub = self.tmp() self.emit(f"{sub} = OpFSub %v2float {st} {half}") self.emit(f"{flo} = OpExtInst %v2float %glsl Floor {sub}") self.emit(f"{i0} = OpConvertFToS %v2int {flo}") if goff is not None: i0o = self.tmp() self.emit(f"{i0o} = OpIAdd %v2int {i0} {goff}") i0 = i0o c1 = self.as_int(self.cu(1)) self.emit(f"{one2} = OpCompositeConstruct %v2int {c1} {c1}") self.emit(f"{i1} = OpIAdd %v2int {i0} {one2}") x0, y0, x1, y1 = (self.tmp() for _ in range(4)) self.emit(f"{x0} = OpCompositeExtract %int {i0} 0") self.emit(f"{y0} = OpCompositeExtract %int {i0} 1") self.emit(f"{x1} = OpCompositeExtract %int {i1} 0") self.emit(f"{y1} = OpCompositeExtract %int {i1} 1") szx, szy = self.tmp(), self.tmp() self.emit(f"{szx} = OpCompositeExtract %int {sz} 0") self.emit(f"{szy} = OpCompositeExtract %int {sz} 1") ax = [self.gather_addr(c, szx, modes[0]) for c in (x0, x1)] ay = [self.gather_addr(c, szy, modes[1]) for c in (y0, y1)] texels, outs = [], [] for (xx, ox), (yy, oy) in ((ax[0], ay[1]), (ax[1], ay[1]), (ax[1], ay[0]), (ax[0], ay[0])): cc = self.tmp() self.emit(f"{cc} = OpCompositeConstruct %v2int {xx} {yy}") texels.append(cc) if ox is not None and oy is not None: both = self.tmp() self.emit(f"{both} = OpLogicalOr %bool {ox} {oy}") outs.append(both) else: outs.append(ox if ox is not None else oy) # SHADER-348: border modes give a tap outside the image the S# border colour's channel. border_one = self.gather_border_one(a[3], ch) if any(o is not None for o in outs) else None def gather_mip(image: str, cls: int, ty: str) -> str: scalar = ("%float", "%uint", "%int")[cls] if border_one is not None: zero_v, one_v = (self.fconst(0.0), self.fconst(1.0)) if cls == 0 else \ (self.cu(0), self.cu(1)) if cls == 1 else (self.as_int(self.cu(0)), self.as_int(self.cu(1))) if isinstance(border_one, bool): border_v = one_v if border_one else zero_v else: border_v = self.tmp() self.emit(f"{border_v} = OpSelect {scalar} {border_one} {one_v} {zero_v}") taps = [] for cc, out in zip(texels, outs): tx, comp = self.tmp(), self.tmp() self.emit(f"{tx} = OpImageFetch {ty} {image} {cc} Lod {mc}") self.emit(f"{comp} = OpCompositeExtract {scalar} {tx} {ch}") if out is not None: sel = self.tmp() self.emit(f"{sel} = OpSelect {scalar} {out} {border_v} {comp}") comp = sel taps.append(comp) result = self.tmp() self.emit(f"{result} = OpCompositeConstruct {ty} {' '.join(taps)}") return result self.image_read_typed(dim, self.sgpr_word(a[2], 1), img, img_idx, 0xf, vdata, d16, gather_mip) self.uses_fhalf = True return if op == "image_gather4_lz": # Gather the 2x2 footprint of one channel (dmask picks it) at mip 0 -> 4 results. if bin(dmask).count("1") != 1 or ncoord not in (2, 3) or is3d or len(f) < ncoord: raise Unsupported("image_gather4_lz form") if dim == "dim:SQ_RSRC_IMG_CUBE": f = self.cube_coords(f) uv = self.tmp() if ncoord == 3: # 2D array (or cube as a 6-layer array): layer is the 3rd coordinate self.emit(f"{uv} = OpCompositeConstruct %v3float {f[0]} {f[1]} {f[2]}") else: self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}") component = self.cu(dmask.bit_length() - 1) offset = f" Offset {goff}" if goff is not None else "" def gather(image, cls, ty): sampled = sampled_image(image, cls) res = self.tmp() self.emit(f"{res} = OpImageGather {ty} {sampled} {uv} {component}{offset}") return res if dim == "dim:SQ_RSRC_IMG_2D": self.uses_int_sampler = True # dmask selects one texture channel; all four taps are written. self.image_read_typed(dim, self.sgpr_word(a[2], 1), img, img_idx, 0xf, vdata, d16, gather) return res = gather(img, 0, "%v4float") comps = [] for c in range(4): comp = self.tmp() self.emit(f"{comp} = OpCompositeExtract %float {res} {c}") comps.append(comp) self.store_gather_taps(vdata["r"], comps, d16) return kind = op[len("image_sample"):] # '', '_lz', '_l', '_b', '_c_lz', '_d', '_d_cl' (+ '_o') off = None if kind.endswith("_o"): # _o: the first address dword packs signed 6-bit texel offsets, x = [5:0], y = [13:8], z = [21:16] # (GFX10 MIMG address order: offset, bias, z-compare, derivatives, coordinates). Mapped to the # SPIR-V Offset operand; Vulkan only guarantees offsets within minTexelOffset..maxTexelOffset. kind = kind[:-2] raw, f = coords[0], f[1:] n_off = 3 if is3d else (1 if ncoord == 1 else 2) parts = [] for k in range(n_off): u, i = self.tmp(), self.tmp() self.emit(f"{u} = OpBitFieldSExtract %uint {raw} {self.cu(8 * k)} {self.cu(6)}") self.emit(f"{i} = OpBitcast %int {u}") parts.append(i) if n_off == 1: off = parts[0] else: off = self.tmp() self.emit(f"{off} = OpCompositeConstruct {'%v3int' if n_off == 3 else '%v2int'} {' '.join(parts)}") if not TEXEL_OFFSET_FALLBACK: self.uses_img_offset = True minlod = None clamp = kind.endswith("_cl") # a min-LOD clamp, read after the coordinates (after the gradients for _d) if clamp: kind = kind[:-3] if kind not in ("", "_b", "_c", "_c_b", "_d"): raise Unsupported(op) self.uses_minlod = True # Address order after the offset: bias, z-compare, gradients, coordinates, LOD, clamp. bias = None if kind in ("_b", "_c_b"): bias, f = f[0], f[1:] if EXPLICIT_LOD_BIAS: bias = self.add_ssharp_lod_bias(bias, a[3]["r"] + 2) ref = None if kind.startswith("_c"): ref, f = f[0], f[1:] grads = None if kind == "_d": # Address order: all dP/dx components, all dP/dy components, then the coordinates. if len(f) < 2 * grad_width + ncoord: raise Unsupported(op + " coords") if grad_width == 1: grads = (f[0], f[1]) else: gx, gy = self.tmp(), self.tmp() self.emit(f"{gx} = OpCompositeConstruct %v{grad_width}float {' '.join(f[:grad_width])}") self.emit(f"{gy} = OpCompositeConstruct %v{grad_width}float {' '.join(f[grad_width:2 * grad_width])}") grads = (gx, gy) if EXPLICIT_LOD_BIAS: grads = self.scale_grads_by_ssharp_bias(grads, grad_width, a[3]["r"] + 2) f = f[2 * grad_width:] if clamp: # The clamp is the component right after the coordinates. Under a16 an f16 pad may follow it, so # it isn't the last one there (taking the last one read that pad until 2026-11-21). if len(f) <= ncoord: raise Unsupported(op + " coords") minlod, f = f[ncoord], f[:ncoord] if len(f) < ncoord: raise Unsupported(op + " coords") if dim == "dim:SQ_RSRC_IMG_CUBE": f = self.cube_coords(f) if ncoord == 1: uv = f[0] elif ncoord == 3: # The array layer arrives as a float coordinate; Vulkan rounds it the same way. uv = self.tmp() self.emit(f"{uv} = OpCompositeConstruct %v3float {f[0]} {f[1]} {f[2]}") else: uv = self.tmp() self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}") lod = f[ncoord] if kind == "_l" and len(f) > ncoord else "%f0" if EXPLICIT_LOD_BIAS and kind in ("_lz", "_l"): lod = self.add_ssharp_lod_bias(lod, a[3]["r"] + 2) if typed_sample: float_only = self._is_float_only_image_op(op, a, mods) # The aliases image_read_typed declares are indexed by the dimension it reads: a cube samples its # 6-layer 2D-array view, which is what `img` was loaded from above. di = self.STORE_DIMS[view_dim][0] if typed_implicit and float_only and not EXPLICIT_LOD_BIAS: # With --explicit-lod-bias the Grad path below scales the derivatives by the S# bias. def sample(image, cls, ty): sampled = sampled_image(image, cls, di) result = self.tmp() self.emit(f"{result} = OpImageSampleImplicitLod {ty} {sampled} {uv}") return result else: operands = f"Lod {lod}" if typed_implicit: # Compute the quad gradients before the per-image format branch. dx, dy = self.tmp(), self.tmp() self.emit(f"{dx} = OpDPdx %v2float {uv}") self.emit(f"{dy} = OpDPdy %v2float {uv}") if EXPLICIT_LOD_BIAS: dx, dy = self.scale_grads_by_ssharp_bias((dx, dy), 2, a[3]["r"] + 2) operands = f"Grad {dx} {dy}" def sample(image, cls, ty): sampled = sampled_image(image, cls, di) result = self.tmp() self.emit(f"{result} = OpImageSampleExplicitLod {ty} {sampled} {uv} {operands}") return result if not float_only: self.uses_int_sampler = True t1 = self.sgpr_word(a[2], 1) if (d16 or not float_only) else None self.image_read_typed(view_dim, t1, img, img_idx, dmask, vdata, d16, sample, float_only=float_only) return res = self.tmp() if off is not None and kind not in ("", "_lz", "_l", "_b", "_c_lz", "_c", "_c_b"): raise Unsupported(op) implicit = kind in ("", "_b", "_c", "_c_b") and self.stage == "ps" # A min-LOD clamp (_cl): MinLod goes with the implicit-LOD forms and Grad. Without derivatives (outside the # PS) the base LOD is 0 (or bias for _b / _c_b) and the clamp raises it, so the explicit LOD is # max(base, clamp) and no MinLod operand. lod_zero = "%f0" if EXPLICIT_LOD_BIAS and not implicit and kind in ("", "_c_lz", "_c"): # Outside the PS these forms are explicit-LOD samples at lod_zero (_b / _c_b carry it in their bias). # The bias goes in before the _cl clamp below: Vulkan clamps the biased LOD, max(bias, minlod). lod_zero = self.add_ssharp_lod_bias(lod_zero, a[3]["r"] + 2) if minlod is not None and not implicit and kind not in ("_d", "_b", "_c_b"): base = lod_zero lod_zero = self.tmp() self.emit(f"{lod_zero} = OpExtInst %float %glsl FMax {base} {minlod}") bias_lod = bias if kind in ("_b", "_c_b") and not implicit and minlod is not None: bias_lod = self.tmp() self.emit(f"{bias_lod} = OpExtInst %float %glsl FMax {bias} {minlod}") # Implicit samples without a bias of their own take the S# bias as a Bias operand. sbias = (self.ssharp_lod_bias(a[3]["r"] + 2) if EXPLICIT_LOD_BIAS and implicit and kind in ("", "_c") else None) grads_fb = None if off is not None and TEXEL_OFFSET_FALLBACK: fb_lod = bias_lod if (not implicit and kind in ("_b", "_c_b")) else lod uv, grads_fb = self.texel_offset_fold(img, si, uv, off, n_off, ncoord, kind, implicit, fb_lod, bias, a[3]) off = None if grads_fb is not None and sbias is not None: # Grad, not Bias, carries these samples now: scale the derivatives instead. grads_fb = self.scale_grads_by_ssharp_bias(grads_fb, 3 if is3d else ncoord, a[3]["r"] + 2) sbias = None def opnd(mask, args): """Image operands in SPIR-V mask order: Bias / Lod, Offset (0x10), MinLod (0x80, implicit forms).""" masks, vals = ([mask], [args]) if mask else ([], []) if off is not None: masks.append("Offset") vals.append(off) if minlod is not None and mask in ("", "Bias") and implicit: masks.append("MinLod") vals.append(minlod) return f" {'|'.join(masks)} {' '.join(vals)}" if masks else "" if kind == "_d": if minlod is not None: self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Grad|MinLod {grads[0]} {grads[1]} {minlod}") else: self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Grad {grads[0]} {grads[1]}") elif grads_fb is not None and not kind.startswith("_c"): self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Grad{'|MinLod' if minlod else ''} " f"{grads_fb[0]} {grads_fb[1]}{' ' + minlod if minlod else ''}") elif kind == "": self.emit(f"{res} = OpImageSampleImplicitLod %v4float {si} {uv}{opnd('Bias', sbias) if sbias else opnd('', '')}" if self.stage == "ps" else f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', lod_zero)}") elif kind in ("_lz", "_l"): self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', lod)}") elif kind == "_b": self.emit(f"{res} = OpImageSampleImplicitLod %v4float {si} {uv}{opnd('Bias', bias)}" if self.stage == "ps" else f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', bias_lod)}") elif kind in ("_c_lz", "_c_l", "_c", "_c_b"): d = self.tmp() if kind in ("_c_lz", "_c_l") or (self.stage != "ps" and kind in ("_c", "_c_b")): # _c / _c_b outside the PS have no derivatives (base LOD 0, or bias / max(bias, minlod) for _c_b) d_lod = f[ncoord] if kind == "_c_l" else (bias_lod if kind == "_c_b" else lod_zero) if EXPLICIT_LOD_BIAS and kind == "_c_l": d_lod = self.add_ssharp_lod_bias(d_lod, a[3]["r"] + 2) self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref}{opnd('Lod', d_lod)}") elif grads_fb is not None: self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref} Grad{'|MinLod' if minlod else ''} " f"{grads_fb[0]} {grads_fb[1]}{' ' + minlod if minlod else ''}") elif kind == "_c_b": self.emit(f"{d} = OpImageSampleDrefImplicitLod %float {si} {uv} {ref}{opnd('Bias', bias)}") else: self.emit(f"{d} = OpImageSampleDrefImplicitLod %float {si} {uv} {ref}{opnd('Bias', sbias) if sbias else opnd('', '')}") if d16: # d16: the compare result is an f16 in the low half, as in the other d16 paths below. Until # 2026-11-21 it was written as f32 bits, whose low half is 0 for every result (1.0 = 0x3f800000). r = self.f16_bits(d) else: r = self.tou(d) self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, r) return else: raise Unsupported(op) ncomp = bin(dmask).count("1") comps = [] for c in range(4): if dmask >> c & 1: comp = self.tmp() self.emit(f"{comp} = OpCompositeExtract %float {res} {c}") comps.append(comp) if len(comps) != ncomp: raise Unsupported("dmask") if d16: # d16: components are packed two per register as f16 (x|y<<16, z|w<<16). for i in range(0, len(comps), 2): second = comps[i + 1] if i + 1 < len(comps) else "%f0" p = self.pack_f16_pair_int(comps[i], second) self.dst({"k": "vgpr", "r": vdata["r"] + i // 2, "n": 1}, p) else: for i, comp in enumerate(comps): self.dst({"k": "vgpr", "r": vdata["r"] + i, "n": 1}, self.tou(comp)) # image atomic -> SPIR-V op (guarded inside `if (active)` so inactive lanes skip the access) IMG_ATOMICS = {"image_atomic_umin": "OpAtomicUMin", "image_atomic_umax": "OpAtomicUMax", "image_atomic_smin": "OpAtomicSMin", "image_atomic_smax": "OpAtomicSMax", "image_atomic_or": "OpAtomicOr", "image_atomic_xor": "OpAtomicXor", "image_atomic_and": "OpAtomicAnd", "image_atomic_add": "OpAtomicIAdd", "image_atomic_sub": "OpAtomicISub"} IMG_ATOMICS_EXTRA = ("image_atomic_swap", "image_atomic_inc", "image_atomic_dec", "image_atomic_fmin", "image_atomic_fmax", "image_atomic_fcmpswap") # image_store views: dim -> (index, SPIR-V Dim, arrayed, coordinate count). Class 0 = float, 1 = uint, 2 = sint # (Vulkan needs the shader's component type to match the image format). STORE_DIMS = {"dim:SQ_RSRC_IMG_2D": (0, "2D", 0, 2), "dim:SQ_RSRC_IMG_2D_ARRAY": (1, "2D", 1, 3), "dim:SQ_RSRC_IMG_3D": (2, "3D", 0, 3), "dim:SQ_RSRC_IMG_1D": (3, "1D", 0, 1), "dim:SQ_RSRC_IMG_1D_ARRAY": (4, "1D", 1, 2)} # The sampled array of each STORE_DIMS index: its binding in set 0 (assemble declares %images, %images_arr, # %images_3d and %images_1d there). Typed image_load reads UINT/SINT images through uint/sint aliases of it. SAMPLED_BINDINGS = {0: 0, 1: 3, 2: 6, 3: 5} R32_UINT = next(code for code, name in GFX10_FORMATS.items() if name == "GFX10_FORMAT_32_UINT") INT_FORMATS = None # (uint mask words, sint mask words) over the 512 GFX10 formats @classmethod def int_format_masks(cls): if cls.INT_FORMATS is None: u, si = [0] * 16, [0] * 16 for k, name in GFX10_FORMATS.items(): if name.endswith("_UINT"): u[k >> 5] |= 1 << (k & 31) elif name.endswith("_SINT"): si[k >> 5] |= 1 << (k & 31) cls.INT_FORMATS = (u, si) return cls.INT_FORMATS FLOAT_FORMATS = None @classmethod def float_format_masks(cls): """(normalized, 32-bit-channel float) 512-bit tables over the GFX10 T# FORMAT field, for the d16 rounding rule: a UNORM/SNORM channel is the one whose exact quotient the hardware rounds once, and a float channel 32 bits wide is the one it narrows toward zero (SHADER-308).""" if cls.FLOAT_FORMATS is None: norm, f32 = [0] * 16, [0] * 16 for k, name in GFX10_FORMATS.items(): if name.endswith(("_UNORM", "_SNORM")): norm[k >> 5] |= 1 << (k & 31) elif name.endswith("_FLOAT") and re.fullmatch(r"GFX10_FORMAT_(32_)*32_FLOAT", name): f32[k >> 5] |= 1 << (k & 31) cls.FLOAT_FORMATS = (norm, f32) return cls.FLOAT_FORMATS def fmt_float_flags(self, word1): """(is UNORM/SNORM, is a 32-bit-channel float format) for a T# word1, from the 512-bit tables.""" for w in [16] + sum(self.float_format_masks(), []): self.cu(w) fmt, word, bit = self.tmp(), self.tmp(), self.tmp() self.emit(f"{fmt} = OpBitFieldUExtract %uint {word1} {self.cu(20)} {self.cu(9)}") self.emit(f"{word} = OpShiftRightLogical %uint {fmt} {self.cu(5)}") self.emit(f"{bit} = OpBitwiseAnd %uint {fmt} {self.cu(31)}") flags = [] for mask in ("%fmt_norm_mask", "%fmt_f32_mask"): ptr, w, b, nz = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{ptr} = OpAccessChain %_ptr_Private_uint {mask} {word}") self.emit(f"{w} = OpLoad %uint {ptr}") self.emit(f"{b} = OpBitFieldUExtract %uint {w} {bit} {self.cu(1)}") self.emit(f"{nz} = OpINotEqual %bool {b} {self.cu(0)}") flags.append(nz) return flags def fmt_int_flags(self, word1): """(is UINT format, is SINT format) for a T# word1 (FORMAT [28:20]), from the 512-bit tables.""" for w in [16] + sum(self.int_format_masks(), []): self.cu(w) fmt, word, bit = self.tmp(), self.tmp(), self.tmp() self.emit(f"{fmt} = OpBitFieldUExtract %uint {word1} {self.cu(20)} {self.cu(9)}") self.emit(f"{word} = OpShiftRightLogical %uint {fmt} {self.cu(5)}") self.emit(f"{bit} = OpBitwiseAnd %uint {fmt} {self.cu(31)}") flags = [] for mask in ("%fmt_uint_mask", "%fmt_sint_mask"): p, w, b, nz = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{p} = OpAccessChain %_ptr_Private_uint {mask} {word}") self.emit(f"{w} = OpLoad %uint {p}") self.emit(f"{b} = OpBitFieldUExtract %uint {w} {bit} {self.cu(1)}") self.emit(f"{nz} = OpINotEqual %bool {b} {self.cu(0)}") flags.append(nz) return flags def saturate_int16(self, bits: str, signed: bool) -> str: """Return the saturated integer as 16 bits in the low half of a uint.""" half = self.tmp() if signed: value, clamped, raw = self.as_int(bits), self.tmp(), self.tmp() self.emit(f"{clamped} = OpExtInst %int %glsl SClamp {value} {self.as_int(self.cu(0xFFFF8000))} " f"{self.as_int(self.cu(0x7FFF))}") self.emit(f"{raw} = OpBitcast %uint {clamped}") # BitFieldUExtract, not And & 0xFFFF: raw is a Bitcast of an %int SClamp and the result # reaches preserve-high-half merges (d16 image/buffer stores); NVIDIA miscompiles the And. self.emit(f"{half} = OpBitFieldUExtract %uint {raw} {self.cu(0)} {self.cu(16)}") else: self.emit(f"{half} = OpExtInst %uint %glsl UMin {bits} {self.cu(0xFFFF)}") return half @staticmethod def tsharp_regs(tsharp): """The same descriptor register group can be printed as a range or a list.""" if tsharp["k"] == "slist": return tuple(tsharp["r"][:8]) if tsharp["k"] == "sgpr": return tuple(range(tsharp["r"], tsharp["r"] + 8)) return () def synthetic_uav(self, tsharp): """Decode the private volume/packed UAV tag (gfx10_descriptors.h), not ordinary hardware metadata.""" t4 = self.sgpr_word(tsharp, 4) t7 = self.sgpr_word(tsharp, 7) flag, flag_set, tag, tag_set, uav = (self.tmp() for _ in range(5)) self.emit(f"{flag} = OpBitwiseAnd %uint {t4} {self.cu(0x80000000)}") self.emit(f"{flag_set} = OpINotEqual %bool {flag} {self.cu(0)}") self.emit(f"{tag} = OpBitwiseAnd %uint {t7} {self.cu(0xff800000)}") self.emit(f"{tag_set} = OpIEqual %bool {tag} {self.cu(0xd7800000)}") self.emit(f"{uav} = OpLogicalAnd %bool {flag_set} {tag_set}") return uav, t7 def packed_uav(self, tsharp): uav, t7 = self.synthetic_uav(tsharp) return self.emit_land(uav, self.emit_ne0(self.emit_and(t7, 0x00400000))) def image_fetch(self, img, coords, lod, ty, volume=None): """Vulkan applies Z slicing to storage views only. Rebase all sampled aliases of a volume UAV.""" if volume is None: res = self.tmp() self.emit(f"{res} = OpImageFetch {ty} {img} {coords} Lod {lod}") return res uav, t7 = volume offset, last, z, relative, absolute, coord = (self.tmp() for _ in range(6)) self.emit(f"{offset} = OpBitFieldUExtract %uint {t7} {self.cu(0)} {self.cu(11)}") self.emit(f"{last} = OpBitFieldUExtract %uint {t7} {self.cu(11)} {self.cu(11)}") self.emit(f"{z} = OpCompositeExtract %int {coords} 2") self.emit(f"{relative} = OpBitcast %uint {z}") self.emit(f"{absolute} = OpIAdd %int {z} {self.as_int(offset)}") self.emit(f"{coord} = OpSelect %int {uav} {absolute} {z}") in_slice, not_uav, valid = (self.tmp() for _ in range(3)) self.emit(f"{in_slice} = OpULessThanEqual %bool {relative} {last}") in_view = in_slice if lod != self.cu(0): base_mip, in_view = self.tmp(), self.tmp() self.emit(f"{base_mip} = OpIEqual %bool {lod} {self.as_int(self.cu(0))}") self.emit(f"{in_view} = OpLogicalAnd %bool {in_slice} {base_mip}") self.emit(f"{not_uav} = OpLogicalNot %bool {uav}") self.emit(f"{valid} = OpLogicalOr %bool {not_uav} {in_view}") body, miss, end = (self.tmp() + s for s in ("_fetch", "_oob", "_end")) adjusted, texel, zero, result = (self.tmp() for _ in range(4)) self.emit(f"OpSelectionMerge {end} None") self.emit(f"OpBranchConditional {valid} {body} {miss}") self.emit(f"{body} = OpLabel") self.emit(f"{adjusted} = OpCompositeInsert %v3int {coord} {coords} 2") self.emit(f"{texel} = OpImageFetch {ty} {img} {adjusted} Lod {lod}") self.emit(f"OpBranch {end}") self.emit(f"{miss} = OpLabel") scalar = {"%v4float": "%f0", "%v4uint_st": self.cu(0), "%v4int_st": None}[ty] if scalar is None: scalar = self.as_int(self.cu(0)) self.emit(f"{zero} = OpCompositeConstruct {ty} {' '.join([scalar] * 4)}") self.emit(f"OpBranch {end}") self.emit(f"{end} = OpLabel") self.emit(f"{result} = OpPhi {ty} {texel} {body} {zero} {miss}") return result def _is_float_only_image_op(self, op, a=None, mods=()): """Whether the current image op is provably float-only so uint/sint runtime branches can be elided. True when either: 1. CFG consumer analysis (float_only_image_ops) proved every reachable consumer of its destination VGPRs interprets them strictly as floating-point (f32, or f16 under d16), with at least one float consumer. 2. It is a filtered image_sample* whose compile-time literal S# word 2 enables bilinear/aniso XY filtering or linear mip filtering (undefined on integer formats in Vulkan and RDNA2).""" if self.cur_ins is not None and id(self.cur_ins) in self.float_only_images: return True if op in ("image_sample", "image_sample_l", "image_sample_lz") and a is not None and len(a) >= 4: w2 = None if self.cur_ins is not None and id(self.cur_ins) in self.literal_sampler_sites: w2 = self.literal_sampler_sites[id(self.cur_ins)][2] elif a[3]["k"] == "sgpr" and a[3].get("n", 1) >= 4: w2 = self.sgpr_imm.get(a[3]["r"] + 2) if w2 is not None: mag = (w2 >> 20) & 3 min_f = (w2 >> 22) & 3 mip = (w2 >> 26) & 3 if mag in (1, 3) or min_f in (1, 3) or mip == 2: return True return False def image_load_typed(self, dim, tsharp, iv, img, idx, dmask, vdata, *, lod, d16=False): """Supply the fetch to the shared typed-image dispatch used by both loads and gathers.""" float_only = self._is_float_only_image_op("image_load") di = self.STORE_DIMS[dim][0] volume = self.synthetic_uav(tsharp) if di == 2 else None atomic_read = (volume is not None and self.tsharp_regs(tsharp) in self.atomic_volume_tsharps and lod == self.cu(0)) if img is None: return self.image_load_storage(dim, tsharp, iv, idx, dmask, vdata, d16) t1 = self.sgpr_word(tsharp, 1) if (d16 or atomic_read or not float_only) else None def fetch(image, cls, ty): if cls != 1 or not atomic_read: return self.image_fetch(image, iv, lod, ty, volume) # Read a tagged logical R32_UINT volume UAV through the same formatted storage view as its atomics. # Other uint descriptors (notably SRVs) must use the sampled alias, not a potentially shorter array. self.uses_storage3d = True fmt, r32, coherent = self.tmp(), self.tmp(), self.tmp() self.emit(f"{fmt} = OpBitFieldUExtract %uint {t1} {self.cu(20)} {self.cu(9)}") self.emit(f"{r32} = OpIEqual %bool {fmt} {self.cu(self.R32_UINT)}") self.emit(f"{coherent} = OpLogicalAnd %bool {r32} {volume[0]}") storage, sampled, fetch_done, end = ( self.tmp() + suffix for suffix in ("_storage", "_sampled", "_fetch_done", "_read_end")) self.emit(f"OpSelectionMerge {end} None") self.emit(f"OpBranchConditional {coherent} {storage} {sampled}") self.emit(f"{storage} = OpLabel") ip, im, raw, result = (self.tmp() for _ in range(4)) self.emit(f"{ip} = OpAccessChain %_ptr_UC_simg3 %simages3d {idx}") self.emit(f"{im} = OpLoad %simg3d_u {ip}") self.emit(f"{raw} = OpImageRead {ty} {im} {iv}") self.emit(f"OpBranch {end}") self.emit(f"{sampled} = OpLabel") texel = self.image_fetch(image, iv, lod, ty, volume) self.emit(f"OpBranch {fetch_done}") self.emit(f"{fetch_done} = OpLabel") self.emit(f"OpBranch {end}") self.emit(f"{end} = OpLabel") self.emit(f"{result} = OpPhi {ty} {raw} {storage} {texel} {fetch_done}") return result self.image_read_typed(dim, t1, img, idx, dmask, vdata, d16, fetch, float_only=float_only) def image_load_coherent(self, dim, tsharp, iv, idx, dmask, vdata, d16): """image_load with glc: a coherent read. On GFX10 a device-scope load is glc + dlc and a device-scope store glc (Mesa ac_get_hw_cache_flags maps ACCESS_COHERENT to exactly these bits); the POPS pixel shaders read and write their ordered images that way. Through the sampled array (image_load_typed) the read could not see another invocation's store: sampled reads have no coherent form, and the interlock between POPS critical sections only makes Coherent memory visible (Vulkan memory model, fragment shader interlock). So the read goes through the storage view the stores write (OpImageRead, StorageImageReadWithoutFormat), and the storage views are decorated Coherent (assemble).""" self.coherent_images = True self.image_load_storage(dim, tsharp, iv, idx, dmask, vdata, d16) def image_load_storage(self, dim, tsharp, iv, idx, dmask, vdata, d16): di = self.STORE_DIMS[dim][0] self.uses_store_reads.add(di) if di >= 2: # Packed RGB9E5 has no float storage view. Untagged 3D SRVs may also have an index beyond # the shorter storage arrays; the coherent operation needs a UAV, not a sampled descriptor. unsupported = self.packed_uav(tsharp) if di == 2: tagged, _ = self.synthetic_uav(tsharp) untagged, reject = self.tmp(), self.tmp() self.emit(f"{untagged} = OpLogicalNot %bool {tagged}") self.emit(f"{reject} = OpLogicalOr %bool {untagged} {unsupported}") unsupported = reject safe = self.tmp() self.emit(f"{safe} = OpSelect %uint {unsupported} {self.cu(0)} {idx}") idx = safe def view(cls): ip, im = self.tmp(), self.tmp() self.dynamic_storage_access(ip, f"%_ptr_UC_stv{cls}_{di}", f"%stv{cls}_{di}", idx) self.emit(f"{im} = OpLoad %stimg{cls}_{di} {ip}") return im def read(image, _cls, ty): res = self.tmp() self.emit(f"{res} = OpImageRead {ty} {image} {iv}") return res float_only = self._is_float_only_image_op("image_load") t1 = self.sgpr_word(tsharp, 1) if (d16 or not float_only) else None self.image_read_typed(dim, t1, None, idx, dmask, vdata, d16, read, view, float_only=float_only) def image_read_typed(self, dim, t1, img, idx, dmask, vdata, d16, read, view=None, float_only=False): """Read an image using the component type selected by FORMAT in T# word 1. read(image, cls, ty) emits the fetch or gather and returns its four components. The float view also handles a lookup miss: index zero holds the RGBA8_UNORM fallback. view(cls) loads the image of class cls (0 float, 1 uint, 2 sint); by default the sampled image img for float and, for UINT and SINT, typed aliases of the dimension's sampled binding (SHADER-151), so no storage image feature is needed. When `float_only` is True, the dead uint/sint branches, format-mask lookups and typed alias arrays are elided. dmask selects the output components; d16 packs two per VGPR.""" di = self.STORE_DIMS[dim][0] if float_only: if d16: self.uses_d16_image = True is_norm_fmt, is_f32_fmt = self.fmt_float_flags(t1) if d16 else (None, None) texel = read(view(0) if view is not None else img, 0, "%v4float") xs = [] for c in range(4): if dmask >> c & 1: comp = self.tmp() self.emit(f"{comp} = OpCompositeExtract %float {texel} {c}") xs.append(self.tou(comp)) if not d16: for k, x in enumerate(xs): self.dst({"k": "vgpr", "r": vdata["r"] + k, "n": 1}, x) return for i in range(0, len(xs), 2): dest = {"k": "vgpr", "r": vdata["r"] + i // 2, "n": 1} if i + 1 == len(xs): self.write_lo16(dest, self.d16_norm_f16(xs[i], is_norm_fmt, is_f32_fmt)) continue hi_s, w = self.tmp(), self.tmp() self.emit(f"{hi_s} = OpShiftLeftLogical %uint " f"{self.d16_norm_f16(xs[i + 1], is_norm_fmt, is_f32_fmt)} {self.cu(16)}") self.emit(f"{w} = OpBitwiseOr %uint {self.d16_norm_f16(xs[i], is_norm_fmt, is_f32_fmt)} {hi_s}") self.dst(dest, w) return if view is None: self.uses_int_fetch.add(di) def view(cls): if cls == 0: return img ip, im = self.tmp(), self.tmp() self.dynamic_sampled_access(ip, f"%_ptr_UC_itx{cls}_{di}", f"%itx{cls}_{di}", idx) self.emit(f"{im} = OpLoad %itximg{cls}_{di} {ip}") return im is_u, is_s = self.fmt_int_flags(t1) # SHADER-308: d16 image results follow the same rounding rule as d16 typed buffer loads. UNORM/SNORM are the # exact quotient rounded once (the two D16_NORM_HALFWAY f32 values are 1 ulp high through f32), and a # 32-bit float channel is narrowed toward zero, not to nearest even. Measured on an RX 6700 (gfx1031). if d16: self.uses_d16_image = True is_norm_fmt, is_f32_fmt = self.fmt_float_flags(t1) if d16 else (None, None) hit = self.tmp() self.emit(f"{hit} = OpINotEqual %bool {idx} {self.cu(0)}") use_u, use_s = self.tmp(), self.tmp() self.emit(f"{use_u} = OpLogicalAnd %bool {is_u} {hit}") self.emit(f"{use_s} = OpLogicalAnd %bool {is_s} {hit}") L = {k: self.tmp() + "_" + k for k in ("s", "rest", "e2", "u", "f", "e3")} def write(v4u, numeric_class): xs = [] for c in range(4): if dmask >> c & 1: x = self.tmp() self.emit(f"{x} = OpCompositeExtract %uint {v4u} {c}") if d16 and numeric_class: x = self.saturate_int16(x, signed=(numeric_class == 2)) xs.append(x) if not d16: for k, x in enumerate(xs): self.dst({"k": "vgpr", "r": vdata["r"] + k, "n": 1}, x) return # D16 packs saturated integer or RTE floating-point halves, low half first. for i in range(0, len(xs), 2): dest = {"k": "vgpr", "r": vdata["r"] + i // 2, "n": 1} if i + 1 == len(xs): lo = (self.d16_norm_f16(xs[i], is_norm_fmt, is_f32_fmt) if numeric_class == 0 else xs[i]) self.write_lo16(dest, lo) continue if numeric_class == 0: hi_s, w = self.tmp(), self.tmp() self.emit(f"{hi_s} = OpShiftLeftLogical %uint " f"{self.d16_norm_f16(xs[i + 1], is_norm_fmt, is_f32_fmt)} {self.cu(16)}") self.emit(f"{w} = OpBitwiseOr %uint {self.d16_norm_f16(xs[i], is_norm_fmt, is_f32_fmt)} {hi_s}") else: hi, w = self.tmp(), self.tmp() self.emit(f"{hi} = OpShiftLeftLogical %uint {xs[i + 1]} {self.cu(16)}") self.emit(f"{w} = OpBitwiseOr %uint {xs[i]} {hi}") self.dst(dest, w) def read_view(cls, ty): texel = read(view(cls), cls, ty) b = self.tmp() self.emit(f"{b} = OpBitcast %v4uint_st {texel}") write(b, cls) self.emit(f"OpSelectionMerge {L['e2']} None") self.emit(f"OpBranchConditional {use_s} {L['s']} {L['rest']}") self.emit(f"{L['s']} = OpLabel") read_view(2, "%v4int_st") self.emit(f"OpBranch {L['e2']}") self.emit(f"{L['rest']} = OpLabel") self.emit(f"OpSelectionMerge {L['e3']} None") self.emit(f"OpBranchConditional {use_u} {L['u']} {L['f']}") self.emit(f"{L['u']} = OpLabel") read_view(1, "%v4uint_st") self.emit(f"OpBranch {L['e3']}") self.emit(f"{L['f']} = OpLabel") read_view(0, "%v4float") self.emit(f"OpBranch {L['e3']}") self.emit(f"{L['e3']} = OpLabel") self.emit(f"OpBranch {L['e2']}") self.emit(f"{L['e2']} = OpLabel") def unpack_image_a16_uints(self, words: list[str]) -> list[str]: """Unpack the unsigned address components of a samplerless MIMG instruction, low half first.""" halves = [] for word in words: lo, hi = self.tmp(), self.tmp() self.emit(f"{lo} = OpBitwiseAnd %uint {word} {self.cu(0xFFFF)}") self.emit(f"{hi} = OpShiftRightLogical %uint {word} {self.cu(16)}") halves.extend((lo, hi)) return halves def image_store(self, a, mods, dim): """image_store vData, vAddr, T#: write the dmask components to a storage image. The view is picked at run time from T# word1 FORMAT [28:20]: *_UINT -> uint view, *_SINT -> sint view, anything else -> float view (UNORM/SNORM/FLOAT convert from the float bits the shader wrote). Missing components are 0. With d16, enabled components are packed two 16-bit values per consecutive VGPR (low half first): IEEE f16 widened to f32 for float/norm views, zero-extended u16 for UINT views, and sign-extended i16 for SINT views.""" # Cube storage images are bound as 6-layer 2D arrays (runtime/src/vulkan_bindless.h). view_dim = "dim:SQ_RSRC_IMG_2D_ARRAY" if dim == "dim:SQ_RSRC_IMG_CUBE" else dim if view_dim not in self.STORE_DIMS or any(m in mods for m in ("tfe", "lwe")): raise Unsupported("image_store " + dim.split("SQ_RSRC_IMG_")[-1] + (" a16" if "a16" in mods else "") + (" d16" if "d16" in mods else "")) di, _, _, nc = self.STORE_DIMS[view_dim] if "glc" in mods: self.coherent_images = True # a coherent store (glc, device scope): see image_load_coherent dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0xf") dmask = int(dm.split(":")[1], 0) vdata, addr = a[0], self.addr_regs(a[1]) if vdata.get("k") != "vgpr": raise Unsupported("image_store vdata") raw = [self.load_reg("vgpr", r) for r in addr] if "a16" in mods: raw = self.unpack_image_a16_uints(raw) if len(raw) < nc: raise Unsupported("image_store coords") if "d16" in mods: # Packed 16-bit data: enabled dmask components occupy consecutive 16-bit halves (low first) across # ceil(popcount(dmask) / 2) VGPRs starting at vData. n_en = sum((dmask >> c) & 1 for c in range(4)) d16_regs = [self.load_reg("vgpr", vdata["r"] + i) for i in range((n_en + 1) // 2)] f_pairs = [] for reg in d16_regs: v2 = self.tmp() self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {reg}") f_pairs.append(v2) fv, uv, sv = [], [], [] pos = 0 for c in range(4): if (dmask >> c) & 1: ri, hi = pos >> 1, pos & 1 reg = d16_regs[ri] fc = self.tmp() self.emit(f"{fc} = OpCompositeExtract %float {f_pairs[ri]} {hi}") fv.append(fc) uv.append(self.u16_half(reg, hi)) sv.append(self.i16_half(reg, hi)) pos += 1 else: fv.append(self.tof(self.cu(0))) uv.append(self.cu(0)) sv.append(self.as_int(self.cu(0))) else: # The enabled components come from consecutive VGPRs, in component order (dmask 0x9: R = vD, A = vD+1). regs = iter(range(vdata["r"], vdata["r"] + 4)) vals = [self.load_reg("vgpr", next(regs)) if dmask >> c & 1 else self.cu(0) for c in range(4)] fv = [self.tof(v) for v in vals] uv = vals sv = [self.as_int(v) for v in vals] coords = [self.as_int(c) for c in raw[:nc]] idx, kind = self.desc_lookup_sgpr(a[2], 8) idx = self.desc_storage_index(idx, kind, view_dim) t1 = self.sgpr_word(a[2], 1) self.uses_store_views.add(di) # Non-contiguous / upper-channel write masks (e.g. dmask:0x8, 0x9, 0xd, 0x2, 0x4) update only the enabled # channels of a multi-channel UAV; read-modify-write the storage image so unset channels are preserved # rather than overwritten with zero. Contiguous low masks (0x1/0x3/0x7/0xf) stay write-only. partial_rmw = dmask not in (0x0, 0x1, 0x3, 0x7, 0xF) if partial_rmw: self.uses_store_reads.add(di) for w in [16] + sum(self.int_format_masks(), []): # constants used by assemble's format masks self.cu(w) if nc == 1: iv = coords[0] else: iv = self.tmp() self.emit(f"{iv} = OpCompositeConstruct {'%v2int' if nc == 2 else '%v3int'} {' '.join(coords)}") is_u, is_s = self.fmt_int_flags(t1) v4f, v4u, v4s = self.tmp(), self.tmp(), self.tmp() self.emit(f"{v4f} = OpCompositeConstruct %v4float {' '.join(fv)}") self.emit(f"{v4u} = OpCompositeConstruct %v4uint_st {' '.join(uv)}") self.emit(f"{v4s} = OpCompositeConstruct %v4int_st {' '.join(sv)}") act = self.active_b() if di >= 2: # no writes to the shared fallback or to R32_UINT-backed logical RGB9E5 found, unpacked = self.tmp(), self.tmp() self.emit(f"{found} = OpINotEqual %bool {idx} {self.cu(0)}") self.emit(f"{unpacked} = OpLogicalNot %bool {self.packed_uav(a[2])}") act = self.emit_land(act, self.emit_land(found, unpacked)) L = {k: self.tmp() + "_" + k for k in ("do", "end", "s", "rest", "e2", "u", "f", "e3")} rmw_shuf = " ".join(str(c if (dmask >> c) & 1 else 4 + c) for c in range(4)) if partial_rmw else None def write(cls, texel, vec_ty): ip, img = self.tmp(), self.tmp() self.dynamic_storage_access(ip, f"%_ptr_UC_stv{cls}_{di}", f"%stv{cls}_{di}", idx) self.emit(f"{img} = OpLoad %stimg{cls}_{di} {ip}") if partial_rmw: old, merged = self.tmp(), self.tmp() self.emit(f"{old} = OpImageRead {vec_ty} {img} {iv}") self.emit(f"{merged} = OpVectorShuffle {vec_ty} {texel} {old} {rmw_shuf}") texel = merged self.emit(f"OpImageWrite {img} {iv} {texel}") self.emit(f"OpSelectionMerge {L['end']} None") self.emit(f"OpBranchConditional {act} {L['do']} {L['end']}") self.emit(f"{L['do']} = OpLabel") self.emit(f"OpSelectionMerge {L['e2']} None") self.emit(f"OpBranchConditional {is_s} {L['s']} {L['rest']}") self.emit(f"{L['s']} = OpLabel") write(2, v4s, "%v4int_st") self.emit(f"OpBranch {L['e2']}") self.emit(f"{L['rest']} = OpLabel") self.emit(f"OpSelectionMerge {L['e3']} None") self.emit(f"OpBranchConditional {is_u} {L['u']} {L['f']}") self.emit(f"{L['u']} = OpLabel") write(1, v4u, "%v4uint_st") self.emit(f"OpBranch {L['e3']}") self.emit(f"{L['f']} = OpLabel") write(0, v4f, "%v4float") self.emit(f"OpBranch {L['e3']}") self.emit(f"{L['e3']} = OpLabel") self.emit(f"OpBranch {L['e2']}") self.emit(f"{L['e2']} = OpLabel") self.emit(f"OpBranch {L['end']}") self.emit(f"{L['end']} = OpLabel") def resinfo_words(self, img, level, array_query, word3): """[width, height, depth, levels] (int ids) of image_get_resinfo for the uint mip level `level`, as RDNA2 returns them (measured on gfx1036 with tools/image_query_probe.py, SHADER-388): the level count of the view; past the last level (level >= levels, unsigned) width, height and depth are 0, and the size is not queried there (OpImageQuerySizeLod is undefined past the view's levels); a 2D image's depth word is 0; a 2D array's is its layer count minified like a 3D depth, max(1, layers >> (BASE_LEVEL + level)), BASE_LEVEL being T# word 3 [15:12] (`word3`, a uint id), which is also the view's first level.""" zero = self.as_int(self.cu(0)) lv, lvu, ok, safe, sz = (self.tmp() for _ in range(5)) self.emit(f"{lv} = OpImageQueryLevels %int {img}") self.emit(f"{lvu} = OpBitcast %uint {lv}") self.emit(f"{ok} = OpULessThan %bool {level} {lvu}") lod = self.as_int(level) self.emit(f"{safe} = OpSelect %int {ok} {lod} {zero}") self.emit(f"{sz} = OpImageQuerySizeLod {'%v3int' if array_query else '%v2int'} {img} {safe}") vals = [] for axis in range(3 if array_query else 2): extent = self.tmp() self.emit(f"{extent} = OpCompositeExtract %int {sz} {axis}") vals.append(extent) if array_query: base, shift, layers, mini, at_least = (self.tmp() for _ in range(5)) self.emit(f"{base} = OpBitFieldUExtract %uint {word3} {self.cu(12)} {self.cu(4)}") self.emit(f"{shift} = OpIAdd %uint {base} {level}") self.emit(f"{layers} = OpBitcast %uint {vals[2]}") self.emit(f"{mini} = OpShiftRightLogical %uint {layers} {shift}") self.emit(f"{at_least} = OpExtInst %uint %glsl UMax {mini} {self.cu(1)}") vals[2] = self.as_int(at_least) else: vals.append(zero) for i in range(3): if i < 2 or array_query: kept = self.tmp() self.emit(f"{kept} = OpSelect %int {ok} {vals[i]} {zero}") vals[i] = kept return vals + [lv] def emit_image_atomic_extra(self, op, ptr_ty, arr_var, idx, iv, vdata, mods, *, volume_active=None): """Lower 32-bit image_atomic_{swap,inc,dec,fmin,fmax,fcmpswap} on an r32ui storage image (2D or 3D). Inactive lanes skip the op and preserve vdata. CAS loops use OpAtomicLoad (valid on Image pointers) + OpAtomicCompareExchange, requiring no shader float atomic extension.""" need_n = 2 if op == "image_atomic_fcmpswap" else 1 if vdata["k"] != "vgpr" or vdata.get("n", 1) != need_n: raise Unsupported(op + " operands") val = self.load_reg("vgpr", vdata["r"]) cmpv = self.load_reg("vgpr", vdata["r"] + 1) if op == "image_atomic_fcmpswap" else None act = self.active_b() if volume_active is None else volume_active lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" self.emit(f"OpSelectionMerge {lbl_end} None") self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") self.emit(f"{lbl_do} = OpLabel") ip, tp = self.tmp(), self.tmp() self.dynamic_storage_access(ip, ptr_ty, arr_var, idx) self.emit(f"{tp} = OpImageTexelPointer %_ptr_Image_uint {ip} {iv} {self.cu(0)}") sc, sem = self.cu(1), self.cu(0) if op == "image_atomic_swap": old = self.tmp() self.emit(f"{old} = OpAtomicExchange %uint {tp} {sc} {sem} {val}") if "glc" in mods: self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, old) elif op == "image_atomic_fcmpswap": # IEEE-754 binary32 ordered equality on raw 32-bit words (denormal-safe on drivers with # shaderDenormPreserveFloat32 = false): equal iff neither is NaN and (cur == cmpv or both are +-0.0). abs_cmp, nan_cmp, init = self.tmp(), self.tmp(), self.tmp() self.emit(f"{abs_cmp} = OpBitwiseAnd %uint {cmpv} {self.cu(0x7FFFFFFF)}") self.emit(f"{nan_cmp} = OpUGreaterThan %bool {abs_cmp} {self.cu(0x7F800000)}") self.emit(f"{init} = OpAtomicLoad %uint {tp} {sc} {sem}") lbl_hdr, lbl_try, lbl_after, lbl_cont, lbl_exit = ( self.tmp() + s for s in ("_hdr", "_try", "_after", "_cont", "_exit")) self.emit(f"OpBranch {lbl_hdr}") self.emit(f"{lbl_hdr} = OpLabel") cur, got, abs_cur, nan_cur, any_nan, not_nan, same_bits, or_abs, both_zero, eq_val, eq_f = ( self.tmp() for _ in range(11)) self.emit(f"{cur} = OpPhi %uint {init} {lbl_do} {got} {lbl_cont}") self.emit(f"{abs_cur} = OpBitwiseAnd %uint {cur} {self.cu(0x7FFFFFFF)}") self.emit(f"{nan_cur} = OpUGreaterThan %bool {abs_cur} {self.cu(0x7F800000)}") self.emit(f"{any_nan} = OpLogicalOr %bool {nan_cur} {nan_cmp}") self.emit(f"{not_nan} = OpLogicalNot %bool {any_nan}") self.emit(f"{same_bits} = OpIEqual %bool {cur} {cmpv}") self.emit(f"{or_abs} = OpBitwiseOr %uint {abs_cur} {abs_cmp}") self.emit(f"{both_zero} = OpIEqual %bool {or_abs} {self.cu(0)}") self.emit(f"{eq_val} = OpLogicalOr %bool {same_bits} {both_zero}") self.emit(f"{eq_f} = OpLogicalAnd %bool {not_nan} {eq_val}") self.emit(f"OpLoopMerge {lbl_exit} {lbl_cont} None") self.emit(f"OpBranchConditional {eq_f} {lbl_try} {lbl_exit}") self.emit(f"{lbl_try} = OpLabel") self.emit(f"{got} = OpAtomicCompareExchange %uint {tp} {sc} {sem} {sem} {val} {cur}") done = self.tmp() self.emit(f"{done} = OpIEqual %bool {got} {cur}") self.emit(f"OpSelectionMerge {lbl_after} None") self.emit(f"OpBranchConditional {done} {lbl_exit} {lbl_after}") self.emit(f"{lbl_after} = OpLabel") self.emit(f"OpBranch {lbl_cont}") self.emit(f"{lbl_cont} = OpLabel") self.emit(f"OpBranch {lbl_hdr}") self.emit(f"{lbl_exit} = OpLabel") if "glc" in mods: self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, cur) else: val_f = None if op in ("image_atomic_fmin", "image_atomic_fmax"): val_f = self.tmp() self.emit(f"{val_f} = OpBitcast %float {val}") init = self.tmp() self.emit(f"{init} = OpAtomicLoad %uint {tp} {sc} {sem}") lbl_hdr, lbl_cont, lbl_exit = (self.tmp() + s for s in ("_hdr", "_cont", "_exit")) self.emit(f"OpBranch {lbl_hdr}") self.emit(f"{lbl_hdr} = OpLabel") cur, got = self.tmp(), self.tmp() self.emit(f"{cur} = OpPhi %uint {init} {lbl_do} {got} {lbl_cont}") if op == "image_atomic_inc": wrap, step, new_u = self.tmp(), self.tmp(), self.tmp() self.emit(f"{wrap} = OpUGreaterThanEqual %bool {cur} {val}") self.emit(f"{step} = OpIAdd %uint {cur} {self.cu(1)}") self.emit(f"{new_u} = OpSelect %uint {wrap} {self.cu(0)} {step}") elif op == "image_atomic_dec": is_z, gt, wrap, step, new_u = (self.tmp() for _ in range(5)) self.emit(f"{is_z} = OpIEqual %bool {cur} {self.cu(0)}") self.emit(f"{gt} = OpUGreaterThan %bool {cur} {val}") self.emit(f"{wrap} = OpLogicalOr %bool {is_z} {gt}") self.emit(f"{step} = OpISub %uint {cur} {self.cu(1)}") self.emit(f"{new_u} = OpSelect %uint {wrap} {val} {step}") else: cur_f, new_f, new_u = self.tmp(), self.tmp(), self.tmp() self.emit(f"{cur_f} = OpBitcast %float {cur}") glsl_op = "NMin" if op == "image_atomic_fmin" else "NMax" self.emit(f"{new_f} = OpExtInst %float %glsl {glsl_op} {cur_f} {val_f}") self.emit(f"{new_u} = OpBitcast %uint {new_f}") done = self.tmp() self.emit(f"{got} = OpAtomicCompareExchange %uint {tp} {sc} {sem} {sem} {new_u} {cur}") self.emit(f"{done} = OpIEqual %bool {got} {cur}") self.emit(f"OpLoopMerge {lbl_exit} {lbl_cont} None") self.emit(f"OpBranchConditional {done} {lbl_exit} {lbl_cont}") self.emit(f"{lbl_cont} = OpLabel") self.emit(f"OpBranch {lbl_hdr}") self.emit(f"{lbl_exit} = OpLabel") if "glc" in mods: self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, cur) self.emit(f"OpBranch {lbl_end}") self.emit(f"{lbl_end} = OpLabel") def image_misc(self, op, a, mods): """Query sampled image dimensions, load mip texels and handle storage image operations.""" if a and a[0]["k"] != "vgpr": # `off`, an SGPR or a constant where the VGPR range of the data goes raise Unsupported(op + " data") dim = next((m for m in mods if m.startswith("dim:")), "dim:SQ_RSRC_IMG_2D") array_query = op == "image_get_resinfo" and dim == "dim:SQ_RSRC_IMG_2D_ARRAY" is_atomic = op in self.IMG_ATOMICS or op == "image_atomic_cmpswap" or op in self.IMG_ATOMICS_EXTRA is3d_atomic = dim == "dim:SQ_RSRC_IMG_3D" and is_atomic if op == "image_store": self.image_store(a, mods, dim) return if op == "image_load_mip": if "glc" in mods: raise Unsupported("image_load_mip glc") # the coherent storage view has only one mip # x, y[, z], mip. All sampled aliases fetch that LOD; only a tagged volume UAV restricts it to zero. is3d = dim == "dim:SQ_RSRC_IMG_3D" ncoord = 3 if is3d else 2 packed = "a16" in mods status = "tfe" in mods or "lwe" in mods if (not is3d and dim != "dim:SQ_RSRC_IMG_2D") or (packed and (is3d or status)): raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1]) if is3d and status and "d16" in mods: raise Unsupported("image_load_mip d16 status") vdata, addr = a[0], self.addr_regs(a[1]) words = 2 if packed else ncoord + 1 if len(addr) < words: raise Unsupported("image_load_mip coords") idx, kind = self.desc_lookup_sgpr(a[2], 8) idx = self.desc_sampled_index(idx, kind, dim) ip, img, iv = self.tmp(), self.tmp(), self.tmp() if is3d: self.uses_tex_3d = True self.dynamic_sampled_access(ip, "%_ptr_UC_img3", "%images_3d", idx) self.emit(f"{img} = OpLoad %img3d {ip}") else: self.dynamic_sampled_access(ip, "%_ptr_UC_img", "%images", idx) self.emit(f"{img} = OpLoad %img2d {ip}") raw = [self.load_reg("vgpr", r) for r in addr[:words]] if packed: raw = self.unpack_image_a16_uints(raw) *coords, lod = [self.as_int(c) for c in raw[:ncoord + 1]] self.emit(f"{iv} = OpCompositeConstruct %v{ncoord}int {' '.join(coords)}") dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1") self.image_load_typed(dim, a[2], iv, img, idx, int(dm.split(":")[1], 0), vdata, lod=lod, d16="d16" in mods) return if ((dim != "dim:SQ_RSRC_IMG_2D" and not (is3d_atomic or array_query)) or ("a16" in mods and not is_atomic) or "d16" in mods): raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1]) vdata, addr = a[0], self.addr_regs(a[1]) idx, kind = self.desc_lookup_sgpr(a[2], 8) def atomic_coords(nc): raw = [self.load_reg("vgpr", r) for r in addr] if "a16" in mods: # 16-bit packed unsigned coordinates: two per VGPR, low half first (same as image_store). halves = [] for c in raw: lo, hi = self.tmp(), self.tmp() self.emit(f"{lo} = OpBitwiseAnd %uint {c} {self.cu(0xFFFF)}") self.emit(f"{hi} = OpShiftRightLogical %uint {c} {self.cu(16)}") halves += [lo, hi] raw = halves if len(raw) < nc: raise Unsupported(op + " coords") return [self.as_int(c) for c in raw[:nc]] if is_atomic: dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1") dmask = int(dm.split(":")[1], 0) is_64bit = ((op == "image_atomic_cmpswap" and dmask == 0xF) or ((op in self.IMG_ATOMICS or op == "image_atomic_swap") and dmask == 0x3)) if is_64bit: # 64-bit 2D R64ui image atomics (set 0 binding 29, Int64ImageEXT + Int64Atomics). if is3d_atomic: raise Unsupported(op + " 64-bit 3D") need_v = 4 if op == "image_atomic_cmpswap" else 2 if vdata["k"] != "vgpr" or vdata.get("n", 1) != need_v: raise Unsupported(op + " data") self.uses_storage64 = True coords = atomic_coords(2) iv = self.tmp() self.emit(f"{iv} = OpCompositeConstruct %v2int {coords[0]} {coords[1]}") idx = self.desc_storage_index(idx, kind, dim) def pack64(reg): lo = self.load_reg("vgpr", reg) hi = self.load_reg("vgpr", reg + 1) lo64, hi64, sh, v64 = (self.tmp() for _ in range(4)) self.emit(f"{lo64} = OpUConvert %ulong {lo}") self.emit(f"{hi64} = OpUConvert %ulong {hi}") self.emit(f"{sh} = OpShiftLeftLogical %ulong {hi64} %c64_32") self.emit(f"{v64} = OpBitwiseOr %ulong {lo64} {sh}") return v64 val64 = pack64(vdata["r"]) cmp64 = pack64(vdata["r"] + 2) if op == "image_atomic_cmpswap" else None act = self.active_b() do, end = self.tmp() + "_do", self.tmp() + "_end" self.emit(f"OpSelectionMerge {end} None") self.emit(f"OpBranchConditional {act} {do} {end}") self.emit(f"{do} = OpLabel") ip, tp, old = self.tmp(), self.tmp(), self.tmp() self.dynamic_storage_access(ip, "%_ptr_UC_simg64", "%simages64", idx) self.emit(f"{tp} = OpImageTexelPointer %_ptr_Image_ulong {ip} {iv} {self.cu(0)}") if op == "image_atomic_cmpswap": self.emit(f"{old} = OpAtomicCompareExchange %ulong {tp} {self.cu(1)} {self.cu(0)} {self.cu(0)} " f"{val64} {cmp64}") else: spv = "OpAtomicExchange" if op == "image_atomic_swap" else self.IMG_ATOMICS[op] self.emit(f"{old} = {spv} %ulong {tp} {self.cu(1)} {self.cu(0)} {val64}") if "glc" in mods: olo, ohi64, ohi = self.tmp(), self.tmp(), self.tmp() self.emit(f"{olo} = OpUConvert %uint {old}") self.emit(f"{ohi64} = OpShiftRightLogical %ulong {old} %c64_32") self.emit(f"{ohi} = OpUConvert %uint {ohi64}") self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, olo) self.dst({"k": "vgpr", "r": vdata["r"] + 1, "n": 1}, ohi) self.emit(f"OpBranch {end}") self.emit(f"{end} = OpLabel") return # 2D (binding 4) or 3D (binding 7) r32ui atomics. For tagged volumes, only a # real R32_UINT UAV with a nonzero descriptor and an active lane may write. if is3d_atomic: self.uses_storage3d = True coords = atomic_coords(3) iv = self.tmp() self.emit(f"{iv} = OpCompositeConstruct %v3int {coords[0]} {coords[1]} {coords[2]}") ptr_ty, arr_var = "%_ptr_UC_simg3", "%simages3d" found, fmt, r32 = (self.tmp() for _ in range(3)) self.emit(f"{found} = OpINotEqual %bool {idx} {self.cu(0)}") t1 = self.sgpr_word(a[2], 1) self.emit(f"{fmt} = OpBitFieldUExtract %uint {t1} {self.cu(20)} {self.cu(9)}") self.emit(f"{r32} = OpIEqual %bool {fmt} {self.cu(self.R32_UINT)}") uav, _ = self.synthetic_uav(a[2]) run = self.emit_land(self.active_b(), self.emit_land(found, self.emit_land(r32, uav))) else: self.uses_storage = True coords = atomic_coords(2) iv = self.tmp() self.emit(f"{iv} = OpCompositeConstruct %v2int {coords[0]} {coords[1]}") ptr_ty, arr_var = "%_ptr_UC_simg", "%simages" run = self.active_b() # A store, atomic or coherent read through a T# of another dimension, or through one whose image has # no storage views, goes to that dimension's storage fallback: writes and atomics there are dropped. idx = self.desc_storage_index(idx, kind, dim) if op in self.IMG_ATOMICS_EXTRA: self.emit_image_atomic_extra(op, ptr_ty, arr_var, idx, iv, vdata, mods, volume_active=run) return if op == "image_atomic_cmpswap": if vdata["k"] != "vgpr" or vdata.get("n", 1) != 2: raise Unsupported(op + " data") elif vdata["k"] != "vgpr": raise Unsupported(op + " data") val = self.load_reg("vgpr", vdata["r"]) cmpv = self.load_reg("vgpr", vdata["r"] + 1) if op == "image_atomic_cmpswap" else None act = run do, end = self.tmp() + "_do", self.tmp() + "_end" self.emit(f"OpSelectionMerge {end} None") self.emit(f"OpBranchConditional {act} {do} {end}") self.emit(f"{do} = OpLabel") # inactive lanes don't touch memory ip, tp, old = self.tmp(), self.tmp(), self.tmp() self.dynamic_storage_access(ip, ptr_ty, arr_var, idx) self.emit(f"{tp} = OpImageTexelPointer %_ptr_Image_uint {ip} {iv} {self.cu(0)}") if op == "image_atomic_cmpswap": self.emit(f"{old} = OpAtomicCompareExchange %uint {tp} {self.cu(1)} {self.cu(0)} {self.cu(0)} {val} {cmpv}") else: spv = self.IMG_ATOMICS[op] self.emit(f"{old} = {spv} %uint {tp} {self.cu(1)} {self.cu(0)} {val}") if "glc" in mods: self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, old) self.emit(f"OpBranch {end}") self.emit(f"{end} = OpLabel") return ip, img = self.tmp(), self.tmp() idx = self.desc_sampled_index(idx, kind, dim) if array_query: self.uses_tex_array = True self.dynamic_sampled_access(ip, "%_ptr_UC_imga", "%images_arr", idx) self.emit(f"{img} = OpLoad %img2da {ip}") else: self.dynamic_sampled_access(ip, "%_ptr_UC_img", "%images", idx) self.emit(f"{img} = OpLoad %img2d {ip}") dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1") dmask = int(dm.split(":")[1], 0) self.uses_query = True if op == "image_get_resinfo": vals = self.resinfo_words(img, self.load_reg("vgpr", addr[0]), array_query, self.load_reg("sgpr", a[2]["r"] + 3)) out = 0 for c in range(4): if dmask >> c & 1: u = self.tmp() self.emit(f"{u} = OpBitcast %uint {vals[c]}") self.dst({"k": "vgpr", "r": vdata["r"] + out, "n": 1}, u) out += 1 return def interp_pair_src(self, op, a, ins): """SHADER-177: the VGPR source of a v_interp_p1/p2 is the barycentric coordinate that op interpolates with — p1 reads I = v0, p2 reads J = v1, per op. The model returns the attribute's interpolated value, which is only that when the register really holds that coordinate: the hardware register, or a plain v_mov copy rooted at it (self.v_interp_copy, from interp_copy_sources, which tracks each copy's root). Anything else — the other coordinate, a copy rooted at the other one — is refused, not guessed at. A computed-I/J site (ins["ij"], interp_ij_analysis) is exempt: its operand is a value the program wrote, and attribute() weights the interpolation with that value.""" if ins.get("ij") is not None: return # computed-I/J site: the analysis vetted the source; attribute() weights with it want, role = (0, "I") if op.startswith("v_interp_p1") else (1, "J") s = a[1] if len(a) > 1 else None c = self.v_interp_copy.get(s["r"]) if (s is not None and s.get("k") == "vgpr") else None if not (s and s.get("k") == "vgpr" and s.get("n", 1) == 1 and (s["r"] == want or (c is not None and c[0] == want and c[1] < ins.get("seq", 1 << 62)))): what = f"v{s['r']}" if s is not None and s.get("k") == "vgpr" else "operand" raise Unsupported(f"{op} {role} source {what}: only v{want} (or a plain v_mov copy of it) is modelled") def interp_weights(self, ins): """(i, j) float ids for a computed-I/J v_interp site, or None for an untouched one (SHADER-177). The pair's p1 loads both operand registers and records its I; the p2 reuses that I and loads its J fresh. The program may rewrite an operand between the two ops (corpus form: J is set up after the p1), and hardware's final value uses the I of the p1 with the J of the p2. The p1's own full-sum value is dead: nothing may read the partial between the ops (interp_ij_analysis).""" tag = ins.get("ij") if tag is None: return None kind, key, i_reg, j_reg = tag if kind == "p1": i, j = self.pair_value(i_reg), self.pair_value(j_reg) self.ij_capture[key] = i return i, j cap = self.ij_capture.get(key) if cap is None: raise Unsupported("computed I/J pair: p2 emitted before its p1") return cap, self.pair_value(j_reg) def pair_value(self, r): """The value VGPR r holds now, as a float: the f32 bits the program last stored there.""" u = self.load_reg("vgpr", r) t = self.tmp() self.emit(f"{t} = OpBitcast %float {u}") return t # shortcut: --f16-interp-fallback has no PerVertexKHR inputs, so computed (i, j) reconstructs P(i, j) from the # smooth input P_c and 1-pixel OpDPdxFine / OpDPdyFine differences of (%bary.y, %bary.z, P). Binary32 rasterizer # quantization on (%bary, P) (~0.5*ulp(P_c) + |P10|*0.5*ulp(I_c) + |P20|*0.5*ulp(J_c)) is amplified by the pixel # step (1 + 2*|alpha| + 2*|beta|, ~|i - I_c| / |dI/dx| up to the primitive's pixel span), and det == 0 (including # line primitives where J is constant across the quad) returns P_c instead of extrapolating along one axis. def ij_quad_eval(self, name, comp, ij): """Approximate P(i, j) = P0 + i*(P1 - P0) + j*(P2 - P0) without PerVertexKHR inputs (--f16-interp-fallback). In real arithmetic perspective-correct BaryCoordKHR (%bary) makes smooth P affine in (I, J) across a 2x2 quad, but binary32 quad finite differences scale input rounding by (|alpha| + |beta|) pixels and fall back to P_c on a zero/subnormal/non-finite determinant. %entry precomputes the uniform 2x2 Jacobian and (P_c, dPdxFine, dPdyFine) so sites inside non-uniform branches or loops execute pure scalar ALU with no derivative ops.""" key = (name, comp) tag = self.ij_deriv.setdefault(key, len(self.ij_deriv)) i, j = ij di, dj, na0, na1, na, alp, nb0, nb1, nb, bet, mx, s, my, r0, r = (self.tmp() for _ in range(15)) self.emit(f"{di} = OpFSub %float {i} %ij_ic") self.emit(f"{dj} = OpFSub %float {j} %ij_jc") self.emit(f"{na0} = OpFMul %float {di} %ij_djy") self.emit(f"{na1} = OpFMul %float {dj} %ij_diy") self.emit(f"{na} = OpFSub %float {na0} {na1}") self.emit(f"{alp} = OpFMul %float {na} %ij_idet") self.emit(f"{nb0} = OpFMul %float %ij_dix {dj}") self.emit(f"{nb1} = OpFMul %float %ij_djx {di}") self.emit(f"{nb} = OpFSub %float {nb0} {nb1}") self.emit(f"{bet} = OpFMul %float {nb} %ij_idet") self.emit(f"{mx} = OpFMul %float {alp} %ijx_{tag}") self.emit(f"{s} = OpFAdd %float %ijc_{tag} {mx}") self.emit(f"{my} = OpFMul %float {bet} %ijy_{tag}") self.emit(f"{r0} = OpFAdd %float {s} {my}") self.emit(f"{r} = OpSelect %float %ij_nz {r0} %ijc_{tag}") return r def attribute(self, n, comp, flat=False, half=None, ij=None, vertex_delta=None): """Component `comp` of fragment input attribute n (declared as a vec4 Input at Location n). An attribute in per_vertex is a PerVertexKHR vec4[3] of the producer's raw 32-bit words. For a packed attribute, `half` 0/1 decodes its low/high f16 at each vertex; None keeps the word as an f32; the three values are then weighted as AMD does, P0 + i(P1 - P0) + j(P2 - P0) with i, j = BaryCoordKHR.y, .z, or vertex 0's taken when `flat`. `ij` overrides the weights with the given SPIR-V values (computed-I/J sites, SHADER-177: the pair the program wrote into the operand registers). `vertex_delta` 1/2 returns P1 - P0 / P2 - P0 instead (v_interp_mov_f32 p10/p20; n must be in per_vertex). --f16-interp-fallback: an f16 read (`half` 0/1) of an attribute in f16_halves is component `comp` of the smooth input at f16_half_location(n, half), which the producer fills with that half decoded to f32 (F16_HALVES). Other reads of such an attribute take the raw word as on any location (smooth, or flat = provoking vertex). Without per_vertex (--f16-interp-fallback), a computed-I/J read (`ij` not None) evaluates P(i, j) from the smooth input's %entry quad derivatives through `ij_quad_eval`.""" if half is not None and n in self.f16_halves: name = f"%in_f16h{n}_{half}" self.inputs.setdefault(name, None) # resolved in assemble() once every raw attribute is known self.interpolated.add(name) if ij is not None: return self.ij_quad_eval(name, comp, ij) p, v = self.tmp(), self.tmp() self.emit(f"{p} = OpAccessChain %_ptr_Input_float {name} {self.cu(comp)}") self.emit(f"{v} = OpLoad %float {p}") return v name = f"%in_attr{n}" self.inputs[name] = n if not flat: self.interpolated.add(name) if n not in self.per_vertex: if ij is not None: return self.ij_quad_eval(name, comp, ij) p, v = self.tmp(), self.tmp() self.emit(f"{p} = OpAccessChain %_ptr_Input_float {name} {self.cu(comp)}") self.emit(f"{v} = OpLoad %float {p}") return v self.cu(3) # the array length pv = [] for k in range(1 if flat else 3): p, v = self.tmp(), self.tmp() self.emit(f"{p} = OpAccessChain %_ptr_Input_float {name} {self.cu(k)} {self.cu(comp)}") self.emit(f"{v} = OpLoad %float {p}") if half is not None: h2, w = self.tmp(), self.tmp() self.emit(f"{h2} = OpExtInst %v2float %glsl UnpackHalf2x16 {self.tou(v)}") self.emit(f"{w} = OpCompositeExtract %float {h2} {half}") v = w pv.append(v) if flat: return pv[0] if vertex_delta is not None: d = self.tmp() self.emit(f"{d} = OpFSub %float {pv[vertex_delta]} {pv[0]}") return d if ij is not None: i, j = ij else: bc = self.tmp() self.emit(f"{bc} = OpLoad %v3float %bary") i, j = self.tmp(), self.tmp() self.emit(f"{i} = OpCompositeExtract %float {bc} 1") self.emit(f"{j} = OpCompositeExtract %float {bc} 2") d1, d2, m1, m2, s, r = (self.tmp() for _ in range(6)) self.emit(f"{d1} = OpFSub %float {pv[1]} {pv[0]}") self.emit(f"{d2} = OpFSub %float {pv[2]} {pv[0]}") if half is not None: # The SPI writes P10/P20 for a 16-bit channel as per-half f16 differences (SHADER-468: measured on # gfx1036, an f16 delta overflows to inf where the f32 difference does not), so each delta is rounded # to f16 before it is weighted. The weights and the sum stay f32 (measured: an exact f32 sum explains # 65,536 of 65,536 samples, an f16 sum 57,583). d1, d2 = self.f16_round(d1), self.f16_round(d2) self.emit(f"{m1} = OpFMul %float {d1} {i}") self.emit(f"{s} = OpFAdd %float {pv[0]} {m1}") self.emit(f"{m2} = OpFMul %float {d2} {j}") self.emit(f"{r} = OpFAdd %float {s} {m2}") return r def texel_offset_fold(self, img, si, uv, off, n_off, ncoord, kind, implicit, lod, bias, s_op): """--texel-offset-fallback: return (uv + offset / size of the sampled level, implicit-LOD gradients or None). The level is 0 for _lz / _c_lz (and for implicit samples outside the PS, which sample LOD 0), the given LOD for _l, and OpImageQueryLod's for implicit samples (plus the bias for _b), rounded the way the S#'s MIP_FILTER (word 2 [27:26]) selects a level and clamped to the image's levels: floored for linear, nearest with a tie rounding up (floor(lod + 0.5), as an RTX 5070 samples LOD 0.5 at mip 1 and image_query_probe.py records for RDNA2) for point and for the value 3, which the runtime also samples as nearest, and 0 for none, whose LOD the runtime holds in [0, 0.25] (gfx10_descriptors.h vulkan_sampler). Texel offsets apply before wrapping and clamping, and an integer offset commutes with them, so the shift is exact for any address mode at that level. Only a trilinear blend of two levels differs: the coarser level moves by offset / 2 of its texels instead of offset. Implicit samples become Grad samples with the derivatives of the original coordinate (scaled by 2^bias for _b): the LOD and anisotropy are those of the unshifted sample, even when the offset changes from pixel to pixel.""" self.uses_query = True ci = lambda v: self.as_int(self.cu(v)) lv, lvm = self.tmp(), self.tmp() self.emit(f"{lv} = OpImageQueryLevels %int {img}") self.emit(f"{lvm} = OpISub %int {lv} {ci(1)}") spatial = n_off # 1D: 1, 2D / 2D array: 2, 3D: 3 (array layer excluded) vf = {1: "%float", 2: "%v2float", 3: "%v3float"}[spatial] vi = {1: "%int", 2: "%v2int", 3: "%v3int"}[spatial] uvs = uv if ncoord > spatial: # 2D array: the spatial part of (u, v, layer) uvs = self.tmp() self.emit(f"{uvs} = OpVectorShuffle %v2float {uv} {uv} 0 1") level_f = None if kind == "_l": level_f = lod if lod is not None else "%f0" elif implicit: q, qx = self.tmp(), self.tmp() self.emit(f"{q} = OpImageQueryLod %v2float {si} {uvs}") self.emit(f"{qx} = OpCompositeExtract %float {q} 0") level_f = qx if kind in ("_b", "_c_b") and bias is not None: qb = self.tmp() self.emit(f"{qb} = OpFAdd %float {qx} {bias}") level_f = qb elif kind in ("_b", "_c_b"): level_f = lod if lod is not None else bias mip = None if level_f is not None: lit = self.sgpr_imm.get(s_op["r"] + 2) if lit is not None: mip = lit >> 26 & 3 else: mip = self.tmp() self.emit(f"{mip} = OpBitFieldUExtract %uint {self.load_reg('sgpr', s_op['r'] + 2)} " f"{self.cu(26)} {self.cu(2)}") if mip == 0: level_f = None if level_f is None: level = ci(0) else: static = isinstance(mip, int) fl, li = self.tmp(), self.tmp() # linear: the finer of the two blended levels self.emit(f"{fl} = OpExtInst %float %glsl Floor {level_f}") self.emit(f"{li} = OpConvertFToS %int {fl}") if not static or mip != 2: # point (and 3): nearest level, a tie rounds up # floor + (fraction >= 0.5), not floor(lod + 0.5): lod - floor(lod) is exact in binary32, the sum # is not (0x3f000001 + 0.5 rounds to 1.0, and 0x3effffff + 0.5 rounds up to 1.0 as well). fr, up, inc, near = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{fr} = OpFSub %float {level_f} {fl}") self.emit(f"{up} = OpFOrdGreaterThanEqual %bool {fr} {self.fconst(0.5)}") self.emit(f"{inc} = OpSelect %int {up} {ci(1)} {ci(0)}") self.emit(f"{near} = OpIAdd %int {li} {inc}") if static: li = near else: lin, none, pick, sel = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{lin} = OpIEqual %bool {mip} {self.cu(2)}") self.emit(f"{pick} = OpSelect %int {lin} {li} {near}") self.emit(f"{none} = OpIEqual %bool {mip} {self.cu(0)}") self.emit(f"{sel} = OpSelect %int {none} {ci(0)} {pick}") li = sel lo = self.tmp() self.emit(f"{lo} = OpExtInst %int %glsl SClamp {li} {ci(0)} {lvm}") level = lo # Size of that level: 1D int, 2D v2int, 2D array / 3D v3int (array: width, height, layers). qtype = "%int" if ncoord == 1 else "%v3int" if ncoord == 3 else "%v2int" sz = self.tmp() self.emit(f"{sz} = OpImageQuerySizeLod {qtype} {img} {level}") if qtype == "%v3int" and spatial == 2: szs = self.tmp() self.emit(f"{szs} = OpVectorShuffle %v2int {sz} {sz} 0 1") sz = szs szf, offf, sh, uvn = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{szf} = OpConvertSToF {vf} {sz}") self.emit(f"{offf} = OpConvertSToF {vf} {off}") self.emit(f"{sh} = OpFDiv {vf} {offf} {szf}") self.emit(f"{uvn} = OpFAdd {vf} {uvs} {sh}") out = uvn if ncoord > spatial: layer, full = self.tmp(), self.tmp() self.emit(f"{layer} = OpCompositeExtract %float {uv} 2") self.emit(f"{full} = OpCompositeConstruct %v3float {uvn} {layer}") out = full grads = None if implicit: dx, dy = self.tmp(), self.tmp() self.emit(f"{dx} = OpDPdx {vf} {uvs}") self.emit(f"{dy} = OpDPdy {vf} {uvs}") if kind in ("_b", "_c_b") and bias is not None: e, ev, sdx, sdy = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{e} = OpExtInst %float %glsl Exp2 {bias}") if spatial == 1: self.emit(f"{sdx} = OpFMul %float {dx} {e}") self.emit(f"{sdy} = OpFMul %float {dy} {e}") else: self.emit(f"{sdx} = OpVectorTimesScalar {vf} {dx} {e}") self.emit(f"{sdy} = OpVectorTimesScalar {vf} {dy} {e}") dx, dy = sdx, sdy grads = (dx, dy) return out, grads def as_int(self, u): i = self.tmp() self.emit(f"{i} = OpBitcast %int {u}") return i def as_uint(self, i): u = self.tmp() self.emit(f"{u} = OpBitcast %uint {i}") return u # ---- legacy (merged ES/GS) geometry shader on LDS rings ---- # Inputs: input vertex i sits at the dword offset the system VGPRs give (v0 lo/hi, v1 lo); the entry sets them # to 64*i, so an LDS read at byte address A + offset is vertex A >> 8, dword ((offset/4) mod 64) = 4*reg + comp # of the ES output (= the GS input signature register). Outputs: every LDS write goes to the per-lane GSVS # area: emitted vertex k is dwords [k*4*nreg, (k+1)*4*nreg), dword = 4*reg + comp of the GS output signature # (checked on $GS_VoxelizeGeneric: 20 dwords = 5 output registers, writes match every declared mask). # EMIT copies slot to the outputs and emits; CUT ends the strip. GS_VTX_DW = 64 def gs_when_active(self, instr): act = self.active_b() do, end = self.tmp() + "_do", self.tmp() + "_end" self.emit(f"OpSelectionMerge {end} None") self.emit(f"OpBranchConditional {act} {do} {end}") self.emit(f"{do} = OpLabel") self.emit(instr) self.emit(f"OpBranch {end}") self.emit(f"{end} = OpLabel") def gs_ds(self, op, a, mods): nreg = self.gs["nreg"] if op in ("ds_read_b32", "ds_read_b64", "ds_read_b96", "ds_read_b128", "ds_read2_b32", "ds_read2st64_b32"): if op in ("ds_read2_b32", "ds_read2st64_b32"): dws = [offset // 4 for offset in self.lds_pair_byte_offsets(op, mods)] else: n = self.LDS_WORDS[op.rsplit("_", 1)[1]] base = self.mod_int(mods, "offset", 0) if base % 4: raise Unsupported("gs lds read alignment") dws = [base // 4 + k for k in range(n)] addr = self.src_u(a[1]) vtx = self.tmp() self.emit(f"{vtx} = OpShiftRightLogical %uint {addr} {self.cu(8)}") for k, dw in enumerate(dws): vertex_delta, dw = divmod(dw, self.GS_VTX_DW) vertex = vtx # A 64-dword stride walks the ES/GS input vertices at a fixed component. if op == "ds_read2st64_b32" and vertex_delta: vertex = self.tmp() self.emit(f"{vertex} = OpIAdd %uint {vtx} {self.cu(vertex_delta)}") reg, comp = dw // 4, dw % 4 regs = {r: sv for r, sv in self.gs["in"]} if reg in regs: var = "%gs_in_pos" if regs[reg] == 1 else f"%gs_in{reg}" pp, v4, c = self.tmp(), self.tmp(), self.tmp() self.emit(f"{pp} = OpAccessChain %_ptr_Input_v4 {var} {vertex}") self.emit(f"{v4} = OpLoad %v4float {pp}") self.emit(f"{c} = OpCompositeExtract %float {v4} {comp}") val = self.tou(c) else: val = self.cu(0) self.dst({"k": "vgpr", "r": a[0]["r"] + k, "n": 1}, val) return if op in ("ds_write_b32", "ds_write_b64", "ds_write_b96", "ds_write_b128", "ds_write2_b32", "ds_write2st64_b32"): if op in ("ds_write2_b32", "ds_write2st64_b32"): offsets = self.lds_pair_byte_offsets(op, mods) items = [(offsets[0] // 4, a[1]), (offsets[1] // 4, a[2])] elif op == "ds_write_b32": items = [(self.mod_int(mods, "offset", 0) // 4, a[1])] else: base = self.mod_int(mods, "offset", 0) // 4 n = self.LDS_WORDS[op.rsplit("_", 1)[1]] items = [(base + k, {"k": "vgpr", "r": a[1]["r"] + k, "n": 1}) for k in range(n)] for dw, src in items: slot, rem = divmod(dw, 4 * nreg) if slot >= self.gs["maxv"]: raise Unsupported("gs output slot") reg, comp = rem // 4, rem % 4 v = self.tof(self.src_u(src)) pp, old, new, sel = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{pp} = OpAccessChain %_ptr_Function_v4_gs %gs_stage {self.cu(slot * nreg + reg)}") self.emit(f"{old} = OpLoad %v4float {pp}") self.emit(f"{new} = OpCompositeInsert %v4float {v} {old} {comp}") self.emit(f"{sel} = OpSelect %v4float {self.active_b()} {new} {old}") self.emit(f"OpStore {pp} {sel}") return raise Unsupported(op + " in gs") def gs_emit(self, *, end_primitive: bool) -> None: nreg = self.gs["nreg"] act = self.active_b() do, end = self.tmp() + "_do", self.tmp() + "_end" self.emit(f"OpSelectionMerge {end} None") self.emit(f"OpBranchConditional {act} {do} {end}") self.emit(f"{do} = OpLabel") k, base = self.tmp(), self.tmp() self.emit(f"{k} = OpLoad %uint %gs_emitted") self.emit(f"{base} = OpIMul %uint {k} {self.cu(nreg)}") for reg, sv in self.gs["out"]: i, pp, v = self.tmp(), self.tmp(), self.tmp() self.emit(f"{i} = OpIAdd %uint {base} {self.cu(reg)}") self.emit(f"{pp} = OpAccessChain %_ptr_Function_v4_gs %gs_stage {i}") self.emit(f"{v} = OpLoad %v4float {pp}") self.emit(f"OpStore {'%gs_out_pos' if sv == 1 else f'%gs_out{reg}'} {v}") self.emit("OpEmitVertex") if end_primitive: self.emit("OpEndPrimitive") k2 = self.tmp() self.emit(f"{k2} = OpIAdd %uint {k} {self.cu(1)}") self.emit(f"OpStore %gs_emitted {k2}") self.emit(f"OpBranch {end}") self.emit(f"{end} = OpLabel") # ---- ray tracing: image_bvh(64)_intersect_ray ---- def image_bvh(self, op, a, mods): """One BVH traversal step against AMD's hardware node format, emulated over buffer reads. Semantics follow Mesa RADV's software path (radv_nir_rt_common.c: intersect_ray_amd_software_box / _tri), which RADV uses in place of this instruction. Node id = byte address >> 3 with the node type in bits [2:0]: 0..3 triangle, 4 box16, 5 box32. Address = descriptor base + ((node & ~7) << 3); the base is BVH descriptor bits [39:0] taken in 256-byte units (ASSUMPTION: RADV only ever uses base 0). Box nodes return the four child ids (misses and inactive boxes = 0xFFFFFFFF), sorted by entry distance when the descriptor's box_sort_enable (bit 63) is set. Triangle nodes read the vertex slots of their type (TRI0 0,1,2; TRI1 1,3,2; TRI2 2,3,4; TRI3 2,4,0) and return the words measured on RDNA2 (docs/design.md, Ray tracing row): with T, det and the edge functions of the watertight test, k = |d[kz]|^3, a hit gives k*(T, det, b_i, b_j) and a miss (copysign(inf, k*det), k*det, k*b_i, k*b_j), i and j chosen by the node type's byte of the triangle-ID word at +60 (AMD GPURT; 0x09 is RADV's v, w). A NaN anywhere in the ray, or an infinite origin, gives (inf, 1, 0, 0). Consumers divide by .y: t = T/det and the barycentrics b/det.""" if "a16" in mods: raise Unsupported(op + " a16") is64 = op.startswith("image_bvh64") self.uses_bvh = True vd = a[0] regs = self.addr_regs(a[1]) need = 12 if is64 else 11 if len(regs) < need or vd["k"] != "vgpr": raise Unsupported(op + " operands") desc = self.sgpr_words(a[2], 4) ld = lambda r: self.load_reg("vgpr", r) self.uses_psb = True self.uses_long = True e = self.emit T = self.tmp def u64(lo, hi): l, h, sh, r = T(), T(), T(), T() e(f"{l} = OpUConvert %ulong {lo}") e(f"{h} = OpUConvert %ulong {hi}") e(f"{sh} = OpShiftLeftLogical %ulong {h} %c64_32") e(f"{r} = OpBitwiseOr %ulong {sh} {l}") return r # descriptor base (bits [39:0], 256-byte units) and sort flag bhi, base40, base = T(), T(), T() e(f"{bhi} = OpBitwiseAnd %uint {desc[1]} {self.cu(0xFF)}") base40 = u64(desc[0], bhi) e(f"{base} = OpShiftLeftLogical %ulong {base40} {self.cl(8)}") sortb, sort = T(), T() e(f"{sortb} = OpShiftRightLogical %uint {desc[1]} {self.cu(31)}") e(f"{sort} = OpINotEqual %bool {sortb} {self.cu(0)}") # node id if is64: node = u64(ld(regs[0]), ld(regs[1])) rest = regs[2:] else: n32 = T() e(f"{n32} = OpUConvert %ulong {ld(regs[0])}") node = n32 rest = regs[1:] nlo, ntype = T(), T() e(f"{nlo} = OpUConvert %uint {node}") e(f"{ntype} = OpBitwiseAnd %uint {nlo} {self.cu(7)}") nm, off, addr = T(), T(), T() e(f"{nm} = OpBitwiseAnd %ulong {node} {self.cl(0xFFFFFFFFFFFFFFF8)}") e(f"{off} = OpShiftLeftLogical %ulong {nm} {self.cl(3)}") e(f"{addr} = OpIAdd %ulong {base} {off}") act = self.active_b() L = {k: T() + "_" + k for k in ("act", "tri", "nt", "box", "oth", "end1", "end2", "act_end")} # Inactive lanes (EXEC == 0) in a divergent traversal loop can hold stale or null node pointers; # guard all PhysicalStorageBuffer loads so masked-off lanes never fault and leave vdst untouched. e(f"OpSelectionMerge {L['act_end']} None") e(f"OpBranchConditional {act} {L['act']} {L['act_end']}") e(f"{L['act']} = OpLabel") ptr = T() def node_delta(): """--address-guard: a box32 node (type 5) is read up to dword 27, the others up to dword 15.""" b32, d = T(), T() e(f"{b32} = OpIEqual %bool {ntype} {self.cu(5)}") e(f"{d} = OpSelect %ulong {b32} {self.cl(4 * 28 - 1)} {self.cl(4 * 16 - 1)}") return d e(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr, 'load', node_delta)}") def ldw(i): pp, v = T(), T() e(f"{pp} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") e(f"{v} = OpLoad %uint {pp} Aligned 4") return v f = lambda r: self.tof(ld(r)) tmax = f(rest[0]) org = [f(r) for r in rest[1:4]] dirv = [f(r) for r in rest[4:7]] inv = [f(r) for r in rest[7:10]] INF, ONE, NEGINF = (self.tof(self.cu(x)) for x in (0x7F800000, 0x3F800000, 0xFF800000)) out = lambda k, v: self.dst({"k": "vgpr", "r": vd["r"] + k, "n": 1}, v) def fop(o, x, y): r = T() e(f"{r} = {o} %float {x} {y}") return r def fext(name, *xs): r = T() e(f"{r} = OpExtInst %float %glsl {name} {' '.join(xs)}") return r def bop(o, x, y): r = T() e(f"{r} = {o} %bool {x} {y}") return r def sel(c, x, y, ty="%float"): r = T() e(f"{r} = OpSelect {ty} {c} {x} {y}") return r def usel_k(c, k, x, invert=False): """c ? k : x (or c ? x : k with invert) for a constant k whose bits are a float NaN. Built as (x & ~m) | (k & m) with m a select of two constants, not as an OpSelect between x and k: KosmicKrisp (Mesa 26.3.1) types an OpSelect by the first concrete type that reaches it, which is float when x came from a bitcast float or shares a register with one, and then prints k as the literal (NAN), which Metal reads as 0x7FC00000 (#6623). Its bitwise ops never take a float type, so they keep k an integer whatever x is.""" kc, zc = self.cu(k), self.cu(0) km = sel(c, zc, kc, "%uint") if invert else sel(c, kc, zc, "%uint") # k where k is chosen, else 0 r = T() if k == 0xFFFFFFFF: # x | km alone gives k where km is set e(f"{r} = OpBitwiseOr %uint {x} {km}") return r ones = self.cu(0xFFFFFFFF) xkeep, xm = (sel(c, ones, zc, "%uint") if invert else sel(c, zc, ones, "%uint")), T() e(f"{xm} = OpBitwiseAnd %uint {x} {xkeep}") e(f"{r} = OpBitwiseOr %uint {xm} {km}") return r is_tri, is_b16, is_box = T(), T(), T() e(f"{is_tri} = OpULessThan %bool {ntype} {self.cu(4)}") e(f"{is_b16} = OpIEqual %bool {ntype} {self.cu(4)}") bx16 = T() e(f"{bx16} = OpIEqual %bool {ntype} {self.cu(5)}") e(f"{is_box} = OpLogicalOr %bool {is_b16} {bx16}") e(f"OpSelectionMerge {L['end1']} None") e(f"OpBranchConditional {is_tri} {L['tri']} {L['nt']}") # ---------------- triangle ---------------- e(f"{L['tri']} = OpLabel") # The node type picks the triangle's vertex slots in the 64-byte node (12 bytes each; slot 4 is the # metadata words 12..14): TRI0 (0,1,2), TRI1 (1,3,2), TRI2 (2,3,4), TRI3 (2,4,0). AMD GPURT # CalcTriangleCompressionVertexIndices; the XDXR software path's Read3Verts (docs/bvh.md 7a). def ldw_dyn(i): pp, v = T(), T() e(f"{pp} = OpAccessChain %_ptr_PSB_uint {ptr} {i}") e(f"{v} = OpLoad %uint {pp} Aligned 4") return v nsh = T() e(f"{nsh} = OpShiftLeftLogical %uint {ntype} {self.cu(2)}") V = [] for table in (0x2210, 0x4331, 0x0422): # slot of vertex j for node types 0..3, one nibble each slot, w0 = T(), T() e(f"{slot} = OpBitFieldUExtract %uint {self.cu(table)} {nsh} {self.cu(4)}") e(f"{w0} = OpIMul %uint {slot} {self.cu(3)}") row = [] for c in range(3): wc = w0 if c: wc = T() e(f"{wc} = OpIAdd %uint {w0} {self.cu(c)}") row.append(self.tof(ldw_dyn(wc))) V.append(row) ad = [fext("FAbs", d) for d in dirv] c01, c02, c12 = bop("OpFOrdGreaterThanEqual", ad[0], ad[1]), bop("OpFOrdGreaterThanEqual", ad[0], ad[2]), \ bop("OpFOrdGreaterThanEqual", ad[1], ad[2]) k_a = sel(c02, self.cu((0 << 4) | (2 << 2) | 1), self.cu((2 << 4) | (1 << 2) | 0), "%uint") k_b = sel(c12, self.cu((1 << 4) | (0 << 2) | 2), self.cu((2 << 4) | (1 << 2) | 0), "%uint") pk = sel(c01, k_a, k_b, "%uint") kx0, ky0, kz = T(), T(), T() e(f"{kx0} = OpBitwiseAnd %uint {pk} {self.cu(3)}") e(f"{ky0} = OpBitFieldUExtract %uint {pk} {self.cu(2)} {self.cu(2)}") e(f"{kz} = OpShiftRightLogical %uint {pk} {self.cu(4)}") dvec = T() e(f"{dvec} = OpCompositeConstruct %v3float {' '.join(dirv)}") def vx(vec, i): r = T() e(f"{r} = OpVectorExtractDynamic %float {vec} {i}") return r dkz = vx(dvec, kz) neg = bop("OpFOrdLessThan", dkz, "%f0") kx = sel(neg, ky0, kx0, "%uint") ky = sel(neg, kx0, ky0, "%uint") # Measured on RDNA2 (docs/design.md, Ray tracing row): the words are the watertight test's T, det and edge # functions, scaled by k = |d[kz]|^3. They are computed here without a division, with the shear multiplied # through by |d[kz]| (A'' = |d[kz]| A' = A[kx] |d[kz]| - sign(d[kz]) d[kx] A[kz]), so U, V, W and det carry # |d[kz]|^2 and the sum below sign(d[kz]) |d[kz]|^3 T. The supplied inverse direction is not used. A shear # divided by d[kz] gives the same words on every measured row but d.z = +inf (and divides by zero at d = 0); # this form gives that row too, a fit after the runs. adz = fext("FAbs", dkz) NEG1 = self.tof(self.cu(0xBF800000)) sgz = sel(neg, NEG1, ONE) sx = fop("OpFMul", sgz, vx(dvec, kx)) # sign(d[kz]) d[kx], sign(d[kz]) d[ky] sy = fop("OpFMul", sgz, vx(dvec, ky)) rel = [] for j in range(3): vv = T() comps = [fop("OpFSub", V[j][c], org[c]) for c in range(3)] e(f"{vv} = OpCompositeConstruct %v3float {' '.join(comps)}") rel.append(vv) def shear(vv): zk = vx(vv, kz) return (fop("OpFSub", fop("OpFMul", vx(vv, kx), adz), fop("OpFMul", sx, zk)), fop("OpFSub", fop("OpFMul", vx(vv, ky), adz), fop("OpFMul", sy, zk)), zk) (ax, ay, az0), (bx, by, bz0), (cx, cy, cz0) = (shear(r) for r in rel) uu = fop("OpFSub", fop("OpFMul", cx, by), fop("OpFMul", cy, bx)) vv_ = fop("OpFSub", fop("OpFMul", ax, cy), fop("OpFMul", ay, cx)) ww = fop("OpFSub", fop("OpFMul", bx, ay), fop("OpFMul", by, ax)) lt0 = lambda x: bop("OpFOrdLessThan", x, "%f0") gt0 = lambda x: bop("OpFOrdGreaterThan", x, "%f0") eq0 = lambda x: bop("OpFOrdEqual", x, "%f0") orr = lambda x, y: bop("OpLogicalOr", x, y) andd = lambda x, y: bop("OpLogicalAnd", x, y) det = fop("OpFAdd", uu, fop("OpFAdd", vv_, ww)) tt = fop("OpFAdd", fop("OpFAdd", fop("OpFMul", uu, az0), fop("OpFMul", vv_, bz0)), fop("OpFMul", ww, cz0)) tk = fop("OpFMul", sgz, tt) # k*T # Inside: det is not 0 or NaN, and every edge function has det's sign, or is 0 and its edge passes RDNA2's tie # rule (docs/design.md, Ray tracing row; measured with x, y and z dominant, both windings, both signs of # d[kz]): the edge from P to Q, with (tx, ty) = Q - P in the sheared frame with the d[kz] < 0 swap undone, # passes when ty == 0 ? sign(det) tx > 0 : sign(d[kz]) sign(det) ty > 0. Hit: inside and sign(det) T >= 0 # (t = 0 hits); there is no test against the ray extent. Every compare is ordered, so a NaN fails it. dpos, dneg = gt0(det), lt0(det) sd = sel(dpos, ONE, NEG1) sdz = fop("OpFMul", sgz, sd) # sign(d[kz]) sign(det) def inside(x, p, q): tx, ty = fop("OpFSub", q[0], p[0]), fop("OpFSub", q[1], p[1]) tx, ty = sel(neg, ty, tx), sel(neg, tx, ty) # undo the kx/ky swap of d[kz] < 0 tie = sel(eq0(ty), gt0(fop("OpFMul", sd, tx)), gt0(fop("OpFMul", sdz, ty)), "%bool") return sel(eq0(x), tie, gt0(fop("OpFMul", sd, x)), "%bool") a2, b2, c2 = (ax, ay), (bx, by), (cx, cy) front = bop("OpFOrdGreaterThanEqual", fop("OpFMul", sd, tk), "%f0") hit = andd(andd(orr(dpos, dneg), andd(inside(uu, b2, c2), inside(vv_, c2, a2))), andd(inside(ww, a2, b2), front)) # The node's triangle-ID word (byte offset 60) holds one byte per node type: bits [1:0] pick which vertex's # weight is returned first, bits [3:2] the second (0 = vertex 0's, U; 1 = V; 2 = W; 3 is not used by a # builder and reads U, as in the XDXR software path). 0x09 is the plain (V, W). AMD GPURT # SwizzleBarycentrics and TRIANGLE_ID_I/J_SRC_SHIFT; XDXR TestXboxBvh4Leaf (docs/bvh.md 7a). tid, tsh, tby = T(), T(), T() e(f"{tsh} = OpShiftLeftLogical %uint {ntype} {self.cu(3)}") e(f"{tid} = OpShiftRightLogical %uint {ldw(15)} {tsh}") e(f"{tby} = OpBitwiseAnd %uint {tid} {self.cu(0xF)}") def pick(shift): s_ = T() e(f"{s_} = OpBitFieldUExtract %uint {tby} {self.cu(shift)} {self.cu(2)}") is1, is2 = T(), T() e(f"{is1} = OpIEqual %bool {s_} {self.cu(1)}") e(f"{is2} = OpIEqual %bool {s_} {self.cu(2)}") return sel(is2, ww, sel(is1, vv_, uu)) # The four words, hit or miss: (k*T, k*det, k*b_i, k*b_j). The hardware returns every zero as +0, where IEEE # arithmetic gives -0 for some (t = 0, an edge function through a vertex on the ray), and every NaN as # 0xFFC00000. SPIR-V leaves a NaN's bits to the driver, and a zero's sign too without float controls, so both # are fixed by a select on the integer side. A miss replaces word 0 with copysign(inf, word 1): det = 0 gives # +inf, a NaN det -inf. def canon(x): u, nan = self.tou(x), T() e(f"{nan} = OpIsNan %bool {x}") return usel_k(nan, 0xFFC00000, sel(eq0(x), self.cu(0), u, "%uint")) w = [canon(x) for x in [tk] + [fop("OpFMul", adz, x) for x in (det, pick(0), pick(2))]] sgn, minf = T(), T() e(f"{sgn} = OpBitwiseAnd %uint {w[1]} {self.cu(0x80000000)}") e(f"{minf} = OpBitwiseOr %uint {sgn} {self.cu(0x7F800000)}") w[0] = sel(hit, w[0], minf, "%uint") # A NaN in t max, the origin, the direction or the inverse direction (an axis nothing else reads included), # or an infinite origin, returns (inf, 1, 0, 0) whatever the node holds. bad = None for x, test in [(tmax, "OpIsNan")] + [(x, "OpIsNan") for x in org + dirv + inv] + [(x, "OpIsInf") for x in org]: b = T() e(f"{b} = {test} %bool {x}") bad = b if bad is None else orr(bad, b) for k, (v, c) in enumerate(zip(w, (0x7F800000, 0x3F800000, 0, 0))): out(k, sel(bad, self.cu(c), v, "%uint")) e(f"OpBranch {L['end1']}") # ---------------- not a triangle ---------------- e(f"{L['nt']} = OpLabel") e(f"OpSelectionMerge {L['end2']} None") e(f"OpBranchConditional {is_box} {L['box']} {L['oth']}") e(f"{L['box']} = OpLabel") dist, idx = [], [] for i in range(4): child = ldw(i) # box32: min/max f32 at 16 + 24 i; box16: 6 halves at 16 + 12 i (min x,y,z, max x,y,z) m32 = [self.tof(ldw(4 + 6 * i + c)) for c in range(6)] h = [ldw(4 + 3 * i + c) for c in range(3)] m16 = [] for w in h: v2 = T() e(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {w}") for c in range(2): x = T() e(f"{x} = OpCompositeExtract %float {v2} {c}") m16.append(x) mm = [sel(is_b16, m16[c], m32[c]) for c in range(6)] b0 = [self.f32_mul_rtz(self.f32_sub_rtz(mm[c], org[c]), inv[c]) for c in range(3)] b1 = [self.f32_mul_rtz(self.f32_sub_rtz(mm[3 + c], org[c]), inv[c]) for c in range(3)] near, far, nnan, fnan = [], [], [], [] for c in range(3): pos = bop("OpFOrdGreaterThanEqual", inv[c], "%f0") n_, f_ = sel(pos, b0[c], b1[c]), sel(pos, b1[c], b0[c]) nn, fn = T(), T() e(f"{nn} = OpIsNan %bool {n_}") e(f"{fn} = OpIsNan %bool {f_}") near.append(sel(nn, NEGINF, n_)) far.append(sel(fn, INF, f_)) nnan.append(nn) fnan.append(fn) tmin = fext("FMax", fext("FMax", near[0], near[1]), near[2]) tmx = fext("FMin", fext("FMin", far[0], far[1]), far[2]) nonan = T() e(f"{nonan} = OpLogicalNot %bool " f"{orr(andd(andd(nnan[0], nnan[1]), nnan[2]), andd(andd(fnan[0], fnan[1]), fnan[2]))}") tnear = fext("FMax", "%f0", tmin) h1 = bop("OpFOrdGreaterThanEqual", tmx, tnear) h2 = bop("OpFOrdLessThan", tmin, tmax) hb = andd(nonan, andd(h1, h2)) dist.append(sel(hb, tnear, INF)) idx.append(usel_k(hb, 0xFFFFFFFF, child, invert=True)) for p_, q_ in ((0, 2), (1, 3), (0, 1), (2, 3), (1, 2)): sw = andd(sort, bop("OpFOrdLessThan", dist[q_], dist[p_])) dist[p_], dist[q_] = sel(sw, dist[q_], dist[p_]), sel(sw, dist[p_], dist[q_]) idx[p_], idx[q_] = sel(sw, idx[q_], idx[p_], "%uint"), sel(sw, idx[p_], idx[q_], "%uint") for k in range(4): out(k, idx[k]) e(f"OpBranch {L['end2']}") e(f"{L['oth']} = OpLabel") for k in range(4): # instance / aabb nodes are handled by the shader, not the instruction out(k, self.cu(0xFFFFFFFF)) e(f"OpBranch {L['end2']}") e(f"{L['end2']} = OpLabel") e(f"OpBranch {L['end1']}") e(f"{L['end1']} = OpLabel") e(f"OpBranch {L['act_end']}") e(f"{L['act_end']} = OpLabel") def export_misc_pos1(self, srcs, act, layer_var, viewport_var): """GFX9+ misc vector at pos1: z[10:0] = Layer, z[19:16] = ViewportIndex. Stages the lanes on in `act` into the int variables named (the VS Output builtins, or the mesh shader's per-invocation staging variables).""" if len(srcs) < 3 or (srcs[2]["k"] == "special" and srcs[2]["t"] == "off"): return z = self.src_u(srcs[2]) if 4 in self.pos_misc: self.uses_layer = True lu, li, old, sel = self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{lu} = OpBitwiseAnd %uint {z} {self.cu(0x7FF)}") self.emit(f"{li} = OpBitcast %int {lu}") self.emit(f"{old} = OpLoad %int {layer_var}") self.emit(f"{sel} = OpSelect %int {act} {li} {old}") self.emit(f"OpStore {layer_var} {sel}") if 5 in self.pos_misc: self.uses_viewport = True vs_, vu, vi, old, sel = self.tmp(), self.tmp(), self.tmp(), self.tmp(), self.tmp() self.emit(f"{vs_} = OpShiftRightLogical %uint {z} {self.cu(16)}") self.emit(f"{vu} = OpBitwiseAnd %uint {vs_} {self.cu(0xF)}") self.emit(f"{vi} = OpBitcast %int {vu}") self.emit(f"{old} = OpLoad %int {viewport_var}") self.emit(f"{sel} = OpSelect %int {act} {vi} {old}") self.emit(f"OpStore {viewport_var} {sel}") def ms_export(self, tgt, ins): """NGG export in a mesh shader: thread t exports vertex t (pos/param) and primitive t (prim). The values are staged in per-invocation variables and written to the mesh outputs at shader end, after OpSetMeshOutputsEXT (see assemble). Exports whose operands are all 'off' are the dummy exports a wave with no vertices must still issue: they write nothing.""" a = ins["args"] srcs = a[1:5] if all(x["k"] == "special" and x["t"] == "off" for x in srcs): return act = self.active_b() if tgt == "prim": # Packed: v0 [8:0], v1 [18:10], v2 [28:20], null primitive [31]. u = self.src_u(srcs[0]) old, sel = self.tmp(), self.tmp() self.emit(f"{old} = OpLoad %uint %ms_prim") self.emit(f"{sel} = OpSelect %uint {act} {u} {old}") self.emit("OpStore %ms_prim " + sel) hp, hs = self.tmp(), self.tmp() self.emit(f"{hp} = OpLoad %bool %ms_has_prim") self.emit(f"{hs} = OpLogicalOr %bool {hp} {act}") self.emit("OpStore %ms_has_prim " + hs) return if tgt.startswith("pos") and tgt != "pos0": pidx = int(tgt[3:]) if pidx == 1 and self.pos_misc: # Layer / ViewportIndex are per-primitive mesh outputs: staged here, written with the primitive. self.export_misc_pos1(srcs, act, "%ms_layer", "%ms_viewport") return comps = self.export_comps(a, ins) if "compr" in ins["mods"] else None mapping = self.pos_map.get(pidx) if not mapping: return wrote = False for comp, (kind, idx) in sorted(mapping.items()): if comp >= len(srcs): continue x = srcs[comp] if comps is not None: fval = comps[comp] if fval is None: continue else: if x["k"] == "special" and x["t"] == "off": continue fval = self.src_f(x) if kind == "clip": self.uses_clip = True var = "%ms_clip" else: self.uses_cull = True var = "%ms_cull_dist" ptr, old, sel = self.tmp(), self.tmp(), self.tmp() self.emit(f"{ptr} = OpAccessChain %_ptr_Function_float {var} {self.cu(idx)}") self.emit(f"{old} = OpLoad %float {ptr}") self.emit(f"{sel} = OpSelect %float {act} {fval} {old}") self.emit(f"OpStore {ptr} {sel}") wrote = True if wrote: hv, hs = self.tmp(), self.tmp() self.emit(f"{hv} = OpLoad %bool %ms_has_vtx") self.emit(f"{hs} = OpLogicalOr %bool {hv} {act}") self.emit("OpStore %ms_has_vtx " + hs) return if not (tgt == "pos0" or tgt.startswith("param")): raise Unsupported(f"mesh export {tgt}") comps = [c or "%f0" for c in self.export_comps(a, ins)] v = self.tmp() self.emit(f"{v} = OpCompositeConstruct %v4float {' '.join(comps[:4])}") var = "%ms_pos" if tgt == "pos0" else f"%ms_param{int(tgt[5:])}" if tgt != "pos0": self.ms_params.add(int(tgt[5:])) old, sel = self.tmp(), self.tmp() self.emit(f"{old} = OpLoad %v4float {var}") self.emit(f"{sel} = OpSelect %v4float {act} {v} {old}") self.emit(f"OpStore {var} {sel}") hv, hs = self.tmp(), self.tmp() self.emit(f"{hv} = OpLoad %bool %ms_has_vtx") self.emit(f"{hs} = OpLogicalOr %bool {hv} {act}") self.emit("OpStore %ms_has_vtx " + hs) def export_comps(self, a, ins): """The four export components as float ids, None where the slot is off. A compressed export ('compr') holds two f16 pairs: two registers, each unpacked to (x,y) and (z,w). LLVM lists each register twice (one slot per half): 'exp mrt0 v4, v4, v5, v5 compr', so the pair is slots 1 and 3. (Found by the GPU texture test: taking the first two operands exported (r,g,r,g).)""" comps = [] if "compr" in ins["mods"]: srcs = a[1:5] regs = [srcs[0], srcs[2]] if len(srcs) >= 3 else srcs[:1] for x in regs: if x["k"] == "special" and x["t"] == "off": comps += [None, None] continue u = self.src_u(x) v2 = self.tmp() self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") for c in (0, 1): f = self.tmp() self.emit(f"{f} = OpCompositeExtract %float {v2} {c}") comps.append(f) else: for x in a[1:5]: if x["k"] == "special" and x["t"] == "off": comps.append(None) else: comps.append(self.src_f(x)) while len(comps) < 4: comps.append(None) return comps[:4] def export(self, ins): a = ins["args"] tgt = a[0]["t"] if a and a[0]["k"] in ("target", "special") else None if self.vm_latch and "vm" in ins["mods"]: # any target, null included self.emit(f"OpStore %vm_mask {self.active_b()}") self.emit("OpStore %vm_set %true") if self.vm_latch and is_color_export(ins): if tgt not in self.col_latched: self.col_latched.append(tgt) self.emit(f"OpStore %col_mask_{tgt} {self.active_b()}") self.emit(f"OpStore %col_set_{tgt} %true") if tgt is None or tgt == "null": return if self.stage == "ms": return self.ms_export(tgt, ins) if tgt.startswith("pos") and tgt != "pos0" and self.stage == "vs": srcs = a[1:5] if all(x["k"] == "special" and x["t"] == "off" for x in srcs): return pidx = int(tgt[3:]) act = self.active_b() if pidx == 1 and self.pos_misc: self.export_misc_pos1(srcs, act, "%out_layer", "%out_viewport") return mapping = self.pos_map.get(pidx) if not mapping: return for comp, (kind, idx) in sorted(mapping.items()): if comp >= len(srcs): continue x = srcs[comp] if x["k"] == "special" and x["t"] == "off": continue fval = self.src_f(x) if kind == "clip": self.uses_clip = True var = "%out_clip" else: self.uses_cull = True var = "%out_cull" ptr, old, sel = self.tmp(), self.tmp(), self.tmp() self.emit(f"{ptr} = OpAccessChain %_ptr_Output_float {var} {self.cu(idx)}") self.emit(f"{old} = OpLoad %float {ptr}") self.emit(f"{sel} = OpSelect %float {act} {fval} {old}") self.emit(f"OpStore {ptr} {sel}") return if tgt == "mrtz" and self.stage == "ps": # Depth export: x is the fragment depth when it's on in an uncompressed export (RGBA = Z, stencil, # sample mask, alpha; Mesa ac_shader_util.c ac_get_spi_shader_z_format). A compressed mrtz is the 16-bit # stencil and sample mask format, which never holds Z (ac_nir_lower_ps_late.c emit_ps_mrtz_export), and # with x off no depth is exported. Until 2026-11-22 both wrote one anyway: 0.0, or an f16 half of the # stencil word under compr. Stencil, sample mask and alpha aren't modelled. x = a[1] if len(a) > 1 else None if "compr" in ins["mods"] or x is None or (x["k"] == "special" and x["t"] == "off"): return self.writes_depth = True old, sel = self.tmp(), self.tmp() self.emit(f"{old} = OpLoad %float %out_depth") self.emit(f"{sel} = OpSelect %float {self.active_b()} {self.src_f(x)} {old}") self.emit(f"OpStore %out_depth {sel}") return name = {"pos0": "%out_pos"}.get(tgt) ctype = 3 if name is None: if tgt.startswith("param") and self.stage == "vs": name = f"%out_param{int(tgt[5:])}" elif tgt.startswith("mrt") and tgt != "mrtz" and self.stage == "ps": # Colour exports are packed: exp mrtK writes the K-th declared SV_Target, not render target K # (docs/design.md, "Pixel colour exports"). Without an OSG1 the index is the render target. k = int(tgt[3:]) if self.mrt_targets and k >= len(self.mrt_targets): raise Unsupported(f"export mrt{k} past the {len(self.mrt_targets)} declared SV_Target outputs") rt = self.mrt_targets[k] if self.mrt_targets else k name = f"%out_mrt{rt}" tgt = f"mrt{rt}" ctype = self.mrt_types.get(rt, 3) elif tgt.startswith("pos"): return # pos1+ (clip/cull/point size): ignored in v0 else: raise Unsupported(f"export {tgt}") if ctype in (1, 2): if "compr" in ins["mods"]: raise Unsupported("compressed integer color export") comps = [] for x in a[1:5]: if x["k"] == "special" and x["t"] == "off": comps.append(None) elif ctype == 1: comps.append(self.src_u(x)) else: comps.append(self.as_int(self.src_u(x))) while len(comps) < 4: comps.append(None) comps = comps[:4] vt, st = ("%v4uint_out", "%uint") if ctype == 1 else ("%v4int_out", "%int") self.output_ctypes[name] = ctype else: comps = self.export_comps(a, ins) vt, st = "%v4float", "%float" v = self.tmp() self.outputs[name] = tgt # Exports from inactive lanes don't happen: keep the previous output value. old, sel = self.tmp(), self.tmp() self.emit(f"{old} = OpLoad {vt} {name}") if self.stage == "ps" and tgt.startswith("mrt") and None in comps: # EN gates each component (each RG/BA pair when compressed). Keep the previous export in off slots. self.partial_color_outputs.add(name) for i, comp in enumerate(comps): if comp is None: comps[i] = self.tmp() self.emit(f"{comps[i]} = OpCompositeExtract {st} {old} {i}") z0 = (self.cu(0) if ctype == 1 else self.as_int(self.cu(0)) if ctype == 2 else "%f0") if None in comps else None self.emit(f"{v} = OpCompositeConstruct {vt} {' '.join(comp or z0 for comp in comps)}") self.emit(f"{sel} = OpSelect {vt} {self.active_b()} {v} {old}") self.emit(f"OpStore {name} {sel}") if F16_HALVES and tgt.startswith("param") and self.stage == "vs": n = int(tgt[5:]) for half, hv in enumerate(self.f16_halves_of(n, v)): hname = f"%out_f16h{n}_{half}" self.outputs[hname] = f"loc{self.f16_half_locs[n][half]}" old, sel = self.tmp(), self.tmp() self.emit(f"{old} = OpLoad %v4float {hname}") self.emit(f"{sel} = OpSelect %v4float {self.active_b()} {hv} {old}") self.emit(f"OpStore {hname} {sel}") def f16_halves_of(self, n, v): """--f16-interp-fallback: param n's exported vec4 `v` as two vec4s, the low and the high f16 half of each channel's raw word decoded to f32 (UnpackHalf2x16), or () when their locations would overlap a param this shader exports (or fall below location 0): runtime PSO linking synthesizes missing halves per pair.""" if n not in self.f16_half_locs: if f16_half_location(n, 0) <= self.param_max: return () self.f16_half_locs[n] = (f16_half_location(n, 0), f16_half_location(n, 1)) lo, hi = [], [] for c in range(4): e, u, h2, a, b = (self.tmp() for _ in range(5)) self.emit(f"{e} = OpCompositeExtract %float {v} {c}") self.emit(f"{u} = OpBitcast %uint {e}") self.emit(f"{h2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") self.emit(f"{a} = OpCompositeExtract %float {h2} 0") self.emit(f"{b} = OpCompositeExtract %float {h2} 1") lo.append(a) hi.append(b) out = [] for parts in (lo, hi): r = self.tmp() self.emit(f"{r} = OpCompositeConstruct %v4float {' '.join(parts)}") out.append(r) return tuple(out) _TYPE_DECL = re.compile(r"\s*(%\w+) = (OpTypeVector|OpTypePointer) (.*)$") _ID_REF = re.compile(r"%\w+") def dedupe_types(text): """SPIR-V forbids duplicate non-aggregate types. Separate features may each declare e.g. a uint4 vector (%v4uint for r32ui storage, %v4uint_st for typed stores, %v4uint_in for vertex inputs): keep the first declaration of each OpTypeVector / OpTypePointer and rename the others everywhere.""" alias, seen, out = {}, {}, [] lines = text.split("\n") for i, line in enumerate(lines): if " = OpFunction " in line: out.extend(lines[i:]) break m = _TYPE_DECL.match(line) if m: name, opc, rest = m.groups() key = (opc, _ID_REF.sub(lambda t: alias.get(t.group(0), t.group(0)), rest)) if key in seen: alias[name] = seen[key] continue seen[key] = name out.append(line) if not alias: return text pattern = re.compile(r"(?:" + "|".join(re.escape(k) for k in sorted(alias, key=len, reverse=True)) + r")\b") return pattern.sub(lambda m: alias[m.group(0)], "\n".join(out)) def ms_prim_indices(c): """The mesh epilogue's primitive: from %mpr (the `exp prim` word) and %msv (the vertex count), %mnb = bit 31 (null primitive) as 0/1, %mnull as a bool and %mi0..%mi2 the three indices. The 9-bit fields leave out the edge flags. GFX10 epilogues mark a primitive null when a field is at or past the vertex count and keep the field, but Vulkan leaves such an index undefined even on a culled primitive (VK_EXT_mesh_shader), so a null primitive's indices are 0 and the others are clamped to the vertex count - 1, as Mesa 22.3 clamps them (ac_nir_lower_ngg.c line 4112). A primitive is written only when %msv > 0 (the primitive count is 0 otherwise).""" L = [f"%mnb = OpShiftRightLogical %uint %mpr {c(31)}", f"%mnull = OpINotEqual %bool %mnb {c(0)}", f"%mvl = OpISub %uint %msv {c(1)}"] for k in range(3): src = f"%mfr{k}" if k else "%mpr" if k: L.append(f"%mfr{k} = OpShiftRightLogical %uint %mpr {c(10 * k)}") L += [f"%mfi{k} = OpBitwiseAnd %uint {src} {c(0x1FF)}", f"%mci{k} = OpExtInst %uint %glsl UMin %mfi{k} %mvl", f"%mi{k} = OpSelect %uint %mnull {c(0)} %mci{k}"] return L def ms_prim_count(c, maxp): """%msp from the allocation's primitive count %msp0: clamped to PSV0's maximum, and 0 without a vertex.""" return [f"%mspc = OpExtInst %uint %glsl UMin %msp0 {c(maxp)}", f"%mvz = OpIEqual %bool %msv {c(0)}", f"%msp = OpSelect %uint %mvz {c(0)} %mspc"] def mesh_compute_epilogue(gen): """--mesh-compute: the mesh epilogue as buffer stores, as lines (assemble indents them; ms_serial_epilogue repeats the writes per pass). Same barrier and counts as the mesh path; then lane 0 writes the header, lane i < vertex count its vertex and lane i < primitive count its primitive, at the offsets of gen.msc_layout in this workgroup's slot (linear workgroup index x + y*nx + z*nx*ny).""" c, lay = gen.cu, gen.msc_layout L = [f"OpControlBarrier {c(2)} {c(2)} " + c(0x108), "%msc = OpLoad %uint %ms_counts", f"%msv0 = OpBitwiseAnd %uint %msc {c(0xFFF)}", f"%msp1 = OpShiftRightLogical %uint %msc {c(12)}", f"%msp0 = OpBitwiseAnd %uint %msp1 {c(0xFFF)}", f"%msv = OpExtInst %uint %glsl UMin %msv0 {c(gen.ms['maxv'])}", *ms_prim_count(c, gen.ms['maxp']), "%mli = OpLoad %uint %local_index", # Slot base = output address (push-constant dwords 36..37, or --pc-tail-ubo dwords 4..5) + linear # workgroup index * slot bytes. pc_tail_chain("%moa_lo_p", 5, c), pc_tail_chain("%moa_hi_p", 6, c), "%moa_lo = OpLoad %uint %moa_lo_p", "%moa_hi = OpLoad %uint %moa_hi_p", "%moa_l64 = OpUConvert %ulong %moa_lo", "%moa_h64 = OpUConvert %ulong %moa_hi", "%moa_sh = OpShiftLeftLogical %ulong %moa_h64 %c64_32", "%moa = OpBitwiseOr %ulong %moa_sh %moa_l64", "%mwg = OpLoad %v3uint %wg_id", "%mnw = OpLoad %v3uint %num_wg", "%mwx = OpCompositeExtract %uint %mwg 0", "%mwy = OpCompositeExtract %uint %mwg 1", "%mwz = OpCompositeExtract %uint %mwg 2", "%mnx = OpCompositeExtract %uint %mnw 0", "%mny = OpCompositeExtract %uint %mnw 1", "%mnxy = OpIMul %uint %mnx %mny", "%mwyx = OpIMul %uint %mwy %mnx", "%mwzxy = OpIMul %uint %mwz %mnxy", "%mwl0 = OpIAdd %uint %mwx %mwyx", "%mwl = OpIAdd %uint %mwl0 %mwzxy", "%mwl64 = OpUConvert %ulong %mwl", f"%mso = OpIMul %ulong %mwl64 {gen.cl(lay['slot_bytes'])}", "%msb = OpIAdd %ulong %moa %mso"] n = [0] def store(off_u32, word): """Store uint `word` at byte offset `off_u32` (a uint id) of the slot.""" k = n[0] n[0] += 1 L.extend([f"%mo{k} = OpUConvert %ulong {off_u32}", f"%ma{k} = OpIAdd %ulong %msb %mo{k}", f"%mp{k} = OpConvertUToPtr %_ptr_PSB_uint %ma{k}", f"OpStore %mp{k} {word} Aligned 4"]) def at(base, extra): """uint id for base + a constant byte offset.""" if not extra: return base k = n[0] n[0] += 1 L.append(f"%mx{k} = OpIAdd %uint {base} {c(extra)}") return f"%mx{k}" def store_floats(base, values): for i, f in enumerate(values): k = n[0] n[0] += 1 L.append(f"%mf{k} = OpBitcast %uint {f}") store(at(base, 4 * i), f"%mf{k}") # Header, lane 0. L += ["%mh0 = OpIEqual %bool %mli %c0", "OpSelectionMerge %msc_hend None", "OpBranchConditional %mh0 %msc_hdo %msc_hend", "%msc_hdo = OpLabel"] store("%c0", "%msv") store(c(4), "%msp") L += ["OpBranch %msc_hend", "%msc_hend = OpLabel"] # Vertex mli. L += ["%mhv = OpLoad %bool %ms_has_vtx", "%mvi = OpULessThan %bool %mli %msv", "%mwv = OpLogicalAnd %bool %mhv %mvi", "OpSelectionMerge %msc_vend None", "OpBranchConditional %mwv %msc_vdo %msc_vend", "%msc_vdo = OpLabel", f"%mvs = OpIMul %uint %mli {c(lay['vertex_stride'])}", f"%mvb = OpIAdd %uint %mvs {c(lay['vertices'])}", "%mpv = OpLoad %v4float %ms_pos"] comps = [] for i in range(4): L.append(f"%mpv{i} = OpCompositeExtract %float %mpv {i}") comps.append(f"%mpv{i}") store_floats("%mvb", comps) for var, count, off in (("%ms_clip", lay["clip_count"], lay["clip_offset"]), ("%ms_cull_dist", lay["cull_count"], lay["cull_offset"])): vals = [] for i in range(count): k = n[0] n[0] += 1 L += [f"%mdp{k} = OpAccessChain %_ptr_Function_float {var} {c(i)}", f"%mdv{k} = OpLoad %float %mdp{k}"] vals.append(f"%mdv{k}") if vals: store_floats(at("%mvb", off), vals) for loc, off in sorted(lay["params"].items()): L.append(f"%mq{loc} = OpLoad %v4float %ms_param{loc}") vals = [] for i in range(4): L.append(f"%mq{loc}_{i} = OpCompositeExtract %float %mq{loc} {i}") vals.append(f"%mq{loc}_{i}") store_floats(at("%mvb", off), vals) L += ["OpBranch %msc_vend", "%msc_vend = OpLabel"] # Primitive mli: three indices and the null-primitive bit (bit 31), as in the mesh path. # Defensive hardening: if %mli < %msp but this invocation never executed `exp prim` (!%ms_has_prim), # emit (0, 0, 0) with null-primitive bit 1 so the slot is never left uninitialized. L += ["%mhp = OpLoad %bool %ms_has_prim", "%mpi = OpULessThan %bool %mli %msp", "OpSelectionMerge %msc_pend None", "OpBranchConditional %mpi %msc_pdo %msc_pend", "%msc_pdo = OpLabel", f"%mps = OpIMul %uint %mli {c(16)}", f"%mpb = OpIAdd %uint %mps {c(lay['primitives'])}", "%mpr = OpLoad %uint %ms_prim", *ms_prim_indices(c), f"%mi0s = OpSelect %uint %mhp %mi0 {c(0)}", f"%mi1s = OpSelect %uint %mhp %mi1 {c(0)}", f"%mi2s = OpSelect %uint %mhp %mi2 {c(0)}", f"%mnbs = OpSelect %uint %mhp %mnb {c(1)}"] for i, w in enumerate(("%mi0s", "%mi1s", "%mi2s", "%mnbs")): store(at("%mpb", 4 * i), w) L += ["OpBranch %msc_pend", "%msc_pend = OpLabel"] return L def float_literal(bits): """The OpConstant %float literal of the f32 `bits` that spirv-as and tools/spirv_asm.py read back as exactly those bits: the shortest decimal of a finite value (it is the f32's own value, so the round to f32 is exact; -0.0 and the denormals too), the SPIRV-Tools hex-float spelling of an infinity or a NaN, its payload as stored.""" f = struct.unpack("> 31 else ''}0x1.{(bits & 0x7FFFFF) << 1:06x}p+128" def insert_late_constants(gen, out, written): """Define the uint constants assemble asked gen.cu for after it wrote the others (the format tables' lengths and entries, prologue indices, ...), right after the last written one, so before any type or instruction that uses them. Without this a constant nothing else had used (fmt_size_arr's length 128 in a shader with only a d16 typed store) was an id with no definition, and the module failed spirv-val.""" late = sorted(v for v in gen.consts if v not in written) # fconst's floats asked for after assemble wrote them, after the uint constants (the %float type comes first). late_f = sorted(v for v in gen.fconsts if v not in gen.fconsts_written and v not in (0, 0x3F800000)) if not late and not late_f: return last = max(written) at = out.index(f"{written[last]} = OpConstant %uint {last}") + 1 out[at:at] = ([f"{gen.consts[v]} = OpConstant %uint {v}" for v in late] + [f"{gen.fconsts[v]} = OpConstant %float {float_literal(v)}" for v in late_f]) def ms_serial_passes(gen, fn, lists): """--mesh-serial-waves, --compute-serial-waves: the function's variables, then a loop over the passes around the prologue (and, appended by the caller, the body). Returns the new `fn`, the lines that close the loop after the body, and the export variables with their per-pass twins.""" w_count = gen.ms_serial or gen.cs_serial builtin = "%local_index" if gen.ms_serial else "%local_id" for lines in lists: for i, l in enumerate(lines): if builtin in l: lines[i] = re.sub(builtin + r"\b", "%real_" + builtin[1:], l) last_var = max(i for i, l in enumerate(fn) if " = OpVariable " in l) head, rest = fn[:last_var + 1], fn[last_var + 1:] var = re.compile(r"^(%\w+) = OpVariable (\S+) Function(?: (\S+))?$") reinit, exports, twins = [], [], [] for l in head: m = var.match(l) if not m: continue name, ptr, init = m.groups() if init: reinit.append(f"OpStore {name} {init}") if name.startswith("%ms_"): exports.append(name) twins += [f"{name}__w{w} = OpVariable {ptr} Function" + (f" {init}" if init else "") for w in range(w_count)] c = gen.cu head = head + [("%local_index = OpVariable %_ptr_Function_uint Function " + c(0) if gen.ms_serial else "%local_id = OpVariable %_ptr_Function_v3u Function"), "%msw_pass = OpVariable %_ptr_Function_uint Function " + c(0)] + twins open_loop = ["OpBranch %msw_head", "%msw_head = OpLabel", "OpLoopMerge %msw_exit %msw_cont None", "OpBranch %msw_body", "%msw_body = OpLabel"] + reinit + ["%msw_w = OpLoad %uint %msw_pass"] if gen.ms_serial: open_loop += ["%msw_rl = OpLoad %uint %real_local_index"] else: open_loop += ["%msw_rid = OpLoad %v3uint %real_local_id", "%msw_rl = OpCompositeExtract %uint %msw_rid 0"] open_loop += [f"%msw_off = OpIMul %uint %msw_w {c(64)}", "%msw_li = OpIAdd %uint %msw_rl %msw_off"] if gen.ms_serial: open_loop += ["OpStore %local_index %msw_li"] else: sx, sy, _ = gen.cs["size"] open_loop += [f"%msw_x = OpUMod %uint %msw_li {c(sx)}", f"%msw_yz = OpUDiv %uint %msw_li {c(sx)}", f"%msw_y = OpUMod %uint %msw_yz {c(sy)}", f"%msw_z = OpUDiv %uint %msw_yz {c(sy)}", "%msw_id = OpCompositeConstruct %v3uint %msw_x %msw_y %msw_z", "OpStore %local_id %msw_id"] close = [] for w in range(w_count if exports else 0): close += [f"%msw_is{w} = OpIEqual %bool %msw_w {c(w)}", f"OpSelectionMerge %msw_sv_end{w} None", f"OpBranchConditional %msw_is{w} %msw_sv{w} %msw_sv_end{w}", f"%msw_sv{w} = OpLabel"] close += [f"OpCopyMemory {name}__w{w} {name}" for name in exports] close += [f"OpBranch %msw_sv_end{w}", f"%msw_sv_end{w} = OpLabel"] close += ["OpBranch %msw_cont", "%msw_cont = OpLabel", f"%msw_n = OpIAdd %uint %msw_w {c(1)}", "OpStore %msw_pass %msw_n", f"%msw_more = OpULessThan %bool %msw_n {c(w_count)}", "OpBranchConditional %msw_more %msw_head %msw_exit", "%msw_exit = OpLabel"] return head + open_loop + rest, close, exports def ms_serial_epilogue(gen, lines, exports): """--mesh-serial-waves: the mesh epilogue for passes. `lines` is the epilogue of one invocation: the barrier, the counts and OpSetMeshOutputsEXT (or, with --mesh-compute, mesh_compute_epilogue's barrier and counts), then (from the load of `%local_index` on) the writes of what the invocation exported. The first part stays as it is, once; the writes are repeated per pass w with the pass's twins of the export variables and the output index real index + 64 * w, every id of the block renamed per pass.""" cut = lines.index("%mli = OpLoad %uint %local_index") once, writes = lines[:cut], lines[cut + 1:] defined = set(re.findall(r"^(%\w+) = ", "\n".join(writes), re.M)) out = list(once) + ["%msw_erl = OpLoad %uint %real_local_index"] for w in range(gen.ms_serial): names = {d: f"{d}_w{w}" for d in defined} names.update({e: f"{e}__w{w}" for e in exports}) names["%mli"] = f"%mli_w{w}" out.append(f"%mli_w{w} = OpIAdd %uint %msw_erl {gen.cu(64 * w)}") for l in writes: out.append(re.sub(r"%\w+", lambda m: names.get(m.group(0), m.group(0)), l)) return out def _detect_barrier_coherency(gen): """Detect whether a compute/mesh shader with s_barrier (or wave64-emulate ordering barriers) requires VulkanMemoryModel intra-workgroup memory coherency for PSB buffers or storage images. Returns `(bar_psb_coh, bar_img_coh)`: - `bar_psb_coh`: barrier + at least one PhysicalStorageBuffer write (`OpStore` or writing `OpAtomic*`) AND at least one PSB read (`OpLoad` or reading `OpAtomic*`) AND at least one plain PSB `OpLoad`/`OpStore`. - `bar_img_coh`: barrier + at least one storage image write (`OpImageWrite` or `OpImageTexelPointer`) AND at least one storage image read (`OpImageRead` or `OpImageTexelPointer`) AND at least one plain `OpImageRead`/`OpImageWrite`. Under GLSL450, `OpControlBarrier 2 2 0x948` (`UniformMemory|ImageMemory`) orders only `Coherent` memory, so RADV/ACO omits per-CU GL0 cache invalidation; under VulkanMemoryModel, plain PSB/storage-image ops without `NonPrivatePointer`/`NonPrivateTexel` are invocation-private and still unordered across CUs. """ if gen.stage not in ("cs", "ms") or not (gen.uses_barrier or gen.bar_rounds or gen.emulate): return False, False seqs = [gen.body] seqs.extend(b for b in gen.blocks if b is not None) seqs.extend(gen.x_segs.values()) seqs.extend(gen.sbuf_slow_fns.values()) psb_ptrs = set() for seq in seqs: for line in seq: s = line.strip() if " = Op" in s and "%_ptr_PSB_" in s: parts = s.split() if len(parts) >= 4 and parts[1] == "=" and parts[3].startswith("%_ptr_PSB_"): psb_ptrs.add(parts[0]) psb_plain_read = psb_plain_write = False psb_atomic_read = psb_atomic_write = False img_plain_read = img_plain_write = img_atomic = False for seq in seqs: for line in seq: s = line.strip() if " = OpLoad " in s: if psb_ptrs: parts = s.split() if len(parts) >= 5 and parts[2] == "OpLoad" and parts[4] in psb_ptrs: psb_plain_read = True elif s.startswith("OpStore "): if psb_ptrs: parts = s.split() if len(parts) >= 3 and parts[1] in psb_ptrs: psb_plain_write = True elif " = OpAtomic" in s: if psb_ptrs: parts = s.split() if len(parts) >= 5 and parts[2].startswith("OpAtomic") and parts[4] in psb_ptrs: if parts[2] == "OpAtomicLoad": psb_atomic_read = True else: psb_atomic_read = True psb_atomic_write = True elif s.startswith("OpAtomicStore "): if psb_ptrs: parts = s.split() if len(parts) >= 2 and parts[1] in psb_ptrs: psb_atomic_write = True elif " = OpImageRead " in s: img_plain_read = True elif s.startswith("OpImageWrite "): img_plain_write = True elif " = OpImageTexelPointer " in s: img_atomic = True bar_psb_coh = ( (psb_plain_write or psb_atomic_write) and (psb_plain_read or psb_atomic_read) and (psb_plain_write or psb_plain_read) ) bar_img_coh = ( (img_plain_write or img_atomic) and (img_plain_read or img_atomic) and (img_plain_write or img_plain_read) ) return bar_psb_coh, bar_img_coh def _add_non_private_psb(line, psb_ptrs): """Ensure a PhysicalStorageBuffer OpLoad/OpStore carries NonPrivatePointer without touching non-PSB ops or already-decorated VMM ops (NonPrivatePointer has no extra operand word).""" s = line.strip() if " = OpLoad " in s: parts = s.split() if len(parts) >= 5 and parts[2] == "OpLoad" and parts[4] in psb_ptrs: if len(parts) == 5: return line + " NonPrivatePointer" mask = parts[5] if "NonPrivatePointer" not in mask.split("|"): parts[5] = "NonPrivatePointer" if mask == "None" else f"{mask}|NonPrivatePointer" indent = line[:len(line) - len(line.lstrip())] return indent + " ".join(parts) elif s.startswith("OpStore "): parts = s.split() if len(parts) >= 3 and parts[1] in psb_ptrs: if len(parts) == 3: return line + " NonPrivatePointer" mask = parts[3] if "NonPrivatePointer" not in mask.split("|"): parts[3] = "NonPrivatePointer" if mask == "None" else f"{mask}|NonPrivatePointer" indent = line[:len(line) - len(line.lstrip())] return indent + " ".join(parts) return line def _add_non_private_texel(line): """Ensure a storage OpImageRead/OpImageWrite carries NonPrivateTexel without double-decorating already-VMM ops (NonPrivateTexel has no extra operand word, preserving operand bit order).""" s = line.strip() if " = OpImageRead " in s: parts = s.split() if len(parts) >= 6 and parts[2] == "OpImageRead": if len(parts) == 6: return line + " NonPrivateTexel" mask = parts[6] if "NonPrivateTexel" not in mask.split("|"): parts[6] = "NonPrivateTexel" if mask == "None" else f"{mask}|NonPrivateTexel" indent = line[:len(line) - len(line.lstrip())] return indent + " ".join(parts) elif s.startswith("OpImageWrite "): parts = s.split() if len(parts) >= 4: if len(parts) == 4: return line + " NonPrivateTexel" mask = parts[4] if "NonPrivateTexel" not in mask.split("|"): parts[4] = "NonPrivateTexel" if mask == "None" else f"{mask}|NonPrivateTexel" indent = line[:len(line) - len(line.lstrip())] return indent + " ".join(parts) return line def assemble(gen): store_dims = gen.uses_store_views | gen.uses_store_reads vs = gen.stage == "vs" cs = gen.stage == "cs" ms = gen.stage == "ms" gsx = gen.stage == "gs" msc = ms and MESH_COMPUTE bar_psb_coh, bar_img_coh = _detect_barrier_coherency(gen) if bar_psb_coh or bar_img_coh: # Intra-workgroup barrier coherency across CUs (Navi31 GL0 cache): enable VulkanMemoryModel # before bar_sem / OpMemoryModel / Coherent decisions, without setting reads_glc_buffer. gen.uses_vmm = True # --f16-interp-fallback, mesh: the params whose decoded halves fit clear of this shader's params (Gen.f16_halves_of) if ms and not msc and F16_HALVES: for n in sorted(gen.ms_params): if n not in gen.f16_half_locs and f16_half_location(n, 0) > gen.param_max: gen.f16_half_locs[n] = (f16_half_location(n, 0), f16_half_location(n, 1)) ms_halves = [n for n in sorted(gen.ms_params) if n in gen.f16_half_locs] if ms and not msc else [] if msc: gen.msc_layout = mesh_compute_layout(gen.ms["maxv"], gen.ms["maxp"], gen.clip_count if gen.uses_clip else 0, gen.cull_count if gen.uses_cull else 0, gen.ms_params) # Built here, before any constant is emitted, so every constant it asks for gets declared. # --mesh-serial-waves: the constants of each pass's output index too (_translate asked for them). gen.msc_epilogue = mesh_compute_epilogue(gen) # --pc-tail-ubo: the uniform block exists only when the shader reads the tail (after the epilogue, which reads it). gen.uses_pc_tail = PC_TAIL_UBO and (gen.uses_heap or gen.uses_codebase or msc) if gen.emulate: # No subgroup operation is left (x_round does them through %x_buf), so none of their capabilities. if any("OpGroupNonUniform" in l or "%sg_lane" in l for b in gen.blocks + list(gen.x_segs.values()) if b is not None for l in b): raise Unsupported("wave64 emulation: a subgroup operation is left") gen.uses_subgroup = gen.uses_vote = gen.uses_ballot = gen.uses_quad = False gen.uses_wave_bits = gen.uses_bcast_first = False x_waves, x_mask, x_sched, x_sink = gen.x_sizes() x_zero = x_sink - x_mask # mask and schedule words: zeroed before the first round x_threads = (gen.cs or gen.ms)["size"] x_threads = x_threads[0] * x_threads[1] * x_threads[2] if gen.ms_serial or gen.cs_serial: x_threads = 64 # the invocations of one pass sx, sy, _ = (gen.cs or gen.ms)["size"] for v in (0, 1, 2, 3, 6, 31, 63, 0x948, x_mask, x_sched, x_sink, x_sink + 1, x_zero - 1, x_threads, x_waves, sx, sx * sy, 0xFFFFFFC0): gen.cu(v) x_missing = gen.x_lanes - x_threads # lanes of a partial last wave that don't exist for k in range(-(-max(x_zero, x_missing) // x_threads)): gen.cu(k * x_threads) if x_missing: for v in (x_missing - 1, gen.x_lanes + x_threads): gen.cu(v) if gen.bar_rounds: sx, sy, _ = gen.cs["size"] bar_sem = 0x6948 if gen.uses_vmm else 0x948 for v in (0, 1, 2, 3, bar_sem, sx, sx * sy): gen.cu(v) model = "Vertex" if vs else "GLCompute" if cs or msc else "MeshEXT" if ms else "Geometry" if gsx else "Fragment" ms_blk = ms and not msc and (gen.uses_clip or gen.uses_cull) iface = list(gen.outputs) + list(gen.inputs) + (["%vertex_index", "%instance_index", "%base_vertex", "%base_instance"] if vs else []) + (["%wg_id", "%local_id"] if cs else []) + (["%lds"] if gen.uses_lds else []) + ( (["%wg_id", "%num_wg", "%local_index", "%ms_counts"] + ([] if msc else # List %ms_cull (PerPrimitiveEXT Block) before %ms_out_vtx (Position+ClipDistance/CullDistance Block): # AMD's proprietary Windows Vulkan driver (24.10.24, LLPC) segfaults (0xC0000005) during # vkCreateGraphicsPipelines when the per-vertex clip/cull Block precedes the per-primitive Block in # OpEntryPoint's interface list (SHADER-MS-CLIP-IFACE / ms_clip). ["%ms_cull", ("%ms_out_vtx" if ms_blk else "%ms_out_pos"), "%ms_prim_idx"] + [f"%ms_out_param{n}" for n in sorted(gen.ms_params)] + [f"%ms_out_f16h{n}_{h}" for n in ms_halves for h in (0, 1)])) if ms else []) + ( ["%x_buf"] if gen.emulate or gen.bar_rounds and not gen.bar_counts_in_lds() else []) + ( ([("%gs_in_pos" if sv == 1 else f"%gs_in{r}") for r, sv in gen.gs["in"]] + [("%gs_out_pos" if sv == 1 else f"%gs_out{r}") for r, sv in gen.gs["out"]]) if gsx else []) + ( ["%fmt_uint_mask", "%fmt_sint_mask"] if store_dims or gen.uses_int_fetch else []) + ( ["%fmt_norm_mask", "%fmt_f32_mask"] if gen.uses_d16_image else []) + \ (["%fmt_size_tab"] if gen.uses_fmt_size else []) + \ (["%fmt_desc_tab", "%fmt_norm_rep_tab"] if gen.uses_fmt_tables else []) + \ (["%fmt_enc_desc_tab"] if gen.uses_fmt_enc_table else []) + \ [f"%stv{c}_{d}" for d in sorted(store_dims) for c in range(3)] + \ [f"%itx{c}_{d}" for d in sorted(gen.uses_int_fetch) for c in (1, 2)] psb = gen.uses_psb tex = gen.uses_tex sg = gen.uses_subgroup if tex: iface += ["%images", "%samplers", "%desc_map"] + (["%images_arr"] if gen.uses_tex_array else []) + \ (["%simages"] if gen.uses_storage else []) + (["%images_1d"] if gen.uses_tex_1d else []) + \ (["%images_3d"] if gen.uses_tex_3d else []) + (["%simages3d"] if gen.uses_storage3d else []) + \ (["%simages64"] if gen.uses_storage64 else []) if sg: iface += ["%sg_lane"] if gen.writes_depth: iface += ["%out_depth"] if vs: if gen.uses_clip: iface += ["%out_clip"] if gen.uses_cull: iface += ["%out_cull"] if gen.uses_layer: iface += ["%out_layer"] if gen.uses_viewport: iface += ["%out_viewport"] iface += [f"%vin{reg}" for reg, _ in gen.vertex_inputs] + ["%user_data"] + (["%pc_tail"] if gen.uses_pc_tail else []) bary = any(str(c).startswith("bary") for c in gen.frag_inputs.values()) or bool(gen.per_vertex) or bool(gen.ij_deriv) # --bary-fallback: %bary is a plain input at the lowest location no attribute uses, so no capability or # extension. Lowest free, not one past the highest: a PS whose only input is attr30 would otherwise put it at 31, # past what drivers with 128 input components accept (#804 review). if gen.stage == "ps" and gen.f16_halves: raw_locs = {v for k, v in gen.inputs.items() if not k.startswith("%in_f16h") and v is not None} gen.f16_half_locs = assign_f16_half_locations(gen.f16_halves, raw_locs) for k in list(gen.inputs): if k.startswith("%in_f16h"): a_str, h_str = k[len("%in_f16h"):].split("_") gen.inputs[k] = gen.f16_half_locs[int(a_str)][int(h_str)] used = set(gen.inputs.values()) if len(used) != len(gen.inputs): # --f16-interp-fallback: a decoded-half location is also an attribute raise Unsupported("--f16-interp-fallback: a decoded-half location is also read as an attribute") # The producer fills both halves of every attribute in f16_halves (the index's f16_halves lists the pair), so a # raw attribute at the location of a half this shader doesn't read is overwritten all the same. reserved = {loc for pair in gen.f16_half_locs.values() for loc in pair} if gen.stage == "ps" else set() if any(not k.startswith("%in_f16h") and v in reserved for k, v in gen.inputs.items()): raise Unsupported("--f16-interp-fallback: a decoded-half location is also read as an attribute") occupied = used | reserved gen.bary_location = next(n for n in range(len(occupied) + 1) if n not in occupied) if bary and BARY_FALLBACK else None bary_builtin = bary and gen.bary_location is None if gen.frag_inputs or bary: iface += ["%frag_coord"] + (["%front_facing"] if "front" in gen.frag_inputs.values() else []) + (["%bary"] if bary else []) for i in range(USER_SGPRS): # index constants for the user-data copy at entry gen.cu(i) if gen.uses_pops and gen.pops_word_sgpr is not None: gen.cu(POPS_COLLISION_SEED) # SPIR-V module layout: every OpCapability, then every OpExtension, then imports. caps = ["Shader"] + (["Int64", "PhysicalStorageBufferAddresses"] if psb else ["Int64"] if gen.uses_storage64 else []) + \ (["Int64Atomics", "Int64ImageEXT"] if gen.uses_storage64 else []) + \ (["RuntimeDescriptorArray"] if tex else []) + (["GroupNonUniform", "GroupNonUniformShuffle"] if sg else []) + \ (["ImageQuery"] if gen.uses_query else []) + (["Sampled1D"] if gen.uses_tex_1d else []) + \ (["MinLod"] if gen.uses_minlod else []) + (["ImageGatherExtended"] if gen.uses_img_offset else []) + \ (["FragmentBarycentricKHR"] if bary_builtin else []) if gen.ij_deriv: caps.append("DerivativeControl") if gen.uses_vote: caps += [c for c in ("GroupNonUniform", "GroupNonUniformVote") if c not in caps] if gen.uses_ballot or gen.uses_bcast_first: caps += [c for c in ("GroupNonUniform", "GroupNonUniformBallot") if c not in caps] if gen.uses_wave_bits: caps += [c for c in ("GroupNonUniform", "GroupNonUniformArithmetic") if c not in caps] if gen.uses_quad: caps += [c for c in ("GroupNonUniform", "GroupNonUniformQuad") if c not in caps] if gen.uses_int_dot: caps += ["DotProductKHR", "DotProductInput4x8BitPackedKHR"] # shaderIntegerDotProduct if gen.uses_f64: caps.append("Float64") if gen.uses_fma_khr: caps.append("FMAKHR") if gen.uses_clock: caps.append("ShaderClockKHR") if gen.uses_dynamic_sampled_index: caps.append("SampledImageArrayDynamicIndexing") if gen.uses_dynamic_storage_index: caps.append("StorageImageArrayDynamicIndexing") if gen.uses_store_views: caps.append("StorageImageWriteWithoutFormat") # shaderStorageImageWriteWithoutFormat if gen.uses_store_reads: caps.append("StorageImageReadWithoutFormat") # shaderStorageImageReadWithoutFormat if store_dims.intersection((3, 4)): caps.append("Image1D") if vs: caps.append("DrawParameters") # BaseVertex / BaseInstance (shaderDrawParameters), see the seeding of v0 / v3 if gsx: caps.append("Geometry") if ms and not msc: caps.append("MeshShadingEXT") if gen.uses_clip and not msc: # --mesh-compute: the distances go to the buffer, not to a builtin caps.append("ClipDistance") if gen.uses_cull and not msc: caps.append("CullDistance") if gen.uses_layer and not msc: caps.append("ShaderLayer") if gen.uses_viewport and not msc: caps.append("ShaderViewportIndex") if FLOAT_CONTROLS: # RDNA2 float ops are IEEE: NaN, +-inf and -0 come out as computed, and f16 denormals are kept. Without these # execution modes Vulkan lets the driver assume none of them occur, and drivers do: AMD's compiler folded a # -0 product to +0 and lost a NaN result narrowed to f16 with integer ops (RX 9070 XT), and NVIDIA flushed # an f16 denormal on its way into f32 (SHADER-526: the 0x0040 that _sdwa src0_sel:BYTE_1 selects read as # +0, RTX 3090 and RTX 4070 SUPER; docs/design.md, "Float controls"). # Core in SPIR-V 1.4, so no extension at vulkan1.2; the runtime checks the properties in "float_controls" # (shaderSignedZeroInfNanPreserveFloat64 too for a module that uses Float64, SHADER-597). caps += ["SignedZeroInfNanPreserve", "DenormPreserve"] if gen.ftz32: caps.append("DenormFlushToZero") pops = gen.uses_pops and gen.stage == "ps" exts = (["SPV_KHR_physical_storage_buffer"] if psb else []) + (["SPV_EXT_descriptor_indexing"] if tex else []) if gen.uses_storage64: exts.append("SPV_EXT_shader_image_int64") if gen.uses_int_dot: exts.append("SPV_KHR_integer_dot_product") if gen.uses_fma_khr: exts.append("SPV_KHR_fma") if gen.uses_clock: exts.append("SPV_KHR_shader_clock") if bary_builtin: exts.append("SPV_KHR_fragment_shader_barycentric") if ms and not msc: exts.append("SPV_EXT_mesh_shader") if pops: caps.append("FragmentShaderPixelInterlockEXT") exts.append("SPV_EXT_fragment_shader_interlock") if gen.uses_vmm: caps += ["VulkanMemoryModel", "VulkanMemoryModelDeviceScope"] exts.append("SPV_KHR_vulkan_memory_model") gen.cu(1) hdr = [f"OpCapability {c}" for c in caps] + [f'OpExtension "{e}"' for e in exts] + \ ['%glsl = OpExtInstImport "GLSL.std.450"', f"OpMemoryModel {'PhysicalStorageBuffer64' if psb else 'Logical'} {'Vulkan' if gen.uses_vmm else 'GLSL450'}", f"OpEntryPoint {model} %main \"main\" {' '.join(iface)}"] if cs: hdr.append("OpExecutionMode %main LocalSize {} {} {}".format(*((64, 1, 1) if gen.cs_serial else gen.cs["size"]))) if gsx: hdr += ["OpExecutionMode %main Triangles", "OpExecutionMode %main Invocations 1", "OpExecutionMode %main OutputTriangleStrip", f"OpExecutionMode %main OutputVertices {gen.gs['maxv']}"] if msc: hdr.append("OpExecutionMode %main LocalSize {} {} {}".format(*((64, 1, 1) if gen.ms_serial else gen.ms["size"]))) elif ms: hdr += ["OpExecutionMode %main LocalSize {} {} {}".format(*((64, 1, 1) if gen.ms_serial else gen.ms["size"])), f"OpExecutionMode %main OutputVertices {gen.ms['maxv']}", f"OpExecutionMode %main OutputPrimitivesEXT {gen.ms['maxp']}", "OpExecutionMode %main OutputTrianglesEXT"] if gen.stage == "ps": hdr.append("OpExecutionMode %main OriginUpperLeft") if pops: hdr.append("OpExecutionMode %main PixelInterlockOrderedEXT") if gen.writes_depth: hdr.append("OpExecutionMode %main DepthReplacing") elif (EARLY_DEPTH and gen.db_shader_control is not None and (gen.db_shader_control & fssm_header.DB_DEPTH_BEFORE_SHADER) and not (gen.db_shader_control & fssm_header.DB_DEPTH_STENCIL_EXPORT) and not gen.osg1_depth_stencil): gen.early_depth = True hdr.append("OpExecutionMode %main EarlyFragmentTests") if FLOAT_CONTROLS: hdr.append("OpExecutionMode %main SignedZeroInfNanPreserve 32") if gen.uses_f64: # SHADER-597: the same for doubles (Vulkan guarantees neither -0 nor NaN/inf for f64 without it), only # in modules that declare Float64; --no-float-controls leaves it out with the other modes. hdr.append("OpExecutionMode %main SignedZeroInfNanPreserve 64") hdr.append("OpExecutionMode %main DenormPreserve 16") if gen.ftz32: hdr.append("OpExecutionMode %main DenormFlushToZero 32") dec = [] if vs: dec.append("OpDecorate %vertex_index BuiltIn VertexIndex") dec.append("OpDecorate %instance_index BuiltIn InstanceIndex") dec.append("OpDecorate %base_vertex BuiltIn BaseVertex") dec.append("OpDecorate %base_instance BuiltIn BaseInstance") if cs: dec += ["OpDecorate %wg_id BuiltIn WorkgroupId", "OpDecorate %local_id BuiltIn LocalInvocationId"] if gsx: for r, sv in gen.gs["in"]: dec.append("OpDecorate %gs_in_pos BuiltIn Position" if sv == 1 else f"OpDecorate %gs_in{r} Location {r}") for r, sv in gen.gs["out"]: dec.append("OpDecorate %gs_out_pos BuiltIn Position" if sv == 1 else f"OpDecorate %gs_out{r} Location {r}") ms_clip_member = ms_cull_member = None if ms: dec += ["OpDecorate %wg_id BuiltIn WorkgroupId", "OpDecorate %num_wg BuiltIn NumWorkgroups", "OpDecorate %local_index BuiltIn LocalInvocationIndex"] if msc: pass # no mesh outputs: the epilogue stores to the --mesh-compute buffer elif ms_blk: dec += ["OpDecorate %ms_vtx_blk Block", "OpMemberDecorate %ms_vtx_blk 0 BuiltIn Position"] mi = 1 if gen.uses_clip: dec.append(f"OpMemberDecorate %ms_vtx_blk {mi} BuiltIn ClipDistance") ms_clip_member = mi mi += 1 if gen.uses_cull: dec.append(f"OpMemberDecorate %ms_vtx_blk {mi} BuiltIn CullDistance") ms_cull_member = mi mi += 1 else: dec.append("OpDecorate %ms_out_pos BuiltIn Position") if not msc: # CullPrimitiveEXT as Block+bool member (VUID-07036): array-of-bool is also legal, but # SPIRV-Tools ≤2025.1 falsely rejects it (#5980); the Block form passes both old and new validators. # PerPrimitiveEXT is a MemberDecorate on the bool (glslang / SPIRV-Tools MeshEXT tests). dec += ["OpDecorate %ms_prim_idx BuiltIn PrimitiveTriangleIndicesEXT", "OpDecorate %ms_cull_blk Block", "OpMemberDecorate %ms_cull_blk 0 BuiltIn CullPrimitiveEXT", "OpMemberDecorate %ms_cull_blk 0 PerPrimitiveEXT"] if gen.uses_layer: dec += ["OpMemberDecorate %ms_cull_blk 1 BuiltIn Layer", "OpMemberDecorate %ms_cull_blk 1 PerPrimitiveEXT"] if gen.uses_viewport: vp_member = 1 + gen.uses_layer dec += [f"OpMemberDecorate %ms_cull_blk {vp_member} BuiltIn ViewportIndex", f"OpMemberDecorate %ms_cull_blk {vp_member} PerPrimitiveEXT"] dec += [f"OpDecorate %ms_out_param{n} Location {n}" for n in sorted(gen.ms_params)] dec += [f"OpDecorate %ms_out_f16h{n}_{h} Location {gen.f16_half_locs[n][h]}" for n in ms_halves for h in (0, 1)] if vs: if gen.uses_clip: dec.append("OpDecorate %out_clip BuiltIn ClipDistance") if gen.uses_cull: dec.append("OpDecorate %out_cull BuiltIn CullDistance") if gen.uses_layer: dec.append("OpDecorate %out_layer BuiltIn Layer") if gen.uses_viewport: dec.append("OpDecorate %out_viewport BuiltIn ViewportIndex") for name, tgt in gen.outputs.items(): if name == "%out_pos": dec.append("OpDecorate %out_pos BuiltIn Position") else: dec.append(f"OpDecorate {name} Location {int(''.join(ch for ch in tgt if ch.isdigit()))}") for name, n in gen.inputs.items(): dec.append(f"OpDecorate {name} Location {n}") if n in gen.per_vertex: dec.append(f"OpDecorate {name} PerVertexKHR") elif name not in gen.interpolated: dec.append(f"OpDecorate {name} Flat") types = ["%void = OpTypeVoid", "%fn = OpTypeFunction %void", "%bool = OpTypeBool", "%uint = OpTypeInt 32 0", "%int = OpTypeInt 32 1", "%float = OpTypeFloat 32", "%v4float = OpTypeVector %float 4", "%v2float = OpTypeVector %float 2", "%umul = OpTypeStruct %uint %uint", "%smul = OpTypeStruct %int %int", "%n256 = OpConstant %uint 256", f"%n_sgprs = OpConstant %uint {gen.SGPRS + len(gen.parked)}", "%arr_v = OpTypeArray %uint %n256", "%arr_s = OpTypeArray %uint %n_sgprs", "%null_v = OpConstantNull %arr_v", "%null_s = OpConstantNull %arr_s", "%_ptr_Function_arr_v = OpTypePointer Function %arr_v", "%_ptr_Function_arr_s = OpTypePointer Function %arr_s", "%_ptr_Function_uint = OpTypePointer Function %uint", "%_ptr_Output_v4 = OpTypePointer Output %v4float", "%_ptr_Input_int = OpTypePointer Input %int", "%_ptr_Input_v4 = OpTypePointer Input %v4float", "%_ptr_Input_float = OpTypePointer Input %float", "%f0 = OpConstant %float 0", "%f1 = OpConstant %float 1", "%true = OpConstantTrue %bool", "%false = OpConstantFalse %bool", "%_ptr_Function_bool = OpTypePointer Function %bool"] if psb: types += ["%ulong = OpTypeInt 64 0", "%c64_32 = OpConstant %ulong 32", "%long = OpTypeInt 64 1", "%rt_uint = OpTypeRuntimeArray %uint", "%_ptr_PSB_arr = OpTypePointer PhysicalStorageBuffer %rt_uint", "%_ptr_PSB_uint = OpTypePointer PhysicalStorageBuffer %uint"] dec.append("OpDecorate %rt_uint ArrayStride 4") if gen.uses_psb_scalar_ro: types += ["%sl_blk1 = OpTypeStruct %uint", "%_ptr_PSB_sl_blk1 = OpTypePointer PhysicalStorageBuffer %sl_blk1"] dec += ["OpDecorate %sl_blk1 Block", "OpMemberDecorate %sl_blk1 0 Offset 0", "OpMemberDecorate %sl_blk1 0 NonWritable"] if gen.uses_psb_vec or gen.uses_psb_vec_rw: # dedupe_types merges these with any other uvec2 / uvec4 types += ["%v2uint_sl = OpTypeVector %uint 2", "%v4uint_sl = OpTypeVector %uint 4", "%_ptr_PSB_v2uint_sl = OpTypePointer PhysicalStorageBuffer %v2uint_sl", "%_ptr_PSB_v4uint_sl = OpTypePointer PhysicalStorageBuffer %v4uint_sl"] if gen.uses_psb_vec: types += ["%sl_blk2 = OpTypeStruct %v2uint_sl", "%sl_blk4 = OpTypeStruct %v4uint_sl", "%_ptr_PSB_sl_blk2 = OpTypePointer PhysicalStorageBuffer %sl_blk2", "%_ptr_PSB_sl_blk4 = OpTypePointer PhysicalStorageBuffer %sl_blk4"] for blk in ("%sl_blk2", "%sl_blk4"): dec += [f"OpDecorate {blk} Block", f"OpMemberDecorate {blk} 0 Offset 0", f"OpMemberDecorate {blk} 0 NonWritable"] if gen.uses_psb_vec_rw: types += ["%sl_rw_blk2 = OpTypeStruct %v2uint_sl", "%sl_rw_blk4 = OpTypeStruct %v4uint_sl", "%_ptr_PSB_sl_rw_blk2 = OpTypePointer PhysicalStorageBuffer %sl_rw_blk2", "%_ptr_PSB_sl_rw_blk4 = OpTypePointer PhysicalStorageBuffer %sl_rw_blk4"] for blk in ("%sl_rw_blk2", "%sl_rw_blk4"): dec += [f"OpDecorate {blk} Block", f"OpMemberDecorate {blk} 0 Offset 0"] types += [f"{name} = OpConstant %ulong {v}" for v, name in sorted(gen.lconsts.items())] if tex: # Bindless set 0: images (binding 0), samplers (binding 1), descriptor hash table (binding 2). types += ["%img2d = OpTypeImage %float 2D 0 0 0 1 Unknown", "%smp = OpTypeSampler", "%simg2d = OpTypeSampledImage %img2d", "%v2int = OpTypeVector %int 2", "%rt_img = OpTypeRuntimeArray %img2d", "%rt_smp = OpTypeRuntimeArray %smp", "%_ptr_UC_rt_img = OpTypePointer UniformConstant %rt_img", "%_ptr_UC_rt_smp = OpTypePointer UniformConstant %rt_smp", "%_ptr_UC_img = OpTypePointer UniformConstant %img2d", "%_ptr_UC_smp = OpTypePointer UniformConstant %smp", "%rt_map = OpTypeRuntimeArray %uint", "%DescMap = OpTypeStruct %rt_map", "%_ptr_SB_DescMap = OpTypePointer StorageBuffer %DescMap", "%_ptr_SB_uint = OpTypePointer StorageBuffer %uint"] dec += ["OpDecorate %images DescriptorSet 0", "OpDecorate %images Binding 0", "OpDecorate %samplers DescriptorSet 0", "OpDecorate %samplers Binding 1", "OpDecorate %desc_map DescriptorSet 0", "OpDecorate %desc_map Binding 2", "OpDecorate %DescMap Block", "OpMemberDecorate %DescMap 0 Offset 0", "OpDecorate %rt_map ArrayStride 4", "OpDecorate %desc_map NonWritable"] types += ["%v3float = OpTypeVector %float 3", "%v3int = OpTypeVector %int 3"] if gen.uses_tex_array: types += ["%img2da = OpTypeImage %float 2D 0 1 0 1 Unknown", "%simg2da = OpTypeSampledImage %img2da", "%rt_imga = OpTypeRuntimeArray %img2da", "%_ptr_UC_rt_imga = OpTypePointer UniformConstant %rt_imga", "%_ptr_UC_imga = OpTypePointer UniformConstant %img2da"] dec += ["OpDecorate %images_arr DescriptorSet 0", "OpDecorate %images_arr Binding 3"] if gen.uses_storage3d: types += ["%simg3d_u = OpTypeImage %uint 3D 0 0 0 2 R32ui", "%rt_simg3 = OpTypeRuntimeArray %simg3d_u", "%_ptr_UC_rt_simg3 = OpTypePointer UniformConstant %rt_simg3", "%_ptr_UC_simg3 = OpTypePointer UniformConstant %simg3d_u"] if not gen.uses_storage: types += ["%_ptr_Image_uint = OpTypePointer Image %uint"] dec += ["OpDecorate %simages3d DescriptorSet 0", "OpDecorate %simages3d Binding 7"] if gen.uses_tex_3d: types += ["%img3d = OpTypeImage %float 3D 0 0 0 1 Unknown", "%simg3d = OpTypeSampledImage %img3d", "%rt_img3 = OpTypeRuntimeArray %img3d", "%_ptr_UC_rt_img3 = OpTypePointer UniformConstant %rt_img3", "%_ptr_UC_img3 = OpTypePointer UniformConstant %img3d"] dec += ["OpDecorate %images_3d DescriptorSet 0", "OpDecorate %images_3d Binding 6"] if gen.uses_tex_1d: types += ["%img1d = OpTypeImage %float 1D 0 0 0 1 Unknown", "%simg1d = OpTypeSampledImage %img1d", "%rt_img1 = OpTypeRuntimeArray %img1d", "%_ptr_UC_rt_img1 = OpTypePointer UniformConstant %rt_img1", "%_ptr_UC_img1 = OpTypePointer UniformConstant %img1d"] dec += ["OpDecorate %images_1d DescriptorSet 0", "OpDecorate %images_1d Binding 5"] if gen.uses_storage: types += ["%simg2d_u = OpTypeImage %uint 2D 0 0 0 2 R32ui", "%rt_simg = OpTypeRuntimeArray %simg2d_u", "%_ptr_UC_rt_simg = OpTypePointer UniformConstant %rt_simg", "%_ptr_UC_simg = OpTypePointer UniformConstant %simg2d_u", "%_ptr_Image_uint = OpTypePointer Image %uint", "%v4uint = OpTypeVector %uint 4"] dec += ["OpDecorate %simages DescriptorSet 0", "OpDecorate %simages Binding 4"] if gen.uses_storage64: if not psb: types += ["%ulong = OpTypeInt 64 0", "%c64_32 = OpConstant %ulong 32"] types += ["%simg64 = OpTypeImage %ulong 2D 0 0 0 2 R64ui", "%rt_simg64 = OpTypeRuntimeArray %simg64", "%_ptr_UC_rt_simg64 = OpTypePointer UniformConstant %rt_simg64", "%_ptr_UC_simg64 = OpTypePointer UniformConstant %simg64", "%_ptr_Image_ulong = OpTypePointer Image %ulong"] dec += ["OpDecorate %simages64 DescriptorSet 0", "OpDecorate %simages64 Binding 29"] if sg: types += ["%_ptr_Input_uint = OpTypePointer Input %uint"] dec += ["OpDecorate %sg_lane BuiltIn SubgroupLocalInvocationId"] if gen.stage == "ps": dec += ["OpDecorate %sg_lane Flat"] gen.consts.setdefault(3, "%c3") if vs: gen.consts.setdefault(3, "%c3") # the instance index goes to v3 if gen.uses_clip: gen.cu(gen.clip_count) if gen.uses_cull: gen.cu(gen.cull_count) if ms_blk: gen.cu(0) if ms_clip_member is not None: gen.cu(ms_clip_member) if ms_cull_member is not None: gen.cu(ms_cull_member) # The buffer-format tables below (uses_fmt_size, uses_store_views/uses_int_fetch) build their # array types from gen.cu ids. Register those constants here, before the dump: a cu() call # after it returns an id that is never defined, and spirv-as then rejects the module. if gen.uses_fmt_size: gen.cu(128) for c in range(128): if c in Gen.FORMATS: gen.cu(Gen.FORMATS[c][0]) if gen.uses_fmt_tables: gen.cu(128) gen.cu(17) if gen.uses_fmt_enc_table: gen.cu(128) for v in Gen.fmt_enc_desc_table(): gen.cu(v) if store_dims or gen.uses_int_fetch or gen.uses_d16_image: gen.cu(16) if store_dims or gen.uses_int_fetch: for words in Gen.int_format_masks(): for w in words: gen.cu(w) if gen.uses_d16_image: for words in Gen.float_format_masks(): for w in words: gen.cu(w) gen.consts.setdefault(0, "%c0") for v, name in sorted(gen.consts.items()): types.append(f"{name} = OpConstant %uint {v}") if gen.uses_lit_sampler_spec and gen.literal_samplers: for i in range(len(gen.literal_samplers)): dec.append(f"OpDecorate %lit_smp_{i} SpecId {i}") types.append(f"%lit_smp_{i} = OpSpecConstant %uint 4294967295") # fconst's floats (%f0 and %f1 are declared with the types above). types += [f"{name} = OpConstant %float {float_literal(v)}" for v, name in sorted(gen.fconsts.items()) if v not in (0, 0x3F800000)] written = dict(gen.consts) # what the module defines; insert_late_constants adds what assemble asks for later gen.fconsts_written = set(gen.fconsts) if gen.desc_fn: # --descriptor-table tagged: the probe also returns the entry's kind word, so the function returns (index, # kind) as a uvec2. if gen.descriptor_table != "plain": types.append("%desc_hit = OpTypeVector %uint 2") types.append("%fn_desc_lookup = OpTypeFunction %desc_hit " + " ".join(["%uint"] * 8)) else: types.append("%fn_desc_lookup = OpTypeFunction %uint " + " ".join(["%uint"] * 8)) if gen.tbuffer_norm_fns: types.append("%fn_tbuffer_norm = OpTypeFunction %uint %uint") if gen.guard_fn: # --address-guard: (heap_base, on, limit, table, offset, delta, sink) -> host address; no other function # type of the module has this signature. types.append("%fn_guard = OpTypeFunction %ulong %ulong %bool %ulong %ulong %ulong %ulong %ulong") for n in sorted({k[0] for k in gen.sbuf_slow_fns}): types += [f"%arr_sbuf_x{n} = OpTypeArray %uint {gen.cu(n)}", f"%_ptr_Function_arr_sbuf_x{n} = OpTypePointer Function %arr_sbuf_x{n}", f"%null_sbuf_x{n} = OpConstantNull %arr_sbuf_x{n}", f"%fn_sbuf_slow_x{n} = OpTypeFunction %arr_sbuf_x{n} %ulong %ulong %ulong"] if gen.fmt_fn or gen.fmt_enc_fn: types.append("%v4uint_fmt = OpTypeVector %uint 4") # dedupe_types merges it with any other uvec4 if gen.fmt_fn: # The decode function takes the format code, the element's four dwords as a v4uint and the component: a type # of its own structure, so it never repeats another function type in the module (SPIR-V forbids that). types.append("%fn_fmt_dec = OpTypeFunction %uint %uint %v4uint_fmt %uint") types.append("%fn_fmt_norm = OpTypeFunction %uint %uint %uint") if gen.fmt_enc_fn: types.append("%fn_fmt_enc_chan = OpTypeFunction %uint %uint %uint %uint %bool") types.append("%fn_fmt_encode = OpTypeFunction %v4uint_fmt " + " ".join(["%uint"] * 29)) for arity, fn_type in sorted(gen.x_round_fn_types.items()): types.append(f"{fn_type} = OpTypeFunction %uint " + " ".join(["%uint"] * arity)) # dedupe_types keeps the first uvec4 it meets: when the typed-image types follow, declare the ballot type after # them, so a shader that gains a ballot keeps the name %v4uint_st (SHADER-1016). st_types = bool(store_dims or gen.uses_int_fetch or gen.uses_d16_image) if gen.uses_ballot and not st_types: types.append("%v4uint_bal = OpTypeVector %uint 4") # dedupe_types merges it with any other uvec4 if gen.uses_bvh and not any(t.startswith("%v3float = ") for t in types): types.append("%v3float = OpTypeVector %float 3") has_uint_out = any(gen.output_ctypes.get(n) == 1 for n in gen.outputs) has_sint_out = any(gen.output_ctypes.get(n) == 2 for n in gen.outputs) has_float_partial = any(gen.output_ctypes.get(n, 3) == 3 for n in gen.partial_color_outputs) has_uint_partial = any(gen.output_ctypes.get(n) == 1 for n in gen.partial_color_outputs) has_sint_partial = any(gen.output_ctypes.get(n) == 2 for n in gen.partial_color_outputs) if has_float_partial: types.append("%initial_mrt = OpConstantNull %v4float") def _out_var(n): ct = gen.output_ctypes.get(n, 3) ptr = {1: "%_ptr_Output_v4u", 2: "%_ptr_Output_v4i"}.get(ct, "%_ptr_Output_v4") init = {1: " %initial_mrt_u", 2: " %initial_mrt_i"}.get(ct, " %initial_mrt") if n in gen.partial_color_outputs else "" return f"{n} = OpVariable {ptr} Output{init}" gvars = [_out_var(n) for n in gen.outputs] # Push constants: s0..s31 user data, then the tail: the 64-bit host address of the Xbox GPU VA window (heap # base), the code base and, with --mesh-compute, the output address. --pc-tail-ubo moves the tail to %pc_tail. tail = ["%uint"] * (6 if msc else 4) types += [f"%n_ud = OpConstant %uint {USER_SGPRS}", "%arr_ud = OpTypeArray %uint %n_ud", " ".join(["%UserData = OpTypeStruct %arr_ud"] + ([] if PC_TAIL_UBO else tail)), "%_ptr_PC_UserData = OpTypePointer PushConstant %UserData", "%_ptr_PC_uint = OpTypePointer PushConstant %uint"] dec += ["OpDecorate %arr_ud ArrayStride 4", "OpDecorate %UserData Block", "OpMemberDecorate %UserData 0 Offset 0"] if not PC_TAIL_UBO: dec += [f"OpMemberDecorate %UserData {k + 1} Offset {4 * USER_SGPRS + 4 * k}" for k in range(len(tail))] gvars += ["%user_data = OpVariable %_ptr_PC_UserData PushConstant"] if gen.uses_pc_tail: types += [" ".join(["%PcTail = OpTypeStruct"] + tail), "%_ptr_Uniform_PcTail = OpTypePointer Uniform %PcTail", "%_ptr_Uniform_uint_tail = OpTypePointer Uniform %uint"] dec += ["OpDecorate %PcTail Block"] + [f"OpMemberDecorate %PcTail {k} Offset {4 * k}" for k in range(len(tail))] dec += [f"OpDecorate %pc_tail DescriptorSet {PC_TAIL_SET}", f"OpDecorate %pc_tail Binding {PC_TAIL_BINDING}"] gvars += ["%pc_tail = OpVariable %_ptr_Uniform_PcTail Uniform"] if gen.uses_fhalf: types += ["%fhalf_g = OpConstant %float 0.5"] if gen.uses_f64: types += ["%double = OpTypeFloat 64"] if gen.uses_f64 or gen.uses_clock: types += ["%v2uint_d = OpTypeVector %uint 2"] if gen.uses_ballot and not st_types: types += ["%v4uint_bal = OpTypeVector %uint 4"] if gen.uses_fmt_size: sizes = [Gen.FORMATS[c][0] if c in Gen.FORMATS else 0 for c in range(128)] types += [f"%fmt_size_arr = OpTypeArray %uint {gen.cu(128)}", "%_ptr_Private_fmt_size = OpTypePointer Private %fmt_size_arr"] if not (store_dims or gen.uses_int_fetch or gen.uses_d16_image): types += ["%_ptr_Private_uint = OpTypePointer Private %uint"] types += ["%fmt_size_init = OpConstantComposite %fmt_size_arr " + " ".join(gen.cu(v) for v in sizes)] gvars += ["%fmt_size_tab = OpVariable %_ptr_Private_fmt_size Private %fmt_size_init"] if gen.uses_fmt_tables: # The run-time format's kind and channel widths, and the repeat constants of the exact norm quotient. types += [f"%fmt_desc_arr = OpTypeArray %uint {gen.cu(128)}", "%_ptr_Private_fmt_desc = OpTypePointer Private %fmt_desc_arr", "%_ptr_Private_fmt_elem = OpTypePointer Private %uint", f"%fmt_rep_arr = OpTypeArray %ulong {gen.cu(17)}", "%_ptr_Private_fmt_rep = OpTypePointer Private %fmt_rep_arr", "%_ptr_Private_fmt_elem64 = OpTypePointer Private %ulong"] types.append("%fmt_desc_init = OpConstantComposite %fmt_desc_arr " + " ".join(gen.consts[v] for v in Gen.fmt_desc_table())) types.append("%fmt_norm_rep_init = OpConstantComposite %fmt_rep_arr " + " ".join(gen.lconsts[v] for v in Gen.fmt_norm_reps())) gvars += ["%fmt_desc_tab = OpVariable %_ptr_Private_fmt_desc Private %fmt_desc_init", "%fmt_norm_rep_tab = OpVariable %_ptr_Private_fmt_rep Private %fmt_norm_rep_init"] if gen.uses_fmt_enc_table: types += [f"%fmt_enc_desc_arr = OpTypeArray %uint {gen.cu(128)}", "%_ptr_Private_fmt_enc_desc = OpTypePointer Private %fmt_enc_desc_arr", "%_ptr_Private_fmt_enc_elem = OpTypePointer Private %uint"] types.append("%fmt_enc_desc_init = OpConstantComposite %fmt_enc_desc_arr " + " ".join(gen.consts[v] for v in Gen.fmt_enc_desc_table())) gvars += ["%fmt_enc_desc_tab = OpVariable %_ptr_Private_fmt_enc_desc Private %fmt_enc_desc_init"] if store_dims or gen.uses_int_fetch or gen.uses_d16_image: u, si = Gen.int_format_masks() types += ["%v4uint_st = OpTypeVector %uint 4", "%v4int_st = OpTypeVector %int 4", *(["%v4uint_bal = OpTypeVector %uint 4"] if gen.uses_ballot else []), f"%fmt_mask_arr = OpTypeArray %uint {gen.cu(16)}", "%_ptr_Private_fmt = OpTypePointer Private %fmt_mask_arr", "%_ptr_Private_uint = OpTypePointer Private %uint"] mask_tables = () if store_dims or gen.uses_int_fetch: mask_tables += (("uint", u), ("sint", si)) if gen.uses_d16_image: mask_tables += (("norm", Gen.float_format_masks()[0]), ("f32", Gen.float_format_masks()[1])) for nm, words in mask_tables: ids = " ".join(gen.cu(w) for w in words) types += [f"%fmt_{nm}_init = OpConstantComposite %fmt_mask_arr {ids}"] gvars += [f"%fmt_{nm}_mask = OpVariable %_ptr_Private_fmt Private %fmt_{nm}_init"] # Typed image_load: uint/sint aliases of the dimension's sampled array (same set and binding; Vulkan allows # several variables on one binding when the descriptor type fits). The runtime binds each image's view in # its own format there, so the alias whose component type matches it is the one a shader reads through. for di in sorted(gen.uses_int_fetch): _, sdim, arr, _ = next(v for v in Gen.STORE_DIMS.values() if v[0] == di) for cls, st in ((1, "%uint"), (2, "%int")): types += [f"%itximg{cls}_{di} = OpTypeImage {st} {sdim} 0 {arr} 0 1 Unknown", f"%rt_itx{cls}_{di} = OpTypeRuntimeArray %itximg{cls}_{di}", f"%_ptr_UC_rt_itx{cls}_{di} = OpTypePointer UniformConstant %rt_itx{cls}_{di}", f"%_ptr_UC_itx{cls}_{di} = OpTypePointer UniformConstant %itximg{cls}_{di}"] if gen.uses_int_sampler: types.append(f"%itxsamp{cls}_{di} = OpTypeSampledImage %itximg{cls}_{di}") dec += [f"OpDecorate %itx{cls}_{di} DescriptorSet 0", f"OpDecorate %itx{cls}_{di} Binding {Gen.SAMPLED_BINDINGS[di]}"] gvars += [f"%itx{cls}_{di} = OpVariable %_ptr_UC_rt_itx{cls}_{di} UniformConstant"] for di in sorted(store_dims): _, sdim, arr, _ = next(v for v in Gen.STORE_DIMS.values() if v[0] == di) # Keep the runtime's multisample SRV bindings (20–25); 1D-array storage follows them. base = 26 if di == 4 else 8 + 3 * di for cls, st in enumerate(("%float", "%uint", "%int")): types += [f"%stimg{cls}_{di} = OpTypeImage {st} {sdim} 0 {arr} 0 2 Unknown", f"%rt_stv{cls}_{di} = OpTypeRuntimeArray %stimg{cls}_{di}", f"%_ptr_UC_rt_stv{cls}_{di} = OpTypePointer UniformConstant %rt_stv{cls}_{di}", f"%_ptr_UC_stv{cls}_{di} = OpTypePointer UniformConstant %stimg{cls}_{di}"] dec += [f"OpDecorate %stv{cls}_{di} DescriptorSet 0", f"OpDecorate %stv{cls}_{di} Binding {base + cls}"] if gen.coherent_images and not gen.uses_vmm: dec.append(f"OpDecorate %stv{cls}_{di} Coherent") gvars += [f"%stv{cls}_{di} = OpVariable %_ptr_UC_rt_stv{cls}_{di} UniformConstant"] if gsx: nst = gen.gs["maxv"] * gen.gs["nreg"] types += [f"%gs_arr_in = OpTypeArray %v4float {gen.cu(3)}", "%_ptr_Input_gs_arr = OpTypePointer Input %gs_arr_in", "%_ptr_Output_v4_gs = OpTypePointer Output %v4float", f"%gs_stage_arr = OpTypeArray %v4float {gen.cu(nst)}", "%_ptr_Function_gs_stage = OpTypePointer Function %gs_stage_arr", "%_ptr_Function_v4_gs = OpTypePointer Function %v4float", "%null_gs_stage = OpConstantNull %gs_stage_arr"] gvars += [("%gs_in_pos" if sv == 1 else f"%gs_in{r}") + " = OpVariable %_ptr_Input_gs_arr Input" for r, sv in gen.gs["in"]] gvars += [("%gs_out_pos" if sv == 1 else f"%gs_out{r}") + " = OpVariable %_ptr_Output_v4_gs Output" for r, sv in gen.gs["out"]] if ms: maxv, maxp = gen.cu(gen.ms["maxv"]), gen.cu(gen.ms["maxp"]) types += ["%v3uint = OpTypeVector %uint 3", "%_ptr_Input_v3u = OpTypePointer Input %v3uint", "%_ptr_Input_uint_ms = OpTypePointer Input %uint", "%_ptr_WG_uint_ms = OpTypePointer Workgroup %uint", f"%ms_arr_v4 = OpTypeArray %v4float {maxv}", "%_ptr_Out_ms_arr_v4 = OpTypePointer Output %ms_arr_v4", "%_ptr_Out_v4_ms = OpTypePointer Output %v4float", f"%ms_arr_idx = OpTypeArray %v3uint {maxp}", "%_ptr_Out_ms_arr_idx = OpTypePointer Output %ms_arr_idx", "%_ptr_Out_v3u_ms = OpTypePointer Output %v3uint", "%ms_cull_blk = OpTypeStruct " + " ".join(["%bool"] + ["%int"] * (gen.uses_layer + gen.uses_viewport)), f"%ms_arr_cull = OpTypeArray %ms_cull_blk {maxp}", "%_ptr_Out_ms_arr_cull = OpTypePointer Output %ms_arr_cull", "%_ptr_Out_bool_ms = OpTypePointer Output %bool", "%_ptr_Out_int_ms = OpTypePointer Output %int", "%_ptr_Function_int_ms = OpTypePointer Function %int", "%null_int_ms = OpConstantNull %int", "%_ptr_Function_v4_ms = OpTypePointer Function %v4float", "%_ptr_Function_bool_ms = OpTypePointer Function %bool", "%null_v4_ms = OpConstantNull %v4float"] if ms and (gen.uses_clip or gen.uses_cull): # staging arrays; the Output block only without msc types += ["%_ptr_Function_float = OpTypePointer Function %float", "%_ptr_Out_float_ms = OpTypePointer Output %float"] blk_fields = ["%v4float"] if gen.uses_clip: types += [f"%ms_arr_clip = OpTypeArray %float {gen.cu(gen.clip_count)}", "%_ptr_Fn_ms_clip = OpTypePointer Function %ms_arr_clip", "%null_ms_clip = OpConstantNull %ms_arr_clip"] blk_fields.append("%ms_arr_clip") if gen.uses_cull: types += [f"%ms_arr_cull_d = OpTypeArray %float {gen.cu(gen.cull_count)}", "%_ptr_Fn_ms_cull_d = OpTypePointer Function %ms_arr_cull_d", "%null_ms_cull_d = OpConstantNull %ms_arr_cull_d"] blk_fields.append("%ms_arr_cull_d") types += [f"%ms_vtx_blk = OpTypeStruct {' '.join(blk_fields)}", f"%ms_arr_vtx_blk = OpTypeArray %ms_vtx_blk {maxv}", "%_ptr_Out_ms_arr_vtx_blk = OpTypePointer Output %ms_arr_vtx_blk"] gvars += ["%wg_id = OpVariable %_ptr_Input_v3u Input", "%num_wg = OpVariable %_ptr_Input_v3u Input", "%local_index = OpVariable %_ptr_Input_uint_ms Input", "%ms_counts = OpVariable %_ptr_WG_uint_ms Workgroup"] if not msc: gvars += [("%ms_out_vtx = OpVariable %_ptr_Out_ms_arr_vtx_blk Output" if ms_blk else "%ms_out_pos = OpVariable %_ptr_Out_ms_arr_v4 Output"), "%ms_prim_idx = OpVariable %_ptr_Out_ms_arr_idx Output", "%ms_cull = OpVariable %_ptr_Out_ms_arr_cull Output"] gvars += [f"%ms_out_param{n} = OpVariable %_ptr_Out_ms_arr_v4 Output" for n in sorted(gen.ms_params)] gvars += [f"%ms_out_f16h{n}_{h} = OpVariable %_ptr_Out_ms_arr_v4 Output" for n in ms_halves for h in (0, 1)] if gen.uses_lds: types += [f"%lds_arr = OpTypeArray %uint {gen.cu(max(gen.lds_dwords, 1))}", "%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr", "%_ptr_WG_uint = OpTypePointer Workgroup %uint"] gvars += ["%lds = OpVariable %_ptr_WG_lds Workgroup"] if gen.emulate: types += [f"%x_arr = OpTypeArray %uint {gen.cu(x_sink + 1)}", "%_ptr_WG_x_arr = OpTypePointer Workgroup %x_arr", "%_ptr_WG_uint_x = OpTypePointer Workgroup %uint"] gvars += ["%x_buf = OpVariable %_ptr_WG_x_arr Workgroup"] elif gen.bar_rounds and not gen.bar_counts_in_lds(): # Barrier rounds: one count of the invocations not done per round, 3 slots by round mod 3 (bar_scheduler). # With a large LDS the count borrows an LDS word instead (SHADER-579, bar_counts_in_lds). types += [f"%x_arr = OpTypeArray %uint {gen.cu(3)}", "%_ptr_WG_x_arr = OpTypePointer Workgroup %x_arr", "%_ptr_WG_uint_x = OpTypePointer Workgroup %uint"] gvars += ["%x_buf = OpVariable %_ptr_WG_x_arr Workgroup"] if cs: types += ["%v3uint = OpTypeVector %uint 3", "%_ptr_Input_v3u = OpTypePointer Input %v3uint"] gvars += ["%wg_id = OpVariable %_ptr_Input_v3u Input", "%local_id = OpVariable %_ptr_Input_v3u Input"] if gen.cs_serial: types += ["%_ptr_Function_v3u = OpTypePointer Function %v3uint"] if gen.uses_lds: types += [f"%lds_arr = OpTypeArray %uint {gen.cu(max(gen.lds_dwords, 1))}", "%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr", "%_ptr_WG_uint = OpTypePointer Workgroup %uint"] gvars += ["%lds = OpVariable %_ptr_WG_lds Workgroup"] # SHADER-309: what fit_shared_memory could not shrink. The LDS counts at its RSRC2 allocation when that is # larger than the array (clipped to 16384 dwords): a declared allocation over the cap is refused, not cut. # An access past the allocation is out of range on hardware (reads 0, writes dropped; lds_access). lds_b = 4 * max(gen.lds_dwords, gen.lds_declared, 1) if gen.uses_lds else 0 wg = lds_b + gen.x_buf_bytes() if wg > MAX_SHARED_BYTES: raise Unsupported(f"CS workgroup memory {wg} B (LDS {lds_b} B + " f"{'wave64 exchange' if gen.emulate else 'barrier rounds'} {gen.x_buf_bytes()} B) " f"over maxComputeSharedMemorySize {MAX_SHARED_BYTES} B") if gen.frag_inputs or bary: dec += ["OpDecorate %frag_coord BuiltIn FragCoord"] gvars += ["%frag_coord = OpVariable %_ptr_Input_v4 Input"] if "front" in gen.frag_inputs.values(): types += ["%_ptr_Input_bool = OpTypePointer Input %bool"] dec += ["OpDecorate %front_facing BuiltIn FrontFacing"] gvars += ["%front_facing = OpVariable %_ptr_Input_bool Input"] if bary: if not tex: types += ["%v3float = OpTypeVector %float 3"] types += ["%_ptr_Input_v3f = OpTypePointer Input %v3float"] # Default (smooth) interpolation is perspective-correct, matching BaryCoordKHR (not BaryCoordNoPerspKHR). dec += ["OpDecorate %bary BuiltIn BaryCoordKHR" if bary_builtin else f"OpDecorate %bary Location {gen.bary_location}"] gvars += ["%bary = OpVariable %_ptr_Input_v3f Input"] if gen.vertex_inputs: types += ["%v4uint_in = OpTypeVector %uint 4", "%v4int_in = OpTypeVector %int 4", "%_ptr_Input_v4u = OpTypePointer Input %v4uint_in", "%_ptr_Input_v4i = OpTypePointer Input %v4int_in"] for reg, ctype in gen.vertex_inputs: dec.append(f"OpDecorate %vin{reg} Location {reg}") if has_uint_out: types += ["%v4uint_out = OpTypeVector %uint 4", "%_ptr_Output_v4u = OpTypePointer Output %v4uint_out"] if has_uint_partial: types.append("%initial_mrt_u = OpConstantNull %v4uint_out") if has_sint_out: types += ["%v4int_out = OpTypeVector %int 4", "%_ptr_Output_v4i = OpTypePointer Output %v4int_out"] if has_sint_partial: types.append("%initial_mrt_i = OpConstantNull %v4int_out") if gen.writes_depth: types += ["%_ptr_Output_float = OpTypePointer Output %float"] dec += ["OpDecorate %out_depth BuiltIn FragDepth"] gvars += ["%out_depth = OpVariable %_ptr_Output_float Output"] if vs: if gen.uses_clip or gen.uses_cull: types += ["%_ptr_Output_float = OpTypePointer Output %float"] if gen.uses_clip: types += [f"%arr_clip = OpTypeArray %float {gen.cu(gen.clip_count)}", "%_ptr_Out_arr_clip = OpTypePointer Output %arr_clip"] gvars += ["%out_clip = OpVariable %_ptr_Out_arr_clip Output"] if gen.uses_cull: types += [f"%arr_cull = OpTypeArray %float {gen.cu(gen.cull_count)}", "%_ptr_Out_arr_cull = OpTypePointer Output %arr_cull"] gvars += ["%out_cull = OpVariable %_ptr_Out_arr_cull Output"] if gen.uses_layer or gen.uses_viewport: types += ["%_ptr_Output_int = OpTypePointer Output %int"] if gen.uses_layer: gvars += ["%out_layer = OpVariable %_ptr_Output_int Output"] if gen.uses_viewport: gvars += ["%out_viewport = OpVariable %_ptr_Output_int Output"] if gen.per_vertex: # the three vertices' raw words for Gen.attribute types += [f"%arr_pv4 = OpTypeArray %v4float {gen.cu(3)}", "%_ptr_Input_pv4 = OpTypePointer Input %arr_pv4"] gvars += [f"{n} = OpVariable {'%_ptr_Input_pv4' if k in gen.per_vertex else '%_ptr_Input_v4'} Input" for n, k in gen.inputs.items()] if sg: gvars += ["%sg_lane = OpVariable %_ptr_Input_uint Input"] if tex: gvars += ["%images = OpVariable %_ptr_UC_rt_img UniformConstant", "%samplers = OpVariable %_ptr_UC_rt_smp UniformConstant", "%desc_map = OpVariable %_ptr_SB_DescMap StorageBuffer"] if gen.uses_tex_array: gvars += ["%images_arr = OpVariable %_ptr_UC_rt_imga UniformConstant"] if gen.uses_storage: gvars += ["%simages = OpVariable %_ptr_UC_rt_simg UniformConstant"] if gen.uses_tex_1d: gvars += ["%images_1d = OpVariable %_ptr_UC_rt_img1 UniformConstant"] if gen.uses_tex_3d: gvars += ["%images_3d = OpVariable %_ptr_UC_rt_img3 UniformConstant"] if gen.uses_storage3d: gvars += ["%simages3d = OpVariable %_ptr_UC_rt_simg3 UniformConstant"] if gen.uses_storage64: gvars += ["%simages64 = OpVariable %_ptr_UC_rt_simg64 UniformConstant"] if vs: gvars.append("%vertex_index = OpVariable %_ptr_Input_int Input") gvars.append("%instance_index = OpVariable %_ptr_Input_int Input") gvars.append("%base_vertex = OpVariable %_ptr_Input_int Input") gvars.append("%base_instance = OpVariable %_ptr_Input_int Input") for reg, ctype in gen.vertex_inputs: ptr = {1: "%_ptr_Input_v4u", 2: "%_ptr_Input_v4i"}.get(ctype, "%_ptr_Input_v4") gvars.append(f"%vin{reg} = OpVariable {ptr} Input") fn = ["%main = OpFunction %void None %fn", "%entry = OpLabel", # Registers start at zero (deterministic); real inputs are written explicitly at entry. "%vgpr = OpVariable %_ptr_Function_arr_v Function %null_v", "%sgpr = OpVariable %_ptr_Function_arr_s Function %null_s", "%vcc = OpVariable %_ptr_Function_uint Function %c0", "%m0 = OpVariable %_ptr_Function_uint Function %c0", "%vcc_hi = OpVariable %_ptr_Function_uint Function %c0", "%scc = OpVariable %_ptr_Function_uint Function %c0", *(["%mode_r16 = OpVariable %_ptr_Function_uint Function %c0"] if gen.round_mode else []), "%active = OpVariable %_ptr_Function_bool Function %true", *[f"{var} = OpVariable {ptr} Function" for var, ptr in gen.eager_vars]] if gen.vm_latch: fn += ["%vm_mask = OpVariable %_ptr_Function_bool Function %true", "%vm_set = OpVariable %_ptr_Function_bool Function %false"] for t in gen.col_latched: fn += [f"%col_mask_{t} = OpVariable %_ptr_Function_bool Function %true", f"%col_set_{t} = OpVariable %_ptr_Function_bool Function %false"] if gen.emulate: fn += ["%x_it = OpVariable %_ptr_Function_uint Function %c0", "%x_bar = OpVariable %_ptr_Function_bool Function %false", "%x_chain = OpVariable %_ptr_Function_bool Function %false"] if gen.emulate_plan and gen.emulate_plan.get("mini_blocks"): fn.append("%x_ldone = OpVariable %_ptr_Function_bool Function %false") fn += [f"{var} = OpVariable {ptr} Function" for var, ptr in gen.x_spills] if gen.uses_perm: fn.append("%x_perm = OpVariable %_ptr_Function_uint Function %c0") elif gen.bar_rounds: fn += ["%x_it = OpVariable %_ptr_Function_uint Function %c0", "%x_bar = OpVariable %_ptr_Function_bool Function %false"] if gen.bar_counts_in_lds(): fn.append("%xb_save = OpVariable %_ptr_Function_uint Function %c0") fn += [f"{var} = OpVariable {ptr} Function" for var, ptr in gen.x_spills] # User data: s0..s31 are loaded at entry from a push-constant block (the driver's user-SGPR setup). if gen.uses_heap: gen.consts.setdefault(1, "%c1") gen.consts.setdefault(2, "%c2") fn += [pc_tail_chain("%ud_base_lo_p", 1, gen.cu), pc_tail_chain("%ud_base_hi_p", 2, gen.cu)] + HEAP_BASE_ENTRY if gen.uses_guard: fn += guard_entry(gen.cl, gen.cu) if gen.uses_codebase: fn += [pc_tail_chain("%ud_code_lo_p", 3, gen.cu), pc_tail_chain("%ud_code_hi_p", 4, gen.cu)] # A mesh shader reads its root arguments from the graphics window (user_data_dword, GRAPHICS_ROOT_DWORD). for i in range(USER_SGPRS): src = user_data_dword(gen.stage, i) if src is None: fn += [f"%ud{i}s = OpAccessChain %_ptr_Function_uint %sgpr {gen.cu(i)}", f"OpStore %ud{i}s {gen.cu(0)}"] continue fn += [f"%ud{i}p = OpAccessChain %_ptr_PC_uint %user_data %c0 {gen.cu(src)}", f"%ud{i} = OpLoad %uint %ud{i}p", f"%ud{i}s = OpAccessChain %_ptr_Function_uint %sgpr {gen.cu(i)}", f"OpStore %ud{i}s %ud{i}"] if gen.uses_pops and gen.pops_word_sgpr is not None: # The POPS collision word is the hardware's, not user data: whatever the push constants hold at its dword # (often 0, wave id == collision id) would keep a wave that enters the wait loop in it until the loop guard. fn += [f"%pops_word = OpAccessChain %_ptr_Function_uint %sgpr {gen.cu(gen.pops_word_sgpr)}", f"OpStore %pops_word {gen.cu(POPS_COLLISION_SEED)}"] if vs: # The hardware's VS input VGPRs are zero-based: v0 is the vertex id without the draw's base vertex and v3 # the instance id without its first instance (Mesa: ac.vertex_id = load_vertex_id_zero_base, the base in # the base_vertex SGPR; ac.instance_id = load_instance_id, the base in start_instance). Vulkan's # VertexIndex / InstanceIndex include firstVertex|vertexOffset / firstInstance, so subtract BaseVertex / # BaseInstance. GPU-checked with runtime/test/shaders/vs_base_ids.asm (VKH_DRAW=16,7). fn += ["%vi = OpLoad %int %vertex_index", "%bv = OpLoad %int %base_vertex", "%vz = OpISub %int %vi %bv", "%viu = OpBitcast %uint %vz", "%v0p = OpAccessChain %_ptr_Function_uint %vgpr %c0", "OpStore %v0p %viu"] # v3 = instance id. Over the corpus, the 494 VS that read v3 before writing it are exactly ones whose input # signature declares SV_InstanceID, and no VS reads v1 or v2 on entry. fn += ["%ii = OpLoad %int %instance_index", "%bi = OpLoad %int %base_instance", "%iz = OpISub %int %ii %bi", "%iiu = OpBitcast %uint %iz", f"%v3p = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(3)}", "OpStore %v3p %iiu"] if gsx: fn[2:2] = ["%gs_stage = OpVariable %_ptr_Function_gs_stage Function %null_gs_stage", "%gs_emitted = OpVariable %_ptr_Function_uint Function %c0"] # Input vertex i at dword 64*i (v0 = vtx0 | vtx1 << 16, v1 = vtx2); s3[15:8] = 64 lanes of work (the # prologue's s_bfm/s_cselect then leave EXEC full), s3[23:16] = 0. fn += [f"%gv0p = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(0)}", f"OpStore %gv0p {gen.cu(64 << 16)}", f"%gv1p = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(1)}", f"OpStore %gv1p {gen.cu(128)}", f"%gs3p = OpAccessChain %_ptr_Function_uint %sgpr {gen.cu(3)}", f"OpStore %gs3p {gen.cu(0x4000)}"] if ms: fn[2:2] = ["%ms_pos = OpVariable %_ptr_Function_v4_ms Function %null_v4_ms", "%ms_prim = OpVariable %_ptr_Function_uint Function %c0", "%ms_has_vtx = OpVariable %_ptr_Function_bool_ms Function %false", "%ms_has_prim = OpVariable %_ptr_Function_bool_ms Function %false"] + \ (["%ms_clip = OpVariable %_ptr_Fn_ms_clip Function %null_ms_clip"] if gen.uses_clip else []) + \ (["%ms_cull_dist = OpVariable %_ptr_Fn_ms_cull_d Function %null_ms_cull_d"] if gen.uses_cull else []) + \ (["%ms_layer = OpVariable %_ptr_Function_int_ms Function %null_int_ms"] if gen.uses_layer else []) + \ (["%ms_viewport = OpVariable %_ptr_Function_int_ms Function %null_int_ms"] if gen.uses_viewport else []) + \ [f"%ms_param{n} = OpVariable %_ptr_Function_v4_ms Function %null_v4_ms" for n in sorted(gen.ms_params)] # v5 = first launch vertex ID of the lane = linear group index * NumThreads + local index (the game's mesh # entry does v5 >> 7 on lane 0 to get the group index; NumThreads is 128 in this corpus). # s3 = merged-wave info with the wave id in [27:24]. fn += ["%wgi = OpLoad %v3uint %wg_id", "%nwg = OpLoad %v3uint %num_wg", "%lidx = OpLoad %uint %local_index", "%wgx = OpCompositeExtract %uint %wgi 0", "%wgy = OpCompositeExtract %uint %wgi 1", "%wgz = OpCompositeExtract %uint %wgi 2", "%nwx = OpCompositeExtract %uint %nwg 0", "%nwy = OpCompositeExtract %uint %nwg 1", "%nxy = OpIMul %uint %nwx %nwy", "%wz = OpIMul %uint %wgz %nxy", "%wy = OpIMul %uint %wgy %nwx", "%wyz = OpIAdd %uint %wy %wz", "%wlin = OpIAdd %uint %wgx %wyz", f"%wbase = OpIMul %uint %wlin {gen.cu(gen.ms['threads'])}", "%v5v = OpIAdd %uint %wbase %lidx", f"%v5p = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(5)}", "OpStore %v5p %v5v", f"%wave = OpShiftRightLogical %uint %lidx {gen.cu(6)}", f"%mwi = OpShiftLeftLogical %uint %wave {gen.cu(24)}", f"%s3p = OpAccessChain %_ptr_Function_uint %sgpr {gen.cu(3)}", "OpStore %s3p %mwi"] if cs: # After the user-data copy: workgroup ids overwrite s[user..], thread ids go to v0..v2. fn += ["%wgi = OpLoad %v3uint %wg_id", "%lci = OpLoad %v3uint %local_id"] for k, c in enumerate(gen.cs["tgid"]): r = gen.cs["user"] + k fn += [f"%wg{c} = OpCompositeExtract %uint %wgi {c}", f"%wgp{c} = OpAccessChain %_ptr_Function_uint %sgpr {gen.cu(r)}", f"OpStore %wgp{c} %wg{c}"] for c in range(gen.cs["tid"] + 1): fn += [f"%li{c} = OpCompositeExtract %uint %lci {c}", f"%lip{c} = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(c)}", f"OpStore %lip{c} %li{c}"] if gen.cs["tg_size"]: # TG_SIZE_EN (RSRC2 bit 10): the SGPR after the workgroup ids holds the number of waves in the group in # [5:0] and this wave's index in it in [11:6] (Mesa ac_nir_lower_intrinsics_to_args.c, GFX6-10: # load_num_subgroups is tg_size[5:0], load_subgroup_id tg_size[11:6], and a wave64 compute shader's # local invocation index is mbcnt(~0, tg_size & 0xfc0)), the wave index again in [24:20] (Mesa's GFX10.3 # field) and bit 31 set in the group's first wave. Measured on gfx1036 through tools/hw_oracle (#6446: # 100, 128 and 133 threads, wave32 and wave64; e.g. wave32 x 128 gives 80000004 00100044 00200084 # 003000c4); the other bits were 0 there. One pipeline-library program reads [24:20]. Not measured on # gfx1013. Thread i is in wave i / W, as for s_get_waveid_in_workgroup. sx, sy, sz = gen.cs["size"] w = 64 if gen.wave64 else 32 r = gen.cs["user"] + len(gen.cs["tgid"]) fn += ["%tgx = OpCompositeExtract %uint %lci 0", "%tgy = OpCompositeExtract %uint %lci 1", "%tgz = OpCompositeExtract %uint %lci 2", f"%tgyx = OpIMul %uint %tgy {gen.cu(sx)}", f"%tgzx = OpIMul %uint %tgz {gen.cu(sx * sy)}", "%tgi0 = OpIAdd %uint %tgx %tgyx", "%tgi = OpIAdd %uint %tgi0 %tgzx", f"%tgw = OpShiftRightLogical %uint %tgi {gen.cu(w.bit_length() - 1)}", f"%tgws = OpShiftLeftLogical %uint %tgw {gen.cu(6)}", f"%tgwh = OpShiftLeftLogical %uint %tgw {gen.cu(20)}", f"%tgf0 = OpIEqual %bool %tgw {gen.cu(0)}", f"%tgf = OpSelect %uint %tgf0 {gen.cu(0x80000000)} {gen.cu(0)}", f"%tgv0 = OpBitwiseOr %uint %tgws {gen.cu(-(-(sx * sy * sz) // w))}", "%tgv1 = OpBitwiseOr %uint %tgv0 %tgwh", "%tgv = OpBitwiseOr %uint %tgv1 %tgf", f"%tgp = OpAccessChain %_ptr_Function_uint %sgpr {gen.cu(r)}", "OpStore %tgp %tgv"] if gen.frag_inputs: fn += ["%fc = OpLoad %v4float %frag_coord"] if bary: fn += ["%bc = OpLoad %v3float %bary"] for r, c in gen.frag_inputs.items(): if str(c).startswith("bary"): k = 1 if c == "bary_i" else 2 fn += [f"%bc{k} = OpCompositeExtract %float %bc {k}", f"%bcu{k} = OpBitcast %uint %bc{k}", f"%bcp{k} = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(r)}", f"OpStore %bcp{k} %bcu{k}"] continue if c == "front": # The mask form, 0xffffffff front / 0 back (SPI_BARYC_CNTL.FRONT_FACE_ALL_BITS = 1, #5123): every # one of the corpus's 345 PS that reads FRONT_FACE tests it as an integer against 0 (344 # v_cmp_ne_u32, 1 v_cmp_eq_u32; SHADER-892), which the float form (+1.0 / -1.0, both non-zero) # would call front for every face. fn += ["%ff = OpLoad %bool %front_facing", f"%ffu = OpSelect %uint %ff {gen.cu(0xFFFFFFFF)} {gen.cu(0)}", f"%ffp = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(r)}", "OpStore %ffp %ffu"] continue fn += [f"%fc{c} = OpCompositeExtract %float %fc {c}", f"%fcu{c} = OpBitcast %uint %fc{c}", f"%fcp{c} = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(r)}", f"OpStore %fcp{c} %fcu{c}"] elif gen.ij_deriv: fn += ["%bc = OpLoad %v3float %bary"] if gen.ij_deriv: # Uniform %entry screen-quad barycentric Jacobian for computed-I/J pairs without PerVertexKHR (shortcut: see # Gen.ij_quad_eval for finite-difference error amplification proportional to pixel step and det == 0 -> P_c). # Test IEEE-754 normal range (0x00800000 <= |det|_bits < 0x7F800000) on integer bits so +-0, subnormals, # +-inf and NaNs fall back cleanly to P_c without OpFDiv-by-zero or MoltenVK OpFOrdNotEqual NaN hazards. fn += ["%ij_ic = OpCompositeExtract %float %bc 1", "%ij_jc = OpCompositeExtract %float %bc 2", "%ij_dix = OpDPdxFine %float %ij_ic", "%ij_diy = OpDPdyFine %float %ij_ic", "%ij_djx = OpDPdxFine %float %ij_jc", "%ij_djy = OpDPdyFine %float %ij_jc", "%ij_ad = OpFMul %float %ij_dix %ij_djy", "%ij_bc_m = OpFMul %float %ij_diy %ij_djx", "%ij_det = OpFSub %float %ij_ad %ij_bc_m", "%ij_du = OpBitcast %uint %ij_det", f"%ij_dabs = OpBitwiseAnd %uint %ij_du {gen.cu(0x7FFFFFFF)}", f"%ij_dlo = OpUGreaterThanEqual %bool %ij_dabs {gen.cu(0x00800000)}", f"%ij_dhi = OpULessThan %bool %ij_dabs {gen.cu(0x7F800000)}", "%ij_nz = OpLogicalAnd %bool %ij_dlo %ij_dhi", "%ij_sdet = OpSelect %float %ij_nz %ij_det %f1", "%ij_idet = OpFDiv %float %f1 %ij_sdet"] for (iname, icomp), tag in sorted(gen.ij_deriv.items(), key=lambda kv: kv[1]): fn += [f"%ijp_{tag} = OpAccessChain %_ptr_Input_float {iname} {gen.cu(icomp)}", f"%ijc_{tag} = OpLoad %float %ijp_{tag}", f"%ijx_{tag} = OpDPdxFine %float %ijc_{tag}", f"%ijy_{tag} = OpDPdyFine %float %ijc_{tag}"] for reg, ctype in gen.vertex_inputs: vt = {1: "%v4uint_in", 2: "%v4int_in"}.get(ctype, "%v4float") st = {1: "%uint", 2: "%int"}.get(ctype, "%float") fn.append(f"%vinv{reg} = OpLoad {vt} %vin{reg}") for c in range(4): vg = 4 + 4 * reg + c fn += [f"%vinc{reg}_{c} = OpCompositeExtract {st} %vinv{reg} {c}", f"%vinb{reg}_{c} = OpBitcast %uint %vinc{reg}_{c}" if ctype != 1 else f"%vinb{reg}_{c} = OpCopyObject %uint %vinc{reg}_{c}", f"%vinp{reg}_{c} = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(vg)}", f"OpStore %vinp{reg}_{c} %vinb{reg}_{c}"] for (kind, r), p in gen.reg_ptrs.items(): arr = "%vgpr" if kind == "vgpr" else "%sgpr" fn.append(f"{p} = OpAccessChain %_ptr_Function_uint {arr} {gen.cu(r)}") # Spill pointers last: a spilled value's type may be declared anywhere above. types += [f"{ptr} = OpTypePointer Function {t}" for t, ptr in gen.x_ptr_types.items()] helpers = (gen.desc_fn or []) + (gen.fmt_fn or []) + (gen.fmt_enc_fn or []) + (gen.guard_fn or []) for function in gen.tbuffer_norm_fns.values(): helpers.extend(function) for function in gen.x_round_fns.values(): helpers.extend(function) for key in sorted(gen.sbuf_slow_fns): helpers.extend(gen.sbuf_slow_fns[key]) tree, nesting = (capped_tree(gen.succ, gen.out_pcs) if gen.blocks and not gen.emulate and not gen.bar_rounds else (None, None)) if nesting is not None: gen.nesting = nesting gen.control_flow = "structured" if tree is not None else "dispatch loop" if gen.blocks else "straight line" if gen.emulate: gen.control_flow = "emulated wave64 structured" if gen.emulate_plan is not None else "emulated wave64 rounds" elif gen.bar_rounds: gen.control_flow = "barrier rounds" def place_structured(items, body, count): def label(prefix): count[0] += 1 return f"%{prefix}{count[0]}" stack = [("items", items)] while stack: step = stack.pop() if step[0] == "items": for it in reversed(step[1]): stack.append(("item", it)) elif step[0] == "item": it = step[1] if it[0] == "block": # Under its own label, as in the dispatch form: OpPhi in a body names it as a predecessor. body.extend([f"OpBranch %blk{it[1]}", f"%blk{it[1]} = OpLabel"] + gen.blocks[it[1]]) elif it[0] == "guard": v, c, do, end = label("g_pc"), label("g_is"), label("g_do"), label("g_end") body.extend([f"{v} = OpLoad %uint %pc", f"{c} = OpIEqual %bool {v} {gen.consts[it[1]]}", f"OpSelectionMerge {end} None", f"OpBranchConditional {c} {do} {end}", f"{do} = OpLabel"]) stack.append(("guard_end", end)) stack.append(("items", it[2])) else: head, top, cont, end = label("l_head"), label("l_body"), label("l_cont"), label("l_end") v, again = label("l_pc"), label("l_again") body.extend([f"OpBranch {head}", f"{head} = OpLabel", f"OpLoopMerge {end} {cont} None", f"OpBranch {top}", f"{top} = OpLabel"]) stack.append(("loop_end", it[1], head, cont, end, v, again)) stack.append(("items", it[2])) elif step[0] == "guard_end": body.extend([f"OpBranch {step[1]}", f"{step[1]} = OpLabel"]) else: _, blk_id, head, cont, end, v, again = step body.extend([f"OpBranch {cont}", f"{cont} = OpLabel", f"{v} = OpLoad %uint %pc", f"{again} = OpIEqual %bool {v} {gen.consts[blk_id]}", f"OpBranchConditional {again} {head} {end}", f"{end} = OpLabel"]) if tree is not None: # Real loops and conditionals (cfg_structure): the blocks nested by dominance, each behind a test of %pc, # and every natural loop as a loop that repeats while %pc names its header. lines = ["%pc = OpVariable %_ptr_Function_uint Function %c0", "%done = OpVariable %_ptr_Function_bool Function %false"] body, count = [], [0] place_structured(tree, body, count) elif gen.emulate and gen.emulate_plan is not None: plan = gen.emulate_plan lines = x_prologue(gen, x_threads) body, count = [], [0] if plan["mode"] == "inline_all": place_structured(plan["tree"], body, count) else: c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 for step in plan["steps"]: kind = step[0] if kind == "inline_block": b = step[1] body.extend([f"OpBranch %blk{b}", f"%blk{b} = OpLabel"] + gen.blocks[b]) elif kind == "inline_sync_free": _, it, pre_bar = step if pre_bar: body.append(f"OpControlBarrier {c(2)} {c(2)} {c(0x948)}") place_structured([it], body, count) elif kind == "mini_scheduler": _, midx, mblocks, pre_bar = step if pre_bar: body.append(f"OpControlBarrier {c(2)} {c(2)} {c(0x948)}") seg_ids = sorted(set(mblocks) | set(gen.mini_segs[midx])) body.extend(x_mini_scheduler(gen, midx, seg_ids)) for i in seg_ids: blines = gen.blocks[i] if i < len(gen.blocks) else gen.x_segs[i] body.append(f"%blk{i} = OpLabel") body += blines body.append(f"OpBranch %xm{midx}_sw_merge") body.extend(x_mini_scheduler_tail(gen, midx)) else: # tail_scheduler _, tblocks, pre_bar = step if pre_bar: body.append(f"OpControlBarrier {c(2)} {c(2)} {c(0x948)}") seg_ids = sorted(set(tblocks) | set(gen.tail_segs)) body.extend(x_round_loop_head(gen, seg_ids)) for i in seg_ids: blines = gen.blocks[i] if i < len(gen.blocks) else gen.x_segs[i] body.append(f"%blk{i} = OpLabel") body += blines body.append("OpBranch %sw_merge") body.extend(x_scheduler_tail(gen)) if sum(1 for l in lines + body if "OpControlBarrier" in l) < 2: body.append(f"OpControlBarrier {gen.consts[2]} {gen.consts[2]} {gen.consts[0x948]}") elif gen.emulate: lines = x_scheduler(gen, x_threads) body = [] for i, blines in sorted([(i, b) for i, b in enumerate(gen.blocks) if b is not None] + list(gen.x_segs.items())): body.append(f"%blk{i} = OpLabel") body += blines body.append("OpBranch %sw_merge") body += x_scheduler_tail(gen) elif gen.bar_rounds: lines = bar_scheduler(gen) body = [] for i, blines in sorted(list(enumerate(gen.blocks)) + list(gen.x_segs.items())): body.append(f"%blk{i} = OpLabel") body += blines body.append("OpBranch %sw_merge") body += bar_scheduler_tail(gen) elif gen.blocks: # Dispatch loop: any CFG (forward/backward branches) in structured SPIR-V form. Used for the irreducible # graphs cfg_structure refuses (a loop with two entries), and with --dispatch-loop. n = len(gen.blocks) lines = ["%pc = OpVariable %_ptr_Function_uint Function %c0", "%done = OpVariable %_ptr_Function_bool Function %false", "OpBranch %loop_head", "%loop_head = OpLabel", "OpLoopMerge %loop_exit %loop_cont None", "OpBranch %dispatch", "%dispatch = OpLabel", "%pcv = OpLoad %uint %pc", "OpSelectionMerge %sw_merge None", "OpSwitch %pcv %sw_default " + " ".join(f"{i} %blk{i}" for i in range(n))] body = [] for i, blines in enumerate(gen.blocks): body.append(f"%blk{i} = OpLabel") body += blines body.append("OpBranch %sw_merge") body += ["%sw_default = OpLabel", "OpStore %done %true", "OpBranch %sw_merge", "%sw_merge = OpLabel", "OpBranch %loop_cont", "%loop_cont = OpLabel", "%dn = OpLoad %bool %done", "OpBranchConditional %dn %loop_exit %loop_head", "%loop_exit = OpLabel"] if gen.blocks: # %pc/%done must be declared with the other Function variables, at the top of the entry block, # before the vertex-shader prologue. fn_vars = lines[:2] flow = lines[2:] last_var = max(i for i, l in enumerate(fn) if " = OpVariable " in l) fn = fn[:last_var + 1] + fn_vars + fn[last_var + 1:] gen.body =[" " + l if not (l.startswith("%") and " = OpLabel" in l) else l for l in flow + body] if pops: fn.append("OpBeginInvocationInterlockEXT") # end of the entry block: uniform, executed once serial_close, serial_exports = [], [] if (ms and gen.ms_serial) or gen.cs_serial: fn, serial_close, serial_exports = ms_serial_passes(gen, fn, (hdr, dec, gvars)) out = hdr + dec + types + gvars + helpers + fn end_lock = " OpEndInvocationInterlockEXT\n" if pops else "" if msc: # The slot writes of one invocation; with passes, once per pass from its twins (ms_serial_epilogue). Lane 0 # of pass 0 is then the only one that writes the header: a later pass's index starts at 64. L = ms_serial_epilogue(gen, gen.msc_epilogue, serial_exports) if gen.ms_serial else gen.msc_epilogue end_lock = "".join((" " + l if " = OpLabel" not in l else l) + "\n" for l in L) + end_lock elif ms: # All invocations reach the end: wait for the ALLOC_REQ write, declare the counts once (uniform), then each # thread writes the vertex and primitive it exported (index = LocalInvocationIndex). c = gen.cu L = ["OpControlBarrier %c2 %c2 " + c(0x108), "%msc = OpLoad %uint %ms_counts", f"%msv0 = OpBitwiseAnd %uint %msc {c(0xFFF)}", f"%msp1 = OpShiftRightLogical %uint %msc {c(12)}", f"%msp0 = OpBitwiseAnd %uint %msp1 {c(0xFFF)}", f"%msv = OpExtInst %uint %glsl UMin %msv0 {c(gen.ms['maxv'])}", *ms_prim_count(c, gen.ms['maxp']), "OpSetMeshOutputsEXT %msv %msp", "%mli = OpLoad %uint %local_index", "%mhv = OpLoad %bool %ms_has_vtx", "%mvi = OpULessThan %bool %mli %msv", "%mwv = OpLogicalAnd %bool %mhv %mvi", "OpSelectionMerge %ms_vend None", "OpBranchConditional %mwv %ms_vdo %ms_vend", "%ms_vdo = OpLabel", "%mpv = OpLoad %v4float %ms_pos", ("%mpp = OpAccessChain %_ptr_Out_v4_ms %ms_out_vtx %mli %c0" if ms_blk else "%mpp = OpAccessChain %_ptr_Out_v4_ms %ms_out_pos %mli"), "OpStore %mpp %mpv"] # Clip and cull distances are copied 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 plain C array assignment, which Metal rejects # ("array type 'threadgroup float[1]' is not assignable"; SHADER-155). Same result on Vulkan. if gen.uses_clip: for i in range(gen.clip_count): L += [f"%mcs{i} = OpAccessChain %_ptr_Function_float %ms_clip {c(i)}", f"%mcv{i} = OpLoad %float %mcs{i}", f"%mcvp{i} = OpAccessChain %_ptr_Out_float_ms %ms_out_vtx %mli {c(ms_clip_member)} {c(i)}", f"OpStore %mcvp{i} %mcv{i}"] if gen.uses_cull: for i in range(gen.cull_count): L += [f"%mks{i} = OpAccessChain %_ptr_Function_float %ms_cull_dist {c(i)}", f"%mkv{i} = OpLoad %float %mks{i}", f"%mkvp{i} = OpAccessChain %_ptr_Out_float_ms %ms_out_vtx %mli {c(ms_cull_member)} {c(i)}", f"OpStore %mkvp{i} %mkv{i}"] for n in sorted(gen.ms_params): L += [f"%mq{n} = OpLoad %v4float %ms_param{n}", f"%mqp{n} = OpAccessChain %_ptr_Out_v4_ms %ms_out_param{n} %mli", f"OpStore %mqp{n} %mq{n}"] if n in ms_halves: # --f16-interp-fallback: each channel's f16 halves decoded to f32 for k in range(4): L += [f"%mqe{n}_{k} = OpCompositeExtract %float %mq{n} {k}", f"%mqu{n}_{k} = OpBitcast %uint %mqe{n}_{k}", f"%mqh{n}_{k} = OpExtInst %v2float %glsl UnpackHalf2x16 %mqu{n}_{k}"] L += [f"%mqh{n}_{k}_{h} = OpCompositeExtract %float %mqh{n}_{k} {h}" for h in (0, 1)] for h in (0, 1): L += [f"%mqv{n}_{h} = OpCompositeConstruct %v4float " + " ".join(f"%mqh{n}_{k}_{h}" for k in range(4)), f"%mqvp{n}_{h} = OpAccessChain %_ptr_Out_v4_ms %ms_out_f16h{n}_{h} %mli", f"OpStore %mqvp{n}_{h} %mqv{n}_{h}"] L += ["OpBranch %ms_vend", "%ms_vend = OpLabel", "%mhp = OpLoad %bool %ms_has_prim", "%mpi = OpULessThan %bool %mli %msp", "OpSelectionMerge %ms_pend None", "OpBranchConditional %mpi %ms_pin %ms_pend", "%ms_pin = OpLabel", "%mixp = OpAccessChain %_ptr_Out_v3u_ms %ms_prim_idx %mli", f"%mcp = OpAccessChain %_ptr_Out_bool_ms %ms_cull %mli {c(0)}", "OpSelectionMerge %ms_pjoin None", "OpBranchConditional %mhp %ms_pdo %ms_pnull", "%ms_pdo = OpLabel", "%mpr = OpLoad %uint %ms_prim", *ms_prim_indices(c), "%mix = OpCompositeConstruct %v3uint %mi0 %mi1 %mi2", "OpStore %mixp %mix", # CullPrimitiveEXT gets a constant on each side of a branch, not the computed bool: llvmpipe # (Mesa 25.2.8, LLVM 20) aborts compiling a computed per-primitive bool store in the wave64-emulated # mesh epilogue ("Cannot emit physreg copy instruction"), and Mesa 26.3.1 drew no primitives for the # same shaders (SHADER-575). Same result on every driver. "OpSelectionMerge %ms_cend None", "OpBranchConditional %mnull %ms_cull1 %ms_cull0", "%ms_cull1 = OpLabel", "OpStore %mcp %true", "OpBranch %ms_cend", "%ms_cull0 = OpLabel", "OpStore %mcp %false", "OpBranch %ms_cend", "%ms_cend = OpLabel"] for member, var, tag in ((1, "%ms_layer", "ly"), (1 + gen.uses_layer, "%ms_viewport", "vp")): if (var == "%ms_layer" and gen.uses_layer) or (var == "%ms_viewport" and gen.uses_viewport): L += [f"%m{tag}v = OpLoad %int {var}", f"%m{tag}p = OpAccessChain %_ptr_Out_int_ms %ms_cull %mli {c(member)}", f"OpStore %m{tag}p %m{tag}v"] L += ["OpBranch %ms_pjoin", "%ms_pnull = OpLabel", f"%mnull_ix = OpCompositeConstruct %v3uint {c(0)} {c(0)} {c(0)}", "OpStore %mixp %mnull_ix", "OpStore %mcp %true", "OpBranch %ms_pjoin", "%ms_pjoin = OpLabel", "OpBranch %ms_pend", "%ms_pend = OpLabel"] if gen.ms_serial: L = ms_serial_epilogue(gen, L, serial_exports) end_lock = "".join((" " + l if " = OpLabel" not in l else l) + "\n" for l in L) + end_lock if gen.uses_active and gen.stage == "ps": # A pixel is written when its lane was on in EXEC at the last `vm` export the path ran (if it ran one) and # at the last export to its color target (measured on RDNA2 with one target; docs/design.md, EXEC). With # several targets the pixel stays when any of them got an export from the lane: Vulkan can't skip one # attachment per pixel, so the others keep what the lane exported before (or the initial value). Without a # latch EXEC can't have changed since those exports, so EXEC at the end is the same mask; a path with no # export at all also goes by EXEC at the end. keep, latched = "%act_end", "" if gen.vm_latch: keep = "%vm_keep" latched = (" %vm_was_set = OpLoad %bool %vm_set\n" " %vm_exec = OpLoad %bool %vm_mask\n" " %vm_part = OpSelect %bool %vm_was_set %vm_exec %true\n" " %no_col = OpSelect %bool %vm_was_set %true %act_end\n") any_set, any_on = "%false", "%false" for t in gen.col_latched: latched += (f" %col_was_set_{t} = OpLoad %bool %col_set_{t}\n" f" %col_exec_{t} = OpLoad %bool %col_mask_{t}\n" f" %col_on_{t} = OpLogicalAnd %bool %col_was_set_{t} %col_exec_{t}\n" f" %col_any_set_{t} = OpLogicalOr %bool {any_set} %col_was_set_{t}\n" f" %col_any_on_{t} = OpLogicalOr %bool {any_on} %col_on_{t}\n") any_set, any_on = f"%col_any_set_{t}", f"%col_any_on_{t}" latched += (f" %col_part = OpSelect %bool {any_set} {any_on} %no_col\n" " %vm_keep = OpLogicalAnd %bool %vm_part %col_part\n") tail = end_lock + (" %act_end = OpLoad %bool %active\n" + latched + " OpSelectionMerge %live None\n" f" OpBranchConditional {keep} %live %dead\n" "%dead = OpLabel\n OpKill\n" "%live = OpLabel\n OpReturn\n OpFunctionEnd\n") else: tail = end_lock + " OpReturn\n OpFunctionEnd\n" if serial_close: gen.body = list(gen.body) + [(" " + l if " = OpLabel" not in l else l) for l in serial_close] if gen.uses_vmm and gen.coherent_images: # VulkanMemoryModel bans the Coherent decoration; use per-op MakeTexelVisible/Available|NonPrivateTexel. c1 = gen.cu(1) def _vmm_texel(line): s = line.strip() if " = OpImageRead " in s and len(s.split()) == 6: return line + f" MakeTexelVisible|NonPrivateTexel {c1}" if s.startswith("OpImageWrite ") and len(s.split()) == 4: return line + f" MakeTexelAvailable|NonPrivateTexel {c1}" return line out = [_vmm_texel(l) for l in out] gen.body = [_vmm_texel(l) for l in gen.body] if bar_psb_coh: # Under VulkanMemoryModel, plain PSB OpLoad/OpStore without NonPrivatePointer are invocation-private # and are not ordered by OpControlBarrier 0x6948 (RADV/ACO omits GL0 invalidation / glc). psb_ptr_types = { s.split()[0] for l in out if " = OpTypePointer PhysicalStorageBuffer " in (s := l.strip()) } psb_ptrs = set() for seq in (out, gen.body): for l in seq: s = l.strip() if " = Op" in s: parts = s.split() if len(parts) >= 4 and parts[1] == "=" and parts[3] in psb_ptr_types: psb_ptrs.add(parts[0]) out = [_add_non_private_psb(l, psb_ptrs) for l in out] gen.body = [_add_non_private_psb(l, psb_ptrs) for l in gen.body] if bar_img_coh: # Plain storage OpImageRead/OpImageWrite across s_barrier need NonPrivateTexel so # OpControlBarrier 0x6948 (MakeAvailable|MakeVisible|ImageMemory) orders texel writes/reads. out = [_add_non_private_texel(l) for l in out] gen.body = [_add_non_private_texel(l) for l in gen.body] if gen.uses_vmm and 0x948 in gen.consts and 2 in gen.consts: # Under VulkanMemoryModel, OpControlBarrier needs MakeAvailable|MakeVisible (0x6000) to order # UniformMemory/ImageMemory writes across invocations in the workgroup. old_bar = f"OpControlBarrier {gen.consts[2]} {gen.consts[2]} {gen.consts[0x948]}" if any(old_bar in l for l in out) or any(old_bar in l for l in gen.body): new_bar = f"OpControlBarrier {gen.consts[2]} {gen.consts[2]} {gen.cu(0x6948)}" out = [l.replace(old_bar, new_bar) for l in out] gen.body = [l.replace(old_bar, new_bar) for l in gen.body] insert_late_constants(gen, out, written) text = "\n".join(" " + l if not l.startswith("%") or " = " not in l else l for l in out) + \ "\n" + "\n".join(gen.body) + "\n" + tail if ADDR_PAIR: text = lower_addr64(text) assembled = dedupe_types(text) if gen.scalar_load_ro is None: assembled = scalar_loads_read_only(assembled) return split_big_switch(no_contraction(assembled)) _PSB_POINTER_TYPE = re.compile(r"(?m)^\s*(%[\w.]+) = OpTypePointer PhysicalStorageBuffer ") _RESULT_OF_TYPE = re.compile(r"(?m)^\s*(%[\w.]+) = Op\w+ (%[\w.]+)") _MEMORY_WRITE = re.compile(r"(?m)^\s*(?:(?:%[\w.]+ = )?(OpStore|OpAtomic\w+|OpCopyMemory\w*)\b(.*)|.*\b(OpImageWrite|" r"OpImageTexelPointer)\b.*)$") def scalar_loads_read_only(text): """Keep scalar_load's NonWritable loads (%sl_blk1 / %sl_blk2 / %sl_blk4) only in a module that writes no memory. NonWritable lets the driver read them as SMEM (RADV: one s_load_b512 for an s_buffer_load_dwordx16), but also lets it order them freely against the module's own stores, and an s_load / s_buffer_load sees what the same program stored before it (docs/design.md, Scalar/buffer memory; tools/valu_fuzz.py --family mem stores and then loads it back, and RADV read the old words in 18 of 600 programs with the decoration). A module with no store, atomic or image write to any memory can't reach that: nothing this dispatch runs writes what it reads.""" if "OpMemberDecorate %sl_blk" not in text: return text ptr_types = set(_PSB_POINTER_TYPE.findall(text)) pointers = {r for r, t in _RESULT_OF_TYPE.findall(text) if t in ptr_types} for m in _MEMORY_WRITE.finditer(text): if m.group(3): break # an image write or texel pointer: treat as a write op, rest = m.group(1), m.group(2).split() target = rest[0] if op in ("OpStore", "OpAtomicStore") or op.startswith("OpCopyMemory") else ( rest[1] if len(rest) > 1 else None) # OpAtomicX %type %pointer ... if target in pointers or op.startswith("OpCopyMemory"): break else: return text return re.sub(r"(?m)^\s*OpMemberDecorate %sl_blk[124] 0 NonWritable\n", "", text) # ---- 64-bit addresses without Int64 ---- # Every PhysicalStorageBuffer address the generator builds is one idiom: widen a 32-bit word (OpUConvert), shift a # high word left by 32, OR, add or subtract (64-bit constants included), AND a mask, take a word back (narrow to # 32 bits, or shift right by 32), sign-extend a dword (the signed offset of a global_* access) and shift it right # arithmetically by 32, shift by 1..31 either way (host_addr's 48-bit sign extension: left and then arithmetically # right by 16), compare two such values (the NUM_RECORDS bound), convert to a pointer. A shader # whose only 64-bit integers are that idiom doesn't need the Int64 capability (Vulkan shaderInt64, which Intel's # drivers lack, #313): lower_addr64 rewrites it to (low, high) pairs of 32-bit words, OpIAddCarry / OpISubBorrow # carrying into the high word, compares high word first, and bitcasts the pair (a uvec2) to the pointer, as # GL_EXT_buffer_reference_uvec2 does. A 64-bit multiply (the swizzled buffer offset's index * stride) and a left # shift by a 32-bit value (its element-size log) are lowered too. A shader with any other 64-bit integer use (a right # shift by a variable amount, a 64-bit OpPhi or variable) is left exactly as it was and keeps Int64. # --int64-addresses turns the lowering off. _A64_PRODUCERS = ("OpUConvert", "OpShiftLeftLogical", "OpShiftRightLogical", "OpBitwiseOr", "OpBitwiseAnd", "OpIAdd", "OpISub", "OpSConvert", "OpBitcast", "OpShiftRightArithmetic", "OpIMul") # 64-bit compares of two addresses: high words first, then the low words. _A64_CMP = {"OpULessThan": ("OpULessThan", False), "OpULessThanEqual": ("OpULessThanEqual", False), "OpUGreaterThan": ("OpULessThan", True), "OpUGreaterThanEqual": ("OpULessThanEqual", True), "OpIEqual": None, "OpINotEqual": None} _A64_ID = re.compile(r"%[\w.]+") def lower_addr64(text): lines = text.split("\n") t64, c64, c32, prod, conv, cmp, narrow, rtype = set(), {}, {}, {}, {}, {}, {}, {} for line in lines: w = line.split() if len(w) < 3 or w[1] != "=": continue res, op, args = w[0], w[2], w[3:] if args: rtype[res] = args[0] # the result type of every typed instruction if op == "OpTypeInt" and args[:1] == ["64"]: t64.add(res) elif op == "OpConstant" and args and args[0] in t64: c64[res] = int(args[1]) & 0xFFFFFFFFFFFFFFFF elif op == "OpConstant" and args[:1] == ["%uint"] and len(args) == 2: c32[res] = int(args[1]) & 0xFFFFFFFF # a shift amount may be a 32-bit constant elif op in _A64_PRODUCERS and args and args[0] in t64: prod[res] = (op, args[1:]) elif op == "OpUConvert" and args[:1] == ["%uint"] and len(args) == 2: narrow[res] = args[1] # a 64-bit value's low word (kept only if it is one) elif op == "OpConvertUToPtr": conv[res] = args elif op in _A64_CMP and args[:1] == ["%bool"] and len(args) == 3: cmp[res] = (op, args[1:]) if not t64: return text v64 = set(c64) | set(prod) # a shift's amount: a 64-bit or 32-bit constant of 1..32 (the 48-bit sign extension of host_addr shifts by 16), or # for a left shift any 32-bit value (the swizzled buffer offset shifts by the element size's log, a V# field) shift = {r: v for r, v in {**c32, **c64}.items() if 1 <= v <= 32} narrow = {r: v for r, v in narrow.items() if v in v64} for res, (op, a) in list(cmp.items()): # a compare of two 64-bit values; any other compare is left alone if a[0] not in v64 and a[1] not in v64: del cmp[res] elif a[0] not in v64 or a[1] not in v64: return text for res, (op, a) in prod.items(): # the idiom, exactly ok = (op in ("OpUConvert", "OpSConvert") and len(a) == 1 and a[0] not in v64 and rtype.get(a[0]) in ("%uint", "%int")) or \ (op == "OpBitcast" and len(a) == 1 and a[0] in v64) or \ (op in ("OpShiftLeftLogical", "OpShiftRightLogical", "OpShiftRightArithmetic") and len(a) == 2 and a[0] in v64 and a[1] in shift) or \ (op == "OpShiftLeftLogical" and len(a) == 2 and a[0] in v64 and a[1] not in v64 and rtype.get(a[1]) == "%uint") or \ (op in ("OpBitwiseOr", "OpBitwiseAnd", "OpIAdd", "OpISub", "OpIMul") and len(a) == 2 and a[0] in v64 and a[1] in v64) if not ok: return text for line in lines: # any other mention of a 64-bit type or value: keep Int64 w = line.split() res = w[0] if len(w) >= 3 and w[1] == "=" else None if res in t64 or res in c64 or res in prod or res in conv or res in cmp or res in narrow: continue if any(tok in t64 or tok in v64 for tok in _A64_ID.findall(line)): return text uc, pair, out, n = {}, {}, [], 0 def const(v): if v not in uc: uc[v] = f"%a64c_{v:x}" return uc[v] for cid, v in c64.items(): pair[cid] = (const(v & 0xFFFFFFFF), const(v >> 32)) for line in lines: w = line.split() res = w[0] if len(w) >= 3 and w[1] == "=" else None if res in t64 or res in c64 or line.strip() == "OpCapability Int64": continue if res in prod: op, a = prod[res] if op == "OpUConvert": pair[res] = (a[0], const(0)) elif op == "OpBitcast": # between the 64-bit integer types: the same words pair[res] = pair[a[0]] elif op == "OpShiftLeftLogical" and a[1] not in shift: # A left shift by a 32-bit value k (0..63 matter; SPIR-V leaves a shift by 32 or more undefined, so # each word's shift stays under 32): k & 31 on both words with the bits that cross, then the words # move up one if k >= 32. n += 1 (xl, xh), k, p = pair[a[0]], a[1], f"%a64_{n}" out += [f" {p}k = OpBitwiseAnd %uint {k} {const(31)}", f" {p}r = OpISub %uint {const(31)} {p}k", f" {p}l = OpShiftLeftLogical %uint {xl} {p}k", f" {p}a = OpShiftLeftLogical %uint {xh} {p}k", f" {p}b = OpShiftRightLogical %uint {xl} {p}r", # lo >> (31 - k) >> 1: 0 when k = 0 f" {p}c = OpShiftRightLogical %uint {p}b {const(1)}", f" {p}h = OpBitwiseOr %uint {p}a {p}c", f" {p}g = OpUGreaterThanEqual %bool {k} {const(32)}", f" {p}L = OpSelect %uint {p}g {const(0)} {p}l", f" {p}H = OpSelect %uint {p}g {p}l {p}h"] pair[res] = (p + "L", p + "H") elif op == "OpIMul": # The low 64 bits of the product: the low words' full product (its high word from the four 16-bit # half products, with plain 32-bit multiplies, so the test interpreters can run it too), plus each # low word times the other's high word into the high word (the rest lies above 64 bits). n += 1 (xl, xh), (yl, yh), p = pair[a[0]], pair[a[1]], f"%a64_{n}" h16, c16 = const(0xFFFF), const(16) out += [f" {p}l = OpIMul %uint {xl} {yl}", f" {p}x0 = OpBitwiseAnd %uint {xl} {h16}", f" {p}x1 = OpShiftRightLogical %uint {xl} {c16}", f" {p}y0 = OpBitwiseAnd %uint {yl} {h16}", f" {p}y1 = OpShiftRightLogical %uint {yl} {c16}", f" {p}p00 = OpIMul %uint {p}x0 {p}y0", f" {p}p01 = OpIMul %uint {p}x0 {p}y1", f" {p}p10 = OpIMul %uint {p}x1 {p}y0", f" {p}p11 = OpIMul %uint {p}x1 {p}y1", f" {p}m0 = OpShiftRightLogical %uint {p}p00 {c16}", f" {p}m1 = OpBitwiseAnd %uint {p}p01 {h16}", f" {p}m2 = OpBitwiseAnd %uint {p}p10 {h16}", f" {p}m3 = OpIAdd %uint {p}m0 {p}m1", f" {p}m = OpIAdd %uint {p}m3 {p}m2", f" {p}c0 = OpShiftRightLogical %uint {p}p01 {c16}", f" {p}c1 = OpShiftRightLogical %uint {p}p10 {c16}", f" {p}c2 = OpShiftRightLogical %uint {p}m {c16}", f" {p}c3 = OpIAdd %uint {p}p11 {p}c0", f" {p}c4 = OpIAdd %uint {p}c3 {p}c1", f" {p}c = OpIAdd %uint {p}c4 {p}c2", f" {p}a = OpIMul %uint {xl} {yh}", f" {p}b = OpIMul %uint {xh} {yl}", f" {p}d = OpIAdd %uint {p}c {p}a", f" {p}h = OpIAdd %uint {p}d {p}b"] pair[res] = (p + "l", p + "h") elif op == "OpShiftLeftLogical" and shift[a[1]] == 32: pair[res] = (const(0), pair[a[0]][0]) elif op == "OpShiftRightLogical" and shift[a[1]] == 32: pair[res] = (pair[a[0]][1], const(0)) elif op == "OpSConvert" or (op == "OpShiftRightArithmetic" and shift[a[1]] == 32): # A sign-extended dword (a 32-bit value widened, or the arithmetic shift by 32, which keeps the high # word and sign-extends it): the high word is the sign, the value shifted right arithmetically by 31. n += 1 p = f"%a64_{n}" if op == "OpSConvert": low = a[0] if rtype.get(low) == "%int": out.append(f" {p}l = OpBitcast %uint {low}") low, signed = p + "l", a[0] else: out.append(f" {p}i = OpBitcast %int {low}") signed = p + "i" else: low = pair[a[0]][1] out.append(f" {p}i = OpBitcast %int {low}") signed = p + "i" out += [f" {p}s = OpShiftRightArithmetic %int {signed} {const(31)}", f" {p}h = OpBitcast %uint {p}s"] pair[res] = (low, p + "h") elif op in ("OpShiftLeftLogical", "OpShiftRightLogical", "OpShiftRightArithmetic"): # A shift by k of 1..31: each word takes the bits the other word shifts across (32 - k of them). n += 1 (xl, xh), k, p = pair[a[0]], shift[a[1]], f"%a64_{n}" if op == "OpShiftLeftLogical": out += [f" {p}l = OpShiftLeftLogical %uint {xl} {const(k)}", f" {p}a = OpShiftLeftLogical %uint {xh} {const(k)}", f" {p}b = OpShiftRightLogical %uint {xl} {const(32 - k)}", f" {p}h = OpBitwiseOr %uint {p}a {p}b"] else: out += [f" {p}a = OpShiftRightLogical %uint {xl} {const(k)}", f" {p}b = OpShiftLeftLogical %uint {xh} {const(32 - k)}", f" {p}l = OpBitwiseOr %uint {p}a {p}b"] if op == "OpShiftRightLogical": out.append(f" {p}h = OpShiftRightLogical %uint {xh} {const(k)}") else: out += [f" {p}i = OpBitcast %int {xh}", f" {p}s = OpShiftRightArithmetic %int {p}i {const(k)}", f" {p}h = OpBitcast %uint {p}s"] pair[res] = (p + "l", p + "h") else: n += 1 (xl, xh), (yl, yh), p = pair[a[0]], pair[a[1]], f"%a64_{n}" if op in ("OpBitwiseOr", "OpBitwiseAnd"): out += [f" {p}l = {op} %uint {xl} {yl}", f" {p}h = {op} %uint {xh} {yh}"] else: # the low words with the carry / borrow out, then the high words with it wide, high = ("OpIAddCarry", "OpIAdd") if op == "OpIAdd" else ("OpISubBorrow", "OpISub") out += [f" {p}s = {wide} %umul {xl} {yl}", f" {p}l = OpCompositeExtract %uint {p}s 0", f" {p}c = OpCompositeExtract %uint {p}s 1", f" {p}g = {high} %uint {xh} {yh}", f" {p}h = {high} %uint {p}g {p}c"] pair[res] = (p + "l", p + "h") continue if res in narrow: out.append(f" {res} = OpCopyObject %uint {pair[narrow[res]][0]}") continue if res in cmp: n += 1 op, a = cmp[res] (xl, xh), (yl, yh), p = pair[a[0]], pair[a[1]], f"%a64_{n}" if _A64_CMP[op] is None: out += [f" {p}h = OpIEqual %bool {xh} {yh}", f" {p}l = OpIEqual %bool {xl} {yl}", f" {p}e = OpLogicalAnd %bool {p}h {p}l"] out.append(f" {res} = OpLogicalNot %bool {p}e" if op == "OpINotEqual" else f" {res} = OpCopyObject %bool {p}e") else: lo_op, swap = _A64_CMP[op] if swap: (xl, xh), (yl, yh) = (yl, yh), (xl, xh) out += [f" {p}h = OpULessThan %bool {xh} {yh}", f" {p}e = OpIEqual %bool {xh} {yh}", f" {p}l = {lo_op} %bool {xl} {yl}", f" {p}a = OpLogicalAnd %bool {p}e {p}l", f" {res} = OpLogicalOr %bool {p}h {p}a"] continue if res in conv and conv[res][1] in pair: n += 1 (xl, xh), p = pair[conv[res][1]], f"%a64_{n}" out += [f" {p}v = OpCompositeConstruct %v2uint_a {xl} {xh}", f" {res} = OpBitcast {conv[res][0]} {p}v"] continue out.append(line) # The pair type and the 32-bit constants the rewrite used, declared right after %uint (constants are made as the # body is rewritten, so they go in once it is done). at = next(i for i, l in enumerate(out) if l.strip() == "%uint = OpTypeInt 32 0") + 1 out[at:at] = ["%v2uint_a = OpTypeVector %uint 2"] + \ [f"{name} = OpConstant %uint {v}" for v, name in sorted(uc.items())] return "\n".join(out) # SPIR-V caps an instruction at 65,535 words. The dispatch loop's OpSwitch has one (literal, label) pair per block, # and with --wave64-emulate the two ScreenProbes compute shaders reach ~37k blocks (74k words). Past the limit the # switch becomes two levels: an outer one on pc / SWITCH_CHUNK picks a chunk; each chunk is its own selection # construct (inner OpSwitch on pc, merge %swm), and that chunk's blocks branch to %swm, which goes on to # %sw_merge. Every block keeps its label and code, so only the routing changes. SWITCH_CHUNK = 16000 # spirv-val also caps a switch at 16,383 (literal, label) pairs _BIG_SWITCH = re.compile(r"^(\s*)OpSwitch %pcv %sw_default ((?:\d+ %\w+ ?)+)$", re.M) def split_big_switch(text): m = _BIG_SWITCH.search(text) if not m: return text pairs = m.group(2).split() cases = [(int(pairs[i]), pairs[i + 1]) for i in range(0, len(pairs), 2)] if len(cases) <= 16383 and 3 + 2 * len(cases) <= 65535: return text ind = m.group(1) chunk_of = {lbl: v // SWITCH_CHUNK for v, lbl in cases} chunks = sorted(set(chunk_of.values())) outer = f"{ind}OpSwitch %pcc %sw_default " + " ".join(f"{k} %swc{k}" for k in chunks) heads = [] for k in chunks: inner = " ".join(f"{v} {lbl}" for v, lbl in cases if chunk_of[lbl] == k) heads += [f"%swc{k} = OpLabel", f"{ind}OpSelectionMerge %swm{k} None", f"{ind}OpSwitch %pcv %swm{k} {inner}"] # OpSelectionMerge must stay right before its switch, so the chunk index is computed above it pre = text[:m.start()] sel = pre.rfind("OpSelectionMerge %sw_merge None") sel = pre.rfind("\n", 0, sel) + 1 pre = pre[:sel] + f"{ind}%pcc = OpUDiv %uint %pcv %c_swchunk\n" + pre[sel:] lines = pre.split("\n") + [outer] + heads + text[m.end():].split("\n")[1:] # route each block's exits to its chunk's merge: a block runs from its label to the next case label out, cur = [], None for line in lines: st = line.strip() if st.endswith("= OpLabel"): lbl = st.split(" = ")[0] if lbl in chunk_of: cur = chunk_of[lbl] elif lbl in ("%sw_default", "%sw_merge") or lbl.startswith("%swc"): cur = None if lbl_is_sw_default(st): out += [f"%swm{k} = OpLabel\n{ind}OpBranch %sw_merge" for k in chunks] # after every chunk's blocks if cur is not None and st == "OpBranch %sw_merge": line = line.replace("OpBranch %sw_merge", f"OpBranch %swm{cur}") out.append(line) text = "\n".join(out) # the chunk-size constant, next to the other uint constants first = re.search(r"^\s*%\w+ = OpConstant %uint \d+$", text, re.M) return text[:first.start()] + f"%c_swchunk = OpConstant %uint {SWITCH_CHUNK}\n" + text[first.start():] def lbl_is_sw_default(st): return st == "%sw_default = OpLabel" _FLOAT_ARITH = re.compile(r"^\s*(%\w+) = Op(?:FMul|FAdd|FSub|FDiv|FNegate|FRem|FMod) ", re.M) def no_contraction(text): """Decorate every float arithmetic instruction NoContraction (multiply, add, subtract, divide, negate, remainder). The hardware rounds a v_mul and the v_add after it separately (its fused instructions are emitted as Fma), but a driver may fuse or otherwise rewrite an undecorated expression, and whether it does depends on how much of the code its optimiser can see at once: with real control flow instead of the dispatch loop, one shader's output moved by a 16-bit-float step in 49 of 4,096 pixels on an AMD GPU (a multiply and an add), and two more by one step in one pixel on Mesa's software driver (divide or negate).""" ids = _FLOAT_ARITH.findall(text) at = text.find("\n%void = OpTypeVoid") if not ids or at < 0: return text return text[:at] + "".join(f"\n OpDecorate {i} NoContraction" for i in ids) + text[at:] _STAGES = None def stage_of(name, path): """Shader stage from the carve index (the DXIL program header in each container), not the name. A successful index read is cached for the process lifetime; the index is assumed immutable once read. """ global _STAGES if _STAGES is None: _STAGES = {} idx = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(path))), "index.json") key = os.path.normcase(os.path.realpath(idx)) stages = _STAGES.get(key) if stages is None: import json stages = {} if os.path.isfile(idx): with open(idx, encoding="utf-8") as f: for e in json.load(f): stages[e["file"][:-5]] = e["stage"] _STAGES[key] = stages return stages.get(name) or (name[:2].lower() if name[2:3] == "_" else "?") # Wave64 markers in the instruction text. Besides EXEC/VCC forms, 64-bit lane-mask SOP1/SOP2 ops # (bcnt/ff/wqm/bfm) imply a 64-lane wave even when the mask lives in ordinary SGPR pairs (#210 part 2). WAVE64_RE = re.compile( r"exec_hi|v_mbcnt_hi_u32_b32|_saveexec_b64|_wrexec_b64|" r"s_bcnt[01]_i32_b64|s_ff[01]_i32_b64|s_wqm_b64|s_bfm_b64" ) # Wave32-only EXEC mask ops, used to catch a wave64 FSSM header contradicting wave32 code. WAVE32_RE = re.compile(r"_(?:saveexec|wrexec)_b32\b") def halves_analysis(g, blocks, succ): """SHADER-10: tier of a wave64 VS/PS/GS on 32-wide subgroups (tools/wave64_halves.py); tier C is refused under --wave64-graphics=error. Runs after the lane-mask analysis, which it reads.""" if not g.wave64 or g.stage not in ("vs", "ps", "gs") or g.emulate or WAVE64_GRAPHICS == "off": return try: g.w64g = wave64_halves.analyse(blocks, succ, g.lane_masks, g.stage) except Exception as e: # the analysis must never cost a translation; what it could not decide is tier C g.w64g = {"tier": "C", "reasons": ["analysis-error"], "idioms": [], "uniform_readlane": set(), "scalar_spills": [], "sites": [("analysis-error", None, type(e).__name__)]} for slot in g.w64g.get("scalar_spills", ()): if slot not in g.parked: g.parked[slot] = g.SGPRS + len(g.parked) g.scalar_spills.add(slot) W64G_COUNTS[g.w64g["tier"]] += 1 if g.w64g["tier"] == "C" and WAVE64_GRAPHICS == "error": raise Unsupported("wave64 graphics tier C: " + ", ".join(g.w64g["reasons"])) def fold_far_branches(insns): """s_getpc_b64 s[a:a+1]; s_add_u32 sa, sa, K; s_addc_u32 sa+1, sa+1, 0|-1; s_setpc_b64 s[a:a+1] is a far branch (s_branch only reaches +-32K dwords): the target is the address after s_getpc plus K. Fold the four instructions into one s_branch with an explicit byte target so the CFG sees an ordinary branch.""" out, i = [], 0 while i < len(insns): w = insns[i:i + 4] ops4 = [base_op(x["op"]) for x in w] if len(w) == 4 and all(x.get("enc") for x in w) and ops4 in (["s_getpc_b64", "s_add_u32", "s_addc_u32", "s_setpc_b64"], ["s_getpc_b64", "s_sub_u32", "s_subb_u32", "s_setpc_b64"]): g, ad, ac, sp = w r = g["args"][0].get("r") if g["args"] and g["args"][0]["k"] == "sgpr" else None ok = r is not None and [x.get("r") for x in ad["args"][:2]] == [r, r] and ad["args"][2]["k"] == "imm" and [x.get("r") for x in ac["args"][:2]] == [r + 1, r + 1] and ac["args"][2]["k"] == "imm" and sp["args"] and sp["args"][0].get("r") == r if ok: k = ad["args"][2]["v"] & 0xFFFFFFFF hi = ac["args"][2]["v"] & 0xFFFFFFFF if hi == 0xFFFFFFFF: k -= 1 << 32 elif hi != 0: ok = False if ops4[1] == "s_sub_u32": # backward far branch (loop back-edge) k = -k if ok: out.append({"op": "s_branch", "args": [], "mods": [], "pc": g["pc"], "enc": "".join(x["enc"] for x in w), "target": g["pc"] + 4 + k}) i += 4 continue out.append(insns[i]) i += 1 return out def unpatch_int_mrt_exports(insns, mrt_targets, mrt_types, mrt_masks): """Unpatch Xbox's default FP16 `v_cvt_pkrtz_f16_f32` + `exp mrtK ... compr` epilogue for integer SV_Targets. Xbox pixel shaders ship with a 6-dword patchable export slot per MRT carrying the FP16_ABGR default (`v_cvt_pkrtz_f16_f32` + `exp mrtK ... compr`); at PSO creation the Xbox driver overwrites integer RTV slots with FSSM template #9 (`SPI_SHADER_32_ABGR`: 4x `s_nop` + uncompressed `exp mrtK vX, vY, vZ, vW` masked by OSG1's component mask). Translating the unpatched FP16 sequence on a UINT/SINT target corrupts bit-packed 32-bit integer values via FP16 RTZ conversion and unpacks them as floats. Runs pre-CFG (after `fold_far_branches`) and replaces bypassed `pkrtz` ops in-place with `s_nop 0` keeping their `pc`/`enc` so branch targets and CFG leaders stay intact. Raises Unsupported if a compressed integer color export does not match the patchable `pkrtz` epilogue.""" def _is_off(x): return x["k"] == "special" and x["t"] == "off" def _is_vgpr(x): return x["k"] == "vgpr" and x.get("n", 1) == 1 def _pkrtz_match(ins, dst_reg): if (ins["op"] not in ("v_cvt_pkrtz_f16_f32", "v_cvt_pkrtz_f16_f32_e32", "v_cvt_pkrtz_f16_f32_e64") or ins.get("mods")): return None a = ins["args"] if len(a) != 3 or not _is_vgpr(a[0]) or a[0]["r"] != dst_reg: return None if any(s.get("abs") or s.get("neg") or s.get("sext") or "sdwa_sel" in s for s in a[1:3]): return None return a[1], a[2] off_arg = {"k": "special", "t": "off"} out = list(insns) branch_targets = set() for br in out: if base_op(br["op"]) not in BRANCHES: continue if "target" in br: branch_targets.add(br["target"]) elif "pc" in br and br.get("enc"): imm = next((x for x in br["args"] if x["k"] == "imm"), None) if imm is not None: v = imm["v"] & 0xFFFF off = v - 0x10000 if v & 0x8000 else v branch_targets.add(br["pc"] + len(br["enc"]) // 2 + 4 * off) for idx, ins in enumerate(out): if ins["op"] != "exp" or "compr" not in ins.get("mods", ()): continue a = ins["args"] tgt = a[0]["t"] if a and a[0]["k"] in ("target", "special") else None if not (tgt and tgt.startswith("mrt") and tgt != "mrtz"): continue k = int(tgt[3:]) if mrt_targets and k >= len(mrt_targets): continue rt = mrt_targets[k] if mrt_targets else k if rt not in mrt_types: continue srcs = a[1:5] if len(srcs) < 4: raise Unsupported("compressed integer color export") r0, r1 = srcs[0], srcs[2] if not _is_vgpr(r0): raise Unsupported("compressed integer color export") if not _is_off(r1): if not _is_vgpr(r1) or r0["r"] == r1["r"] or idx < 2: raise Unsupported("compressed integer color export") m0 = _pkrtz_match(out[idx - 2], r0["r"]) m1 = _pkrtz_match(out[idx - 1], r1["r"]) if m0 is None or m1 is None: raise Unsupported("compressed integer color export") if any(_is_vgpr(s) and s["r"] == r0["r"] for s in m1): raise Unsupported("compressed integer color export") raw = [m0[0], m0[1], m1[0], m1[1]] nop_idxs = (idx - 2, idx - 1) else: m0 = _pkrtz_match(out[idx - 1], r0["r"]) if idx >= 1 else None if m0 is not None: nop_idxs = (idx - 1,) elif idx >= 2 and base_op(out[idx - 1]["op"]) == "s_nop": m0 = _pkrtz_match(out[idx - 2], r0["r"]) if m0 is None: raise Unsupported("compressed integer color export") nop_idxs = (idx - 2,) else: raise Unsupported("compressed integer color export") raw = [m0[0], m0[1], off_arg, off_arg] if any(out[j].get("pc") in branch_targets for j in range(min(nop_idxs) + 1, idx + 1) if "pc" in out[j]): raise Unsupported("compressed integer color export") mask = mrt_masks.get(rt, 0xF) raw = [raw[c] if (mask >> c) & 1 else off_arg for c in range(4)] for ni in nop_idxs: old = out[ni] nop = {"op": "s_nop", "args": [{"k": "imm", "v": 0}], "mods": []} if "pc" in old: nop["pc"] = old["pc"] if "enc" in old: nop["enc"] = old["enc"] out[ni] = nop new_exp = dict(ins) new_exp["mods"] = [m for m in ins["mods"] if m != "compr"] new_exp["args"] = [a[0]] + raw out[idx] = new_exp return out def reachable_code(insns, code_end=None): """Instructions reachable from the first one, following fall-through and branch targets. Fall-through stops after s_endpgm, s_branch and s_setpc_b64. Raises Unsupported if a branch target isn't an instruction start, or if an instruction falls through into words that are not an instruction (undecodable words before later code).""" by_pc = {i["pc"]: k for k, i in enumerate(insns)} # the code ends at the declared end of its range (the listing header), or else after the last printed instruction code_end = max([i["pc"] + len(i["enc"]) // 2 for i in insns] + [code_end or 0]) seen, work = set(), [0] while work: k = work.pop() while k is not None and k < len(insns) and k not in seen: seen.add(k) ins = insns[k] op = base_op(ins["op"]) nxt = ins["pc"] + len(ins["enc"]) // 2 if op in BRANCHES: imm = next((x for x in ins["args"] if x["k"] == "imm"), None) v = (imm["v"] & 0xFFFF) if imm else 0 tgt = ins["target"] if "target" in ins else nxt + 4 * (v - 0x10000 if v & 0x8000 else v) if tgt not in by_pc: raise Unsupported("branch into data") work.append(by_pc[tgt]) if op == "s_branch": break if op in ("s_endpgm", "s_setpc_b64"): break k = by_pc.get(nxt) if k is None and nxt < code_end: # The next words are ones llvm-mc could not decode (re-anchoring skipped them) and this instruction # runs into them: ending the path here would drop every later store and export without a word. raise Unsupported("fall-through into undecodable words") return [insns[k] for k in sorted(seen)] def writes_exec(ins): """Whether an instruction can change EXEC: v_cmpx, saveexec / wrexec, or EXEC in any destination operand (operand 0 of everything but compares, plus operand 1 of VOP3b two-destination ops like v_add_co_u32, v_sub_co_u32, v_mad_u64_u32, and v_div_scale_f32 whose second operand is the scalar carry/flag destination).""" op, a = ins["op"], ins["args"] bop = base_op(op) if bop.startswith("v_cmpx") or "saveexec" in bop or "wrexec" in bop: return True if bop.startswith(("s_cmp_", "s_cmpk_", "s_bitcmp")): return False if a and a[0]["k"] == "special" and a[0]["t"].startswith("exec"): return True if bop in VOP3_TWO_DESTS and len(a) > 1 and a[1]["k"] == "special" and a[1]["t"].startswith("exec"): return True return False def is_color_export(ins): """An `exp` to a color target (mrt0-mrt7; not mrtz, null or a position / parameter).""" a = ins["args"] t = a[0].get("t", "") if a and a[0]["k"] in ("target", "special") else "" return base_op(ins["op"]) == "exp" and t.startswith("mrt") and t[3:].isdigit() def exec_changes_after_vm(blocks, succ): """Whether some path writes EXEC after an `exp ... vm` or after a color export. Only then does a PS need EXEC at those exports kept: a pixel is written when its lane was on at the last `vm` export and at the last color export, and with EXEC unchanged since then that is EXEC at the end.""" after = [] for n, blk in enumerate(blocks): seen_vm = False for ins in blk: op = base_op(ins["op"]) if op == "s_endpgm" or op in BRANCHES: break if seen_vm and writes_exec(ins): return True if op == "exp" and ("vm" in ins["mods"] or is_color_export(ins)): seen_vm = True if seen_vm: after += succ[n] reached = set() while after: n = after.pop() if n in reached or not 0 <= n < len(blocks): continue reached.add(n) for ins in blocks[n]: op = base_op(ins["op"]) if op == "s_endpgm" or op in BRANCHES: break if writes_exec(ins): return True after += succ[n] return False def vgpr_dest_registers(ins: dict, extra: int = 0) -> range | tuple[int, ...]: """Register numbers written by a VGPR-destination instruction, after filtering stores and compares.""" args = ins["args"] if base_op(ins["op"]) == "v_swap_b32": return tuple(a["r"] for a in args[:2] if a["k"] == "vgpr") dst = args[0] return range(dst["r"], dst["r"] + dst.get("n", 1) + extra) def sdwa_reads_dst(op: str, mods: list[str]) -> bool: """A byte or word insert with UNUSED_PRESERVE reads the rest of its destination.""" return (op.endswith("_sdwa") and "dst_unused:UNUSED_PRESERVE" in mods and any(m.startswith(("dst_sel:BYTE_", "dst_sel:WORD_")) for m in mods)) # Ops whose VGPR destination is also a source operand (the accumulating forms, and v_swap_b32, which reads both). DST_ALSO_READ = ("v_swap_b32", "v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8", "v_pk_fmac_f16", "v_dot2c_f32_f16", "v_dot2c_i32_i16", "v_dot2c_u32_u16", "v_dot4c_u32_u8", "v_dot8c_i32_i4", "v_dot8c_u32_u4") # All VGPR operands of these instructions are sources, including store address and data ranges. VGPR_READ_ONLY_PREFIXES = ("exp", "buffer_store", "tbuffer_store", "image_store", "v_cmp", "ds_write", "global_store", "flat_store", "scratch_store") _FLOAT_ONLY_IMAGE_OPS = frozenset({"image_load", "image_load_mip", "image_sample", "image_sample_l", "image_sample_lz"}) # VALU ops whose VGPR source operands are strictly IEEE binary32 float (never raw integer/bitfield ops). _F32_ONLY_CONSUMERS = frozenset({ "v_add_f32", "v_sub_f32", "v_subrev_f32", "v_mul_f32", "v_mul_legacy_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f32", "v_fma_f32", "v_fma_legacy_f32", "v_fmaak_f32", "v_fmamk_f32", "v_mad_f32", "v_mad_legacy_f32", "v_madak_f32", "v_madmk_f32", "v_min_f32", "v_max_f32", "v_min3_f32", "v_max3_f32", "v_med3_f32", "v_rcp_f32", "v_rcp_iflag_f32", "v_rsq_f32", "v_sqrt_f32", "v_log_f32", "v_exp_f32", "v_sin_f32", "v_cos_f32", "v_floor_f32", "v_ceil_f32", "v_trunc_f32", "v_rndne_f32", "v_fract_f32", "v_cvt_f16_f32", "v_cvt_pkrtz_f16_f32", "v_cvt_pknorm_i16_f32", "v_cvt_pknorm_u16_f32", "v_cvt_u32_f32", "v_cvt_i32_f32", "v_cvt_f64_f32", "v_cvt_rpi_i32_f32", "v_cvt_flr_i32_f32", "v_frexp_mant_f32", "v_frexp_exp_i32_f32", "v_cubema_f32", "v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", "v_div_fixup_f32", "v_div_fmas_f32", "v_div_scale_f32", }) # VALU ops whose VGPR source operands are strictly IEEE binary16 float (packed or scalar f16). _F16_ONLY_CONSUMERS = frozenset({ "v_add_f16", "v_sub_f16", "v_subrev_f16", "v_mul_f16", "v_fma_f16", "v_fmac_f16", "v_fmaak_f16", "v_fmamk_f16", "v_min_f16", "v_max_f16", "v_min3_f16", "v_max3_f16", "v_med3_f16", "v_rcp_f16", "v_rsq_f16", "v_sqrt_f16", "v_log_f16", "v_exp_f16", "v_sin_f16", "v_cos_f16", "v_floor_f16", "v_ceil_f16", "v_trunc_f16", "v_rndne_f16", "v_fract_f16", "v_pk_add_f16", "v_pk_mul_f16", "v_pk_fma_f16", "v_pk_fmac_f16", "v_pk_min_f16", "v_pk_max_f16", "v_cvt_f32_f16", "v_cvt_u16_f16", "v_cvt_i16_f16", "v_cvt_norm_i16_f16", "v_cvt_norm_u16_f16", "v_cvt_pknorm_i16_f16", "v_cvt_pknorm_u16_f16", "v_div_fixup_f16", "v_frexp_mant_f16", "v_frexp_exp_i16_f16", }) def _arg_vgprs(arg): """Set of VGPR indices named by a single parsed operand.""" if arg["k"] == "vgpr": return set(range(arg["r"], arg["r"] + arg.get("n", 1))) if arg["k"] == "vlist": return set(arg["r"]) return set() def _is_ds_dst_only(bop): """Whether a DS op has a pure VGPR destination in a[0] (does not read a[0] as an address/data source).""" return (bop.startswith(("ds_read", "ds_swizzle", "ds_permute", "ds_bpermute", "ds_append", "ds_consume")) or "_rtn" in bop) def _permlane_preserves_dst(bop, mods): """Whether v_permlane16_b32 / v_permlanex16_b32 may preserve vdst (FI=0 and BOUND_CTRL=0).""" if bop not in ("v_permlane16_b32", "v_permlanex16_b32"): return False if "fi:1" in mods or "bound_ctrl:1" in mods: return False sel = next((m for m in mods if m.startswith("op_sel:")), None) if sel is not None: try: bits = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] except (IndexError, ValueError): return True if (len(bits) >= 1 and bits[0]) or (len(bits) >= 2 and bits[1]): return False return True def _vgpr_reads_of(ins): """Set of VGPR indices read by instruction `ins` (matches read_before_write_vgprs + atomics/DS).""" a, op = ins["args"], ins["op"] if not a: return set() bop = base_op(op) mods = ins.get("mods", ()) reads_all = (op.startswith(VGPR_READ_ONLY_PREFIXES) or bop.startswith(("buffer_atomic_", "image_atomic_", "flat_atomic_", "global_atomic_")) or (bop.startswith(("buffer_load", "tbuffer_load")) and "lds" in mods) or (bop.startswith("ds_") and not _is_ds_dst_only(bop))) regs = set() for x in (a if reads_all or sdwa_reads_dst(op, mods) else a[1:]): if x["k"] == "vgpr": regs.update(range(x["r"], x["r"] + x.get("n", 1))) elif x["k"] == "vlist": regs.update(x["r"]) if (bop in DST_ALSO_READ or _permlane_preserves_dst(bop, mods) or (op.startswith(("global_load_", "buffer_load_")) and "_d16" in op and "format" not in op) or op == "buffer_load_format_d16_hi_x") and \ a[0]["k"] == "vgpr": regs.add(a[0]["r"]) return regs def _vgpr_full_writes_of(ins): """Set of VGPR indices unconditionally and completely overwritten by `ins` (conservative).""" a, op = ins["args"], ins["op"] if not a or op.endswith(("_sdwa", "_dpp")): return set() bop = base_op(op) mods = ins.get("mods", ()) if bop == "v_writelane_b32" or _permlane_preserves_dst(bop, mods): return set() if bop.startswith(("buffer_atomic_", "image_atomic_", "flat_atomic_", "global_atomic_")): return set() if bop.startswith(("buffer_load", "tbuffer_load")) and "lds" in mods: return set() if bop.startswith("ds_") and not _is_ds_dst_only(bop): return set() reads_all = op.startswith(VGPR_READ_ONLY_PREFIXES) if reads_all or a[0]["k"] != "vgpr": return set() if "_d16" in op or "d16" in mods: return set() if bop.startswith("image_"): dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1") try: ncomp = bin(int(dm.split(":")[1], 0)).count("1") except ValueError: return set() if ncomp <= 0: return set() return set(range(a[0]["r"], a[0]["r"] + min(ncomp, a[0].get("n", 1)))) # Scalar 16-bit VALU ops preserve the unwritten 16-bit half of a[0], so never kill the full 32-bit VGPR. if (any(s in bop for s in ("_f16", "_u16", "_i16", "_b16")) and not bop.startswith(("v_pk_", "v_cvt_pk", "v_cvt_f32_", "v_cvt_u32_", "v_cvt_i32_", "v_pack_b32_", "v_dot2", "v_dot4", "v_dot8"))): return set() return set(vgpr_dest_registers(ins)) def _exec_monotone_widen(ins): """Whether a writes_exec instruction only turns ON lanes (EXEC_new >= EXEC_old).""" bop = base_op(ins["op"]) a = ins["args"] if bop in ("s_or_saveexec_b32", "s_or_saveexec_b64"): return True if bop in ("s_or_b32", "s_or_b64") and len(a) >= 3 and a[0]["k"] == "special": dst_t = a[0].get("t", "") if dst_t in ("exec", "exec_lo", "exec_hi"): return any(x["k"] == "special" and x.get("t") == dst_t for x in a[1:3]) if bop in ("s_wqm_b32", "s_wqm_b64") and len(a) >= 2 and a[0]["k"] == "special" and a[1]["k"] == "special": dst_t = a[0].get("t", "") if dst_t in ("exec", "exec_lo", "exec_hi") and a[1].get("t") == dst_t: return True return False def _is_float_consumer_of(ins, regs, d16): """Whether `ins` strictly interprets every VGPR in `regs` it reads as floating-point (f16 if d16, else f32).""" raw_op = ins["op"] if raw_op.endswith("_sdwa"): return False bop = base_op(raw_op) a = ins["args"] mods = ins.get("mods", ()) if bop in ("v_fma_mix_f32", "v_fma_mixlo_f16", "v_fma_mixhi_f16"): selhi = next((m for m in mods if m.startswith("op_sel_hi:")), "op_sel_hi:[0,0,0]") try: hb = ([int(x) for x in selhi.split("[")[1].rstrip("]").split(",")] + [0, 0, 0])[:3] except (IndexError, ValueError): return False f16_srcs, f32_srcs = set(), set() for i in range(3): if 1 + i < len(a): (f16_srcs if hb[i] else f32_srcs).update(_arg_vgprs(a[1 + i])) want, other = (f16_srcs, f32_srcs) if d16 else (f32_srcs, f16_srcs) return bool(regs) and regs <= want and not (regs & other) if d16: if bop in _F16_ONLY_CONSUMERS: return True if bop.startswith(("v_cmp_", "v_cmpx_")) and bop.endswith("_f16"): if "_class_" not in bop: return True src0_idx = 0 if (bop.startswith("v_cmpx_") or len(a) == 2) else 1 s0 = _arg_vgprs(a[src0_idx]) if src0_idx < len(a) else set() s1 = _arg_vgprs(a[src0_idx + 1]) if src0_idx + 1 < len(a) else set() return bool(regs) and regs <= s0 and not (regs & s1) if bop == "v_ldexp_f16": s0 = _arg_vgprs(a[1]) if len(a) > 1 else set() s1 = _arg_vgprs(a[2]) if len(a) > 2 else set() return bool(regs) and regs <= s0 and not (regs & s1) if bop in ("v_dot2_f32_f16", "v_dot2c_f32_f16"): # src0 (a[1]) and src1 (a[2]) are f16x2; accumulator (a[3] / a[0]) is f32. f16_srcs = (_arg_vgprs(a[1]) if len(a) > 1 else set()) | (_arg_vgprs(a[2]) if len(a) > 2 else set()) acc_idx = 3 if bop == "v_dot2_f32_f16" else 0 acc_regs = _arg_vgprs(a[acc_idx]) if acc_idx < len(a) else set() return bool(regs) and regs <= f16_srcs and not (regs & acc_regs) if bop == "v_pack_b32_f16" and not raw_op.endswith("_dpp") and len(a) >= 3: # Plain v_pack_b32_f16 without sign/abs modifiers is also used to pack integer 16-bit halves # (handled by transitive copy propagation below); with neg/abs it is strictly IEEE f16 sign/abs. hit = [src for src in a[1:3] if _arg_vgprs(src) & regs] return bool(hit) and all(src.get("neg") or src.get("abs") for src in hit) return False if bop in _F32_ONLY_CONSUMERS: return True if bop.startswith(("v_cmp_", "v_cmpx_")) and bop.endswith("_f32"): if "_class_" not in bop: return True src0_idx = 0 if (bop.startswith("v_cmpx_") or len(a) == 2) else 1 s0 = _arg_vgprs(a[src0_idx]) if src0_idx < len(a) else set() s1 = _arg_vgprs(a[src0_idx + 1]) if src0_idx + 1 < len(a) else set() return bool(regs) and regs <= s0 and not (regs & s1) if bop == "v_ldexp_f32": s0 = _arg_vgprs(a[1]) if len(a) > 1 else set() s1 = _arg_vgprs(a[2]) if len(a) > 2 else set() return bool(regs) and regs <= s0 and not (regs & s1) if bop == "v_cvt_pk_u8_f32": # src0 (a[1]) is f32; src1 (a[2], byte index) and src2 (a[3], packed u32) are integer. s0 = _arg_vgprs(a[1]) if len(a) > 1 else set() other = (_arg_vgprs(a[2]) if len(a) > 2 else set()) | (_arg_vgprs(a[3]) if len(a) > 3 else set()) return bool(regs) and regs <= s0 and not (regs & other) if bop in ("v_dot2_f32_f16", "v_dot2c_f32_f16"): acc_idx = 3 if bop == "v_dot2_f32_f16" else 0 acc_regs = _arg_vgprs(a[acc_idx]) if acc_idx < len(a) else set() f16_srcs = (_arg_vgprs(a[1]) if len(a) > 1 else set()) | (_arg_vgprs(a[2]) if len(a) > 2 else set()) return bool(regs) and regs <= acc_regs and not (regs & f16_srcs) if not raw_op.endswith("_dpp") and not mods: # VOP3 float sign/abs modifiers (-v / |v|) on v_mov_b32 / v_cndmask_b32 interpret f32 sign bit. if bop == "v_mov_b32" and len(a) >= 2 and (_arg_vgprs(a[1]) & regs): return bool(a[1].get("neg") or a[1].get("abs")) if bop == "v_cndmask_b32" and len(a) >= 3: hit = [src for src in a[1:3] if _arg_vgprs(src) & regs] return bool(hit) and all(src.get("neg") or src.get("abs") for src in hit) return False def _copy_prop_dst(ins, regs, d16): """If `ins` is a pure register copy/select/pack forwarding `regs` into a single VGPR, return that dst VGPR.""" raw_op = ins["op"] if raw_op.endswith(("_sdwa", "_dpp")): return None bop = base_op(raw_op) a = ins["args"] mods = ins.get("mods", ()) if not a or a[0]["k"] != "vgpr" or a[0].get("n", 1) != 1: return None if bop == "v_mov_b32" and not mods and len(a) >= 2 and a[1]["k"] == "vgpr" and a[1].get("n", 1) == 1: if not a[1].get("neg") and not a[1].get("abs"): return a[0]["r"] return None if bop == "v_cndmask_b32" and not mods and len(a) >= 3: if d16 and any((src.get("neg") or src.get("abs")) for src in a[1:3] if _arg_vgprs(src) & regs): return None return a[0]["r"] if d16 and bop == "v_pack_b32_f16" and len(a) >= 3: return a[0]["r"] return None def float_only_image_ops(blocks, succ): """Set of id(ins) for image_load/image_sample ops whose dest VGPRs are consumed solely by float ops.""" nb = len(blocks) out = set() for b_idx, blk in enumerate(blocks): for i_idx, ins in enumerate(blk): bop = base_op(ins["op"]) if bop not in _FLOAT_ONLY_IMAGE_OPS: continue a = ins["args"] if not a or a[0]["k"] != "vgpr": continue mods = ins.get("mods", ()) d16 = "d16" in mods dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1") try: dmask = int(dm.split(":")[1], 0) except ValueError: continue ncomp = bin(dmask).count("1") nregs = (ncomp + 1) // 2 if d16 else ncomp if nregs <= 0: continue dst_regs = set(range(a[0]["r"], a[0]["r"] + nregs)) # Monotone forward dataflow from (b_idx, i_idx + 1): # in_live[b]: union of tracked VGPRs (including transitive copies) reaching block b # in_exec_sup[b]: True iff EVERY reaching path preserved EXEC >= EXEC_at_image_load in_live = [None] * nb in_exec_sup = [None] * nb saw_float = False ok = True def _scan(cb, start_i, live, exec_sup): nonlocal saw_float, ok ended = False for u in blocks[cb][start_i:]: ubop = base_op(u["op"]) if ubop == "s_endpgm": ended = True break if (ubop.startswith(("v_movrels", "v_movreld", "v_movrelsd", "v_swaprel")) or ubop in ("s_swappc_b64", "s_setpc_b64", "s_call_b64")): ok = False return r_used = live & _vgpr_reads_of(u) copied_dst = None if r_used: if _is_float_consumer_of(u, r_used, d16): saw_float = True else: copied_dst = _copy_prop_dst(u, r_used, d16) if copied_dst is None: ok = False return if writes_exec(u) and not _exec_monotone_widen(u): exec_sup = False if copied_dst is not None: live.add(copied_dst) elif exec_sup: live -= _vgpr_full_writes_of(u) if not live: ended = True break if ok and not ended and live: for nxt in succ[cb]: if in_live[nxt] is None: in_live[nxt] = set(live) in_exec_sup[nxt] = exec_sup work.append(nxt) else: new_live = in_live[nxt] | live new_sup = in_exec_sup[nxt] and exec_sup if len(new_live) != len(in_live[nxt]) or new_sup != in_exec_sup[nxt]: in_live[nxt] = new_live in_exec_sup[nxt] = new_sup work.append(nxt) work = [] _scan(b_idx, i_idx + 1, set(dst_regs), True) while work and ok: cb = work.pop() _scan(cb, 0, set(in_live[cb]), in_exec_sup[cb]) if ok and saw_float: out.add(id(ins)) return out def read_before_write_vgprs(insns): """VGPRs a shader reads before writing them: for a fetch-calling VS these are the fetched attributes. v_writelane_b32 writes one lane and keeps the others (SHADER-768), so its destination is not written by it: the kept lanes still hold what the register held at entry. They are *carried*, and become a read only when something other than v_readlane_b32 reads the register before a full write (shdann's two cases on #4297: a PS whose first touch of v0 is a writelane, then a v_mov of v0, reads the barycentric in the other lanes; a VS that spills an SGPR into one lane of v40 around the fetch call and reads it back with v_readlane never uses the entry value, so v40 is not a fetched attribute). The approximation: a v_readlane of a lane the writelane didn't write would read the entry value, and is not counted.""" written, first, carried = set(), [], set() for ins in insns: a, op = ins["args"], ins["op"] if not a: continue reads_all = op.startswith(VGPR_READ_ONLY_PREFIXES) \ or (op.startswith("global_atomic_") and "glc" not in ins["mods"]) # no vdst without glc regs = [] for x in (a if reads_all or sdwa_reads_dst(op, ins.get("mods", [])) else a[1:]): if x["k"] == "vgpr": regs += range(x["r"], x["r"] + x.get("n", 1)) elif x["k"] == "vlist": regs += x["r"] if (base_op(op) in DST_ALSO_READ or (op.startswith(("global_load_", "flat_load_", "buffer_load_")) and "_d16" in op and "format" not in op) or op == "buffer_load_format_d16_hi_x") and \ a[0]["k"] == "vgpr": # d16 keeps a half regs.append(a[0]["r"]) lane_read = base_op(op) == "v_readlane_b32" for r in regs: if r in written or r in first or (r in carried and lane_read): continue first.append(r) if base_op(op) == "v_writelane_b32" and a[0]["k"] == "vgpr": if a[0]["r"] not in written: carried.add(a[0]["r"]) elif not reads_all and a[0]["k"] == "vgpr": dst = vgpr_dest_registers(ins) written.update(dst) carried.difference_update(dst) return set(first) def interp_ij_analysis(insns, g): """SHADER-177: how each v_interp_p1/p2's I/J operand reaches the site, and what to do with it. Hardware weights the interpolation with the values the named VGPRs hold at the two ops, not with the hardware's own pair (Vonsek's #1224 image evidence: zeroed sources interpolate to P0, swapped operand roles to (v,u)). A program that overwrites v0/v1 with computed barycentrics -- evaluate-at-offset, snapped coordinates, copies held in other registers -- therefore interpolates through the computed pair. Each op of such a pair is annotated ins["ij"] = (kind, key, i VGPR, j VGPR): * pristine: both operands of the pair are v0/v1 and nothing in the shader writes those registers (11,888 of 12,101 PS). The single-lane model's own read -- the interpolated input -- is exact and the site is left untouched. * computed: either operand is written anywhere in the shader (v0/v1 -- conservative under branches) or before the site (any other register). The attribute becomes PerVertexKHR and both ops interpolate with the operand values loaded from %vgpr, which holds whatever the program computed: v_mov, arithmetic on the pair, multi-writer sequences. The p1 loads its I and keeps it for the p2 (the program may rewrite an operand between the two ops: 574 corpus sites set J up between them), and the p2 loads its J fresh; the p1's own full-sum value is dead unless something reads the partial between the ops. A source that is neither v0/v1 nor written is left to interp_pair_src (#1224), which refuses it at emission naming the role; a plain v_mov copy of the pair (g.v_interp_copy) stays #1224's to model, keeping its bit-identical .spv. Refused here (Unsupported, naming the pattern): a computed pair whose ops are not in one basic block (the captured I would not dominate the p2), whose shared partial register -- the f32 vdst, or the f16 p2's fourth operand naming the p1's vdst -- is written between the ops, or read between them by anything but a p2's partial operand, any computed pair under --bary-fallback (no PerVertexKHR inputs), and a computed v_interp_*_f32 on a 16-bit-flagged interpolant (which half the 32-bit op reads is not established). Under --f16-interp-fallback (without --bary-fallback), Gen.ij_quad_eval approximates P(i, j) from the smooth input via its %entry 2x2 screen-quad barycentric Jacobian instead of refusing (shortcut: see Gen.ij_quad_eval). Over the corpus all refused classes are empty under --f16-interp-fallback: 213 PS hold candidate pairs (207 reaching), every pair sits in one block, and no partial is touched between the ops. Returns the set of attribute numbers the computed pairs need in g.per_vertex.""" P1 = ("v_interp_p1_f32", "v_interp_p1ll_f16", "v_interp_p1lv_f16") P2_OF = {"v_interp_p1_f32": "v_interp_p2_f32", "v_interp_p1ll_f16": "v_interp_p2_f16", "v_interp_p1lv_f16": "v_interp_p2_f16"} writes = defaultdict(list) # vgpr -> indexes of insns writing it (read_before_write rules) for n, ins in enumerate(insns): a, op = ins["args"], ins["op"] if not a: continue reads_all = op.startswith(VGPR_READ_ONLY_PREFIXES) if not reads_all and a[0]["k"] == "vgpr": for r in vgpr_dest_registers(ins): writes[r].append(n) sites = [] for n, ins in enumerate(insns): op = base_op(ins["op"]) if op not in P1 and op not in ("v_interp_p2_f32", "v_interp_p2_f16"): continue a = ins["args"] attr = next((x for x in a if x["k"] == "attr"), None) if attr is None or len(a) < 2 or a[0]["k"] != "vgpr" or a[1]["k"] != "vgpr": continue # the emission site raises its own Unsupported partial = a[3]["r"] if (op == "v_interp_p2_f16" and len(a) > 3 and a[3]["k"] == "vgpr") else None sites.append({"n": n, "ins": ins, "op": op, "vdst": a[0]["r"], "src": a[1]["r"], "partial": partial, "attr": attr["a"], "chan": attr["c"], "computed": False}) # Block index per instruction (translate's leader rule), for the reaching-write test and the # same-block requirement. def next_pc(i): return i["pc"] + (len(i["enc"]) // 2 if i["enc"] else 4) def branch_target(i): if "target" in i: return i["target"] imm = next((x for x in i["args"] if x["k"] == "imm"), None) v = imm["v"] & 0xFFFF if imm is not None else 0 return next_pc(i) + 4 * (v - 0x10000 if v & 0x8000 else v) leaders = {insns[0]["pc"]} for i in insns: if base_op(i["op"]) in BRANCHES or base_op(i["op"]) == "s_endpgm": leaders.add(branch_target(i)) leaders.add(next_pc(i)) blk, cur, prev, block_of_pc = [], None, None, {} for k, i in enumerate(insns): if i["pc"] in leaders and i["pc"] != prev: cur = k # a block starts at a leader pc that newly appears prev = i["pc"] blk.append(cur) block_of_pc[i["pc"]] = cur last_of = {} # block -> index of its last instruction, in one pass for k, b in enumerate(blk): last_of[b] = k preds = defaultdict(set) # block -> blocks that can run right before it for b in sorted(last_of): last = last_of[b] op = base_op(insns[last]["op"]) if op == "s_endpgm": continue tgts = [] if op in BRANCHES: t = block_of_pc.get(branch_target(insns[last])) if t is None: raise Unsupported("branch target outside code") tgts.append(t) if op != "s_branch" and last + 1 < len(insns): tgts.append(blk[last + 1]) # conditional branches and plain fallthrough for t in tgts: preds[t].add(b) def reaching_write(reg, s): """A write of reg the site can see: earlier in its own block, or in any block a path runs through first (loops included). A write at the site itself -- an interp whose destination is its own I/J register -- happens after the operand is read and does not count.""" ws = writes.get(reg) if not ws: return False b = blk[s["n"]] if any(w < s["n"] and blk[w] == b for w in ws): return True write_blocks = {blk[w] for w in ws} # b itself is not pre-seeded: reached again through a back-edge, a write after the site counts # (and index 0 is a valid write, so test membership, not truthiness). seen, work = set(), [b] while work: for p in preds[work.pop()]: if p not in seen: seen.add(p) if p in write_blocks: return True work.append(p) return False for s in sites: if s["src"] in (0, 1): s["computed"] = reaching_write(s["src"], s) elif reaching_write(s["src"], s) and s["src"] not in g.v_interp_copy: s["computed"] = True # any other source is pristine: interp_pair_src (#1224) accepts it only as the op's own # coordinate (v0 for p1, v1 for p2) or a plain v_mov copy rooted there — which # interp_copy_sources already vetted, so such a copy keeps #1224's centre-interpolated # read and its bit-identical .spv — and refuses the rest at emission, naming the role if s["computed"] and s["op"].endswith("_f32") and g.pixel_interpolants is not None and \ (g.pixel_interpolants[1] >> s["attr"]) & 1: raise Unsupported("computed I/J on 16-bit interpolant through v_interp_*_f32") # Sites by (op, anchor register, attribute, channel), in program order, for partner(): the f16 p2 is # keyed by its partial (the p1's vdst it names), every other op by its vdst. by_key = defaultdict(list) for t in sites: anchor_reg = t["partial"] if t["op"] == "v_interp_p2_f16" else t["vdst"] by_key[(t["op"], anchor_reg, t["attr"], t["chan"])].append(t) n_by_key = {key: [t["n"] for t in ts] for key, ts in by_key.items()} def partner(k, s): """The other op of the pair: the p1 the p2 completes (nearest before), or the p2 that reads the p1's vdst as its partial (nearest after). Same attribute channel; the f32 pair's vdst is shared, the f16 p2 names the p1's vdst as its fourth operand.""" if s["op"] in P1: want = (P2_OF[s["op"]],) anchor = s["vdst"] elif s["op"] == "v_interp_p2_f32": want = ("v_interp_p1_f32",) anchor = s["vdst"] else: want = ("v_interp_p1ll_f16", "v_interp_p1lv_f16") anchor = s["partial"] # The f32 pair shares the vdst; the f16 p2 names the p1's vdst as its fourth operand (its # partial), and its own vdst is just where the f16 result goes. by_key holds each kind's sites in # program order, so the nearest one after (p1) or before (p2) the site is a binary search. found = [] for op in want: key = (op, anchor, s["attr"], s["chan"]) ts = by_key.get(key) if not ts: continue ns = n_by_key[key] if s["op"] in P1: i = bisect.bisect_right(ns, k) if i < len(ts): found.append(ts[i]) else: i = bisect.bisect_left(ns, k) if i: found.append(ts[i - 1]) if not found: return None return (min if s["op"] in P1 else max)(found, key=lambda t: t["n"]) # Which pairs are computed (either operand is): both ops then take the computed model, so a p2 whose # own operand is pristine still weights with the I its p1 held. pair_of = {} for k, s in enumerate(sites): m = partner(s["n"], s) pair_of[id(s["ins"])] = m if m is not None and (s["computed"] or m["computed"]): s["computed"] = m["computed"] = True attrs = set() for k, s in enumerate(sites): if not s["computed"]: continue m = pair_of[id(s["ins"])] why = None if m is None: why = f"{s['op']} without its {'p2' if s['op'] in P1 else 'p1'} partner" else: lo, hi = min(s["n"], m["n"]), max(s["n"], m["n"]) p1 = s if s["op"] in P1 else m kr = p1["vdst"] # where the p1 partial lives (the f16 p2 reads it by name) if blk[lo] != blk[hi]: why = "the pair's ops are not in one basic block" else: rr, ww = reg_reads_writes(insns[lo + 1:hi]) if kr in ww: why = "the p1 partial is rewritten between the ops" elif kr in rr: # Another p2 reading the same partial is fine (two p2s of one p1); anything else # would observe the p1 partial P10*I, which the full-sum model does not produce. for t in insns[lo + 1:hi]: r, _ = reg_reads_writes([t]) if kr in r and not (base_op(t["op"]) == "v_interp_p2_f16" and t["args"][3:4] and t["args"][3]["k"] == "vgpr" and t["args"][3]["r"] == kr): why = "the p1 partial is read between the ops" break if why: raise Unsupported(f"computed I/J pair: {why}") p1, p2 = (s, m) if s["op"] in P1 else (m, s) s["ins"]["ij"] = ("p1" if s["op"] in P1 else "p2", (p1["vdst"], p1["attr"], p1["chan"]), p1["src"], p2["src"]) # A computed pair loads both weights from the VGPR file, including a hardware weight # whose only use is v_interp. Initialize it even if some paths replace it before this site. if s["src"] in (0, 1): g.frag_inputs[s["src"]] = ("bary_i", "bary_j")[s["src"]] attrs.add(s["attr"]) if attrs and BARY_FALLBACK: raise Unsupported("computed I/J pair under --bary-fallback: no PerVertexKHR inputs") return attrs def reg_reads_writes(insns): """(vgprs read, vgprs written) over a slice of insns, by read_before_write_vgprs' conventions.""" rr, ww = set(), set() for ins in insns: a, op = ins["args"], ins["op"] if not a: continue reads_all = op.startswith(VGPR_READ_ONLY_PREFIXES) regs = [] for x in (a if reads_all or sdwa_reads_dst(op, ins.get("mods", [])) else a[1:]): if x["k"] == "vgpr": regs += range(x["r"], x["r"] + x.get("n", 1)) elif x["k"] == "vlist": regs += x["r"] if (base_op(op) in DST_ALSO_READ or base_op(op) == "v_writelane_b32") and a[0]["k"] == "vgpr": # v_writelane_b32 keeps the other lanes: over a slice that is a read of the destination regs.append(a[0]["r"]) rr.update(regs) if not reads_all and a[0]["k"] == "vgpr": ww.update(vgpr_dest_registers(ins)) return rr, ww def shader_container(path, name): """The DXBC container next to the .s file's folder (/../.dxbc). A pipeline-library program whose source isn't in the carve has none (docs/shader_library.md): Unsupported for that shader, where the bare open() raised FileNotFoundError and stopped the whole run.""" try: with open(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(path))), name + ".dxbc"), "rb") as f: return f.read() except FileNotFoundError: raise Unsupported("no shader container (signatures, PSV0)") from None def source_wave_size(path, name): """Read the source container's wave size only when all of its FSSM payloads agree.""" try: blobs = fssm_unpack.unpack_all(shader_container(path, name)) except (OSError, Unsupported, ValueError, struct.error, zlib.error): return None sizes = {fssm_header.wave_size(blob) for blob in blobs} if len(sizes) == 1: return sizes.pop() return None def input_signature_full(path, name): """ISG1 elements as (system value, declared mask, read/write mask).""" d = shader_container(path, name) for k in range(struct.unpack_from("> 2) == 0x35 # VOP3 (encoding 110101) vop3p = printed[3] == 0xCC if not (vop3 or vop3p): return False op = base_op(op) if op.startswith("v_cmpx_"): source_count = 2 # EXEC is implicit on gfx10, but some listings spell it out. else: dest_count = 2 if op in VOP3_TWO_DESTS else 1 source_count = operand_count - dest_count for index, shift in enumerate((41, 50), start=1): # SRC1, SRC2 if 0 <= source_count <= index and (diff >> shift) & 0x1FF == 0x80 and (r >> shift) & 0x1FF == 0: diff &= ~(0x1FF << shift) two_src = op.startswith("v_pk_") and not any(k in op for k in ("fma", "mad")) if vop3p and source_count == 2 and two_src: diff &= ~(1 << 14) return diff == 0 def restore_dot4_inline_sel(ins, raw, printed): """LLVM prints default op_sel_hi on a signed-byte dot with a replicated low inline integer half.""" if ins["op"] != "v_dot4_i32_i8" or len(raw) != 8 or len(printed) != 8: return False w0, w1 = struct.unpack("> 8 != 0xCC1640 or w1 >> 27 != 1 or not 128 <= (w1 >> 9 & 511) <= 208 or struct.pack("> 16 and any(a.get("k") == "imm" and a.get("v") == literal & 0xFFFF for a in ins["args"][1:4]): restore_mix_literal(ins, enc, literal) def restore_mix_literal(ins, raw, literal): """Give every source of ``ins`` that the stored bytes encode as the literal (SRC field 0xff) its 32-bit value.""" w1 = int.from_bytes(raw[4:8], "little") for i in range(3): if (w1 >> (9 * i)) & 0x1FF == 0xFF and ins["args"][1 + i].get("k") == "imm": ins["args"][1 + i] = {**ins["args"][1 + i], "v": literal} # The f16 bits each inline constant code stands for when llvm-mc 21 prints a v_fma_mix* literal as that constant: # 0..64, -1..-16, +-0.5, +-1.0, +-2.0, +-4.0 and 1/(2*pi). Measured with llvm-mc 21.1.8 (-mcpu=gfx1013) over all 65,536 # low halves of a literal under three high halves (0x0000, 0x3f80, 0xffff): exactly these 90 low halves print as the # inline constant, whatever the high half; every other literal prints in full. MIX_INLINE_F16 = {**{0x80 + n: n for n in range(65)}, **{0xC0 + n: -n & 0xFFFF for n in range(1, 17)}, 0xF0: 0x3800, 0xF1: 0xB800, 0xF2: 0x3C00, 0xF3: 0xBC00, 0xF4: 0x4000, 0xF5: 0xC000, 0xF6: 0x4400, 0xF7: 0xC400, 0xF8: 0x3118} def sdwa_inline_float(raw, printed, op): """LLVM 19 can print an integer-to-half SDWA conversion's inline float as an extra literal dword.""" if op not in ("v_cvt_f16_u16_sdwa", "v_cvt_f16_i16_sdwa") or len(printed) != 12 or len(raw) < 8: return False # Keep only the native VOP1 opcode and source marker when checking the first dword. word = int.from_bytes(raw[:4], "little") & 0xfe01ffff opcode = 0x7e00a0f9 if op == "v_cvt_f16_u16_sdwa" else 0x7e00a2f9 return (word == opcode and 0xf0 <= raw[4] <= 0xf8 and raw[6] & 0x80 and printed[4] == 0xff and raw[:4] == printed[:4] and raw[5:8] == printed[5:8] and int.from_bytes(printed[8:], "little") == MIX_INLINE_F16[raw[4]]) def restore_sdwa_source(ins, raw): import rdna2_decode source, = rdna2_decode.decode_bytes(raw[:8])["insns"] ins["args"][1] = source["args"][1] ins["enc"] = raw[:8].hex() def mix_inline_literal(raw, printed, op): """The 32-bit literal of a v_fma_mix* that llvm-mc 21 printed as an inline constant, else None. llvm-mc 21's gfx1013 decoder reads a v_fma_mix* literal as 16 bits. When those low 16 bits are the f16 value of an inline constant (MIX_INLINE_F16), it prints that constant and re-encodes the instruction in 8 bytes: each SRC field that held 0xff (the literal) holds the inline code instead, and the literal word is gone (0x3f800000, 1.0 as an f32 source, prints as 0; 0x3c003800 as `0.5`). llvm-mc 23 prints lit(...) instead. ``raw`` is the 12 stored bytes at the instruction's offset, ``printed`` the 8-byte printed encoding. Only that change is accepted: every source field that differs must be 0xff in the blob and the inline code of the literal's low half in the print, and the rest of the 8 bytes must match exactly (same_encoding with all three sources live).""" if not op.startswith("v_fma_mix") or len(raw) != 12 or len(printed) != 8 or raw[3] != 0xCC: return None literal = int.from_bytes(raw[8:], "little") stored, shown = int.from_bytes(raw[4:8], "little"), int.from_bytes(printed[4:8], "little") patched = shown for i in range(3): field = (shown >> 9 * i) & 0x1FF if (stored >> 9 * i) & 0x1FF == 0xFF and field != 0xFF and MIX_INLINE_F16.get(field) == literal & 0xFFFF: patched = (patched & ~(0x1FF << 9 * i)) | (0xFF << 9 * i) if patched == shown or not same_encoding(raw[:8], printed[:4] + patched.to_bytes(4, "little"), op, 4): return None return literal def restore_mix_inline_literal(ins, raw, literal): """Give ``ins`` the stored instruction mix_inline_literal accepted: every source the blob encodes as the literal (SRC field 0xff) reads the 32-bit ``literal`` with the stored neg (NEG) and abs (NEG_HI, as abs on v_fma_mix*) bits, and the encoding is the 12 stored bytes, so the next instruction starts after them.""" w0, w1 = int.from_bytes(raw[:4], "little"), int.from_bytes(raw[4:8], "little") for i in range(3): if (w1 >> 9 * i) & 0x1FF == 0xFF: ins["args"][1 + i] = {"k": "imm", "v": literal, "neg": bool((w1 >> (29 + i)) & 1), "abs": bool((w0 >> (8 + i)) & 1)} ins["enc"] = raw.hex() def skipped_form(ins, blob, at): """Whether rdna2_decode's instruction at blob offset ``at`` is one of the forms llvm-mc skips that restore_vcc_tuples takes from the blob: a tuple that reaches vcc (SGPRs 106 and 107), a VOPC f32 compare (v_cmp or v_cmpx) in DPP form (docs/design.md, "DPP on a VOPC compare"), or the measured v_dot4_i32_i8 with op_sel 2 / op_sel_hi 5 and no clamp or neg, all reserved bits clear (tedin7, upstream PR #281; docs/fspx.md). shader_disasm.py prints the last two itself; this covers a listing made without that pass (#984).""" op = ins["op"] if op.startswith(("v_cmp_", "v_cmpx_")) and op.endswith("_f32_dpp"): return True if op == "v_dot4_i32_i8" and int.from_bytes(blob[at:at + 4], "little") >> 8 == 0xCC1650 and blob[at + 7] >> 3 == 1: return True return any(a["k"] == "slist" and ("vcc_lo" in a["r"] or "vcc_hi" in a["r"]) for a in ins["args"]) def restore_vcc_tuples(insns, blob, code_start, code_end, wave32=True): """Decode from the blob the instructions llvm-mc rejects because a scalar tuple runs into vcc. SGPRs 106 and 107 are vcc, and llvm-mc refuses to print a tuple that crosses into them (s_buffer_load_dwordx8 into s[100:107], a buffer resource in s[104:107]): it skips the first word as invalid and then prints the second word as an instruction of its own, one that is junk or does not match the blob (docs/shader_library.md section 5). The pure-Python decoder reads such a word as a VCCTuple list, [s100,...,s105,vcc_lo,vcc_hi], the form the translator takes for these instructions. Only uncovered offsets reached from code_start by fall-through or branches (including folded far branches) are offered to it, so unreachable embedded data words skipped by a branch or after s_endpgm are never decoded across a following branch target; the instruction is used only if its operands hold such a list and no reachable branch targets its interior dwords. Instructions printed inside the words of a restored one are dropped. The instructions already carry their blob offsets in "pc"; returns the list sorted by it. The junk can be longer than the second word it starts at, and then it also swallows the instruction after the tuple, which no printed instruction covers once the junk is dropped. The words after a restored instruction are therefore decoded the same way until the stream is back at an instruction llvm-mc printed there. A word that llvm-mc itself rejected, inside no printed instruction, is not one of those and stays undecodable. wave32 is the shader's wave size: a swallowed VOP3 compare writes one SGPR in wave32 and a pair in wave64.""" import rdna2_decode printed, covered, starts = set(), set(), set() unplaced = None # the pc of the first junk since an instruction that matched the blob for ins in insns: if ins.get("normalized"): # Its pc is a lower bound: the word llvm-mc rejected before it was not counted. unplaced = ins["pc"] if unplaced is None else unplaced continue if unplaced is not None: printed.update(range(unplaced, ins["pc"], 4)) unplaced = None words = range(ins["pc"], ins["pc"] + len(ins["enc"]) // 2, 4) printed.update(words) starts.add(ins["pc"]) covered.update(words) folded = fold_far_branches(insns) by_pc = {ins["pc"]: ins for ins in folded if all(o in covered for o in range(ins["pc"], ins["pc"] + len(ins["enc"]) // 2, 4))} stop = min(len(blob), code_end if code_end is not None else len(blob)) runs, restored_covered, reachable_targets = [], set(), set() # runs: a tuple and the instructions after it seen, work = set(), [code_start] while work: at = work.pop() run = None # the run the previous instruction was restored into, or None after a printed one while code_start <= at < stop and at not in seen: ins = by_pc.get(at) if ins is not None: run = None else: # inside junk llvm-mc printed, not at a start: the words after a restored instruction are code resync = run is not None and at in printed and at not in starts if at in restored_covered or (at in covered and not resync): break found = rdna2_decode.decode_bytes(blob[at:min(at + 20, stop)], wave32=wave32)["insns"][:1] if not (found and found[0]["pc"] == 0 and (resync or skipped_form(found[0], blob, at))): break ins = found[0] end = at + len(ins["enc"]) // 2 if end > stop or any(o in restored_covered for o in range(at, end, 4)): break ins["pc"] = at if not resync: run = [] runs.append(run) run.append(ins) restored_covered.update(range(at, end, 4)) seen.add(at) op = base_op(ins["op"]) at += len(ins["enc"]) // 2 if op in BRANCHES: imm = next((x for x in ins["args"] if x["k"] == "imm"), None) v = (imm["v"] & 0xFFFF) if imm else 0 tgt = ins["target"] if "target" in ins else at + 4 * (v - 0x10000 if v & 0x8000 else v) reachable_targets.add(tgt) work.append(tgt) # shortcut: a swallowed far branch is not followed, so a tuple only it reaches stays refused if op in ("s_branch", "s_endpgm", "s_setpc_b64"): break restored = [] for run in runs: for r in run: if any(o in reachable_targets for o in range(r["pc"] + 4, r["pc"] + len(r["enc"]) // 2, 4)): break # not an instruction, so the words after it are not known to be code either restored.append(r) if not restored: return insns spans = [(r["pc"], r["pc"] + len(r["enc"]) // 2) for r in restored] kept = [i for i in insns if not any(i["pc"] < hi and i["pc"] + len(i["enc"]) // 2 > lo for lo, hi in spans)] return sorted(kept + restored, key=lambda i: i["pc"]) def explicit_carry_vcc(insns): """In place: the assembler's short form v_add_co_ci_u32 vD, src0, src1 (also v_sub_co_ci_u32, v_subrev_co_ci_u32) gets its carry-out and carry-in operands, VCC, as llvm-mc and the disassembler print it (v_add_co_ci_u32_e32 vD, vcc_lo, src0, src1, vcc_lo). Every analysis then sees the VCC it writes.""" for ins in insns: a = ins["args"] if base_op(ins["op"]) in ("v_add_co_ci_u32", "v_sub_co_ci_u32", "v_subrev_co_ci_u32") and len(a) == 3: ins["args"] = [a[0], {"k": "special", "t": "vcc"}, a[1], a[2], {"k": "special", "t": "vcc"}] def widen_wave64_masks(insns): """In place: the lane-mask SGPR operands of VALU instructions become the pairs they are in wave64. The listings come from llvm-mc without +wavefrontsize64, so it prints the wave32 form: v_cmp_*_e64 s8 where the wave64 hardware writes s[8:9], and reads s[10:11] for the s10 of v_cndmask_b32_e64. Taken literally the high SGPR keeps its old value, and the next s_mov_b64 exec, s[8:9] gives lanes 32..63 the wrong bits. Listings disassembled with +wavefrontsize64 already print the pairs and are left as they are.""" for ins in insns: op, a = base_op(ins["op"]), ins["args"] if op.startswith("v_cmp") and len(a) == 3: at = (0,) elif op.startswith("v_") and "_co_ci_" in op: at = (1, 4) elif op.startswith("v_") and "_co_" in op or op in ("v_mad_u64_u32", "v_mad_i64_i32", "v_div_scale_f32", "v_div_scale_f64"): at = (1,) elif op in ("v_cndmask_b32", "v_cndmask_b16"): at = (3,) else: continue for i in at: if i < len(a) and a[i]["k"] == "sgpr" and a[i].get("n", 1) == 1: a[i] = dict(a[i], n=2) def output_signature(path, name): """OSG1 elements as (register, system value), one per register (first element wins).""" d = shader_container(path, name) for k in range(struct.unpack_from("> c) & 1: slots.append(("clip", clip_n)) clip_n += 1 cull_n = 0 for _, _, mask in cull_elems: for c in range(4): if (mask >> c) & 1: slots.append(("cull", cull_n)) cull_n += 1 base_pos = 2 if has_misc else 1 pos_map = {} for k, target in enumerate(slots[:8]): p = base_pos + k // 4 pos_map.setdefault(p, {})[k % 4] = target clip_n = min(clip_n, 8) cull_n = min(cull_n, max(0, 8 - clip_n)) return pos_map, misc_svs, clip_n, cull_n def check_read_methods(methods, insns): """Refuse a PS whose FSSM read methods (tools/fssm_header.py, flags bits 0-1) disagree with its code. Bit 0 says the code reads the input through v_interp_mov_f32 (declared Flat here), bit 1 through v_interp_p1/p2 or the f16 forms (a plain input: perspective, pixel centre, BaryCoordKHR for raw i/j). In the corpus each read position agrees (12,101 of 12,101 PS) and neither-or-both never occurs. A disagreement means a table this translator does not understand, so it is rejected instead of being read as perspective-centre. That every interpolated input is perspective-centre comes from PSV0 (docs/design.md "PS interpolation modes", #1256), not from these bits. Positions past the table are not checked (the 10 kind-7 tables undercount).""" for ins in insns: op = base_op(ins["op"]) if not op.startswith("v_interp_"): continue attr = next((x for x in ins["args"] if x["k"] == "attr"), None) if attr is None or attr["a"] >= len(methods): continue want = fssm_header.READ_MOV if op == "v_interp_mov_f32" else fssm_header.READ_INTERP if methods[attr["a"]] != want: raise Unsupported(f"PS input {attr['a']} read method {methods[attr['a']]} read by {op}") def mesh_psv(path, name): """PSV0 runtime info of a mesh shader: MSInfo (GroupSharedBytesUsed, GroupSharedViewIDDependentBytes, PayloadSizeInBytes, u16 MaxOutputVertices, u16 MaxOutputPrimitives), wave lane counts, then PSVRuntimeInfo1 (stage, UsesViewID, u8 SigPrimVectors, u8 MeshOutputTopology, ...) and PSVRuntimeInfo2 NumThreadsX/Y/Z.""" d = shader_container(path, name) for k in range(struct.unpack_from(".fssm for the game's shaders, and fspx/.code and fspx/.json for the FSPX programs tools/fspx_unpack.py writes (docs/fspx.md).""" root = os.path.dirname(os.path.dirname(os.path.realpath(path))) return (os.path.join(root, "fssm", name + ".fssm"), os.path.join(root, "fspx", name + ".code"), os.path.join(root, "fspx", name + ".json")) def native_blob(path, name): """The bytes the .s was disassembled from (its code_start offset is into these): the FSSM blob, or the FSPX program when there is no FSSM for this name.""" fssm, code, _ = native_paths(path, name) with open(fssm if os.path.isfile(fssm) or not os.path.isfile(code) else code, "rb") as f: return f.read() def ds_const_extent(op, key, value): """Dwords from LDS address 0 to the end of the access a DS instruction's constant offset field `key` makes with vaddr 0: `offset` counts bytes; read2/write2/wrxchg2 offset0/offset1 count elements (x64 for st64). The access width is the instruction's (b8 1 byte ... b128 16), so an access ending at a 64 KiB allocation counts 16384.""" if key == "offset": size = (16 if "b128" in op else 12 if "b96" in op else 8 if "b64" in op else 2 if re.search(r"_[uib]16", op) else 1 if re.search(r"_[uib]8", op) else 4) start = value else: size = 8 if op.endswith("_b64") else 4 start = value * size * (64 if "st64" in op else 1) return (start + size - 1) // 4 + 1 def check_printed_encodings(path, info): """A listing without undecodable words is translated from LLVM's text, which shows the instruction LLVM decoded, not the bytes it read. Where those bytes sit next to the listing (fssm/ or fspx/), each instruction's printed encoding must be the bytes at its offset (same_encoding), so a field the decoder drops is refused instead of being translated as 0: llvm-mc's gfx1013 decoder prints 16-bit VOPC compares without their VOP3 op_sel bits and re-encodes them as 0. On the 1.0.2.1 corpus all 30,335,381 instructions of the 25,030 such listings match. Only a listing whose header names the code range it was disassembled from (shader_disasm.py), with a blob that holds that range, is checked: a hand-written listing, run_gpu_tests.py's "code 0x0..0x0 (synthetic)" and a test's header-only blob are not the bytes the text came from.""" for ins in info["insns"]: if ins.get("enc"): # needs only the printed encoding, so it runs before the blob checks below restore_text_cut_mix_literal(ins, bytes.fromhex(ins["enc"])) with open(path, encoding="utf-8", errors="replace") as f: m = HDR.match(f.readline()) if not m or int(m.group(3), 16) <= int(m.group(2), 16): return fssm, code, _ = native_paths(path, info["name"]) if not (os.path.isfile(fssm) or os.path.isfile(code)): return blob = native_blob(path, info["name"]) if int(m.group(3), 16) > len(blob): return shift = 0 # actual bytes consumed minus printed bytes consumed so far for ins in info["insns"]: ins["pc"] += shift if not ins.get("enc"): continue enc = bytes.fromhex(ins["enc"]) raw = blob[ins["pc"]:ins["pc"] + len(enc)] if not same_encoding(raw, enc, ins["op"], len(ins["args"])): if sdwa_inline_float(raw, enc, ins["op"]): restore_sdwa_source(ins, raw) shift -= 4 continue if restore_dot4_inline_sel(ins, raw, enc): continue literal = mix_literal(raw, enc, base_op(ins["op"])) if literal is not None: restore_mix_literal(ins, raw, literal) continue raw12 = blob[ins["pc"]:ins["pc"] + 12] literal = mix_inline_literal(raw12, enc, base_op(ins["op"])) if literal is not None: restore_mix_inline_literal(ins, raw12, literal) shift += 4 continue raise Unsupported(f"{ins['op']} at 0x{ins['pc']:x}: the blob holds {raw.hex()}, LLVM printed " f"{enc.hex()} (a field the disassembler dropped)") def cs_dispatch_state(path, name): """(COMPUTE_PGM_RSRC2, group x, y, z): FSSM header words 0x138..0x144, or an FSPX program's kind-0 entry.""" fssm, _, meta = native_paths(path, name) if os.path.isfile(fssm) or not os.path.isfile(meta): with open(fssm, "rb") as f: hdr = f.read(0x148) return struct.unpack_from("<4I", hdr, 0x138) with open(meta, encoding="utf-8") as f: m = _json.load(f) return (m["rsrc2"], *m["threads"]) def fspx_wave_size(path, name): """32 or 64 from an FSPX program's dispatch state, or None: the `wave32` field tools/fspx_unpack.py writes to fspx/.json from kind 0's word 4 bit 20 (set = wave32; docs/fspx.md, "Kind 0: dispatch state"). None when the program has an FSSM blob, no fspx/.json, or a kind 0 too short to hold word 4.""" fssm, _, meta = native_paths(path, name) if os.path.isfile(fssm) or not os.path.isfile(meta): return None try: with open(meta, encoding="utf-8") as f: wave32 = _json.load(f).get("wave32") except (OSError, ValueError, AttributeError): return None return None if not isinstance(wave32, bool) else (32 if wave32 else 64) def lower_final_halts(insns): """Lower supported s_sethalt forms in place in the instruction stream, preserving their PCs. s_sethalt sets the wave's HALT bit to SIMM16[0] (RDNA2 ISA, SOPP): 1 stops issuing instructions until a debugger or the host clears it, 0 lets it run. Nothing clears it in a translated dispatch, so a halt right before s_endpgm ends the wave exactly where the s_endpgm would, after the same memory writes, and s_sethalt 0 does nothing. A halt with more code after it would hang the wave on the console, which an invocation cannot do; that one is refused. """ out = [] for k, ins in enumerate(insns): if base_op(ins["op"]) != "s_sethalt": out.append(ins) continue a = ins["args"] value = a[0].get("v") if a and a[0].get("k") == "imm" else None if not isinstance(value, int): raise Unsupported("s_sethalt without an immediate") nxt = insns[k + 1]["op"] if k + 1 < len(insns) else None halts = value & 1 if halts and nxt != "s_endpgm": raise Unsupported("s_sethalt 1 before more code") # A branch can target this PC, and the PC can also be its fall-through block's leader. out.append({**ins, "op": "s_endpgm" if halts else "s_nop", "args": [], "mods": ""}) return out def fssm_wave_size(path, name): """32 or 64 from the FSSM header flags, or None when the program has no FSSM blob.""" try: with open(native_paths(path, name)[0], "rb") as f: return fssm_header.wave_size(f.read(fssm_header.WAVE_FLAGS_OFFSET + 4)) except OSError: return None def wave_markers(insns): """The wave size the code itself shows: (strict wave64 ops, any wave64 use, any wave32 EXEC op).""" w64_marks = {base_op(i["op"]) for i in insns if WAVE64_RE.search(" ".join([i["op"]] + [x.get("t", "") for x in i["args"]]))} code_w64 = bool(w64_marks) or any(base_op(i["op"]).endswith("_b64") and any(x.get("t") in ("exec", "vcc") for x in i["args"]) for i in insns) code_w32 = any(WAVE32_RE.search(i["op"]) for i in insns) return w64_marks, code_w64, code_w32 def marker_wave64(path, name, stage, insns): """Whether a program whose header and dispatch state hold no wave size is wave64, from its code.""" w64_marks, code_w64, code_w32 = wave_markers(insns) if (stage in ("vs", "ps") and code_w64 and code_w32 and not (w64_marks - {"s_bfm_b64"}) and os.path.isfile(native_paths(path, name)[1]) and source_wave_size(path, name) == 32): # A library program can use s_bfm_b64 as scalar data. Use the matching source's # wave32 flags only when this program's own EXEC instructions corroborate them. return False return code_w64 or stage == "ms" # NGG mesh shaders here are wave64 (thread = wave id * 64 + lane) _FLOW = re.compile(r"(?m)^[ \t]*(?:(%[\w.]+)\s*=\s*)?(OpLabel|OpSelectionMerge|OpLoopMerge|OpBranch|" r"OpBranchConditional|OpControlBarrier)\b([^;\n]*)") def barriers_under_control_flow(text): """Whether some OpControlBarrier is reached by only part of the workgroup. SPIR-V requires a workgroup-scope barrier to be reached by every invocation in uniform control flow. NVIDIA's wait is for every thread (docs/design.md "Workgroup barriers"): a barrier one invocation never reaches stands the whole group until the driver resets the card (Xid 109 / device lost). Emulated wave64 exchanges (`Gen.x_round`, `x_order_barrier`) emit such barriers inline, so the inline structured form may bury one inside a `%pc` guard, a lane-local region or a loop body; `Gen.x_scheduler` keeps one barrier at the end of every round instead, in the loop's continue block. A barrier in a loop's continue block counts as uniform: every invocation runs the round loop.""" label_at, constructs, pending = {}, [], [] for match in _FLOW.finditer(text): result, op, operands = match.groups() args = operands.split() if op == "OpLabel": label_at[result] = match.start() elif op in ("OpLoopMerge", "OpSelectionMerge"): nxt = _FLOW.search(text, match.end()) if nxt is None or nxt.group(2) not in ("OpBranch", "OpBranchConditional"): continue # a switch head has no body label to compare body = nxt.group(3).split()[0 if nxt.group(2) == "OpBranch" else 1] pending.append((op, body, args[0], args[1] if op == "OpLoopMerge" else None)) for op, body, merge, cont in pending: if body in label_at and merge in label_at: constructs.append({"kind": op, "cont": cont, "start": label_at[body], "end": label_at[merge]}) if not constructs: return False block_at = sorted((match.start(), match.group(1)) for match in _FLOW.finditer(text) if match.group(2) == "OpLabel") for match in _FLOW.finditer(text): if match.group(2) != "OpControlBarrier": continue block = next((name for at, name in reversed(block_at) if at < match.start()), None) inside = [c for c in constructs if c["start"] <= match.start() < c["end"]] while inside and inside[-1]["kind"] == "OpLoopMerge" and inside[-1]["cont"] == block: inside.pop() # the round barrier: the whole workgroup runs it if inside: return True return False _FTZ32_DISABLE_OPS = frozenset({"v_div_scale_f32", "v_div_fmas_f32", "s_denorm_mode"}) _HWREG_MODE_RE = re.compile( r"^hwreg\(\s*(\w+)(?:\s*,\s*(0x[0-9a-fA-F]+|\d+)(?:\s*,\s*(0x[0-9a-fA-F]+|\d+))?)?\s*\)$" ) def _disables_ftz32(insns): """Whether any instruction in `insns` requires disabling hardware DenormFlushToZero 32. v_div_scale_f32 and v_div_fmas_f32 preserve subnormal f32 inputs/intermediates on RDNA2 even under denorm32=0, and s_denorm_mode / s_setreg* writing HW_REG_MODE bits [5:4] (FP_DENORM.fp32) to a non-zero or non-constant value may disable f32 denormal flushing. Writes to disjoint MODE bit ranges (such as FP_ROUND.fp64_fp16 in bits [3:2]) or immediate writes that set the overlapped [5:4] bits to 0 keep FTZ32 enabled.""" for ins in insns: op = base_op(ins["op"]) if op in _FTZ32_DISABLE_OPS: return True if not op.startswith("s_setreg"): continue if not ins["args"]: return True a0 = ins["args"][0] if a0.get("k") == "imm": simm16 = a0["v"] & 0xFFFF if (simm16 & 0x3F) != 1: continue offset = (simm16 >> 6) & 0x1F size = ((simm16 >> 11) & 0x1F) + 1 else: t = a0.get("t", "") m = _HWREG_MODE_RE.match(t) if not m: return True reg_id = m.group(1) if reg_id != "HW_REG_MODE": try: if int(reg_id, 0) != 1: continue except ValueError: continue offset = int(m.group(2), 0) if m.group(2) is not None else 0 size = int(m.group(3), 0) if m.group(3) is not None else 32 if offset < 0 or offset >= 32 or size <= 0 or size > 32: return True lo = max(offset, 4) hi = min(offset + size, 6) if lo >= hi: continue if op == "s_setreg_imm32_b32" and len(ins["args"]) >= 2 and ins["args"][1].get("k") == "imm" \ and not ins["args"][1].get("abs"): val = ins["args"][1]["v"] & 0xFFFFFFFF mask = (1 << (hi - lo)) - 1 if ((val >> (lo - offset)) & mask) != 0: return True continue return True return False _PSB_WRITE_PREFIXES = ( "buffer_store", "tbuffer_store", "buffer_atomic", "global_store", "global_atomic", "flat_store", "flat_atomic", "scratch_store", "s_store", "s_buffer_store", "s_atomic", "s_buffer_atomic", ) def _scalar_operand_slots(arg): """Return list of scalar slots (int SGPR index or 'vcc_lo'/'vcc_hi') for an operand, or None.""" k = arg.get("k") if k == "sgpr": return list(range(arg["r"], arg["r"] + arg.get("n", 1))) if k == "slist": return list(arg["r"]) if k == "special" and arg.get("t") in ("vcc", "vcc_lo", "vcc_hi"): return ["vcc_lo", "vcc_hi"] if arg["t"] == "vcc" else [arg["t"]] return None def _symbolic_origin(tag): """Return a non-constant symbolic descriptor/pointer origin tag, or None if unknown/constant.""" if tag is None or tag[0] == "const": return None return tag def _root_origin(tag): """Unwrap an arithmetic-offset wrapper ('off', root) to its underlying symbolic root origin.""" if tag is not None and tag[0] == "off": return tag[1] return tag def _as_offset_origin(tag): """Mark a symbolic pointer tag as having an untracked arithmetic offset (preserving code/rodata).""" if tag is None or tag[0] in ("const", "code", "off"): return tag return ("off", tag) def _origin_depth(tag): """Nesting depth of a symbolic ('load'/'load_dyn', base, ...) origin tag.""" d = 0 cur = _root_origin(tag) while cur is not None and cur[0] in ("load", "load_dyn"): d += 1 cur = _root_origin(cur[1]) return d def _merge_sym_tag(v1, v2): """Join two symbolic provenance tags at a CFG merge or conditional select.""" if v1 == v2: return v1 if v1 is None or v2 is None: return None r1, r2 = _root_origin(v1), _root_origin(v2) if r1 is not None and r1 == r2 and r1[0] != "const": return _as_offset_origin(r1) if r1 is not None and r2 is not None and r1[0] in ("load", "load_dyn") and r2[0] in ("load", "load_dyn") and r1[1] == r2[1]: return ("load_dyn", r1[1]) return None def _origins_may_alias(o1, o2): """Conservative alias check between two symbolic descriptor/pointer origins.""" if o1 is None or o2 is None: return True r1, r2 = _root_origin(o1), _root_origin(o2) if r1 is None or r2 is None: return True if r1 == r2: return True if r1[0] == "code" or r2[0] == "code": return False if r1[0] == "load" and r2[0] == "load": return r1[2] == r2[2] and _origins_may_alias(r1[1], r2[1]) # Dynamic offset load from an aliasing base table may hit any static/dynamic slot in that table. if r1[0] in ("load", "load_dyn") and r2[0] in ("load", "load_dyn"): return _origins_may_alias(r1[1], r2[1]) return False def _origin_chain_aliases_known(origin, known_writes): """Whether `origin` or any ancestor table pointer in its load chain aliases a write origin in `known_writes`.""" cur = _root_origin(origin) while cur is not None: if any(_origins_may_alias(cur, wo) for wo in known_writes): return True cur = _root_origin(cur[1]) if cur[0] in ("load", "load_dyn") else None return False def _psb_write_origin(ins, sym): """Extract the symbolic base-address origin of a PSB memory write instruction, or None if unknown.""" op = base_op(ins["op"]) a = ins["args"] if op.startswith(("buffer_store", "tbuffer_store", "buffer_atomic")): if len(a) >= 3: slots = _scalar_operand_slots(a[2]) if slots and len(slots) == 4: return _symbolic_origin(sym.get(slots[0])) return None if op.startswith("global_store"): if len(a) >= 3: slots = _scalar_operand_slots(a[2]) if slots and len(slots) == 2: return _symbolic_origin(sym.get(slots[0])) return None if op.startswith("global_atomic"): idx = 3 if "glc" in ins["mods"] else 2 if len(a) > idx: slots = _scalar_operand_slots(a[idx]) if slots and len(slots) == 2: return _symbolic_origin(sym.get(slots[0])) return None if op.startswith(("s_store", "s_buffer_store", "s_atomic", "s_buffer_atomic")): if len(a) >= 2: slots = _scalar_operand_slots(a[1]) if slots: return _symbolic_origin(sym.get(slots[0])) return None return None def _sload_static_offset(ins, sym, is_sbuf): """Return the normalized static byte offset of an s_load / s_buffer_load, or None if dynamic.""" a = ins["args"] off = a[2] if len(a) > 2 else {"k": "imm", "v": 0} inst = [m.split(":", 1)[1] for m in ins["mods"] if m.startswith("offset:")] if len(inst) > 1 or (inst and off["k"] == "imm"): return None imm = 0 if inst: try: imm = int(inst[0], 0) except ValueError: return None reg_const = None if off["k"] == "imm": imm = off["v"] elif off["k"] == "special" and off.get("t") == "null": reg_const = 0 else: slots = _scalar_operand_slots(off) if not slots or len(slots) != 1: return None tag = sym.get(slots[0]) if tag is None or tag[0] != "const": return None reg_const = tag[1] & 0xFFFFFFFC if is_sbuf: imm &= 0xFFFFFFFF else: imm = ((imm & 0x1FFFFF) ^ 0x100000) - 0x100000 imm &= ~3 return (reg_const + imm) if reg_const is not None else imm def _read_scalar_tag(sym, arg): """Read a 32-bit constant or symbolic provenance tag for a single scalar operand.""" if arg["k"] == "imm": return ("const", arg["v"] & 0xFFFFFFFF) if arg["k"] == "special" and arg.get("t") == "null": return ("const", 0) slots = _scalar_operand_slots(arg) if slots and len(slots) == 1: return sym.get(slots[0]) return None def _const_lane(sym, arg): """Constant lane index (0..63) for v_writelane_b32 / v_readlane_b32, or None if dynamic.""" t = _read_scalar_tag(sym, arg) return t[1] & 63 if t is not None and t[0] == "const" else None def _step_scalar_provenance(sym, ins, desc_src=None): """Advance forward SGPR/VCC/spill-VGPR provenance state across one instruction. When `desc_src` is given (slot -> frozenset of s_load instruction ids), also propagates which s_load instructions originated each slot's value (through copies, selects, and VGPR spill lanes) so descriptor-only loads can be verified.""" op = base_op(ins["op"]) a = ins["args"] if op in ("s_swappc_b64", "s_setpc_b64", "s_call_b64") or op.startswith("s_movreld"): sym.clear() if desc_src is not None: desc_src.clear() return if not a: return def read_tag(arg): return _read_scalar_tag(sym, arg) def clear_slots(slots): if slots: for s in slots: sym.pop(s, None) if desc_src is not None: desc_src.pop(s, None) def clear_vgpr_lanes(vregs): if not vregs: return for k in [k for k in sym if isinstance(k, tuple) and k[1] in vregs]: del sym[k] if desc_src is not None: for k in [k for k in desc_src if isinstance(k, tuple) and k[1] in vregs]: del desc_src[k] if op.startswith(("v_movreld", "v_movrelsd", "v_swaprel")): for k in [k for k in sym if isinstance(k, tuple)]: del sym[k] if desc_src is not None: for k in [k for k in desc_src if isinstance(k, tuple)]: del desc_src[k] return if op == "v_writelane_b32" and len(a) >= 3 and a[0]["k"] == "vgpr": vr = a[0]["r"] lane = _const_lane(sym, a[2]) if lane is None: clear_vgpr_lanes({vr}) return key = ("v", vr, lane) t = read_tag(a[1]) if t is not None: sym[key] = t else: sym.pop(key, None) if desc_src is not None: src = _scalar_operand_slots(a[1]) if src and len(src) == 1 and src[0] in desc_src: desc_src[key] = desc_src[src[0]] else: desc_src.pop(key, None) return if op == "v_readlane_b32": dst = _scalar_operand_slots(a[0]) if dst and len(dst) == 1 and len(a) >= 3 and a[1]["k"] == "vgpr": lane = _const_lane(sym, a[2]) if lane is not None: key = ("v", a[1]["r"], lane) t = sym.get(key) if t is not None: sym[dst[0]] = t else: sym.pop(dst[0], None) if desc_src is not None: if key in desc_src: desc_src[dst[0]] = desc_src[key] else: desc_src.pop(dst[0], None) return clear_slots(dst) return if op == "s_mov_b32" and len(a) >= 2: dst = _scalar_operand_slots(a[0]) if dst and len(dst) == 1: t = read_tag(a[1]) if t is not None: sym[dst[0]] = t else: sym.pop(dst[0], None) if desc_src is not None: src = _scalar_operand_slots(a[1]) if src and len(src) == 1 and src[0] in desc_src: desc_src[dst[0]] = desc_src[src[0]] else: desc_src.pop(dst[0], None) return if op == "s_movk_i32" and len(a) >= 2 and a[1]["k"] == "imm": dst = _scalar_operand_slots(a[0]) if dst and len(dst) == 1: v = a[1]["v"] & 0xFFFF if v & 0x8000: v |= 0xFFFF0000 sym[dst[0]] = ("const", v & 0xFFFFFFFF) if desc_src is not None: desc_src.pop(dst[0], None) return if op in ("s_addk_i32", "s_mulk_i32") and len(a) >= 2 and a[1]["k"] == "imm": dst = _scalar_operand_slots(a[0]) if dst and len(dst) == 1: v = a[1]["v"] & 0xFFFF if v & 0x8000: v -= 0x10000 cur = sym.get(dst[0]) if cur is not None and cur[0] == "const": sym[dst[0]] = ("const", ((cur[1] + v) if op == "s_addk_i32" else (cur[1] * v)) & 0xFFFFFFFF) elif op == "s_addk_i32" and _symbolic_origin(cur) is not None: sym[dst[0]] = cur if v == 0 else _as_offset_origin(cur) else: sym.pop(dst[0], None) if desc_src is not None: desc_src.pop(dst[0], None) return if op == "s_mov_b64" and len(a) >= 2: dst = _scalar_operand_slots(a[0]) if dst and len(dst) == 2: if a[1]["k"] == "imm": v = a[1]["v"] sym[dst[0]] = ("const", v & 0xFFFFFFFF) sym[dst[1]] = ("const", (v >> 32) & 0xFFFFFFFF) if desc_src is not None: desc_src.pop(dst[0], None) desc_src.pop(dst[1], None) else: src = _scalar_operand_slots(a[1]) if src and len(src) == 2: vals = [sym.get(src[0]), sym.get(src[1])] dvals = [desc_src.get(src[0]), desc_src.get(src[1])] if desc_src is not None else None for i, (d, v) in enumerate(zip(dst, vals)): if v is not None: sym[d] = v else: sym.pop(d, None) if desc_src is not None: if dvals[i] is not None: desc_src[d] = dvals[i] else: desc_src.pop(d, None) else: clear_slots(dst) return if op in ("s_cselect_b32", "s_cmov_b32") and len(a) >= (3 if op == "s_cselect_b32" else 2): dst = _scalar_operand_slots(a[0]) if dst and len(dst) == 1: x_arg, y_arg = (a[1], a[2]) if op == "s_cselect_b32" else (a[1], a[0]) merged = _merge_sym_tag(read_tag(x_arg), read_tag(y_arg)) if merged is not None: sym[dst[0]] = merged else: sym.pop(dst[0], None) if desc_src is not None: sx = _scalar_operand_slots(x_arg) sy = _scalar_operand_slots(y_arg) dx = desc_src.get(sx[0]) if sx and len(sx) == 1 else None dy = desc_src.get(sy[0]) if sy and len(sy) == 1 else None union = (dx or frozenset()) | (dy or frozenset()) if union: desc_src[dst[0]] = union else: desc_src.pop(dst[0], None) return if op in ("s_cselect_b64", "s_cmov_b64") and len(a) >= (3 if op == "s_cselect_b64" else 2): dst = _scalar_operand_slots(a[0]) if dst and len(dst) == 2: x_arg, y_arg = (a[1], a[2]) if op == "s_cselect_b64" else (a[1], a[0]) def _pair_tags(arg): if arg["k"] == "imm": v = arg["v"] return [("const", v & 0xFFFFFFFF), ("const", (v >> 32) & 0xFFFFFFFF)], [None, None] s = _scalar_operand_slots(arg) if s and len(s) == 2: return ([sym.get(s[0]), sym.get(s[1])], [desc_src.get(s[0]), desc_src.get(s[1])] if desc_src is not None else [None, None]) return [None, None], [None, None] xt, xd = _pair_tags(x_arg) yt, yd = _pair_tags(y_arg) for i, d in enumerate(dst): merged = _merge_sym_tag(xt[i], yt[i]) if merged is not None: sym[d] = merged else: sym.pop(d, None) if desc_src is not None: union = (xd[i] or frozenset()) | (yd[i] or frozenset()) if union: desc_src[d] = union else: desc_src.pop(d, None) return if op == "s_getpc_b64": dst = _scalar_operand_slots(a[0]) if dst and len(dst) == 2: sym[dst[0]] = ("code",) sym[dst[1]] = ("code",) if desc_src is not None: desc_src.pop(dst[0], None) desc_src.pop(dst[1], None) return if op in ("s_add_u32", "s_add_i32", "s_addc_u32", "s_sub_u32", "s_sub_i32", "s_subb_u32", "s_and_b32", "s_or_b32", "s_xor_b32", "s_lshl_b32", "s_lshr_b32", "s_mul_i32", "s_lshl1_add_u32", "s_lshl2_add_u32", "s_lshl3_add_u32", "s_lshl4_add_u32") and len(a) >= 3: dst = _scalar_operand_slots(a[0]) if dst and len(dst) == 1: t0, t1 = read_tag(a[1]), read_tag(a[2]) c0_flag = t0 is not None and t0[0] == "const" c1_flag = t1 is not None and t1[0] == "const" s0_slots = _scalar_operand_slots(a[1]) s1_slots = _scalar_operand_slots(a[2]) out = None if op == "s_and_b32" and (t0 == ("const", 0) or t1 == ("const", 0)): out = ("const", 0) elif op in ("s_xor_b32", "s_sub_u32", "s_sub_i32") and s0_slots and s0_slots == s1_slots: out = ("const", 0) elif c0_flag and c1_flag: c0, c1 = t0[1], t1[1] if op in ("s_add_u32", "s_add_i32"): out = ("const", (c0 + c1) & 0xFFFFFFFF) elif op in ("s_sub_u32", "s_sub_i32"): out = ("const", (c0 - c1) & 0xFFFFFFFF) elif op == "s_and_b32": out = ("const", c0 & c1) elif op == "s_or_b32": out = ("const", c0 | c1) elif op == "s_xor_b32": out = ("const", c0 ^ c1) elif op == "s_lshl_b32": out = ("const", (c0 << (c1 & 31)) & 0xFFFFFFFF) elif op == "s_lshr_b32": out = ("const", (c0 >> (c1 & 31)) & 0xFFFFFFFF) elif op == "s_mul_i32": out = ("const", (c0 * c1) & 0xFFFFFFFF) elif op.startswith("s_lshl"): sh = int(op[6]) out = ("const", ((c0 << sh) + c1) & 0xFFFFFFFF) elif op not in ("s_xor_b32", "s_lshl_b32", "s_lshr_b32", "s_mul_i32"): s0, s1 = _symbolic_origin(t0), _symbolic_origin(t1) if op.startswith("s_lshl"): # (S0 << sh) + S1: shifting a base pointer left does not preserve its origin; # only propagate S1 when the shifted index S0 is a known constant (marking as offset if non-zero). if c0_flag and s1 is not None: out = s1 if t0[1] == 0 else _as_offset_origin(s1) elif s0 is not None and c1_flag: noop = (op in ("s_add_u32", "s_add_i32", "s_sub_u32", "s_sub_i32", "s_or_b32") and t1[1] == 0) \ or (op == "s_and_b32" and t1[1] == 0xFFFFFFFF) out = s0 if noop else _as_offset_origin(s0) elif s1 is not None and c0_flag and op not in ("s_sub_u32", "s_sub_i32", "s_subb_u32"): noop = (op in ("s_add_u32", "s_add_i32", "s_or_b32") and t0[1] == 0) \ or (op == "s_and_b32" and t0[1] == 0xFFFFFFFF) out = s1 if noop else _as_offset_origin(s1) elif op in ("s_and_b32", "s_or_b32") and s0 is not None and _root_origin(s0) == _root_origin(s1): out = s0 if s0 == s1 else _as_offset_origin(s0) if out is not None: sym[dst[0]] = out else: sym.pop(dst[0], None) if desc_src is not None: desc_src.pop(dst[0], None) return if op.startswith(("s_load_dword", "s_buffer_load_dword")) and len(a) >= 2: dst = _scalar_operand_slots(a[0]) base = _scalar_operand_slots(a[1]) if dst: base_tag = _symbolic_origin(sym.get(base[0])) if base else None base_root = _root_origin(base_tag) if base_root is not None and _origin_depth(base_root) < 4: off = None if base_tag[0] == "off" else _sload_static_offset(ins, sym, op.startswith("s_buffer")) for i, slot in enumerate(dst): sym[slot] = ("load", base_root, off + 4 * i) if off is not None else ("load_dyn", base_root) else: clear_slots(dst) if desc_src is not None: tag = frozenset((id(ins),)) if op.startswith("s_load_dword") else None for slot in dst: if tag is not None: desc_src[slot] = tag else: desc_src.pop(slot, None) return # Any non-writelane instruction that writes a VGPR clears any spilled scalar lanes parked in that VGPR. if (not op.startswith(VGPR_READ_ONLY_PREFIXES) and not (op.startswith(("buffer_load", "tbuffer_load")) and "lds" in ins.get("mods", ())) and not (op.startswith("ds_") and not _is_ds_dst_only(op))): written_v = _arg_vgprs(a[0]) if op == "v_swap_b32" and len(a) >= 2: written_v |= _arg_vgprs(a[1]) if written_v: clear_vgpr_lanes(written_v) # Any other instruction that writes scalar destination slots clears their provenance. if op.startswith(("s_cmp", "s_bitcmp", "s_cbranch", "s_branch", "s_waitcnt", "s_nop", "s_endpgm", "s_barrier", "s_sendmsg", "s_setreg", "s_round_mode", "s_store", "s_buffer_store", "buffer_", "tbuffer_", "global_", "flat_", "scratch_", "image_", "ds_", "exp")): return if op.startswith("v_cmp"): if not op.startswith("v_cmpx"): dst = _scalar_operand_slots(a[0]) clear_slots(dst if dst else ["vcc_lo", "vcc_hi"]) elif op.startswith("s_") or op in ("v_readfirstlane_b32", "v_readlane_b32"): clear_slots(_scalar_operand_slots(a[0])) if len(a) >= 2 and op in ("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", "v_div_scale_f32", "v_div_scale_f64"): clear_slots(_scalar_operand_slots(a[1])) def _classify_scalar_uses(ins, sym, desc_src, used_as_desc, used_as_data, used_as_sload_base): """Record whether scalar operands read by `ins` are used solely as descriptors (T#/S#/V#), as base pointers of another s_load, or as general data.""" if not desc_src: return op = base_op(ins["op"]) a = ins["args"] if not a: return if op in ("s_mov_b32", "s_mov_b64", "s_cselect_b32", "s_cselect_b64", "s_cmov_b32", "s_cmov_b64"): dst = _scalar_operand_slots(a[0]) want = 2 if op.endswith("_b64") else 1 if dst and len(dst) == want: # Pure copies/selects into tracked scalar slots propagate desc_src without classifying the value yet. return if op in ("s_swappc_b64", "s_setpc_b64", "s_call_b64") or op.startswith("s_movrel"): for tags in desc_src.values(): used_as_data.update(tags) return if op == "v_writelane_b32": if len(a) >= 3 and a[0]["k"] == "vgpr": lane = _const_lane(sym, a[2]) # Lane index operand (if scalar reg) is data; source sS propagates into ("v", vr, lane) when lane is const. for idx in ((2,) if lane is not None else (1, 2)): slots = _scalar_operand_slots(a[idx]) if slots: for s in slots: tags = desc_src.get(s) if tags: used_as_data.update(tags) else: for arg in a: slots = _scalar_operand_slots(arg) if slots: for s in slots: tags = desc_src.get(s) if tags: used_as_data.update(tags) return if op == "v_readlane_b32": if len(a) >= 3 and a[1]["k"] == "vgpr": lane = _const_lane(sym, a[2]) slots = _scalar_operand_slots(a[2]) if slots: for s in slots: tags = desc_src.get(s) if tags: used_as_data.update(tags) if lane is None: vr = a[1]["r"] for k, tags in desc_src.items(): if isinstance(k, tuple) and k[1] == vr: used_as_data.update(tags) return if op.startswith(("v_movrels", "v_movreld", "v_movrelsd", "v_swaprel")): for k, tags in desc_src.items(): if isinstance(k, tuple): used_as_data.update(tags) else: # Any non-readlane read of a spill VGPR consumes all descriptor tags parked in its lanes as general data. vreads = _vgpr_reads_of(ins) if vreads: for k, tags in desc_src.items(): if isinstance(k, tuple) and k[1] in vreads: used_as_data.update(tags) # Identify operand indices that are pure descriptor reads (T#, S#, V#), s_load base ptrs, or write-only. desc_idxs = set() sload_base_idxs = set() write_only_idxs = set() if op.startswith("image_"): if len(a) >= 3: desc_idxs.add(2) # T# if len(a) >= 4: desc_idxs.add(3) # S# if not op.startswith(("image_store", "image_atomic")): write_only_idxs.add(0) elif op.startswith(("buffer_", "tbuffer_")): if "lds" in ins.get("mods", ()) and op.startswith(("buffer_load", "tbuffer_load")): if len(a) >= 2: desc_idxs.add(1) # V# (no vdata operand when lds is set) else: if len(a) >= 3: desc_idxs.add(2) # V# if op.startswith(("buffer_load", "tbuffer_load")): write_only_idxs.add(0) elif op.startswith("s_buffer_"): if len(a) >= 2: desc_idxs.add(1) # V# if op.startswith("s_buffer_load"): write_only_idxs.add(0) elif op.startswith("s_load_dword"): write_only_idxs.add(0) if len(a) >= 2: sload_base_idxs.add(1) elif op.startswith("s_") and not op.startswith(("s_cmp", "s_bitcmp", "s_cbranch", "s_branch", "s_store", "s_atomic", "s_setreg", "s_sendmsg", "s_waitcnt", "s_nop", "s_endpgm", "s_barrier", "s_round_mode", "s_cmov", "s_bitset")): write_only_idxs.add(0) elif op.startswith("v_") and not op.startswith(("v_cmp", "v_cmpx")) and op not in DST_ALSO_READ: write_only_idxs.add(0) if op in ("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", "v_div_scale_f32", "v_div_scale_f64"): write_only_idxs.add(1) child_id = id(ins) for idx, arg in enumerate(a): if idx in write_only_idxs: continue slots = _scalar_operand_slots(arg) if not slots: continue if idx in sload_base_idxs: for s in slots: tags = desc_src.get(s) if tags: for parent_id in tags: used_as_sload_base.setdefault(parent_id, set()).add(child_id) continue target = used_as_desc if idx in desc_idxs else used_as_data for s in slots: tags = desc_src.get(s) if tags: target.update(tags) def analyse_scalar_load_ro(blocks, succ, user_limit=USER_SGPRS, sys_sgprs=()): """Decide which s_load* / s_buffer_load* instructions may safely carry NonWritable (allowing RADV/ACO SMEM). Returns True when the shader performs no PhysicalStorageBuffer memory writes at all (all scalar loads are safe), or a frozenset of id(ins) for scalar loads proven not to alias any PSB write in the module: - If any s_dcache_* instruction is present alongside a PSB write, falls back conservatively to frozenset(). - Descriptor-only s_load* (from a 32-bit or 64-bit user SGPR table pointer or multi-level table load, including descriptors carried through scalar-spill VGPRs via v_writelane_b32/v_readlane_b32, whose origin chain is not explicitly written and whose loaded dwords are consumed solely as T#/S#/V# descriptors or as the base pointer of another descriptor-only s_load) and s_getpc_b64 code/rodata loads are read-only. - Any scalar load with no PSB write reachable before it on any CFG path (`not store_reached`, including loop back-edges) is read-only unless its known origin explicitly aliases a known PSB write reachable after it. - Any scalar load whose symbolic descriptor/pointer origin (user SGPR root or static descriptor-table slot) is strictly disjoint from every PSB write's origin in the module is read-only.""" if not blocks: return True nb = len(blocks) has_dcache = False has_any_write = False for b, blk in enumerate(blocks): for ins in blk: op = base_op(ins["op"]) if op == "s_endpgm": break if op.startswith("s_dcache_"): has_dcache = True if op.startswith(_PSB_WRITE_PREFIXES): has_any_write = True if not has_any_write: return True if has_dcache: return frozenset() # Forward SGPR/VCC/spill-VGPR descriptor provenance and s_load-origin dataflow (also discovers reachable blocks). system = set(sys_sgprs) entry_sym = [None] * nb entry_dsrc = [None] * nb entry_sym[0] = {r: ("in", r) for r in range(user_limit) if r not in system} entry_dsrc[0] = {} work = [0] while work: b = work.pop() sym = dict(entry_sym[b]) dsrc = dict(entry_dsrc[b]) for ins in blocks[b]: if base_op(ins["op"]) == "s_endpgm": break _step_scalar_provenance(sym, ins, dsrc) for s in succ[b]: if entry_sym[s] is None: entry_sym[s] = dict(sym) entry_dsrc[s] = dict(dsrc) work.append(s) else: merged_sym = {} for k, v in entry_sym[s].items(): m = _merge_sym_tag(v, sym.get(k)) if m is not None: merged_sym[k] = m # Join desc_src by union so any path on which a slot comes from an s_load sees all its uses. merged_dsrc = dict(entry_dsrc[s]) for k, v in dsrc.items(): merged_dsrc[k] = merged_dsrc[k] | v if k in merged_dsrc else v if merged_sym != entry_sym[s] or merged_dsrc != entry_dsrc[s]: entry_sym[s] = merged_sym entry_dsrc[s] = merged_dsrc work.append(s) # Collect per-block PSB writes/origins, classify s_load uses, and record every scalar load at its exact point. write_origins = set() block_writes_list = [[] for _ in range(nb)] # per block: [(idx, origin_or_None), ...] used_as_desc, used_as_data = set(), set() used_as_sload_base = {} # parent s_load id -> set of child s_load ids scalar_loads = [] # (ins, b, idx, is_desc_ptr, origin) for b in range(nb): if entry_sym[b] is None: continue sym = dict(entry_sym[b]) dsrc = dict(entry_dsrc[b]) for idx, ins in enumerate(blocks[b]): op = base_op(ins["op"]) if op == "s_endpgm": break _classify_scalar_uses(ins, sym, dsrc, used_as_desc, used_as_data, used_as_sload_base) if op.startswith(_PSB_WRITE_PREFIXES): wo = _psb_write_origin(ins, sym) write_origins.add(wo) block_writes_list[b].append((idx, wo)) elif op.startswith(("s_load_dword", "s_buffer_load_dword")) and len(ins["args"]) >= 2: base = _scalar_operand_slots(ins["args"][1]) origin = _symbolic_origin(sym.get(base[0])) if base else None hi_tag = sym.get(base[1]) if (base and len(base) == 2) else None origin_root = _root_origin(origin) hi_root = _root_origin(hi_tag) is_desc_ptr = ( op.startswith("s_load_dword") and base is not None and len(base) == 2 and origin_root is not None and origin_root[0] in ("in", "load", "load_dyn") and hi_root is not None and hi_root[0] in ("const", "in", "load", "load_dyn") ) scalar_loads.append((ins, b, idx, is_desc_ptr, origin)) _step_scalar_provenance(sym, ins, dsrc) # Forward CFG store-reachability: whether any PSB write can precede entry to block b (including loop back-edges). block_writes = [bool(block_writes_list[b]) for b in range(nb)] write_in = [False] * nb write_out = list(block_writes) changed = True while changed: changed = False for b in range(nb): if write_out[b]: for s in succ[b]: if not write_in[s]: write_in[s] = True if not write_out[s]: write_out[s] = True changed = True # Backward CFG reachability: whether any PSB write (and which write origins, including None) can follow block b. write_after_out = [False] * nb write_after_in = list(block_writes) write_after_out_origins = [set() for _ in range(nb)] write_after_in_origins = [{wo for _, wo in block_writes_list[b]} for b in range(nb)] changed = True while changed: changed = False for b in range(nb): if any(write_after_in[s] for s in succ[b]): if not write_after_out[b]: write_after_out[b] = True if not write_after_in[b]: write_after_in[b] = True changed = True for s in succ[b]: if write_after_in_origins[s]: before_o = len(write_after_out_origins[b]) write_after_out_origins[b].update(write_after_in_origins[s]) if len(write_after_out_origins[b]) != before_o: write_after_in_origins[b].update(write_after_out_origins[b]) changed = True # Least fixed point for multi-level descriptor-only s_load_dword* instructions. known_write_origins = {wo for wo in write_origins if wo is not None} desc_cand = set() for ins, b, idx, is_desc_ptr, origin in scalar_loads: lid = id(ins) if (is_desc_ptr and not _origin_chain_aliases_known(origin, known_write_origins) and lid not in used_as_data and (lid in used_as_desc or lid in used_as_sload_base)): desc_cand.add(lid) desc_only_ro = set() changed = True while changed: changed = False for lid in desc_cand: if lid in desc_only_ro: continue children = used_as_sload_base.get(lid) if children is None: if lid in used_as_desc: desc_only_ro.add(lid) changed = True elif children <= desc_only_ro: desc_only_ro.add(lid) changed = True ro = set() for ins, b, idx, is_desc_ptr, origin in scalar_loads: if origin == ("code",): ro.add(id(ins)) continue if id(ins) in desc_only_ro: ro.add(id(ins)) continue w_before = write_in[b] or any(w_idx < idx for w_idx, _ in block_writes_list[b]) w_after = write_after_out[b] or any(w_idx > idx for w_idx, _ in block_writes_list[b]) if not w_before and not w_after: ro.add(id(ins)) continue if not w_before: after_origins = write_after_out_origins[b] | {wo for w_idx, wo in block_writes_list[b] if w_idx > idx} if origin is not None and None not in after_origins and not _origin_chain_aliases_known(origin, after_origins): ro.add(id(ins)) continue if origin is not None and not _origin_chain_aliases_known(origin, write_origins): ro.add(id(ins)) return frozenset(ro) def _translate(path): global GUARD_MODULE_ID GUARD_MODULE_ID = fnv1a32(os.path.splitext(os.path.basename(path))[0]) info = parse_file(path) stage = stage_of(info["name"], path) if stage not in ("vs", "ps", "cs", "ms", "gs"): raise Unsupported(f"stage {stage}") insns = info["insns"] if not insns: # parse_file only reads tab-indented instructions, so a hand-written or re-indented .s parses to nothing # and used to translate to a module that passes spirv-val and does no work at all. Refuse it instead. raise Unsupported("no instructions (nothing tab-indented?)") if info["invalid"]: # Undecodable words are constant tables embedded in the code range (147/155 such VS/PS use s_getpc_b64 to # read them). LLVM skips them, so re-anchor every instruction to its true offset in the FSSM blob, then # translate only code reachable from entry; a branch into data is rejected below. blob = native_blob(path, info["name"]) pos = info["code_start"] # llvm-mc's own messages say where it rejected a word, and it moves on by 4 bytes after each: with them the # stream is anchored exactly, with no forward search (which can match a later copy of the same encoding when # the printed bytes are not the bytes read, and then loses every instruction after it). A listed offset whose # bytes are the next instruction is not skipped, so a listing whose messages do not match its blob still reads. bad = set(info.get("invalid_at") or ()) exact = bool(bad) and len(bad) == info["invalid"] for ins in insns: enc = bytes.fromhex(ins["enc"]) restore_text_cut_mix_literal(ins, enc) op, operand_count = ins["op"], len(ins["args"]) if exact: while pos in bad and not same_encoding(blob[pos:pos + len(enc)], enc, op, operand_count): pos += 4 window = blob[pos:pos + len(enc)] # The same repairs as the forward search below: a signed-byte dot's stored op_sel_hi first. if not same_encoding(window, enc, op, operand_count) and not restore_dot4_inline_sel(ins, window, enc): literal = mix_literal(window, enc, base_op(op)) if literal is not None: restore_mix_literal(ins, window, literal) else: literal = mix_inline_literal(blob[pos:pos + 12], enc, base_op(op)) if literal is not None: restore_mix_inline_literal(ins, blob[pos:pos + 12], literal) enc = blob[pos:pos + 12] elif pos + len(enc) > len(blob): raise Unsupported("undecodable words (cannot re-anchor)") else: ins["normalized"] = True ins["pc"] = pos pos += len(enc) continue skipped, at = 0, pos while not same_encoding(blob[at:at + len(enc)], enc, op, operand_count): if restore_dot4_inline_sel(ins, blob[at:at + len(enc)], enc): break literal = mix_literal(blob[at:at + len(enc)], enc, base_op(op)) if literal is not None: restore_mix_literal(ins, blob[at:at + len(enc)], literal) break raw8 = blob[at:at + 8] if sdwa_inline_float(raw8, enc, op): restore_sdwa_source(ins, raw8) enc = raw8 break literal = mix_inline_literal(blob[at:at + 12], enc, base_op(op)) if literal is not None: restore_mix_inline_literal(ins, blob[at:at + 12], literal) enc = blob[at:at + 12] # the 12 bytes the decoder read: the next one starts after them break at += 4 skipped += 4 if skipped > 4096 or at >= len(blob): at = None break if at is None: # LLVM prints the encoding of the instruction it decoded, not the bytes it read: data words that # decode with ignored fields set (e.g. 0xbe8d2242 -> s_rfe_b64, printed 0xbe802242) never match. # The decoder consumed the same number of bytes, so the instruction sits at the current position. # Such words are data in every case seen; reachable_code drops them unless a branch lands there. if pos + len(enc) > len(blob): raise Unsupported("undecodable words (cannot re-anchor)") at = pos ins["normalized"] = True ins["pc"] = at pos = at + len(enc) wave = fssm_wave_size(path, info["name"]) or fspx_wave_size(path, info["name"]) if wave is None: matched = [i for i in insns if not i.get("normalized")] wave = 64 if marker_wave64(path, info["name"], stage, matched) else 32 insns = restore_vcc_tuples(insns, blob, info["code_start"], info.get("code_end"), wave32=wave == 32) insns = fold_far_branches(insns) insns = reachable_code(insns, info.get("code_end")) if any(i.get("normalized") for i in insns): raise Unsupported("reachable instruction with normalized encoding") else: check_printed_encodings(path, info) insns = lower_final_halts(insns) def _uses_vcc_tuple(ins): return any(a.get("k") == "slist" and ("vcc_lo" in a["r"] or "vcc_hi" in a["r"]) for a in ins["args"]) g = Gen(stage, hoist_reg_ptrs=True, cache_active=True) g.vcc_scalar_pointer = any( (i["op"].startswith("s_load_dword") and len(i["args"]) >= 2 and i["args"][1].get("t") == "vcc") or _uses_vcc_tuple(i) for i in insns ) g.exec_static_true = not any(writes_exec(i) for i in insns) g.atomic_volume_tsharps = {g.tsharp_regs(i["args"][2]) for i in insns if base_op(i["op"]) in (*Gen.IMG_ATOMICS, *Gen.IMG_ATOMICS_EXTRA, "image_atomic_cmpswap") and "dim:SQ_RSRC_IMG_3D" in i["mods"] and len(i["args"]) >= 3 and i["args"][2]["k"] in ("sgpr", "slist")} if stage in ("vs", "ms"): # --f16-interp-fallback places the decoded halves clear of every param g.param_max = max((int(t[5:]) for i in insns if base_op(i["op"]) == "exp" for t in (i["args"][0].get("t", ""),) if t.startswith("param") and t[5:].isdigit()), default=-1) g.round_mode = any(i["op"] == "s_round_mode" or (i["op"].startswith("s_setreg") and "HW_REG_MODE" in i["args"][0].get("t", "")) for i in insns) g.ftz32 = bool(FLOAT_CONTROLS and FTZ32 and not _disables_ftz32(insns)) w64_marks, code_w64, code_w32 = wave_markers(insns) # Authoritative wave size from the FSSM header flags at 0xD4 bit 5 (0x20 = wave32, 0 = wave64; # verified with 0 contradictions across all 26,503 corpus blobs). Falls back to the code-marker # heuristic (+ wave64 default for NGG mesh shaders) when no FSSM sidecar is present (FSPX or # synthetic listings). fssm_ws = fssm_wave_size(path, info["name"]) # An FSPX program (the FidelityFX DLL's) has no FSSM header; its kind-0 dispatch state carries the wave size # instead (word 4 bit 20 = wave32, docs/fspx.md). Only the strict markers count against it: a _b64 op on vcc or # exec is not one, since these programs move vcc as an ordinary SGPR pair (s_mov_b64 vcc, s[..]) in wave32 code. # Nor is s_bfm_b64: it is 64-bit data in wave32 code (958 pipeline-library compute programs whose state says # wave32, 905 of them with *_saveexec_b32, build an S# with it; see the s_bfm_b64 translation). fspx_ws = fspx_wave_size(path, info["name"]) if fssm_ws is None else None if fssm_ws is not None: if fssm_ws == 32 and code_w64: raise Unsupported("FSSM wave32 header contradicts wave64 code") if fssm_ws == 64 and code_w32: raise Unsupported("FSSM wave64 header contradicts wave32 code") g.wave64 = fssm_ws == 64 elif fspx_ws is not None: if fspx_ws == 32 and w64_marks - {"s_bfm_b64"}: raise Unsupported("FSPX wave32 dispatch state contradicts wave64 code") if fspx_ws == 64 and code_w32: raise Unsupported("FSPX wave64 dispatch state contradicts wave32 code") g.wave64 = fspx_ws == 64 else: g.wave64 = marker_wave64(path, info["name"], stage, insns) explicit_carry_vcc(insns) if g.wave64: widen_wave64_masks(insns) # A wave32 program using VCC as an SMEM pointer, in a descriptor tuple ([..., vcc_lo, vcc_hi]), or as a # 64-bit SGPR pair move (`s_mov_b64 vcc, s[a:b]`; wave32 lane masks are 32-bit `vcc_lo` only) needs both # scalar words. Mark its pair producers before lane-mask analysis so later reads see both exact words. g.wave32_vcc_pointer = not g.wave64 and any( (i["op"].startswith("s_load_") and len(i["args"]) > 1 and i["args"][1].get("t") == "vcc") or _uses_vcc_tuple(i) or (base_op(i["op"]) == "s_mov_b64" and len(i["args"]) == 2 and i["args"][0].get("t") == "vcc" and i["args"][1].get("k") == "sgpr" and i["args"][1].get("n") == 2) for i in insns ) if g.wave32_vcc_pointer: for i in insns: if lane_masks.wave32_vcc_pair_op(base_op(i["op"]), i["args"]): i["vcc_data_pair"] = True if stage == "gs": ins_by_reg = {} for reg, mask, sv, ctype in input_signature(path, info["name"]): if reg in ins_by_reg and (ins_by_reg[reg] == 1) != (sv == 1): raise Unsupported("gs signature") ins_by_reg.setdefault(reg, sv) ins_sig = sorted(ins_by_reg.items()) outs = output_signature(path, info["name"]) if not ins_sig or not outs: raise Unsupported("gs signature") n_emit = sum(1 for i in insns if base_op(i["op"]) == "s_sendmsg" and any("GS_OP_EMIT" in x.get("t", "") for x in i["args"])) if not (1 <= n_emit <= 64): raise Unsupported("gs emit count") g.gs = {"in": ins_sig, "out": outs, "nreg": max(r for r, _ in outs) + 1, "maxv": n_emit} for i in (0, 1, 3, 8, 64, 128, 0x4000, g.gs["nreg"], 64 << 16): # used by assemble g.cu(i) for i in range(n_emit * g.gs["nreg"] + 1): g.cu(i) if stage == "ms": # Mesh shaders run as NGG wave64 programs. PSV0 (DXBC) gives NumThreads, MaxOutputVertices/Primitives and # the output topology. System inputs (Mesa radv_shader_args.c, mesh as NGG on GFX10.3): v5 = first launch # vertex ID of the lane, groupIndex * NumThreads + lane ("vertex_id" slot); the merged-wave-info SGPR (s3 here) holds the wave id in [27:24]; user data # follows in s16.. (from push constants, like every stage). psv = mesh_psv(path, info["name"]) if psv is None: raise Unsupported("mesh PSV0") if psv["topology"] != 2: raise Unsupported(f"mesh topology {psv['topology']}") if not (1 <= psv["threads"] <= 1024) or not (1 <= psv["maxv"] <= 256) or not (1 <= psv["maxp"] <= 512): raise Unsupported("mesh limits") g.ms = psv g.cu(psv["threads"]) # the v5 seed (assemble) multiplies by it; constants must exist before assembly # LDS: the declared group-shared size. With LDS_BOUNDS (default ON; Mandy 21633b328 parity), any declared # allocation > 0 sizes the array to lds_declared and bounds-checks every access (OOB reads 0, OOB writes and # atomics dropped instead of wrapping onto low LDS slots, matching RDNA2 ISA 3.6.1 / 3.6.6). g.lds_declared = (psv.get("shared", 0) + 3) // 4 need = g.lds_declared for ins in insns: if not ins["op"].startswith("ds_") or ins["op"].startswith(("ds_swizzle", "ds_bpermute", "ds_permute")): continue for m in ins["mods"]: k, _, v = m.partition(":") if not v[:1].isdigit(): continue if k in ("offset", "offset0", "offset1"): need = max(need, ds_const_extent(ins["op"], k, int(v, 0))) g.lds_need = need if LDS_BOUNDS and g.lds_declared > 0: g.lds_dwords = g.lds_bound = min(g.lds_declared, 16384) g.cu(g.lds_bound) else: n = 16 while n < need: n *= 2 g.lds_dwords = min(n, 16384) g.cu(max(g.lds_dwords, 1)) g.cu(max(g.lds_dwords, 1) - 1) for i in (2, 3, 5, 6, 10, 12, 20, 24, 31, 63, 0x108, 0x1FF, 0xFFF, psv["maxv"], psv["maxp"]): # used by assemble g.cu(i) if stage == "cs": # Compute system registers come from the FSSM header. Word 0x138 is COMPUTE_PGM_RSRC2 (checked against # the SGPRs all 2,689 CS read before writing: 2,540 stay inside it, the other 149 overshoot only through # loop-carried registers of the straight-line check; docs/design.md): USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], # TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11]. Words 0x13C/0x140/0x144 are the thread-group size. Layout (Mesa # radv_shader_args.c): s0..user-1 = user data, then the enabled workgroup ids, then with TG_SIZE_EN the # thread-group SGPR; v0, v1, v2 = thread id x, y, z (separate VGPRs on GFX10). An FSPX program (the FidelityFX # DLL's shaders) and a pipeline-library program (docs/shader_library.md) carry the same two fields in their # kind-0 entry (docs/fspx.md). rsrc2, lx, ly, lz = cs_dispatch_state(path, info["name"]) if not (1 <= lx * ly * lz <= 1024): raise Unsupported("CS group size") user = (rsrc2 >> 1) & 31 g.cs = {"user": user, "tgid": [c for c in range(3) if (rsrc2 >> (7 + c)) & 1], "tid": (rsrc2 >> 11) & 3, "size": (lx, ly, lz), "tg_size": bool((rsrc2 >> 10) & 1)} # LDS_SIZE [23:15] in 512-byte units. All 485 LDS-using corpus CS stay inside it; a constant offset past it, # which RDNA2 treats as out of range, is bounds-checked below (SHADER-309). need = ((rsrc2 >> 15) & 0x1FF) * 128 for ins in insns: if not ins["op"].startswith("ds_") or ins["op"].startswith(("ds_swizzle", "ds_bpermute", "ds_permute")): continue for m in ins["mods"]: k, _, v = m.partition(":") if not v[:1].isdigit(): continue if k in ("offset", "offset0", "offset1"): need = max(need, ds_const_extent(ins["op"], k, int(v, 0))) g.lds_declared = ((rsrc2 >> 15) & 0x1FF) * 128 g.lds_need = need if need > g.lds_declared or (LDS_BOUNDS and g.lds_declared > 0): # Unconditional RDNA2 LDS bounds (Mandy 21633b328 / SHADER-309): RDNA2 LDS does not wrap; an access # outside the RSRC2 allocation reads 0 and drops its write/atomic (ISA 3.6.1, 3.6.6). The array is # sized to the declared allocation (even when non-power-of-two) and every access is bounds-checked via # lds_access(). --no-lds-bounds restores the wrapped power-of-two array when constant offsets stay inside. g.lds_dwords = g.lds_bound = min(g.lds_declared, 16384) g.cu(g.lds_bound) else: n = 16 while n < need: n *= 2 g.lds_dwords = min(n, 16384) g.cu(max(g.lds_dwords, 1)) g.cu(max(g.lds_dwords, 1) - 1) for i in range(user, user + 3): g.cu(i) if stage == "ps": # Pixel-shader system VGPRs (12,098 of 12,101 PS exact; docs/design.md): v0-v1 = barycentrics (modelled through # v_interp -> attributes), then v2.. = the SV_Position components the shader reads, packed in order. # Anything else a PS reads before writing is an input layout we haven't confirmed: reject it. sig = input_signature_full(path, info["name"]) pos = [rw for sv, m, rw in sig if sv == 1] used = pos[0] if pos else 0 # Position w: AMD's POS_W_FLOAT input holds 1/w. Mesa (src/amd/common/nir/ac_nir_lower_intrinsics_to_args.c) # lowers nir_intrinsic_load_frag_coord_w_rcp straight to frag_pos[3]. That's the same value as Vulkan's # FragCoord.w, so all four components map directly. # Hardware order (Mesa src/amd/vulkan/radv_shader_args.c): barycentric pairs, ..., POS_X/Y/Z/W, FRONT_FACE, # ANCILLARY, SAMPLE_COVERAGE, POS_FIXED_PT. Only enabled inputs are packed. Front face holds 0xffffffff # (front) / 0 (back), the form the game's shaders test (SHADER-892; Mesa's float form is +1.0 / -1.0). layout = {} nxt = 2 for c in range(4): if used >> c & 1: layout[nxt] = c nxt += 1 if any(sv == 9 for sv, _, _ in sig): # D3D_NAME_IS_FRONT_FACE layout[nxt] = "front" nxt += 1 no_bary = [dict(i, args=[x for k, x in enumerate(i["args"]) if not (i["op"].startswith("v_interp") and x["k"] == "vgpr" and k != 0)]) for i in insns] reads = read_before_write_vgprs(no_bary) # Reads inside the system-input range that aren't in the layout (raw barycentrics, unknown inputs): reject. # Reads past the last hardware input can't be hardware inputs: they're values undefined on some path, and # the zero-initialised registers stand in for them. # Raw reads of the barycentric pair (v0 = i, v1 = j) outside v_interp, e.g. v_readfirstlane_b32 s41, v1 in # 315 PS: AMD interpolates P = P0 + i(P1 - P0) + j(P2 - P0), so i and j are the weights of vertices 1 and 2, # which VK_KHR_fragment_shader_barycentric gives as BaryCoordKHR.y / .z. Assumes the pair is the # perspective-center one, the only pair this layout models. for r, comp in ((0, "bary_i"), (1, "bary_j")): if r in reads: layout[r] = comp unexplained = {r for r in reads if r < nxt and r not in layout} if unexplained: raise Unsupported("PS system inputs") g.frag_inputs = layout attr_reads: dict[str, set[int]] = defaultdict(set) for ins in insns: op = base_op(ins["op"]) if op.startswith("v_interp_"): attr_reads[op].update(arg["a"] for arg in ins["args"] if arg["k"] == "attr") f16_read = attr_reads["v_interp_p1ll_f16"] | attr_reads["v_interp_p1lv_f16"] | attr_reads["v_interp_p2_f16"] mixed_f32 = attr_reads["v_interp_mov_f32"] & (attr_reads["v_interp_p1_f32"] | attr_reads["v_interp_p2_f32"]) if mixed_f32 and (BARY_FALLBACK or F16_HALVES): raise Unsupported("flat and interpolated reads of one f32 attribute need per-vertex inputs") mov_delta = {x["a"] for i in insns if base_op(i["op"]) == "v_interp_mov_f32" and any(x.get("k") == "interp" and x.get("t") in ("p10", "p20") for x in i["args"]) for x in i["args"] if x["k"] == "attr"} if F16_HALVES: # decoded halves from the producer: no per-vertex inputs (and no barycentrics) g.f16_halves = f16_read elif not BARY_FALLBACK: # A smooth input alone cannot supply P0 for a MOV reading the same location. g.per_vertex = f16_read | mixed_f32 | mov_delta for r in layout: g.cu(r) # FSSM pixel-input table (tools/fssm_header.py): the authoritative interpolant list. Position i of the # table is v_interp attr i; interpolants() gives the count and the 16-bit flag mask by position. Every # table position is declared as a fragment input (the table lists inputs the code never reads: 775 of # 12,101 PS overcount by one or more), and the mask marks 16-bit interpolants for the v_interp path # above. No sidecar, or a sidecar with no table, leaves the code-driven declarations untouched. try: with open(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(path))), "fssm", info["name"] + ".fssm"), "rb") as f: blob = f.read() count, fp16 = fssm_header.interpolants(blob) methods = fssm_header.read_methods(blob) g.db_shader_control = fssm_header.db_shader_control(blob) except OSError: count, fp16, methods = 0, 0, [] check_read_methods(methods, insns) if count: g.pixel_interpolants = (count, fp16) g.pixel_flat = [n for n, m in enumerate(methods) if m == fssm_header.READ_MOV] for n in range(count): g.inputs.setdefault(f"%in_attr{n}", n) if stage == "ps": # D3D_NAME_TARGET (64); OSG1 keeps SV_Target n in register n, so the semantic index is the render target. osg1 = output_signature_full(path, info["name"]) g.mrt_targets = sorted({sem for _, sem, sysv, _, _, _ in osg1 if sysv == 64}) # D3D_NAME_DEPTH (65), DEPTH_GREATER_EQUAL (67), DEPTH_LESS_EQUAL (68), STENCIL_REF (69). g.osg1_depth_stencil = any(sysv in (65, 67, 68, 69) for _, _, sysv, _, _, _ in osg1) for _, sem, sysv, mask, _, ctype in osg1: if sysv == 64: g.mrt_masks[sem] = mask & 0xF if ctype in (1, 2): g.mrt_types[sem] = ctype if stage in ("vs", "ms"): g.pos_map, g.pos_misc, g.clip_count, g.cull_count = pos_export_layout( output_signature_full(path, info["name"]), insns) if stage == "vs" and any(base_op(i["op"]) == "s_swappc_b64" for i in insns): # The call goes to a driver-generated fetch program (not in the blob). Verified rule over 788 shaders: # input-signature register r, component c is fetched into v(4 + 4r + c). Replace the call with Vulkan # vertex inputs (location = register) written into those VGPRs at entry. sig = [s for s in input_signature(path, info["name"]) if s[2] == 0] # Any component of a declared register may be read: components the vertex format lacks come back as the # format defaults (0, 0, 1 for y, z, w) from the hardware fetch, and Vulkan fills a vec4 input from a # narrower format the same way. Seen: .w of an xyz position. predicted = {4 + 4 * reg + c for reg, mask, _, _ in sig for c in range(4)} reads = {r for r in read_before_write_vgprs(insns) if r >= 4} if not reads <= predicted: raise Unsupported("fetch mapping") g.vertex_inputs = vertex_input_locations(sig) g.vertex_signature = [{"register": reg, "mask": mask, "system_value": sv, "component_type": ctype} for reg, mask, sv, ctype in sig] for reg, _ in g.vertex_inputs: # register the VGPR index constants before assembly for c in range(4): g.cu(4 + 4 * reg + c) insns = [i for i in insns if base_op(i["op"]) != "s_swappc_b64"] user_limit = g.cs["user"] if g.cs else USER_SGPRS sys_sgprs = (3,) if stage in ("ms", "gs") else () if WAVE64_EMULATE and g.wave64 and stage in ("cs", "ms"): # A first-active-lane read can see different values in the two physical subgroups: the lowering takes the # first active lane of the executing subgroup. Every corpus mesh shader has one on a VGPR other than v5 # (9,282/9,282), so the flag selects none of them until a per-use rule proves the source wave-uniform. if (MESH_NATIVE_WAVE32 and stage == "ms" and not any( i["op"].startswith("ds_") or any(b in i["op"] for b in ("v_readlane", "v_readfirstlane", "v_writelane", "v_permlane", "s_bcnt1", "s_ff1", "s_flbit", "_dpp", "quad", "atomic", "store")) or (i["op"].startswith("v_mbcnt_") and not (len(i["args"]) >= 2 and i["args"][1]["k"] == "imm" and i["args"][1]["v"] == -1)) for i in insns)): g.ms_native_wave32 = True else: g.emulate = True size = (g.cs or g.ms)["size"] g.x_lanes = -(-size[0] * size[1] * size[2] // 64) * 64 threads = size[0] * size[1] * size[2] if (MESH_SERIAL_WAVES and stage == "ms" and threads > 64 and threads % 64 == 0 and not any(i["op"].startswith("ds_") or "store" in i["op"] or "atomic" in i["op"] for i in insns)): # The waves of such a program cannot pass each other anything: no LDS, and no store or atomic to # memory another wave could read (ms_wave_info_s3 counts lanes in LDS across an s_barrier and keeps # the side-by-side form). What is left between them is the allocation request and the exports, which # assemble() orders itself. The order of the waves is then not observable. g.ms_serial = threads // 64 # passes; every pass is one whole wave g.x_lanes = 64 for k in range(g.ms_serial + 1): g.cu(k) g.cu(64 * k) elif (COMPUTE_SERIAL_WAVES and stage == "cs" and threads > 64 and threads % 64 == 0 and not any(i["op"].startswith("ds_") or "atomic" in i["op"] or base_op(i["op"]) == "s_barrier" for i in insns)): g.cs_serial = threads // 64 g.x_lanes = 64 for v in size[:2]: g.cu(v) for k in range(g.cs_serial + 1): g.cu(k) g.cu(64 * k) insns = fold_far_branches(insns) if stage == "ps" and g.mrt_types: insns = unpatch_int_mrt_exports(insns, g.mrt_targets, g.mrt_types, g.mrt_masks) branchy = any(base_op(i["op"]) in BRANCHES for i in insns) if stage == "ps": g.v_interp_copy = interp_copy_sources(insns) # before v_interp runs: I/J guards (SHADER-177) # SHADER-177: annotate v_interp sites whose I/J operand is a computed pair, and let those # attributes be read per-vertex when PerVertexKHR is available; under --f16-interp-fallback # (without --bary-fallback), Gen.ij_quad_eval evaluates them from smooth inputs + %entry fine derivatives. ij_attrs = interp_ij_analysis(insns, g) if not F16_HALVES: g.per_vertex |= ij_attrs if any("ij" in i for i in insns): # Computed v_interp sites load their I/J VGPRs at runtime; no_bary above stripped all # v_interp sources, so an untouched (or conditionally/EXEC-masked written) v0/v1 still # needs BaryCoordKHR loaded into %vgpr[0]/%vgpr[1] in the prologue. with_ij = [dict(i, args=[x for k, x in enumerate(i["args"]) if not (i["op"].startswith("v_interp") and "ij" not in i and x["k"] == "vgpr" and k != 0)]) for i in insns] ij_reads = read_before_write_vgprs(with_ij) conditional = branchy or any(writes_exec(i) for i in insns) for r, comp in ((0, "bary_i"), (1, "bary_j")): if (r in ij_reads or conditional) and r not in g.frag_inputs: g.frag_inputs[r] = comp g.cu(r) if any(base_op(i["op"]) in BRANCHES and not i.get("enc") for i in insns): # A branch target is relative to the next PC, which needs the branch's `; encoding:` bytes (missing in a # hand-written listing). Until 2026-11-22 this was a TypeError in next_pc. raise Unsupported("branch without encoding") if not branchy and not g.emulate: g.vm_latch = stage == "ps" and exec_changes_after_vm([insns], [[]]) g.park_masks(([insns], [[]])) halves_analysis(g, [insns], [[]]) meta_extra = {} g.build_meta = _shader_meta.collect(path, info["name"], [insns], [[]], user_sgpr_limit=user_limit, system_sgprs=sys_sgprs, extra=meta_extra) if g.build_meta.get("literal_samplers"): g.literal_samplers = [tuple(w) for w in g.build_meta["literal_samplers"]] g.literal_sampler_index = {w: i for i, w in enumerate(g.literal_samplers)} g.literal_sampler_sites = meta_extra.get("literal_sampler_sites", {}) g.note_pops_word(insns) g.fit_shared_memory() end = next((k for k, ins in enumerate(insns) if base_op(ins["op"]) == "s_endpgm"), len(insns)) g.tsharp_from_heap = descriptor_sources.analyse([insns[:end]], [[]], user_limit, sys_sgprs) g.scalar_load_ro = analyse_scalar_load_ro([insns[:end]], [[]], user_limit, sys_sgprs) g.float_only_images = float_only_image_ops([insns[:end]], [[]]) g.exec_changes = any(g.may_write_exec(ins) for ins in insns[:end]) g.insns(insns[:end]) _translate.last_gen = g return finish_module(g) # ---- basic blocks ---- def next_pc(ins): return ins["pc"] + len(ins["enc"]) // 2 def target(ins): if "target" in ins: return ins["target"] imm = next((x for x in ins["args"] if x["k"] == "imm"), None) if imm is None: raise Unsupported("branch without offset") v = imm["v"] & 0xFFFF return next_pc(ins) + 4 * (v - 0x10000 if v & 0x8000 else v) leaders = {insns[0]["pc"]} for ins in insns: if base_op(ins["op"]) in BRANCHES: leaders.add(target(ins)) leaders.add(next_pc(ins)) pcs = {i["pc"] for i in insns} starts = sorted(p for p in leaders if p in pcs) if any(p not in starts for p in (target(i) for i in insns if base_op(i["op"]) in BRANCHES)): raise Unsupported("branch target outside code") index = {p: n for n, p in enumerate(starts)} blocks = [[] for _ in starts] for n in range(len(blocks) + 1): g.cu(n) # block numbers: %pc is compared with any of them cur = -1 for ins in insns: if ins["pc"] in index: cur = index[ins["pc"]] blocks[cur].append(ins) # Successors ahead of emission, for node splitting and lane-mask analysis (the loop below works them out # again as it goes, and the two are compared at the end). raw_edges = [] for n, blk in enumerate(blocks): last = next((i for i in blk if base_op(i["op"]) == "s_endpgm" or base_op(i["op"]) in BRANCHES), None) fall = [n + 1] if n + 1 < len(blocks) else [] if last is None: raw_edges.append(fall) elif base_op(last["op"]) == "s_endpgm": raw_edges.append([]) elif base_op(last["op"]) == "s_branch": raw_edges.append([index[target(last)]]) else: raw_edges.append([index[target(last)]] + fall) split_edges = None if STRUCTURED: res = cfg_structure.split_irreducible(raw_edges) if res is not None and len(res[0]) > len(blocks): split_edges, orig_of = res # Shallow-copy each instruction dict so lane_masks.py's id(ins) keys stay unique across clones. blocks = [[dict(ins) for ins in blocks[o]] for o in orig_of] for n in range(len(blocks) + 1): g.cu(n) raw_edges = split_edges succ = [list(dict.fromkeys(e)) for e in raw_edges] g.out_pcs = _block_out_pcs(blocks, raw_edges, succ) g.vm_latch = stage == "ps" and exec_changes_after_vm(blocks, succ) # A lane mask that meets data at a merge is turned into the wave's bits on the way there (lane_masks.py). lane_masks.insert_data_merges(blocks, succ, BRANCHES | {"s_endpgm"}, wave64=g.wave64) g.park_masks((blocks, succ)) halves_analysis(g, blocks, succ) meta_extra = {} g.build_meta = _shader_meta.collect(path, info["name"], blocks, succ, user_sgpr_limit=user_limit, system_sgprs=sys_sgprs, extra=meta_extra) if g.build_meta.get("literal_samplers"): g.literal_samplers = [tuple(w) for w in g.build_meta["literal_samplers"]] g.literal_sampler_index = {w: i for i, w in enumerate(g.literal_samplers)} g.literal_sampler_sites = meta_extra.get("literal_sampler_sites", {}) g.note_pops_word(insns) g.bar_rounds = needs_barrier_rounds(g, blocks, succ) g.tsharp_from_heap = descriptor_sources.analyse(blocks, succ, user_limit, sys_sgprs) g.scalar_load_ro = analyse_scalar_load_ro(blocks, succ, user_limit, sys_sgprs) g.float_only_images = float_only_image_ops(blocks, succ) folds, fold_chain, absorbed = {}, {}, set() if g.emulate: g.scc_live = wave64_emulate_opt.scc_live_outs(blocks, succ) # v0 is LocalInvocationId.x (the prologue) and a wave is 64 consecutive threads, so no two lanes of a wave # share v0 when the group is one row of x or a row is a whole number of waves. sx, sy, sz = g.cs["size"] if stage == "cs" else (0, 0, 0) tid = frozenset({0}) if stage == "cs" and (sy * sz == 1 or sx % 64 == 0) else frozenset() folds, fold_chain, absorbed = wave64_emulate_opt.find_local_exec_folds( blocks, raw_edges, succ, g.lane_masks, g.scc_live, g.mask_writes, tid) if STRUCTURED and WAVE64_PLAN: g.emulate_plan = wave64_emulate_opt.plan_structured_emulation( blocks, raw_edges, succ, folds, fold_chain, absorbed, g.lane_masks, g.scc_live, g.x_lanes) g.fit_shared_memory() g.exec_changes = any(g.may_write_exec(ins) for blk in blocks for ins in blk) g.x_seg = len(blocks) + 1 # emulate: continuation segments are numbered after "done" (len(blocks)) def emit_folded_region(fd): """Emit a safe lane-local s_cbranch_execz/nz region inline behind `if (%active)`. Uniform control flow before the branch orders any prior conflicting accesses against reads/writes in the region; inside the region zero x_split or OpControlBarrier calls occur, keeping all 64 lanes synchronized.""" if (any((kind, "w") in g.x_dirty for kind in fd["mem_reads"]) or any((kind, "r") in g.x_dirty or (kind, "w") in g.x_dirty for kind in fd["mem_writes"])): g.x_order_barrier() g.desc_cache.clear() g._active_ssa = None g.sgpr_imm.clear() g.x_tok.clear() g.x_mcache.clear() act = g.active_b() lbl_do, lbl_end = g.tmp(), g.tmp() g.emit(f"OpSelectionMerge {lbl_end} None") g.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") g.emit(f"{lbl_do} = OpLabel") marks_before = len(g.x_marks) body_before = len(g.body) g.x_one_lane = fd["one_lane"] if fd["sub_tree"] is None: for ins in blocks[fd["run"]]: op = base_op(ins["op"]) if op == "s_endpgm" or op in BRANCHES: break g.insn(ins) else: order = fd["order"] idx_of = {u: i for i, u in enumerate(order)} sub_end = len(order) for i in range(sub_end + 1): g.cu(i) g.emit(f"OpStore %pc {g.cu(0)}") stack = [("items", fd["sub_tree"])] while stack: step = stack.pop() if step[0] == "items": for it in reversed(step[1]): stack.append(("item", it)) elif step[0] == "item": it = step[1] if it[0] == "block": u = order[it[1]] blbl = g.tmp() g.emit(f"OpBranch {blbl}") g.emit(f"{blbl} = OpLabel") g.desc_cache.clear() g._active_ssa = None g.sgpr_imm.clear() g.x_tok.clear() g.x_mcache.clear() uterm = None for ins in blocks[u]: op = base_op(ins["op"]) if op == "s_endpgm": uterm = ("end",) break if op in BRANCHES: uterm = ("br", op) break g.insn(ins) uedges = raw_edges[u] if uterm is None or uterm[0] == "end": nxt = idx_of.get(uedges[0], sub_end) if (uterm is None and uedges) else sub_end g.emit(f"OpStore %pc {g.cu(nxt)}") elif uterm[1] == "s_branch": g.emit(f"OpStore %pc {g.cu(idx_of.get(uedges[0], sub_end))}") else: uop = uterm[1] utgt = g.cu(idx_of.get(uedges[0], sub_end)) ufall = g.cu(idx_of.get(uedges[1], sub_end) if len(uedges) > 1 else sub_end) if uop in ("s_cbranch_execz", "s_cbranch_execnz"): uact = g.active_b() if uop == "s_cbranch_execz": ucond = g.tmp() g.emit(f"{ucond} = OpLogicalNot %bool {uact}") else: ucond = uact else: ucond = branch_condition(g, uop) ur = g.tmp() g.emit(f"{ur} = OpSelect %uint {ucond} {utgt} {ufall}") g.emit(f"OpStore %pc {ur}") elif it[0] == "guard": v, c, do, end = g.tmp(), g.tmp(), g.tmp(), g.tmp() g.emit(f"{v} = OpLoad %uint %pc") g.emit(f"{c} = OpIEqual %bool {v} {g.cu(it[1])}") g.emit(f"OpSelectionMerge {end} None") g.emit(f"OpBranchConditional {c} {do} {end}") g.emit(f"{do} = OpLabel") stack.append(("guard_end", end)) stack.append(("items", it[2])) else: head, top, cont, end = g.tmp(), g.tmp(), g.tmp(), g.tmp() g.emit(f"OpBranch {head}") g.emit(f"{head} = OpLabel") g.emit(f"OpLoopMerge {end} {cont} None") g.emit(f"OpBranch {top}") g.emit(f"{top} = OpLabel") stack.append(("loop_end", it[1], head, cont, end)) stack.append(("items", it[2])) elif step[0] == "guard_end": g.emit(f"OpBranch {step[1]}") g.emit(f"{step[1]} = OpLabel") else: _, sub_id, head, cont, end = step v, again = g.tmp(), g.tmp() g.emit(f"OpBranch {cont}") g.emit(f"{cont} = OpLabel") g.emit(f"{v} = OpLoad %uint %pc") g.emit(f"{again} = OpIEqual %bool {v} {g.cu(sub_id)}") g.emit(f"OpBranchConditional {again} {head} {end}") g.emit(f"{end} = OpLabel") g.x_one_lane = False assert len(g.x_marks) == marks_before, "wave64 emulation: x_split inside a folded lane-local region" assert not any("OpControlBarrier" in l for l in g.body[body_before:]), \ "wave64 emulation: OpControlBarrier inside a folded lane-local region" g.emit(f"OpBranch {lbl_end}") g.emit(f"{lbl_end} = OpLabel") for kind in fd["mem_reads"]: g.x_dirty.add((kind, "r")) for kind in fd["mem_writes"]: g.x_dirty.add((kind, "w")) g.desc_cache.clear() g._active_ssa = None g.sgpr_imm.clear() g.x_tok.clear() g.x_mcache.clear() for n, blk in enumerate(blocks): if n in absorbed: g.blocks.append(None) g.succ.append(succ[n]) continue plan = g.emulate_plan g.emulate_inline = bool(plan is not None and n in plan["inline_blocks"]) mini_idx = plan["mini_of_block"].get(n) if plan is not None else None mini_set = plan["mini_blocks"][mini_idx] if mini_idx is not None else None in_tail = bool(plan is not None and n in plan["tail_blocks"]) g.body = [] g.block_label = f"%blk{n}" g.x_marks = [] g.x_dirty = set(plan["dirty_in"].get(n, ())) if g.emulate_inline else set() g.x_tok, g.x_mcache = {}, {} # a register's value is only known from where this block wrote it g.x_gen += 1 g.desc_cache.clear() g._active_ssa = None # a cached lookup is only good inside the block that made it g.sgpr_imm.clear() cur = n while True: term, body = None, blocks[cur] for k, ins in enumerate(blocks[cur]): op = base_op(ins["op"]) if op == "s_endpgm": term, body = ("end",), blocks[cur][:k] break if op in BRANCHES: term, body = ("br", op, index[target(ins)]), blocks[cur][:k] break g.insns(body) if cur in folds: emit_folded_region(folds[cur]) if cur in fold_chain: cur = fold_chain[cur] g.desc_cache.clear() g._active_ssa = None g.sgpr_imm.clear() g.x_tok.clear() g.x_mcache.clear() continue nxt_skip = folds[cur]["skip"] g.emit(f"OpStore %pc {g.cu(nxt_skip)}") if mini_set is not None and nxt_skip not in mini_set: g.emit("OpStore %x_ldone %true") g.succ.append(succ[n]) break edges = raw_edges[cur] fall = (edges[0] if edges else None) if term is None else (edges[1] if len(edges) > 1 else None) # Every block leaves the number of the block to run next in %pc (len(blocks) = none: the program is over), # and its possible successors in g.succ for cfg_structure. if term is None or term[0] == "end": nxt = fall if term is None else None g.emit(f"OpStore %pc {g.cu(nxt if nxt is not None else len(blocks))}") if nxt is None: g.emit("OpStore %done %true") if mini_set is not None and (nxt is None or nxt not in mini_set): g.emit("OpStore %x_ldone %true") g.succ.append(succ[n] if cur != n else ([nxt] if nxt is not None else [])) else: _, op, _ = term tgt = edges[0] if op == "s_branch": g.emit(f"OpStore %pc {g.cu(tgt)}") if mini_set is not None and tgt not in mini_set: g.emit("OpStore %x_ldone %true") g.succ.append(succ[n] if cur != n else [tgt]) else: marks0, body0 = len(g.x_marks), len(g.body) cond = branch_condition(g, op) alt = g.cu(fall) if fall is not None else g.cu(len(blocks)) # past the end = default -> done r = g.tmp() g.emit(f"{r} = OpSelect %uint {cond} {g.cu(tgt)} {alt}") g.emit(f"OpStore %pc {r}") if g.emulate and not g.emulate_inline and op in ( "s_cbranch_vccz", "s_cbranch_vccnz", "s_cbranch_execz", "s_cbranch_execnz"): # This segment only reads the vote and sets %pc, and the code before the vote ran in an earlier # round: the successor can start in this one (x_scheduler). That only holds when the vote's own # x_split started this segment: then it holds the vote read and the %pc select and nothing else. # A vote that reused an earlier exchange (no split) would put the end of the block in the # successor's round, with no barrier between their memory accesses. if len(g.x_marks) != marks0 + 1 or g.x_marks[-1][0] < body0: raise Unsupported("wave64 emulation: a voted branch must start its own segment") g.emit("OpStore %x_chain %true") if mini_set is not None: tgt_in = tgt in mini_set fall_in = fall is not None and fall in mini_set if not tgt_in and not fall_in: g.emit("OpStore %x_ldone %true") elif not tgt_in and fall_in: g.emit(f"OpStore %x_ldone {cond}") elif tgt_in and not fall_in: nc = g.tmp() g.emit(f"{nc} = OpLogicalNot %bool {cond}") g.emit(f"OpStore %x_ldone {nc}") g.succ.append(succ[n] if cur != n else list(dict.fromkeys([tgt] + ([fall] if fall is not None else [])))) break if g.emulate_inline: assert not g.x_marks, "wave64 emulation: unexpected x_split in inline block" if plan is not None and n in plan["sync_free_blocks"]: assert not any("OpControlBarrier" in l for l in g.body), \ "wave64 emulation: unexpected OpControlBarrier in sync-free multi-wave block" lines = [l.strip() for l in g.body] if g.x_marks: cuts = [0] + [i for i, _ in g.x_marks] + [len(lines)] parts = x_spill(g, [lines[a:b] for a, b in zip(cuts, cuts[1:])]) g.blocks.append(parts[0]) for (_, seg), part in zip(g.x_marks, parts[1:]): g.x_segs[seg] = part if mini_idx is not None: g.mini_segs[mini_idx].append(seg) elif in_tail: g.tail_segs.append(seg) else: g.blocks.append(lines) g.emulate_inline = False assert succ == g.succ, "the lane-mask analysis ran on a different graph" g.body = [] _translate.last_gen = g return finish_module(g) _DEF = re.compile(r"(%\w+) = (Op\w+)(?: (%\w+))?") def translate(path): """translate() with one fallback: an emulated wave64 program whose inline structured form puts an exchange barrier under control flow only some invocations take is translated again as the round loop (`Gen.x_scheduler`, one OpControlBarrier per round in uniform control flow). A workgroup barrier has to be reached by every invocation. NVIDIA waits for every thread, so one that an invocation never reaches stands the group until the driver resets the card (Xid 109, device lost). A program that hangs costs a whole run; re-translating it costs one more pass offline. Only a multi-wave plan falls back. A single-wave workgroup (`inline_all`, `x_lanes == 64`) is one wave: its barriers sit at the top level or under `%pc` guards, and `%pc` between blocks comes from scalar state and votes read back from `%x_buf`, so all invocations take the same path; lane-local `%pc` exists only in `emit_folded_region`'s `if (%active)` bodies, which emit no exchange and no barrier. The round loop is also what drives RADV/ACO's spiller to tens of GB and the program 10-100 times slower (docs/design.md, "Wave64 emulation: single-wave barrier fallback").""" global WAVE64_PLAN asm = _translate(path) gen = _translate.last_gen plan = getattr(gen, "emulate_plan", None) if gen is not None else None if (plan is not None and plan.get("mode") != "inline_all" and barriers_under_control_flow(asm)): WAVE64_PLAN = False try: asm = _translate(path) finally: WAVE64_PLAN = True translate.last_gen = _translate.last_gen return asm def finish_module(g): text = assemble(g) if OPT_SPIRV: import spirv_opt text = spirv_opt.optimize(text) return spirv_loop_guard.add_guards(text, LOOP_LIMIT) def _block_out_pcs(blocks, raw_edges, succ): """Possible `%pc` values each basic block can store (`cfg_structure.END` when the block can end the shader). A conditional branch with no fallthrough block (`len(raw_edges[b]) == 1`, i.e. the last block or a split clone of it) emits `OpSelect %uint cond tgt len(blocks)` and therefore writes either `tgt` or `END`.""" out_pcs = {} for b, blk in enumerate(blocks): pcs = set(succ[b]) if not pcs: pcs.add(cfg_structure.END) elif len(raw_edges[b]) == 1: last = next((i for i in blk if base_op(i["op"]) == "s_endpgm" or base_op(i["op"]) in BRANCHES), None) if last is not None and base_op(last["op"]) in BRANCHES and base_op(last["op"]) != "s_branch": pcs.add(cfg_structure.END) out_pcs[b] = frozenset(pcs) return out_pcs def capped_tree(succ, out_pcs=None): """(tree, nesting): the structured tree for `succ` and its depth, or (None, None) under --dispatch-loop or when cfg_structure can't structure it; tree is None (nesting still the measured depth) when it nests deeper than MAX_STRUCTURED_DEPTH. assemble() emits exactly this tree, and needs_barrier_rounds() decides from the same one (SHADER-427 review): a barrier in a tree that falls back to the dispatch loop isn't at a structured top level.""" if out_pcs is None: out_pcs = {b: (set(succ[b]) if succ[b] else {cfg_structure.END}) for b in range(len(succ))} tree = cfg_structure.structure(succ, out_pcs=out_pcs) if STRUCTURED else None if tree is None: return None, None tree = cfg_structure.unwrap_known_pc_guards(tree, out_pcs) nesting = cfg_structure.depth(tree) if MAX_STRUCTURED_DEPTH and nesting > MAX_STRUCTURED_DEPTH: return None, nesting # too deep to validate cheaply: use the flat form return tree, nesting def needs_barrier_rounds(g, blocks, succ): """SHADER-91: whether a native wave32 compute shader has to run in barrier rounds (bar_scheduler). On RDNA every s_barrier counts against the same workgroup barrier, so waves on different paths meet at different s_barrier sites. SPIR-V requires an OpControlBarrier to be reached by the whole workgroup in uniform control flow, and an Intel GPU hangs (device lost) when it isn't (cs_barrier_divergent.asm). A barrier is only certain to be uniform in a block at the top level of the structured tree, which every invocation runs; one under a guard or in a loop, or anywhere in the dispatch loop, may be reached by some waves and not others.""" if g.stage != "cs" or g.emulate or g.wave64: return False # emulated: already rounds; native wave64 cs and ms run on AMD only with_barrier = set() for n, blk in enumerate(blocks): for ins in blk: op = base_op(ins["op"]) if op == "s_endpgm" or op in BRANCHES: break if op == "s_barrier": with_barrier.add(n) break if not with_barrier: return False tree, _ = capped_tree(succ, g.out_pcs) # the tree assemble() emits: over MAX_STRUCTURED_DEPTH it's the dispatch loop top = {it[1] for it in tree if it[0] == "block"} if tree is not None else set() return not with_barrier <= top def interp_copy_sources(insns): """SHADER-177: the VGPRs a v_interp may name as its I/J barycentric source besides v0/v1, as {vgpr: (root coordinate v0/v1 the copy chain carries, program-order index of the defining instruction)}. A register qualifies when its single write in the whole shader is one plain v_mov_b32 from v0/v1 — which must itself be unwritten up to that point: a copy of an already-overwritten v0/v1 carries a computed value, not the pair, while a write after the copy is fine (the copy saved the value) — or from another qualifying register defined earlier (compilers copy the pair out of v0/v1; the corpus has one shader that reads its J through such a copy). One definition means every read that is not undefined garbage reads the copied barycentric value, whatever the control flow. Every VGPR destination counts as a write (memory stores only read their data operand; tfe's extra status VGPR is one too).""" writes = {} for i, ins in enumerate(insns): ins["seq"] = i # program order: also unique without encoding comments (test fixtures share a pc) a = ins["args"] if not (a and a[0].get("k") == "vgpr") or base_op(ins["op"]).startswith( ("buffer_store", "tbuffer_store", "scratch_store", "global_store", "flat_store", "image_store", "ds_write")): continue for r in vgpr_dest_registers(ins, extra=int("tfe" in ins["mods"])): writes.setdefault(r, []).append(ins) copies = {} grew = True while grew: # copy chains resolve over passes: v15 = v14 after v14 = v1 grew = False for r, ws in writes.items(): if r in copies or len(ws) != 1: continue ins = ws[0] a = ins["args"] s = a[1] if len(a) > 1 else None plain = (base_op(ins["op"]) == "v_mov_b32" and not ins["mods"] and a[0].get("n", 1) == 1 and not a[0].get("sdwa_dst") and s is not None and s.get("k") == "vgpr" and s.get("n", 1) == 1 and not s.get("neg") and not s.get("abs") and not s.get("sdwa_sel")) if plain and ((s["r"] in (0, 1) and not any(w["seq"] < ins["seq"] for w in writes.get(s["r"], ()))) or (s["r"] in copies and copies[s["r"]][1] < ins["seq"])): copies[r] = (s["r"] if s["r"] in (0, 1) else copies[s["r"]][0], ins["seq"]) grew = True return copies def x_spill(g, parts): """Emulated wave64 and barrier rounds: the segments of one block run in different rounds, i.e. in different cases of the scheduler's switch and different loop iterations, so an SSA value defined in one and used in a later one can't be referenced directly. It goes through a Function variable: stored at the end of the segment that defines it and loaded, under a new id, at the top of each later segment that uses it.""" defs, out = {}, [] for k, part in enumerate(parts): used = [] for line in part: for ref in _ID_REF.findall(line): if ref in defs and ref not in used: used.append(ref) loads, rename = [], {} for ref in used: seg, typ, var = defs[ref] if var is None: if typ is None or typ.startswith("%_ptr"): mode = "barrier rounds" if g.bar_rounds else "wave64 emulation" raise Unsupported(f"{mode}: a pointer lives across a round") ptr = {"%uint": "%_ptr_Function_uint", "%bool": "%_ptr_Function_bool"}.get(typ) if ptr is None: ptr = g.x_ptr_types.setdefault(typ, f"%_ptr_Function_x_{typ[1:]}") var = f"%xs_{ref[1:]}" g.x_spills.append((var, ptr)) out[seg].append(f"OpStore {var} {ref}") defs[ref] = (seg, typ, var) new = f"{ref}_r{k}" loads.append(f"{new} = OpLoad {typ} {var}") rename[ref] = new body = [_ID_REF.sub(lambda t: rename.get(t.group(0), t.group(0)), l) for l in part] if rename else list(part) out.append(loads + body) for line in part: m = _DEF.match(line) if m and m.group(2) != "OpLabel": defs[m.group(1)] = (k, m.group(3), None) return out def x_prologue(gen, threads): """Emulated wave64 prologue: %pc/%done declarations, invocation/lane/wave indices, and %x_buf zeroing + barrier. Shared by x_scheduler (round loop) and structured wave64 emulation (inline_all / structured_hybrid).""" c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 _, x_mask, _, x_sink = gen.x_sizes() sx, sy, _ = (gen.cs or gen.ms)["size"] L = ["%pc = OpVariable %_ptr_Function_uint Function %c0", "%done = OpVariable %_ptr_Function_bool Function %false"] # This invocation's place: index in the workgroup, lane and wave (the same split as Gen.wave_lane). if gen.stage == "ms": # --mesh-serial-waves: the exchange is one wave's, so its place in %x_buf comes from the invocation's own index # (0-63), not from the workgroup index of the lane it runs in this pass (ms_serial_passes). L += ["%x_li = OpLoad %uint " + ("%real_local_index" if gen.ms_serial else "%local_index")] else: L += ["%x_lid = OpLoad %v3uint " + ("%real_local_id" if gen.cs_serial else "%local_id"), "%x_lx = OpCompositeExtract %uint %x_lid 0", "%x_ly = OpCompositeExtract %uint %x_lid 1", "%x_lz = OpCompositeExtract %uint %x_lid 2", f"%x_ly2 = OpIMul %uint %x_ly {c(sx)}", f"%x_lz2 = OpIMul %uint %x_lz {c(sx * sy)}", "%x_lxy = OpIAdd %uint %x_lx %x_ly2", "%x_li = OpIAdd %uint %x_lxy %x_lz2"] L += [f"%x_lane = OpBitwiseAnd %uint %x_li {c(63)}", f"%x_wave = OpShiftRightLogical %uint %x_li {c(6)}", f"%x_wbase = OpBitwiseAnd %uint %x_li {c(0xFFFFFFC0)}"] # Workgroup memory starts undefined: zero the mask and schedule words, every invocation a share of them. zero = x_sink - x_mask for k in range(-(-zero // threads)): L += [f"%x_z{k} = OpIAdd %uint %x_li {c(k * threads)}", f"%x_zm{k} = OpExtInst %uint %glsl UMin %x_z{k} {c(zero - 1)}", f"%x_zi{k} = OpIAdd %uint %x_zm{k} {c(x_mask)}", f"%x_zp{k} = OpAccessChain %_ptr_WG_uint_x %x_buf %x_zi{k}", f"OpAtomicStore %x_zp{k} {c(2)} {c(0)} {c(0)}"] # A partial last wave: its missing lanes never write their data slots. They read as 0, as a lane that is # off does for ds_bpermute (and v_readlane of a lane that doesn't exist has no defined value anyway). missing = gen.x_lanes - threads for k in range(-(-missing // threads) if missing else 0): for par, base in ((0, threads), (1, gen.x_lanes + threads)): L += [f"%x_y{k}_{par} = OpIAdd %uint %x_li {c(k * threads)}", f"%x_ym{k}_{par} = OpExtInst %uint %glsl UMin %x_y{k}_{par} {c(missing - 1)}", f"%x_yi{k}_{par} = OpIAdd %uint %x_ym{k}_{par} {c(base)}", f"%x_yp{k}_{par} = OpAccessChain %_ptr_WG_uint_x %x_buf %x_yi{k}_{par}", f"OpAtomicStore %x_yp{k}_{par} {c(2)} {c(0)} {c(0)}"] L.append(f"OpControlBarrier {c(2)} {c(2)} {c(0x948)}") return L def x_round_loop_head(gen, seg_ids): """Emulated wave64 round loop head switching over `seg_ids` (shared by x_scheduler and tail_scheduler).""" c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 x_waves, x_mask, x_sched, x_sink = gen.x_sizes() return ["OpBranch %loop_head", "%loop_head = OpLabel", "OpLoopMerge %loop_exit %loop_cont None", "OpBranch %x_round", "%x_round = OpLabel", "%x_itv = OpLoad %uint %x_it", f"%x_s = OpUMod %uint %x_itv {c(3)}", # Free the slot of round + 1 for its writers. Its readers ran before the last barrier (round - 2 wrote # it, round - 1 read it); its writers come after the next one. Lane 0 of each wave clears the wave's # mask words, invocation 0 the counts; the others store to the sink word. f"%x_n1 = OpIAdd %uint %x_itv {c(1)}", f"%x_sn = OpUMod %uint %x_n1 {c(3)}", f"%x_m0 = OpIMul %uint %x_sn {c(x_waves)}", "%x_m1 = OpIAdd %uint %x_m0 %x_wave", f"%x_m2 = OpIMul %uint %x_m1 {c(2)}", f"%x_m3 = OpIAdd %uint %x_m2 {c(x_mask)}", f"%x_m4 = OpIAdd %uint %x_m3 {c(1)}", f"%x_ml = OpIEqual %bool %x_lane {c(0)}", f"%x_m5 = OpSelect %uint %x_ml %x_m3 {c(x_sink)}", f"%x_m6 = OpSelect %uint %x_ml %x_m4 {c(x_sink)}", "%x_mp5 = OpAccessChain %_ptr_WG_uint_x %x_buf %x_m5", f"OpAtomicStore %x_mp5 {c(2)} {c(0)} {c(0)}", "%x_mp6 = OpAccessChain %_ptr_WG_uint_x %x_buf %x_m6", f"OpAtomicStore %x_mp6 {c(2)} {c(0)} {c(0)}", f"%x_q0 = OpIMul %uint %x_sn {c(2)}", f"%x_q1 = OpIAdd %uint %x_q0 {c(x_sched)}", f"%x_q2 = OpIAdd %uint %x_q1 {c(1)}", f"%x_ql = OpIEqual %bool %x_li {c(0)}", f"%x_q3 = OpSelect %uint %x_ql %x_q1 {c(x_sink)}", f"%x_q4 = OpSelect %uint %x_ql %x_q2 {c(x_sink)}", "%x_qp3 = OpAccessChain %_ptr_WG_uint_x %x_buf %x_q3", f"OpAtomicStore %x_qp3 {c(2)} {c(0)} {c(0)}", "%x_qp4 = OpAccessChain %_ptr_WG_uint_x %x_buf %x_q4", f"OpAtomicStore %x_qp4 {c(2)} {c(0)} {c(0)}", "%x_d = OpLoad %bool %done", "%x_b = OpLoad %bool %x_bar", "%x_nd = OpLogicalNot %bool %x_d", "%x_nb = OpLogicalNot %bool %x_b", "%x_run = OpLogicalAnd %bool %x_nd %x_nb", "OpSelectionMerge %x_ran None", "OpBranchConditional %x_run %dispatch %x_ran", # A segment that only reads a vote and picks the next block sets %x_chain: that block runs in the same # round (its code before the vote was in an earlier one, and it starts a fresh segment). "%dispatch = OpLabel", "OpBranch %x_ch_head", "%x_ch_head = OpLabel", "OpLoopMerge %x_ch_merge %x_ch_cont None", "OpBranch %x_ch_body", "%x_ch_body = OpLabel", "%pcv = OpLoad %uint %pc", "OpSelectionMerge %sw_merge None", "OpSwitch %pcv %sw_default " + " ".join(f"{i} %blk{i}" for i in seg_ids)] def x_mini_scheduler(gen, midx, seg_ids): """Local multi-wave round loop covering only one wave-divergent region `seg_ids` (no s_barrier / s_endpgm).""" c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 x_waves, x_mask, x_sched, x_sink = gen.x_sizes() p = f"%xm{midx}" return ["OpStore %x_ldone %false", f"OpBranch {p}_head", f"{p}_head = OpLabel", f"OpLoopMerge {p}_exit {p}_cont None", f"OpBranch {p}_round", f"{p}_round = OpLabel", f"{p}_itv = OpLoad %uint %x_it", f"{p}_s = OpUMod %uint {p}_itv {c(3)}", f"{p}_n1 = OpIAdd %uint {p}_itv {c(1)}", f"{p}_sn = OpUMod %uint {p}_n1 {c(3)}", f"{p}_m0 = OpIMul %uint {p}_sn {c(x_waves)}", f"{p}_m1 = OpIAdd %uint {p}_m0 %x_wave", f"{p}_m2 = OpIMul %uint {p}_m1 {c(2)}", f"{p}_m3 = OpIAdd %uint {p}_m2 {c(x_mask)}", f"{p}_m4 = OpIAdd %uint {p}_m3 {c(1)}", f"{p}_ml = OpIEqual %bool %x_lane {c(0)}", f"{p}_m5 = OpSelect %uint {p}_ml {p}_m3 {c(x_sink)}", f"{p}_m6 = OpSelect %uint {p}_ml {p}_m4 {c(x_sink)}", f"{p}_mp5 = OpAccessChain %_ptr_WG_uint_x %x_buf {p}_m5", f"OpAtomicStore {p}_mp5 {c(2)} {c(0)} {c(0)}", f"{p}_mp6 = OpAccessChain %_ptr_WG_uint_x %x_buf {p}_m6", f"OpAtomicStore {p}_mp6 {c(2)} {c(0)} {c(0)}", f"{p}_q0 = OpIMul %uint {p}_sn {c(2)}", f"{p}_q1 = OpIAdd %uint {p}_q0 {c(x_sched)}", f"{p}_q2 = OpIAdd %uint {p}_q1 {c(1)}", f"{p}_ql = OpIEqual %bool %x_li {c(0)}", f"{p}_q3 = OpSelect %uint {p}_ql {p}_q1 {c(x_sink)}", f"{p}_q4 = OpSelect %uint {p}_ql {p}_q2 {c(x_sink)}", f"{p}_qp3 = OpAccessChain %_ptr_WG_uint_x %x_buf {p}_q3", f"OpAtomicStore {p}_qp3 {c(2)} {c(0)} {c(0)}", f"{p}_qp4 = OpAccessChain %_ptr_WG_uint_x %x_buf {p}_q4", f"OpAtomicStore {p}_qp4 {c(2)} {c(0)} {c(0)}", f"{p}_d = OpLoad %bool %x_ldone", f"{p}_run = OpLogicalNot %bool {p}_d", f"OpSelectionMerge {p}_ran None", f"OpBranchConditional {p}_run {p}_dispatch {p}_ran", f"{p}_dispatch = OpLabel", f"OpBranch {p}_ch_head", f"{p}_ch_head = OpLabel", f"OpLoopMerge {p}_ch_merge {p}_ch_cont None", f"OpBranch {p}_ch_body", f"{p}_ch_body = OpLabel", f"{p}_pcv = OpLoad %uint %pc", f"OpSelectionMerge {p}_sw_merge None", f"OpSwitch {p}_pcv {p}_default " + " ".join(f"{i} %blk{i}" for i in seg_ids)] def x_mini_scheduler_tail(gen, midx): """End of a local multi-wave mini-scheduler round: exits when every wave has left the region.""" c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 _, _, x_sched, _ = gen.x_sizes() p = f"%xm{midx}" return [f"{p}_default = OpLabel", "OpStore %x_ldone %true", f"OpBranch {p}_sw_merge", f"{p}_sw_merge = OpLabel", f"OpBranch {p}_ch_cont", f"{p}_ch_cont = OpLabel", f"{p}_chv = OpLoad %bool %x_chain", "OpStore %x_chain %false", f"OpBranchConditional {p}_chv {p}_ch_head {p}_ch_merge", f"{p}_ch_merge = OpLabel", f"OpBranch {p}_ran", f"{p}_ran = OpLabel", f"{p}_d2 = OpLoad %bool %x_ldone", f"{p}_nd2 = OpLogicalNot %bool {p}_d2", f"{p}_c0 = OpSelect %uint {p}_nd2 {c(1)} {c(0)}", f"{p}_s0 = OpIMul %uint {p}_s {c(2)}", f"{p}_s1 = OpIAdd %uint {p}_s0 {c(x_sched)}", f"{p}_p0 = OpAccessChain %_ptr_WG_uint_x %x_buf {p}_s1", f"{p}_a0 = OpAtomicIAdd %uint {p}_p0 {c(2)} {c(0)} {p}_c0", f"OpBranch {p}_cont", f"{p}_cont = OpLabel", f"OpControlBarrier {c(2)} {c(2)} {c(0x948)}", f"{p}_r0 = OpLoad %uint {p}_p0", f"{p}_it1 = OpIAdd %uint {p}_itv {c(1)}", f"OpStore %x_it {p}_it1", f"{p}_fin = OpIEqual %bool {p}_r0 {c(0)}", f"OpBranchConditional {p}_fin {p}_exit {p}_head", f"{p}_exit = OpLabel"] def x_scheduler(gen, threads): """Emulated wave64: the head of the round loop (see Gen.x_round), up to the switch over %pc. The first two lines are the Function variables %pc and %done, as for the dispatch loop. Every invocation runs every round, so the loop and the barrier at its end are in uniform control flow. In a round an invocation runs one segment unless it is done or waits at s_barrier. After the segment it adds itself to the round's counts (not done; neither done nor waiting); after the barrier everyone reads the same counts: no lane left ends the loop, and no lane left that isn't waiting releases the s_barrier.""" seg_ids = sorted([i for i, b in enumerate(gen.blocks) if b is not None] + list(gen.x_segs)) return x_prologue(gen, threads) + x_round_loop_head(gen, seg_ids) def x_scheduler_tail(gen): """Emulated wave64: the end of a round, after the switch (see x_scheduler).""" c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 _, _, x_sched, _ = gen.x_sizes() return ["%sw_default = OpLabel", "OpStore %done %true", "OpBranch %sw_merge", "%sw_merge = OpLabel", "OpBranch %x_ch_cont", "%x_ch_cont = OpLabel", "%x_chv = OpLoad %bool %x_chain", "OpStore %x_chain %false", "OpBranchConditional %x_chv %x_ch_head %x_ch_merge", "%x_ch_merge = OpLabel", "OpBranch %x_ran", "%x_ran = OpLabel", "%x_d2 = OpLoad %bool %done", "%x_b2 = OpLoad %bool %x_bar", "%x_nd2 = OpLogicalNot %bool %x_d2", "%x_nb2 = OpLogicalNot %bool %x_b2", "%x_w = OpLogicalAnd %bool %x_nd2 %x_nb2", f"%x_c0 = OpSelect %uint %x_nd2 {c(1)} {c(0)}", f"%x_c1 = OpSelect %uint %x_w {c(1)} {c(0)}", f"%x_s0 = OpIMul %uint %x_s {c(2)}", f"%x_s1 = OpIAdd %uint %x_s0 {c(x_sched)}", f"%x_s2 = OpIAdd %uint %x_s1 {c(1)}", "%x_p0 = OpAccessChain %_ptr_WG_uint_x %x_buf %x_s1", "%x_p1 = OpAccessChain %_ptr_WG_uint_x %x_buf %x_s2", f"%x_a0 = OpAtomicIAdd %uint %x_p0 {c(2)} {c(0)} %x_c0", f"%x_a1 = OpAtomicIAdd %uint %x_p1 {c(2)} {c(0)} %x_c1", "OpBranch %loop_cont", "%loop_cont = OpLabel", # Workgroup, acquire-release, workgroup + uniform + image memory: also orders the stores a round made. f"OpControlBarrier {c(2)} {c(2)} {c(0x948)}", "%x_r0 = OpLoad %uint %x_p0", "%x_r1 = OpLoad %uint %x_p1", f"%x_rel = OpIEqual %bool %x_r1 {c(0)}", "%x_b3 = OpLoad %bool %x_bar", "%x_nrel = OpLogicalNot %bool %x_rel", "%x_b4 = OpLogicalAnd %bool %x_b3 %x_nrel", "OpStore %x_bar %x_b4", f"%x_it1 = OpIAdd %uint %x_itv {c(1)}", "OpStore %x_it %x_it1", f"%x_fin = OpIEqual %bool %x_r0 {c(0)}", "OpBranchConditional %x_fin %loop_exit %loop_head", "%loop_exit = OpLabel"] def bar_scheduler(gen): """Barrier rounds (SHADER-91): a native wave32 compute shader whose s_barrier isn't in uniform control flow (needs_barrier_rounds). The emulated wave64 loop without its cross-lane part: s_barrier ends a segment, and the code after it is a continuation segment (x_split). In a round each invocation that isn't done runs its blocks, through the switch over %pc, until it reaches an s_barrier or the end; then the whole workgroup meets at one OpControlBarrier, at the end of the round loop, in uniform control flow. After the inner loop every invocation is done or waits, so the barrier always releases the waiting ones, and a wave that has ended doesn't hold the others back (RDNA's rule). Cross-lane operations stay subgroup operations: a wave runs one segment at a time, as in the dispatch loop. The round's count of invocations not done ends the loop at 0. %x_buf holds 3 counts, by round mod 3: round r adds to its own slot before the barrier and reads it after, and invocation 0 clears the slot of round r + 1, last read in round r - 2 (before the barrier of r - 1). With a large LDS (bar_counts_in_lds, SHADER-579) there is no %x_buf: the count borrows LDS word 0 between rounds, when no invocation runs shader code (see bar_scheduler_tail), and starts cleared in every round. The first two lines are the Function variables %pc and %done, as for the dispatch loop.""" c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 sx, sy, _ = gen.cs["size"] in_lds = gen.bar_counts_in_lds() bar_sem = 0x6948 if gen.uses_vmm else 0x948 return ["%pc = OpVariable %_ptr_Function_uint Function %c0", "%done = OpVariable %_ptr_Function_bool Function %false", "%xb_lid = OpLoad %v3uint %local_id", "%xb_lx = OpCompositeExtract %uint %xb_lid 0", "%xb_ly = OpCompositeExtract %uint %xb_lid 1", "%xb_lz = OpCompositeExtract %uint %xb_lid 2", f"%xb_ly2 = OpIMul %uint %xb_ly {c(sx)}", f"%xb_lz2 = OpIMul %uint %xb_lz {c(sx * sy)}", "%xb_lxy = OpIAdd %uint %xb_lx %xb_ly2", "%xb_li = OpIAdd %uint %xb_lxy %xb_lz2", f"%xb_first = OpIEqual %bool %xb_li {c(0)}"] + ([] if in_lds else [ # Workgroup memory starts undefined: invocation 0 clears round 0's count before the first round. "OpSelectionMerge %xb_z_end None", "OpBranchConditional %xb_first %xb_z %xb_z_end", "%xb_z = OpLabel", f"%xb_zp = OpAccessChain %_ptr_WG_uint_x %x_buf {c(0)}", f"OpStore %xb_zp {c(0)}", "OpBranch %xb_z_end", "%xb_z_end = OpLabel", f"OpControlBarrier {c(2)} {c(2)} {c(bar_sem)}"]) + [ "OpBranch %loop_head", "%loop_head = OpLabel", "OpLoopMerge %loop_exit %loop_cont None", "OpBranch %xb_round", "%xb_round = OpLabel", "%xb_itv = OpLoad %uint %x_it"] + ([] if in_lds else [ f"%xb_s = OpUMod %uint %xb_itv {c(3)}", f"%xb_n1 = OpIAdd %uint %xb_itv {c(1)}", f"%xb_sn = OpUMod %uint %xb_n1 {c(3)}", "OpSelectionMerge %xb_r_end None", "OpBranchConditional %xb_first %xb_r %xb_r_end", "%xb_r = OpLabel", "%xb_rp = OpAccessChain %_ptr_WG_uint_x %x_buf %xb_sn", f"OpStore %xb_rp {c(0)}", "OpBranch %xb_r_end", "%xb_r_end = OpLabel"]) + [ "%xb_d = OpLoad %bool %done", "OpSelectionMerge %xb_ran None", "OpBranchConditional %xb_d %xb_ran %xb_run", "%xb_run = OpLabel", # The invocation's blocks, until an s_barrier (%x_bar) or the end (%done). "OpBranch %xb_in_head", "%xb_in_head = OpLabel", "OpLoopMerge %xb_in_merge %xb_in_cont None", "OpBranch %dispatch", "%dispatch = OpLabel", "%pcv = OpLoad %uint %pc", "OpSelectionMerge %sw_merge None", "OpSwitch %pcv %sw_default " + " ".join(f"{i} %blk{i}" for i in sorted(list(range(len(gen.blocks))) + list(gen.x_segs)))] def bar_scheduler_tail(gen): """Barrier rounds: the end of a round, after the switch (see bar_scheduler). SHADER-579, the count in LDS (bar_counts_in_lds): after s_barrier's own barrier (A) every invocation is done or waits, so no shader code touches LDS until the next round. Invocation 0 saves LDS word 0 in a Function variable and clears it; barrier B; every invocation not done adds 1; barrier C; all read the count; barrier D; invocation 0 puts the saved word back; barrier E, before the next round's code. The shader sees its LDS unchanged, and B to E only add workgroup barriers at a point where the whole workgroup already waits.""" c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 bar_sem = 0x6948 if gen.uses_vmm else 0x948 bar = f"OpControlBarrier {c(2)} {c(2)} {c(bar_sem)}" head = ["%sw_default = OpLabel", "OpStore %done %true", "OpBranch %sw_merge", "%sw_merge = OpLabel", "OpBranch %xb_in_cont", "%xb_in_cont = OpLabel", "%xb_d1 = OpLoad %bool %done", "%xb_b1 = OpLoad %bool %x_bar", "%xb_stop = OpLogicalOr %bool %xb_d1 %xb_b1", "OpBranchConditional %xb_stop %xb_in_merge %xb_in_head", "%xb_in_merge = OpLabel"] if gen.bar_counts_in_lds(): return head + [ "OpBranch %xb_ran", "%xb_ran = OpLabel", bar, # A: s_barrier's own barrier f"%xb_wp = OpAccessChain %_ptr_WG_uint %lds {c(0)}", "OpSelectionMerge %xb_sv_end None", "OpBranchConditional %xb_first %xb_sv %xb_sv_end", "%xb_sv = OpLabel", "%xb_old = OpLoad %uint %xb_wp", "OpStore %xb_save %xb_old", f"OpStore %xb_wp {c(0)}", "OpBranch %xb_sv_end", "%xb_sv_end = OpLabel", bar, # B: the word is cleared "%xb_d2 = OpLoad %bool %done", "OpSelectionMerge %xb_c_end None", "OpBranchConditional %xb_d2 %xb_c_end %xb_c", "%xb_c = OpLabel", f"%xb_ca = OpAtomicIAdd %uint %xb_wp {c(2)} {c(0)} {c(1)}", "OpBranch %xb_c_end", "%xb_c_end = OpLabel", bar, # C: every count is in "%xb_left = OpLoad %uint %xb_wp", bar, # D: every invocation has read it "OpSelectionMerge %xb_rs_end None", "OpBranchConditional %xb_first %xb_rs %xb_rs_end", "%xb_rs = OpLabel", "%xb_old2 = OpLoad %uint %xb_save", "OpStore %xb_wp %xb_old2", "OpBranch %xb_rs_end", "%xb_rs_end = OpLabel", "OpBranch %loop_cont", "%loop_cont = OpLabel", bar, # E: the shader's word is back "OpStore %x_bar %false", f"%xb_it1 = OpIAdd %uint %xb_itv {c(1)}", "OpStore %x_it %xb_it1", f"%xb_fin = OpIEqual %bool %xb_left {c(0)}", "OpBranchConditional %xb_fin %loop_exit %loop_head", "%loop_exit = OpLabel"] return head + [ # Not done: count this invocation in the round's slot. "%xb_d2 = OpLoad %bool %done", "OpSelectionMerge %xb_c_end None", "OpBranchConditional %xb_d2 %xb_c_end %xb_c", "%xb_c = OpLabel", "%xb_cp = OpAccessChain %_ptr_WG_uint_x %x_buf %xb_s", f"%xb_ca = OpAtomicIAdd %uint %xb_cp {c(2)} {c(0)} {c(1)}", "OpBranch %xb_c_end", "%xb_c_end = OpLabel", "OpBranch %xb_ran", "%xb_ran = OpLabel", "OpBranch %loop_cont", "%loop_cont = OpLabel", # s_barrier's own barrier (workgroup, acquire-release, uniform/workgroup/image memory), now in uniform # control flow; it also orders the count, read below. bar, "%xb_lp = OpAccessChain %_ptr_WG_uint_x %x_buf %xb_s", "%xb_left = OpLoad %uint %xb_lp", "OpStore %x_bar %false", f"%xb_it1 = OpIAdd %uint %xb_itv {c(1)}", "OpStore %x_it %xb_it1", f"%xb_fin = OpIEqual %bool %xb_left {c(0)}", "OpBranchConditional %xb_fin %loop_exit %loop_head", "%loop_exit = OpLabel"] BRANCHES = {"s_branch", "s_cbranch_scc0", "s_cbranch_scc1", "s_cbranch_vccz", "s_cbranch_vccnz", "s_cbranch_execz", "s_cbranch_execnz"} def branch_condition(g, op): """Boolean SPIR-V id: whether the branch is taken for this lane.""" if op in ("s_cbranch_scc0", "s_cbranch_scc1"): s = g.tmp() g.emit(f"{s} = OpLoad %uint %scc") b = g.tmp() g.emit(f"{b} = {'OpIEqual' if op.endswith('0') else 'OpINotEqual'} %bool {s} {g.cu(0)}") return b # VCC and EXEC are wave-wide registers: the hardware branch is taken (or not) by the whole wave. With one # invocation per lane, each lane holds only its own bit, so the condition is reduced across the subgroup # (= the wave). Deciding per lane would let lanes skip scalar instructions the wave executes, leaving their # SGPRs stale, and would break cross-lane ops and barriers inside the block. if op in ("s_cbranch_vccz", "s_cbranch_vccnz"): s = g.tmp() g.emit(f"{s} = OpLoad %uint %vcc") lane = g.tmp() g.emit(f"{lane} = OpINotEqual %bool {s} {g.cu(0)}") if g.wave64 and "vcc" not in g.cur_masks: # VCC holds data, not a lane mask: VCCZ/VCCNZ test all 64 bits, so the high word matters too. # Each invocation holds the same data word, and the subgroup vote below reduces the bool once. # A VCC certified as a lane mask keeps one bit per lane in %vcc; %vcc_hi is not the other half # of the vote there, because that vote already covers both halves of the wave. hi = g.tmp() g.emit(f"{hi} = OpLoad %uint %vcc_hi") hi_nz = g.tmp() g.emit(f"{hi_nz} = OpINotEqual %bool {hi} {g.cu(0)}") both = g.tmp() g.emit(f"{both} = OpLogicalOr %bool {lane} {hi_nz}") lane = both else: lane = g.active_b() any_ = g.tmp() g.g_vote(any_, "Any", lane) g.uses_vote = True if op in ("s_cbranch_vccnz", "s_cbranch_execnz"): return any_ b = g.tmp() g.emit(f"{b} = OpLogicalNot %bool {any_}") return b def _sha256_file(path): """Hex SHA-256 of a file, or None when the path is missing (fssm sidecars are optional).""" try: h = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(1 << 20), b""): h.update(chunk) return h.hexdigest() except OSError: return None def shader_meta(g, asm, src_path=None, fssm_path=None): """What a runtime needs to create the pipeline for this module without inspecting it: stage, wave size, Vulkan features/extensions it requires, descriptor bindings (set 0), push-constant size, workgroup size, LDS bytes, mesh/geometry limits, the input/output locations, plus identity metadata (src/fssm hashes and the full ISG1 vertex-input signature) for PSO lookup and corpus auditing.""" caps = sorted(set(re.findall(r"OpCapability (\w+)", asm))) exts = sorted(set(re.findall(r'OpExtension "([^"]+)"', asm))) # Set 0 only: --pc-tail-ubo's %pc_tail is in set 1 and recorded as "pc_tail". binds = sorted({int(b) for b in re.findall(r"OpDecorate %(?!pc_tail\b)\w+ Binding (\d+)", asm)}) feats = {"FragmentBarycentricKHR": "fragmentShaderBarycentric", "FragmentShaderPixelInterlockEXT": "fragmentShaderPixelInterlock", "MeshShadingEXT": "meshShader", "Geometry": "geometryShader", "Float64": "shaderFloat64", "Int64": "shaderInt64", "StorageImageWriteWithoutFormat": "shaderStorageImageWriteWithoutFormat", "StorageImageReadWithoutFormat": "shaderStorageImageReadWithoutFormat", "PhysicalStorageBufferAddresses": "bufferDeviceAddress", "RuntimeDescriptorArray": "runtimeDescriptorArray", "ImageGatherExtended": "shaderImageGatherExtended", "SampledImageArrayDynamicIndexing": "shaderSampledImageArrayDynamicIndexing", "StorageImageArrayDynamicIndexing": "shaderStorageImageArrayDynamicIndexing", "MinLod": "shaderResourceMinLod", "Image1D": "shaderImage1D? (core)", "Sampled1D": "core", "ClipDistance": "shaderClipDistance", "CullDistance": "shaderCullDistance", "ShaderLayer": "shaderOutputLayer", "ShaderViewportIndex": "shaderOutputViewportIndex", "DrawParameters": "shaderDrawParameters", "DotProductKHR": "shaderIntegerDotProduct", "VulkanMemoryModel": "vulkanMemoryModel", "VulkanMemoryModelDeviceScope": "vulkanMemoryModelDeviceScope", "Int64ImageEXT": "shaderImageInt64Atomics", } # FMAKHR: shaderFmaFloat32 / shaderFmaFloat64 (VK_KHR_shader_fma) by the width used, below m = {"stage": g.stage, "wave64": bool(g.wave64), "control_flow": getattr(g, "control_flow", "straight line"), # How fused multiply-adds were emitted. --fma khr is already implied by the FMAKHR capability, # but --fma exact has no capability to distinguish it from the default GLSL Fma (TEST-1147). "fma": g.fma_mode, "capabilities": caps, "extensions": exts, "features": sorted({feats[c] for c in caps if c in feats and not feats[c].startswith(("core", "shaderImage1D"))} | {{"subgroup": "shaderSubgroupClock", "device": "shaderDeviceClock"}[k] for k in getattr(g, "uses_clock", ())} | {f for f, used in (("shaderFmaFloat32", getattr(g, "uses_fma_khr32", False)), ("shaderFmaFloat64", getattr(g, "uses_fma_khr64", False))) if used}), "bindings": binds, "push_constant_bytes": 4 * USER_SGPRS + 16, "vsharp_base_sign_extended": True, "subgroup_size": 64 if g.wave64 else 32, # Which stages can ask for a 64-wide subgroup is the driver's requiredSubgroupSizeStages, not a fixed rule: # the AMD Windows driver (FRAGMENT | COMPUTE | TASK | MESH) and Mesa RADV on GFX10+ (COMPUTE | FRAGMENT | # task/mesh) allow a wave64 PS to request 64, so it is exact there; NVIDIA has no 64 at all, and no driver # lists VERTEX or GEOMETRY. The runtime decides per device (runtime/src/subgroup_size.h) from `wave64`, # `subgroup_size` and `wave64_exchange`. This field stays true for VS/PS/GS wave64 (consumers rely on it): # it says the shader has no cross-half exchange, so it is per-subgroup, not that it must run 2x32. "wave64_emulated": bool(g.wave64 and (g.stage in ("vs", "ps", "gs") or g.emulate))} if g.descriptor_hash != "fnv1a": m["descriptor_hash"] = g.descriptor_hash if g.descriptor_table != "plain": # The module reads the kind word from every table entry it hits: the runtime must fill it # (runtime/src/descriptor_table.h, docs/design.md "Images and samplers (T# dimension)"). m["descriptor_table"] = g.descriptor_table # Every module of this translator reads a T#'s bindless index from its dword 6 where the word carries one, so the # runtime must write that word into the heaps it keeps (docs/design.md, "Bindless index in the T#"). The counts # say how many image instructions take it alone and how many still look the T# up in the hash table too. m["tsharp_index"] = TSHARP_INDEX if g.tsharp_index_reads or g.tsharp_lookups: m["tsharp_index_reads"] = g.tsharp_index_reads m["tsharp_lookups"] = g.tsharp_lookups if g.w64g: # SHADER-10: partition invariance on 32-wide subgroups. A and B are exact there (B: aggregated atomics up to # the order of the slots), C is not; the reasons name the construct (docs/design.md, Wave64 graphics). m["wave64_graphics"] = g.w64g["tier"] if g.w64g["reasons"]: m["wave64_graphics_reasons"] = g.w64g["reasons"] if g.w64g["idioms"]: m["wave64_graphics_idioms"] = g.w64g["idioms"] if g.stage == "ms": # The mesh shader's root SGPRs read the graphics window (user_data_dword): s16 is push dword 8. m["root_window"] = {"sgpr": MS_ROOT_SGPR, "dword": GRAPHICS_ROOT_DWORD} if g.emulate: # Exact on any subgroup size: no subgroup operation, cross-lane data in %x_buf (workgroup memory). m["wave64_exchange"] = "workgroup" m["subgroup_size"] = None elif g.ms_native_wave32: m["mesh_native_wave32"] = True m["wave64_emulated"] = True m["subgroup_size"] = None if "Offset " in asm and re.search(r"OpImageSample\w+ [^\n]*Offset", asm): m["needs_maintenance8"] = True if "SignedZeroInfNanPreserve" in caps: # Properties, not features: VkPhysicalDeviceFloatControlsProperties members the device must report true, # one per width the module declares SignedZeroInfNanPreserve for (32 always, 64 with Float64; SHADER-597). # DenormPreserve 16 comes after them: the driver may otherwise flush an f16 denormal (SHADER-526). widths = sorted({int(w) for w in re.findall(r"OpExecutionMode %main SignedZeroInfNanPreserve (\d+)", asm)}) m["float_controls"] = [f"shaderSignedZeroInfNanPreserveFloat{w}" for w in widths] if "DenormPreserve" in caps: m["float_controls"].append("shaderDenormPreserveFloat16") if "DenormFlushToZero" in caps: m["float_controls"].append("shaderDenormFlushToZeroFloat32") if g.uses_codebase: m["uses_code_base"] = True if g.cs: m["local_size"] = list(g.cs["size"]) if g.cs_serial: m["compute_serial_waves"] = g.cs_serial m["user_sgprs"] = g.cs["user"] if getattr(g, "msc_layout", None): # --mesh-compute: dispatch it as compute (same grid), then draw the slots with tools/mesh_compute_vs.py. lay = dict(g.msc_layout) lay["params"] = {str(k): v for k, v in lay["params"].items()} m["mesh_compute"] = lay m["push_constant_bytes"] = lay["push_constant_bytes"] if g.uses_guard: m["address_guard"] = True # --address-guard: its accesses read the runtime's guard header if PC_TAIL_UBO: # --pc-tail-ubo: s0..s31 alone in push constants; the tail, if the shader reads it, in a uniform block. m["push_constant_bytes"] = 4 * USER_SGPRS if g.uses_pc_tail: m["pc_tail"] = {"set": PC_TAIL_SET, "binding": PC_TAIL_BINDING, "bytes": 24 if getattr(g, "msc_layout", None) else 16} if g.ms: m["local_size"] = list(g.ms["size"]) if g.ms_serial: # the program's thread count stays in local_size; the module declares 64 invocations m["mesh_serial_waves"] = g.ms_serial m["max_vertices"], m["max_primitives"] = g.ms["maxv"], g.ms["maxp"] m["params"] = sorted(g.ms_params) if g.gs: m["max_vertices"] = g.gs["maxv"] m["gs_inputs"] = [r for r, _ in g.gs["in"]] m["gs_outputs"] = [r for r, _ in g.gs["out"]] m["gs_input_locations"] = sorted(r for r, sv in g.gs["in"] if sv != 1) m["gs_output_locations"] = sorted(r for r, sv in g.gs["out"] if sv != 1) # Every Workgroup byte of a compute shader (LDS + %x_buf of the emulation or the barrier rounds; SHADER-309): the # runtime compares it with the device's maxComputeSharedMemorySize. A mesh shader also has its 4-byte %ms_counts. lds = (4 * g.lds_dwords if g.uses_lds else 0) + (g.x_buf_bytes() if g.cs or g.emulate else 0) + (4 if g.ms else 0) if lds: m["lds_bytes"] = lds if g.vertex_inputs: m["vertex_inputs"] = [{"location": r, "type": {1: "uint", 2: "sint"}.get(t, "float")} for r, t in g.vertex_inputs] if getattr(g, "vertex_signature", None): m["vertex_input_signature"] = list(g.vertex_signature) if getattr(g, "dynamic_format", False): # A runtime V# FORMAT means codes outside FORMATS decode to 0; flag for atlas coverage. m["dynamic_format"] = True if getattr(g, "fixed_format_codes", None): m["fixed_format_codes"] = sorted(g.fixed_format_codes) if src_path: src_hash = _sha256_file(src_path) if src_hash: m["src_sha256"] = src_hash if fssm_path: fssm_hash = _sha256_file(fssm_path) if fssm_hash: m["fssm_sha256"] = fssm_hash if g.frag_inputs: m["ps_system_inputs"] = sorted({str(c) for c in g.frag_inputs.values()}) if getattr(g, "pixel_interpolants", None): # FSSM pixel-input table the PS input path used: interpolant count and 16-bit positions by table order. count, fp16 = g.pixel_interpolants m["ps_interpolants"] = count m["ps_fp16_interpolants"] = [n for n in range(count) if (fp16 >> n) & 1] # Table positions whose read method is v_interp_mov (flags bit 0): the inputs declared Flat. m["ps_flat_interpolants"] = getattr(g, "pixel_flat", []) outs = sorted(int("".join(ch for ch in t if ch.isdigit()) or 0) for t in g.outputs.values() if not t.startswith("pos")) if outs: m["outputs"] = outs if g.stage == "vs" and g.uses_clip: m["clip_distance_count"] = g.clip_count if g.stage == "vs" and g.uses_cull: m["cull_distance_count"] = g.cull_count if g.writes_depth: m["writes_depth"] = True if g.early_depth: m["early_depth"] = True if g.inputs: m["inputs"] = sorted(g.inputs.values()) if getattr(g, "bary_location", None) is not None: # --bary-fallback: the raw barycentrics are a perspective-interpolated vec3 at this location; the stage # before the PS must write (1,0,0), (0,1,0), (0,0,1) at the triangle's vertices (see BARY_FALLBACK). m["bary_fallback_input"] = {"location": g.bary_location} if F16_HALVES and g.stage in ("vs", "ms", "ps"): # --f16-interp-fallback: PS = the attributes whose f16 reads take decoded halves, VS/MS = the params that # export them; each as {n: [low-half location, high-half location]}. When a PS's canonical half slots would # collide with its raw attributes, assign_f16_half_locations packs them into free locations <= F16_HALF_TOP # and runtime PSO linking patches/synthesizes the producer's halves to match (SHADER-378). if g.stage == "ms" and getattr(g, "msc_layout", None) is not None: pairs = {n: (f16_half_location(n, 0), f16_half_location(n, 1)) for n in sorted(g.ms_params) if f16_half_location(n, 0) > g.param_max} else: pairs = g.f16_half_locs if pairs: m["f16_halves"] = {str(n): [lo, hi] for n, (lo, hi) in sorted(pairs.items())} if "mesh_compute" in m: # tools/mesh_compute_vs.py exports them from the slot's raw params m["mesh_compute"] = dict(m["mesh_compute"], f16_halves=m["f16_halves"]) if getattr(g, "reads_glc_buffer", False): m["reads_glc_buffer"] = True if g.build_meta: m.update(g.build_meta) m.setdefault("writes_buffer", False) m.setdefault("buffer_write_slots", []) if getattr(g, "uses_lit_sampler_spec", False) and m.get("literal_samplers"): m["literal_sampler_spec_base"] = 0 return m 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 = None try: # Unique per writer, and not a .json file: --merge globs index.part*.json. with tempfile.NamedTemporaryFile( mode="w", encoding="utf-8", newline="\n", dir=os.path.dirname(os.path.abspath(path)), prefix=".index-", suffix=".tmp", delete=False, ) as f: tmp = f.name _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 os.chmod(tmp, published_mode(path)) # do not publish NamedTemporaryFile's private 0600 mode replace_retry(tmp, path) # a scanner or sync client on Windows may hold the new file open for a moment except BaseException: if tmp is not None: try: os.chmod(tmp, 0o600) except OSError: pass try: os.unlink(tmp) except OSError: pass raise class ShardSetError(Exception): """The index parts on disk are not one complete shard set: merging them would publish a partial index.""" SHARD_MARKER = "shard{index}.json" def _read_shard_markers(out): """{index: count} from the shard.json markers a --shard run writes beside its index.part.json.""" import glob as _gl, json as _js markers = {} for path in sorted(_gl.glob(os.path.join(out, "shard*.json"))): m = re.fullmatch(r"shard(\d+)\.json", os.path.basename(path)) if not m: # make_game.py's shards.json plan is not a marker continue try: with open(path, encoding="utf-8") as f: doc = _js.load(f) except (OSError, ValueError) as e: raise ShardSetError(f"cannot read the shard marker {path}: {e}; delete it and run the shard again") from None try: index, count = int(doc["index"]), int(doc["count"]) except (KeyError, TypeError, ValueError): raise ShardSetError(f"{path} is not a shard marker (expected an object with \"index\" and \"count\")") from None if index != int(m.group(1)): raise ShardSetError(f"{path} is a marker for shard {index}, but its name says shard {m.group(1)}") if index in markers and markers[index] != count: raise ShardSetError(f"shard markers disagree on the shard count: {path}") markers[index] = count return markers def _missing_shard_summary(indices, expected): """Describe gaps in sorted unique indices without allocating the full missing range.""" valid = [i for i in indices if i < expected] missing_count = expected - len(valid) if not missing_count: return "" preview, start = [], 0 for stop in (*valid, expected): preview.extend(range(start, min(stop, start + 16 - len(preview)))) if len(preview) == 16: break start = stop + 1 omitted = missing_count - len(preview) return f", missing {preview}" + (f" ({omitted} more)" if omitted else "") def merge_shard_parts(out): """{shader: meta} from index.part*.json, after checking the set is complete and not empty. A --shard i/n run writes index.part.json and shard.json ({"index": i, "count": n}); the markers say how many parts the set has. Parts from before the markers existed fall back to make_game.py's shards.json plan. When neither exists the count is unknown, so the parts must at least be contiguous from 0: the merge fails closed instead of publishing a partial index that make_game.py would take as a finished translation. A complete set of empty parts fails closed the same way: `index.json` is the marker that says the corpus was translated, so publishing {} claims a translation of nothing.""" import glob as _gl, json as _js parts = sorted(_gl.glob(os.path.join(out, "index.part*.json"))) if not parts: raise ShardSetError(f"no index.part*.json in {out}; run --shard i/n first, then --merge") indices = [] for part in parts: m = re.search(r"index\.part(\d+)\.json$", part) if not m: raise ShardSetError(f"{part} is not an index.part.json file") indices.append(int(m.group(1))) if len(set(indices)) != len(indices): raise ShardSetError(f"index.part*.json has two parts with the same index: {sorted(indices)}") indices.sort() plan_jobs = None plan = os.path.join(out, "shards.json") if os.path.isfile(plan): try: with open(plan, encoding="utf-8") as f: doc = _js.load(f) jobs = doc.get("jobs") if isinstance(doc, dict) else None if type(jobs) is not int or jobs < 1: raise ValueError("no positive integer \"jobs\"") except (OSError, ValueError, TypeError, AttributeError) as e: raise ShardSetError(f"cannot read the shard plan {plan}: {e}; fix or remove it before --merge") from None plan_jobs = jobs markers = _read_shard_markers(out) expected = None if markers: counts = set(markers.values()) if len(counts) != 1: raise ShardSetError(f"shard markers disagree on the shard count: {sorted(counts)}") expected = counts.pop() if plan_jobs is not None and plan_jobs != expected: raise ShardSetError(f"shard markers say {expected} shards but the plan says {plan_jobs}; " "delete the stale parts or the plan and run every shard again") elif plan_jobs is not None: expected = plan_jobs if expected is not None: missing = _missing_shard_summary(indices, expected) extra = [i for i in indices if i >= expected] if missing or extra: raise ShardSetError( f"incomplete shard set: {len(indices)} of {expected} parts (0..{expected - 1})" + missing + (f", unexpected {extra}" if extra else "") + "; let every --shard run finish before --merge") elif indices[-1] != len(indices) - 1: raise ShardSetError(f"incomplete shard set: parts {indices} are not contiguous from 0" + _missing_shard_summary(indices, indices[-1] + 1) + "; without a shard count the merge refuses a set with a gap") if markers and set(markers) != set(indices): raise ShardSetError(f"index parts and shard markers disagree: parts {sorted(set(indices))}, " f"markers {sorted(markers)}") merged = {} for part in parts: try: with open(part, encoding="utf-8") as f: doc = _js.load(f) except (OSError, ValueError) as e: raise ShardSetError(f"cannot read {part}: {e}; delete that part and run --shard / again") from None if not isinstance(doc, dict): raise ShardSetError(f"{part} does not contain a shader index object") merged.update(doc) if not merged: raise ShardSetError(f"the shard set in {out} holds no shaders: every part is empty; " "check the disassembly (llvm-mc output and the .s files) before --merge") return merged # The longest run of refusals measured was 3.8 s, with every hardware thread busy at the workers' priority. SPAWN_RETRY_SECONDS = 10.0 _NOT_ENOUGH_QUOTA = 1816 # ERROR_NOT_ENOUGH_QUOTA def _run_spirv_tool(cmd, **kwargs): # A Windows job's active-process limit can still count a tool that has just exited, and CreateProcess then # refuses the next one with ERROR_NOT_ENOUGH_QUOTA: the compute worker's job allows itself and one tool # (scripts/compute_workers_win.py). The refused tool never started, so it is started again for a bounded time. # Same backoff as tools/replace_retry.py, kept apart because that one retries a rename, not a process start. start = time.monotonic() deadline = start + SPAWN_RETRY_SECONDS delay = 0.005 attempts = 0 while True: attempts += 1 try: return subprocess.run(cmd, **kwargs) except FileNotFoundError as exc: # Windows CreateProcess omits the executable name from WinError 2. if getattr(exc, "winerror", None) == 2 and exc.filename is None: exc.filename = cmd[0] raise except OSError as exc: if getattr(exc, "winerror", None) != _NOT_ENOUGH_QUOTA: raise if time.monotonic() >= deadline: exc.add_note(f"{cmd[0]}: refused {attempts} times in {time.monotonic() - start:.1f} s " f"(SPAWN_RETRY_SECONDS = {SPAWN_RETRY_SECONDS})") raise time.sleep(min(delay, max(0.0, deadline - time.monotonic()))) delay = min(delay * 2, 0.1) def _clean_stale_spirv_temps(out): """Remove leftover .spirv-*.tmp staging files in `out` when no shard is running.""" if not os.path.isdir(out): return try: with os.scandir(out) as entries: for entry in entries: if entry.name.startswith(".spirv-") and entry.name.endswith(".tmp") and entry.is_file(follow_symlinks=False): try: os.unlink(entry.path) except OSError: pass except OSError: pass # Keep resource bindings, specialization constants and stage interfaces used by the runtime linker. # Avoid the generic -O/-Os pipelines: they inline the shared typed-buffer and descriptor helpers. COMPACT_PASSES = ("--preserve-interface", "--preserve-bindings", "--preserve-spec-constants", "--eliminate-local-single-block", "--redundancy-elimination", "--eliminate-dead-code-aggressive") SPIRV_OPT_SSA_PASSES = ( "--convert-local-access-chains", "--ssa-rewrite", "--eliminate-dead-code-aggressive", "--ccp", "--simplify-instructions", "--redundancy-elimination", "--eliminate-dead-const", "--merge-blocks", ) SPIRV_OPT_LARGE_BYTES = 512 * 1024 # >= 512 KiB uses SSA passes to avoid NVIDIA 590 --scalar-replacement=0 crash def assemble_spirv(sa, sv, asm_text=None, assembler="spirv-as", validate=True, compact=False, spirv_opt=False): """Keep the assembled module out of the final path until validation succeeds. `assembler="spirv-as"` invokes the external spirv-as binary on `sa` (default); `assembler="python"` encodes `asm_text` (or reads `sa`) directly in memory with tools/spirv_asm.py, avoiding the spirv-as subprocess and temporary .spvasm I/O. When `validate=False`, skip running `spirv-val` after assembly. """ with tempfile.NamedTemporaryFile(prefix=".spirv-", suffix=".tmp", dir=os.path.dirname(sv), delete=False) as f: tmp = Path(f.name) # spirv-as reads the .spvasm from stdin, and both tools run in the output folder with the staging file's bare # name. On Windows they read their command line in the ANSI code page, so a folder name outside it (a Cyrillic or # CJK user name, say) reached them as '?' and every shader failed with "file does not exist". folder = os.path.dirname(os.path.abspath(tmp)) try: if assembler == "python": import spirv_asm try: text = asm_text if asm_text is not None else Path(sa).read_text(encoding="utf-8") tmp.write_bytes(spirv_asm.assemble(text, target_env="vulkan1.2")) result = subprocess.CompletedProcess(["spirv_asm"], 0, "", "") except (OSError, spirv_asm.SpirvAsmError) as exc: result = subprocess.CompletedProcess(["spirv_asm"], 1, "", str(exc)) else: try: with open(sa, "rb") as f: source = f.read() except OSError as exc: result = subprocess.CompletedProcess(["spirv-as"], 1, "", f"error: cannot read {sa}: {exc}") else: result = _run_spirv_tool(["spirv-as", "-", "-o", tmp.name, "--target-env", "vulkan1.2"], input=source, capture_output=True, cwd=folder) # stdin is bytes, so the output is too; a test double may already answer in text. if isinstance(result.stdout, bytes): result.stdout = result.stdout.decode("utf-8", "replace") if isinstance(result.stderr, bytes): result.stderr = result.stderr.decode("utf-8", "replace") if result.returncode == 0 and spirv_opt: opt_tmp = Path(str(tmp) + ".opt.spv") try: sz = tmp.stat().st_size opt_flags = SPIRV_OPT_SSA_PASSES if sz >= SPIRV_OPT_LARGE_BYTES else ("-O",) opt_res = _run_spirv_tool(["spirv-opt", "--target-env=vulkan1.3", "--skip-validation", *opt_flags, tmp.name, "-o", opt_tmp.name], capture_output=True, text=True, cwd=folder) if opt_res.returncode == 0: if validate: val_opt = _run_spirv_tool(["spirv-val", "--target-env", "vulkan1.2", "--allow-offset-texture-operand", opt_tmp.name], capture_output=True, text=True, cwd=folder) if val_opt.returncode == 0: opt_tmp.replace(tmp) else: opt_tmp.replace(tmp) finally: opt_tmp.unlink(missing_ok=True) elif result.returncode == 0 and compact: # spirv-opt lacks spirv-val's maintenance8 offset switch. Use the same project validator # below on the optimized binary, before publishing it. Both paths stay ASCII for Windows. result = _run_spirv_tool(["spirv-opt", "--target-env=vulkan1.2", "--skip-validation", *COMPACT_PASSES, tmp.name, "-o", tmp.name], capture_output=True, text=True, cwd=folder) if result.returncode == 0 and validate: # Offset on non-gather: VK_KHR_maintenance8 result = _run_spirv_tool(["spirv-val", "--target-env", "vulkan1.2", "--allow-offset-texture-operand", tmp.name], capture_output=True, text=True, cwd=folder) if result.returncode == 0: tmp.replace(sv) else: Path(sv).unlink(missing_ok=True) return result finally: tmp.unlink(missing_ok=True) def _limit_arg(text): """--limit N: at least 1. 0 used to mean "no limit" (the whole corpus) and a negative N dropped the last N.""" try: value = int(text) except ValueError: raise argparse.ArgumentTypeError(f"not a whole number: {text!r}") from None if value < 1: raise argparse.ArgumentTypeError("must be at least 1") return value def shard_bucket(files, index, count): """The `index`-th of `count` buckets of a size-balanced partition: largest first, each file to the lightest bucket. `files[index::count]` balanced nothing. Shaders differ in size by two orders of magnitude, so a round-robin split can hand one shard most of the work while every other process waits for it; on a synthetic corpus whose largest shader is 11% of the total that cost 1.18x at 4 shards and 1.30x at 8. Every shard derives this partition from the file sizes, so the buckets agree without the processes talking to each other, and each bucket is still handed out in name order. """ weight = {} for path in files: try: weight[path] = os.path.getsize(path) except OSError as error: # Not a weight of 0: a shard that cannot size one file would place it by a number no other shard has, so # the buckets would overlap and leave another shader out of the set, and the merge would publish a corpus # with a hole in it (reported by @Zhenyettta on #7479). Every shard derives this partition on its own, so # a size it cannot read has to stop the run and be retried, not be guessed at. raise OSError(f"cannot read the size of {path} for the shard partition: {error}; " "fix or restore the file and run the shard again") from error buckets = [[] for _ in range(count)] loads = [0] * count for path in sorted(files, key=lambda p: (-weight[p], p)): target = min(range(count), key=lambda b: (loads[b], b)) buckets[target].append(path) loads[target] += weight[path] return sorted(buckets[index]) def _shard_arg(text): """--shard i/n with n >= 1 and 0 <= i < n. n = 0 was a ValueError (slice step 0) and i >= n translated nothing.""" try: si, sn = (int(x) for x in text.split("/")) except ValueError: raise argparse.ArgumentTypeError(f"expected i/n, for example 0/8, not {text!r}") from None if sn < 1 or not 0 <= si < sn: raise argparse.ArgumentTypeError(f"{text!r}: need n >= 1 and 0 <= i < n") return si, sn def _depth_arg(text): """--max-structured-depth N: 0 (never fall back to the dispatch loop) or a positive nesting depth.""" try: value = int(text) except ValueError: raise argparse.ArgumentTypeError(f"not a whole number: {text!r}") from None if value < 0: raise argparse.ArgumentTypeError("must be 0 (no bound) or a positive depth") return value def _out_inside_input(src, out): """True when --out is the input folder or a folder inside it: translating there writes among the inputs. `src` is a .s file or the folder of them; a single file's folder is its input folder. `same_report_path` covers the same spelling, `..`, links and (on Windows) case; `path_key` folds a case-insensitive macOS volume for the containment test. Standard library only. """ folder = src if os.path.isdir(src) else os.path.dirname(os.path.abspath(src)) if same_report_path(folder, out): return True root, target = path_key(folder), path_key(out) return target.startswith(root.rstrip(os.sep) + os.sep) def main(): global MAX_SHARED_BYTES, MAX_STRUCTURED_DEPTH, LOOP_LIMIT, DESCRIPTOR_HASH, DESCRIPTOR_TABLE ap = argparse.ArgumentParser() ap.add_argument("src") ap.add_argument("--out", required=True) ap.add_argument("--limit", type=_limit_arg) ap.add_argument("--shard", type=_shard_arg, help="i/n: translate the i-th of n size-balanced buckets of shaders (run n processes in " "parallel, then merge the index.part*.json files with --merge)") ap.add_argument("--no-asm", action="store_true", help="delete each .spvasm once its .spv is written (the text is ~2.7x the binary: 35 GB for the corpus)") ap.add_argument("--assembler", choices=("spirv-as", "python"), default="spirv-as", help="SPIR-V binary assembler: spirv-as (default, external binary) or python (in-process " "tools/spirv_asm.py; skips writing .spvasm to disk when combined with --no-asm)") ap.add_argument("--no-validate", action="store_true", help="skip spirv-val after assembly (for running GPU tests without SPIRV-Tools when paired " "with --assembler python)") ap.add_argument("--merge", action="store_true", help="merge index.part*.json in --out into index.json and exit") ap.add_argument("--fssm-dir", default=None, help="optional dir with .fssm sidecars: records fssm_sha256 per shader in the index") ap.add_argument("--dispatch-loop", action="store_true", help="emit control flow the old way, as one loop around a switch (to compare with the default)") ap.add_argument("--no-float-controls", action="store_true", help="don't declare SignedZeroInfNanPreserve, DenormPreserve or DenormFlushToZero (for a driver " "whose float-control properties are false); NaN, inf, -0 and f16/f32 denormals are then not " "guaranteed") ap.add_argument("--no-ftz32", action="store_true", help="don't declare DenormFlushToZero 32; keep software f32 denormal flushes instead (for a driver " "whose shaderDenormFlushToZeroFloat32 is false, e.g. llvmpipe)") ap.add_argument("--no-lds-bounds", action="store_true", help="don't bounds-check LDS accesses against the shader's declared LDS size (restore the wrapped " "power-of-two array when constant offsets stay inside)") ap.add_argument("--no-early-depth", action="store_true", help="don't emit OpExecutionMode EarlyFragmentTests even when PS DB_SHADER_CONTROL bit 12 is set") ap.add_argument("--wave64-emulate", action="store_true", help="wave64 compute and mesh shaders exact on any subgroup size (32-wide NVIDIA, Intel): " "cross-lane operations go through workgroup memory instead of subgroup operations") ap.add_argument("--wave64-graphics", choices=("warn", "error", "off"), default="warn", help="wave64 vertex, pixel and geometry shaders that are not exact on 32-wide subgroups (tier C of " "tools/wave64_halves.py): warn = count them in the summary and mark them in the index, " "error = refuse them (Unsupported), off = skip the analysis") ap.add_argument("--integer-dot-fallback", action="store_true", help="4x8-bit dot products (v_dot4_*) as extracts, multiplies and adds instead of " "SPV_KHR_integer_dot_product, for devices without shaderIntegerDotProduct") ap.add_argument("--int64-addresses", action="store_true", help="keep 64-bit integer address arithmetic (Int64 / shaderInt64) instead of lowering it to 32-bit pairs") ap.add_argument("--bary-fallback", action="store_true", help="pixel shaders that read raw barycentrics take them from an ordinary interpolated input " "(metadata: bary_fallback_input) instead of BaryCoordKHR, for devices without " "VK_KHR_fragment_shader_barycentric (e.g. NVIDIA Pascal)") ap.add_argument("--texel-offset-fallback", action="store_true", help="image_sample*_o without VK_KHR_maintenance8 (e.g. NVIDIA Pascal): fold the texel offset into " "the coordinate instead of the Offset operand") ap.add_argument("--explicit-lod-bias", action="store_true", help="apply the S# LOD_BIAS in the shader, for a driver whose sampler drops mipLodBias (measured by " "tools/lod_bias_probe.py); elsewhere the bias would count twice") ap.add_argument("--mesh-compute", action="store_true", help="mesh shaders become compute shaders that write their vertices and primitives to a buffer " "(metadata: mesh_compute), drawn by tools/mesh_compute_vs.py, for devices without " "VK_EXT_mesh_shader (e.g. NVIDIA Pascal)") ap.add_argument("--mesh-serial-waves", action="store_true", help="with --wave64-emulate: a mesh shader of more than 64 threads whose waves cannot pass each " "other anything (no LDS, no store or atomic) runs its waves one after the other in 64 " "invocations, one single-wave pass per wave, instead of side by side (docs/design.md)") ap.add_argument("--compute-serial-waves", action="store_true", help="with --wave64-emulate: a compute shader of more than 64 threads with no LDS, s_barrier or " "atomic runs its waves one after the other in 64 invocations (metadata: compute_serial_waves)") ap.add_argument("--mesh-native-wave32", action="store_true", help="with --wave64-emulate: partition-invariant mesh shaders skip wave64 emulation and run " "natively in 1 pass at full LocalSize on 32-wide subgroups (metadata: mesh_native_wave32)") ap.add_argument("--shader-clock", choices=("off", "khr"), default="off", help="s_memtime / s_memrealtime: off = Unsupported (default), khr = OpReadClockKHR (needs " "VK_KHR_shader_clock; feature shaderSubgroupClock / shaderDeviceClock in the metadata)") ap.add_argument("--fma", choices=("glsl", "khr", "exact"), default="glsl", help="how fused multiply-adds (v_fma_f32, v_fmac_f32, v_fmaak/fmamk_f32, v_fma_mix*) are emitted: " "glsl = GLSL.std.450 Fma (default; the Vulkan spec lets a driver round twice), khr = OpFmaKHR " "(guaranteed single rounding, f32 and f64; needs VK_KHR_shader_fma + shaderFmaFloat32/64, listed in the " "shader's metadata as capability FMAKHR / feature shaderFmaFloat32/64), exact = a single " "rounding built from NoContraction f32 ops, for a device that splits Fma and has no " "VK_KHR_shader_fma (about 110 instructions, 31 NoContraction decorations and 13 constants per multiply-add; no extension needed)") ap.add_argument("--f16-interp-fallback", action="store_true", help="16-bit interpolation without PerVertexKHR inputs, for devices that can't compile them " "(MoltenVK): VS and mesh params also export their f16 halves decoded to f32, which the PS " "reads as ordinary interpolated inputs (metadata: f16_halves)") ap.add_argument("--max-shared-memory", type=int, default=MAX_SHARED_BYTES, metavar="BYTES", help="cap on a compute shader's workgroup memory, its LDS plus what --wave64-emulate adds " "(default %(default)s, the 64 KiB hard cap): over it the LDS array shrinks to the program's " "need, or the shader is refused (Unsupported). The device's own maxComputeSharedMemorySize " "(32768 on some drivers) is checked by the runtime against lds_bytes in index.json") ap.add_argument("--pc-tail-ubo", action="store_true", help="keep only s0..s31 (128 bytes) in push constants and read the heap base, code base and " "--mesh-compute output address from a uniform block at set 1, binding 0 (metadata: pc_tail), " "for devices whose maxPushConstantsSize is below 144") ap.add_argument("--address-guard", action="store_true", help="check every heap_base + VA access against the runtime's page table of backed memory " "(LEONIDA_ADDRESS_GUARD=1): an unbacked one reads 0 and drops its store instead of reaching " "a wild GPU address (metadata: address_guard; docs/d3d12_vulkan.md, Address guard)") ap.add_argument("--descriptor-hash", choices=DESCRIPTOR_HASHES, default="fnv1a", help="bindless descriptor table hash shared with the runtime (default: fnv1a)") ap.add_argument("--descriptor-table", choices=DESCRIPTOR_TABLES, default="tagged", help="descriptor table entry layout: 'tagged' also carries each image's array kind, recorded as " "descriptor_table in the module meta (default: tagged; 'plain' is the old layout, for a " "library that keeps the runtime's old behaviour)") ap.add_argument("--loop-limit", type=spirv_loop_guard.parse_limit, default=spirv_loop_guard.DEFAULT_LIMIT, help="maximum visits to each loop header, including dispatch loops (default %(default)s, 0 disables)") ap.add_argument("--max-structured-depth", type=_depth_arg, default=MAX_STRUCTURED_DEPTH, metavar="N", help="a shader whose structured control flow nests deeper than N is emitted in the dispatch-loop " "form instead (default %(default)s; 0 = never): that form validates faster at great depth " "but compiles 1.7-2x slower on NVIDIA (SHADER-427, docs/design.md \"Control flow\")") ap.add_argument("--compact-spirv", action="store_true", help="remove redundant local loads, repeated values and dead instructions with spirv-opt") ap.add_argument("--spirv-opt", action="store_true", help="run spirv-opt (-O below 512 KiB, safe SSA pass set at >= 512 KiB) with automatic fallback " "to unoptimized SPIR-V if spirv-opt or spirv-val rejects the optimized module") ap.add_argument("--opt", action="store_true", help="run basic-block SPIR-V peephole optimization (tools/spirv_opt.py: register store-to-load " "forwarding, OpAccessChain CSE, dead-store elimination, OpSelect/CopyObject folding, DCE)") if hasattr(signal, "SIGTERM"): def _on_sigterm(_signum, _frame): raise SystemExit(128 + signal.SIGTERM) try: signal.signal(signal.SIGTERM, _on_sigterm) except ValueError: pass a = ap.parse_args() # A file at --out (or one above it) can never become a folder. Refuse it here, before # --merge publishes an index or os.makedirs raises a traceback. Same check as #1607's # shader_disasm.py and #1632's tex_export.py. if os.path.lexists(a.out) and not os.path.isdir(a.out): ap.error(f"{a.out} is a file, not a folder") # realpath resolves symlink components before '..' is applied, so a symlinked parent # does not make the walk inspect a different tree than os.makedirs will use. ancestor = os.path.dirname(os.path.realpath(a.out)) while ancestor and not os.path.exists(ancestor): parent = os.path.dirname(ancestor) if parent == ancestor: # a root that doesn't exist, e.g. an unmapped Windows drive ap.error(f"cannot create {a.out}: {ancestor} is not a folder") ancestor = parent if ancestor and not os.path.isdir(ancestor): ap.error(f"cannot create {a.out}: {ancestor} is a file, not a folder") MAX_SHARED_BYTES = a.max_shared_memory DESCRIPTOR_HASH = a.descriptor_hash DESCRIPTOR_TABLE = a.descriptor_table LOOP_LIMIT = a.loop_limit MAX_STRUCTURED_DEPTH = a.max_structured_depth global INTEGER_DOT_FALLBACK global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, EXPLICIT_LOD_BIAS, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV global MESH_SERIAL_WAVES, COMPUTE_SERIAL_WAVES, MESH_NATIVE_WAVE32 global PC_TAIL_UBO, ADDR_PAIR, ADDRESS_GUARD PC_TAIL_UBO = a.pc_tail_ubo ADDRESS_GUARD = a.address_guard global FMA_EXACT FMA_KHR = a.fma == "khr" SHADER_CLOCK = a.shader_clock == "khr" FMA_EXACT = a.fma == "exact" STRUCTURED = not a.dispatch_loop global FLOAT_CONTROLS, FTZ32, LDS_BOUNDS, EARLY_DEPTH FLOAT_CONTROLS = not a.no_float_controls FTZ32 = not a.no_ftz32 LDS_BOUNDS = not a.no_lds_bounds EARLY_DEPTH = not a.no_early_depth WAVE64_EMULATE = a.wave64_emulate WAVE64_GRAPHICS = a.wave64_graphics BARY_FALLBACK = a.bary_fallback INTEGER_DOT_FALLBACK = a.integer_dot_fallback ADDR_PAIR = not a.int64_addresses TEXEL_OFFSET_FALLBACK = a.texel_offset_fallback EXPLICIT_LOD_BIAS = a.explicit_lod_bias MESH_COMPUTE = a.mesh_compute MESH_SERIAL_WAVES = a.mesh_serial_waves COMPUTE_SERIAL_WAVES = a.compute_serial_waves MESH_NATIVE_WAVE32 = a.mesh_native_wave32 F16_HALVES = a.f16_interp_fallback OPT_SPIRV = a.opt if a.merge: try: merged = merge_shard_parts(a.out) except ShardSetError as e: print(f"ERROR: {e}", file=sys.stderr) # The parts no longer describe the old index: leaving it would let the next run take the failed merge # as a finished translation. It is regenerated by the next successful --merge. index = os.path.join(a.out, "index.json") try: os.remove(index) except FileNotFoundError: pass except OSError as remove_error: print(f"WARNING: cannot remove the stale {index}: {remove_error}", file=sys.stderr) return 2 # The stubs go first: index.json is what tells make_game.py the translation finished. import spirv_stubs spirv_stubs.generate_for_index(a.out, merged) write_index(os.path.join(a.out, "index.json"), merged) _clean_stale_spirv_temps(a.out) print(f"merged {len(merged)} entries") return 0 single_file = os.path.isfile(a.src) and a.src.endswith(".s") if not single_file and not os.path.isdir(a.src): ap.error(f"{a.src} is not a .s file or a folder of .s files") # Writing translations into the input folder mixes them with the .s inputs (and a rerun then scans its # own output); refuse it before mkdir, the index or any module is written. --merge above is exempt: its # src is not read, and merging parts in place is how a shard run finishes. if _out_inside_input(a.src, a.out): print(f"ERROR: --out {a.out} is the input folder or inside it; choose a separate output folder", file=sys.stderr) return 2 try: os.makedirs(a.out, exist_ok=True) except OSError as e: # a trailing separator on a file, or a symlink changed since the check above ap.error(f"cannot create {a.out}: {e.strerror or e}") shard = None idx_path = os.path.join(a.out, "index.json") if a.shard: shard, sn = a.shard part = os.path.join(a.out, f"index.part{shard}.json") # Resume trusts the part, and consumers trust the merged index. Withdraw both # before scanning or modifying outputs, even if a retry is killed mid-shader. Path(part).unlink(missing_ok=True) Path(idx_path).unlink(missing_ok=True) write_index(os.path.join(a.out, SHARD_MARKER.format(index=shard)), {"index": shard, "count": sn}) idx_path = part if single_file: files = [a.src] else: with os.scandir(a.src) as entries: files = sorted(e.path for e in entries if e.name.endswith(".s") and e.is_file()) if a.limit is not None: files = files[:a.limit] if shard is not None: files = shard_bucket(files, shard, sn) why, ok, valid = Counter(), 0, 0 meta = {} invalid = set() total = len(files) t0 = time.time() last_progress = 0.0 label = f"shard {shard}" if shard is not None else "translate" missing_inputs = 0 def drop_stale(name): # A shader that no longer translates must not stay published from an earlier run: remove its old # module, and the index merge below drops its entry, exactly like a spirv-as/val rejection. The # .spvasm text stays for diagnosis, as it does on a rejection. Path(os.path.join(a.out, name + ".spv")).unlink(missing_ok=True) invalid.add(name) for i, p in enumerate(files, 1): name = os.path.splitext(os.path.basename(p))[0] try: asm = translate(p) except FileNotFoundError as e: # Optional inputs have fallbacks in translate(). A failed required read must also # retire this shader's previous module and index entry on a retry. print(f"ERROR: {name}: missing translation input {e.filename}", file=sys.stderr) missing_inputs += 1 drop_stale(name) continue except Unsupported as e: why[str(e)] += 1 drop_stale(name) continue except (IndexError, KeyError, ValueError, AssertionError, TypeError, AttributeError, ZeroDivisionError, RecursionError) as e: # A translator bug on one program refuses that program and is counted; it does not end a run over a # whole pack (an assert in --wave64-emulate stopped make_game.py's shaders stage, #3976). why[f"translator error {type(e).__name__}"] += 1 drop_stale(name) continue ok += 1 sa = os.path.join(a.out, name + ".spvasm") sv = os.path.join(a.out, name + ".spv") write_asm = not (a.no_asm and a.assembler == "python") if write_asm: with open(sa, "w", encoding="utf-8", newline="\n") as f: f.write(asm) try: r = assemble_spirv(sa, sv, asm_text=asm, assembler=a.assembler, validate=not a.no_validate, compact=a.compact_spirv, spirv_opt=a.spirv_opt) except OSError as e: # A missing spirv-as/spirv-val fails every shader the same way; report it once as a setup # error (exit 2) instead of a FileNotFoundError traceback from the first one. if e.filename not in ("spirv-as", "spirv-val", "spirv-opt"): raise print(f"ERROR: {e.filename} not found; install SPIRV-Tools " "and put it on PATH", file=sys.stderr) return 2 if r.returncode == 0: valid += 1 try: fssm_sidecar = os.path.join(a.fssm_dir, name + ".fssm") if a.fssm_dir else None meta[name] = shader_meta(translate.last_gen, asm, src_path=p, fssm_path=fssm_sidecar) except Exception as e: # noqa: BLE001 - metadata must never cost a translation meta[name] = {"error": f"{type(e).__name__}: {e}"} else: if not write_asm: with open(sa, "w", encoding="utf-8", newline="\n") as f: f.write(asm) drop_stale(name) why["INVALID: " + (r.stderr.strip().splitlines() or ["?"])[0][:90]] += 1 if a.no_asm and os.path.exists(sa): os.remove(sa) now = time.time() if total and (i == total or i % 100 == 0 or now - last_progress >= 15.0): last_progress = now pct = 100 * i // total elapsed = now - t0 if 0 < i < total and elapsed > 0: left = elapsed * (total - i) / i if left < 60: eta = f", ~{int(left)}s left" elif left < 3600: eta = f", ~{int(left) // 60}m left" else: eta = f", ~{int(left) // 3600}h {int(left) // 60 % 60:02d}m left" else: eta = "" print(f" {label}: {i}/{total} ({pct}%){eta}", flush=True) import json as _js old = {} if shard is None and os.path.isfile(idx_path) and a.limit is None and len(files) < 1000: with open(idx_path, encoding="utf-8") as f: old = _js.load(f) # partial runs merge into an existing index for name in invalid: old.pop(name, None) old.update(meta) if shard is None or not missing_inputs: write_index(idx_path, old) if shard is None: _clean_stale_spirv_temps(a.out) import spirv_stubs spirv_stubs.generate_for_index(a.out, old) status_label = "assembled (spirv-val skipped)" if a.no_validate else "pass spirv-val" print(f"{len(files)} shaders: {ok} translated, {valid} {status_label}") if W64G_COUNTS: print("wave64 VS/PS/GS on 32-wide subgroups: " + ", ".join(f"tier {t}: {n}" for t, n in sorted(W64G_COUNTS.items())) + (" (tier C is not exact there; see wave64_graphics_reasons in the index)" if W64G_COUNTS["C"] else "")) for k, v in why.most_common(25): print(f" {v:6} {k}") if missing_inputs: print(f"{missing_inputs} of {len(files)} selected shaders missing required inputs", file=sys.stderr) return 1 if __name__ == "__main__": try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode sys.stdout.reconfigure(errors="replace") except (AttributeError, ValueError, OSError): pass sys.exit(main())