spill.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. //! The spilled user-data table of a compute program.
  2. //!
  3. //! A compute program has as many user SGPRs as `COMPUTE_PGM_RSRC2` says. A
  4. //! root signature that needs more dwords than that keeps none of its
  5. //! parameters in registers: user-data dwords 0 and 1 then hold the 40-bit
  6. //! address of a table in memory (`s0`, and `s1 & 0xff` as bits 32-39), and
  7. //! the parameter the layout declares at user-data index N (16 or above) is
  8. //! at byte `4 * (N - 16)` of that table. The code reads it with
  9. //! `s_load_dword*` through that pointer. (Every compute program of the
  10. //! console's ray-tracing structure builder, `XboxBvhBuilder.dll`, is of this
  11. //! kind; measured there: 118 of 118 such loads land on a declared parameter.)
  12. //!
  13. //! [`user_data`] rewrites those loads away: each dword they read becomes the
  14. //! entry value of the SGPR its user-data index names, as if the parameter
  15. //! had arrived in a register. Resource tracking and lowering then treat a
  16. //! spilled parameter like any other (the host binds user data by root slot
  17. //! and dword, not by register).
  18. use crate::ShaderError;
  19. use crate::gfx10::{Fields, NULL, Operand};
  20. use crate::ir::{self, Program, Reg, Value};
  21. use crate::native::{HwStage, NativeProgram, StageIo};
  22. /// The user-data index of the table's first dword.
  23. const FIRST: u32 = 16;
  24. /// [`ir::build`] of `native`'s code as the hardware runs it, with the loads
  25. /// of a spilled user-data table rewritten ([`user_data`]).
  26. pub fn build(native: &NativeProgram) -> Result<Program, ShaderError> {
  27. let mut p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
  28. user_data(&mut p, native);
  29. Ok(p)
  30. }
  31. /// Whether `native` is a compute program that keeps its root parameters in
  32. /// a spilled user-data table (see the module): the entries no register
  33. /// holds, as (first user-data index, dwords), if the table starts at index
  34. /// 16 and the program has the two registers of its address.
  35. fn spilled(native: &NativeProgram) -> Option<Vec<(u32, u32)>> {
  36. let StageIo::Cs(cs) = &native.io else {
  37. return None;
  38. };
  39. if native.stage != HwStage::Cs {
  40. return None;
  41. }
  42. let registers = u32::from(cs.user_sgprs());
  43. let spilled: Vec<(u32, u32)> = native
  44. .layout
  45. .iter()
  46. .filter(|e| e.sgprs > 0 && u32::from(e.user_data) >= registers)
  47. .map(|e| (u32::from(e.user_data), e.sgprs))
  48. .collect();
  49. // Only the one arrangement seen: the table starts at index 16.
  50. (spilled.iter().map(|e| e.0).min() == Some(FIRST) && registers >= 2).then_some(spilled)
  51. }
  52. /// Whether `native` reads its root parameters from a spilled user-data
  53. /// table. (In the title exactly the compute programs of the
  54. /// console's ray-tracing structure builder do.)
  55. pub fn is_spilled(native: &NativeProgram) -> bool {
  56. spilled(native).is_some()
  57. }
  58. /// Rewrites the loads of `native`'s spilled user-data table in `p`; returns
  59. /// how many loads it replaced. Nothing changes unless the program is a
  60. /// compute program whose layout has entries past its user SGPRs, the first
  61. /// at index 16. A load is left alone (and resource tracking then refuses it
  62. /// as before) when its offset is not a constant on a dword, or when a dword
  63. /// it reads and the program uses is in no layout entry.
  64. pub fn user_data(p: &mut Program, native: &NativeProgram) -> usize {
  65. let Some(spilled) = spilled(native) else {
  66. return 0;
  67. };
  68. let entry = |reg: Reg, p: &Program| p.inputs.iter().find(|i| i.0 == reg).map(|i| i.1);
  69. let (Some(low), Some(high)) = (entry(Reg::S(0), p), entry(Reg::S(1), p)) else {
  70. return 0;
  71. };
  72. // The pointer's halves: `s0` and its copies, `s1 & 0xff` and its copies.
  73. let mut lows = vec![low];
  74. let mut highs: Vec<Value> = Vec::new();
  75. let mut raw_highs = vec![high];
  76. // Instructions that only form the pointer: dropped when nothing reads
  77. // them any more.
  78. let mut forming: Vec<(usize, usize)> = Vec::new();
  79. loop {
  80. let mut changed = false;
  81. for (b, block) in p.blocks.iter().enumerate() {
  82. for (i, inst) in block.insts.iter().enumerate() {
  83. let Fields::Sop { dst, src, .. } = &inst.fields else {
  84. continue;
  85. };
  86. let Some(Operand::Scalar { code: d, .. }) = *dst else {
  87. continue;
  88. };
  89. let Some(out) = inst.write(Reg::S(d)) else {
  90. continue;
  91. };
  92. let read = |op: &Operand| match *op {
  93. Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)),
  94. _ => None,
  95. };
  96. let found = match (inst.name(), &src[..]) {
  97. ("s_mov_b32", [s]) => match read(s) {
  98. Some(v) if lows.contains(&v) => Some(&mut lows),
  99. Some(v) if highs.contains(&v) => Some(&mut highs),
  100. Some(v) if raw_highs.contains(&v) => Some(&mut raw_highs),
  101. _ => None,
  102. },
  103. ("s_and_b32", [x, y]) => {
  104. let masked = |a: &Operand, m: &Operand| {
  105. matches!(*m, Operand::Literal(0xff))
  106. && read(a).is_some_and(|v| raw_highs.contains(&v))
  107. };
  108. (masked(x, y) || masked(y, x)).then_some(&mut highs)
  109. }
  110. _ => None,
  111. };
  112. if let Some(set) = found
  113. && !set.contains(&out)
  114. {
  115. set.push(out);
  116. forming.push((b, i));
  117. changed = true;
  118. }
  119. }
  120. }
  121. if !changed {
  122. break;
  123. }
  124. }
  125. if highs.is_empty() {
  126. return 0;
  127. }
  128. // Values some instruction or phi reads.
  129. let mut read_somewhere = std::collections::HashSet::new();
  130. for block in &p.blocks {
  131. read_somewhere.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied()));
  132. read_somewhere.extend(block.insts.iter().flat_map(|i| i.reads.iter().map(|r| r.1)));
  133. }
  134. let mut next = p
  135. .inputs
  136. .iter()
  137. .map(|i| i.1)
  138. .chain(p.blocks.iter().flat_map(|b| {
  139. b.phis
  140. .iter()
  141. .map(|phi| phi.value)
  142. .chain(b.insts.iter().flat_map(|i| i.writes.iter().map(|w| w.1)))
  143. }))
  144. .map(|v| v.0 + 1)
  145. .max()
  146. .unwrap_or(0);
  147. // Each load through the pointer: its dwords become entry values.
  148. let mut replaced: std::collections::HashMap<Value, Value> = Default::default();
  149. let mut gone: Vec<(usize, usize)> = Vec::new();
  150. let mut inputs = p.inputs.clone();
  151. for (b, block) in p.blocks.iter().enumerate() {
  152. 'insts: for (i, inst) in block.insts.iter().enumerate() {
  153. let Fields::Smem {
  154. data: Some(Operand::Scalar { code: first, .. }),
  155. base: Operand::Scalar { code: base, .. },
  156. offset,
  157. soffset,
  158. ..
  159. } = inst.fields
  160. else {
  161. continue;
  162. };
  163. if !inst.name().starts_with("s_load_dword")
  164. || !matches!(soffset, Operand::Scalar { code: NULL, .. } | Operand::Const(128))
  165. || offset < 0
  166. || offset % 4 != 0
  167. || !inst.read(Reg::S(base)).is_some_and(|v| lows.contains(&v))
  168. || !inst.read(Reg::S(base + 1)).is_some_and(|v| highs.contains(&v))
  169. {
  170. continue;
  171. }
  172. let mut dwords = Vec::new();
  173. for &(reg, v) in &inst.writes {
  174. let Reg::S(code) = reg else {
  175. continue 'insts;
  176. };
  177. let Some(k) = code.checked_sub(first) else {
  178. continue 'insts;
  179. };
  180. let index = FIRST + offset as u32 / 4 + u32::from(k);
  181. let declared = spilled.iter().any(|&(at, n)| index >= at && index < at + n);
  182. if !declared {
  183. if read_somewhere.contains(&v) {
  184. continue 'insts;
  185. }
  186. continue;
  187. }
  188. // SGPR codes end at 105; no root signature reaches there.
  189. let Ok(code) = u8::try_from(index) else {
  190. continue 'insts;
  191. };
  192. if code > 105 {
  193. continue 'insts;
  194. }
  195. dwords.push((Reg::S(code), v));
  196. }
  197. for (reg, v) in dwords {
  198. let value = match inputs.iter().find(|e| e.0 == reg) {
  199. Some(e) => e.1,
  200. None => {
  201. let value = Value(next);
  202. next += 1;
  203. inputs.push((reg, value));
  204. value
  205. }
  206. };
  207. replaced.insert(v, value);
  208. }
  209. gone.push((b, i));
  210. }
  211. }
  212. if gone.is_empty() {
  213. return 0;
  214. }
  215. p.inputs = inputs;
  216. let renamed = |v: &mut Value| {
  217. if let Some(&to) = replaced.get(v) {
  218. *v = to;
  219. }
  220. };
  221. for block in &mut p.blocks {
  222. for phi in &mut block.phis {
  223. phi.args.iter_mut().for_each(renamed);
  224. }
  225. for inst in &mut block.insts {
  226. inst.reads.iter_mut().for_each(|r| renamed(&mut r.1));
  227. }
  228. }
  229. // The loads go, then what only formed the pointer (last first, so a
  230. // copy goes before what it copied).
  231. let mut drop = gone.clone();
  232. loop {
  233. let read_somewhere = {
  234. let mut used = std::collections::HashSet::new();
  235. for (b, block) in p.blocks.iter().enumerate() {
  236. used.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied()));
  237. for (i, inst) in block.insts.iter().enumerate() {
  238. if !drop.contains(&(b, i)) {
  239. used.extend(inst.reads.iter().map(|r| r.1));
  240. }
  241. }
  242. }
  243. used
  244. };
  245. let before = drop.len();
  246. for &site in &forming {
  247. let inst = &p.blocks[site.0].insts[site.1];
  248. if !drop.contains(&site) && inst.writes.iter().all(|w| !read_somewhere.contains(&w.1)) {
  249. drop.push(site);
  250. }
  251. }
  252. if drop.len() == before {
  253. break;
  254. }
  255. }
  256. for (b, block) in p.blocks.iter_mut().enumerate() {
  257. let mut i = 0;
  258. block.insts.retain(|_| {
  259. i += 1;
  260. !drop.contains(&(b, i - 1))
  261. });
  262. }
  263. // The pointer's registers are no inputs once nothing reads them.
  264. let mut read = std::collections::HashSet::new();
  265. for block in &p.blocks {
  266. read.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied()));
  267. read.extend(block.insts.iter().flat_map(|i| i.reads.iter().map(|r| r.1)));
  268. }
  269. p.inputs
  270. .retain(|&(reg, v)| !matches!(reg, Reg::S(0 | 1)) || read.contains(&v));
  271. gone.len()
  272. }
  273. #[cfg(test)]
  274. mod tests {
  275. use super::*;
  276. use crate::native::{ComputeIo, RootParam, RootType};
  277. fn param(root: RootType, user_data: u8, sgprs: u32, slot: u8) -> RootParam {
  278. RootParam {
  279. root,
  280. table_offset_dwords: 0,
  281. sgprs,
  282. base_register: 0,
  283. user_data,
  284. slot,
  285. }
  286. }
  287. /// A compute program with `registers` user SGPRs and the group id after
  288. /// them.
  289. fn native(words: &[u32], registers: u32, layout: Vec<RootParam>) -> NativeProgram {
  290. NativeProgram {
  291. stage: HwStage::Cs,
  292. wave64: false,
  293. vgprs: 256,
  294. layout,
  295. used: vec![],
  296. io: StageIo::Cs(ComputeIo {
  297. rsrc2: registers << 1 | 1 << 7,
  298. threads: [1, 1, 1],
  299. }),
  300. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  301. }
  302. }
  303. // s_and_b32 s3, s1, 0xff; s_mov_b32 s2, s0; s_load_dword s5, s[2:3],
  304. // 0x10; s_load_dwordx2 s[0:1], s[2:3], 0; s_endpgm.
  305. const TABLE: [u32; 8] = [
  306. 0x8703_FF01,
  307. 0x0000_00FF,
  308. 0xBE82_0300,
  309. 0xF400_0141,
  310. 0xFA00_0010,
  311. 0xF404_0001,
  312. 0xFA00_0000,
  313. 0xBF81_0000,
  314. ];
  315. #[test]
  316. fn loads_of_the_spilled_table_become_entry_registers() {
  317. let n = native(
  318. &TABLE,
  319. 4,
  320. vec![
  321. param(RootType::Descriptor, 16, 2, 0),
  322. param(RootType::Descriptor, 18, 2, 1),
  323. param(RootType::Constants, 20, 16, 2),
  324. ],
  325. );
  326. let mut p = ir::build(&n.code, false, 256).unwrap();
  327. assert_eq!(user_data(&mut p, &n), 2);
  328. let names: Vec<&str> = p.blocks.iter().flat_map(|b| &b.insts).map(|i| i.name()).collect();
  329. assert!(!names.iter().any(|n| n.starts_with("s_load_")), "{names:?}");
  330. // The pointer is gone with the loads; byte 0x10 is index 20, the
  331. // first root constant, and bytes 0-7 are the first root view.
  332. let mut regs: Vec<Reg> = p.inputs.iter().map(|i| i.0).collect();
  333. regs.sort();
  334. assert_eq!(regs, [Reg::S(16), Reg::S(17), Reg::S(20)]);
  335. }
  336. #[test]
  337. fn parameters_in_registers_are_left_alone() {
  338. // The same code where s0 and s1 are a root view the layout declares.
  339. let n = native(&TABLE, 6, vec![param(RootType::Descriptor, 0, 2, 0)]);
  340. let mut p = ir::build(&n.code, false, 256).unwrap();
  341. let before = p.clone();
  342. assert_eq!(user_data(&mut p, &n), 0);
  343. assert_eq!(p, before);
  344. }
  345. #[test]
  346. fn a_used_dword_no_parameter_declares_keeps_its_load() {
  347. // As above with `s_mov_b32 s6, s5` before the end: the dword at
  348. // byte 0x10 (index 20) is read, and here nothing declares it.
  349. let mut words = TABLE.to_vec();
  350. words.insert(7, 0xBE86_0305);
  351. let n = native(&words, 4, vec![param(RootType::Descriptor, 16, 2, 0)]);
  352. let mut p = ir::build(&n.code, false, 256).unwrap();
  353. assert_eq!(user_data(&mut p, &n), 1);
  354. let loads = p
  355. .blocks
  356. .iter()
  357. .flat_map(|b| &b.insts)
  358. .filter(|i| i.name().starts_with("s_load_"))
  359. .count();
  360. assert_eq!(loads, 1);
  361. // The pointer is still read, by the load that stays.
  362. assert!(p.inputs.iter().any(|i| i.0 == Reg::S(0)));
  363. }
  364. }