diff --git a/README.md b/README.md index 72d811d2..ba5cd482 100644 --- a/README.md +++ b/README.md @@ -187,6 +187,7 @@ The on/off switches below (`...=1`) are off when unset or set to `0`. | `VICTORY_PIPELINE_LOG=` | a line per title pipeline created (key, shaders, state), first used, and made or loaded (library name); `translate --cache --pipelines` writes the last kind too | | `VICTORY_PREBUILD_KEYS=` | `translate --cache --pipelines` makes nothing and lists each pack record's key, shaders and state (or why it is skipped) | | `VICTORY_SHADER_LOOP_LIMIT=` | translated shader loops stop after `n` iterations per lane instead of 2^20 (own shader cache entries); if a lower `n` makes world frames much faster, loops hitting the limit are what makes them slow | +| `VICTORY_LITERAL_HALVES=0` | disable the literal translation retry for 64-thread wave64 compute shaders on 32-lane hosts (separate shader cache entries) | | `VICTORY_AUDIO_CAPTURE=` | records what the title plays (our process only) | | `VICTORY_XMA_DUMP=` | saves the first 32 XMA voices' context and input | diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e774813a..58a1e990 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -4159,12 +4159,7 @@ void main(uint3 id : SV_DispatchThreadID) { &res, Options { view_marks: true, - atomic_locks: false, - atomic_lock_rounds: false, - atomic_umax: false, - bias_as_gradients: false, - host_wave32: false, - narrow_waves: false, + ..Options::default() }, ) .unwrap(); diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index bd71e89b..744d6fa9 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -155,6 +155,12 @@ fn narrow_waves() -> bool { }) } +/// Whether 64-thread wave64 shaders keep only the per-lane translation. +fn literal_halves_disabled() -> bool { + static OFF: OnceLock = OnceLock::new(); + *OFF.get_or_init(|| std::env::var("VICTORY_LITERAL_HALVES").as_deref() == Ok("0")) +} + /// Whether this runs under Wine (on a Mac: D3DMetal's D3D12). #[cfg(windows)] pub(crate) fn under_wine() -> bool { @@ -175,23 +181,25 @@ pub(crate) fn under_wine() -> bool { } /// [`build`] for translations with host workarounds (atomic locks, their -/// rounds and umax reduction, bias as gradients, narrow waves): their own -/// cache entries, one per combination. +/// rounds and umax reduction, bias as gradients, narrow waves, and literal +/// halves): their own cache entries, one per combination. pub(crate) fn translation_build(options: victory_shader::emit::Options) -> &'static [u8; 32] { let locks = options.atomic_locks; let bias = options.bias_as_gradients; let narrow = options.narrow_waves; let rounds = locks && options.atomic_lock_rounds; let umax = rounds && options.atomic_umax; - if !locks && !bias && !narrow { + let no_literal = options.host_wave32 && options.disable_literal_halves; + if !locks && !bias && !narrow && !no_literal { return build(); } - static BUILDS: [OnceLock<[u8; 32]>; 32] = [const { OnceLock::new() }; 32]; + static BUILDS: [OnceLock<[u8; 32]>; 64] = [const { OnceLock::new() }; 64]; let n = usize::from(locks) | usize::from(bias) << 1 | usize::from(narrow) << 2 | usize::from(rounds) << 3 - | usize::from(umax) << 4; + | usize::from(umax) << 4 + | usize::from(no_literal) << 5; BUILDS[n].get_or_init(|| { let mut h = blake3::Hasher::new(); h.update(build()); @@ -210,6 +218,9 @@ pub(crate) fn translation_build(options: victory_shader::emit::Options) -> &'sta if narrow { h.update(b"narrow waves"); } + if no_literal { + h.update(b"literal halves disabled"); + } *h.finalize().as_bytes() }) } @@ -228,6 +239,7 @@ pub(crate) fn runtime_options() -> victory_shader::emit::Options { bias_as_gradients: bias_as_gradients(), host_wave32: host_wave32(), narrow_waves: narrow_waves(), + disable_literal_halves: literal_halves_disabled(), } } @@ -545,6 +557,23 @@ mod tests { assert!(!rounds_on(false, Some("1")), "nor when asked for"); } + #[test] + fn disabling_literal_halves_changes_the_translation_key() { + let options = victory_shader::emit::Options { + host_wave32: true, + ..runtime_options() + }; + let on = translation_build(victory_shader::emit::Options { + disable_literal_halves: false, + ..options + }); + let off = translation_build(victory_shader::emit::Options { + disable_literal_halves: true, + ..options + }); + assert_ne!(on, off); + } + fn shader() -> HostShader { HostShader { stage: HwStage::Ps, diff --git a/crates/victory-shader/src/emit/halves_tests.rs b/crates/victory-shader/src/emit/halves_tests.rs index f24f1390..2db59d43 100644 --- a/crates/victory-shader/src/emit/halves_tests.rs +++ b/crates/victory-shader/src/emit/halves_tests.rs @@ -9,8 +9,11 @@ //! where the adapter has 64-lane waves (AMD), which is the console's own //! form; the results must be the console's, computed here, in both. +#[cfg(windows)] use super::host::{Dispatch, Host, Root, Stride, View}; -use super::{lower, validator}; +use super::lower; +#[cfg(windows)] +use super::validator; use crate::native::{ ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, }; @@ -74,6 +77,7 @@ fn in_halves() -> Vec { } /// What the console gives [`in_halves`]'s lane `l`. +#[cfg(windows)] fn console(l: u32) -> [u32; 8] { [ l, @@ -137,31 +141,45 @@ fn lowered_with( native: &NativeProgram, host_wave32: bool, narrow_waves: bool, +) -> Result { + lower_halves(native, host_wave32, narrow_waves, false) +} + +fn lower_halves( + native: &NativeProgram, + host_wave32: bool, + narrow_waves: bool, + literal: bool, ) -> Result { let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); let st = structure::structure(&p).expect("structure"); let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); let io = io::raise(&p, native).expect("io::raise"); - lower::lower(&lower::Parts { - native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: Vec::new(), - outputs: Vec::new(), - prims: Vec::new(), - mesh_stride: 0, - view_marks: false, - atomic_locks: false, - atomic_lock_rounds: false, - atomic_umax: false, - bias_as_gradients: false, - narrow_waves, - host_wave32, - }) + lower::lower_pruned( + &lower::Parts { + native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + view_marks: false, + atomic_locks: false, + atomic_lock_rounds: false, + atomic_umax: false, + bias_as_gradients: false, + narrow_waves, + host_wave32, + }, + None, + literal, + ) } +#[cfg(windows)] fn shader(l: lower::Lowered) -> super::HostShader { super::HostShader { stage: HwStage::Cs, @@ -363,6 +381,7 @@ fn a_wave64_program_reading_lanes_declares_32_lane_waves_in_halves() { let whole = lowered(&n, false).expect("one wave64"); assert_eq!(halves.wave_size, Some(32)); assert_eq!(whole.wave_size, Some(64)); + #[cfg(windows)] if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut halves.dxil.clone()) .expect("DXIL validation failed"); @@ -416,6 +435,7 @@ fn lanes_below(limit: u32) -> Vec { /// What the console gives [`lanes_below`]`(limit)`'s lane `l` in a group of /// `threads`. +#[cfg(windows)] fn console_lanes_below(limit: u32, threads: u32, l: u32) -> [u32; 3] { let wave = l & !63; let below = |end: u32| limit.min(threads).min(end).saturating_sub(wave); @@ -557,6 +577,7 @@ fn reduction(op: u32, ident: u32, input: u32) -> Vec { /// What the console gives [`reduction`] of `f` (folding the inputs of a /// console wave's lanes) in lane `l` of a group of `threads`. +#[cfg(windows)] fn console_reduction( threads: u32, l: u32, @@ -658,6 +679,7 @@ fn lane_masks_read_as_data_pass_between_halves() { let halves = lowered(&native(&lanes_below(40), true, 64, 0), true).expect("halves"); assert_eq!(halves.wave_size, Some(32)); + #[cfg(windows)] if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut halves.dxil.clone()) .expect("DXIL validation failed"); @@ -669,6 +691,7 @@ fn lane_masks_read_as_data_pass_between_halves() { /// two (one mask each), and in a group of 96, whose second console wave has /// no upper half (a high dword of 0). #[test] +#[cfg(windows)] fn lane_masks_passed_between_halves_match_the_console_on_every_gpu() { let mut failed = differences(&first_active_lane(), 64, 1, &[0; 64]); for (limit, threads) in [(40, 64), (100, 128), (80, 96), (96, 96)] { @@ -713,6 +736,7 @@ fn reductions_and_prefixes_pass_between_halves() { for words in [sum, exclusive_prefix()] { let halves = lowered(&native(&words, true, 96, 0), true).expect("halves"); assert_eq!(halves.wave_size, Some(32)); + #[cfg(windows)] if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { @@ -727,6 +751,7 @@ fn reductions_and_prefixes_pass_between_halves() { /// console wave in two halves), of 128 (two), and of 96, whose second /// console wave has no upper half. #[test] +#[cfg(windows)] fn reductions_and_prefixes_across_halves_match_the_console_on_every_gpu() { let mut failed = Vec::new(); for threads in [32, 64, 96, 128] { @@ -851,6 +876,7 @@ fn lane_reads_pass_between_halves() { for words in [lane_reads(20, 5), first_lane_of_the_thread_id()] { let halves = lowered(&native(&words, true, 96, 0), true).expect("halves"); assert_eq!(halves.wave_size, Some(32)); + #[cfg(windows)] if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { @@ -864,6 +890,7 @@ fn lane_reads_pass_between_halves() { /// adapter give the console's lanes: in a group of one console wave, of /// two, of 96 (the second console wave has no upper half), and of 32. #[test] +#[cfg(windows)] fn lane_reads_across_halves_match_the_console_on_every_gpu() { let mut failed = Vec::new(); for (k, s, threads) in [ @@ -936,12 +963,14 @@ fn lds_of_a_one_wave64_group_is_refused_in_halves() { /// `per_lane` dwords at `l * 32`, on every hardware adapter: in halves, and /// as one wave64 where the adapter runs 64-lane waves. A line per lane whose /// dwords differ from `want` (the console's, `per_lane` per lane). +#[cfg(windows)] fn differences(words: &[u32], threads: u32, per_lane: usize, want: &[u32]) -> Vec { differences_with(words, threads, per_lane, want, 0, false) } /// [`differences`] for a program with `lds_bytes` of LDS, lowered with /// `narrow_waves` ([`lowered_with`]). +#[cfg(windows)] fn differences_with( words: &[u32], threads: u32, @@ -958,11 +987,14 @@ fn differences_with( want, lds_bytes, narrow_waves, + false, ) } /// [`differences_with`] for a program of console waves of 64 lanes /// (`wave64`) or of 32, which a host of any wave size runs as it is. +#[cfg(windows)] +#[allow(clippy::too_many_arguments)] fn differences_in( wave64: bool, words: &[u32], @@ -971,13 +1003,19 @@ fn differences_in( want: &[u32], lds_bytes: u32, narrow_waves: bool, + literal: bool, ) -> Vec { let n = native(words, wave64, threads, lds_bytes); - let forms = if wave64 { + let forms = if literal { + vec![( + "literal halves", + shader(lower_halves(&n, true, narrow_waves, true).expect("literal halves")), + )] + } else if wave64 { vec![ ( "halves", - shader(lowered_with(&n, true, narrow_waves).expect("halves")), + shader(lower_halves(&n, true, narrow_waves, literal).expect("halves")), ), ( "wave64", @@ -1071,6 +1109,7 @@ fn dpp_row_mask() -> Vec { } #[test] +#[cfg(windows)] fn dpp_row_masks_name_the_console_rows_on_every_gpu() { let want: Vec = (0..64) .map(|l| if l >= 32 { l ^ 1 } else { u32::MAX }) @@ -1145,6 +1184,7 @@ fn first_lane_alike() -> Vec { /// the whole console wave), and one value per console wave in a group of /// 128, where each half reads its console wave's. #[test] +#[cfg(windows)] fn first_lanes_kept_in_halves_match_the_console_on_every_gpu() { let mut failed = differences(&first_lane_of_the_thread_id(), 32, 1, &[0; 32]); let want: Vec = (0..128).flat_map(|l| [l >> 6, l & 63]).collect(); @@ -1155,6 +1195,7 @@ fn first_lanes_kept_in_halves_match_the_console_on_every_gpu() { /// [`in_halves`] on every hardware adapter: in halves, and as one wave64 /// where the adapter runs 64-lane waves; both give the console's results. #[test] +#[cfg(windows)] fn wave64_programs_in_halves_match_the_console_on_every_gpu() { let want: Vec = (0..64).flat_map(console).collect(); let failed = differences(&in_halves(), 64, 8, &want); @@ -1238,6 +1279,7 @@ fn lds_of_a_one_wave64_group_synced_by_barriers_runs_in_halves() { /// the count the lane in the other half wrote (32 for the low half, the /// lane less 32 for the high one). #[test] +#[cfg(windows)] fn lds_synced_in_halves_matches_the_console_on_every_gpu() { let want: Vec = (0..64u32).map(|l| (l ^ 32).min(32)).collect(); let failed = differences_with(&lds_across_halves(), 64, 1, &want, 256, true); @@ -1285,6 +1327,7 @@ fn lds_in_a_loop() -> Vec { /// What the console gives [`lds_in_a_loop`]: each pass, a lane's sum and /// that of the lane 32 away both become their total. +#[cfg(windows)] fn console_lds_in_a_loop() -> Vec { let mut sum: Vec = (0..64).collect(); for _ in 0..4 { @@ -1330,6 +1373,7 @@ fn lds_of_a_one_wave64_group_in_a_loop_runs_in_halves() { let synced = lowered_with(&n, true, true).expect("synced, in halves"); assert_eq!(synced.wave_size, Some(32)); assert_eq!(synced.split_barriers, 2); + #[cfg(windows)] if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut synced.dxil.clone()) .expect("DXIL validation failed"); @@ -1347,6 +1391,7 @@ fn lds_of_a_one_wave64_group_in_a_loop_runs_in_halves() { /// The loop on every hardware adapter, in halves: every pass gives the /// console's sums. #[test] +#[cfg(windows)] fn lds_in_a_loop_in_halves_matches_the_console_on_every_gpu() { let failed = differences_with(&lds_in_a_loop(), 64, 1, &console_lds_in_a_loop(), 256, true); assert!(failed.is_empty(), "{}", failed.join("\n")); @@ -1374,6 +1419,7 @@ const PERM_OLD: u32 = 0xAAAA; /// for FI clear and BOUND_CTRL clear, FI clear and BOUND_CTRL set, FI set /// and BOUND_CTRL clear, and FI and BOUND_CTRL both set, each over a `v1` /// holding [`PERM_OLD`]. EXEC is whole again for every store. +#[cfg(windows)] fn permlanex16_program(lanes: u32) -> Vec { let wave64 = lanes == 64; let full = |w: &mut Vec| { @@ -1473,6 +1519,7 @@ fn the_permlanex16_program_is_what_its_comments_say() { /// 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] { @@ -1485,6 +1532,7 @@ fn permlanex16_picks_lanes_as_the_console_does_on_every_gpu() { &want, 0, false, + false, )); } assert!(failed.is_empty(), "{}", failed.join("\n")); @@ -1503,3 +1551,367 @@ fn the_permlanex16_model_follows_the_instruction() { assert_eq!(permlanex16_console(32)[0], 63); assert_eq!(permlanex16_console(48)[0], 47); } + +/// 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] + ]) +} + +/// 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_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] + ]); + // 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) +} + +/// 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] + ]) +} + +/// 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 + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0xD501_0003, + 0x01A9_FF03, // v_cndmask_b32 v3, v3, 2048.0 in f16, vcc + 0x0000_6800, + ]; + body.extend(&sum[PROLOGUE.len() + 2..sum.len() - 3]); + body.extend([ + 0x7E06_0301, // v_mov_b32 v3, v1 + 0xBEFE_0414, // restore: s_mov_b64 exec, s[20:21] + ]); + body[3] |= (body.len() - 5) as u32; + literal_program(&body) +} + +#[test] +fn literal_wave64_recovers_refusals_in_exactly_one_wave() { + for (words, lds, reason) in [ + (literal_mask_join(false), 0, "a lane mask read as data"), + ( + literal_mask_join(true), + 0, + "a lane mask whose lanes depend on its own value", + ), + (literal_lane_reads(false), 0, "a lane read that may cross"), + (literal_lane_reads(true), 0, "a first-lane read"), + (literal_exec_dwords(), 0, "a lane mask holding lanes elsewhere read as data"), + (literal_lane_write(), 0, "a lane read that may cross"), + (literal_mask_loop(false), 0, "a lane read that may cross"), + (literal_mask_loop(true), 0, "a lane read that may cross"), + (literal_swizzles(), 0, "a lane read that may cross"), + ( + literal_lds(), + 512, + "LDS one console wave64 shares without barriers", + ), + ( + literal_sum(), + 0, + "a wave reduction over both 32-lane halves", + ), + ( + literal_half_sum(), + 0, + "a wave reduction over both 32-lane halves", + ), + ] { + let n = native(&words, true, 64, lds); + let why = lowered_with(&n, true, true).err().expect(reason); + assert!(why.to_string().contains(reason), "{why}"); + let l = lower_halves(&n, true, true, true).unwrap_or_else(|e| panic!("{reason}: {e}")); + assert_eq!(l.wave_size, Some(32)); + if lds != 0 { + assert_eq!(l.split_barriers, 1); + } + #[cfg(windows)] + if let Ok(mut v) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { + v.validate(&mut l.dxil.clone()).expect(reason); + } + } + let words = literal_lane_reads(false); + for threads in [48, 96, 128] { + let n = native(&words, true, threads, 0); + let why = lower_halves(&n, true, true, true) + .err() + .expect("literal is limited to 64 threads"); + assert!( + why.to_string().contains("a lane read that may cross"), + "{why}" + ); + } +} + +#[test] +fn literal_wave64_refuses_a_selector_from_hardware_state() { + let words = literal_program(&[ + 0xB909_0004, // s_getreg_b32 s9, hwreg(HW_ID) + 0xD760_000A, + 0x0200_1300, // v_readlane_b32 s10, v0, s9 + 0x7E06_020A, // v_mov_b32 v3, s10 + ]); + let n = native(&words, true, 64, 512); + let why = lower_halves(&n, true, false, true) + .err() + .expect("unproven lane selector"); + assert!( + why.to_string().contains("a lane read that may cross"), + "{why}" + ); +} + +#[test] +fn literal_wave64_refuses_a_barrier_under_an_unproven_branch() { + let mut words = literal_lds(); + let at = words.iter().position(|&w| w == 0xBF88_0006).unwrap(); + words.splice( + at..=at, + [ + 0xB909_0004, // s_getreg_b32 s9, hwreg(HW_ID) + 0xBF06_8009, // s_cmp_eq_u32 s9, 0 + 0xBF84_0006, // s_cbranch_scc0 restore + ], + ); + let n = native(&words, true, 64, 512); + let why = lower_halves(&n, true, true, true) + .err() + .expect("unproven group convergence"); + assert!( + why.to_string().contains("uniform group control flow"), + "{why}" + ); +} + +#[test] +#[cfg(windows)] +fn literal_wave64_programs_match_the_console_on_every_gpu() { + let cases: [(Vec, u32, Vec); 12] = [ + ( + literal_mask_join(false), + 0, + (0..64).map(|l| 48 * u32::from(l >= 40)).collect(), + ), + ( + literal_mask_join(true), + 0, + (0..64).map(|l| 48 * u32::from(l >= 40)).collect(), + ), + ( + literal_lane_reads(false), + 0, + (0..64).map(|l| 50 * u32::from(l >= 40)).collect(), + ), + ( + literal_lane_reads(true), + 0, + (0..64).map(|l| 40 * u32::from(l >= 40)).collect(), + ), + ( + literal_exec_dwords(), + 0, + (0..64).map(|l| 32 * u32::from(l >= 32)).collect(), + ), + ( + literal_lane_write(), + 0, + (0..64).map(|l| 55 * u32::from(l < 20 || l == 40)).collect(), + ), + ( + literal_mask_loop(false), + 0, + (0..64).map(|l| 7 * (l & 3)).collect(), + ), + ( + literal_mask_loop(true), + 0, + (0..64).map(|l| 7 * (l & 3)).collect(), + ), + (literal_swizzles(), 0, (0..64).map(|l| l & 32).collect()), + ( + literal_lds(), + 512, + (0..64) + .map(|l| if (l & 31) >= 16 { l ^ 32 } else { 0 }) + .collect(), + ), + ( + literal_sum(), + 0, + (0..64) + .map(|l| if l >= 20 { 1826f32.to_bits() } else { 0 }) + .collect(), + ), + ( + literal_half_sum(), + 0, + (0..64).map(|l| if l < 3 { 0x6800 } else { 0 }).collect(), + ), + ]; + for (words, lds, want) in cases { + let failed = differences_in(true, &words, 64, 1, &want, lds, true, true); + assert!(failed.is_empty(), "{}", failed.join("\n")); + } +} diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 3942e51a..8e19cf85 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -25,7 +25,7 @@ mod atomics; mod bvh; mod halves; mod mesh; -use barriers::{in_step, split_wave_barriers}; +use barriers::{group_uniform, in_step, split_wave_barriers}; pub(crate) use mesh::KeptOutputs; use mesh::prune_signature; @@ -122,6 +122,7 @@ pub(crate) struct Lowered { pub raw_loads: [Vec; 2], } +#[derive(Clone)] pub(crate) struct Parts<'a> { pub native: &'a NativeProgram, pub p: &'a Program, @@ -160,14 +161,66 @@ enum Stop { Fail(ShaderError), } +#[cfg(any(test, all(windows, feature = "host")))] pub(crate) fn lower(parts: &Parts) -> Result { - lower_pruned(parts, None) + lower_pruned(parts, None, false) } pub(crate) fn lower_pruned( parts: &Parts, keep: Option<&KeptOutputs>, + literal_halves: bool, ) -> Result { + // Retry refusals from the legacy cross-half gates with whole-wave control flow. + let original = lower_with_structure(parts, keep); + if !literal_halves + || !parts.host_wave32 + || !parts.native.wave64 + || !matches!(&parts.native.io, StageIo::Cs(cs) if cs.threads.iter().product::() == 64) + || !matches!( + &original, + Err(ShaderError::Unsupported { + what: halves::MASK_ACROSS + | LANE_MASK + | MASK_CYCLE + | MASK_ELSEWHERE + | halves::LDS_ACROSS + | halves::REDUCTION_ACROSS + | halves::FIRST_ACROSS + | halves::READ_ACROSS, + .. + }) + ) + { + return original; + } + + let native = parts.native; + // Register-relative move bounds and resource paths must use the same + // control flow as lowering. The per-lane move bounds do not apply here. + let p = crate::ir::build(&native.patched_code(), true, native.vgprs)?; + let st = crate::structure::split_literal(&p)?; + let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st))?; + if !res.waterfall.reads.is_empty() { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a resource waterfall in literal wave64 halves", + }); + } + let io = crate::io::raise(&p, native)?; + lower_with_structure( + &Parts { + p: &p, + st: &st, + res: &res, + io: &io, + ..parts.clone() + }, + keep, + ) +} + +fn lower_with_structure(parts: &Parts, keep: Option<&KeptOutputs>) -> Result { let mut bad = HashMap::new(); loop { match Lower::new(parts, &bad, keep).run() { @@ -278,8 +331,8 @@ struct Lower<'a> { lane_bits: Map, /// IR phi location by value. phi_at: Map, - mask_phis: Map, - pending_masks: Vec<(V, usize, usize)>, + mask_phis: Map, + pending_masks: Vec, data_phis: Vec<(V, usize, usize)>, /// Phis that code reads. Left a std set: [`Lower::live_edges`] starts /// its walk in this set's iteration order, and few phis are read. @@ -342,6 +395,8 @@ struct Lower<'a> { /// In halves: per IR block, whether every lane of the group runs it /// together ([`in_step`]), where values can pass between the halves. step: Vec, + /// In literal halves, the scalar values proven to agree across the group. + group_scalars: Set, /// In halves: the group-shared dwords values pass between the halves /// through, once made ([`Lower::exchange_halves`]). half_words: Option, @@ -510,8 +565,15 @@ enum MaskData { None, } +/// A lane-mask phi made before its inputs: the phi, its IR block and phi +/// index, and in literal halves the (low, high) halves of a 64-lane mask +/// whose per-edge lanes come from `mask_inputs`. +type PendingMask = (V, usize, usize, Option<(Value, Value)>); + /// What a value holding a lane mask read as a number stops with. const LANE_MASK: Why = "a lane mask read as data"; +const MASK_CYCLE: Why = "a lane mask whose lanes depend on its own value"; +const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data"; /// Instructions that read a lane mask (not EXEC implicitly, not a lane's /// bit) as a number. @@ -708,7 +770,7 @@ impl<'a> Lower<'a> { // Code reading other lanes needs the console's wave size and // lane order; so do lane masks read as numbers, and LDS shared // within one wave, where the console compiler leaves out barriers. - console_lanes = insts().any(|i| { + console_lanes = x.st.literal || insts().any(|i| { let n = i.name(); n.starts_with("ds_swizzle") || n.contains("permute") @@ -749,7 +811,7 @@ impl<'a> Lower<'a> { // The console's one wave is several host waves: LDS no longer // passes between its lanes without a barrier. let mut synced = false; - if x.narrow_waves && one_wave && group > 32 && s.lds_dwords > 0 { + if (x.narrow_waves || x.st.literal) && one_wave && group > 32 && s.lds_dwords > 0 { // shortcut: a read in divergent code of what divergent code // wrote gets no barrier (none could be placed there); the // program then runs as before. @@ -829,6 +891,14 @@ impl<'a> Lower<'a> { } } } + let (step, group_scalars) = if x.st.literal { + group_uniform(p, x.st) + } else { + ( + if halves { in_step(p, x.st) } else { Vec::new() }, + Set::default(), + ) + }; Lower { s, x, @@ -880,7 +950,8 @@ impl<'a> Lower<'a> { halves, halves_refused, relabelled: None, - step: if halves { in_step(p, x.st) } else { Vec::new() }, + step, + group_scalars, half_words: None, level: 0, alike: if halves { @@ -1266,7 +1337,20 @@ impl<'a> Lower<'a> { let p = self.x.p; let mut inside: HashMap = HashMap::new(); for b in 0..p.blocks.len() { - let found = super::wave::sections(p, b); + let mut found = super::wave::sections(p, b); + if self.x.st.literal { + // Keep the original f16 addition order and its rounding. + // Sections containing memory operations also keep their LDS barriers. + found.retain(|&start, section| { + !section + .shapes + .values() + .any(|s| matches!(s, super::wave::Shape::Half(..))) + && p.blocks[b].insts[start + 1..section.end] + .iter() + .all(|i| matches!(i.fields, Fields::Valu(_))) + }); + } for (&start, sec) in &found { for i in start + 1..sec.end { for &(_, w) in &p.blocks[b].insts[i].writes { @@ -1323,7 +1407,7 @@ impl<'a> Lower<'a> { /// expanded gives on that wave. fn shape(&mut self, shape: super::wave::Shape) -> Result { use super::wave::{Op, Shape}; - const ACROSS: Why = "a wave reduction over both 32-lane halves (wave64 on a 32-lane host)"; + use halves::REDUCTION_ACROSS as ACROSS; let (op, src, mask, ident, prefix) = match shape { Shape::K(k) => return Ok(self.s.m.i32(k)), Shape::Value(v) => return self.i32_of(v), @@ -1532,6 +1616,12 @@ impl<'a> Lower<'a> { } self.cur = self.s.entry; self.level = self.s.entry; + if self.x.st.literal && order.iter().any(|&b| !self.step[b]) { + return Err(unsupported( + 0, + "literal wave64 halves without uniform group control flow", + )); + } if let Some(why) = self.halves_refused { return Err(unsupported(0, why)); } @@ -1553,7 +1643,14 @@ impl<'a> Lower<'a> { self.exported[b] = !preds.is_empty() && preds.iter().all(|&q| self.exported_out(q)); for (i, phi) in p.blocks[b].phis.iter().enumerate() { let val = match phi.reg { - Reg::S(c) if c == EXEC || c == EXEC + 1 => Val::Missing("a lane mask"), + Reg::S(c) + if (c == EXEC || c == EXEC + 1) + && (!self.x.st.literal + || self.x.st.masks.contains_key(&phi.value) + || self.x.st.highs.contains_key(&phi.value)) => + { + Val::Missing("a lane mask") + } _ if self.bad.contains_key(&phi.value) => Val::Missing(self.bad[&phi.value]), Reg::Scc => { let v = self.s.m.phi(self.cur, self.s.t.i1); @@ -1977,6 +2074,12 @@ impl<'a> Lower<'a> { if let Some(val @ (Val::I32(_) | Val::Bit(_))) = found { return Ok(val); } + if let Some(&vote) = self.x.st.scc_votes.get(&v) { + let at = self + .across_at(self.def_block.get(&v).copied()) + .ok_or(halves::MASK_ACROSS)?; + return self.boolean(vote, at).map(Val::Bit); + } if self.mask_ok && (self.x.st.masks.contains_key(&v) || self.x.st.highs.contains_key(&v)) { return self.mask_dword(v).map(Val::I32); } @@ -2162,7 +2265,8 @@ impl<'a> Lower<'a> { None => (v, false), }; let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?; - if !self.x.st.active.contains(&lo) && !self.ballots.contains_key(&lo) { + if !self.x.st.literal && !self.x.st.active.contains(&lo) && !self.ballots.contains_key(&lo) + { let xy = self.mask_number(lo)?; self.ballots.insert(lo, xy); } @@ -2185,7 +2289,7 @@ impl<'a> Lower<'a> { at = self.across_at(def).ok_or(halves::MASK_ACROSS)?; } if !self.balloting.insert(lo) { - return Err("a lane mask whose lanes depend on its own value"); + return Err(MASK_CYCLE); } let bit = self.boolean(m, at); self.balloting.remove(&lo); @@ -2219,7 +2323,7 @@ impl<'a> Lower<'a> { /// no ballot there gives it: with console lanes, the scalar operation /// that writes it applied to its operands' numbers, as the console does. fn mask_number(&mut self, lo: Value) -> Result<(V, V), Why> { - const ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data"; + use MASK_ELSEWHERE as ELSEWHERE; if self.mask_data != MaskData::Console { return Err(ELSEWHERE); } @@ -3006,6 +3110,27 @@ impl<'a> Lower<'a> { .copied() .unwrap_or("a lane mask from a carry") }), + Atom::Any(bit) => { + if !self.x.st.literal + || !(at == self.level && self.step[self.cur_ir] + || at == self.s.entry + || self + .tail + .iter() + .zip(&self.step) + .any(|(&tail, &step)| step && tail == Some(at))) + { + return Err("a wave64 vote outside converged group code"); + } + let bit = self.boolean(bit, at)?; + let (lo, hi) = self.ballot_across_halves(bit, at)?; + let bits = self.s.m.bin(at, Bin::Or, lo, hi); + let zero = self.s.m.i32(0); + Ok(self.s.m.cmp(at, pred::NE, bits, zero)) + } + Atom::Uniform(v) if self.x.st.literal && !self.group_scalars.contains(&v) => { + Err("an SCC value that may differ between 32-lane halves") + } Atom::Uniform(v) => match self.get(v)? { Val::Bit(x) => Ok(x), Val::I32(x) => { @@ -3014,18 +3139,30 @@ impl<'a> Lower<'a> { } Val::Missing(w) => Err(w), }, - Atom::Phi(id) => { - if let Some(&v) = self.mask_phis.get(&id) { + Atom::Phi(_) | Atom::PairPhi(..) => { + if let Some(&v) = self.mask_phis.get(&atom) { return Ok(v); } + let (id, pair) = match atom { + Atom::Phi(id) => (id, None), + Atom::PairPhi(lo, hi) => ( + if self.phi_at.contains_key(&lo) { + lo + } else { + hi + }, + Some((lo, hi)), + ), + _ => unreachable!(), + }; let &(b, i) = self .phi_at .get(&id) .ok_or("a lane-mask join without a phi")?; let blk = self.block[b].ok_or("an unreachable join")?; let v = self.s.m.phi(blk, self.s.t.i1); - self.mask_phis.insert(id, v); - self.pending_masks.push((v, b, i)); + self.mask_phis.insert(atom, v); + self.pending_masks.push((v, b, i, pair)); Ok(v) } // shortcut: "some lane of the quad is set" is taken as true: the @@ -3048,6 +3185,15 @@ impl<'a> Lower<'a> { let hi = hi.map(word).transpose()?; Ok(self.lane_bit(at, lo, hi)) } + Atom::OpaquePair(lo, hi) => { + if !self.group_scalars.contains(&lo) || !self.group_scalars.contains(&hi) { + return Err("a numeric mask that may differ between 32-lane halves"); + } + let (Val::I32(lo), Val::I32(hi)) = (self.get(lo)?, self.get(hi)?) else { + return Err("an opaque lane mask"); + }; + Ok(self.lane_bit(at, lo, Some(hi))) + } Atom::Constant(k) if self.console_lanes => { let lo = self.s.m.i32(k as u32); let hi = self.s.m.i32((k >> 32) as u32); @@ -3201,7 +3347,7 @@ impl<'a> Lower<'a> { }; // What lanes keep is zero where it has no DXIL form (as // above), so keeping a phi does not make it live. - if let Some(o) = o.filter(|_| !read) { + if let Some(o) = o.filter(|_| !read && !self.x.st.literal) { self.read_phis.remove(&o); } self.s.m.select(self.cur, g, x, old) @@ -3945,6 +4091,14 @@ impl<'a> Lower<'a> { || name.starts_with("ds_swizzle") || name.contains("permute")); let r = match &inst.fields { + Fields::Sop { .. } + if name.starts_with("s_cmp_") + && inst + .write(Reg::Scc) + .is_some_and(|v| self.x.st.scc_votes.contains_key(&v)) => + { + Ok(()) + } Fields::Sop { .. } => self.sop(inst), Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()), Fields::Sopp { .. } if name == "s_barrier" => { @@ -3990,7 +4144,9 @@ impl<'a> Lower<'a> { _ => None, }; let lo = dst_code.and_then(|c| inst.write(Reg::S(c))); - if inst.write(Reg::S(EXEC)).is_some() || self.is_mask(lo) { + let exec_pair = inst.write(Reg::S(EXEC)).is_some() + && (!self.x.st.literal || inst.write(Reg::S(EXEC + 1)).is_some()); + if exec_pair || self.is_mask(lo) { return Err(LANE_MASK); } if matches!( @@ -6435,6 +6591,15 @@ impl<'a> Lower<'a> { } return r; } + if self.x.st.literal && name == "v_readfirstlane_b32" { + if !self.across_here() { + return Err(halves::FIRST_ACROSS); + } + let value = self.src(inst, 0)?; + let exec = self.guard(b, i)?; + let r = self.first_lane_across(value, exec)?; + return self.write_i(inst, r, None); + } // A scalar result (`v_readlane`, `v_readfirstlane`) is written // whatever EXEC holds. let mut guard = match v.dst { @@ -7161,14 +7326,7 @@ impl<'a> Lower<'a> { Some(&Operand::Scalar { code, .. }) => { let m = inst .read(Reg::S(code)) - .and_then(|m| { - self.x - .st - .masks - .get(&m) - .or_else(|| self.x.st.other.get(&m)) - .copied() - }) + .and_then(|m| self.x.st.select_mask(m, inst.read(Reg::S(code + 1)))) .ok_or("a select on an untracked mask")?; self.boolean(m, c)? } @@ -7277,6 +7435,9 @@ impl<'a> Lower<'a> { Err("a VGPR of spilled SGPRs read per lane") } "v_readlane_b32" => { + if self.x.st.literal && !halves::uniform_selector(inst, &self.group_scalars) { + return Err(halves::READ_ACROSS); + } let (a, lane) = (s(self, 0)?, s(self, 1)?); // A computed lane in a pixel or vertex program is a host lane // (from a mask or `v_mbcnt`); a constant one is the console's. @@ -7287,9 +7448,7 @@ impl<'a> Lower<'a> { } if self.halves && !self.one_host_wave() { if !self.across_here() { - return Err( - "a lane read that may cross 32-lane halves (wave64 on a 32-lane host)", - ); + return Err(halves::READ_ACROSS); } let r = self.read_lane_across(a, lane)?; return int(self, r); @@ -7316,6 +7475,15 @@ impl<'a> Lower<'a> { }; self.cross_lane(false)?; let me = self.console_lane(); + let lane = if self.x.st.literal { + if !halves::uniform_selector(inst, &self.group_scalars) { + return Err("a lane write with a nonuniform selector in wave64 halves"); + } + let mask = self.s.m.i32(63); + self.s.m.bin(c, Bin::And, lane, mask) + } else { + lane + }; let is = self.s.m.cmp(c, pred::EQ, me, lane); let r = self.s.m.select(c, is, a, old); int(self, r) @@ -7380,7 +7548,7 @@ impl<'a> Lower<'a> { return Err(halves::FIRST_ACROSS); } let a = s(self, 0)?; - let r = self.first_lane_across(a)?; + let r = self.first_lane_across(a, None)?; return int(self, r); } let a = s(self, 0)?; @@ -9025,16 +9193,35 @@ impl<'a> Lower<'a> { fn uniform_join(&self, b: usize) -> bool { let st = self.x.st; let preds = &self.x.p.blocks[b].preds; - preds.iter().filter(|&&q| self.block[q].is_some()).all(|&q| match st.exits[q] { - LaneExit::Branch { when, taken, not_taken } if taken != not_taken => { - st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) - } - _ => true, - }) + preds + .iter() + .filter(|&&q| self.block[q].is_some()) + .all(|&q| match st.exits[q] { + LaneExit::Branch { + when, + taken, + not_taken, + } if taken != not_taken => st + .bools + .support(when) + .iter() + .all(|a| matches!(a, Atom::Uniform(_) | Atom::Any(_))), + _ => true, + }) } /// Whether no lane goes from IR block `q` to `b`. fn never_taken(&self, q: usize, b: usize) -> bool { + if self.x.st.literal + && self.x.p.blocks[q] + .exit + .successors() + .iter() + .any(|&t| self.rpo[t] <= self.rpo[q]) + { + // The iteration limit can force an exit the console never takes. + return false; + } !self.x.st.bools.meet(&self.lane_edge(q, b)) } @@ -11128,6 +11315,16 @@ impl<'a> Lower<'a> { // A back edge is taken only below the iteration limit. let back = |l: &Self, to: usize| l.counters.contains_key(&to) && l.rpo[to] <= l.rpo[b]; + if self.x.st.literal + && taken != not_taken + && back(self, taken) + && back(self, not_taken) + { + return Err(unsupported( + offset, + "a wave64 branch with two loop back edges", + )); + } // (No `xor` of a compare: a loop exit testing one hung the // AMD driver.) let cond = if back(self, taken) { @@ -11372,6 +11569,16 @@ impl<'a> Lower<'a> { | Atom::Phi(v) | Atom::Quad(v) | Atom::Opaque(v) => Some(v), + Atom::Any(bit) => { + stack.push(bit); + None + } + Atom::PairPhi(lo, hi) | Atom::OpaquePair(lo, hi) => { + if tainted.contains(&lo) || tainted.contains(&hi) { + return true; + } + None + } Atom::Constant(_) => None, }; if v.is_some_and(|v| tainted.contains(&v)) { @@ -11771,14 +11978,38 @@ impl<'a> Lower<'a> { } fn fill_phis(&mut self) -> Result<(), Stop> { + let data = std::mem::take(&mut self.data_phis); + loop { + let before = self.read_phis.len(); + if self.x.st.literal { + self.fill_mask_phis()?; + } + self.fill_data_phis(&data)?; + self.fill_mask_phis()?; + if !self.x.st.literal || before == self.read_phis.len() { + break; + } + } + for (phi, incoming) in std::mem::take(&mut self.counters).into_values() { + self.s.m.set_phi(phi, incoming); + } + Ok(()) + } + + fn fill_data_phis(&mut self, data: &[(V, usize, usize)]) -> Result<(), Stop> { let p = self.x.p; let live = self.live_edges(); - for (v, b, i) in std::mem::take(&mut self.data_phis) { + for &(v, b, i) in data { let phi = &p.blocks[b].phis[i]; let bit = phi.reg == Reg::Scc; let mut incoming = Vec::new(); for (n, &q) in p.blocks[b].preds.iter().enumerate() { let Some(qb) = self.tail[q] else { continue }; + if self.x.st.literal { + self.cur = qb; + self.level = qb; + self.cur_ir = q; + } let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); let arg = phi.args[n]; let read = live.contains(&(phi.value, n)); @@ -11787,7 +12018,8 @@ impl<'a> Lower<'a> { // No lane from this edge reads it, or no lane comes // along it at all: any value will do. _ if read - && (self.never_taken(q, b) || self.dead_on_edge(b, n, phi.reg)) => + && (self.never_taken(q, b) + || !self.x.st.literal && self.dead_on_edge(b, n, phi.reg)) => { if bit { self.s.m.bool(false) @@ -11808,6 +12040,13 @@ impl<'a> Lower<'a> { // A lane mask joined with data at a join every lane // enters along one edge: the register holds the mask's // number there (console lanes, so exact). + _ if read && bit && self.x.st.scc_votes.contains_key(&arg) => self + .get(arg) + .and_then(|v| match v { + Val::Bit(x) => Ok(x), + _ => Err("an SCC without a value"), + }) + .map_err(|w| Stop::Retry(phi.value, w))?, _ if read && !bit && self.mask_data == MaskData::Console @@ -11829,16 +12068,29 @@ impl<'a> Lower<'a> { } self.s.m.set_phi(v, incoming); } - for (phi, incoming) in std::mem::take(&mut self.counters).into_values() { - self.s.m.set_phi(phi, incoming); - } - while let Some((v, b, i)) = self.pending_masks.pop() { + Ok(()) + } + + fn fill_mask_phis(&mut self) -> Result<(), Stop> { + let p = self.x.p; + while let Some((v, b, i, pair)) = self.pending_masks.pop() { let phi = &p.blocks[b].phis[i]; let offset = p.blocks[b].offset; let mut incoming = Vec::new(); for (n, &q) in p.blocks[b].preds.iter().enumerate() { - let Some(qb) = self.tail[q] else { continue }; - let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); + let Some(tail) = self.tail[q] else { continue }; + let qb = self.edges.get(&(q, b)).copied().unwrap_or(tail); + if let Some(pair) = pair { + self.cur = tail; + self.level = tail; + self.cur_ir = q; + let bit = self.x.st.mask_inputs[&pair][n]; + let x = self + .boolean(bit, tail) + .map_err(|w| unsupported(offset, w))?; + incoming.push((x, qb)); + continue; + } let arg = phi.args[n]; const UNTRACKED: Why = "a lane-mask join of an untracked mask"; // Data joined with masks where the wave takes one edge (the BVH diff --git a/crates/victory-shader/src/emit/lower/barriers.rs b/crates/victory-shader/src/emit/lower/barriers.rs index 70855e14..14082a48 100644 --- a/crates/victory-shader/src/emit/lower/barriers.rs +++ b/crates/victory-shader/src/emit/lower/barriers.rs @@ -131,8 +131,13 @@ pub(crate) fn split_wave_barriers(p: &Program, st: &Structured) -> Option Vec { + group_uniform(p, st).0 +} + +/// Blocks reached together and scalar values computed alike by the group. +pub(super) fn group_uniform(p: &Program, st: &Structured) -> (Vec, Set) { let Some(regions) = halves::branch_regions(st) else { - return once_per_lane(p); + return (once_per_lane(p), Set::default()); }; let n = p.blocks.len(); let scalar = |r: Reg| matches!(r, Reg::S(_) | Reg::Scc); @@ -171,17 +176,23 @@ pub(crate) fn in_step(p: &Program, st: &Structured) -> Vec { ) })) .collect(); + let tracked = |v| { + st.literal + && (st.masks.contains_key(&v) + || st.highs.contains_key(&v) + || st.scc_votes.contains_key(&v)) + }; loop { let mut step = vec![true; n]; for (d, region) in ®ions { let LaneExit::Branch { when, .. } = st.exits[*d] else { continue; }; - let together = st - .bools - .support(when) - .iter() - .all(|a| matches!(a, Atom::Uniform(v) if alike.contains(v))); + let together = st.bools.support(when).iter().all(|a| match *a { + Atom::Uniform(v) => alike.contains(&v), + Atom::Any(_) => st.literal, + _ => false, + }); if !together { for (b, &r) in region.iter().enumerate() { step[b] &= !r; @@ -198,7 +209,9 @@ pub(crate) fn in_step(p: &Program, st: &Structured) -> Vec { // Every host wave enters by the same edge. let entered = step[b] && block.preds.iter().all(|&q| step[q]); for phi in &block.phis { - if scalar(phi.reg) && entered && phi.args.iter().all(|a| alike.contains(a)) { + if scalar(phi.reg) + && (tracked(phi.value) || entered && phi.args.iter().all(|a| alike.contains(a))) + { next.insert(phi.value); } } @@ -206,14 +219,26 @@ pub(crate) fn in_step(p: &Program, st: &Structured) -> Vec { let from = inst .reads .iter() - .all(|&(r, v)| scalar(r) && !mask(r) && alike.contains(&v)); - if from && !own(inst) { - next.extend(inst.writes.iter().filter(|w| scalar(w.0)).map(|w| w.1)); - } + .all(|&(r, v)| scalar(r) && (!mask(r) || tracked(v)) && alike.contains(&v)); + let lane_read = st.literal + && step[b] + && match inst.name() { + "v_readfirstlane_b32" => true, + "v_readlane_b32" => { + halves::uniform_selector(inst, &alike) + && inst.writes.first() + .and_then(|w| st.restored.get(&w.1)) + .is_none_or(|source| alike.contains(source)) + } + _ => false, + }; + next.extend(inst.writes.iter().filter_map(|&(r, v)| { + (scalar(r) && (tracked(v) || from && !own(inst) || lane_read)).then_some(v) + })); } } if next.len() == alike.len() { - return step; + return (step, next); } alike = next; } diff --git a/crates/victory-shader/src/emit/lower/halves.rs b/crates/victory-shader/src/emit/lower/halves.rs index 866cb0b1..abb69c77 100644 --- a/crates/victory-shader/src/emit/lower/halves.rs +++ b/crates/victory-shader/src/emit/lower/halves.rs @@ -76,8 +76,7 @@ impl Lower<'_> { /// Why a program in halves cannot run: LDS a group of one console wave /// shares without barriers, split across two host waves. pub(super) fn halves_lds(group: u32, lds_dwords: u32) -> Option { - (lds_dwords > 0 && group > HALF && group <= 64) - .then_some("LDS one console wave64 shares without barriers, on a host of 32-lane waves") + (lds_dwords > 0 && group > HALF && group <= 64).then_some(LDS_ACROSS) } /// The flat thread id, relabelled so that each host wave holds a run of @@ -264,7 +263,21 @@ impl Lower<'_> { /// `v_readfirstlane_b32` of `x`, in halves ([`Lower::across_here`]): the /// lower half's first lane. Every lane of the group runs the block, so /// the console's first lane is in the lower half. - pub(super) fn first_lane_across(&mut self, x: V) -> Result { + pub(super) fn first_lane_across(&mut self, x: V, exec: Option) -> Result { + if let Some(exec) = exec { + let c = self.cur; + let (lo, hi) = self.ballot_across_halves(exec, c)?; + let (zero, k32) = (self.s.m.i32(0), self.s.m.i32(32)); + let first_lo = self.unary_bits(c, 32, lo); + let first_hi = self.unary_bits(c, 32, hi); + let upper = self.s.m.bin(c, Bin::Add, first_hi, k32); + let has_lo = self.s.m.cmp(c, pred::NE, lo, zero); + let has_hi = self.s.m.cmp(c, pred::NE, hi, zero); + // The console reads lane zero when EXEC is empty. + let upper = self.s.m.select(c, has_hi, upper, zero); + let lane = self.s.m.select(c, has_lo, first_lo, upper); + return self.read_lane_across(x, lane); + } let c = self.cur; let (i32t, zero) = (self.s.t.i32, self.s.m.i32(0)); self.s.flags |= flags::WAVE_OPS; @@ -327,6 +340,28 @@ impl Lower<'_> { } } +pub(super) const LDS_ACROSS: Why = + "LDS one console wave64 shares without barriers, on a host of 32-lane waves"; +pub(super) const REDUCTION_ACROSS: Why = + "a wave reduction over both 32-lane halves (wave64 on a 32-lane host)"; +pub(super) const READ_ACROSS: Why = + "a lane read that may cross 32-lane halves (wave64 on a 32-lane host)"; + +/// Whether both halves calculate the same selector for a lane read or write. +pub(super) fn uniform_selector(inst: &Inst, alike: &Set) -> bool { + let Fields::Valu(v) = &inst.fields else { + return false; + }; + match v.src.get(1) { + Some(Operand::Const(k)) => crate::resource::inline(*k).is_some(), + Some(Operand::Literal(_) | Operand::Scalar { code: NULL, .. }) => true, + Some(Operand::Scalar { code, .. }) => { + inst.read(Reg::S(*code)).is_some_and(|v| alike.contains(&v)) + } + _ => false, + } +} + /// Why a lane mask read as data stops in halves: it is written where the /// lanes of the group may not all be, as often, so no group barrier can pass /// it between the halves. diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index b82ed4f1..65023426 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -247,7 +247,7 @@ mod crosslane_tests; mod diff_tests; #[cfg(all(test, windows))] mod flow_tests; -#[cfg(all(test, windows))] +#[cfg(test)] mod halves_tests; #[cfg(all(windows, any(test, feature = "host")))] pub mod host; @@ -461,6 +461,8 @@ pub struct Options { /// than 32 lanes gets group barriers where its lanes read LDS other /// lanes may have written, which the console's lockstep made safe. pub narrow_waves: bool, + /// Keep the per-lane translation for wave64 programs on 32-lane hosts. + pub disable_literal_halves: bool, } /// Metal's limit on a mesh shader's outputs per thread group, in bytes @@ -842,14 +844,14 @@ fn emit_pruned( host_wave32: options.host_wave32, narrow_waves: options.narrow_waves, }; - let l = match lower::lower_pruned(&parts(st, res), keep) { + let l = match lower::lower_pruned(&parts(st, res), keep, !options.disable_literal_halves) { // Discarded lanes kept on as helpers can read what no surviving // lane does (a register only killed lanes skipped writing); such a // program kills them as the console does (`structure::killing`). Err(_) if !st.discards.is_empty() => { let st = structure::killing(p)?; let res = resource::track(p, &native.layout, native.stage, Some(&st))?; - lower::lower_pruned(&parts(&st, &res), keep)? + lower::lower_pruned(&parts(&st, &res), keep, false)? } l => l?, }; diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs index 525f04f0..88a30010 100644 --- a/crates/victory-shader/src/structure.rs +++ b/crates/victory-shader/src/structure.rs @@ -49,14 +49,20 @@ pub enum Atom { Lane(Value), /// An SCC value, the same in every lane. Uniform(Value), + /// Some lane of the console wave satisfies the predicate. + Any(Bool), /// A lane mask joined at a block entry, by its low dword's phi. Phi(Value), + /// A literal mask join by its exact pair of dword values. + PairPhi(Value, Value), /// `s_wqm` result: some lane of the quad is in the source mask. Quad(Value), /// A mask the pass cannot see into (loaded, built from scalars, an /// EXEC write it does not follow): the lane's bit of the register pair /// this value is a dword of. Opaque(Value), + /// A literal mask held in two scalar dwords. + OpaquePair(Value, Value), /// A constant mask other than all lanes or none. Constant(u64), } @@ -430,7 +436,7 @@ impl Bools { pub enum LaneExit { Jump(usize), /// To `taken` in lanes where `when` holds. A condition over - /// [`Atom::Uniform`]s only is a uniform branch. + /// [`Atom::Uniform`] and [`Atom::Any`] predicates is a uniform branch. Branch { when: Bool, taken: usize, @@ -440,10 +446,16 @@ pub enum LaneExit { Indirect, } -/// A [`Program`] as one lane runs it: same blocks, per-lane branches. +/// Lane conditions and branches of a [`Program`]. #[derive(Debug, Clone)] pub struct Structured { pub bools: Bools, + /// Every lane follows the console wave through the blocks. + pub(crate) literal: bool, + /// The incoming lane predicates of each literal mask join. + pub(crate) mask_inputs: Map>, + /// SCC values computed by votes over a mask in literal mode. + pub(crate) scc_votes: Map, /// Per block. pub exits: Vec, /// Per block and instruction: the condition, beyond reaching it, under @@ -461,6 +473,7 @@ pub struct Structured { pub other: Map, /// Exact Wave64 pairs for checking masks at their uses. paired_masks: Map, + paired_other: Map, /// Wave64 masks: low dword's value by the high dword's. pub highs: Map, /// Masks (low dwords) set only in lanes whose EXEC bit is set where @@ -476,6 +489,21 @@ pub struct Structured { } impl Structured { + pub(crate) fn select_mask(&self, low: Value, high: Option) -> Option { + if self.literal { + let key = (low, high?); + self.paired_masks + .get(&key) + .or_else(|| self.paired_other.get(&key)) + .copied() + } else { + self.masks + .get(&low) + .or_else(|| self.other.get(&low)) + .copied() + } + } + pub(crate) fn mask_bits(&self, low: Value, high: Option) -> Option { match high { Some(high) => self.paired_masks.get(&(low, high)), @@ -498,8 +526,16 @@ pub fn killing(program: &Program) -> Result { structure_as(program, false) } +/// Builds the whole-wave form with the console's EXEC at each vector use. +pub(crate) fn split_literal(program: &Program) -> Result { + let mut l = Lanes::new(program, true)?; + let execs = l.masks_in_order(); + let reach = vec![Bool::TRUE; program.blocks.len()]; + l.finish(&execs, &reach) +} + fn structure_as(program: &Program, helpers: bool) -> Result { - let mut l = Lanes::new(program)?; + let mut l = Lanes::new(program, false)?; if !helpers { l.kills.clear(); } @@ -521,6 +557,8 @@ type Key = (Value, Value); struct Lanes<'a> { p: &'a Program, + literal: bool, + pair_joins: Map>, order: Vec, /// Reverse-postorder index per block. index: Vec, @@ -540,6 +578,7 @@ struct Lanes<'a> { /// For branches: SCC of a mask operation ("some lane is set") as the /// lane's own bit. scc_lane: Map, + scc_votes: Map, /// Joins resolved to a constant, to check once all edges are known. joins: Vec, /// Per block: what a lane knows on entry, over forward edges only. @@ -577,7 +616,7 @@ struct SopMasks { const MAX_ROUNDS: usize = 256; impl<'a> Lanes<'a> { - fn new(p: &'a Program) -> Result { + fn new(p: &'a Program, literal: bool) -> Result { let blocks = &p.blocks; let order = crate::ir::reverse_postorder(blocks); let mut index = vec![usize::MAX; blocks.len()]; @@ -607,6 +646,8 @@ impl<'a> Lanes<'a> { } let mut l = Lanes { p, + literal, + pair_joins: Map::default(), order, index, incoming, @@ -617,6 +658,7 @@ impl<'a> Lanes<'a> { masks: Map::default(), other: Map::default(), scc_lane: Map::default(), + scc_votes: Map::default(), joins: Vec::new(), first: vec![Bool::FALSE; blocks.len()], when: vec![None; blocks.len()], @@ -624,7 +666,7 @@ impl<'a> Lanes<'a> { restored: Map::default(), kills: HashSet::new(), }; - for block in blocks { + for block in blocks.iter().filter(|_| !literal) { if let Exit::Branch { taken, not_taken } = block.exit && let Some(last) = block.insts.last() && let Some(live) = l.discards(last) @@ -720,11 +762,13 @@ impl<'a> Lanes<'a> { for n in 0..self.order.len() { let b = self.order[n]; let mut c = if n == 0 { Bool::TRUE } else { Bool::FALSE }; - for k in 0..self.incoming[b].len() { - let (q, taken) = self.incoming[b][k]; - if self.index[q] < n { - let e = self.edge(self.first[q], q, taken); - c = self.b.or(c, e); + if !self.literal { + for k in 0..self.incoming[b].len() { + let (q, taken) = self.incoming[b][k]; + if self.index[q] < n { + let e = self.edge(self.first[q], q, taken); + c = self.b.or(c, e); + } } } self.first[b] = c; @@ -756,7 +800,7 @@ impl<'a> Lanes<'a> { let m = self.mask(old).0; self.masks.insert(new, m); if let Some(scc) = inst.write(Reg::Scc) { - self.scc_lane.insert(scc, m); + self.record_scc(scc, m, false); } } if let Some(k) = self.key(|r| inst.write(r), EXEC) { @@ -766,7 +810,7 @@ impl<'a> Lanes<'a> { if let Exit::Branch { taken, not_taken } = p.blocks[b].exit && let Some(last) = p.blocks[b].insts.last() { - let mut w = self.branch(last); + let mut w = self.raw_when(last); // A discard's "no lane is left" exit: no lane takes it (the // live mask keeps every lane, see `kills`). if let Some(live) = self.discards(last) @@ -829,6 +873,14 @@ impl<'a> Lanes<'a> { cond: &[Bool], ) -> Result { let blocks = &self.p.blocks; + // Resolve back-edge inputs after every definition has been visited. + let mut mask_inputs = Map::default(); + while !self.pair_joins.is_empty() { + for (pair, args) in std::mem::take(&mut self.pair_joins) { + let incoming = args.into_iter().map(|a| self.mask(a).0).collect(); + mask_inputs.insert(pair, incoming); + } + } let b = &mut self.b; let guards = blocks .iter() @@ -846,6 +898,9 @@ impl<'a> Lanes<'a> { | (_, Fields::Sop { .. } | Fields::Sopp { .. } | Fields::Smem { .. }) => { None } + (&Some(e), _) if self.literal => { + (e != Bool::TRUE && inst.name() != "v_writelane_b32").then_some(e) + } (&Some(e), _) => { if let Some((prev, guard)) = last_guard && prev == e @@ -868,7 +923,11 @@ impl<'a> Lanes<'a> { Exit::End => LaneExit::End, Exit::Indirect => LaneExit::Indirect, Exit::Branch { taken, not_taken } => LaneExit::Branch { - when: b.given(self.when[n].unwrap_or(Bool::FALSE), cond[n]), + when: if self.literal { + self.when[n].unwrap_or(Bool::FALSE) + } else { + b.given(self.when[n].unwrap_or(Bool::FALSE), cond[n]) + }, taken, not_taken, }, @@ -877,20 +936,33 @@ impl<'a> Lanes<'a> { if self.b.overflow { return Err(TOO_LARGE); } + // A partially overwritten pair can be read as a mask, but its two + // dwords do not denote a single numeric definition. + let words = self.masks.iter().filter(|&(&(lo, hi), _)| { + !self.literal + || self.defs.get(&lo) == self.defs.get(&hi) + && self.phis.get(&lo).map(|x| x.0) == self.phis.get(&hi).map(|x| x.0) + }); Ok(Structured { - masks: self.masks.iter().map(|(&(lo, _), &m)| (lo, m)).collect(), + literal: self.literal, + mask_inputs, + scc_votes: self.scc_votes, + masks: words.clone().map(|(&(lo, _), &m)| (lo, m)).collect(), other: self.other.iter().map(|(&(lo, _), &m)| (lo, m)).collect(), - highs: self - .masks - .keys() - .filter(|(lo, hi)| lo != hi) - .map(|&(lo, hi)| (hi, lo)) + highs: words + .filter(|&(&(lo, hi), _)| lo != hi) + .map(|(&(lo, hi), _)| (hi, lo)) .collect(), paired_masks: if self.p.wave64 { self.masks } else { Map::default() }, + paired_other: if self.literal { + self.other + } else { + Map::default() + }, active: self.active, restored: self.restored, discards: self @@ -966,7 +1038,12 @@ impl<'a> Lanes<'a> { let derived = exec_write(lo, k.0) || exec_write(hi, k.1); let m = m.unwrap_or_else(|| { let born = self.born(k.0); - self.b.atom(Atom::Opaque(k.0), born) + let atom = if self.literal { + Atom::OpaquePair(k.0, k.1) + } else { + Atom::Opaque(k.0) + }; + self.b.atom(atom, born) }); (m, derived) } @@ -1018,6 +1095,13 @@ impl<'a> Lanes<'a> { { return Some((m, derived)); } + if self.literal { + self.pair_joins.insert(k, args); + return Some(( + self.b.atom(Atom::PairPhi(k.0, k.1), self.index[block]), + derived, + )); + } if !self.unresolved.contains(&id) { for value in [true, false] { let b = &mut self.b; @@ -1125,7 +1209,11 @@ impl<'a> Lanes<'a> { let (a, c) = (arg(0, self)?, arg(1, self)?); let scc = inst.read(Reg::Scc)?; let born = self.born(scc); - let u = self.b.atom(Atom::Uniform(scc), born); + let u = self + .scc_votes + .get(&scc) + .copied() + .unwrap_or_else(|| self.b.atom(Atom::Uniform(scc), born)); (self.b.ite(u, a, c), None) } _ => { @@ -1211,7 +1299,7 @@ impl<'a> Lanes<'a> { } } if let (Some(scc), Some(m)) = (inst.write(Reg::Scc), r.scc) { - self.scc_lane.insert(scc, m); + self.record_scc(scc, m, false); } } // `s_cmp_eq/lg` of a mask: "no lane differs" per lane. @@ -1232,7 +1320,7 @@ impl<'a> Lanes<'a> { } else { ne }; - self.scc_lane.insert(scc, m); + self.record_scc(scc, m, rest.starts_with("eq")); } } Fields::Valu(v) => { @@ -1353,18 +1441,25 @@ impl<'a> Lanes<'a> { false } - /// The per-lane condition under which a block's closing branch is taken. - fn branch(&mut self, inst: &Inst) -> Bool { + /// The closing branch before simplification by its block's reach. + fn raw_when(&mut self, inst: &Inst) -> Bool { let exec = self.exec(inst); match inst.name() { - "s_cbranch_execz" => self.b.not(exec), - "s_cbranch_execnz" => exec, + n @ ("s_cbranch_execz" | "s_cbranch_execnz") => { + let any = self.any(exec, 0); + if n.ends_with("nz") { + any + } else { + self.b.not(any) + } + } n @ ("s_cbranch_vccz" | "s_cbranch_vccnz") => { let vcc = match self.key(|r| inst.read(r), VCC) { Some(k) => self.mask(k).0, None => Bool::FALSE, }; - let any = self.b.and(vcc, exec); + let masked = self.b.and(vcc, exec); + let any = self.any(masked, 0); if n.ends_with("nz") { any } else { @@ -1375,7 +1470,7 @@ impl<'a> Lanes<'a> { let Some(scc) = inst.read(Reg::Scc) else { return Bool::FALSE; }; - let set = match self.scc_lane.get(&scc) { + let set = match self.scc_votes.get(&scc).or(self.scc_lane.get(&scc)) { Some(&m) => m, None => { let born = self.born(scc); @@ -1391,6 +1486,25 @@ impl<'a> Lanes<'a> { } } + fn any(&mut self, bit: Bool, born: usize) -> Bool { + if self.literal && bit != Bool::FALSE && bit != Bool::TRUE { + self.b.atom(Atom::Any(bit), born) + } else { + bit + } + } + + fn record_scc(&mut self, scc: Value, bit: Bool, all: bool) { + if self.literal { + let test = if all { self.b.not(bit) } else { bit }; + let voted = self.any(test, self.born(scc)); + let voted = if all { self.b.not(voted) } else { voted }; + self.scc_votes.insert(scc, voted); + } else { + self.scc_lane.insert(scc, bit); + } + } + /// What a lane knows on entering each block, to a fixpoint. A loop /// header forgets what the back edge says about atoms the loop redefines. fn paths(&mut self) -> Result, ShaderError> {