2
0

lower.rs 486 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569
  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, 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 used for comparisons.
  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. /// The f16 bits of inline float constant `c` (240..=248: 0.5, -0.5, 1.0,
  100. /// -1.0, 2.0, -2.0, 4.0, -4.0, 1/(2 pi)).
  101. fn inline_f16(c: u8) -> u32 {
  102. [
  103. 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118,
  104. ][usize::from(c - 240)]
  105. }
  106. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  107. enum Numeric {
  108. Unorm,
  109. Snorm,
  110. Uscaled,
  111. Sscaled,
  112. Uint,
  113. Sint,
  114. Float,
  115. }
  116. /// A GFX10 buffer format (the unified format of typed buffer loads): the
  117. /// channel widths from the lowest bits up, and how the channels convert.
  118. /// Formats are numbered in families (`8`, `16`, `8_8`, ...: AMD names
  119. /// list channels from the highest bits), each with its numeric formats in
  120. /// the order unorm, snorm, uscaled, sscaled, uint, sint, float.
  121. fn buffer_format(format: u8) -> Option<(&'static [u32], Numeric)> {
  122. use Numeric::*;
  123. const NORM: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint];
  124. const ALL: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint, Float];
  125. const WIDE: &[Numeric] = &[Uint, Sint, Float];
  126. // Numbers and order from LLVM's `UfmtGFX10` (`SIDefines.h`); the GFX10
  127. // buffer formats have no 5_9_9_9. Channel order from Mesa
  128. // (`ac_formats.c`): R11G11B10_FLOAT is 10_11_11, and 10_10_10_2 has
  129. // its 2-bit channel in the lowest bits.
  130. const FAMILIES: [(&[u32], &[Numeric]); 14] = [
  131. (&[8], NORM),
  132. (&[16], ALL),
  133. (&[8, 8], NORM),
  134. (&[32], WIDE),
  135. (&[16, 16], ALL),
  136. (&[11, 11, 10], ALL), // 10_11_11
  137. (&[10, 11, 11], ALL), // 11_11_10
  138. (&[2, 10, 10, 10], NORM), // 10_10_10_2
  139. (&[10, 10, 10, 2], NORM), // 2_10_10_10
  140. (&[8, 8, 8, 8], NORM),
  141. (&[32, 32], WIDE),
  142. (&[16, 16, 16, 16], ALL),
  143. (&[32, 32, 32], WIDE),
  144. (&[32, 32, 32, 32], WIDE),
  145. ];
  146. let mut n = usize::from(format.checked_sub(1)?);
  147. for (bits, numerics) in FAMILIES {
  148. if n < numerics.len() {
  149. return Some((bits, numerics[n]));
  150. }
  151. n -= numerics.len();
  152. }
  153. None
  154. }
  155. /// How far a float channel of `width` bits (16, or the unsigned 11- and
  156. /// 10-bit floats of the packed formats) shifts up to be a half:
  157. /// the small floats are a half's exponent (5 bits, biased 15) and the top
  158. /// of its mantissa, without the sign, so `legacyF16ToF32` widens them
  159. /// exactly, denormals, infinities and NaNs included.
  160. fn half_shift(width: u32) -> u32 {
  161. debug_assert!(matches!(width, 10 | 11 | 16), "{width}-bit float");
  162. if width == 16 { 0 } else { 15 - width }
  163. }
  164. struct Lower<'a> {
  165. s: Shader,
  166. x: &'a Parts<'a>,
  167. bad: &'a HashMap<Value, Why>,
  168. lane_fail: HashMap<Value, Why>,
  169. vals: HashMap<Value, Val>,
  170. floats: HashMap<Value, V>,
  171. /// DXIL block per IR block (unreachable: none).
  172. block: Vec<Option<usize>>,
  173. cur: usize,
  174. bools: HashMap<(usize, Bool), V>,
  175. lane_bits: HashMap<Value, V>,
  176. /// IR phi location by value.
  177. phi_at: HashMap<Value, (usize, usize)>,
  178. /// Descriptor dwords with no host value (addresses, formats, all of a constant
  179. /// buffer's): no program reads them as numbers ([`Self::dead`]).
  180. stale: HashSet<Value>,
  181. mask_phis: HashMap<Value, V>,
  182. pending_masks: Vec<(V, usize, usize)>,
  183. data_phis: Vec<(V, usize, usize)>,
  184. read_phis: HashSet<Value>,
  185. params: HashMap<Value, (usize, u32)>,
  186. user_data: Option<V>,
  187. user_reads: BTreeMap<u32, UserData>,
  188. samplers: Vec<[u32; 4]>,
  189. descriptors: HashMap<(Site, bool), &'a Source>,
  190. scalar: HashMap<Site, Address>,
  191. exports: HashMap<Site, &'a Export>,
  192. interps: HashMap<Site, &'a Interp>,
  193. handles: HashMap<(usize, Site, u8, bool, (u32, u32)), V>,
  194. /// Element strides read from the host's table by heap slot
  195. /// ([`super::shader::SLOT_STRIDES`]), by block and descriptor load.
  196. strides: HashMap<(usize, Site, u8), V>,
  197. /// Blocks splitting the edge from one IR block to another.
  198. edges: HashMap<(usize, usize), usize>,
  199. /// Per IR block: a `done` export is behind every lane entering it.
  200. exported: Vec<bool>,
  201. /// Reverse-postorder index per IR block.
  202. rpo: Vec<usize>,
  203. /// DXIL block each IR block ends in (guarded stores split blocks).
  204. tail: Vec<Option<usize>>,
  205. /// The program writes UAVs: barriers fence them too.
  206. writes_uavs: bool,
  207. /// src0 of the current instruction as DPP fetched it.
  208. src0: Option<V>,
  209. /// Compute code that reads other lanes: thread ids follow the host
  210. /// lanes, so lane n is console lane n.
  211. console_lanes: bool,
  212. /// Mesh: the thread index in the group (made in the entry block).
  213. flat: Option<V>,
  214. /// Mesh: IR blocks whose `s_barrier` is left out.
  215. no_barrier: HashSet<usize>,
  216. /// IR blocks whose `s_barrier` not every lane is sure to reach (a lane
  217. /// branch lies between the entry and the block, or the program has a
  218. /// loop a lane can be cut out of): the barrier there keeps its fences
  219. /// and does not wait for the group ([`super::group_sync`]).
  220. fence_only: HashSet<usize>,
  221. /// A group barrier before every LDS access (a console wave run as two host waves).
  222. split_lds: bool,
  223. /// With `split_lds`, LDS accesses in lane branches: per IR block whether every lane runs
  224. /// it, and whether the host waves meet at its start and before its exit ([`lds_meetings`]).
  225. lds_meet: Option<(Vec<bool>, Vec<(bool, bool)>)>,
  226. /// A console wave64 program run as two host waves of 32 that exchange through LDS: the first
  227. /// of two exchange dwords, whether the group has no upper half (32 threads or fewer), and per
  228. /// IR block whether every lane runs it (exchanges need both halves there).
  229. exchange: Option<(u32, bool, Vec<bool>)>,
  230. /// With `exchange`: nothing is exchanged, each host wave acts as a wave
  231. /// of its own ([`with_local_waves`]).
  232. local: bool,
  233. /// The instruction being lowered may read a lane mask as a number under
  234. /// `local` (a bit count, a first set bit, `v_mbcnt`).
  235. local_ok: bool,
  236. /// With `local`: every mask read and lane read is taken per host wave
  237. /// ([`with_local_waves_any`]).
  238. local_any: bool,
  239. /// With `exchange`: VGPR values every lane holds alike ([`lane_uniform`]); a first-lane
  240. /// read of one needs nothing from the other host wave.
  241. uniform: HashSet<Value>,
  242. /// With `exchange`: the wave ORs that only steer a loop over each lane's own bits, which
  243. /// a host wave takes over its own lanes wherever they stand ([`super::own_bits`]).
  244. own_bits: super::own_bits::OwnBits,
  245. /// The console lane (0..63) of this thread, made in the entry block.
  246. clane: Option<V>,
  247. /// The first exchange dword of this thread's console wave ([`Self::exchange_pair`]).
  248. pair: Option<V>,
  249. /// A console wave64 program in host waves of 32: the LDS dword counting the console threads
  250. /// handed to host waves (`wave_base`), and the base made in the entry block.
  251. halves: Option<u32>,
  252. wave_base: Option<V>,
  253. /// Vertex and mesh outputs holding 16-bit values: row, whether two per
  254. /// dword, and the row packed after it.
  255. half_outputs: HashMap<u8, (bool, Option<u8>)>,
  256. /// How lane masks become data.
  257. mask_data: MaskData,
  258. /// The instruction being lowered may read lane masks as data.
  259. mask_ok: bool,
  260. /// Ballots of masks read as data, by low dword: (low, high).
  261. ballots: HashMap<Value, (V, V)>,
  262. /// Masks whose ballot is being built: a mask whose lane bit needs its
  263. /// own value as a number (an opaque mask keyed by a dword it shares
  264. /// with another) would otherwise recurse until the stack overflows.
  265. balloting: HashSet<Value>,
  266. /// Block writing each value.
  267. def_block: HashMap<Value, usize>,
  268. /// IR block being lowered.
  269. cur_ir: usize,
  270. /// Whole-wave sections by block and start index.
  271. sections: HashMap<usize, HashMap<usize, super::wave::Section>>,
  272. /// Values written in a section that code outside it reads.
  273. section_out: HashSet<Value>,
  274. /// The program's constant table (the code from the first byte read
  275. /// through `s_getpc_b64` on): global, first byte, dwords.
  276. code_table: Option<(V, u32, u32)>,
  277. /// Loop headers' iteration counters (see [`LOOP_LIMIT`]): the phi by
  278. /// IR block, and its incoming (value, DXIL block) pairs.
  279. counters: HashMap<usize, (V, Vec<(V, usize)>)>,
  280. /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from.
  281. abort: Option<usize>,
  282. }
  283. /// Iterations after which a loop is left (per entry into it), unless
  284. /// [`super::loop_limit`] says otherwise. The console runs a loop as long as
  285. /// its data says; data the host has not mirrored yet (a null view reads
  286. /// zeros) can make that four billion iterations, which hangs the host GPU
  287. /// until the driver resets it. A lane that reaches the limit leaves the
  288. /// program as killed (a pixel discards).
  289. // shortcut: a genuine loop of more iterations than this is cut short too.
  290. pub(super) const LOOP_LIMIT: u32 = 1 << 20;
  291. /// Lane masks read as numbers (`s_bcnt1`, `s_ff1`, `v_mbcnt`, scalar
  292. /// compares, bit tests) are ballots of the lanes' booleans, taken where the
  293. /// mask is written: structurisation's `active` masks hold only lanes that
  294. /// reach that block, so the ballot misses none.
  295. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  296. enum MaskData {
  297. /// Compute: host lane n is console lane n (the program declares the
  298. /// console's wave size), so ballots are the console's masks bit for bit
  299. /// and any use is exact.
  300. Console,
  301. /// Pixel and vertex programs: ballots over the host's wave, whatever its
  302. /// size. Only uses that mean the same on any wave are allowed: counts,
  303. /// the first lane, the count below a lane, equality (the HLSL wave
  304. /// operations the console compiler expands). Lane numbers stay host
  305. /// lanes throughout (`v_mbcnt`, `v_readlane` at a computed lane).
  306. Host,
  307. /// Mesh programs: their lanes and waves (LDS per console wave) are the
  308. /// console's but no host wave size can be declared.
  309. None,
  310. }
  311. /// What a value holding a lane mask read as a number stops with.
  312. pub(super) const LANE_MASK: Why = "a lane mask read as data";
  313. /// A mask with lanes outside EXEC where it is written, read as a number where the lanes that
  314. /// run that block are not all of the wave.
  315. pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data";
  316. /// Instructions that read a lane mask (not EXEC implicitly, not a lane's
  317. /// bit) as a number.
  318. /// Per IR block: every lane of the wave that started the program runs it – no per-lane branch
  319. /// separates it from the entry (it lies in no lane branch's region: the blocks reachable from
  320. /// the branch that do not post-dominate it). None with an indirect exit (not followed).
  321. fn all_lane_blocks(st: &Structured) -> Option<Vec<bool>> {
  322. let n = st.exits.len();
  323. let mut all = vec![true; n];
  324. for (_, region) in lane_regions(st)? {
  325. for b in (0..n).filter(|&b| region[b]) {
  326. all[b] = false;
  327. }
  328. }
  329. Some(all)
  330. }
  331. /// Every per-lane branch (by its block) with its region: the blocks reachable from it that do
  332. /// not post-dominate it, which only some lanes run. Not the branches the wave takes together
  333. /// ([`Structured::wide`]), nor those on scalar conditions. None with an indirect exit.
  334. fn lane_regions(st: &Structured) -> Option<Vec<(usize, Vec<bool>)>> {
  335. let n = st.exits.len();
  336. let mut succ: Vec<Vec<usize>> = vec![Vec::new(); n];
  337. for (b, e) in st.exits.iter().enumerate() {
  338. match *e {
  339. LaneExit::Jump(t) => succ[b].push(t),
  340. LaneExit::Branch { taken, not_taken, .. } => {
  341. succ[b].push(taken);
  342. succ[b].push(not_taken);
  343. }
  344. LaneExit::End => {}
  345. LaneExit::Indirect => return None,
  346. }
  347. }
  348. // post-dominators (bitsets; a virtual exit after every End)
  349. let words = n.div_ceil(64);
  350. let full = vec![u64::MAX; words];
  351. 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();
  352. let mut changed = true;
  353. while changed {
  354. changed = false;
  355. for b in (0..n).rev() {
  356. if succ[b].is_empty() {
  357. continue;
  358. }
  359. let mut v = full.clone();
  360. for &t in &succ[b] {
  361. for w in 0..words {
  362. v[w] &= pdom[t][w];
  363. }
  364. }
  365. v[b / 64] |= 1 << (b % 64);
  366. if v != pdom[b] {
  367. pdom[b] = v;
  368. changed = true;
  369. }
  370. }
  371. }
  372. let mut regions = Vec::new();
  373. for (d, e) in st.exits.iter().enumerate() {
  374. let LaneExit::Branch { when, .. } = *e else { continue };
  375. if st.wide.contains(&d) || st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) {
  376. continue; // a wave-wide or uniform branch: all lanes go the same way
  377. }
  378. // blocks reachable from the lane branch that do not post-dominate it
  379. let mut seen = vec![false; n];
  380. let mut stack: Vec<usize> = succ[d].clone();
  381. while let Some(b) = stack.pop() {
  382. if seen[b] || pdom[d][b / 64] >> (b % 64) & 1 == 1 {
  383. continue;
  384. }
  385. seen[b] = true;
  386. stack.extend(succ[b].iter().copied());
  387. }
  388. regions.push((d, seen));
  389. }
  390. Some(regions)
  391. }
  392. /// The per-lane branches (by block) whose regions hold a block of `needs` (blocks where two
  393. /// host waves must meet, [`take_needs`]): the ones to take wave-wide
  394. /// ([`crate::structure::structure_wide`]) so that every lane runs those blocks. None if one
  395. /// of them is a branch whose wave-wide meaning is not known ([`Structured::wave_any`]).
  396. pub(super) fn branches_around(st: &Structured, needs: &[usize]) -> Option<Vec<usize>> {
  397. let mut out = Vec::new();
  398. for (d, region) in lane_regions(st)? {
  399. if needs.iter().any(|&b| region.get(b).copied().unwrap_or(false)) {
  400. st.wave_any.get(d).copied().flatten()?;
  401. out.push(d);
  402. }
  403. }
  404. Some(out)
  405. }
  406. /// Whether a refusal is of code that needs every lane of the wave where it stands (two host
  407. /// waves meeting there), which the other forms of the program may give it.
  408. pub(super) fn needs_every_lane(what: &str) -> bool {
  409. what.ends_with("where not every lane runs") || what == MASK_ELSEWHERE
  410. }
  411. /// The blocks where the last lowering on this thread wanted every lane and did not have it
  412. /// (its "... where not every lane runs" refusals), which it forgets.
  413. pub(super) fn take_needs() -> Vec<usize> {
  414. NEEDS.take()
  415. }
  416. fn need(block: usize) {
  417. NEEDS.with_borrow_mut(|n| {
  418. if !n.contains(&block) {
  419. n.push(block);
  420. }
  421. });
  422. }
  423. /// VGPR values that are the same in every lane holding them (`all` is [`all_lane_blocks`]):
  424. /// written by an instruction every arriving lane runs (no guard), lane by lane, from scalars,
  425. /// constants and such values; or loaded from an address made of them. The compiler keeps
  426. /// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`.
  427. /// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes
  428. /// run (no lane branch can have split the arriving lanes); loop-carried values never do.
  429. fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet<Value> {
  430. let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
  431. let mut same: HashSet<Value> = HashSet::new();
  432. for b in crate::ir::reverse_postorder(&p.blocks) {
  433. let block = &p.blocks[b];
  434. let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false));
  435. for phi in &block.phis {
  436. if matches!(phi.reg, Reg::V(_)) && whole && phi.args.iter().all(|a| same.contains(a)) {
  437. same.insert(phi.value);
  438. }
  439. }
  440. for (i, inst) in block.insts.iter().enumerate() {
  441. let name = inst.name();
  442. let ops: Vec<Operand> = match &inst.fields {
  443. Fields::Valu(v)
  444. if v.dpp.is_none()
  445. && v.sdwa.is_none()
  446. && !name.starts_with("v_mbcnt")
  447. && !name.starts_with("v_cmpx")
  448. && !name.contains("lane") =>
  449. {
  450. v.src.clone()
  451. }
  452. _ => continue,
  453. };
  454. if st.guards[b][i].is_some() {
  455. continue; // lanes outside EXEC keep another value
  456. }
  457. let alike = ops.iter().all(|op| match *op {
  458. Operand::Vector { reg, .. } => {
  459. // every dword of the operand the instruction reads from that register on
  460. let read: Vec<Value> =
  461. inst.reads.iter().filter(|r| matches!(r.0, Reg::V(x) if x >= reg)).map(|r| r.1).collect();
  462. !read.is_empty() && read.iter().all(|x| same.contains(x))
  463. }
  464. // a scalar is one value; a lane mask is not, unless a compare of such values made it
  465. Operand::Scalar { code, .. } if code != NULL => {
  466. inst.read(Reg::S(code)).is_none_or(|x| !is_mask(x) || same.contains(&x))
  467. }
  468. _ => true,
  469. });
  470. if alike {
  471. same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1));
  472. }
  473. }
  474. }
  475. same
  476. }
  477. /// What a register value holds, for [`wave_local`].
  478. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  479. enum Wave {
  480. /// Nothing that depends on how the threads are divided into waves.
  481. Plain,
  482. /// The number of the wave's first lane in a mask (`s_ff1`).
  483. First,
  484. /// A reduction over the wave's lanes: a count, a sum, a minimum...
  485. Total(super::wave::Op),
  486. /// A count or sum over the lanes below this one.
  487. Prefix,
  488. /// Derived from what a first-lane atomic returned: the slots the wave reserved.
  489. Base,
  490. /// A mix the idiom does not make.
  491. Mixed,
  492. }
  493. /// Whether a console wave64 program may run with each host wave as a wave of its own
  494. /// ([`with_local_waves`]): its wave-wide values are used only as the allocation idiom uses
  495. /// them, which does not care how the threads are divided into waves. A first-lane number only
  496. /// picks the first lane; a count or sum only goes into that lane's atomic on a shared counter;
  497. /// a prefix only goes onto the base that atomic returned; the first lane does nothing else.
  498. /// Anything else done with them takes one wave to be the whole thread group (a tile's result,
  499. /// say) and is refused, with the offset and what was found.
  500. /// Lane masks read as numbers by other instructions and lane reads outside whole-wave sections
  501. /// are stopped by the lowering itself.
  502. // shortcut: `v_readfirstlane` of a value that differs between lanes is taken as it is (this
  503. // host wave's first lane), and a guarded write of a plain value over a wave-dependent one is
  504. // the only mix of old and new lanes that is looked at.
  505. pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'static str)> {
  506. use super::wave::{Op, Shape};
  507. const FIRST: Why = "a wave's first-lane number used as data";
  508. const TOTAL: Why = "a count or sum over the wave used as data";
  509. const PREFIX: Why = "a count or sum over the lanes below used without a reserved base";
  510. const MIXED: Why = "a value that depends on the wave on some paths only";
  511. const EFFECT: Why = "a write by the wave's first lane other than its reservation";
  512. fn of(kind: &HashMap<Value, Wave>, v: Option<Value>) -> Wave {
  513. v.and_then(|v| kind.get(&v).copied()).unwrap_or(Wave::Plain)
  514. }
  515. fn put(kind: &mut HashMap<Value, Wave>, v: Value, k: Wave) {
  516. if k == Wave::Plain {
  517. kind.remove(&v);
  518. } else {
  519. kind.insert(v, k);
  520. }
  521. }
  522. let wild = |k: Wave| !matches!(k, Wave::Plain | Wave::Base);
  523. let why = |k: Wave| match k {
  524. Wave::First => FIRST,
  525. Wave::Total(_) => TOTAL,
  526. Wave::Prefix => PREFIX,
  527. _ => MIXED,
  528. };
  529. // a mask (by its low dword) under which only a wave's first lane runs
  530. let first_mask = |firsts: &HashSet<Value>, m: Option<Value>| {
  531. m.and_then(|m| st.masks.get(&m)).is_some_and(|&b| {
  532. st.bools
  533. .support(b)
  534. .iter()
  535. .any(|a| matches!(a, Atom::Lane(v) if firsts.contains(v)))
  536. })
  537. };
  538. // One instruction outside a section: the kind of what it writes, and whether it is a
  539. // first lane's reservation.
  540. let step = |inst: &Inst, kind: &HashMap<Value, Wave>, firsts: &mut HashSet<Value>| -> Result<(Wave, bool), Why> {
  541. let name = inst.name();
  542. let val = |op: &Operand| match *op {
  543. Operand::Vector { reg, .. } => inst.read(Reg::V(reg)),
  544. Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)),
  545. _ => None,
  546. };
  547. let ops: Vec<Operand> = match &inst.fields {
  548. Fields::Valu(v) => v.src.clone(),
  549. Fields::Sop { dst, src, .. } => {
  550. let mut o = src.clone();
  551. if matches!(name, "s_addk_i32" | "s_mulk_i32") {
  552. o.extend(dst.iter().copied());
  553. }
  554. o
  555. }
  556. Fields::Buffer { data, .. } if name.contains("_atomic_") || name.contains("_store_") => {
  557. data.iter().copied().collect()
  558. }
  559. _ => Vec::new(),
  560. };
  561. let kinds: Vec<Wave> = ops.iter().map(|o| of(kind, val(o))).collect();
  562. // Everything else it reads (addresses, descriptors, SCC, the high dwords of wide
  563. // operands) must not depend on the wave. Not EXEC, and not the old value of a VGPR it
  564. // writes, which only the lanes outside EXEC keep.
  565. let named: Vec<Value> = ops.iter().filter_map(&val).collect();
  566. for &(r, v) in &inst.reads {
  567. let kept = matches!(r, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == r);
  568. if matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) || kept || named.contains(&v) {
  569. continue;
  570. }
  571. let k = of(kind, Some(v));
  572. if wild(k) {
  573. return Err(why(k));
  574. }
  575. }
  576. let w = kinds.iter().copied().find(|&k| wild(k)).unwrap_or(Wave::Mixed);
  577. let sum = |k: Wave| k == Wave::Total(Op::AddU);
  578. let is_mask = |o: &Operand| {
  579. val(o).is_some_and(|v| st.masks.contains_key(&v) || st.highs.contains_key(&v))
  580. };
  581. let mut reserved = false;
  582. let out = match (name, &kinds[..]) {
  583. ("s_ff1_i32_b64" | "s_ff1_i32_b32", _) if ops.first().is_some_and(is_mask) => Wave::First,
  584. ("s_bcnt1_i32_b64" | "s_bcnt1_i32_b32", _) if ops.first().is_some_and(is_mask) => {
  585. Wave::Total(Op::AddU)
  586. }
  587. // bits of a mask below the lane; with -1 for the mask, the lane's number
  588. ("v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32", [_, b]) => {
  589. match (matches!(ops[0], Operand::Scalar { .. }), *b) {
  590. (_, Wave::Prefix) | (true, Wave::Plain | Wave::Base) => Wave::Prefix,
  591. (false, Wave::Plain | Wave::Base) => Wave::Plain,
  592. (_, k) => return Err(why(k)),
  593. }
  594. }
  595. // nothing wave-dependent goes in; what derives from a reserved base stays marked
  596. _ if !kinds.iter().any(|&k| wild(k)) => {
  597. let derives = matches!(inst.fields, Fields::Valu(_) | Fields::Sop { .. });
  598. if derives && kinds.contains(&Wave::Base) { Wave::Base } else { Wave::Plain }
  599. }
  600. ("v_mov_b32" | "s_mov_b32", [k]) => *k,
  601. ("v_cmp_eq_i32" | "v_cmp_eq_u32" | "v_cmpx_eq_i32" | "v_cmpx_eq_u32", [a, b]) => {
  602. // the lane whose own number is the first lane's
  603. let lane = match (*a, *b) {
  604. (Wave::First, k) if !wild(k) => &ops[1],
  605. (k, Wave::First) if !wild(k) => &ops[0],
  606. _ => return Err(why(w)),
  607. };
  608. if !matches!(lane, Operand::Vector { .. }) {
  609. return Err(FIRST);
  610. }
  611. let mask = match &inst.fields {
  612. _ if name.starts_with("v_cmpx") => inst.write(Reg::S(EXEC)),
  613. Fields::Valu(v) => match v.dst {
  614. Some(Operand::Scalar { code, .. }) => inst.write(Reg::S(code)),
  615. _ => None,
  616. },
  617. _ => None,
  618. };
  619. firsts.extend(mask);
  620. Wave::Plain
  621. }
  622. ("v_add_nc_u32" | "s_add_i32", [a, b]) => match (*a, *b) {
  623. (Wave::Prefix, Wave::Base) | (Wave::Base, Wave::Prefix) => Wave::Base,
  624. (Wave::Prefix, Wave::Plain | Wave::Prefix) | (Wave::Plain, Wave::Prefix) => Wave::Prefix,
  625. (x, y) if sum(x) && sum(y) => x,
  626. _ => return Err(why(w)),
  627. },
  628. ("v_sub_nc_u32" | "s_sub_i32", [a, b]) => match (*a, *b) {
  629. (Wave::Base, Wave::Prefix) => Wave::Base,
  630. (Wave::Prefix, Wave::Plain) => Wave::Prefix,
  631. (Wave::Plain, y) if sum(y) && matches!(ops[0], Operand::Const(128)) => y,
  632. _ => return Err(why(w)),
  633. },
  634. ("s_mul_i32" | "v_mul_lo_u32" | "v_mul_u32_u24", [a, b]) => match (*a, *b) {
  635. (x, Wave::Plain) | (Wave::Plain, x) if sum(x) || x == Wave::Prefix => x,
  636. _ => return Err(why(w)),
  637. },
  638. ("s_lshl_b32", [x, Wave::Plain]) | ("v_lshlrev_b32", [Wave::Plain, x])
  639. if sum(*x) || *x == Wave::Prefix =>
  640. {
  641. *x
  642. }
  643. ("v_lshl_add_u32", [Wave::Prefix, Wave::Plain, c]) if !wild(*c) => {
  644. if *c == Wave::Base { Wave::Base } else { Wave::Prefix }
  645. }
  646. // the reservation: the first lane adds its wave's total to a shared counter
  647. (_, [Wave::Total(op)]) if name.contains("_atomic_") => {
  648. let want = match op {
  649. Op::AddU => "buffer_atomic_add",
  650. Op::MinU => "buffer_atomic_umin",
  651. Op::MaxU => "buffer_atomic_umax",
  652. Op::MinI => "buffer_atomic_smin",
  653. Op::MaxI => "buffer_atomic_smax",
  654. Op::Or => "buffer_atomic_or",
  655. Op::And => "buffer_atomic_and",
  656. Op::Xor => "buffer_atomic_xor",
  657. _ => "",
  658. };
  659. if name != want || !first_mask(firsts, inst.read(Reg::S(EXEC))) {
  660. return Err(TOTAL);
  661. }
  662. reserved = true;
  663. Wave::Base
  664. }
  665. _ => return Err(why(w)),
  666. };
  667. Ok((out, reserved))
  668. };
  669. let sections: Vec<_> = (0..p.blocks.len()).map(|b| super::wave::sections(p, b)).collect();
  670. let order = crate::ir::reverse_postorder(&p.blocks);
  671. let pass = |kind: &mut HashMap<Value, Wave>, firsts: &mut HashSet<Value>, check: bool| -> Result<(), (usize, Why)> {
  672. for &b in &order {
  673. let block = &p.blocks[b];
  674. for phi in &block.phis {
  675. let mut k = Wave::Plain;
  676. for (n, &a) in phi.args.iter().enumerate() {
  677. let x = of(kind, Some(a));
  678. k = match (k, x) {
  679. _ if n == 0 => x,
  680. (k, x) if k == x => k,
  681. (Wave::Plain, m @ (Wave::Base | Wave::Prefix))
  682. | (m @ (Wave::Base | Wave::Prefix), Wave::Plain) => m,
  683. _ => Wave::Mixed,
  684. };
  685. }
  686. put(kind, phi.value, k);
  687. }
  688. for (i, inst) in block.insts.iter().enumerate() {
  689. // inside a whole-wave section: what the simulation found each value to be
  690. if let Some((_, sec)) = sections[b].iter().find(|(s, sec)| i > **s && i < sec.end) {
  691. for &(_, w) in &inst.writes {
  692. let k = match sec.shapes.get(&w) {
  693. None => Wave::Mixed,
  694. Some(&Shape::K(_)) => Wave::Plain,
  695. Some(&Shape::Value(v)) => of(kind, Some(v)),
  696. Some(&Shape::Masked(src, _, _)) => of(kind, Some(src)),
  697. Some(&Shape::Active(op, src, mask, _)) => match of(kind, Some(src)) {
  698. Wave::Plain | Wave::Base => Wave::Total(op),
  699. // the first lane's own sum of a total is that total
  700. Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => Wave::Total(op),
  701. _ => Wave::Mixed,
  702. },
  703. Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => match of(kind, Some(src)) {
  704. Wave::Plain | Wave::Base => Wave::Prefix,
  705. Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => Wave::Prefix,
  706. _ => Wave::Mixed,
  707. },
  708. Some(_) => Wave::Mixed,
  709. };
  710. put(kind, w, k);
  711. }
  712. continue;
  713. }
  714. let name = inst.name();
  715. if name.starts_with("s_cbranch") {
  716. continue; // with the block's exit, below
  717. }
  718. let (k, reserved) = match step(inst, kind, firsts) {
  719. Ok(r) => r,
  720. Err(why) if check => return Err((inst.machine.offset, why)),
  721. Err(_) => (Wave::Mixed, false),
  722. };
  723. // the same test as `Lower::inst`'s `effect`
  724. let effect = matches!(inst.fields, Fields::Exp { .. })
  725. || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
  726. || name.contains("store")
  727. || name.contains("atomic")
  728. || matches!(inst.fields, Fields::Ds { .. })
  729. && !(name.starts_with("ds_read")
  730. || name.starts_with("ds_swizzle")
  731. || name.contains("permute"));
  732. if check && effect && !reserved && first_mask(firsts, inst.read(Reg::S(EXEC))) {
  733. return Err((inst.machine.offset, EFFECT));
  734. }
  735. let guarded = st.guards[b][i].is_some();
  736. for &(r, w) in &inst.writes {
  737. let mut kw = match r {
  738. // "some lane is counted" keeps the count's kind; any other SCC is one bit of data
  739. Reg::Scc if !name.starts_with("s_bcnt1") => {
  740. if wild(k) { Wave::Mixed } else { Wave::Plain }
  741. }
  742. _ => k,
  743. };
  744. // a guarded write leaves the old value in the lanes outside EXEC
  745. if guarded
  746. && matches!(r, Reg::V(_))
  747. && kw == Wave::Plain
  748. && matches!(of(kind, inst.read(r)), Wave::First | Wave::Total(_) | Wave::Prefix)
  749. {
  750. kw = Wave::Mixed;
  751. }
  752. put(kind, w, kw);
  753. }
  754. }
  755. // a branch on "some lane is counted": fine where the structure made it the lane's
  756. // own bit (the mask is EXEC under a scalar condition)
  757. if check
  758. && let Some(last) = block.insts.last()
  759. && last.name().starts_with("s_cbranch_scc")
  760. && let Some(scc) = last.read(Reg::Scc)
  761. && wild(of(kind, Some(scc)))
  762. {
  763. let own = matches!(st.exits[b], LaneExit::Branch { when, .. }
  764. if !st.bools.support(when).iter().any(|a| matches!(a, Atom::Uniform(v) if *v == scc)));
  765. if !own {
  766. return Err((last.machine.offset, TOTAL));
  767. }
  768. }
  769. }
  770. Ok(())
  771. };
  772. let mut kind: HashMap<Value, Wave> = HashMap::new();
  773. let mut firsts: HashSet<Value> = HashSet::new();
  774. // to a fixpoint (values carried around loops), then once more to say what is wrong
  775. let mut settled = false;
  776. for _ in 0..16 {
  777. let before = (kind.clone(), firsts.len());
  778. pass(&mut kind, &mut firsts, false)?;
  779. if (&before.0, before.1) == (&kind, firsts.len()) {
  780. settled = true;
  781. break;
  782. }
  783. }
  784. if !settled {
  785. return Err((0, MIXED));
  786. }
  787. pass(&mut kind, &mut firsts, true)
  788. }
  789. /// The mode of a group barrier the translation adds (host waves meeting):
  790. /// a wait for the group with a shared-memory fence; the fence alone with
  791. /// `VICTORY_GROUP_SYNC=0` ([`super::group_sync`]).
  792. fn meeting_mode() -> u32 {
  793. if super::group_sync() == 0 { 8 } else { 1 | 8 }
  794. }
  795. /// LDS accesses of a console wave run as two host waves, where some sit in blocks that only
  796. /// some lanes run (`all` is [`all_lane_blocks`]): per IR block, whether the host waves meet (a
  797. /// group barrier) at its start and before its exit. `None` if barriers cannot keep the
  798. /// console's order.
  799. ///
  800. /// The console runs the wave's lanes in step, so an LDS write is seen by every later read. Two
  801. /// host waves keep that order if they meet between any two accesses of which one writes. A
  802. /// barrier must be run by every thread, so it cannot stand in a lane branch's region; but
  803. /// every way into and out of such a region passes a block all lanes run, and the waves meet
  804. /// there: before the exit of an all-lane block into a region with LDS accesses, and at the
  805. /// start of an all-lane block entered from one. Accesses in all-lane blocks get their own
  806. /// barrier as before. What that cannot order is a write and a read inside one region (blocks
  807. /// joined without an all-lane block between them): refused.
  808. /// shortcut: two writes in one region are taken not to hit the same dword from both halves.
  809. fn lds_meetings(p: &crate::ir::Program, st: &Structured, all: &[bool]) -> Option<Vec<(bool, bool)>> {
  810. let n = st.exits.len();
  811. let succ = |b: usize| -> Vec<usize> {
  812. match st.exits[b] {
  813. LaneExit::Jump(t) => vec![t],
  814. LaneExit::Branch { taken, not_taken, .. } => vec![taken, not_taken],
  815. LaneExit::End | LaneExit::Indirect => Vec::new(),
  816. }
  817. };
  818. // regions: blocks not every lane runs, joined by the edges between them
  819. let mut region: Vec<usize> = (0..n).collect();
  820. fn find(region: &mut [usize], mut b: usize) -> usize {
  821. while region[b] != b {
  822. region[b] = region[region[b]];
  823. b = region[b];
  824. }
  825. b
  826. }
  827. for b in 0..n {
  828. for t in succ(b) {
  829. if !all[b] && !all[t] {
  830. let (x, y) = (find(&mut region, b), find(&mut region, t));
  831. region[x] = y;
  832. }
  833. }
  834. }
  835. // per region: LDS reads, LDS writes
  836. let mut reads = vec![false; n];
  837. let mut writes = vec![false; n];
  838. for (b, block) in p.blocks.iter().enumerate().take(n) {
  839. if all[b] {
  840. continue;
  841. }
  842. let r = find(&mut region, b);
  843. for i in &block.insts {
  844. let name = i.name();
  845. if !matches!(i.fields, Fields::Ds { .. }) || name.starts_with("ds_swizzle") || name.contains("permute") {
  846. continue;
  847. }
  848. if name.starts_with("ds_read") {
  849. reads[r] = true;
  850. } else {
  851. writes[r] = true;
  852. }
  853. }
  854. }
  855. if (0..n).any(|r| reads[r] && writes[r]) {
  856. return None;
  857. }
  858. let mut meet = vec![(false, false); n];
  859. for b in 0..n {
  860. for t in succ(b) {
  861. if all[b] && !all[t] {
  862. let r = find(&mut region, t);
  863. meet[b].1 |= reads[r] || writes[r];
  864. } else if !all[b] && all[t] {
  865. let r = find(&mut region, b);
  866. meet[t].0 |= reads[r] || writes[r];
  867. }
  868. }
  869. }
  870. Some(meet)
  871. }
  872. /// Masks held as numbers or constant lane sets in guards or lane branches: the lane tests its
  873. /// own bit by its console lane.
  874. fn lane_constant_masks(st: &Structured) -> bool {
  875. let whens = st.exits.iter().filter_map(|e| match *e {
  876. LaneExit::Branch { when, .. } => Some(when),
  877. _ => None,
  878. });
  879. let mut work: Vec<Bool> = st.guards.iter().flatten().flatten().copied().chain(whens).collect();
  880. // Through lane-mask joins too: an edge that brings a number or a constant lane set needs
  881. // the lane's own bit of it.
  882. // shortcut: masks only selects read (`v_cndmask_b32`, carries in) are not followed; such
  883. // a program still stops with "a constant lane mask" or "an opaque lane mask".
  884. let (mut seen, mut joins) = (HashSet::new(), HashSet::new());
  885. while let Some(g) = work.pop() {
  886. if !seen.insert(g) {
  887. continue;
  888. }
  889. for a in st.bools.support(g) {
  890. match a {
  891. Atom::Opaque(_) | Atom::Constant(_) => return true,
  892. Atom::Phi(id) if joins.insert(id) => {
  893. if let Some(edges) = st.phi_masks.get(&id) {
  894. work.extend(edges.iter().copied());
  895. }
  896. }
  897. _ => {}
  898. }
  899. }
  900. }
  901. false
  902. }
  903. /// The widest wave the host GPU runs (0: not known – no host-specific forms); see
  904. /// [`set_host_max_wave`].
  905. static HOST_MAX_WAVE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  906. /// The host GPU's `WaveLaneCountMax`: 32 lets console wave64 compute programs whose cross-lane
  907. /// code stays inside 32-lane halves run in waves of 32 instead of being refused.
  908. pub fn set_host_max_wave(lanes: u32) {
  909. HOST_MAX_WAVE.store(lanes, std::sync::atomic::Ordering::Relaxed);
  910. }
  911. thread_local! {
  912. /// See [`take_needs`].
  913. static NEEDS: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
  914. /// See [`with_local_waves`].
  915. static LOCAL_WAVES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
  916. /// See [`with_local_waves_any`].
  917. static LOCAL_ANY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
  918. }
  919. /// As [`with_local_waves`], with every other use of a lane mask as a number
  920. /// and every lane read and write taken per host wave too: the program runs
  921. /// as it would on a console of 32-lane waves, lanes numbered 0..31 or
  922. /// 32..63 by half. Right for code that only relies on what HLSL's wave
  923. /// operations promise; a program that takes one wave to be its whole
  924. /// thread group gets per-half results. The last resort for programs that
  925. /// do not translate otherwise.
  926. pub(super) fn with_local_waves_any<R>(f: impl FnOnce() -> R) -> R {
  927. let was = LOCAL_ANY.replace(true);
  928. let r = with_local_waves(f);
  929. LOCAL_ANY.set(was);
  930. r
  931. }
  932. /// Runs `f` with console wave64 programs on 32-lane hosts lowered with each
  933. /// host wave as a wave of its own ("local"): no exchange between the two
  934. /// halves of a console wave, so no barriers and no need for every lane to
  935. /// reach the code. What HLSL's wave operations promise holds for any
  936. /// division of the threads into waves, and the idiom the title's compute
  937. /// programs use them for does not care which wave a thread is in: count or
  938. /// sum over the wave, the first lane reserves that many slots with an atomic
  939. /// add, every lane takes the base (`WaveReadLaneFirst`) plus its prefix.
  940. /// Each lane still gets a slot of its own; only the order differs.
  941. /// Only that idiom's operations are lowered this way: a lane mask read as
  942. /// a number by anything but a bit count, a first-set-bit or `v_mbcnt`, and
  943. /// lane reads and writes outside whole-wave sections, stop the translation.
  944. /// shortcut: where a count or sum goes is not checked. A program that uses
  945. /// a wave-wide result as data for the whole console wave (a tile's maximum,
  946. /// say, with one wave per thread group) gets its half's result. It is used
  947. /// only for programs that do not translate otherwise.
  948. pub(super) fn with_local_waves<R>(f: impl FnOnce() -> R) -> R {
  949. let was = LOCAL_WAVES.replace(true);
  950. let r = f();
  951. LOCAL_WAVES.set(was);
  952. r
  953. }
  954. /// `VICTORY_F16_NEAREST=1`: the results of 16-bit float operations (`v_add_f16`,
  955. /// `v_mul_f16`, `v_cvt_f16_f32` ...) are rounded to nearest as the console rounds them
  956. /// ([`Lower::f16_nearest`]) instead of as the host's `f32tof16` does (toward zero on NVIDIA:
  957. /// the last place of a result that is not exact is then one lower than the console's).
  958. /// Off by default: it is exact but untried in a game run, and adds instructions to every
  959. /// such operation. The wave sum of 16-bit floats ([`Lower::half_sum`]) is always exact.
  960. fn f16_nearest_on() -> bool {
  961. #[cfg(test)]
  962. if let Some(on) = TEST_F16_NEAREST.get() {
  963. return on;
  964. }
  965. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  966. *ON.get_or_init(|| std::env::var_os("VICTORY_F16_NEAREST").is_some_and(|v| v == "1"))
  967. }
  968. #[cfg(test)]
  969. thread_local! {
  970. /// A test's choice for [`f16_nearest_on`], for its thread only.
  971. pub(super) static TEST_F16_NEAREST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
  972. }
  973. /// `VICTORY_WAVE_OWN_BITS=0`: a wave OR where not every lane runs is refused as before
  974. /// ([`super::own_bits`]).
  975. fn own_bits_on() -> bool {
  976. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  977. *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0"))
  978. }
  979. pub(super) fn host_max_wave() -> u32 {
  980. #[cfg(test)]
  981. if let Some(lanes) = TEST_HOST_WAVE.get() {
  982. return lanes;
  983. }
  984. HOST_MAX_WAVE.load(std::sync::atomic::Ordering::Relaxed)
  985. }
  986. #[cfg(test)]
  987. thread_local! {
  988. /// A test's host wave size, for its thread only ([`set_host_max_wave`] is the process's).
  989. pub(super) static TEST_HOST_WAVE: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
  990. }
  991. pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool {
  992. let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
  993. let ops: Vec<&Operand> = match &i.fields {
  994. // A mask operation (its result a mask) is no data use.
  995. Fields::Sop { .. }
  996. if i.writes
  997. .iter()
  998. .any(|&(r, w)| matches!(r, Reg::S(_)) && is_mask(w)) =>
  999. {
  1000. return false;
  1001. }
  1002. Fields::Sop { src, .. } => src.iter().collect(),
  1003. Fields::Valu(v)
  1004. if !matches!(i.name(), "v_cndmask_b32") && !i.name().contains("_co_ci_") =>
  1005. {
  1006. v.src.iter().collect()
  1007. }
  1008. _ => return false,
  1009. };
  1010. ops.into_iter().any(|op| match *op {
  1011. Operand::Scalar { code, .. } if code != NULL => i.read(Reg::S(code)).is_some_and(is_mask),
  1012. _ => false,
  1013. })
  1014. }
  1015. /// The parameters packing 16-bit rows two per dword and where each lays
  1016. /// its elements out: (first row, [(dword, register, column, columns)]).
  1017. ///
  1018. /// The console gives every 16-bit element whole dwords. A parameter leads
  1019. /// with the first element of its first row, then the first element of its
  1020. /// second row. An element that shares a register behind another one (the
  1021. /// signature packs a short element into the free columns of an earlier
  1022. /// register) is NOT in that row's halves: it follows in the first
  1023. /// parameter, in row order, that has whole dwords left. Grand Theft Auto
  1024. /// VI's packed pedestrian shaders show both cases: TEXCOORD7 (register 1,
  1025. /// columns 2-3, behind the two columns of TEXCOORD0) is exported in dword 3
  1026. /// of parameter 0, after TEXCOORD1's two dwords; TEXCOORD6 (register 4,
  1027. /// column 3, behind the three columns of TEXCOORD4) in dword 3 of
  1028. /// parameter 3, after TEXCOORD5 and TEXCOORD7, while the high half of
  1029. /// TEXCOORD4's second dword stays zero.
  1030. type PackedLayout = Vec<(u8, Vec<(u8, u8, u8, u8)>)>;
  1031. fn packed_layout(elements: &[SigElement], packs: &[(u8, Option<u8>)]) -> PackedLayout {
  1032. let of_row = |r: u8| {
  1033. let mut of: Vec<&SigElement> = elements
  1034. .iter()
  1035. .filter(|e| e.row == Some(u32::from(r)))
  1036. .collect();
  1037. of.sort_by_key(|e| e.col);
  1038. of
  1039. };
  1040. let mut packs = packs.to_vec();
  1041. packs.sort_unstable();
  1042. packs.dedup_by_key(|p| p.0);
  1043. // Per parameter: its first row, the dwords used, the elements.
  1044. let mut layout: Vec<(u8, u8, Vec<(u8, u8, u8, u8)>)> = Vec::new();
  1045. let mut behind = Vec::new();
  1046. for &(a, b) in &packs {
  1047. let mut placed = Vec::new();
  1048. let mut at = 0u8;
  1049. if !of_row(a).is_empty() {
  1050. for r in [Some(a), b].into_iter().flatten() {
  1051. let of = of_row(r);
  1052. let Some((lead, more)) = of.split_first() else {
  1053. continue;
  1054. };
  1055. placed.push((at, r, lead.col, lead.cols));
  1056. at += lead.cols.div_ceil(2);
  1057. behind.extend(more.iter().map(|e| (r, e.col, e.cols)));
  1058. }
  1059. }
  1060. layout.push((a, at, placed));
  1061. }
  1062. behind.sort_unstable();
  1063. for (r, col, cols) in behind {
  1064. let need = cols.div_ceil(2);
  1065. if let Some(p) = layout.iter_mut().find(|p| p.1 + need <= 4) {
  1066. p.2.push((p.1, r, col, cols));
  1067. p.1 += need;
  1068. }
  1069. }
  1070. layout.into_iter().map(|(a, _, of)| (a, of)).collect()
  1071. }
  1072. /// Where half `h` (dword h / 2, the high half when odd) of the parameter
  1073. /// whose first 16-bit row is `a` comes from: a register and column of
  1074. /// `elements`, none for padding ([`packed_layout`]; `packs` lists every
  1075. /// parameter packing two 16-bit rows per dword).
  1076. fn packed_half(
  1077. elements: &[SigElement],
  1078. packs: &[(u8, Option<u8>)],
  1079. a: u8,
  1080. h: u8,
  1081. ) -> Option<(u8, u8)> {
  1082. let layout = packed_layout(elements, packs);
  1083. let (_, of) = layout.iter().find(|p| p.0 == a)?;
  1084. of.iter().find_map(|&(dword, row, col, cols)| {
  1085. let k = h.checked_sub(2 * dword)?;
  1086. (k < cols).then_some((row, col + k))
  1087. })
  1088. }
  1089. /// The pixel inputs packing two 16-bit rows per dword, as (first row,
  1090. /// second row) ([`packed_layout`]).
  1091. fn input_packs(io: &StageIo, inputs: &[SigElement]) -> Vec<(u8, Option<u8>)> {
  1092. let StageIo::Ps {
  1093. inputs: entries, ..
  1094. } = io
  1095. else {
  1096. return Vec::new();
  1097. };
  1098. let partners = half_input_partners(io, inputs);
  1099. entries
  1100. .iter()
  1101. .filter(|i| i.fp16 && i.pack2)
  1102. .map(|i| {
  1103. let b = if i.row2 != i.row {
  1104. Some(i.row2)
  1105. } else {
  1106. partners.get(&i.row).copied()
  1107. };
  1108. (i.row, b)
  1109. })
  1110. .collect()
  1111. }
  1112. /// Vertex or mesh outputs of 16-bit values (see [`Lower::half_outputs`]):
  1113. /// a packed row's partner is the next 16-bit row of the signature that no
  1114. /// output entry names, taken in row order.
  1115. fn half_outputs(io: &StageIo, outputs: &[SigElement]) -> HashMap<u8, (bool, Option<u8>)> {
  1116. let entries = match io {
  1117. StageIo::Vs { outputs, .. } => outputs,
  1118. StageIo::Ms(ms) => &ms.outputs,
  1119. _ => return HashMap::new(),
  1120. };
  1121. let per_vertex = || entries.iter().filter(|o| o.param & 0x80 == 0);
  1122. let mut free: Vec<u8> = outputs
  1123. .iter()
  1124. .filter(|e| e.half && e.kind == 0)
  1125. .filter_map(|e| u8::try_from(e.row?).ok())
  1126. .filter(|&r| !per_vertex().any(|o| o.row == r))
  1127. .collect();
  1128. free.sort_unstable();
  1129. free.dedup();
  1130. let mut halves: Vec<_> = per_vertex().filter(|o| o.fp16).collect();
  1131. halves.sort_by_key(|o| o.row);
  1132. halves
  1133. .into_iter()
  1134. .map(|o| {
  1135. let b = o
  1136. .pack2
  1137. .then(|| free.iter().position(|&r| r > o.row))
  1138. .flatten();
  1139. (o.row, (o.pack2, b.map(|i| free.remove(i))))
  1140. })
  1141. .collect()
  1142. }
  1143. /// Pixel inputs packing two 16-bit rows per dword whose second row the
  1144. /// metadata leaves out (`row2` = `row`): as for outputs
  1145. /// ([`half_outputs`]), the next 16-bit row of the signature that no input
  1146. /// entry names, taken in row order (rows the metadata does give are taken
  1147. /// first).
  1148. fn half_input_partners(io: &StageIo, inputs: &[SigElement]) -> HashMap<u8, u8> {
  1149. let StageIo::Ps {
  1150. inputs: entries, ..
  1151. } = io
  1152. else {
  1153. return HashMap::new();
  1154. };
  1155. let packed = || entries.iter().filter(|i| i.fp16 && i.pack2);
  1156. let mut free: Vec<u8> = inputs
  1157. .iter()
  1158. .filter(|e| e.half && e.kind == 0)
  1159. .filter_map(|e| u8::try_from(e.row?).ok())
  1160. .filter(|&r| !entries.iter().any(|i| i.row == r))
  1161. .filter(|&r| !packed().any(|i| i.row2 != i.row && i.row2 == r))
  1162. .collect();
  1163. free.sort_unstable();
  1164. free.dedup();
  1165. let mut missing: Vec<_> = packed().filter(|i| i.row2 == i.row).collect();
  1166. missing.sort_by_key(|i| i.row);
  1167. let mut partners = HashMap::new();
  1168. for i in missing {
  1169. if let Some(k) = free.iter().position(|&r| r > i.row) {
  1170. partners.insert(i.row, free.remove(k));
  1171. }
  1172. }
  1173. partners
  1174. }
  1175. fn unsupported(offset: usize, what: Why) -> Stop {
  1176. Stop::Fail(ShaderError::Unsupported { offset, what })
  1177. }
  1178. impl<'a> Lower<'a> {
  1179. fn new(x: &'a Parts<'a>, bad: &'a HashMap<Value, Why>) -> Self {
  1180. let p = x.p;
  1181. let mut phi_at = HashMap::new();
  1182. for (b, block) in p.blocks.iter().enumerate() {
  1183. for (i, phi) in block.phis.iter().enumerate() {
  1184. phi_at.insert(phi.value, (b, i));
  1185. }
  1186. }
  1187. let mut s = Shader::new(x.native.stage == HwStage::Ps);
  1188. s.inputs = x.inputs.clone();
  1189. s.outputs = x.outputs.clone();
  1190. let insts = || p.blocks.iter().flat_map(|b| &b.insts);
  1191. let writes_uavs = insts().any(|i| {
  1192. matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. })
  1193. && (i.name().contains("store") || i.name().contains("atomic"))
  1194. });
  1195. let mut console_lanes = false;
  1196. // LDS accesses get a group barrier each (a console wave split in two host waves)
  1197. let mut split_lds = false;
  1198. // with `split_lds`, LDS accesses in lane branches: the blocks every lane runs, and
  1199. // where the host waves meet around those branches (`lds_meetings`)
  1200. let mut lds_meet: Option<(Vec<bool>, Vec<(bool, bool)>)> = None;
  1201. // a console wave64 program in two host waves of 32 (`exchange`)
  1202. let mut exchange: Option<(u32, bool, Vec<bool>)> = None;
  1203. // a console wave64 program in host waves of 32: the LDS dword of `wave_base`'s counter
  1204. let mut halves: Option<u32> = None;
  1205. if let StageIo::Cs(cs) = x.native.io {
  1206. s.threads = Some(cs.threads);
  1207. s.lds_dwords = cs.lds_bytes() / 4;
  1208. // Code reading other lanes needs the console's wave size and
  1209. // lane order; so do lane masks read as numbers, and LDS shared
  1210. // within one wave, where the console compiler leaves out barriers.
  1211. console_lanes = insts().any(|i| {
  1212. let n = i.name();
  1213. n.starts_with("ds_swizzle")
  1214. || n.contains("permute")
  1215. || n.starts_with("v_mbcnt")
  1216. || matches!(n, "v_readlane_b32" | "v_writelane_b32")
  1217. || matches!(&i.fields, Fields::Valu(v) if v.dpp.is_some())
  1218. || reads_mask_as_data(x.st, i)
  1219. }) || lane_constant_masks(x.st)
  1220. // (a branch the wave takes together asks the wave)
  1221. || !x.st.wide.is_empty();
  1222. let mut wave = if x.native.wave64 { 64 } else { 32 };
  1223. let group = cs.threads.iter().product::<u32>();
  1224. let one_wave = group <= wave;
  1225. // A host whose waves are at most 32 lanes (NVIDIA) refuses `WaveSize(64)`. A console
  1226. // wave64 program whose cross-lane code stays inside 32-lane halves – DPP rows,
  1227. // `ds_swizzle`, `v_permlane16` / `v_permlanex16`, which the ISA confines there – runs
  1228. // exactly in waves of 32: the thread relabelling makes each host wave one half of a
  1229. // console wave (lanes 32k..32k+31). Not when it crosses halves (`v_mbcnt`,
  1230. // `v_readlane`, `v_writelane`, `ds_(b)permute`, masks as numbers or lane-constant
  1231. // masks), nor when LDS may be shared within the console wave without barriers (a
  1232. // group over 32 threads with LDS): those still need 64-lane waves.
  1233. if wave == 64 && host_max_wave() == 32 && (console_lanes || one_wave && s.lds_dwords > 0) {
  1234. let crosses = insts().any(|i| {
  1235. let n = i.name();
  1236. n.starts_with("v_mbcnt")
  1237. || matches!(n, "v_readlane_b32" | "v_writelane_b32")
  1238. || n.starts_with("ds_permute")
  1239. || n.starts_with("ds_bpermute")
  1240. || reads_mask_as_data(x.st, i)
  1241. }) || lane_constant_masks(x.st)
  1242. || !x.st.wide.is_empty();
  1243. if !crosses && (s.lds_dwords == 0 || group <= 32) {
  1244. wave = 32;
  1245. } else {
  1246. // (Groups of several console waves too: each console wave is two host
  1247. // waves, which exchange through their own pair of dwords.)
  1248. // LDS the console shares within its one wave without barriers: split into
  1249. // two waves of 32, a group barrier before every LDS access keeps their order
  1250. // – where every thread of the group gets there (no lane branch around it,
  1251. // no guard), else a barrier would hang the group
  1252. let lds = |i: &Inst| {
  1253. matches!(i.fields, Fields::Ds { .. })
  1254. && !(i.name().starts_with("ds_swizzle") || i.name().contains("permute"))
  1255. };
  1256. if let Some(all) = all_lane_blocks(x.st) {
  1257. let ok = p.blocks.iter().enumerate().all(|(b, blk)| {
  1258. blk.insts.iter().all(|inst| {
  1259. !lds(inst) || all.get(b).copied().unwrap_or(false)
  1260. })
  1261. });
  1262. let mut lds_ok = !(s.lds_dwords > 0 && group > 32) || ok;
  1263. if !lds_ok && let Some(meet) = lds_meetings(p, x.st, &all) {
  1264. lds_meet = Some((all.clone(), meet));
  1265. lds_ok = true;
  1266. }
  1267. if !lds_ok {
  1268. // (the blocks whose LDS accesses not every lane runs: with the
  1269. // branches around them taken wave-wide they get their barriers)
  1270. for (b, blk) in p.blocks.iter().enumerate() {
  1271. if !all.get(b).copied().unwrap_or(false) && blk.insts.iter().any(lds) {
  1272. need(b);
  1273. }
  1274. }
  1275. }
  1276. if lds_ok {
  1277. wave = 32;
  1278. split_lds = s.lds_dwords > 0 && group > 32;
  1279. if crosses {
  1280. // lanes 32..63 are the other host wave: masks, lane reads and lane
  1281. // numbers go through two exchange dwords past the program's LDS
  1282. exchange = Some((s.lds_dwords, group <= 32, all));
  1283. s.lds_dwords += 2 * group.div_ceil(64);
  1284. }
  1285. }
  1286. }
  1287. }
  1288. // `VICTORY_WAVE_WHY=1`: why a program keeps 64-lane waves (one line per reason)
  1289. if wave == 64 && std::env::var_os("VICTORY_WAVE_WHY").is_some() {
  1290. let mut why: Vec<&str> = Vec::new();
  1291. for i in insts() {
  1292. let n = i.name();
  1293. let r = if n.starts_with("v_mbcnt") {
  1294. "v_mbcnt"
  1295. } else if n == "v_readlane_b32" {
  1296. "v_readlane"
  1297. } else if n == "v_writelane_b32" {
  1298. "v_writelane"
  1299. } else if n.starts_with("ds_permute") || n.starts_with("ds_bpermute") {
  1300. "ds_(b)permute"
  1301. } else if reads_mask_as_data(x.st, i) {
  1302. "mask as data"
  1303. } else {
  1304. continue;
  1305. };
  1306. if !why.contains(&r) {
  1307. why.push(r);
  1308. }
  1309. }
  1310. if lane_constant_masks(x.st) {
  1311. why.push("lane-constant mask");
  1312. }
  1313. if s.lds_dwords > 0 && group > 32 {
  1314. why.push("LDS in a group over 32");
  1315. match all_lane_blocks(x.st) {
  1316. None => why.push("an indirect exit"),
  1317. Some(all) if lds_meetings(p, x.st, &all).is_none() => {
  1318. why.push("an LDS read and write in one lane-branch region")
  1319. }
  1320. Some(_) => {}
  1321. }
  1322. }
  1323. why.sort_unstable();
  1324. eprintln!("WAVE64-WHY group={group} lds={} [{}]", s.lds_dwords > 0, why.join(", "));
  1325. }
  1326. }
  1327. if wave == 32 && x.native.wave64 {
  1328. // console threads go to host waves in the order the waves take them (`wave_base`)
  1329. halves = Some(s.lds_dwords);
  1330. s.lds_dwords += 1;
  1331. }
  1332. if console_lanes || one_wave && s.lds_dwords > 0 {
  1333. s.wave_size = Some(wave);
  1334. }
  1335. }
  1336. // The title's barriers a thread of the group may never reach, which
  1337. // leaves the others waiting on the host: those in blocks some lanes
  1338. // do not run, and all of them in a program with a loop closed by a
  1339. // plain jump (a lane still in it at the iteration limit leaves the
  1340. // program there, `abort_block`).
  1341. let fence_only: HashSet<usize> = if insts().any(|i| i.name() == "s_barrier") {
  1342. let order = crate::ir::reverse_postorder(&p.blocks);
  1343. let mut place = vec![usize::MAX; p.blocks.len()];
  1344. for (n, &b) in order.iter().enumerate() {
  1345. place[b] = n;
  1346. }
  1347. let back = |from: usize, to: usize| {
  1348. let at = |b: usize| place.get(b).copied().unwrap_or(usize::MAX);
  1349. at(from) != usize::MAX && at(to) <= at(from)
  1350. };
  1351. let cut_short = x
  1352. .st
  1353. .exits
  1354. .iter()
  1355. .enumerate()
  1356. .any(|(b, e)| matches!(*e, LaneExit::Jump(t) if back(b, t)));
  1357. let all = all_lane_blocks(x.st);
  1358. (0..p.blocks.len())
  1359. .filter(|&b| p.blocks[b].insts.iter().any(|i| i.name() == "s_barrier"))
  1360. .filter(|&b| {
  1361. cut_short
  1362. || all
  1363. .as_ref()
  1364. .is_none_or(|all| !all.get(b).copied().unwrap_or(false))
  1365. })
  1366. .collect()
  1367. } else {
  1368. HashSet::new()
  1369. };
  1370. let mut no_barrier = HashSet::new();
  1371. if let StageIo::Ms(ms) = &x.native.io {
  1372. s.prims = x.prims.clone();
  1373. s.threads = Some([ms.threads, 1, 1]);
  1374. s.lds_dwords = ms.lds_bytes.div_ceil(4);
  1375. s.mesh = Some(super::shader::Mesh {
  1376. max_vertices: ms.max_vertices,
  1377. max_primitives: ms.max_primitives,
  1378. topology: ms.topology,
  1379. });
  1380. // Barriers order the lanes' LDS accesses; the console's
  1381. // allocation request needs them too, but the host does not. One
  1382. // lane sends that request, and what it dominates (the path for
  1383. // counts out of range) runs in that lane alone, so its barrier
  1384. // would hang the host.
  1385. let order = crate::ir::reverse_postorder(&p.blocks);
  1386. let mut index = vec![usize::MAX; p.blocks.len()];
  1387. for (n, &b) in order.iter().enumerate() {
  1388. index[b] = n;
  1389. }
  1390. let idom = crate::ir::idoms(&p.blocks, &order, &index);
  1391. let alloc: Vec<usize> = (0..p.blocks.len())
  1392. .filter(|&b| {
  1393. p.blocks[b].insts.iter().any(|i| {
  1394. i.name() == "s_sendmsg"
  1395. && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == GS_ALLOC_REQ)
  1396. })
  1397. })
  1398. .collect();
  1399. for &b in &order {
  1400. let mut d = b;
  1401. let dominated = loop {
  1402. if alloc.contains(&d) {
  1403. break true;
  1404. }
  1405. if idom[d] == d || idom[d] == usize::MAX {
  1406. break false;
  1407. }
  1408. d = idom[d];
  1409. };
  1410. if ms.lds_bytes == 0 || dominated {
  1411. no_barrier.insert(b);
  1412. }
  1413. }
  1414. }
  1415. Lower {
  1416. s,
  1417. x,
  1418. bad,
  1419. lane_fail: HashMap::new(),
  1420. vals: HashMap::new(),
  1421. floats: HashMap::new(),
  1422. block: vec![None; p.blocks.len()],
  1423. cur: 0,
  1424. bools: HashMap::new(),
  1425. lane_bits: HashMap::new(),
  1426. phi_at,
  1427. mask_phis: HashMap::new(),
  1428. pending_masks: Vec::new(),
  1429. data_phis: Vec::new(),
  1430. read_phis: HashSet::new(),
  1431. stale: HashSet::new(),
  1432. params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(),
  1433. user_data: None,
  1434. user_reads: BTreeMap::new(),
  1435. samplers: Vec::new(),
  1436. descriptors: x
  1437. .res
  1438. .descriptors
  1439. .iter()
  1440. .map(|d| ((d.site, d.role == Role::Sampler), &d.source))
  1441. .collect(),
  1442. scalar: x.res.scalar.iter().copied().collect(),
  1443. exports: x.io.exports.iter().map(|e| (e.site, e)).collect(),
  1444. interps: x.io.interps.iter().map(|(s, i)| (*s, i)).collect(),
  1445. handles: HashMap::new(),
  1446. strides: HashMap::new(),
  1447. edges: HashMap::new(),
  1448. exported: vec![false; p.blocks.len()],
  1449. rpo: vec![usize::MAX; p.blocks.len()],
  1450. tail: vec![None; p.blocks.len()],
  1451. writes_uavs,
  1452. src0: None,
  1453. console_lanes,
  1454. split_lds,
  1455. lds_meet,
  1456. local: exchange.is_some() && LOCAL_WAVES.get(),
  1457. local_ok: false,
  1458. local_any: LOCAL_ANY.get(),
  1459. uniform: match &exchange {
  1460. Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all),
  1461. _ => HashSet::new(),
  1462. },
  1463. own_bits: match &exchange {
  1464. Some((_, false, _)) if !LOCAL_WAVES.get() && own_bits_on() => {
  1465. super::own_bits::find(p, x.st, std::env::var_os("VICTORY_WAVE_WHY").is_some())
  1466. }
  1467. _ => Default::default(),
  1468. },
  1469. exchange,
  1470. clane: None,
  1471. pair: None,
  1472. halves,
  1473. wave_base: None,
  1474. flat: None,
  1475. no_barrier,
  1476. fence_only,
  1477. half_outputs: half_outputs(&x.native.io, &x.outputs),
  1478. mask_data: match x.native.stage {
  1479. HwStage::Cs => MaskData::Console,
  1480. HwStage::Ps | HwStage::Vs => MaskData::Host,
  1481. _ => MaskData::None,
  1482. },
  1483. mask_ok: false,
  1484. ballots: HashMap::new(),
  1485. balloting: HashSet::new(),
  1486. def_block: p
  1487. .blocks
  1488. .iter()
  1489. .enumerate()
  1490. .flat_map(|(b, block)| {
  1491. block
  1492. .insts
  1493. .iter()
  1494. .flat_map(move |i| i.writes.iter().map(move |w| (w.1, b)))
  1495. .chain(block.phis.iter().map(move |phi| (phi.value, b)))
  1496. })
  1497. .collect(),
  1498. cur_ir: 0,
  1499. sections: HashMap::new(),
  1500. section_out: HashSet::new(),
  1501. code_table: None,
  1502. counters: HashMap::new(),
  1503. abort: None,
  1504. }
  1505. }
  1506. /// The dword of the program's code at byte `byte` (a constant table
  1507. /// the compiler appends to the code), as an internal constant array.
  1508. // shortcut: an index outside the table reads its last dword (the
  1509. // console would read whatever memory follows the code).
  1510. fn code_dword(&mut self, byte: V) -> Result<V, Why> {
  1511. let (g, base, len) = match self.code_table {
  1512. Some(t) => t,
  1513. None => {
  1514. let first = self
  1515. .x
  1516. .res
  1517. .scalar
  1518. .iter()
  1519. .map(|s| s.1)
  1520. .chain(self.x.res.descriptors.iter().flat_map(|d| {
  1521. d.source.leaves().into_iter().filter_map(|l| match l {
  1522. Source::Built { address, .. } => Some(*address),
  1523. _ => None,
  1524. })
  1525. }))
  1526. .filter(|a| a.param == CODE)
  1527. .map(|a| a.offset & !3)
  1528. .min()
  1529. .ok_or("a code table")?;
  1530. let code = &self.x.native.code;
  1531. let words: Vec<u32> = code
  1532. .get(first as usize..)
  1533. .ok_or("a code table past the code")?
  1534. .chunks(4)
  1535. .map(|c| {
  1536. let mut w = [0u8; 4];
  1537. w[..c.len()].copy_from_slice(c);
  1538. u32::from_le_bytes(w)
  1539. })
  1540. .collect();
  1541. if words.is_empty() {
  1542. return Err("a code table past the code");
  1543. }
  1544. let elems: Vec<V> = words.iter().map(|&w| self.s.m.i32(w)).collect();
  1545. let arr = self.s.m.array(words.len() as u32, self.s.t.i32);
  1546. let init = self.s.m.aggregate(arr, &elems);
  1547. let g = self.s.m.constant_global("code", init);
  1548. let t = (g, first, words.len() as u32);
  1549. self.code_table = Some(t);
  1550. t
  1551. }
  1552. };
  1553. let c = self.cur;
  1554. let k = self.s.m.i32(base);
  1555. let rel = self.s.m.bin(c, Bin::Sub, byte, k);
  1556. let two = self.s.m.i32(2);
  1557. let index = self.s.m.bin(c, Bin::LShr, rel, two);
  1558. let last = self.s.m.i32(len - 1);
  1559. let over = self.s.m.cmp(c, pred::IUGT, index, last);
  1560. let index = self.s.m.select(c, over, last, index);
  1561. let at = self.s.m.element(c, g, index);
  1562. Ok(self.s.m.load(c, at))
  1563. }
  1564. /// A global memory load (`global_load_*`): from the program's constant
  1565. /// table, or from a root SRV at the address the title sets.
  1566. fn flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  1567. let Fields::Flat { dst, .. } = &inst.fields else {
  1568. unreachable!()
  1569. };
  1570. let name = inst.name();
  1571. if self.scalar.get(&(b, i)).is_some_and(|a| a.param == MEMORY) {
  1572. return self.memory_flat(inst, b, i);
  1573. }
  1574. let rest = name
  1575. .strip_prefix("global_load_")
  1576. .ok_or("a global memory write")?;
  1577. let (n, sub) = match rest {
  1578. "dword" => (1, None),
  1579. "dwordx2" => (2, None),
  1580. "dwordx3" => (3, None),
  1581. "dwordx4" => (4, None),
  1582. "ubyte" => (1, Some((8, false))),
  1583. "sbyte" => (1, Some((8, true))),
  1584. "ushort" => (1, Some((16, false))),
  1585. "sshort" => (1, Some((16, true))),
  1586. _ => return Err(name),
  1587. };
  1588. let a = *self
  1589. .scalar
  1590. .get(&(b, i))
  1591. .ok_or("an untracked global address")?;
  1592. let guard = self.guard(b, i)?;
  1593. let Some(Operand::Vector { reg, .. }) = *dst else {
  1594. return Err("a global load result");
  1595. };
  1596. let c = self.cur;
  1597. let mut off = self.s.m.i32(a.offset);
  1598. if let Some(d) = a.dynamic {
  1599. let d = self.i32_of(d)?;
  1600. off = self.s.m.bin(c, Bin::Add, off, d);
  1601. }
  1602. let h = if a.param == CODE {
  1603. None
  1604. } else {
  1605. let src = Source::Built {
  1606. address: a,
  1607. bits: 0,
  1608. words: [0, 0],
  1609. };
  1610. if let Some(bias) = self.root_bias(a.param) {
  1611. off = self.s.m.bin(c, Bin::Add, off, bias);
  1612. }
  1613. Some(self.handle((b, i), &src, false, (11, 0))?)
  1614. };
  1615. let dword = |l: &mut Self, byte: V| -> Result<V, Why> {
  1616. match h {
  1617. None => l.code_dword(byte),
  1618. Some(h) => {
  1619. let c = l.cur;
  1620. let (u, mask, al) = (l.s.m.undef(l.s.t.i32), l.s.m.i8(1), l.s.m.i32(4));
  1621. let r = l.s.op(
  1622. c,
  1623. "rawBufferLoad.f32",
  1624. Attr::ReadOnly,
  1625. l.s.t.res_ret,
  1626. 139,
  1627. &[h, byte, u, mask, al],
  1628. );
  1629. let x = l.s.m.extract(c, r, 0);
  1630. Ok(l.as_int(x))
  1631. }
  1632. }
  1633. };
  1634. for k in 0..n {
  1635. let x = match sub {
  1636. None => {
  1637. let four = self.s.m.i32(4 * k);
  1638. let at = self.s.m.bin(c, Bin::Add, off, four);
  1639. dword(self, at)?
  1640. }
  1641. Some((width, signed)) => {
  1642. // shortcut: the field is taken not to cross a dword.
  1643. let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3));
  1644. let at = self.s.m.bin(c, Bin::And, off, not3);
  1645. let w = dword(self, at)?;
  1646. let byte = self.s.m.bin(c, Bin::And, off, three);
  1647. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  1648. let x = self.s.m.bin(c, Bin::LShr, w, sh);
  1649. let left = self.s.m.i32(32 - width);
  1650. let x = self.s.m.bin(c, Bin::Shl, x, left);
  1651. self.s
  1652. .m
  1653. .bin(c, if signed { Bin::AShr } else { Bin::LShr }, x, left)
  1654. }
  1655. };
  1656. self.write(inst, Reg::V(reg + k as u8), x, guard);
  1657. }
  1658. Ok(())
  1659. }
  1660. /// Finds the whole-wave sections and the values they leave.
  1661. fn find_sections(&mut self) {
  1662. let p = self.x.p;
  1663. let mut inside: HashMap<Value, (usize, usize, usize)> = HashMap::new();
  1664. for b in 0..p.blocks.len() {
  1665. let found = super::wave::sections(p, b);
  1666. for (&start, sec) in &found {
  1667. for i in start + 1..sec.end {
  1668. for &(_, w) in &p.blocks[b].insts[i].writes {
  1669. inside.insert(w, (b, start, sec.end));
  1670. }
  1671. }
  1672. }
  1673. if !found.is_empty() {
  1674. self.sections.insert(b, found);
  1675. }
  1676. }
  1677. if inside.is_empty() {
  1678. return;
  1679. }
  1680. for (b, block) in p.blocks.iter().enumerate() {
  1681. for phi in &block.phis {
  1682. self.section_out
  1683. .extend(phi.args.iter().filter(|a| inside.contains_key(a)));
  1684. }
  1685. for (i, inst) in block.insts.iter().enumerate() {
  1686. for &(_, r) in &inst.reads {
  1687. if let Some(&(sb, start, end)) = inside.get(&r)
  1688. && !(sb == b && i > start && i < end)
  1689. {
  1690. self.section_out.insert(r);
  1691. }
  1692. }
  1693. }
  1694. }
  1695. }
  1696. /// An instruction inside a whole-wave section: the values that leave
  1697. /// the section are made from what the simulation found them to be.
  1698. fn section_inst(&mut self, b: usize, i: usize, start: usize) {
  1699. const UNKNOWN: Why = "a whole-wave section step the simulation does not follow";
  1700. let inst = &self.x.p.blocks[b].insts[i];
  1701. for &(_, w) in &inst.writes {
  1702. let val = if self.section_out.contains(&w) {
  1703. let shape = self.sections[&b][&start].shapes.get(&w).copied();
  1704. let own = self.own_bits.totals.contains(&w);
  1705. match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh, own)) {
  1706. Ok(x) => Val::I32(x),
  1707. Err(why) => Val::Missing(why),
  1708. }
  1709. } else {
  1710. Val::Missing(UNKNOWN)
  1711. };
  1712. self.vals.insert(w, val);
  1713. }
  1714. }
  1715. /// A value a whole-wave section leaves, as DXIL wave operations over the
  1716. /// host's active lanes: the console's result with console lanes; on
  1717. /// another wave size, what the HLSL wave operation the console compiler
  1718. /// expanded gives on that wave.
  1719. ///
  1720. /// `own`: a wave OR that only steers a loop over each lane's own bits
  1721. /// ([`super::own_bits`]); where two host waves cannot exchange their halves' ORs it is
  1722. /// this host wave's.
  1723. fn shape(&mut self, shape: super::wave::Shape, own: bool) -> Result<V, Why> {
  1724. use super::wave::{Op, Shape};
  1725. let (op, src, mask, ident, prefix) = match shape {
  1726. Shape::K(k) => return Ok(self.s.m.i32(k)),
  1727. Shape::Value(v) => return self.i32_of(v),
  1728. Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None),
  1729. Shape::ActiveF64(lo, hi, mask, high) => {
  1730. return self.active_f64_sum(lo, hi, mask, high);
  1731. }
  1732. Shape::Masked(src, mask, ident) => {
  1733. let c = self.cur;
  1734. let &m = self
  1735. .x
  1736. .st
  1737. .masks
  1738. .get(&mask)
  1739. .ok_or("a wave reduction's untracked mask")?;
  1740. let on = self.boolean(m, c)?;
  1741. let x = self.i32_of(src)?;
  1742. let id = self.s.m.i32(ident);
  1743. return Ok(self.s.m.select(c, on, x, id));
  1744. }
  1745. Shape::Prefix(op, src, mask, ident, inclusive) => {
  1746. (op, src, mask, ident, Some(inclusive))
  1747. }
  1748. };
  1749. // Mesh: no host wave size can be declared, so a reduction is over this host wave
  1750. // only. A minimum or maximum is taken that way: the compiler's "next distinct
  1751. // value" loop (the wave's minimum, then the lanes that hold it) serves every
  1752. // lane however the lanes are divided into waves. A sum, a bit reduction or a
  1753. // prefix would be of part of a console wave: still refused.
  1754. if self.mask_data == MaskData::None
  1755. && (prefix.is_some()
  1756. || !matches!(
  1757. op,
  1758. Op::MinU | Op::MaxU | Op::MinI | Op::MaxI | Op::MinF | Op::MaxF
  1759. ))
  1760. {
  1761. return Err("a wave reduction in a mesh shader");
  1762. }
  1763. let c = self.cur;
  1764. let &m = self
  1765. .x
  1766. .st
  1767. .masks
  1768. .get(&mask)
  1769. .ok_or("a wave reduction's untracked mask")?;
  1770. let on = self.boolean(m, c)?;
  1771. let x = self.i32_of(src)?;
  1772. let id = self.s.m.i32(ident);
  1773. let x = self.s.m.select(c, on, x, id);
  1774. self.s.flags |= flags::WAVE_OPS;
  1775. if op == Op::AddH {
  1776. return match prefix {
  1777. Some(_) => Err("a wave prefix of an operation other than a sum"),
  1778. None => self.half_sum(x),
  1779. };
  1780. }
  1781. let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF);
  1782. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  1783. let arg = if float { self.as_float(x) } else { x };
  1784. let ty = if float { f32t } else { i32t };
  1785. let sfx = if float { "f32" } else { "i32" };
  1786. let r = match (op, prefix) {
  1787. (Op::AddU | Op::AddF, Some(inclusive)) => {
  1788. let (k0, k1) = (self.s.m.i8(0), self.s.m.i8(1));
  1789. let r = self.s.op(
  1790. c,
  1791. &format!("wavePrefixOp.{sfx}"),
  1792. Attr::NoUnwind,
  1793. ty,
  1794. 121,
  1795. &[arg, k0, k1],
  1796. );
  1797. if inclusive {
  1798. self.s.m.bin(c, Bin::Add, r, arg)
  1799. } else {
  1800. r
  1801. }
  1802. }
  1803. (_, Some(_)) => return Err("a wave prefix of an operation other than a sum"),
  1804. (Op::Or | Op::And | Op::Xor, None) => {
  1805. let k = self.s.m.i8(match op {
  1806. Op::And => 0,
  1807. Op::Or => 1,
  1808. _ => 2,
  1809. });
  1810. self.s
  1811. .op(c, "waveActiveBit.i32", Attr::NoUnwind, i32t, 120, &[arg, k])
  1812. }
  1813. (_, None) => {
  1814. let (code, unsigned) = match op {
  1815. Op::AddU => (0, 1),
  1816. Op::AddF => (0, 0),
  1817. Op::MinU => (2, 1),
  1818. Op::MaxU => (3, 1),
  1819. Op::MinI | Op::MinF => (2, 0),
  1820. _ => (3, 0),
  1821. };
  1822. let (k, u) = (self.s.m.i8(code), self.s.m.i8(unsigned));
  1823. self.s.op(
  1824. c,
  1825. &format!("waveActiveOp.{sfx}"),
  1826. Attr::NoUnwind,
  1827. ty,
  1828. 119,
  1829. &[arg, k, u],
  1830. )
  1831. }
  1832. };
  1833. // two host waves of 32 hold the console's 64 lanes: their results combine
  1834. let r = if self.local || self.exchange.as_ref().is_some_and(|e| e.1) {
  1835. // this host wave's own result (and prefix): each wave on its own, or a group of
  1836. // 32 threads or fewer, which one host wave holds whole (combining with the 0 a
  1837. // missing half "gives" broke AND, MIN and signed MAX)
  1838. r
  1839. } else if own && prefix.is_none() && op == Op::Or && !self.all_lanes(self.cur_ir) {
  1840. // each thread walks the bits of this value and works only at its own, which the
  1841. // host wave's OR holds: the same run as with the console wave's OR
  1842. r
  1843. } else if self.exchange.is_some() {
  1844. if !self.all_lanes(self.cur_ir) {
  1845. need(self.cur_ir);
  1846. return Err("a wave reduction where not every lane runs");
  1847. }
  1848. let bits = |l: &mut Self, v: V| if float { l.as_int(v) } else { v };
  1849. let back = |l: &mut Self, v: V| if float { l.as_float(v) } else { v };
  1850. match prefix {
  1851. Some(_) => {
  1852. // the upper half adds the lower half's total to its prefix
  1853. let (k0, ku) = (self.s.m.i8(0), self.s.m.i8(u8::from(!float)));
  1854. let total = self.s.op(c, &format!("waveActiveOp.{sfx}"), Attr::NoUnwind, ty, 119, &[arg, k0, ku]);
  1855. let tb = bits(self, total);
  1856. let c = self.cur;
  1857. let (lo, _) = self.exchange_halves(c, tb);
  1858. let lo = back(self, lo);
  1859. let cl = self.console_lane();
  1860. let k32 = self.s.m.i32(32);
  1861. let upper = self.s.m.cmp(c, pred::IUGE, cl, k32);
  1862. let zero = if float { self.s.m.f32(0) } else { self.s.m.i32(0) };
  1863. let add = self.s.m.select(c, upper, lo, zero);
  1864. self.s.m.bin(c, Bin::Add, r, add)
  1865. }
  1866. None => {
  1867. let rb = bits(self, r);
  1868. let c = self.cur;
  1869. let (lo, hi) = self.exchange_halves(c, rb);
  1870. let (lo, hi) = (back(self, lo), back(self, hi));
  1871. match op {
  1872. Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, lo, hi),
  1873. Op::Or => self.s.m.bin(c, Bin::Or, lo, hi),
  1874. Op::And => self.s.m.bin(c, Bin::And, lo, hi),
  1875. Op::Xor => self.s.m.bin(c, Bin::Xor, lo, hi),
  1876. _ => {
  1877. // FMax 35, FMin 36, IMax 37, IMin 38, UMax 39, UMin 40
  1878. let code = match op {
  1879. Op::MaxF => 35,
  1880. Op::MinF => 36,
  1881. Op::MinU => 40,
  1882. Op::MaxU => 39,
  1883. Op::MinI => 38,
  1884. _ => 37,
  1885. };
  1886. self.s.op(c, &format!("binary.{sfx}"), Attr::ReadNone, ty, code, &[lo, hi])
  1887. }
  1888. }
  1889. }
  1890. }
  1891. } else {
  1892. r
  1893. };
  1894. Ok(if float { self.as_int(r) } else { r })
  1895. }
  1896. /// `WaveActiveSum` of 64-bit floats (`f64(lo, hi)` in active lanes, `+0.0` elsewhere),
  1897. /// returning the low (`!high`) or high (`high`) 32-bit word.
  1898. fn active_f64_sum(
  1899. &mut self,
  1900. lo: Value,
  1901. hi: Value,
  1902. mask: Value,
  1903. high: bool,
  1904. ) -> Result<V, Why> {
  1905. if self.mask_data == MaskData::None {
  1906. return Err("a wave reduction in a mesh shader");
  1907. }
  1908. let c = self.cur;
  1909. let &m = self
  1910. .x
  1911. .st
  1912. .masks
  1913. .get(&mask)
  1914. .ok_or("a wave reduction's untracked mask")?;
  1915. let on = self.boolean(m, c)?;
  1916. let lo = self.i32_of(lo)?;
  1917. let hi = self.i32_of(hi)?;
  1918. let z = self.s.m.i32(0);
  1919. let lo = self.s.m.select(c, on, lo, z);
  1920. let hi = self.s.m.select(c, on, hi, z);
  1921. self.s.flags |= flags::WAVE_OPS | flags::DOUBLES;
  1922. let f64t = self.s.m.double();
  1923. let i32t = self.s.t.i32;
  1924. let split_ty = self
  1925. .s
  1926. .m
  1927. .named_struct("dx.types.splitdouble", vec![i32t, i32t]);
  1928. let arg = self
  1929. .s
  1930. .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]);
  1931. let (k0, k0b) = (self.s.m.i8(0), self.s.m.i8(0));
  1932. let sum = self
  1933. .s
  1934. .op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[arg, k0, k0b]);
  1935. let split = self
  1936. .s
  1937. .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[sum]);
  1938. let mut r_lo = self.s.m.extract(c, split, 0);
  1939. let mut r_hi = self.s.m.extract(c, split, 1);
  1940. if self.exchange.is_some() {
  1941. if !self.all_lanes(self.cur_ir) {
  1942. need(self.cur_ir);
  1943. return Err("a wave reduction where not every lane runs");
  1944. }
  1945. let (lo0, lo1) = self.exchange_halves(self.cur, r_lo);
  1946. let (hi0, hi1) = self.exchange_halves(self.cur, r_hi);
  1947. let c = self.cur;
  1948. let d0 = self
  1949. .s
  1950. .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo0, hi0]);
  1951. let d1 = self
  1952. .s
  1953. .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo1, hi1]);
  1954. let total = self.s.m.bin(c, Bin::Add, d0, d1);
  1955. let split = self
  1956. .s
  1957. .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[total]);
  1958. r_lo = self.s.m.extract(c, split, 0);
  1959. r_hi = self.s.m.extract(c, split, 1);
  1960. }
  1961. Ok(if high { r_hi } else { r_lo })
  1962. }
  1963. /// The sum of two 16-bit floats (the low halves of `a` and `b`) as the console's
  1964. /// `v_add_f16` gives it: added in f32 and rounded to 16 bits, to nearest
  1965. /// ([`Self::f16_nearest`]).
  1966. fn add_halves(&mut self, a: V, b: V) -> V {
  1967. let c = self.cur;
  1968. let f32t = self.s.t.f32;
  1969. let low = self.s.m.i32(0xFFFF);
  1970. let wide = |l: &mut Self, x: V| {
  1971. let h = l.s.m.bin(c, Bin::And, x, low);
  1972. l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h])
  1973. };
  1974. let (fa, fb) = (wide(self, a), wide(self, b));
  1975. let f = self.s.m.bin(c, Bin::Add, fa, fb);
  1976. self.f16_nearest(f)
  1977. }
  1978. /// `WaveActiveSum` of 16-bit floats (`x`: each lane's term in its low half, +0 in the
  1979. /// lanes outside the mask), bit for bit as the console adds it: every addition rounds to
  1980. /// 16 bits, so the order counts, and the compiler's is the balanced tree over the lanes
  1981. /// in their order (lanes 2k and 2k+1, then pairs, ... then the wave's two halves;
  1982. /// [`super::wave::buddies`]). Each lane adds its partner's partial sum, read from the
  1983. /// lane whose number differs in one bit, step by step; two host waves of 32 then exchange
  1984. /// their halves' sums for the last addition. The high half of the result is lane 0's,
  1985. /// which no `v_add_f16` writes.
  1986. /// That needs every lane of a full wave there to be read: refused where not every lane
  1987. /// runs, in a thread group that does not fill its waves, and for each half-wave on its
  1988. /// own (half a sum is no sum).
  1989. fn half_sum(&mut self, x: V) -> Result<V, Why> {
  1990. const WHERE: Why = "a wave sum of 16-bit floats where not every lane runs";
  1991. let threads = self.s.threads.ok_or("a wave sum of 16-bit floats outside compute")?;
  1992. if threads.iter().product::<u32>() % 64 != 0 {
  1993. return Err("a wave sum of 16-bit floats in a wave that is not full");
  1994. }
  1995. if self.local {
  1996. return Err("a wave sum of 16-bit floats in a half-wave");
  1997. }
  1998. // two host waves of 32 that exchange, or one host wave of 64 lanes
  1999. let halves = match (&self.exchange, self.s.wave_size) {
  2000. (Some((_, false, _)), _) => true,
  2001. (None, Some(64)) if self.x.p.wave64 => false,
  2002. _ => return Err("a wave sum of 16-bit floats on these waves"),
  2003. };
  2004. let every = if halves {
  2005. self.all_lanes(self.cur_ir)
  2006. } else {
  2007. all_lane_blocks(self.x.st).is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false))
  2008. };
  2009. if !every {
  2010. if halves {
  2011. need(self.cur_ir);
  2012. }
  2013. return Err(WHERE);
  2014. }
  2015. let c = self.cur;
  2016. let i32t = self.s.t.i32;
  2017. let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  2018. let mut sum = x;
  2019. for step in 0..if halves { 5 } else { 6 } {
  2020. let bit = self.s.m.i32(1 << step);
  2021. let partner = self.s.m.bin(c, Bin::Xor, lane, bit);
  2022. let theirs = self.read_lane(sum, partner);
  2023. sum = self.add_halves(sum, theirs);
  2024. }
  2025. let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0));
  2026. let first = self.read_lane(x, zero);
  2027. let first = self.s.m.bin(c, Bin::And, first, high);
  2028. let sum = self.s.m.bin(c, Bin::And, sum, low);
  2029. let mine = self.s.m.bin(c, Bin::Or, first, sum);
  2030. if !halves {
  2031. return Ok(mine);
  2032. }
  2033. let (lo, hi) = self.exchange_halves(c, mine);
  2034. let c = self.cur;
  2035. let total = self.add_halves(lo, hi);
  2036. let total = self.s.m.bin(c, Bin::And, total, low);
  2037. let first = self.s.m.bin(c, Bin::And, lo, high);
  2038. Ok(self.s.m.bin(c, Bin::Or, first, total))
  2039. }
  2040. fn run(mut self) -> Result<Lowered, Stop> {
  2041. let p = self.x.p;
  2042. let order = crate::ir::reverse_postorder(&p.blocks);
  2043. for (n, &b) in order.iter().enumerate() {
  2044. self.rpo[b] = n;
  2045. }
  2046. for (n, &b) in order.iter().enumerate() {
  2047. self.block[b] = Some(if n == 0 {
  2048. self.s.entry
  2049. } else {
  2050. self.s.m.new_block()
  2051. });
  2052. }
  2053. // Loop headers count iterations (`LOOP_LIMIT`).
  2054. for &b in &order {
  2055. let header = p.blocks[b]
  2056. .preds
  2057. .iter()
  2058. .any(|&q| self.block[q].is_some() && self.rpo[b] <= self.rpo[q]);
  2059. if header {
  2060. let blk = self.block[b].expect("reachable");
  2061. let phi = self.s.m.phi(blk, self.s.t.i32);
  2062. self.counters.insert(b, (phi, Vec::new()));
  2063. }
  2064. }
  2065. self.cur = self.s.entry;
  2066. self.find_sections();
  2067. self.inputs()?;
  2068. if let Some(mesh) = self.s.mesh {
  2069. self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?;
  2070. self.block[order[0]] = Some(self.cur);
  2071. }
  2072. for &b in &order {
  2073. self.cur = self.block[b].expect("reachable");
  2074. self.cur_ir = b;
  2075. let preds: Vec<usize> = p.blocks[b]
  2076. .preds
  2077. .iter()
  2078. .copied()
  2079. .filter(|&q| self.block[q].is_some())
  2080. .collect();
  2081. self.exported[b] = !preds.is_empty() && preds.iter().all(|&q| self.exported_out(q));
  2082. for (i, phi) in p.blocks[b].phis.iter().enumerate() {
  2083. let val = match phi.reg {
  2084. Reg::S(c) if c == EXEC || c == EXEC + 1 => Val::Missing("a lane mask"),
  2085. _ if self.bad.contains_key(&phi.value) => Val::Missing(self.bad[&phi.value]),
  2086. Reg::Scc => {
  2087. let v = self.s.m.phi(self.cur, self.s.t.i1);
  2088. self.data_phis.push((v, b, i));
  2089. Val::Bit(v)
  2090. }
  2091. _ => {
  2092. let v = self.s.m.phi(self.cur, self.s.t.i32);
  2093. self.data_phis.push((v, b, i));
  2094. Val::I32(v)
  2095. }
  2096. };
  2097. self.vals.insert(phi.value, val);
  2098. }
  2099. if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].0) {
  2100. self.lds_meeting();
  2101. }
  2102. let mut i = 0;
  2103. while i < p.blocks[b].insts.len() {
  2104. self.inst(b, i)?;
  2105. if let Some(end) = self.sections.get(&b).and_then(|s| s.get(&i)).map(|s| s.end) {
  2106. for j in i + 1..end {
  2107. self.section_inst(b, j, i);
  2108. }
  2109. i = end;
  2110. continue;
  2111. }
  2112. i += 1;
  2113. }
  2114. self.mask_ok = self.mask_data == MaskData::Console;
  2115. if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].1) {
  2116. self.lds_meeting();
  2117. }
  2118. self.tail[b] = Some(self.cur);
  2119. self.exit(b)?;
  2120. }
  2121. self.fill_phis()?;
  2122. let user_data = self.user_reads.values().copied().collect();
  2123. self.s.samplers = self.samplers.len() as u32;
  2124. let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect();
  2125. let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect();
  2126. let root_uavs = self.s.root_uavs.iter().map(|r| r.0).collect();
  2127. let cmp_samplers = self.s.cmp_samplers;
  2128. let wave_size = self.s.wave_size;
  2129. Ok(Lowered {
  2130. wave_size,
  2131. cmp_samplers,
  2132. root_cbvs,
  2133. root_srvs,
  2134. root_uavs,
  2135. #[cfg(test)]
  2136. nonuniform_handles: self.s.nonuniform_handles,
  2137. #[cfg(test)]
  2138. wave_ops: self.s.flags & flags::WAVE_OPS != 0,
  2139. dxil: self.s.finish(),
  2140. user_data,
  2141. samplers: self.samplers,
  2142. })
  2143. }
  2144. fn exported_out(&self, b: usize) -> bool {
  2145. self.exported[b] || self.has_done_export(b)
  2146. }
  2147. fn has_done_export(&self, b: usize) -> bool {
  2148. (0..self.x.p.blocks[b].insts.len())
  2149. .any(|i| self.exports.get(&(b, i)).is_some_and(|e| e.done))
  2150. }
  2151. /// Values of the program's input registers.
  2152. fn inputs(&mut self) -> Result<(), Stop> {
  2153. let io_inputs: HashMap<Value, Input> = self.x.io.inputs.iter().copied().collect();
  2154. for &(reg, v) in &self.x.p.inputs {
  2155. let val = match reg {
  2156. Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use
  2157. // Most programs only interpolate with them: loaded on first
  2158. // use as a value (`get`).
  2159. Reg::V(_) if matches!(io_inputs.get(&v), Some(Input::Barycentric { .. })) => {
  2160. continue;
  2161. }
  2162. Reg::S(n) => match io_inputs.get(&v) {
  2163. Some(&input) => self.input(input),
  2164. // Above the SGPRs the hardware initializes, a register
  2165. // holds what the last wave left, so no program depends
  2166. // on it: a read the paths only seem to allow (a branch
  2167. // past the write, taken only with one past the read)
  2168. // reads zero, as VGPRs do.
  2169. None if n <= 105 && self.x.io.initialized_sgprs.is_some_and(|k| n >= k) => {
  2170. Val::I32(self.s.m.i32(0))
  2171. }
  2172. // A scalar parked in a VGPR lane (`ir::unspill`), read where the
  2173. // paths only seem to allow it before any save: the lane of a VGPR
  2174. // nobody wrote, and VGPRs nobody set read as zero.
  2175. None if n >= crate::ir::PARKED => Val::I32(self.s.m.i32(0)),
  2176. None => Val::Missing("a hardware SGPR input"),
  2177. },
  2178. Reg::Scc => Val::Missing("SCC on entry"),
  2179. Reg::V(_) => match io_inputs.get(&v) {
  2180. Some(&input) => self.input(input),
  2181. // Registers no one set read as zero (the validator
  2182. // refuses reads of undef).
  2183. None => Val::I32(self.s.m.i32(0)),
  2184. },
  2185. };
  2186. self.vals.insert(v, val);
  2187. }
  2188. Ok(())
  2189. }
  2190. fn input(&mut self, input: Input) -> Val {
  2191. let (kind, col) = match input {
  2192. Input::VertexId => (1, 0),
  2193. Input::InstanceId => (2, 0),
  2194. Input::Position(c) => (3, c),
  2195. Input::Attribute { row, channel } => {
  2196. return match self.find_input(row, channel) {
  2197. Some((id, col)) => self.load_input(id, col),
  2198. None => Val::Missing("a vertex input the signature lacks"),
  2199. };
  2200. }
  2201. Input::Barycentric { kind, index } => return self.barycentric(kind, index),
  2202. Input::PrimitiveId => return Val::Missing("the primitive id"),
  2203. // The console code tests it against 0 (`v_cmp_ne_u32`), as the
  2204. // host's value can be.
  2205. Input::FrontFace => (13, 0),
  2206. Input::ThreadIdInGroup(c) => return self.thread_id(c),
  2207. Input::GroupId(c) => return self.compute_id("groupId.i32", 94, c),
  2208. Input::GroupInfo => return Val::Missing("the thread-group info SGPR"),
  2209. Input::MeshGroup => {
  2210. let Val::I32(g) = self.compute_id("groupId.i32", 94, 0) else {
  2211. unreachable!()
  2212. };
  2213. let n = self.s.m.i32(self.x.mesh_stride);
  2214. return Val::I32(self.s.m.bin(self.s.entry, Bin::Mul, g, n));
  2215. }
  2216. Input::MergedWaveInfo => {
  2217. // shortcut: only the wave index (bits 24-27) is set; the
  2218. // console's other bits (lane counts) are read by no program.
  2219. let f = self.mesh_thread();
  2220. let shift = self.s.m.i32(self.wave().trailing_zeros());
  2221. let w = self.s.m.bin(self.s.entry, Bin::LShr, f, shift);
  2222. let k24 = self.s.m.i32(24);
  2223. return Val::I32(self.s.m.bin(self.s.entry, Bin::Shl, w, k24));
  2224. }
  2225. _ => return Val::Missing("a pixel system input"),
  2226. };
  2227. let free = self
  2228. .s
  2229. .inputs
  2230. .iter()
  2231. .filter_map(|e| e.row)
  2232. .map(|r| r + 1)
  2233. .max()
  2234. .unwrap_or(0);
  2235. let id = match self.s.inputs.iter().position(|e| e.kind == kind) {
  2236. Some(id) => {
  2237. if kind != 3 {
  2238. self.s.inputs[id].row.get_or_insert(free);
  2239. }
  2240. id
  2241. }
  2242. None if kind >= 3 => return Val::Missing("a pixel system input the signature lacks"),
  2243. None => {
  2244. // The console signature leaves out vertex and instance ids; PC
  2245. // gives them a row after the others.
  2246. let row = self
  2247. .s
  2248. .inputs
  2249. .iter()
  2250. .filter_map(|e| e.row)
  2251. .map(|r| r + 1)
  2252. .max()
  2253. .unwrap_or(0);
  2254. self.s.inputs.push(SigElement {
  2255. name: ["", "SV_VertexID", "SV_InstanceID"][kind as usize].into(),
  2256. index: 0,
  2257. kind,
  2258. comp: 5,
  2259. interp: 0,
  2260. row: Some(row),
  2261. col: 0,
  2262. cols: 1,
  2263. usage: 0,
  2264. half: false,
  2265. });
  2266. self.s.inputs.len() - 1
  2267. }
  2268. };
  2269. self.load_input(id, col)
  2270. }
  2271. /// A component of a compute thread or group id, read in the entry block.
  2272. fn compute_id(&mut self, name: &str, opcode: u32, c: u8) -> Val {
  2273. let (entry, c) = (self.s.entry, self.s.m.i32(u32::from(c)));
  2274. Val::I32(
  2275. self.s
  2276. .op(entry, name, Attr::ReadNone, self.s.t.i32, opcode, &[c]),
  2277. )
  2278. }
  2279. fn find_input(&self, row: u8, channel: u8) -> Option<(usize, u8)> {
  2280. self.s.inputs.iter().enumerate().find_map(|(id, e)| {
  2281. let r = e.row?;
  2282. // `then`, not `then_some`: the channel is only past `col` when
  2283. // the condition holds.
  2284. (r == u32::from(row) && channel >= e.col && channel < e.col + e.cols)
  2285. .then(|| (id, channel - e.col))
  2286. })
  2287. }
  2288. fn load_input(&mut self, id: usize, col: u8) -> Val {
  2289. if self.s.inputs[id].half {
  2290. // shortcut: 16-bit vertex inputs (the fetch routine's) are not
  2291. // unpacked; pixel inputs are (`interp`).
  2292. return Val::Missing("a 16-bit input");
  2293. }
  2294. self.load_any_input(id, col)
  2295. }
  2296. /// An input element's channel as declared (16-bit ones as 32-bit floats).
  2297. fn load_any_input(&mut self, id: usize, col: u8) -> Val {
  2298. let e = &mut self.s.inputs[id];
  2299. e.usage |= 1 << col;
  2300. let (int, bit) = (e.comp != 9, e.comp == 1);
  2301. let ty = if bit {
  2302. self.s.t.i1
  2303. } else if int {
  2304. self.s.t.i32
  2305. } else {
  2306. self.s.t.f32
  2307. };
  2308. let suffix = if bit {
  2309. ".i1"
  2310. } else if int {
  2311. ".i32"
  2312. } else {
  2313. ".f32"
  2314. };
  2315. let entry = self.s.entry;
  2316. let args = [
  2317. self.s.m.i32(id as u32),
  2318. self.s.m.i32(0),
  2319. self.s.m.i8(col),
  2320. self.s.m.undef(self.s.t.i32),
  2321. ];
  2322. let v = self.s.op(
  2323. entry,
  2324. &format!("loadInput{suffix}"),
  2325. Attr::ReadNone,
  2326. ty,
  2327. 4,
  2328. &args,
  2329. );
  2330. if bit {
  2331. let z = self.s.m.cast(entry, Cast::ZExt, v, self.s.t.i32);
  2332. Val::I32(z)
  2333. } else if int {
  2334. Val::I32(v)
  2335. } else {
  2336. Val::I32(self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.i32))
  2337. }
  2338. }
  2339. /// The DXIL form of an IR value.
  2340. fn get(&mut self, v: Value) -> Result<Val, Why> {
  2341. if self.phi_at.contains_key(&v) {
  2342. self.read_phis.insert(v);
  2343. }
  2344. let is_mask = self.x.st.masks.contains_key(&v) || self.x.st.highs.contains_key(&v);
  2345. match self.vals.get(&v) {
  2346. Some(&Val::Missing(_)) | None if self.mask_ok && is_mask => {
  2347. return self.mask_dword(v).map(Val::I32);
  2348. }
  2349. Some(&Val::Missing(w)) => return Err(w),
  2350. Some(&val) => return Ok(val),
  2351. None => {}
  2352. }
  2353. if let Some(&(param, dword)) = self.params.get(&v) {
  2354. let val = self.user(param, dword);
  2355. self.vals.insert(v, val);
  2356. return Ok(val);
  2357. }
  2358. if let Some(loaded) = self.lazy_barycentric(v) {
  2359. loaded?;
  2360. return Ok(self.vals[&v]);
  2361. }
  2362. Err("a value defined after its use")
  2363. }
  2364. /// Loads `v` if it is a barycentric input VGPR not loaded yet (see
  2365. /// `inputs`): `None` if it is not one.
  2366. fn lazy_barycentric(&mut self, v: Value) -> Option<Result<(), Why>> {
  2367. let (kind, index) = self.x.io.inputs.iter().find_map(|&(w, i)| match i {
  2368. Input::Barycentric { kind, index } if w == v => Some((kind, index)),
  2369. _ => None,
  2370. })?;
  2371. let val = self.barycentric(kind, index);
  2372. self.vals.insert(v, val);
  2373. Some(match val {
  2374. Val::Missing(w) => Err(w),
  2375. _ => Ok(()),
  2376. })
  2377. }
  2378. /// Barycentric `index` (0 i, 1 j) of `kind` as a value: a channel of
  2379. /// `SV_Barycentrics` declared with the same interpolation mode.
  2380. ///
  2381. /// GFX10 interpolates P0 + i (P1 - P0) + j (P2 - P0), so i and j are
  2382. /// the weights of vertices 1 and 2. The host's weights (x, y, z) are
  2383. /// those of vertices 0, 1 and 2, vertex 0 being the provoking vertex,
  2384. /// which is the console's P0 (`v_interp_mov` P0 is lowered to a flat
  2385. /// input): i is y and j is z.
  2386. /// shortcut: triangles only; on lines and points the console's i and j
  2387. /// are not checked against the host's weights.
  2388. fn barycentric(&mut self, kind: Barycentric, index: u8) -> Val {
  2389. let Some(mode) = interp_mode(kind) else {
  2390. return Val::Missing("pull-model barycentrics");
  2391. };
  2392. if index > 1 {
  2393. return Val::Missing("pull-model barycentrics");
  2394. }
  2395. // One element per interpolation mode (the console's own, if its
  2396. // signature declares one): DXIL allows two.
  2397. let bary = |e: &SigElement| e.kind == 28;
  2398. let id = match self
  2399. .s
  2400. .inputs
  2401. .iter()
  2402. .position(|e| bary(e) && (e.interp == mode || e.usage == 0))
  2403. {
  2404. Some(id) => id,
  2405. None => {
  2406. let index = self.s.inputs.iter().filter(|e| bary(e)).count() as u32;
  2407. if index >= 2 {
  2408. return Val::Missing("barycentrics of a third interpolation mode");
  2409. }
  2410. // A system value the validator wants unpacked (packing
  2411. // location -1), like other non-packed system values.
  2412. self.s.inputs.push(SigElement {
  2413. name: "SV_Barycentrics".into(),
  2414. index,
  2415. kind: 28,
  2416. comp: 9,
  2417. interp: mode,
  2418. row: None,
  2419. col: 0,
  2420. cols: 3,
  2421. usage: 0,
  2422. half: false,
  2423. });
  2424. self.s.inputs.len() - 1
  2425. }
  2426. };
  2427. let e = &mut self.s.inputs[id];
  2428. if e.col != 0 || e.cols < 3 {
  2429. return Val::Missing("a console barycentrics element without i and j");
  2430. }
  2431. e.row = None;
  2432. e.interp = mode;
  2433. self.s.flags |= flags::BARYCENTRICS;
  2434. self.load_any_input(id, index + 1)
  2435. }
  2436. fn i32_of(&mut self, v: Value) -> Result<V, Why> {
  2437. match self.get(v)? {
  2438. Val::I32(x) => Ok(x),
  2439. Val::Bit(x) => Ok(self.s.m.cast(self.cur, Cast::ZExt, x, self.s.t.i32)),
  2440. Val::Missing(w) => Err(w),
  2441. }
  2442. }
  2443. /// A user-data dword: a root parameter's value.
  2444. fn user(&mut self, param: usize, dword: u32) -> Val {
  2445. let rp = self.x.native.layout[param];
  2446. match rp.root {
  2447. RootType::ResourceHeap | RootType::SamplerHeap => return Val::I32(self.s.m.i32(0)),
  2448. RootType::Constants | RootType::Table => {}
  2449. _ => return Val::Missing("a root descriptor"),
  2450. }
  2451. let index = u32::from(rp.user_data) + dword - self.user_first();
  2452. self.user_reads.insert(
  2453. index,
  2454. UserData {
  2455. index,
  2456. slot: rp.slot,
  2457. root: rp.root,
  2458. dword,
  2459. },
  2460. );
  2461. Val::I32(self.user_at(index))
  2462. }
  2463. /// The user-data index that is dword 0 of the host's user data: 0, or
  2464. /// 16 for a program with a spilled user-data table, whose parameters
  2465. /// all sit at 16 and above. (The host's root signature has 64 dwords:
  2466. /// a builder stage with constants up to index 45, eight root views,
  2467. /// their biases and the memory directory would not fit with 16 dwords
  2468. /// nothing reads in front.)
  2469. fn user_first(&self) -> u32 {
  2470. if crate::spill::is_spilled(self.x.native) {
  2471. 16
  2472. } else {
  2473. 0
  2474. }
  2475. }
  2476. /// A user-data dword no register of the console's holds: one the host
  2477. /// computes when it binds (`root` says what, an `Other` code of
  2478. /// `shader.rs`), placed after the layout's own dwords.
  2479. fn host_word(&mut self, root: RootType, slot: u8, dword: u32) -> V {
  2480. let known = self
  2481. .user_reads
  2482. .values()
  2483. .find(|u| u.root == root && u.slot == slot && u.dword == dword)
  2484. .map(|u| u.index);
  2485. let index = match known {
  2486. Some(index) => index,
  2487. None => {
  2488. let first = self.user_first();
  2489. let layout = &self.x.native.layout;
  2490. let mut index = layout
  2491. .iter()
  2492. .map(|e| u32::from(e.user_data) + e.sgprs)
  2493. .max()
  2494. .unwrap_or(0)
  2495. .saturating_sub(first);
  2496. while self.user_reads.contains_key(&index) {
  2497. index += 1;
  2498. }
  2499. self.user_reads.insert(
  2500. index,
  2501. UserData {
  2502. index,
  2503. slot,
  2504. root,
  2505. dword,
  2506. },
  2507. );
  2508. index
  2509. }
  2510. };
  2511. self.user_at(index)
  2512. }
  2513. /// User-data dword `index`, loaded in the entry block.
  2514. fn user_at(&mut self, index: u32) -> V {
  2515. self.s.user_data = self.s.user_data.max(index + 1);
  2516. let h = match self.user_data {
  2517. Some(h) => h,
  2518. None => {
  2519. let h = self.s.user_data_handle();
  2520. self.user_data = Some(h);
  2521. h
  2522. }
  2523. };
  2524. let entry = self.s.entry;
  2525. let row = self.s.m.i32(index / 4);
  2526. let r = self.s.op(
  2527. entry,
  2528. "cbufferLoadLegacy.i32",
  2529. Attr::ReadOnly,
  2530. self.s.t.cbuf_ret,
  2531. 59,
  2532. &[h, row],
  2533. );
  2534. self.s.m.extract(entry, r, index % 4)
  2535. }
  2536. /// Whether some instruction computes with `v` (scalar or vector
  2537. /// arithmetic), rather than only naming it in a descriptor operand,
  2538. /// moving it (at most `depth` moves are followed) or comparing it: a
  2539. /// waterfall loop keeps a descriptor's dwords per lane, reads the first
  2540. /// lane's back and compares the lanes' with them.
  2541. fn computed_with(&self, v: Value, depth: u32) -> bool {
  2542. self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| {
  2543. if !i.reads.iter().any(|r| r.1 == v) {
  2544. return false;
  2545. }
  2546. let name = i.name();
  2547. let moves = matches!(
  2548. name,
  2549. "s_mov_b32"
  2550. | "s_mov_b64"
  2551. | "v_mov_b32"
  2552. | "v_readfirstlane_b32"
  2553. | "v_readlane_b32"
  2554. | "v_writelane_b32"
  2555. | "v_cndmask_b32"
  2556. );
  2557. match &i.fields {
  2558. Fields::Sop { .. } | Fields::Valu(_) if moves => {
  2559. depth > 0 && i.writes.iter().any(|w| self.computed_with(w.1, depth - 1))
  2560. }
  2561. Fields::Sop { .. } | Fields::Valu(_) => {
  2562. !(name.starts_with("v_cmp") || name.starts_with("s_cmp"))
  2563. }
  2564. _ => false,
  2565. }
  2566. })
  2567. }
  2568. /// The title address (low dword, bits from 32 up) of the buffer view
  2569. /// whose descriptor the scalar load at `site` reads from the start of
  2570. /// a table entry, as the host tells it when it binds (`shader.rs`
  2571. /// `USER_VIEW_ADDRESS`); none for anything else. (The console's
  2572. /// descriptor holds more in the second dword, the stride from bit 16
  2573. /// up; code that takes the address masks those away.)
  2574. fn view_address(&mut self, site: Site) -> Option<(V, V)> {
  2575. use super::shader::USER_VIEW_ADDRESS;
  2576. let a = self.scalar.get(&site).copied()?;
  2577. let rp = *self.x.native.layout.get(a.param)?;
  2578. if rp.root != RootType::Table || a.dynamic.is_some() || a.offset % 32 != 0 {
  2579. return None;
  2580. }
  2581. let dword = a.offset / 4;
  2582. let used = self
  2583. .x
  2584. .native
  2585. .used
  2586. .iter()
  2587. .filter(|u| {
  2588. u.root == RootType::Table
  2589. && u.user_data == rp.user_data
  2590. && u.table_offset_dwords <= dword
  2591. })
  2592. .max_by_key(|u| u.table_offset_dwords)?;
  2593. if used.dwords != 4 || !matches!(used.kind, ResourceType::Srv | ResourceType::Uav) {
  2594. return None;
  2595. }
  2596. let lo = self.host_word(RootType::Other(USER_VIEW_ADDRESS), rp.slot, dword);
  2597. let hi = self.host_word(RootType::Other(USER_VIEW_ADDRESS + 1), rp.slot, dword);
  2598. Some((lo, hi))
  2599. }
  2600. /// `lo`, `hi` plus the instruction's byte offset `off`, with the carry.
  2601. fn address_plus(&mut self, lo: V, hi: V, off: i32) -> (V, V) {
  2602. if off == 0 {
  2603. return (lo, hi);
  2604. }
  2605. let c = self.cur;
  2606. let i32t = self.s.t.i32;
  2607. let k = self.s.m.i32(off as u32);
  2608. let sum = self.s.m.bin(c, Bin::Add, lo, k);
  2609. // Up: a carry when the sum wrapped below `lo`. Down: a borrow when
  2610. // it wrapped above.
  2611. let wrapped = self
  2612. .s
  2613. .m
  2614. .cmp(c, if off > 0 { pred::IULT } else { pred::IUGT }, sum, lo);
  2615. let one = self.s.m.cast(c, Cast::ZExt, wrapped, i32t);
  2616. let hi = self.s.m.bin(c, if off > 0 { Bin::Add } else { Bin::Sub }, hi, one);
  2617. (sum, hi)
  2618. }
  2619. /// Title memory at the 40-bit address `lo`, `hi` (`shader.rs`
  2620. /// `SLOT_MEMORY`): the handle of the raw view of the host copy holding
  2621. /// it and the byte in that view. A page without a copy reads zeros
  2622. /// (and drops writes) through the null view at the first slot, and its
  2623. /// number is left for the host, for lanes that run (`guard`).
  2624. fn memory(&mut self, lo: V, hi: V, guard: Option<V>) -> (V, V) {
  2625. use super::shader::{MEMORY_FAULTS, MEMORY_PAGES, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE};
  2626. let c = self.cur;
  2627. let (i32t, res) = (self.s.t.i32, self.s.t.res_ret);
  2628. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  2629. let (k16, k8) = (k(self, 16), k(self, 0xFF));
  2630. let low = self.s.m.bin(c, Bin::LShr, lo, k16);
  2631. let high = self.s.m.bin(c, Bin::And, hi, k8);
  2632. let high = self.s.m.bin(c, Bin::Shl, high, k16);
  2633. let page = self.s.m.bin(c, Bin::Or, low, high);
  2634. // Inside the directory whatever the address (lanes that do not run
  2635. // compute one too); its last entry is never filled.
  2636. let last = k(self, MEMORY_PAGES - 1);
  2637. let page = self
  2638. .s
  2639. .op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[page, last]);
  2640. let k3 = k(self, 3);
  2641. let at = self.s.m.bin(c, Bin::Shl, page, k3);
  2642. let directory = self.s.root_srv_handle(SLOT_MEMORY);
  2643. let (iu, both, align) = (self.s.m.undef(i32t), self.s.m.i8(3), k(self, 4));
  2644. let entry = self.s.op(
  2645. c,
  2646. "rawBufferLoad.f32",
  2647. Attr::ReadOnly,
  2648. res,
  2649. 139,
  2650. &[directory, at, iu, both, align],
  2651. );
  2652. let (copy, start) = (self.s.m.extract(c, entry, 0), self.s.m.extract(c, entry, 1));
  2653. let (copy, start) = (self.as_int(copy), self.as_int(start));
  2654. // A page without a copy: its number, at a place by the number, or
  2655. // at the sink for lanes that do not run and pages that have one.
  2656. let zero = k(self, 0);
  2657. let mut missing = self.s.m.cmp(c, pred::EQ, copy, zero);
  2658. if let Some(g) = guard {
  2659. missing = self.s.m.bin(c, Bin::And, missing, g);
  2660. }
  2661. let places = k(self, MEMORY_FAULTS - 1);
  2662. let place = self.s.m.bin(c, Bin::URem, page, places);
  2663. let one = k(self, 1);
  2664. let place = self.s.m.bin(c, Bin::Add, place, one);
  2665. let k2 = k(self, 2);
  2666. let place = self.s.m.bin(c, Bin::Shl, place, k2);
  2667. let place = self.s.m.select(c, missing, place, zero);
  2668. let faults = self.s.root_uav_handle(SLOT_FAULTS);
  2669. let void = self.s.t.void;
  2670. let mask = self.s.m.i8(1);
  2671. self.s.op(
  2672. c,
  2673. "rawBufferStore.i32",
  2674. Attr::NoUnwind,
  2675. void,
  2676. 140,
  2677. &[faults, place, iu, page, iu, iu, iu, mask, align],
  2678. );
  2679. let base = self.host_word(RootType::Other(USER_MEMORY_BASE), 0, 0);
  2680. let slot = self.s.m.bin(c, Bin::Add, base, copy);
  2681. let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000, 0));
  2682. let k64k = k(self, 0xFFFF);
  2683. let within = self.s.m.bin(c, Bin::And, lo, k64k);
  2684. let byte = self.s.m.bin(c, Bin::Add, start, within);
  2685. (h, byte)
  2686. }
  2687. /// `global_load_*`, `global_store_*` and `global_atomic_*` on title
  2688. /// memory by address (`resource::MEMORY`): the address is the VGPR
  2689. /// pair, each lane its own.
  2690. fn memory_flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  2691. let Fields::Flat {
  2692. dst,
  2693. addr,
  2694. data,
  2695. saddr,
  2696. offset,
  2697. lds,
  2698. cache,
  2699. } = &inst.fields
  2700. else {
  2701. unreachable!()
  2702. };
  2703. if *lds || !matches!(saddr, None | Some(Operand::Scalar { code: NULL, .. })) {
  2704. return Err("a global address with a scalar base");
  2705. }
  2706. let Some(Operand::Vector { reg: areg, .. }) = *addr else {
  2707. return Err("a global address not in VGPRs");
  2708. };
  2709. let word = |l: &mut Self, k: u8| -> Result<V, Why> {
  2710. let v = inst.read(Reg::V(areg + k)).ok_or("a global address")?;
  2711. l.i32_of(v)
  2712. };
  2713. let (lo, hi) = (word(self, 0)?, word(self, 1)?);
  2714. let (lo, hi) = self.address_plus(lo, hi, i32::from(*offset));
  2715. let guard = self.guard(b, i)?;
  2716. let c = self.cur;
  2717. let (i32t, res, void) = (self.s.t.i32, self.s.t.res_ret, self.s.t.void);
  2718. let iu = self.s.m.undef(i32t);
  2719. let align = self.s.m.i32(4);
  2720. let name = inst.name();
  2721. let count = |rest: &str| match rest {
  2722. "dword" => Ok(1u8),
  2723. "dwordx2" => Ok(2),
  2724. "dwordx3" => Ok(3),
  2725. "dwordx4" => Ok(4),
  2726. _ => Err(name),
  2727. };
  2728. if let Some(rest) = name.strip_prefix("global_load_") {
  2729. let n = count(rest)?;
  2730. let Some(Operand::Vector { reg, .. }) = *dst else {
  2731. return Err("a global load result");
  2732. };
  2733. let (h, byte) = self.memory(lo, hi, guard);
  2734. let mask = self.s.m.i8((1u8 << n) - 1);
  2735. let r = self.s.op(
  2736. c,
  2737. "rawBufferLoad.f32",
  2738. Attr::ReadOnly,
  2739. res,
  2740. 139,
  2741. &[h, byte, iu, mask, align],
  2742. );
  2743. for k in 0..n {
  2744. let x = self.s.m.extract(c, r, u32::from(k));
  2745. let x = self.as_int(x);
  2746. self.write(inst, Reg::V(reg + k), x, guard);
  2747. }
  2748. return Ok(());
  2749. }
  2750. if let Some(rest) = name.strip_prefix("global_store_") {
  2751. let n = count(rest)?;
  2752. let d = data.as_ref().ok_or("global store data")?;
  2753. let vals = self.vgprs(inst, d, n)?;
  2754. let (h, byte) = self.memory(lo, hi, guard);
  2755. let mut args = vec![h, byte, iu];
  2756. args.extend(&vals);
  2757. args.resize(3 + 4, iu);
  2758. args.push(self.s.m.i8((1u8 << n) - 1));
  2759. args.push(align);
  2760. let at = self.begin_guarded(guard);
  2761. self.s
  2762. .op(self.cur, "rawBufferStore.i32", Attr::NoUnwind, void, 140, &args);
  2763. self.end_guarded(at, &[]);
  2764. return Ok(());
  2765. }
  2766. let Some(op) = name.strip_prefix("global_atomic_") else {
  2767. return Err(name);
  2768. };
  2769. let d = data.as_ref().ok_or("global atomic data")?;
  2770. let v = self.vgprs(inst, d, 1)?[0];
  2771. // With `glc` the value from before comes back, in the result
  2772. // register the instruction names.
  2773. let back = match (*dst, cache.glc) {
  2774. (Some(Operand::Vector { reg, .. }), true) => Some(reg),
  2775. _ => None,
  2776. };
  2777. let old = match back.and_then(|reg| inst.read(Reg::V(reg))) {
  2778. Some(x) => self.i32_of(x)?,
  2779. None => self.s.m.i32(0),
  2780. };
  2781. let (h, byte) = self.memory(lo, hi, guard);
  2782. // DXIL's atomic operations: add 0, and 1, or 2, xor 3, signed
  2783. // minimum 4 and maximum 5, unsigned 6 and 7, exchange 8.
  2784. let simple = match op {
  2785. "add" => Some((0, v)),
  2786. "sub" => {
  2787. let zero = self.s.m.i32(0);
  2788. Some((0, self.s.m.bin(c, Bin::Sub, zero, v)))
  2789. }
  2790. "and" => Some((1, v)),
  2791. "or" => Some((2, v)),
  2792. "xor" => Some((3, v)),
  2793. "smin" => Some((4, v)),
  2794. "smax" => Some((5, v)),
  2795. "umin" => Some((6, v)),
  2796. "umax" => Some((7, v)),
  2797. "swap" => Some((8, v)),
  2798. "fmin" | "fmax" => None,
  2799. _ => return Err(name),
  2800. };
  2801. let at = self.begin_guarded(guard);
  2802. let was = match simple {
  2803. Some((code, x)) => {
  2804. let code = self.s.m.i32(code);
  2805. self.s.op(
  2806. self.cur,
  2807. "atomicBinOp.i32",
  2808. Attr::NoUnwind,
  2809. i32t,
  2810. 78,
  2811. &[h, code, byte, iu, iu, x],
  2812. )
  2813. }
  2814. None => {
  2815. // A float minimum or maximum has no atomic operation on
  2816. // the host: the dword is exchanged for the smaller (larger)
  2817. // of itself and the value until no other thread got in
  2818. // between. Each failed pass means another one's succeeded;
  2819. // the limit only keeps a broken card from hanging.
  2820. let head = self.cur;
  2821. let mask = self.s.m.i8(1);
  2822. let first = self.s.op(
  2823. head,
  2824. "rawBufferLoad.f32",
  2825. Attr::ReadOnly,
  2826. res,
  2827. 139,
  2828. &[h, byte, iu, mask, align],
  2829. );
  2830. let first = self.s.m.extract(head, first, 0);
  2831. let first = self.as_int(first);
  2832. let (pass, done) = (self.s.m.new_block(), self.s.m.new_block());
  2833. self.s.m.terminate(head, Term::Br(pass));
  2834. self.cur = pass;
  2835. let seen = self.s.m.phi(pass, i32t);
  2836. let n = self.s.m.phi(pass, i32t);
  2837. let (f32t, fv) = (self.s.t.f32, self.as_float(v));
  2838. let fseen = self.as_float(seen);
  2839. // `dx.op.binary`: FMax 35, FMin 36.
  2840. let pick = if op == "fmin" { 36 } else { 35 };
  2841. let wanted = self
  2842. .s
  2843. .op(pass, "binary.f32", Attr::ReadNone, f32t, pick, &[fseen, fv]);
  2844. let wanted = self.as_int(wanted);
  2845. let found = self.s.op(
  2846. pass,
  2847. "atomicCompareExchange.i32",
  2848. Attr::NoUnwind,
  2849. i32t,
  2850. 79,
  2851. &[h, byte, iu, iu, seen, wanted],
  2852. );
  2853. let one = self.s.m.i32(1);
  2854. let n1 = self.s.m.bin(pass, Bin::Add, n, one);
  2855. let lost = self.s.m.cmp(pass, pred::NE, found, seen);
  2856. let limit = self.s.m.i32(1 << 16);
  2857. let more = self.s.m.cmp(pass, pred::IULT, n1, limit);
  2858. let again = self.s.m.bin(pass, Bin::And, lost, more);
  2859. self.s.m.terminate(pass, Term::CondBr(again, pass, done));
  2860. let zero = self.s.m.i32(0);
  2861. self.s.m.set_phi(seen, vec![(first, head), (found, pass)]);
  2862. self.s.m.set_phi(n, vec![(zero, head), (n1, pass)]);
  2863. self.cur = done;
  2864. found
  2865. }
  2866. };
  2867. let was = self.end_guarded(at, &[(was, old)])[0];
  2868. if let Some(reg) = back {
  2869. self.write(inst, Reg::V(reg), was, None);
  2870. }
  2871. Ok(())
  2872. }
  2873. /// `s_load_dword*` from title memory by address (`resource::MEMORY`):
  2874. /// the SGPR pair plus the instruction's offsets.
  2875. fn memory_smem(&mut self, inst: &Inst) -> Result<(), Why> {
  2876. let Fields::Smem {
  2877. data: Some(Operand::Scalar { code, .. }),
  2878. base: Operand::Scalar { code: base, .. },
  2879. offset,
  2880. soffset,
  2881. ..
  2882. } = inst.fields
  2883. else {
  2884. return Err("a scalar load from memory");
  2885. };
  2886. let count = match inst.name().strip_prefix("s_load_dword") {
  2887. Some("") => 1u8,
  2888. Some("x2") => 2,
  2889. Some("x4") => 4,
  2890. Some("x8") => 8,
  2891. Some("x16") => 16,
  2892. _ => return Err("a scalar memory access by address"),
  2893. };
  2894. let word = |l: &mut Self, k: u8| -> Result<V, Why> {
  2895. let v = inst.read(Reg::S(base + k)).ok_or("an address not in SGPRs")?;
  2896. l.i32_of(v)
  2897. };
  2898. let (mut lo, mut hi) = (word(self, 0)?, word(self, 1)?);
  2899. let c = self.cur;
  2900. let (i32t, res) = (self.s.t.i32, self.s.t.res_ret);
  2901. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  2902. // An offset register counts up from the address.
  2903. let so = self.operand(inst, &soffset)?;
  2904. let sum = self.s.m.bin(c, Bin::Add, lo, so);
  2905. let carry = self.s.m.cmp(c, pred::IULT, sum, lo);
  2906. let carry = self.s.m.cast(c, Cast::ZExt, carry, i32t);
  2907. hi = self.s.m.bin(c, Bin::Add, hi, carry);
  2908. lo = sum;
  2909. }
  2910. let (iu, align) = (self.s.m.undef(i32t), self.s.m.i32(4));
  2911. for first in (0..count).step_by(4) {
  2912. let n = (count - first).min(4);
  2913. let (lo, hi) = self.address_plus(lo, hi, offset + 4 * i32::from(first));
  2914. let (h, byte) = self.memory(lo, hi, None);
  2915. let mask = self.s.m.i8((1u8 << n) - 1);
  2916. let r = self.s.op(
  2917. c,
  2918. "rawBufferLoad.f32",
  2919. Attr::ReadOnly,
  2920. res,
  2921. 139,
  2922. &[h, byte, iu, mask, align],
  2923. );
  2924. for k in 0..n {
  2925. let x = self.s.m.extract(c, r, u32::from(k));
  2926. let x = self.as_int(x);
  2927. self.write(inst, Reg::S(code + first + k), x, None);
  2928. }
  2929. }
  2930. Ok(())
  2931. }
  2932. /// A dword of a lane mask as a number: the ballot of the lanes' bits,
  2933. /// taken in the block that writes the mask (see [`MaskData`]).
  2934. fn mask_dword(&mut self, v: Value) -> Result<V, Why> {
  2935. let (lo, high) = match self.x.st.highs.get(&v) {
  2936. Some(&lo) => (lo, true),
  2937. None => (v, false),
  2938. };
  2939. let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?;
  2940. // A mask that holds lanes outside EXEC where it is written (the complement of one,
  2941. // say) is the ballot of the lanes that are there: all of them, where two exchanging
  2942. // host waves know every lane runs that block.
  2943. let made = self.def_block.get(&lo).copied();
  2944. let whole = self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b));
  2945. if !self.x.st.active.contains(&lo) && !whole {
  2946. if self.exchange.is_some() && !self.local {
  2947. need(made.unwrap_or(0));
  2948. }
  2949. return Err(MASK_ELSEWHERE);
  2950. }
  2951. let (x, y) = match self.ballots.get(&lo) {
  2952. Some(&xy) => xy,
  2953. None => {
  2954. let at = match self.def_block.get(&lo) {
  2955. // Program inputs (EXEC on entry).
  2956. None => self.s.entry,
  2957. Some(&b) if b == self.cur_ir => self.cur,
  2958. Some(&b) => self.tail[b].ok_or("a lane mask written after its use")?,
  2959. };
  2960. if !self.balloting.insert(lo) {
  2961. return Err("a lane mask whose lanes depend on its own value");
  2962. }
  2963. let bit = self.boolean(m, at);
  2964. self.balloting.remove(&lo);
  2965. let bit = bit?;
  2966. let i32t = self.s.t.i32;
  2967. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  2968. let r = self
  2969. .s
  2970. .op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, &[bit]);
  2971. self.s.flags |= flags::WAVE_OPS;
  2972. let mut xy = (self.s.m.extract(at, r, 0), self.s.m.extract(at, r, 1));
  2973. if self.exchange.is_some() {
  2974. // a host wave's ballot is its half's 32 bits: the halves exchange them
  2975. let b = self.def_block.get(&lo).copied();
  2976. if self.local {
  2977. if !self.local_ok && !self.local_any {
  2978. return Err("a lane mask read as data in a half-wave");
  2979. }
  2980. } else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) {
  2981. // (a group of 32 or fewer has no other half to exchange with)
  2982. need(b.unwrap_or(0));
  2983. return Err("a lane mask exchanged where not every lane runs");
  2984. }
  2985. xy = self.exchange_halves(at, xy.0);
  2986. }
  2987. self.ballots.insert(lo, xy);
  2988. xy
  2989. }
  2990. };
  2991. Ok(if high { y } else { x })
  2992. }
  2993. // ---- operands ----
  2994. fn operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> {
  2995. match *op {
  2996. Operand::Scalar { code: NULL, .. } => Ok(self.s.m.i32(0)),
  2997. Operand::Scalar { code, .. } => {
  2998. let v = inst.read(Reg::S(code)).ok_or("an unread operand")?;
  2999. self.i32_of(v)
  3000. }
  3001. Operand::Vector { reg, .. } => {
  3002. let v = inst.read(Reg::V(reg)).ok_or("an unread operand")?;
  3003. self.i32_of(v)
  3004. }
  3005. Operand::Const(c) => crate::resource::inline(c)
  3006. .map(|x| self.s.m.i32(x))
  3007. .ok_or("a special operand (vccz, execz, scc, lds_direct)"),
  3008. Operand::Literal(x) => Ok(self.s.m.i32(x)),
  3009. Operand::Attr { .. } => Err("an attribute operand"),
  3010. }
  3011. }
  3012. /// An operand read as f16 data: GFX10 puts an inline f16 constant in
  3013. /// the low half of the operand (upstream PR #637, checked there against
  3014. /// the instruction encodings; the half-and-half reading taken from PR
  3015. /// #458 gave the high half the constant too).
  3016. fn f16_operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> {
  3017. match *op {
  3018. Operand::Const(c @ 240..=248) => Ok(self.s.m.i32(inline_f16(c))),
  3019. _ => self.operand(inst, op),
  3020. }
  3021. }
  3022. fn as_float(&mut self, x: V) -> V {
  3023. self.s.m.cast(self.cur, Cast::Bitcast, x, self.s.t.f32)
  3024. }
  3025. fn as_int(&mut self, f: V) -> V {
  3026. self.s.m.cast(self.cur, Cast::Bitcast, f, self.s.t.i32)
  3027. }
  3028. /// The SDWA operand selection of source `k`: a byte or word of the
  3029. /// dword, zero- or sign-extended (none: the whole dword).
  3030. fn sdwa_src(inst: &Inst, k: usize) -> Option<(u8, bool)> {
  3031. let Fields::Valu(v) = &inst.fields else {
  3032. return None;
  3033. };
  3034. let s = v.sdwa?;
  3035. let sel = *s.src_sel.get(k)?;
  3036. let sext = s.sext >> k & 1 != 0;
  3037. (sel < 6).then_some((sel, sext))
  3038. }
  3039. /// Bits `sel` (0-3 a byte, 4-5 a word) of `x`, extended.
  3040. fn select_bits(&mut self, x: V, sel: u8, sext: bool) -> V {
  3041. let c = self.cur;
  3042. let (width, at) = if sel < 4 {
  3043. (8, 8 * sel)
  3044. } else {
  3045. (16, 16 * (sel - 4))
  3046. };
  3047. let left = self.s.m.i32(u32::from(32 - width - at));
  3048. let t = self.s.m.bin(c, Bin::Shl, x, left);
  3049. let right = self.s.m.i32(32 - u32::from(width));
  3050. let op = if sext { Bin::AShr } else { Bin::LShr };
  3051. self.s.m.bin(c, op, t, right)
  3052. }
  3053. /// A float source with its abs/neg modifiers.
  3054. fn fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  3055. let Fields::Valu(v) = &inst.fields else {
  3056. unreachable!()
  3057. };
  3058. let op = *v.src.get(k).ok_or("a missing operand")?;
  3059. let selected = Self::sdwa_src(inst, k);
  3060. let mut f = match op {
  3061. _ if selected.is_some() => {
  3062. let (sel, sext) = selected.expect("checked");
  3063. let x = self.operand(inst, &op)?;
  3064. let x = self.select_bits(x, sel, sext);
  3065. self.as_float(x)
  3066. }
  3067. _ if k == 0 && self.src0.is_some() => {
  3068. let x = self.src0.expect("checked");
  3069. self.as_float(x)
  3070. }
  3071. Operand::Vector { reg, .. } | Operand::Scalar { code: reg, .. }
  3072. if !matches!(op, Operand::Scalar { code: NULL, .. }) =>
  3073. {
  3074. let r = if matches!(op, Operand::Vector { .. }) {
  3075. Reg::V(reg)
  3076. } else {
  3077. Reg::S(reg)
  3078. };
  3079. let val = inst.read(r).ok_or("an unread operand")?;
  3080. match self.floats.get(&val) {
  3081. Some(&f) => f,
  3082. None => {
  3083. let x = self.i32_of(val)?;
  3084. self.as_float(x)
  3085. }
  3086. }
  3087. }
  3088. _ => {
  3089. let x = self.operand(inst, &op)?;
  3090. self.as_float(x)
  3091. }
  3092. };
  3093. if v.abs >> k & 1 != 0 {
  3094. f = self.unary(6, f);
  3095. }
  3096. if v.neg >> k & 1 != 0 {
  3097. let z = self.s.m.f32(0x8000_0000);
  3098. f = self.s.m.bin(self.cur, Bin::Sub, z, f);
  3099. }
  3100. Ok(f)
  3101. }
  3102. fn src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  3103. let Fields::Valu(v) = &inst.fields else {
  3104. unreachable!()
  3105. };
  3106. let op = *v.src.get(k).ok_or("a missing operand")?;
  3107. if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 {
  3108. return Err("integer operand modifiers");
  3109. }
  3110. match self.src0 {
  3111. Some(x) if k == 0 => Ok(x),
  3112. _ => {
  3113. let x = self.operand(inst, &op)?;
  3114. Ok(match Self::sdwa_src(inst, k) {
  3115. Some((sel, sext)) => self.select_bits(x, sel, sext),
  3116. None => x,
  3117. })
  3118. }
  3119. }
  3120. }
  3121. fn unary(&mut self, op: u32, f: V) -> V {
  3122. self.s.op(
  3123. self.cur,
  3124. "unary.f32",
  3125. Attr::ReadNone,
  3126. self.s.t.f32,
  3127. op,
  3128. &[f],
  3129. )
  3130. }
  3131. fn binary(&mut self, op: u32, a: V, b: V) -> V {
  3132. self.s.op(
  3133. self.cur,
  3134. "binary.f32",
  3135. Attr::ReadNone,
  3136. self.s.t.f32,
  3137. op,
  3138. &[a, b],
  3139. )
  3140. }
  3141. /// The hardware's maximum (`max`) or minimum of two floats: as DXIL's
  3142. /// FMax/FMin, but -0 orders below +0 (RDNA2 ISA, `v_max_f32`), where
  3143. /// the compare and select DXIL specifies gives either zero.
  3144. fn max_min(&mut self, max: bool, a: V, b: V) -> V {
  3145. let c = self.cur;
  3146. let r = self.binary(if max { 35 } else { 36 }, a, b);
  3147. let (ia, ib) = (self.as_int(a), self.as_int(b));
  3148. let either = self.s.m.bin(c, Bin::Or, ia, ib);
  3149. let magnitude = self.s.m.i32(0x7FFF_FFFF);
  3150. let either = self.s.m.bin(c, Bin::And, either, magnitude);
  3151. let zero = self.s.m.i32(0);
  3152. let zeros = self.s.m.cmp(c, pred::EQ, either, zero);
  3153. // Of two zeros, +0 unless both are -0 (max), -0 unless neither (min).
  3154. let op = if max { Bin::And } else { Bin::Or };
  3155. let sign = self.s.m.bin(c, op, ia, ib);
  3156. let signed = self.as_float(sign);
  3157. self.s.m.select(c, zeros, signed, r)
  3158. }
  3159. fn fmad(&mut self, a: V, b: V, c: V) -> V {
  3160. self.s.op(
  3161. self.cur,
  3162. "tertiary.f32",
  3163. Attr::ReadNone,
  3164. self.s.t.f32,
  3165. 46,
  3166. &[a, b, c],
  3167. )
  3168. }
  3169. /// `f` as an f16 in the low bits, rounded toward zero: the nearest-even
  3170. /// conversion, one step back toward zero where it rounded away (which
  3171. /// also turns an overflow to infinity into the largest finite half).
  3172. fn f16_toward_zero(&mut self, f: V) -> V {
  3173. let c = self.cur;
  3174. let i32t = self.s.t.i32;
  3175. let h = self
  3176. .s
  3177. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
  3178. let back = self
  3179. .s
  3180. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]);
  3181. let (fa, ba) = (self.unary(6, f), self.unary(6, back));
  3182. // Ordered: never for NaN.
  3183. let away = self.s.m.cmp(c, pred::OGT, ba, fa);
  3184. let one = self.s.m.i32(1);
  3185. let stepped = self.s.m.bin(c, Bin::Sub, h, one);
  3186. self.s.m.select(c, away, stepped, h)
  3187. }
  3188. /// `f` as an f16 in the low bits, rounded to nearest, ties to even, as the console's
  3189. /// 16-bit float operations round, whatever the host's own conversion does: D3D lets
  3190. /// `f32tof16` round toward zero, and the NVIDIA driver's does (measured on an RTX 4070:
  3191. /// `wave64_tests`). The conversion toward zero, or the next half away from zero where
  3192. /// that one is nearer, or as near and the first one odd. Past the largest half the next
  3193. /// one counts as 2^16, the bound IEEE rounds by, so 65520 and up become infinity.
  3194. /// (`f` is an f32 result of two halves here; rounding it again to 16 bits gives the
  3195. /// rounding of the exact result, 24 bits being more than twice 11 and two.)
  3196. fn f16_nearest(&mut self, f: V) -> V {
  3197. let c = self.cur;
  3198. let f32t = self.s.t.f32;
  3199. let lo = self.f16_toward_zero(f);
  3200. let (one, zero) = (self.s.m.i32(1), self.s.m.i32(0));
  3201. let hi = self.s.m.bin(c, Bin::Add, lo, one);
  3202. let size = |l: &mut Self, h: V| {
  3203. let w = l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  3204. l.unary(6, w)
  3205. };
  3206. let (below, above) = (size(self, lo), size(self, hi));
  3207. let (magnitude, infinity) = (self.s.m.i32(0x7FFF), self.s.m.i32(0x7C00));
  3208. let m = self.s.m.bin(c, Bin::And, hi, magnitude);
  3209. let top = self.s.m.cmp(c, pred::EQ, m, infinity);
  3210. let bound = self.s.m.f32(65536.0f32.to_bits());
  3211. let above = self.s.m.select(c, top, bound, above);
  3212. let fa = self.unary(6, f);
  3213. // (both differences are exact: the three values lie within one half's step)
  3214. let under = self.s.m.bin(c, Bin::Sub, fa, below);
  3215. let over = self.s.m.bin(c, Bin::Sub, above, fa);
  3216. // Ordered: never for NaN, which stays what the conversion made of it.
  3217. let nearer = self.s.m.cmp(c, pred::OLT, over, under);
  3218. let tie = self.s.m.cmp(c, pred::OEQ, over, under);
  3219. let odd = self.s.m.bin(c, Bin::And, lo, one);
  3220. let odd = self.s.m.cmp(c, pred::NE, odd, zero);
  3221. let tie = self.s.m.bin(c, Bin::And, tie, odd);
  3222. let up = self.s.m.bin(c, Bin::Or, nearer, tie);
  3223. self.s.m.select(c, up, hi, lo)
  3224. }
  3225. /// `(a >> off[4:0]) & ((1 << width) - 1)`, sign-extended from the field's
  3226. /// top bit when `signed`; widths from 32 on take every bit. A signed
  3227. /// field that runs past bit 31 extends from bit 31, as the hardware
  3228. /// does: the shift is arithmetic then.
  3229. fn bfe(&mut self, a: V, off: V, width: V, signed: bool) -> V {
  3230. let c = self.cur;
  3231. let (k31, k32, zero, one, ones) = (
  3232. self.s.m.i32(31),
  3233. self.s.m.i32(32),
  3234. self.s.m.i32(0),
  3235. self.s.m.i32(1),
  3236. self.s.m.i32(u32::MAX),
  3237. );
  3238. let off = self.s.m.bin(c, Bin::And, off, k31);
  3239. let shift = if signed { Bin::AShr } else { Bin::LShr };
  3240. let shifted = self.s.m.bin(c, shift, a, off);
  3241. let full = self.s.m.cmp(c, pred::IUGE, width, k32);
  3242. let w = self.s.m.bin(c, Bin::And, width, k31);
  3243. let mask = self.s.m.bin(c, Bin::Shl, one, w);
  3244. let mask = self.s.m.bin(c, Bin::Sub, mask, one);
  3245. let mask = self.s.m.select(c, full, ones, mask);
  3246. let r = self.s.m.bin(c, Bin::And, shifted, mask);
  3247. if !signed {
  3248. return r;
  3249. }
  3250. // Sign-extend a field narrower than 32 bits (none for width 0).
  3251. let left = self.s.m.bin(c, Bin::Sub, k32, w);
  3252. let left = self.s.m.bin(c, Bin::And, left, k31);
  3253. let t = self.s.m.bin(c, Bin::Shl, r, left);
  3254. let t = self.s.m.bin(c, Bin::AShr, t, left);
  3255. let is0 = self.s.m.cmp(c, pred::EQ, w, zero);
  3256. let keep = self.s.m.bin(c, Bin::Or, full, is0);
  3257. self.s.m.select(c, keep, r, t)
  3258. }
  3259. /// Whether an f32 value is NaN, tested in integer arithmetic so host
  3260. /// drivers (such as NVIDIA) do not fold `fcmp uno` away under fast-math.
  3261. fn is_nan_f32(&mut self, f: V) -> V {
  3262. let c = self.cur;
  3263. let bits = self.as_int(f);
  3264. let mask = self.s.m.i32(0x7FFF_FFFF);
  3265. let abs = self.s.m.bin(c, Bin::And, bits, mask);
  3266. let inf = self.s.m.i32(0x7F80_0000);
  3267. self.s.m.cmp(c, pred::IUGT, abs, inf)
  3268. }
  3269. /// The median of three. With a NaN among them the hardware gives the
  3270. /// minimum of the three instead (the host's minimum skips NaNs, so that
  3271. /// is the smallest number among them).
  3272. fn med3(&mut self, a: V, b: V, third: V) -> V {
  3273. let c = self.cur;
  3274. let lo = self.binary(36, a, b);
  3275. let hi = self.binary(35, a, b);
  3276. let t = self.binary(36, hi, third);
  3277. let median = self.binary(35, lo, t);
  3278. let least = self.binary(36, lo, third);
  3279. let nan_a = self.is_nan_f32(a);
  3280. let nan_b = self.is_nan_f32(b);
  3281. let nan_3 = self.is_nan_f32(third);
  3282. let nan_ab = self.s.m.bin(c, Bin::Or, nan_a, nan_b);
  3283. let nan = self.s.m.bin(c, Bin::Or, nan_ab, nan_3);
  3284. self.s.m.select(c, nan, least, median)
  3285. }
  3286. /// `a - floor(a)`, which on the hardware never reaches 1.0: where it
  3287. /// would round to it (a tiny negative `a`), the result is `below_one`,
  3288. /// the largest value under 1.0 in the operation's width. Hosts differ
  3289. /// here (some give 1.0). Comparing against a `threshold` distinct from
  3290. /// `below_one` prevents drivers (observed on NVIDIA) from folding
  3291. /// `r > k ? k : r` into `minNum` (`FMNMX`) and swallowing NaN.
  3292. fn fract(&mut self, a: V, threshold: f32, below_one: f32) -> V {
  3293. let c = self.cur;
  3294. let r = self.unary(22, a);
  3295. let limit = self.s.m.f32(threshold.to_bits());
  3296. let k = self.s.m.f32(below_one.to_bits());
  3297. let over = self.s.m.cmp(c, pred::OGE, r, limit);
  3298. self.s.m.select(c, over, k, r)
  3299. }
  3300. /// Sine, or cosine, of an angle in turns, as the hardware takes it. The
  3301. /// whole turns are taken off first (`x - round_even(x)`, exact, within
  3302. /// half a turn), so a large angle keeps its fraction; scaling to radians
  3303. /// first rounds it away. A zero passes unreduced (the sine of -0 is -0).
  3304. /// The sine of a half turn and the cosine of a quarter turn are exactly
  3305. /// +0 on the hardware, where the host's function of the rounded angle
  3306. /// gives about 1e-7. Infinities and NaN give NaN.
  3307. /// shortcut: below 2^-12 turns the hardware scales by a slightly
  3308. /// different constant than 2π (a last-place difference).
  3309. fn trig_turns(&mut self, x: V, cosine: bool) -> V {
  3310. let c = self.cur;
  3311. let zero = self.s.m.f32(0);
  3312. let whole = self.unary(26, x);
  3313. let part = self.s.m.bin(c, Bin::Sub, x, whole);
  3314. let is_zero = self.s.m.cmp(c, pred::OEQ, x, zero);
  3315. let part = self.s.m.select(c, is_zero, x, part);
  3316. let k = self.s.m.f32(TWO_PI.to_bits());
  3317. let angle = self.s.m.bin(c, Bin::Mul, part, k);
  3318. let r = self.unary(if cosine { 12 } else { 13 }, angle);
  3319. let at = if cosine { 0.25f32 } else { 0.5 };
  3320. let at = self.s.m.f32(at.to_bits());
  3321. let size = self.unary(6, part);
  3322. let exact = self.s.m.cmp(c, pred::OEQ, size, at);
  3323. self.s.m.select(c, exact, zero, r)
  3324. }
  3325. /// The high dword of a 32 × 32-bit product.
  3326. fn mul_hi(&mut self, a: V, b: V, signed: bool) -> V {
  3327. let c = self.cur;
  3328. let i64t = self.s.m.int(64);
  3329. let ext = if signed { Cast::SExt } else { Cast::ZExt };
  3330. let a = self.s.m.cast(c, ext, a, i64t);
  3331. let b = self.s.m.cast(c, ext, b, i64t);
  3332. let m = self.s.m.bin(c, Bin::Mul, a, b);
  3333. let k32 = self.s.m.int_const(i64t, 32);
  3334. let hi = self.s.m.bin(c, Bin::LShr, m, k32);
  3335. self.s.flags |= flags::INT64;
  3336. self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32)
  3337. }
  3338. /// `0 × anything = 0`, as in D3D9.
  3339. fn legacy_mul(&mut self, a: V, b: V) -> V {
  3340. let c = self.cur;
  3341. let m = self.s.m.bin(c, Bin::Mul, a, b);
  3342. let zero = self.s.m.f32(0);
  3343. let az = self.s.m.cmp(c, pred::OEQ, a, zero);
  3344. let bz = self.s.m.cmp(c, pred::OEQ, b, zero);
  3345. let z = self.s.m.bin(c, Bin::Or, az, bz);
  3346. self.s.m.select(c, z, zero, m)
  3347. }
  3348. // ---- lane booleans ----
  3349. fn boolean(&mut self, b: Bool, at: usize) -> Result<V, Why> {
  3350. if b == Bool::TRUE || b == Bool::FALSE {
  3351. return Ok(self.s.m.bool(b == Bool::TRUE));
  3352. }
  3353. if let Some(&v) = self.bools.get(&(at, b)) {
  3354. return Ok(v);
  3355. }
  3356. let (atom, lo, hi) = self.x.st.bools.node(b).expect("not a constant");
  3357. let a = self.atom(atom, at)?;
  3358. let m = &mut self.s.m;
  3359. let v = match (lo, hi) {
  3360. (Bool::FALSE, Bool::TRUE) => a,
  3361. (Bool::TRUE, Bool::FALSE) => {
  3362. let t = m.bool(true);
  3363. m.bin(at, Bin::Xor, a, t)
  3364. }
  3365. (Bool::FALSE, h) => {
  3366. let h = self.boolean(h, at)?;
  3367. self.s.m.bin(at, Bin::And, a, h)
  3368. }
  3369. (l, Bool::TRUE) => {
  3370. let l = self.boolean(l, at)?;
  3371. self.s.m.bin(at, Bin::Or, a, l)
  3372. }
  3373. (l, h) => {
  3374. let l = self.boolean(l, at)?;
  3375. let h = self.boolean(h, at)?;
  3376. self.s.m.select(at, a, h, l)
  3377. }
  3378. };
  3379. self.bools.insert((at, b), v);
  3380. Ok(v)
  3381. }
  3382. fn atom(&mut self, atom: Atom, at: usize) -> Result<V, Why> {
  3383. match atom {
  3384. Atom::Lane(v) => self.lane_bits.get(&v).copied().ok_or_else(|| {
  3385. self.lane_fail
  3386. .get(&v)
  3387. .copied()
  3388. .unwrap_or("a lane mask from a carry")
  3389. }),
  3390. Atom::Uniform(v) => match self.get(v)? {
  3391. Val::Bit(x) => Ok(x),
  3392. Val::I32(x) => {
  3393. let z = self.s.m.i32(0);
  3394. Ok(self.s.m.cmp(at, pred::NE, x, z))
  3395. }
  3396. Val::Missing(w) => Err(w),
  3397. },
  3398. Atom::Phi(id) => {
  3399. if let Some(&v) = self.mask_phis.get(&id) {
  3400. return Ok(v);
  3401. }
  3402. let &(b, i) = self
  3403. .phi_at
  3404. .get(&id)
  3405. .ok_or("a lane-mask join without a phi")?;
  3406. let blk = self.block[b].ok_or("an unreachable join")?;
  3407. let v = self.s.m.phi(blk, self.s.t.i1);
  3408. self.mask_phis.insert(id, v);
  3409. self.pending_masks.push((v, b, i));
  3410. Ok(v)
  3411. }
  3412. // shortcut: "some lane of the quad is set" is taken as true: the
  3413. // lanes it adds only feed derivatives, and exports keep their own
  3414. // masks. Wrong if such a section had a side effect.
  3415. Atom::Quad(_) => Ok(self.s.m.bool(true)),
  3416. // With console lanes, a mask held as a number is the console's:
  3417. // the lane tests its own bit.
  3418. Atom::Opaque(v) if self.console_lanes => {
  3419. let hi = match self.pair_high(v) {
  3420. Some(h) => Some(self.get(h)?),
  3421. None => None,
  3422. };
  3423. let lo = self.get(v)?;
  3424. let word = |w: Val| match w {
  3425. Val::I32(x) => Ok(x),
  3426. _ => Err("an opaque lane mask"),
  3427. };
  3428. let lo = word(lo)?;
  3429. let hi = hi.map(word).transpose()?;
  3430. Ok(self.lane_bit(at, lo, hi))
  3431. }
  3432. Atom::Constant(k) if self.console_lanes => {
  3433. let lo = self.s.m.i32(k as u32);
  3434. let hi = self.s.m.i32((k >> 32) as u32);
  3435. Ok(self.lane_bit(at, lo, Some(hi)))
  3436. }
  3437. Atom::Opaque(_) => Err("an opaque lane mask"),
  3438. Atom::Constant(_) => Err("a constant lane mask"),
  3439. }
  3440. }
  3441. /// A console wave64 program in host waves of 32: the first console thread of this host wave
  3442. /// (0, 32, 64, ...). A GPU need not give a host wave consecutive thread indices (NVIDIA's
  3443. /// 8 x 8 groups), so each wave takes the next 32 from an LDS counter instead: every thread
  3444. /// zeroes it, the group meets, each wave's first lane adds 32 and the wave takes what it
  3445. /// found. Branch-free, in the entry block, which every thread runs.
  3446. fn wave_base(&mut self) -> Option<V> {
  3447. let slot = self.halves?;
  3448. if let Some(v) = self.wave_base {
  3449. return Some(v);
  3450. }
  3451. let (e, i32t) = (self.s.entry, self.s.t.i32);
  3452. let lds = self.s.lds();
  3453. let k = self.s.m.i32(slot);
  3454. let ptr = self.s.m.element(e, lds, k);
  3455. let zero = self.s.m.i32(0);
  3456. self.s.m.store(e, ptr, zero);
  3457. self.group_sync(e);
  3458. let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  3459. let first = self.s.m.cmp(e, pred::EQ, lane, zero);
  3460. let k32 = self.s.m.i32(32);
  3461. let add = self.s.m.select(e, first, k32, zero);
  3462. let ptr = self.s.m.element(e, lds, k);
  3463. let old = self.s.m.atomic(e, Rmw::Add, ptr, add);
  3464. let base = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[old]);
  3465. self.s.flags |= flags::WAVE_OPS;
  3466. self.wave_base = Some(base);
  3467. Some(base)
  3468. }
  3469. /// The console thread index of this thread in the group: `wave_base` plus the host lane
  3470. /// (host waves of 32), else the wave's first thread index rounded down plus the lane.
  3471. fn console_thread(&mut self) -> V {
  3472. let (e, i32t) = (self.s.entry, self.s.t.i32);
  3473. let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  3474. if let Some(base) = self.wave_base() {
  3475. return self.s.m.bin(e, Bin::Add, base, lane);
  3476. }
  3477. let flat = self.s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, &[]);
  3478. let first = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[flat]);
  3479. let wave = self.s.wave_size.unwrap_or(32);
  3480. let mask = self.s.m.i32(!(wave - 1));
  3481. let base = self.s.m.bin(e, Bin::And, first, mask);
  3482. self.s.m.bin(e, Bin::Add, base, lane)
  3483. }
  3484. /// This thread's console lane (0..63): its relabelled thread index (`thread_id`), whose host
  3485. /// wave holds a 32-aligned run of console lanes. Without `exchange`: the host lane.
  3486. fn console_lane(&mut self) -> V {
  3487. if self.exchange.is_none() {
  3488. return self.lane_index();
  3489. }
  3490. if let Some(v) = self.clane {
  3491. return v;
  3492. }
  3493. let (e, i32t) = (self.s.entry, self.s.t.i32);
  3494. let f = self.console_thread();
  3495. let _ = i32t;
  3496. let k63 = self.s.m.i32(63);
  3497. let cl = self.s.m.bin(e, Bin::And, f, k63);
  3498. self.s.flags |= flags::WAVE_OPS;
  3499. self.clane = Some(cl);
  3500. cl
  3501. }
  3502. /// A group barrier with an LDS fence in `block`.
  3503. fn group_sync(&mut self, block: usize) {
  3504. let mode = self.s.m.i32(meeting_mode());
  3505. let void = self.s.t.void;
  3506. self.s.op(block, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  3507. }
  3508. /// `exchange`: each host wave gives `mine` (the same in all its lanes) for its half; both get
  3509. /// (lower half's, upper half's). A group with no upper half gets 0 for it.
  3510. fn exchange_halves(&mut self, at: usize, mine: V) -> (V, V) {
  3511. let Some((slot, small, _)) = self.exchange.as_ref().map(|(a, b, _)| (*a, *b, ())) else {
  3512. let z = self.s.m.i32(0);
  3513. return (mine, z);
  3514. };
  3515. if small {
  3516. let z = self.s.m.i32(0);
  3517. return (mine, z);
  3518. }
  3519. if self.local {
  3520. // each host wave on its own: its half holds `mine`, the other nothing
  3521. let cl = self.console_lane();
  3522. let (k32, z) = (self.s.m.i32(32), self.s.m.i32(0));
  3523. let upper = self.s.m.cmp(at, pred::IUGE, cl, k32);
  3524. let lo = self.s.m.select(at, upper, z, mine);
  3525. let hi = self.s.m.select(at, upper, mine, z);
  3526. return (lo, hi);
  3527. }
  3528. // the pair of dwords of this thread's console wave: its half's, then both
  3529. let pair = self.exchange_pair(slot);
  3530. let cl = self.console_lane();
  3531. let five = self.s.m.i32(5);
  3532. let half = self.s.m.bin(at, Bin::LShr, cl, five);
  3533. let index = self.s.m.bin(at, Bin::Add, pair, half);
  3534. let lds = self.s.lds();
  3535. let ptr = self.s.m.element(at, lds, index);
  3536. self.s.m.store(at, ptr, mine);
  3537. self.group_sync(at);
  3538. let one = self.s.m.i32(1);
  3539. let k1 = self.s.m.bin(at, Bin::Add, pair, one);
  3540. let p0 = self.s.m.element(at, lds, pair);
  3541. let p1 = self.s.m.element(at, lds, k1);
  3542. let lo = self.s.m.load(at, p0);
  3543. let hi = self.s.m.load(at, p1);
  3544. // the slots are written again only after every thread read them
  3545. self.group_sync(at);
  3546. (lo, hi)
  3547. }
  3548. /// The first of the two exchange dwords of this thread's console wave (made in the entry
  3549. /// block): a group of several console waves has a pair for each.
  3550. fn exchange_pair(&mut self, slot: u32) -> V {
  3551. if let Some(v) = self.pair {
  3552. return v;
  3553. }
  3554. let e = self.s.entry;
  3555. let thread = self.console_thread();
  3556. let six = self.s.m.i32(6);
  3557. let wave = self.s.m.bin(e, Bin::LShr, thread, six);
  3558. let one = self.s.m.i32(1);
  3559. let twice = self.s.m.bin(e, Bin::Shl, wave, one);
  3560. let base = self.s.m.i32(slot);
  3561. let v = self.s.m.bin(e, Bin::Add, base, twice);
  3562. self.pair = Some(v);
  3563. v
  3564. }
  3565. /// The console's decision of the branch closing IR block `b`, which the wave takes
  3566. /// together ([`Structured::wide`]): `when` is the lane's own bit, and the branch is taken
  3567. /// when some lane's `when` holds (`execnz`, `vccnz`, SCC of a mask operation set) or
  3568. /// when every lane's does (`execz`, `vccz`, that SCC clear), [`Structured::wave_any`].
  3569. /// Each host wave asks its lanes and the halves exchange the answers, so both go the
  3570. /// same way and can meet again inside the branch.
  3571. /// SCC of a mask operation as data ([`Structured::scc_some`]): whether some lane of the
  3572. /// console wave has its bit of the result, asked where the operation stands. The lanes
  3573. /// that are elsewhere have no bit (the result is ANDed with EXEC or is EXEC), so with
  3574. /// the console's waves the host wave's answer is the console's; two host waves of 32
  3575. /// exchange theirs, which needs every lane there.
  3576. fn scc_some(&mut self, scc: Value) -> Result<V, Why> {
  3577. let &m = self.x.st.scc_some.get(&scc).ok_or(LANE_MASK)?;
  3578. // (not for a console wave cut into host waves that do not exchange)
  3579. if !self.console_lanes || self.local || self.exchange.is_none() && self.halves.is_some() {
  3580. return Err(LANE_MASK);
  3581. }
  3582. let made = self.def_block.get(&scc).copied();
  3583. let at = match made {
  3584. None => self.s.entry,
  3585. Some(b) if b == self.cur_ir => self.cur,
  3586. Some(b) => self.tail[b].ok_or("a lane mask written after its use")?,
  3587. };
  3588. let bit = self.boolean(m, at)?;
  3589. let (i1t, i32t) = (self.s.t.i1, self.s.t.i32);
  3590. let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]);
  3591. self.s.flags |= flags::WAVE_OPS;
  3592. if !self.exchange.as_ref().is_some_and(|e| !e.1) {
  3593. return Ok(some);
  3594. }
  3595. if !made.is_none_or(|b| self.all_lanes(b)) {
  3596. need(made.unwrap_or(0));
  3597. return Err("a lane mask exchanged where not every lane runs");
  3598. }
  3599. let some = self.s.m.cast(at, Cast::ZExt, some, i32t);
  3600. let (lo, hi) = self.exchange_halves(at, some);
  3601. let both = self.s.m.bin(at, Bin::Or, lo, hi);
  3602. let z = self.s.m.i32(0);
  3603. Ok(self.s.m.cmp(at, pred::NE, both, z))
  3604. }
  3605. fn wave_wide(&mut self, b: usize, when: Bool) -> Result<V, Why> {
  3606. const WHY: Why = "a wave-wide branch where not every lane runs";
  3607. let any = self.x.st.wave_any.get(b).copied().flatten().ok_or("a wave-wide branch on a scalar condition")?;
  3608. if self.exchange.is_none() && self.halves.is_none() && self.console_lanes && self.mask_data == MaskData::Console {
  3609. // The host's waves are the console's: the wave's own answer. The lanes that are
  3610. // elsewhere have no bit set, as on the console, so "some lane" needs no one but
  3611. // the lanes here, and "every lane's bit is clear" is true of the others anyway.
  3612. let c = self.cur;
  3613. let mine = self.boolean(when, c)?;
  3614. let i1t = self.s.t.i1;
  3615. self.s.flags |= flags::WAVE_OPS;
  3616. let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) };
  3617. return Ok(self.s.op(c, name, Attr::NoUnwind, i1t, code, &[mine]));
  3618. }
  3619. if self.local || !self.exchange.as_ref().is_some_and(|e| !e.1) {
  3620. return Err(WHY);
  3621. }
  3622. if !self.all_lanes(b) {
  3623. need(b);
  3624. return Err(WHY);
  3625. }
  3626. let c = self.cur;
  3627. let mine = self.boolean(when, c)?;
  3628. // what the halves exchange is "some lane speaks against" either way (for `any`:
  3629. // some lane's `when` holds; else: some lane's does not), so a half with no lane says
  3630. // nothing
  3631. let set = if any {
  3632. mine
  3633. } else {
  3634. let t = self.s.m.bool(true);
  3635. self.s.m.bin(c, Bin::Xor, mine, t)
  3636. };
  3637. let (i1t, i32t) = (self.s.t.i1, self.s.t.i32);
  3638. let some = self.s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]);
  3639. self.s.flags |= flags::WAVE_OPS;
  3640. let some = self.s.m.cast(c, Cast::ZExt, some, i32t);
  3641. let (lo, hi) = self.exchange_halves(c, some);
  3642. let c = self.cur;
  3643. let both = self.s.m.bin(c, Bin::Or, lo, hi);
  3644. let z = self.s.m.i32(0);
  3645. Ok(self.s.m.cmp(c, if any { pred::NE } else { pred::EQ }, both, z))
  3646. }
  3647. /// Whether every lane runs IR block `b` (always true without `exchange`).
  3648. fn all_lanes(&self, b: usize) -> bool {
  3649. self.exchange.as_ref().is_none_or(|(_, _, all)| all.get(b).copied().unwrap_or(false))
  3650. }
  3651. /// This lane's bit of the mask `lo`, `hi` (wave64).
  3652. fn lane_bit(&mut self, at: usize, lo: V, hi: Option<V>) -> V {
  3653. self.s.flags |= flags::WAVE_OPS;
  3654. let lane = if self.exchange.is_some() {
  3655. self.console_lane()
  3656. } else {
  3657. self.s.op(at, "waveGetLaneIndex", Attr::ReadOnly, self.s.t.i32, 111, &[])
  3658. };
  3659. let (k31, k32, one, z) = (
  3660. self.s.m.i32(31),
  3661. self.s.m.i32(32),
  3662. self.s.m.i32(1),
  3663. self.s.m.i32(0),
  3664. );
  3665. let word = match hi {
  3666. Some(hi) => {
  3667. let low = self.s.m.cmp(at, pred::IULT, lane, k32);
  3668. self.s.m.select(at, low, lo, hi)
  3669. }
  3670. None => lo,
  3671. };
  3672. let sh = self.s.m.bin(at, Bin::And, lane, k31);
  3673. let t = self.s.m.bin(at, Bin::LShr, word, sh);
  3674. let t = self.s.m.bin(at, Bin::And, t, one);
  3675. self.s.m.cmp(at, pred::NE, t, z)
  3676. }
  3677. /// The value of the high dword of the wave64 register pair whose low
  3678. /// dword holds `lo` (none in wave32).
  3679. fn pair_high(&self, lo: Value) -> Option<Value> {
  3680. if !self.x.native.wave64 {
  3681. return None;
  3682. }
  3683. let p = self.x.p;
  3684. let pick = |reg: Reg| match reg {
  3685. Reg::S(c) => Some(Reg::S(c + 1)),
  3686. _ => None,
  3687. };
  3688. if let Some(&(reg, _)) = p.inputs.iter().find(|i| i.1 == lo) {
  3689. let h = pick(reg)?;
  3690. return p.inputs.iter().find(|i| i.0 == h).map(|i| i.1);
  3691. }
  3692. if let Some(&(b, i)) = self.phi_at.get(&lo) {
  3693. let h = pick(p.blocks[b].phis[i].reg)?;
  3694. return p.blocks[b]
  3695. .phis
  3696. .iter()
  3697. .find(|q| q.reg == h)
  3698. .map(|q| q.value);
  3699. }
  3700. let b = *self.def_block.get(&lo)?;
  3701. let inst = p.blocks[b]
  3702. .insts
  3703. .iter()
  3704. .find(|i| i.writes.iter().any(|w| w.1 == lo))?;
  3705. let &(reg, _) = inst.writes.iter().find(|w| w.1 == lo)?;
  3706. inst.write(pick(reg)?)
  3707. }
  3708. fn guard(&mut self, b: usize, i: usize) -> Result<Option<V>, Why> {
  3709. match self.x.st.guards[b][i] {
  3710. None => Ok(None),
  3711. Some(g) => Ok(Some(self.boolean(g, self.cur)?)),
  3712. }
  3713. }
  3714. // ---- results ----
  3715. fn set(&mut self, v: Option<Value>, val: Val) {
  3716. if let Some(v) = v {
  3717. self.vals.insert(v, val);
  3718. }
  3719. }
  3720. /// Writes VGPR `reg` (or the SGPR of a lane read), under `guard`.
  3721. fn write(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) {
  3722. let x = match (Self::sdwa_dst(inst), reg) {
  3723. (Some((sel, unused)), Reg::V(_)) => self.place_bits(inst, reg, x, sel, unused),
  3724. _ => x,
  3725. };
  3726. self.write_placed(inst, reg, x, guard);
  3727. }
  3728. /// [`Self::write`] of a dword already placed (SDWA applied).
  3729. fn write_placed(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) {
  3730. let Some(new) = inst.write(reg) else { return };
  3731. let x = match (guard, reg) {
  3732. (Some(g), Reg::V(_)) => {
  3733. let old = match inst.read(reg).map(|o| self.i32_of(o)) {
  3734. Some(Ok(o)) => o,
  3735. // The validator refuses reads of undef.
  3736. _ => self.s.m.i32(0),
  3737. };
  3738. self.s.m.select(self.cur, g, x, old)
  3739. }
  3740. _ => x,
  3741. };
  3742. self.vals.insert(new, Val::I32(x));
  3743. }
  3744. /// The SDWA destination selection: a byte or word, and what the other
  3745. /// bits get (0 zeros, 1 the sign above the field, 2 the old bits).
  3746. fn sdwa_dst(inst: &Inst) -> Option<(u8, u8)> {
  3747. let Fields::Valu(v) = &inst.fields else {
  3748. return None;
  3749. };
  3750. let s = v.sdwa?;
  3751. (s.dst_sel < 6).then_some((s.dst_sel, s.dst_unused))
  3752. }
  3753. /// The low byte or word of `x` placed at `sel` in VGPR `reg`.
  3754. fn place_bits(&mut self, inst: &Inst, reg: Reg, x: V, sel: u8, unused: u8) -> V {
  3755. let c = self.cur;
  3756. let (width, at) = if sel < 4 {
  3757. (8u32, 8 * u32::from(sel))
  3758. } else {
  3759. (16, 16 * u32::from(sel - 4))
  3760. };
  3761. let left = self.s.m.i32(32 - width);
  3762. let t = self.s.m.bin(c, Bin::Shl, x, left);
  3763. let right = self.s.m.i32(32 - width - at);
  3764. if unused == 1 {
  3765. // Bits below the field shift in as zeros.
  3766. return self.s.m.bin(c, Bin::AShr, t, right);
  3767. }
  3768. let field = self.s.m.bin(c, Bin::LShr, t, right);
  3769. if unused != 2 {
  3770. return field;
  3771. }
  3772. let old = match inst.read(reg).map(|o| self.i32_of(o)) {
  3773. Some(Ok(o)) => o,
  3774. _ => self.s.m.i32(0),
  3775. };
  3776. let keep = self.s.m.i32(!((((1u64 << width) - 1) as u32) << at));
  3777. let old = self.s.m.bin(c, Bin::And, old, keep);
  3778. self.s.m.bin(c, Bin::Or, old, field)
  3779. }
  3780. fn write_f(&mut self, inst: &Inst, f: V, guard: Option<V>) -> Result<(), Why> {
  3781. let Fields::Valu(v) = &inst.fields else {
  3782. unreachable!()
  3783. };
  3784. let mut f = f;
  3785. match v.omod {
  3786. 0 => {}
  3787. k => {
  3788. let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)];
  3789. let c = self.s.m.f32(factor.to_bits());
  3790. f = self.s.m.bin(self.cur, Bin::Mul, f, c);
  3791. }
  3792. }
  3793. if v.clamp {
  3794. f = self.unary(7, f);
  3795. }
  3796. let Some(Operand::Vector { reg, .. }) = v.dst else {
  3797. return Err("a float result outside a VGPR");
  3798. };
  3799. let x = self.as_int(f);
  3800. self.write(inst, Reg::V(reg), x, guard);
  3801. if guard.is_none()
  3802. && Self::sdwa_dst(inst).is_none()
  3803. && let Some(new) = inst.write(Reg::V(reg))
  3804. {
  3805. self.floats.insert(new, f);
  3806. }
  3807. Ok(())
  3808. }
  3809. fn write_i(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> {
  3810. let Fields::Valu(v) = &inst.fields else {
  3811. unreachable!()
  3812. };
  3813. if v.clamp || v.omod != 0 {
  3814. return Err("integer output modifiers");
  3815. }
  3816. match v.dst {
  3817. Some(Operand::Vector { reg, .. }) => self.write(inst, Reg::V(reg), x, guard),
  3818. Some(Operand::Scalar { code, .. }) => self.write(inst, Reg::S(code), x, None),
  3819. _ => return Err("a result without a register"),
  3820. }
  3821. Ok(())
  3822. }
  3823. /// Starts code only the lanes where `guard` holds run (a store under a
  3824. /// lane guard): returns where it started and the join block.
  3825. fn begin_guarded(&mut self, guard: Option<V>) -> Option<(usize, usize)> {
  3826. let g = guard?;
  3827. let (then, join) = (self.s.m.new_block(), self.s.m.new_block());
  3828. self.s.m.terminate(self.cur, Term::CondBr(g, then, join));
  3829. let head = self.cur;
  3830. self.cur = then;
  3831. Some((head, join))
  3832. }
  3833. /// Ends guarded code; each (value inside, value outside) becomes a phi.
  3834. fn end_guarded(&mut self, at: Option<(usize, usize)>, values: &[(V, V)]) -> Vec<V> {
  3835. let Some((head, join)) = at else {
  3836. return values.iter().map(|v| v.0).collect();
  3837. };
  3838. let then = self.cur;
  3839. self.s.m.terminate(then, Term::Br(join));
  3840. self.cur = join;
  3841. values
  3842. .iter()
  3843. .map(|&(inside, outside)| {
  3844. let ty = self.s.m.type_of(inside);
  3845. let phi = self.s.m.phi(join, ty);
  3846. self.s.m.set_phi(phi, vec![(inside, then), (outside, head)]);
  3847. phi
  3848. })
  3849. .collect()
  3850. }
  3851. /// Code that depends on the lane layout: wave operations, and in compute
  3852. /// the console's wave size (lanes are thread ids in group order there).
  3853. /// Pixel lanes match only within a quad.
  3854. fn cross_lane(&mut self, quad: bool) -> Result<(), Why> {
  3855. if self.s.mesh.is_some() {
  3856. // shortcut: no wave size for mesh shaders in SM 6.6, so host
  3857. // lanes cannot follow the console's; emulate through group-shared
  3858. // memory if mesh programs turn out to need these.
  3859. return Err("a cross-lane operation in a mesh shader");
  3860. }
  3861. if self.s.threads.is_none() && !(quad && self.s.pixel) {
  3862. return Err("a cross-lane operation outside compute");
  3863. }
  3864. debug_assert!(self.s.threads.is_none() || self.console_lanes);
  3865. self.s.flags |= flags::WAVE_OPS;
  3866. Ok(())
  3867. }
  3868. /// Component `c` of the thread id in the group. With console lanes, the
  3869. /// thread is relabelled so that its host lane is its console lane: the
  3870. /// flat id is the wave's first lane's, rounded down to the wave size,
  3871. /// plus the lane index. (A bijection while each host wave holds a
  3872. /// wave-aligned run of flat ids, as the console's waves do.)
  3873. fn thread_id(&mut self, c: u8) -> Val {
  3874. if !self.console_lanes {
  3875. return self.compute_id("threadIdInGroup.i32", 95, c);
  3876. }
  3877. let [x, y, _] = self.s.threads.expect("compute");
  3878. let e = self.s.entry;
  3879. let i32t = self.s.t.i32;
  3880. if self.halves.is_some() {
  3881. let f = self.console_thread();
  3882. self.s.flags |= flags::WAVE_OPS;
  3883. let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y));
  3884. return Val::I32(match c {
  3885. 0 => self.s.m.bin(e, Bin::URem, f, xk),
  3886. 1 => {
  3887. let t = self.s.m.bin(e, Bin::UDiv, f, xk);
  3888. self.s.m.bin(e, Bin::URem, t, yk)
  3889. }
  3890. _ => self.s.m.bin(e, Bin::UDiv, f, xy),
  3891. });
  3892. }
  3893. let flat = self.s.op(
  3894. e,
  3895. "flattenedThreadIdInGroup.i32",
  3896. Attr::ReadNone,
  3897. i32t,
  3898. 96,
  3899. &[],
  3900. );
  3901. let first = self.s.op(
  3902. e,
  3903. "waveReadLaneFirst.i32",
  3904. Attr::NoUnwind,
  3905. i32t,
  3906. 118,
  3907. &[flat],
  3908. );
  3909. let wave = self.s.wave_size.expect("set with console lanes");
  3910. let mask = self.s.m.i32(!(wave - 1));
  3911. let base = self.s.m.bin(e, Bin::And, first, mask);
  3912. let lane = self.lane_index();
  3913. let f = self.s.m.bin(e, Bin::Add, base, lane);
  3914. self.s.flags |= flags::WAVE_OPS;
  3915. let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y));
  3916. Val::I32(match c {
  3917. 0 => self.s.m.bin(e, Bin::URem, f, xk),
  3918. 1 => {
  3919. let t = self.s.m.bin(e, Bin::UDiv, f, xk);
  3920. self.s.m.bin(e, Bin::URem, t, yk)
  3921. }
  3922. _ => self.s.m.bin(e, Bin::UDiv, f, xy),
  3923. })
  3924. }
  3925. /// Mesh: the counts and the primitives no lane exports. The console's
  3926. /// counts come from one lane's allocation request, which DXIL cannot
  3927. /// express (one call, dominating every output write).
  3928. // shortcut: the counts are the declared maxima and each lane first culls
  3929. // its primitive (all indices 0, zero area), so primitives past the
  3930. // program's count are culled and vertices past it unused; this costs
  3931. // the host the unused vertex and primitive slots. Pass the program's own
  3932. // counts if that shows in frame time.
  3933. fn mesh_prologue(&mut self, mut mesh: super::shader::Mesh) -> Result<(), Why> {
  3934. let threads = self.s.threads.expect("mesh")[0];
  3935. if mesh.topology != 2 {
  3936. return Err("a mesh shader not drawing triangles");
  3937. }
  3938. if threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256 {
  3939. return Err("a mesh shader beyond the host's limits");
  3940. }
  3941. // D3D12 caps the outputs of the declared maxima at 32 KiB. Lane n
  3942. // writes only vertex n and primitive n, so maxima past the lanes are
  3943. // never reached: they come down to the lane count when the outputs
  3944. // do not fit.
  3945. use super::container::{MESH_OUTPUT_LIMIT, mesh_output_bytes};
  3946. let (outputs, prims) = (&self.s.outputs, &self.s.prims);
  3947. let fits = |m: super::shader::Mesh| {
  3948. mesh_output_bytes(outputs, prims, m.max_vertices, m.max_primitives) <= MESH_OUTPUT_LIMIT
  3949. };
  3950. if !fits(mesh) {
  3951. mesh.max_vertices = mesh.max_vertices.min(threads);
  3952. mesh.max_primitives = mesh.max_primitives.min(threads);
  3953. // shortcut: outputs past the cap even at the lane count are
  3954. // still emitted with the lower maxima (drivers take them);
  3955. // refuse them here if one hangs.
  3956. // Experiment (`VICTORY_MESH_OUTPUT_STRICT=1`): they are refused.
  3957. if !fits(mesh) && std::env::var_os("VICTORY_MESH_OUTPUT_STRICT").is_some() {
  3958. return Err("a mesh shader whose outputs pass the host's 32 KiB");
  3959. }
  3960. self.s.mesh = Some(mesh);
  3961. }
  3962. let e = self.s.entry;
  3963. let void = self.s.t.void;
  3964. let (v, p) = (
  3965. self.s.m.i32(mesh.max_vertices),
  3966. self.s.m.i32(mesh.max_primitives),
  3967. );
  3968. self.s
  3969. .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]);
  3970. let flat = self.mesh_thread();
  3971. let z = self.s.m.i32(0);
  3972. // Every primitive of the declared count starts culled, also those
  3973. // past the lanes (a count of 256 with 128 lanes): lane n culls
  3974. // primitives n, n + lanes, ... The host draws all it was promised,
  3975. // and one never written has whatever indices its memory held: long
  3976. // triangles over the whole target, each pixel of them shaded.
  3977. let passes = mesh.max_primitives.div_ceil(threads.max(1));
  3978. for pass in 0..passes {
  3979. let index = if pass == 0 {
  3980. flat
  3981. } else {
  3982. let past = self.s.m.i32(pass * threads);
  3983. self.s.m.bin(self.cur, Bin::Add, flat, past)
  3984. };
  3985. let guard = ((pass + 1) * threads > mesh.max_primitives)
  3986. .then(|| self.s.m.cmp(self.cur, pred::IULT, index, p));
  3987. let at = self.begin_guarded(guard);
  3988. self.s.op(
  3989. self.cur,
  3990. "emitIndices",
  3991. Attr::NoUnwind,
  3992. void,
  3993. 169,
  3994. &[index, z, z, z],
  3995. );
  3996. self.end_guarded(at, &[]);
  3997. }
  3998. Ok(())
  3999. }
  4000. /// Mesh: the thread's index in the group, which is its vertex and
  4001. /// primitive index.
  4002. fn mesh_thread(&mut self) -> V {
  4003. if let Some(f) = self.flat {
  4004. return f;
  4005. }
  4006. let e = self.s.entry;
  4007. let f = self.s.op(
  4008. e,
  4009. "flattenedThreadIdInGroup.i32",
  4010. Attr::ReadNone,
  4011. self.s.t.i32,
  4012. 96,
  4013. &[],
  4014. );
  4015. self.flat = Some(f);
  4016. f
  4017. }
  4018. /// The console wave size.
  4019. fn wave(&self) -> u32 {
  4020. if self.x.native.wave64 { 64 } else { 32 }
  4021. }
  4022. fn lane_index(&mut self) -> V {
  4023. if self.s.mesh.is_some() {
  4024. // The console's lane: mesh code reads no other lanes, so host
  4025. // waves need not match the console's.
  4026. let f = self.mesh_thread();
  4027. let m = self.s.m.i32(self.wave() - 1);
  4028. return self.s.m.bin(self.s.entry, Bin::And, f, m);
  4029. }
  4030. self.s.op(
  4031. self.cur,
  4032. "waveGetLaneIndex",
  4033. Attr::ReadOnly,
  4034. self.s.t.i32,
  4035. 111,
  4036. &[],
  4037. )
  4038. }
  4039. /// `x` of lane `src` (in this lane's quad) through quad reads, whose
  4040. /// lane must be a constant.
  4041. fn quad_pick(&mut self, x: V, src: V) -> V {
  4042. self.s.flags |= flags::WAVE_OPS;
  4043. let c = self.cur;
  4044. let three = self.s.m.i32(3);
  4045. let q = self.s.m.bin(c, Bin::And, src, three);
  4046. let mut r = x;
  4047. for n in 0..4 {
  4048. let kn = self.s.m.i32(n);
  4049. let read = self.s.op(
  4050. c,
  4051. "quadReadLaneAt.i32",
  4052. Attr::NoUnwind,
  4053. self.s.t.i32,
  4054. 122,
  4055. &[x, kn],
  4056. );
  4057. let is = self.s.m.cmp(c, pred::EQ, q, kn);
  4058. r = self.s.m.select(c, is, read, r);
  4059. }
  4060. r
  4061. }
  4062. /// `x` in the first lane of this host wave where `guard` holds, and whether it has such a
  4063. /// lane: the console reads the first lane of EXEC, and a lane that got here with EXEC clear
  4064. /// (a guard, not a branch) is not one. With none, `x` of the wave's first lane here.
  4065. fn first_lane(&mut self, x: V, guard: Option<V>) -> (V, V) {
  4066. let c = self.cur;
  4067. let i32t = self.s.t.i32;
  4068. self.s.flags |= flags::WAVE_OPS;
  4069. let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[x]);
  4070. let Some(g) = guard else {
  4071. return (first, self.s.m.bool(true));
  4072. };
  4073. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  4074. let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[g]);
  4075. let (lo, hi) = (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1));
  4076. let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32));
  4077. // FirstbitLo (dx.op 32): the lowest set bit
  4078. let flo = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[lo]);
  4079. let fhi = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[hi]);
  4080. let fhi = self.s.m.bin(c, Bin::Add, fhi, k32);
  4081. let in_lo = self.s.m.cmp(c, pred::NE, lo, z);
  4082. let in_hi = self.s.m.cmp(c, pred::NE, hi, z);
  4083. let any = self.s.m.bin(c, Bin::Or, in_lo, in_hi);
  4084. let lane = self.s.m.select(c, in_lo, flo, fhi);
  4085. // no lane in EXEC: read this lane (one that is here); the read is not used
  4086. let me = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  4087. let lane = self.s.m.select(c, any, lane, me);
  4088. let at = self.read_lane(x, lane);
  4089. (self.s.m.select(c, any, at, first), any)
  4090. }
  4091. fn read_lane(&mut self, x: V, lane: V) -> V {
  4092. self.s.op(
  4093. self.cur,
  4094. "waveReadLaneAt.i32",
  4095. Attr::NoUnwind,
  4096. self.s.t.i32,
  4097. 117,
  4098. &[x, lane],
  4099. )
  4100. }
  4101. /// The float value of a register value.
  4102. fn float_of(&mut self, v: Value) -> Result<V, Why> {
  4103. if let Some(&f) = self.floats.get(&v) {
  4104. return Ok(f);
  4105. }
  4106. let x = self.i32_of(v)?;
  4107. Ok(self.as_float(x))
  4108. }
  4109. /// The values of VGPRs `reg..reg + n` as `inst` reads them.
  4110. fn vgprs(&mut self, inst: &Inst, op: &Operand, n: u8) -> Result<Vec<V>, Why> {
  4111. let Operand::Vector { reg, .. } = *op else {
  4112. return Err("a vector operand");
  4113. };
  4114. (0..n)
  4115. .map(|k| {
  4116. let v = inst.read(Reg::V(reg + k)).ok_or("an unread operand")?;
  4117. self.i32_of(v)
  4118. })
  4119. .collect()
  4120. }
  4121. /// LDS (thread-group shared memory) and `ds_swizzle`.
  4122. fn ds(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  4123. let Fields::Ds {
  4124. dst,
  4125. addr,
  4126. data,
  4127. offset0,
  4128. offset1,
  4129. gds,
  4130. } = &inst.fields
  4131. else {
  4132. unreachable!()
  4133. };
  4134. if *gds {
  4135. return Err("GDS");
  4136. }
  4137. let name = inst.name();
  4138. let guard = self.guard(b, i)?;
  4139. let c = self.cur;
  4140. let offset = u32::from(*offset0) | u32::from(*offset1) << 8;
  4141. let dst_reg = match dst {
  4142. Some(Operand::Vector { reg, .. }) => Some(*reg),
  4143. _ => None,
  4144. };
  4145. if name == "ds_swizzle_b32" {
  4146. // Bit 15 set: each lane of a quad picks a lane of it; else lanes
  4147. // of each group of 32 combine their index with and/or/xor masks.
  4148. let quad = offset & 0x8000 != 0
  4149. || offset & 0x1C == 0x1C && offset & 0x380 == 0 && offset >> 10 & 0x1F < 4;
  4150. // Mesh: host quads are threads 4n..4n+3 of a 1D group, as the
  4151. // console's, so quad-local swizzles read through quad operations.
  4152. let mesh_quad = self.s.mesh.is_some() && quad;
  4153. if !mesh_quad {
  4154. self.cross_lane(quad)?;
  4155. }
  4156. // The source sits in the address field.
  4157. let x = self.vgprs(inst, addr.as_ref().ok_or("a swizzle source")?, 1)?[0];
  4158. let lane = self.lane_index();
  4159. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  4160. let src = if offset & 0x8000 != 0 {
  4161. let (three, one) = (k(self, 3), k(self, 1));
  4162. let sel = self.s.m.bin(c, Bin::And, lane, three);
  4163. let sh = self.s.m.bin(c, Bin::Shl, sel, one);
  4164. let pattern = k(self, offset & 0xFF);
  4165. let pick = self.s.m.bin(c, Bin::LShr, pattern, sh);
  4166. let pick = self.s.m.bin(c, Bin::And, pick, three);
  4167. let not3 = k(self, !3);
  4168. let base = self.s.m.bin(c, Bin::And, lane, not3);
  4169. self.s.m.bin(c, Bin::Or, base, pick)
  4170. } else {
  4171. let and = k(self, offset & 0x1F | !0x1F);
  4172. let or = k(self, offset >> 5 & 0x1F);
  4173. let xor = k(self, offset >> 10 & 0x1F);
  4174. let t = self.s.m.bin(c, Bin::And, lane, and);
  4175. let t = self.s.m.bin(c, Bin::Or, t, or);
  4176. self.s.m.bin(c, Bin::Xor, t, xor)
  4177. };
  4178. let r = if mesh_quad {
  4179. self.quad_pick(x, src)
  4180. } else {
  4181. self.read_lane(x, src)
  4182. };
  4183. let reg = dst_reg.ok_or("a swizzle result")?;
  4184. self.write(inst, Reg::V(reg), r, guard);
  4185. return Ok(());
  4186. }
  4187. if name == "ds_bpermute_b32" {
  4188. // Backward permute: no LDS is touched. Each lane takes the data
  4189. // register of the lane its address names, (address + offset) / 4
  4190. // within the wave; a source lane outside EXEC gives 0. (Grand
  4191. // Theft Auto VI's checkerboard shadow-mask generators read their
  4192. // neighbours' samples with it; without them every shadowed light
  4193. // was multiplied by an empty mask.)
  4194. // shortcut: a source lane that is not at this instruction on the
  4195. // host (it left through a branch, not a guard) is read as the
  4196. // host gives it; the console reads 0.
  4197. self.cross_lane(false)?;
  4198. if self.exchange.as_ref().is_some_and(|e| !e.1) {
  4199. // a console wave of 64 run as two host waves: the lane named
  4200. // may be in the other one
  4201. return Err("a lane permute across two host waves");
  4202. }
  4203. let at = self.vgprs(inst, addr.as_ref().ok_or("a permute address")?, 1)?[0];
  4204. let x = self.vgprs(inst, data.first().ok_or("a permute source")?, 1)?[0];
  4205. let o = self.s.m.i32(offset);
  4206. let at = self.s.m.bin(c, Bin::Add, at, o);
  4207. let two = self.s.m.i32(2);
  4208. let src = self.s.m.bin(c, Bin::LShr, at, two);
  4209. let last = self.s.m.i32(self.wave() - 1);
  4210. let src = self.s.m.bin(c, Bin::And, src, last);
  4211. let x = match guard {
  4212. Some(g) => {
  4213. let z = self.s.m.i32(0);
  4214. self.s.m.select(c, g, x, z)
  4215. }
  4216. None => x,
  4217. };
  4218. let r = self.read_lane(x, src);
  4219. let reg = dst_reg.ok_or("a permute result")?;
  4220. self.write(inst, Reg::V(reg), r, guard);
  4221. return Ok(());
  4222. }
  4223. if self.s.lds_dwords == 0 {
  4224. return Err("LDS the program does not allocate");
  4225. }
  4226. let a = self.vgprs(inst, addr.as_ref().ok_or("an LDS address")?, 1)?[0];
  4227. // shortcut: LDS addresses are taken as dword-aligned and in bounds
  4228. // (out-of-bounds console accesses read 0 and drop writes).
  4229. let dword = |l: &mut Self, bytes: u32| -> V {
  4230. let c = l.cur;
  4231. let o = l.s.m.i32(bytes);
  4232. let at = l.s.m.bin(c, Bin::Add, a, o);
  4233. let two = l.s.m.i32(2);
  4234. let index = l.s.m.bin(c, Bin::LShr, at, two);
  4235. let lds = l.s.lds();
  4236. l.s.m.element(c, lds, index)
  4237. };
  4238. let width = |n: &str| match n.rsplit('_').next() {
  4239. Some("b64") => 2,
  4240. Some("b96") => 3,
  4241. Some("b128") => 4,
  4242. _ => 1,
  4243. };
  4244. // (byte offset, dwords) per element; read2/write2 scale their two
  4245. // offsets by the element size (×64 for st64).
  4246. let pair = |n: &str| -> Vec<(u32, u32)> {
  4247. let w = width(n);
  4248. let scale = 4 * w * if n.contains("st64") { 64 } else { 1 };
  4249. vec![
  4250. (u32::from(*offset0) * scale, w),
  4251. (u32::from(*offset1) * scale, w),
  4252. ]
  4253. };
  4254. // Bytes and halves: the dword holding them, and their bit position
  4255. // in it (naturally aligned, so they never straddle dwords).
  4256. // `_d16` reads fill a register's low half (`_d16_hi` its high half)
  4257. // and keep the other; `_d16_hi` writes take the data's high half.
  4258. let base = name.trim_end_matches("_hi").trim_end_matches("_d16");
  4259. let sub = match base {
  4260. "ds_read_u8" | "ds_read_i8" | "ds_write_b8" => Some(8u32),
  4261. "ds_read_u16" | "ds_read_i16" | "ds_write_b16" => Some(16),
  4262. _ => None,
  4263. };
  4264. let sub = sub.filter(|_| {
  4265. base == name
  4266. || name.ends_with("_d16") && base.starts_with("ds_read")
  4267. || name.ends_with("_d16_hi")
  4268. });
  4269. if let Some(bits) = sub {
  4270. let p = dword(self, offset);
  4271. let o = self.s.m.i32(offset);
  4272. let at = self.s.m.bin(c, Bin::Add, a, o);
  4273. let three = self.s.m.i32(3);
  4274. let byte = self.s.m.bin(c, Bin::And, at, three);
  4275. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  4276. let mask = self.s.m.i32((1u32 << bits) - 1);
  4277. if name.starts_with("ds_read") {
  4278. let reg = dst_reg.ok_or("an LDS read result")?;
  4279. let w = self.s.m.load(c, p);
  4280. let x = self.s.m.bin(c, Bin::LShr, w, sh);
  4281. let x = if base.contains("_i") {
  4282. let k = self.s.m.i32(32 - bits);
  4283. let x = self.s.m.bin(c, Bin::Shl, x, k);
  4284. self.s.m.bin(c, Bin::AShr, x, k)
  4285. } else {
  4286. self.s.m.bin(c, Bin::And, x, mask)
  4287. };
  4288. let x = if base == name {
  4289. x
  4290. } else {
  4291. let old = match inst.read(Reg::V(reg)) {
  4292. Some(v) => self.i32_of(v)?,
  4293. None => self.s.m.i32(0),
  4294. };
  4295. let half = self.s.m.i32(0xFFFF);
  4296. let x = self.s.m.bin(c, Bin::And, x, half);
  4297. let (x, keep) = if name.ends_with("_hi") {
  4298. let k16 = self.s.m.i32(16);
  4299. (self.s.m.bin(c, Bin::Shl, x, k16), half)
  4300. } else {
  4301. (x, self.s.m.i32(0xFFFF_0000))
  4302. };
  4303. let old = self.s.m.bin(c, Bin::And, old, keep);
  4304. self.s.m.bin(c, Bin::Or, old, x)
  4305. };
  4306. self.write(inst, Reg::V(reg), x, guard);
  4307. } else {
  4308. // Clear, then set: two atomics, so lanes writing other
  4309. // bytes of the dword keep theirs.
  4310. let mut x = self.vgprs(inst, data.first().ok_or("an LDS write")?, 1)?[0];
  4311. if name != base {
  4312. // The data's high half.
  4313. let k16 = self.s.m.i32(16);
  4314. x = self.s.m.bin(c, Bin::LShr, x, k16);
  4315. }
  4316. let x = self.s.m.bin(c, Bin::And, x, mask);
  4317. let x = self.s.m.bin(c, Bin::Shl, x, sh);
  4318. let m = self.s.m.bin(c, Bin::Shl, mask, sh);
  4319. let ones = self.s.m.i32(u32::MAX);
  4320. let keep = self.s.m.bin(c, Bin::Xor, m, ones);
  4321. use super::bitcode::Rmw;
  4322. let at = self.begin_guarded(guard);
  4323. self.s.m.atomic(self.cur, Rmw::And, p, keep);
  4324. self.s.m.atomic(self.cur, Rmw::Or, p, x);
  4325. self.end_guarded(at, &[]);
  4326. }
  4327. return Ok(());
  4328. }
  4329. if let Some(rest) = name.strip_prefix("ds_read") {
  4330. let elements = if rest.starts_with('2') {
  4331. pair(name)
  4332. } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") {
  4333. vec![(offset, width(name))]
  4334. } else {
  4335. return Err("an LDS read of bytes or halves");
  4336. };
  4337. let reg = dst_reg.ok_or("an LDS read result")?;
  4338. let mut n = 0;
  4339. for (off, w) in elements {
  4340. for k in 0..w {
  4341. let p = dword(self, off + 4 * k);
  4342. let x = self.s.m.load(self.cur, p);
  4343. self.write(inst, Reg::V(reg + n), x, guard);
  4344. n += 1;
  4345. }
  4346. }
  4347. return Ok(());
  4348. }
  4349. if let Some(rest) = name.strip_prefix("ds_write") {
  4350. let elements = if rest.starts_with('2') {
  4351. pair(name)
  4352. } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") {
  4353. vec![(offset, width(name))]
  4354. } else {
  4355. return Err("an LDS write of bytes or halves");
  4356. };
  4357. let mut stores = Vec::new();
  4358. for (e, (off, w)) in elements.into_iter().enumerate() {
  4359. let vals = self.vgprs(inst, data.get(e).ok_or("an LDS write")?, w as u8)?;
  4360. for (k, x) in vals.into_iter().enumerate() {
  4361. stores.push((off + 4 * k as u32, x));
  4362. }
  4363. }
  4364. let at = self.begin_guarded(guard);
  4365. for (off, x) in stores {
  4366. let p = dword(self, off);
  4367. self.s.m.store(self.cur, p, x);
  4368. }
  4369. self.end_guarded(at, &[]);
  4370. return Ok(());
  4371. }
  4372. // Atomics: the old value returns with `_rtn`.
  4373. let op = name
  4374. .strip_prefix("ds_")
  4375. .map(|n| n.replace("_rtn", ""))
  4376. .ok_or("an LDS operation")?;
  4377. use super::bitcode::Rmw;
  4378. let rmw = match op.as_str() {
  4379. "add_u32" => Some(Rmw::Add),
  4380. "sub_u32" => Some(Rmw::Sub),
  4381. "and_b32" => Some(Rmw::And),
  4382. "or_b32" => Some(Rmw::Or),
  4383. "xor_b32" => Some(Rmw::Xor),
  4384. "min_i32" => Some(Rmw::Min),
  4385. "max_i32" => Some(Rmw::Max),
  4386. "min_u32" => Some(Rmw::UMin),
  4387. "max_u32" => Some(Rmw::UMax),
  4388. "wrxchg_b32" => Some(Rmw::Xchg),
  4389. "cmpst_b32" | "max_f32" | "min_f32" => None,
  4390. _ => return Err("an LDS operation"),
  4391. };
  4392. let v0 = self.vgprs(inst, data.first().ok_or("an LDS atomic")?, 1)?[0];
  4393. let v1 = match data.get(1) {
  4394. Some(d) => Some(self.vgprs(inst, d, 1)?[0]),
  4395. None => None,
  4396. };
  4397. let old_reg = dst_reg.and_then(|r| inst.read(Reg::V(r)).map(|v| (r, v)));
  4398. let outside = match old_reg {
  4399. Some((_, v)) => self.i32_of(v).unwrap_or(self.s.m.i32(0)),
  4400. None => self.s.m.i32(0),
  4401. };
  4402. let p = dword(self, offset);
  4403. if let Some(max) = match op.as_str() {
  4404. "max_f32" => Some(true),
  4405. "min_f32" => Some(false),
  4406. _ => None,
  4407. } {
  4408. let at = self.begin_guarded(guard);
  4409. let r = self.lds_float_min_max(p, v0, max);
  4410. let r = self.end_guarded(at, &[(r, outside)])[0];
  4411. if let Some(reg) = dst_reg {
  4412. self.write(inst, Reg::V(reg), r, None);
  4413. }
  4414. return Ok(());
  4415. }
  4416. let at = self.begin_guarded(guard);
  4417. let r = match rmw {
  4418. Some(op) => self.s.m.atomic(self.cur, op, p, v0),
  4419. // Compare with data0, store data1.
  4420. None => self
  4421. .s
  4422. .m
  4423. .cmpxchg(self.cur, p, v0, v1.ok_or("an LDS compare")?),
  4424. };
  4425. let r = self.end_guarded(at, &[(r, outside)])[0];
  4426. if let Some(reg) = dst_reg {
  4427. self.write(inst, Reg::V(reg), r, None);
  4428. }
  4429. Ok(())
  4430. }
  4431. /// `ds_max_f32` (`max`) or `ds_min_f32` on the LDS dword at `p` with
  4432. /// the float bits `data`; the old bits return.
  4433. ///
  4434. /// DXIL has no float atomics on group-shared memory, so this is a
  4435. /// compare-exchange loop around [`Lower::lds_float_pick`], which gives
  4436. /// what RDNA2 writes (measured on gfx1036, reported on the pull
  4437. /// request): an sNaN, data first, then memory, is written quieted;
  4438. /// otherwise a NaN loses to a number (two quiet NaNs give the data);
  4439. /// numbers compare as floats with -0 below +0.
  4440. // shortcut: f32 denormals compare as kept; with the console's MODE
  4441. // flushing them they would order as ±0 first (MODE is not modelled).
  4442. fn lds_float_min_max(&mut self, p: V, data: V, max: bool) -> V {
  4443. let pre = self.cur;
  4444. let init = self.s.m.load(pre, p);
  4445. let (lp, exit) = (self.s.m.new_block(), self.s.m.new_block());
  4446. self.s.m.terminate(pre, Term::Br(lp));
  4447. let i32t = self.s.t.i32;
  4448. let old = self.s.m.phi(lp, i32t);
  4449. self.cur = lp;
  4450. let new = self.lds_float_pick(old, data, max);
  4451. let prev = self.s.m.cmpxchg(lp, p, old, new);
  4452. let done = self.s.m.cmp(lp, pred::EQ, prev, old);
  4453. self.s.m.set_phi(old, vec![(init, pre), (prev, lp)]);
  4454. self.s.m.terminate(lp, Term::CondBr(done, exit, lp));
  4455. self.cur = exit;
  4456. old
  4457. }
  4458. /// What `ds_max_f32` (`max`) or `ds_min_f32` writes over the dword
  4459. /// `mem` with `data` (float bits; see [`Lower::lds_float_min_max`]).
  4460. fn lds_float_pick(&mut self, mem: V, data: V, max: bool) -> V {
  4461. let c = self.cur;
  4462. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  4463. let (abs_mask, inf, quiet, zero) = (
  4464. k(self, 0x7FFF_FFFF),
  4465. k(self, 0x7F80_0000),
  4466. k(self, 0x40_0000),
  4467. k(self, 0),
  4468. );
  4469. let nan = |l: &mut Self, x: V| {
  4470. let m = l.s.m.bin(c, Bin::And, x, abs_mask);
  4471. l.s.m.cmp(c, pred::IUGT, m, inf)
  4472. };
  4473. let snan = |l: &mut Self, x: V| {
  4474. let n = nan(l, x);
  4475. let q = l.s.m.bin(c, Bin::And, x, quiet);
  4476. let sig = l.s.m.cmp(c, pred::EQ, q, zero);
  4477. l.s.m.bin(c, Bin::And, n, sig)
  4478. };
  4479. // A total order of the numbers as signed integers, -0 below +0:
  4480. // negative floats' magnitude bits reversed.
  4481. let key = |l: &mut Self, x: V| {
  4482. let k31 = l.s.m.i32(31);
  4483. let sign = l.s.m.bin(c, Bin::AShr, x, k31);
  4484. let flip = l.s.m.bin(c, Bin::And, sign, abs_mask);
  4485. l.s.m.bin(c, Bin::Xor, x, flip)
  4486. };
  4487. let (dk, mk) = (key(self, data), key(self, mem));
  4488. let take = self
  4489. .s
  4490. .m
  4491. .cmp(c, if max { pred::SGT } else { pred::SLT }, dk, mk);
  4492. let r = self.s.m.select(c, take, data, mem);
  4493. let (dn, mn) = (nan(self, data), nan(self, mem));
  4494. // One NaN: the number; two quiet NaNs: the data.
  4495. let r = self.s.m.select(c, mn, data, r);
  4496. let both = self.s.m.bin(c, Bin::And, dn, mn);
  4497. let only_data = {
  4498. let t = self.s.m.bool(true);
  4499. let not_both = self.s.m.bin(c, Bin::Xor, both, t);
  4500. self.s.m.bin(c, Bin::And, dn, not_both)
  4501. };
  4502. let r = self.s.m.select(c, only_data, mem, r);
  4503. // Signalling NaNs win, quieted: the data's first.
  4504. let qm = self.s.m.bin(c, Bin::Or, mem, quiet);
  4505. let sm = snan(self, mem);
  4506. let r = self.s.m.select(c, sm, qm, r);
  4507. let qd = self.s.m.bin(c, Bin::Or, data, quiet);
  4508. let sd = snan(self, data);
  4509. self.s.m.select(c, sd, qd, r)
  4510. }
  4511. // ---- instructions ----
  4512. // ---- instructions ----
  4513. fn inst(&mut self, b: usize, i: usize) -> Result<(), Stop> {
  4514. let inst: &'a Inst = &self.x.p.blocks[b].insts[i];
  4515. let offset = inst.machine.offset;
  4516. let name = inst.name();
  4517. self.local_ok = name.starts_with("s_bcnt1_i32_")
  4518. || name.starts_with("s_ff1_i32_")
  4519. || name.starts_with("v_mbcnt_");
  4520. self.mask_ok = match self.mask_data {
  4521. MaskData::Console => true,
  4522. MaskData::Host => {
  4523. name.starts_with("s_bcnt1_i32_")
  4524. || name.starts_with("s_ff1_i32_")
  4525. || name.starts_with("v_mbcnt_")
  4526. || matches!(
  4527. name,
  4528. "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_u64" | "s_cmp_lg_u64"
  4529. )
  4530. }
  4531. // Mesh: only "do all lanes hold the first lane's value?" (`uniform_test`), which
  4532. // each host wave answers for itself.
  4533. MaskData::None => self.uniform_test(inst),
  4534. };
  4535. let effect = matches!(inst.fields, Fields::Exp { .. })
  4536. || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
  4537. || name.contains("store")
  4538. || name.contains("atomic")
  4539. || name == "s_barrier"
  4540. || matches!(inst.fields, Fields::Ds { .. })
  4541. && !(name.starts_with("ds_read")
  4542. || name.starts_with("ds_swizzle")
  4543. || name.contains("permute"));
  4544. if self.split_lds
  4545. && matches!(inst.fields, Fields::Ds { .. })
  4546. && !(name.starts_with("ds_swizzle") || name.contains("permute"))
  4547. && self.lds_meet.as_ref().is_none_or(|(all, _)| all[b])
  4548. {
  4549. // the two host waves of a console wave meet before each LDS access: what the other
  4550. // half wrote is visible, and what it still reads is not overwritten
  4551. let mode = self.s.m.i32(meeting_mode());
  4552. let void = self.s.t.void;
  4553. self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  4554. }
  4555. let r = match &inst.fields {
  4556. Fields::Sop { .. } => self.sop(inst),
  4557. Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()),
  4558. Fields::Sopp { .. } if name == "s_barrier" => {
  4559. // Thread-group sync with a shared-memory fence, and a UAV
  4560. // fence when the program writes UAVs (the waits before an
  4561. // s_barrier make those writes visible on the console).
  4562. let mut mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 };
  4563. // Without the wait for the group (bit 0) where not every
  4564. // lane arrives, or where the switch says so.
  4565. let waits = match super::group_sync() {
  4566. 0 => false,
  4567. 1 => !self.fence_only.contains(&b),
  4568. _ => true,
  4569. };
  4570. if !waits {
  4571. mode &= !1;
  4572. }
  4573. let mode = self.s.m.i32(mode);
  4574. let void = self.s.t.void;
  4575. self.s
  4576. .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  4577. Ok(())
  4578. }
  4579. Fields::Sopp { .. } => Ok(()),
  4580. Fields::Smem { .. } => self.smem(inst, (b, i)),
  4581. Fields::Valu(_) if name.starts_with("v_interp_") => self.interp(inst, (b, i)),
  4582. Fields::Valu(_) => self.valu(inst, b, i),
  4583. Fields::Vintrp { .. } => self.interp(inst, (b, i)),
  4584. // The ray and node test. A failure is a refusal at once: an
  4585. // instruction without a side effect otherwise only stops the
  4586. // program where its results are needed, and two trace programs
  4587. // came out without their test that way.
  4588. Fields::Image { .. } if name.starts_with("image_bvh") => {
  4589. return self
  4590. .bvh(inst, b, i)
  4591. .map_err(|why| unsupported(offset, why));
  4592. }
  4593. Fields::Image { .. } => self.image(inst, b, i),
  4594. Fields::Buffer { .. } => self.buffer(inst, b, i),
  4595. Fields::Exp { .. } => self.export(b, i),
  4596. Fields::Ds { .. } => self.ds(inst, b, i),
  4597. Fields::Flat { .. } if name.starts_with("global_") => self.flat(inst, b, i),
  4598. Fields::Flat { .. } => Err("flat memory"),
  4599. };
  4600. match r {
  4601. Ok(()) => Ok(()),
  4602. Err(why) if effect => Err(unsupported(offset, why)),
  4603. Err(why) => {
  4604. for &(_, v) in &inst.writes {
  4605. self.vals.insert(v, Val::Missing(why));
  4606. }
  4607. Ok(())
  4608. }
  4609. }
  4610. }
  4611. /// The two host waves of a console wave meet (a group barrier with a shared-memory
  4612. /// fence): LDS writes before are seen by reads after.
  4613. fn lds_meeting(&mut self) {
  4614. let mode = self.s.m.i32(meeting_mode());
  4615. let void = self.s.t.void;
  4616. self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  4617. }
  4618. /// Whether `v` is a register no program reads as a number: a descriptor dword without
  4619. /// a host value ([`Self::stale`]), a lane mask's dword (outside compute, where a ballot
  4620. /// gives the mask as data), or a join of only such values. Compiled code joins numbers
  4621. /// with numbers: where one of these meets numbers at a join, the register is dead on
  4622. /// that path (a variable set in one arm of a branch, its use behind a flag kept in a
  4623. /// VGPR).
  4624. fn dead(&self, v: Value, seen: &mut Vec<Value>) -> bool {
  4625. if self.stale.contains(&v) {
  4626. return true;
  4627. }
  4628. let st = self.x.st;
  4629. if self.mask_data != MaskData::Console
  4630. && (st.masks.contains_key(&v) || st.highs.contains_key(&v))
  4631. {
  4632. return true;
  4633. }
  4634. let Some(&(b, i)) = self.phi_at.get(&v) else {
  4635. return false;
  4636. };
  4637. if seen.contains(&v) {
  4638. return true;
  4639. }
  4640. seen.push(v);
  4641. self.x.p.blocks[b].phis[i]
  4642. .args
  4643. .iter()
  4644. .all(|&a| self.dead(a, seen))
  4645. }
  4646. /// `s_bcnt1_i32_b*` of the lanes that differ from the first lane's value:
  4647. /// `v_readfirstlane_b32 s, v`, `v_cmp_eq_u32 m, s, v`, `s_xor_b* d, m, exec`. The
  4648. /// compiler tests a value for being the same in the whole wave this way, to take a
  4649. /// scalar path; both paths give each lane the same result, so the lanes of a host
  4650. /// wave may ask it of their own first lane, whatever the wave's size.
  4651. fn uniform_test(&self, inst: &Inst) -> bool {
  4652. let p = self.x.p;
  4653. let writer = |v: Value| -> Option<&'a Inst> {
  4654. let b = *self.def_block.get(&v)?;
  4655. p.blocks[b]
  4656. .insts
  4657. .iter()
  4658. .find(|i| i.writes.iter().any(|w| w.1 == v))
  4659. };
  4660. let scalar = |i: &Inst, op: &Operand| match *op {
  4661. Operand::Scalar { code, .. } if code != NULL && code != EXEC => i.read(Reg::S(code)),
  4662. _ => None,
  4663. };
  4664. if !inst.name().starts_with("s_bcnt1_i32_") {
  4665. return false;
  4666. }
  4667. let Fields::Sop { src, .. } = &inst.fields else {
  4668. return false;
  4669. };
  4670. let Some(xor) = src.first().and_then(|o| scalar(inst, o)).and_then(writer) else {
  4671. return false;
  4672. };
  4673. let Fields::Sop { src, .. } = &xor.fields else {
  4674. return false;
  4675. };
  4676. if !matches!(xor.name(), "s_xor_b64" | "s_xor_b32")
  4677. || !src
  4678. .iter()
  4679. .any(|o| matches!(o, Operand::Scalar { code: EXEC, .. }))
  4680. {
  4681. return false;
  4682. }
  4683. let Some(cmp) = src.iter().find_map(|o| scalar(xor, o)).and_then(writer) else {
  4684. return false;
  4685. };
  4686. let Fields::Valu(f) = &cmp.fields else {
  4687. return false;
  4688. };
  4689. if !matches!(cmp.name(), "v_cmp_eq_u32" | "v_cmp_eq_i32") || f.sdwa.is_some() || f.dpp.is_some() {
  4690. return false;
  4691. }
  4692. let lanes = f.src.iter().find_map(|o| match *o {
  4693. Operand::Vector { reg, .. } => cmp.read(Reg::V(reg)),
  4694. _ => None,
  4695. });
  4696. let first = f.src.iter().find_map(|o| scalar(cmp, o)).and_then(writer);
  4697. lanes.is_some()
  4698. && first.is_some_and(|fl| {
  4699. fl.name() == "v_readfirstlane_b32"
  4700. && matches!(&fl.fields, Fields::Valu(g)
  4701. if matches!(g.src.first(), Some(&Operand::Vector { reg, .. })
  4702. if fl.read(Reg::V(reg)) == lanes))
  4703. })
  4704. }
  4705. fn is_mask(&self, v: Option<Value>) -> bool {
  4706. v.is_some_and(|v| self.x.st.masks.contains_key(&v))
  4707. }
  4708. fn sop(&mut self, inst: &Inst) -> Result<(), Why> {
  4709. let Fields::Sop { dst, src, imm } = &inst.fields else {
  4710. unreachable!()
  4711. };
  4712. let name = inst.name();
  4713. let scc = inst.write(Reg::Scc);
  4714. let dst_code = match dst {
  4715. Some(Operand::Scalar { code, .. }) => Some(*code),
  4716. _ => None,
  4717. };
  4718. let lo = dst_code.and_then(|c| inst.write(Reg::S(c)));
  4719. if inst.write(Reg::S(EXEC)).is_some() || self.is_mask(lo) {
  4720. return Err(LANE_MASK);
  4721. }
  4722. if matches!(
  4723. name,
  4724. "s_setreg_imm32_b32" | "s_setreg_b32" | "s_swappc_b64" | "s_version"
  4725. ) || name.starts_with("s_waitcnt")
  4726. {
  4727. // shortcut: the float MODE register is not modelled; s_swappc_b64 is the
  4728. // vertex fetch call, whose results arrive as inputs.
  4729. return Err("a register the emitter does not model");
  4730. }
  4731. if name == "s_getpc_b64" {
  4732. // The address of the next instruction is no number the host has: tables in
  4733. // the code are read by their tracked address. As a number the counter is
  4734. // that instruction's offset in the code, so an address paths join before
  4735. // one load is the byte in the code, whichever table each path took
  4736. // (resource tracking gives such a join as the computed term, with no base).
  4737. let z = self.s.m.i32(0);
  4738. let at = self.s.m.i32(inst.machine.offset as u32 + 4);
  4739. let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1)));
  4740. self.set(lo, Val::I32(at));
  4741. self.set(hi, Val::I32(z));
  4742. return Ok(());
  4743. }
  4744. let c = self.cur;
  4745. let src32 = |l: &mut Self, k: usize| -> Result<V, Why> {
  4746. // SOPK arithmetic reads its destination as the first source.
  4747. if k == 0 && matches!(name, "s_addk_i32" | "s_mulk_i32") {
  4748. let d = dst.as_ref().ok_or("a missing operand")?;
  4749. return l.operand(inst, d);
  4750. }
  4751. let op = src.get(k).ok_or("a missing operand")?;
  4752. l.operand(inst, op)
  4753. };
  4754. let sext16 = |l: &mut Self| l.s.m.i32(i32::from(imm.unwrap_or(0) as i16) as u32);
  4755. // Dword `h` of 64-bit source `k` (inline constants sign-extend).
  4756. let half = |l: &mut Self, k: usize, h: u8| -> Result<V, Why> {
  4757. match src.get(k) {
  4758. Some(&Operand::Scalar { code, .. }) if code != NULL => {
  4759. let v = inst.read(Reg::S(code + h)).ok_or("an unread operand")?;
  4760. l.i32_of(v)
  4761. }
  4762. Some(op) if h == 0 => l.operand(inst, op),
  4763. Some(Operand::Const(k)) => {
  4764. let x = crate::resource::inline(*k).ok_or("a special operand")?;
  4765. Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 }))
  4766. }
  4767. _ => Ok(l.s.m.i32(0)),
  4768. }
  4769. };
  4770. if let Some(op) = name.strip_prefix("s_bitcmp") {
  4771. // SCC is whether bit src1 (mod 32, or mod 64 for the 64-bit form)
  4772. // of src0 is clear (bitcmp0) or set (bitcmp1).
  4773. let (bit, k31) = (src32(self, 1)?, self.s.m.i32(31));
  4774. let idx = self.s.m.bin(c, Bin::And, bit, k31);
  4775. let word = if op.ends_with("_b64") {
  4776. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  4777. let k32 = self.s.m.i32(32);
  4778. let upper = self.s.m.bin(c, Bin::And, bit, k32);
  4779. let z = self.s.m.i32(0);
  4780. let upper = self.s.m.cmp(c, pred::NE, upper, z);
  4781. self.s.m.select(c, upper, b, a)
  4782. } else {
  4783. src32(self, 0)?
  4784. };
  4785. let shifted = self.s.m.bin(c, Bin::LShr, word, idx);
  4786. let one = self.s.m.i32(1);
  4787. let tested = self.s.m.bin(c, Bin::And, shifted, one);
  4788. let want = self.s.m.i32(u32::from(op.starts_with('1')));
  4789. let r = self.s.m.cmp(c, pred::EQ, tested, want);
  4790. self.set(scc, Val::Bit(r));
  4791. return Ok(());
  4792. }
  4793. if let Some(op) = name.strip_prefix("s_cmp_").filter(|o| o.ends_with("_u64")) {
  4794. // eq and lg only: both dwords.
  4795. let mut r = None;
  4796. for h in 0..2 {
  4797. let (a, b) = (half(self, 0, h)?, half(self, 1, h)?);
  4798. let e = self.s.m.cmp(c, pred::EQ, a, b);
  4799. r = Some(match r {
  4800. Some(x) => self.s.m.bin(c, Bin::And, x, e),
  4801. None => e,
  4802. });
  4803. }
  4804. let mut r = r.expect("two dwords");
  4805. if op.starts_with("lg") {
  4806. let t = self.s.m.bool(true);
  4807. r = self.s.m.bin(c, Bin::Xor, r, t);
  4808. }
  4809. self.set(scc, Val::Bit(r));
  4810. return Ok(());
  4811. }
  4812. if let Some(op) = name.strip_prefix("s_cmp_").or(name.strip_prefix("s_cmpk_")) {
  4813. let (a, b) = if name.starts_with("s_cmpk_") {
  4814. let b = if op.ends_with("_i32") {
  4815. sext16(self)
  4816. } else {
  4817. self.s.m.i32(u32::from(imm.unwrap_or(0)))
  4818. };
  4819. (src32(self, 0)?, b)
  4820. } else {
  4821. if op.ends_with("64") {
  4822. return Err("a 64-bit scalar compare");
  4823. }
  4824. (src32(self, 0)?, src32(self, 1)?)
  4825. };
  4826. let signed = op.ends_with("_i32");
  4827. let p = match &op[..2] {
  4828. "eq" => pred::EQ,
  4829. "lg" => pred::NE,
  4830. "gt" if signed => pred::SGT,
  4831. "ge" if signed => pred::SGE,
  4832. "lt" if signed => pred::SLT,
  4833. "le" if signed => pred::SLE,
  4834. "gt" => pred::IUGT,
  4835. "ge" => pred::IUGE,
  4836. "lt" => pred::IULT,
  4837. "le" => pred::IULE,
  4838. _ => return Err("a scalar compare"),
  4839. };
  4840. let r = self.s.m.cmp(c, p, a, b);
  4841. self.set(scc, Val::Bit(r));
  4842. return Ok(());
  4843. }
  4844. let wide = name.ends_with("_b64") || name.ends_with("_u64") || name.ends_with("_i64");
  4845. if wide {
  4846. let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1)));
  4847. let nonzero = |l: &mut Self, a: V, b: V| {
  4848. let o = l.s.m.bin(c, Bin::Or, a, b);
  4849. let z = l.s.m.i32(0);
  4850. l.s.m.cmp(c, pred::NE, o, z)
  4851. };
  4852. return match name {
  4853. "s_bcnt1_i32_b64" => {
  4854. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  4855. let i32t = self.s.t.i32;
  4856. let na = self
  4857. .s
  4858. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[a]);
  4859. let nb = self
  4860. .s
  4861. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[b]);
  4862. let r = self.s.m.bin(c, Bin::Add, na, nb);
  4863. self.set(lo, Val::I32(r));
  4864. let z = self.s.m.i32(0);
  4865. let s = self.s.m.cmp(c, pred::NE, r, z);
  4866. self.set(scc, Val::Bit(s));
  4867. Ok(())
  4868. }
  4869. "s_ff1_i32_b64" => {
  4870. // The lowest set bit; -1 for none (as DXIL's first bit low).
  4871. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  4872. let i32t = self.s.t.i32;
  4873. let fa = self
  4874. .s
  4875. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[a]);
  4876. let fb = self
  4877. .s
  4878. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[b]);
  4879. let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32));
  4880. let fb32 = self.s.m.bin(c, Bin::Add, fb, k32);
  4881. let none = self.s.m.cmp(c, pred::EQ, b, z);
  4882. let fb = self.s.m.select(c, none, fb, fb32);
  4883. let low = self.s.m.cmp(c, pred::NE, a, z);
  4884. let r = self.s.m.select(c, low, fa, fb);
  4885. self.set(lo, Val::I32(r));
  4886. Ok(())
  4887. }
  4888. "s_and_b64" | "s_or_b64" | "s_xor_b64" | "s_andn2_b64" | "s_orn2_b64"
  4889. | "s_nand_b64" | "s_nor_b64" | "s_xnor_b64" | "s_not_b64" => {
  4890. let ones = self.s.m.i32(u32::MAX);
  4891. let mut r = Vec::new();
  4892. for h in 0..2u8 {
  4893. let a = half(self, 0, h)?;
  4894. let x = if name == "s_not_b64" {
  4895. self.s.m.bin(c, Bin::Xor, a, ones)
  4896. } else {
  4897. let mut b = half(self, 1, h)?;
  4898. if name.contains("n2") {
  4899. b = self.s.m.bin(c, Bin::Xor, b, ones);
  4900. }
  4901. let op = match &name[2..5] {
  4902. "and" | "nan" => Bin::And,
  4903. "or_" | "orn" | "nor" => Bin::Or,
  4904. _ => Bin::Xor,
  4905. };
  4906. let x = self.s.m.bin(c, op, a, b);
  4907. if matches!(name, "s_nand_b64" | "s_nor_b64" | "s_xnor_b64") {
  4908. self.s.m.bin(c, Bin::Xor, x, ones)
  4909. } else {
  4910. x
  4911. }
  4912. };
  4913. r.push(x);
  4914. }
  4915. self.set(lo, Val::I32(r[0]));
  4916. self.set(hi, Val::I32(r[1]));
  4917. let s = nonzero(self, r[0], r[1]);
  4918. self.set(scc, Val::Bit(s));
  4919. Ok(())
  4920. }
  4921. "s_lshl_b64" | "s_lshr_b64" | "s_ashr_i64" => {
  4922. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  4923. let n = src32(self, 1)?;
  4924. let i64t = self.s.m.int(64);
  4925. self.s.flags |= flags::INT64;
  4926. let a = self.s.m.cast(c, Cast::ZExt, a, i64t);
  4927. let b = self.s.m.cast(c, Cast::ZExt, b, i64t);
  4928. let k32 = self.s.m.int_const(i64t, 32);
  4929. let b = self.s.m.bin(c, Bin::Shl, b, k32);
  4930. let x = self.s.m.bin(c, Bin::Or, a, b);
  4931. let k63 = self.s.m.i32(63);
  4932. let n = self.s.m.bin(c, Bin::And, n, k63);
  4933. let n = self.s.m.cast(c, Cast::ZExt, n, i64t);
  4934. let op = match name {
  4935. "s_lshl_b64" => Bin::Shl,
  4936. "s_lshr_b64" => Bin::LShr,
  4937. _ => Bin::AShr,
  4938. };
  4939. let r = self.s.m.bin(c, op, x, n);
  4940. let rl = self.s.m.cast(c, Cast::Trunc, r, self.s.t.i32);
  4941. let rh = self.s.m.bin(c, Bin::LShr, r, k32);
  4942. let rh = self.s.m.cast(c, Cast::Trunc, rh, self.s.t.i32);
  4943. self.set(lo, Val::I32(rl));
  4944. self.set(hi, Val::I32(rh));
  4945. let s = nonzero(self, rl, rh);
  4946. self.set(scc, Val::Bit(s));
  4947. Ok(())
  4948. }
  4949. "s_mov_b64" => {
  4950. // Each half by itself: two numbers that travel as a pair (two scalars
  4951. // parked in neighbouring VGPR lanes, say) need not both have a value.
  4952. for (h, v) in [(0, lo), (1, hi)] {
  4953. let val = match half(self, 0, h) {
  4954. Ok(a) => Val::I32(a),
  4955. Err(why) => Val::Missing(why),
  4956. };
  4957. self.set(v, val);
  4958. }
  4959. Ok(())
  4960. }
  4961. "s_cselect_b64" => {
  4962. let cond = self.scc_in(inst)?;
  4963. for (h, v) in [(0, lo), (1, hi)] {
  4964. let (a, b) = (half(self, 0, h)?, half(self, 1, h)?);
  4965. let r = self.s.m.select(c, cond, a, b);
  4966. self.set(v, Val::I32(r));
  4967. }
  4968. Ok(())
  4969. }
  4970. _ => Err(name),
  4971. };
  4972. }
  4973. let m = &mut self.s.m;
  4974. let _ = m;
  4975. let (r, carry): (V, Option<V>) = match name {
  4976. "s_mov_b32" => (src32(self, 0)?, None),
  4977. "s_movk_i32" => (sext16(self), None),
  4978. "s_cselect_b32" => {
  4979. let cond = self.scc_in(inst)?;
  4980. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  4981. (self.s.m.select(c, cond, a, b), None)
  4982. }
  4983. "s_brev_b32" => {
  4984. let a = src32(self, 0)?;
  4985. let r = self
  4986. .s
  4987. .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a]);
  4988. (r, None)
  4989. }
  4990. "s_not_b32" => {
  4991. let a = src32(self, 0)?;
  4992. let ones = self.s.m.i32(u32::MAX);
  4993. (self.s.m.bin(c, Bin::Xor, a, ones), None)
  4994. }
  4995. "s_add_u32" | "s_add_i32" | "s_addk_i32" => {
  4996. let a = src32(self, 0)?;
  4997. let b = if name == "s_addk_i32" {
  4998. sext16(self)
  4999. } else {
  5000. src32(self, 1)?
  5001. };
  5002. let r = self.s.m.bin(c, Bin::Add, a, b);
  5003. let carry = if name == "s_add_u32" {
  5004. Some(self.s.m.cmp(c, pred::IULT, r, a))
  5005. } else {
  5006. None
  5007. };
  5008. (r, carry)
  5009. }
  5010. "s_sub_u32" | "s_sub_i32" => {
  5011. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5012. let r = self.s.m.bin(c, Bin::Sub, a, b);
  5013. let carry = (name == "s_sub_u32").then(|| self.s.m.cmp(c, pred::IULT, a, b));
  5014. (r, carry)
  5015. }
  5016. "s_addc_u32" | "s_subb_u32" => {
  5017. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5018. let cin = self.scc_in(inst)?;
  5019. let (r, carry) = self.add_sub_carry(c, name == "s_addc_u32", a, b, Some(cin));
  5020. (r, Some(carry))
  5021. }
  5022. "s_mul_i32" | "s_mulk_i32" => {
  5023. let a = src32(self, 0)?;
  5024. let b = if name == "s_mulk_i32" {
  5025. sext16(self)
  5026. } else {
  5027. src32(self, 1)?
  5028. };
  5029. (self.s.m.bin(c, Bin::Mul, a, b), None)
  5030. }
  5031. "s_mul_hi_u32" | "s_mul_hi_i32" => {
  5032. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5033. (self.mul_hi(a, b, name.ends_with("i32")), None)
  5034. }
  5035. "s_flbit_i32_b32" | "s_flbit_i32" => {
  5036. // The first bit from the top (differing from the sign for
  5037. // the signed form), -1 for none: DXIL's first-bit-high.
  5038. let a = src32(self, 0)?;
  5039. let op = if name == "s_flbit_i32_b32" { 33 } else { 34 };
  5040. let r = self
  5041. .s
  5042. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  5043. (r, None)
  5044. }
  5045. "s_ff1_i32_b32" | "s_bcnt1_i32_b32" => {
  5046. // First set bit (-1 for zero, as DXIL's), or the bit count.
  5047. let a = src32(self, 0)?;
  5048. let op = if name == "s_ff1_i32_b32" { 32 } else { 31 };
  5049. let r = self
  5050. .s
  5051. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  5052. (r, None)
  5053. }
  5054. "s_bfe_u32" | "s_bfe_i32" => {
  5055. // src1: offset in bits 0-4, width in bits 16-22.
  5056. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5057. let (k16, k127) = (self.s.m.i32(16), self.s.m.i32(0x7F));
  5058. let w = self.s.m.bin(c, Bin::LShr, b, k16);
  5059. let w = self.s.m.bin(c, Bin::And, w, k127);
  5060. (self.bfe(a, b, w, name == "s_bfe_i32"), None)
  5061. }
  5062. "s_and_b32" | "s_or_b32" | "s_xor_b32" | "s_andn2_b32" | "s_orn2_b32"
  5063. | "s_nand_b32" | "s_nor_b32" | "s_xnor_b32" => {
  5064. let (a, mut b) = (src32(self, 0)?, src32(self, 1)?);
  5065. let ones = self.s.m.i32(u32::MAX);
  5066. if name.contains("n2") {
  5067. b = self.s.m.bin(c, Bin::Xor, b, ones);
  5068. }
  5069. let op = match &name[2..5] {
  5070. "and" | "nan" => Bin::And,
  5071. "or_" | "orn" | "nor" => Bin::Or,
  5072. _ => Bin::Xor,
  5073. };
  5074. let mut r = self.s.m.bin(c, op, a, b);
  5075. if matches!(name, "s_nand_b32" | "s_nor_b32" | "s_xnor_b32") {
  5076. r = self.s.m.bin(c, Bin::Xor, r, ones);
  5077. }
  5078. (r, None)
  5079. }
  5080. "s_lshl_b32" | "s_lshr_b32" | "s_ashr_i32" => {
  5081. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5082. let k31 = self.s.m.i32(31);
  5083. let b = self.s.m.bin(c, Bin::And, b, k31);
  5084. let op = match name {
  5085. "s_lshl_b32" => Bin::Shl,
  5086. "s_lshr_b32" => Bin::LShr,
  5087. _ => Bin::AShr,
  5088. };
  5089. (self.s.m.bin(c, op, a, b), None)
  5090. }
  5091. "s_lshl1_add_u32" | "s_lshl2_add_u32" | "s_lshl3_add_u32" | "s_lshl4_add_u32" => {
  5092. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5093. let k = self.s.m.i32(u32::from(name.as_bytes()[6] - b'0'));
  5094. let t = self.s.m.bin(c, Bin::Shl, a, k);
  5095. (self.s.m.bin(c, Bin::Add, t, b), None)
  5096. }
  5097. "s_min_u32" | "s_max_u32" | "s_min_i32" | "s_max_i32" => {
  5098. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5099. let p = match name {
  5100. "s_min_u32" => pred::IULT,
  5101. "s_max_u32" => pred::IUGT,
  5102. "s_min_i32" => pred::SLT,
  5103. _ => pred::SGT,
  5104. };
  5105. let t = self.s.m.cmp(c, p, a, b);
  5106. (self.s.m.select(c, t, a, b), None)
  5107. }
  5108. "s_abs_i32" => {
  5109. let a = src32(self, 0)?;
  5110. let z = self.s.m.i32(0);
  5111. let neg = self.s.m.cmp(c, pred::SLT, a, z);
  5112. let n = self.s.m.bin(c, Bin::Sub, z, a);
  5113. (self.s.m.select(c, neg, n, a), None)
  5114. }
  5115. "s_bitset0_b32" | "s_bitset1_b32" => {
  5116. // Sets (clears) bit src[4:0] of the destination it reads.
  5117. let old = self.operand(inst, dst.as_ref().ok_or("a missing operand")?)?;
  5118. let a = src32(self, 0)?;
  5119. let (k31, one) = (self.s.m.i32(31), self.s.m.i32(1));
  5120. let a = self.s.m.bin(c, Bin::And, a, k31);
  5121. let bit = self.s.m.bin(c, Bin::Shl, one, a);
  5122. if name == "s_bitset1_b32" {
  5123. (self.s.m.bin(c, Bin::Or, old, bit), None)
  5124. } else {
  5125. let ones = self.s.m.i32(u32::MAX);
  5126. let nb = self.s.m.bin(c, Bin::Xor, bit, ones);
  5127. (self.s.m.bin(c, Bin::And, old, nb), None)
  5128. }
  5129. }
  5130. "s_bfm_b32" => {
  5131. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5132. let k31 = self.s.m.i32(31);
  5133. let one = self.s.m.i32(1);
  5134. let a = self.s.m.bin(c, Bin::And, a, k31);
  5135. let b = self.s.m.bin(c, Bin::And, b, k31);
  5136. let m = self.s.m.bin(c, Bin::Shl, one, a);
  5137. let m = self.s.m.bin(c, Bin::Sub, m, one);
  5138. (self.s.m.bin(c, Bin::Shl, m, b), None)
  5139. }
  5140. _ => return Err(name),
  5141. };
  5142. self.set(lo, Val::I32(r));
  5143. if let Some(scc) = scc {
  5144. let val = match carry {
  5145. Some(k) => Val::Bit(k),
  5146. None if matches!(
  5147. name,
  5148. "s_mov_b32"
  5149. | "s_movk_i32"
  5150. | "s_cselect_b32"
  5151. | "s_brev_b32"
  5152. | "s_mul_i32"
  5153. | "s_mulk_i32"
  5154. ) =>
  5155. {
  5156. return Ok(());
  5157. }
  5158. None if name.starts_with("s_add") || name.starts_with("s_sub") => {
  5159. Val::Missing("the carry of a scalar operation")
  5160. }
  5161. None => {
  5162. let z = self.s.m.i32(0);
  5163. Val::Bit(self.s.m.cmp(c, pred::NE, r, z))
  5164. }
  5165. };
  5166. self.vals.insert(scc, val);
  5167. }
  5168. Ok(())
  5169. }
  5170. /// `a + b (+ cin)` or `a - b (- cin)` with the carry (borrow) out, as the
  5171. /// scalar and vector add-with-carry instructions set it.
  5172. fn add_sub_carry(&mut self, c: usize, add: bool, a: V, b: V, cin: Option<V>) -> (V, V) {
  5173. let op = if add { Bin::Add } else { Bin::Sub };
  5174. let mut r = self.s.m.bin(c, op, a, b);
  5175. // Without a carry in: a + b wraps below a; a - b borrows when a < b.
  5176. let mut carry = if add {
  5177. self.s.m.cmp(c, pred::IULT, r, a)
  5178. } else {
  5179. self.s.m.cmp(c, pred::IULT, a, b)
  5180. };
  5181. if let Some(cin) = cin {
  5182. let one = self.s.m.cast(c, Cast::ZExt, cin, self.s.t.i32);
  5183. let t = r;
  5184. r = self.s.m.bin(c, op, t, one);
  5185. // The carry in carries on when the partial result is all ones
  5186. // (add) or zero (sub).
  5187. let edge = self.s.m.i32(if add { u32::MAX } else { 0 });
  5188. let at_edge = self.s.m.cmp(c, pred::EQ, t, edge);
  5189. let more = self.s.m.bin(c, Bin::And, cin, at_edge);
  5190. carry = self.s.m.bin(c, Bin::Or, carry, more);
  5191. }
  5192. (r, carry)
  5193. }
  5194. fn scc_in(&mut self, inst: &Inst) -> Result<V, Why> {
  5195. let v = inst.read(Reg::Scc).ok_or("an unread SCC")?;
  5196. match self.get(v)? {
  5197. Val::Bit(x) => Ok(x),
  5198. _ => Err("SCC without a value"),
  5199. }
  5200. }
  5201. fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  5202. let Fields::Smem {
  5203. data,
  5204. offset,
  5205. soffset,
  5206. ..
  5207. } = &inst.fields
  5208. else {
  5209. unreachable!()
  5210. };
  5211. let name = inst.name();
  5212. if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) {
  5213. return self.code_smem(inst, a);
  5214. }
  5215. if self.scalar.get(&site).is_some_and(|a| a.param == MEMORY) {
  5216. return self.memory_smem(inst);
  5217. }
  5218. let Some(rest) = name.strip_prefix("s_buffer_load_dword") else {
  5219. return self.descriptor_data(inst, site);
  5220. };
  5221. let count = match rest {
  5222. "" => 1,
  5223. "x2" => 2,
  5224. "x4" => 4,
  5225. "x8" => 8,
  5226. "x16" => 16,
  5227. _ => return Err("a scalar buffer load"),
  5228. };
  5229. let Some(Operand::Scalar { code, .. }) = *data else {
  5230. return Err("a scalar buffer load");
  5231. };
  5232. let src = self
  5233. .descriptors
  5234. .get(&(site, false))
  5235. .copied()
  5236. .ok_or("an untracked descriptor")?;
  5237. let kind = self.used_kind(src);
  5238. let c = self.cur;
  5239. let (base, extra) = self.built_offset(src)?;
  5240. let offset = &((*offset as u32).wrapping_add(base) as i32);
  5241. let mut addr = self.s.m.i32(*offset as u32);
  5242. if let Some(x) = extra {
  5243. addr = self.s.m.bin(c, Bin::Add, addr, x);
  5244. }
  5245. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  5246. let so = self.operand(inst, soffset)?;
  5247. addr = self.s.m.bin(c, Bin::Add, addr, so);
  5248. }
  5249. if matches!(src, Source::Built { address, .. } if address.param == CODE) {
  5250. // A descriptor built around a table in the code.
  5251. for k in 0..count {
  5252. let off = self.s.m.i32(4 * k);
  5253. let a = self.s.m.bin(c, Bin::Add, addr, off);
  5254. let x = self.code_dword(a)?;
  5255. self.write(inst, Reg::S(code + k as u8), x, None);
  5256. }
  5257. return Ok(());
  5258. }
  5259. // A buffer the program picks from the view heap by an index it
  5260. // computes (`ResourceHeap`) has no used-resource entry, and the
  5261. // heap holds a buffer view there, not a constant buffer: read as
  5262. // raw bytes, as a table's SRV is below. Read as a constant buffer
  5263. // (the host's validation: "Descriptor Type in Heap: SRV, Register
  5264. // Type: CBV", heap index 17) the loads gave nothing: Grand Theft
  5265. // Auto VI's meshlet culling (BatchCullMeshlets,
  5266. // BatchCullPreSkinnedMeshlets, BatchCullBatchCSMeshlets) reads its
  5267. // batch records, mesh headers and instance transforms this way, so
  5268. // it passed no meshlet and every indirect mesh draw ran empty.
  5269. // The host's table of strides by heap slot tells a buffer view
  5270. // (not 0) from anything else, which is still read as a constant
  5271. // buffer; only the load that fits the slot runs.
  5272. let picked = match kind {
  5273. None => self.slot_stride(src)?,
  5274. Some(_) => None,
  5275. };
  5276. if let Some(stride) = picked {
  5277. let zero = self.s.m.i32(0);
  5278. let is_buffer = self.s.m.cmp(self.cur, pred::NE, stride, zero);
  5279. let at = self.begin_guarded(Some(is_buffer));
  5280. let h = self.handle(site, src, false, (11, 0))?;
  5281. let mut raw = Vec::new();
  5282. for k in 0..count {
  5283. let b = self.cur;
  5284. let off = self.s.m.i32(4 * k);
  5285. let a = self.s.m.bin(b, Bin::Add, addr, off);
  5286. let mask = self.s.m.i8(1);
  5287. let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  5288. let r = self.s.op(
  5289. b,
  5290. "rawBufferLoad.f32",
  5291. Attr::ReadOnly,
  5292. self.s.t.res_ret,
  5293. 139,
  5294. &[h, a, u, mask, al],
  5295. );
  5296. let x = self.s.m.extract(b, r, 0);
  5297. let x = self.as_int(x);
  5298. raw.push((x, zero));
  5299. }
  5300. let raw = self.end_guarded(at, &raw);
  5301. let other = self.s.m.cmp(self.cur, pred::EQ, stride, zero);
  5302. let at = self.begin_guarded(Some(other));
  5303. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  5304. let mut both = Vec::new();
  5305. for (k, &r) in raw.iter().enumerate() {
  5306. let b = self.cur;
  5307. let off = self.s.m.i32(4 * k as u32);
  5308. let a = self.s.m.bin(b, Bin::Add, addr, off);
  5309. let x = self.cbuffer_dword(h, a);
  5310. both.push((x, r));
  5311. }
  5312. let both = self.end_guarded(at, &both);
  5313. for (k, x) in both.into_iter().enumerate() {
  5314. self.write(inst, Reg::S(code + k as u8), x, None);
  5315. }
  5316. return Ok(());
  5317. }
  5318. if matches!(kind, Some(u) if u.kind == ResourceType::Srv) {
  5319. let h = self.handle(site, src, false, (11, 0))?;
  5320. for k in 0..count {
  5321. let off = self.s.m.i32(4 * k);
  5322. let a = self.s.m.bin(c, Bin::Add, addr, off);
  5323. let mask = self.s.m.i8(1);
  5324. let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  5325. let r = self.s.op(
  5326. c,
  5327. "rawBufferLoad.f32",
  5328. Attr::ReadOnly,
  5329. self.s.t.res_ret,
  5330. 139,
  5331. &[h, a, u, mask, al],
  5332. );
  5333. let x = self.s.m.extract(c, r, 0);
  5334. let x = self.as_int(x);
  5335. self.write(inst, Reg::S(code + k as u8), x, None);
  5336. }
  5337. return Ok(());
  5338. }
  5339. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  5340. let constant = match addr {
  5341. V::Const(_)
  5342. if matches!(soffset, Operand::Scalar { code: NULL, .. }) && extra.is_none() =>
  5343. {
  5344. Some(*offset as u32)
  5345. }
  5346. _ => None,
  5347. };
  5348. let mut rows: HashMap<u32, V> = HashMap::new();
  5349. for k in 0..count {
  5350. let x = match constant {
  5351. Some(base) => {
  5352. let byte = base + 4 * k;
  5353. let row = match rows.get(&(byte >> 4)) {
  5354. Some(&r) => r,
  5355. None => {
  5356. let ri = self.s.m.i32(byte >> 4);
  5357. let r = self.s.op(
  5358. c,
  5359. "cbufferLoadLegacy.i32",
  5360. Attr::ReadOnly,
  5361. self.s.t.cbuf_ret,
  5362. 59,
  5363. &[h, ri],
  5364. );
  5365. rows.insert(byte >> 4, r);
  5366. r
  5367. }
  5368. };
  5369. self.s.m.extract(c, row, (byte >> 2) & 3)
  5370. }
  5371. None => {
  5372. let off = self.s.m.i32(4 * k);
  5373. let a = self.s.m.bin(c, Bin::Add, addr, off);
  5374. self.cbuffer_dword(h, a)
  5375. }
  5376. };
  5377. self.write(inst, Reg::S(code + k as u8), x, None);
  5378. }
  5379. Ok(())
  5380. }
  5381. /// A descriptor load (`s_load_dword*` from a table or heap) whose dwords
  5382. /// the code also reads as numbers: the console compiler computes sizes
  5383. /// from descriptor bits (an image's width, height, depth, levels; a
  5384. /// buffer's record count) instead of querying them. Those fields are
  5385. /// rebuilt from the host view's dimensions in the GFX10 layout (image
  5386. /// dword 1 bits 30-31 and dword 2 bits 0-13 width - 1, dword 2 bits
  5387. /// 14-29 height - 1, dword 3 identity swizzle, last level at 16, type at
  5388. /// 28, dword 4 depth or layers - 1; buffer dword 2 the record count).
  5389. // shortcut: the base level reads 0 (the host view starts at its own
  5390. // level 0, so sizes the code shifts by it come out right) and the other
  5391. // dwords (addresses, formats, tiling) have no host value: reading them
  5392. // stops the program.
  5393. fn descriptor_data(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  5394. const OTHER: Why = "a descriptor's address or format read as data";
  5395. let Fields::Smem {
  5396. data: Some(Operand::Scalar { code, .. }),
  5397. ..
  5398. } = inst.fields
  5399. else {
  5400. return Err("a scalar memory read as data");
  5401. };
  5402. let count = match inst.name().strip_prefix("s_load_dword") {
  5403. Some("") => 1u32,
  5404. Some("x2") => 2,
  5405. Some("x4") => 4,
  5406. Some("x8") => 8,
  5407. Some("x16") => 16,
  5408. _ => return Err("a scalar memory read as data"),
  5409. };
  5410. // How the program uses the descriptor tells the view's kind: an image or buffer
  5411. // instruction before a scalar buffer load, which reads any buffer.
  5412. let x = self.x;
  5413. let uses = |of: Site| {
  5414. x.res
  5415. .descriptors
  5416. .iter()
  5417. .filter(|d| d.role == Role::Resource)
  5418. .filter_map(move |d| {
  5419. d.source.leaves().into_iter().find_map(|l| match *l {
  5420. Source::Loaded { load, first } if load == of => Some((d.site, first)),
  5421. _ => None,
  5422. })
  5423. })
  5424. };
  5425. let by_scalar_load = |u: &(Site, u8)| {
  5426. matches!(x.p.blocks[u.0.0].insts[u.0.1].fields, Fields::Smem { .. })
  5427. };
  5428. let use_of = |of: Site| uses(of).find(|u| !by_scalar_load(u)).or_else(|| uses(of).next());
  5429. // The console compiler loads a descriptor again wherever it needs it, and for a
  5430. // size it reads the dwords of a load that nothing uses as a descriptor (a texture
  5431. // picked from the heap by an index held per lane: one load for its width, one for
  5432. // its base level, one for each read of the image). Another load of as many dwords
  5433. // from the same address reads the same descriptor, so what uses that one tells
  5434. // this one's kind. The handle is still made from this load's own operands, which
  5435. // hold here.
  5436. let address = self.scalar.get(&site).copied();
  5437. let twin = || {
  5438. let a = address?;
  5439. let same = |s: Site| x.p.blocks[s.0].insts[s.1].name() == inst.name();
  5440. x.res
  5441. .scalar
  5442. .iter()
  5443. .filter(|(s, b)| *s != site && *b == a && same(*s))
  5444. .find_map(|(s, _)| use_of(*s))
  5445. };
  5446. let use_at = use_of(site).or_else(twin);
  5447. let Some((at, first)) = use_at else {
  5448. // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only
  5449. // copies its dwords and compares them, lane against first lane, and every load
  5450. // that reaches those lanes reads one address. Each dword stands in as its place
  5451. // in the table, so the lanes compare equal as they do on the console.
  5452. if self.x.res.lane_copied.contains(&site)
  5453. && let Some(a) = self.scalar.get(&site).copied()
  5454. {
  5455. for k in 0..count {
  5456. let x = self.s.m.i32(a.offset / 4 + k);
  5457. self.write(inst, Reg::S(code + k as u8), x, None);
  5458. }
  5459. return Ok(());
  5460. }
  5461. // A sampler's descriptor: no program reads its dwords as numbers, so where one
  5462. // meets numbers at a join the register is dead on that path (`dead`), as a
  5463. // descriptor's address or format is.
  5464. let sampler = x.res.descriptors.iter().any(|d| {
  5465. d.role == Role::Sampler
  5466. && d.source.leaves().into_iter().any(
  5467. |l| matches!(*l, Source::Loaded { load, .. } if load == site),
  5468. )
  5469. });
  5470. if sampler {
  5471. self.stale.extend(inst.writes.iter().map(|w| w.1));
  5472. return Err("a sampler's descriptor read as data");
  5473. }
  5474. // A buffer view the code only takes the address of, to walk
  5475. // the memory behind it (a ray-tracing structure): the address
  5476. // from the host, the other dwords have no value.
  5477. if count <= 4
  5478. && let Some((lo, hi)) = self.view_address(site)
  5479. {
  5480. for k in 0..count {
  5481. let reg = Reg::S(code + k as u8);
  5482. match k {
  5483. 0 => self.write(inst, reg, lo, None),
  5484. 1 => self.write(inst, reg, hi, None),
  5485. _ => {
  5486. if let Some(v) = inst.write(reg) {
  5487. self.vals.insert(v, Val::Missing(OTHER));
  5488. self.stale.insert(v);
  5489. }
  5490. }
  5491. }
  5492. }
  5493. return Ok(());
  5494. }
  5495. return Err("a descriptor read only as data");
  5496. };
  5497. let src = Source::Loaded { load: site, first };
  5498. let used = self.used_kind(&src);
  5499. let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1];
  5500. let un = ui.name();
  5501. let uav = un.contains("store")
  5502. || un.contains("atomic")
  5503. || used.is_some_and(|u| u.kind == ResourceType::Uav);
  5504. let u = if uav { 0x1000 } else { 0 };
  5505. let (props, image) = match &ui.fields {
  5506. // A ray-tracing structure in a buffer of the host: read raw.
  5507. Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None),
  5508. Fields::Image { dim, .. } => {
  5509. let kind = match dim {
  5510. 0 => 1,
  5511. 1 => 2,
  5512. 2 => 4,
  5513. 4 => 6,
  5514. 5 => 7,
  5515. _ => return Err("an image dimension (cube or MSAA)"),
  5516. };
  5517. ((kind | u, 0x409), Some(kind))
  5518. }
  5519. Fields::Buffer { idxen, format, .. } => {
  5520. let stride = used.map_or(0, |u| u.stride);
  5521. let props = if un.starts_with("buffer_load_format")
  5522. || un.starts_with("buffer_store_format")
  5523. {
  5524. (10 | u, 0x409)
  5525. } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) {
  5526. (12 | u, stride)
  5527. } else {
  5528. (11 | u, 0)
  5529. };
  5530. if used.is_some_and(|u| u.kind == ResourceType::Cbv) {
  5531. self.stale.extend(inst.writes.iter().map(|w| w.1));
  5532. return Err("a constant buffer's descriptor read as data");
  5533. }
  5534. (props, None)
  5535. }
  5536. // Read by scalar buffer loads alone: the raw view `smem` reads it through.
  5537. Fields::Smem { .. } if used.is_some_and(|u| u.kind == ResourceType::Srv) => {
  5538. ((11, 0), None)
  5539. }
  5540. // A constant buffer: nothing of its descriptor is a number.
  5541. Fields::Smem { .. } => {
  5542. self.stale.extend(inst.writes.iter().map(|w| w.1));
  5543. return Err("a constant buffer's descriptor read as data");
  5544. }
  5545. _ => return Err("a scalar memory read as data"),
  5546. };
  5547. let h = self.handle(site, &src, false, props)?;
  5548. let c = self.cur;
  5549. let i32t = self.s.t.i32;
  5550. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  5551. let mip = if image.is_some() && !uav {
  5552. self.s.m.i32(0)
  5553. } else {
  5554. self.s.m.undef(i32t)
  5555. };
  5556. let d = self
  5557. .s
  5558. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  5559. let field = |l: &mut Self, k: u32| l.s.m.extract(c, d, k);
  5560. let words: Vec<(u32, V)> = match image {
  5561. Some(kind) => {
  5562. let one = self.s.m.i32(1);
  5563. let w = field(self, 0);
  5564. let (height, depth) = match kind {
  5565. 1 => (one, one),
  5566. 2 => (field(self, 1), one),
  5567. 6 => (one, field(self, 1)),
  5568. _ => (field(self, 1), field(self, 2)),
  5569. };
  5570. let levels = if uav { one } else { field(self, 3) };
  5571. let less = |l: &mut Self, x: V| l.s.m.bin(c, Bin::Sub, x, one);
  5572. let (w, height, depth, levels) = (
  5573. less(self, w),
  5574. less(self, height),
  5575. less(self, depth),
  5576. less(self, levels),
  5577. );
  5578. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  5579. let (k30, k2, k14, k16, mask) = (
  5580. k(self, 30),
  5581. k(self, 2),
  5582. k(self, 14),
  5583. k(self, 16),
  5584. k(self, 0x3FFF),
  5585. );
  5586. let d1 = self.s.m.bin(c, Bin::Shl, w, k30);
  5587. let hi = self.s.m.bin(c, Bin::LShr, w, k2);
  5588. let hi = self.s.m.bin(c, Bin::And, hi, mask);
  5589. let ht = self.s.m.bin(c, Bin::Shl, height, k14);
  5590. let d2 = self.s.m.bin(c, Bin::Or, hi, ht);
  5591. let ty = [0, 8, 9, 0, 10, 0, 12, 13][kind as usize];
  5592. let base = k(self, 0xFAC | ty << 28);
  5593. let last = self.s.m.bin(c, Bin::Shl, levels, k16);
  5594. let d3 = self.s.m.bin(c, Bin::Or, base, last);
  5595. vec![(1, d1), (2, d2), (3, d3), (4, depth)]
  5596. }
  5597. None => {
  5598. // A raw view counts bytes; the descriptor's record count is in elements.
  5599. let n = field(self, 0);
  5600. let stride = used.map_or(0, |u| u.stride);
  5601. let n = if props.0 & 0xFF == 11 && stride > 1 {
  5602. let k = self.s.m.i32(stride);
  5603. self.s.m.bin(c, Bin::UDiv, n, k)
  5604. } else {
  5605. n
  5606. };
  5607. let mut words = vec![(2, n)];
  5608. // Its address too, where the code computes with it and the
  5609. // host can tell it.
  5610. let computed = (0..2u8).any(|k| {
  5611. inst.write(Reg::S(code + first + k))
  5612. .is_some_and(|v| self.computed_with(v, 6))
  5613. });
  5614. if first == 0
  5615. && computed
  5616. && let Some((lo, hi)) = self.view_address(site)
  5617. {
  5618. words.extend([(0, lo), (1, hi)]);
  5619. }
  5620. words
  5621. }
  5622. };
  5623. for k in 0..count {
  5624. let rel = k.wrapping_sub(u32::from(first));
  5625. match words.iter().find(|w| w.0 == rel) {
  5626. Some(&(_, x)) => self.write(inst, Reg::S(code + k as u8), x, None),
  5627. None => {
  5628. if let Some(v) = inst.write(Reg::S(code + k as u8)) {
  5629. self.vals.insert(v, Val::Missing(OTHER));
  5630. self.stale.insert(v);
  5631. }
  5632. }
  5633. }
  5634. }
  5635. Ok(())
  5636. }
  5637. /// `s_load_dword*` from the program's constant table.
  5638. fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> {
  5639. let Fields::Smem {
  5640. data: Some(Operand::Scalar { code, .. }),
  5641. ..
  5642. } = inst.fields
  5643. else {
  5644. return Err("a scalar load");
  5645. };
  5646. let count = match inst.name().strip_prefix("s_load_dword") {
  5647. Some("") => 1u32,
  5648. Some("x2") => 2,
  5649. Some("x4") => 4,
  5650. Some("x8") => 8,
  5651. Some("x16") => 16,
  5652. _ => return Err("a scalar load from the code"),
  5653. };
  5654. let c = self.cur;
  5655. let mut addr = self.s.m.i32(a.offset);
  5656. if let Some(value) = a.dynamic {
  5657. let mut d = self.i32_of(value)?;
  5658. // A term held per lane reached the address through
  5659. // `v_readfirstlane_b32`: the first lane's.
  5660. let per_lane = self.def_block.get(&value).is_some_and(|&b| {
  5661. let writes = |i: &Inst| i.writes.iter().any(|w| w.1 == value && matches!(w.0, Reg::V(_)));
  5662. self.x.p.blocks[b].insts.iter().any(writes)
  5663. });
  5664. if per_lane {
  5665. self.s.flags |= flags::WAVE_OPS;
  5666. let i32t = self.s.t.i32;
  5667. d = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[d]);
  5668. }
  5669. addr = self.s.m.bin(c, Bin::Add, addr, d);
  5670. }
  5671. for k in 0..count {
  5672. let off = self.s.m.i32(4 * k);
  5673. let at = self.s.m.bin(c, Bin::Add, addr, off);
  5674. let x = self.code_dword(at)?;
  5675. self.write(inst, Reg::S(code + k as u8), x, None);
  5676. }
  5677. Ok(())
  5678. }
  5679. /// The dword at a computed byte address of a constant buffer.
  5680. fn cbuffer_dword(&mut self, h: V, a: V) -> V {
  5681. let c = self.cur;
  5682. let four = self.s.m.i32(4);
  5683. let ri = self.s.m.bin(c, Bin::LShr, a, four);
  5684. let r = self.s.op(
  5685. c,
  5686. "cbufferLoadLegacy.i32",
  5687. Attr::ReadOnly,
  5688. self.s.t.cbuf_ret,
  5689. 59,
  5690. &[h, ri],
  5691. );
  5692. let two = self.s.m.i32(2);
  5693. let three = self.s.m.i32(3);
  5694. let comp = self.s.m.bin(c, Bin::LShr, a, two);
  5695. let comp = self.s.m.bin(c, Bin::And, comp, three);
  5696. let mut x = self.s.m.extract(c, r, 0);
  5697. for j in 1..4 {
  5698. let e = self.s.m.extract(c, r, j);
  5699. let jc = self.s.m.i32(j);
  5700. let is = self.s.m.cmp(c, pred::EQ, comp, jc);
  5701. x = self.s.m.select(c, is, e, x);
  5702. }
  5703. x
  5704. }
  5705. /// `channels` channels of the element at byte `off` of raw buffer `h`,
  5706. /// converted from the GFX10 buffer format `format` as the hardware's
  5707. /// typed loads do (channels past the format's read 0, 0, 0, 1).
  5708. // shortcut: the descriptor's channel swizzle is taken as the identity
  5709. // (it is for raw views and the descriptors code builds), elements of 4
  5710. // bytes or more as dword-aligned. Norm formats divide, which the AMD
  5711. // driver does 1 ULP off the hardware's correctly rounded conversion for
  5712. // some values; correct it with an integer check if a title compares
  5713. // converted values exactly.
  5714. fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result<Vec<V>, Why> {
  5715. let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?;
  5716. let c = self.cur;
  5717. let total: u32 = bits.iter().sum();
  5718. let (u, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  5719. let load = |l: &mut Self, at: V, n: u32| -> Vec<V> {
  5720. let mask = l.s.m.i8((1u8 << n) - 1);
  5721. let r = l.s.op(
  5722. c,
  5723. "rawBufferLoad.f32",
  5724. Attr::ReadOnly,
  5725. l.s.t.res_ret,
  5726. 139,
  5727. &[h, at, u, mask, align],
  5728. );
  5729. (0..n)
  5730. .map(|k| {
  5731. let x = l.s.m.extract(c, r, k);
  5732. l.as_int(x)
  5733. })
  5734. .collect()
  5735. };
  5736. let words = if total < 32 {
  5737. // A byte or half inside the dword that holds it.
  5738. let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3));
  5739. let at = self.s.m.bin(c, Bin::And, off, not3);
  5740. let w = load(self, at, 1)[0];
  5741. let byte = self.s.m.bin(c, Bin::And, off, three);
  5742. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  5743. vec![self.s.m.bin(c, Bin::LShr, w, sh)]
  5744. } else {
  5745. load(self, off, total / 32)
  5746. };
  5747. let float = |l: &mut Self, f: V| l.as_int(f);
  5748. let mut out = Vec::new();
  5749. let mut at = 0;
  5750. for &w in bits {
  5751. let word = words[(at / 32) as usize];
  5752. let field = if w == 32 {
  5753. word
  5754. } else {
  5755. let sh = self.s.m.i32(at % 32);
  5756. let t = self.s.m.bin(c, Bin::LShr, word, sh);
  5757. let m = self.s.m.i32((1 << w) - 1);
  5758. self.s.m.bin(c, Bin::And, t, m)
  5759. };
  5760. at += w;
  5761. // Sign-extended from the field's top bit.
  5762. let signed = |l: &mut Self| {
  5763. if w == 32 {
  5764. return field;
  5765. }
  5766. let k = l.s.m.i32(32 - w);
  5767. let t = l.s.m.bin(c, Bin::Shl, field, k);
  5768. l.s.m.bin(c, Bin::AShr, t, k)
  5769. };
  5770. let f32t = self.s.t.f32;
  5771. let x = match numeric {
  5772. Numeric::Unorm => {
  5773. let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
  5774. let max = self.s.m.f32((((1u64 << w) - 1) as f32).to_bits());
  5775. let q = self.s.m.bin(c, Bin::SDiv, f, max);
  5776. float(self, q)
  5777. }
  5778. Numeric::Snorm => {
  5779. let s = signed(self);
  5780. let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
  5781. let max = self.s.m.f32((((1u64 << (w - 1)) - 1) as f32).to_bits());
  5782. let q = self.s.m.bin(c, Bin::SDiv, f, max);
  5783. let lo = self.s.m.f32((-1.0f32).to_bits());
  5784. let q = self.binary(35, q, lo);
  5785. float(self, q)
  5786. }
  5787. Numeric::Uscaled => {
  5788. let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
  5789. float(self, f)
  5790. }
  5791. Numeric::Sscaled => {
  5792. let s = signed(self);
  5793. let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
  5794. float(self, f)
  5795. }
  5796. Numeric::Uint => field,
  5797. Numeric::Sint => signed(self),
  5798. Numeric::Float if w == 32 => field,
  5799. Numeric::Float => {
  5800. let h = match half_shift(w) {
  5801. 0 => field,
  5802. k => {
  5803. let sh = self.s.m.i32(k);
  5804. self.s.m.bin(c, Bin::Shl, field, sh)
  5805. }
  5806. };
  5807. let f = self
  5808. .s
  5809. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  5810. float(self, f)
  5811. }
  5812. };
  5813. out.push(x);
  5814. }
  5815. let one = match numeric {
  5816. Numeric::Uint | Numeric::Sint => 1,
  5817. _ => 1.0f32.to_bits(),
  5818. };
  5819. for k in out.len() as u32..channels {
  5820. out.push(self.s.m.i32(if k == 3 { one } else { 0 }));
  5821. }
  5822. out.truncate(channels as usize);
  5823. Ok(out)
  5824. }
  5825. /// The byte offset a buffer descriptor built around a root descriptor adds
  5826. /// (constant and computed parts); none for other descriptors.
  5827. fn built_offset(&mut self, src: &Source) -> Result<(u32, Option<V>), Why> {
  5828. match src {
  5829. Source::Built { address, .. } => {
  5830. let mut x = match address.dynamic {
  5831. Some(v) => Some(self.i32_of(v)?),
  5832. None => None,
  5833. };
  5834. if let Some(bias) = self.root_bias(address.param) {
  5835. x = Some(match x {
  5836. Some(d) => self.s.m.bin(self.cur, Bin::Add, d, bias),
  5837. None => bias,
  5838. });
  5839. }
  5840. Ok((address.offset, x))
  5841. }
  5842. _ => Ok((0, None)),
  5843. }
  5844. }
  5845. /// For a root view the host binds as a raw view that may begin before
  5846. /// the title's address (`shader.rs` `USER_VIEW_BIAS`): the bytes to add
  5847. /// to offsets through it. Every root UAV, and the root SRVs of programs
  5848. /// with a spilled user-data table (the others keep the views they
  5849. /// have).
  5850. fn root_bias(&mut self, param: usize) -> Option<V> {
  5851. use super::shader::USER_VIEW_BIAS;
  5852. let rp = *self.x.native.layout.get(param)?;
  5853. if rp.root != RootType::Descriptor {
  5854. return None;
  5855. }
  5856. let kind = self
  5857. .x
  5858. .native
  5859. .used
  5860. .iter()
  5861. .find(|u| u.user_data == rp.user_data)
  5862. .map(|u| u.kind);
  5863. let biased = match kind {
  5864. Some(ResourceType::Uav) => true,
  5865. Some(ResourceType::Srv) => crate::spill::is_spilled(self.x.native),
  5866. _ => false,
  5867. };
  5868. biased.then(|| self.host_word(RootType::Other(USER_VIEW_BIAS), rp.slot, 0))
  5869. }
  5870. /// The used-resource entry a descriptor loaded from a table falls in.
  5871. fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> {
  5872. if let Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } =
  5873. src
  5874. {
  5875. return self.used_kind(args.first()?);
  5876. }
  5877. if let Source::LanePhi { args, .. } = src {
  5878. return args.iter().flatten().find_map(|a| self.used_kind(a));
  5879. }
  5880. if let Source::Built { address, .. } = src {
  5881. let rp = self.x.native.layout.get(address.param)?;
  5882. return self
  5883. .x
  5884. .native
  5885. .used
  5886. .iter()
  5887. .find(|u| u.root == RootType::Descriptor && u.user_data == rp.user_data);
  5888. }
  5889. let (Source::Loaded { load, first } | Source::Fetched { load, first }) = src else {
  5890. return None;
  5891. };
  5892. let a = self.scalar.get(load)?;
  5893. let rp = self.x.native.layout.get(a.param)?;
  5894. if rp.root != RootType::Table {
  5895. return None;
  5896. }
  5897. let dword = (a.offset / 4) + u32::from(*first);
  5898. self.x
  5899. .native
  5900. .used
  5901. .iter()
  5902. .filter(|u| {
  5903. u.root == RootType::Table
  5904. && u.user_data == rp.user_data
  5905. && u.table_offset_dwords <= dword
  5906. })
  5907. .max_by_key(|u| u.table_offset_dwords)
  5908. }
  5909. /// A handle for the descriptor `src` read at `site`.
  5910. fn handle(
  5911. &mut self,
  5912. site: Site,
  5913. src: &Source,
  5914. sampler: bool,
  5915. props: (u32, u32),
  5916. ) -> Result<V, Why> {
  5917. match src {
  5918. Source::Loaded { load, first } => {
  5919. let key = (self.cur, *load, *first, sampler, props);
  5920. if let Some(&h) = self.handles.get(&key) {
  5921. return Ok(h);
  5922. }
  5923. let index = self.heap_index(*load, *first, sampler)?;
  5924. // A waterfall loop's load at the first lane's offset reads
  5925. // each lane's own entry (see `resource::Waterfall`).
  5926. let per_lane = self.x.res.waterfall.loads.contains(load);
  5927. let h = self
  5928. .s
  5929. .heap_handle(self.cur, index, sampler, per_lane, props);
  5930. self.handles.insert(key, h);
  5931. Ok(h)
  5932. }
  5933. Source::Constant(words) if sampler => {
  5934. let words: [u32; 4] = words
  5935. .get(..4)
  5936. .and_then(|w| w.try_into().ok())
  5937. .ok_or("a sampler constant")?;
  5938. let n = match self.samplers.iter().position(|w| *w == words) {
  5939. Some(n) => n,
  5940. None => {
  5941. self.samplers.push(words);
  5942. self.samplers.len() - 1
  5943. }
  5944. };
  5945. if props.0 & 0x8000 != 0 {
  5946. // shortcut: one sampler used with and without comparison
  5947. // would need two static samplers; it becomes a comparison one.
  5948. self.s.cmp_samplers |= 1 << n;
  5949. }
  5950. Ok(self.s.sampler_handle(self.cur, n as u32))
  5951. }
  5952. Source::Constant(_) => Err("a constant resource descriptor"),
  5953. Source::Built { address, .. } => {
  5954. let rp = *self
  5955. .x
  5956. .native
  5957. .layout
  5958. .get(address.param)
  5959. .ok_or("a descriptor built around a table in the code")?;
  5960. let kind = self
  5961. .x
  5962. .native
  5963. .used
  5964. .iter()
  5965. .find(|u| u.user_data == rp.user_data)
  5966. .map(|u| u.kind);
  5967. match (rp.root, kind, props.0) {
  5968. (RootType::Descriptor, Some(ResourceType::Cbv) | None, 13) => {
  5969. Ok(self.s.root_cbv_handle(rp.slot))
  5970. }
  5971. (RootType::Descriptor, Some(ResourceType::Srv), 11) => {
  5972. Ok(self.s.root_srv_handle(rp.slot))
  5973. }
  5974. // A root UAV: a raw buffer whether the access reads
  5975. // (11) or writes (11 with the UAV bit). Indexed
  5976. // accesses reach here as raw ones at index times the
  5977. // entry's stride (`buffer`).
  5978. (RootType::Descriptor, Some(ResourceType::Uav), 11 | 0x100b) => {
  5979. Ok(self.s.root_uav_handle(rp.slot))
  5980. }
  5981. (RootType::Descriptor, Some(ResourceType::Srv), 0x100b) => {
  5982. Err("a write through a root SRV")
  5983. }
  5984. _ => Err("a typed root view"),
  5985. }
  5986. }
  5987. Source::Phi { block, args } => {
  5988. let _ = site;
  5989. let phi = self.descriptor_phi(*block, args, sampler, 8)?;
  5990. Ok(self.s.heap_handle(self.cur, phi, sampler, false, props))
  5991. }
  5992. Source::Select { scc, args } => {
  5993. // The heap index of each choice, picked by SCC (uniform).
  5994. let [
  5995. Source::Loaded { load: a, first: fa },
  5996. Source::Loaded { load: b, first: fb },
  5997. ] = args[..]
  5998. else {
  5999. return Err("a descriptor chosen by a condition");
  6000. };
  6001. let cond = match self.get(*scc)? {
  6002. Val::Bit(x) => x,
  6003. _ => return Err("SCC without a value"),
  6004. };
  6005. let set = self.heap_index(a, fa, sampler)?;
  6006. let clear = self.heap_index(b, fb, sampler)?;
  6007. let index = self.s.m.select(self.cur, cond, set, clear);
  6008. Ok(self.s.heap_handle(self.cur, index, sampler, false, props))
  6009. }
  6010. Source::Fetched { .. } | Source::Lanes { .. } | Source::LanePhi { .. } => {
  6011. // A descriptor each lane has its own of (a waterfall loop
  6012. // reads it from the first active lane): each lane's heap
  6013. // index, non-uniform.
  6014. let index = self.lane_heap_index(src, sampler)?;
  6015. Ok(self.s.heap_handle(self.cur, index, sampler, true, props))
  6016. }
  6017. }
  6018. }
  6019. /// The heap index a descriptor phi picks. Each predecessor computes its
  6020. /// heap index at its end and the join picks one with a phi; a
  6021. /// predecessor whose descriptor is itself chosen by control flow (a
  6022. /// phi of an earlier join, which dominates it) gives that join's phi,
  6023. /// at most `depth` joins deep.
  6024. fn descriptor_phi(
  6025. &mut self,
  6026. block: usize,
  6027. args: &[Source],
  6028. sampler: bool,
  6029. depth: u32,
  6030. ) -> Result<V, Why> {
  6031. const WHY: Why = "a descriptor chosen by control flow";
  6032. let p = self.x.p;
  6033. let mut incoming = Vec::new();
  6034. for (&q, arg) in p.blocks[block].preds.iter().zip(args) {
  6035. if self.block[q].is_none() {
  6036. continue;
  6037. }
  6038. let tail = self.tail[q].ok_or(WHY)?;
  6039. let at = self.edges.get(&(q, block)).copied().unwrap_or(tail);
  6040. let index = match arg {
  6041. Source::Loaded { load, first } => {
  6042. let here = std::mem::replace(&mut self.cur, at);
  6043. let index = self.heap_index(*load, *first, sampler);
  6044. self.cur = here;
  6045. index?
  6046. }
  6047. Source::Phi { block: inner, args: inner_args } if depth > 0 => {
  6048. self.descriptor_phi(*inner, inner_args, sampler, depth - 1)?
  6049. }
  6050. _ => return Err(WHY),
  6051. };
  6052. incoming.push((index, at));
  6053. }
  6054. let join = self.block[block].ok_or(WHY)?;
  6055. let phi = self.s.m.phi(join, self.s.t.i32);
  6056. self.s.m.set_phi(phi, incoming);
  6057. Ok(phi)
  6058. }
  6059. /// The bytes per element of the buffer view `src` names, if the program
  6060. /// picks it from the view heap at an index it computes (root type
  6061. /// `ResourceHeap`): read from the host's table by heap slot in the
  6062. /// current block.
  6063. fn slot_stride(&mut self, src: &Source) -> Result<Option<V>, Why> {
  6064. let Source::Loaded { load, first } = src else {
  6065. return Ok(None);
  6066. };
  6067. let heap = self
  6068. .scalar
  6069. .get(load)
  6070. .and_then(|a| self.x.native.layout.get(a.param))
  6071. .is_some_and(|p| p.root == RootType::ResourceHeap);
  6072. if !heap {
  6073. return Ok(None);
  6074. }
  6075. let key = (self.cur, *load, *first);
  6076. if let Some(&v) = self.strides.get(&key) {
  6077. return Ok(Some(v));
  6078. }
  6079. let c = self.cur;
  6080. let slot = self.heap_index(*load, *first, false)?;
  6081. // Inside the table whatever the index (lanes that do not run
  6082. // compute one too): a root view has no bounds of its own.
  6083. let last = self.s.m.i32(super::shader::SLOT_STRIDES_COUNT - 1);
  6084. let i32t = self.s.t.i32;
  6085. let slot = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[slot, last]);
  6086. let two = self.s.m.i32(2);
  6087. let byte = self.s.m.bin(c, Bin::Shl, slot, two);
  6088. let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES);
  6089. let iu = self.s.m.undef(self.s.t.i32);
  6090. let mask = self.s.m.i8(1);
  6091. let align = self.s.m.i32(4);
  6092. let r = self.s.op(
  6093. c,
  6094. "rawBufferLoad.f32",
  6095. Attr::ReadOnly,
  6096. self.s.t.res_ret,
  6097. 139,
  6098. &[h, byte, iu, mask, align],
  6099. );
  6100. let f = self.s.m.extract(c, r, 0);
  6101. let v = self.as_int(f);
  6102. self.strides.insert(key, v);
  6103. Ok(Some(v))
  6104. }
  6105. /// The heap index of a descriptor that may differ between lanes,
  6106. /// computed in the current block (or, chosen by control flow, at the
  6107. /// join).
  6108. fn lane_heap_index(&mut self, src: &Source, sampler: bool) -> Result<V, Why> {
  6109. match src {
  6110. Source::Loaded { load, first } => self.heap_index(*load, *first, sampler),
  6111. Source::Fetched { load, first } => self.fetched_index(*load, *first, sampler),
  6112. Source::Lanes { mask, args } | Source::Select { scc: mask, args } => {
  6113. let [a, b] = &args[..] else {
  6114. return Err("a descriptor chosen per lane");
  6115. };
  6116. let cond = if matches!(src, Source::Lanes { .. }) {
  6117. let &m = self
  6118. .x
  6119. .st
  6120. .masks
  6121. .get(mask)
  6122. .ok_or("a descriptor chosen per lane by an untracked mask")?;
  6123. self.boolean(m, self.cur)?
  6124. } else {
  6125. match self.get(*mask)? {
  6126. Val::Bit(x) => x,
  6127. _ => return Err("SCC without a value"),
  6128. }
  6129. };
  6130. let set = self.lane_heap_index(a, sampler)?;
  6131. let clear = self.lane_heap_index(b, sampler)?;
  6132. Ok(self.s.m.select(self.cur, cond, set, clear))
  6133. }
  6134. Source::LanePhi { block, args } => {
  6135. // Each predecessor computes its heap index at its end (what
  6136. // it reads is there: the dwords are, on that edge); the join
  6137. // picks the one of the edge the lane came by. An edge no
  6138. // lane reading it takes gives index 0.
  6139. let join =
  6140. self.block[*block].ok_or("a per-lane descriptor chosen by control flow")?;
  6141. let mut incoming = Vec::new();
  6142. for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) {
  6143. if self.block[q].is_none() {
  6144. continue;
  6145. }
  6146. let tail =
  6147. self.tail[q].ok_or("a per-lane descriptor joined from a later block")?;
  6148. let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail);
  6149. let index = match arg {
  6150. Some(arg) => {
  6151. let here = std::mem::replace(&mut self.cur, at);
  6152. let index = self.lane_heap_index(arg, sampler);
  6153. self.cur = here;
  6154. index?
  6155. }
  6156. None => self.s.m.i32(0),
  6157. };
  6158. incoming.push((index, at));
  6159. }
  6160. let phi = self.s.m.phi(join, self.s.t.i32);
  6161. self.s.m.set_phi(phi, incoming);
  6162. Ok(phi)
  6163. }
  6164. _ => Err("a per-lane descriptor from neither a heap load nor a choice of them"),
  6165. }
  6166. }
  6167. /// The heap index of the descriptor at dword `first` of what the global
  6168. /// load at `load` reads, in each lane: its address (base plus offsets)
  6169. /// over the descriptor size.
  6170. fn fetched_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> {
  6171. const WHY: Why = "a per-lane descriptor load";
  6172. let a = *self
  6173. .scalar
  6174. .get(&load)
  6175. .ok_or("an untracked descriptor load")?;
  6176. match self.x.native.layout.get(a.param).map(|p| p.root) {
  6177. Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {}
  6178. _ => return Err("a descriptor outside the heaps"),
  6179. }
  6180. let li: &Inst = &self.x.p.blocks[load.0].insts[load.1];
  6181. let Fields::Flat {
  6182. addr: Some(Operand::Vector { reg, .. }),
  6183. saddr,
  6184. offset,
  6185. ..
  6186. } = li.fields
  6187. else {
  6188. return Err(WHY);
  6189. };
  6190. let c = self.cur;
  6191. // The low dword of the address: SGPR base plus VGPR offset, or the
  6192. // VGPR pair's low half (heap addresses fit in 32 bits).
  6193. let mut at = self.i32_of(li.read(Reg::V(reg)).ok_or(WHY)?)?;
  6194. if let Some(Operand::Scalar { code, .. }) = saddr
  6195. && code != NULL
  6196. {
  6197. let base = self.i32_of(li.read(Reg::S(code)).ok_or(WHY)?)?;
  6198. at = self.s.m.bin(c, Bin::Add, base, at);
  6199. }
  6200. let k = self
  6201. .s
  6202. .m
  6203. .i32((offset as i32 as u32).wrapping_add(4 * u32::from(first)));
  6204. at = self.s.m.bin(c, Bin::Add, at, k);
  6205. let shift = self.s.m.i32(if sampler { 4 } else { 5 });
  6206. Ok(self.s.m.bin(c, Bin::LShr, at, shift))
  6207. }
  6208. /// The heap index of the descriptor at dword `first` of what the scalar
  6209. /// load at `load` reads, computed in the current block.
  6210. fn heap_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> {
  6211. let a = *self
  6212. .scalar
  6213. .get(&load)
  6214. .ok_or("an untracked descriptor load")?;
  6215. match self.x.native.layout.get(a.param).map(|p| p.root) {
  6216. Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {}
  6217. _ => return Err("a descriptor outside the heaps"),
  6218. }
  6219. let li: &Inst = &self.x.p.blocks[load.0].insts[load.1];
  6220. let Fields::Smem {
  6221. base,
  6222. offset,
  6223. soffset,
  6224. ..
  6225. } = &li.fields
  6226. else {
  6227. return Err("a descriptor load");
  6228. };
  6229. let Operand::Scalar { code, .. } = *base else {
  6230. return Err("a descriptor load");
  6231. };
  6232. let c = self.cur;
  6233. let base = li.read(Reg::S(code)).ok_or("a descriptor load")?;
  6234. let mut addr = self.i32_of(base)?;
  6235. let k = self
  6236. .s
  6237. .m
  6238. .i32((*offset as u32).wrapping_add(4 * u32::from(first)));
  6239. addr = self.s.m.bin(c, Bin::Add, addr, k);
  6240. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  6241. let so = self.operand(li, soffset)?;
  6242. addr = self.s.m.bin(c, Bin::Add, addr, so);
  6243. }
  6244. let shift = self.s.m.i32(if sampler { 4 } else { 5 });
  6245. Ok(self.s.m.bin(c, Bin::LShr, addr, shift))
  6246. }
  6247. fn valu(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  6248. let Fields::Valu(v) = &inst.fields else {
  6249. unreachable!()
  6250. };
  6251. let name = inst.name();
  6252. if self.x.res.waterfall.compares.contains(&(b, i)) {
  6253. // The first lane's dwords of a waterfall loop are each lane's
  6254. // own (see `resource::Waterfall`).
  6255. self.lane(inst, Some(true));
  6256. return Ok(());
  6257. }
  6258. if let Some(rest) = name.strip_prefix("v_cmp_").or(name.strip_prefix("v_cmpx_")) {
  6259. let r = if v.dpp.is_some() {
  6260. Err("a compare with DPP")
  6261. } else {
  6262. self.compare(inst, rest)
  6263. };
  6264. if let Err(why) = r {
  6265. for &(_, w) in &inst.writes {
  6266. self.lane_fail.insert(w, why);
  6267. }
  6268. }
  6269. return r;
  6270. }
  6271. let mut guard = self.guard(b, i)?;
  6272. if let Some(d) = v.dpp {
  6273. let (x, enable) = self.dpp(inst, d)?;
  6274. guard = match (guard, enable) {
  6275. (Some(g), Some(e)) => Some(self.s.m.bin(self.cur, Bin::And, g, e)),
  6276. (g, e) => g.or(e),
  6277. };
  6278. self.src0 = Some(x);
  6279. }
  6280. let r = self.valu_op(inst, guard);
  6281. self.src0 = None;
  6282. r
  6283. }
  6284. /// DPP: src0 as read from another lane, and which lanes write their
  6285. /// result (none: all).
  6286. fn dpp(&mut self, inst: &Inst, dpp: Dpp) -> Result<(V, Option<V>), Why> {
  6287. let Fields::Valu(v) = &inst.fields else {
  6288. unreachable!()
  6289. };
  6290. let Some(&Operand::Vector { reg, .. }) = v.src.first() else {
  6291. return Err("a DPP operand");
  6292. };
  6293. let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("a DPP operand")?)?;
  6294. // Quad permutations and DPP8 stay in groups the pixel layout shares.
  6295. let quad = matches!(dpp, Dpp::Row { ctrl: 0..=0xFF, .. });
  6296. let mesh_quad = self.s.mesh.is_some() && quad;
  6297. if !mesh_quad {
  6298. self.cross_lane(quad)?;
  6299. }
  6300. let c = self.cur;
  6301. let lane = self.lane_index();
  6302. let k = |l: &mut Self, n: u32| l.s.m.i32(n);
  6303. let (sixteen_mask, low) = (k(self, !15), k(self, 15));
  6304. let row = self.s.m.bin(c, Bin::And, lane, sixteen_mask);
  6305. let pos = self.s.m.bin(c, Bin::And, lane, low);
  6306. // Source lane, and whether it lies in the row.
  6307. let (src, inside, masks, zero) = match dpp {
  6308. Dpp::Lanes { sel, .. } => {
  6309. let (seven, not7, three) = (k(self, 7), k(self, !7), k(self, 3));
  6310. let p = self.s.m.bin(c, Bin::And, lane, seven);
  6311. let sh = self.s.m.bin(c, Bin::Mul, p, three);
  6312. let sel = k(self, sel);
  6313. let pick = self.s.m.bin(c, Bin::LShr, sel, sh);
  6314. let pick = self.s.m.bin(c, Bin::And, pick, seven);
  6315. let base = self.s.m.bin(c, Bin::And, lane, not7);
  6316. (self.s.m.bin(c, Bin::Or, base, pick), None, None, false)
  6317. }
  6318. Dpp::Row {
  6319. ctrl,
  6320. row_mask,
  6321. bank_mask,
  6322. bound_ctrl,
  6323. ..
  6324. } => {
  6325. let n = u32::from(ctrl & 15);
  6326. let (src, inside) = match ctrl {
  6327. 0..=0xFF => {
  6328. let (three, one, not3) = (k(self, 3), k(self, 1), k(self, !3));
  6329. let p = self.s.m.bin(c, Bin::And, lane, three);
  6330. let sh = self.s.m.bin(c, Bin::Shl, p, one);
  6331. let perm = k(self, u32::from(ctrl));
  6332. let pick = self.s.m.bin(c, Bin::LShr, perm, sh);
  6333. let pick = self.s.m.bin(c, Bin::And, pick, three);
  6334. let base = self.s.m.bin(c, Bin::And, lane, not3);
  6335. (self.s.m.bin(c, Bin::Or, base, pick), None)
  6336. }
  6337. 0x101..=0x10F | 0x111..=0x11F => {
  6338. let nn = k(self, n);
  6339. let left = ctrl < 0x110;
  6340. let (op, p) = if left {
  6341. (Bin::Add, pred::IULT)
  6342. } else {
  6343. (Bin::Sub, pred::IUGE)
  6344. };
  6345. let s = self.s.m.bin(c, op, lane, nn);
  6346. // Left: pos + n < 16; right: pos >= n.
  6347. let bound = if left { k(self, 16 - n) } else { nn };
  6348. (s, Some(self.s.m.cmp(c, p, pos, bound)))
  6349. }
  6350. 0x121..=0x12F => {
  6351. let nn = k(self, n);
  6352. let t = self.s.m.bin(c, Bin::Sub, pos, nn);
  6353. let t = self.s.m.bin(c, Bin::And, t, low);
  6354. (self.s.m.bin(c, Bin::Or, row, t), None)
  6355. }
  6356. 0x140 | 0x141 => {
  6357. let m = k(self, if ctrl == 0x140 { 15 } else { 7 });
  6358. let t = self.s.m.bin(c, Bin::Xor, lane, m);
  6359. (t, None)
  6360. }
  6361. 0x150..=0x15F => {
  6362. let nn = k(self, n);
  6363. (self.s.m.bin(c, Bin::Or, row, nn), None)
  6364. }
  6365. 0x160..=0x16F => {
  6366. let nn = k(self, n);
  6367. (self.s.m.bin(c, Bin::Xor, lane, nn), None)
  6368. }
  6369. _ => return Err("a DPP lane pattern"),
  6370. };
  6371. let masks = (row_mask != 0xF || bank_mask != 0xF).then_some((row_mask, bank_mask));
  6372. (src, inside, masks, bound_ctrl)
  6373. }
  6374. };
  6375. let mut r = if mesh_quad {
  6376. self.quad_pick(x, src)
  6377. } else {
  6378. self.read_lane(x, src)
  6379. };
  6380. let mut enable = None;
  6381. if let Some(inside) = inside {
  6382. if zero {
  6383. let z = k(self, 0);
  6384. r = self.s.m.select(c, inside, r, z);
  6385. } else {
  6386. enable = Some(inside);
  6387. }
  6388. }
  6389. if let Some((rows, banks)) = masks {
  6390. // Row (16 lanes) and bank (4 lanes of a row) write masks.
  6391. let (four, two, three) = (k(self, 4), k(self, 2), k(self, 3));
  6392. let ri = self.s.m.bin(c, Bin::LShr, lane, four);
  6393. let ri = self.s.m.bin(c, Bin::And, ri, three);
  6394. let bi = self.s.m.bin(c, Bin::LShr, lane, two);
  6395. let bi = self.s.m.bin(c, Bin::And, bi, three);
  6396. let (rm, bm) = (k(self, u32::from(rows)), k(self, u32::from(banks)));
  6397. let rb = self.s.m.bin(c, Bin::LShr, rm, ri);
  6398. let bb = self.s.m.bin(c, Bin::LShr, bm, bi);
  6399. let both = self.s.m.bin(c, Bin::And, rb, bb);
  6400. let (one, z) = (k(self, 1), k(self, 0));
  6401. let both = self.s.m.bin(c, Bin::And, both, one);
  6402. let on = self.s.m.cmp(c, pred::NE, both, z);
  6403. enable = Some(match enable {
  6404. Some(e) => self.s.m.bin(c, Bin::And, e, on),
  6405. None => on,
  6406. });
  6407. }
  6408. Ok((r, enable))
  6409. }
  6410. fn valu_op(&mut self, inst: &Inst, guard: Option<V>) -> Result<(), Why> {
  6411. let Fields::Valu(v) = &inst.fields else {
  6412. unreachable!()
  6413. };
  6414. let name = inst.name();
  6415. let c = self.cur;
  6416. let f = |l: &mut Self, k| l.fsrc(inst, k);
  6417. let s = |l: &mut Self, k| l.src(inst, k);
  6418. let float = |l: &mut Self, r: V| l.write_f(inst, r, guard);
  6419. let int = |l: &mut Self, r: V| l.write_i(inst, r, guard);
  6420. if let Some(r) = self.valu16(inst, name, guard) {
  6421. return r;
  6422. }
  6423. if let Some(op) = name.strip_prefix("v_pk_") {
  6424. return self.packed16(inst, op, guard);
  6425. }
  6426. match name {
  6427. "v_mad_u64_u32" => {
  6428. // a * b + c, c and the result 64 bits wide; the carry out
  6429. // of the sum is this lane's bit of the mask it names.
  6430. let (a, b) = (s(self, 0)?, s(self, 1)?);
  6431. let x = self.src64(inst, 2)?;
  6432. let i64t = self.s.m.int(64);
  6433. self.s.flags |= flags::INT64;
  6434. let a = self.s.m.cast(c, Cast::ZExt, a, i64t);
  6435. let b = self.s.m.cast(c, Cast::ZExt, b, i64t);
  6436. let product = self.s.m.bin(c, Bin::Mul, a, b);
  6437. let r = self.s.m.bin(c, Bin::Add, product, x);
  6438. let carry = self.s.m.cmp(c, pred::IULT, r, x);
  6439. let Some(Operand::Vector { reg, .. }) = v.dst else {
  6440. return Err("a 64-bit result");
  6441. };
  6442. let (lo, hi) = self.split64(r);
  6443. self.write(inst, Reg::V(reg), lo, guard);
  6444. self.write(inst, Reg::V(reg + 1), hi, guard);
  6445. if let Some(Operand::Scalar { code, .. }) = v.carry
  6446. && let Some(w) = inst.write(Reg::S(code))
  6447. {
  6448. self.lane_bits.insert(w, carry);
  6449. }
  6450. for &(_, w) in &inst.writes {
  6451. self.vals
  6452. .entry(w)
  6453. .or_insert(Val::Missing("a lane mask read as data"));
  6454. }
  6455. Ok(())
  6456. }
  6457. "v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => {
  6458. let n = s(self, 0)?;
  6459. let x = self.src64(inst, 1)?;
  6460. let i64t = self.s.m.int(64);
  6461. let k63 = self.s.m.i32(63);
  6462. let n = self.s.m.bin(c, Bin::And, n, k63);
  6463. let n = self.s.m.cast(c, Cast::ZExt, n, i64t);
  6464. let op = match name {
  6465. "v_lshlrev_b64" => Bin::Shl,
  6466. "v_lshrrev_b64" => Bin::LShr,
  6467. _ => Bin::AShr,
  6468. };
  6469. let r = self.s.m.bin(c, op, x, n);
  6470. let Some(Operand::Vector { reg, .. }) = v.dst else {
  6471. return Err("a 64-bit result");
  6472. };
  6473. let (lo, hi) = self.split64(r);
  6474. self.write(inst, Reg::V(reg), lo, guard);
  6475. self.write(inst, Reg::V(reg + 1), hi, guard);
  6476. Ok(())
  6477. }
  6478. "v_cubeid_f32" | "v_cubesc_f32" | "v_cubetc_f32" | "v_cubema_f32" => {
  6479. // Cube-map face coordinates (AMD's ISA): the major axis is z
  6480. // when |z| >= |x| and |z| >= |y|, else y when |y| >= |x|,
  6481. // else x.
  6482. let (x, y, z) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  6483. let (ax, ay, az) = (self.unary(6, x), self.unary(6, y), self.unary(6, z));
  6484. let zx = self.s.m.cmp(c, pred::OGE, az, ax);
  6485. let zy = self.s.m.cmp(c, pred::OGE, az, ay);
  6486. let zmaj = self.s.m.bin(c, Bin::And, zx, zy);
  6487. let ymaj = self.s.m.cmp(c, pred::OGE, ay, ax);
  6488. let zero = self.s.m.f32(0);
  6489. let neg = |l: &mut Self, v: V| l.s.m.cmp(c, pred::OLT, v, zero);
  6490. let minus = |l: &mut Self, v: V| {
  6491. let z = l.s.m.f32(0x8000_0000);
  6492. l.s.m.bin(c, Bin::Sub, z, v)
  6493. };
  6494. let pick = |l: &mut Self, zv: V, yv: V, xv: V| {
  6495. let t = l.s.m.select(c, ymaj, yv, xv);
  6496. l.s.m.select(c, zmaj, zv, t)
  6497. };
  6498. let r = match name {
  6499. "v_cubeid_f32" => {
  6500. let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits());
  6501. let (nz, ny, nx) = (neg(self, z), neg(self, y), neg(self, x));
  6502. let (f5, f4, f3, f2, f1, f0) = (
  6503. k(self, 5.0),
  6504. k(self, 4.0),
  6505. k(self, 3.0),
  6506. k(self, 2.0),
  6507. k(self, 1.0),
  6508. k(self, 0.0),
  6509. );
  6510. let zf = self.s.m.select(c, nz, f5, f4);
  6511. let yf = self.s.m.select(c, ny, f3, f2);
  6512. let xf = self.s.m.select(c, nx, f1, f0);
  6513. pick(self, zf, yf, xf)
  6514. }
  6515. "v_cubesc_f32" => {
  6516. let (nz, nx) = (neg(self, z), neg(self, x));
  6517. let (mx, mz) = (minus(self, x), minus(self, z));
  6518. let zf = self.s.m.select(c, nz, mx, x);
  6519. let xf = self.s.m.select(c, nx, z, mz);
  6520. pick(self, zf, x, xf)
  6521. }
  6522. "v_cubetc_f32" => {
  6523. let ny = neg(self, y);
  6524. let (my, mz) = (minus(self, y), minus(self, z));
  6525. let yf = self.s.m.select(c, ny, mz, z);
  6526. pick(self, my, yf, my)
  6527. }
  6528. _ => {
  6529. let t = pick(self, z, y, x);
  6530. let two = self.s.m.f32(2.0f32.to_bits());
  6531. self.s.m.bin(c, Bin::Mul, t, two)
  6532. }
  6533. };
  6534. float(self, r)
  6535. }
  6536. "v_movrels_b32" | "v_movreld_b32" | "v_movrelsd_b32" => {
  6537. // M0 indexes the source (movrels), the destination (movreld)
  6538. // or both, from the encoded register up to the program's
  6539. // VGPR count (the registers the instruction reads or writes).
  6540. let m0 = self.i32_of(inst.read(Reg::S(crate::ir::M0)).ok_or("M0")?)?;
  6541. let (
  6542. Some(&Operand::Vector { reg: sreg, .. }),
  6543. Some(Operand::Vector { reg: dreg, .. }),
  6544. ) = (v.src.first(), v.dst)
  6545. else {
  6546. return Err("an M0-relative move");
  6547. };
  6548. let indexed_src = name != "v_movreld_b32";
  6549. let value = if indexed_src {
  6550. let mut r = self.s.m.i32(0);
  6551. for k in 0..=255u8.saturating_sub(sreg) {
  6552. let Some(x) = inst.read(Reg::V(sreg + k)) else {
  6553. break;
  6554. };
  6555. let x = self.i32_of(x)?;
  6556. let kk = self.s.m.i32(u32::from(k));
  6557. let is = self.s.m.cmp(c, pred::EQ, m0, kk);
  6558. r = self.s.m.select(c, is, x, r);
  6559. }
  6560. r
  6561. } else {
  6562. s(self, 0)?
  6563. };
  6564. if name == "v_movrels_b32" {
  6565. return int(self, value);
  6566. }
  6567. for k in 0..=255u8.saturating_sub(dreg) {
  6568. let Some(_) = inst.write(Reg::V(dreg + k)) else {
  6569. break;
  6570. };
  6571. let old = match inst.read(Reg::V(dreg + k)) {
  6572. Some(o) => self.i32_of(o)?,
  6573. None => self.s.m.i32(0),
  6574. };
  6575. let kk = self.s.m.i32(u32::from(k));
  6576. let is = self.s.m.cmp(c, pred::EQ, m0, kk);
  6577. let x = self.s.m.select(c, is, value, old);
  6578. self.write_placed(inst, Reg::V(dreg + k), x, guard);
  6579. }
  6580. Ok(())
  6581. }
  6582. "v_swap_b32" => {
  6583. let (
  6584. Some(&Operand::Vector { reg: sreg, .. }),
  6585. Some(Operand::Vector { reg: dreg, .. }),
  6586. ) = (v.src.first(), v.dst)
  6587. else {
  6588. return Err("v_swap_b32");
  6589. };
  6590. let a = self.i32_of(inst.read(Reg::V(dreg)).ok_or("v_swap_b32")?)?;
  6591. let b = self.i32_of(inst.read(Reg::V(sreg)).ok_or("v_swap_b32")?)?;
  6592. self.write_placed(inst, Reg::V(dreg), b, guard);
  6593. if dreg != sreg {
  6594. self.write_placed(inst, Reg::V(sreg), a, guard);
  6595. }
  6596. Ok(())
  6597. }
  6598. "v_ffbh_u32" | "v_ffbh_i32" => {
  6599. // Counted from the top bit, -1 when none (DXIL's too).
  6600. let a = s(self, 0)?;
  6601. let op = if name == "v_ffbh_u32" { 33 } else { 34 };
  6602. let r = self
  6603. .s
  6604. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  6605. int(self, r)
  6606. }
  6607. "v_mov_b32" => {
  6608. if v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 {
  6609. let a = f(self, 0)?;
  6610. return float(self, a);
  6611. }
  6612. let a = s(self, 0)?;
  6613. int(self, a)
  6614. }
  6615. "v_add_f32" | "v_sub_f32" | "v_subrev_f32" | "v_mul_f32" | "v_mul_legacy_f32"
  6616. | "v_max_f32" | "v_min_f32" => {
  6617. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  6618. let r = match name {
  6619. "v_add_f32" => self.s.m.bin(c, Bin::Add, a, bb),
  6620. "v_sub_f32" => self.s.m.bin(c, Bin::Sub, a, bb),
  6621. "v_subrev_f32" => self.s.m.bin(c, Bin::Sub, bb, a),
  6622. "v_mul_f32" => self.s.m.bin(c, Bin::Mul, a, bb),
  6623. "v_mul_legacy_f32" => self.legacy_mul(a, bb),
  6624. "v_max_f32" => self.max_min(true, a, bb),
  6625. _ => self.max_min(false, a, bb),
  6626. };
  6627. float(self, r)
  6628. }
  6629. "v_fma_f32" | "v_fmaak_f32" | "v_fmamk_f32" => {
  6630. // shortcut: DXIL has no fused f32 multiply-add; FMad lets the driver fuse.
  6631. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  6632. let r = self.fmad(a, bb, cc);
  6633. float(self, r)
  6634. }
  6635. "v_div_scale_f32" => {
  6636. // RDNA2 ISA: src0 = value to scale, src1 = denominator, src2 = numerator.
  6637. let (a, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  6638. let (ai, ni, di) = (self.as_int(a), self.as_int(num), self.as_int(den));
  6639. let (k23, k255, kabs) = (
  6640. self.s.m.i32(23),
  6641. self.s.m.i32(0xFF),
  6642. self.s.m.i32(0x7FFF_FFFF),
  6643. );
  6644. let (zero, k23_exp, k232_exp, k96) = (
  6645. self.s.m.i32(0),
  6646. self.s.m.i32(23),
  6647. self.s.m.i32(232),
  6648. self.s.m.i32(96),
  6649. );
  6650. let exp_of = |l: &mut Self, x: V| {
  6651. let s = l.s.m.bin(c, Bin::LShr, x, k23);
  6652. l.s.m.bin(c, Bin::And, s, k255)
  6653. };
  6654. let (e1, e2) = (exp_of(self, ni), exp_of(self, di));
  6655. let n_abs = self.s.m.bin(c, Bin::And, ni, kabs);
  6656. let d_abs = self.s.m.bin(c, Bin::And, di, kabs);
  6657. let z1 = self.s.m.cmp(c, pred::EQ, n_abs, zero);
  6658. let z2 = self.s.m.cmp(c, pred::EQ, d_abs, zero);
  6659. let any_zero = self.s.m.bin(c, Bin::Or, z1, z2);
  6660. let special = {
  6661. let s1 = self.s.m.cmp(c, pred::EQ, e1, k255);
  6662. let s2 = self.s.m.cmp(c, pred::EQ, e2, k255);
  6663. let a12 = self.s.m.bin(c, Bin::Or, s1, s2);
  6664. self.s.m.bin(c, Bin::Or, a12, any_zero)
  6665. };
  6666. let is_den = self.s.m.cmp(c, pred::EQ, ai, di);
  6667. let diff = self.s.m.bin(c, Bin::Sub, e2, e1);
  6668. let den_tiny = self.s.m.cmp(c, pred::IULE, e2, k23_exp);
  6669. let den_huge = self.s.m.cmp(c, pred::IUGE, e2, k232_exp);
  6670. let num_tiny_exp = self.s.m.cmp(c, pred::IULE, e1, k23_exp);
  6671. let num_huge = self.s.m.cmp(c, pred::IUGE, e1, k232_exp);
  6672. let num_gap = self.s.m.cmp(c, pred::SGE, diff, k96);
  6673. let not_den_huge = {
  6674. let t = self.s.m.bool(true);
  6675. self.s.m.bin(c, Bin::Xor, den_huge, t)
  6676. };
  6677. let num_gap = self.s.m.bin(c, Bin::And, num_gap, not_den_huge);
  6678. let num_tiny = self.s.m.bin(c, Bin::Or, num_tiny_exp, num_gap);
  6679. let up_raw = self.s.m.select(c, is_den, den_tiny, num_tiny);
  6680. let dn_raw = self.s.m.select(c, is_den, den_huge, num_huge);
  6681. let not_special = {
  6682. let t = self.s.m.bool(true);
  6683. self.s.m.bin(c, Bin::Xor, special, t)
  6684. };
  6685. let up = self.s.m.bin(c, Bin::And, up_raw, not_special);
  6686. let dn = self.s.m.bin(c, Bin::And, dn_raw, not_special);
  6687. let uncancelled = {
  6688. let x_tiny = self.s.m.bin(c, Bin::Xor, den_tiny, num_tiny);
  6689. let x_huge = self.s.m.bin(c, Bin::Xor, den_huge, num_huge);
  6690. self.s.m.bin(c, Bin::Or, x_tiny, x_huge)
  6691. };
  6692. let flag_raw = self.s.m.select(c, is_den, uncancelled, up_raw);
  6693. let flag = self.s.m.bin(c, Bin::And, flag_raw, not_special);
  6694. let k_up = self.s.m.f32(0x5F80_0000);
  6695. let k_dn = self.s.m.f32(0x1F80_0000);
  6696. let a_up = self.s.m.bin(c, Bin::Mul, a, k_up);
  6697. let a_dn = self.s.m.bin(c, Bin::Mul, a, k_dn);
  6698. let r = self.s.m.select(c, dn, a_dn, a);
  6699. let r = self.s.m.select(c, up, a_up, r);
  6700. let qnan = self.s.m.f32(0x7FC0_0000);
  6701. let r = self.s.m.select(c, any_zero, qnan, r);
  6702. float(self, r)?;
  6703. if let Some(Operand::Scalar { code, .. }) = v.carry
  6704. && let Some(w) = inst.write(Reg::S(code))
  6705. {
  6706. self.lane_bits.insert(w, flag);
  6707. }
  6708. for &(_, w) in &inst.writes {
  6709. self.vals
  6710. .entry(w)
  6711. .or_insert(Val::Missing("a lane mask read as data"));
  6712. }
  6713. Ok(())
  6714. }
  6715. "v_div_fmas_f32" => {
  6716. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  6717. let m = inst
  6718. .read(Reg::S(crate::ir::VCC))
  6719. .and_then(|v| self.x.st.masks.get(&v).copied())
  6720. .ok_or("v_div_fmas_f32 without VCC")?;
  6721. let vcc = self.boolean(m, c)?;
  6722. let tmp = self.fmad(a, bb, cc);
  6723. let ci = self.as_int(cc);
  6724. let (k23, k255, k128) = (self.s.m.i32(23), self.s.m.i32(0xFF), self.s.m.i32(128));
  6725. let sh = self.s.m.bin(c, Bin::LShr, ci, k23);
  6726. let exp = self.s.m.bin(c, Bin::And, sh, k255);
  6727. let exp_ge = self.s.m.cmp(c, pred::IUGE, exp, k128);
  6728. let (k_up, k_dn) = (self.s.m.f32(0x5F80_0000), self.s.m.f32(0x1F80_0000));
  6729. let scale = self.s.m.select(c, exp_ge, k_up, k_dn);
  6730. let scaled = self.s.m.bin(c, Bin::Mul, tmp, scale);
  6731. let r = self.s.m.select(c, vcc, scaled, tmp);
  6732. float(self, r)
  6733. }
  6734. "v_div_fixup_f32" => {
  6735. let (q, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  6736. let (qi, di, ni) = (self.as_int(q), self.as_int(den), self.as_int(num));
  6737. let (ksign, kabs, kinf) = (
  6738. self.s.m.i32(0x8000_0000),
  6739. self.s.m.i32(0x7FFF_FFFF),
  6740. self.s.m.i32(0x7F80_0000),
  6741. );
  6742. let (kqnan_bit, kneg_qnan, zero) = (
  6743. self.s.m.i32(0x0040_0000),
  6744. self.s.m.i32(0xFFC0_0000),
  6745. self.s.m.i32(0),
  6746. );
  6747. let sign = {
  6748. let x = self.s.m.bin(c, Bin::Xor, ni, di);
  6749. self.s.m.bin(c, Bin::And, x, ksign)
  6750. };
  6751. let q_abs = self.s.m.bin(c, Bin::And, qi, kabs);
  6752. let d_abs = self.s.m.bin(c, Bin::And, di, kabs);
  6753. let n_abs = self.s.m.bin(c, Bin::And, ni, kabs);
  6754. let q_nan = self.s.m.cmp(c, pred::IUGT, q_abs, kinf);
  6755. let d_nan = self.s.m.cmp(c, pred::IUGT, d_abs, kinf);
  6756. let n_nan = self.s.m.cmp(c, pred::IUGT, n_abs, kinf);
  6757. let d_inf = self.s.m.cmp(c, pred::EQ, d_abs, kinf);
  6758. let n_inf = self.s.m.cmp(c, pred::EQ, n_abs, kinf);
  6759. let d_zero = self.s.m.cmp(c, pred::EQ, d_abs, zero);
  6760. let n_zero = self.s.m.cmp(c, pred::EQ, n_abs, zero);
  6761. let both_inf = self.s.m.bin(c, Bin::And, n_inf, d_inf);
  6762. let both_zero = self.s.m.bin(c, Bin::And, n_zero, d_zero);
  6763. let invalid = self.s.m.bin(c, Bin::Or, both_inf, both_zero);
  6764. let make_inf = {
  6765. let t = self.s.m.bin(c, Bin::Or, n_inf, d_zero);
  6766. self.s.m.bin(c, Bin::Or, t, q_nan)
  6767. };
  6768. let make_zero = self.s.m.bin(c, Bin::Or, d_inf, n_zero);
  6769. let signed_q = self.s.m.bin(c, Bin::Or, sign, q_abs);
  6770. let signed_inf = self.s.m.bin(c, Bin::Or, sign, kinf);
  6771. let n_qnan = self.s.m.bin(c, Bin::Or, ni, kqnan_bit);
  6772. let d_qnan = self.s.m.bin(c, Bin::Or, di, kqnan_bit);
  6773. let r = self.s.m.select(c, make_zero, sign, signed_q);
  6774. let r = self.s.m.select(c, make_inf, signed_inf, r);
  6775. let r = self.s.m.select(c, invalid, kneg_qnan, r);
  6776. let r = self.s.m.select(c, d_nan, d_qnan, r);
  6777. let r = self.s.m.select(c, n_nan, n_qnan, r);
  6778. let rf = self.as_float(r);
  6779. float(self, rf)
  6780. }
  6781. "v_fmac_f32" | "v_mac_f32" | "v_mac_legacy_f32" => {
  6782. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  6783. let Some(Operand::Vector { reg, .. }) = v.dst else {
  6784. return Err("an accumulator");
  6785. };
  6786. let acc = inst.read(Reg::V(reg)).ok_or("an accumulator")?;
  6787. let acc = match self.floats.get(&acc) {
  6788. Some(&x) => x,
  6789. None => {
  6790. let x = self.i32_of(acc)?;
  6791. self.as_float(x)
  6792. }
  6793. };
  6794. let r = match name {
  6795. "v_fmac_f32" => self.fmad(a, bb, acc),
  6796. "v_mac_f32" => {
  6797. let m = self.s.m.bin(c, Bin::Mul, a, bb);
  6798. self.s.m.bin(c, Bin::Add, m, acc)
  6799. }
  6800. _ => {
  6801. let m = self.legacy_mul(a, bb);
  6802. self.s.m.bin(c, Bin::Add, m, acc)
  6803. }
  6804. };
  6805. float(self, r)
  6806. }
  6807. "v_mad_f32" | "v_madak_f32" | "v_madmk_f32" | "v_mad_legacy_f32" => {
  6808. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  6809. let m = if name == "v_mad_legacy_f32" {
  6810. self.legacy_mul(a, bb)
  6811. } else {
  6812. self.s.m.bin(c, Bin::Mul, a, bb)
  6813. };
  6814. let r = self.s.m.bin(c, Bin::Add, m, cc);
  6815. float(self, r)
  6816. }
  6817. "v_max3_f32" | "v_min3_f32" | "v_med3_f32" => {
  6818. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  6819. let r = match name {
  6820. "v_max3_f32" => {
  6821. let t = self.max_min(true, a, bb);
  6822. self.max_min(true, t, cc)
  6823. }
  6824. "v_min3_f32" => {
  6825. let t = self.max_min(false, a, bb);
  6826. self.max_min(false, t, cc)
  6827. }
  6828. _ => self.med3(a, bb, cc),
  6829. };
  6830. float(self, r)
  6831. }
  6832. "v_rcp_f32" | "v_rcp_iflag_f32" => {
  6833. // shortcut: the hardware reciprocal is approximate (1 ULP); this divides.
  6834. let a = f(self, 0)?;
  6835. let one = self.s.m.f32(1.0f32.to_bits());
  6836. let r = self.s.m.bin(c, Bin::SDiv, one, a);
  6837. float(self, r)
  6838. }
  6839. "v_rsq_f32" | "v_sqrt_f32" | "v_log_f32" | "v_exp_f32" | "v_fract_f32"
  6840. | "v_trunc_f32" | "v_floor_f32" | "v_ceil_f32" | "v_rndne_f32" | "v_sin_f32"
  6841. | "v_cos_f32" => {
  6842. let a = f(self, 0)?;
  6843. let op = match name {
  6844. "v_rsq_f32" => 25,
  6845. "v_sqrt_f32" => 24,
  6846. "v_log_f32" => 23,
  6847. "v_exp_f32" => 21,
  6848. "v_fract_f32" => 22,
  6849. "v_trunc_f32" => 29,
  6850. "v_floor_f32" => 27,
  6851. "v_ceil_f32" => 28,
  6852. "v_rndne_f32" => 26,
  6853. "v_sin_f32" => 13,
  6854. _ => 12,
  6855. };
  6856. let r = match op {
  6857. 12 | 13 => self.trig_turns(a, op == 12),
  6858. 22 => self.fract(a, 1.0, f32::from_bits(0x3F7F_FFFF)),
  6859. _ => self.unary(op, a),
  6860. };
  6861. float(self, r)
  6862. }
  6863. "v_cvt_i32_f32" | "v_cvt_u32_f32" | "v_cvt_flr_i32_f32" | "v_cvt_rpi_i32_f32" => {
  6864. let mut a = f(self, 0)?;
  6865. if name == "v_cvt_rpi_i32_f32" {
  6866. let h = self.s.m.f32(0.5f32.to_bits());
  6867. a = self.s.m.bin(c, Bin::Add, a, h);
  6868. }
  6869. if name != "v_cvt_i32_f32" && name != "v_cvt_u32_f32" {
  6870. a = self.unary(27, a);
  6871. }
  6872. // D3D's conversions saturate and give 0 for NaN, as the
  6873. // hardware does (checked on the RX 6700 XT and WARP).
  6874. let op = if name == "v_cvt_u32_f32" {
  6875. Cast::FpToUi
  6876. } else {
  6877. Cast::FpToSi
  6878. };
  6879. let r = self.s.m.cast(c, op, a, self.s.t.i32);
  6880. int(self, r)
  6881. }
  6882. "v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1"
  6883. | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => {
  6884. let mut a = s(self, 0)?;
  6885. if let Some(n) = name.strip_prefix("v_cvt_f32_ubyte") {
  6886. let sh = self.s.m.i32(8 * u32::from(n.as_bytes()[0] - b'0'));
  6887. let ff = self.s.m.i32(0xff);
  6888. a = self.s.m.bin(c, Bin::LShr, a, sh);
  6889. a = self.s.m.bin(c, Bin::And, a, ff);
  6890. }
  6891. let op = if name == "v_cvt_f32_i32" {
  6892. Cast::SiToFp
  6893. } else {
  6894. Cast::UiToFp
  6895. };
  6896. let r = self.s.m.cast(c, op, a, self.s.t.f32);
  6897. float(self, r)
  6898. }
  6899. "v_cvt_f32_f64" => {
  6900. let (lo, hi) = self.f64_pair(inst, 0)?;
  6901. let bits = self.f64_to_f32_bits(lo, hi);
  6902. let r = self.as_float(bits);
  6903. float(self, r)
  6904. }
  6905. "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => {
  6906. // Each source is f32, or with op_sel_hi the low (op_sel: high)
  6907. // f16 half; neg_hi is the absolute value here.
  6908. let mut xs = Vec::new();
  6909. for i in 0..3 {
  6910. let op = v.src.get(i).ok_or("a missing operand")?;
  6911. let mut x = if v.opsel_hi >> i & 1 != 0 {
  6912. let x = self.f16_operand(inst, op)?;
  6913. let h = if v.opsel >> i & 1 != 0 {
  6914. let k16 = self.s.m.i32(16);
  6915. self.s.m.bin(c, Bin::LShr, x, k16)
  6916. } else {
  6917. x
  6918. };
  6919. self.s
  6920. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h])
  6921. } else {
  6922. let x = self.operand(inst, op)?;
  6923. self.as_float(x)
  6924. };
  6925. if v.neg_hi >> i & 1 != 0 {
  6926. x = self.unary(6, x);
  6927. }
  6928. if v.neg >> i & 1 != 0 {
  6929. let z = self.s.m.f32(0x8000_0000);
  6930. x = self.s.m.bin(c, Bin::Sub, z, x);
  6931. }
  6932. xs.push(x);
  6933. }
  6934. let mut r = self.fmad(xs[0], xs[1], xs[2]);
  6935. if name == "v_fma_mix_f32" {
  6936. return float(self, r);
  6937. }
  6938. if v.clamp {
  6939. r = self.unary(7, r);
  6940. }
  6941. // The f16 result goes to one half; the other half stays.
  6942. let Some(Operand::Vector { reg, .. }) = v.dst else {
  6943. return Err("a mixed-precision result");
  6944. };
  6945. let old = match inst.read(Reg::V(reg)) {
  6946. Some(o) => self.i32_of(o)?,
  6947. None => self.s.m.i32(0),
  6948. };
  6949. let h = self
  6950. .s
  6951. .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[r]);
  6952. let (keep, h) = if name == "v_fma_mixhi_f16" {
  6953. let k16 = self.s.m.i32(16);
  6954. (0xFFFF, self.s.m.bin(c, Bin::Shl, h, k16))
  6955. } else {
  6956. (0xFFFF_0000, h)
  6957. };
  6958. let keep = self.s.m.i32(keep);
  6959. let old = self.s.m.bin(c, Bin::And, old, keep);
  6960. let x = self.s.m.bin(c, Bin::Or, old, h);
  6961. self.write(inst, Reg::V(reg), x, guard);
  6962. Ok(())
  6963. }
  6964. "v_cvt_pkrtz_f16_f32" => {
  6965. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  6966. let lo = self.f16_toward_zero(a);
  6967. let hi = self.f16_toward_zero(bb);
  6968. let sh = self.s.m.i32(16);
  6969. let hi = self.s.m.bin(c, Bin::Shl, hi, sh);
  6970. let r = self.s.m.bin(c, Bin::Or, lo, hi);
  6971. int(self, r)
  6972. }
  6973. "v_cvt_f16_f32" if v.opsel == 0 => {
  6974. // Rounded to nearest even (the MODE default) into the low half.
  6975. let a = f(self, 0)?;
  6976. let r = self
  6977. .s
  6978. .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[a]);
  6979. let Some(Operand::Vector { reg, .. }) = v.dst else {
  6980. return Err("a 16-bit result outside a VGPR");
  6981. };
  6982. let r = self.low_half(inst, reg, r);
  6983. int(self, r)
  6984. }
  6985. "v_pack_b32_f16" => {
  6986. // Two f16 sources (op_sel: their high halves; abs and neg on
  6987. // the sign bit) into the low and high half.
  6988. let mut halves = Vec::new();
  6989. for k in 0..2 {
  6990. let op = v.src.get(k).ok_or("a missing operand")?;
  6991. let mut x = self.f16_operand(inst, op)?;
  6992. if v.opsel >> k & 1 != 0 {
  6993. let k16 = self.s.m.i32(16);
  6994. x = self.s.m.bin(c, Bin::LShr, x, k16);
  6995. }
  6996. let mask = if v.abs >> k & 1 != 0 { 0x7FFF } else { 0xFFFF };
  6997. let mask = self.s.m.i32(mask);
  6998. x = self.s.m.bin(c, Bin::And, x, mask);
  6999. if v.neg >> k & 1 != 0 {
  7000. let sign = self.s.m.i32(0x8000);
  7001. x = self.s.m.bin(c, Bin::Xor, x, sign);
  7002. }
  7003. halves.push(x);
  7004. }
  7005. let k16 = self.s.m.i32(16);
  7006. let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16);
  7007. let r = self.s.m.bin(c, Bin::Or, halves[0], hi);
  7008. int(self, r)
  7009. }
  7010. "v_cvt_f32_f16" if v.opsel == 0 => {
  7011. let a = s(self, 0)?;
  7012. let r = self
  7013. .s
  7014. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[a]);
  7015. float(self, r)
  7016. }
  7017. "v_cndmask_b32" => {
  7018. let mask = match v.src.get(2) {
  7019. Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
  7020. _ => None,
  7021. };
  7022. const UNTRACKED: Why = "a select on an untracked mask";
  7023. let cond = match mask.and_then(|m| self.x.st.masks.get(&m).copied()) {
  7024. Some(m) => self.boolean(m, c)?,
  7025. // A mask the code holds as a number (a constant bit
  7026. // pattern: every other lane, every other pair...):
  7027. // this lane's bit of it. Exact where host lanes are
  7028. // the console's.
  7029. None if self.mask_data == MaskData::Console => {
  7030. // Each host wave taken as a wave of its own has no
  7031. // console lane numbers to pick the bits by.
  7032. if self.local {
  7033. return Err("a constant lane mask in a half-wave");
  7034. }
  7035. let m = mask.ok_or(UNTRACKED)?;
  7036. let lo = self.i32_of(m).map_err(|_| UNTRACKED)?;
  7037. // wave64: the register after it holds lanes 32-63.
  7038. let high = match v.src.get(2) {
  7039. Some(&Operand::Scalar { code, .. }) if self.x.native.wave64 => {
  7040. Some(inst.read(Reg::S(code + 1)).ok_or(UNTRACKED)?)
  7041. }
  7042. _ => None,
  7043. };
  7044. let hi = match high {
  7045. Some(h) => Some(self.i32_of(h).map_err(|_| UNTRACKED)?),
  7046. None => None,
  7047. };
  7048. self.cross_lane(false)?;
  7049. self.lane_bit(c, lo, hi)
  7050. }
  7051. None => return Err(UNTRACKED),
  7052. };
  7053. if v.abs != 0 || v.neg != 0 {
  7054. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  7055. let r = self.s.m.select(c, cond, bb, a);
  7056. return float(self, r);
  7057. }
  7058. let (a, bb) = (s(self, 0)?, s(self, 1)?);
  7059. let r = self.s.m.select(c, cond, bb, a);
  7060. int(self, r)
  7061. }
  7062. "v_add_co_u32" | "v_sub_co_u32" | "v_subrev_co_u32" | "v_add_co_ci_u32"
  7063. | "v_sub_co_ci_u32" | "v_subrev_co_ci_u32" => {
  7064. // The carry (borrow) out is a lane mask: this lane's bit.
  7065. let (mut a, mut bb) = (s(self, 0)?, s(self, 1)?);
  7066. if name.contains("subrev") {
  7067. std::mem::swap(&mut a, &mut bb);
  7068. }
  7069. let cin = if name.ends_with("_ci_u32") {
  7070. let m = match v.src.get(2) {
  7071. Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
  7072. _ => None,
  7073. };
  7074. let m = m
  7075. .and_then(|m| self.x.st.masks.get(&m).copied())
  7076. .ok_or("a carry-in from an untracked mask")?;
  7077. Some(self.boolean(m, c)?)
  7078. } else {
  7079. None
  7080. };
  7081. let (r, carry) = self.add_sub_carry(c, name.starts_with("v_add"), a, bb, cin);
  7082. int(self, r)?;
  7083. if let Some(Operand::Scalar { code, .. }) = v.carry
  7084. && let Some(w) = inst.write(Reg::S(code))
  7085. {
  7086. self.lane_bits.insert(w, carry);
  7087. }
  7088. for &(_, w) in &inst.writes {
  7089. self.vals
  7090. .entry(w)
  7091. .or_insert(Val::Missing("a lane mask read as data"));
  7092. }
  7093. Ok(())
  7094. }
  7095. "v_readlane_b32" => {
  7096. let (a, lane) = (s(self, 0)?, s(self, 1)?);
  7097. // A computed lane in a pixel or vertex program is a host lane
  7098. // (from a mask or `v_mbcnt`); a constant one is the console's.
  7099. if self.mask_data == MaskData::Host && !matches!(lane, V::Const(_)) {
  7100. self.s.flags |= flags::WAVE_OPS;
  7101. } else {
  7102. self.cross_lane(false)?;
  7103. }
  7104. if let Some(slot) = self.exchange.as_ref().map(|e| e.0) {
  7105. if self.local && self.local_any {
  7106. // this host wave's lane of that number (lanes 32..63 are 0..31 here)
  7107. let k31 = self.s.m.i32(31);
  7108. let here = self.s.m.bin(self.cur, Bin::And, lane, k31);
  7109. let r = self.read_lane(a, here);
  7110. return int(self, r);
  7111. }
  7112. if self.local {
  7113. return Err("a lane read in a half-wave");
  7114. }
  7115. if self.exchange.as_ref().is_some_and(|e| e.1) {
  7116. // a group of 32 or fewer: the lane is in this host wave
  7117. let r = self.read_lane(a, lane);
  7118. return int(self, r);
  7119. }
  7120. // the lane that holds it may be in the other host wave: it gives it through LDS
  7121. if !self.all_lanes(self.cur_ir) {
  7122. need(self.cur_ir);
  7123. return Err("a lane read where not every lane runs");
  7124. }
  7125. let cl = self.console_lane();
  7126. let is = self.s.m.cmp(self.cur, pred::EQ, cl, lane);
  7127. let k = self.exchange_pair(slot);
  7128. let at = self.begin_guarded(Some(is));
  7129. let lds = self.s.lds();
  7130. let ptr = self.s.m.element(self.cur, lds, k);
  7131. self.s.m.store(self.cur, ptr, a);
  7132. self.end_guarded(at, &[]);
  7133. let c2 = self.cur;
  7134. self.group_sync(c2);
  7135. let ptr = self.s.m.element(c2, lds, k);
  7136. let r = self.s.m.load(c2, ptr);
  7137. self.group_sync(c2);
  7138. return int(self, r);
  7139. }
  7140. let r = self.read_lane(a, lane);
  7141. int(self, r)
  7142. }
  7143. "v_writelane_b32" => {
  7144. // The lane given takes the scalar; the others keep their value.
  7145. let (a, lane) = (s(self, 0)?, s(self, 1)?);
  7146. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7147. return Err("a lane write");
  7148. };
  7149. let old = match inst.read(Reg::V(reg)) {
  7150. Some(o) => self.i32_of(o)?,
  7151. None => self.s.m.i32(0),
  7152. };
  7153. self.cross_lane(false)?;
  7154. if self.local && !self.local_any {
  7155. return Err("a lane write in a half-wave");
  7156. }
  7157. let me = self.console_lane();
  7158. let is = self.s.m.cmp(c, pred::EQ, me, lane);
  7159. let r = self.s.m.select(c, is, a, old);
  7160. int(self, r)
  7161. }
  7162. "v_readfirstlane_b32"
  7163. if inst
  7164. .writes
  7165. .first()
  7166. .is_some_and(|w| self.x.res.waterfall.reads.contains(&w.1)) =>
  7167. {
  7168. // A waterfall loop's read of a descriptor dword: the lane's own.
  7169. let a = s(self, 0)?;
  7170. int(self, a)
  7171. }
  7172. "v_readfirstlane_b32"
  7173. if matches!(v.src.first(), Some(&Operand::Vector { reg, .. })
  7174. if inst.read(Reg::V(reg)).is_some_and(|x| self.own_bits.alike.contains(&x))) =>
  7175. {
  7176. // The bits a loop over a wave OR has still to visit (`own_bits`): every lane of
  7177. // the host wave holds the same, so the first lane's is the lane's own.
  7178. let a = s(self, 0)?;
  7179. int(self, a)
  7180. }
  7181. "v_readfirstlane_b32" => {
  7182. let a = s(self, 0)?;
  7183. let (mine, any) = self.first_lane(a, guard);
  7184. // two host waves that exchange: the console's first lane may be in the other
  7185. // one, unless every lane holds the same value
  7186. let alike = match v.src.first() {
  7187. Some(&Operand::Vector { reg, .. }) => {
  7188. inst.read(Reg::V(reg)).is_some_and(|x| self.uniform.contains(&x))
  7189. }
  7190. _ => true,
  7191. };
  7192. let halves = self.exchange.as_ref().is_some_and(|e| !e.1) && !self.local;
  7193. let r = if halves && !alike {
  7194. if !self.all_lanes(self.cur_ir) {
  7195. need(self.cur_ir);
  7196. return Err("a first-lane read where not every lane runs");
  7197. }
  7198. let c = self.cur;
  7199. let i32t = self.s.t.i32;
  7200. let has = self.s.m.cast(c, Cast::ZExt, any, i32t);
  7201. let (lo_has, hi_has) = self.exchange_halves(c, has);
  7202. let (lo, hi) = self.exchange_halves(c, mine);
  7203. let z = self.s.m.i32(0);
  7204. let in_lo = self.s.m.cmp(c, pred::NE, lo_has, z);
  7205. let in_hi = self.s.m.cmp(c, pred::NE, hi_has, z);
  7206. // neither half has a lane in EXEC: the console reads lane 0
  7207. let hi = self.s.m.select(c, in_hi, hi, lo);
  7208. self.s.m.select(c, in_lo, lo, hi)
  7209. } else {
  7210. mine
  7211. };
  7212. int(self, r)
  7213. }
  7214. _ => {
  7215. let r = self.integer(inst, name)?;
  7216. int(self, r)
  7217. }
  7218. }
  7219. }
  7220. /// A 64-bit source (a register pair; inline constants sign-extend).
  7221. fn src64(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  7222. let Fields::Valu(v) = &inst.fields else {
  7223. unreachable!()
  7224. };
  7225. if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 || v.sdwa.is_some() || v.dpp.is_some() {
  7226. return Err("64-bit operand modifiers");
  7227. }
  7228. let c = self.cur;
  7229. let i64t = self.s.m.int(64);
  7230. self.s.flags |= flags::INT64;
  7231. let op = *v.src.get(k).ok_or("a missing operand")?;
  7232. let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<V, Why> {
  7233. let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?;
  7234. let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?;
  7235. Ok(l.join64(lo, hi))
  7236. };
  7237. match op {
  7238. Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1)),
  7239. Operand::Scalar { code, .. } if code != NULL => {
  7240. pair(self, Reg::S(code), Reg::S(code + 1))
  7241. }
  7242. Operand::Const(k @ 128..=208) => {
  7243. let x = crate::resource::inline(k).ok_or("a special operand")?;
  7244. Ok(self.s.m.int_const(i64t, i64::from(x as i32)))
  7245. }
  7246. _ => {
  7247. // Literals and the null register: zero-extended.
  7248. let x = self.operand(inst, &op)?;
  7249. Ok(self.s.m.cast(c, Cast::ZExt, x, i64t))
  7250. }
  7251. }
  7252. }
  7253. /// Reads an IEEE-754 binary64 operand as `(lo, hi)` 32-bit words, applying
  7254. /// `abs` and `neg` input modifiers on operand `k`.
  7255. fn f64_pair(&mut self, inst: &Inst, k: usize) -> Result<(V, V), Why> {
  7256. let Fields::Valu(v) = &inst.fields else {
  7257. unreachable!()
  7258. };
  7259. if v.sdwa.is_some() || v.dpp.is_some() {
  7260. return Err("64-bit operand modifiers");
  7261. }
  7262. let op = *v.src.get(k).ok_or("a missing operand")?;
  7263. let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<(V, V), Why> {
  7264. let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?;
  7265. let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?;
  7266. Ok((lo, hi))
  7267. };
  7268. let (lo, mut hi) = match op {
  7269. Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1))?,
  7270. Operand::Scalar { code, .. } if code != NULL => {
  7271. pair(self, Reg::S(code), Reg::S(code + 1))?
  7272. }
  7273. Operand::Const(128) => (self.s.m.i32(0), self.s.m.i32(0)),
  7274. Operand::Const(c @ 240..=248) => {
  7275. const INLINE_F64: [f64; 9] = [
  7276. 0.5,
  7277. -0.5,
  7278. 1.0,
  7279. -1.0,
  7280. 2.0,
  7281. -2.0,
  7282. 4.0,
  7283. -4.0,
  7284. 1.0 / std::f64::consts::TAU,
  7285. ];
  7286. let bits = INLINE_F64[(c - 240) as usize].to_bits();
  7287. (self.s.m.i32(bits as u32), self.s.m.i32((bits >> 32) as u32))
  7288. }
  7289. // GFX10 places a 32-bit literal in the high 32 bits of a 64-bit float operand.
  7290. Operand::Literal(x) => (self.s.m.i32(0), self.s.m.i32(x)),
  7291. _ => return Err("a 64-bit float operand"),
  7292. };
  7293. let c = self.cur;
  7294. if v.abs >> k & 1 != 0 {
  7295. let mask = self.s.m.i32(0x7FFF_FFFF);
  7296. hi = self.s.m.bin(c, Bin::And, hi, mask);
  7297. }
  7298. if v.neg >> k & 1 != 0 {
  7299. let sign = self.s.m.i32(0x8000_0000);
  7300. hi = self.s.m.bin(c, Bin::Xor, hi, sign);
  7301. }
  7302. Ok((lo, hi))
  7303. }
  7304. /// Converts IEEE-754 binary64 `(lo, hi)` to binary32 bits with round-to-nearest-even,
  7305. /// without requiring host `DOUBLES` (`f64`) support.
  7306. fn f64_to_f32_bits(&mut self, lo: V, hi: V) -> V {
  7307. let c = self.cur;
  7308. let k0 = self.s.m.i32(0);
  7309. let k1 = self.s.m.i32(1);
  7310. let sign_mask = self.s.m.i32(0x8000_0000);
  7311. let sign = self.s.m.bin(c, Bin::And, hi, sign_mask);
  7312. let k20 = self.s.m.i32(20);
  7313. let k7ff = self.s.m.i32(0x7FF);
  7314. let exp64 = self.s.m.bin(c, Bin::LShr, hi, k20);
  7315. let exp64 = self.s.m.bin(c, Bin::And, exp64, k7ff);
  7316. let frac_mask = self.s.m.i32(0x000F_FFFF);
  7317. let frac_hi = self.s.m.bin(c, Bin::And, hi, frac_mask);
  7318. let frac_any = self.s.m.bin(c, Bin::Or, frac_hi, lo);
  7319. let frac_nz = self.s.m.cmp(c, pred::NE, frac_any, k0);
  7320. let k3 = self.s.m.i32(3);
  7321. let k29 = self.s.m.i32(29);
  7322. let m23_hi = self.s.m.bin(c, Bin::Shl, frac_hi, k3);
  7323. let m23_lo = self.s.m.bin(c, Bin::LShr, lo, k29);
  7324. let m23 = self.s.m.bin(c, Bin::Or, m23_hi, m23_lo);
  7325. let rem_mask = self.s.m.i32(0x1FFF_FFFF);
  7326. let rem = self.s.m.bin(c, Bin::And, lo, rem_mask);
  7327. let half_rem = self.s.m.i32(0x1000_0000);
  7328. let gt_half = self.s.m.cmp(c, pred::IUGT, rem, half_rem);
  7329. let eq_half = self.s.m.cmp(c, pred::EQ, rem, half_rem);
  7330. let m23_odd_bit = self.s.m.bin(c, Bin::And, m23, k1);
  7331. let m23_odd = self.s.m.cmp(c, pred::NE, m23_odd_bit, k0);
  7332. let tie_up = self.s.m.bin(c, Bin::And, eq_half, m23_odd);
  7333. let norm_round = self.s.m.bin(c, Bin::Or, gt_half, tie_up);
  7334. let norm_inc = self.s.m.select(c, norm_round, k1, k0);
  7335. // Normal range: exp64 in [897, 1150] -> exp32 in [1, 254].
  7336. let k896 = self.s.m.i32(896);
  7337. let k23 = self.s.m.i32(23);
  7338. let exp32 = self.s.m.bin(c, Bin::Sub, exp64, k896);
  7339. let exp32_sh = self.s.m.bin(c, Bin::Shl, exp32, k23);
  7340. let norm_body = self.s.m.bin(c, Bin::Add, exp32_sh, m23);
  7341. let norm_body = self.s.m.bin(c, Bin::Add, norm_body, norm_inc);
  7342. let norm_res = self.s.m.bin(c, Bin::Or, sign, norm_body);
  7343. // Subnormal range: exp64 in [874, 896] -> shift in [1, 23].
  7344. let k897 = self.s.m.i32(897);
  7345. let k32 = self.s.m.i32(32);
  7346. let k31 = self.s.m.i32(31);
  7347. let imp = self.s.m.i32(0x0080_0000);
  7348. let sig24 = self.s.m.bin(c, Bin::Or, imp, m23);
  7349. let raw_shift = self.s.m.bin(c, Bin::Sub, k897, exp64);
  7350. // Clamp shift to [1, 23] so shifts never produce poison outside the subnormal branch.
  7351. let lt1 = self.s.m.cmp(c, pred::IULT, raw_shift, k1);
  7352. let shift = self.s.m.select(c, lt1, k1, raw_shift);
  7353. let gt23 = self.s.m.cmp(c, pred::IUGT, shift, k23);
  7354. let shift = self.s.m.select(c, gt23, k23, shift);
  7355. let sub_m = self.s.m.bin(c, Bin::LShr, sig24, shift);
  7356. let inv_shift = self.s.m.bin(c, Bin::Sub, k32, shift);
  7357. let lost = self.s.m.bin(c, Bin::Shl, sig24, inv_shift);
  7358. let round_bit = self.s.m.bin(c, Bin::LShr, lost, k31);
  7359. let round_on = self.s.m.cmp(c, pred::NE, round_bit, k0);
  7360. let low31 = self.s.m.i32(0x7FFF_FFFF);
  7361. let lost_lo = self.s.m.bin(c, Bin::And, lost, low31);
  7362. let sticky = self.s.m.bin(c, Bin::Or, lost_lo, rem);
  7363. let sticky_on = self.s.m.cmp(c, pred::NE, sticky, k0);
  7364. let sub_odd_bit = self.s.m.bin(c, Bin::And, sub_m, k1);
  7365. let sub_odd = self.s.m.cmp(c, pred::NE, sub_odd_bit, k0);
  7366. let sub_tie = self.s.m.bin(c, Bin::Or, sticky_on, sub_odd);
  7367. let sub_round = self.s.m.bin(c, Bin::And, round_on, sub_tie);
  7368. let sub_inc = self.s.m.select(c, sub_round, k1, k0);
  7369. let sub_body = self.s.m.bin(c, Bin::Add, sub_m, sub_inc);
  7370. let sub_res = self.s.m.bin(c, Bin::Or, sign, sub_body);
  7371. // Underflow range: exp64 < 874. Only exp64 == 873 with non-zero fraction rounds up to min subnormal (1).
  7372. let k873 = self.s.m.i32(873);
  7373. let eq873 = self.s.m.cmp(c, pred::EQ, exp64, k873);
  7374. let round_min = self.s.m.bin(c, Bin::And, eq873, frac_nz);
  7375. let min_bit = self.s.m.select(c, round_min, k1, k0);
  7376. let under_res = self.s.m.bin(c, Bin::Or, sign, min_bit);
  7377. // Overflow / Inf / NaN: exp64 >= 1151.
  7378. let is_exp_all = self.s.m.cmp(c, pred::EQ, exp64, k7ff);
  7379. let is_nan = self.s.m.bin(c, Bin::And, is_exp_all, frac_nz);
  7380. let inf_bits = self.s.m.i32(0x7F80_0000);
  7381. let qnan_bits = self.s.m.i32(0x7FC0_0000);
  7382. let nan_body = self.s.m.bin(c, Bin::Or, qnan_bits, m23);
  7383. let over_body = self.s.m.select(c, is_nan, nan_body, inf_bits);
  7384. let over_res = self.s.m.bin(c, Bin::Or, sign, over_body);
  7385. // Select final result by exponent range.
  7386. let k874 = self.s.m.i32(874);
  7387. let k1151 = self.s.m.i32(1151);
  7388. let is_under = self.s.m.cmp(c, pred::IULT, exp64, k874);
  7389. let is_sub = self.s.m.cmp(c, pred::IULT, exp64, k897);
  7390. let is_over = self.s.m.cmp(c, pred::IUGE, exp64, k1151);
  7391. let r = self.s.m.select(c, is_over, over_res, norm_res);
  7392. let r = self.s.m.select(c, is_sub, sub_res, r);
  7393. self.s.m.select(c, is_under, under_res, r)
  7394. }
  7395. fn join64(&mut self, lo: V, hi: V) -> V {
  7396. let c = self.cur;
  7397. let ty = self.s.m.int(64);
  7398. let lo = self.s.m.cast(c, Cast::ZExt, lo, ty);
  7399. let hi = self.s.m.cast(c, Cast::ZExt, hi, ty);
  7400. let shift = self.s.m.int_const(ty, 32);
  7401. let hi = self.s.m.bin(c, Bin::Shl, hi, shift);
  7402. self.s.m.bin(c, Bin::Or, lo, hi)
  7403. }
  7404. /// The low and high dwords of an i64.
  7405. fn split64(&mut self, x: V) -> (V, V) {
  7406. let c = self.cur;
  7407. let i64t = self.s.m.int(64);
  7408. let k32 = self.s.m.int_const(i64t, 32);
  7409. let lo = self.s.m.cast(c, Cast::Trunc, x, self.s.t.i32);
  7410. let hi = self.s.m.bin(c, Bin::LShr, x, k32);
  7411. let hi = self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32);
  7412. (lo, hi)
  7413. }
  7414. /// Source `k` of a 16-bit operation in the low 16 bits (the rest 0):
  7415. /// op_sel (or an SDWA word select) picks the high half; inline float
  7416. /// constants are f16 values here.
  7417. fn half_src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  7418. let Fields::Valu(v) = &inst.fields else {
  7419. unreachable!()
  7420. };
  7421. let op = *v.src.get(k).ok_or("a missing operand")?;
  7422. let mut high = v.opsel >> k & 1 != 0;
  7423. if let Some(sd) = v.sdwa {
  7424. match sd.src_sel.get(k).copied().unwrap_or(6) {
  7425. 4 => {}
  7426. 5 => high = true,
  7427. 6 => {}
  7428. _ => return Err("a byte select on a 16-bit operation"),
  7429. }
  7430. }
  7431. let x = match self.src0 {
  7432. Some(x) if k == 0 => x,
  7433. _ => self.f16_operand(inst, &op)?,
  7434. };
  7435. let c = self.cur;
  7436. let x = if high {
  7437. let k16 = self.s.m.i32(16);
  7438. self.s.m.bin(c, Bin::LShr, x, k16)
  7439. } else {
  7440. x
  7441. };
  7442. let m = self.s.m.i32(0xFFFF);
  7443. Ok(self.s.m.bin(c, Bin::And, x, m))
  7444. }
  7445. /// An f16 source as an f32 (exact), with its abs/neg modifiers.
  7446. fn half_fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  7447. let Fields::Valu(v) = &inst.fields else {
  7448. unreachable!()
  7449. };
  7450. let h = self.half_src(inst, k)?;
  7451. let f32t = self.s.t.f32;
  7452. let mut f = self
  7453. .s
  7454. .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  7455. if v.abs >> k & 1 != 0 {
  7456. f = self.unary(6, f);
  7457. }
  7458. if v.neg >> k & 1 != 0 {
  7459. let z = self.s.m.f32(0x8000_0000);
  7460. f = self.s.m.bin(self.cur, Bin::Sub, z, f);
  7461. }
  7462. Ok(f)
  7463. }
  7464. /// Writes a 16-bit result (low bits of `x`) into the destination's low
  7465. /// half, or its high half with op_sel bit 3 (or an SDWA WORD_1 select);
  7466. /// the other half is kept (GFX10).
  7467. fn write_half(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> {
  7468. let Fields::Valu(v) = &inst.fields else {
  7469. unreachable!()
  7470. };
  7471. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7472. return Err("a 16-bit result outside a VGPR");
  7473. };
  7474. let mut high = v.opsel >> 3 & 1 != 0;
  7475. // SDWA: the word written, the other one kept (preserve) or zero
  7476. // (pad; a sign extension above the high word adds nothing).
  7477. let mut keep = true;
  7478. if let Some(sd) = v.sdwa {
  7479. match (sd.dst_sel, sd.dst_unused) {
  7480. (4, 2) => {}
  7481. (5, 2) => high = true,
  7482. (4 | 6, _) => keep = false,
  7483. (5, _) => (high, keep) = (true, false),
  7484. _ => return Err("an SDWA destination of a 16-bit operation"),
  7485. }
  7486. }
  7487. let c = self.cur;
  7488. let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) {
  7489. Some(Ok(o)) if keep => o,
  7490. _ => self.s.m.i32(0),
  7491. };
  7492. let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
  7493. let x = self.s.m.bin(c, Bin::And, x, low);
  7494. let r = if high {
  7495. let o = self.s.m.bin(c, Bin::And, old, low);
  7496. let x = self.s.m.bin(c, Bin::Shl, x, k16);
  7497. self.s.m.bin(c, Bin::Or, o, x)
  7498. } else {
  7499. let keep = self.s.m.i32(0xFFFF_0000);
  7500. let o = self.s.m.bin(c, Bin::And, old, keep);
  7501. self.s.m.bin(c, Bin::Or, o, x)
  7502. };
  7503. self.write_placed(inst, Reg::V(reg), r, guard);
  7504. Ok(())
  7505. }
  7506. /// 16-bit operations, computed in f32 or i32: f16 sums, differences and
  7507. /// products are exact there and round once to f16 (f32 has the 2 x 11 +
  7508. /// 2 bits that make double rounding harmless); `None` if `name` is none.
  7509. fn valu16(&mut self, inst: &Inst, name: &str, guard: Option<V>) -> Option<Result<(), Why>> {
  7510. const FLOAT2: &[&str] = &[
  7511. "v_add_f16",
  7512. "v_sub_f16",
  7513. "v_subrev_f16",
  7514. "v_mul_f16",
  7515. "v_max_f16",
  7516. "v_min_f16",
  7517. ];
  7518. const FLOAT3: &[&str] = &[
  7519. "v_fma_f16",
  7520. "v_mad_f16",
  7521. "v_fmac_f16",
  7522. "v_mac_f16",
  7523. "v_max3_f16",
  7524. "v_min3_f16",
  7525. "v_med3_f16",
  7526. ];
  7527. const FLOAT1: &[&str] = &[
  7528. "v_rcp_f16",
  7529. "v_sqrt_f16",
  7530. "v_rsq_f16",
  7531. "v_log_f16",
  7532. "v_exp_f16",
  7533. "v_fract_f16",
  7534. "v_trunc_f16",
  7535. "v_floor_f16",
  7536. "v_ceil_f16",
  7537. "v_rndne_f16",
  7538. "v_sin_f16",
  7539. "v_cos_f16",
  7540. "v_cvt_f16_u16",
  7541. "v_cvt_f16_i16",
  7542. ];
  7543. const INT: &[&str] = &[
  7544. "v_add_nc_u16",
  7545. "v_sub_nc_u16",
  7546. "v_subrev_nc_u16",
  7547. "v_mul_lo_u16",
  7548. "v_lshlrev_b16",
  7549. "v_lshrrev_b16",
  7550. "v_ashrrev_i16",
  7551. "v_max_u16",
  7552. "v_max_i16",
  7553. "v_min_u16",
  7554. "v_min_i16",
  7555. "v_cvt_u16_f16",
  7556. "v_cvt_i16_f16",
  7557. "v_cvt_norm_i16_f16",
  7558. "v_cvt_norm_u16_f16",
  7559. ];
  7560. let all = [FLOAT1, FLOAT2, FLOAT3, INT];
  7561. if !all.iter().any(|l| l.contains(&name))
  7562. && !matches!(name, "v_cvt_f16_f32" | "v_cvt_f32_f16")
  7563. {
  7564. return None;
  7565. }
  7566. Some(self.valu16_op(inst, name, guard, FLOAT1, FLOAT2, FLOAT3))
  7567. }
  7568. #[allow(clippy::too_many_arguments)]
  7569. fn valu16_op(
  7570. &mut self,
  7571. inst: &Inst,
  7572. name: &str,
  7573. guard: Option<V>,
  7574. float1: &[&str],
  7575. float2: &[&str],
  7576. float3: &[&str],
  7577. ) -> Result<(), Why> {
  7578. let Fields::Valu(v) = &inst.fields else {
  7579. unreachable!()
  7580. };
  7581. let c = self.cur;
  7582. let i32t = self.s.t.i32;
  7583. let f32t = self.s.t.f32;
  7584. if name == "v_cvt_f32_f16" {
  7585. let f = self.half_fsrc(inst, 0)?;
  7586. return self.write_f(inst, f, guard);
  7587. }
  7588. let float_result = |l: &mut Self, mut f: V| -> Result<(), Why> {
  7589. match v.omod {
  7590. 0 => {}
  7591. k => {
  7592. let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)];
  7593. let k = l.s.m.f32(factor.to_bits());
  7594. f = l.s.m.bin(l.cur, Bin::Mul, f, k);
  7595. }
  7596. }
  7597. if v.clamp {
  7598. f = l.unary(7, f);
  7599. }
  7600. // The console rounds to nearest; the host's conversion may round toward zero
  7601. // (NVIDIA's does), one step of the last place lower where the two differ.
  7602. // shortcut: the host's conversion unless `VICTORY_F16_NEAREST=1`
  7603. // ([`f16_nearest_on`]), which costs a dozen instructions per result.
  7604. let h = if f16_nearest_on() {
  7605. l.f16_nearest(f)
  7606. } else {
  7607. l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  7608. };
  7609. l.write_half(inst, h, guard)
  7610. };
  7611. if name == "v_cvt_f16_f32" {
  7612. let f = self.fsrc(inst, 0)?;
  7613. return float_result(self, f);
  7614. }
  7615. if float2.contains(&name) {
  7616. let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?);
  7617. let r = match name {
  7618. "v_add_f16" => self.s.m.bin(c, Bin::Add, a, b),
  7619. "v_sub_f16" => self.s.m.bin(c, Bin::Sub, a, b),
  7620. "v_subrev_f16" => self.s.m.bin(c, Bin::Sub, b, a),
  7621. "v_mul_f16" => self.s.m.bin(c, Bin::Mul, a, b),
  7622. "v_max_f16" => self.max_min(true, a, b),
  7623. _ => self.max_min(false, a, b),
  7624. };
  7625. return float_result(self, r);
  7626. }
  7627. if float3.contains(&name) {
  7628. let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?);
  7629. let acc = if matches!(name, "v_fmac_f16" | "v_mac_f16") {
  7630. // The accumulator is the destination's half that is written.
  7631. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7632. return Err("an accumulator");
  7633. };
  7634. let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?;
  7635. let x = if v.opsel >> 3 & 1 != 0 {
  7636. let k16 = self.s.m.i32(16);
  7637. self.s.m.bin(c, Bin::LShr, x, k16)
  7638. } else {
  7639. x
  7640. };
  7641. let m = self.s.m.i32(0xFFFF);
  7642. let x = self.s.m.bin(c, Bin::And, x, m);
  7643. self.s
  7644. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x])
  7645. } else {
  7646. self.half_fsrc(inst, 2)?
  7647. };
  7648. let r = match name {
  7649. // shortcut: fused f16 multiply-adds as FMad in f32 (the
  7650. // product is exact; the sum rounds twice).
  7651. "v_fma_f16" | "v_fmac_f16" | "v_mad_f16" | "v_mac_f16" => self.fmad(a, b, acc),
  7652. "v_max3_f16" => {
  7653. let t = self.max_min(true, a, b);
  7654. self.max_min(true, t, acc)
  7655. }
  7656. "v_min3_f16" => {
  7657. let t = self.max_min(false, a, b);
  7658. self.max_min(false, t, acc)
  7659. }
  7660. _ => self.med3(a, b, acc),
  7661. };
  7662. return float_result(self, r);
  7663. }
  7664. if float1.contains(&name) {
  7665. let r = match name {
  7666. "v_cvt_f16_u16" | "v_cvt_f16_i16" => {
  7667. let mut x = self.half_src(inst, 0)?;
  7668. let op = if name == "v_cvt_f16_i16" {
  7669. let k16 = self.s.m.i32(16);
  7670. let t = self.s.m.bin(c, Bin::Shl, x, k16);
  7671. x = self.s.m.bin(c, Bin::AShr, t, k16);
  7672. Cast::SiToFp
  7673. } else {
  7674. Cast::UiToFp
  7675. };
  7676. self.s.m.cast(c, op, x, f32t)
  7677. }
  7678. "v_rcp_f16" => {
  7679. let a = self.half_fsrc(inst, 0)?;
  7680. let one = self.s.m.f32(1.0f32.to_bits());
  7681. self.s.m.bin(c, Bin::SDiv, one, a)
  7682. }
  7683. _ => {
  7684. let a = self.half_fsrc(inst, 0)?;
  7685. let op = match name {
  7686. "v_sqrt_f16" => 24,
  7687. "v_rsq_f16" => 25,
  7688. "v_log_f16" => 23,
  7689. "v_exp_f16" => 21,
  7690. "v_fract_f16" => 22,
  7691. "v_trunc_f16" => 29,
  7692. "v_floor_f16" => 27,
  7693. "v_ceil_f16" => 28,
  7694. "v_rndne_f16" => 26,
  7695. "v_sin_f16" => 13,
  7696. _ => 12,
  7697. };
  7698. match op {
  7699. 12 | 13 => self.trig_turns(a, op == 12),
  7700. // Any f16 in (-2^-11, 0) has fract >= 1 - 2^-12; clamp to 0x3bff (1 - 2^-11).
  7701. 22 => self.fract(a, 1.0 - 1.0 / 4096.0, 1.0 - 1.0 / 2048.0),
  7702. _ => self.unary(op, a),
  7703. }
  7704. }
  7705. };
  7706. return float_result(self, r);
  7707. }
  7708. if matches!(name, "v_cvt_u16_f16" | "v_cvt_i16_f16") {
  7709. if v.clamp || v.omod != 0 {
  7710. return Err("modifiers on a 16-bit integer operation");
  7711. }
  7712. // Toward zero, saturating at the 16-bit range (infinities
  7713. // included); NaN gives 0. Clamped in f32 first, where every
  7714. // f16 is exact, so the conversion never leaves i32's range
  7715. // (upstream PR #384's arithmetic; the source's abs and neg
  7716. // modifiers are applied by `half_fsrc`, as before).
  7717. let a = self.half_fsrc(inst, 0)?;
  7718. let (lo, hi) = if name == "v_cvt_u16_f16" {
  7719. (0.0f32, 65535.0f32)
  7720. } else {
  7721. (-32768.0, 32767.0)
  7722. };
  7723. let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits()));
  7724. let t = self.binary(35, a, lo);
  7725. let t = self.binary(36, t, hi);
  7726. let r = self.s.m.cast(c, Cast::FpToSi, t, i32t);
  7727. let nan = self.s.m.cmp(c, pred::UNO, a, a);
  7728. let z = self.s.m.i32(0);
  7729. let r = self.s.m.select(c, nan, z, r);
  7730. return self.write_half(inst, r, guard);
  7731. }
  7732. if matches!(name, "v_cvt_norm_i16_f16" | "v_cvt_norm_u16_f16") {
  7733. if v.clamp || v.omod != 0 {
  7734. return Err("modifiers on a 16-bit integer operation");
  7735. }
  7736. let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?;
  7737. return self.write_half(inst, r, guard);
  7738. }
  7739. // 16-bit integers: computed on the low halves, the low 16 bits kept.
  7740. if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 {
  7741. return Err("modifiers on a 16-bit integer operation");
  7742. }
  7743. let r = {
  7744. let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
  7745. let k16 = self.s.m.i32(16);
  7746. let sext = |l: &mut Self, x: V| {
  7747. let t = l.s.m.bin(c, Bin::Shl, x, k16);
  7748. l.s.m.bin(c, Bin::AShr, t, k16)
  7749. };
  7750. if name.ends_with("_i16") {
  7751. a = sext(self, a);
  7752. b = sext(self, b);
  7753. }
  7754. let k15 = self.s.m.i32(15);
  7755. match name {
  7756. "v_add_nc_u16" => self.s.m.bin(c, Bin::Add, a, b),
  7757. "v_sub_nc_u16" => self.s.m.bin(c, Bin::Sub, a, b),
  7758. "v_subrev_nc_u16" => self.s.m.bin(c, Bin::Sub, b, a),
  7759. "v_mul_lo_u16" => self.s.m.bin(c, Bin::Mul, a, b),
  7760. "v_lshlrev_b16" | "v_lshrrev_b16" | "v_ashrrev_i16" => {
  7761. // src0 is the shift (4 bits), src1 the value.
  7762. let sh = self.s.m.bin(c, Bin::And, a, k15);
  7763. let x = if name == "v_ashrrev_i16" {
  7764. sext(self, b)
  7765. } else {
  7766. b
  7767. };
  7768. let op = match name {
  7769. "v_lshlrev_b16" => Bin::Shl,
  7770. "v_lshrrev_b16" => Bin::LShr,
  7771. _ => Bin::AShr,
  7772. };
  7773. self.s.m.bin(c, op, x, sh)
  7774. }
  7775. _ => {
  7776. let p = match name {
  7777. "v_max_u16" => pred::IUGT,
  7778. "v_min_u16" => pred::IULT,
  7779. "v_max_i16" => pred::SGT,
  7780. _ => pred::SLT,
  7781. };
  7782. let t = self.s.m.cmp(c, p, a, b);
  7783. self.s.m.select(c, t, a, b)
  7784. }
  7785. }
  7786. };
  7787. self.write_half(inst, r, guard)
  7788. }
  7789. /// `v_cvt_norm_i16_f16` / `v_cvt_norm_u16_f16`: the f16 source (with its
  7790. /// abs/neg modifiers) clamped to [-1, 1] or [0, 1], times 32767 or 65535,
  7791. /// rounded to nearest even once from the exact product; NaN gives 0.
  7792. /// Worked on the f16's bits in integers, because in f32 the product
  7793. /// (up to 26 significant bits) would round before the rounding to an
  7794. /// integer.
  7795. fn cvt_norm16(&mut self, inst: &Inst, signed: bool) -> Result<V, Why> {
  7796. let Fields::Valu(v) = &inst.fields else {
  7797. unreachable!()
  7798. };
  7799. let c = self.cur;
  7800. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  7801. let mut h = self.half_src(inst, 0)?;
  7802. if v.abs & 1 != 0 {
  7803. let m = k(self, 0x7FFF);
  7804. h = self.s.m.bin(c, Bin::And, h, m);
  7805. }
  7806. if v.neg & 1 != 0 {
  7807. let m = k(self, 0x8000);
  7808. h = self.s.m.bin(c, Bin::Xor, h, m);
  7809. }
  7810. let scale = if signed { 0x7FFF } else { 0xFFFF };
  7811. let (k0, k1, k10) = (k(self, 0), k(self, 1), k(self, 10));
  7812. let mag_mask = k(self, 0x7FFF);
  7813. let mag = self.s.m.bin(c, Bin::And, h, mag_mask);
  7814. let k15 = k(self, 15);
  7815. let neg = self.s.m.bin(c, Bin::LShr, h, k15);
  7816. let neg = self.s.m.cmp(c, pred::NE, neg, k0);
  7817. // |x| < 1: x = m * 2^-s with m < 2^11 and 11 <= s <= 24.
  7818. let exp = self.s.m.bin(c, Bin::LShr, mag, k10);
  7819. let man_mask = k(self, 0x3FF);
  7820. let man = self.s.m.bin(c, Bin::And, mag, man_mask);
  7821. let implicit = k(self, 0x400);
  7822. let normal = self.s.m.bin(c, Bin::Or, man, implicit);
  7823. let sub = self.s.m.cmp(c, pred::EQ, exp, k0);
  7824. let m = self.s.m.select(c, sub, man, normal);
  7825. let k25 = k(self, 25);
  7826. let s_norm = self.s.m.bin(c, Bin::Sub, k25, exp);
  7827. let k24 = k(self, 24);
  7828. let sh = self.s.m.select(c, sub, k24, s_norm);
  7829. let ks = k(self, scale);
  7830. let p = self.s.m.bin(c, Bin::Mul, m, ks);
  7831. let q = self.s.m.bin(c, Bin::LShr, p, sh);
  7832. let one_s = self.s.m.bin(c, Bin::Shl, k1, sh);
  7833. let low_mask = self.s.m.bin(c, Bin::Sub, one_s, k1);
  7834. let rem = self.s.m.bin(c, Bin::And, p, low_mask);
  7835. let half = self.s.m.bin(c, Bin::LShr, one_s, k1);
  7836. let above = self.s.m.cmp(c, pred::IUGT, rem, half);
  7837. let tie = self.s.m.cmp(c, pred::EQ, rem, half);
  7838. let odd = self.s.m.bin(c, Bin::And, q, k1);
  7839. let odd = self.s.m.cmp(c, pred::NE, odd, k0);
  7840. let tie_up = self.s.m.bin(c, Bin::And, tie, odd);
  7841. let up = self.s.m.bin(c, Bin::Or, above, tie_up);
  7842. let r = self.s.m.select(c, up, k1, k0);
  7843. let r = self.s.m.bin(c, Bin::Add, q, r);
  7844. // |x| >= 1 (and infinity) saturates; NaN gives 0.
  7845. let one_h = k(self, 0x3C00);
  7846. let big = self.s.m.cmp(c, pred::IUGE, mag, one_h);
  7847. let r = self.s.m.select(c, big, ks, r);
  7848. let inf = k(self, 0x7C00);
  7849. let nan = self.s.m.cmp(c, pred::IUGT, mag, inf);
  7850. let r = self.s.m.select(c, nan, k0, r);
  7851. let r = if signed {
  7852. let n = self.s.m.bin(c, Bin::Sub, k0, r);
  7853. self.s.m.select(c, neg, n, r)
  7854. } else {
  7855. self.s.m.select(c, neg, k0, r)
  7856. };
  7857. let m16 = k(self, 0xFFFF);
  7858. Ok(self.s.m.bin(c, Bin::And, r, m16))
  7859. }
  7860. /// Half `high` of source `k` of a packed (VOP3P) operation, in the low
  7861. /// 16 bits: op_sel picks the half the low result reads, op_sel_hi the
  7862. /// half the high result reads. Packed integer instructions see the f32
  7863. /// bits of an inline float constant.
  7864. fn packed_src(&mut self, inst: &Inst, k: usize, high: bool, float: bool) -> Result<V, Why> {
  7865. let Fields::Valu(v) = &inst.fields else {
  7866. unreachable!()
  7867. };
  7868. let op = *v.src.get(k).ok_or("a missing operand")?;
  7869. let sel = if high { v.opsel_hi } else { v.opsel } >> k & 1 != 0;
  7870. let x = if float {
  7871. self.f16_operand(inst, &op)?
  7872. } else {
  7873. self.operand(inst, &op)?
  7874. };
  7875. let c = self.cur;
  7876. let x = if sel {
  7877. let k16 = self.s.m.i32(16);
  7878. self.s.m.bin(c, Bin::LShr, x, k16)
  7879. } else {
  7880. x
  7881. };
  7882. let m = self.s.m.i32(0xFFFF);
  7883. Ok(self.s.m.bin(c, Bin::And, x, m))
  7884. }
  7885. /// Packed 16-bit operations (`v_pk_*`): each half computed as the
  7886. /// 16-bit operation does, f16 through f32 as in [`Self::valu16`].
  7887. fn packed16(&mut self, inst: &Inst, op: &str, guard: Option<V>) -> Result<(), Why> {
  7888. let Fields::Valu(v) = &inst.fields else {
  7889. unreachable!()
  7890. };
  7891. let float = op.ends_with("_f16");
  7892. let n = match op {
  7893. "fma_f16" | "mad_u16" | "mad_i16" => 3,
  7894. "add_f16" | "mul_f16" | "min_f16" | "max_f16" | "add_u16" | "sub_u16" | "add_i16"
  7895. | "sub_i16" | "mul_lo_u16" | "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16"
  7896. | "max_u16" | "min_u16" | "max_i16" | "min_i16" => 2,
  7897. _ => return Err("a packed 16-bit operation"),
  7898. };
  7899. if v.omod != 0 || !float && (v.clamp || v.neg != 0 || v.neg_hi != 0) {
  7900. return Err("modifiers on a packed integer operation");
  7901. }
  7902. let c = self.cur;
  7903. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  7904. let mut halves = Vec::new();
  7905. for high in [false, true] {
  7906. let mut xs = Vec::new();
  7907. for k in 0..n {
  7908. let h = self.packed_src(inst, k, high, float)?;
  7909. if float {
  7910. let mut f = self
  7911. .s
  7912. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  7913. let neg = if high { v.neg_hi } else { v.neg };
  7914. if neg >> k & 1 != 0 {
  7915. let z = self.s.m.f32(0x8000_0000);
  7916. f = self.s.m.bin(c, Bin::Sub, z, f);
  7917. }
  7918. xs.push(f);
  7919. } else {
  7920. xs.push(h);
  7921. }
  7922. }
  7923. let r = if float {
  7924. let mut f = match op {
  7925. "add_f16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
  7926. "mul_f16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
  7927. "min_f16" => self.max_min(false, xs[0], xs[1]),
  7928. "max_f16" => self.max_min(true, xs[0], xs[1]),
  7929. // shortcut: FMad in f32, as v_fma_f16.
  7930. _ => self.fmad(xs[0], xs[1], xs[2]),
  7931. };
  7932. if v.clamp {
  7933. f = self.unary(7, f);
  7934. }
  7935. self.s
  7936. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  7937. } else {
  7938. let k16 = self.s.m.i32(16);
  7939. let sext = |l: &mut Self, x: V| {
  7940. let t = l.s.m.bin(c, Bin::Shl, x, k16);
  7941. l.s.m.bin(c, Bin::AShr, t, k16)
  7942. };
  7943. if op.ends_with("_i16") {
  7944. for x in &mut xs {
  7945. *x = sext(self, *x);
  7946. }
  7947. }
  7948. let k15 = self.s.m.i32(15);
  7949. match op {
  7950. "add_u16" | "add_i16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
  7951. "sub_u16" | "sub_i16" => self.s.m.bin(c, Bin::Sub, xs[0], xs[1]),
  7952. "mul_lo_u16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
  7953. "mad_u16" | "mad_i16" => {
  7954. let m = self.s.m.bin(c, Bin::Mul, xs[0], xs[1]);
  7955. self.s.m.bin(c, Bin::Add, m, xs[2])
  7956. }
  7957. "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16" => {
  7958. let sh = self.s.m.bin(c, Bin::And, xs[0], k15);
  7959. let o = match op {
  7960. "lshlrev_b16" => Bin::Shl,
  7961. "lshrrev_b16" => Bin::LShr,
  7962. _ => Bin::AShr,
  7963. };
  7964. let x = if op == "ashrrev_i16" {
  7965. sext(self, xs[1])
  7966. } else {
  7967. xs[1]
  7968. };
  7969. self.s.m.bin(c, o, x, sh)
  7970. }
  7971. _ => {
  7972. let p = match op {
  7973. "max_u16" => pred::IUGT,
  7974. "min_u16" => pred::IULT,
  7975. "max_i16" => pred::SGT,
  7976. _ => pred::SLT,
  7977. };
  7978. let t = self.s.m.cmp(c, p, xs[0], xs[1]);
  7979. self.s.m.select(c, t, xs[0], xs[1])
  7980. }
  7981. }
  7982. };
  7983. let m = self.s.m.i32(0xFFFF);
  7984. halves.push(self.s.m.bin(c, Bin::And, r, m));
  7985. }
  7986. let k16 = self.s.m.i32(16);
  7987. let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16);
  7988. let r = self.s.m.bin(c, Bin::Or, halves[0], hi);
  7989. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7990. return Err("a packed result outside a VGPR");
  7991. };
  7992. self.write(inst, Reg::V(reg), r, guard);
  7993. Ok(())
  7994. }
  7995. fn integer(&mut self, inst: &Inst, name: &'static str) -> Result<V, Why> {
  7996. let c = self.cur;
  7997. let s = |l: &mut Self, k| l.src(inst, k);
  7998. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  7999. let m31 = |l: &mut Self, x: V| {
  8000. let k31 = l.s.m.i32(31);
  8001. l.s.m.bin(c, Bin::And, x, k31)
  8002. };
  8003. Ok(match name {
  8004. "v_and_b32" | "v_or_b32" | "v_xor_b32" | "v_add_nc_u32" | "v_sub_nc_u32"
  8005. | "v_subrev_nc_u32" | "v_mul_lo_u32" => {
  8006. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8007. let (op, a, b) = match name {
  8008. "v_and_b32" => (Bin::And, a, b),
  8009. "v_or_b32" => (Bin::Or, a, b),
  8010. "v_xor_b32" => (Bin::Xor, a, b),
  8011. "v_add_nc_u32" => (Bin::Add, a, b),
  8012. "v_sub_nc_u32" => (Bin::Sub, a, b),
  8013. "v_subrev_nc_u32" => (Bin::Sub, b, a),
  8014. _ => (Bin::Mul, a, b),
  8015. };
  8016. self.s.m.bin(c, op, a, b)
  8017. }
  8018. "v_xnor_b32" => {
  8019. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8020. let x = self.s.m.bin(c, Bin::Xor, a, b);
  8021. let ones = k(self, u32::MAX);
  8022. self.s.m.bin(c, Bin::Xor, x, ones)
  8023. }
  8024. "v_not_b32" => {
  8025. let a = s(self, 0)?;
  8026. let ones = k(self, u32::MAX);
  8027. self.s.m.bin(c, Bin::Xor, a, ones)
  8028. }
  8029. "v_lshlrev_b32" | "v_lshrrev_b32" | "v_ashrrev_i32" => {
  8030. let (sh, a) = (s(self, 0)?, s(self, 1)?);
  8031. let sh = m31(self, sh);
  8032. let op = match name {
  8033. "v_lshlrev_b32" => Bin::Shl,
  8034. "v_lshrrev_b32" => Bin::LShr,
  8035. _ => Bin::AShr,
  8036. };
  8037. self.s.m.bin(c, op, a, sh)
  8038. }
  8039. "v_lshl_add_u32" | "v_lshl_or_b32" | "v_add_lshl_u32" | "v_and_or_b32"
  8040. | "v_or3_b32" | "v_xad_u32" | "v_add3_u32" | "v_xor3_b32" => {
  8041. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8042. match name {
  8043. "v_lshl_add_u32" | "v_lshl_or_b32" => {
  8044. let b = m31(self, b);
  8045. let t = self.s.m.bin(c, Bin::Shl, a, b);
  8046. let op = if name == "v_lshl_add_u32" {
  8047. Bin::Add
  8048. } else {
  8049. Bin::Or
  8050. };
  8051. self.s.m.bin(c, op, t, d)
  8052. }
  8053. "v_add_lshl_u32" => {
  8054. let t = self.s.m.bin(c, Bin::Add, a, b);
  8055. let d = m31(self, d);
  8056. self.s.m.bin(c, Bin::Shl, t, d)
  8057. }
  8058. _ => {
  8059. let (o1, o2) = match name {
  8060. "v_and_or_b32" => (Bin::And, Bin::Or),
  8061. "v_or3_b32" => (Bin::Or, Bin::Or),
  8062. "v_xad_u32" => (Bin::Xor, Bin::Add),
  8063. "v_add3_u32" => (Bin::Add, Bin::Add),
  8064. _ => (Bin::Xor, Bin::Xor),
  8065. };
  8066. let t = self.s.m.bin(c, o1, a, b);
  8067. self.s.m.bin(c, o2, t, d)
  8068. }
  8069. }
  8070. }
  8071. "v_mul_u32_u24" | "v_mul_i32_i24" => {
  8072. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8073. let (sh, op) = (
  8074. k(self, 8),
  8075. if name == "v_mul_i32_i24" {
  8076. Bin::AShr
  8077. } else {
  8078. Bin::LShr
  8079. },
  8080. );
  8081. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  8082. let a = self.s.m.bin(c, op, a, sh);
  8083. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  8084. let b = self.s.m.bin(c, op, b, sh);
  8085. self.s.m.bin(c, Bin::Mul, a, b)
  8086. }
  8087. "v_bfe_u32" | "v_bfe_i32" => {
  8088. let (a, off, w) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8089. let w = m31(self, w);
  8090. self.bfe(a, off, w, name == "v_bfe_i32")
  8091. }
  8092. "v_bfi_b32" => {
  8093. let (m, a, b) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8094. let ones = k(self, u32::MAX);
  8095. let nm = self.s.m.bin(c, Bin::Xor, m, ones);
  8096. let x = self.s.m.bin(c, Bin::And, m, a);
  8097. let y = self.s.m.bin(c, Bin::And, nm, b);
  8098. self.s.m.bin(c, Bin::Or, x, y)
  8099. }
  8100. "v_max_i32" | "v_min_i32" | "v_max_u32" | "v_min_u32" => {
  8101. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8102. let p = match name {
  8103. "v_max_i32" => pred::SGT,
  8104. "v_min_i32" => pred::SLT,
  8105. "v_max_u32" => pred::IUGT,
  8106. _ => pred::IULT,
  8107. };
  8108. let t = self.s.m.cmp(c, p, a, b);
  8109. self.s.m.select(c, t, a, b)
  8110. }
  8111. "v_mul_hi_u32" | "v_mul_hi_i32" => {
  8112. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8113. self.mul_hi(a, b, name == "v_mul_hi_i32")
  8114. }
  8115. "v_alignbit_b32" | "v_alignbyte_b32" => {
  8116. // The low dword of {a, b} >> shift.
  8117. let (a, b, sh) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8118. let sh = if name == "v_alignbyte_b32" {
  8119. let three = k(self, 3);
  8120. let t = self.s.m.bin(c, Bin::And, sh, three);
  8121. let k3 = k(self, 3);
  8122. self.s.m.bin(c, Bin::Shl, t, k3)
  8123. } else {
  8124. m31(self, sh)
  8125. };
  8126. let k32 = k(self, 32);
  8127. let lo = self.s.m.bin(c, Bin::LShr, b, sh);
  8128. let left = self.s.m.bin(c, Bin::Sub, k32, sh);
  8129. let left = m31(self, left);
  8130. let hi = self.s.m.bin(c, Bin::Shl, a, left);
  8131. let zero = k(self, 0);
  8132. let none = self.s.m.cmp(c, pred::EQ, sh, zero);
  8133. let hi = self.s.m.select(c, none, zero, hi);
  8134. self.s.m.bin(c, Bin::Or, lo, hi)
  8135. }
  8136. "v_bfrev_b32" => {
  8137. let a = s(self, 0)?;
  8138. self.s
  8139. .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a])
  8140. }
  8141. "v_bcnt_u32_b32" => {
  8142. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8143. let n = self
  8144. .s
  8145. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[a]);
  8146. self.s.m.bin(c, Bin::Add, n, b)
  8147. }
  8148. "v_mad_u32_u24" | "v_mad_i32_i24" => {
  8149. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8150. let (sh, op) = (
  8151. k(self, 8),
  8152. if name == "v_mad_i32_i24" {
  8153. Bin::AShr
  8154. } else {
  8155. Bin::LShr
  8156. },
  8157. );
  8158. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  8159. let a = self.s.m.bin(c, op, a, sh);
  8160. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  8161. let b = self.s.m.bin(c, op, b, sh);
  8162. let m = self.s.m.bin(c, Bin::Mul, a, b);
  8163. self.s.m.bin(c, Bin::Add, m, d)
  8164. }
  8165. "v_min3_i32" | "v_max3_i32" | "v_min3_u32" | "v_max3_u32" | "v_med3_i32"
  8166. | "v_med3_u32" => {
  8167. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8168. let signed = name.ends_with("i32");
  8169. let (lt, gt) = if signed {
  8170. (pred::SLT, pred::SGT)
  8171. } else {
  8172. (pred::IULT, pred::IUGT)
  8173. };
  8174. let pick = |l: &mut Self, p, x, y| {
  8175. let t = l.s.m.cmp(c, p, x, y);
  8176. l.s.m.select(c, t, x, y)
  8177. };
  8178. match &name[2..6] {
  8179. "min3" => {
  8180. let t = pick(self, lt, a, b);
  8181. pick(self, lt, t, d)
  8182. }
  8183. "max3" => {
  8184. let t = pick(self, gt, a, b);
  8185. pick(self, gt, t, d)
  8186. }
  8187. _ => {
  8188. let lo = pick(self, lt, a, b);
  8189. let hi = pick(self, gt, a, b);
  8190. let t = pick(self, lt, hi, d);
  8191. pick(self, gt, lo, t)
  8192. }
  8193. }
  8194. }
  8195. "v_perm_b32" => {
  8196. // Byte i of the result is byte S of {src0, src1} (src1 the
  8197. // low dword) for selector byte S below 8; 8-11 repeat the
  8198. // sign of bytes 1 and 3 of src1, then of src0; 12 is 0x00,
  8199. // higher 0xFF.
  8200. let Fields::Valu(v) = &inst.fields else {
  8201. unreachable!()
  8202. };
  8203. let sel = match v.src.get(2) {
  8204. Some(&Operand::Literal(x)) => x,
  8205. Some(&Operand::Const(k)) => crate::resource::inline(k).ok_or(name)?,
  8206. _ => {
  8207. // A computed selector: each byte picked at run time.
  8208. let (a, b, sv) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8209. let mut r = k(self, 0);
  8210. for i in 0..4u32 {
  8211. let (sh, ff) = (k(self, 8 * i), k(self, 0xFF));
  8212. let sel = self.s.m.bin(c, Bin::LShr, sv, sh);
  8213. let sel = self.s.m.bin(c, Bin::And, sel, ff);
  8214. // Select a dword and a byte within it.
  8215. // Later selects handle codes 8 and above.
  8216. let four = k(self, 4);
  8217. let zero = k(self, 0);
  8218. let high = self.s.m.bin(c, Bin::And, sel, four);
  8219. let high = self.s.m.cmp(c, pred::NE, high, zero);
  8220. let word = self.s.m.select(c, high, a, b);
  8221. let three = k(self, 3);
  8222. let index = self.s.m.bin(c, Bin::And, sel, three);
  8223. let bits = self.s.m.bin(c, Bin::Shl, index, three);
  8224. let x = self.s.m.bin(c, Bin::LShr, word, bits);
  8225. let mut byte = self.s.m.bin(c, Bin::And, x, ff);
  8226. // 8-11: the sign of bytes 1, 3 of src1, then of src0.
  8227. for (n, src, bit) in [(8, b, 15), (9, b, 31), (10, a, 15), (11, a, 31)]
  8228. {
  8229. let left = k(self, 31 - bit);
  8230. let t = self.s.m.bin(c, Bin::Shl, src, left);
  8231. let k31 = k(self, 31);
  8232. let t = self.s.m.bin(c, Bin::AShr, t, k31);
  8233. let t = self.s.m.bin(c, Bin::And, t, ff);
  8234. let kn = k(self, n);
  8235. let is = self.s.m.cmp(c, pred::EQ, sel, kn);
  8236. byte = self.s.m.select(c, is, t, byte);
  8237. }
  8238. let (k12, z) = (k(self, 12), k(self, 0));
  8239. let is12 = self.s.m.cmp(c, pred::EQ, sel, k12);
  8240. byte = self.s.m.select(c, is12, z, byte);
  8241. let above = self.s.m.cmp(c, pred::IUGT, sel, k12);
  8242. byte = self.s.m.select(c, above, ff, byte);
  8243. let at = k(self, 8 * i);
  8244. let byte = self.s.m.bin(c, Bin::Shl, byte, at);
  8245. r = self.s.m.bin(c, Bin::Or, r, byte);
  8246. }
  8247. return Ok(r);
  8248. }
  8249. };
  8250. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8251. let mut r = k(self, 0);
  8252. for i in 0..4 {
  8253. let pick = sel >> (8 * i) & 0xFF;
  8254. let byte = match pick {
  8255. 0..=7 => {
  8256. let (src, n) = if pick < 4 { (b, pick) } else { (a, pick - 4) };
  8257. let sh = k(self, 8 * n);
  8258. let t = self.s.m.bin(c, Bin::LShr, src, sh);
  8259. let ff = k(self, 0xFF);
  8260. self.s.m.bin(c, Bin::And, t, ff)
  8261. }
  8262. 8..=11 => {
  8263. let src = if pick < 10 { b } else { a };
  8264. let bit = if pick % 2 == 0 { 15 } else { 31 };
  8265. let left = k(self, 31 - bit);
  8266. let t = self.s.m.bin(c, Bin::Shl, src, left);
  8267. let k31 = k(self, 31);
  8268. let t = self.s.m.bin(c, Bin::AShr, t, k31);
  8269. let ff = k(self, 0xFF);
  8270. self.s.m.bin(c, Bin::And, t, ff)
  8271. }
  8272. 12 => continue,
  8273. _ => k(self, 0xFF),
  8274. };
  8275. let at = k(self, 8 * i);
  8276. let byte = self.s.m.bin(c, Bin::Shl, byte, at);
  8277. r = self.s.m.bin(c, Bin::Or, r, byte);
  8278. }
  8279. r
  8280. }
  8281. "v_bfm_b32" => {
  8282. // ((1 << src0[4:0]) - 1) << src1[4:0]
  8283. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8284. let one = k(self, 1);
  8285. let (a, b) = (m31(self, a), m31(self, b));
  8286. let m = self.s.m.bin(c, Bin::Shl, one, a);
  8287. let m = self.s.m.bin(c, Bin::Sub, m, one);
  8288. self.s.m.bin(c, Bin::Shl, m, b)
  8289. }
  8290. "v_cvt_pk_u8_f32" => {
  8291. // src0 rounded to nearest even and saturated to a byte, into
  8292. // byte src1[1:0] of src2.
  8293. let f = self.fsrc(inst, 0)?;
  8294. let (b, d) = (s(self, 1)?, s(self, 2)?);
  8295. let f = self.unary(26, f);
  8296. let (zero, max) = (self.s.m.f32(0), self.s.m.f32(255.0f32.to_bits()));
  8297. let f = self.binary(35, f, zero);
  8298. let f = self.binary(36, f, max);
  8299. let x = self.s.m.cast(c, Cast::FpToUi, f, self.s.t.i32);
  8300. let (three, k3) = (k(self, 3), k(self, 3));
  8301. let sh = self.s.m.bin(c, Bin::And, b, three);
  8302. let sh = self.s.m.bin(c, Bin::Shl, sh, k3);
  8303. let x = self.s.m.bin(c, Bin::Shl, x, sh);
  8304. let ff = k(self, 0xFF);
  8305. let hole = self.s.m.bin(c, Bin::Shl, ff, sh);
  8306. let ones = k(self, u32::MAX);
  8307. let hole = self.s.m.bin(c, Bin::Xor, hole, ones);
  8308. let d = self.s.m.bin(c, Bin::And, d, hole);
  8309. self.s.m.bin(c, Bin::Or, d, x)
  8310. }
  8311. "v_ffbl_b32" => {
  8312. // -1 for zero, as DXIL's first-bit-low.
  8313. let a = s(self, 0)?;
  8314. self.s
  8315. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 32, &[a])
  8316. }
  8317. "v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32" => {
  8318. // Bits of the mask's low (high) half below this lane, plus src1:
  8319. // with an all-ones mask, the lane index.
  8320. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8321. // Mesh lanes are the console's by construction; pixel and
  8322. // vertex lanes are the host's, as their masks are.
  8323. if self.mask_data == MaskData::Host {
  8324. // Host lanes: the mask must be one (a ballot) or all lanes.
  8325. let Fields::Valu(v) = &inst.fields else {
  8326. unreachable!()
  8327. };
  8328. let host = match v.src.first() {
  8329. Some(&Operand::Const(193)) => true,
  8330. Some(&Operand::Scalar { code, .. }) => {
  8331. inst.read(Reg::S(code)).is_some_and(|m| {
  8332. self.x.st.masks.contains_key(&m) || self.x.st.highs.contains_key(&m)
  8333. })
  8334. }
  8335. _ => false,
  8336. };
  8337. if !host {
  8338. return Err("v_mbcnt of a mask that is no ballot (console lane layout)");
  8339. }
  8340. self.s.flags |= flags::WAVE_OPS;
  8341. } else if self.s.mesh.is_none() {
  8342. self.cross_lane(false)?;
  8343. }
  8344. let lane = self.console_lane();
  8345. let below = if name == "v_mbcnt_lo_u32_b32" {
  8346. lane
  8347. } else {
  8348. let (k32, z) = (k(self, 32), k(self, 0));
  8349. let t = self.s.m.bin(c, Bin::Sub, lane, k32);
  8350. let low = self.s.m.cmp(c, pred::IULT, lane, k32);
  8351. self.s.m.select(c, low, z, t)
  8352. };
  8353. // (1 << below) - 1, all ones from 32 on.
  8354. let (one, k32, ones) = (k(self, 1), k(self, 32), k(self, u32::MAX));
  8355. let sh = m31(self, below);
  8356. let m = self.s.m.bin(c, Bin::Shl, one, sh);
  8357. let m = self.s.m.bin(c, Bin::Sub, m, one);
  8358. let full = self.s.m.cmp(c, pred::IUGE, below, k32);
  8359. let m = self.s.m.select(c, full, ones, m);
  8360. let x = self.s.m.bin(c, Bin::And, a, m);
  8361. let n = self
  8362. .s
  8363. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[x]);
  8364. self.s.m.bin(c, Bin::Add, n, b)
  8365. }
  8366. _ => return Err(name),
  8367. })
  8368. }
  8369. fn compare(&mut self, inst: &Inst, rest: &str) -> Result<(), Why> {
  8370. let (op, ty) = rest.rsplit_once('_').ok_or("a compare")?;
  8371. let c = self.cur;
  8372. let r = match ty {
  8373. "f32" | "f16" if op == "class" => {
  8374. // Bit k of src1 tests class k: signalling NaN, quiet NaN,
  8375. // -inf, -normal, -denormal, -0, +0, +denormal, +normal, +inf.
  8376. let f16 = ty == "f16";
  8377. let x = if f16 {
  8378. let Fields::Valu(v) = &inst.fields else {
  8379. unreachable!()
  8380. };
  8381. let mut h = self.half_src(inst, 0)?;
  8382. if v.abs & 1 != 0 {
  8383. let m = self.s.m.i32(0x7FFF);
  8384. h = self.s.m.bin(c, Bin::And, h, m);
  8385. }
  8386. if v.neg & 1 != 0 {
  8387. let s = self.s.m.i32(0x8000);
  8388. h = self.s.m.bin(c, Bin::Xor, h, s);
  8389. }
  8390. h
  8391. } else {
  8392. let x = self.fsrc(inst, 0)?;
  8393. self.as_int(x)
  8394. };
  8395. let mask = self.src(inst, 1)?;
  8396. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  8397. let (exp_sh, sign_sh, exp_mask, mant_mask, quiet_bit) = if f16 {
  8398. (10, 15, 0x1F, 0x03FF, 0x0200)
  8399. } else {
  8400. (23, 31, 0xFF, 0x7F_FFFF, 0x40_0000)
  8401. };
  8402. let (k_exp, k_sign, k_emax, mant, quiet) = (
  8403. k(self, exp_sh),
  8404. k(self, sign_sh),
  8405. k(self, exp_mask),
  8406. k(self, mant_mask),
  8407. k(self, quiet_bit),
  8408. );
  8409. let e = self.s.m.bin(c, Bin::LShr, x, k_exp);
  8410. let e = self.s.m.bin(c, Bin::And, e, k_emax);
  8411. let m = self.s.m.bin(c, Bin::And, x, mant);
  8412. let neg = self.s.m.bin(c, Bin::LShr, x, k_sign);
  8413. let zero = k(self, 0);
  8414. let (e0, emax) = (
  8415. self.s.m.cmp(c, pred::EQ, e, zero),
  8416. self.s.m.cmp(c, pred::EQ, e, k_emax),
  8417. );
  8418. let m0 = self.s.m.cmp(c, pred::EQ, m, zero);
  8419. let q = self.s.m.bin(c, Bin::And, x, quiet);
  8420. let q = self.s.m.cmp(c, pred::NE, q, zero);
  8421. // Positive classes 6-9; negative ones are 11 minus those.
  8422. let (normal, inf, zero_c, denorm) =
  8423. (k(self, 8), k(self, 9), k(self, 6), k(self, 7));
  8424. let t = self.s.m.select(c, m0, zero_c, denorm);
  8425. let t = self.s.m.select(c, e0, t, normal);
  8426. let t = self.s.m.select(c, emax, inf, t);
  8427. let eleven = k(self, 11);
  8428. let mirrored = self.s.m.bin(c, Bin::Sub, eleven, t);
  8429. let is_neg = self.s.m.cmp(c, pred::NE, neg, zero);
  8430. let t = self.s.m.select(c, is_neg, mirrored, t);
  8431. let (one, snan) = (k(self, 1), k(self, 0));
  8432. let nan_class = self.s.m.select(c, q, one, snan);
  8433. let yes = self.s.m.bool(true);
  8434. let nan = self.s.m.bin(c, Bin::Xor, m0, yes);
  8435. let nan = self.s.m.bin(c, Bin::And, nan, emax);
  8436. let t = self.s.m.select(c, nan, nan_class, t);
  8437. let bit = self.s.m.bin(c, Bin::LShr, mask, t);
  8438. let bit = self.s.m.bin(c, Bin::And, bit, one);
  8439. self.s.m.cmp(c, pred::NE, bit, zero)
  8440. }
  8441. "f32" | "f16" => {
  8442. let (a, b) = if ty == "f16" {
  8443. (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?)
  8444. } else {
  8445. (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?)
  8446. };
  8447. if op == "lg" {
  8448. // Ordered and not equal, false for a NaN, as `olt | ogt`.
  8449. // `fcmp one` means the same, but the AMD D3D12 driver
  8450. // runs it as unordered (true for a NaN) where NVIDIA
  8451. // and WARP do not; olt and ogt agree on all three.
  8452. let lt = self.s.m.cmp(c, pred::OLT, a, b);
  8453. let gt = self.s.m.cmp(c, pred::OGT, a, b);
  8454. self.s.m.bin(c, Bin::Or, lt, gt)
  8455. } else {
  8456. let p = match op {
  8457. "f" => pred::FALSE,
  8458. "lt" => pred::OLT,
  8459. "eq" => pred::OEQ,
  8460. "le" => pred::OLE,
  8461. "gt" => pred::OGT,
  8462. "ge" => pred::OGE,
  8463. "o" => pred::ORD,
  8464. "u" => pred::UNO,
  8465. "nge" => pred::ULT,
  8466. "nlg" => pred::UEQ,
  8467. "ngt" => pred::ULE,
  8468. "nle" => pred::UGT,
  8469. "neq" => pred::UNE,
  8470. "nlt" => pred::UGE,
  8471. "tru" => pred::TRUE,
  8472. _ => return Err(inst.name()),
  8473. };
  8474. self.s.m.cmp(c, p, a, b)
  8475. }
  8476. }
  8477. "u64" | "i64" => {
  8478. let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?);
  8479. let signed = ty == "i64";
  8480. let p = match op {
  8481. "eq" => pred::EQ,
  8482. "ne" | "lg" => pred::NE,
  8483. "lt" if signed => pred::SLT,
  8484. "le" if signed => pred::SLE,
  8485. "gt" if signed => pred::SGT,
  8486. "ge" if signed => pred::SGE,
  8487. "lt" => pred::IULT,
  8488. "le" => pred::IULE,
  8489. "gt" => pred::IUGT,
  8490. "ge" => pred::IUGE,
  8491. _ => return Err("a 64-bit compare"),
  8492. };
  8493. self.s.m.cmp(c, p, a, b)
  8494. }
  8495. "u32" | "i32" | "u16" | "i16" => {
  8496. let (a, b) = if ty.ends_with("16") {
  8497. let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
  8498. if ty == "i16" {
  8499. let k16 = self.s.m.i32(16);
  8500. for x in [&mut a, &mut b] {
  8501. let t = self.s.m.bin(c, Bin::Shl, *x, k16);
  8502. *x = self.s.m.bin(c, Bin::AShr, t, k16);
  8503. }
  8504. }
  8505. (a, b)
  8506. } else {
  8507. (self.src(inst, 0)?, self.src(inst, 1)?)
  8508. };
  8509. let signed = ty == "i32" || ty == "i16";
  8510. let p = match op {
  8511. "eq" => pred::EQ,
  8512. "ne" | "lg" => pred::NE,
  8513. "lt" if signed => pred::SLT,
  8514. "le" if signed => pred::SLE,
  8515. "gt" if signed => pred::SGT,
  8516. "ge" if signed => pred::SGE,
  8517. "lt" => pred::IULT,
  8518. "le" => pred::IULE,
  8519. "gt" => pred::IUGT,
  8520. "ge" => pred::IUGE,
  8521. "f" | "t" => {
  8522. self.lane(inst, Some(op == "t"));
  8523. return Ok(());
  8524. }
  8525. _ => return Err("an integer compare"),
  8526. };
  8527. self.s.m.cmp(c, p, a, b)
  8528. }
  8529. _ => return Err(inst.name()),
  8530. };
  8531. self.lane_bits_for(inst, r);
  8532. Ok(())
  8533. }
  8534. fn lane(&mut self, inst: &Inst, value: Option<bool>) {
  8535. let b = self.s.m.bool(value == Some(true));
  8536. self.lane_bits_for(inst, b);
  8537. }
  8538. fn lane_bits_for(&mut self, inst: &Inst, r: V) {
  8539. let Fields::Valu(v) = &inst.fields else {
  8540. return;
  8541. };
  8542. let code = if inst.name().starts_with("v_cmpx") {
  8543. Some(EXEC)
  8544. } else {
  8545. match v.dst {
  8546. Some(Operand::Scalar { code, .. }) => Some(code),
  8547. _ => None,
  8548. }
  8549. };
  8550. if let Some(lo) = code.and_then(|c| inst.write(Reg::S(c))) {
  8551. self.lane_bits.insert(lo, r);
  8552. }
  8553. for &(_, w) in &inst.writes {
  8554. self.vals
  8555. .entry(w)
  8556. .or_insert(Val::Missing("a lane mask read as data"));
  8557. }
  8558. }
  8559. fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  8560. let Some(&interp) = self.interps.get(&site) else {
  8561. return Err("the first half of an interpolation");
  8562. };
  8563. let name = inst.name();
  8564. let (dst, src) = match &inst.fields {
  8565. Fields::Vintrp { dst, src, .. } => (*dst, Some(*src)),
  8566. Fields::Valu(v) => {
  8567. if v.abs != 0 || v.neg != 0 {
  8568. return Err("interpolation operand modifiers");
  8569. }
  8570. (v.dst.ok_or("an interpolation")?, v.src.get(1).copied())
  8571. }
  8572. _ => unreachable!(),
  8573. };
  8574. let Operand::Vector { reg, .. } = dst else {
  8575. return Err("an interpolation");
  8576. };
  8577. // A float operand of the instruction.
  8578. let float = |l: &mut Self, op: Option<Operand>| -> Result<V, Why> {
  8579. let x = l.operand(inst, &op.ok_or("an interpolation operand")?)?;
  8580. Ok(l.as_float(x))
  8581. };
  8582. // What the result adds to the evaluated channel (a second half's
  8583. // first half, when the halves evaluate on their own).
  8584. let mut add = None;
  8585. let (attribute, eval) = match *interp {
  8586. Interp::Interpolated {
  8587. attribute,
  8588. barycentric,
  8589. ..
  8590. } => {
  8591. let mode = interp_mode(barycentric).ok_or("pull-model interpolation")?;
  8592. let eval = if self.per_vertex(attribute.row) {
  8593. // The element is read per vertex elsewhere, so it is
  8594. // constant: weigh its vertices with SV_Barycentrics.
  8595. let mut ij = [None; 2];
  8596. for (index, w) in ij.iter_mut().enumerate() {
  8597. let x = match self.barycentric(barycentric, index as u8) {
  8598. Val::I32(x) => x,
  8599. Val::Missing(w) => return Err(w),
  8600. Val::Bit(_) => unreachable!(),
  8601. };
  8602. *w = Some(self.as_float(x));
  8603. }
  8604. Eval::Weights {
  8605. p0: true,
  8606. i: ij[0],
  8607. j: ij[1],
  8608. }
  8609. } else {
  8610. Eval::Mode(mode)
  8611. };
  8612. (attribute, eval)
  8613. }
  8614. // P0, the provoking vertex: a flat (nointerpolation) input.
  8615. Interp::Vertex {
  8616. attribute,
  8617. vertex: 2,
  8618. } => (attribute, Eval::Mode(1)),
  8619. // P10 and P20: what the first and second halves weigh, P1 - P0
  8620. // and P2 - P0, which is what the hardware holds for an
  8621. // attribute the program also interpolates.
  8622. Interp::Vertex { attribute, vertex } if self.interpolated(attribute.row) => {
  8623. let one = Some(self.s.m.f32(1f32.to_bits()));
  8624. let (i, j) = if vertex == 0 {
  8625. (one, None)
  8626. } else {
  8627. (None, one)
  8628. };
  8629. (attribute, Eval::Weights { p0: false, i, j })
  8630. }
  8631. Interp::Vertex { .. } => return Err("a non-provoking vertex value"),
  8632. // A half of an interpolation with computed i or j: P0 + i P10,
  8633. // or the old dst (f16: the third operand) + j P20.
  8634. Interp::Weighted { attribute } if name.starts_with("v_interp_p1") => {
  8635. let i = Some(float(self, src)?);
  8636. (
  8637. attribute,
  8638. Eval::Weights {
  8639. p0: true,
  8640. i,
  8641. j: None,
  8642. },
  8643. )
  8644. }
  8645. Interp::Weighted { attribute } => {
  8646. let old = match &inst.fields {
  8647. Fields::Valu(v) => v.src.get(2).copied(),
  8648. _ => Some(dst),
  8649. };
  8650. add = Some(float(self, old)?);
  8651. let j = Some(float(self, src)?);
  8652. (
  8653. attribute,
  8654. Eval::Weights {
  8655. p0: false,
  8656. i: None,
  8657. j,
  8658. },
  8659. )
  8660. }
  8661. };
  8662. let packing = match &self.x.native.io {
  8663. StageIo::Ps { inputs, .. } => inputs
  8664. .iter()
  8665. .find(|i| i.row == attribute.row && i.fp16)
  8666. .map(|i| {
  8667. let packs = if i.pack2 {
  8668. input_packs(&self.x.native.io, &self.s.inputs)
  8669. } else {
  8670. Vec::new()
  8671. };
  8672. (i.pack2, packs)
  8673. }),
  8674. _ => None,
  8675. };
  8676. let f16 = name.ends_with("_f16");
  8677. // The evaluated channel plus `add`, as a float.
  8678. let total = |l: &mut Self, row: u8, ch: u8| -> Result<V, Why> {
  8679. let x = l.eval_channel(row, ch, eval)?;
  8680. let x = l.as_float(x);
  8681. Ok(match add {
  8682. Some(a) => l.s.m.bin(l.cur, Bin::Add, a, x),
  8683. None => x,
  8684. })
  8685. };
  8686. let x = match packing {
  8687. None if f16 || attribute.high => return Err("a 16-bit read of a 32-bit input"),
  8688. None => {
  8689. let x = total(self, attribute.row, attribute.channel)?;
  8690. self.as_int(x)
  8691. }
  8692. Some((pack2, packs)) => {
  8693. // 16-bit values: one in the low half of each dword, or two
  8694. // per dword (`packed_half`); the host's are 32-bit floats.
  8695. let half = |l: &mut Self, h: u8| -> Result<Option<V>, Why> {
  8696. let src = if pack2 {
  8697. packed_half(&l.s.inputs, &packs, attribute.row, h)
  8698. } else {
  8699. h.is_multiple_of(2).then_some((attribute.row, h / 2))
  8700. };
  8701. match src {
  8702. Some((row, ch)) => total(l, row, ch).map(Some),
  8703. None => Ok(None),
  8704. }
  8705. };
  8706. let to_f16 = |l: &mut Self, f: V| {
  8707. let i32t = l.s.t.i32;
  8708. l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  8709. };
  8710. let h = 2 * attribute.channel + u8::from(attribute.high);
  8711. let c = self.cur;
  8712. if name == "v_interp_p1ll_f16" {
  8713. // An f32 result from 16-bit vertex values.
  8714. let f = half(self, h)?.ok_or("a packed input half no element holds")?;
  8715. self.as_int(f)
  8716. } else if f16 {
  8717. let f = half(self, h)?.ok_or("a packed input half no element holds")?;
  8718. let lo = to_f16(self, f);
  8719. self.low_half(inst, reg, lo)
  8720. } else if matches!(eval, Eval::Mode(1)) {
  8721. // The whole dword of a flat input: both halves.
  8722. let h = 2 * attribute.channel;
  8723. let z = self.s.m.i32(0);
  8724. let lo = match half(self, h)? {
  8725. Some(f) => to_f16(self, f),
  8726. None => z,
  8727. };
  8728. let hi = match half(self, h + 1)? {
  8729. Some(f) => to_f16(self, f),
  8730. None => z,
  8731. };
  8732. let k16 = self.s.m.i32(16);
  8733. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  8734. self.s.m.bin(c, Bin::Or, lo, hi)
  8735. } else {
  8736. return Err("32-bit interpolation of a 16-bit input");
  8737. }
  8738. }
  8739. };
  8740. // A pixel interpolates in every lane; guards only hide inactive ones.
  8741. self.write(inst, Reg::V(reg), x, None);
  8742. Ok(())
  8743. }
  8744. /// Whether the program reads attribute row `row` per vertex (an
  8745. /// interpolation with computed barycentrics, or P10 or P20): then its
  8746. /// element is declared constant and read with `attributeAtVertex`.
  8747. fn per_vertex(&self, row: u8) -> bool {
  8748. self.x.io.interps.iter().any(|(_, i)| match *i {
  8749. Interp::Weighted { attribute } => attribute.row == row,
  8750. Interp::Vertex { attribute, vertex } => {
  8751. attribute.row == row && vertex != 2 && self.interpolated(row)
  8752. }
  8753. Interp::Interpolated { .. } => false,
  8754. })
  8755. }
  8756. /// Whether the program interpolates attribute row `row` (so the
  8757. /// hardware holds P1 - P0 and P2 - P0 for it).
  8758. fn interpolated(&self, row: u8) -> bool {
  8759. self.x.io.interps.iter().any(|(_, i)| match *i {
  8760. Interp::Interpolated { attribute, .. } | Interp::Weighted { attribute } => {
  8761. attribute.row == row
  8762. }
  8763. Interp::Vertex { .. } => false,
  8764. })
  8765. }
  8766. /// Channel `ch` of input row `row` evaluated as `eval` says, as raw bits.
  8767. fn eval_channel(&mut self, row: u8, ch: u8, eval: Eval) -> Result<V, Why> {
  8768. let (id, col) = self
  8769. .find_input(row, ch)
  8770. .ok_or("an input the signature lacks")?;
  8771. let mode = match eval {
  8772. Eval::Mode(mode) => mode,
  8773. Eval::Weights { .. } => 1,
  8774. };
  8775. let e = &mut self.s.inputs[id];
  8776. if e.interp != mode && e.usage != 0 {
  8777. return Err("one input interpolated two ways");
  8778. }
  8779. e.interp = mode;
  8780. let Eval::Weights { p0, i, j } = eval else {
  8781. return match self.load_any_input(id, col) {
  8782. Val::I32(x) => Ok(x),
  8783. _ => Err("an input"),
  8784. };
  8785. };
  8786. let v0 = self.vertex_input(id, col, 0);
  8787. let c = self.cur;
  8788. let mut acc = p0.then_some(v0);
  8789. for (k, w) in [(1, i), (2, j)] {
  8790. let Some(w) = w else { continue };
  8791. let vk = self.vertex_input(id, col, k);
  8792. let d = self.s.m.bin(c, Bin::Sub, vk, v0);
  8793. acc = Some(match acc {
  8794. Some(a) => self.fmad(w, d, a),
  8795. None => self.s.m.bin(c, Bin::Mul, w, d),
  8796. });
  8797. }
  8798. let acc = acc.ok_or("an interpolation")?;
  8799. Ok(self.as_int(acc))
  8800. }
  8801. /// Vertex `k` (0 the provoking vertex, as `barycentric` orders them)
  8802. /// of a constant input element's channel, as a float.
  8803. fn vertex_input(&mut self, id: usize, col: u8, k: u8) -> V {
  8804. let e = &mut self.s.inputs[id];
  8805. e.usage |= 1 << col;
  8806. let int = e.comp != 9;
  8807. let (ty, suffix) = if int {
  8808. (self.s.t.i32, ".i32")
  8809. } else {
  8810. (self.s.t.f32, ".f32")
  8811. };
  8812. self.s.flags |= flags::BARYCENTRICS;
  8813. let entry = self.s.entry;
  8814. let args = [
  8815. self.s.m.i32(id as u32),
  8816. self.s.m.i32(0),
  8817. self.s.m.i8(col),
  8818. self.s.m.i8(k),
  8819. ];
  8820. let v = self.s.op(
  8821. entry,
  8822. &format!("attributeAtVertex{suffix}"),
  8823. Attr::ReadNone,
  8824. ty,
  8825. 137,
  8826. &args,
  8827. );
  8828. if int {
  8829. self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.f32)
  8830. } else {
  8831. v
  8832. }
  8833. }
  8834. /// `x` (an f16 in the low bits) as the low half of VGPR `reg`: 16-bit
  8835. /// results keep the register's high half (GFX10).
  8836. fn low_half(&mut self, inst: &Inst, reg: u8, x: V) -> V {
  8837. let c = self.cur;
  8838. let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) {
  8839. Some(Ok(o)) => o,
  8840. _ => self.s.m.i32(0),
  8841. };
  8842. let (high, low) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF));
  8843. let old = self.s.m.bin(c, Bin::And, old, high);
  8844. let x = self.s.m.bin(c, Bin::And, x, low);
  8845. self.s.m.bin(c, Bin::Or, old, x)
  8846. }
  8847. fn image(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  8848. let Fields::Image {
  8849. data,
  8850. addr,
  8851. dmask,
  8852. dim,
  8853. unorm,
  8854. a16,
  8855. d16,
  8856. tfe,
  8857. lwe,
  8858. ..
  8859. } = &inst.fields
  8860. else {
  8861. unreachable!()
  8862. };
  8863. if *tfe || *lwe {
  8864. return Err("an image access with tfe or lwe");
  8865. }
  8866. let name = inst.name();
  8867. // A load or sample with no channel enabled returns the first.
  8868. let dmask = if *dmask == 0 { &1 } else { dmask };
  8869. let site = (b, i);
  8870. let guard = self.guard(b, i)?;
  8871. let c = self.cur;
  8872. let (kind, coords) = match dim {
  8873. 0 => (1, 1),
  8874. 1 => (2, 2),
  8875. 2 => (4, 3),
  8876. // Sampled (face coordinates and face, see `cube_direction`) or
  8877. // sized only.
  8878. 3 if name.starts_with("image_sample")
  8879. || name.starts_with("image_gather")
  8880. || name == "image_get_resinfo" =>
  8881. {
  8882. (5, 3)
  8883. }
  8884. 4 => (6, 2),
  8885. 5 => (7, 3),
  8886. _ => return Err("an image dimension (cube loads or MSAA)"),
  8887. };
  8888. // Address VGPRs in order.
  8889. let mut regs = Vec::new();
  8890. for a in addr {
  8891. if let Operand::Vector { reg, dwords } = *a {
  8892. regs.extend((0..dwords).map(|k| reg + k));
  8893. }
  8894. }
  8895. // Full 32-bit address VGPR at `reg_idx` (offset, bias, z-compare).
  8896. let addr_u32 = |l: &mut Self, reg_idx: usize| -> Result<V, Why> {
  8897. let r = *regs.get(reg_idx).ok_or("an image address")?;
  8898. let v = inst.read(Reg::V(r)).ok_or("an image address")?;
  8899. l.i32_of(v)
  8900. };
  8901. // With a16, two 16-bit components per VGPR starting at `base_reg`, low half first.
  8902. let addr_packed = |l: &mut Self, base_reg: usize, k: usize| -> Result<V, Why> {
  8903. let x = addr_u32(l, base_reg + if *a16 { k / 2 } else { k })?;
  8904. if !*a16 {
  8905. return Ok(x);
  8906. }
  8907. let c = l.cur;
  8908. let (sh, mask) = (l.s.m.i32(16 * (k as u32 % 2)), l.s.m.i32(0xFFFF));
  8909. let x = l.s.m.bin(c, Bin::LShr, x, sh);
  8910. Ok(l.s.m.bin(c, Bin::And, x, mask))
  8911. };
  8912. let addr_val = |l: &mut Self, k: usize| -> Result<V, Why> { addr_packed(l, 0, k) };
  8913. let src = self
  8914. .descriptors
  8915. .get(&(site, false))
  8916. .copied()
  8917. .ok_or("an untracked image")?;
  8918. let store = name.starts_with("image_store");
  8919. let uav = store
  8920. || self
  8921. .used_kind(src)
  8922. .is_some_and(|u| u.kind == ResourceType::Uav);
  8923. let props = (kind | if uav { 0x1000 } else { 0 }, 0x409);
  8924. if let Some(op) = name.strip_prefix("image_atomic_") {
  8925. // GLC returns the old value. DXIL implements subtraction by adding
  8926. // the two's complement of the operand at the same width.
  8927. let code = match op {
  8928. "add" | "sub" => 0,
  8929. "and" => 1,
  8930. "or" => 2,
  8931. "xor" => 3,
  8932. "smin" => 4,
  8933. "smax" => 5,
  8934. "umin" => 6,
  8935. "umax" => 7,
  8936. "swap" => 8,
  8937. "cmpswap" => u32::MAX,
  8938. _ => return Err(name),
  8939. };
  8940. let Fields::Image { cache, .. } = &inst.fields else {
  8941. unreachable!()
  8942. };
  8943. if *d16 || *a16 {
  8944. return Err("a 16-bit image atomic");
  8945. }
  8946. // Compare-exchange consumes a replacement followed by a comparand.
  8947. let compare = code == u32::MAX;
  8948. let wide = match (compare, *dmask) {
  8949. (false, 1) | (true, 3) => false,
  8950. (false, 3) | (true, 15) => true,
  8951. _ => return Err("an image atomic data mask"),
  8952. };
  8953. let iu = self.s.m.undef(self.s.t.i32);
  8954. let mut cs = vec![iu; 3];
  8955. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  8956. *slot = addr_val(self, k)?;
  8957. }
  8958. let Operand::Vector { reg, .. } = *data else {
  8959. return Err("image atomic data");
  8960. };
  8961. let width = if wide { 2 } else { 1 };
  8962. let vals = self.vgprs(inst, data, if compare { 2 * width } else { width })?;
  8963. let (ty, component) = if wide {
  8964. self.s.flags |= flags::INT64 | flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64;
  8965. (self.s.m.int(64), 0x107) // one uint64_t in an R32G32_UINT view
  8966. } else {
  8967. (self.s.t.i32, 0x105)
  8968. };
  8969. let original = if wide {
  8970. self.join64(vals[0], vals[1])
  8971. } else {
  8972. vals[0]
  8973. };
  8974. let value = if op == "sub" {
  8975. let zero = self.s.m.int_const(ty, 0);
  8976. self.s.m.bin(c, Bin::Sub, zero, original)
  8977. } else {
  8978. original
  8979. };
  8980. let h = self.handle(site, src, false, (kind | 0x1000, component))?;
  8981. let mut args = vec![h];
  8982. let (intrinsic, opcode) = if compare {
  8983. let comparand = if wide {
  8984. self.join64(vals[2], vals[3])
  8985. } else {
  8986. vals[1]
  8987. };
  8988. args.extend(cs);
  8989. args.extend([comparand, value]);
  8990. let intrinsic = if wide {
  8991. "atomicCompareExchange.i64"
  8992. } else {
  8993. "atomicCompareExchange.i32"
  8994. };
  8995. (intrinsic, 79)
  8996. } else {
  8997. args.push(self.s.m.i32(code));
  8998. args.extend(cs);
  8999. args.push(value);
  9000. (
  9001. if wide {
  9002. "atomicBinOp.i64"
  9003. } else {
  9004. "atomicBinOp.i32"
  9005. },
  9006. 78,
  9007. )
  9008. };
  9009. let at = self.begin_guarded(guard);
  9010. let r = self
  9011. .s
  9012. .op(self.cur, intrinsic, Attr::NoUnwind, ty, opcode, &args);
  9013. if cache.glc {
  9014. let old = self.end_guarded(at, &[(r, original)])[0];
  9015. if wide {
  9016. let (lo, hi) = self.split64(old);
  9017. self.write(inst, Reg::V(reg), lo, None);
  9018. self.write(inst, Reg::V(reg + 1), hi, None);
  9019. } else {
  9020. self.write(inst, Reg::V(reg), old, None);
  9021. }
  9022. } else {
  9023. self.end_guarded(at, &[]);
  9024. }
  9025. return Ok(());
  9026. }
  9027. if store {
  9028. if name != "image_store" {
  9029. return Err("an image store to a mip level");
  9030. }
  9031. // shortcut: stores are taken to write all four channels of a
  9032. // float format (the console converts by the view's format).
  9033. if *dmask != 0xF {
  9034. return Err("an image store of some channels");
  9035. }
  9036. let iu = self.s.m.undef(self.s.t.i32);
  9037. let mut cs = vec![iu; 3];
  9038. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  9039. *slot = addr_val(self, k)?;
  9040. }
  9041. let Operand::Vector { reg, .. } = *data else {
  9042. return Err("image store data");
  9043. };
  9044. let mut vals = Vec::new();
  9045. for k in 0..4u8 {
  9046. // d16: two f16 channels per VGPR, low half first.
  9047. let r = if *d16 { k / 2 } else { k };
  9048. let v = inst.read(Reg::V(reg + r)).ok_or("image store data")?;
  9049. vals.push(if *d16 {
  9050. let mut x = self.i32_of(v)?;
  9051. if k % 2 == 1 {
  9052. let k16 = self.s.m.i32(16);
  9053. x = self.s.m.bin(self.cur, Bin::LShr, x, k16);
  9054. }
  9055. let f32t = self.s.t.f32;
  9056. self.s
  9057. .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x])
  9058. } else {
  9059. self.float_of(v)?
  9060. });
  9061. }
  9062. let h = self.handle(site, src, false, props)?;
  9063. let at = self.begin_guarded(guard);
  9064. let mut args = vec![h];
  9065. args.extend(cs);
  9066. args.extend(vals);
  9067. args.push(self.s.m.i8(0xF));
  9068. let void = self.s.t.void;
  9069. self.s.op(
  9070. self.cur,
  9071. "textureStore.f32",
  9072. Attr::NoUnwind,
  9073. void,
  9074. 67,
  9075. &args,
  9076. );
  9077. self.end_guarded(at, &[]);
  9078. return Ok(());
  9079. }
  9080. let has_cl = name.ends_with("_cl");
  9081. let (op, sample) = match name {
  9082. "image_sample" | "image_sample_o" | "image_sample_cl" => (60, true),
  9083. "image_sample_lz" | "image_sample_l" | "image_sample_lz_o" => (62, true),
  9084. "image_sample_b" | "image_sample_b_cl" => (61, true),
  9085. "image_sample_c_lz" => (65, true),
  9086. "image_sample_d" | "image_sample_d_cl" => (63, true),
  9087. "image_get_lod" if self.s.pixel => (81, true),
  9088. // Implicit derivatives: pixel shaders only.
  9089. "image_sample_c" if self.s.pixel => (64, true),
  9090. "image_sample_c_cl" if self.s.pixel => (64, true),
  9091. "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" | "image_gather4_l" | "image_gather4_l_o" => (73, true),
  9092. "image_load" | "image_load_mip" => (66, false),
  9093. "image_get_resinfo" => (72, false),
  9094. _ => return Err(name),
  9095. };
  9096. if op == 72 {
  9097. // Width, height, depth or layers, levels (per dmask) of the level
  9098. // in the first address: DXIL's dimensions; a channel DXIL leaves
  9099. // out reads 1 (UAVs: one level).
  9100. let h = self.handle(site, src, false, props)?;
  9101. let mip = if uav {
  9102. self.s.m.undef(self.s.t.i32)
  9103. } else {
  9104. addr_val(self, 0)?
  9105. };
  9106. let i32t = self.s.t.i32;
  9107. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  9108. let d = self
  9109. .s
  9110. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  9111. let one = self.s.m.i32(1);
  9112. let present = match kind {
  9113. 1 => [true, false, false, true],
  9114. 2 | 5 | 6 => [true, true, false, true],
  9115. _ => [true, true, true, true],
  9116. };
  9117. let Operand::Vector { reg, .. } = *data else {
  9118. return Err("an image result");
  9119. };
  9120. for (k, ch) in (0..4u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() {
  9121. let x = if ch == 3 && uav || !present[ch as usize] {
  9122. one
  9123. } else {
  9124. self.s.m.extract(c, d, ch)
  9125. };
  9126. self.write(inst, Reg::V(reg + k as u8), x, guard);
  9127. }
  9128. return Ok(());
  9129. }
  9130. if uav && op != 66 {
  9131. return Err("sampling a UAV");
  9132. }
  9133. let h = self.handle(site, src, false, props)?;
  9134. let fu = self.s.m.undef(self.s.t.f32);
  9135. let iu = self.s.m.undef(self.s.t.i32);
  9136. // A gather at a named level, done as four texel reads (below).
  9137. let mut gathered: Option<[V; 4]> = None;
  9138. let r = if sample {
  9139. let ss = self
  9140. .descriptors
  9141. .get(&(site, true))
  9142. .copied()
  9143. .ok_or("an untracked sampler")?;
  9144. // Comparison: the reference value is the first address after
  9145. // the bias, and the sampler is a comparison sampler.
  9146. let cmp = matches!(op, 64 | 65);
  9147. if cmp && (*a16 || dmask.count_ones() != 1) {
  9148. return Err("a comparison sample of 16-bit coordinates or several channels");
  9149. }
  9150. let sh = self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?;
  9151. // Texel offsets (`_o`) come first: x in bits 0-5, y in 8-13,
  9152. // signed (programmable offsets: gathers only).
  9153. let offset_word = name.ends_with("_o");
  9154. let first = usize::from(offset_word)
  9155. + usize::from(name.starts_with("image_sample_b"))
  9156. + usize::from(cmp);
  9157. // Coordinates the size divides (not the array slice); explicit
  9158. // gradients (x then y) come before the coordinates.
  9159. let spatial = coords - usize::from(kind == 6 || kind == 7);
  9160. // A cube's gradients are the two of its face coordinates.
  9161. let grads = if kind == 5 { 2 } else { spatial };
  9162. let deriv_regs = if op == 63 {
  9163. if *a16 {
  9164. grads.div_ceil(2)
  9165. } else {
  9166. grads
  9167. }
  9168. } else {
  9169. 0
  9170. };
  9171. let coord_base = first + 2 * deriv_regs;
  9172. let mut cs = vec![fu; 4];
  9173. // With a16, sampling coordinates, gradients, LOD and clamp are f16.
  9174. let to_float = |l: &mut Self, x: V| {
  9175. if *a16 {
  9176. let f = l.s.t.f32;
  9177. l.s.op(l.cur, "legacyF16ToF32", Attr::ReadNone, f, 131, &[x])
  9178. } else {
  9179. l.as_float(x)
  9180. }
  9181. };
  9182. if kind == 5 && (*unorm || op == 81) {
  9183. return Err("a cube sample with texel coordinates or a level query");
  9184. }
  9185. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  9186. let x = addr_packed(self, coord_base, k)?;
  9187. *slot = to_float(self, x);
  9188. }
  9189. if kind == 5 {
  9190. let dir = self.cube_direction(cs[0], cs[1], cs[2]);
  9191. cs[..3].copy_from_slice(&dir);
  9192. }
  9193. if *unorm {
  9194. // Texel coordinates: divided by the size of level 0.
  9195. let i32t = self.s.t.i32;
  9196. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  9197. let z = self.s.m.i32(0);
  9198. let d = self
  9199. .s
  9200. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]);
  9201. for (k, slot) in cs.iter_mut().enumerate().take(spatial) {
  9202. let n = self.s.m.extract(c, d, k as u32);
  9203. let n = self.s.m.cast(c, Cast::UiToFp, n, self.s.t.f32);
  9204. *slot = self.s.m.bin(c, Bin::SDiv, *slot, n);
  9205. }
  9206. }
  9207. if op == 81 {
  9208. // The clamped then the unclamped level of detail.
  9209. let Operand::Vector { reg, .. } = *data else {
  9210. return Err("an image result");
  9211. };
  9212. let f32t = self.s.t.f32;
  9213. for (k, ch) in (0..2u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() {
  9214. let clamped = self.s.m.bool(ch == 0);
  9215. let lod = self.s.op(
  9216. c,
  9217. "calculateLOD.f32",
  9218. Attr::ReadOnly,
  9219. f32t,
  9220. 81,
  9221. &[h, sh, cs[0], cs[1], cs[2], clamped],
  9222. );
  9223. let x = self.as_int(lod);
  9224. self.write(inst, Reg::V(reg + k as u8), x, guard);
  9225. }
  9226. return Ok(());
  9227. }
  9228. let offsets = if kind == 5 {
  9229. 0
  9230. } else {
  9231. (coords - usize::from(kind == 6 || kind == 7)).min(3)
  9232. };
  9233. let zero = self.s.m.i32(0);
  9234. let mut os = vec![iu; 3];
  9235. for o in os.iter_mut().take(offsets) {
  9236. *o = zero;
  9237. }
  9238. if offset_word && offsets > 0 {
  9239. let w = addr_val(self, 0)?;
  9240. for (k, at) in [(0, 26), (1, 18)].into_iter().take(offsets.min(2)) {
  9241. // Bits at..at+5 sign-extended: shift up, then down.
  9242. let left = self.s.m.i32(at);
  9243. let t = self.s.m.bin(c, Bin::Shl, w, left);
  9244. let k26 = self.s.m.i32(26);
  9245. os[k] = self.s.m.bin(c, Bin::AShr, t, k26);
  9246. }
  9247. }
  9248. let mut args = vec![h, sh];
  9249. args.extend(&cs);
  9250. let clamp = if has_cl {
  9251. let x = addr_packed(self, coord_base, coords)?;
  9252. to_float(self, x)
  9253. } else {
  9254. fu
  9255. };
  9256. match op {
  9257. // Outside a pixel shader there are no screen derivatives:
  9258. // the validator refuses `sample` there ("features
  9259. // incompatible with the shader stage": 730 compute programs,
  9260. // among them the G-buffer resolves and the sky), and what a
  9261. // driver does with it is its own affair.
  9262. // shortcut: such a sample reads level 0 (a bias: that
  9263. // level). The console takes derivatives from neighbouring
  9264. // lanes there; compute them from the lanes if a resolve
  9265. // shows the wrong mip.
  9266. 60 if !self.s.pixel => {
  9267. args.extend(&os);
  9268. args.push(self.s.m.f32(0));
  9269. self.s.op(
  9270. c,
  9271. "sampleLevel.f32",
  9272. Attr::ReadOnly,
  9273. self.s.t.res_ret,
  9274. 62,
  9275. &args,
  9276. )
  9277. }
  9278. 60 => {
  9279. if offset_word {
  9280. // DXIL wants immediate offsets in -8..=7 here; the
  9281. // console's are 6-bit and may be computed. A
  9282. // constant word in range becomes immediates
  9283. // (upstream PR #634); anything else keeps the
  9284. // offsets computed above (upstream refuses those).
  9285. let w = addr_val(self, 0)?;
  9286. if let Some(w) = self.s.m.int_value(w) {
  9287. let w = w as u32;
  9288. let field = |k: usize| {
  9289. let x = (w >> (8 * k) & 0x3F) as i32;
  9290. if x >= 32 { x - 64 } else { x }
  9291. };
  9292. let n = offsets.min(2);
  9293. if (0..n).all(|k| (-8..=7).contains(&field(k))) {
  9294. for (k, o) in os.iter_mut().enumerate().take(n) {
  9295. *o = self.s.m.i32(field(k) as u32);
  9296. }
  9297. }
  9298. }
  9299. }
  9300. args.extend(&os);
  9301. args.push(clamp);
  9302. self.s
  9303. .op(c, "sample.f32", Attr::ReadOnly, self.s.t.res_ret, 60, &args)
  9304. }
  9305. 61 => {
  9306. // With a16 the bias is an f16 in the low half of its
  9307. // word (the word is whole, the value is not).
  9308. let bias = addr_u32(self, usize::from(offset_word))?;
  9309. let bias = if *a16 {
  9310. let low = self.s.m.i32(0xFFFF);
  9311. let bias = self.s.m.bin(c, Bin::And, bias, low);
  9312. to_float(self, bias)
  9313. } else {
  9314. self.as_float(bias)
  9315. };
  9316. args.extend(&os);
  9317. if self.s.pixel {
  9318. args.extend([bias, clamp]);
  9319. self.s.op(
  9320. c,
  9321. "sampleBias.f32",
  9322. Attr::ReadOnly,
  9323. self.s.t.res_ret,
  9324. 61,
  9325. &args,
  9326. )
  9327. } else {
  9328. // As above: the bias is the level.
  9329. args.push(bias);
  9330. self.s.op(
  9331. c,
  9332. "sampleLevel.f32",
  9333. Attr::ReadOnly,
  9334. self.s.t.res_ret,
  9335. 62,
  9336. &args,
  9337. )
  9338. }
  9339. }
  9340. 63 if kind == 5 => {
  9341. // A cube with explicit gradients: the host wants them
  9342. // as changes of the direction, the console gives the
  9343. // changes of the face coordinates (the face is one
  9344. // unit wide). The level they select is taken from the
  9345. // longer of the two, in texels, and sampled directly.
  9346. // shortcut: no anisotropic filtering for these samples
  9347. // (the longer axis alone decides the level).
  9348. let mut len = [fu; 2];
  9349. for (axis, slot) in len.iter_mut().enumerate() {
  9350. let mut sum = self.s.m.f32(0);
  9351. for k in 0..2 {
  9352. let x = addr_packed(self, first + axis * deriv_regs, k)?;
  9353. let x = to_float(self, x);
  9354. let sq = self.s.m.bin(c, Bin::Mul, x, x);
  9355. sum = self.s.m.bin(c, Bin::Add, sum, sq);
  9356. }
  9357. *slot = self.unary(24, sum); // square root
  9358. }
  9359. let longer = self.binary(35, len[0], len[1]); // maximum
  9360. let i32t = self.s.t.i32;
  9361. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  9362. let z = self.s.m.i32(0);
  9363. let d = self
  9364. .s
  9365. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]);
  9366. let width = self.s.m.extract(c, d, 0);
  9367. let width = self.s.m.cast(c, Cast::UiToFp, width, self.s.t.f32);
  9368. let texels = self.s.m.bin(c, Bin::Mul, longer, width);
  9369. // log2 = natural logarithm / ln 2; a length of 0 gives
  9370. // minus infinity, which the sampler clamps to level 0.
  9371. let ln = self.unary(23, texels);
  9372. let per_ln2 = self.s.m.f32(std::f32::consts::LOG2_E.to_bits());
  9373. let lod = self.s.m.bin(c, Bin::Mul, ln, per_ln2);
  9374. args.extend(&os);
  9375. args.push(lod);
  9376. self.s.op(
  9377. c,
  9378. "sampleLevel.f32",
  9379. Attr::ReadOnly,
  9380. self.s.t.res_ret,
  9381. 62,
  9382. &args,
  9383. )
  9384. }
  9385. 63 => {
  9386. let mut g = vec![fu; 6];
  9387. for k in 0..spatial {
  9388. let x = addr_packed(self, first, k)?;
  9389. g[k] = to_float(self, x);
  9390. let y = addr_packed(self, first + deriv_regs, k)?;
  9391. g[3 + k] = to_float(self, y);
  9392. }
  9393. args.extend(&os);
  9394. args.extend(g);
  9395. args.push(clamp);
  9396. self.s.op(
  9397. c,
  9398. "sampleGrad.f32",
  9399. Attr::ReadOnly,
  9400. self.s.t.res_ret,
  9401. 63,
  9402. &args,
  9403. )
  9404. }
  9405. 64 | 65 => {
  9406. let reference = addr_u32(self, first - 1)?;
  9407. let reference = self.as_float(reference);
  9408. args.extend(&os);
  9409. args.push(reference);
  9410. let name = if op == 64 {
  9411. args.push(clamp);
  9412. "sampleCmp.f32"
  9413. } else {
  9414. "sampleCmpLevelZero.f32"
  9415. };
  9416. self.s
  9417. .op(c, name, Attr::ReadOnly, self.s.t.res_ret, op, &args)
  9418. }
  9419. 62 => {
  9420. let lod = if name == "image_sample_l" {
  9421. let x = addr_packed(self, coord_base, coords)?;
  9422. to_float(self, x)
  9423. } else {
  9424. self.s.m.f32(0)
  9425. };
  9426. args.extend(&os);
  9427. args.push(lod);
  9428. self.s.op(
  9429. c,
  9430. "sampleLevel.f32",
  9431. Attr::ReadOnly,
  9432. self.s.t.res_ret,
  9433. 62,
  9434. &args,
  9435. )
  9436. }
  9437. _ => {
  9438. if name == "image_gather4" {
  9439. return Err("a gather with implicit level");
  9440. }
  9441. if dmask.count_ones() != 1 {
  9442. return Err("a gather of several channels");
  9443. }
  9444. if matches!(name, "image_gather4_l" | "image_gather4_l_o")
  9445. && coords == 2
  9446. && spatial == 2
  9447. {
  9448. // The host's gather has no level: it read level 0
  9449. // where the title names one (the depth pyramid its
  9450. // occlusion tests read: most of the world was
  9451. // culled against the wrong depths). The four texels
  9452. // are read at the level instead, in the gather's
  9453. // order: (u0,v1) (u1,v1) (u1,v0) (u0,v0).
  9454. // With an offset too (`image_gather4_l_o`): the
  9455. // offset is in texels of that level. Grand Theft
  9456. // Auto VI's meshlet culling takes a 4x4 block of
  9457. // the pyramid as one gather and three offset ones
  9458. // ((2,0), (0,2), (2,2)); the three read level 0,
  9459. // two texels beside the first one's place, so a
  9460. // meshlet three or four texels wide was tested
  9461. // against a quarter of what it covers.
  9462. // shortcut: the level is rounded to a whole one and
  9463. // coordinates past the edge are clamped, whatever
  9464. // the sampler says.
  9465. let lod = addr_packed(self, coord_base, coords)?;
  9466. let lod = to_float(self, lod);
  9467. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  9468. let zero = self.s.m.f32(0);
  9469. let lod = self.binary(35, lod, zero); // maximum
  9470. let lod = self.unary(26, lod); // round to nearest
  9471. let mip = self.s.m.cast(c, Cast::FpToUi, lod, i32t);
  9472. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  9473. let d = self
  9474. .s
  9475. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  9476. let half = self.s.m.f32(0.5f32.to_bits());
  9477. let one = self.s.m.f32(1.0f32.to_bits());
  9478. let (mut lo, mut hi) = ([iu; 2], [iu; 2]);
  9479. for k in 0..2 {
  9480. let n = self.s.m.extract(c, d, k as u32);
  9481. let n = self.s.m.cast(c, Cast::UiToFp, n, f32t);
  9482. let last = self.s.m.bin(c, Bin::Sub, n, one);
  9483. let t = self.s.m.bin(c, Bin::Mul, cs[k], n);
  9484. let t = self.s.m.bin(c, Bin::Sub, t, half);
  9485. let first = self.unary(27, t); // round down
  9486. // The offset word's field (0 without one).
  9487. let by = self.s.m.cast(c, Cast::SiToFp, os[k], f32t);
  9488. let first = self.s.m.bin(c, Bin::Add, first, by);
  9489. let next = self.s.m.bin(c, Bin::Add, first, one);
  9490. for (slot, x) in [(&mut lo[k], first), (&mut hi[k], next)] {
  9491. let x = self.binary(35, x, zero); // maximum
  9492. let x = self.binary(36, x, last); // minimum
  9493. *slot = self.s.m.cast(c, Cast::FpToSi, x, i32t);
  9494. }
  9495. }
  9496. let ch = dmask.trailing_zeros();
  9497. let mut g = [fu; 4];
  9498. let mut read = None;
  9499. let texels = [(lo[0], hi[1]), (hi[0], hi[1]), (hi[0], lo[1]), (lo[0], lo[1])];
  9500. for (slot, (x, y)) in g.iter_mut().zip(texels) {
  9501. let r = self.s.op(
  9502. c,
  9503. "textureLoad.f32",
  9504. Attr::ReadOnly,
  9505. self.s.t.res_ret,
  9506. 66,
  9507. &[h, mip, x, y, iu, iu, iu, iu],
  9508. );
  9509. *slot = self.s.m.extract(c, r, ch);
  9510. read = Some(r);
  9511. }
  9512. gathered = Some(g);
  9513. read.expect("four reads")
  9514. } else {
  9515. args.extend(&os[..2]);
  9516. args.push(self.s.m.i32(dmask.trailing_zeros()));
  9517. self.s.op(
  9518. c,
  9519. "textureGather.f32",
  9520. Attr::ReadOnly,
  9521. self.s.t.res_ret,
  9522. 73,
  9523. &args,
  9524. )
  9525. }
  9526. }
  9527. }
  9528. } else {
  9529. let mut cs = vec![iu; 3];
  9530. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  9531. *slot = addr_val(self, k)?;
  9532. }
  9533. let mip = if name == "image_load_mip" {
  9534. addr_val(self, coords)?
  9535. } else if uav {
  9536. // Our declarations have four channels.
  9537. self.s.flags |= flags::TYPED_UAV_LOADS;
  9538. iu
  9539. } else {
  9540. self.s.m.i32(0)
  9541. };
  9542. let mut args = vec![h, mip];
  9543. args.extend(&cs);
  9544. args.extend([iu, iu, iu]);
  9545. self.s.op(
  9546. c,
  9547. "textureLoad.f32",
  9548. Attr::ReadOnly,
  9549. self.s.t.res_ret,
  9550. 66,
  9551. &args,
  9552. )
  9553. };
  9554. let Operand::Vector { reg, .. } = *data else {
  9555. return Err("an image result");
  9556. };
  9557. let channels: Vec<u32> = if op == 73 {
  9558. vec![0, 1, 2, 3]
  9559. } else {
  9560. (0..4).filter(|ch| dmask >> ch & 1 != 0).collect()
  9561. };
  9562. let mut xs = Vec::new();
  9563. for ch in channels {
  9564. let x = match gathered {
  9565. Some(g) => g[ch as usize],
  9566. None => self.s.m.extract(c, r, ch),
  9567. };
  9568. xs.push(if *d16 {
  9569. // shortcut: d16 results are taken as floats (rounded to
  9570. // nearest even); integer formats would keep 16 bits.
  9571. let i32t = self.s.t.i32;
  9572. self.s
  9573. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x])
  9574. } else {
  9575. self.as_int(x)
  9576. });
  9577. }
  9578. if *d16 {
  9579. // Two channels per VGPR, low half first (an odd last high half 0).
  9580. let k16 = self.s.m.i32(16);
  9581. xs = xs
  9582. .chunks(2)
  9583. .map(|p| match *p {
  9584. [lo, hi] => {
  9585. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  9586. self.s.m.bin(c, Bin::Or, lo, hi)
  9587. }
  9588. _ => p[0],
  9589. })
  9590. .collect();
  9591. }
  9592. for (k, x) in xs.into_iter().enumerate() {
  9593. self.write(inst, Reg::V(reg + k as u8), x, guard);
  9594. }
  9595. Ok(())
  9596. }
  9597. /// The direction a cube sample's face coordinates stand for: the
  9598. /// console takes s and t in [1, 2] (`v_cubesc`/`v_cubetc` over
  9599. /// `|v_cubema|`, plus 1.5) and the face id (`v_cubeid`), which the
  9600. /// host's cube sampling turns back into the same texel.
  9601. // shortcut: the view is taken as a cube, not a cube array (whose face
  9602. // operand adds 8 × the slice).
  9603. fn cube_direction(&mut self, s: V, t: V, face: V) -> [V; 3] {
  9604. let c = self.cur;
  9605. let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits());
  9606. let (two, three) = (k(self, 2.0), k(self, 3.0));
  9607. let u = self.s.m.bin(c, Bin::Mul, s, two);
  9608. let u = self.s.m.bin(c, Bin::Sub, u, three);
  9609. let v = self.s.m.bin(c, Bin::Mul, t, two);
  9610. let v = self.s.m.bin(c, Bin::Sub, v, three);
  9611. let z = self.s.m.f32(0x8000_0000);
  9612. let (nu, nv) = (
  9613. self.s.m.bin(c, Bin::Sub, z, u),
  9614. self.s.m.bin(c, Bin::Sub, z, v),
  9615. );
  9616. let (one, mone) = (k(self, 1.0), k(self, -1.0));
  9617. let f = self.s.m.cast(c, Cast::FpToUi, face, self.s.t.i32);
  9618. // Per face +x, -x, +y, -y, +z, -z.
  9619. let table = [
  9620. [one, mone, u, u, u, nu],
  9621. [nv, nv, one, mone, nv, nv],
  9622. [nu, u, v, nv, one, mone],
  9623. ];
  9624. table.map(|row| {
  9625. let mut r = row[0];
  9626. for (n, &x) in row.iter().enumerate().skip(1) {
  9627. let kn = self.s.m.i32(n as u32);
  9628. let is = self.s.m.cmp(c, pred::EQ, f, kn);
  9629. r = self.s.m.select(c, is, x, r);
  9630. }
  9631. r
  9632. })
  9633. }
  9634. fn buffer(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  9635. let Fields::Buffer {
  9636. data,
  9637. addr,
  9638. soffset,
  9639. offset,
  9640. offen,
  9641. idxen,
  9642. format,
  9643. lds,
  9644. tfe,
  9645. ..
  9646. } = &inst.fields
  9647. else {
  9648. unreachable!()
  9649. };
  9650. let name = inst.name();
  9651. if name == "buffer_gl0_inv" || name == "buffer_gl1_inv" {
  9652. // The host has no console buffer cache to invalidate.
  9653. return Ok(());
  9654. }
  9655. if *lds || *tfe {
  9656. return Err("a buffer access to LDS or with tfe");
  9657. }
  9658. if format.is_some() && !name.starts_with("tbuffer_load_format_") {
  9659. return Err(name);
  9660. }
  9661. let site = (b, i);
  9662. let guard = self.guard(b, i)?;
  9663. let c = self.cur;
  9664. let store = name.starts_with("buffer_store_");
  9665. // DXIL atomic operations: add, and, or, xor, signed and unsigned
  9666. // min and max, exchange; compare-exchange apart.
  9667. let atomic = match name.strip_prefix("buffer_atomic_") {
  9668. None => None,
  9669. Some("add") => Some(0),
  9670. Some("and") => Some(1),
  9671. Some("or") => Some(2),
  9672. Some("xor") => Some(3),
  9673. Some("smin") => Some(4),
  9674. Some("smax") => Some(5),
  9675. Some("umin") => Some(6),
  9676. Some("umax") => Some(7),
  9677. Some("swap") => Some(8),
  9678. Some("cmpswap") => Some(u32::MAX),
  9679. Some(_) => return Err(name),
  9680. };
  9681. // Byte and 16-bit accesses: bits, and whether a load sign-extends.
  9682. let narrow = match name {
  9683. "buffer_load_ubyte" | "buffer_store_byte" => Some((8, false)),
  9684. "buffer_load_sbyte" => Some((8, true)),
  9685. "buffer_load_ushort" | "buffer_store_short" => Some((16, false)),
  9686. "buffer_load_sshort" => Some((16, true)),
  9687. _ => None,
  9688. };
  9689. // d16: two 16-bit channels per VGPR, low half first.
  9690. let d16 = name.starts_with("buffer_") && name.contains("_format_d16_");
  9691. let plain = name.replace("_format_d16_", "_format_");
  9692. let (typed, count) = match plain
  9693. .strip_prefix("buffer_load_")
  9694. .or(plain.strip_prefix("buffer_store_"))
  9695. .or(plain.strip_prefix("tbuffer_load_"))
  9696. {
  9697. _ if atomic.is_some() || narrow.is_some() => (false, 1),
  9698. Some("dword") => (false, 1),
  9699. Some("dwordx2") => (false, 2),
  9700. Some("dwordx3") => (false, 3),
  9701. Some("dwordx4") => (false, 4),
  9702. Some("format_x") => (true, 1),
  9703. Some("format_xy") => (true, 2),
  9704. Some("format_xyz") => (true, 3),
  9705. Some("format_xyzw") => (true, 4),
  9706. _ => return Err(name),
  9707. };
  9708. let Operand::Vector { reg: areg, .. } = *addr else {
  9709. return Err("a buffer address");
  9710. };
  9711. let vaddr = |l: &mut Self, k: u8| -> Result<V, Why> {
  9712. let v = inst.read(Reg::V(areg + k)).ok_or("a buffer address")?;
  9713. l.i32_of(v)
  9714. };
  9715. let index = if *idxen { Some(vaddr(self, 0)?) } else { None };
  9716. let mut off = self.s.m.i32(u32::from(*offset));
  9717. if *offen {
  9718. let o = vaddr(self, u8::from(*idxen))?;
  9719. off = self.s.m.bin(c, Bin::Add, off, o);
  9720. }
  9721. if !matches!(
  9722. soffset,
  9723. Operand::Scalar { code: NULL, .. } | Operand::Const(128)
  9724. ) {
  9725. let so = self.operand(inst, soffset)?;
  9726. off = self.s.m.bin(c, Bin::Add, off, so);
  9727. }
  9728. let src = self
  9729. .descriptors
  9730. .get(&(site, false))
  9731. .copied()
  9732. .ok_or("an untracked buffer")?;
  9733. let used = self.used_kind(src);
  9734. let (base, extra) = self.built_offset(src)?;
  9735. if base != 0 {
  9736. let b = self.s.m.i32(base);
  9737. off = self.s.m.bin(c, Bin::Add, off, b);
  9738. }
  9739. if let Some(x) = extra {
  9740. off = self.s.m.bin(c, Bin::Add, off, x);
  9741. }
  9742. // A buffer the program picks from the view heap by an index it
  9743. // computes: no used-resource entry gives its stride, the host's
  9744. // table by heap slot does; the access becomes a raw one at the
  9745. // element's byte. (Also tells the host this shader reads such
  9746. // buffers.)
  9747. let mut index = index;
  9748. if let Some(stride) = self.slot_stride(src)?
  9749. && let Some(element) = index
  9750. && !typed
  9751. && used.is_none()
  9752. {
  9753. let at = self.s.m.bin(c, Bin::Mul, element, stride);
  9754. off = self.s.m.bin(c, Bin::Add, at, off);
  9755. index = None;
  9756. }
  9757. // A structured buffer by its used-resource entry's stride: raw
  9758. // bytes too. The host makes its buffer views raw (a raw read
  9759. // through a structured view gives zeros on NVIDIA), and one kind
  9760. // of view can then serve every shader that reads the buffer.
  9761. if let (Some(element), Some(u)) = (index, used)
  9762. && !typed
  9763. && u.kind != ResourceType::Cbv
  9764. && u.stride >= 4
  9765. && u.stride.is_multiple_of(4)
  9766. {
  9767. let k = self.s.m.i32(u.stride);
  9768. let at = self.s.m.bin(c, Bin::Mul, element, k);
  9769. off = self.s.m.bin(c, Bin::Add, at, off);
  9770. index = None;
  9771. }
  9772. if used.is_some_and(|u| u.kind == ResourceType::Cbv) && !typed {
  9773. // A constant buffer read per lane (a dynamically indexed array).
  9774. // shortcut: the console's CBV descriptor is taken to have a 16-byte
  9775. // stride, as the vector loads of whole rows suggest.
  9776. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  9777. let byte = match index {
  9778. Some(i) => {
  9779. let sixteen = self.s.m.i32(16);
  9780. let rows = self.s.m.bin(c, Bin::Mul, i, sixteen);
  9781. self.s.m.bin(c, Bin::Add, rows, off)
  9782. }
  9783. None => off,
  9784. };
  9785. let Some(Operand::Vector { reg, .. }) = *data else {
  9786. return Err("a buffer result");
  9787. };
  9788. for k in 0..count {
  9789. let four = self.s.m.i32(4 * k);
  9790. let a = self.s.m.bin(c, Bin::Add, byte, four);
  9791. let x = self.cbuffer_dword(h, a);
  9792. self.write(inst, Reg::V(reg + k as u8), x, guard);
  9793. }
  9794. return Ok(());
  9795. }
  9796. let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav);
  9797. let u = if uav { 0x1000 } else { 0 };
  9798. let iu = self.s.m.undef(self.s.t.i32);
  9799. if let Some((bits, signed)) = narrow {
  9800. // Below a dword: raw buffers are read and written in dwords on
  9801. // 4 bytes, so the dword that holds the value is read and
  9802. // shifted, or changed with two atomic operations that touch
  9803. // only the value's own bits (other lanes may write the rest of
  9804. // the dword at the same time). A 16-bit value at a dword's
  9805. // last byte continues in the next dword.
  9806. let byte = match index {
  9807. None => off,
  9808. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  9809. self.s.m.bin(c, Bin::Add, index, off)
  9810. }
  9811. Some(_) => return Err("a byte or 16-bit buffer access by index"),
  9812. };
  9813. let h = self.handle(site, src, false, (11 | u, 0))?;
  9814. let k3 = self.s.m.i32(3);
  9815. let within = self.s.m.bin(c, Bin::And, byte, k3);
  9816. let aligned = self.s.m.bin(c, Bin::Sub, byte, within);
  9817. let shift = self.s.m.bin(c, Bin::Shl, within, k3);
  9818. let four = self.s.m.i32(4);
  9819. let next = self.s.m.bin(c, Bin::Add, aligned, four);
  9820. let ones = self.s.m.i32(if bits == 8 { 0xff } else { 0xffff });
  9821. let zero = self.s.m.i32(0);
  9822. let k8 = self.s.m.i32(8);
  9823. let straddles = self.s.m.cmp(c, pred::EQ, within, k3);
  9824. if !store {
  9825. let mask = self.s.m.i8(1);
  9826. let align = self.s.m.i32(4);
  9827. let dword = |l: &mut Self, at: V| {
  9828. let r = l.s.op(
  9829. c,
  9830. "rawBufferLoad.f32",
  9831. Attr::ReadOnly,
  9832. l.s.t.res_ret,
  9833. 139,
  9834. &[h, at, iu, mask, align],
  9835. );
  9836. let f = l.s.m.extract(c, r, 0);
  9837. l.as_int(f)
  9838. };
  9839. let low = dword(self, aligned);
  9840. let mut x = self.s.m.bin(c, Bin::LShr, low, shift);
  9841. if bits == 16 {
  9842. let high = dword(self, next);
  9843. let high = self.s.m.bin(c, Bin::Shl, high, k8);
  9844. let high = self.s.m.select(c, straddles, high, zero);
  9845. x = self.s.m.bin(c, Bin::Or, x, high);
  9846. }
  9847. x = self.s.m.bin(c, Bin::And, x, ones);
  9848. if signed {
  9849. let up = self.s.m.i32(32 - bits);
  9850. x = self.s.m.bin(c, Bin::Shl, x, up);
  9851. x = self.s.m.bin(c, Bin::AShr, x, up);
  9852. }
  9853. let Some(Operand::Vector { reg, .. }) = *data else {
  9854. return Err("a buffer result");
  9855. };
  9856. self.write(inst, Reg::V(reg), x, guard);
  9857. return Ok(());
  9858. }
  9859. let d = data.as_ref().ok_or("buffer store data")?;
  9860. let v = self.vgprs(inst, d, 1)?[0];
  9861. let v = self.s.m.bin(c, Bin::And, v, ones);
  9862. let all = self.s.m.i32(u32::MAX);
  9863. let clear = self.s.m.bin(c, Bin::Shl, ones, shift);
  9864. let keep = self.s.m.bin(c, Bin::Xor, clear, all);
  9865. let set = self.s.m.bin(c, Bin::Shl, v, shift);
  9866. let keep_next = self.s.m.i32(0xffff_ff00);
  9867. let set_next = self.s.m.bin(c, Bin::LShr, v, k8);
  9868. let (and, or) = (self.s.m.i32(1), self.s.m.i32(2));
  9869. let i32t = self.s.t.i32;
  9870. let at = self.begin_guarded(guard);
  9871. for (op, x) in [(and, keep), (or, set)] {
  9872. let args = [h, op, aligned, iu, iu, x];
  9873. self.s
  9874. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args);
  9875. }
  9876. if bits == 16 {
  9877. let second = self.begin_guarded(Some(straddles));
  9878. for (op, x) in [(and, keep_next), (or, set_next)] {
  9879. let args = [h, op, next, iu, iu, x];
  9880. self.s
  9881. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args);
  9882. }
  9883. self.end_guarded(second, &[]);
  9884. }
  9885. self.end_guarded(at, &[]);
  9886. return Ok(());
  9887. }
  9888. if let Some(op) = atomic {
  9889. let d = data.as_ref().ok_or("buffer atomic data")?;
  9890. let vals = self.vgprs(inst, d, if op == u32::MAX { 2 } else { 1 })?;
  9891. let (h, coords) = match index {
  9892. // A raw buffer (stride 1) read by index: the index is the byte.
  9893. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  9894. let byte = self.s.m.bin(c, Bin::Add, index, off);
  9895. (self.handle(site, src, false, (11 | u, 0))?, [byte, iu, iu])
  9896. }
  9897. Some(index) => {
  9898. let stride = used.map_or(0, |u| u.stride);
  9899. if stride < 4 || !stride.is_multiple_of(4) {
  9900. return Err("a structured buffer of unknown stride");
  9901. }
  9902. let h = self.handle(site, src, false, (12 | u, stride))?;
  9903. (h, [index, off, iu])
  9904. }
  9905. None => (self.handle(site, src, false, (11 | u, 0))?, [off, iu, iu]),
  9906. };
  9907. let Operand::Vector { reg, .. } = *d else {
  9908. return Err("buffer atomic data");
  9909. };
  9910. let returns = matches!(inst.fields, Fields::Buffer { cache, .. } if cache.glc);
  9911. let old = match inst.read(Reg::V(reg)) {
  9912. Some(v) if returns => self.i32_of(v)?,
  9913. _ => self.s.m.i32(0),
  9914. };
  9915. let at = self.begin_guarded(guard);
  9916. let i32t = self.s.t.i32;
  9917. let r = if op == u32::MAX {
  9918. // cmpswap: data is (new, compare).
  9919. let mut args = vec![h];
  9920. args.extend(coords);
  9921. args.extend([vals[1], vals[0]]);
  9922. self.s.op(
  9923. self.cur,
  9924. "atomicCompareExchange.i32",
  9925. Attr::NoUnwind,
  9926. i32t,
  9927. 79,
  9928. &args,
  9929. )
  9930. } else {
  9931. let mut args = vec![h, self.s.m.i32(op)];
  9932. args.extend(coords);
  9933. args.push(vals[0]);
  9934. self.s
  9935. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args)
  9936. };
  9937. let r = self.end_guarded(at, &[(r, old)])[0];
  9938. if returns {
  9939. self.write(inst, Reg::V(reg), r, None);
  9940. }
  9941. return Ok(());
  9942. }
  9943. if store {
  9944. let regs = if d16 { count.div_ceil(2) } else { count };
  9945. let mut vals =
  9946. self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?;
  9947. if d16 {
  9948. // shortcut: d16 data is taken as f16 (integer formats would
  9949. // keep 16 bits), widened for the 32-bit float store.
  9950. let mut wide = Vec::new();
  9951. for k in 0..count {
  9952. let mut x = vals[(k / 2) as usize];
  9953. if k % 2 == 1 {
  9954. let k16 = self.s.m.i32(16);
  9955. x = self.s.m.bin(c, Bin::LShr, x, k16);
  9956. }
  9957. let f32t = self.s.t.f32;
  9958. let f = self
  9959. .s
  9960. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
  9961. wide.push(self.as_int(f));
  9962. }
  9963. vals = wide;
  9964. }
  9965. let mut args = Vec::new();
  9966. let (op, name) = if typed {
  9967. // shortcut: typed stores are taken to write all four channels
  9968. // of a float format.
  9969. if count != 4 || *offen || *offset != 0 {
  9970. return Err("a typed buffer store of some channels or at an offset");
  9971. }
  9972. args.push(self.handle(site, src, false, (10 | u, 0x409))?);
  9973. args.extend([index.unwrap_or(self.s.m.i32(0)), iu]);
  9974. for x in vals {
  9975. args.push(self.as_float(x));
  9976. }
  9977. (69, "bufferStore.f32")
  9978. } else {
  9979. match index {
  9980. // A raw buffer (stride 1) written by index: the index is the byte.
  9981. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  9982. let byte = self.s.m.bin(c, Bin::Add, index, off);
  9983. args.push(self.handle(site, src, false, (11 | u, 0))?);
  9984. args.extend([byte, iu]);
  9985. }
  9986. Some(index) => {
  9987. let stride = used.map_or(0, |u| u.stride);
  9988. if stride < 4 || !stride.is_multiple_of(4) {
  9989. return Err("a structured buffer of unknown stride");
  9990. }
  9991. args.push(self.handle(site, src, false, (12 | u, stride))?);
  9992. args.extend([index, off]);
  9993. }
  9994. None => {
  9995. args.push(self.handle(site, src, false, (11 | u, 0))?);
  9996. args.extend([off, iu]);
  9997. }
  9998. }
  9999. args.extend(&vals);
  10000. args.resize(3 + 4, iu);
  10001. (140, "rawBufferStore.i32")
  10002. };
  10003. args.push(self.s.m.i8(if typed { 0xF } else { (1u8 << count) - 1 }));
  10004. if !typed {
  10005. args.push(self.s.m.i32(4));
  10006. }
  10007. let at = self.begin_guarded(guard);
  10008. let void = self.s.t.void;
  10009. self.s.op(self.cur, name, Attr::NoUnwind, void, op, &args);
  10010. self.end_guarded(at, &[]);
  10011. return Ok(());
  10012. }
  10013. if let Some(f) = *format {
  10014. if index.is_some() {
  10015. return Err("a typed-format load by index");
  10016. }
  10017. let h = self.handle(site, src, false, (11 | u, 0))?;
  10018. let Some(Operand::Vector { reg, .. }) = *data else {
  10019. return Err("a buffer result");
  10020. };
  10021. for (k, x) in self.format_load(h, off, f, count)?.into_iter().enumerate() {
  10022. self.write(inst, Reg::V(reg + k as u8), x, guard);
  10023. }
  10024. return Ok(());
  10025. }
  10026. let r = if typed {
  10027. if *offen || matches!(off, V::Inst(_)) || *offset != 0 {
  10028. return Err("a typed buffer load at an offset");
  10029. }
  10030. if uav {
  10031. self.s.flags |= flags::TYPED_UAV_LOADS;
  10032. }
  10033. let h = self.handle(site, src, false, (10 | u, 0x409))?;
  10034. let index = index.unwrap_or(self.s.m.i32(0));
  10035. self.s.op(
  10036. c,
  10037. "bufferLoad.f32",
  10038. Attr::ReadOnly,
  10039. self.s.t.res_ret,
  10040. 68,
  10041. &[h, index, iu],
  10042. )
  10043. } else {
  10044. let mask = self.s.m.i8((1u8 << count) - 1);
  10045. let align = self.s.m.i32(4);
  10046. match index {
  10047. // A raw buffer (stride 1) read by index: the index is the byte.
  10048. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  10049. let byte = self.s.m.bin(c, Bin::Add, index, off);
  10050. let h = self.handle(site, src, false, (11 | u, 0))?;
  10051. self.s.op(
  10052. c,
  10053. "rawBufferLoad.f32",
  10054. Attr::ReadOnly,
  10055. self.s.t.res_ret,
  10056. 139,
  10057. &[h, byte, iu, mask, align],
  10058. )
  10059. }
  10060. Some(index) => {
  10061. let stride = used.map_or(0, |u| u.stride);
  10062. if stride < 4 || !stride.is_multiple_of(4) {
  10063. return Err("a structured buffer of unknown stride");
  10064. }
  10065. let h = self.handle(site, src, false, (12 | u, stride))?;
  10066. self.s.op(
  10067. c,
  10068. "rawBufferLoad.f32",
  10069. Attr::ReadOnly,
  10070. self.s.t.res_ret,
  10071. 139,
  10072. &[h, index, off, mask, align],
  10073. )
  10074. }
  10075. None => {
  10076. let h = self.handle(site, src, false, (11 | u, 0))?;
  10077. self.s.op(
  10078. c,
  10079. "rawBufferLoad.f32",
  10080. Attr::ReadOnly,
  10081. self.s.t.res_ret,
  10082. 139,
  10083. &[h, off, iu, mask, align],
  10084. )
  10085. }
  10086. }
  10087. };
  10088. let Some(Operand::Vector { reg, .. }) = *data else {
  10089. return Err("a buffer result");
  10090. };
  10091. if d16 {
  10092. // Two f16 channels per VGPR (an odd last high half 0).
  10093. let k16 = self.s.m.i32(16);
  10094. let i32t = self.s.t.i32;
  10095. for k in 0..count.div_ceil(2) {
  10096. let mut x = None;
  10097. for ch in (2 * k..(2 * k + 2).min(count)).rev() {
  10098. let f = self.s.m.extract(c, r, ch);
  10099. let h = self
  10100. .s
  10101. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
  10102. x = Some(match x {
  10103. Some(hi) => {
  10104. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  10105. self.s.m.bin(c, Bin::Or, h, hi)
  10106. }
  10107. None => h,
  10108. });
  10109. }
  10110. self.write(inst, Reg::V(reg + k as u8), x.expect("a channel"), guard);
  10111. }
  10112. return Ok(());
  10113. }
  10114. for k in 0..count {
  10115. let x = self.s.m.extract(c, r, k);
  10116. let x = self.as_int(x);
  10117. self.write(inst, Reg::V(reg + k as u8), x, guard);
  10118. }
  10119. Ok(())
  10120. }
  10121. fn export(&mut self, b: usize, i: usize) -> Result<(), Why> {
  10122. let e = *self
  10123. .exports
  10124. .get(&(b, i))
  10125. .ok_or("an export I/O raising did not see")?;
  10126. if e.compressed {
  10127. return Err("a compressed export");
  10128. }
  10129. let guard = self.guard(b, i)?;
  10130. let mesh = self.s.mesh.is_some();
  10131. let c = self.cur;
  10132. if let Some(g) = guard
  10133. && !mesh
  10134. {
  10135. if !(e.done && self.s.pixel) {
  10136. return Err("a conditional export");
  10137. }
  10138. let t = self.s.m.bool(true);
  10139. let kill = self.s.m.bin(c, Bin::Xor, g, t);
  10140. self.s
  10141. .op(c, "discard", Attr::NoUnwind, self.s.t.void, 82, &[kill]);
  10142. }
  10143. if mesh && e.target == Target::Primitive {
  10144. return self.emit_indices(e, guard);
  10145. }
  10146. let param_row = |usage: Usage, row: u8| match usage {
  10147. // The 2020 compiler leaves a mesh program's first entry zeroed
  10148. // (usage "position"): its row is the one no other entry names.
  10149. Usage::Other(0) if mesh => self.unnamed_row(),
  10150. _ => Some(row),
  10151. };
  10152. // (output element, channel) per exported channel; per-primitive
  10153. // outputs are elements of `prims`.
  10154. let mut stores = Vec::new();
  10155. let primitive = matches!(e.target, Target::PrimitiveParam { .. });
  10156. let outputs = if primitive {
  10157. &self.s.prims
  10158. } else {
  10159. &self.s.outputs
  10160. };
  10161. let by_kind = |kind: u8| outputs.iter().position(|o| o.kind == kind);
  10162. // 16-bit vertex outputs: the halves each dword carries, as (output
  10163. // element, channel, high half) per channel.
  10164. let halves = match e.target {
  10165. Target::Param { usage, row } => {
  10166. param_row(usage, row).and_then(|r| self.half_outputs.get(&r).map(|&h| (r, h)))
  10167. }
  10168. _ => None,
  10169. };
  10170. if let Some((row, (pack2, _))) = halves {
  10171. let packs: Vec<(u8, Option<u8>)> = self
  10172. .half_outputs
  10173. .iter()
  10174. .filter(|(_, h)| h.0)
  10175. .map(|(&r, h)| (r, h.1))
  10176. .collect();
  10177. for ch in 0..4u8 {
  10178. let Some(value) = e.values[usize::from(ch)] else {
  10179. continue;
  10180. };
  10181. for high in [false, true] {
  10182. let h = 2 * ch + u8::from(high);
  10183. let src = if pack2 {
  10184. packed_half(outputs, &packs, row, h)
  10185. } else {
  10186. (!high).then_some((row, ch))
  10187. };
  10188. let found = src.and_then(|(r, c)| {
  10189. outputs.iter().position(|o| {
  10190. o.row == Some(u32::from(r)) && c >= o.col && c < o.col + o.cols
  10191. })
  10192. });
  10193. if let Some(id) = found {
  10194. let col = src.expect("found").1 - outputs[id].col;
  10195. stores.push((id, col, value, Some(high)));
  10196. }
  10197. }
  10198. }
  10199. }
  10200. for ch in 0..4u8 {
  10201. let Some(value) = e.values[usize::from(ch)] else {
  10202. continue;
  10203. };
  10204. if halves.is_some() {
  10205. break;
  10206. }
  10207. let found = match e.target {
  10208. Target::Color(n) => outputs
  10209. .iter()
  10210. .position(|o| o.kind == 16 && o.row == Some(u32::from(n)))
  10211. .map(|id| (id, ch)),
  10212. Target::Position(0) => by_kind(3).map(|id| (id, ch)),
  10213. Target::Depth => match ch {
  10214. 0 => by_kind(17)
  10215. .or(by_kind(18))
  10216. .or(by_kind(19))
  10217. .map(|id| (id, 0)),
  10218. 1 => by_kind(20).map(|id| (id, 0)),
  10219. 2 => by_kind(14).map(|id| (id, 0)),
  10220. _ => None,
  10221. },
  10222. Target::Param { usage, row } | Target::PrimitiveParam { usage, row } => {
  10223. let row = param_row(usage, row);
  10224. outputs
  10225. .iter()
  10226. .position(|o| {
  10227. row.is_some_and(|r| o.row == Some(u32::from(r)))
  10228. && ch >= o.col
  10229. && ch < o.col + o.cols
  10230. })
  10231. .map(|id| (id, ch - outputs[id].col))
  10232. }
  10233. Target::Null | Target::Unread => None,
  10234. Target::Position(n @ 1..=2) => {
  10235. // shortcut: without the misc vector (point size, render
  10236. // target or viewport index) pos1 and pos2 carry the clip
  10237. // then cull distances, in semantic order.
  10238. if outputs.iter().any(|o| matches!(o.kind, 4 | 5)) {
  10239. return Err("render-target or viewport index exports");
  10240. }
  10241. let mut dists: Vec<usize> = (0..outputs.len())
  10242. .filter(|&i| matches!(outputs[i].kind, 6 | 7))
  10243. .collect();
  10244. dists.sort_by_key(|&i| (outputs[i].kind, outputs[i].index));
  10245. let flat: Vec<(usize, u8)> = dists
  10246. .iter()
  10247. .flat_map(|&i| (0..outputs[i].cols).map(move |c| (i, c)))
  10248. .collect();
  10249. // Channels past the distances the signature declares are
  10250. // ones the clipper does not enable (`PA_CL_VS_OUT_CNTL`).
  10251. let k = usize::from(n - 1) * 4 + usize::from(ch);
  10252. flat.get(k).copied()
  10253. }
  10254. Target::Position(_) => return Err("clip, cull or point-size exports"),
  10255. Target::Primitive => return Err("a primitive export"),
  10256. };
  10257. if let Some((id, col)) = found {
  10258. stores.push((id, col, value, None));
  10259. }
  10260. }
  10261. fn elements<'l>(l: &'l mut Lower, primitive: bool) -> &'l mut Vec<SigElement> {
  10262. if primitive {
  10263. &mut l.s.prims
  10264. } else {
  10265. &mut l.s.outputs
  10266. }
  10267. }
  10268. if stores
  10269. .iter()
  10270. .any(|s| s.3.is_none() && elements(self, primitive)[s.0].half)
  10271. {
  10272. return Err("a 16-bit output the stage data does not mark");
  10273. }
  10274. // A mesh lane writes its own vertex or primitive, where it exports.
  10275. let at = if mesh {
  10276. let flat = self.mesh_thread();
  10277. let limit = if let Some(m) = self.s.mesh {
  10278. if primitive {
  10279. m.max_primitives
  10280. } else {
  10281. m.max_vertices
  10282. }
  10283. } else {
  10284. 0
  10285. };
  10286. let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX);
  10287. let mesh_guard = if limit > 0 && threads > limit {
  10288. let lim = self.s.m.i32(limit);
  10289. let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, lim);
  10290. match guard {
  10291. Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)),
  10292. None => Some(in_bounds),
  10293. }
  10294. } else {
  10295. guard
  10296. };
  10297. self.begin_guarded(mesh_guard)
  10298. } else {
  10299. None
  10300. };
  10301. let (name, opcode) = match (mesh, primitive) {
  10302. (false, _) => ("storeOutput", 5),
  10303. (true, false) => ("storeVertexOutput", 171),
  10304. (true, true) => ("storePrimitiveOutput", 172),
  10305. };
  10306. for (id, col, value, half) in stores {
  10307. let mut x = self.i32_of(value)?;
  10308. if let Some(high) = half {
  10309. // An f16 half, declared a 32-bit float on the host.
  10310. let c = self.cur;
  10311. if high {
  10312. let k16 = self.s.m.i32(16);
  10313. x = self.s.m.bin(c, Bin::LShr, x, k16);
  10314. }
  10315. let f32t = self.s.t.f32;
  10316. let f = self
  10317. .s
  10318. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
  10319. x = self.as_int(f);
  10320. }
  10321. let el = &mut elements(self, primitive)[id];
  10322. el.usage |= 1 << col;
  10323. let (suffix, x) = match el.comp {
  10324. 9 if half.is_some() => (".f32", self.as_float(x)),
  10325. 9 => {
  10326. let f = match self.floats.get(&value) {
  10327. Some(&f) => f,
  10328. None => self.as_float(x),
  10329. };
  10330. (".f32", f)
  10331. }
  10332. _ => (".i32", x),
  10333. };
  10334. let mut args = vec![
  10335. self.s.m.i32(id as u32),
  10336. self.s.m.i32(0),
  10337. self.s.m.i8(col),
  10338. x,
  10339. ];
  10340. if mesh {
  10341. args.push(self.mesh_thread());
  10342. }
  10343. let void = self.s.t.void;
  10344. self.s.op(
  10345. self.cur,
  10346. &format!("{name}{suffix}"),
  10347. Attr::NoUnwind,
  10348. void,
  10349. opcode,
  10350. &args,
  10351. );
  10352. }
  10353. self.end_guarded(at, &[]);
  10354. Ok(())
  10355. }
  10356. /// Mesh: `exp prim` as the lane's primitive. Bit 31 culls it (all
  10357. /// indices 0: no area).
  10358. fn emit_indices(&mut self, e: &Export, guard: Option<V>) -> Result<(), Why> {
  10359. let v = e.values[0].ok_or("a primitive export without its indices")?;
  10360. let x = self.i32_of(v)?;
  10361. let flat = self.mesh_thread();
  10362. let guard = if let Some(mesh) = self.s.mesh {
  10363. let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX);
  10364. if threads > mesh.max_primitives {
  10365. let p = self.s.m.i32(mesh.max_primitives);
  10366. let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, p);
  10367. match guard {
  10368. Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)),
  10369. None => Some(in_bounds),
  10370. }
  10371. } else {
  10372. guard
  10373. }
  10374. } else {
  10375. guard
  10376. };
  10377. let at = self.begin_guarded(guard);
  10378. let c = self.cur;
  10379. let z = self.s.m.i32(0);
  10380. let mut culled = self.s.m.cmp(c, pred::SLT, x, z);
  10381. // A primitive that names a vertex past the declared count, or one
  10382. // no lane writes (lane n writes vertex n alone), is culled too: the
  10383. // host would read a vertex nothing set, at any position.
  10384. let written = self.s.mesh.map(|m| {
  10385. m.max_vertices
  10386. .min(self.s.threads.map_or(u32::MAX, |t| t[0]))
  10387. });
  10388. let mut indices = [z; 3];
  10389. for (k, slot) in indices.iter_mut().enumerate() {
  10390. let (shift, mask) = (self.s.m.i32(10 * k as u32), self.s.m.i32(0x3FF));
  10391. let i = self.s.m.bin(c, Bin::LShr, x, shift);
  10392. let i = self.s.m.bin(c, Bin::And, i, mask);
  10393. if let Some(n) = written {
  10394. let n = self.s.m.i32(n);
  10395. let past = self.s.m.cmp(c, pred::IUGE, i, n);
  10396. culled = self.s.m.bin(c, Bin::Or, culled, past);
  10397. }
  10398. *slot = i;
  10399. }
  10400. let mut args = vec![flat];
  10401. for i in indices {
  10402. args.push(self.s.m.select(c, culled, z, i));
  10403. }
  10404. let void = self.s.t.void;
  10405. self.s
  10406. .op(c, "emitIndices", Attr::NoUnwind, void, 169, &args);
  10407. self.end_guarded(at, &[]);
  10408. Ok(())
  10409. }
  10410. /// The per-vertex arbitrary row no mesh output entry names but one
  10411. /// (the 2020 compiler's zeroed entry).
  10412. fn unnamed_row(&self) -> Option<u8> {
  10413. let StageIo::Ms(ms) = &self.x.native.io else {
  10414. return None;
  10415. };
  10416. let named = |r: u32| {
  10417. ms.outputs
  10418. .iter()
  10419. .any(|o| o.param & 0x80 == 0 && o.usage != Usage::Other(0) && u32::from(o.row) == r)
  10420. };
  10421. let free: std::collections::BTreeSet<u32> = self
  10422. .s
  10423. .outputs
  10424. .iter()
  10425. .filter(|o| o.kind == 0)
  10426. .filter_map(|o| o.row)
  10427. .filter(|&r| !named(r))
  10428. .collect();
  10429. match free.into_iter().collect::<Vec<_>>()[..] {
  10430. [r] => u8::try_from(r).ok(),
  10431. _ => None,
  10432. }
  10433. }
  10434. fn exit(&mut self, b: usize) -> Result<(), Stop> {
  10435. let offset = self.x.p.blocks[b]
  10436. .insts
  10437. .last()
  10438. .map_or(self.x.p.blocks[b].offset, |i| i.machine.offset);
  10439. let term = match self.x.st.exits[b] {
  10440. LaneExit::Jump(t) if self.counters.contains_key(&t) && self.rpo[t] <= self.rpo[b] => {
  10441. let ok = self.count_iteration(t, pred::IULT);
  10442. let abort = self.abort_block();
  10443. Term::CondBr(ok, self.block[t].expect("reachable"), abort)
  10444. }
  10445. LaneExit::Jump(t) => {
  10446. self.enter_loop(b, t, self.cur);
  10447. Term::Br(self.block[t].expect("reachable"))
  10448. }
  10449. LaneExit::Branch {
  10450. when,
  10451. taken,
  10452. not_taken,
  10453. } => {
  10454. // A negated condition branches the other way round.
  10455. let (cond, taken, not_taken) = match self.x.st.bools.node(when) {
  10456. _ if self.x.st.wide.contains(&b) => {
  10457. let c = self.wave_wide(b, when).map_err(|w| unsupported(offset, w))?;
  10458. (c, taken, not_taken)
  10459. }
  10460. Some((atom, Bool::TRUE, Bool::FALSE)) => {
  10461. let a = self
  10462. .atom(atom, self.cur)
  10463. .map_err(|w| unsupported(offset, w))?;
  10464. (a, not_taken, taken)
  10465. }
  10466. _ => {
  10467. let c = self
  10468. .boolean(when, self.cur)
  10469. .map_err(|w| unsupported(offset, w))?;
  10470. (c, taken, not_taken)
  10471. }
  10472. };
  10473. // A back edge is taken only below the iteration limit.
  10474. let back =
  10475. |l: &Self, to: usize| l.counters.contains_key(&to) && l.rpo[to] <= l.rpo[b];
  10476. // (No `xor` of a compare: a loop exit testing one hung the
  10477. // AMD driver.)
  10478. let cond = if back(self, taken) {
  10479. let ok = self.count_iteration(taken, pred::IULT);
  10480. self.s.m.bin(self.cur, Bin::And, cond, ok)
  10481. } else if back(self, not_taken) {
  10482. let stop = self.count_iteration(not_taken, pred::IUGE);
  10483. self.s.m.bin(self.cur, Bin::Or, cond, stop)
  10484. } else {
  10485. cond
  10486. };
  10487. // Critical edges get a block of their own, so loops have
  10488. // dedicated exits and preheaders as DXC emits them.
  10489. let (t, f) = (self.edge(b, taken), self.edge(b, not_taken));
  10490. for (to, via) in [(taken, t), (not_taken, f)] {
  10491. if !back(self, to) {
  10492. // From an edge block, or from here.
  10493. let from = if Some(via) == self.block[to] {
  10494. self.cur
  10495. } else {
  10496. via
  10497. };
  10498. self.enter_loop(b, to, from);
  10499. }
  10500. }
  10501. Term::CondBr(cond, t, f)
  10502. }
  10503. LaneExit::End => {
  10504. if self.s.pixel && !self.exported[b] && !self.has_done_export(b) {
  10505. // A lane leaving without its final export was killed.
  10506. let t = self.s.m.bool(true);
  10507. self.s
  10508. .op(self.cur, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]);
  10509. }
  10510. Term::Ret
  10511. }
  10512. LaneExit::Indirect => return Err(unsupported(offset, "an indirect jump")),
  10513. };
  10514. let _ = Exit::End;
  10515. self.s.m.terminate(self.cur, term);
  10516. Ok(())
  10517. }
  10518. /// A forward edge into loop header `to` (from DXIL block `via`) starts
  10519. /// its count at 0.
  10520. fn enter_loop(&mut self, _from: usize, to: usize, via: usize) {
  10521. if let Some((_, incoming)) = self.counters.get_mut(&to) {
  10522. let z = self.s.m.i32(0);
  10523. incoming.push((z, via));
  10524. }
  10525. }
  10526. /// A back edge to header `to` (a back edge keeps its block, no
  10527. /// critical-edge block): the count goes up; the result compares it with
  10528. /// [`LOOP_LIMIT`] by `p` (below: go on; at or above: stop).
  10529. fn count_iteration(&mut self, to: usize, p: u8) -> V {
  10530. let c = self.cur;
  10531. let (phi, _) = self.counters[&to];
  10532. let one = self.s.m.i32(1);
  10533. let next = self.s.m.bin(c, Bin::Add, phi, one);
  10534. // Per stage unless the switch names one: a loop that never meets its
  10535. // exit (a count read from a buffer the host has not got yet, say)
  10536. // runs to the limit in every lane. A million iterations a pixel
  10537. // hung the GPU for seconds a draw until Windows reset it
  10538. // (PS_Textured_Eight, 2026-11-24, run 12).
  10539. // shortcut: a pixel loop past 128 iterations, a vertex or mesh loop
  10540. // past 256 or a compute loop past 4,096 is cut short. (They were
  10541. // 1,024, 4,096 and 65,536: the opening cutscene then lost the card
  10542. // 14-25 frames in, in a minimap or shadow mesh draw; with every
  10543. // loop cut at 64 it ran 90 frames. Raise them again once shaders
  10544. // stop reading data that is not there yet.)
  10545. let limit = match super::loop_limit() {
  10546. LOOP_LIMIT if self.s.pixel => 1 << 7,
  10547. LOOP_LIMIT if self.s.mesh.is_some() || self.s.threads.is_none() => 1 << 8,
  10548. LOOP_LIMIT => 1 << 12,
  10549. named => named,
  10550. };
  10551. let limit = self.s.m.i32(limit);
  10552. self.counters
  10553. .get_mut(&to)
  10554. .expect("header")
  10555. .1
  10556. .push((next, c));
  10557. self.s.m.cmp(c, p, next, limit)
  10558. }
  10559. /// The block a lane stopped by [`LOOP_LIMIT`] leaves through.
  10560. fn abort_block(&mut self) -> usize {
  10561. if let Some(a) = self.abort {
  10562. return a;
  10563. }
  10564. let a = self.s.m.new_block();
  10565. if self.s.pixel {
  10566. let t = self.s.m.bool(true);
  10567. self.s
  10568. .op(a, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]);
  10569. }
  10570. self.s.m.terminate(a, Term::Ret);
  10571. self.abort = Some(a);
  10572. a
  10573. }
  10574. /// The DXIL block a branch from IR block `from` to `to` goes to.
  10575. fn edge(&mut self, from: usize, to: usize) -> usize {
  10576. let target = self.block[to].expect("reachable");
  10577. let preds = self.x.p.blocks[to]
  10578. .preds
  10579. .iter()
  10580. .filter(|&&q| self.block[q].is_some())
  10581. .count();
  10582. // Back edges stay as they are: the exiting block is the latch.
  10583. if preds < 2 || self.rpo[to] <= self.rpo[from] {
  10584. return target;
  10585. }
  10586. let e = self.s.m.new_block();
  10587. self.s.m.terminate(e, Term::Br(target));
  10588. self.edges.insert((from, to), e);
  10589. e
  10590. }
  10591. fn fill_phis(&mut self) -> Result<(), Stop> {
  10592. let p = self.x.p;
  10593. // Lane-mask joins first (what an edge brings may ask for more joins,
  10594. // of masks and of numbers): each edge's mask as the structure
  10595. // tracked it, a constant or a scalar-built one included.
  10596. let st = self.x.st;
  10597. while let Some((v, b, i)) = self.pending_masks.pop() {
  10598. let phi = &p.blocks[b].phis[i];
  10599. let offset = p.blocks[b].offset;
  10600. let args = st
  10601. .phi_masks
  10602. .get(&phi.value)
  10603. .ok_or_else(|| unsupported(offset, "a lane-mask join of an untracked mask"))?;
  10604. let mut incoming = Vec::new();
  10605. for (n, &q) in p.blocks[b].preds.iter().enumerate() {
  10606. let Some(qb) = self.tail[q] else { continue };
  10607. let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb);
  10608. let x = self.boolean(args[n], qb).map_err(|w| unsupported(offset, w))?;
  10609. incoming.push((x, qb));
  10610. }
  10611. self.s.m.set_phi(v, incoming);
  10612. }
  10613. // A join that only another join reads is read wherever that one is. Left
  10614. // unmarked, a value without a DXIL form coming into it became zero without a
  10615. // word (the looked-up tint of the material resolve programs, whose size
  10616. // computation had no value, was zero in every lane that way).
  10617. // shortcut: only with `VICTORY_STRICT_JOINS` set (the offline pack
  10618. // listing sets it to count them): 40 programs that translate today
  10619. // stop by name with it (vehicle paint pixel shaders at "the first
  10620. // half of an interpolation", foliage mesh shaders); until those are
  10621. // lowered they keep drawing with that zero.
  10622. static STRICT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  10623. let strict = *STRICT.get_or_init(|| std::env::var_os("VICTORY_STRICT_JOINS").is_some());
  10624. let mut work: Vec<Value> = if strict {
  10625. self.read_phis.iter().copied().collect()
  10626. } else {
  10627. Vec::new()
  10628. };
  10629. while let Some(v) = work.pop() {
  10630. let Some(&(b, i)) = self.phi_at.get(&v) else {
  10631. continue;
  10632. };
  10633. for &a in &p.blocks[b].phis[i].args {
  10634. if self.phi_at.contains_key(&a) && self.read_phis.insert(a) {
  10635. work.push(a);
  10636. }
  10637. }
  10638. }
  10639. for (v, b, i) in std::mem::take(&mut self.data_phis) {
  10640. let phi = &p.blocks[b].phis[i];
  10641. let bit = phi.reg == Reg::Scc;
  10642. // A join of numbers with dead registers (`dead`): the paths that bring those
  10643. // never read the result, so they bring zero. Not for a join that is itself a
  10644. // lane mask (a ballot gives that one as data).
  10645. let st = self.x.st;
  10646. let numbers = !bit
  10647. && !st.masks.contains_key(&phi.value)
  10648. && !st.highs.contains_key(&phi.value)
  10649. && phi
  10650. .args
  10651. .iter()
  10652. .any(|a| matches!(self.vals.get(a), Some(Val::I32(_))));
  10653. let mut incoming = Vec::new();
  10654. for (n, &q) in p.blocks[b].preds.iter().enumerate() {
  10655. let Some(qb) = self.tail[q] else { continue };
  10656. let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb);
  10657. let arg = phi.args[n];
  10658. if self.read_phis.contains(&phi.value) && !self.vals.contains_key(&arg) {
  10659. let _ = self.lazy_barycentric(arg);
  10660. // A root parameter nothing read before the join (user
  10661. // data is loaded on first use, in the entry block).
  10662. if !self.vals.contains_key(&arg)
  10663. && let Some(&(param, dword)) = self.params.get(&arg)
  10664. {
  10665. let val = self.user(param, dword);
  10666. self.vals.insert(arg, val);
  10667. }
  10668. }
  10669. let x = match (self.vals.get(&arg).copied(), bit) {
  10670. (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x,
  10671. (Some(Val::Missing(_)) | None, false)
  10672. if numbers && self.dead(arg, &mut Vec::new()) =>
  10673. {
  10674. self.s.m.i32(0)
  10675. }
  10676. // A lane mask joined with numbers (a traversal that keeps its lanes' masks on
  10677. // a stack with its node numbers): the mask comes as the number it is, the
  10678. // ballot of its lanes where it is written.
  10679. (Some(Val::Missing(_)) | None, false)
  10680. if self.read_phis.contains(&phi.value)
  10681. && self.mask_data == MaskData::Console
  10682. && (st.masks.contains_key(&arg) || st.highs.contains_key(&arg)) =>
  10683. {
  10684. match self.mask_dword(arg) {
  10685. Ok(x) => x,
  10686. Err(why) => return Err(Stop::Retry(phi.value, why)),
  10687. }
  10688. }
  10689. // SCC of a mask operation ("some lane is left") joined with a scalar test:
  10690. // the compiler branches around code that sets SCC and tests SCC after it,
  10691. // the skip bringing "no lane" along. As data it is "some lane of the wave
  10692. // has the bit" - right only if the wave took that skip together, as the
  10693. // console does: a lane that skipped alone would bring "some lane" where the
  10694. // console has the skipped code's SCC. So the branch must be one the wave
  10695. // takes together; else its region is named for `emit`'s retry to widen it.
  10696. (Some(Val::Missing(_)) | None, true)
  10697. if self.read_phis.contains(&phi.value)
  10698. && self.mask_data == MaskData::Console
  10699. && st.scc_some.contains_key(&arg) =>
  10700. {
  10701. let per_lane = !st.wide.contains(&q)
  10702. && matches!(st.exits[q], LaneExit::Branch { when, .. }
  10703. if !st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))));
  10704. if per_lane {
  10705. for &other in p.blocks[b].preds.iter().filter(|&&o| o != q) {
  10706. need(other);
  10707. }
  10708. return Err(Stop::Retry(phi.value, LANE_MASK));
  10709. }
  10710. match self.scc_some(arg) {
  10711. Ok(x) => x,
  10712. Err(why) => return Err(Stop::Retry(phi.value, why)),
  10713. }
  10714. }
  10715. (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => {
  10716. return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values"));
  10717. }
  10718. (Some(Val::Missing(why)), _) if self.read_phis.contains(&phi.value) => {
  10719. return Err(Stop::Retry(phi.value, why));
  10720. }
  10721. _ if self.read_phis.contains(&phi.value) => {
  10722. return Err(Stop::Retry(phi.value, "a join of mismatched values"));
  10723. }
  10724. _ if bit => self.s.m.bool(false),
  10725. _ => self.s.m.i32(0),
  10726. };
  10727. incoming.push((x, qb));
  10728. }
  10729. self.s.m.set_phi(v, incoming);
  10730. }
  10731. for (phi, incoming) in std::mem::take(&mut self.counters).into_values() {
  10732. self.s.m.set_phi(phi, incoming);
  10733. }
  10734. Ok(())
  10735. }
  10736. }
  10737. /// The DXIL interpolation mode of a kind of barycentrics (none for the
  10738. /// pull model).
  10739. fn interp_mode(kind: Barycentric) -> Option<u8> {
  10740. Some(match kind {
  10741. Barycentric::PerspectiveCenter => 2,
  10742. Barycentric::PerspectiveCentroid => 3,
  10743. Barycentric::PerspectiveSample => 6,
  10744. Barycentric::LinearCenter => 4,
  10745. Barycentric::LinearCentroid => 5,
  10746. Barycentric::LinearSample => 7,
  10747. Barycentric::PerspectivePullModel => return None,
  10748. })
  10749. }
  10750. #[cfg(test)]
  10751. mod tests {
  10752. use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower};
  10753. use crate::native::{
  10754. ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
  10755. };
  10756. use crate::{io, ir, resource, structure};
  10757. const S_ENDPGM: u32 = 0xBF81_0000;
  10758. #[test]
  10759. fn packed_pixel_inputs_find_their_second_row() {
  10760. use super::super::container::SigElement;
  10761. use super::half_input_partners;
  10762. use crate::native::{PsInput, Usage};
  10763. let entry = |row, row2, pack2| PsInput {
  10764. usage: Usage::Generic,
  10765. row,
  10766. mask: 0xF,
  10767. attr: row,
  10768. flat: false,
  10769. fp16: true,
  10770. pack2,
  10771. row2,
  10772. };
  10773. let element = |row| SigElement {
  10774. name: "TEXCOORD".into(),
  10775. index: row,
  10776. kind: 0,
  10777. comp: 9,
  10778. interp: 2,
  10779. row: Some(row),
  10780. col: 0,
  10781. cols: 4,
  10782. usage: 0,
  10783. half: true,
  10784. };
  10785. // Rows 0 and 3 pack and leave their second row out; 5 names its
  10786. // own (6). Unnamed 16-bit rows: 1, 4, 6, 7.
  10787. let io = StageIo::Ps {
  10788. inputs: vec![entry(0, 0, true), entry(3, 3, true), entry(5, 6, true)],
  10789. input_addr: 0,
  10790. db_shader_control: 0,
  10791. patches: vec![],
  10792. };
  10793. let sig: Vec<_> = [0, 1, 3, 4, 5, 6, 7].map(element).into();
  10794. let p = half_input_partners(&io, &sig);
  10795. assert_eq!(p.get(&0), Some(&1));
  10796. assert_eq!(p.get(&3), Some(&4));
  10797. assert_eq!(p.get(&5), None);
  10798. }
  10799. /// The packed pedestrian layouts of Grand Theft Auto VI: an element
  10800. /// behind another one in its register follows in the first parameter
  10801. /// with a dword left, and is not a half of its register's row.
  10802. #[test]
  10803. fn packed_elements_behind_another_take_the_first_free_dword() {
  10804. use super::super::container::SigElement;
  10805. use super::packed_half;
  10806. let element = |index, row, col, cols| SigElement {
  10807. name: "TEXCOORD".into(),
  10808. index,
  10809. kind: 0,
  10810. comp: 9,
  10811. interp: 2,
  10812. row: Some(row),
  10813. col,
  10814. cols,
  10815. usage: 0,
  10816. half: true,
  10817. };
  10818. // MS_VS_PedTransformPreSkinD_Packed 005fe88ec1bdc0c7 and its pixel
  10819. // shader 93667197d3d05e1c: TEXCOORD6 is one value at register 4
  10820. // column 3; parameter 3 (rows 6 and 7) carries it in dword 3.
  10821. let sig = vec![
  10822. element(1, 2, 0, 4),
  10823. element(2, 3, 0, 4),
  10824. element(4, 4, 0, 3),
  10825. element(6, 4, 3, 1),
  10826. element(3, 5, 0, 4),
  10827. element(5, 6, 0, 4),
  10828. element(7, 7, 0, 2),
  10829. element(9, 9, 0, 3),
  10830. element(11, 10, 0, 3),
  10831. element(15, 12, 0, 4),
  10832. ];
  10833. let packs = [
  10834. (2, Some(3)),
  10835. (4, Some(5)),
  10836. (6, Some(7)),
  10837. (9, Some(10)),
  10838. (12, None),
  10839. ];
  10840. let at = |a, h| packed_half(&sig, &packs, a, h);
  10841. // Parameter 2: TEXCOORD4's three values, a zero half, TEXCOORD3.
  10842. assert_eq!(at(4, 2), Some((4, 2)));
  10843. assert_eq!(at(4, 3), None);
  10844. assert_eq!(at(4, 4), Some((5, 0)));
  10845. assert_eq!(at(4, 7), Some((5, 3)));
  10846. // Parameter 3: TEXCOORD5, TEXCOORD7, then TEXCOORD6 alone.
  10847. assert_eq!(at(6, 3), Some((6, 3)));
  10848. assert_eq!(at(6, 5), Some((7, 1)));
  10849. assert_eq!(at(6, 6), Some((4, 3)));
  10850. assert_eq!(at(6, 7), None);
  10851. // Parameters without such an element are as before.
  10852. assert_eq!(at(9, 3), None);
  10853. assert_eq!(at(9, 4), Some((10, 0)));
  10854. assert_eq!(at(12, 3), Some((12, 3)));
  10855. assert_eq!(at(12, 4), None);
  10856. // The common layout (29805d23a495cdf8): TEXCOORD7 is two values at
  10857. // register 1 columns 2-3; parameter 0 is TEXCOORD0, TEXCOORD1,
  10858. // TEXCOORD7.
  10859. let sig = vec![
  10860. element(0, 1, 0, 2),
  10861. element(7, 1, 2, 2),
  10862. element(1, 2, 0, 4),
  10863. element(2, 3, 0, 4),
  10864. element(4, 4, 0, 3),
  10865. ];
  10866. let packs = [(3, Some(4)), (1, Some(2))];
  10867. let at = |a, h| packed_half(&sig, &packs, a, h);
  10868. assert_eq!(at(1, 1), Some((1, 1)));
  10869. assert_eq!(at(1, 2), Some((2, 0)));
  10870. assert_eq!(at(1, 5), Some((2, 3)));
  10871. assert_eq!(at(1, 6), Some((1, 2)));
  10872. assert_eq!(at(1, 7), Some((1, 3)));
  10873. assert_eq!(at(3, 6), Some((4, 2)));
  10874. assert_eq!(at(3, 7), None);
  10875. // A row no element holds gives nothing, as before.
  10876. assert_eq!(packed_half(&sig, &[(8, None)], 8, 0), None);
  10877. }
  10878. /// Whether a synthetic compute program translates with these input registers.
  10879. fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> {
  10880. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  10881. let native = NativeProgram {
  10882. stage: HwStage::Cs,
  10883. wave64: false,
  10884. vgprs: 256,
  10885. layout: vec![],
  10886. used: vec![],
  10887. io: StageIo::Cs(ComputeIo {
  10888. rsrc2,
  10889. threads: [1, 1, 1],
  10890. }),
  10891. code,
  10892. };
  10893. let p = ir::build(&native.code, false, 256).unwrap();
  10894. let st = structure::structure(&p).unwrap();
  10895. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  10896. let io = io::raise(&p, &native).unwrap();
  10897. lower(&Parts {
  10898. native: &native,
  10899. p: &p,
  10900. st: &st,
  10901. io: &io,
  10902. res: &res,
  10903. inputs: vec![],
  10904. outputs: vec![],
  10905. prims: vec![],
  10906. mesh_stride: 0,
  10907. })
  10908. .map(|_| ())
  10909. }
  10910. /// Lowers a compute program with the root parameters `layout` (in user
  10911. /// SGPRs from s0 on) and the used resources `used`.
  10912. fn lower_with(
  10913. words: &[u32],
  10914. layout: Vec<RootParam>,
  10915. used: Vec<UsedResource>,
  10916. ) -> Result<Lowered, crate::ShaderError> {
  10917. lower_wave(words, layout, used, false)
  10918. }
  10919. /// [`lower_with`] in wave64 if `wave64`.
  10920. fn lower_wave(
  10921. words: &[u32],
  10922. layout: Vec<RootParam>,
  10923. used: Vec<UsedResource>,
  10924. wave64: bool,
  10925. ) -> Result<Lowered, crate::ShaderError> {
  10926. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  10927. let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum();
  10928. let native = NativeProgram {
  10929. stage: HwStage::Cs,
  10930. wave64,
  10931. vgprs: 256,
  10932. layout,
  10933. used,
  10934. io: StageIo::Cs(ComputeIo {
  10935. // The layout's user SGPRs (at least two), 512 bytes of LDS.
  10936. rsrc2: 1 << 15 | sgprs.max(2) << 1,
  10937. threads: [1, 1, 1],
  10938. }),
  10939. code,
  10940. };
  10941. let p = ir::build(&native.code, wave64, 256).unwrap();
  10942. let st = structure::structure(&p).unwrap();
  10943. let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
  10944. let io = io::raise(&p, &native).unwrap();
  10945. lower(&Parts {
  10946. native: &native,
  10947. p: &p,
  10948. st: &st,
  10949. io: &io,
  10950. res: &res,
  10951. inputs: vec![],
  10952. outputs: vec![],
  10953. prims: vec![],
  10954. mesh_stride: 0,
  10955. })
  10956. }
  10957. /// Root parameter `slot` in user SGPRs from `user_data` on.
  10958. fn root(root: RootType, user_data: u8, slot: u8) -> RootParam {
  10959. RootParam {
  10960. root,
  10961. table_offset_dwords: 0,
  10962. sgprs: if root == RootType::Descriptor { 2 } else { 1 },
  10963. base_register: 0,
  10964. user_data,
  10965. slot,
  10966. }
  10967. }
  10968. #[test]
  10969. fn buffer_cache_invalidations_lower_as_no_ops() {
  10970. // MUBUF opcode 0x071/0x072 with no data operand: the title asks the
  10971. // host to invalidate its cached view of a buffer.
  10972. assert!(lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl0_inv");
  10973. assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv");
  10974. }
  10975. #[test]
  10976. fn a_scalar_carry_chain_reaches_the_select() {
  10977. // The high dword of a 64-bit add or subtract, then a select on the
  10978. // carry (borrow) the high half leaves in SCC, and a branch on it
  10979. // (only code with an effect needs its operands).
  10980. let add = [
  10981. 0xBE80_03C1, // s_mov_b32 s0, -1
  10982. 0xBE81_0380, // s_mov_b32 s1, 0
  10983. 0x8000_8100, // s_add_u32 s0, s0, 1
  10984. 0x8201_8001, // s_addc_u32 s1, s1, 0
  10985. 0x8502_0001, // s_cselect_b32 s2, s1, s0
  10986. 0xBF07_8002, // s_cmp_lg_u32 s2, 0
  10987. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  10988. 0xBE83_0380, // s_mov_b32 s3, 0
  10989. S_ENDPGM,
  10990. ];
  10991. let sub = [
  10992. 0xBE80_0380, // s_mov_b32 s0, 0
  10993. 0xBE81_0380, // s_mov_b32 s1, 0
  10994. 0x8080_8100, // s_sub_u32 s0, s0, 1
  10995. 0x8281_8001, // s_subb_u32 s1, s1, 0
  10996. 0x8502_0001, // s_cselect_b32 s2, s1, s0
  10997. 0xBF07_8002, // s_cmp_lg_u32 s2, 0
  10998. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  10999. 0xBE83_0380, // s_mov_b32 s3, 0
  11000. S_ENDPGM,
  11001. ];
  11002. for words in [add, sub] {
  11003. lowers(&words, 0).unwrap();
  11004. }
  11005. }
  11006. fn perm_features(selector: u32) -> u64 {
  11007. // Synthetic compute shader:
  11008. // v0 is the thread ID and can supply a dynamic selector.
  11009. // Store the result in LDS to keep the permutation live.
  11010. let words = [
  11011. 0x7E02_02FFu32,
  11012. 0x817F_34AB,
  11013. 0x7E04_02FF,
  11014. 0xFE01_56CD,
  11015. 0xD744_0003,
  11016. 257 | (258 << 9) | (selector << 18),
  11017. 0x3408_0082,
  11018. 0xD834_0000,
  11019. 0x0000_0304,
  11020. S_ENDPGM,
  11021. ];
  11022. let code: Vec<u8> = words.iter()
  11023. .flat_map(|w| w.to_le_bytes())
  11024. .collect();
  11025. let native = NativeProgram {
  11026. stage: HwStage::Cs,
  11027. wave64: false,
  11028. vgprs: 256,
  11029. layout: vec![],
  11030. used: vec![],
  11031. io: StageIo::Cs(ComputeIo {
  11032. rsrc2: 1 << 15,
  11033. threads: [64, 1, 1],
  11034. }),
  11035. code,
  11036. };
  11037. let p = ir::build(&native.code, false, 256).unwrap();
  11038. assert!(p.blocks.iter()
  11039. .flat_map(|b| &b.insts)
  11040. .any(|i| i.name() == "v_perm_b32"));
  11041. let st = structure::structure(&p).unwrap();
  11042. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  11043. let io = io::raise(&p, &native).unwrap();
  11044. let emitted = lower(&Parts {
  11045. native: &native,
  11046. p: &p,
  11047. st: &st,
  11048. io: &io,
  11049. res: &res,
  11050. inputs: vec![],
  11051. outputs: vec![],
  11052. prims: vec![],
  11053. mesh_stride: 0,
  11054. }).unwrap();
  11055. let container =
  11056. crate::Container::parse(&emitted.dxil).unwrap();
  11057. let features =
  11058. container.part(crate::FourCC::SFI0).unwrap();
  11059. u64::from_le_bytes(features.data.try_into().unwrap())
  11060. }
  11061. #[test]
  11062. fn perm_constant_selector_needs_no_int64() {
  11063. assert_eq!(perm_features(128) & 0x8000, 0);
  11064. }
  11065. #[test]
  11066. fn perm_dynamic_selector_needs_no_int64() {
  11067. assert_eq!(
  11068. perm_features(256) & 0x8000,
  11069. 0,
  11070. "dynamic v_perm_b32 must not require INT64"
  11071. );
  11072. }
  11073. #[test]
  11074. fn a_descriptor_selected_by_scc_picks_its_heap_index() {
  11075. // Two buffer descriptors loaded from the table at s0, one picked by
  11076. // a root constant (s1) with s_cselect_b64 per half, and loaded
  11077. // through by index and stored to LDS so the load is needed.
  11078. let words = [
  11079. 0xBE84_0300, // s_mov_b32 s4, s0
  11080. 0xBE85_0380, // s_mov_b32 s5, 0
  11081. 0xF408_0202,
  11082. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null
  11083. 0xF408_0302,
  11084. 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10
  11085. 0xBF06_8001, // s_cmp_eq_u32 s1, 0
  11086. 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13]
  11087. 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15]
  11088. 0xE030_2000,
  11089. 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen
  11090. 0xD834_0000,
  11091. 0x0000_0100, // ds_write_b32 v0, v1
  11092. S_ENDPGM,
  11093. ];
  11094. let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)];
  11095. // Both are structured buffers of dwords in the table's range.
  11096. let used = || {
  11097. vec![UsedResource {
  11098. kind: ResourceType::Srv,
  11099. root: RootType::Table,
  11100. table_offset_dwords: 0,
  11101. lower_bound: 0,
  11102. stride: 4,
  11103. dwords: 4,
  11104. user_data: 0,
  11105. slot: 0,
  11106. }]
  11107. };
  11108. lower_with(&words, layout(), used()).unwrap();
  11109. }
  11110. /// Tables of 2D textures at s0 and samplers at s1.
  11111. fn texture_tables() -> (Vec<RootParam>, Vec<UsedResource>) {
  11112. let range = |kind, user_data, slot| UsedResource {
  11113. kind,
  11114. root: RootType::Table,
  11115. table_offset_dwords: 0,
  11116. lower_bound: 0,
  11117. stride: 0,
  11118. dwords: if kind == ResourceType::Sampler { 4 } else { 8 },
  11119. user_data,
  11120. slot,
  11121. };
  11122. (
  11123. vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)],
  11124. vec![
  11125. range(ResourceType::Srv, 0, 0),
  11126. range(ResourceType::Sampler, 1, 1),
  11127. ],
  11128. )
  11129. }
  11130. #[test]
  11131. fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() {
  11132. use crate::resource::tests::{
  11133. WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32,
  11134. };
  11135. for (words, wave64) in [
  11136. (WATERFALL_FETCHED_WAVE32, false),
  11137. (WATERFALL_FETCHED_WAVE64, true),
  11138. (WATERFALL_PICKED_WAVE32, false),
  11139. ] {
  11140. let (layout, used) = texture_tables();
  11141. let l = lower_wave(words, layout, used, wave64).unwrap();
  11142. // The loop's reads of the first lane became each lane's own
  11143. // dwords: no wave operation is left.
  11144. assert_eq!(l.nonuniform_handles, 1);
  11145. assert!(!l.wave_ops);
  11146. }
  11147. }
  11148. /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first.
  11149. pub(crate) fn texture_and_uav_tables() -> (Vec<RootParam>, Vec<UsedResource>) {
  11150. let (layout, mut used) = texture_tables();
  11151. used.push(UsedResource {
  11152. kind: ResourceType::Uav,
  11153. root: RootType::Table,
  11154. table_offset_dwords: 16,
  11155. lower_bound: 0,
  11156. stride: 0,
  11157. dwords: 4,
  11158. user_data: 0,
  11159. slot: 0,
  11160. });
  11161. (layout, used)
  11162. }
  11163. #[test]
  11164. fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() {
  11165. use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32};
  11166. for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] {
  11167. let (layout, used) = texture_and_uav_tables();
  11168. let l = lower_wave(words, layout, used, false).unwrap();
  11169. // One image handle, from the join's per-lane heap index.
  11170. assert_eq!(l.nonuniform_handles, 1);
  11171. assert!(!l.wave_ops);
  11172. }
  11173. }
  11174. #[test]
  11175. fn scalar_bit_tests_lower() {
  11176. // Each tests one bit of a constant into SCC and branches on it (only
  11177. // code with an effect needs its operands).
  11178. let tail = [
  11179. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  11180. 0xBE84_0380, // s_mov_b32 s4, 0
  11181. S_ENDPGM,
  11182. ];
  11183. let bit_tests: [&[u32]; 4] = [
  11184. &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3
  11185. &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3
  11186. &[
  11187. 0xBE80_0387, // s_mov_b32 s0, 7
  11188. 0xBE81_0380, // s_mov_b32 s1, 0
  11189. 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3
  11190. ],
  11191. &[
  11192. 0xBE80_0387, // s_mov_b32 s0, 7
  11193. 0xBE81_0380, // s_mov_b32 s1, 0
  11194. 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3
  11195. ],
  11196. ];
  11197. for head in bit_tests {
  11198. let words: Vec<u32> = head.iter().chain(&tail).copied().collect();
  11199. lowers(&words, 0).unwrap();
  11200. }
  11201. }
  11202. #[test]
  11203. #[ignore = "ours marks joins read through joins only with VICTORY_STRICT_JOINS (40 programs stop otherwise)"]
  11204. fn a_missing_value_stays_missing_through_two_live_joins() {
  11205. let mut words = [
  11206. 0xF490_0180,
  11207. 0, // s_memtime s[6:7]
  11208. 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X)
  11209. 0xBF85_0001, // skip the first overwrite
  11210. 0xBE86_0380, // s_mov_b32 s6, 0
  11211. 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y)
  11212. 0xBF85_0001, // skip the second overwrite
  11213. 0xBE86_0381, // s_mov_b32 s6, 1
  11214. 0xBF07_8006, // s_cmp_lg_u32 s6, 0
  11215. 0xBF85_0001, // use the result to branch
  11216. 0xBE83_0380,
  11217. S_ENDPGM,
  11218. ];
  11219. let group_ids_xy = 3 << 7;
  11220. // Compare to a direct read so future timestamp support works in both cases.
  11221. let refusal = |code: &[u32]| match lowers(code, group_ids_xy) {
  11222. Ok(()) => None,
  11223. Err(crate::ShaderError::Unsupported { what, .. }) => Some(what),
  11224. Err(error) => panic!("{error}"),
  11225. };
  11226. let direct = [&words[..2], &words[8..]].concat();
  11227. assert_eq!(refusal(&words), refusal(&direct));
  11228. words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead
  11229. lowers(&words, group_ids_xy).expect("dead timestamp");
  11230. }
  11231. #[test]
  11232. fn buffer_formats_by_number() {
  11233. // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM,
  11234. // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT.
  11235. assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm)));
  11236. assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm)));
  11237. assert_eq!(
  11238. buffer_format(50),
  11239. Some((&[10, 10, 10, 2][..], Numeric::Unorm))
  11240. );
  11241. assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float)));
  11242. assert_eq!(
  11243. buffer_format(77),
  11244. Some((&[32, 32, 32, 32][..], Numeric::Float))
  11245. );
  11246. // Invalid, past the table.
  11247. assert_eq!(buffer_format(0), None);
  11248. assert_eq!(buffer_format(78), None);
  11249. }
  11250. #[test]
  11251. fn packed_buffer_formats_by_number() {
  11252. // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43,
  11253. // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT
  11254. // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first.
  11255. assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm)));
  11256. assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float)));
  11257. assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm)));
  11258. assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float)));
  11259. assert_eq!(
  11260. buffer_format(44),
  11261. Some((&[2, 10, 10, 10][..], Numeric::Unorm))
  11262. );
  11263. assert_eq!(
  11264. buffer_format(45),
  11265. Some((&[2, 10, 10, 10][..], Numeric::Snorm))
  11266. );
  11267. assert_eq!(
  11268. buffer_format(46),
  11269. Some((&[2, 10, 10, 10][..], Numeric::Uscaled))
  11270. );
  11271. assert_eq!(
  11272. buffer_format(47),
  11273. Some((&[2, 10, 10, 10][..], Numeric::Sscaled))
  11274. );
  11275. assert_eq!(
  11276. buffer_format(48),
  11277. Some((&[2, 10, 10, 10][..], Numeric::Uint))
  11278. );
  11279. assert_eq!(
  11280. buffer_format(49),
  11281. Some((&[2, 10, 10, 10][..], Numeric::Sint))
  11282. );
  11283. }
  11284. /// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as
  11285. /// `legacyF16ToF32` widens it.
  11286. fn half(h: u32) -> f32 {
  11287. let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023);
  11288. let v = match e {
  11289. 0 => m as f32 * 2f32.powi(-24),
  11290. 31 if m == 0 => f32::INFINITY,
  11291. 31 => f32::NAN,
  11292. _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25),
  11293. };
  11294. if s == 1 { -v } else { v }
  11295. }
  11296. #[test]
  11297. fn small_floats_widen_as_halves() {
  11298. // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a
  11299. // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec.
  11300. let f11 = |x: u32| half(x << half_shift(11));
  11301. let f10 = |x: u32| half(x << half_shift(10));
  11302. assert_eq!(f11(0), 0.0);
  11303. assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal
  11304. assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal
  11305. assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal
  11306. assert_eq!(f11(0x3C0), 1.0);
  11307. assert_eq!(f11(0x3E0), 1.5);
  11308. assert_eq!(f11(0x7BF), 65024.0); // largest
  11309. assert_eq!(f11(0x7C0), f32::INFINITY);
  11310. assert!(f11(0x7C1).is_nan());
  11311. assert_eq!(f10(0x001), 2f32.powi(-19));
  11312. assert_eq!(f10(0x020), 2f32.powi(-14));
  11313. assert_eq!(f10(0x1E0), 1.0);
  11314. assert_eq!(f10(0x3DF), 64512.0);
  11315. assert_eq!(f10(0x3E0), f32::INFINITY);
  11316. assert!(f10(0x3FF).is_nan());
  11317. // A 16-bit float is a half already, sign included.
  11318. assert_eq!(half(0xBC00 << half_shift(16)), -1.0);
  11319. }
  11320. }