opt.rs 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225
  1. //! Clean-up of a finished module before it is written: the lowering emits
  2. //! one instruction after another as the console code names them, and
  3. //! nothing stands between it and the driver's compiler. Every pass here is
  4. //! exact: the module computes the same values and has the same effects for
  5. //! every input.
  6. //!
  7. //! - [`DEAD`]: instructions without an effect whose result nothing reads
  8. //! are left out (the lowering computes every dword of every register a
  9. //! console instruction writes; a guarded write reads the register's old
  10. //! value whether anything reads the new one or not).
  11. //! - [`FOLD`]: integer arithmetic on constants is done here, and identities
  12. //! (`x + 0`, `x & -1`, a select between a value and itself, a cast there
  13. //! and back, a join of one value) give their operand. Float arithmetic is
  14. //! left alone: `x + 0.0` and `x * 1.0` are not `x` for every `x`.
  15. //! - [`REUSE`]: an instruction without an effect whose operands are those
  16. //! of an earlier one that every path to it has run gives that one's
  17. //! result (a descriptor handle made again in each block, an index clamped
  18. //! again, a register read as a float again).
  19. //! - [`FACTS`]: in the blocks only one side of a branch leads to, the
  20. //! branch's condition is that side's constant, and so is what the
  21. //! condition was made of (both terms of an `and` that held, the opposite
  22. //! comparison). The lowering branches on a lane's condition and then
  23. //! guards each instruction behind the branch with the same condition.
  24. //! - [`LOADS`]: within a block, a read of the same place as an earlier read
  25. //! gives that one's result while no store, atomic, barrier or other call
  26. //! with an effect stands between them (another thread's unsynchronised
  27. //! store may fall between any two reads or before both: the title's code
  28. //! cannot tell which).
  29. //!
  30. //! Which passes run is `emit::shader_opt()` (`VICTORY_SHADER_OPT`), part of
  31. //! the translation and so of the shader cache's key.
  32. use std::collections::HashMap;
  33. use super::{
  34. Attr, Bin, Cast, Const, Func, MdDef, Module, Op, Term, Ty, TypeDef, V, for_each_operand, pred,
  35. successors,
  36. };
  37. /// Dead-code elimination.
  38. pub const DEAD: u32 = 1;
  39. /// Constants folded, identities removed.
  40. pub const FOLD: u32 = 2;
  41. /// One instruction for one value.
  42. pub const REUSE: u32 = 4;
  43. /// What a branch taken says about its condition.
  44. pub const FACTS: u32 = 8;
  45. /// One read for one place within a block, while nothing is stored.
  46. pub const LOADS: u32 = 16;
  47. /// Not a pass over the module: the lowering of a first-lane read in a
  48. /// wave64 program run as two host waves skips the exchange that asks which
  49. /// half has a lane where every lane is in EXEC (`lower.rs`,
  50. /// `v_readfirstlane_b32`).
  51. pub const FIRST: u32 = 32;
  52. /// Not a pass over the module either: the lowering reads the dwords of one
  53. /// console load (`s_buffer_load_dwordx2` to `x16` from an SRV, a
  54. /// `global_load_dwordx2` to `x4`) by one call for every four of them, not
  55. /// by a call each (`lower.rs`, `raw_dwords`). The same bytes are read.
  56. pub const WIDE: u32 = 64;
  57. /// The passes over the module.
  58. pub const MODULE: u32 = DEAD | FOLD | REUSE | FACTS | LOADS;
  59. /// Every pass.
  60. pub const ALL: u32 = MODULE | FIRST | WIDE;
  61. /// The passes that run when nothing says which: every one but [`WIDE`],
  62. /// which no card has shown a gain for yet (`VICTORY_SHADER_OPT=127` asks
  63. /// for it).
  64. pub const DEFAULT: u32 = ALL & !WIDE;
  65. /// What the instructions a module writes use, of the features a shader
  66. /// declares by flag (the validator's "flags must match usage").
  67. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
  68. pub(crate) struct Usage {
  69. /// A wave or quad operation.
  70. pub wave_ops: bool,
  71. /// A rasterizer ordered view.
  72. pub rovs: bool,
  73. /// A 64-bit integer, as a result or an operand.
  74. pub int64: bool,
  75. /// A typed load of several components from a UAV.
  76. pub typed_uav_loads: bool,
  77. /// A handle from the view heap.
  78. pub heap_views: bool,
  79. /// A handle from the sampler heap.
  80. pub heap_samplers: bool,
  81. /// A 64-bit atomic.
  82. pub atomic64: bool,
  83. }
  84. /// What makes two instructions without an effect the same value.
  85. #[derive(Debug, Clone, PartialEq, Eq, Hash)]
  86. enum Key {
  87. Bin(u8, V, V),
  88. Cast(u8, Ty, V),
  89. Cmp(u8, V, V),
  90. Select(V, V, V),
  91. Extract(V, u32),
  92. Call(u32, Vec<V>),
  93. Gep(Ty, V, Vec<V>),
  94. Load(V),
  95. }
  96. /// The blocks reached from the entry, each after the blocks that dominate
  97. /// it, and each block's children in the dominator tree.
  98. struct Tree {
  99. order: Vec<usize>,
  100. children: Vec<Vec<usize>>,
  101. /// Per block: the reached blocks that branch to it, once per edge.
  102. preds: Vec<Vec<usize>>,
  103. }
  104. /// The comparison that holds exactly when `p` does not (floats 0-15,
  105. /// integers 32-41).
  106. fn opposite(p: u8) -> u8 {
  107. match p {
  108. 0..=15 => 15 - p,
  109. pred::EQ => pred::NE,
  110. pred::NE => pred::EQ,
  111. pred::IUGT => pred::IULE,
  112. pred::IULE => pred::IUGT,
  113. pred::IUGE => pred::IULT,
  114. pred::IULT => pred::IUGE,
  115. pred::SGT => pred::SLE,
  116. pred::SLE => pred::SGT,
  117. pred::SGE => pred::SLT,
  118. _ => pred::SGE,
  119. }
  120. }
  121. /// What holds in the block being walked: values that are a known bit there,
  122. /// and comparisons (by their operands) with a known outcome.
  123. #[derive(Default)]
  124. struct Facts {
  125. bits: HashMap<V, bool>,
  126. compares: HashMap<(u8, V, V), bool>,
  127. }
  128. /// The facts a block added, to forget when its part of the tree is done.
  129. #[derive(Default)]
  130. struct Learned {
  131. bits: Vec<V>,
  132. compares: Vec<(u8, V, V)>,
  133. }
  134. fn mask(bits: u32) -> u64 {
  135. if bits >= 64 { !0 } else { (1 << bits) - 1 }
  136. }
  137. /// `x` of `bits` bits as a signed number.
  138. fn signed(bits: u32, x: u64) -> i64 {
  139. if bits < 64 && x >> (bits - 1) & 1 != 0 {
  140. (x | !mask(bits)) as i64
  141. } else {
  142. x as i64
  143. }
  144. }
  145. /// What `v` stands for after the replacements so far.
  146. fn resolve(repl: &[Option<V>], mut v: V) -> V {
  147. while let V::Inst(i) = v {
  148. match repl[i as usize] {
  149. Some(r) => v = r,
  150. None => break,
  151. }
  152. }
  153. v
  154. }
  155. /// Replaces every value `op` reads by `f` of it.
  156. fn map_operands(op: &mut Op, mut f: impl FnMut(V) -> V) {
  157. match op {
  158. Op::Bin(_, a, b) | Op::Cmp(_, a, b) | Op::Store(a, b) | Op::AtomicRmw(_, a, b) => {
  159. *a = f(*a);
  160. *b = f(*b);
  161. }
  162. Op::Cast(_, v) | Op::Extract(v, _) | Op::Load(v) => *v = f(*v),
  163. Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => {
  164. *a = f(*a);
  165. *b = f(*b);
  166. *c = f(*c);
  167. }
  168. Op::Call(_, args) => args.iter_mut().for_each(|a| *a = f(*a)),
  169. Op::Phi(inc) => inc.iter_mut().for_each(|x| x.0 = f(x.0)),
  170. Op::Gep(_, p, idx) => {
  171. *p = f(*p);
  172. idx.iter_mut().for_each(|i| *i = f(*i));
  173. }
  174. }
  175. }
  176. /// What a call does besides returning its result.
  177. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  178. pub(super) enum Effect {
  179. /// Nothing, and the result depends on the arguments alone for the whole
  180. /// run of the shader (arithmetic, handles, inputs, constant buffers,
  181. /// resource sizes).
  182. Pure,
  183. /// Nothing, but the result depends on memory a store may change
  184. /// (buffer and texture reads).
  185. Reads,
  186. /// Nothing, but the result depends on which lanes run the instruction
  187. /// (wave and quad operations).
  188. Lanes,
  189. /// Stores, atomics, barriers, outputs, discards: always kept.
  190. Writes,
  191. }
  192. pub(super) fn effect(f: &Func) -> Effect {
  193. let name = f.name.strip_prefix("dx.op.").unwrap_or(&f.name);
  194. match f.attr {
  195. Some(Attr::ReadNone) => Effect::Pure,
  196. // A shader cannot write a constant buffer or resize a resource.
  197. Some(Attr::ReadOnly)
  198. if name.starts_with("cbufferLoadLegacy") || name.starts_with("getDimensions") =>
  199. {
  200. Effect::Pure
  201. }
  202. Some(Attr::ReadOnly) if name.starts_with("wave") => Effect::Lanes,
  203. Some(Attr::ReadOnly) => Effect::Reads,
  204. // Declared with the attribute of calls that have effects, and have
  205. // none: they read the other lanes' values.
  206. _ if name.starts_with("wave") || name.starts_with("quad") => Effect::Lanes,
  207. _ => Effect::Writes,
  208. }
  209. }
  210. impl Module {
  211. /// Runs the clean-up passes named in `passes` ([`ALL`]: every one).
  212. pub(crate) fn optimise(&mut self, passes: u32) {
  213. if passes & (FOLD | REUSE | FACTS | LOADS) != 0 {
  214. // Values merged in one round can make two joins the same in
  215. // the next (a loop's registers that only go round), and a
  216. // branch that goes one way leaves blocks with one way in.
  217. for _ in 0..4 {
  218. let mut changed = self.merge(passes);
  219. if passes & FOLD != 0 {
  220. changed |= self.prune();
  221. }
  222. if !changed {
  223. break;
  224. }
  225. }
  226. }
  227. if passes & DEAD != 0 {
  228. self.drop_dead();
  229. }
  230. }
  231. /// Per function: what a call of it does.
  232. pub(super) fn effects(&self) -> Vec<Effect> {
  233. self.funcs.iter().map(effect).collect()
  234. }
  235. /// The blocks reached from the entry.
  236. pub(super) fn reached(&self) -> Vec<bool> {
  237. let mut seen = vec![false; self.blocks.len()];
  238. if self.blocks.is_empty() {
  239. return seen;
  240. }
  241. let mut stack = vec![0usize];
  242. seen[0] = true;
  243. while let Some(b) = stack.pop() {
  244. for &s in successors(self.blocks[b].term).iter() {
  245. if !seen[s] {
  246. seen[s] = true;
  247. stack.push(s);
  248. }
  249. }
  250. }
  251. seen
  252. }
  253. fn dominator_tree(&self) -> Tree {
  254. let n = self.blocks.len();
  255. let succs = |b: usize| successors(self.blocks[b].term);
  256. // Reverse postorder, as `write` lays the blocks out.
  257. let mut seen = vec![false; n];
  258. let mut post = Vec::new();
  259. let mut stack = vec![(0usize, 0usize)];
  260. seen[0] = true;
  261. while let Some(top) = stack.last_mut() {
  262. let (b, k) = *top;
  263. top.1 += 1;
  264. match succs(b).get(k) {
  265. Some(&s) if !seen[s] => {
  266. seen[s] = true;
  267. stack.push((s, 0));
  268. }
  269. Some(_) => {}
  270. None => {
  271. post.push(b);
  272. stack.pop();
  273. }
  274. }
  275. }
  276. post.reverse();
  277. let order = post;
  278. let mut number = vec![usize::MAX; n];
  279. for (k, &b) in order.iter().enumerate() {
  280. number[b] = k;
  281. }
  282. let mut preds = vec![Vec::new(); n];
  283. for &b in &order {
  284. for &s in succs(b).iter() {
  285. preds[s].push(b);
  286. }
  287. }
  288. // Immediate dominators (Cooper, Harvey and Kennedy's iteration).
  289. let mut idom = vec![usize::MAX; n];
  290. idom[0] = 0;
  291. let mut changed = true;
  292. while changed {
  293. changed = false;
  294. for &b in &order[1..] {
  295. let mut new = usize::MAX;
  296. for &p in &preds[b] {
  297. if idom[p] == usize::MAX {
  298. continue;
  299. }
  300. if new == usize::MAX {
  301. new = p;
  302. continue;
  303. }
  304. let (mut x, mut y) = (p, new);
  305. while x != y {
  306. while number[x] > number[y] {
  307. x = idom[x];
  308. }
  309. while number[y] > number[x] {
  310. y = idom[y];
  311. }
  312. }
  313. new = x;
  314. }
  315. if idom[b] != new {
  316. idom[b] = new;
  317. changed = true;
  318. }
  319. }
  320. }
  321. let mut children = vec![Vec::new(); n];
  322. for &b in &order[1..] {
  323. children[idom[b]].push(b);
  324. }
  325. Tree {
  326. order,
  327. children,
  328. preds,
  329. }
  330. }
  331. /// Notes that `v` (an i1) is `holds` in the block being walked, and what
  332. /// follows from it for the values `v` was made of.
  333. fn learn(&self, v: V, holds: bool, facts: &mut Facts, learned: &mut Learned, depth: u32) {
  334. let V::Inst(i) = v else { return };
  335. if facts.bits.contains_key(&v) {
  336. return;
  337. }
  338. facts.bits.insert(v, holds);
  339. learned.bits.push(v);
  340. if depth == 0 {
  341. return;
  342. }
  343. match self.insts[i as usize].op {
  344. // Both terms of an `and` that holds hold; neither of an `or`
  345. // that does not.
  346. Op::Bin(Bin::And, a, b) if holds => {
  347. self.learn(a, true, facts, learned, depth - 1);
  348. self.learn(b, true, facts, learned, depth - 1);
  349. }
  350. Op::Bin(Bin::Or, a, b) if !holds => {
  351. self.learn(a, false, facts, learned, depth - 1);
  352. self.learn(b, false, facts, learned, depth - 1);
  353. }
  354. Op::Bin(Bin::Xor, a, b) => {
  355. let (x, k) = match (self.int_k(a), self.int_k(b)) {
  356. (None, Some((1, k))) => (a, k),
  357. (Some((1, k)), None) => (b, k),
  358. _ => return,
  359. };
  360. self.learn(x, holds != (k != 0), facts, learned, depth - 1);
  361. }
  362. // The opposite comparison of the same operands.
  363. Op::Cmp(p, a, b) => {
  364. let key = (opposite(p), a, b);
  365. if let std::collections::hash_map::Entry::Vacant(e) = facts.compares.entry(key) {
  366. e.insert(!holds);
  367. learned.compares.push(key);
  368. }
  369. }
  370. _ => {}
  371. }
  372. }
  373. fn int_bits(&self, ty: Ty) -> Option<u32> {
  374. match self.types[ty.0 as usize] {
  375. TypeDef::Int(bits) => Some(bits),
  376. _ => None,
  377. }
  378. }
  379. /// An integer constant's width and value (the bits of that width).
  380. pub(crate) fn int_k(&self, v: V) -> Option<(u32, u64)> {
  381. let V::Const(i) = v else { return None };
  382. let (ty, Const::Int(x)) = &self.consts[i as usize] else {
  383. return None;
  384. };
  385. let bits = self.int_bits(*ty)?;
  386. Some((bits, *x as u64 & mask(bits)))
  387. }
  388. /// The bits of a 32-bit float that is a constant, given as one or as a
  389. /// cast of an integer constant.
  390. pub(crate) fn float_k(&self, v: V) -> Option<f32> {
  391. let (v, cast) = match v {
  392. V::Inst(i) => match self.insts[i as usize].op {
  393. Op::Cast(Cast::Bitcast, x) => (x, true),
  394. _ => return None,
  395. },
  396. _ => (v, false),
  397. };
  398. let V::Const(i) = v else { return None };
  399. match &self.consts[i as usize].1 {
  400. Const::Float(bits) if !cast => Some(f32::from_bits(*bits)),
  401. Const::Int(_) if cast => {
  402. let (bits, x) = self.int_k(v)?;
  403. (bits == 32).then_some(f32::from_bits(x as u32))
  404. }
  405. _ => None,
  406. }
  407. }
  408. /// For a float that is a number and not an infinity whatever the program
  409. /// reads: a power of two its magnitude does not pass.
  410. pub(crate) fn bounded(&self, v: V, depth: u32) -> Option<f32> {
  411. if let Some(k) = self.float_k(v) {
  412. return k.is_finite().then(|| k.abs().max(1e-30).log2().ceil());
  413. }
  414. let V::Inst(i) = v else { return None };
  415. let depth = depth.checked_sub(1)?;
  416. let of = |v: V| self.bounded(v, depth);
  417. // (A power that overflows, or might with rounding, is no bound.)
  418. let held = |b: f32| (b < 126.0).then_some(b);
  419. match &self.insts[i as usize].op {
  420. Op::Cast(Cast::UiToFp | Cast::SiToFp, _) => Some(32.0),
  421. Op::Cast(Cast::Bitcast, x) => match *x {
  422. V::Inst(j) => match self.insts[j as usize].op {
  423. Op::Cast(Cast::Bitcast, y) if self.type_of(y) == self.type_of(v) => of(y),
  424. _ => None,
  425. },
  426. _ => None,
  427. },
  428. Op::Bin(Bin::Mul, a, b) => held(of(*a)? + of(*b)?),
  429. Op::Bin(Bin::Add | Bin::Sub, a, b) => held(of(*a)?.max(of(*b)?) + 1.0),
  430. Op::Select(_, a, b) => Some(of(*a)?.max(of(*b)?)),
  431. Op::Call(_, args) => {
  432. let (_, code) = self.int_k(*args.first()?)?;
  433. match (code, &args[1..]) {
  434. // Saturated, a fraction, a cosine or sine (of a number).
  435. (7, [_]) => Some(0.0),
  436. (6, [x]) => of(*x),
  437. (22 | 12 | 13, [x]) => of(*x).map(|_| 0.0),
  438. (26..=29, [x]) => held(of(*x)? + 1.0),
  439. // Of two numbers; or one of them the other way round: the
  440. // minimum (36) of a constant and a maximum of another.
  441. (35 | 36, [a, b]) => match (of(*a), of(*b)) {
  442. (Some(x), Some(y)) => Some(x.max(y)),
  443. _ => {
  444. let other = if code == 35 { 36 } else { 35 };
  445. let (inner, k) = if self.float_k(*b).is_some() { (*a, *b) } else { (*b, *a) };
  446. let k = self.float_k(k).and_then(|_| of(k))?;
  447. let V::Inst(j) = inner else { return None };
  448. let Op::Call(_, inner) = &self.insts[j as usize].op else { return None };
  449. let (_, code) = self.int_k(*inner.first()?)?;
  450. let low = inner[1..].iter().find(|x| self.float_k(**x).is_some())?;
  451. (code == other).then_some(())?;
  452. Some(k.max(of(*low)?))
  453. }
  454. },
  455. (46, [a, b, c]) => held((of(*a)? + of(*b)?).max(of(*c)?) + 1.0),
  456. _ => None,
  457. }
  458. }
  459. _ => None,
  460. }
  461. }
  462. /// The constant `x` of the integer type `ty`, kept sign-extended as
  463. /// [`Module::i32`] and [`Module::bool`] keep theirs.
  464. fn k(&mut self, ty: Ty, bits: u32, x: u64) -> V {
  465. self.int_const(ty, signed(bits, x & mask(bits)))
  466. }
  467. /// The value instruction `i` is known to have without it, if any: a
  468. /// constant or an earlier value. May instead give `i` simpler operands
  469. /// (`changed` says so).
  470. fn simplify(&mut self, i: u32, changed: &mut bool) -> Option<V> {
  471. let ty = self.insts[i as usize].ty;
  472. match self.insts[i as usize].op {
  473. Op::Bin(op, a, b) => {
  474. // Floats: `x + 0.0`, `x * 1.0` and the like are not `x` for
  475. // every `x` (a negative zero, a signalling NaN).
  476. let bits = self.int_bits(ty)?;
  477. let (ka, kb) = (self.int_k(a).map(|k| k.1), self.int_k(b).map(|k| k.1));
  478. let all = mask(bits);
  479. if let (Some(x), Some(y)) = (ka, kb) {
  480. // A shift by the width or more and a division by zero
  481. // have no defined result: left as they are.
  482. let amount = u32::try_from(y).ok().filter(|&y| y < bits);
  483. let r = match op {
  484. Bin::Add => x.wrapping_add(y),
  485. Bin::Sub => x.wrapping_sub(y),
  486. Bin::Mul => x.wrapping_mul(y),
  487. Bin::And => x & y,
  488. Bin::Or => x | y,
  489. Bin::Xor => x ^ y,
  490. Bin::Shl => x << amount?,
  491. Bin::LShr => x >> amount?,
  492. Bin::AShr => (signed(bits, x) >> amount?) as u64,
  493. Bin::UDiv if y != 0 => x / y,
  494. Bin::URem if y != 0 => x % y,
  495. _ => return None,
  496. };
  497. return Some(self.k(ty, bits, r));
  498. }
  499. match (op, ka, kb) {
  500. (
  501. Bin::Add | Bin::Sub | Bin::Or | Bin::Xor | Bin::Shl | Bin::LShr | Bin::AShr,
  502. _,
  503. Some(0),
  504. ) => Some(a),
  505. (Bin::Add | Bin::Or | Bin::Xor, Some(0), _) => Some(b),
  506. (Bin::Mul | Bin::UDiv, _, Some(1)) => Some(a),
  507. (Bin::Mul, Some(1), _) => Some(b),
  508. (Bin::Mul | Bin::And, _, Some(0)) => Some(b),
  509. (Bin::Mul | Bin::And, Some(0), _) => Some(a),
  510. (Bin::And, _, Some(m)) if m == all => Some(a),
  511. (Bin::And, Some(m), _) if m == all => Some(b),
  512. (Bin::Or, _, Some(m)) if m == all => Some(b),
  513. (Bin::Or, Some(m), _) if m == all => Some(a),
  514. (Bin::And | Bin::Or, _, _) if a == b => Some(a),
  515. _ => None,
  516. }
  517. }
  518. Op::Cmp(p, a, b) if p <= pred::TRUE => {
  519. // Two float constants compare one way (`v_mul_legacy` asks
  520. // whether its constant factor is zero).
  521. let (V::Const(x), V::Const(y)) = (a, b) else {
  522. return None;
  523. };
  524. let (Const::Float(x), Const::Float(y)) =
  525. (&self.consts[x as usize].1, &self.consts[y as usize].1)
  526. else {
  527. return None;
  528. };
  529. let (x, y) = (f32::from_bits(*x), f32::from_bits(*y));
  530. let unordered = x.is_nan() || y.is_nan();
  531. // Bits 0-2 of a predicate: equal, greater, less; bit 3:
  532. // or unordered.
  533. let holds = if unordered {
  534. p & 8 != 0
  535. } else {
  536. (p & 1 != 0 && x == y) || (p & 2 != 0 && x > y) || (p & 4 != 0 && x < y)
  537. };
  538. Some(self.bool(holds))
  539. }
  540. Op::Cmp(p, a, b) => {
  541. if !(pred::EQ..=pred::SLE).contains(&p) {
  542. return None;
  543. }
  544. let holds = |x: u64, y: u64, bits: u32| {
  545. let (sx, sy) = (signed(bits, x), signed(bits, y));
  546. match p {
  547. pred::EQ => x == y,
  548. pred::NE => x != y,
  549. pred::IUGT => x > y,
  550. pred::IUGE => x >= y,
  551. pred::IULT => x < y,
  552. pred::IULE => x <= y,
  553. pred::SGT => sx > sy,
  554. pred::SGE => sx >= sy,
  555. pred::SLT => sx < sy,
  556. _ => sx <= sy,
  557. }
  558. };
  559. if let (Some((bits, x)), Some((_, y))) = (self.int_k(a), self.int_k(b)) {
  560. return Some(self.bool(holds(x, y, bits)));
  561. }
  562. if a == b {
  563. return Some(self.bool(holds(0, 0, 32)));
  564. }
  565. // A bit widened and tested again is the bit.
  566. if p == pred::NE
  567. && self.int_k(b).is_some_and(|k| k.1 == 0)
  568. && let V::Inst(z) = a
  569. && let Op::Cast(Cast::ZExt, x) = self.insts[z as usize].op
  570. && self.type_of(x) == ty
  571. {
  572. return Some(x);
  573. }
  574. None
  575. }
  576. Op::Select(c, mut t, mut f) => {
  577. if let Some((_, c)) = self.int_k(c) {
  578. return Some(if c != 0 { t } else { f });
  579. }
  580. // Under the same condition an inner select is one of its
  581. // operands (two guarded writes of one register in a row).
  582. let mut inner = false;
  583. while let V::Inst(x) = t
  584. && let Op::Select(c2, t2, _) = self.insts[x as usize].op
  585. && c2 == c
  586. {
  587. (t, inner) = (t2, true);
  588. }
  589. while let V::Inst(x) = f
  590. && let Op::Select(c2, _, f2) = self.insts[x as usize].op
  591. && c2 == c
  592. {
  593. (f, inner) = (f2, true);
  594. }
  595. if t == f {
  596. return Some(t);
  597. }
  598. if self.int_bits(ty) == Some(1)
  599. && self.int_k(t).is_some_and(|k| k.1 == 1)
  600. && self.int_k(f).is_some_and(|k| k.1 == 0)
  601. {
  602. return Some(c);
  603. }
  604. if inner {
  605. self.insts[i as usize].op = Op::Select(c, t, f);
  606. *changed = true;
  607. }
  608. None
  609. }
  610. Op::Cast(op, x) => {
  611. let from = self.type_of(x);
  612. let through = match x {
  613. V::Inst(y) => match self.insts[y as usize].op {
  614. Op::Cast(op2, z) => Some((op2, z)),
  615. _ => None,
  616. },
  617. _ => None,
  618. };
  619. match op {
  620. Cast::Bitcast => {
  621. if from == ty {
  622. return Some(x);
  623. }
  624. // There and back: the bits are the same.
  625. if let Some((Cast::Bitcast, z)) = through
  626. && self.type_of(z) == ty
  627. {
  628. return Some(z);
  629. }
  630. let V::Const(c) = x else { return None };
  631. let to_float = matches!(self.types[ty.0 as usize], TypeDef::Float);
  632. match self.consts[c as usize].1 {
  633. Const::Int(bits) if to_float && self.int_bits(from) == Some(32) => {
  634. Some(self.f32(bits as u32))
  635. }
  636. Const::Float(bits) if self.int_bits(ty) == Some(32) => {
  637. Some(self.int_const(ty, i64::from(bits as i32)))
  638. }
  639. _ => None,
  640. }
  641. }
  642. Cast::ZExt | Cast::SExt | Cast::Trunc => {
  643. let to = self.int_bits(ty)?;
  644. if let Some((bits, k)) = self.int_k(x) {
  645. let k = if op == Cast::SExt {
  646. signed(bits, k) as u64
  647. } else {
  648. k
  649. };
  650. return Some(self.k(ty, to, k));
  651. }
  652. // Widened and narrowed again.
  653. if op == Cast::Trunc
  654. && let Some((Cast::ZExt | Cast::SExt, z)) = through
  655. && self.type_of(z) == ty
  656. {
  657. return Some(z);
  658. }
  659. None
  660. }
  661. _ => None,
  662. }
  663. }
  664. _ => None,
  665. }
  666. }
  667. /// What kind of instruction `i` is for merging.
  668. fn class(&self, effects: &[Effect], i: u32) -> Effect {
  669. match &self.insts[i as usize].op {
  670. Op::Bin(..)
  671. | Op::Cast(..)
  672. | Op::Cmp(..)
  673. | Op::Select(..)
  674. | Op::Extract(..)
  675. | Op::Gep(..) => Effect::Pure,
  676. Op::Load(p) => {
  677. // A constant table reads the same whatever is stored.
  678. let base = match *p {
  679. V::Inst(g) => match &self.insts[g as usize].op {
  680. Op::Gep(_, base, _) => *base,
  681. _ => *p,
  682. },
  683. _ => *p,
  684. };
  685. match base {
  686. V::Global(g) if self.globals[g as usize].init.is_some() => Effect::Pure,
  687. _ => Effect::Reads,
  688. }
  689. }
  690. Op::Store(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => Effect::Writes,
  691. Op::Phi(_) => Effect::Lanes,
  692. Op::Call(f, _) => effects[*f as usize],
  693. }
  694. }
  695. fn key(&self, i: u32) -> Option<Key> {
  696. let inst = &self.insts[i as usize];
  697. Some(match &inst.op {
  698. Op::Bin(op, a, b) => {
  699. // Integer sums, products and bit operations whichever way
  700. // round; float ones as written (which NaN an operation of
  701. // two NaNs gives is the hardware's choice by operand).
  702. let commutes = matches!(op, Bin::Add | Bin::Mul | Bin::And | Bin::Or | Bin::Xor)
  703. && self.int_bits(inst.ty).is_some();
  704. let (a, b) = if commutes && b < a {
  705. (*b, *a)
  706. } else {
  707. (*a, *b)
  708. };
  709. Key::Bin(*op as u8, a, b)
  710. }
  711. Op::Cast(op, v) => Key::Cast(*op as u8, inst.ty, *v),
  712. Op::Cmp(p, a, b) => Key::Cmp(*p, *a, *b),
  713. Op::Select(c, t, f) => Key::Select(*c, *t, *f),
  714. Op::Extract(a, n) => Key::Extract(*a, *n),
  715. Op::Call(f, args) => Key::Call(*f, args.clone()),
  716. Op::Gep(ty, p, idx) => Key::Gep(*ty, *p, idx.clone()),
  717. Op::Load(p) => Key::Load(*p),
  718. _ => return None,
  719. })
  720. }
  721. /// [`FOLD`], [`REUSE`], [`FACTS`] and [`LOADS`]: one walk over the
  722. /// dominator tree. Returns whether anything changed.
  723. fn merge(&mut self, passes: u32) -> bool {
  724. if self.blocks.is_empty() {
  725. return false;
  726. }
  727. let effects = self.effects();
  728. let tree = self.dominator_tree();
  729. let mut repl: Vec<Option<V>> = vec![None; self.insts.len()];
  730. let mut changed = false;
  731. // Joins of one value: until none is left (one gone can leave
  732. // another with one value).
  733. if passes & FOLD != 0 {
  734. let mut again = true;
  735. while again {
  736. again = false;
  737. for &b in &tree.order {
  738. for &p in &self.blocks[b].phis {
  739. if repl[p as usize].is_some() {
  740. continue;
  741. }
  742. let Op::Phi(incoming) = &self.insts[p as usize].op else {
  743. continue;
  744. };
  745. let mut one = None;
  746. let mut same = true;
  747. for &(v, _) in incoming {
  748. let v = resolve(&repl, v);
  749. if v == V::Inst(p) {
  750. continue;
  751. }
  752. match one {
  753. None => one = Some(v),
  754. Some(o) if o == v => {}
  755. Some(_) => same = false,
  756. }
  757. }
  758. if let (true, Some(v)) = (same, one) {
  759. repl[p as usize] = Some(v);
  760. again = true;
  761. changed = true;
  762. }
  763. }
  764. }
  765. }
  766. }
  767. // The values every path to the block being walked has computed
  768. // (those of the blocks above it in the tree, and its own so far).
  769. let mut known: HashMap<Key, V> = HashMap::new();
  770. // The reads of the block being walked since its last store.
  771. let mut read: HashMap<Key, V> = HashMap::new();
  772. let mut facts = Facts::default();
  773. let (yes, no) = (self.bool(true), self.bool(false));
  774. enum Step {
  775. Enter(usize),
  776. Leave(Vec<Key>, Learned),
  777. }
  778. let mut steps = vec![Step::Enter(0)];
  779. while let Some(step) = steps.pop() {
  780. let b = match step {
  781. Step::Enter(b) => b,
  782. Step::Leave(keys, learned) => {
  783. for k in keys {
  784. known.remove(&k);
  785. }
  786. for v in learned.bits {
  787. facts.bits.remove(&v);
  788. }
  789. for k in learned.compares {
  790. facts.compares.remove(&k);
  791. }
  792. continue;
  793. }
  794. };
  795. let mut added = Vec::new();
  796. // Reached from one block alone, by one side of its branch: the
  797. // condition is that side's, here and in every block below.
  798. let mut learned = Learned::default();
  799. if passes & FACTS != 0
  800. && let [p] = tree.preds[b][..]
  801. && let Some(Term::CondBr(c, t, f)) = self.blocks[p].term
  802. && t != f
  803. {
  804. self.learn(resolve(&repl, c), b == t, &mut facts, &mut learned, 8);
  805. }
  806. let known_bit = |facts: &Facts, v: V| match facts.bits.get(&v) {
  807. Some(true) => yes,
  808. Some(false) => no,
  809. None => v,
  810. };
  811. read.clear();
  812. // Two joins of the same values from the same blocks are one.
  813. if passes & REUSE != 0 && self.blocks[b].phis.len() > 1 {
  814. let mut joins: HashMap<Vec<(usize, V)>, V> = HashMap::new();
  815. for &p in &self.blocks[b].phis {
  816. if repl[p as usize].is_some() {
  817. continue;
  818. }
  819. let ty = self.insts[p as usize].ty;
  820. let Op::Phi(incoming) = &self.insts[p as usize].op else {
  821. continue;
  822. };
  823. let mut key: Vec<(usize, V)> = incoming
  824. .iter()
  825. .map(|&(v, from)| (from, resolve(&repl, v)))
  826. .collect();
  827. key.sort();
  828. // The type too: an undefined value of one type is not
  829. // that of another.
  830. key.push((ty.0 as usize, V::Global(u32::MAX)));
  831. match joins.get(&key) {
  832. Some(&first) => {
  833. repl[p as usize] = Some(first);
  834. changed = true;
  835. }
  836. None => {
  837. joins.insert(key, V::Inst(p));
  838. }
  839. }
  840. }
  841. }
  842. let body = std::mem::take(&mut self.blocks[b].body);
  843. let mut kept = Vec::with_capacity(body.len());
  844. for i in body {
  845. map_operands(&mut self.insts[i as usize].op, |v| {
  846. let v = resolve(&repl, v);
  847. let bit = known_bit(&facts, v);
  848. changed |= bit != v;
  849. bit
  850. });
  851. if let Op::Cmp(p, x, y) = self.insts[i as usize].op
  852. && let Some(&holds) = facts.compares.get(&(p, x, y))
  853. {
  854. repl[i as usize] = Some(if holds { yes } else { no });
  855. changed = true;
  856. continue;
  857. }
  858. if passes & FOLD != 0
  859. && let Some(v) = self.simplify(i, &mut changed)
  860. {
  861. repl[i as usize] = Some(v);
  862. changed = true;
  863. continue;
  864. }
  865. let class = self.class(&effects, i);
  866. if passes & REUSE != 0
  867. && class == Effect::Pure
  868. && let Some(key) = self.key(i)
  869. {
  870. if let Some(&first) = known.get(&key) {
  871. repl[i as usize] = Some(first);
  872. changed = true;
  873. continue;
  874. }
  875. known.insert(key.clone(), V::Inst(i));
  876. added.push(key);
  877. }
  878. // Reads of memory, and wave operations (the same lanes run
  879. // the whole block): the block's own earlier one.
  880. if passes & LOADS != 0
  881. && matches!(class, Effect::Reads | Effect::Lanes)
  882. && let Some(key) = self.key(i)
  883. {
  884. if let Some(&first) = read.get(&key) {
  885. repl[i as usize] = Some(first);
  886. changed = true;
  887. continue;
  888. }
  889. read.insert(key, V::Inst(i));
  890. }
  891. if class == Effect::Writes {
  892. read.clear();
  893. }
  894. kept.push(i);
  895. }
  896. self.blocks[b].body = kept;
  897. if let Some(Term::CondBr(c, t, f)) = self.blocks[b].term {
  898. let c = known_bit(&facts, resolve(&repl, c));
  899. self.blocks[b].term = Some(Term::CondBr(c, t, f));
  900. }
  901. steps.push(Step::Leave(added, learned));
  902. for &c in tree.children[b].iter().rev() {
  903. steps.push(Step::Enter(c));
  904. }
  905. }
  906. if !changed {
  907. return false;
  908. }
  909. // Everything that read a replaced value reads its replacement
  910. // (joins read values from blocks walked after them).
  911. for blk in &mut self.blocks {
  912. blk.phis.retain(|&p| repl[p as usize].is_none());
  913. if let Some(Term::CondBr(c, t, f)) = blk.term {
  914. blk.term = Some(Term::CondBr(resolve(&repl, c), t, f));
  915. }
  916. }
  917. let (blocks, insts) = (&self.blocks, &mut self.insts);
  918. for blk in blocks {
  919. for &i in blk.phis.iter().chain(&blk.body) {
  920. map_operands(&mut insts[i as usize].op, |v| resolve(&repl, v));
  921. }
  922. }
  923. true
  924. }
  925. /// [`FOLD`]: a branch on a constant goes one way. The side not taken
  926. /// loses the branching block's values at its joins, and so do the joins
  927. /// of blocks that nothing reaches any more. Returns whether a branch
  928. /// changed.
  929. fn prune(&mut self) -> bool {
  930. let mut changed = false;
  931. for b in 0..self.blocks.len() {
  932. let Some(Term::CondBr(c, t, f)) = self.blocks[b].term else {
  933. continue;
  934. };
  935. // Both sides one block: two edges into it, left as they are.
  936. if t == f {
  937. continue;
  938. }
  939. let Some((_, k)) = self.int_k(c) else {
  940. continue;
  941. };
  942. let (taken, not) = if k != 0 { (t, f) } else { (f, t) };
  943. self.blocks[b].term = Some(Term::Br(taken));
  944. changed = true;
  945. for n in 0..self.blocks[not].phis.len() {
  946. let p = self.blocks[not].phis[n];
  947. if let Op::Phi(incoming) = &mut self.insts[p as usize].op {
  948. incoming.retain(|&(_, from)| from != b);
  949. }
  950. }
  951. }
  952. if !changed {
  953. return false;
  954. }
  955. let reached = self.reached();
  956. let (blocks, insts) = (&self.blocks, &mut self.insts);
  957. for (_, blk) in blocks.iter().enumerate().filter(|(b, _)| reached[*b]) {
  958. for &p in &blk.phis {
  959. if let Op::Phi(incoming) = &mut insts[p as usize].op {
  960. incoming.retain(|&(_, from)| reached[from]);
  961. }
  962. }
  963. }
  964. true
  965. }
  966. /// Whether instruction `i` must stay whatever reads it.
  967. fn has_effect(&self, effects: &[Effect], i: u32) -> bool {
  968. match &self.insts[i as usize].op {
  969. Op::Store(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => true,
  970. Op::Call(f, _) => effects[*f as usize] == Effect::Writes,
  971. _ => false,
  972. }
  973. }
  974. /// [`DEAD`]: keeps the instructions with an effect, the branch
  975. /// conditions, and what they read, transitively; the rest leave their
  976. /// blocks. Blocks no branch reaches are emptied (they are not written).
  977. fn drop_dead(&mut self) {
  978. let effects = self.effects();
  979. let reached = self.reached();
  980. let mut live = vec![false; self.insts.len()];
  981. let mut work: Vec<u32> = Vec::new();
  982. let mark = |live: &mut [bool], work: &mut Vec<u32>, v: V| {
  983. if let V::Inst(i) = v
  984. && !live[i as usize]
  985. {
  986. live[i as usize] = true;
  987. work.push(i);
  988. }
  989. };
  990. for (b, blk) in self.blocks.iter().enumerate() {
  991. if !reached[b] {
  992. continue;
  993. }
  994. for &i in &blk.body {
  995. if self.has_effect(&effects, i) {
  996. mark(&mut live, &mut work, V::Inst(i));
  997. }
  998. }
  999. if let Some(Term::CondBr(c, ..)) = blk.term {
  1000. mark(&mut live, &mut work, c);
  1001. }
  1002. }
  1003. while let Some(i) = work.pop() {
  1004. for_each_operand(&self.insts[i as usize].op, |v| {
  1005. mark(&mut live, &mut work, v)
  1006. });
  1007. }
  1008. for (b, blk) in self.blocks.iter_mut().enumerate() {
  1009. if reached[b] {
  1010. blk.body.retain(|&i| live[i as usize]);
  1011. blk.phis.retain(|&i| live[i as usize]);
  1012. } else {
  1013. blk.body.clear();
  1014. blk.phis.clear();
  1015. }
  1016. }
  1017. self.drop_unused_functions();
  1018. self.drop_unused_tables();
  1019. }
  1020. /// See [`Usage`]: over the blocks reached from the entry.
  1021. pub(crate) fn usage(&self) -> Usage {
  1022. let mut u = Usage::default();
  1023. let reached = self.reached();
  1024. let wide = |ty: Ty| self.types[ty.0 as usize] == TypeDef::Int(64);
  1025. // The first field of a handle's annotation: its kind, with the UAV
  1026. // bit; the second: the component type and count.
  1027. let annotation = |h: V| -> Option<(i64, i64)> {
  1028. let V::Inst(a) = h else { return None };
  1029. let Op::Call(f, args) = &self.insts[a as usize].op else {
  1030. return None;
  1031. };
  1032. if self.funcs[*f as usize].name != "dx.op.annotateHandle" {
  1033. return None;
  1034. }
  1035. let V::Const(props) = *args.get(2)? else {
  1036. return None;
  1037. };
  1038. let Const::Aggregate(fields) = &self.consts[props as usize].1 else {
  1039. return None;
  1040. };
  1041. match (
  1042. &self.consts[fields[0] as usize].1,
  1043. &self.consts[fields[1] as usize].1,
  1044. ) {
  1045. (Const::Int(kind), Const::Int(components)) => Some((*kind, *components)),
  1046. _ => None,
  1047. }
  1048. };
  1049. for (_, blk) in self.blocks.iter().enumerate().filter(|(b, _)| reached[*b]) {
  1050. for &i in blk.phis.iter().chain(&blk.body) {
  1051. let inst = &self.insts[i as usize];
  1052. u.int64 |= wide(inst.ty);
  1053. for_each_operand(&inst.op, |v| u.int64 |= wide(self.type_of(v)));
  1054. let Op::Call(f, args) = &inst.op else {
  1055. continue;
  1056. };
  1057. let name = self.funcs[*f as usize].name.as_str();
  1058. let name = name.strip_prefix("dx.op.").unwrap_or(name);
  1059. if name.starts_with("wave") || name.starts_with("quad") {
  1060. u.wave_ops = true;
  1061. } else if name == "createHandleFromHeap" {
  1062. match args.get(2).and_then(|&s| self.int_k(s)) {
  1063. Some((_, 0)) => u.heap_views = true,
  1064. _ => u.heap_samplers = true,
  1065. }
  1066. } else if name == "annotateHandle" {
  1067. u.rovs |= annotation(V::Inst(i)).is_some_and(|(kind, _)| kind & 0x2000 != 0);
  1068. } else if name.starts_with("atomic") && name.ends_with(".i64") {
  1069. u.atomic64 = true;
  1070. } else if name.starts_with("textureLoad") || name.starts_with("bufferLoad") {
  1071. u.typed_uav_loads |= args.get(1).and_then(|&h| annotation(h)).is_none_or(
  1072. |(kind, components)| kind & 0x1000 != 0 && components >> 8 & 0xff > 1,
  1073. );
  1074. }
  1075. }
  1076. }
  1077. u
  1078. }
  1079. /// A constant table no remaining load reads leaves the module (the
  1080. /// validator refuses an internal declaration nothing uses). Shared
  1081. /// memory stays declared whether it is read or not.
  1082. fn drop_unused_tables(&mut self) {
  1083. let mut used: Vec<bool> = self.globals.iter().map(|g| g.init.is_none()).collect();
  1084. if used.iter().all(|&u| u) {
  1085. return;
  1086. }
  1087. for blk in &self.blocks {
  1088. for &i in blk.phis.iter().chain(&blk.body) {
  1089. for_each_operand(&self.insts[i as usize].op, |v| {
  1090. if let V::Global(g) = v {
  1091. used[g as usize] = true;
  1092. }
  1093. });
  1094. }
  1095. }
  1096. for md in &self.mds {
  1097. if let MdDef::Value(_, V::Global(g)) = md {
  1098. used[*g as usize] = true;
  1099. }
  1100. }
  1101. if used.iter().all(|&u| u) {
  1102. return;
  1103. }
  1104. let mut new = vec![u32::MAX; used.len()];
  1105. for (next, (old, _)) in used.iter().enumerate().filter(|u| *u.1).enumerate() {
  1106. new[old] = next as u32;
  1107. }
  1108. let mut old = 0;
  1109. self.globals.retain(|_| {
  1110. old += 1;
  1111. used[old - 1]
  1112. });
  1113. let renumber = |v: V| match v {
  1114. V::Global(g) if used[g as usize] => V::Global(new[g as usize]),
  1115. v => v,
  1116. };
  1117. for inst in &mut self.insts {
  1118. map_operands(&mut inst.op, renumber);
  1119. }
  1120. for md in &mut self.mds {
  1121. if let MdDef::Value(_, v) = md {
  1122. *v = renumber(*v);
  1123. }
  1124. }
  1125. }
  1126. /// Declarations no remaining call names leave the module (the validator
  1127. /// refuses an external function nothing uses); the others keep their
  1128. /// order, so `main` stays function 0.
  1129. fn drop_unused_functions(&mut self) {
  1130. let mut used: Vec<bool> = self.funcs.iter().map(|f| f.body).collect();
  1131. for blk in &self.blocks {
  1132. for &i in blk.phis.iter().chain(&blk.body) {
  1133. if let Op::Call(f, _) = self.insts[i as usize].op {
  1134. used[f as usize] = true;
  1135. }
  1136. }
  1137. }
  1138. for md in &self.mds {
  1139. if let MdDef::Value(_, V::Func(f)) = md {
  1140. used[*f as usize] = true;
  1141. }
  1142. }
  1143. if used.iter().all(|&u| u) {
  1144. return;
  1145. }
  1146. let mut new = vec![u32::MAX; used.len()];
  1147. for (next, (old, _)) in used.iter().enumerate().filter(|u| *u.1).enumerate() {
  1148. new[old] = next as u32;
  1149. }
  1150. let mut old = 0;
  1151. self.funcs.retain(|_| {
  1152. old += 1;
  1153. used[old - 1]
  1154. });
  1155. self.func_ids = self
  1156. .funcs
  1157. .iter()
  1158. .enumerate()
  1159. .map(|(i, f)| (f.name.clone(), i as u32))
  1160. .collect();
  1161. // Instructions that left their block keep a stale number: nothing
  1162. // reads them again.
  1163. for inst in &mut self.insts {
  1164. if let Op::Call(f, _) = &mut inst.op
  1165. && used[*f as usize]
  1166. {
  1167. *f = new[*f as usize];
  1168. }
  1169. }
  1170. for md in &mut self.mds {
  1171. if let MdDef::Value(_, V::Func(f)) = md {
  1172. *f = new[*f as usize];
  1173. }
  1174. }
  1175. }
  1176. }
  1177. #[cfg(test)]
  1178. mod tests {
  1179. use super::*;
  1180. /// `main` with one block and a function of each kind of effect.
  1181. struct Kit {
  1182. m: Module,
  1183. b: usize,
  1184. pure: V,
  1185. reads: V,
  1186. writes: V,
  1187. }
  1188. fn kit() -> Kit {
  1189. let mut m = Module::default();
  1190. let i32t = m.int(32);
  1191. let void = m.void();
  1192. let fty = m.func_ty(i32t, vec![i32t, i32t]);
  1193. m.ptr(fty);
  1194. let pure = m.function("dx.op.binary.i32", fty, Some(Attr::ReadNone), false);
  1195. let reads = m.function("dx.op.bufferLoad.i32", fty, Some(Attr::ReadOnly), false);
  1196. let writes = m.function("dx.op.bufferStore.i32", fty, Some(Attr::NoUnwind), false);
  1197. let main_ty = m.func_ty(void, vec![]);
  1198. m.ptr(main_ty);
  1199. m.function("main", main_ty, None, true);
  1200. let b = m.new_block();
  1201. Kit {
  1202. m,
  1203. b,
  1204. pure,
  1205. reads,
  1206. writes,
  1207. }
  1208. }
  1209. fn body(m: &Module, b: usize) -> usize {
  1210. m.blocks[b].body.len()
  1211. }
  1212. #[test]
  1213. fn unread_results_without_effect_are_dropped() {
  1214. let Kit {
  1215. mut m,
  1216. b,
  1217. pure,
  1218. reads,
  1219. writes,
  1220. } = kit();
  1221. let (one, two) = (m.i32(1), m.i32(2));
  1222. let used = m.call(b, reads, vec![one, two]);
  1223. let dead = m.call(b, reads, vec![two, one]);
  1224. let chain = m.bin(b, Bin::Add, dead, one);
  1225. let _unread = m.call(b, pure, vec![chain, two]);
  1226. // A store's result is unread and stays, with what it reads.
  1227. let kept = m.bin(b, Bin::Add, used, two);
  1228. m.call(b, writes, vec![kept, one]);
  1229. m.terminate(b, Term::Ret);
  1230. m.optimise(DEAD);
  1231. assert_eq!(body(&m, b), 3, "the load, the add and the store");
  1232. m.write();
  1233. }
  1234. #[test]
  1235. fn branch_conditions_and_phi_cycles() {
  1236. let Kit {
  1237. mut m,
  1238. b,
  1239. reads,
  1240. writes,
  1241. ..
  1242. } = kit();
  1243. let i32t = m.int(32);
  1244. let (zero, one) = (m.i32(0), m.i32(1));
  1245. let (head, exit) = (m.new_block(), m.new_block());
  1246. m.terminate(b, Term::Br(head));
  1247. // A counter that decides the branch, and a register that only
  1248. // feeds itself round the loop.
  1249. let count = m.phi(head, i32t);
  1250. let idle = m.phi(head, i32t);
  1251. let next = m.bin(head, Bin::Add, count, one);
  1252. let idle_next = m.call(head, reads, vec![idle, one]);
  1253. let more = m.cmp(head, pred::IULT, next, one);
  1254. m.terminate(head, Term::CondBr(more, head, exit));
  1255. m.set_phi(count, vec![(zero, b), (next, head)]);
  1256. m.set_phi(idle, vec![(zero, b), (idle_next, head)]);
  1257. m.call(exit, writes, vec![zero, one]);
  1258. m.terminate(exit, Term::Ret);
  1259. m.optimise(DEAD);
  1260. assert_eq!(m.blocks[head].phis.len(), 1, "the counter");
  1261. assert_eq!(body(&m, head), 2, "the step and the test");
  1262. assert_eq!(body(&m, exit), 1);
  1263. m.write();
  1264. }
  1265. #[test]
  1266. fn wave_operations_have_no_effect_of_their_own() {
  1267. let mut k = kit();
  1268. let i32t = k.m.int(32);
  1269. let fty = k.m.func_ty(i32t, vec![i32t, i32t]);
  1270. let first = k.m.function(
  1271. "dx.op.waveReadLaneFirst.i32",
  1272. fty,
  1273. Some(Attr::NoUnwind),
  1274. false,
  1275. );
  1276. let barrier =
  1277. k.m.function("dx.op.barrier", fty, Some(Attr::NoDuplicate), false);
  1278. let one = k.m.i32(1);
  1279. k.m.call(k.b, first, vec![one, one]);
  1280. k.m.call(k.b, barrier, vec![one, one]);
  1281. k.m.terminate(k.b, Term::Ret);
  1282. k.m.optimise(DEAD);
  1283. assert_eq!(body(&k.m, k.b), 1, "the barrier");
  1284. // The declarations nothing calls any more are gone, and the call
  1285. // that stayed names its function by the new number.
  1286. let names: Vec<&str> = k.m.funcs.iter().map(|f| f.name.as_str()).collect();
  1287. assert_eq!(names, ["main", "dx.op.barrier"]);
  1288. let Op::Call(f, _) = k.m.insts[k.m.blocks[k.b].body[0] as usize].op else {
  1289. panic!("a call");
  1290. };
  1291. assert_eq!(k.m.funcs[f as usize].name, "dx.op.barrier");
  1292. k.m.write();
  1293. }
  1294. /// The operands of each store left in block `b`.
  1295. fn stores(m: &Module, b: usize) -> Vec<Vec<V>> {
  1296. m.blocks[b]
  1297. .body
  1298. .iter()
  1299. .filter_map(|&i| match &m.insts[i as usize].op {
  1300. Op::Call(g, args) if m.funcs[*g as usize].name.contains("Store") => {
  1301. Some(args.clone())
  1302. }
  1303. _ => None,
  1304. })
  1305. .collect()
  1306. }
  1307. #[test]
  1308. fn constants_and_identities_fold() {
  1309. let Kit {
  1310. mut m,
  1311. b,
  1312. reads,
  1313. writes,
  1314. ..
  1315. } = kit();
  1316. let (i32t, f32t) = (m.int(32), m.float());
  1317. let (zero, one, all) = (m.i32(0), m.i32(1), m.i32(u32::MAX));
  1318. let x = m.call(b, reads, vec![one, one]);
  1319. // x + 0, -1 & x, x >> 0, x * 1, x | x: all x.
  1320. let a = m.bin(b, Bin::Add, x, zero);
  1321. let a = m.bin(b, Bin::And, all, a);
  1322. let a = m.bin(b, Bin::LShr, a, zero);
  1323. let a = m.bin(b, Bin::Mul, a, one);
  1324. let a = m.bin(b, Bin::Or, a, a);
  1325. // There and back.
  1326. let f = m.cast(b, Cast::Bitcast, a, f32t);
  1327. let a = m.cast(b, Cast::Bitcast, f, i32t);
  1328. // Constants: (262168 >> 16) & 127 = 4, 7 & 31 = 7, -8 >>s 1 = -4.
  1329. let k = m.i32(262168);
  1330. let sixteen = m.i32(16);
  1331. let k = m.bin(b, Bin::LShr, k, sixteen);
  1332. let k127 = m.i32(127);
  1333. let k = m.bin(b, Bin::And, k, k127);
  1334. let minus8 = m.i32(-8i32 as u32);
  1335. let s = m.bin(b, Bin::AShr, minus8, one);
  1336. // A shift by the width is left alone.
  1337. let k32 = m.i32(32);
  1338. let wide = m.bin(b, Bin::Shl, one, k32);
  1339. // A select between a value and itself, and on a constant.
  1340. let c = m.cmp(b, pred::IULT, zero, one);
  1341. let sel = m.select(b, c, a, wide);
  1342. let same = m.select(b, c, sel, sel);
  1343. m.call(b, writes, vec![same, k]);
  1344. m.call(b, writes, vec![s, wide]);
  1345. m.terminate(b, Term::Ret);
  1346. m.optimise(FOLD | DEAD);
  1347. assert_eq!(body(&m, b), 4, "the read, the wide shift and two stores");
  1348. let four = m.i32(4);
  1349. let minus4 = m.i32(-4i32 as u32);
  1350. let stores = stores(&m, b);
  1351. assert_eq!(stores, [vec![x, four], vec![minus4, wide]]);
  1352. m.write();
  1353. }
  1354. #[test]
  1355. fn float_arithmetic_is_not_folded() {
  1356. let Kit {
  1357. mut m, b, writes, ..
  1358. } = kit();
  1359. let f32t = m.float();
  1360. let fty = m.func_ty(f32t, vec![f32t, f32t]);
  1361. let input = m.function("dx.op.loadInput.f32", fty, Some(Attr::ReadNone), false);
  1362. let (zero, one, two) = (m.f32(0), m.f32(1.0f32.to_bits()), m.f32(2.0f32.to_bits()));
  1363. let x = m.call(b, input, vec![zero, zero]);
  1364. let y = m.call(b, input, vec![one, one]);
  1365. let a = m.bin(b, Bin::Add, x, zero);
  1366. let p = m.bin(b, Bin::Mul, a, one);
  1367. // The same sum the other way round is another instruction.
  1368. let xy = m.bin(b, Bin::Add, x, y);
  1369. let yx = m.bin(b, Bin::Add, y, x);
  1370. // Constants compare here: 1 < 2, and nothing equals a NaN.
  1371. let nan = m.f32(f32::NAN.to_bits());
  1372. let lt = m.cmp(b, pred::OLT, one, two);
  1373. let eq = m.cmp(b, pred::OEQ, nan, nan);
  1374. let une = m.cmp(b, pred::UNE, nan, one);
  1375. let sel = m.select(b, lt, xy, yx);
  1376. let sel = m.select(b, eq, p, sel);
  1377. let sel = m.select(b, une, sel, p);
  1378. m.call(b, writes, vec![sel, p]);
  1379. m.terminate(b, Term::Ret);
  1380. m.optimise(ALL);
  1381. // Two inputs, x + 0.0, * 1.0, x + y and the store: y + x and the
  1382. // selects are gone.
  1383. assert_eq!(body(&m, b), 6);
  1384. assert_eq!(stores(&m, b), [[xy, p]]);
  1385. m.write();
  1386. }
  1387. /// entry: `c = x < y`, branch to `then` or `other`, which join.
  1388. struct Diamond {
  1389. k: Kit,
  1390. x: V,
  1391. y: V,
  1392. c: V,
  1393. then: usize,
  1394. other: usize,
  1395. join: usize,
  1396. }
  1397. fn diamond() -> Diamond {
  1398. let mut k = kit();
  1399. let (one, two) = (k.m.i32(1), k.m.i32(2));
  1400. let x = k.m.call(k.b, k.reads, vec![one, one]);
  1401. let y = k.m.call(k.b, k.reads, vec![two, two]);
  1402. let c = k.m.cmp(k.b, pred::IULT, x, y);
  1403. let (then, other, join) = (k.m.new_block(), k.m.new_block(), k.m.new_block());
  1404. k.m.terminate(k.b, Term::CondBr(c, then, other));
  1405. k.m.terminate(then, Term::Br(join));
  1406. k.m.terminate(other, Term::Br(join));
  1407. k.m.terminate(join, Term::Ret);
  1408. Diamond {
  1409. k,
  1410. x,
  1411. y,
  1412. c,
  1413. then,
  1414. other,
  1415. join,
  1416. }
  1417. }
  1418. #[test]
  1419. fn a_value_is_reused_below_its_block_and_not_beside_it() {
  1420. let Diamond {
  1421. k:
  1422. Kit {
  1423. mut m,
  1424. b,
  1425. pure,
  1426. writes,
  1427. ..
  1428. },
  1429. x,
  1430. y,
  1431. then,
  1432. other,
  1433. join,
  1434. ..
  1435. } = diamond();
  1436. // The entry's value again in a branch; a branch's value again in
  1437. // the other branch and in the join (neither is on every path).
  1438. let top = m.call(b, pure, vec![x, y]);
  1439. m.call(b, writes, vec![top, top]);
  1440. let again = m.call(then, pure, vec![x, y]);
  1441. let side = m.bin(then, Bin::Add, y, x);
  1442. m.call(then, writes, vec![again, side]);
  1443. let beside = m.bin(other, Bin::Add, x, y);
  1444. m.call(other, writes, vec![beside, beside]);
  1445. let after = m.bin(join, Bin::Add, x, y);
  1446. m.call(join, writes, vec![after, after]);
  1447. m.optimise(REUSE);
  1448. assert_eq!(stores(&m, then), [[top, side]]);
  1449. assert_eq!(body(&m, then), 2);
  1450. assert_eq!(body(&m, other), 2);
  1451. assert_eq!(body(&m, join), 2);
  1452. m.write();
  1453. }
  1454. #[test]
  1455. fn a_branch_taken_says_what_its_condition_is() {
  1456. let Diamond {
  1457. k:
  1458. Kit {
  1459. mut m,
  1460. b,
  1461. reads,
  1462. writes,
  1463. ..
  1464. },
  1465. x,
  1466. y,
  1467. c,
  1468. then,
  1469. other,
  1470. join,
  1471. } = diamond();
  1472. let three = m.i32(3);
  1473. let d = m.call(b, reads, vec![three, three]);
  1474. let d = m.cmp(b, pred::NE, d, three);
  1475. let both = m.bin(b, Bin::And, c, d);
  1476. // Behind the branch: the condition again (a guard), its opposite
  1477. // comparison, and a guarded write.
  1478. let guard = m.bin(then, Bin::And, c, d);
  1479. let old = m.select(then, guard, x, y);
  1480. let not = m.cmp(then, pred::IUGE, x, y);
  1481. let new = m.select(then, not, y, old);
  1482. m.call(then, writes, vec![new, new]);
  1483. let kept = m.select(other, c, x, y);
  1484. m.call(other, writes, vec![kept, kept]);
  1485. // After the join nothing is known.
  1486. let open = m.select(join, c, x, y);
  1487. m.call(join, writes, vec![open, open]);
  1488. m.optimise(FOLD | FACTS);
  1489. // then: select(d, x, y) and the store; other: y is stored.
  1490. assert_eq!(body(&m, then), 2);
  1491. let V::Inst(sel) = stores(&m, then)[0][0] else {
  1492. panic!()
  1493. };
  1494. assert!(matches!(m.insts[sel as usize].op, Op::Select(g, a, z) if (g, a, z) == (d, x, y)));
  1495. assert_eq!(stores(&m, other), [[y, y]]);
  1496. assert_eq!(body(&m, join), 2);
  1497. let _ = both;
  1498. m.write();
  1499. // Both terms of an `and` that held hold behind it.
  1500. let Diamond {
  1501. k:
  1502. Kit {
  1503. mut m,
  1504. b,
  1505. reads,
  1506. writes,
  1507. ..
  1508. },
  1509. x,
  1510. y,
  1511. c,
  1512. ..
  1513. } = diamond();
  1514. let three = m.i32(3);
  1515. let d = m.call(b, reads, vec![three, three]);
  1516. let d = m.cmp(b, pred::NE, d, three);
  1517. let both = m.bin(b, Bin::And, c, d);
  1518. let (inner, out) = (m.new_block(), m.new_block());
  1519. m.terminate(b, Term::CondBr(both, inner, out));
  1520. let a = m.select(inner, c, x, y);
  1521. let z = m.select(inner, d, a, y);
  1522. m.call(inner, writes, vec![z, z]);
  1523. m.terminate(inner, Term::Br(out));
  1524. // Where the `and` did not hold either term may.
  1525. let w = m.select(out, d, x, y);
  1526. m.call(out, writes, vec![w, w]);
  1527. m.terminate(out, Term::Ret);
  1528. m.optimise(FOLD | FACTS);
  1529. assert_eq!(stores(&m, inner), [[x, x]]);
  1530. assert_eq!(body(&m, out), 2);
  1531. m.write();
  1532. }
  1533. #[test]
  1534. fn a_branch_on_a_constant_goes_one_way() {
  1535. let Diamond {
  1536. k: Kit {
  1537. mut m, b, writes, ..
  1538. },
  1539. x,
  1540. y,
  1541. c,
  1542. then,
  1543. other,
  1544. join,
  1545. } = diamond();
  1546. let i32t = m.int(32);
  1547. // Behind the branch the same test again: its other side is never
  1548. // run, and the join behind it has one value.
  1549. let (deep, never, meet) = (m.new_block(), m.new_block(), m.new_block());
  1550. m.terminate(then, Term::CondBr(c, deep, never));
  1551. m.terminate(deep, Term::Br(meet));
  1552. m.call(never, writes, vec![y, y]);
  1553. m.terminate(never, Term::Br(meet));
  1554. let p = m.phi(meet, i32t);
  1555. m.set_phi(p, vec![(x, deep), (y, never)]);
  1556. m.call(meet, writes, vec![p, p]);
  1557. m.terminate(meet, Term::Br(join));
  1558. let q = m.phi(join, i32t);
  1559. m.set_phi(q, vec![(p, meet), (y, other)]);
  1560. m.call(join, writes, vec![q, q]);
  1561. m.optimise(ALL);
  1562. assert!(matches!(m.blocks[then].term, Some(Term::Br(t)) if t == deep));
  1563. assert_eq!(stores(&m, meet), [[x, x]]);
  1564. assert!(m.blocks[meet].phis.is_empty());
  1565. assert_eq!(body(&m, never), 0, "emptied: nothing reaches it");
  1566. let Op::Phi(incoming) = &m.insts[m.blocks[join].phis[0] as usize].op else {
  1567. panic!()
  1568. };
  1569. assert_eq!(incoming, &vec![(x, meet), (y, other)]);
  1570. let _ = b;
  1571. m.write();
  1572. }
  1573. #[test]
  1574. fn a_read_is_reused_within_its_block_until_a_store() {
  1575. let Diamond {
  1576. k:
  1577. Kit {
  1578. mut m,
  1579. b,
  1580. reads,
  1581. writes,
  1582. ..
  1583. },
  1584. x,
  1585. y,
  1586. then,
  1587. ..
  1588. } = diamond();
  1589. let i32t = m.int(32);
  1590. // The entry reads (1, 1) for x: again in the entry it is x; in the
  1591. // next block it is read again.
  1592. let one = m.i32(1);
  1593. let again = m.call(b, reads, vec![one, one]);
  1594. m.call(b, writes, vec![again, y]);
  1595. let after = m.call(b, reads, vec![one, one]);
  1596. let twice = m.call(b, reads, vec![one, one]);
  1597. let sum = m.bin(b, Bin::Add, after, twice);
  1598. m.call(b, writes, vec![sum, sum]);
  1599. let below = m.call(then, reads, vec![one, one]);
  1600. m.call(then, writes, vec![below, below]);
  1601. // A constant buffer cannot change: one load for the function.
  1602. let cfty = m.func_ty(i32t, vec![i32t, i32t]);
  1603. let cb = m.function(
  1604. "dx.op.cbufferLoadLegacy.i32",
  1605. cfty,
  1606. Some(Attr::ReadOnly),
  1607. false,
  1608. );
  1609. let top = m.call(b, cb, vec![one, one]);
  1610. m.call(b, writes, vec![top, top]);
  1611. let under = m.call(then, cb, vec![one, one]);
  1612. m.call(then, writes, vec![under, under]);
  1613. m.optimise(REUSE | LOADS);
  1614. let stores = stores(&m, b);
  1615. assert_eq!(stores[0], [x, y], "the second read is the first");
  1616. let V::Inst(sum) = stores[1][0] else { panic!() };
  1617. assert!(
  1618. matches!(m.insts[sum as usize].op, Op::Bin(Bin::Add, a, z) if a == after && z == after),
  1619. "read again after the store, once"
  1620. );
  1621. assert_eq!(stores[2], [top, top]);
  1622. assert_eq!(
  1623. super::tests::stores(&m, then),
  1624. [vec![below, below], vec![top, top]]
  1625. );
  1626. m.write();
  1627. }
  1628. #[test]
  1629. fn a_join_of_one_value_and_two_equal_joins() {
  1630. let Diamond {
  1631. k: Kit { mut m, writes, .. },
  1632. x,
  1633. y,
  1634. then,
  1635. other,
  1636. join,
  1637. ..
  1638. } = diamond();
  1639. let i32t = m.int(32);
  1640. let one = m.phi(join, i32t);
  1641. m.set_phi(one, vec![(x, then), (x, other)]);
  1642. let p = m.phi(join, i32t);
  1643. m.set_phi(p, vec![(x, then), (y, other)]);
  1644. let q = m.phi(join, i32t);
  1645. m.set_phi(q, vec![(y, other), (x, then)]);
  1646. m.call(join, writes, vec![one, p]);
  1647. let sum = m.bin(join, Bin::Add, p, q);
  1648. m.call(join, writes, vec![sum, q]);
  1649. m.optimise(FOLD | REUSE);
  1650. assert_eq!(
  1651. m.blocks[join].phis,
  1652. [match p {
  1653. V::Inst(i) => i,
  1654. _ => unreachable!(),
  1655. }]
  1656. );
  1657. let stores = stores(&m, join);
  1658. assert_eq!(stores[0], [x, p]);
  1659. assert_eq!(stores[1][1], p);
  1660. m.write();
  1661. }
  1662. // ---- the passes against an interpreter, on random programs ----
  1663. /// Runs `m` on `inputs`: the stores it makes, in order (and how it
  1664. /// ended). Reads a value before its definition ran: a panic.
  1665. fn run(m: &Module, inputs: &[u32]) -> Vec<(String, Vec<u64>)> {
  1666. let mut vals: Vec<Option<u64>> = vec![None; m.insts.len()];
  1667. let mut memory = [0u64; 16];
  1668. let mut trace = Vec::new();
  1669. let eval = |vals: &[Option<u64>], v: V| -> u64 {
  1670. match v {
  1671. V::Inst(i) => vals[i as usize].expect("a value defined before its use"),
  1672. V::Const(c) => {
  1673. match (&m.consts[c as usize].1, m.int_bits(m.consts[c as usize].0)) {
  1674. (Const::Int(x), Some(bits)) => *x as u64 & mask(bits),
  1675. (Const::Float(bits), _) => u64::from(*bits),
  1676. _ => 0,
  1677. }
  1678. }
  1679. _ => panic!("a global or function as a value"),
  1680. }
  1681. };
  1682. let (mut b, mut from) = (0usize, usize::MAX);
  1683. for _ in 0..4000 {
  1684. let blk = &m.blocks[b];
  1685. // Joins take their values together, before any is assigned.
  1686. let joined: Vec<(u32, u64)> = blk
  1687. .phis
  1688. .iter()
  1689. .map(|&p| {
  1690. let Op::Phi(incoming) = &m.insts[p as usize].op else {
  1691. panic!("a join")
  1692. };
  1693. let v = incoming
  1694. .iter()
  1695. .find(|x| x.1 == from)
  1696. .expect("a value for the edge taken");
  1697. (p, eval(&vals, v.0))
  1698. })
  1699. .collect();
  1700. for (p, x) in joined {
  1701. vals[p as usize] = Some(x);
  1702. }
  1703. for &i in &blk.body {
  1704. let inst = &m.insts[i as usize];
  1705. let bits = m.int_bits(inst.ty);
  1706. let float = |x: u64| f32::from_bits(x as u32);
  1707. let r = match &inst.op {
  1708. Op::Bin(op, x, y) => {
  1709. let (x, y) = (eval(&vals, *x), eval(&vals, *y));
  1710. match bits {
  1711. Some(bits) => {
  1712. let r = match op {
  1713. Bin::Add => x.wrapping_add(y),
  1714. Bin::Sub => x.wrapping_sub(y),
  1715. Bin::Mul => x.wrapping_mul(y),
  1716. Bin::And => x & y,
  1717. Bin::Or => x | y,
  1718. Bin::Xor => x ^ y,
  1719. Bin::Shl => x << y,
  1720. Bin::LShr => x >> y,
  1721. Bin::AShr => (signed(bits, x) >> y) as u64,
  1722. _ => panic!("no divisions here"),
  1723. };
  1724. r & mask(bits)
  1725. }
  1726. None => {
  1727. let (x, y) = (float(x), float(y));
  1728. let r = match op {
  1729. Bin::Add => x + y,
  1730. Bin::Sub => x - y,
  1731. _ => x * y,
  1732. };
  1733. u64::from(r.to_bits())
  1734. }
  1735. }
  1736. }
  1737. Op::Cmp(p, x, y) => {
  1738. let wide = m.int_bits(m.type_of(*x));
  1739. let (x, y) = (eval(&vals, *x), eval(&vals, *y));
  1740. let holds = match wide {
  1741. Some(bits) => {
  1742. let (sx, sy) = (signed(bits, x), signed(bits, y));
  1743. match *p {
  1744. pred::EQ => x == y,
  1745. pred::NE => x != y,
  1746. pred::IUGT => x > y,
  1747. pred::IUGE => x >= y,
  1748. pred::IULT => x < y,
  1749. pred::IULE => x <= y,
  1750. pred::SGT => sx > sy,
  1751. pred::SGE => sx >= sy,
  1752. pred::SLT => sx < sy,
  1753. _ => sx <= sy,
  1754. }
  1755. }
  1756. None => {
  1757. let (x, y) = (float(x), float(y));
  1758. if x.is_nan() || y.is_nan() {
  1759. p & 8 != 0
  1760. } else {
  1761. (p & 1 != 0 && x == y)
  1762. || (p & 2 != 0 && x > y)
  1763. || (p & 4 != 0 && x < y)
  1764. }
  1765. }
  1766. };
  1767. u64::from(holds)
  1768. }
  1769. Op::Select(c, t, f) => {
  1770. if eval(&vals, *c) != 0 {
  1771. eval(&vals, *t)
  1772. } else {
  1773. eval(&vals, *f)
  1774. }
  1775. }
  1776. Op::Cast(op, x) => {
  1777. let from_bits = m.int_bits(m.type_of(*x));
  1778. let x = eval(&vals, *x);
  1779. match (op, from_bits, bits) {
  1780. (Cast::Bitcast, _, _) => x,
  1781. (Cast::ZExt, _, _) => x,
  1782. (Cast::SExt, Some(f), Some(t)) => signed(f, x) as u64 & mask(t),
  1783. (Cast::Trunc, _, Some(t)) => x & mask(t),
  1784. _ => panic!("a cast the generator does not make"),
  1785. }
  1786. }
  1787. Op::Call(f, args) => {
  1788. let a: Vec<u64> = args.iter().map(|&v| eval(&vals, v)).collect();
  1789. let name = m.funcs[*f as usize].name.as_str();
  1790. match name {
  1791. "dx.op.loadInput.i32" => {
  1792. u64::from(inputs[(a[0] ^ a[1]) as usize % inputs.len()])
  1793. }
  1794. "dx.op.binary.i32" => a[0].min(a[1]),
  1795. "dx.op.cbufferLoadLegacy.i32" => u64::from(
  1796. inputs[a[0] as usize % inputs.len()].rotate_left(a[1] as u32 & 31),
  1797. ),
  1798. "dx.op.bufferLoad.i32" => memory[(a[0] ^ a[1]) as usize % 16],
  1799. "dx.op.waveReadLaneFirst.i32" => a[0] ^ a[1],
  1800. _ => {
  1801. memory[a[0] as usize % 16] = a[1];
  1802. trace.push((name.to_owned(), a));
  1803. 0
  1804. }
  1805. }
  1806. }
  1807. _ => panic!("an instruction the generator does not make"),
  1808. };
  1809. vals[i as usize] = Some(r);
  1810. }
  1811. from = b;
  1812. b = match blk.term.expect("a terminator") {
  1813. Term::Ret => {
  1814. trace.push(("ret".into(), Vec::new()));
  1815. return trace;
  1816. }
  1817. Term::Br(t) => t,
  1818. Term::CondBr(c, t, f) => {
  1819. if eval(&vals, c) != 0 {
  1820. t
  1821. } else {
  1822. f
  1823. }
  1824. }
  1825. };
  1826. }
  1827. trace.push(("still running".into(), Vec::new()));
  1828. trace
  1829. }
  1830. /// A random structured program over a few registers, as the lowering
  1831. /// makes them: every register joined at every join, conditions tested
  1832. /// again behind their branch, values computed again.
  1833. struct Gen {
  1834. k: Kit,
  1835. rng: u64,
  1836. regs: Vec<V>,
  1837. conds: Vec<V>,
  1838. cur: usize,
  1839. input: V,
  1840. table: V,
  1841. wave: V,
  1842. /// The operands of the block's last read (to read the place again,
  1843. /// and to store to it).
  1844. last: Option<(V, V)>,
  1845. }
  1846. impl Gen {
  1847. fn next(&mut self, n: u64) -> u64 {
  1848. self.rng ^= self.rng << 13;
  1849. self.rng ^= self.rng >> 7;
  1850. self.rng ^= self.rng << 17;
  1851. (self.rng >> 11) % n
  1852. }
  1853. fn reg(&mut self) -> V {
  1854. let n = self.next(self.regs.len() as u64) as usize;
  1855. self.regs[n]
  1856. }
  1857. /// A register or a small constant.
  1858. fn value(&mut self) -> V {
  1859. match self.next(4) {
  1860. 0 => {
  1861. let k = [0u32, 1, 2, 31, u32::MAX, 0x8000_0000, 7][self.next(7) as usize];
  1862. self.k.m.i32(k)
  1863. }
  1864. _ => self.reg(),
  1865. }
  1866. }
  1867. fn cond(&mut self) -> V {
  1868. let c = self.cur;
  1869. let made = match self.next(6) {
  1870. 0 if !self.conds.is_empty() => {
  1871. let n = self.next(self.conds.len() as u64) as usize;
  1872. return self.conds[n];
  1873. }
  1874. 1 if self.conds.len() > 1 => {
  1875. let (a, b) = (
  1876. self.next(self.conds.len() as u64),
  1877. self.next(self.conds.len() as u64),
  1878. );
  1879. let op = [Bin::And, Bin::Or, Bin::Xor][self.next(3) as usize];
  1880. self.k
  1881. .m
  1882. .bin(c, op, self.conds[a as usize], self.conds[b as usize])
  1883. }
  1884. 2 if !self.conds.is_empty() => {
  1885. let n = self.next(self.conds.len() as u64) as usize;
  1886. let t = self.k.m.bool(true);
  1887. self.k.m.bin(c, Bin::Xor, self.conds[n], t)
  1888. }
  1889. _ => {
  1890. let p = pred::EQ + self.next(10) as u8;
  1891. let (x, y) = (self.reg(), self.value());
  1892. self.k.m.cmp(c, p, x, y)
  1893. }
  1894. };
  1895. self.conds.push(made);
  1896. made
  1897. }
  1898. fn statement(&mut self) {
  1899. let c = self.cur;
  1900. let d = self.next(self.regs.len() as u64) as usize;
  1901. let i32t = self.k.m.int(32);
  1902. let f32t = self.k.m.float();
  1903. let r = match self.next(14) {
  1904. 0..=3 => {
  1905. let op = [Bin::Add, Bin::Sub, Bin::Mul, Bin::And, Bin::Or, Bin::Xor]
  1906. [self.next(6) as usize];
  1907. let (x, y) = (self.value(), self.value());
  1908. self.k.m.bin(c, op, x, y)
  1909. }
  1910. 4 => {
  1911. let op = [Bin::Shl, Bin::LShr, Bin::AShr][self.next(3) as usize];
  1912. let x = self.value();
  1913. let by = self.next(32) as u32;
  1914. let by = self.k.m.i32(by);
  1915. self.k.m.bin(c, op, x, by)
  1916. }
  1917. 5 | 6 => {
  1918. // A guarded write: the old value where the guard fails.
  1919. let g = self.cond();
  1920. let x = self.value();
  1921. self.k.m.select(self.cur, g, x, self.regs[d])
  1922. }
  1923. 7 => {
  1924. let (x, y) = (self.value(), self.value());
  1925. let f = [self.k.pure, self.input, self.table, self.wave][self.next(4) as usize];
  1926. self.k.m.call(c, f, vec![x, y])
  1927. }
  1928. 8 | 9 => {
  1929. let again = self.next(2) == 0;
  1930. let (x, y) = match self.last {
  1931. Some(last) if again => last,
  1932. _ => (self.value(), self.value()),
  1933. };
  1934. self.last = Some((x, y));
  1935. self.k.m.call(c, self.k.reads, vec![x, y])
  1936. }
  1937. 10 => {
  1938. // A store, half the time to the place read last.
  1939. let (mut x, y) = (self.value(), self.value());
  1940. let there = self.next(2) == 0;
  1941. if let Some((a, b)) = self.last
  1942. && there
  1943. {
  1944. x = self.k.m.bin(c, Bin::Xor, a, b);
  1945. }
  1946. self.k.m.call(c, self.k.writes, vec![x, y]);
  1947. return;
  1948. }
  1949. 11 => {
  1950. // Float arithmetic, read back as bits.
  1951. let (x, y) = (self.value(), self.value());
  1952. let (x, y) = (
  1953. self.k.m.cast(c, Cast::Bitcast, x, f32t),
  1954. self.k.m.cast(c, Cast::Bitcast, y, f32t),
  1955. );
  1956. let op = [Bin::Add, Bin::Sub, Bin::Mul][self.next(3) as usize];
  1957. let f = self.k.m.bin(c, op, x, y);
  1958. if self.next(2) == 0 {
  1959. let p = self.next(16) as u8;
  1960. let t = self.k.m.cmp(c, p, f, y);
  1961. self.conds.push(t);
  1962. }
  1963. self.k.m.cast(c, Cast::Bitcast, f, i32t)
  1964. }
  1965. 12 => {
  1966. let g = self.cond();
  1967. self.k.m.cast(self.cur, Cast::ZExt, g, i32t)
  1968. }
  1969. _ => {
  1970. let x = self.value();
  1971. let f = self.k.m.cast(c, Cast::Bitcast, x, f32t);
  1972. self.k.m.cast(c, Cast::Bitcast, f, i32t)
  1973. }
  1974. };
  1975. self.regs[d] = r;
  1976. }
  1977. fn code(&mut self, depth: u32) {
  1978. for _ in 0..1 + self.next(6) {
  1979. match self.next(8) {
  1980. 0 | 1 if depth > 0 => self.branch(depth - 1),
  1981. 2 if depth > 0 => self.repeat(depth - 1),
  1982. _ => self.statement(),
  1983. }
  1984. }
  1985. }
  1986. /// if / else, every register joined.
  1987. fn branch(&mut self, depth: u32) {
  1988. let c = self.cond();
  1989. let i32t = self.k.m.int(32);
  1990. let (then, other, join) = (
  1991. self.k.m.new_block(),
  1992. self.k.m.new_block(),
  1993. self.k.m.new_block(),
  1994. );
  1995. self.k.m.terminate(self.cur, Term::CondBr(c, then, other));
  1996. let (before, known) = (self.regs.clone(), self.conds.len());
  1997. self.cur = then;
  1998. self.last = None;
  1999. self.code(depth);
  2000. let (then_regs, then_end) = (std::mem::replace(&mut self.regs, before), self.cur);
  2001. self.k.m.terminate(then_end, Term::Br(join));
  2002. self.conds.truncate(known);
  2003. self.cur = other;
  2004. self.last = None;
  2005. if self.next(3) != 0 {
  2006. self.code(depth);
  2007. }
  2008. let other_end = self.cur;
  2009. self.k.m.terminate(other_end, Term::Br(join));
  2010. self.conds.truncate(known);
  2011. for (r, &t) in then_regs.iter().enumerate() {
  2012. let p = self.k.m.phi(join, i32t);
  2013. self.k
  2014. .m
  2015. .set_phi(p, vec![(t, then_end), (self.regs[r], other_end)]);
  2016. self.regs[r] = p;
  2017. }
  2018. self.cur = join;
  2019. self.last = None;
  2020. }
  2021. /// A loop that runs at most a few times, every register joined at
  2022. /// its head.
  2023. fn repeat(&mut self, depth: u32) {
  2024. let i32t = self.k.m.int(32);
  2025. let (head, exit) = (self.k.m.new_block(), self.k.m.new_block());
  2026. let before = self.cur;
  2027. self.k.m.terminate(before, Term::Br(head));
  2028. let entering = self.regs.clone();
  2029. let joins: Vec<V> = (0..self.regs.len())
  2030. .map(|_| self.k.m.phi(head, i32t))
  2031. .collect();
  2032. let count = self.k.m.phi(head, i32t);
  2033. self.regs = joins.clone();
  2034. let known = self.conds.len();
  2035. self.cur = head;
  2036. self.last = None;
  2037. self.code(depth);
  2038. let one = self.k.m.i32(1);
  2039. let next = self.k.m.bin(self.cur, Bin::Add, count, one);
  2040. let limit = 1 + self.next(3) as u32;
  2041. let limit = self.k.m.i32(limit);
  2042. let mut more = self.k.m.cmp(self.cur, pred::IULT, next, limit);
  2043. if self.next(2) == 0 {
  2044. let c = self.cond();
  2045. more = self.k.m.bin(self.cur, Bin::And, more, c);
  2046. }
  2047. let latch = self.cur;
  2048. self.k.m.terminate(latch, Term::CondBr(more, head, exit));
  2049. for (r, &p) in joins.iter().enumerate() {
  2050. self.k
  2051. .m
  2052. .set_phi(p, vec![(entering[r], before), (self.regs[r], latch)]);
  2053. }
  2054. let zero = self.k.m.i32(0);
  2055. self.k.m.set_phi(count, vec![(zero, before), (next, latch)]);
  2056. self.conds.truncate(known);
  2057. self.cur = exit;
  2058. self.last = None;
  2059. }
  2060. }
  2061. fn random_program(seed: u64) -> Module {
  2062. let mut k = kit();
  2063. let i32t = k.m.int(32);
  2064. let fty = k.m.func_ty(i32t, vec![i32t, i32t]);
  2065. let input =
  2066. k.m.function("dx.op.loadInput.i32", fty, Some(Attr::ReadNone), false);
  2067. let table = k.m.function(
  2068. "dx.op.cbufferLoadLegacy.i32",
  2069. fty,
  2070. Some(Attr::ReadOnly),
  2071. false,
  2072. );
  2073. let wave = k.m.function(
  2074. "dx.op.waveReadLaneFirst.i32",
  2075. fty,
  2076. Some(Attr::NoUnwind),
  2077. false,
  2078. );
  2079. let b = k.b;
  2080. let mut g = Gen {
  2081. k,
  2082. rng: seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1,
  2083. regs: Vec::new(),
  2084. conds: Vec::new(),
  2085. cur: b,
  2086. input,
  2087. table,
  2088. wave,
  2089. last: None,
  2090. };
  2091. for r in 0..5 {
  2092. let (x, y) = (g.k.m.i32(r), g.k.m.i32(r * 3));
  2093. let v = g.k.m.call(b, input, vec![x, y]);
  2094. g.regs.push(v);
  2095. }
  2096. g.code(3);
  2097. g.code(2);
  2098. // Every register is read at the end.
  2099. for r in 0..g.regs.len() {
  2100. let at = g.k.m.i32(r as u32);
  2101. g.k.m.call(g.cur, g.k.writes, vec![at, g.regs[r]]);
  2102. }
  2103. g.k.m.terminate(g.cur, Term::Ret);
  2104. g.k.m
  2105. }
  2106. #[test]
  2107. fn every_pass_leaves_what_random_programs_store() {
  2108. let mut removed = 0;
  2109. for seed in 1..=400u64 {
  2110. let plain = random_program(seed);
  2111. let inputs: Vec<Vec<u32>> = (0..6u32)
  2112. .map(|n| {
  2113. (0..7u32)
  2114. .map(|i| match n {
  2115. 0 => 0,
  2116. 1 => i,
  2117. 2 => u32::MAX - i,
  2118. _ => {
  2119. (seed as u32 ^ n)
  2120. .wrapping_mul(0x9E37_79B9)
  2121. .rotate_left(i * 5)
  2122. ^ (i << 28)
  2123. }
  2124. })
  2125. .collect()
  2126. })
  2127. .collect();
  2128. let expected: Vec<_> = inputs.iter().map(|i| run(&plain, i)).collect();
  2129. let written: usize = plain
  2130. .blocks
  2131. .iter()
  2132. .map(|b| b.body.len() + b.phis.len())
  2133. .sum();
  2134. for passes in [
  2135. DEAD,
  2136. FOLD,
  2137. REUSE,
  2138. FACTS,
  2139. LOADS,
  2140. FOLD | FACTS,
  2141. FOLD | REUSE | DEAD,
  2142. ALL,
  2143. ] {
  2144. let mut m = random_program(seed);
  2145. m.optimise(passes);
  2146. for (i, want) in inputs.iter().zip(&expected) {
  2147. assert_eq!(&run(&m, i), want, "seed {seed}, passes {passes}");
  2148. }
  2149. if passes == ALL {
  2150. let left: usize = m.blocks.iter().map(|b| b.body.len() + b.phis.len()).sum();
  2151. removed += written - left;
  2152. }
  2153. m.write();
  2154. }
  2155. }
  2156. // The programs are of the wasteful kind: the passes find work.
  2157. assert!(removed > 4000, "{removed} instructions removed");
  2158. }
  2159. }