diff --git a/crates/xcl/build.rs b/crates/xcl/build.rs index 64a6b08bd3..09c6a27da0 100644 --- a/crates/xcl/build.rs +++ b/crates/xcl/build.rs @@ -14,6 +14,7 @@ const TRANSLATOR_SOURCES: &[&str] = &[ "src/gpu/recomp/emit.rs", "src/gpu/recomp/mesh_wave.rs", "src/gpu/recomp/mod.rs", + "src/gpu/recomp/regions.rs", "src/gpu/recomp/upper_lanes.rs", "src/gpu/recomp/x64_masks.rs", "src/gpu/shader.rs", diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 96966005b6..620ca5fe3c 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -18,6 +18,7 @@ pub(super) enum Flow { pub(super) struct Em { opt: Options, + pub regions: Option, out: String, pub indent: usize, sgprs: BTreeSet, @@ -466,6 +467,7 @@ impl Em { pub fn new(opt: Options) -> Self { Em { opt, + regions: None, out: String::new(), indent: 1, sgprs: BTreeSet::new(), @@ -1700,6 +1702,8 @@ impl Em { let index = if idxen { self.vreg(vaddr) } else { "0u".into() }; let voff = if offen { self.vreg(vaddr + idxen as u64) } else { "0u".into() }; let t = self.t(); + self.line(&format!("uint {t}_index = {index} + select(({d3} & 0x800000u) != 0u, lane_id & 63u, 0u);")); + let index = format!("{t}_index"); let is_store = small.map_or(matches!(kind, BufKind::Store | BufKind::FormatStore), |(_, _, s)| s); self.line(&format!("uint {t}_stride = ({d1} >> 16) & 0x3FFFu;")); if self.opt.mem_windows > 1 { @@ -1718,25 +1722,19 @@ impl Em { self.line(&format!("uint {t}_a = {d0} + {soff} + {t}_off + {t}_stride * {index};")); } let act = self.act(); - let multi = self.opt.mem_windows > 1; - let in_range = |bytes: String| { - if multi { - format!("select({t}_stride == 0u, {t}_off + (uint64_t)({bytes}) <= (uint64_t){d2}, {index} < {d2})") - } else { - format!("select({t}_stride == 0u, {t}_off + {bytes} <= {d2}, {index} < {d2})") - } - }; + let in_range = |bytes: String| format!("xcl_buf_in_range({d1}, {d2}, {d3}, {index}, (uint64_t){t}_off, {bytes}, {soff})"); if let Some((n, signed, store)) = small { let ok = in_range(format!("{n}u")); let v = self.vreg(vdata); if store { self.line(&format!("if (and({act}, {ok})) st_bytes({t}_a, uint4({v}, 0u, 0u, 0u), {n}u);")); } else { + self.line(&format!("uint {t}_safe_a = select(and({act}, {ok}), {t}_a, 0u);")); let bits = 8 * n; let val = if signed { - format!("(uint)(((int)(ld_raw({t}_a).x << {}u)) >> {}u)", 32 - bits, 32 - bits) + format!("(uint)(((int)(ld_raw({t}_safe_a).x << {}u)) >> {}u)", 32 - bits, 32 - bits) } else { - format!("(ld_raw({t}_a).x & {}u)", (1u64 << bits) - 1) + format!("(ld_raw({t}_safe_a).x & {}u)", (1u64 << bits) - 1) }; self.line(&format!("if ({act}) {v} = {ok} ? {val} : 0u;")); } @@ -1780,9 +1778,20 @@ impl Em { self.line(&format!("uint {t}_info = FMT_INFO[min({fmt}, 77u)];")); self.line(&format!("bool {t}_int = ((({t}_info >> 3) & 7u) == 4u) || ((({t}_info >> 3) & 7u) == 5u);")); self.line(&format!("bool {t}_ok = and(({t}_info & 7u) != 0u, {});", in_range(format!("fmt_bytes({t}_info)")))); - self.line(&format!("uint4 {t}_r = ld_raw({t}_a);")); + if d16_format.map_or(count, |(_, components, _)| components) == 1 { + let v = self.vreg(vdata); + let value = if let Some((_, _, high)) = d16_format { + let half = format!("select({t}_int, {t}_v & 0xFFFFu, f32tof16(asfloat({t}_v)))"); + if high { format!("({v} & 0xFFFFu) | ({half} << 16)") } else { half } + } else { + format!("{t}_v") + }; + self.line(&format!("if ({act}) {{ uint {t}_v = fmt_load_selected({t}_a, {t}_info, {d3} & 7u, {t}_ok); {v} = {value}; }}")); + return Ok(()); + } + self.line(&format!("uint4 {t}_r = ld_raw(select(and({act}, {t}_ok), {t}_a, 0u));")); self.line(&format!( - "uint4 {t}_c = uint4(fmt_comp({t}_r, {t}_info, 0u), fmt_comp({t}_r, {t}_info, 1u), fmt_comp({t}_r, {t}_info, 2u), fmt_comp({t}_r, {t}_info, 3u));" + "uint4 {t}_c = select({t}_ok, uint4(fmt_comp({t}_r, {t}_info, 0u), fmt_comp({t}_r, {t}_info, 1u), fmt_comp({t}_r, {t}_info, 2u), fmt_comp({t}_r, {t}_info, 3u)), uint4(0u, 0u, 0u, 0u));" )); if let Some((_, components, high)) = d16_format { let half = |component: u64| { @@ -1792,13 +1801,13 @@ impl Em { let mut assigns = Vec::new(); if high { let v = self.vreg(vdata); - assigns.push(format!("{v} = ({v} & 0xFFFFu) | ({t}_ok ? ({} << 16) : 0u);", half(0))); + assigns.push(format!("{v} = ({v} & 0xFFFFu) | ({} << 16);", half(0))); } else { for i in 0..count { let lo = half(2 * i); let hi = if 2 * i + 1 < components { half(2 * i + 1) } else { "0u".into() }; let v = self.vreg(vdata + i); - assigns.push(format!("{v} = {t}_ok ? ({lo} | ({hi} << 16)) : 0u;")); + assigns.push(format!("{v} = {lo} | ({hi} << 16);")); } } self.line(&format!("if ({act}) {{ {} }}", assigns.join(" "))); @@ -1807,7 +1816,7 @@ impl Em { let mut assigns = Vec::new(); for i in 0..count { let v = self.vreg(vdata + i); - assigns.push(format!("{v} = select({t}_ok, dst_sel({t}_c, ({d3} >> {}u) & 7u, {t}_int), 0u);", 3 * i)); + assigns.push(format!("{v} = dst_sel({t}_c, ({d3} >> {}u) & 7u, {t}_int);", 3 * i)); } self.line(&format!("if ({act}) {{ {} }}", assigns.join(" "))); } @@ -3684,10 +3693,12 @@ impl Em { let (vdata, vaddr, srsrc) = (f("VDATA"), f("VADDR"), Self::field(d, "SRSRC")); let soff = self.code32(f("SOFFSET"), None, false).ok_or("op")?; let (offen, idxen) = (f("OFFEN") != 0, f("IDXEN") != 0); - let (d0, d1, d2) = (self.sreg(srsrc), self.sreg(srsrc + 1), self.sreg(srsrc + 2)); + let (d0, d1, d2, d3) = (self.sreg(srsrc), self.sreg(srsrc + 1), self.sreg(srsrc + 2), self.sreg(srsrc + 3)); let index = if idxen { self.vreg(vaddr) } else { "0u".into() }; let voff = if offen { self.vreg(vaddr + idxen as u64) } else { "0u".into() }; let t = self.t(); + self.line(&format!("uint {t}_index = {index} + select(({d3} & 0x800000u) != 0u, lane_id & 63u, 0u);")); + let index = format!("{t}_index"); let x2 = op.ends_with("_x2"); let op = op.trim_end_matches("_x2"); let bytes = if x2 { 8 } else { 4 }; @@ -3699,11 +3710,11 @@ impl Em { )); self.window_write(&format!("(uint)({t}_ea >> 32)")); self.line(&format!("uint {t}_a = (uint){t}_ea & ~{}u;", bytes - 1)); - self.line(&format!("bool {t}_ok = select({t}_stride == 0u, {t}_off + (uint64_t){bytes}u <= (uint64_t){d2}, {index} < {d2});")); + self.line(&format!("bool {t}_ok = xcl_buf_in_range({d1}, {d2}, {d3}, {index}, {t}_off, {bytes}u, {soff});")); } else { self.line(&format!("uint {t}_off = {voff} + {}u;", f("OFFSET"))); self.line(&format!("uint {t}_a = ({d0} + {soff} + {t}_off + {t}_stride * {index}) & ~{}u;", bytes - 1)); - self.line(&format!("bool {t}_ok = select({t}_stride == 0u, {t}_off + {bytes}u <= {d2}, {index} < {d2});")); + self.line(&format!("bool {t}_ok = xcl_buf_in_range({d1}, {d2}, {d3}, {index}, (uint64_t){t}_off, {bytes}u, {soff});")); } let act = self.act(); if x2 { @@ -3742,10 +3753,12 @@ impl Em { let (vdata, vaddr, srsrc) = (f("VDATA"), f("VADDR"), Self::field(d, "SRSRC")); let soff = self.code32(f("SOFFSET"), None, false).ok_or("op")?; let (offen, idxen) = (f("OFFEN") != 0, f("IDXEN") != 0); - let (d0, d1, d2) = (self.sreg(srsrc), self.sreg(srsrc + 1), self.sreg(srsrc + 2)); + let (d0, d1, d2, d3) = (self.sreg(srsrc), self.sreg(srsrc + 1), self.sreg(srsrc + 2), self.sreg(srsrc + 3)); let index = if idxen { self.vreg(vaddr) } else { "0u".into() }; let voff = if offen { self.vreg(vaddr + idxen as u64) } else { "0u".into() }; let t = self.t(); + self.line(&format!("uint {t}_index = {index} + select(({d3} & 0x800000u) != 0u, lane_id & 63u, 0u);")); + let index = format!("{t}_index"); self.line(&format!("uint {t}_stride = ({d1} >> 16) & 0x3FFFu;")); if self.opt.mem_windows > 1 { self.line(&format!("uint64_t {t}_off = (uint64_t){voff} + (uint64_t){}u;", f("OFFSET"))); @@ -3762,17 +3775,13 @@ impl Em { self.line(&format!("uint {t}_off = {voff} + {}u;", f("OFFSET"))); self.line(&format!("uint {t}_a = {d0} + {soff} + {t}_off + {t}_stride * {index};")); } - let ok = if self.opt.mem_windows > 1 { - format!("select({t}_stride == 0u, {t}_off + (uint64_t){n}u <= (uint64_t){d2}, {index} < {d2})") - } else { - format!("select({t}_stride == 0u, {t}_off + {n}u <= {d2}, {index} < {d2})") - }; + let ok = format!("xcl_buf_in_range({d1}, {d2}, {d3}, {index}, (uint64_t){t}_off, {n}u, {soff})"); let act = self.act(); let v = self.vreg(vdata); if store { self.line(&format!("if (and({act}, {ok})) st_bytes({t}_a, uint4({}, 0u, 0u, 0u), {n}u);", d16_data(&v, half))); } else { - let raw = format!("select({ok}, ld_raw({t}_a).x, 0u)"); + let raw = format!("select({ok}, ld_raw(select(and({act}, {ok}), {t}_a, 0u)).x, 0u)"); self.line(&format!("if ({act}) {v} = {};", d16_merge(&v, &raw, n, signed, half))); } Ok(()) @@ -4185,7 +4194,7 @@ impl Em { } /// Storage and functions of the split wave64 form (`PRELUDE_X64`). - fn x64_prelude(&self, h: &mut String) { + fn x64_prelude(&self, h: &mut String, outline: bool) { let threads = self.x64_threads(); let waves = threads.div_ceil(64).max(1) as usize; let slot = self.x64_words; @@ -4206,7 +4215,7 @@ impl Em { let _ = writeln!(h, "groupshared uint xcl_xs[{slots}];\ngroupshared uint xcl_xc[{counters}];\ngroupshared uint xcl_xw;"); h.push_str("#define XCL_XS(i) xcl_xs[(i)]\n#define XCL_XC(i) xcl_xc[(i)]\n#define XCL_XW xcl_xw\n"); } - h.push_str(PRELUDE_X64); + h.push_str(&PRELUDE_X64.replace("XCL_EXCHANGE_FN ", if outline { "[noinline] " } else { "" })); } /// Storage and functions for early-exit-safe, bounded `s_barrier` (`PRELUDE_SAFE_BARRIER`). @@ -4231,7 +4240,10 @@ impl Em { h.push_str(" xcl_xn = XCL_X_THREADS > ((xcl_tid & ~31u) ^ 32u) ? min(32u, XCL_X_THREADS - ((xcl_tid & ~31u) ^ 32u)) : 0u;\n"); } - pub fn finish(&self, body: &str) -> String { + pub fn finish(&self, body: &str, instructions: usize) -> String { + // DXC otherwise copies each window switch and split-wave rendezvous to every call + // site. Keep short programs inline so the compiler can specialize their accesses. + let outline = instructions >= 1024 && matches!(self.opt.mode, Mode::Kernel | Mode::Compute(_)); let mut h = String::new(); h.push_str("// generated by XCL (RDNA2 -> HLSL), do not edit\n"); if matches!(self.opt.mode, Mode::Pixel(_)) { @@ -4259,9 +4271,16 @@ impl Em { let ty = if *cmp { "SamplerComparisonState" } else { "SamplerState" }; let _ = writeln!(h, "{ty} xcl_ss{k} : register(s{k}, space1);"); } - h.push_str(PRELUDE); + if instructions >= 4096 && matches!(self.opt.mode, Mode::Kernel | Mode::Compute(_)) { + // Each VALU instruction tests EXEC. Sharing this bit test saves a large program + // tens of thousands of copies while retaining the current EXEC at every call. + h.push_str(&PRELUDE.replacen("bool lanebit(uint lo, uint hi)", "[noinline] bool lanebit(uint lo, uint hi)", 1)); + } else { + h.push_str(PRELUDE); + } + h.push_str(&PRELUDE_BUFFER_BOUNDS.replace("XCL_OUTLINE", if outline { "[noinline] " } else { "" })); if self.x64() { - self.x64_prelude(&mut h); + self.x64_prelude(&mut h, outline); } if let Some(u) = &self.upper { // wave64 VS / PS on a GPU with 32-lane waves only (`upper_lanes`) @@ -4272,7 +4291,16 @@ impl Em { } let infos: Vec = (0..BUF_FORMATS.len()).map(|i| format!("0x{:08X}u", buf_format_info(i))).collect(); let _ = writeln!(h, "static const uint FMT_INFO[78] = {{ {} }};", infos.join(", ")); - h.push_str(PRELUDE_MEM); + // A channel in an unaligned element can cross a 4 GiB window boundary. Select + // each word's window independently and leave the instruction's base window intact. + if windows > 1 { + h.push_str("uint fmt_word(uint base, uint offset) { uint at = base + offset; uint saved = xcl_w; xcl_w += uint(at < base); uint word = mem.Load(at); xcl_w = saved; return word; }\n"); + } else { + h.push_str("uint fmt_word(uint base, uint offset) { return mem.Load(base + offset); }\n"); + } + // Typed buffer conversions are large and often repeated hundreds or thousands of + // times in one program. Keep their scalar implementations shared in larger CSs. + h.push_str(&format_mem_prelude(instructions >= 256 && matches!(self.opt.mode, Mode::Kernel | Mode::Compute(_)))); if self.uses_scratch { h.push_str(PRELUDE_SCRATCH); } @@ -4299,6 +4327,7 @@ impl Em { } // split wave64: 64 threads (the console wave) in two hardware wave32s let hw_lanes = if self.x64() { 32 } else { lanes }; + if let Some(regions) = &self.regions { regions.emit(&mut h); } let _ = writeln!(h, "[WaveSize({hw_lanes})]\n[numthreads({lanes}, 1, 1)]\nvoid main(uint gi : SV_GroupIndex)\n{{"); if split { h.push_str(" uint xcl_hw_lane = WaveGetLaneIndex();\n xcl_w32 = WaveGetLaneCount() > 32u;\n xcl_half = xcl_w32 ? xcl_hw_lane >> 5 : 0u;\n lane_id = xcl_hw_lane & 31u;\n"); @@ -4397,6 +4426,7 @@ impl Em { } } self.safe_barrier_prelude(&mut h); + if let Some(regions) = &self.regions { regions.emit(&mut h); } let _ = writeln!( h, "[WaveSize({hw_lanes})]\n[numthreads({x}, {y}, {z})]\nvoid main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID, uint gi : SV_GroupIndex)\n{{" @@ -4704,7 +4734,7 @@ impl Em { } if windows > 1 { let coherent = if matches!(self.opt.mode, Mode::Compute(_)) { "globallycoherent " } else { "" }; - h = windowed(&h, windows, self.opt.heap_windows.then_some(coherent)); + h = windowed(&h, windows, self.opt.heap_windows.then_some(coherent), outline); } h } @@ -4839,8 +4869,13 @@ pub fn mesh_passthrough_for(ms: &MsInterface, ps_inputs: Option<&[SigElement]>) let _ = writeln!(fill, " o.p{k} = {v};"); } let tri_base = MESH_HEADER + mv as usize * vd; + // The declaration is chosen by the vertex budget, the dispatch group count separately: + // a record over the budget in whole vertices can still fit one compact group (its few + // triangles' own copies fit) – declaring verts[mv] there is refused by DXC (80 vertices + // with 22 float4 rows are accounted as 96: 33792 B > 32768). + let cap = passthrough_max_vertices(16 * (1 + elems.len() as u32)); let split = passthrough_split(ms, elems.len()); - if split == 1 { + if mv <= cap { let _ = writeln!( h, "[outputtopology(\"triangle\")]\n[numthreads({t}, 1, 1)]\nvoid main(uint gi : SV_GroupIndex, uint3 gid : SV_GroupID, out vertices XclVert verts[{mv}], out indices uint3 tris[{mp}])\n{{" @@ -4886,15 +4921,26 @@ pub fn mesh_passthrough_for(ms: &MsInterface, ps_inputs: Option<&[SigElement]>) /// D3D12's limit on what one mesh shader group outputs (vertex + primitive attributes). const MESH_OUTPUT_BYTES: u32 = 32768; -/// Mesh groups the pass-through spends on one record: 1 when the record's vertices fit the -/// mesh output limit as they are, else the triangles are split into runs whose own vertex -/// copies (3 per triangle) fit. `elements`: output elements besides SV_Position. +/// Vertices the pass-through puts in one mesh group: the vertex output budget divided by the +/// stride, and DXC accounts whole chunks of 32 vertices even when fewer are declared (78 +/// vertices with 22 rows are accounted as 96). Measured with dxc 1.8.2502 (ms_6_6): every +/// boundary from 9 to 26 float4 rows agrees. +fn passthrough_max_vertices(vbytes: u32) -> u32 { + (MESH_OUTPUT_BYTES / vbytes).min(256) / 32 * 32 +} + +/// Mesh groups the pass-through spends on one record: the record's vertices fit the mesh +/// output limit as they are, or the triangles go out in runs whose own vertex copies (3 per +/// triangle) fit. The layout choice in `mesh_passthrough_for` is by the vertex budget alone; +/// this count is the dispatch's, and one compact group can carry a record whose whole +/// declaration would be refused. `elements`: output elements besides SV_Position. pub fn passthrough_split(ms: &MsInterface, elements: usize) -> u32 { let vbytes = 16 * (1 + elements as u32); - if vbytes * ms.max_vertices <= MESH_OUTPUT_BYTES { + let cap = passthrough_max_vertices(vbytes); + if ms.max_vertices <= cap { return 1; } - let ppg = (MESH_OUTPUT_BYTES / (3 * vbytes)).max(1); + let ppg = (cap / 3).max(1); ms.max_primitives.max(1).div_ceil(ppg) } @@ -5095,7 +5141,8 @@ const LOADX4_ONE_WINDOW: &str = "uint4 xcl_loadx4(uint4 a) { return uint4(mem.Lo /// definitions replace the placeholder. /// `heap`: Some(storage class) – the accessors take window k from the descriptor heap /// (`Options::heap_windows`) instead of switching over the root UAVs. -fn windowed(h: &str, windows: u32, heap: Option<&str>) -> String { +fn windowed(h: &str, windows: u32, heap: Option<&str>, outline: bool) -> String { + let outline = outline && heap.is_none(); let mut out = String::with_capacity(h.len() + 8192); let mut rest = h; while let Some(i) = rest.find("mem.") { @@ -5107,13 +5154,95 @@ fn windowed(h: &str, windows: u32, heap: Option<&str>) -> String { out.push_str("xcl_m"); out.push_str(&tail[..name_len]); rest = &tail[name_len..]; + if outline && scalar_window_method(&tail[..name_len]) { + out.push_str("(xcl_w, "); + rest = &rest[1..]; + } } else { out.push_str(&rest[..i + 4]); rest = tail; } } out.push_str(rest); - out.replacen(MEM_ACCESSORS_HERE, &mem_accessors(windows, heap), 1) + out.replacen(MEM_ACCESSORS_HERE, &mem_accessors(windows, heap, outline), 1) +} + +// SM 6.6 DXIL retains scalar calls. Vector accessors use scalar out parameters below +// so the driver sees one copy of the memory-window switch instead of one per use. +fn scalar_window_method(name: &str) -> bool { + matches!(name, "Load" | "Store") || name.starts_with("Interlocked") +} + +fn vector_window_accessor(windows: u32, name: &str, components: usize, store: bool, separate_addresses: bool) -> String { + let lanes = &['x', 'y', 'z', 'w'][..components]; + let ty = format!("uint{components}"); + let method = if separate_addresses { "Load".to_string() } else { name.trim_start_matches("xcl_m").to_string() }; + let mut s = String::new(); + let input = if separate_addresses { + lanes.iter().map(|c| format!("uint a{c}")).collect::>().join(", ") + } else { + "uint a".into() + }; + let extra = lanes.iter().map(|c| format!("{}uint {}{c}", if store { "" } else { "out " }, if store { 'v' } else { 'o' })).collect::>().join(", "); + let _ = write!(s, "[noinline] void {name}_shared(uint window, {input}, {extra}) {{ "); + if store { + let values = lanes.iter().map(|c| format!("v{c}")).collect::>().join(", "); + let _ = write!(s, "{ty} v = {ty}({values}); "); + } else { + let _ = write!(s, "{ty} v; "); + } + s.push_str("[branch] switch (window) { "); + for k in 0..windows { + let mem = if k == 0 { "mem".to_string() } else { format!("mem{k}") }; + let _ = write!(s, "case {k}u: "); + if store { + let _ = write!(s, "{mem}.{method}(a, v); "); + } else if separate_addresses { + let values = lanes.iter().map(|c| format!("{mem}.Load(a{c})")).collect::>().join(", "); + let _ = write!(s, "v = {ty}({values}); "); + } else { + let _ = write!(s, "v = {mem}.{method}(a); "); + } + s.push_str("break; "); + } + if !store { + let zeros = vec!["0u"; components].join(", "); + let _ = write!(s, "default: v = {ty}({zeros}); break; }} "); + for c in lanes { + let _ = write!(s, "o{c} = v.{c}; "); + } + } else { + s.push_str("default: break; } "); + } + s.push_str("}\n"); + let wrapper_input = if separate_addresses { format!("{ty} a") } else if store { format!("uint a, {ty} v") } else { "uint a".into() }; + let _ = write!(s, "{} {name}({wrapper_input}) {{ ", if store { "void" } else { &ty }); + if !store { + for c in lanes { + let _ = write!(s, "uint o{c}; "); + } + } + let source = if separate_addresses { + lanes.iter().map(|c| format!("a.{c}")).collect::>().join(", ") + } else if store { + let values = lanes.iter().map(|c| format!("v.{c}")).collect::>().join(", "); + format!("a, {values}") + } else { + "a".into() + }; + let _ = write!(s, "{name}_shared(xcl_w, {source}"); + if !store { + for c in lanes { + let _ = write!(s, ", o{c}"); + } + } + s.push_str("); "); + if !store { + let values = lanes.iter().map(|c| format!("o{c}")).collect::>().join(", "); + let _ = write!(s, "return {ty}({values}); "); + } + s.push_str("}\n"); + s } /// The accessor functions: one per `mem` method (and overload) the translator emits. @@ -5122,7 +5251,8 @@ fn windowed(h: &str, windows: u32, heap: Option<&str>) -> String { /// out-of-UMA pointers can never wrap onto live memory windows. /// `heap`: Some(storage class) – window k is taken from the descriptor heap /// (`Options::heap_windows`) and the same rule is one comparison before the access. -fn mem_accessors(windows: u32, heap: Option<&str>) -> String { +fn mem_accessors(windows: u32, heap: Option<&str>, outline: bool) -> String { + let outline = outline && heap.is_none(); let mut sigs: Vec<(&str, String, &str, &str, &str)> = vec![ ("uint", "Load".into(), "uint a", "a", "return 0u;"), ("uint2", "Load2".into(), "uint a", "a", "return uint2(0u, 0u);"), @@ -5160,14 +5290,27 @@ fn mem_accessors(windows: u32, heap: Option<&str>) -> String { } return s; } - let _ = write!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] switch (xcl_w) {{ "); - let _ = write!(s, "case 0u: return uint4(mem.Load(a.x), mem.Load(a.y), mem.Load(a.z), mem.Load(a.w)); "); - for k in 1..windows { - let _ = write!(s, "case {k}u: return uint4(mem{k}.Load(a.x), mem{k}.Load(a.y), mem{k}.Load(a.z), mem{k}.Load(a.w)); "); + if outline { + s.push_str(&vector_window_accessor(windows, "xcl_loadx4", 4, false, true)); + } else { + let _ = write!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] switch (xcl_w) {{ "); + let _ = write!(s, "case 0u: return uint4(mem.Load(a.x), mem.Load(a.y), mem.Load(a.z), mem.Load(a.w)); "); + for k in 1..windows { + let _ = write!(s, "case {k}u: return uint4(mem{k}.Load(a.x), mem{k}.Load(a.y), mem{k}.Load(a.z), mem{k}.Load(a.w)); "); + } + let _ = writeln!(s, "default: return uint4(0u, 0u, 0u, 0u); }} }}"); } - let _ = writeln!(s, "default: return uint4(0u, 0u, 0u, 0u); }} }}"); for (ret, name, params, args, def) in sigs { - let _ = write!(s, "{ret} xcl_m{name}({params}) {{ [branch] switch (xcl_w) {{ "); + if outline && matches!(name.as_str(), "Load2" | "Load3" | "Load4" | "Store2" | "Store3" | "Store4") { + let components = name.chars().last().unwrap().to_digit(10).unwrap() as usize; + s.push_str(&vector_window_accessor(windows, &format!("xcl_m{name}"), components, name.starts_with("Store"), false)); + continue; + } + if outline && scalar_window_method(&name) { + let _ = write!(s, "[noinline] {ret} xcl_m{name}(uint window, {params}) {{ [branch] switch (window) {{ "); + } else { + let _ = write!(s, "{ret} xcl_m{name}({params}) {{ [branch] switch (xcl_w) {{ "); + } if ret == "void" { let _ = write!(s, "case 0u: mem.{name}({args}); break; "); for k in 1..windows { @@ -5250,6 +5393,23 @@ fn d16_merge(v: &str, raw: &str, n: u32, signed: bool, half: u32) -> String { } } +/// RDNA2 V# word 3 [29:28] selects the bounds rule. Mode 3 subtracts the +/// scalar offset from the raw byte extent. Formatted accesses pass their +/// entire payload, while unformatted vector accesses check each component. +const PRELUDE_BUFFER_BOUNDS: &str = r#" +XCL_OUTLINEbool xcl_buf_in_range(uint word1, uint records, uint word3, uint index, uint64_t offset, uint bytes, uint sgpr_offset) { + uint mode = (word3 >> 28) & 3u; + uint stride = (word1 >> 16) & 0x3FFFu; + uint64_t end = offset + (uint64_t)bytes; + if (mode == 0u) return index < records && offset < (uint64_t)stride; + if (mode == 1u) return index < records; + if (mode == 2u) return records != 0u; + if ((word1 & 0x80000000u) != 0u && stride != 0u) + return index < records && end <= (uint64_t)stride; + return end + (uint64_t)sgpr_offset <= (uint64_t)records; +} +"#; + /// Per-lane private memory of scratch_* (static = thread-private in HLSL; 4 KB per lane). const PRELUDE_SCRATCH: &str = r#" static uint xcl_scratch[1024]; @@ -5261,6 +5421,11 @@ void scr_st(uint a, uint v, uint n) { } "#; +fn format_mem_prelude(outline: bool) -> String { + // Retained DXIL calls require scalar parameters and results on the supported profiles. + PRELUDE_MEM.replace("XCL_FORMAT_FN ", if outline { "[noinline] " } else { "" }) +} + const PRELUDE_MEM: &str = r#" uint4 ld_raw(uint a) { // one Load4 + one Load (with several memory windows each is a switch) and no branch @@ -5290,12 +5455,10 @@ float uf_small(uint v, uint mb) { return select(e == 31u, special, select(e == 0u, fm * exp2(-14.0f), exp2((float)e - 15.0f) * (1.0f + fm))); } uint fmt_bytes(uint info) { return (((info >> 8) & 63u) + ((info >> 14) & 63u) + ((info >> 20) & 63u) + ((info >> 26) & 63u)) / 8u; } -uint fmt_comp(uint4 r, uint info, uint c) { - uint n = info & 7u; uint ty = (info >> 3) & 7u; - bool isint = or(ty == 4u, ty == 5u); - uint off = select(c > 0u, (info >> 8) & 63u, 0u) + select(c > 1u, (info >> 14) & 63u, 0u) + select(c > 2u, (info >> 20) & 63u, 0u); - uint w = (info >> ((8u + 6u * c) & 31u)) & 63u; - uint v = bits_at(r, off, w); +uint fmt_offset(uint info, uint c) { + return select(c > 0u, (info >> 8) & 63u, 0u) + select(c > 1u, (info >> 14) & 63u, 0u) + select(c > 2u, (info >> 20) & 63u, 0u); +} +XCL_FORMAT_FN uint fmt_value(uint v, uint w, uint ty) { uint sh = (32u - w) & 31u; int sv = select(w >= 32u, (int)v, ((int)(v << sh)) >> sh); float maxu = select(w >= 32u, 4294967295.0f, (float)((1u << (w & 31u)) - 1u)); @@ -5305,8 +5468,26 @@ uint fmt_comp(uint4 r, uint info, uint c) { uint f_un = asuint(select(v == 0u, 0.0f, select(fv >= maxu, 1.0f, fv / maxu))); uint f_sn = asuint(select(sv == 0, 0.0f, select(fsv >= maxs, 1.0f, max(fsv / maxs, -1.0f)))); uint flt = select(w == 32u, v, select(w == 16u, asuint(f16tof32(v)), asuint(uf_small(v, select(w == 11u, 6u, 5u))))); - uint res = select(ty == 0u, f_un, select(ty == 1u, f_sn, select(ty == 2u, asuint(fv), select(ty == 3u, asuint(fsv), select(ty == 4u, v, select(ty == 5u, (uint)sv, flt)))))); - return select(c >= n, select(c == 3u, select(isint, 1u, 0x3F800000u), 0u), res); + return select(ty == 0u, f_un, select(ty == 1u, f_sn, select(ty == 2u, asuint(fv), select(ty == 3u, asuint(fsv), select(ty == 4u, v, select(ty == 5u, (uint)sv, flt)))))); +} +uint fmt_one(uint ty) { return select(or(ty == 4u, ty == 5u), 1u, 0x3F800000u); } +uint fmt_comp(uint4 r, uint info, uint c) { + uint ty = (info >> 3) & 7u, w = (info >> (8u + 6u * c)) & 63u; + return select(c >= (info & 7u), select(c == 3u, fmt_one(ty), 0u), fmt_value(bits_at(r, fmt_offset(info, c), w), w, ty)); +} +// BUFFER_LOAD_FORMAT_X needs one swizzled channel. Check the whole record but fetch +// just its selected bits. Constants and out-of-range reads do not touch the UAV. +XCL_FORMAT_FN uint fmt_load_selected(uint a, uint info, uint sel, bool ok) { + uint ty = (info >> 3) & 7u, c = (sel - 4u) & 3u; + if (sel == 1u) return fmt_one(ty); + if (sel == 0u || !ok) return 0u; + if (c >= (info & 7u)) return c == 3u ? fmt_one(ty) : 0u; + uint w = (info >> (8u + 6u * c)) & 63u; + uint bit = (a & 3u) * 8u + fmt_offset(info, c); + uint offset = (bit >> 5) * 4u, shift = bit & 31u; + uint value = fmt_word(a & ~3u, offset) >> shift; + if (shift + w > 32u) value |= fmt_word(a & ~3u, offset + 4u) << (32u - shift); + return fmt_value(w == 32u ? value : value & ((1u << w) - 1u), w, ty); } // image_bvh(64)_intersect_ray: type = node & 7, at = low 32 bits of base + (node & ~7) * 8. // box32 (5) / box16 (4): 4 child ids + boxes → hit children (closest first when sorting), @@ -5381,19 +5562,38 @@ uint fmt_encode(uint x, uint info, uint c) { uint h = f32tof16(f); return w == 11u ? ((h >> 4) & 0x7FFu) : ((h >> 5) & 0x3FFu); } -uint4 fmt_pack(uint4 v, uint info) { +XCL_FORMAT_FN void fmt_pack_shared(uint v0, uint v1, uint v2, uint v3, uint info, out uint o0, out uint o1, out uint o2, out uint o3) { + uint4 v = uint4(v0, v1, v2, v3); uint4 r = uint4(0u, 0u, 0u, 0u); uint n = info & 7u; uint off = 0u; [unroll] for (uint c = 0u; c < 4u; c++) { if (c < n) { uint w = (info >> (8u + 6u * c)) & 63u; put_bits(r, off, w, fmt_encode(v[c], info, c)); off += w; } } - return r; + o0 = r.x; o1 = r.y; o2 = r.z; o3 = r.w; +} +uint4 fmt_pack(uint4 v, uint info) { uint o0, o1, o2, o3; fmt_pack_shared(v.x, v.y, v.z, v.w, info, o0, o1, o2, o3); return uint4(o0, o1, o2, o3); } +void st_part(uint b, uint m, uint v) { + // Update this mask in one atomic step, including when another writer overlaps it. + uint old = mem.Load(b), seen; + for (;;) { + mem.InterlockedCompareExchange(b, old, (old & ~m) | (v & m), seen); + if (seen == old) break; + old = seen; + } } -void st_part(uint b, uint m, uint v) { mem.InterlockedAnd(b, ~m); mem.InterlockedOr(b, v & m); } -void st_bytes(uint a, uint4 r, uint n) { +XCL_FORMAT_FN void st_bytes_shared(uint a, uint r0, uint r1, uint r2, uint r3, uint n) { + uint4 r = uint4(r0, r1, r2, r3); uint s = (a & 3u) * 8u; uint b = a & ~3u; if (s == 0u && (n & 3u) == 0u) { [unroll] for (uint k = 0u; k < 4u; k++) if (k * 4u < n) mem.Store(b + 4u * k, r[k]); return; } - uint m = n >= 4u ? 0xFFFFFFFFu : ((1u << (8u * n)) - 1u); - st_part(b, m << s, r.x << s); - if (s != 0u && s + 8u * n > 32u) st_part(b + 4u, m >> (32u - s), r.x >> (32u - s)); + // An unaligned 8- or 16-byte format spans up to five dwords. Write every affected + // dword, preserving bytes outside the formatted value, including adjacent lanes' data. + uint end = s + 8u * min(n, 16u); + [loop] for (uint k = 0u; k < 5u; k++) { + uint low = 32u * k, first = max(s, low), last = min(end, low + 32u); + if (first >= last) continue; + uint width = last - first, shift = first - low; + uint mask = (width == 32u ? 0xFFFFFFFFu : ((1u << width) - 1u)) << shift; + st_part(b + 4u * k, mask, bits_at(r, first - s, width) << shift); + } } +void st_bytes(uint a, uint4 r, uint n) { st_bytes_shared(a, r.x, r.y, r.z, r.w, n); } uint dst_sel(uint4 c, uint sel, bool isint) { return select(sel == 0u, 0u, select(sel == 1u, select(isint, 1u, 0x3F800000u), pick4(c, (sel - 4u) & 3u))); } "#; @@ -5432,7 +5632,7 @@ uint xcl_x_at(uint half, uint k) { return ((xcl_cw * 2u + half) * 2u + (k & 1u)) void xcl_x_put(uint i, uint v) { XCL_XS(xcl_x_at(xcl_half, xcl_xk) + i) = v; } uint xcl_x_get(uint i) { return XCL_XS(xcl_x_at(xcl_half ^ 1u, xcl_xk - 1u) + i); } // meet the other half after `xcl_x_put`: true = its words are readable (`xcl_x_get`) -bool xcl_x_meet() { +XCL_EXCHANGE_FN bool xcl_x_meet() { uint k = xcl_xk; xcl_xk = k + 1u; if (xcl_xn == 0u) return false; @@ -5466,21 +5666,23 @@ bool xcl_x_meet() { #endif return true; } -uint2 xcl_x_ballot(bool b) { +XCL_EXCHANGE_FN void xcl_x_ballot_shared(bool b, out uint lo, out uint hi) { uint m = WaveActiveBallot(b).x; xcl_x_put(0u, m); uint o = xcl_x_meet() ? xcl_x_get(0u) : 0u; - return xcl_half != 0u ? uint2(o, m) : uint2(m, o); + lo = xcl_half != 0u ? o : m; + hi = xcl_half != 0u ? m : o; } +uint2 xcl_x_ballot(bool b) { uint lo, hi; xcl_x_ballot_shared(b, lo, hi); return uint2(lo, hi); } // v_readlane / v_readfirstlane: the same lane index in both halves; the owner half's value -uint xcl_x_rla_uniform(uint v, uint l) { +XCL_EXCHANGE_FN uint xcl_x_rla_uniform(uint v, uint l) { uint m = WaveReadLaneAt(v, l & 31u); xcl_x_put(0u, m); uint o = xcl_x_meet() ? xcl_x_get(0u) : 0u; return (l >> 5) == xcl_half ? m : o; } // ds_bpermute: any lane of the wave -uint xcl_x_rla_any(uint v, uint l) { +XCL_EXCHANGE_FN uint xcl_x_rla_any(uint v, uint l) { xcl_x_put(WaveGetLaneIndex(), v); uint o = xcl_x_meet() ? xcl_x_get(l & 31u) : 0u; uint m = WaveReadLaneAt(v, l & 31u); diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 1a1a8ba79d..db155cab94 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -57,6 +57,7 @@ pub mod lane_masks; pub mod lower; pub mod lower_dxil; pub(crate) mod emit; +mod regions; pub mod mesh_dispatch; pub mod mesh_wave; pub mod x64_masks; @@ -1058,10 +1059,19 @@ fn emit_structured( _ => "false".into(), }; body.push_str(&format!("{ipad}if (!({cond})) {{\n")); + let arm = body.len(); let mut r = emit_structured(c, em, body, end, t, u, nest + 1, cont, &none, d + 1, blocks, flags); + if let Some(regions) = &mut em.regions { + if r.is_empty() { regions.outline(body, arm, d + 1); } + } if let Some(u) = u { body.push_str(&format!("{ipad}}} else {{\n")); - r.extend(emit_structured(c, em, body, t, u, None, nest + 1, cont, &none, d + 1, blocks, flags)); + let arm = body.len(); + let other = emit_structured(c, em, body, t, u, None, nest + 1, cont, &none, d + 1, blocks, flags); + if let Some(regions) = &mut em.regions { + if other.is_empty() { regions.outline(body, arm, d + 1); } + } + r.extend(other); } body.push_str(&format!("{ipad}}}\n")); r @@ -1389,6 +1399,10 @@ pub(crate) fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet) -> B } pub fn translate(code: &[u8], opt: &Options) -> Result { + translate_program(code, opt, true) +} + +fn translate_program(code: &[u8], opt: &Options, share_regions: bool) -> Result { let program = code; let normalized; let opt = if opt.mem_windows & HEAP_WINDOWS != 0 { @@ -1493,9 +1507,12 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { if gs_jump.is_none() && opt.structured && std::env::var_os("XCL_RECOMP_NO_STRUCTURED").is_none() && structurable(&sctx, 0, u64::MAX).is_some() { // structured control flow: plain if / loops, no block dispatch on `pc` (much // smaller for DXC and the driver on big programs) + if share_regions && matches!(opt.mode, Mode::Compute(_) | Mode::Kernel) && regions::worthwhile(&sctx, program) { + em.regions = Some(Default::default()); + } emit_structured(&sctx, &mut em, &mut code, 0, u64::MAX, None, 0, &Conts::default(), &BTreeSet::new(), 1, &mut blocks, &mut flags); if code.len() > STRUCTURED_BYTES_PER_CODE_BYTE * program.len() { - return translate(program, &Options { structured: false, ..opt.clone() }); + return translate_program(program, &Options { structured: false, ..opt.clone() }, share_regions); } } else { if gs_jump.is_some() && opt.split_wave64 && opt.wave64 { @@ -1510,7 +1527,7 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { } body.push_str(&code); } - let hlsl = em.finish(&body); + let hlsl = em.finish(&body, insts.len()); let static_samplers = em.static_used.clone(); Ok(Translation { hlsl, unsupported: em.unsupported, unsupported_why: em.unsupported_why, ignored: em.ignored, instructions: insts.len(), blocks, static_samplers }) } diff --git a/crates/xcl/src/gpu/recomp/regions.rs b/crates/xcl/src/gpu/recomp/regions.rs new file mode 100644 index 0000000000..b25123af1a --- /dev/null +++ b/crates/xcl/src/gpu/recomp/regions.rs @@ -0,0 +1,151 @@ +//! Outline repeated, single-entry arms of the structured compute CFG. The input is the +//! emitter's own HLSL. A closed set of expressions makes the register interface explicit: +//! other operations, local entry-point state and nonlocal jumps stay in their original scope. + +use std::collections::{HashMap, HashSet}; +use std::fmt::Write as _; + +use super::{block_end, insts_in, Ctx}; +use crate::gpu::rdna2; + +pub(super) fn worthwhile(c: &Ctx, bytes: &[u8]) -> bool { + // Scalar copy-in/copy-out also costs DXIL. Two measured trees of 1,066 and + // 6,466 instructions were smaller inline. Look for extensive whole-program + // repetition before introducing call boundaries. + if c.insts.len() < 4096 || c.edges.len() < 128 { + return false; + } + let mut copies = HashMap::<&[u8], usize>::new(); + let mut repeated = 0; + for (i, &start) in c.leaders.iter().enumerate() { + let Some(last) = insts_in(c, start, block_end(c, i)).last() else { continue }; + let end = if rdna2::branch_target(last).is_some() { last.pc as usize } else { last.pc as usize + last.len }; + let block = &bytes[start as usize..end]; + let count = copies.entry(block).or_default(); + *count += 1; + if *count >= 16 { + repeated += block.len(); + } + } + repeated > bytes.len() / 3 +} + +#[derive(Default)] +pub(super) struct Regions { + // Full string equality is required. The insertion order supplies stable function names. + by_body: HashMap, + functions: Vec, +} + +struct Function { + body: String, + writes: Vec, + uses: usize, +} + +fn numbered(name: &str, prefix: &str) -> bool { + name.strip_prefix(prefix).is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) +} + +fn register(name: &str) -> bool { + numbered(name, "s") || numbered(name, "v") || numbered(name, "ttmp") || + matches!(name, "scc" | "m0" | "vcc_lo" | "vcc_hi" | "exec_lo" | "exec_hi") +} + +// These emitter operations take their registers by value. An operation with an output +// argument needs an explicit write rule before it can be added here. +fn known(name: &str) -> bool { + matches!(name, + "if" | "else" | "true" | "false" | "uint" | "uint2" | "uint3" | "uint4" | "uint64_t" | + "int" | "int2" | "int3" | "int4" | "int64_t" | "float" | "float2" | "float3" | "float4" | + "bool" | "bool2" | "bool3" | "bool4" | "asfloat" | "asuint" | "asint" | "min" | "max" | + "select" | "or" | "and" | "abs" | "floor" | "mad" | "rcp" | "rsqrt" | "saturate" | + "isnan" | "reversebits" | "f16tof32" | "f32tof16" | "cvt_u32" | "bfe_u" | "mul_legacy" | + "lane_id" | "lanebit" | "ballot" | "xcl_x_ballot" | "xcl_x_ballot_local" | + "mem" | "Load" | "Load2" | "Load3" | "Load4" | "Store" | "Store2" | "Store3" | "Store4" | + "xcl_w" | "xcl_uma_base" | "xcl_loadx4" | "xcl_buf_in_range" | "FMT_INFO" | + "fmt_bytes" | "ld_raw" | "fmt_comp" | "fmt_load_selected" | "dst_sel" | "img_cls" | + "ResourceDescriptorHeap" | "SamplerDescriptorHeap" | "NonUniformResourceIndex" | + "Texture2D" | "SamplerState" | "GatherRed" | "SampleLevel" + ) || numbered(name, "xcl_ss") || (name.len() <= 4 && name.bytes().all(|b| b"xyzw".contains(&b))) +} + +fn assigning(tail: &str) -> bool { + let tail = tail.trim_start(); + (tail.starts_with('=') && !tail.starts_with("==")) || + ["+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "++", "--"].iter().any(|op| tail.starts_with(op)) +} + +impl Regions { + pub fn outline(&mut self, body: &mut String, start: usize, indent: usize) { + let mut regs = Vec::<&str>::new(); + let mut outputs = HashSet::new(); + let mut temps = HashMap::new(); + let mut canonical = String::new(); + for raw in body[start..].lines() { + let line = raw.split("//").next().unwrap().trim(); + if line.is_empty() { continue; } + // Child calls occupy one whole line and pass each register exactly once. + // Propagate their copy-out parameters when forming the enclosing function. + if let Some(call) = line.strip_prefix("xcl_region_") { + let Some((id, args)) = call.split_once('(') else { return }; + let Some(f) = id.parse::().ok().and_then(|i| self.functions.get(i)) else { return }; + let Some(args) = args.strip_suffix(");") else { return }; + for (arg, &written) in args.split(", ").zip(&f.writes) { + if written { outputs.insert(arg); } + } + } + let mut rest = line; + while let Some(i) = rest.find(|c: char| c.is_ascii_alphanumeric() || c == '_') { + canonical.push_str(&rest[..i]); + rest = &rest[i..]; + let end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_').unwrap_or(rest.len()); + let token = &rest[..end]; + rest = &rest[end..]; + if register(token) { + let index = regs.iter().position(|&r| r == token).unwrap_or_else(|| { regs.push(token); regs.len() - 1 }); + if assigning(rest) { outputs.insert(token); } + let _ = write!(canonical, "p{index}"); + } else if let Some(temp) = token.strip_prefix('t').filter(|s| s.starts_with(|c: char| c.is_ascii_digit())) { + let digits = temp.find(|c: char| !c.is_ascii_digit()).unwrap_or(temp.len()); + let suffix = &temp[digits..]; + if !suffix.is_empty() && !suffix.starts_with('_') { return; } + let next = temps.len(); + let index = temps.entry(&temp[..digits]).or_insert(next); + let _ = write!(canonical, "t{index}{suffix}"); + } else if token.as_bytes()[0].is_ascii_digit() || known(token) || numbered(token, "xcl_region_") { + canonical.push_str(token); + } else { + return; + } + } + canonical.push_str(rest); + canonical.push('\n'); + } + if canonical.len() < 100 { return; } + let id = *self.by_body.entry(canonical.clone()).or_insert_with(|| { + let writes = regs.iter().map(|r| outputs.contains(r)).collect(); + self.functions.push(Function { body: canonical, writes, uses: 0 }); + self.functions.len() - 1 + }); + self.functions[id].uses += 1; + let args = regs.join(", "); + body.truncate(start); + let _ = writeln!(body, "{}xcl_region_{id}({args});", " ".repeat(indent)); + } + + pub fn emit(&self, h: &mut String) { + for (id, f) in self.functions.iter().enumerate() { + if f.uses > 1 { h.push_str("[noinline] "); } + let _ = write!(h, "void xcl_region_{id}("); + for (i, &write) in f.writes.iter().enumerate() { + if i != 0 { h.push_str(", "); } + if write { h.push_str("inout "); } + let _ = write!(h, "uint p{i}"); + } + h.push_str(") {\n"); + h.push_str(&f.body); + h.push_str("}\n"); + } + } +} diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 55ef19082f..ab57fbc762 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -192,7 +192,8 @@ fn hlsl_is_generated_for_straight_line_and_branches() { assert!(t.complete(), "{:?}", t.unsupported); assert_eq!(t.blocks, 3, "{}", t.hlsl); // forward branches only: a plain `if`, no loop and no block dispatch on pc - assert!(t.hlsl.contains("if (!(") && !t.hlsl.contains("pc ==") && !t.hlsl.contains("for (;;)") && t.hlsl.contains("[WaveSize(64)]"), "{}", t.hlsl); + let entry = t.hlsl.split_once("void main(").unwrap().1; + assert!(entry.contains("if (!(") && !entry.contains("pc ==") && !entry.contains("for (;;)") && t.hlsl.contains("[WaveSize(64)]"), "{}", t.hlsl); // the guarded block chain (fallback form) for the same program // (an option, not the environment variable: other tests translate at the same time) let g = translate(&code, &Options { structured: false, ..Options::default() }).unwrap(); @@ -429,7 +430,7 @@ fn atomic_fcmpswap_x2_is_a_bitwise_64_bit_cas() { assert!(t.hlsl.contains("_cmp = (uint64_t)v26 | ((uint64_t)v27 << 32);"), "{}", t.hlsl); // 8-byte alignment of all three cells; the buffer form's bounds check reads records in dwords assert_eq!(t.hlsl.matches("& ~7u;").count(), 3, "{}", t.hlsl); - assert!(t.hlsl.contains("_off + 8u <= s10"), "{}", t.hlsl); + assert!(t.hlsl.contains("xcl_buf_in_range(s9, s10, s11"), "{}", t.hlsl); // GLC returns the old u64 as a low / high dword pair – in place in VDATA for the buffer // form, into VDST for flat / global assert_eq!(t.hlsl.matches("_old >> 32").count(), 3, "{}", t.hlsl); @@ -1313,6 +1314,7 @@ fn gpu_memory_and_exports() { st.sgpr[12] = 0x40; // V#: base 0x40, stride 0, 0x100 bytes st.sgpr[13] = 0; st.sgpr[14] = 0x100; + st.sgpr[15] = 3 << 28; // raw byte extent for (l, r) in st.vgpr.iter_mut().enumerate() { r[0] = 4 * l as u32; r[6] = f(0.5); @@ -1355,9 +1357,9 @@ fn gpu_grouped_loads_bounds_and_inactive_lanes() { let mut st = KernelState::default(); st.sgpr[0] = 0; // flat pointer 0 st.sgpr[4..8].copy_from_slice(&[0x80, 0, 20, 0]); // V#: base 0x80, 20 bytes - st.sgpr[8..12].copy_from_slice(&[0x100, 0, 0x100, 0]); // V#: base 0x100, 0x100 bytes + st.sgpr[8..12].copy_from_slice(&[0x100, 0, 0x100, 3 << 28]); // V#: base 0x100, 0x100 bytes st.sgpr[12..16].copy_from_slice(&[0x100, 12 << 16, 40, 0]); // V#: base 0x100, stride 12, 40 records - st.sgpr[52..56].copy_from_slice(&[0x400, 0, 0x104, 0]); // V#: base 0x400, 0x104 bytes + st.sgpr[52..56].copy_from_slice(&[0x400, 0, 0x104, 3 << 28]); // V#: base 0x400, 0x104 bytes for (l, r) in st.vgpr.iter_mut().enumerate() { r[1] = l as u32; r[2] = 8 * l as u32; @@ -1387,6 +1389,110 @@ fn gpu_grouped_loads_bounds_and_inactive_lanes() { } } +/// The V# OOB_SELECT bits govern all buffer operations, including scalar offsets +/// in raw mode. The same descriptor is used for loads, stores and atomics. +#[test] +fn gpu_buffer_descriptor_bounds_modes() { + if !gpu_ready() { + return; + } + for (mode, stride, records, sgpr_offset, visible) in [ + (0u32, 4u32, 8u32, 0u32, 8usize), + (1, 4, 8, 0, 8), + (2, 4, 1, 0, 64), + (2, 4, 0, 0, 0), + (3, 0, 20, 8, 3), + (3, 4, 20, 0, 64), + ] { + let raw_offset = mode == 3 && stride == 0; + let address_field = if raw_offset { "OFFEN" } else { "IDXEN" }; + let code = prog(&[ + ("BUFFER_LOAD_DWORD", "ENC_MUBUF", vec![("VDATA", 10), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 1), (address_field, 1)], None), + ("BUFFER_STORE_DWORD", "ENC_MUBUF", vec![("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("SOFFSET", 1), (address_field, 1)], None), + ("BUFFER_ATOMIC_ADD", "ENC_MUBUF", vec![("VDATA", 11), ("VADDR", 0), ("SRSRC", 5), ("SOFFSET", 1), (address_field, 1)], None), + ].iter().map(|(n,e,f,l)| (*n,*e,f.as_slice(),*l)).collect::>()); + let mut mem = vec![0xA5A5_A5A5u32; 1024]; + let mut st = KernelState::default(); + st.sgpr[1] = sgpr_offset; + for (slot, base) in [(3, 0x100u32), (4, 0x400), (5, 0x800)] { + st.sgpr[slot * 4..slot * 4 + 4].copy_from_slice(&[base, stride << 16, records, mode << 28]); + } + for lane in 0..64 { + let offset = (sgpr_offset / 4) as usize + lane; + mem[0x100 / 4 + offset] = 1000 + lane as u32; + mem[0x800 / 4 + offset] = 0; + st.vgpr[lane][0] = if raw_offset { lane as u32 * 4 } else { lane as u32 }; + st.vgpr[lane][11] = 1; + } + let result = runner::run_code(&code, &st, &mem).unwrap(); + for lane in 0..64 { + let offset = (sgpr_offset / 4) as usize + lane; + let active = lane < visible; + assert_eq!(result.vgpr[lane][10], if active { 1000 + lane as u32 } else { 0 }, "load mode {mode}, lane {lane}"); + assert_eq!(result.mem[0x400 / 4 + offset], if active { 1000 + lane as u32 } else { 0xA5A5_A5A5 }, "store mode {mode}, lane {lane}"); + assert_eq!(result.mem[0x800 / 4 + offset], u32::from(active), "atomic mode {mode}, lane {lane}"); + } + } + // Mode 0 checks the starting offset, even when a dword load's payload + // extends beyond the stride. The low address bits are ignored by the load. + let code = prog(&[( + "BUFFER_LOAD_DWORD", + "ENC_MUBUF", + &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("OFFEN", 1)], + None, + )]); + let mut st = KernelState::default(); + st.sgpr[12..16].copy_from_slice(&[0x400, 8 << 16, 1, 0]); + for lane in &mut st.vgpr { + lane[0] = 7; + } + let mut mem = vec![0u32; 512]; + mem[0x404 / 4] = 0x1122_3344; + let result = runner::run_code(&code, &st, &mem).unwrap(); + for lane in 0..64 { + assert_eq!(result.vgpr[lane][10], 0x1122_3344, "mode 0 starting offset, lane {lane}"); + } + // ADD_TID_ENABLE contributes the console lane to both the address and the + // record check even when the instruction has no explicit index VGPR. + let code = prog(&[( + "BUFFER_LOAD_DWORD", + "ENC_MUBUF", + &[("VDATA", 10), ("SRSRC", 3), ("SOFFSET", 128)], + None, + )]); + let mut st = KernelState::default(); + st.sgpr[12..16].copy_from_slice(&[0x100, 4 << 16, 8, 1 << 23]); + let mut mem = vec![0u32; 256]; + for i in 0..8 { + mem[0x100 / 4 + i] = 0xAB00 + i as u32; + } + let result = runner::run_code(&code, &st, &mem).unwrap(); + for lane in 0..64 { + let expected = if lane < 8 { 0xAB00 + lane as u32 } else { 0 }; + assert_eq!(result.vgpr[lane][10], expected, "ADD_TID lane {lane}"); + } +} + +#[test] +fn gpu_typed_buffer_out_of_bounds_keeps_one_selected_channels() { + if !gpu_ready() { + return; + } + let code = prog(&[( + "BUFFER_LOAD_FORMAT_XYZW", + "ENC_MUBUF", + &[("VDATA", 10), ("SRSRC", 3), ("SOFFSET", 128)], + None, + )]); + let mut st = KernelState::default(); + // 8_8_8_8_UNORM, OOB_SELECT 2 with no records, selectors 1/0/1/0. + st.sgpr[12..16].copy_from_slice(&[0x100, 0, 0, (2 << 28) | (56 << 12) | 1 | (1 << 6)]); + let result = runner::run_code(&code, &st, &vec![0xDEAD_BEEFu32; 256]).unwrap(); + for lane in 0..64 { + assert_eq!(&result.vgpr[lane][10..14], &[1.0f32.to_bits(), 0, 1.0f32.to_bits(), 0], "lane {lane}"); + } +} + /// A real console vertex shader from the retail pack, run on the PC GPU /// (needs XCL_SAMPLE_RPF=…\shaders.rpf). #[test] @@ -1524,8 +1630,8 @@ fn buffer_format_d16_packs_and_unpacks_halves() { ]); let t = translate(&code, &Options::default()).unwrap(); assert!(t.complete(), "{:?}\n{}", t.unsupported_why, t.hlsl); - assert!(t.hlsl.contains("v10 = t1_ok ? (select(t1_int") && t.hlsl.contains("v11 = t1_ok ? (select(t1_int"), "{}", t.hlsl); - assert!(t.hlsl.contains("v12 = (v12 & 0xFFFFu) | (t2_ok ? (select(t2_int") && t.hlsl.contains("<< 16) : 0u)"), "{}", t.hlsl); + assert!(t.hlsl.contains("t1_c = select(t1_ok") && t.hlsl.contains("v10 = select(t1_int") && t.hlsl.contains("v11 = select(t1_int"), "{}", t.hlsl); + assert!(t.hlsl.contains("v12 = (v12 & 0xFFFFu) | (select(t2_int"), "{}", t.hlsl); assert!(t.hlsl.contains("uint t3_ty = (t3_info >> 3) & 7u") && t.hlsl.contains("f16tof32(((v14) & 0xFFFFu))"), "{}", t.hlsl); assert!(t.hlsl.contains("f16tof32(((v16 >> 16) & 0xFFFFu))"), "{}", t.hlsl); if super::dxc::location().is_ok() { @@ -1541,7 +1647,7 @@ fn gpu_typed_buffer_loads_and_stores() { } let ident = 4 | 5 << 3 | 6 << 6 | 7 << 9; let bgra = 6 | 5 << 3 | 4 << 6 | 7 << 9; - let vs = |base: u32, fmt: u32, sel: u32| [base, 0, 0x100, sel | fmt << 12]; + let vs = |base: u32, fmt: u32, sel: u32| [base, 0, 0x100, (3 << 28) | sel | fmt << 12]; let code = prog(&[ ("BUFFER_LOAD_FORMAT_XYZW", "ENC_MUBUF", &[("VDATA", 10), ("SRSRC", 3), ("SOFFSET", 128)], None), // A ("BUFFER_LOAD_FORMAT_XYZW", "ENC_MUBUF", &[("VDATA", 14), ("SRSRC", 4), ("SOFFSET", 128)], None), // B @@ -1577,7 +1683,7 @@ fn gpu_typed_buffer_loads_and_stores() { vs(0x118, 8, ident), vs(0x11C, 36, ident), vs(0x120, 0, ident), - [0x400, 0, 0x100, 0], + [0x400, 0, 0x100, 3 << 28], ] .iter() .enumerate() @@ -2557,6 +2663,155 @@ fn half_bits(x: f32) -> u32 { (b >> 16 & 0x8000) | ((e as u32) << 10) | ((b >> 13) & 0x3FF) } +#[test] +fn gpu_single_formatted_load_matches_vector_swizzle() { + if !gpu_ready() { return; } + // Compare all V# formats and selector codes, including constant channels, across + // unaligned addresses, out-of-range indices and inactive lanes in both wave halves. + const BATCH: usize = 16; + let mut code = Vec::new(); + for i in 0..BATCH { + let dst = (8 + 9 * i) as u64; + let desc = (3 + i) as u64; + for (op, v) in [("BUFFER_LOAD_FORMAT_X", dst), ("BUFFER_LOAD_FORMAT_XYZW", dst + 1), + ("BUFFER_LOAD_FORMAT_D16_X", dst + 5), ("BUFFER_LOAD_FORMAT_D16_HI_X", dst + 6), + ("BUFFER_LOAD_FORMAT_D16_XYZW", dst + 7)] { + code.extend(encode(op, "ENC_MUBUF", &[("VDATA", v), ("SRSRC", desc), ("SOFFSET", 128), ("VADDR", 0), ("IDXEN", 1), ("OFFEN", 1)], None).unwrap()); + } + } + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let t = translate(&code, &on_gpu(Options::default())).unwrap(); + assert!(t.complete()); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let mut state = KernelState::default(); + state.sgpr[126] = 0xDDDD_DDDD; + state.sgpr[127] = 0xB6DB_6DB6; + let guard = 0xA53C_E17B; + for (lane, regs) in state.vgpr.iter_mut().enumerate() { + regs.fill(guard); + regs[0] = lane as u32; + regs[1] = (lane & 3) as u32; + } + let mem: Vec = (0..512u32).map(|i| i.wrapping_mul(0x37AD_91EB).rotate_left(i & 31)).collect(); + for first in (0..78 * 8).step_by(BATCH) { + for i in 0..BATCH { + let fmt = (first + i) as u32 / 8; + let sel = (first + i) as u32 & 7; + let slot = 12 + 4 * i; + state.sgpr[slot..slot + 4].copy_from_slice(&[128, 24 << 16, 48, (1 << 28) | (fmt << 12) | (sel * 0x249)]); + } + let r = runner::run(&dxil, &state, &mem).unwrap(); + assert_eq!(r.mem, mem); + for i in 0..BATCH { + let dst = 8 + 9 * i; + for (lane, regs) in r.vgpr.iter().enumerate() { + let active = state.sgpr[126 + lane / 32] & (1 << (lane % 32)) != 0; + assert_eq!(regs[dst], regs[dst + 1], "descriptor {}, lane {lane}", first + i); + let half = regs[dst + 7] & 0xFFFF; + assert_eq!(regs[dst + 5], if active { half } else { guard }, "D16 X, descriptor {}, lane {lane}", first + i); + assert_eq!(regs[dst + 6], if active { (half << 16) | (guard & 0xFFFF) } else { guard }, "D16 HI, descriptor {}, lane {lane}", first + i); + } + } + } +} + +#[test] +fn gpu_repeated_conditional_arms_preserve_registers_and_stores() { + if !gpu_ready() { return; } + let branch = |op, bytes| encode(op, "ENC_SOPP", &[("SIMM16", (bytes / 4) as u64)], None).unwrap(); + let add = |dst, src| encode("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", dst), ("SRC0", src), ("VSRC1", dst)], None).unwrap(); + let cmp = |sgpr| encode("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", sgpr), ("SSRC1", 128)], None).unwrap(); + let mut program = Vec::new(); + for round in 0..384 { + let dst = 10 + round % 2; + // Alternate a distinct input register and a source that aliases its destination. + let src = if round % 4 == 0 { V + dst } else { V + 2 }; + let inner: Vec = [add(dst, src), add(dst, 129), add(dst, V + 3)].concat(); + let mut yes = [add(dst, V + 3), cmp(6), branch("S_CBRANCH_SCC0", inner.len()), inner].concat(); + yes.extend(encode("S_ADD_U32", "ENC_SOP2", &[("SDST", 8), ("SSRC0", 8), ("SSRC1", 129)], None).unwrap()); + let no = [add(dst, src), add(dst, 130)].concat(); + program.extend(cmp(4 + (round / 2) % 2)); + program.extend(branch("S_CBRANCH_SCC0", yes.len() + 4)); + program.extend(yes); + program.extend(branch("S_BRANCH", no.len())); + program.extend(no); + } + program.extend(prog(&[("BUFFER_STORE_DWORDX2", "ENC_MUBUF", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 3), ("IDXEN", 1), ("SOFFSET", 128)], None)])); + let opt = on_gpu(Options::default()); + let folded = translate(&program, &opt).unwrap(); + let plain = super::translate_program(&program, &opt, false).unwrap(); + assert!(folded.complete() && plain.complete()); + assert!(folded.hlsl.contains("[noinline] void xcl_region_")); + assert!(!plain.hlsl.contains("void xcl_region_")); + let compile = |hlsl: &str| super::dxc::compile(hlsl, "main", "cs_6_6", &[]).unwrap(); + let (folded, plain) = (compile(&folded.hlsl), compile(&plain.hlsl)); + let mut state = KernelState::default(); + state.sgpr[5] = 1; + state.sgpr[12..16].copy_from_slice(&[64, 8 << 16, 52, 1 << 28]); + state.sgpr[126] = 0xEEEE_EEEE; + state.sgpr[127] = 0xB6DB_6DB6; + for (lane, regs) in state.vgpr.iter_mut().enumerate() { + regs[0] = lane as u32; + regs[2] = 1 + lane as u32; + regs[3] = 93 - lane as u32; + regs[10] = 3; + regs[11] = 12; + } + let mem = vec![0xABCDEF01; 160]; + for inner in [0, 1] { + state.sgpr[6] = inner; + let a = runner::run(&folded, &state, &mem).unwrap(); + let b = runner::run(&plain, &state, &mem).unwrap(); + assert_eq!(a.sgpr, b.sgpr); + assert_eq!(a.scc, b.scc); + assert_eq!(a.vgpr, b.vgpr); + assert_eq!(a.mem, b.mem); + assert_eq!(a.sgpr[8], 192); + assert_eq!(a.mem[18..20], a.vgpr[1][10..12]); + assert_ne!(a.mem[18..20], mem[18..20]); + assert_eq!(a.mem[120..], mem[120..]); + } +} + +#[test] +fn gpu_unaligned_typed_stores_write_all_components_and_keep_guard_bytes() { + if !gpu_ready() { + return; + } + let code = prog(&[ + ("TBUFFER_STORE_FORMAT_XYZW", "ENC_MTBUF", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1), ("OFFSET", 1), ("FORMAT", 77)], None), + ("TBUFFER_STORE_FORMAT_XYZW", "ENC_MTBUF", &[("VDATA", 14), ("VADDR", 0), ("SRSRC", 4), ("SOFFSET", 128), ("IDXEN", 1), ("OFFSET", 3), ("FORMAT", 71)], None), + ]); + let mut st = KernelState::default(); + st.sgpr[12..16].copy_from_slice(&[0x100, 24 << 16, 64, 1 << 28]); + st.sgpr[16..20].copy_from_slice(&[0x800, 16 << 16, 64, 1 << 28]); + for (lane, v) in st.vgpr.iter_mut().enumerate() { + v[0] = lane as u32; + for c in 0..4 { + v[10 + c] = f((lane * 4 + c + 1) as f32); + } + for (c, value) in [1.0, -2.0, 0.5, 4.0].into_iter().enumerate() { + v[14 + c] = f(value); + } + } + let result = runner::run_code(&code, &st, &vec![0xA5A5_A5A5; 1200]).unwrap(); + let byte = |at: usize| (result.mem[at / 4] >> (8 * (at & 3))) as u8; + for lane in 0..64 { + let base = 0x100 + 24 * lane; + let payload: Vec = (0..4).flat_map(|c| f((lane * 4 + c + 1) as f32).to_le_bytes()).collect(); + for k in 0..24 { + let expected = if (1..17).contains(&k) { payload[k - 1] } else { 0xA5 }; + assert_eq!(byte(base + k), expected, "32-bit format, lane {lane}, byte {k}"); + } + let base = 0x800 + 16 * lane; + let payload: Vec = [0x3C00u16, 0xC000, 0x3800, 0x4400].into_iter().flat_map(u16::to_le_bytes).collect(); + for k in 0..16 { + let expected = if (3..11).contains(&k) { payload[k - 3] } else { 0xA5 }; + assert_eq!(byte(base + k), expected, "16-bit format, lane {lane}, byte {k}"); + } + } +} + #[test] fn gpu_format_stores_atomics_global_lds() { if !gpu_ready() { @@ -2586,7 +2841,7 @@ fn gpu_format_stores_atomics_global_lds() { st.sgpr[2] = 0x500; // global base st.sgpr[12..16].copy_from_slice(&[0x100, 4 << 16, 64, (4 | 5 << 3 | 6 << 6 | 7 << 9) | 56 << 12]); st.sgpr[16..20].copy_from_slice(&[0x300, 2 << 16, 64, (4 | 5 << 3 | 6 << 6 | 7 << 9) | 13 << 12]); - st.sgpr[20..24].copy_from_slice(&[0x400, 0, 16, 0]); + st.sgpr[20..24].copy_from_slice(&[0x400, 0, 16, 3 << 28]); for (l, r) in st.vgpr.iter_mut().enumerate() { let l32 = l as u32; r[0] = l32; @@ -2953,6 +3208,107 @@ fn gpu_mesh_mode_two_passes() { assert!(px16 == px, "split pass-through draws the same pixels"); } +/// The mesh output budget with wide vertices: DXC accounts whole chunks of 32 vertices even +/// when fewer are declared, so 78 vertices with 22 float4 rows are accounted as 96 (33792 B > +/// 32768) and the record must go out in split groups. A retail title's NGG transform programs +/// have this shape (128 vertices / 128 primitives, 21 params + SV_ClipDistance0); the previous +/// budget (32768 / stride) emitted verts[78] and DXC refused every one of them. +#[test] +fn mesh_split_accounts_vertex_chunks() { + use super::emit::{mesh_passthrough, passthrough_elements, passthrough_split}; + use super::MsInterface; + if super::dxc::location().is_err() { + println!("no DXC – skipping"); + runner::skip_test("no DXC"); + return; + } + let sig = |name: &str, sv: u32, reg: u32, index: u32| crate::gpu::dxbc::SigElement { + name: name.into(), + index, + system_value: sv, + component_type: 3, + register: reg, + mask: 0xF, + rw_mask: 0xF, + stream: 0, + }; + let mut outputs = vec![sig("SV_Position", 1, 0, 0)]; + for k in 0..20u32 { + outputs.push(sig("TEXCOORD", 0, k + 1, k)); + } + outputs.push(sig("SV_ClipDistance", 2, 21, 0)); + let ms = MsInterface { outputs, threads: 128, max_vertices: 128, max_primitives: 128 }; + let elems = passthrough_elements(&ms, None); + assert_eq!(elems, 21); + // 22 rows * 16 B = 352 B/vertex: 64 accounted vertices fit (96 would be 33792 B), so at + // most 21 triangles' worth of copies per group, ceil(128/21) = 7 groups of 19 + let split = passthrough_split(&ms, elems); + assert_eq!(split, 7, "chunks of 32: 78 verts are accounted as 96 and refused"); + let pass = mesh_passthrough(&ms); + assert!(pass.contains("verts[57]"), "19 triangles per group:\n{pass}"); + super::dxc::compile(&pass, "main", "ms_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{pass}")); + // 20 rows * 16 B = 320 B/vertex: 96 accounted vertices fit (30720 B), but a whole record + // is 128 vertices (40960 B) – 4 groups of 32 triangles, 96 vertices each + let mut ms20 = ms.clone(); + ms20.outputs.pop(); + assert_eq!(passthrough_split(&ms20, passthrough_elements(&ms20, None)), 4); + let pass20 = mesh_passthrough(&ms20); + assert!(pass20.contains("verts[96]"), "96 vertices per group:\n{pass20}"); + super::dxc::compile(&pass20, "main", "ms_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{pass20}")); + // 8 rows * 16 B = 128 B/vertex: 128 vertices are 16384 B – the record stays whole + let mut ms8 = ms.clone(); + ms8.outputs.truncate(8); + assert_eq!(passthrough_split(&ms8, passthrough_elements(&ms8, None)), 1); + let pass8 = mesh_passthrough(&ms8); + assert!(pass8.contains("verts[128]"), "whole record:\n{pass8}"); + super::dxc::compile(&pass8, "main", "ms_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{pass8}")); +} + +/// The layout and the dispatch count are chosen separately: a record of 80 vertices with 22 +/// float4 rows does not fit the mesh output budget as a whole (DXC accounts 96 vertices: +/// 33792 B > 32768 B), but its single triangle's copies fit one compact group. The pass- +/// through must then declare the compact layout while `passthrough_split` returns 1, and DXC +/// accepts it (the whole-record declaration is refused). +#[test] +fn mesh_layout_independent_of_group_count() { + use super::emit::{mesh_passthrough, passthrough_elements, passthrough_split}; + use super::MsInterface; + if super::dxc::location().is_err() { + println!("no DXC – skipping"); + runner::skip_test("no DXC"); + return; + } + let sig = |name: &str, sv: u32, reg: u32, index: u32| crate::gpu::dxbc::SigElement { + name: name.into(), + index, + system_value: sv, + component_type: 3, + register: reg, + mask: 0xF, + rw_mask: 0xF, + stream: 0, + }; + let mut outputs = vec![sig("SV_Position", 1, 0, 0)]; + for k in 0..20u32 { + outputs.push(sig("TEXCOORD", 0, k + 1, k)); + } + outputs.push(sig("SV_ClipDistance", 2, 21, 0)); + // 22 rows * 16 B = 352 B/vertex: 64 accounted vertices fit; 80 declared do not + let ms = MsInterface { outputs, threads: 128, max_vertices: 80, max_primitives: 1 }; + let elems = passthrough_elements(&ms, None); + assert_eq!(elems, 21); + // one triangle: its 3 copies fit one compact group, so the dispatch count is 1 + assert_eq!(passthrough_split(&ms, elems), 1, "one triangle fits one compact group"); + let pass = mesh_passthrough(&ms); + assert!(pass.contains("verts[3]"), "the compact layout is chosen, not verts[80]:\n{pass}"); + super::dxc::compile(&pass, "main", "ms_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{pass}")); + // the whole-record form is what DXC refuses at this width: the same record declared whole + // (verts[80], accounted as 96: 33792 B) does not validate + let whole = pass.replace("verts[3]", "verts[80]"); + assert!(whole.contains("verts[80]"), "the whole-record declaration for the refusal check:\n{whole}"); + assert!(super::dxc::compile(&whole, "main", "ms_6_6", &[]).is_err(), "DXC refuses 96 accounted vertices of 352 B"); +} + /// DXC optimisation levels on a saved HLSL file (`XCL_TIME_HLSL=path`, profile in `XCL_TIME_PROFILE`). #[test] #[ignore] @@ -3314,6 +3670,65 @@ fn memory_windows_above_4_gib(heap: bool) { assert_eq!(*word(w0 + 0x6000), 0, "nothing in window 0 at the same low address"); } +#[test] +fn gpu_large_compute_shares_wave_and_window_helpers() { + if !gpu_ready() { + return; + } + let opt = Options { mem_windows: 2, split_wave64: runner::graphics_wave32(), ..Default::default() }; + let load = encode("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 2), ("ADDR", 0), ("SADDR", 0x7D)], None).unwrap(); + let add = encode("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 12), ("VSRC1", 2)], None).unwrap(); + let store = encode("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("DATA", 3), ("ADDR", 0), ("SADDR", 0x7D)], None).unwrap(); + let end = encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap(); + let small = translate(&[load.as_slice(), &end].concat(), &opt).unwrap(); + assert!(!small.hlsl.contains("[noinline]")); + + // Padding exercises the large-program path without making an expensive test shader. + let mut code = encode("S_NOP", "ENC_SOPP", &[], None).unwrap().repeat(1024); + let mut expected = std::array::from_fn::(|lane| lane as u32 + 1); + let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap(); + let mut state = KernelState::default(); + let vector_base = arena.window(1).0 + 0x8000; + state.sgpr[40..44].copy_from_slice(&[vector_base as u32, ((vector_base >> 32) as u32 & 0xFFFF) | (16 << 16), 64, 0]); + let address = |lane: usize| arena.window(lane % 2).0 + 4096 + 4 * lane; + for (lane, regs) in state.vgpr.iter_mut().enumerate() { + let addr = address(lane); + unsafe { *(addr as *mut u32) = expected[lane] }; + regs[0] = addr as u32; + regs[1] = (addr >> 32) as u32; + regs[8] = lane as u32; + for component in 0..4 { + unsafe { *((vector_base + 16 * lane + 4 * component) as *mut u32) = 10_000 + 10 * lane as u32 + component as u32 }; + } + } + for round in 0..32 { + let lane = if round % 2 == 0 { 37 } else { 4 }; + let selected = expected[lane]; + expected.iter_mut().for_each(|v| *v = v.wrapping_add(selected)); + code.extend_from_slice(&load); + code.extend(encode("V_READLANE_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", 128 + lane as u64)], None).unwrap()); + code.extend_from_slice(&add); + code.extend_from_slice(&store); + } + code.extend(encode("BUFFER_LOAD_DWORDX4", "ENC_MUBUF", &[("VDATA", 20), ("VADDR", 8), ("SRSRC", 10), ("SOFFSET", 128), ("IDXEN", 1)], None).unwrap()); + code.extend_from_slice(&end); + let t = translate(&code, &opt).unwrap(); + assert!(t.complete()); + assert!(t.hlsl.contains("[noinline] uint xcl_mLoad")); + assert!(t.hlsl.contains("[noinline] void xcl_loadx4_shared")); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let inline = super::dxc::compile(&t.hlsl.replace("[noinline] ", ""), "main", "cs_6_6", &[]).unwrap(); + assert!(dxil.len() < inline.len(), "outlined {} bytes, inline {}", dxil.len(), inline.len()); + let result = runner::run_in_arena(&dxil, &state, &arena).unwrap(); + for (lane, expected) in expected.into_iter().enumerate() { + assert_eq!(result.vgpr[lane][3], expected, "lane {lane}"); + assert_eq!(unsafe { *(address(lane) as *const u32) }, expected, "window {}, lane {lane}", lane % 2); + for component in 0..4 { + assert_eq!(result.vgpr[lane][20 + component], 10_000 + 10 * lane as u32 + component as u32, "vector lane {lane}, component {component}"); + } + } +} + /// Out-of-UMA addresses must NEVER alias onto live UMA windows via `& 3`: /// - high dwords outside `[base_hi, base_hi + mem_windows)` (such as `base_hi + 4` / `+ 5` / /// `base_hi - 1` / `0xFFFFFFFF` that share low bits with live windows) drop stores & atomics @@ -4603,7 +5018,7 @@ fn gpu_global_atomics_and_sub_dword_access() { code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); let mut st = KernelState::default(); st.sgpr[2] = 0x600; - st.sgpr[24..28].copy_from_slice(&[0x700, 0, 0x200, 0]); + st.sgpr[24..28].copy_from_slice(&[0x700, 0, 0x200, 3 << 28]); for (l, r) in st.vgpr.iter_mut().enumerate() { let l32 = l as u32; r[2] = 2 * l32; @@ -4819,8 +5234,8 @@ fn gpu_atomic_fcmpswap_x2() { let mut st = KernelState::default(); st.sgpr[2] = 0xA00; st.sgpr[3] = 0x1200; - st.sgpr[8..12].copy_from_slice(&[0x600, 0, 0x200, 0]); // V#: base, stride/flags, records, – - st.sgpr[12..16].copy_from_slice(&[0xC00, 0, 0x200, 0]); + st.sgpr[8..12].copy_from_slice(&[0x600, 0, 0x200, 3 << 28]); // V#: base, stride/flags, records, raw byte extent + st.sgpr[12..16].copy_from_slice(&[0xC00, 0, 0x200, 3 << 28]); const INIT: u64 = 0x3FF8_0000_0000_0000; // f64 bits of 1.5 const NEG_ZERO: u64 = 0x8000_0000_0000_0000; // -0.0: == +0.0 numerically, different bits let newv = |tag: u64, l: u64| tag << 48 | l; @@ -4914,7 +5329,7 @@ fn gpu_atomic_fmin_fmax_negative_zero() { code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); let mut st = KernelState::default(); st.sgpr[2] = 0x600; - st.sgpr[8..12].copy_from_slice(&[0x700, 0, 0x200, 0]); + st.sgpr[8..12].copy_from_slice(&[0x700, 0, 0x200, 3 << 28]); for r in st.vgpr.iter_mut() { r[30] = 0; r[32] = (-0.0f32).to_bits(); @@ -4970,7 +5385,7 @@ fn gpu_atomic_fmin_fmax_x2() { let mut st = KernelState::default(); st.sgpr[2] = 0xA00; st.sgpr[3] = 0xB00; - st.sgpr[8..12].copy_from_slice(&[0x800, 0, 0x100, 0]); + st.sgpr[8..12].copy_from_slice(&[0x800, 0, 0x100, 3 << 28]); let put = |r: &mut Vec, at: usize, v: u64| { r[at] = v as u32; r[at + 1] = (v >> 32) as u32; @@ -7187,7 +7602,7 @@ fn gpu_pknorm_i16_f32_nan_and_fmt_encode_snorm_ufloat() { return; } let ident = 4 | 5 << 3 | 6 << 6 | 7 << 9; - let vs = |base: u32, fmt: u32| [base, 0, 0x100, ident | fmt << 12]; + let vs = |base: u32, fmt: u32| [base, 0, 0x100, (3 << 28) | ident | fmt << 12]; // Formats: 43 = 11_11_10_FLOAT (X:10b, Y:11b, Z:11b), 36 = 10_11_11_FLOAT (X:11b, Y:11b, Z:10b), 24 = 16_16_SNORM let p = prog(&[ ("V_CVT_PKNORM_I16_F32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 0), ("SRC1", V + 0)], None), // (NaN, NaN)