threading.rs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. //! Jump threading for uniform diamonds. One arm can set a flag that fixes
  2. //! the join's next branch. Registers recycled on that arm then never reach
  3. //! the other successor, even if an ordinary SSA phi joins their values.
  4. use crate::gfx10::{Fields, Operand, Valu};
  5. use crate::ir::{Exit, Program, Reg, Value};
  6. use crate::structure::{Atom, Bool, LaneExit, Structured};
  7. use std::collections::HashMap;
  8. fn plain(v: &Valu) -> bool {
  9. v.abs == 0
  10. && v.neg == 0
  11. && v.opsel == 0
  12. && !v.clamp
  13. && v.omod == 0
  14. && v.sdwa.is_none()
  15. && v.dpp.is_none()
  16. }
  17. fn immediate(op: Operand) -> Option<u32> {
  18. match op {
  19. Operand::Const(c) => crate::resource::inline(c),
  20. Operand::Literal(n) => Some(n),
  21. _ => None,
  22. }
  23. }
  24. pub(super) fn constant_edges(p: &Program, st: &Structured) -> Vec<(usize, usize, usize)> {
  25. let mut constants = HashMap::new();
  26. for (b, block) in p.blocks.iter().enumerate() {
  27. for (i, inst) in block.insts.iter().enumerate() {
  28. if inst.name() == "v_mov_b32"
  29. && st.guards[b][i].is_none()
  30. && let Fields::Valu(v) = &inst.fields
  31. && plain(v)
  32. && let [src] = v.src.as_slice()
  33. && let Some(word) = immediate(*src)
  34. && let [(_, dst)] = inst.writes.as_slice()
  35. {
  36. constants.insert(*dst, word);
  37. }
  38. }
  39. }
  40. let mut edges = Vec::new();
  41. for (join, block) in p.blocks.iter().enumerate() {
  42. let LaneExit::Branch {
  43. when,
  44. taken,
  45. not_taken,
  46. } = st.exits[join]
  47. else {
  48. continue;
  49. };
  50. if when == Bool::TRUE || when == Bool::FALSE {
  51. continue;
  52. }
  53. // Keep memory accesses and wave operations at their original
  54. // reconvergence point. Only duplicate scalar ALU and comparisons.
  55. if !block.insts.iter().all(|i| match &i.fields {
  56. Fields::Sop { .. } => true,
  57. Fields::Sopp { .. } => i.name().starts_with("s_cbranch_"),
  58. Fields::Valu(_) => i.name().starts_with("v_cmp_"),
  59. _ => false,
  60. }) {
  61. continue;
  62. }
  63. let [a, b] = block.preds.as_slice() else {
  64. continue;
  65. };
  66. // A triangle has a direct edge from the fork to the join. A full
  67. // diamond has an unconditional jump at the end of each arm.
  68. let arm_from = |arm: usize| match p.blocks[arm].preds.as_slice() {
  69. &[fork] if p.blocks[arm].exit == Exit::Jump(join) => Some(fork),
  70. _ => None,
  71. };
  72. let fork = match (arm_from(*a), arm_from(*b)) {
  73. (Some(f), Some(g)) if f == g => f,
  74. (_, Some(f)) if f == *a => f,
  75. (Some(f), _) if f == *b => f,
  76. _ => continue,
  77. };
  78. if fork == join || a == b {
  79. continue;
  80. }
  81. let LaneExit::Branch { when: entry, .. } = st.exits[fork] else {
  82. continue;
  83. };
  84. if !st
  85. .bools
  86. .support(entry)
  87. .iter()
  88. .all(|a| matches!(a, Atom::Uniform(_)))
  89. {
  90. continue;
  91. }
  92. for (edge, &pred) in block.preds.iter().enumerate() {
  93. let value = |v: Value| {
  94. let input = block
  95. .phis
  96. .iter()
  97. .find(|p| p.value == v)
  98. .map_or(v, |p| p.args[edge]);
  99. constants.get(&input).copied()
  100. };
  101. // Restrict the branch's decision diagram to known comparisons.
  102. // Unknown tests stop the proof. Keep the original join for the
  103. // other arm, which may still go either way.
  104. let mut cond = when;
  105. while let Some((Atom::Lane(id), lo, hi)) = st.bools.node(cond) {
  106. let Some(inst) = block
  107. .insts
  108. .iter()
  109. .find(|i| i.writes.iter().any(|&(_, v)| v == id))
  110. else {
  111. break;
  112. };
  113. let Fields::Valu(v) = &inst.fields else { break };
  114. let [left, right] = v.src.as_slice() else {
  115. break;
  116. };
  117. let operand = |op| match op {
  118. Operand::Vector { reg, dwords: 1 } => value(inst.read(Reg::V(reg))?),
  119. _ => immediate(op),
  120. };
  121. let (Some(x), Some(y)) = (operand(*left), operand(*right)) else {
  122. break;
  123. };
  124. if !plain(v) {
  125. break;
  126. }
  127. let yes = match inst.name() {
  128. "v_cmp_eq_u32" | "v_cmp_eq_i32" => x == y,
  129. "v_cmp_ne_u32" | "v_cmp_ne_i32" => x != y,
  130. _ => break,
  131. };
  132. cond = if yes { hi } else { lo };
  133. }
  134. if cond == Bool::TRUE || cond == Bool::FALSE {
  135. edges.push((
  136. pred,
  137. join,
  138. if cond == Bool::TRUE { taken } else { not_taken },
  139. ));
  140. break;
  141. }
  142. }
  143. }
  144. edges
  145. }
  146. #[cfg(test)]
  147. mod tests {
  148. use super::*;
  149. use crate::ir;
  150. use crate::structure;
  151. // s8 initially holds a descriptor address. One arm overwrites it with
  152. // a buffer load and sets v1. Only that arm can use s8 as the stored value.
  153. const WORDS: [u32; 19] = [
  154. 0xbe810380, // s1 = 0 (table address high)
  155. 0xf4080200, 0xfa000000, // load SRV into s[8:11]
  156. 0xf4080300, 0xfa000020, // load UAV into s[12:15]
  157. 0x7e020280, // v1 = 0
  158. 0xbf068002, 0xbf850003, // if s2 == 0, jump to join
  159. 0xf4200204, 0xfa00000c, // s8 = buffer.Load(12)
  160. 0x7e020281, // v1 = 1
  161. 0x7d840280, 0xbf870002, // join: if v1 == 0, jump to constant
  162. 0x7e060208, 0xbf820001, // v3 = s8, jump to store
  163. 0x7e060293, // constant: v3 = 19
  164. 0xe0700000, 0x80030300, // store v3 at byte 0
  165. 0xbf810000, // end
  166. ];
  167. fn program(words: &[u32]) -> Program {
  168. ir::build(
  169. &words
  170. .iter()
  171. .flat_map(|w| w.to_le_bytes())
  172. .collect::<Vec<_>>(),
  173. false,
  174. 4,
  175. )
  176. .unwrap()
  177. }
  178. #[test]
  179. fn only_the_buffer_load_reaches_the_numeric_read() {
  180. let p = program(&WORDS);
  181. let st = structure::structure(&p).unwrap();
  182. let edges = constant_edges(&p, &st);
  183. assert_eq!(edges, [(0, 2, 4)]);
  184. let p = ir::thread_edges(&p, &edges).unwrap();
  185. let load = &p.blocks[1].insts[0];
  186. assert_eq!(p.blocks[3].insts[0].read(Reg::S(8)), load.write(Reg::S(8)));
  187. assert_eq!(
  188. p.blocks[0].exit,
  189. Exit::Branch {
  190. taken: 6,
  191. not_taken: 1
  192. }
  193. );
  194. assert_eq!(p.blocks[6].exit, Exit::Jump(4));
  195. assert_eq!(p.blocks[6].insts.len(), p.blocks[2].insts.len());
  196. }
  197. #[test]
  198. fn leaves_unknown_flags_and_divergent_forks_alone() {
  199. let mut words = WORDS;
  200. words[5] = 0x7e020202; // v1 = s2
  201. words[10] = 0x7e020203; // v1 = s3
  202. let p = program(&words);
  203. assert!(constant_edges(&p, &structure::structure(&p).unwrap()).is_empty());
  204. let mut words = WORDS;
  205. words[6] = 0x7d840080; // compare 0 with lane-dependent v0
  206. words[7] = 0xbf870003; // branch on VCC
  207. let p = program(&words);
  208. assert!(constant_edges(&p, &structure::structure(&p).unwrap()).is_empty());
  209. }
  210. }