diff --git a/docs/experiments.md b/docs/experiments.md index b31ebc06b9..e499a4bbca 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7531,11 +7531,15 @@ Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_b64_shift$' -V`. (#870, issue #1919). They now lower as `~(S0 & S1)`, `~(S0 | S1)` and `~(S0 ^ S1)` on 32 bits, the text `pixel_aot` uses, and set SCC when the result is nonzero like the other logic operations. The check decodes SGPR, in-place, inline-constant, literal and m0-destination forms and evaluates the emitted lines against an -integer reference over 0, all ones, alternating bits, every single bit and mixed words. Lane-mask forms (a -vcc_lo/exec_lo operand or destination, or an SGPR holding a compare mask) are refused: guest SCC reads the whole -32-bit mask, which the per-lane projection cannot show. A table +integer reference over 0, all ones, alternating bits, every single bit and mixed words. A table entry without the complement or without the SCC write must fail, and SOP2 operations with no lowering stay -refused by name. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sop2_complement$' -V`; with +refused by name. On lane masks (vcc_lo, exec_lo or an SGPR holding a compare mask) the result is exact per lane +when every source is a mask, because bit i of the complement depends only on bit i of each source: that form +lowers to `(~(a op b)) & 1` into an SGPR, checked on all 32 lanes of the edge words. Guest SCC reads the whole +32-bit result, which the per-lane projection cannot show, so SCC is not emitted and a program that can read it +before the next SCC write is refused, through joins and back edges. A mask mixed with a plain word or a constant +and a vcc_lo or exec_lo destination stay refused, as does a mask source whose last write does not dominate a +branch target crossed since, or which a block on a path to that target writes again. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sop2_complement$' -V`; with LLVM 15, `tests/startup_gfx2hlsl_sop2_complement_check.py binary ` and `decode ` round-trip the same words. diff --git a/tests/startup_gfx2hlsl_sop2_complement_check.py b/tests/startup_gfx2hlsl_sop2_complement_check.py index 2655ba1342..6c1b7de02d 100644 --- a/tests/startup_gfx2hlsl_sop2_complement_check.py +++ b/tests/startup_gfx2hlsl_sop2_complement_check.py @@ -16,9 +16,18 @@ The lowering text and SCC rule equal pixel_aot's SCALAR entries for the same operations (#561). Every numeric form (SGPR, inline, literal or m0 operands) emits the lines of its non-complement sibling (s_and_b32, s_or_b32, s_xor_b32) -with the operation wrapped in ~( ). Lane-mask forms are refused: a vcc_lo or exec_lo operand or destination, or an -SGPR holding a compare mask, is the whole wave's mask, and SCC is set when any bit of the complemented 32-bit result -is; the translator's per-lane projection cannot show that, so no mask lowering is claimed. +with the operation wrapped in ~( ). + +Lane masks: vcc_lo, exec_lo or an SGPR holding a compare mask is the whole wave's mask, of which the translator keeps +one lane's bit. Bit i of ~(S0 op S1) depends only on bit i of each source, so with every source a lane mask and an +SGPR destination the lane's bit of the result is exact: the form is accepted and checked here on every lane of the +edge words. SCC is set when any bit of the complemented 32-bit result is, which the other lanes decide (the bit of an +idle lane is set); the per-lane projection cannot show that, so SCC is not emitted and a program that can read it +before the next SCC write is refused (through branches too). A mask and a plain word mixed, a constant source, and a +vcc_lo or exec_lo destination stay refused. The mask mark follows program order, so a mark is a proof at a branch +target only if the register's last write dominates the target and no block on a path from that write to the target +writes the register again; otherwise the complement is refused until the register is written again. Mutations: the +join rule disabled and the SCC read scan disabled must each accept a refused program. Mutations: the table entry with the complement dropped, and the entry with the SCC write dropped, must each read a wrong result or SCC. Refused: every SOP2 operation the decoder names that still has no lowering. @@ -228,6 +237,124 @@ def first_mismatch(name, reference=None, updates_scc=True): return None +def run_text(*instructions): + """Translate disassembly text with the branch scan of a real stage -> emitted lines.""" + stage = Probe() + stage.attrs = {} + stage.ins = [(4 * i, 4, asm.split()[0], asm) for i, asm in enumerate(instructions)] + stage.translate() + return [line for _, lines, _ in stage.blocks for line in lines] + + +def text_refusal(*instructions): + try: + return 'accepted: %s' % run_text(*instructions) + except G.Unsupported as error: + return str(error) + + +def lane_mask_controls(): + operator = {name: SIBLING_OPERATOR[sibling] for name, (sibling, _) in OPS.items()} + # 1. Every source a lane mask, SGPR destination: one line, the lane's bit of the complement, and no SCC write. + forms = [('s3, s1, s2', 's3', 's1', 's2'), ('s1, s2, s1', 's1', 's2', 's1'), ('s3, vcc_lo, s1', 's3', 'vcc', 's1'), + ('s3, s2, exec_lo', 's3', 's2', 'exec'), ('s3, vcc_lo, exec_lo', 's3', 'vcc', 'exec')] + for name, (_, reference) in OPS.items(): + wrong = [] + for operands, dest, left, right in forms: + stage = Probe() + stage.masks.update((1, 2)) + stage.one(name, '%s %s' % (name, operands)) + expected = ['%s = (~(%s %s %s)) & 1;' % (dest, left, operator[name], right)] + if stage.lines != expected or int(dest[1:]) not in stage.masks or stage.scc_effect != 'a lane-mask complement': + wrong.append((operands, stage.lines, expected, sorted(stage.masks), stage.scc_effect)) + continue + for a, b in ((a, b) for a in SPECIAL for b in SPECIAL): + for lane in range(32): + env = {left: (a >> lane) & 1, right: (b >> lane) & 1, 'scc': SCC_UNSET} + out = run_lines(stage.lines, env) + if (out[dest], out['scc']) != ((reference(a, b) >> lane) & 1, SCC_UNSET): + wrong.append((operands, hex(a), hex(b), lane, out[dest], out['scc'])) + break + check('%s: %d all-mask forms give the lane bit of the reference on 32 lanes x %d pairs, SCC not written' + % (name, len(forms), len(SPECIAL) ** 2), not wrong, str(wrong[:2])) + + # 2. Still refused: a constant or plain-word source next to a mask, a mask destination, a high-half mask name. + for name in OPS: + wrong = [] + for operands in ('s3, s1, s9', 's3, s9, vcc_lo', 's3, s1, -1', 's3, 0, vcc_lo', 'vcc_lo, s1, s2', + 'exec_lo, s1, s2', 's3, s1, vcc_hi', 'm0, s1, s2'): + stage = Probe() + stage.masks.update((1, 2)) + try: + stage.one(name, '%s %s' % (name, operands)) + wrong.append((operands, stage.lines)) + except G.Unsupported as error: + if str(error) != '%s on a lane mask' % name or stage.lines: + wrong.append((operands, str(error), stage.lines)) + check('%s: mixed, constant and mask-destination forms stay refused' % name, not wrong, str(wrong[:2])) + + # 3. Whole programs. SCC after the complement is not the guest's: a read before the next SCC write is refused. + masks = ('v_cmp_eq_f32_e64 s5, 0, v1', 'v_cmp_lt_f32_e64 s4, 0, v2') + for name in OPS: + complement = '%s s4, s5, s4' % name + line = 's4 = (~(s5 %s s4)) & 1;' % operator[name] + lines = run_text(*masks, complement, 's_and_saveexec_b32 s4, s4', 's_endpgm') + at = lines.index(line) if line in lines else -1 + check('%s between two compares and s_and_saveexec_b32 is accepted' % name, + at >= 0 and lines[at + 1:at + 3] == ['w = s4;', 's4 = exec;'] and 'scc = s4 != 0;' not in lines, str(lines)) + lines = run_text(*masks, complement, 's_cmp_eq_u32 s2, 0', 's_cselect_b32 s6, 1, 0', 's_endpgm') + check('%s then an SCC write then a read is accepted' % name, + line in lines and any(text.startswith('s6 = scc ?') for text in lines), str(lines)) + programs = { + 's_cselect_b32': (*masks, complement, 's_cselect_b32 s6, 1, 0', 's_endpgm'), + 's_cbranch_scc1': (*masks, complement, 's_cbranch_scc1 label_0010', 's_endpgm'), + # the read sits behind a jump that skips the SCC write + 's_cmov_b32': (*masks, complement, 's_branch label_0014', 's_cmp_eq_u32 s2, 0', 's_cmov_b32 s6, s7', + 's_endpgm'), + # the read sits at a loop head that the complement reaches over the back edge + 's_cselect_b64': ('s_cmp_eq_u32 s2, 0', 's_cselect_b64 s[6:7], 1, 0', *masks, complement, + 's_cbranch_vccz label_0004', 's_endpgm'), + } + got = {reader: text_refusal(*program) for reader, program in programs.items()} + want = {reader: 'scc from a lane-mask complement in %s' % reader for reader in programs} + check('%s: an SCC read before the next SCC write is refused (%d programs)' % (name, len(programs)), + got == want, str(got)) + + # 4. The mask mark at a branch target. + skip = ('s_cmp_eq_u32 s2, 0', 's_cbranch_scc1 label_0010', *masks) # the branch skips both compares + loop = (*masks, 's_nand_b32 s6, s5, s4', 's_mov_b32 s5, s3', 's_cmp_eq_u32 s2, 0', 's_cbranch_scc0 label_0008', + 's_endpgm') # the body overwrites s5 before the back edge + arms = ('v_cmp_eq_f32_e64 s5, 0, v1', 's_cmp_eq_u32 s2, 0', 's_cbranch_scc1 label_0014', 'v_cmp_lt_f32_e64 s4, 0, v2', + 's_branch label_0020', 'v_cmp_lt_f32_e64 s4, 0, v3', 's_nand_b32 s4, s5, s4', 's_and_saveexec_b32 s4, s4', + 's_endpgm') # s5 is written before the split only + joined = 's_nand_b32 on a lane mask joined at a branch target' + got = [text_refusal(*skip, 's_nand_b32 s6, s5, s4', 's_endpgm'), text_refusal(*loop)] + check('a mask that another path into the branch target changes is refused (skipped write, loop body write)', + got == [joined, joined], str(got)) + lines = run_text(*arms) + check('a mask written before the split and on no arm crosses the join', 's4 = (~(s5 & s4)) & 1;' in lines, str(lines)) + lines = run_text(*skip, *masks, 's_nand_b32 s6, s5, s4', 's_endpgm') + check('a mask written again after the join is proven again', 's6 = (~(s5 & s4)) & 1;' in lines, str(lines)) + got = text_refusal(*masks, 's_mov_b32 s5, s3', 's_nand_b32 s6, s5, s4', 's_endpgm') + check('an overwritten mask is a plain word: refused', got == 's_nand_b32 on a lane mask', got) + + # 5. Mutations: each rule disabled accepts a program refused above. + saved = G.Stage.unjoined_masks + G.Stage.unjoined_masks = lambda self, target, last_write: set() + try: + got = [text_refusal(*skip, 's_nand_b32 s6, s5, s4', 's_endpgm'), text_refusal(*loop)] + finally: + G.Stage.unjoined_masks = saved + check('mutation without the join rule accepts both programs', all(t.startswith('accepted') for t in got), str(got)) + saved = G.Stage.descriptor_scc_reads + G.Stage.descriptor_scc_reads = lambda self, branches, effects: iter(()) + try: + got = text_refusal(*masks, 's_nand_b32 s4, s5, s4', 's_cselect_b32 s6, 1, 0', 's_endpgm') + finally: + G.Stage.descriptor_scc_reads = saved + check('mutation without the SCC read scan accepts the read', got.startswith('accepted'), got) + + def pack_controls(): def reference(a, b): return (b // 65536) * 65536 + a // 65536 @@ -501,7 +628,7 @@ def controls(): check('%s: %d numeric forms emit the %s lines complemented, same mask and EXEC bookkeeping' % (name, len(VALUE_FORMS), sibling), not wrong, str(wrong[:2])) - # 5b. Lane-mask forms are refused: vcc_lo/exec_lo operands and destinations, and an SGPR holding a compare mask. + # 5b. Refused: a lane mask next to a plain word, or as the destination (lane_mask_controls has the accepted forms). for name in OPS: accepted = [] for form in MASK_FORMS: @@ -560,6 +687,7 @@ def controls(): wrong.append((asm, str(error))) check('%d SOP2 operations without a lowering are refused by name (%s)' % (len(missing), ', '.join(missing)), missing and not wrong and not set(OPS) & set(missing), str(wrong)) + lane_mask_controls() pack_controls() bfe_controls() mul_controls() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 6f1bf62bc6..5b7581e446 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1618,8 +1618,35 @@ def joined_registers(self, with_cfg=False): regs = set().union(*(writes[w] for w in div)) if div else set() affected = ({off_of[w] for w in div} | ({off_of[ipd]} if ipd is not None else set())) & all_targets div_targets[off] = (regs, affected) + self.flow = (index, block_of, succ, dom, writes, {}) return joined, forward_splits, div_targets + def unjoined_masks(self, target, last_write): + """Marked SGPRs whose mark is not proven at a branch target. self.masks follows program order, so a mark + holds on every path into the target only if the block of the register's last write dominates the target and + no block on a path from that write to the target writes the register again.""" + index, block_of, succ, dom, writes, reached = self.flow + if target not in index: + return set(self.masks) + def after(block): # blocks reached from block over at least one edge + if block not in reached: + seen, todo = set(), list(succ[block]) + while todo: + b = todo.pop() + if b not in seen: + seen.add(b) + todo += succ[b] + reached[block] = seen + return reached[block] + t = block_of[index[target]] + into = {b for b in range(len(succ)) if t in after(b)} + out = set() + for reg in self.masks: + w = block_of[index[last_write[reg]]] if reg in last_write else 0 + if w not in dom[t] or any(reg in writes[b] for b in (after(w) & into) - {w}): + out.add(reg) + return out + def translate(self): refusals = getattr(self, 'refusals', None) # unit probes build a Stage without __init__ try: @@ -1671,6 +1698,8 @@ def translate(self): self.exec_known = init_exec_known self.wqm_exec = init_wqm_exec self.masks = set(init_masks) + self.join_masks = set() # marked SGPRs whose mark is not proven on every path (unjoined_masks) + last_write = {} # SGPR -> offset of its last write in program order self.attrs = dict(init_attrs) self.used_s, self.used_v = set(init_used_s), set(init_used_v) self.exports = {} @@ -1748,6 +1777,7 @@ def translate(self): if reg != 'm0': self.used_s.add(reg) clobber = here if off in joined else every_sgpr + self.join_masks |= self.unjoined_masks(off, last_write) fwd_clobber = forward_splits.get(off, clobber) blocked = force_unproven | force_at.get(off, set()) kept_u = { @@ -1786,6 +1816,7 @@ def translate(self): falls = name not in ('s_branch', 's_setpc_b64', 's_endpgm') dests = scalar_destinations(name, asm) written |= every_sgpr if 'any' in dests else dests + last_write.update(dict.fromkeys(dests, off)) try: if off in refused: raise Unsupported(refused[off]) @@ -1815,6 +1846,8 @@ def translate(self): raise refusals.append((handler_error(name, error, refusals), self.kind)) continue + # A write proves the mark again: every path from here on runs it. s_movreld can write any SGPR. + self.join_masks = (self.join_masks | every_sgpr) if 'any' in dests else self.join_masks - dests if self.scc_effect: scc_effects[off] = self.scc_effect if term: @@ -1843,9 +1876,9 @@ def translate(self): if self.lines: self.blocks.append((start, self.lines, None)) self.materialized = materialize # declarations() assigns these before the body (and before any loop) - if 'descriptor' in scc_effects.values(): - for name in self.descriptor_scc_reads(dict(branches), scc_effects): - reason = 'scc from descriptor data in %s' % name + if set(scc_effects.values()) - {'emitted'}: + for kind, name in self.descriptor_scc_reads(dict(branches), scc_effects): + reason = 'scc from %s in %s' % ('descriptor data' if kind == 'descriptor' else kind, name) if refusals is None: raise Unsupported(reason) refusals.append((reason, self.kind)) @@ -1860,7 +1893,7 @@ def translate(self): def descriptor_scc_reads(self, branches, effects): """Find reads reachable with an elided SCC write, including through joins and back edges.""" instructions = {off: (size, name, asm) for off, size, name, asm in self.ins} - pending = [(0, False)] + pending = [(0, None)] # stale: None, or the scc_effect of the write that left the emitted scc behind seen = set() while pending: off, stale = pending.pop() @@ -1869,9 +1902,9 @@ def descriptor_scc_reads(self, branches, effects): seen.add((off, stale)) size, name, asm = instructions[off] if stale and off not in self.calculated_pc and reads_scc(name, asm): - yield name + yield stale, name if off in effects: - stale = effects[off] == 'descriptor' + stale = effects[off] if effects[off] != 'emitted' else None if off in branches: pending.append((branches[off], stale)) if name not in ('s_branch', 's_setpc_b64', 's_endpgm'): @@ -2383,6 +2416,7 @@ def low(tok): srcs = [str(sopk_imm(srcs[0], True))] # D.i32 = signext(SIMM16) shift_add = base in SHIFT_ADD word_complement = base in ('s_nand_b32', 's_nor_b32', 's_xnor_b32') + lane_complement = False # s_mul_hi_u32 needs the whole 32-bit word of each source, like the halfword pack. word_pack = base in ('s_pack_hh_b32_b16', 's_sext_i32_i8', 's_sext_i32_i16', 's_mul_hi_u32') if shift_add or word_complement or word_pack: @@ -2390,8 +2424,19 @@ def low(tok): # SGPR that held a mask replaces it with a plain word (set_s drops the mark), so only vcc/exec count. mask_dest = (dname in ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi') if base == 's_mul_hi_u32' else self.is_lane_mask(dname)) - if mask_dest or any(self.is_lane_mask(t) for t in srcs): + # Bit i of ~(S0 op S1) depends only on bit i of each source, so with every source a lane mask the lane's + # bit of the result is exact. Only an SGPR destination is taken; a mixed mask and plain word is not. + def mask_source(tok): + r = reg_range(tok) + return tok in ('vcc', 'vcc_lo', 'exec', 'exec_lo') or bool( + r and r[0] == 's' and r[1] == r[2] and r[1] in self.masks) + lane_complement = (word_complement and bool(dst) and dst[0] == 's' and dst[1] == dst[2] and dst[1] <= 105 + and all(mask_source(t) for t in srcs)) + if not lane_complement and (mask_dest or any(self.is_lane_mask(t) for t in srcs)): raise Unsupported('%s on a lane mask' % base) + if lane_complement and any(reg_range(t) and reg_range(t)[1] in getattr(self, 'join_masks', ()) + for t in srcs): + raise Unsupported('%s on a lane mask joined at a branch target' % base) if shift_add and dname != 'm0' and (not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105): raise Unsupported('%s destination %s' % (base, dname)) if word_pack: @@ -2531,7 +2576,13 @@ def known(tok): high_source = 's%d' % high if high is not None else srcs[0] high_uniform = (self.tracks_uniformity() and high != d and self.uniform_source(high_source)) - self.set_s(d, expr, scc=scc) + self.set_s(d, expr, scc=None if lane_complement else scc) + if lane_complement: + # The guest SCC is (the whole complemented word != 0), which the bits of every other lane decide (an + # idle lane's bit is set). It is not emitted: translate() refuses a program that can read it. + self.scc_effect = 'a lane-mask complement' + if self.tracks_uniformity(): + self.scc_uniform = False if is_mask: self.masks.add(d) if pair and base != 's_mov_b64':