diff --git a/crates/viport-shader/src/emit/lower.rs b/crates/viport-shader/src/emit/lower.rs index 05ccaeb..f977bae 100644 --- a/crates/viport-shader/src/emit/lower.rs +++ b/crates/viport-shader/src/emit/lower.rs @@ -11562,1186 +11562,5 @@ fn heap_usage_marks() -> bool { } #[cfg(test)] -mod tests { - use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower, packed_half}; - use crate::native::{ - ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, - }; - use crate::{io, ir, resource, structure}; - - const S_ENDPGM: u32 = 0xBF81_0000; - - /// Whether a synthetic compute program translates with these input registers. - fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { - lowered(words, rsrc2).map(|_| ()) - } - - /// [`lowers`], keeping the lowered program so its DXIL can be inspected. - fn lowered(words: &[u32], rsrc2: u32) -> Result { - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2, - threads: [1, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, false, 256).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - let io = io::raise(&p, &native).unwrap(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - }) - } - - /// Lowers a compute program with the root parameters `layout` (in user - /// SGPRs from s0 on) and the used resources `used`. - fn lower_with( - words: &[u32], - layout: Vec, - used: Vec, - ) -> Result { - lower_wave(words, layout, used, false) - } - - /// [`lower_with`] in wave64 if `wave64`. - fn lower_wave( - words: &[u32], - layout: Vec, - used: Vec, - wave64: bool, - ) -> Result { - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64, - vgprs: 256, - layout, - used, - io: StageIo::Cs(ComputeIo { - // The layout's user SGPRs (at least two), 512 bytes of LDS. - rsrc2: 1 << 15 | sgprs.max(2) << 1, - threads: [1, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, wave64, 256).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - let io = io::raise(&p, &native).unwrap(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - }) - } - - /// Root parameter `slot` in user SGPRs from `user_data` on. - fn root(root: RootType, user_data: u8, slot: u8) -> RootParam { - RootParam { - root, - table_offset_dwords: 0, - sgprs: if root == RootType::Descriptor { 2 } else { 1 }, - base_register: 0, - user_data, - slot, - } - } - - /// Lowers a pixel program with one float `SV_Target0`: whether it - /// translates. - fn lowers_ps(words: &[u32]) -> Result<(), crate::ShaderError> { - let target = crate::emit::container::SigElement { - name: "SV_Target".into(), - index: 0, - kind: 16, - comp: 9, - interp: 0, - row: Some(0), - col: 0, - cols: 4, - usage: 0, - half: false, - }; - lowers_ps_with(words, vec![target]) - } - - /// [`lowers_ps`] with the output elements `outputs`. - fn lowers_ps_with( - words: &[u32], - outputs: Vec, - ) -> Result<(), crate::ShaderError> { - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let native = NativeProgram { - stage: HwStage::Ps, - wave64: false, - vgprs: 4, - layout: vec![], - used: vec![], - io: StageIo::Ps { - inputs: vec![], - input_addr: 0, - db_shader_control: 0, - patches: vec![], - }, - code, - }; - let p = ir::build(&native.code, false, 4).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - let io = io::raise(&p, &native).unwrap(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs, - prims: vec![], - mesh_stride: 0, - }) - .map(|_| ()) - } - - #[test] - fn a_compressed_export_unpacks_two_f16_channels_per_dword() { - // A compr export: each source dword packs two f16 channels, the - // low half first, so four channels come from two VGPRs. - let words = [ - 0x7E00_0282, // v_mov_b32 v0, 2 - 0x7E02_0282, // v_mov_b32 v1, 2 - 0xF800_0C0F, - 0x0000_0100, // exp mrt0, v0, v0, v1, v1 done compr - S_ENDPGM, - ]; - lowers_ps(&words).unwrap(); - } - - #[test] - fn a_compressed_export_to_a_uint_target_stays_refused() { - // The halves of a compr dword are f16 values: a uint target would - // store their f32 bits as integers, so the export stays refused. - let words = [ - 0x7E00_0282, // v_mov_b32 v0, 2 - 0x7E02_0282, // v_mov_b32 v1, 2 - 0xF800_0C0F, - 0x0000_0100, // exp mrt0, v0, v0, v1, v1 done compr - S_ENDPGM, - ]; - let target = crate::emit::container::SigElement { - name: "SV_Target".into(), - index: 0, - kind: 16, - comp: 5, - interp: 0, - row: Some(0), - col: 0, - cols: 4, - usage: 0, - half: false, - }; - assert!(matches!( - lowers_ps_with(&words, vec![target]), - Err(crate::ShaderError::Unsupported { - what: "a compressed export", - .. - }) - )); - } - - #[test] - fn a_compressed_depth_export_with_stencil_stays_refused() { - // `exp mrtz` compr packs the depth and the stencil into one dword. - // The stencil half is an integer, so the export stays refused. - let words = [ - 0x7E00_0282, // v_mov_b32 v0, 2 - 0xF800_0C8F, - 0x0000_0000, // exp mrtz, v0, v0 done compr - S_ENDPGM, - ]; - let element = |name: &str, kind: u8, comp: u8| crate::emit::container::SigElement { - name: name.into(), - index: 0, - kind, - comp, - interp: 0, - row: None, - col: 0, - cols: 1, - usage: 0, - half: false, - }; - let outputs = vec![element("SV_Depth", 17, 9), element("SV_StencilRef", 20, 5)]; - assert!(matches!( - lowers_ps_with(&words, outputs), - Err(crate::ShaderError::Unsupported { - what: "a compressed export", - .. - }) - )); - } - - #[test] - fn a_scalar_carry_chain_reaches_the_select() { - // The high dword of a 64-bit add or subtract, then a select on the - // carry (borrow) the high half leaves in SCC, and a branch on it - // (only code with an effect needs its operands). - let add = [ - 0xBE80_03C1, // s_mov_b32 s0, -1 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0x8000_8100, // s_add_u32 s0, s0, 1 - 0x8201_8001, // s_addc_u32 s1, s1, 0 - 0x8502_0001, // s_cselect_b32 s2, s1, s0 - 0xBF07_8002, // s_cmp_lg_u32 s2, 0 - 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm - 0xBE83_0380, // s_mov_b32 s3, 0 - S_ENDPGM, - ]; - let sub = [ - 0xBE80_0380, // s_mov_b32 s0, 0 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0x8080_8100, // s_sub_u32 s0, s0, 1 - 0x8281_8001, // s_subb_u32 s1, s1, 0 - 0x8502_0001, // s_cselect_b32 s2, s1, s0 - 0xBF07_8002, // s_cmp_lg_u32 s2, 0 - 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm - 0xBE83_0380, // s_mov_b32 s3, 0 - S_ENDPGM, - ]; - - for words in [add, sub] { - lowers(&words, 0).unwrap(); - } - } - - #[test] - fn v_cndmask_accepts_uniform_and_constant_masks() { - // Uniform select (`s_cselect_b32`) and inline constant masks in `v_cndmask_b32` - // (resolved in `Structured::other` or directly as constants). - let words = [ - 0xBF06_8000u32, // s_cmp_eq_u32 s0, 0 - 0x8500_80C1, // s_cselect_b32 s0, -1, 0 - 0xD501_0001, - 0x0001_0080, // v_cndmask_b32 v1, 0, 1, s0 - 0xD501_0002, - 0x0201_02C1, // v_cndmask_b32 v2, 1, v1, -1 - 0xD834_0000, - 0x0000_0200, // ds_write_b32 v0, v2 - S_ENDPGM, - ]; - lowers(&words, 0x8001).unwrap(); - } - - fn perm_features(selector: u32) -> u64 { - // Synthetic compute shader: - // v0 is the thread ID and can supply a dynamic selector. - // Store the result in LDS to keep the permutation live. - let words = [ - 0x7E02_02FFu32, - 0x817F_34AB, - 0x7E04_02FF, - 0xFE01_56CD, - 0xD744_0003, - 257 | (258 << 9) | (selector << 18), - 0x3408_0082, - 0xD834_0000, - 0x0000_0304, - S_ENDPGM, - ]; - - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2: 1 << 15, - threads: [64, 1, 1], - }), - code, - }; - - let p = ir::build(&native.code, false, 256).unwrap(); - - assert!( - p.blocks - .iter() - .flat_map(|b| &b.insts) - .any(|i| i.name() == "v_perm_b32") - ); - - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); - - let io = io::raise(&p, &native).unwrap(); - - let emitted = lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - }) - .unwrap(); - - let container = crate::Container::parse(&emitted.dxil).unwrap(); - - let features = container.part(crate::FourCC::SFI0).unwrap(); - - u64::from_le_bytes(features.data.try_into().unwrap()) - } - - /// Lowers `alu` on the thread id v0 into v3, kept by an LDS store. - fn refactoring(alu: &[u32]) -> (bool, Vec) { - let mut words = alu.to_vec(); - words.extend([ - 0x7E08_0280, // v_mov_b32 v4, 0 - 0xD834_0000, // ds_write_b32 v4, v3 - 0x0000_0304, - S_ENDPGM, - ]); - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let names = ir::build(&code, false, 256).unwrap().blocks[0] - .insts - .iter() - .map(|i| i.name().to_string()) - .collect(); - let lowered = lower_with(&words, vec![], vec![]).unwrap(); - (lowered.refactoring, names) - } - - #[test] - fn only_programs_with_fmad_let_the_host_refactor() { - let (fused, names) = refactoring(&[ - 0xD54B_0003, // v_fma_f32 v3, v0, v0, v0 - 0x0402_0100, - ]); - assert_eq!(names[0], "v_fma_f32"); - assert!(fused, "FMad needs refactoring to fuse"); - let (apart, names) = refactoring(&[ - 0x1006_0100, // v_mul_f32 v3, v0, v0 - 0x0606_0103, // v_add_f32 v3, v3, v0 - ]); - assert_eq!(names[..2], ["v_mul_f32", "v_add_f32"]); - assert!(!apart, "a multiply and an add stay apart"); - } - - #[test] - fn perm_constant_selector_needs_no_int64() { - assert_eq!(perm_features(128) & 0x8000, 0); - } - - #[test] - fn perm_dynamic_selector_needs_no_int64() { - assert_eq!( - perm_features(256) & 0x8000, - 0, - "dynamic v_perm_b32 must not require INT64" - ); - } - - #[test] - fn a_descriptor_selected_by_scc_picks_its_heap_index() { - // Two buffer descriptors loaded from the table at s0, one picked by - // a root constant (s1) with s_cselect_b64 per half, and loaded - // through by index and stored to LDS so the load is needed. - let words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null - 0xF408_0302, - 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10 - 0xBF06_8001, // s_cmp_eq_u32 s1, 0 - 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13] - 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15] - 0xE030_2000, - 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; - // Both are structured buffers of dwords in the table's range. - let used = || { - vec![UsedResource { - kind: ResourceType::Srv, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 4, - dwords: 4, - user_data: 0, - slot: 0, - }] - }; - lower_with(&words, layout(), used()).unwrap(); - } - - /// `v_mov_b32 vdst, src0` (`src0`: 128 is the inline zero). - fn v_mov(vdst: u8, src0: u16) -> u32 { - 0x7E00_0000 | (vdst as u32) << 17 | 0x01 << 9 | (src0 as u32 & 0x1FF) - } - - /// `ds_write_b32 v[addr], v[data]`. - fn ds_write_b32(addr: u8, data: u8) -> [u32; 2] { - [0xD834_0000, u32::from(addr) | u32::from(data) << 8] - } - - /// A buffer access: MUBUF (`mtbuf` false, opcode in bits 18-25, a - /// resource and optional `idxen`/`offen`) or MTBUF (`mtbuf` true, opcode - /// in bits 15-18, the format in bits 19-25), `srsrc` the first of four - /// resource SGPRs, `vdata`/`vaddr` VGPRs and `offset` a byte offset. - #[allow(clippy::too_many_arguments)] - fn buffer( - opcode: u16, - mtbuf: bool, - format: u8, - offset: u16, - offen: bool, - idxen: bool, - vdata: u8, - vaddr: u8, - srsrc: u8, - ) -> [u32; 2] { - let class = if mtbuf { 0x3A } else { 0x38 }; - let op_shift = if mtbuf { 16 } else { 18 }; - [ - class << 26 - | u32::from(opcode & if mtbuf { 0x7 } else { 0x7F }) << op_shift - | u32::from(format) << 19 - | u32::from(offen) << 12 - | u32::from(idxen) << 13 - | u32::from(offset), - // soffset is the inline zero, TFE and GLC clear; MTBUF keeps - // the top bit of its opcode here. - 0x80 << 24 - | u32::from(if mtbuf { opcode >> 3 } else { 0 }) << 21 - | u32::from(srsrc >> 2) << 16 - | u32::from(vdata) << 8 - | u32::from(vaddr), - ] - } - - /// A program that reads the descriptor at table entry 0 into `s[8:11]`, - /// runs `fetch` (VGPRs from 0, its address in v3) and writes its VGPRs - /// to LDS: the three positions of a vertex fetch, or four channels. - fn fetch_program(fetch: [u32; 2], channels: u8) -> Vec { - let mut words = vec![ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null - v_mov(3, 128), // v_mov_b32 v3, 0 (the fetch's address) - v_mov(channels + 1, 128), // v_mov_b32 v5, 0 (the LDS address) - ]; - words.extend_from_slice(&fetch); - for k in 0..channels { - words.extend_from_slice(&ds_write_b32(channels + 1, k)); - } - words.push(S_ENDPGM); - words - } - - /// The descriptor at table entry 0: a typed or raw SRV of `stride` (0: - /// none), read as `dwords` dwords. - fn fetch_tables(stride: u32, dwords: u8) -> (Vec, Vec) { - let layout = vec![root(RootType::Table, 0, 0)]; - let used = vec![UsedResource { - kind: ResourceType::Srv, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride, - dwords, - user_data: 0, - slot: 0, - }]; - (layout, used) - } - - #[test] - fn every_buffer_format_names_its_bits_and_numbers() { - // Every number names a format, 1 to 77, and no number past that - // does: the element sizes the typed fetches read follow from these. - for format in 1..=77u8 { - let (bits, _) = buffer_format(format).unwrap_or_else(|| panic!("format {format}")); - let total: u32 = bits.iter().sum(); - assert_eq!(total % 8, 0, "format {format}: {bits:?} is whole bytes"); - assert!( - total == 8 || total == 16 || total >= 32, - "format {format}: {bits:?} is a dword or a byte/half inside one" - ); - } - assert_eq!(buffer_format(78), None); - // The vertex fetch shapes: float3 is 12 bytes (16_16_16_16 comes - // first, at 65), half2 and unorm8x4 are 4. - let bytes = |f| -> u32 { buffer_format(f).unwrap().0.iter().sum::() / 8 }; - assert_eq!(bytes(74), 12, "32_32_32_FLOAT"); - assert_eq!(bytes(24), 4, "16_16_SNORM"); - assert_eq!(bytes(56), 4, "8_8_8_8_UNORM"); - } - - #[test] - fn a_typed_fetch_inside_a_dword_reads_the_pair_around_it() { - // `tbuffer_load_format_xyz` at byte offset 33: the console reads - // the bytes at 33, so the host reads the dword-aligned pair and - // shifts (a dword read promised at 33 can return zeros). - let odd = buffer(0x002, true, 74, 33, false, false, 0, 3, 8); - let (layout, used) = fetch_tables(0, 4); - let l = lower_with(&fetch_program(odd, 3), layout, used).unwrap(); - assert_eq!(l.unaligned_typed_loads, 1); - // The same fetch on a dword boundary is one plain read. - let even = buffer(0x002, true, 74, 32, false, false, 0, 3, 8); - let (layout, used) = fetch_tables(0, 4); - let l = lower_with(&fetch_program(even, 3), layout, used).unwrap(); - assert_eq!(l.unaligned_typed_loads, 0); - } - - #[test] - fn a_four_dword_typed_fetch_inside_a_dword_loads_at_most_four_words_at_a_time() { - // `tbuffer_load_format_xyzw` of format 77 at byte offset 33 needs - // five aligned words; one raw load returns four and then the - // status, so the fifth is read by a second load (the load closure - // asserts no load asks for more than four). - let odd = buffer(0x003, true, 77, 33, false, false, 0, 3, 8); - let (layout, used) = fetch_tables(0, 4); - let l = lower_with(&fetch_program(odd, 4), layout, used).unwrap(); - assert_eq!(l.unaligned_typed_loads, 1); - } - - #[test] - fn a_typed_fetch_of_no_format_is_refused() { - // Format 0 is not a format: the fetch must stop rather than read - // whatever the descriptor holds. - let fetch = buffer(0x002, true, 0, 0, true, false, 0, 3, 8); - let (layout, used) = fetch_tables(0, 4); - let err = match lower_with(&fetch_program(fetch, 3), layout, used) { - Err(e) => e, - Ok(_) => panic!("a fetch of format 0 lowered"), - }; - assert!( - matches!( - err, - crate::ShaderError::Unsupported { - what: "a buffer format", - .. - } - ), - "{err:?}" - ); - } - - /// Tables of 2D textures at s0 and samplers at s1. - fn texture_tables() -> (Vec, Vec) { - let range = |kind, user_data, slot| UsedResource { - kind, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: if kind == ResourceType::Sampler { 4 } else { 8 }, - user_data, - slot, - }; - ( - vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)], - vec![ - range(ResourceType::Srv, 0, 0), - range(ResourceType::Sampler, 1, 1), - ], - ) - } - - #[test] - fn a_descriptor_loaded_only_for_its_size_takes_the_kind_of_its_reload() { - // The record count of the buffer at s0 (count - 1 as an index), then - // the same descriptor loaded again for the indexed read. - let words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null - 0x810C_C10A, // s_add_i32 s12, s10, -1 - 0xF408_0402, - 0xFA00_0000, // s_load_dwordx4 s[16:19], s[4:5], null - 0x7E04_020C, // v_mov_b32 v2, s12 - 0xE030_2000, - 0x8004_0102, // buffer_load_dword v1, v2, s[16:19], 0 idxen - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; - let used = vec![UsedResource { - kind: ResourceType::Srv, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 4, - dwords: 4, - user_data: 0, - slot: 0, - }]; - lower_with(&words, layout, used).unwrap(); - } - - #[test] - fn a_waterfall_loop_that_only_sizes_takes_the_kind_of_the_sampled_one() { - // Each lane names table entry (lane & 1) by its byte offset in v7. - // A first waterfall loop only reads the width bits of the entry - // (`v_alignbit_b32`), a second one samples it; the width goes to the - // buffer at dword 16 of the table. - let words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xBE86_0301, // s_mov_b32 s6, s1 - 0xBE87_0380, // s_mov_b32 s7, 0 - 0xF408_0203, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 - 0xF408_0A02, - 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 - 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 - 0x7E06_0302, // v_mov_b32 v3, v2 - 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 - 0x360E_0081, // v_and_b32 v7, 1, v0 - 0x340E_0E85, // v_lshlrev_b32 v7, 5, v7 - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0xBE97_037E, // s_mov_b32 s23, exec_lo - 0xBE95_037E, // s_mov_b32 s21, exec_lo - 0x7E28_0507, // L1: v_readfirstlane_b32 s20, v7 - 0x7DA4_0E14, // v_cmpx_eq_u32 exec_lo, s20, v7 - 0xF40C_0302, - 0x2800_0000, // s_load_dwordx8 s[12:19], s[4:5], s20 - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0xD54E_0008, - 0x0278_1A0E, // v_alignbit_b32 v8, s14, s13, 30 - 0xBE95_4715, // s_andn2_wrexec_b32 s21, s21 - 0xBF89_FFF7, // s_cbranch_execnz L1 - 0xBEFE_0317, // s_mov_b32 exec_lo, s23 - 0xBE95_037E, // s_mov_b32 s21, exec_lo - 0x7E28_0507, // L2: v_readfirstlane_b32 s20, v7 - 0x7DA4_0E14, // v_cmpx_eq_u32 exec_lo, s20, v7 - 0xF40C_0302, - 0x2800_0000, // s_load_dwordx8 s[12:19], s[4:5], s20 - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0xF09C_0F08, - 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:2D - 0xBF8C_3F70, // s_waitcnt vmcnt(0) - 0xBE95_4715, // s_andn2_wrexec_b32 s21, s21 - 0xBF89_FFF6, // s_cbranch_execnz L2 - 0xBEFE_0317, // s_mov_b32 exec_lo, s23 - 0xE070_1000, - 0x800A_0810, // buffer_store_dword v8, v16, s[40:43], 0 offen - S_ENDPGM, - ]; - let (layout, used) = texture_and_uav_tables(); - lower_wave(&words, layout, used, false).unwrap(); - } - - #[test] - fn compute_spills_beside_a_descriptor_word_read_back() { - // Dword 0 of a buffer descriptor (no host value) and a root constant - // spilled to lanes 0 and 1 of v5 in a compute program; reading lane - // 1 back is the constant (the descriptor's lane is never read). - let words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null - 0xD761_0005, - 0x0001_0008, // v_writelane_b32 v5, s8, 0 - 0xD761_0005, - 0x0001_0201, // v_writelane_b32 v5, s1, 1 - 0xD760_000C, - 0x0001_0305, // v_readlane_b32 s12, v5, 1 - 0xE030_2000, - 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen - 0x7E06_020C, // v_mov_b32 v3, s12 - 0xD834_0000, - 0x0000_0300, // ds_write_b32 v0, v3 - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; - let used = vec![UsedResource { - kind: ResourceType::Srv, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 4, - dwords: 4, - user_data: 0, - slot: 0, - }]; - lower_with(&words, layout, used).unwrap(); - } - - #[test] - fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() { - use crate::resource::tests::{ - WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32, - }; - for (words, wave64) in [ - (WATERFALL_FETCHED_WAVE32, false), - (WATERFALL_FETCHED_WAVE64, true), - (WATERFALL_PICKED_WAVE32, false), - ] { - let (layout, used) = texture_tables(); - let l = lower_wave(words, layout, used, wave64).unwrap(); - // The loop's reads of the first lane became each lane's own - // dwords: no wave operation is left. - assert_eq!(l.nonuniform_handles, 1); - assert!(!l.wave_ops); - } - } - - /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first. - pub(crate) fn texture_and_uav_tables() -> (Vec, Vec) { - let (layout, mut used) = texture_tables(); - used.push(UsedResource { - kind: ResourceType::Uav, - root: RootType::Table, - table_offset_dwords: 16, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data: 0, - slot: 0, - }); - (layout, used) - } - - #[test] - fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() { - use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32}; - for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] { - let (layout, used) = texture_and_uav_tables(); - let l = lower_wave(words, layout, used, false).unwrap(); - // One image handle, from the join's per-lane heap index. - assert_eq!(l.nonuniform_handles, 1); - assert!(!l.wave_ops); - } - } - - #[test] - fn scalar_bit_tests_lower() { - // Each tests one bit of a constant into SCC and branches on it (only - // code with an effect needs its operands). - let tail = [ - 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm - 0xBE84_0380, // s_mov_b32 s4, 0 - S_ENDPGM, - ]; - let bit_tests: [&[u32]; 4] = [ - &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3 - &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3 - &[ - 0xBE80_0387, // s_mov_b32 s0, 7 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3 - ], - &[ - 0xBE80_0387, // s_mov_b32 s0, 7 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3 - ], - ]; - for head in bit_tests { - let words: Vec = head.iter().chain(&tail).copied().collect(); - lowers(&words, 0).unwrap(); - } - } - - #[test] - fn scalar_64_bit_field_ops_lower() { - // Each makes a 64-bit field from constants and branches on SCC (only - // code with an effect needs its operands). - let tail = [ - 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm - 0xBE87_0380, // s_mov_b32 s7, 0 - S_ENDPGM, - ]; - let consts = [ - 0xBE80_0387, // s_mov_b32 s0, 7 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0xBE82_0388, // s_mov_b32 s2, 8 - ]; - let field_tests: [&[u32]; 3] = [ - &[0x9484_0200], // s_bfe_u64 s[4:5], s[0:1], s2 - &[0x9504_0200], // s_bfe_i64 s[4:5], s[0:1], s2 - // s_bfm_b64 s[4:5], s0, s1; its result is read by s_or_b32, - // which sets the SCC the branch uses. - &[0x9284_0100, 0x8806_0504], - ]; - for body in field_tests { - let words: Vec = consts.iter().chain(body).chain(&tail).copied().collect(); - lowers(&words, 0).unwrap(); - } - } - - #[test] - fn a_missing_value_stays_missing_through_two_live_joins() { - let mut words = [ - 0xF490_0180, - 0, // s_memtime s[6:7] - 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) - 0xBF85_0001, // skip the first overwrite - 0xBE86_0380, // s_mov_b32 s6, 0 - 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y) - 0xBF85_0001, // skip the second overwrite - 0xBE86_0381, // s_mov_b32 s6, 1 - 0xBF07_8006, // s_cmp_lg_u32 s6, 0 - 0xBF85_0001, // use the result to branch - 0xBE83_0380, - S_ENDPGM, - ]; - let group_ids_xy = 3 << 7; - // Compare to a direct read so future timestamp support works in both cases. - let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { - Ok(()) => None, - Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), - Err(error) => panic!("{error}"), - }; - let direct = [&words[..2], &words[8..]].concat(); - assert_eq!(refusal(&words), refusal(&direct)); - words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead - lowers(&words, group_ids_xy).expect("dead timestamp"); - } - - #[test] - fn a_wave_prefix_of_min_lowers() { - // A whole-wave section that leaves the inclusive prefix of a min: - // each lane the minimum of the lanes up to and including it. The - // scan runs with `row_shr` steps inside each row, and the first - // row's prefix is read out and folded under the second. The store - // after the section reads the prefix, so the value cannot be left - // missing: a wave prefix of a min has to lower. - let words = [ - 0x7E00_0280, // v_mov_b32 v0, 0 - // 32-bit scalar forms: the wave32 pass follows their masks. - 0xBE84_3DC1, // s_or_saveexec_b32 s4, -1 - 0x876A_C104, // s_and_b32 s106, s4, -1 - 0x0202_00C1, // v_cndmask_b32 v1, -1, v0, vcc - 0x2602_02FA, // v_min_u32 v1, v1 row_shr:1, v1 - 0xFF01_1101, - 0x2602_02FA, // v_min_u32 v1, v1 row_shr:2, v1 - 0xFF01_1201, - 0x2602_02FA, // v_min_u32 v1, v1 row_shr:3, v1 - 0xFF01_1301, - 0x2602_02FA, // v_min_u32 v1, v1 row_shr:4, v1 - 0xFF01_1401, - 0x2602_02FA, // v_min_u32 v1, v1 row_shr:5, v1 - 0xFF01_1501, - 0x2602_02FA, // v_min_u32 v1, v1 row_shr:6, v1 - 0xFF01_1601, - 0x2602_02FA, // v_min_u32 v1, v1 row_shr:7, v1 - 0xFF01_1701, - 0x2602_02FA, // v_min_u32 v1, v1 row_shr:8, v1 - 0xFF01_1801, - 0x2602_02FA, // v_min_u32 v1, v1 row_shr:9, v1 - 0xFF01_1901, - 0x2602_02FA, // v_min_u32 v1, v1 row_shr:10, v1 - 0xFF01_1A01, - 0x2602_02FA, // v_min_u32 v1, v1 row_shr:11, v1 - 0xFF01_1B01, - 0x2602_02FA, // v_min_u32 v1, v1 row_shr:12, v1 - 0xFF01_1C01, - 0x2602_02FA, // v_min_u32 v1, v1 row_shr:13, v1 - 0xFF01_1D01, - 0x2602_02FA, // v_min_u32 v1, v1 row_shr:14, v1 - 0xFF01_1E01, - 0x2602_02FA, // v_min_u32 v1, v1 row_shr:15, v1 - 0xFF01_1F01, - 0xD760_0006, // v_readlane_b32 s6, v1, 15 - 0x0001_1F01, - 0x7E04_0206, // v_mov_b32 v2, s6 - 0x2602_02FA, // v_min_u32 v1, v2 quad_perm:[0,1,2,3] row_mask:0x2, v1 - 0x2F00_E402, - 0xBEFE_0304, // s_mov_b32 exec_lo, s4 - 0xD834_0000, // ds_write_b32 v0, v1 - 0x0000_0100, - S_ENDPGM, - ]; - let out = lowered(&words, 1 << 15).unwrap(); - // Drivers do not implement `wavePrefixOp` kinds 2 and 3 (hardware - // readback on PR #470), so the min prefix must lower to a - // `WaveReadLaneAt` scan instead. - assert_eq!(out.prefix_scans, 1, "a min prefix must scan, not prefix-op"); - // dxil.dll, where there is one, checks the scan's module too. - #[cfg(windows)] - { - if let Ok(mut v) = super::super::validator::Validator::load( - super::super::validator::Validator::default_path().as_deref(), - ) { - v.validate(&mut out.dxil.clone()).unwrap(); - } - } - } - -#[test] - fn a_value_no_lane_from_its_edge_reads_needs_no_form() { - // s6 is a timestamp (no DXIL form) where the load is skipped and 5 - // where it runs; a flag in v1, set only with the load, guards the - // read after the join (the console compiler's form, where the - // skipped path leaves a stale lane mask in the register). - let mut words = [ - 0xF490_0180, - 0, // s_memtime s[6:7] - 0x7E02_0280, // v_mov_b32 v1, 0 - 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) - 0xBF85_0002, // s_cbranch_scc1 -> join - 0xBE86_0385, // s_mov_b32 s6, 5 - 0x7E02_02C1, // v_mov_b32 v1, -1 - 0x7D84_02C1, // join: v_cmp_eq_u32 vcc_lo, -1, v1 - 0xBF86_0003, // s_cbranch_vccz -> end - 0xBF07_8006, // s_cmp_lg_u32 s6, 0 - 0xBF85_0001, // s_cbranch_scc1 -> end - 0xBE84_0380, // s_mov_b32 s4, 0 - S_ENDPGM, - ]; - let group_ids_xy = 3 << 7; - lowers(&words, group_ids_xy).expect("the timestamp is never read"); - // With the flag set on both paths the timestamp is read: as refused - // (or accepted) as a direct read. - words[2] = 0x7E02_02C1; // v_mov_b32 v1, -1 - let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { - Ok(()) => None, - Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), - Err(error) => panic!("{error}"), - }; - let direct = [&words[..2], &words[9..]].concat(); - assert_eq!(refusal(&words), refusal(&direct)); - } - - #[test] - fn a_missing_value_on_a_path_no_lane_takes_is_dead() { - let refusal = |code: &[u32]| match lowers(code, 1 << 7) { - Ok(()) => None, - Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), - Err(error) => panic!("{error}"), - }; - // The timestamp stays in s6 only where s0 == 0, and those lanes - // overwrite it before the second join: it never reaches the read. - let mut joins = [ - 0xF490_0180, - 0, // s_memtime s[6:7] - 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) - 0xBF85_0001, // s_cbranch_scc1: s0 == 0 keeps the timestamp - 0xBE86_0380, // s_mov_b32 s6, 0 - 0xBF84_0001, // s_cbranch_scc0: s0 != 0 keeps that 0 - 0xBE86_0381, // s_mov_b32 s6, 1 - 0xBF07_8006, // s_cmp_lg_u32 s6, 0 - 0xBF85_0001, - 0xBE83_0380, - S_ENDPGM, - ]; - assert_eq!(refusal(&joins), None); - // Tested on the other side, the timestamp reaches the read. - joins[5] = 0xBF85_0001; // s_cbranch_scc1 - assert!(refusal(&joins).is_some()); - // The same through a VGPR whose old value a guarded write keeps - // (lanes outside it get 0 for a value with no DXIL form, as for any - // such write): keeping does not make the join live. - let kept = [ - 0xF490_0180, - 0, // s_memtime s[6:7] - 0x7E02_0206, // v_mov_b32 v1, s6 - 0xBF06_8000, // s_cmp_eq_u32 s0, 0 - 0xBF85_0001, // s_cbranch_scc1: s0 == 0 keeps the timestamp - 0x7E02_0280, // v_mov_b32 v1, 0 - 0xBF84_0004, // s_cbranch_scc0: s0 != 0 keeps that 0 - 0x7DA4_0080, // v_cmpx_eq_u32 exec, 0, v0 - 0x7E02_0282, // v_mov_b32 v1, 2 (the other lanes keep v1) - 0xBEFE_03C1, // s_mov_b32 exec_lo, -1 - 0x7E02_0283, // v_mov_b32 v1, 3 - 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 - 0xBF87_0001, // s_cbranch_vccnz - 0xBE83_0380, - S_ENDPGM, - ]; - assert_eq!(refusal(&kept), None); - } - - #[test] - fn buffer_formats_by_number() { - // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, - // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT. - assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm))); - assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm))); - assert_eq!( - buffer_format(50), - Some((&[10, 10, 10, 2][..], Numeric::Unorm)) - ); - assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float))); - assert_eq!( - buffer_format(77), - Some((&[32, 32, 32, 32][..], Numeric::Float)) - ); - // Invalid, past the table. - assert_eq!(buffer_format(0), None); - assert_eq!(buffer_format(78), None); - } - - #[test] - fn packed_buffer_formats_by_number() { - // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43, - // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT - // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first. - assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm))); - assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float))); - assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm))); - assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float))); - assert_eq!( - buffer_format(44), - Some((&[2, 10, 10, 10][..], Numeric::Unorm)) - ); - assert_eq!( - buffer_format(45), - Some((&[2, 10, 10, 10][..], Numeric::Snorm)) - ); - assert_eq!( - buffer_format(46), - Some((&[2, 10, 10, 10][..], Numeric::Uscaled)) - ); - assert_eq!( - buffer_format(47), - Some((&[2, 10, 10, 10][..], Numeric::Sscaled)) - ); - assert_eq!( - buffer_format(48), - Some((&[2, 10, 10, 10][..], Numeric::Uint)) - ); - assert_eq!( - buffer_format(49), - Some((&[2, 10, 10, 10][..], Numeric::Sint)) - ); - } - - /// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as - /// `legacyF16ToF32` widens it. - fn half(h: u32) -> f32 { - let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023); - let v = match e { - 0 => m as f32 * 2f32.powi(-24), - 31 if m == 0 => f32::INFINITY, - 31 => f32::NAN, - _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25), - }; - if s == 1 { -v } else { v } - } - - #[test] - fn small_floats_widen_as_halves() { - // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a - // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec. - let f11 = |x: u32| half(x << half_shift(11)); - let f10 = |x: u32| half(x << half_shift(10)); - assert_eq!(f11(0), 0.0); - assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal - assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal - assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal - assert_eq!(f11(0x3C0), 1.0); - assert_eq!(f11(0x3E0), 1.5); - assert_eq!(f11(0x7BF), 65024.0); // largest - assert_eq!(f11(0x7C0), f32::INFINITY); - assert!(f11(0x7C1).is_nan()); - assert_eq!(f10(0x001), 2f32.powi(-19)); - assert_eq!(f10(0x020), 2f32.powi(-14)); - assert_eq!(f10(0x1E0), 1.0); - assert_eq!(f10(0x3DF), 64512.0); - assert_eq!(f10(0x3E0), f32::INFINITY); - assert!(f10(0x3FF).is_nan()); - // A 16-bit float is a half already, sign included. - assert_eq!(half(0xBC00 << half_shift(16)), -1.0); - } - - #[test] - fn packed_halves_fill_parameters_first_fit() { - // 16-bit rows as a title's signature has them: row 0 holds two - // elements (x y and z w), row 3 is 32-bit, row 4 has one channel at w. - let el = |row: u32, col: u8, cols: u8, half: bool| super::SigElement { - name: "TEXCOORD".into(), - index: row, - kind: 0, - comp: 9, - interp: 0, - row: Some(row), - col, - cols, - usage: 0, - half, - }; - let sig = [ - el(0, 0, 2, true), - el(0, 2, 2, true), - el(1, 0, 4, true), - el(2, 0, 3, true), - el(3, 0, 4, false), - el(4, 0, 3, true), - el(4, 3, 1, true), - el(5, 0, 3, true), - ]; - // Each half as row and channel ("-": padding or past the end). - let param = |a| { - (0..8) - .map(|h| match packed_half(&sig, a, h) { - Some((r, c)) => format!("{r}{}", ["x", "y", "z", "w"][usize::from(c)]), - None => "-".into(), - }) - .collect::>() - .join(" ") - }; - // By first channel, then row: row 0's x y, all of row 1, then (last, - // as it starts at z) row 0's z w. - assert_eq!(param(0), "0x 0y 1x 1y 1z 1w 0z 0w"); - // Three channels take two dwords; row 4's w fills the first - // parameter with room, after row 5. - assert_eq!(param(2), "2x 2y 2z - 4x 4y 4z -"); - assert_eq!(param(5), "5x 5y 5z - 4w - - -"); - // No parameter starts in rows 1, 3 or 4. - for a in [1, 3, 4] { - assert_eq!(param(a), "- - - - - - - -"); - } - } - #[test] - fn permlane16_lowers() { - let words = [ - // v_permlanex16_b32 v2, v0, s0, s1 (VOP3 opcode 0x378) - 0xD778_0002, - (1 << 18) | 0x100, - S_ENDPGM, - ]; - lowers(&words, 0).expect("v_permlanex16_b32 should lower"); - } -} +#[path = "lower_tests.rs"] +mod tests; diff --git a/crates/viport-shader/src/emit/lower_tests.rs b/crates/viport-shader/src/emit/lower_tests.rs new file mode 100644 index 0000000..2b8ed59 --- /dev/null +++ b/crates/viport-shader/src/emit/lower_tests.rs @@ -0,0 +1,1181 @@ +use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower, packed_half}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{io, ir, resource, structure}; + +const S_ENDPGM: u32 = 0xBF81_0000; + +/// Whether a synthetic compute program translates with these input registers. +fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { + lowered(words, rsrc2).map(|_| ()) +} + +/// [`lowers`], keeping the lowered program so its DXIL can be inspected. +fn lowered(words: &[u32], rsrc2: u32) -> Result { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, false, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) +} + +/// Lowers a compute program with the root parameters `layout` (in user +/// SGPRs from s0 on) and the used resources `used`. +fn lower_with( + words: &[u32], + layout: Vec, + used: Vec, +) -> Result { + lower_wave(words, layout, used, false) +} + +/// [`lower_with`] in wave64 if `wave64`. +fn lower_wave( + words: &[u32], + layout: Vec, + used: Vec, + wave64: bool, +) -> Result { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64, + vgprs: 256, + layout, + used, + io: StageIo::Cs(ComputeIo { + // The layout's user SGPRs (at least two), 512 bytes of LDS. + rsrc2: 1 << 15 | sgprs.max(2) << 1, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, wave64, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) +} + +/// Root parameter `slot` in user SGPRs from `user_data` on. +fn root(root: RootType, user_data: u8, slot: u8) -> RootParam { + RootParam { + root, + table_offset_dwords: 0, + sgprs: if root == RootType::Descriptor { 2 } else { 1 }, + base_register: 0, + user_data, + slot, + } +} + +/// Lowers a pixel program with one float `SV_Target0`: whether it +/// translates. +fn lowers_ps(words: &[u32]) -> Result<(), crate::ShaderError> { + let target = crate::emit::container::SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0, + half: false, + }; + lowers_ps_with(words, vec![target]) +} + +/// [`lowers_ps`] with the output elements `outputs`. +fn lowers_ps_with( + words: &[u32], + outputs: Vec, +) -> Result<(), crate::ShaderError> { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 4, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code, + }; + let p = ir::build(&native.code, false, 4).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs, + prims: vec![], + mesh_stride: 0, + }) + .map(|_| ()) +} + +#[test] +fn a_compressed_export_unpacks_two_f16_channels_per_dword() { + // A compr export: each source dword packs two f16 channels, the + // low half first, so four channels come from two VGPRs. + let words = [ + 0x7E00_0282, // v_mov_b32 v0, 2 + 0x7E02_0282, // v_mov_b32 v1, 2 + 0xF800_0C0F, + 0x0000_0100, // exp mrt0, v0, v0, v1, v1 done compr + S_ENDPGM, + ]; + lowers_ps(&words).unwrap(); +} + +#[test] +fn a_compressed_export_to_a_uint_target_stays_refused() { + // The halves of a compr dword are f16 values: a uint target would + // store their f32 bits as integers, so the export stays refused. + let words = [ + 0x7E00_0282, // v_mov_b32 v0, 2 + 0x7E02_0282, // v_mov_b32 v1, 2 + 0xF800_0C0F, + 0x0000_0100, // exp mrt0, v0, v0, v1, v1 done compr + S_ENDPGM, + ]; + let target = crate::emit::container::SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 5, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0, + half: false, + }; + assert!(matches!( + lowers_ps_with(&words, vec![target]), + Err(crate::ShaderError::Unsupported { + what: "a compressed export", + .. + }) + )); +} + +#[test] +fn a_compressed_depth_export_with_stencil_stays_refused() { + // `exp mrtz` compr packs the depth and the stencil into one dword. + // The stencil half is an integer, so the export stays refused. + let words = [ + 0x7E00_0282, // v_mov_b32 v0, 2 + 0xF800_0C8F, + 0x0000_0000, // exp mrtz, v0, v0 done compr + S_ENDPGM, + ]; + let element = |name: &str, kind: u8, comp: u8| crate::emit::container::SigElement { + name: name.into(), + index: 0, + kind, + comp, + interp: 0, + row: None, + col: 0, + cols: 1, + usage: 0, + half: false, + }; + let outputs = vec![element("SV_Depth", 17, 9), element("SV_StencilRef", 20, 5)]; + assert!(matches!( + lowers_ps_with(&words, outputs), + Err(crate::ShaderError::Unsupported { + what: "a compressed export", + .. + }) + )); +} + +#[test] +fn a_scalar_carry_chain_reaches_the_select() { + // The high dword of a 64-bit add or subtract, then a select on the + // carry (borrow) the high half leaves in SCC, and a branch on it + // (only code with an effect needs its operands). + let add = [ + 0xBE80_03C1, // s_mov_b32 s0, -1 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0x8000_8100, // s_add_u32 s0, s0, 1 + 0x8201_8001, // s_addc_u32 s1, s1, 0 + 0x8502_0001, // s_cselect_b32 s2, s1, s0 + 0xBF07_8002, // s_cmp_lg_u32 s2, 0 + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE83_0380, // s_mov_b32 s3, 0 + S_ENDPGM, + ]; + let sub = [ + 0xBE80_0380, // s_mov_b32 s0, 0 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0x8080_8100, // s_sub_u32 s0, s0, 1 + 0x8281_8001, // s_subb_u32 s1, s1, 0 + 0x8502_0001, // s_cselect_b32 s2, s1, s0 + 0xBF07_8002, // s_cmp_lg_u32 s2, 0 + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE83_0380, // s_mov_b32 s3, 0 + S_ENDPGM, + ]; + + for words in [add, sub] { + lowers(&words, 0).unwrap(); + } +} + +#[test] +fn v_cndmask_accepts_uniform_and_constant_masks() { + // Uniform select (`s_cselect_b32`) and inline constant masks in `v_cndmask_b32` + // (resolved in `Structured::other` or directly as constants). + let words = [ + 0xBF06_8000u32, // s_cmp_eq_u32 s0, 0 + 0x8500_80C1, // s_cselect_b32 s0, -1, 0 + 0xD501_0001, + 0x0001_0080, // v_cndmask_b32 v1, 0, 1, s0 + 0xD501_0002, + 0x0201_02C1, // v_cndmask_b32 v2, 1, v1, -1 + 0xD834_0000, + 0x0000_0200, // ds_write_b32 v0, v2 + S_ENDPGM, + ]; + lowers(&words, 0x8001).unwrap(); +} + +fn perm_features(selector: u32) -> u64 { + // Synthetic compute shader: + // v0 is the thread ID and can supply a dynamic selector. + // Store the result in LDS to keep the permutation live. + let words = [ + 0x7E02_02FFu32, + 0x817F_34AB, + 0x7E04_02FF, + 0xFE01_56CD, + 0xD744_0003, + 257 | (258 << 9) | (selector << 18), + 0x3408_0082, + 0xD834_0000, + 0x0000_0304, + S_ENDPGM, + ]; + + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 1 << 15, + threads: [64, 1, 1], + }), + code, + }; + + let p = ir::build(&native.code, false, 256).unwrap(); + + assert!( + p.blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.name() == "v_perm_b32") + ); + + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + + let io = io::raise(&p, &native).unwrap(); + + let emitted = lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + .unwrap(); + + let container = crate::Container::parse(&emitted.dxil).unwrap(); + + let features = container.part(crate::FourCC::SFI0).unwrap(); + + u64::from_le_bytes(features.data.try_into().unwrap()) +} + +/// Lowers `alu` on the thread id v0 into v3, kept by an LDS store. +fn refactoring(alu: &[u32]) -> (bool, Vec) { + let mut words = alu.to_vec(); + words.extend([ + 0x7E08_0280, // v_mov_b32 v4, 0 + 0xD834_0000, // ds_write_b32 v4, v3 + 0x0000_0304, + S_ENDPGM, + ]); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let names = ir::build(&code, false, 256).unwrap().blocks[0] + .insts + .iter() + .map(|i| i.name().to_string()) + .collect(); + let lowered = lower_with(&words, vec![], vec![]).unwrap(); + (lowered.refactoring, names) +} + +#[test] +fn only_programs_with_fmad_let_the_host_refactor() { + let (fused, names) = refactoring(&[ + 0xD54B_0003, // v_fma_f32 v3, v0, v0, v0 + 0x0402_0100, + ]); + assert_eq!(names[0], "v_fma_f32"); + assert!(fused, "FMad needs refactoring to fuse"); + let (apart, names) = refactoring(&[ + 0x1006_0100, // v_mul_f32 v3, v0, v0 + 0x0606_0103, // v_add_f32 v3, v3, v0 + ]); + assert_eq!(names[..2], ["v_mul_f32", "v_add_f32"]); + assert!(!apart, "a multiply and an add stay apart"); +} + +#[test] +fn perm_constant_selector_needs_no_int64() { + assert_eq!(perm_features(128) & 0x8000, 0); +} + +#[test] +fn perm_dynamic_selector_needs_no_int64() { + assert_eq!( + perm_features(256) & 0x8000, + 0, + "dynamic v_perm_b32 must not require INT64" + ); +} + +#[test] +fn a_descriptor_selected_by_scc_picks_its_heap_index() { + // Two buffer descriptors loaded from the table at s0, one picked by + // a root constant (s1) with s_cselect_b64 per half, and loaded + // through by index and stored to LDS so the load is needed. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0xF408_0302, + 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13] + 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15] + 0xE030_2000, + 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + // Both are structured buffers of dwords in the table's range. + let used = || { + vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 0, + slot: 0, + }] + }; + lower_with(&words, layout(), used()).unwrap(); +} + +/// `v_mov_b32 vdst, src0` (`src0`: 128 is the inline zero). +fn v_mov(vdst: u8, src0: u16) -> u32 { + 0x7E00_0000 | (vdst as u32) << 17 | 0x01 << 9 | (src0 as u32 & 0x1FF) +} + +/// `ds_write_b32 v[addr], v[data]`. +fn ds_write_b32(addr: u8, data: u8) -> [u32; 2] { + [0xD834_0000, u32::from(addr) | u32::from(data) << 8] +} + +/// A buffer access: MUBUF (`mtbuf` false, opcode in bits 18-25, a +/// resource and optional `idxen`/`offen`) or MTBUF (`mtbuf` true, opcode +/// in bits 15-18, the format in bits 19-25), `srsrc` the first of four +/// resource SGPRs, `vdata`/`vaddr` VGPRs and `offset` a byte offset. +#[allow(clippy::too_many_arguments)] +fn buffer( + opcode: u16, + mtbuf: bool, + format: u8, + offset: u16, + offen: bool, + idxen: bool, + vdata: u8, + vaddr: u8, + srsrc: u8, +) -> [u32; 2] { + let class = if mtbuf { 0x3A } else { 0x38 }; + let op_shift = if mtbuf { 16 } else { 18 }; + [ + class << 26 + | u32::from(opcode & if mtbuf { 0x7 } else { 0x7F }) << op_shift + | u32::from(format) << 19 + | u32::from(offen) << 12 + | u32::from(idxen) << 13 + | u32::from(offset), + // soffset is the inline zero, TFE and GLC clear; MTBUF keeps + // the top bit of its opcode here. + 0x80 << 24 + | u32::from(if mtbuf { opcode >> 3 } else { 0 }) << 21 + | u32::from(srsrc >> 2) << 16 + | u32::from(vdata) << 8 + | u32::from(vaddr), + ] +} + +/// A program that reads the descriptor at table entry 0 into `s[8:11]`, +/// runs `fetch` (VGPRs from 0, its address in v3) and writes its VGPRs +/// to LDS: the three positions of a vertex fetch, or four channels. +fn fetch_program(fetch: [u32; 2], channels: u8) -> Vec { + let mut words = vec![ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + v_mov(3, 128), // v_mov_b32 v3, 0 (the fetch's address) + v_mov(channels + 1, 128), // v_mov_b32 v5, 0 (the LDS address) + ]; + words.extend_from_slice(&fetch); + for k in 0..channels { + words.extend_from_slice(&ds_write_b32(channels + 1, k)); + } + words.push(S_ENDPGM); + words +} + +/// The descriptor at table entry 0: a typed or raw SRV of `stride` (0: +/// none), read as `dwords` dwords. +fn fetch_tables(stride: u32, dwords: u8) -> (Vec, Vec) { + let layout = vec![root(RootType::Table, 0, 0)]; + let used = vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride, + dwords, + user_data: 0, + slot: 0, + }]; + (layout, used) +} + +#[test] +fn every_buffer_format_names_its_bits_and_numbers() { + // Every number names a format, 1 to 77, and no number past that + // does: the element sizes the typed fetches read follow from these. + for format in 1..=77u8 { + let (bits, _) = buffer_format(format).unwrap_or_else(|| panic!("format {format}")); + let total: u32 = bits.iter().sum(); + assert_eq!(total % 8, 0, "format {format}: {bits:?} is whole bytes"); + assert!( + total == 8 || total == 16 || total >= 32, + "format {format}: {bits:?} is a dword or a byte/half inside one" + ); + } + assert_eq!(buffer_format(78), None); + // The vertex fetch shapes: float3 is 12 bytes (16_16_16_16 comes + // first, at 65), half2 and unorm8x4 are 4. + let bytes = |f| -> u32 { buffer_format(f).unwrap().0.iter().sum::() / 8 }; + assert_eq!(bytes(74), 12, "32_32_32_FLOAT"); + assert_eq!(bytes(24), 4, "16_16_SNORM"); + assert_eq!(bytes(56), 4, "8_8_8_8_UNORM"); +} + +#[test] +fn a_typed_fetch_inside_a_dword_reads_the_pair_around_it() { + // `tbuffer_load_format_xyz` at byte offset 33: the console reads + // the bytes at 33, so the host reads the dword-aligned pair and + // shifts (a dword read promised at 33 can return zeros). + let odd = buffer(0x002, true, 74, 33, false, false, 0, 3, 8); + let (layout, used) = fetch_tables(0, 4); + let l = lower_with(&fetch_program(odd, 3), layout, used).unwrap(); + assert_eq!(l.unaligned_typed_loads, 1); + // The same fetch on a dword boundary is one plain read. + let even = buffer(0x002, true, 74, 32, false, false, 0, 3, 8); + let (layout, used) = fetch_tables(0, 4); + let l = lower_with(&fetch_program(even, 3), layout, used).unwrap(); + assert_eq!(l.unaligned_typed_loads, 0); +} + +#[test] +fn a_four_dword_typed_fetch_inside_a_dword_loads_at_most_four_words_at_a_time() { + // `tbuffer_load_format_xyzw` of format 77 at byte offset 33 needs + // five aligned words; one raw load returns four and then the + // status, so the fifth is read by a second load (the load closure + // asserts no load asks for more than four). + let odd = buffer(0x003, true, 77, 33, false, false, 0, 3, 8); + let (layout, used) = fetch_tables(0, 4); + let l = lower_with(&fetch_program(odd, 4), layout, used).unwrap(); + assert_eq!(l.unaligned_typed_loads, 1); +} + +#[test] +fn a_typed_fetch_of_no_format_is_refused() { + // Format 0 is not a format: the fetch must stop rather than read + // whatever the descriptor holds. + let fetch = buffer(0x002, true, 0, 0, true, false, 0, 3, 8); + let (layout, used) = fetch_tables(0, 4); + let err = match lower_with(&fetch_program(fetch, 3), layout, used) { + Err(e) => e, + Ok(_) => panic!("a fetch of format 0 lowered"), + }; + assert!( + matches!( + err, + crate::ShaderError::Unsupported { + what: "a buffer format", + .. + } + ), + "{err:?}" + ); +} + +/// Tables of 2D textures at s0 and samplers at s1. +fn texture_tables() -> (Vec, Vec) { + let range = |kind, user_data, slot| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: if kind == ResourceType::Sampler { 4 } else { 8 }, + user_data, + slot, + }; + ( + vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)], + vec![ + range(ResourceType::Srv, 0, 0), + range(ResourceType::Sampler, 1, 1), + ], + ) +} + +#[test] +fn a_descriptor_loaded_only_for_its_size_takes_the_kind_of_its_reload() { + // The record count of the buffer at s0 (count - 1 as an index), then + // the same descriptor loaded again for the indexed read. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0x810C_C10A, // s_add_i32 s12, s10, -1 + 0xF408_0402, + 0xFA00_0000, // s_load_dwordx4 s[16:19], s[4:5], null + 0x7E04_020C, // v_mov_b32 v2, s12 + 0xE030_2000, + 0x8004_0102, // buffer_load_dword v1, v2, s[16:19], 0 idxen + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + let used = vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 0, + slot: 0, + }]; + lower_with(&words, layout, used).unwrap(); +} + +#[test] +fn a_waterfall_loop_that_only_sizes_takes_the_kind_of_the_sampled_one() { + // Each lane names table entry (lane & 1) by its byte offset in v7. + // A first waterfall loop only reads the width bits of the entry + // (`v_alignbit_b32`), a second one samples it; the width goes to the + // buffer at dword 16 of the table. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x360E_0081, // v_and_b32 v7, 1, v0 + 0x340E_0E85, // v_lshlrev_b32 v7, 5, v7 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0xBE95_037E, // s_mov_b32 s21, exec_lo + 0x7E28_0507, // L1: v_readfirstlane_b32 s20, v7 + 0x7DA4_0E14, // v_cmpx_eq_u32 exec_lo, s20, v7 + 0xF40C_0302, + 0x2800_0000, // s_load_dwordx8 s[12:19], s[4:5], s20 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xD54E_0008, + 0x0278_1A0E, // v_alignbit_b32 v8, s14, s13, 30 + 0xBE95_4715, // s_andn2_wrexec_b32 s21, s21 + 0xBF89_FFF7, // s_cbranch_execnz L1 + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xBE95_037E, // s_mov_b32 s21, exec_lo + 0x7E28_0507, // L2: v_readfirstlane_b32 s20, v7 + 0x7DA4_0E14, // v_cmpx_eq_u32 exec_lo, s20, v7 + 0xF40C_0302, + 0x2800_0000, // s_load_dwordx8 s[12:19], s[4:5], s20 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xBE95_4715, // s_andn2_wrexec_b32 s21, s21 + 0xBF89_FFF6, // s_cbranch_execnz L2 + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xE070_1000, + 0x800A_0810, // buffer_store_dword v8, v16, s[40:43], 0 offen + S_ENDPGM, + ]; + let (layout, used) = texture_and_uav_tables(); + lower_wave(&words, layout, used, false).unwrap(); +} + +#[test] +fn compute_spills_beside_a_descriptor_word_read_back() { + // Dword 0 of a buffer descriptor (no host value) and a root constant + // spilled to lanes 0 and 1 of v5 in a compute program; reading lane + // 1 back is the constant (the descriptor's lane is never read). + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0xD761_0005, + 0x0001_0008, // v_writelane_b32 v5, s8, 0 + 0xD761_0005, + 0x0001_0201, // v_writelane_b32 v5, s1, 1 + 0xD760_000C, + 0x0001_0305, // v_readlane_b32 s12, v5, 1 + 0xE030_2000, + 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen + 0x7E06_020C, // v_mov_b32 v3, s12 + 0xD834_0000, + 0x0000_0300, // ds_write_b32 v0, v3 + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + let used = vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 0, + slot: 0, + }]; + lower_with(&words, layout, used).unwrap(); +} + +#[test] +fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() { + use crate::resource::tests::{ + WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32, + }; + for (words, wave64) in [ + (WATERFALL_FETCHED_WAVE32, false), + (WATERFALL_FETCHED_WAVE64, true), + (WATERFALL_PICKED_WAVE32, false), + ] { + let (layout, used) = texture_tables(); + let l = lower_wave(words, layout, used, wave64).unwrap(); + // The loop's reads of the first lane became each lane's own + // dwords: no wave operation is left. + assert_eq!(l.nonuniform_handles, 1); + assert!(!l.wave_ops); + } +} + +/// [`texture_tables`] with a raw buffer UAV at dword 16 of the first. +pub(crate) fn texture_and_uav_tables() -> (Vec, Vec) { + let (layout, mut used) = texture_tables(); + used.push(UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 16, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }); + (layout, used) +} + +#[test] +fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() { + use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32}; + for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] { + let (layout, used) = texture_and_uav_tables(); + let l = lower_wave(words, layout, used, false).unwrap(); + // One image handle, from the join's per-lane heap index. + assert_eq!(l.nonuniform_handles, 1); + assert!(!l.wave_ops); + } +} + +#[test] +fn scalar_bit_tests_lower() { + // Each tests one bit of a constant into SCC and branches on it (only + // code with an effect needs its operands). + let tail = [ + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE84_0380, // s_mov_b32 s4, 0 + S_ENDPGM, + ]; + let bit_tests: [&[u32]; 4] = [ + &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3 + &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3 + &[ + 0xBE80_0387, // s_mov_b32 s0, 7 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3 + ], + &[ + 0xBE80_0387, // s_mov_b32 s0, 7 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3 + ], + ]; + for head in bit_tests { + let words: Vec = head.iter().chain(&tail).copied().collect(); + lowers(&words, 0).unwrap(); + } +} + +#[test] +fn scalar_64_bit_field_ops_lower() { + // Each makes a 64-bit field from constants and branches on SCC (only + // code with an effect needs its operands). + let tail = [ + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE87_0380, // s_mov_b32 s7, 0 + S_ENDPGM, + ]; + let consts = [ + 0xBE80_0387, // s_mov_b32 s0, 7 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xBE82_0388, // s_mov_b32 s2, 8 + ]; + let field_tests: [&[u32]; 3] = [ + &[0x9484_0200], // s_bfe_u64 s[4:5], s[0:1], s2 + &[0x9504_0200], // s_bfe_i64 s[4:5], s[0:1], s2 + // s_bfm_b64 s[4:5], s0, s1; its result is read by s_or_b32, + // which sets the SCC the branch uses. + &[0x9284_0100, 0x8806_0504], + ]; + for body in field_tests { + let words: Vec = consts.iter().chain(body).chain(&tail).copied().collect(); + lowers(&words, 0).unwrap(); + } +} + +#[test] +fn a_missing_value_stays_missing_through_two_live_joins() { + let mut words = [ + 0xF490_0180, + 0, // s_memtime s[6:7] + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) + 0xBF85_0001, // skip the first overwrite + 0xBE86_0380, // s_mov_b32 s6, 0 + 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y) + 0xBF85_0001, // skip the second overwrite + 0xBE86_0381, // s_mov_b32 s6, 1 + 0xBF07_8006, // s_cmp_lg_u32 s6, 0 + 0xBF85_0001, // use the result to branch + 0xBE83_0380, + S_ENDPGM, + ]; + let group_ids_xy = 3 << 7; + // Compare to a direct read so future timestamp support works in both cases. + let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { + Ok(()) => None, + Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), + Err(error) => panic!("{error}"), + }; + let direct = [&words[..2], &words[8..]].concat(); + assert_eq!(refusal(&words), refusal(&direct)); + words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead + lowers(&words, group_ids_xy).expect("dead timestamp"); +} + +#[test] +fn a_wave_prefix_of_min_lowers() { + // A whole-wave section that leaves the inclusive prefix of a min: + // each lane the minimum of the lanes up to and including it. The + // scan runs with `row_shr` steps inside each row, and the first + // row's prefix is read out and folded under the second. The store + // after the section reads the prefix, so the value cannot be left + // missing: a wave prefix of a min has to lower. + let words = [ + 0x7E00_0280, // v_mov_b32 v0, 0 + // 32-bit scalar forms: the wave32 pass follows their masks. + 0xBE84_3DC1, // s_or_saveexec_b32 s4, -1 + 0x876A_C104, // s_and_b32 s106, s4, -1 + 0x0202_00C1, // v_cndmask_b32 v1, -1, v0, vcc + 0x2602_02FA, // v_min_u32 v1, v1 row_shr:1, v1 + 0xFF01_1101, + 0x2602_02FA, // v_min_u32 v1, v1 row_shr:2, v1 + 0xFF01_1201, + 0x2602_02FA, // v_min_u32 v1, v1 row_shr:3, v1 + 0xFF01_1301, + 0x2602_02FA, // v_min_u32 v1, v1 row_shr:4, v1 + 0xFF01_1401, + 0x2602_02FA, // v_min_u32 v1, v1 row_shr:5, v1 + 0xFF01_1501, + 0x2602_02FA, // v_min_u32 v1, v1 row_shr:6, v1 + 0xFF01_1601, + 0x2602_02FA, // v_min_u32 v1, v1 row_shr:7, v1 + 0xFF01_1701, + 0x2602_02FA, // v_min_u32 v1, v1 row_shr:8, v1 + 0xFF01_1801, + 0x2602_02FA, // v_min_u32 v1, v1 row_shr:9, v1 + 0xFF01_1901, + 0x2602_02FA, // v_min_u32 v1, v1 row_shr:10, v1 + 0xFF01_1A01, + 0x2602_02FA, // v_min_u32 v1, v1 row_shr:11, v1 + 0xFF01_1B01, + 0x2602_02FA, // v_min_u32 v1, v1 row_shr:12, v1 + 0xFF01_1C01, + 0x2602_02FA, // v_min_u32 v1, v1 row_shr:13, v1 + 0xFF01_1D01, + 0x2602_02FA, // v_min_u32 v1, v1 row_shr:14, v1 + 0xFF01_1E01, + 0x2602_02FA, // v_min_u32 v1, v1 row_shr:15, v1 + 0xFF01_1F01, + 0xD760_0006, // v_readlane_b32 s6, v1, 15 + 0x0001_1F01, + 0x7E04_0206, // v_mov_b32 v2, s6 + 0x2602_02FA, // v_min_u32 v1, v2 quad_perm:[0,1,2,3] row_mask:0x2, v1 + 0x2F00_E402, + 0xBEFE_0304, // s_mov_b32 exec_lo, s4 + 0xD834_0000, // ds_write_b32 v0, v1 + 0x0000_0100, + S_ENDPGM, + ]; + let out = lowered(&words, 1 << 15).unwrap(); + // Drivers do not implement `wavePrefixOp` kinds 2 and 3 (hardware + // readback on PR #470), so the min prefix must lower to a + // `WaveReadLaneAt` scan instead. + assert_eq!(out.prefix_scans, 1, "a min prefix must scan, not prefix-op"); + // dxil.dll, where there is one, checks the scan's module too. + #[cfg(windows)] + { + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut out.dxil.clone()).unwrap(); + } + } +} + +#[test] +fn a_value_no_lane_from_its_edge_reads_needs_no_form() { + // s6 is a timestamp (no DXIL form) where the load is skipped and 5 + // where it runs; a flag in v1, set only with the load, guards the + // read after the join (the console compiler's form, where the + // skipped path leaves a stale lane mask in the register). + let mut words = [ + 0xF490_0180, + 0, // s_memtime s[6:7] + 0x7E02_0280, // v_mov_b32 v1, 0 + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) + 0xBF85_0002, // s_cbranch_scc1 -> join + 0xBE86_0385, // s_mov_b32 s6, 5 + 0x7E02_02C1, // v_mov_b32 v1, -1 + 0x7D84_02C1, // join: v_cmp_eq_u32 vcc_lo, -1, v1 + 0xBF86_0003, // s_cbranch_vccz -> end + 0xBF07_8006, // s_cmp_lg_u32 s6, 0 + 0xBF85_0001, // s_cbranch_scc1 -> end + 0xBE84_0380, // s_mov_b32 s4, 0 + S_ENDPGM, + ]; + let group_ids_xy = 3 << 7; + lowers(&words, group_ids_xy).expect("the timestamp is never read"); + // With the flag set on both paths the timestamp is read: as refused + // (or accepted) as a direct read. + words[2] = 0x7E02_02C1; // v_mov_b32 v1, -1 + let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { + Ok(()) => None, + Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), + Err(error) => panic!("{error}"), + }; + let direct = [&words[..2], &words[9..]].concat(); + assert_eq!(refusal(&words), refusal(&direct)); +} + +#[test] +fn a_missing_value_on_a_path_no_lane_takes_is_dead() { + let refusal = |code: &[u32]| match lowers(code, 1 << 7) { + Ok(()) => None, + Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), + Err(error) => panic!("{error}"), + }; + // The timestamp stays in s6 only where s0 == 0, and those lanes + // overwrite it before the second join: it never reaches the read. + let mut joins = [ + 0xF490_0180, + 0, // s_memtime s[6:7] + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) + 0xBF85_0001, // s_cbranch_scc1: s0 == 0 keeps the timestamp + 0xBE86_0380, // s_mov_b32 s6, 0 + 0xBF84_0001, // s_cbranch_scc0: s0 != 0 keeps that 0 + 0xBE86_0381, // s_mov_b32 s6, 1 + 0xBF07_8006, // s_cmp_lg_u32 s6, 0 + 0xBF85_0001, + 0xBE83_0380, + S_ENDPGM, + ]; + assert_eq!(refusal(&joins), None); + // Tested on the other side, the timestamp reaches the read. + joins[5] = 0xBF85_0001; // s_cbranch_scc1 + assert!(refusal(&joins).is_some()); + // The same through a VGPR whose old value a guarded write keeps + // (lanes outside it get 0 for a value with no DXIL form, as for any + // such write): keeping does not make the join live. + let kept = [ + 0xF490_0180, + 0, // s_memtime s[6:7] + 0x7E02_0206, // v_mov_b32 v1, s6 + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 + 0xBF85_0001, // s_cbranch_scc1: s0 == 0 keeps the timestamp + 0x7E02_0280, // v_mov_b32 v1, 0 + 0xBF84_0004, // s_cbranch_scc0: s0 != 0 keeps that 0 + 0x7DA4_0080, // v_cmpx_eq_u32 exec, 0, v0 + 0x7E02_0282, // v_mov_b32 v1, 2 (the other lanes keep v1) + 0xBEFE_03C1, // s_mov_b32 exec_lo, -1 + 0x7E02_0283, // v_mov_b32 v1, 3 + 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 + 0xBF87_0001, // s_cbranch_vccnz + 0xBE83_0380, + S_ENDPGM, + ]; + assert_eq!(refusal(&kept), None); +} + +#[test] +fn buffer_formats_by_number() { + // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, + // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT. + assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm))); + assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm))); + assert_eq!( + buffer_format(50), + Some((&[10, 10, 10, 2][..], Numeric::Unorm)) + ); + assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float))); + assert_eq!( + buffer_format(77), + Some((&[32, 32, 32, 32][..], Numeric::Float)) + ); + // Invalid, past the table. + assert_eq!(buffer_format(0), None); + assert_eq!(buffer_format(78), None); +} + +#[test] +fn packed_buffer_formats_by_number() { + // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43, + // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT + // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first. + assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm))); + assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float))); + assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm))); + assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float))); + assert_eq!( + buffer_format(44), + Some((&[2, 10, 10, 10][..], Numeric::Unorm)) + ); + assert_eq!( + buffer_format(45), + Some((&[2, 10, 10, 10][..], Numeric::Snorm)) + ); + assert_eq!( + buffer_format(46), + Some((&[2, 10, 10, 10][..], Numeric::Uscaled)) + ); + assert_eq!( + buffer_format(47), + Some((&[2, 10, 10, 10][..], Numeric::Sscaled)) + ); + assert_eq!( + buffer_format(48), + Some((&[2, 10, 10, 10][..], Numeric::Uint)) + ); + assert_eq!( + buffer_format(49), + Some((&[2, 10, 10, 10][..], Numeric::Sint)) + ); +} + +/// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as +/// `legacyF16ToF32` widens it. +fn half(h: u32) -> f32 { + let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023); + let v = match e { + 0 => m as f32 * 2f32.powi(-24), + 31 if m == 0 => f32::INFINITY, + 31 => f32::NAN, + _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25), + }; + if s == 1 { -v } else { v } +} + +#[test] +fn small_floats_widen_as_halves() { + // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a + // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec. + let f11 = |x: u32| half(x << half_shift(11)); + let f10 = |x: u32| half(x << half_shift(10)); + assert_eq!(f11(0), 0.0); + assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal + assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal + assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal + assert_eq!(f11(0x3C0), 1.0); + assert_eq!(f11(0x3E0), 1.5); + assert_eq!(f11(0x7BF), 65024.0); // largest + assert_eq!(f11(0x7C0), f32::INFINITY); + assert!(f11(0x7C1).is_nan()); + assert_eq!(f10(0x001), 2f32.powi(-19)); + assert_eq!(f10(0x020), 2f32.powi(-14)); + assert_eq!(f10(0x1E0), 1.0); + assert_eq!(f10(0x3DF), 64512.0); + assert_eq!(f10(0x3E0), f32::INFINITY); + assert!(f10(0x3FF).is_nan()); + // A 16-bit float is a half already, sign included. + assert_eq!(half(0xBC00 << half_shift(16)), -1.0); +} + +#[test] +fn packed_halves_fill_parameters_first_fit() { + // 16-bit rows as a title's signature has them: row 0 holds two + // elements (x y and z w), row 3 is 32-bit, row 4 has one channel at w. + let el = |row: u32, col: u8, cols: u8, half: bool| super::SigElement { + name: "TEXCOORD".into(), + index: row, + kind: 0, + comp: 9, + interp: 0, + row: Some(row), + col, + cols, + usage: 0, + half, + }; + let sig = [ + el(0, 0, 2, true), + el(0, 2, 2, true), + el(1, 0, 4, true), + el(2, 0, 3, true), + el(3, 0, 4, false), + el(4, 0, 3, true), + el(4, 3, 1, true), + el(5, 0, 3, true), + ]; + // Each half as row and channel ("-": padding or past the end). + let param = |a| { + (0..8) + .map(|h| match packed_half(&sig, a, h) { + Some((r, c)) => format!("{r}{}", ["x", "y", "z", "w"][usize::from(c)]), + None => "-".into(), + }) + .collect::>() + .join(" ") + }; + // By first channel, then row: row 0's x y, all of row 1, then (last, + // as it starts at z) row 0's z w. + assert_eq!(param(0), "0x 0y 1x 1y 1z 1w 0z 0w"); + // Three channels take two dwords; row 4's w fills the first + // parameter with room, after row 5. + assert_eq!(param(2), "2x 2y 2z - 4x 4y 4z -"); + assert_eq!(param(5), "5x 5y 5z - 4w - - -"); + // No parameter starts in rows 1, 3 or 4. + for a in [1, 3, 4] { + assert_eq!(param(a), "- - - - - - - -"); + } +} +#[test] +fn permlane16_lowers() { + let words = [ + // v_permlanex16_b32 v2, v0, s0, s1 (VOP3 opcode 0x378) + 0xD778_0002, + (1 << 18) | 0x100, + S_ENDPGM, + ]; + lowers(&words, 0).expect("v_permlanex16_b32 should lower"); +}