ir.rs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. //! One-to-one SSA form of a native program (decision 0003, step 1).
  2. //!
  3. //! Every machine instruction becomes one [`Inst`], except scheduling-only
  4. //! ones (`s_nop`, `s_waitcnt*`, `s_inst_prefetch`...), which are dropped.
  5. //! Each register dword is a variable: a read names the [`Value`] it sees, a
  6. //! write defines a new one, and [`Phi`]s merge values where control flow
  7. //! joins. Nothing is raised: an instruction keeps its opcode and decoded
  8. //! fields, so its exact semantics stay with it.
  9. //!
  10. //! Implicit operands are explicit: SCC, M0, and EXEC, which every vector
  11. //! instruction reads. A write to a VGPR also reads the register's old value,
  12. //! because lanes disabled in EXEC keep it.
  13. //!
  14. //! M0-relative VGPR access (`v_movrels/d/sd_b32`, `v_swaprel_b32`) names its
  15. //! operand's whole possible range: from the encoded register up to the
  16. //! program's VGPR count, all read (and all written, for a destination).
  17. use crate::ShaderError;
  18. use crate::gfx10::{self, Fields, Flow, Instruction, Operand};
  19. /// One register dword. Scalar codes as in [`Operand::Scalar`]: 0-105 SGPRs,
  20. /// 106/107 VCC, 108-123 trap temporaries, 124 M0, 126/127 EXEC.
  21. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
  22. pub enum Reg {
  23. S(u8),
  24. Scc,
  25. V(u8),
  26. }
  27. pub const VCC: u8 = 106;
  28. pub const M0: u8 = 124;
  29. pub const EXEC: u8 = 126;
  30. /// An SSA value: the content of one register dword (SCC: one bit).
  31. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
  32. pub struct Value(pub u32);
  33. #[derive(Debug, Clone, PartialEq, Eq)]
  34. pub struct Program {
  35. pub wave64: bool,
  36. /// VGPRs v0 up to this exist; bounds M0-relative access.
  37. pub vgprs: u16,
  38. /// In code order, then copies made to give every loop one entry; block 0
  39. /// is the entry.
  40. pub blocks: Vec<Block>,
  41. /// Registers read before any write, with their value on entry: what the
  42. /// hardware or a called fetch routine set up (user SGPRs, system values,
  43. /// vertex inputs).
  44. pub inputs: Vec<(Reg, Value)>,
  45. }
  46. #[derive(Debug, Clone, PartialEq, Eq)]
  47. pub struct Block {
  48. /// Byte offset of the block's first machine instruction (shared by a
  49. /// block and its copies).
  50. pub offset: usize,
  51. pub preds: Vec<usize>,
  52. pub phis: Vec<Phi>,
  53. pub insts: Vec<Inst>,
  54. pub exit: Exit,
  55. }
  56. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  57. pub enum Exit {
  58. Jump(usize),
  59. /// `s_cbranch_*`, the block's last instruction.
  60. Branch {
  61. taken: usize,
  62. not_taken: usize,
  63. },
  64. /// `s_endpgm` and its variants.
  65. End,
  66. /// `s_setpc_b64` to an address held in registers, e.g. the handover to
  67. /// the next half of a merged hardware stage.
  68. Indirect,
  69. }
  70. impl Exit {
  71. pub fn successors(&self) -> Vec<usize> {
  72. match *self {
  73. Exit::Jump(b) => vec![b],
  74. Exit::Branch { taken, not_taken } => vec![taken, not_taken],
  75. Exit::End | Exit::Indirect => vec![],
  76. }
  77. }
  78. }
  79. #[derive(Debug, Clone, PartialEq, Eq)]
  80. pub struct Phi {
  81. pub reg: Reg,
  82. pub value: Value,
  83. /// One per predecessor, in [`Block::preds`] order.
  84. pub args: Vec<Value>,
  85. }
  86. #[derive(Debug, Clone, PartialEq, Eq)]
  87. pub struct Inst {
  88. pub machine: Instruction,
  89. pub fields: Fields,
  90. /// Every register dword read, with the value it holds.
  91. pub reads: Vec<(Reg, Value)>,
  92. /// Every register dword written, with the value it receives.
  93. pub writes: Vec<(Reg, Value)>,
  94. }
  95. impl Inst {
  96. pub fn name(&self) -> &'static str {
  97. self.machine.name().unwrap_or("")
  98. }
  99. /// The value `reg` holds when this instruction reads it.
  100. pub fn read(&self, reg: Reg) -> Option<Value> {
  101. self.reads.iter().find(|r| r.0 == reg).map(|r| r.1)
  102. }
  103. /// The value this instruction writes to `reg`.
  104. pub fn write(&self, reg: Reg) -> Option<Value> {
  105. self.writes.iter().find(|w| w.0 == reg).map(|w| w.1)
  106. }
  107. }
  108. /// Decodes `code` and builds its SSA form; `vgprs` is the program's VGPR
  109. /// count. Fails on instructions the IR cannot express yet
  110. /// ([`ShaderError::Unsupported`]).
  111. pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderError> {
  112. let list = gfx10::decode(code)?;
  113. let lanes = 1 + u8::from(wave64);
  114. let isa = |offset, reason| ShaderError::Isa { offset, reason };
  115. let mut flows = Vec::with_capacity(list.len());
  116. let mut leaders = vec![0];
  117. for (i, inst) in list.iter().enumerate() {
  118. let flow = gfx10::control(inst, code.len(), |at| {
  119. list[..list.partition_point(|i| i.offset < at)].last()
  120. })?;
  121. if let Flow::Jump(t) | Flow::Branch(t) = flow {
  122. leaders.push(t);
  123. }
  124. if flow != Flow::Next
  125. && let Some(next) = list.get(i + 1)
  126. {
  127. leaders.push(next.offset);
  128. }
  129. flows.push(flow);
  130. }
  131. leaders.sort_unstable();
  132. leaders.dedup();
  133. let block_at = |offset: usize| {
  134. leaders
  135. .binary_search(&offset)
  136. .map_err(|_| isa(offset, "jump into a block"))
  137. };
  138. let mut blocks: Vec<Block> = leaders
  139. .iter()
  140. .map(|&offset| Block {
  141. offset,
  142. preds: Vec::new(),
  143. phis: Vec::new(),
  144. insts: Vec::new(),
  145. exit: Exit::End,
  146. })
  147. .collect();
  148. let next_offsets: Vec<Option<usize>> = (0..list.len())
  149. .map(|i| list.get(i + 1).map(|n| n.offset))
  150. .collect();
  151. for ((machine, flow), next) in list.into_iter().zip(flows).zip(next_offsets) {
  152. let b = leaders.partition_point(|&l| l <= machine.offset) - 1;
  153. let name = machine.name().ok_or(ShaderError::Unsupported {
  154. offset: machine.offset,
  155. what: "unknown opcode",
  156. })?;
  157. let fields = machine.fields(wave64);
  158. let fallthrough = || block_at(next.ok_or(isa(machine.offset, "falls off the code"))?);
  159. let ends = flow != Flow::Next || next.is_none_or(|n| leaders.binary_search(&n).is_ok());
  160. if ends {
  161. blocks[b].exit = match flow {
  162. Flow::Next => Exit::Jump(fallthrough()?),
  163. Flow::Jump(t) => Exit::Jump(block_at(t)?),
  164. Flow::Branch(t) => Exit::Branch {
  165. taken: block_at(t)?,
  166. not_taken: fallthrough()?,
  167. },
  168. Flow::Stop if name == "s_setpc_b64" => Exit::Indirect,
  169. Flow::Stop => Exit::End,
  170. };
  171. }
  172. if let Some((reads, writes)) = effects(&machine, &fields, name, lanes, vgprs)? {
  173. let unset = |regs: Vec<Reg>| regs.into_iter().map(|r| (r, NONE)).collect();
  174. blocks[b].insts.push(Inst {
  175. machine,
  176. fields,
  177. reads: unset(reads),
  178. writes: unset(writes),
  179. });
  180. }
  181. }
  182. link(&mut blocks);
  183. if !blocks[0].preds.is_empty() {
  184. return Err(ShaderError::Unsupported {
  185. offset: 0,
  186. what: "a branch to the program entry",
  187. });
  188. }
  189. split_irreducible(&mut blocks)?;
  190. let order = reverse_postorder(&blocks);
  191. let (live_in, live_out) = liveness(&blocks, &order);
  192. let mut values = 0u32;
  193. let mut new_value = || {
  194. values += 1;
  195. Value(values - 1)
  196. };
  197. let mut inputs = Vec::new();
  198. let mut outs: Vec<Vec<(Reg, Value)>> = vec![Vec::new(); blocks.len()];
  199. let mut current = [NONE; REGS];
  200. for &b in &order {
  201. current.fill(NONE);
  202. let block = &mut blocks[b];
  203. for reg in members(&live_in[b]) {
  204. current[index(reg)] = match block.preds[..] {
  205. [] => {
  206. let v = new_value();
  207. inputs.push((reg, v));
  208. v
  209. }
  210. // A single predecessor comes earlier in reverse postorder.
  211. [p] => lookup(&outs[p], reg),
  212. _ => {
  213. let value = new_value();
  214. block.phis.push(Phi {
  215. reg,
  216. value,
  217. args: Vec::new(),
  218. });
  219. value
  220. }
  221. };
  222. }
  223. for inst in &mut block.insts {
  224. for (reg, v) in &mut inst.reads {
  225. *v = current[index(*reg)];
  226. debug_assert_ne!(*v, NONE, "{reg:?} read at {:#x}", inst.machine.offset);
  227. }
  228. for (reg, v) in &mut inst.writes {
  229. *v = new_value();
  230. current[index(*reg)] = *v;
  231. }
  232. }
  233. outs[b] = members(&live_out[b])
  234. .map(|reg| (reg, current[index(reg)]))
  235. .collect();
  236. }
  237. for block in &mut blocks {
  238. for phi in &mut block.phis {
  239. phi.args = block
  240. .preds
  241. .iter()
  242. .map(|&p| lookup(&outs[p], phi.reg))
  243. .collect();
  244. debug_assert!(!phi.args.contains(&NONE), "{phi:?}");
  245. }
  246. }
  247. remove_trivial_phis(&mut blocks, values);
  248. Ok(Program {
  249. wave64,
  250. vgprs,
  251. blocks,
  252. inputs,
  253. })
  254. }
  255. /// Placeholder before renaming.
  256. const NONE: Value = Value(u32::MAX);
  257. /// SGPR codes 0-127, SCC, VGPRs 0-255.
  258. const REGS: usize = 128 + 1 + 256;
  259. type RegSet = [u64; REGS.div_ceil(64)];
  260. fn index(reg: Reg) -> usize {
  261. match reg {
  262. Reg::S(c) => usize::from(c),
  263. Reg::Scc => 128,
  264. Reg::V(r) => 129 + usize::from(r),
  265. }
  266. }
  267. fn reg_at(i: usize) -> Reg {
  268. match i {
  269. 0..128 => Reg::S(i as u8),
  270. 128 => Reg::Scc,
  271. _ => Reg::V((i - 129) as u8),
  272. }
  273. }
  274. fn insert(set: &mut RegSet, reg: Reg) {
  275. let i = index(reg);
  276. set[i / 64] |= 1 << (i % 64);
  277. }
  278. fn contains(set: &RegSet, reg: Reg) -> bool {
  279. let i = index(reg);
  280. set[i / 64] >> (i % 64) & 1 != 0
  281. }
  282. /// In [`Reg`] order, which is also index order.
  283. fn members(set: &RegSet) -> impl Iterator<Item = Reg> + '_ {
  284. (0..REGS)
  285. .filter(|&i| set[i / 64] >> (i % 64) & 1 != 0)
  286. .map(reg_at)
  287. }
  288. /// `outs` is sorted by register, and holds every register live out.
  289. fn lookup(outs: &[(Reg, Value)], reg: Reg) -> Value {
  290. outs.binary_search_by_key(&reg, |&(r, _)| r)
  291. .map_or(NONE, |i| outs[i].1)
  292. }
  293. pub(crate) fn reverse_postorder(blocks: &[Block]) -> Vec<usize> {
  294. let mut seen = vec![false; blocks.len()];
  295. let mut post = Vec::with_capacity(blocks.len());
  296. let mut stack = vec![(0, 0)];
  297. seen[0] = true;
  298. while let Some(top) = stack.last_mut() {
  299. let (b, i) = *top;
  300. top.1 += 1;
  301. match blocks[b].exit.successors().get(i) {
  302. Some(&s) if !seen[s] => {
  303. seen[s] = true;
  304. stack.push((s, 0));
  305. }
  306. Some(_) => {}
  307. None => {
  308. post.push(b);
  309. stack.pop();
  310. }
  311. }
  312. }
  313. post.reverse();
  314. post
  315. }
  316. /// Recomputes every block's predecessors from the exits.
  317. fn link(blocks: &mut [Block]) {
  318. for block in blocks.iter_mut() {
  319. block.preds.clear();
  320. }
  321. for b in 0..blocks.len() {
  322. for s in blocks[b].exit.successors() {
  323. blocks[s].preds.push(b);
  324. }
  325. }
  326. }
  327. /// An edge to an earlier block in reverse postorder whose target does not
  328. /// dominate its source, if any: there the control flow is irreducible.
  329. /// `index` is each block's position in `order`.
  330. pub(crate) fn irreducible_edge(
  331. blocks: &[Block],
  332. order: &[usize],
  333. index: &[usize],
  334. ) -> Option<(usize, usize)> {
  335. let &entry = order.first()?;
  336. let idom = idoms(blocks, order, index);
  337. for &b in order {
  338. for s in blocks[b].exit.successors() {
  339. if index[s] > index[b] {
  340. continue;
  341. }
  342. let mut d = b;
  343. while d != s && d != entry {
  344. d = idom[d];
  345. }
  346. if d != s {
  347. return Some((b, s));
  348. }
  349. }
  350. }
  351. None
  352. }
  353. /// Each block's immediate dominator (the entry's is itself, unreachable
  354. /// blocks' `usize::MAX`); `order` is reverse postorder, `index` each
  355. /// block's position in it.
  356. pub(crate) fn idoms(blocks: &[Block], order: &[usize], index: &[usize]) -> Vec<usize> {
  357. let mut idom = vec![usize::MAX; blocks.len()];
  358. let Some(&entry) = order.first() else {
  359. return idom;
  360. };
  361. idom[entry] = entry;
  362. let intersect = |idom: &[usize], mut a: usize, mut b: usize| {
  363. while a != b {
  364. while index[a] > index[b] {
  365. a = idom[a];
  366. }
  367. while index[b] > index[a] {
  368. b = idom[b];
  369. }
  370. }
  371. a
  372. };
  373. let mut changed = true;
  374. while changed {
  375. changed = false;
  376. for &b in &order[1..] {
  377. let mut new = usize::MAX;
  378. for &q in blocks[b].preds.iter().filter(|&&q| idom[q] != usize::MAX) {
  379. new = if new == usize::MAX {
  380. q
  381. } else {
  382. intersect(&idom, q, new)
  383. };
  384. }
  385. if idom[b] != new {
  386. idom[b] = new;
  387. changed = true;
  388. }
  389. }
  390. }
  391. idom
  392. }
  393. /// Node splitting, before SSA. While a loop is entered at several blocks
  394. /// (a compiler-rotated loop whose peeled first test jumps into its body),
  395. /// the entry first in reverse postorder stays the header, and another
  396. /// entry's outside predecessors move to a copy of everything that entry
  397. /// reaches in the loop before the header. The copies run the same
  398. /// instructions, so behaviour is unchanged.
  399. fn split_irreducible(blocks: &mut Vec<Block>) -> Result<(), ShaderError> {
  400. let limit = 4 * blocks.len() + 64;
  401. loop {
  402. let order = reverse_postorder(blocks);
  403. let mut index = vec![usize::MAX; blocks.len()];
  404. for (i, &b) in order.iter().enumerate() {
  405. index[b] = i;
  406. }
  407. let Some((from, _)) = irreducible_edge(blocks, &order, &index) else {
  408. return Ok(());
  409. };
  410. let found = multi_entry_loop(blocks, &vec![true; blocks.len()]);
  411. let Some((region, mut entries)) = found.filter(|_| blocks.len() < limit) else {
  412. return Err(ShaderError::Unsupported {
  413. offset: blocks[from].offset,
  414. what: "irreducible control flow",
  415. });
  416. };
  417. entries.sort_by_key(|&e| index[e]);
  418. let (header, entry) = (entries[0], entries[1]);
  419. // What `entry` reaches in the loop before the header, and its copies.
  420. let mut copy = vec![usize::MAX; blocks.len()];
  421. let mut copied = Vec::new();
  422. let mut stack = vec![entry];
  423. while let Some(b) = stack.pop() {
  424. if copy[b] != usize::MAX {
  425. continue;
  426. }
  427. copy[b] = blocks.len() + copied.len();
  428. copied.push(b);
  429. for s in blocks[b].exit.successors() {
  430. if region[s] && s != header {
  431. stack.push(s);
  432. }
  433. }
  434. }
  435. let retarget = |exit: &mut Exit, to: &dyn Fn(usize) -> usize| match exit {
  436. Exit::Jump(s) => *s = to(*s),
  437. Exit::Branch { taken, not_taken } => {
  438. *taken = to(*taken);
  439. *not_taken = to(*not_taken);
  440. }
  441. Exit::End | Exit::Indirect => {}
  442. };
  443. for &b in &copied {
  444. let mut block = blocks[b].clone();
  445. retarget(&mut block.exit, &|s| {
  446. if copy[s] == usize::MAX { s } else { copy[s] }
  447. });
  448. blocks.push(block);
  449. }
  450. let outside: Vec<usize> = blocks[entry]
  451. .preds
  452. .iter()
  453. .copied()
  454. .filter(|&p| !region[p])
  455. .collect();
  456. for p in outside {
  457. retarget(&mut blocks[p].exit, &|s| {
  458. if s == entry { copy[entry] } else { s }
  459. });
  460. }
  461. link(blocks);
  462. }
  463. }
  464. /// A loop among the `inside` blocks entered at more than one block, with
  465. /// its entries. Loops nested in a single-entry loop are searched with its
  466. /// header removed, so one is found whenever the control flow is irreducible.
  467. fn multi_entry_loop(blocks: &[Block], inside: &[bool]) -> Option<(Vec<bool>, Vec<usize>)> {
  468. let reach = |from: usize, forward: bool| {
  469. let mut seen = vec![false; blocks.len()];
  470. let mut stack = vec![from];
  471. while let Some(b) = stack.pop() {
  472. let next = if forward {
  473. blocks[b].exit.successors()
  474. } else {
  475. blocks[b].preds.clone()
  476. };
  477. for n in next {
  478. if inside[n] && !seen[n] {
  479. seen[n] = true;
  480. stack.push(n);
  481. }
  482. }
  483. }
  484. seen
  485. };
  486. let mut done = vec![false; blocks.len()];
  487. for v in (0..blocks.len()).filter(|&v| inside[v]) {
  488. if done[v] {
  489. continue;
  490. }
  491. // Blocks on a cycle through `v`; `v` itself only if there is one.
  492. let (ahead, behind) = (reach(v, true), reach(v, false));
  493. let region: Vec<bool> = ahead.iter().zip(&behind).map(|(a, b)| a & b).collect();
  494. if !region[v] {
  495. continue;
  496. }
  497. let members = (0..blocks.len()).filter(|&b| region[b]);
  498. for b in members.clone() {
  499. done[b] = true;
  500. }
  501. let entries: Vec<usize> = members
  502. .filter(|&b| blocks[b].preds.iter().any(|&p| !region[p]))
  503. .collect();
  504. match entries[..] {
  505. [] => {}
  506. [header] => {
  507. let mut nested = region;
  508. nested[header] = false;
  509. if let Some(found) = multi_entry_loop(blocks, &nested) {
  510. return Some(found);
  511. }
  512. }
  513. _ => return Some((region, entries)),
  514. }
  515. }
  516. None
  517. }
  518. /// Registers live into and out of each block.
  519. fn liveness(blocks: &[Block], order: &[usize]) -> (Vec<RegSet>, Vec<RegSet>) {
  520. let empty = [0; REGS.div_ceil(64)];
  521. let mut uses = vec![empty; blocks.len()];
  522. let mut defs = vec![empty; blocks.len()];
  523. for (b, block) in blocks.iter().enumerate() {
  524. for inst in &block.insts {
  525. for &(reg, _) in &inst.reads {
  526. if !contains(&defs[b], reg) {
  527. insert(&mut uses[b], reg);
  528. }
  529. }
  530. for &(reg, _) in &inst.writes {
  531. insert(&mut defs[b], reg);
  532. }
  533. }
  534. }
  535. let mut live_in = vec![empty; blocks.len()];
  536. let mut live_out = vec![empty; blocks.len()];
  537. let mut changed = true;
  538. while changed {
  539. changed = false;
  540. for &b in order.iter().rev() {
  541. let mut out = empty;
  542. for s in blocks[b].exit.successors() {
  543. for (o, i) in out.iter_mut().zip(&live_in[s]) {
  544. *o |= i;
  545. }
  546. }
  547. let mut inn = empty;
  548. for w in 0..inn.len() {
  549. inn[w] = uses[b][w] | out[w] & !defs[b][w];
  550. }
  551. if inn != live_in[b] || out != live_out[b] {
  552. (live_in[b], live_out[b]) = (inn, out);
  553. changed = true;
  554. }
  555. }
  556. }
  557. (live_in, live_out)
  558. }
  559. /// Phis are placed for every live register at every join; those whose
  560. /// arguments are all one value (or the phi itself) are replaced by it.
  561. fn remove_trivial_phis(blocks: &mut [Block], values: u32) {
  562. let mut replaced: Vec<Value> = (0..values).map(Value).collect();
  563. let find = |replaced: &[Value], mut v: Value| {
  564. while replaced[v.0 as usize] != v {
  565. v = replaced[v.0 as usize];
  566. }
  567. v
  568. };
  569. let mut changed = true;
  570. while changed {
  571. changed = false;
  572. for block in blocks.iter_mut() {
  573. block.phis.retain(|phi| {
  574. let mut only = None;
  575. for &a in &phi.args {
  576. let a = find(&replaced, a);
  577. if a == phi.value || Some(a) == only {
  578. continue;
  579. }
  580. if only.is_some() {
  581. return true;
  582. }
  583. only = Some(a);
  584. }
  585. let Some(v) = only else { return true };
  586. replaced[phi.value.0 as usize] = v;
  587. changed = true;
  588. false
  589. });
  590. }
  591. }
  592. for block in blocks {
  593. for phi in &mut block.phis {
  594. for a in &mut phi.args {
  595. *a = find(&replaced, *a);
  596. }
  597. }
  598. for inst in &mut block.insts {
  599. for (_, v) in &mut inst.reads {
  600. *v = find(&replaced, *v);
  601. }
  602. }
  603. }
  604. }
  605. /// Scheduling hints, performance counters and tracing: no effect on results.
  606. const DROPPED: &[&str] = &[
  607. "s_nop",
  608. "s_waitcnt",
  609. "s_waitcnt_vscnt",
  610. "s_waitcnt_vmcnt",
  611. "s_waitcnt_expcnt",
  612. "s_waitcnt_lgkmcnt",
  613. "s_waitcnt_depctr",
  614. "s_wait_idle",
  615. "s_inst_prefetch",
  616. "s_clause",
  617. "s_setprio",
  618. "s_sleep",
  619. "s_ttracedata",
  620. "s_ttracedata_imm",
  621. "s_incperflevel",
  622. "s_decperflevel",
  623. "v_nop",
  624. "v_pipeflush",
  625. "v_clrexcp",
  626. ];
  627. /// Registers read, registers written.
  628. type Effects = (Vec<Reg>, Vec<Reg>);
  629. /// Registers an instruction reads and writes, one per dword, or `None` if
  630. /// the IR drops it.
  631. fn effects(
  632. inst: &Instruction,
  633. fields: &Fields,
  634. name: &'static str,
  635. lanes: u8,
  636. vgprs: u16,
  637. ) -> Result<Option<Effects>, ShaderError> {
  638. if DROPPED.contains(&name) {
  639. return Ok(None);
  640. }
  641. let unsupported = || ShaderError::Unsupported {
  642. offset: inst.offset,
  643. what: name,
  644. };
  645. let mask = |code: u8| (0..lanes).map(move |i| Reg::S(code + i));
  646. let (mut r, mut w) = (Vec::new(), Vec::new());
  647. let regs = |op: &Operand, out: &mut Vec<Reg>| {
  648. add_regs(op, lanes, out).map_err(|_| ShaderError::Isa {
  649. offset: inst.offset,
  650. reason: "register range out of bounds",
  651. })
  652. };
  653. let vector = !matches!(
  654. fields,
  655. Fields::Sop { .. } | Fields::Sopp { .. } | Fields::Smem { .. }
  656. );
  657. match fields {
  658. Fields::Sop { dst, src, .. } => {
  659. if name.starts_with("s_movrel")
  660. || name.starts_with("s_subvector_loop")
  661. || matches!(name, "s_call_b64" | "s_rfe_b64")
  662. {
  663. return Err(unsupported());
  664. }
  665. for s in src {
  666. regs(s, &mut r)?;
  667. }
  668. if let Some(d) = dst {
  669. regs(d, &mut w)?;
  670. // These change (or may keep) the destination's old value.
  671. if name.starts_with("s_bitset")
  672. || name.starts_with("s_cmov")
  673. || matches!(name, "s_addk_i32" | "s_mulk_i32")
  674. {
  675. regs(d, &mut r)?;
  676. }
  677. }
  678. if matches!(name, "s_addc_u32" | "s_subb_u32" | "s_cmovk_i32")
  679. || name.starts_with("s_cselect_")
  680. || name.starts_with("s_cmov_")
  681. {
  682. r.push(Reg::Scc);
  683. }
  684. if name.contains("saveexec") || name.contains("wrexec") {
  685. r.extend(mask(EXEC));
  686. w.extend(mask(EXEC));
  687. }
  688. if writes_scc(inst.encoding, name) {
  689. w.push(Reg::Scc);
  690. }
  691. }
  692. Fields::Sopp { .. } => match name {
  693. "s_cbranch_scc0" | "s_cbranch_scc1" => r.push(Reg::Scc),
  694. "s_cbranch_vccz" | "s_cbranch_vccnz" => r.extend(mask(VCC)),
  695. "s_cbranch_execz" | "s_cbranch_execnz" => r.extend(mask(EXEC)),
  696. "s_sendmsg" | "s_sendmsghalt" => r.push(Reg::S(M0)),
  697. "s_endpgm"
  698. | "s_endpgm_saved"
  699. | "s_endpgm_ordered_ps_done"
  700. | "s_code_end"
  701. | "s_branch"
  702. | "s_barrier"
  703. | "s_icache_inv"
  704. | "s_wakeup"
  705. | "s_round_mode"
  706. | "s_denorm_mode" => {}
  707. _ => return Err(unsupported()),
  708. },
  709. Fields::Smem {
  710. data,
  711. base,
  712. soffset,
  713. ..
  714. } => match name {
  715. "s_memtime" | "s_memrealtime" | "s_get_waveid_in_workgroup" => {
  716. regs(data.as_ref().ok_or_else(unsupported)?, &mut w)?;
  717. }
  718. "s_gl1_inv" | "s_dcache_inv" | "s_dcache_wb" => {}
  719. _ if name.contains("_load_") || name.contains("_store_") => {
  720. regs(base, &mut r)?;
  721. regs(soffset, &mut r)?;
  722. let data = data.as_ref().ok_or_else(unsupported)?;
  723. regs(
  724. data,
  725. if name.contains("_load_") {
  726. &mut w
  727. } else {
  728. &mut r
  729. },
  730. )?;
  731. }
  732. _ => return Err(unsupported()),
  733. },
  734. Fields::Valu(v) => {
  735. let (src_indexed, dst_indexed) = match name {
  736. "v_movrels_b32" => (true, false),
  737. "v_movreld_b32" => (false, true),
  738. "v_movrelsd_b32" | "v_movrelsd_2_b32" | "v_swaprel_b32" => (true, true),
  739. _ => (false, false),
  740. };
  741. // v[reg + M0] for any M0 that stays inside the program's VGPRs.
  742. let indexed = |op: &Operand, out: &mut Vec<Reg>| match *op {
  743. Operand::Vector { reg, .. } if u16::from(reg) < vgprs => {
  744. out.extend((u16::from(reg)..vgprs).map(|r| Reg::V(r as u8)));
  745. Ok(())
  746. }
  747. _ => Err(ShaderError::Isa {
  748. offset: inst.offset,
  749. reason: "relative VGPR base outside the program's VGPRs",
  750. }),
  751. };
  752. for (i, s) in v.src.iter().enumerate() {
  753. if i == 0 && src_indexed {
  754. indexed(s, &mut r)?;
  755. } else {
  756. regs(s, &mut r)?;
  757. }
  758. }
  759. // GFX10 compares into EXEC write nothing else.
  760. if name.starts_with("v_cmpx") {
  761. w.extend(mask(EXEC));
  762. } else if let Some(d) = &v.dst {
  763. if dst_indexed {
  764. indexed(d, &mut w)?;
  765. } else {
  766. regs(d, &mut w)?;
  767. }
  768. }
  769. if let Some(c) = &v.carry {
  770. regs(c, &mut w)?;
  771. }
  772. match name {
  773. "v_swap_b32" => {
  774. regs(&v.src[0], &mut w)?;
  775. if let Some(d) = &v.dst {
  776. regs(d, &mut r)?;
  777. }
  778. }
  779. "v_swaprel_b32" => {
  780. indexed(&v.src[0], &mut w)?;
  781. if let Some(d) = &v.dst {
  782. indexed(d, &mut r)?;
  783. }
  784. }
  785. _ => {}
  786. }
  787. if name.starts_with("v_interp_") || src_indexed || dst_indexed {
  788. r.push(Reg::S(M0));
  789. }
  790. }
  791. Fields::Vintrp { dst, src, .. } => {
  792. regs(src, &mut r)?;
  793. r.push(Reg::S(M0));
  794. regs(dst, &mut w)?;
  795. }
  796. Fields::Ds {
  797. dst,
  798. addr,
  799. data,
  800. gds,
  801. ..
  802. } => {
  803. for o in addr.iter().chain(data) {
  804. regs(o, &mut r)?;
  805. }
  806. if let Some(d) = dst {
  807. regs(d, &mut w)?;
  808. }
  809. if *gds
  810. || name.starts_with("ds_gws")
  811. || name.contains("addtid")
  812. || matches!(name, "ds_ordered_count" | "ds_append" | "ds_consume")
  813. {
  814. r.push(Reg::S(M0));
  815. }
  816. }
  817. Fields::Buffer {
  818. data,
  819. addr,
  820. rsrc,
  821. soffset,
  822. offen,
  823. idxen,
  824. lds,
  825. cache,
  826. ..
  827. } => {
  828. if *offen || *idxen {
  829. regs(addr, &mut r)?;
  830. }
  831. regs(rsrc, &mut r)?;
  832. regs(soffset, &mut r)?;
  833. if *lds {
  834. r.push(Reg::S(M0));
  835. }
  836. if let Some(d) = data {
  837. if name.contains("_load_") {
  838. if !lds {
  839. regs(d, &mut w)?;
  840. }
  841. } else if name.contains("_store_") {
  842. regs(d, &mut r)?;
  843. } else if name.contains("_atomic_") {
  844. regs(d, &mut r)?;
  845. if cache.glc {
  846. regs(&atomic_result(d, name), &mut w)?;
  847. }
  848. } else {
  849. return Err(unsupported());
  850. }
  851. }
  852. }
  853. Fields::Image {
  854. data,
  855. addr,
  856. rsrc,
  857. sampler,
  858. cache,
  859. ..
  860. } => {
  861. for a in addr.iter().chain([rsrc]).chain(sampler) {
  862. regs(a, &mut r)?;
  863. }
  864. if name.contains("_store") {
  865. regs(data, &mut r)?;
  866. } else if name.contains("_atomic_") {
  867. regs(data, &mut r)?;
  868. if cache.glc {
  869. regs(&atomic_result(data, name), &mut w)?;
  870. }
  871. } else {
  872. regs(data, &mut w)?;
  873. }
  874. }
  875. Fields::Flat {
  876. dst,
  877. addr,
  878. data,
  879. saddr,
  880. ..
  881. } => {
  882. for o in [addr, data, saddr].into_iter().flatten() {
  883. regs(o, &mut r)?;
  884. }
  885. if let Some(d) = dst {
  886. regs(d, &mut w)?;
  887. }
  888. }
  889. Fields::Exp { src, .. } => {
  890. for s in src.iter().flatten() {
  891. regs(s, &mut r)?;
  892. }
  893. }
  894. }
  895. if vector {
  896. r.extend(mask(EXEC));
  897. // Lanes disabled in EXEC keep the old value.
  898. r.extend(w.iter().filter(|w| matches!(w, Reg::V(_))));
  899. }
  900. let mut seen = Vec::with_capacity(r.len());
  901. r.retain(|reg| {
  902. let new = !seen.contains(reg);
  903. seen.push(*reg);
  904. new
  905. });
  906. Ok(Some((r, w)))
  907. }
  908. /// Scalar ALU opcodes that set SCC (carry, overflow, comparison, or "result
  909. /// is not zero").
  910. fn writes_scc(encoding: gfx10::Encoding, name: &str) -> bool {
  911. use gfx10::Encoding::*;
  912. match encoding {
  913. Sopc => true,
  914. Sopk => name.starts_with("s_cmpk_") || name == "s_addk_i32",
  915. _ => {
  916. let stem = name.split('_').nth(1).unwrap_or("");
  917. name.contains("saveexec")
  918. || name.contains("wrexec")
  919. || matches!(
  920. stem,
  921. "add"
  922. | "sub"
  923. | "addc"
  924. | "subb"
  925. | "min"
  926. | "max"
  927. | "and"
  928. | "or"
  929. | "xor"
  930. | "andn2"
  931. | "orn2"
  932. | "nand"
  933. | "nor"
  934. | "xnor"
  935. | "lshl"
  936. | "lshr"
  937. | "ashr"
  938. | "bfe"
  939. | "absdiff"
  940. | "lshl1"
  941. | "lshl2"
  942. | "lshl3"
  943. | "lshl4"
  944. | "not"
  945. | "wqm"
  946. | "bcnt0"
  947. | "bcnt1"
  948. | "quadmask"
  949. | "abs"
  950. )
  951. }
  952. }
  953. }
  954. /// What an atomic with `glc` returns: the old value (for compare-and-swap,
  955. /// half the data operand).
  956. fn atomic_result(data: &Operand, name: &str) -> Operand {
  957. match *data {
  958. Operand::Vector { reg, dwords } if name.contains("cmpswap") => Operand::Vector {
  959. reg,
  960. dwords: dwords / 2,
  961. },
  962. op => op,
  963. }
  964. }
  965. /// Appends the register dwords an operand names; reading `vccz`, `execz`,
  966. /// `scc` or `lds_direct` reads the register behind it.
  967. fn add_regs(op: &Operand, lanes: u8, out: &mut Vec<Reg>) -> Result<(), ()> {
  968. match *op {
  969. Operand::Scalar { code, .. } if code == gfx10::NULL => {}
  970. Operand::Scalar { code, dwords } => {
  971. let end = u16::from(code) + u16::from(dwords);
  972. if end > 128 {
  973. return Err(());
  974. }
  975. out.extend((code..end as u8).map(Reg::S));
  976. }
  977. Operand::Vector { reg, dwords } => {
  978. if u16::from(reg) + u16::from(dwords) > 256 {
  979. return Err(());
  980. }
  981. out.extend((0..dwords).map(|i| Reg::V(reg + i)));
  982. }
  983. Operand::Const(251) => out.extend((0..lanes).map(|i| Reg::S(VCC + i))),
  984. Operand::Const(252) => out.extend((0..lanes).map(|i| Reg::S(EXEC + i))),
  985. Operand::Const(253) => out.push(Reg::Scc),
  986. Operand::Const(254) => out.push(Reg::S(M0)),
  987. Operand::Const(_) | Operand::Literal(_) | Operand::Attr { .. } => {}
  988. }
  989. Ok(())
  990. }
  991. #[cfg(test)]
  992. mod tests {
  993. use super::*;
  994. const S_ENDPGM: u32 = 0xBF81_0000;
  995. fn build_words(words: &[u32], wave64: bool) -> Program {
  996. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  997. build(&code, wave64, 256).unwrap()
  998. }
  999. fn input(p: &Program, reg: Reg) -> Value {
  1000. p.inputs.iter().find(|i| i.0 == reg).expect("input").1
  1001. }
  1002. #[test]
  1003. fn joins_get_phis_only_where_values_differ() {
  1004. let code = [
  1005. 0xBF06_0100, // s_cmp_eq_u32 s0, s1
  1006. 0xBF85_0001, // s_cbranch_scc1 -> 12
  1007. 0xBE82_0380, // s_mov_b32 s2, 0
  1008. 0x7E00_0202, // 12: v_mov_b32 v0, s2
  1009. 0x7E02_0200, // v_mov_b32 v1, s0
  1010. S_ENDPGM,
  1011. ];
  1012. for wave64 in [false, true] {
  1013. let p = build_words(&code, wave64);
  1014. let [b0, b1, b2] = &p.blocks[..] else {
  1015. panic!("{:?}", p.blocks)
  1016. };
  1017. assert_eq!(
  1018. b0.exit,
  1019. Exit::Branch {
  1020. taken: 2,
  1021. not_taken: 1
  1022. }
  1023. );
  1024. assert_eq!(b1.exit, Exit::Jump(2));
  1025. assert_eq!(b2.preds, [0, 1]);
  1026. assert_eq!(b0.insts[1].read(Reg::Scc), b0.insts[0].write(Reg::Scc));
  1027. // s2 differs per path; s0, EXEC, v0 and v1 do not.
  1028. let [phi] = &b2.phis[..] else {
  1029. panic!("{:?}", b2.phis)
  1030. };
  1031. assert_eq!(phi.reg, Reg::S(2));
  1032. assert_eq!(
  1033. phi.args,
  1034. [input(&p, Reg::S(2)), b1.insts[0].write(Reg::S(2)).unwrap()]
  1035. );
  1036. let [mov0, mov1, end] = &b2.insts[..] else {
  1037. panic!()
  1038. };
  1039. assert_eq!(mov0.read(Reg::S(2)), Some(phi.value));
  1040. assert_eq!(mov1.read(Reg::S(0)), Some(input(&p, Reg::S(0))));
  1041. // The old v1 is read: lanes outside EXEC keep it.
  1042. assert_eq!(mov1.read(Reg::V(1)), Some(input(&p, Reg::V(1))));
  1043. assert_eq!(mov1.read(Reg::S(EXEC)), Some(input(&p, Reg::S(EXEC))));
  1044. assert_eq!(mov1.read(Reg::S(EXEC + 1)).is_some(), wave64);
  1045. assert_eq!((end.name(), b2.exit), ("s_endpgm", Exit::End));
  1046. }
  1047. }
  1048. #[test]
  1049. fn in_place_scalar_ops_read_their_destination() {
  1050. let p = build_words(
  1051. &[
  1052. 0xBE8D_1D94, // s_bitset1_b32 s13, 20
  1053. 0xB78E_0010, // s_addk_i32 s14, 0x10
  1054. 0xBE8F_0380, // s_mov_b32 s15, 0
  1055. S_ENDPGM,
  1056. ],
  1057. false,
  1058. );
  1059. let [bitset, addk, mov, _] = &p.blocks[0].insts[..] else {
  1060. panic!("{:?}", p.blocks[0].insts)
  1061. };
  1062. assert_eq!(bitset.read(Reg::S(13)), Some(input(&p, Reg::S(13))));
  1063. assert_eq!(addk.read(Reg::S(14)), Some(input(&p, Reg::S(14))));
  1064. assert_eq!(mov.read(Reg::S(15)), None);
  1065. }
  1066. #[test]
  1067. fn loops_carry_values_through_phis() {
  1068. let p = build_words(
  1069. &[
  1070. 0xBE80_0380, // s_mov_b32 s0, 0
  1071. 0x8000_8100, // 4: s_add_u32 s0, s0, 1
  1072. 0xBF07_8400, // s_cmp_lg_u32 s0, 4
  1073. 0xBF85_FFFD, // s_cbranch_scc1 -> 4
  1074. S_ENDPGM,
  1075. ],
  1076. true,
  1077. );
  1078. assert!(p.inputs.is_empty(), "{:?}", p.inputs);
  1079. let [b0, b1, b2] = &p.blocks[..] else {
  1080. panic!()
  1081. };
  1082. assert_eq!(b1.preds, [0, 1]);
  1083. assert_eq!(
  1084. b1.exit,
  1085. Exit::Branch {
  1086. taken: 1,
  1087. not_taken: 2
  1088. }
  1089. );
  1090. let [phi] = &b1.phis[..] else {
  1091. panic!("{:?}", b1.phis)
  1092. };
  1093. let add = &b1.insts[0];
  1094. assert_eq!(phi.reg, Reg::S(0));
  1095. assert_eq!(
  1096. phi.args,
  1097. [
  1098. b0.insts[0].write(Reg::S(0)).unwrap(),
  1099. add.write(Reg::S(0)).unwrap()
  1100. ]
  1101. );
  1102. assert_eq!(add.read(Reg::S(0)), Some(phi.value));
  1103. assert_eq!(b1.insts[1].read(Reg::S(0)), add.write(Reg::S(0)));
  1104. assert_eq!(b2.insts[0].name(), "s_endpgm");
  1105. }
  1106. #[test]
  1107. fn drops_scheduling_and_follows_far_jumps() {
  1108. let p = build_words(
  1109. &[
  1110. 0xBF80_0000, // s_nop 0
  1111. 0xBE88_1F00, // s_getpc_b64 s[8:9]
  1112. 0x8008_FF08,
  1113. 20, // s_add_u32 s8, s8, 20 -> 8 + 20 = 28
  1114. 0x8209_8009, // s_addc_u32 s9, s9, 0
  1115. 0xBE80_2008, // s_setpc_b64 s[8:9]
  1116. 0xFFFF_FFFF, // not code
  1117. S_ENDPGM,
  1118. ],
  1119. false,
  1120. );
  1121. let names: Vec<_> = p.blocks[0].insts.iter().map(Inst::name).collect();
  1122. assert_eq!(
  1123. names,
  1124. ["s_getpc_b64", "s_add_u32", "s_addc_u32", "s_setpc_b64"]
  1125. );
  1126. assert_eq!(p.blocks[0].exit, Exit::Jump(1));
  1127. assert_eq!(p.blocks[1].offset, 28);
  1128. // s_addc_u32 reads the carry s_add_u32 left in SCC.
  1129. let i = &p.blocks[0].insts;
  1130. assert_eq!(i[2].read(Reg::Scc), i[1].write(Reg::Scc));
  1131. }
  1132. #[test]
  1133. fn reports_what_it_cannot_express() {
  1134. let code: Vec<u8> = [0xBE80_2E01_u32, S_ENDPGM] // s_movrels_b32 s0, s1
  1135. .iter()
  1136. .flat_map(|w| w.to_le_bytes())
  1137. .collect();
  1138. assert_eq!(
  1139. build(&code, false, 256),
  1140. Err(ShaderError::Unsupported {
  1141. offset: 0,
  1142. what: "s_movrels_b32"
  1143. })
  1144. );
  1145. }
  1146. #[test]
  1147. fn relative_vgpr_access_spans_up_to_the_vgpr_count() {
  1148. let code: Vec<u8> = [
  1149. 0x7E04_8501_u32, // v_movreld_b32 v2, v1: v[2 + m0] = v1
  1150. 0x7E00_8704, // v_movrels_b32 v0, v4: v0 = v[4 + m0]
  1151. S_ENDPGM,
  1152. ]
  1153. .iter()
  1154. .flat_map(|w| w.to_le_bytes())
  1155. .collect();
  1156. let p = build(&code, false, 6).unwrap();
  1157. let [movreld, movrels, _] = &p.blocks[0].insts[..] else {
  1158. panic!()
  1159. };
  1160. let vgprs = |regs: &[(Reg, Value)]| -> Vec<u8> {
  1161. regs.iter()
  1162. .filter_map(|r| match r.0 {
  1163. Reg::V(v) => Some(v),
  1164. _ => None,
  1165. })
  1166. .collect()
  1167. };
  1168. assert_eq!(vgprs(&movreld.writes), [2, 3, 4, 5]);
  1169. // v1 is the source; v2-v5 are read for the lanes and indices not written.
  1170. assert_eq!(vgprs(&movreld.reads), [1, 2, 3, 4, 5]);
  1171. assert!(movreld.read(Reg::S(M0)).is_some());
  1172. assert_eq!(vgprs(&movrels.writes), [0]);
  1173. assert_eq!(vgprs(&movrels.reads), [4, 5, 0]);
  1174. assert_eq!(movrels.read(Reg::V(4)), movreld.write(Reg::V(4)));
  1175. assert!(build(&code, false, 4).is_err(), "v4 is past 4 VGPRs");
  1176. }
  1177. }