//! GFX10 machine code: instruction boundaries, encodings and opcodes. //! //! Instructions are found by following control flow from offset 0, not by a //! linear sweep: compilers place data (constant tables) in the code region //! after the end of the program. [`Instruction::fields`] decodes the operand //! fields and [`Instruction::text`] prints them in AMD's SP3 syntax. //! //! Encodings by the top bits of the first dword: //! //! ```text //! 0xxxxxxx VOP2; 0111111 VOP1; 0111110 VOPC //! 10 SOP2; 1011 SOPK; 101111101 SOP1; 101111110 SOPC; 101111111 SOPP //! 110010 VINTRP 110011 VOP3P 110101 VOP3 110110 DS 110111 FLAT/GLOBAL/SCRATCH //! 111000 MUBUF 111010 MTBUF 111100 MIMG 111101 SMEM 111110 EXP //! ``` mod fields; mod opcodes; mod sp3; pub use fields::{Cache, Dpp, Fields, NULL, Operand, Sdwa, Valu}; use std::borrow::Borrow; use crate::ShaderError; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Encoding { Sop2, Sopk, Sop1, Sopc, Sopp, Smem, Vop2, Vop1, Vopc, Vop3, Vop3p, Vintrp, Ds, Mubuf, Mtbuf, Mimg, Exp, Flat, Global, Scratch, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Instruction { /// Byte offset in the program. pub offset: usize, pub encoding: Encoding, pub opcode: u16, /// Every dword of the instruction, including literals and extra dwords. pub words: Vec, } impl Instruction { /// AMD's name for the opcode, if it is in our table. pub fn name(&self) -> Option<&'static str> { name(self.encoding, self.opcode) } } /// Decodes every instruction reachable from offset 0, sorted by offset. pub fn decode(code: &[u8]) -> Result, ShaderError> { if !code.len().is_multiple_of(4) { return Err(isa(code.len(), "code size is not a multiple of 4")); } // Far jumps can land at unaligned byte offsets. Record each exact start. let mut starts = vec![0u8; code.len().div_ceil(8)]; let mut list = Vec::new(); let mut max_bytes = 0; let mut pending = vec![0usize]; while let Some(mut offset) = pending.pop() { loop { let seen = |at: usize| starts.get(at / 8).is_some_and(|b| b & (1 << (at % 8)) != 0); if seen(offset) { break; } let inst = instruction(code, offset)?; let next = offset + 4 * inst.words.len(); let flow = control(&inst, code.len(), |at| { // Only far jumps look back. A more distant predecessor cannot end // at 'at'. Use the nearest start even when instructions overlap. (at.saturating_sub(max_bytes)..at) .rev() .find(|&pos| seen(pos)) .map(|pos| instruction(code, pos).expect("previously decoded instruction")) })?; max_bytes = max_bytes.max(next - offset); starts[offset / 8] |= 1 << (offset % 8); list.push(inst); match flow { Flow::Next => offset = next, Flow::Stop => break, Flow::Jump(target) => offset = target, Flow::Branch(target) => { pending.push(target); offset = next; } } } } if !list.is_sorted_by_key(|i| i.offset) { list.sort_unstable_by_key(|i| i.offset); } if let Some(w) = list .windows(2) .find(|w| w[0].offset + 4 * w[0].words.len() > w[1].offset) { return Err(isa(w[1].offset, "a branch lands inside an instruction")); } Ok(list) } /// Where execution goes after an instruction. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Flow { Next, /// End of the program, or an indirect jump that is not a far jump. Stop, Jump(usize), /// Conditional: to the target or the next instruction. Branch(usize), } /// Control flow after `inst`, resolving far jumps. `before(at)` returns the /// decoded instruction with the highest offset below `at`, if any. It may /// also return `None` when that instruction does not end at `at`. pub(crate) fn control>( inst: &Instruction, len: usize, before: impl Fn(usize) -> Option, ) -> Result { Ok(match flow(inst, inst.offset + 4 * inst.words.len(), len)? { Flow::Stop if inst.name() == Some("s_setpc_b64") => { far_jump(before, inst, len)?.map_or(Flow::Stop, Flow::Jump) } flow => flow, }) } fn flow(inst: &Instruction, next: usize, len: usize) -> Result { let target = || { let delta = 4 * i64::from(inst.words[0] as u16 as i16); usize::try_from(next as i64 + delta) .ok() .filter(|&t| t < len) .ok_or(isa(inst.offset, "branch target outside the code")) }; Ok(match (inst.encoding, inst.name().unwrap_or("")) { ( Encoding::Sopp, "s_endpgm" | "s_endpgm_saved" | "s_endpgm_ordered_ps_done" | "s_code_end", ) => Flow::Stop, (Encoding::Sopp, "s_branch") => Flow::Jump(target()?), (Encoding::Sopp, name) if name.starts_with("s_cbranch_") => Flow::Branch(target()?), (Encoding::Sopk, "s_call_b64") => Flow::Branch(target()?), // Indirect jump; `decode` resolves the compiler's far-jump form. (Encoding::Sop1, "s_setpc_b64") => Flow::Stop, _ => Flow::Next, }) } /// Resolves the far jump compilers emit beyond the reach of a branch offset: /// `s_getpc_b64 s[n:n+1]`, `s_add_u32|s_sub_u32 sn, sn, literal`, a carry /// into s(n+1), `s_setpc_b64 s[n:n+1]`, looking back over the straight-line /// run just decoded. Any other `s_setpc_b64` (e.g. a handover to the next /// merged stage through registers) gives `None`. fn far_jump>( before: impl Fn(usize) -> Option, setpc: &Instruction, len: usize, ) -> Result, ShaderError> { let n = setpc.words[0] & 0xFF; let mut delta = None; let mut at = setpc.offset; for _ in 0..4 { let Some(prev) = before(at) else { break; }; let prev = prev.borrow(); if prev.offset + 4 * prev.words.len() != at { break; } let w = prev.words[0]; let (sdst, ssrc0, ssrc1) = ((w >> 16) & 0x7F, w & 0xFF, (w >> 8) & 0xFF); match (prev.encoding, prev.name()) { (Encoding::Sop2, Some(op @ ("s_add_u32" | "s_sub_u32"))) if sdst == n && ssrc0 == n && ssrc1 == 0xFF && delta.is_none() => { // The low dword of a signed 64-bit offset: a backward jump // adds a negative one (its high dword is -1). let literal = i64::from(prev.words[1] as i32); delta = Some(if op == "s_add_u32" { literal } else { -literal }); } (Encoding::Sop1, Some("s_getpc_b64")) if sdst == n => { let Some(delta) = delta else { break }; // s_getpc_b64 yields the address of the instruction after it. return usize::try_from(prev.offset as i64 + 4 + delta) .ok() .filter(|&t| t < len) .map(Some) .ok_or(isa(setpc.offset, "far jump target outside the code")); } _ => {} } at = prev.offset; } Ok(None) } fn instruction(code: &[u8], offset: usize) -> Result { let word = |i: usize| { code.get(offset + 4 * i..offset + 4 * i + 4) .map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes"))) .ok_or(isa(offset, "instruction runs past the end of the code")) }; let w = word(0)?; let (encoding, opcode, len) = if w >> 31 == 0 { let src0 = w & 0x1FF; // Literal constant, SDWA, DPP16, DPP8, DPP8 with fetch-inactive. let extra = usize::from(matches!(src0, 0xFF | 0xF9 | 0xFA | 0xE9 | 0xEA)); match w >> 25 { 0x3F => { let opcode = (w >> 9) & 0xFF; // v_nop, v_pipeflush and v_clrexcp ignore SRC0. let len = if matches!(opcode, 0x00 | 0x1b | 0x41) { 1 } else { 1 + extra }; (Encoding::Vop1, opcode, len) } 0x3E => (Encoding::Vopc, (w >> 17) & 0xFF, 1 + extra), op => { let mk_ak = name(Encoding::Vop2, op as u16).is_some_and(|n| { matches!( n, "v_madmk_f32" | "v_madak_f32" | "v_fmamk_f32" | "v_fmaak_f32" | "v_madmk_f16" | "v_madak_f16" | "v_fmamk_f16" | "v_fmaak_f16" ) }); (Encoding::Vop2, op, 1 + extra.max(usize::from(mk_ak))) } } } else if w >> 30 == 0b10 { let literal = |srcs: &[u32]| 1 + usize::from(srcs.contains(&0xFF)); match w >> 23 { 0x17D => (Encoding::Sop1, (w >> 8) & 0xFF, literal(&[w & 0xFF])), 0x17E => ( Encoding::Sopc, (w >> 16) & 0x7F, literal(&[w & 0xFF, (w >> 8) & 0xFF]), ), 0x17F => (Encoding::Sopp, (w >> 16) & 0x7F, 1), _ if w >> 28 == 0b1011 => { let op = (w >> 23) & 0x1F; let imm32 = name(Encoding::Sopk, op as u16) == Some("s_setreg_imm32_b32"); (Encoding::Sopk, op, 1 + usize::from(imm32)) } _ => ( Encoding::Sop2, (w >> 23) & 0x7F, literal(&[w & 0xFF, (w >> 8) & 0xFF]), ), } } else { let vop3 = |w1: u32| 2 + usize::from([w1, w1 >> 9, w1 >> 18].iter().any(|s| s & 0x1FF == 0xFF)); match w >> 26 { 0x32 => (Encoding::Vintrp, (w >> 16) & 0x3, 1), 0x33 => (Encoding::Vop3p, (w >> 16) & 0x7F, vop3(word(1)?)), 0x35 => (Encoding::Vop3, (w >> 16) & 0x3FF, vop3(word(1)?)), 0x36 => (Encoding::Ds, (w >> 18) & 0xFF, 2), 0x37 => { let encoding = match (w >> 14) & 3 { 0 => Encoding::Flat, 1 => Encoding::Scratch, 2 => Encoding::Global, _ => return Err(isa(offset, "reserved FLAT segment")), }; (encoding, (w >> 18) & 0x7F, 2) } 0x38 => (Encoding::Mubuf, (w >> 18) & 0x7F | (w >> 25 & 1) << 7, 2), 0x3A => ( Encoding::Mtbuf, (w >> 16) & 0x7 | (word(1)? >> 21 & 1) << 3, 2, ), // Bits 2:1 count extra dwords of non-sequential address registers. 0x3C => ( Encoding::Mimg, (w >> 18) & 0x7F | (w & 1) << 7, 2 + (w as usize >> 1 & 3), ), 0x3D => (Encoding::Smem, (w >> 18) & 0xFF, 2), 0x3E => (Encoding::Exp, 0, 2), _ => return Err(isa(offset, "unknown encoding")), } }; Ok(Instruction { offset, encoding, opcode: opcode as u16, words: (0..len).map(word).collect::>()?, }) } fn name(encoding: Encoding, opcode: u16) -> Option<&'static str> { use opcodes as t; let (table, op) = match encoding { Encoding::Sop2 => (t::SOP2, opcode), Encoding::Sopk => (t::SOPK, opcode), Encoding::Sop1 => (t::SOP1, opcode), Encoding::Sopc => (t::SOPC, opcode), Encoding::Sopp => (t::SOPP, opcode), Encoding::Smem => (t::SMEM, opcode), Encoding::Vop2 => (t::VOP2, opcode), Encoding::Vop1 => (t::VOP1, opcode), Encoding::Vopc => (t::VOPC, opcode), // VOP3 also encodes the VOPC, VOP2 and VOP1 opcodes at fixed bases. Encoding::Vop3 => match opcode { 0x000..0x100 => (t::VOPC, opcode), 0x100..0x140 => (t::VOP2, opcode - 0x100), 0x180..0x200 => (t::VOP1, opcode - 0x180), _ => (t::VOP3, opcode), }, Encoding::Vop3p => (t::VOP3P, opcode), Encoding::Vintrp => (t::VINTRP, opcode), Encoding::Ds => (t::DS, opcode), Encoding::Mubuf => (t::MUBUF, opcode), Encoding::Mtbuf => (t::MTBUF, opcode), Encoding::Mimg => (t::MIMG, opcode), Encoding::Exp => return Some("exp"), Encoding::Flat => (t::FLAT, opcode), Encoding::Global => (t::GLOBAL, opcode), Encoding::Scratch => (t::SCRATCH, opcode), }; table .binary_search_by_key(&op, |&(o, _)| o) .ok() .map(|i| table[i].1) } fn isa(offset: usize, reason: &'static str) -> ShaderError { ShaderError::Isa { offset, reason } } #[cfg(test)] mod tests { use std::collections::BTreeMap; use super::*; const S_ENDPGM: u32 = 0xBF81_0000; /// s_branch / s_cbranch_scc0 with a dword offset relative to the next instruction. const fn sopp(op: u32, simm16: i16) -> u32 { 0xBF80_0000 | op << 16 | simm16 as u16 as u32 } fn bytes(words: &[u32]) -> Vec { words.iter().flat_map(|w| w.to_le_bytes()).collect() } fn summary(code: &[u32]) -> Vec<(usize, usize, &'static str)> { decode(&bytes(code)) .unwrap() .iter() .map(|i| (i.offset, i.words.len(), i.name().unwrap_or("?"))) .collect() } // The loop exit is pending while the decoder visits the nested diamonds. // The latch jumps back to a known header, so both else arms are discovered // out of order before the traversal moves on to the next loop. fn nested_loops() -> Vec { let mut words = [0x8001_8100, 0x0600_0100].repeat(20); for _ in 0..32 { words.extend([ 0xBF00_0100, // loop header: s_cmp_eq_i32 sopp(4, 12), // exit to the next header (or endpgm) 0xBF00_0201, sopp(4, 7), // outer else 0xBF00_0302, sopp(4, 3), // inner else 0xBE80_03FF, 0x3F80_0000, // then: s_mov_b32 with literal sopp(2, 1), // inner join 0x7E00_0201, sopp(2, 1), // outer join 0x0600_0100, 0x8001_8100, // latch: s_add_u32 sopp(2, -14), // repeat ]); } words.push(S_ENDPGM); bytes(&words) } // Keep the original tree-only traversal as an independent reference for decode. fn reference_decode(code: &[u8]) -> Result, ShaderError> { if !code.len().is_multiple_of(4) { return Err(isa(code.len(), "code size is not a multiple of 4")); } let mut found = BTreeMap::new(); let mut pending = vec![0usize]; while let Some(mut offset) = pending.pop() { while !found.contains_key(&offset) { let inst = instruction(code, offset)?; let next = offset + 4 * inst.words.len(); let flow = control(&inst, code.len(), |at| { found.range(..at).next_back().map(|(_, i)| i) })?; found.insert(offset, inst); match flow { Flow::Next => offset = next, Flow::Stop => break, Flow::Jump(target) => offset = target, Flow::Branch(target) => { pending.push(target); offset = next; } } } } let list: Vec = found.into_values().collect(); if let Some(w) = list .windows(2) .find(|w| w[0].offset + 4 * w[0].words.len() > w[1].offset) { return Err(isa(w[1].offset, "a branch lands inside an instruction")); } Ok(list) } fn assert_same_decode(code: &[u8]) { assert_eq!( decode(code), reference_decode(code), "decoder mismatch for {code:x?}" ); } #[test] fn matches_tree_decoder_across_encodings_and_truncations() { // Vary all nine leading bits, the payload (including literal and DPP // selectors), and each possible instruction length through five dwords. for prefix in 0..512 { for payload in [0, 0xE9, 0xEA, 0xF9, 0xFA, 0xFF, 0x55_FF02, 0x7F_FFFF] { let code = bytes(&[prefix << 23 | payload, 0x03FE_0000, 1, 2, 3, S_ENDPGM]); for len in (0..=code.len()).step_by(4) { assert_same_decode(&code[..len]); } } } assert_same_decode(&[1, 2, 3]); } #[test] fn matches_tree_decoder_across_opcode_ranges() { for (base, shift, opcodes) in [ (0x8000_0000, 23, 128), (0xB000_0000, 23, 32), (0xBE80_0000, 8, 256), (0xBF00_0000, 16, 128), (0xBF80_0000, 16, 128), (0xF400_0000, 18, 256), (0, 25, 64), (0x7E00_0000, 9, 256), (0x7C00_0000, 17, 256), (0xD400_0000, 16, 1024), (0xCC00_0000, 16, 128), (0xC800_0000, 16, 4), (0xD800_0000, 18, 256), (0xE000_0000, 18, 256), (0xE800_0000, 16, 8), (0xF000_0000, 18, 128), (0xDC00_0000, 18, 128), (0xF800_0000, 0, 1), ] { for op in 0..opcodes { for (flags, w1) in [(0, 0), (1, 1 << 21), (1 << 14, 0xFF), (2 << 14, 0)] { assert_same_decode(&bytes(&[ base | op << shift | flags, w1, S_ENDPGM, S_ENDPGM, ])); } } } } #[test] fn matches_tree_decoder_across_branch_targets() { // Conditional and unconditional edges, including backward jumps, // revisits, holes, out-of-range targets and jumps into literal data. for op in [2, 4] { for a in -2..=9 { for b in -8..=4 { assert_same_decode(&bytes(&[ sopp(op, a), 0xBE80_03FF, S_ENDPGM, sopp(2, 2), sopp(4, -4), S_ENDPGM, sopp(op, b), S_ENDPGM, ])); } } } } #[test] fn matches_tree_on_nested_loops_and_random_streams() { assert_same_decode(&nested_loops()); let mut state = 0x9e37_79b9_u32; for _ in 0..4096 { let mut words = [0u32; 24]; for w in &mut words { state ^= state << 13; state ^= state >> 17; state ^= state << 5; let delta = (state % 25) as i16 - 12; *w = match state >> 29 { 0 => sopp(2, delta), 1 | 2 => sopp(4, delta), 3 => 0xBE80_03FF, 4 => S_ENDPGM, 5 => state, _ => 0x0600_0100, }; } assert_same_decode(&bytes(&words)); } } #[test] fn preserves_overlap_error_precedence_and_unaligned_far_targets() { // The pending target is a literal. Its own decode/flow error takes // precedence over the overlap, which is only checked after traversal. for literal in [S_ENDPGM, sopp(2, -100), 0xFFFF_FFFF] { assert_same_decode(&bytes(&[sopp(4, 1), 0xBE80_03FF, literal, S_ENDPGM])); } // Discover the literal first, then the instruction which contains it. assert_same_decode(&bytes(&[ sopp(4, 1), sopp(2, 1), 0xBE80_03FF, S_ENDPGM, S_ENDPGM, ])); for target in 0u32..=32 { let mut code = bytes(&[ 0xBE88_1F00, 0x8008_FF08, target.wrapping_sub(4), 0x8209_8009, 0xBE80_2008, 0, 0, S_ENDPGM, ]); if (20..=28).contains(&target) { code[target as usize..target as usize + 4].copy_from_slice(&S_ENDPGM.to_le_bytes()); } assert_same_decode(&code); } } #[test] fn operandless_vop1_preserves_the_following_instruction() { for (opcode, name) in [(0, "v_nop"), (0x1b, "v_pipeflush"), (0x41, "v_clrexcp")] { for src in [0xe9, 0xea, 0xf9, 0xfa, 0xff] { let word = 0x7e00_0000 | (opcode << 9) | src; assert_eq!(summary(&[word, S_ENDPGM]), [(0, 1, name), (4, 1, "s_endpgm")]); } } assert_eq!(summary(&[0x7e00_02ff, 123, S_ENDPGM]), [(0, 2, "v_mov_b32"), (8, 1, "s_endpgm")]); } #[test] fn vop3_cmpx_writes_the_active_exec_lanes() { let code = bytes(&[0xd411_0005, 0x0001_e501, S_ENDPGM]); let decoded = decode(&code).unwrap(); assert_eq!(decoded[0].name(), Some("v_cmpx_lt_f32")); for (wave64, dwords) in [(false, 1), (true, 2)] { let Fields::Valu(v) = decoded[0].fields(wave64) else { panic!("expected a vector instruction") }; assert_eq!(v.dst, Some(Operand::Scalar { code: 126, dwords })); } } // cargo test --release -p victory-shader gfx10_decode_throughput -- --ignored --nocapture #[test] #[ignore = "benchmark"] fn gfx10_decode_throughput() { use std::{hint::black_box, time::Instant}; // A synthetic shader block with a reconverging conditional branch, // scalar and vector ALU, memory, interpolation and export instructions. let block = [ 0xBE80_03FF, 0x3F80_0000, // s_mov_b32 with a literal 0x8001_8100, 0xBF00_0100, 0xB002_0004, // SOP2, SOPC, SOPK sopp(4, 1), // conditional branch over v_mov_b32 0x7E00_0201, 0x0600_0100, 0x7C04_0100, // v_add_f32, v_cmp_eq_f32 0xD54B_0000, 0x03FE_0000, 0x4000_0000, // v_fma_f32 with a literal 0xCC02_0000, 0x0402_0100, // packed vector add 0xF400_0000, 0x0000_0004, // scalar load 0xE000_0000, 0x8001_0203, 0xE800_0000, 0x8001_0203, // buffer loads 0xF080_0F0A, 0x0000_0201, 0x0000_0003, // image sample with NSA 0xD800_0000, 0x0000_0201, 0xDC30_0000, 0x0000_0001, // DS, FLAT 0xC800_0000, 0xF800_000F, 0x0302_0100, // interpolation, export ]; let mut words = block.repeat(32); words.push(S_ENDPGM); let code = bytes(&words); let decoded = decode(&code).unwrap(); let count = 18 * 32 + 1; assert_eq!(decoded.len(), count); assert!(decoded.iter().all(|i| i.name().is_some())); drop(decoded); const RUNS: usize = 1024; let mut samples = [std::time::Duration::ZERO; 7]; for sample in &mut samples { let start = Instant::now(); for _ in 0..RUNS { black_box(decode(black_box(&code)).unwrap()); } *sample = start.elapsed(); } samples.sort_unstable(); let seconds = samples[samples.len() / 2].as_secs_f64(); println!( "{:.3} M inst/s, {:.3} MB/s (median of {} samples)", (count * RUNS) as f64 / seconds / 1e6, (code.len() * RUNS) as f64 / seconds / 1e6, samples.len() ); } #[test] fn tables_are_sorted() { for t in [ opcodes::SOP2, opcodes::SOPK, opcodes::SOP1, opcodes::SOPC, opcodes::SOPP, opcodes::SMEM, opcodes::VOP2, opcodes::VOP1, opcodes::VOPC, opcodes::VOP3, opcodes::VOP3P, opcodes::VINTRP, opcodes::DS, opcodes::MUBUF, opcodes::MTBUF, opcodes::MIMG, opcodes::FLAT, opcodes::GLOBAL, opcodes::SCRATCH, ] { assert!(t.windows(2).all(|w| w[0].0 < w[1].0)); } } #[test] fn lengths_and_names() { let code = [ 0xBE80_03FF, 0x3F80_0000, // s_mov_b32 s0, literal 0x0600_0000, // v_add_f32 v0, s0, v0 0xD54B_0000, 0x03FE_0000, 0x4000_0000, // v_fma_f32 with a literal src2 0xF080_0F0A, 0, 0, // image_sample (2D) with one extra address dword 0xF800_080F, 0, // exp S_ENDPGM, ]; assert_eq!( summary(&code), [ (0, 2, "s_mov_b32"), (8, 1, "v_add_f32"), (12, 3, "v_fma_f32"), (24, 3, "image_sample"), (36, 2, "exp"), (44, 1, "s_endpgm"), ] ); } #[test] fn follows_branches_and_skips_data() { let code = [ sopp(0x04, 1), // s_cbranch_scc0 -> 8 sopp(0x02, 1), // s_branch -> 12 S_ENDPGM, S_ENDPGM, S_ENDPGM, // data follows the program end 0xFFFF_FFFF, ]; let found: Vec<_> = summary(&code).iter().map(|i| i.0).collect(); assert_eq!(found, [0, 4, 8, 12]); } #[test] fn follows_far_jumps() { let code = [ 0xBE88_1F00, // s_getpc_b64 s[8:9] 0x8008_FF08, 20, // s_add_u32 s8, s8, 20 -> 4 + 20 = 24 0x8209_8009, // s_addc_u32 s9, s9, 0 0xBE80_2008, // s_setpc_b64 s[8:9] 0xFFFF_FFFF, // not code S_ENDPGM, ]; let found: Vec<_> = summary(&code).iter().map(|i| (i.0, i.2)).collect(); assert_eq!( found, [ (0, "s_getpc_b64"), (4, "s_add_u32"), (12, "s_addc_u32"), (16, "s_setpc_b64"), (24, "s_endpgm"), ] ); // Through other registers (a handover to another stage): the path ends. assert_eq!(summary(&[0xBE80_2018, S_ENDPGM]).len(), 1); } #[test] fn follows_far_jumps_backward() { // The compiler's backward far jump adds a negative offset: the low // dword as a 32-bit literal, the high dword as -1 with the carry. let code = [ sopp(0x02, 1), // s_branch -> 8, past the jump target S_ENDPGM, // the far jump's target: only it reaches here 0xBE88_1F00, // s_getpc_b64 s[8:9] 0x8008_FF08, 0xFFFF_FFF8, // s_add_u32 s8, s8, -8 -> 12 - 8 = 4 0x8209_C109, // s_addc_u32 s9, s9, -1 0xBE80_2008, // s_setpc_b64 s[8:9] ]; let found: Vec<_> = summary(&code).iter().map(|i| (i.0, i.2)).collect(); assert_eq!( found, [ (0, "s_branch"), (4, "s_endpgm"), (8, "s_getpc_b64"), (12, "s_add_u32"), (20, "s_addc_u32"), (24, "s_setpc_b64"), ] ); } #[test] fn rejects_bad_code() { assert!(decode(&[0; 3]).is_err(), "size not a multiple of 4"); assert!( decode(&bytes(&[sopp(0x02, 100)])).is_err(), "branch out of range" ); assert!( decode(&bytes(&[0xBE80_03FF])).is_err(), "literal past the end" ); assert!( decode(&bytes(&[0xE400_0000, 0])).is_err(), "unknown encoding" ); // s_cbranch_scc0 into the literal of the s_mov_b32 at 4. assert!(decode(&bytes(&[sopp(0x04, 1), 0xBE80_03FF, S_ENDPGM, S_ENDPGM])).is_err()); } }