io.rs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  1. //! I/O raising (decision 0003): what a program's input registers, its
  2. //! interpolation and its exports mean.
  3. //!
  4. //! Pixel shaders get the VGPRs `SPI_PS_INPUT_ADDR` enables, in a fixed
  5. //! order (barycentrics, then position, front face...). `v_interp_p1` and
  6. //! `v_interp_p2` (and their f16 forms) evaluate an attribute from a pair of
  7. //! barycentrics; `v_interp_mov` reads one vertex's value. After the 32-bit
  8. //! export patch ([`NativeProgram::patched_code`]) exports carry plain
  9. //! 32-bit values: `mrt<n>` is render target n, `mrtz` depth, stencil and
  10. //! sample mask, `null` nothing. A lane whose EXEC bit is clear at the
  11. //! export that ends the program (`done`) is discarded: that export's guard
  12. //! after structurisation.
  13. //!
  14. //! Vertex shaders that run as the hardware VS get the vertex id in v0, the
  15. //! primitive id in v2 and the instance id in v3; the fetch shader loads
  16. //! channel k of each attribute into its VGPR + k. `exp pos0` is the
  17. //! position, `exp param<n>` the output with parameter n.
  18. //!
  19. //! Attributes and outputs are named by their row: a register of the
  20. //! container's signature part.
  21. //!
  22. //! Compute programs get the thread id in the group in v0-v2 and the group
  23. //! id in the SGPRs after the user data, as `COMPUTE_PGM_RSRC2` enables them.
  24. //!
  25. //! Mesh programs run as one NGG stage. The program computes its thread
  26. //! index from the wave index (s3 bits 24-27) and the lane (`v_mbcnt`), and
  27. //! its group id from v5 of the first lane (`v_readfirstlane`: the group
  28. //! times the group size). Lane n exports vertex n (`exp pos`, `exp param`)
  29. //! and primitive n (`exp prim`: 10-bit vertex indices at bits 0, 10, 20,
  30. //! bit 31 culls); `param` entries with bit 7 are per-primitive outputs. One
  31. //! lane sends the output counts (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices |
  32. //! primitives << 12).
  33. use crate::ShaderError;
  34. use crate::gfx10::{Fields, Operand};
  35. use crate::ir::{Exit, Inst, Program, Reg, Value, operand_reads};
  36. use crate::native::{HwStage, NativeProgram, PsInput, StageIo, Usage};
  37. use crate::resource::Site;
  38. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  39. pub enum Input {
  40. VertexId,
  41. PrimitiveId,
  42. InstanceId,
  43. /// A vertex attribute the fetch shader loads.
  44. Attribute {
  45. row: u8,
  46. channel: u8,
  47. },
  48. /// `index` 0 is i, 1 is j (2 the pull model's w).
  49. Barycentric {
  50. kind: Barycentric,
  51. index: u8,
  52. },
  53. /// Pixel position channel (0-3: x, y, z, w).
  54. Position(u8),
  55. FrontFace,
  56. /// Sample id and other bits.
  57. Ancillary,
  58. SampleCoverage,
  59. FixedPosition,
  60. LineStipple,
  61. /// Compute: thread-group id component (an SGPR).
  62. GroupId(u8),
  63. /// Compute: thread id within the group, component (a VGPR).
  64. ThreadIdInGroup(u8),
  65. /// Compute: the thread-group info SGPR (wave index and count).
  66. GroupInfo,
  67. /// Mesh: v5, the group id times the group size (read as uniform).
  68. MeshGroup,
  69. /// Mesh: s3, the wave's index in the group in bits 24-27.
  70. MergedWaveInfo,
  71. }
  72. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  73. pub enum Barycentric {
  74. PerspectiveSample,
  75. PerspectiveCenter,
  76. PerspectiveCentroid,
  77. PerspectivePullModel,
  78. LinearSample,
  79. LinearCenter,
  80. LinearCentroid,
  81. }
  82. /// The pixel input VGPRs in hardware order: one entry per
  83. /// `SPI_PS_INPUT_ADDR` bit.
  84. const PS_VGPRS: [(u8, Option<Barycentric>); 16] = [
  85. (2, Some(Barycentric::PerspectiveSample)),
  86. (2, Some(Barycentric::PerspectiveCenter)),
  87. (2, Some(Barycentric::PerspectiveCentroid)),
  88. (3, Some(Barycentric::PerspectivePullModel)),
  89. (2, Some(Barycentric::LinearSample)),
  90. (2, Some(Barycentric::LinearCenter)),
  91. (2, Some(Barycentric::LinearCentroid)),
  92. (1, None), // line stipple
  93. (1, None), // position x
  94. (1, None), // y
  95. (1, None), // z
  96. (1, None), // w
  97. (1, None), // front face
  98. (1, None), // ancillary
  99. (1, None), // sample coverage
  100. (1, None), // fixed-point position
  101. ];
  102. fn ps_system(bit: usize) -> Input {
  103. match bit {
  104. 7 => Input::LineStipple,
  105. 8..=11 => Input::Position(bit as u8 - 8),
  106. 12 => Input::FrontFace,
  107. 13 => Input::Ancillary,
  108. 14 => Input::SampleCoverage,
  109. _ => Input::FixedPosition,
  110. }
  111. }
  112. /// An attribute channel of the input signature.
  113. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  114. pub struct Attribute {
  115. pub usage: Usage,
  116. pub row: u8,
  117. pub channel: u8,
  118. /// The upper f16 half of the channel (packed fp16 inputs).
  119. pub high: bool,
  120. }
  121. #[derive(Debug, Clone, PartialEq, Eq)]
  122. pub enum Interp {
  123. /// This site's result (`v_interp_p2*`) is the attribute interpolated
  124. /// with `barycentric`; `first` are the `v_interp_p1*` halves it
  125. /// completes (one per path where the compiler shares a first half).
  126. Interpolated {
  127. attribute: Attribute,
  128. barycentric: Barycentric,
  129. first: Vec<Site>,
  130. },
  131. /// One vertex's value (`v_interp_mov_f32`), as encoded: 0 for P10,
  132. /// 1 for P20, 2 for P0 (the provoking vertex).
  133. Vertex { attribute: Attribute, vertex: u8 },
  134. /// A half of an interpolation whose i or j is computed rather than
  135. /// loaded: each half evaluates as the hardware does, from the
  136. /// attribute's vertex values (`v_interp_p1*`: P0 + i P10, with P10 =
  137. /// P1 - P0; `v_interp_p2*`: its old dst + j P20, with P20 = P2 - P0).
  138. Weighted { attribute: Attribute },
  139. }
  140. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  141. pub enum Target {
  142. Color(u8),
  143. /// Depth, stencil, sample mask (channels as `DB_SHADER_CONTROL` enables).
  144. Depth,
  145. Null,
  146. Position(u8),
  147. Param {
  148. usage: Usage,
  149. row: u8,
  150. },
  151. /// `param0` of a vertex shader without outputs: the hardware wants one
  152. /// parameter export regardless.
  153. Unread,
  154. /// The primitive export of a merged or mesh stage.
  155. Primitive,
  156. /// A mesh program's per-primitive output (a row of `PSG1`).
  157. PrimitiveParam {
  158. usage: Usage,
  159. row: u8,
  160. },
  161. }
  162. #[derive(Debug, Clone, PartialEq, Eq)]
  163. pub struct Export {
  164. pub site: Site,
  165. pub target: Target,
  166. /// Per channel, as the instruction enables them.
  167. pub values: [Option<Value>; 4],
  168. /// Two f16 values per dword.
  169. pub compressed: bool,
  170. /// The program's last export (for pixels: kills the lanes not in EXEC).
  171. pub done: bool,
  172. }
  173. #[derive(Debug, Clone, Default, PartialEq, Eq)]
  174. pub struct Io {
  175. /// Input values the hardware loads, with their meaning; other VGPRs
  176. /// read before written hold undefined values.
  177. pub inputs: Vec<(Value, Input)>,
  178. pub interps: Vec<(Site, Interp)>,
  179. pub exports: Vec<Export>,
  180. /// Compute: how many SGPRs the hardware initializes
  181. /// ([`ComputeIo::initialized_sgprs`](crate::native::ComputeIo::initialized_sgprs)).
  182. pub initialized_sgprs: Option<u8>,
  183. }
  184. /// Raises the I/O of `p`, built from `native`'s patched code. Fails for
  185. /// stages whose stage data is not read and on constructs not covered yet.
  186. pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> {
  187. let unsupported = |offset, what| ShaderError::Unsupported { offset, what };
  188. let (loaded, ps_inputs, params) = match (&native.io, native.stage) {
  189. (
  190. StageIo::Ps {
  191. inputs, input_addr, ..
  192. },
  193. HwStage::Ps,
  194. ) => {
  195. // A pixel shader exports no parameters; `[]` never reaches `Unread`.
  196. let loaded = ps_vgprs(*input_addr)
  197. .into_iter()
  198. .map(|(r, i)| (Reg::V(r), i))
  199. .collect();
  200. (loaded, &inputs[..], &[][..])
  201. }
  202. (StageIo::Vs { inputs, outputs }, HwStage::Vs) => {
  203. let mut loaded = vec![
  204. (Reg::V(0), Input::VertexId),
  205. (Reg::V(2), Input::PrimitiveId),
  206. (Reg::V(3), Input::InstanceId),
  207. ];
  208. for i in inputs {
  209. for channel in (0..4).filter(|c| i.mask >> c & 1 != 0) {
  210. let input = Input::Attribute {
  211. row: i.row,
  212. channel,
  213. };
  214. loaded.push((Reg::V(i.vgpr + channel), input));
  215. }
  216. }
  217. (loaded, &[][..], &outputs[..])
  218. }
  219. // Compute: thread ids in v0-v2, group ids and the group info in the
  220. // SGPRs after the user data.
  221. (StageIo::Cs(cs), HwStage::Cs) => {
  222. let (ids, info) = cs.system_sgprs();
  223. let mut loaded: Vec<(Reg, Input)> = (0..cs.thread_id_vgprs())
  224. .map(|c| (Reg::V(c), Input::ThreadIdInGroup(c)))
  225. .collect();
  226. for (c, s) in ids.into_iter().enumerate() {
  227. if let Some(s) = s {
  228. loaded.push((Reg::S(s), Input::GroupId(c as u8)));
  229. }
  230. }
  231. loaded.extend(info.map(|s| (Reg::S(s), Input::GroupInfo)));
  232. (loaded, &[][..], &[][..])
  233. }
  234. (StageIo::Ms(ms), HwStage::Ms) => {
  235. // The group input, and the phis that may carry it past a join.
  236. let mut group: Vec<Value> = p
  237. .inputs
  238. .iter()
  239. .filter(|i| i.0 == Reg::V(5))
  240. .map(|i| i.1)
  241. .collect();
  242. // No lane is active over the EXEC-zero edge of s_cbranch_execz or
  243. // _execnz, the same case as a partial-EXEC write below.
  244. let no_lanes = |q: usize, b: usize| match (
  245. p.blocks[q].insts.last().map(Inst::name),
  246. p.blocks[q].exit,
  247. ) {
  248. (Some("s_cbranch_execz"), Exit::Branch { taken, not_taken }) => {
  249. taken == b && not_taken != b
  250. }
  251. (Some("s_cbranch_execnz"), Exit::Branch { taken, not_taken }) => {
  252. not_taken == b && taken != b
  253. }
  254. _ => false,
  255. };
  256. while let Some(v) = p
  257. .blocks
  258. .iter()
  259. .enumerate()
  260. .flat_map(|(b, k)| k.phis.iter().map(move |f| (b, f)))
  261. .find_map(|(b, f)| {
  262. let mut args = f.args.iter().zip(&p.blocks[b].preds);
  263. let carried = args.any(|(a, &q)| group.contains(a) && !no_lanes(q, b));
  264. (carried && !group.contains(&f.value)).then_some(f.value)
  265. })
  266. {
  267. group.push(v);
  268. }
  269. // The group input holds the same value in every lane only as the
  270. // first lane reads it. A write to v5 reads its old value too, which
  271. // only lanes outside EXEC keep.
  272. // shortcut: writes that may keep the old v5 in active lanes
  273. // (v_fmac_f32's accumulator, a 16-bit half or d16 load,
  274. // v_writelane_b32, v_movreld_b32, DPP that skips lanes) and
  275. // partial-EXEC writes pass; check those too if a mesh program
  276. // writes v5 that way.
  277. let per_lane = p.blocks.iter().flat_map(|b| &b.insts).find(|i| {
  278. i.read(Reg::V(5)).is_some_and(|v| group.contains(&v))
  279. && i.name() != "v_readfirstlane_b32"
  280. && (i.write(Reg::V(5)).is_none() || operand_reads(p, i).contains(&Reg::V(5)))
  281. });
  282. if let Some(i) = per_lane {
  283. return Err(unsupported(
  284. i.machine.offset,
  285. "the mesh group input read per lane",
  286. ));
  287. }
  288. let loaded = vec![
  289. (Reg::V(5), Input::MeshGroup),
  290. (Reg::S(3), Input::MergedWaveInfo),
  291. ];
  292. (loaded, &[][..], &ms.outputs[..])
  293. }
  294. _ => return Err(unsupported(0, "I/O of this stage")),
  295. };
  296. let inputs: Vec<(Value, Input)> = p
  297. .inputs
  298. .iter()
  299. .filter_map(|&(reg, v)| loaded.iter().find(|l| l.0 == reg).map(|l| (v, l.1)))
  300. .collect();
  301. let input_of = |v: Value| inputs.iter().find(|i| i.0 == v).map(|i| i.1);
  302. let attribute = |inst: &Inst, attr: &Operand| match *attr {
  303. Operand::Attr { index, chan, high } => ps_inputs
  304. .iter()
  305. .find(|i: &&PsInput| i.attr == index)
  306. .map(|i| Attribute {
  307. usage: i.usage,
  308. row: i.row,
  309. channel: chan,
  310. high,
  311. })
  312. .ok_or(unsupported(
  313. inst.machine.offset,
  314. "an interpolated attribute the stage data does not list",
  315. )),
  316. _ => Err(unsupported(inst.machine.offset, "an interpolation operand")),
  317. };
  318. // A VGPR value's barycentric kind and index, if it is one as loaded.
  319. let barycentric = |v: Option<Value>| match v.and_then(input_of) {
  320. Some(Input::Barycentric { kind, index }) => Some((kind, index)),
  321. _ => None,
  322. };
  323. let mut io = Io {
  324. inputs: inputs.clone(),
  325. initialized_sgprs: match &native.io {
  326. StageIo::Cs(cs) => Some(cs.initialized_sgprs()),
  327. _ => None,
  328. },
  329. ..Io::default()
  330. };
  331. let defs: std::collections::HashMap<Value, Site> = p
  332. .blocks
  333. .iter()
  334. .enumerate()
  335. .flat_map(|(b, block)| {
  336. block
  337. .insts
  338. .iter()
  339. .enumerate()
  340. .flat_map(move |(i, inst)| inst.writes.iter().map(move |w| (w.1, (b, i))))
  341. })
  342. .collect();
  343. let phis: std::collections::HashMap<Value, (usize, usize)> = p
  344. .blocks
  345. .iter()
  346. .enumerate()
  347. .flat_map(|(b, block)| {
  348. block
  349. .phis
  350. .iter()
  351. .enumerate()
  352. .map(move |(i, phi)| (phi.value, (b, i)))
  353. })
  354. .collect();
  355. let halves = Halves {
  356. p,
  357. defs: &defs,
  358. phis: &phis,
  359. };
  360. for (b, block) in p.blocks.iter().enumerate() {
  361. for (i, inst) in block.insts.iter().enumerate() {
  362. let site = (b, i);
  363. let at = inst.machine.offset;
  364. let name = inst.name();
  365. match &inst.fields {
  366. Fields::Vintrp { dst, src, attr } => {
  367. let attribute = attribute(inst, attr)?;
  368. match (name, *src) {
  369. ("v_interp_mov_f32", Operand::Const(vertex)) => {
  370. io.interps
  371. .push((site, Interp::Vertex { attribute, vertex }));
  372. }
  373. ("v_interp_p1_f32", _) => {}
  374. ("v_interp_p2_f32", Operand::Vector { reg, .. }) => {
  375. let Operand::Vector { reg: d, .. } = *dst else {
  376. return Err(unsupported(at, "an interpolation operand"));
  377. };
  378. // The first half's result is this one's old dst.
  379. let interp = halves
  380. .pair(
  381. attr,
  382. inst.read(Reg::V(d)),
  383. inst.read(Reg::V(reg)),
  384. &barycentric,
  385. )
  386. .map_err(|what| unsupported(at, what))?;
  387. push_pair(&mut io, site, interp, attribute);
  388. }
  389. _ => return Err(unsupported(at, "an interpolation form")),
  390. }
  391. }
  392. Fields::Valu(v) if name.starts_with("v_interp_") => match name {
  393. "v_interp_p1ll_f16" => {}
  394. "v_interp_p2_f16" => {
  395. let attribute = attribute(inst, &v.src[0])?;
  396. let read = |k: usize| match v.src.get(k) {
  397. Some(&Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)),
  398. _ => None,
  399. };
  400. let interp = halves
  401. .pair(&v.src[0], read(2), read(1), &barycentric)
  402. .map_err(|what| unsupported(at, what))?;
  403. push_pair(&mut io, site, interp, attribute);
  404. }
  405. _ => return Err(unsupported(at, "an interpolation form")),
  406. },
  407. Fields::Exp {
  408. target,
  409. src,
  410. compr,
  411. done,
  412. ..
  413. } => {
  414. let target = match *target {
  415. t @ 0..=7 => Target::Color(t),
  416. 8 => Target::Depth,
  417. 9 => Target::Null,
  418. t @ 12..=16 => Target::Position(t - 12),
  419. 20 => Target::Primitive,
  420. 32 if params.is_empty() => Target::Unread,
  421. t @ 32..=63 => {
  422. // Bit 7: a mesh program's per-primitive output.
  423. let o = params.iter().find(|o| o.param & 0x7F == t - 32).ok_or(
  424. unsupported(at, "a parameter export the stage data does not list"),
  425. )?;
  426. let (usage, row) = (o.usage, o.row);
  427. if o.param & 0x80 != 0 {
  428. Target::PrimitiveParam { usage, row }
  429. } else {
  430. Target::Param { usage, row }
  431. }
  432. }
  433. _ => return Err(unsupported(at, "an export target")),
  434. };
  435. let values = src.map(|s| match s {
  436. Some(Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)),
  437. _ => None,
  438. });
  439. io.exports.push(Export {
  440. site,
  441. target,
  442. values,
  443. compressed: *compr,
  444. done: *done,
  445. });
  446. }
  447. _ => {}
  448. }
  449. }
  450. }
  451. Ok(io)
  452. }
  453. /// The pixel input VGPRs that `addr` enables, with their meaning.
  454. fn ps_vgprs(addr: u32) -> Vec<(u8, Input)> {
  455. let mut out = Vec::new();
  456. let mut next = 0u8;
  457. for (bit, &(count, kind)) in PS_VGPRS.iter().enumerate() {
  458. if addr >> bit & 1 == 0 {
  459. continue;
  460. }
  461. for index in 0..count {
  462. let input = match kind {
  463. Some(kind) => Input::Barycentric { kind, index },
  464. None => ps_system(bit),
  465. };
  466. out.push((next + index, input));
  467. }
  468. next += count;
  469. }
  470. out
  471. }
  472. /// An interpolation before its attribute is known: `barycentric` none
  473. /// when i or j is computed.
  474. struct Pair {
  475. barycentric: Option<Barycentric>,
  476. first: Vec<Site>,
  477. }
  478. impl Pair {
  479. fn with(self, attribute: Attribute) -> Interp {
  480. match self.barycentric {
  481. Some(barycentric) => Interp::Interpolated {
  482. attribute,
  483. barycentric,
  484. first: self.first,
  485. },
  486. None => Interp::Weighted { attribute },
  487. }
  488. }
  489. }
  490. /// Records interpolation `pair` at `site`, and its first halves too when
  491. /// they evaluate on their own (computed barycentrics).
  492. fn push_pair(io: &mut Io, site: Site, pair: Pair, attribute: Attribute) {
  493. if pair.barycentric.is_none() {
  494. for &f in &pair.first {
  495. if !io.interps.iter().any(|(s, _)| *s == f) {
  496. io.interps.push((f, Interp::Weighted { attribute }));
  497. }
  498. }
  499. }
  500. io.interps.push((site, pair.with(attribute)));
  501. }
  502. /// Finds the first halves of interpolations.
  503. struct Halves<'a> {
  504. p: &'a Program,
  505. defs: &'a std::collections::HashMap<Value, Site>,
  506. phis: &'a std::collections::HashMap<Value, (usize, usize)>,
  507. }
  508. impl Halves<'_> {
  509. /// The interpolation whose second half reads the first half's result
  510. /// `acc`, the barycentric `j`, and attribute `attr`: every first half
  511. /// must read the same attribute channel. With j and every first half's
  512. /// i loaded as one kind's, the pair interpolates with that kind;
  513. /// otherwise each half evaluates on its own (`Interp::Weighted`).
  514. fn pair(
  515. &self,
  516. attr: &Operand,
  517. acc: Option<Value>,
  518. j: Option<Value>,
  519. barycentric: &impl Fn(Option<Value>) -> Option<(Barycentric, u8)>,
  520. ) -> Result<Pair, &'static str> {
  521. let mut first = Vec::new();
  522. self.sites(
  523. acc.ok_or("an interpolation without its first half")?,
  524. &mut Vec::new(),
  525. &mut first,
  526. )?;
  527. let mut kind = match barycentric(j) {
  528. Some((kind, 1)) => Some(kind),
  529. _ => None,
  530. };
  531. for &(b, i) in &first {
  532. let inst = &self.p.blocks[b].insts[i];
  533. let (a, i) = match &inst.fields {
  534. Fields::Vintrp {
  535. src: Operand::Vector { reg, .. },
  536. attr,
  537. ..
  538. } if inst.name() == "v_interp_p1_f32" => (*attr, inst.read(Reg::V(*reg))),
  539. Fields::Valu(v) if inst.name() == "v_interp_p1ll_f16" => match v.src.get(1) {
  540. Some(&Operand::Vector { reg, .. }) => (v.src[0], inst.read(Reg::V(reg))),
  541. _ => return Err("an interpolation without its first half"),
  542. },
  543. _ => return Err("an interpolation without its first half"),
  544. };
  545. if a != *attr {
  546. return Err("interpolation halves of different attributes");
  547. }
  548. if kind.is_some_and(|k| barycentric(i) != Some((k, 0))) {
  549. kind = None;
  550. }
  551. }
  552. Ok(Pair {
  553. barycentric: kind,
  554. first,
  555. })
  556. }
  557. /// The instructions `v` comes from, through phis (`seen`: phis on the
  558. /// way; a loop back to one adds nothing).
  559. fn sites(
  560. &self,
  561. v: Value,
  562. seen: &mut Vec<Value>,
  563. out: &mut Vec<Site>,
  564. ) -> Result<(), &'static str> {
  565. if let Some(&site) = self.defs.get(&v) {
  566. if !out.contains(&site) {
  567. out.push(site);
  568. }
  569. return Ok(());
  570. }
  571. let &(b, i) = self
  572. .phis
  573. .get(&v)
  574. .ok_or("an interpolation without its first half")?;
  575. if !seen.contains(&v) {
  576. seen.push(v);
  577. for &a in &self.p.blocks[b].phis[i].args {
  578. self.sites(a, seen, out)?;
  579. }
  580. }
  581. Ok(())
  582. }
  583. }
  584. #[cfg(test)]
  585. mod tests {
  586. use super::*;
  587. use crate::native::ExportPatch;
  588. const S_ENDPGM: u32 = 0xBF81_0000;
  589. fn program(words: &[u32]) -> Program {
  590. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  591. crate::ir::build(&code, false, 256).unwrap()
  592. }
  593. fn pixel(inputs: Vec<PsInput>, input_addr: u32) -> NativeProgram {
  594. NativeProgram {
  595. stage: HwStage::Ps,
  596. wave64: false,
  597. vgprs: 256,
  598. layout: vec![],
  599. used: vec![],
  600. io: StageIo::Ps {
  601. inputs,
  602. input_addr,
  603. db_shader_control: 0,
  604. patches: Vec::<ExportPatch>::new(),
  605. },
  606. code: vec![],
  607. }
  608. }
  609. const TEXCOORD: PsInput = PsInput {
  610. usage: Usage::Generic,
  611. row: 1,
  612. mask: 3,
  613. attr: 0,
  614. flat: false,
  615. fp16: false,
  616. pack2: false,
  617. row2: 1,
  618. };
  619. #[test]
  620. fn interpolation_pairs_and_color_exports() {
  621. // Blit's pixel shader: TEXCOORD.xy from the perspective-center i/j
  622. // in v0/v1, then exported unconverted to MRT0.
  623. let p = program(&[
  624. 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
  625. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  626. 0xF800_180F,
  627. 0x0302_0102, // exp mrt0, v2, v1, v2, v3 done vm
  628. S_ENDPGM,
  629. ]);
  630. let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap();
  631. let input = |reg| p.inputs.iter().find(|i| i.0 == Reg::V(reg)).unwrap().1;
  632. let center = |index| Input::Barycentric {
  633. kind: Barycentric::PerspectiveCenter,
  634. index,
  635. };
  636. assert!(io.inputs.contains(&(input(0), center(0))));
  637. assert!(io.inputs.contains(&(input(1), center(1))));
  638. // v2 and v3 are read before written but hold nothing.
  639. assert!(!io.inputs.iter().any(|i| i.0 == input(3)));
  640. assert_eq!(
  641. io.interps,
  642. [(
  643. (0, 1),
  644. Interp::Interpolated {
  645. attribute: Attribute {
  646. usage: Usage::Generic,
  647. row: 1,
  648. channel: 0,
  649. high: false
  650. },
  651. barycentric: Barycentric::PerspectiveCenter,
  652. first: vec![(0, 0)],
  653. }
  654. )]
  655. );
  656. let [e] = &io.exports[..] else {
  657. panic!("{:?}", io.exports)
  658. };
  659. assert_eq!(
  660. (e.target, e.done, e.compressed),
  661. (Target::Color(0), true, false)
  662. );
  663. assert_eq!(e.values[0], p.blocks[0].insts[1].write(Reg::V(2)));
  664. }
  665. #[test]
  666. fn unpaired_or_unknown_interpolation_fails() {
  667. // p2 alone: its old dst is no p1's result.
  668. let lone = program(&[0xC809_0001, S_ENDPGM]); // v_interp_p2_f32 v2, v1, attr0.x
  669. assert!(raise(&lone, &pixel(vec![TEXCOORD], 2)).is_err());
  670. // attr1 is not in the stage data.
  671. let other = program(&[0xC808_0400, S_ENDPGM]); // v_interp_p1_f32 v2, v0, attr1.x
  672. assert!(raise(&other, &pixel(vec![TEXCOORD], 2)).is_err());
  673. }
  674. #[test]
  675. fn computed_barycentrics_evaluate_each_half() {
  676. // i scaled before the first half: both halves stand on their own.
  677. let p = program(&[
  678. 0x1006_00F0, // v_mul_f32 v3, 0.5, v0
  679. 0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x
  680. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  681. S_ENDPGM,
  682. ]);
  683. let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap();
  684. let attribute = Attribute {
  685. usage: Usage::Generic,
  686. row: 1,
  687. channel: 0,
  688. high: false,
  689. };
  690. let mut interps = io.interps.clone();
  691. interps.sort_by_key(|i| i.0);
  692. assert_eq!(
  693. interps,
  694. [
  695. ((0, 1), Interp::Weighted { attribute }),
  696. ((0, 2), Interp::Weighted { attribute }),
  697. ]
  698. );
  699. }
  700. #[test]
  701. fn mesh_inputs_and_primitive_export() {
  702. let mesh = |words: &[u32]| {
  703. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  704. let p = crate::ir::build(&code, true, 256).unwrap();
  705. let native = NativeProgram {
  706. stage: HwStage::Ms,
  707. wave64: true,
  708. vgprs: 256,
  709. layout: vec![],
  710. used: vec![],
  711. io: StageIo::Ms(crate::native::MeshIo {
  712. outputs: vec![],
  713. clip_cntl: 0,
  714. threads: 128,
  715. max_vertices: 128,
  716. max_primitives: 128,
  717. topology: 2,
  718. lds_bytes: 0,
  719. }),
  720. code,
  721. };
  722. raise(&p, &native)
  723. };
  724. let io = mesh(&[
  725. 0x7E04_0505, // v_readfirstlane_b32 s2, v5
  726. 0xF800_0941,
  727. 0x0000_0009, // exp prim, v9, off, off, off done
  728. S_ENDPGM,
  729. ])
  730. .unwrap();
  731. assert!(io.inputs.iter().any(|i| i.1 == Input::MeshGroup));
  732. assert_eq!(io.exports[0].target, Target::Primitive);
  733. // The group input is uniform only as the first lane reads it.
  734. assert!(mesh(&[0x7E02_0305, S_ENDPGM]).is_err()); // v_mov_b32 v1, v5
  735. // Also as an operand of a write to v5, or after a join.
  736. let per_lane: [&[u32]; 5] = [
  737. &[0x4A0A_0305, S_ENDPGM], // v_add_nc_u32 v5, v5, v1
  738. &[0x7E0A_0D05, S_ENDPGM], // v_cvt_f32_u32 v5, v5
  739. &[0xDC30_8000, 0x0500_0005, S_ENDPGM], // global_load_dword v5, v5, s[0:1]
  740. &[0x7E0A_CB01, S_ENDPGM], // v_swap_b32 v5, v1
  741. &[
  742. 0xBF06_8001, // s_cmp_eq_u32 s1, 0
  743. 0xBF85_0001, // s_cbranch_scc1 -> 0xc
  744. 0x7E0A_0280, // v_mov_b32 v5, 0
  745. 0x7E02_0305, // 0xc: v_mov_b32 v1, v5
  746. S_ENDPGM,
  747. ],
  748. ];
  749. let accepted: Vec<_> = per_lane.iter().filter(|w| mesh(w).is_ok()).collect();
  750. assert!(accepted.is_empty(), "accepted: {accepted:08X?}");
  751. // Overwriting v5 reads the group input only for lanes outside EXEC:
  752. // v_mov_b32 v5, 0; v_mov_b32 v1, v5.
  753. assert!(mesh(&[0x7E0A_0280, 0x7E02_0305, S_ENDPGM]).is_ok());
  754. // Skipping that write with s_cbranch_execz is the same case: under the
  755. // same mask, the read sees only the 0.
  756. let reuse = [
  757. 0x7E04_0505, // v_readfirstlane_b32 s2, v5
  758. 0x7D88_0084, // v_cmp_gt_u32 vcc, 4, v0
  759. 0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc
  760. 0xBF88_0001, // s_cbranch_execz -> 0x14
  761. 0x7E0A_0280, // v_mov_b32 v5, 0
  762. 0x88FE_067E, // 0x14: s_or_b64 exec, exec, s[6:7]
  763. 0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc
  764. 0xBF88_0001, // s_cbranch_execz -> 0x24
  765. 0x7E02_0305, // v_mov_b32 v1, v5
  766. 0x88FE_067E, // 0x24: s_or_b64 exec, exec, s[6:7]
  767. S_ENDPGM,
  768. ];
  769. assert_eq!(mesh(&reuse).map(|_| ()), Ok(()));
  770. }
  771. #[test]
  772. fn pixel_vgprs_follow_the_input_address() {
  773. // Linear center (bit 5), then position x and y (bits 8, 9).
  774. let v = ps_vgprs(1 << 5 | 1 << 8 | 1 << 9);
  775. assert_eq!(
  776. v,
  777. [
  778. (
  779. 0,
  780. Input::Barycentric {
  781. kind: Barycentric::LinearCenter,
  782. index: 0
  783. }
  784. ),
  785. (
  786. 1,
  787. Input::Barycentric {
  788. kind: Barycentric::LinearCenter,
  789. index: 1
  790. }
  791. ),
  792. (2, Input::Position(0)),
  793. (3, Input::Position(1)),
  794. ]
  795. );
  796. }
  797. }