diff --git a/crates/victory-shader/src/emit/halves_tests.rs b/crates/victory-shader/src/emit/halves_tests.rs index 73efefbed..7a37e91b8 100644 --- a/crates/victory-shader/src/emit/halves_tests.rs +++ b/crates/victory-shader/src/emit/halves_tests.rs @@ -1444,6 +1444,18 @@ fn lds_in_a_loop_in_halves_matches_the_console_on_every_gpu() { assert!(failed.is_empty(), "{}", failed.join("\n")); } +/// `v_permlane16_b32` or `v_permlanex16_b32` with the FI and BOUND_CTRL bits +/// (`op_sel` bits 0 and 1, word bits 11 and 12): lane `l` takes the value +/// of `v0` from its own row of 16 (or the other row of its half), the lane +/// its nibble of `s8` (lanes 0 to 7) or `s9` (lanes 8 to 15) names. +const fn permlane16(other_row: bool, fetch_inactive: bool, bound_ctrl: bool) -> [u32; 2] { + let opcode = if other_row { 0xD778_0001 } else { 0xD777_0001 }; + [ + opcode | (fetch_inactive as u32) << 11 | (bound_ctrl as u32) << 12, + 0x0024_1100, + ] +} + /// The selectors: every nibble of `s8` is odd and every one of `s9` is even. const PERM_LOW: u32 = 0x1357_9BDF; @@ -1452,182 +1464,506 @@ const PERM_HIGH: u32 = 0x2468_ACE0; /// What `v1` holds before an instruction that may leave it alone. const PERM_OLD: u32 = 0xAAAA; -/// A single result in v3, stored after the body restores EXEC. -fn literal_program(body: &[u32]) -> Vec { - [ - PROLOGUE.as_slice(), - &[0x3420_0085, 0x7E06_0280], // v16 = v0 * 32; v3 = 0 - body, - &store(3, 0), - &[S_ENDPGM], - ] - .concat() -} - -/// A nonempty mixed EXEC takes the direct edge to the join. Inactive -/// lanes remain inactive there. The first popcount forces a numeric mask -/// in the narrowed block, and the joined popcount supplies the result. -fn literal_mask_join(high_only: bool) -> Vec { - literal_program(&[ - 0x7D86_00A8, // v_cmp_le_u32 vcc, 40, v0 - 0xBE94_246A, // s_and_saveexec_b64 s[20:21], vcc - 0xBF88_0006, // s_cbranch_execz restore - 0xBE8C_107E, // s_bcnt1_i32_b64 s12, exec - 0xBF89_0001, // s_cbranch_execnz join - if high_only { 0xBEFF_0380 } else { 0xBEFE_04C1 }, // s_mov_b32 exec_hi, 0 or s_mov_b64 exec, -1 - 0xBE8D_107E, // join: s_bcnt1_i32_b64 s13, exec - 0x7E1A_020D, // v_mov_b32 v13, s13 - 0x4A06_1A0C, // v_add_nc_u32 v3, s12, v13 - 0xBEFE_0414, // restore: s_mov_b64 exec, s[20:21] - ]) -} +/// Keep arbitrary high bits in the same-row fixture's source data. +const PERM_PAYLOAD: u32 = 0xDEAD_BE00; -/// Both scalar lane reads happen under an EXEC mask with no low lanes. -fn literal_lane_reads(first: bool) -> Vec { - let read: &[u32] = if first { - &[0x7E14_0500] // v_readfirstlane_b32 s10, v0 - } else { - &[0xD760_000A, 0x0201_6500] // v_readlane_b32 s10, v0, 50 +/// Per workgroup lane: `v0` (its thread id, or a raw value made from the +/// workgroup and thread ids for the same-row form), permuted first with all +/// lanes active, then with only even lanes active and every FI/BOUND_CTRL +/// combination. The same-row form also checks full EXEC with BOUND_CTRL +/// set. Each masked or potentially out-of-bounds read starts with `v1` +/// holding [`PERM_OLD`]. EXEC is whole again for every store. +#[cfg(windows)] +fn permlane16_program(lanes: u32, other_row: bool) -> Vec { + let wave64 = lanes > 32; + let full = |w: &mut Vec| { + w.push(if wave64 { + 0xBEFE_04C1 // s_mov_b64 exec, -1 + } else { + 0xBEFE_03C1 // s_mov_b32 exec_lo, -1 + }); }; - let mut body = vec![ - 0x7D86_00A8, // v_cmp_le_u32 vcc, 40, v0 - 0xBE94_246A, // s_and_saveexec_b64 s[20:21], vcc - 0xBF88_0000 | (read.len() as u32 + 1), // s_cbranch_execz restore - ]; - body.extend(read); - body.extend([ - 0x7E06_020A, // v_mov_b32 v3, s10 - 0xBEFE_0414, // restore: s_mov_b64 exec, s[20:21] + let even = |w: &mut Vec| { + w.push(if wave64 { + 0xBEFE_040A // s_mov_b64 exec, s[10:11] + } else { + 0xBEFE_030A // s_mov_b32 exec_lo, s10 + }); + }; + let mut w = PROLOGUE.to_vec(); + if other_row { + w.push(0x3420_0085); // v_lshlrev_b32 v16, 5, v0 + } else { + w.extend([ + 0x8F02_8801, // s_lshl_b32 s2, s1 (group id X), 8 + 0x4A22_0002, // v_add_nc_u32 v17, s2, v0 + 0x3420_2285, // v_lshlrev_b32 v16, 5, v17 + 0x3A00_22FF, + PERM_PAYLOAD, // v_xor_b32 v0, PERM_PAYLOAD, v17 + ]); + } + w.extend([ + 0xBE88_03FF, + PERM_LOW, // s_mov_b32 s8, PERM_LOW + 0xBE89_03FF, + PERM_HIGH, // s_mov_b32 s9, PERM_HIGH + 0xBE8A_03FF, + 0x5555_5555, // s_mov_b32 s10, 0x55555555 + 0xBE8B_03FF, + 0x5555_5555, // s_mov_b32 s11, 0x55555555 ]); - // The first-lane case also names the console lanes. - body.extend([0xD765_0001, 0x0001_00C1]); // v_mbcnt_lo_u32_b32 v1, -1, 0 - literal_program(&body) + if !other_row { + w.extend([0x7E02_02FF, PERM_OLD]); // v_mov_b32 v1, PERM_OLD + } + w.extend(permlane16(other_row, false, false)); + w.extend(store(1, 0)); + for (slot, (fi, bc)) in [(false, false), (false, true), (true, false), (true, true)] + .into_iter() + .enumerate() + { + w.extend([0x7E02_02FF, PERM_OLD]); // v_mov_b32 v1, PERM_OLD + even(&mut w); + w.extend(permlane16(other_row, fi, bc)); + full(&mut w); + w.extend(store(1, 4 * (slot as u32 + 1))); + } + if !other_row { + w.extend([0x7E02_02FF, PERM_OLD]); // v_mov_b32 v1, PERM_OLD + w.extend(permlane16(false, false, true)); + w.extend(store(1, 20)); + } + w.push(S_ENDPGM); + w } -/// Separate writes select the upper half before reading its first lane. -fn literal_exec_dwords() -> Vec { - literal_program(&[ - 0xBE94_047E, // s_mov_b64 s[20:21], exec - 0xBEFE_0380, // s_mov_b32 exec_lo, 0 - 0xBEFF_03C1, // s_mov_b32 exec_hi, -1 - 0xBF88_0002, // s_cbranch_execz restore - 0x7E14_0500, // v_readfirstlane_b32 s10, v0 - 0x7E06_020A, // v_mov_b32 v3, s10 - 0xBEFE_0414, // restore: s_mov_b64 exec, s[20:21] - ]) +/// What the console gives [`permlane16_program`]'s lane `l`. An FI read +/// from a lane that was never launched has no documented input value. +fn permlane16_console(l: u32, group: u32, threads: u32, other_row: bool) -> [Option; 6] { + let in_row = l % 16; + let selectors = if in_row >= 8 { PERM_HIGH } else { PERM_LOW }; + let row = if other_row { (l / 16) ^ 1 } else { l / 16 }; + let source = row * 16 + ((selectors >> (4 * (in_row % 8))) & 15); + let value = if other_row { + source + } else { + (256 * group + source) ^ PERM_PAYLOAD + }; + let active = |lane: u32| lane.is_multiple_of(2); + let result = |masked: bool, fi: bool, bc: bool| { + if masked && !active(l) { + Some(PERM_OLD) + } else if fi { + (source < threads).then_some(value) + } else if source < threads && (!masked || active(source)) { + Some(value) + } else if bc { + Some(0) + } else { + Some(PERM_OLD) + } + }; + [ + result(false, false, false), + result(true, false, false), + result(true, false, true), + result(true, true, false), + result(true, true, true), + result(false, false, true), + ] } -/// Lane 40 is inactive when the scalar write targets it. -fn literal_lane_write() -> Vec { - literal_program(&[ - 0x7D88_0094, // v_cmp_gt_u32 vcc, 20, v0 - 0xBE94_246A, // s_and_saveexec_b64 s[20:21], vcc - 0xBF88_0005, // s_cbranch_execz restore - 0xD761_0003, - 0x0001_50B7, // v_writelane_b32 v3, 55, 40 - 0xD760_000A, - 0x0201_5103, // v_readlane_b32 s10, v3, 40 - 0x7E06_020A, // v_mov_b32 v3, s10 - 0xBEFE_0414, // restore: s_mov_b64 exec, s[20:21] - ]) +/// The hand-encoded words are the instructions their comments name. +#[test] +fn the_permlane16_programs_are_what_their_comments_say() { + for (words, opcode) in [ + (permlane16(true, false, false), "v_permlanex16_b32"), + (permlane16(true, true, true), "v_permlanex16_b32"), + (permlane16(false, false, false), "v_permlane16_b32"), + (permlane16(false, true, true), "v_permlane16_b32"), + ] { + let p = ir::build( + &[words[0], words[1], S_ENDPGM] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect::>(), + false, + 32, + ) + .expect("ir::build"); + assert_eq!(p.blocks[0].insts[0].name(), opcode); + } } -/// Lanes leave independently as their counter reaches zero. SCC is set -/// only when every bit of EXEC compares equal to zero. -fn literal_mask_loop(mask_eq: bool) -> Vec { - let mut body = vec![ - 0x3602_0083, // v_and_b32 v1, 3, v0 - 0xBE98_047E, // s_mov_b64 s[24:25], exec - 0x7D82_0280, // v_cmp_lt_u32 vcc, 0, v1 - 0x87FE_6A7E, // s_and_b64 exec, exec, vcc - 0xBF88_0008, // s_cbranch_execz done - 0xD760_000A, - 0x0201_0F00, // top: v_readlane_b32 s10, v0, 7 - 0x4A06_060A, // v_add_nc_u32 v3, s10, v3 - 0x4E02_0281, // v_subrev_nc_u32 v1, 1, v1 - 0x7D82_0280, // v_cmp_lt_u32 vcc, 0, v1 - 0x87FE_6A7E, // s_and_b64 exec, exec, vcc - 0xBF12_807E, // s_cmp_eq_u64 exec, 0 - 0xBF84_FFF8, // s_cbranch_scc0 top - 0xBEFE_0418, // done: s_mov_b64 exec, s[24:25] - ]; - if !mask_eq { - body.remove(11); - body[4] = 0xBF88_0007; // s_cbranch_execz done - body[11] = 0xBF89_FFF9; // s_cbranch_execnz top +/// The lanes of each row read the other row of their 32-lane half through +/// their selector nibbles, and an inactive source lane gives the old value, +/// zero or its register as FI and BOUND_CTRL say, on every hardware +/// adapter, in console waves of 32 and of 64 (in halves and whole). +#[test] +#[cfg(windows)] +fn permlanex16_picks_lanes_as_the_console_does_on_every_gpu() { + let mut failed = Vec::new(); + for lanes in [32, 64] { + let want: Vec = (0..lanes) + .flat_map(|l| { + permlane16_console(l, 0, lanes, true) + .into_iter() + .take(5) + .map(|value| value.expect("full cross-row fixtures")) + }) + .collect(); + failed.extend(differences_in( + lanes == 64, + &permlane16_program(lanes, true), + lanes, + 5, + &want, + 0, + false, + false, + )); } - literal_program(&body) + assert!(failed.is_empty(), "{}", failed.join("\n")); } -/// Repeated swizzles keep the first lane number of each half. -fn literal_swizzles() -> Vec { - let mut body = vec![V_MOV_V3_V0]; - for _ in 0..12 { - body.extend([ - 0xD8D4_80B1, - 0x0300_0003, // ds_swizzle_b32 v3, v3 quad_perm:[1,0,3,2] - S_WAITCNT_LGKM, - 0xD8D4_0020, - 0x0300_0003, // ds_swizzle_b32 v3, v3 broadcast lane 1 of each half - S_WAITCNT_LGKM, - ]); +/// Lane 0 selects an odd lane (nibble 15) and lane 8 selects an even lane +/// (nibble 0). Lane 32 stays in the same half for either row choice. +#[test] +fn the_permlane16_model_follows_the_instructions() { + assert_eq!( + permlane16_console(0, 0, 64, true), + [31, PERM_OLD, 0, 31, 31, 31].map(Some) + ); + assert_eq!(permlane16_console(8, 0, 64, true), [Some(16); 6]); + assert_eq!( + permlane16_console(1, 0, 64, true), + [29, PERM_OLD, PERM_OLD, PERM_OLD, PERM_OLD, 29].map(Some) + ); + assert_eq!(permlane16_console(16, 0, 64, true)[0], Some(15)); + assert_eq!(permlane16_console(32, 0, 64, true)[0], Some(63)); + assert_eq!(permlane16_console(48, 0, 64, true)[0], Some(47)); + assert_eq!( + permlane16_console(0, 0, 64, false), + [ + 0xDEAD_BE0F, + PERM_OLD, + 0, + 0xDEAD_BE0F, + 0xDEAD_BE0F, + 0xDEAD_BE0F + ] + .map(Some) + ); + assert_eq!(permlane16_console(8, 0, 64, false), [Some(PERM_PAYLOAD); 6]); + assert_eq!(permlane16_console(32, 1, 64, false)[0], Some(0xDEAD_BF2F)); + assert_eq!( + permlane16_console(64, 0, 79, false), + [Some(PERM_OLD), Some(PERM_OLD), Some(0), None, None, Some(0)] + ); +} + +fn same_row_permlane16_native(threads: u32) -> NativeProgram { + let words = permlane16_program(threads, false); + let mut n = native(&words, threads > 32, threads, 0); + let StageIo::Cs(cs) = &mut n.io else { + unreachable!() + }; + cs.rsrc2 |= 1 << 7; // group id X in s1, after the user-data SGPR + n +} + +#[test] +fn same_row_permlane16_uses_host_lanes_without_an_exchange() { + let n = same_row_permlane16_native(64); + let l = super::with_thread_ticket(false, || lowered(&n, true)) + .expect("a live same-row permute lowers in wave64 halves"); + assert_eq!(l.wave_size, Some(32)); + assert!(l.uses_lane_index); + assert_eq!(l.barriers, 0); +} + +/// The last 16-lane row is complete at 80 and 112 threads. At 79 threads +/// some selectors name the missing lane. Check both BOUND_CTRL outcomes +/// for those reads with FI clear. +#[test] +#[cfg(windows)] +fn same_row_permlane16_matches_the_console_on_hardware() { + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let hosts = Host::each_hardware(); + if hosts.is_empty() { + eprintln!("no SM 6.6 hardware device; skipped same-row permlane16"); + return; } - body.extend([ - 0x7D86_00A8, // v_cmp_le_u32 vcc, 40, v0 - 0xBE94_246A, // s_and_saveexec_b64 s[20:21], vcc - 0xBF88_0003, // s_cbranch_execz restore - 0xD760_000A, - 0x0201_6503, // v_readlane_b32 s10, v3, 50 - 0x7E06_020A, // v_mov_b32 v3, s10 - 0xBEFE_0414, // restore: s_mov_b64 exec, s[20:21] - ]); - literal_program(&body) + let workgroups = 3; + let mut completed = 0; + let mut checked_lanes = 0; + let mut checked_dwords = 0; + for (adapter, host) in &hosts { + for threads in [32, 64, 79, 80, 96, 112, 128, 256] { + let n = same_row_permlane16_native(threads); + let bytes = crate::dxbc::build(&[]); + let container = crate::dxbc::Container::parse(&bytes).expect("empty test container"); + let (p, st) = + crate::range::build(&n.patched_code(), n.wave64, n.vgprs).expect("range::build"); + let st = st.expect("structure"); + let res = resource::track(&p, &n.layout, n.stage, Some(&st)).expect("track"); + let io = io::raise(&p, &n).expect("io::raise"); + let shader = super::emit_with( + &container, + &n, + &p, + &st, + &io, + &res, + super::Options { + host_wave32: true, + narrow_waves: true, + ..Default::default() + }, + ) + .expect("production translation of same-row permlane16"); + let label = format!("{adapter}: {threads} threads"); + if let Ok(mut v) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { + v.validate(&mut shader.dxil.clone()) + .unwrap_or_else(|e| panic!("{label}: DXIL validation: {e}")); + } + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{label}: pipeline creation: {e}")); + let ud = vec![0; shader.user_data_dwords().max(1) as usize]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &[0; 4], + stride: Stride::Structured(16), + }, + View::RawUav(workgroups * 256 * 8), + ], + samplers: &[], + groups: [workgroups, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!(out.len(), 1, "{label}: readback UAV count"); + assert_eq!( + out[0].len(), + (workgroups * 256 * 8) as usize, + "{label}: readback length" + ); + for group in 0..workgroups { + for lane in 0..threads { + let offset = ((group * 256 + lane) * 8) as usize; + for (slot, expected) in permlane16_console(lane, group, threads, false) + .into_iter() + .enumerate() + { + if let Some(expected) = expected { + assert_eq!( + out[0][offset + slot], + expected, + "{label}: workgroup {group}, lane {lane}, slot {slot}" + ); + checked_dwords += 1; + } + } + } + } + completed += 1; + checked_lanes += threads * workgroups; + eprintln!("{label}: pipeline created, {workgroups} workgroups completed and checked"); + } + } + assert!(completed > 0 && checked_lanes > 0 && checked_dwords > 0); + eprintln!( + "same-row permlane16: {completed} hardware dispatches, {checked_lanes} lanes and {checked_dwords} defined dwords checked" + ); } -/// Active lanes in both halves write under EXEC and then read their peers. -fn literal_lds() -> Vec { +/// A single result in v3, stored after the body restores EXEC. +fn literal_program(body: &[u32]) -> Vec { + [ + PROLOGUE.as_slice(), + &[0x3420_0085, 0x7E06_0280], // v16 = v0 * 32; v3 = 0 + body, + &store(3, 0), + &[S_ENDPGM], + ] + .concat() +} + +/// A nonempty mixed EXEC takes the direct edge to the join. Inactive +/// lanes remain inactive there. The first popcount forces a numeric mask +/// in the narrowed block, and the joined popcount supplies the result. +fn literal_mask_join(high_only: bool) -> Vec { literal_program(&[ - 0x3404_0082, // v_lshlrev_b32 v2, 2, v0 - 0x3A08_00A0, // v_xor_b32 v4, 32, v0 - 0x3408_0882, // v_lshlrev_b32 v4, 2, v4 - 0x3602_009F, // v_and_b32 v1, 31, v0 - 0x7D86_0290, // v_cmp_le_u32 vcc, 16, v1 - 0xBE94_246A, // s_and_saveexec_b64 s[20:21], vcc - 0xBF88_0006, // s_cbranch_execz restore - 0xD834_0000, - 0x0000_0002, // ds_write_b32 v2, v0 - S_WAITCNT_LGKM, - 0xD8D8_0000, - 0x0300_0004, // ds_read_b32 v3, v4 - S_WAITCNT_LGKM, - 0xBEFE_0414, // restore: s_mov_b64 exec, s[20:21] + 0x7D86_00A8, // v_cmp_le_u32 vcc, 40, v0 + 0xBE94_246A, // s_and_saveexec_b64 s[20:21], vcc + 0xBF88_0006, // s_cbranch_execz restore + 0xBE8C_107E, // s_bcnt1_i32_b64 s12, exec + 0xBF89_0001, // s_cbranch_execnz join + if high_only { 0xBEFF_0380 } else { 0xBEFE_04C1 }, // s_mov_b32 exec_hi, 0 or s_mov_b64 exec, -1 + 0xBE8D_107E, // join: s_bcnt1_i32_b64 s13, exec + 0x7E1A_020D, // v_mov_b32 v13, s13 + 0x4A06_1A0C, // v_add_nc_u32 v3, s12, v13 + 0xBEFE_0414, // restore: s_mov_b64 exec, s[20:21] ]) } -/// The compiler's whole-wave sum of lanes 20 through 63. -fn literal_sum() -> Vec { - let sum = reduction(V_ADD_F32, 0x80, 0x7E06_0D00); - let steps = &sum[PROLOGUE.len() + 1..sum.len() - 3]; +/// Both scalar lane reads happen under an EXEC mask with no low lanes. +fn literal_lane_reads(first: bool) -> Vec { + let read: &[u32] = if first { + &[0x7E14_0500] // v_readfirstlane_b32 s10, v0 + } else { + &[0xD760_000A, 0x0201_6500] // v_readlane_b32 s10, v0, 50 + }; let mut body = vec![ - 0x7D86_0094, // v_cmp_le_u32 vcc, 20, v0 - 0xBE94_246A, // s_and_saveexec_b64 s[20:21], vcc - 0xBF88_0000 | (steps.len() as u32 + 1), // s_cbranch_execz restore + 0x7D86_00A8, // v_cmp_le_u32 vcc, 40, v0 + 0xBE94_246A, // s_and_saveexec_b64 s[20:21], vcc + 0xBF88_0000 | (read.len() as u32 + 1), // s_cbranch_execz restore ]; - body.extend(steps); + body.extend(read); body.extend([ - 0x7E06_0301, // v_mov_b32 v3, v1 + 0x7E06_020A, // v_mov_b32 v3, s10 0xBEFE_0414, // restore: s_mov_b64 exec, s[20:21] ]); + // The first-lane case also names the console lanes. + body.extend([0xD765_0001, 0x0001_00C1]); // v_mbcnt_lo_u32_b32 v1, -1, 0 literal_program(&body) } -/// Lane 0 adds 2048 to 1 twice, rounding each addition to 2048 in f16. -fn literal_half_sum() -> Vec { - let sum = reduction(0x32, 0x80, V_MOV_V3_V0); - let mut body = vec![ - 0x7D86_0083, // v_cmp_le_u32 vcc, 3, v0 +/// Separate writes select the upper half before reading its first lane. +fn literal_exec_dwords() -> Vec { + literal_program(&[ 0xBE94_047E, // s_mov_b64 s[20:21], exec - 0x8AFE_6A7E, // s_andn2_b64 exec, exec, vcc + 0xBEFE_0380, // s_mov_b32 exec_lo, 0 + 0xBEFF_03C1, // s_mov_b32 exec_hi, -1 + 0xBF88_0002, // s_cbranch_execz restore + 0x7E14_0500, // v_readfirstlane_b32 s10, v0 + 0x7E06_020A, // v_mov_b32 v3, s10 + 0xBEFE_0414, // restore: s_mov_b64 exec, s[20:21] + ]) +} + +/// Lane 40 is inactive when the scalar write targets it. +fn literal_lane_write() -> Vec { + literal_program(&[ + 0x7D88_0094, // v_cmp_gt_u32 vcc, 20, v0 + 0xBE94_246A, // s_and_saveexec_b64 s[20:21], vcc + 0xBF88_0005, // s_cbranch_execz restore + 0xD761_0003, + 0x0001_50B7, // v_writelane_b32 v3, 55, 40 + 0xD760_000A, + 0x0201_5103, // v_readlane_b32 s10, v3, 40 + 0x7E06_020A, // v_mov_b32 v3, s10 + 0xBEFE_0414, // restore: s_mov_b64 exec, s[20:21] + ]) +} + +/// Lanes leave independently as their counter reaches zero. SCC is set +/// only when every bit of EXEC compares equal to zero. +fn literal_mask_loop(mask_eq: bool) -> Vec { + let mut body = vec![ + 0x3602_0083, // v_and_b32 v1, 3, v0 + 0xBE98_047E, // s_mov_b64 s[24:25], exec + 0x7D82_0280, // v_cmp_lt_u32 vcc, 0, v1 + 0x87FE_6A7E, // s_and_b64 exec, exec, vcc + 0xBF88_0008, // s_cbranch_execz done + 0xD760_000A, + 0x0201_0F00, // top: v_readlane_b32 s10, v0, 7 + 0x4A06_060A, // v_add_nc_u32 v3, s10, v3 + 0x4E02_0281, // v_subrev_nc_u32 v1, 1, v1 + 0x7D82_0280, // v_cmp_lt_u32 vcc, 0, v1 + 0x87FE_6A7E, // s_and_b64 exec, exec, vcc + 0xBF12_807E, // s_cmp_eq_u64 exec, 0 + 0xBF84_FFF8, // s_cbranch_scc0 top + 0xBEFE_0418, // done: s_mov_b64 exec, s[24:25] + ]; + if !mask_eq { + body.remove(11); + body[4] = 0xBF88_0007; // s_cbranch_execz done + body[11] = 0xBF89_FFF9; // s_cbranch_execnz top + } + literal_program(&body) +} + +/// Repeated swizzles keep the first lane number of each half. +fn literal_swizzles() -> Vec { + let mut body = vec![V_MOV_V3_V0]; + for _ in 0..12 { + body.extend([ + 0xD8D4_80B1, + 0x0300_0003, // ds_swizzle_b32 v3, v3 quad_perm:[1,0,3,2] + S_WAITCNT_LGKM, + 0xD8D4_0020, + 0x0300_0003, // ds_swizzle_b32 v3, v3 broadcast lane 1 of each half + S_WAITCNT_LGKM, + ]); + } + body.extend([ + 0x7D86_00A8, // v_cmp_le_u32 vcc, 40, v0 + 0xBE94_246A, // s_and_saveexec_b64 s[20:21], vcc + 0xBF88_0003, // s_cbranch_execz restore + 0xD760_000A, + 0x0201_6503, // v_readlane_b32 s10, v3, 50 + 0x7E06_020A, // v_mov_b32 v3, s10 + 0xBEFE_0414, // restore: s_mov_b64 exec, s[20:21] + ]); + literal_program(&body) +} + +/// Active lanes in both halves write under EXEC and then read their peers. +fn literal_lds() -> Vec { + literal_program(&[ + 0x3404_0082, // v_lshlrev_b32 v2, 2, v0 + 0x3A08_00A0, // v_xor_b32 v4, 32, v0 + 0x3408_0882, // v_lshlrev_b32 v4, 2, v4 + 0x3602_009F, // v_and_b32 v1, 31, v0 + 0x7D86_0290, // v_cmp_le_u32 vcc, 16, v1 + 0xBE94_246A, // s_and_saveexec_b64 s[20:21], vcc + 0xBF88_0006, // s_cbranch_execz restore + 0xD834_0000, + 0x0000_0002, // ds_write_b32 v2, v0 + S_WAITCNT_LGKM, + 0xD8D8_0000, + 0x0300_0004, // ds_read_b32 v3, v4 + S_WAITCNT_LGKM, + 0xBEFE_0414, // restore: s_mov_b64 exec, s[20:21] + ]) +} + +/// The compiler's whole-wave sum of lanes 20 through 63. +fn literal_sum() -> Vec { + let sum = reduction(V_ADD_F32, 0x80, 0x7E06_0D00); + let steps = &sum[PROLOGUE.len() + 1..sum.len() - 3]; + let mut body = vec![ + 0x7D86_0094, // v_cmp_le_u32 vcc, 20, v0 + 0xBE94_246A, // s_and_saveexec_b64 s[20:21], vcc + 0xBF88_0000 | (steps.len() as u32 + 1), // s_cbranch_execz restore + ]; + body.extend(steps); + body.extend([ + 0x7E06_0301, // v_mov_b32 v3, v1 + 0xBEFE_0414, // restore: s_mov_b64 exec, s[20:21] + ]); + literal_program(&body) +} + +/// Lane 0 adds 2048 to 1 twice, rounding each addition to 2048 in f16. +fn literal_half_sum() -> Vec { + let sum = reduction(0x32, 0x80, V_MOV_V3_V0); + let mut body = vec![ + 0x7D86_0083, // v_cmp_le_u32 vcc, 3, v0 + 0xBE94_047E, // s_mov_b64 s[20:21], exec + 0x8AFE_6A7E, // s_andn2_b64 exec, exec, vcc 0xBF88_0000, // s_cbranch_execz restore 0x7E06_02FF, 0x0000_3C00, // v_mov_b32 v3, 1.0 in f16 @@ -1889,238 +2225,34 @@ fn literal_wave64_vcc_hi_offset_matches_the_console_on_every_gpu() { assert!(failed.is_empty(), "{}", failed.join("\n")); } -/// How a full-LDS program reaches its halves exchange. -#[derive(Clone, Copy, Debug)] -enum Exchanges { - /// One ballot read as data. - One, - /// Two back to back. - Two, - /// One in a loop of 3 trips, each adding 1 to the dwords the exchange - /// borrows (the first 1,024) first. - Loop, -} - -/// What the program adds to dwords 0..1023 before reading them back. -const fn full_lds_bump(e: Exchanges) -> u32 { - match e { - Exchanges::Loop => 3, - _ => 0, - } -} +/// VOP2 opcode for `v_add_f16`. +const V_ADD_F16: u32 = 0x32; -/// A 1,024-thread wave64 program that fills all 8,192 dwords of its LDS -/// (thread t writes dword `t + 1024k` = `t + 1024k + 0xA500_0000` for k -/// 0-7), passes a ballot between the halves (`e`), and reads all eight of -/// another wave's dwords back (thread t reads those of `(t + 32) % 1024`). -/// Per lane: the ballots' lane count, the OR of every difference from what -/// was written (0 when the LDS came back byte for byte), and its own dword -/// `t` as it is at the end. -fn full_lds_program(e: Exchanges) -> Vec { - const BASE: u32 = 0xA500_0000; - let bump = full_lds_bump(e); - let ds_write = |offset: u32| [0xD834_0000 | offset, 0x0000_0401]; // ds_write_b32 v1, v4 offset: - let ds_read = |offset: u32| [0xD8D8_0000 | offset, 0x0E00_000A]; // ds_read_b32 v14, v10 offset: - let mut w = PROLOGUE.to_vec(); - w.extend([ - 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 - 0x3402_0082, // v_lshlrev_b32 v1, 2, v0 - 0x4A04_00FF, - BASE, // v_add_nc_u32 v2, BASE, v0 - ]); - for k in 0..8u32 { - w.extend([0x4A08_04FF, 1024 * k]); // v_add_nc_u32 v4, 1024k, v2 - w.extend(ds_write(4096 * k)); - } - w.extend([ - S_WAITCNT_LGKM, - 0xBF8A_0000, // s_barrier - 0x360E_00BF, // v_and_b32 v7, 63, v0 - ]); - // Lanes 0-39 of each console wave: 40 a ballot. - let ballot = [ - 0x7D88_0EA8, // v_cmp_gt_u32 vcc, 40, v7 - 0xBE8C_106A, // s_bcnt1_i32_b64 s12, vcc - ]; - match e { - Exchanges::One => w.extend(ballot), - Exchanges::Two => { - w.extend(ballot); - w.extend([ - 0x7D88_0E94, // v_cmp_gt_u32 vcc, 20, v7 - 0xBE8D_106A, // s_bcnt1_i32_b64 s13, vcc - 0x800C_0D0C, // s_add_u32 s12, s12, s13 - ]); - } - Exchanges::Loop => { - w.extend([ - 0x7E12_0281, // v_mov_b32 v9, 1 - 0xBE94_0380, // s_mov_b32 s20, 0 - 0xBE8E_0380, // s_mov_b32 s14, 0 - ]); - let top = w.len(); - w.extend([0xD800_0000, 0x0000_0901]); // ds_add_u32 v1, v9 - w.extend(ballot); - w.extend([ - 0x800E_0C0E, // s_add_u32 s14, s14, s12 - 0x8014_8114, // s_add_u32 s20, s20, 1 - 0xBF0A_8314, // s_cmp_lt_u32 s20, 3 - ]); - let back = (top as i32 - (w.len() as i32 + 1)) as u16; - w.push(0xBF85_0000 | u32::from(back)); // s_cbranch_scc1 top - w.push(0xBE8C_030E); // s_mov_b32 s12, s14 - } - } +/// Appends the console compiler's whole-wave reduction of `v3` by VOP2 `op` +/// (identity inline constant `ident`), leaving the wave result in `s15`. +fn emit_reduction_body(w: &mut Vec, op: u32, ident: u32) { + let vop2 = |word: u32| word & !(0x3F << 25) | op << 25; w.extend([ - S_WAITCNT_LGKM, - 0xBF8A_0000, // s_barrier - 0x4A1A_00A0, // v_add_nc_u32 v13, 32, v0 - 0x361A_1AFF, - 0x0000_03FF, // v_and_b32 v13, 1023, v13 - 0x3414_1A82, // v_lshlrev_b32 v10, 2, v13 - 0x4A18_1AFF, - BASE, // v_add_nc_u32 v12, BASE, v13 - 0x7E16_0280, // v_mov_b32 v11, 0 + 0xBE8C_25C1, // s_or_saveexec_b64 s[12:13], -1 + 0xD501_0001, + 0x0032_0600 | ident, // v_cndmask_b32 v1, ident, v3, s[12:13] ]); - for k in 0..8u32 { - w.extend(ds_read(4096 * k)); + for control in [0x161, 0x162, 0x164, 0x168] { w.extend([ - S_WAITCNT_LGKM, - 0x4A1E_18FF, - 1024 * k + if k == 0 { bump } else { 0 }, // v_add_nc_u32 v15, what was written, v12 - 0x3A1C_1F0E, // v_xor_b32 v14, v14, v15 - 0x3816_1D0B, // v_or_b32 v11, v11, v14 + vop2(0x0602_02FA), + 0xFF00_0001 | control << 8, // op v1, v1, v1 row_xmask ]); } w.extend([ - 0xD8D8_0000, - 0x1100_0001, // ds_read_b32 v17, v1 - S_WAITCNT_LGKM, - 0x7E06_020C, // v_mov_b32 v3, s12 - ]); - w.extend(store(3, 0)); - w.extend(store(11, 4)); - w.extend(store(17, 8)); - w.push(S_ENDPGM); - w -} - -/// What each lane of [`full_lds_program`] stores. -fn full_lds_want(e: Exchanges) -> Vec { - let count = match e { - Exchanges::One => 40, - Exchanges::Two => 60, - Exchanges::Loop => 120, - }; - (0..1024u32) - .flat_map(|t| [count, 0, t + 0xA500_0000 + full_lds_bump(e)]) - .collect() -} - -/// The program's words are the instructions their comments name. -#[test] -fn the_full_lds_programs_are_what_their_comments_say() { - for e in [Exchanges::One, Exchanges::Two, Exchanges::Loop] { - let words = full_lds_program(e); - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let p = ir::build(&code, true, 256).unwrap(); - let insts: Vec<_> = p.blocks.iter().flat_map(|b| b.insts.iter()).collect(); - let count = |name: &str| insts.iter().filter(|i| i.name() == name).count(); - assert_eq!(count("ds_write_b32"), 8, "{e:?}"); - assert_eq!(count("ds_read_b32"), 9, "{e:?}"); - assert_eq!(count("s_barrier"), 2, "{e:?}"); - for name in [ - "v_lshlrev_b32", - "v_add_nc_u32", - "v_and_b32", - "v_xor_b32", - "v_or_b32", - "v_cmp_gt_u32", - "s_bcnt1_i32_b64", - "buffer_store_dword", - ] { - assert!(count(name) > 0, "{e:?}: no {name}"); - } - let offsets: Vec = insts - .iter() - .filter(|i| i.name() == "ds_write_b32") - .map(|i| match &i.fields { - gfx10::Fields::Ds { - offset0, offset1, .. - } => i32::from(*offset1) << 8 | i32::from(*offset0), - _ => -1, - }) - .collect(); - assert_eq!(offsets, (0..8).map(|k| 4096 * k).collect::>()); - if let Exchanges::Loop = e { - assert_eq!(count("ds_add_u32"), 1); - assert_eq!(count("s_cbranch_scc1"), 1); - assert!(p.blocks.len() >= 3); - } - } -} - -/// A program whose own LDS is the host's whole 32 KiB passes values between -/// its halves through dwords it borrows from that LDS. -#[test] -fn halves_exchange_in_a_program_that_fills_the_lds() { - for e in [Exchanges::One, Exchanges::Two, Exchanges::Loop] { - let words = full_lds_program(e); - let full = lowered_with(&native(&words, true, 1024, 32768), true, true) - .unwrap_or_else(|why| panic!("{e:?}: {why}")); - assert_eq!(full.wave_size, Some(32)); - } -} - -#[test] -#[cfg(windows)] -fn halves_give_back_borrowed_lds_on_every_gpu() { - let mut failed = Vec::new(); - for e in [Exchanges::One, Exchanges::Two, Exchanges::Loop] { - failed.extend( - differences_with( - &full_lds_program(e), - 1024, - 3, - &full_lds_want(e), - 32768, - true, - ) - .into_iter() - .map(|f| format!("{e:?}: {f}")), - ); - } - assert!(failed.is_empty(), "{}", failed.join("\n")); -} - -/// VOP2 opcode for `v_add_f16`. -const V_ADD_F16: u32 = 0x32; - -/// Appends the console compiler's whole-wave reduction of `v3` by VOP2 `op` -/// (identity inline constant `ident`), leaving the wave result in `s15`. -fn emit_reduction_body(w: &mut Vec, op: u32, ident: u32) { - let vop2 = |word: u32| word & !(0x3F << 25) | op << 25; - w.extend([ - 0xBE8C_25C1, // s_or_saveexec_b64 s[12:13], -1 - 0xD501_0001, - 0x0032_0600 | ident, // v_cndmask_b32 v1, ident, v3, s[12:13] - ]); - for control in [0x161, 0x162, 0x164, 0x168] { - w.extend([ - vop2(0x0602_02FA), - 0xFF00_0001 | control << 8, // op v1, v1, v1 row_xmask - ]); - } - w.extend([ - 0xD778_0002, - 0x0201_0101, // v_permlanex16_b32 v2, v1, 0, 0 - vop2(0x0602_0302), // op v1, v2, v1 - 0xD760_000E, - 0x0001_4101, // v_readlane_b32 s14, v1, 32 - vop2(0x0602_020E), // op v1, s14, v1 - 0xD760_000F, - 0x0001_0101, // v_readlane_b32 s15, v1, 0 - 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + 0xD778_0002, + 0x0201_0101, // v_permlanex16_b32 v2, v1, 0, 0 + vop2(0x0602_0302), // op v1, v2, v1 + 0xD760_000E, + 0x0001_4101, // v_readlane_b32 s14, v1, 32 + vop2(0x0602_020E), // op v1, s14, v1 + 0xD760_000F, + 0x0001_0101, // v_readlane_b32 s15, v1, 0 + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] ]); } @@ -3766,217 +3898,46 @@ fn thread_limit(l: &lower::Lowered) -> Option { l.user_data.iter().copied().find(|u| u.root == code) } -/// Which programs know a dispatch's count of threads: those of one -/// dimension, only when the translation asks for it; not literal halves. -/// Where no lane waits for another the lanes past the count leave at the -/// start; with a group barrier or in 32-lane halves that pass values they -/// stay, outside EXEC. The word is past the console's user data and names -/// the group's width. +/// A program whose only cross-half operations are first-lane reads goes to +/// halves for them (#522). Where halves cannot pass the read between them, +/// here in a loop counted to the console wave's first lane, it is refused, +/// with or without console lanes asked for as well: each 32-lane host wave +/// reading its own first lane would count the upper half's loop to thread +/// 32 and store 32 there, where the console stores 0 +/// ([`a_first_lane_read_in_a_loop_matches_the_console_on_every_gpu`]). #[test] -fn only_programs_whose_lanes_never_wait_leave_past_a_count_of_threads() { - let limited = |words: &[u32], wave64, threads, host_wave32| { - let n = native(words, wave64, threads, 0); - let l = lower_halves_limited(&n, host_wave32, true, true, true).expect("translates"); - thread_limit(&l) - }; - let plain = counted_lanes(&[]); - let word = limited(&plain, false, 64, true).expect("a word for the count"); - assert_eq!( - (word.index, word.dword), - (1, 64), - "past the one user-data SGPR" - ); - assert_eq!( - limited(&plain, true, 64, true).map(|u| u.dword), - Some(64), - "wave64 in 32-lane waves" - ); - let n = native(&plain, false, 64, 0); - assert_eq!( - thread_limit(&lower_halves(&n, true, true, false).unwrap()), - None, - "not asked for" - ); - assert_eq!( - limited(&plain, false, 1, true), - None, - "a group of one thread" - ); - let mut flat = native(&plain, false, 64, 0); - flat.io = StageIo::Cs(ComputeIo { - rsrc2: 1 << 1, - threads: [8, 8, 1], - }); - let l = lower_halves_limited(&flat, true, true, true, true).unwrap(); - assert_eq!(thread_limit(&l), None, "two dimensions"); - // s_barrier: lanes that left would never reach it. They stay, outside - // EXEC from the entry on. - assert!( - limited(&counted_lanes(&[0xBF8A_0000]), false, 64, true).is_some(), - "a group barrier" - ); - // v_mbcnt reads console lanes: a wave64 group of 64 runs in halves, - // which pass values between them at barriers (the lanes stay there - // too); one of 32 does not. - let lanes = counted_lanes(&[0xD765_0003, 0x0001_00C1]); - assert!(limited(&lanes, true, 64, true).is_some(), "in halves"); - assert!(limited(&lanes, true, 32, true).is_some(), "one host wave"); - assert!( - limited(&lanes, true, 64, false).is_some(), - "one host wave64" - ); - // A lane read across the halves, under a guard: in halves, the lanes - // stay. - let n = native(&literal_lane_reads(false), true, 64, 0); - let l = lower_halves_limited(&n, true, true, true, true).expect("in halves"); - assert!(thread_limit(&l).is_some(), "a lane read across the halves"); - // Literal halves take EXEC as the console wave's whole: no word there. - let n = native(&literal_exec_dwords(), true, 64, 0); - let l = lower_halves_limited(&n, true, true, true, true).expect("literal halves"); - assert_eq!(thread_limit(&l), None, "literal halves"); - let code: Vec = lanes.iter().flat_map(|w| w.to_le_bytes()).collect(); - let text: Vec = gfx10::decode(&code) - .unwrap() - .iter() - .map(|i| i.text(true)) - .collect(); - for want in [ - "v_mbcnt_lo_u32_b32 v3, -1, 0", - "v_lshlrev_b32 v1, 2, v0", - "v_mov_b32 v2, 1", - "buffer_atomic_add v2, v1, s[40:43], 0 offen", - ] { - assert!( - text.iter().any(|t| t.contains(want)), - "{want:?} not in {text:?}" - ); +fn first_lane_reads_halves_cannot_pass_are_refused() { + let words = first_lane_in_a_counted_loop(); + let with_mbcnt = in_a_loop(&[0x7E18_0500], 12, Count::FirstLane); + for threads in [64, 128, 256] { + for program in [&words, &with_mbcnt] { + let why = refusal(program, threads, 0); + assert!( + why.contains("a first-lane read of a value that may differ between 32-lane halves"), + "{threads} threads: {why}" + ); + } } - let code: Vec = [0xBF8A_0000u32, S_ENDPGM] - .iter() - .flat_map(|w| w.to_le_bytes()) - .collect(); - assert_eq!(gfx10::decode(&code).unwrap()[0].text(true), "s_barrier"); } -/// A dispatch counted in threads (`DispatchX`, after DexNom/VIctory -/// bc3cd4b0): of two groups of 64 only the lanes below the count run, in -/// wave32 and wave64 programs, and a count of 0 runs them all. Each lane -/// that runs adds 1 to the counter of its local x. On hardware devices -/// only, as the other halves tests that run programs. -#[cfg(windows)] -#[test] -fn the_lanes_past_a_count_of_threads_do_not_run() { - let _one = super::valu_tests::ONE_AT_A_TIME - .lock() - .unwrap_or_else(|e| e.into_inner()); - let hosts = Host::each_hardware(); - if hosts.is_empty() { - eprintln!("no SM 6.6 hardware device; skipped"); - return; - } - let views = [ - View::Texture(1, 1, &[[0.0; 4]]), - View::Buffer { - data: &[0; 4], - stride: Stride::Structured(16), - }, - View::RawUav(64), - ]; - // Plain (the lanes past the count leave at the start), with a group - // barrier, and reading console lanes (`v_mbcnt`: in halves where the - // host's waves are 32 lanes): in the last two the lanes stay, outside - // EXEC. - let extras: [(&str, &[u32]); 3] = [ - ("plain", &[]), - ("s_barrier", &[0xBF8A_0000]), - ("v_mbcnt", &[0xD765_0003, 0x0001_00C1]), - ]; - for (adapter, host) in &hosts { - let wave32 = host.wave32().unwrap_or(false); - for (wave64, (kind, extra)) in [false, true] - .into_iter() - .flat_map(|w| extras.iter().map(move |e| (w, *e))) - { - let n = native(&counted_lanes(extra), wave64, 64, 0); - let l = lower_halves_limited(&n, wave32, wave32, true, true).expect("translates"); - let limit = thread_limit(&l).expect("a word for the count"); - let shader = shader(l); - if let Ok(mut v) = - validator::Validator::load(validator::Validator::default_path().as_deref()) - { - v.validate(&mut shader.dxil.clone()) - .expect("DXIL validation failed"); - } - let label = format!("{adapter} (wave64 {wave64}, {kind})"); - let Ok((root, pso)) = host.compute_pipeline(&shader) else { - panic!("{label}: no pipeline"); - }; - for count in [0u32, 1, 7, 31, 32, 33, 63, 64, 65, 74, 127, 128] { - let mut ud = vec![0; shader.user_data_dwords() as usize]; - ud[limit.index as usize] = count; - let out = host - .dispatch( - &root, - &pso, - &Dispatch { - roots: vec![(0, Root::Constants(ud))], - views: &views, - samplers: &[], - groups: [2, 1, 1], - }, - ) - .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); - let runs = if count == 0 { 128 } else { count }; - let want: Vec = (0..64) - .map(|i| u32::from(i < runs) + u32::from(i + 64 < runs)) - .collect(); - assert_eq!(out[0], want, "{label}: count {count}"); - } - eprintln!("{label}: the lanes past every count stayed out"); - } - } -} - -/// A program whose only cross-half operations are first-lane reads goes to -/// halves for them (#522). Where halves cannot pass the read between them, -/// here in a loop counted to the console wave's first lane, it is refused, -/// with or without console lanes asked for as well: each 32-lane host wave -/// reading its own first lane would count the upper half's loop to thread -/// 32 and store 32 there, where the console stores 0 -/// ([`a_first_lane_read_in_a_loop_matches_the_console_on_every_gpu`]). -#[test] -fn first_lane_reads_halves_cannot_pass_are_refused() { - let words = first_lane_in_a_counted_loop(); - let with_mbcnt = in_a_loop(&[0x7E18_0500], 12, Count::FirstLane); - for threads in [64, 128, 256] { - for program in [&words, &with_mbcnt] { - let why = refusal(program, threads, 0); - assert!( - why.contains("a first-lane read of a value that may differ between 32-lane halves"), - "{threads} threads: {why}" - ); - } - } -} - -/// [`in_a_loop`] of `v_readfirstlane_b32 s12, v0` counted to the first -/// lane, without its `v_mbcnt`: a program whose only cross-half operations -/// are first-lane reads, one of them in a loop. -fn first_lane_in_a_counted_loop() -> Vec { - let mbcnt = [0xD765_0001, 0x0001_00C1]; // v_mbcnt_lo_u32_b32 v1, -1, 0 - let first = [0x7E18_0500]; // v_readfirstlane_b32 s12, v0 - let with_mbcnt = in_a_loop(&first, 12, Count::FirstLane); - let at = with_mbcnt - .windows(2) - .position(|w| w == mbcnt) - .expect("in_a_loop's v_mbcnt"); - [&with_mbcnt[..at], &with_mbcnt[at + 2..]].concat() -} - -/// A first-lane read the halves cannot pass between them is refused, never -/// made by each 32-lane host wave from its own first lane: on the console -/// every lane of a wave64 reads the wave's first lane, thread `l & !63`, -/// where the upper host wave's own first lane is thread `l & !31`. +/// [`in_a_loop`] of `v_readfirstlane_b32 s12, v0` counted to the first +/// lane, without its `v_mbcnt`: a program whose only cross-half operations +/// are first-lane reads, one of them in a loop. +fn first_lane_in_a_counted_loop() -> Vec { + let mbcnt = [0xD765_0001, 0x0001_00C1]; // v_mbcnt_lo_u32_b32 v1, -1, 0 + let first = [0x7E18_0500]; // v_readfirstlane_b32 s12, v0 + let with_mbcnt = in_a_loop(&first, 12, Count::FirstLane); + let at = with_mbcnt + .windows(2) + .position(|w| w == mbcnt) + .expect("in_a_loop's v_mbcnt"); + [&with_mbcnt[..at], &with_mbcnt[at + 2..]].concat() +} + +/// A first-lane read the halves cannot pass between them is refused, never +/// made by each 32-lane host wave from its own first lane: on the console +/// every lane of a wave64 reads the wave's first lane, thread `l & !63`, +/// where the upper host wave's own first lane is thread `l & !31`. #[cfg(windows)] #[test] fn a_first_lane_read_in_a_loop_matches_the_console_on_every_gpu() { @@ -4280,1225 +4241,1606 @@ fn a_first_lane_read_of_a_multiply_accumulate_matches_the_console_on_every_gpu() assert!(failed.is_empty(), "{}", failed.join("\n")); } -/// Two first-lane reads of values the same in every lane that makes them, -/// in an `s_and_saveexec_b64` region whose EXEC is `mask_words`'s: -/// `v4 = 42` then `v4 = 1.0 + v4` (1.0, read into `s12`) and `v5 = 1.0 + v4` -/// (2.0, read into `s13`). The lanes outside the region never make `v4` or -/// `v5`. Every lane stores `v2` and `v6`, which take the two reads after -/// EXEC is restored (every lane), or with `inside` in the region (its lanes -/// only, the others keeping 0: reads only the lanes that ran them see). -/// `with_mbcnt`: a `v_mbcnt` first, so the program runs in halves on a -/// 32-lane host whatever else it holds. -fn alike_reads_in_a_region(mask_words: &[u32], with_mbcnt: bool, inside: bool) -> Vec { +/// A `while` loop as the console compiler lays one out: the entry jumps to +/// the test, which branches back to the body while lanes stay; the body +/// falls into the test. The body reads the first lane's thread id +/// (`v_readfirstlane_b32 s6, v0`) into an accumulator `v2`, and counts its +/// passes in `v1`. `narrow`: a lane stays while `v1 < (tid & 7)`, and the +/// test drops the lanes done from EXEC (`s_and_b64 exec, exec, vcc; +/// s_cbranch_execnz`). Else every lane stays while `v1 < 7`, a test the +/// same in every lane, and EXEC stays (`s_and_b64 vcc, exec, vcc; +/// s_cbranch_vccnz`, as GTA VI's loops test). Every lane stores `v2`. +fn while_loop_first_lane(narrow: bool) -> Vec { let mut w = PROLOGUE.to_vec(); w.extend([ 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x7E02_0280, // v_mov_b32 v1, 0 0x7E04_0280, // v_mov_b32 v2, 0 - 0x7E0C_0280, // v_mov_b32 v6, 0 + if narrow { + 0x360A_0087 // v_and_b32 v5, 7, v0 + } else { + 0x7E0A_0287 // v_mov_b32 v5, 7 + }, + 0xBEA4_047E, // s_mov_b64 s[36:37], exec + 0xBF82_0003, // s_branch (the test) + 0x7E0C_0500, // v_readfirstlane_b32 s6, v0 + 0x4A04_0406, // v_add_nc_u32 v2, s6, v2 + 0x4A02_0281, // v_add_nc_u32 v1, 1, v1 + 0x7D82_0B01, // v_cmp_lt_u32 vcc, v1, v5 ]); - if with_mbcnt { + if narrow { w.extend([ - 0xD765_0001, - 0x0001_00C1, // v_mbcnt_lo_u32_b32 v1, -1, 0 + 0x87FE_6A7E, // s_and_b64 exec, exec, vcc + 0xBF89_FFFA, // s_cbranch_execnz (the body) + ]); + } else { + w.extend([ + 0x87EA_6A7E, // s_and_b64 vcc, exec, vcc + 0xBF87_FFFA, // s_cbranch_vccnz (the body) ]); } - w.extend(mask_words); - let moves = [ - 0x7E04_020C, // v_mov_b32 v2, s12 - 0x7E0C_020D, // v_mov_b32 v6, s13 - ]; - w.extend([ - 0xBE80_246A, // s_and_saveexec_b64 s[0:1], vcc - 0xBF88_0005 + 2 * u32::from(inside), // s_cbranch_execz (past the region) - 0x7E08_02AA, // v_mov_b32 v4, 42 - 0x0608_08F2, // v_add_f32 v4, 1.0, v4 - 0x7E18_0504, // v_readfirstlane_b32 s12, v4 - 0x060A_08F2, // v_add_f32 v5, 1.0, v4 - 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 - ]); - if inside { - w.extend(moves); - } - w.push(0xBEFE_0400); // s_mov_b64 exec, s[0:1] - if !inside { - w.extend(moves); - } + w.push(0xBEFE_0424); // s_mov_b64 exec, s[36:37] w.extend(store(2, 0)); - w.extend(store(6, 4)); w.push(S_ENDPGM); w } +/// What every lane of [`while_loop_first_lane`] stores on the console: the +/// first lane still in the loop in each pass is the console wave's thread +/// `64 * wave + pass + 1` (narrow), or its first, `64 * wave`, in all 7 +/// passes. +fn console_while_loop_first_lane(narrow: bool, t: u32) -> u32 { + let base = t & !63; + if narrow { + let n = t & 7; + n * base + n * (n + 1) / 2 + } else { + 7 * base + } +} + #[test] -fn the_alike_read_programs_are_what_their_comments_say() { - let words = alike_reads_in_a_region(&MASK_LANES_40_41, true, false); - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let all = gfx10::decode(&code) - .expect("decodes") +fn the_while_loop_programs_are_what_their_comments_say() { + for narrow in [false, true] { + let words = while_loop_first_lane(narrow); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let all = gfx10::decode(&code) + .expect("decodes") + .iter() + .map(|i| i.text(true)) + .collect::>() + .join("\n"); + let tail: &[&str] = if narrow { + &["s_and_b64 exec, exec, vcc", "s_cbranch_execnz"] + } else { + &["s_and_b64 vcc, exec, vcc", "s_cbranch_vccnz"] + }; + let bound = if narrow { + "v_and_b32 v5, 7, v0" + } else { + "v_mov_b32 v5, 7" + }; + for want in [ + bound, + "s_mov_b64 s[36:37], exec", + "s_branch", + "v_readfirstlane_b32 s6, v0", + "v_add_nc_u32 v2, s6, v2", + "v_add_nc_u32 v1, 1, v1", + "v_cmp_lt_u32 vcc, v1, v5", + "s_mov_b64 exec, s[36:37]", + ] .iter() - .map(|i| i.text(true)) - .collect::>() - .join("\n"); - for want in [ - "v_mov_b32 v6, 0", - "v_mbcnt_lo_u32_b32 v1, -1, 0", - "v_cmp_eq_u32 vcc, 20, v3", - "s_and_saveexec_b64 s[0:1], vcc", - "s_cbranch_execz", - "v_mov_b32 v4, 42", - "v_add_f32 v4, 1.0, v4", - "v_readfirstlane_b32 s12, v4", - "v_add_f32 v5, 1.0, v4", - "v_readfirstlane_b32 s13, v5", - "s_mov_b64 exec, s[0:1]", - "v_mov_b32 v2, s12", - "v_mov_b32 v6, s13", - ] { - assert!(all.contains(want), "{want:?} not in:\n{all}"); + .chain(tail) + { + assert!(all.contains(want), "{want:?} not in:\n{all}"); + } } } -/// Lanes 8 and 9 of every console wave (its lower half). -const MASK_WAVE_LANES_8_9: [u32; 2] = [ - 0x3606_00BE, // v_and_b32 v3, 62, v0 - 0x7D84_0688, // v_cmp_eq_u32 vcc, 8, v3 -]; - -/// Lanes 40 and 41 of every console wave (its upper half). -const MASK_WAVE_LANES_40_41: [u32; 2] = [ - 0x3606_00BE, // v_and_b32 v3, 62, v0 - 0x7D84_06A8, // v_cmp_eq_u32 vcc, 40, v3 -]; - -/// A first-lane read of a value the same in every lane that makes it reads -/// a lane that made it. The halves run such a region in every lane, under a -/// predicate: the host wave's first lane may be outside it and hold an old -/// value (the read took that one), and a half with no lane of the region -/// holds none at all (it takes the other half's). `inside`: only the -/// region's lanes see the reads, each half making them by itself -/// (`first_lane::read_alone`), from a lane of the region too. -#[cfg(windows)] +/// A first-lane read in a `while` loop (its exit test before the latch's +/// work, as GTA VI's `23d507cbb6a22e86` and `b0095eb50222e808` have) runs in +/// halves with the loop in lockstep: the group stays while any lane stays, +/// so the halves meet in every pass and pass the console wave's first lane +/// between them. Before, the read was refused there. #[test] -fn a_first_lane_read_of_an_alike_value_in_a_region_matches_the_console_on_every_gpu() { +fn a_first_lane_read_in_a_while_loop_translates_in_halves() { + for narrow in [false, true] { + for threads in [64, 128, 256] { + let words = while_loop_first_lane(narrow); + let l = lowered(&native(&words, true, threads, 0), true) + .unwrap_or_else(|e| panic!("narrow={narrow} {threads} threads: {e}")); + assert_eq!(l.wave_size, Some(32)); + assert!(l.barriers > 0, "the halves meet in the loop"); + } + } +} + +/// The read in a `while` loop gives the console's lanes on every GPU. +#[cfg(windows)] +#[test] +fn a_first_lane_read_in_a_while_loop_matches_the_console_on_every_gpu() { let mut failed = Vec::new(); - type InRegion = fn(u32) -> bool; - let masks: [(&str, &[u32; 2], InRegion); 3] = [ - ("lower_8_9", &MASK_WAVE_LANES_8_9, |t| t & 62 == 8), - ("upper_40_41", &MASK_WAVE_LANES_40_41, |t| t & 62 == 40), - ("both_12_44", &MASK_LANES_12_44, |t| t & 31 == 12), - ]; - for (label, mask, in_region) in masks { - for with_mbcnt in [false, true] { - for threads in [64, 128] { - for inside in [false, true] { - let words = alike_reads_in_a_region(mask, with_mbcnt, inside); - let want: Vec = (0..threads) - .flat_map(|t| { - if !inside || in_region(t) { - [1.0f32.to_bits(), 2.0f32.to_bits()] - } else { - [0, 0] - } - }) - .collect(); - let found = differences_with_buffer( - true, &words, threads, 2, &want, 0, false, false, &[0; 4], - ); - failed.extend(found.into_iter().map(|m| { - format!("{label}(mbcnt={with_mbcnt}, inside={inside}) {threads} threads: {m}") - })); - } - } + for narrow in [false, true] { + for threads in [64, 128] { + let words = while_loop_first_lane(narrow); + let want: Vec = (0..threads) + .map(|t| console_while_loop_first_lane(narrow, t)) + .collect(); + failed.extend( + differences(&words, threads, 1, &want) + .into_iter() + .map(|m| format!("narrow={narrow} {threads} threads: {m}")), + ); } } assert!(failed.is_empty(), "{}", failed.join("\n")); } -/// The masks are what their comments say. +/// [`while_loop_first_lane`] (the form lanes leave one by one: a lane stays +/// while `v1 < (tid & 7)`) with a store in its body: each pass a lane makes +/// stores its count of passes `v1` at dword `v1` of its own eight. A lane +/// that has left the loop stores no more. +fn while_loop_with_a_store() -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0x7E04_0280, // v_mov_b32 v2, 0 + 0x360A_0087, // v_and_b32 v5, 7, v0 + 0xBEA4_047E, // s_mov_b64 s[36:37], exec + 0xBF82_0007, // s_branch (the test) + 0x7E0C_0500, // v_readfirstlane_b32 s6, v0 + 0x4A04_0406, // v_add_nc_u32 v2, s6, v2 + 0x4A02_0281, // v_add_nc_u32 v1, 1, v1 + 0x3422_0282, // v_lshlrev_b32 v17, 2, v1 + 0x4A22_2310, // v_add_nc_u32 v17, v16, v17 + 0xE070_1000, + 0x800A_0111, // buffer_store_dword v1, v17, s[40:43], 0 offen + 0x7D82_0B01, // v_cmp_lt_u32 vcc, v1, v5 + 0x87FE_6A7E, // s_and_b64 exec, exec, vcc + 0xBF89_FFF6, // s_cbranch_execnz (the body) + 0xBEFE_0424, // s_mov_b64 exec, s[36:37] + ]); + w.extend(store(2, 0)); + w.push(S_ENDPGM); + w +} + #[test] -fn the_wave_lane_masks_are_what_their_comments_say() { - for (mask, want) in [ - (&MASK_WAVE_LANES_8_9, "v_cmp_eq_u32 vcc, 8, v3"), - (&MASK_WAVE_LANES_40_41, "v_cmp_eq_u32 vcc, 40, v3"), - ] { - let code: Vec = mask - .iter() - .chain(&[S_ENDPGM]) - .flat_map(|w| w.to_le_bytes()) +fn the_while_loop_with_a_store_is_what_its_comments_say() { + let words = while_loop_with_a_store(); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let text: Vec = gfx10::decode(&code) + .expect("decodes") + .iter() + .map(|i| i.text(true)) + .collect(); + let want = [ + "v_lshlrev_b32 v16, 5, v0", + "v_mov_b32 v1, 0", + "v_mov_b32 v2, 0", + "v_and_b32 v5, 7, v0", + "s_mov_b64 s[36:37], exec", + "s_branch", + "v_readfirstlane_b32 s6, v0", + "v_add_nc_u32 v2, s6, v2", + "v_add_nc_u32 v1, 1, v1", + "v_lshlrev_b32 v17, 2, v1", + "v_add_nc_u32 v17, v16, v17", + "buffer_store_dword v1, v17, s[40:43], 0 offen", + "v_cmp_lt_u32 vcc, v1, v5", + "s_and_b64 exec, exec, vcc", + "s_cbranch_execnz", + "s_mov_b64 exec, s[36:37]", + ]; + // The prologue's five words are four instructions. + for (n, want) in want.iter().enumerate() { + let got = &text[PROLOGUE.len() - 1 + n]; + assert!(got.starts_with(want), "{n}: {got:?}, not {want:?}"); + } +} + +/// A store in a `while` loop run in lockstep is made by the lanes still in +/// the loop only: a lane that left keeps running the body with the group, +/// inactive, and stores nothing. Each lane's dwords 1 to `tid & 7` hold +/// their own index, the rest stay 0; dword 0 is the accumulator of +/// [`console_while_loop_first_lane`]. +#[cfg(windows)] +#[test] +fn a_store_in_a_while_loop_is_made_by_the_lanes_still_in_it_on_every_gpu() { + let words = while_loop_with_a_store(); + let mut failed = Vec::new(); + for threads in [64, 128] { + let want: Vec = (0..threads) + .flat_map(|t| { + let n = t & 7; + let mut lane = [0; 8]; + lane[0] = console_while_loop_first_lane(true, t); + for p in 1..=n { + lane[p as usize] = p; + } + lane + }) .collect(); + failed.extend( + differences(&words, threads, 8, &want) + .into_iter() + .map(|m| format!("{threads} threads: {m}")), + ); + } + assert!(failed.is_empty(), "{}", failed.join("\n")); +} + +/// [`native`] for a group of two dimensions: thread ids x and y in `v0` and +/// `v1`, the group's x in `s1` (after the one user-data SGPR). +fn native_2d(words: &[u32], threads: [u32; 2]) -> NativeProgram { + let mut n = native(words, true, threads[0] * threads[1], 0); + n.io = StageIo::Cs(ComputeIo { + // One user-data SGPR, the group's x (bit 7), thread ids x and y + // (bits 11-12: 1). + rsrc2: 1 << 1 | 1 << 7 | 1 << 11, + threads: [threads[0], threads[1], 1], + }); + n +} + +/// [`while_loop_with_a_store`] in a group `width` threads wide (8 or 16), of +/// several rows, in a dispatch of several groups: the thread's flat id +/// `width y + x` is in `v0`, and a lane stays while +/// `v1 < ((flat + group) & 7)`, so the lanes leave at passes that differ +/// from group to group. Each lane has 16 dwords at +/// `(256 group + flat) * 64`: the accumulator of first lanes, its passes +/// at dwords 1 to 7, `flat + 1` added (atomically, so a thread id two +/// host lanes hold shows) at dword 8, and its count of passes at dword 9. `forever`: no lane ever leaves (the +/// loop then runs to the translation's limit of passes), and no pass stores. +fn while_loop_in_rows(forever: bool, width: u32) -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3406_0280 | width.trailing_zeros(), // v_lshlrev_b32 v3, 3 or 4, v1 + 0x4A00_0700, // v_add_nc_u32 v0, v0, v3 + 0x3420_0086, // v_lshlrev_b32 v16, 6, v0 + 0x7E08_0201, // v_mov_b32 v4, s1 + 0x3408_088E, // v_lshlrev_b32 v4, 14, v4 + 0x4A20_0910, // v_add_nc_u32 v16, v16, v4 + 0x4A0C_0001, // v_add_nc_u32 v6, s1, v0 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0x7E04_0280, // v_mov_b32 v2, 0 + if forever { + 0x7E0A_02C1 // v_mov_b32 v5, -1 + } else { + 0x360A_0C87 // v_and_b32 v5, 7, v6 + }, + 0xBEA4_047E, // s_mov_b64 s[36:37], exec + ]); + if forever { + w.extend([ + 0xBF82_0003, // s_branch (the test) + 0x7E0C_0500, // v_readfirstlane_b32 s6, v0 + 0x4A04_0406, // v_add_nc_u32 v2, s6, v2 + 0x4A02_0281, // v_add_nc_u32 v1, 1, v1 + 0x7D82_0B01, // v_cmp_lt_u32 vcc, v1, v5 + 0x87FE_6A7E, // s_and_b64 exec, exec, vcc + 0xBF89_FFFA, // s_cbranch_execnz (the body) + ]); + } else { + w.extend([ + 0xBF82_0007, // s_branch (the test) + 0x7E0C_0500, // v_readfirstlane_b32 s6, v0 + 0x4A04_0406, // v_add_nc_u32 v2, s6, v2 + 0x4A02_0281, // v_add_nc_u32 v1, 1, v1 + 0x3422_0282, // v_lshlrev_b32 v17, 2, v1 + 0x4A22_2310, // v_add_nc_u32 v17, v16, v17 + 0xE070_1000, + 0x800A_0111, // buffer_store_dword v1, v17, s[40:43], 0 offen + 0x7D82_0B01, // v_cmp_lt_u32 vcc, v1, v5 + 0x87FE_6A7E, // s_and_b64 exec, exec, vcc + 0xBF89_FFF6, // s_cbranch_execnz (the body) + ]); + } + w.extend([ + 0xBEFE_0424, // s_mov_b64 exec, s[36:37] + 0x4A0E_0081, // v_add_nc_u32 v7, 1, v0 + 0xE0C8_1020, + 0x800A_0710, // buffer_atomic_add v7, v16, s[40:43], 0 offen offset:32 + ]); + w.extend(store(1, 36)); + w.extend(store(2, 0)); + w.push(S_ENDPGM); + w +} + +#[test] +fn the_while_loop_in_rows_is_what_its_comments_say() { + for (forever, width) in [(false, 8), (true, 8), (false, 16)] { + let words = while_loop_in_rows(forever, width); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let text: Vec = gfx10::decode(&code) .expect("decodes") .iter() .map(|i| i.text(true)) .collect(); - assert_eq!(text[..2], ["v_and_b32 v3, 62, v0", want]); - } -} - -/// The hand-encoded words are the instructions their comments name. -#[test] -fn the_test_programs_are_what_their_comments_say() { - let programs: Vec<(Vec, &[&str])> = vec![ - ( - in_halves(), - &[ - "v_mbcnt_lo_u32_b32 v1, -1, 0", - "v_mbcnt_hi_u32_b32 v1, -1, v1", - "ds_swizzle_b32 v2, v0", - "v_xor_b32 v4, 9, v0", - "ds_bpermute_b32 v3, v4, v0", - "v_writelane_b32 v5, s8, 40", - "v_cndmask_b32 v6, 0, 1, s[20:21]", - "v_mov_b32 v7, v0 quad_perm:[1,0,3,2]", - "buffer_store_dword v7, v16, s[40:43], 0 offen offset:24", - ], - ), - ( - sum_after_a_loop_lanes_leave(), - &[ - "v_and_b32 v5, 3, v0", - "v_mov_b32 v6, 0", - "s_mov_b64 s[4:5], exec", - "v_cmp_lt_u32 vcc, v6, v5", - "s_and_b64 exec, exec, vcc", - "s_cbranch_execz", - "v_add_nc_u32 v6, 1, v6", - "s_branch", - "s_mov_b64 exec, s[4:5]", - "v_cvt_f32_u32 v3, v6", - ], - ), - ( - loops_sharing_a_latch(), - &[ - "s_add_u32 s22, s22, 1", - "s_cmp_lt_u32 s22, 3", - "s_add_u32 s20, s20, 1", - "s_cmp_gt_u32 s20, 2", - "s_mov_b32 s22, 0", - "s_add_u32 s21, s21, 1", - "v_mov_b32 v1, s21", - ], - ), - ( - dpp_row_mask(), - &[ - "v_mov_b32 v7, -1", - "v_mov_b32 v7, v0 quad_perm:[1,0,3,2] row_mask:0xc", - "buffer_store_dword v7, v16, s[40:43], 0 offen", - ], - ), - ( - first_lane_of_the_thread_id(), - &[ - "v_mbcnt_lo_u32_b32 v1, -1, 0", - "v_readfirstlane_b32 s12, v0", - "v_mov_b32 v2, s12", - ], - ), - ( - first_lane_of_a_buffer_load(3), - &[ - "s_load_dwordx4 s[44:47], s[4:5], 0x000020", - "v_mov_b32 v3, 4", - "buffer_load_dword v4, v3, s[44:47], 0 offen", - "s_waitcnt vmcnt(0)", - "v_readfirstlane_b32 s12, v4", - "v_mov_b32 v5, s12", - ], - ), - ( - first_lane_alike(), - &[ - "v_lshrrev_b32 v2, 6, v0", - "v_readfirstlane_b32 s12, v2", - "v_mov_b32 v3, s12", - "buffer_store_dword v1, v16, s[40:43], 0 offen offset:4", - ], - ), - ( - first_active_lane(), - &["s_ff1_i32_b64 s12, exec", "v_mov_b32 v1, s12"], - ), - ( - lanes_below(100), - &[ - "v_cmp_gt_u32 vcc, lit(0x00000064), v0", - "s_bcnt1_i32_b64 s12, vcc", - "v_mov_b32 v2, vcc_hi", - "v_mbcnt_lo_u32_b32 v3, vcc_lo, 0", - "v_mbcnt_hi_u32_b32 v3, vcc_hi, v3", - "buffer_store_dword v3, v16, s[40:43], 0 offen offset:8", - ], - ), - ( - lanes_below_in_a_loop(), - &[ - "s_mov_b32 s20, 0", - "v_cmp_gt_u32 vcc, 40, v0", - "s_add_u32 s20, s20, 1", - "s_cmp_lt_u32 s20, 2", - "s_cbranch_scc1", - ], - ), - ( - lane_reads(40, 33), - &[ - "v_readlane_b32 s12, v0, 40", - "v_readlane_b32 s14, v0, s13", - "v_mov_b32 v1, s12", - "v_mov_b32 v2, s14", - "buffer_store_dword v2, v16, s[40:43], 0 offen offset:4", - ], - ), - ( - reduction(V_ADD_F32, 0x80, 0x7E06_0D00), - &[ - "v_cvt_f32_u32 v3, v0", - "s_or_saveexec_b64 s[12:13], -1", - "v_cndmask_b32 v1, 0, v3, s[12:13]", - "v_permlanex16_b32 v2, v1, 0, 0", - "v_add_f32 v1, v2, v1", - "v_readlane_b32 s14, v1, 32", - "v_add_f32 v1, s14, v1", - "v_readlane_b32 s15, v1, 0", - "s_mov_b64 exec, s[12:13]", - "v_mov_b32 v1, s15", - ], - ), - ( - reduction(V_MIN_U32, 0xC1, V_MOV_V3_V0), - &[ - "v_mov_b32 v3, v0", - "v_cndmask_b32 v1, -1, v3, s[12:13]", - "v_min_u32 v1, v2, v1", - "v_min_u32 v1, s14, v1", - ], - ), - ( - reduction(V_MAX_U32, 0x80, V_MOV_V3_V0), - &["v_max_u32 v1, v2, v1", "v_max_u32 v1, s14, v1"], - ), - ( - exclusive_prefix(), - &[ - "s_or_saveexec_b64 s[0:1], -1", - "v_cndmask_b32 v1, 0, v0, s[0:1]", - "v_add_nc_u32 v1, v1, v1 row_shr:8", - "v_readlane_b32 s2, v1, 47", - "v_mov_b32 v3, v1 row_shr:1", - "s_mov_b64 exec, -2", - "v_mov_b32 v2, v3", - "s_mov_b64 exec, s[0:1]", - "buffer_store_dword v2, v16, s[40:43], 0 offen", - ], - ), - ( - in_a_loop(&[0xD760_000C, 0x0001_5100], 12, Count::Two), - &[ - "v_readlane_b32 s12, v0, 40", - "s_add_u32 s20, s20, 1", - "s_cmp_lt_u32 s20, 2", - "s_cbranch_scc1", - "v_mov_b32 v1, s12", - ], - ), - ( - in_a_loop(&[0x7D88_00A8, 0xBE8C_106A], 12, Count::FirstLane), - &[ - "v_readfirstlane_b32 s21, v0", - "v_cmp_gt_u32 vcc, 40, v0", - "s_bcnt1_i32_b64 s12, vcc", - "s_cmp_lt_u32 s20, s21", - "s_cbranch_scc1", - ], - ), - ]; - for (words, wants) in programs { - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let all = gfx10::decode(&code) - .expect("decodes") - .iter() - .map(|i| i.text(true)) - .collect::>() - .join("\n"); - for want in wants { - assert!(all.contains(want), "{want:?} not in:\n{all}"); - } - } -} - -/// Each lane counts to the low two bits of its thread id in a loop it leaves -/// on its own, whose back edge is unconditional (`s_branch`): lowering caps -/// that back edge at the loop iteration limit. Then the console compiler's -/// whole-wave sum of the counts ([`reduction`] of `v_cvt_f32_u32 v3, v6`). -/// Per thread, one dword at `l * 32`: its console wave's sum. -fn sum_after_a_loop_lanes_leave() -> Vec { - let sum = reduction(V_ADD_F32, 0x80, 0x7E06_0D06); - let mut w = PROLOGUE.to_vec(); - w.extend([ - 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 - 0x360A_0083, // v_and_b32 v5, 3, v0 - 0x7E0C_0280, // v_mov_b32 v6, 0 - 0xBE84_047E, // s_mov_b64 s[4:5], exec - 0x7D82_0B06, // v_cmp_lt_u32 vcc, v6, v5 - 0x87FE_6A7E, // s_and_b64 exec, exec, vcc - 0xBF88_0002, // s_cbranch_execz (past the s_branch) - 0x4A0C_0C81, // v_add_nc_u32 v6, 1, v6 - 0xBF82_FFFB, // s_branch (back to the v_cmp) - 0xBEFE_0404, // s_mov_b64 exec, s[4:5] - ]); - w.extend(&sum[PROLOGUE.len() + 1..]); - w -} - -/// Two scalar loops whose latches share a block, as the console compiler -/// lays them out: the latch branches back to the inner loop's header three -/// times and otherwise falls through to the outer loop's header, which runs -/// twice. Both targets of that branch are back edges. Per thread, one dword -/// at `l * 32`: the inner loop's passes, 6. -fn loops_sharing_a_latch() -> Vec { - let mut w = PROLOGUE.to_vec(); - w.extend([ - 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 - 0xBE94_0380, // s_mov_b32 s20, 0 - 0xBE95_0380, // s_mov_b32 s21, 0 - 0xBF82_0003, // s_branch (to the outer header) - 0x8016_8116, // s_add_u32 s22, s22, 1 (the shared latch) - 0xBF0A_8316, // s_cmp_lt_u32 s22, 3 - 0xBF85_0004, // s_cbranch_scc1 (back to the inner header) - 0x8014_8114, // s_add_u32 s20, s20, 1 (the outer header) - 0xBF08_8214, // s_cmp_gt_u32 s20, 2 - 0xBF85_0003, // s_cbranch_scc1 (out of both loops) - 0xBE96_0380, // s_mov_b32 s22, 0 - 0x8015_8115, // s_add_u32 s21, s21, 1 (the inner header) - 0xBF82_FFF7, // s_branch (to the shared latch) - 0x7E02_0215, // v_mov_b32 v1, s21 - ]); - w.extend(store(1, 0)); - w.push(S_ENDPGM); - w -} - -/// A reduction after a loop the lanes leave one by one, whose back edge is -/// capped at the loop iteration limit ([`sum_after_a_loop_lanes_leave`]): -/// the console runs the loop to its end, so with the cap taken as never -/// reached every lane of the group runs the reduction together and the -/// halves pass each other their sums. Only with the cap's barriers refused -/// (`VICTORY_CAP_BARRIERS=1`) is a lane taken to have left at the cap, and -/// the reduction refused. -#[test] -fn a_reduction_after_a_loop_lanes_leave_passes_between_halves() { - let words = sum_after_a_loop_lanes_leave(); - for threads in [64, 96, 128] { - // The lockstep loops of #591 may now translate this shape even with - // the cap's barriers, so the refusal is no longer required. - let why = super::with_cap_barriers(true, || refusal(&words, threads, 0)); - assert!( - why == "translated" || why.contains("a wave reduction over both 32-lane halves"), - "{threads}: {why}" - ); - let translated = super::with_cap_barriers(false, || refusal(&words, threads, 0)); - assert_eq!(translated, "translated", "{threads}"); - } - assert_eq!(refusal(&words, 32, 0), "translated"); -} - -/// [`sum_after_a_loop_lanes_leave`] on every hardware adapter gives the -/// console's sums, in a group of 64 (one console wave in two halves), of 96 -/// (the second console wave has no upper half) and of 128 (two). -#[test] -#[cfg(windows)] -fn a_reduction_after_a_loop_lanes_leave_matches_the_console_on_every_gpu() { - let words = sum_after_a_loop_lanes_leave(); - let mut failed = Vec::new(); - for threads in [64, 96, 128] { - let want: Vec = (0..threads) - .map(|l| (console_reduction(threads, l, |a, b| a + b, |t| t & 3) as f32).to_bits()) - .collect(); - failed.extend(super::with_cap_barriers(false, || { - differences(&words, threads, 1, &want) - })); - } - assert!(failed.is_empty(), "{}", failed.join("\n")); -} - -/// [`loops_sharing_a_latch`] in whole-wave halves: each side of the shared -/// latch's branch counts its own loop's passes under the iteration limit. -#[test] -fn a_branch_back_to_two_loops_runs_in_whole_wave_halves() { - let n = native(&loops_sharing_a_latch(), true, 64, 0); - let literal = lower_halves(&n, true, false, true).expect("whole-wave halves"); - assert_eq!(literal.wave_size, Some(32)); -} - -/// [`loops_sharing_a_latch`] in whole-wave halves on every hardware adapter -/// gives the console's count in every lane. -#[test] -#[cfg(windows)] -fn a_branch_back_to_two_loops_matches_the_console_on_every_gpu() { - let words = loops_sharing_a_latch(); - let failed = differences_in(true, &words, 64, 1, &[6; 64], 0, false, true); - assert!(failed.is_empty(), "{}", failed.join("\n")); -} - -/// `v_permlane16_b32` or `v_permlanex16_b32` with the FI and BOUND_CTRL bits -/// (`op_sel` bits 0 and 1, word bits 11 and 12): lane `l` takes the value -/// of `v0` from its own row of 16 (or the other row of its half), the lane -/// its nibble of `s8` (lanes 0 to 7) or `s9` (lanes 8 to 15) names. -const fn permlane16(other_row: bool, fetch_inactive: bool, bound_ctrl: bool) -> [u32; 2] { - let opcode = if other_row { 0xD778_0001 } else { 0xD777_0001 }; - [ - opcode | (fetch_inactive as u32) << 11 | (bound_ctrl as u32) << 12, - 0x0024_1100, - ] -} - -/// Keep arbitrary high bits in the same-row fixture's source data. -const PERM_PAYLOAD: u32 = 0xDEAD_BE00; - -/// Per workgroup lane: `v0` (its thread id, or a raw value made from the -/// workgroup and thread ids for the same-row form), permuted first with all -/// lanes active, then with only even lanes active and every FI/BOUND_CTRL -/// combination. The same-row form also checks full EXEC with BOUND_CTRL -/// set. Each masked or potentially out-of-bounds read starts with `v1` -/// holding [`PERM_OLD`]. EXEC is whole again for every store. -#[cfg(windows)] -fn permlane16_program(lanes: u32, other_row: bool) -> Vec { - let wave64 = lanes > 32; - let full = |w: &mut Vec| { - w.push(if wave64 { - 0xBEFE_04C1 // s_mov_b64 exec, -1 + let bound = if forever { + "v_mov_b32 v5, -1" } else { - 0xBEFE_03C1 // s_mov_b32 exec_lo, -1 - }); - }; - let even = |w: &mut Vec| { - w.push(if wave64 { - 0xBEFE_040A // s_mov_b64 exec, s[10:11] + "v_and_b32 v5, 7, v6" + }; + let rows = if width == 8 { + "v_lshlrev_b32 v3, 3, v1" } else { - 0xBEFE_030A // s_mov_b32 exec_lo, s10 - }); - }; - let mut w = PROLOGUE.to_vec(); - if other_row { - w.push(0x3420_0085); // v_lshlrev_b32 v16, 5, v0 - } else { - w.extend([ - 0x8F02_8801, // s_lshl_b32 s2, s1 (group id X), 8 - 0x4A22_0002, // v_add_nc_u32 v17, s2, v0 - 0x3420_2285, // v_lshlrev_b32 v16, 5, v17 - 0x3A00_22FF, - PERM_PAYLOAD, // v_xor_b32 v0, PERM_PAYLOAD, v17 + "v_lshlrev_b32 v3, 4, v1" + }; + let mut want = vec![ + rows, + "v_add_nc_u32 v0, v0, v3", + "v_lshlrev_b32 v16, 6, v0", + "v_mov_b32 v4, s1", + "v_lshlrev_b32 v4, 14, v4", + "v_add_nc_u32 v16, v16, v4", + "v_add_nc_u32 v6, s1, v0", + "v_mov_b32 v1, 0", + "v_mov_b32 v2, 0", + bound, + "s_mov_b64 s[36:37], exec", + "s_branch", + "v_readfirstlane_b32 s6, v0", + "v_add_nc_u32 v2, s6, v2", + "v_add_nc_u32 v1, 1, v1", + ]; + if !forever { + want.extend([ + "v_lshlrev_b32 v17, 2, v1", + "v_add_nc_u32 v17, v16, v17", + "buffer_store_dword v1, v17, s[40:43], 0 offen", + ]); + } + want.extend([ + "v_cmp_lt_u32 vcc, v1, v5", + "s_and_b64 exec, exec, vcc", + "s_cbranch_execnz", + "s_mov_b64 exec, s[36:37]", + "v_add_nc_u32 v7, 1, v0", + "buffer_atomic_add v7, v16, s[40:43], 0 offen offset:32", + "buffer_store_dword v1, v16, s[40:43], 0 offen offset:36", ]); + // The prologue's five words are four instructions. + for (n, want) in want.iter().enumerate() { + let got = &text[PROLOGUE.len() - 1 + n]; + assert!(got.starts_with(want), "{n}: {got:?}, not {want:?}"); + } } - w.extend([ - 0xBE88_03FF, - PERM_LOW, // s_mov_b32 s8, PERM_LOW - 0xBE89_03FF, - PERM_HIGH, // s_mov_b32 s9, PERM_HIGH - 0xBE8A_03FF, - 0x5555_5555, // s_mov_b32 s10, 0x55555555 - 0xBE8B_03FF, - 0x5555_5555, // s_mov_b32 s11, 0x55555555 - ]); - if !other_row { - w.extend([0x7E02_02FF, PERM_OLD]); // v_mov_b32 v1, PERM_OLD - } - w.extend(permlane16(other_row, false, false)); - w.extend(store(1, 0)); - for (slot, (fi, bc)) in [(false, false), (false, true), (true, false), (true, true)] - .into_iter() - .enumerate() - { - w.extend([0x7E02_02FF, PERM_OLD]); // v_mov_b32 v1, PERM_OLD - even(&mut w); - w.extend(permlane16(other_row, fi, bc)); - full(&mut w); - w.extend(store(1, 4 * (slot as u32 + 1))); - } - if !other_row { - w.extend([0x7E02_02FF, PERM_OLD]); // v_mov_b32 v1, PERM_OLD - w.extend(permlane16(false, false, true)); - w.extend(store(1, 20)); - } - w.push(S_ENDPGM); - w } -/// What the console gives [`permlane16_program`]'s lane `l`. An FI read -/// from a lane that was never launched has no documented input value. -fn permlane16_console(l: u32, group: u32, threads: u32, other_row: bool) -> [Option; 6] { - let in_row = l % 16; - let selectors = if in_row >= 8 { PERM_HIGH } else { PERM_LOW }; - let row = if other_row { (l / 16) ^ 1 } else { l / 16 }; - let source = row * 16 + ((selectors >> (4 * (in_row % 8))) & 15); - let value = if other_row { - source - } else { - (256 * group + source) ^ PERM_PAYLOAD - }; - let active = |lane: u32| lane.is_multiple_of(2); - let result = |masked: bool, fi: bool, bc: bool| { - if masked && !active(l) { - Some(PERM_OLD) - } else if fi { - (source < threads).then_some(value) - } else if source < threads && (!masked || active(source)) { - Some(value) - } else if bc { - Some(0) - } else { - Some(PERM_OLD) - } - }; - [ - result(false, false, false), - result(true, false, false), - result(true, false, true), - result(true, true, false), - result(true, true, true), - result(false, false, true), - ] +/// What the console stores for [`while_loop_in_rows`]'s lanes of group +/// `group`, `lanes` threads in console waves of 64: 16 dwords each. +#[cfg(windows)] +fn console_while_loop_in_rows(lanes: u32, group: u32) -> Vec<[u32; 16]> { + let stays = |t: u32| (t + group) & 7; + (0..lanes) + .map(|t| { + let mut lane = [0; 16]; + let wave = (t & !63)..lanes.min((t & !63) + 64); + for pass in 0..stays(t) { + // The first lane of its wave still in the loop in this pass. + lane[0] += wave.clone().find(|&f| stays(f) > pass).expect("this one"); + lane[pass as usize + 1] = pass + 1; + } + lane[8] = t + 1; + lane[9] = stays(t); + lane + }) + .collect() } -/// The hand-encoded words are the instructions their comments name. +/// A `while` loop in lockstep translates in halves in groups of rows. #[test] -fn the_permlane16_programs_are_what_their_comments_say() { - for (words, opcode) in [ - (permlane16(true, false, false), "v_permlanex16_b32"), - (permlane16(true, true, true), "v_permlanex16_b32"), - (permlane16(false, false, false), "v_permlane16_b32"), - (permlane16(false, true, true), "v_permlane16_b32"), - ] { - let p = ir::build( - &[words[0], words[1], S_ENDPGM] - .iter() - .flat_map(|w| w.to_le_bytes()) - .collect::>(), - false, - 32, - ) - .expect("ir::build"); - assert_eq!(p.blocks[0].insts[0].name(), opcode); +fn a_while_loop_in_rows_translates_in_halves() { + for threads in [[8, 8], [8, 6], [16, 16]] { + for forever in [false, true] { + let n = native_2d(&while_loop_in_rows(forever, threads[0]), threads); + let l = + lowered(&n, true).unwrap_or_else(|e| panic!("{threads:?} forever={forever}: {e}")); + assert_eq!(l.wave_size, Some(32)); + assert!(l.barriers > 0, "the halves meet in the loop"); + } } } -/// The lanes of each row read the other row of their 32-lane half through -/// their selector nibbles, and an inactive source lane gives the old value, -/// zero or its register as FI and BOUND_CTRL say, on every hardware -/// adapter, in console waves of 32 and of 64 (in halves and whole). -#[test] +/// A `while` loop in lockstep in groups of rows (8x8: two full host waves; +/// 8x6: 48 threads, the console wave's upper half 16 lanes; 16x16: four +/// console waves, as GTA VI's programs with such a loop have), several groups +/// to a dispatch, lanes leaving at different passes: every lane stores what +/// the console's does, its count of passes too, and each thread id is held +/// by one host lane. Left by no lane, the loop ends at the translation's +/// limit of passes in every lane of every group. +/// +/// A group that stayed in the loop after its last lane left would store +/// nothing more, so that shows only in time. Time does not tell here: on an +/// M5 Pro 2,048 groups of 8x8 took 22 to 25 ms, and 56 to 62 ms with every +/// group at the limit (16,383 passes, two exchanges each), so the times are +/// printed, not checked. #[cfg(windows)] -fn permlanex16_picks_lanes_as_the_console_does_on_every_gpu() { +#[test] +fn a_while_loop_in_rows_matches_the_console_and_leaves_on_every_gpu() { + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let hosts = Host::each_hardware(); + if hosts.is_empty() { + eprintln!("no SM 6.6 hardware device; skipped"); + return; + } let mut failed = Vec::new(); - for lanes in [32, 64] { - let want: Vec = (0..lanes) - .flat_map(|l| { - permlane16_console(l, 0, lanes, true) - .into_iter() - .take(5) - .map(|value| value.expect("full cross-row fixtures")) - }) - .collect(); - failed.extend(differences_in( - lanes == 64, - &permlane16_program(lanes, true), - lanes, - 5, - &want, - 0, - false, - false, - )); + for (adapter, host) in &hosts { + for threads in [[8u32, 8], [8, 6], [16, 16]] { + let lanes = threads[0] * threads[1]; + for narrow_waves in [false, true] { + let label = format!("{adapter} {threads:?} narrow_waves={narrow_waves}"); + let make = |forever: bool| { + let n = native_2d(&while_loop_in_rows(forever, threads[0]), threads); + let s = shader(lower_halves(&n, true, narrow_waves, false).expect("halves")); + if let Ok(mut v) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { + v.validate(&mut s.dxil.clone()) + .expect("DXIL validation failed"); + } + let Ok((root, pso)) = host.compute_pipeline(&s) else { + panic!("{label}: no pipeline"); + }; + (s, root, pso) + }; + let leaves = make(false); + let stays = make(true); + let run = |forever: bool, groups: u32| { + let (s, root, pso) = if forever { &stays } else { &leaves }; + let ud = vec![0u32; s.user_data_dwords().max(1) as usize]; + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &[0; 4], + stride: Stride::Structured(16), + }, + View::RawUav(groups * 256 * 16), + ]; + let start = std::time::Instant::now(); + let out = host + .dispatch( + root, + pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &views, + samplers: &[], + groups: [groups, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + (out, start.elapsed()) + }; + for groups in [1u32, 5, 37] { + let (out, _) = run(false, groups); + let mut wrong = 0; + for g in 0..groups { + let want = console_while_loop_in_rows(lanes, g); + for (t, want) in want.iter().enumerate() { + let at = (g as usize * 256 + t) * 16; + let got = &out[0][at..at + 16]; + if got != want { + wrong += 1; + failed.push(format!( + "{label}: {groups} groups: group {g} lane {t}: {got:?}, the console {want:?}" + )); + } + } + // Nothing stored where the group has no thread. + let past = (g as usize * 256 + lanes as usize) * 16; + let end = (g as usize + 1) * 256 * 16; + if out[0][past..end].iter().any(|&d| d != 0) { + wrong += 1; + failed.push(format!( + "{label}: {groups} groups: group {g}: stores past its {lanes} threads" + )); + } + } + eprintln!("{label}: {groups} groups: {wrong} lanes differ from the console"); + } + // Many groups, the best of three, and the loop no lane leaves + // (every group at the limit of passes). + let groups = 512; + let best = (0..3).map(|_| run(false, groups).1).min().expect("three"); + let (out, limit) = run(true, groups); + // Every lane of every group ran to the limit of passes. + let passes: std::collections::BTreeSet = (0..groups as usize * 256) + .filter(|t| t % 256 < lanes as usize) + .map(|t| out[0][t * 16 + 9]) + .collect(); + eprintln!("{label}: passes at the limit: {passes:?}"); + if passes != [super::DEFAULT_LOOP_LIMIT - 1].into() { + failed.push(format!("{label}: passes at the limit: {passes:?}")); + } + eprintln!( + "{label}: {groups} groups: {best:?}; with every group at the limit of passes {limit:?}" + ); + } + } } assert!(failed.is_empty(), "{}", failed.join("\n")); } -/// Lane 0 selects an odd lane (nibble 15) and lane 8 selects an even lane -/// (nibble 0). Lane 32 stays in the same half for either row choice. +/// A sum over the group's earlier console waves, in a `while` loop whose +/// exit test is in its header and whose latch reads the first lane (the +/// shape of the loops in GTA VI's acceleration-structure builder): every +/// lane writes its wave's number plus 5 to the wave's LDS dword; after a +/// barrier, the lanes of wave `w > 0` add dwords 0 to `w - 1` up, carrying +/// the sum from pass to pass through the first lane (`s17`), and leave when +/// the pass count `s18` is their wave. Each lane stores its sum. +fn sum_of_earlier_waves() -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x2C0E_0086, // v_lshrrev_b32 v7, 6, v0 + 0x3410_0E82, // v_lshlrev_b32 v8, 2, v7 + 0x4A12_0E85, // v_add_nc_u32 v9, 5, v7 + 0xD834_0000, + 0x0000_0908, // ds_write_b32 v8, v9 + S_WAITCNT_LGKM, + 0xBF8A_0000, // s_barrier + 0x7E10_0280, // v_mov_b32 v8, 0 + 0xBE80_047E, // s_mov_b64 s[0:1], exec + 0x7DAA_0E80, // v_cmpx_ne_u32 exec, 0, v7 + 0xBF88_0012, // s_cbranch_execz (the end) + 0xBE82_047E, // s_mov_b64 s[2:3], exec + 0xBE86_047E, // s_mov_b64 s[6:7], exec + 0xBE92_0380, // s_mov_b32 s18, 0 + 0xBE91_0380, // s_mov_b32 s17, 0 + 0xBF82_0002, // s_branch (the header) + 0x87FE_0610, // s_and_b64 exec, s[16:17], s[6:7] + 0x7E22_0508, // v_readfirstlane_b32 s17, v8 + 0x8F10_8212, // s_lshl_b32 s16, s18, 2 + 0x8112_8112, // s_add_i32 s18, s18, 1 + 0x7E10_0210, // v_mov_b32 v8, s16 + 0xD8D8_0000, + 0x0800_0008, // ds_read_b32 v8, v8 + S_WAITCNT_LGKM, + 0x4A10_1011, // v_add_nc_u32 v8, s17, v8 + 0xBE90_047E, // s_mov_b64 s[16:17], exec + 0x7DA4_0E12, // v_cmpx_eq_u32 exec, s18, v7 + 0x8A86_7E06, // s_andn2_b64 s[6:7], s[6:7], exec + 0xBF85_FFF3, // s_cbranch_scc1 (the latch) + 0xBEFE_0400, // s_mov_b64 exec, s[0:1] + ]); + w.extend(store(8, 0)); + w.push(S_ENDPGM); + w +} + #[test] -fn the_permlane16_model_follows_the_instructions() { - assert_eq!( - permlane16_console(0, 0, 64, true), - [31, PERM_OLD, 0, 31, 31, 31].map(Some) - ); - assert_eq!(permlane16_console(8, 0, 64, true), [Some(16); 6]); - assert_eq!( - permlane16_console(1, 0, 64, true), - [29, PERM_OLD, PERM_OLD, PERM_OLD, PERM_OLD, 29].map(Some) +fn the_sum_of_earlier_waves_is_what_its_comments_say() { + let words = sum_of_earlier_waves(); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let text: Vec = gfx10::decode(&code) + .expect("decodes") + .iter() + .map(|i| i.text(true)) + .collect(); + let want = [ + "v_lshlrev_b32 v16, 5, v0", + "v_lshrrev_b32 v7, 6, v0", + "v_lshlrev_b32 v8, 2, v7", + "v_add_nc_u32 v9, 5, v7", + "ds_write_b32 v8, v9", + "s_waitcnt lgkmcnt(0)", + "s_barrier", + "v_mov_b32 v8, 0", + "s_mov_b64 s[0:1], exec", + "v_cmpx_ne_u32 exec, 0, v7", + "s_cbranch_execz", + "s_mov_b64 s[2:3], exec", + "s_mov_b64 s[6:7], exec", + "s_mov_b32 s18, 0", + "s_mov_b32 s17, 0", + "s_branch", + "s_and_b64 exec, s[16:17], s[6:7]", + "v_readfirstlane_b32 s17, v8", + "s_lshl_b32 s16, s18, 2", + "s_add_i32 s18, s18, 1", + "v_mov_b32 v8, s16", + "ds_read_b32 v8, v8", + "s_waitcnt lgkmcnt(0)", + "v_add_nc_u32 v8, s17, v8", + "s_mov_b64 s[16:17], exec", + "v_cmpx_eq_u32 exec, s18, v7", + "s_andn2_b64 s[6:7], s[6:7], exec", + "s_cbranch_scc1", + "s_mov_b64 exec, s[0:1]", + ]; + // The prologue's five words are four instructions. + for (n, want) in want.iter().enumerate() { + let got = &text[PROLOGUE.len() - 1 + n]; + assert!(got.starts_with(want), "{n}: {got:?}, not {want:?}"); + } + // The three branches go to the end, the header and the latch. + let at = |name: &str| { + let i = gfx10::decode(&code).expect("decodes"); + i.iter() + .find(|i| i.text(true).starts_with(name)) + .map(|i| i.text(true)) + .expect("there") + }; + let offset = |n: usize| { + let i = gfx10::decode(&code).expect("decodes"); + i[PROLOGUE.len() - 1 + n].offset + }; + assert!( + at("s_cbranch_execz").contains(&format!("{:04X}", offset(28))), + "{}", + at("s_cbranch_execz") ); - assert_eq!(permlane16_console(16, 0, 64, true)[0], Some(15)); - assert_eq!(permlane16_console(32, 0, 64, true)[0], Some(63)); - assert_eq!(permlane16_console(48, 0, 64, true)[0], Some(47)); - assert_eq!( - permlane16_console(0, 0, 64, false), - [ - 0xDEAD_BE0F, - PERM_OLD, - 0, - 0xDEAD_BE0F, - 0xDEAD_BE0F, - 0xDEAD_BE0F - ] - .map(Some) + assert!( + at("s_branch").contains(&format!("{:04X}", offset(18))), + "{}", + at("s_branch") ); - assert_eq!(permlane16_console(8, 0, 64, false), [Some(PERM_PAYLOAD); 6]); - assert_eq!(permlane16_console(32, 1, 64, false)[0], Some(0xDEAD_BF2F)); - assert_eq!( - permlane16_console(64, 0, 79, false), - [Some(PERM_OLD), Some(PERM_OLD), Some(0), None, None, Some(0)] + assert!( + at("s_cbranch_scc1").contains(&format!("{:04X}", offset(16))), + "{}", + at("s_cbranch_scc1") ); } -fn same_row_permlane16_native(threads: u32) -> NativeProgram { - let words = permlane16_program(threads, false); - let mut n = native(&words, threads > 32, threads, 0); - let StageIo::Cs(cs) = &mut n.io else { - unreachable!() - }; - cs.rsrc2 |= 1 << 7; // group id X in s1, after the user-data SGPR - n +/// The sum translates in halves, its loop in lockstep. +#[test] +fn a_sum_of_earlier_waves_translates_in_halves() { + for threads in [128, 256, 512] { + for narrow_waves in [false, true] { + let n = native(&sum_of_earlier_waves(), true, threads, 512); + let l = lowered_with(&n, true, narrow_waves) + .unwrap_or_else(|e| panic!("{threads} threads narrow_waves={narrow_waves}: {e}")); + assert_eq!(l.wave_size, Some(32)); + } + } } +/// Each lane of wave `w` stores `5 + 6 + ... + (w + 4)`, as on the console. +#[cfg(windows)] #[test] -fn same_row_permlane16_uses_host_lanes_without_an_exchange() { - let n = same_row_permlane16_native(64); - let l = super::with_thread_ticket(false, || lowered(&n, true)) - .expect("a live same-row permute lowers in wave64 halves"); - assert_eq!(l.wave_size, Some(32)); - assert!(l.uses_lane_index); - assert_eq!(l.barriers, 0); +fn a_sum_of_earlier_waves_matches_the_console_on_every_gpu() { + let words = sum_of_earlier_waves(); + let mut failed = Vec::new(); + for threads in [128u32, 256, 512] { + let want: Vec = (0..threads) + .map(|t| (0..t >> 6).map(|k| k + 5).sum()) + .collect(); + for narrow_waves in [false, true] { + failed.extend( + differences_with(&words, threads, 1, &want, 512, narrow_waves) + .into_iter() + .map(|m| format!("{threads} threads narrow_waves={narrow_waves}: {m}")), + ); + } + } + assert!(failed.is_empty(), "{}", failed.join("\n")); } -/// The last 16-lane row is complete at 80 and 112 threads. At 79 threads -/// some selectors name the missing lane. Check both BOUND_CTRL outcomes -/// for those reads with FI clear. -#[test] -#[cfg(windows)] -fn same_row_permlane16_matches_the_console_on_hardware() { - let _one = super::valu_tests::ONE_AT_A_TIME - .lock() - .unwrap_or_else(|e| e.into_inner()); - let hosts = Host::each_hardware(); - if hosts.is_empty() { - eprintln!("no SM 6.6 hardware device; skipped same-row permlane16"); - return; +/// LDS written in a `while` loop of a group of one console wave (64 +/// threads), the shape of the loops in the builder's `28918b7150a7aad5` and +/// `caa78b8ca62bc3d6`: each lane clears its eight LDS dwords; the lanes whose +/// count `tid & 7` is not 0 then loop, writing the pass number `s28` at +/// dword `s28 - 1` of theirs in each pass, and leave when `s28` is their +/// count (the latch restores EXEC from the mask of lanes left, `s[16:17]`). +/// After the loop each lane reads the eight dwords of lane `tid ^ 63`, in +/// the wave's other half, and stores them. +fn lds_written_in_a_while_loop() -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x3614_0087, // v_and_b32 v10, 7, v0 + 0x3418_0085, // v_lshlrev_b32 v12, 5, v0 + 0x7E16_0280, // v_mov_b32 v11, 0 + ]); + for k in 0..8 { + w.extend([0xD834_0000 | (4 * k), 0x0000_0B0C]); // ds_write_b32 v12, v11 offset:4k } - let workgroups = 3; - let mut completed = 0; - let mut checked_lanes = 0; - let mut checked_dwords = 0; - for (adapter, host) in &hosts { - for threads in [32, 64, 79, 80, 96, 112, 128, 256] { - let n = same_row_permlane16_native(threads); - let bytes = crate::dxbc::build(&[]); - let container = crate::dxbc::Container::parse(&bytes).expect("empty test container"); - let (p, st) = - crate::range::build(&n.patched_code(), n.wave64, n.vgprs).expect("range::build"); - let st = st.expect("structure"); - let res = resource::track(&p, &n.layout, n.stage, Some(&st)).expect("track"); - let io = io::raise(&p, &n).expect("io::raise"); - let shader = super::emit_with( - &container, - &n, - &p, - &st, - &io, - &res, - super::Options { - host_wave32: true, - narrow_waves: true, - ..Default::default() - }, - ) - .expect("production translation of same-row permlane16"); - let label = format!("{adapter}: {threads} threads"); - if let Ok(mut v) = - validator::Validator::load(validator::Validator::default_path().as_deref()) - { - v.validate(&mut shader.dxil.clone()) - .unwrap_or_else(|e| panic!("{label}: DXIL validation: {e}")); - } - let (root, pso) = host - .compute_pipeline(&shader) - .unwrap_or_else(|e| panic!("{label}: pipeline creation: {e}")); - let ud = vec![0; shader.user_data_dwords().max(1) as usize]; - let out = host - .dispatch( - &root, - &pso, - &Dispatch { - roots: vec![(0, Root::Constants(ud))], - views: &[ - View::Texture(1, 1, &[[0.0; 4]]), - View::Buffer { - data: &[0; 4], - stride: Stride::Structured(16), - }, - View::RawUav(workgroups * 256 * 8), - ], - samplers: &[], - groups: [workgroups, 1, 1], - }, - ) - .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); - assert_eq!(out.len(), 1, "{label}: readback UAV count"); - assert_eq!( - out[0].len(), - (workgroups * 256 * 8) as usize, - "{label}: readback length" - ); - for group in 0..workgroups { - for lane in 0..threads { - let offset = ((group * 256 + lane) * 8) as usize; - for (slot, expected) in permlane16_console(lane, group, threads, false) - .into_iter() - .enumerate() - { - if let Some(expected) = expected { - assert_eq!( - out[0][offset + slot], - expected, - "{label}: workgroup {group}, lane {lane}, slot {slot}" - ); - checked_dwords += 1; - } - } - } + w.extend([ + 0xBE8C_047E, // s_mov_b64 s[12:13], exec + 0x7DAA_1480, // v_cmpx_ne_u32 exec, 0, v10 + 0xBF88_000F, // s_cbranch_execz (the end) + 0xBE8E_047E, // s_mov_b64 s[14:15], exec + 0xBE90_047E, // s_mov_b64 s[16:17], exec + 0xBE9C_0380, // s_mov_b32 s28, 0 + 0xBF82_0001, // s_branch (the header) + 0x87FE_1012, // s_and_b64 exec, s[18:19], s[16:17] + 0x8F12_821C, // s_lshl_b32 s18, s28, 2 + 0x811C_811C, // s_add_i32 s28, s28, 1 + 0x4A1A_1812, // v_add_nc_u32 v13, s18, v12 + 0x7E1E_021C, // v_mov_b32 v15, s28 + 0xBE92_047E, // s_mov_b64 s[18:19], exec + 0xD834_0000, + 0x0000_0F0D, // ds_write_b32 v13, v15 + 0x7DA4_141C, // v_cmpx_eq_u32 exec, s28, v10 + 0x8A90_7E10, // s_andn2_b64 s[16:17], s[16:17], exec + 0xBF85_FFF5, // s_cbranch_scc1 (the latch) + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + 0x3A1C_00BF, // v_xor_b32 v14, 63, v0 + 0x341C_1C85, // v_lshlrev_b32 v14, 5, v14 + ]); + for k in 0..8 { + w.extend([0xD8D8_0000 | (4 * k), 0x0000_000E | (20 + k) << 24]); // ds_read_b32 v(20+k), v14 offset:4k + } + w.push(S_WAITCNT_LGKM); + for k in 0..8 { + w.extend(store(20 + k as u8, 4 * k)); + } + w.push(S_ENDPGM); + w +} + +#[test] +fn the_lds_while_loop_is_what_its_comments_say() { + let words = lds_written_in_a_while_loop(); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let list = gfx10::decode(&code).expect("decodes"); + let text: Vec = list.iter().map(|i| i.text(true)).collect(); + let all = text.join("\n"); + for want in [ + "v_lshlrev_b32 v16, 5, v0", + "v_and_b32 v10, 7, v0", + "v_lshlrev_b32 v12, 5, v0", + "v_mov_b32 v11, 0", + "ds_write_b32 v12, v11\n", + "ds_write_b32 v12, v11 offset:28", + "s_mov_b64 s[12:13], exec", + "v_cmpx_ne_u32 exec, 0, v10", + "s_mov_b64 s[14:15], exec", + "s_mov_b64 s[16:17], exec", + "s_mov_b32 s28, 0", + "s_and_b64 exec, s[18:19], s[16:17]", + "s_lshl_b32 s18, s28, 2", + "s_add_i32 s28, s28, 1", + "v_add_nc_u32 v13, s18, v12", + "v_mov_b32 v15, s28", + "s_mov_b64 s[18:19], exec", + "ds_write_b32 v13, v15", + "v_cmpx_eq_u32 exec, s28, v10", + "s_andn2_b64 s[16:17], s[16:17], exec", + "s_mov_b64 exec, s[12:13]", + "v_xor_b32 v14, 63, v0", + "v_lshlrev_b32 v14, 5, v14", + "ds_read_b32 v20, v14\n", + "ds_read_b32 v27, v14 offset:28", + ] { + assert!(all.contains(want), "{want:?} not in:\n{all}"); + } + // The branches: to the end, the header and the latch. + let at = |name: &str| { + list.iter() + .position(|i| i.text(true).starts_with(name)) + .expect("there") + }; + let target = |n: usize| format!("{:04X}", list[n].offset); + let (end, header, latch) = ( + at("s_mov_b64 exec, s[12:13]"), + at("s_lshl_b32 s18"), + at("s_and_b64 exec, s[18:19]"), + ); + assert!( + text[at("s_cbranch_execz")].contains(&target(end)), + "{}", + text[at("s_cbranch_execz")] + ); + assert!( + text[at("s_branch")].contains(&target(header)), + "{}", + text[at("s_branch")] + ); + assert!( + text[at("s_cbranch_scc1")].contains(&target(latch)), + "{}", + text[at("s_cbranch_scc1")] + ); +} + +/// Each lane stores the dwords of lane `tid ^ 63`: 1 to that lane's count, +/// then zeros, as on the console. +#[cfg(windows)] +#[test] +fn lds_written_in_a_while_loop_matches_the_console_on_every_gpu() { + let words = lds_written_in_a_while_loop(); + let want: Vec = (0..64u32) + .flat_map(|t| { + let n = (t ^ 63) & 7; + (1..=8).map(move |p| if p <= n { p } else { 0 }) + }) + .collect(); + let mut failed = Vec::new(); + for narrow_waves in [true, false] { + let n = native(&words, true, 64, 2048); + match lowered_with(&n, true, narrow_waves) { + Ok(l) => eprintln!( + "narrow_waves={narrow_waves}: translates, {} barriers", + l.barriers + ), + Err(e) => { + eprintln!("narrow_waves={narrow_waves}: refused: {e}"); + continue; } - completed += 1; - checked_lanes += threads * workgroups; - eprintln!("{label}: pipeline created, {workgroups} workgroups completed and checked"); } + failed.extend( + differences_with(&words, 64, 8, &want, 2048, narrow_waves) + .into_iter() + .map(|m| format!("narrow_waves={narrow_waves}: {m}")), + ); } - assert!(completed > 0 && checked_lanes > 0 && checked_dwords > 0); - eprintln!( - "same-row permlane16: {completed} hardware dispatches, {checked_lanes} lanes and {checked_dwords} defined dwords checked" - ); + assert!(failed.is_empty(), "{}", failed.join("\n")); } -/// A `while` loop as the console compiler lays one out: the entry jumps to -/// the test, which branches back to the body while lanes stay; the body -/// falls into the test. The body reads the first lane's thread id -/// (`v_readfirstlane_b32 s6, v0`) into an accumulator `v2`, and counts its -/// passes in `v1`. `narrow`: a lane stays while `v1 < (tid & 7)`, and the -/// test drops the lanes done from EXEC (`s_and_b64 exec, exec, vcc; -/// s_cbranch_execnz`). Else every lane stays while `v1 < 7`, a test the -/// same in every lane, and EXEC stays (`s_and_b64 vcc, exec, vcc; -/// s_cbranch_vccnz`, as GTA VI's loops test). Every lane stores `v2`. -fn while_loop_first_lane(narrow: bool) -> Vec { +/// A register-index waterfall as the console compiler writes one for a +/// per-lane `v[3 + index]`: `v3..v10` hold `k * 1000 + thread id`, the index +/// is `(thread id >> 2) & 7`, and the loop reads one index left +/// (`v_readfirstlane_b32 s38, v28`), runs the lanes holding it with +/// `m0 = s38` and `v_movrels_b32 v31, v3`, drops them, and loops while any +/// lane is left. Every lane stores `v31`: `index * 1000 + thread id`. +/// `with_mbcnt` asks for console lanes as well (so the program runs in +/// halves); `after` is put after the loop, `body` before the loop's +/// `s_xor_b64`. +fn index_waterfall(with_mbcnt: bool, body: &[u32], after: &[u32]) -> Vec { + let mut w = PROLOGUE.to_vec(); + w.push(0x3420_0085); // v_lshlrev_b32 v16, 5, v0 + if with_mbcnt { + w.extend([ + 0xD765_0001, + 0x0001_00C1, // v_mbcnt_lo_u32_b32 v1, -1, 0 + ]); + } + for k in 0..8u32 { + // v_add_nc_u32 v(3 + k), k * 1000, v0 + w.extend([0x4A00_00FF | (3 + k) << 17, k * 1000]); + } + w.extend([ + 0x2C38_0082, // v_lshrrev_b32 v28, 2, v0 + 0x3638_3887, // v_and_b32 v28, 7, v28 + 0xBEA4_047E, // s_mov_b64 s[36:37], exec + ]); + let looped = [ + &[ + 0x7E4C_051C, // v_readfirstlane_b32 s38, v28 + 0x7D84_3826, // v_cmp_eq_u32 vcc, s38, v28 + 0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc + 0xBEFC_0326, // s_mov_b32 m0, s38 + 0x7E3E_8703, // v_movrels_b32 v31, v3 + ][..], + body, + &[0x89FE_067E], // s_xor_b64 exec, exec, s[6:7] + ] + .concat(); + let back = -(looped.len() as i32 + 1); + w.extend(&looped); + w.push(0xBF89_0000 | (back as u32 & 0xFFFF)); // s_cbranch_execnz (the read) + w.push(0xBEFE_0424); // s_mov_b64 exec, s[36:37] + w.extend(after); + w.extend(store(31, 0)); + w.push(S_ENDPGM); + w +} + +/// How the lanes of [`break_loop`] break out of it. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Breaks { + /// Lane `l` in pass `l & 3`: the lanes with 3 never, so the loop runs + /// to its own end. + ByLane, + /// Lane `l` in pass `l & 1`: no lane is left after the second pass, and + /// the console wave leaves the loop there. + AllEarly, + /// By half: the lanes of host wave `w` in pass `w & 3`, so from the + /// second pass on a console wave's first lane left is in its upper half. + ByHalf, +} + +/// A loop of three passes, counted in `s30`, that lanes break out of one by +/// one, as the console compiler lays one out (GTA VI's `9991e29feaa26e3e` +/// at 0x1f08): each pass takes the lanes whose `v5` is the pass out of the +/// mask of lanes left (`v_cmpx_eq_u32 exec, s30, v5; s_andn2_b64 s[26:27], +/// s[26:27], exec`), leaves if none is left (`s_cbranch_scc0`), and else +/// goes on with those left (`s_and_b64 exec, s[22:23], s[26:27]`). Each +/// pass reads the first lane left (`v_readfirstlane_b32 s6, v0`) into an +/// accumulator `v2` and counts in `v3`; a lane that breaks sets `v1` to 1, +/// one that never does gets 2 after the last pass. Every lane stores +/// `v2 + (v3 << 16) + (v1 << 24)`. `late`: stores `s30` too, a scalar the +/// loop writes. +fn break_loop(breaks: Breaks, late: bool) -> Vec { let mut w = PROLOGUE.to_vec(); w.extend([ 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 0x7E02_0280, // v_mov_b32 v1, 0 0x7E04_0280, // v_mov_b32 v2, 0 - if narrow { - 0x360A_0087 // v_and_b32 v5, 7, v0 - } else { - 0x7E0A_0287 // v_mov_b32 v5, 7 - }, - 0xBEA4_047E, // s_mov_b64 s[36:37], exec - 0xBF82_0003, // s_branch (the test) + 0x7E06_0280, // v_mov_b32 v3, 0 + ]); + match breaks { + Breaks::ByLane => w.push(0x360A_0083), // v_and_b32 v5, 3, v0 + Breaks::AllEarly => w.push(0x360A_0081), // v_and_b32 v5, 1, v0 + Breaks::ByHalf => w.extend([ + 0x2C0A_0085, // v_lshrrev_b32 v5, 5, v0 + 0x360A_0A83, // v_and_b32 v5, 3, v5 + ]), + } + w.extend([ + 0xBE9E_0380, // s_mov_b32 s30, 0 + 0xBE9A_047E, // s_mov_b64 s[26:27], exec + 0xBE96_047E, // s_mov_b64 s[22:23], exec + // the loop 0x7E0C_0500, // v_readfirstlane_b32 s6, v0 0x4A04_0406, // v_add_nc_u32 v2, s6, v2 - 0x4A02_0281, // v_add_nc_u32 v1, 1, v1 - 0x7D82_0B01, // v_cmp_lt_u32 vcc, v1, v5 + 0x4A06_0681, // v_add_nc_u32 v3, 1, v3 + 0x7DA4_0A1E, // v_cmpx_eq_u32 exec, s30, v5 + 0x7E02_0281, // v_mov_b32 v1, 1 + 0x8A9A_7E1A, // s_andn2_b64 s[26:27], s[26:27], exec + 0xBF84_0005, // s_cbranch_scc0 (past the loop) + 0x87FE_1A16, // s_and_b64 exec, s[22:23], s[26:27] + 0x811E_811E, // s_add_i32 s30, s30, 1 + 0xBF02_821E, // s_cmp_gt_i32 s30, 2 + 0xBF84_FFF5, // s_cbranch_scc0 (the loop) + 0x7E02_0282, // v_mov_b32 v1, 2 + // past the loop + 0xBEFE_0416, // s_mov_b64 exec, s[22:23] + 0x3406_0690, // v_lshlrev_b32 v3, 16, v3 + 0x3402_0298, // v_lshlrev_b32 v1, 24, v1 + 0x4A04_0503, // v_add_nc_u32 v2, v3, v2 + 0x4A04_0501, // v_add_nc_u32 v2, v1, v2 ]); - if narrow { - w.extend([ - 0x87FE_6A7E, // s_and_b64 exec, exec, vcc - 0xBF89_FFFA, // s_cbranch_execnz (the body) - ]); - } else { - w.extend([ - 0x87EA_6A7E, // s_and_b64 vcc, exec, vcc - 0xBF87_FFFA, // s_cbranch_vccnz (the body) - ]); - } - w.push(0xBEFE_0424); // s_mov_b64 exec, s[36:37] w.extend(store(2, 0)); + if late { + w.push(0x7E08_021E); // v_mov_b32 v4, s30 + w.extend(store(4, 4)); + } w.push(S_ENDPGM); w } -/// What every lane of [`while_loop_first_lane`] stores on the console: the -/// first lane still in the loop in each pass is the console wave's thread -/// `64 * wave + pass + 1` (narrow), or its first, `64 * wave`, in all 7 -/// passes. -fn console_while_loop_first_lane(narrow: bool, t: u32) -> u32 { - let base = t & !63; - if narrow { - let n = t & 7; - n * base + n * (n + 1) / 2 - } else { - 7 * base - } -} - #[test] -fn the_while_loop_programs_are_what_their_comments_say() { - for narrow in [false, true] { - let words = while_loop_first_lane(narrow); - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let all = gfx10::decode(&code) - .expect("decodes") - .iter() - .map(|i| i.text(true)) - .collect::>() - .join("\n"); - let tail: &[&str] = if narrow { - &["s_and_b64 exec, exec, vcc", "s_cbranch_execnz"] - } else { - &["s_and_b64 vcc, exec, vcc", "s_cbranch_vccnz"] - }; - let bound = if narrow { - "v_and_b32 v5, 7, v0" - } else { - "v_mov_b32 v5, 7" - }; - for want in [ - bound, - "s_mov_b64 s[36:37], exec", - "s_branch", - "v_readfirstlane_b32 s6, v0", - "v_add_nc_u32 v2, s6, v2", - "v_add_nc_u32 v1, 1, v1", - "v_cmp_lt_u32 vcc, v1, v5", - "s_mov_b64 exec, s[36:37]", - ] +fn the_index_waterfall_programs_are_what_their_comments_say() { + let words = index_waterfall(true, &[], &[]); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let all = gfx10::decode(&code) + .expect("decodes") .iter() - .chain(tail) - { - assert!(all.contains(want), "{want:?} not in:\n{all}"); - } + .map(|i| i.text(true)) + .collect::>() + .join("\n"); + for want in [ + "v_add_nc_u32 v3, lit(0x00000000), v0", + "v_add_nc_u32 v10, lit(0x00001b58), v0", + "v_lshrrev_b32 v28, 2, v0", + "v_and_b32 v28, 7, v28", + "s_mov_b64 s[36:37], exec", + "v_readfirstlane_b32 s38, v28", + "v_cmp_eq_u32 vcc, s38, v28", + "s_and_saveexec_b64 s[6:7], vcc", + "s_mov_b32 m0, s38", + "v_movrels_b32 v31, v3", + "s_xor_b64 exec, exec, s[6:7]", + "s_cbranch_execnz", + "s_mov_b64 exec, s[36:37]", + ] { + assert!(all.contains(want), "{want:?} not in:\n{all}"); } } -/// A first-lane read in a `while` loop (its exit test before the latch's -/// work, as GTA VI's `23d507cbb6a22e86` and `b0095eb50222e808` have) runs in -/// halves with the loop in lockstep: the group stays while any lane stays, -/// so the halves meet in every pass and pass the console wave's first lane -/// between them. Before, the read was refused there. +/// The first-lane read opening a register-index waterfall is made by each +/// host half by itself: the program needs no halves for it, and translates +/// in halves too although the read is in a loop (#522 sent GTA VI's +/// `11eeb27c2d15980d` to halves for it, which refused it). Where the read's +/// result is seen after the loop, or the loop body does scalar work, whose +/// iterations the halves would see, the read still takes halves (refused +/// where they cannot meet). #[test] -fn a_first_lane_read_in_a_while_loop_translates_in_halves() { - for narrow in [false, true] { - for threads in [64, 128, 256] { - let words = while_loop_first_lane(narrow); - let l = lowered(&native(&words, true, threads, 0), true) - .unwrap_or_else(|e| panic!("narrow={narrow} {threads} threads: {e}")); - assert_eq!(l.wave_size, Some(32)); - assert!(l.barriers > 0, "the halves meet in the loop"); - } +fn a_register_index_waterfall_is_made_in_each_half() { + let across = "a first-lane read of a value that may differ between 32-lane halves"; + let halves = |words: &[u32], threads: u32| match lowered(&native(words, true, threads, 0), true) + { + Ok(l) => l.wave_size == Some(32), + Err(e) => e.to_string().contains(across), + }; + for threads in [64, 128] { + assert!(!halves(&index_waterfall(false, &[], &[]), threads)); + assert!(halves(&index_waterfall(true, &[], &[]), threads)); + // v_mov_b32 v31, s38 after the loop + assert!(halves( + &index_waterfall(false, &[], &[0x7E3E_0226]), + threads + )); + // s_add_u32 s50, s50, 1 in the body + assert!(halves( + &index_waterfall(false, &[0x8032_8132], &[]), + threads + )); } } -/// The read in a `while` loop gives the console's lanes on every GPU. +/// The register-index waterfall gives the console's lanes on every GPU, in +/// halves and not: `((thread id >> 2) & 7) * 1000 + thread id` in every +/// lane. #[cfg(windows)] #[test] -fn a_first_lane_read_in_a_while_loop_matches_the_console_on_every_gpu() { +fn a_register_index_waterfall_matches_the_console_on_every_gpu() { let mut failed = Vec::new(); - for narrow in [false, true] { - for threads in [64, 128] { - let words = while_loop_first_lane(narrow); - let want: Vec = (0..threads) - .map(|t| console_while_loop_first_lane(narrow, t)) - .collect(); + for threads in [64, 128] { + let want: Vec = (0..threads).map(|t| ((t >> 2) & 7) * 1000 + t).collect(); + for with_mbcnt in [false, true] { + let words = index_waterfall(with_mbcnt, &[], &[]); failed.extend( differences(&words, threads, 1, &want) .into_iter() - .map(|m| format!("narrow={narrow} {threads} threads: {m}")), + .map(|m| format!("{threads} threads (mbcnt={with_mbcnt}): {m}")), ); } } assert!(failed.is_empty(), "{}", failed.join("\n")); } -/// [`while_loop_first_lane`] (the form lanes leave one by one: a lane stays -/// while `v1 < (tid & 7)`) with a store in its body: each pass a lane makes -/// stores its count of passes `v1` at dword `v1` of its own eight. A lane -/// that has left the loop stores no more. -fn while_loop_with_a_store() -> Vec { +/// What each thread of a group of `threads` stores in [`break_loop`] on the +/// console: its wave64s run by the instructions' own rules. +#[cfg(windows)] +fn console_break_loop(breaks: Breaks, threads: u32) -> Vec { + let mut out = vec![0; threads as usize]; + for base in (0..threads).step_by(64) { + let lanes: Vec = (base..threads.min(base + 64)).collect(); + let v5 = |t: u32| match breaks { + Breaks::ByLane => t & 3, + Breaks::AllEarly => t & 1, + Breaks::ByHalf => t >> 5 & 3, + }; + let (mut v1, mut v2, mut v3) = (vec![0u32; 64], vec![0u32; 64], vec![0u32; 64]); + let mut left = vec![true; lanes.len()]; + let mut pass = 0; + loop { + let first = lanes[left.iter().position(|&l| l).expect("a lane is left")]; + for (n, &t) in lanes.iter().enumerate() { + if !left[n] { + continue; + } + v2[n] += first; + v3[n] += 1; + if v5(t) == pass { + v1[n] = 1; + left[n] = false; + } + } + if !left.contains(&true) { + break; + } + pass += 1; + if pass > 2 { + for n in 0..lanes.len() { + if left[n] { + v1[n] = 2; + } + } + break; + } + } + for (n, &t) in lanes.iter().enumerate() { + out[t as usize] = v2[n] + (v3[n] << 16) + (v1[n] << 24); + } + } + out +} + +/// A loop of three passes whose body is a guard in a guard, both skipping +/// to the loop's end (`if (a) { if (b) { .. } }`, as in GTA VI's +/// `9991e29feaa26e3e` at 0x2158): in the inner one, a first-lane read +/// (`v_readfirstlane_b32 s6, v0`) into an accumulator `v2`, which every +/// lane stores. The outer guard takes the odd lanes, or with `upper` the +/// upper half of each console wave; the inner one the lanes with bit 1. +fn nested_guards_first_lane(upper: bool) -> Vec { let mut w = PROLOGUE.to_vec(); w.extend([ 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 - 0x7E02_0280, // v_mov_b32 v1, 0 0x7E04_0280, // v_mov_b32 v2, 0 - 0x360A_0087, // v_and_b32 v5, 7, v0 - 0xBEA4_047E, // s_mov_b64 s[36:37], exec - 0xBF82_0007, // s_branch (the test) + 0xBE9E_0380, // s_mov_b32 s30, 0 + // the loop + if upper { + 0x2C0A_0085 // v_lshrrev_b32 v5, 5, v0 + } else { + 0x7E0A_0300 // v_mov_b32 v5, v0 + }, + 0x360A_0A81, // v_and_b32 v5, 1, v5 + 0x7D84_0A81, // v_cmp_eq_u32 vcc, 1, v5 + 0xBE9C_246A, // s_and_saveexec_b64 s[28:29], vcc + 0xBF88_0006, // s_cbranch_execz (the loop's end) + 0x360C_0082, // v_and_b32 v6, 2, v0 + 0x7D84_0C82, // v_cmp_eq_u32 vcc, 2, v6 + 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc + 0xBF88_0002, // s_cbranch_execz (the loop's end) 0x7E0C_0500, // v_readfirstlane_b32 s6, v0 0x4A04_0406, // v_add_nc_u32 v2, s6, v2 - 0x4A02_0281, // v_add_nc_u32 v1, 1, v1 - 0x3422_0282, // v_lshlrev_b32 v17, 2, v1 - 0x4A22_2310, // v_add_nc_u32 v17, v16, v17 - 0xE070_1000, - 0x800A_0111, // buffer_store_dword v1, v17, s[40:43], 0 offen - 0x7D82_0B01, // v_cmp_lt_u32 vcc, v1, v5 - 0x87FE_6A7E, // s_and_b64 exec, exec, vcc - 0xBF89_FFF6, // s_cbranch_execnz (the body) - 0xBEFE_0424, // s_mov_b64 exec, s[36:37] + // the loop's end + 0xBEFE_041C, // s_mov_b64 exec, s[28:29] + 0x811E_811E, // s_add_i32 s30, s30, 1 + 0xBF02_821E, // s_cmp_gt_i32 s30, 2 + 0xBF84_FFF1, // s_cbranch_scc0 (the loop) ]); w.extend(store(2, 0)); w.push(S_ENDPGM); w } +/// What thread `t` of a group of `threads` stores in +/// [`nested_guards_first_lane`] on the console: three times the first +/// thread of its wave64 that both guards take, if they take it. +#[cfg(windows)] +fn console_nested_guards_first_lane(upper: bool, threads: u32, t: u32) -> u32 { + let takes = |t: u32| (if upper { t >> 5 } else { t }) & 1 == 1 && t & 2 == 2; + let base = t & !63; + let first = (base..threads.min(base + 64)).find(|&l| takes(l)); + match first { + Some(first) if takes(t) => 3 * first, + _ => 0, + } +} + #[test] -fn the_while_loop_with_a_store_is_what_its_comments_say() { - let words = while_loop_with_a_store(); - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let text: Vec = gfx10::decode(&code) - .expect("decodes") - .iter() - .map(|i| i.text(true)) - .collect(); +fn the_break_loop_programs_are_what_their_comments_say() { + let text = |words: &[u32]| { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + gfx10::decode(&code) + .expect("decodes") + .iter() + .map(|i| i.text(true)) + .collect::>() + }; + // The prologue's five words are four instructions. + let skip = PROLOGUE.len() - 1; + let all = text(&break_loop(Breaks::ByHalf, true)); let want = [ "v_lshlrev_b32 v16, 5, v0", "v_mov_b32 v1, 0", "v_mov_b32 v2, 0", - "v_and_b32 v5, 7, v0", - "s_mov_b64 s[36:37], exec", - "s_branch", + "v_mov_b32 v3, 0", + "v_lshrrev_b32 v5, 5, v0", + "v_and_b32 v5, 3, v5", + "s_mov_b32 s30, 0", + "s_mov_b64 s[26:27], exec", + "s_mov_b64 s[22:23], exec", "v_readfirstlane_b32 s6, v0", "v_add_nc_u32 v2, s6, v2", - "v_add_nc_u32 v1, 1, v1", - "v_lshlrev_b32 v17, 2, v1", - "v_add_nc_u32 v17, v16, v17", - "buffer_store_dword v1, v17, s[40:43], 0 offen", - "v_cmp_lt_u32 vcc, v1, v5", - "s_and_b64 exec, exec, vcc", - "s_cbranch_execnz", - "s_mov_b64 exec, s[36:37]", + "v_add_nc_u32 v3, 1, v3", + "v_cmpx_eq_u32 exec, s30, v5", + "v_mov_b32 v1, 1", + "s_andn2_b64 s[26:27], s[26:27], exec", + "s_cbranch_scc0", + "s_and_b64 exec, s[22:23], s[26:27]", + "s_add_i32 s30, s30, 1", + "s_cmp_gt_i32 s30, 2", + "s_cbranch_scc0", + "v_mov_b32 v1, 2", + "s_mov_b64 exec, s[22:23]", + "v_lshlrev_b32 v3, 16, v3", + "v_lshlrev_b32 v1, 24, v1", + "v_add_nc_u32 v2, v3, v2", + "v_add_nc_u32 v2, v1, v2", ]; - // The prologue's five words are four instructions. for (n, want) in want.iter().enumerate() { - let got = &text[PROLOGUE.len() - 1 + n]; + let got = &all[skip + n]; assert!(got.starts_with(want), "{n}: {got:?}, not {want:?}"); } + assert!(all.iter().any(|t| t == "v_mov_b32 v4, s30"), "{all:?}"); + let has = |words: &[u32], want: &str| text(words).iter().any(|t| t == want); + assert!(has(&break_loop(Breaks::ByLane, false), "v_and_b32 v5, 3, v0")); + assert!(has(&break_loop(Breaks::AllEarly, false), "v_and_b32 v5, 1, v0")); + let all = text(&nested_guards_first_lane(true)); + let want = [ + "v_lshlrev_b32 v16, 5, v0", + "v_mov_b32 v2, 0", + "s_mov_b32 s30, 0", + "v_lshrrev_b32 v5, 5, v0", + "v_and_b32 v5, 1, v5", + "v_cmp_eq_u32 vcc, 1, v5", + "s_and_saveexec_b64 s[28:29], vcc", + "s_cbranch_execz", + "v_and_b32 v6, 2, v0", + "v_cmp_eq_u32 vcc, 2, v6", + "s_and_saveexec_b64 s[12:13], vcc", + "s_cbranch_execz", + "v_readfirstlane_b32 s6, v0", + "v_add_nc_u32 v2, s6, v2", + "s_mov_b64 exec, s[28:29]", + "s_add_i32 s30, s30, 1", + "s_cmp_gt_i32 s30, 2", + "s_cbranch_scc0", + ]; + for (n, want) in want.iter().enumerate() { + let got = &all[skip + n]; + assert!(got.starts_with(want), "{n}: {got:?}, not {want:?}"); + } + assert!(has(&nested_guards_first_lane(false), "v_mov_b32 v5, v0")); } -/// A store in a `while` loop run in lockstep is made by the lanes still in -/// the loop only: a lane that left keeps running the body with the group, -/// inactive, and stores nothing. Each lane's dwords 1 to `tid & 7` hold -/// their own index, the rest stay 0; dword 0 is the accumulator of -/// [`console_while_loop_first_lane`]. +/// A first-lane read in a counted loop that lanes break out of one by one +/// runs in halves: the break is predicated away (the lanes that broke stay +/// in the loop, inactive, to its own end), so every lane of the group runs +/// every pass and the halves pass the console wave's first lane left +/// between them. Before, the read was refused there. +#[test] +fn a_first_lane_read_in_a_loop_lanes_break_out_of_translates_in_halves() { + for breaks in [Breaks::ByLane, Breaks::AllEarly, Breaks::ByHalf] { + for threads in [64, 128, 256] { + let words = break_loop(breaks, false); + let l = lowered(&native(&words, true, threads, 0), true) + .unwrap_or_else(|e| panic!("{breaks:?} {threads} threads: {e}")); + assert_eq!(l.wave_size, Some(32)); + assert!(l.barriers > 0, "the halves meet in the loop"); + } + } +} + +/// A scalar the loop writes, read after it, keeps the break as it is: the +/// console wave leaves once its every lane broke, with the count of that +/// pass, and the lanes kept in the loop would count on. The read stays +/// refused. +#[test] +fn a_loop_lanes_break_out_of_whose_count_is_read_after_it_is_refused() { + for threads in [64, 128] { + let words = break_loop(Breaks::AllEarly, true); + let e = lowered(&native(&words, true, threads, 0), true) + .err() + .unwrap_or_else(|| panic!("{threads} threads: translated")); + assert!(e.to_string().contains("a first-lane read"), "{e}"); + } +} + +/// A first-lane read under a guard in a guard, both skipping to one join, +/// runs in halves: the region is laid out flat, the inner guard's body in +/// step with it. Before, only the outer guard's own block was, and the +/// read was refused. +#[test] +fn a_first_lane_read_under_nested_guards_translates_in_halves() { + for upper in [false, true] { + for threads in [64, 128, 256] { + let words = nested_guards_first_lane(upper); + let l = lowered(&native(&words, true, threads, 0), true) + .unwrap_or_else(|e| panic!("upper={upper} {threads} threads: {e}")); + assert_eq!(l.wave_size, Some(32)); + assert!(l.barriers > 0, "the halves meet at the read"); + } + } +} + +/// Both give the console's lanes on every GPU. #[cfg(windows)] #[test] -fn a_store_in_a_while_loop_is_made_by_the_lanes_still_in_it_on_every_gpu() { - let words = while_loop_with_a_store(); +fn first_lane_reads_past_a_break_and_under_nested_guards_match_the_console_on_every_gpu() { let mut failed = Vec::new(); for threads in [64, 128] { - let want: Vec = (0..threads) - .flat_map(|t| { - let n = t & 7; - let mut lane = [0; 8]; - lane[0] = console_while_loop_first_lane(true, t); - for p in 1..=n { - lane[p as usize] = p; - } - lane - }) - .collect(); - failed.extend( - differences(&words, threads, 8, &want) - .into_iter() - .map(|m| format!("{threads} threads: {m}")), - ); + for breaks in [Breaks::ByLane, Breaks::AllEarly, Breaks::ByHalf] { + let words = break_loop(breaks, false); + let want = console_break_loop(breaks, threads); + failed.extend( + differences(&words, threads, 1, &want) + .into_iter() + .map(|m| format!("{breaks:?} {threads} threads: {m}")), + ); + } + for upper in [false, true] { + let words = nested_guards_first_lane(upper); + let want: Vec = (0..threads) + .map(|t| console_nested_guards_first_lane(upper, threads, t)) + .collect(); + failed.extend( + differences(&words, threads, 1, &want) + .into_iter() + .map(|m| format!("nested upper={upper} {threads} threads: {m}")), + ); + } } assert!(failed.is_empty(), "{}", failed.join("\n")); } -/// [`native`] for a group of two dimensions: thread ids x and y in `v0` and -/// `v1`, the group's x in `s1` (after the one user-data SGPR). -fn native_2d(words: &[u32], threads: [u32; 2]) -> NativeProgram { - let mut n = native(words, true, threads[0] * threads[1], 0); - n.io = StageIo::Cs(ComputeIo { - // One user-data SGPR, the group's x (bit 7), thread ids x and y - // (bits 11-12: 1). - rsrc2: 1 << 1 | 1 << 7 | 1 << 11, - threads: [threads[0], threads[1], 1], - }); - n +/// How a full-LDS program reaches its halves exchange. +#[derive(Clone, Copy, Debug)] +enum Exchanges { + /// One ballot read as data. + One, + /// Two back to back. + Two, + /// One in a loop of 3 trips, each adding 1 to the dwords the exchange + /// borrows (the first 1,024) first. + Loop, } -/// [`while_loop_with_a_store`] in a group `width` threads wide (8 or 16), of -/// several rows, in a dispatch of several groups: the thread's flat id -/// `width y + x` is in `v0`, and a lane stays while -/// `v1 < ((flat + group) & 7)`, so the lanes leave at passes that differ -/// from group to group. Each lane has 16 dwords at -/// `(256 group + flat) * 64`: the accumulator of first lanes, its passes -/// at dwords 1 to 7, `flat + 1` added (atomically, so a thread id two -/// host lanes hold shows) at dword 8, and its count of passes at dword 9. `forever`: no lane ever leaves (the -/// loop then runs to the translation's limit of passes), and no pass stores. -fn while_loop_in_rows(forever: bool, width: u32) -> Vec { +/// What the program adds to dwords 0..1023 before reading them back. +const fn full_lds_bump(e: Exchanges) -> u32 { + match e { + Exchanges::Loop => 3, + _ => 0, + } +} + +/// A 1,024-thread wave64 program that fills all 8,192 dwords of its LDS +/// (thread t writes dword `t + 1024k` = `t + 1024k + 0xA500_0000` for k +/// 0-7), passes a ballot between the halves (`e`), and reads all eight of +/// another wave's dwords back (thread t reads those of `(t + 32) % 1024`). +/// Per lane: the ballots' lane count, the OR of every difference from what +/// was written (0 when the LDS came back byte for byte), and its own dword +/// `t` as it is at the end. +fn full_lds_program(e: Exchanges) -> Vec { + const BASE: u32 = 0xA500_0000; + let bump = full_lds_bump(e); + let ds_write = |offset: u32| [0xD834_0000 | offset, 0x0000_0401]; // ds_write_b32 v1, v4 offset: + let ds_read = |offset: u32| [0xD8D8_0000 | offset, 0x0E00_000A]; // ds_read_b32 v14, v10 offset: let mut w = PROLOGUE.to_vec(); w.extend([ - 0x3406_0280 | width.trailing_zeros(), // v_lshlrev_b32 v3, 3 or 4, v1 - 0x4A00_0700, // v_add_nc_u32 v0, v0, v3 - 0x3420_0086, // v_lshlrev_b32 v16, 6, v0 - 0x7E08_0201, // v_mov_b32 v4, s1 - 0x3408_088E, // v_lshlrev_b32 v4, 14, v4 - 0x4A20_0910, // v_add_nc_u32 v16, v16, v4 - 0x4A0C_0001, // v_add_nc_u32 v6, s1, v0 - 0x7E02_0280, // v_mov_b32 v1, 0 - 0x7E04_0280, // v_mov_b32 v2, 0 - if forever { - 0x7E0A_02C1 // v_mov_b32 v5, -1 - } else { - 0x360A_0C87 // v_and_b32 v5, 7, v6 - }, - 0xBEA4_047E, // s_mov_b64 s[36:37], exec + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x3402_0082, // v_lshlrev_b32 v1, 2, v0 + 0x4A04_00FF, + BASE, // v_add_nc_u32 v2, BASE, v0 + ]); + for k in 0..8u32 { + w.extend([0x4A08_04FF, 1024 * k]); // v_add_nc_u32 v4, 1024k, v2 + w.extend(ds_write(4096 * k)); + } + w.extend([ + S_WAITCNT_LGKM, + 0xBF8A_0000, // s_barrier + 0x360E_00BF, // v_and_b32 v7, 63, v0 + ]); + // Lanes 0-39 of each console wave: 40 a ballot. + let ballot = [ + 0x7D88_0EA8, // v_cmp_gt_u32 vcc, 40, v7 + 0xBE8C_106A, // s_bcnt1_i32_b64 s12, vcc + ]; + match e { + Exchanges::One => w.extend(ballot), + Exchanges::Two => { + w.extend(ballot); + w.extend([ + 0x7D88_0E94, // v_cmp_gt_u32 vcc, 20, v7 + 0xBE8D_106A, // s_bcnt1_i32_b64 s13, vcc + 0x800C_0D0C, // s_add_u32 s12, s12, s13 + ]); + } + Exchanges::Loop => { + w.extend([ + 0x7E12_0281, // v_mov_b32 v9, 1 + 0xBE94_0380, // s_mov_b32 s20, 0 + 0xBE8E_0380, // s_mov_b32 s14, 0 + ]); + let top = w.len(); + w.extend([0xD800_0000, 0x0000_0901]); // ds_add_u32 v1, v9 + w.extend(ballot); + w.extend([ + 0x800E_0C0E, // s_add_u32 s14, s14, s12 + 0x8014_8114, // s_add_u32 s20, s20, 1 + 0xBF0A_8314, // s_cmp_lt_u32 s20, 3 + ]); + let back = (top as i32 - (w.len() as i32 + 1)) as u16; + w.push(0xBF85_0000 | u32::from(back)); // s_cbranch_scc1 top + w.push(0xBE8C_030E); // s_mov_b32 s12, s14 + } + } + w.extend([ + S_WAITCNT_LGKM, + 0xBF8A_0000, // s_barrier + 0x4A1A_00A0, // v_add_nc_u32 v13, 32, v0 + 0x361A_1AFF, + 0x0000_03FF, // v_and_b32 v13, 1023, v13 + 0x3414_1A82, // v_lshlrev_b32 v10, 2, v13 + 0x4A18_1AFF, + BASE, // v_add_nc_u32 v12, BASE, v13 + 0x7E16_0280, // v_mov_b32 v11, 0 ]); - if forever { - w.extend([ - 0xBF82_0003, // s_branch (the test) - 0x7E0C_0500, // v_readfirstlane_b32 s6, v0 - 0x4A04_0406, // v_add_nc_u32 v2, s6, v2 - 0x4A02_0281, // v_add_nc_u32 v1, 1, v1 - 0x7D82_0B01, // v_cmp_lt_u32 vcc, v1, v5 - 0x87FE_6A7E, // s_and_b64 exec, exec, vcc - 0xBF89_FFFA, // s_cbranch_execnz (the body) - ]); - } else { + for k in 0..8u32 { + w.extend(ds_read(4096 * k)); w.extend([ - 0xBF82_0007, // s_branch (the test) - 0x7E0C_0500, // v_readfirstlane_b32 s6, v0 - 0x4A04_0406, // v_add_nc_u32 v2, s6, v2 - 0x4A02_0281, // v_add_nc_u32 v1, 1, v1 - 0x3422_0282, // v_lshlrev_b32 v17, 2, v1 - 0x4A22_2310, // v_add_nc_u32 v17, v16, v17 - 0xE070_1000, - 0x800A_0111, // buffer_store_dword v1, v17, s[40:43], 0 offen - 0x7D82_0B01, // v_cmp_lt_u32 vcc, v1, v5 - 0x87FE_6A7E, // s_and_b64 exec, exec, vcc - 0xBF89_FFF6, // s_cbranch_execnz (the body) + S_WAITCNT_LGKM, + 0x4A1E_18FF, + 1024 * k + if k == 0 { bump } else { 0 }, // v_add_nc_u32 v15, what was written, v12 + 0x3A1C_1F0E, // v_xor_b32 v14, v14, v15 + 0x3816_1D0B, // v_or_b32 v11, v11, v14 ]); } w.extend([ - 0xBEFE_0424, // s_mov_b64 exec, s[36:37] - 0x4A0E_0081, // v_add_nc_u32 v7, 1, v0 - 0xE0C8_1020, - 0x800A_0710, // buffer_atomic_add v7, v16, s[40:43], 0 offen offset:32 + 0xD8D8_0000, + 0x1100_0001, // ds_read_b32 v17, v1 + S_WAITCNT_LGKM, + 0x7E06_020C, // v_mov_b32 v3, s12 ]); - w.extend(store(1, 36)); - w.extend(store(2, 0)); + w.extend(store(3, 0)); + w.extend(store(11, 4)); + w.extend(store(17, 8)); w.push(S_ENDPGM); w } +/// What each lane of [`full_lds_program`] stores. +fn full_lds_want(e: Exchanges) -> Vec { + let count = match e { + Exchanges::One => 40, + Exchanges::Two => 60, + Exchanges::Loop => 120, + }; + (0..1024u32) + .flat_map(|t| [count, 0, t + 0xA500_0000 + full_lds_bump(e)]) + .collect() +} + +/// The program's words are the instructions their comments name. #[test] -fn the_while_loop_in_rows_is_what_its_comments_say() { - for (forever, width) in [(false, 8), (true, 8), (false, 16)] { - let words = while_loop_in_rows(forever, width); +fn the_full_lds_programs_are_what_their_comments_say() { + for e in [Exchanges::One, Exchanges::Two, Exchanges::Loop] { + let words = full_lds_program(e); let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let text: Vec = gfx10::decode(&code) - .expect("decodes") + let p = ir::build(&code, true, 256).unwrap(); + let insts: Vec<_> = p.blocks.iter().flat_map(|b| b.insts.iter()).collect(); + let count = |name: &str| insts.iter().filter(|i| i.name() == name).count(); + assert_eq!(count("ds_write_b32"), 8, "{e:?}"); + assert_eq!(count("ds_read_b32"), 9, "{e:?}"); + assert_eq!(count("s_barrier"), 2, "{e:?}"); + for name in [ + "v_lshlrev_b32", + "v_add_nc_u32", + "v_and_b32", + "v_xor_b32", + "v_or_b32", + "v_cmp_gt_u32", + "s_bcnt1_i32_b64", + "buffer_store_dword", + ] { + assert!(count(name) > 0, "{e:?}: no {name}"); + } + let offsets: Vec = insts .iter() - .map(|i| i.text(true)) + .filter(|i| i.name() == "ds_write_b32") + .map(|i| match &i.fields { + gfx10::Fields::Ds { + offset0, offset1, .. + } => i32::from(*offset1) << 8 | i32::from(*offset0), + _ => -1, + }) .collect(); - let bound = if forever { - "v_mov_b32 v5, -1" - } else { - "v_and_b32 v5, 7, v6" - }; - let rows = if width == 8 { - "v_lshlrev_b32 v3, 3, v1" - } else { - "v_lshlrev_b32 v3, 4, v1" - }; - let mut want = vec![ - rows, - "v_add_nc_u32 v0, v0, v3", - "v_lshlrev_b32 v16, 6, v0", - "v_mov_b32 v4, s1", - "v_lshlrev_b32 v4, 14, v4", - "v_add_nc_u32 v16, v16, v4", - "v_add_nc_u32 v6, s1, v0", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - bound, - "s_mov_b64 s[36:37], exec", - "s_branch", - "v_readfirstlane_b32 s6, v0", - "v_add_nc_u32 v2, s6, v2", - "v_add_nc_u32 v1, 1, v1", - ]; - if !forever { - want.extend([ - "v_lshlrev_b32 v17, 2, v1", - "v_add_nc_u32 v17, v16, v17", - "buffer_store_dword v1, v17, s[40:43], 0 offen", - ]); - } - want.extend([ - "v_cmp_lt_u32 vcc, v1, v5", - "s_and_b64 exec, exec, vcc", - "s_cbranch_execnz", - "s_mov_b64 exec, s[36:37]", - "v_add_nc_u32 v7, 1, v0", - "buffer_atomic_add v7, v16, s[40:43], 0 offen offset:32", - "buffer_store_dword v1, v16, s[40:43], 0 offen offset:36", - ]); - // The prologue's five words are four instructions. - for (n, want) in want.iter().enumerate() { - let got = &text[PROLOGUE.len() - 1 + n]; - assert!(got.starts_with(want), "{n}: {got:?}, not {want:?}"); + assert_eq!(offsets, (0..8).map(|k| 4096 * k).collect::>()); + if let Exchanges::Loop = e { + assert_eq!(count("ds_add_u32"), 1); + assert_eq!(count("s_cbranch_scc1"), 1); + assert!(p.blocks.len() >= 3); } } } -/// What the console stores for [`while_loop_in_rows`]'s lanes of group -/// `group`, `lanes` threads in console waves of 64: 16 dwords each. +/// A program whose own LDS is the host's whole 32 KiB passes values between +/// its halves through dwords it borrows from that LDS. +#[test] +fn halves_exchange_in_a_program_that_fills_the_lds() { + for e in [Exchanges::One, Exchanges::Two, Exchanges::Loop] { + let words = full_lds_program(e); + let full = lowered_with(&native(&words, true, 1024, 32768), true, true) + .unwrap_or_else(|why| panic!("{e:?}: {why}")); + assert_eq!(full.wave_size, Some(32)); + } +} + +#[test] #[cfg(windows)] -fn console_while_loop_in_rows(lanes: u32, group: u32) -> Vec<[u32; 16]> { - let stays = |t: u32| (t + group) & 7; - (0..lanes) - .map(|t| { - let mut lane = [0; 16]; - let wave = (t & !63)..lanes.min((t & !63) + 64); - for pass in 0..stays(t) { - // The first lane of its wave still in the loop in this pass. - lane[0] += wave.clone().find(|&f| stays(f) > pass).expect("this one"); - lane[pass as usize + 1] = pass + 1; - } - lane[8] = t + 1; - lane[9] = stays(t); - lane - }) - .collect() +fn halves_give_back_borrowed_lds_on_every_gpu() { + let mut failed = Vec::new(); + for e in [Exchanges::One, Exchanges::Two, Exchanges::Loop] { + failed.extend( + differences_with( + &full_lds_program(e), + 1024, + 3, + &full_lds_want(e), + 32768, + true, + ) + .into_iter() + .map(|f| format!("{e:?}: {f}")), + ); + } + assert!(failed.is_empty(), "{}", failed.join("\n")); } -/// A `while` loop in lockstep translates in halves in groups of rows. +/// Which programs know a dispatch's count of threads: those of one +/// dimension, only when the translation asks for it; not literal halves. +/// Where no lane waits for another the lanes past the count leave at the +/// start; with a group barrier or in 32-lane halves that pass values they +/// stay, outside EXEC. The word is past the console's user data and names +/// the group's width. #[test] -fn a_while_loop_in_rows_translates_in_halves() { - for threads in [[8, 8], [8, 6], [16, 16]] { - for forever in [false, true] { - let n = native_2d(&while_loop_in_rows(forever, threads[0]), threads); - let l = - lowered(&n, true).unwrap_or_else(|e| panic!("{threads:?} forever={forever}: {e}")); - assert_eq!(l.wave_size, Some(32)); - assert!(l.barriers > 0, "the halves meet in the loop"); - } +fn only_programs_whose_lanes_never_wait_leave_past_a_count_of_threads() { + let limited = |words: &[u32], wave64, threads, host_wave32| { + let n = native(words, wave64, threads, 0); + let l = lower_halves_limited(&n, host_wave32, true, true, true).expect("translates"); + thread_limit(&l) + }; + let plain = counted_lanes(&[]); + let word = limited(&plain, false, 64, true).expect("a word for the count"); + assert_eq!( + (word.index, word.dword), + (1, 64), + "past the one user-data SGPR" + ); + assert_eq!( + limited(&plain, true, 64, true).map(|u| u.dword), + Some(64), + "wave64 in 32-lane waves" + ); + let n = native(&plain, false, 64, 0); + assert_eq!( + thread_limit(&lower_halves(&n, true, true, false).unwrap()), + None, + "not asked for" + ); + assert_eq!( + limited(&plain, false, 1, true), + None, + "a group of one thread" + ); + let mut flat = native(&plain, false, 64, 0); + flat.io = StageIo::Cs(ComputeIo { + rsrc2: 1 << 1, + threads: [8, 8, 1], + }); + let l = lower_halves_limited(&flat, true, true, true, true).unwrap(); + assert_eq!(thread_limit(&l), None, "two dimensions"); + // s_barrier: lanes that left would never reach it. They stay, outside + // EXEC from the entry on. + assert!( + limited(&counted_lanes(&[0xBF8A_0000]), false, 64, true).is_some(), + "a group barrier" + ); + // v_mbcnt reads console lanes: a wave64 group of 64 runs in halves, + // which pass values between them at barriers (the lanes stay there + // too); one of 32 does not. + let lanes = counted_lanes(&[0xD765_0003, 0x0001_00C1]); + assert!(limited(&lanes, true, 64, true).is_some(), "in halves"); + assert!(limited(&lanes, true, 32, true).is_some(), "one host wave"); + assert!( + limited(&lanes, true, 64, false).is_some(), + "one host wave64" + ); + // A lane read across the halves, under a guard: in halves, the lanes + // stay. + let n = native(&literal_lane_reads(false), true, 64, 0); + let l = lower_halves_limited(&n, true, true, true, true).expect("in halves"); + assert!(thread_limit(&l).is_some(), "a lane read across the halves"); + // Literal halves take EXEC as the console wave's whole: no word there. + let n = native(&literal_exec_dwords(), true, 64, 0); + let l = lower_halves_limited(&n, true, true, true, true).expect("literal halves"); + assert_eq!(thread_limit(&l), None, "literal halves"); + let code: Vec = lanes.iter().flat_map(|w| w.to_le_bytes()).collect(); + let text: Vec = gfx10::decode(&code) + .unwrap() + .iter() + .map(|i| i.text(true)) + .collect(); + for want in [ + "v_mbcnt_lo_u32_b32 v3, -1, 0", + "v_lshlrev_b32 v1, 2, v0", + "v_mov_b32 v2, 1", + "buffer_atomic_add v2, v1, s[40:43], 0 offen", + ] { + assert!( + text.iter().any(|t| t.contains(want)), + "{want:?} not in {text:?}" + ); } + let code: Vec = [0xBF8A_0000u32, S_ENDPGM] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + assert_eq!(gfx10::decode(&code).unwrap()[0].text(true), "s_barrier"); } -/// A `while` loop in lockstep in groups of rows (8x8: two full host waves; -/// 8x6: 48 threads, the console wave's upper half 16 lanes; 16x16: four -/// console waves, as GTA VI's programs with such a loop have), several groups -/// to a dispatch, lanes leaving at different passes: every lane stores what -/// the console's does, its count of passes too, and each thread id is held -/// by one host lane. Left by no lane, the loop ends at the translation's -/// limit of passes in every lane of every group. -/// -/// A group that stayed in the loop after its last lane left would store -/// nothing more, so that shows only in time. Time does not tell here: on an -/// M5 Pro 2,048 groups of 8x8 took 22 to 25 ms, and 56 to 62 ms with every -/// group at the limit (16,383 passes, two exchanges each), so the times are -/// printed, not checked. +/// A dispatch counted in threads (`DispatchX`, after DexNom/VIctory +/// bc3cd4b0): of two groups of 64 only the lanes below the count run, in +/// wave32 and wave64 programs, and a count of 0 runs them all. Each lane +/// that runs adds 1 to the counter of its local x. On hardware devices +/// only, as the other halves tests that run programs. #[cfg(windows)] #[test] -fn a_while_loop_in_rows_matches_the_console_and_leaves_on_every_gpu() { +fn the_lanes_past_a_count_of_threads_do_not_run() { let _one = super::valu_tests::ONE_AT_A_TIME .lock() .unwrap_or_else(|e| e.into_inner()); @@ -5507,538 +5849,528 @@ fn a_while_loop_in_rows_matches_the_console_and_leaves_on_every_gpu() { eprintln!("no SM 6.6 hardware device; skipped"); return; } - let mut failed = Vec::new(); + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &[0; 4], + stride: Stride::Structured(16), + }, + View::RawUav(64), + ]; + // Plain (the lanes past the count leave at the start), with a group + // barrier, and reading console lanes (`v_mbcnt`: in halves where the + // host's waves are 32 lanes): in the last two the lanes stay, outside + // EXEC. + let extras: [(&str, &[u32]); 3] = [ + ("plain", &[]), + ("s_barrier", &[0xBF8A_0000]), + ("v_mbcnt", &[0xD765_0003, 0x0001_00C1]), + ]; for (adapter, host) in &hosts { - for threads in [[8u32, 8], [8, 6], [16, 16]] { - let lanes = threads[0] * threads[1]; - for narrow_waves in [false, true] { - let label = format!("{adapter} {threads:?} narrow_waves={narrow_waves}"); - let make = |forever: bool| { - let n = native_2d(&while_loop_in_rows(forever, threads[0]), threads); - let s = shader(lower_halves(&n, true, narrow_waves, false).expect("halves")); - if let Ok(mut v) = - validator::Validator::load(validator::Validator::default_path().as_deref()) - { - v.validate(&mut s.dxil.clone()) - .expect("DXIL validation failed"); - } - let Ok((root, pso)) = host.compute_pipeline(&s) else { - panic!("{label}: no pipeline"); - }; - (s, root, pso) - }; - let leaves = make(false); - let stays = make(true); - let run = |forever: bool, groups: u32| { - let (s, root, pso) = if forever { &stays } else { &leaves }; - let ud = vec![0u32; s.user_data_dwords().max(1) as usize]; - let views = [ - View::Texture(1, 1, &[[0.0; 4]]), - View::Buffer { - data: &[0; 4], - stride: Stride::Structured(16), + let wave32 = host.wave32().unwrap_or(false); + for (wave64, (kind, extra)) in [false, true] + .into_iter() + .flat_map(|w| extras.iter().map(move |e| (w, *e))) + { + let n = native(&counted_lanes(extra), wave64, 64, 0); + let l = lower_halves_limited(&n, wave32, wave32, true, true).expect("translates"); + let limit = thread_limit(&l).expect("a word for the count"); + let shader = shader(l); + if let Ok(mut v) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } + let label = format!("{adapter} (wave64 {wave64}, {kind})"); + let Ok((root, pso)) = host.compute_pipeline(&shader) else { + panic!("{label}: no pipeline"); + }; + for count in [0u32, 1, 7, 31, 32, 33, 63, 64, 65, 74, 127, 128] { + let mut ud = vec![0; shader.user_data_dwords() as usize]; + ud[limit.index as usize] = count; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &views, + samplers: &[], + groups: [2, 1, 1], }, - View::RawUav(groups * 256 * 16), - ]; - let start = std::time::Instant::now(); - let out = host - .dispatch( - root, - pso, - &Dispatch { - roots: vec![(0, Root::Constants(ud))], - views: &views, - samplers: &[], - groups: [groups, 1, 1], - }, - ) - .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); - (out, start.elapsed()) - }; - for groups in [1u32, 5, 37] { - let (out, _) = run(false, groups); - let mut wrong = 0; - for g in 0..groups { - let want = console_while_loop_in_rows(lanes, g); - for (t, want) in want.iter().enumerate() { - let at = (g as usize * 256 + t) * 16; - let got = &out[0][at..at + 16]; - if got != want { - wrong += 1; - failed.push(format!( - "{label}: {groups} groups: group {g} lane {t}: {got:?}, the console {want:?}" - )); - } - } - // Nothing stored where the group has no thread. - let past = (g as usize * 256 + lanes as usize) * 16; - let end = (g as usize + 1) * 256 * 16; - if out[0][past..end].iter().any(|&d| d != 0) { - wrong += 1; - failed.push(format!( - "{label}: {groups} groups: group {g}: stores past its {lanes} threads" - )); - } - } - eprintln!("{label}: {groups} groups: {wrong} lanes differ from the console"); - } - // Many groups, the best of three, and the loop no lane leaves - // (every group at the limit of passes). - let groups = 512; - let best = (0..3).map(|_| run(false, groups).1).min().expect("three"); - let (out, limit) = run(true, groups); - // Every lane of every group ran to the limit of passes. - let passes: std::collections::BTreeSet = (0..groups as usize * 256) - .filter(|t| t % 256 < lanes as usize) - .map(|t| out[0][t * 16 + 9]) + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + let runs = if count == 0 { 128 } else { count }; + let want: Vec = (0..64) + .map(|i| u32::from(i < runs) + u32::from(i + 64 < runs)) .collect(); - eprintln!("{label}: passes at the limit: {passes:?}"); - if passes != [super::DEFAULT_LOOP_LIMIT - 1].into() { - failed.push(format!("{label}: passes at the limit: {passes:?}")); - } - eprintln!( - "{label}: {groups} groups: {best:?}; with every group at the limit of passes {limit:?}" - ); + assert_eq!(out[0], want, "{label}: count {count}"); } + eprintln!("{label}: the lanes past every count stayed out"); } } - assert!(failed.is_empty(), "{}", failed.join("\n")); } -/// A sum over the group's earlier console waves, in a `while` loop whose -/// exit test is in its header and whose latch reads the first lane (the -/// shape of the loops in GTA VI's acceleration-structure builder): every -/// lane writes its wave's number plus 5 to the wave's LDS dword; after a -/// barrier, the lanes of wave `w > 0` add dwords 0 to `w - 1` up, carrying -/// the sum from pass to pass through the first lane (`s17`), and leave when -/// the pass count `s18` is their wave. Each lane stores its sum. -fn sum_of_earlier_waves() -> Vec { +/// Two first-lane reads of values the same in every lane that makes them, +/// in an `s_and_saveexec_b64` region whose EXEC is `mask_words`'s: +/// `v4 = 42` then `v4 = 1.0 + v4` (1.0, read into `s12`) and `v5 = 1.0 + v4` +/// (2.0, read into `s13`). The lanes outside the region never make `v4` or +/// `v5`. Every lane stores `v2` and `v6`, which take the two reads after +/// EXEC is restored (every lane), or with `inside` in the region (its lanes +/// only, the others keeping 0: reads only the lanes that ran them see). +/// `with_mbcnt`: a `v_mbcnt` first, so the program runs in halves on a +/// 32-lane host whatever else it holds. +fn alike_reads_in_a_region(mask_words: &[u32], with_mbcnt: bool, inside: bool) -> Vec { let mut w = PROLOGUE.to_vec(); w.extend([ - 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 - 0x2C0E_0086, // v_lshrrev_b32 v7, 6, v0 - 0x3410_0E82, // v_lshlrev_b32 v8, 2, v7 - 0x4A12_0E85, // v_add_nc_u32 v9, 5, v7 - 0xD834_0000, - 0x0000_0908, // ds_write_b32 v8, v9 - S_WAITCNT_LGKM, - 0xBF8A_0000, // s_barrier - 0x7E10_0280, // v_mov_b32 v8, 0 - 0xBE80_047E, // s_mov_b64 s[0:1], exec - 0x7DAA_0E80, // v_cmpx_ne_u32 exec, 0, v7 - 0xBF88_0012, // s_cbranch_execz (the end) - 0xBE82_047E, // s_mov_b64 s[2:3], exec - 0xBE86_047E, // s_mov_b64 s[6:7], exec - 0xBE92_0380, // s_mov_b32 s18, 0 - 0xBE91_0380, // s_mov_b32 s17, 0 - 0xBF82_0002, // s_branch (the header) - 0x87FE_0610, // s_and_b64 exec, s[16:17], s[6:7] - 0x7E22_0508, // v_readfirstlane_b32 s17, v8 - 0x8F10_8212, // s_lshl_b32 s16, s18, 2 - 0x8112_8112, // s_add_i32 s18, s18, 1 - 0x7E10_0210, // v_mov_b32 v8, s16 - 0xD8D8_0000, - 0x0800_0008, // ds_read_b32 v8, v8 - S_WAITCNT_LGKM, - 0x4A10_1011, // v_add_nc_u32 v8, s17, v8 - 0xBE90_047E, // s_mov_b64 s[16:17], exec - 0x7DA4_0E12, // v_cmpx_eq_u32 exec, s18, v7 - 0x8A86_7E06, // s_andn2_b64 s[6:7], s[6:7], exec - 0xBF85_FFF3, // s_cbranch_scc1 (the latch) - 0xBEFE_0400, // s_mov_b64 exec, s[0:1] + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x7E04_0280, // v_mov_b32 v2, 0 + 0x7E0C_0280, // v_mov_b32 v6, 0 + ]); + if with_mbcnt { + w.extend([ + 0xD765_0001, + 0x0001_00C1, // v_mbcnt_lo_u32_b32 v1, -1, 0 + ]); + } + w.extend(mask_words); + let moves = [ + 0x7E04_020C, // v_mov_b32 v2, s12 + 0x7E0C_020D, // v_mov_b32 v6, s13 + ]; + w.extend([ + 0xBE80_246A, // s_and_saveexec_b64 s[0:1], vcc + 0xBF88_0005 + 2 * u32::from(inside), // s_cbranch_execz (past the region) + 0x7E08_02AA, // v_mov_b32 v4, 42 + 0x0608_08F2, // v_add_f32 v4, 1.0, v4 + 0x7E18_0504, // v_readfirstlane_b32 s12, v4 + 0x060A_08F2, // v_add_f32 v5, 1.0, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 ]); - w.extend(store(8, 0)); + if inside { + w.extend(moves); + } + w.push(0xBEFE_0400); // s_mov_b64 exec, s[0:1] + if !inside { + w.extend(moves); + } + w.extend(store(2, 0)); + w.extend(store(6, 4)); w.push(S_ENDPGM); w } #[test] -fn the_sum_of_earlier_waves_is_what_its_comments_say() { - let words = sum_of_earlier_waves(); +fn the_alike_read_programs_are_what_their_comments_say() { + let words = alike_reads_in_a_region(&MASK_LANES_40_41, true, false); let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let text: Vec = gfx10::decode(&code) + let all = gfx10::decode(&code) .expect("decodes") .iter() .map(|i| i.text(true)) - .collect(); - let want = [ - "v_lshlrev_b32 v16, 5, v0", - "v_lshrrev_b32 v7, 6, v0", - "v_lshlrev_b32 v8, 2, v7", - "v_add_nc_u32 v9, 5, v7", - "ds_write_b32 v8, v9", - "s_waitcnt lgkmcnt(0)", - "s_barrier", - "v_mov_b32 v8, 0", - "s_mov_b64 s[0:1], exec", - "v_cmpx_ne_u32 exec, 0, v7", + .collect::>() + .join("\n"); + for want in [ + "v_mov_b32 v6, 0", + "v_mbcnt_lo_u32_b32 v1, -1, 0", + "v_cmp_eq_u32 vcc, 20, v3", + "s_and_saveexec_b64 s[0:1], vcc", "s_cbranch_execz", - "s_mov_b64 s[2:3], exec", - "s_mov_b64 s[6:7], exec", - "s_mov_b32 s18, 0", - "s_mov_b32 s17, 0", - "s_branch", - "s_and_b64 exec, s[16:17], s[6:7]", - "v_readfirstlane_b32 s17, v8", - "s_lshl_b32 s16, s18, 2", - "s_add_i32 s18, s18, 1", - "v_mov_b32 v8, s16", - "ds_read_b32 v8, v8", - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32 v8, s17, v8", - "s_mov_b64 s[16:17], exec", - "v_cmpx_eq_u32 exec, s18, v7", - "s_andn2_b64 s[6:7], s[6:7], exec", - "s_cbranch_scc1", + "v_mov_b32 v4, 42", + "v_add_f32 v4, 1.0, v4", + "v_readfirstlane_b32 s12, v4", + "v_add_f32 v5, 1.0, v4", + "v_readfirstlane_b32 s13, v5", "s_mov_b64 exec, s[0:1]", - ]; - // The prologue's five words are four instructions. - for (n, want) in want.iter().enumerate() { - let got = &text[PROLOGUE.len() - 1 + n]; - assert!(got.starts_with(want), "{n}: {got:?}, not {want:?}"); + "v_mov_b32 v2, s12", + "v_mov_b32 v6, s13", + ] { + assert!(all.contains(want), "{want:?} not in:\n{all}"); } - // The three branches go to the end, the header and the latch. - let at = |name: &str| { - let i = gfx10::decode(&code).expect("decodes"); - i.iter() - .find(|i| i.text(true).starts_with(name)) - .map(|i| i.text(true)) - .expect("there") - }; - let offset = |n: usize| { - let i = gfx10::decode(&code).expect("decodes"); - i[PROLOGUE.len() - 1 + n].offset - }; - assert!( - at("s_cbranch_execz").contains(&format!("{:04X}", offset(28))), - "{}", - at("s_cbranch_execz") - ); - assert!( - at("s_branch").contains(&format!("{:04X}", offset(18))), - "{}", - at("s_branch") - ); - assert!( - at("s_cbranch_scc1").contains(&format!("{:04X}", offset(16))), - "{}", - at("s_cbranch_scc1") - ); } -/// The sum translates in halves, its loop in lockstep. -#[test] -fn a_sum_of_earlier_waves_translates_in_halves() { - for threads in [128, 256, 512] { - for narrow_waves in [false, true] { - let n = native(&sum_of_earlier_waves(), true, threads, 512); - let l = lowered_with(&n, true, narrow_waves) - .unwrap_or_else(|e| panic!("{threads} threads narrow_waves={narrow_waves}: {e}")); - assert_eq!(l.wave_size, Some(32)); - } - } -} +/// Lanes 8 and 9 of every console wave (its lower half). +const MASK_WAVE_LANES_8_9: [u32; 2] = [ + 0x3606_00BE, // v_and_b32 v3, 62, v0 + 0x7D84_0688, // v_cmp_eq_u32 vcc, 8, v3 +]; -/// Each lane of wave `w` stores `5 + 6 + ... + (w + 4)`, as on the console. +/// Lanes 40 and 41 of every console wave (its upper half). +const MASK_WAVE_LANES_40_41: [u32; 2] = [ + 0x3606_00BE, // v_and_b32 v3, 62, v0 + 0x7D84_06A8, // v_cmp_eq_u32 vcc, 40, v3 +]; + +/// A first-lane read of a value the same in every lane that makes it reads +/// a lane that made it. The halves run such a region in every lane, under a +/// predicate: the host wave's first lane may be outside it and hold an old +/// value (the read took that one), and a half with no lane of the region +/// holds none at all (it takes the other half's). `inside`: only the +/// region's lanes see the reads, each half making them by itself +/// (`first_lane::read_alone`), from a lane of the region too. #[cfg(windows)] #[test] -fn a_sum_of_earlier_waves_matches_the_console_on_every_gpu() { - let words = sum_of_earlier_waves(); +fn a_first_lane_read_of_an_alike_value_in_a_region_matches_the_console_on_every_gpu() { let mut failed = Vec::new(); - for threads in [128u32, 256, 512] { - let want: Vec = (0..threads) - .map(|t| (0..t >> 6).map(|k| k + 5).sum()) - .collect(); - for narrow_waves in [false, true] { - failed.extend( - differences_with(&words, threads, 1, &want, 512, narrow_waves) - .into_iter() - .map(|m| format!("{threads} threads narrow_waves={narrow_waves}: {m}")), - ); - } - } - assert!(failed.is_empty(), "{}", failed.join("\n")); -} - -/// LDS written in a `while` loop of a group of one console wave (64 -/// threads), the shape of the loops in the builder's `28918b7150a7aad5` and -/// `caa78b8ca62bc3d6`: each lane clears its eight LDS dwords; the lanes whose -/// count `tid & 7` is not 0 then loop, writing the pass number `s28` at -/// dword `s28 - 1` of theirs in each pass, and leave when `s28` is their -/// count (the latch restores EXEC from the mask of lanes left, `s[16:17]`). -/// After the loop each lane reads the eight dwords of lane `tid ^ 63`, in -/// the wave's other half, and stores them. -fn lds_written_in_a_while_loop() -> Vec { - let mut w = PROLOGUE.to_vec(); - w.extend([ - 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 - 0x3614_0087, // v_and_b32 v10, 7, v0 - 0x3418_0085, // v_lshlrev_b32 v12, 5, v0 - 0x7E16_0280, // v_mov_b32 v11, 0 - ]); - for k in 0..8 { - w.extend([0xD834_0000 | (4 * k), 0x0000_0B0C]); // ds_write_b32 v12, v11 offset:4k - } - w.extend([ - 0xBE8C_047E, // s_mov_b64 s[12:13], exec - 0x7DAA_1480, // v_cmpx_ne_u32 exec, 0, v10 - 0xBF88_000F, // s_cbranch_execz (the end) - 0xBE8E_047E, // s_mov_b64 s[14:15], exec - 0xBE90_047E, // s_mov_b64 s[16:17], exec - 0xBE9C_0380, // s_mov_b32 s28, 0 - 0xBF82_0001, // s_branch (the header) - 0x87FE_1012, // s_and_b64 exec, s[18:19], s[16:17] - 0x8F12_821C, // s_lshl_b32 s18, s28, 2 - 0x811C_811C, // s_add_i32 s28, s28, 1 - 0x4A1A_1812, // v_add_nc_u32 v13, s18, v12 - 0x7E1E_021C, // v_mov_b32 v15, s28 - 0xBE92_047E, // s_mov_b64 s[18:19], exec - 0xD834_0000, - 0x0000_0F0D, // ds_write_b32 v13, v15 - 0x7DA4_141C, // v_cmpx_eq_u32 exec, s28, v10 - 0x8A90_7E10, // s_andn2_b64 s[16:17], s[16:17], exec - 0xBF85_FFF5, // s_cbranch_scc1 (the latch) - 0xBEFE_040C, // s_mov_b64 exec, s[12:13] - 0x3A1C_00BF, // v_xor_b32 v14, 63, v0 - 0x341C_1C85, // v_lshlrev_b32 v14, 5, v14 - ]); - for k in 0..8 { - w.extend([0xD8D8_0000 | (4 * k), 0x0000_000E | (20 + k) << 24]); // ds_read_b32 v(20+k), v14 offset:4k - } - w.push(S_WAITCNT_LGKM); - for k in 0..8 { - w.extend(store(20 + k as u8, 4 * k)); + type InRegion = fn(u32) -> bool; + let masks: [(&str, &[u32; 2], InRegion); 3] = [ + ("lower_8_9", &MASK_WAVE_LANES_8_9, |t| t & 62 == 8), + ("upper_40_41", &MASK_WAVE_LANES_40_41, |t| t & 62 == 40), + ("both_12_44", &MASK_LANES_12_44, |t| t & 31 == 12), + ]; + for (label, mask, in_region) in masks { + for with_mbcnt in [false, true] { + for threads in [64, 128] { + for inside in [false, true] { + let words = alike_reads_in_a_region(mask, with_mbcnt, inside); + let want: Vec = (0..threads) + .flat_map(|t| { + if !inside || in_region(t) { + [1.0f32.to_bits(), 2.0f32.to_bits()] + } else { + [0, 0] + } + }) + .collect(); + let found = differences_with_buffer( + true, &words, threads, 2, &want, 0, false, false, &[0; 4], + ); + failed.extend(found.into_iter().map(|m| { + format!("{label}(mbcnt={with_mbcnt}, inside={inside}) {threads} threads: {m}") + })); + } + } + } } - w.push(S_ENDPGM); - w + assert!(failed.is_empty(), "{}", failed.join("\n")); } +/// The masks are what their comments say. #[test] -fn the_lds_while_loop_is_what_its_comments_say() { - let words = lds_written_in_a_while_loop(); - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let list = gfx10::decode(&code).expect("decodes"); - let text: Vec = list.iter().map(|i| i.text(true)).collect(); - let all = text.join("\n"); - for want in [ - "v_lshlrev_b32 v16, 5, v0", - "v_and_b32 v10, 7, v0", - "v_lshlrev_b32 v12, 5, v0", - "v_mov_b32 v11, 0", - "ds_write_b32 v12, v11\n", - "ds_write_b32 v12, v11 offset:28", - "s_mov_b64 s[12:13], exec", - "v_cmpx_ne_u32 exec, 0, v10", - "s_mov_b64 s[14:15], exec", - "s_mov_b64 s[16:17], exec", - "s_mov_b32 s28, 0", - "s_and_b64 exec, s[18:19], s[16:17]", - "s_lshl_b32 s18, s28, 2", - "s_add_i32 s28, s28, 1", - "v_add_nc_u32 v13, s18, v12", - "v_mov_b32 v15, s28", - "s_mov_b64 s[18:19], exec", - "ds_write_b32 v13, v15", - "v_cmpx_eq_u32 exec, s28, v10", - "s_andn2_b64 s[16:17], s[16:17], exec", - "s_mov_b64 exec, s[12:13]", - "v_xor_b32 v14, 63, v0", - "v_lshlrev_b32 v14, 5, v14", - "ds_read_b32 v20, v14\n", - "ds_read_b32 v27, v14 offset:28", +fn the_wave_lane_masks_are_what_their_comments_say() { + for (mask, want) in [ + (&MASK_WAVE_LANES_8_9, "v_cmp_eq_u32 vcc, 8, v3"), + (&MASK_WAVE_LANES_40_41, "v_cmp_eq_u32 vcc, 40, v3"), ] { - assert!(all.contains(want), "{want:?} not in:\n{all}"); + let code: Vec = mask + .iter() + .chain(&[S_ENDPGM]) + .flat_map(|w| w.to_le_bytes()) + .collect(); + let text: Vec = gfx10::decode(&code) + .expect("decodes") + .iter() + .map(|i| i.text(true)) + .collect(); + assert_eq!(text[..2], ["v_and_b32 v3, 62, v0", want]); } - // The branches: to the end, the header and the latch. - let at = |name: &str| { - list.iter() - .position(|i| i.text(true).starts_with(name)) - .expect("there") - }; - let target = |n: usize| format!("{:04X}", list[n].offset); - let (end, header, latch) = ( - at("s_mov_b64 exec, s[12:13]"), - at("s_lshl_b32 s18"), - at("s_and_b64 exec, s[18:19]"), - ); - assert!( - text[at("s_cbranch_execz")].contains(&target(end)), - "{}", - text[at("s_cbranch_execz")] - ); - assert!( - text[at("s_branch")].contains(&target(header)), - "{}", - text[at("s_branch")] - ); - assert!( - text[at("s_cbranch_scc1")].contains(&target(latch)), - "{}", - text[at("s_cbranch_scc1")] - ); } -/// Each lane stores the dwords of lane `tid ^ 63`: 1 to that lane's count, -/// then zeros, as on the console. -#[cfg(windows)] +/// The hand-encoded words are the instructions their comments name. #[test] -fn lds_written_in_a_while_loop_matches_the_console_on_every_gpu() { - let words = lds_written_in_a_while_loop(); - let want: Vec = (0..64u32) - .flat_map(|t| { - let n = (t ^ 63) & 7; - (1..=8).map(move |p| if p <= n { p } else { 0 }) - }) - .collect(); - let mut failed = Vec::new(); - for narrow_waves in [true, false] { - let n = native(&words, true, 64, 2048); - match lowered_with(&n, true, narrow_waves) { - Ok(l) => eprintln!( - "narrow_waves={narrow_waves}: translates, {} barriers", - l.barriers - ), - Err(e) => { - eprintln!("narrow_waves={narrow_waves}: refused: {e}"); - continue; - } +fn the_test_programs_are_what_their_comments_say() { + let programs: Vec<(Vec, &[&str])> = vec![ + ( + in_halves(), + &[ + "v_mbcnt_lo_u32_b32 v1, -1, 0", + "v_mbcnt_hi_u32_b32 v1, -1, v1", + "ds_swizzle_b32 v2, v0", + "v_xor_b32 v4, 9, v0", + "ds_bpermute_b32 v3, v4, v0", + "v_writelane_b32 v5, s8, 40", + "v_cndmask_b32 v6, 0, 1, s[20:21]", + "v_mov_b32 v7, v0 quad_perm:[1,0,3,2]", + "buffer_store_dword v7, v16, s[40:43], 0 offen offset:24", + ], + ), + ( + sum_after_a_loop_lanes_leave(), + &[ + "v_and_b32 v5, 3, v0", + "v_mov_b32 v6, 0", + "s_mov_b64 s[4:5], exec", + "v_cmp_lt_u32 vcc, v6, v5", + "s_and_b64 exec, exec, vcc", + "s_cbranch_execz", + "v_add_nc_u32 v6, 1, v6", + "s_branch", + "s_mov_b64 exec, s[4:5]", + "v_cvt_f32_u32 v3, v6", + ], + ), + ( + loops_sharing_a_latch(), + &[ + "s_add_u32 s22, s22, 1", + "s_cmp_lt_u32 s22, 3", + "s_add_u32 s20, s20, 1", + "s_cmp_gt_u32 s20, 2", + "s_mov_b32 s22, 0", + "s_add_u32 s21, s21, 1", + "v_mov_b32 v1, s21", + ], + ), + ( + dpp_row_mask(), + &[ + "v_mov_b32 v7, -1", + "v_mov_b32 v7, v0 quad_perm:[1,0,3,2] row_mask:0xc", + "buffer_store_dword v7, v16, s[40:43], 0 offen", + ], + ), + ( + first_lane_of_the_thread_id(), + &[ + "v_mbcnt_lo_u32_b32 v1, -1, 0", + "v_readfirstlane_b32 s12, v0", + "v_mov_b32 v2, s12", + ], + ), + ( + first_lane_of_a_buffer_load(3), + &[ + "s_load_dwordx4 s[44:47], s[4:5], 0x000020", + "v_mov_b32 v3, 4", + "buffer_load_dword v4, v3, s[44:47], 0 offen", + "s_waitcnt vmcnt(0)", + "v_readfirstlane_b32 s12, v4", + "v_mov_b32 v5, s12", + ], + ), + ( + first_lane_alike(), + &[ + "v_lshrrev_b32 v2, 6, v0", + "v_readfirstlane_b32 s12, v2", + "v_mov_b32 v3, s12", + "buffer_store_dword v1, v16, s[40:43], 0 offen offset:4", + ], + ), + ( + first_active_lane(), + &["s_ff1_i32_b64 s12, exec", "v_mov_b32 v1, s12"], + ), + ( + lanes_below(100), + &[ + "v_cmp_gt_u32 vcc, lit(0x00000064), v0", + "s_bcnt1_i32_b64 s12, vcc", + "v_mov_b32 v2, vcc_hi", + "v_mbcnt_lo_u32_b32 v3, vcc_lo, 0", + "v_mbcnt_hi_u32_b32 v3, vcc_hi, v3", + "buffer_store_dword v3, v16, s[40:43], 0 offen offset:8", + ], + ), + ( + lanes_below_in_a_loop(), + &[ + "s_mov_b32 s20, 0", + "v_cmp_gt_u32 vcc, 40, v0", + "s_add_u32 s20, s20, 1", + "s_cmp_lt_u32 s20, 2", + "s_cbranch_scc1", + ], + ), + ( + lane_reads(40, 33), + &[ + "v_readlane_b32 s12, v0, 40", + "v_readlane_b32 s14, v0, s13", + "v_mov_b32 v1, s12", + "v_mov_b32 v2, s14", + "buffer_store_dword v2, v16, s[40:43], 0 offen offset:4", + ], + ), + ( + reduction(V_ADD_F32, 0x80, 0x7E06_0D00), + &[ + "v_cvt_f32_u32 v3, v0", + "s_or_saveexec_b64 s[12:13], -1", + "v_cndmask_b32 v1, 0, v3, s[12:13]", + "v_permlanex16_b32 v2, v1, 0, 0", + "v_add_f32 v1, v2, v1", + "v_readlane_b32 s14, v1, 32", + "v_add_f32 v1, s14, v1", + "v_readlane_b32 s15, v1, 0", + "s_mov_b64 exec, s[12:13]", + "v_mov_b32 v1, s15", + ], + ), + ( + reduction(V_MIN_U32, 0xC1, V_MOV_V3_V0), + &[ + "v_mov_b32 v3, v0", + "v_cndmask_b32 v1, -1, v3, s[12:13]", + "v_min_u32 v1, v2, v1", + "v_min_u32 v1, s14, v1", + ], + ), + ( + reduction(V_MAX_U32, 0x80, V_MOV_V3_V0), + &["v_max_u32 v1, v2, v1", "v_max_u32 v1, s14, v1"], + ), + ( + exclusive_prefix(), + &[ + "s_or_saveexec_b64 s[0:1], -1", + "v_cndmask_b32 v1, 0, v0, s[0:1]", + "v_add_nc_u32 v1, v1, v1 row_shr:8", + "v_readlane_b32 s2, v1, 47", + "v_mov_b32 v3, v1 row_shr:1", + "s_mov_b64 exec, -2", + "v_mov_b32 v2, v3", + "s_mov_b64 exec, s[0:1]", + "buffer_store_dword v2, v16, s[40:43], 0 offen", + ], + ), + ( + in_a_loop(&[0xD760_000C, 0x0001_5100], 12, Count::Two), + &[ + "v_readlane_b32 s12, v0, 40", + "s_add_u32 s20, s20, 1", + "s_cmp_lt_u32 s20, 2", + "s_cbranch_scc1", + "v_mov_b32 v1, s12", + ], + ), + ( + in_a_loop(&[0x7D88_00A8, 0xBE8C_106A], 12, Count::FirstLane), + &[ + "v_readfirstlane_b32 s21, v0", + "v_cmp_gt_u32 vcc, 40, v0", + "s_bcnt1_i32_b64 s12, vcc", + "s_cmp_lt_u32 s20, s21", + "s_cbranch_scc1", + ], + ), + ]; + for (words, wants) in programs { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let all = gfx10::decode(&code) + .expect("decodes") + .iter() + .map(|i| i.text(true)) + .collect::>() + .join("\n"); + for want in wants { + assert!(all.contains(want), "{want:?} not in:\n{all}"); } - failed.extend( - differences_with(&words, 64, 8, &want, 2048, narrow_waves) - .into_iter() - .map(|m| format!("narrow_waves={narrow_waves}: {m}")), - ); } - assert!(failed.is_empty(), "{}", failed.join("\n")); } -/// A register-index waterfall as the console compiler writes one for a -/// per-lane `v[3 + index]`: `v3..v10` hold `k * 1000 + thread id`, the index -/// is `(thread id >> 2) & 7`, and the loop reads one index left -/// (`v_readfirstlane_b32 s38, v28`), runs the lanes holding it with -/// `m0 = s38` and `v_movrels_b32 v31, v3`, drops them, and loops while any -/// lane is left. Every lane stores `v31`: `index * 1000 + thread id`. -/// `with_mbcnt` asks for console lanes as well (so the program runs in -/// halves); `after` is put after the loop, `body` before the loop's -/// `s_xor_b64`. -fn index_waterfall(with_mbcnt: bool, body: &[u32], after: &[u32]) -> Vec { +/// Each lane counts to the low two bits of its thread id in a loop it leaves +/// on its own, whose back edge is unconditional (`s_branch`): lowering caps +/// that back edge at the loop iteration limit. Then the console compiler's +/// whole-wave sum of the counts ([`reduction`] of `v_cvt_f32_u32 v3, v6`). +/// Per thread, one dword at `l * 32`: its console wave's sum. +fn sum_after_a_loop_lanes_leave() -> Vec { + let sum = reduction(V_ADD_F32, 0x80, 0x7E06_0D06); let mut w = PROLOGUE.to_vec(); - w.push(0x3420_0085); // v_lshlrev_b32 v16, 5, v0 - if with_mbcnt { - w.extend([ - 0xD765_0001, - 0x0001_00C1, // v_mbcnt_lo_u32_b32 v1, -1, 0 - ]); - } - for k in 0..8u32 { - // v_add_nc_u32 v(3 + k), k * 1000, v0 - w.extend([0x4A00_00FF | (3 + k) << 17, k * 1000]); - } w.extend([ - 0x2C38_0082, // v_lshrrev_b32 v28, 2, v0 - 0x3638_3887, // v_and_b32 v28, 7, v28 - 0xBEA4_047E, // s_mov_b64 s[36:37], exec + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x360A_0083, // v_and_b32 v5, 3, v0 + 0x7E0C_0280, // v_mov_b32 v6, 0 + 0xBE84_047E, // s_mov_b64 s[4:5], exec + 0x7D82_0B06, // v_cmp_lt_u32 vcc, v6, v5 + 0x87FE_6A7E, // s_and_b64 exec, exec, vcc + 0xBF88_0002, // s_cbranch_execz (past the s_branch) + 0x4A0C_0C81, // v_add_nc_u32 v6, 1, v6 + 0xBF82_FFFB, // s_branch (back to the v_cmp) + 0xBEFE_0404, // s_mov_b64 exec, s[4:5] ]); - let looped = [ - &[ - 0x7E4C_051C, // v_readfirstlane_b32 s38, v28 - 0x7D84_3826, // v_cmp_eq_u32 vcc, s38, v28 - 0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc - 0xBEFC_0326, // s_mov_b32 m0, s38 - 0x7E3E_8703, // v_movrels_b32 v31, v3 - ][..], - body, - &[0x89FE_067E], // s_xor_b64 exec, exec, s[6:7] - ] - .concat(); - let back = -(looped.len() as i32 + 1); - w.extend(&looped); - w.push(0xBF89_0000 | (back as u32 & 0xFFFF)); // s_cbranch_execnz (the read) - w.push(0xBEFE_0424); // s_mov_b64 exec, s[36:37] - w.extend(after); - w.extend(store(31, 0)); + w.extend(&sum[PROLOGUE.len() + 1..]); + w +} + +/// Two scalar loops whose latches share a block, as the console compiler +/// lays them out: the latch branches back to the inner loop's header three +/// times and otherwise falls through to the outer loop's header, which runs +/// twice. Both targets of that branch are back edges. Per thread, one dword +/// at `l * 32`: the inner loop's passes, 6. +fn loops_sharing_a_latch() -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0xBE94_0380, // s_mov_b32 s20, 0 + 0xBE95_0380, // s_mov_b32 s21, 0 + 0xBF82_0003, // s_branch (to the outer header) + 0x8016_8116, // s_add_u32 s22, s22, 1 (the shared latch) + 0xBF0A_8316, // s_cmp_lt_u32 s22, 3 + 0xBF85_0004, // s_cbranch_scc1 (back to the inner header) + 0x8014_8114, // s_add_u32 s20, s20, 1 (the outer header) + 0xBF08_8214, // s_cmp_gt_u32 s20, 2 + 0xBF85_0003, // s_cbranch_scc1 (out of both loops) + 0xBE96_0380, // s_mov_b32 s22, 0 + 0x8015_8115, // s_add_u32 s21, s21, 1 (the inner header) + 0xBF82_FFF7, // s_branch (to the shared latch) + 0x7E02_0215, // v_mov_b32 v1, s21 + ]); + w.extend(store(1, 0)); w.push(S_ENDPGM); w } +/// A reduction after a loop the lanes leave one by one, whose back edge is +/// capped at the loop iteration limit ([`sum_after_a_loop_lanes_leave`]): +/// the console runs the loop to its end, so with the cap taken as never +/// reached every lane of the group runs the reduction together and the +/// halves pass each other their sums. Only with the cap's barriers refused +/// (`VICTORY_CAP_BARRIERS=1`) is a lane taken to have left at the cap, and +/// the reduction refused. #[test] -fn the_index_waterfall_programs_are_what_their_comments_say() { - let words = index_waterfall(true, &[], &[]); - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let all = gfx10::decode(&code) - .expect("decodes") - .iter() - .map(|i| i.text(true)) - .collect::>() - .join("\n"); - for want in [ - "v_add_nc_u32 v3, lit(0x00000000), v0", - "v_add_nc_u32 v10, lit(0x00001b58), v0", - "v_lshrrev_b32 v28, 2, v0", - "v_and_b32 v28, 7, v28", - "s_mov_b64 s[36:37], exec", - "v_readfirstlane_b32 s38, v28", - "v_cmp_eq_u32 vcc, s38, v28", - "s_and_saveexec_b64 s[6:7], vcc", - "s_mov_b32 m0, s38", - "v_movrels_b32 v31, v3", - "s_xor_b64 exec, exec, s[6:7]", - "s_cbranch_execnz", - "s_mov_b64 exec, s[36:37]", - ] { - assert!(all.contains(want), "{want:?} not in:\n{all}"); +fn a_reduction_after_a_loop_lanes_leave_passes_between_halves() { + let words = sum_after_a_loop_lanes_leave(); + for threads in [64, 96, 128] { + // The lockstep loops of #591 may now translate this shape even with + // the cap's barriers, so the refusal is no longer required. + let why = super::with_cap_barriers(true, || refusal(&words, threads, 0)); + assert!( + why == "translated" || why.contains("a wave reduction over both 32-lane halves"), + "{threads}: {why}" + ); + let translated = super::with_cap_barriers(false, || refusal(&words, threads, 0)); + assert_eq!(translated, "translated", "{threads}"); } + assert_eq!(refusal(&words, 32, 0), "translated"); } -/// The first-lane read opening a register-index waterfall is made by each -/// host half by itself: the program needs no halves for it, and translates -/// in halves too although the read is in a loop (#522 sent GTA VI's -/// `11eeb27c2d15980d` to halves for it, which refused it). Where the read's -/// result is seen after the loop, or the loop body does scalar work, whose -/// iterations the halves would see, the read still takes halves (refused -/// where they cannot meet). +/// [`sum_after_a_loop_lanes_leave`] on every hardware adapter gives the +/// console's sums, in a group of 64 (one console wave in two halves), of 96 +/// (the second console wave has no upper half) and of 128 (two). #[test] -fn a_register_index_waterfall_is_made_in_each_half() { - let across = "a first-lane read of a value that may differ between 32-lane halves"; - let halves = |words: &[u32], threads: u32| match lowered(&native(words, true, threads, 0), true) - { - Ok(l) => l.wave_size == Some(32), - Err(e) => e.to_string().contains(across), - }; - for threads in [64, 128] { - assert!(!halves(&index_waterfall(false, &[], &[]), threads)); - assert!(halves(&index_waterfall(true, &[], &[]), threads)); - // v_mov_b32 v31, s38 after the loop - assert!(halves( - &index_waterfall(false, &[], &[0x7E3E_0226]), - threads - )); - // s_add_u32 s50, s50, 1 in the body - assert!(halves( - &index_waterfall(false, &[0x8032_8132], &[]), - threads - )); +#[cfg(windows)] +fn a_reduction_after_a_loop_lanes_leave_matches_the_console_on_every_gpu() { + let words = sum_after_a_loop_lanes_leave(); + let mut failed = Vec::new(); + for threads in [64, 96, 128] { + let want: Vec = (0..threads) + .map(|l| (console_reduction(threads, l, |a, b| a + b, |t| t & 3) as f32).to_bits()) + .collect(); + failed.extend(super::with_cap_barriers(false, || { + differences(&words, threads, 1, &want) + })); } + assert!(failed.is_empty(), "{}", failed.join("\n")); } -/// The register-index waterfall gives the console's lanes on every GPU, in -/// halves and not: `((thread id >> 2) & 7) * 1000 + thread id` in every -/// lane. -#[cfg(windows)] +/// [`loops_sharing_a_latch`] in whole-wave halves: each side of the shared +/// latch's branch counts its own loop's passes under the iteration limit. #[test] -fn a_register_index_waterfall_matches_the_console_on_every_gpu() { - let mut failed = Vec::new(); - for threads in [64, 128] { - let want: Vec = (0..threads).map(|t| ((t >> 2) & 7) * 1000 + t).collect(); - for with_mbcnt in [false, true] { - let words = index_waterfall(with_mbcnt, &[], &[]); - failed.extend( - differences(&words, threads, 1, &want) - .into_iter() - .map(|m| format!("{threads} threads (mbcnt={with_mbcnt}): {m}")), - ); - } - } +fn a_branch_back_to_two_loops_runs_in_whole_wave_halves() { + let n = native(&loops_sharing_a_latch(), true, 64, 0); + let literal = lower_halves(&n, true, false, true).expect("whole-wave halves"); + assert_eq!(literal.wave_size, Some(32)); +} + +/// [`loops_sharing_a_latch`] in whole-wave halves on every hardware adapter +/// gives the console's count in every lane. +#[test] +#[cfg(windows)] +fn a_branch_back_to_two_loops_matches_the_console_on_every_gpu() { + let words = loops_sharing_a_latch(); + let failed = differences_in(true, &words, 64, 1, &[6; 64], 0, false, true); assert!(failed.is_empty(), "{}", failed.join("\n")); } diff --git a/crates/victory-shader/src/emit/lower/predicate.rs b/crates/victory-shader/src/emit/lower/predicate.rs index 435f0c46d..def496833 100644 --- a/crates/victory-shader/src/emit/lower/predicate.rs +++ b/crates/victory-shader/src/emit/lower/predicate.rs @@ -244,6 +244,17 @@ impl PredicatePlan { &needs, &plan, ) + // A guard nested in the body that skips to the same join + // (`if (a) { if (b) { .. } }`) cannot be a skip guard of + // its own, the join being this one's, so what it guards + // stays out of step. Where that needs to be in step and + // the whole region can be laid out flat instead (shape + // 3), that is done. + && !(guards_to_join(&eff_exits, body, join, &needs) + && match_sese_diamond( + p, &eff_exits, d, taken, not_taken, join, &rpo, &needs, &plan, + ) + .is_some()) { plan.exits.insert(d, FlatExit::SkipGuard { body }); plan.skip_bodies.insert(body, d); @@ -359,6 +370,47 @@ impl PredicatePlan { } } + if !changed && host_wave32 { + // Shape 6: a loop every lane ends together but for a break + // lanes take one by one: the break predicated away, the + // lanes that broke kept inactive to the loop's own end. + let wanted = (0..n).any(|b| needs[b] && !plan.step[b]); + 'shape6: for &h in &order { + if !wanted || plan.dead_blocks.contains(&h) || plan.in_diamond.contains(&h) { + continue; + } + let Some(two) = two_exits(&eff_exits, h, &rpo, &plan) else { + continue; + }; + for (breaking, _) in two.leaving { + let Some(lp) = + match_break_loop(p, st, &eff_exits, &rpo, &plan, &two, breaking) + else { + continue; + }; + // Only where the loop is then in step, and the + // block after it. + let mut exits = eff_exits.clone(); + exits[lp.breaking] = LaneExit::Jump(lp.stay); + let step = barriers::in_step_with(p, st, &exits, &plan.uniform_branches); + if !(lp.body.iter().all(|&b| step[b]) && step[lp.exit]) { + continue; + } + plan.exits + .insert(lp.breaking, FlatExit::EarlyOut { cont: lp.stay }); + plan.early_conts.insert(lp.stay, lp.breaking); + plan.skipped_edges.insert((lp.breaking, lp.exit)); + plan.lockstep_headers.insert(h, lp.latch); + plan.lockstep_exits.insert(lp.exit, h); + plan.in_lockstep_loop.extend(lp.body); + eff_exits = exits; + plan.step = step; + changed = true; + break 'shape6; + } + } + } + if !changed { break; } @@ -682,6 +734,56 @@ fn match_skip_guard( Some(body) } +/// Whether a block reached from `body` before `join` branches one way to +/// `join` itself, with a block that needs to be in step (`needs`) on its +/// other way: a guard nested in a skip guard's body, skipping to the same +/// join, around such a block. +fn guards_to_join(exits: &[LaneExit], body: usize, join: usize, needs: &[bool]) -> bool { + // Whether a block reached from `from` before `join` needs to be in step. + let needed = |from: usize| { + let mut seen = Set::default(); + let mut stack = vec![from]; + while let Some(b) = stack.pop() { + if b == join || !seen.insert(b) { + continue; + } + if needs[b] { + return true; + } + match exits[b] { + LaneExit::Jump(t) => stack.push(t), + LaneExit::Branch { + taken, not_taken, .. + } => stack.extend([taken, not_taken]), + LaneExit::End | LaneExit::Indirect => {} + } + } + false + }; + let mut seen = Set::default(); + let mut stack = vec![body]; + while let Some(b) = stack.pop() { + if b == join || !seen.insert(b) { + continue; + } + match exits[b] { + LaneExit::Jump(t) => stack.push(t), + LaneExit::Branch { + taken, not_taken, .. + } => { + if taken == join && not_taken != join && needed(not_taken) + || not_taken == join && taken != join && needed(taken) + { + return true; + } + stack.extend([taken, not_taken]); + } + LaneExit::End | LaneExit::Indirect => {} + } + } + false +} + #[allow(clippy::too_many_arguments)] fn match_sese_diamond( p: &Program, @@ -930,6 +1032,24 @@ fn match_lockstep_loop( Some((latch, exit, stay_when_true, body)) } +/// Whether a block outside the loop `body` reads one of `values` (the +/// scalars the body writes), in an instruction or a phi. +fn read_outside(p: &Program, plan: &PredicatePlan, body: &Set, values: &Set) -> bool { + !values.is_empty() + && p.blocks.iter().enumerate().any(|(b, block)| { + !body.contains(&b) + && !plan.dead_blocks.contains(&b) + && (block + .phis + .iter() + .any(|phi| phi.args.iter().any(|v| values.contains(v))) + || block + .insts + .iter() + .any(|i| i.reads.iter().any(|(_, v)| values.contains(v)))) + }) +} + /// A while-shaped loop [`match_lockstep_while_loop`] found. struct WhileLoop { /// The block jumping back to the header, unconditionally. @@ -1089,6 +1209,268 @@ fn match_lockstep_while_loop( }) } +/// A loop [`match_break_loop`] found. +struct BreakLoop { + /// The block whose branch lanes leave the loop by, one by one. + breaking: usize, + /// Its successor inside the loop, and the one outside. + stay: usize, + exit: usize, + /// The block jumping (or branching) back to the header. + latch: usize, + body: Set, +} + +/// A loop two edges leave ([`two_exits`]). +struct TwoExits { + header: usize, + /// The block jumping (or branching) back to the header. + latch: usize, + body: Set, + /// The two edges, each (from, to). + leaving: [(usize, usize); 2], +} + +/// The loop of header `h`, if it has one latch, is entered only at `h` +/// from blocks in step, holds no cycle of its own and nothing predicated +/// yet, and exactly two edges leave it. +fn two_exits( + exits: &[LaneExit], + h: usize, + rpo: &[usize], + plan: &PredicatePlan, +) -> Option { + let preds = eff_preds(exits, &plan.dead_blocks, h); + let (back, out): (Vec, Vec) = preds.into_iter().partition(|&q| rpo[q] >= rpo[h]); + let [latch] = back[..] else { + return None; + }; + if out.is_empty() + || !out.iter().all(|&q| plan.step[q]) + || plan.lockstep_headers.contains_key(&h) + { + return None; + } + // The natural loop body, by reverse DFS from `latch` stopping at `h`. + let mut body = Set::default(); + body.insert(h); + let mut stack = vec![latch]; + while let Some(b) = stack.pop() { + if b == h || !body.insert(b) { + continue; + } + if body.len() > MAX_LOCKSTEP_LOOP_BLOCKS { + return None; + } + for q in eff_preds(exits, &plan.dead_blocks, b) { + if !body.contains(&q) { + if rpo[q] < rpo[h] { + return None; // side entry into loop body + } + stack.push(q); + } + } + } + if body.iter().any(|b| { + plan.in_diamond.contains(b) + || plan.in_lockstep_loop.contains(b) + || plan.dead_blocks.contains(b) + || plan.exits.contains_key(b) + || plan.early_conts.contains_key(b) + }) { + return None; + } + // Two edges leave the body: the break's and the loop's own end's. No + // cycle inside the body but the latch's. + let mut leaving = Vec::new(); + for &b in &body { + let succs: Vec = match exits[b] { + LaneExit::Jump(t) => vec![t], + LaneExit::Branch { + taken, not_taken, .. + } => vec![taken, not_taken], + LaneExit::End | LaneExit::Indirect => return None, + }; + for t in succs { + if !body.contains(&t) { + leaving.push((b, t)); + } else if rpo[t] <= rpo[b] && !(b == latch && t == h) { + return None; // nested cycle inside loop + } + } + } + let [e0, e1] = leaving[..] else { + return None; + }; + Some(TwoExits { + header: h, + latch, + body, + leaving: [e0, e1], + }) +} + +/// A loop with two exits to one block `exit`: a branch lanes leave by one +/// by one (a `break`: `breaking -> exit`), and the loop's own end, taken +/// by every lane left (`ending -> exit`, directly or through one block of +/// its own). The break is predicated away like an early-out: the lanes that +/// break stay in the loop, inactive, to its own end, and reach `exit` with +/// the others. Every vector write is guarded by the lanes still active, so +/// a lane that broke holds at `exit` what it held when it broke: what the +/// edge it would have taken carries. +/// +/// The caller checks that the loop's own end is then one every lane of the +/// group takes together ([`barriers::in_step_with`]). +fn match_break_loop( + p: &Program, + st: &Structured, + exits: &[LaneExit], + rpo: &[usize], + plan: &PredicatePlan, + lp: &TwoExits, + breaking: usize, +) -> Option { + let TwoExits { + header: h, + latch, + ref body, + leaving: [(b0, t0), (b1, t1)], + } = *lp; + let (exit, (ending, after)) = if b0 == breaking { + (t0, (b1, t1)) + } else if b1 == breaking { + (t1, (b0, t0)) + } else { + return None; + }; + if ending == breaking { + return None; + } + let LaneExit::Branch { + taken, not_taken, .. + } = exits[breaking] + else { + return None; + }; + let stay = if taken == exit { not_taken } else { taken }; + if !body.contains(&stay) || eff_preds(exits, &plan.dead_blocks, stay) != [breaking] { + return None; + } + // `stay` dominates the latch and the loop's own end: a lane there came + // past the break in that pass, so the lanes active there (each block's + // are its immediate dominator's, or fewer) are among those that stayed. + let below_stay = |mut b: usize| loop { + if b == stay { + break true; + } + let up = plan.idom.get(b).copied().unwrap_or(usize::MAX); + if b == h || up == b || up == usize::MAX { + break false; + } + b = up; + }; + if !below_stay(latch) || !below_stay(ending) { + return None; + } + // The loop's own end reaches `exit` directly, or through one block + // only it enters. + let mut exit_preds = eff_preds(exits, &plan.dead_blocks, exit); + exit_preds.sort_unstable(); + let through = if after == exit { + ending + } else { + if exits[after] != LaneExit::Jump(exit) + || eff_preds(exits, &plan.dead_blocks, after) != [ending] + || !p.blocks[after].phis.is_empty() + || plan.exits.contains_key(&after) + || plan.in_diamond.contains(&after) + || plan.skip_joins.contains_key(&after) + || plan.diamond_joins.contains_key(&after) + || plan.lockstep_exits.contains_key(&after) + { + return None; + } + after + }; + let mut want = vec![breaking, through]; + want.sort_unstable(); + if exit_preds != want + || rpo[exit] <= rpo[h] + || plan.lockstep_exits.contains_key(&exit) + || plan.diamond_joins.contains_key(&exit) + || plan.skip_joins.contains_key(&exit) + || plan.skip_bodies.contains_key(&exit) + || plan.early_conts.contains_key(&exit) + { + return None; + } + // A lane that broke keeps its vector registers, each write being + // guarded by the lanes still active. It keeps nothing else the loop + // makes: so none of that may be seen past the loop. + // + // No lane mask is joined at `exit` (a mask is a function of what each + // edge carries, and the lanes that broke would read the other edge's), + // and none written in the loop is read after it (a compare there is made + // again in every pass, of scalars that change). + let is_mask = |v: &Value| st.masks.contains_key(v) || st.highs.contains_key(v); + let is_mask_reg = + |r: Reg| matches!(r, Reg::S(k) if [EXEC, EXEC + 1, VCC, VCC + 1].contains(&k)); + if p.blocks[exit] + .phis + .iter() + .any(|phi| is_mask(&phi.value) || is_mask_reg(phi.reg)) + { + return None; + } + // No scalar the loop writes is read after it, as for + // `match_lockstep_loop`: the console wave leaves once its every lane + // broke, and here it runs the loop to its own end. The block the loop's + // own end leaves through is run by the lanes that never broke, as on + // the console: it may read them. + let mut inside = body.clone(); + inside.insert(through); + let mut written: Set = Set::default(); + for &b in &inside { + let block = &p.blocks[b]; + written.extend( + block + .phis + .iter() + .filter(|phi| matches!(phi.reg, Reg::S(_) | Reg::Scc) || is_mask(&phi.value)) + .map(|phi| phi.value), + ); + for inst in &block.insts { + // Scalar code runs whatever lanes are active: no scalar effect + // may be in a pass the console wave does not make. + let name = inst.name(); + if name.starts_with("s_store") + || name.starts_with("s_atomic") + || name.starts_with("s_buffer_store") + || name.starts_with("s_buffer_atomic") + || name.starts_with("s_sendmsg") + { + return None; + } + written.extend( + inst.writes + .iter() + .filter(|(r, v)| matches!(r, Reg::S(_) | Reg::Scc) || is_mask(v)) + .map(|w| w.1), + ); + } + } + if read_outside(p, plan, &inside, &written) { + return None; + } + Some(BreakLoop { + breaking, + stay, + exit, + latch, + body: body.clone(), + }) +} + fn post_dominators(exits: &[LaneExit]) -> Vec> { let n = exits.len(); let words = n.div_ceil(64);