resource.rs 150 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848
  1. //! Resource tracking (decision 0003): where each descriptor a program uses
  2. //! comes from, in terms of the root signature.
  3. //!
  4. //! Root parameters arrive in user SGPRs ([`RootParam`]): a descriptor table
  5. //! as the 32-bit heap address of its range (the code sets the high half to
  6. //! 0), a root descriptor as a 64-bit buffer address, root constants as
  7. //! themselves. A root signature with dynamic resources (SM 6.6) adds the
  8. //! 32-bit base addresses of both heaps; a descriptor is then loaded from
  9. //! one of them at an index the code computes (from a root constant, say). The code loads table descriptors from heap memory with
  10. //! `s_load_dword*`, and builds a buffer descriptor around a root
  11. //! descriptor's address itself. Each descriptor operand and each scalar
  12. //! memory address is traced through the SSA values back to those
  13. //! parameters, by data flow: copies, phis that agree, and additions.
  14. use crate::ShaderError;
  15. use crate::gfx10::{Fields, NULL, Operand};
  16. use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value};
  17. use crate::native::{HwStage, RootParam, RootType};
  18. use crate::structure::{Bool, LaneExit, Meets, Structured};
  19. /// An instruction: block and index in [`crate::ir::Block::insts`].
  20. pub type Site = (usize, usize);
  21. /// A byte address: a root parameter's, plus a constant and at most one
  22. /// value the program computes (an index times a stride, say).
  23. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  24. pub struct Address {
  25. /// Index into the layout, or [`CODE`].
  26. pub param: usize,
  27. /// Added modulo 2^32 (with carry into the high half of a root
  28. /// descriptor's address).
  29. pub offset: u32,
  30. pub dynamic: Option<Value>,
  31. }
  32. /// [`Address::param`] of the program's own code: a constant table the
  33. /// compiler appends after the code and reads through `s_getpc_b64`; the
  34. /// offset is then the byte offset in the code.
  35. pub const CODE: usize = usize::MAX;
  36. /// [`Address::param`] of title memory at an address no root parameter
  37. /// gives: one the code computes from root constants, reads out of a
  38. /// descriptor or loads from other memory (compute programs only: the
  39. /// ray-tracing structure builder and the programs that walk its
  40. /// structures). Offset and computed term are not used: lowering takes the
  41. /// 64-bit address from the instruction's operands.
  42. pub const MEMORY: usize = usize::MAX - 1;
  43. /// The reasons an address traces to no root parameter for which the
  44. /// address is then taken as it stands ([`MEMORY`]).
  45. const RAW: [&str; 5] = [
  46. "an address not from a root parameter",
  47. "an address from a root parameter that is no address",
  48. "an address in an SGPR that is no root parameter",
  49. "an address loaded from memory",
  50. "an address from a phi",
  51. ];
  52. #[derive(Debug, Clone, PartialEq, Eq)]
  53. pub enum Source {
  54. /// Dwords `first..` of what the scalar load at `load` reads (see
  55. /// [`Resources::scalar`] for its address).
  56. Loaded { load: Site, first: u8 },
  57. /// A buffer descriptor built around an address: `bits` OR-ed into
  58. /// dword 1 (stride, swizzle), dwords 2 and 3 as given.
  59. Built {
  60. address: Address,
  61. bits: u32,
  62. words: [u32; 2],
  63. },
  64. /// Fixed in the code (an immediate sampler, say).
  65. Constant(Vec<u32>),
  66. /// Chosen by control flow: one source per predecessor of `block`, in
  67. /// [`crate::ir::Block::preds`] order.
  68. Phi { block: usize, args: Vec<Source> },
  69. /// Chosen by SCC (`scc`, the value an `s_cselect` or `s_cmov` of each
  70. /// dword reads): the source when it is set, then when it is clear.
  71. Select { scc: Value, args: Vec<Source> },
  72. /// Dwords `first..` of what the vector load at `load` (`global_load_*`)
  73. /// reads, each lane at its own address (see [`Resources::scalar`]); the
  74. /// dwords past that load come from loads of the bytes that follow. A
  75. /// descriptor that differs between lanes.
  76. Fetched { load: Site, first: u8 },
  77. /// Picked per lane by `v_cndmask_b32` reading the lane mask whose low
  78. /// dword is `mask`: the source where the lane's bit is set, then where it
  79. /// is clear.
  80. Lanes { mask: Value, args: Vec<Source> },
  81. /// Per-lane dwords chosen by control flow (VGPRs joined where lanes
  82. /// that took different paths meet): one source per predecessor of
  83. /// `block`, in [`crate::ir::Block::preds`] order, `None` on an edge no
  84. /// lane that accesses the descriptor takes. A descriptor that differs
  85. /// between lanes.
  86. LanePhi {
  87. block: usize,
  88. args: Vec<Option<Source>>,
  89. },
  90. }
  91. impl Source {
  92. /// The sources this one picks from (itself unless a phi).
  93. pub fn leaves(&self) -> Vec<&Source> {
  94. match self {
  95. Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } => {
  96. args.iter().flat_map(Source::leaves).collect()
  97. }
  98. Source::LanePhi { args, .. } => {
  99. args.iter().flatten().flat_map(Source::leaves).collect()
  100. }
  101. s => vec![s],
  102. }
  103. }
  104. }
  105. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  106. pub enum Role {
  107. /// Image, buffer or `s_buffer_load` resource.
  108. Resource,
  109. Sampler,
  110. }
  111. #[derive(Debug, Clone, PartialEq, Eq)]
  112. pub struct Descriptor {
  113. pub site: Site,
  114. pub role: Role,
  115. pub source: Source,
  116. }
  117. /// A view-heap descriptor whose byte address can be evaluated when binding
  118. /// the draw, using a table base and a root constant.
  119. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  120. pub struct RootIndexedView {
  121. pub table_slot: u8,
  122. pub constant_slot: u8,
  123. pub constant_dword: u32,
  124. pub byte_offset: u32,
  125. pub shift: u8,
  126. }
  127. #[derive(Debug, Clone, Default, PartialEq, Eq)]
  128. pub struct Resources {
  129. /// Every scalar memory access by address (`s_load_*`, `s_store_*`), and
  130. /// every global memory access (`global_*`, the dynamic term per lane).
  131. pub scalar: Vec<(Site, Address)>,
  132. pub descriptors: Vec<Descriptor>,
  133. /// Direct descriptor sources with a draw-evaluable index.
  134. pub root_indexed_views: Vec<RootIndexedView>,
  135. /// User SGPRs holding root parameters: value on entry, layout index,
  136. /// dword within the parameter.
  137. pub params: Vec<(Value, usize, u32)>,
  138. /// Scalar loads of one descriptor the code keeps per lane in VGPRs
  139. /// ([`Tracer::lane_copies`]): they read one address, so their dwords
  140. /// stand in for each other.
  141. pub lane_copied: Vec<Site>,
  142. pub waterfall: Waterfall,
  143. /// Every `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`: where
  144. /// its nodes are.
  145. pub bvh: Vec<(Site, BvhNodes)>,
  146. }
  147. /// Where a ray-tracing node test ([`crate::bvh`]) reads its nodes. Its
  148. /// descriptor operand names a range of memory, not a texture.
  149. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  150. pub enum BvhNodes {
  151. /// A buffer of the host: the descriptor is loaded from a table (it is
  152. /// among [`Resources::descriptors`]), and node pointers count from the
  153. /// buffer's start. Its flags are not known to the shader: boxes are
  154. /// sorted and triangles return barycentrics, as every descriptor Grand
  155. /// Theft Auto VI builds asks.
  156. Resource,
  157. /// Title memory by address: the code makes the descriptor from numbers
  158. /// (the title: the whole address space, or one structure's address in
  159. /// dword 0). Dwords 1 and 3, which hold its flags.
  160. Memory { word1: u32, word3: u32 },
  161. }
  162. /// Waterfall loops over descriptors that differ between lanes: each pass
  163. /// reads the first active lane's descriptor with `v_readfirstlane_b32`,
  164. /// compares it with every lane's own (`v_cmp_eq`), and runs the access with
  165. /// the lanes that match. Their accesses take each lane's own descriptor
  166. /// ([`Source::Fetched`], [`Source::Lanes`]), so the first lane's dwords are
  167. /// each lane's own too: the compares hold in every lane and one pass serves
  168. /// all lanes.
  169. #[derive(Debug, Clone, Default, PartialEq, Eq)]
  170. pub struct Waterfall {
  171. /// The compares, true in every lane.
  172. pub compares: Vec<Site>,
  173. /// The `v_readfirstlane_b32` results they compare, each the lane's own
  174. /// source dword.
  175. pub reads: Vec<Value>,
  176. /// Descriptor loads at a table offset among `reads` (the console
  177. /// compiler's form): each lane loads its own entry.
  178. pub loads: Vec<Site>,
  179. }
  180. /// Traces every descriptor and scalar address of `p`, which runs as
  181. /// `stage`, to the root parameters in `layout`. Fails on the first one it
  182. /// cannot trace. `lanes`, `p` as one lane runs it, tells which paths the
  183. /// lanes that access a per-lane descriptor took and which writes they ran;
  184. /// without it, per-lane descriptors chosen by control flow are refused and
  185. /// per-lane writes are taken to run in every lane.
  186. pub fn track(
  187. p: &Program,
  188. layout: &[RootParam],
  189. stage: HwStage,
  190. lanes: Option<&Structured>,
  191. ) -> Result<Resources, ShaderError> {
  192. let t = Tracer::new(p, layout, stage, lanes)?;
  193. let mut out = Resources {
  194. params: p
  195. .inputs
  196. .iter()
  197. .filter_map(|&(reg, v)| {
  198. let (param, dword) = t.param_of(reg)?;
  199. Some((v, param, dword))
  200. })
  201. .collect(),
  202. ..Resources::default()
  203. };
  204. // Group accesses in the same loop so a shared mask can select several
  205. // descriptors together.
  206. let mut first_lane_at = std::collections::BTreeMap::<usize, (Vec<usize>, Vec<Value>)>::new();
  207. // The console compiler's waterfall reads the first lane's table offset
  208. // and loads that entry: accesses, offset reads and loads by block.
  209. let mut offset_at =
  210. std::collections::BTreeMap::<usize, (Vec<usize>, Vec<Value>, Vec<Site>)>::new();
  211. for (b, block) in p.blocks.iter().enumerate() {
  212. t.at.set(Some(b));
  213. for (i, inst) in block.insts.iter().enumerate() {
  214. let site = (b, i);
  215. let fail = |what| ShaderError::Unsupported {
  216. offset: inst.machine.offset,
  217. what,
  218. };
  219. let mut first_lane = Vec::new();
  220. let mut offset = Vec::new();
  221. let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> {
  222. let source = t.descriptor(inst, op, b).map_err(fail)?;
  223. // A descriptor the code keeps per lane ([`Tracer::lane_copies`])
  224. // is the same in every lane: its loop is lowered as it stands
  225. // and needs no proof.
  226. if !t.kept_per_lane(inst, op) {
  227. first_lane.extend(t.first_lane_words(inst, op).unwrap_or_default());
  228. }
  229. if let Source::Loaded { load, .. } = source
  230. && out.scalar.iter().any(|s| s.0 == load)
  231. && let Some(v) = t.first_lane_offset(load)
  232. {
  233. offset.push((v, load));
  234. }
  235. out.descriptors.push(Descriptor { site, role, source });
  236. Ok(())
  237. };
  238. match &inst.fields {
  239. Fields::Image { rsrc, .. } if inst.name().starts_with("image_bvh") => {
  240. // The ray and node test names no texture. A descriptor
  241. // whose flag dwords the code sets as numbers and whose
  242. // type is a ray-tracing structure is a range of title
  243. // memory (the title: all of it, or from one structure's
  244. // address on), and the node's address is among the
  245. // operands; any other descriptor must be a resource of
  246. // the host.
  247. let word = |k: u8| match *rsrc {
  248. Operand::Scalar { code, dwords } if k < dwords => {
  249. inst.read(Reg::S(code + k)).map(|v| t.origin(v))
  250. }
  251. _ => None,
  252. };
  253. match (word(1), word(3)) {
  254. (Some(Term::Const(word1)), Some(Term::Const(word3)))
  255. if word3 >> 28 == crate::bvh::DESCRIPTOR_TYPE =>
  256. {
  257. out.bvh.push((site, BvhNodes::Memory { word1, word3 }));
  258. }
  259. _ => {
  260. descriptor(rsrc, Role::Resource)?;
  261. out.bvh.push((site, BvhNodes::Resource));
  262. }
  263. }
  264. }
  265. Fields::Image { rsrc, sampler, .. } => {
  266. descriptor(rsrc, Role::Resource)?;
  267. if let Some(s) = sampler {
  268. descriptor(s, Role::Sampler)?;
  269. }
  270. }
  271. // Cache invalidations name a buffer's address space but do
  272. // not read its descriptor; the host has no cache to drop.
  273. Fields::Buffer { rsrc, .. } if !inst.name().ends_with("_inv") => {
  274. descriptor(rsrc, Role::Resource)?
  275. }
  276. Fields::Buffer { .. } => {}
  277. Fields::Smem { base, .. } if inst.name().starts_with("s_buffer_") => {
  278. descriptor(base, Role::Resource)?;
  279. }
  280. Fields::Smem {
  281. base,
  282. offset,
  283. soffset,
  284. ..
  285. } if inst.name().contains("_load_") || inst.name().contains("_store_") => {
  286. let address = t
  287. .smem_address(inst, base, *offset, soffset)
  288. .or_else(|why| t.by_address(why))
  289. .map_err(fail)?;
  290. out.scalar.push((site, address));
  291. }
  292. Fields::Flat {
  293. addr,
  294. saddr,
  295. offset,
  296. ..
  297. } if inst.name().starts_with("global_") => {
  298. let address = t
  299. .flat_address(inst, addr.as_ref(), saddr.as_ref(), *offset)
  300. .or_else(|why| t.by_address(why))
  301. .map_err(fail)?;
  302. out.scalar.push((site, address));
  303. }
  304. _ => {}
  305. }
  306. if !first_lane.is_empty() {
  307. let (accesses, reads) = first_lane_at.entry(b).or_default();
  308. accesses.push(i);
  309. reads.extend(first_lane);
  310. }
  311. if !offset.is_empty() {
  312. let (accesses, reads, loads) = offset_at.entry(b).or_default();
  313. accesses.push(i);
  314. for (v, load) in offset {
  315. reads.push(v);
  316. loads.push(load);
  317. }
  318. }
  319. }
  320. }
  321. // What follows traces no access of one block.
  322. t.at.set(None);
  323. // The proof needs the per-lane form. Without it nothing is emitted, and
  324. // its failure is the one to report, so the reads stay unproven here.
  325. if t.lanes.is_none() {
  326. return Ok(out);
  327. }
  328. for (block, (accesses, mut reads)) in first_lane_at {
  329. reads.sort_unstable();
  330. reads.dedup();
  331. let proof = t
  332. .waterfall(block, &accesses, &reads)
  333. .map_err(|what| ShaderError::Unsupported {
  334. offset: t.inst((block, accesses[0])).machine.offset,
  335. what,
  336. })?;
  337. out.waterfall.compares.extend(proof.compares);
  338. out.waterfall.reads.extend(proof.reads);
  339. }
  340. // Unproven, an offset read stays the first lane's (one uniform entry),
  341. // which is what the hardware reads outside a waterfall loop.
  342. for (block, (accesses, mut reads, loads)) in offset_at {
  343. reads.sort_unstable();
  344. reads.dedup();
  345. if let Ok(proof) = t.waterfall(block, &accesses, &reads) {
  346. out.waterfall.compares.extend(proof.compares);
  347. out.waterfall.reads.extend(proof.reads);
  348. out.waterfall.loads.extend(loads);
  349. }
  350. }
  351. out.lane_copied = t.lane_copied.take();
  352. out.lane_copied.sort_unstable();
  353. out.lane_copied.dedup();
  354. out.root_indexed_views = out
  355. .descriptors
  356. .iter()
  357. .filter_map(|d| t.root_indexed_view(d, &out.scalar))
  358. .collect();
  359. Ok(out)
  360. }
  361. /// A dword after copy propagation.
  362. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  363. enum Term {
  364. Const(u32),
  365. Value(Value),
  366. }
  367. /// A 32-bit sum: optional root parameter (as its first dword), constant,
  368. /// optional computed term.
  369. struct Sum {
  370. base: Option<Value>,
  371. offset: u32,
  372. dynamic: Option<Value>,
  373. }
  374. struct Tracer<'a> {
  375. p: &'a Program,
  376. layout: &'a [RootParam],
  377. stage: HwStage,
  378. /// Defining instruction per value (phis and inputs have none).
  379. defs: Vec<Option<Site>>,
  380. /// Block and index of each phi value.
  381. phis: Vec<Option<(usize, usize)>>,
  382. /// Register per input value.
  383. inputs: Vec<Option<Reg>>,
  384. origin: Vec<Term>,
  385. /// See [`Resources::lane_copied`].
  386. lane_copied: std::cell::RefCell<Vec<Site>>,
  387. lanes: Option<&'a Structured>,
  388. /// While set, [`Self::sum`] keeps the first-lane read of an index as
  389. /// the computed term instead of what the lanes hold.
  390. read_first_lane: std::cell::Cell<bool>,
  391. /// What the conditions asked of `lanes` so far came down to: the proofs
  392. /// of one program ask about the same blocks and masks again and again.
  393. meets: std::cell::RefCell<Meets>,
  394. /// Reverse-postorder index per block.
  395. rpo: Vec<usize>,
  396. /// The block of the access being traced ([`Self::live`]).
  397. at: std::cell::Cell<Option<usize>>,
  398. }
  399. /// What lanes are known to satisfy: each [`Bool`] where its flag is set,
  400. /// its negation where not.
  401. type Known = Vec<(Bool, bool)>;
  402. const MAX_ROUNDS: usize = 64;
  403. const MAX_JOINS: usize = 8;
  404. /// VGPR values followed for one dword of a descriptor kept per lane.
  405. const MAX_COPIES: usize = 64;
  406. impl<'a> Tracer<'a> {
  407. fn new(
  408. p: &'a Program,
  409. layout: &'a [RootParam],
  410. stage: HwStage,
  411. lanes: Option<&'a Structured>,
  412. ) -> Result<Self, ShaderError> {
  413. let all = || {
  414. p.inputs
  415. .iter()
  416. .map(|i| i.1)
  417. .chain(p.blocks.iter().flat_map(|b| {
  418. b.phis
  419. .iter()
  420. .map(|phi| phi.value)
  421. .chain(b.insts.iter().flat_map(|i| i.writes.iter().map(|w| w.1)))
  422. }))
  423. };
  424. let n = all().map(|v| v.0 as usize + 1).max().unwrap_or(0);
  425. let mut defs = vec![None; n];
  426. let mut phis = vec![None; n];
  427. let mut inputs = vec![None; n];
  428. for &(reg, v) in &p.inputs {
  429. inputs[v.0 as usize] = Some(reg);
  430. }
  431. for (b, block) in p.blocks.iter().enumerate() {
  432. for (i, phi) in block.phis.iter().enumerate() {
  433. phis[phi.value.0 as usize] = Some((b, i));
  434. }
  435. for (i, inst) in block.insts.iter().enumerate() {
  436. for &(_, v) in &inst.writes {
  437. defs[v.0 as usize] = Some((b, i));
  438. }
  439. }
  440. }
  441. let mut rpo = vec![usize::MAX; p.blocks.len()];
  442. for (n, b) in crate::ir::reverse_postorder(&p.blocks)
  443. .into_iter()
  444. .enumerate()
  445. {
  446. rpo[b] = n;
  447. }
  448. let mut t = Tracer {
  449. p,
  450. layout,
  451. stage,
  452. defs,
  453. phis,
  454. inputs,
  455. origin: Vec::new(),
  456. lane_copied: Default::default(),
  457. lanes,
  458. read_first_lane: Default::default(),
  459. meets: Default::default(),
  460. rpo,
  461. at: Default::default(),
  462. };
  463. t.origin = t.propagate_copies(n)?;
  464. Ok(t)
  465. }
  466. /// Optimistic copy propagation: a move's result is its source's
  467. /// origin, a phi's the one origin its arguments agree on.
  468. fn propagate_copies(&self, n: usize) -> Result<Vec<Term>, ShaderError> {
  469. let mut o: Vec<Option<Term>> = vec![None; n];
  470. for &(_, v) in &self.p.inputs {
  471. o[v.0 as usize] = Some(Term::Value(v));
  472. }
  473. let order = crate::ir::reverse_postorder(&self.p.blocks);
  474. for _ in 0..MAX_ROUNDS {
  475. let mut changed = false;
  476. for &b in &order {
  477. let block = &self.p.blocks[b];
  478. for phi in &block.phis {
  479. let own = Term::Value(phi.value);
  480. let mut args = phi
  481. .args
  482. .iter()
  483. .filter_map(|a| o[a.0 as usize])
  484. .filter(|&t| t != own);
  485. let new = args
  486. .next()
  487. .map(|first| if args.all(|t| t == first) { first } else { own });
  488. if new.is_some() && new != o[phi.value.0 as usize] {
  489. o[phi.value.0 as usize] = new;
  490. changed = true;
  491. }
  492. }
  493. for inst in &block.insts {
  494. for (k, &(_, v)) in inst.writes.iter().enumerate() {
  495. let new = match copy_source(inst, k).or_else(|| self.restored(inst)) {
  496. Some(Moved::Const(c)) => Some(Term::Const(c)),
  497. Some(Moved::Value(s)) => o[s.0 as usize],
  498. None => Some(Term::Value(v)),
  499. };
  500. if new.is_some() && new != o[v.0 as usize] {
  501. o[v.0 as usize] = new;
  502. changed = true;
  503. }
  504. }
  505. }
  506. }
  507. if !changed {
  508. return Ok(o
  509. .into_iter()
  510. .enumerate()
  511. .map(|(v, t)| t.unwrap_or(Term::Value(Value(v as u32))))
  512. .collect());
  513. }
  514. }
  515. Err(ShaderError::Unsupported {
  516. offset: 0,
  517. what: "copies that do not settle",
  518. })
  519. }
  520. /// Whether some lane can satisfy all of `conditions` ([`Bools::meet`]).
  521. ///
  522. /// [`Bools::meet`]: crate::structure::Bools::meet
  523. fn meet(&self, lanes: &Structured, conditions: &[(Bool, bool)]) -> bool {
  524. lanes
  525. .bools
  526. .meet_seen(conditions, &mut self.meets.borrow_mut())
  527. }
  528. fn inst(&self, (b, i): Site) -> &'a Inst {
  529. &self.p.blocks[b].insts[i]
  530. }
  531. fn def(&self, v: Value) -> Option<&'a Inst> {
  532. self.defs[v.0 as usize].map(|s| self.inst(s))
  533. }
  534. fn origin(&self, v: Value) -> Term {
  535. self.origin[v.0 as usize]
  536. }
  537. /// The origin of a one-dword operand as `inst` reads it.
  538. fn term(&self, inst: &Inst, op: &Operand) -> Option<Term> {
  539. match *op {
  540. Operand::Scalar { code: NULL, .. } => Some(Term::Const(0)),
  541. Operand::Scalar { code, .. } => Some(self.origin(inst.read(Reg::S(code))?)),
  542. Operand::Const(c) => inline(c).map(Term::Const),
  543. Operand::Literal(x) => Some(Term::Const(x)),
  544. _ => None,
  545. }
  546. }
  547. /// Layout index and dword of the root parameter `reg` holds on entry.
  548. fn param_of(&self, reg: Reg) -> Option<(usize, u32)> {
  549. let Reg::S(code) = reg else { return None };
  550. self.layout.iter().enumerate().find_map(|(i, p)| {
  551. let first = self.stage.user_sgpr(p.user_data);
  552. let dword = u32::from(code).checked_sub(first.into())?;
  553. (dword < p.sgprs).then_some((i, dword))
  554. })
  555. }
  556. /// The SOP2 operands of `v` if an instruction with one of `names` wrote it.
  557. fn sop2(&self, v: Value, names: &[&str]) -> Option<(&'a Inst, [Term; 2])> {
  558. let inst = self.def(v)?;
  559. if !names.contains(&inst.name()) || inst.writes.first()?.1 != v {
  560. return None;
  561. }
  562. let Fields::Sop { src, .. } = &inst.fields else {
  563. return None;
  564. };
  565. Some((
  566. inst,
  567. [
  568. self.term(inst, src.first()?)?,
  569. self.term(inst, src.get(1)?)?,
  570. ],
  571. ))
  572. }
  573. fn root_indexed_view(
  574. &self,
  575. descriptor: &Descriptor,
  576. scalar: &[(Site, Address)],
  577. ) -> Option<RootIndexedView> {
  578. if descriptor.role != Role::Resource {
  579. return None;
  580. }
  581. let Source::Loaded { load, first } = descriptor.source else {
  582. return None;
  583. };
  584. let i = scalar.binary_search_by_key(&load, |(site, _)| *site).ok()?;
  585. let address = scalar[i].1;
  586. let base = self.layout.get(address.param)?;
  587. if base.root != RootType::Table {
  588. return None;
  589. }
  590. let dynamic = address.dynamic?;
  591. let (input, shift) = match self.sop2(dynamic, &["s_lshl_b32"]) {
  592. Some((_, [Term::Value(input), Term::Const(shift)])) => (input, (shift & 31) as u8),
  593. _ => (dynamic, 0),
  594. };
  595. let (param, constant_dword) = self.param_of(self.inputs[input.0 as usize]?)?;
  596. let constant = self.layout.get(param)?;
  597. if constant.root != RootType::Constants {
  598. return None;
  599. }
  600. Some(RootIndexedView {
  601. table_slot: base.slot,
  602. constant_slot: constant.slot,
  603. constant_dword,
  604. byte_offset: address.offset.wrapping_add(u32::from(first) * 4),
  605. shift,
  606. })
  607. }
  608. fn sum(&self, t: Term) -> Sum {
  609. let v = match t {
  610. Term::Const(c) => {
  611. return Sum {
  612. base: None,
  613. offset: c,
  614. dynamic: None,
  615. };
  616. }
  617. Term::Value(v) => v,
  618. };
  619. let dynamic = Sum {
  620. base: None,
  621. offset: 0,
  622. dynamic: Some(v),
  623. };
  624. if let Some(reg) = self.inputs[v.0 as usize] {
  625. return match self.param_of(reg) {
  626. Some((_, 0)) => Sum {
  627. base: Some(v),
  628. offset: 0,
  629. dynamic: None,
  630. },
  631. _ => dynamic,
  632. };
  633. }
  634. if self.getpc(v).is_some() {
  635. return Sum {
  636. base: Some(v),
  637. offset: 0,
  638. dynamic: None,
  639. };
  640. }
  641. // Paths that each add an index to a table in the code and meet before one
  642. // load: the join itself is the computed term. Lowering gives every
  643. // `s_getpc_b64` its own offset in the code as its value, so the join is the
  644. // byte in the code whichever table a path took ([`Self::address`] adds no
  645. // base to it).
  646. if let Some(pc) = self.code_join(v) {
  647. return Sum {
  648. base: Some(pc),
  649. offset: 0,
  650. dynamic: Some(v),
  651. };
  652. }
  653. // An address computed in VGPRs and taken from the first lane (a
  654. // table in the code indexed by a value held per lane, or a table
  655. // offset held per lane, the console's waterfall): the sum of what
  656. // the lanes hold. Loads at one offset in different loops (each with
  657. // its own `v_readfirstlane_b32`) then have one address, which is
  658. // what tells lowering that they read one descriptor. With
  659. // `read_first_lane` a first-lane read of an index alone stays the
  660. // computed term ([`Self::first_lane_offset`]).
  661. if let Some(lane) = self.first_lane(v) {
  662. let per_lane = self.sum(self.vorigin(lane));
  663. return if per_lane.base.is_some() || !self.read_first_lane.get() {
  664. per_lane
  665. } else {
  666. dynamic
  667. };
  668. }
  669. let Some([a, b]) = self
  670. .sop2(v, &["s_add_u32", "s_add_i32"])
  671. .map(|(_, t)| t)
  672. .or_else(|| self.vadd(v))
  673. else {
  674. return dynamic;
  675. };
  676. let (x, y) = (self.sum(a), self.sum(b));
  677. if x.base.is_some() && y.base.is_some() || x.dynamic.is_some() && y.dynamic.is_some() {
  678. return dynamic;
  679. }
  680. Sum {
  681. base: x.base.or(y.base),
  682. offset: x.offset.wrapping_add(y.offset),
  683. dynamic: x.dynamic.or(y.dynamic),
  684. }
  685. }
  686. /// For a join `v` whose every incoming value adds to an `s_getpc_b64` low
  687. /// dword: the first of those (one level of joins only). The paths may add
  688. /// to different ones: two tables in the code, one picked by control flow
  689. /// (Grand Theft Auto VI's fog reconstruction reads its sample offsets from
  690. /// one of two tables, by the sample's number; refused, the lit frame was
  691. /// multiplied by a fog transmittance nothing had written).
  692. fn code_join(&self, v: Value) -> Option<Value> {
  693. let (b, i) = self.phis[v.0 as usize]?;
  694. let mut base = None;
  695. for &a in &self.p.blocks[b].phis[i].args {
  696. let Term::Value(x) = self.vorigin(a) else {
  697. return None;
  698. };
  699. if x == v {
  700. continue;
  701. }
  702. let pc = self.code_base(x, 4)?;
  703. base = base.or(Some(pc));
  704. }
  705. base
  706. }
  707. /// `t` is the high dword of an `s_getpc_b64`, or `s_addc_u32`s of one:
  708. /// the carry may be added in steps (the counter's high dword plus 0
  709. /// where the table's offset is added, then plus the index's high dword).
  710. fn code_high(&self, t: Term) -> bool {
  711. self.code_high_in(t, 4)
  712. }
  713. /// [`Self::code_high`], at most `depth` additions deep.
  714. fn code_high_in(&self, t: Term, depth: u32) -> bool {
  715. let Term::Value(x) = t else { return false };
  716. if self.def(x).is_some_and(|i| {
  717. i.name() == "s_getpc_b64" && i.writes.get(1).is_some_and(|w| w.1 == x)
  718. }) {
  719. return true;
  720. }
  721. depth > 0
  722. && self.sop2(x, &["s_addc_u32"]).is_some_and(|(_, [p, q])| {
  723. self.code_high_in(p, depth - 1) || self.code_high_in(q, depth - 1)
  724. })
  725. }
  726. /// The `s_getpc_b64` low dword among the terms `v` adds up (`depth`
  727. /// additions deep; joins are not followed).
  728. fn code_base(&self, v: Value, depth: u32) -> Option<Value> {
  729. if self.getpc(v).is_some() {
  730. return Some(v);
  731. }
  732. // Computed in VGPRs and taken from the first lane.
  733. if let Some(lane) = self.first_lane(v) {
  734. return match self.vorigin(lane) {
  735. Term::Value(x) => self.code_base(x, depth),
  736. Term::Const(_) => None,
  737. };
  738. }
  739. if depth == 0 || self.phis[v.0 as usize].is_some() {
  740. return None;
  741. }
  742. let terms = self
  743. .sop2(v, &["s_add_u32", "s_add_i32"])
  744. .map(|(_, t)| t)
  745. .or_else(|| self.vadd(v))?;
  746. terms.into_iter().find_map(|t| match t {
  747. Term::Value(x) => self.code_base(x, depth - 1),
  748. Term::Const(_) => None,
  749. })
  750. }
  751. /// `t` is `high` or an `s_addc_u32` of it.
  752. fn is_high(&self, t: Term, high: Value) -> bool {
  753. match t {
  754. Term::Value(x) => {
  755. x == high
  756. || self
  757. .sop2(x, &["s_addc_u32"])
  758. .is_some_and(|(_, [p, q])| p == Term::Value(high) || q == Term::Value(high))
  759. }
  760. Term::Const(_) => false,
  761. }
  762. }
  763. /// The VGPR value `v_readfirstlane_b32` reads to write the scalar `v`.
  764. fn first_lane(&self, v: Value) -> Option<Value> {
  765. let inst = self.def(v)?;
  766. if inst.name() != "v_readfirstlane_b32" || inst.writes.first()?.1 != v {
  767. return None;
  768. }
  769. let Fields::Valu(f) = &inst.fields else {
  770. return None;
  771. };
  772. if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() {
  773. return None;
  774. }
  775. match *f.src.first()? {
  776. Operand::Vector { reg, .. } => inst.read(Reg::V(reg)),
  777. _ => None,
  778. }
  779. }
  780. /// The `s_getpc_b64` writing `lo` as its low dword.
  781. fn getpc(&self, lo: Value) -> Option<&'a Inst> {
  782. let inst = self.def(lo)?;
  783. (inst.name() == "s_getpc_b64" && inst.writes.first().is_some_and(|w| w.1 == lo))
  784. .then_some(inst)
  785. }
  786. /// The operands of a VALU addition (`v_add_co_u32`, `v_add_nc_u32`)
  787. /// writing `v`, through VGPR copies of scalars.
  788. fn vadd(&self, v: Value) -> Option<[Term; 2]> {
  789. let inst = self.def(v)?;
  790. let Fields::Valu(f) = &inst.fields else {
  791. return None;
  792. };
  793. if !matches!(inst.name(), "v_add_co_u32" | "v_add_nc_u32")
  794. || f.dst.is_none_or(|d| !matches!(d, Operand::Vector { .. }))
  795. || inst.write(Reg::V(match f.dst? {
  796. Operand::Vector { reg, .. } => reg,
  797. _ => return None,
  798. })) != Some(v)
  799. || f.abs != 0
  800. || f.neg != 0
  801. || f.sdwa.is_some()
  802. || f.dpp.is_some()
  803. {
  804. return None;
  805. }
  806. Some([
  807. self.vterm(inst, f.src.first()?)?,
  808. self.vterm(inst, f.src.get(1)?)?,
  809. ])
  810. }
  811. /// The origin of a VALU operand.
  812. fn vterm(&self, inst: &Inst, op: &Operand) -> Option<Term> {
  813. match *op {
  814. Operand::Vector { reg, .. } => Some(self.vorigin(inst.read(Reg::V(reg))?)),
  815. op => self.term(inst, &op),
  816. }
  817. }
  818. /// A VGPR value's origin through `v_mov_b32` copies.
  819. fn vorigin(&self, v: Value) -> Term {
  820. if let Some(inst) = self.def(v)
  821. && inst.name() == "v_mov_b32"
  822. && let Fields::Valu(f) = &inst.fields
  823. && f.abs == 0
  824. && f.neg == 0
  825. && f.sdwa.is_none()
  826. && f.dpp.is_none()
  827. && let Some(t) = f.src.first().and_then(|s| self.vterm(inst, s))
  828. {
  829. return t;
  830. }
  831. self.origin(v)
  832. }
  833. /// The address of an access that traces to no root parameter (`why`
  834. /// says how it failed): title memory at the address as it stands, in a
  835. /// compute program.
  836. fn by_address(&self, why: &'static str) -> Result<Address, &'static str> {
  837. if self.stage == HwStage::Cs && RAW.contains(&why) {
  838. Ok(Address {
  839. param: MEMORY,
  840. offset: 0,
  841. dynamic: None,
  842. })
  843. } else {
  844. Err(why)
  845. }
  846. }
  847. /// A global memory address: an SGPR pair plus a VGPR offset, or a VGPR
  848. /// pair.
  849. fn flat_address(
  850. &self,
  851. inst: &Inst,
  852. addr: Option<&Operand>,
  853. saddr: Option<&Operand>,
  854. offset: i16,
  855. ) -> Result<Address, &'static str> {
  856. let Some(&Operand::Vector { reg, .. }) = addr else {
  857. return Err("a global address not in VGPRs");
  858. };
  859. let off = offset as i32 as u32;
  860. match saddr {
  861. Some(&Operand::Scalar { code, .. }) if code != NULL => {
  862. let word = |k| Some(self.origin(inst.read(Reg::S(code + k))?));
  863. let (Some(lo), Some(hi)) = (word(0), word(1)) else {
  864. return Err("an address not in SGPRs");
  865. };
  866. let v = inst.read(Reg::V(reg)).ok_or("a global address")?;
  867. let mut extra = self.sum(self.vorigin(v));
  868. if extra.base.is_some() {
  869. return Err("an offset from a root parameter");
  870. }
  871. extra.offset = extra.offset.wrapping_add(off);
  872. self.address(lo, hi, extra)
  873. }
  874. _ => {
  875. let word = |k| inst.read(Reg::V(reg + k)).map(|v| self.vorigin(v));
  876. let (Some(lo), Some(hi)) = (word(0), word(1)) else {
  877. return Err("a global address");
  878. };
  879. self.address(
  880. lo,
  881. hi,
  882. Sum {
  883. base: None,
  884. offset: off,
  885. dynamic: None,
  886. },
  887. )
  888. }
  889. }
  890. }
  891. /// The address `lo` and `hi` hold, plus `extra` (an instruction's
  892. /// immediate and offset register).
  893. fn address(&self, lo: Term, hi: Term, extra: Sum) -> Result<Address, &'static str> {
  894. // The high half as the lanes that read through the address hold
  895. // it, where that is a constant or what a register held on entry
  896. // (the code clears a table address's high half inside a branch
  897. // and uses the address after the join).
  898. let hi = match self.live(hi) {
  899. t @ Term::Const(_) => t,
  900. Term::Value(v) if self.inputs[v.0 as usize].is_some() => Term::Value(v),
  901. _ => hi,
  902. };
  903. let s = self.sum(lo);
  904. if s.dynamic.is_some() && extra.dynamic.is_some() {
  905. return Err("an address with two computed terms");
  906. }
  907. let base = s.base.ok_or_else(|| self.why_no_base(s.dynamic))?;
  908. if let Some(pc) = self.getpc(base) {
  909. // A table in the code: the base is the next instruction's offset.
  910. let high = pc.writes.get(1).map(|w| w.1);
  911. if !self.high_half(hi, high) && !high.is_some_and(|h| self.carried(hi, h)) {
  912. return Err("an address with an untracked high half");
  913. }
  914. // A join of paths into tables in the code is the byte in the code
  915. // already: each path's `s_getpc_b64` counts as its own offset.
  916. let joined = s.dynamic.is_some_and(|d| self.code_join(d).is_some());
  917. let first = if joined { 0 } else { pc.machine.offset as u32 + 4 };
  918. return Ok(Address {
  919. param: CODE,
  920. offset: first.wrapping_add(s.offset).wrapping_add(extra.offset),
  921. dynamic: s.dynamic.or(extra.dynamic),
  922. });
  923. }
  924. let reg = self.inputs[base.0 as usize].ok_or("an address not from a root parameter")?;
  925. let (param, _) = self
  926. .param_of(reg)
  927. .ok_or("an address not from a root parameter")?;
  928. let high = match self.layout[param].root {
  929. RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap => None,
  930. RootType::Descriptor => {
  931. let high = Reg::S(self.stage.user_sgpr(self.layout[param].user_data) + 1);
  932. let input = self.p.inputs.iter().find(|i| i.0 == high);
  933. Some(input.ok_or("a root descriptor without its high half")?.1)
  934. }
  935. _ => return Err("an address from a root parameter that is no address"),
  936. };
  937. // shortcut: with a computed term, a high half that adds anything to the
  938. // base's is taken as the carry of that term (offsets below 4 GB).
  939. let dynamic = s.dynamic.or(extra.dynamic);
  940. if !self.high_half(hi, high)
  941. && !(dynamic.is_some() && high.is_some_and(|h| self.carried(hi, h)))
  942. {
  943. return Err("an address with an untracked high half");
  944. }
  945. Ok(Address {
  946. param,
  947. offset: s.offset.wrapping_add(extra.offset),
  948. dynamic: s.dynamic.or(extra.dynamic),
  949. })
  950. }
  951. /// `hi` is `high` (0 for a table), possibly plus a carry.
  952. fn high_half(&self, hi: Term, high: Option<Value>) -> bool {
  953. let want = high.map_or(Term::Const(0), Term::Value);
  954. hi == want
  955. || matches!(hi, Term::Value(v) if self.sop2(v, &["s_addc_u32"]).is_some_and(
  956. |(_, [a, b])| a == want && b == Term::Const(0) || b == want && a == Term::Const(0)
  957. ))
  958. }
  959. /// `hi` adds something (with carry) to `high`: `s_addc_u32` or
  960. /// `v_add_co_ci_u32` with `high` as an operand.
  961. fn carried(&self, hi: Term, high: Value) -> bool {
  962. let Term::Value(v) = hi else { return false };
  963. if v == high {
  964. return true;
  965. }
  966. // A join ([`Self::code_join`]): every path carries into the table's high half.
  967. if let Some((b, i)) = self.phis[v.0 as usize] {
  968. // A path may carry into another table's high half ([`Self::code_join`]).
  969. let high_of = |t: Term| self.is_high(t, high) || self.code_high(t);
  970. return self.p.blocks[b].phis[i].args.iter().all(|&a| {
  971. let t = self.vorigin(a);
  972. if t == Term::Value(v) || high_of(t) {
  973. return true;
  974. }
  975. let Term::Value(x) = t else {
  976. return false;
  977. };
  978. // Computed in VGPRs and taken from the first lane.
  979. let x = match self.first_lane(x).map(|lane| self.vorigin(lane)) {
  980. Some(Term::Value(y)) => y,
  981. Some(Term::Const(_)) => return false,
  982. None => x,
  983. };
  984. let Some(inst) = self.def(x) else {
  985. return false;
  986. };
  987. let Fields::Valu(f) = &inst.fields else {
  988. return false;
  989. };
  990. inst.name() == "v_add_co_ci_u32"
  991. && f.src[..2.min(f.src.len())]
  992. .iter()
  993. .any(|o| self.vterm(inst, o).is_some_and(high_of))
  994. });
  995. }
  996. if let Some(lane) = self.first_lane(v) {
  997. return self.carried(self.vorigin(lane), high);
  998. }
  999. if let Some((_, [a, b])) = self.sop2(v, &["s_addc_u32"]) {
  1000. return self.carried(a, high) || self.carried(b, high);
  1001. }
  1002. let Some(inst) = self.def(v) else {
  1003. return false;
  1004. };
  1005. let Fields::Valu(f) = &inst.fields else {
  1006. return false;
  1007. };
  1008. inst.name() == "v_add_co_ci_u32"
  1009. && f.src[..2.min(f.src.len())]
  1010. .iter()
  1011. .any(|o| self.vterm(inst, o).is_some_and(|t| self.carried(t, high)))
  1012. }
  1013. fn why_no_base(&self, dynamic: Option<Value>) -> &'static str {
  1014. let Some(v) = dynamic else {
  1015. return "a constant address";
  1016. };
  1017. if self.inputs[v.0 as usize].is_some() {
  1018. return "an address in an SGPR that is no root parameter";
  1019. }
  1020. if self
  1021. .leaves(v)
  1022. .any(|l| self.def(l).is_some_and(|i| i.name() == "s_getpc_b64"))
  1023. {
  1024. return "an address relative to the program counter";
  1025. }
  1026. match self.def(v).map(|i| i.name()) {
  1027. Some(n) if n.starts_with("s_load_") => "an address loaded from memory",
  1028. None => "an address from a phi",
  1029. _ => "an address not from a root parameter",
  1030. }
  1031. }
  1032. /// The terms of the additions that compute `v`.
  1033. fn leaves(&self, v: Value) -> Box<dyn Iterator<Item = Value> + '_> {
  1034. match self.sop2(v, &["s_add_u32", "s_add_i32"]) {
  1035. Some((_, terms)) => Box::new(terms.into_iter().flat_map(move |t| match t {
  1036. Term::Value(x) => self.leaves(x),
  1037. Term::Const(_) => Box::new(std::iter::empty()),
  1038. })),
  1039. None => Box::new(std::iter::once(v)),
  1040. }
  1041. }
  1042. fn smem_address(
  1043. &self,
  1044. inst: &Inst,
  1045. base: &Operand,
  1046. offset: i32,
  1047. soffset: &Operand,
  1048. ) -> Result<Address, &'static str> {
  1049. let Operand::Scalar { code, .. } = *base else {
  1050. return Err("an address not in SGPRs");
  1051. };
  1052. let word = |k| Some(self.origin(inst.read(Reg::S(code + k))?));
  1053. let (Some(lo), Some(hi)) = (word(0), word(1)) else {
  1054. return Err("an address not in SGPRs");
  1055. };
  1056. let mut extra = self.sum(
  1057. self.term(inst, soffset)
  1058. .ok_or("an unknown offset operand")?,
  1059. );
  1060. if extra.base.is_some() {
  1061. return Err("an offset from a root parameter");
  1062. }
  1063. extra.offset = extra.offset.wrapping_add(offset as u32);
  1064. self.address(lo, hi, extra)
  1065. }
  1066. /// The source of the descriptor operand `op` of `inst`, in block `at`.
  1067. fn descriptor(&self, inst: &Inst, op: &Operand, at: usize) -> Result<Source, &'static str> {
  1068. let Operand::Scalar { code, dwords } = *op else {
  1069. return Err("a descriptor not in SGPRs");
  1070. };
  1071. let words = (0..dwords)
  1072. .map(|k| inst.read(Reg::S(code + k)).map(|v| self.origin(v)))
  1073. .collect::<Option<Vec<_>>>()
  1074. .ok_or("a descriptor not in SGPRs")?;
  1075. // Only the lanes that reach the access read the descriptor.
  1076. let mut known = Vec::from_iter(self.lanes.map(|l| (l.reach[at], true)));
  1077. self.classify(&words, &mut Vec::new(), &mut known)
  1078. }
  1079. /// The source of a descriptor's words; `joins` are the phi blocks
  1080. /// being resolved, `known` holds in every lane that reads them.
  1081. fn classify(
  1082. &self,
  1083. words: &[Term],
  1084. joins: &mut Vec<usize>,
  1085. known: &mut Known,
  1086. ) -> Result<Source, &'static str> {
  1087. if let Some(source) = self.phi(words, joins, known)? {
  1088. return Ok(source);
  1089. }
  1090. if let Some(source) = self.select(words, joins, known)? {
  1091. return Ok(source);
  1092. }
  1093. let read = |w: &Term| match *w {
  1094. Term::Value(v) => self.first_lane_source(v),
  1095. Term::Const(_) => None,
  1096. };
  1097. if let Some(sources) = words.iter().map(read).collect::<Option<Vec<_>>>() {
  1098. // One descriptor the code keeps per lane: the lanes agree.
  1099. if let Some(source) = self.lane_copies(words) {
  1100. return Ok(source);
  1101. }
  1102. // Read from the first active lane, as a waterfall loop does: the
  1103. // dwords each lane holds.
  1104. let lanes: Vec<Term> = sources.into_iter().map(Term::Value).collect();
  1105. return self.per_lane(&lanes, joins, known);
  1106. }
  1107. if words.iter().any(|w| read(w).is_some()) {
  1108. return Err("a descriptor partly read from the first lane");
  1109. }
  1110. if let Some(consts) = words
  1111. .iter()
  1112. .map(|w| match *w {
  1113. Term::Const(c) => Some(c),
  1114. Term::Value(_) => None,
  1115. })
  1116. .collect::<Option<Vec<_>>>()
  1117. {
  1118. return Ok(Source::Constant(consts));
  1119. }
  1120. if let Some(source) = self.loaded(words) {
  1121. return Ok(source);
  1122. }
  1123. if let [lo, hi, Term::Const(w2), Term::Const(w3)] = *words {
  1124. let (mut hi, mut bits) = (hi, 0);
  1125. while let Term::Value(v) = hi
  1126. && let Some((x, more)) = self.set_bits(v)
  1127. {
  1128. (hi, bits) = (x, bits | more);
  1129. }
  1130. let address = self.address(
  1131. lo,
  1132. hi,
  1133. Sum {
  1134. base: None,
  1135. offset: 0,
  1136. dynamic: None,
  1137. },
  1138. )?;
  1139. return Ok(Source::Built {
  1140. address,
  1141. bits,
  1142. words: [w2, w3],
  1143. });
  1144. }
  1145. let loaded = |w: &Term| {
  1146. matches!(*w, Term::Value(v)
  1147. if self.def(v).is_some_and(|i| i.name().starts_with("s_load_")))
  1148. };
  1149. Err(if words.iter().any(loaded) {
  1150. "a descriptor changed after loading"
  1151. } else {
  1152. "a descriptor neither loaded nor built"
  1153. })
  1154. }
  1155. /// The one edge into the join `block` that lanes satisfying `known`
  1156. /// can have taken, if the lanes' paths ([`Structured`]) rule out every
  1157. /// other: the console compiler loads a descriptor (or clears an
  1158. /// address's high half) inside a branch that skips code when no lane
  1159. /// is left for it, and uses it after the join, where only lanes that
  1160. /// ran the branch are left (Grand Theft Auto VI's
  1161. /// `CS_Alpha_Schedule`: the registers' values from before the branch,
  1162. /// which the join also sees, are what a wave with no such lane holds).
  1163. /// None at loop headers and without the lanes' paths.
  1164. fn only_edge(&self, block: usize, known: &mut Known) -> Option<usize> {
  1165. let lanes = self.lanes?;
  1166. let preds = &self.p.blocks[block].preds;
  1167. if preds.len() < 2 || preds.iter().any(|&q| self.rpo[q] >= self.rpo[block]) {
  1168. return None;
  1169. }
  1170. let mut only = None;
  1171. for (j, &q) in preds.iter().enumerate() {
  1172. let n = known.len();
  1173. known.push((lanes.reach[q], true));
  1174. if let LaneExit::Branch {
  1175. when,
  1176. taken,
  1177. not_taken,
  1178. } = lanes.exits[q]
  1179. && taken != not_taken
  1180. {
  1181. known.push((when, taken == block));
  1182. }
  1183. let possible = self.meet(lanes, known);
  1184. known.truncate(n);
  1185. if possible {
  1186. if only.is_some() {
  1187. return None;
  1188. }
  1189. only = Some(j);
  1190. }
  1191. }
  1192. only
  1193. }
  1194. /// Whether lowering can make a handle for `source` in any block: its
  1195. /// heap index comes from root parameters and constants alone (a table
  1196. /// offset the code computes exists only where the load is).
  1197. fn anywhere(&self, source: &Source) -> bool {
  1198. match source {
  1199. Source::Constant(_) => true,
  1200. Source::Built { address, .. } => address.dynamic.is_none(),
  1201. Source::Loaded { load, .. } => {
  1202. let inst = self.inst(*load);
  1203. match &inst.fields {
  1204. Fields::Smem {
  1205. base,
  1206. offset,
  1207. soffset,
  1208. ..
  1209. } => self
  1210. .smem_address(inst, base, *offset, soffset)
  1211. .is_ok_and(|a| a.dynamic.is_none()),
  1212. _ => false,
  1213. }
  1214. }
  1215. _ => false,
  1216. }
  1217. }
  1218. /// `t` as the lanes that reach the access being traced hold it: through
  1219. /// joins they can have entered by one edge only ([`Self::only_edge`]).
  1220. fn live(&self, mut t: Term) -> Term {
  1221. let (Some(at), Some(lanes)) = (self.at.get(), self.lanes) else {
  1222. return t;
  1223. };
  1224. let mut known = vec![(lanes.reach[at], true)];
  1225. for _ in 0..MAX_JOINS {
  1226. let Term::Value(v) = t else { break };
  1227. let Some((block, i)) = self.phis[v.0 as usize] else {
  1228. break;
  1229. };
  1230. let Some(j) = self.only_edge(block, &mut known) else {
  1231. break;
  1232. };
  1233. t = self.origin(self.p.blocks[block].phis[i].args[j]);
  1234. }
  1235. t
  1236. }
  1237. /// Words that phis of one block join, traced per predecessor (words
  1238. /// defined before the join hold on every edge).
  1239. fn phi(
  1240. &self,
  1241. words: &[Term],
  1242. joins: &mut Vec<usize>,
  1243. known: &mut Known,
  1244. ) -> Result<Option<Source>, &'static str> {
  1245. let phi_of = |w: &Term| match *w {
  1246. Term::Value(v) => self.phis[v.0 as usize],
  1247. Term::Const(_) => None,
  1248. };
  1249. let Some((block, _)) = words.iter().find_map(phi_of) else {
  1250. return Ok(None);
  1251. };
  1252. if words.iter().filter_map(phi_of).any(|(b, _)| b != block) {
  1253. return Err("a descriptor joined in several blocks");
  1254. }
  1255. if joins.contains(&block) {
  1256. return Err("a descriptor that changes in a loop");
  1257. }
  1258. // Each level multiplies the sources by the predecessor count.
  1259. if joins.len() >= MAX_JOINS {
  1260. return Err("a descriptor joined too often");
  1261. }
  1262. joins.push(block);
  1263. let phis = &self.p.blocks[block].phis;
  1264. let edge = |j: usize| -> Vec<Term> {
  1265. words
  1266. .iter()
  1267. .map(|w| match phi_of(w) {
  1268. Some((_, i)) => self.origin(phis[i].args[j]),
  1269. None => *w,
  1270. })
  1271. .collect()
  1272. };
  1273. let args = (0..self.p.blocks[block].preds.len())
  1274. .map(|j| self.classify(&edge(j), joins, known))
  1275. .collect::<Result<_, _>>();
  1276. let source = match args {
  1277. Ok(args) => Ok(Source::Phi { block, args }),
  1278. // An edge holds no descriptor. With only one edge the lanes
  1279. // that read the descriptor can have come by, it is what the
  1280. // registers hold on that one (a wave that took another edge
  1281. // has no lane left that reads it), if that can be named where
  1282. // it is read.
  1283. Err(e) => match self.only_edge(block, known) {
  1284. Some(j) => match self.classify(&edge(j), joins, known) {
  1285. Ok(source) if self.anywhere(&source) => Ok(source),
  1286. _ => Err(e),
  1287. },
  1288. None => Err(e),
  1289. },
  1290. };
  1291. joins.pop();
  1292. source.map(Some)
  1293. }
  1294. /// Words that `s_cselect` (or `s_cmov`) picks by one SCC value, traced
  1295. /// per outcome (other words are the same for both).
  1296. fn select(
  1297. &self,
  1298. words: &[Term],
  1299. joins: &mut Vec<usize>,
  1300. known: &mut Known,
  1301. ) -> Result<Option<Source>, &'static str> {
  1302. let picks: Vec<_> = words
  1303. .iter()
  1304. .map(|w| match *w {
  1305. Term::Value(v) => self.picked(v),
  1306. Term::Const(_) => None,
  1307. })
  1308. .collect();
  1309. let Some(scc) = picks.iter().flatten().map(|p| p.0).next() else {
  1310. return Ok(None);
  1311. };
  1312. if picks.iter().flatten().any(|p| p.0 != scc) {
  1313. return Err("a descriptor chosen by several conditions");
  1314. }
  1315. // Each level doubles the sources; selects count like joins (a
  1316. // marker no block index reaches).
  1317. if joins.len() >= MAX_JOINS {
  1318. return Err("a descriptor joined too often");
  1319. }
  1320. joins.push(usize::MAX);
  1321. let side = |set: bool| -> Vec<Term> {
  1322. words
  1323. .iter()
  1324. .zip(&picks)
  1325. .map(|(w, p)| match p {
  1326. Some((_, t, f)) => {
  1327. if set {
  1328. *t
  1329. } else {
  1330. *f
  1331. }
  1332. }
  1333. None => *w,
  1334. })
  1335. .collect()
  1336. };
  1337. let args = [true, false]
  1338. .into_iter()
  1339. .map(|set| self.classify(&side(set), joins, known))
  1340. .collect::<Result<_, _>>();
  1341. joins.pop();
  1342. Ok(Some(Source::Select { scc, args: args? }))
  1343. }
  1344. /// For `v` written by `s_cselect_b32`/`_b64` or `s_cmov_b32`/`_b64`:
  1345. /// the SCC it reads and the dword it is when SCC is set, then clear.
  1346. fn picked(&self, v: Value) -> Option<(Value, Term, Term)> {
  1347. let inst = self.def(v)?;
  1348. let Fields::Sop { dst, src, .. } = &inst.fields else {
  1349. return None;
  1350. };
  1351. let k = inst.writes.iter().position(|w| w.1 == v)? as u8;
  1352. let wide = match inst.name() {
  1353. "s_cselect_b32" | "s_cmov_b32" => false,
  1354. "s_cselect_b64" | "s_cmov_b64" => true,
  1355. _ => return None,
  1356. };
  1357. // A dword of a 32- or 64-bit operand: 64-bit inline integers are
  1358. // sign-extended; 64-bit literals and float constants are not
  1359. // followed.
  1360. let dword = |op: &Operand| match *op {
  1361. Operand::Scalar { code: NULL, .. } => Some(Term::Const(0)),
  1362. Operand::Scalar { code, .. } => Some(self.origin(inst.read(Reg::S(code + k))?)),
  1363. Operand::Const(c) if !wide => inline(c).map(Term::Const),
  1364. Operand::Const(c @ 128..=208) => {
  1365. let low = inline(c)?;
  1366. Some(Term::Const(if k == 0 {
  1367. low
  1368. } else {
  1369. ((low as i32) >> 31) as u32
  1370. }))
  1371. }
  1372. Operand::Literal(x) if !wide => Some(Term::Const(x)),
  1373. _ => None,
  1374. };
  1375. let set = dword(src.first()?)?;
  1376. let clear = if inst.name().starts_with("s_cmov") {
  1377. dword(dst.as_ref()?)?
  1378. } else {
  1379. dword(src.get(1)?)?
  1380. };
  1381. Some((inst.read(Reg::Scc)?, set, clear))
  1382. }
  1383. /// `v` as some other dword with constant bits set.
  1384. fn set_bits(&self, v: Value) -> Option<(Term, u32)> {
  1385. if let Some((_, [x, Term::Const(bits)] | [Term::Const(bits), x])) =
  1386. self.sop2(v, &["s_or_b32"])
  1387. {
  1388. return Some((x, bits));
  1389. }
  1390. let inst = self.def(v)?;
  1391. let Fields::Sop {
  1392. dst: Some(Operand::Scalar { code, .. }),
  1393. src,
  1394. ..
  1395. } = &inst.fields
  1396. else {
  1397. return None;
  1398. };
  1399. match (inst.name(), self.term(inst, src.first()?)?) {
  1400. ("s_bitset1_b32", Term::Const(bit)) => {
  1401. Some((self.origin(inst.read(Reg::S(*code))?), 1 << (bit & 31)))
  1402. }
  1403. _ => None,
  1404. }
  1405. }
  1406. /// For a `v_readfirstlane_b32` result: the VGPR value it reads.
  1407. fn first_lane_source(&self, v: Value) -> Option<Value> {
  1408. let inst = self.def(v)?;
  1409. let Fields::Valu(f) = &inst.fields else {
  1410. return None;
  1411. };
  1412. if inst.name() != "v_readfirstlane_b32" || f.sdwa.is_some() || f.dpp.is_some() {
  1413. return None;
  1414. }
  1415. let Some(&Operand::Vector { reg, .. }) = f.src.first() else {
  1416. return None;
  1417. };
  1418. inst.read(Reg::V(reg))
  1419. }
  1420. /// The `v_readfirstlane_b32` result the scalar load at `load` adds to
  1421. /// its address as a table offset (the console's waterfall,
  1422. /// `s_load_dwordx8 .., s[4:5], s20`): `track` proves the waterfall from
  1423. /// it, and lowering reads it per lane there.
  1424. fn first_lane_offset(&self, load: Site) -> Option<Value> {
  1425. let inst = self.inst(load);
  1426. let Fields::Smem {
  1427. base,
  1428. offset,
  1429. soffset,
  1430. ..
  1431. } = &inst.fields
  1432. else {
  1433. return None;
  1434. };
  1435. self.read_first_lane.set(true);
  1436. let address = self.smem_address(inst, base, *offset, soffset);
  1437. self.read_first_lane.set(false);
  1438. match self.origin(address.ok()?.dynamic?) {
  1439. Term::Value(v) if self.first_lane_source(v).is_some() => Some(v),
  1440. _ => None,
  1441. }
  1442. }
  1443. /// Whether the descriptor operand `op` of `inst` is one the code keeps
  1444. /// per lane ([`Self::lane_copies`]).
  1445. fn kept_per_lane(&self, inst: &Inst, op: &Operand) -> bool {
  1446. let Operand::Scalar { code, dwords } = *op else {
  1447. return false;
  1448. };
  1449. (0..dwords)
  1450. .map(|k| inst.read(Reg::S(code + k)).map(|v| self.origin(v)))
  1451. .collect::<Option<Vec<_>>>()
  1452. .is_some_and(|words| self.lane_copies(&words).is_some())
  1453. }
  1454. /// The `v_readfirstlane_b32` results the descriptor operand `op` of
  1455. /// `inst` is, when every dword is one.
  1456. fn first_lane_words(&self, inst: &Inst, op: &Operand) -> Option<Vec<Value>> {
  1457. let Operand::Scalar { code, dwords } = *op else {
  1458. return None;
  1459. };
  1460. (0..dwords)
  1461. .map(|k| match self.origin(inst.read(Reg::S(code + k))?) {
  1462. Term::Value(v) => self.first_lane_source(v).map(|_| v),
  1463. Term::Const(_) => None,
  1464. })
  1465. .collect()
  1466. }
  1467. /// `t` through VGPR copies (of VGPRs or of scalars) and copies.
  1468. fn lane_term(&self, mut t: Term) -> Term {
  1469. for _ in 0..MAX_JOINS * 2 {
  1470. let Term::Value(v) = t else { break };
  1471. let next = self.vorigin(v);
  1472. if next == t {
  1473. break;
  1474. }
  1475. t = next;
  1476. }
  1477. t
  1478. }
  1479. /// Whether `t` is a value each lane holds its own of (one in VGPRs).
  1480. fn varies(&self, t: Term) -> bool {
  1481. let Term::Value(v) = t else { return false };
  1482. let reg = match (self.inputs[v.0 as usize], self.phis[v.0 as usize]) {
  1483. (Some(reg), _) => Some(reg),
  1484. (None, Some((b, i))) => Some(self.p.blocks[b].phis[i].reg),
  1485. (None, None) => self
  1486. .def(v)
  1487. .and_then(|i| i.writes.iter().find(|w| w.1 == v))
  1488. .map(|w| w.0),
  1489. };
  1490. matches!(reg, Some(Reg::V(_)))
  1491. }
  1492. /// [`Self::lane_term`], where every lane in `known` runs each VGPR copy
  1493. /// it follows.
  1494. fn lane_value(&self, mut t: Term, known: &Known) -> Result<Term, &'static str> {
  1495. for _ in 0..MAX_JOINS * 2 {
  1496. let Term::Value(v) = t else { break };
  1497. let next = self.vstep(v);
  1498. if next == t {
  1499. break;
  1500. }
  1501. if self.varies(t)
  1502. && let Some(site) = self.defs[v.0 as usize]
  1503. {
  1504. self.runs(site, known)?;
  1505. }
  1506. t = next;
  1507. }
  1508. Ok(t)
  1509. }
  1510. /// One copy of [`Self::vorigin`]: what the `v_mov_b32` writing `v`
  1511. /// reads, or `v`'s origin.
  1512. fn vstep(&self, v: Value) -> Term {
  1513. if let Some(inst) = self.def(v)
  1514. && inst.name() == "v_mov_b32"
  1515. && let Fields::Valu(f) = &inst.fields
  1516. && f.abs == 0
  1517. && f.neg == 0
  1518. && f.sdwa.is_none()
  1519. && f.dpp.is_none()
  1520. && let Some(t) = f.src.first().and_then(|s| self.raw(inst, s))
  1521. {
  1522. return t;
  1523. }
  1524. self.origin(v)
  1525. }
  1526. /// A VALU operand as `inst` reads it: a VGPR's value itself, other
  1527. /// operands' origins.
  1528. fn raw(&self, inst: &Inst, op: &Operand) -> Option<Term> {
  1529. match *op {
  1530. Operand::Vector { reg, .. } => Some(Term::Value(inst.read(Reg::V(reg))?)),
  1531. op => self.term(inst, &op),
  1532. }
  1533. }
  1534. /// Fails unless every lane in `known` that reaches the vector
  1535. /// instruction at `site` runs it: one with its EXEC bit clear there
  1536. /// keeps what the registers held before.
  1537. fn runs(&self, site: Site, known: &Known) -> Result<(), &'static str> {
  1538. let Some(lanes) = self.lanes else {
  1539. return Ok(());
  1540. };
  1541. let Some(&Some(guard)) = lanes.guards.get(site.0).and_then(|g| g.get(site.1)) else {
  1542. return Ok(());
  1543. };
  1544. let mut skips = known.clone();
  1545. skips.extend([(lanes.reach[site.0], true), (guard, false)]);
  1546. if self.meet(lanes, &skips) {
  1547. return Err("a per-lane descriptor written where some lanes may keep the old one");
  1548. }
  1549. Ok(())
  1550. }
  1551. /// The source of descriptor dwords each lane holds its own of (a
  1552. /// waterfall loop reads them from the first active lane): the same in
  1553. /// every lane, loaded per lane from memory a heap address points to, or
  1554. /// picked per lane between such sources, by a lane mask or by the path
  1555. /// the lane took. `known` holds in every lane that accesses them.
  1556. fn per_lane(
  1557. &self,
  1558. words: &[Term],
  1559. joins: &mut Vec<usize>,
  1560. known: &mut Known,
  1561. ) -> Result<Source, &'static str> {
  1562. let words = words
  1563. .iter()
  1564. .map(|&w| self.lane_value(w, known))
  1565. .collect::<Result<Vec<_>, _>>()?;
  1566. let words = &words[..];
  1567. let Some(&lane) = words.iter().find(|&&w| self.varies(w)) else {
  1568. return self.classify(words, joins, known);
  1569. };
  1570. if let Some(source) = self.fetched(words, known)? {
  1571. return Ok(source);
  1572. }
  1573. if let Some(source) = self.lane_select(words, joins, known)? {
  1574. return Ok(source);
  1575. }
  1576. if let Some(source) = self.lane_phi(words, joins, known)? {
  1577. return Ok(source);
  1578. }
  1579. let Term::Value(v) = lane else { unreachable!() };
  1580. let name = self.def(v).map(|i| i.name());
  1581. Err(match name {
  1582. _ if self.inputs[v.0 as usize].is_some() => {
  1583. "a descriptor read from the first lane of an input VGPR"
  1584. }
  1585. None => "a descriptor read from the first lane of a phi",
  1586. Some(n) if n.starts_with("ds_read") => {
  1587. "a descriptor read from the first lane of an LDS read"
  1588. }
  1589. Some(n) if n.starts_with("buffer_load") => {
  1590. "a descriptor read from the first lane of a buffer load"
  1591. }
  1592. Some(n) if n.starts_with("global_load") || n.starts_with("flat_load") => {
  1593. "a descriptor read from the first lane of a partial or mixed load"
  1594. }
  1595. Some(_) => "a descriptor read from the first lane of computed VGPRs",
  1596. })
  1597. }
  1598. /// Dwords of `global_load_dword*` that line up: `first..` of one load,
  1599. /// then the bytes that follow (an image descriptor takes two
  1600. /// `global_load_dwordx4`).
  1601. fn fetched(&self, words: &[Term], known: &Known) -> Result<Option<Source>, &'static str> {
  1602. let at = |w: &Term| -> Option<(Site, usize)> {
  1603. let Term::Value(v) = *w else { return None };
  1604. let site = self.defs[v.0 as usize]?;
  1605. let inst = self.inst(site);
  1606. if !inst.name().starts_with("global_load_dword") {
  1607. return None;
  1608. }
  1609. let k = inst
  1610. .writes
  1611. .iter()
  1612. .filter(|w| matches!(w.0, Reg::V(_)))
  1613. .position(|w| w.1 == v)?;
  1614. Some((site, k))
  1615. };
  1616. let Some(sites) = words.iter().map(at).collect::<Option<Vec<_>>>() else {
  1617. return Ok(None);
  1618. };
  1619. let address = |site: Site| {
  1620. let inst = self.inst(site);
  1621. let Fields::Flat {
  1622. addr,
  1623. saddr,
  1624. offset,
  1625. ..
  1626. } = &inst.fields
  1627. else {
  1628. return Err("a global load");
  1629. };
  1630. self.flat_address(inst, addr.as_ref(), saddr.as_ref(), *offset)
  1631. };
  1632. let (load, first) = sites[0];
  1633. let a0 = address(load)?;
  1634. for (k, &(site, dword)) in sites.iter().enumerate() {
  1635. self.runs(site, known)?;
  1636. let a = address(site)?;
  1637. let want = a0.offset.wrapping_add(4 * (first + k) as u32);
  1638. if (a.param, a.dynamic) != (a0.param, a0.dynamic)
  1639. || a.offset.wrapping_add(4 * dword as u32) != want
  1640. {
  1641. return Err("a descriptor read from the first lane of loads that do not line up");
  1642. }
  1643. }
  1644. Ok(Some(Source::Fetched {
  1645. load,
  1646. first: first as u8,
  1647. }))
  1648. }
  1649. /// Words that `v_cndmask_b32` picks by one lane mask, traced per outcome
  1650. /// (other words are the same for both).
  1651. fn lane_select(
  1652. &self,
  1653. words: &[Term],
  1654. joins: &mut Vec<usize>,
  1655. known: &mut Known,
  1656. ) -> Result<Option<Source>, &'static str> {
  1657. let picks: Vec<_> = words
  1658. .iter()
  1659. .map(|w| match *w {
  1660. Term::Value(v) => self.lane_picked(v),
  1661. Term::Const(_) => None,
  1662. })
  1663. .collect();
  1664. let Some(mask) = picks.iter().flatten().map(|p| p.0).next() else {
  1665. return Ok(None);
  1666. };
  1667. if picks.iter().flatten().any(|p| p.0 != mask) {
  1668. return Err("a descriptor chosen per lane by several masks");
  1669. }
  1670. for (w, p) in words.iter().zip(&picks) {
  1671. if let (Term::Value(v), Some(_)) = (*w, p)
  1672. && let Some(site) = self.defs[v.0 as usize]
  1673. {
  1674. self.runs(site, known)?;
  1675. }
  1676. }
  1677. if joins.len() >= MAX_JOINS {
  1678. return Err("a descriptor joined too often");
  1679. }
  1680. joins.push(usize::MAX);
  1681. // Each side holds where the lane's bit of the mask is set, or clear.
  1682. let bit = self.lanes.and_then(|l| l.masks.get(&mask).copied());
  1683. let side = |set: bool| -> Vec<Term> {
  1684. words
  1685. .iter()
  1686. .zip(&picks)
  1687. .map(|(w, p)| match p {
  1688. Some((_, t, f)) => {
  1689. if set {
  1690. *t
  1691. } else {
  1692. *f
  1693. }
  1694. }
  1695. None => *w,
  1696. })
  1697. .collect()
  1698. };
  1699. let args = [true, false]
  1700. .into_iter()
  1701. .map(|set| {
  1702. let n = known.len();
  1703. known.extend(bit.map(|b| (b, set)));
  1704. let arg = self.per_lane(&side(set), joins, known);
  1705. known.truncate(n);
  1706. arg
  1707. })
  1708. .collect::<Result<_, _>>();
  1709. joins.pop();
  1710. Ok(Some(Source::Lanes { mask, args: args? }))
  1711. }
  1712. /// For `v` written by a plain `v_cndmask_b32`: the low dword of the
  1713. /// lane mask it reads, and the dword it is where the lane's bit is set
  1714. /// (src1), then clear (src0).
  1715. fn lane_picked(&self, v: Value) -> Option<(Value, Term, Term)> {
  1716. let inst = self.def(v)?;
  1717. let Fields::Valu(f) = &inst.fields else {
  1718. return None;
  1719. };
  1720. let Some(Operand::Vector { reg, .. }) = f.dst else {
  1721. return None;
  1722. };
  1723. if inst.name() != "v_cndmask_b32"
  1724. || inst.write(Reg::V(reg)) != Some(v)
  1725. || f.abs != 0
  1726. || f.neg != 0
  1727. || f.clamp
  1728. || f.omod != 0
  1729. || f.sdwa.is_some()
  1730. || f.dpp.is_some()
  1731. {
  1732. return None;
  1733. }
  1734. let [clear, set, Operand::Scalar { code, .. }] = f.src[..] else {
  1735. return None;
  1736. };
  1737. let mask = inst.read(Reg::S(code))?;
  1738. Some((mask, self.raw(inst, &set)?, self.raw(inst, &clear)?))
  1739. }
  1740. /// Per-lane words that phis of one block join, as an if/else on a
  1741. /// per-lane condition leaves them: traced on each edge into the block
  1742. /// that lanes in `known` can take (other words hold on every edge).
  1743. /// Lanes take their own paths ([`Structured`]), so each gets the value
  1744. /// of the edge it came by; an edge they cannot take is `None` (a flow
  1745. /// block's phi joins an arm's dwords with what lanes that skipped the
  1746. /// arm held before, which only they read).
  1747. fn lane_phi(
  1748. &self,
  1749. words: &[Term],
  1750. joins: &mut Vec<usize>,
  1751. known: &mut Known,
  1752. ) -> Result<Option<Source>, &'static str> {
  1753. let phi_of = |w: &Term| match *w {
  1754. Term::Value(v) => self.phis[v.0 as usize],
  1755. Term::Const(_) => None,
  1756. };
  1757. let Some((block, _)) = words.iter().find_map(phi_of) else {
  1758. return Ok(None);
  1759. };
  1760. if words.iter().filter_map(phi_of).any(|(b, _)| b != block) {
  1761. return Err("a descriptor joined in several blocks");
  1762. }
  1763. if joins.contains(&block) {
  1764. return Err("a descriptor that changes in a loop");
  1765. }
  1766. let preds = &self.p.blocks[block].preds;
  1767. if preds.iter().any(|&q| self.rpo[q] >= self.rpo[block]) {
  1768. // shortcut: what a lane holds after some passes is not traced.
  1769. return Err("a descriptor read from the first lane of a phi at a loop header");
  1770. }
  1771. let Some(lanes) = self.lanes else {
  1772. return Err("a descriptor read from the first lane of a phi, without the lanes' paths");
  1773. };
  1774. // The other words must be there before the join: defined in a
  1775. // block that dominates it, which (both dominating the access) is
  1776. // one the join does not reach.
  1777. for w in words {
  1778. if let Term::Value(v) = *w
  1779. && phi_of(w).is_none()
  1780. && let Some((d, _)) = self.defs[v.0 as usize]
  1781. && (d == block || self.reaches(block, d))
  1782. {
  1783. return Err("a descriptor partly joined by control flow");
  1784. }
  1785. }
  1786. if joins.len() >= MAX_JOINS {
  1787. return Err("a descriptor joined too often");
  1788. }
  1789. joins.push(block);
  1790. let phis = &self.p.blocks[block].phis;
  1791. let mut args = Vec::new();
  1792. for (j, &q) in preds.iter().enumerate() {
  1793. let n = known.len();
  1794. known.push((lanes.reach[q], true));
  1795. if let LaneExit::Branch {
  1796. when,
  1797. taken,
  1798. not_taken,
  1799. } = lanes.exits[q]
  1800. && taken != not_taken
  1801. {
  1802. known.push((when, taken == block));
  1803. }
  1804. let arg = if self.meet(lanes, known) {
  1805. let edge: Vec<Term> = words
  1806. .iter()
  1807. .map(|w| match phi_of(w) {
  1808. Some((_, i)) => Term::Value(phis[i].args[j]),
  1809. None => *w,
  1810. })
  1811. .collect();
  1812. self.per_lane(&edge, joins, known).map(Some)
  1813. } else {
  1814. Ok(None)
  1815. };
  1816. known.truncate(n);
  1817. match arg {
  1818. Ok(a) => args.push(a),
  1819. Err(e) => {
  1820. joins.pop();
  1821. return Err(e);
  1822. }
  1823. }
  1824. }
  1825. joins.pop();
  1826. Ok(Some(Source::LanePhi { block, args }))
  1827. }
  1828. /// Whether a path leads from block `from` to block `to` (to `from`
  1829. /// itself only through a back edge).
  1830. fn reaches(&self, from: usize, to: usize) -> bool {
  1831. let mut seen = vec![false; self.p.blocks.len()];
  1832. let mut stack = self.p.blocks[from].exit.successors();
  1833. while let Some(x) = stack.pop() {
  1834. if x == to {
  1835. return true;
  1836. }
  1837. if std::mem::replace(&mut seen[x], true) {
  1838. continue;
  1839. }
  1840. stack.extend(self.p.blocks[x].exit.successors());
  1841. }
  1842. false
  1843. }
  1844. /// Prove a single-block waterfall at the descriptor access. In each
  1845. /// iteration the access serves exactly the matching lanes, and the
  1846. /// back edge keeps exactly the other lanes active. Otherwise, why not.
  1847. ///
  1848. // shortcut: only the accesses are proven. Any other per-lane work in the
  1849. // loop is taken to run once for each lane, as the access does; a body
  1850. // whose effect adds up over the passes a lane waits through (a counter
  1851. // before the mask is narrowed) would differ. Compilers put nothing but
  1852. // the reads, the compares and the access in these loops.
  1853. fn waterfall(
  1854. &self,
  1855. b: usize,
  1856. accesses: &[usize],
  1857. reads: &[Value],
  1858. ) -> Result<Waterfall, &'static str> {
  1859. const LOOP: &str = "a descriptor read from the first lane outside a waterfall loop";
  1860. const SPLIT: &str = "a waterfall loop nested in another or split over blocks";
  1861. const SELECT: &str = "a waterfall loop whose compares do not select the access's lanes";
  1862. const RETRY: &str = "a waterfall loop whose retry does not keep the lanes still waiting";
  1863. let access = accesses[0];
  1864. let block = &self.p.blocks[b];
  1865. let lanes = self.lanes.ok_or(LOOP)?;
  1866. let exit = block.insts.last().ok_or(LOOP)?;
  1867. if !matches!(block.exit, Exit::Branch { taken, not_taken } if taken == b && not_taken != b)
  1868. || exit.name() != "s_cbranch_execnz"
  1869. {
  1870. return Err(LOOP);
  1871. }
  1872. let mask = |low: Option<Value>, high: Option<Value>| {
  1873. let high = if self.p.wave64 { Some(high?) } else { None };
  1874. lanes.mask_bits(low?, high)
  1875. };
  1876. let exec = |inst: &Inst| mask(inst.read(Reg::S(EXEC)), inst.read(Reg::S(EXEC + 1)));
  1877. // The reads belong to this loop's own block: a loop around this one
  1878. // (one per operand, as LLVM nests them for a per-lane image and
  1879. // sampler) is not followed.
  1880. if reads
  1881. .iter()
  1882. .any(|v| self.defs[v.0 as usize].is_none_or(|at| at.0 != b))
  1883. {
  1884. return Err(SPLIT);
  1885. }
  1886. let selected = exec(&block.insts[access]).ok_or(SELECT)?;
  1887. if accesses
  1888. .iter()
  1889. .any(|&i| exec(&block.insts[i]) != Some(selected))
  1890. {
  1891. return Err(SELECT);
  1892. }
  1893. let retry = exec(exit).ok_or(RETRY)?;
  1894. let first = self.defs[reads[0].0 as usize].ok_or(LOOP)?;
  1895. let remaining = exec(self.inst(first)).ok_or(SELECT)?;
  1896. if reads.iter().any(|v| {
  1897. self.defs[v.0 as usize]
  1898. .is_none_or(|at| at.1 >= access || exec(self.inst(at)) != Some(remaining))
  1899. }) {
  1900. return Err(SELECT);
  1901. }
  1902. let reach = (lanes.reach[b], true);
  1903. let meet = |conditions: &[(Bool, bool)]| self.meet(lanes, conditions);
  1904. let mut out = Waterfall::default();
  1905. let mut required = vec![(remaining, true)];
  1906. for (i, inst) in block.insts[..access].iter().enumerate() {
  1907. let Fields::Valu(f) = &inst.fields else {
  1908. continue;
  1909. };
  1910. let Some(ty) = inst
  1911. .name()
  1912. .strip_prefix("v_cmp_eq_")
  1913. .or(inst.name().strip_prefix("v_cmpx_eq_"))
  1914. else {
  1915. continue;
  1916. };
  1917. let dwords = match ty {
  1918. "u32" | "i32" => 1,
  1919. "u64" | "i64" => 2,
  1920. _ => continue,
  1921. };
  1922. if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() {
  1923. continue;
  1924. }
  1925. // The first lane's dwords on one side, the lane's own on the
  1926. // other.
  1927. let pair = |first: &Operand, own: &Operand| -> Option<Vec<Value>> {
  1928. let (&Operand::Scalar { code, .. }, &Operand::Vector { reg, .. }) = (first, own)
  1929. else {
  1930. return None;
  1931. };
  1932. (0..dwords)
  1933. .map(|k| {
  1934. let Term::Value(x) = self.origin(inst.read(Reg::S(code + k))?) else {
  1935. return None;
  1936. };
  1937. let lane = inst.read(Reg::V(reg + k))?;
  1938. let (_, read) = self.defs[x.0 as usize]?;
  1939. let same = reads.contains(&x)
  1940. && read < i
  1941. && self.lane_term(Term::Value(self.first_lane_source(x)?))
  1942. == self.lane_term(Term::Value(lane));
  1943. same.then_some(x)
  1944. })
  1945. .collect()
  1946. };
  1947. let (Some(a), Some(c)) = (f.src.first(), f.src.get(1)) else {
  1948. continue;
  1949. };
  1950. if let Some(xs) = pair(a, c).or_else(|| pair(c, a)) {
  1951. let code = if inst.name().starts_with("v_cmpx_") {
  1952. EXEC
  1953. } else if let Some(Operand::Scalar { code, .. }) = f.dst {
  1954. code
  1955. } else {
  1956. continue;
  1957. };
  1958. let Some(matched) = mask(inst.write(Reg::S(code)), inst.write(Reg::S(code + 1))) else {
  1959. continue;
  1960. };
  1961. if meet(&[reach, (selected, true), (matched, false)]) {
  1962. continue;
  1963. }
  1964. required.push((matched, true));
  1965. out.compares.push((b, i));
  1966. for x in xs {
  1967. if !out.reads.contains(&x) {
  1968. out.reads.push(x);
  1969. }
  1970. }
  1971. }
  1972. }
  1973. if reads.iter().any(|v| !out.reads.contains(v))
  1974. || meet(&[reach, (selected, true), (remaining, false)])
  1975. {
  1976. return Err(SELECT);
  1977. }
  1978. // The access must take every match.
  1979. required.extend([reach, (selected, false)]);
  1980. if meet(&required) {
  1981. return Err(SELECT);
  1982. }
  1983. // The retry must keep exactly the lanes that were eligible but did
  1984. // not perform the access.
  1985. if meet(&[reach, (retry, true), (remaining, false)])
  1986. || meet(&[reach, (retry, true), (selected, true)])
  1987. || meet(&[reach, (remaining, true), (selected, false), (retry, false)])
  1988. {
  1989. return Err(RETRY);
  1990. }
  1991. Ok(out)
  1992. }
  1993. /// Consecutive dwords of one scalar load.
  1994. fn loaded(&self, words: &[Term]) -> Option<Source> {
  1995. let Term::Value(v0) = words[0] else {
  1996. return None;
  1997. };
  1998. let load = self.defs[v0.0 as usize]?;
  1999. let inst = self.inst(load);
  2000. if !inst.name().starts_with("s_load_") {
  2001. return None;
  2002. }
  2003. let first = inst.writes.iter().position(|w| w.1 == v0)?;
  2004. let same = words.iter().enumerate().all(|(k, w)| {
  2005. inst.writes
  2006. .get(first + k)
  2007. .is_some_and(|x| *w == Term::Value(x.1))
  2008. });
  2009. same.then_some(Source::Loaded {
  2010. load,
  2011. first: first as u8,
  2012. })
  2013. }
  2014. /// A descriptor the code keeps per lane: every dword of `words` is the
  2015. /// first lane (`v_readfirstlane_b32`) of a VGPR that `v_mov_b32` filled
  2016. /// from SGPRs. The console compiler does this to a descriptor loaded on
  2017. /// both sides of a per-lane branch: the join is per lane, so it lives in
  2018. /// VGPRs, and the instruction that needs it in SGPRs runs in a loop over
  2019. /// the distinct values (the first lane's, the lanes holding the same,
  2020. /// then the rest). When every scalar those moves copy is the same dword
  2021. /// of loads from one constant address, the lanes agree and the
  2022. /// descriptor is any of those loads.
  2023. // shortcut: what else the VGPRs held (numbers, on paths or in lanes that
  2024. // never read them as a descriptor) is ignored, and a move is taken to
  2025. // leave either its source or what a move before it wrote; a descriptor
  2026. // read per lane from memory (`global_load_*`) refuses.
  2027. fn lane_copies(&self, words: &[Term]) -> Option<Source> {
  2028. let mut loads: Vec<Site> = Vec::new();
  2029. let mut first = None;
  2030. for (k, w) in words.iter().enumerate() {
  2031. let Term::Value(v) = *w else { return None };
  2032. let mut copies = Vec::new();
  2033. if !self.scalar_copies(self.first_lane(v)?, &mut copies) {
  2034. return None;
  2035. }
  2036. let mut found = false;
  2037. for c in copies {
  2038. let Term::Value(c) = c else { continue };
  2039. let Some(site) = self.defs[c.0 as usize] else {
  2040. continue;
  2041. };
  2042. let load = self.inst(site);
  2043. if !load.name().starts_with("s_load_") {
  2044. continue;
  2045. }
  2046. // Dword k of the operand is dword `first + k` of each load.
  2047. let dword = load.writes.iter().position(|x| x.1 == c)?;
  2048. let f = dword.checked_sub(k)?;
  2049. if *first.get_or_insert(f) != f {
  2050. return None;
  2051. }
  2052. if !loads.contains(&site) {
  2053. loads.push(site);
  2054. }
  2055. found = true;
  2056. }
  2057. if !found {
  2058. return None;
  2059. }
  2060. }
  2061. let address = |site: Site| {
  2062. let inst = self.inst(site);
  2063. match &inst.fields {
  2064. Fields::Smem {
  2065. base,
  2066. offset,
  2067. soffset,
  2068. ..
  2069. } => self.smem_address(inst, base, *offset, soffset).ok(),
  2070. _ => None,
  2071. }
  2072. };
  2073. let a = address(*loads.first()?)?;
  2074. if a.dynamic.is_some() || loads.iter().any(|&l| address(l) != Some(a)) {
  2075. return None;
  2076. }
  2077. // The handle is made where the descriptor is used, from the load's
  2078. // operands: take a load whose base is the root parameter's own SGPR.
  2079. loads.sort_unstable();
  2080. let load = *loads.iter().find(|&&l| self.base_from_entry(l))?;
  2081. self.lane_copied.borrow_mut().extend(&loads);
  2082. Some(Source::Loaded {
  2083. load,
  2084. first: first? as u8,
  2085. })
  2086. }
  2087. /// The scalars (as origins) that `v_mov_b32` copies put in VGPR value
  2088. /// `v`, through joins, moves between VGPRs and per-lane selects; a move
  2089. /// keeps what it wrote over in the lanes it does not run. False if the
  2090. /// VGPR may hold something read per lane from memory.
  2091. fn scalar_copies(&self, v: Value, out: &mut Vec<Term>) -> bool {
  2092. let (mut seen, mut work) = (Vec::new(), vec![v]);
  2093. while let Some(v) = work.pop() {
  2094. if seen.contains(&v) {
  2095. continue;
  2096. }
  2097. if seen.len() == MAX_COPIES {
  2098. return false;
  2099. }
  2100. seen.push(v);
  2101. if let Some((b, i)) = self.phis[v.0 as usize] {
  2102. work.extend(&self.p.blocks[b].phis[i].args);
  2103. continue;
  2104. }
  2105. // An entry value, or a number some instruction computed.
  2106. let Some(inst) = self.def(v) else { continue };
  2107. if inst.name().starts_with("global_load_") {
  2108. return false;
  2109. }
  2110. let Fields::Valu(f) = &inst.fields else {
  2111. continue;
  2112. };
  2113. let sources = match inst.name() {
  2114. "v_mov_b32" => 1,
  2115. "v_cndmask_b32" => 2,
  2116. _ => continue,
  2117. };
  2118. if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() {
  2119. continue;
  2120. }
  2121. for op in f.src.iter().take(sources) {
  2122. match *op {
  2123. Operand::Vector { reg, .. } => work.extend(inst.read(Reg::V(reg))),
  2124. Operand::Scalar { code, .. } if code != NULL => {
  2125. out.extend(inst.read(Reg::S(code)).map(|s| self.origin(s)));
  2126. }
  2127. _ => {}
  2128. }
  2129. }
  2130. // Lanes outside EXEC keep the old value.
  2131. if let Some(Operand::Vector { reg, .. }) = f.dst {
  2132. work.extend(inst.read(Reg::V(reg)));
  2133. }
  2134. }
  2135. true
  2136. }
  2137. /// The load at `site` has a constant offset and takes its base from a
  2138. /// root parameter's SGPR through moves alone: a value that exists
  2139. /// wherever the descriptor is used.
  2140. fn base_from_entry(&self, site: Site) -> bool {
  2141. let inst = self.inst(site);
  2142. let Fields::Smem {
  2143. base: Operand::Scalar { code, .. },
  2144. soffset: Operand::Scalar { code: NULL, .. },
  2145. ..
  2146. } = &inst.fields
  2147. else {
  2148. return false;
  2149. };
  2150. let Some(mut v) = inst.read(Reg::S(*code)) else {
  2151. return false;
  2152. };
  2153. loop {
  2154. if self.inputs[v.0 as usize].is_some() {
  2155. return true;
  2156. }
  2157. let Some(def) = self.def(v) else { return false };
  2158. let Some(k) = def.writes.iter().position(|w| w.1 == v) else {
  2159. return false;
  2160. };
  2161. match copy_source(def, k) {
  2162. Some(Moved::Value(s)) => v = s,
  2163. _ => return false,
  2164. }
  2165. }
  2166. }
  2167. }
  2168. #[derive(Clone, Copy, PartialEq, Eq)]
  2169. enum Moved {
  2170. Const(u32),
  2171. Value(Value),
  2172. }
  2173. impl Tracer<'_> {
  2174. /// For `v_readlane_b32` of a constant lane: the SGPR spilled to that
  2175. /// lane, found by following the VGPR's `v_writelane_b32` writes.
  2176. fn restored(&self, inst: &Inst) -> Option<Moved> {
  2177. let Fields::Valu(v) = &inst.fields else {
  2178. return None;
  2179. };
  2180. if inst.name() != "v_readlane_b32" {
  2181. return None;
  2182. }
  2183. let [Operand::Vector { reg, .. }, lane] = v.src[..] else {
  2184. return None;
  2185. };
  2186. self.spilled(inst.read(Reg::V(reg))?, lane_of(lane)?, &mut Vec::new())
  2187. .ok()
  2188. .flatten()
  2189. }
  2190. /// What lane `lane` of VGPR value `v` holds: `Ok(None)` for a phi in
  2191. /// `seen` (already being resolved), `Err` if not a spilled SGPR.
  2192. fn spilled(&self, v: Value, lane: u32, seen: &mut Vec<Value>) -> Result<Option<Moved>, ()> {
  2193. if let Some((b, i)) = self.phis[v.0 as usize] {
  2194. if seen.contains(&v) {
  2195. return Ok(None);
  2196. }
  2197. seen.push(v);
  2198. let mut found = None;
  2199. for &a in &self.p.blocks[b].phis[i].args {
  2200. if let Some(m) = self.spilled(a, lane, seen)? {
  2201. if found.is_some_and(|f| f != m) {
  2202. return Err(());
  2203. }
  2204. found = Some(m);
  2205. }
  2206. }
  2207. return Ok(found);
  2208. }
  2209. let inst = self.def(v).ok_or(())?;
  2210. let Fields::Valu(w) = &inst.fields else {
  2211. return Err(());
  2212. };
  2213. let (Some(Operand::Vector { reg, .. }), [value, at]) = (w.dst, &w.src[..]) else {
  2214. return Err(());
  2215. };
  2216. if inst.name() != "v_writelane_b32" {
  2217. return Err(());
  2218. }
  2219. if lane_of(*at).ok_or(())? != lane {
  2220. return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, seen);
  2221. }
  2222. match *value {
  2223. Operand::Scalar { code, .. } if code != NULL => {
  2224. inst.read(Reg::S(code)).map(Moved::Value)
  2225. }
  2226. Operand::Literal(x) => Some(Moved::Const(x)),
  2227. Operand::Const(c) => inline(c).map(Moved::Const),
  2228. _ => None,
  2229. }
  2230. .map(Some)
  2231. .ok_or(())
  2232. }
  2233. }
  2234. /// A lane select given as a constant.
  2235. fn lane_of(op: Operand) -> Option<u32> {
  2236. match op {
  2237. Operand::Const(c) => inline(c),
  2238. Operand::Literal(x) => Some(x),
  2239. _ => None,
  2240. }
  2241. }
  2242. /// What dword `k` of a move's result copies.
  2243. fn copy_source(inst: &Inst, k: usize) -> Option<Moved> {
  2244. let Fields::Sop { src, imm, .. } = &inst.fields else {
  2245. return None;
  2246. };
  2247. if inst.name() == "s_movk_i32" {
  2248. return Some(Moved::Const(i32::from((*imm)? as i16) as u32));
  2249. }
  2250. let src = src.first()?;
  2251. match (inst.name(), *src) {
  2252. ("s_mov_b32" | "s_mov_b64", Operand::Scalar { code, .. }) if code != NULL => {
  2253. inst.read(Reg::S(code + k as u8)).map(Moved::Value)
  2254. }
  2255. ("s_mov_b32" | "s_mov_b64", Operand::Scalar { .. }) => Some(Moved::Const(0)),
  2256. ("s_mov_b32", Operand::Literal(x)) => Some(Moved::Const(x)),
  2257. ("s_mov_b32", Operand::Const(c)) => inline(c).map(Moved::Const),
  2258. // shortcut: only the one-operand ways the compiler makes a constant
  2259. // that has no inline form; fold more if descriptors need it.
  2260. ("s_brev_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(x.reverse_bits())),
  2261. ("s_not_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(!x)),
  2262. // 64-bit inline integers are sign-extended.
  2263. ("s_mov_b64", Operand::Const(c @ 128..=208)) => {
  2264. let low = inline(c)?;
  2265. Some(Moved::Const(if k == 0 {
  2266. low
  2267. } else {
  2268. ((low as i32) >> 31) as u32
  2269. }))
  2270. }
  2271. _ => None,
  2272. }
  2273. }
  2274. /// The 32-bit value of an inline constant operand.
  2275. pub(crate) fn inline(code: u8) -> Option<u32> {
  2276. let float = |f: f32| Some(f.to_bits());
  2277. match code {
  2278. 128..=192 => Some(u32::from(code) - 128),
  2279. 193..=208 => Some((192 - i32::from(code)) as u32),
  2280. 240 => float(0.5),
  2281. 241 => float(-0.5),
  2282. 242 => float(1.0),
  2283. 243 => float(-1.0),
  2284. 244 => float(2.0),
  2285. 245 => float(-2.0),
  2286. 246 => float(4.0),
  2287. 247 => float(-4.0),
  2288. 248 => Some(0x3E22_F983),
  2289. _ => None,
  2290. }
  2291. }
  2292. #[cfg(test)]
  2293. pub(crate) mod tests {
  2294. use super::*;
  2295. use crate::native::RootType::*;
  2296. const S_ENDPGM: u32 = 0xBF81_0000;
  2297. fn track_words(words: &[u32], layout: &[RootParam], stage: HwStage) -> Resources {
  2298. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  2299. let p = crate::ir::build(&code, false, 256).unwrap();
  2300. track(&p, layout, stage, lanes(&p).as_ref()).unwrap()
  2301. }
  2302. /// `p` as one lane runs it, if it structures.
  2303. fn lanes(p: &Program) -> Option<Structured> {
  2304. crate::structure::structure(p).ok()
  2305. }
  2306. fn param(root: RootType, user_data: u8, sgprs: u32) -> RootParam {
  2307. RootParam {
  2308. root,
  2309. table_offset_dwords: 0,
  2310. sgprs,
  2311. base_register: 0,
  2312. user_data,
  2313. slot: 0,
  2314. }
  2315. }
  2316. fn at(param: usize, offset: u32) -> Address {
  2317. Address {
  2318. param,
  2319. offset,
  2320. dynamic: None,
  2321. }
  2322. }
  2323. #[test]
  2324. fn table_descriptors_are_loaded_from_their_range() {
  2325. let r = track_words(
  2326. &[
  2327. 0xBE82_0309, // s_mov_b32 s2, s9
  2328. 0xBE89_0380, // s_mov_b32 s9, 0
  2329. 0xBE83_0380, // s_mov_b32 s3, 0
  2330. 0xF408_0204,
  2331. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[8:9], null
  2332. 0xF40C_0001,
  2333. 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null
  2334. 0xF080_0F08,
  2335. 0x0040_0002, // image_sample v[0:3], v[2:3], s[0:7], s[8:11]
  2336. S_ENDPGM,
  2337. ],
  2338. &[param(Table, 8, 1), param(Table, 9, 1)],
  2339. HwStage::Ps,
  2340. );
  2341. assert_eq!(r.scalar, [((0, 3), at(0, 0)), ((0, 4), at(1, 0))]);
  2342. let roles: Vec<_> = r.descriptors.iter().map(|d| (d.role, &d.source)).collect();
  2343. assert_eq!(
  2344. roles,
  2345. [
  2346. (
  2347. Role::Resource,
  2348. &Source::Loaded {
  2349. load: (0, 4),
  2350. first: 0
  2351. }
  2352. ),
  2353. (
  2354. Role::Sampler,
  2355. &Source::Loaded {
  2356. load: (0, 3),
  2357. first: 0
  2358. }
  2359. ),
  2360. ]
  2361. );
  2362. }
  2363. #[test]
  2364. fn root_descriptors_are_built_in_code() {
  2365. let r = track_words(
  2366. &[
  2367. 0x8801_FF0B,
  2368. 0x0010_0000, // s_or_b32 s1, s11, 0x100000
  2369. 0xBE80_030A, // s_mov_b32 s0, s10
  2370. 0xBE82_03C1, // s_mov_b32 s2, -1
  2371. 0xBE83_03FF,
  2372. 0x1101_4FAC, // s_mov_b32 s3, 0x11014fac
  2373. 0xF430_0000,
  2374. 0xFA00_0000, // s_buffer_load_dwordx16 s[0:15], s[0:3], null
  2375. S_ENDPGM,
  2376. ],
  2377. &[param(Descriptor, 10, 2)],
  2378. HwStage::Vs,
  2379. );
  2380. assert_eq!(
  2381. r.descriptors[0].source,
  2382. Source::Built {
  2383. address: at(0, 0),
  2384. bits: 0x10_0000,
  2385. words: [u32::MAX, 0x1101_4FAC]
  2386. }
  2387. );
  2388. assert_eq!(
  2389. r.params.iter().map(|p| (p.1, p.2)).collect::<Vec<_>>(),
  2390. [(0, 0), (0, 1)]
  2391. );
  2392. }
  2393. #[test]
  2394. fn heap_indices_from_root_constants_in_a_merged_stage() {
  2395. // User data starts at s8: the constant (index 6) is s14, the heap
  2396. // (index 10) s18.
  2397. let code = [
  2398. 0x8F08_850E, // s_lshl_b32 s8, s14, 5
  2399. 0xBE93_0380, // s_mov_b32 s19, 0
  2400. 0xF408_0209,
  2401. 0x1000_0000, // s_load_dwordx4 s[8:11], s[18:19], s8
  2402. 0xE000_2000,
  2403. 0x8002_0400, // buffer_load_format_x v4, v0, s[8:11], 0 idxen
  2404. S_ENDPGM,
  2405. ];
  2406. let r = track_words(
  2407. &code,
  2408. &[param(Constants, 6, 1), param(ResourceHeap, 10, 1)],
  2409. HwStage::Ms,
  2410. );
  2411. let index = r.params.iter().find(|p| p.1 == 0).unwrap().0;
  2412. let shift = r.scalar[0].1.dynamic.unwrap();
  2413. assert_eq!(r.scalar[0].1.param, 1);
  2414. // The computed term is the shifted constant, not the constant itself.
  2415. assert_ne!(shift, index);
  2416. assert_eq!(
  2417. r.descriptors[0].source,
  2418. Source::Loaded {
  2419. load: (0, 2),
  2420. first: 0
  2421. }
  2422. );
  2423. assert!(r.root_indexed_views.is_empty());
  2424. let table = RootParam {
  2425. slot: 7,
  2426. ..param(Table, 10, 1)
  2427. };
  2428. let indexed = track_words(&code, &[param(Constants, 6, 1), table], HwStage::Ms);
  2429. assert_eq!(
  2430. indexed.root_indexed_views,
  2431. [RootIndexedView {
  2432. table_slot: 7,
  2433. constant_slot: 0,
  2434. constant_dword: 0,
  2435. byte_offset: 0,
  2436. shift: 5,
  2437. }]
  2438. );
  2439. let nonconstant = track_words(&code, &[param(Table, 6, 1), table], HwStage::Ms);
  2440. assert!(nonconstant.root_indexed_views.is_empty());
  2441. }
  2442. #[test]
  2443. fn spilled_sgprs_are_followed_through_vgpr_lanes() {
  2444. let r = track_words(
  2445. &[
  2446. 0xD761_0000,
  2447. 0x0001_0609, // v_writelane_b32 v0, s9, 3
  2448. 0xD760_0002,
  2449. 0x0001_0700, // v_readlane_b32 s2, v0, 3
  2450. 0xBE83_0380, // s_mov_b32 s3, 0
  2451. 0xF40C_0001,
  2452. 0xFA00_0020, // s_load_dwordx8 s[0:7], s[2:3], 0x20
  2453. S_ENDPGM,
  2454. ],
  2455. &[param(Table, 9, 1)],
  2456. HwStage::Ps,
  2457. );
  2458. assert_eq!(r.scalar, [((0, 3), at(0, 0x20))]);
  2459. }
  2460. #[test]
  2461. fn descriptors_joined_by_control_flow_are_traced_per_edge() {
  2462. let r = track_words(
  2463. &[
  2464. 0xBE82_0309, // s_mov_b32 s2, s9
  2465. 0xBE83_0380, // s_mov_b32 s3, 0
  2466. 0xBF06_8001, // s_cmp_eq_u32 s1, 0
  2467. 0xBF85_0003, // s_cbranch_scc1 -> 0x1c
  2468. 0xF408_0001,
  2469. 0xFA00_0000, // s_load_dwordx4 s[0:3], s[2:3], null
  2470. 0xBF82_0002, // s_branch -> 0x24
  2471. 0xF408_0001,
  2472. 0xFA00_0010, // 0x1c: s_load_dwordx4 s[0:3], s[2:3], 0x10
  2473. 0xF420_0100,
  2474. 0xFA00_0000, // 0x24: s_buffer_load_dword s4, s[0:3], null
  2475. S_ENDPGM,
  2476. ],
  2477. &[param(Table, 9, 1)],
  2478. HwStage::Ps,
  2479. );
  2480. let Source::Phi { args, .. } = &r.descriptors[0].source else {
  2481. panic!("{:?}", r.descriptors)
  2482. };
  2483. let offsets: Vec<_> = args
  2484. .iter()
  2485. .map(|a| match a {
  2486. Source::Loaded { load, .. } => {
  2487. r.scalar.iter().find(|s| s.0 == *load).unwrap().1.offset
  2488. }
  2489. a => panic!("{a:?}"),
  2490. })
  2491. .collect();
  2492. assert_eq!(offsets.len(), 2);
  2493. assert!(
  2494. offsets.contains(&0) && offsets.contains(&0x10),
  2495. "{offsets:?}"
  2496. );
  2497. }
  2498. /// Two paths add an index to one table in the code and meet before one load
  2499. /// (hair `CS_InterpolateStrands`): the join is the computed term, counted
  2500. /// from the `s_getpc_b64`.
  2501. #[test]
  2502. fn two_paths_into_one_code_table_load() {
  2503. let r = track_words(
  2504. &[
  2505. 0xBE82_1F00, // 0x00: s_getpc_b64 s[2:3]
  2506. 0x8002_FF02,
  2507. 0x0000_0040, // s_add_u32 s2, s2, 0x40
  2508. 0x8203_8003, // s_addc_u32 s3, s3, 0
  2509. 0xBF06_8001, // 0x10: s_cmp_eq_u32 s1, 0
  2510. 0xBF85_0005, // 0x14: s_cbranch_scc1 -> 0x2c
  2511. 0xD70F_0457,
  2512. 0x0000_054A, // 0x18: v_add_co_u32 v87, s4, v74, s2
  2513. 0xD528_0458,
  2514. 0x0010_0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4
  2515. 0xBF82_0004, // 0x28: s_branch -> 0x3c
  2516. 0xD70F_0457,
  2517. 0x0000_054B, // 0x2c: v_add_co_u32 v87, s4, v75, s2
  2518. 0xD528_0458,
  2519. 0x0010_0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4
  2520. 0xDC34_8000,
  2521. 0x577D_0057, // 0x3c: global_load_dwordx2 v[87:88], v[87:88], null
  2522. S_ENDPGM,
  2523. ],
  2524. &[],
  2525. HwStage::Cs,
  2526. );
  2527. assert_eq!(r.scalar.len(), 1);
  2528. let a = r.scalar[0].1;
  2529. assert_eq!((a.param, a.offset), (CODE, 0));
  2530. assert!(a.dynamic.is_some(), "the join is the computed term, the byte in the code");
  2531. }
  2532. /// An address into a table in the code computed per lane and taken from
  2533. /// the first lane (`avgLuminanceCompute` `ColorDownsample`): the per-lane
  2534. /// sum carries the `s_getpc_b64` base, so the first-lane read is looked
  2535. /// through and the lane's index is the computed term. (A first-lane read
  2536. /// of an index alone stays the computed term itself; see
  2537. /// `the_console_waterfall_over_a_first_lane_offset_is_one`.)
  2538. #[test]
  2539. fn a_code_table_address_taken_from_the_first_lane() {
  2540. let r = track_words(
  2541. &[
  2542. 0xBE82_1F00, // 0x00: s_getpc_b64 s[2:3]
  2543. 0xD70F_0457,
  2544. 0x0000_054A, // v_add_co_u32 v87, s4, v74, s2
  2545. 0xD528_0458,
  2546. 0x0010_0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4
  2547. 0x7E0C_0557, // v_readfirstlane_b32 s6, v87
  2548. 0x7E0E_0558, // v_readfirstlane_b32 s7, v88
  2549. 0xF400_0203,
  2550. 0xFA00_0000, // s_load_dword s8, s[6:7], 0x0
  2551. S_ENDPGM,
  2552. ],
  2553. &[],
  2554. HwStage::Cs,
  2555. );
  2556. assert_eq!(r.scalar.len(), 1);
  2557. let a = r.scalar[0].1;
  2558. assert_eq!((a.param, a.offset), (CODE, 4));
  2559. assert!(a.dynamic.is_some(), "the lane's index is the computed term");
  2560. }
  2561. #[test]
  2562. fn a_descriptor_kept_per_lane_is_its_load_and_needs_no_waterfall() {
  2563. // The console compiler's way with a descriptor it joins per lane:
  2564. // the dwords go to VGPRs and come back from the first lane. Every
  2565. // lane holds the one load's dwords, so the descriptor is that load
  2566. // (`lane_copied`), and no waterfall is asked for.
  2567. let mut words = vec![
  2568. 0xBE82_0309, // s_mov_b32 s2, s9
  2569. 0xBE83_0380, // s_mov_b32 s3, 0
  2570. 0xF40C_0001,
  2571. 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null
  2572. ];
  2573. // v_mov_b32 v10.., s0..; v_readfirstlane_b32 s16.., v10..
  2574. words.extend((0..8).map(|k| 0x7E00_0200 | (10 + k) << 17 | k));
  2575. words.extend((0..8).map(|k| 0x7E00_0400 | (16 + k) << 17 | (0x100 + 10 + k)));
  2576. words.extend([
  2577. 0xF000_1700,
  2578. 0x0004_0D06, // image_load v[13:15], v6, s[16:23]
  2579. S_ENDPGM,
  2580. ]);
  2581. let r = track_words(&words, &[param(Table, 9, 1)], HwStage::Ps);
  2582. let load = (0, 2);
  2583. assert_eq!(r.scalar, [(load, at(0, 0))]);
  2584. let sources: Vec<_> = r.descriptors.iter().map(|d| &d.source).collect();
  2585. assert_eq!(sources, [&Source::Loaded { load, first: 0 }]);
  2586. assert_eq!(r.lane_copied, [load]);
  2587. assert_eq!(r.waterfall, Waterfall::default());
  2588. }
  2589. #[test]
  2590. fn loads_at_one_first_lane_offset_have_one_address() {
  2591. // Two loads of the table entry at the offset v4 holds, each with
  2592. // its own first-lane read, as the console compiler loads a
  2593. // descriptor again wherever it needs it: one address, by which
  2594. // lowering knows them for the same descriptor.
  2595. let r = track_words(
  2596. &[
  2597. 0xBE82_0309, // s_mov_b32 s2, s9
  2598. 0xBE83_0380, // s_mov_b32 s3, 0
  2599. 0x7E08_0504, // v_readfirstlane_b32 s4, v4
  2600. 0xF40C_0201,
  2601. 0x0800_0000, // s_load_dwordx8 s[8:15], s[2:3], s4
  2602. 0x7E0A_0504, // v_readfirstlane_b32 s5, v4
  2603. 0xF40C_0401,
  2604. 0x0A00_0000, // s_load_dwordx8 s[16:23], s[2:3], s5
  2605. 0xF000_1700,
  2606. 0x0004_0D06, // image_load v[13:15], v6, s[16:23]
  2607. S_ENDPGM,
  2608. ],
  2609. &[param(Table, 9, 1)],
  2610. HwStage::Ps,
  2611. );
  2612. let [(_, a), (_, b)] = r.scalar[..] else {
  2613. panic!("{:?}", r.scalar)
  2614. };
  2615. assert_eq!(a, b);
  2616. assert_eq!((a.param, a.offset), (0, 0));
  2617. assert!(
  2618. a.dynamic.is_some(),
  2619. "the lane's offset is the computed term"
  2620. );
  2621. }
  2622. #[test]
  2623. fn descriptors_selected_by_scc_are_traced_per_outcome() {
  2624. // Two buffer descriptors loaded from the table at s9 and one
  2625. // picked with s_cselect_b64 per half, as the compiler makes a
  2626. // conditional choice of resources without a branch.
  2627. let r = track_words(
  2628. &[
  2629. 0xBE8C_0309, // s_mov_b32 s12, s9
  2630. 0xBE8D_0380, // s_mov_b32 s13, 0
  2631. 0xF408_0006,
  2632. 0xFA00_0000, // s_load_dwordx4 s[0:3], s[12:13], null
  2633. 0xF408_0106,
  2634. 0xFA00_0010, // s_load_dwordx4 s[4:7], s[12:13], 0x10
  2635. 0xBF06_800E, // s_cmp_eq_u32 s14, 0
  2636. 0x8588_0400, // s_cselect_b64 s[8:9], s[0:1], s[4:5]
  2637. 0x858A_0602, // s_cselect_b64 s[10:11], s[2:3], s[6:7]
  2638. 0xF420_0404,
  2639. 0xFA00_0000, // s_buffer_load_dword s16, s[8:11], null
  2640. S_ENDPGM,
  2641. ],
  2642. &[param(Table, 9, 1)],
  2643. HwStage::Ps,
  2644. );
  2645. let Source::Select { args, .. } = &r.descriptors[0].source else {
  2646. panic!("{:?}", r.descriptors)
  2647. };
  2648. // SCC set picks the first operand.
  2649. assert_eq!(
  2650. args[..],
  2651. [
  2652. Source::Loaded {
  2653. load: (0, 2),
  2654. first: 0
  2655. },
  2656. Source::Loaded {
  2657. load: (0, 3),
  2658. first: 0
  2659. },
  2660. ]
  2661. );
  2662. assert_eq!(r.scalar, [((0, 2), at(0, 0)), ((0, 3), at(0, 0x10))]);
  2663. }
  2664. #[test]
  2665. fn a_selection_that_mixes_two_descriptors_fails() {
  2666. // The high half picked from the first load whatever SCC is: when
  2667. // clear, the descriptor is half of one load and half of the other.
  2668. let code: Vec<u8> = [
  2669. 0xBE8C_0309, // s_mov_b32 s12, s9
  2670. 0xBE8D_0380, // s_mov_b32 s13, 0
  2671. 0xF408_0006,
  2672. 0xFA00_0000, // s_load_dwordx4 s[0:3], s[12:13], null
  2673. 0xF408_0106,
  2674. 0xFA00_0010, // s_load_dwordx4 s[4:7], s[12:13], 0x10
  2675. 0xBF06_800E, // s_cmp_eq_u32 s14, 0
  2676. 0x8588_0400, // s_cselect_b64 s[8:9], s[0:1], s[4:5]
  2677. 0x858A_0202, // s_cselect_b64 s[10:11], s[2:3], s[2:3]
  2678. 0xF420_0404,
  2679. 0xFA00_0000, // s_buffer_load_dword s16, s[8:11], null
  2680. S_ENDPGM,
  2681. ]
  2682. .iter()
  2683. .flat_map(|w: &u32| w.to_le_bytes())
  2684. .collect();
  2685. let p = crate::ir::build(&code, false, 256).unwrap();
  2686. let err = track(&p, &[param(Table, 9, 1)], HwStage::Ps, lanes(&p).as_ref()).unwrap_err();
  2687. assert_eq!(
  2688. err,
  2689. ShaderError::Unsupported {
  2690. offset: 36,
  2691. what: "a descriptor changed after loading"
  2692. }
  2693. );
  2694. }
  2695. #[test]
  2696. fn untraceable_addresses_fail_with_a_reason() {
  2697. let code: Vec<u8> = [0xF408_0001, 0xFA00_0000, S_ENDPGM] // s_load_dwordx4 s[0:3], s[2:3]
  2698. .iter()
  2699. .flat_map(|w: &u32| w.to_le_bytes())
  2700. .collect();
  2701. let p = crate::ir::build(&code, false, 256).unwrap();
  2702. let err = track(&p, &[param(Table, 9, 1)], HwStage::Ps, lanes(&p).as_ref()).unwrap_err();
  2703. assert_eq!(
  2704. err,
  2705. ShaderError::Unsupported {
  2706. offset: 0,
  2707. what: "an address in an SGPR that is no root parameter"
  2708. }
  2709. );
  2710. }
  2711. /// A waterfall loop over an image descriptor each lane loads from the
  2712. /// table at s0 (wave32, assembled with llvm-mc for gfx1030): lane i
  2713. /// reads entry i with two `global_load_dwordx4`, the loop reads the
  2714. /// first active lane's descriptor into s[12:19], samples with the lanes
  2715. /// whose descriptor it is, and repeats for the others. The sampler comes
  2716. /// from the table at s1; the result goes to LDS so the sample is needed.
  2717. pub(crate) const WATERFALL_FETCHED_WAVE32: &[u32] = &[
  2718. 0xBE84_0300, // s_mov_b32 s4, s0
  2719. 0xBE85_0380, // s_mov_b32 s5, 0
  2720. 0xBE86_0301, // s_mov_b32 s6, s1
  2721. 0xBE87_0380, // s_mov_b32 s7, 0
  2722. 0x3402_0085, // v_lshlrev_b32 v1, 5, v0
  2723. 0xDC38_8000,
  2724. 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5]
  2725. 0xDC38_8010,
  2726. 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16
  2727. 0xF408_0203,
  2728. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0
  2729. 0x7E04_0D00, // v_cvt_f32_u32 v2, v0
  2730. 0x7E06_0302, // v_mov_b32 v3, v2
  2731. 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0)
  2732. 0xBE94_037E, // s_mov_b32 s20, exec_lo
  2733. 0x7E18_0504, // 0x3c: v_readfirstlane_b32 s12, v4
  2734. 0x7E1A_0505, // v_readfirstlane_b32 s13, v5
  2735. 0x7E1C_0506, // v_readfirstlane_b32 s14, v6
  2736. 0x7E1E_0507, // v_readfirstlane_b32 s15, v7
  2737. 0x7E20_0508, // v_readfirstlane_b32 s16, v8
  2738. 0x7E22_0509, // v_readfirstlane_b32 s17, v9
  2739. 0x7E24_050A, // v_readfirstlane_b32 s18, v10
  2740. 0x7E26_050B, // v_readfirstlane_b32 s19, v11
  2741. 0xD4E2_0015,
  2742. 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5]
  2743. 0xD4E2_0016,
  2744. 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7]
  2745. 0x8715_1615, // s_and_b32 s21, s21, s22
  2746. 0xD4E2_0016,
  2747. 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9]
  2748. 0x8715_1615, // s_and_b32 s21, s21, s22
  2749. 0xD4E2_0016,
  2750. 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11]
  2751. 0x8715_1615, // s_and_b32 s21, s21, s22
  2752. 0xBE95_3C15, // s_and_saveexec_b32 s21, s21
  2753. 0xBF80_0000, // s_nop 0
  2754. 0xF09C_0F08,
  2755. 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
  2756. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  2757. 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21
  2758. 0xBF89_FFE6, // s_cbranch_execnz -> 0x3c
  2759. 0xBEFE_0314, // s_mov_b32 exec_lo, s20
  2760. 0xD834_0000,
  2761. 0x0000_0C00, // ds_write_b32 v0, v12
  2762. 0xBF81_0000, // s_endpgm
  2763. ];
  2764. /// [`WATERFALL_FETCHED_WAVE32`] in wave64: 64-bit lane masks.
  2765. pub(crate) const WATERFALL_FETCHED_WAVE64: &[u32] = &[
  2766. 0xBE84_0300, // s_mov_b32 s4, s0
  2767. 0xBE85_0380, // s_mov_b32 s5, 0
  2768. 0xBE86_0301, // s_mov_b32 s6, s1
  2769. 0xBE87_0380, // s_mov_b32 s7, 0
  2770. 0x3402_0085, // v_lshlrev_b32 v1, 5, v0
  2771. 0xDC38_8000,
  2772. 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5]
  2773. 0xDC38_8010,
  2774. 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16
  2775. 0xF408_0203,
  2776. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0
  2777. 0x7E04_0D00, // v_cvt_f32_u32 v2, v0
  2778. 0x7E06_0302, // v_mov_b32 v3, v2
  2779. 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0)
  2780. 0xBE94_047E, // s_mov_b64 s[20:21], exec
  2781. 0x7E18_0504, // 0x3c: v_readfirstlane_b32 s12, v4
  2782. 0x7E1A_0505, // v_readfirstlane_b32 s13, v5
  2783. 0x7E1C_0506, // v_readfirstlane_b32 s14, v6
  2784. 0x7E1E_0507, // v_readfirstlane_b32 s15, v7
  2785. 0x7E20_0508, // v_readfirstlane_b32 s16, v8
  2786. 0x7E22_0509, // v_readfirstlane_b32 s17, v9
  2787. 0x7E24_050A, // v_readfirstlane_b32 s18, v10
  2788. 0x7E26_050B, // v_readfirstlane_b32 s19, v11
  2789. 0xD4E2_0016,
  2790. 0x0002_080C, // v_cmp_eq_u64_e64 s[22:23], s[12:13], v[4:5]
  2791. 0xD4E2_0018,
  2792. 0x0002_0C0E, // v_cmp_eq_u64_e64 s[24:25], s[14:15], v[6:7]
  2793. 0x8796_1816, // s_and_b64 s[22:23], s[22:23], s[24:25]
  2794. 0xD4E2_0018,
  2795. 0x0002_1010, // v_cmp_eq_u64_e64 s[24:25], s[16:17], v[8:9]
  2796. 0x8796_1816, // s_and_b64 s[22:23], s[22:23], s[24:25]
  2797. 0xD4E2_0018,
  2798. 0x0002_1412, // v_cmp_eq_u64_e64 s[24:25], s[18:19], v[10:11]
  2799. 0x8796_1816, // s_and_b64 s[22:23], s[22:23], s[24:25]
  2800. 0xBE96_2416, // s_and_saveexec_b64 s[22:23], s[22:23]
  2801. 0xBF80_0000, // s_nop 0
  2802. 0xF09C_0F08,
  2803. 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
  2804. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  2805. 0x89FE_167E, // s_xor_b64 exec, exec, s[22:23]
  2806. 0xBF89_FFE6, // s_cbranch_execnz -> 0x3c
  2807. 0xBEFE_0414, // s_mov_b64 exec, s[20:21]
  2808. 0xD834_0000,
  2809. 0x0000_0C00, // ds_write_b32 v0, v12
  2810. 0xBF81_0000, // s_endpgm
  2811. ];
  2812. /// The same waterfall over one of two image descriptors loaded from the
  2813. /// table at s0, picked per lane by `v_cndmask_b32` (lanes below 16 take
  2814. /// the first).
  2815. pub(crate) const WATERFALL_PICKED_WAVE32: &[u32] = &[
  2816. 0xBE84_0300, // s_mov_b32 s4, s0
  2817. 0xBE85_0380, // s_mov_b32 s5, 0
  2818. 0xBE86_0301, // s_mov_b32 s6, s1
  2819. 0xBE87_0380, // s_mov_b32 s7, 0
  2820. 0xF40C_0602,
  2821. 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0
  2822. 0xF40C_0802,
  2823. 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20
  2824. 0xF408_0203,
  2825. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0
  2826. 0x7E04_0D00, // v_cvt_f32_u32 v2, v0
  2827. 0x7E06_0302, // v_mov_b32 v3, v2
  2828. 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0
  2829. 0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
  2830. 0x7E08_0218, // v_mov_b32 v4, s24
  2831. 0x0208_0820, // v_cndmask_b32 v4, s32, v4, vcc_lo
  2832. 0x7E0A_0219, // v_mov_b32 v5, s25
  2833. 0x020A_0A21, // v_cndmask_b32 v5, s33, v5, vcc_lo
  2834. 0x7E0C_021A, // v_mov_b32 v6, s26
  2835. 0x020C_0C22, // v_cndmask_b32 v6, s34, v6, vcc_lo
  2836. 0x7E0E_021B, // v_mov_b32 v7, s27
  2837. 0x020E_0E23, // v_cndmask_b32 v7, s35, v7, vcc_lo
  2838. 0x7E10_021C, // v_mov_b32 v8, s28
  2839. 0x0210_1024, // v_cndmask_b32 v8, s36, v8, vcc_lo
  2840. 0x7E12_021D, // v_mov_b32 v9, s29
  2841. 0x0212_1225, // v_cndmask_b32 v9, s37, v9, vcc_lo
  2842. 0x7E14_021E, // v_mov_b32 v10, s30
  2843. 0x0214_1426, // v_cndmask_b32 v10, s38, v10, vcc_lo
  2844. 0x7E16_021F, // v_mov_b32 v11, s31
  2845. 0x0216_1627, // v_cndmask_b32 v11, s39, v11, vcc_lo
  2846. 0xBE94_037E, // s_mov_b32 s20, exec_lo
  2847. 0x7E18_0504, // 0x7c: v_readfirstlane_b32 s12, v4
  2848. 0x7E1A_0505, // v_readfirstlane_b32 s13, v5
  2849. 0x7E1C_0506, // v_readfirstlane_b32 s14, v6
  2850. 0x7E1E_0507, // v_readfirstlane_b32 s15, v7
  2851. 0x7E20_0508, // v_readfirstlane_b32 s16, v8
  2852. 0x7E22_0509, // v_readfirstlane_b32 s17, v9
  2853. 0x7E24_050A, // v_readfirstlane_b32 s18, v10
  2854. 0x7E26_050B, // v_readfirstlane_b32 s19, v11
  2855. 0xD4E2_0015,
  2856. 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5]
  2857. 0xD4E2_0016,
  2858. 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7]
  2859. 0x8715_1615, // s_and_b32 s21, s21, s22
  2860. 0xD4E2_0016,
  2861. 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9]
  2862. 0x8715_1615, // s_and_b32 s21, s21, s22
  2863. 0xD4E2_0016,
  2864. 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11]
  2865. 0x8715_1615, // s_and_b32 s21, s21, s22
  2866. 0xBE95_3C15, // s_and_saveexec_b32 s21, s21
  2867. 0xBF80_0000, // s_nop 0
  2868. 0xF09C_0F08,
  2869. 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
  2870. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  2871. 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21
  2872. 0xBF89_FFE6, // s_cbranch_execnz -> 0x7c
  2873. 0xBEFE_0314, // s_mov_b32 exec_lo, s20
  2874. 0xD834_0000,
  2875. 0x0000_0C00, // ds_write_b32 v0, v12
  2876. 0xBF81_0000, // s_endpgm
  2877. ];
  2878. /// The waterfall loop of [`WATERFALL_PICKED_WAVE32`] over one of two
  2879. /// image descriptors loaded from the table at s0, chosen by control flow
  2880. /// as the compiler lowers an if/else on a per-lane condition: lanes below
  2881. /// 16 move the first into v[4:11], the others the second, each arm
  2882. /// skipped when no lane takes it. The sample goes to the buffer at dword
  2883. /// 16 of the table, at lane * 4.
  2884. pub(crate) const WATERFALL_JOINED_WAVE32: &[u32] = &[
  2885. 0xBE84_0300, // s_mov_b32 s4, s0
  2886. 0xBE85_0380, // s_mov_b32 s5, 0
  2887. 0xBE86_0301, // s_mov_b32 s6, s1
  2888. 0xBE87_0380, // s_mov_b32 s7, 0
  2889. 0xF40C_0602,
  2890. 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0
  2891. 0xF40C_0802,
  2892. 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20
  2893. 0xF408_0203,
  2894. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0
  2895. 0xF408_0A02,
  2896. 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40
  2897. 0x7E04_0D00, // v_cvt_f32_u32 v2, v0
  2898. 0x7E06_0302, // v_mov_b32 v3, v2
  2899. 0x3420_0082, // v_lshlrev_b32 v16, 2, v0
  2900. 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0
  2901. 0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
  2902. 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo
  2903. 0x8914_147E, // s_xor_b32 s20, exec_lo, s20
  2904. 0xBF88_0008, // s_cbranch_execz -> 0x70
  2905. 0x7E08_0218, // v_mov_b32 v4, s24
  2906. 0x7E0A_0219, // v_mov_b32 v5, s25
  2907. 0x7E0C_021A, // v_mov_b32 v6, s26
  2908. 0x7E0E_021B, // v_mov_b32 v7, s27
  2909. 0x7E10_021C, // v_mov_b32 v8, s28
  2910. 0x7E12_021D, // v_mov_b32 v9, s29
  2911. 0x7E14_021E, // v_mov_b32 v10, s30
  2912. 0x7E16_021F, // v_mov_b32 v11, s31
  2913. 0xBE94_3D14, // 0x70: s_or_saveexec_b32 s20, s20
  2914. 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20
  2915. 0xBF88_0008, // s_cbranch_execz -> 0x9c
  2916. 0x7E08_0220, // v_mov_b32 v4, s32
  2917. 0x7E0A_0221, // v_mov_b32 v5, s33
  2918. 0x7E0C_0222, // v_mov_b32 v6, s34
  2919. 0x7E0E_0223, // v_mov_b32 v7, s35
  2920. 0x7E10_0224, // v_mov_b32 v8, s36
  2921. 0x7E12_0225, // v_mov_b32 v9, s37
  2922. 0x7E14_0226, // v_mov_b32 v10, s38
  2923. 0x7E16_0227, // v_mov_b32 v11, s39
  2924. 0x887E_147E, // 0x9c: s_or_b32 exec_lo, exec_lo, s20
  2925. 0xBE97_037E, // s_mov_b32 s23, exec_lo
  2926. 0x7E18_0504, // 0xa4: v_readfirstlane_b32 s12, v4
  2927. 0x7E1A_0505, // v_readfirstlane_b32 s13, v5
  2928. 0x7E1C_0506, // v_readfirstlane_b32 s14, v6
  2929. 0x7E1E_0507, // v_readfirstlane_b32 s15, v7
  2930. 0x7E20_0508, // v_readfirstlane_b32 s16, v8
  2931. 0x7E22_0509, // v_readfirstlane_b32 s17, v9
  2932. 0x7E24_050A, // v_readfirstlane_b32 s18, v10
  2933. 0x7E26_050B, // v_readfirstlane_b32 s19, v11
  2934. 0xD4E2_0015,
  2935. 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5]
  2936. 0xD4E2_0016,
  2937. 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7]
  2938. 0x8715_1615, // s_and_b32 s21, s21, s22
  2939. 0xD4E2_0016,
  2940. 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9]
  2941. 0x8715_1615, // s_and_b32 s21, s21, s22
  2942. 0xD4E2_0016,
  2943. 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11]
  2944. 0x8715_1615, // s_and_b32 s21, s21, s22
  2945. 0xBE95_3C15, // s_and_saveexec_b32 s21, s21
  2946. 0xBF80_0000, // s_nop 0
  2947. 0xF09C_0F08,
  2948. 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
  2949. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  2950. 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21
  2951. 0xBF89_FFE6, // s_cbranch_execnz -> 0xa4
  2952. 0xBEFE_0317, // s_mov_b32 exec_lo, s23
  2953. 0xE070_1000,
  2954. 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen
  2955. 0xBF81_0000, // s_endpgm
  2956. ];
  2957. /// The console compiler's waterfall (Grand Theft Auto VI's ray-tracing
  2958. /// resolve and others): each lane holds its entry's byte offset in the
  2959. /// table at s0 (v7 = (lane & 1) * 32); the loop reads the first active
  2960. /// lane's offset, narrows EXEC to the lanes with the same one
  2961. /// (`v_cmpx_eq_u32`), loads that entry with `s_load_dwordx8` and samples,
  2962. /// then drops those lanes (`s_andn2_wrexec_b32`). The sample goes to the
  2963. /// buffer at dword 16 of the table, at lane * 4.
  2964. pub(crate) const WATERFALL_INDEXED_WAVE32: &[u32] = &[
  2965. 0xBE84_0300, // s_mov_b32 s4, s0
  2966. 0xBE85_0380, // s_mov_b32 s5, 0
  2967. 0xBE86_0301, // s_mov_b32 s6, s1
  2968. 0xBE87_0380, // s_mov_b32 s7, 0
  2969. 0xF408_0203,
  2970. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0
  2971. 0xF408_0A02,
  2972. 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40
  2973. 0x7E04_0D00, // v_cvt_f32_u32 v2, v0
  2974. 0x7E06_0302, // v_mov_b32 v3, v2
  2975. 0x3420_0082, // v_lshlrev_b32 v16, 2, v0
  2976. 0x360E_0081, // v_and_b32 v7, 1, v0
  2977. 0x340E_0E85, // v_lshlrev_b32 v7, 5, v7
  2978. 0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
  2979. 0xBE97_037E, // s_mov_b32 s23, exec_lo
  2980. 0xBE95_037E, // s_mov_b32 s21, exec_lo
  2981. 0x7E28_0507, // 0x40: v_readfirstlane_b32 s20, v7
  2982. 0x7DA4_0E14, // v_cmpx_eq_u32 exec_lo, s20, v7
  2983. 0xF40C_0302,
  2984. 0x2800_0000, // s_load_dwordx8 s[12:19], s[4:5], s20
  2985. 0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
  2986. 0xF09C_0F08,
  2987. 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
  2988. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  2989. 0xBE95_4715, // s_andn2_wrexec_b32 s21, s21
  2990. 0xBF89_FFF6, // s_cbranch_execnz -> 0x40
  2991. 0xBEFE_0317, // s_mov_b32 exec_lo, s23
  2992. 0xE070_1000,
  2993. 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen
  2994. 0xBF81_0000, // s_endpgm
  2995. ];
  2996. #[test]
  2997. fn the_console_waterfall_over_a_first_lane_offset_is_one() {
  2998. let r = waterfall(WATERFALL_INDEXED_WAVE32, false).unwrap();
  2999. let image = r
  3000. .descriptors
  3001. .iter()
  3002. .find(|d| d.role == Role::Resource)
  3003. .unwrap();
  3004. let Source::Loaded { load, first: 0 } = image.source else {
  3005. panic!("{:?}", image.source)
  3006. };
  3007. let (_, address) = r.scalar.iter().find(|s| s.0 == load).unwrap();
  3008. assert!(address.dynamic.is_some(), "{address:?}");
  3009. assert_eq!(r.waterfall.compares.len(), 1);
  3010. assert_eq!(r.waterfall.reads.len(), 1);
  3011. assert_eq!(r.waterfall.loads, [load]);
  3012. }
  3013. /// [`WATERFALL_JOINED_WAVE32`] with other sources on each path: lanes
  3014. /// below 16 load table entry (lane & 1) with two `global_load_dwordx4`,
  3015. /// the others pick per lane with `v_cndmask_b32` (lanes below 24 the
  3016. /// first entry, the rest the second).
  3017. pub(crate) const WATERFALL_JOINED_MIXED_WAVE32: &[u32] = &[
  3018. 0xBE84_0300, // s_mov_b32 s4, s0
  3019. 0xBE85_0380, // s_mov_b32 s5, 0
  3020. 0xBE86_0301, // s_mov_b32 s6, s1
  3021. 0xBE87_0380, // s_mov_b32 s7, 0
  3022. 0xF40C_0602,
  3023. 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0
  3024. 0xF40C_0802,
  3025. 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20
  3026. 0xF408_0203,
  3027. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0
  3028. 0xF408_0A02,
  3029. 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40
  3030. 0x7E04_0D00, // v_cvt_f32_u32 v2, v0
  3031. 0x7E06_0302, // v_mov_b32 v3, v2
  3032. 0x3420_0082, // v_lshlrev_b32 v16, 2, v0
  3033. 0x3602_0081, // v_and_b32 v1, 1, v0
  3034. 0x3402_0285, // v_lshlrev_b32 v1, 5, v1
  3035. 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0
  3036. 0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
  3037. 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo
  3038. 0x8914_147E, // s_xor_b32 s20, exec_lo, s20
  3039. 0xBF88_0004, // s_cbranch_execz -> 0x68
  3040. 0xDC38_8000,
  3041. 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5]
  3042. 0xDC38_8010,
  3043. 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16
  3044. 0xBE94_3D14, // 0x68: s_or_saveexec_b32 s20, s20
  3045. 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20
  3046. 0xBF88_0011, // s_cbranch_execz -> 0xb8
  3047. 0x7D88_0098, // v_cmp_gt_u32 vcc_lo, 24, v0
  3048. 0x7E08_0218, // v_mov_b32 v4, s24
  3049. 0x0208_0820, // v_cndmask_b32 v4, s32, v4, vcc_lo
  3050. 0x7E0A_0219, // v_mov_b32 v5, s25
  3051. 0x020A_0A21, // v_cndmask_b32 v5, s33, v5, vcc_lo
  3052. 0x7E0C_021A, // v_mov_b32 v6, s26
  3053. 0x020C_0C22, // v_cndmask_b32 v6, s34, v6, vcc_lo
  3054. 0x7E0E_021B, // v_mov_b32 v7, s27
  3055. 0x020E_0E23, // v_cndmask_b32 v7, s35, v7, vcc_lo
  3056. 0x7E10_021C, // v_mov_b32 v8, s28
  3057. 0x0210_1024, // v_cndmask_b32 v8, s36, v8, vcc_lo
  3058. 0x7E12_021D, // v_mov_b32 v9, s29
  3059. 0x0212_1225, // v_cndmask_b32 v9, s37, v9, vcc_lo
  3060. 0x7E14_021E, // v_mov_b32 v10, s30
  3061. 0x0214_1426, // v_cndmask_b32 v10, s38, v10, vcc_lo
  3062. 0x7E16_021F, // v_mov_b32 v11, s31
  3063. 0x0216_1627, // v_cndmask_b32 v11, s39, v11, vcc_lo
  3064. 0x887E_147E, // 0xb8: s_or_b32 exec_lo, exec_lo, s20
  3065. 0xBE97_037E, // s_mov_b32 s23, exec_lo
  3066. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  3067. 0x7E18_0504, // 0xc4: v_readfirstlane_b32 s12, v4
  3068. 0x7E1A_0505, // v_readfirstlane_b32 s13, v5
  3069. 0x7E1C_0506, // v_readfirstlane_b32 s14, v6
  3070. 0x7E1E_0507, // v_readfirstlane_b32 s15, v7
  3071. 0x7E20_0508, // v_readfirstlane_b32 s16, v8
  3072. 0x7E22_0509, // v_readfirstlane_b32 s17, v9
  3073. 0x7E24_050A, // v_readfirstlane_b32 s18, v10
  3074. 0x7E26_050B, // v_readfirstlane_b32 s19, v11
  3075. 0xD4E2_0015,
  3076. 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5]
  3077. 0xD4E2_0016,
  3078. 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7]
  3079. 0x8715_1615, // s_and_b32 s21, s21, s22
  3080. 0xD4E2_0016,
  3081. 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9]
  3082. 0x8715_1615, // s_and_b32 s21, s21, s22
  3083. 0xD4E2_0016,
  3084. 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11]
  3085. 0x8715_1615, // s_and_b32 s21, s21, s22
  3086. 0xBE95_3C15, // s_and_saveexec_b32 s21, s21
  3087. 0xBF80_0000, // s_nop 0
  3088. 0xF09C_0F08,
  3089. 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
  3090. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  3091. 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21
  3092. 0xBF89_FFE6, // s_cbranch_execnz -> 0xc4
  3093. 0xBEFE_0317, // s_mov_b32 exec_lo, s23
  3094. 0xE070_1000,
  3095. 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen
  3096. 0xBF81_0000, // s_endpgm
  3097. ];
  3098. /// A waterfall loop whose descriptor changes on each pass: v[4:11] holds
  3099. /// the first table entry on entry and the second after every pass, so
  3100. /// the first lane's dwords are phis of the loop header.
  3101. pub(crate) const WATERFALL_LOOPED_WAVE32: &[u32] = &[
  3102. 0xBE84_0300, // s_mov_b32 s4, s0
  3103. 0xBE85_0380, // s_mov_b32 s5, 0
  3104. 0xBE86_0301, // s_mov_b32 s6, s1
  3105. 0xBE87_0380, // s_mov_b32 s7, 0
  3106. 0xF40C_0602,
  3107. 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0
  3108. 0xF40C_0802,
  3109. 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20
  3110. 0xF408_0203,
  3111. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0
  3112. 0xF408_0A02,
  3113. 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40
  3114. 0x7E04_0D00, // v_cvt_f32_u32 v2, v0
  3115. 0x7E06_0302, // v_mov_b32 v3, v2
  3116. 0x3420_0082, // v_lshlrev_b32 v16, 2, v0
  3117. 0x7E08_0218, // v_mov_b32 v4, s24
  3118. 0x7E0A_0219, // v_mov_b32 v5, s25
  3119. 0x7E0C_021A, // v_mov_b32 v6, s26
  3120. 0x7E0E_021B, // v_mov_b32 v7, s27
  3121. 0x7E10_021C, // v_mov_b32 v8, s28
  3122. 0x7E12_021D, // v_mov_b32 v9, s29
  3123. 0x7E14_021E, // v_mov_b32 v10, s30
  3124. 0x7E16_021F, // v_mov_b32 v11, s31
  3125. 0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
  3126. 0xBE97_037E, // s_mov_b32 s23, exec_lo
  3127. 0x7E18_0504, // 0x64: v_readfirstlane_b32 s12, v4
  3128. 0x7E1A_0505, // v_readfirstlane_b32 s13, v5
  3129. 0x7E1C_0506, // v_readfirstlane_b32 s14, v6
  3130. 0x7E1E_0507, // v_readfirstlane_b32 s15, v7
  3131. 0x7E20_0508, // v_readfirstlane_b32 s16, v8
  3132. 0x7E22_0509, // v_readfirstlane_b32 s17, v9
  3133. 0x7E24_050A, // v_readfirstlane_b32 s18, v10
  3134. 0x7E26_050B, // v_readfirstlane_b32 s19, v11
  3135. 0xD4E2_0015,
  3136. 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5]
  3137. 0xD4E2_0016,
  3138. 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7]
  3139. 0x8715_1615, // s_and_b32 s21, s21, s22
  3140. 0xD4E2_0016,
  3141. 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9]
  3142. 0x8715_1615, // s_and_b32 s21, s21, s22
  3143. 0xD4E2_0016,
  3144. 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11]
  3145. 0x8715_1615, // s_and_b32 s21, s21, s22
  3146. 0xBE95_3C15, // s_and_saveexec_b32 s21, s21
  3147. 0xBF80_0000, // s_nop 0
  3148. 0xF09C_0F08,
  3149. 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
  3150. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  3151. 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21
  3152. 0x7E08_0220, // v_mov_b32 v4, s32
  3153. 0x7E0A_0221, // v_mov_b32 v5, s33
  3154. 0x7E0C_0222, // v_mov_b32 v6, s34
  3155. 0x7E0E_0223, // v_mov_b32 v7, s35
  3156. 0x7E10_0224, // v_mov_b32 v8, s36
  3157. 0x7E12_0225, // v_mov_b32 v9, s37
  3158. 0x7E14_0226, // v_mov_b32 v10, s38
  3159. 0x7E16_0227, // v_mov_b32 v11, s39
  3160. 0xBF89_FFDE, // s_cbranch_execnz -> 0x64
  3161. 0xBEFE_0317, // s_mov_b32 exec_lo, s23
  3162. 0xE070_1000,
  3163. 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen
  3164. 0xBF81_0000, // s_endpgm
  3165. ];
  3166. /// A waterfall loop over one of two buffer descriptors (four dwords)
  3167. /// loaded from the table at s0, chosen by nested if/else: lanes below 16
  3168. /// move the first into v[4:7], lanes from 16 to 23 the second, and the
  3169. /// others keep what v[4:7] held. Only lanes below 24 (the same mask)
  3170. /// run the loop, which loads dword `lane` of the chosen buffer, and
  3171. /// store it to the buffer at dword 16 of the table.
  3172. pub(crate) const WATERFALL_JOINED_BUFFER_WAVE32: &[u32] = &[
  3173. 0xBE84_0300, // s_mov_b32 s4, s0
  3174. 0xBE85_0380, // s_mov_b32 s5, 0
  3175. 0xF408_0602,
  3176. 0xFA00_0000, // s_load_dwordx4 s[24:27], s[4:5], 0x0
  3177. 0xF408_0802,
  3178. 0xFA00_0020, // s_load_dwordx4 s[32:35], s[4:5], 0x20
  3179. 0xF408_0A02,
  3180. 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40
  3181. 0x3420_0082, // v_lshlrev_b32 v16, 2, v0
  3182. 0xD4C4_001E,
  3183. 0x0002_0098, // v_cmp_gt_u32_e64 s30, 24, v0
  3184. 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0
  3185. 0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
  3186. 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo
  3187. 0x8914_147E, // s_xor_b32 s20, exec_lo, s20
  3188. 0xBF88_0004, // s_cbranch_execz -> 0x50
  3189. 0x7E08_0218, // 0x40: v_mov_b32 v4, s24
  3190. 0x7E0A_0219, // v_mov_b32 v5, s25
  3191. 0x7E0C_021A, // v_mov_b32 v6, s26
  3192. 0x7E0E_021B, // v_mov_b32 v7, s27
  3193. 0xBE94_3D14, // 0x50: s_or_saveexec_b32 s20, s20
  3194. 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20
  3195. 0xBF88_0007, // s_cbranch_execz -> 0x78
  3196. 0xBE9F_3C1E, // s_and_saveexec_b32 s31, s30
  3197. 0xBF88_0004, // s_cbranch_execz -> 0x74
  3198. 0x7E08_0220, // 0x64: v_mov_b32 v4, s32
  3199. 0x7E0A_0221, // v_mov_b32 v5, s33
  3200. 0x7E0C_0222, // v_mov_b32 v6, s34
  3201. 0x7E0E_0223, // v_mov_b32 v7, s35
  3202. 0x887E_1F7E, // 0x74: s_or_b32 exec_lo, exec_lo, s31
  3203. 0x887E_147E, // 0x78: s_or_b32 exec_lo, exec_lo, s20
  3204. 0xBE97_3C1E, // s_and_saveexec_b32 s23, s30
  3205. 0xBF88_0013, // s_cbranch_execz -> 0xd0
  3206. 0xBE9D_037E, // s_mov_b32 s29, exec_lo
  3207. 0x7E18_0504, // 0x88: v_readfirstlane_b32 s12, v4
  3208. 0x7E1A_0505, // v_readfirstlane_b32 s13, v5
  3209. 0x7E1C_0506, // v_readfirstlane_b32 s14, v6
  3210. 0x7E1E_0507, // v_readfirstlane_b32 s15, v7
  3211. 0xD4E2_0015,
  3212. 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5]
  3213. 0xD4E2_0016,
  3214. 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7]
  3215. 0x8715_1615, // s_and_b32 s21, s21, s22
  3216. 0xBE95_3C15, // s_and_saveexec_b32 s21, s21
  3217. 0xE030_1000,
  3218. 0x8003_0C10, // buffer_load_dword v12, v16, s[12:15], 0 offen
  3219. 0xBF8C_3F70, // s_waitcnt vmcnt(0)
  3220. 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21
  3221. 0xBF89_FFF1, // s_cbranch_execnz -> 0x88
  3222. 0xBEFE_031D, // s_mov_b32 exec_lo, s29
  3223. 0xE070_1000,
  3224. 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen
  3225. 0x887E_177E, // 0xd0: s_or_b32 exec_lo, exec_lo, s23
  3226. 0xBF81_0000, // s_endpgm
  3227. ];
  3228. fn waterfall(words: &[u32], wave64: bool) -> Result<Resources, ShaderError> {
  3229. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  3230. let p = crate::ir::build(&code, wave64, 256).unwrap();
  3231. let layout = [param(Table, 0, 1), param(Table, 1, 1)];
  3232. track(&p, &layout, HwStage::Cs, lanes(&p).as_ref())
  3233. }
  3234. #[test]
  3235. fn descriptors_read_from_the_first_lane_of_per_lane_loads_are_traced_to_them() {
  3236. for (words, wave64) in [
  3237. (WATERFALL_FETCHED_WAVE32, false),
  3238. (WATERFALL_FETCHED_WAVE64, true),
  3239. ] {
  3240. let r = waterfall(words, wave64).unwrap();
  3241. let image = r
  3242. .descriptors
  3243. .iter()
  3244. .find(|d| d.role == Role::Resource)
  3245. .unwrap();
  3246. let Source::Fetched { load, first: 0 } = image.source else {
  3247. panic!("{:?}", image.source)
  3248. };
  3249. // The first of the two loads: entry v0 * 32 of the table at s0.
  3250. let a = r.scalar.iter().find(|s| s.0 == load).unwrap().1;
  3251. assert_eq!((a.param, a.offset), (0, 0));
  3252. assert!(a.dynamic.is_some());
  3253. // The sampler is the same for every lane.
  3254. let sampler = r.descriptors.iter().find(|d| d.role == Role::Sampler);
  3255. assert!(matches!(
  3256. sampler.unwrap().source,
  3257. Source::Loaded { first: 0, .. }
  3258. ));
  3259. // Four 64-bit compares of the first lane's dwords with the lane's
  3260. // own; the eight reads become the lane's own dwords.
  3261. assert_eq!(r.waterfall.compares.len(), 4);
  3262. assert_eq!(r.waterfall.reads.len(), 8);
  3263. }
  3264. }
  3265. #[test]
  3266. fn descriptors_read_from_the_first_lane_of_a_per_lane_choice_are_traced_per_lane() {
  3267. let r = waterfall(WATERFALL_PICKED_WAVE32, false).unwrap();
  3268. let image = &r.descriptors[0];
  3269. let Source::Lanes { args, .. } = &image.source else {
  3270. panic!("{:?}", image.source)
  3271. };
  3272. // Lanes with their bit set take the first load (offset 0), the
  3273. // others the second (0x20).
  3274. let offsets: Vec<u32> = args
  3275. .iter()
  3276. .map(|a| match *a {
  3277. Source::Loaded { load, first: 0 } => {
  3278. r.scalar.iter().find(|s| s.0 == load).unwrap().1.offset
  3279. }
  3280. ref a => panic!("{a:?}"),
  3281. })
  3282. .collect();
  3283. assert_eq!(offsets, [0, 0x20]);
  3284. assert_eq!(r.waterfall.compares.len(), 4);
  3285. }
  3286. #[test]
  3287. fn a_first_lane_read_outside_a_loop_is_no_waterfall() {
  3288. // The waterfall without its back edge: the s_cbranch_execnz is an
  3289. // s_nop, so lanes the first one does not match never get a pass.
  3290. let mut words = WATERFALL_FETCHED_WAVE32.to_vec();
  3291. let back = words.iter().position(|&w| w == 0xBF89_FFE6).unwrap();
  3292. words[back] = 0xBF80_0000;
  3293. let err = waterfall(&words, false).unwrap_err();
  3294. assert!(
  3295. matches!(
  3296. err,
  3297. ShaderError::Unsupported {
  3298. what: "a descriptor read from the first lane outside a waterfall loop",
  3299. ..
  3300. }
  3301. ),
  3302. "{err:?}"
  3303. );
  3304. }
  3305. /// Why resource tracking refuses `words`.
  3306. fn refusal(words: &[u32], wave64: bool) -> &'static str {
  3307. match waterfall(words, wave64) {
  3308. Err(ShaderError::Unsupported { what, .. }) => what,
  3309. other => panic!("not refused: {other:?}"),
  3310. }
  3311. }
  3312. const NO_LOOP: &str = "a descriptor read from the first lane outside a waterfall loop";
  3313. const NOT_SELECTED: &str = "a waterfall loop whose compares do not select the access's lanes";
  3314. const BAD_RETRY: &str = "a waterfall loop whose retry does not keep the lanes still waiting";
  3315. const SPLIT: &str = "a waterfall loop nested in another or split over blocks";
  3316. /// The index of `word` in `words`.
  3317. fn word_at(words: &[u32], word: u32) -> usize {
  3318. words.iter().position(|&w| w == word).unwrap()
  3319. }
  3320. #[test]
  3321. fn a_first_lane_read_without_its_compare_is_no_waterfall() {
  3322. // The loop without the compare of dwords 0 and 1: nothing makes
  3323. // the first lane's dwords the lane's own there.
  3324. let mut words = WATERFALL_FETCHED_WAVE32.to_vec();
  3325. let cmp = word_at(&words, 0x0002_080C);
  3326. words[cmp - 1..=cmp].copy_from_slice(&[0xBF80_0000, 0xBF80_0000]);
  3327. assert_eq!(refusal(&words, false), NOT_SELECTED);
  3328. }
  3329. #[test]
  3330. fn a_compare_that_does_not_mask_the_access_is_no_waterfall() {
  3331. // The compares are all there, but their result never narrows EXEC:
  3332. // every lane samples with the first lane's descriptor (reported by
  3333. // ifBars on upstream PR #566).
  3334. let mut words = WATERFALL_JOINED_WAVE32.to_vec();
  3335. let save = word_at(&words, 0xBE95_3C15);
  3336. words[save] = 0xBE95_037E; // s_mov_b32 s21, exec_lo
  3337. assert_eq!(refusal(&words, false), NOT_SELECTED);
  3338. }
  3339. #[test]
  3340. fn an_access_under_a_further_mask_is_no_waterfall() {
  3341. // The access runs for the matching lanes that VCC also holds, yet
  3342. // the retry removes every matching lane.
  3343. let mut words = WATERFALL_JOINED_WAVE32.to_vec();
  3344. let nop = word_at(&words, 0xBE95_3C15) + 1;
  3345. assert_eq!(words[nop], 0xBF80_0000);
  3346. words[nop] = 0x877E_6A7E; // s_and_b32 exec_lo, exec_lo, vcc_lo
  3347. assert_eq!(refusal(&words, false), NOT_SELECTED);
  3348. }
  3349. #[test]
  3350. fn a_loop_that_drops_unmatched_lanes_is_no_waterfall() {
  3351. let mut words = WATERFALL_JOINED_WAVE32.to_vec();
  3352. let retry = word_at(&words, 0x897E_157E);
  3353. words[retry] = 0xBEFE_0380; // s_mov_b32 exec_lo, 0
  3354. assert_eq!(refusal(&words, false), BAD_RETRY);
  3355. }
  3356. #[test]
  3357. fn a_retry_that_keeps_other_lanes_than_those_waiting_is_no_waterfall() {
  3358. // The retry keeps the lanes of VCC that did not just sample, not
  3359. // the waiting ones: lanes 16 and up never sample on the console.
  3360. let mut words = WATERFALL_JOINED_WAVE32.to_vec();
  3361. let retry = word_at(&words, 0x897E_157E);
  3362. words[retry] = 0x8A7E_7E6A; // s_andn2_b32 exec_lo, vcc_lo, exec_lo
  3363. assert_eq!(refusal(&words, false), BAD_RETRY);
  3364. }
  3365. #[test]
  3366. fn a_wave64_retry_of_one_half_is_no_waterfall() {
  3367. // Only the low half of EXEC loses the lanes just served.
  3368. let mut words = WATERFALL_FETCHED_WAVE64.to_vec();
  3369. let retry = word_at(&words, 0x89FE_167E);
  3370. words[retry] = 0x897E_167E; // s_xor_b32 exec_lo, exec_lo, s22
  3371. assert_eq!(refusal(&words, true), BAD_RETRY);
  3372. }
  3373. #[test]
  3374. fn a_descriptor_used_after_exec_is_restored_is_no_waterfall() {
  3375. let mut words = WATERFALL_JOINED_WAVE32.to_vec();
  3376. let sample = word_at(&words, 0xF09C_0F08);
  3377. let restore = word_at(&words, 0xBEFE_0317);
  3378. let image = [words[sample], words[sample + 1]];
  3379. words[sample..sample + 2].fill(0xBF80_0000); // Keep the branch offsets.
  3380. words.splice(restore + 1..restore + 1, image);
  3381. assert_eq!(refusal(&words, false), NO_LOOP);
  3382. }
  3383. #[test]
  3384. fn a_wave64_access_with_exec_hi_overwritten_is_no_waterfall() {
  3385. let mut words = WATERFALL_FETCHED_WAVE64.to_vec();
  3386. let save = word_at(&words, 0xBE96_2416);
  3387. words[save + 1] = 0xBEFF_03C1; // s_mov_b32 exec_hi, -1
  3388. assert_eq!(refusal(&words, true), NOT_SELECTED);
  3389. }
  3390. /// The waterfall with `v_cmpx_eq` narrowing EXEC itself, and the retry
  3391. /// as `todo & !EXEC` (`folded`: in one `s_andn2_wrexec`), as LLVM's
  3392. /// AMDGPU backend writes it for GFX10 and later.
  3393. pub(crate) fn cmpx_waterfall(wave64: bool, folded: bool) -> Vec<u32> {
  3394. let (base, todo, restore): (&[u32], u32, u32) = if wave64 {
  3395. (WATERFALL_FETCHED_WAVE64, 0xBE94_047E, 0xBEFE_0414)
  3396. } else {
  3397. (WATERFALL_JOINED_WAVE32, 0xBE97_037E, 0xBEFE_0317)
  3398. };
  3399. let reads = word_at(base, 0x7E18_0504);
  3400. let sample = word_at(base, 0xF09C_0F08);
  3401. let mut w = base[..=word_at(base, todo)].to_vec();
  3402. // s_mov_b32 s21, exec_lo / s_mov_b64 s[22:23], exec
  3403. w.push(if wave64 { 0xBE96_047E } else { 0xBE95_037E });
  3404. w.extend(&base[reads..reads + 8]); // v_readfirstlane_b32 s12..s19
  3405. w.extend([
  3406. 0x7DE4_080C, // v_cmpx_eq_u64 s[12:13], v[4:5]
  3407. 0x7DE4_0C0E, // v_cmpx_eq_u64 s[14:15], v[6:7]
  3408. 0x7DE4_1010, // v_cmpx_eq_u64 s[16:17], v[8:9]
  3409. 0x7DE4_1412, // v_cmpx_eq_u64 s[18:19], v[10:11]
  3410. ]);
  3411. w.extend(&base[sample..sample + 2]); // image_sample_lz
  3412. match (wave64, folded) {
  3413. // s_andn2_wrexec_b32 s21, s21; s_cbranch_execnz
  3414. (false, true) => w.extend([0xBE95_4715, 0xBF89_FFF0]),
  3415. // s_andn2_b32 s21, s21, exec_lo; s_mov_b32 exec_lo, s21
  3416. (false, false) => w.extend([0x8A15_7E15, 0xBEFE_0315, 0xBF89_FFEF]),
  3417. // s_andn2_wrexec_b64 s[22:23], s[22:23]
  3418. (true, true) => w.extend([0xBE96_3A16, 0xBF89_FFF0]),
  3419. // s_andn2_b64 s[22:23], s[22:23], exec; s_mov_b64 exec, s[22:23]
  3420. (true, false) => w.extend([0x8A96_7E16, 0xBEFE_0416, 0xBF89_FFEF]),
  3421. }
  3422. w.extend(&base[word_at(base, restore)..]);
  3423. w
  3424. }
  3425. #[test]
  3426. fn a_waterfall_narrowed_by_v_cmpx_is_one() {
  3427. for wave64 in [false, true] {
  3428. for folded in [false, true] {
  3429. let r = waterfall(&cmpx_waterfall(wave64, folded), wave64)
  3430. .unwrap_or_else(|e| panic!("wave64 {wave64} folded {folded}: {e:?}"));
  3431. assert_eq!(r.waterfall.compares.len(), 4, "{wave64} {folded}");
  3432. assert_eq!(r.waterfall.reads.len(), 8, "{wave64} {folded}");
  3433. }
  3434. }
  3435. }
  3436. #[test]
  3437. fn a_v_cmpx_waterfall_whose_retry_drops_lanes_is_none() {
  3438. let mut words = cmpx_waterfall(false, false);
  3439. let retry = word_at(&words, 0x8A15_7E15);
  3440. words[retry] = 0x8A15_7E6A; // s_andn2_b32 s21, vcc_lo, exec_lo
  3441. assert_eq!(refusal(&words, false), BAD_RETRY);
  3442. }
  3443. #[test]
  3444. fn a_waterfall_nested_in_another_is_refused_by_name() {
  3445. // An image whose resource and sampler are both per lane, with one
  3446. // loop per operand, the one for the sampler inside the one for the
  3447. // resource (what the SelectionDAG legalisation in LLVM would give).
  3448. // The console gives each lane its own pair. Refused for now: the
  3449. // access of the inner loop reads the first-lane dwords of the outer
  3450. // loop, which another block holds.
  3451. let words = [
  3452. 0xBE84_0300, // s_mov_b32 s4, s0
  3453. 0xBE85_0380, // s_mov_b32 s5, 0
  3454. 0xBE86_0301, // s_mov_b32 s6, s1
  3455. 0xBE87_0380, // s_mov_b32 s7, 0
  3456. 0xF408_0A02,
  3457. 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40
  3458. 0x7E04_0D00, // v_cvt_f32_u32 v2, v0
  3459. 0x7E06_0302, // v_mov_b32 v3, v2
  3460. 0x3420_0082, // v_lshlrev_b32 v16, 2, v0
  3461. 0x3602_0081, // v_and_b32 v1, 1, v0
  3462. 0x3402_0285, // v_lshlrev_b32 v1, 5, v1
  3463. 0x3622_0080, // v_and_b32 v17, 0, v0
  3464. 0x3422_2284, // v_lshlrev_b32 v17, 4, v17
  3465. 0xDC38_8000,
  3466. 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5]
  3467. 0xDC38_8010,
  3468. 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16
  3469. 0xDC38_8000,
  3470. 0x1406_0011, // global_load_dwordx4 v[20:23], v17, s[6:7]
  3471. 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0)
  3472. 0xBE94_037E, // s_mov_b32 s20, exec_lo
  3473. // L1, the loop over the resource:
  3474. 0x7E18_0504, // v_readfirstlane_b32 s12, v4
  3475. 0x7E1A_0505,
  3476. 0x7E1C_0506,
  3477. 0x7E1E_0507,
  3478. 0x7E20_0508,
  3479. 0x7E22_0509,
  3480. 0x7E24_050A,
  3481. 0x7E26_050B, // v_readfirstlane_b32 s19, v11
  3482. 0xD4E2_0015,
  3483. 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5]
  3484. 0xD4E2_0016,
  3485. 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7]
  3486. 0x8715_1615, // s_and_b32 s21, s21, s22
  3487. 0xD4E2_0016,
  3488. 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9]
  3489. 0x8715_1615, // s_and_b32 s21, s21, s22
  3490. 0xD4E2_0016,
  3491. 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11]
  3492. 0x8715_1615, // s_and_b32 s21, s21, s22
  3493. 0xBE95_3C15, // s_and_saveexec_b32 s21, s21
  3494. 0xBE9A_037E, // s_mov_b32 s26, exec_lo
  3495. // L2, the loop over the sampler:
  3496. 0x7E10_0514, // v_readfirstlane_b32 s8, v20
  3497. 0x7E12_0515, // v_readfirstlane_b32 s9, v21
  3498. 0x7E14_0516, // v_readfirstlane_b32 s10, v22
  3499. 0x7E16_0517, // v_readfirstlane_b32 s11, v23
  3500. 0xD4E2_0018,
  3501. 0x0002_2808, // v_cmp_eq_u64_e64 s24, s[8:9], v[20:21]
  3502. 0xD4E2_0019,
  3503. 0x0002_2C0A, // v_cmp_eq_u64_e64 s25, s[10:11], v[22:23]
  3504. 0x8718_1918, // s_and_b32 s24, s24, s25
  3505. 0xBE98_3C18, // s_and_saveexec_b32 s24, s24
  3506. 0xF09C_0F08,
  3507. 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11]
  3508. 0x897E_187E, // s_xor_b32 exec_lo, exec_lo, s24
  3509. 0xBF89_FFF2, // s_cbranch_execnz L2
  3510. 0xBEFE_031A, // s_mov_b32 exec_lo, s26
  3511. 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21
  3512. 0xBF89_FFDA, // s_cbranch_execnz L1
  3513. 0xBEFE_0314, // s_mov_b32 exec_lo, s20
  3514. 0xE070_1000,
  3515. 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen
  3516. 0xBF81_0000, // s_endpgm
  3517. ];
  3518. assert_eq!(refusal(&words, false), SPLIT);
  3519. }
  3520. #[test]
  3521. fn descriptors_read_from_the_first_lane_of_lds_fail_naming_it() {
  3522. // The waterfall over descriptors each lane read from LDS:
  3523. // ds_read_b128 v[4:7], v1 and ds_read_b128 v[8:11], v1 offset:16
  3524. // in place of the global loads.
  3525. let mut words = WATERFALL_FETCHED_WAVE32.to_vec();
  3526. words[5..9].copy_from_slice(&[0xDBFC_0000, 0x0400_0001, 0xDBFC_0010, 0x0800_0001]);
  3527. let err = waterfall(&words, false).unwrap_err();
  3528. assert!(
  3529. matches!(
  3530. err,
  3531. ShaderError::Unsupported {
  3532. what: "a descriptor read from the first lane of an LDS read",
  3533. ..
  3534. }
  3535. ),
  3536. "{err:?}"
  3537. );
  3538. }
  3539. /// The block of `p` at byte `offset`.
  3540. fn block_at(words: &[u32], offset: usize) -> usize {
  3541. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  3542. let p = crate::ir::build(&code, false, 256).unwrap();
  3543. p.blocks.iter().position(|b| b.offset == offset).unwrap()
  3544. }
  3545. /// The table offset of what the scalar load of `s` reads.
  3546. fn table_offset(r: &Resources, s: &Source) -> u32 {
  3547. match *s {
  3548. Source::Loaded { load, first: 0 } => {
  3549. r.scalar.iter().find(|x| x.0 == load).unwrap().1.offset
  3550. }
  3551. ref s => panic!("{s:?}"),
  3552. }
  3553. }
  3554. #[test]
  3555. fn descriptors_read_from_the_first_lane_of_an_if_else_join_are_traced_per_path() {
  3556. let words = WATERFALL_JOINED_WAVE32;
  3557. let r = waterfall(words, false).unwrap();
  3558. let image = r
  3559. .descriptors
  3560. .iter()
  3561. .find(|d| matches!(d.source, Source::LanePhi { .. }))
  3562. .unwrap();
  3563. // The join after the else arm: lanes that ran it (lanes from 16 on)
  3564. // take the second entry (0x20); the others come through the flow
  3565. // block, whose join gives lanes that ran the then arm the first one
  3566. // (0). No lane that skipped the then arm comes that way, so the
  3567. // dwords they held before (the inputs) are not traced.
  3568. let Source::LanePhi { block, args } = &image.source else {
  3569. unreachable!()
  3570. };
  3571. assert_eq!(*block, block_at(words, 0x9c));
  3572. let [Some(flow), Some(other)] = &args[..] else {
  3573. panic!("{args:?}")
  3574. };
  3575. assert_eq!(table_offset(&r, other), 0x20);
  3576. let Source::LanePhi { block, args } = flow else {
  3577. panic!("{flow:?}")
  3578. };
  3579. assert_eq!(*block, block_at(words, 0x70));
  3580. let [None, Some(then)] = &args[..] else {
  3581. panic!("{args:?}")
  3582. };
  3583. assert_eq!(table_offset(&r, then), 0);
  3584. // The loop's compares are of the joined dwords; still recognised.
  3585. assert_eq!(r.waterfall.compares.len(), 4);
  3586. assert_eq!(r.waterfall.reads.len(), 8);
  3587. // Without the lanes' paths the join is refused.
  3588. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  3589. let p = crate::ir::build(&code, false, 256).unwrap();
  3590. let layout = [param(Table, 0, 1), param(Table, 1, 1)];
  3591. let err = track(&p, &layout, HwStage::Cs, None).unwrap_err();
  3592. assert!(
  3593. matches!(
  3594. err,
  3595. ShaderError::Unsupported {
  3596. what: "a descriptor read from the first lane of a phi, without the lanes' paths",
  3597. ..
  3598. }
  3599. ),
  3600. "{err:?}"
  3601. );
  3602. }
  3603. #[test]
  3604. fn descriptors_joined_from_a_per_lane_load_and_a_per_lane_choice_are_traced_per_path() {
  3605. let words = WATERFALL_JOINED_MIXED_WAVE32;
  3606. let r = waterfall(words, false).unwrap();
  3607. let image = r
  3608. .descriptors
  3609. .iter()
  3610. .find(|d| matches!(d.source, Source::LanePhi { .. }))
  3611. .unwrap();
  3612. let Source::LanePhi { block, args } = &image.source else {
  3613. unreachable!()
  3614. };
  3615. assert_eq!(*block, block_at(words, 0xb8));
  3616. let [
  3617. Some(Source::LanePhi { args: flow, .. }),
  3618. Some(Source::Lanes { args: picked, .. }),
  3619. ] = &args[..]
  3620. else {
  3621. panic!("{args:?}")
  3622. };
  3623. // The then arm loads each lane's entry from the table at s0.
  3624. let [None, Some(Source::Fetched { load, first: 0 })] = flow[..] else {
  3625. panic!("{flow:?}")
  3626. };
  3627. let a = r.scalar.iter().find(|s| s.0 == load).unwrap().1;
  3628. assert_eq!((a.param, a.offset), (0, 0));
  3629. assert!(a.dynamic.is_some());
  3630. // The else arm picks the first entry where vcc is set.
  3631. let offsets: Vec<u32> = picked.iter().map(|s| table_offset(&r, s)).collect();
  3632. assert_eq!(offsets, [0, 0x20]);
  3633. assert_eq!(r.waterfall.compares.len(), 4);
  3634. }
  3635. #[test]
  3636. fn a_descriptor_read_from_the_first_lane_of_a_loop_phi_fails_naming_it() {
  3637. let err = waterfall(WATERFALL_LOOPED_WAVE32, false).unwrap_err();
  3638. assert!(
  3639. matches!(
  3640. err,
  3641. ShaderError::Unsupported {
  3642. what: "a descriptor read from the first lane of a phi at a loop header",
  3643. ..
  3644. }
  3645. ),
  3646. "{err:?}"
  3647. );
  3648. }
  3649. #[test]
  3650. fn a_per_lane_descriptor_some_lanes_do_not_write_fails() {
  3651. // The else arm of WATERFALL_JOINED_WAVE32 not skipped (its
  3652. // s_cbranch_execz an s_nop): it runs with EXEC clear in the lanes
  3653. // of the then arm, which keep the first entry; the second is not
  3654. // every lane's.
  3655. let mut words = WATERFALL_JOINED_WAVE32.to_vec();
  3656. let skip = words.iter().rposition(|&w| w == 0xBF88_0008).unwrap();
  3657. words[skip] = 0xBF80_0000;
  3658. let err = waterfall(&words, false).unwrap_err();
  3659. assert!(
  3660. matches!(
  3661. err,
  3662. ShaderError::Unsupported {
  3663. what: "a per-lane descriptor written where some lanes may keep the old one",
  3664. ..
  3665. }
  3666. ),
  3667. "{err:?}"
  3668. );
  3669. }
  3670. #[test]
  3671. fn a_buffer_descriptor_joined_per_lane_is_traced_on_the_paths_of_lanes_that_load() {
  3672. let words = WATERFALL_JOINED_BUFFER_WAVE32;
  3673. let r = waterfall(words, false).unwrap();
  3674. let buffer = r
  3675. .descriptors
  3676. .iter()
  3677. .find(|d| matches!(d.source, Source::LanePhi { .. }))
  3678. .unwrap();
  3679. // The outer join: lanes from the else arm's inner join, or (below
  3680. // 16) through the flow block.
  3681. let Source::LanePhi { block, args } = &buffer.source else {
  3682. unreachable!()
  3683. };
  3684. assert_eq!(*block, block_at(words, 0x78));
  3685. let [
  3686. Some(Source::LanePhi { args: flow, .. }),
  3687. Some(Source::LanePhi {
  3688. block: inner,
  3689. args: nested,
  3690. }),
  3691. ] = &args[..]
  3692. else {
  3693. panic!("{args:?}")
  3694. };
  3695. let [None, Some(then)] = &flow[..] else {
  3696. panic!("{flow:?}")
  3697. };
  3698. assert_eq!(table_offset(&r, then), 0);
  3699. // Lanes from 24 on skip the inner arm and keep the inputs, but do
  3700. // not load: that edge is not traced.
  3701. assert_eq!(*inner, block_at(words, 0x74));
  3702. let [None, Some(other)] = &nested[..] else {
  3703. panic!("{nested:?}")
  3704. };
  3705. assert_eq!(table_offset(&r, other), 0x20);
  3706. assert_eq!(r.waterfall.compares.len(), 2);
  3707. assert_eq!(r.waterfall.reads.len(), 4);
  3708. }
  3709. }