diff options
| author | edwin042331-hue <edwin042331@gmail.com> | 2026-11-22 11:54:15 -0400 |
|---|---|---|
| committer | edwin042331-hue <edwin042331@gmail.com> | 2026-11-22 11:54:15 -0400 |
| commit | 4d9ef4eb27e48110e57c8a81bafa66a3841283d2 (patch) | |
| tree | f797a2fc3ddeeb51cf95759e0b04990287ee269b /tools/wave64_emulate_opt.py | |
| parent | 13de8d810b01ebbbe5bf927dfa261a2c0396204b (diff) | |
wave64-emulate: add acyclic single-write folding and structured inline/hybrid emulation (#884)
Diffstat (limited to 'tools/wave64_emulate_opt.py')
| -rw-r--r-- | tools/wave64_emulate_opt.py | 569 |
1 files changed, 540 insertions, 29 deletions
diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py index 06c200c11..ee9f25690 100644 --- a/tools/wave64_emulate_opt.py +++ b/tools/wave64_emulate_opt.py | |||
| @@ -414,20 +414,39 @@ def _sgpr_pair(x): | |||
| 414 | return None | 414 | return None |
| 415 | 415 | ||
| 416 | 416 | ||
| 417 | def _x_memory_order_access(op): | ||
| 418 | """Exact mirror of Gen.x_memory_order(op) in tools/rdna2spirv.py -> (kind, reads, writes) or None.""" | ||
| 419 | if op in ("ds_swizzle_b32", "ds_bpermute_b32", "ds_permute_b32", "ds_nop"): | ||
| 420 | return None | ||
| 421 | if op.startswith("ds_"): | ||
| 422 | kind = "lds" | ||
| 423 | elif op.startswith(("buffer_", "tbuffer_", "global_", "flat_", "image_load", "image_store", "image_atomic", | ||
| 424 | "s_load_", "s_buffer_load_")): | ||
| 425 | kind = "mem" | ||
| 426 | else: | ||
| 427 | return None | ||
| 428 | store = "store" in op or op.startswith("ds_write") | ||
| 429 | reads = not store | ||
| 430 | writes = store or "atomic" in op or (kind == "lds" and not op.startswith("ds_read")) | ||
| 431 | return kind, reads, writes | ||
| 432 | |||
| 433 | |||
| 417 | def _classify_block_body(insns, lane_masks, scc_live, mask_writes): | 434 | def _classify_block_body(insns, lane_masks, scc_live, mask_writes): |
| 418 | """Inspect non-terminator instructions of a block for lane-local region safety. | 435 | """Inspect non-terminator instructions of a block for lane-local region safety. |
| 419 | 436 | ||
| 420 | Returns `(clean, mem_reads, may_write_scalars, exec_writes, sgpr_write_ops)` where: | 437 | Returns `(clean, mem_stats, may_write_scalars, exec_writes, sgpr_write_ops)` where: |
| 421 | - `clean`: True if no instruction does a cross-lane op, barrier, memory write, or unmasked side effect. | 438 | - `clean`: True if no instruction does a cross-lane op, barrier, or unmasked side effect. |
| 422 | - `mem_reads`: subset of {"lds", "mem"}. | 439 | - `mem_stats`: `(mem_ops, mem_r, mem_w, lds_ops, lds_r, lds_w)` counting EXEC-masked memory/LDS ops. |
| 423 | - `may_write_scalars`: int bitmask of scalar regs possibly written. | 440 | - `may_write_scalars`: int bitmask of scalar regs possibly written. |
| 424 | - `exec_writes`: list of `(op, args)` that write EXEC. | 441 | - `exec_writes`: list of `(op, args)` that write EXEC. |
| 425 | - `sgpr_write_ops`: list of `(sgpr_bitmask, op, args)` for every instruction writing any SGPR. | 442 | - `sgpr_write_ops`: list of `(sgpr_bitmask, op, args)` for every instruction writing any SGPR. |
| 426 | """ | 443 | """ |
| 427 | mem_reads = set() | 444 | mem_ops = lds_ops = 0 |
| 445 | mem_r = mem_w = lds_r = lds_w = False | ||
| 428 | may_w = 0 | 446 | may_w = 0 |
| 429 | exec_writes = [] | 447 | exec_writes = [] |
| 430 | sgpr_write_ops = [] | 448 | sgpr_write_ops = [] |
| 449 | empty_stats = (0, False, False, 0, False, False) | ||
| 431 | 450 | ||
| 432 | for ins in insns: | 451 | for ins in insns: |
| 433 | raw_op = ins["op"] | 452 | raw_op = ins["op"] |
| @@ -436,51 +455,67 @@ def _classify_block_body(insns, lane_masks, scc_live, mask_writes): | |||
| 436 | break | 455 | break |
| 437 | if id(ins) in mask_writes: | 456 | if id(ins) in mask_writes: |
| 438 | # write_all_lanes VGPR store (parked lane mask): runs even when EXEC == 0, so must not be skipped. | 457 | # write_all_lanes VGPR store (parked lane mask): runs even when EXEC == 0, so must not be skipped. |
| 439 | return False, frozenset(), 0, (), () | 458 | return False, empty_stats, 0, (), () |
| 440 | a = ins["args"] | 459 | a = ins["args"] |
| 441 | lm = lane_masks.get(id(ins), {}) | 460 | lm = lane_masks.get(id(ins), {}) |
| 442 | 461 | ||
| 443 | # 1. Strictly forbidden opcodes inside a lane-local folded region. | 462 | # 1. Strictly forbidden opcodes inside a lane-local folded region (cross-lane, barrier, unmasked writes). |
| 444 | if raw_op.endswith(("_dpp", "_dpp8")): | 463 | if raw_op.endswith(("_dpp", "_dpp8")): |
| 445 | return False, frozenset(), 0, (), () | 464 | return False, empty_stats, 0, (), () |
| 446 | if op in ("s_barrier", "s_sendmsg", "s_setpc_b64", "s_swappc_b64", "s_trap", | 465 | if op in ("s_barrier", "s_sendmsg", "s_setpc_b64", "s_swappc_b64", "s_trap", |
| 447 | "s_sethalt", "s_setkill", "s_sleep", "s_setprio", | 466 | "s_sethalt", "s_setkill", "s_sleep", "s_setprio", |
| 448 | "s_round_mode", "s_denorm_mode", | 467 | "s_round_mode", "s_denorm_mode", |
| 449 | "v_readlane_b32", "v_readfirstlane_b32", "v_writelane_b32", | 468 | "v_readlane_b32", "v_readfirstlane_b32", "v_writelane_b32", |
| 450 | "v_permlane16_b32", "v_permlanex16_b32", | 469 | "v_permlane16_b32", "v_permlanex16_b32", |
| 451 | "ds_bpermute_b32", "ds_permute_b32", "ds_swizzle_b32", | 470 | "ds_bpermute_b32", "ds_permute_b32", "ds_swizzle_b32", |
| 471 | "ds_gws_init", "ds_gws_sema_v", "ds_gws_sema_br", "ds_gws_sema_p", "ds_gws_barrier", | ||
| 472 | "ds_consume", "ds_append", "ds_ordered_count", | ||
| 452 | "s_wqm_b32", "s_wqm_b64", "s_quadmask_b32", "s_quadmask_b64"): | 473 | "s_wqm_b32", "s_wqm_b64", "s_quadmask_b32", "s_quadmask_b64"): |
| 453 | return False, frozenset(), 0, (), () | 474 | return False, empty_stats, 0, (), () |
| 454 | if op.startswith(("s_movrel", "s_setreg", "s_getreg", "s_store", "s_buffer_store", "s_atomic", "exp")): | 475 | if op.startswith(("s_movrel", "s_setreg", "s_getreg", "s_store", "s_buffer_store", "s_atomic", |
| 455 | return False, frozenset(), 0, (), () | 476 | "ds_gws", "exp")): |
| 456 | if "store" in op or "atomic" in op: | 477 | return False, empty_stats, 0, (), () |
| 457 | return False, frozenset(), 0, (), () | 478 | |
| 458 | if op.startswith("ds_"): | 479 | acc = _x_memory_order_access(op) |
| 459 | if not op.startswith("ds_read"): | 480 | if acc is not None: |
| 460 | return False, frozenset(), 0, (), () | 481 | kind, r, w = acc |
| 461 | mem_reads.add("lds") | 482 | if kind == "lds": |
| 462 | elif op.startswith(("buffer_", "tbuffer_", "global_", "flat_", "scratch_", | 483 | lds_ops += 1 |
| 463 | "s_load_", "s_buffer_load_", | 484 | lds_r = lds_r or r |
| 464 | "image_load", "image_sample", "image_gather", "image_bvh")): | 485 | lds_w = lds_w or w |
| 465 | mem_reads.add("mem") | 486 | else: |
| 487 | mem_ops += 1 | ||
| 488 | mem_r = mem_r or r | ||
| 489 | mem_w = mem_w or w | ||
| 490 | elif op.startswith(("scratch_", "image_sample", "image_gather", "image_bvh")): | ||
| 491 | if "store" in op or "atomic" in op: | ||
| 492 | mem_ops += 1 | ||
| 493 | mem_w = True | ||
| 494 | if "atomic" in op: | ||
| 495 | mem_r = True | ||
| 496 | else: | ||
| 497 | mem_ops += 1 | ||
| 498 | mem_r = True | ||
| 499 | elif "store" in op or "atomic" in op: | ||
| 500 | return False, empty_stats, 0, (), () | ||
| 466 | 501 | ||
| 467 | # 2. Cross-lane mask readers (`wave_mask`, `wave_equal`, live-SCC `scc_from_mask`). | 502 | # 2. Cross-lane mask readers (`wave_mask`, `wave_equal`, live-SCC `scc_from_mask`). |
| 468 | if op in ("s_bcnt0_i32_b32", "s_bcnt1_i32_b32", "s_bcnt0_i32_b64", "s_bcnt1_i32_b64", | 503 | if op in ("s_bcnt0_i32_b32", "s_bcnt1_i32_b32", "s_bcnt0_i32_b64", "s_bcnt1_i32_b64", |
| 469 | "s_ff0_i32_b32", "s_ff1_i32_b32", "s_ff0_i32_b64", "s_ff1_i32_b64"): | 504 | "s_ff0_i32_b32", "s_ff1_i32_b32", "s_ff0_i32_b64", "s_ff1_i32_b64"): |
| 470 | if len(a) > 1 and _holds_lane_mask(ins, a[1], lm): | 505 | if len(a) > 1 and _holds_lane_mask(ins, a[1], lm): |
| 471 | return False, frozenset(), 0, (), () | 506 | return False, empty_stats, 0, (), () |
| 472 | elif op in ("v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32"): | 507 | elif op in ("v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32"): |
| 473 | if len(a) > 1 and a[1].get("k") != "imm" and _holds_lane_mask(ins, a[1], lm): | 508 | if len(a) > 1 and a[1].get("k") != "imm" and _holds_lane_mask(ins, a[1], lm): |
| 474 | return False, frozenset(), 0, (), () | 509 | return False, empty_stats, 0, (), () |
| 475 | elif op.startswith(("s_cmp", "s_bitcmp")): | 510 | elif op.startswith(("s_cmp", "s_bitcmp")): |
| 476 | if any(_holds_lane_mask(ins, x, lm) for x in a): | 511 | if any(_holds_lane_mask(ins, x, lm) for x in a): |
| 477 | return False, frozenset(), 0, (), () | 512 | return False, empty_stats, 0, (), () |
| 478 | elif op in _MASK_SCC_VOTE_OPS and id(ins) in scc_live: | 513 | elif op in _MASK_SCC_VOTE_OPS and id(ins) in scc_live: |
| 479 | # Would emit scc_from_mask -> x_round if operating on a lane mask (matches Gen.is_mask_op). | 514 | # Would emit scc_from_mask -> x_round if operating on a lane mask (matches Gen.is_mask_op). |
| 480 | is_mask_dst = bool(a) and a[0].get("k") == "special" and a[0].get("t", "").startswith(("exec", "vcc")) | 515 | is_mask_dst = bool(a) and a[0].get("k") == "special" and a[0].get("t", "").startswith(("exec", "vcc")) |
| 481 | if "saveexec" in op or "wrexec" in op or op.endswith("_mask") or is_mask_dst \ | 516 | if "saveexec" in op or "wrexec" in op or op.endswith("_mask") or is_mask_dst \ |
| 482 | or any(_is_mask_op(ins, x, lm) for x in a[1:]): | 517 | or any(_is_mask_op(ins, x, lm) for x in a[1:]): |
| 483 | return False, frozenset(), 0, (), () | 518 | return False, empty_stats, 0, (), () |
| 484 | 519 | ||
| 485 | # 3. Track scalar writes and EXEC writes. | 520 | # 3. Track scalar writes and EXEC writes. |
| 486 | _, ins_mw, _ = _scalar_rw(ins) | 521 | _, ins_mw, _ = _scalar_rw(ins) |
| @@ -493,7 +528,7 @@ def _classify_block_body(insns, lane_masks, scc_live, mask_writes): | |||
| 493 | if writes_exec: | 528 | if writes_exec: |
| 494 | exec_writes.append((op, a)) | 529 | exec_writes.append((op, a)) |
| 495 | 530 | ||
| 496 | return True, frozenset(mem_reads), may_w, exec_writes, sgpr_write_ops | 531 | return True, (mem_ops, mem_r, mem_w, lds_ops, lds_r, lds_w), may_w, exec_writes, sgpr_write_ops |
| 497 | 532 | ||
| 498 | 533 | ||
| 499 | def _is_zero_val(x, zero_pairs): | 534 | def _is_zero_val(x, zero_pairs): |
| @@ -572,12 +607,86 @@ def _exec_writes_stay_inactive(region_blocks, blk_info, run_live_in): | |||
| 572 | return True | 607 | return True |
| 573 | 608 | ||
| 574 | 609 | ||
| 610 | def _tree_has_loop(tree): | ||
| 611 | """Iterative check whether a cfg_structure tree contains any loop node.""" | ||
| 612 | if not tree: | ||
| 613 | return False | ||
| 614 | stack = [tree] | ||
| 615 | while stack: | ||
| 616 | for it in stack.pop(): | ||
| 617 | if it[0] == "loop": | ||
| 618 | return True | ||
| 619 | if it[0] == "guard": | ||
| 620 | stack.append(it[2]) | ||
| 621 | return False | ||
| 622 | |||
| 623 | |||
| 624 | def _blocks_in_tree(tree): | ||
| 625 | """Iterative set of all block ids appearing in a cfg_structure tree (or single item).""" | ||
| 626 | out = set() | ||
| 627 | stack = [tree if isinstance(tree, list) else [tree]] | ||
| 628 | while stack: | ||
| 629 | for it in stack.pop(): | ||
| 630 | if it[0] == "block": | ||
| 631 | out.add(it[1]) | ||
| 632 | else: | ||
| 633 | stack.append(it[2]) | ||
| 634 | return out | ||
| 635 | |||
| 636 | |||
| 637 | def _map_tree_ids(tree, mapping): | ||
| 638 | """Iterative copy of a cfg_structure tree replacing every compact id with `mapping[id]`.""" | ||
| 639 | out = [] | ||
| 640 | stack = [(tree, out)] | ||
| 641 | while stack: | ||
| 642 | src, dst = stack.pop() | ||
| 643 | for it in src: | ||
| 644 | if it[0] == "block": | ||
| 645 | dst.append(("block", mapping[it[1]])) | ||
| 646 | else: | ||
| 647 | child = [] | ||
| 648 | dst.append((it[0], mapping[it[1]], child)) | ||
| 649 | stack.append((it[2], child)) | ||
| 650 | return out | ||
| 651 | |||
| 652 | |||
| 653 | def _region_has_cycle(region, succ): | ||
| 654 | """Iterative 3-color cycle check over the subgraph induced by `region`.""" | ||
| 655 | color = {} | ||
| 656 | for start in region: | ||
| 657 | if start in color: | ||
| 658 | continue | ||
| 659 | color[start] = 1 | ||
| 660 | stack = [(start, iter(succ[start]))] | ||
| 661 | while stack: | ||
| 662 | u, it = stack[-1] | ||
| 663 | for v in it: | ||
| 664 | if v not in region: | ||
| 665 | continue | ||
| 666 | c = color.get(v, 0) | ||
| 667 | if c == 1: | ||
| 668 | return True | ||
| 669 | if c == 0: | ||
| 670 | color[v] = 1 | ||
| 671 | stack.append((v, iter(succ[v]))) | ||
| 672 | break | ||
| 673 | else: | ||
| 674 | color[u] = 2 | ||
| 675 | stack.pop() | ||
| 676 | return False | ||
| 677 | |||
| 678 | |||
| 575 | def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_writes=frozenset()): | 679 | def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_writes=frozenset()): |
| 576 | """Find safe lane-local `s_cbranch_execz`/`nz` regions to fold inline under --wave64-emulate. | 680 | """Find safe lane-local `s_cbranch_execz`/`nz` regions to fold inline under --wave64-emulate. |
| 577 | 681 | ||
| 682 | Allows read-only regions (including regions with internal scalar-counted loops) AND acyclic | ||
| 683 | single-write-per-domain regions (at most one store/atomic touching `"mem"` or `"lds"` with no | ||
| 684 | other access to that domain inside the region). | ||
| 685 | |||
| 578 | Returns `(folds, fold_chain, absorbed)`: | 686 | Returns `(folds, fold_chain, absorbed)`: |
| 579 | - `folds`: dict `head_block -> {"run": int, "skip": int, "region": frozenset[int], | 687 | - `folds`: dict `head_block -> {"run": int, "skip": int, "region": frozenset[int], |
| 580 | "order": list[int], "sub_tree": list | None, "mem_reads": frozenset[str]}` | 688 | "order": list[int], "sub_tree": list | None, "mem_reads": frozenset[str], |
| 689 | "mem_writes": frozenset[str], "mem_stats": tuple}` | ||
| 581 | containing only the maximal (outermost) folded regions. | 690 | containing only the maximal (outermost) folded regions. |
| 582 | - `fold_chain`: dict `head_block -> skip_block` when `skip_block` has no predecessors outside | 691 | - `fold_chain`: dict `head_block -> skip_block` when `skip_block` has no predecessors outside |
| 583 | `{head_block} | region` and can be emitted directly after the fold in the same block. | 692 | `{head_block} | region` and can be emitted directly after the fold in the same block. |
| @@ -647,6 +756,21 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr | |||
| 647 | break | 756 | break |
| 648 | if not ok: | 757 | if not ok: |
| 649 | continue | 758 | continue |
| 759 | # Memory-write safety: if R writes "mem" (or "lds"), R must be acyclic and touch that domain at most once. | ||
| 760 | mem_ops = lds_ops = 0 | ||
| 761 | mem_r = mem_w = lds_r = lds_w = False | ||
| 762 | for u in region: | ||
| 763 | mo, mr, mw, lo, lr, lw = blk_info[u][1] | ||
| 764 | mem_ops += mo | ||
| 765 | mem_r = mem_r or mr | ||
| 766 | mem_w = mem_w or mw | ||
| 767 | lds_ops += lo | ||
| 768 | lds_r = lds_r or lr | ||
| 769 | lds_w = lds_w or lw | ||
| 770 | if (mem_w and mem_ops > 1) or (lds_w and lds_ops > 1): | ||
| 771 | continue | ||
| 772 | if (mem_w or lds_w) and _region_has_cycle(region, succ): | ||
| 773 | continue | ||
| 650 | # No scalar written in R may be live-in at `skip`. | 774 | # No scalar written in R may be live-in at `skip`. |
| 651 | region_may_w = 0 | 775 | region_may_w = 0 |
| 652 | for u in region: | 776 | for u in region: |
| @@ -656,12 +780,13 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr | |||
| 656 | # EXEC must stay inactive for any lane that skipped R. | 780 | # EXEC must stay inactive for any lane that skipped R. |
| 657 | if not _exec_writes_stay_inactive(region, blk_info, scalar_live_in[run]): | 781 | if not _exec_writes_stay_inactive(region, blk_info, scalar_live_in[run]): |
| 658 | continue | 782 | continue |
| 659 | candidates.append((len(region), b, run, skip, frozenset(region))) | 783 | candidates.append((len(region), b, run, skip, frozenset(region), |
| 784 | (mem_ops, mem_r, mem_w, lds_ops, lds_r, lds_w))) | ||
| 660 | 785 | ||
| 661 | # Validate innermost regions first so nested s_cbranch_execz/nz inside an outer region are already verified. | 786 | # Validate innermost regions first so nested s_cbranch_execz/nz inside an outer region are already verified. |
| 662 | candidates.sort(key=lambda item: (item[0], item[1])) | 787 | candidates.sort(key=lambda item: (item[0], item[1])) |
| 663 | valid = {} | 788 | valid = {} |
| 664 | for _, b, run, skip, region in candidates: | 789 | for _, b, run, skip, region, mem_stats in candidates: |
| 665 | ok = True | 790 | ok = True |
| 666 | for u in region: | 791 | for u in region: |
| 667 | tkind, top = terms[u] | 792 | tkind, top = terms[u] |
| @@ -689,7 +814,9 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr | |||
| 689 | sub_tree = cfg_structure.structure(sub_succ) | 814 | sub_tree = cfg_structure.structure(sub_succ) |
| 690 | if sub_tree is None: | 815 | if sub_tree is None: |
| 691 | continue | 816 | continue |
| 692 | mem_reads = frozenset().union(*(blk_info[u][1] for u in region)) | 817 | _, mem_r, mem_w, _, lds_r, lds_w = mem_stats |
| 818 | mem_reads = frozenset(k for k, flag in (("mem", mem_r), ("lds", lds_r)) if flag) | ||
| 819 | mem_writes = frozenset(k for k, flag in (("mem", mem_w), ("lds", lds_w)) if flag) | ||
| 693 | valid[b] = { | 820 | valid[b] = { |
| 694 | "run": run, | 821 | "run": run, |
| 695 | "skip": skip, | 822 | "skip": skip, |
| @@ -697,6 +824,8 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr | |||
| 697 | "order": order, | 824 | "order": order, |
| 698 | "sub_tree": sub_tree, | 825 | "sub_tree": sub_tree, |
| 699 | "mem_reads": mem_reads, | 826 | "mem_reads": mem_reads, |
| 827 | "mem_writes": mem_writes, | ||
| 828 | "mem_stats": mem_stats, | ||
| 700 | } | 829 | } |
| 701 | 830 | ||
| 702 | # Select maximal (non-overlapping outermost) folded regions. | 831 | # Select maximal (non-overlapping outermost) folded regions. |
| @@ -736,3 +865,385 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr | |||
| 736 | 865 | ||
| 737 | absorbed = in_region | chained | 866 | absorbed = in_region | chained |
| 738 | return selected, fold_chain, absorbed | 867 | return selected, fold_chain, absorbed |
| 868 | |||
| 869 | |||
| 870 | _SOP2_B32_LOGIC = frozenset({ | ||
| 871 | "s_and_b32", "s_or_b32", "s_xor_b32", "s_andn2_b32", "s_orn2_b32", | ||
| 872 | "s_nand_b32", "s_nor_b32", "s_xnor_b32", "s_not_b32", | ||
| 873 | }) | ||
| 874 | |||
| 875 | |||
| 876 | def _is_uniform_scc_safe(active_blocks, lane_masks, scc_live): | ||
| 877 | """True iff no instruction triggers wave64's per-lane 32-bit half-mask SCC write (rdna2spirv.py scc_logic) | ||
| 878 | with live SCC. When True, %scc is guaranteed identical across all 64 lanes of each wave.""" | ||
| 879 | for insns in active_blocks: | ||
| 880 | for ins in insns: | ||
| 881 | op = base_op(ins["op"]) | ||
| 882 | if op not in _SOP2_B32_LOGIC or id(ins) not in scc_live: | ||
| 883 | continue | ||
| 884 | a = ins["args"] | ||
| 885 | lm = lane_masks.get(id(ins), {}) | ||
| 886 | writes_exec = bool(a) and a[0].get("k") == "special" and a[0].get("t", "").startswith("exec") | ||
| 887 | if writes_exec or any(_holds_lane_mask(ins, x, lm) for x in a[1:]): | ||
| 888 | return False | ||
| 889 | return True | ||
| 890 | |||
| 891 | |||
| 892 | def _insn_may_barrier(ins, lane_masks, scc_live): | ||
| 893 | """Conservative (over-approximate) check: True if `ins` may emit x_round or OpControlBarrier in --wave64-emulate.""" | ||
| 894 | raw_op = ins["op"] | ||
| 895 | op = base_op(raw_op) | ||
| 896 | if op == "s_endpgm" or op in BRANCHES: | ||
| 897 | return False | ||
| 898 | if raw_op.endswith(("_dpp", "_dpp8")): | ||
| 899 | return True | ||
| 900 | if op in ("s_barrier", "v_readlane_b32", "v_readfirstlane_b32", | ||
| 901 | "v_permlane16_b32", "v_permlanex16_b32", | ||
| 902 | "ds_bpermute_b32", "ds_permute_b32", "ds_swizzle_b32", | ||
| 903 | "s_wqm_b32", "s_wqm_b64"): | ||
| 904 | return True | ||
| 905 | if op.startswith("s_movrel"): | ||
| 906 | return True | ||
| 907 | a = ins["args"] | ||
| 908 | lm = lane_masks.get(id(ins), {}) | ||
| 909 | if op in ("s_bcnt0_i32_b32", "s_bcnt1_i32_b32", "s_bcnt0_i32_b64", "s_bcnt1_i32_b64", | ||
| 910 | "s_ff0_i32_b32", "s_ff1_i32_b32", "s_ff0_i32_b64", "s_ff1_i32_b64"): | ||
| 911 | return len(a) > 1 and _holds_lane_mask(ins, a[1], lm) | ||
| 912 | if op in ("v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32"): | ||
| 913 | return len(a) > 1 and a[1].get("k") != "imm" and _holds_lane_mask(ins, a[1], lm) | ||
| 914 | if op.startswith(("s_cmp", "s_bitcmp")): | ||
| 915 | return any(_holds_lane_mask(ins, x, lm) for x in a) | ||
| 916 | if op in _MASK_SCC_VOTE_OPS and id(ins) in scc_live: | ||
| 917 | is_mask_dst = bool(a) and a[0].get("k") == "special" and a[0].get("t", "").startswith(("exec", "vcc")) | ||
| 918 | return ("saveexec" in op or "wrexec" in op or op.endswith("_mask") or is_mask_dst | ||
| 919 | or any(_is_mask_op(ins, x, lm) for x in a[1:])) | ||
| 920 | return False | ||
| 921 | |||
| 922 | |||
| 923 | def _dirty_conflicts(dirty, reads, writes): | ||
| 924 | return (any((k, "w") in dirty for k in reads) | ||
| 925 | or any((k, "r") in dirty or (k, "w") in dirty for k in writes)) | ||
| 926 | |||
| 927 | |||
| 928 | def plan_structured_emulation(blocks, raw_edges, succ, folds, fold_chain, absorbed, lane_masks, scc_live, x_lanes): | ||
| 929 | """Plan structured --wave64-emulate emission eliminating the giant global round-loop OpSwitch. | ||
| 930 | |||
| 931 | - Single-wave workgroups (`x_lanes == 64`): every reducible CFG emits 100% inline structured SPIR-V | ||
| 932 | with direct workgroup barriers (`0` OpSwitch cases, `0` x_spill variables, `0` scheduler atomics). | ||
| 933 | - Multi-wave workgroups (`x_lanes > 64`): decomposes top-level post-dominating spine blocks and | ||
| 934 | barrier-free guards/loops (including live-out scalars, single-write stores, EXEC-widening, and | ||
| 935 | read-only loops) into inline structured SPIR-V, isolating any remaining wave-divergent barrier | ||
| 936 | regions into tiny local mini-schedulers instead of one global K_{1,N} switch clique. | ||
| 937 | |||
| 938 | Returns `None` when the shader already collapsed to 1 superblock, is irreducible, uses non-uniform | ||
| 939 | 32-bit half-mask SCC, or (multi-wave) has a divergent `s_barrier` or no decomposition gain. | ||
| 940 | """ | ||
| 941 | n = len(blocks) | ||
| 942 | eff_blocks = [b for b in range(n) if b not in absorbed] | ||
| 943 | if len(eff_blocks) < 2: | ||
| 944 | return None # straight-line or fully folded to 1 superblock: existing x_scheduler already has <=1 case | ||
| 945 | |||
| 946 | active_blocks = [_active_insns(blk) for blk in blocks] | ||
| 947 | if not _is_uniform_scc_safe(active_blocks, lane_masks, scc_live): | ||
| 948 | return None | ||
| 949 | |||
| 950 | # Build superblock chains and effective post-fold CFG over `eff_blocks`. | ||
| 951 | eff_idx = {b: i for i, b in enumerate(eff_blocks)} | ||
| 952 | chain_of = {} | ||
| 953 | eff_succ = {} | ||
| 954 | eff_succ_compact = [] | ||
| 955 | for b in eff_blocks: | ||
| 956 | chain = [] | ||
| 957 | cur = b | ||
| 958 | while True: | ||
| 959 | chain.append(cur) | ||
| 960 | if cur in folds and cur in fold_chain: | ||
| 961 | cur = fold_chain[cur] | ||
| 962 | continue | ||
| 963 | break | ||
| 964 | chain_of[b] = chain | ||
| 965 | tail = chain[-1] | ||
| 966 | if tail in folds: | ||
| 967 | nxt = [folds[tail]["skip"]] | ||
| 968 | else: | ||
| 969 | nxt = succ[tail] | ||
| 970 | if any(s not in eff_idx for s in nxt): | ||
| 971 | return None # defensive: every effective successor must be a non-absorbed block | ||
| 972 | eff_succ[b] = nxt | ||
| 973 | eff_succ_compact.append([eff_idx[s] for s in nxt]) | ||
| 974 | |||
| 975 | compact_tree = cfg_structure.structure(eff_succ_compact) | ||
| 976 | if compact_tree is None: | ||
| 977 | return None | ||
| 978 | tree = _map_tree_ids(compact_tree, eff_blocks) | ||
| 979 | |||
| 980 | # Precompute per-superblock instruction summaries (for dirty transfer, sync-free check, s_barrier, s_endpgm). | ||
| 981 | sb_has_sbarrier = {} | ||
| 982 | sb_has_endpgm = {} | ||
| 983 | sb_may_barrier = {} | ||
| 984 | sb_mem_stats = {} | ||
| 985 | |||
| 986 | for b in eff_blocks: | ||
| 987 | has_sb = False | ||
| 988 | has_end = False | ||
| 989 | may_bar = False | ||
| 990 | mem_ops = lds_ops = 0 | ||
| 991 | mem_r = mem_w = lds_r = lds_w = False | ||
| 992 | chain = chain_of[b] | ||
| 993 | for idx_c, cur in enumerate(chain): | ||
| 994 | insns = active_blocks[cur] | ||
| 995 | for ins in insns: | ||
| 996 | op = base_op(ins["op"]) | ||
| 997 | if op == "s_endpgm": | ||
| 998 | has_end = True | ||
| 999 | break | ||
| 1000 | if op in BRANCHES: | ||
| 1001 | if idx_c == len(chain) - 1 and cur not in folds: | ||
| 1002 | if op in ("s_cbranch_execz", "s_cbranch_execnz", "s_cbranch_vccz", "s_cbranch_vccnz"): | ||
| 1003 | may_bar = True | ||
| 1004 | break | ||
| 1005 | if op == "s_barrier": | ||
| 1006 | has_sb = True | ||
| 1007 | may_bar = True | ||
| 1008 | elif _insn_may_barrier(ins, lane_masks, scc_live): | ||
| 1009 | may_bar = True | ||
| 1010 | acc = _x_memory_order_access(op) | ||
| 1011 | if acc is not None: | ||
| 1012 | kind, r, w = acc | ||
| 1013 | if kind == "lds": | ||
| 1014 | lds_ops += 1 | ||
| 1015 | lds_r = lds_r or r | ||
| 1016 | lds_w = lds_w or w | ||
| 1017 | else: | ||
| 1018 | mem_ops += 1 | ||
| 1019 | mem_r = mem_r or r | ||
| 1020 | mem_w = mem_w or w | ||
| 1021 | elif op.startswith("scratch_"): | ||
| 1022 | mem_ops += 1 | ||
| 1023 | if "store" in op or "atomic" in op: | ||
| 1024 | mem_w = True | ||
| 1025 | if "atomic" in op: | ||
| 1026 | mem_r = True | ||
| 1027 | else: | ||
| 1028 | mem_r = True | ||
| 1029 | if cur in folds: | ||
| 1030 | mo, mr, mw, lo, lr, lw = folds[cur]["mem_stats"] | ||
| 1031 | mem_ops += mo | ||
| 1032 | mem_r = mem_r or mr | ||
| 1033 | mem_w = mem_w or mw | ||
| 1034 | lds_ops += lo | ||
| 1035 | lds_r = lds_r or lr | ||
| 1036 | lds_w = lds_w or lw | ||
| 1037 | sb_has_sbarrier[b] = has_sb | ||
| 1038 | sb_has_endpgm[b] = has_end | ||
| 1039 | sb_may_barrier[b] = may_bar | ||
| 1040 | sb_mem_stats[b] = (mem_ops, mem_r, mem_w, lds_ops, lds_r, lds_w) | ||
| 1041 | |||
| 1042 | def transfer_superblock(b, d_in): | ||
| 1043 | """Conservative under-approximate barrier clearing + exact x_memory_order dirty transfer.""" | ||
| 1044 | d = set(d_in) | ||
| 1045 | chain = chain_of[b] | ||
| 1046 | for idx_c, cur in enumerate(chain): | ||
| 1047 | insns = active_blocks[cur] | ||
| 1048 | for ins in insns: | ||
| 1049 | op = base_op(ins["op"]) | ||
| 1050 | if op == "s_endpgm": | ||
| 1051 | break | ||
| 1052 | if op in BRANCHES: | ||
| 1053 | if idx_c == len(chain) - 1 and cur not in folds: | ||
| 1054 | if op in ("s_cbranch_execz", "s_cbranch_execnz", "s_cbranch_vccz", "s_cbranch_vccnz"): | ||
| 1055 | d.clear() # branch_condition unconditionally runs g_vote -> x_round -> barrier | ||
| 1056 | break | ||
| 1057 | if op == "s_barrier": | ||
| 1058 | d.clear() | ||
| 1059 | continue | ||
| 1060 | acc = _x_memory_order_access(op) | ||
| 1061 | if acc is not None: | ||
| 1062 | kind, r, w = acc | ||
| 1063 | if (kind, "w") in d or (w and (kind, "r") in d): | ||
| 1064 | d.clear() | ||
| 1065 | if r: | ||
| 1066 | d.add((kind, "r")) | ||
| 1067 | if w: | ||
| 1068 | d.add((kind, "w")) | ||
| 1069 | if cur in folds: | ||
| 1070 | fd = folds[cur] | ||
| 1071 | if _dirty_conflicts(d, fd["mem_reads"], fd["mem_writes"]): | ||
| 1072 | d.clear() | ||
| 1073 | for k in fd["mem_reads"]: | ||
| 1074 | d.add((k, "r")) | ||
| 1075 | for k in fd["mem_writes"]: | ||
| 1076 | d.add((k, "w")) | ||
| 1077 | return frozenset(d) | ||
| 1078 | |||
| 1079 | # ---- Mode 1: Single-wave (`x_lanes == 64`) -> 100% inline structured SPIR-V, 0 OpSwitch ---- | ||
| 1080 | if x_lanes == 64: | ||
| 1081 | dirty_in = {b: set() for b in eff_blocks} | ||
| 1082 | work = collections.deque(eff_blocks) | ||
| 1083 | in_work = set(eff_blocks) | ||
| 1084 | while work: | ||
| 1085 | u = work.popleft() | ||
| 1086 | in_work.discard(u) | ||
| 1087 | d_out = transfer_superblock(u, dirty_in[u]) | ||
| 1088 | for v in eff_succ[u]: | ||
| 1089 | if not d_out <= dirty_in[v]: | ||
| 1090 | dirty_in[v].update(d_out) | ||
| 1091 | if v not in in_work: | ||
| 1092 | in_work.add(v) | ||
| 1093 | work.append(v) | ||
| 1094 | return { | ||
| 1095 | "mode": "inline_all", | ||
| 1096 | "tree": tree, | ||
| 1097 | "dirty_in": {b: frozenset(d) for b, d in dirty_in.items()}, | ||
| 1098 | "inline_blocks": set(eff_blocks), | ||
| 1099 | "sync_free_blocks": set(), | ||
| 1100 | "mini_of_block": {}, | ||
| 1101 | "mini_blocks": {}, | ||
| 1102 | "tail_blocks": set(), | ||
| 1103 | } | ||
| 1104 | |||
| 1105 | # ---- Mode 2: Multi-wave (`x_lanes > 64`) -> top-level uniform inline + sync-free + local mini-schedulers ---- | ||
| 1106 | ipdom_c = _postdominators(eff_succ_compact) | ||
| 1107 | m_eff = len(eff_blocks) | ||
| 1108 | # Require every effective block to reach exit (no infinite-loop sink SCCs bypassing post-dominators). | ||
| 1109 | entry_pdoms = set() | ||
| 1110 | if len(ipdom_c) == m_eff + 1 and 0 in ipdom_c: | ||
| 1111 | cur_c = 0 | ||
| 1112 | while cur_c != m_eff: | ||
| 1113 | entry_pdoms.add(eff_blocks[cur_c]) | ||
| 1114 | nxt_c = ipdom_c.get(cur_c) | ||
| 1115 | if nxt_c is None or nxt_c == cur_c: | ||
| 1116 | break | ||
| 1117 | cur_c = nxt_c | ||
| 1118 | |||
| 1119 | eff_preds = {b: set() for b in eff_blocks} | ||
| 1120 | for u in eff_blocks: | ||
| 1121 | for v in eff_succ[u]: | ||
| 1122 | eff_preds[v].add(u) | ||
| 1123 | |||
| 1124 | # Unwrap top-level guards whose entry strictly post-dominates entry 0 and whose non-back-edge | ||
| 1125 | # predecessors have all been emitted, exposing the full post-dominating spine at top level. | ||
| 1126 | flat_top = [] | ||
| 1127 | q = collections.deque(tree) | ||
| 1128 | seen_before = set() | ||
| 1129 | saw_endpgm = False | ||
| 1130 | while q: | ||
| 1131 | it = q.popleft() | ||
| 1132 | if not saw_endpgm and it[0] == "guard": | ||
| 1133 | entry_b = it[1] | ||
| 1134 | sub = it[2] | ||
| 1135 | if entry_b in entry_pdoms and sub: | ||
| 1136 | first_kind = sub[0][0] | ||
| 1137 | if first_kind == "block" and sub[0][1] == entry_b: | ||
| 1138 | need_preds = eff_preds[entry_b] | ||
| 1139 | elif first_kind == "loop" and sub[0][1] == entry_b: | ||
| 1140 | loop_nodes = _blocks_in_tree(sub[0]) | ||
| 1141 | need_preds = eff_preds[entry_b] - loop_nodes | ||
| 1142 | else: | ||
| 1143 | need_preds = None | ||
| 1144 | if need_preds is not None and need_preds <= seen_before: | ||
| 1145 | for child in reversed(sub): | ||
| 1146 | q.appendleft(child) | ||
| 1147 | continue | ||
| 1148 | flat_top.append(it) | ||
| 1149 | it_blocks = _blocks_in_tree(it) | ||
| 1150 | seen_before.update(it_blocks) | ||
| 1151 | if any(sb_has_endpgm[u] for u in it_blocks): | ||
| 1152 | saw_endpgm = True | ||
| 1153 | |||
| 1154 | # Multi-wave soundness guard: any `s_barrier` inside a non-top-level guard/loop must stay in global x_scheduler | ||
| 1155 | # so waves on different paths can meet at different s_barrier sites (cs_barrier_divergent). | ||
| 1156 | for it in flat_top: | ||
| 1157 | if it[0] != "block": | ||
| 1158 | if any(sb_has_sbarrier[u] for u in _blocks_in_tree(it)): | ||
| 1159 | return None | ||
| 1160 | |||
| 1161 | def check_sync_free(it): | ||
| 1162 | sub_blocks = _blocks_in_tree(it) | ||
| 1163 | has_loop = _tree_has_loop([it]) | ||
| 1164 | mem_ops = lds_ops = 0 | ||
| 1165 | mem_r = mem_w = lds_r = lds_w = False | ||
| 1166 | for u in sub_blocks: | ||
| 1167 | if sb_may_barrier[u] or sb_has_endpgm[u] or sb_has_sbarrier[u]: | ||
| 1168 | return False, frozenset(), frozenset() | ||
| 1169 | mo, mr, mw, lo, lr, lw = sb_mem_stats[u] | ||
| 1170 | mem_ops += mo | ||
| 1171 | mem_r = mem_r or mr | ||
| 1172 | mem_w = mem_w or mw | ||
| 1173 | lds_ops += lo | ||
| 1174 | lds_r = lds_r or lr | ||
| 1175 | lds_w = lds_w or lw | ||
| 1176 | if has_loop: | ||
| 1177 | if mem_w or lds_w: | ||
| 1178 | return False, frozenset(), frozenset() | ||
| 1179 | else: | ||
| 1180 | if (mem_w and mem_ops > 1) or (lds_w and lds_ops > 1): | ||
| 1181 | return False, frozenset(), frozenset() | ||
| 1182 | reads = frozenset(k for k, f in (("mem", mem_r), ("lds", lds_r)) if f) | ||
| 1183 | writes = frozenset(k for k, f in (("mem", mem_w), ("lds", lds_w)) if f) | ||
| 1184 | return True, reads, writes | ||
| 1185 | |||
| 1186 | steps = [] | ||
| 1187 | dirty_in = {} | ||
| 1188 | inline_blocks = set() | ||
| 1189 | sync_free_blocks = set() | ||
| 1190 | mini_of_block = {} | ||
| 1191 | mini_blocks = {} | ||
| 1192 | tail_blocks = set() | ||
| 1193 | cur_dirty = frozenset() | ||
| 1194 | mini_idx = 0 | ||
| 1195 | |||
| 1196 | for idx_it, it in enumerate(flat_top): | ||
| 1197 | it_blocks = _blocks_in_tree(it) | ||
| 1198 | has_end = any(sb_has_endpgm[u] for u in it_blocks) | ||
| 1199 | if it[0] == "block" and (not has_end or idx_it == len(flat_top) - 1): | ||
| 1200 | b = it[1] | ||
| 1201 | dirty_in[b] = cur_dirty | ||
| 1202 | inline_blocks.add(b) | ||
| 1203 | cur_dirty = transfer_superblock(b, cur_dirty) | ||
| 1204 | steps.append(("inline_block", b)) | ||
| 1205 | continue | ||
| 1206 | if has_end: | ||
| 1207 | # Early s_endpgm inside a wave-divergent guard/loop (or non-final block): hand remaining tail to x_scheduler. | ||
| 1208 | rem = set() | ||
| 1209 | for rem_it in flat_top[idx_it:]: | ||
| 1210 | rem.update(_blocks_in_tree(rem_it)) | ||
| 1211 | tail_blocks = rem | ||
| 1212 | steps.append(("tail_scheduler", rem, bool(cur_dirty))) | ||
| 1213 | cur_dirty = frozenset() | ||
| 1214 | break | ||
| 1215 | ok_sf, sf_reads, sf_writes = check_sync_free(it) | ||
| 1216 | if ok_sf: | ||
| 1217 | pre_bar = _dirty_conflicts(cur_dirty, sf_reads, sf_writes) | ||
| 1218 | if pre_bar: | ||
| 1219 | cur_dirty = frozenset() | ||
| 1220 | for u in it_blocks: | ||
| 1221 | dirty_in[u] = frozenset() # pre_bar cleared conflicts before entering sync-free region | ||
| 1222 | inline_blocks.add(u) | ||
| 1223 | sync_free_blocks.add(u) | ||
| 1224 | cur_dirty = frozenset(set(cur_dirty) | ||
| 1225 | | {(k, "r") for k in sf_reads} | ||
| 1226 | | {(k, "w") for k in sf_writes}) | ||
| 1227 | steps.append(("inline_sync_free", it, pre_bar)) | ||
| 1228 | else: | ||
| 1229 | pre_bar = bool(cur_dirty) | ||
| 1230 | cur_dirty = frozenset() # mini-scheduler ends with OpControlBarrier %c2 %c2 %c948 | ||
| 1231 | mini_blocks[mini_idx] = it_blocks | ||
| 1232 | for u in it_blocks: | ||
| 1233 | mini_of_block[u] = mini_idx | ||
| 1234 | steps.append(("mini_scheduler", mini_idx, it_blocks, pre_bar)) | ||
| 1235 | mini_idx += 1 | ||
| 1236 | |||
| 1237 | # Only engage structured_hybrid when it actually eliminates global-switch blocks or splits into smaller regions. | ||
| 1238 | if len(steps) == 1 and steps[0][0] in ("tail_scheduler", "mini_scheduler"): | ||
| 1239 | return None | ||
| 1240 | return { | ||
| 1241 | "mode": "structured_hybrid", | ||
| 1242 | "steps": steps, | ||
| 1243 | "dirty_in": dirty_in, | ||
| 1244 | "inline_blocks": inline_blocks, | ||
| 1245 | "sync_free_blocks": sync_free_blocks, | ||
| 1246 | "mini_of_block": mini_of_block, | ||
| 1247 | "mini_blocks": mini_blocks, | ||
| 1248 | "tail_blocks": tail_blocks, | ||
| 1249 | } | ||