From ef74563f862eaabeee1e25332dfc9984d5aec78f Mon Sep 17 00:00:00 2001 From: Robin Snyders Date: Wed, 25 Nov 2026 11:02:57 +0100 Subject: [PATCH] Shaders: the DXIL backend simplifies the entry function after value numbering A Simplifier pass after ValueNumbering and DeadCode: block chains reached only by an unconditional branch merge, branches on a constant or to one block twice become unconditional, phis of one value are that value and ConstantFolding folds what that decides. Wave and quad reads are nounwind, so nothing removed them: unread ones go, and one equal to an earlier one in its block with no effect between is shared. Reuses ConstantFolding, DominatorTree and ValueNumbering.Key from main. RaytracingResolve 1.57 -> 1.06 MB of DXIL, AMD pipeline 36.5 s / 8.4 GB -> 26.2 s / 3.6 GB; ActivateProbes 9.98 -> 8.50 MB. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SKtJsfjasPuTLtS3mEXFru --- docs/dxil-backend.md | 16 +- src/FiveStar.Shaders/Dxil/Ir/Instruction.cs | 2 +- src/FiveStar.Shaders/Dxil/Ir/Simplifier.cs | 347 ++++++++++++++++++ .../Dxil/Ir/ValueNumbering.cs | 2 +- .../Dxil/Lowering/ShaderLowering.cs | 5 + .../DxilSimplifierTests.cs | 139 +++++++ 6 files changed, 508 insertions(+), 3 deletions(-) create mode 100644 src/FiveStar.Shaders/Dxil/Ir/Simplifier.cs create mode 100644 tests/FiveStar.Shaders.Tests/DxilSimplifierTests.cs diff --git a/docs/dxil-backend.md b/docs/dxil-backend.md index 12876331..cd04d6c3 100644 --- a/docs/dxil-backend.md +++ b/docs/dxil-backend.md @@ -36,7 +36,8 @@ flowchart LR parse --> lower["Lowering
types, inlining, SSA, entry signatures, constant folding"] lower --> gvn["ValueNumbering"] gvn --> dce["DeadCode"] - dce --> write["ModuleWriter
LLVM 3.7 bitcode"] + dce --> simplify["Simplifier"] + simplify --> write["ModuleWriter
LLVM 3.7 bitcode"] write --> container["ShaderContainer
SFI0 ISG1 OSG1 PSG1 PSV0 DXIL + digest"] ``` @@ -70,6 +71,19 @@ unoptimized form for comparison. VIctory reports about 43% fewer host instructio | `MS_VS_TransformD`, w32 form | 2.65 MB | 2.04 MB (-23%) | | | the same, native | 2.02 MB | 1.63 MB (-19%) | | +`Simplifier` follows (skipped by `--no-optimize` too), twice, each round cleaned by `DeadCode`. A block that only its +predecessor's unconditional branch reaches joins it (every inlined call and structured region ends in one); a branch on +a constant or to one block twice becomes unconditional, a phi of one value that value, and `ConstantFolding` folds +what that decides. Wave and quad reads (ballot, any, read-lane, active ops) are declared nounwind as dxc declares them, +so no pass removed them: one nothing reads goes, and one with the operands of an earlier one in its block, with no +effect between them (a discard or barrier may change the lanes), is that one. The translator's EXEC emulation makes +a ballot pair for every mask write and an any for every SCC, most never read. + +| Program (translated today) | after `ValueNumbering` | after `Simplifier` | AMD RX 7800 XT pipeline | +|---|---|---|---| +| `CS_RaytracingResolve` (wave32) | 1.57 MB | 1.06 MB (-32%) | 36.5 s, 8.4 GB -> 26.2 s, 3.6 GB | +| `CS_ScreenProbes_ActivateProbes` (wave64) | 9.98 MB | 8.50 MB (-15%) | over 50 GB either way | + All five pass dxil.dll validation. What is left is mostly the wave emulation's control flow: in the cascade program 73,515 phis (about 6 operands each) and 124,610 blocks, which neither pass touches. diff --git a/src/FiveStar.Shaders/Dxil/Ir/Instruction.cs b/src/FiveStar.Shaders/Dxil/Ir/Instruction.cs index bdd734bc..cec8f8ca 100644 --- a/src/FiveStar.Shaders/Dxil/Ir/Instruction.cs +++ b/src/FiveStar.Shaders/Dxil/Ir/Instruction.cs @@ -37,7 +37,7 @@ internal Instruction(Opcode opcode, IrType type, BasicBlock block, int operands) /// A removed phi's value (set by SSA construction). internal Value? Replacement { get; set; } - public BasicBlock Block { get; } + public BasicBlock Block { get; internal set; } public List Operands { get; } diff --git a/src/FiveStar.Shaders/Dxil/Ir/Simplifier.cs b/src/FiveStar.Shaders/Dxil/Ir/Simplifier.cs new file mode 100644 index 00000000..47222942 --- /dev/null +++ b/src/FiveStar.Shaders/Dxil/Ir/Simplifier.cs @@ -0,0 +1,347 @@ +// Copyright (c) 2026 Five Star Recomp contributors. +// SPDX-License-Identifier: GPL-3.0-or-later + +using System.Collections.Frozen; +using FiveStar.Shaders.Dxil.Ops; + +namespace FiveStar.Shaders.Dxil.Ir; + +/// +/// The clean-ups after that change the blocks or touch wave operations. A block that +/// only its predecessor's unconditional branch reaches joins that predecessor (every inlined call and structured +/// region ends in such a branch); a branch on a constant or to one block twice becomes an unconditional branch, a phi +/// of one value that value, and what their operands then decide is folded again (). +/// Wave and quad operations that only read are declared nounwind, as dxc declares them, so nothing removed them: one +/// nothing reads goes, and one with the operands of an earlier one in its block, with no effect between them, is that +/// one (a discard or a barrier between them may change the lanes). Two rounds, as a folded branch frees blocks to merge. +/// +public static class Simplifier +{ + private const int Rounds = 2; + + /// Wave and quad operations whose value depends only on their operands and the lanes that run them. + private static readonly FrozenSet WaveReadOperations = new[] + { + DxOpCode.WaveIsFirstLane, DxOpCode.WaveAnyTrue, DxOpCode.WaveAllTrue, DxOpCode.WaveActiveAllEqual, + DxOpCode.WaveActiveBallot, DxOpCode.WaveReadLaneAt, DxOpCode.WaveReadLaneFirst, DxOpCode.WaveActiveOp, + DxOpCode.WaveActiveBit, DxOpCode.WavePrefixOp, DxOpCode.WaveAllBitCount, DxOpCode.WavePrefixBitCount, + DxOpCode.QuadReadLaneAt, DxOpCode.QuadOp, + }.Select(code => (int)code).ToFrozenSet(); + + /// Simplifies , numbered and cleaned; cleans it again after each round. + public static void Run(IrFunction function, DxilModule module) + { + for (var round = 0; round < Rounds && function.Blocks.Count > 0; round++) + { + var replaced = new Dictionary(); + MergeChains(function, replaced); + var tree = DominatorTree.Of(function); + var pending = new Stack(); + pending.Push(function.Blocks[0]); + + // Dominator-tree preorder: an instruction's operands other than phis are folded before it. + while (pending.Count > 0) + { + var block = pending.Pop(); + Simplify(block, module, replaced); + + foreach (var child in tree.Children(block)) + { + pending.Push(child); + } + } + + foreach (var block in function.Blocks) + { + block.Phis.ForEach(phi => Resolve(phi, replaced)); + block.Body.ForEach(instruction => Resolve(instruction, replaced)); + Resolve(block.Terminator!, replaced); + } + + RemoveUnreadWaveReads(function); + DeadCode.Remove(function); + } + } + + /// Appends each block reached only by its predecessor's unconditional branch to that predecessor. + private static void MergeChains(IrFunction function, Dictionary replaced) + { + var entry = function.Blocks[0]; + var edges = new Dictionary(); + + foreach (var successor in function.Blocks.SelectMany(block => block.Successors)) + { + edges[successor] = edges.GetValueOrDefault(successor) + 1; + } + + var merged = new HashSet(); + + foreach (var block in function.Blocks) + { + if (merged.Contains(block)) + { + continue; + } + + while (block.Terminator!.Opcode == Opcode.Branch) + { + var next = block.Terminator.Targets[0]; + + if (ReferenceEquals(next, block) || ReferenceEquals(next, entry) || edges[next] != 1) + { + break; + } + + Absorb(block, next, replaced); + merged.Add(next); + } + } + + function.Blocks.RemoveAll(merged.Contains); + } + + private static void Absorb(BasicBlock block, BasicBlock next, Dictionary replaced) + { + // One incoming edge: every phi has the one value from this block. + foreach (var phi in next.Phis) + { + replaced[phi] = phi.Operands[0]; + } + + foreach (var instruction in next.Body) + { + instruction.Block = block; + block.Body.Add(instruction); + } + + var terminator = next.Terminator!; + terminator.Block = block; + block.Terminator = terminator; + + foreach (var phi in terminator.Targets.Distinct().SelectMany(successor => successor.Phis)) + { + for (var index = 0; index < phi.Targets.Count; index++) + { + if (ReferenceEquals(phi.Targets[index], next)) + { + phi.Targets[index] = block; + } + } + } + } + + /// Phis of one value, folds, wave reads the block already made, then the block's branch. + private static void Simplify(BasicBlock block, DxilModule module, Dictionary replaced) + { + foreach (var phi in block.Phis) + { + Resolve(phi, replaced); + var single = SingleValue(phi); + + if (single is not null) + { + replaced[phi] = single; + } + } + + var waveReads = new Dictionary(); + + block.Body.RemoveAll(instruction => Replace(instruction, module, replaced, waveReads)); + Resolve(block.Terminator!, replaced); + FoldBranch(block, module); + } + + /// True when the instruction is replaced by a constant, an operand or an earlier wave read. + private static bool Replace(Instruction instruction, DxilModule module, Dictionary replaced, Dictionary waveReads) + { + Resolve(instruction, replaced); + var folded = Fold(instruction, module); + + if (folded is not null) + { + replaced[instruction] = folded; + + return true; + } + + if (!IsWaveRead(instruction)) + { + if (instruction.HasEffect) + { + waveReads.Clear(); + } + + return false; + } + + var key = new ValueNumbering.Key(instruction); + + if (waveReads.TryGetValue(key, out var earlier)) + { + replaced[instruction] = earlier; + + return true; + } + + waveReads[key] = instruction; + + return false; + } + + /// The value gives the instruction now that its operands are resolved, or null. + private static Value? Fold(Instruction instruction, DxilModule module) + { + var operands = instruction.Operands; + + switch (instruction.Opcode) + { + case Opcode.Binary: + return ConstantFolding.Binary(module, (BinaryOp)instruction.Code, operands[0], operands[1]); + case Opcode.Compare: + return ConstantFolding.Compare(module, (Predicate)instruction.Code, operands[0], operands[1]); + case Opcode.Cast: + return ConstantFolding.Cast(module, (CastOp)instruction.Code, operands[0], instruction.Type); + case Opcode.Select: + return ConstantFolding.Select(operands[0], operands[1], operands[^1]); + default: + return null; + } + } + + private static bool IsWaveRead(Instruction instruction) + { + var operands = instruction.Operands; + + if (instruction.Opcode != Opcode.Call || operands.Count == 0 || operands[0] is not Constant code || !code.IsInteger) + { + return false; + } + + return WaveReadOperations.Contains((int)code.Bits); + } + + /// Removes the wave reads nothing with an effect depends on; then removes their operands. + private static void RemoveUnreadWaveReads(IrFunction function) + { + var work = new Stack(); + + foreach (var block in function.Blocks) + { + foreach (var instruction in block.Body.Where(instruction => instruction.HasEffect && !IsWaveRead(instruction))) + { + MarkLive(instruction, work); + } + + MarkLive(block.Terminator!, work); + } + + while (work.Count > 0) + { + foreach (var operand in work.Pop().Operands) + { + if (operand is Instruction instruction) + { + MarkLive(instruction, work); + } + } + } + + foreach (var block in function.Blocks) + { + block.Body.RemoveAll(instruction => IsWaveRead(instruction) && !instruction.Live); + block.Phis.ForEach(phi => phi.Live = false); + block.Body.ForEach(instruction => instruction.Live = false); + block.Terminator!.Live = false; + } + } + + private static void MarkLive(Instruction instruction, Stack work) + { + if (!instruction.Live) + { + instruction.Live = true; + work.Push(instruction); + } + } + + /// The one value every incoming edge of brings (the phi itself aside), or null. + private static Value? SingleValue(Instruction phi) + { + Value? single = null; + + foreach (var operand in phi.Operands) + { + if (ReferenceEquals(operand, phi) || ReferenceEquals(operand, single)) + { + continue; + } + + if (single is not null) + { + return null; + } + + single = operand; + } + + return single; + } + + /// A conditional branch on a constant, or to one block twice, becomes a branch; the dropped edge leaves the phis. + private static void FoldBranch(BasicBlock block, DxilModule module) + { + var terminator = block.Terminator!; + + if (terminator.Opcode != Opcode.ConditionalBranch) + { + return; + } + + var whenTrue = terminator.Targets[0]; + var whenFalse = terminator.Targets[1]; + var constant = terminator.Operands[0] as Constant; + var known = constant is not null && constant.IsInteger; + + if (!known && !ReferenceEquals(whenTrue, whenFalse)) + { + return; + } + + var kept = whenTrue; + var dropped = whenFalse; + + if (known && constant!.Bits == 0) + { + kept = whenFalse; + dropped = whenTrue; + } + + foreach (var phi in dropped.Phis) + { + var index = phi.Targets.IndexOf(block); + phi.Operands.RemoveAt(index); + phi.Targets.RemoveAt(index); + } + + var branch = new Instruction(Opcode.Branch, module.Types.Void, block); + branch.Targets.Add(kept); + block.Terminator = branch; + } + + private static void Resolve(Instruction instruction, Dictionary replaced) + { + var operands = instruction.Operands; + + for (var index = 0; index < operands.Count; index++) + { + var value = operands[index]; + + while (replaced.TryGetValue(value, out var next)) + { + value = next; + } + + operands[index] = value; + } + } +} diff --git a/src/FiveStar.Shaders/Dxil/Ir/ValueNumbering.cs b/src/FiveStar.Shaders/Dxil/Ir/ValueNumbering.cs index 0d599ca8..35e41ae3 100644 --- a/src/FiveStar.Shaders/Dxil/Ir/ValueNumbering.cs +++ b/src/FiveStar.Shaders/Dxil/Ir/ValueNumbering.cs @@ -288,7 +288,7 @@ private enum Kind } /// What an instruction computes: its operator, codes, types and operands (by reference; constants are interned). - private sealed class Key : IEquatable + internal sealed class Key : IEquatable { private readonly Instruction _instruction; private readonly int _hash; diff --git a/src/FiveStar.Shaders/Dxil/Lowering/ShaderLowering.cs b/src/FiveStar.Shaders/Dxil/Lowering/ShaderLowering.cs index 2387f7b2..ea713847 100644 --- a/src/FiveStar.Shaders/Dxil/Lowering/ShaderLowering.cs +++ b/src/FiveStar.Shaders/Dxil/Lowering/ShaderLowering.cs @@ -62,6 +62,11 @@ public static (DxilModule Module, IrFunction Main, ShaderDescription Description DeadCode.Remove(main); + if (DxilBackend.Optimize) + { + Simplifier.Run(main, module); + } + context.Graphics?.RecordUsage(main); context.Mesh?.RecordUsage(main); context.Geometry?.RecordUsage(main); diff --git a/tests/FiveStar.Shaders.Tests/DxilSimplifierTests.cs b/tests/FiveStar.Shaders.Tests/DxilSimplifierTests.cs new file mode 100644 index 00000000..bd6ceba9 --- /dev/null +++ b/tests/FiveStar.Shaders.Tests/DxilSimplifierTests.cs @@ -0,0 +1,139 @@ +// Copyright (c) 2026 Five Star Recomp contributors. +// SPDX-License-Identifier: GPL-3.0-or-later + +using FiveStar.Shaders.Dxil; +using FiveStar.Shaders.Dxil.Ir; +using FiveStar.Shaders.Dxil.Ops; +using FiveStar.Shaders.Tests.Toolchain; +using FiveStar.Shaders.Tests.Warp; +using Xunit; + +namespace FiveStar.Shaders.Tests; + +/// +/// The backend's : a program shaped like the translator's (helpers called with constants, wave +/// reads in divergent regions, repeated and unread wave reads) computes the same words on WARP optimized and plain, +/// in a smaller module; and on a hand-built function it merges a block chain, folds a constant branch, makes a wave +/// read once and drops an unread one. +/// +public sealed class DxilSimplifierTests : IClassFixture +{ + private const int OutputSlot = 1; + private const int InputSlot = 2; + private const int Threads = 64; + private const int Casts = 2; + + private const string Program = """ + uint field(uint x, uint shift, uint width) { return (x >> (shift & 31u)) & ((1u << width) - 1u); } + uint fetch(uint index) { ByteAddressBuffer b = ResourceDescriptorHeap[2]; return b.Load(index * 4u); } + [numthreads(64, 1, 1)] + void main(uint3 id : SV_DispatchThreadID) { + RWByteAddressBuffer output = ResourceDescriptorHeap[1]; + uint lane = WaveGetLaneIndex(); + bool odd = (id.x & 1u) != 0; + uint outer = WaveActiveBallot(odd).x; + uint again = WaveActiveBallot(odd).x; + bool unread = WaveActiveAnyTrue(odd); + uint v = field(id.x * 0x01010101u, 8u, 8u) + 0u; + if (odd) { + uint inner = WaveActiveBallot(odd).x; + v += fetch(id.x) + inner + WaveReadLaneFirst(lane); + } else { + v ^= fetch(id.x + 1u) * 1u; + } + if ((id.x & 3u) == 0u) { + v += WaveActiveCountBits(odd) + WaveActiveBallot(odd).x; + } + output.Store(id.x * 4u, v + outer + again + WaveGetLaneIndex()); + } + """; + + private readonly WarpFixture _fixture; + + public DxilSimplifierTests(WarpFixture fixture) + { + _fixture = fixture; + } + + [WarpFact] + public void A_simplified_program_computes_the_same_words_in_a_smaller_module() + { + var (plain, plainBytes) = Run(optimize: false); + var (simplified, simplifiedBytes) = Run(optimize: true); + + Assert.Equal(plain, simplified); + Assert.NotEqual(new uint[Threads], plain); + Assert.True(simplifiedBytes < plainBytes, $"{simplifiedBytes} bytes simplified, {plainBytes} plain"); + } + + [Fact] + public void A_chain_merges_a_constant_branch_folds_and_wave_reads_are_shared_or_dropped() + { + var module = new DxilModule(); + var types = module.Types; + var main = module.Function("main", types.Function(types.Void, []), AttributeSet.None, hasBody: true); + + var entry = module.NewBlock(); + var next = module.NewBlock(); + var taken = module.NewBlock(); + var skipped = module.NewBlock(); + main.Blocks.AddRange([entry, next, taken, skipped]); + + var builder = new IrBuilder(module, entry); + var ops = new DxOps(builder); + var thread = ops.ThreadIdComponent(DxOpCode.ThreadId, "threadId", 0); + var odd = builder.Compare(Predicate.NotEqual, builder.Binary(BinaryOp.And, thread, module.Int32(1)), module.Int32(0)); + builder.Branch(next); + + builder.Block = next; + var first = AnyTrue(ops, odd); + var second = AnyTrue(ops, odd); + AnyTrue(ops, builder.Compare(Predicate.Equal, thread, module.Int32(0))); + builder.ConditionalBranch(module.Bool(true), taken, skipped); + + builder.Block = taken; + var handle = ops.HeapHandle(module.Int32(OutputSlot), sampler: false, DxOps.RawBufferKind | DxOps.UavBit, 0); + ops.RawStore(handle, thread, [builder.Cast(CastOp.ZExt, first, types.Int32), builder.Cast(CastOp.ZExt, second, types.Int32)]); + builder.Return(); + + builder.Block = skipped; + builder.Return(); + + DeadCode.Remove(main); + Simplifier.Run(main, module); + + var block = Assert.Single(main.Blocks); + Assert.Single(block.Body, instruction => instruction.Callee?.Name == "dx.op.waveAnyTrue"); + + var casts = block.Body.Where(instruction => instruction.Opcode == Opcode.Cast).ToList(); + Assert.Equal(Casts, casts.Count); + Assert.Same(casts[0].Operands[0], casts[1].Operands[0]); + } + + private static Value AnyTrue(DxOps ops, Value condition) + { + return ops.Call(DxOpCode.WaveAnyTrue, "waveAnyTrue", AttributeSet.NoUnwind, condition.Type, condition); + } + + private (uint[] Words, int Bytes) Run(bool optimize) + { + byte[] container; + var previous = DxilBackend.Optimize; + DxilBackend.Optimize = optimize; + + try + { + container = DxilBackend.Compile(Program, "cs"); + } + finally + { + DxilBackend.Optimize = previous; + } + + var input = new BufferResource(InputSlot, Enumerable.Range(0, Threads + 1).Select(index => (uint)((index * 7919) ^ 0x5a5a)).ToArray(), Writable: false); + var output = new BufferResource(OutputSlot, new uint[Threads], Writable: true); + var result = _fixture.Runner.Compute(new ComputeJob(container, 1, 1, 1, new Bindings { Buffers = [output, input] })); + + return (result.Buffers[OutputSlot], container.Length); + } +}