lower.rs 533 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594
  1. //! IR to DXIL, one machine instruction at a time (decision 0003).
  2. //!
  3. //! Every register dword is an `i32` (SCC an `i1`); float operations bitcast
  4. //! their operands. Lane masks exist only as the per-lane booleans of
  5. //! structurisation; branches and guards are built from them. A value the
  6. //! emitter cannot express is `Missing` with a reason, and only fails the
  7. //! program when something with an effect (an export, a branch) needs it.
  8. use std::collections::{BTreeMap, HashMap, HashSet};
  9. use super::UserData;
  10. use super::bitcode::{Attr, Bin, Cast, Rmw, Tag, Term, V, pred};
  11. use super::container::SigElement;
  12. use super::shader::{Shader, flags};
  13. use crate::ShaderError;
  14. use crate::gfx10::{Dpp, Fields, NULL, Operand};
  15. use crate::io::{Barycentric, Export, Input, Interp, Io, Target};
  16. use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value};
  17. use crate::native::{HwStage, NativeProgram, ResourceType, RootType, StageIo, Usage, UsedResource};
  18. use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source};
  19. use crate::structure::{Atom, Bool, LaneExit, Structured};
  20. /// The ray-tracing node test (`image_bvh_intersect_ray`), a child module so
  21. /// it shares the emitter's state.
  22. #[path = "intersect.rs"]
  23. pub(super) mod intersect;
  24. type Why = &'static str;
  25. /// How an interpolation evaluates an input channel.
  26. #[derive(Debug, Clone, Copy)]
  27. enum Eval {
  28. /// Loaded with this DXIL interpolation mode (1: constant, P0).
  29. Mode(u8),
  30. /// From the vertex values of a constant element: P0 when `p0`, plus
  31. /// i (P1 - P0), plus j (P2 - P0), weights as floats.
  32. Weights {
  33. p0: bool,
  34. i: Option<V>,
  35. j: Option<V>,
  36. },
  37. }
  38. #[derive(Debug, Clone, Copy)]
  39. enum Val {
  40. I32(V),
  41. Bit(V),
  42. Missing(Why),
  43. }
  44. pub(crate) struct Lowered {
  45. pub dxil: Vec<u8>,
  46. /// Bit n: immediate sampler n is a comparison sampler.
  47. pub cmp_samplers: u64,
  48. pub root_cbvs: Vec<u8>,
  49. pub root_srvs: Vec<u8>,
  50. pub root_uavs: Vec<u8>,
  51. pub user_data: Vec<UserData>,
  52. pub samplers: Vec<[u32; 4]>,
  53. /// The wave size the shader requires of the host, if any.
  54. pub wave_size: Option<u32>,
  55. /// Heap handles made with a non-uniform index.
  56. #[cfg(test)]
  57. pub nonuniform_handles: u32,
  58. /// Whether the program uses wave operations.
  59. #[cfg(test)]
  60. pub wave_ops: bool,
  61. }
  62. pub(crate) struct Parts<'a> {
  63. pub native: &'a NativeProgram,
  64. pub p: &'a Program,
  65. pub st: &'a Structured,
  66. pub io: &'a Io,
  67. pub res: &'a Resources,
  68. pub inputs: Vec<SigElement>,
  69. pub outputs: Vec<SigElement>,
  70. pub prims: Vec<SigElement>,
  71. /// Mesh: what the group id arrives multiplied by.
  72. pub mesh_stride: u32,
  73. }
  74. enum Stop {
  75. /// A phi whose incoming value has no DXIL form was read: redo with it missing.
  76. Retry(Value, Why),
  77. Fail(ShaderError),
  78. }
  79. pub(crate) fn lower(parts: &Parts) -> Result<Lowered, ShaderError> {
  80. let mut bad = HashMap::new();
  81. loop {
  82. match Lower::new(parts, &bad).run() {
  83. Ok(l) => return Ok(l),
  84. Err(Stop::Retry(v, why)) => {
  85. if bad.insert(v, why).is_some() {
  86. return Err(ShaderError::Unsupported {
  87. offset: 0,
  88. what: "a phi that does not settle",
  89. });
  90. }
  91. }
  92. Err(Stop::Fail(e)) => return Err(e),
  93. }
  94. }
  95. }
  96. const TWO_PI: f32 = std::f32::consts::TAU;
  97. /// `s_sendmsg` id of a mesh or NGG stage's output allocation request.
  98. const GS_ALLOC_REQ: u16 = 9;
  99. /// `s_sendmsg` id that ends a pixel wave's ordered section.
  100. const ORDERED_PS_DONE: u16 = 7;
  101. /// Hardware register (of `s_setreg_b32`) a pixel wave names its packer in
  102. /// before it waits for the waves it overlaps.
  103. const POPS_PACKER: u16 = 25;
  104. /// The operand `src_pops_exiting_wave_id`.
  105. const POPS_EXITING: u8 = 239;
  106. /// The instructions inside a pixel program's ordered section
  107. /// (primitive-ordered pixel shading, which the console compiler makes of
  108. /// rasterizer ordered views): from the write of `POPS_PACKER`, along every
  109. /// path, to the message that ends the section or the program's end. The
  110. /// console waits there until the waves holding earlier primitives' samples
  111. /// of the same pixels have left their sections; a host's rasterizer ordered
  112. /// views wait by themselves, at their first access. Empty for a program
  113. /// without such a section.
  114. fn ordered_section(p: &Program) -> HashSet<Site> {
  115. let starts = |i: &Inst| {
  116. i.name() == "s_setreg_b32"
  117. && matches!(i.fields, Fields::Sop { imm: Some(imm), .. } if imm & 0x3F == POPS_PACKER)
  118. };
  119. let ends = |i: &Inst| {
  120. i.name() == "s_sendmsg"
  121. && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == ORDERED_PS_DONE)
  122. };
  123. let mut section = HashSet::new();
  124. let mut entered = vec![false; p.blocks.len()];
  125. let mut work: Vec<Site> = p
  126. .blocks
  127. .iter()
  128. .enumerate()
  129. .flat_map(|(b, block)| {
  130. (0..block.insts.len())
  131. .filter(|&i| starts(&block.insts[i]))
  132. .map(move |i| (b, i))
  133. })
  134. .collect();
  135. while let Some((b, from)) = work.pop() {
  136. let block = &p.blocks[b];
  137. let mut done = false;
  138. for i in from..block.insts.len() {
  139. if ends(&block.insts[i]) {
  140. done = true;
  141. break;
  142. }
  143. section.insert((b, i));
  144. }
  145. if done {
  146. continue;
  147. }
  148. for (t, next) in p.blocks.iter().enumerate() {
  149. if next.preds.contains(&b) && !std::mem::replace(&mut entered[t], true) {
  150. work.push((t, 0));
  151. }
  152. }
  153. }
  154. section
  155. }
  156. /// The f16 bits of inline float constant `c` (240..=248: 0.5, -0.5, 1.0,
  157. /// -1.0, 2.0, -2.0, 4.0, -4.0, 1/(2 pi)).
  158. fn inline_f16(c: u8) -> u32 {
  159. [
  160. 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118,
  161. ][usize::from(c - 240)]
  162. }
  163. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  164. enum Numeric {
  165. Unorm,
  166. Snorm,
  167. Uscaled,
  168. Sscaled,
  169. Uint,
  170. Sint,
  171. Float,
  172. }
  173. /// A GFX10 buffer format (the unified format of typed buffer loads): the
  174. /// channel widths from the lowest bits up, and how the channels convert.
  175. /// Formats are numbered in families (`8`, `16`, `8_8`, ...: AMD names
  176. /// list channels from the highest bits), each with its numeric formats in
  177. /// the order unorm, snorm, uscaled, sscaled, uint, sint, float.
  178. fn buffer_format(format: u8) -> Option<(&'static [u32], Numeric)> {
  179. use Numeric::*;
  180. const NORM: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint];
  181. const ALL: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint, Float];
  182. const WIDE: &[Numeric] = &[Uint, Sint, Float];
  183. // Numbers and order from LLVM's `UfmtGFX10` (`SIDefines.h`); the GFX10
  184. // buffer formats have no 5_9_9_9. Channel order from Mesa
  185. // (`ac_formats.c`): R11G11B10_FLOAT is 10_11_11, and 10_10_10_2 has
  186. // its 2-bit channel in the lowest bits.
  187. const FAMILIES: [(&[u32], &[Numeric]); 14] = [
  188. (&[8], NORM),
  189. (&[16], ALL),
  190. (&[8, 8], NORM),
  191. (&[32], WIDE),
  192. (&[16, 16], ALL),
  193. (&[11, 11, 10], ALL), // 10_11_11
  194. (&[10, 11, 11], ALL), // 11_11_10
  195. (&[2, 10, 10, 10], NORM), // 10_10_10_2
  196. (&[10, 10, 10, 2], NORM), // 2_10_10_10
  197. (&[8, 8, 8, 8], NORM),
  198. (&[32, 32], WIDE),
  199. (&[16, 16, 16, 16], ALL),
  200. (&[32, 32, 32], WIDE),
  201. (&[32, 32, 32, 32], WIDE),
  202. ];
  203. let mut n = usize::from(format.checked_sub(1)?);
  204. for (bits, numerics) in FAMILIES {
  205. if n < numerics.len() {
  206. return Some((bits, numerics[n]));
  207. }
  208. n -= numerics.len();
  209. }
  210. None
  211. }
  212. /// How far a float channel of `width` bits (16, or the unsigned 11- and
  213. /// 10-bit floats of the packed formats) shifts up to be a half:
  214. /// the small floats are a half's exponent (5 bits, biased 15) and the top
  215. /// of its mantissa, without the sign, so `legacyF16ToF32` widens them
  216. /// exactly, denormals, infinities and NaNs included.
  217. fn half_shift(width: u32) -> u32 {
  218. debug_assert!(matches!(width, 10 | 11 | 16), "{width}-bit float");
  219. if width == 16 { 0 } else { 15 - width }
  220. }
  221. struct Lower<'a> {
  222. s: Shader,
  223. x: &'a Parts<'a>,
  224. bad: &'a HashMap<Value, Why>,
  225. lane_fail: HashMap<Value, Why>,
  226. vals: HashMap<Value, Val>,
  227. floats: HashMap<Value, V>,
  228. /// DXIL block per IR block (unreachable: none).
  229. block: Vec<Option<usize>>,
  230. cur: usize,
  231. bools: HashMap<(usize, Bool), V>,
  232. lane_bits: HashMap<Value, V>,
  233. /// IR phi location by value.
  234. phi_at: HashMap<Value, (usize, usize)>,
  235. /// Descriptor dwords with no host value (addresses, formats, all of a constant
  236. /// buffer's): no program reads them as numbers ([`Self::dead`]).
  237. stale: HashSet<Value>,
  238. /// See [`ordered_section`] (pixel programs).
  239. ordered: HashSet<Site>,
  240. /// Raw UAV buffers (see [`Lower::entry`]) the program loads from past its
  241. /// wave's cache (GLC): other groups write what it waits for. On the host
  242. /// they are globally coherent; a load in a loop that only waits would
  243. /// be made once otherwise.
  244. coherent: HashSet<(usize, u32)>,
  245. mask_phis: HashMap<Value, V>,
  246. pending_masks: Vec<(V, usize, usize)>,
  247. data_phis: Vec<(V, usize, usize)>,
  248. read_phis: HashSet<Value>,
  249. params: HashMap<Value, (usize, u32)>,
  250. user_data: Option<V>,
  251. user_reads: BTreeMap<u32, UserData>,
  252. samplers: Vec<[u32; 4]>,
  253. descriptors: HashMap<(Site, bool), &'a Source>,
  254. scalar: HashMap<Site, Address>,
  255. exports: HashMap<Site, &'a Export>,
  256. interps: HashMap<Site, &'a Interp>,
  257. handles: HashMap<(usize, Site, u8, bool, (u32, u32)), V>,
  258. /// Element strides read from the host's table by heap slot
  259. /// ([`super::shader::SLOT_STRIDES`]), by block and descriptor load.
  260. strides: HashMap<(usize, Site, u8), V>,
  261. /// Blocks splitting the edge from one IR block to another.
  262. edges: HashMap<(usize, usize), usize>,
  263. /// Per IR block: a `done` export is behind every lane entering it.
  264. exported: Vec<bool>,
  265. /// Reverse-postorder index per IR block.
  266. rpo: Vec<usize>,
  267. /// DXIL block each IR block ends in (guarded stores split blocks).
  268. tail: Vec<Option<usize>>,
  269. /// The program writes UAVs: barriers fence them too.
  270. writes_uavs: bool,
  271. /// src0 of the current instruction as DPP fetched it.
  272. src0: Option<V>,
  273. /// Compute code that reads other lanes: thread ids follow the host
  274. /// lanes, so lane n is console lane n.
  275. console_lanes: bool,
  276. /// Mesh: the thread index in the group (made in the entry block).
  277. flat: Option<V>,
  278. /// Mesh: IR blocks whose `s_barrier` is left out.
  279. no_barrier: HashSet<usize>,
  280. /// IR blocks whose `s_barrier` not every lane is sure to reach (a lane
  281. /// branch lies between the entry and the block, or the program has a
  282. /// loop a lane can be cut out of): the barrier there keeps its fences
  283. /// and does not wait for the group ([`super::group_sync`]).
  284. fence_only: HashSet<usize>,
  285. /// A group barrier before every LDS access (a console wave run as two host waves).
  286. split_lds: bool,
  287. /// With `split_lds`, LDS accesses in lane branches: per IR block whether every lane runs
  288. /// it, and whether the host waves meet at its start and before its exit ([`lds_meetings`]).
  289. lds_meet: Option<(Vec<bool>, Vec<(bool, bool)>)>,
  290. /// A console wave64 program run as two host waves of 32 that exchange through LDS: the first
  291. /// of two exchange dwords, whether the group has no upper half (32 threads or fewer), and per
  292. /// IR block whether every lane runs it (exchanges need both halves there).
  293. exchange: Option<(u32, bool, Vec<bool>)>,
  294. /// With `exchange`: nothing is exchanged, each host wave acts as a wave
  295. /// of its own ([`with_local_waves`]).
  296. local: bool,
  297. /// The instruction being lowered may read a lane mask as a number under
  298. /// `local` (a bit count, a first set bit, `v_mbcnt`).
  299. local_ok: bool,
  300. /// With `local`: every mask read and lane read is taken per host wave
  301. /// ([`with_local_waves_any`]).
  302. local_any: bool,
  303. /// With `exchange`: VGPR values every lane holds alike ([`lane_uniform`]); a first-lane
  304. /// read of one needs nothing from the other host wave.
  305. uniform: HashSet<Value>,
  306. /// With `exchange`: the wave ORs that only steer a loop over each lane's own bits, which
  307. /// a host wave takes over its own lanes wherever they stand ([`super::own_bits`]).
  308. own_bits: super::own_bits::OwnBits,
  309. /// The console lane (0..63) of this thread, made in the entry block.
  310. clane: Option<V>,
  311. /// The first exchange dword of this thread's console wave ([`Self::exchange_pair`]).
  312. pair: Option<V>,
  313. /// A console wave64 program in host waves of 32: the LDS dword counting the console threads
  314. /// handed to host waves (`wave_base`), and the base made in the entry block.
  315. halves: Option<u32>,
  316. wave_base: Option<V>,
  317. /// Vertex and mesh outputs holding 16-bit values: row, whether two per
  318. /// dword, and the row packed after it.
  319. half_outputs: HashMap<u8, (bool, Option<u8>)>,
  320. /// How lane masks become data.
  321. mask_data: MaskData,
  322. /// The instruction being lowered may read lane masks as data.
  323. mask_ok: bool,
  324. /// Ballots of masks read as data, by low dword: (low, high).
  325. ballots: HashMap<Value, (V, V)>,
  326. /// Masks whose ballot is being built: a mask whose lane bit needs its
  327. /// own value as a number (an opaque mask keyed by a dword it shares
  328. /// with another) would otherwise recurse until the stack overflows.
  329. balloting: HashSet<Value>,
  330. /// Block writing each value.
  331. def_block: HashMap<Value, usize>,
  332. /// IR block being lowered.
  333. cur_ir: usize,
  334. /// Whole-wave sections by block and start index.
  335. sections: HashMap<usize, HashMap<usize, super::wave::Section>>,
  336. /// Values written in a section that code outside it reads.
  337. section_out: HashSet<Value>,
  338. /// The program's constant table (the code from the first byte read
  339. /// through `s_getpc_b64` on): global, first byte, dwords.
  340. code_table: Option<(V, u32, u32)>,
  341. /// Loop headers' iteration counters (see [`LOOP_LIMIT`]): the phi by
  342. /// IR block, and its incoming (value, DXIL block) pairs.
  343. counters: HashMap<usize, (V, Vec<(V, usize)>)>,
  344. /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from.
  345. abort: Option<usize>,
  346. }
  347. /// Iterations after which a loop is left (per entry into it), unless
  348. /// [`super::loop_limit`] says otherwise. The console runs a loop as long as
  349. /// its data says; data the host has not mirrored yet (a null view reads
  350. /// zeros) can make that four billion iterations, which hangs the host GPU
  351. /// until the driver resets it. A lane that reaches the limit leaves the
  352. /// program as killed (a pixel discards).
  353. // shortcut: a genuine loop of more iterations than this is cut short too.
  354. pub(super) const LOOP_LIMIT: u32 = 1 << 20;
  355. /// Lane masks read as numbers (`s_bcnt1`, `s_ff1`, `v_mbcnt`, scalar
  356. /// compares, bit tests) are ballots of the lanes' booleans, taken where the
  357. /// mask is written: structurisation's `active` masks hold only lanes that
  358. /// reach that block, so the ballot misses none.
  359. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  360. enum MaskData {
  361. /// Compute: host lane n is console lane n (the program declares the
  362. /// console's wave size), so ballots are the console's masks bit for bit
  363. /// and any use is exact.
  364. Console,
  365. /// Pixel and vertex programs: ballots over the host's wave, whatever its
  366. /// size. Only uses that mean the same on any wave are allowed: counts,
  367. /// the first lane, the count below a lane, equality (the HLSL wave
  368. /// operations the console compiler expands). Lane numbers stay host
  369. /// lanes throughout (`v_mbcnt`, `v_readlane` at a computed lane).
  370. Host,
  371. /// Mesh programs: their lanes and waves (LDS per console wave) are the
  372. /// console's but no host wave size can be declared.
  373. None,
  374. }
  375. /// What a value holding a lane mask read as a number stops with.
  376. pub(super) const LANE_MASK: Why = "a lane mask read as data";
  377. /// A mask with lanes outside EXEC where it is written, read as a number where the lanes that
  378. /// run that block are not all of the wave.
  379. pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data";
  380. /// Instructions that read a lane mask (not EXEC implicitly, not a lane's
  381. /// bit) as a number.
  382. /// Per IR block: every lane of the wave that started the program runs it – no per-lane branch
  383. /// separates it from the entry (it lies in no lane branch's region: the blocks reachable from
  384. /// the branch that do not post-dominate it). None with an indirect exit (not followed).
  385. fn all_lane_blocks(st: &Structured) -> Option<Vec<bool>> {
  386. let n = st.exits.len();
  387. let mut all = vec![true; n];
  388. for (_, region) in lane_regions(st)? {
  389. for b in (0..n).filter(|&b| region[b]) {
  390. all[b] = false;
  391. }
  392. }
  393. Some(all)
  394. }
  395. /// Every per-lane branch (by its block) with its region: the blocks reachable from it that do
  396. /// not post-dominate it, which only some lanes run. Not the branches the wave takes together
  397. /// ([`Structured::wide`]), nor those on scalar conditions. None with an indirect exit.
  398. fn lane_regions(st: &Structured) -> Option<Vec<(usize, Vec<bool>)>> {
  399. let n = st.exits.len();
  400. let mut succ: Vec<Vec<usize>> = vec![Vec::new(); n];
  401. for (b, e) in st.exits.iter().enumerate() {
  402. match *e {
  403. LaneExit::Jump(t) => succ[b].push(t),
  404. LaneExit::Branch { taken, not_taken, .. } => {
  405. succ[b].push(taken);
  406. succ[b].push(not_taken);
  407. }
  408. LaneExit::End => {}
  409. LaneExit::Indirect => return None,
  410. }
  411. }
  412. // post-dominators (bitsets; a virtual exit after every End)
  413. let words = n.div_ceil(64);
  414. let full = vec![u64::MAX; words];
  415. let mut pdom: Vec<Vec<u64>> = (0..n).map(|b| if succ[b].is_empty() { let mut v = vec![0; words]; v[b / 64] |= 1 << (b % 64); v } else { full.clone() }).collect();
  416. let mut changed = true;
  417. while changed {
  418. changed = false;
  419. for b in (0..n).rev() {
  420. if succ[b].is_empty() {
  421. continue;
  422. }
  423. let mut v = full.clone();
  424. for &t in &succ[b] {
  425. for w in 0..words {
  426. v[w] &= pdom[t][w];
  427. }
  428. }
  429. v[b / 64] |= 1 << (b % 64);
  430. if v != pdom[b] {
  431. pdom[b] = v;
  432. changed = true;
  433. }
  434. }
  435. }
  436. let mut regions = Vec::new();
  437. for (d, e) in st.exits.iter().enumerate() {
  438. let LaneExit::Branch { when, .. } = *e else { continue };
  439. if st.wide.contains(&d) || st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) {
  440. continue; // a wave-wide or uniform branch: all lanes go the same way
  441. }
  442. // blocks reachable from the lane branch that do not post-dominate it
  443. let mut seen = vec![false; n];
  444. let mut stack: Vec<usize> = succ[d].clone();
  445. while let Some(b) = stack.pop() {
  446. if seen[b] || pdom[d][b / 64] >> (b % 64) & 1 == 1 {
  447. continue;
  448. }
  449. seen[b] = true;
  450. stack.extend(succ[b].iter().copied());
  451. }
  452. regions.push((d, seen));
  453. }
  454. Some(regions)
  455. }
  456. /// The per-lane branches (by block) whose regions hold a block of `needs` (blocks where two
  457. /// host waves must meet, [`take_needs`]): the ones to take wave-wide
  458. /// ([`crate::structure::structure_wide`]) so that every lane runs those blocks. None if one
  459. /// of them is a branch whose wave-wide meaning is not known ([`Structured::wave_any`]).
  460. pub(super) fn branches_around(st: &Structured, needs: &[usize]) -> Option<Vec<usize>> {
  461. let mut out = Vec::new();
  462. for (d, region) in lane_regions(st)? {
  463. if needs.iter().any(|&b| region.get(b).copied().unwrap_or(false)) {
  464. st.wave_any.get(d).copied().flatten()?;
  465. out.push(d);
  466. }
  467. }
  468. Some(out)
  469. }
  470. /// Whether a refusal is of code that needs every lane of the wave where it stands (two host
  471. /// waves meeting there), which the other forms of the program may give it.
  472. pub(super) fn needs_every_lane(what: &str) -> bool {
  473. what.ends_with("where not every lane runs") || what == MASK_ELSEWHERE
  474. }
  475. /// The blocks where the last lowering on this thread wanted every lane and did not have it
  476. /// (its "... where not every lane runs" refusals), which it forgets.
  477. pub(super) fn take_needs() -> Vec<usize> {
  478. NEEDS.take()
  479. }
  480. fn need(block: usize) {
  481. NEEDS.with_borrow_mut(|n| {
  482. if !n.contains(&block) {
  483. n.push(block);
  484. }
  485. });
  486. }
  487. /// VGPR values that are the same in every lane holding them (`all` is [`all_lane_blocks`]):
  488. /// written by an instruction every arriving lane runs (no guard), lane by lane, from scalars,
  489. /// constants and such values; or loaded from an address made of them. The compiler keeps
  490. /// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`.
  491. /// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes
  492. /// run (no lane branch can have split the arriving lanes); loop-carried values never do.
  493. fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet<Value> {
  494. let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
  495. let mut same: HashSet<Value> = HashSet::new();
  496. for b in crate::ir::reverse_postorder(&p.blocks) {
  497. let block = &p.blocks[b];
  498. let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false));
  499. for phi in &block.phis {
  500. if matches!(phi.reg, Reg::V(_)) && whole && phi.args.iter().all(|a| same.contains(a)) {
  501. same.insert(phi.value);
  502. }
  503. }
  504. for (i, inst) in block.insts.iter().enumerate() {
  505. let name = inst.name();
  506. let ops: Vec<Operand> = match &inst.fields {
  507. Fields::Valu(v)
  508. if v.dpp.is_none()
  509. && v.sdwa.is_none()
  510. && !name.starts_with("v_mbcnt")
  511. && !name.starts_with("v_cmpx")
  512. && !name.contains("lane") =>
  513. {
  514. v.src.clone()
  515. }
  516. _ => continue,
  517. };
  518. if st.guards[b][i].is_some() {
  519. continue; // lanes outside EXEC keep another value
  520. }
  521. let alike = ops.iter().all(|op| match *op {
  522. Operand::Vector { reg, .. } => {
  523. // every dword of the operand the instruction reads from that register on
  524. let read: Vec<Value> =
  525. inst.reads.iter().filter(|r| matches!(r.0, Reg::V(x) if x >= reg)).map(|r| r.1).collect();
  526. !read.is_empty() && read.iter().all(|x| same.contains(x))
  527. }
  528. // a scalar is one value; a lane mask is not, unless a compare of such values made it
  529. Operand::Scalar { code, .. } if code != NULL => {
  530. inst.read(Reg::S(code)).is_none_or(|x| !is_mask(x) || same.contains(&x))
  531. }
  532. _ => true,
  533. });
  534. if alike {
  535. same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1));
  536. }
  537. }
  538. }
  539. same
  540. }
  541. /// What a register value holds, for [`wave_local`].
  542. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  543. enum Wave {
  544. /// Nothing that depends on how the threads are divided into waves.
  545. Plain,
  546. /// The number of the wave's first lane in a mask (`s_ff1`).
  547. First,
  548. /// A reduction over the wave's lanes: a count, a sum, a minimum...
  549. Total(super::wave::Op),
  550. /// A count or sum over the lanes below this one.
  551. Prefix,
  552. /// Derived from what a first-lane atomic returned: the slots the wave reserved.
  553. Base,
  554. /// A mix the idiom does not make.
  555. Mixed,
  556. }
  557. /// Whether a console wave64 program may run with each host wave as a wave of its own
  558. /// ([`with_local_waves`]): its wave-wide values are used only as the allocation idiom uses
  559. /// them, which does not care how the threads are divided into waves. A first-lane number only
  560. /// picks the first lane; a count or sum only goes into that lane's atomic on a shared counter;
  561. /// a prefix only goes onto the base that atomic returned; the first lane does nothing else.
  562. /// Anything else done with them takes one wave to be the whole thread group (a tile's result,
  563. /// say) and is refused, with the offset and what was found.
  564. /// Lane masks read as numbers by other instructions and lane reads outside whole-wave sections
  565. /// are stopped by the lowering itself.
  566. // shortcut: `v_readfirstlane` of a value that differs between lanes is taken as it is (this
  567. // host wave's first lane), and a guarded write of a plain value over a wave-dependent one is
  568. // the only mix of old and new lanes that is looked at.
  569. pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'static str)> {
  570. use super::wave::{Op, Shape};
  571. const FIRST: Why = "a wave's first-lane number used as data";
  572. const TOTAL: Why = "a count or sum over the wave used as data";
  573. const PREFIX: Why = "a count or sum over the lanes below used without a reserved base";
  574. const MIXED: Why = "a value that depends on the wave on some paths only";
  575. const EFFECT: Why = "a write by the wave's first lane other than its reservation";
  576. fn of(kind: &HashMap<Value, Wave>, v: Option<Value>) -> Wave {
  577. v.and_then(|v| kind.get(&v).copied()).unwrap_or(Wave::Plain)
  578. }
  579. fn put(kind: &mut HashMap<Value, Wave>, v: Value, k: Wave) {
  580. if k == Wave::Plain {
  581. kind.remove(&v);
  582. } else {
  583. kind.insert(v, k);
  584. }
  585. }
  586. let wild = |k: Wave| !matches!(k, Wave::Plain | Wave::Base);
  587. let why = |k: Wave| match k {
  588. Wave::First => FIRST,
  589. Wave::Total(_) => TOTAL,
  590. Wave::Prefix => PREFIX,
  591. _ => MIXED,
  592. };
  593. // a mask (by its low dword) under which only a wave's first lane runs
  594. let first_mask = |firsts: &HashSet<Value>, m: Option<Value>| {
  595. m.and_then(|m| st.masks.get(&m)).is_some_and(|&b| {
  596. st.bools
  597. .support(b)
  598. .iter()
  599. .any(|a| matches!(a, Atom::Lane(v) if firsts.contains(v)))
  600. })
  601. };
  602. // One instruction outside a section: the kind of what it writes, and whether it is a
  603. // first lane's reservation.
  604. let step = |inst: &Inst, kind: &HashMap<Value, Wave>, firsts: &mut HashSet<Value>| -> Result<(Wave, bool), Why> {
  605. let name = inst.name();
  606. let val = |op: &Operand| match *op {
  607. Operand::Vector { reg, .. } => inst.read(Reg::V(reg)),
  608. Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)),
  609. _ => None,
  610. };
  611. let ops: Vec<Operand> = match &inst.fields {
  612. Fields::Valu(v) => v.src.clone(),
  613. Fields::Sop { dst, src, .. } => {
  614. let mut o = src.clone();
  615. if matches!(name, "s_addk_i32" | "s_mulk_i32") {
  616. o.extend(dst.iter().copied());
  617. }
  618. o
  619. }
  620. Fields::Buffer { data, .. } if name.contains("_atomic_") || name.contains("_store_") => {
  621. data.iter().copied().collect()
  622. }
  623. _ => Vec::new(),
  624. };
  625. let kinds: Vec<Wave> = ops.iter().map(|o| of(kind, val(o))).collect();
  626. // Everything else it reads (addresses, descriptors, SCC, the high dwords of wide
  627. // operands) must not depend on the wave. Not EXEC, and not the old value of a VGPR it
  628. // writes, which only the lanes outside EXEC keep.
  629. let named: Vec<Value> = ops.iter().filter_map(&val).collect();
  630. for &(r, v) in &inst.reads {
  631. let kept = matches!(r, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == r);
  632. if matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) || kept || named.contains(&v) {
  633. continue;
  634. }
  635. let k = of(kind, Some(v));
  636. if wild(k) {
  637. return Err(why(k));
  638. }
  639. }
  640. let w = kinds.iter().copied().find(|&k| wild(k)).unwrap_or(Wave::Mixed);
  641. let sum = |k: Wave| k == Wave::Total(Op::AddU);
  642. let is_mask = |o: &Operand| {
  643. val(o).is_some_and(|v| st.masks.contains_key(&v) || st.highs.contains_key(&v))
  644. };
  645. let mut reserved = false;
  646. let out = match (name, &kinds[..]) {
  647. ("s_ff1_i32_b64" | "s_ff1_i32_b32", _) if ops.first().is_some_and(is_mask) => Wave::First,
  648. ("s_bcnt1_i32_b64" | "s_bcnt1_i32_b32", _) if ops.first().is_some_and(is_mask) => {
  649. Wave::Total(Op::AddU)
  650. }
  651. // bits of a mask below the lane; with -1 for the mask, the lane's number
  652. ("v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32", [_, b]) => {
  653. match (matches!(ops[0], Operand::Scalar { .. }), *b) {
  654. (_, Wave::Prefix) | (true, Wave::Plain | Wave::Base) => Wave::Prefix,
  655. (false, Wave::Plain | Wave::Base) => Wave::Plain,
  656. (_, k) => return Err(why(k)),
  657. }
  658. }
  659. // nothing wave-dependent goes in; what derives from a reserved base stays marked
  660. _ if !kinds.iter().any(|&k| wild(k)) => {
  661. let derives = matches!(inst.fields, Fields::Valu(_) | Fields::Sop { .. });
  662. if derives && kinds.contains(&Wave::Base) { Wave::Base } else { Wave::Plain }
  663. }
  664. ("v_mov_b32" | "s_mov_b32", [k]) => *k,
  665. ("v_cmp_eq_i32" | "v_cmp_eq_u32" | "v_cmpx_eq_i32" | "v_cmpx_eq_u32", [a, b]) => {
  666. // the lane whose own number is the first lane's
  667. let lane = match (*a, *b) {
  668. (Wave::First, k) if !wild(k) => &ops[1],
  669. (k, Wave::First) if !wild(k) => &ops[0],
  670. _ => return Err(why(w)),
  671. };
  672. if !matches!(lane, Operand::Vector { .. }) {
  673. return Err(FIRST);
  674. }
  675. let mask = match &inst.fields {
  676. _ if name.starts_with("v_cmpx") => inst.write(Reg::S(EXEC)),
  677. Fields::Valu(v) => match v.dst {
  678. Some(Operand::Scalar { code, .. }) => inst.write(Reg::S(code)),
  679. _ => None,
  680. },
  681. _ => None,
  682. };
  683. firsts.extend(mask);
  684. Wave::Plain
  685. }
  686. ("v_add_nc_u32" | "s_add_i32", [a, b]) => match (*a, *b) {
  687. (Wave::Prefix, Wave::Base) | (Wave::Base, Wave::Prefix) => Wave::Base,
  688. (Wave::Prefix, Wave::Plain | Wave::Prefix) | (Wave::Plain, Wave::Prefix) => Wave::Prefix,
  689. (x, y) if sum(x) && sum(y) => x,
  690. _ => return Err(why(w)),
  691. },
  692. ("v_sub_nc_u32" | "s_sub_i32", [a, b]) => match (*a, *b) {
  693. (Wave::Base, Wave::Prefix) => Wave::Base,
  694. (Wave::Prefix, Wave::Plain) => Wave::Prefix,
  695. (Wave::Plain, y) if sum(y) && matches!(ops[0], Operand::Const(128)) => y,
  696. _ => return Err(why(w)),
  697. },
  698. ("s_mul_i32" | "v_mul_lo_u32" | "v_mul_u32_u24", [a, b]) => match (*a, *b) {
  699. (x, Wave::Plain) | (Wave::Plain, x) if sum(x) || x == Wave::Prefix => x,
  700. _ => return Err(why(w)),
  701. },
  702. ("s_lshl_b32", [x, Wave::Plain]) | ("v_lshlrev_b32", [Wave::Plain, x])
  703. if sum(*x) || *x == Wave::Prefix =>
  704. {
  705. *x
  706. }
  707. ("v_lshl_add_u32", [Wave::Prefix, Wave::Plain, c]) if !wild(*c) => {
  708. if *c == Wave::Base { Wave::Base } else { Wave::Prefix }
  709. }
  710. // the reservation: the first lane adds its wave's total to a shared counter
  711. (_, [Wave::Total(op)]) if name.contains("_atomic_") => {
  712. let want = match op {
  713. Op::AddU => "buffer_atomic_add",
  714. Op::MinU => "buffer_atomic_umin",
  715. Op::MaxU => "buffer_atomic_umax",
  716. Op::MinI => "buffer_atomic_smin",
  717. Op::MaxI => "buffer_atomic_smax",
  718. Op::Or => "buffer_atomic_or",
  719. Op::And => "buffer_atomic_and",
  720. Op::Xor => "buffer_atomic_xor",
  721. _ => "",
  722. };
  723. if name != want || !first_mask(firsts, inst.read(Reg::S(EXEC))) {
  724. return Err(TOTAL);
  725. }
  726. reserved = true;
  727. Wave::Base
  728. }
  729. _ => return Err(why(w)),
  730. };
  731. Ok((out, reserved))
  732. };
  733. let sections: Vec<_> = (0..p.blocks.len()).map(|b| super::wave::sections(p, b)).collect();
  734. let order = crate::ir::reverse_postorder(&p.blocks);
  735. let pass = |kind: &mut HashMap<Value, Wave>, firsts: &mut HashSet<Value>, check: bool| -> Result<(), (usize, Why)> {
  736. for &b in &order {
  737. let block = &p.blocks[b];
  738. for phi in &block.phis {
  739. let mut k = Wave::Plain;
  740. for (n, &a) in phi.args.iter().enumerate() {
  741. let x = of(kind, Some(a));
  742. k = match (k, x) {
  743. _ if n == 0 => x,
  744. (k, x) if k == x => k,
  745. (Wave::Plain, m @ (Wave::Base | Wave::Prefix))
  746. | (m @ (Wave::Base | Wave::Prefix), Wave::Plain) => m,
  747. _ => Wave::Mixed,
  748. };
  749. }
  750. put(kind, phi.value, k);
  751. }
  752. for (i, inst) in block.insts.iter().enumerate() {
  753. // inside a whole-wave section: what the simulation found each value to be
  754. if let Some((_, sec)) = sections[b].iter().find(|(s, sec)| i > **s && i < sec.end) {
  755. for &(_, w) in &inst.writes {
  756. let k = match sec.shapes.get(&w) {
  757. None => Wave::Mixed,
  758. Some(&Shape::K(_)) => Wave::Plain,
  759. Some(&Shape::Value(v)) => of(kind, Some(v)),
  760. Some(&Shape::Masked(src, _, _)) => of(kind, Some(src)),
  761. Some(&Shape::Active(op, src, mask, _)) => match of(kind, Some(src)) {
  762. Wave::Plain | Wave::Base => Wave::Total(op),
  763. // the first lane's own sum of a total is that total
  764. Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => Wave::Total(op),
  765. _ => Wave::Mixed,
  766. },
  767. Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => match of(kind, Some(src)) {
  768. Wave::Plain | Wave::Base => Wave::Prefix,
  769. Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => Wave::Prefix,
  770. _ => Wave::Mixed,
  771. },
  772. Some(_) => Wave::Mixed,
  773. };
  774. put(kind, w, k);
  775. }
  776. continue;
  777. }
  778. let name = inst.name();
  779. if name.starts_with("s_cbranch") {
  780. continue; // with the block's exit, below
  781. }
  782. let (k, reserved) = match step(inst, kind, firsts) {
  783. Ok(r) => r,
  784. Err(why) if check => return Err((inst.machine.offset, why)),
  785. Err(_) => (Wave::Mixed, false),
  786. };
  787. // the same test as `Lower::inst`'s `effect`
  788. let effect = matches!(inst.fields, Fields::Exp { .. })
  789. || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
  790. || name.contains("store")
  791. || name.contains("atomic")
  792. || matches!(inst.fields, Fields::Ds { .. })
  793. && !(name.starts_with("ds_read")
  794. || name.starts_with("ds_swizzle")
  795. || name.contains("permute"));
  796. if check && effect && !reserved && first_mask(firsts, inst.read(Reg::S(EXEC))) {
  797. return Err((inst.machine.offset, EFFECT));
  798. }
  799. let guarded = st.guards[b][i].is_some();
  800. for &(r, w) in &inst.writes {
  801. let mut kw = match r {
  802. // "some lane is counted" keeps the count's kind; any other SCC is one bit of data
  803. Reg::Scc if !name.starts_with("s_bcnt1") => {
  804. if wild(k) { Wave::Mixed } else { Wave::Plain }
  805. }
  806. _ => k,
  807. };
  808. // a guarded write leaves the old value in the lanes outside EXEC
  809. if guarded
  810. && matches!(r, Reg::V(_))
  811. && kw == Wave::Plain
  812. && matches!(of(kind, inst.read(r)), Wave::First | Wave::Total(_) | Wave::Prefix)
  813. {
  814. kw = Wave::Mixed;
  815. }
  816. put(kind, w, kw);
  817. }
  818. }
  819. // a branch on "some lane is counted": fine where the structure made it the lane's
  820. // own bit (the mask is EXEC under a scalar condition)
  821. if check
  822. && let Some(last) = block.insts.last()
  823. && last.name().starts_with("s_cbranch_scc")
  824. && let Some(scc) = last.read(Reg::Scc)
  825. && wild(of(kind, Some(scc)))
  826. {
  827. let own = matches!(st.exits[b], LaneExit::Branch { when, .. }
  828. if !st.bools.support(when).iter().any(|a| matches!(a, Atom::Uniform(v) if *v == scc)));
  829. if !own {
  830. return Err((last.machine.offset, TOTAL));
  831. }
  832. }
  833. }
  834. Ok(())
  835. };
  836. let mut kind: HashMap<Value, Wave> = HashMap::new();
  837. let mut firsts: HashSet<Value> = HashSet::new();
  838. // to a fixpoint (values carried around loops), then once more to say what is wrong
  839. let mut settled = false;
  840. for _ in 0..16 {
  841. let before = (kind.clone(), firsts.len());
  842. pass(&mut kind, &mut firsts, false)?;
  843. if (&before.0, before.1) == (&kind, firsts.len()) {
  844. settled = true;
  845. break;
  846. }
  847. }
  848. if !settled {
  849. return Err((0, MIXED));
  850. }
  851. pass(&mut kind, &mut firsts, true)
  852. }
  853. /// The mode of a group barrier the translation adds (host waves meeting):
  854. /// a wait for the group with a shared-memory fence; the fence alone with
  855. /// `VICTORY_GROUP_SYNC=0` ([`super::group_sync`]).
  856. fn meeting_mode() -> u32 {
  857. if super::group_sync() == 0 { 8 } else { 1 | 8 }
  858. }
  859. /// LDS accesses of a console wave run as two host waves, where some sit in blocks that only
  860. /// some lanes run (`all` is [`all_lane_blocks`]): per IR block, whether the host waves meet (a
  861. /// group barrier) at its start and before its exit. `None` if barriers cannot keep the
  862. /// console's order.
  863. ///
  864. /// The console runs the wave's lanes in step, so an LDS write is seen by every later read. Two
  865. /// host waves keep that order if they meet between any two accesses of which one writes. A
  866. /// barrier must be run by every thread, so it cannot stand in a lane branch's region; but
  867. /// every way into and out of such a region passes a block all lanes run, and the waves meet
  868. /// there: before the exit of an all-lane block into a region with LDS accesses, and at the
  869. /// start of an all-lane block entered from one. Accesses in all-lane blocks get their own
  870. /// barrier as before. What that cannot order is a write and a read inside one region (blocks
  871. /// joined without an all-lane block between them): refused.
  872. /// shortcut: two writes in one region are taken not to hit the same dword from both halves.
  873. fn lds_meetings(p: &crate::ir::Program, st: &Structured, all: &[bool]) -> Option<Vec<(bool, bool)>> {
  874. let n = st.exits.len();
  875. let succ = |b: usize| -> Vec<usize> {
  876. match st.exits[b] {
  877. LaneExit::Jump(t) => vec![t],
  878. LaneExit::Branch { taken, not_taken, .. } => vec![taken, not_taken],
  879. LaneExit::End | LaneExit::Indirect => Vec::new(),
  880. }
  881. };
  882. // regions: blocks not every lane runs, joined by the edges between them
  883. let mut region: Vec<usize> = (0..n).collect();
  884. fn find(region: &mut [usize], mut b: usize) -> usize {
  885. while region[b] != b {
  886. region[b] = region[region[b]];
  887. b = region[b];
  888. }
  889. b
  890. }
  891. for b in 0..n {
  892. for t in succ(b) {
  893. if !all[b] && !all[t] {
  894. let (x, y) = (find(&mut region, b), find(&mut region, t));
  895. region[x] = y;
  896. }
  897. }
  898. }
  899. // per region: LDS reads, LDS writes
  900. let mut reads = vec![false; n];
  901. let mut writes = vec![false; n];
  902. for (b, block) in p.blocks.iter().enumerate().take(n) {
  903. if all[b] {
  904. continue;
  905. }
  906. let r = find(&mut region, b);
  907. for i in &block.insts {
  908. let name = i.name();
  909. if !matches!(i.fields, Fields::Ds { .. }) || name.starts_with("ds_swizzle") || name.contains("permute") {
  910. continue;
  911. }
  912. if name.starts_with("ds_read") {
  913. reads[r] = true;
  914. } else {
  915. writes[r] = true;
  916. }
  917. }
  918. }
  919. if (0..n).any(|r| reads[r] && writes[r]) {
  920. return None;
  921. }
  922. let mut meet = vec![(false, false); n];
  923. for b in 0..n {
  924. for t in succ(b) {
  925. if all[b] && !all[t] {
  926. let r = find(&mut region, t);
  927. meet[b].1 |= reads[r] || writes[r];
  928. } else if !all[b] && all[t] {
  929. let r = find(&mut region, b);
  930. meet[t].0 |= reads[r] || writes[r];
  931. }
  932. }
  933. }
  934. Some(meet)
  935. }
  936. /// Masks held as numbers or constant lane sets in guards or lane branches: the lane tests its
  937. /// own bit by its console lane.
  938. fn lane_constant_masks(st: &Structured) -> bool {
  939. let whens = st.exits.iter().filter_map(|e| match *e {
  940. LaneExit::Branch { when, .. } => Some(when),
  941. _ => None,
  942. });
  943. let mut work: Vec<Bool> = st.guards.iter().flatten().flatten().copied().chain(whens).collect();
  944. // Through lane-mask joins too: an edge that brings a number or a constant lane set needs
  945. // the lane's own bit of it.
  946. // shortcut: masks only selects read (`v_cndmask_b32`, carries in) are not followed; such
  947. // a program still stops with "a constant lane mask" or "an opaque lane mask".
  948. let (mut seen, mut joins) = (HashSet::new(), HashSet::new());
  949. while let Some(g) = work.pop() {
  950. if !seen.insert(g) {
  951. continue;
  952. }
  953. for a in st.bools.support(g) {
  954. match a {
  955. Atom::Opaque(_) | Atom::Constant(_) => return true,
  956. Atom::Phi(id) if joins.insert(id) => {
  957. if let Some(edges) = st.phi_masks.get(&id) {
  958. work.extend(edges.iter().copied());
  959. }
  960. }
  961. _ => {}
  962. }
  963. }
  964. }
  965. false
  966. }
  967. /// The widest wave the host GPU runs (0: not known – no host-specific forms); see
  968. /// [`set_host_max_wave`].
  969. static HOST_MAX_WAVE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  970. /// The host GPU's `WaveLaneCountMax`: 32 lets console wave64 compute programs whose cross-lane
  971. /// code stays inside 32-lane halves run in waves of 32 instead of being refused.
  972. pub fn set_host_max_wave(lanes: u32) {
  973. HOST_MAX_WAVE.store(lanes, std::sync::atomic::Ordering::Relaxed);
  974. }
  975. thread_local! {
  976. /// See [`take_needs`].
  977. static NEEDS: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
  978. /// See [`with_local_waves`].
  979. static LOCAL_WAVES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
  980. /// See [`with_local_waves_any`].
  981. static LOCAL_ANY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
  982. }
  983. /// As [`with_local_waves`], with every other use of a lane mask as a number
  984. /// and every lane read and write taken per host wave too: the program runs
  985. /// as it would on a console of 32-lane waves, lanes numbered 0..31 or
  986. /// 32..63 by half. Right for code that only relies on what HLSL's wave
  987. /// operations promise; a program that takes one wave to be its whole
  988. /// thread group gets per-half results. The last resort for programs that
  989. /// do not translate otherwise.
  990. pub(super) fn with_local_waves_any<R>(f: impl FnOnce() -> R) -> R {
  991. let was = LOCAL_ANY.replace(true);
  992. let r = with_local_waves(f);
  993. LOCAL_ANY.set(was);
  994. r
  995. }
  996. /// Runs `f` with console wave64 programs on 32-lane hosts lowered with each
  997. /// host wave as a wave of its own ("local"): no exchange between the two
  998. /// halves of a console wave, so no barriers and no need for every lane to
  999. /// reach the code. What HLSL's wave operations promise holds for any
  1000. /// division of the threads into waves, and the idiom the title's compute
  1001. /// programs use them for does not care which wave a thread is in: count or
  1002. /// sum over the wave, the first lane reserves that many slots with an atomic
  1003. /// add, every lane takes the base (`WaveReadLaneFirst`) plus its prefix.
  1004. /// Each lane still gets a slot of its own; only the order differs.
  1005. /// Only that idiom's operations are lowered this way: a lane mask read as
  1006. /// a number by anything but a bit count, a first-set-bit or `v_mbcnt`, and
  1007. /// lane reads and writes outside whole-wave sections, stop the translation.
  1008. /// shortcut: where a count or sum goes is not checked. A program that uses
  1009. /// a wave-wide result as data for the whole console wave (a tile's maximum,
  1010. /// say, with one wave per thread group) gets its half's result. It is used
  1011. /// only for programs that do not translate otherwise.
  1012. pub(super) fn with_local_waves<R>(f: impl FnOnce() -> R) -> R {
  1013. let was = LOCAL_WAVES.replace(true);
  1014. let r = f();
  1015. LOCAL_WAVES.set(was);
  1016. r
  1017. }
  1018. /// `VICTORY_F16_NEAREST=1`: the results of 16-bit float operations (`v_add_f16`,
  1019. /// `v_mul_f16`, `v_cvt_f16_f32` ...) are rounded to nearest as the console rounds them
  1020. /// ([`Lower::f16_nearest`]) instead of as the host's `f32tof16` does (toward zero on NVIDIA:
  1021. /// the last place of a result that is not exact is then one lower than the console's).
  1022. /// Off by default: it is exact but untried in a game run, and adds instructions to every
  1023. /// such operation. The wave sum of 16-bit floats ([`Lower::half_sum`]) is always exact.
  1024. fn f16_nearest_on() -> bool {
  1025. #[cfg(test)]
  1026. if let Some(on) = TEST_F16_NEAREST.get() {
  1027. return on;
  1028. }
  1029. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1030. *ON.get_or_init(|| std::env::var_os("VICTORY_F16_NEAREST").is_some_and(|v| v == "1"))
  1031. }
  1032. #[cfg(test)]
  1033. thread_local! {
  1034. /// A test's choice for [`f16_nearest_on`], for its thread only.
  1035. pub(super) static TEST_F16_NEAREST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
  1036. }
  1037. /// `VICTORY_WAVE_OWN_BITS=0`: a wave OR where not every lane runs is refused as before
  1038. /// ([`super::own_bits`]).
  1039. fn own_bits_on() -> bool {
  1040. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1041. *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0"))
  1042. }
  1043. /// What the translator was told of the host, for a cache's key: the widest
  1044. /// wave and the view heap's limit.
  1045. pub fn host_settings() -> [u32; 2] {
  1046. [host_max_wave(), super::shader::view_heap_limit()]
  1047. }
  1048. pub(super) fn host_max_wave() -> u32 {
  1049. #[cfg(test)]
  1050. if let Some(lanes) = TEST_HOST_WAVE.get() {
  1051. return lanes;
  1052. }
  1053. HOST_MAX_WAVE.load(std::sync::atomic::Ordering::Relaxed)
  1054. }
  1055. #[cfg(test)]
  1056. thread_local! {
  1057. /// A test's host wave size, for its thread only ([`set_host_max_wave`] is the process's).
  1058. pub(super) static TEST_HOST_WAVE: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
  1059. }
  1060. pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool {
  1061. let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
  1062. let ops: Vec<&Operand> = match &i.fields {
  1063. // A mask operation (its result a mask) is no data use.
  1064. Fields::Sop { .. }
  1065. if i.writes
  1066. .iter()
  1067. .any(|&(r, w)| matches!(r, Reg::S(_)) && is_mask(w)) =>
  1068. {
  1069. return false;
  1070. }
  1071. Fields::Sop { src, .. } => src.iter().collect(),
  1072. Fields::Valu(v)
  1073. if !matches!(i.name(), "v_cndmask_b32") && !i.name().contains("_co_ci_") =>
  1074. {
  1075. v.src.iter().collect()
  1076. }
  1077. _ => return false,
  1078. };
  1079. ops.into_iter().any(|op| match *op {
  1080. Operand::Scalar { code, .. } if code != NULL => i.read(Reg::S(code)).is_some_and(is_mask),
  1081. _ => false,
  1082. })
  1083. }
  1084. /// The parameters packing 16-bit rows two per dword and where each lays
  1085. /// its elements out: (first row, [(dword, register, column, columns)]).
  1086. ///
  1087. /// The console gives every 16-bit element whole dwords. A parameter leads
  1088. /// with the first element of its first row, then the first element of its
  1089. /// second row. An element that shares a register behind another one (the
  1090. /// signature packs a short element into the free columns of an earlier
  1091. /// register) is NOT in that row's halves: it follows in the first
  1092. /// parameter, in row order, that has whole dwords left.
  1093. /// The title's packed pedestrian shaders show both cases: TEXCOORD7 (register 1,
  1094. /// columns 2-3, behind the two columns of TEXCOORD0) is exported in dword 3
  1095. /// of parameter 0, after TEXCOORD1's two dwords; TEXCOORD6 (register 4,
  1096. /// column 3, behind the three columns of TEXCOORD4) in dword 3 of
  1097. /// parameter 3, after TEXCOORD5 and TEXCOORD7, while the high half of
  1098. /// TEXCOORD4's second dword stays zero.
  1099. type PackedLayout = Vec<(u8, Vec<(u8, u8, u8, u8)>)>;
  1100. fn packed_layout(elements: &[SigElement], packs: &[(u8, Option<u8>)]) -> PackedLayout {
  1101. let of_row = |r: u8| {
  1102. let mut of: Vec<&SigElement> = elements
  1103. .iter()
  1104. .filter(|e| e.row == Some(u32::from(r)))
  1105. .collect();
  1106. of.sort_by_key(|e| e.col);
  1107. of
  1108. };
  1109. let mut packs = packs.to_vec();
  1110. packs.sort_unstable();
  1111. packs.dedup_by_key(|p| p.0);
  1112. // Per parameter: its first row, the dwords used, the elements.
  1113. let mut layout: Vec<(u8, u8, Vec<(u8, u8, u8, u8)>)> = Vec::new();
  1114. let mut behind = Vec::new();
  1115. for &(a, b) in &packs {
  1116. let mut placed = Vec::new();
  1117. let mut at = 0u8;
  1118. if !of_row(a).is_empty() {
  1119. for r in [Some(a), b].into_iter().flatten() {
  1120. let of = of_row(r);
  1121. let Some((lead, more)) = of.split_first() else {
  1122. continue;
  1123. };
  1124. placed.push((at, r, lead.col, lead.cols));
  1125. at += lead.cols.div_ceil(2);
  1126. behind.extend(more.iter().map(|e| (r, e.col, e.cols)));
  1127. }
  1128. }
  1129. layout.push((a, at, placed));
  1130. }
  1131. behind.sort_unstable();
  1132. for (r, col, cols) in behind {
  1133. let need = cols.div_ceil(2);
  1134. if let Some(p) = layout.iter_mut().find(|p| p.1 + need <= 4) {
  1135. p.2.push((p.1, r, col, cols));
  1136. p.1 += need;
  1137. }
  1138. }
  1139. layout.into_iter().map(|(a, _, of)| (a, of)).collect()
  1140. }
  1141. /// Where half `h` (dword h / 2, the high half when odd) of the parameter
  1142. /// whose first 16-bit row is `a` comes from: a register and column of
  1143. /// `elements`, none for padding ([`packed_layout`]; `packs` lists every
  1144. /// parameter packing two 16-bit rows per dword).
  1145. fn packed_half(
  1146. elements: &[SigElement],
  1147. packs: &[(u8, Option<u8>)],
  1148. a: u8,
  1149. h: u8,
  1150. ) -> Option<(u8, u8)> {
  1151. let layout = packed_layout(elements, packs);
  1152. let (_, of) = layout.iter().find(|p| p.0 == a)?;
  1153. of.iter().find_map(|&(dword, row, col, cols)| {
  1154. let k = h.checked_sub(2 * dword)?;
  1155. (k < cols).then_some((row, col + k))
  1156. })
  1157. }
  1158. /// The pixel inputs packing two 16-bit rows per dword, as (first row,
  1159. /// second row) ([`packed_layout`]).
  1160. fn input_packs(io: &StageIo, inputs: &[SigElement]) -> Vec<(u8, Option<u8>)> {
  1161. let StageIo::Ps {
  1162. inputs: entries, ..
  1163. } = io
  1164. else {
  1165. return Vec::new();
  1166. };
  1167. let partners = half_input_partners(io, inputs);
  1168. entries
  1169. .iter()
  1170. .filter(|i| i.fp16 && i.pack2)
  1171. .map(|i| {
  1172. let b = if i.row2 != i.row {
  1173. Some(i.row2)
  1174. } else {
  1175. partners.get(&i.row).copied()
  1176. };
  1177. (i.row, b)
  1178. })
  1179. .collect()
  1180. }
  1181. /// Vertex or mesh outputs of 16-bit values (see [`Lower::half_outputs`]):
  1182. /// a packed row's partner is the next 16-bit row of the signature that no
  1183. /// output entry names, taken in row order.
  1184. fn half_outputs(io: &StageIo, outputs: &[SigElement]) -> HashMap<u8, (bool, Option<u8>)> {
  1185. let entries = match io {
  1186. StageIo::Vs { outputs, .. } => outputs,
  1187. StageIo::Ms(ms) => &ms.outputs,
  1188. _ => return HashMap::new(),
  1189. };
  1190. let per_vertex = || entries.iter().filter(|o| o.param & 0x80 == 0);
  1191. let mut free: Vec<u8> = outputs
  1192. .iter()
  1193. .filter(|e| e.half && e.kind == 0)
  1194. .filter_map(|e| u8::try_from(e.row?).ok())
  1195. .filter(|&r| !per_vertex().any(|o| o.row == r))
  1196. .collect();
  1197. free.sort_unstable();
  1198. free.dedup();
  1199. let mut halves: Vec<_> = per_vertex().filter(|o| o.fp16).collect();
  1200. halves.sort_by_key(|o| o.row);
  1201. halves
  1202. .into_iter()
  1203. .map(|o| {
  1204. let b = o
  1205. .pack2
  1206. .then(|| free.iter().position(|&r| r > o.row))
  1207. .flatten();
  1208. (o.row, (o.pack2, b.map(|i| free.remove(i))))
  1209. })
  1210. .collect()
  1211. }
  1212. /// Pixel inputs packing two 16-bit rows per dword whose second row the
  1213. /// metadata leaves out (`row2` = `row`): as for outputs
  1214. /// ([`half_outputs`]), the next 16-bit row of the signature that no input
  1215. /// entry names, taken in row order (rows the metadata does give are taken
  1216. /// first).
  1217. fn half_input_partners(io: &StageIo, inputs: &[SigElement]) -> HashMap<u8, u8> {
  1218. let StageIo::Ps {
  1219. inputs: entries, ..
  1220. } = io
  1221. else {
  1222. return HashMap::new();
  1223. };
  1224. let packed = || entries.iter().filter(|i| i.fp16 && i.pack2);
  1225. let mut free: Vec<u8> = inputs
  1226. .iter()
  1227. .filter(|e| e.half && e.kind == 0)
  1228. .filter_map(|e| u8::try_from(e.row?).ok())
  1229. .filter(|&r| !entries.iter().any(|i| i.row == r))
  1230. .filter(|&r| !packed().any(|i| i.row2 != i.row && i.row2 == r))
  1231. .collect();
  1232. free.sort_unstable();
  1233. free.dedup();
  1234. let mut missing: Vec<_> = packed().filter(|i| i.row2 == i.row).collect();
  1235. missing.sort_by_key(|i| i.row);
  1236. let mut partners = HashMap::new();
  1237. for i in missing {
  1238. if let Some(k) = free.iter().position(|&r| r > i.row) {
  1239. partners.insert(i.row, free.remove(k));
  1240. }
  1241. }
  1242. partners
  1243. }
  1244. fn unsupported(offset: usize, what: Why) -> Stop {
  1245. Stop::Fail(ShaderError::Unsupported { offset, what })
  1246. }
  1247. impl<'a> Lower<'a> {
  1248. fn new(x: &'a Parts<'a>, bad: &'a HashMap<Value, Why>) -> Self {
  1249. let p = x.p;
  1250. let mut phi_at = HashMap::new();
  1251. for (b, block) in p.blocks.iter().enumerate() {
  1252. for (i, phi) in block.phis.iter().enumerate() {
  1253. phi_at.insert(phi.value, (b, i));
  1254. }
  1255. }
  1256. let mut s = Shader::new(x.native.stage == HwStage::Ps);
  1257. s.inputs = x.inputs.clone();
  1258. s.outputs = x.outputs.clone();
  1259. let insts = || p.blocks.iter().flat_map(|b| &b.insts);
  1260. let writes_uavs = insts().any(|i| {
  1261. matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. })
  1262. && (i.name().contains("store") || i.name().contains("atomic"))
  1263. });
  1264. let mut console_lanes = false;
  1265. // LDS accesses get a group barrier each (a console wave split in two host waves)
  1266. let mut split_lds = false;
  1267. // with `split_lds`, LDS accesses in lane branches: the blocks every lane runs, and
  1268. // where the host waves meet around those branches (`lds_meetings`)
  1269. let mut lds_meet: Option<(Vec<bool>, Vec<(bool, bool)>)> = None;
  1270. // a console wave64 program in two host waves of 32 (`exchange`)
  1271. let mut exchange: Option<(u32, bool, Vec<bool>)> = None;
  1272. // a console wave64 program in host waves of 32: the LDS dword of `wave_base`'s counter
  1273. let mut halves: Option<u32> = None;
  1274. if let StageIo::Cs(cs) = x.native.io {
  1275. s.threads = Some(cs.threads);
  1276. s.lds_dwords = cs.lds_bytes() / 4;
  1277. // Code reading other lanes needs the console's wave size and
  1278. // lane order; so do lane masks read as numbers, and LDS shared
  1279. // within one wave, where the console compiler leaves out barriers.
  1280. console_lanes = insts().any(|i| {
  1281. let n = i.name();
  1282. n.starts_with("ds_swizzle")
  1283. || n.contains("permute")
  1284. || n.starts_with("v_permlane")
  1285. || n.starts_with("v_mbcnt")
  1286. || matches!(n, "v_readlane_b32" | "v_writelane_b32")
  1287. || matches!(&i.fields, Fields::Valu(v) if v.dpp.is_some())
  1288. || reads_mask_as_data(x.st, i)
  1289. }) || lane_constant_masks(x.st)
  1290. // (a branch the wave takes together asks the wave)
  1291. || !x.st.wide.is_empty();
  1292. let mut wave = if x.native.wave64 { 64 } else { 32 };
  1293. let group = cs.threads.iter().product::<u32>();
  1294. let one_wave = group <= wave;
  1295. // A host whose waves are at most 32 lanes (NVIDIA) refuses `WaveSize(64)`. A console
  1296. // wave64 program whose cross-lane code stays inside 32-lane halves – DPP rows,
  1297. // `ds_swizzle`, `v_permlane16` / `v_permlanex16`, which the ISA confines there – runs
  1298. // exactly in waves of 32: the thread relabelling makes each host wave one half of a
  1299. // console wave (lanes 32k..32k+31). Not when it crosses halves (`v_mbcnt`,
  1300. // `v_readlane`, `v_writelane`, `ds_(b)permute`, masks as numbers or lane-constant
  1301. // masks), nor when LDS may be shared within the console wave without barriers (a
  1302. // group over 32 threads with LDS): those still need 64-lane waves.
  1303. if wave == 64 && host_max_wave() == 32 && (console_lanes || one_wave && s.lds_dwords > 0) {
  1304. let crosses = insts().any(|i| {
  1305. let n = i.name();
  1306. n.starts_with("v_mbcnt")
  1307. || matches!(n, "v_readlane_b32" | "v_writelane_b32")
  1308. || n.starts_with("ds_permute")
  1309. || n.starts_with("ds_bpermute")
  1310. || reads_mask_as_data(x.st, i)
  1311. }) || lane_constant_masks(x.st)
  1312. || !x.st.wide.is_empty();
  1313. if !crosses && (s.lds_dwords == 0 || group <= 32) {
  1314. wave = 32;
  1315. } else {
  1316. // (Groups of several console waves too: each console wave is two host
  1317. // waves, which exchange through their own pair of dwords.)
  1318. // LDS the console shares within its one wave without barriers: split into
  1319. // two waves of 32, a group barrier before every LDS access keeps their order
  1320. // – where every thread of the group gets there (no lane branch around it,
  1321. // no guard), else a barrier would hang the group
  1322. let lds = |i: &Inst| {
  1323. matches!(i.fields, Fields::Ds { .. })
  1324. && !(i.name().starts_with("ds_swizzle") || i.name().contains("permute"))
  1325. };
  1326. if let Some(all) = all_lane_blocks(x.st) {
  1327. let ok = p.blocks.iter().enumerate().all(|(b, blk)| {
  1328. blk.insts.iter().all(|inst| {
  1329. !lds(inst) || all.get(b).copied().unwrap_or(false)
  1330. })
  1331. });
  1332. let mut lds_ok = !(s.lds_dwords > 0 && group > 32) || ok;
  1333. if !lds_ok && let Some(meet) = lds_meetings(p, x.st, &all) {
  1334. lds_meet = Some((all.clone(), meet));
  1335. lds_ok = true;
  1336. }
  1337. if !lds_ok {
  1338. // (the blocks whose LDS accesses not every lane runs: with the
  1339. // branches around them taken wave-wide they get their barriers)
  1340. for (b, blk) in p.blocks.iter().enumerate() {
  1341. if !all.get(b).copied().unwrap_or(false) && blk.insts.iter().any(lds) {
  1342. need(b);
  1343. }
  1344. }
  1345. }
  1346. if lds_ok {
  1347. wave = 32;
  1348. split_lds = s.lds_dwords > 0 && group > 32;
  1349. if crosses {
  1350. // lanes 32..63 are the other host wave: masks, lane reads and lane
  1351. // numbers go through two exchange dwords past the program's LDS
  1352. exchange = Some((s.lds_dwords, group <= 32, all));
  1353. s.lds_dwords += 2 * group.div_ceil(64);
  1354. }
  1355. }
  1356. }
  1357. }
  1358. // `VICTORY_WAVE_WHY=1`: why a program keeps 64-lane waves (one line per reason)
  1359. if wave == 64 && std::env::var_os("VICTORY_WAVE_WHY").is_some() {
  1360. let mut why: Vec<&str> = Vec::new();
  1361. for i in insts() {
  1362. let n = i.name();
  1363. let r = if n.starts_with("v_mbcnt") {
  1364. "v_mbcnt"
  1365. } else if n == "v_readlane_b32" {
  1366. "v_readlane"
  1367. } else if n == "v_writelane_b32" {
  1368. "v_writelane"
  1369. } else if n.starts_with("ds_permute") || n.starts_with("ds_bpermute") {
  1370. "ds_(b)permute"
  1371. } else if reads_mask_as_data(x.st, i) {
  1372. "mask as data"
  1373. } else {
  1374. continue;
  1375. };
  1376. if !why.contains(&r) {
  1377. why.push(r);
  1378. }
  1379. }
  1380. if lane_constant_masks(x.st) {
  1381. why.push("lane-constant mask");
  1382. }
  1383. if s.lds_dwords > 0 && group > 32 {
  1384. why.push("LDS in a group over 32");
  1385. match all_lane_blocks(x.st) {
  1386. None => why.push("an indirect exit"),
  1387. Some(all) if lds_meetings(p, x.st, &all).is_none() => {
  1388. why.push("an LDS read and write in one lane-branch region")
  1389. }
  1390. Some(_) => {}
  1391. }
  1392. }
  1393. why.sort_unstable();
  1394. eprintln!("WAVE64-WHY group={group} lds={} [{}]", s.lds_dwords > 0, why.join(", "));
  1395. }
  1396. }
  1397. if wave == 32 && x.native.wave64 {
  1398. // console threads go to host waves in the order the waves take them (`wave_base`)
  1399. halves = Some(s.lds_dwords);
  1400. s.lds_dwords += 1;
  1401. }
  1402. if console_lanes || one_wave && s.lds_dwords > 0 {
  1403. s.wave_size = Some(wave);
  1404. }
  1405. }
  1406. // The title's barriers a thread of the group may never reach, which
  1407. // leaves the others waiting on the host: those in blocks some lanes
  1408. // do not run, and all of them in a program with a loop closed by a
  1409. // plain jump (a lane still in it at the iteration limit leaves the
  1410. // program there, `abort_block`).
  1411. let fence_only: HashSet<usize> = if insts().any(|i| i.name() == "s_barrier") {
  1412. let order = crate::ir::reverse_postorder(&p.blocks);
  1413. let mut place = vec![usize::MAX; p.blocks.len()];
  1414. for (n, &b) in order.iter().enumerate() {
  1415. place[b] = n;
  1416. }
  1417. let back = |from: usize, to: usize| {
  1418. let at = |b: usize| place.get(b).copied().unwrap_or(usize::MAX);
  1419. at(from) != usize::MAX && at(to) <= at(from)
  1420. };
  1421. let cut_short = x
  1422. .st
  1423. .exits
  1424. .iter()
  1425. .enumerate()
  1426. .any(|(b, e)| matches!(*e, LaneExit::Jump(t) if back(b, t)));
  1427. let all = all_lane_blocks(x.st);
  1428. (0..p.blocks.len())
  1429. .filter(|&b| p.blocks[b].insts.iter().any(|i| i.name() == "s_barrier"))
  1430. .filter(|&b| {
  1431. cut_short
  1432. || all
  1433. .as_ref()
  1434. .is_none_or(|all| !all.get(b).copied().unwrap_or(false))
  1435. })
  1436. .collect()
  1437. } else {
  1438. HashSet::new()
  1439. };
  1440. let mut no_barrier = HashSet::new();
  1441. if let StageIo::Ms(ms) = &x.native.io {
  1442. s.prims = x.prims.clone();
  1443. s.threads = Some([ms.threads, 1, 1]);
  1444. s.lds_dwords = ms.lds_bytes.div_ceil(4);
  1445. s.mesh = Some(super::shader::Mesh {
  1446. max_vertices: ms.max_vertices,
  1447. max_primitives: ms.max_primitives,
  1448. topology: ms.topology,
  1449. });
  1450. // Barriers order the lanes' LDS accesses; the console's
  1451. // allocation request needs them too, but the host does not. One
  1452. // lane sends that request, and what it dominates (the path for
  1453. // counts out of range) runs in that lane alone, so its barrier
  1454. // would hang the host.
  1455. let order = crate::ir::reverse_postorder(&p.blocks);
  1456. let mut index = vec![usize::MAX; p.blocks.len()];
  1457. for (n, &b) in order.iter().enumerate() {
  1458. index[b] = n;
  1459. }
  1460. let idom = crate::ir::idoms(&p.blocks, &order, &index);
  1461. let alloc: Vec<usize> = (0..p.blocks.len())
  1462. .filter(|&b| {
  1463. p.blocks[b].insts.iter().any(|i| {
  1464. i.name() == "s_sendmsg"
  1465. && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == GS_ALLOC_REQ)
  1466. })
  1467. })
  1468. .collect();
  1469. for &b in &order {
  1470. let mut d = b;
  1471. let dominated = loop {
  1472. if alloc.contains(&d) {
  1473. break true;
  1474. }
  1475. if idom[d] == d || idom[d] == usize::MAX {
  1476. break false;
  1477. }
  1478. d = idom[d];
  1479. };
  1480. if ms.lds_bytes == 0 || dominated {
  1481. no_barrier.insert(b);
  1482. }
  1483. }
  1484. }
  1485. Lower {
  1486. s,
  1487. x,
  1488. bad,
  1489. lane_fail: HashMap::new(),
  1490. vals: HashMap::new(),
  1491. floats: HashMap::new(),
  1492. block: vec![None; p.blocks.len()],
  1493. cur: 0,
  1494. bools: HashMap::new(),
  1495. lane_bits: HashMap::new(),
  1496. phi_at,
  1497. mask_phis: HashMap::new(),
  1498. pending_masks: Vec::new(),
  1499. data_phis: Vec::new(),
  1500. read_phis: HashSet::new(),
  1501. stale: HashSet::new(),
  1502. coherent: HashSet::new(),
  1503. ordered: if x.native.stage == HwStage::Ps {
  1504. ordered_section(p)
  1505. } else {
  1506. HashSet::new()
  1507. },
  1508. params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(),
  1509. user_data: None,
  1510. user_reads: BTreeMap::new(),
  1511. samplers: Vec::new(),
  1512. descriptors: x
  1513. .res
  1514. .descriptors
  1515. .iter()
  1516. .map(|d| ((d.site, d.role == Role::Sampler), &d.source))
  1517. .collect(),
  1518. scalar: x.res.scalar.iter().copied().collect(),
  1519. exports: x.io.exports.iter().map(|e| (e.site, e)).collect(),
  1520. interps: {
  1521. let mut m: HashMap<Site, &Interp> = x.io.interps.iter().map(|(s, i)| (*s, i)).collect();
  1522. // A first half whose result is also read as data (an f16 second half keeps
  1523. // the other half of its dst, PS_DeferredTextured): evaluated as the pair it
  1524. // starts. Approximate for those other bits (P0 + i P10 on the console); a
  1525. // first half only the second half reads is gone before lowering.
  1526. if std::env::var_os("VICTORY_FIRST_HALF").is_none_or(|v| v != "0") {
  1527. for (_, i) in &x.io.interps {
  1528. if let Interp::Interpolated { first, .. } = i {
  1529. for s in first {
  1530. m.entry(*s).or_insert(i);
  1531. }
  1532. }
  1533. }
  1534. }
  1535. m
  1536. },
  1537. handles: HashMap::new(),
  1538. strides: HashMap::new(),
  1539. edges: HashMap::new(),
  1540. exported: vec![false; p.blocks.len()],
  1541. rpo: vec![usize::MAX; p.blocks.len()],
  1542. tail: vec![None; p.blocks.len()],
  1543. writes_uavs,
  1544. src0: None,
  1545. console_lanes,
  1546. split_lds,
  1547. lds_meet,
  1548. local: exchange.is_some() && LOCAL_WAVES.get(),
  1549. local_ok: false,
  1550. local_any: LOCAL_ANY.get(),
  1551. uniform: match &exchange {
  1552. Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all),
  1553. _ => HashSet::new(),
  1554. },
  1555. own_bits: match &exchange {
  1556. Some((_, false, _)) if !LOCAL_WAVES.get() && own_bits_on() => {
  1557. super::own_bits::find(p, x.st, std::env::var_os("VICTORY_WAVE_WHY").is_some())
  1558. }
  1559. _ => Default::default(),
  1560. },
  1561. exchange,
  1562. clane: None,
  1563. pair: None,
  1564. halves,
  1565. wave_base: None,
  1566. flat: None,
  1567. no_barrier,
  1568. fence_only,
  1569. half_outputs: half_outputs(&x.native.io, &x.outputs),
  1570. mask_data: match x.native.stage {
  1571. HwStage::Cs => MaskData::Console,
  1572. HwStage::Ps | HwStage::Vs => MaskData::Host,
  1573. _ => MaskData::None,
  1574. },
  1575. mask_ok: false,
  1576. ballots: HashMap::new(),
  1577. balloting: HashSet::new(),
  1578. def_block: p
  1579. .blocks
  1580. .iter()
  1581. .enumerate()
  1582. .flat_map(|(b, block)| {
  1583. block
  1584. .insts
  1585. .iter()
  1586. .flat_map(move |i| i.writes.iter().map(move |w| (w.1, b)))
  1587. .chain(block.phis.iter().map(move |phi| (phi.value, b)))
  1588. })
  1589. .collect(),
  1590. cur_ir: 0,
  1591. sections: HashMap::new(),
  1592. section_out: HashSet::new(),
  1593. code_table: None,
  1594. counters: HashMap::new(),
  1595. abort: None,
  1596. }
  1597. }
  1598. /// The dword of the program's code at byte `byte` (a constant table
  1599. /// the compiler appends to the code), as an internal constant array.
  1600. // shortcut: an index outside the table reads its last dword (the
  1601. // console would read whatever memory follows the code).
  1602. fn code_dword(&mut self, byte: V) -> Result<V, Why> {
  1603. let (g, base, len) = match self.code_table {
  1604. Some(t) => t,
  1605. None => {
  1606. let first = self
  1607. .x
  1608. .res
  1609. .scalar
  1610. .iter()
  1611. .map(|s| s.1)
  1612. .chain(self.x.res.descriptors.iter().flat_map(|d| {
  1613. d.source.leaves().into_iter().filter_map(|l| match l {
  1614. Source::Built { address, .. } => Some(*address),
  1615. _ => None,
  1616. })
  1617. }))
  1618. .filter(|a| a.param == CODE)
  1619. .map(|a| a.offset & !3)
  1620. .min()
  1621. .ok_or("a code table")?;
  1622. let code = &self.x.native.code;
  1623. let words: Vec<u32> = code
  1624. .get(first as usize..)
  1625. .ok_or("a code table past the code")?
  1626. .chunks(4)
  1627. .map(|c| {
  1628. let mut w = [0u8; 4];
  1629. w[..c.len()].copy_from_slice(c);
  1630. u32::from_le_bytes(w)
  1631. })
  1632. .collect();
  1633. if words.is_empty() {
  1634. return Err("a code table past the code");
  1635. }
  1636. let elems: Vec<V> = words.iter().map(|&w| self.s.m.i32(w)).collect();
  1637. let arr = self.s.m.array(words.len() as u32, self.s.t.i32);
  1638. let init = self.s.m.aggregate(arr, &elems);
  1639. let g = self.s.m.constant_global("code", init);
  1640. let t = (g, first, words.len() as u32);
  1641. self.code_table = Some(t);
  1642. t
  1643. }
  1644. };
  1645. let c = self.cur;
  1646. let k = self.s.m.i32(base);
  1647. let rel = self.s.m.bin(c, Bin::Sub, byte, k);
  1648. let two = self.s.m.i32(2);
  1649. let index = self.s.m.bin(c, Bin::LShr, rel, two);
  1650. let last = self.s.m.i32(len - 1);
  1651. let over = self.s.m.cmp(c, pred::IUGT, index, last);
  1652. let index = self.s.m.select(c, over, last, index);
  1653. let at = self.s.m.element(c, g, index);
  1654. Ok(self.s.m.load(c, at))
  1655. }
  1656. /// A global memory load (`global_load_*`): from the program's constant
  1657. /// table, or from a root SRV at the address the title sets.
  1658. fn flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  1659. let Fields::Flat { dst, .. } = &inst.fields else {
  1660. unreachable!()
  1661. };
  1662. let name = inst.name();
  1663. if self.scalar.get(&(b, i)).is_some_and(|a| a.param == MEMORY) {
  1664. return self.memory_flat(inst, b, i);
  1665. }
  1666. let rest = name
  1667. .strip_prefix("global_load_")
  1668. .ok_or("a global memory write")?;
  1669. let (n, sub) = match rest {
  1670. "dword" => (1, None),
  1671. "dwordx2" => (2, None),
  1672. "dwordx3" => (3, None),
  1673. "dwordx4" => (4, None),
  1674. "ubyte" => (1, Some((8, false))),
  1675. "sbyte" => (1, Some((8, true))),
  1676. "ushort" => (1, Some((16, false))),
  1677. "sshort" => (1, Some((16, true))),
  1678. _ => return Err(name),
  1679. };
  1680. let a = *self
  1681. .scalar
  1682. .get(&(b, i))
  1683. .ok_or("an untracked global address")?;
  1684. let guard = self.guard(b, i)?;
  1685. let Some(Operand::Vector { reg, .. }) = *dst else {
  1686. return Err("a global load result");
  1687. };
  1688. let c = self.cur;
  1689. let mut off = self.s.m.i32(a.offset);
  1690. if let Some(d) = a.dynamic {
  1691. let d = self.i32_of(d)?;
  1692. off = self.s.m.bin(c, Bin::Add, off, d);
  1693. }
  1694. let h = if a.param == CODE {
  1695. None
  1696. } else {
  1697. let src = Source::Built {
  1698. address: a,
  1699. bits: 0,
  1700. words: [0, 0],
  1701. };
  1702. if let Some(bias) = self.root_bias(a.param) {
  1703. off = self.s.m.bin(c, Bin::Add, off, bias);
  1704. }
  1705. Some(self.handle((b, i), &src, false, (11, 0))?)
  1706. };
  1707. let dword = |l: &mut Self, byte: V| -> Result<V, Why> {
  1708. match h {
  1709. None => l.code_dword(byte),
  1710. Some(h) => {
  1711. let c = l.cur;
  1712. let (u, mask, al) = (l.s.m.undef(l.s.t.i32), l.s.m.i8(1), l.s.m.i32(4));
  1713. let r = l.s.op(
  1714. c,
  1715. "rawBufferLoad.f32",
  1716. Attr::ReadOnly,
  1717. l.s.t.res_ret,
  1718. 139,
  1719. &[h, byte, u, mask, al],
  1720. );
  1721. let x = l.s.m.extract(c, r, 0);
  1722. Ok(l.as_int(x))
  1723. }
  1724. }
  1725. };
  1726. for k in 0..n {
  1727. let x = match sub {
  1728. None => {
  1729. let four = self.s.m.i32(4 * k);
  1730. let at = self.s.m.bin(c, Bin::Add, off, four);
  1731. dword(self, at)?
  1732. }
  1733. Some((width, signed)) => {
  1734. // shortcut: the field is taken not to cross a dword.
  1735. let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3));
  1736. let at = self.s.m.bin(c, Bin::And, off, not3);
  1737. let w = dword(self, at)?;
  1738. let byte = self.s.m.bin(c, Bin::And, off, three);
  1739. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  1740. let x = self.s.m.bin(c, Bin::LShr, w, sh);
  1741. let left = self.s.m.i32(32 - width);
  1742. let x = self.s.m.bin(c, Bin::Shl, x, left);
  1743. self.s
  1744. .m
  1745. .bin(c, if signed { Bin::AShr } else { Bin::LShr }, x, left)
  1746. }
  1747. };
  1748. self.write(inst, Reg::V(reg + k as u8), x, guard);
  1749. }
  1750. Ok(())
  1751. }
  1752. /// Finds the whole-wave sections and the values they leave.
  1753. fn find_sections(&mut self) {
  1754. let p = self.x.p;
  1755. let mut inside: HashMap<Value, (usize, usize, usize)> = HashMap::new();
  1756. for b in 0..p.blocks.len() {
  1757. let found = super::wave::sections(p, b);
  1758. for (&start, sec) in &found {
  1759. for i in start + 1..sec.end {
  1760. for &(_, w) in &p.blocks[b].insts[i].writes {
  1761. inside.insert(w, (b, start, sec.end));
  1762. }
  1763. }
  1764. }
  1765. if !found.is_empty() {
  1766. self.sections.insert(b, found);
  1767. }
  1768. }
  1769. if inside.is_empty() {
  1770. return;
  1771. }
  1772. for (b, block) in p.blocks.iter().enumerate() {
  1773. for phi in &block.phis {
  1774. self.section_out
  1775. .extend(phi.args.iter().filter(|a| inside.contains_key(a)));
  1776. }
  1777. for (i, inst) in block.insts.iter().enumerate() {
  1778. for &(_, r) in &inst.reads {
  1779. if let Some(&(sb, start, end)) = inside.get(&r)
  1780. && !(sb == b && i > start && i < end)
  1781. {
  1782. self.section_out.insert(r);
  1783. }
  1784. }
  1785. }
  1786. }
  1787. }
  1788. /// An instruction inside a whole-wave section: the values that leave
  1789. /// the section are made from what the simulation found them to be.
  1790. fn section_inst(&mut self, b: usize, i: usize, start: usize) {
  1791. const UNKNOWN: Why = "a whole-wave section step the simulation does not follow";
  1792. let inst = &self.x.p.blocks[b].insts[i];
  1793. for &(_, w) in &inst.writes {
  1794. let val = if self.section_out.contains(&w) {
  1795. let shape = self.sections[&b][&start].shapes.get(&w).copied();
  1796. let own = self.own_bits.totals.contains(&w);
  1797. match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh, own)) {
  1798. Ok(x) => Val::I32(x),
  1799. Err(why) => Val::Missing(why),
  1800. }
  1801. } else {
  1802. Val::Missing(UNKNOWN)
  1803. };
  1804. self.vals.insert(w, val);
  1805. }
  1806. }
  1807. /// A value a whole-wave section leaves, as DXIL wave operations over the
  1808. /// host's active lanes: the console's result with console lanes; on
  1809. /// another wave size, what the HLSL wave operation the console compiler
  1810. /// expanded gives on that wave.
  1811. ///
  1812. /// `own`: a wave OR that only steers a loop over each lane's own bits
  1813. /// ([`super::own_bits`]); where two host waves cannot exchange their halves' ORs it is
  1814. /// this host wave's.
  1815. fn shape(&mut self, shape: super::wave::Shape, own: bool) -> Result<V, Why> {
  1816. use super::wave::{Op, Shape};
  1817. let (op, src, mask, ident, prefix) = match shape {
  1818. Shape::K(k) => return Ok(self.s.m.i32(k)),
  1819. Shape::Value(v) => return self.i32_of(v),
  1820. Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None),
  1821. Shape::ActiveF64(lo, hi, mask, high) => {
  1822. return self.active_f64_sum(lo, hi, mask, high);
  1823. }
  1824. Shape::Masked(src, mask, ident) => {
  1825. let c = self.cur;
  1826. let &m = self
  1827. .x
  1828. .st
  1829. .masks
  1830. .get(&mask)
  1831. .ok_or("a wave reduction's untracked mask")?;
  1832. let on = self.boolean(m, c)?;
  1833. let x = self.i32_of(src)?;
  1834. let id = self.s.m.i32(ident);
  1835. return Ok(self.s.m.select(c, on, x, id));
  1836. }
  1837. Shape::Prefix(op, src, mask, ident, inclusive) => {
  1838. (op, src, mask, ident, Some(inclusive))
  1839. }
  1840. };
  1841. // Mesh: no host wave size can be declared, so a reduction is over this host wave
  1842. // only. A minimum or maximum is taken that way: the compiler's "next distinct
  1843. // value" loop (the wave's minimum, then the lanes that hold it) serves every
  1844. // lane however the lanes are divided into waves. A sum, a bit reduction or a
  1845. // prefix would be of part of a console wave: still refused.
  1846. if self.mask_data == MaskData::None
  1847. && (prefix.is_some()
  1848. || !matches!(
  1849. op,
  1850. Op::MinU | Op::MaxU | Op::MinI | Op::MaxI | Op::MinF | Op::MaxF
  1851. ))
  1852. {
  1853. return Err("a wave reduction in a mesh shader");
  1854. }
  1855. let c = self.cur;
  1856. let &m = self
  1857. .x
  1858. .st
  1859. .masks
  1860. .get(&mask)
  1861. .ok_or("a wave reduction's untracked mask")?;
  1862. let on = self.boolean(m, c)?;
  1863. let x = self.i32_of(src)?;
  1864. let id = self.s.m.i32(ident);
  1865. let x = self.s.m.select(c, on, x, id);
  1866. self.s.flags |= flags::WAVE_OPS;
  1867. if op == Op::AddH {
  1868. return match prefix {
  1869. Some(_) => Err("a wave prefix of an operation other than a sum"),
  1870. None => self.half_sum(x),
  1871. };
  1872. }
  1873. let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF);
  1874. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  1875. let arg = if float { self.as_float(x) } else { x };
  1876. let ty = if float { f32t } else { i32t };
  1877. let sfx = if float { "f32" } else { "i32" };
  1878. let r = match (op, prefix) {
  1879. (Op::AddU | Op::AddF, Some(inclusive)) => {
  1880. let (k0, k1) = (self.s.m.i8(0), self.s.m.i8(1));
  1881. let r = self.s.op(
  1882. c,
  1883. &format!("wavePrefixOp.{sfx}"),
  1884. Attr::NoUnwind,
  1885. ty,
  1886. 121,
  1887. &[arg, k0, k1],
  1888. );
  1889. if inclusive {
  1890. self.s.m.bin(c, Bin::Add, r, arg)
  1891. } else {
  1892. r
  1893. }
  1894. }
  1895. (_, Some(_)) => return Err("a wave prefix of an operation other than a sum"),
  1896. (Op::Or | Op::And | Op::Xor, None) => {
  1897. let k = self.s.m.i8(match op {
  1898. Op::And => 0,
  1899. Op::Or => 1,
  1900. _ => 2,
  1901. });
  1902. self.s
  1903. .op(c, "waveActiveBit.i32", Attr::NoUnwind, i32t, 120, &[arg, k])
  1904. }
  1905. (_, None) => {
  1906. let (code, unsigned) = match op {
  1907. Op::AddU => (0, 1),
  1908. Op::AddF => (0, 0),
  1909. Op::MinU => (2, 1),
  1910. Op::MaxU => (3, 1),
  1911. Op::MinI | Op::MinF => (2, 0),
  1912. _ => (3, 0),
  1913. };
  1914. let (k, u) = (self.s.m.i8(code), self.s.m.i8(unsigned));
  1915. self.s.op(
  1916. c,
  1917. &format!("waveActiveOp.{sfx}"),
  1918. Attr::NoUnwind,
  1919. ty,
  1920. 119,
  1921. &[arg, k, u],
  1922. )
  1923. }
  1924. };
  1925. // two host waves of 32 hold the console's 64 lanes: their results combine
  1926. let r = if self.local || self.exchange.as_ref().is_some_and(|e| e.1) {
  1927. // this host wave's own result (and prefix): each wave on its own, or a group of
  1928. // 32 threads or fewer, which one host wave holds whole (combining with the 0 a
  1929. // missing half "gives" broke AND, MIN and signed MAX)
  1930. r
  1931. } else if own && prefix.is_none() && op == Op::Or && !self.all_lanes(self.cur_ir) {
  1932. // each thread walks the bits of this value and works only at its own, which the
  1933. // host wave's OR holds: the same run as with the console wave's OR
  1934. r
  1935. } else if self.exchange.is_some() {
  1936. if !self.all_lanes(self.cur_ir) {
  1937. need(self.cur_ir);
  1938. return Err("a wave reduction where not every lane runs");
  1939. }
  1940. let bits = |l: &mut Self, v: V| if float { l.as_int(v) } else { v };
  1941. let back = |l: &mut Self, v: V| if float { l.as_float(v) } else { v };
  1942. match prefix {
  1943. Some(_) => {
  1944. // the upper half adds the lower half's total to its prefix
  1945. let (k0, ku) = (self.s.m.i8(0), self.s.m.i8(u8::from(!float)));
  1946. let total = self.s.op(c, &format!("waveActiveOp.{sfx}"), Attr::NoUnwind, ty, 119, &[arg, k0, ku]);
  1947. let tb = bits(self, total);
  1948. let c = self.cur;
  1949. let (lo, _) = self.exchange_halves(c, tb);
  1950. let lo = back(self, lo);
  1951. let cl = self.console_lane();
  1952. let k32 = self.s.m.i32(32);
  1953. let upper = self.s.m.cmp(c, pred::IUGE, cl, k32);
  1954. let zero = if float { self.s.m.f32(0) } else { self.s.m.i32(0) };
  1955. let add = self.s.m.select(c, upper, lo, zero);
  1956. self.s.m.bin(c, Bin::Add, r, add)
  1957. }
  1958. None => {
  1959. let rb = bits(self, r);
  1960. let c = self.cur;
  1961. let (lo, hi) = self.exchange_halves(c, rb);
  1962. let (lo, hi) = (back(self, lo), back(self, hi));
  1963. match op {
  1964. Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, lo, hi),
  1965. Op::Or => self.s.m.bin(c, Bin::Or, lo, hi),
  1966. Op::And => self.s.m.bin(c, Bin::And, lo, hi),
  1967. Op::Xor => self.s.m.bin(c, Bin::Xor, lo, hi),
  1968. _ => {
  1969. // FMax 35, FMin 36, IMax 37, IMin 38, UMax 39, UMin 40
  1970. let code = match op {
  1971. Op::MaxF => 35,
  1972. Op::MinF => 36,
  1973. Op::MinU => 40,
  1974. Op::MaxU => 39,
  1975. Op::MinI => 38,
  1976. _ => 37,
  1977. };
  1978. self.s.op(c, &format!("binary.{sfx}"), Attr::ReadNone, ty, code, &[lo, hi])
  1979. }
  1980. }
  1981. }
  1982. }
  1983. } else {
  1984. r
  1985. };
  1986. Ok(if float { self.as_int(r) } else { r })
  1987. }
  1988. /// `WaveActiveSum` of 64-bit floats (`f64(lo, hi)` in active lanes, `+0.0` elsewhere),
  1989. /// returning the low (`!high`) or high (`high`) 32-bit word.
  1990. fn active_f64_sum(
  1991. &mut self,
  1992. lo: Value,
  1993. hi: Value,
  1994. mask: Value,
  1995. high: bool,
  1996. ) -> Result<V, Why> {
  1997. if self.mask_data == MaskData::None {
  1998. return Err("a wave reduction in a mesh shader");
  1999. }
  2000. let c = self.cur;
  2001. let &m = self
  2002. .x
  2003. .st
  2004. .masks
  2005. .get(&mask)
  2006. .ok_or("a wave reduction's untracked mask")?;
  2007. let on = self.boolean(m, c)?;
  2008. let lo = self.i32_of(lo)?;
  2009. let hi = self.i32_of(hi)?;
  2010. let z = self.s.m.i32(0);
  2011. let lo = self.s.m.select(c, on, lo, z);
  2012. let hi = self.s.m.select(c, on, hi, z);
  2013. self.s.flags |= flags::WAVE_OPS | flags::DOUBLES;
  2014. let f64t = self.s.m.double();
  2015. let i32t = self.s.t.i32;
  2016. let split_ty = self
  2017. .s
  2018. .m
  2019. .named_struct("dx.types.splitdouble", vec![i32t, i32t]);
  2020. let arg = self
  2021. .s
  2022. .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]);
  2023. let (k0, k0b) = (self.s.m.i8(0), self.s.m.i8(0));
  2024. let sum = self
  2025. .s
  2026. .op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[arg, k0, k0b]);
  2027. let split = self
  2028. .s
  2029. .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[sum]);
  2030. let mut r_lo = self.s.m.extract(c, split, 0);
  2031. let mut r_hi = self.s.m.extract(c, split, 1);
  2032. if self.exchange.is_some() {
  2033. if !self.all_lanes(self.cur_ir) {
  2034. need(self.cur_ir);
  2035. return Err("a wave reduction where not every lane runs");
  2036. }
  2037. let (lo0, lo1) = self.exchange_halves(self.cur, r_lo);
  2038. let (hi0, hi1) = self.exchange_halves(self.cur, r_hi);
  2039. let c = self.cur;
  2040. let d0 = self
  2041. .s
  2042. .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo0, hi0]);
  2043. let d1 = self
  2044. .s
  2045. .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo1, hi1]);
  2046. let total = self.s.m.bin(c, Bin::Add, d0, d1);
  2047. let split = self
  2048. .s
  2049. .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[total]);
  2050. r_lo = self.s.m.extract(c, split, 0);
  2051. r_hi = self.s.m.extract(c, split, 1);
  2052. }
  2053. Ok(if high { r_hi } else { r_lo })
  2054. }
  2055. /// The sum of two 16-bit floats (the low halves of `a` and `b`) as the console's
  2056. /// `v_add_f16` gives it: added in f32 and rounded to 16 bits, to nearest
  2057. /// ([`Self::f16_nearest`]).
  2058. fn add_halves(&mut self, a: V, b: V) -> V {
  2059. let c = self.cur;
  2060. let f32t = self.s.t.f32;
  2061. let low = self.s.m.i32(0xFFFF);
  2062. let wide = |l: &mut Self, x: V| {
  2063. let h = l.s.m.bin(c, Bin::And, x, low);
  2064. l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h])
  2065. };
  2066. let (fa, fb) = (wide(self, a), wide(self, b));
  2067. let f = self.s.m.bin(c, Bin::Add, fa, fb);
  2068. self.f16_nearest(f)
  2069. }
  2070. /// `WaveActiveSum` of 16-bit floats (`x`: each lane's term in its low half, +0 in the
  2071. /// lanes outside the mask), bit for bit as the console adds it: every addition rounds to
  2072. /// 16 bits, so the order counts, and the compiler's is the balanced tree over the lanes
  2073. /// in their order (lanes 2k and 2k+1, then pairs, ... then the wave's two halves;
  2074. /// [`super::wave::buddies`]). Each lane adds its partner's partial sum, read from the
  2075. /// lane whose number differs in one bit, step by step; two host waves of 32 then exchange
  2076. /// their halves' sums for the last addition. The high half of the result is lane 0's,
  2077. /// which no `v_add_f16` writes.
  2078. /// On a host wave of 64 lanes where not every lane runs, the lanes that are elsewhere
  2079. /// count as the console's do (it masks them to +0): a partner's partial sum is read from
  2080. /// the first lane there is of the partner's run of lanes, and is +0 without one. Two host
  2081. /// waves of 32 can only exchange where every lane runs: refused elsewhere, in a thread
  2082. /// group that does not fill its waves, and for each half-wave on its own (half a sum is
  2083. /// no sum).
  2084. fn half_sum(&mut self, x: V) -> Result<V, Why> {
  2085. const WHERE: Why = "a wave sum of 16-bit floats where not every lane runs";
  2086. let threads = self.s.threads.ok_or("a wave sum of 16-bit floats outside compute")?;
  2087. if threads.iter().product::<u32>() % 64 != 0 {
  2088. return Err("a wave sum of 16-bit floats in a wave that is not full");
  2089. }
  2090. if self.local {
  2091. return Err("a wave sum of 16-bit floats in a half-wave");
  2092. }
  2093. // two host waves of 32 that exchange, or one host wave of 64 lanes
  2094. let halves = match (&self.exchange, self.s.wave_size) {
  2095. (Some((_, false, _)), _) => true,
  2096. (None, Some(64)) if self.x.p.wave64 => false,
  2097. _ => return Err("a wave sum of 16-bit floats on these waves"),
  2098. };
  2099. let every = if halves {
  2100. self.all_lanes(self.cur_ir)
  2101. } else {
  2102. all_lane_blocks(self.x.st).is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false))
  2103. };
  2104. if !every && halves {
  2105. need(self.cur_ir);
  2106. return Err(WHERE);
  2107. }
  2108. let c = self.cur;
  2109. let i32t = self.s.t.i32;
  2110. let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  2111. let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0));
  2112. // the lanes that are here, when not all are
  2113. let here = (!every).then(|| {
  2114. self.s.flags |= flags::WAVE_OPS;
  2115. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  2116. let yes = self.s.m.bool(true);
  2117. let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[yes]);
  2118. (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1))
  2119. });
  2120. // `v` of the first lane here of the `n` (a power of two) lanes from `base`: +0 of none
  2121. let first_of = |l: &mut Self, v: V, base: V, n: u32| {
  2122. let Some((lo, hi)) = here else {
  2123. return l.read_lane(v, base);
  2124. };
  2125. let (k31, k32) = (l.s.m.i32(31), l.s.m.i32(32));
  2126. let lower = l.s.m.cmp(c, pred::IULT, base, k32);
  2127. let word = l.s.m.select(c, lower, lo, hi);
  2128. let shift = l.s.m.bin(c, Bin::And, base, k31);
  2129. let word = l.s.m.bin(c, Bin::LShr, word, shift);
  2130. let run = l.s.m.i32(u32::MAX >> (32 - n));
  2131. let word = l.s.m.bin(c, Bin::And, word, run);
  2132. let any = l.s.m.cmp(c, pred::NE, word, zero);
  2133. let nth = l.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[word]);
  2134. let from = l.s.m.bin(c, Bin::Add, base, nth);
  2135. // (no lane there: this one, which is here; the read is not used)
  2136. let from = l.s.m.select(c, any, from, lane);
  2137. let got = l.read_lane(v, from);
  2138. l.s.m.select(c, any, got, zero)
  2139. };
  2140. let mut sum = x;
  2141. for step in 0..if halves { 5 } else { 6 } {
  2142. let bit = self.s.m.i32(1 << step);
  2143. let mut partner = self.s.m.bin(c, Bin::Xor, lane, bit);
  2144. if !every {
  2145. let run = self.s.m.i32(!((1 << step) - 1));
  2146. partner = self.s.m.bin(c, Bin::And, partner, run);
  2147. }
  2148. let theirs = first_of(self, sum, partner, 1 << step);
  2149. sum = self.add_halves(sum, theirs);
  2150. }
  2151. let first = first_of(self, x, zero, 1);
  2152. let first = self.s.m.bin(c, Bin::And, first, high);
  2153. let sum = self.s.m.bin(c, Bin::And, sum, low);
  2154. let mine = self.s.m.bin(c, Bin::Or, first, sum);
  2155. if !halves {
  2156. return Ok(mine);
  2157. }
  2158. let (lo, hi) = self.exchange_halves(c, mine);
  2159. let c = self.cur;
  2160. let total = self.add_halves(lo, hi);
  2161. let total = self.s.m.bin(c, Bin::And, total, low);
  2162. let first = self.s.m.bin(c, Bin::And, lo, high);
  2163. Ok(self.s.m.bin(c, Bin::Or, first, total))
  2164. }
  2165. fn run(mut self) -> Result<Lowered, Stop> {
  2166. let p = self.x.p;
  2167. self.find_coherent();
  2168. let order = crate::ir::reverse_postorder(&p.blocks);
  2169. for (n, &b) in order.iter().enumerate() {
  2170. self.rpo[b] = n;
  2171. }
  2172. for (n, &b) in order.iter().enumerate() {
  2173. self.block[b] = Some(if n == 0 {
  2174. self.s.entry
  2175. } else {
  2176. self.s.m.new_block()
  2177. });
  2178. }
  2179. // Loop headers count iterations (`LOOP_LIMIT`).
  2180. for &b in &order {
  2181. let header = p.blocks[b]
  2182. .preds
  2183. .iter()
  2184. .any(|&q| self.block[q].is_some() && self.rpo[b] <= self.rpo[q]);
  2185. if header {
  2186. let blk = self.block[b].expect("reachable");
  2187. let phi = self.s.m.phi(blk, self.s.t.i32);
  2188. self.counters.insert(b, (phi, Vec::new()));
  2189. }
  2190. }
  2191. self.cur = self.s.entry;
  2192. self.find_sections();
  2193. self.inputs()?;
  2194. if let Some(mesh) = self.s.mesh {
  2195. self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?;
  2196. self.block[order[0]] = Some(self.cur);
  2197. }
  2198. for &b in &order {
  2199. self.cur = self.block[b].expect("reachable");
  2200. self.cur_ir = b;
  2201. let preds: Vec<usize> = p.blocks[b]
  2202. .preds
  2203. .iter()
  2204. .copied()
  2205. .filter(|&q| self.block[q].is_some())
  2206. .collect();
  2207. self.exported[b] = !preds.is_empty() && preds.iter().all(|&q| self.exported_out(q));
  2208. for (i, phi) in p.blocks[b].phis.iter().enumerate() {
  2209. let val = match phi.reg {
  2210. Reg::S(c) if c == EXEC || c == EXEC + 1 => Val::Missing("a lane mask"),
  2211. _ if self.bad.contains_key(&phi.value) => Val::Missing(self.bad[&phi.value]),
  2212. Reg::Scc => {
  2213. let v = self.s.m.phi(self.cur, self.s.t.i1);
  2214. self.data_phis.push((v, b, i));
  2215. Val::Bit(v)
  2216. }
  2217. _ => {
  2218. let v = self.s.m.phi(self.cur, self.s.t.i32);
  2219. self.data_phis.push((v, b, i));
  2220. Val::I32(v)
  2221. }
  2222. };
  2223. self.vals.insert(phi.value, val);
  2224. }
  2225. if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].0) {
  2226. self.lds_meeting();
  2227. }
  2228. let mut i = 0;
  2229. while i < p.blocks[b].insts.len() {
  2230. self.inst(b, i)?;
  2231. if let Some(end) = self.sections.get(&b).and_then(|s| s.get(&i)).map(|s| s.end) {
  2232. for j in i + 1..end {
  2233. self.section_inst(b, j, i);
  2234. }
  2235. i = end;
  2236. continue;
  2237. }
  2238. i += 1;
  2239. }
  2240. self.mask_ok = self.mask_data == MaskData::Console;
  2241. if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].1) {
  2242. self.lds_meeting();
  2243. }
  2244. self.tail[b] = Some(self.cur);
  2245. self.exit(b)?;
  2246. }
  2247. self.fill_phis()?;
  2248. let user_data = self.user_reads.values().copied().collect();
  2249. self.s.samplers = self.samplers.len() as u32;
  2250. let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect();
  2251. let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect();
  2252. let root_uavs = self.s.root_uavs.iter().map(|r| r.0).collect();
  2253. let cmp_samplers = self.s.cmp_samplers;
  2254. let wave_size = self.s.wave_size;
  2255. Ok(Lowered {
  2256. wave_size,
  2257. cmp_samplers,
  2258. root_cbvs,
  2259. root_srvs,
  2260. root_uavs,
  2261. #[cfg(test)]
  2262. nonuniform_handles: self.s.nonuniform_handles,
  2263. #[cfg(test)]
  2264. wave_ops: self.s.flags & flags::WAVE_OPS != 0,
  2265. dxil: self.s.finish(),
  2266. user_data,
  2267. samplers: self.samplers,
  2268. })
  2269. }
  2270. fn exported_out(&self, b: usize) -> bool {
  2271. self.exported[b] || self.has_done_export(b)
  2272. }
  2273. fn has_done_export(&self, b: usize) -> bool {
  2274. (0..self.x.p.blocks[b].insts.len())
  2275. .any(|i| self.exports.get(&(b, i)).is_some_and(|e| e.done))
  2276. }
  2277. /// Values of the program's input registers.
  2278. fn inputs(&mut self) -> Result<(), Stop> {
  2279. let io_inputs: HashMap<Value, Input> = self.x.io.inputs.iter().copied().collect();
  2280. for &(reg, v) in &self.x.p.inputs {
  2281. let val = match reg {
  2282. Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use
  2283. // Most programs only interpolate with them: loaded on first
  2284. // use as a value (`get`).
  2285. Reg::V(_) if matches!(io_inputs.get(&v), Some(Input::Barycentric { .. })) => {
  2286. continue;
  2287. }
  2288. Reg::S(n) => match io_inputs.get(&v) {
  2289. Some(&input) => self.input(input),
  2290. // Above the SGPRs the hardware initializes, a register
  2291. // holds what the last wave left, so no program depends
  2292. // on it: a read the paths only seem to allow (a branch
  2293. // past the write, taken only with one past the read)
  2294. // reads zero, as VGPRs do.
  2295. None if n <= 105 && self.x.io.initialized_sgprs.is_some_and(|k| n >= k) => {
  2296. Val::I32(self.s.m.i32(0))
  2297. }
  2298. // A scalar parked in a VGPR lane (`ir::unspill`), read where the
  2299. // paths only seem to allow it before any save: the lane of a VGPR
  2300. // nobody wrote, and VGPRs nobody set read as zero.
  2301. None if n >= crate::ir::PARKED => Val::I32(self.s.m.i32(0)),
  2302. // No wave overlaps this one (see `ordered_section`).
  2303. None if self.pops_collision(v) => Val::I32(self.s.m.i32(0)),
  2304. None => Val::Missing("a hardware SGPR input"),
  2305. },
  2306. Reg::Scc => Val::Missing("SCC on entry"),
  2307. Reg::V(_) => match io_inputs.get(&v) {
  2308. Some(&input) => self.input(input),
  2309. // Registers no one set read as zero (the validator
  2310. // refuses reads of undef).
  2311. None => Val::I32(self.s.m.i32(0)),
  2312. },
  2313. };
  2314. self.vals.insert(v, val);
  2315. }
  2316. Ok(())
  2317. }
  2318. /// Whether the input SGPR `v` is the POPS collision wave id: a program
  2319. /// with an ordered section only takes its fields apart (bit 31 says
  2320. /// that the wave overlaps another, the others which packer and waves).
  2321. fn pops_collision(&self, v: Value) -> bool {
  2322. if self.ordered.is_empty() {
  2323. return false;
  2324. }
  2325. let mut packer = false;
  2326. for block in &self.x.p.blocks {
  2327. if block.phis.iter().any(|p| p.args.contains(&v)) {
  2328. return false;
  2329. }
  2330. for i in &block.insts {
  2331. if !i.reads.iter().any(|r| r.1 == v) {
  2332. continue;
  2333. }
  2334. let Fields::Sop { src, .. } = &i.fields else {
  2335. return false;
  2336. };
  2337. match (i.name(), src.get(1)) {
  2338. // bits 28 and 29: the packer
  2339. ("s_bfe_u32", Some(Operand::Literal(0x0002_001C))) => packer = true,
  2340. ("s_bfe_u32" | "s_lshr_b32", _) => {}
  2341. _ => return false,
  2342. }
  2343. }
  2344. }
  2345. packer
  2346. }
  2347. fn input(&mut self, input: Input) -> Val {
  2348. let (kind, col) = match input {
  2349. Input::VertexId => (1, 0),
  2350. Input::InstanceId => (2, 0),
  2351. Input::Position(c) => (3, c),
  2352. Input::Attribute { row, channel } => {
  2353. return match self.find_input(row, channel) {
  2354. Some((id, col)) => self.load_input(id, col),
  2355. None => Val::Missing("a vertex input the signature lacks"),
  2356. };
  2357. }
  2358. Input::Barycentric { kind, index } => return self.barycentric(kind, index),
  2359. Input::PrimitiveId => return Val::Missing("the primitive id"),
  2360. // The console code tests it against 0 (`v_cmp_ne_u32`), as the
  2361. // host's value can be.
  2362. Input::FrontFace => (13, 0),
  2363. Input::ThreadIdInGroup(c) => return self.thread_id(c),
  2364. Input::GroupId(c) => return self.compute_id("groupId.i32", 94, c),
  2365. Input::GroupInfo => return Val::Missing("the thread-group info SGPR"),
  2366. Input::MeshGroup => {
  2367. let Val::I32(g) = self.compute_id("groupId.i32", 94, 0) else {
  2368. unreachable!()
  2369. };
  2370. let n = self.s.m.i32(self.x.mesh_stride);
  2371. return Val::I32(self.s.m.bin(self.s.entry, Bin::Mul, g, n));
  2372. }
  2373. Input::MergedWaveInfo => {
  2374. // shortcut: only the wave index (bits 24-27) is set; the
  2375. // console's other bits (lane counts) are read by no program.
  2376. let f = self.mesh_thread();
  2377. let shift = self.s.m.i32(self.wave().trailing_zeros());
  2378. let w = self.s.m.bin(self.s.entry, Bin::LShr, f, shift);
  2379. let k24 = self.s.m.i32(24);
  2380. return Val::I32(self.s.m.bin(self.s.entry, Bin::Shl, w, k24));
  2381. }
  2382. _ => return Val::Missing("a pixel system input"),
  2383. };
  2384. let free = self
  2385. .s
  2386. .inputs
  2387. .iter()
  2388. .filter_map(|e| e.row)
  2389. .map(|r| r + 1)
  2390. .max()
  2391. .unwrap_or(0);
  2392. let id = match self.s.inputs.iter().position(|e| e.kind == kind) {
  2393. Some(id) => {
  2394. if kind != 3 {
  2395. self.s.inputs[id].row.get_or_insert(free);
  2396. }
  2397. id
  2398. }
  2399. None if kind >= 3 => return Val::Missing("a pixel system input the signature lacks"),
  2400. None => {
  2401. // The console signature leaves out vertex and instance ids; PC
  2402. // gives them a row after the others.
  2403. let row = self
  2404. .s
  2405. .inputs
  2406. .iter()
  2407. .filter_map(|e| e.row)
  2408. .map(|r| r + 1)
  2409. .max()
  2410. .unwrap_or(0);
  2411. self.s.inputs.push(SigElement {
  2412. name: ["", "SV_VertexID", "SV_InstanceID"][kind as usize].into(),
  2413. index: 0,
  2414. kind,
  2415. comp: 5,
  2416. interp: 0,
  2417. row: Some(row),
  2418. col: 0,
  2419. cols: 1,
  2420. usage: 0,
  2421. half: false,
  2422. });
  2423. self.s.inputs.len() - 1
  2424. }
  2425. };
  2426. self.load_input(id, col)
  2427. }
  2428. /// A component of a compute thread or group id, read in the entry block.
  2429. fn compute_id(&mut self, name: &str, opcode: u32, c: u8) -> Val {
  2430. let (entry, c) = (self.s.entry, self.s.m.i32(u32::from(c)));
  2431. Val::I32(
  2432. self.s
  2433. .op(entry, name, Attr::ReadNone, self.s.t.i32, opcode, &[c]),
  2434. )
  2435. }
  2436. fn find_input(&self, row: u8, channel: u8) -> Option<(usize, u8)> {
  2437. self.s.inputs.iter().enumerate().find_map(|(id, e)| {
  2438. let r = e.row?;
  2439. // `then`, not `then_some`: the channel is only past `col` when
  2440. // the condition holds.
  2441. (r == u32::from(row) && channel >= e.col && channel < e.col + e.cols)
  2442. .then(|| (id, channel - e.col))
  2443. })
  2444. }
  2445. fn load_input(&mut self, id: usize, col: u8) -> Val {
  2446. if self.s.inputs[id].half {
  2447. // shortcut: 16-bit vertex inputs (the fetch routine's) are not
  2448. // unpacked; pixel inputs are (`interp`).
  2449. return Val::Missing("a 16-bit input");
  2450. }
  2451. self.load_any_input(id, col)
  2452. }
  2453. /// An input element's channel as declared (16-bit ones as 32-bit floats).
  2454. fn load_any_input(&mut self, id: usize, col: u8) -> Val {
  2455. let e = &mut self.s.inputs[id];
  2456. e.usage |= 1 << col;
  2457. let (int, bit) = (e.comp != 9, e.comp == 1);
  2458. let ty = if bit {
  2459. self.s.t.i1
  2460. } else if int {
  2461. self.s.t.i32
  2462. } else {
  2463. self.s.t.f32
  2464. };
  2465. let suffix = if bit {
  2466. ".i1"
  2467. } else if int {
  2468. ".i32"
  2469. } else {
  2470. ".f32"
  2471. };
  2472. let entry = self.s.entry;
  2473. let args = [
  2474. self.s.m.i32(id as u32),
  2475. self.s.m.i32(0),
  2476. self.s.m.i8(col),
  2477. self.s.m.undef(self.s.t.i32),
  2478. ];
  2479. let v = self.s.op(
  2480. entry,
  2481. &format!("loadInput{suffix}"),
  2482. Attr::ReadNone,
  2483. ty,
  2484. 4,
  2485. &args,
  2486. );
  2487. if bit {
  2488. let z = self.s.m.cast(entry, Cast::ZExt, v, self.s.t.i32);
  2489. Val::I32(z)
  2490. } else if int {
  2491. Val::I32(v)
  2492. } else {
  2493. Val::I32(self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.i32))
  2494. }
  2495. }
  2496. /// The DXIL form of an IR value.
  2497. fn get(&mut self, v: Value) -> Result<Val, Why> {
  2498. if self.phi_at.contains_key(&v) {
  2499. self.read_phis.insert(v);
  2500. }
  2501. let is_mask = self.x.st.masks.contains_key(&v) || self.x.st.highs.contains_key(&v);
  2502. match self.vals.get(&v) {
  2503. Some(&Val::Missing(_)) | None if self.mask_ok && is_mask => {
  2504. return self.mask_dword(v).map(Val::I32);
  2505. }
  2506. Some(&Val::Missing(w)) => return Err(w),
  2507. Some(&val) => return Ok(val),
  2508. None => {}
  2509. }
  2510. if let Some(&(param, dword)) = self.params.get(&v) {
  2511. let val = self.user(param, dword);
  2512. self.vals.insert(v, val);
  2513. return Ok(val);
  2514. }
  2515. if let Some(loaded) = self.lazy_barycentric(v) {
  2516. loaded?;
  2517. return Ok(self.vals[&v]);
  2518. }
  2519. Err("a value defined after its use")
  2520. }
  2521. /// Loads `v` if it is a barycentric input VGPR not loaded yet (see
  2522. /// `inputs`): `None` if it is not one.
  2523. fn lazy_barycentric(&mut self, v: Value) -> Option<Result<(), Why>> {
  2524. let (kind, index) = self.x.io.inputs.iter().find_map(|&(w, i)| match i {
  2525. Input::Barycentric { kind, index } if w == v => Some((kind, index)),
  2526. _ => None,
  2527. })?;
  2528. let val = self.barycentric(kind, index);
  2529. self.vals.insert(v, val);
  2530. Some(match val {
  2531. Val::Missing(w) => Err(w),
  2532. _ => Ok(()),
  2533. })
  2534. }
  2535. /// Barycentric `index` (0 i, 1 j) of `kind` as a value: a channel of
  2536. /// `SV_Barycentrics` declared with the same interpolation mode.
  2537. ///
  2538. /// GFX10 interpolates P0 + i (P1 - P0) + j (P2 - P0), so i and j are
  2539. /// the weights of vertices 1 and 2. The host's weights (x, y, z) are
  2540. /// those of vertices 0, 1 and 2, vertex 0 being the provoking vertex,
  2541. /// which is the console's P0 (`v_interp_mov` P0 is lowered to a flat
  2542. /// input): i is y and j is z.
  2543. /// shortcut: triangles only; on lines and points the console's i and j
  2544. /// are not checked against the host's weights.
  2545. fn barycentric(&mut self, kind: Barycentric, index: u8) -> Val {
  2546. let Some(mode) = interp_mode(kind) else {
  2547. return Val::Missing("pull-model barycentrics");
  2548. };
  2549. if index > 1 {
  2550. return Val::Missing("pull-model barycentrics");
  2551. }
  2552. // One element per interpolation mode (the console's own, if its
  2553. // signature declares one): DXIL allows two.
  2554. let bary = |e: &SigElement| e.kind == 28;
  2555. let id = match self
  2556. .s
  2557. .inputs
  2558. .iter()
  2559. .position(|e| bary(e) && (e.interp == mode || e.usage == 0))
  2560. {
  2561. Some(id) => id,
  2562. None => {
  2563. let index = self.s.inputs.iter().filter(|e| bary(e)).count() as u32;
  2564. if index >= 2 {
  2565. return Val::Missing("barycentrics of a third interpolation mode");
  2566. }
  2567. // A system value the validator wants unpacked (packing
  2568. // location -1), like other non-packed system values.
  2569. self.s.inputs.push(SigElement {
  2570. name: "SV_Barycentrics".into(),
  2571. index,
  2572. kind: 28,
  2573. comp: 9,
  2574. interp: mode,
  2575. row: None,
  2576. col: 0,
  2577. cols: 3,
  2578. usage: 0,
  2579. half: false,
  2580. });
  2581. self.s.inputs.len() - 1
  2582. }
  2583. };
  2584. let e = &mut self.s.inputs[id];
  2585. if e.col != 0 || e.cols < 3 {
  2586. return Val::Missing("a console barycentrics element without i and j");
  2587. }
  2588. e.row = None;
  2589. e.interp = mode;
  2590. self.s.flags |= flags::BARYCENTRICS;
  2591. self.load_any_input(id, index + 1)
  2592. }
  2593. fn i32_of(&mut self, v: Value) -> Result<V, Why> {
  2594. match self.get(v)? {
  2595. Val::I32(x) => Ok(x),
  2596. Val::Bit(x) => Ok(self.s.m.cast(self.cur, Cast::ZExt, x, self.s.t.i32)),
  2597. Val::Missing(w) => Err(w),
  2598. }
  2599. }
  2600. /// A user-data dword: a root parameter's value.
  2601. fn user(&mut self, param: usize, dword: u32) -> Val {
  2602. let rp = self.x.native.layout[param];
  2603. match rp.root {
  2604. RootType::ResourceHeap | RootType::SamplerHeap => return Val::I32(self.s.m.i32(0)),
  2605. RootType::Constants | RootType::Table => {}
  2606. _ => return Val::Missing("a root descriptor"),
  2607. }
  2608. let index = u32::from(rp.user_data) + dword - self.user_first();
  2609. self.user_reads.insert(
  2610. index,
  2611. UserData {
  2612. index,
  2613. slot: rp.slot,
  2614. root: rp.root,
  2615. dword,
  2616. },
  2617. );
  2618. Val::I32(self.user_at(index))
  2619. }
  2620. /// The user-data index that is dword 0 of the host's user data: 0, or
  2621. /// 16 for a program with a spilled user-data table, whose parameters
  2622. /// all sit at 16 and above. (The host's root signature has 64 dwords:
  2623. /// a builder stage with constants up to index 45, eight root views,
  2624. /// their biases and the memory directory would not fit with 16 dwords
  2625. /// nothing reads in front.)
  2626. fn user_first(&self) -> u32 {
  2627. if crate::spill::is_spilled(self.x.native) {
  2628. 16
  2629. } else {
  2630. 0
  2631. }
  2632. }
  2633. /// A user-data dword no register of the console's holds: one the host
  2634. /// computes when it binds (`root` says what, an `Other` code of
  2635. /// `shader.rs`), placed after the layout's own dwords.
  2636. fn host_word(&mut self, root: RootType, slot: u8, dword: u32) -> V {
  2637. let known = self
  2638. .user_reads
  2639. .values()
  2640. .find(|u| u.root == root && u.slot == slot && u.dword == dword)
  2641. .map(|u| u.index);
  2642. let index = match known {
  2643. Some(index) => index,
  2644. None => {
  2645. let first = self.user_first();
  2646. let layout = &self.x.native.layout;
  2647. let mut index = layout
  2648. .iter()
  2649. .map(|e| u32::from(e.user_data) + e.sgprs)
  2650. .max()
  2651. .unwrap_or(0)
  2652. .saturating_sub(first);
  2653. while self.user_reads.contains_key(&index) {
  2654. index += 1;
  2655. }
  2656. self.user_reads.insert(
  2657. index,
  2658. UserData {
  2659. index,
  2660. slot,
  2661. root,
  2662. dword,
  2663. },
  2664. );
  2665. index
  2666. }
  2667. };
  2668. self.user_at(index)
  2669. }
  2670. /// User-data dword `index`, loaded in the entry block.
  2671. fn user_at(&mut self, index: u32) -> V {
  2672. self.s.user_data = self.s.user_data.max(index + 1);
  2673. let h = match self.user_data {
  2674. Some(h) => h,
  2675. None => {
  2676. let h = self.s.user_data_handle();
  2677. self.user_data = Some(h);
  2678. h
  2679. }
  2680. };
  2681. let entry = self.s.entry;
  2682. let row = self.s.m.i32(index / 4);
  2683. let r = self.s.op(
  2684. entry,
  2685. "cbufferLoadLegacy.i32",
  2686. Attr::ReadOnly,
  2687. self.s.t.cbuf_ret,
  2688. 59,
  2689. &[h, row],
  2690. );
  2691. self.s.m.extract(entry, r, index % 4)
  2692. }
  2693. /// Whether some instruction reads `v` as a number (or may, through a
  2694. /// join), rather than in a descriptor operand.
  2695. fn read_as_number(&self, v: Value) -> bool {
  2696. self.x.p.blocks.iter().any(|b| {
  2697. b.phis.iter().any(|p| p.args.contains(&v))
  2698. || b.insts.iter().any(|i| {
  2699. matches!(i.fields, Fields::Sop { .. } | Fields::Valu(_))
  2700. && i.reads.iter().any(|r| r.1 == v)
  2701. })
  2702. })
  2703. }
  2704. /// Whether some instruction computes with `v` (scalar or vector
  2705. /// arithmetic), rather than only naming it in a descriptor operand,
  2706. /// moving it (at most `depth` moves are followed) or comparing it: a
  2707. /// waterfall loop keeps a descriptor's dwords per lane, reads the first
  2708. /// lane's back and compares the lanes' with them.
  2709. fn computed_with(&self, v: Value, depth: u32) -> bool {
  2710. self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| {
  2711. if !i.reads.iter().any(|r| r.1 == v) {
  2712. return false;
  2713. }
  2714. let name = i.name();
  2715. let moves = matches!(
  2716. name,
  2717. "s_mov_b32"
  2718. | "s_mov_b64"
  2719. | "v_mov_b32"
  2720. | "v_readfirstlane_b32"
  2721. | "v_readlane_b32"
  2722. | "v_writelane_b32"
  2723. | "v_cndmask_b32"
  2724. );
  2725. match &i.fields {
  2726. Fields::Sop { .. } | Fields::Valu(_) if moves => {
  2727. depth > 0 && i.writes.iter().any(|w| self.computed_with(w.1, depth - 1))
  2728. }
  2729. Fields::Sop { .. } | Fields::Valu(_) => {
  2730. !(name.starts_with("v_cmp") || name.starts_with("s_cmp"))
  2731. }
  2732. _ => false,
  2733. }
  2734. })
  2735. }
  2736. /// Whether the image `src` names is one of 32-bit integers (one channel):
  2737. /// the program has an integer atomic on the same table entry, which
  2738. /// takes no other view.
  2739. fn is_counter(&self, src: &Source) -> bool {
  2740. let Some(this) = self.entry(src) else {
  2741. return false;
  2742. };
  2743. self.x.res.descriptors.iter().any(|d| {
  2744. let i = &self.x.p.blocks[d.site.0].insts[d.site.1];
  2745. d.role == Role::Resource
  2746. && matches!(i.fields, Fields::Image { dmask: 1, .. })
  2747. && matches!(
  2748. i.name(),
  2749. "image_atomic_add"
  2750. | "image_atomic_sub"
  2751. | "image_atomic_and"
  2752. | "image_atomic_or"
  2753. | "image_atomic_xor"
  2754. | "image_atomic_smin"
  2755. | "image_atomic_smax"
  2756. | "image_atomic_umin"
  2757. | "image_atomic_umax"
  2758. )
  2759. && self.entry(&d.source) == Some(this)
  2760. })
  2761. }
  2762. /// Which table entry `src` is loaded from: its root parameter and byte.
  2763. fn entry(&self, src: &Source) -> Option<(usize, u32)> {
  2764. let Source::Loaded { load, first } = src else {
  2765. return None;
  2766. };
  2767. let a = self.scalar.get(load).filter(|a| a.dynamic.is_none())?;
  2768. Some((a.param, a.offset + 4 * u32::from(*first)))
  2769. }
  2770. /// See [`Lower::coherent`].
  2771. fn find_coherent(&mut self) {
  2772. let found: Vec<_> = self
  2773. .x
  2774. .res
  2775. .descriptors
  2776. .iter()
  2777. .filter(|d| {
  2778. let i = &self.x.p.blocks[d.site.0].insts[d.site.1];
  2779. matches!(&i.fields, Fields::Buffer { cache, .. } if cache.glc)
  2780. && i.name().starts_with("buffer_load_dword")
  2781. && self.used_kind(&d.source).is_some_and(|u| u.kind == ResourceType::Uav)
  2782. })
  2783. .filter_map(|d| self.entry(&d.source))
  2784. .collect();
  2785. self.coherent.extend(found);
  2786. }
  2787. /// The kind of a view no instruction uses (in this program, or through
  2788. /// another load of its address), by what the code reads of the
  2789. /// descriptor the load `inst` at `site` writes to the SGPRs from `code`:
  2790. /// `Some(true)` for a 2D image, read only for its size, `Some(false)`
  2791. /// for a structured buffer, read only for its record count.
  2792. ///
  2793. /// - Eight dwords are an image's. `GetDimensions` of a 2D one reads the
  2794. /// width (dwords 1 and 2), the height (dword 2, bits 14-29, with one
  2795. /// `s_bfe_u32`) and the base level or the last (dword 3); of an array,
  2796. /// a cube or a volume also dword 4.
  2797. /// - Four dwords at a table entry the used resources list as an SRV or
  2798. /// UAV are a buffer's. A stride above 4 bytes there is an element's
  2799. /// (a typed or raw view has at most 4): a test for a null view reads
  2800. /// the record count, nothing else.
  2801. fn sized_view(&self, inst: &Inst, site: Site, code: u8, count: u32) -> Option<bool> {
  2802. let dword = |k: u8| inst.write(Reg::S(code + k));
  2803. let read = |v: Value| {
  2804. self.x.p.blocks.iter().any(|b| {
  2805. b.insts.iter().any(|i| i.reads.iter().any(|r| r.1 == v))
  2806. || b.phis.iter().any(|p| p.args.contains(&v))
  2807. })
  2808. };
  2809. let only = |allowed: &[u8]| {
  2810. (0..count as u8).all(|k| allowed.contains(&k) || !dword(k).is_some_and(read))
  2811. };
  2812. match count {
  2813. 8 => {
  2814. const HEIGHT: u32 = 16 << 16 | 14;
  2815. let v = dword(2)?;
  2816. let height = self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| {
  2817. i.name() == "s_bfe_u32"
  2818. && i.reads.iter().any(|r| r.1 == v)
  2819. && matches!(&i.fields, Fields::Sop { src, .. }
  2820. if matches!(src.get(1), Some(Operand::Literal(HEIGHT))))
  2821. });
  2822. (height && only(&[1, 2, 3])).then_some(true)
  2823. }
  2824. 4 => {
  2825. let used = self.used_kind(&Source::Loaded { load: site, first: 0 })?;
  2826. let a = self.scalar.get(&site)?;
  2827. let buffer = used.dwords == 4
  2828. && a.dynamic.is_none()
  2829. && used.table_offset_dwords == a.offset / 4
  2830. && matches!(used.kind, ResourceType::Srv | ResourceType::Uav)
  2831. && used.stride > 4
  2832. && used.stride.is_multiple_of(4);
  2833. (buffer && only(&[2])).then_some(false)
  2834. }
  2835. _ => None,
  2836. }
  2837. }
  2838. /// The title address (low dword, bits from 32 up) of the buffer view
  2839. /// whose descriptor the scalar load at `site` reads from the start of
  2840. /// a table entry, as the host tells it when it binds (`shader.rs`
  2841. /// `USER_VIEW_ADDRESS`); none for anything else. (The console's
  2842. /// descriptor holds more in the second dword, the stride from bit 16
  2843. /// up; code that takes the address masks those away.)
  2844. fn view_address(&mut self, site: Site) -> Option<(V, V)> {
  2845. use super::shader::USER_VIEW_ADDRESS;
  2846. let a = self.scalar.get(&site).copied()?;
  2847. let rp = *self.x.native.layout.get(a.param)?;
  2848. if rp.root != RootType::Table || a.dynamic.is_some() || a.offset % 32 != 0 {
  2849. return None;
  2850. }
  2851. let dword = a.offset / 4;
  2852. let used = self
  2853. .x
  2854. .native
  2855. .used
  2856. .iter()
  2857. .filter(|u| {
  2858. u.root == RootType::Table
  2859. && u.user_data == rp.user_data
  2860. && u.table_offset_dwords <= dword
  2861. })
  2862. .max_by_key(|u| u.table_offset_dwords)?;
  2863. if used.dwords != 4 || !matches!(used.kind, ResourceType::Srv | ResourceType::Uav) {
  2864. return None;
  2865. }
  2866. let lo = self.host_word(RootType::Other(USER_VIEW_ADDRESS), rp.slot, dword);
  2867. let hi = self.host_word(RootType::Other(USER_VIEW_ADDRESS + 1), rp.slot, dword);
  2868. Some((lo, hi))
  2869. }
  2870. /// `lo`, `hi` plus the instruction's byte offset `off`, with the carry.
  2871. fn address_plus(&mut self, lo: V, hi: V, off: i32) -> (V, V) {
  2872. if off == 0 {
  2873. return (lo, hi);
  2874. }
  2875. let c = self.cur;
  2876. let i32t = self.s.t.i32;
  2877. let k = self.s.m.i32(off as u32);
  2878. let sum = self.s.m.bin(c, Bin::Add, lo, k);
  2879. // Up: a carry when the sum wrapped below `lo`. Down: a borrow when
  2880. // it wrapped above.
  2881. let wrapped = self
  2882. .s
  2883. .m
  2884. .cmp(c, if off > 0 { pred::IULT } else { pred::IUGT }, sum, lo);
  2885. let one = self.s.m.cast(c, Cast::ZExt, wrapped, i32t);
  2886. let hi = self.s.m.bin(c, if off > 0 { Bin::Add } else { Bin::Sub }, hi, one);
  2887. (sum, hi)
  2888. }
  2889. /// Title memory at the 40-bit address `lo`, `hi` (`shader.rs`
  2890. /// `SLOT_MEMORY`): the handle of the raw view of the host copy holding
  2891. /// it and the byte in that view. A page without a copy reads zeros
  2892. /// (and drops writes) through the null view at the first slot, and its
  2893. /// number is left for the host, for lanes that run (`guard`).
  2894. fn memory(&mut self, lo: V, hi: V, guard: Option<V>) -> (V, V) {
  2895. use super::shader::{MEMORY_FAULTS, MEMORY_PAGES, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE};
  2896. let c = self.cur;
  2897. let (i32t, res) = (self.s.t.i32, self.s.t.res_ret);
  2898. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  2899. let (k16, k8) = (k(self, 16), k(self, 0xFF));
  2900. let low = self.s.m.bin(c, Bin::LShr, lo, k16);
  2901. let high = self.s.m.bin(c, Bin::And, hi, k8);
  2902. let high = self.s.m.bin(c, Bin::Shl, high, k16);
  2903. let page = self.s.m.bin(c, Bin::Or, low, high);
  2904. // Inside the directory whatever the address (lanes that do not run
  2905. // compute one too); its last entry is never filled.
  2906. let last = k(self, MEMORY_PAGES - 1);
  2907. let page = self
  2908. .s
  2909. .op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[page, last]);
  2910. self.s.m.tag(page, Tag::Clamp);
  2911. let k3 = k(self, 3);
  2912. let at = self.s.m.bin(c, Bin::Shl, page, k3);
  2913. let directory = self.s.root_srv_handle(SLOT_MEMORY);
  2914. let (iu, both, align) = (self.s.m.undef(i32t), self.s.m.i8(3), k(self, 4));
  2915. let entry = self.s.op(
  2916. c,
  2917. "rawBufferLoad.f32",
  2918. Attr::ReadOnly,
  2919. res,
  2920. 139,
  2921. &[directory, at, iu, both, align],
  2922. );
  2923. let (copy, start) = (self.s.m.extract(c, entry, 0), self.s.m.extract(c, entry, 1));
  2924. let (copy, start) = (self.as_int(copy), self.as_int(start));
  2925. // A page without a copy: its number, at a place by the number, or
  2926. // at the sink for lanes that do not run and pages that have one.
  2927. let zero = k(self, 0);
  2928. let mut missing = self.s.m.cmp(c, pred::EQ, copy, zero);
  2929. if let Some(g) = guard {
  2930. missing = self.s.m.bin(c, Bin::And, missing, g);
  2931. }
  2932. let places = k(self, MEMORY_FAULTS - 1);
  2933. let place = self.s.m.bin(c, Bin::URem, page, places);
  2934. let one = k(self, 1);
  2935. let place = self.s.m.bin(c, Bin::Add, place, one);
  2936. let k2 = k(self, 2);
  2937. let place = self.s.m.bin(c, Bin::Shl, place, k2);
  2938. let place = self.s.m.select(c, missing, place, zero);
  2939. let faults = self.s.root_uav_handle(SLOT_FAULTS);
  2940. let void = self.s.t.void;
  2941. let mask = self.s.m.i8(1);
  2942. self.s.op(
  2943. c,
  2944. "rawBufferStore.i32",
  2945. Attr::NoUnwind,
  2946. void,
  2947. 140,
  2948. &[faults, place, iu, page, iu, iu, iu, mask, align],
  2949. );
  2950. let base = self.host_word(RootType::Other(USER_MEMORY_BASE), 0, 0);
  2951. let slot = self.s.m.bin(c, Bin::Add, base, copy);
  2952. let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000, 0));
  2953. let k64k = k(self, 0xFFFF);
  2954. let within = self.s.m.bin(c, Bin::And, lo, k64k);
  2955. let byte = self.s.m.bin(c, Bin::Add, start, within);
  2956. (h, byte)
  2957. }
  2958. /// `global_load_*`, `global_store_*` and `global_atomic_*` on title
  2959. /// memory by address (`resource::MEMORY`): the address is the VGPR
  2960. /// pair, each lane its own.
  2961. fn memory_flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  2962. let Fields::Flat {
  2963. dst,
  2964. addr,
  2965. data,
  2966. saddr,
  2967. offset,
  2968. lds,
  2969. cache,
  2970. } = &inst.fields
  2971. else {
  2972. unreachable!()
  2973. };
  2974. if *lds || !matches!(saddr, None | Some(Operand::Scalar { code: NULL, .. })) {
  2975. return Err("a global address with a scalar base");
  2976. }
  2977. let Some(Operand::Vector { reg: areg, .. }) = *addr else {
  2978. return Err("a global address not in VGPRs");
  2979. };
  2980. let word = |l: &mut Self, k: u8| -> Result<V, Why> {
  2981. let v = inst.read(Reg::V(areg + k)).ok_or("a global address")?;
  2982. l.i32_of(v)
  2983. };
  2984. let (lo, hi) = (word(self, 0)?, word(self, 1)?);
  2985. let (lo, hi) = self.address_plus(lo, hi, i32::from(*offset));
  2986. let guard = self.guard(b, i)?;
  2987. let c = self.cur;
  2988. let (i32t, res, void) = (self.s.t.i32, self.s.t.res_ret, self.s.t.void);
  2989. let iu = self.s.m.undef(i32t);
  2990. let align = self.s.m.i32(4);
  2991. let name = inst.name();
  2992. let count = |rest: &str| match rest {
  2993. "dword" => Ok(1u8),
  2994. "dwordx2" => Ok(2),
  2995. "dwordx3" => Ok(3),
  2996. "dwordx4" => Ok(4),
  2997. _ => Err(name),
  2998. };
  2999. if let Some(rest) = name.strip_prefix("global_load_") {
  3000. let n = count(rest)?;
  3001. let Some(Operand::Vector { reg, .. }) = *dst else {
  3002. return Err("a global load result");
  3003. };
  3004. let (h, byte) = self.memory(lo, hi, guard);
  3005. let mask = self.s.m.i8((1u8 << n) - 1);
  3006. let r = self.s.op(
  3007. c,
  3008. "rawBufferLoad.f32",
  3009. Attr::ReadOnly,
  3010. res,
  3011. 139,
  3012. &[h, byte, iu, mask, align],
  3013. );
  3014. for k in 0..n {
  3015. let x = self.s.m.extract(c, r, u32::from(k));
  3016. let x = self.as_int(x);
  3017. self.write(inst, Reg::V(reg + k), x, guard);
  3018. }
  3019. return Ok(());
  3020. }
  3021. if let Some(rest) = name.strip_prefix("global_store_") {
  3022. let n = count(rest)?;
  3023. let d = data.as_ref().ok_or("global store data")?;
  3024. let vals = self.vgprs(inst, d, n)?;
  3025. let (h, byte) = self.memory(lo, hi, guard);
  3026. let mut args = vec![h, byte, iu];
  3027. args.extend(&vals);
  3028. args.resize(3 + 4, iu);
  3029. args.push(self.s.m.i8((1u8 << n) - 1));
  3030. args.push(align);
  3031. let at = self.begin_guarded(guard);
  3032. self.s
  3033. .op(self.cur, "rawBufferStore.i32", Attr::NoUnwind, void, 140, &args);
  3034. self.end_guarded(at, &[]);
  3035. return Ok(());
  3036. }
  3037. let Some(op) = name.strip_prefix("global_atomic_") else {
  3038. return Err(name);
  3039. };
  3040. let d = data.as_ref().ok_or("global atomic data")?;
  3041. let v = self.vgprs(inst, d, 1)?[0];
  3042. // With `glc` the value from before comes back, in the result
  3043. // register the instruction names.
  3044. let back = match (*dst, cache.glc) {
  3045. (Some(Operand::Vector { reg, .. }), true) => Some(reg),
  3046. _ => None,
  3047. };
  3048. let old = match back.and_then(|reg| inst.read(Reg::V(reg))) {
  3049. Some(x) => self.i32_of(x)?,
  3050. None => self.s.m.i32(0),
  3051. };
  3052. let (h, byte) = self.memory(lo, hi, guard);
  3053. // DXIL's atomic operations: add 0, and 1, or 2, xor 3, signed
  3054. // minimum 4 and maximum 5, unsigned 6 and 7, exchange 8.
  3055. let simple = match op {
  3056. "add" => Some((0, v)),
  3057. "sub" => {
  3058. let zero = self.s.m.i32(0);
  3059. Some((0, self.s.m.bin(c, Bin::Sub, zero, v)))
  3060. }
  3061. "and" => Some((1, v)),
  3062. "or" => Some((2, v)),
  3063. "xor" => Some((3, v)),
  3064. "smin" => Some((4, v)),
  3065. "smax" => Some((5, v)),
  3066. "umin" => Some((6, v)),
  3067. "umax" => Some((7, v)),
  3068. "swap" => Some((8, v)),
  3069. "fmin" | "fmax" => None,
  3070. _ => return Err(name),
  3071. };
  3072. let at = self.begin_guarded(guard);
  3073. let was = match simple {
  3074. Some((code, x)) => {
  3075. let code = self.s.m.i32(code);
  3076. self.s.op(
  3077. self.cur,
  3078. "atomicBinOp.i32",
  3079. Attr::NoUnwind,
  3080. i32t,
  3081. 78,
  3082. &[h, code, byte, iu, iu, x],
  3083. )
  3084. }
  3085. None => {
  3086. // A float minimum or maximum has no atomic operation on
  3087. // the host: the dword is exchanged for the smaller (larger)
  3088. // of itself and the value until no other thread got in
  3089. // between. Each failed pass means another one's succeeded;
  3090. // the limit only keeps a broken card from hanging.
  3091. let head = self.cur;
  3092. let mask = self.s.m.i8(1);
  3093. let first = self.s.op(
  3094. head,
  3095. "rawBufferLoad.f32",
  3096. Attr::ReadOnly,
  3097. res,
  3098. 139,
  3099. &[h, byte, iu, mask, align],
  3100. );
  3101. let first = self.s.m.extract(head, first, 0);
  3102. let first = self.as_int(first);
  3103. let (pass, done) = (self.s.m.new_block(), self.s.m.new_block());
  3104. self.s.m.terminate(head, Term::Br(pass));
  3105. self.cur = pass;
  3106. let seen = self.s.m.phi(pass, i32t);
  3107. let n = self.s.m.phi(pass, i32t);
  3108. let (f32t, fv) = (self.s.t.f32, self.as_float(v));
  3109. let fseen = self.as_float(seen);
  3110. // `dx.op.binary`: FMax 35, FMin 36.
  3111. let pick = if op == "fmin" { 36 } else { 35 };
  3112. let wanted = self
  3113. .s
  3114. .op(pass, "binary.f32", Attr::ReadNone, f32t, pick, &[fseen, fv]);
  3115. let wanted = self.as_int(wanted);
  3116. let found = self.s.op(
  3117. pass,
  3118. "atomicCompareExchange.i32",
  3119. Attr::NoUnwind,
  3120. i32t,
  3121. 79,
  3122. &[h, byte, iu, iu, seen, wanted],
  3123. );
  3124. let one = self.s.m.i32(1);
  3125. let n1 = self.s.m.bin(pass, Bin::Add, n, one);
  3126. let lost = self.s.m.cmp(pass, pred::NE, found, seen);
  3127. let limit = self.s.m.i32(1 << 16);
  3128. let more = self.s.m.cmp(pass, pred::IULT, n1, limit);
  3129. let again = self.s.m.bin(pass, Bin::And, lost, more);
  3130. self.s.m.terminate(pass, Term::CondBr(again, pass, done));
  3131. let zero = self.s.m.i32(0);
  3132. self.s.m.set_phi(seen, vec![(first, head), (found, pass)]);
  3133. self.s.m.set_phi(n, vec![(zero, head), (n1, pass)]);
  3134. self.cur = done;
  3135. found
  3136. }
  3137. };
  3138. let was = self.end_guarded(at, &[(was, old)])[0];
  3139. if let Some(reg) = back {
  3140. self.write(inst, Reg::V(reg), was, None);
  3141. }
  3142. Ok(())
  3143. }
  3144. /// `s_load_dword*` from title memory by address (`resource::MEMORY`):
  3145. /// the SGPR pair plus the instruction's offsets.
  3146. fn memory_smem(&mut self, inst: &Inst) -> Result<(), Why> {
  3147. let Fields::Smem {
  3148. data: Some(Operand::Scalar { code, .. }),
  3149. base: Operand::Scalar { code: base, .. },
  3150. offset,
  3151. soffset,
  3152. ..
  3153. } = inst.fields
  3154. else {
  3155. return Err("a scalar load from memory");
  3156. };
  3157. let count = match inst.name().strip_prefix("s_load_dword") {
  3158. Some("") => 1u8,
  3159. Some("x2") => 2,
  3160. Some("x4") => 4,
  3161. Some("x8") => 8,
  3162. Some("x16") => 16,
  3163. _ => return Err("a scalar memory access by address"),
  3164. };
  3165. let word = |l: &mut Self, k: u8| -> Result<V, Why> {
  3166. let v = inst.read(Reg::S(base + k)).ok_or("an address not in SGPRs")?;
  3167. l.i32_of(v)
  3168. };
  3169. let (mut lo, mut hi) = (word(self, 0)?, word(self, 1)?);
  3170. let c = self.cur;
  3171. let (i32t, res) = (self.s.t.i32, self.s.t.res_ret);
  3172. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  3173. // An offset register counts up from the address.
  3174. let so = self.operand(inst, &soffset)?;
  3175. let sum = self.s.m.bin(c, Bin::Add, lo, so);
  3176. let carry = self.s.m.cmp(c, pred::IULT, sum, lo);
  3177. let carry = self.s.m.cast(c, Cast::ZExt, carry, i32t);
  3178. hi = self.s.m.bin(c, Bin::Add, hi, carry);
  3179. lo = sum;
  3180. }
  3181. let (iu, align) = (self.s.m.undef(i32t), self.s.m.i32(4));
  3182. for first in (0..count).step_by(4) {
  3183. let n = (count - first).min(4);
  3184. let (lo, hi) = self.address_plus(lo, hi, offset + 4 * i32::from(first));
  3185. let (h, byte) = self.memory(lo, hi, None);
  3186. let mask = self.s.m.i8((1u8 << n) - 1);
  3187. let r = self.s.op(
  3188. c,
  3189. "rawBufferLoad.f32",
  3190. Attr::ReadOnly,
  3191. res,
  3192. 139,
  3193. &[h, byte, iu, mask, align],
  3194. );
  3195. for k in 0..n {
  3196. let x = self.s.m.extract(c, r, u32::from(k));
  3197. let x = self.as_int(x);
  3198. self.write(inst, Reg::S(code + first + k), x, None);
  3199. }
  3200. }
  3201. Ok(())
  3202. }
  3203. /// A dword of a lane mask as a number: the ballot of the lanes' bits,
  3204. /// taken in the block that writes the mask (see [`MaskData`]).
  3205. fn mask_dword(&mut self, v: Value) -> Result<V, Why> {
  3206. let (lo, high) = match self.x.st.highs.get(&v) {
  3207. Some(&lo) => (lo, true),
  3208. None => (v, false),
  3209. };
  3210. let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?;
  3211. // A mask that holds lanes outside EXEC where it is written (the complement of one,
  3212. // say) is the ballot of the lanes that are there: all of them, where two exchanging
  3213. // host waves know every lane runs that block.
  3214. let made = self.def_block.get(&lo).copied();
  3215. let whole = self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b));
  3216. if !self.x.st.active.contains(&lo) && !whole {
  3217. if self.exchange.is_some() && !self.local {
  3218. need(made.unwrap_or(0));
  3219. }
  3220. return Err(MASK_ELSEWHERE);
  3221. }
  3222. let (x, y) = match self.ballots.get(&lo) {
  3223. Some(&xy) => xy,
  3224. None => {
  3225. let at = match self.def_block.get(&lo) {
  3226. // Program inputs (EXEC on entry).
  3227. None => self.s.entry,
  3228. Some(&b) if b == self.cur_ir => self.cur,
  3229. Some(&b) => self.tail[b].ok_or("a lane mask written after its use")?,
  3230. };
  3231. if !self.balloting.insert(lo) {
  3232. return Err("a lane mask whose lanes depend on its own value");
  3233. }
  3234. let bit = self.boolean(m, at);
  3235. self.balloting.remove(&lo);
  3236. let bit = bit?;
  3237. let i32t = self.s.t.i32;
  3238. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  3239. let r = self
  3240. .s
  3241. .op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, &[bit]);
  3242. self.s.flags |= flags::WAVE_OPS;
  3243. let mut xy = (self.s.m.extract(at, r, 0), self.s.m.extract(at, r, 1));
  3244. if self.exchange.is_some() {
  3245. // a host wave's ballot is its half's 32 bits: the halves exchange them
  3246. let b = self.def_block.get(&lo).copied();
  3247. if self.local {
  3248. if !self.local_ok && !self.local_any {
  3249. return Err("a lane mask read as data in a half-wave");
  3250. }
  3251. } else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) {
  3252. // (a group of 32 or fewer has no other half to exchange with)
  3253. need(b.unwrap_or(0));
  3254. return Err("a lane mask exchanged where not every lane runs");
  3255. }
  3256. xy = self.exchange_halves(at, xy.0);
  3257. }
  3258. self.ballots.insert(lo, xy);
  3259. xy
  3260. }
  3261. };
  3262. Ok(if high { y } else { x })
  3263. }
  3264. // ---- operands ----
  3265. fn operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> {
  3266. match *op {
  3267. Operand::Scalar { code: NULL, .. } => Ok(self.s.m.i32(0)),
  3268. Operand::Scalar { code, .. } => {
  3269. let v = inst.read(Reg::S(code)).ok_or("an unread operand")?;
  3270. self.i32_of(v)
  3271. }
  3272. Operand::Vector { reg, .. } => {
  3273. let v = inst.read(Reg::V(reg)).ok_or("an unread operand")?;
  3274. self.i32_of(v)
  3275. }
  3276. // src_scc: SCC as 0 or 1 (VIctory upstream 0b35b7f, as the dot
  3277. // products and packed multiply-adds below).
  3278. Operand::Const(253) => {
  3279. let bit = self.scc_in(inst)?;
  3280. Ok(self.s.m.cast(self.cur, Cast::ZExt, bit, self.s.t.i32))
  3281. }
  3282. // Nothing to wait for (see `ordered_section`).
  3283. Operand::Const(POPS_EXITING) if !self.ordered.is_empty() => Ok(self.s.m.i32(0)),
  3284. Operand::Const(c) => crate::resource::inline(c)
  3285. .map(|x| self.s.m.i32(x))
  3286. .ok_or("a special operand (vccz, execz, scc, lds_direct)"),
  3287. Operand::Literal(x) => Ok(self.s.m.i32(x)),
  3288. Operand::Attr { .. } => Err("an attribute operand"),
  3289. }
  3290. }
  3291. /// An operand read as f16 data: GFX10 puts an inline f16 constant in
  3292. /// the low half of the operand (upstream PR #637, checked there against
  3293. /// the instruction encodings; the half-and-half reading taken from PR
  3294. /// #458 gave the high half the constant too).
  3295. fn f16_operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> {
  3296. match *op {
  3297. Operand::Const(c @ 240..=248) => Ok(self.s.m.i32(inline_f16(c))),
  3298. _ => self.operand(inst, op),
  3299. }
  3300. }
  3301. fn as_float(&mut self, x: V) -> V {
  3302. self.s.m.cast(self.cur, Cast::Bitcast, x, self.s.t.f32)
  3303. }
  3304. fn as_int(&mut self, f: V) -> V {
  3305. self.s.m.cast(self.cur, Cast::Bitcast, f, self.s.t.i32)
  3306. }
  3307. /// The SDWA operand selection of source `k`: a byte or word of the
  3308. /// dword, zero- or sign-extended (none: the whole dword).
  3309. fn sdwa_src(inst: &Inst, k: usize) -> Option<(u8, bool)> {
  3310. let Fields::Valu(v) = &inst.fields else {
  3311. return None;
  3312. };
  3313. let s = v.sdwa?;
  3314. let sel = *s.src_sel.get(k)?;
  3315. let sext = s.sext >> k & 1 != 0;
  3316. (sel < 6).then_some((sel, sext))
  3317. }
  3318. /// Bits `sel` (0-3 a byte, 4-5 a word) of `x`, extended.
  3319. fn select_bits(&mut self, x: V, sel: u8, sext: bool) -> V {
  3320. let c = self.cur;
  3321. let (width, at) = if sel < 4 {
  3322. (8, 8 * sel)
  3323. } else {
  3324. (16, 16 * (sel - 4))
  3325. };
  3326. let left = self.s.m.i32(u32::from(32 - width - at));
  3327. let t = self.s.m.bin(c, Bin::Shl, x, left);
  3328. let right = self.s.m.i32(32 - u32::from(width));
  3329. let op = if sext { Bin::AShr } else { Bin::LShr };
  3330. self.s.m.bin(c, op, t, right)
  3331. }
  3332. /// A float source with its abs/neg modifiers.
  3333. fn fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  3334. let Fields::Valu(v) = &inst.fields else {
  3335. unreachable!()
  3336. };
  3337. let op = *v.src.get(k).ok_or("a missing operand")?;
  3338. let selected = Self::sdwa_src(inst, k);
  3339. let mut f = match op {
  3340. _ if selected.is_some() => {
  3341. let (sel, sext) = selected.expect("checked");
  3342. let x = self.operand(inst, &op)?;
  3343. let x = self.select_bits(x, sel, sext);
  3344. self.as_float(x)
  3345. }
  3346. _ if k == 0 && self.src0.is_some() => {
  3347. let x = self.src0.expect("checked");
  3348. self.as_float(x)
  3349. }
  3350. Operand::Vector { reg, .. } | Operand::Scalar { code: reg, .. }
  3351. if !matches!(op, Operand::Scalar { code: NULL, .. }) =>
  3352. {
  3353. let r = if matches!(op, Operand::Vector { .. }) {
  3354. Reg::V(reg)
  3355. } else {
  3356. Reg::S(reg)
  3357. };
  3358. let val = inst.read(r).ok_or("an unread operand")?;
  3359. match self.floats.get(&val) {
  3360. Some(&f) => f,
  3361. None => {
  3362. let x = self.i32_of(val)?;
  3363. self.as_float(x)
  3364. }
  3365. }
  3366. }
  3367. _ => {
  3368. let x = self.operand(inst, &op)?;
  3369. self.as_float(x)
  3370. }
  3371. };
  3372. if v.abs >> k & 1 != 0 {
  3373. f = self.unary(6, f);
  3374. }
  3375. if v.neg >> k & 1 != 0 {
  3376. let z = self.s.m.f32(0x8000_0000);
  3377. f = self.s.m.bin(self.cur, Bin::Sub, z, f);
  3378. }
  3379. Ok(f)
  3380. }
  3381. fn src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  3382. let Fields::Valu(v) = &inst.fields else {
  3383. unreachable!()
  3384. };
  3385. let op = *v.src.get(k).ok_or("a missing operand")?;
  3386. if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 {
  3387. return Err("integer operand modifiers");
  3388. }
  3389. match self.src0 {
  3390. Some(x) if k == 0 => Ok(x),
  3391. _ => {
  3392. let x = self.operand(inst, &op)?;
  3393. Ok(match Self::sdwa_src(inst, k) {
  3394. Some((sel, sext)) => self.select_bits(x, sel, sext),
  3395. None => x,
  3396. })
  3397. }
  3398. }
  3399. }
  3400. fn unary(&mut self, op: u32, f: V) -> V {
  3401. self.s.op(
  3402. self.cur,
  3403. "unary.f32",
  3404. Attr::ReadNone,
  3405. self.s.t.f32,
  3406. op,
  3407. &[f],
  3408. )
  3409. }
  3410. fn binary(&mut self, op: u32, a: V, b: V) -> V {
  3411. self.s.op(
  3412. self.cur,
  3413. "binary.f32",
  3414. Attr::ReadNone,
  3415. self.s.t.f32,
  3416. op,
  3417. &[a, b],
  3418. )
  3419. }
  3420. /// The hardware's maximum (`max`) or minimum of two floats: as DXIL's
  3421. /// FMax/FMin, but -0 orders below +0 (RDNA2 ISA, `v_max_f32`), where
  3422. /// the compare and select DXIL specifies gives either zero.
  3423. fn max_min(&mut self, max: bool, a: V, b: V) -> V {
  3424. let c = self.cur;
  3425. let r = self.binary(if max { 35 } else { 36 }, a, b);
  3426. let (ia, ib) = (self.as_int(a), self.as_int(b));
  3427. let either = self.s.m.bin(c, Bin::Or, ia, ib);
  3428. let magnitude = self.s.m.i32(0x7FFF_FFFF);
  3429. let either = self.s.m.bin(c, Bin::And, either, magnitude);
  3430. let zero = self.s.m.i32(0);
  3431. let zeros = self.s.m.cmp(c, pred::EQ, either, zero);
  3432. // Of two zeros, +0 unless both are -0 (max), -0 unless neither (min).
  3433. let op = if max { Bin::And } else { Bin::Or };
  3434. let sign = self.s.m.bin(c, op, ia, ib);
  3435. let signed = self.as_float(sign);
  3436. self.s.m.select(c, zeros, signed, r)
  3437. }
  3438. fn fmad(&mut self, a: V, b: V, c: V) -> V {
  3439. self.s.op(
  3440. self.cur,
  3441. "tertiary.f32",
  3442. Attr::ReadNone,
  3443. self.s.t.f32,
  3444. 46,
  3445. &[a, b, c],
  3446. )
  3447. }
  3448. /// `f` as an f16 in the low bits, rounded toward zero: the nearest-even
  3449. /// conversion, one step back toward zero where it rounded away (which
  3450. /// also turns an overflow to infinity into the largest finite half).
  3451. fn f16_toward_zero(&mut self, f: V) -> V {
  3452. let c = self.cur;
  3453. let i32t = self.s.t.i32;
  3454. let h = self
  3455. .s
  3456. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
  3457. let back = self
  3458. .s
  3459. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]);
  3460. let (fa, ba) = (self.unary(6, f), self.unary(6, back));
  3461. // Ordered: never for NaN.
  3462. let away = self.s.m.cmp(c, pred::OGT, ba, fa);
  3463. let one = self.s.m.i32(1);
  3464. let stepped = self.s.m.bin(c, Bin::Sub, h, one);
  3465. self.s.m.select(c, away, stepped, h)
  3466. }
  3467. /// `f` as an f16 in the low bits, rounded to nearest, ties to even, as the console's
  3468. /// 16-bit float operations round, whatever the host's own conversion does: D3D lets
  3469. /// `f32tof16` round toward zero, and the NVIDIA driver's does (measured on an RTX 4070:
  3470. /// `wave64_tests`). The conversion toward zero, or the next half away from zero where
  3471. /// that one is nearer, or as near and the first one odd. Past the largest half the next
  3472. /// one counts as 2^16, the bound IEEE rounds by, so 65520 and up become infinity.
  3473. /// (`f` is an f32 result of two halves here; rounding it again to 16 bits gives the
  3474. /// rounding of the exact result, 24 bits being more than twice 11 and two.)
  3475. fn f16_nearest(&mut self, f: V) -> V {
  3476. let c = self.cur;
  3477. let f32t = self.s.t.f32;
  3478. let lo = self.f16_toward_zero(f);
  3479. let (one, zero) = (self.s.m.i32(1), self.s.m.i32(0));
  3480. let hi = self.s.m.bin(c, Bin::Add, lo, one);
  3481. let size = |l: &mut Self, h: V| {
  3482. let w = l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  3483. l.unary(6, w)
  3484. };
  3485. let (below, above) = (size(self, lo), size(self, hi));
  3486. let (magnitude, infinity) = (self.s.m.i32(0x7FFF), self.s.m.i32(0x7C00));
  3487. let m = self.s.m.bin(c, Bin::And, hi, magnitude);
  3488. let top = self.s.m.cmp(c, pred::EQ, m, infinity);
  3489. let bound = self.s.m.f32(65536.0f32.to_bits());
  3490. let above = self.s.m.select(c, top, bound, above);
  3491. let fa = self.unary(6, f);
  3492. // (both differences are exact: the three values lie within one half's step)
  3493. let under = self.s.m.bin(c, Bin::Sub, fa, below);
  3494. let over = self.s.m.bin(c, Bin::Sub, above, fa);
  3495. // Ordered: never for NaN, which stays what the conversion made of it.
  3496. let nearer = self.s.m.cmp(c, pred::OLT, over, under);
  3497. let tie = self.s.m.cmp(c, pred::OEQ, over, under);
  3498. let odd = self.s.m.bin(c, Bin::And, lo, one);
  3499. let odd = self.s.m.cmp(c, pred::NE, odd, zero);
  3500. let tie = self.s.m.bin(c, Bin::And, tie, odd);
  3501. let up = self.s.m.bin(c, Bin::Or, nearer, tie);
  3502. self.s.m.select(c, up, hi, lo)
  3503. }
  3504. /// `(a >> off[4:0]) & ((1 << width) - 1)`, sign-extended from the field's
  3505. /// top bit when `signed`; widths from 32 on take every bit. A signed
  3506. /// field that runs past bit 31 extends from bit 31, as the hardware
  3507. /// does: the shift is arithmetic then.
  3508. fn bfe(&mut self, a: V, off: V, width: V, signed: bool) -> V {
  3509. let c = self.cur;
  3510. let (k31, k32, zero, one, ones) = (
  3511. self.s.m.i32(31),
  3512. self.s.m.i32(32),
  3513. self.s.m.i32(0),
  3514. self.s.m.i32(1),
  3515. self.s.m.i32(u32::MAX),
  3516. );
  3517. let off = self.s.m.bin(c, Bin::And, off, k31);
  3518. let shift = if signed { Bin::AShr } else { Bin::LShr };
  3519. let shifted = self.s.m.bin(c, shift, a, off);
  3520. let full = self.s.m.cmp(c, pred::IUGE, width, k32);
  3521. let w = self.s.m.bin(c, Bin::And, width, k31);
  3522. let mask = self.s.m.bin(c, Bin::Shl, one, w);
  3523. let mask = self.s.m.bin(c, Bin::Sub, mask, one);
  3524. let mask = self.s.m.select(c, full, ones, mask);
  3525. let r = self.s.m.bin(c, Bin::And, shifted, mask);
  3526. if !signed {
  3527. return r;
  3528. }
  3529. // Sign-extend a field narrower than 32 bits (none for width 0).
  3530. let left = self.s.m.bin(c, Bin::Sub, k32, w);
  3531. let left = self.s.m.bin(c, Bin::And, left, k31);
  3532. let t = self.s.m.bin(c, Bin::Shl, r, left);
  3533. let t = self.s.m.bin(c, Bin::AShr, t, left);
  3534. let is0 = self.s.m.cmp(c, pred::EQ, w, zero);
  3535. let keep = self.s.m.bin(c, Bin::Or, full, is0);
  3536. self.s.m.select(c, keep, r, t)
  3537. }
  3538. /// Whether an f32 value is NaN, tested in integer arithmetic so host
  3539. /// drivers (such as NVIDIA) do not fold `fcmp uno` away under fast-math.
  3540. fn is_nan_f32(&mut self, f: V) -> V {
  3541. let c = self.cur;
  3542. let bits = self.as_int(f);
  3543. let mask = self.s.m.i32(0x7FFF_FFFF);
  3544. let abs = self.s.m.bin(c, Bin::And, bits, mask);
  3545. let inf = self.s.m.i32(0x7F80_0000);
  3546. self.s.m.cmp(c, pred::IUGT, abs, inf)
  3547. }
  3548. /// The median of three. With a NaN among them the hardware gives the
  3549. /// minimum of the three instead (the host's minimum skips NaNs, so that
  3550. /// is the smallest number among them).
  3551. fn med3(&mut self, a: V, b: V, third: V) -> V {
  3552. let c = self.cur;
  3553. let lo = self.binary(36, a, b);
  3554. let hi = self.binary(35, a, b);
  3555. let t = self.binary(36, hi, third);
  3556. let median = self.binary(35, lo, t);
  3557. let least = self.binary(36, lo, third);
  3558. let nan_a = self.is_nan_f32(a);
  3559. let nan_b = self.is_nan_f32(b);
  3560. let nan_3 = self.is_nan_f32(third);
  3561. let nan_ab = self.s.m.bin(c, Bin::Or, nan_a, nan_b);
  3562. let nan = self.s.m.bin(c, Bin::Or, nan_ab, nan_3);
  3563. self.s.m.select(c, nan, least, median)
  3564. }
  3565. /// `a - floor(a)`, which on the hardware never reaches 1.0: where it
  3566. /// would round to it (a tiny negative `a`), the result is `below_one`,
  3567. /// the largest value under 1.0 in the operation's width. Hosts differ
  3568. /// here (some give 1.0). Comparing against a `threshold` distinct from
  3569. /// `below_one` prevents drivers (observed on NVIDIA) from folding
  3570. /// `r > k ? k : r` into `minNum` (`FMNMX`) and swallowing NaN.
  3571. fn fract(&mut self, a: V, threshold: f32, below_one: f32) -> V {
  3572. let c = self.cur;
  3573. let r = self.unary(22, a);
  3574. let limit = self.s.m.f32(threshold.to_bits());
  3575. let k = self.s.m.f32(below_one.to_bits());
  3576. let over = self.s.m.cmp(c, pred::OGE, r, limit);
  3577. self.s.m.select(c, over, k, r)
  3578. }
  3579. /// Sine, or cosine, of an angle in turns, as the hardware takes it. The
  3580. /// whole turns are taken off first (`x - round_even(x)`, exact, within
  3581. /// half a turn), so a large angle keeps its fraction; scaling to radians
  3582. /// first rounds it away. A zero passes unreduced (the sine of -0 is -0).
  3583. /// The sine of a half turn and the cosine of a quarter turn are exactly
  3584. /// +0 on the hardware, where the host's function of the rounded angle
  3585. /// gives about 1e-7. Infinities and NaN give NaN.
  3586. /// shortcut: below 2^-12 turns the hardware scales by a slightly
  3587. /// different constant than 2π (a last-place difference).
  3588. fn trig_turns(&mut self, x: V, cosine: bool) -> V {
  3589. let c = self.cur;
  3590. let zero = self.s.m.f32(0);
  3591. let whole = self.unary(26, x);
  3592. let part = self.s.m.bin(c, Bin::Sub, x, whole);
  3593. let is_zero = self.s.m.cmp(c, pred::OEQ, x, zero);
  3594. let part = self.s.m.select(c, is_zero, x, part);
  3595. let k = self.s.m.f32(TWO_PI.to_bits());
  3596. let angle = self.s.m.bin(c, Bin::Mul, part, k);
  3597. let r = self.unary(if cosine { 12 } else { 13 }, angle);
  3598. let at = if cosine { 0.25f32 } else { 0.5 };
  3599. let at = self.s.m.f32(at.to_bits());
  3600. let size = self.unary(6, part);
  3601. let exact = self.s.m.cmp(c, pred::OEQ, size, at);
  3602. self.s.m.select(c, exact, zero, r)
  3603. }
  3604. /// The high dword of a 32 × 32-bit product.
  3605. fn mul_hi(&mut self, a: V, b: V, signed: bool) -> V {
  3606. let c = self.cur;
  3607. let i64t = self.s.m.int(64);
  3608. let ext = if signed { Cast::SExt } else { Cast::ZExt };
  3609. let a = self.s.m.cast(c, ext, a, i64t);
  3610. let b = self.s.m.cast(c, ext, b, i64t);
  3611. let m = self.s.m.bin(c, Bin::Mul, a, b);
  3612. let k32 = self.s.m.int_const(i64t, 32);
  3613. let hi = self.s.m.bin(c, Bin::LShr, m, k32);
  3614. self.s.flags |= flags::INT64;
  3615. self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32)
  3616. }
  3617. /// `0 × anything = 0`, as in D3D9.
  3618. fn legacy_mul(&mut self, a: V, b: V) -> V {
  3619. let c = self.cur;
  3620. let m = self.s.m.bin(c, Bin::Mul, a, b);
  3621. let zero = self.s.m.f32(0);
  3622. let az = self.s.m.cmp(c, pred::OEQ, a, zero);
  3623. let bz = self.s.m.cmp(c, pred::OEQ, b, zero);
  3624. let z = self.s.m.bin(c, Bin::Or, az, bz);
  3625. self.s.m.select(c, z, zero, m)
  3626. }
  3627. // ---- lane booleans ----
  3628. fn boolean(&mut self, b: Bool, at: usize) -> Result<V, Why> {
  3629. if b == Bool::TRUE || b == Bool::FALSE {
  3630. return Ok(self.s.m.bool(b == Bool::TRUE));
  3631. }
  3632. if let Some(&v) = self.bools.get(&(at, b)) {
  3633. return Ok(v);
  3634. }
  3635. let (atom, lo, hi) = self.x.st.bools.node(b).expect("not a constant");
  3636. let a = self.atom(atom, at)?;
  3637. let m = &mut self.s.m;
  3638. let v = match (lo, hi) {
  3639. (Bool::FALSE, Bool::TRUE) => a,
  3640. (Bool::TRUE, Bool::FALSE) => {
  3641. let t = m.bool(true);
  3642. m.bin(at, Bin::Xor, a, t)
  3643. }
  3644. (Bool::FALSE, h) => {
  3645. let h = self.boolean(h, at)?;
  3646. self.s.m.bin(at, Bin::And, a, h)
  3647. }
  3648. (l, Bool::TRUE) => {
  3649. let l = self.boolean(l, at)?;
  3650. self.s.m.bin(at, Bin::Or, a, l)
  3651. }
  3652. (l, h) => {
  3653. let l = self.boolean(l, at)?;
  3654. let h = self.boolean(h, at)?;
  3655. self.s.m.select(at, a, h, l)
  3656. }
  3657. };
  3658. self.bools.insert((at, b), v);
  3659. Ok(v)
  3660. }
  3661. fn atom(&mut self, atom: Atom, at: usize) -> Result<V, Why> {
  3662. match atom {
  3663. Atom::Lane(v) => self.lane_bits.get(&v).copied().ok_or_else(|| {
  3664. self.lane_fail
  3665. .get(&v)
  3666. .copied()
  3667. .unwrap_or("a lane mask from a carry")
  3668. }),
  3669. Atom::Uniform(v) => match self.get(v)? {
  3670. Val::Bit(x) => Ok(x),
  3671. Val::I32(x) => {
  3672. let z = self.s.m.i32(0);
  3673. Ok(self.s.m.cmp(at, pred::NE, x, z))
  3674. }
  3675. Val::Missing(w) => Err(w),
  3676. },
  3677. Atom::Phi(id) => {
  3678. if let Some(&v) = self.mask_phis.get(&id) {
  3679. return Ok(v);
  3680. }
  3681. let &(b, i) = self
  3682. .phi_at
  3683. .get(&id)
  3684. .ok_or("a lane-mask join without a phi")?;
  3685. let blk = self.block[b].ok_or("an unreachable join")?;
  3686. let v = self.s.m.phi(blk, self.s.t.i1);
  3687. self.mask_phis.insert(id, v);
  3688. self.pending_masks.push((v, b, i));
  3689. Ok(v)
  3690. }
  3691. // shortcut: "some lane of the quad is set" is taken as true: the
  3692. // lanes it adds only feed derivatives, and exports keep their own
  3693. // masks. Wrong if such a section had a side effect.
  3694. Atom::Quad(_) => Ok(self.s.m.bool(true)),
  3695. // With console lanes, a mask held as a number is the console's:
  3696. // the lane tests its own bit.
  3697. Atom::Opaque(v) if self.console_lanes => {
  3698. let hi = match self.pair_high(v) {
  3699. Some(h) => Some(self.get(h)?),
  3700. None => None,
  3701. };
  3702. let lo = self.get(v)?;
  3703. let word = |w: Val| match w {
  3704. Val::I32(x) => Ok(x),
  3705. _ => Err("an opaque lane mask"),
  3706. };
  3707. let lo = word(lo)?;
  3708. let hi = hi.map(word).transpose()?;
  3709. Ok(self.lane_bit(at, lo, hi))
  3710. }
  3711. Atom::Constant(k) if self.console_lanes => {
  3712. let lo = self.s.m.i32(k as u32);
  3713. let hi = self.s.m.i32((k >> 32) as u32);
  3714. Ok(self.lane_bit(at, lo, Some(hi)))
  3715. }
  3716. Atom::Opaque(_) => Err("an opaque lane mask"),
  3717. Atom::Constant(_) => Err("a constant lane mask"),
  3718. }
  3719. }
  3720. /// A console wave64 program in host waves of 32: the first console thread of this host wave
  3721. /// (0, 32, 64, ...). A GPU need not give a host wave consecutive thread indices (NVIDIA's
  3722. /// 8 x 8 groups), so each wave takes the next 32 from an LDS counter instead: every thread
  3723. /// zeroes it, the group meets, each wave's first lane adds 32 and the wave takes what it
  3724. /// found. Branch-free, in the entry block, which every thread runs.
  3725. fn wave_base(&mut self) -> Option<V> {
  3726. let slot = self.halves?;
  3727. if let Some(v) = self.wave_base {
  3728. return Some(v);
  3729. }
  3730. let (e, i32t) = (self.s.entry, self.s.t.i32);
  3731. let lds = self.s.lds();
  3732. let k = self.s.m.i32(slot);
  3733. let ptr = self.s.m.element(e, lds, k);
  3734. let zero = self.s.m.i32(0);
  3735. self.s.m.store(e, ptr, zero);
  3736. self.group_sync(e);
  3737. let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  3738. let first = self.s.m.cmp(e, pred::EQ, lane, zero);
  3739. let k32 = self.s.m.i32(32);
  3740. let add = self.s.m.select(e, first, k32, zero);
  3741. let ptr = self.s.m.element(e, lds, k);
  3742. let old = self.s.m.atomic(e, Rmw::Add, ptr, add);
  3743. let base = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[old]);
  3744. self.s.flags |= flags::WAVE_OPS;
  3745. self.wave_base = Some(base);
  3746. Some(base)
  3747. }
  3748. /// The console thread index of this thread in the group: `wave_base` plus the host lane
  3749. /// (host waves of 32), else the wave's first thread index rounded down plus the lane.
  3750. fn console_thread(&mut self) -> V {
  3751. let (e, i32t) = (self.s.entry, self.s.t.i32);
  3752. let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  3753. if let Some(base) = self.wave_base() {
  3754. return self.s.m.bin(e, Bin::Add, base, lane);
  3755. }
  3756. let flat = self.s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, &[]);
  3757. let first = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[flat]);
  3758. let wave = self.s.wave_size.unwrap_or(32);
  3759. let mask = self.s.m.i32(!(wave - 1));
  3760. let base = self.s.m.bin(e, Bin::And, first, mask);
  3761. self.s.m.bin(e, Bin::Add, base, lane)
  3762. }
  3763. /// This thread's console lane (0..63): its relabelled thread index (`thread_id`), whose host
  3764. /// wave holds a 32-aligned run of console lanes. Without `exchange`: the host lane.
  3765. fn console_lane(&mut self) -> V {
  3766. if self.exchange.is_none() {
  3767. return self.lane_index();
  3768. }
  3769. if let Some(v) = self.clane {
  3770. return v;
  3771. }
  3772. let (e, i32t) = (self.s.entry, self.s.t.i32);
  3773. let f = self.console_thread();
  3774. let _ = i32t;
  3775. let k63 = self.s.m.i32(63);
  3776. let cl = self.s.m.bin(e, Bin::And, f, k63);
  3777. self.s.flags |= flags::WAVE_OPS;
  3778. self.clane = Some(cl);
  3779. cl
  3780. }
  3781. /// A group barrier with an LDS fence in `block`.
  3782. fn group_sync(&mut self, block: usize) {
  3783. let mode = self.s.m.i32(meeting_mode());
  3784. let void = self.s.t.void;
  3785. self.s.op(block, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  3786. }
  3787. /// `exchange`: each host wave gives `mine` (the same in all its lanes) for its half; both get
  3788. /// (lower half's, upper half's). A group with no upper half gets 0 for it.
  3789. fn exchange_halves(&mut self, at: usize, mine: V) -> (V, V) {
  3790. let Some((slot, small, _)) = self.exchange.as_ref().map(|(a, b, _)| (*a, *b, ())) else {
  3791. let z = self.s.m.i32(0);
  3792. return (mine, z);
  3793. };
  3794. if small {
  3795. let z = self.s.m.i32(0);
  3796. return (mine, z);
  3797. }
  3798. if self.local {
  3799. // each host wave on its own: its half holds `mine`, the other nothing
  3800. let cl = self.console_lane();
  3801. let (k32, z) = (self.s.m.i32(32), self.s.m.i32(0));
  3802. let upper = self.s.m.cmp(at, pred::IUGE, cl, k32);
  3803. let lo = self.s.m.select(at, upper, z, mine);
  3804. let hi = self.s.m.select(at, upper, mine, z);
  3805. return (lo, hi);
  3806. }
  3807. // the pair of dwords of this thread's console wave: its half's, then both
  3808. let pair = self.exchange_pair(slot);
  3809. let cl = self.console_lane();
  3810. let five = self.s.m.i32(5);
  3811. let half = self.s.m.bin(at, Bin::LShr, cl, five);
  3812. let index = self.s.m.bin(at, Bin::Add, pair, half);
  3813. let lds = self.s.lds();
  3814. let ptr = self.s.m.element(at, lds, index);
  3815. self.s.m.store(at, ptr, mine);
  3816. self.group_sync(at);
  3817. let one = self.s.m.i32(1);
  3818. let k1 = self.s.m.bin(at, Bin::Add, pair, one);
  3819. let p0 = self.s.m.element(at, lds, pair);
  3820. let p1 = self.s.m.element(at, lds, k1);
  3821. let lo = self.s.m.load(at, p0);
  3822. let hi = self.s.m.load(at, p1);
  3823. // the slots are written again only after every thread read them
  3824. self.group_sync(at);
  3825. (lo, hi)
  3826. }
  3827. /// The first of the two exchange dwords of this thread's console wave (made in the entry
  3828. /// block): a group of several console waves has a pair for each.
  3829. fn exchange_pair(&mut self, slot: u32) -> V {
  3830. if let Some(v) = self.pair {
  3831. return v;
  3832. }
  3833. let e = self.s.entry;
  3834. let thread = self.console_thread();
  3835. let six = self.s.m.i32(6);
  3836. let wave = self.s.m.bin(e, Bin::LShr, thread, six);
  3837. let one = self.s.m.i32(1);
  3838. let twice = self.s.m.bin(e, Bin::Shl, wave, one);
  3839. let base = self.s.m.i32(slot);
  3840. let v = self.s.m.bin(e, Bin::Add, base, twice);
  3841. self.pair = Some(v);
  3842. v
  3843. }
  3844. /// The console's decision of the branch closing IR block `b`, which the wave takes
  3845. /// together ([`Structured::wide`]): `when` is the lane's own bit, and the branch is taken
  3846. /// when some lane's `when` holds (`execnz`, `vccnz`, SCC of a mask operation set) or
  3847. /// when every lane's does (`execz`, `vccz`, that SCC clear), [`Structured::wave_any`].
  3848. /// Each host wave asks its lanes and the halves exchange the answers, so both go the
  3849. /// same way and can meet again inside the branch.
  3850. /// SCC of a mask operation as data ([`Structured::scc_some`]): whether some lane of the
  3851. /// console wave has its bit of the result, asked where the operation stands. The lanes
  3852. /// that are elsewhere have no bit (the result is ANDed with EXEC or is EXEC), so with
  3853. /// the console's waves the host wave's answer is the console's; two host waves of 32
  3854. /// exchange theirs, which needs every lane there.
  3855. fn scc_some(&mut self, scc: Value) -> Result<V, Why> {
  3856. let &m = self.x.st.scc_some.get(&scc).ok_or(LANE_MASK)?;
  3857. // (not for a console wave cut into host waves that do not exchange)
  3858. if !self.console_lanes || self.local || self.exchange.is_none() && self.halves.is_some() {
  3859. return Err(LANE_MASK);
  3860. }
  3861. let made = self.def_block.get(&scc).copied();
  3862. let at = match made {
  3863. None => self.s.entry,
  3864. Some(b) if b == self.cur_ir => self.cur,
  3865. Some(b) => self.tail[b].ok_or("a lane mask written after its use")?,
  3866. };
  3867. let bit = self.boolean(m, at)?;
  3868. let (i1t, i32t) = (self.s.t.i1, self.s.t.i32);
  3869. let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]);
  3870. self.s.flags |= flags::WAVE_OPS;
  3871. if !self.exchange.as_ref().is_some_and(|e| !e.1) {
  3872. return Ok(some);
  3873. }
  3874. if !made.is_none_or(|b| self.all_lanes(b)) {
  3875. need(made.unwrap_or(0));
  3876. return Err("a lane mask exchanged where not every lane runs");
  3877. }
  3878. let some = self.s.m.cast(at, Cast::ZExt, some, i32t);
  3879. let (lo, hi) = self.exchange_halves(at, some);
  3880. let both = self.s.m.bin(at, Bin::Or, lo, hi);
  3881. let z = self.s.m.i32(0);
  3882. Ok(self.s.m.cmp(at, pred::NE, both, z))
  3883. }
  3884. fn wave_wide(&mut self, b: usize, when: Bool) -> Result<V, Why> {
  3885. const WHY: Why = "a wave-wide branch where not every lane runs";
  3886. let any = self.x.st.wave_any.get(b).copied().flatten().ok_or("a wave-wide branch on a scalar condition")?;
  3887. if self.exchange.is_none() && self.halves.is_none() && self.console_lanes && self.mask_data == MaskData::Console {
  3888. // The host's waves are the console's: the wave's own answer. The lanes that are
  3889. // elsewhere have no bit set, as on the console, so "some lane" needs no one but
  3890. // the lanes here, and "every lane's bit is clear" is true of the others anyway.
  3891. let c = self.cur;
  3892. let mine = self.boolean(when, c)?;
  3893. let i1t = self.s.t.i1;
  3894. self.s.flags |= flags::WAVE_OPS;
  3895. let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) };
  3896. return Ok(self.s.op(c, name, Attr::NoUnwind, i1t, code, &[mine]));
  3897. }
  3898. if self.local || !self.exchange.as_ref().is_some_and(|e| !e.1) {
  3899. return Err(WHY);
  3900. }
  3901. if !self.all_lanes(b) {
  3902. need(b);
  3903. return Err(WHY);
  3904. }
  3905. let c = self.cur;
  3906. let mine = self.boolean(when, c)?;
  3907. // what the halves exchange is "some lane speaks against" either way (for `any`:
  3908. // some lane's `when` holds; else: some lane's does not), so a half with no lane says
  3909. // nothing
  3910. let set = if any {
  3911. mine
  3912. } else {
  3913. let t = self.s.m.bool(true);
  3914. self.s.m.bin(c, Bin::Xor, mine, t)
  3915. };
  3916. let (i1t, i32t) = (self.s.t.i1, self.s.t.i32);
  3917. let some = self.s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]);
  3918. self.s.flags |= flags::WAVE_OPS;
  3919. let some = self.s.m.cast(c, Cast::ZExt, some, i32t);
  3920. let (lo, hi) = self.exchange_halves(c, some);
  3921. let c = self.cur;
  3922. let both = self.s.m.bin(c, Bin::Or, lo, hi);
  3923. let z = self.s.m.i32(0);
  3924. Ok(self.s.m.cmp(c, if any { pred::NE } else { pred::EQ }, both, z))
  3925. }
  3926. /// Whether every lane runs IR block `b` (always true without `exchange`).
  3927. fn all_lanes(&self, b: usize) -> bool {
  3928. self.exchange.as_ref().is_none_or(|(_, _, all)| all.get(b).copied().unwrap_or(false))
  3929. }
  3930. /// This lane's bit of the mask `lo`, `hi` (wave64).
  3931. fn lane_bit(&mut self, at: usize, lo: V, hi: Option<V>) -> V {
  3932. self.s.flags |= flags::WAVE_OPS;
  3933. let lane = if self.exchange.is_some() {
  3934. self.console_lane()
  3935. } else {
  3936. self.s.op(at, "waveGetLaneIndex", Attr::ReadOnly, self.s.t.i32, 111, &[])
  3937. };
  3938. let (k31, k32, one, z) = (
  3939. self.s.m.i32(31),
  3940. self.s.m.i32(32),
  3941. self.s.m.i32(1),
  3942. self.s.m.i32(0),
  3943. );
  3944. let word = match hi {
  3945. Some(hi) => {
  3946. let low = self.s.m.cmp(at, pred::IULT, lane, k32);
  3947. self.s.m.select(at, low, lo, hi)
  3948. }
  3949. None => lo,
  3950. };
  3951. let sh = self.s.m.bin(at, Bin::And, lane, k31);
  3952. let t = self.s.m.bin(at, Bin::LShr, word, sh);
  3953. let t = self.s.m.bin(at, Bin::And, t, one);
  3954. self.s.m.cmp(at, pred::NE, t, z)
  3955. }
  3956. /// The value of the high dword of the wave64 register pair whose low
  3957. /// dword holds `lo` (none in wave32).
  3958. fn pair_high(&self, lo: Value) -> Option<Value> {
  3959. if !self.x.native.wave64 {
  3960. return None;
  3961. }
  3962. let p = self.x.p;
  3963. let pick = |reg: Reg| match reg {
  3964. Reg::S(c) => Some(Reg::S(c + 1)),
  3965. _ => None,
  3966. };
  3967. if let Some(&(reg, _)) = p.inputs.iter().find(|i| i.1 == lo) {
  3968. let h = pick(reg)?;
  3969. return p.inputs.iter().find(|i| i.0 == h).map(|i| i.1);
  3970. }
  3971. if let Some(&(b, i)) = self.phi_at.get(&lo) {
  3972. let h = pick(p.blocks[b].phis[i].reg)?;
  3973. return p.blocks[b]
  3974. .phis
  3975. .iter()
  3976. .find(|q| q.reg == h)
  3977. .map(|q| q.value);
  3978. }
  3979. let b = *self.def_block.get(&lo)?;
  3980. let inst = p.blocks[b]
  3981. .insts
  3982. .iter()
  3983. .find(|i| i.writes.iter().any(|w| w.1 == lo))?;
  3984. let &(reg, _) = inst.writes.iter().find(|w| w.1 == lo)?;
  3985. inst.write(pick(reg)?)
  3986. }
  3987. fn guard(&mut self, b: usize, i: usize) -> Result<Option<V>, Why> {
  3988. match self.x.st.guards[b][i] {
  3989. None => Ok(None),
  3990. Some(g) => Ok(Some(self.boolean(g, self.cur)?)),
  3991. }
  3992. }
  3993. // ---- results ----
  3994. fn set(&mut self, v: Option<Value>, val: Val) {
  3995. if let Some(v) = v {
  3996. self.vals.insert(v, val);
  3997. }
  3998. }
  3999. /// Writes VGPR `reg` (or the SGPR of a lane read), under `guard`.
  4000. fn write(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) {
  4001. let x = match (Self::sdwa_dst(inst), reg) {
  4002. (Some((sel, unused)), Reg::V(_)) => self.place_bits(inst, reg, x, sel, unused),
  4003. _ => x,
  4004. };
  4005. self.write_placed(inst, reg, x, guard);
  4006. }
  4007. /// [`Self::write`] of a dword already placed (SDWA applied).
  4008. fn write_placed(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) {
  4009. let Some(new) = inst.write(reg) else { return };
  4010. let x = match (guard, reg) {
  4011. (Some(g), Reg::V(_)) => {
  4012. let old = match inst.read(reg).map(|o| self.i32_of(o)) {
  4013. Some(Ok(o)) => o,
  4014. // The validator refuses reads of undef.
  4015. _ => self.s.m.i32(0),
  4016. };
  4017. let v = self.s.m.select(self.cur, g, x, old);
  4018. self.s.m.tag(v, Tag::Guard);
  4019. v
  4020. }
  4021. _ => x,
  4022. };
  4023. self.vals.insert(new, Val::I32(x));
  4024. }
  4025. /// The SDWA destination selection: a byte or word, and what the other
  4026. /// bits get (0 zeros, 1 the sign above the field, 2 the old bits).
  4027. fn sdwa_dst(inst: &Inst) -> Option<(u8, u8)> {
  4028. let Fields::Valu(v) = &inst.fields else {
  4029. return None;
  4030. };
  4031. let s = v.sdwa?;
  4032. (s.dst_sel < 6).then_some((s.dst_sel, s.dst_unused))
  4033. }
  4034. /// The low byte or word of `x` placed at `sel` in VGPR `reg`.
  4035. fn place_bits(&mut self, inst: &Inst, reg: Reg, x: V, sel: u8, unused: u8) -> V {
  4036. let c = self.cur;
  4037. let (width, at) = if sel < 4 {
  4038. (8u32, 8 * u32::from(sel))
  4039. } else {
  4040. (16, 16 * u32::from(sel - 4))
  4041. };
  4042. let left = self.s.m.i32(32 - width);
  4043. let t = self.s.m.bin(c, Bin::Shl, x, left);
  4044. let right = self.s.m.i32(32 - width - at);
  4045. if unused == 1 {
  4046. // Bits below the field shift in as zeros.
  4047. return self.s.m.bin(c, Bin::AShr, t, right);
  4048. }
  4049. let field = self.s.m.bin(c, Bin::LShr, t, right);
  4050. if unused != 2 {
  4051. return field;
  4052. }
  4053. let old = match inst.read(reg).map(|o| self.i32_of(o)) {
  4054. Some(Ok(o)) => o,
  4055. _ => self.s.m.i32(0),
  4056. };
  4057. let keep = self.s.m.i32(!((((1u64 << width) - 1) as u32) << at));
  4058. let old = self.s.m.bin(c, Bin::And, old, keep);
  4059. self.s.m.bin(c, Bin::Or, old, field)
  4060. }
  4061. fn write_f(&mut self, inst: &Inst, f: V, guard: Option<V>) -> Result<(), Why> {
  4062. let Fields::Valu(v) = &inst.fields else {
  4063. unreachable!()
  4064. };
  4065. let mut f = f;
  4066. match v.omod {
  4067. 0 => {}
  4068. k => {
  4069. let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)];
  4070. let c = self.s.m.f32(factor.to_bits());
  4071. f = self.s.m.bin(self.cur, Bin::Mul, f, c);
  4072. }
  4073. }
  4074. if v.clamp {
  4075. f = self.unary(7, f);
  4076. }
  4077. let Some(Operand::Vector { reg, .. }) = v.dst else {
  4078. return Err("a float result outside a VGPR");
  4079. };
  4080. let x = self.as_int(f);
  4081. self.write(inst, Reg::V(reg), x, guard);
  4082. if guard.is_none()
  4083. && Self::sdwa_dst(inst).is_none()
  4084. && let Some(new) = inst.write(Reg::V(reg))
  4085. {
  4086. self.floats.insert(new, f);
  4087. }
  4088. Ok(())
  4089. }
  4090. fn write_i(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> {
  4091. let Fields::Valu(v) = &inst.fields else {
  4092. unreachable!()
  4093. };
  4094. if v.clamp || v.omod != 0 {
  4095. return Err("integer output modifiers");
  4096. }
  4097. match v.dst {
  4098. Some(Operand::Vector { reg, .. }) => self.write(inst, Reg::V(reg), x, guard),
  4099. Some(Operand::Scalar { code, .. }) => self.write(inst, Reg::S(code), x, None),
  4100. _ => return Err("a result without a register"),
  4101. }
  4102. Ok(())
  4103. }
  4104. /// Starts code only the lanes where `guard` holds run (a store under a
  4105. /// lane guard): returns where it started and the join block.
  4106. fn begin_guarded(&mut self, guard: Option<V>) -> Option<(usize, usize)> {
  4107. let g = guard?;
  4108. let (then, join) = (self.s.m.new_block(), self.s.m.new_block());
  4109. self.s.m.terminate(self.cur, Term::CondBr(g, then, join));
  4110. let head = self.cur;
  4111. self.cur = then;
  4112. Some((head, join))
  4113. }
  4114. /// Ends guarded code; each (value inside, value outside) becomes a phi.
  4115. fn end_guarded(&mut self, at: Option<(usize, usize)>, values: &[(V, V)]) -> Vec<V> {
  4116. let Some((head, join)) = at else {
  4117. return values.iter().map(|v| v.0).collect();
  4118. };
  4119. let then = self.cur;
  4120. self.s.m.terminate(then, Term::Br(join));
  4121. self.cur = join;
  4122. values
  4123. .iter()
  4124. .map(|&(inside, outside)| {
  4125. let ty = self.s.m.type_of(inside);
  4126. let phi = self.s.m.phi(join, ty);
  4127. self.s.m.set_phi(phi, vec![(inside, then), (outside, head)]);
  4128. phi
  4129. })
  4130. .collect()
  4131. }
  4132. /// Code that depends on the lane layout: wave operations, and in compute
  4133. /// the console's wave size (lanes are thread ids in group order there).
  4134. /// Pixel lanes match only within a quad.
  4135. fn cross_lane(&mut self, quad: bool) -> Result<(), Why> {
  4136. if self.s.mesh.is_some() {
  4137. // shortcut: no wave size for mesh shaders in SM 6.6, so host
  4138. // lanes cannot follow the console's; emulate through group-shared
  4139. // memory if mesh programs turn out to need these.
  4140. return Err("a cross-lane operation in a mesh shader");
  4141. }
  4142. if self.s.threads.is_none() && !(quad && self.s.pixel) {
  4143. return Err("a cross-lane operation outside compute");
  4144. }
  4145. debug_assert!(self.s.threads.is_none() || self.console_lanes);
  4146. self.s.flags |= flags::WAVE_OPS;
  4147. Ok(())
  4148. }
  4149. /// Component `c` of the thread id in the group. With console lanes, the
  4150. /// thread is relabelled so that its host lane is its console lane: the
  4151. /// flat id is the wave's first lane's, rounded down to the wave size,
  4152. /// plus the lane index. (A bijection while each host wave holds a
  4153. /// wave-aligned run of flat ids, as the console's waves do.)
  4154. fn thread_id(&mut self, c: u8) -> Val {
  4155. if !self.console_lanes {
  4156. return self.compute_id("threadIdInGroup.i32", 95, c);
  4157. }
  4158. let [x, y, _] = self.s.threads.expect("compute");
  4159. let e = self.s.entry;
  4160. let i32t = self.s.t.i32;
  4161. if self.halves.is_some() {
  4162. let f = self.console_thread();
  4163. self.s.flags |= flags::WAVE_OPS;
  4164. let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y));
  4165. return Val::I32(match c {
  4166. 0 => self.s.m.bin(e, Bin::URem, f, xk),
  4167. 1 => {
  4168. let t = self.s.m.bin(e, Bin::UDiv, f, xk);
  4169. self.s.m.bin(e, Bin::URem, t, yk)
  4170. }
  4171. _ => self.s.m.bin(e, Bin::UDiv, f, xy),
  4172. });
  4173. }
  4174. let flat = self.s.op(
  4175. e,
  4176. "flattenedThreadIdInGroup.i32",
  4177. Attr::ReadNone,
  4178. i32t,
  4179. 96,
  4180. &[],
  4181. );
  4182. let first = self.s.op(
  4183. e,
  4184. "waveReadLaneFirst.i32",
  4185. Attr::NoUnwind,
  4186. i32t,
  4187. 118,
  4188. &[flat],
  4189. );
  4190. let wave = self.s.wave_size.expect("set with console lanes");
  4191. let mask = self.s.m.i32(!(wave - 1));
  4192. let base = self.s.m.bin(e, Bin::And, first, mask);
  4193. let lane = self.lane_index();
  4194. let f = self.s.m.bin(e, Bin::Add, base, lane);
  4195. self.s.flags |= flags::WAVE_OPS;
  4196. let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y));
  4197. Val::I32(match c {
  4198. 0 => self.s.m.bin(e, Bin::URem, f, xk),
  4199. 1 => {
  4200. let t = self.s.m.bin(e, Bin::UDiv, f, xk);
  4201. self.s.m.bin(e, Bin::URem, t, yk)
  4202. }
  4203. _ => self.s.m.bin(e, Bin::UDiv, f, xy),
  4204. })
  4205. }
  4206. /// Mesh: the counts and the primitives no lane exports. The console's
  4207. /// counts come from one lane's allocation request, which DXIL cannot
  4208. /// express (one call, dominating every output write).
  4209. // shortcut: the counts are the declared maxima and each lane first culls
  4210. // its primitive (all indices 0, zero area), so primitives past the
  4211. // program's count are culled and vertices past it unused; this costs
  4212. // the host the unused vertex and primitive slots. Pass the program's own
  4213. // counts if that shows in frame time.
  4214. fn mesh_prologue(&mut self, mut mesh: super::shader::Mesh) -> Result<(), Why> {
  4215. let threads = self.s.threads.expect("mesh")[0];
  4216. if mesh.topology != 2 {
  4217. return Err("a mesh shader not drawing triangles");
  4218. }
  4219. if threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256 {
  4220. return Err("a mesh shader beyond the host's limits");
  4221. }
  4222. // D3D12 caps the outputs of the declared maxima at 32 KiB. Lane n
  4223. // writes only vertex n and primitive n, so maxima past the lanes are
  4224. // never reached: they come down to the lane count when the outputs
  4225. // do not fit.
  4226. use super::container::{MESH_OUTPUT_LIMIT, mesh_output_bytes};
  4227. let (outputs, prims) = (&self.s.outputs, &self.s.prims);
  4228. let fits = |m: super::shader::Mesh| {
  4229. mesh_output_bytes(outputs, prims, m.max_vertices, m.max_primitives) <= MESH_OUTPUT_LIMIT
  4230. };
  4231. if !fits(mesh) {
  4232. mesh.max_vertices = mesh.max_vertices.min(threads);
  4233. mesh.max_primitives = mesh.max_primitives.min(threads);
  4234. // shortcut: outputs past the cap even at the lane count are
  4235. // still emitted with the lower maxima (drivers take them);
  4236. // refuse them here if one hangs.
  4237. // Experiment (`VICTORY_MESH_OUTPUT_STRICT=1`): they are refused.
  4238. if !fits(mesh) && std::env::var_os("VICTORY_MESH_OUTPUT_STRICT").is_some() {
  4239. return Err("a mesh shader whose outputs pass the host's 32 KiB");
  4240. }
  4241. self.s.mesh = Some(mesh);
  4242. }
  4243. let e = self.s.entry;
  4244. let void = self.s.t.void;
  4245. let (v, p) = (
  4246. self.s.m.i32(mesh.max_vertices),
  4247. self.s.m.i32(mesh.max_primitives),
  4248. );
  4249. self.s
  4250. .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]);
  4251. let flat = self.mesh_thread();
  4252. let z = self.s.m.i32(0);
  4253. // Every primitive of the declared count starts culled, also those
  4254. // past the lanes (a count of 256 with 128 lanes): lane n culls
  4255. // primitives n, n + lanes, ... The host draws all it was promised,
  4256. // and one never written has whatever indices its memory held: long
  4257. // triangles over the whole target, each pixel of them shaded.
  4258. let passes = mesh.max_primitives.div_ceil(threads.max(1));
  4259. for pass in 0..passes {
  4260. let index = if pass == 0 {
  4261. flat
  4262. } else {
  4263. let past = self.s.m.i32(pass * threads);
  4264. self.s.m.bin(self.cur, Bin::Add, flat, past)
  4265. };
  4266. let guard = ((pass + 1) * threads > mesh.max_primitives)
  4267. .then(|| self.s.m.cmp(self.cur, pred::IULT, index, p));
  4268. let at = self.begin_guarded(guard);
  4269. self.s.op(
  4270. self.cur,
  4271. "emitIndices",
  4272. Attr::NoUnwind,
  4273. void,
  4274. 169,
  4275. &[index, z, z, z],
  4276. );
  4277. self.end_guarded(at, &[]);
  4278. }
  4279. Ok(())
  4280. }
  4281. /// Mesh: the thread's index in the group, which is its vertex and
  4282. /// primitive index.
  4283. fn mesh_thread(&mut self) -> V {
  4284. if let Some(f) = self.flat {
  4285. return f;
  4286. }
  4287. let e = self.s.entry;
  4288. let f = self.s.op(
  4289. e,
  4290. "flattenedThreadIdInGroup.i32",
  4291. Attr::ReadNone,
  4292. self.s.t.i32,
  4293. 96,
  4294. &[],
  4295. );
  4296. self.flat = Some(f);
  4297. f
  4298. }
  4299. /// The console wave size.
  4300. fn wave(&self) -> u32 {
  4301. if self.x.native.wave64 { 64 } else { 32 }
  4302. }
  4303. fn lane_index(&mut self) -> V {
  4304. if self.s.mesh.is_some() {
  4305. // The console's lane: mesh code reads no other lanes, so host
  4306. // waves need not match the console's.
  4307. let f = self.mesh_thread();
  4308. let m = self.s.m.i32(self.wave() - 1);
  4309. return self.s.m.bin(self.s.entry, Bin::And, f, m);
  4310. }
  4311. self.s.op(
  4312. self.cur,
  4313. "waveGetLaneIndex",
  4314. Attr::ReadOnly,
  4315. self.s.t.i32,
  4316. 111,
  4317. &[],
  4318. )
  4319. }
  4320. /// `x` of lane `src` (in this lane's quad) through quad reads, whose
  4321. /// lane must be a constant.
  4322. fn quad_pick(&mut self, x: V, src: V) -> V {
  4323. self.s.flags |= flags::WAVE_OPS;
  4324. let c = self.cur;
  4325. let three = self.s.m.i32(3);
  4326. let q = self.s.m.bin(c, Bin::And, src, three);
  4327. let mut r = x;
  4328. for n in 0..4 {
  4329. let kn = self.s.m.i32(n);
  4330. let read = self.s.op(
  4331. c,
  4332. "quadReadLaneAt.i32",
  4333. Attr::NoUnwind,
  4334. self.s.t.i32,
  4335. 122,
  4336. &[x, kn],
  4337. );
  4338. let is = self.s.m.cmp(c, pred::EQ, q, kn);
  4339. r = self.s.m.select(c, is, read, r);
  4340. }
  4341. r
  4342. }
  4343. /// `x` in the first lane of this host wave where `guard` holds, and whether it has such a
  4344. /// lane: the console reads the first lane of EXEC, and a lane that got here with EXEC clear
  4345. /// (a guard, not a branch) is not one. With none, `x` of the wave's first lane here.
  4346. ///
  4347. /// A helper lane of a pixel shader takes its own value: the console's whole-quad mode has
  4348. /// helper lanes in EXEC, so a waterfall loop serves them too, and the host's wave operations
  4349. /// leave them out. Once only helper lanes are left in such a loop none of them ever matched:
  4350. /// they ran to the iteration limit, and left with no sample for their quad's derivatives,
  4351. /// along every triangle's edges (upstream #908, the fix of #1733 for this tree's form).
  4352. fn first_lane(&mut self, x: V, guard: Option<V>) -> (V, V) {
  4353. let (first, any) = self.first_live_lane(x, guard);
  4354. if !self.s.pixel || !super::helper_own() {
  4355. return (first, any);
  4356. }
  4357. let helper = self.helper_lane();
  4358. let c = self.cur;
  4359. let yes = self.s.m.bool(true);
  4360. (self.s.m.select(c, helper, x, first), self.s.m.select(c, helper, yes, any))
  4361. }
  4362. /// Whether this lane of a pixel shader is a helper lane.
  4363. fn helper_lane(&mut self) -> V {
  4364. let i1t = self.s.t.i1;
  4365. self.s.op(self.cur, "isHelperLane.i1", Attr::ReadOnly, i1t, 221, &[])
  4366. }
  4367. fn first_live_lane(&mut self, x: V, guard: Option<V>) -> (V, V) {
  4368. let c = self.cur;
  4369. let i32t = self.s.t.i32;
  4370. self.s.flags |= flags::WAVE_OPS;
  4371. let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[x]);
  4372. let Some(g) = guard else {
  4373. return (first, self.s.m.bool(true));
  4374. };
  4375. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  4376. let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[g]);
  4377. let (lo, hi) = (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1));
  4378. let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32));
  4379. // FirstbitLo (dx.op 32): the lowest set bit
  4380. let flo = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[lo]);
  4381. let fhi = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[hi]);
  4382. let fhi = self.s.m.bin(c, Bin::Add, fhi, k32);
  4383. let in_lo = self.s.m.cmp(c, pred::NE, lo, z);
  4384. let in_hi = self.s.m.cmp(c, pred::NE, hi, z);
  4385. let any = self.s.m.bin(c, Bin::Or, in_lo, in_hi);
  4386. let lane = self.s.m.select(c, in_lo, flo, fhi);
  4387. // no lane in EXEC: read this lane (one that is here); the read is not used
  4388. let me = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  4389. let lane = self.s.m.select(c, any, lane, me);
  4390. let at = self.read_lane(x, lane);
  4391. (self.s.m.select(c, any, at, first), any)
  4392. }
  4393. fn read_lane(&mut self, x: V, lane: V) -> V {
  4394. self.s.op(
  4395. self.cur,
  4396. "waveReadLaneAt.i32",
  4397. Attr::NoUnwind,
  4398. self.s.t.i32,
  4399. 117,
  4400. &[x, lane],
  4401. )
  4402. }
  4403. /// The float value of a register value.
  4404. fn float_of(&mut self, v: Value) -> Result<V, Why> {
  4405. if let Some(&f) = self.floats.get(&v) {
  4406. return Ok(f);
  4407. }
  4408. let x = self.i32_of(v)?;
  4409. Ok(self.as_float(x))
  4410. }
  4411. /// The values of VGPRs `reg..reg + n` as `inst` reads them.
  4412. fn vgprs(&mut self, inst: &Inst, op: &Operand, n: u8) -> Result<Vec<V>, Why> {
  4413. let Operand::Vector { reg, .. } = *op else {
  4414. return Err("a vector operand");
  4415. };
  4416. (0..n)
  4417. .map(|k| {
  4418. let v = inst.read(Reg::V(reg + k)).ok_or("an unread operand")?;
  4419. self.i32_of(v)
  4420. })
  4421. .collect()
  4422. }
  4423. /// LDS (thread-group shared memory) and `ds_swizzle`.
  4424. fn ds(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  4425. let Fields::Ds {
  4426. dst,
  4427. addr,
  4428. data,
  4429. offset0,
  4430. offset1,
  4431. gds,
  4432. } = &inst.fields
  4433. else {
  4434. unreachable!()
  4435. };
  4436. if *gds {
  4437. return Err("GDS");
  4438. }
  4439. let name = inst.name();
  4440. let guard = self.guard(b, i)?;
  4441. let c = self.cur;
  4442. let offset = u32::from(*offset0) | u32::from(*offset1) << 8;
  4443. let dst_reg = match dst {
  4444. Some(Operand::Vector { reg, .. }) => Some(*reg),
  4445. _ => None,
  4446. };
  4447. if name == "ds_swizzle_b32" {
  4448. // Bit 15 set: each lane of a quad picks a lane of it; else lanes
  4449. // of each group of 32 combine their index with and/or/xor masks.
  4450. let quad = offset & 0x8000 != 0
  4451. || offset & 0x1C == 0x1C && offset & 0x380 == 0 && offset >> 10 & 0x1F < 4;
  4452. // Mesh: host quads are threads 4n..4n+3 of a 1D group, as the
  4453. // console's, so quad-local swizzles read through quad operations.
  4454. let mesh_quad = self.s.mesh.is_some() && quad;
  4455. if !mesh_quad {
  4456. self.cross_lane(quad)?;
  4457. }
  4458. // The source sits in the address field.
  4459. let x = self.vgprs(inst, addr.as_ref().ok_or("a swizzle source")?, 1)?[0];
  4460. let lane = self.lane_index();
  4461. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  4462. let src = if offset & 0x8000 != 0 {
  4463. let (three, one) = (k(self, 3), k(self, 1));
  4464. let sel = self.s.m.bin(c, Bin::And, lane, three);
  4465. let sh = self.s.m.bin(c, Bin::Shl, sel, one);
  4466. let pattern = k(self, offset & 0xFF);
  4467. let pick = self.s.m.bin(c, Bin::LShr, pattern, sh);
  4468. let pick = self.s.m.bin(c, Bin::And, pick, three);
  4469. let not3 = k(self, !3);
  4470. let base = self.s.m.bin(c, Bin::And, lane, not3);
  4471. self.s.m.bin(c, Bin::Or, base, pick)
  4472. } else {
  4473. let and = k(self, offset & 0x1F | !0x1F);
  4474. let or = k(self, offset >> 5 & 0x1F);
  4475. let xor = k(self, offset >> 10 & 0x1F);
  4476. let t = self.s.m.bin(c, Bin::And, lane, and);
  4477. let t = self.s.m.bin(c, Bin::Or, t, or);
  4478. self.s.m.bin(c, Bin::Xor, t, xor)
  4479. };
  4480. let r = if mesh_quad {
  4481. self.quad_pick(x, src)
  4482. } else {
  4483. self.read_lane(x, src)
  4484. };
  4485. let reg = dst_reg.ok_or("a swizzle result")?;
  4486. self.write(inst, Reg::V(reg), r, guard);
  4487. return Ok(());
  4488. }
  4489. if name == "ds_bpermute_b32" {
  4490. // Backward permute: no LDS is touched. Each lane takes the data
  4491. // register of the lane its address names, (address + offset) / 4
  4492. // within the wave; a source lane outside EXEC gives 0. (
  4493. // the title's checkerboard shadow-mask generators read their
  4494. // neighbours' samples with it; without them every shadowed light
  4495. // was multiplied by an empty mask.)
  4496. // shortcut: a source lane that is not at this instruction on the
  4497. // host (it left through a branch, not a guard) is read as the
  4498. // host gives it; the console reads 0.
  4499. self.cross_lane(false)?;
  4500. if self.exchange.as_ref().is_some_and(|e| !e.1) {
  4501. // a console wave of 64 run as two host waves: the lane named
  4502. // may be in the other one
  4503. return Err("a lane permute across two host waves");
  4504. }
  4505. let at = self.vgprs(inst, addr.as_ref().ok_or("a permute address")?, 1)?[0];
  4506. let x = self.vgprs(inst, data.first().ok_or("a permute source")?, 1)?[0];
  4507. let o = self.s.m.i32(offset);
  4508. let at = self.s.m.bin(c, Bin::Add, at, o);
  4509. let two = self.s.m.i32(2);
  4510. let src = self.s.m.bin(c, Bin::LShr, at, two);
  4511. let last = self.s.m.i32(self.wave() - 1);
  4512. let src = self.s.m.bin(c, Bin::And, src, last);
  4513. let x = match guard {
  4514. Some(g) => {
  4515. let z = self.s.m.i32(0);
  4516. self.s.m.select(c, g, x, z)
  4517. }
  4518. None => x,
  4519. };
  4520. let r = self.read_lane(x, src);
  4521. let reg = dst_reg.ok_or("a permute result")?;
  4522. self.write(inst, Reg::V(reg), r, guard);
  4523. return Ok(());
  4524. }
  4525. if self.s.lds_dwords == 0 {
  4526. return Err("LDS the program does not allocate");
  4527. }
  4528. let a = self.vgprs(inst, addr.as_ref().ok_or("an LDS address")?, 1)?[0];
  4529. // shortcut: LDS addresses are taken as dword-aligned and in bounds
  4530. // (out-of-bounds console accesses read 0 and drop writes).
  4531. let dword = |l: &mut Self, bytes: u32| -> V {
  4532. let c = l.cur;
  4533. let o = l.s.m.i32(bytes);
  4534. let at = l.s.m.bin(c, Bin::Add, a, o);
  4535. let two = l.s.m.i32(2);
  4536. let index = l.s.m.bin(c, Bin::LShr, at, two);
  4537. let lds = l.s.lds();
  4538. l.s.m.element(c, lds, index)
  4539. };
  4540. let width = |n: &str| match n.rsplit('_').next() {
  4541. Some("b64") => 2,
  4542. Some("b96") => 3,
  4543. Some("b128") => 4,
  4544. _ => 1,
  4545. };
  4546. // (byte offset, dwords) per element; read2/write2 scale their two
  4547. // offsets by the element size (×64 for st64).
  4548. let pair = |n: &str| -> Vec<(u32, u32)> {
  4549. let w = width(n);
  4550. let scale = 4 * w * if n.contains("st64") { 64 } else { 1 };
  4551. vec![
  4552. (u32::from(*offset0) * scale, w),
  4553. (u32::from(*offset1) * scale, w),
  4554. ]
  4555. };
  4556. // Bytes and halves: the dword holding them, and their bit position
  4557. // in it (naturally aligned, so they never straddle dwords).
  4558. // `_d16` reads fill a register's low half (`_d16_hi` its high half)
  4559. // and keep the other; `_d16_hi` writes take the data's high half.
  4560. let base = name.trim_end_matches("_hi").trim_end_matches("_d16");
  4561. let sub = match base {
  4562. "ds_read_u8" | "ds_read_i8" | "ds_write_b8" => Some(8u32),
  4563. "ds_read_u16" | "ds_read_i16" | "ds_write_b16" => Some(16),
  4564. _ => None,
  4565. };
  4566. let sub = sub.filter(|_| {
  4567. base == name
  4568. || name.ends_with("_d16") && base.starts_with("ds_read")
  4569. || name.ends_with("_d16_hi")
  4570. });
  4571. if let Some(bits) = sub {
  4572. let p = dword(self, offset);
  4573. let o = self.s.m.i32(offset);
  4574. let at = self.s.m.bin(c, Bin::Add, a, o);
  4575. let three = self.s.m.i32(3);
  4576. let byte = self.s.m.bin(c, Bin::And, at, three);
  4577. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  4578. let mask = self.s.m.i32((1u32 << bits) - 1);
  4579. if name.starts_with("ds_read") {
  4580. let reg = dst_reg.ok_or("an LDS read result")?;
  4581. let w = self.s.m.load(c, p);
  4582. let x = self.s.m.bin(c, Bin::LShr, w, sh);
  4583. let x = if base.contains("_i") {
  4584. let k = self.s.m.i32(32 - bits);
  4585. let x = self.s.m.bin(c, Bin::Shl, x, k);
  4586. self.s.m.bin(c, Bin::AShr, x, k)
  4587. } else {
  4588. self.s.m.bin(c, Bin::And, x, mask)
  4589. };
  4590. let x = if base == name {
  4591. x
  4592. } else {
  4593. let old = match inst.read(Reg::V(reg)) {
  4594. Some(v) => self.i32_of(v)?,
  4595. None => self.s.m.i32(0),
  4596. };
  4597. let half = self.s.m.i32(0xFFFF);
  4598. let x = self.s.m.bin(c, Bin::And, x, half);
  4599. let (x, keep) = if name.ends_with("_hi") {
  4600. let k16 = self.s.m.i32(16);
  4601. (self.s.m.bin(c, Bin::Shl, x, k16), half)
  4602. } else {
  4603. (x, self.s.m.i32(0xFFFF_0000))
  4604. };
  4605. let old = self.s.m.bin(c, Bin::And, old, keep);
  4606. self.s.m.bin(c, Bin::Or, old, x)
  4607. };
  4608. self.write(inst, Reg::V(reg), x, guard);
  4609. } else {
  4610. // Clear, then set: two atomics, so lanes writing other
  4611. // bytes of the dword keep theirs.
  4612. let mut x = self.vgprs(inst, data.first().ok_or("an LDS write")?, 1)?[0];
  4613. if name != base {
  4614. // The data's high half.
  4615. let k16 = self.s.m.i32(16);
  4616. x = self.s.m.bin(c, Bin::LShr, x, k16);
  4617. }
  4618. let x = self.s.m.bin(c, Bin::And, x, mask);
  4619. let x = self.s.m.bin(c, Bin::Shl, x, sh);
  4620. let m = self.s.m.bin(c, Bin::Shl, mask, sh);
  4621. let ones = self.s.m.i32(u32::MAX);
  4622. let keep = self.s.m.bin(c, Bin::Xor, m, ones);
  4623. use super::bitcode::Rmw;
  4624. let at = self.begin_guarded(guard);
  4625. self.s.m.atomic(self.cur, Rmw::And, p, keep);
  4626. self.s.m.atomic(self.cur, Rmw::Or, p, x);
  4627. self.end_guarded(at, &[]);
  4628. }
  4629. return Ok(());
  4630. }
  4631. if let Some(rest) = name.strip_prefix("ds_read") {
  4632. let elements = if rest.starts_with('2') {
  4633. pair(name)
  4634. } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") {
  4635. vec![(offset, width(name))]
  4636. } else {
  4637. return Err("an LDS read of bytes or halves");
  4638. };
  4639. let reg = dst_reg.ok_or("an LDS read result")?;
  4640. let mut n = 0;
  4641. for (off, w) in elements {
  4642. for k in 0..w {
  4643. let p = dword(self, off + 4 * k);
  4644. let x = self.s.m.load(self.cur, p);
  4645. self.write(inst, Reg::V(reg + n), x, guard);
  4646. n += 1;
  4647. }
  4648. }
  4649. return Ok(());
  4650. }
  4651. if let Some(rest) = name.strip_prefix("ds_write") {
  4652. let elements = if rest.starts_with('2') {
  4653. pair(name)
  4654. } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") {
  4655. vec![(offset, width(name))]
  4656. } else {
  4657. return Err("an LDS write of bytes or halves");
  4658. };
  4659. let mut stores = Vec::new();
  4660. for (e, (off, w)) in elements.into_iter().enumerate() {
  4661. let vals = self.vgprs(inst, data.get(e).ok_or("an LDS write")?, w as u8)?;
  4662. for (k, x) in vals.into_iter().enumerate() {
  4663. stores.push((off + 4 * k as u32, x));
  4664. }
  4665. }
  4666. let at = self.begin_guarded(guard);
  4667. for (off, x) in stores {
  4668. let p = dword(self, off);
  4669. self.s.m.store(self.cur, p, x);
  4670. }
  4671. self.end_guarded(at, &[]);
  4672. return Ok(());
  4673. }
  4674. // Atomics: the old value returns with `_rtn`.
  4675. let op = name
  4676. .strip_prefix("ds_")
  4677. .map(|n| n.replace("_rtn", ""))
  4678. .ok_or("an LDS operation")?;
  4679. use super::bitcode::Rmw;
  4680. let rmw = match op.as_str() {
  4681. "add_u32" => Some(Rmw::Add),
  4682. "sub_u32" => Some(Rmw::Sub),
  4683. "and_b32" => Some(Rmw::And),
  4684. "or_b32" => Some(Rmw::Or),
  4685. "xor_b32" => Some(Rmw::Xor),
  4686. "min_i32" => Some(Rmw::Min),
  4687. "max_i32" => Some(Rmw::Max),
  4688. "min_u32" => Some(Rmw::UMin),
  4689. "max_u32" => Some(Rmw::UMax),
  4690. "wrxchg_b32" => Some(Rmw::Xchg),
  4691. "cmpst_b32" | "max_f32" | "min_f32" => None,
  4692. _ => return Err("an LDS operation"),
  4693. };
  4694. let v0 = self.vgprs(inst, data.first().ok_or("an LDS atomic")?, 1)?[0];
  4695. let v1 = match data.get(1) {
  4696. Some(d) => Some(self.vgprs(inst, d, 1)?[0]),
  4697. None => None,
  4698. };
  4699. let old_reg = dst_reg.and_then(|r| inst.read(Reg::V(r)).map(|v| (r, v)));
  4700. let outside = match old_reg {
  4701. Some((_, v)) => self.i32_of(v).unwrap_or(self.s.m.i32(0)),
  4702. None => self.s.m.i32(0),
  4703. };
  4704. let p = dword(self, offset);
  4705. if let Some(max) = match op.as_str() {
  4706. "max_f32" => Some(true),
  4707. "min_f32" => Some(false),
  4708. _ => None,
  4709. } {
  4710. let at = self.begin_guarded(guard);
  4711. let r = self.lds_float_min_max(p, v0, max);
  4712. let r = self.end_guarded(at, &[(r, outside)])[0];
  4713. if let Some(reg) = dst_reg {
  4714. self.write(inst, Reg::V(reg), r, None);
  4715. }
  4716. return Ok(());
  4717. }
  4718. let at = self.begin_guarded(guard);
  4719. let r = match rmw {
  4720. Some(op) => self.s.m.atomic(self.cur, op, p, v0),
  4721. // Compare with data0, store data1.
  4722. None => self
  4723. .s
  4724. .m
  4725. .cmpxchg(self.cur, p, v0, v1.ok_or("an LDS compare")?),
  4726. };
  4727. let r = self.end_guarded(at, &[(r, outside)])[0];
  4728. if let Some(reg) = dst_reg {
  4729. self.write(inst, Reg::V(reg), r, None);
  4730. }
  4731. Ok(())
  4732. }
  4733. /// `ds_max_f32` (`max`) or `ds_min_f32` on the LDS dword at `p` with
  4734. /// the float bits `data`; the old bits return.
  4735. ///
  4736. /// DXIL has no float atomics on group-shared memory, so this is a
  4737. /// compare-exchange loop around [`Lower::lds_float_pick`], which gives
  4738. /// what RDNA2 writes (measured on gfx1036, reported on the pull
  4739. /// request): an sNaN, data first, then memory, is written quieted;
  4740. /// otherwise a NaN loses to a number (two quiet NaNs give the data);
  4741. /// numbers compare as floats with -0 below +0.
  4742. // shortcut: f32 denormals compare as kept; with the console's MODE
  4743. // flushing them they would order as ±0 first (MODE is not modelled).
  4744. fn lds_float_min_max(&mut self, p: V, data: V, max: bool) -> V {
  4745. let pre = self.cur;
  4746. let init = self.s.m.load(pre, p);
  4747. let (lp, exit) = (self.s.m.new_block(), self.s.m.new_block());
  4748. self.s.m.terminate(pre, Term::Br(lp));
  4749. let i32t = self.s.t.i32;
  4750. let old = self.s.m.phi(lp, i32t);
  4751. self.cur = lp;
  4752. let new = self.lds_float_pick(old, data, max);
  4753. let prev = self.s.m.cmpxchg(lp, p, old, new);
  4754. let done = self.s.m.cmp(lp, pred::EQ, prev, old);
  4755. self.s.m.set_phi(old, vec![(init, pre), (prev, lp)]);
  4756. self.s.m.terminate(lp, Term::CondBr(done, exit, lp));
  4757. self.cur = exit;
  4758. old
  4759. }
  4760. /// What `ds_max_f32` (`max`) or `ds_min_f32` writes over the dword
  4761. /// `mem` with `data` (float bits; see [`Lower::lds_float_min_max`]).
  4762. fn lds_float_pick(&mut self, mem: V, data: V, max: bool) -> V {
  4763. let c = self.cur;
  4764. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  4765. let (abs_mask, inf, quiet, zero) = (
  4766. k(self, 0x7FFF_FFFF),
  4767. k(self, 0x7F80_0000),
  4768. k(self, 0x40_0000),
  4769. k(self, 0),
  4770. );
  4771. let nan = |l: &mut Self, x: V| {
  4772. let m = l.s.m.bin(c, Bin::And, x, abs_mask);
  4773. l.s.m.cmp(c, pred::IUGT, m, inf)
  4774. };
  4775. let snan = |l: &mut Self, x: V| {
  4776. let n = nan(l, x);
  4777. let q = l.s.m.bin(c, Bin::And, x, quiet);
  4778. let sig = l.s.m.cmp(c, pred::EQ, q, zero);
  4779. l.s.m.bin(c, Bin::And, n, sig)
  4780. };
  4781. // A total order of the numbers as signed integers, -0 below +0:
  4782. // negative floats' magnitude bits reversed.
  4783. let key = |l: &mut Self, x: V| {
  4784. let k31 = l.s.m.i32(31);
  4785. let sign = l.s.m.bin(c, Bin::AShr, x, k31);
  4786. let flip = l.s.m.bin(c, Bin::And, sign, abs_mask);
  4787. l.s.m.bin(c, Bin::Xor, x, flip)
  4788. };
  4789. let (dk, mk) = (key(self, data), key(self, mem));
  4790. let take = self
  4791. .s
  4792. .m
  4793. .cmp(c, if max { pred::SGT } else { pred::SLT }, dk, mk);
  4794. let r = self.s.m.select(c, take, data, mem);
  4795. let (dn, mn) = (nan(self, data), nan(self, mem));
  4796. // One NaN: the number; two quiet NaNs: the data.
  4797. let r = self.s.m.select(c, mn, data, r);
  4798. let both = self.s.m.bin(c, Bin::And, dn, mn);
  4799. let only_data = {
  4800. let t = self.s.m.bool(true);
  4801. let not_both = self.s.m.bin(c, Bin::Xor, both, t);
  4802. self.s.m.bin(c, Bin::And, dn, not_both)
  4803. };
  4804. let r = self.s.m.select(c, only_data, mem, r);
  4805. // Signalling NaNs win, quieted: the data's first.
  4806. let qm = self.s.m.bin(c, Bin::Or, mem, quiet);
  4807. let sm = snan(self, mem);
  4808. let r = self.s.m.select(c, sm, qm, r);
  4809. let qd = self.s.m.bin(c, Bin::Or, data, quiet);
  4810. let sd = snan(self, data);
  4811. self.s.m.select(c, sd, qd, r)
  4812. }
  4813. // ---- instructions ----
  4814. // ---- instructions ----
  4815. fn inst(&mut self, b: usize, i: usize) -> Result<(), Stop> {
  4816. let inst: &'a Inst = &self.x.p.blocks[b].insts[i];
  4817. let offset = inst.machine.offset;
  4818. let name = inst.name();
  4819. self.local_ok = name.starts_with("s_bcnt1_i32_")
  4820. || name.starts_with("s_ff1_i32_")
  4821. || name.starts_with("v_mbcnt_");
  4822. self.mask_ok = match self.mask_data {
  4823. MaskData::Console => true,
  4824. MaskData::Host => {
  4825. name.starts_with("s_bcnt1_i32_")
  4826. || name.starts_with("s_ff1_i32_")
  4827. || name.starts_with("v_mbcnt_")
  4828. || matches!(
  4829. name,
  4830. "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_u64" | "s_cmp_lg_u64"
  4831. )
  4832. }
  4833. // Mesh: only "do all lanes hold the first lane's value?" (`uniform_test`), which
  4834. // each host wave answers for itself.
  4835. MaskData::None => self.uniform_test(inst),
  4836. };
  4837. let effect = matches!(inst.fields, Fields::Exp { .. })
  4838. || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
  4839. || name.contains("store")
  4840. || name.contains("atomic")
  4841. || name == "s_barrier"
  4842. || matches!(inst.fields, Fields::Ds { .. })
  4843. && !(name.starts_with("ds_read")
  4844. || name.starts_with("ds_swizzle")
  4845. || name.contains("permute"));
  4846. if self.split_lds
  4847. && matches!(inst.fields, Fields::Ds { .. })
  4848. && !(name.starts_with("ds_swizzle") || name.contains("permute"))
  4849. && self.lds_meet.as_ref().is_none_or(|(all, _)| all[b])
  4850. {
  4851. // the two host waves of a console wave meet before each LDS access: what the other
  4852. // half wrote is visible, and what it still reads is not overwritten
  4853. let mode = self.s.m.i32(meeting_mode());
  4854. let void = self.s.t.void;
  4855. self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  4856. }
  4857. let r = match &inst.fields {
  4858. Fields::Sop { .. } => self.sop(inst),
  4859. Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()),
  4860. Fields::Sopp { .. } if name == "s_barrier" => {
  4861. // Thread-group sync with a shared-memory fence, and a UAV
  4862. // fence when the program writes UAVs (the waits before an
  4863. // s_barrier make those writes visible on the console).
  4864. let mut mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 };
  4865. // Without the wait for the group (bit 0) where not every
  4866. // lane arrives, or where the switch says so.
  4867. let waits = match super::group_sync() {
  4868. 0 => false,
  4869. 1 => !self.fence_only.contains(&b),
  4870. _ => true,
  4871. };
  4872. if !waits {
  4873. mode &= !1;
  4874. }
  4875. let mode = self.s.m.i32(mode);
  4876. let void = self.s.t.void;
  4877. self.s
  4878. .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  4879. Ok(())
  4880. }
  4881. Fields::Sopp { .. } => Ok(()),
  4882. Fields::Smem { .. } => self.smem(inst, (b, i)),
  4883. Fields::Valu(_) if name.starts_with("v_interp_") => self.interp(inst, (b, i)),
  4884. Fields::Valu(_) => self.valu(inst, b, i),
  4885. Fields::Vintrp { .. } => self.interp(inst, (b, i)),
  4886. // The ray and node test. A failure is a refusal at once: an
  4887. // instruction without a side effect otherwise only stops the
  4888. // program where its results are needed, and two trace programs
  4889. // came out without their test that way.
  4890. Fields::Image { .. } if name.starts_with("image_bvh") => {
  4891. return self
  4892. .bvh(inst, b, i)
  4893. .map_err(|why| unsupported(offset, why));
  4894. }
  4895. Fields::Image { .. } => self.image(inst, b, i),
  4896. Fields::Buffer { .. } => self.buffer(inst, b, i),
  4897. Fields::Exp { .. } => self.export(b, i),
  4898. Fields::Ds { .. } => self.ds(inst, b, i),
  4899. Fields::Flat { .. } if name.starts_with("global_") => self.flat(inst, b, i),
  4900. Fields::Flat { .. } => Err("flat memory"),
  4901. };
  4902. match r {
  4903. Ok(()) => Ok(()),
  4904. Err(why) if effect => Err(unsupported(offset, why)),
  4905. Err(why) => {
  4906. for &(_, v) in &inst.writes {
  4907. self.vals.insert(v, Val::Missing(why));
  4908. }
  4909. Ok(())
  4910. }
  4911. }
  4912. }
  4913. /// The two host waves of a console wave meet (a group barrier with a shared-memory
  4914. /// fence): LDS writes before are seen by reads after.
  4915. fn lds_meeting(&mut self) {
  4916. let mode = self.s.m.i32(meeting_mode());
  4917. let void = self.s.t.void;
  4918. self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  4919. }
  4920. /// Whether `v` is a register no program reads as a number: a descriptor dword without
  4921. /// a host value ([`Self::stale`]), a lane mask's dword (outside compute, where a ballot
  4922. /// gives the mask as data), or a join of only such values. Compiled code joins numbers
  4923. /// with numbers: where one of these meets numbers at a join, the register is dead on
  4924. /// that path (a variable set in one arm of a branch, its use behind a flag kept in a
  4925. /// VGPR).
  4926. fn dead(&self, v: Value, seen: &mut Vec<Value>) -> bool {
  4927. if self.stale.contains(&v) {
  4928. return true;
  4929. }
  4930. let st = self.x.st;
  4931. if self.mask_data != MaskData::Console
  4932. && (st.masks.contains_key(&v) || st.highs.contains_key(&v))
  4933. {
  4934. return true;
  4935. }
  4936. let Some(&(b, i)) = self.phi_at.get(&v) else {
  4937. return false;
  4938. };
  4939. if seen.contains(&v) {
  4940. return true;
  4941. }
  4942. seen.push(v);
  4943. self.x.p.blocks[b].phis[i]
  4944. .args
  4945. .iter()
  4946. .all(|&a| self.dead(a, seen))
  4947. }
  4948. /// `s_bcnt1_i32_b*` of the lanes that differ from the first lane's value:
  4949. /// `v_readfirstlane_b32 s, v`, `v_cmp_eq_u32 m, s, v`, `s_xor_b* d, m, exec`. The
  4950. /// compiler tests a value for being the same in the whole wave this way, to take a
  4951. /// scalar path; both paths give each lane the same result, so the lanes of a host
  4952. /// wave may ask it of their own first lane, whatever the wave's size.
  4953. fn uniform_test(&self, inst: &Inst) -> bool {
  4954. let p = self.x.p;
  4955. let writer = |v: Value| -> Option<&'a Inst> {
  4956. let b = *self.def_block.get(&v)?;
  4957. p.blocks[b]
  4958. .insts
  4959. .iter()
  4960. .find(|i| i.writes.iter().any(|w| w.1 == v))
  4961. };
  4962. let scalar = |i: &Inst, op: &Operand| match *op {
  4963. Operand::Scalar { code, .. } if code != NULL && code != EXEC => i.read(Reg::S(code)),
  4964. _ => None,
  4965. };
  4966. if !inst.name().starts_with("s_bcnt1_i32_") {
  4967. return false;
  4968. }
  4969. let Fields::Sop { src, .. } = &inst.fields else {
  4970. return false;
  4971. };
  4972. let Some(xor) = src.first().and_then(|o| scalar(inst, o)).and_then(writer) else {
  4973. return false;
  4974. };
  4975. let Fields::Sop { src, .. } = &xor.fields else {
  4976. return false;
  4977. };
  4978. if !matches!(xor.name(), "s_xor_b64" | "s_xor_b32")
  4979. || !src
  4980. .iter()
  4981. .any(|o| matches!(o, Operand::Scalar { code: EXEC, .. }))
  4982. {
  4983. return false;
  4984. }
  4985. let Some(cmp) = src.iter().find_map(|o| scalar(xor, o)).and_then(writer) else {
  4986. return false;
  4987. };
  4988. let Fields::Valu(f) = &cmp.fields else {
  4989. return false;
  4990. };
  4991. if !matches!(cmp.name(), "v_cmp_eq_u32" | "v_cmp_eq_i32") || f.sdwa.is_some() || f.dpp.is_some() {
  4992. return false;
  4993. }
  4994. let lanes = f.src.iter().find_map(|o| match *o {
  4995. Operand::Vector { reg, .. } => cmp.read(Reg::V(reg)),
  4996. _ => None,
  4997. });
  4998. let first = f.src.iter().find_map(|o| scalar(cmp, o)).and_then(writer);
  4999. lanes.is_some()
  5000. && first.is_some_and(|fl| {
  5001. fl.name() == "v_readfirstlane_b32"
  5002. && matches!(&fl.fields, Fields::Valu(g)
  5003. if matches!(g.src.first(), Some(&Operand::Vector { reg, .. })
  5004. if fl.read(Reg::V(reg)) == lanes))
  5005. })
  5006. }
  5007. fn is_mask(&self, v: Option<Value>) -> bool {
  5008. v.is_some_and(|v| self.x.st.masks.contains_key(&v))
  5009. }
  5010. fn sop(&mut self, inst: &Inst) -> Result<(), Why> {
  5011. let Fields::Sop { dst, src, imm } = &inst.fields else {
  5012. unreachable!()
  5013. };
  5014. let name = inst.name();
  5015. let scc = inst.write(Reg::Scc);
  5016. let dst_code = match dst {
  5017. Some(Operand::Scalar { code, .. }) => Some(*code),
  5018. _ => None,
  5019. };
  5020. let lo = dst_code.and_then(|c| inst.write(Reg::S(c)));
  5021. if inst.write(Reg::S(EXEC)).is_some() || self.is_mask(lo) {
  5022. return Err(LANE_MASK);
  5023. }
  5024. if matches!(
  5025. name,
  5026. "s_setreg_imm32_b32" | "s_setreg_b32" | "s_swappc_b64" | "s_version"
  5027. ) || name.starts_with("s_waitcnt")
  5028. {
  5029. // shortcut: the float MODE register is not modelled; s_swappc_b64 is the
  5030. // vertex fetch call, whose results arrive as inputs.
  5031. return Err("a register the emitter does not model");
  5032. }
  5033. if name == "s_getpc_b64" {
  5034. // The address of the next instruction is no number the host has: tables in
  5035. // the code are read by their tracked address. As a number the counter is
  5036. // that instruction's offset in the code, so an address paths join before
  5037. // one load is the byte in the code, whichever table each path took
  5038. // (resource tracking gives such a join as the computed term, with no base).
  5039. let z = self.s.m.i32(0);
  5040. let at = self.s.m.i32(inst.machine.offset as u32 + 4);
  5041. let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1)));
  5042. self.set(lo, Val::I32(at));
  5043. self.set(hi, Val::I32(z));
  5044. return Ok(());
  5045. }
  5046. let c = self.cur;
  5047. let src32 = |l: &mut Self, k: usize| -> Result<V, Why> {
  5048. // SOPK arithmetic reads its destination as the first source.
  5049. if k == 0 && matches!(name, "s_addk_i32" | "s_mulk_i32") {
  5050. let d = dst.as_ref().ok_or("a missing operand")?;
  5051. return l.operand(inst, d);
  5052. }
  5053. let op = src.get(k).ok_or("a missing operand")?;
  5054. l.operand(inst, op)
  5055. };
  5056. let sext16 = |l: &mut Self| l.s.m.i32(i32::from(imm.unwrap_or(0) as i16) as u32);
  5057. // Dword `h` of 64-bit source `k` (inline constants sign-extend).
  5058. let half = |l: &mut Self, k: usize, h: u8| -> Result<V, Why> {
  5059. match src.get(k) {
  5060. Some(&Operand::Scalar { code, .. }) if code != NULL => {
  5061. let v = inst.read(Reg::S(code + h)).ok_or("an unread operand")?;
  5062. l.i32_of(v)
  5063. }
  5064. Some(op) if h == 0 => l.operand(inst, op),
  5065. Some(Operand::Const(k)) => {
  5066. let x = crate::resource::inline(*k).ok_or("a special operand")?;
  5067. Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 }))
  5068. }
  5069. // Of a signed operand, a literal sign-extends too.
  5070. Some(&Operand::Literal(x)) if name.ends_with("_i64") => {
  5071. Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 }))
  5072. }
  5073. _ => Ok(l.s.m.i32(0)),
  5074. }
  5075. };
  5076. if let Some(op) = name.strip_prefix("s_bitcmp") {
  5077. // SCC is whether bit src1 (mod 32, or mod 64 for the 64-bit form)
  5078. // of src0 is clear (bitcmp0) or set (bitcmp1).
  5079. let (bit, k31) = (src32(self, 1)?, self.s.m.i32(31));
  5080. let idx = self.s.m.bin(c, Bin::And, bit, k31);
  5081. let word = if op.ends_with("_b64") {
  5082. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5083. let k32 = self.s.m.i32(32);
  5084. let upper = self.s.m.bin(c, Bin::And, bit, k32);
  5085. let z = self.s.m.i32(0);
  5086. let upper = self.s.m.cmp(c, pred::NE, upper, z);
  5087. self.s.m.select(c, upper, b, a)
  5088. } else {
  5089. src32(self, 0)?
  5090. };
  5091. let shifted = self.s.m.bin(c, Bin::LShr, word, idx);
  5092. let one = self.s.m.i32(1);
  5093. let tested = self.s.m.bin(c, Bin::And, shifted, one);
  5094. let want = self.s.m.i32(u32::from(op.starts_with('1')));
  5095. let r = self.s.m.cmp(c, pred::EQ, tested, want);
  5096. self.set(scc, Val::Bit(r));
  5097. return Ok(());
  5098. }
  5099. if let Some(op) = name.strip_prefix("s_cmp_").filter(|o| o.ends_with("_u64")) {
  5100. // eq and lg only: both dwords.
  5101. let mut r = None;
  5102. for h in 0..2 {
  5103. let (a, b) = (half(self, 0, h)?, half(self, 1, h)?);
  5104. let e = self.s.m.cmp(c, pred::EQ, a, b);
  5105. r = Some(match r {
  5106. Some(x) => self.s.m.bin(c, Bin::And, x, e),
  5107. None => e,
  5108. });
  5109. }
  5110. let mut r = r.expect("two dwords");
  5111. if op.starts_with("lg") {
  5112. let t = self.s.m.bool(true);
  5113. r = self.s.m.bin(c, Bin::Xor, r, t);
  5114. }
  5115. self.set(scc, Val::Bit(r));
  5116. return Ok(());
  5117. }
  5118. if let Some(op) = name.strip_prefix("s_cmp_").or(name.strip_prefix("s_cmpk_")) {
  5119. let (a, b) = if name.starts_with("s_cmpk_") {
  5120. let b = if op.ends_with("_i32") {
  5121. sext16(self)
  5122. } else {
  5123. self.s.m.i32(u32::from(imm.unwrap_or(0)))
  5124. };
  5125. (src32(self, 0)?, b)
  5126. } else {
  5127. if op.ends_with("64") {
  5128. return Err("a 64-bit scalar compare");
  5129. }
  5130. (src32(self, 0)?, src32(self, 1)?)
  5131. };
  5132. let signed = op.ends_with("_i32");
  5133. let p = match &op[..2] {
  5134. "eq" => pred::EQ,
  5135. "lg" => pred::NE,
  5136. "gt" if signed => pred::SGT,
  5137. "ge" if signed => pred::SGE,
  5138. "lt" if signed => pred::SLT,
  5139. "le" if signed => pred::SLE,
  5140. "gt" => pred::IUGT,
  5141. "ge" => pred::IUGE,
  5142. "lt" => pred::IULT,
  5143. "le" => pred::IULE,
  5144. _ => return Err("a scalar compare"),
  5145. };
  5146. let r = self.s.m.cmp(c, p, a, b);
  5147. self.set(scc, Val::Bit(r));
  5148. return Ok(());
  5149. }
  5150. let wide = name.ends_with("_b64") || name.ends_with("_u64") || name.ends_with("_i64");
  5151. if wide {
  5152. let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1)));
  5153. let nonzero = |l: &mut Self, a: V, b: V| {
  5154. let o = l.s.m.bin(c, Bin::Or, a, b);
  5155. let z = l.s.m.i32(0);
  5156. l.s.m.cmp(c, pred::NE, o, z)
  5157. };
  5158. return match name {
  5159. "s_quadmask_b64" => {
  5160. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5161. let low = self.quad_mask(a);
  5162. let high = self.quad_mask(b);
  5163. let k8 = self.s.m.i32(8);
  5164. let high = self.s.m.bin(c, Bin::Shl, high, k8);
  5165. let mask = self.s.m.bin(c, Bin::Or, low, high);
  5166. let zero = self.s.m.i32(0);
  5167. self.set(lo, Val::I32(mask));
  5168. self.set(hi, Val::I32(zero));
  5169. let nonzero = self.s.m.cmp(c, pred::NE, mask, zero);
  5170. self.set(scc, Val::Bit(nonzero));
  5171. Ok(())
  5172. }
  5173. "s_bcnt1_i32_b64" => {
  5174. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5175. let i32t = self.s.t.i32;
  5176. let na = self
  5177. .s
  5178. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[a]);
  5179. let nb = self
  5180. .s
  5181. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[b]);
  5182. let r = self.s.m.bin(c, Bin::Add, na, nb);
  5183. self.set(lo, Val::I32(r));
  5184. let z = self.s.m.i32(0);
  5185. let s = self.s.m.cmp(c, pred::NE, r, z);
  5186. self.set(scc, Val::Bit(s));
  5187. Ok(())
  5188. }
  5189. "s_ff1_i32_b64" => {
  5190. // The lowest set bit; -1 for none (as DXIL's first bit low).
  5191. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5192. let i32t = self.s.t.i32;
  5193. let fa = self
  5194. .s
  5195. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[a]);
  5196. let fb = self
  5197. .s
  5198. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[b]);
  5199. let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32));
  5200. let fb32 = self.s.m.bin(c, Bin::Add, fb, k32);
  5201. let none = self.s.m.cmp(c, pred::EQ, b, z);
  5202. let fb = self.s.m.select(c, none, fb, fb32);
  5203. let low = self.s.m.cmp(c, pred::NE, a, z);
  5204. let r = self.s.m.select(c, low, fa, fb);
  5205. self.set(lo, Val::I32(r));
  5206. Ok(())
  5207. }
  5208. "s_and_b64" | "s_or_b64" | "s_xor_b64" | "s_andn2_b64" | "s_orn2_b64"
  5209. | "s_nand_b64" | "s_nor_b64" | "s_xnor_b64" | "s_not_b64" => {
  5210. let ones = self.s.m.i32(u32::MAX);
  5211. let mut r = Vec::new();
  5212. for h in 0..2u8 {
  5213. let a = half(self, 0, h)?;
  5214. let x = if name == "s_not_b64" {
  5215. self.s.m.bin(c, Bin::Xor, a, ones)
  5216. } else {
  5217. let mut b = half(self, 1, h)?;
  5218. if name.contains("n2") {
  5219. b = self.s.m.bin(c, Bin::Xor, b, ones);
  5220. }
  5221. let op = match &name[2..5] {
  5222. "and" | "nan" => Bin::And,
  5223. "or_" | "orn" | "nor" => Bin::Or,
  5224. _ => Bin::Xor,
  5225. };
  5226. let x = self.s.m.bin(c, op, a, b);
  5227. if matches!(name, "s_nand_b64" | "s_nor_b64" | "s_xnor_b64") {
  5228. self.s.m.bin(c, Bin::Xor, x, ones)
  5229. } else {
  5230. x
  5231. }
  5232. };
  5233. r.push(x);
  5234. }
  5235. self.set(lo, Val::I32(r[0]));
  5236. self.set(hi, Val::I32(r[1]));
  5237. let s = nonzero(self, r[0], r[1]);
  5238. self.set(scc, Val::Bit(s));
  5239. Ok(())
  5240. }
  5241. "s_lshl_b64" | "s_lshr_b64" | "s_ashr_i64" => {
  5242. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5243. let n = src32(self, 1)?;
  5244. let i64t = self.s.m.int(64);
  5245. self.s.flags |= flags::INT64;
  5246. let a = self.s.m.cast(c, Cast::ZExt, a, i64t);
  5247. let b = self.s.m.cast(c, Cast::ZExt, b, i64t);
  5248. let k32 = self.s.m.int_const(i64t, 32);
  5249. let b = self.s.m.bin(c, Bin::Shl, b, k32);
  5250. let x = self.s.m.bin(c, Bin::Or, a, b);
  5251. let k63 = self.s.m.i32(63);
  5252. let n = self.s.m.bin(c, Bin::And, n, k63);
  5253. let n = self.s.m.cast(c, Cast::ZExt, n, i64t);
  5254. let op = match name {
  5255. "s_lshl_b64" => Bin::Shl,
  5256. "s_lshr_b64" => Bin::LShr,
  5257. _ => Bin::AShr,
  5258. };
  5259. let r = self.s.m.bin(c, op, x, n);
  5260. let rl = self.s.m.cast(c, Cast::Trunc, r, self.s.t.i32);
  5261. let rh = self.s.m.bin(c, Bin::LShr, r, k32);
  5262. let rh = self.s.m.cast(c, Cast::Trunc, rh, self.s.t.i32);
  5263. self.set(lo, Val::I32(rl));
  5264. self.set(hi, Val::I32(rh));
  5265. let s = nonzero(self, rl, rh);
  5266. self.set(scc, Val::Bit(s));
  5267. Ok(())
  5268. }
  5269. "s_mov_b64" => {
  5270. // Each half by itself: two numbers that travel as a pair (two scalars
  5271. // parked in neighbouring VGPR lanes, say) need not both have a value.
  5272. for (h, v) in [(0, lo), (1, hi)] {
  5273. let val = match half(self, 0, h) {
  5274. Ok(a) => Val::I32(a),
  5275. Err(why) => Val::Missing(why),
  5276. };
  5277. self.set(v, val);
  5278. }
  5279. Ok(())
  5280. }
  5281. "s_cselect_b64" => {
  5282. let cond = self.scc_in(inst)?;
  5283. for (h, v) in [(0, lo), (1, hi)] {
  5284. let (a, b) = (half(self, 0, h)?, half(self, 1, h)?);
  5285. let r = self.s.m.select(c, cond, a, b);
  5286. self.set(v, Val::I32(r));
  5287. }
  5288. Ok(())
  5289. }
  5290. _ => Err(name),
  5291. };
  5292. }
  5293. let m = &mut self.s.m;
  5294. let _ = m;
  5295. let (r, carry): (V, Option<V>) = match name {
  5296. "s_mov_b32" => (src32(self, 0)?, None),
  5297. "s_movk_i32" => (sext16(self), None),
  5298. "s_quadmask_b32" => {
  5299. let pixels = src32(self, 0)?;
  5300. (self.quad_mask(pixels), None)
  5301. }
  5302. "s_cselect_b32" => {
  5303. let cond = self.scc_in(inst)?;
  5304. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5305. (self.s.m.select(c, cond, a, b), None)
  5306. }
  5307. "s_brev_b32" => {
  5308. let a = src32(self, 0)?;
  5309. let r = self
  5310. .s
  5311. .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a]);
  5312. (r, None)
  5313. }
  5314. "s_not_b32" => {
  5315. let a = src32(self, 0)?;
  5316. let ones = self.s.m.i32(u32::MAX);
  5317. (self.s.m.bin(c, Bin::Xor, a, ones), None)
  5318. }
  5319. "s_add_u32" | "s_add_i32" | "s_addk_i32" => {
  5320. let a = src32(self, 0)?;
  5321. let b = if name == "s_addk_i32" {
  5322. sext16(self)
  5323. } else {
  5324. src32(self, 1)?
  5325. };
  5326. let r = self.s.m.bin(c, Bin::Add, a, b);
  5327. let carry = if name == "s_add_u32" {
  5328. Some(self.s.m.cmp(c, pred::IULT, r, a))
  5329. } else {
  5330. None
  5331. };
  5332. (r, carry)
  5333. }
  5334. "s_sub_u32" | "s_sub_i32" => {
  5335. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5336. let r = self.s.m.bin(c, Bin::Sub, a, b);
  5337. let carry = (name == "s_sub_u32").then(|| self.s.m.cmp(c, pred::IULT, a, b));
  5338. (r, carry)
  5339. }
  5340. "s_addc_u32" | "s_subb_u32" => {
  5341. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5342. let cin = self.scc_in(inst)?;
  5343. let (r, carry) = self.add_sub_carry(c, name == "s_addc_u32", a, b, Some(cin));
  5344. (r, Some(carry))
  5345. }
  5346. "s_mul_i32" | "s_mulk_i32" => {
  5347. let a = src32(self, 0)?;
  5348. let b = if name == "s_mulk_i32" {
  5349. sext16(self)
  5350. } else {
  5351. src32(self, 1)?
  5352. };
  5353. (self.s.m.bin(c, Bin::Mul, a, b), None)
  5354. }
  5355. "s_mul_hi_u32" | "s_mul_hi_i32" => {
  5356. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5357. (self.mul_hi(a, b, name.ends_with("i32")), None)
  5358. }
  5359. "s_flbit_i32_b32" | "s_flbit_i32" => {
  5360. // The first bit from the top (differing from the sign for
  5361. // the signed form), -1 for none: DXIL's first-bit-high.
  5362. let a = src32(self, 0)?;
  5363. let op = if name == "s_flbit_i32_b32" { 33 } else { 34 };
  5364. let r = self
  5365. .s
  5366. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  5367. (r, None)
  5368. }
  5369. "s_ff1_i32_b32" | "s_bcnt1_i32_b32" => {
  5370. // First set bit (-1 for zero, as DXIL's), or the bit count.
  5371. let a = src32(self, 0)?;
  5372. let op = if name == "s_ff1_i32_b32" { 32 } else { 31 };
  5373. let r = self
  5374. .s
  5375. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  5376. (r, None)
  5377. }
  5378. "s_bfe_u32" | "s_bfe_i32" => {
  5379. // src1: offset in bits 0-4, width in bits 16-22.
  5380. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5381. let (k16, k127) = (self.s.m.i32(16), self.s.m.i32(0x7F));
  5382. let w = self.s.m.bin(c, Bin::LShr, b, k16);
  5383. let w = self.s.m.bin(c, Bin::And, w, k127);
  5384. (self.bfe(a, b, w, name == "s_bfe_i32"), None)
  5385. }
  5386. "s_and_b32" | "s_or_b32" | "s_xor_b32" | "s_andn2_b32" | "s_orn2_b32"
  5387. | "s_nand_b32" | "s_nor_b32" | "s_xnor_b32" => {
  5388. let (a, mut b) = (src32(self, 0)?, src32(self, 1)?);
  5389. let ones = self.s.m.i32(u32::MAX);
  5390. if name.contains("n2") {
  5391. b = self.s.m.bin(c, Bin::Xor, b, ones);
  5392. }
  5393. let op = match &name[2..5] {
  5394. "and" | "nan" => Bin::And,
  5395. "or_" | "orn" | "nor" => Bin::Or,
  5396. _ => Bin::Xor,
  5397. };
  5398. let mut r = self.s.m.bin(c, op, a, b);
  5399. if matches!(name, "s_nand_b32" | "s_nor_b32" | "s_xnor_b32") {
  5400. r = self.s.m.bin(c, Bin::Xor, r, ones);
  5401. }
  5402. (r, None)
  5403. }
  5404. "s_lshl_b32" | "s_lshr_b32" | "s_ashr_i32" => {
  5405. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5406. let k31 = self.s.m.i32(31);
  5407. let b = self.s.m.bin(c, Bin::And, b, k31);
  5408. let op = match name {
  5409. "s_lshl_b32" => Bin::Shl,
  5410. "s_lshr_b32" => Bin::LShr,
  5411. _ => Bin::AShr,
  5412. };
  5413. (self.s.m.bin(c, op, a, b), None)
  5414. }
  5415. "s_lshl1_add_u32" | "s_lshl2_add_u32" | "s_lshl3_add_u32" | "s_lshl4_add_u32" => {
  5416. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5417. let k = self.s.m.i32(u32::from(name.as_bytes()[6] - b'0'));
  5418. let t = self.s.m.bin(c, Bin::Shl, a, k);
  5419. (self.s.m.bin(c, Bin::Add, t, b), None)
  5420. }
  5421. "s_min_u32" | "s_max_u32" | "s_min_i32" | "s_max_i32" => {
  5422. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5423. let p = match name {
  5424. "s_min_u32" => pred::IULT,
  5425. "s_max_u32" => pred::IUGT,
  5426. "s_min_i32" => pred::SLT,
  5427. _ => pred::SGT,
  5428. };
  5429. let t = self.s.m.cmp(c, p, a, b);
  5430. (self.s.m.select(c, t, a, b), None)
  5431. }
  5432. "s_abs_i32" => {
  5433. let a = src32(self, 0)?;
  5434. let z = self.s.m.i32(0);
  5435. let neg = self.s.m.cmp(c, pred::SLT, a, z);
  5436. let n = self.s.m.bin(c, Bin::Sub, z, a);
  5437. (self.s.m.select(c, neg, n, a), None)
  5438. }
  5439. "s_bitset0_b32" | "s_bitset1_b32" => {
  5440. // Sets (clears) bit src[4:0] of the destination it reads.
  5441. let old = self.operand(inst, dst.as_ref().ok_or("a missing operand")?)?;
  5442. let a = src32(self, 0)?;
  5443. let (k31, one) = (self.s.m.i32(31), self.s.m.i32(1));
  5444. let a = self.s.m.bin(c, Bin::And, a, k31);
  5445. let bit = self.s.m.bin(c, Bin::Shl, one, a);
  5446. if name == "s_bitset1_b32" {
  5447. (self.s.m.bin(c, Bin::Or, old, bit), None)
  5448. } else {
  5449. let ones = self.s.m.i32(u32::MAX);
  5450. let nb = self.s.m.bin(c, Bin::Xor, bit, ones);
  5451. (self.s.m.bin(c, Bin::And, old, nb), None)
  5452. }
  5453. }
  5454. "s_bfm_b32" => {
  5455. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5456. let k31 = self.s.m.i32(31);
  5457. let one = self.s.m.i32(1);
  5458. let a = self.s.m.bin(c, Bin::And, a, k31);
  5459. let b = self.s.m.bin(c, Bin::And, b, k31);
  5460. let m = self.s.m.bin(c, Bin::Shl, one, a);
  5461. let m = self.s.m.bin(c, Bin::Sub, m, one);
  5462. (self.s.m.bin(c, Bin::Shl, m, b), None)
  5463. }
  5464. _ => return Err(name),
  5465. };
  5466. self.set(lo, Val::I32(r));
  5467. if let Some(scc) = scc {
  5468. let val = match carry {
  5469. Some(k) => Val::Bit(k),
  5470. None if matches!(
  5471. name,
  5472. "s_mov_b32"
  5473. | "s_movk_i32"
  5474. | "s_cselect_b32"
  5475. | "s_brev_b32"
  5476. | "s_mul_i32"
  5477. | "s_mulk_i32"
  5478. ) =>
  5479. {
  5480. return Ok(());
  5481. }
  5482. None if name.starts_with("s_add") || name.starts_with("s_sub") => {
  5483. Val::Missing("the carry of a scalar operation")
  5484. }
  5485. None => {
  5486. let z = self.s.m.i32(0);
  5487. Val::Bit(self.s.m.cmp(c, pred::NE, r, z))
  5488. }
  5489. };
  5490. self.vals.insert(scc, val);
  5491. }
  5492. Ok(())
  5493. }
  5494. /// Packs whether each consecutive group of four pixels has a set bit.
  5495. fn quad_mask(&mut self, pixels: V) -> V {
  5496. let c = self.cur;
  5497. let one = self.s.m.i32(1);
  5498. let shifted = self.s.m.bin(c, Bin::LShr, pixels, one);
  5499. let mut mask = self.s.m.bin(c, Bin::Or, pixels, shifted);
  5500. // Fold each nibble into its bottom bit, then gather those bits into
  5501. // the low byte in three stages without needing a 64-bit operation.
  5502. for (distance, keep) in [
  5503. (2, 0x1111_1111),
  5504. (3, 0x0303_0303),
  5505. (6, 0x000f_000f),
  5506. (12, 0x0000_00ff),
  5507. ] {
  5508. let distance = self.s.m.i32(distance);
  5509. let shifted = self.s.m.bin(c, Bin::LShr, mask, distance);
  5510. let combined = self.s.m.bin(c, Bin::Or, mask, shifted);
  5511. let keep = self.s.m.i32(keep);
  5512. mask = self.s.m.bin(c, Bin::And, combined, keep);
  5513. }
  5514. mask
  5515. }
  5516. /// `a + b (+ cin)` or `a - b (- cin)` with the carry (borrow) out, as the
  5517. /// scalar and vector add-with-carry instructions set it.
  5518. fn add_sub_carry(&mut self, c: usize, add: bool, a: V, b: V, cin: Option<V>) -> (V, V) {
  5519. let op = if add { Bin::Add } else { Bin::Sub };
  5520. let mut r = self.s.m.bin(c, op, a, b);
  5521. // Without a carry in: a + b wraps below a; a - b borrows when a < b.
  5522. let mut carry = if add {
  5523. self.s.m.cmp(c, pred::IULT, r, a)
  5524. } else {
  5525. self.s.m.cmp(c, pred::IULT, a, b)
  5526. };
  5527. if let Some(cin) = cin {
  5528. let one = self.s.m.cast(c, Cast::ZExt, cin, self.s.t.i32);
  5529. let t = r;
  5530. r = self.s.m.bin(c, op, t, one);
  5531. // The carry in carries on when the partial result is all ones
  5532. // (add) or zero (sub).
  5533. let edge = self.s.m.i32(if add { u32::MAX } else { 0 });
  5534. let at_edge = self.s.m.cmp(c, pred::EQ, t, edge);
  5535. let more = self.s.m.bin(c, Bin::And, cin, at_edge);
  5536. carry = self.s.m.bin(c, Bin::Or, carry, more);
  5537. }
  5538. (r, carry)
  5539. }
  5540. fn scc_in(&mut self, inst: &Inst) -> Result<V, Why> {
  5541. let v = inst.read(Reg::Scc).ok_or("an unread SCC")?;
  5542. match self.get(v) {
  5543. Ok(Val::Bit(x)) => Ok(x),
  5544. Ok(_) => Err("SCC without a value"),
  5545. // Of a mask operation whose result lies within EXEC: whether
  5546. // some lane is left.
  5547. Err(LANE_MASK) if self.within_exec(v) => self.scc_some(v),
  5548. Err(why) => Err(why),
  5549. }
  5550. }
  5551. /// Whether the mask operation that sets the SCC value `scc` gives no
  5552. /// lane outside EXEC a bit.
  5553. fn within_exec(&self, scc: Value) -> bool {
  5554. let Some(&b) = self.def_block.get(&scc) else {
  5555. return false;
  5556. };
  5557. let by = self.x.p.blocks[b].insts.iter().find(|i| i.write(Reg::Scc) == Some(scc));
  5558. by.is_some_and(|i| {
  5559. i.write(Reg::S(EXEC)).is_some()
  5560. || matches!(&i.fields, Fields::Sop { dst: Some(Operand::Scalar { code, .. }), .. }
  5561. if i.write(Reg::S(*code)).is_some_and(|lo| self.x.st.active.contains(&lo)))
  5562. })
  5563. }
  5564. fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  5565. let Fields::Smem {
  5566. data,
  5567. offset,
  5568. soffset,
  5569. ..
  5570. } = &inst.fields
  5571. else {
  5572. unreachable!()
  5573. };
  5574. let name = inst.name();
  5575. if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) {
  5576. return self.code_smem(inst, a);
  5577. }
  5578. if self.scalar.get(&site).is_some_and(|a| a.param == MEMORY) {
  5579. return self.memory_smem(inst);
  5580. }
  5581. let Some(rest) = name.strip_prefix("s_buffer_load_dword") else {
  5582. return self.descriptor_data(inst, site);
  5583. };
  5584. let count = match rest {
  5585. "" => 1,
  5586. "x2" => 2,
  5587. "x4" => 4,
  5588. "x8" => 8,
  5589. "x16" => 16,
  5590. _ => return Err("a scalar buffer load"),
  5591. };
  5592. let Some(Operand::Scalar { code, .. }) = *data else {
  5593. return Err("a scalar buffer load");
  5594. };
  5595. let src = self
  5596. .descriptors
  5597. .get(&(site, false))
  5598. .copied()
  5599. .ok_or("an untracked descriptor")?;
  5600. let kind = self.used_kind(src);
  5601. let c = self.cur;
  5602. let (base, extra) = self.built_offset(src)?;
  5603. let offset = &((*offset as u32).wrapping_add(base) as i32);
  5604. let mut addr = self.s.m.i32(*offset as u32);
  5605. if let Some(x) = extra {
  5606. addr = self.s.m.bin(c, Bin::Add, addr, x);
  5607. }
  5608. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  5609. let so = self.operand(inst, soffset)?;
  5610. addr = self.s.m.bin(c, Bin::Add, addr, so);
  5611. }
  5612. if matches!(src, Source::Built { address, .. } if address.param == CODE) {
  5613. // A descriptor built around a table in the code.
  5614. for k in 0..count {
  5615. let off = self.s.m.i32(4 * k);
  5616. let a = self.s.m.bin(c, Bin::Add, addr, off);
  5617. let x = self.code_dword(a)?;
  5618. self.write(inst, Reg::S(code + k as u8), x, None);
  5619. }
  5620. return Ok(());
  5621. }
  5622. // A buffer the program picks from the view heap by an index it
  5623. // computes (`ResourceHeap`) has no used-resource entry, and the
  5624. // heap holds a buffer view there, not a constant buffer: read as
  5625. // raw bytes, as a table's SRV is below. Read as a constant buffer
  5626. // (the host's validation: "Descriptor Type in Heap: SRV, Register
  5627. // Type: CBV", heap index 17) the loads gave nothing:
  5628. // the title's meshlet culling (BatchCullMeshlets,
  5629. // BatchCullPreSkinnedMeshlets, BatchCullBatchCSMeshlets) reads its
  5630. // batch records, mesh headers and instance transforms this way, so
  5631. // it passed no meshlet and every indirect mesh draw ran empty.
  5632. // The host's table of strides by heap slot tells a buffer view
  5633. // (not 0) from anything else, which is still read as a constant
  5634. // buffer; only the load that fits the slot runs.
  5635. let picked = match kind {
  5636. None => self.slot_stride(src)?,
  5637. Some(_) => None,
  5638. };
  5639. if let Some(stride) = picked {
  5640. let zero = self.s.m.i32(0);
  5641. let is_buffer = self.s.m.cmp(self.cur, pred::NE, stride, zero);
  5642. let at = self.begin_guarded(Some(is_buffer));
  5643. let h = self.handle(site, src, false, (11, 0))?;
  5644. let mut raw = Vec::new();
  5645. for k in 0..count {
  5646. let b = self.cur;
  5647. let off = self.s.m.i32(4 * k);
  5648. let a = self.s.m.bin(b, Bin::Add, addr, off);
  5649. let mask = self.s.m.i8(1);
  5650. let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  5651. let r = self.s.op(
  5652. b,
  5653. "rawBufferLoad.f32",
  5654. Attr::ReadOnly,
  5655. self.s.t.res_ret,
  5656. 139,
  5657. &[h, a, u, mask, al],
  5658. );
  5659. let x = self.s.m.extract(b, r, 0);
  5660. let x = self.as_int(x);
  5661. raw.push((x, zero));
  5662. }
  5663. let raw = self.end_guarded(at, &raw);
  5664. let other = self.s.m.cmp(self.cur, pred::EQ, stride, zero);
  5665. let at = self.begin_guarded(Some(other));
  5666. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  5667. let mut both = Vec::new();
  5668. for (k, &r) in raw.iter().enumerate() {
  5669. let b = self.cur;
  5670. let off = self.s.m.i32(4 * k as u32);
  5671. let a = self.s.m.bin(b, Bin::Add, addr, off);
  5672. let x = self.cbuffer_dword(h, a);
  5673. both.push((x, r));
  5674. }
  5675. let both = self.end_guarded(at, &both);
  5676. for (k, x) in both.into_iter().enumerate() {
  5677. self.write(inst, Reg::S(code + k as u8), x, None);
  5678. }
  5679. return Ok(());
  5680. }
  5681. if matches!(kind, Some(u) if u.kind == ResourceType::Srv) {
  5682. let h = self.handle(site, src, false, (11, 0))?;
  5683. for k in 0..count {
  5684. let off = self.s.m.i32(4 * k);
  5685. let a = self.s.m.bin(c, Bin::Add, addr, off);
  5686. let mask = self.s.m.i8(1);
  5687. let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  5688. let r = self.s.op(
  5689. c,
  5690. "rawBufferLoad.f32",
  5691. Attr::ReadOnly,
  5692. self.s.t.res_ret,
  5693. 139,
  5694. &[h, a, u, mask, al],
  5695. );
  5696. let x = self.s.m.extract(c, r, 0);
  5697. let x = self.as_int(x);
  5698. self.write(inst, Reg::S(code + k as u8), x, None);
  5699. }
  5700. return Ok(());
  5701. }
  5702. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  5703. let constant = match addr {
  5704. V::Const(_)
  5705. if matches!(soffset, Operand::Scalar { code: NULL, .. }) && extra.is_none() =>
  5706. {
  5707. Some(*offset as u32)
  5708. }
  5709. _ => None,
  5710. };
  5711. let mut rows: HashMap<u32, V> = HashMap::new();
  5712. for k in 0..count {
  5713. let x = match constant {
  5714. Some(base) => {
  5715. let byte = base + 4 * k;
  5716. let row = match rows.get(&(byte >> 4)) {
  5717. Some(&r) => r,
  5718. None => {
  5719. let ri = self.s.m.i32(byte >> 4);
  5720. let r = self.s.op(
  5721. c,
  5722. "cbufferLoadLegacy.i32",
  5723. Attr::ReadOnly,
  5724. self.s.t.cbuf_ret,
  5725. 59,
  5726. &[h, ri],
  5727. );
  5728. rows.insert(byte >> 4, r);
  5729. r
  5730. }
  5731. };
  5732. self.s.m.extract(c, row, (byte >> 2) & 3)
  5733. }
  5734. None => {
  5735. let off = self.s.m.i32(4 * k);
  5736. let a = self.s.m.bin(c, Bin::Add, addr, off);
  5737. self.cbuffer_dword(h, a)
  5738. }
  5739. };
  5740. self.write(inst, Reg::S(code + k as u8), x, None);
  5741. }
  5742. Ok(())
  5743. }
  5744. /// A descriptor load (`s_load_dword*` from a table or heap) whose dwords
  5745. /// the code also reads as numbers: the console compiler computes sizes
  5746. /// from descriptor bits (an image's width, height, depth, levels; a
  5747. /// buffer's record count) instead of querying them. Those fields are
  5748. /// rebuilt from the host view's dimensions in the GFX10 layout (image
  5749. /// dword 1 bits 30-31 and dword 2 bits 0-13 width - 1, dword 2 bits
  5750. /// 14-29 height - 1, dword 3 identity swizzle, last level at 16, type at
  5751. /// 28, dword 4 depth or layers - 1; buffer dword 2 the record count).
  5752. // shortcut: the base level reads 0 (the host view starts at its own
  5753. // level 0, so sizes the code shifts by it come out right) and the other
  5754. // dwords (addresses, formats, tiling) have no host value: reading them
  5755. // stops the program.
  5756. fn descriptor_data(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  5757. const OTHER: Why = "a descriptor's address or format read as data";
  5758. let Fields::Smem {
  5759. data: Some(Operand::Scalar { code, .. }),
  5760. ..
  5761. } = inst.fields
  5762. else {
  5763. return Err("a scalar memory read as data");
  5764. };
  5765. let count = match inst.name().strip_prefix("s_load_dword") {
  5766. Some("") => 1u32,
  5767. Some("x2") => 2,
  5768. Some("x4") => 4,
  5769. Some("x8") => 8,
  5770. Some("x16") => 16,
  5771. _ => return Err("a scalar memory read as data"),
  5772. };
  5773. // How the program uses the descriptor tells the view's kind: an image or buffer
  5774. // instruction before a scalar buffer load, which reads any buffer.
  5775. let x = self.x;
  5776. let uses = |of: Site| {
  5777. x.res
  5778. .descriptors
  5779. .iter()
  5780. .filter(|d| d.role == Role::Resource)
  5781. .filter_map(move |d| {
  5782. d.source.leaves().into_iter().find_map(|l| match *l {
  5783. Source::Loaded { load, first } if load == of => Some((d.site, first)),
  5784. _ => None,
  5785. })
  5786. })
  5787. };
  5788. let by_scalar_load = |u: &(Site, u8)| {
  5789. matches!(x.p.blocks[u.0.0].insts[u.0.1].fields, Fields::Smem { .. })
  5790. };
  5791. let use_of = |of: Site| uses(of).find(|u| !by_scalar_load(u)).or_else(|| uses(of).next());
  5792. // The console compiler loads a descriptor again wherever it needs it, and for a
  5793. // size it reads the dwords of a load that nothing uses as a descriptor (a texture
  5794. // picked from the heap by an index held per lane: one load for its width, one for
  5795. // its base level, one for each read of the image). Another load of as many dwords
  5796. // from the same address reads the same descriptor, so what uses that one tells
  5797. // this one's kind. The handle is still made from this load's own operands, which
  5798. // hold here.
  5799. let address = self.scalar.get(&site).copied();
  5800. let twin = || {
  5801. let a = address?;
  5802. let same = |s: Site| x.p.blocks[s.0].insts[s.1].name() == inst.name();
  5803. x.res
  5804. .scalar
  5805. .iter()
  5806. .filter(|(s, b)| *s != site && *b == a && same(*s))
  5807. .find_map(|(s, _)| use_of(*s))
  5808. };
  5809. let use_at = use_of(site).or_else(twin);
  5810. // A view whose kind no use tells, but what is read of it does.
  5811. let sized = match use_at {
  5812. Some(_) => None,
  5813. None => self.sized_view(inst, site, code, count),
  5814. };
  5815. let Some((at, first)) = use_at.or(sized.map(|_| (site, 0))) else {
  5816. // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only
  5817. // copies its dwords and compares them, lane against first lane, and every load
  5818. // that reaches those lanes reads one address. Each dword stands in as its place
  5819. // in the table, so the lanes compare equal as they do on the console.
  5820. if self.x.res.lane_copied.contains(&site)
  5821. && let Some(a) = self.scalar.get(&site).copied()
  5822. {
  5823. for k in 0..count {
  5824. let x = self.s.m.i32(a.offset / 4 + k);
  5825. self.write(inst, Reg::S(code + k as u8), x, None);
  5826. }
  5827. return Ok(());
  5828. }
  5829. // A sampler's descriptor: no program reads its dwords as numbers, so where one
  5830. // meets numbers at a join the register is dead on that path (`dead`), as a
  5831. // descriptor's address or format is.
  5832. let sampler = x.res.descriptors.iter().any(|d| {
  5833. d.role == Role::Sampler
  5834. && d.source.leaves().into_iter().any(
  5835. |l| matches!(*l, Source::Loaded { load, .. } if load == site),
  5836. )
  5837. });
  5838. if sampler {
  5839. self.stale.extend(inst.writes.iter().map(|w| w.1));
  5840. return Err("a sampler's descriptor read as data");
  5841. }
  5842. // A buffer view the code only takes the address of, to walk
  5843. // the memory behind it (a ray-tracing structure): the address
  5844. // from the host, the other dwords have no value.
  5845. if count <= 4
  5846. && let Some((lo, hi)) = self.view_address(site)
  5847. {
  5848. for k in 0..count {
  5849. let reg = Reg::S(code + k as u8);
  5850. match k {
  5851. 0 => self.write(inst, reg, lo, None),
  5852. 1 => self.write(inst, reg, hi, None),
  5853. _ => {
  5854. if let Some(v) = inst.write(reg) {
  5855. self.vals.insert(v, Val::Missing(OTHER));
  5856. self.stale.insert(v);
  5857. }
  5858. }
  5859. }
  5860. }
  5861. return Ok(());
  5862. }
  5863. if std::env::var_os("VICTORY_DESC_WHY").is_some() {
  5864. eprintln!(
  5865. "DESC-WHY {:#x} {} scalar={:?} lane_copied={}",
  5866. inst.machine.offset,
  5867. inst.name(),
  5868. address,
  5869. self.x.res.lane_copied.contains(&site)
  5870. );
  5871. }
  5872. return Err("a descriptor read only as data");
  5873. };
  5874. let src = Source::Loaded { load: site, first };
  5875. let used = self.used_kind(&src);
  5876. let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1];
  5877. let un = ui.name();
  5878. let uav = un.contains("store")
  5879. || un.contains("atomic")
  5880. || used.is_some_and(|u| u.kind == ResourceType::Uav);
  5881. let u = if uav { 0x1000 } else { 0 };
  5882. let (props, image) = match &ui.fields {
  5883. _ if sized.is_some_and(|image| image) => ((2 | u, 0x409), Some(2)),
  5884. _ if sized.is_some() => ((11 | u, 0), None),
  5885. // A ray-tracing structure in a buffer of the host: read raw.
  5886. Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None),
  5887. Fields::Image { dim, .. } => {
  5888. let kind = match dim {
  5889. 0 => 1,
  5890. 1 => 2,
  5891. 2 => 4,
  5892. 4 => 6,
  5893. 5 => 7,
  5894. _ => return Err("an image dimension (cube or MSAA)"),
  5895. };
  5896. ((kind | u, 0x409), Some(kind))
  5897. }
  5898. Fields::Buffer { idxen, format, .. } => {
  5899. let stride = used.map_or(0, |u| u.stride);
  5900. let counted = inst
  5901. .write(Reg::S(code + first + 2))
  5902. .is_some_and(|v| self.read_as_number(v));
  5903. let props = if un.starts_with("buffer_load_format")
  5904. || un.starts_with("buffer_store_format")
  5905. {
  5906. (10 | u, 0x409)
  5907. } else if !counted
  5908. && *idxen
  5909. && format.is_none()
  5910. && stride >= 4
  5911. && stride.is_multiple_of(4)
  5912. {
  5913. // Nothing reads the count: the query is cleaned up.
  5914. (12 | u, stride)
  5915. } else {
  5916. // Structured ones too: the host's views of them are raw
  5917. // (see `buffer`), which count bytes, and a size asked
  5918. // for as a structured view's is that count on AMD.
  5919. (11 | u, 0)
  5920. };
  5921. if used.is_some_and(|u| u.kind == ResourceType::Cbv) {
  5922. self.stale.extend(inst.writes.iter().map(|w| w.1));
  5923. return Err("a constant buffer's descriptor read as data");
  5924. }
  5925. (props, None)
  5926. }
  5927. // Read by scalar buffer loads alone: the raw view `smem` reads it through.
  5928. Fields::Smem { .. } if used.is_some_and(|u| u.kind == ResourceType::Srv) => {
  5929. ((11, 0), None)
  5930. }
  5931. // A constant buffer: nothing of its descriptor is a number.
  5932. Fields::Smem { .. } => {
  5933. self.stale.extend(inst.writes.iter().map(|w| w.1));
  5934. return Err("a constant buffer's descriptor read as data");
  5935. }
  5936. _ => return Err("a scalar memory read as data"),
  5937. };
  5938. let h = self.handle(site, &src, false, props)?;
  5939. let c = self.cur;
  5940. let i32t = self.s.t.i32;
  5941. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  5942. let mip = if image.is_some() && !uav {
  5943. self.s.m.i32(0)
  5944. } else {
  5945. self.s.m.undef(i32t)
  5946. };
  5947. let d = self
  5948. .s
  5949. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  5950. let field = |l: &mut Self, k: u32| l.s.m.extract(c, d, k);
  5951. let words: Vec<(u32, V)> = match image {
  5952. Some(kind) => {
  5953. let one = self.s.m.i32(1);
  5954. let w = field(self, 0);
  5955. let (height, depth) = match kind {
  5956. 1 => (one, one),
  5957. 2 => (field(self, 1), one),
  5958. 6 => (one, field(self, 1)),
  5959. _ => (field(self, 1), field(self, 2)),
  5960. };
  5961. let levels = if uav { one } else { field(self, 3) };
  5962. let less = |l: &mut Self, x: V| l.s.m.bin(c, Bin::Sub, x, one);
  5963. let (w, height, depth, levels) = (
  5964. less(self, w),
  5965. less(self, height),
  5966. less(self, depth),
  5967. less(self, levels),
  5968. );
  5969. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  5970. let (k30, k2, k14, k16, mask) = (
  5971. k(self, 30),
  5972. k(self, 2),
  5973. k(self, 14),
  5974. k(self, 16),
  5975. k(self, 0x3FFF),
  5976. );
  5977. let d1 = self.s.m.bin(c, Bin::Shl, w, k30);
  5978. let hi = self.s.m.bin(c, Bin::LShr, w, k2);
  5979. let hi = self.s.m.bin(c, Bin::And, hi, mask);
  5980. let ht = self.s.m.bin(c, Bin::Shl, height, k14);
  5981. let d2 = self.s.m.bin(c, Bin::Or, hi, ht);
  5982. let ty = [0, 8, 9, 0, 10, 0, 12, 13][kind as usize];
  5983. let base = k(self, 0xFAC | ty << 28);
  5984. let last = self.s.m.bin(c, Bin::Shl, levels, k16);
  5985. let d3 = self.s.m.bin(c, Bin::Or, base, last);
  5986. vec![(1, d1), (2, d2), (3, d3), (4, depth)]
  5987. }
  5988. None => {
  5989. // A raw view counts bytes; the descriptor's record count is in elements.
  5990. let n = field(self, 0);
  5991. let stride = used.map_or(0, |u| u.stride);
  5992. let counted = inst
  5993. .write(Reg::S(code + first + 2))
  5994. .is_some_and(|v| self.read_as_number(v));
  5995. let n = if props.0 & 0xFF == 11 && stride > 1 {
  5996. let k = self.s.m.i32(stride);
  5997. self.s.m.bin(c, Bin::UDiv, n, k)
  5998. } else if props.0 & 0xFF == 11
  5999. && counted
  6000. && let Some(stride) = self.slot_stride(&src)?
  6001. {
  6002. // Picked from the heap: the host's table has the stride.
  6003. let (i32t, one) = (self.s.t.i32, self.s.m.i32(1));
  6004. let k = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 39, &[stride, one]);
  6005. self.s.m.bin(c, Bin::UDiv, n, k)
  6006. } else {
  6007. n
  6008. };
  6009. let mut words = vec![(2, n)];
  6010. // Its address too, where the code computes with it and the
  6011. // host can tell it.
  6012. let computed = (0..2u8).any(|k| {
  6013. inst.write(Reg::S(code + first + k))
  6014. .is_some_and(|v| self.computed_with(v, 6))
  6015. });
  6016. if first == 0
  6017. && computed
  6018. && let Some((lo, hi)) = self.view_address(site)
  6019. {
  6020. words.extend([(0, lo), (1, hi)]);
  6021. }
  6022. words
  6023. }
  6024. };
  6025. for k in 0..count {
  6026. let rel = k.wrapping_sub(u32::from(first));
  6027. match words.iter().find(|w| w.0 == rel) {
  6028. Some(&(_, x)) => self.write(inst, Reg::S(code + k as u8), x, None),
  6029. None => {
  6030. if let Some(v) = inst.write(Reg::S(code + k as u8)) {
  6031. self.vals.insert(v, Val::Missing(OTHER));
  6032. self.stale.insert(v);
  6033. }
  6034. }
  6035. }
  6036. }
  6037. Ok(())
  6038. }
  6039. /// `s_load_dword*` from the program's constant table.
  6040. fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> {
  6041. let Fields::Smem {
  6042. data: Some(Operand::Scalar { code, .. }),
  6043. ..
  6044. } = inst.fields
  6045. else {
  6046. return Err("a scalar load");
  6047. };
  6048. let count = match inst.name().strip_prefix("s_load_dword") {
  6049. Some("") => 1u32,
  6050. Some("x2") => 2,
  6051. Some("x4") => 4,
  6052. Some("x8") => 8,
  6053. Some("x16") => 16,
  6054. _ => return Err("a scalar load from the code"),
  6055. };
  6056. let c = self.cur;
  6057. let mut addr = self.s.m.i32(a.offset);
  6058. if let Some(value) = a.dynamic {
  6059. let mut d = self.i32_of(value)?;
  6060. // A term held per lane reached the address through
  6061. // `v_readfirstlane_b32`: the first lane's.
  6062. let per_lane = self.def_block.get(&value).is_some_and(|&b| {
  6063. let writes = |i: &Inst| i.writes.iter().any(|w| w.1 == value && matches!(w.0, Reg::V(_)));
  6064. self.x.p.blocks[b].insts.iter().any(writes)
  6065. });
  6066. if per_lane {
  6067. self.s.flags |= flags::WAVE_OPS;
  6068. let i32t = self.s.t.i32;
  6069. let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[d]);
  6070. d = if self.s.pixel && super::helper_own() {
  6071. let helper = self.helper_lane();
  6072. self.s.m.select(c, helper, d, first)
  6073. } else {
  6074. first
  6075. };
  6076. }
  6077. addr = self.s.m.bin(c, Bin::Add, addr, d);
  6078. }
  6079. for k in 0..count {
  6080. let off = self.s.m.i32(4 * k);
  6081. let at = self.s.m.bin(c, Bin::Add, addr, off);
  6082. let x = self.code_dword(at)?;
  6083. self.write(inst, Reg::S(code + k as u8), x, None);
  6084. }
  6085. Ok(())
  6086. }
  6087. /// The dword at a computed byte address of a constant buffer.
  6088. fn cbuffer_dword(&mut self, h: V, a: V) -> V {
  6089. let c = self.cur;
  6090. let four = self.s.m.i32(4);
  6091. let ri = self.s.m.bin(c, Bin::LShr, a, four);
  6092. let r = self.s.op(
  6093. c,
  6094. "cbufferLoadLegacy.i32",
  6095. Attr::ReadOnly,
  6096. self.s.t.cbuf_ret,
  6097. 59,
  6098. &[h, ri],
  6099. );
  6100. let two = self.s.m.i32(2);
  6101. let three = self.s.m.i32(3);
  6102. let comp = self.s.m.bin(c, Bin::LShr, a, two);
  6103. let comp = self.s.m.bin(c, Bin::And, comp, three);
  6104. let mut x = self.s.m.extract(c, r, 0);
  6105. for j in 1..4 {
  6106. let e = self.s.m.extract(c, r, j);
  6107. let jc = self.s.m.i32(j);
  6108. let is = self.s.m.cmp(c, pred::EQ, comp, jc);
  6109. x = self.s.m.select(c, is, e, x);
  6110. }
  6111. x
  6112. }
  6113. /// `channels` channels of the element at byte `off` of raw buffer `h`,
  6114. /// converted from the GFX10 buffer format `format` as the hardware's
  6115. /// typed loads do (channels past the format's read 0, 0, 0, 1).
  6116. // shortcut: the descriptor's channel swizzle is taken as the identity
  6117. // (it is for raw views and the descriptors code builds), elements of 4
  6118. // bytes or more as dword-aligned. Norm formats divide, which the AMD
  6119. // driver does 1 ULP off the hardware's correctly rounded conversion for
  6120. // some values; correct it with an integer check if a title compares
  6121. // converted values exactly.
  6122. fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result<Vec<V>, Why> {
  6123. let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?;
  6124. let c = self.cur;
  6125. let total: u32 = bits.iter().sum();
  6126. let (u, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  6127. let load = |l: &mut Self, at: V, n: u32| -> Vec<V> {
  6128. let mask = l.s.m.i8((1u8 << n) - 1);
  6129. let r = l.s.op(
  6130. c,
  6131. "rawBufferLoad.f32",
  6132. Attr::ReadOnly,
  6133. l.s.t.res_ret,
  6134. 139,
  6135. &[h, at, u, mask, align],
  6136. );
  6137. (0..n)
  6138. .map(|k| {
  6139. let x = l.s.m.extract(c, r, k);
  6140. l.as_int(x)
  6141. })
  6142. .collect()
  6143. };
  6144. let words = if total < 32 {
  6145. // A byte or half inside the dword that holds it.
  6146. let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3));
  6147. let at = self.s.m.bin(c, Bin::And, off, not3);
  6148. let w = load(self, at, 1)[0];
  6149. let byte = self.s.m.bin(c, Bin::And, off, three);
  6150. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  6151. vec![self.s.m.bin(c, Bin::LShr, w, sh)]
  6152. } else {
  6153. load(self, off, total / 32)
  6154. };
  6155. let float = |l: &mut Self, f: V| l.as_int(f);
  6156. let mut out = Vec::new();
  6157. let mut at = 0;
  6158. for &w in bits {
  6159. let word = words[(at / 32) as usize];
  6160. let field = if w == 32 {
  6161. word
  6162. } else {
  6163. let sh = self.s.m.i32(at % 32);
  6164. let t = self.s.m.bin(c, Bin::LShr, word, sh);
  6165. let m = self.s.m.i32((1 << w) - 1);
  6166. self.s.m.bin(c, Bin::And, t, m)
  6167. };
  6168. at += w;
  6169. // Sign-extended from the field's top bit.
  6170. let signed = |l: &mut Self| {
  6171. if w == 32 {
  6172. return field;
  6173. }
  6174. let k = l.s.m.i32(32 - w);
  6175. let t = l.s.m.bin(c, Bin::Shl, field, k);
  6176. l.s.m.bin(c, Bin::AShr, t, k)
  6177. };
  6178. let f32t = self.s.t.f32;
  6179. // A normalized format's ends are exactly 1.0 and -1.0. The host
  6180. // may divide through a reciprocal and land just below 1.0: RDNA
  6181. // 4 loaded 16_16_UNORM's 65535 as the half 0x3BFF, not 0x3C00.
  6182. let x = match numeric {
  6183. Numeric::Unorm => {
  6184. let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
  6185. let top = (1u64 << w) - 1;
  6186. let max = self.s.m.f32((top as f32).to_bits());
  6187. let q = self.s.m.bin(c, Bin::SDiv, f, max);
  6188. let (high, one) = (self.s.m.i32(top as u32), self.s.m.f32(1.0f32.to_bits()));
  6189. let at_top = self.s.m.cmp(c, pred::EQ, field, high);
  6190. let q = self.s.m.select(c, at_top, one, q);
  6191. float(self, q)
  6192. }
  6193. Numeric::Snorm => {
  6194. let s = signed(self);
  6195. let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
  6196. let top = (1u32 << (w - 1)) - 1;
  6197. let max = self.s.m.f32((top as f32).to_bits());
  6198. let q = self.s.m.bin(c, Bin::SDiv, f, max);
  6199. // The lowest value is -1.0 too, as is the one above it.
  6200. let (high, one) = (self.s.m.i32(top), self.s.m.f32(1.0f32.to_bits()));
  6201. let at_top = self.s.m.cmp(c, pred::SGE, s, high);
  6202. let q = self.s.m.select(c, at_top, one, q);
  6203. let low = self.s.m.i32(top.wrapping_neg());
  6204. let minus_one = self.s.m.f32((-1.0f32).to_bits());
  6205. let at_bottom = self.s.m.cmp(c, pred::SLE, s, low);
  6206. let q = self.s.m.select(c, at_bottom, minus_one, q);
  6207. float(self, q)
  6208. }
  6209. Numeric::Uscaled => {
  6210. let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
  6211. float(self, f)
  6212. }
  6213. Numeric::Sscaled => {
  6214. let s = signed(self);
  6215. let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
  6216. float(self, f)
  6217. }
  6218. Numeric::Uint => field,
  6219. Numeric::Sint => signed(self),
  6220. Numeric::Float if w == 32 => field,
  6221. Numeric::Float => {
  6222. let h = match half_shift(w) {
  6223. 0 => field,
  6224. k => {
  6225. let sh = self.s.m.i32(k);
  6226. self.s.m.bin(c, Bin::Shl, field, sh)
  6227. }
  6228. };
  6229. let f = self
  6230. .s
  6231. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  6232. float(self, f)
  6233. }
  6234. };
  6235. out.push(x);
  6236. }
  6237. let one = match numeric {
  6238. Numeric::Uint | Numeric::Sint => 1,
  6239. _ => 1.0f32.to_bits(),
  6240. };
  6241. for k in out.len() as u32..channels {
  6242. out.push(self.s.m.i32(if k == 3 { one } else { 0 }));
  6243. }
  6244. out.truncate(channels as usize);
  6245. Ok(out)
  6246. }
  6247. /// Channels of buffer format `format`, as [`Self::format_load`] gives
  6248. /// them, as d16 data: 16 bits each, two per dword, low half first (an
  6249. /// odd last high half 0). Integer formats keep their low 16 bits; the
  6250. /// others become f16.
  6251. fn d16_channels(&mut self, format: u8, channels: Vec<V>) -> Result<Vec<V>, Why> {
  6252. let (_, numeric) = buffer_format(format).ok_or("a buffer format")?;
  6253. let c = self.cur;
  6254. let mut halves = Vec::new();
  6255. for x in channels {
  6256. halves.push(if matches!(numeric, Numeric::Uint | Numeric::Sint) {
  6257. let m = self.s.m.i32(0xFFFF);
  6258. self.s.m.bin(c, Bin::And, x, m)
  6259. } else {
  6260. let (f, i32t) = (self.as_float(x), self.s.t.i32);
  6261. self.s
  6262. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  6263. });
  6264. }
  6265. let mut out = Vec::new();
  6266. for pair in halves.chunks(2) {
  6267. out.push(match *pair {
  6268. [lo, hi] => {
  6269. let k16 = self.s.m.i32(16);
  6270. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  6271. self.s.m.bin(c, Bin::Or, lo, hi)
  6272. }
  6273. [lo] => lo,
  6274. _ => unreachable!("chunks of one or two"),
  6275. });
  6276. }
  6277. Ok(out)
  6278. }
  6279. /// The byte offset a buffer descriptor built around a root descriptor adds
  6280. /// (constant and computed parts); none for other descriptors.
  6281. fn built_offset(&mut self, src: &Source) -> Result<(u32, Option<V>), Why> {
  6282. match src {
  6283. Source::Built { address, .. } => {
  6284. let mut x = match address.dynamic {
  6285. Some(v) => Some(self.i32_of(v)?),
  6286. None => None,
  6287. };
  6288. if let Some(bias) = self.root_bias(address.param) {
  6289. x = Some(match x {
  6290. Some(d) => self.s.m.bin(self.cur, Bin::Add, d, bias),
  6291. None => bias,
  6292. });
  6293. }
  6294. Ok((address.offset, x))
  6295. }
  6296. _ => Ok((0, None)),
  6297. }
  6298. }
  6299. /// For a root view the host binds as a raw view that may begin before
  6300. /// the title's address (`shader.rs` `USER_VIEW_BIAS`): the bytes to add
  6301. /// to offsets through it. Every root UAV, and the root SRVs of programs
  6302. /// with a spilled user-data table (the others keep the views they
  6303. /// have).
  6304. fn root_bias(&mut self, param: usize) -> Option<V> {
  6305. use super::shader::USER_VIEW_BIAS;
  6306. let rp = *self.x.native.layout.get(param)?;
  6307. if rp.root != RootType::Descriptor {
  6308. return None;
  6309. }
  6310. let kind = self
  6311. .x
  6312. .native
  6313. .used
  6314. .iter()
  6315. .find(|u| u.user_data == rp.user_data)
  6316. .map(|u| u.kind);
  6317. let biased = match kind {
  6318. Some(ResourceType::Uav) => true,
  6319. Some(ResourceType::Srv) => crate::spill::is_spilled(self.x.native),
  6320. _ => false,
  6321. };
  6322. biased.then(|| self.host_word(RootType::Other(USER_VIEW_BIAS), rp.slot, 0))
  6323. }
  6324. /// The used-resource entry a descriptor loaded from a table falls in.
  6325. fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> {
  6326. if let Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } =
  6327. src
  6328. {
  6329. return self.used_kind(args.first()?);
  6330. }
  6331. if let Source::LanePhi { args, .. } = src {
  6332. return args.iter().flatten().find_map(|a| self.used_kind(a));
  6333. }
  6334. if let Source::Built { address, .. } = src {
  6335. let rp = self.x.native.layout.get(address.param)?;
  6336. return self
  6337. .x
  6338. .native
  6339. .used
  6340. .iter()
  6341. .find(|u| u.root == RootType::Descriptor && u.user_data == rp.user_data);
  6342. }
  6343. let (Source::Loaded { load, first } | Source::Fetched { load, first }) = src else {
  6344. return None;
  6345. };
  6346. let a = self.scalar.get(load)?;
  6347. let rp = self.x.native.layout.get(a.param)?;
  6348. if rp.root != RootType::Table {
  6349. return None;
  6350. }
  6351. let dword = (a.offset / 4) + u32::from(*first);
  6352. self.x
  6353. .native
  6354. .used
  6355. .iter()
  6356. .filter(|u| {
  6357. u.root == RootType::Table
  6358. && u.user_data == rp.user_data
  6359. && u.table_offset_dwords <= dword
  6360. })
  6361. .max_by_key(|u| u.table_offset_dwords)
  6362. }
  6363. /// A handle for the descriptor `src` read at `site`.
  6364. fn handle(
  6365. &mut self,
  6366. site: Site,
  6367. src: &Source,
  6368. sampler: bool,
  6369. props: (u32, u32),
  6370. ) -> Result<V, Why> {
  6371. match src {
  6372. Source::Loaded { load, first } => {
  6373. let key = (self.cur, *load, *first, sampler, props);
  6374. if let Some(&h) = self.handles.get(&key) {
  6375. return Ok(h);
  6376. }
  6377. let index = self.heap_index(*load, *first, sampler)?;
  6378. // A waterfall loop's load at the first lane's offset reads
  6379. // each lane's own entry (see `resource::Waterfall`).
  6380. let per_lane = self.x.res.waterfall.loads.contains(load);
  6381. let h = self
  6382. .s
  6383. .heap_handle(self.cur, index, sampler, per_lane, props);
  6384. self.handles.insert(key, h);
  6385. Ok(h)
  6386. }
  6387. Source::Constant(words) if sampler => {
  6388. let n = self.register_sampler(words, props.0 & 0x8000 != 0)?;
  6389. Ok(self.s.sampler_handle(self.cur, n))
  6390. }
  6391. Source::Constant(_) => Err("a constant resource descriptor"),
  6392. Source::Built { address, .. } => {
  6393. let rp = *self
  6394. .x
  6395. .native
  6396. .layout
  6397. .get(address.param)
  6398. .ok_or("a descriptor built around a table in the code")?;
  6399. let kind = self
  6400. .x
  6401. .native
  6402. .used
  6403. .iter()
  6404. .find(|u| u.user_data == rp.user_data)
  6405. .map(|u| u.kind);
  6406. match (rp.root, kind, props.0) {
  6407. (RootType::Descriptor, Some(ResourceType::Cbv) | None, 13) => {
  6408. Ok(self.s.root_cbv_handle(rp.slot))
  6409. }
  6410. (RootType::Descriptor, Some(ResourceType::Srv), 11) => {
  6411. Ok(self.s.root_srv_handle(rp.slot))
  6412. }
  6413. // A root UAV: a raw buffer whether the access reads
  6414. // (11) or writes (11 with the UAV bit). Indexed
  6415. // accesses reach here as raw ones at index times the
  6416. // entry's stride (`buffer`).
  6417. (RootType::Descriptor, Some(ResourceType::Uav), 11 | 0x100b) => {
  6418. Ok(self.s.root_uav_handle(rp.slot))
  6419. }
  6420. (RootType::Descriptor, Some(ResourceType::Srv), 0x100b) => {
  6421. Err("a write through a root SRV")
  6422. }
  6423. _ => Err("a typed root view"),
  6424. }
  6425. }
  6426. Source::Phi { block, args } => {
  6427. let _ = site;
  6428. let phi = self.descriptor_phi(*block, args, sampler, 8)?;
  6429. Ok(self.s.heap_handle(self.cur, phi, sampler, false, props))
  6430. }
  6431. Source::Select { scc, args } => {
  6432. // The heap index of each choice, picked by SCC (uniform).
  6433. let [
  6434. Source::Loaded { load: a, first: fa },
  6435. Source::Loaded { load: b, first: fb },
  6436. ] = args[..]
  6437. else {
  6438. return Err("a descriptor chosen by a condition");
  6439. };
  6440. let cond = match self.get(*scc)? {
  6441. Val::Bit(x) => x,
  6442. _ => return Err("SCC without a value"),
  6443. };
  6444. let set = self.heap_index(a, fa, sampler)?;
  6445. let clear = self.heap_index(b, fb, sampler)?;
  6446. let index = self.s.m.select(self.cur, cond, set, clear);
  6447. Ok(self.s.heap_handle(self.cur, index, sampler, false, props))
  6448. }
  6449. Source::Fetched { .. } | Source::Lanes { .. } | Source::LanePhi { .. } => {
  6450. // A descriptor each lane has its own of (a waterfall loop
  6451. // reads it from the first active lane): each lane's heap
  6452. // index, non-uniform.
  6453. let index = self.lane_heap_index(src, sampler)?;
  6454. Ok(self.s.heap_handle(self.cur, index, sampler, true, props))
  6455. }
  6456. }
  6457. }
  6458. /// The heap index a descriptor phi picks. Each predecessor computes its
  6459. /// heap index at its end and the join picks one with a phi; a
  6460. /// predecessor whose descriptor is itself chosen by control flow (a
  6461. /// phi of an earlier join, which dominates it) gives that join's phi,
  6462. /// at most `depth` joins deep.
  6463. fn descriptor_phi(
  6464. &mut self,
  6465. block: usize,
  6466. args: &[Source],
  6467. sampler: bool,
  6468. depth: u32,
  6469. ) -> Result<V, Why> {
  6470. const WHY: Why = "a descriptor chosen by control flow";
  6471. let p = self.x.p;
  6472. let mut incoming = Vec::new();
  6473. for (&q, arg) in p.blocks[block].preds.iter().zip(args) {
  6474. if self.block[q].is_none() {
  6475. continue;
  6476. }
  6477. let tail = self.tail[q].ok_or(WHY)?;
  6478. let at = self.edges.get(&(q, block)).copied().unwrap_or(tail);
  6479. let index = match arg {
  6480. Source::Loaded { load, first } => {
  6481. let here = std::mem::replace(&mut self.cur, at);
  6482. let index = self.heap_index(*load, *first, sampler);
  6483. self.cur = here;
  6484. index?
  6485. }
  6486. Source::Phi { block: inner, args: inner_args } if depth > 0 => {
  6487. self.descriptor_phi(*inner, inner_args, sampler, depth - 1)?
  6488. }
  6489. _ => return Err(WHY),
  6490. };
  6491. incoming.push((index, at));
  6492. }
  6493. let join = self.block[block].ok_or(WHY)?;
  6494. let phi = self.s.m.phi(join, self.s.t.i32);
  6495. self.s.m.set_phi(phi, incoming);
  6496. Ok(phi)
  6497. }
  6498. /// Registers an immediate sampler constant and returns its slot index: a
  6499. /// constant used with and without comparison takes one slot for each.
  6500. fn register_sampler(&mut self, words: &[u32], cmp: bool) -> Result<u32, Why> {
  6501. let words: [u32; 4] = words
  6502. .get(..4)
  6503. .and_then(|w| w.try_into().ok())
  6504. .ok_or("a sampler constant")?;
  6505. let slot = self
  6506. .samplers
  6507. .iter()
  6508. .enumerate()
  6509. .position(|(n, w)| *w == words && (self.s.cmp_samplers >> n & 1 != 0) == cmp);
  6510. let n = match slot {
  6511. Some(n) => n,
  6512. None => {
  6513. let n = self.samplers.len();
  6514. if n >= u64::BITS as usize {
  6515. return Err("more than 64 immediate sampler slots");
  6516. }
  6517. self.samplers.push(words);
  6518. self.s.cmp_samplers |= u64::from(cmp) << n;
  6519. n
  6520. }
  6521. };
  6522. Ok(n as u32)
  6523. }
  6524. /// Resolves a control-flow phi of immediate sampler constants into either a
  6525. /// single static sampler register (`One`) or a uniform `i32` phi index over
  6526. /// `regs` (`Many`) for branch dispatch at the sample site.
  6527. fn sampler_phi_choice(
  6528. &mut self,
  6529. block: usize,
  6530. args: &[Source],
  6531. cmp: bool,
  6532. depth: u32,
  6533. ) -> Result<(Option<V>, Vec<u32>), Why> {
  6534. const WHY: Why = "a descriptor chosen by control flow";
  6535. let mut distinct: Vec<[u32; 4]> = Vec::new();
  6536. self.collect_constant_samplers(block, args, depth, &mut distinct)?;
  6537. if distinct.is_empty() {
  6538. return Err(WHY);
  6539. }
  6540. let mut regs = Vec::with_capacity(distinct.len());
  6541. for w in &distinct {
  6542. regs.push(self.register_sampler(w, cmp)?);
  6543. }
  6544. if regs.len() == 1 {
  6545. return Ok((None, regs));
  6546. }
  6547. let idx = self.sampler_index_phi(block, args, 0, &distinct, depth)?;
  6548. Ok((Some(idx), regs))
  6549. }
  6550. fn collect_constant_samplers(
  6551. &self,
  6552. block: usize,
  6553. args: &[Source],
  6554. depth: u32,
  6555. distinct: &mut Vec<[u32; 4]>,
  6556. ) -> Result<(), Why> {
  6557. const WHY: Why = "a descriptor chosen by control flow";
  6558. let p = self.x.p;
  6559. for (&q, arg) in p.blocks[block].preds.iter().zip(args) {
  6560. if self.block[q].is_none() {
  6561. continue;
  6562. }
  6563. match arg {
  6564. Source::Constant(w) if w.len() >= 4 => {
  6565. let k: [u32; 4] = w[..4].try_into().unwrap();
  6566. if !distinct.contains(&k) {
  6567. distinct.push(k);
  6568. }
  6569. }
  6570. Source::Phi {
  6571. block: inner,
  6572. args: inner_args,
  6573. } if depth > 0 => {
  6574. self.collect_constant_samplers(*inner, inner_args, depth - 1, distinct)?;
  6575. }
  6576. _ => return Err(WHY),
  6577. }
  6578. }
  6579. Ok(())
  6580. }
  6581. fn sampler_index_phi(
  6582. &mut self,
  6583. block: usize,
  6584. args: &[Source],
  6585. lower: u32,
  6586. distinct: &[[u32; 4]],
  6587. depth: u32,
  6588. ) -> Result<V, Why> {
  6589. const WHY: Why = "a descriptor chosen by control flow";
  6590. let p = self.x.p;
  6591. let mut incoming = Vec::new();
  6592. for (&q, arg) in p.blocks[block].preds.iter().zip(args) {
  6593. if self.block[q].is_none() {
  6594. continue;
  6595. }
  6596. let tail = self.tail[q].ok_or(WHY)?;
  6597. let at = self.edges.get(&(q, block)).copied().unwrap_or(tail);
  6598. let idx = match arg {
  6599. Source::Constant(w) if w.len() >= 4 => {
  6600. let k: [u32; 4] = w[..4].try_into().unwrap();
  6601. let pos = distinct.iter().position(|d| *d == k).ok_or(WHY)? as u32;
  6602. self.s.m.i32(lower + pos)
  6603. }
  6604. Source::Phi {
  6605. block: inner,
  6606. args: inner_args,
  6607. } if depth > 0 => {
  6608. self.sampler_index_phi(*inner, inner_args, lower, distinct, depth - 1)?
  6609. }
  6610. _ => return Err(WHY),
  6611. };
  6612. incoming.push((idx, at));
  6613. }
  6614. let join = self.block[block].ok_or(WHY)?;
  6615. let phi = self.s.m.phi(join, self.s.t.i32);
  6616. self.s.m.set_phi(phi, incoming);
  6617. Ok(phi)
  6618. }
  6619. /// The bytes per element of the buffer view `src` names, if the program
  6620. /// picks it from the view heap at an index it computes (root type
  6621. /// `ResourceHeap`): read from the host's table by heap slot in the
  6622. /// current block.
  6623. fn slot_stride(&mut self, src: &Source) -> Result<Option<V>, Why> {
  6624. let Source::Loaded { load, first } = src else {
  6625. return Ok(None);
  6626. };
  6627. let heap = self
  6628. .scalar
  6629. .get(load)
  6630. .and_then(|a| self.x.native.layout.get(a.param))
  6631. .is_some_and(|p| p.root == RootType::ResourceHeap);
  6632. if !heap {
  6633. return Ok(None);
  6634. }
  6635. let key = (self.cur, *load, *first);
  6636. if let Some(&v) = self.strides.get(&key) {
  6637. return Ok(Some(v));
  6638. }
  6639. let c = self.cur;
  6640. let slot = self.heap_index(*load, *first, false)?;
  6641. // Inside the table whatever the index (lanes that do not run
  6642. // compute one too): a root view has no bounds of its own.
  6643. let last = self.s.m.i32(super::shader::SLOT_STRIDES_COUNT - 1);
  6644. let i32t = self.s.t.i32;
  6645. let slot = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[slot, last]);
  6646. self.s.m.tag(slot, Tag::Clamp);
  6647. let two = self.s.m.i32(2);
  6648. let byte = self.s.m.bin(c, Bin::Shl, slot, two);
  6649. let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES);
  6650. let iu = self.s.m.undef(self.s.t.i32);
  6651. let mask = self.s.m.i8(1);
  6652. let align = self.s.m.i32(4);
  6653. let r = self.s.op(
  6654. c,
  6655. "rawBufferLoad.f32",
  6656. Attr::ReadOnly,
  6657. self.s.t.res_ret,
  6658. 139,
  6659. &[h, byte, iu, mask, align],
  6660. );
  6661. let f = self.s.m.extract(c, r, 0);
  6662. let v = self.as_int(f);
  6663. self.strides.insert(key, v);
  6664. Ok(Some(v))
  6665. }
  6666. /// The heap index of a descriptor that may differ between lanes,
  6667. /// computed in the current block (or, chosen by control flow, at the
  6668. /// join).
  6669. fn lane_heap_index(&mut self, src: &Source, sampler: bool) -> Result<V, Why> {
  6670. match src {
  6671. Source::Loaded { load, first } => self.heap_index(*load, *first, sampler),
  6672. Source::Fetched { load, first } => self.fetched_index(*load, *first, sampler),
  6673. Source::Lanes { mask, args } | Source::Select { scc: mask, args } => {
  6674. let [a, b] = &args[..] else {
  6675. return Err("a descriptor chosen per lane");
  6676. };
  6677. let cond = if matches!(src, Source::Lanes { .. }) {
  6678. let &m = self
  6679. .x
  6680. .st
  6681. .masks
  6682. .get(mask)
  6683. .ok_or("a descriptor chosen per lane by an untracked mask")?;
  6684. self.boolean(m, self.cur)?
  6685. } else {
  6686. match self.get(*mask)? {
  6687. Val::Bit(x) => x,
  6688. _ => return Err("SCC without a value"),
  6689. }
  6690. };
  6691. let set = self.lane_heap_index(a, sampler)?;
  6692. let clear = self.lane_heap_index(b, sampler)?;
  6693. Ok(self.s.m.select(self.cur, cond, set, clear))
  6694. }
  6695. Source::LanePhi { block, args } => {
  6696. // Each predecessor computes its heap index at its end (what
  6697. // it reads is there: the dwords are, on that edge); the join
  6698. // picks the one of the edge the lane came by. An edge no
  6699. // lane reading it takes gives index 0.
  6700. let join =
  6701. self.block[*block].ok_or("a per-lane descriptor chosen by control flow")?;
  6702. let mut incoming = Vec::new();
  6703. for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) {
  6704. if self.block[q].is_none() {
  6705. continue;
  6706. }
  6707. let tail =
  6708. self.tail[q].ok_or("a per-lane descriptor joined from a later block")?;
  6709. let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail);
  6710. let index = match arg {
  6711. Some(arg) => {
  6712. let here = std::mem::replace(&mut self.cur, at);
  6713. let index = self.lane_heap_index(arg, sampler);
  6714. self.cur = here;
  6715. index?
  6716. }
  6717. None => self.s.m.i32(0),
  6718. };
  6719. incoming.push((index, at));
  6720. }
  6721. let phi = self.s.m.phi(join, self.s.t.i32);
  6722. self.s.m.set_phi(phi, incoming);
  6723. Ok(phi)
  6724. }
  6725. _ => Err("a per-lane descriptor from neither a heap load nor a choice of them"),
  6726. }
  6727. }
  6728. /// The heap index of the descriptor at dword `first` of what the global
  6729. /// load at `load` reads, in each lane: its address (base plus offsets)
  6730. /// over the descriptor size.
  6731. fn fetched_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> {
  6732. const WHY: Why = "a per-lane descriptor load";
  6733. let a = *self
  6734. .scalar
  6735. .get(&load)
  6736. .ok_or("an untracked descriptor load")?;
  6737. match self.x.native.layout.get(a.param).map(|p| p.root) {
  6738. Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {}
  6739. _ => return Err("a descriptor outside the heaps"),
  6740. }
  6741. let li: &Inst = &self.x.p.blocks[load.0].insts[load.1];
  6742. let Fields::Flat {
  6743. addr: Some(Operand::Vector { reg, .. }),
  6744. saddr,
  6745. offset,
  6746. ..
  6747. } = li.fields
  6748. else {
  6749. return Err(WHY);
  6750. };
  6751. let c = self.cur;
  6752. // The low dword of the address: SGPR base plus VGPR offset, or the
  6753. // VGPR pair's low half (heap addresses fit in 32 bits).
  6754. let mut at = self.i32_of(li.read(Reg::V(reg)).ok_or(WHY)?)?;
  6755. if let Some(Operand::Scalar { code, .. }) = saddr
  6756. && code != NULL
  6757. {
  6758. let base = self.i32_of(li.read(Reg::S(code)).ok_or(WHY)?)?;
  6759. at = self.s.m.bin(c, Bin::Add, base, at);
  6760. }
  6761. let k = self
  6762. .s
  6763. .m
  6764. .i32((offset as i32 as u32).wrapping_add(4 * u32::from(first)));
  6765. at = self.s.m.bin(c, Bin::Add, at, k);
  6766. let shift = self.s.m.i32(if sampler { 4 } else { 5 });
  6767. Ok(self.s.m.bin(c, Bin::LShr, at, shift))
  6768. }
  6769. /// The heap index of the descriptor at dword `first` of what the scalar
  6770. /// load at `load` reads, computed in the current block.
  6771. fn heap_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> {
  6772. let a = *self
  6773. .scalar
  6774. .get(&load)
  6775. .ok_or("an untracked descriptor load")?;
  6776. match self.x.native.layout.get(a.param).map(|p| p.root) {
  6777. Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {}
  6778. _ => return Err("a descriptor outside the heaps"),
  6779. }
  6780. let li: &Inst = &self.x.p.blocks[load.0].insts[load.1];
  6781. let Fields::Smem {
  6782. base,
  6783. offset,
  6784. soffset,
  6785. ..
  6786. } = &li.fields
  6787. else {
  6788. return Err("a descriptor load");
  6789. };
  6790. let Operand::Scalar { code, .. } = *base else {
  6791. return Err("a descriptor load");
  6792. };
  6793. let c = self.cur;
  6794. let base = li.read(Reg::S(code)).ok_or("a descriptor load")?;
  6795. let mut addr = self.i32_of(base)?;
  6796. let k = self
  6797. .s
  6798. .m
  6799. .i32((*offset as u32).wrapping_add(4 * u32::from(first)));
  6800. addr = self.s.m.bin(c, Bin::Add, addr, k);
  6801. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  6802. let so = self.operand(li, soffset)?;
  6803. addr = self.s.m.bin(c, Bin::Add, addr, so);
  6804. }
  6805. let shift = self.s.m.i32(if sampler { 4 } else { 5 });
  6806. Ok(self.s.m.bin(c, Bin::LShr, addr, shift))
  6807. }
  6808. fn valu(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  6809. let Fields::Valu(v) = &inst.fields else {
  6810. unreachable!()
  6811. };
  6812. let name = inst.name();
  6813. if self.x.res.waterfall.compares.contains(&(b, i)) {
  6814. // The first lane's dwords of a waterfall loop are each lane's
  6815. // own (see `resource::Waterfall`).
  6816. self.lane(inst, Some(true));
  6817. return Ok(());
  6818. }
  6819. // One lane of a VGPR a whole-wave section left.
  6820. if name == "v_readlane_b32"
  6821. && let Some(&(_, w)) = inst.writes.first()
  6822. && let Some(sh) = self.sections.get(&b).and_then(|s| {
  6823. s.iter().filter(|s| s.1.end < i).find_map(|s| s.1.reads.get(&w).copied())
  6824. })
  6825. {
  6826. let x = self.shape(sh, false)?;
  6827. self.vals.insert(w, Val::I32(x));
  6828. return Ok(());
  6829. }
  6830. if let Some(rest) = name.strip_prefix("v_cmp_").or(name.strip_prefix("v_cmpx_")) {
  6831. let r = if v.dpp.is_some() {
  6832. Err("a compare with DPP")
  6833. } else {
  6834. self.compare(inst, rest)
  6835. };
  6836. if let Err(why) = r {
  6837. for &(_, w) in &inst.writes {
  6838. self.lane_fail.insert(w, why);
  6839. }
  6840. }
  6841. return r;
  6842. }
  6843. let mut guard = self.guard(b, i)?;
  6844. if let Some(d) = v.dpp {
  6845. let (x, enable) = self.dpp(inst, d)?;
  6846. guard = match (guard, enable) {
  6847. (Some(g), Some(e)) => Some(self.s.m.bin(self.cur, Bin::And, g, e)),
  6848. (g, e) => g.or(e),
  6849. };
  6850. self.src0 = Some(x);
  6851. }
  6852. let r = self.valu_op(inst, guard);
  6853. self.src0 = None;
  6854. r
  6855. }
  6856. /// DPP: src0 as read from another lane, and which lanes write their
  6857. /// result (none: all).
  6858. fn dpp(&mut self, inst: &Inst, dpp: Dpp) -> Result<(V, Option<V>), Why> {
  6859. let Fields::Valu(v) = &inst.fields else {
  6860. unreachable!()
  6861. };
  6862. let Some(&Operand::Vector { reg, .. }) = v.src.first() else {
  6863. return Err("a DPP operand");
  6864. };
  6865. let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("a DPP operand")?)?;
  6866. // Quad permutations and DPP8 stay in groups the pixel layout shares.
  6867. let quad = matches!(dpp, Dpp::Row { ctrl: 0..=0xFF, .. });
  6868. let mesh_quad = self.s.mesh.is_some() && quad;
  6869. if !mesh_quad {
  6870. self.cross_lane(quad)?;
  6871. }
  6872. let c = self.cur;
  6873. let lane = self.lane_index();
  6874. let k = |l: &mut Self, n: u32| l.s.m.i32(n);
  6875. let (sixteen_mask, low) = (k(self, !15), k(self, 15));
  6876. let row = self.s.m.bin(c, Bin::And, lane, sixteen_mask);
  6877. let pos = self.s.m.bin(c, Bin::And, lane, low);
  6878. // Source lane, and whether it lies in the row.
  6879. let (src, inside, masks, zero) = match dpp {
  6880. Dpp::Lanes { sel, .. } => {
  6881. let (seven, not7, three) = (k(self, 7), k(self, !7), k(self, 3));
  6882. let p = self.s.m.bin(c, Bin::And, lane, seven);
  6883. let sh = self.s.m.bin(c, Bin::Mul, p, three);
  6884. let sel = k(self, sel);
  6885. let pick = self.s.m.bin(c, Bin::LShr, sel, sh);
  6886. let pick = self.s.m.bin(c, Bin::And, pick, seven);
  6887. let base = self.s.m.bin(c, Bin::And, lane, not7);
  6888. (self.s.m.bin(c, Bin::Or, base, pick), None, None, false)
  6889. }
  6890. Dpp::Row {
  6891. ctrl,
  6892. row_mask,
  6893. bank_mask,
  6894. bound_ctrl,
  6895. ..
  6896. } => {
  6897. let n = u32::from(ctrl & 15);
  6898. let (src, inside) = match ctrl {
  6899. 0..=0xFF => {
  6900. let (three, one, not3) = (k(self, 3), k(self, 1), k(self, !3));
  6901. let p = self.s.m.bin(c, Bin::And, lane, three);
  6902. let sh = self.s.m.bin(c, Bin::Shl, p, one);
  6903. let perm = k(self, u32::from(ctrl));
  6904. let pick = self.s.m.bin(c, Bin::LShr, perm, sh);
  6905. let pick = self.s.m.bin(c, Bin::And, pick, three);
  6906. let base = self.s.m.bin(c, Bin::And, lane, not3);
  6907. (self.s.m.bin(c, Bin::Or, base, pick), None)
  6908. }
  6909. 0x101..=0x10F | 0x111..=0x11F => {
  6910. let nn = k(self, n);
  6911. let left = ctrl < 0x110;
  6912. let (op, p) = if left {
  6913. (Bin::Add, pred::IULT)
  6914. } else {
  6915. (Bin::Sub, pred::IUGE)
  6916. };
  6917. let s = self.s.m.bin(c, op, lane, nn);
  6918. // Left: pos + n < 16; right: pos >= n.
  6919. let bound = if left { k(self, 16 - n) } else { nn };
  6920. (s, Some(self.s.m.cmp(c, p, pos, bound)))
  6921. }
  6922. 0x121..=0x12F => {
  6923. let nn = k(self, n);
  6924. let t = self.s.m.bin(c, Bin::Sub, pos, nn);
  6925. let t = self.s.m.bin(c, Bin::And, t, low);
  6926. (self.s.m.bin(c, Bin::Or, row, t), None)
  6927. }
  6928. 0x140 | 0x141 => {
  6929. let m = k(self, if ctrl == 0x140 { 15 } else { 7 });
  6930. let t = self.s.m.bin(c, Bin::Xor, lane, m);
  6931. (t, None)
  6932. }
  6933. 0x150..=0x15F => {
  6934. let nn = k(self, n);
  6935. (self.s.m.bin(c, Bin::Or, row, nn), None)
  6936. }
  6937. 0x160..=0x16F => {
  6938. let nn = k(self, n);
  6939. (self.s.m.bin(c, Bin::Xor, lane, nn), None)
  6940. }
  6941. _ => return Err("a DPP lane pattern"),
  6942. };
  6943. let masks = (row_mask != 0xF || bank_mask != 0xF).then_some((row_mask, bank_mask));
  6944. (src, inside, masks, bound_ctrl)
  6945. }
  6946. };
  6947. let mut r = if mesh_quad {
  6948. self.quad_pick(x, src)
  6949. } else {
  6950. self.read_lane(x, src)
  6951. };
  6952. let mut enable = None;
  6953. if let Some(inside) = inside {
  6954. if zero {
  6955. let z = k(self, 0);
  6956. r = self.s.m.select(c, inside, r, z);
  6957. } else {
  6958. enable = Some(inside);
  6959. }
  6960. }
  6961. if let Some((rows, banks)) = masks {
  6962. // Row (16 lanes) and bank (4 lanes of a row) write masks.
  6963. let (four, two, three) = (k(self, 4), k(self, 2), k(self, 3));
  6964. let ri = self.s.m.bin(c, Bin::LShr, lane, four);
  6965. let ri = self.s.m.bin(c, Bin::And, ri, three);
  6966. let bi = self.s.m.bin(c, Bin::LShr, lane, two);
  6967. let bi = self.s.m.bin(c, Bin::And, bi, three);
  6968. let (rm, bm) = (k(self, u32::from(rows)), k(self, u32::from(banks)));
  6969. let rb = self.s.m.bin(c, Bin::LShr, rm, ri);
  6970. let bb = self.s.m.bin(c, Bin::LShr, bm, bi);
  6971. let both = self.s.m.bin(c, Bin::And, rb, bb);
  6972. let (one, z) = (k(self, 1), k(self, 0));
  6973. let both = self.s.m.bin(c, Bin::And, both, one);
  6974. let on = self.s.m.cmp(c, pred::NE, both, z);
  6975. enable = Some(match enable {
  6976. Some(e) => self.s.m.bin(c, Bin::And, e, on),
  6977. None => on,
  6978. });
  6979. }
  6980. Ok((r, enable))
  6981. }
  6982. fn valu_op(&mut self, inst: &Inst, guard: Option<V>) -> Result<(), Why> {
  6983. let Fields::Valu(v) = &inst.fields else {
  6984. unreachable!()
  6985. };
  6986. let name = inst.name();
  6987. let c = self.cur;
  6988. let f = |l: &mut Self, k| l.fsrc(inst, k);
  6989. let s = |l: &mut Self, k| l.src(inst, k);
  6990. let float = |l: &mut Self, r: V| l.write_f(inst, r, guard);
  6991. let int = |l: &mut Self, r: V| l.write_i(inst, r, guard);
  6992. if let Some(r) = self.valu16(inst, name, guard) {
  6993. return r;
  6994. }
  6995. if let Some(op) = name.strip_prefix("v_pk_") {
  6996. return self.packed16(inst, op, guard);
  6997. }
  6998. match name {
  6999. "v_mad_u64_u32" => {
  7000. // a * b + c, c and the result 64 bits wide; the carry out
  7001. // of the sum is this lane's bit of the mask it names.
  7002. let (a, b) = (s(self, 0)?, s(self, 1)?);
  7003. let x = self.src64(inst, 2)?;
  7004. let i64t = self.s.m.int(64);
  7005. self.s.flags |= flags::INT64;
  7006. let a = self.s.m.cast(c, Cast::ZExt, a, i64t);
  7007. let b = self.s.m.cast(c, Cast::ZExt, b, i64t);
  7008. let product = self.s.m.bin(c, Bin::Mul, a, b);
  7009. let r = self.s.m.bin(c, Bin::Add, product, x);
  7010. let carry = self.s.m.cmp(c, pred::IULT, r, x);
  7011. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7012. return Err("a 64-bit result");
  7013. };
  7014. let (lo, hi) = self.split64(r);
  7015. self.write(inst, Reg::V(reg), lo, guard);
  7016. self.write(inst, Reg::V(reg + 1), hi, guard);
  7017. if let Some(Operand::Scalar { code, .. }) = v.carry
  7018. && let Some(w) = inst.write(Reg::S(code))
  7019. {
  7020. self.lane_bits.insert(w, carry);
  7021. }
  7022. for &(_, w) in &inst.writes {
  7023. self.vals
  7024. .entry(w)
  7025. .or_insert(Val::Missing("a lane mask read as data"));
  7026. }
  7027. Ok(())
  7028. }
  7029. "v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => {
  7030. let n = s(self, 0)?;
  7031. let x = self.src64(inst, 1)?;
  7032. let i64t = self.s.m.int(64);
  7033. let k63 = self.s.m.i32(63);
  7034. let n = self.s.m.bin(c, Bin::And, n, k63);
  7035. let n = self.s.m.cast(c, Cast::ZExt, n, i64t);
  7036. let op = match name {
  7037. "v_lshlrev_b64" => Bin::Shl,
  7038. "v_lshrrev_b64" => Bin::LShr,
  7039. _ => Bin::AShr,
  7040. };
  7041. let r = self.s.m.bin(c, op, x, n);
  7042. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7043. return Err("a 64-bit result");
  7044. };
  7045. let (lo, hi) = self.split64(r);
  7046. self.write(inst, Reg::V(reg), lo, guard);
  7047. self.write(inst, Reg::V(reg + 1), hi, guard);
  7048. Ok(())
  7049. }
  7050. "v_cubeid_f32" | "v_cubesc_f32" | "v_cubetc_f32" | "v_cubema_f32" => {
  7051. // Cube-map face coordinates (AMD's ISA): the major axis is z
  7052. // when |z| >= |x| and |z| >= |y|, else y when |y| >= |x|,
  7053. // else x.
  7054. let (x, y, z) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7055. let (ax, ay, az) = (self.unary(6, x), self.unary(6, y), self.unary(6, z));
  7056. let zx = self.s.m.cmp(c, pred::OGE, az, ax);
  7057. let zy = self.s.m.cmp(c, pred::OGE, az, ay);
  7058. let zmaj = self.s.m.bin(c, Bin::And, zx, zy);
  7059. let ymaj = self.s.m.cmp(c, pred::OGE, ay, ax);
  7060. let zero = self.s.m.f32(0);
  7061. let neg = |l: &mut Self, v: V| l.s.m.cmp(c, pred::OLT, v, zero);
  7062. let minus = |l: &mut Self, v: V| {
  7063. let z = l.s.m.f32(0x8000_0000);
  7064. l.s.m.bin(c, Bin::Sub, z, v)
  7065. };
  7066. let pick = |l: &mut Self, zv: V, yv: V, xv: V| {
  7067. let t = l.s.m.select(c, ymaj, yv, xv);
  7068. l.s.m.select(c, zmaj, zv, t)
  7069. };
  7070. let r = match name {
  7071. "v_cubeid_f32" => {
  7072. let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits());
  7073. let (nz, ny, nx) = (neg(self, z), neg(self, y), neg(self, x));
  7074. let (f5, f4, f3, f2, f1, f0) = (
  7075. k(self, 5.0),
  7076. k(self, 4.0),
  7077. k(self, 3.0),
  7078. k(self, 2.0),
  7079. k(self, 1.0),
  7080. k(self, 0.0),
  7081. );
  7082. let zf = self.s.m.select(c, nz, f5, f4);
  7083. let yf = self.s.m.select(c, ny, f3, f2);
  7084. let xf = self.s.m.select(c, nx, f1, f0);
  7085. pick(self, zf, yf, xf)
  7086. }
  7087. "v_cubesc_f32" => {
  7088. let (nz, nx) = (neg(self, z), neg(self, x));
  7089. let (mx, mz) = (minus(self, x), minus(self, z));
  7090. let zf = self.s.m.select(c, nz, mx, x);
  7091. let xf = self.s.m.select(c, nx, z, mz);
  7092. pick(self, zf, x, xf)
  7093. }
  7094. "v_cubetc_f32" => {
  7095. let ny = neg(self, y);
  7096. let (my, mz) = (minus(self, y), minus(self, z));
  7097. let yf = self.s.m.select(c, ny, mz, z);
  7098. pick(self, my, yf, my)
  7099. }
  7100. _ => {
  7101. let t = pick(self, z, y, x);
  7102. let two = self.s.m.f32(2.0f32.to_bits());
  7103. self.s.m.bin(c, Bin::Mul, t, two)
  7104. }
  7105. };
  7106. float(self, r)
  7107. }
  7108. "v_movrels_b32" | "v_movreld_b32" | "v_movrelsd_b32" => {
  7109. // M0 indexes the source (movrels), the destination (movreld)
  7110. // or both, from the encoded register up to the program's
  7111. // VGPR count (the registers the instruction reads or writes).
  7112. let m0 = self.i32_of(inst.read(Reg::S(crate::ir::M0)).ok_or("M0")?)?;
  7113. let (
  7114. Some(&Operand::Vector { reg: sreg, .. }),
  7115. Some(Operand::Vector { reg: dreg, .. }),
  7116. ) = (v.src.first(), v.dst)
  7117. else {
  7118. return Err("an M0-relative move");
  7119. };
  7120. let indexed_src = name != "v_movreld_b32";
  7121. let value = if indexed_src {
  7122. let mut r = self.s.m.i32(0);
  7123. for k in 0..=255u8.saturating_sub(sreg) {
  7124. let Some(x) = inst.read(Reg::V(sreg + k)) else {
  7125. break;
  7126. };
  7127. let x = self.i32_of(x)?;
  7128. let kk = self.s.m.i32(u32::from(k));
  7129. let is = self.s.m.cmp(c, pred::EQ, m0, kk);
  7130. r = self.s.m.select(c, is, x, r);
  7131. }
  7132. r
  7133. } else {
  7134. s(self, 0)?
  7135. };
  7136. if name == "v_movrels_b32" {
  7137. return int(self, value);
  7138. }
  7139. for k in 0..=255u8.saturating_sub(dreg) {
  7140. let Some(_) = inst.write(Reg::V(dreg + k)) else {
  7141. break;
  7142. };
  7143. let old = match inst.read(Reg::V(dreg + k)) {
  7144. Some(o) => self.i32_of(o)?,
  7145. None => self.s.m.i32(0),
  7146. };
  7147. let kk = self.s.m.i32(u32::from(k));
  7148. let is = self.s.m.cmp(c, pred::EQ, m0, kk);
  7149. let x = self.s.m.select(c, is, value, old);
  7150. self.write_placed(inst, Reg::V(dreg + k), x, guard);
  7151. }
  7152. Ok(())
  7153. }
  7154. "v_swap_b32" => {
  7155. let (
  7156. Some(&Operand::Vector { reg: sreg, .. }),
  7157. Some(Operand::Vector { reg: dreg, .. }),
  7158. ) = (v.src.first(), v.dst)
  7159. else {
  7160. return Err("v_swap_b32");
  7161. };
  7162. let a = self.i32_of(inst.read(Reg::V(dreg)).ok_or("v_swap_b32")?)?;
  7163. let b = self.i32_of(inst.read(Reg::V(sreg)).ok_or("v_swap_b32")?)?;
  7164. self.write_placed(inst, Reg::V(dreg), b, guard);
  7165. if dreg != sreg {
  7166. self.write_placed(inst, Reg::V(sreg), a, guard);
  7167. }
  7168. Ok(())
  7169. }
  7170. "v_ffbh_u32" | "v_ffbh_i32" => {
  7171. // Counted from the top bit, -1 when none (DXIL's too).
  7172. let a = s(self, 0)?;
  7173. let op = if name == "v_ffbh_u32" { 33 } else { 34 };
  7174. let r = self
  7175. .s
  7176. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  7177. int(self, r)
  7178. }
  7179. "v_dot4c_i32_i8" => {
  7180. // D += the dot product of four signed bytes, wrapping: DXIL's
  7181. // Dot4AddI8Packed.
  7182. let (a, bb) = (s(self, 0)?, s(self, 1)?);
  7183. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7184. return Err("an accumulator");
  7185. };
  7186. let acc = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?;
  7187. let i32_ty = self.s.t.i32;
  7188. let r = self.s.op(
  7189. c,
  7190. "dot4AddPacked.i32",
  7191. Attr::ReadNone,
  7192. i32_ty,
  7193. 163,
  7194. &[acc, a, bb],
  7195. );
  7196. int(self, r)
  7197. }
  7198. "v_dot4_i32_i8" => {
  7199. // VOP3P: op_sel picks the half each multiplicand's low half
  7200. // reads, op_sel_hi its high half's; the accumulator is read
  7201. // whole (as AMD's compilers fold constants into it).
  7202. if v.clamp || v.neg_hi != 0 {
  7203. return Err("a saturating or negated dot product");
  7204. }
  7205. let mut xs = Vec::new();
  7206. for k in 0..2 {
  7207. let x = s(self, k)?;
  7208. let (lo, hi) = (v.opsel >> k & 1 != 0, v.opsel_hi >> k & 1 != 0);
  7209. if (lo, hi) == (false, true) {
  7210. xs.push(x);
  7211. continue;
  7212. }
  7213. let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
  7214. let top = self.s.m.bin(c, Bin::LShr, x, k16);
  7215. let bottom = self.s.m.bin(c, Bin::And, x, low);
  7216. let hi = self
  7217. .s
  7218. .m
  7219. .bin(c, Bin::Shl, if hi { top } else { bottom }, k16);
  7220. xs.push(self.s.m.bin(c, Bin::Or, if lo { top } else { bottom }, hi));
  7221. }
  7222. let acc = s(self, 2)?;
  7223. let i32_ty = self.s.t.i32;
  7224. let r = self.s.op(
  7225. c,
  7226. "dot4AddPacked.i32",
  7227. Attr::ReadNone,
  7228. i32_ty,
  7229. 163,
  7230. &[acc, xs[0], xs[1]],
  7231. );
  7232. int(self, r)
  7233. }
  7234. "v_mov_b32" => {
  7235. if v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 {
  7236. let a = f(self, 0)?;
  7237. return float(self, a);
  7238. }
  7239. let a = s(self, 0)?;
  7240. int(self, a)
  7241. }
  7242. "v_add_f32" | "v_sub_f32" | "v_subrev_f32" | "v_mul_f32" | "v_mul_legacy_f32"
  7243. | "v_max_f32" | "v_min_f32" => {
  7244. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  7245. let r = match name {
  7246. "v_add_f32" => self.s.m.bin(c, Bin::Add, a, bb),
  7247. "v_sub_f32" => self.s.m.bin(c, Bin::Sub, a, bb),
  7248. "v_subrev_f32" => self.s.m.bin(c, Bin::Sub, bb, a),
  7249. "v_mul_f32" => self.s.m.bin(c, Bin::Mul, a, bb),
  7250. "v_mul_legacy_f32" => self.legacy_mul(a, bb),
  7251. "v_max_f32" => self.max_min(true, a, bb),
  7252. _ => self.max_min(false, a, bb),
  7253. };
  7254. float(self, r)
  7255. }
  7256. "v_fma_f32" | "v_fmaak_f32" | "v_fmamk_f32" => {
  7257. // shortcut: DXIL has no fused f32 multiply-add; FMad lets the driver fuse.
  7258. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7259. let r = self.fmad(a, bb, cc);
  7260. float(self, r)
  7261. }
  7262. "v_div_scale_f32" => {
  7263. // RDNA2 ISA: src0 = value to scale, src1 = denominator, src2 = numerator.
  7264. let (a, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7265. let (ai, ni, di) = (self.as_int(a), self.as_int(num), self.as_int(den));
  7266. let (k23, k255, kabs) = (
  7267. self.s.m.i32(23),
  7268. self.s.m.i32(0xFF),
  7269. self.s.m.i32(0x7FFF_FFFF),
  7270. );
  7271. let (zero, k23_exp, k232_exp, k96) = (
  7272. self.s.m.i32(0),
  7273. self.s.m.i32(23),
  7274. self.s.m.i32(232),
  7275. self.s.m.i32(96),
  7276. );
  7277. let exp_of = |l: &mut Self, x: V| {
  7278. let s = l.s.m.bin(c, Bin::LShr, x, k23);
  7279. l.s.m.bin(c, Bin::And, s, k255)
  7280. };
  7281. let (e1, e2) = (exp_of(self, ni), exp_of(self, di));
  7282. let n_abs = self.s.m.bin(c, Bin::And, ni, kabs);
  7283. let d_abs = self.s.m.bin(c, Bin::And, di, kabs);
  7284. let z1 = self.s.m.cmp(c, pred::EQ, n_abs, zero);
  7285. let z2 = self.s.m.cmp(c, pred::EQ, d_abs, zero);
  7286. let any_zero = self.s.m.bin(c, Bin::Or, z1, z2);
  7287. let special = {
  7288. let s1 = self.s.m.cmp(c, pred::EQ, e1, k255);
  7289. let s2 = self.s.m.cmp(c, pred::EQ, e2, k255);
  7290. let a12 = self.s.m.bin(c, Bin::Or, s1, s2);
  7291. self.s.m.bin(c, Bin::Or, a12, any_zero)
  7292. };
  7293. let is_den = self.s.m.cmp(c, pred::EQ, ai, di);
  7294. let diff = self.s.m.bin(c, Bin::Sub, e2, e1);
  7295. let den_tiny = self.s.m.cmp(c, pred::IULE, e2, k23_exp);
  7296. let den_huge = self.s.m.cmp(c, pred::IUGE, e2, k232_exp);
  7297. let num_tiny_exp = self.s.m.cmp(c, pred::IULE, e1, k23_exp);
  7298. let num_huge = self.s.m.cmp(c, pred::IUGE, e1, k232_exp);
  7299. let num_gap = self.s.m.cmp(c, pred::SGE, diff, k96);
  7300. let not_den_huge = {
  7301. let t = self.s.m.bool(true);
  7302. self.s.m.bin(c, Bin::Xor, den_huge, t)
  7303. };
  7304. let num_gap = self.s.m.bin(c, Bin::And, num_gap, not_den_huge);
  7305. let num_tiny = self.s.m.bin(c, Bin::Or, num_tiny_exp, num_gap);
  7306. let up_raw = self.s.m.select(c, is_den, den_tiny, num_tiny);
  7307. let dn_raw = self.s.m.select(c, is_den, den_huge, num_huge);
  7308. let not_special = {
  7309. let t = self.s.m.bool(true);
  7310. self.s.m.bin(c, Bin::Xor, special, t)
  7311. };
  7312. let up = self.s.m.bin(c, Bin::And, up_raw, not_special);
  7313. let dn = self.s.m.bin(c, Bin::And, dn_raw, not_special);
  7314. let uncancelled = {
  7315. let x_tiny = self.s.m.bin(c, Bin::Xor, den_tiny, num_tiny);
  7316. let x_huge = self.s.m.bin(c, Bin::Xor, den_huge, num_huge);
  7317. self.s.m.bin(c, Bin::Or, x_tiny, x_huge)
  7318. };
  7319. let flag_raw = self.s.m.select(c, is_den, uncancelled, up_raw);
  7320. let flag = self.s.m.bin(c, Bin::And, flag_raw, not_special);
  7321. let k_up = self.s.m.f32(0x5F80_0000);
  7322. let k_dn = self.s.m.f32(0x1F80_0000);
  7323. let a_up = self.s.m.bin(c, Bin::Mul, a, k_up);
  7324. let a_dn = self.s.m.bin(c, Bin::Mul, a, k_dn);
  7325. let r = self.s.m.select(c, dn, a_dn, a);
  7326. let r = self.s.m.select(c, up, a_up, r);
  7327. let qnan = self.s.m.f32(0x7FC0_0000);
  7328. let r = self.s.m.select(c, any_zero, qnan, r);
  7329. float(self, r)?;
  7330. if let Some(Operand::Scalar { code, .. }) = v.carry
  7331. && let Some(w) = inst.write(Reg::S(code))
  7332. {
  7333. self.lane_bits.insert(w, flag);
  7334. }
  7335. for &(_, w) in &inst.writes {
  7336. self.vals
  7337. .entry(w)
  7338. .or_insert(Val::Missing("a lane mask read as data"));
  7339. }
  7340. Ok(())
  7341. }
  7342. "v_div_fmas_f32" => {
  7343. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7344. let m = inst
  7345. .read(Reg::S(crate::ir::VCC))
  7346. .and_then(|v| self.x.st.masks.get(&v).copied())
  7347. .ok_or("v_div_fmas_f32 without VCC")?;
  7348. let vcc = self.boolean(m, c)?;
  7349. let tmp = self.fmad(a, bb, cc);
  7350. let ci = self.as_int(cc);
  7351. let (k23, k255, k128) = (self.s.m.i32(23), self.s.m.i32(0xFF), self.s.m.i32(128));
  7352. let sh = self.s.m.bin(c, Bin::LShr, ci, k23);
  7353. let exp = self.s.m.bin(c, Bin::And, sh, k255);
  7354. let exp_ge = self.s.m.cmp(c, pred::IUGE, exp, k128);
  7355. let (k_up, k_dn) = (self.s.m.f32(0x5F80_0000), self.s.m.f32(0x1F80_0000));
  7356. let scale = self.s.m.select(c, exp_ge, k_up, k_dn);
  7357. let scaled = self.s.m.bin(c, Bin::Mul, tmp, scale);
  7358. let r = self.s.m.select(c, vcc, scaled, tmp);
  7359. float(self, r)
  7360. }
  7361. "v_div_fixup_f32" => {
  7362. let (q, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7363. let (qi, di, ni) = (self.as_int(q), self.as_int(den), self.as_int(num));
  7364. let (ksign, kabs, kinf) = (
  7365. self.s.m.i32(0x8000_0000),
  7366. self.s.m.i32(0x7FFF_FFFF),
  7367. self.s.m.i32(0x7F80_0000),
  7368. );
  7369. let (kqnan_bit, kneg_qnan, zero) = (
  7370. self.s.m.i32(0x0040_0000),
  7371. self.s.m.i32(0xFFC0_0000),
  7372. self.s.m.i32(0),
  7373. );
  7374. let sign = {
  7375. let x = self.s.m.bin(c, Bin::Xor, ni, di);
  7376. self.s.m.bin(c, Bin::And, x, ksign)
  7377. };
  7378. let q_abs = self.s.m.bin(c, Bin::And, qi, kabs);
  7379. let d_abs = self.s.m.bin(c, Bin::And, di, kabs);
  7380. let n_abs = self.s.m.bin(c, Bin::And, ni, kabs);
  7381. let q_nan = self.s.m.cmp(c, pred::IUGT, q_abs, kinf);
  7382. let d_nan = self.s.m.cmp(c, pred::IUGT, d_abs, kinf);
  7383. let n_nan = self.s.m.cmp(c, pred::IUGT, n_abs, kinf);
  7384. let d_inf = self.s.m.cmp(c, pred::EQ, d_abs, kinf);
  7385. let n_inf = self.s.m.cmp(c, pred::EQ, n_abs, kinf);
  7386. let d_zero = self.s.m.cmp(c, pred::EQ, d_abs, zero);
  7387. let n_zero = self.s.m.cmp(c, pred::EQ, n_abs, zero);
  7388. let both_inf = self.s.m.bin(c, Bin::And, n_inf, d_inf);
  7389. let both_zero = self.s.m.bin(c, Bin::And, n_zero, d_zero);
  7390. let invalid = self.s.m.bin(c, Bin::Or, both_inf, both_zero);
  7391. let make_inf = {
  7392. let t = self.s.m.bin(c, Bin::Or, n_inf, d_zero);
  7393. self.s.m.bin(c, Bin::Or, t, q_nan)
  7394. };
  7395. let make_zero = self.s.m.bin(c, Bin::Or, d_inf, n_zero);
  7396. let signed_q = self.s.m.bin(c, Bin::Or, sign, q_abs);
  7397. let signed_inf = self.s.m.bin(c, Bin::Or, sign, kinf);
  7398. let n_qnan = self.s.m.bin(c, Bin::Or, ni, kqnan_bit);
  7399. let d_qnan = self.s.m.bin(c, Bin::Or, di, kqnan_bit);
  7400. let r = self.s.m.select(c, make_zero, sign, signed_q);
  7401. let r = self.s.m.select(c, make_inf, signed_inf, r);
  7402. let r = self.s.m.select(c, invalid, kneg_qnan, r);
  7403. let r = self.s.m.select(c, d_nan, d_qnan, r);
  7404. let r = self.s.m.select(c, n_nan, n_qnan, r);
  7405. let rf = self.as_float(r);
  7406. float(self, rf)
  7407. }
  7408. "v_fmac_f32" | "v_mac_f32" | "v_mac_legacy_f32" => {
  7409. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  7410. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7411. return Err("an accumulator");
  7412. };
  7413. let acc = inst.read(Reg::V(reg)).ok_or("an accumulator")?;
  7414. let acc = match self.floats.get(&acc) {
  7415. Some(&x) => x,
  7416. None => {
  7417. let x = self.i32_of(acc)?;
  7418. self.as_float(x)
  7419. }
  7420. };
  7421. let r = match name {
  7422. "v_fmac_f32" => self.fmad(a, bb, acc),
  7423. "v_mac_f32" => {
  7424. let m = self.s.m.bin(c, Bin::Mul, a, bb);
  7425. self.s.m.bin(c, Bin::Add, m, acc)
  7426. }
  7427. _ => {
  7428. let m = self.legacy_mul(a, bb);
  7429. self.s.m.bin(c, Bin::Add, m, acc)
  7430. }
  7431. };
  7432. float(self, r)
  7433. }
  7434. "v_mad_f32" | "v_madak_f32" | "v_madmk_f32" | "v_mad_legacy_f32" => {
  7435. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7436. let m = if name == "v_mad_legacy_f32" {
  7437. self.legacy_mul(a, bb)
  7438. } else {
  7439. self.s.m.bin(c, Bin::Mul, a, bb)
  7440. };
  7441. let r = self.s.m.bin(c, Bin::Add, m, cc);
  7442. float(self, r)
  7443. }
  7444. "v_max3_f32" | "v_min3_f32" | "v_med3_f32" => {
  7445. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7446. let r = match name {
  7447. "v_max3_f32" => {
  7448. let t = self.max_min(true, a, bb);
  7449. self.max_min(true, t, cc)
  7450. }
  7451. "v_min3_f32" => {
  7452. let t = self.max_min(false, a, bb);
  7453. self.max_min(false, t, cc)
  7454. }
  7455. _ => self.med3(a, bb, cc),
  7456. };
  7457. float(self, r)
  7458. }
  7459. "v_rcp_f32" | "v_rcp_iflag_f32" => {
  7460. // shortcut: the hardware reciprocal is approximate (1 ULP); this divides.
  7461. let a = f(self, 0)?;
  7462. let one = self.s.m.f32(1.0f32.to_bits());
  7463. let r = self.s.m.bin(c, Bin::SDiv, one, a);
  7464. float(self, r)
  7465. }
  7466. "v_rsq_f32" | "v_sqrt_f32" | "v_log_f32" | "v_exp_f32" | "v_fract_f32"
  7467. | "v_trunc_f32" | "v_floor_f32" | "v_ceil_f32" | "v_rndne_f32" | "v_sin_f32"
  7468. | "v_cos_f32" => {
  7469. let a = f(self, 0)?;
  7470. let op = match name {
  7471. "v_rsq_f32" => 25,
  7472. "v_sqrt_f32" => 24,
  7473. "v_log_f32" => 23,
  7474. "v_exp_f32" => 21,
  7475. "v_fract_f32" => 22,
  7476. "v_trunc_f32" => 29,
  7477. "v_floor_f32" => 27,
  7478. "v_ceil_f32" => 28,
  7479. "v_rndne_f32" => 26,
  7480. "v_sin_f32" => 13,
  7481. _ => 12,
  7482. };
  7483. let r = match op {
  7484. 12 | 13 => self.trig_turns(a, op == 12),
  7485. 22 => self.fract(a, 1.0, f32::from_bits(0x3F7F_FFFF)),
  7486. _ => self.unary(op, a),
  7487. };
  7488. float(self, r)
  7489. }
  7490. "v_cvt_i32_f32" | "v_cvt_u32_f32" | "v_cvt_flr_i32_f32" | "v_cvt_rpi_i32_f32" => {
  7491. let mut a = f(self, 0)?;
  7492. if name == "v_cvt_rpi_i32_f32" {
  7493. let h = self.s.m.f32(0.5f32.to_bits());
  7494. a = self.s.m.bin(c, Bin::Add, a, h);
  7495. }
  7496. if name != "v_cvt_i32_f32" && name != "v_cvt_u32_f32" {
  7497. a = self.unary(27, a);
  7498. }
  7499. // D3D's conversions saturate and give 0 for NaN, as the
  7500. // hardware does (checked on the RX 6700 XT and WARP).
  7501. let op = if name == "v_cvt_u32_f32" {
  7502. Cast::FpToUi
  7503. } else {
  7504. Cast::FpToSi
  7505. };
  7506. let r = self.s.m.cast(c, op, a, self.s.t.i32);
  7507. int(self, r)
  7508. }
  7509. "v_cvt_f32_f64" => {
  7510. let (lo, hi) = self.f64_pair(inst, 0)?;
  7511. let bits = self.f64_to_f32_bits(lo, hi);
  7512. let r = self.as_float(bits);
  7513. float(self, r)
  7514. }
  7515. "v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1"
  7516. | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => {
  7517. let mut a = s(self, 0)?;
  7518. if let Some(n) = name.strip_prefix("v_cvt_f32_ubyte") {
  7519. let sh = self.s.m.i32(8 * u32::from(n.as_bytes()[0] - b'0'));
  7520. let ff = self.s.m.i32(0xff);
  7521. a = self.s.m.bin(c, Bin::LShr, a, sh);
  7522. a = self.s.m.bin(c, Bin::And, a, ff);
  7523. }
  7524. let op = if name == "v_cvt_f32_i32" {
  7525. Cast::SiToFp
  7526. } else {
  7527. Cast::UiToFp
  7528. };
  7529. let r = self.s.m.cast(c, op, a, self.s.t.f32);
  7530. float(self, r)
  7531. }
  7532. "v_cvt_off_f32_i4" => {
  7533. // The low nibble as a signed 4-bit integer, over 16.
  7534. let a = s(self, 0)?;
  7535. let k28 = self.s.m.i32(28);
  7536. let a = self.s.m.bin(c, Bin::Shl, a, k28);
  7537. let a = self.s.m.bin(c, Bin::AShr, a, k28);
  7538. let f = self.s.m.cast(c, Cast::SiToFp, a, self.s.t.f32);
  7539. let k = self.s.m.f32(0.0625f32.to_bits());
  7540. let r = self.s.m.bin(c, Bin::Mul, f, k);
  7541. float(self, r)
  7542. }
  7543. "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => {
  7544. // Each source is f32, or with op_sel_hi the low (op_sel: high)
  7545. // f16 half; neg_hi is the absolute value here.
  7546. let mut xs = Vec::new();
  7547. for i in 0..3 {
  7548. let op = v.src.get(i).ok_or("a missing operand")?;
  7549. let mut x = if v.opsel_hi >> i & 1 != 0 {
  7550. let x = self.f16_operand(inst, op)?;
  7551. let h = if v.opsel >> i & 1 != 0 {
  7552. let k16 = self.s.m.i32(16);
  7553. self.s.m.bin(c, Bin::LShr, x, k16)
  7554. } else {
  7555. x
  7556. };
  7557. self.s
  7558. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h])
  7559. } else {
  7560. let x = self.operand(inst, op)?;
  7561. self.as_float(x)
  7562. };
  7563. if v.neg_hi >> i & 1 != 0 {
  7564. x = self.unary(6, x);
  7565. }
  7566. if v.neg >> i & 1 != 0 {
  7567. let z = self.s.m.f32(0x8000_0000);
  7568. x = self.s.m.bin(c, Bin::Sub, z, x);
  7569. }
  7570. xs.push(x);
  7571. }
  7572. let mut r = self.fmad(xs[0], xs[1], xs[2]);
  7573. if name == "v_fma_mix_f32" {
  7574. return float(self, r);
  7575. }
  7576. if v.clamp {
  7577. r = self.unary(7, r);
  7578. }
  7579. // The f16 result goes to one half; the other half stays.
  7580. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7581. return Err("a mixed-precision result");
  7582. };
  7583. let old = match inst.read(Reg::V(reg)) {
  7584. Some(o) => self.i32_of(o)?,
  7585. None => self.s.m.i32(0),
  7586. };
  7587. let h = self
  7588. .s
  7589. .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[r]);
  7590. let (keep, h) = if name == "v_fma_mixhi_f16" {
  7591. let k16 = self.s.m.i32(16);
  7592. (0xFFFF, self.s.m.bin(c, Bin::Shl, h, k16))
  7593. } else {
  7594. (0xFFFF_0000, h)
  7595. };
  7596. let keep = self.s.m.i32(keep);
  7597. let old = self.s.m.bin(c, Bin::And, old, keep);
  7598. let x = self.s.m.bin(c, Bin::Or, old, h);
  7599. self.write(inst, Reg::V(reg), x, guard);
  7600. Ok(())
  7601. }
  7602. "v_cvt_pkrtz_f16_f32" => {
  7603. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  7604. let lo = self.f16_toward_zero(a);
  7605. let hi = self.f16_toward_zero(bb);
  7606. let sh = self.s.m.i32(16);
  7607. let hi = self.s.m.bin(c, Bin::Shl, hi, sh);
  7608. let r = self.s.m.bin(c, Bin::Or, lo, hi);
  7609. int(self, r)
  7610. }
  7611. "v_cvt_f16_f32" if v.opsel == 0 => {
  7612. // Rounded to nearest even (the MODE default) into the low half.
  7613. let a = f(self, 0)?;
  7614. let r = self
  7615. .s
  7616. .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[a]);
  7617. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7618. return Err("a 16-bit result outside a VGPR");
  7619. };
  7620. let r = self.low_half(inst, reg, r);
  7621. int(self, r)
  7622. }
  7623. "v_pack_b32_f16" => {
  7624. // Two f16 sources (op_sel: their high halves; abs and neg on
  7625. // the sign bit) into the low and high half.
  7626. let mut halves = Vec::new();
  7627. for k in 0..2 {
  7628. let op = v.src.get(k).ok_or("a missing operand")?;
  7629. let mut x = self.f16_operand(inst, op)?;
  7630. if v.opsel >> k & 1 != 0 {
  7631. let k16 = self.s.m.i32(16);
  7632. x = self.s.m.bin(c, Bin::LShr, x, k16);
  7633. }
  7634. let mask = if v.abs >> k & 1 != 0 { 0x7FFF } else { 0xFFFF };
  7635. let mask = self.s.m.i32(mask);
  7636. x = self.s.m.bin(c, Bin::And, x, mask);
  7637. if v.neg >> k & 1 != 0 {
  7638. let sign = self.s.m.i32(0x8000);
  7639. x = self.s.m.bin(c, Bin::Xor, x, sign);
  7640. }
  7641. halves.push(x);
  7642. }
  7643. let k16 = self.s.m.i32(16);
  7644. let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16);
  7645. let r = self.s.m.bin(c, Bin::Or, halves[0], hi);
  7646. int(self, r)
  7647. }
  7648. "v_cvt_f32_f16" if v.opsel == 0 => {
  7649. let a = s(self, 0)?;
  7650. let r = self
  7651. .s
  7652. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[a]);
  7653. float(self, r)
  7654. }
  7655. "v_cndmask_b32" => {
  7656. let mask = match v.src.get(2) {
  7657. Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
  7658. _ => None,
  7659. };
  7660. const UNTRACKED: Why = "a select on an untracked mask";
  7661. let cond = match mask.and_then(|m| self.x.st.masks.get(&m).copied()) {
  7662. Some(m) => self.boolean(m, c)?,
  7663. // A mask the code holds as a number (a constant bit
  7664. // pattern: every other lane, every other pair...):
  7665. // this lane's bit of it. Exact where host lanes are
  7666. // the console's.
  7667. None if self.mask_data == MaskData::Console => {
  7668. // Each host wave taken as a wave of its own has no
  7669. // console lane numbers to pick the bits by.
  7670. if self.local {
  7671. return Err("a constant lane mask in a half-wave");
  7672. }
  7673. let m = mask.ok_or(UNTRACKED)?;
  7674. let lo = self.i32_of(m).map_err(|_| UNTRACKED)?;
  7675. // wave64: the register after it holds lanes 32-63.
  7676. let high = match v.src.get(2) {
  7677. Some(&Operand::Scalar { code, .. }) if self.x.native.wave64 => {
  7678. Some(inst.read(Reg::S(code + 1)).ok_or(UNTRACKED)?)
  7679. }
  7680. _ => None,
  7681. };
  7682. let hi = match high {
  7683. Some(h) => Some(self.i32_of(h).map_err(|_| UNTRACKED)?),
  7684. None => None,
  7685. };
  7686. self.cross_lane(false)?;
  7687. self.lane_bit(c, lo, hi)
  7688. }
  7689. None => return Err(UNTRACKED),
  7690. };
  7691. if v.abs != 0 || v.neg != 0 {
  7692. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  7693. let r = self.s.m.select(c, cond, bb, a);
  7694. return float(self, r);
  7695. }
  7696. let (a, bb) = (s(self, 0)?, s(self, 1)?);
  7697. let r = self.s.m.select(c, cond, bb, a);
  7698. int(self, r)
  7699. }
  7700. "v_add_co_u32" | "v_sub_co_u32" | "v_subrev_co_u32" | "v_add_co_ci_u32"
  7701. | "v_sub_co_ci_u32" | "v_subrev_co_ci_u32" => {
  7702. // The carry (borrow) out is a lane mask: this lane's bit.
  7703. let (mut a, mut bb) = (s(self, 0)?, s(self, 1)?);
  7704. if name.contains("subrev") {
  7705. std::mem::swap(&mut a, &mut bb);
  7706. }
  7707. let cin = if name.ends_with("_ci_u32") {
  7708. let m = match v.src.get(2) {
  7709. Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
  7710. _ => None,
  7711. };
  7712. let m = m
  7713. .and_then(|m| self.x.st.masks.get(&m).copied())
  7714. .ok_or("a carry-in from an untracked mask")?;
  7715. Some(self.boolean(m, c)?)
  7716. } else {
  7717. None
  7718. };
  7719. let (r, carry) = self.add_sub_carry(c, name.starts_with("v_add"), a, bb, cin);
  7720. int(self, r)?;
  7721. if let Some(Operand::Scalar { code, .. }) = v.carry
  7722. && let Some(w) = inst.write(Reg::S(code))
  7723. {
  7724. self.lane_bits.insert(w, carry);
  7725. }
  7726. for &(_, w) in &inst.writes {
  7727. self.vals
  7728. .entry(w)
  7729. .or_insert(Val::Missing("a lane mask read as data"));
  7730. }
  7731. Ok(())
  7732. }
  7733. "v_permlane16_b32" | "v_permlanex16_b32" => {
  7734. // RDNA2 ISA 12.12: each nibble of {src2, src1} selects a lane
  7735. // in this row of 16, or the other row of the same 32-lane half.
  7736. // OP_SEL[0:1] are fetch-inactive and bound-control, not half selects.
  7737. if v.abs != 0 || v.neg != 0 || v.opsel & !3 != 0 {
  7738. return Err("permlane input modifiers");
  7739. }
  7740. self.cross_lane(false)?;
  7741. let fetch_inactive = v.opsel & 1 != 0;
  7742. if fetch_inactive
  7743. && !all_lane_blocks(self.x.st).is_some_and(|all| all[self.cur_ir])
  7744. {
  7745. // DXIL cannot read the last VGPR value of a host invocation
  7746. // that has left through a lane branch. A guard keeps it here.
  7747. return Err("a permlane fetch from lanes outside the host branch");
  7748. }
  7749. let (x, lo, hi) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  7750. let lane = self.lane_index();
  7751. let (k7, k8, k15, k16, k31, k32, k4, one, zero) = (
  7752. self.s.m.i32(7),
  7753. self.s.m.i32(8),
  7754. self.s.m.i32(15),
  7755. self.s.m.i32(16),
  7756. self.s.m.i32(31),
  7757. self.s.m.i32(32),
  7758. self.s.m.i32(4),
  7759. self.s.m.i32(1),
  7760. self.s.m.i32(0),
  7761. );
  7762. let pos = self.s.m.bin(c, Bin::And, lane, k15);
  7763. let lower = self.s.m.cmp(c, pred::IULT, pos, k8);
  7764. let packed = self.s.m.select(c, lower, lo, hi);
  7765. let shift = self.s.m.bin(c, Bin::And, pos, k7);
  7766. let shift = self.s.m.bin(c, Bin::Mul, shift, k4);
  7767. let pick = self.s.m.bin(c, Bin::LShr, packed, shift);
  7768. let pick = self.s.m.bin(c, Bin::And, pick, k15);
  7769. let not15 = self.s.m.i32(!15);
  7770. let mut row = self.s.m.bin(c, Bin::And, lane, not15);
  7771. if name == "v_permlanex16_b32" {
  7772. row = self.s.m.bin(c, Bin::Xor, row, k16);
  7773. }
  7774. let src = self.s.m.bin(c, Bin::Or, row, pick);
  7775. let r = if fetch_inactive {
  7776. self.read_lane(x, src)
  7777. } else {
  7778. // Ballot the console EXEC guard as well as the host's active
  7779. // invocations. Never shuffle from an inactive host lane.
  7780. let enabled = guard.unwrap_or_else(|| self.s.m.bool(true));
  7781. let i32t = self.s.t.i32;
  7782. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  7783. let mask = self.s.op(
  7784. c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[enabled],
  7785. );
  7786. let lo = self.s.m.extract(c, mask, 0);
  7787. let hi = self.s.m.extract(c, mask, 1);
  7788. let lower = self.s.m.cmp(c, pred::IULT, src, k32);
  7789. let word = self.s.m.select(c, lower, lo, hi);
  7790. let bit = self.s.m.bin(c, Bin::And, src, k31);
  7791. let bit = self.s.m.bin(c, Bin::LShr, word, bit);
  7792. let bit = self.s.m.bin(c, Bin::And, bit, one);
  7793. let active = self.s.m.cmp(c, pred::NE, bit, zero);
  7794. let safe = self.s.m.select(c, active, src, lane);
  7795. let read = self.read_lane(x, safe);
  7796. let fallback = if v.opsel & 2 != 0 {
  7797. zero
  7798. } else {
  7799. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7800. return Err("a permlane result outside a VGPR");
  7801. };
  7802. self.i32_of(inst.read(Reg::V(reg)).ok_or("a permlane old value")?)?
  7803. };
  7804. self.s.m.select(c, active, read, fallback)
  7805. };
  7806. int(self, r)
  7807. }
  7808. "v_readlane_b32" => {
  7809. let (a, lane) = (s(self, 0)?, s(self, 1)?);
  7810. // A computed lane in a pixel or vertex program is a host lane
  7811. // (from a mask or `v_mbcnt`); a constant one is the console's.
  7812. if self.mask_data == MaskData::Host && !matches!(lane, V::Const(_)) {
  7813. self.s.flags |= flags::WAVE_OPS;
  7814. } else {
  7815. self.cross_lane(false)?;
  7816. }
  7817. if let Some(slot) = self.exchange.as_ref().map(|e| e.0) {
  7818. if self.local && self.local_any {
  7819. // this host wave's lane of that number (lanes 32..63 are 0..31 here)
  7820. let k31 = self.s.m.i32(31);
  7821. let here = self.s.m.bin(self.cur, Bin::And, lane, k31);
  7822. let r = self.read_lane(a, here);
  7823. return int(self, r);
  7824. }
  7825. if self.local {
  7826. return Err("a lane read in a half-wave");
  7827. }
  7828. if self.exchange.as_ref().is_some_and(|e| e.1) {
  7829. // a group of 32 or fewer: the lane is in this host wave
  7830. let r = self.read_lane(a, lane);
  7831. return int(self, r);
  7832. }
  7833. // the lane that holds it may be in the other host wave: it gives it through LDS
  7834. if !self.all_lanes(self.cur_ir) {
  7835. need(self.cur_ir);
  7836. return Err("a lane read where not every lane runs");
  7837. }
  7838. let cl = self.console_lane();
  7839. let is = self.s.m.cmp(self.cur, pred::EQ, cl, lane);
  7840. let k = self.exchange_pair(slot);
  7841. let at = self.begin_guarded(Some(is));
  7842. let lds = self.s.lds();
  7843. let ptr = self.s.m.element(self.cur, lds, k);
  7844. self.s.m.store(self.cur, ptr, a);
  7845. self.end_guarded(at, &[]);
  7846. let c2 = self.cur;
  7847. self.group_sync(c2);
  7848. let ptr = self.s.m.element(c2, lds, k);
  7849. let r = self.s.m.load(c2, ptr);
  7850. self.group_sync(c2);
  7851. return int(self, r);
  7852. }
  7853. let r = self.read_lane(a, lane);
  7854. int(self, r)
  7855. }
  7856. "v_writelane_b32" => {
  7857. // The lane given takes the scalar; the others keep their value.
  7858. let (a, lane) = (s(self, 0)?, s(self, 1)?);
  7859. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7860. return Err("a lane write");
  7861. };
  7862. let old = match inst.read(Reg::V(reg)) {
  7863. Some(o) => self.i32_of(o)?,
  7864. None => self.s.m.i32(0),
  7865. };
  7866. self.cross_lane(false)?;
  7867. if self.local && !self.local_any {
  7868. return Err("a lane write in a half-wave");
  7869. }
  7870. let me = self.console_lane();
  7871. let is = self.s.m.cmp(c, pred::EQ, me, lane);
  7872. let r = self.s.m.select(c, is, a, old);
  7873. int(self, r)
  7874. }
  7875. "v_readfirstlane_b32"
  7876. if inst
  7877. .writes
  7878. .first()
  7879. .is_some_and(|w| self.x.res.waterfall.reads.contains(&w.1)) =>
  7880. {
  7881. // A waterfall loop's read of a descriptor dword: the lane's own.
  7882. let a = s(self, 0)?;
  7883. int(self, a)
  7884. }
  7885. "v_readfirstlane_b32"
  7886. if matches!(v.src.first(), Some(&Operand::Vector { reg, .. })
  7887. if inst.read(Reg::V(reg)).is_some_and(|x| self.own_bits.alike.contains(&x))) =>
  7888. {
  7889. // The bits a loop over a wave OR has still to visit (`own_bits`): every lane of
  7890. // the host wave holds the same, so the first lane's is the lane's own.
  7891. let a = s(self, 0)?;
  7892. int(self, a)
  7893. }
  7894. "v_readfirstlane_b32" => {
  7895. let a = s(self, 0)?;
  7896. let (mine, any) = self.first_lane(a, guard);
  7897. // two host waves that exchange: the console's first lane may be in the other
  7898. // one, unless every lane holds the same value
  7899. let alike = match v.src.first() {
  7900. Some(&Operand::Vector { reg, .. }) => {
  7901. inst.read(Reg::V(reg)).is_some_and(|x| self.uniform.contains(&x))
  7902. }
  7903. _ => true,
  7904. };
  7905. let halves = self.exchange.as_ref().is_some_and(|e| !e.1) && !self.local;
  7906. let r = if halves && !alike {
  7907. if !self.all_lanes(self.cur_ir) {
  7908. // shortcut: `VICTORY_FIRSTLANE_OWN=1` takes the host wave's own
  7909. // first lane, exact when the value is the same in every lane of
  7910. // the console wave (the ray-tracing builder's scans read a sum of
  7911. // scalars this way, inside a loop whose exit is per console wave).
  7912. static OWN: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  7913. if *OWN.get_or_init(|| std::env::var_os("VICTORY_FIRSTLANE_OWN").is_some_and(|v| v == "1")) {
  7914. return int(self, mine);
  7915. }
  7916. need(self.cur_ir);
  7917. return Err("a first-lane read where not every lane runs");
  7918. }
  7919. let c = self.cur;
  7920. if guard.is_none() && super::shader_opt() & super::bitcode::opt::FIRST != 0 {
  7921. // Every lane is in EXEC: the console's first lane is
  7922. // lane 0, which the lower half of every console wave
  7923. // has. No half needs to ask the other whether it has
  7924. // a lane (an exchange of the constant 1: two group
  7925. // barriers), and the lower half's value is the answer.
  7926. let (lo, _) = self.exchange_halves(c, mine);
  7927. lo
  7928. } else {
  7929. let i32t = self.s.t.i32;
  7930. let has = self.s.m.cast(c, Cast::ZExt, any, i32t);
  7931. let (lo_has, hi_has) = self.exchange_halves(c, has);
  7932. let (lo, hi) = self.exchange_halves(c, mine);
  7933. let z = self.s.m.i32(0);
  7934. let in_lo = self.s.m.cmp(c, pred::NE, lo_has, z);
  7935. let in_hi = self.s.m.cmp(c, pred::NE, hi_has, z);
  7936. // neither half has a lane in EXEC: the console reads lane 0
  7937. let hi = self.s.m.select(c, in_hi, hi, lo);
  7938. self.s.m.select(c, in_lo, lo, hi)
  7939. }
  7940. } else {
  7941. mine
  7942. };
  7943. int(self, r)
  7944. }
  7945. _ => {
  7946. let r = self.integer(inst, name)?;
  7947. int(self, r)
  7948. }
  7949. }
  7950. }
  7951. /// A 64-bit source (a register pair; inline constants sign-extend).
  7952. fn src64(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  7953. let Fields::Valu(v) = &inst.fields else {
  7954. unreachable!()
  7955. };
  7956. if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 || v.sdwa.is_some() || v.dpp.is_some() {
  7957. return Err("64-bit operand modifiers");
  7958. }
  7959. let c = self.cur;
  7960. let i64t = self.s.m.int(64);
  7961. self.s.flags |= flags::INT64;
  7962. let op = *v.src.get(k).ok_or("a missing operand")?;
  7963. let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<V, Why> {
  7964. let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?;
  7965. let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?;
  7966. Ok(l.join64(lo, hi))
  7967. };
  7968. match op {
  7969. Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1)),
  7970. Operand::Scalar { code, .. } if code != NULL => {
  7971. pair(self, Reg::S(code), Reg::S(code + 1))
  7972. }
  7973. Operand::Const(k @ 128..=208) => {
  7974. let x = crate::resource::inline(k).ok_or("a special operand")?;
  7975. Ok(self.s.m.int_const(i64t, i64::from(x as i32)))
  7976. }
  7977. // A signed 64-bit operand sign-extends its 32-bit literal, as
  7978. // the hardware does (LLVM's AMDGPU operand rules).
  7979. Operand::Literal(x) if inst.name().ends_with("_i64") => {
  7980. Ok(self.s.m.int_const(i64t, i64::from(x as i32)))
  7981. }
  7982. _ => {
  7983. // Literals (of unsigned and bit operands) and the null
  7984. // register: zero-extended.
  7985. let x = self.operand(inst, &op)?;
  7986. Ok(self.s.m.cast(c, Cast::ZExt, x, i64t))
  7987. }
  7988. }
  7989. }
  7990. /// Reads an IEEE-754 binary64 operand as `(lo, hi)` 32-bit words, applying
  7991. /// `abs` and `neg` input modifiers on operand `k`.
  7992. fn f64_pair(&mut self, inst: &Inst, k: usize) -> Result<(V, V), Why> {
  7993. let Fields::Valu(v) = &inst.fields else {
  7994. unreachable!()
  7995. };
  7996. if v.sdwa.is_some() || v.dpp.is_some() {
  7997. return Err("64-bit operand modifiers");
  7998. }
  7999. let op = *v.src.get(k).ok_or("a missing operand")?;
  8000. let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<(V, V), Why> {
  8001. let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?;
  8002. let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?;
  8003. Ok((lo, hi))
  8004. };
  8005. let (lo, mut hi) = match op {
  8006. Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1))?,
  8007. Operand::Scalar { code, .. } if code != NULL => {
  8008. pair(self, Reg::S(code), Reg::S(code + 1))?
  8009. }
  8010. Operand::Const(128) => (self.s.m.i32(0), self.s.m.i32(0)),
  8011. Operand::Const(c @ 240..=248) => {
  8012. const INLINE_F64: [f64; 9] = [
  8013. 0.5,
  8014. -0.5,
  8015. 1.0,
  8016. -1.0,
  8017. 2.0,
  8018. -2.0,
  8019. 4.0,
  8020. -4.0,
  8021. 1.0 / std::f64::consts::TAU,
  8022. ];
  8023. let bits = INLINE_F64[(c - 240) as usize].to_bits();
  8024. (self.s.m.i32(bits as u32), self.s.m.i32((bits >> 32) as u32))
  8025. }
  8026. // GFX10 places a 32-bit literal in the high 32 bits of a 64-bit float operand.
  8027. Operand::Literal(x) => (self.s.m.i32(0), self.s.m.i32(x)),
  8028. _ => return Err("a 64-bit float operand"),
  8029. };
  8030. let c = self.cur;
  8031. if v.abs >> k & 1 != 0 {
  8032. let mask = self.s.m.i32(0x7FFF_FFFF);
  8033. hi = self.s.m.bin(c, Bin::And, hi, mask);
  8034. }
  8035. if v.neg >> k & 1 != 0 {
  8036. let sign = self.s.m.i32(0x8000_0000);
  8037. hi = self.s.m.bin(c, Bin::Xor, hi, sign);
  8038. }
  8039. Ok((lo, hi))
  8040. }
  8041. /// Converts IEEE-754 binary64 `(lo, hi)` to binary32 bits with round-to-nearest-even,
  8042. /// without requiring host `DOUBLES` (`f64`) support.
  8043. fn f64_to_f32_bits(&mut self, lo: V, hi: V) -> V {
  8044. let c = self.cur;
  8045. let k0 = self.s.m.i32(0);
  8046. let k1 = self.s.m.i32(1);
  8047. let sign_mask = self.s.m.i32(0x8000_0000);
  8048. let sign = self.s.m.bin(c, Bin::And, hi, sign_mask);
  8049. let k20 = self.s.m.i32(20);
  8050. let k7ff = self.s.m.i32(0x7FF);
  8051. let exp64 = self.s.m.bin(c, Bin::LShr, hi, k20);
  8052. let exp64 = self.s.m.bin(c, Bin::And, exp64, k7ff);
  8053. let frac_mask = self.s.m.i32(0x000F_FFFF);
  8054. let frac_hi = self.s.m.bin(c, Bin::And, hi, frac_mask);
  8055. let frac_any = self.s.m.bin(c, Bin::Or, frac_hi, lo);
  8056. let frac_nz = self.s.m.cmp(c, pred::NE, frac_any, k0);
  8057. let k3 = self.s.m.i32(3);
  8058. let k29 = self.s.m.i32(29);
  8059. let m23_hi = self.s.m.bin(c, Bin::Shl, frac_hi, k3);
  8060. let m23_lo = self.s.m.bin(c, Bin::LShr, lo, k29);
  8061. let m23 = self.s.m.bin(c, Bin::Or, m23_hi, m23_lo);
  8062. let rem_mask = self.s.m.i32(0x1FFF_FFFF);
  8063. let rem = self.s.m.bin(c, Bin::And, lo, rem_mask);
  8064. let half_rem = self.s.m.i32(0x1000_0000);
  8065. let gt_half = self.s.m.cmp(c, pred::IUGT, rem, half_rem);
  8066. let eq_half = self.s.m.cmp(c, pred::EQ, rem, half_rem);
  8067. let m23_odd_bit = self.s.m.bin(c, Bin::And, m23, k1);
  8068. let m23_odd = self.s.m.cmp(c, pred::NE, m23_odd_bit, k0);
  8069. let tie_up = self.s.m.bin(c, Bin::And, eq_half, m23_odd);
  8070. let norm_round = self.s.m.bin(c, Bin::Or, gt_half, tie_up);
  8071. let norm_inc = self.s.m.select(c, norm_round, k1, k0);
  8072. // Normal range: exp64 in [897, 1150] -> exp32 in [1, 254].
  8073. let k896 = self.s.m.i32(896);
  8074. let k23 = self.s.m.i32(23);
  8075. let exp32 = self.s.m.bin(c, Bin::Sub, exp64, k896);
  8076. let exp32_sh = self.s.m.bin(c, Bin::Shl, exp32, k23);
  8077. let norm_body = self.s.m.bin(c, Bin::Add, exp32_sh, m23);
  8078. let norm_body = self.s.m.bin(c, Bin::Add, norm_body, norm_inc);
  8079. let norm_res = self.s.m.bin(c, Bin::Or, sign, norm_body);
  8080. // Subnormal range: exp64 in [874, 896] -> shift in [1, 23].
  8081. let k897 = self.s.m.i32(897);
  8082. let k32 = self.s.m.i32(32);
  8083. let k31 = self.s.m.i32(31);
  8084. let imp = self.s.m.i32(0x0080_0000);
  8085. let sig24 = self.s.m.bin(c, Bin::Or, imp, m23);
  8086. let raw_shift = self.s.m.bin(c, Bin::Sub, k897, exp64);
  8087. // Clamp shift to [1, 23] so shifts never produce poison outside the subnormal branch.
  8088. let lt1 = self.s.m.cmp(c, pred::IULT, raw_shift, k1);
  8089. let shift = self.s.m.select(c, lt1, k1, raw_shift);
  8090. let gt23 = self.s.m.cmp(c, pred::IUGT, shift, k23);
  8091. let shift = self.s.m.select(c, gt23, k23, shift);
  8092. let sub_m = self.s.m.bin(c, Bin::LShr, sig24, shift);
  8093. let inv_shift = self.s.m.bin(c, Bin::Sub, k32, shift);
  8094. let lost = self.s.m.bin(c, Bin::Shl, sig24, inv_shift);
  8095. let round_bit = self.s.m.bin(c, Bin::LShr, lost, k31);
  8096. let round_on = self.s.m.cmp(c, pred::NE, round_bit, k0);
  8097. let low31 = self.s.m.i32(0x7FFF_FFFF);
  8098. let lost_lo = self.s.m.bin(c, Bin::And, lost, low31);
  8099. let sticky = self.s.m.bin(c, Bin::Or, lost_lo, rem);
  8100. let sticky_on = self.s.m.cmp(c, pred::NE, sticky, k0);
  8101. let sub_odd_bit = self.s.m.bin(c, Bin::And, sub_m, k1);
  8102. let sub_odd = self.s.m.cmp(c, pred::NE, sub_odd_bit, k0);
  8103. let sub_tie = self.s.m.bin(c, Bin::Or, sticky_on, sub_odd);
  8104. let sub_round = self.s.m.bin(c, Bin::And, round_on, sub_tie);
  8105. let sub_inc = self.s.m.select(c, sub_round, k1, k0);
  8106. let sub_body = self.s.m.bin(c, Bin::Add, sub_m, sub_inc);
  8107. let sub_res = self.s.m.bin(c, Bin::Or, sign, sub_body);
  8108. // Underflow range: exp64 < 874. Only exp64 == 873 with non-zero fraction rounds up to min subnormal (1).
  8109. let k873 = self.s.m.i32(873);
  8110. let eq873 = self.s.m.cmp(c, pred::EQ, exp64, k873);
  8111. let round_min = self.s.m.bin(c, Bin::And, eq873, frac_nz);
  8112. let min_bit = self.s.m.select(c, round_min, k1, k0);
  8113. let under_res = self.s.m.bin(c, Bin::Or, sign, min_bit);
  8114. // Overflow / Inf / NaN: exp64 >= 1151.
  8115. let is_exp_all = self.s.m.cmp(c, pred::EQ, exp64, k7ff);
  8116. let is_nan = self.s.m.bin(c, Bin::And, is_exp_all, frac_nz);
  8117. let inf_bits = self.s.m.i32(0x7F80_0000);
  8118. let qnan_bits = self.s.m.i32(0x7FC0_0000);
  8119. let nan_body = self.s.m.bin(c, Bin::Or, qnan_bits, m23);
  8120. let over_body = self.s.m.select(c, is_nan, nan_body, inf_bits);
  8121. let over_res = self.s.m.bin(c, Bin::Or, sign, over_body);
  8122. // Select final result by exponent range.
  8123. let k874 = self.s.m.i32(874);
  8124. let k1151 = self.s.m.i32(1151);
  8125. let is_under = self.s.m.cmp(c, pred::IULT, exp64, k874);
  8126. let is_sub = self.s.m.cmp(c, pred::IULT, exp64, k897);
  8127. let is_over = self.s.m.cmp(c, pred::IUGE, exp64, k1151);
  8128. let r = self.s.m.select(c, is_over, over_res, norm_res);
  8129. let r = self.s.m.select(c, is_sub, sub_res, r);
  8130. self.s.m.select(c, is_under, under_res, r)
  8131. }
  8132. fn join64(&mut self, lo: V, hi: V) -> V {
  8133. let c = self.cur;
  8134. let ty = self.s.m.int(64);
  8135. let lo = self.s.m.cast(c, Cast::ZExt, lo, ty);
  8136. let hi = self.s.m.cast(c, Cast::ZExt, hi, ty);
  8137. let shift = self.s.m.int_const(ty, 32);
  8138. let hi = self.s.m.bin(c, Bin::Shl, hi, shift);
  8139. self.s.m.bin(c, Bin::Or, lo, hi)
  8140. }
  8141. /// The bits of the float nearest the double whose dwords are `lo` and
  8142. /// `hi`, on 32-bit integers: round to nearest even, infinities and NaN
  8143. /// kept (a NaN stays quiet), a result below the smallest normal float
  8144. /// signed zero (flushed, as the console's default float mode does).
  8145. // The flush-to-zero form of v_cvt_f32_f64: kept beside the IEEE form in use until the console's
  8146. // float mode for this instruction is checked.
  8147. #[allow(dead_code)]
  8148. fn f64_bits_to_f32_bits(&mut self, lo: V, hi: V) -> V {
  8149. let c = self.cur;
  8150. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  8151. let (k20, k29, k3, k23) = (k(self, 20), k(self, 29), k(self, 3), k(self, 23));
  8152. let sign_mask = k(self, 0x8000_0000);
  8153. let sign = self.s.m.bin(c, Bin::And, hi, sign_mask);
  8154. let e = self.s.m.bin(c, Bin::LShr, hi, k20);
  8155. let e_mask = k(self, 0x7ff);
  8156. let e = self.s.m.bin(c, Bin::And, e, e_mask);
  8157. // The top 23 bits of the 52-bit mantissa, and the 29 below them.
  8158. let m_mask = k(self, 0x000f_ffff);
  8159. let mh = self.s.m.bin(c, Bin::And, hi, m_mask);
  8160. let mh = self.s.m.bin(c, Bin::Shl, mh, k3);
  8161. let ml = self.s.m.bin(c, Bin::LShr, lo, k29);
  8162. let m = self.s.m.bin(c, Bin::Or, mh, ml);
  8163. let rest_mask = k(self, 0x1fff_ffff);
  8164. let rest = self.s.m.bin(c, Bin::And, lo, rest_mask);
  8165. // Round to nearest even: up past half, or at half when odd.
  8166. let half = k(self, 0x1000_0000);
  8167. let one = k(self, 1);
  8168. let above = self.s.m.cmp(c, pred::IUGT, rest, half);
  8169. let at = self.s.m.cmp(c, pred::EQ, rest, half);
  8170. let odd = self.s.m.bin(c, Bin::And, m, one);
  8171. let zero = k(self, 0);
  8172. let odd = self.s.m.cmp(c, pred::NE, odd, zero);
  8173. let tie = self.s.m.bin(c, Bin::And, at, odd);
  8174. let up = self.s.m.bin(c, Bin::Or, above, tie);
  8175. let up = self.s.m.select(c, up, one, zero);
  8176. // Rebias the exponent (1023 → 127); a carry out of the mantissa
  8177. // steps the exponent, up to infinity.
  8178. let bias = k(self, 1023 - 127);
  8179. let e32 = self.s.m.bin(c, Bin::Sub, e, bias);
  8180. let ex = self.s.m.bin(c, Bin::Shl, e32, k23);
  8181. let normal = self.s.m.bin(c, Bin::Add, ex, m);
  8182. let normal = self.s.m.bin(c, Bin::Add, normal, up);
  8183. let normal = self.s.m.bin(c, Bin::Or, normal, sign);
  8184. // Exponents out of the float's range (signed, after rebiasing).
  8185. let inf = k(self, 0x7f80_0000);
  8186. let inf = self.s.m.bin(c, Bin::Or, inf, sign);
  8187. let k255 = k(self, 255);
  8188. let big = self.s.m.cmp(c, pred::SGE, e32, k255);
  8189. let small = self.s.m.cmp(c, pred::SLE, e32, zero);
  8190. let r = self.s.m.select(c, big, inf, normal);
  8191. let r = self.s.m.select(c, small, sign, r);
  8192. // Infinity and NaN (a NaN with any mantissa bit set stays a NaN).
  8193. let all = k(self, 0x7ff);
  8194. let special = self.s.m.cmp(c, pred::EQ, e, all);
  8195. let any = self.s.m.bin(c, Bin::Or, mh, ml);
  8196. let any = self.s.m.bin(c, Bin::Or, any, rest);
  8197. let nan = self.s.m.cmp(c, pred::NE, any, zero);
  8198. let quiet = k(self, 0x0040_0000);
  8199. let quiet = self.s.m.select(c, nan, quiet, zero);
  8200. let special_bits = self.s.m.bin(c, Bin::Or, inf, quiet);
  8201. self.s.m.select(c, special, special_bits, r)
  8202. }
  8203. /// The low and high dwords of an i64.
  8204. fn split64(&mut self, x: V) -> (V, V) {
  8205. let c = self.cur;
  8206. let i64t = self.s.m.int(64);
  8207. let k32 = self.s.m.int_const(i64t, 32);
  8208. let lo = self.s.m.cast(c, Cast::Trunc, x, self.s.t.i32);
  8209. let hi = self.s.m.bin(c, Bin::LShr, x, k32);
  8210. let hi = self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32);
  8211. (lo, hi)
  8212. }
  8213. /// Source `k` of a 16-bit operation in the low 16 bits (the rest 0):
  8214. /// op_sel (or an SDWA word select) picks the high half; inline float
  8215. /// constants are f16 values here.
  8216. fn half_src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  8217. let Fields::Valu(v) = &inst.fields else {
  8218. unreachable!()
  8219. };
  8220. let op = *v.src.get(k).ok_or("a missing operand")?;
  8221. let mut high = v.opsel >> k & 1 != 0;
  8222. if let Some(sd) = v.sdwa {
  8223. match sd.src_sel.get(k).copied().unwrap_or(6) {
  8224. 4 => {}
  8225. 5 => high = true,
  8226. 6 => {}
  8227. _ => return Err("a byte select on a 16-bit operation"),
  8228. }
  8229. }
  8230. let x = match self.src0 {
  8231. Some(x) if k == 0 => x,
  8232. _ => self.f16_operand(inst, &op)?,
  8233. };
  8234. let c = self.cur;
  8235. let x = if high {
  8236. let k16 = self.s.m.i32(16);
  8237. self.s.m.bin(c, Bin::LShr, x, k16)
  8238. } else {
  8239. x
  8240. };
  8241. let m = self.s.m.i32(0xFFFF);
  8242. Ok(self.s.m.bin(c, Bin::And, x, m))
  8243. }
  8244. /// An f16 source as an f32 (exact), with its abs/neg modifiers.
  8245. fn half_fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  8246. let Fields::Valu(v) = &inst.fields else {
  8247. unreachable!()
  8248. };
  8249. let h = self.half_src(inst, k)?;
  8250. let f32t = self.s.t.f32;
  8251. let mut f = self
  8252. .s
  8253. .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  8254. if v.abs >> k & 1 != 0 {
  8255. f = self.unary(6, f);
  8256. }
  8257. if v.neg >> k & 1 != 0 {
  8258. let z = self.s.m.f32(0x8000_0000);
  8259. f = self.s.m.bin(self.cur, Bin::Sub, z, f);
  8260. }
  8261. Ok(f)
  8262. }
  8263. /// Writes a 16-bit result (low bits of `x`) into the destination's low
  8264. /// half, or its high half with op_sel bit 3 (or an SDWA WORD_1 select);
  8265. /// the other half is kept (GFX10).
  8266. fn write_half(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> {
  8267. let Fields::Valu(v) = &inst.fields else {
  8268. unreachable!()
  8269. };
  8270. let Some(Operand::Vector { reg, .. }) = v.dst else {
  8271. return Err("a 16-bit result outside a VGPR");
  8272. };
  8273. let mut high = v.opsel >> 3 & 1 != 0;
  8274. // SDWA: the word written, the other one kept (preserve) or zero
  8275. // (pad; a sign extension above the high word adds nothing).
  8276. let mut keep = true;
  8277. if let Some(sd) = v.sdwa {
  8278. match (sd.dst_sel, sd.dst_unused) {
  8279. (4, 2) => {}
  8280. (5, 2) => high = true,
  8281. (4 | 6, _) => keep = false,
  8282. (5, _) => (high, keep) = (true, false),
  8283. _ => return Err("an SDWA destination of a 16-bit operation"),
  8284. }
  8285. }
  8286. let c = self.cur;
  8287. let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) {
  8288. Some(Ok(o)) if keep => o,
  8289. _ => self.s.m.i32(0),
  8290. };
  8291. let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
  8292. let x = self.s.m.bin(c, Bin::And, x, low);
  8293. let r = if high {
  8294. let o = self.s.m.bin(c, Bin::And, old, low);
  8295. let x = self.s.m.bin(c, Bin::Shl, x, k16);
  8296. self.s.m.bin(c, Bin::Or, o, x)
  8297. } else {
  8298. let keep = self.s.m.i32(0xFFFF_0000);
  8299. let o = self.s.m.bin(c, Bin::And, old, keep);
  8300. self.s.m.bin(c, Bin::Or, o, x)
  8301. };
  8302. self.write_placed(inst, Reg::V(reg), r, guard);
  8303. Ok(())
  8304. }
  8305. /// 16-bit operations, computed in f32 or i32: f16 sums, differences and
  8306. /// products are exact there and round once to f16 (f32 has the 2 x 11 +
  8307. /// 2 bits that make double rounding harmless); `None` if `name` is none.
  8308. fn valu16(&mut self, inst: &Inst, name: &str, guard: Option<V>) -> Option<Result<(), Why>> {
  8309. const FLOAT2: &[&str] = &[
  8310. "v_add_f16",
  8311. "v_sub_f16",
  8312. "v_subrev_f16",
  8313. "v_mul_f16",
  8314. "v_max_f16",
  8315. "v_min_f16",
  8316. ];
  8317. const FLOAT3: &[&str] = &[
  8318. "v_fma_f16",
  8319. "v_mad_f16",
  8320. "v_fmac_f16",
  8321. "v_mac_f16",
  8322. "v_max3_f16",
  8323. "v_min3_f16",
  8324. "v_med3_f16",
  8325. ];
  8326. const FLOAT1: &[&str] = &[
  8327. "v_rcp_f16",
  8328. "v_sqrt_f16",
  8329. "v_rsq_f16",
  8330. "v_log_f16",
  8331. "v_exp_f16",
  8332. "v_fract_f16",
  8333. "v_trunc_f16",
  8334. "v_floor_f16",
  8335. "v_ceil_f16",
  8336. "v_rndne_f16",
  8337. "v_sin_f16",
  8338. "v_cos_f16",
  8339. "v_cvt_f16_u16",
  8340. "v_cvt_f16_i16",
  8341. ];
  8342. const INT: &[&str] = &[
  8343. "v_add_nc_u16",
  8344. "v_sub_nc_u16",
  8345. "v_subrev_nc_u16",
  8346. "v_mul_lo_u16",
  8347. "v_lshlrev_b16",
  8348. "v_lshrrev_b16",
  8349. "v_ashrrev_i16",
  8350. "v_max_u16",
  8351. "v_max_i16",
  8352. "v_min_u16",
  8353. "v_min_i16",
  8354. "v_cvt_u16_f16",
  8355. "v_cvt_i16_f16",
  8356. "v_cvt_norm_i16_f16",
  8357. "v_cvt_norm_u16_f16",
  8358. ];
  8359. let all = [FLOAT1, FLOAT2, FLOAT3, INT];
  8360. if !all.iter().any(|l| l.contains(&name))
  8361. && !matches!(name, "v_cvt_f16_f32" | "v_cvt_f32_f16")
  8362. {
  8363. return None;
  8364. }
  8365. Some(self.valu16_op(inst, name, guard, FLOAT1, FLOAT2, FLOAT3))
  8366. }
  8367. #[allow(clippy::too_many_arguments)]
  8368. fn valu16_op(
  8369. &mut self,
  8370. inst: &Inst,
  8371. name: &str,
  8372. guard: Option<V>,
  8373. float1: &[&str],
  8374. float2: &[&str],
  8375. float3: &[&str],
  8376. ) -> Result<(), Why> {
  8377. let Fields::Valu(v) = &inst.fields else {
  8378. unreachable!()
  8379. };
  8380. let c = self.cur;
  8381. let i32t = self.s.t.i32;
  8382. let f32t = self.s.t.f32;
  8383. if name == "v_cvt_f32_f16" {
  8384. let f = self.half_fsrc(inst, 0)?;
  8385. return self.write_f(inst, f, guard);
  8386. }
  8387. let float_result = |l: &mut Self, mut f: V| -> Result<(), Why> {
  8388. match v.omod {
  8389. 0 => {}
  8390. k => {
  8391. let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)];
  8392. let k = l.s.m.f32(factor.to_bits());
  8393. f = l.s.m.bin(l.cur, Bin::Mul, f, k);
  8394. }
  8395. }
  8396. if v.clamp {
  8397. f = l.unary(7, f);
  8398. }
  8399. // The console rounds to nearest; the host's conversion may round toward zero
  8400. // (NVIDIA's does), one step of the last place lower where the two differ.
  8401. // shortcut: the host's conversion unless `VICTORY_F16_NEAREST=1`
  8402. // ([`f16_nearest_on`]), which costs a dozen instructions per result.
  8403. let h = if f16_nearest_on() {
  8404. l.f16_nearest(f)
  8405. } else {
  8406. l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  8407. };
  8408. l.write_half(inst, h, guard)
  8409. };
  8410. if name == "v_cvt_f16_f32" {
  8411. let f = self.fsrc(inst, 0)?;
  8412. return float_result(self, f);
  8413. }
  8414. if float2.contains(&name) {
  8415. let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?);
  8416. let r = match name {
  8417. "v_add_f16" => self.s.m.bin(c, Bin::Add, a, b),
  8418. "v_sub_f16" => self.s.m.bin(c, Bin::Sub, a, b),
  8419. "v_subrev_f16" => self.s.m.bin(c, Bin::Sub, b, a),
  8420. "v_mul_f16" => self.s.m.bin(c, Bin::Mul, a, b),
  8421. "v_max_f16" => self.max_min(true, a, b),
  8422. _ => self.max_min(false, a, b),
  8423. };
  8424. return float_result(self, r);
  8425. }
  8426. if float3.contains(&name) {
  8427. let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?);
  8428. let acc = if matches!(name, "v_fmac_f16" | "v_mac_f16") {
  8429. // The accumulator is the destination's half that is written.
  8430. let Some(Operand::Vector { reg, .. }) = v.dst else {
  8431. return Err("an accumulator");
  8432. };
  8433. let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?;
  8434. let x = if v.opsel >> 3 & 1 != 0 {
  8435. let k16 = self.s.m.i32(16);
  8436. self.s.m.bin(c, Bin::LShr, x, k16)
  8437. } else {
  8438. x
  8439. };
  8440. let m = self.s.m.i32(0xFFFF);
  8441. let x = self.s.m.bin(c, Bin::And, x, m);
  8442. self.s
  8443. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x])
  8444. } else {
  8445. self.half_fsrc(inst, 2)?
  8446. };
  8447. let r = match name {
  8448. // shortcut: fused f16 multiply-adds as FMad in f32 (the
  8449. // product is exact; the sum rounds twice).
  8450. "v_fma_f16" | "v_fmac_f16" | "v_mad_f16" | "v_mac_f16" => self.fmad(a, b, acc),
  8451. "v_max3_f16" => {
  8452. let t = self.max_min(true, a, b);
  8453. self.max_min(true, t, acc)
  8454. }
  8455. "v_min3_f16" => {
  8456. let t = self.max_min(false, a, b);
  8457. self.max_min(false, t, acc)
  8458. }
  8459. _ => self.med3(a, b, acc),
  8460. };
  8461. return float_result(self, r);
  8462. }
  8463. if float1.contains(&name) {
  8464. let r = match name {
  8465. "v_cvt_f16_u16" | "v_cvt_f16_i16" => {
  8466. let mut x = self.half_src(inst, 0)?;
  8467. let op = if name == "v_cvt_f16_i16" {
  8468. let k16 = self.s.m.i32(16);
  8469. let t = self.s.m.bin(c, Bin::Shl, x, k16);
  8470. x = self.s.m.bin(c, Bin::AShr, t, k16);
  8471. Cast::SiToFp
  8472. } else {
  8473. Cast::UiToFp
  8474. };
  8475. self.s.m.cast(c, op, x, f32t)
  8476. }
  8477. "v_rcp_f16" => {
  8478. let a = self.half_fsrc(inst, 0)?;
  8479. let one = self.s.m.f32(1.0f32.to_bits());
  8480. self.s.m.bin(c, Bin::SDiv, one, a)
  8481. }
  8482. _ => {
  8483. let a = self.half_fsrc(inst, 0)?;
  8484. let op = match name {
  8485. "v_sqrt_f16" => 24,
  8486. "v_rsq_f16" => 25,
  8487. "v_log_f16" => 23,
  8488. "v_exp_f16" => 21,
  8489. "v_fract_f16" => 22,
  8490. "v_trunc_f16" => 29,
  8491. "v_floor_f16" => 27,
  8492. "v_ceil_f16" => 28,
  8493. "v_rndne_f16" => 26,
  8494. "v_sin_f16" => 13,
  8495. _ => 12,
  8496. };
  8497. match op {
  8498. 12 | 13 => self.trig_turns(a, op == 12),
  8499. // Any f16 in (-2^-11, 0) has fract >= 1 - 2^-12; clamp to 0x3bff (1 - 2^-11).
  8500. 22 => self.fract(a, 1.0 - 1.0 / 4096.0, 1.0 - 1.0 / 2048.0),
  8501. _ => self.unary(op, a),
  8502. }
  8503. }
  8504. };
  8505. return float_result(self, r);
  8506. }
  8507. if matches!(name, "v_cvt_u16_f16" | "v_cvt_i16_f16") {
  8508. if v.clamp || v.omod != 0 {
  8509. return Err("modifiers on a 16-bit integer operation");
  8510. }
  8511. // Toward zero, saturating at the 16-bit range (infinities
  8512. // included); NaN gives 0. Clamped in f32 first, where every
  8513. // f16 is exact, so the conversion never leaves i32's range
  8514. // (upstream PR #384's arithmetic; the source's abs and neg
  8515. // modifiers are applied by `half_fsrc`, as before).
  8516. let a = self.half_fsrc(inst, 0)?;
  8517. let (lo, hi) = if name == "v_cvt_u16_f16" {
  8518. (0.0f32, 65535.0f32)
  8519. } else {
  8520. (-32768.0, 32767.0)
  8521. };
  8522. let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits()));
  8523. let t = self.binary(35, a, lo);
  8524. let t = self.binary(36, t, hi);
  8525. let r = self.s.m.cast(c, Cast::FpToSi, t, i32t);
  8526. let nan = self.s.m.cmp(c, pred::UNO, a, a);
  8527. let z = self.s.m.i32(0);
  8528. let r = self.s.m.select(c, nan, z, r);
  8529. return self.write_half(inst, r, guard);
  8530. }
  8531. if matches!(name, "v_cvt_norm_i16_f16" | "v_cvt_norm_u16_f16") {
  8532. if v.clamp || v.omod != 0 {
  8533. return Err("modifiers on a 16-bit integer operation");
  8534. }
  8535. let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?;
  8536. return self.write_half(inst, r, guard);
  8537. }
  8538. // 16-bit integers: computed on the low halves, the low 16 bits kept.
  8539. if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 {
  8540. return Err("modifiers on a 16-bit integer operation");
  8541. }
  8542. let r = {
  8543. let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
  8544. let k16 = self.s.m.i32(16);
  8545. let sext = |l: &mut Self, x: V| {
  8546. let t = l.s.m.bin(c, Bin::Shl, x, k16);
  8547. l.s.m.bin(c, Bin::AShr, t, k16)
  8548. };
  8549. if name.ends_with("_i16") {
  8550. a = sext(self, a);
  8551. b = sext(self, b);
  8552. }
  8553. let k15 = self.s.m.i32(15);
  8554. match name {
  8555. "v_add_nc_u16" => self.s.m.bin(c, Bin::Add, a, b),
  8556. "v_sub_nc_u16" => self.s.m.bin(c, Bin::Sub, a, b),
  8557. "v_subrev_nc_u16" => self.s.m.bin(c, Bin::Sub, b, a),
  8558. "v_mul_lo_u16" => self.s.m.bin(c, Bin::Mul, a, b),
  8559. "v_lshlrev_b16" | "v_lshrrev_b16" | "v_ashrrev_i16" => {
  8560. // src0 is the shift (4 bits), src1 the value.
  8561. let sh = self.s.m.bin(c, Bin::And, a, k15);
  8562. let x = if name == "v_ashrrev_i16" {
  8563. sext(self, b)
  8564. } else {
  8565. b
  8566. };
  8567. let op = match name {
  8568. "v_lshlrev_b16" => Bin::Shl,
  8569. "v_lshrrev_b16" => Bin::LShr,
  8570. _ => Bin::AShr,
  8571. };
  8572. self.s.m.bin(c, op, x, sh)
  8573. }
  8574. _ => {
  8575. let p = match name {
  8576. "v_max_u16" => pred::IUGT,
  8577. "v_min_u16" => pred::IULT,
  8578. "v_max_i16" => pred::SGT,
  8579. _ => pred::SLT,
  8580. };
  8581. let t = self.s.m.cmp(c, p, a, b);
  8582. self.s.m.select(c, t, a, b)
  8583. }
  8584. }
  8585. };
  8586. self.write_half(inst, r, guard)
  8587. }
  8588. /// `v_cvt_norm_i16_f16` / `v_cvt_norm_u16_f16`: the f16 source (with its
  8589. /// abs/neg modifiers) clamped to [-1, 1] or [0, 1], times 32767 or 65535,
  8590. /// rounded to nearest even once from the exact product; NaN gives 0.
  8591. /// Worked on the f16's bits in integers, because in f32 the product
  8592. /// (up to 26 significant bits) would round before the rounding to an
  8593. /// integer.
  8594. fn cvt_norm16(&mut self, inst: &Inst, signed: bool) -> Result<V, Why> {
  8595. let Fields::Valu(v) = &inst.fields else {
  8596. unreachable!()
  8597. };
  8598. let c = self.cur;
  8599. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  8600. let mut h = self.half_src(inst, 0)?;
  8601. if v.abs & 1 != 0 {
  8602. let m = k(self, 0x7FFF);
  8603. h = self.s.m.bin(c, Bin::And, h, m);
  8604. }
  8605. if v.neg & 1 != 0 {
  8606. let m = k(self, 0x8000);
  8607. h = self.s.m.bin(c, Bin::Xor, h, m);
  8608. }
  8609. let scale = if signed { 0x7FFF } else { 0xFFFF };
  8610. let (k0, k1, k10) = (k(self, 0), k(self, 1), k(self, 10));
  8611. let mag_mask = k(self, 0x7FFF);
  8612. let mag = self.s.m.bin(c, Bin::And, h, mag_mask);
  8613. let k15 = k(self, 15);
  8614. let neg = self.s.m.bin(c, Bin::LShr, h, k15);
  8615. let neg = self.s.m.cmp(c, pred::NE, neg, k0);
  8616. // |x| < 1: x = m * 2^-s with m < 2^11 and 11 <= s <= 24.
  8617. let exp = self.s.m.bin(c, Bin::LShr, mag, k10);
  8618. let man_mask = k(self, 0x3FF);
  8619. let man = self.s.m.bin(c, Bin::And, mag, man_mask);
  8620. let implicit = k(self, 0x400);
  8621. let normal = self.s.m.bin(c, Bin::Or, man, implicit);
  8622. let sub = self.s.m.cmp(c, pred::EQ, exp, k0);
  8623. let m = self.s.m.select(c, sub, man, normal);
  8624. let k25 = k(self, 25);
  8625. let s_norm = self.s.m.bin(c, Bin::Sub, k25, exp);
  8626. let k24 = k(self, 24);
  8627. let sh = self.s.m.select(c, sub, k24, s_norm);
  8628. let ks = k(self, scale);
  8629. let p = self.s.m.bin(c, Bin::Mul, m, ks);
  8630. let q = self.s.m.bin(c, Bin::LShr, p, sh);
  8631. let one_s = self.s.m.bin(c, Bin::Shl, k1, sh);
  8632. let low_mask = self.s.m.bin(c, Bin::Sub, one_s, k1);
  8633. let rem = self.s.m.bin(c, Bin::And, p, low_mask);
  8634. let half = self.s.m.bin(c, Bin::LShr, one_s, k1);
  8635. let above = self.s.m.cmp(c, pred::IUGT, rem, half);
  8636. let tie = self.s.m.cmp(c, pred::EQ, rem, half);
  8637. let odd = self.s.m.bin(c, Bin::And, q, k1);
  8638. let odd = self.s.m.cmp(c, pred::NE, odd, k0);
  8639. let tie_up = self.s.m.bin(c, Bin::And, tie, odd);
  8640. let up = self.s.m.bin(c, Bin::Or, above, tie_up);
  8641. let r = self.s.m.select(c, up, k1, k0);
  8642. let r = self.s.m.bin(c, Bin::Add, q, r);
  8643. // |x| >= 1 (and infinity) saturates; NaN gives 0.
  8644. let one_h = k(self, 0x3C00);
  8645. let big = self.s.m.cmp(c, pred::IUGE, mag, one_h);
  8646. let r = self.s.m.select(c, big, ks, r);
  8647. let inf = k(self, 0x7C00);
  8648. let nan = self.s.m.cmp(c, pred::IUGT, mag, inf);
  8649. let r = self.s.m.select(c, nan, k0, r);
  8650. let r = if signed {
  8651. let n = self.s.m.bin(c, Bin::Sub, k0, r);
  8652. self.s.m.select(c, neg, n, r)
  8653. } else {
  8654. self.s.m.select(c, neg, k0, r)
  8655. };
  8656. let m16 = k(self, 0xFFFF);
  8657. Ok(self.s.m.bin(c, Bin::And, r, m16))
  8658. }
  8659. /// Half `high` of source `k` of a packed (VOP3P) operation, in the low
  8660. /// 16 bits: op_sel picks the half the low result reads, op_sel_hi the
  8661. /// half the high result reads. Packed integer instructions see the f32
  8662. /// bits of an inline float constant.
  8663. fn packed_src(&mut self, inst: &Inst, k: usize, high: bool, float: bool) -> Result<V, Why> {
  8664. let Fields::Valu(v) = &inst.fields else {
  8665. unreachable!()
  8666. };
  8667. let op = *v.src.get(k).ok_or("a missing operand")?;
  8668. let sel = if high { v.opsel_hi } else { v.opsel } >> k & 1 != 0;
  8669. let x = if float {
  8670. self.f16_operand(inst, &op)?
  8671. } else {
  8672. self.operand(inst, &op)?
  8673. };
  8674. let c = self.cur;
  8675. let x = if sel {
  8676. let k16 = self.s.m.i32(16);
  8677. self.s.m.bin(c, Bin::LShr, x, k16)
  8678. } else {
  8679. x
  8680. };
  8681. let m = self.s.m.i32(0xFFFF);
  8682. Ok(self.s.m.bin(c, Bin::And, x, m))
  8683. }
  8684. /// Half `high` of source `k` of `v_pk_fmac_f16`, in the low 16 bits: a
  8685. /// VOP2 operation (no op_sel) whose third source is its destination.
  8686. fn fmac_half(&mut self, inst: &Inst, k: usize, high: bool) -> Result<V, Why> {
  8687. let Fields::Valu(v) = &inst.fields else {
  8688. unreachable!()
  8689. };
  8690. let op = if k == 2 { v.dst } else { v.src.get(k).copied() };
  8691. let op = op.ok_or("a missing operand")?;
  8692. if matches!(op, Operand::Const(_) | Operand::Literal(_)) {
  8693. // shortcut: no constant operand seen; its high half is not known.
  8694. return Err("a constant operand of v_pk_fmac_f16");
  8695. }
  8696. let x = self.operand(inst, &op)?;
  8697. let c = self.cur;
  8698. let x = if high {
  8699. let k16 = self.s.m.i32(16);
  8700. self.s.m.bin(c, Bin::LShr, x, k16)
  8701. } else {
  8702. x
  8703. };
  8704. let m = self.s.m.i32(0xFFFF);
  8705. Ok(self.s.m.bin(c, Bin::And, x, m))
  8706. }
  8707. /// Packed 16-bit operations (`v_pk_*`): each half computed as the
  8708. /// 16-bit operation does, f16 through f32 as in [`Self::valu16`].
  8709. fn packed16(&mut self, inst: &Inst, op: &str, guard: Option<V>) -> Result<(), Why> {
  8710. let Fields::Valu(v) = &inst.fields else {
  8711. unreachable!()
  8712. };
  8713. let float = op.ends_with("_f16");
  8714. let n = match op {
  8715. "fma_f16" | "fmac_f16" | "mad_u16" | "mad_i16" => 3,
  8716. "add_f16" | "mul_f16" | "min_f16" | "max_f16" | "add_u16" | "sub_u16" | "add_i16"
  8717. | "sub_i16" | "mul_lo_u16" | "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16"
  8718. | "max_u16" | "min_u16" | "max_i16" | "min_i16" => 2,
  8719. _ => return Err("a packed 16-bit operation"),
  8720. };
  8721. if v.omod != 0 || !float && (v.clamp || v.neg != 0 || v.neg_hi != 0) {
  8722. return Err("modifiers on a packed integer operation");
  8723. }
  8724. let c = self.cur;
  8725. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  8726. let mut halves = Vec::new();
  8727. for high in [false, true] {
  8728. let mut xs = Vec::new();
  8729. for k in 0..n {
  8730. let h = if op == "fmac_f16" {
  8731. self.fmac_half(inst, k, high)?
  8732. } else {
  8733. self.packed_src(inst, k, high, float)?
  8734. };
  8735. if float {
  8736. let mut f = self
  8737. .s
  8738. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  8739. let neg = if high { v.neg_hi } else { v.neg };
  8740. if neg >> k & 1 != 0 {
  8741. let z = self.s.m.f32(0x8000_0000);
  8742. f = self.s.m.bin(c, Bin::Sub, z, f);
  8743. }
  8744. xs.push(f);
  8745. } else {
  8746. xs.push(h);
  8747. }
  8748. }
  8749. let r = if float {
  8750. let mut f = match op {
  8751. "add_f16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
  8752. "mul_f16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
  8753. "min_f16" => self.max_min(false, xs[0], xs[1]),
  8754. "max_f16" => self.max_min(true, xs[0], xs[1]),
  8755. // shortcut: FMad in f32, as v_fma_f16.
  8756. _ => self.fmad(xs[0], xs[1], xs[2]),
  8757. };
  8758. if v.clamp {
  8759. f = self.unary(7, f);
  8760. }
  8761. self.s
  8762. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  8763. } else {
  8764. let k16 = self.s.m.i32(16);
  8765. let sext = |l: &mut Self, x: V| {
  8766. let t = l.s.m.bin(c, Bin::Shl, x, k16);
  8767. l.s.m.bin(c, Bin::AShr, t, k16)
  8768. };
  8769. if op.ends_with("_i16") {
  8770. for x in &mut xs {
  8771. *x = sext(self, *x);
  8772. }
  8773. }
  8774. let k15 = self.s.m.i32(15);
  8775. match op {
  8776. "add_u16" | "add_i16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
  8777. "sub_u16" | "sub_i16" => self.s.m.bin(c, Bin::Sub, xs[0], xs[1]),
  8778. "mul_lo_u16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
  8779. "mad_u16" | "mad_i16" => {
  8780. let m = self.s.m.bin(c, Bin::Mul, xs[0], xs[1]);
  8781. self.s.m.bin(c, Bin::Add, m, xs[2])
  8782. }
  8783. "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16" => {
  8784. let sh = self.s.m.bin(c, Bin::And, xs[0], k15);
  8785. let o = match op {
  8786. "lshlrev_b16" => Bin::Shl,
  8787. "lshrrev_b16" => Bin::LShr,
  8788. _ => Bin::AShr,
  8789. };
  8790. let x = if op == "ashrrev_i16" {
  8791. sext(self, xs[1])
  8792. } else {
  8793. xs[1]
  8794. };
  8795. self.s.m.bin(c, o, x, sh)
  8796. }
  8797. _ => {
  8798. let p = match op {
  8799. "max_u16" => pred::IUGT,
  8800. "min_u16" => pred::IULT,
  8801. "max_i16" => pred::SGT,
  8802. _ => pred::SLT,
  8803. };
  8804. let t = self.s.m.cmp(c, p, xs[0], xs[1]);
  8805. self.s.m.select(c, t, xs[0], xs[1])
  8806. }
  8807. }
  8808. };
  8809. let m = self.s.m.i32(0xFFFF);
  8810. halves.push(self.s.m.bin(c, Bin::And, r, m));
  8811. }
  8812. let k16 = self.s.m.i32(16);
  8813. let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16);
  8814. let r = self.s.m.bin(c, Bin::Or, halves[0], hi);
  8815. let Some(Operand::Vector { reg, .. }) = v.dst else {
  8816. return Err("a packed result outside a VGPR");
  8817. };
  8818. self.write(inst, Reg::V(reg), r, guard);
  8819. Ok(())
  8820. }
  8821. fn integer(&mut self, inst: &Inst, name: &'static str) -> Result<V, Why> {
  8822. let c = self.cur;
  8823. let s = |l: &mut Self, k| l.src(inst, k);
  8824. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  8825. let m31 = |l: &mut Self, x: V| {
  8826. let k31 = l.s.m.i32(31);
  8827. l.s.m.bin(c, Bin::And, x, k31)
  8828. };
  8829. Ok(match name {
  8830. "v_and_b32" | "v_or_b32" | "v_xor_b32" | "v_add_nc_u32" | "v_sub_nc_u32"
  8831. | "v_subrev_nc_u32" | "v_mul_lo_u32" => {
  8832. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8833. let (op, a, b) = match name {
  8834. "v_and_b32" => (Bin::And, a, b),
  8835. "v_or_b32" => (Bin::Or, a, b),
  8836. "v_xor_b32" => (Bin::Xor, a, b),
  8837. "v_add_nc_u32" => (Bin::Add, a, b),
  8838. "v_sub_nc_u32" => (Bin::Sub, a, b),
  8839. "v_subrev_nc_u32" => (Bin::Sub, b, a),
  8840. _ => (Bin::Mul, a, b),
  8841. };
  8842. self.s.m.bin(c, op, a, b)
  8843. }
  8844. "v_xnor_b32" => {
  8845. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8846. let x = self.s.m.bin(c, Bin::Xor, a, b);
  8847. let ones = k(self, u32::MAX);
  8848. self.s.m.bin(c, Bin::Xor, x, ones)
  8849. }
  8850. "v_not_b32" => {
  8851. let a = s(self, 0)?;
  8852. let ones = k(self, u32::MAX);
  8853. self.s.m.bin(c, Bin::Xor, a, ones)
  8854. }
  8855. "v_lshlrev_b32" | "v_lshrrev_b32" | "v_ashrrev_i32" => {
  8856. let (sh, a) = (s(self, 0)?, s(self, 1)?);
  8857. let sh = m31(self, sh);
  8858. let op = match name {
  8859. "v_lshlrev_b32" => Bin::Shl,
  8860. "v_lshrrev_b32" => Bin::LShr,
  8861. _ => Bin::AShr,
  8862. };
  8863. self.s.m.bin(c, op, a, sh)
  8864. }
  8865. "v_lshl_add_u32" | "v_lshl_or_b32" | "v_add_lshl_u32" | "v_and_or_b32"
  8866. | "v_or3_b32" | "v_xad_u32" | "v_add3_u32" | "v_xor3_b32" => {
  8867. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8868. match name {
  8869. "v_lshl_add_u32" | "v_lshl_or_b32" => {
  8870. let b = m31(self, b);
  8871. let t = self.s.m.bin(c, Bin::Shl, a, b);
  8872. let op = if name == "v_lshl_add_u32" {
  8873. Bin::Add
  8874. } else {
  8875. Bin::Or
  8876. };
  8877. self.s.m.bin(c, op, t, d)
  8878. }
  8879. "v_add_lshl_u32" => {
  8880. let t = self.s.m.bin(c, Bin::Add, a, b);
  8881. let d = m31(self, d);
  8882. self.s.m.bin(c, Bin::Shl, t, d)
  8883. }
  8884. _ => {
  8885. let (o1, o2) = match name {
  8886. "v_and_or_b32" => (Bin::And, Bin::Or),
  8887. "v_or3_b32" => (Bin::Or, Bin::Or),
  8888. "v_xad_u32" => (Bin::Xor, Bin::Add),
  8889. "v_add3_u32" => (Bin::Add, Bin::Add),
  8890. _ => (Bin::Xor, Bin::Xor),
  8891. };
  8892. let t = self.s.m.bin(c, o1, a, b);
  8893. self.s.m.bin(c, o2, t, d)
  8894. }
  8895. }
  8896. }
  8897. "v_mul_u32_u24" | "v_mul_i32_i24" => {
  8898. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8899. let (sh, op) = (
  8900. k(self, 8),
  8901. if name == "v_mul_i32_i24" {
  8902. Bin::AShr
  8903. } else {
  8904. Bin::LShr
  8905. },
  8906. );
  8907. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  8908. let a = self.s.m.bin(c, op, a, sh);
  8909. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  8910. let b = self.s.m.bin(c, op, b, sh);
  8911. self.s.m.bin(c, Bin::Mul, a, b)
  8912. }
  8913. "v_mul_hi_u32_u24" | "v_mul_hi_i32_i24" => {
  8914. // The high dword of the same 48-bit product: the low 24 bits
  8915. // of each operand, zero- or sign-extended, multiplied.
  8916. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8917. let signed = name == "v_mul_hi_i32_i24";
  8918. let (sh, op) = (k(self, 8), if signed { Bin::AShr } else { Bin::LShr });
  8919. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  8920. let a = self.s.m.bin(c, op, a, sh);
  8921. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  8922. let b = self.s.m.bin(c, op, b, sh);
  8923. self.mul_hi(a, b, signed)
  8924. }
  8925. "v_bfe_u32" | "v_bfe_i32" => {
  8926. let (a, off, w) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8927. let w = m31(self, w);
  8928. self.bfe(a, off, w, name == "v_bfe_i32")
  8929. }
  8930. "v_bfi_b32" => {
  8931. let (m, a, b) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8932. let ones = k(self, u32::MAX);
  8933. let nm = self.s.m.bin(c, Bin::Xor, m, ones);
  8934. let x = self.s.m.bin(c, Bin::And, m, a);
  8935. let y = self.s.m.bin(c, Bin::And, nm, b);
  8936. self.s.m.bin(c, Bin::Or, x, y)
  8937. }
  8938. "v_max_i32" | "v_min_i32" | "v_max_u32" | "v_min_u32" => {
  8939. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8940. let p = match name {
  8941. "v_max_i32" => pred::SGT,
  8942. "v_min_i32" => pred::SLT,
  8943. "v_max_u32" => pred::IUGT,
  8944. _ => pred::IULT,
  8945. };
  8946. let t = self.s.m.cmp(c, p, a, b);
  8947. self.s.m.select(c, t, a, b)
  8948. }
  8949. "v_mul_hi_u32" | "v_mul_hi_i32" => {
  8950. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8951. self.mul_hi(a, b, name == "v_mul_hi_i32")
  8952. }
  8953. "v_alignbit_b32" | "v_alignbyte_b32" => {
  8954. // The low dword of {a, b} >> shift.
  8955. let (a, b, sh) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8956. let sh = if name == "v_alignbyte_b32" {
  8957. let three = k(self, 3);
  8958. let t = self.s.m.bin(c, Bin::And, sh, three);
  8959. let k3 = k(self, 3);
  8960. self.s.m.bin(c, Bin::Shl, t, k3)
  8961. } else {
  8962. m31(self, sh)
  8963. };
  8964. let k32 = k(self, 32);
  8965. let lo = self.s.m.bin(c, Bin::LShr, b, sh);
  8966. let left = self.s.m.bin(c, Bin::Sub, k32, sh);
  8967. let left = m31(self, left);
  8968. let hi = self.s.m.bin(c, Bin::Shl, a, left);
  8969. let zero = k(self, 0);
  8970. let none = self.s.m.cmp(c, pred::EQ, sh, zero);
  8971. let hi = self.s.m.select(c, none, zero, hi);
  8972. self.s.m.bin(c, Bin::Or, lo, hi)
  8973. }
  8974. "v_bfrev_b32" => {
  8975. let a = s(self, 0)?;
  8976. self.s
  8977. .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a])
  8978. }
  8979. "v_bcnt_u32_b32" => {
  8980. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8981. let n = self
  8982. .s
  8983. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[a]);
  8984. self.s.m.bin(c, Bin::Add, n, b)
  8985. }
  8986. "v_mad_u32_u24" | "v_mad_i32_i24" => {
  8987. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8988. let (sh, op) = (
  8989. k(self, 8),
  8990. if name == "v_mad_i32_i24" {
  8991. Bin::AShr
  8992. } else {
  8993. Bin::LShr
  8994. },
  8995. );
  8996. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  8997. let a = self.s.m.bin(c, op, a, sh);
  8998. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  8999. let b = self.s.m.bin(c, op, b, sh);
  9000. let m = self.s.m.bin(c, Bin::Mul, a, b);
  9001. self.s.m.bin(c, Bin::Add, m, d)
  9002. }
  9003. "v_sad_u8" | "v_sad_hi_u8" | "v_sad_u16" | "v_sad_u32" | "v_msad_u8" => {
  9004. // src2 plus the sum of the unsigned differences |a - b| of
  9005. // the operands' bytes, halves or whole dwords, wrapping at 32
  9006. // bits. v_sad_hi_u8 adds the sum shifted to the high half;
  9007. // v_msad_u8 leaves out a byte whose mask byte (src1) is 0.
  9008. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9009. let (width, parts) = match name {
  9010. "v_sad_u16" => (16, 2),
  9011. "v_sad_u32" => (32, 1),
  9012. _ => (8, 4),
  9013. };
  9014. let zero = k(self, 0);
  9015. let mut sum = zero;
  9016. for i in 0..parts {
  9017. let (mut x, mut y) = (a, b);
  9018. if width < 32 {
  9019. let (sh, mask) = (k(self, width * i), k(self, (1 << width) - 1));
  9020. x = self.s.m.bin(c, Bin::LShr, x, sh);
  9021. x = self.s.m.bin(c, Bin::And, x, mask);
  9022. y = self.s.m.bin(c, Bin::LShr, y, sh);
  9023. y = self.s.m.bin(c, Bin::And, y, mask);
  9024. }
  9025. let above = self.s.m.cmp(c, pred::IUGT, x, y);
  9026. let hi = self.s.m.select(c, above, x, y);
  9027. let lo = self.s.m.select(c, above, y, x);
  9028. let mut diff = self.s.m.bin(c, Bin::Sub, hi, lo);
  9029. if name == "v_msad_u8" {
  9030. let masked = self.s.m.cmp(c, pred::NE, y, zero);
  9031. diff = self.s.m.select(c, masked, diff, zero);
  9032. }
  9033. sum = self.s.m.bin(c, Bin::Add, sum, diff);
  9034. }
  9035. if name == "v_sad_hi_u8" {
  9036. let k16 = k(self, 16);
  9037. sum = self.s.m.bin(c, Bin::Shl, sum, k16);
  9038. }
  9039. self.s.m.bin(c, Bin::Add, sum, d)
  9040. }
  9041. "v_min3_i32" | "v_max3_i32" | "v_min3_u32" | "v_max3_u32" | "v_med3_i32"
  9042. | "v_med3_u32" => {
  9043. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9044. let signed = name.ends_with("i32");
  9045. let (lt, gt) = if signed {
  9046. (pred::SLT, pred::SGT)
  9047. } else {
  9048. (pred::IULT, pred::IUGT)
  9049. };
  9050. let pick = |l: &mut Self, p, x, y| {
  9051. let t = l.s.m.cmp(c, p, x, y);
  9052. l.s.m.select(c, t, x, y)
  9053. };
  9054. match &name[2..6] {
  9055. "min3" => {
  9056. let t = pick(self, lt, a, b);
  9057. pick(self, lt, t, d)
  9058. }
  9059. "max3" => {
  9060. let t = pick(self, gt, a, b);
  9061. pick(self, gt, t, d)
  9062. }
  9063. _ => {
  9064. let lo = pick(self, lt, a, b);
  9065. let hi = pick(self, gt, a, b);
  9066. let t = pick(self, lt, hi, d);
  9067. pick(self, gt, lo, t)
  9068. }
  9069. }
  9070. }
  9071. "v_perm_b32" => {
  9072. // Byte i of the result is byte S of {src0, src1} (src1 the
  9073. // low dword) for selector byte S below 8; 8-11 repeat the
  9074. // sign of bytes 1 and 3 of src1, then of src0; 12 is 0x00,
  9075. // higher 0xFF.
  9076. let Fields::Valu(v) = &inst.fields else {
  9077. unreachable!()
  9078. };
  9079. let sel = match v.src.get(2) {
  9080. Some(&Operand::Literal(x)) => x,
  9081. Some(&Operand::Const(k)) => crate::resource::inline(k).ok_or(name)?,
  9082. _ => {
  9083. // A computed selector: each byte picked at run time.
  9084. let (a, b, sv) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  9085. let mut r = k(self, 0);
  9086. for i in 0..4u32 {
  9087. let (sh, ff) = (k(self, 8 * i), k(self, 0xFF));
  9088. let sel = self.s.m.bin(c, Bin::LShr, sv, sh);
  9089. let sel = self.s.m.bin(c, Bin::And, sel, ff);
  9090. // Select a dword and a byte within it.
  9091. // Later selects handle codes 8 and above.
  9092. let four = k(self, 4);
  9093. let zero = k(self, 0);
  9094. let high = self.s.m.bin(c, Bin::And, sel, four);
  9095. let high = self.s.m.cmp(c, pred::NE, high, zero);
  9096. let word = self.s.m.select(c, high, a, b);
  9097. let three = k(self, 3);
  9098. let index = self.s.m.bin(c, Bin::And, sel, three);
  9099. let bits = self.s.m.bin(c, Bin::Shl, index, three);
  9100. let x = self.s.m.bin(c, Bin::LShr, word, bits);
  9101. let mut byte = self.s.m.bin(c, Bin::And, x, ff);
  9102. // 8-11: the sign of bytes 1, 3 of src1, then of src0.
  9103. for (n, src, bit) in [(8, b, 15), (9, b, 31), (10, a, 15), (11, a, 31)]
  9104. {
  9105. let left = k(self, 31 - bit);
  9106. let t = self.s.m.bin(c, Bin::Shl, src, left);
  9107. let k31 = k(self, 31);
  9108. let t = self.s.m.bin(c, Bin::AShr, t, k31);
  9109. let t = self.s.m.bin(c, Bin::And, t, ff);
  9110. let kn = k(self, n);
  9111. let is = self.s.m.cmp(c, pred::EQ, sel, kn);
  9112. byte = self.s.m.select(c, is, t, byte);
  9113. }
  9114. let (k12, z) = (k(self, 12), k(self, 0));
  9115. let is12 = self.s.m.cmp(c, pred::EQ, sel, k12);
  9116. byte = self.s.m.select(c, is12, z, byte);
  9117. let above = self.s.m.cmp(c, pred::IUGT, sel, k12);
  9118. byte = self.s.m.select(c, above, ff, byte);
  9119. let at = k(self, 8 * i);
  9120. let byte = self.s.m.bin(c, Bin::Shl, byte, at);
  9121. r = self.s.m.bin(c, Bin::Or, r, byte);
  9122. }
  9123. return Ok(r);
  9124. }
  9125. };
  9126. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9127. let mut r = k(self, 0);
  9128. for i in 0..4 {
  9129. let pick = sel >> (8 * i) & 0xFF;
  9130. let byte = match pick {
  9131. 0..=7 => {
  9132. let (src, n) = if pick < 4 { (b, pick) } else { (a, pick - 4) };
  9133. let sh = k(self, 8 * n);
  9134. let t = self.s.m.bin(c, Bin::LShr, src, sh);
  9135. let ff = k(self, 0xFF);
  9136. self.s.m.bin(c, Bin::And, t, ff)
  9137. }
  9138. 8..=11 => {
  9139. let src = if pick < 10 { b } else { a };
  9140. let bit = if pick % 2 == 0 { 15 } else { 31 };
  9141. let left = k(self, 31 - bit);
  9142. let t = self.s.m.bin(c, Bin::Shl, src, left);
  9143. let k31 = k(self, 31);
  9144. let t = self.s.m.bin(c, Bin::AShr, t, k31);
  9145. let ff = k(self, 0xFF);
  9146. self.s.m.bin(c, Bin::And, t, ff)
  9147. }
  9148. 12 => continue,
  9149. _ => k(self, 0xFF),
  9150. };
  9151. let at = k(self, 8 * i);
  9152. let byte = self.s.m.bin(c, Bin::Shl, byte, at);
  9153. r = self.s.m.bin(c, Bin::Or, r, byte);
  9154. }
  9155. r
  9156. }
  9157. "v_bfm_b32" => {
  9158. // ((1 << src0[4:0]) - 1) << src1[4:0]
  9159. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9160. let one = k(self, 1);
  9161. let (a, b) = (m31(self, a), m31(self, b));
  9162. let m = self.s.m.bin(c, Bin::Shl, one, a);
  9163. let m = self.s.m.bin(c, Bin::Sub, m, one);
  9164. self.s.m.bin(c, Bin::Shl, m, b)
  9165. }
  9166. "v_cvt_pk_u8_f32" => {
  9167. // src0 rounded to nearest even and saturated to a byte, into
  9168. // byte src1[1:0] of src2.
  9169. let f = self.fsrc(inst, 0)?;
  9170. let (b, d) = (s(self, 1)?, s(self, 2)?);
  9171. let f = self.unary(26, f);
  9172. let (zero, max) = (self.s.m.f32(0), self.s.m.f32(255.0f32.to_bits()));
  9173. let f = self.binary(35, f, zero);
  9174. let f = self.binary(36, f, max);
  9175. let x = self.s.m.cast(c, Cast::FpToUi, f, self.s.t.i32);
  9176. let (three, k3) = (k(self, 3), k(self, 3));
  9177. let sh = self.s.m.bin(c, Bin::And, b, three);
  9178. let sh = self.s.m.bin(c, Bin::Shl, sh, k3);
  9179. let x = self.s.m.bin(c, Bin::Shl, x, sh);
  9180. let ff = k(self, 0xFF);
  9181. let hole = self.s.m.bin(c, Bin::Shl, ff, sh);
  9182. let ones = k(self, u32::MAX);
  9183. let hole = self.s.m.bin(c, Bin::Xor, hole, ones);
  9184. let d = self.s.m.bin(c, Bin::And, d, hole);
  9185. self.s.m.bin(c, Bin::Or, d, x)
  9186. }
  9187. "v_ffbl_b32" => {
  9188. // -1 for zero, as DXIL's first-bit-low.
  9189. let a = s(self, 0)?;
  9190. self.s
  9191. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 32, &[a])
  9192. }
  9193. "v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32" => {
  9194. // Bits of the mask's low (high) half below this lane, plus src1:
  9195. // with an all-ones mask, the lane index.
  9196. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9197. // Mesh lanes are the console's by construction; pixel and
  9198. // vertex lanes are the host's, as their masks are.
  9199. if self.mask_data == MaskData::Host {
  9200. // Host lanes: the mask must be one (a ballot) or all lanes.
  9201. let Fields::Valu(v) = &inst.fields else {
  9202. unreachable!()
  9203. };
  9204. let host = match v.src.first() {
  9205. Some(&Operand::Const(193)) => true,
  9206. Some(&Operand::Scalar { code, .. }) => {
  9207. inst.read(Reg::S(code)).is_some_and(|m| {
  9208. self.x.st.masks.contains_key(&m) || self.x.st.highs.contains_key(&m)
  9209. })
  9210. }
  9211. _ => false,
  9212. };
  9213. if !host {
  9214. return Err("v_mbcnt of a mask that is no ballot (console lane layout)");
  9215. }
  9216. self.s.flags |= flags::WAVE_OPS;
  9217. } else if self.s.mesh.is_none() {
  9218. self.cross_lane(false)?;
  9219. }
  9220. let lane = self.console_lane();
  9221. let below = if name == "v_mbcnt_lo_u32_b32" {
  9222. lane
  9223. } else {
  9224. let (k32, z) = (k(self, 32), k(self, 0));
  9225. let t = self.s.m.bin(c, Bin::Sub, lane, k32);
  9226. let low = self.s.m.cmp(c, pred::IULT, lane, k32);
  9227. self.s.m.select(c, low, z, t)
  9228. };
  9229. // (1 << below) - 1, all ones from 32 on.
  9230. let (one, k32, ones) = (k(self, 1), k(self, 32), k(self, u32::MAX));
  9231. let sh = m31(self, below);
  9232. let m = self.s.m.bin(c, Bin::Shl, one, sh);
  9233. let m = self.s.m.bin(c, Bin::Sub, m, one);
  9234. let full = self.s.m.cmp(c, pred::IUGE, below, k32);
  9235. let m = self.s.m.select(c, full, ones, m);
  9236. let x = self.s.m.bin(c, Bin::And, a, m);
  9237. let n = self
  9238. .s
  9239. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[x]);
  9240. self.s.m.bin(c, Bin::Add, n, b)
  9241. }
  9242. _ => return Err(name),
  9243. })
  9244. }
  9245. fn compare(&mut self, inst: &Inst, rest: &str) -> Result<(), Why> {
  9246. let (op, ty) = rest.rsplit_once('_').ok_or("a compare")?;
  9247. let c = self.cur;
  9248. let r = match ty {
  9249. "f32" | "f16" if op == "class" => {
  9250. // Bit k of src1 tests class k: signalling NaN, quiet NaN,
  9251. // -inf, -normal, -denormal, -0, +0, +denormal, +normal, +inf.
  9252. let f16 = ty == "f16";
  9253. let x = if f16 {
  9254. let Fields::Valu(v) = &inst.fields else {
  9255. unreachable!()
  9256. };
  9257. let mut h = self.half_src(inst, 0)?;
  9258. if v.abs & 1 != 0 {
  9259. let m = self.s.m.i32(0x7FFF);
  9260. h = self.s.m.bin(c, Bin::And, h, m);
  9261. }
  9262. if v.neg & 1 != 0 {
  9263. let s = self.s.m.i32(0x8000);
  9264. h = self.s.m.bin(c, Bin::Xor, h, s);
  9265. }
  9266. h
  9267. } else {
  9268. let x = self.fsrc(inst, 0)?;
  9269. self.as_int(x)
  9270. };
  9271. let mask = self.src(inst, 1)?;
  9272. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  9273. let (exp_sh, sign_sh, exp_mask, mant_mask, quiet_bit) = if f16 {
  9274. (10, 15, 0x1F, 0x03FF, 0x0200)
  9275. } else {
  9276. (23, 31, 0xFF, 0x7F_FFFF, 0x40_0000)
  9277. };
  9278. let (k_exp, k_sign, k_emax, mant, quiet) = (
  9279. k(self, exp_sh),
  9280. k(self, sign_sh),
  9281. k(self, exp_mask),
  9282. k(self, mant_mask),
  9283. k(self, quiet_bit),
  9284. );
  9285. let e = self.s.m.bin(c, Bin::LShr, x, k_exp);
  9286. let e = self.s.m.bin(c, Bin::And, e, k_emax);
  9287. let m = self.s.m.bin(c, Bin::And, x, mant);
  9288. let neg = self.s.m.bin(c, Bin::LShr, x, k_sign);
  9289. let zero = k(self, 0);
  9290. let (e0, emax) = (
  9291. self.s.m.cmp(c, pred::EQ, e, zero),
  9292. self.s.m.cmp(c, pred::EQ, e, k_emax),
  9293. );
  9294. let m0 = self.s.m.cmp(c, pred::EQ, m, zero);
  9295. let q = self.s.m.bin(c, Bin::And, x, quiet);
  9296. let q = self.s.m.cmp(c, pred::NE, q, zero);
  9297. // Positive classes 6-9; negative ones are 11 minus those.
  9298. let (normal, inf, zero_c, denorm) =
  9299. (k(self, 8), k(self, 9), k(self, 6), k(self, 7));
  9300. let t = self.s.m.select(c, m0, zero_c, denorm);
  9301. let t = self.s.m.select(c, e0, t, normal);
  9302. let t = self.s.m.select(c, emax, inf, t);
  9303. let eleven = k(self, 11);
  9304. let mirrored = self.s.m.bin(c, Bin::Sub, eleven, t);
  9305. let is_neg = self.s.m.cmp(c, pred::NE, neg, zero);
  9306. let t = self.s.m.select(c, is_neg, mirrored, t);
  9307. let (one, snan) = (k(self, 1), k(self, 0));
  9308. let nan_class = self.s.m.select(c, q, one, snan);
  9309. let yes = self.s.m.bool(true);
  9310. let nan = self.s.m.bin(c, Bin::Xor, m0, yes);
  9311. let nan = self.s.m.bin(c, Bin::And, nan, emax);
  9312. let t = self.s.m.select(c, nan, nan_class, t);
  9313. let bit = self.s.m.bin(c, Bin::LShr, mask, t);
  9314. let bit = self.s.m.bin(c, Bin::And, bit, one);
  9315. self.s.m.cmp(c, pred::NE, bit, zero)
  9316. }
  9317. "f32" | "f16" => {
  9318. let (a, b) = if ty == "f16" {
  9319. (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?)
  9320. } else {
  9321. (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?)
  9322. };
  9323. if op == "lg" {
  9324. // Ordered and not equal, false for a NaN, as `olt | ogt`.
  9325. // `fcmp one` means the same, but the AMD D3D12 driver
  9326. // runs it as unordered (true for a NaN) where NVIDIA
  9327. // and WARP do not; olt and ogt agree on all three.
  9328. let lt = self.s.m.cmp(c, pred::OLT, a, b);
  9329. let gt = self.s.m.cmp(c, pred::OGT, a, b);
  9330. self.s.m.bin(c, Bin::Or, lt, gt)
  9331. } else {
  9332. let p = match op {
  9333. "f" => pred::FALSE,
  9334. "lt" => pred::OLT,
  9335. "eq" => pred::OEQ,
  9336. "le" => pred::OLE,
  9337. "gt" => pred::OGT,
  9338. "ge" => pred::OGE,
  9339. "o" => pred::ORD,
  9340. "u" => pred::UNO,
  9341. "nge" => pred::ULT,
  9342. "nlg" => pred::UEQ,
  9343. "ngt" => pred::ULE,
  9344. "nle" => pred::UGT,
  9345. "neq" => pred::UNE,
  9346. "nlt" => pred::UGE,
  9347. "tru" => pred::TRUE,
  9348. _ => return Err(inst.name()),
  9349. };
  9350. self.s.m.cmp(c, p, a, b)
  9351. }
  9352. }
  9353. "u64" | "i64" => {
  9354. let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?);
  9355. let signed = ty == "i64";
  9356. let p = match op {
  9357. "eq" => pred::EQ,
  9358. "ne" | "lg" => pred::NE,
  9359. "lt" if signed => pred::SLT,
  9360. "le" if signed => pred::SLE,
  9361. "gt" if signed => pred::SGT,
  9362. "ge" if signed => pred::SGE,
  9363. "lt" => pred::IULT,
  9364. "le" => pred::IULE,
  9365. "gt" => pred::IUGT,
  9366. "ge" => pred::IUGE,
  9367. _ => return Err("a 64-bit compare"),
  9368. };
  9369. self.s.m.cmp(c, p, a, b)
  9370. }
  9371. "u32" | "i32" | "u16" | "i16" => {
  9372. let (a, b) = if ty.ends_with("16") {
  9373. let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
  9374. if ty == "i16" {
  9375. let k16 = self.s.m.i32(16);
  9376. for x in [&mut a, &mut b] {
  9377. let t = self.s.m.bin(c, Bin::Shl, *x, k16);
  9378. *x = self.s.m.bin(c, Bin::AShr, t, k16);
  9379. }
  9380. }
  9381. (a, b)
  9382. } else {
  9383. (self.src(inst, 0)?, self.src(inst, 1)?)
  9384. };
  9385. let signed = ty == "i32" || ty == "i16";
  9386. let p = match op {
  9387. "eq" => pred::EQ,
  9388. "ne" | "lg" => pred::NE,
  9389. "lt" if signed => pred::SLT,
  9390. "le" if signed => pred::SLE,
  9391. "gt" if signed => pred::SGT,
  9392. "ge" if signed => pred::SGE,
  9393. "lt" => pred::IULT,
  9394. "le" => pred::IULE,
  9395. "gt" => pred::IUGT,
  9396. "ge" => pred::IUGE,
  9397. "f" | "t" => {
  9398. self.lane(inst, Some(op == "t"));
  9399. return Ok(());
  9400. }
  9401. _ => return Err("an integer compare"),
  9402. };
  9403. self.s.m.cmp(c, p, a, b)
  9404. }
  9405. _ => return Err(inst.name()),
  9406. };
  9407. self.lane_bits_for(inst, r);
  9408. Ok(())
  9409. }
  9410. fn lane(&mut self, inst: &Inst, value: Option<bool>) {
  9411. let b = self.s.m.bool(value == Some(true));
  9412. self.lane_bits_for(inst, b);
  9413. }
  9414. fn lane_bits_for(&mut self, inst: &Inst, r: V) {
  9415. let Fields::Valu(v) = &inst.fields else {
  9416. return;
  9417. };
  9418. let code = if inst.name().starts_with("v_cmpx") {
  9419. Some(EXEC)
  9420. } else {
  9421. match v.dst {
  9422. Some(Operand::Scalar { code, .. }) => Some(code),
  9423. _ => None,
  9424. }
  9425. };
  9426. if let Some(lo) = code.and_then(|c| inst.write(Reg::S(c))) {
  9427. self.lane_bits.insert(lo, r);
  9428. }
  9429. for &(_, w) in &inst.writes {
  9430. self.vals
  9431. .entry(w)
  9432. .or_insert(Val::Missing("a lane mask read as data"));
  9433. }
  9434. }
  9435. fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  9436. let Some(&interp) = self.interps.get(&site) else {
  9437. return Err("the first half of an interpolation");
  9438. };
  9439. let name = inst.name();
  9440. let (dst, src) = match &inst.fields {
  9441. Fields::Vintrp { dst, src, .. } => (*dst, Some(*src)),
  9442. Fields::Valu(v) => {
  9443. if v.abs != 0 || v.neg != 0 {
  9444. return Err("interpolation operand modifiers");
  9445. }
  9446. (v.dst.ok_or("an interpolation")?, v.src.get(1).copied())
  9447. }
  9448. _ => unreachable!(),
  9449. };
  9450. let Operand::Vector { reg, .. } = dst else {
  9451. return Err("an interpolation");
  9452. };
  9453. // A float operand of the instruction.
  9454. let float = |l: &mut Self, op: Option<Operand>| -> Result<V, Why> {
  9455. let x = l.operand(inst, &op.ok_or("an interpolation operand")?)?;
  9456. Ok(l.as_float(x))
  9457. };
  9458. // What the result adds to the evaluated channel (a second half's
  9459. // first half, when the halves evaluate on their own).
  9460. let mut add = None;
  9461. let (attribute, eval) = match *interp {
  9462. Interp::Interpolated {
  9463. attribute,
  9464. barycentric,
  9465. ..
  9466. } => {
  9467. let mode = interp_mode(barycentric).ok_or("pull-model interpolation")?;
  9468. let eval = if self.per_vertex(attribute.row) {
  9469. // The element is read per vertex elsewhere, so it is
  9470. // constant: weigh its vertices with SV_Barycentrics.
  9471. let mut ij = [None; 2];
  9472. for (index, w) in ij.iter_mut().enumerate() {
  9473. let x = match self.barycentric(barycentric, index as u8) {
  9474. Val::I32(x) => x,
  9475. Val::Missing(w) => return Err(w),
  9476. Val::Bit(_) => unreachable!(),
  9477. };
  9478. *w = Some(self.as_float(x));
  9479. }
  9480. Eval::Weights {
  9481. p0: true,
  9482. i: ij[0],
  9483. j: ij[1],
  9484. }
  9485. } else {
  9486. Eval::Mode(mode)
  9487. };
  9488. (attribute, eval)
  9489. }
  9490. // P0, the provoking vertex: a flat (nointerpolation) input.
  9491. Interp::Vertex {
  9492. attribute,
  9493. vertex: 2,
  9494. } => (attribute, Eval::Mode(1)),
  9495. // P10 and P20: what the first and second halves weigh, P1 - P0
  9496. // and P2 - P0, which is what the hardware holds for an
  9497. // attribute the program also interpolates.
  9498. Interp::Vertex { attribute, vertex } if self.interpolated(attribute.row) => {
  9499. let one = Some(self.s.m.f32(1f32.to_bits()));
  9500. let (i, j) = if vertex == 0 {
  9501. (one, None)
  9502. } else {
  9503. (None, one)
  9504. };
  9505. (attribute, Eval::Weights { p0: false, i, j })
  9506. }
  9507. Interp::Vertex { .. } => return Err("a non-provoking vertex value"),
  9508. // A half of an interpolation with computed i or j: P0 + i P10,
  9509. // or the old dst (f16: the third operand) + j P20.
  9510. Interp::Weighted { attribute } if name.starts_with("v_interp_p1") => {
  9511. let i = Some(float(self, src)?);
  9512. (
  9513. attribute,
  9514. Eval::Weights {
  9515. p0: true,
  9516. i,
  9517. j: None,
  9518. },
  9519. )
  9520. }
  9521. Interp::Weighted { attribute } => {
  9522. let old = match &inst.fields {
  9523. Fields::Valu(v) => v.src.get(2).copied(),
  9524. _ => Some(dst),
  9525. };
  9526. add = Some(float(self, old)?);
  9527. let j = Some(float(self, src)?);
  9528. (
  9529. attribute,
  9530. Eval::Weights {
  9531. p0: false,
  9532. i: None,
  9533. j,
  9534. },
  9535. )
  9536. }
  9537. };
  9538. let packing = match &self.x.native.io {
  9539. StageIo::Ps { inputs, .. } => inputs
  9540. .iter()
  9541. .find(|i| i.row == attribute.row && i.fp16)
  9542. .map(|i| {
  9543. let packs = if i.pack2 {
  9544. input_packs(&self.x.native.io, &self.s.inputs)
  9545. } else {
  9546. Vec::new()
  9547. };
  9548. (i.pack2, packs)
  9549. }),
  9550. _ => None,
  9551. };
  9552. let f16 = name.ends_with("_f16");
  9553. // The evaluated channel plus `add`, as a float.
  9554. let total = |l: &mut Self, row: u8, ch: u8| -> Result<V, Why> {
  9555. let x = l.eval_channel(row, ch, eval)?;
  9556. let x = l.as_float(x);
  9557. Ok(match add {
  9558. Some(a) => l.s.m.bin(l.cur, Bin::Add, a, x),
  9559. None => x,
  9560. })
  9561. };
  9562. let x = match packing {
  9563. None if f16 || attribute.high => return Err("a 16-bit read of a 32-bit input"),
  9564. None => {
  9565. let x = total(self, attribute.row, attribute.channel)?;
  9566. self.as_int(x)
  9567. }
  9568. Some((pack2, packs)) => {
  9569. // 16-bit values: one in the low half of each dword, or two
  9570. // per dword (`packed_half`); the host's are 32-bit floats.
  9571. let half = |l: &mut Self, h: u8| -> Result<Option<V>, Why> {
  9572. let src = if pack2 {
  9573. packed_half(&l.s.inputs, &packs, attribute.row, h)
  9574. } else {
  9575. h.is_multiple_of(2).then_some((attribute.row, h / 2))
  9576. };
  9577. match src {
  9578. Some((row, ch)) => total(l, row, ch).map(Some),
  9579. None => Ok(None),
  9580. }
  9581. };
  9582. let to_f16 = |l: &mut Self, f: V| {
  9583. let i32t = l.s.t.i32;
  9584. l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  9585. };
  9586. let h = 2 * attribute.channel + u8::from(attribute.high);
  9587. let c = self.cur;
  9588. if name == "v_interp_p1ll_f16" {
  9589. // An f32 result from 16-bit vertex values.
  9590. let f = half(self, h)?.ok_or("a packed input half no element holds")?;
  9591. self.as_int(f)
  9592. } else if f16 {
  9593. let f = half(self, h)?.ok_or("a packed input half no element holds")?;
  9594. let lo = to_f16(self, f);
  9595. self.low_half(inst, reg, lo)
  9596. } else if matches!(eval, Eval::Mode(1)) {
  9597. // The whole dword of a flat input: both halves.
  9598. let h = 2 * attribute.channel;
  9599. let z = self.s.m.i32(0);
  9600. let lo = match half(self, h)? {
  9601. Some(f) => to_f16(self, f),
  9602. None => z,
  9603. };
  9604. let hi = match half(self, h + 1)? {
  9605. Some(f) => to_f16(self, f),
  9606. None => z,
  9607. };
  9608. let k16 = self.s.m.i32(16);
  9609. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  9610. self.s.m.bin(c, Bin::Or, lo, hi)
  9611. } else {
  9612. return Err("32-bit interpolation of a 16-bit input");
  9613. }
  9614. }
  9615. };
  9616. // A pixel interpolates in every lane; guards only hide inactive ones.
  9617. self.write(inst, Reg::V(reg), x, None);
  9618. Ok(())
  9619. }
  9620. /// Whether the program reads attribute row `row` per vertex (an
  9621. /// interpolation with computed barycentrics, or P10 or P20): then its
  9622. /// element is declared constant and read with `attributeAtVertex`.
  9623. fn per_vertex(&self, row: u8) -> bool {
  9624. self.x.io.interps.iter().any(|(_, i)| match *i {
  9625. Interp::Weighted { attribute } => attribute.row == row,
  9626. Interp::Vertex { attribute, vertex } => {
  9627. attribute.row == row && vertex != 2 && self.interpolated(row)
  9628. }
  9629. Interp::Interpolated { .. } => false,
  9630. })
  9631. }
  9632. /// Whether the program interpolates attribute row `row` (so the
  9633. /// hardware holds P1 - P0 and P2 - P0 for it).
  9634. fn interpolated(&self, row: u8) -> bool {
  9635. self.x.io.interps.iter().any(|(_, i)| match *i {
  9636. Interp::Interpolated { attribute, .. } | Interp::Weighted { attribute } => {
  9637. attribute.row == row
  9638. }
  9639. Interp::Vertex { .. } => false,
  9640. })
  9641. }
  9642. /// Channel `ch` of input row `row` evaluated as `eval` says, as raw bits.
  9643. fn eval_channel(&mut self, row: u8, ch: u8, eval: Eval) -> Result<V, Why> {
  9644. let (id, col) = self
  9645. .find_input(row, ch)
  9646. .ok_or("an input the signature lacks")?;
  9647. let mode = match eval {
  9648. Eval::Mode(mode) => mode,
  9649. Eval::Weights { .. } => 1,
  9650. };
  9651. let e = &mut self.s.inputs[id];
  9652. if e.interp != mode && e.usage != 0 {
  9653. return Err("one input interpolated two ways");
  9654. }
  9655. e.interp = mode;
  9656. let Eval::Weights { p0, i, j } = eval else {
  9657. return match self.load_any_input(id, col) {
  9658. Val::I32(x) => Ok(x),
  9659. _ => Err("an input"),
  9660. };
  9661. };
  9662. let v0 = self.vertex_input(id, col, 0);
  9663. let c = self.cur;
  9664. let mut acc = p0.then_some(v0);
  9665. for (k, w) in [(1, i), (2, j)] {
  9666. let Some(w) = w else { continue };
  9667. let vk = self.vertex_input(id, col, k);
  9668. let d = self.s.m.bin(c, Bin::Sub, vk, v0);
  9669. acc = Some(match acc {
  9670. Some(a) => self.fmad(w, d, a),
  9671. None => self.s.m.bin(c, Bin::Mul, w, d),
  9672. });
  9673. }
  9674. let acc = acc.ok_or("an interpolation")?;
  9675. Ok(self.as_int(acc))
  9676. }
  9677. /// Vertex `k` (0 the provoking vertex, as `barycentric` orders them)
  9678. /// of a constant input element's channel, as a float.
  9679. fn vertex_input(&mut self, id: usize, col: u8, k: u8) -> V {
  9680. let e = &mut self.s.inputs[id];
  9681. e.usage |= 1 << col;
  9682. let int = e.comp != 9;
  9683. let (ty, suffix) = if int {
  9684. (self.s.t.i32, ".i32")
  9685. } else {
  9686. (self.s.t.f32, ".f32")
  9687. };
  9688. self.s.flags |= flags::BARYCENTRICS;
  9689. let entry = self.s.entry;
  9690. let args = [
  9691. self.s.m.i32(id as u32),
  9692. self.s.m.i32(0),
  9693. self.s.m.i8(col),
  9694. self.s.m.i8(k),
  9695. ];
  9696. let v = self.s.op(
  9697. entry,
  9698. &format!("attributeAtVertex{suffix}"),
  9699. Attr::ReadNone,
  9700. ty,
  9701. 137,
  9702. &args,
  9703. );
  9704. if int {
  9705. self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.f32)
  9706. } else {
  9707. v
  9708. }
  9709. }
  9710. /// `x` (an f16 in the low bits) as the low half of VGPR `reg`: 16-bit
  9711. /// results keep the register's high half (GFX10).
  9712. fn low_half(&mut self, inst: &Inst, reg: u8, x: V) -> V {
  9713. let c = self.cur;
  9714. let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) {
  9715. Some(Ok(o)) => o,
  9716. _ => self.s.m.i32(0),
  9717. };
  9718. let (high, low) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF));
  9719. let old = self.s.m.bin(c, Bin::And, old, high);
  9720. let x = self.s.m.bin(c, Bin::And, x, low);
  9721. self.s.m.bin(c, Bin::Or, old, x)
  9722. }
  9723. fn image(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  9724. let Fields::Image {
  9725. data,
  9726. addr,
  9727. dmask,
  9728. dim,
  9729. unorm,
  9730. a16,
  9731. d16,
  9732. tfe,
  9733. lwe,
  9734. ..
  9735. } = &inst.fields
  9736. else {
  9737. unreachable!()
  9738. };
  9739. if *tfe || *lwe {
  9740. return Err("an image access with tfe or lwe");
  9741. }
  9742. let name = inst.name();
  9743. // A load or sample with no channel enabled returns the first.
  9744. let dmask = if *dmask == 0 { &1 } else { dmask };
  9745. let site = (b, i);
  9746. let guard = self.guard(b, i)?;
  9747. let c = self.cur;
  9748. let (kind, coords) = match dim {
  9749. 0 => (1, 1),
  9750. 1 => (2, 2),
  9751. 2 => (4, 3),
  9752. // Sampled (face coordinates and face, see `cube_direction`) or
  9753. // sized only.
  9754. 3 if name.starts_with("image_sample")
  9755. || name.starts_with("image_gather")
  9756. || name == "image_get_resinfo" =>
  9757. {
  9758. (5, 3)
  9759. }
  9760. 4 => (6, 2),
  9761. 5 => (7, 3),
  9762. _ => return Err("an image dimension (cube loads or MSAA)"),
  9763. };
  9764. // Address VGPRs in order.
  9765. let mut regs = Vec::new();
  9766. for a in addr {
  9767. if let Operand::Vector { reg, dwords } = *a {
  9768. regs.extend((0..dwords).map(|k| reg + k));
  9769. }
  9770. }
  9771. // Full 32-bit address VGPR at `reg_idx` (offset, bias, z-compare).
  9772. let addr_u32 = |l: &mut Self, reg_idx: usize| -> Result<V, Why> {
  9773. let r = *regs.get(reg_idx).ok_or("an image address")?;
  9774. let v = inst.read(Reg::V(r)).ok_or("an image address")?;
  9775. l.i32_of(v)
  9776. };
  9777. // With a16, two 16-bit components per VGPR starting at `base_reg`, low half first.
  9778. let addr_packed = |l: &mut Self, base_reg: usize, k: usize| -> Result<V, Why> {
  9779. let x = addr_u32(l, base_reg + if *a16 { k / 2 } else { k })?;
  9780. if !*a16 {
  9781. return Ok(x);
  9782. }
  9783. let c = l.cur;
  9784. let (sh, mask) = (l.s.m.i32(16 * (k as u32 % 2)), l.s.m.i32(0xFFFF));
  9785. let x = l.s.m.bin(c, Bin::LShr, x, sh);
  9786. Ok(l.s.m.bin(c, Bin::And, x, mask))
  9787. };
  9788. let addr_val = |l: &mut Self, k: usize| -> Result<V, Why> { addr_packed(l, 0, k) };
  9789. let src = self
  9790. .descriptors
  9791. .get(&(site, false))
  9792. .copied()
  9793. .ok_or("an untracked image")?;
  9794. let store = name.starts_with("image_store");
  9795. let uav = store
  9796. || self
  9797. .used_kind(src)
  9798. .is_some_and(|u| u.kind == ResourceType::Uav);
  9799. // A UAV inside an ordered section is a rasterizer ordered view.
  9800. let ordered = uav && self.ordered.contains(&site);
  9801. if ordered {
  9802. self.s.flags |= flags::ROVS;
  9803. }
  9804. let rov = if ordered { 0x2000 } else { 0 };
  9805. let props = (kind | if uav { 0x1000 } else { 0 } | rov, 0x409);
  9806. if let Some(op) = name.strip_prefix("image_atomic_") {
  9807. // GLC returns the old value. DXIL implements subtraction by adding
  9808. // the two's complement of the operand at the same width.
  9809. let code = match op {
  9810. "add" | "sub" => 0,
  9811. "and" => 1,
  9812. "or" => 2,
  9813. "xor" => 3,
  9814. "smin" => 4,
  9815. "smax" => 5,
  9816. "umin" => 6,
  9817. "umax" => 7,
  9818. "swap" => 8,
  9819. "cmpswap" => u32::MAX,
  9820. _ => return Err(name),
  9821. };
  9822. let Fields::Image { cache, .. } = &inst.fields else {
  9823. unreachable!()
  9824. };
  9825. // 16-bit coordinates (a16) are read as `addr_val` reads them.
  9826. if *d16 {
  9827. return Err("a 16-bit image atomic");
  9828. }
  9829. // Compare-exchange consumes a replacement followed by a comparand.
  9830. let compare = code == u32::MAX;
  9831. let wide = match (compare, *dmask) {
  9832. (false, 1) | (true, 3) => false,
  9833. (false, 3) | (true, 15) => true,
  9834. _ => return Err("an image atomic data mask"),
  9835. };
  9836. let iu = self.s.m.undef(self.s.t.i32);
  9837. let mut cs = vec![iu; 3];
  9838. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  9839. *slot = addr_val(self, k)?;
  9840. }
  9841. let Operand::Vector { reg, .. } = *data else {
  9842. return Err("image atomic data");
  9843. };
  9844. let width = if wide { 2 } else { 1 };
  9845. let vals = self.vgprs(inst, data, if compare { 2 * width } else { width })?;
  9846. let (ty, component) = if wide {
  9847. self.s.flags |= flags::INT64 | flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64;
  9848. (self.s.m.int(64), 0x107) // one uint64_t in an R32G32_UINT view
  9849. } else {
  9850. (self.s.t.i32, 0x105)
  9851. };
  9852. let original = if wide {
  9853. self.join64(vals[0], vals[1])
  9854. } else {
  9855. vals[0]
  9856. };
  9857. let value = if op == "sub" {
  9858. let zero = self.s.m.int_const(ty, 0);
  9859. self.s.m.bin(c, Bin::Sub, zero, original)
  9860. } else {
  9861. original
  9862. };
  9863. let h = self.handle(site, src, false, (kind | 0x1000 | rov, component))?;
  9864. let mut args = vec![h];
  9865. let (intrinsic, opcode) = if compare {
  9866. let comparand = if wide {
  9867. self.join64(vals[2], vals[3])
  9868. } else {
  9869. vals[1]
  9870. };
  9871. args.extend(cs);
  9872. args.extend([comparand, value]);
  9873. let intrinsic = if wide {
  9874. "atomicCompareExchange.i64"
  9875. } else {
  9876. "atomicCompareExchange.i32"
  9877. };
  9878. (intrinsic, 79)
  9879. } else {
  9880. args.push(self.s.m.i32(code));
  9881. args.extend(cs);
  9882. args.push(value);
  9883. (
  9884. if wide {
  9885. "atomicBinOp.i64"
  9886. } else {
  9887. "atomicBinOp.i32"
  9888. },
  9889. 78,
  9890. )
  9891. };
  9892. let at = self.begin_guarded(guard);
  9893. let r = self
  9894. .s
  9895. .op(self.cur, intrinsic, Attr::NoUnwind, ty, opcode, &args);
  9896. if cache.glc {
  9897. let old = self.end_guarded(at, &[(r, original)])[0];
  9898. if wide {
  9899. let (lo, hi) = self.split64(old);
  9900. self.write(inst, Reg::V(reg), lo, None);
  9901. self.write(inst, Reg::V(reg + 1), hi, None);
  9902. } else {
  9903. self.write(inst, Reg::V(reg), old, None);
  9904. }
  9905. } else {
  9906. self.end_guarded(at, &[]);
  9907. }
  9908. return Ok(());
  9909. }
  9910. if store {
  9911. if name != "image_store" {
  9912. return Err("an image store to a mip level");
  9913. }
  9914. // shortcut: stores are taken to write all four channels of a
  9915. // float format (the console converts by the view's format).
  9916. // One channel goes into a view the program also counts in.
  9917. let counter = *dmask == 1 && self.is_counter(src);
  9918. if *dmask != 0xF && !counter {
  9919. return Err("an image store of some channels");
  9920. }
  9921. let iu = self.s.m.undef(self.s.t.i32);
  9922. let mut cs = vec![iu; 3];
  9923. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  9924. *slot = addr_val(self, k)?;
  9925. }
  9926. let Operand::Vector { reg, .. } = *data else {
  9927. return Err("image store data");
  9928. };
  9929. if counter {
  9930. let v = inst.read(Reg::V(reg)).ok_or("image store data")?;
  9931. let x = self.i32_of(v)?;
  9932. // A 16-bit integer, extended by the view's sign: the same
  9933. // number either way only if it is known to be small.
  9934. if *d16 && !self.s.m.int_k(x).is_some_and(|(_, k)| k < 0x8000) {
  9935. return Err("a 16-bit image store of one channel");
  9936. }
  9937. let h = self.handle(site, src, false, (kind | 0x1000 | rov, 0x105))?;
  9938. let at = self.begin_guarded(guard);
  9939. // All four channels are written (the validator wants them
  9940. // all): the view has the first alone.
  9941. let mut args = vec![h];
  9942. args.extend(cs);
  9943. args.extend([x; 4]);
  9944. args.push(self.s.m.i8(0xF));
  9945. let void = self.s.t.void;
  9946. self.s.op(
  9947. self.cur,
  9948. "textureStore.i32",
  9949. Attr::NoUnwind,
  9950. void,
  9951. 67,
  9952. &args,
  9953. );
  9954. self.end_guarded(at, &[]);
  9955. return Ok(());
  9956. }
  9957. let mut vals = Vec::new();
  9958. for k in 0..4u8 {
  9959. // d16: two f16 channels per VGPR, low half first.
  9960. let r = if *d16 { k / 2 } else { k };
  9961. let v = inst.read(Reg::V(reg + r)).ok_or("image store data")?;
  9962. vals.push(if *d16 {
  9963. let mut x = self.i32_of(v)?;
  9964. if k % 2 == 1 {
  9965. let k16 = self.s.m.i32(16);
  9966. x = self.s.m.bin(self.cur, Bin::LShr, x, k16);
  9967. }
  9968. let f32t = self.s.t.f32;
  9969. self.s
  9970. .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x])
  9971. } else {
  9972. self.float_of(v)?
  9973. });
  9974. }
  9975. let h = self.handle(site, src, false, props)?;
  9976. let at = self.begin_guarded(guard);
  9977. let mut args = vec![h];
  9978. args.extend(cs);
  9979. args.extend(vals);
  9980. args.push(self.s.m.i8(0xF));
  9981. let void = self.s.t.void;
  9982. self.s.op(
  9983. self.cur,
  9984. "textureStore.f32",
  9985. Attr::NoUnwind,
  9986. void,
  9987. 67,
  9988. &args,
  9989. );
  9990. self.end_guarded(at, &[]);
  9991. return Ok(());
  9992. }
  9993. let has_cl = name.ends_with("_cl");
  9994. let (op, sample) = match name {
  9995. "image_sample" | "image_sample_o" | "image_sample_cl" => (60, true),
  9996. "image_sample_lz" | "image_sample_l" | "image_sample_lz_o" => (62, true),
  9997. "image_sample_b" | "image_sample_b_cl" => (61, true),
  9998. "image_sample_c_lz" => (65, true),
  9999. "image_sample_d" | "image_sample_d_cl" => (63, true),
  10000. "image_get_lod" if self.s.pixel => (81, true),
  10001. // Implicit derivatives: pixel shaders only.
  10002. "image_sample_c" if self.s.pixel => (64, true),
  10003. "image_sample_c_cl" if self.s.pixel => (64, true),
  10004. "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" | "image_gather4_l" | "image_gather4_l_o" => (73, true),
  10005. "image_load" | "image_load_mip" => (66, false),
  10006. "image_get_resinfo" => (72, false),
  10007. _ => return Err(name),
  10008. };
  10009. if op == 72 {
  10010. // Width, height, depth or layers, levels (per dmask) of the level
  10011. // in the first address: DXIL's dimensions; a channel DXIL leaves
  10012. // out reads 1 (UAVs: one level).
  10013. let h = self.handle(site, src, false, props)?;
  10014. let mip = if uav {
  10015. self.s.m.undef(self.s.t.i32)
  10016. } else {
  10017. addr_val(self, 0)?
  10018. };
  10019. let i32t = self.s.t.i32;
  10020. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  10021. let d = self
  10022. .s
  10023. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  10024. let one = self.s.m.i32(1);
  10025. let present = match kind {
  10026. 1 => [true, false, false, true],
  10027. 2 | 5 | 6 => [true, true, false, true],
  10028. _ => [true, true, true, true],
  10029. };
  10030. let Operand::Vector { reg, .. } = *data else {
  10031. return Err("an image result");
  10032. };
  10033. for (k, ch) in (0..4u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() {
  10034. let x = if ch == 3 && uav || !present[ch as usize] {
  10035. one
  10036. } else {
  10037. self.s.m.extract(c, d, ch)
  10038. };
  10039. self.write(inst, Reg::V(reg + k as u8), x, guard);
  10040. }
  10041. return Ok(());
  10042. }
  10043. if uav && op != 66 {
  10044. return Err("sampling a UAV");
  10045. }
  10046. let h = self.handle(site, src, false, props)?;
  10047. let fu = self.s.m.undef(self.s.t.f32);
  10048. let iu = self.s.m.undef(self.s.t.i32);
  10049. // A gather at a named level, done as four texel reads (below).
  10050. let mut gathered: Option<[V; 4]> = None;
  10051. let r = if sample {
  10052. let ss = self
  10053. .descriptors
  10054. .get(&(site, true))
  10055. .copied()
  10056. .ok_or("an untracked sampler")?;
  10057. // Comparison: the reference value is the first address after
  10058. // the bias, and the sampler is a comparison sampler.
  10059. let cmp = matches!(op, 64 | 65);
  10060. if cmp && (*a16 || dmask.count_ones() != 1) {
  10061. return Err("a comparison sample of 16-bit coordinates or several channels");
  10062. }
  10063. let mut sampler_choice: Option<(V, Vec<u32>)> = None;
  10064. let sh = match ss {
  10065. Source::Phi { block, args } => {
  10066. match self.sampler_phi_choice(*block, args, cmp, 8) {
  10067. Ok((None, regs)) => self.s.sampler_handle(self.cur, regs[0]),
  10068. Ok((Some(idx), regs)) => {
  10069. let first = self.s.sampler_handle(self.cur, regs[0]);
  10070. sampler_choice = Some((idx, regs));
  10071. first
  10072. }
  10073. Err(_) => {
  10074. self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?
  10075. }
  10076. }
  10077. }
  10078. _ => self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?,
  10079. };
  10080. // Texel offsets (`_o`) come first: x in bits 0-5, y in 8-13,
  10081. // signed (programmable offsets: gathers only).
  10082. let offset_word = name.ends_with("_o");
  10083. let first = usize::from(offset_word)
  10084. + usize::from(name.starts_with("image_sample_b"))
  10085. + usize::from(cmp);
  10086. // Coordinates the size divides (not the array slice); explicit
  10087. // gradients (x then y) come before the coordinates.
  10088. let spatial = coords - usize::from(kind == 6 || kind == 7);
  10089. // A cube's gradients are the two of its face coordinates.
  10090. let grads = if kind == 5 { 2 } else { spatial };
  10091. let deriv_regs = if op == 63 {
  10092. if *a16 {
  10093. grads.div_ceil(2)
  10094. } else {
  10095. grads
  10096. }
  10097. } else {
  10098. 0
  10099. };
  10100. let coord_base = first + 2 * deriv_regs;
  10101. let mut cs = vec![fu; 4];
  10102. // With a16, sampling coordinates, gradients, LOD and clamp are f16.
  10103. let to_float = |l: &mut Self, x: V| {
  10104. if *a16 {
  10105. let f = l.s.t.f32;
  10106. l.s.op(l.cur, "legacyF16ToF32", Attr::ReadNone, f, 131, &[x])
  10107. } else {
  10108. l.as_float(x)
  10109. }
  10110. };
  10111. if kind == 5 && (*unorm || op == 81) {
  10112. return Err("a cube sample with texel coordinates or a level query");
  10113. }
  10114. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  10115. let x = addr_packed(self, coord_base, k)?;
  10116. *slot = to_float(self, x);
  10117. }
  10118. if kind == 5 {
  10119. let dir = self.cube_direction(cs[0], cs[1], cs[2]);
  10120. cs[..3].copy_from_slice(&dir);
  10121. }
  10122. if *unorm {
  10123. // Texel coordinates: divided by the size of level 0.
  10124. let i32t = self.s.t.i32;
  10125. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  10126. let z = self.s.m.i32(0);
  10127. let d = self
  10128. .s
  10129. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]);
  10130. for (k, slot) in cs.iter_mut().enumerate().take(spatial) {
  10131. let n = self.s.m.extract(c, d, k as u32);
  10132. let n = self.s.m.cast(c, Cast::UiToFp, n, self.s.t.f32);
  10133. *slot = self.s.m.bin(c, Bin::SDiv, *slot, n);
  10134. }
  10135. }
  10136. if op == 81 {
  10137. // The clamped then the unclamped level of detail.
  10138. let Operand::Vector { reg, .. } = *data else {
  10139. return Err("an image result");
  10140. };
  10141. let f32t = self.s.t.f32;
  10142. for (k, ch) in (0..2u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() {
  10143. let clamped = self.s.m.bool(ch == 0);
  10144. let lod = self.s.op(
  10145. c,
  10146. "calculateLOD.f32",
  10147. Attr::ReadOnly,
  10148. f32t,
  10149. 81,
  10150. &[h, sh, cs[0], cs[1], cs[2], clamped],
  10151. );
  10152. let x = self.as_int(lod);
  10153. self.write(inst, Reg::V(reg + k as u8), x, guard);
  10154. }
  10155. return Ok(());
  10156. }
  10157. let offsets = if kind == 5 {
  10158. 0
  10159. } else {
  10160. (coords - usize::from(kind == 6 || kind == 7)).min(3)
  10161. };
  10162. let zero = self.s.m.i32(0);
  10163. let mut os = vec![iu; 3];
  10164. for o in os.iter_mut().take(offsets) {
  10165. *o = zero;
  10166. }
  10167. if offset_word && offsets > 0 {
  10168. let w = addr_val(self, 0)?;
  10169. for (k, at) in [(0, 26), (1, 18)].into_iter().take(offsets.min(2)) {
  10170. // Bits at..at+5 sign-extended: shift up, then down.
  10171. let left = self.s.m.i32(at);
  10172. let t = self.s.m.bin(c, Bin::Shl, w, left);
  10173. let k26 = self.s.m.i32(26);
  10174. os[k] = self.s.m.bin(c, Bin::AShr, t, k26);
  10175. }
  10176. }
  10177. let mut args = vec![h, sh];
  10178. args.extend(&cs);
  10179. let clamp = if has_cl {
  10180. let x = addr_packed(self, coord_base, coords)?;
  10181. to_float(self, x)
  10182. } else {
  10183. fu
  10184. };
  10185. let call_sample = |l: &mut Self,
  10186. intrinsic: &str,
  10187. opcode: u32,
  10188. args: &[V],
  10189. gathered: &mut Option<[V; 4]>|
  10190. -> V {
  10191. let Some((idx, ref regs)) = sampler_choice else {
  10192. return l
  10193. .s
  10194. .op(c, intrinsic, Attr::ReadOnly, l.s.t.res_ret, opcode, args);
  10195. };
  10196. let merge = l.s.m.new_block();
  10197. let mut cur_test = c;
  10198. let mut per_ch: [Vec<(V, usize)>; 4] = Default::default();
  10199. let mut last_r = args[0];
  10200. for (i, &reg) in regs.iter().enumerate() {
  10201. let arm = if i + 1 == regs.len() {
  10202. cur_test
  10203. } else {
  10204. let arm = l.s.m.new_block();
  10205. let next = l.s.m.new_block();
  10206. let k = l.s.m.i32(i as u32);
  10207. let cond = l.s.m.cmp(cur_test, pred::EQ, idx, k);
  10208. l.s.m.terminate(cur_test, Term::CondBr(cond, arm, next));
  10209. cur_test = next;
  10210. arm
  10211. };
  10212. let mut arm_args = args.to_vec();
  10213. arm_args[1] = l.s.sampler_handle(arm, reg);
  10214. let r_i = l.s.op(
  10215. arm,
  10216. intrinsic,
  10217. Attr::ReadOnly,
  10218. l.s.t.res_ret,
  10219. opcode,
  10220. &arm_args,
  10221. );
  10222. for (ch, slot) in per_ch.iter_mut().enumerate() {
  10223. let v = l.s.m.extract(arm, r_i, ch as u32);
  10224. slot.push((v, arm));
  10225. }
  10226. l.s.m.terminate(arm, Term::Br(merge));
  10227. last_r = r_i;
  10228. }
  10229. let mut phis = [fu; 4];
  10230. for (ch, incoming) in per_ch.into_iter().enumerate() {
  10231. let phi = l.s.m.phi(merge, l.s.t.f32);
  10232. l.s.m.set_phi(phi, incoming);
  10233. phis[ch] = phi;
  10234. }
  10235. *gathered = Some(phis);
  10236. l.cur = merge;
  10237. last_r
  10238. };
  10239. match op {
  10240. // Outside a pixel shader there are no screen derivatives:
  10241. // the validator refuses `sample` there ("features
  10242. // incompatible with the shader stage": 730 compute programs,
  10243. // among them the G-buffer resolves and the sky), and what a
  10244. // driver does with it is its own affair.
  10245. // shortcut: such a sample reads level 0 (a bias: that
  10246. // level). The console takes derivatives from neighbouring
  10247. // lanes there; compute them from the lanes if a resolve
  10248. // shows the wrong mip.
  10249. 60 if !self.s.pixel => {
  10250. args.extend(&os);
  10251. args.push(self.s.m.f32(0));
  10252. call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
  10253. }
  10254. 60 => {
  10255. if offset_word {
  10256. // DXIL wants immediate offsets in -8..=7 here; the
  10257. // console's are 6-bit and may be computed. A
  10258. // constant word in range becomes immediates
  10259. // (upstream PR #634); anything else keeps the
  10260. // offsets computed above (upstream refuses those).
  10261. let w = addr_val(self, 0)?;
  10262. if let Some(w) = self.s.m.int_value(w) {
  10263. let w = w as u32;
  10264. let field = |k: usize| {
  10265. let x = (w >> (8 * k) & 0x3F) as i32;
  10266. if x >= 32 { x - 64 } else { x }
  10267. };
  10268. let n = offsets.min(2);
  10269. if (0..n).all(|k| (-8..=7).contains(&field(k))) {
  10270. for (k, o) in os.iter_mut().enumerate().take(n) {
  10271. *o = self.s.m.i32(field(k) as u32);
  10272. }
  10273. }
  10274. }
  10275. }
  10276. args.extend(&os);
  10277. args.push(clamp);
  10278. call_sample(self, "sample.f32", 60, &args, &mut gathered)
  10279. }
  10280. 61 => {
  10281. // With a16 the bias is an f16 in the low half of its
  10282. // word (the word is whole, the value is not).
  10283. let bias = addr_u32(self, usize::from(offset_word))?;
  10284. let bias = if *a16 {
  10285. let low = self.s.m.i32(0xFFFF);
  10286. let bias = self.s.m.bin(c, Bin::And, bias, low);
  10287. to_float(self, bias)
  10288. } else {
  10289. self.as_float(bias)
  10290. };
  10291. args.extend(&os);
  10292. if self.s.pixel {
  10293. args.extend([bias, clamp]);
  10294. call_sample(self, "sampleBias.f32", 61, &args, &mut gathered)
  10295. } else {
  10296. // As above: the bias is the level.
  10297. args.push(bias);
  10298. call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
  10299. }
  10300. }
  10301. 63 if kind == 5 => {
  10302. // A cube with explicit gradients: the host wants them
  10303. // as changes of the direction, the console gives the
  10304. // changes of the face coordinates (the face is one
  10305. // unit wide). The level they select is taken from the
  10306. // longer of the two, in texels, and sampled directly.
  10307. // shortcut: no anisotropic filtering for these samples
  10308. // (the longer axis alone decides the level).
  10309. let mut len = [fu; 2];
  10310. for (axis, slot) in len.iter_mut().enumerate() {
  10311. let mut sum = self.s.m.f32(0);
  10312. for k in 0..2 {
  10313. let x = addr_packed(self, first + axis * deriv_regs, k)?;
  10314. let x = to_float(self, x);
  10315. let sq = self.s.m.bin(c, Bin::Mul, x, x);
  10316. sum = self.s.m.bin(c, Bin::Add, sum, sq);
  10317. }
  10318. *slot = self.unary(24, sum); // square root
  10319. }
  10320. let longer = self.binary(35, len[0], len[1]); // maximum
  10321. let i32t = self.s.t.i32;
  10322. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  10323. let z = self.s.m.i32(0);
  10324. let d = self
  10325. .s
  10326. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]);
  10327. let width = self.s.m.extract(c, d, 0);
  10328. let width = self.s.m.cast(c, Cast::UiToFp, width, self.s.t.f32);
  10329. let texels = self.s.m.bin(c, Bin::Mul, longer, width);
  10330. // log2 = natural logarithm / ln 2; a length of 0 gives
  10331. // minus infinity, which the sampler clamps to level 0.
  10332. let ln = self.unary(23, texels);
  10333. let per_ln2 = self.s.m.f32(std::f32::consts::LOG2_E.to_bits());
  10334. let lod = self.s.m.bin(c, Bin::Mul, ln, per_ln2);
  10335. args.extend(&os);
  10336. args.push(lod);
  10337. call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
  10338. }
  10339. 63 => {
  10340. let mut g = vec![fu; 6];
  10341. for k in 0..spatial {
  10342. let x = addr_packed(self, first, k)?;
  10343. g[k] = to_float(self, x);
  10344. let y = addr_packed(self, first + deriv_regs, k)?;
  10345. g[3 + k] = to_float(self, y);
  10346. }
  10347. args.extend(&os);
  10348. args.extend(g);
  10349. args.push(clamp);
  10350. call_sample(self, "sampleGrad.f32", 63, &args, &mut gathered)
  10351. }
  10352. 64 | 65 => {
  10353. let reference = addr_u32(self, first - 1)?;
  10354. let reference = self.as_float(reference);
  10355. args.extend(&os);
  10356. args.push(reference);
  10357. let name = if op == 64 {
  10358. args.push(clamp);
  10359. "sampleCmp.f32"
  10360. } else {
  10361. "sampleCmpLevelZero.f32"
  10362. };
  10363. call_sample(self, name, op, &args, &mut gathered)
  10364. }
  10365. 62 => {
  10366. let lod = if name == "image_sample_l" {
  10367. let x = addr_packed(self, coord_base, coords)?;
  10368. to_float(self, x)
  10369. } else {
  10370. self.s.m.f32(0)
  10371. };
  10372. args.extend(&os);
  10373. args.push(lod);
  10374. call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
  10375. }
  10376. _ => {
  10377. if name == "image_gather4" {
  10378. return Err("a gather with implicit level");
  10379. }
  10380. if dmask.count_ones() != 1 {
  10381. return Err("a gather of several channels");
  10382. }
  10383. if matches!(name, "image_gather4_l" | "image_gather4_l_o")
  10384. && coords == 2
  10385. && spatial == 2
  10386. {
  10387. // The host's gather has no level: it read level 0
  10388. // where the title names one (the depth pyramid its
  10389. // occlusion tests read: most of the world was
  10390. // culled against the wrong depths). The four texels
  10391. // are read at the level instead, in the gather's
  10392. // order: (u0,v1) (u1,v1) (u1,v0) (u0,v0).
  10393. // With an offset too (`image_gather4_l_o`): the
  10394. // offset is in texels of that level.
  10395. // The title's meshlet culling takes a 4x4 block of
  10396. // the pyramid as one gather and three offset ones
  10397. // ((2,0), (0,2), (2,2)); the three read level 0,
  10398. // two texels beside the first one's place, so a
  10399. // meshlet three or four texels wide was tested
  10400. // against a quarter of what it covers.
  10401. // shortcut: the level is rounded to a whole one and
  10402. // coordinates past the edge are clamped, whatever
  10403. // the sampler says.
  10404. let lod = addr_packed(self, coord_base, coords)?;
  10405. let lod = to_float(self, lod);
  10406. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  10407. let zero = self.s.m.f32(0);
  10408. let lod = self.binary(35, lod, zero); // maximum
  10409. let lod = self.unary(26, lod); // round to nearest
  10410. let mip = self.s.m.cast(c, Cast::FpToUi, lod, i32t);
  10411. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  10412. let d = self
  10413. .s
  10414. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  10415. let half = self.s.m.f32(0.5f32.to_bits());
  10416. let one = self.s.m.f32(1.0f32.to_bits());
  10417. let (mut lo, mut hi) = ([iu; 2], [iu; 2]);
  10418. for k in 0..2 {
  10419. let n = self.s.m.extract(c, d, k as u32);
  10420. let n = self.s.m.cast(c, Cast::UiToFp, n, f32t);
  10421. let last = self.s.m.bin(c, Bin::Sub, n, one);
  10422. let t = self.s.m.bin(c, Bin::Mul, cs[k], n);
  10423. let t = self.s.m.bin(c, Bin::Sub, t, half);
  10424. let first = self.unary(27, t); // round down
  10425. // The offset word's field (0 without one).
  10426. let by = self.s.m.cast(c, Cast::SiToFp, os[k], f32t);
  10427. let first = self.s.m.bin(c, Bin::Add, first, by);
  10428. let next = self.s.m.bin(c, Bin::Add, first, one);
  10429. for (slot, x) in [(&mut lo[k], first), (&mut hi[k], next)] {
  10430. let x = self.binary(35, x, zero); // maximum
  10431. let x = self.binary(36, x, last); // minimum
  10432. *slot = self.s.m.cast(c, Cast::FpToSi, x, i32t);
  10433. }
  10434. }
  10435. let ch = dmask.trailing_zeros();
  10436. let mut g = [fu; 4];
  10437. let mut read = None;
  10438. let texels = [(lo[0], hi[1]), (hi[0], hi[1]), (hi[0], lo[1]), (lo[0], lo[1])];
  10439. for (slot, (x, y)) in g.iter_mut().zip(texels) {
  10440. let r = self.s.op(
  10441. c,
  10442. "textureLoad.f32",
  10443. Attr::ReadOnly,
  10444. self.s.t.res_ret,
  10445. 66,
  10446. &[h, mip, x, y, iu, iu, iu, iu],
  10447. );
  10448. *slot = self.s.m.extract(c, r, ch);
  10449. read = Some(r);
  10450. }
  10451. gathered = Some(g);
  10452. read.expect("four reads")
  10453. } else {
  10454. args.extend(&os[..2]);
  10455. args.push(self.s.m.i32(dmask.trailing_zeros()));
  10456. call_sample(self, "textureGather.f32", 73, &args, &mut gathered)
  10457. }
  10458. }
  10459. }
  10460. } else {
  10461. let mut cs = vec![iu; 3];
  10462. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  10463. *slot = addr_val(self, k)?;
  10464. }
  10465. let mip = if name == "image_load_mip" {
  10466. addr_val(self, coords)?
  10467. } else if uav {
  10468. // Our declarations have four channels.
  10469. self.s.flags |= flags::TYPED_UAV_LOADS;
  10470. iu
  10471. } else {
  10472. self.s.m.i32(0)
  10473. };
  10474. let mut args = vec![h, mip];
  10475. args.extend(&cs);
  10476. args.extend([iu, iu, iu]);
  10477. self.s.op(
  10478. c,
  10479. "textureLoad.f32",
  10480. Attr::ReadOnly,
  10481. self.s.t.res_ret,
  10482. 66,
  10483. &args,
  10484. )
  10485. };
  10486. let Operand::Vector { reg, .. } = *data else {
  10487. return Err("an image result");
  10488. };
  10489. let channels: Vec<u32> = if op == 73 {
  10490. vec![0, 1, 2, 3]
  10491. } else {
  10492. (0..4).filter(|ch| dmask >> ch & 1 != 0).collect()
  10493. };
  10494. let mut xs = Vec::new();
  10495. for ch in channels {
  10496. let x = match gathered {
  10497. Some(g) => g[ch as usize],
  10498. None => self.s.m.extract(c, r, ch),
  10499. };
  10500. xs.push(if *d16 {
  10501. // shortcut: d16 results are taken as floats (rounded to
  10502. // nearest even); integer formats would keep 16 bits.
  10503. let i32t = self.s.t.i32;
  10504. self.s
  10505. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x])
  10506. } else {
  10507. self.as_int(x)
  10508. });
  10509. }
  10510. if *d16 {
  10511. // Two channels per VGPR, low half first (an odd last high half 0).
  10512. let k16 = self.s.m.i32(16);
  10513. xs = xs
  10514. .chunks(2)
  10515. .map(|p| match *p {
  10516. [lo, hi] => {
  10517. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  10518. self.s.m.bin(c, Bin::Or, lo, hi)
  10519. }
  10520. _ => p[0],
  10521. })
  10522. .collect();
  10523. }
  10524. for (k, x) in xs.into_iter().enumerate() {
  10525. self.write(inst, Reg::V(reg + k as u8), x, guard);
  10526. }
  10527. Ok(())
  10528. }
  10529. /// The direction a cube sample's face coordinates stand for: the
  10530. /// console takes s and t in [1, 2] (`v_cubesc`/`v_cubetc` over
  10531. /// `|v_cubema|`, plus 1.5) and the face id (`v_cubeid`), which the
  10532. /// host's cube sampling turns back into the same texel.
  10533. // shortcut: the view is taken as a cube, not a cube array (whose face
  10534. // operand adds 8 × the slice).
  10535. fn cube_direction(&mut self, s: V, t: V, face: V) -> [V; 3] {
  10536. let c = self.cur;
  10537. let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits());
  10538. let (two, three) = (k(self, 2.0), k(self, 3.0));
  10539. let u = self.s.m.bin(c, Bin::Mul, s, two);
  10540. let u = self.s.m.bin(c, Bin::Sub, u, three);
  10541. let v = self.s.m.bin(c, Bin::Mul, t, two);
  10542. let v = self.s.m.bin(c, Bin::Sub, v, three);
  10543. let z = self.s.m.f32(0x8000_0000);
  10544. let (nu, nv) = (
  10545. self.s.m.bin(c, Bin::Sub, z, u),
  10546. self.s.m.bin(c, Bin::Sub, z, v),
  10547. );
  10548. let (one, mone) = (k(self, 1.0), k(self, -1.0));
  10549. let f = self.s.m.cast(c, Cast::FpToUi, face, self.s.t.i32);
  10550. // Per face +x, -x, +y, -y, +z, -z.
  10551. let table = [
  10552. [one, mone, u, u, u, nu],
  10553. [nv, nv, one, mone, nv, nv],
  10554. [nu, u, v, nv, one, mone],
  10555. ];
  10556. table.map(|row| {
  10557. let mut r = row[0];
  10558. for (n, &x) in row.iter().enumerate().skip(1) {
  10559. let kn = self.s.m.i32(n as u32);
  10560. let is = self.s.m.cmp(c, pred::EQ, f, kn);
  10561. r = self.s.m.select(c, is, x, r);
  10562. }
  10563. r
  10564. })
  10565. }
  10566. fn buffer(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  10567. let Fields::Buffer {
  10568. data,
  10569. addr,
  10570. soffset,
  10571. offset,
  10572. offen,
  10573. idxen,
  10574. format,
  10575. lds,
  10576. tfe,
  10577. ..
  10578. } = &inst.fields
  10579. else {
  10580. unreachable!()
  10581. };
  10582. let name = inst.name();
  10583. if name == "buffer_gl0_inv" || name == "buffer_gl1_inv" {
  10584. // The host has no console buffer cache to invalidate.
  10585. return Ok(());
  10586. }
  10587. if *lds || *tfe {
  10588. return Err("a buffer access to LDS or with tfe");
  10589. }
  10590. if format.is_some() && !name.starts_with("tbuffer_load_format_") {
  10591. return Err(name);
  10592. }
  10593. let site = (b, i);
  10594. let guard = self.guard(b, i)?;
  10595. let c = self.cur;
  10596. let store = name.starts_with("buffer_store_");
  10597. // DXIL atomic operations: add, and, or, xor, signed and unsigned
  10598. // min and max, exchange; compare-exchange apart.
  10599. let atomic = match name.strip_prefix("buffer_atomic_") {
  10600. None => None,
  10601. Some("add") => Some(0),
  10602. Some("and") => Some(1),
  10603. Some("or") => Some(2),
  10604. Some("xor") => Some(3),
  10605. Some("smin") => Some(4),
  10606. Some("smax") => Some(5),
  10607. Some("umin") => Some(6),
  10608. Some("umax") => Some(7),
  10609. Some("swap") => Some(8),
  10610. Some("cmpswap") => Some(u32::MAX),
  10611. Some(_) => return Err(name),
  10612. };
  10613. // Byte and 16-bit accesses: bits, and whether a load sign-extends.
  10614. let narrow = match name {
  10615. "buffer_load_ubyte" | "buffer_store_byte" => Some((8, false)),
  10616. "buffer_load_sbyte" => Some((8, true)),
  10617. "buffer_load_ushort" | "buffer_store_short" => Some((16, false)),
  10618. "buffer_load_sshort" => Some((16, true)),
  10619. _ => None,
  10620. };
  10621. // d16: two 16-bit channels per VGPR, low half first (buffer and
  10622. // tbuffer formats alike).
  10623. let d16 = name.contains("_format_d16_");
  10624. let plain = name.replace("_format_d16_", "_format_");
  10625. let (typed, count) = match plain
  10626. .strip_prefix("buffer_load_")
  10627. .or(plain.strip_prefix("buffer_store_"))
  10628. .or(plain.strip_prefix("tbuffer_load_"))
  10629. {
  10630. _ if atomic.is_some() || narrow.is_some() => (false, 1),
  10631. Some("dword") => (false, 1),
  10632. Some("dwordx2") => (false, 2),
  10633. Some("dwordx3") => (false, 3),
  10634. Some("dwordx4") => (false, 4),
  10635. Some("format_x") => (true, 1),
  10636. Some("format_xy") => (true, 2),
  10637. Some("format_xyz") => (true, 3),
  10638. Some("format_xyzw") => (true, 4),
  10639. _ => return Err(name),
  10640. };
  10641. let Operand::Vector { reg: areg, .. } = *addr else {
  10642. return Err("a buffer address");
  10643. };
  10644. let vaddr = |l: &mut Self, k: u8| -> Result<V, Why> {
  10645. let v = inst.read(Reg::V(areg + k)).ok_or("a buffer address")?;
  10646. l.i32_of(v)
  10647. };
  10648. let index = if *idxen { Some(vaddr(self, 0)?) } else { None };
  10649. let mut off = self.s.m.i32(u32::from(*offset));
  10650. if *offen {
  10651. let o = vaddr(self, u8::from(*idxen))?;
  10652. off = self.s.m.bin(c, Bin::Add, off, o);
  10653. }
  10654. if !matches!(
  10655. soffset,
  10656. Operand::Scalar { code: NULL, .. } | Operand::Const(128)
  10657. ) {
  10658. let so = self.operand(inst, soffset)?;
  10659. off = self.s.m.bin(c, Bin::Add, off, so);
  10660. }
  10661. let src = self
  10662. .descriptors
  10663. .get(&(site, false))
  10664. .copied()
  10665. .ok_or("an untracked buffer")?;
  10666. let used = self.used_kind(src);
  10667. let (base, extra) = self.built_offset(src)?;
  10668. if base != 0 {
  10669. let b = self.s.m.i32(base);
  10670. off = self.s.m.bin(c, Bin::Add, off, b);
  10671. }
  10672. if let Some(x) = extra {
  10673. off = self.s.m.bin(c, Bin::Add, off, x);
  10674. }
  10675. // A buffer the program picks from the view heap by an index it
  10676. // computes: no used-resource entry gives its stride, the host's
  10677. // table by heap slot does; the access becomes a raw one at the
  10678. // element's byte. (Also tells the host this shader reads such
  10679. // buffers.)
  10680. let mut index = index;
  10681. if let Some(stride) = self.slot_stride(src)?
  10682. && let Some(element) = index
  10683. && !typed
  10684. && used.is_none()
  10685. {
  10686. let at = self.s.m.bin(c, Bin::Mul, element, stride);
  10687. off = self.s.m.bin(c, Bin::Add, at, off);
  10688. index = None;
  10689. }
  10690. // A structured buffer by its used-resource entry's stride: raw
  10691. // bytes too. The host makes its buffer views raw (a raw read
  10692. // through a structured view gives zeros on NVIDIA), and one kind
  10693. // of view can then serve every shader that reads the buffer.
  10694. if let (Some(element), Some(u)) = (index, used)
  10695. && !typed
  10696. && u.kind != ResourceType::Cbv
  10697. && u.stride >= 4
  10698. && u.stride.is_multiple_of(4)
  10699. {
  10700. let k = self.s.m.i32(u.stride);
  10701. let at = self.s.m.bin(c, Bin::Mul, element, k);
  10702. off = self.s.m.bin(c, Bin::Add, at, off);
  10703. index = None;
  10704. }
  10705. if used.is_some_and(|u| u.kind == ResourceType::Cbv) && !typed {
  10706. // A constant buffer read per lane (a dynamically indexed array).
  10707. // shortcut: the console's CBV descriptor is taken to have a 16-byte
  10708. // stride, as the vector loads of whole rows suggest.
  10709. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  10710. let byte = match index {
  10711. Some(i) => {
  10712. let sixteen = self.s.m.i32(16);
  10713. let rows = self.s.m.bin(c, Bin::Mul, i, sixteen);
  10714. self.s.m.bin(c, Bin::Add, rows, off)
  10715. }
  10716. None => off,
  10717. };
  10718. let Some(Operand::Vector { reg, .. }) = *data else {
  10719. return Err("a buffer result");
  10720. };
  10721. for k in 0..count {
  10722. let four = self.s.m.i32(4 * k);
  10723. let a = self.s.m.bin(c, Bin::Add, byte, four);
  10724. let x = self.cbuffer_dword(h, a);
  10725. self.write(inst, Reg::V(reg + k as u8), x, guard);
  10726. }
  10727. return Ok(());
  10728. }
  10729. let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav);
  10730. let mut u = if uav { 0x1000 } else { 0 };
  10731. if uav && !typed && self.entry(src).is_some_and(|e| self.coherent.contains(&e)) {
  10732. u |= 0x4000;
  10733. }
  10734. let iu = self.s.m.undef(self.s.t.i32);
  10735. if let Some((bits, signed)) = narrow {
  10736. // Below a dword: raw buffers are read and written in dwords on
  10737. // 4 bytes, so the dword that holds the value is read and
  10738. // shifted, or changed with two atomic operations that touch
  10739. // only the value's own bits (other lanes may write the rest of
  10740. // the dword at the same time). A 16-bit value at a dword's
  10741. // last byte continues in the next dword.
  10742. let byte = match index {
  10743. None => off,
  10744. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  10745. self.s.m.bin(c, Bin::Add, index, off)
  10746. }
  10747. Some(_) => return Err("a byte or 16-bit buffer access by index"),
  10748. };
  10749. let h = self.handle(site, src, false, (11 | u, 0))?;
  10750. let k3 = self.s.m.i32(3);
  10751. let within = self.s.m.bin(c, Bin::And, byte, k3);
  10752. let aligned = self.s.m.bin(c, Bin::Sub, byte, within);
  10753. let shift = self.s.m.bin(c, Bin::Shl, within, k3);
  10754. let four = self.s.m.i32(4);
  10755. let next = self.s.m.bin(c, Bin::Add, aligned, four);
  10756. let ones = self.s.m.i32(if bits == 8 { 0xff } else { 0xffff });
  10757. let zero = self.s.m.i32(0);
  10758. let k8 = self.s.m.i32(8);
  10759. let straddles = self.s.m.cmp(c, pred::EQ, within, k3);
  10760. if !store {
  10761. let mask = self.s.m.i8(1);
  10762. let align = self.s.m.i32(4);
  10763. let dword = |l: &mut Self, at: V| {
  10764. let r = l.s.op(
  10765. c,
  10766. "rawBufferLoad.f32",
  10767. Attr::ReadOnly,
  10768. l.s.t.res_ret,
  10769. 139,
  10770. &[h, at, iu, mask, align],
  10771. );
  10772. let f = l.s.m.extract(c, r, 0);
  10773. l.as_int(f)
  10774. };
  10775. let low = dword(self, aligned);
  10776. let mut x = self.s.m.bin(c, Bin::LShr, low, shift);
  10777. if bits == 16 {
  10778. let high = dword(self, next);
  10779. let high = self.s.m.bin(c, Bin::Shl, high, k8);
  10780. let high = self.s.m.select(c, straddles, high, zero);
  10781. x = self.s.m.bin(c, Bin::Or, x, high);
  10782. }
  10783. x = self.s.m.bin(c, Bin::And, x, ones);
  10784. if signed {
  10785. let up = self.s.m.i32(32 - bits);
  10786. x = self.s.m.bin(c, Bin::Shl, x, up);
  10787. x = self.s.m.bin(c, Bin::AShr, x, up);
  10788. }
  10789. let Some(Operand::Vector { reg, .. }) = *data else {
  10790. return Err("a buffer result");
  10791. };
  10792. self.write(inst, Reg::V(reg), x, guard);
  10793. return Ok(());
  10794. }
  10795. let d = data.as_ref().ok_or("buffer store data")?;
  10796. let v = self.vgprs(inst, d, 1)?[0];
  10797. let v = self.s.m.bin(c, Bin::And, v, ones);
  10798. let all = self.s.m.i32(u32::MAX);
  10799. let clear = self.s.m.bin(c, Bin::Shl, ones, shift);
  10800. let keep = self.s.m.bin(c, Bin::Xor, clear, all);
  10801. let set = self.s.m.bin(c, Bin::Shl, v, shift);
  10802. let keep_next = self.s.m.i32(0xffff_ff00);
  10803. let set_next = self.s.m.bin(c, Bin::LShr, v, k8);
  10804. let (and, or) = (self.s.m.i32(1), self.s.m.i32(2));
  10805. let i32t = self.s.t.i32;
  10806. let at = self.begin_guarded(guard);
  10807. for (op, x) in [(and, keep), (or, set)] {
  10808. let args = [h, op, aligned, iu, iu, x];
  10809. self.s
  10810. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args);
  10811. }
  10812. if bits == 16 {
  10813. let second = self.begin_guarded(Some(straddles));
  10814. for (op, x) in [(and, keep_next), (or, set_next)] {
  10815. let args = [h, op, next, iu, iu, x];
  10816. self.s
  10817. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args);
  10818. }
  10819. self.end_guarded(second, &[]);
  10820. }
  10821. self.end_guarded(at, &[]);
  10822. return Ok(());
  10823. }
  10824. if let Some(op) = atomic {
  10825. let d = data.as_ref().ok_or("buffer atomic data")?;
  10826. let vals = self.vgprs(inst, d, if op == u32::MAX { 2 } else { 1 })?;
  10827. let (h, coords) = match index {
  10828. // A raw buffer (stride 1) read by index: the index is the byte.
  10829. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  10830. let byte = self.s.m.bin(c, Bin::Add, index, off);
  10831. (self.handle(site, src, false, (11 | u, 0))?, [byte, iu, iu])
  10832. }
  10833. Some(index) => {
  10834. let stride = used.map_or(0, |u| u.stride);
  10835. if stride < 4 || !stride.is_multiple_of(4) {
  10836. return Err("a structured buffer of unknown stride");
  10837. }
  10838. let h = self.handle(site, src, false, (12 | u, stride))?;
  10839. (h, [index, off, iu])
  10840. }
  10841. None => (self.handle(site, src, false, (11 | u, 0))?, [off, iu, iu]),
  10842. };
  10843. let Operand::Vector { reg, .. } = *d else {
  10844. return Err("buffer atomic data");
  10845. };
  10846. let returns = matches!(inst.fields, Fields::Buffer { cache, .. } if cache.glc);
  10847. let old = match inst.read(Reg::V(reg)) {
  10848. Some(v) if returns => self.i32_of(v)?,
  10849. _ => self.s.m.i32(0),
  10850. };
  10851. let at = self.begin_guarded(guard);
  10852. let i32t = self.s.t.i32;
  10853. let r = if op == u32::MAX {
  10854. // cmpswap: data is (new, compare).
  10855. let mut args = vec![h];
  10856. args.extend(coords);
  10857. args.extend([vals[1], vals[0]]);
  10858. self.s.op(
  10859. self.cur,
  10860. "atomicCompareExchange.i32",
  10861. Attr::NoUnwind,
  10862. i32t,
  10863. 79,
  10864. &args,
  10865. )
  10866. } else {
  10867. let mut args = vec![h, self.s.m.i32(op)];
  10868. args.extend(coords);
  10869. args.push(vals[0]);
  10870. self.s
  10871. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args)
  10872. };
  10873. let r = self.end_guarded(at, &[(r, old)])[0];
  10874. if returns {
  10875. self.write(inst, Reg::V(reg), r, None);
  10876. }
  10877. return Ok(());
  10878. }
  10879. if store {
  10880. let regs = if d16 { count.div_ceil(2) } else { count };
  10881. let mut vals =
  10882. self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?;
  10883. if d16 {
  10884. // shortcut: d16 data is taken as f16 (integer formats would
  10885. // keep 16 bits), widened for the 32-bit float store.
  10886. let mut wide = Vec::new();
  10887. for k in 0..count {
  10888. let mut x = vals[(k / 2) as usize];
  10889. if k % 2 == 1 {
  10890. let k16 = self.s.m.i32(16);
  10891. x = self.s.m.bin(c, Bin::LShr, x, k16);
  10892. }
  10893. let f32t = self.s.t.f32;
  10894. let f = self
  10895. .s
  10896. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
  10897. wide.push(self.as_int(f));
  10898. }
  10899. vals = wide;
  10900. }
  10901. let mut args = Vec::new();
  10902. let (op, name) = if typed {
  10903. // shortcut: typed stores are taken to write all four channels
  10904. // of a float format.
  10905. if count != 4 || *offen || *offset != 0 {
  10906. return Err("a typed buffer store of some channels or at an offset");
  10907. }
  10908. args.push(self.handle(site, src, false, (10 | u, 0x409))?);
  10909. args.extend([index.unwrap_or(self.s.m.i32(0)), iu]);
  10910. for x in vals {
  10911. args.push(self.as_float(x));
  10912. }
  10913. (69, "bufferStore.f32")
  10914. } else {
  10915. match index {
  10916. // A raw buffer (stride 1) written by index: the index is the byte.
  10917. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  10918. let byte = self.s.m.bin(c, Bin::Add, index, off);
  10919. args.push(self.handle(site, src, false, (11 | u, 0))?);
  10920. args.extend([byte, iu]);
  10921. }
  10922. Some(index) => {
  10923. let stride = used.map_or(0, |u| u.stride);
  10924. if stride < 4 || !stride.is_multiple_of(4) {
  10925. return Err("a structured buffer of unknown stride");
  10926. }
  10927. args.push(self.handle(site, src, false, (12 | u, stride))?);
  10928. args.extend([index, off]);
  10929. }
  10930. None => {
  10931. args.push(self.handle(site, src, false, (11 | u, 0))?);
  10932. args.extend([off, iu]);
  10933. }
  10934. }
  10935. args.extend(&vals);
  10936. args.resize(3 + 4, iu);
  10937. (140, "rawBufferStore.i32")
  10938. };
  10939. args.push(self.s.m.i8(if typed { 0xF } else { (1u8 << count) - 1 }));
  10940. if !typed {
  10941. args.push(self.s.m.i32(4));
  10942. }
  10943. let at = self.begin_guarded(guard);
  10944. let void = self.s.t.void;
  10945. self.s.op(self.cur, name, Attr::NoUnwind, void, op, &args);
  10946. self.end_guarded(at, &[]);
  10947. return Ok(());
  10948. }
  10949. if let Some(f) = *format {
  10950. if index.is_some() {
  10951. return Err("a typed-format load by index");
  10952. }
  10953. let h = self.handle(site, src, false, (11 | u, 0))?;
  10954. let Some(Operand::Vector { reg, .. }) = *data else {
  10955. return Err("a buffer result");
  10956. };
  10957. let mut xs = self.format_load(h, off, f, count)?;
  10958. if d16 {
  10959. xs = self.d16_channels(f, xs)?;
  10960. }
  10961. for (k, x) in xs.into_iter().enumerate() {
  10962. self.write(inst, Reg::V(reg + k as u8), x, guard);
  10963. }
  10964. return Ok(());
  10965. }
  10966. let r = if typed {
  10967. if *offen || matches!(off, V::Inst(_)) || *offset != 0 {
  10968. return Err("a typed buffer load at an offset");
  10969. }
  10970. if uav {
  10971. self.s.flags |= flags::TYPED_UAV_LOADS;
  10972. }
  10973. let h = self.handle(site, src, false, (10 | u, 0x409))?;
  10974. let index = index.unwrap_or(self.s.m.i32(0));
  10975. self.s.op(
  10976. c,
  10977. "bufferLoad.f32",
  10978. Attr::ReadOnly,
  10979. self.s.t.res_ret,
  10980. 68,
  10981. &[h, index, iu],
  10982. )
  10983. } else {
  10984. let mask = self.s.m.i8((1u8 << count) - 1);
  10985. let align = self.s.m.i32(4);
  10986. match index {
  10987. // A raw buffer (stride 1) read by index: the index is the byte.
  10988. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  10989. let byte = self.s.m.bin(c, Bin::Add, index, off);
  10990. let h = self.handle(site, src, false, (11 | u, 0))?;
  10991. self.s.op(
  10992. c,
  10993. "rawBufferLoad.f32",
  10994. Attr::ReadOnly,
  10995. self.s.t.res_ret,
  10996. 139,
  10997. &[h, byte, iu, mask, align],
  10998. )
  10999. }
  11000. Some(index) => {
  11001. let stride = used.map_or(0, |u| u.stride);
  11002. if stride < 4 || !stride.is_multiple_of(4) {
  11003. return Err("a structured buffer of unknown stride");
  11004. }
  11005. let h = self.handle(site, src, false, (12 | u, stride))?;
  11006. self.s.op(
  11007. c,
  11008. "rawBufferLoad.f32",
  11009. Attr::ReadOnly,
  11010. self.s.t.res_ret,
  11011. 139,
  11012. &[h, index, off, mask, align],
  11013. )
  11014. }
  11015. None => {
  11016. let h = self.handle(site, src, false, (11 | u, 0))?;
  11017. self.s.op(
  11018. c,
  11019. "rawBufferLoad.f32",
  11020. Attr::ReadOnly,
  11021. self.s.t.res_ret,
  11022. 139,
  11023. &[h, off, iu, mask, align],
  11024. )
  11025. }
  11026. }
  11027. };
  11028. let Some(Operand::Vector { reg, .. }) = *data else {
  11029. return Err("a buffer result");
  11030. };
  11031. if d16 {
  11032. // Two f16 channels per VGPR (an odd last high half 0).
  11033. let k16 = self.s.m.i32(16);
  11034. let i32t = self.s.t.i32;
  11035. for k in 0..count.div_ceil(2) {
  11036. let mut x = None;
  11037. for ch in (2 * k..(2 * k + 2).min(count)).rev() {
  11038. let f = self.s.m.extract(c, r, ch);
  11039. let h = self
  11040. .s
  11041. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
  11042. x = Some(match x {
  11043. Some(hi) => {
  11044. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  11045. self.s.m.bin(c, Bin::Or, h, hi)
  11046. }
  11047. None => h,
  11048. });
  11049. }
  11050. self.write(inst, Reg::V(reg + k as u8), x.expect("a channel"), guard);
  11051. }
  11052. return Ok(());
  11053. }
  11054. for k in 0..count {
  11055. let x = self.s.m.extract(c, r, k);
  11056. let x = self.as_int(x);
  11057. self.write(inst, Reg::V(reg + k as u8), x, guard);
  11058. }
  11059. Ok(())
  11060. }
  11061. fn export(&mut self, b: usize, i: usize) -> Result<(), Why> {
  11062. let e = *self
  11063. .exports
  11064. .get(&(b, i))
  11065. .ok_or("an export I/O raising did not see")?;
  11066. if e.compressed {
  11067. return Err("a compressed export");
  11068. }
  11069. let guard = self.guard(b, i)?;
  11070. let mesh = self.s.mesh.is_some();
  11071. let c = self.cur;
  11072. if let Some(g) = guard
  11073. && !mesh
  11074. {
  11075. if !(e.done && self.s.pixel) {
  11076. return Err("a conditional export");
  11077. }
  11078. let t = self.s.m.bool(true);
  11079. let kill = self.s.m.bin(c, Bin::Xor, g, t);
  11080. self.s
  11081. .op(c, "discard", Attr::NoUnwind, self.s.t.void, 82, &[kill]);
  11082. }
  11083. if mesh && e.target == Target::Primitive {
  11084. return self.emit_indices(e, guard);
  11085. }
  11086. let param_row = |usage: Usage, row: u8| match usage {
  11087. // The 2020 compiler leaves a mesh program's first entry zeroed
  11088. // (usage "position"): its row is the one no other entry names.
  11089. Usage::Other(0) if mesh => self.unnamed_row(),
  11090. _ => Some(row),
  11091. };
  11092. // (output element, channel) per exported channel; per-primitive
  11093. // outputs are elements of `prims`.
  11094. let mut stores = Vec::new();
  11095. let primitive = matches!(e.target, Target::PrimitiveParam { .. });
  11096. let outputs = if primitive {
  11097. &self.s.prims
  11098. } else {
  11099. &self.s.outputs
  11100. };
  11101. let by_kind = |kind: u8| outputs.iter().position(|o| o.kind == kind);
  11102. // 16-bit vertex outputs: the halves each dword carries, as (output
  11103. // element, channel, high half) per channel.
  11104. let halves = match e.target {
  11105. Target::Param { usage, row } => {
  11106. param_row(usage, row).and_then(|r| self.half_outputs.get(&r).map(|&h| (r, h)))
  11107. }
  11108. _ => None,
  11109. };
  11110. if let Some((row, (pack2, _))) = halves {
  11111. let packs: Vec<(u8, Option<u8>)> = self
  11112. .half_outputs
  11113. .iter()
  11114. .filter(|(_, h)| h.0)
  11115. .map(|(&r, h)| (r, h.1))
  11116. .collect();
  11117. for ch in 0..4u8 {
  11118. let Some(value) = e.values[usize::from(ch)] else {
  11119. continue;
  11120. };
  11121. for high in [false, true] {
  11122. let h = 2 * ch + u8::from(high);
  11123. let src = if pack2 {
  11124. packed_half(outputs, &packs, row, h)
  11125. } else {
  11126. (!high).then_some((row, ch))
  11127. };
  11128. let found = src.and_then(|(r, c)| {
  11129. outputs.iter().position(|o| {
  11130. o.row == Some(u32::from(r)) && c >= o.col && c < o.col + o.cols
  11131. })
  11132. });
  11133. if let Some(id) = found {
  11134. let col = src.expect("found").1 - outputs[id].col;
  11135. stores.push((id, col, value, Some(high)));
  11136. }
  11137. }
  11138. }
  11139. }
  11140. for ch in 0..4u8 {
  11141. let Some(value) = e.values[usize::from(ch)] else {
  11142. continue;
  11143. };
  11144. if halves.is_some() {
  11145. break;
  11146. }
  11147. let found = match e.target {
  11148. Target::Color(n) => outputs
  11149. .iter()
  11150. .position(|o| o.kind == 16 && o.row == Some(u32::from(n)))
  11151. .map(|id| (id, ch)),
  11152. Target::Position(0) => by_kind(3).map(|id| (id, ch)),
  11153. Target::Depth => match ch {
  11154. 0 => by_kind(17)
  11155. .or(by_kind(18))
  11156. .or(by_kind(19))
  11157. .map(|id| (id, 0)),
  11158. 1 => by_kind(20).map(|id| (id, 0)),
  11159. 2 => by_kind(14).map(|id| (id, 0)),
  11160. _ => None,
  11161. },
  11162. Target::Param { usage, row } | Target::PrimitiveParam { usage, row } => {
  11163. let row = param_row(usage, row);
  11164. outputs
  11165. .iter()
  11166. .position(|o| {
  11167. row.is_some_and(|r| o.row == Some(u32::from(r)))
  11168. && ch >= o.col
  11169. && ch < o.col + o.cols
  11170. })
  11171. .map(|id| (id, ch - outputs[id].col))
  11172. }
  11173. Target::Null | Target::Unread => None,
  11174. Target::Position(n @ 1..=2) => {
  11175. // shortcut: without the misc vector (point size, render
  11176. // target or viewport index) pos1 and pos2 carry the clip
  11177. // then cull distances, in semantic order.
  11178. if outputs.iter().any(|o| matches!(o.kind, 4 | 5)) {
  11179. return Err("render-target or viewport index exports");
  11180. }
  11181. let mut dists: Vec<usize> = (0..outputs.len())
  11182. .filter(|&i| matches!(outputs[i].kind, 6 | 7))
  11183. .collect();
  11184. dists.sort_by_key(|&i| (outputs[i].kind, outputs[i].index));
  11185. let flat: Vec<(usize, u8)> = dists
  11186. .iter()
  11187. .flat_map(|&i| (0..outputs[i].cols).map(move |c| (i, c)))
  11188. .collect();
  11189. // Channels past the distances the signature declares are
  11190. // ones the clipper does not enable (`PA_CL_VS_OUT_CNTL`).
  11191. let k = usize::from(n - 1) * 4 + usize::from(ch);
  11192. flat.get(k).copied()
  11193. }
  11194. Target::Position(_) => return Err("clip, cull or point-size exports"),
  11195. Target::Primitive => return Err("a primitive export"),
  11196. };
  11197. if let Some((id, col)) = found {
  11198. stores.push((id, col, value, None));
  11199. }
  11200. }
  11201. fn elements<'l>(l: &'l mut Lower, primitive: bool) -> &'l mut Vec<SigElement> {
  11202. if primitive {
  11203. &mut l.s.prims
  11204. } else {
  11205. &mut l.s.outputs
  11206. }
  11207. }
  11208. if stores
  11209. .iter()
  11210. .any(|s| s.3.is_none() && elements(self, primitive)[s.0].half)
  11211. {
  11212. return Err("a 16-bit output the stage data does not mark");
  11213. }
  11214. // A mesh lane writes its own vertex or primitive, where it exports.
  11215. let at = if mesh {
  11216. let flat = self.mesh_thread();
  11217. let limit = if let Some(m) = self.s.mesh {
  11218. if primitive {
  11219. m.max_primitives
  11220. } else {
  11221. m.max_vertices
  11222. }
  11223. } else {
  11224. 0
  11225. };
  11226. let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX);
  11227. let mesh_guard = if limit > 0 && threads > limit {
  11228. let lim = self.s.m.i32(limit);
  11229. let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, lim);
  11230. match guard {
  11231. Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)),
  11232. None => Some(in_bounds),
  11233. }
  11234. } else {
  11235. guard
  11236. };
  11237. self.begin_guarded(mesh_guard)
  11238. } else {
  11239. None
  11240. };
  11241. let (name, opcode) = match (mesh, primitive) {
  11242. (false, _) => ("storeOutput", 5),
  11243. (true, false) => ("storeVertexOutput", 171),
  11244. (true, true) => ("storePrimitiveOutput", 172),
  11245. };
  11246. for (id, col, value, half) in stores {
  11247. let mut x = self.i32_of(value)?;
  11248. if let Some(high) = half {
  11249. // An f16 half, declared a 32-bit float on the host.
  11250. let c = self.cur;
  11251. if high {
  11252. let k16 = self.s.m.i32(16);
  11253. x = self.s.m.bin(c, Bin::LShr, x, k16);
  11254. }
  11255. let f32t = self.s.t.f32;
  11256. let f = self
  11257. .s
  11258. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
  11259. x = self.as_int(f);
  11260. }
  11261. let el = &mut elements(self, primitive)[id];
  11262. el.usage |= 1 << col;
  11263. let (suffix, x) = match el.comp {
  11264. 9 if half.is_some() => (".f32", self.as_float(x)),
  11265. 9 => {
  11266. let f = match self.floats.get(&value) {
  11267. Some(&f) => f,
  11268. None => self.as_float(x),
  11269. };
  11270. (".f32", f)
  11271. }
  11272. _ => (".i32", x),
  11273. };
  11274. let mut args = vec![
  11275. self.s.m.i32(id as u32),
  11276. self.s.m.i32(0),
  11277. self.s.m.i8(col),
  11278. x,
  11279. ];
  11280. if mesh {
  11281. args.push(self.mesh_thread());
  11282. }
  11283. let void = self.s.t.void;
  11284. self.s.op(
  11285. self.cur,
  11286. &format!("{name}{suffix}"),
  11287. Attr::NoUnwind,
  11288. void,
  11289. opcode,
  11290. &args,
  11291. );
  11292. }
  11293. self.end_guarded(at, &[]);
  11294. Ok(())
  11295. }
  11296. /// Mesh: `exp prim` as the lane's primitive. Each corner takes ten
  11297. /// bits: a 9-bit vertex index and, above it, its edge flag (bits 9, 19
  11298. /// and 29), which only the console's edge-flag rasterisation reads and
  11299. /// which is no part of the index. Bit 31 culls it (all indices 0: no
  11300. /// area).
  11301. fn emit_indices(&mut self, e: &Export, guard: Option<V>) -> Result<(), Why> {
  11302. let v = e.values[0].ok_or("a primitive export without its indices")?;
  11303. let x = self.i32_of(v)?;
  11304. let flat = self.mesh_thread();
  11305. let guard = if let Some(mesh) = self.s.mesh {
  11306. let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX);
  11307. if threads > mesh.max_primitives {
  11308. let p = self.s.m.i32(mesh.max_primitives);
  11309. let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, p);
  11310. match guard {
  11311. Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)),
  11312. None => Some(in_bounds),
  11313. }
  11314. } else {
  11315. guard
  11316. }
  11317. } else {
  11318. guard
  11319. };
  11320. let at = self.begin_guarded(guard);
  11321. let c = self.cur;
  11322. let z = self.s.m.i32(0);
  11323. let mut culled = self.s.m.cmp(c, pred::SLT, x, z);
  11324. // A primitive that names a vertex past the declared count, or one
  11325. // no lane writes (lane n writes vertex n alone), is culled too: the
  11326. // host would read a vertex nothing set, at any position.
  11327. let written = self.s.mesh.map(|m| {
  11328. m.max_vertices
  11329. .min(self.s.threads.map_or(u32::MAX, |t| t[0]))
  11330. });
  11331. let mut indices = [z; 3];
  11332. for (k, slot) in indices.iter_mut().enumerate() {
  11333. let (shift, mask) = (self.s.m.i32(10 * k as u32), self.s.m.i32(0x1FF));
  11334. let i = self.s.m.bin(c, Bin::LShr, x, shift);
  11335. let i = self.s.m.bin(c, Bin::And, i, mask);
  11336. if let Some(n) = written {
  11337. let n = self.s.m.i32(n);
  11338. let past = self.s.m.cmp(c, pred::IUGE, i, n);
  11339. culled = self.s.m.bin(c, Bin::Or, culled, past);
  11340. }
  11341. *slot = i;
  11342. }
  11343. let mut args = vec![flat];
  11344. for i in indices {
  11345. args.push(self.s.m.select(c, culled, z, i));
  11346. }
  11347. let void = self.s.t.void;
  11348. self.s
  11349. .op(c, "emitIndices", Attr::NoUnwind, void, 169, &args);
  11350. self.end_guarded(at, &[]);
  11351. Ok(())
  11352. }
  11353. /// The per-vertex arbitrary row no mesh output entry names but one
  11354. /// (the 2020 compiler's zeroed entry).
  11355. fn unnamed_row(&self) -> Option<u8> {
  11356. let StageIo::Ms(ms) = &self.x.native.io else {
  11357. return None;
  11358. };
  11359. let named = |r: u32| {
  11360. ms.outputs
  11361. .iter()
  11362. .any(|o| o.param & 0x80 == 0 && o.usage != Usage::Other(0) && u32::from(o.row) == r)
  11363. };
  11364. let free: std::collections::BTreeSet<u32> = self
  11365. .s
  11366. .outputs
  11367. .iter()
  11368. .filter(|o| o.kind == 0)
  11369. .filter_map(|o| o.row)
  11370. .filter(|&r| !named(r))
  11371. .collect();
  11372. match free.into_iter().collect::<Vec<_>>()[..] {
  11373. [r] => u8::try_from(r).ok(),
  11374. _ => None,
  11375. }
  11376. }
  11377. fn exit(&mut self, b: usize) -> Result<(), Stop> {
  11378. let offset = self.x.p.blocks[b]
  11379. .insts
  11380. .last()
  11381. .map_or(self.x.p.blocks[b].offset, |i| i.machine.offset);
  11382. let term = match self.x.st.exits[b] {
  11383. LaneExit::Jump(t) if self.counters.contains_key(&t) && self.rpo[t] <= self.rpo[b] => {
  11384. let ok = self.count_iteration(t, pred::IULT);
  11385. let abort = self.abort_block();
  11386. Term::CondBr(ok, self.block[t].expect("reachable"), abort)
  11387. }
  11388. LaneExit::Jump(t) => {
  11389. self.enter_loop(b, t, self.cur);
  11390. Term::Br(self.block[t].expect("reachable"))
  11391. }
  11392. LaneExit::Branch {
  11393. when,
  11394. taken,
  11395. not_taken,
  11396. } => {
  11397. // A negated condition branches the other way round.
  11398. let (cond, taken, not_taken) = match self.x.st.bools.node(when) {
  11399. _ if self.x.st.wide.contains(&b) => {
  11400. let c = self.wave_wide(b, when).map_err(|w| unsupported(offset, w))?;
  11401. (c, taken, not_taken)
  11402. }
  11403. Some((atom, Bool::TRUE, Bool::FALSE)) => {
  11404. let a = self
  11405. .atom(atom, self.cur)
  11406. .map_err(|w| unsupported(offset, w))?;
  11407. (a, not_taken, taken)
  11408. }
  11409. _ => {
  11410. let c = self
  11411. .boolean(when, self.cur)
  11412. .map_err(|w| unsupported(offset, w))?;
  11413. (c, taken, not_taken)
  11414. }
  11415. };
  11416. // A back edge is taken only below the iteration limit.
  11417. let back =
  11418. |l: &Self, to: usize| l.counters.contains_key(&to) && l.rpo[to] <= l.rpo[b];
  11419. // (No `xor` of a compare: a loop exit testing one hung the
  11420. // AMD driver.)
  11421. let cond = if back(self, taken) {
  11422. let ok = self.count_iteration(taken, pred::IULT);
  11423. self.s.m.bin(self.cur, Bin::And, cond, ok)
  11424. } else if back(self, not_taken) {
  11425. let stop = self.count_iteration(not_taken, pred::IUGE);
  11426. self.s.m.bin(self.cur, Bin::Or, cond, stop)
  11427. } else {
  11428. cond
  11429. };
  11430. // Critical edges get a block of their own, so loops have
  11431. // dedicated exits and preheaders as DXC emits them.
  11432. let (t, f) = (self.edge(b, taken), self.edge(b, not_taken));
  11433. for (to, via) in [(taken, t), (not_taken, f)] {
  11434. if !back(self, to) {
  11435. // From an edge block, or from here.
  11436. let from = if Some(via) == self.block[to] {
  11437. self.cur
  11438. } else {
  11439. via
  11440. };
  11441. self.enter_loop(b, to, from);
  11442. }
  11443. }
  11444. Term::CondBr(cond, t, f)
  11445. }
  11446. LaneExit::End => {
  11447. if self.s.pixel && !self.exported[b] && !self.has_done_export(b) {
  11448. // A lane leaving without its final export was killed.
  11449. let t = self.s.m.bool(true);
  11450. self.s
  11451. .op(self.cur, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]);
  11452. }
  11453. Term::Ret
  11454. }
  11455. LaneExit::Indirect => return Err(unsupported(offset, "an indirect jump")),
  11456. };
  11457. let _ = Exit::End;
  11458. self.s.m.terminate(self.cur, term);
  11459. Ok(())
  11460. }
  11461. /// A forward edge into loop header `to` (from DXIL block `via`) starts
  11462. /// its count at 0.
  11463. fn enter_loop(&mut self, _from: usize, to: usize, via: usize) {
  11464. if let Some((_, incoming)) = self.counters.get_mut(&to) {
  11465. let z = self.s.m.i32(0);
  11466. incoming.push((z, via));
  11467. }
  11468. }
  11469. /// A back edge to header `to` (a back edge keeps its block, no
  11470. /// critical-edge block): the count goes up; the result compares it with
  11471. /// [`LOOP_LIMIT`] by `p` (below: go on; at or above: stop).
  11472. fn count_iteration(&mut self, to: usize, p: u8) -> V {
  11473. let c = self.cur;
  11474. let (phi, _) = self.counters[&to];
  11475. let one = self.s.m.i32(1);
  11476. let next = self.s.m.bin(c, Bin::Add, phi, one);
  11477. self.s.m.tag(phi, Tag::Counter);
  11478. self.s.m.tag(next, Tag::Counter);
  11479. // Per stage unless the switch names one: a loop that never meets its
  11480. // exit (a count read from a buffer the host has not got yet, say)
  11481. // runs to the limit in every lane. A million iterations a pixel
  11482. // hung the GPU for seconds a draw until Windows reset it
  11483. // (PS_Textured_Eight, 2026-11-24, run 12).
  11484. // shortcut: a pixel loop past 128 iterations, a vertex or mesh loop
  11485. // past 256 or a compute loop past 4,096 is cut short. (They were
  11486. // 1,024, 4,096 and 65,536: the opening cutscene then lost the card
  11487. // 14-25 frames in, in a minimap or shadow mesh draw; with every
  11488. // loop cut at 64 it ran 90 frames. Raise them again once shaders
  11489. // stop reading data that is not there yet.)
  11490. let limit = match super::loop_limit() {
  11491. LOOP_LIMIT if self.s.pixel => 1 << 7,
  11492. LOOP_LIMIT if self.s.mesh.is_some() || self.s.threads.is_none() => 1 << 8,
  11493. LOOP_LIMIT => 1 << 12,
  11494. named => named,
  11495. };
  11496. let limit = self.s.m.i32(limit);
  11497. self.counters
  11498. .get_mut(&to)
  11499. .expect("header")
  11500. .1
  11501. .push((next, c));
  11502. let over = self.s.m.cmp(c, p, next, limit);
  11503. self.s.m.tag(over, Tag::Counter);
  11504. over
  11505. }
  11506. /// The block a lane stopped by [`LOOP_LIMIT`] leaves through.
  11507. fn abort_block(&mut self) -> usize {
  11508. if let Some(a) = self.abort {
  11509. return a;
  11510. }
  11511. let a = self.s.m.new_block();
  11512. if self.s.pixel {
  11513. let t = self.s.m.bool(true);
  11514. self.s
  11515. .op(a, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]);
  11516. }
  11517. self.s.m.terminate(a, Term::Ret);
  11518. self.abort = Some(a);
  11519. a
  11520. }
  11521. /// The DXIL block a branch from IR block `from` to `to` goes to.
  11522. fn edge(&mut self, from: usize, to: usize) -> usize {
  11523. let target = self.block[to].expect("reachable");
  11524. let preds = self.x.p.blocks[to]
  11525. .preds
  11526. .iter()
  11527. .filter(|&&q| self.block[q].is_some())
  11528. .count();
  11529. // Back edges stay as they are: the exiting block is the latch.
  11530. if preds < 2 || self.rpo[to] <= self.rpo[from] {
  11531. return target;
  11532. }
  11533. let e = self.s.m.new_block();
  11534. self.s.m.terminate(e, Term::Br(target));
  11535. self.edges.insert((from, to), e);
  11536. e
  11537. }
  11538. fn fill_phis(&mut self) -> Result<(), Stop> {
  11539. let p = self.x.p;
  11540. // Lane-mask joins first (what an edge brings may ask for more joins,
  11541. // of masks and of numbers): each edge's mask as the structure
  11542. // tracked it, a constant or a scalar-built one included.
  11543. let st = self.x.st;
  11544. while let Some((v, b, i)) = self.pending_masks.pop() {
  11545. let phi = &p.blocks[b].phis[i];
  11546. let offset = p.blocks[b].offset;
  11547. let args = st
  11548. .phi_masks
  11549. .get(&phi.value)
  11550. .ok_or_else(|| unsupported(offset, "a lane-mask join of an untracked mask"))?;
  11551. let mut incoming = Vec::new();
  11552. for (n, &q) in p.blocks[b].preds.iter().enumerate() {
  11553. let Some(qb) = self.tail[q] else { continue };
  11554. let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb);
  11555. let x = self.boolean(args[n], qb).map_err(|w| unsupported(offset, w))?;
  11556. incoming.push((x, qb));
  11557. }
  11558. self.s.m.set_phi(v, incoming);
  11559. }
  11560. // A join that only another join reads is read wherever that one is. Left
  11561. // unmarked, a value without a DXIL form coming into it became zero without a
  11562. // word (the looked-up tint of the material resolve programs, whose size
  11563. // computation had no value, was zero in every lane that way).
  11564. // shortcut: only with `VICTORY_STRICT_JOINS` set (the offline pack
  11565. // listing sets it to count them): 40 programs that translate today
  11566. // stop by name with it (vehicle paint pixel shaders at "the first
  11567. // half of an interpolation", foliage mesh shaders); until those are
  11568. // lowered they keep drawing with that zero.
  11569. static STRICT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  11570. let strict = *STRICT.get_or_init(|| std::env::var_os("VICTORY_STRICT_JOINS").is_some());
  11571. let mut work: Vec<Value> = if strict {
  11572. self.read_phis.iter().copied().collect()
  11573. } else {
  11574. Vec::new()
  11575. };
  11576. while let Some(v) = work.pop() {
  11577. let Some(&(b, i)) = self.phi_at.get(&v) else {
  11578. continue;
  11579. };
  11580. for &a in &p.blocks[b].phis[i].args {
  11581. if self.phi_at.contains_key(&a) && self.read_phis.insert(a) {
  11582. work.push(a);
  11583. }
  11584. }
  11585. }
  11586. for (v, b, i) in std::mem::take(&mut self.data_phis) {
  11587. let phi = &p.blocks[b].phis[i];
  11588. let bit = phi.reg == Reg::Scc;
  11589. // A join of numbers with dead registers (`dead`): the paths that bring those
  11590. // never read the result, so they bring zero. Not for a join that is itself a
  11591. // lane mask (a ballot gives that one as data).
  11592. let st = self.x.st;
  11593. let numbers = !bit
  11594. && !st.masks.contains_key(&phi.value)
  11595. && !st.highs.contains_key(&phi.value)
  11596. && phi
  11597. .args
  11598. .iter()
  11599. .any(|a| matches!(self.vals.get(a), Some(Val::I32(_))));
  11600. let mut incoming = Vec::new();
  11601. for (n, &q) in p.blocks[b].preds.iter().enumerate() {
  11602. let Some(qb) = self.tail[q] else { continue };
  11603. let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb);
  11604. let arg = phi.args[n];
  11605. if self.read_phis.contains(&phi.value) && !self.vals.contains_key(&arg) {
  11606. let _ = self.lazy_barycentric(arg);
  11607. // A root parameter nothing read before the join (user
  11608. // data is loaded on first use, in the entry block).
  11609. if !self.vals.contains_key(&arg)
  11610. && let Some(&(param, dword)) = self.params.get(&arg)
  11611. {
  11612. let val = self.user(param, dword);
  11613. self.vals.insert(arg, val);
  11614. }
  11615. }
  11616. let x = match (self.vals.get(&arg).copied(), bit) {
  11617. (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x,
  11618. (Some(Val::Missing(_)) | None, false)
  11619. if numbers && self.dead(arg, &mut Vec::new()) =>
  11620. {
  11621. self.s.m.i32(0)
  11622. }
  11623. // A lane mask joined with numbers (a traversal that keeps its lanes' masks on
  11624. // a stack with its node numbers): the mask comes as the number it is, the
  11625. // ballot of its lanes where it is written.
  11626. (Some(Val::Missing(_)) | None, false)
  11627. if self.read_phis.contains(&phi.value)
  11628. && self.mask_data == MaskData::Console
  11629. && (st.masks.contains_key(&arg) || st.highs.contains_key(&arg)) =>
  11630. {
  11631. match self.mask_dword(arg) {
  11632. Ok(x) => x,
  11633. Err(why) => return Err(Stop::Retry(phi.value, why)),
  11634. }
  11635. }
  11636. // SCC of a mask operation ("some lane is left") joined with a scalar test:
  11637. // the compiler branches around code that sets SCC and tests SCC after it,
  11638. // the skip bringing "no lane" along. As data it is "some lane of the wave
  11639. // has the bit" - right only if the wave took that skip together, as the
  11640. // console does: a lane that skipped alone would bring "some lane" where the
  11641. // console has the skipped code's SCC. So the branch must be one the wave
  11642. // takes together; else its region is named for `emit`'s retry to widen it.
  11643. (Some(Val::Missing(_)) | None, true)
  11644. if self.read_phis.contains(&phi.value)
  11645. && self.mask_data == MaskData::Console
  11646. && st.scc_some.contains_key(&arg) =>
  11647. {
  11648. let per_lane = !st.wide.contains(&q)
  11649. && matches!(st.exits[q], LaneExit::Branch { when, .. }
  11650. if !st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))));
  11651. if per_lane {
  11652. for &other in p.blocks[b].preds.iter().filter(|&&o| o != q) {
  11653. need(other);
  11654. }
  11655. return Err(Stop::Retry(phi.value, LANE_MASK));
  11656. }
  11657. match self.scc_some(arg) {
  11658. Ok(x) => x,
  11659. Err(why) => return Err(Stop::Retry(phi.value, why)),
  11660. }
  11661. }
  11662. (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => {
  11663. return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values"));
  11664. }
  11665. (Some(Val::Missing(why)), _) if self.read_phis.contains(&phi.value) => {
  11666. return Err(Stop::Retry(phi.value, why));
  11667. }
  11668. _ if self.read_phis.contains(&phi.value) => {
  11669. return Err(Stop::Retry(phi.value, "a join of mismatched values"));
  11670. }
  11671. _ if bit => self.s.m.bool(false),
  11672. _ => self.s.m.i32(0),
  11673. };
  11674. incoming.push((x, qb));
  11675. }
  11676. self.s.m.set_phi(v, incoming);
  11677. }
  11678. for (phi, incoming) in std::mem::take(&mut self.counters).into_values() {
  11679. self.s.m.set_phi(phi, incoming);
  11680. }
  11681. Ok(())
  11682. }
  11683. }
  11684. /// The DXIL interpolation mode of a kind of barycentrics (none for the
  11685. /// pull model).
  11686. fn interp_mode(kind: Barycentric) -> Option<u8> {
  11687. Some(match kind {
  11688. Barycentric::PerspectiveCenter => 2,
  11689. Barycentric::PerspectiveCentroid => 3,
  11690. Barycentric::PerspectiveSample => 6,
  11691. Barycentric::LinearCenter => 4,
  11692. Barycentric::LinearCentroid => 5,
  11693. Barycentric::LinearSample => 7,
  11694. Barycentric::PerspectivePullModel => return None,
  11695. })
  11696. }
  11697. #[cfg(test)]
  11698. mod tests {
  11699. use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower};
  11700. use crate::native::{
  11701. ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
  11702. };
  11703. use crate::{io, ir, resource, structure};
  11704. const S_ENDPGM: u32 = 0xBF81_0000;
  11705. #[test]
  11706. fn packed_pixel_inputs_find_their_second_row() {
  11707. use super::super::container::SigElement;
  11708. use super::half_input_partners;
  11709. use crate::native::{PsInput, Usage};
  11710. let entry = |row, row2, pack2| PsInput {
  11711. usage: Usage::Generic,
  11712. row,
  11713. mask: 0xF,
  11714. attr: row,
  11715. flat: false,
  11716. fp16: true,
  11717. pack2,
  11718. row2,
  11719. };
  11720. let element = |row| SigElement {
  11721. name: "TEXCOORD".into(),
  11722. index: row,
  11723. kind: 0,
  11724. comp: 9,
  11725. interp: 2,
  11726. row: Some(row),
  11727. col: 0,
  11728. cols: 4,
  11729. usage: 0,
  11730. half: true,
  11731. };
  11732. // Rows 0 and 3 pack and leave their second row out; 5 names its
  11733. // own (6). Unnamed 16-bit rows: 1, 4, 6, 7.
  11734. let io = StageIo::Ps {
  11735. inputs: vec![entry(0, 0, true), entry(3, 3, true), entry(5, 6, true)],
  11736. input_addr: 0,
  11737. db_shader_control: 0,
  11738. patches: vec![],
  11739. };
  11740. let sig: Vec<_> = [0, 1, 3, 4, 5, 6, 7].map(element).into();
  11741. let p = half_input_partners(&io, &sig);
  11742. assert_eq!(p.get(&0), Some(&1));
  11743. assert_eq!(p.get(&3), Some(&4));
  11744. assert_eq!(p.get(&5), None);
  11745. }
  11746. /// The packed pedestrian layouts of the title: an element
  11747. /// behind another one in its register follows in the first parameter
  11748. /// with a dword left, and is not a half of its register's row.
  11749. #[test]
  11750. fn packed_elements_behind_another_take_the_first_free_dword() {
  11751. use super::super::container::SigElement;
  11752. use super::packed_half;
  11753. let element = |index, row, col, cols| SigElement {
  11754. name: "TEXCOORD".into(),
  11755. index,
  11756. kind: 0,
  11757. comp: 9,
  11758. interp: 2,
  11759. row: Some(row),
  11760. col,
  11761. cols,
  11762. usage: 0,
  11763. half: true,
  11764. };
  11765. // MS_VS_PedTransformPreSkinD_Packed 005fe88ec1bdc0c7 and its pixel
  11766. // shader 93667197d3d05e1c: TEXCOORD6 is one value at register 4
  11767. // column 3; parameter 3 (rows 6 and 7) carries it in dword 3.
  11768. let sig = vec![
  11769. element(1, 2, 0, 4),
  11770. element(2, 3, 0, 4),
  11771. element(4, 4, 0, 3),
  11772. element(6, 4, 3, 1),
  11773. element(3, 5, 0, 4),
  11774. element(5, 6, 0, 4),
  11775. element(7, 7, 0, 2),
  11776. element(9, 9, 0, 3),
  11777. element(11, 10, 0, 3),
  11778. element(15, 12, 0, 4),
  11779. ];
  11780. let packs = [
  11781. (2, Some(3)),
  11782. (4, Some(5)),
  11783. (6, Some(7)),
  11784. (9, Some(10)),
  11785. (12, None),
  11786. ];
  11787. let at = |a, h| packed_half(&sig, &packs, a, h);
  11788. // Parameter 2: TEXCOORD4's three values, a zero half, TEXCOORD3.
  11789. assert_eq!(at(4, 2), Some((4, 2)));
  11790. assert_eq!(at(4, 3), None);
  11791. assert_eq!(at(4, 4), Some((5, 0)));
  11792. assert_eq!(at(4, 7), Some((5, 3)));
  11793. // Parameter 3: TEXCOORD5, TEXCOORD7, then TEXCOORD6 alone.
  11794. assert_eq!(at(6, 3), Some((6, 3)));
  11795. assert_eq!(at(6, 5), Some((7, 1)));
  11796. assert_eq!(at(6, 6), Some((4, 3)));
  11797. assert_eq!(at(6, 7), None);
  11798. // Parameters without such an element are as before.
  11799. assert_eq!(at(9, 3), None);
  11800. assert_eq!(at(9, 4), Some((10, 0)));
  11801. assert_eq!(at(12, 3), Some((12, 3)));
  11802. assert_eq!(at(12, 4), None);
  11803. // The common layout (29805d23a495cdf8): TEXCOORD7 is two values at
  11804. // register 1 columns 2-3; parameter 0 is TEXCOORD0, TEXCOORD1,
  11805. // TEXCOORD7.
  11806. let sig = vec![
  11807. element(0, 1, 0, 2),
  11808. element(7, 1, 2, 2),
  11809. element(1, 2, 0, 4),
  11810. element(2, 3, 0, 4),
  11811. element(4, 4, 0, 3),
  11812. ];
  11813. let packs = [(3, Some(4)), (1, Some(2))];
  11814. let at = |a, h| packed_half(&sig, &packs, a, h);
  11815. assert_eq!(at(1, 1), Some((1, 1)));
  11816. assert_eq!(at(1, 2), Some((2, 0)));
  11817. assert_eq!(at(1, 5), Some((2, 3)));
  11818. assert_eq!(at(1, 6), Some((1, 2)));
  11819. assert_eq!(at(1, 7), Some((1, 3)));
  11820. assert_eq!(at(3, 6), Some((4, 2)));
  11821. assert_eq!(at(3, 7), None);
  11822. // A row no element holds gives nothing, as before.
  11823. assert_eq!(packed_half(&sig, &[(8, None)], 8, 0), None);
  11824. }
  11825. /// Whether a synthetic compute program translates with these input registers.
  11826. fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> {
  11827. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  11828. let native = NativeProgram {
  11829. stage: HwStage::Cs,
  11830. wave64: false,
  11831. vgprs: 256,
  11832. layout: vec![],
  11833. used: vec![],
  11834. io: StageIo::Cs(ComputeIo {
  11835. rsrc2,
  11836. threads: [1, 1, 1],
  11837. }),
  11838. code,
  11839. };
  11840. let p = ir::build(&native.code, false, 256).unwrap();
  11841. let st = structure::structure(&p).unwrap();
  11842. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  11843. let io = io::raise(&p, &native).unwrap();
  11844. lower(&Parts {
  11845. native: &native,
  11846. p: &p,
  11847. st: &st,
  11848. io: &io,
  11849. res: &res,
  11850. inputs: vec![],
  11851. outputs: vec![],
  11852. prims: vec![],
  11853. mesh_stride: 0,
  11854. })
  11855. .map(|_| ())
  11856. }
  11857. /// Lowers a compute program with the root parameters `layout` (in user
  11858. /// SGPRs from s0 on) and the used resources `used`.
  11859. fn lower_with(
  11860. words: &[u32],
  11861. layout: Vec<RootParam>,
  11862. used: Vec<UsedResource>,
  11863. ) -> Result<Lowered, crate::ShaderError> {
  11864. lower_wave(words, layout, used, false)
  11865. }
  11866. /// [`lower_with`] in wave64 if `wave64`.
  11867. fn lower_wave(
  11868. words: &[u32],
  11869. layout: Vec<RootParam>,
  11870. used: Vec<UsedResource>,
  11871. wave64: bool,
  11872. ) -> Result<Lowered, crate::ShaderError> {
  11873. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  11874. let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum();
  11875. let native = NativeProgram {
  11876. stage: HwStage::Cs,
  11877. wave64,
  11878. vgprs: 256,
  11879. layout,
  11880. used,
  11881. io: StageIo::Cs(ComputeIo {
  11882. // The layout's user SGPRs (at least two), 512 bytes of LDS.
  11883. rsrc2: 1 << 15 | sgprs.max(2) << 1,
  11884. threads: [1, 1, 1],
  11885. }),
  11886. code,
  11887. };
  11888. let p = ir::build(&native.code, wave64, 256).unwrap();
  11889. let st = structure::structure(&p).unwrap();
  11890. let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
  11891. let io = io::raise(&p, &native).unwrap();
  11892. lower(&Parts {
  11893. native: &native,
  11894. p: &p,
  11895. st: &st,
  11896. io: &io,
  11897. res: &res,
  11898. inputs: vec![],
  11899. outputs: vec![],
  11900. prims: vec![],
  11901. mesh_stride: 0,
  11902. })
  11903. }
  11904. /// Root parameter `slot` in user SGPRs from `user_data` on.
  11905. fn root(root: RootType, user_data: u8, slot: u8) -> RootParam {
  11906. RootParam {
  11907. root,
  11908. table_offset_dwords: 0,
  11909. sgprs: if root == RootType::Descriptor { 2 } else { 1 },
  11910. base_register: 0,
  11911. user_data,
  11912. slot,
  11913. }
  11914. }
  11915. /// Lowers a one-thread compute program that copies four root constants
  11916. /// (s0..s3) into v1..v4, runs `body`, and stores v0 to a raw buffer from a
  11917. /// descriptor table, so the vector instructions in `body` have an effect.
  11918. fn lowers_valu(body: &[u32]) -> Result<(), crate::ShaderError> {
  11919. let mut words = vec![
  11920. 0xBE85_0380, // s_mov_b32 s5, 0
  11921. 0xF408_0202, // s_load_dwordx4 s[8:11], s[4:5], 0
  11922. 0xFA00_0000,
  11923. ];
  11924. // v_mov_b32 v1..v4, s0..s3
  11925. words.extend((0..4u32).map(|i| 0x7E00_0200 | (i + 1) << 17 | i));
  11926. words.extend_from_slice(body);
  11927. words.extend_from_slice(&[
  11928. 0xE070_0000, // buffer_store_dword v0, off, s[8:11], 0
  11929. 0x8002_0000,
  11930. S_ENDPGM,
  11931. ]);
  11932. let constants = RootParam {
  11933. sgprs: 4,
  11934. ..root(RootType::Constants, 0, 0)
  11935. };
  11936. let buffer = UsedResource {
  11937. kind: ResourceType::Uav,
  11938. root: RootType::Table,
  11939. table_offset_dwords: 0,
  11940. lower_bound: 0,
  11941. stride: 0,
  11942. dwords: 4,
  11943. user_data: 4,
  11944. slot: 1,
  11945. };
  11946. lower_with(
  11947. &words,
  11948. vec![constants, root(RootType::Table, 4, 1)],
  11949. vec![buffer],
  11950. )
  11951. .map(|_| ())
  11952. }
  11953. #[test]
  11954. fn the_24_bit_multiplies_lower_both_halves() {
  11955. // VOP2 `op v0, v1, v2`: v_mul_i32_i24 and v_mul_u32_u24 (the low
  11956. // dword) and v_mul_hi_i32_i24 and v_mul_hi_u32_u24 (the high one).
  11957. for op in [0x09u32, 0x0A, 0x0B, 0x0C] {
  11958. let word = op << 25 | 2 << 9 | 0x101;
  11959. lowers_valu(&[word]).unwrap_or_else(|e| panic!("VOP2 {op:#x}: {e}"));
  11960. }
  11961. }
  11962. #[test]
  11963. fn buffer_cache_invalidations_lower_as_no_ops() {
  11964. // MUBUF opcode 0x071/0x072 with no data operand: the title asks the
  11965. // host to invalidate its cached view of a buffer.
  11966. assert!(lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl0_inv");
  11967. assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv");
  11968. }
  11969. #[test]
  11970. fn sums_of_absolute_differences_lower() {
  11971. // VOP3 `op v0, v1, v2, v3`: v_sad_u8, v_sad_hi_u8, v_sad_u16,
  11972. // v_sad_u32 and v_msad_u8.
  11973. for op in [0x15Au32, 0x15B, 0x15C, 0x15D, 0x171] {
  11974. let words = [0xD400_0000 | op << 16, 0x101 | 0x102 << 9 | 0x103 << 18];
  11975. lowers_valu(&words).unwrap_or_else(|e| panic!("VOP3 {op:#x}: {e}"));
  11976. }
  11977. }
  11978. #[test]
  11979. fn a_scalar_carry_chain_reaches_the_select() {
  11980. // The high dword of a 64-bit add or subtract, then a select on the
  11981. // carry (borrow) the high half leaves in SCC, and a branch on it
  11982. // (only code with an effect needs its operands).
  11983. let add = [
  11984. 0xBE80_03C1, // s_mov_b32 s0, -1
  11985. 0xBE81_0380, // s_mov_b32 s1, 0
  11986. 0x8000_8100, // s_add_u32 s0, s0, 1
  11987. 0x8201_8001, // s_addc_u32 s1, s1, 0
  11988. 0x8502_0001, // s_cselect_b32 s2, s1, s0
  11989. 0xBF07_8002, // s_cmp_lg_u32 s2, 0
  11990. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  11991. 0xBE83_0380, // s_mov_b32 s3, 0
  11992. S_ENDPGM,
  11993. ];
  11994. let sub = [
  11995. 0xBE80_0380, // s_mov_b32 s0, 0
  11996. 0xBE81_0380, // s_mov_b32 s1, 0
  11997. 0x8080_8100, // s_sub_u32 s0, s0, 1
  11998. 0x8281_8001, // s_subb_u32 s1, s1, 0
  11999. 0x8502_0001, // s_cselect_b32 s2, s1, s0
  12000. 0xBF07_8002, // s_cmp_lg_u32 s2, 0
  12001. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  12002. 0xBE83_0380, // s_mov_b32 s3, 0
  12003. S_ENDPGM,
  12004. ];
  12005. for words in [add, sub] {
  12006. lowers(&words, 0).unwrap();
  12007. }
  12008. }
  12009. fn perm_features(selector: u32) -> u64 {
  12010. // Synthetic compute shader:
  12011. // v0 is the thread ID and can supply a dynamic selector.
  12012. // Store the result in LDS to keep the permutation live.
  12013. let words = [
  12014. 0x7E02_02FFu32,
  12015. 0x817F_34AB,
  12016. 0x7E04_02FF,
  12017. 0xFE01_56CD,
  12018. 0xD744_0003,
  12019. 257 | (258 << 9) | (selector << 18),
  12020. 0x3408_0082,
  12021. 0xD834_0000,
  12022. 0x0000_0304,
  12023. S_ENDPGM,
  12024. ];
  12025. let code: Vec<u8> = words.iter()
  12026. .flat_map(|w| w.to_le_bytes())
  12027. .collect();
  12028. let native = NativeProgram {
  12029. stage: HwStage::Cs,
  12030. wave64: false,
  12031. vgprs: 256,
  12032. layout: vec![],
  12033. used: vec![],
  12034. io: StageIo::Cs(ComputeIo {
  12035. rsrc2: 1 << 15,
  12036. threads: [64, 1, 1],
  12037. }),
  12038. code,
  12039. };
  12040. let p = ir::build(&native.code, false, 256).unwrap();
  12041. assert!(p.blocks.iter()
  12042. .flat_map(|b| &b.insts)
  12043. .any(|i| i.name() == "v_perm_b32"));
  12044. let st = structure::structure(&p).unwrap();
  12045. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  12046. let io = io::raise(&p, &native).unwrap();
  12047. let emitted = lower(&Parts {
  12048. native: &native,
  12049. p: &p,
  12050. st: &st,
  12051. io: &io,
  12052. res: &res,
  12053. inputs: vec![],
  12054. outputs: vec![],
  12055. prims: vec![],
  12056. mesh_stride: 0,
  12057. }).unwrap();
  12058. let container =
  12059. crate::Container::parse(&emitted.dxil).unwrap();
  12060. let features =
  12061. container.part(crate::FourCC::SFI0).unwrap();
  12062. u64::from_le_bytes(features.data.try_into().unwrap())
  12063. }
  12064. #[test]
  12065. fn perm_constant_selector_needs_no_int64() {
  12066. assert_eq!(perm_features(128) & 0x8000, 0);
  12067. }
  12068. #[test]
  12069. fn perm_dynamic_selector_needs_no_int64() {
  12070. assert_eq!(
  12071. perm_features(256) & 0x8000,
  12072. 0,
  12073. "dynamic v_perm_b32 must not require INT64"
  12074. );
  12075. }
  12076. #[test]
  12077. fn a_descriptor_selected_by_scc_picks_its_heap_index() {
  12078. // Two buffer descriptors loaded from the table at s0, one picked by
  12079. // a root constant (s1) with s_cselect_b64 per half, and loaded
  12080. // through by index and stored to LDS so the load is needed.
  12081. let words = [
  12082. 0xBE84_0300, // s_mov_b32 s4, s0
  12083. 0xBE85_0380, // s_mov_b32 s5, 0
  12084. 0xF408_0202,
  12085. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null
  12086. 0xF408_0302,
  12087. 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10
  12088. 0xBF06_8001, // s_cmp_eq_u32 s1, 0
  12089. 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13]
  12090. 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15]
  12091. 0xE030_2000,
  12092. 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen
  12093. 0xD834_0000,
  12094. 0x0000_0100, // ds_write_b32 v0, v1
  12095. S_ENDPGM,
  12096. ];
  12097. let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)];
  12098. // Both are structured buffers of dwords in the table's range.
  12099. let used = || {
  12100. vec![UsedResource {
  12101. kind: ResourceType::Srv,
  12102. root: RootType::Table,
  12103. table_offset_dwords: 0,
  12104. lower_bound: 0,
  12105. stride: 4,
  12106. dwords: 4,
  12107. user_data: 0,
  12108. slot: 0,
  12109. }]
  12110. };
  12111. lower_with(&words, layout(), used()).unwrap();
  12112. }
  12113. /// Tables of 2D textures at s0 and samplers at s1.
  12114. fn texture_tables() -> (Vec<RootParam>, Vec<UsedResource>) {
  12115. let range = |kind, user_data, slot| UsedResource {
  12116. kind,
  12117. root: RootType::Table,
  12118. table_offset_dwords: 0,
  12119. lower_bound: 0,
  12120. stride: 0,
  12121. dwords: if kind == ResourceType::Sampler { 4 } else { 8 },
  12122. user_data,
  12123. slot,
  12124. };
  12125. (
  12126. vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)],
  12127. vec![
  12128. range(ResourceType::Srv, 0, 0),
  12129. range(ResourceType::Sampler, 1, 1),
  12130. ],
  12131. )
  12132. }
  12133. #[test]
  12134. fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() {
  12135. use crate::resource::tests::{
  12136. WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32,
  12137. };
  12138. for (words, wave64) in [
  12139. (WATERFALL_FETCHED_WAVE32, false),
  12140. (WATERFALL_FETCHED_WAVE64, true),
  12141. (WATERFALL_PICKED_WAVE32, false),
  12142. ] {
  12143. let (layout, used) = texture_tables();
  12144. let l = lower_wave(words, layout, used, wave64).unwrap();
  12145. // The loop's reads of the first lane became each lane's own
  12146. // dwords: no wave operation is left.
  12147. assert_eq!(l.nonuniform_handles, 1);
  12148. assert!(!l.wave_ops);
  12149. }
  12150. }
  12151. /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first.
  12152. pub(crate) fn texture_and_uav_tables() -> (Vec<RootParam>, Vec<UsedResource>) {
  12153. let (layout, mut used) = texture_tables();
  12154. used.push(UsedResource {
  12155. kind: ResourceType::Uav,
  12156. root: RootType::Table,
  12157. table_offset_dwords: 16,
  12158. lower_bound: 0,
  12159. stride: 0,
  12160. dwords: 4,
  12161. user_data: 0,
  12162. slot: 0,
  12163. });
  12164. (layout, used)
  12165. }
  12166. #[test]
  12167. fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() {
  12168. use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32};
  12169. for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] {
  12170. let (layout, used) = texture_and_uav_tables();
  12171. let l = lower_wave(words, layout, used, false).unwrap();
  12172. // One image handle, from the join's per-lane heap index.
  12173. assert_eq!(l.nonuniform_handles, 1);
  12174. assert!(!l.wave_ops);
  12175. }
  12176. }
  12177. #[test]
  12178. fn scalar_bit_tests_lower() {
  12179. // Each tests one bit of a constant into SCC and branches on it (only
  12180. // code with an effect needs its operands).
  12181. let tail = [
  12182. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  12183. 0xBE84_0380, // s_mov_b32 s4, 0
  12184. S_ENDPGM,
  12185. ];
  12186. let bit_tests: [&[u32]; 4] = [
  12187. &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3
  12188. &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3
  12189. &[
  12190. 0xBE80_0387, // s_mov_b32 s0, 7
  12191. 0xBE81_0380, // s_mov_b32 s1, 0
  12192. 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3
  12193. ],
  12194. &[
  12195. 0xBE80_0387, // s_mov_b32 s0, 7
  12196. 0xBE81_0380, // s_mov_b32 s1, 0
  12197. 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3
  12198. ],
  12199. ];
  12200. for head in bit_tests {
  12201. let words: Vec<u32> = head.iter().chain(&tail).copied().collect();
  12202. lowers(&words, 0).unwrap();
  12203. }
  12204. }
  12205. #[test]
  12206. #[ignore = "ours marks joins read through joins only with VICTORY_STRICT_JOINS (40 programs stop otherwise)"]
  12207. fn a_missing_value_stays_missing_through_two_live_joins() {
  12208. let mut words = [
  12209. 0xF490_0180,
  12210. 0, // s_memtime s[6:7]
  12211. 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X)
  12212. 0xBF85_0001, // skip the first overwrite
  12213. 0xBE86_0380, // s_mov_b32 s6, 0
  12214. 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y)
  12215. 0xBF85_0001, // skip the second overwrite
  12216. 0xBE86_0381, // s_mov_b32 s6, 1
  12217. 0xBF07_8006, // s_cmp_lg_u32 s6, 0
  12218. 0xBF85_0001, // use the result to branch
  12219. 0xBE83_0380,
  12220. S_ENDPGM,
  12221. ];
  12222. let group_ids_xy = 3 << 7;
  12223. // Compare to a direct read so future timestamp support works in both cases.
  12224. let refusal = |code: &[u32]| match lowers(code, group_ids_xy) {
  12225. Ok(()) => None,
  12226. Err(crate::ShaderError::Unsupported { what, .. }) => Some(what),
  12227. Err(error) => panic!("{error}"),
  12228. };
  12229. let direct = [&words[..2], &words[8..]].concat();
  12230. assert_eq!(refusal(&words), refusal(&direct));
  12231. words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead
  12232. lowers(&words, group_ids_xy).expect("dead timestamp");
  12233. }
  12234. #[test]
  12235. fn buffer_formats_by_number() {
  12236. // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM,
  12237. // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT.
  12238. assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm)));
  12239. assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm)));
  12240. assert_eq!(
  12241. buffer_format(50),
  12242. Some((&[10, 10, 10, 2][..], Numeric::Unorm))
  12243. );
  12244. assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float)));
  12245. assert_eq!(
  12246. buffer_format(77),
  12247. Some((&[32, 32, 32, 32][..], Numeric::Float))
  12248. );
  12249. // Invalid, past the table.
  12250. assert_eq!(buffer_format(0), None);
  12251. assert_eq!(buffer_format(78), None);
  12252. }
  12253. #[test]
  12254. fn packed_buffer_formats_by_number() {
  12255. // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43,
  12256. // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT
  12257. // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first.
  12258. assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm)));
  12259. assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float)));
  12260. assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm)));
  12261. assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float)));
  12262. assert_eq!(
  12263. buffer_format(44),
  12264. Some((&[2, 10, 10, 10][..], Numeric::Unorm))
  12265. );
  12266. assert_eq!(
  12267. buffer_format(45),
  12268. Some((&[2, 10, 10, 10][..], Numeric::Snorm))
  12269. );
  12270. assert_eq!(
  12271. buffer_format(46),
  12272. Some((&[2, 10, 10, 10][..], Numeric::Uscaled))
  12273. );
  12274. assert_eq!(
  12275. buffer_format(47),
  12276. Some((&[2, 10, 10, 10][..], Numeric::Sscaled))
  12277. );
  12278. assert_eq!(
  12279. buffer_format(48),
  12280. Some((&[2, 10, 10, 10][..], Numeric::Uint))
  12281. );
  12282. assert_eq!(
  12283. buffer_format(49),
  12284. Some((&[2, 10, 10, 10][..], Numeric::Sint))
  12285. );
  12286. }
  12287. /// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as
  12288. /// `legacyF16ToF32` widens it.
  12289. fn half(h: u32) -> f32 {
  12290. let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023);
  12291. let v = match e {
  12292. 0 => m as f32 * 2f32.powi(-24),
  12293. 31 if m == 0 => f32::INFINITY,
  12294. 31 => f32::NAN,
  12295. _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25),
  12296. };
  12297. if s == 1 { -v } else { v }
  12298. }
  12299. #[test]
  12300. fn small_floats_widen_as_halves() {
  12301. // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a
  12302. // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec.
  12303. let f11 = |x: u32| half(x << half_shift(11));
  12304. let f10 = |x: u32| half(x << half_shift(10));
  12305. assert_eq!(f11(0), 0.0);
  12306. assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal
  12307. assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal
  12308. assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal
  12309. assert_eq!(f11(0x3C0), 1.0);
  12310. assert_eq!(f11(0x3E0), 1.5);
  12311. assert_eq!(f11(0x7BF), 65024.0); // largest
  12312. assert_eq!(f11(0x7C0), f32::INFINITY);
  12313. assert!(f11(0x7C1).is_nan());
  12314. assert_eq!(f10(0x001), 2f32.powi(-19));
  12315. assert_eq!(f10(0x020), 2f32.powi(-14));
  12316. assert_eq!(f10(0x1E0), 1.0);
  12317. assert_eq!(f10(0x3DF), 64512.0);
  12318. assert_eq!(f10(0x3E0), f32::INFINITY);
  12319. assert!(f10(0x3FF).is_nan());
  12320. // A 16-bit float is a half already, sign included.
  12321. assert_eq!(half(0xBC00 << half_shift(16)), -1.0);
  12322. }
  12323. }