Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 144 additions & 0 deletions tests/semantic/test_ballot_bit_loop.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
"""A scalar loop over the lanes of a ballot, inside a wave64 loop that ends on a vote (SHADER-WAVE-LOOP-EXEC-VOTE).

The compiler walks the lanes a ballot found with a scalar loop: `s_and_b64 s[26:27], vcc, exec`, then
`s_ff1_i32_b32` / `s_xor_b32` of s26 and `s_mov_b32 s26, sN` on the back edge, so s26 is a lane mask on the way in and
a number around the loop. The translator keeps a mask as each lane's own bit (0 or ~0) and data as one number, and at
the loop header took s26 as data without gathering the mask's bits: every lane found its own first bit and took its
own number of passes, where the wave takes one (lane_masks.insert_data_merges now gathers them on the way in).

The program is hand-written in the shape of a library compute program that ran its outer loop to the loop guard
(#1608, SHADER-LIB-LOOP-AT-GUARD): an outer loop over the lanes' work items, 64 apart, that ends when
`v_cmpx_le` + `s_andn2_b64 saved, saved, exec` leaves no lane; inside it, one bit loop over each half of a ballot with a
lane-local `s_cbranch_execz` region. No game data.

python -I tests/semantic/test_ballot_bit_loop.py
"""
import os
import sys
import unittest

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from test_loop_ballot_barrier import VSHARP, _translate_cs, run_compute_workgroup # noqa: E402


def program(count):
p = [
f"s_movk_i32 s12, {count}",
"s_mov_b64 s[14:15], exec",
"s_add_u32 s16, s12, 63", # s16 = min(ceil(count / 64), 4) * 64: the passes, at most 4
"s_lshr_b32 s16, s16, 6",
"s_min_u32 s16, s16, 4",
"s_lshl_b32 s16, s16, 6",
"v_mov_b32_e32 v1, v0", # the lane, kept
"v_mov_b32_e32 v2, 0", # passes of the outer loop
"v_mov_b32_e32 v3, 0", # passes of the bit loops' lane-local regions
"v_cmpx_gt_i32_e32 s16, v0",
"s_cbranch_execz done",
"s_mov_b64 s[18:19], exec",
"s_mov_b64 s[24:25], exec", # the lanes still looping
"s_branch body",
"head:",
"s_mov_b64 exec, s[24:25]",
"body:",
"v_add_nc_u32_e32 v2, 1, v2",
"v_cmpx_gt_u32_e32 s12, v0", # the lanes with an item this pass
"v_and_b32_e32 v4, 1, v0",
"v_cmp_eq_u32_e32 vcc, 0, v4", # ... whose item is even: the ballot
"s_and_b64 s[26:27], vcc, exec",
"s_mov_b64 exec, s[24:25]",
# Lanes 0-31 of the ballot, one pass per lane set; lanes below 16 count them.
"s_cmp_lg_i32 s26, 0",
"s_cbranch_scc0 after_lo",
"lo:",
"s_ff1_i32_b32 s32, s26",
"s_lshl_b32 s32, 1, s32",
"s_xor_b32 s35, s32, s26",
"v_cmp_gt_u32_e32 vcc, 16, v1",
"s_and_b64 exec, vcc, exec",
"s_cbranch_execz skip_lo",
"v_add_nc_u32_e32 v3, 1, v3",
"skip_lo:",
"s_mov_b64 exec, s[24:25]",
"s_cmp_eq_i32 s26, s32",
"s_cbranch_scc1 after_lo",
"s_mov_b32 s26, s35",
"s_branch lo",
"after_lo:",
# Lanes 32-63, the same through s27; lanes above 47 count them in the second byte.
"s_cmp_lg_i32 s27, 0",
"s_cbranch_scc0 after_hi",
"hi:",
"s_ff1_i32_b32 s32, s27",
"s_lshl_b32 s32, 1, s32",
"s_xor_b32 s35, s32, s27",
"v_cmp_lt_u32_e32 vcc, 47, v1",
"s_and_b64 exec, vcc, exec",
"s_cbranch_execz skip_hi",
"v_add_nc_u32_e32 v3, 0x100, v3",
"skip_hi:",
"s_mov_b64 exec, s[24:25]",
"s_cmp_eq_i32 s27, s32",
"s_cbranch_scc1 after_hi",
"s_mov_b32 s27, s35",
"s_branch hi",
"after_hi:",
# The next item 64 on; the loop ends when no lane has one left.
"v_add_nc_u32_e32 v0, 64, v0",
"v_cmpx_le_i32_e32 s16, v0",
"s_andn2_b64 s[24:25], s[24:25], exec",
"s_cbranch_scc1 head",
"s_mov_b64 exec, s[18:19]",
"done:",
"s_mov_b64 exec, s[14:15]",
"v_lshlrev_b32_e32 v6, 3, v1",
"buffer_store_dword v2, v6, s[0:3], 0 offen offset:0",
"buffer_store_dword v3, v6, s[0:3], 0 offen offset:4",
"s_endpgm",
]
return p


def expected(count):
"""(outer passes, bit-loop visits) per lane, as one wave64 runs it."""
limit = min((count + 63) >> 6, 4) << 6
item = {t: t for t in range(64)}
passes = {t: 0 for t in range(64)}
visits = {t: 0 for t in range(64)}
alive = [t for t in range(64) if item[t] < limit]
while alive:
for t in alive:
passes[t] += 1
ballot = [t for t in alive if item[t] < count and item[t] % 2 == 0]
for _ in [t for t in ballot if t < 32]:
for t in alive:
visits[t] += 1 if t < 16 else 0
for _ in [t for t in ballot if t >= 32]:
for t in alive:
visits[t] += 0x100 if t > 47 else 0
for t in alive:
item[t] += 64
alive = [t for t in alive if item[t] < limit]
return {t: (passes[t], visits[t]) for t in range(64)}


class BallotBitLoop(unittest.TestCase):
def test_every_lane_walks_the_wave_ballot(self):
configs = [
("native64", False, 64, True),
("emulate_sg32", True, 32, True),
("emulate_sg32_rounds", True, 32, False),
]
for count in (100, 200, 7):
want = expected(count)
for label, emulate, sg, structured in configs:
with self.subTest(count=count, mode=label):
spv, _ = _translate_cs(f"cs_ballot_bit_loop_{label}_{count}", program(count), threads=64,
emulate=emulate, structured=structured)
mem = run_compute_workgroup(spv, 64, sg, push_constants=VSHARP)
for t in range(64):
got = (mem.get(8 * t, -1), mem.get(8 * t + 4, -1))
self.assertEqual(got, want[t], f"{label} count {count} lane {t}")


if __name__ == "__main__":
unittest.main()
43 changes: 43 additions & 0 deletions tests/test_lane_masks.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,48 @@ def test_wave32_vcc_hi_isolation():
assert out_w64 == {}


def test_mask_meets_data_at_a_merge():
"""insert_data_merges: a lane mask that a merge takes as data gets the wave's bits on the way there (the scalar
loop over a ballot's lanes: s_and_b64 s[26:27], vcc, exec, then s_ff1 / s_xor of s26 and s_mov_b32 s26 on the
back edge). Only where every successor takes it as data and one may still read it."""
branches = {"s_branch", "s_cbranch_scc0", "s_cbranch_scc1", "s_endpgm"}

def bit_loop():
return [
[ins("v_cmp_eq_u32_e32", sp("vcc"), imm(0), v(4)), ins("s_and_b64", s(26, 2), sp("vcc"), sp("exec")),
ins("s_cmp_lg_i32", s(26), imm(0)), ins("s_cbranch_scc0")], # 0
[ins("s_ff1_i32_b32", s(32), s(26)), ins("s_lshl_b32", s(32), imm(1), s(32)), # 1: loop header
ins("s_xor_b32", s(35), s(32), s(26)), ins("s_cmp_eq_i32", s(26), s(32)), ins("s_cbranch_scc1")],
[ins("s_mov_b32", s(26), s(35)), ins("s_branch")], # 2: back edge
[ins("s_endpgm")], # 3
], [[3, 1], [3, 2], [1], []]

blocks, succ = bit_loop()
# Before: s26 is a mask where block 0 ends and data at the loop header (a number on the back edge).
assert masks_at_last(blocks, succ, 0) >= {26}
assert 26 not in L.analyse(blocks, succ)[0][id(blocks[1][0])]
assert L.insert_data_merges(blocks, succ, branches) == 1
marker = blocks[0][-2]
assert marker["op"] == L.TO_DATA and marker["args"][0] == s(26) == marker["args"][1]
assert L.base_op(blocks[0][-1]["op"]) == "s_cbranch_scc0" # before the branch
# The marker itself still sees the mask (it gathers it) and leaves data behind it.
assert 26 in L.analyse(blocks, succ)[0][id(marker)]
assert 26 not in L.analyse(blocks, succ)[0][id(blocks[0][-1])]
# s27 is a mask at the merge too, but nothing reads it again: no gather for it. Running again adds nothing.
assert all(i["args"][0]["r"] != 27 for blk in blocks for i in blk if i["op"] == L.TO_DATA)
assert L.insert_data_merges(blocks, succ, branches) == 0

# A successor that still reads the register as a mask keeps this lane's bit: nothing is inserted.
blocks = [[ins("s_mov_b64", s(6, 2), sp("exec")), ins("s_cbranch_scc0")],
[ins("s_mov_b64", sp("exec"), s(6, 2)), ins("s_endpgm")]]
assert L.insert_data_merges(blocks, [[1], []], branches) == 0
# A mask on both paths to a merge is no data merge.
blocks = [[ins("s_mov_b64", s(6, 2), sp("exec")), ins("s_cbranch_scc0")],
[ins("s_and_b64", s(6, 2), s(6, 2), sp("vcc"))],
[ins("s_bcnt1_i32_b64", s(8), s(6, 2)), ins("s_endpgm")]]
assert L.insert_data_merges(blocks, [[2, 1], [2], []], branches) == 0


if __name__ == "__main__":
test_straight_line()
test_joins()
Expand All @@ -387,4 +429,5 @@ def test_wave32_vcc_hi_isolation():
test_writelane_sdwa_dpp_swaps_stores_and_div_scale()
test_v_and_or_xnor_bfi_track_vector_masks()
test_wave32_vcc_hi_isolation()
test_mask_meets_data_at_a_merge()
print("ok")
159 changes: 159 additions & 0 deletions tools/lane_masks.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,165 @@ def parked(blocks, masks):
return sorted(found)


TO_DATA = "s_mask_to_data_b32" # the translator's own: sD = the real bits of the lane-mask word in sD


def _fixpoint(blocks, succ, wave64):
"""Each block's state on entry (None where it is not reached), as analyse() works it out."""
entry = [None] * len(blocks)
if blocks:
entry[0] = {}
work = [0] if blocks else []
while work:
n = work.pop()
state = dict(entry[n])
for ins in blocks[n]:
step(state, ins, wave64)
for s in succ[n]:
merged = dict(state) if entry[s] is None else _merge(entry[s], state)
if merged != entry[s]:
entry[s] = merged
work.append(s)
return entry


def _merge(a, b):
"""A mask on both paths, or a mask on one and 0 / -1 on the other; anything else is data (left out)."""
merged = {}
for r in a.keys() & b.keys():
a_k, b_k = a[r], b[r]
if a_k == b_k:
merged[r] = a_k
elif a_k == EITHER:
merged[r] = b_k
elif b_k == EITHER:
merged[r] = a_k
else:
merged[r] = MASK
return merged


ALL = "all" # an instruction that may read any SGPR (s_movrels / s_movrelsd: the register comes from M0)


def _sgprs(x):
if x.get("k") == "sgpr":
return set(range(x["r"], x["r"] + x.get("n", 1)))
if x.get("k") == "slist":
return {r for r in x["r"] if isinstance(r, int)}
return set()


def _reads_writes(ins):
"""The SGPR numbers `ins` reads and the ones it surely writes (a destination it may leave alone is read too)."""
op, a = base_op(ins["op"]), ins["args"]
if op.startswith(("s_movrels", "s_movreld", "s_swappc", "s_setpc", "s_getpc", "s_call", "s_cbranch_g_fork")):
return ALL, set()
if not a:
return set(), set()
if op.startswith(NO_DESTINATION):
reads = set()
for x in a:
if x is not None:
reads |= _sgprs(x)
return reads, set()
reads = set()
for x in a[1:]:
if x is not None:
reads |= _sgprs(x)
# A SOPK read-modify-write, a 16-bit or SDWA/DPP partial write, or a VOP3b carry-out pair: the first operand is
# taken as read too, which only ever keeps a register live.
if op in ("s_addk_i32", "s_mulk_i32", "s_cmovk_i32") or op.startswith("s_cmov") or \
ins["op"].endswith(("_sdwa", "_dpp", "_dpp8")) or "_co_" in op:
reads |= _sgprs(a[0])
return reads, set()
return reads, _sgprs(a[0])


def _live_in(blocks, succ):
"""The SGPR numbers each block may read before writing (ALL for every one)."""
use, kill = [], []
for blk in blocks:
u, k = set(), set()
for ins in blk:
r, w = _reads_writes(ins)
if r is ALL:
u = ALL
break
u |= r - k
k |= w
use.append(u)
kill.append(k)
live = [set() if u is not ALL else ALL for u in use]
changed = True
while changed:
changed = False
for n in range(len(blocks) - 1, -1, -1):
if live[n] is ALL:
continue
out = set()
for s in succ[n]:
if live[s] is ALL:
out = ALL
break
out |= live[s]
new = ALL if out is ALL else (use[n] | (out - kill[n]))
if new != live[n]:
live[n] = new
changed = True
return live


def insert_data_merges(blocks, succ, branches, wave64=True):
"""In place: where an SGPR holds a lane mask at the end of a block but is data where a successor begins (a
mask on one path to it, a number on another), insert a TO_DATA instruction for it before the block's branch.

The two kinds of value are kept differently: a mask as this lane's bit (all ones or zero), data as the same
number in every lane. Where they meet the register is taken as data, which the path that wrote the mask does
not hold. The compiler makes such a merge when it walks the lanes of a ballot with a scalar loop:
`s_and_b64 s[26:27], vcc, exec`, then s_ff1_i32_b32 / s_xor_b32 of s26 and `s_mov_b32 s26, sN` on the back
edge. The loop's s26 was this lane's 0 / ~0 on the first pass, so each lane found its own first bit and took
its own number of passes, where the wave takes one. TO_DATA gathers the wave's real bits into the register
(rdna2spirv's lane_mask_word), so the loop sees on every path what the hardware has.

A register is converted only when every successor takes it as data (one that still reads it as a mask keeps
this lane's bit) and some successor may read it before writing it: the gather is a cross-lane step, and a
register nothing reads again needs none. A later mask use of the converted register stays exact: the
translator takes bit L of a data register for lane L (rdna2spirv's mask_src). `branches`: the opcodes that end
a block. Returns how many instructions were inserted."""
inserted = 0
live = _live_in(blocks, succ)
for _ in range(len(blocks) + 1): # each round only takes masks away, so this ends
entry = _fixpoint(blocks, succ, wave64)
added = 0
for n, blk in enumerate(blocks):
if entry[n] is None or not succ[n]:
continue
state = dict(entry[n])
for ins in blk:
step(state, ins, wave64)
regs = []
for r, k in sorted((r, k) for r, k in state.items() if isinstance(r, int) and k in MASK_KINDS):
if all(entry[s] is not None and r not in entry[s] for s in succ[n]) and \
any(live[s] is ALL or r in live[s] for s in succ[n]):
regs.append(r)
if not regs:
continue
last = blk[-1] if blk else None
at = len(blk) - 1 if last is not None and (base_op(last["op"]) in branches) else len(blk)
pc = last.get("pc", 0) if last is not None else 0
for r in regs:
reg = {"k": "sgpr", "r": r, "n": 1}
blk.insert(at, {"op": TO_DATA, "args": [dict(reg), dict(reg)], "mods": [], "pc": pc, "enc": "",
"synthetic": True})
at += 1
added += 1
inserted += added
if not added:
break
return inserted


def analyse(blocks, succ, *, include_either=False, wave64=True):
entry = [None] * len(blocks) # None: not reached yet
if blocks:
Expand Down
9 changes: 9 additions & 0 deletions tools/rdna2spirv.py
Original file line number Diff line number Diff line change
Expand Up @@ -7556,6 +7556,13 @@ def insn(self, ins):
self.x_memory_order(base_op(ins["op"]))
self.cur_either = self.lane_either.get(id(ins), ())
try:
if ins["op"] == lane_masks.TO_DATA:
# A lane mask that a merge further on takes as data (lane_masks.insert_data_merges): the
# register gets the wave's real bits, the same number in every lane.
src = ins["args"][1]
val = self.lane_mask_word(src) if self.holds_lane_mask(src) else self.src_u(src)
self.dst(ins["args"][0], val)
return None
if ins["op"].endswith("_dpp"):
bop = base_op(ins["op"])
if bop in SOPC_CMP32_OPS or bop in SOPC_CMP64_OPS or bop in SOPC_BITCMP_OPS:
Expand Down Expand Up @@ -18938,6 +18945,8 @@ def target(ins):
succ = [list(dict.fromkeys(e)) for e in raw_edges]
g.out_pcs = _block_out_pcs(blocks, raw_edges, succ)
g.vm_latch = stage == "ps" and exec_changes_after_vm(blocks, succ)
# A lane mask that meets data at a merge is turned into the wave's bits on the way there (lane_masks.py).
lane_masks.insert_data_merges(blocks, succ, BRANCHES | {"s_endpgm"}, wave64=g.wave64)
g.park_masks((blocks, succ))
halves_analysis(g, blocks, succ)
g.build_meta = _shader_meta.collect(path, info["name"], blocks, succ,
Expand Down
1 change: 1 addition & 0 deletions tools/wave64_emulate_opt.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
"s_bcnt0_i32_b32", "s_bcnt1_i32_b32", "s_bcnt0_i32_b64", "s_bcnt1_i32_b64",
"s_ff0_i32_b32", "s_ff1_i32_b32", "s_ff0_i32_b64", "s_ff1_i32_b64",
"s_flbit_i32_b32", "s_flbit_i32_b64", "s_flbit_i32",
"s_mask_to_data_b32", # lane_masks.TO_DATA: the mask's bits where a merge takes the register as data
})

# Mask ops that emit a cross-lane vote in --wave64-emulate when SCC is live.
Expand Down
Loading