diff --git a/tests/test_spirv_opt.py b/tests/test_spirv_opt.py index 764eeed7e8..201684d5a6 100644 --- a/tests/test_spirv_opt.py +++ b/tests/test_spirv_opt.py @@ -6,6 +6,7 @@ import sys import tempfile import unittest +from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TOOLS = os.path.join(ROOT, "tools") @@ -60,6 +61,57 @@ def test_alu_chain_bit_exact_and_shrinks_significantly(self): self.assertLess(len(opt.splitlines()), len(raw.splitlines()) * 0.5) self.assertNotIn("OpLoad %bool %active", opt) + def test_alias_resolution_requires_a_surviving_definition(self): + for aliases in ({"a": "a"}, {"a": "b", "b": "a"}, {"a": "b", "b": "c", "c": "b"}): + with self.subTest(aliases=aliases): + before = aliases.copy() + with self.assertRaises(spirv_opt._CyclicAlias): + spirv_opt._resolve_alias(aliases, "a") + self.assertEqual(aliases, before) + + aliases = {"a": "b", "b": "terminal"} + self.assertEqual(spirv_opt._resolve_alias(aliases, "a"), "terminal") + self.assertEqual(aliases["a"], "terminal") + self.assertEqual(spirv_opt._resolve_alias(aliases, "other"), "other") + + def test_cyclic_substitution_preserves_the_function_and_its_names(self): + affected_body = ( + "%affected = OpFunction %void None %fn\n" + "%entry_a = OpLabel\n" + "%affected_copy = OpCopyObject %uint %one\n" + "OpReturn\n" + "OpFunctionEnd\n" + ) + module = ( + "OpCapability Shader\n" + "OpMemoryModel Logical GLSL450\n" + 'OpEntryPoint GLCompute %affected "main"\n' + "OpExecutionMode %affected LocalSize 1 1 1\n" + 'OpName %affected_copy "affected copy"\n' + 'OpName %regular_copy "regular copy"\n' + "%void = OpTypeVoid\n%fn = OpTypeFunction %void\n" + "%uint = OpTypeInt 32 0\n%one = OpConstant %uint 1\n" + + affected_body + + "%regular = OpFunction %void None %fn\n" + "%entry_b = OpLabel\n" + "%regular_copy = OpCopyObject %uint %one\n" + "OpReturn\n" + "OpFunctionEnd\n" + ) + resolve = spirv_opt._resolve_alias + + def inject_cycle(aliases, token): + if "%affected_copy" in aliases: + return resolve({"a": "b", "b": "a"}, "a") + return resolve(aliases, token) + + with mock.patch.object(spirv_opt, "_resolve_alias", side_effect=inject_cycle): + optimized = spirv_opt.optimize(module) + self.assertIn(affected_body, optimized) + self.assertIn('OpName %affected_copy "affected copy"', optimized) + self.assertNotIn("%regular_copy", optimized) + _validate(optimized) + def test_dynamic_register_indexing_preserved_soundly(self): # v_movrels_b32 / s_movrels_b32 use dynamic OpAccessChain into %vgpr / %sgpr; optimizer must NOT # drop stores or forward stale values across dynamic accesses. diff --git a/tools/spirv_opt.py b/tools/spirv_opt.py index 828cf2e9bf..34d23752cc 100644 --- a/tools/spirv_opt.py +++ b/tools/spirv_opt.py @@ -380,6 +380,27 @@ def _fold_int_op(op: str, res_ty: str, args: list[str], return None +class _CyclicAlias(Exception): + """A proposed result replacement chain has no surviving definition.""" + + +def _resolve_alias(aliases: dict[str, str], token: str) -> str: + target = aliases.get(token) + if target is None: + return token + if target not in aliases: + return target + + seen = {token} + while target in aliases: + if target in seen: + raise _CyclicAlias + seen.add(target) + target = aliases[target] + aliases[token] = target + return target + + def _optimize_function(body_lines: list[str], const_ids: set[str], const_true: set[str], const_false: set[str], const_null_elem_zero: dict[str, str], const_type: dict[str, str], const_int_val: dict[str, tuple[str, int, int, int]], @@ -540,14 +561,6 @@ def strictly_dominates(a: int, b: int) -> bool: alias: dict[str, str] = {} - def resolve(tok: str) -> str: - cur = tok - while cur in alias: - cur = alias[cur] - if cur != tok: - alias[tok] = cur - return cur - dead_idx: set[int] = set() # Scoped dominator-tree tables (maintained via undo logs during iterative DFS). @@ -578,7 +591,7 @@ def process_block(b: int, slot_val: dict[tuple, str], entry_null_zero: dict[str, continue if alias and args: - new_args = [resolve(t) if t.startswith("%") else t for t in args] + new_args = [_resolve_alias(alias, t) if t.startswith("%") else t for t in args] if new_args != args: entry[2] = new_args args = new_args @@ -941,7 +954,7 @@ def process_block(b: int, slot_val: dict[tuple, str], entry_null_zero: dict[str, _, op, args, _ = entry if op is None or not args: continue - new_args = [resolve(t) if t.startswith("%") else t for t in args] + new_args = [_resolve_alias(alias, t) if t.startswith("%") else t for t in args] if new_args != args: entry[2] = new_args changed = True @@ -1130,12 +1143,18 @@ def optimize(spvasm: str, max_passes: int = 4) -> str: all_deleted: set[str] = set() opt_funcs: dict[int, list[str]] = {} for start, end in func_ranges: - new_body, deleted = _optimize_function( - lines[start:end], const_ids, const_true, const_false, - const_null_elem_zero, const_type, const_int_val, int_const_by_val, - int_type_info, readonly_global_vars, glsl_sets, decorated_ids, - max_passes=max_passes, - ) + body = lines[start:end] + try: + new_body, deleted = _optimize_function( + body, const_ids, const_true, const_false, + const_null_elem_zero, const_type, const_int_val, int_const_by_val, + int_type_info, readonly_global_vars, glsl_sets, decorated_ids, + max_passes=max_passes, + ) + except _CyclicAlias: + # A cyclic substitution cannot justify deleting definitions from this function. + opt_funcs[start] = body + continue opt_funcs[start] = new_body all_deleted.update(deleted)