mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 15:58:36 +00:00
12381 lines
705 KiB
Python
12381 lines
705 KiB
Python
"""RDNA (gfx10) shader -> SPIR-V assembly, version 0.
|
|
|
|
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 treated as all-ones (valid for branch-free code).
|
|
|
|
Supported in v0 (anything else is reported, never guessed):
|
|
vector ALU v_mov_b32 v_add/sub/subrev/mul/mul_legacy/fma/fmac/fmaak/fmamk/mac/max/min_f32 v_rcp/rsq/sqrt/
|
|
exp/log/floor/fract/ceil/trunc_f32 v_cvt_f32_u32/i32/ubyte0..3 v_cvt_u32/i32_f32
|
|
v_add/sub_nc_u32 v_and/or/xor_b32 v_lshlrev/lshrrev/ashrrev_i32 v_cndmask_b32 v_mul_u32_u24
|
|
v_bfe_u32 v_med3_f32 v_mad_u32_u24
|
|
scalar s_mov_b32 s_add_u32 s_and_b32 s_or_b32 s_lshl_b32 s_lshr_b32 s_mul_i32
|
|
no-ops s_waitcnt* s_nop s_inst_prefetch s_endpgm s_setprio s_clause s_delay_alu
|
|
export exp pos0..3 / param0..31 (vertex) and mrt0..7 (pixel)
|
|
Vertex inputs: v0 = VertexIndex (the full-screen-triangle shaders read only that).
|
|
|
|
Usage (needs spirv-as/spirv-val on PATH, from the Vulkan SDK or spirv-tools):
|
|
python3 -I rdna2spirv.py <disasm dir or .s> --out DIR [--limit N]
|
|
Writes <name>.spvasm for each translated shader and <name>.spv only for validated modules.
|
|
Prints coverage and validation results.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import os
|
|
import re
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from collections import Counter, defaultdict
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, os.path.dirname(__file__))
|
|
from shader_ir import HDR, parse_file # noqa: E402
|
|
import cfg_structure # noqa: E402
|
|
import fssm_header # noqa: E402
|
|
import lane_masks # noqa: E402
|
|
import shader_meta as _shader_meta # noqa: E402
|
|
import wave64_halves # 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. `spirv-val`'s selection/loop
|
|
# checking cost grows with the nesting depth: over the 1.0.2.1 corpus (26,503 modules) the deepest block of a
|
|
# module is nested 118 constructs deep and 85% of the validation time is in modules nested 20 or deeper, while
|
|
# the dispatch-loop form validates a depth-20 module 1.4x faster, a depth-50 one 2.3x and a depth-77 one 4.5x
|
|
# (SHADER-299, docs/design.md "Control flow"). Both forms are equivalent; only the routing differs.
|
|
MAX_STRUCTURED_DEPTH = 16
|
|
WAVE64_EMULATE = False # --wave64-emulate: wave64 compute/mesh shaders exact on any subgroup size (Gen.x_round)
|
|
# --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
|
|
FMA_KHR = False # --fma khr: fused multiply-adds are OpFmaKHR (SPV_KHR_fma, VK_KHR_shader_fma), not GLSL Fma
|
|
# --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
|
|
# --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
|
|
# --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
|
|
|
|
|
|
def f16_half_location(n, half):
|
|
"""--f16-interp-fallback: the location of param n's decoded low (half 0) or high (half 1) f16 halves."""
|
|
return F16_HALF_TOP - 2 * n - 1 + half
|
|
|
|
|
|
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
|
|
return {"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]}
|
|
|
|
# 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()}
|
|
|
|
# User SGPRs s0..s(USER_SGPRS-1) are initialised from push constants (128 bytes = Vulkan's guaranteed minimum).
|
|
USER_SGPRS = 32
|
|
|
|
# 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).
|
|
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"}
|
|
|
|
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"}
|
|
|
|
|
|
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):
|
|
self.stage = stage
|
|
self.body = []
|
|
self.consts = {}
|
|
self.n = 0
|
|
self.outputs = {}
|
|
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.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.uses_psb = False
|
|
self.uses_active = False
|
|
self.vm_latch = False # PS: EXEC can change after a `vm` export, so that export's 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_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.reads_store_views = False # a coherent image_load reads a storage view (StorageImageReadWithoutFormat)
|
|
self.coherent_images = False # a glc image_load/image_store: the storage views are decorated Coherent
|
|
self.writes_depth = False
|
|
self.uses_smul = False
|
|
self.uses_minlod = False
|
|
self.uses_img_offset = False
|
|
self.uses_pops = False
|
|
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_fma_khr = False # an OpFmaKHR was emitted: capability FMAKHR + extension SPV_KHR_fma
|
|
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_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.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.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.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.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.emulate = False # --wave64-emulate: exact wave64 on any subgroup size (cs/ms; see x_round)
|
|
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.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.x_lanes = 64 # emulate: workgroup invocations rounded up to whole waves
|
|
self.bar_rounds = False # native wave32 cs with an s_barrier outside uniform control flow (bar_scheduler)
|
|
self.uses_storage3d = False
|
|
self.uses_heap = False
|
|
self.uses_codebase = False
|
|
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.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.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
|
|
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
|
|
|
|
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 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 load_reg(self, kind, r):
|
|
arr = "%vgpr" if kind == "vgpr" else "%sgpr"
|
|
p, t = self.tmp(), self.tmp()
|
|
self.emit(f"{p} = OpAccessChain %_ptr_Function_uint {arr} {self.cu(r)}")
|
|
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])}
|
|
arr = "%vgpr" if kind == "vgpr" else "%sgpr"
|
|
p = self.tmp()
|
|
self.emit(f"{p} = OpAccessChain %_ptr_Function_uint {arr} {self.cu(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 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 runtime puts 0 (no collision) in the collision SGPR.
|
|
v = self.cu(0)
|
|
self.uses_pops = True
|
|
elif k == "imm":
|
|
v = self.cu(a["v"])
|
|
elif k == "fimm":
|
|
v = self.cu(struct.unpack("<I", struct.pack("<f", a["v"]))[0])
|
|
elif k == "special" and a["t"] in ("vcc_lo", "vcc"):
|
|
v = self.tmp()
|
|
self.emit(f"{v} = OpLoad %uint %vcc")
|
|
elif k == "ssa":
|
|
v = a["v"] # a value already in SSA form (DPP's shuffled source)
|
|
else:
|
|
raise Unsupported(f"operand {a.get('t', k)}")
|
|
if "sdwa_sel" in a:
|
|
v = self.sdwa_src(v, a)
|
|
return self.modify(v, a)
|
|
|
|
def modify(self, v, a):
|
|
if a.get("abs") or a.get("neg"):
|
|
f = self.tof(v)
|
|
if a.get("abs"):
|
|
g = self.tmp()
|
|
self.emit(f"{g} = OpExtInst %float %glsl FAbs {f}")
|
|
f = g
|
|
if a.get("neg"):
|
|
g = self.tmp()
|
|
self.emit(f"{g} = OpFNegate %float {f}")
|
|
f = g
|
|
v = self.tou(f)
|
|
return v
|
|
|
|
def write_lo16(self, d, lo16, preserve_high=True):
|
|
"""Write a 16-bit result into the low half of VGPR d. On GFX10, f16 VOP1/VOP2 ops and opsel-capable VOP3
|
|
ops are partial writes that keep the high half (Mesa ACO aco_ir.cpp: instr_is_16bit / can_use_opsel);
|
|
non-opsel VOP2 16-bit integer ops define the whole register (high half modelled as zero)."""
|
|
if not preserve_high or d["k"] != "vgpr":
|
|
self.dst(d, lo16)
|
|
return
|
|
old, keep, r = self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', d['r'])}")
|
|
self.emit(f"{keep} = OpBitwiseAnd %uint {old} {self.cu(0xFFFF0000)}")
|
|
self.emit(f"{r} = OpBitwiseOr %uint {keep} {lo16}")
|
|
self.dst(d, r)
|
|
|
|
def write_half16(self, d, lo16, dhi):
|
|
"""Write a 16-bit result to the low half of VGPR ``d``, or to the high half when ``dhi`` (op_sel destination bit);
|
|
the other half is kept either way."""
|
|
if not dhi:
|
|
self.write_lo16(d, lo16)
|
|
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 {lo16} {self.cu(16)}")
|
|
self.emit(f"{v} = OpBitwiseOr %uint {keep} {sh16}")
|
|
self.dst(d, v)
|
|
|
|
_DPP_MODS = ("row_mirror", "row_half_mirror")
|
|
_DPP_PREFIXES = ("dpp8:", "quad_perm:", "row_shl:", "row_shr:", "row_ror:",
|
|
"row_share:", "row_xmask:", "fi:", "bound_ctrl:", "row_mask:", "bank_mask:")
|
|
|
|
@classmethod
|
|
def non_dpp_mods(cls, raw_op, mods):
|
|
"""Return modifiers that do not belong to DPP control when raw_op is a _dpp form."""
|
|
if not raw_op.endswith("_dpp"):
|
|
return list(mods)
|
|
return [m for m in mods if m not in cls._DPP_MODS and not m.startswith(cls._DPP_PREFIXES)]
|
|
|
|
@staticmethod
|
|
def opsel_bits(mods, nsrc):
|
|
"""Parse the VOP3 ``op_sel:[...]`` modifier of an op with ``nsrc`` sources -> (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 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."""
|
|
if s["k"] == "fimm":
|
|
try:
|
|
return self.cu(struct.unpack("<H", struct.pack("<e", s["v"]))[0])
|
|
except OverflowError:
|
|
raise Unsupported("f16 inline constant out of range") from None
|
|
return self.src_u({**s, "neg": False, "abs": False})
|
|
|
|
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."""
|
|
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}")
|
|
return self.modify_f(f, s)
|
|
|
|
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]")
|
|
sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")]
|
|
hb = [int(x) for x in selhi.split("[")[1].rstrip("]").split(",")]
|
|
# 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):
|
|
"""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."""
|
|
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)}")
|
|
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}")
|
|
if not rtz:
|
|
one, msk, rem, half, odd, gt, eq, tie, up, upu, sub2 = (t() for _ in range(11))
|
|
self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {shc}")
|
|
self.emit(f"{msk} = OpISub %uint {one} {self.cu(1)}")
|
|
self.emit(f"{rem} = OpBitwiseAnd %uint {man} {msk}")
|
|
self.emit(f"{half} = OpShiftRightLogical %uint {one} {self.cu(1)}")
|
|
self.emit(f"{odd} = OpBitwiseAnd %uint {sub} {self.cu(1)}")
|
|
self.emit(f"{gt} = OpUGreaterThan %bool {rem} {half}")
|
|
self.emit(f"{eq} = OpIEqual %bool {rem} {half}")
|
|
self.emit(f"{tie} = OpLogicalAnd %bool {eq} {self.emit_ne0(odd)}")
|
|
self.emit(f"{up} = OpLogicalOr %bool {gt} {tie}")
|
|
self.emit(f"{upu} = OpSelect %uint {up} {self.cu(1)} {self.cu(0)}")
|
|
self.emit(f"{sub2} = OpIAdd %uint {sub} {upu}")
|
|
sub = sub2
|
|
# pick the range
|
|
isn, issub, tiny, big, isinf, isnan = t(), t(), t(), t(), t(), t()
|
|
self.emit(f"{isn} = OpUGreaterThanEqual %bool {a} {self.cu(0x38800000)}")
|
|
self.emit(f"{tiny} = OpULessThan %bool {e} {self.cu(101)}")
|
|
r1, r2, r3, r4, r5, nanb, res = t(), t(), t(), t(), t(), t(), t()
|
|
self.emit(f"{r1} = OpSelect %uint {isn} {nh} {sub}")
|
|
self.emit(f"{r2} = OpSelect %uint {tiny} {self.cu(0)} {r1}")
|
|
if rtz:
|
|
self.emit(f"{big} = OpUGreaterThanEqual %bool {a} {self.cu(0x47800000)}")
|
|
self.emit(f"{r3} = OpSelect %uint {big} {self.cu(0x7BFF)} {r2}")
|
|
else:
|
|
self.emit(f"{big} = OpUGreaterThanEqual %bool {a} {self.cu(0x477FF000)}")
|
|
self.emit(f"{r3} = OpSelect %uint {big} {self.cu(0x7C00)} {r2}")
|
|
self.emit(f"{isinf} = OpIEqual %bool {a} {self.cu(0x7F800000)}")
|
|
self.emit(f"{r4} = OpSelect %uint {isinf} {self.cu(0x7C00)} {r3}")
|
|
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):
|
|
"""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)."""
|
|
lo = self.f16_bits(f)
|
|
if not self.round_mode:
|
|
return lo
|
|
z, m, is_z, r = self.f16_bits(f, rtz=True), 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"{r} = OpSelect %uint {is_z} {z} {lo}")
|
|
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 an RX 6800 does it
|
|
(@shelbykb2 on #718): after the rounding and before clamp, so 65520 div:2 is inf. 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 or after the scaling, gives +0 (2^-15 mul:2 and -0 mul:2 measured 0x0000), inf and NaN
|
|
pass through, and a finite overflow gives inf (65504 under MODE toward zero, as f16_res)."""
|
|
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 results are flushed, and the omod makes -0 +0; div:2 takes exponent 1 to a denormal too.
|
|
self.emit(f"{tiny} = OpULessThan %bool {e} {self.cu(2 if d < 0 else 1)}")
|
|
if d < 0:
|
|
self.emit(f"{scaled} = OpISub %uint {h} {self.cu(1 << 10)}")
|
|
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 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. The rounding error comes
|
|
from TwoSum (exact: every float op is NoContraction): e = (x - (r - (r - x))) + (y - (r - x)); 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)."""
|
|
bb, t1, t2, t3, e = (self.tmp() for _ in range(5))
|
|
self.emit(f"{bb} = OpFSub %double {r} {x}")
|
|
self.emit(f"{t1} = OpFSub %double {r} {bb}")
|
|
self.emit(f"{t2} = OpFSub %double {x} {t1}")
|
|
self.emit(f"{t3} = OpFSub %double {y} {bb}")
|
|
self.emit(f"{e} = OpFAdd %double {t2} {t3}")
|
|
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")
|
|
new = a[1]["v"] & 3
|
|
if new in (1, 2):
|
|
raise Unsupported("MODE.FP_ROUND[3:2] directed rounding (+inf/-inf)")
|
|
self.emit(f"OpStore %mode_r16 {self.cu(new)}")
|
|
|
|
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 = True
|
|
self.emit(f"{r} = OpFmaKHR %float {x} {y} {z}")
|
|
else:
|
|
self.emit(f"{r} = OpExtInst %float %glsl Fma {x} {y} {z}")
|
|
|
|
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 f16_pack2(self, lo, hi):
|
|
"""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), self.f16_res(hi), 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 f16_out(self, d, r, hi=0, fract=False, mode=True):
|
|
"""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) 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
|
|
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_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):
|
|
"""Xbox GPU virtual address (ulong id) -> host buffer device address: heap base (push constant
|
|
dwords 32..33) + VA. The runtime maps the console's GPU address window into one host buffer."""
|
|
lo, hi, l64, h64, sh, base, r = (self.tmp() for _ in range(7))
|
|
self.emit(f"{lo} = OpLoad %uint %ud_base_lo_p")
|
|
self.emit(f"{hi} = OpLoad %uint %ud_base_hi_p")
|
|
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"{r} = OpIAdd %ulong {base} {xbox_va}")
|
|
self.uses_heap = True
|
|
self.cu(1), self.cu(2) # member indices of the push-constant block, declared before assembly
|
|
return r
|
|
|
|
def tof(self, u):
|
|
f = self.tmp()
|
|
self.emit(f"{f} = OpBitcast %float {u}")
|
|
return f
|
|
|
|
def tou(self, f):
|
|
u = self.tmp()
|
|
self.emit(f"{u} = OpBitcast %uint {f}")
|
|
return u
|
|
|
|
def src_f(self, a):
|
|
return self.tof(self.src_u(a))
|
|
|
|
# ---- EXEC (this lane's active bit) ----
|
|
def active_b(self):
|
|
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."""
|
|
r = self.tmp()
|
|
self.emit(f"{r} = OpSelect %uint {self.active_b()} {self.cu(0xFFFFFFFF)} {self.cu(0)}")
|
|
return r
|
|
|
|
def set_exec(self, mask_u):
|
|
self.emit(f"OpStore %active {self.tmp_bool_nz(mask_u)}")
|
|
self.uses_active = True
|
|
|
|
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 a["k"] == "special" and a["t"] in ("exec_lo", "exec"):
|
|
self.set_exec(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.
|
|
if self.write_all_lanes:
|
|
self.store_reg("vgpr", a["r"], val)
|
|
return
|
|
p, old, r = self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{p} = OpAccessChain %_ptr_Function_uint %vgpr {self.cu(a['r'])}")
|
|
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 "vcc" in self.cur_masks:
|
|
# 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'])}")
|
|
|
|
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 d["k"] == "special" and d["t"] in ("vcc", "vcc_lo"):
|
|
self.emit(f"OpStore %vcc {self.mask_src(s)}")
|
|
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 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])
|
|
xs, ys = self.tmp(), self.tmp()
|
|
f = "OpBitFieldSExtract" if ty == "i16" else "OpBitFieldUExtract"
|
|
self.emit(f"{xs} = {f} %uint {x} {self.cu(16 if sel[0] else 0)} {self.cu(16)}")
|
|
self.emit(f"{ys} = {f} %uint {y} {self.cu(16 if sel[1] else 0)} {self.cu(16)}")
|
|
x, y = xs, ys
|
|
if ty == "i16":
|
|
x, y = self.as_int(x), self.as_int(y)
|
|
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"}
|
|
else:
|
|
raise Unsupported(op)
|
|
is_float = ty in ("f32", "f16")
|
|
b, r = self.tmp(), 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)
|
|
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)
|
|
# 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
|
|
elif dst["k"] == "special" and dst["t"] in ("vcc", "vcc_lo"):
|
|
self.emit(f"OpStore %vcc {r}")
|
|
elif dst["k"] == "sgpr":
|
|
self.mask_dst(dst, r)
|
|
else:
|
|
raise Unsupported("v_cmp destination")
|
|
|
|
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 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")
|
|
if self.holds_lane_mask(a[0]):
|
|
lo, hi = self.wave_mask(a[0])
|
|
if not is_64 and self.wave64:
|
|
half = self.mask_half(a[0])
|
|
if half == "hi":
|
|
lo = hi
|
|
elif is_64 and a[0]["k"] == "sgpr" and a[0].get("n") == 2:
|
|
lo, hi = self.load_reg("sgpr", a[0]["r"]), self.load_reg("sgpr", a[0]["r"] + 1)
|
|
elif is_64 and a[0]["k"] == "imm":
|
|
v = a[0]["v"] & 0xFFFFFFFFFFFFFFFF
|
|
lo, hi = self.cu(v & 0xFFFFFFFF), self.cu(v >> 32)
|
|
elif is_64:
|
|
lo, hi = self.mask_src(a[0]), self.cu(0)
|
|
else:
|
|
lo = self.src_u(a[0])
|
|
|
|
sh = 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(...): 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)
|
|
if not m and not bm:
|
|
raise Unsupported("ds_swizzle pattern")
|
|
kind = "BITMASK_PERM" if bm else m.group(1)
|
|
args = [int(x) for x in m.group(2).split(",")[1:]] if m and m.group(2) else []
|
|
self.uses_subgroup = True
|
|
lane = self.tmp()
|
|
self.sub_lane(lane)
|
|
if kind == "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.
|
|
and_m = or_m = xor_m = 0
|
|
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
|
|
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)
|
|
v, r = self.src_u(a[1]), self.tmp()
|
|
self.g_shuffle(r, v, src)
|
|
self.dst(a[0], r)
|
|
|
|
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)
|
|
self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}")
|
|
|
|
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} Aligned 4")
|
|
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)
|
|
self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}")
|
|
p0, w0 = self.buf_dword_ptr(ptr, host, step, 0), self.tmp()
|
|
self.emit(f"{w0} = OpLoad %uint {p0} Aligned 4")
|
|
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)
|
|
self.emit(f"{w1} = OpLoad %uint {p1} Aligned 4")
|
|
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.
|
|
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].
|
|
5: (1, "uint", (8,)), 11: (2, "uint", (16,)), 18: (2, "uint", (8, 8)),
|
|
6: (1, "sint", (8,)), 12: (2, "sint", (16,)), 19: (2, "sint", (8, 8)), 28: (4, "sint", (16, 16)),
|
|
61: (4, "sint", (8, 8, 8, 8)), 70: (8, "sint", (16, 16, 16, 16))}
|
|
|
|
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":
|
|
field = self.f16_bits(self.tof(fcomps[c]))
|
|
elif kind == "unorm":
|
|
cl, sc, rd, u = self.tmp(), self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{cl} = OpExtInst %float %glsl FClamp {self.tof(fcomps[c])} %f0 %f1")
|
|
self.emit(f"{sc} = OpFMul %float {cl} {self.fconst(float((1 << w) - 1))}")
|
|
self.emit(f"{rd} = OpExtInst %float %glsl RoundEven {sc}")
|
|
self.emit(f"{u} = OpConvertFToU %uint {rd}")
|
|
field = u
|
|
elif kind == "snorm":
|
|
cl, sc, rd, i, u = self.tmp(), self.tmp(), self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{cl} = OpExtInst %float %glsl FClamp {self.tof(fcomps[c])} {self.fconst(-1.0)} %f1")
|
|
self.emit(f"{sc} = OpFMul %float {cl} {self.fconst(float((1 << (w - 1)) - 1))}")
|
|
self.emit(f"{rd} = OpExtInst %float %glsl RoundEven {sc}")
|
|
self.emit(f"{i} = OpConvertFToS %int {rd}")
|
|
self.emit(f"{u} = OpBitcast %uint {i}")
|
|
field = u
|
|
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}")
|
|
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 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":
|
|
v2, x = self.tmp(), self.tmp()
|
|
self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {f}")
|
|
self.emit(f"{x} = OpCompositeExtract %float {v2} 0")
|
|
out.append(self.tou(x))
|
|
elif kind == "unorm":
|
|
out.append(normalize(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 global_atomic(self, op, a, mods):
|
|
"""global_atomic_<op> [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. 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. The other
|
|
_x2 forms (add/sub/min/max carry or compare across the dwords, cmpswap_x2 compares all 64 bits), inc/dec and
|
|
the float atomics stay Unsupported."""
|
|
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)
|
|
if kind not in self.BUF_ATOMICS or any(m in mods for m in ("slc", "dlc", "lds")):
|
|
raise Unsupported(op if kind not in self.BUF_ATOMICS 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 == "cmpswap" 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 == "cmpswap" else None
|
|
old_d = self.load_reg("vgpr", vdst["r"]) if vdst is not None else self.cu(0)
|
|
lbl_do, lbl_end, res, old = self.tmp() + "_do", self.tmp() + "_end", self.tmp(), self.tmp()
|
|
pre = self.current_label_placeholder()
|
|
act = self.active_b() # loaded before the merge: OpSelectionMerge must directly precede the branch
|
|
self.emit(f"OpSelectionMerge {lbl_end} None")
|
|
self.emit(f"OpBranchConditional {act} {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)}")
|
|
self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}")
|
|
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}")
|
|
self.emit(f"OpBranch {lbl_end}")
|
|
self.emit(f"{lbl_end} = OpLabel")
|
|
self.emit(f"{old} = OpPhi %uint {res} {lbl_do} {old_d} {pre}")
|
|
if vdst is not None:
|
|
self.store_reg("vgpr", vdst["r"], 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."""
|
|
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"]))
|
|
old_d = self.load_reg("vgpr", vdst["r"]) if vdst is not None else self.cu(0)
|
|
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()
|
|
act = self.active_b() # loaded before the merge: OpSelectionMerge must directly precede the branch
|
|
self.emit(f"OpSelectionMerge {lbl_end} None")
|
|
self.emit(f"OpBranchConditional {act} {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(full)}")
|
|
self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}")
|
|
self.emit(f"{init} = OpLoad %uint {p} Aligned 4")
|
|
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")
|
|
self.emit(f"OpBranch {lbl_end}")
|
|
self.emit(f"{lbl_end} = OpLabel")
|
|
old = self.tmp()
|
|
self.emit(f"{old} = OpPhi %uint {cur} {lbl_exit} {old_d} {pre}")
|
|
if vdst is not None:
|
|
self.store_reg("vgpr", vdst["r"], 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)]
|
|
keep = [self.load_reg("vgpr", vdst["r"] + w) for w in range(2)] if vdst is not None else [self.cu(0)] * 2
|
|
spv = self.BUF_ATOMICS[kind][0]
|
|
lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end"
|
|
pre = self.current_label_placeholder()
|
|
act = self.active_b() # loaded before the merge: OpSelectionMerge must directly precede the branch
|
|
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)}")
|
|
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)
|
|
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} {keep[w]} {pre}")
|
|
olds.append(old)
|
|
if vdst is not None:
|
|
for w in range(2):
|
|
self.store_reg("vgpr", vdst["r"] + w, olds[w])
|
|
|
|
def buffer_atomic(self, op, a, mods):
|
|
"""buffer_atomic_<op> 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."""
|
|
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 not in self.BUF_ATOMICS or "x2" in kind:
|
|
raise Unsupported(op)
|
|
spv, neutral = self.BUF_ATOMICS[kind]
|
|
addr, _, in_b, _ = self.buffer_address(a, mods)
|
|
vd = a[0]
|
|
val = self.load_reg("vgpr", vd["r"])
|
|
cond = self.tmp()
|
|
self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {in_b}")
|
|
# Guard all atomics with a structured if so inactive or OOB lanes never touch memory.
|
|
lbl_do, lbl_end, res_do, old = self.tmp() + "_do", self.tmp() + "_end", self.tmp(), 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)}")
|
|
self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}")
|
|
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}")
|
|
self.emit(f"OpBranch {lbl_end}")
|
|
self.emit(f"{lbl_end} = OpLabel")
|
|
self.emit(f"{old} = OpPhi %uint {res_do} {lbl_do} {self.cu(0)} {pre_label}")
|
|
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. The bounds check covers the whole 8-byte element, all or nothing, as for a typed element (a 32_32
|
|
format): how hardware treats a 64-bit atomic that is only partly in range is not measured."""
|
|
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)]
|
|
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")
|
|
ptr = self.tmp()
|
|
self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr)}")
|
|
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)
|
|
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 or out-of-range lane returns 0, as buffer_atomic does
|
|
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). For
|
|
arrays the query takes only the 2D coordinate; the layer doesn't affect the LOD."""
|
|
dim = next((m for m in mods if m.startswith("dim:")), "dim:SQ_RSRC_IMG_2D")
|
|
if dim not in ("dim:SQ_RSRC_IMG_2D", "dim:SQ_RSRC_IMG_2D_ARRAY") or self.stage != "ps" or "a16" in mods:
|
|
raise Unsupported("image_get_lod form")
|
|
arr = dim.endswith("_ARRAY")
|
|
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, addr = a[0], self.addr_regs(a[1])
|
|
img_idx = self.desc_lookup_sgpr(a[2], 8)
|
|
smp_idx = self.desc_lookup_sgpr(a[3], 4)
|
|
ip, img, sp, smp, si = (self.tmp() for _ in range(5))
|
|
self.emit(f"{ip} = OpAccessChain %{'_ptr_UC_imga' if arr else '_ptr_UC_img'} "
|
|
f"{'%images_arr' if arr else '%images'} {img_idx}")
|
|
self.emit(f"{img} = OpLoad {'%img2da' if arr else '%img2d'} {ip}")
|
|
self.emit(f"{sp} = OpAccessChain %_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}")
|
|
f = [self.tof(self.load_reg("vgpr", r)) for r in addr[:2]]
|
|
uv, lod = self.tmp(), self.tmp()
|
|
self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}")
|
|
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 decode_any_format(self, fmt, words):
|
|
"""Decode every supported format from 4 packed dwords, then pick by FORMAT (0 for one outside FORMATS)."""
|
|
comps = [self.cu(0)] * 4
|
|
for code in self.FORMATS:
|
|
dec = self.decode_format(words, code)
|
|
e = self.tmp()
|
|
self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code)}")
|
|
nxt = []
|
|
for c in range(4):
|
|
s = self.tmp()
|
|
self.emit(f"{s} = OpSelect %uint {e} {dec[c]} {comps[c]}")
|
|
nxt.append(s)
|
|
comps = nxt
|
|
return comps
|
|
|
|
def format_decode_call(self, fmt, words):
|
|
"""4 uint ids: the element decoded per the run-time FORMAT, through one function in the module.
|
|
|
|
Decoding all FORMATS is about 900 instructions (the exact UNORM/SNORM quotients are integer code). Inlined at
|
|
every dynamic-format load, 3,281 loads made a 60 MB module whose id bound passed SPIR-V's 4,194,303 limit
|
|
(indirect_diffuse_lighting ScreenProbes_ActivateProbes under --wave64-emulate)."""
|
|
if self.fmt_fn is None:
|
|
params = ["%fd_fmt"] + [f"%fd_w{i}" for i in range(4)]
|
|
saved, self.body = self.body, []
|
|
dec = self.decode_any_format(params[0], params[1:])
|
|
res = self.tmp()
|
|
self.emit(f"{res} = OpCompositeConstruct %v4uint_fmt " + " ".join(dec))
|
|
lines, self.body = self.body, saved
|
|
self.fmt_fn = (["%fmt_decode_fn = OpFunction %v4uint_fmt None %fn_fmt_decode"] +
|
|
[f"{q} = OpFunctionParameter %uint" for q in params] + ["%fd_entry = OpLabel"] +
|
|
lines + [f" OpReturnValue {res}", "OpFunctionEnd"])
|
|
r = self.tmp()
|
|
self.emit(f"{r} = OpFunctionCall %v4uint_fmt %fmt_decode_fn {fmt} " + " ".join(words[:4]))
|
|
comps = []
|
|
for c in range(4):
|
|
x = self.tmp()
|
|
self.emit(f"{x} = OpCompositeExtract %uint {r} {c}")
|
|
comps.append(x)
|
|
return comps
|
|
|
|
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
|
|
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.
|
|
need = self.cu(1)
|
|
for code, (size, _, _) in self.FORMATS.items():
|
|
e, sum_, n2 = (self.tmp() for _ in range(3))
|
|
self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code)}")
|
|
self.emit(f"{sum_} = OpIAdd %uint {b3} {self.cu(size + 3)}")
|
|
self.emit(f"{n2} = OpShiftRightLogical %uint {sum_} {self.cu(2)}")
|
|
sel = self.tmp()
|
|
self.emit(f"{sel} = OpSelect %uint {e} {n2} {need}")
|
|
need = sel
|
|
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)
|
|
self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}")
|
|
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} Aligned 4")
|
|
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:
|
|
comps = self.format_decode_call(fmt, words)
|
|
# DST_SEL swizzle: 0 -> 0, 1 -> 1.0 (float/norm) or integer 1 (UINT/SINT; SHADER-86), 4..7 -> X..W.
|
|
is_int_fmt, is_signed = "%false", "%false"
|
|
for code_v, (_, kind, _) in self.FORMATS.items():
|
|
if kind in ("u32", "i32", "uint", "sint"):
|
|
e, o = self.tmp(), self.tmp()
|
|
self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}")
|
|
self.emit(f"{o} = OpLogicalOr %bool {is_int_fmt} {e}")
|
|
is_int_fmt = o
|
|
if d16 and kind in ("i32", "sint"):
|
|
signed = self.tmp()
|
|
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)}")
|
|
outs = []
|
|
for c in range(ncomp):
|
|
sel = self.tmp()
|
|
self.emit(f"{sel} = OpBitFieldUExtract %uint {d3} {self.cu(3 * c)} {self.cu(3)}")
|
|
r = self.cu(0)
|
|
for code_v, src in ((1, dst1), (4, comps[0]), (5, comps[1]), (6, comps[2]), (7, 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
|
|
rb = self.tmp()
|
|
self.emit(f"{rb} = OpSelect %uint {in_b} {r} {self.cu(0)}")
|
|
if d16:
|
|
outs.append(rb)
|
|
else:
|
|
self.dst({"k": "vgpr", "r": vd["r"] + c, "n": 1}, rb)
|
|
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 = "%false"
|
|
for code_v, (_, kind, _) in self.FORMATS.items():
|
|
if kind in ("unorm", "snorm") and (fixed_fmt is None or code_v == fixed_fmt):
|
|
e, o = self.tmp(), self.tmp()
|
|
self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}")
|
|
self.emit(f"{o} = OpLogicalOr %bool {is_norm} {e}")
|
|
is_norm = o
|
|
for i in range(0, len(outs), 2):
|
|
dest = {"k": "vgpr", "r": vd["r"] + i // 2, "n": 1}
|
|
lo = outs[i]
|
|
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.
|
|
fl = self.d16_norm_f16(lo, is_norm)
|
|
self.emit(f"{r} = OpSelect %uint {is_int_fmt} {il} {fl}")
|
|
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)} {self.cu(16)}")
|
|
self.emit(f"{ph} = OpBitwiseOr %uint {self.d16_norm_f16(lo, is_norm)} {fh_s}")
|
|
ih, pi = self.tmp(), self.tmp()
|
|
high_half = 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):
|
|
"""f16 bits of a typed d16 buffer load component from its decoded f32 ``bits``. Round to nearest even
|
|
(f16_bits), except that a UNORM/SNORM quotient (``is_norm``) whose f32 is one of D16_NORM_HALFWAY takes the
|
|
f16 below it. The hardware rounds the exact quotient once; f32 first and then f16 rounds twice, which is 1 ulp
|
|
high on exactly those values (UNORM16 0xffaf and 0xffef, SNORM16 0x7ff7 and 0x8009, the 14- and 15-bit
|
|
twins). Measured on an RX 6700 (gfx1031) for every UNORM8/SNORM8/UNORM10/UNORM16/SNORM16 value, MUBUF and
|
|
MTBUF, wave32 and wave64 (tools/d16_format_probe.py). A float format keeps the plain rounding: a 32_FLOAT
|
|
0x3f7ff000 is a real tie."""
|
|
h = self.f16_bits(self.tof(bits))
|
|
mag, a, b, hit, both, dn, out = (self.tmp() for _ in range(7))
|
|
self.emit(f"{mag} = OpBitwiseAnd %uint {bits} {self.cu(0x7FFFFFFF)}")
|
|
self.emit(f"{a} = OpIEqual %bool {mag} {self.cu(self.D16_NORM_HALFWAY[0])}")
|
|
self.emit(f"{b} = OpIEqual %bool {mag} {self.cu(self.D16_NORM_HALFWAY[1])}")
|
|
self.emit(f"{hit} = OpLogicalOr %bool {a} {b}")
|
|
self.emit(f"{both} = OpLogicalAnd %bool {hit} {is_norm}")
|
|
self.emit(f"{dn} = OpISub %uint {h} {self.cu(1)}") # sign-magnitude: 1 ulp toward zero
|
|
self.emit(f"{out} = OpSelect %uint {both} {dn} {h}")
|
|
return out
|
|
|
|
def global_address(self, op, vaddr, saddr, mods):
|
|
"""The 64-bit Xbox GPU VA a global_* instruction accesses (ulong id): (saddr: 64-bit SGPR pair + zero-extended
|
|
32-bit vaddr | off: 64-bit VGPR pair) + the signed 12-bit instruction offset."""
|
|
# 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):
|
|
"""(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)}")
|
|
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")
|
|
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)
|
|
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} Aligned 4")
|
|
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:
|
|
# 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)
|
|
bits, signed = sub
|
|
lo32, b3, b64, al, ptr1, w, shb, v = (self.tmp() for _ in range(8))
|
|
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"{ptr1} = OpConvertUToPtr %_ptr_PSB_uint {self.host_addr(al)}")
|
|
self.emit(f"{w} = OpLoad %uint {ptr1} Aligned 4")
|
|
self.emit(f"{shb} = OpShiftLeftLogical %uint {b3} {self.cu(3)}")
|
|
self.emit(f"{v} = {'OpBitFieldSExtract' if signed else 'OpBitFieldUExtract'} %uint {w} {shb} {self.cu(bits)}")
|
|
vals.append(v)
|
|
else:
|
|
ptr = self.tmp()
|
|
self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}")
|
|
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} Aligned 4")
|
|
vals.append(v)
|
|
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]} {lbl_do} {olds[i]} {pre}")
|
|
phis.append(ph)
|
|
for i, ph in enumerate(phis):
|
|
self.store_reg("vgpr", data["r"] + i, ph)
|
|
else:
|
|
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)}")
|
|
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]} Aligned 4")
|
|
self.emit(f"OpBranch {lbl_end}")
|
|
self.emit(f"{lbl_end} = OpLabel")
|
|
|
|
def buf_dword_ptr(self, arr, host, step, i):
|
|
"""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,
|
|
since dword k of a swizzled access is 4 * index_stride bytes after dword k - 1 (buffer_address)."""
|
|
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
|
|
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) for a MUBUF/MTBUF instruction: vdata, vaddr,
|
|
srsrc, soffset. The address is V#.base + soffset + inst_offset + (offen ? vaddr : 0) + (idxen ? vindex *
|
|
stride : 0), byte exact. in_bounds is the V# OOB_SELECT (word3 bits [29:28]) check of the first dword, shared
|
|
by stores, atomics and format loads. With `idx` = vindex (0 without idxen), `off` = inst_offset + vaddr offset
|
|
(offen), `offs` = off + soffset, out of range on RDNA2 as measured natively on gfx1036 (docs/buffer_bounds.md,
|
|
Mesa's GFX11 column) when, for a dword at byte k * 4 of the access:
|
|
0 STRUCTURED_WITH_OFFSET: idx >= num_records or off + 4k + 4 > stride
|
|
1 STRUCTURED: idx >= num_records
|
|
2 DISABLED: num_records == 0
|
|
3 RAW: offs + 4k + 4 > num_records (idx * stride is not part of the check)
|
|
A V# word3 that an s_mov_b32 wrote earlier in the block (`sgpr_imm`) folds to one of these; a run-time one
|
|
selects with OpSelect. elem="fmt" is for typed loads and stores: the whole element (its format's size, from the
|
|
instruction's fixed_fmt, a literal word3 or the V# at run time) must end inside. parts=True adds a 4th element for buffer_load: a function k -> in-range bool id for
|
|
dword k (modes 0 and 3, and a run-time V#), or None when the literal mode is 1 or 2 (every dword shares
|
|
in_bounds). Multi-dword loads are per dword for mode 3 (measured, RX 6800); mode 0 is by analogy.
|
|
A swizzled V# (SWIZZLE_ENABLE) gets the RDNA2 ISA's swizzled buffer_offset, ADD_TID_ENABLE adds the wave lane
|
|
to idx, and mode 3 checks like mode 0 when swizzled with a stride (ISA table 35). Every tuple ends with `step`:
|
|
None when consecutive dwords of the access are 4 bytes apart, else the id of that distance (4 * index_stride
|
|
when swizzled, selected at run time for a run-time word1), for buf_dword_ptr."""
|
|
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; RDNA2 ISA 8.1.5 "Swizzled Buffer Addressing"
|
|
# and table 35; fields from Mesa gfx10-rsrc.json SQ_BUF_RSRC_WORD1/WORD3): SWIZZLE_ENABLE is word1 bit 31,
|
|
# INDEX_STRIDE word3 [22:21] (IS = 8 << n indices), ADD_TID_ENABLE word3 bit 23, element_size fixed at 4.
|
|
# A literal word folds its bit (a Python bool); a run-time one is a SPIR-V id (0 or 1).
|
|
swz = bool(lit1 >> 31) if lit1 is not None else None
|
|
tid = bool(lit3 >> 23 & 1) if lit3 is not None else None
|
|
inst = next((int(m.split(":")[1], 0) for m in mods if m.startswith("offset:")), 0)
|
|
soff_v = self.src_u(soff)
|
|
total = self.tmp()
|
|
self.emit(f"{total} = OpIAdd %uint {soff_v} {self.cu(inst)}")
|
|
vregs = [] if vaddr["k"] == "special" else [vaddr["r"] + i for i in range(vaddr.get("n", 1))]
|
|
idx = None
|
|
if "idxen" in mods:
|
|
idx = self.load_reg("vgpr", vregs[0])
|
|
voff = None
|
|
if "offen" in mods:
|
|
voff = self.load_reg("vgpr", vregs[1] if "idxen" in mods else vregs[0])
|
|
# ADD_TID_ENABLE adds the lane within the wave (thread_id[5:0]) to the index, swizzled or linear (ISA table
|
|
# 33 and the Ring/stream-out column of table 36, which is linear with add_tid); the bounds check sees it too
|
|
if tid is not False:
|
|
lane = self.wave_lane()
|
|
if tid is None: # lane * the run-time bit
|
|
b, t = self.tmp(), self.tmp()
|
|
self.emit(f"{b} = OpBitFieldUExtract %uint {d3} {self.cu(23)} {self.cu(1)}")
|
|
self.emit(f"{t} = OpIMul %uint {lane} {b}")
|
|
lane = t
|
|
if idx is None:
|
|
idx = lane
|
|
else:
|
|
s = self.tmp()
|
|
self.emit(f"{s} = OpIAdd %uint {idx} {lane}")
|
|
idx = s
|
|
# offs = soffset + inst_offset + vaddr offset (idx * stride excluded): the raw bounds check's offset
|
|
offs = total
|
|
if voff is not None:
|
|
offs = self.tmp()
|
|
self.emit(f"{offs} = OpIAdd %uint {total} {voff}")
|
|
total = offs
|
|
# step: bytes between consecutive dwords of one access, None for the linear 4 (callers index an array then)
|
|
step = None
|
|
if swz is False:
|
|
if idx is not None:
|
|
m, total = self.tmp(), self.tmp()
|
|
self.emit(f"{m} = OpIMul %uint {idx} {stride}")
|
|
self.emit(f"{total} = OpIAdd %uint {offs} {m}")
|
|
sw3 = False
|
|
else:
|
|
# buffer_offset = (index / IS * stride + offset / 4 * 4) * IS + index % IS * 4 + offset % 4, Offset =
|
|
# inst_offset + vaddr offset (no soffset), added to base + soffset; IS = 2^L. Dword k of the access is
|
|
# element offset / 4 + k, 4 * IS bytes further. L = 0 (a run-time V# without SWIZZLE_ENABLE) is the
|
|
# linear address: index * stride + offset. 32-bit arithmetic, like the linear address.
|
|
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 is None: # L * the run-time bit: 0 when not swizzled
|
|
b, t = self.tmp(), self.tmp()
|
|
self.emit(f"{b} = OpBitFieldUExtract %uint {d1} {self.cu(31)} {self.cu(1)}")
|
|
self.emit(f"{t} = OpIMul %uint {L} {b}")
|
|
L, Li = t, None
|
|
off_s = self.cu(inst)
|
|
if voff is not None:
|
|
off_s = self.tmp()
|
|
self.emit(f"{off_s} = OpIAdd %uint {voff} {self.cu(inst)}")
|
|
om4, ol, sh = self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{om4} = OpBitwiseAnd %uint {off_s} {self.cu(0xFFFFFFFC)}")
|
|
self.emit(f"{ol} = OpBitwiseAnd %uint {off_s} {self.cu(3)}")
|
|
if idx is not None:
|
|
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}")
|
|
sh = im
|
|
else:
|
|
self.emit(f"{sh} = OpShiftLeftLogical %uint {om4} {L}")
|
|
b_off, total = self.tmp(), self.tmp()
|
|
self.emit(f"{b_off} = OpIAdd %uint {sh} {ol}")
|
|
self.emit(f"{total} = OpIAdd %uint {soff_v} {b_off}")
|
|
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 SWIZZLE_ENABLE and a stride != 0 checks like mode 0 (ISA table 35): index >=
|
|
# num_records or offset + payload > stride, offset without soffset
|
|
if lit1 is not None:
|
|
sw3 = (lit1 >> 16 & 0x3FFF) != 0
|
|
else: # L * stride != 0: swizzled (L >= 3) and a stride (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)}")
|
|
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}")
|
|
mode = None if lit3 is None else lit3 >> 28 & 3
|
|
mode0_rule = mode in (None, 0) or (mode == 3 and sw3 is not False)
|
|
# idx (0 without idxen) < num_records and num_records != 0 do not depend on the dword; the two end checks do
|
|
p1 = p2 = None
|
|
if mode in (None, 0, 1) or mode0_rule:
|
|
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)}")
|
|
lim = {}
|
|
if mode0_rule:
|
|
# off = inst_offset + vaddr offset, without soffset (docs/buffer_bounds.md)
|
|
off = self.cu(inst)
|
|
if voff is not None:
|
|
off = self.tmp()
|
|
self.emit(f"{off} = OpIAdd %uint {voff} {self.cu(inst)}")
|
|
lim[0] = (self.tmp(), self.tmp())
|
|
self.emit(f"{lim[0][0]} = OpUConvert %ulong {off}")
|
|
self.emit(f"{lim[0][1]} = OpUConvert %ulong {stride}")
|
|
if mode in (None, 3):
|
|
lim[3] = (self.tmp(), self.tmp())
|
|
self.emit(f"{lim[3][0]} = OpUConvert %ulong {offs}")
|
|
self.emit(f"{lim[3][1]} = OpUConvert %ulong {d2}")
|
|
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)
|
|
|
|
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, ok = self.tmp(), self.tmp()
|
|
self.emit(f"{end} = OpIAdd %ulong {x} {self.cl(end_bytes) if isinstance(end_bytes, int) else end_bytes}")
|
|
self.emit(f"{ok} = OpULessThanEqual %bool {end} {limit}")
|
|
return ok
|
|
|
|
def raw_or_swizzled(e0, end_bytes):
|
|
"""mode 3: the raw end check, or mode 0's e0 for a swizzled V# with a stride (sw3)."""
|
|
if sw3 is True:
|
|
return e0
|
|
raw = end_ok(3, end_bytes)
|
|
if sw3 is False:
|
|
return raw
|
|
r = self.tmp()
|
|
self.emit(f"{r} = OpSelect %bool {sw3} {e0} {raw}")
|
|
return r
|
|
|
|
def check_end(end_bytes):
|
|
"""in-range bool of an access that ends end_bytes after its first byte."""
|
|
if mode == 1:
|
|
return p1
|
|
if mode == 2:
|
|
return p2
|
|
if mode == 3 and sw3 is False:
|
|
return end_ok(3, end_bytes)
|
|
e0 = self.tmp()
|
|
self.emit(f"{e0} = OpLogicalAnd %bool {p1} {end_ok(0, end_bytes)}")
|
|
if mode == 0:
|
|
return e0
|
|
if mode == 3:
|
|
return raw_or_swizzled(e0, 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]} {raw_or_swizzled(e0, end_bytes)} {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, sz = self.tmp(), self.cu(4)
|
|
self.emit(f"{fc} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}")
|
|
for fcode, (fsz, _, _) in self.FORMATS.items():
|
|
if fsz != 4:
|
|
e, n = self.tmp(), self.tmp()
|
|
self.emit(f"{e} = OpIEqual %bool {fc} {self.cu(fcode)}")
|
|
self.emit(f"{n} = OpSelect %uint {e} {self.cu(fsz)} {sz}")
|
|
sz = n
|
|
size = self.tmp()
|
|
self.emit(f"{size} = OpUConvert %ulong {sz}")
|
|
in_b = check_end(size)
|
|
return addr, d3, in_b, step
|
|
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
|
|
return addr, d3, in_b, (check if mode in (None, 0, 3) else None), step
|
|
return addr, d3, in_b, step
|
|
|
|
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")
|
|
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]
|
|
v2, f, iv = self.tmp(), self.tmp(), self.tmp()
|
|
sh = self.tmp()
|
|
self.emit(f"{sh} = OpShiftRightLogical %uint {r} {self.cu(16 * (i % 2))}")
|
|
self.emit(f"{iv} = OpBitwiseAnd %uint {sh} {self.cu(0xFFFF)}")
|
|
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)
|
|
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} Aligned 4")
|
|
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)
|
|
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} Aligned 4")
|
|
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 = []
|
|
for component in ic[:n]:
|
|
extended = self.tmp()
|
|
self.emit(f"{extended} = OpBitFieldSExtract %int {self.as_int(component)} {self.cu(0)} {self.cu(16)}")
|
|
signed_ic.append(self.tou(extended))
|
|
formats = self.FORMATS.items() if fmt is not None else [(fixed_fmt, self.FORMATS[fixed_fmt])]
|
|
for code, (size, kind, widths) in formats:
|
|
if fmt is not None:
|
|
e = self.tmp()
|
|
self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code)}")
|
|
ld, le = self.tmp() + "_s", self.tmp() + "_se"
|
|
self.emit(f"OpSelectionMerge {le} None")
|
|
self.emit(f"OpBranchConditional {e} {ld} {le}")
|
|
self.emit(f"{ld} = OpLabel")
|
|
ncomp = min(len(widths), n)
|
|
source = normalized if kind in ("unorm", "snorm") 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} Aligned 4")
|
|
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)}")
|
|
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}")
|
|
if fmt is not None:
|
|
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):
|
|
"""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."""
|
|
x, mask = self.src_f(a[-2]), self.src_u(a[-1])
|
|
u = self.tou(x)
|
|
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)
|
|
|
|
def b(cond_line):
|
|
t = self.tmp()
|
|
self.emit(f"{t} = {cond_line}")
|
|
return t
|
|
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)}")
|
|
man_nz = b(f"OpLogicalNot %bool {man0}")
|
|
is_inf = b(f"OpLogicalAnd %bool {expmax} {man0}")
|
|
is_nan = b(f"OpLogicalAnd %bool {expmax} {man_nz}")
|
|
quiet = b(f"OpUGreaterThanEqual %bool {man} {self.cu(0x400000)}")
|
|
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)}")
|
|
d = a[0]
|
|
if len(a) == 2 or (d["k"] == "special" and d["t"] in ("vcc", "vcc_lo")):
|
|
self.emit(f"OpStore %vcc {r}")
|
|
else:
|
|
self.mask_dst(d, 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
|
|
|
|
# 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)}")
|
|
if self.lds_dwords & (self.lds_dwords - 1): # shrunk to fit the limit (fit_shared_memory)
|
|
self.emit(f"{m} = OpUMod %uint {i} {self.cu(self.lds_dwords)}")
|
|
else:
|
|
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_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
|
|
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)
|
|
sizes = {"b32": 1, "b64": 2, "b96": 3, "b128": 4}
|
|
if op in ("ds_read_b32", "ds_read_b64", "ds_read_b96", "ds_read_b128"):
|
|
addr = self.src_u(a[1])
|
|
for k in range(sizes[op.rsplit("_", 1)[1]]):
|
|
v = self.tmp()
|
|
self.emit(f"{v} = OpLoad %uint {self.lds_ptr(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(sizes[op.rsplit("_", 1)[1]]):
|
|
v = self.load_reg("vgpr", a[1]["r"] + k)
|
|
self.emit(f"OpStore {self.lds_ptr(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
|
|
unit = 4 * words * (64 if "st64" in op else 1)
|
|
offs = (self.mod_int(mods, "offset0", 0) * unit, self.mod_int(mods, "offset1", 0) * unit)
|
|
if op.startswith("ds_read2"):
|
|
addr = self.src_u(a[1])
|
|
vals = []
|
|
for o in offs:
|
|
for w in range(words):
|
|
v = self.tmp()
|
|
self.emit(f"{v} = OpLoad %uint {self.lds_ptr(addr, o + 4 * w)}")
|
|
vals.append(v)
|
|
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:
|
|
addr = self.src_u(a[0])
|
|
for k, o in enumerate(offs):
|
|
data = a[1 + k]
|
|
for w in range(words):
|
|
if words == 1:
|
|
v = self.src_u(data)
|
|
elif data["k"] == "vgpr" and data.get("n") == 2:
|
|
v = self.load_reg("vgpr", data["r"] + w)
|
|
else:
|
|
raise Unsupported(op + " data")
|
|
self.emit(f"OpStore {self.lds_ptr(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)}")
|
|
self.emit(f"{w} = OpLoad %uint {self.lds_ptr(addr, off)}")
|
|
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}")
|
|
p = self.lds_ptr(addr, off)
|
|
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}")
|
|
elif name in self.LDS_ATOMICS:
|
|
d, ad, dat = (a[0], a[1], a[2]) if rtn else (None, a[0], a[1])
|
|
p = self.lds_ptr(self.src_u(ad), off)
|
|
old = self.tmp()
|
|
self.emit(f"{old} = {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")):
|
|
p = self.lds_ptr(addr, self.mod_int(mods, name, 0) * unit)
|
|
old = self.tmp()
|
|
self.emit(f"{old} = 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.tmp()
|
|
self.emit(f"{old} = OpAtomicExchange %uint {self.lds_ptr(addr, o + 4 * w)} {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.tmp()
|
|
self.emit(f"{old} = {k} %uint {self.lds_ptr(addr, off + 4 * w)} {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])
|
|
p = self.lds_ptr(self.src_u(ad), off)
|
|
inv, old, _or = self.tmp(), self.tmp(), self.tmp()
|
|
m_val, d_val = self.src_u(msk), self.src_u(dat)
|
|
self.emit(f"{inv} = OpNot %uint {m_val}")
|
|
self.emit(f"{old} = OpAtomicAnd %uint {p} {sc} {sem} {inv}")
|
|
self.emit(f"{_or} = OpAtomicOr %uint {p} {sc} {sem} {d_val}")
|
|
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])
|
|
p = self.lds_ptr(self.src_u(ad), off)
|
|
old = self.tmp()
|
|
self.emit(f"{old} = OpAtomicCompareExchange %uint {p} {sc} {sem} {sem} {self.src_u(src)} {self.src_u(cmp_)}")
|
|
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
|
|
|
|
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, which is
|
|
the hardware lane when the runtime runs them with subgroup size == wave size."""
|
|
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:
|
|
self.uses_subgroup = True
|
|
self.emit(f"{lane} = OpLoad %uint %sg_lane")
|
|
return lane
|
|
|
|
# ---- 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
|
|
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)."""
|
|
return 4 * (self.x_sizes()[3] + 1) if self.emulate else 12 if self.bar_rounds else 0
|
|
|
|
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 what is left (lds_ptr then wraps with OpUMod; addresses below the need are unchanged).
|
|
%x_buf is already sized to the workgroup, so when even the need does not fit, assemble refuses the shader."""
|
|
if not self.cs:
|
|
return
|
|
room = (MAX_SHARED_BYTES - self.x_buf_bytes()) // 4
|
|
if self.lds_dwords > room >= max(self.lds_need, 1):
|
|
self.lds_dwords = room
|
|
self.cu(room)
|
|
|
|
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.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_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_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. Both are only valid in the code emitted after this call, which
|
|
runs one round later."""
|
|
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_word(j)
|
|
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). Not ordered: sampling an
|
|
image the wave wrote."""
|
|
if op in ("ds_swizzle_b32", "ds_bpermute_b32", "ds_permute_b32"):
|
|
return
|
|
if op.startswith("ds_"):
|
|
kind = "lds"
|
|
elif op.startswith(("buffer_", "tbuffer_", "global_", "flat_", "image_load", "image_store", "image_atomic",
|
|
"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"))
|
|
if (kind, "w") in self.x_dirty or (writes and (kind, "r") in self.x_dirty):
|
|
self.x_split()
|
|
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:
|
|
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, zero_inactive=False):
|
|
"""r = v of lane `src` of this wave (OpGroupNonUniformShuffle; emulated: any lane 0-63). zero_inactive:
|
|
a source lane that is off in EXEC gives 0 (ds_bpermute)."""
|
|
if not self.emulate:
|
|
self.emit(f"{r} = OpGroupNonUniformShuffle %uint %c3 {v} {src}")
|
|
return
|
|
if zero_inactive:
|
|
z = self.tmp()
|
|
self.emit(f"{z} = OpSelect %uint {self.active_b()} {v} {self.cu(0)}")
|
|
v = z
|
|
read = self.x_round(data=v)[0]
|
|
self.emit(f"{r} = OpCopyObject %uint {read(src)}")
|
|
|
|
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)}")
|
|
if self.wave64:
|
|
sgl = self.tmp()
|
|
self.emit(f"{sgl} = OpLoad %uint %sg_lane")
|
|
self.emit(f"{half} = OpBitwiseAnd %uint {sgl} {self.cu(32)}")
|
|
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:
|
|
src = self.tmp()
|
|
self.emit(f"{src} = OpBitwiseOr %uint {half} {self.cu(j)}")
|
|
ex, shv, v, shd, hit, nxt = (self.tmp() for _ in range(6))
|
|
# a shuffle from a lane that isn't running (the missing lanes of a partial wave) is undefined
|
|
self.emit(f"{ex} = OpGroupNonUniformBallotBitExtract %bool %c3 {bal} {src}")
|
|
self.emit(f"{shv} = OpGroupNonUniformShuffle %uint %c3 {tp} {src}")
|
|
self.emit(f"{v} = OpSelect %uint {ex} {shv} {self.cu(0)}")
|
|
self.emit(f"{shd} = OpGroupNonUniformShuffle %uint %c3 {dat} {src}")
|
|
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:
|
|
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. RDNA2 is unmeasured."""
|
|
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."""
|
|
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")
|
|
|
|
def sop2_b32_srcs(self, op, a):
|
|
"""The two sources of a 32-bit SOP2. In a wave32 program a bitwise op (or s_cselect) that writes EXEC / VCC
|
|
reads both through mask_src, 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. Data ops, and wave64 programs (a b32 op there is on one half of a mask), are unchanged."""
|
|
if op in self.MASK_SOP2_B32 and not self.wave64 and len(a) >= 3:
|
|
d = a[0]
|
|
to_mask = d["k"] == "special" and d.get("t", "") in ("exec_lo", "vcc_lo", "exec", "vcc")
|
|
maskable = all(x["k"] in ("sgpr", "imm") or (x["k"] == "special" and
|
|
x.get("t", "").startswith(("exec", "vcc"))) for x in a[1:3])
|
|
# Only when the result is a mask (EXEC / VCC destination). An SGPR destination is classified by
|
|
# lane_masks.py, which calls it data when the other operand is a constant; a per-lane bit stored there
|
|
# would then be counted as data (s_and_b32 s20, exec_lo, 1; s_bcnt1_i32_b32 s21, s20 gave 32 and 0
|
|
# instead of 1, found by @Pierre-Kookis on #1792), so that case keeps the data read.
|
|
if maskable and to_mask:
|
|
return self.mask_src(a[1], wide=False), self.mask_src(a[2], wide=False)
|
|
return self.src_u(a[1]), self.src_u(a[2])
|
|
|
|
def scc_logic(self, a, r):
|
|
"""SCC of a 32-bit bitwise SOP2 (s_and/or/xor/andn2/orn2/nand/nor/xnor_b32): D != 0. In a wave32 program
|
|
an operation on lane masks (a source holds one, or it writes EXEC) has the whole wave's mask as D, so SCC
|
|
is the vote of scc_from_mask, as for the _b64 forms. Until 2026-11-22 it was this lane's bit instead:
|
|
`s_and_b32 s0, vcc_lo, exec_lo; s_cbranch_scc0` skipped the block in the lanes whose own bit was 0
|
|
although the wave runs it, and a loop closed by `s_andn2_b32 exec_lo, ...; s_cbranch_scc1` let each lane
|
|
leave on its last iteration, before the wave did (tools/cf_diff.py, FUZZ-8). In a wave64 program the
|
|
same op works on one half of a mask (lanes 0-31 or 32-63), whose SCC would be a vote of that half only;
|
|
that case still takes the lane's bit and is not covered by the fuzzer yet."""
|
|
writes_exec = a[0]["k"] == "special" and a[0].get("t", "").startswith("exec")
|
|
if not self.wave64 and (writes_exec or self.holds_lane_mask(a[1]) or self.holds_lane_mask(a[2])):
|
|
self.scc_from_mask(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)."""
|
|
self.lane_masks, self.mask_writes = lane_masks.analyse(*blocks)
|
|
# 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)
|
|
self.parked = {slot: self.SGPRS + i for i, slot in enumerate(slots)}
|
|
|
|
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 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"
|
|
return None
|
|
|
|
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", "")
|
|
return t.startswith("exec") or (t in ("vcc", "vcc_lo") and "vcc" in self.cur_masks) or \
|
|
(t == "vcc_hi" and self.wave64 and "vcc" in self.cur_masks)
|
|
return a["k"] == "sgpr" and all(a["r"] + i in self.cur_masks for i in range(a.get("n", 1)))
|
|
|
|
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 = self.uses_wave_bits = 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":
|
|
key = ("v", self.x_gen, self.x_tok.get(("sgpr", a["r"]), ("start", a["r"])))
|
|
elif a["k"] == "special" and a["t"] in ("vcc", "vcc_lo", "vcc_hi"):
|
|
key = ("v", self.x_gen, self.x_tok.get("%vcc", ("start", "vcc")))
|
|
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
|
|
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 lo, 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 quad ops do it (the invocations of a quad are 4 consecutive subgroup
|
|
invocations; in a fragment shader the 2x2 quad, which on hardware is also 4 consecutive lanes; vertex,
|
|
geometry and mesh shaders shuffle, as quad operations are only guaranteed in fragment and compute stages);
|
|
emulated, the four lanes' values are read through the exchange buffer. Not handled: an absent invocation in
|
|
a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value natively."""
|
|
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 in ("ps", "cs"):
|
|
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:
|
|
# Quad operations are only guaranteed in fragment and compute shaders (quadOperationsInAllStages):
|
|
# vertex, geometry and mesh shaders shuffle from the four lanes of the quad instead.
|
|
self.uses_subgroup = True
|
|
lane, base = self.tmp(), self.tmp()
|
|
self.sub_lane(lane)
|
|
self.emit(f"{base} = OpBitwiseAnd %uint {lane} {self.cu(0xFFFFFFFC)}")
|
|
acc = b
|
|
for k in range(4):
|
|
i, w, o = self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{i} = OpIAdd %uint {base} {self.cu(k)}")
|
|
self.g_shuffle(w, b, i)
|
|
self.emit(f"{o} = OpBitwiseOr %uint {acc} {w}")
|
|
acc = o
|
|
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}")
|
|
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."""
|
|
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(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)]
|
|
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])
|
|
else:
|
|
# EXEC / VCC filled from data: this lane takes its own bit of the result.
|
|
lane = self.wave_lane()
|
|
sh, b, pick = self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{sh} = OpBitwiseAnd %uint {lane} {self.cu(31)}")
|
|
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]}")
|
|
self.emit(f"{b} = OpBitFieldUExtract %uint {word} {sh} {self.cu(1)}")
|
|
self.emit(f"{pick} = OpSelect %uint {self.tmp_bool_nz(b)} {self.cu(0xFFFFFFFF)} {self.cu(0)}")
|
|
self.put_mask(d, pick, half)
|
|
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 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):
|
|
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
|
|
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
|
|
if a["k"] == "special" and a["t"] in ("vcc", "vcc_lo", "vcc_hi"):
|
|
v = self.tmp()
|
|
self.emit(f"{v} = OpLoad %uint %vcc")
|
|
return v
|
|
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
|
|
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 src64_data(self, s, op):
|
|
if s["k"] == "sgpr" and s.get("n") == 2:
|
|
return self.load_reg("sgpr", s["r"]), self.load_reg("sgpr", 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")
|
|
|
|
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 mask_dst(self, d, v):
|
|
if 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}")
|
|
else:
|
|
raise Unsupported("mask destination")
|
|
|
|
def clamp_mods(self, v, mods):
|
|
# Output modifier (mul:2 / mul:4 / div:2) is applied before clamp, as on hardware.
|
|
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:
|
|
g = self.tmp()
|
|
self.emit(f"{g} = OpExtInst %float %glsl FClamp {v} %f0 %f1")
|
|
return g
|
|
return v
|
|
|
|
def flush_f32(self, f):
|
|
"""v_mad_f32, v_mac_f32 and v_mad_legacy_f32 have no f32 denormal support: 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. Emulated 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)."""
|
|
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 clamp_mods_f64(self, v, mods):
|
|
"""clamp_mods for a %double result (VOP3 f64 arithmetic): 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)."""
|
|
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 fconst(self, x):
|
|
bits = struct.unpack("<I", struct.pack("<f", x))[0]
|
|
return self.tof(self.cu(bits))
|
|
|
|
def dconst(self, x):
|
|
"""A %double value (needs uses_f64): the two words of x, bitcast."""
|
|
bits = struct.unpack("<Q", struct.pack("<d", x))[0]
|
|
v2, d = self.tmp(), self.tmp()
|
|
self.emit(f"{v2} = OpCompositeConstruct %v2uint_d {self.cu(bits & 0xFFFFFFFF)} {self.cu(bits >> 32)}")
|
|
self.emit(f"{d} = OpBitcast %double {v2}")
|
|
return d
|
|
|
|
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
|
|
|
|
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 = []
|
|
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("<I", struct.pack("<f", s["v"]))[0]
|
|
if bits is not None:
|
|
if sel is None:
|
|
is_nan = (bits & 0x7F800000) == 0x7F800000 and bits & 0x7FFFFF
|
|
else:
|
|
h = (bits >> 16 if sel[i] else bits) & 0xFFFF
|
|
is_nan = (h & 0x7C00) == 0x7C00 and h & 0x3FF
|
|
if not is_nan:
|
|
continue
|
|
c = self.tmp()
|
|
self.emit(f"{c} = OpIsNan %bool {v}")
|
|
checks.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
|
|
mn, r = self.tmp(), self.tmp()
|
|
self.emit(f"{mn} = OpExtInst %float %glsl NMin {lo} {z}")
|
|
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<i>_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_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"]
|
|
if self.emulate:
|
|
self.x_memory_order(base_op(ins["op"]))
|
|
if ins["op"].endswith("_dpp"):
|
|
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
|
|
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 and (kv.get("dst_sel", "DWORD") != "DWORD"):
|
|
args[0]["sdwa_dst"] = (kv["dst_sel"], kv.get("dst_unused", "UNUSED_PAD"))
|
|
return self._insn({**ins, "args": args})
|
|
|
|
def sdwa_src(self, v, a):
|
|
off, width = self.SDWA_SEL[a["sdwa_sel"]]
|
|
if width == 32:
|
|
return v
|
|
r = self.tmp()
|
|
f = "OpBitFieldSExtract" if a.get("sext") else "OpBitFieldUExtract"
|
|
self.emit(f"{r} = {f} %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 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")
|
|
if args[0].get("k") != "vgpr" or args[0].get("n", 1) != 1:
|
|
raise Unsupported("DPP destination")
|
|
if args[1].get("n", 1) != 1:
|
|
raise Unsupported("DPP 64-bit source")
|
|
src = args[1]
|
|
src_val = self.src_u(src) # neg/abs are lane-uniform, so before or after the shuffle is the same
|
|
|
|
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 before the shuffle: its value is discarded below, but the lane index
|
|
# passed to OpGroupNonUniformShuffle must still be in range.
|
|
safe_sg = self.tmp()
|
|
self.emit(f"{safe_sg} = OpSelect %uint {in_bounds} {src_sg} {self.cu(0)}")
|
|
else:
|
|
safe_sg = src_sg
|
|
|
|
if fi:
|
|
# fi:1 fetches the inactive source as well; only an out-of-row lane is still invalid.
|
|
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
|
|
active = self.tmp()
|
|
self.emit(f"{active} = OpGroupNonUniformBallotBitExtract %bool {self.cu(3)} {ballot} {safe_sg}")
|
|
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":
|
|
self.uses_subgroup = True
|
|
shuffled = self.tmp()
|
|
self.emit(f"{shuffled} = OpGroupNonUniformShuffle %uint {self.cu(3)} {src_val} {safe_sg}")
|
|
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 dpp8 is not None or bound:
|
|
write = enabled
|
|
else:
|
|
write = self.tmp()
|
|
self.emit(f"{write} = OpLogicalAnd %bool {enabled} {src_ok}")
|
|
args[1] = {"k": "ssa", "v": src0}
|
|
previous = self.dpp_guard
|
|
self.dpp_guard = write
|
|
try:
|
|
return self._insn({**ins, "args": args})
|
|
finally:
|
|
self.dpp_guard = previous
|
|
|
|
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()
|
|
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":
|
|
m = self.tmp()
|
|
self.emit(f"{m} = OpLoad %uint %m0")
|
|
self.emit(f"OpStore %ms_counts {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 in ("s_denorm_mode", "s_round_mode"):
|
|
raise Unsupported(op + " (not in the corpus; MODE is modelled through s_setreg only)")
|
|
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("<I", struct.pack("<f", src["v"]))[0]
|
|
# an SGPR that isn't a mask (a constant, say) gives each lane its own bit, as a constant does (mask_src)
|
|
val = None if const is not None else (self.mask_src(src, wide=False) if src["k"] == "sgpr"
|
|
else self.src_u(src))
|
|
self.exec_half_write(0 if a[0]["t"] == "exec_lo" else 1, val, const)
|
|
elif op == "v_mov_b32" or op == "s_mov_b32":
|
|
lit_val = None
|
|
if op == "s_mov_b32" and a[0]["k"] == "sgpr" and self.desc_cache_ok():
|
|
if a[1]["k"] == "imm":
|
|
lit_val = a[1]["v"] & 0xFFFFFFFF # a literal S# word, see gather_addr_modes
|
|
elif a[1]["k"] == "sgpr":
|
|
lit_val = self.sgpr_imm.get(a[1]["r"])
|
|
self.dst(a[0], self.src_u(a[1]))
|
|
if lit_val is not None:
|
|
self.sgpr_imm[a[0]["r"]] = lit_val
|
|
elif op == "s_mov_b64":
|
|
self.mov64(a[0], a[1])
|
|
elif op in ("v_max3_f32", "v_min3_f32"):
|
|
x, y, z = (self.src_f(t) for t in a[1:4])
|
|
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} {x} {y}")
|
|
self.emit(f"{r} = OpExtInst %float %glsl {f} {m} {z}")
|
|
self.dst(a[0], self.tou(self.clamp_mods(r, mods)))
|
|
elif op == "v_and_or_b32":
|
|
x, y, z = (self.src_u(t) for t in a[1:4])
|
|
m, r = self.tmp(), self.tmp()
|
|
self.emit(f"{m} = OpBitwiseAnd %uint {x} {y}")
|
|
self.emit(f"{r} = OpBitwiseOr %uint {m} {z}")
|
|
self.dst(a[0], r)
|
|
elif op == "s_brev_b64":
|
|
# D = the 64 bits of S0 in reverse order: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). SCC is not
|
|
# written. 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 # 64-bit inline/literal constant: sign-extended
|
|
lo, hi = self.cu(v & 0xFFFFFFFF), self.cu(v >> 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"
|
|
if self.is_mask_op(x) or (d["k"] == "special" and d.get("t", "").startswith(("exec", "vcc"))):
|
|
raise Unsupported(op + " on a lane mask")
|
|
if 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 half in (0, 16):
|
|
t = self.tmp()
|
|
self.emit(f"{t} = OpShiftRightLogical %uint {words[0]} {self.cu(half)}")
|
|
# Spread the 16 bits to the even positions, then copy each to the odd one above it.
|
|
for sh, m in ((None, 0xFFFF), (8, 0x00FF00FF), (4, 0x0F0F0F0F), (2, 0x33333333),
|
|
(1, 0x55555555)):
|
|
if sh is not None:
|
|
u, o = self.tmp(), self.tmp()
|
|
self.emit(f"{u} = OpShiftLeftLogical %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
|
|
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:
|
|
v2, f = self.tmp(), self.tmp()
|
|
self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {h}")
|
|
self.emit(f"{f} = OpCompositeExtract %float {v2} 0")
|
|
h = self.f16_bits(self.clamp_mods(f, ["clamp"])) # exact: the clamped value is an f16
|
|
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.
|
|
if a[1]["k"] == "vgpr" and ("v", a[1]["r"]) in self.cur_masks:
|
|
# A lane mask that went through the vector unit (three SGPRs ORed with v_or3_b32, say). The
|
|
# hardware reads the first lane's copy of the whole mask; here the lane's own copy is its bit.
|
|
self.dst(a[0], self.src_u(a[1]))
|
|
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}")
|
|
self.dst(a[0], read(first))
|
|
return
|
|
self.uses_subgroup = self.uses_ballot = self.uses_vote = True
|
|
v, act = self.src_u(a[1]), self.active_b()
|
|
bal, lsb, any_, first, r = (self.tmp() for _ in range(5))
|
|
self.emit(f"{bal} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} {act}")
|
|
self.emit(f"{lsb} = OpGroupNonUniformBallotFindLSB %uint {self.cu(3)} {bal}")
|
|
self.emit(f"{any_} = OpGroupNonUniformAny %bool {self.cu(3)} {act}")
|
|
self.emit(f"{first} = OpSelect %uint {any_} {lsb} {self.cu(0)}")
|
|
self.emit(f"{r} = OpGroupNonUniformShuffle %uint {self.cu(3)} {v} {first}")
|
|
self.dst(a[0], r)
|
|
elif op in ("image_sample_o", "image_sample_lz_o", "image_sample_l_o", "image_sample_b_o",
|
|
"image_sample_c_lz_o") or op in ("image_sample", "image_sample_lz", "image_sample_l", "image_sample_b", "image_sample_c_lz",
|
|
"image_sample_d", "image_sample_d_cl", "image_load", "image_gather4_lz", "image_gather4_l",
|
|
"image_gather4_lz_o", "image_gather4_l_o"):
|
|
self.image_op(op, a, mods)
|
|
elif op in ("v_sin_f16", "v_cos_f16"):
|
|
u = self.src_h(a[1])
|
|
v2, f, r = self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}")
|
|
self.emit(f"{f} = OpCompositeExtract %float {v2} 0")
|
|
f = self.modify_f(f, a[1])
|
|
t = self.turn_angle(f)
|
|
self.emit(f"{r} = OpExtInst %float %glsl {'Sin' if 'sin' in op else 'Cos'} {t}")
|
|
r = self.clamp_mods(r, mods)
|
|
self.write_lo16(a[0], self.f16_bits(r)) # 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 (add/sub/mad) saturates the half to its type's range; the exact value fits in
|
|
# 32 bits (0xFFFF * 0xFFFF + 0xFFFF < 2^32, and the i16 forms within int32). neg_lo/neg_hi are float-only.
|
|
# A constant operand reads as its low 16 bits; its high half under op_sel is not measured for integer
|
|
# ops (for f16 constants it reads +0.0, see src_h), so that form is rejected rather than guessed.
|
|
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(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
|
|
if clamp and kind not in ("add", "sub", "mad"):
|
|
raise Unsupported(op + " clamp")
|
|
for i in range(ns):
|
|
if a[1 + i]["k"] not in ("vgpr", "sgpr") and (sel[i] or selhi[i]):
|
|
raise Unsupported(op + " high half of a constant")
|
|
srcs = [self.src_u(t) for t in a[1:1 + ns]]
|
|
ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract"
|
|
halves = []
|
|
for sl in (sel, selhi):
|
|
v = []
|
|
for i in range(ns):
|
|
e = self.tmp()
|
|
self.emit(f"{e} = {ext} %uint {srcs[i]} {self.cu(16 * sl[i])} {self.cu(16)}")
|
|
v.append(e)
|
|
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":
|
|
self.emit(f"{r} = OpIMul %uint {v[0]} {v[1]}")
|
|
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"):
|
|
# Packed integer dot products (RDNA2 ISA VOP3P):
|
|
# D = sum_{k=0..N-1} (S0.elem[k] * S1.elem[k]) + S2
|
|
# Wrapping at 32 bits by default; VOP3P clamp saturates to [INT32_MIN, INT32_MAX] (signed) or
|
|
# [0, UINT32_MAX] (unsigned). Hardware default is op_sel:[0,0,0] and op_sel_hi:[1,1,1] (op_sel_hi[k] = 0
|
|
# selects the low half for lane 1 of S_k on v_dot2_*); any other op_sel/op_sel_hi, neg_lo/neg_hi,
|
|
# DPP/SDWA, or source neg/abs are refused.
|
|
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")
|
|
width = 16 if "_dot2_" in op else (8 if "_dot4" in op else 4)
|
|
signed = op.endswith(("i16", "i4"))
|
|
clamp = "clamp" in mods
|
|
ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract"
|
|
x, y, acc = self.src_u(a[1]), self.src_u(a[2]), self.src_u(a[3])
|
|
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_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.
|
|
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
|
|
sel, selhi = bits("op_sel", [0, 0]), bits("op_sel_hi", [1, 1])
|
|
sh_src, val_src = self.src_u(a[1]), self.src_u(a[2])
|
|
halves = []
|
|
for h, sl in ((0, sel), (1, selhi)):
|
|
amt, val, am, r16 = self.tmp(), self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{amt} = OpBitFieldUExtract %uint {sh_src} {self.cu(16 * sl[0])} {self.cu(4)}")
|
|
ext = "OpBitFieldSExtract" if op.endswith("i16") else "OpBitFieldUExtract"
|
|
self.emit(f"{val} = {ext} %uint {val_src} {self.cu(16 * sl[1])} {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}")
|
|
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.
|
|
x, y, z = (self.src_f(t) for t in a[1:4])
|
|
m, r = self.tmp(), self.tmp()
|
|
self.emit(f"{m} = OpFMul %float {x} {y}")
|
|
self.emit(f"{r} = OpFAdd %float {m} {z}")
|
|
self.dst(a[0], self.tou(r))
|
|
elif op in ("v_bfi_b32", "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 == "v_bfi_b32":
|
|
p, n, q = self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{p} = OpBitwiseAnd %uint {x} {y}")
|
|
self.emit(f"{n} = OpNot %uint {x}")
|
|
self.emit(f"{q} = OpBitwiseAnd %uint {n} {z}")
|
|
self.emit(f"{r} = OpBitwiseOr %uint {p} {q}")
|
|
elif 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 a Radeon 680M (gfx1036) ``-v0`` turned 0x7c01 into 0xfc01 under IEEE 0 and
|
|
# 0xfe01 under IEEE 1, in either half and with op_sel (#1548 SHADER-260). abs rests on the ISA's sign
|
|
# clear, it was not measured on this instruction. Only the IEEE 1 sNaN quieting is open (SHADER-190).
|
|
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)
|
|
if sb[i]:
|
|
s = self.tmp()
|
|
self.emit(f"{s} = OpShiftRightLogical %uint {u} {self.cu(16)}")
|
|
u = s
|
|
m = self.tmp()
|
|
self.emit(f"{m} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}")
|
|
if src.get("abs"):
|
|
# The ISA defines ABS on a float operand as |S|, a clear of the sign bit, and it is applied before
|
|
# neg; no hardware run of this instruction with `abs` exists yet.
|
|
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"):
|
|
self.cmp_class(a, exec_only=op == "v_cmpx_class_f32")
|
|
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.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:
|
|
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":
|
|
m = pick(z, y, x)
|
|
r = self.tmp()
|
|
self.emit(f"{r} = OpFMul %float {m} {self.fconst(2.0)}")
|
|
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
|
|
mask = self.wave_mask(a[1])[0 if op.endswith("lo_u32_b32") else 1]
|
|
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]
|
|
self.emit(f"{inrange} = OpULessThan %bool {rel} {self.cu(32)}")
|
|
self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {rel}")
|
|
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])
|
|
wm, om, one, m1, r = (self.tmp() for _ in range(5))
|
|
self.emit(f"{wm} = OpBitwiseAnd %uint {w} {self.cu(31)}")
|
|
self.emit(f"{om} = OpBitwiseAnd %uint {o} {self.cu(31)}")
|
|
self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {wm}")
|
|
self.emit(f"{m1} = OpISub %uint {one} {self.cu(1)}")
|
|
self.emit(f"{r} = OpShiftLeftLogical %uint {m1} {om}")
|
|
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
|
|
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. The pair is 64-bit data (as for
|
|
# s_lshl_b64); a lane-mask source stays Unsupported (#210).
|
|
x = a[1]
|
|
if self.holds_lane_mask(x):
|
|
raise Unsupported(op + " of a lane mask")
|
|
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")
|
|
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") or a[1]["k"] == "imm":
|
|
# A b32 source is a plain scalar value, not a lane mask; for b64 an immediate is the low word.
|
|
lo, hi = self.src_u(a[1]), 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_add_f64", "v_cvt_f32_f64"):
|
|
# f64: register pairs as doubles (shaderFloat64). neg/abs modifiers apply to the double.
|
|
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"] == "imm" or sv["k"] == "fimm":
|
|
import struct as _st
|
|
bits = _st.unpack("<Q", _st.pack("<d", float(sv["v"])))[0] if sv["k"] == "fimm" else sv["v"] & 0xFFFFFFFFFFFFFFFF
|
|
lo, hi = self.cu(bits & 0xFFFFFFFF), self.cu(bits >> 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
|
|
self.uses_f64 = True
|
|
if op == "v_add_f64":
|
|
x, y = f64(a[1]), f64(a[2])
|
|
r, v2, lo, hi = self.tmp(), self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{r} = OpFAdd %double {x} {y}")
|
|
if self.round_mode:
|
|
# MODE rounds the sum itself; clamp/omod then apply to the rounded value, as on the hardware.
|
|
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
|
|
# VOP3_Profile<VOP_F64_F64_F64>: HasClamp and HasOMod (LLVM VOPProfile, f64 is a modifier type).
|
|
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")
|
|
d = a[0]
|
|
if d["k"] != "vgpr":
|
|
raise Unsupported(op + " destination")
|
|
self.dst({"k": "vgpr", "r": d["r"], "n": 1}, lo)
|
|
self.dst({"k": "vgpr", "r": d["r"] + 1, "n": 1}, hi)
|
|
else:
|
|
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)))
|
|
elif op in ("image_bvh_intersect_ray", "image_bvh64_intersect_ray"):
|
|
self.image_bvh(op, a, mods)
|
|
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.
|
|
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)
|
|
elif op == "s_bfm_b32":
|
|
# D = ((1 << (S0 & 31)) - 1) << (S1 & 31): an ordinary scalar value
|
|
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)
|
|
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, ln2, r = self.tmp(), self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{s1} = OpIAdd %uint {ad} {self.cu(off)}")
|
|
self.emit(f"{ln} = OpShiftRightLogical %uint {s1} {self.cu(2)}")
|
|
self.emit(f"{ln2} = OpBitwiseAnd %uint {ln} {self.cu(31)}")
|
|
if self.emulate:
|
|
# Wave64 runs it as two wave32s (RDNA ISA 10.4.4): lanes 32-63 read from their own half, and a
|
|
# source lane that is off in EXEC reads as 0.
|
|
half, src = self.tmp(), self.tmp()
|
|
self.emit(f"{half} = OpBitwiseAnd %uint {self.wave_lane()} {self.cu(32)}")
|
|
self.emit(f"{src} = OpBitwiseOr %uint {half} {ln2}")
|
|
self.g_shuffle(r, dat, src, zero_inactive=True)
|
|
else:
|
|
lane = self.tmp()
|
|
self.emit(f"{lane} = OpLoad %uint %sg_lane")
|
|
src = ln2
|
|
if self.wave64:
|
|
half, src = self.tmp(), self.tmp()
|
|
self.emit(f"{half} = OpBitwiseAnd %uint {lane} {self.cu(32)}")
|
|
self.emit(f"{src} = OpBitwiseOr %uint {half} {ln2}")
|
|
# EXEC-off source lanes supply zero. Redirect missing source lanes to the calling lane before
|
|
# shuffling so the zero mask never has to consume an undefined result.
|
|
z, bal, ex, safe_src, sh, mask = (self.tmp() for _ in range(6))
|
|
self.emit(f"{z} = OpSelect %uint {self.active_b()} {dat} {self.cu(0)}")
|
|
self.emit(f"{bal} = OpGroupNonUniformBallot %v4uint_bal %c3 %true")
|
|
self.emit(f"{ex} = OpGroupNonUniformBallotBitExtract %bool %c3 {bal} {src}")
|
|
self.emit(f"{safe_src} = OpSelect %uint {ex} {src} {lane}")
|
|
self.emit(f"{sh} = OpGroupNonUniformShuffle %uint %c3 {z} {safe_src}")
|
|
self.emit(f"{mask} = OpSelect %uint {ex} {self.cu(0xFFFFFFFF)} {self.cu(0)}")
|
|
self.emit(f"{r} = OpBitwiseAnd %uint {sh} {mask}")
|
|
self.uses_subgroup = self.uses_ballot = True
|
|
# A scalar select can become a short-circuiting ternary in MSL, moving the ballot and shuffle into
|
|
# divergent control flow. Use bitwise masks for both the result and the destination write.
|
|
self.dst(d, r, eager=not self.emulate)
|
|
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 through s_waitcnt before it, so include workgroup memory.
|
|
if self.stage not in ("cs", "ms"):
|
|
raise Unsupported("s_barrier outside compute")
|
|
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(0x108)}")
|
|
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])
|
|
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)}")
|
|
self.g_shuffle(r, v, m)
|
|
self.dst(a[0], r)
|
|
elif op == "v_writelane_b32":
|
|
# vD[lane] = sS: only the named lane changes (independent of EXEC, as on hardware).
|
|
self.uses_subgroup = True
|
|
val, ln = self.src_u(a[1]), self.src_u(a[2])
|
|
slot = lane_masks.lane_slot(a[0], 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"):
|
|
# The hardware lane: lanes 32-63 of a wave64 are lanes 0-31 of a second 32-wide 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.tmp()
|
|
self.emit(f"{p} = OpAccessChain %_ptr_Function_uint %vgpr {self.cu(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.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"):
|
|
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}")
|
|
r = self.tmp()
|
|
self.g_shuffle(r, v, src)
|
|
self.dst(a[0], r)
|
|
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"):
|
|
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 == "s_bitset1_b32":
|
|
# sD |= 1 << (src & 31) (sD is both source and destination)
|
|
b = self.src_u(a[1])
|
|
m, sh, old, r = (self.tmp() for _ in range(4))
|
|
self.emit(f"{m} = OpBitwiseAnd %uint {b} {self.cu(31)}")
|
|
self.emit(f"{sh} = OpShiftLeftLogical %uint {self.cu(1)} {m}")
|
|
self.emit(f"{old} = OpCopyObject %uint {self.src_u(a[0])}")
|
|
self.emit(f"{r} = OpBitwiseOr %uint {old} {sh}")
|
|
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":
|
|
# Per byte: D.b = (S0.b + S1.b + (bit 0 of S2.b)) >> 1, an unsigned average whose rounding comes from
|
|
# S2 (RDNA ISA pseudocode). The 9-bit sum never reaches past its own byte after the shift.
|
|
if "clamp" in mods:
|
|
raise Unsupported(op + " clamp")
|
|
x, y, z = (self.src_u(t) for t in a[1:4])
|
|
r = None
|
|
for off in (0, 8, 16, 24):
|
|
xb, yb, zb, t1, t2, avg = (self.tmp() for _ in range(6))
|
|
self.emit(f"{xb} = OpBitFieldUExtract %uint {x} {self.cu(off)} {self.cu(8)}")
|
|
self.emit(f"{yb} = OpBitFieldUExtract %uint {y} {self.cu(off)} {self.cu(8)}")
|
|
self.emit(f"{zb} = OpBitFieldUExtract %uint {z} {self.cu(off)} {self.cu(1)}")
|
|
self.emit(f"{t1} = OpIAdd %uint {xb} {yb}")
|
|
self.emit(f"{t2} = OpIAdd %uint {t1} {zb}")
|
|
self.emit(f"{avg} = OpShiftRightLogical %uint {t2} {self.cu(1)}")
|
|
if r is None:
|
|
r = avg
|
|
else:
|
|
sh, o = self.tmp(), self.tmp()
|
|
self.emit(f"{sh} = OpShiftLeftLogical %uint {avg} {self.cu(off)}")
|
|
self.emit(f"{o} = OpBitwiseOr %uint {r} {sh}")
|
|
r = o
|
|
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 = 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 = 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.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])
|
|
def pair64(sv):
|
|
if sv["k"] in ("vgpr", "sgpr") and sv.get("n") == 2:
|
|
return self.load_reg(sv["k"], sv["r"]), self.load_reg(sv["k"], sv["r"] + 1)
|
|
if sv["k"] == "imm":
|
|
v = sv["v"] & 0xFFFFFFFFFFFFFFFF
|
|
return self.cu(v & 0xFFFFFFFF), self.cu(v >> 32)
|
|
raise Unsupported(op + " operand")
|
|
(x0, x1), (y0, y1) = pair64(x), pair64(y)
|
|
cond, signed = op.split("_")[2], op.endswith("_i64")
|
|
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)}")
|
|
if d["k"] == "special" and d["t"] in ("vcc", "vcc_lo"):
|
|
self.emit(f"OpStore %vcc {r}")
|
|
else:
|
|
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: sign-extended from 32 bits.
|
|
v = 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_mods(r, mods)
|
|
self.f16_out(a[0], r, dhi) # GFX10: f16 ops keep the other half
|
|
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_subrev_u16",
|
|
"v_mul_lo_u16", "v_max_u16", "v_min_u16", "v_max_i16", "v_min_i16", "v_and_b16", "v_or_b16",
|
|
"v_xor_b16", "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 = an 8-byte encoding. LLVM 21 prints the VOP3 form of these ops without the _e64 suffix (every
|
|
# one in the game's shaders), so the mnemonic alone would make them VOP2 writes and zero the high half.
|
|
enc = ins.get("enc")
|
|
e64 = len(enc) == 16 if enc else ins["op"].endswith("_e64")
|
|
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[:2] != [0, 0]:
|
|
raise Unsupported(op + " op_sel")
|
|
halves = []
|
|
for k, s in enumerate(a[1:3]):
|
|
u = self.src_u(s)
|
|
if sb[k]:
|
|
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)}")
|
|
halves.append(h)
|
|
x, y = halves
|
|
r = self.tmp()
|
|
if op in ("v_lshrrev_b16", "v_lshlrev_b16", "v_ashrrev_i16"):
|
|
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":
|
|
self.emit(f"{r} = OpShiftRightLogical %uint {y} {sh}")
|
|
elif op == "v_lshlrev_b16":
|
|
self.emit(f"{r} = OpShiftLeftLogical %uint {y} {sh}")
|
|
else:
|
|
yi, ri = self.tmp(), self.tmp()
|
|
self.emit(f"{yi} = OpBitFieldSExtract %int {self.as_int(y)} {self.cu(0)} {self.cu(16)}")
|
|
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, yi, ri = self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{xi} = OpBitFieldSExtract %int {self.as_int(x)} {self.cu(0)} {self.cu(16)}")
|
|
self.emit(f"{yi} = OpBitFieldSExtract %int {self.as_int(y)} {self.cu(0)} {self.cu(16)}")
|
|
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, yi, ri = self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{xi} = OpBitFieldSExtract %int {self.as_int(x)} {self.cu(0)} {self.cu(16)}")
|
|
self.emit(f"{yi} = OpBitFieldSExtract %int {self.as_int(y)} {self.cu(0)} {self.cu(16)}")
|
|
self.emit(f"{ri} = OpExtInst %int %glsl {'SMax' if 'max' in op else 'SMin'} {xi} {yi}")
|
|
self.emit(f"{r} = OpBitcast %uint {ri}")
|
|
else:
|
|
k = {"v_add_u16": "OpIAdd", "v_sub_u16": "OpISub", "v_mul_lo_u16": "OpIMul", "v_and_b16": "OpBitwiseAnd",
|
|
"v_or_b16": "OpBitwiseOr", "v_xor_b16": "OpBitwiseXor"}.get(op)
|
|
if op == "v_subrev_u16":
|
|
self.emit(f"{r} = OpISub %uint {y} {x}")
|
|
elif 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", "v_subrev_u16"):
|
|
raise Unsupported(op + " clamp")
|
|
if op in ("v_add_u16", "v_sub_u16", "v_subrev_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()
|
|
self.emit(f"{lo} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}")
|
|
if e64 and sb[2]:
|
|
# op_sel destination bit: the result goes to the high half, the low half is kept.
|
|
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_)
|
|
if sb[k]:
|
|
t = self.tmp()
|
|
self.emit(f"{t} = OpShiftRightLogical %uint {u} {self.cu(16)}")
|
|
u = t
|
|
h = self.tmp()
|
|
if op == "v_mad_u16":
|
|
self.emit(f"{h} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}")
|
|
else:
|
|
hi_ = self.tmp()
|
|
self.emit(f"{hi_} = OpBitFieldSExtract %int {self.as_int(u)} {self.cu(0)} {self.cu(16)}")
|
|
self.emit(f"{h} = OpBitcast %uint {hi_}")
|
|
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} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}")
|
|
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 not modelled on integer min/max/med3.
|
|
if "clamp" in mods:
|
|
raise Unsupported(op + " clamp")
|
|
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_)
|
|
if sb[k]:
|
|
t = self.tmp()
|
|
self.emit(f"{t} = OpShiftRightLogical %uint {u} {self.cu(16)}")
|
|
u = t
|
|
h = self.tmp()
|
|
if signed:
|
|
self.emit(f"{h} = OpBitFieldSExtract %int {self.as_int(u)} {self.cu(0)} {self.cu(16)}")
|
|
else:
|
|
self.emit(f"{h} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}")
|
|
vals.append(h)
|
|
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} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}")
|
|
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 == "v_bcnt_u32_b32":
|
|
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 == "s_bitset0_b32":
|
|
b = self.src_u(a[1])
|
|
m, sh, n, r = (self.tmp() for _ in range(4))
|
|
self.emit(f"{m} = OpBitwiseAnd %uint {b} {self.cu(31)}")
|
|
self.emit(f"{sh} = OpShiftLeftLogical %uint {self.cu(1)} {m}")
|
|
self.emit(f"{n} = OpNot %uint {sh}")
|
|
self.emit(f"{r} = OpBitwiseAnd %uint {self.src_u(a[0])} {n}")
|
|
self.dst(a[0], r)
|
|
elif op in ("s_min_i32", "s_max_i32"):
|
|
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":
|
|
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_mods(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)
|
|
return [int(v) for v in m.split("[")[1].rstrip("]").split(",")] if m else 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)
|
|
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 = []
|
|
for half_sel, neg in ((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)
|
|
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")
|
|
self.emit(f"{p} = OpCopyObject %uint {self.f16_pack2(c0, c1)}")
|
|
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.
|
|
# As for v_movrel*, the hardware's range check against the VGPR allocation is not modelled.
|
|
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)}")
|
|
ptrs, vals = [], []
|
|
for reg, off in ((d["r"], md), (s0["r"], lo)):
|
|
i, p_, v = self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{i} = OpIAdd %uint {self.cu(reg)} {off}")
|
|
self.emit(f"{p_} = OpAccessChain %_ptr_Function_uint %vgpr {i}")
|
|
self.emit(f"{v} = OpLoad %uint {p_}")
|
|
ptrs.append(p_)
|
|
vals.append(v)
|
|
act = self.active_b()
|
|
# 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 ((ptrs[0], vals[1], vals[0]), (ptrs[1], vals[0], vals[1])):
|
|
sel = self.tmp()
|
|
self.emit(f"{sel} = OpSelect %uint {act} {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).
|
|
d, s = a[0], a[1]
|
|
if d["k"] != "vgpr" or s["k"] != "vgpr":
|
|
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"):
|
|
si, sp, v = self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{si} = OpIAdd %uint {self.cu(s['r'])} {m0_src}")
|
|
self.emit(f"{sp} = OpAccessChain %_ptr_Function_uint %vgpr {si}")
|
|
self.emit(f"{v} = OpLoad %uint {sp}")
|
|
else:
|
|
v = self.load_reg("vgpr", s["r"])
|
|
if op in ("v_movreld_b32", "v_movrelsd_b32", "v_movrelsd_2_b32"):
|
|
di, dp, old, sel = (self.tmp() for _ in range(4))
|
|
self.emit(f"{di} = OpIAdd %uint {self.cu(d['r'])} {m0_dst}")
|
|
self.emit(f"{dp} = OpAccessChain %_ptr_Function_uint %vgpr {di}")
|
|
self.emit(f"{old} = OpLoad %uint {dp}")
|
|
self.emit(f"{sel} = OpSelect %uint {self.active_b()} {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"):
|
|
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])]
|
|
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]}")
|
|
r = self.clamp_mods(r, mods)
|
|
self.f16_out(a[0], r, dhi) # opsel-capable VOP3: keeps the other half (Mesa ACO can_use_opsel)
|
|
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")
|
|
|
|
def pair(sv):
|
|
if sv["k"] in ("vgpr", "sgpr") and sv.get("n") == 2:
|
|
return self.load_reg(sv["k"], sv["r"]), self.load_reg(sv["k"], sv["r"] + 1)
|
|
if sv["k"] == "imm":
|
|
v = sv["v"] & 0xFFFFFFFFFFFFFFFF # 64-bit inline/literal constant: sign-extended
|
|
return self.cu(v & 0xFFFFFFFF), self.cu(v >> 32)
|
|
raise Unsupported(op + " operands")
|
|
(x_lo, x_hi), y, (c_lo, c_hi) = pair(a[1]), self.src_u(a[2]), pair(a[3])
|
|
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.tmp()
|
|
self.emit(f"{total} = OpBitFieldUExtract %uint {acc_w} {self.cu(16 * (k % 2))} {self.cu(16)}")
|
|
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
|
|
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]
|
|
if s0["k"] in ("vgpr", "sgpr") and s0.get("n") == 2:
|
|
x_lo, x_hi = self.load_reg(s0["k"], s0["r"]), self.load_reg(s0["k"], s0["r"] + 1)
|
|
elif s0["k"] == "imm":
|
|
v = s0["v"] & 0xFFFFFFFFFFFFFFFF # 64-bit inline/literal constant: sign-extended
|
|
x_lo, x_hi = self.cu(v & 0xFFFFFFFF), self.cu(v >> 32)
|
|
else:
|
|
raise Unsupported(op + " operands")
|
|
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.
|
|
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:
|
|
self.emit(f"{r} = OpExtInst %float %glsl {fn} {f}")
|
|
else:
|
|
self.emit(f"{r} = OpFDiv %float %f1 {f}")
|
|
if fn == "Fract":
|
|
r = self.fract_below_one(r)
|
|
r = self.clamp_mods(r, mods)
|
|
# 0x3c00 -> 0x3bff only when 0x3c00 is Fract's own rounding: after mul:2 fract(0.5) is a true 1.0.
|
|
omod = any(m in ("mul:2", "mul:4", "div:2") for m in mods)
|
|
# 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" and not omod,
|
|
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":
|
|
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.
|
|
sel, dhi = self.opsel_bits(mods, 2)
|
|
vals = [self.f16_in(s, sel[i]) for i, s in enumerate(a[1:3])]
|
|
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]}")
|
|
r = self.clamp_mods(r, mods)
|
|
self.f16_out(a[0], r, dhi) # 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"] in ("vgpr", "sgpr") and s.get("n") == 2:
|
|
return self.load_reg(s["k"], s["r"]), self.load_reg(s["k"], s["r"] + 1)
|
|
if s["k"] == "imm":
|
|
v = s["v"] & 0xFFFFFFFFFFFFFFFF
|
|
return self.cu(v & 0xFFFFFFFF), self.cu(v >> 32)
|
|
raise Unsupported(op + " operand")
|
|
(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)}")
|
|
if d["k"] == "special" and d["t"] in ("vcc", "vcc_lo"):
|
|
self.emit(f"OpStore %vcc {r}")
|
|
else:
|
|
self.mask_dst(d, r)
|
|
elif op == "s_not_b32":
|
|
x_val = self.imm_val(a[1])
|
|
if x_val is not None:
|
|
val = (~x_val) & 0xFFFFFFFF
|
|
r = self.cu(val)
|
|
self.dst(a[0], r)
|
|
self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}")
|
|
else:
|
|
x = self.src_u(a[1])
|
|
r = self.tmp()
|
|
self.emit(f"{r} = OpNot %uint {x}")
|
|
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 ("s_cmp_eq_u64", "s_cmp_lg_u64"):
|
|
# 64-bit compare of masks/pointers: equal iff both halves are equal.
|
|
m0, m1 = self.holds_lane_mask(a[0]), self.holds_lane_mask(a[1])
|
|
|
|
def _is_u64_zero_or_all_ones(src):
|
|
if src["k"] != "imm":
|
|
return False
|
|
v = src["v"] & 0xFFFFFFFFFFFFFFFF
|
|
return v == 0
|
|
|
|
use_vote = (m0 and m1) or (m0 and _is_u64_zero_or_all_ones(a[1])) or (m1 and _is_u64_zero_or_all_ones(a[0]))
|
|
|
|
def halves(s, is_mask):
|
|
if is_mask and not use_vote:
|
|
return self.wave_mask(s)
|
|
if s["k"] == "sgpr" and s.get("n") == 2:
|
|
return self.load_reg("sgpr", s["r"]), self.load_reg("sgpr", s["r"] + 1)
|
|
if s["k"] == "imm":
|
|
v = s["v"] & 0xFFFFFFFFFFFFFFFF
|
|
return self.cu(v & 0xFFFFFFFF), self.cu(v >> 32)
|
|
m = self.mask_src(s)
|
|
return m, m
|
|
|
|
(x0, x1), (y0, y1) = halves(a[0], m0), halves(a[1], m1)
|
|
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 use_vote:
|
|
eq = self.wave_equal(eq, True)
|
|
if op == "s_cmp_lg_u64":
|
|
ne = self.tmp()
|
|
self.emit(f"{ne} = OpLogicalNot %bool {eq}")
|
|
eq = ne
|
|
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.
|
|
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)
|
|
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":
|
|
# Legacy multiply treats 0 * anything (inf/NaN included) as 0.
|
|
x, y = self.src_f(a[1]), self.src_f(a[2])
|
|
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}")
|
|
self.dst(a[0], self.tou(self.clamp_mods(r, mods)))
|
|
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(self.clamp_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.startswith("s_load_dword") or op.startswith("s_buffer_load_dword"):
|
|
self.scalar_load(op, a, ins["mods"])
|
|
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 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).
|
|
x, y = self.src_u(a[1]), self.src_u(a[2])
|
|
sub = op.startswith("s_sub")
|
|
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}")
|
|
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])
|
|
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)
|
|
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"):
|
|
if op == "s_xor_b32":
|
|
x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2])
|
|
writes_exec = a[0]["k"] == "special" and a[0].get("t", "").startswith("exec")
|
|
is_mask = not self.wave64 and (writes_exec 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:
|
|
val = (x_val ^ y_val) & 0xFFFFFFFF
|
|
r = self.cu(val)
|
|
self.dst(a[0], r)
|
|
self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}")
|
|
return
|
|
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.dst(a[0], r)
|
|
# 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)
|
|
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_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(self.clamp_mods(r, mods))))
|
|
elif op in ("v_mul_lo_u32", "v_min_u32", "v_max_u32", "v_min_i32", "v_max_i32"):
|
|
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. No clamp or
|
|
# output multiplier (rejected rather than guessed). 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"). int -> f16 rounds like every f16 result (f16_out).
|
|
if any(m == "clamp" or m.startswith(("mul:", "div:")) for m in mods):
|
|
raise Unsupported(op + " output modifier")
|
|
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})
|
|
if sel[0]:
|
|
t = self.tmp()
|
|
self.emit(f"{t} = OpShiftRightLogical %uint {u} {self.cu(16)}")
|
|
u = t
|
|
f = self.tmp()
|
|
if op == "v_cvt_f16_u16":
|
|
m = self.tmp()
|
|
self.emit(f"{m} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}")
|
|
self.emit(f"{f} = OpConvertUToF %float {m}")
|
|
else:
|
|
m = self.tmp()
|
|
self.emit(f"{m} = OpBitFieldSExtract %int {self.as_int(u)} {self.cu(0)} {self.cu(16)}")
|
|
self.emit(f"{f} = OpConvertSToF %float {m}")
|
|
self.f16_out(a[0], f, dhi)
|
|
else:
|
|
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}")
|
|
self.emit(f"{lo} = OpBitwiseAnd %uint {conv} {self.cu(0xFFFF)}")
|
|
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). clamp and output multipliers are rejected rather than guessed.
|
|
if any(m == "clamp" or m.startswith(("mul:", "div:")) for m in mods):
|
|
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])
|
|
if sel[0]:
|
|
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 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).
|
|
n = self.src_u(a[2])
|
|
if sel[1]:
|
|
t = self.tmp()
|
|
self.emit(f"{t} = OpShiftRightLogical %uint {n} {self.cu(16)}")
|
|
n = t
|
|
n16, nu, nb, small, neg, lim, nc = (self.tmp() for _ in range(7))
|
|
self.emit(f"{n16} = OpBitFieldSExtract %int {self.as_int(n)} {self.cu(0)} {self.cu(16)}")
|
|
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}")
|
|
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.
|
|
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}")
|
|
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)}")
|
|
self.write_half16(a[0], lo, dhi)
|
|
elif op == "v_cvt_f32_f16":
|
|
u = self.src_h(a[1])
|
|
v2, f = self.tmp(), self.tmp()
|
|
self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}")
|
|
self.emit(f"{f} = OpCompositeExtract %float {v2} 0")
|
|
self.dst(a[0], self.tou(self.clamp_mods(self.modify_f(f, a[1]), mods)))
|
|
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")
|
|
if op == "v_interp_mov_f32":
|
|
sel = a[1] if len(a) > 1 else None
|
|
if not (sel and sel.get("k") == "interp" and sel.get("t") == "p0"):
|
|
what = sel.get("t") if sel is not None and sel.get("k") == "interp" else "operand"
|
|
raise Unsupported(f"v_interp_mov_f32 vertex select {what}: only p0 is modelled")
|
|
else:
|
|
self.interp_pair_src(op, a, ins)
|
|
f = self.attribute(attr["a"], attr["c"], flat=op == "v_interp_mov_f32", ij=self.interp_weights(ins))
|
|
if self.pixel_interpolants is not None and (self.pixel_interpolants[1] >> attr["a"]) & 1:
|
|
# 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") and not op.endswith(("_u64", "_i64")):
|
|
self.compare(op, a, scalar=False, mods=mods)
|
|
elif op.startswith("v_cmpx_") and not op.startswith("v_cmpx_class") and not op.endswith(("_u64", "_i64")):
|
|
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.
|
|
saved = self.exec_value()
|
|
src = self.mask_src(a[1], wide=op.endswith("b64"))
|
|
r = self.exec_logic(op[2:].split("_saveexec")[0], src, saved)
|
|
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).
|
|
x, y = self.mask_src(a[1], wide=op.endswith("b64")), self.exec_value()
|
|
r = self.exec_logic(op[2:].split("_wrexec")[0], x, y)
|
|
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].
|
|
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, sel = (self.src_u(t) for t in a[1:4])
|
|
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", "s_and_b32_mask", "s_or_b32_mask"):
|
|
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 op.endswith("_mask") or \
|
|
(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.
|
|
self.dst(a[0], self.f16_res(self.clamp_mods(f, mods)))
|
|
else: # p1ll/p1lv produce the f32 intermediate consumed by p2_f16
|
|
self.dst(a[0], self.tou(f))
|
|
elif op.startswith("s_cmp_"):
|
|
self.compare(op, a, scalar=True)
|
|
elif op.startswith("s_cmpk_"):
|
|
# s_cmpk_<cond>_<ty> 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.startswith("s_bitcmp"):
|
|
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, 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_mods(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":
|
|
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 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 (not measured on hardware). The whole dword is written.
|
|
if "clamp" in mods:
|
|
raise Unsupported(op + " clamp")
|
|
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")
|
|
self.emit(f"{m} = OpFMul %float {c} {self.fconst(32767.0 if snorm else 65535.0)}")
|
|
self.emit(f"{rr} = OpExtInst %float %glsl RoundEven {m}")
|
|
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 == "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:
|
|
x, y = self.src_f(a[1]), self.src_f(a[2])
|
|
r = self.tmp()
|
|
if F2[op] in ("max", "min"):
|
|
self.emit(f"{r} = OpExtInst %float %glsl {'NMax' if F2[op] == 'max' else 'NMin'} {x} {y}")
|
|
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(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}")
|
|
else:
|
|
self.emit(f"{r} = OpExtInst %float %glsl {F1[op]} {x}")
|
|
if F1[op] == "Fract":
|
|
r = self.fract_below_one(r)
|
|
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).
|
|
x = self.src_u(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_cvt_f32_u32", "v_cvt_f32_i32"):
|
|
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"):
|
|
# 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.
|
|
self.emit(f"{safe_x_u} = OpSelect %uint {x_in_range} {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"):
|
|
# 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:
|
|
if op in S2:
|
|
x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2])
|
|
writes_exec = a[0]["k"] == "special" and a[0].get("t", "").startswith("exec")
|
|
is_mask = not self.wave64 and (writes_exec 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:
|
|
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 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.dst(a[0], r)
|
|
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)
|
|
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":
|
|
v = s2["v"] & 0xFFFFFFFFFFFFFFFF # 64-bit inline/literal constant: sign-extended from 32 bits
|
|
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. S2 and D are whole
|
|
# dwords, so an op_sel bit on them, and clamp, are not modelled: rejected rather than guessed.
|
|
sel, dhi = self.opsel_bits(mods, 3)
|
|
if sel[2] or dhi or "clamp" in mods:
|
|
raise Unsupported(op + " op_sel/clamp")
|
|
ext = "OpBitFieldSExtract" if op == "v_mad_i32_i16" else "OpBitFieldUExtract"
|
|
hs = []
|
|
for i, src in enumerate(a[1:3]):
|
|
h = self.tmp()
|
|
self.emit(f"{h} = {ext} %uint {self.src_u(src)} {self.cu(16 * sel[i])} {self.cu(16)}")
|
|
hs.append(h)
|
|
m, r = self.tmp(), self.tmp()
|
|
self.emit(f"{m} = OpIMul %uint {hs[0]} {hs[1]}")
|
|
self.emit(f"{r} = OpIAdd %uint {m} {self.src_u(a[3])}")
|
|
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.
|
|
# Measured on RDNA2 hardware (docs/design.md, "Signed-byte dot products"), where clamp saturates
|
|
# v_dot4_i32_i8 to a signed 32-bit value and op_sel picks the 16-bit half of a source each half of the
|
|
# product reads. llvm-mc prints neither for the programs measured, so both forms are refused, not guessed.
|
|
# 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.
|
|
if "clamp" in mods or any(m.startswith("op_sel") for m in mods):
|
|
raise Unsupported(op + (" clamp" if "clamp" in mods 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")
|
|
x, y = self.src_u(a[1]), self.src_u(a[2])
|
|
acc = self.src_u(a[3]) if op == "v_dot4_i32_i8" else self.src_u(a[0])
|
|
for i in range(4):
|
|
xb, yb, prod, total = (self.tmp() for _ in range(4))
|
|
self.emit(f"{xb} = OpBitFieldSExtract %uint {x} {self.cu(8 * i)} {self.cu(8)}")
|
|
self.emit(f"{yb} = OpBitFieldSExtract %uint {y} {self.cu(8 * i)} {self.cu(8)}")
|
|
self.emit(f"{prod} = OpIMul %uint {xb} {yb}")
|
|
self.emit(f"{total} = OpIAdd %uint {acc} {prod}")
|
|
acc = total
|
|
self.dst(a[0], acc)
|
|
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
|
|
x, y = self.src_u(a[1]), self.src_u(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 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.
|
|
Not measured, and inferred: s_load with sOFF + IMM < 0 (the 64-bit signed sum is used), x16 (same rule as
|
|
x8), an s_buffer_load immediate with bit 20 set or a negative one (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 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)
|
|
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}")
|
|
ptr = self.tmp()
|
|
self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}")
|
|
self.uses_psb = True
|
|
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)
|
|
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
|
|
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}")
|
|
for i in range(n):
|
|
p, v = self.tmp(), self.tmp()
|
|
if lim is None:
|
|
self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}")
|
|
self.emit(f"{v} = OpLoad %uint {p} Aligned 4")
|
|
elif lim_val is not None and reg is None:
|
|
end_val = imm + 4 * i + 4
|
|
if lim_val >= end_val:
|
|
self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}")
|
|
self.emit(f"{v} = OpLoad %uint {p} Aligned 4")
|
|
else:
|
|
v = self.cu(0)
|
|
else:
|
|
# dword i is in range when off + 4*i + 4 <= limit; outside it memory is not read and the result is 0
|
|
end, ok, got = self.tmp(), self.tmp(), self.tmp()
|
|
lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end"
|
|
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}")
|
|
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")
|
|
self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}")
|
|
self.emit(f"{got} = OpLoad %uint {p} Aligned 4")
|
|
self.emit(f"OpBranch {lbl_end}")
|
|
self.emit(f"{lbl_end} = OpLabel")
|
|
self.emit(f"{v} = OpPhi %uint {got} {lbl_do} {self.cu(0)} {pre}")
|
|
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, pad.
|
|
# Probes 8 slots from hash(key) & mask; a miss yields index 0 (the runtime puts a fallback there).
|
|
PROBES = 8
|
|
|
|
def desc_lookup(self, words):
|
|
"""words: 8 uint ids. Returns a uint id with the bindless index.
|
|
|
|
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
|
|
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
|
|
self.desc_fn = (["%desc_lookup_fn = OpFunction %uint 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 %uint %desc_lookup_fn " + " ".join(words))
|
|
return r
|
|
|
|
def desc_probe(self, words):
|
|
"""The lookup itself: FNV-1a of the 8 dwords, then PROBES slots compared in turn."""
|
|
h = self.cu(2166136261)
|
|
for w in words: # FNV-1a over the 8 dwords
|
|
x, m = self.tmp(), self.tmp()
|
|
self.emit(f"{x} = OpBitwiseXor %uint {h} {w}")
|
|
self.emit(f"{m} = OpIMul %uint {x} {self.cu(16777619)}")
|
|
h = m
|
|
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).
|
|
kv, iv = "%dl_k", "%dl_idx" # slot number, and the result (0 until a slot matches)
|
|
self.body[0:0] = [f" {kv} = OpVariable %_ptr_Function_uint Function %c0",
|
|
f" {iv} = OpVariable %_ptr_Function_uint Function %c0"]
|
|
self.emit("OpBranch %dl_head")
|
|
self.body.append("%dl_head = OpLabel")
|
|
self.emit("OpLoopMerge %dl_end %dl_cont None")
|
|
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}")
|
|
self.emit(f"OpStore {kv} {self.cu(self.PROBES)}") # the first match ends the search
|
|
self.emit("OpBranch %dl_next")
|
|
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}")
|
|
return r
|
|
|
|
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)
|
|
|
|
# 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):
|
|
"""(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)."""
|
|
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 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 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."""
|
|
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
|
|
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] = self.tmp()
|
|
self.emit(f"{res[0]} = OpSMod %int {c} {n}")
|
|
if 1 in want:
|
|
n2, p, hi, rf, lt, res[1] = (self.tmp() for _ in range(6))
|
|
self.emit(f"{n2} = OpIAdd %int {n} {n}")
|
|
self.emit(f"{p} = OpSMod %int {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
|
|
|
|
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 id of the call's result per (first SGPR, n). 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 the bindless index (a uint id)."""
|
|
if a["k"] == "slist" and len(a["r"]) >= n:
|
|
words = self.sgpr_words(a, n)
|
|
if n < 8:
|
|
words = words + [self.cu(0xFFFFFFFF)] * (8 - n)
|
|
return self.desc_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()
|
|
words = self.sgpr_words(a, n)
|
|
if n < 8:
|
|
words = words + [self.cu(0xFFFFFFFF)] * (8 - n)
|
|
idx = self.desc_lookup(words)
|
|
if top:
|
|
self.desc_cache[key] = idx
|
|
return idx
|
|
|
|
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 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 image_op(self, op, a, mods):
|
|
a16 = "a16" in mods
|
|
d16 = "d16" in mods
|
|
dim = next((m for m in mods if m.startswith("dim:")), "dim:SQ_RSRC_IMG_2D")
|
|
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 dim not in kinds:
|
|
raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1])
|
|
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.endswith("_d"):
|
|
raise Unsupported(op + " 3D gradients")
|
|
# 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 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, addr = a[0], self.addr_regs(a[1])
|
|
img_idx = self.desc_lookup_sgpr(a[2], 8)
|
|
img = None # a coherent image_load reads the storage view, not this sampled one
|
|
if not coherent:
|
|
ip, img = self.tmp(), self.tmp()
|
|
self.emit(f"{ip} = OpAccessChain %{iptr} {iarr} {img_idx}")
|
|
self.emit(f"{img} = OpLoad %{itype} {ip}")
|
|
coords = [self.load_reg("vgpr", r) for r in addr]
|
|
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.
|
|
extras = op[len("image_sample"):] if op.startswith("image_sample") else ""
|
|
w_off = 1 if extras.endswith("_o") else 0
|
|
extras = extras[:-2] if w_off else extras
|
|
w_bias = 1 if extras in ("_b", "_c_b") else 0
|
|
w_grad = 2 * min(ncoord, 2) 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.
|
|
ints = []
|
|
for c in [self.load_reg("vgpr", r) for r in addr]:
|
|
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)}")
|
|
ints += [lo, hi]
|
|
coords = ints
|
|
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(dim, self.load_reg("sgpr", a[2]["r"] + 1), iv, img_idx, dmask, vdata, d16)
|
|
return
|
|
if dim in self.STORE_DIMS:
|
|
self.image_load_typed(dim, self.sgpr_word(a[2], 1), iv, img, img_idx,
|
|
dmask, vdata, self.cu(0), d16)
|
|
return
|
|
res = self.tmp()
|
|
self.emit(f"{res} = OpImageFetch %v4float {img} {iv} Lod {self.cu(0)}")
|
|
ncomp = bin(dmask).count("1")
|
|
else:
|
|
smp_idx = self.desc_lookup_sgpr(a[3], 4)
|
|
sp, smp, si = self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{sp} = OpAccessChain %_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"
|
|
typed_sample = typed_implicit or (op == "image_sample_lz" and dim == "dim:SQ_RSRC_IMG_2D")
|
|
|
|
def sampled_image(image, cls):
|
|
sampled = self.tmp()
|
|
sampler_type = f"itxsamp{cls}_0" if cls else stype
|
|
self.emit(f"{sampled} = OpSampledImage %{sampler_type} {image} {smp}")
|
|
return sampled
|
|
|
|
if not typed_sample and op not in ("image_gather4_lz", "image_gather4_lz_o", "image_gather4_l", "image_gather4_l_o"):
|
|
self.emit(f"{si} = OpSampledImage %{stype} {img} {smp}")
|
|
f = [self.tof(c) for c in coords]
|
|
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:
|
|
raise Unsupported(op + " a16")
|
|
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).
|
|
biased = self.tmp()
|
|
self.emit(f"{biased} = OpFAdd %float {lod} %fhalf_g")
|
|
self.emit(f"{rl} = OpExtInst %float %glsl Floor {biased}")
|
|
self.emit(f"{mi} = OpConvertFToS %int {rl}")
|
|
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 == "_d_cl" # _d plus a min-LOD clamp, read after the gradients
|
|
if clamp:
|
|
kind = "_d"
|
|
self.uses_minlod = True
|
|
ref = None
|
|
if kind.startswith("_c"):
|
|
ref, f = f[0], f[1:]
|
|
bias = None
|
|
if kind in ("_b", "_c_b"):
|
|
bias, f = f[0], f[1:]
|
|
grads = None
|
|
if kind == "_d":
|
|
# Address: gradients first, then coords. 2D and 2D-array have 2-component gradients (the array
|
|
# layer has none): ds/dx, dt/dx, ds/dy, dt/dy. 1D has scalar ds/dx, ds/dy.
|
|
if ncoord == 1:
|
|
if len(f) < 3:
|
|
raise Unsupported(op + " coords")
|
|
grads, f = (f[0], f[1]), f[2:]
|
|
else:
|
|
if len(f) < 4 + ncoord:
|
|
raise Unsupported(op + " coords")
|
|
gx, gy = self.tmp(), self.tmp()
|
|
self.emit(f"{gx} = OpCompositeConstruct %v2float {f[0]} {f[1]}")
|
|
self.emit(f"{gy} = OpCompositeConstruct %v2float {f[2]} {f[3]}")
|
|
grads, f = (gx, gy), f[4:]
|
|
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]}")
|
|
if typed_sample:
|
|
operands = "Lod %f0"
|
|
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}")
|
|
operands = f"Grad {dx} {dy}"
|
|
|
|
def sample(image, cls, ty):
|
|
sampled = sampled_image(image, cls)
|
|
result = self.tmp()
|
|
self.emit(f"{result} = OpImageSampleExplicitLod {ty} {sampled} {uv} {operands}")
|
|
return result
|
|
|
|
self.uses_int_sampler = True
|
|
self.image_read_typed(dim, self.sgpr_word(a[2], 1), img, img_idx,
|
|
dmask, vdata, d16, sample)
|
|
return
|
|
res = self.tmp()
|
|
if off is not None and kind not in ("", "_lz", "_l", "_b", "_c_lz"):
|
|
raise Unsupported(op)
|
|
implicit = kind in ("", "_b") and self.stage == "ps"
|
|
grads_fb = None
|
|
if off is not None and TEXEL_OFFSET_FALLBACK:
|
|
uv, grads_fb = self.texel_offset_fold(img, si, uv, off, n_off, ncoord, kind, implicit,
|
|
f[ncoord] if kind == "_l" and len(f) > ncoord else None, bias)
|
|
off = None
|
|
|
|
def opnd(mask, args):
|
|
"""Image operands with the texel offset appended (Offset = 0x10 sorts after Lod/Bias)."""
|
|
if off is None:
|
|
return f" {mask} {args}" if mask else ""
|
|
return f" {mask + '|' if mask else ''}Offset {args + ' ' if args else ''}{off}"
|
|
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:
|
|
self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Grad {grads_fb[0]} {grads_fb[1]}")
|
|
elif kind == "":
|
|
self.emit(f"{res} = OpImageSampleImplicitLod %v4float {si} {uv}{opnd('', '')}" if self.stage == "ps" else
|
|
f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', '%f0')}")
|
|
elif kind == "_lz":
|
|
self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', '%f0')}")
|
|
elif kind == "_l":
|
|
self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', f[ncoord] if len(f) > ncoord else '%f0')}")
|
|
elif kind == "_b" and self.stage == "ps":
|
|
self.emit(f"{res} = OpImageSampleImplicitLod %v4float {si} {uv}{opnd('Bias', bias)}")
|
|
elif kind == "_c_lz":
|
|
d = self.tmp()
|
|
self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref}{opnd('Lod', '%f0')}")
|
|
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, value that leaves memory unchanged, used for inactive lanes)
|
|
IMG_ATOMICS = {"image_atomic_umin": ("OpAtomicUMin", 0xFFFFFFFF), "image_atomic_umax": ("OpAtomicUMax", 0),
|
|
"image_atomic_smin": ("OpAtomicSMin", 0x7FFFFFFF), "image_atomic_smax": ("OpAtomicSMax", 0x80000000),
|
|
"image_atomic_or": ("OpAtomicOr", 0), "image_atomic_xor": ("OpAtomicXor", 0),
|
|
"image_atomic_and": ("OpAtomicAnd", 0xFFFFFFFF), "image_atomic_add": ("OpAtomicIAdd", 0),
|
|
"image_atomic_sub": ("OpAtomicISub", 0)}
|
|
|
|
# image_store views: dim -> (index, SPIR-V Dim, arrayed, coordinate count). Bindings 8 + 3 * index + class,
|
|
# 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)}
|
|
# 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}
|
|
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
|
|
|
|
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}")
|
|
self.emit(f"{half} = OpBitwiseAnd %uint {raw} {self.cu(0xFFFF)}")
|
|
else:
|
|
self.emit(f"{half} = OpExtInst %uint %glsl UMin {bits} {self.cu(0xFFFF)}")
|
|
return half
|
|
|
|
def image_load_typed(self, dim, t1, iv, img, idx, dmask, vdata, lod, d16=False):
|
|
def fetch(image, _cls, ty):
|
|
res = self.tmp()
|
|
self.emit(f"{res} = OpImageFetch {ty} {image} {iv} Lod {lod}")
|
|
return res
|
|
self.image_read_typed(dim, t1, img, idx, dmask, vdata, d16, fetch)
|
|
|
|
def image_load_coherent(self, dim, t1, 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)."""
|
|
di = self.STORE_DIMS[dim][0]
|
|
self.uses_store_views.add(di)
|
|
self.reads_store_views = True
|
|
self.coherent_images = True
|
|
|
|
def view(cls):
|
|
ip, im = self.tmp(), self.tmp()
|
|
self.emit(f"{ip} = OpAccessChain %_ptr_UC_stv{cls}_{di} %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
|
|
self.image_read_typed(dim, t1, None, idx, dmask, vdata, d16, read, view)
|
|
|
|
def image_read_typed(self, dim, t1, img, idx, dmask, vdata, d16, read, view=None):
|
|
"""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.
|
|
dmask selects the output components; d16 packs two per VGPR."""
|
|
di = self.STORE_DIMS[dim][0]
|
|
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.emit(f"{ip} = OpAccessChain %_ptr_UC_itx{cls}_{di} %itx{cls}_{di} {idx}")
|
|
self.emit(f"{im} = OpLoad %itximg{cls}_{di} {ip}")
|
|
return im
|
|
is_u, is_s = self.fmt_int_flags(t1)
|
|
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.f16_bits(self.tof(xs[i])) if numeric_class == 0 else xs[i]
|
|
self.write_lo16(dest, lo)
|
|
continue
|
|
if numeric_class == 0:
|
|
w = self.pack_f16_pair_int(self.tof(xs[i]), self.tof(xs[i + 1]))
|
|
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_integer(cls, ty):
|
|
im = view(cls)
|
|
b = self.tmp()
|
|
r = read(im, cls, ty)
|
|
self.emit(f"{b} = OpBitcast %v4uint_st {r}")
|
|
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_integer(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_integer(1, "%v4uint_st")
|
|
self.emit(f"OpBranch {L['e3']}")
|
|
self.emit(f"{L['f']} = OpLabel")
|
|
res = read(view(0), 0, "%v4float")
|
|
b = self.tmp()
|
|
self.emit(f"{b} = OpBitcast %v4uint_st {res}")
|
|
write(b, 0)
|
|
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 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."""
|
|
if dim not in self.STORE_DIMS or "d16" in mods:
|
|
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[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])
|
|
raw = [self.load_reg("vgpr", r) for r in addr]
|
|
if "a16" in mods:
|
|
# 16-bit coordinates: two unsigned 16-bit values per register, low half first.
|
|
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("image_store coords")
|
|
# 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)]
|
|
coords = [self.as_int(c) for c in raw[:nc]]
|
|
idx = self.desc_lookup_sgpr(a[2], 8)
|
|
t1 = self.sgpr_word(a[2], 1)
|
|
self.uses_store_views.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)
|
|
fv = [self.tof(v) for v in vals]
|
|
sv = [self.as_int(v) for v in vals]
|
|
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(vals)}")
|
|
self.emit(f"{v4s} = OpCompositeConstruct %v4int_st {' '.join(sv)}")
|
|
act = self.active_b()
|
|
L = {k: self.tmp() + "_" + k for k in ("do", "end", "s", "rest", "e2", "u", "f", "e3")}
|
|
|
|
def write(cls, texel):
|
|
ip, img = self.tmp(), self.tmp()
|
|
self.emit(f"{ip} = OpAccessChain %_ptr_UC_stv{cls}_{di} %stv{cls}_{di} {idx}")
|
|
self.emit(f"{img} = OpLoad %stimg{cls}_{di} {ip}")
|
|
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)
|
|
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)
|
|
self.emit(f"OpBranch {L['e3']}")
|
|
self.emit(f"{L['f']} = OpLabel")
|
|
write(0, v4f)
|
|
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 image_misc(self, op, a, mods):
|
|
"""Query sampled image dimensions, load mip texels and handle storage image operations."""
|
|
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"
|
|
is3d_atomic = dim == "dim:SQ_RSRC_IMG_3D" and (op in self.IMG_ATOMICS or op == "image_atomic_cmpswap")
|
|
if op == "image_store":
|
|
self.image_store(a, mods, dim)
|
|
return
|
|
if op == "image_load_mip" and "glc" in mods:
|
|
# A coherent read of one mip: image_load_coherent reads a storage view, which has one level.
|
|
raise Unsupported("image_load_mip glc")
|
|
if op == "image_load_mip" and dim == "dim:SQ_RSRC_IMG_3D" and "d16" not in mods and "a16" not in mods:
|
|
# x, y, z, mip from a 3D sampled image (binding 6)
|
|
vdata, addr = a[0], self.addr_regs(a[1])
|
|
if len(addr) < 4:
|
|
raise Unsupported("image_load_mip coords")
|
|
idx = self.desc_lookup_sgpr(a[2], 8)
|
|
self.uses_tex_3d = True
|
|
ip, img, iv, res = self.tmp(), self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{ip} = OpAccessChain %_ptr_UC_img3 %images_3d {idx}")
|
|
self.emit(f"{img} = OpLoad %img3d {ip}")
|
|
xs = [self.as_int(self.load_reg("vgpr", r)) for r in addr[:4]]
|
|
self.emit(f"{iv} = OpCompositeConstruct %v3int {xs[0]} {xs[1]} {xs[2]}")
|
|
self.emit(f"{res} = OpImageFetch %v4float {img} {iv} Lod {xs[3]}")
|
|
dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1")
|
|
dmask, out = int(dm.split(":")[1], 0), 0
|
|
for c in range(4):
|
|
if dmask >> c & 1:
|
|
comp = self.tmp()
|
|
self.emit(f"{comp} = OpCompositeExtract %float {res} {c}")
|
|
self.dst({"k": "vgpr", "r": vdata["r"] + out, "n": 1}, self.tou(comp))
|
|
out += 1
|
|
return
|
|
is_atomic = op in self.IMG_ATOMICS or op == "image_atomic_cmpswap"
|
|
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 and op != "image_load_mip")):
|
|
raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1])
|
|
vdata, addr = a[0], self.addr_regs(a[1])
|
|
idx = 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 is3d_atomic:
|
|
# 3D r32ui storage image atomics (binding 7).
|
|
self.uses_storage3d = True
|
|
coords = atomic_coords(3)
|
|
iv, ip, tp, old, safe = (self.tmp() for _ in range(5))
|
|
self.emit(f"{iv} = OpCompositeConstruct %v3int {coords[0]} {coords[1]} {coords[2]}")
|
|
self.emit(f"{ip} = OpAccessChain %_ptr_UC_simg3 %simages3d {idx}")
|
|
val = self.load_reg("vgpr", vdata["r"])
|
|
if op == "image_atomic_cmpswap":
|
|
cmpv = self.load_reg("vgpr", vdata["r"] + 1)
|
|
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(f"{tp} = OpImageTexelPointer %_ptr_Image_uint {ip} {iv} {self.cu(0)}")
|
|
self.emit(f"{old} = OpAtomicCompareExchange %uint {tp} {self.cu(1)} {self.cu(0)} {self.cu(0)} {val} {cmpv}")
|
|
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
|
|
spv, neutral = self.IMG_ATOMICS[op]
|
|
self.emit(f"{tp} = OpImageTexelPointer %_ptr_Image_uint {ip} {iv} {self.cu(0)}")
|
|
self.emit(f"{safe} = OpSelect %uint {self.active_b()} {val} {self.cu(neutral)}")
|
|
self.emit(f"{old} = {spv} %uint {tp} {self.cu(1)} {self.cu(0)} {safe}")
|
|
if "glc" in mods:
|
|
self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, old)
|
|
return
|
|
if op == "image_store":
|
|
self.image_store(a, mods, dim)
|
|
return
|
|
if op in self.IMG_ATOMICS or op == "image_atomic_cmpswap":
|
|
# Storage image (2D r32ui). Atomics: vdata holds the operand; with 'glc' the pre-op value comes back.
|
|
self.uses_storage = True
|
|
coords = atomic_coords(2)
|
|
iv = self.tmp()
|
|
self.emit(f"{iv} = OpCompositeConstruct %v2int {coords[0]} {coords[1]}")
|
|
ip = self.tmp()
|
|
self.emit(f"{ip} = OpAccessChain %_ptr_UC_simg %simages {idx}")
|
|
val = self.load_reg("vgpr", vdata["r"])
|
|
if op == "image_store":
|
|
# Writes dmask component 0 as r32ui; only active lanes store.
|
|
img, lbl_do, lbl_end = self.tmp(), self.tmp() + "_do", self.tmp() + "_end"
|
|
self.emit(f"{img} = OpLoad %simg2d_u {ip}")
|
|
v4 = self.tmp()
|
|
self.emit(f"{v4} = OpCompositeConstruct %v4uint {val} {self.cu(0)} {self.cu(0)} {self.cu(0)}")
|
|
act = self.active_b() # must be computed before OpSelectionMerge (merge directly precedes branch)
|
|
self.emit(f"OpSelectionMerge {lbl_end} None")
|
|
self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}")
|
|
self.emit(f"{lbl_do} = OpLabel")
|
|
self.emit(f"OpImageWrite {img} {iv} {v4}")
|
|
self.emit(f"OpBranch {lbl_end}")
|
|
self.emit(f"{lbl_end} = OpLabel")
|
|
self.uses_v4uint = True
|
|
return
|
|
if op == "image_atomic_cmpswap":
|
|
# vdata = (src, cmp): memory = (memory == cmp) ? src : memory; glc returns the old value.
|
|
cmpv = self.load_reg("vgpr", vdata["r"] + 1)
|
|
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") # inactive lanes don't touch memory
|
|
tp, old = self.tmp(), self.tmp()
|
|
self.emit(f"{tp} = OpImageTexelPointer %_ptr_Image_uint {ip} {iv} {self.cu(0)}")
|
|
self.emit(f"{old} = OpAtomicCompareExchange %uint {tp} {self.cu(1)} {self.cu(0)} {self.cu(0)} {val} {cmpv}")
|
|
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
|
|
spv, neutral = self.IMG_ATOMICS[op]
|
|
tp, old, safe = self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{tp} = OpImageTexelPointer %_ptr_Image_uint {ip} {iv} {self.cu(0)}")
|
|
self.emit(f"{safe} = OpSelect %uint {self.active_b()} {val} {self.cu(neutral)}")
|
|
self.emit(f"{old} = {spv} %uint {tp} {self.cu(1)} {self.cu(0)} {safe}")
|
|
if "glc" in mods:
|
|
self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, old)
|
|
return
|
|
ip, img = self.tmp(), self.tmp()
|
|
if array_query:
|
|
self.uses_tex_array = True
|
|
self.emit(f"{ip} = OpAccessChain %_ptr_UC_imga %images_arr {idx}")
|
|
self.emit(f"{img} = OpLoad %img2da {ip}")
|
|
else:
|
|
self.emit(f"{ip} = OpAccessChain %_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":
|
|
lod = self.as_int(self.load_reg("vgpr", addr[0]))
|
|
sz, lv = self.tmp(), self.tmp()
|
|
size_type = "%v3int" if array_query else "%v2int"
|
|
self.emit(f"{sz} = OpImageQuerySizeLod {size_type} {img} {lod}")
|
|
self.emit(f"{lv} = OpImageQueryLevels %int {img}")
|
|
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 not array_query:
|
|
vals.append(self.as_int(self.cu(1)))
|
|
vals.append(lv)
|
|
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
|
|
# image_load_mip: x, y, mip, with the same typed SRV as image_load.
|
|
if len(addr) < 3:
|
|
raise Unsupported("image_load_mip coords")
|
|
xs = [self.as_int(self.load_reg("vgpr", r)) for r in addr[:3]]
|
|
iv = self.tmp()
|
|
self.emit(f"{iv} = OpCompositeConstruct %v2int {xs[0]} {xs[1]}")
|
|
self.image_load_typed(dim, self.sgpr_word(a[2], 1), iv, img, idx, dmask, vdata, xs[2], d16="d16" in mods)
|
|
|
|
|
|
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
|
|
|
|
def attribute(self, n, comp, flat=False, half=None, ij=None):
|
|
"""Component `comp` of fragment input attribute n (declared as a vec4 Input at Location n).
|
|
|
|
An attribute in per_vertex (read by a *_f16 interp somewhere) is a PerVertexKHR vec4[3] of the producer's
|
|
raw 32-bit words, which hold two f16 (low, high). `half` 0/1 decodes that f16 of 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).
|
|
|
|
--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)."""
|
|
if half is not None and n in self.f16_halves:
|
|
loc = f16_half_location(n, half)
|
|
if loc < 0:
|
|
raise Unsupported(f"--f16-interp-fallback: attr{n} has no decoded-half location")
|
|
name = f"%in_f16h{n}_{half}"
|
|
self.inputs[name] = loc
|
|
self.interpolated.add(name)
|
|
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:
|
|
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 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]}")
|
|
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):
|
|
"""--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), floored and clamped to the image's
|
|
levels. 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 == "_b" and bias is not None:
|
|
qb = self.tmp()
|
|
self.emit(f"{qb} = OpFAdd %float {qx} {bias}")
|
|
level_f = qb
|
|
if level_f is None:
|
|
level = ci(0)
|
|
else:
|
|
fl, li, lo = self.tmp(), self.tmp(), self.tmp()
|
|
self.emit(f"{fl} = OpExtInst %float %glsl Floor {level_f}")
|
|
self.emit(f"{li} = OpConvertFToS %int {fl}")
|
|
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 == "_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
|
|
|
|
# ---- 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 <emit count> 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_read2_b32", "ds_read_b128", "ds_read_b96"):
|
|
if op == "ds_read2_b32":
|
|
dws = [self.mod_int(mods, "offset0", 0), self.mod_int(mods, "offset1", 0)]
|
|
else:
|
|
n = {"ds_read_b32": 1, "ds_read_b64": 2, "ds_read_b96": 3, "ds_read_b128": 4}[op]
|
|
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):
|
|
dw %= self.GS_VTX_DW
|
|
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} {vtx}")
|
|
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_write2_b32", "ds_write_b64"):
|
|
if op == "ds_write2_b32":
|
|
items = [(self.mod_int(mods, "offset0", 0), a[1]), (self.mod_int(mods, "offset1", 0), a[2])]
|
|
elif op == "ds_write_b64":
|
|
base = self.mod_int(mods, "offset", 0) // 4
|
|
items = [(base, {"k": "vgpr", "r": a[1]["r"], "n": 1}), (base + 1, {"k": "vgpr", "r": a[1]["r"] + 1, "n": 1})]
|
|
else:
|
|
items = [(self.mod_int(mods, "offset", 0) // 4, a[1])]
|
|
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):
|
|
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")
|
|
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 (t/|det|, sign(det), b_i/|det|, b_j/|det|), or (inf, 1, 0, 0) on a miss, with 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). Consumers
|
|
divide by .y, which gives the same values as the hardware's numerator/denominator form."""
|
|
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}")
|
|
ptr = T()
|
|
e(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr)}")
|
|
|
|
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, NEGMAX, POSMAX = (self.tof(self.cu(x)) for x in (0x7F800000, 0x3F800000, 0xFF7FFFFF, 0x7F7FFFFF))
|
|
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
|
|
|
|
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}")
|
|
L = {k: T() + "_" + k for k in ("tri", "nt", "box", "oth", "end1", "end2")}
|
|
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, ivec = T(), T()
|
|
e(f"{dvec} = OpCompositeConstruct %v3float {' '.join(dirv)}")
|
|
e(f"{ivec} = OpCompositeConstruct %v3float {' '.join(inv)}")
|
|
|
|
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")
|
|
sz = vx(ivec, kz)
|
|
sx = fop("OpFMul", vx(dvec, kx), sz)
|
|
sy = fop("OpFMul", vx(dvec, ky), sz)
|
|
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", vx(vv, kx), fop("OpFMul", sx, zk)),
|
|
fop("OpFSub", vx(vv, ky), 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")
|
|
le0 = lambda x: bop("OpFOrdLessThanEqual", x, "%f0")
|
|
orr = lambda x, y: bop("OpLogicalOr", x, y)
|
|
andd = lambda x, y: bop("OpLogicalAnd", x, y)
|
|
cback = orr(orr(lt0(uu), lt0(vv_)), lt0(ww))
|
|
cfront = orr(orr(gt0(uu), gt0(vv_)), gt0(ww))
|
|
cond = T()
|
|
e(f"{cond} = OpLogicalNot %bool {andd(cback, cfront)}")
|
|
ea, eb, ec = eq0(uu), eq0(vv_), eq0(ww)
|
|
|
|
def edge(v0x, v0y, v1x, v1y):
|
|
tx = fop("OpFSub", v1x, v0x)
|
|
ty = fop("OpFSub", v1y, v0y)
|
|
return sel(eq0(tx), lt0(ty), lt0(tx), "%bool")
|
|
|
|
def vert(v0x, v1x, v2x):
|
|
return andd(le0(fop("OpFSub", v1x, v0x)), gt0(fop("OpFSub", v2x, v0x)))
|
|
iea = andd(ea, edge(bx, by, cx, cy))
|
|
ieb = andd(eb, edge(cx, cy, ax, ay))
|
|
iec = andd(ec, edge(ax, ay, bx, by))
|
|
ie = andd(cond, orr(orr(iea, ieb), iec))
|
|
isva, isvb, isvc = andd(eb, ec), andd(ea, ec), andd(ea, eb)
|
|
iva = andd(isva, vert(ax, bx, cx))
|
|
ivb = andd(isvb, vert(bx, cx, ax))
|
|
ivc = andd(isvc, vert(cx, ax, bx))
|
|
isv = orr(orr(isva, isvb), isvc)
|
|
nisv = T()
|
|
e(f"{nisv} = OpLogicalNot %bool {isv}")
|
|
iv = orr(nisv, orr(orr(iva, ivb), ivc))
|
|
ie2 = andd(ie, iv)
|
|
cedge = orr(orr(ea, eb), ec)
|
|
hitc = sel(cedge, ie2, cond, "%bool")
|
|
det = fop("OpFAdd", uu, fop("OpFAdd", vv_, ww))
|
|
azz, bzz, czz = (fop("OpFMul", sz, z) for z in (az0, bz0, cz0))
|
|
tt = fop("OpFAdd", fop("OpFAdd", fop("OpFMul", uu, azz), fop("OpFMul", vv_, bzz)), fop("OpFMul", ww, czz))
|
|
sg = fext("FSign", det)
|
|
ts = fop("OpFMul", sg, tt)
|
|
front = T()
|
|
e(f"{front} = OpLogicalNot %bool {lt0(ts)}")
|
|
hit = andd(hitc, front)
|
|
dab = fext("FAbs", det)
|
|
rt = sel(hit, fop("OpFDiv", tt, dab), INF)
|
|
rs = sel(hit, sg, ONE)
|
|
# 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))
|
|
rv = sel(hit, fop("OpFDiv", pick(0), dab), "%f0")
|
|
rw = sel(hit, fop("OpFDiv", pick(2), dab), "%f0")
|
|
for k, v in enumerate((rt, rs, rv, rw)):
|
|
out(k, self.tou(v))
|
|
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")
|
|
invc = [fext("FClamp", d, NEGMAX, POSMAX) for d in inv]
|
|
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 = [fop("OpFMul", fop("OpFSub", mm[c], org[c]), invc[c]) for c in range(3)]
|
|
b1 = [fop("OpFMul", fop("OpFSub", mm[3 + c], org[c]), invc[c]) for c in range(3)]
|
|
tmin = fext("FMax", fext("FMax", fext("FMin", b0[0], b1[0]), fext("FMin", b0[1], b1[1])),
|
|
fext("FMin", b0[2], b1[2]))
|
|
tmx = fext("FMin", fext("FMin", fext("FMax", b0[0], b1[0]), fext("FMax", b0[1], b1[1])),
|
|
fext("FMax", b0[2], b1[2]))
|
|
notnan = T()
|
|
e(f"{notnan} = OpFOrdEqual %bool {mm[0]} {mm[0]}")
|
|
h1 = bop("OpFOrdGreaterThanEqual", tmx, fext("FMax", "%f0", tmin))
|
|
h2 = bop("OpFOrdLessThan", tmin, tmax)
|
|
hb = andd(notnan, andd(h1, h2))
|
|
dist.append(sel(hb, tmin, INF))
|
|
idx.append(sel(hb, child, self.cu(0xFFFFFFFF), "%uint"))
|
|
for p_, q_ in ((0, 1), (2, 3), (0, 2), (1, 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")
|
|
|
|
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":
|
|
if "compr" in ins["mods"]:
|
|
raise Unsupported("mesh compressed export")
|
|
pidx = int(tgt[3:])
|
|
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 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}")
|
|
if "compr" in ins["mods"]:
|
|
raise Unsupported("mesh compressed export")
|
|
comps = [("%f0" if x["k"] == "special" and x["t"] == "off" else self.src_f(x)) for x in srcs]
|
|
comps += ["%f0"] * (4 - len(comps))
|
|
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(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 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:
|
|
# GFX9+ misc vector at pos1: z[10:0] = Layer, z[19:16] = ViewportIndex.
|
|
if len(srcs) >= 3 and not (srcs[2]["k"] == "special" and srcs[2]["t"] == "off"):
|
|
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 %out_layer")
|
|
self.emit(f"{sel} = OpSelect %int {act} {li} {old}")
|
|
self.emit(f"OpStore %out_layer {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 %out_viewport")
|
|
self.emit(f"{sel} = OpSelect %int {act} {vi} {old}")
|
|
self.emit(f"OpStore %out_viewport {sel}")
|
|
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
|
|
comps = []
|
|
if "compr" in ins["mods"]:
|
|
# Compressed export: two registers, each holding two f16 values (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).)
|
|
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 += ["%f0", "%f0"]
|
|
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("%f0")
|
|
else:
|
|
comps.append(self.src_f(x))
|
|
while len(comps) < 4:
|
|
comps.append("%f0")
|
|
comps = comps[:4]
|
|
v = self.tmp()
|
|
self.emit(f"{v} = OpCompositeConstruct %v4float {' '.join(comps)}")
|
|
name = {"pos0": "%out_pos"}.get(tgt)
|
|
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":
|
|
name = f"%out_mrt{int(tgt[3:])}"
|
|
elif tgt.startswith("pos"):
|
|
return # pos1+ (clip/cull/point size): ignored in v0
|
|
else:
|
|
raise Unsupported(f"export {tgt}")
|
|
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 %v4float {name}")
|
|
self.emit(f"{sel} = OpSelect %v4float {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{f16_half_location(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): the PS reading them is then fed by another producer or rejects."""
|
|
if f16_half_location(n, 0) <= self.param_max:
|
|
return ()
|
|
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 mesh_compute_epilogue(gen):
|
|
"""--mesh-compute: the mesh epilogue as buffer stores. 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'])}",
|
|
f"%msp = OpExtInst %uint %glsl UMin %msp0 {c(gen.ms['maxp'])}",
|
|
"%mli = OpLoad %uint %local_index",
|
|
# Slot base = output address (push-constant dwords 36..37) + linear workgroup index * slot bytes.
|
|
f"%moa_lo_p = OpAccessChain %_ptr_PC_uint %user_data {c(5)}",
|
|
f"%moa_hi_p = OpAccessChain %_ptr_PC_uint %user_data {c(6)}",
|
|
"%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 9-bit indices and the null-primitive bit (bit 31), as in the mesh path.
|
|
L += ["%mhp = OpLoad %bool %ms_has_prim", "%mpi = OpULessThan %bool %mli %msp",
|
|
"%mwp = OpLogicalAnd %bool %mhp %mpi",
|
|
"OpSelectionMerge %msc_pend None", "OpBranchConditional %mwp %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",
|
|
f"%mi0 = OpBitwiseAnd %uint %mpr {c(0x1FF)}",
|
|
f"%mr1 = OpShiftRightLogical %uint %mpr {c(10)}", f"%mi1 = OpBitwiseAnd %uint %mr1 {c(0x1FF)}",
|
|
f"%mr2 = OpShiftRightLogical %uint %mpr {c(20)}", f"%mi2 = OpBitwiseAnd %uint %mr2 {c(0x1FF)}",
|
|
f"%mnb = OpShiftRightLogical %uint %mpr {c(31)}"]
|
|
for i, w in enumerate(("%mi0", "%mi1", "%mi2", "%mnb")):
|
|
store(at("%mpb", 4 * i), w)
|
|
L += ["OpBranch %msc_pend", "%msc_pend = OpLabel"]
|
|
return "".join((" " + l if " = OpLabel" not in l else l) + "\n" for l in L)
|
|
|
|
|
|
def assemble(gen):
|
|
vs = gen.stage == "vs"
|
|
cs = gen.stage == "cs"
|
|
ms = gen.stage == "ms"
|
|
gsx = gen.stage == "gs"
|
|
msc = ms and MESH_COMPUTE
|
|
# --f16-interp-fallback, mesh: the params whose decoded halves fit clear of this shader's params (Gen.f16_halves_of)
|
|
ms_halves = [n for n in sorted(gen.ms_params) if F16_HALVES and f16_half_location(n, 0) > gen.param_max] \
|
|
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.
|
|
gen.msc_epilogue = mesh_compute_epilogue(gen)
|
|
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()) for l in b):
|
|
raise Unsupported("wave64 emulation: a subgroup operation is left")
|
|
gen.uses_subgroup = gen.uses_vote = gen.uses_ballot = gen.uses_wave_bits = gen.uses_quad = 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]
|
|
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"]
|
|
for v in (0, 1, 2, 3, 0x108, 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"] 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
|
|
[("%ms_out_vtx" if ms_blk else "%ms_out_pos"), "%ms_prim_idx", "%ms_cull"] +
|
|
[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 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 gen.uses_store_views or gen.uses_int_fetch else []) + \
|
|
[f"%stv{c}_{d}" for d in sorted(gen.uses_store_views) 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 [])
|
|
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"]
|
|
bary = any(str(c).startswith("bary") for c in gen.frag_inputs.values()) or bool(gen.per_vertex)
|
|
# --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).
|
|
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 = {f16_half_location(n, h) for n in gen.f16_halves for h in (0, 1)}
|
|
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")
|
|
gen.bary_location = next(n for n in range(len(used) + 1) if n not in used) 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)
|
|
# SPIR-V module layout: every OpCapability, then every OpExtension, then imports.
|
|
caps = ["Shader"] + (["Int64", "PhysicalStorageBufferAddresses"] if psb 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.uses_vote:
|
|
caps += [c for c in ("GroupNonUniform", "GroupNonUniformVote") if c not in caps]
|
|
if gen.uses_ballot:
|
|
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_f64:
|
|
caps.append("Float64")
|
|
if gen.uses_fma_khr:
|
|
caps.append("FMAKHR")
|
|
if gen.uses_store_views:
|
|
caps.append("StorageImageWriteWithoutFormat") # shaderStorageImageWriteWithoutFormat
|
|
if gen.reads_store_views:
|
|
caps.append("StorageImageReadWithoutFormat") # shaderStorageImageReadWithoutFormat: coherent image_load
|
|
if 3 in gen.uses_store_views:
|
|
caps.append("Image1D")
|
|
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:
|
|
caps.append("ShaderLayer")
|
|
if gen.uses_viewport:
|
|
caps.append("ShaderViewportIndex")
|
|
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_fma_khr:
|
|
exts.append("SPV_KHR_fma")
|
|
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")
|
|
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'} GLSL450",
|
|
f"OpEntryPoint {model} %main \"main\" {' '.join(iface)}"]
|
|
if cs:
|
|
hdr.append("OpExecutionMode %main LocalSize {} {} {}".format(*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(*gen.ms["size"]))
|
|
elif ms:
|
|
hdr += ["OpExecutionMode %main LocalSize {} {} {}".format(*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")
|
|
dec = []
|
|
if vs:
|
|
dec.append("OpDecorate %vertex_index BuiltIn VertexIndex")
|
|
dec.append("OpDecorate %instance_index BuiltIn InstanceIndex")
|
|
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"]
|
|
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 {f16_half_location(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")
|
|
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 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)
|
|
gen.consts.setdefault(0, "%c0")
|
|
for v, name in sorted(gen.consts.items()):
|
|
types.append(f"{name} = OpConstant %uint {v}")
|
|
if gen.desc_fn:
|
|
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.fmt_fn:
|
|
types.append("%v4uint_fmt = OpTypeVector %uint 4") # dedupe_types merges it with any other uvec4
|
|
types.append("%fn_fmt_decode = OpTypeFunction %v4uint_fmt " + " ".join(["%uint"] * 5))
|
|
if gen.uses_ballot:
|
|
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")
|
|
gvars = [f"{n} = OpVariable %_ptr_Output_v4 Output" for n in gen.outputs]
|
|
# Push constants: s0..s31 user data, then the 64-bit host address of the Xbox GPU VA window (heap base).
|
|
types += [f"%n_ud = OpConstant %uint {USER_SGPRS}", "%arr_ud = OpTypeArray %uint %n_ud",
|
|
"%UserData = OpTypeStruct %arr_ud %uint %uint %uint %uint" + (" %uint %uint" if msc else ""),
|
|
"%_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",
|
|
f"OpMemberDecorate %UserData 1 Offset {4 * USER_SGPRS}",
|
|
f"OpMemberDecorate %UserData 2 Offset {4 * USER_SGPRS + 4}",
|
|
f"OpMemberDecorate %UserData 3 Offset {4 * USER_SGPRS + 8}",
|
|
f"OpMemberDecorate %UserData 4 Offset {4 * USER_SGPRS + 12}"] + (
|
|
[f"OpMemberDecorate %UserData 5 Offset {4 * USER_SGPRS + 16}",
|
|
f"OpMemberDecorate %UserData 6 Offset {4 * USER_SGPRS + 20}"] if msc else [])
|
|
gvars += ["%user_data = OpVariable %_ptr_PC_UserData PushConstant"]
|
|
if gen.uses_fhalf:
|
|
types += ["%fhalf_g = OpConstant %float 0.5"]
|
|
if gen.uses_f64:
|
|
types += ["%double = OpTypeFloat 64", "%v2uint_d = OpTypeVector %uint 2"]
|
|
if gen.uses_ballot:
|
|
types += ["%v4uint_bal = OpTypeVector %uint 4"]
|
|
if gen.uses_store_views or gen.uses_int_fetch:
|
|
u, si = Gen.int_format_masks()
|
|
types += ["%v4uint_st = OpTypeVector %uint 4", "%v4int_st = OpTypeVector %int 4",
|
|
f"%fmt_mask_arr = OpTypeArray %uint {gen.cu(16)}",
|
|
"%_ptr_Private_fmt = OpTypePointer Private %fmt_mask_arr",
|
|
"%_ptr_Private_uint = OpTypePointer Private %uint"]
|
|
for nm, words in (("uint", u), ("sint", si)):
|
|
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 and di == 0:
|
|
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(gen.uses_store_views):
|
|
_, sdim, arr, _ = next(v for v in Gen.STORE_DIMS.values() if v[0] == 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 {8 + 3 * di + cls}"]
|
|
if gen.coherent_images:
|
|
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 %bool",
|
|
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_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(gen.lds_dwords)}",
|
|
"%_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:
|
|
# Barrier rounds: one count of the invocations not done per round, 3 slots by round mod 3 (bar_scheduler).
|
|
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.uses_lds:
|
|
types += [f"%lds_arr = OpTypeArray %uint {gen.cu(gen.lds_dwords)}",
|
|
"%_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.
|
|
# A constant ds offset past 64 KiB is not counted: on hardware it is out of range (reads 0, writes dropped).
|
|
lds_b = 4 * max(gen.lds_dwords, gen.lds_declared) 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 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 of a location a *_f16 interp reads (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 vs:
|
|
gvars.append("%vertex_index = OpVariable %_ptr_Input_int Input")
|
|
gvars.append("%instance_index = 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"]
|
|
if gen.vm_latch:
|
|
fn += ["%vm_mask = OpVariable %_ptr_Function_bool Function %true",
|
|
"%vm_set = 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"]
|
|
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"]
|
|
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 += ["%ud_base_lo_p = OpAccessChain %_ptr_PC_uint %user_data %c1",
|
|
"%ud_base_hi_p = OpAccessChain %_ptr_PC_uint %user_data %c2"]
|
|
if gen.uses_codebase:
|
|
fn += ["%ud_code_lo_p = OpAccessChain %_ptr_PC_uint %user_data %c3",
|
|
"%ud_code_hi_p = OpAccessChain %_ptr_PC_uint %user_data %c4"]
|
|
for i in range(USER_SGPRS):
|
|
fn += [f"%ud{i}p = OpAccessChain %_ptr_PC_uint %user_data %c0 {gen.cu(i)}",
|
|
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 vs:
|
|
fn += ["%vi = OpLoad %int %vertex_index", "%viu = OpBitcast %uint %vi",
|
|
"%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", "%iiu = OpBitcast %uint %ii",
|
|
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 []) + \
|
|
[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.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":
|
|
fn += ["%ff = OpLoad %bool %front_facing", "%ffm1 = OpFNegate %float %f1",
|
|
"%ffv = OpSelect %float %ff %f1 %ffm1", "%ffu = OpBitcast %uint %ffv",
|
|
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}"]
|
|
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}"]
|
|
# 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 [])
|
|
for function in gen.tbuffer_norm_fns.values():
|
|
helpers.extend(function)
|
|
tree = (cfg_structure.structure(gen.succ) if gen.blocks and STRUCTURED and not gen.emulate and not gen.bar_rounds
|
|
else None)
|
|
if tree is not None:
|
|
nesting = cfg_structure.depth(tree)
|
|
if nesting > MAX_STRUCTURED_DEPTH:
|
|
tree = None # too deep to validate cheaply: use the flat form
|
|
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 rounds"
|
|
elif gen.bar_rounds:
|
|
gen.control_flow = "barrier rounds"
|
|
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]
|
|
|
|
def label(prefix):
|
|
count[0] += 1
|
|
return f"%{prefix}{count[0]}"
|
|
|
|
stack = [("items", 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":
|
|
# 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"])
|
|
elif gen.emulate:
|
|
lines = x_scheduler(gen, x_threads)
|
|
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 += 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
|
|
out = hdr + dec + types + gvars + helpers + fn
|
|
end_lock = " OpEndInvocationInterlockEXT\n" if pops else ""
|
|
if msc:
|
|
end_lock = gen.msc_epilogue + 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'])}",
|
|
f"%msp = OpExtInst %uint %glsl UMin %msp0 {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",
|
|
"%mwp = OpLogicalAnd %bool %mhp %mpi",
|
|
"OpSelectionMerge %ms_pend None", "OpBranchConditional %mwp %ms_pdo %ms_pend",
|
|
"%ms_pdo = OpLabel",
|
|
"%mpr = OpLoad %uint %ms_prim",
|
|
f"%mi0 = OpBitwiseAnd %uint %mpr {c(0x1FF)}",
|
|
f"%mr1 = OpShiftRightLogical %uint %mpr {c(10)}", f"%mi1 = OpBitwiseAnd %uint %mr1 {c(0x1FF)}",
|
|
f"%mr2 = OpShiftRightLogical %uint %mpr {c(20)}", f"%mi2 = OpBitwiseAnd %uint %mr2 {c(0x1FF)}",
|
|
"%mix = OpCompositeConstruct %v3uint %mi0 %mi1 %mi2",
|
|
"%mixp = OpAccessChain %_ptr_Out_v3u_ms %ms_prim_idx %mli", "OpStore %mixp %mix",
|
|
f"%mnb = OpShiftRightLogical %uint %mpr {c(31)}", "%mnull = OpINotEqual %bool %mnb %c0",
|
|
f"%mcp = OpAccessChain %_ptr_Out_bool_ms %ms_cull %mli {c(0)}", "OpStore %mcp %mnull",
|
|
"OpBranch %ms_pend", "%ms_pend = OpLabel"]
|
|
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 lane off in EXEC at the last `vm` export is discarded. Without a latch EXEC can't have changed since
|
|
# that export, or there is none: then it is 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_keep = OpSelect %bool %vm_was_set %vm_exec %act_end\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"
|
|
return split_big_switch(no_contraction(dedupe_types(
|
|
"\n".join(" " + l if not l.startswith("%") or " = " not in l else l for l in out) +
|
|
"\n" + "\n".join(gen.body) + "\n" + tail)))
|
|
|
|
|
|
# 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<k>), and that chunk's blocks branch to %swm<k>, 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."""
|
|
global _STAGES
|
|
if _STAGES is None:
|
|
import json
|
|
idx = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(path))), "index.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"]
|
|
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(),
|
|
"sites": [("analysis-error", None, type(e).__name__)]}
|
|
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 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 reachable_code(insns):
|
|
"""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."""
|
|
by_pc = {i["pc"]: k for k, i in enumerate(insns)}
|
|
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 op not in ("s_endpgm",):
|
|
break
|
|
return [insns[k] for k in sorted(seen)]
|
|
|
|
|
|
def writes_exec(ins):
|
|
"""Whether an instruction can change EXEC: v_cmpx, saveexec / wrexec, or EXEC as the destination (first operand
|
|
of everything but the compares, which only read it there)."""
|
|
op, a = ins["op"], ins["args"]
|
|
if op.startswith("v_cmpx") or "saveexec" in op or "wrexec" in op:
|
|
return True
|
|
if op.startswith(("s_cmp_", "s_cmpk_", "s_bitcmp")):
|
|
return False
|
|
return bool(a) and a[0]["k"] == "special" and a[0]["t"].startswith("exec")
|
|
|
|
|
|
def exec_changes_after_vm(blocks, succ):
|
|
"""Whether some path writes EXEC after an `exp ... vm`. Only then does a PS need that export's EXEC kept."""
|
|
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"]:
|
|
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 read_before_write_vgprs(insns):
|
|
"""VGPRs a shader reads before writing them: for a fetch-calling VS these are the fetched attributes."""
|
|
written, first = set(), []
|
|
for ins in insns:
|
|
a, op = ins["args"], ins["op"]
|
|
if not a:
|
|
continue
|
|
reads_all = op.startswith(("exp", "buffer_store", "tbuffer_store", "image_store", "v_cmp", "v_cmpx", "ds_write",
|
|
"global_store")) \
|
|
or (op.startswith("global_atomic_") and "glc" not in ins["mods"]) # no vdst without glc
|
|
regs = []
|
|
for x in (a if reads_all 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 ("v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8", "v_pk_fmac_f16") or
|
|
(op.startswith("global_load_") and "_d16" in op)) and a[0]["k"] == "vgpr": # d16 keeps a half
|
|
regs.append(a[0]["r"])
|
|
for r in regs:
|
|
if r not in written and r not in first:
|
|
first.append(r)
|
|
if not reads_all and a[0]["k"] == "vgpr":
|
|
written.update(range(a[0]["r"], a[0]["r"] + a[0].get("n", 1)))
|
|
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 site
|
|
under --bary-fallback or --f16-interp-fallback (neither has PerVertexKHR inputs), and a computed v_interp_*_f32 on a 16-bit-flagged
|
|
interpolant (which half the 32-bit op reads is not established). Over the corpus all of these are
|
|
empty: 213 PS hold computed pairs, 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(("exp", "buffer_store", "tbuffer_store", "image_store", "v_cmp", "v_cmpx", "ds_write",
|
|
"global_store"))
|
|
if not reads_all and a[0]["k"] == "vgpr":
|
|
for r in range(a[0]["r"], a[0]["r"] + a[0].get("n", 1)):
|
|
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
|
|
preds = defaultdict(set) # block -> blocks that can run right before it
|
|
for b in sorted(set(blk)):
|
|
last = next((k for k in range(len(insns) - 1, -1, -1) if blk[k] == b), None)
|
|
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
|
|
seen, work = {b}, [b]
|
|
while work:
|
|
for p in preds[work.pop()]:
|
|
if p not in seen:
|
|
seen.add(p)
|
|
if any(w for w in ws if blk[w] == p):
|
|
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")
|
|
|
|
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.
|
|
cand = [t for t in sites if t["op"] in want
|
|
and (t["partial"] if t["op"] == "v_interp_p2_f16" else t["vdst"]) == anchor
|
|
and t["attr"] == s["attr"] and t["chan"] == s["chan"]]
|
|
if s["op"] in P1:
|
|
after = [t for t in cand if t["n"] > k]
|
|
return min(after, key=lambda t: t["n"]) if after else None
|
|
return max((t for t in cand if t["n"] < k), key=lambda t: t["n"], default=None)
|
|
|
|
# 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"])
|
|
attrs.add(s["attr"])
|
|
if attrs and BARY_FALLBACK:
|
|
raise Unsupported("computed I/J pair under --bary-fallback: no PerVertexKHR inputs")
|
|
if attrs and F16_HALVES:
|
|
# --f16-interp-fallback reads decoded halves from the producer: no per-vertex inputs either
|
|
raise Unsupported("computed I/J pair under --f16-interp-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(("exp", "buffer_store", "tbuffer_store", "image_store", "v_cmp", "v_cmpx", "ds_write",
|
|
"global_store"))
|
|
regs = []
|
|
for x in (a if reads_all 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 ("v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8", "v_pk_fmac_f16") and a[0]["k"] == "vgpr":
|
|
regs.append(a[0]["r"])
|
|
rr.update(regs)
|
|
if not reads_all and a[0]["k"] == "vgpr":
|
|
ww.update(range(a[0]["r"], a[0]["r"] + a[0].get("n", 1)))
|
|
return rr, ww
|
|
|
|
|
|
def input_signature_full(path, name):
|
|
"""ISG1 elements as (system value, declared mask, read/write mask)."""
|
|
dxbc = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(path))), name + ".dxbc")
|
|
with open(dxbc, "rb") as f:
|
|
d = f.read()
|
|
for k in range(struct.unpack_from("<I", d, 28)[0]):
|
|
off = struct.unpack_from("<I", d, 32 + 4 * k)[0]
|
|
if d[off:off + 4] == b"ISG1":
|
|
p = d[off + 8:off + 8 + struct.unpack_from("<I", d, off + 4)[0]]
|
|
cnt, eo = struct.unpack_from("<II", p, 0)
|
|
return [(struct.unpack_from("<I", p, eo + 32 * i + 12)[0], p[eo + 32 * i + 24], p[eo + 32 * i + 25])
|
|
for i in range(cnt)]
|
|
return []
|
|
|
|
|
|
def input_signature(path, name):
|
|
"""ISG1 elements of the shader's DXBC container: (register, mask, system value, component type)."""
|
|
dxbc = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(path))), name + ".dxbc")
|
|
with open(dxbc, "rb") as f:
|
|
d = f.read()
|
|
for k in range(struct.unpack_from("<I", d, 28)[0]):
|
|
off = struct.unpack_from("<I", d, 32 + 4 * k)[0]
|
|
if d[off:off + 4] == b"ISG1":
|
|
p = d[off + 8:off + 8 + struct.unpack_from("<I", d, off + 4)[0]]
|
|
cnt, eo = struct.unpack_from("<II", p, 0)
|
|
out = []
|
|
for i in range(cnt):
|
|
e = p[eo + 32 * i:eo + 32 * i + 32]
|
|
_, _, _, sysv, ctype, reg = struct.unpack_from("<6I", e, 0)
|
|
out.append((reg, e[24], sysv, ctype))
|
|
return out
|
|
return []
|
|
|
|
|
|
def same_encoding(raw, printed, op):
|
|
"""True if the bytes in the blob are the instruction LLVM printed. Exact match, except for fields the
|
|
hardware ignores that LLVM re-encodes with its default: VOP3P op_sel_hi[2] (bit 14) on two-source packed
|
|
ops (seen: v_pk_add_f16 stored with 0, printed with 1), and unused VOP3/VOP3P SRC1 (bits 49:41) and SRC2
|
|
(bits 58:50) fields, which the game's compiler stores as 0 and LLVM 23 prints as 0x80 (inline constant 0;
|
|
seen on two-source v_mul_legacy_f32/v_sub_f32/v_cmp_*_e64/v_mul_lo_u32/v_pk_mul_f16 and one-source
|
|
v_rcp/v_log/v_sqrt_f32_e64). LLVM decoded these bytes, so a source it actually reads would have printed as
|
|
s0, not 0x80."""
|
|
if raw == printed:
|
|
return True
|
|
if len(raw) != len(printed) or len(raw) < 8:
|
|
return False
|
|
r = int.from_bytes(raw, "little")
|
|
diff = r ^ int.from_bytes(printed, "little")
|
|
vop3 = (printed[3] >> 2) == 0x35 # VOP3 (encoding 110101)
|
|
vop3p = printed[3] == 0xCC
|
|
if vop3 or vop3p:
|
|
for shift in (41, 50): # SRC1, SRC2: unused field stored 0, printed 0x80
|
|
if (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 two_src:
|
|
diff &= ~(1 << 14)
|
|
return diff == 0
|
|
|
|
|
|
def output_signature(path, name):
|
|
"""OSG1 elements as (register, system value), one per register (first element wins)."""
|
|
dxbc = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(path))), name + ".dxbc")
|
|
with open(dxbc, "rb") as f:
|
|
d = f.read()
|
|
for k in range(struct.unpack_from("<I", d, 28)[0]):
|
|
off = struct.unpack_from("<I", d, 32 + 4 * k)[0]
|
|
if d[off:off + 4] == b"OSG1":
|
|
p = d[off + 8:off + 8 + struct.unpack_from("<I", d, off + 4)[0]]
|
|
cnt, eo = struct.unpack_from("<II", p, 0)
|
|
seen = {}
|
|
for i in range(cnt):
|
|
e = p[eo + 32 * i:eo + 32 * i + 32]
|
|
_, _, _, sysv, _, reg = struct.unpack_from("<6I", e, 0)
|
|
seen.setdefault(reg, sysv)
|
|
return sorted(seen.items())
|
|
return []
|
|
|
|
|
|
def output_signature_full(path, name):
|
|
"""OSG1 elements as (register, semantic_index, system_value, mask, rw_mask)."""
|
|
dxbc = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(path))), name + ".dxbc")
|
|
if not os.path.isfile(dxbc):
|
|
return []
|
|
with open(dxbc, "rb") as f:
|
|
d = f.read()
|
|
for k in range(struct.unpack_from("<I", d, 28)[0]):
|
|
off = struct.unpack_from("<I", d, 32 + 4 * k)[0]
|
|
if d[off:off + 4] == b"OSG1":
|
|
p = d[off + 8:off + 8 + struct.unpack_from("<I", d, off + 4)[0]]
|
|
cnt, eo = struct.unpack_from("<II", p, 0)
|
|
out = []
|
|
for i in range(cnt):
|
|
e = p[eo + 32 * i:eo + 32 * i + 32]
|
|
_, _, sem_idx, sysv, _, reg = struct.unpack_from("<6I", e, 0)
|
|
out.append((reg, sem_idx, sysv, e[24], e[25]))
|
|
return out
|
|
return []
|
|
|
|
|
|
def pos_export_layout(osg1, insns):
|
|
"""Map RDNA/GFX10 pos1..pos3 export components to BuiltIn ClipDistance / CullDistance (and misc).
|
|
|
|
Hardware ABI (Mesa src/amd/common/nir/ac_nir_prerast_utils.c: ac_nir_export_position;
|
|
AMD LLPC lgc/lowering/LowerInOut.cpp: LowerInOut::visitReturnInst):
|
|
- pos0 = SV_Position
|
|
- if any misc output (PointSize / EdgeFlag / ShadingRate / Layer / ViewportIndex) is active,
|
|
pos1 holds the misc vector (z[10:0] = Layer, z[19:16] = ViewportIndex on GFX9+) and
|
|
clip/cull distances start at pos2; otherwise clip/cull distances start at pos1.
|
|
- clip distances precede cull distances, packed contiguously into 4-component pos exports (<= 8 total).
|
|
Contrasted with DXBC OSG1 (D3D_NAME: 2=SV_ClipDistance, 3=SV_CullDistance,
|
|
4=SV_RenderTargetArrayIndex, 5=SV_ViewportArrayIndex, 23=SV_ShadingRate).
|
|
When OSG1 is absent (or declares no clip/cull/misc outputs), pos1..pos3 exports are ignored.
|
|
"""
|
|
misc_svs = {sv for _, _, sv, _, _ in osg1 if sv in (4, 5, 23)}
|
|
has_misc = bool(misc_svs)
|
|
clip_elems = sorted((sem, reg, mask) for reg, sem, sv, mask, _ in osg1 if sv == 2)
|
|
cull_elems = sorted((sem, reg, mask) for reg, sem, sv, mask, _ in osg1 if sv == 3)
|
|
slots = []
|
|
clip_n = 0
|
|
for _, _, mask in clip_elems:
|
|
for c in range(4):
|
|
if (mask >> 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."""
|
|
dxbc = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(path))), name + ".dxbc")
|
|
with open(dxbc, "rb") as f:
|
|
d = f.read()
|
|
for k in range(struct.unpack_from("<I", d, 28)[0]):
|
|
off = struct.unpack_from("<I", d, 32 + 4 * k)[0]
|
|
if d[off:off + 4] == b"PSV0":
|
|
p = d[off + 8:off + 8 + struct.unpack_from("<I", d, off + 4)[0]]
|
|
size = struct.unpack_from("<I", p, 0)[0]
|
|
r = p[4:4 + size]
|
|
if size < 48 or r[24] != 13:
|
|
return None
|
|
maxv, maxp = struct.unpack_from("<HH", r, 12)
|
|
tx, ty, tz = struct.unpack_from("<III", r, 36)
|
|
shared, = struct.unpack_from("<I", r, 0)
|
|
return {"maxv": maxv, "maxp": maxp, "topology": r[27], "threads": tx * ty * tz, "size": (tx, ty, tz),
|
|
"shared": shared}
|
|
return None
|
|
|
|
|
|
def native_paths(path, name):
|
|
"""The .s file's sources next to its folder: fssm/<name>.fssm for the game's shaders, and fspx/<name>.code and
|
|
fspx/<name>.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 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."""
|
|
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
|
|
for ins in info["insns"]:
|
|
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, base_op(ins["op"])):
|
|
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 translate(path):
|
|
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"]
|
|
for ins in insns:
|
|
enc = bytes.fromhex(ins["enc"])
|
|
skipped, at = 0, pos
|
|
while not same_encoding(blob[at:at + len(enc)], enc, base_op(ins["op"])):
|
|
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)
|
|
insns = fold_far_branches(insns)
|
|
insns = reachable_code(insns)
|
|
if any(i.get("normalized") for i in insns):
|
|
raise Unsupported("reachable instruction with normalized encoding")
|
|
else:
|
|
check_printed_encodings(path, info)
|
|
g = Gen(stage)
|
|
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"].startswith("s_setreg") and "HW_REG_MODE" in i["args"][0].get("t", "") for i in insns)
|
|
code_w64 = any(WAVE64_RE.search(" ".join([i["op"]] + [x.get("t", "") for x in i["args"]])) or
|
|
(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)
|
|
# 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_path = native_paths(path, info["name"])[0]
|
|
fssm_ws = None
|
|
try:
|
|
with open(fssm_path, "rb") as f:
|
|
fssm_ws = fssm_header.wave_size(f.read(fssm_header.WAVE_FLAGS_OFFSET + 4))
|
|
except OSError:
|
|
pass
|
|
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
|
|
else:
|
|
g.wave64 = code_w64 or stage == "ms" # NGG mesh shaders here are wave64 (thread = wave id * 64 + lane)
|
|
if stage == "gs":
|
|
ins_sig = [(reg, sv) for reg, mask, sv, ctype in input_signature(path, info["name"])]
|
|
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, grown to cover every constant offset the code uses.
|
|
need = (psv.get("shared", 0) + 3) // 4
|
|
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 == "offset":
|
|
need = max(need, int(v, 0) // 4 + 4)
|
|
elif k in ("offset0", "offset1"):
|
|
need = max(need, int(v, 0) * (64 if "st64" in ins["op"] else 1) * 2 + 4)
|
|
n = 16
|
|
while n < need:
|
|
n *= 2
|
|
g.lds_dwords = min(n, 16384)
|
|
g.cu(g.lds_dwords)
|
|
g.cu(g.lds_dwords - 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
|
|
# what 2,689 CS read before writing: 2,281 fit exactly, the rest are loop artifacts of the straight-line
|
|
# check): 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; v0, v1, v2 = thread id x, y, z (separate VGPRs on GFX10). An FSPX program
|
|
# (the FidelityFX DLL's shaders) carries the same two fields in its kind-0 entry (docs/fspx.md).
|
|
rsrc2, lx, ly, lz = cs_dispatch_state(path, info["name"])
|
|
if (rsrc2 >> 10) & 1:
|
|
raise Unsupported("CS thread-group-size SGPR")
|
|
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)}
|
|
# LDS_SIZE [23:15] in 512-byte units (470 of 486 LDS-using CS stay below it; the rest index past it with
|
|
# constant offsets, so the array also covers the largest offset in the code).
|
|
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 == "offset":
|
|
need = max(need, int(v, 0) // 4 + 4)
|
|
elif k in ("offset0", "offset1"):
|
|
need = max(need, int(v, 0) * (64 if "st64" in ins["op"] else 1) * 2 + 4)
|
|
n = 16
|
|
while n < need:
|
|
n *= 2
|
|
g.lds_dwords = min(n, 16384)
|
|
g.lds_need = need
|
|
g.lds_declared = ((rsrc2 >> 15) & 0x1FF) * 128
|
|
g.cu(g.lds_dwords)
|
|
g.cu(g.lds_dwords - 1)
|
|
for i in range(user, user + 3):
|
|
g.cu(i)
|
|
if stage == "ps":
|
|
# Pixel-shader system VGPRs (verified on 2,531 of 3,000 PS): 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 is a float whose
|
|
# sign gives facing (Mesa: load_front_face = front_face > 0; load_front_face_fsign = the raw value).
|
|
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
|
|
f16_read = {x["a"] for i in insns if base_op(i["op"]) in ("v_interp_p1ll_f16", "v_interp_p1lv_f16",
|
|
"v_interp_p2_f16")
|
|
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:
|
|
g.per_vertex = f16_read
|
|
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)
|
|
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 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 = [(reg, ctype) for reg, _, _, ctype in 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"):
|
|
g.emulate = True
|
|
size = (g.cs or g.ms)["size"]
|
|
g.x_lanes = -(-size[0] * size[1] * size[2] // 64) * 64
|
|
insns = fold_far_branches(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 (attribute() weights them with the operand values).
|
|
g.per_vertex |= interp_ij_analysis(insns, g)
|
|
branchy = any(base_op(i["op"]) in BRANCHES for i in insns)
|
|
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], [[]])
|
|
g.build_meta = _shader_meta.collect(path, info["name"], [insns], [[]],
|
|
user_sgpr_limit=user_limit, system_sgprs=sys_sgprs)
|
|
g.fit_shared_memory()
|
|
for ins in insns:
|
|
if base_op(ins["op"]) == "s_endpgm":
|
|
break
|
|
g.insn(ins)
|
|
translate.last_gen = g
|
|
return assemble(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.vm_latch = stage == "ps" and exec_changes_after_vm(blocks, succ)
|
|
g.park_masks((blocks, succ))
|
|
halves_analysis(g, blocks, succ)
|
|
g.build_meta = _shader_meta.collect(path, info["name"], blocks, succ,
|
|
user_sgpr_limit=user_limit, system_sgprs=sys_sgprs)
|
|
|
|
g.bar_rounds = needs_barrier_rounds(g, blocks, succ)
|
|
g.fit_shared_memory()
|
|
g.x_seg = len(blocks) + 1 # emulate: continuation segments are numbered after "done" (len(blocks))
|
|
for n, blk in enumerate(blocks):
|
|
g.body = []
|
|
g.block_label = f"%blk{n}"
|
|
g.x_marks, g.x_dirty = [], 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() # a cached lookup is only good inside the block that made it
|
|
g.sgpr_imm.clear()
|
|
term = None
|
|
for ins in blk:
|
|
op = base_op(ins["op"])
|
|
if op == "s_endpgm":
|
|
term = ("end",)
|
|
break
|
|
if op in BRANCHES:
|
|
term = ("br", op, index[target(ins)])
|
|
break
|
|
g.insn(ins)
|
|
edges = raw_edges[n]
|
|
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")
|
|
g.succ.append([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)}")
|
|
g.succ.append([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 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")
|
|
g.succ.append(list(dict.fromkeys([tgt] + ([fall] if fall is not None else []))))
|
|
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
|
|
else:
|
|
g.blocks.append(lines)
|
|
assert succ == g.succ, "the lane-mask analysis ran on a different graph"
|
|
g.body = []
|
|
translate.last_gen = g
|
|
return assemble(g)
|
|
|
|
|
|
_DEF = re.compile(r"(%\w+) = (Op\w+)(?: (%\w+))?")
|
|
|
|
|
|
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 = cfg_structure.structure(succ) if STRUCTURED else None
|
|
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", "image_store", "ds_write")):
|
|
continue
|
|
for r in range(a[0]["r"], a[0]["r"] + a[0].get("n", 1) + (1 if "tfe" in ins["mods"] else 0)):
|
|
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_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."""
|
|
c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731
|
|
x_waves, x_mask, x_sched, 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":
|
|
L += ["%x_li = OpLoad %uint %local_index"]
|
|
else:
|
|
L += ["%x_lid = OpLoad %v3uint %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"OpStore %x_zp{k} {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"OpStore %x_yp{k}_{par} {c(0)}"]
|
|
L += [f"OpControlBarrier {c(2)} {c(2)} {c(0x948)}",
|
|
"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"OpStore %x_mp5 {c(0)}",
|
|
"%x_mp6 = OpAccessChain %_ptr_WG_uint_x %x_buf %x_m6", f"OpStore %x_mp6 {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"OpStore %x_qp3 {c(0)}",
|
|
"%x_qp4 = OpAccessChain %_ptr_WG_uint_x %x_buf %x_q4", f"OpStore %x_qp4 {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
|
|
sorted(list(range(len(gen.blocks))) + list(gen.x_segs)))]
|
|
return L
|
|
|
|
|
|
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).
|
|
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"]
|
|
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)}",
|
|
# 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(0x108)}",
|
|
"OpBranch %loop_head", "%loop_head = OpLabel", "OpLoopMerge %loop_exit %loop_cont None",
|
|
"OpBranch %xb_round", "%xb_round = OpLabel",
|
|
"%xb_itv = OpLoad %uint %x_it", 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)."""
|
|
c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731
|
|
return ["%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",
|
|
# 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, workgroup memory), now in uniform control flow;
|
|
# it also orders the count, read below.
|
|
f"OpControlBarrier {c(2)} {c(2)} {c(0x108)}",
|
|
"%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)}")
|
|
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)))
|
|
binds = sorted({int(b) for b in re.findall(r"OpDecorate %\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",
|
|
"MinLod": "shaderResourceMinLod", "Image1D": "shaderImage1D? (core)", "Sampled1D": "core",
|
|
"ClipDistance": "shaderClipDistance", "CullDistance": "shaderCullDistance",
|
|
"ShaderLayer": "shaderOutputLayer", "ShaderViewportIndex": "shaderOutputViewportIndex",
|
|
"FMAKHR": "shaderFmaFloat32"} # VkPhysicalDeviceShaderFmaFeaturesKHR (VK_KHR_shader_fma)
|
|
m = {"stage": g.stage, "wave64": bool(g.wave64), "control_flow": getattr(g, "control_flow", "straight line"),
|
|
"capabilities": caps, "extensions": exts,
|
|
"features": sorted({feats[c] for c in caps if c in feats and not feats[c].startswith(("core", "shaderImage1D"))}),
|
|
"bindings": binds, "push_constant_bytes": 4 * USER_SGPRS + 16,
|
|
"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.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.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
|
|
if "Offset " in asm and re.search(r"OpImageSample\w+ [^\n]*Offset", asm):
|
|
m["needs_maintenance8"] = True
|
|
if g.uses_codebase:
|
|
m["uses_code_base"] = True
|
|
if g.cs:
|
|
m["local_size"] = list(g.cs["size"])
|
|
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.ms:
|
|
m["local_size"] = list(g.ms["size"])
|
|
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.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]}. A pipeline links when every PS entry
|
|
# is among its producer's (see F16_HALVES).
|
|
if g.stage == "ps":
|
|
ns = sorted(g.f16_halves)
|
|
elif g.stage == "ms":
|
|
ns = sorted(g.ms_params)
|
|
else:
|
|
ns = sorted({int(t[5:]) for t in g.outputs.values() if t.startswith("param")})
|
|
ns = [n for n in ns if g.stage == "ps" or f16_half_location(n, 0) > g.param_max]
|
|
if ns:
|
|
m["f16_halves"] = {str(n): [f16_half_location(n, 0), f16_half_location(n, 1)] for n in ns}
|
|
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 g.build_meta:
|
|
m.update(g.build_meta)
|
|
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 = path + ".tmp" # must not end in .json: --merge globs index.part*.json
|
|
with open(tmp, "w", encoding="utf-8", newline="\n") as f:
|
|
_json.dump(index, f, indent=0, sort_keys=True)
|
|
f.flush()
|
|
os.fsync(f.fileno()) # on disk before the rename, or a power cut could leave the name with no data
|
|
os.replace(tmp, path) # ponytail: no retry; add one if a scanner on Windows ever holds the new file open
|
|
|
|
|
|
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<i>.json markers a --shard run writes beside its index.part<i>.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 merge_shard_parts(out):
|
|
"""{shader: meta} from index.part*.json, after checking the set is complete.
|
|
|
|
A --shard i/n run writes index.part<i>.json and shard<i>.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."""
|
|
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<i>.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)}")
|
|
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 = [i for i in range(expected) if i not in set(indices)]
|
|
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})"
|
|
+ (f", missing {missing}" if missing else "")
|
|
+ (f", unexpected {extra}" if extra else "")
|
|
+ "; let every --shard run finish before --merge")
|
|
elif indices != list(range(len(indices))):
|
|
gap = [i for i in range(max(indices) + 1) if i not in set(indices)]
|
|
raise ShardSetError(f"incomplete shard set: parts {sorted(indices)} are not contiguous from 0"
|
|
+ (f", missing {gap}" if gap else "")
|
|
+ "; 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:
|
|
with open(part, encoding="utf-8") as f:
|
|
doc = _js.load(f)
|
|
if not isinstance(doc, dict):
|
|
raise ShardSetError(f"{part} does not contain a shader index object")
|
|
merged.update(doc)
|
|
return merged
|
|
|
|
|
|
def assemble_spirv(sa, sv):
|
|
"""Keep the assembled module out of the final path until validation succeeds."""
|
|
with tempfile.NamedTemporaryFile(prefix=".spirv-", suffix=".tmp", dir=os.path.dirname(sv), delete=False) as f:
|
|
tmp = Path(f.name)
|
|
try:
|
|
result = subprocess.run(["spirv-as", sa, "-o", str(tmp), "--target-env", "vulkan1.2"],
|
|
capture_output=True, text=True)
|
|
if result.returncode == 0:
|
|
# Offset on non-gather: VK_KHR_maintenance8
|
|
result = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", "--allow-offset-texture-operand",
|
|
str(tmp)], capture_output=True, text=True)
|
|
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_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 main():
|
|
global MAX_SHARED_BYTES
|
|
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 every n-th shader starting at i (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("--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 <name>.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("--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("--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("--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("--fma", choices=("glsl", "khr"), 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; needs VK_KHR_shader_fma + shaderFmaFloat32, listed in the "
|
|
"shader's metadata as capability FMAKHR / feature shaderFmaFloat32)")
|
|
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")
|
|
a = ap.parse_args()
|
|
MAX_SHARED_BYTES = a.max_shared_memory
|
|
global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, F16_HALVES
|
|
FMA_KHR = a.fma == "khr"
|
|
STRUCTURED = not a.dispatch_loop
|
|
WAVE64_EMULATE = a.wave64_emulate
|
|
WAVE64_GRAPHICS = a.wave64_graphics
|
|
BARY_FALLBACK = a.bary_fallback
|
|
TEXEL_OFFSET_FALLBACK = a.texel_offset_fallback
|
|
MESH_COMPUTE = a.mesh_compute
|
|
F16_HALVES = a.f16_interp_fallback
|
|
if a.merge:
|
|
try:
|
|
merged = merge_shard_parts(a.out)
|
|
except ShardSetError as e:
|
|
print(f"ERROR: {e}", 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)
|
|
print(f"merged {len(merged)} entries")
|
|
return 0
|
|
if os.path.isfile(a.src) and a.src.endswith(".s"):
|
|
files = [a.src]
|
|
elif os.path.isdir(a.src):
|
|
with os.scandir(a.src) as entries:
|
|
files = sorted(e.path for e in entries if e.name.endswith(".s") and e.is_file())
|
|
else:
|
|
ap.error(f"{a.src} is not a .s file or a folder of .s files")
|
|
files = files[: a.limit] if a.limit is not None else files
|
|
shard = None
|
|
if a.shard:
|
|
si, sn = a.shard
|
|
files = files[si::sn]
|
|
shard = si
|
|
os.makedirs(a.out, exist_ok=True)
|
|
why, ok, valid = Counter(), 0, 0
|
|
meta = {}
|
|
invalid = set()
|
|
|
|
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 p in files:
|
|
name = os.path.splitext(os.path.basename(p))[0]
|
|
try:
|
|
asm = translate(p)
|
|
except Unsupported as e:
|
|
why[str(e)] += 1
|
|
drop_stale(name)
|
|
continue
|
|
except (IndexError, KeyError, ValueError) as e:
|
|
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")
|
|
with open(sa, "w", newline="\n") as f:
|
|
f.write(asm)
|
|
r = assemble_spirv(sa, sv)
|
|
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:
|
|
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)
|
|
import json as _js
|
|
idx_path = os.path.join(a.out, f"index.part{shard}.json" if shard is not None else "index.json")
|
|
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 not None: # a marker beside the part, so --merge can tell a complete set from a partial one
|
|
write_index(os.path.join(a.out, SHARD_MARKER.format(index=shard)), {"index": shard, "count": sn})
|
|
write_index(idx_path, old)
|
|
if shard is None:
|
|
import spirv_stubs
|
|
spirv_stubs.generate_for_index(a.out, old)
|
|
print(f"{len(files)} shaders: {ok} translated, {valid} pass spirv-val")
|
|
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 __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())
|