lower.rs 521 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340
  1. //! IR to DXIL, one machine instruction at a time (decision 0003).
  2. //!
  3. //! Every register dword is an `i32` (SCC an `i1`); float operations bitcast
  4. //! their operands. Lane masks exist only as the per-lane booleans of
  5. //! structurisation; branches and guards are built from them. A value the
  6. //! emitter cannot express is `Missing` with a reason, and only fails the
  7. //! program when something with an effect (an export, a branch) needs it.
  8. use std::collections::{BTreeMap, HashMap, HashSet};
  9. use super::UserData;
  10. use super::bitcode::{Attr, Bin, Cast, Rmw, Tag, Term, V, pred};
  11. use super::container::SigElement;
  12. use super::shader::{Shader, flags};
  13. use crate::ShaderError;
  14. use crate::gfx10::{Dpp, Fields, NULL, Operand};
  15. use crate::io::{Barycentric, Export, Input, Interp, Io, Target};
  16. use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value};
  17. use crate::native::{HwStage, NativeProgram, ResourceType, RootType, StageIo, Usage, UsedResource};
  18. use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source};
  19. use crate::structure::{Atom, Bool, LaneExit, Structured};
  20. /// The ray-tracing node test (`image_bvh_intersect_ray`), a child module so
  21. /// it shares the emitter's state.
  22. #[path = "intersect.rs"]
  23. pub(super) mod intersect;
  24. type Why = &'static str;
  25. /// How an interpolation evaluates an input channel.
  26. #[derive(Debug, Clone, Copy)]
  27. enum Eval {
  28. /// Loaded with this DXIL interpolation mode (1: constant, P0).
  29. Mode(u8),
  30. /// From the vertex values of a constant element: P0 when `p0`, plus
  31. /// i (P1 - P0), plus j (P2 - P0), weights as floats.
  32. Weights {
  33. p0: bool,
  34. i: Option<V>,
  35. j: Option<V>,
  36. },
  37. }
  38. #[derive(Debug, Clone, Copy)]
  39. enum Val {
  40. I32(V),
  41. Bit(V),
  42. Missing(Why),
  43. }
  44. pub(crate) struct Lowered {
  45. pub dxil: Vec<u8>,
  46. /// Bit n: immediate sampler n is 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. /// `s_sendmsg` id that ends a pixel wave's ordered section.
  100. const ORDERED_PS_DONE: u16 = 7;
  101. /// Hardware register (of `s_setreg_b32`) a pixel wave names its packer in
  102. /// before it waits for the waves it overlaps.
  103. const POPS_PACKER: u16 = 25;
  104. /// The operand `src_pops_exiting_wave_id`.
  105. const POPS_EXITING: u8 = 239;
  106. /// The instructions inside a pixel program's ordered section
  107. /// (primitive-ordered pixel shading, which the console compiler makes of
  108. /// rasterizer ordered views): from the write of `POPS_PACKER`, along every
  109. /// path, to the message that ends the section or the program's end. The
  110. /// console waits there until the waves holding earlier primitives' samples
  111. /// of the same pixels have left their sections; a host's rasterizer ordered
  112. /// views wait by themselves, at their first access. Empty for a program
  113. /// without such a section.
  114. fn ordered_section(p: &Program) -> HashSet<Site> {
  115. let starts = |i: &Inst| {
  116. i.name() == "s_setreg_b32"
  117. && matches!(i.fields, Fields::Sop { imm: Some(imm), .. } if imm & 0x3F == POPS_PACKER)
  118. };
  119. let ends = |i: &Inst| {
  120. i.name() == "s_sendmsg"
  121. && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == ORDERED_PS_DONE)
  122. };
  123. let mut section = HashSet::new();
  124. let mut entered = vec![false; p.blocks.len()];
  125. let mut work: Vec<Site> = p
  126. .blocks
  127. .iter()
  128. .enumerate()
  129. .flat_map(|(b, block)| {
  130. (0..block.insts.len())
  131. .filter(|&i| starts(&block.insts[i]))
  132. .map(move |i| (b, i))
  133. })
  134. .collect();
  135. while let Some((b, from)) = work.pop() {
  136. let block = &p.blocks[b];
  137. let mut done = false;
  138. for i in from..block.insts.len() {
  139. if ends(&block.insts[i]) {
  140. done = true;
  141. break;
  142. }
  143. section.insert((b, i));
  144. }
  145. if done {
  146. continue;
  147. }
  148. for (t, next) in p.blocks.iter().enumerate() {
  149. if next.preds.contains(&b) && !std::mem::replace(&mut entered[t], true) {
  150. work.push((t, 0));
  151. }
  152. }
  153. }
  154. section
  155. }
  156. /// The f16 bits of inline float constant `c` (240..=248: 0.5, -0.5, 1.0,
  157. /// -1.0, 2.0, -2.0, 4.0, -4.0, 1/(2 pi)).
  158. fn inline_f16(c: u8) -> u32 {
  159. [
  160. 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118,
  161. ][usize::from(c - 240)]
  162. }
  163. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  164. enum Numeric {
  165. Unorm,
  166. Snorm,
  167. Uscaled,
  168. Sscaled,
  169. Uint,
  170. Sint,
  171. Float,
  172. }
  173. /// A GFX10 buffer format (the unified format of typed buffer loads): the
  174. /// channel widths from the lowest bits up, and how the channels convert.
  175. /// Formats are numbered in families (`8`, `16`, `8_8`, ...: AMD names
  176. /// list channels from the highest bits), each with its numeric formats in
  177. /// the order unorm, snorm, uscaled, sscaled, uint, sint, float.
  178. fn buffer_format(format: u8) -> Option<(&'static [u32], Numeric)> {
  179. use Numeric::*;
  180. const NORM: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint];
  181. const ALL: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint, Float];
  182. const WIDE: &[Numeric] = &[Uint, Sint, Float];
  183. // Numbers and order from LLVM's `UfmtGFX10` (`SIDefines.h`); the GFX10
  184. // buffer formats have no 5_9_9_9. Channel order from Mesa
  185. // (`ac_formats.c`): R11G11B10_FLOAT is 10_11_11, and 10_10_10_2 has
  186. // its 2-bit channel in the lowest bits.
  187. const FAMILIES: [(&[u32], &[Numeric]); 14] = [
  188. (&[8], NORM),
  189. (&[16], ALL),
  190. (&[8, 8], NORM),
  191. (&[32], WIDE),
  192. (&[16, 16], ALL),
  193. (&[11, 11, 10], ALL), // 10_11_11
  194. (&[10, 11, 11], ALL), // 11_11_10
  195. (&[2, 10, 10, 10], NORM), // 10_10_10_2
  196. (&[10, 10, 10, 2], NORM), // 2_10_10_10
  197. (&[8, 8, 8, 8], NORM),
  198. (&[32, 32], WIDE),
  199. (&[16, 16, 16, 16], ALL),
  200. (&[32, 32, 32], WIDE),
  201. (&[32, 32, 32, 32], WIDE),
  202. ];
  203. let mut n = usize::from(format.checked_sub(1)?);
  204. for (bits, numerics) in FAMILIES {
  205. if n < numerics.len() {
  206. return Some((bits, numerics[n]));
  207. }
  208. n -= numerics.len();
  209. }
  210. None
  211. }
  212. /// How far a float channel of `width` bits (16, or the unsigned 11- and
  213. /// 10-bit floats of the packed formats) shifts up to be a half:
  214. /// the small floats are a half's exponent (5 bits, biased 15) and the top
  215. /// of its mantissa, without the sign, so `legacyF16ToF32` widens them
  216. /// exactly, denormals, infinities and NaNs included.
  217. fn half_shift(width: u32) -> u32 {
  218. debug_assert!(matches!(width, 10 | 11 | 16), "{width}-bit float");
  219. if width == 16 { 0 } else { 15 - width }
  220. }
  221. struct Lower<'a> {
  222. s: Shader,
  223. x: &'a Parts<'a>,
  224. bad: &'a HashMap<Value, Why>,
  225. lane_fail: HashMap<Value, Why>,
  226. vals: HashMap<Value, Val>,
  227. floats: HashMap<Value, V>,
  228. /// DXIL block per IR block (unreachable: none).
  229. block: Vec<Option<usize>>,
  230. cur: usize,
  231. bools: HashMap<(usize, Bool), V>,
  232. lane_bits: HashMap<Value, V>,
  233. /// IR phi location by value.
  234. phi_at: HashMap<Value, (usize, usize)>,
  235. /// Descriptor dwords with no host value (addresses, formats, all of a constant
  236. /// buffer's): no program reads them as numbers ([`Self::dead`]).
  237. stale: HashSet<Value>,
  238. /// See [`ordered_section`] (pixel programs).
  239. ordered: HashSet<Site>,
  240. mask_phis: HashMap<Value, V>,
  241. pending_masks: Vec<(V, usize, usize)>,
  242. data_phis: Vec<(V, usize, usize)>,
  243. read_phis: HashSet<Value>,
  244. params: HashMap<Value, (usize, u32)>,
  245. user_data: Option<V>,
  246. user_reads: BTreeMap<u32, UserData>,
  247. samplers: Vec<[u32; 4]>,
  248. descriptors: HashMap<(Site, bool), &'a Source>,
  249. scalar: HashMap<Site, Address>,
  250. exports: HashMap<Site, &'a Export>,
  251. interps: HashMap<Site, &'a Interp>,
  252. handles: HashMap<(usize, Site, u8, bool, (u32, u32)), V>,
  253. /// Element strides read from the host's table by heap slot
  254. /// ([`super::shader::SLOT_STRIDES`]), by block and descriptor load.
  255. strides: HashMap<(usize, Site, u8), V>,
  256. /// Blocks splitting the edge from one IR block to another.
  257. edges: HashMap<(usize, usize), usize>,
  258. /// Per IR block: a `done` export is behind every lane entering it.
  259. exported: Vec<bool>,
  260. /// Reverse-postorder index per IR block.
  261. rpo: Vec<usize>,
  262. /// DXIL block each IR block ends in (guarded stores split blocks).
  263. tail: Vec<Option<usize>>,
  264. /// The program writes UAVs: barriers fence them too.
  265. writes_uavs: bool,
  266. /// src0 of the current instruction as DPP fetched it.
  267. src0: Option<V>,
  268. /// Compute code that reads other lanes: thread ids follow the host
  269. /// lanes, so lane n is console lane n.
  270. console_lanes: bool,
  271. /// Mesh: the thread index in the group (made in the entry block).
  272. flat: Option<V>,
  273. /// Mesh: IR blocks whose `s_barrier` is left out.
  274. no_barrier: HashSet<usize>,
  275. /// IR blocks whose `s_barrier` not every lane is sure to reach (a lane
  276. /// branch lies between the entry and the block, or the program has a
  277. /// loop a lane can be cut out of): the barrier there keeps its fences
  278. /// and does not wait for the group ([`super::group_sync`]).
  279. fence_only: HashSet<usize>,
  280. /// A group barrier before every LDS access (a console wave run as two host waves).
  281. split_lds: bool,
  282. /// With `split_lds`, LDS accesses in lane branches: per IR block whether every lane runs
  283. /// it, and whether the host waves meet at its start and before its exit ([`lds_meetings`]).
  284. lds_meet: Option<(Vec<bool>, Vec<(bool, bool)>)>,
  285. /// A console wave64 program run as two host waves of 32 that exchange through LDS: the first
  286. /// of two exchange dwords, whether the group has no upper half (32 threads or fewer), and per
  287. /// IR block whether every lane runs it (exchanges need both halves there).
  288. exchange: Option<(u32, bool, Vec<bool>)>,
  289. /// With `exchange`: nothing is exchanged, each host wave acts as a wave
  290. /// of its own ([`with_local_waves`]).
  291. local: bool,
  292. /// The instruction being lowered may read a lane mask as a number under
  293. /// `local` (a bit count, a first set bit, `v_mbcnt`).
  294. local_ok: bool,
  295. /// With `local`: every mask read and lane read is taken per host wave
  296. /// ([`with_local_waves_any`]).
  297. local_any: bool,
  298. /// With `exchange`: VGPR values every lane holds alike ([`lane_uniform`]); a first-lane
  299. /// read of one needs nothing from the other host wave.
  300. uniform: HashSet<Value>,
  301. /// With `exchange`: the wave ORs that only steer a loop over each lane's own bits, which
  302. /// a host wave takes over its own lanes wherever they stand ([`super::own_bits`]).
  303. own_bits: super::own_bits::OwnBits,
  304. /// The console lane (0..63) of this thread, made in the entry block.
  305. clane: Option<V>,
  306. /// The first exchange dword of this thread's console wave ([`Self::exchange_pair`]).
  307. pair: Option<V>,
  308. /// A console wave64 program in host waves of 32: the LDS dword counting the console threads
  309. /// handed to host waves (`wave_base`), and the base made in the entry block.
  310. halves: Option<u32>,
  311. wave_base: Option<V>,
  312. /// Vertex and mesh outputs holding 16-bit values: row, whether two per
  313. /// dword, and the row packed after it.
  314. half_outputs: HashMap<u8, (bool, Option<u8>)>,
  315. /// How lane masks become data.
  316. mask_data: MaskData,
  317. /// The instruction being lowered may read lane masks as data.
  318. mask_ok: bool,
  319. /// Ballots of masks read as data, by low dword: (low, high).
  320. ballots: HashMap<Value, (V, V)>,
  321. /// Masks whose ballot is being built: a mask whose lane bit needs its
  322. /// own value as a number (an opaque mask keyed by a dword it shares
  323. /// with another) would otherwise recurse until the stack overflows.
  324. balloting: HashSet<Value>,
  325. /// Block writing each value.
  326. def_block: HashMap<Value, usize>,
  327. /// IR block being lowered.
  328. cur_ir: usize,
  329. /// Whole-wave sections by block and start index.
  330. sections: HashMap<usize, HashMap<usize, super::wave::Section>>,
  331. /// Values written in a section that code outside it reads.
  332. section_out: HashSet<Value>,
  333. /// The program's constant table (the code from the first byte read
  334. /// through `s_getpc_b64` on): global, first byte, dwords.
  335. code_table: Option<(V, u32, u32)>,
  336. /// Loop headers' iteration counters (see [`LOOP_LIMIT`]): the phi by
  337. /// IR block, and its incoming (value, DXIL block) pairs.
  338. counters: HashMap<usize, (V, Vec<(V, usize)>)>,
  339. /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from.
  340. abort: Option<usize>,
  341. }
  342. /// Iterations after which a loop is left (per entry into it), unless
  343. /// [`super::loop_limit`] says otherwise. The console runs a loop as long as
  344. /// its data says; data the host has not mirrored yet (a null view reads
  345. /// zeros) can make that four billion iterations, which hangs the host GPU
  346. /// until the driver resets it. A lane that reaches the limit leaves the
  347. /// program as killed (a pixel discards).
  348. // shortcut: a genuine loop of more iterations than this is cut short too.
  349. pub(super) const LOOP_LIMIT: u32 = 1 << 20;
  350. /// Lane masks read as numbers (`s_bcnt1`, `s_ff1`, `v_mbcnt`, scalar
  351. /// compares, bit tests) are ballots of the lanes' booleans, taken where the
  352. /// mask is written: structurisation's `active` masks hold only lanes that
  353. /// reach that block, so the ballot misses none.
  354. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  355. enum MaskData {
  356. /// Compute: host lane n is console lane n (the program declares the
  357. /// console's wave size), so ballots are the console's masks bit for bit
  358. /// and any use is exact.
  359. Console,
  360. /// Pixel and vertex programs: ballots over the host's wave, whatever its
  361. /// size. Only uses that mean the same on any wave are allowed: counts,
  362. /// the first lane, the count below a lane, equality (the HLSL wave
  363. /// operations the console compiler expands). Lane numbers stay host
  364. /// lanes throughout (`v_mbcnt`, `v_readlane` at a computed lane).
  365. Host,
  366. /// Mesh programs: their lanes and waves (LDS per console wave) are the
  367. /// console's but no host wave size can be declared.
  368. None,
  369. }
  370. /// What a value holding a lane mask read as a number stops with.
  371. pub(super) const LANE_MASK: Why = "a lane mask read as data";
  372. /// A mask with lanes outside EXEC where it is written, read as a number where the lanes that
  373. /// run that block are not all of the wave.
  374. pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data";
  375. /// Instructions that read a lane mask (not EXEC implicitly, not a lane's
  376. /// bit) as a number.
  377. /// Per IR block: every lane of the wave that started the program runs it – no per-lane branch
  378. /// separates it from the entry (it lies in no lane branch's region: the blocks reachable from
  379. /// the branch that do not post-dominate it). None with an indirect exit (not followed).
  380. fn all_lane_blocks(st: &Structured) -> Option<Vec<bool>> {
  381. let n = st.exits.len();
  382. let mut all = vec![true; n];
  383. for (_, region) in lane_regions(st)? {
  384. for b in (0..n).filter(|&b| region[b]) {
  385. all[b] = false;
  386. }
  387. }
  388. Some(all)
  389. }
  390. /// Every per-lane branch (by its block) with its region: the blocks reachable from it that do
  391. /// not post-dominate it, which only some lanes run. Not the branches the wave takes together
  392. /// ([`Structured::wide`]), nor those on scalar conditions. None with an indirect exit.
  393. fn lane_regions(st: &Structured) -> Option<Vec<(usize, Vec<bool>)>> {
  394. let n = st.exits.len();
  395. let mut succ: Vec<Vec<usize>> = vec![Vec::new(); n];
  396. for (b, e) in st.exits.iter().enumerate() {
  397. match *e {
  398. LaneExit::Jump(t) => succ[b].push(t),
  399. LaneExit::Branch { taken, not_taken, .. } => {
  400. succ[b].push(taken);
  401. succ[b].push(not_taken);
  402. }
  403. LaneExit::End => {}
  404. LaneExit::Indirect => return None,
  405. }
  406. }
  407. // post-dominators (bitsets; a virtual exit after every End)
  408. let words = n.div_ceil(64);
  409. let full = vec![u64::MAX; words];
  410. 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();
  411. let mut changed = true;
  412. while changed {
  413. changed = false;
  414. for b in (0..n).rev() {
  415. if succ[b].is_empty() {
  416. continue;
  417. }
  418. let mut v = full.clone();
  419. for &t in &succ[b] {
  420. for w in 0..words {
  421. v[w] &= pdom[t][w];
  422. }
  423. }
  424. v[b / 64] |= 1 << (b % 64);
  425. if v != pdom[b] {
  426. pdom[b] = v;
  427. changed = true;
  428. }
  429. }
  430. }
  431. let mut regions = Vec::new();
  432. for (d, e) in st.exits.iter().enumerate() {
  433. let LaneExit::Branch { when, .. } = *e else { continue };
  434. if st.wide.contains(&d) || st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) {
  435. continue; // a wave-wide or uniform branch: all lanes go the same way
  436. }
  437. // blocks reachable from the lane branch that do not post-dominate it
  438. let mut seen = vec![false; n];
  439. let mut stack: Vec<usize> = succ[d].clone();
  440. while let Some(b) = stack.pop() {
  441. if seen[b] || pdom[d][b / 64] >> (b % 64) & 1 == 1 {
  442. continue;
  443. }
  444. seen[b] = true;
  445. stack.extend(succ[b].iter().copied());
  446. }
  447. regions.push((d, seen));
  448. }
  449. Some(regions)
  450. }
  451. /// The per-lane branches (by block) whose regions hold a block of `needs` (blocks where two
  452. /// host waves must meet, [`take_needs`]): the ones to take wave-wide
  453. /// ([`crate::structure::structure_wide`]) so that every lane runs those blocks. None if one
  454. /// of them is a branch whose wave-wide meaning is not known ([`Structured::wave_any`]).
  455. pub(super) fn branches_around(st: &Structured, needs: &[usize]) -> Option<Vec<usize>> {
  456. let mut out = Vec::new();
  457. for (d, region) in lane_regions(st)? {
  458. if needs.iter().any(|&b| region.get(b).copied().unwrap_or(false)) {
  459. st.wave_any.get(d).copied().flatten()?;
  460. out.push(d);
  461. }
  462. }
  463. Some(out)
  464. }
  465. /// Whether a refusal is of code that needs every lane of the wave where it stands (two host
  466. /// waves meeting there), which the other forms of the program may give it.
  467. pub(super) fn needs_every_lane(what: &str) -> bool {
  468. what.ends_with("where not every lane runs") || what == MASK_ELSEWHERE
  469. }
  470. /// The blocks where the last lowering on this thread wanted every lane and did not have it
  471. /// (its "... where not every lane runs" refusals), which it forgets.
  472. pub(super) fn take_needs() -> Vec<usize> {
  473. NEEDS.take()
  474. }
  475. fn need(block: usize) {
  476. NEEDS.with_borrow_mut(|n| {
  477. if !n.contains(&block) {
  478. n.push(block);
  479. }
  480. });
  481. }
  482. /// VGPR values that are the same in every lane holding them (`all` is [`all_lane_blocks`]):
  483. /// written by an instruction every arriving lane runs (no guard), lane by lane, from scalars,
  484. /// constants and such values; or loaded from an address made of them. The compiler keeps
  485. /// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`.
  486. /// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes
  487. /// run (no lane branch can have split the arriving lanes); loop-carried values never do.
  488. fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet<Value> {
  489. let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
  490. let mut same: HashSet<Value> = HashSet::new();
  491. for b in crate::ir::reverse_postorder(&p.blocks) {
  492. let block = &p.blocks[b];
  493. let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false));
  494. for phi in &block.phis {
  495. if matches!(phi.reg, Reg::V(_)) && whole && phi.args.iter().all(|a| same.contains(a)) {
  496. same.insert(phi.value);
  497. }
  498. }
  499. for (i, inst) in block.insts.iter().enumerate() {
  500. let name = inst.name();
  501. let ops: Vec<Operand> = match &inst.fields {
  502. Fields::Valu(v)
  503. if v.dpp.is_none()
  504. && v.sdwa.is_none()
  505. && !name.starts_with("v_mbcnt")
  506. && !name.starts_with("v_cmpx")
  507. && !name.contains("lane") =>
  508. {
  509. v.src.clone()
  510. }
  511. _ => continue,
  512. };
  513. if st.guards[b][i].is_some() {
  514. continue; // lanes outside EXEC keep another value
  515. }
  516. let alike = ops.iter().all(|op| match *op {
  517. Operand::Vector { reg, .. } => {
  518. // every dword of the operand the instruction reads from that register on
  519. let read: Vec<Value> =
  520. inst.reads.iter().filter(|r| matches!(r.0, Reg::V(x) if x >= reg)).map(|r| r.1).collect();
  521. !read.is_empty() && read.iter().all(|x| same.contains(x))
  522. }
  523. // a scalar is one value; a lane mask is not, unless a compare of such values made it
  524. Operand::Scalar { code, .. } if code != NULL => {
  525. inst.read(Reg::S(code)).is_none_or(|x| !is_mask(x) || same.contains(&x))
  526. }
  527. _ => true,
  528. });
  529. if alike {
  530. same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1));
  531. }
  532. }
  533. }
  534. same
  535. }
  536. /// What a register value holds, for [`wave_local`].
  537. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  538. enum Wave {
  539. /// Nothing that depends on how the threads are divided into waves.
  540. Plain,
  541. /// The number of the wave's first lane in a mask (`s_ff1`).
  542. First,
  543. /// A reduction over the wave's lanes: a count, a sum, a minimum...
  544. Total(super::wave::Op),
  545. /// A count or sum over the lanes below this one.
  546. Prefix,
  547. /// Derived from what a first-lane atomic returned: the slots the wave reserved.
  548. Base,
  549. /// A mix the idiom does not make.
  550. Mixed,
  551. }
  552. /// Whether a console wave64 program may run with each host wave as a wave of its own
  553. /// ([`with_local_waves`]): its wave-wide values are used only as the allocation idiom uses
  554. /// them, which does not care how the threads are divided into waves. A first-lane number only
  555. /// picks the first lane; a count or sum only goes into that lane's atomic on a shared counter;
  556. /// a prefix only goes onto the base that atomic returned; the first lane does nothing else.
  557. /// Anything else done with them takes one wave to be the whole thread group (a tile's result,
  558. /// say) and is refused, with the offset and what was found.
  559. /// Lane masks read as numbers by other instructions and lane reads outside whole-wave sections
  560. /// are stopped by the lowering itself.
  561. // shortcut: `v_readfirstlane` of a value that differs between lanes is taken as it is (this
  562. // host wave's first lane), and a guarded write of a plain value over a wave-dependent one is
  563. // the only mix of old and new lanes that is looked at.
  564. pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'static str)> {
  565. use super::wave::{Op, Shape};
  566. const FIRST: Why = "a wave's first-lane number used as data";
  567. const TOTAL: Why = "a count or sum over the wave used as data";
  568. const PREFIX: Why = "a count or sum over the lanes below used without a reserved base";
  569. const MIXED: Why = "a value that depends on the wave on some paths only";
  570. const EFFECT: Why = "a write by the wave's first lane other than its reservation";
  571. fn of(kind: &HashMap<Value, Wave>, v: Option<Value>) -> Wave {
  572. v.and_then(|v| kind.get(&v).copied()).unwrap_or(Wave::Plain)
  573. }
  574. fn put(kind: &mut HashMap<Value, Wave>, v: Value, k: Wave) {
  575. if k == Wave::Plain {
  576. kind.remove(&v);
  577. } else {
  578. kind.insert(v, k);
  579. }
  580. }
  581. let wild = |k: Wave| !matches!(k, Wave::Plain | Wave::Base);
  582. let why = |k: Wave| match k {
  583. Wave::First => FIRST,
  584. Wave::Total(_) => TOTAL,
  585. Wave::Prefix => PREFIX,
  586. _ => MIXED,
  587. };
  588. // a mask (by its low dword) under which only a wave's first lane runs
  589. let first_mask = |firsts: &HashSet<Value>, m: Option<Value>| {
  590. m.and_then(|m| st.masks.get(&m)).is_some_and(|&b| {
  591. st.bools
  592. .support(b)
  593. .iter()
  594. .any(|a| matches!(a, Atom::Lane(v) if firsts.contains(v)))
  595. })
  596. };
  597. // One instruction outside a section: the kind of what it writes, and whether it is a
  598. // first lane's reservation.
  599. let step = |inst: &Inst, kind: &HashMap<Value, Wave>, firsts: &mut HashSet<Value>| -> Result<(Wave, bool), Why> {
  600. let name = inst.name();
  601. let val = |op: &Operand| match *op {
  602. Operand::Vector { reg, .. } => inst.read(Reg::V(reg)),
  603. Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)),
  604. _ => None,
  605. };
  606. let ops: Vec<Operand> = match &inst.fields {
  607. Fields::Valu(v) => v.src.clone(),
  608. Fields::Sop { dst, src, .. } => {
  609. let mut o = src.clone();
  610. if matches!(name, "s_addk_i32" | "s_mulk_i32") {
  611. o.extend(dst.iter().copied());
  612. }
  613. o
  614. }
  615. Fields::Buffer { data, .. } if name.contains("_atomic_") || name.contains("_store_") => {
  616. data.iter().copied().collect()
  617. }
  618. _ => Vec::new(),
  619. };
  620. let kinds: Vec<Wave> = ops.iter().map(|o| of(kind, val(o))).collect();
  621. // Everything else it reads (addresses, descriptors, SCC, the high dwords of wide
  622. // operands) must not depend on the wave. Not EXEC, and not the old value of a VGPR it
  623. // writes, which only the lanes outside EXEC keep.
  624. let named: Vec<Value> = ops.iter().filter_map(&val).collect();
  625. for &(r, v) in &inst.reads {
  626. let kept = matches!(r, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == r);
  627. if matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) || kept || named.contains(&v) {
  628. continue;
  629. }
  630. let k = of(kind, Some(v));
  631. if wild(k) {
  632. return Err(why(k));
  633. }
  634. }
  635. let w = kinds.iter().copied().find(|&k| wild(k)).unwrap_or(Wave::Mixed);
  636. let sum = |k: Wave| k == Wave::Total(Op::AddU);
  637. let is_mask = |o: &Operand| {
  638. val(o).is_some_and(|v| st.masks.contains_key(&v) || st.highs.contains_key(&v))
  639. };
  640. let mut reserved = false;
  641. let out = match (name, &kinds[..]) {
  642. ("s_ff1_i32_b64" | "s_ff1_i32_b32", _) if ops.first().is_some_and(is_mask) => Wave::First,
  643. ("s_bcnt1_i32_b64" | "s_bcnt1_i32_b32", _) if ops.first().is_some_and(is_mask) => {
  644. Wave::Total(Op::AddU)
  645. }
  646. // bits of a mask below the lane; with -1 for the mask, the lane's number
  647. ("v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32", [_, b]) => {
  648. match (matches!(ops[0], Operand::Scalar { .. }), *b) {
  649. (_, Wave::Prefix) | (true, Wave::Plain | Wave::Base) => Wave::Prefix,
  650. (false, Wave::Plain | Wave::Base) => Wave::Plain,
  651. (_, k) => return Err(why(k)),
  652. }
  653. }
  654. // nothing wave-dependent goes in; what derives from a reserved base stays marked
  655. _ if !kinds.iter().any(|&k| wild(k)) => {
  656. let derives = matches!(inst.fields, Fields::Valu(_) | Fields::Sop { .. });
  657. if derives && kinds.contains(&Wave::Base) { Wave::Base } else { Wave::Plain }
  658. }
  659. ("v_mov_b32" | "s_mov_b32", [k]) => *k,
  660. ("v_cmp_eq_i32" | "v_cmp_eq_u32" | "v_cmpx_eq_i32" | "v_cmpx_eq_u32", [a, b]) => {
  661. // the lane whose own number is the first lane's
  662. let lane = match (*a, *b) {
  663. (Wave::First, k) if !wild(k) => &ops[1],
  664. (k, Wave::First) if !wild(k) => &ops[0],
  665. _ => return Err(why(w)),
  666. };
  667. if !matches!(lane, Operand::Vector { .. }) {
  668. return Err(FIRST);
  669. }
  670. let mask = match &inst.fields {
  671. _ if name.starts_with("v_cmpx") => inst.write(Reg::S(EXEC)),
  672. Fields::Valu(v) => match v.dst {
  673. Some(Operand::Scalar { code, .. }) => inst.write(Reg::S(code)),
  674. _ => None,
  675. },
  676. _ => None,
  677. };
  678. firsts.extend(mask);
  679. Wave::Plain
  680. }
  681. ("v_add_nc_u32" | "s_add_i32", [a, b]) => match (*a, *b) {
  682. (Wave::Prefix, Wave::Base) | (Wave::Base, Wave::Prefix) => Wave::Base,
  683. (Wave::Prefix, Wave::Plain | Wave::Prefix) | (Wave::Plain, Wave::Prefix) => Wave::Prefix,
  684. (x, y) if sum(x) && sum(y) => x,
  685. _ => return Err(why(w)),
  686. },
  687. ("v_sub_nc_u32" | "s_sub_i32", [a, b]) => match (*a, *b) {
  688. (Wave::Base, Wave::Prefix) => Wave::Base,
  689. (Wave::Prefix, Wave::Plain) => Wave::Prefix,
  690. (Wave::Plain, y) if sum(y) && matches!(ops[0], Operand::Const(128)) => y,
  691. _ => return Err(why(w)),
  692. },
  693. ("s_mul_i32" | "v_mul_lo_u32" | "v_mul_u32_u24", [a, b]) => match (*a, *b) {
  694. (x, Wave::Plain) | (Wave::Plain, x) if sum(x) || x == Wave::Prefix => x,
  695. _ => return Err(why(w)),
  696. },
  697. ("s_lshl_b32", [x, Wave::Plain]) | ("v_lshlrev_b32", [Wave::Plain, x])
  698. if sum(*x) || *x == Wave::Prefix =>
  699. {
  700. *x
  701. }
  702. ("v_lshl_add_u32", [Wave::Prefix, Wave::Plain, c]) if !wild(*c) => {
  703. if *c == Wave::Base { Wave::Base } else { Wave::Prefix }
  704. }
  705. // the reservation: the first lane adds its wave's total to a shared counter
  706. (_, [Wave::Total(op)]) if name.contains("_atomic_") => {
  707. let want = match op {
  708. Op::AddU => "buffer_atomic_add",
  709. Op::MinU => "buffer_atomic_umin",
  710. Op::MaxU => "buffer_atomic_umax",
  711. Op::MinI => "buffer_atomic_smin",
  712. Op::MaxI => "buffer_atomic_smax",
  713. Op::Or => "buffer_atomic_or",
  714. Op::And => "buffer_atomic_and",
  715. Op::Xor => "buffer_atomic_xor",
  716. _ => "",
  717. };
  718. if name != want || !first_mask(firsts, inst.read(Reg::S(EXEC))) {
  719. return Err(TOTAL);
  720. }
  721. reserved = true;
  722. Wave::Base
  723. }
  724. _ => return Err(why(w)),
  725. };
  726. Ok((out, reserved))
  727. };
  728. let sections: Vec<_> = (0..p.blocks.len()).map(|b| super::wave::sections(p, b)).collect();
  729. let order = crate::ir::reverse_postorder(&p.blocks);
  730. let pass = |kind: &mut HashMap<Value, Wave>, firsts: &mut HashSet<Value>, check: bool| -> Result<(), (usize, Why)> {
  731. for &b in &order {
  732. let block = &p.blocks[b];
  733. for phi in &block.phis {
  734. let mut k = Wave::Plain;
  735. for (n, &a) in phi.args.iter().enumerate() {
  736. let x = of(kind, Some(a));
  737. k = match (k, x) {
  738. _ if n == 0 => x,
  739. (k, x) if k == x => k,
  740. (Wave::Plain, m @ (Wave::Base | Wave::Prefix))
  741. | (m @ (Wave::Base | Wave::Prefix), Wave::Plain) => m,
  742. _ => Wave::Mixed,
  743. };
  744. }
  745. put(kind, phi.value, k);
  746. }
  747. for (i, inst) in block.insts.iter().enumerate() {
  748. // inside a whole-wave section: what the simulation found each value to be
  749. if let Some((_, sec)) = sections[b].iter().find(|(s, sec)| i > **s && i < sec.end) {
  750. for &(_, w) in &inst.writes {
  751. let k = match sec.shapes.get(&w) {
  752. None => Wave::Mixed,
  753. Some(&Shape::K(_)) => Wave::Plain,
  754. Some(&Shape::Value(v)) => of(kind, Some(v)),
  755. Some(&Shape::Masked(src, _, _)) => of(kind, Some(src)),
  756. Some(&Shape::Active(op, src, mask, _)) => match of(kind, Some(src)) {
  757. Wave::Plain | Wave::Base => Wave::Total(op),
  758. // the first lane's own sum of a total is that total
  759. Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => Wave::Total(op),
  760. _ => Wave::Mixed,
  761. },
  762. Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => match of(kind, Some(src)) {
  763. Wave::Plain | Wave::Base => Wave::Prefix,
  764. Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => Wave::Prefix,
  765. _ => Wave::Mixed,
  766. },
  767. Some(_) => Wave::Mixed,
  768. };
  769. put(kind, w, k);
  770. }
  771. continue;
  772. }
  773. let name = inst.name();
  774. if name.starts_with("s_cbranch") {
  775. continue; // with the block's exit, below
  776. }
  777. let (k, reserved) = match step(inst, kind, firsts) {
  778. Ok(r) => r,
  779. Err(why) if check => return Err((inst.machine.offset, why)),
  780. Err(_) => (Wave::Mixed, false),
  781. };
  782. // the same test as `Lower::inst`'s `effect`
  783. let effect = matches!(inst.fields, Fields::Exp { .. })
  784. || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
  785. || name.contains("store")
  786. || name.contains("atomic")
  787. || matches!(inst.fields, Fields::Ds { .. })
  788. && !(name.starts_with("ds_read")
  789. || name.starts_with("ds_swizzle")
  790. || name.contains("permute"));
  791. if check && effect && !reserved && first_mask(firsts, inst.read(Reg::S(EXEC))) {
  792. return Err((inst.machine.offset, EFFECT));
  793. }
  794. let guarded = st.guards[b][i].is_some();
  795. for &(r, w) in &inst.writes {
  796. let mut kw = match r {
  797. // "some lane is counted" keeps the count's kind; any other SCC is one bit of data
  798. Reg::Scc if !name.starts_with("s_bcnt1") => {
  799. if wild(k) { Wave::Mixed } else { Wave::Plain }
  800. }
  801. _ => k,
  802. };
  803. // a guarded write leaves the old value in the lanes outside EXEC
  804. if guarded
  805. && matches!(r, Reg::V(_))
  806. && kw == Wave::Plain
  807. && matches!(of(kind, inst.read(r)), Wave::First | Wave::Total(_) | Wave::Prefix)
  808. {
  809. kw = Wave::Mixed;
  810. }
  811. put(kind, w, kw);
  812. }
  813. }
  814. // a branch on "some lane is counted": fine where the structure made it the lane's
  815. // own bit (the mask is EXEC under a scalar condition)
  816. if check
  817. && let Some(last) = block.insts.last()
  818. && last.name().starts_with("s_cbranch_scc")
  819. && let Some(scc) = last.read(Reg::Scc)
  820. && wild(of(kind, Some(scc)))
  821. {
  822. let own = matches!(st.exits[b], LaneExit::Branch { when, .. }
  823. if !st.bools.support(when).iter().any(|a| matches!(a, Atom::Uniform(v) if *v == scc)));
  824. if !own {
  825. return Err((last.machine.offset, TOTAL));
  826. }
  827. }
  828. }
  829. Ok(())
  830. };
  831. let mut kind: HashMap<Value, Wave> = HashMap::new();
  832. let mut firsts: HashSet<Value> = HashSet::new();
  833. // to a fixpoint (values carried around loops), then once more to say what is wrong
  834. let mut settled = false;
  835. for _ in 0..16 {
  836. let before = (kind.clone(), firsts.len());
  837. pass(&mut kind, &mut firsts, false)?;
  838. if (&before.0, before.1) == (&kind, firsts.len()) {
  839. settled = true;
  840. break;
  841. }
  842. }
  843. if !settled {
  844. return Err((0, MIXED));
  845. }
  846. pass(&mut kind, &mut firsts, true)
  847. }
  848. /// The mode of a group barrier the translation adds (host waves meeting):
  849. /// a wait for the group with a shared-memory fence; the fence alone with
  850. /// `VICTORY_GROUP_SYNC=0` ([`super::group_sync`]).
  851. fn meeting_mode() -> u32 {
  852. if super::group_sync() == 0 { 8 } else { 1 | 8 }
  853. }
  854. /// LDS accesses of a console wave run as two host waves, where some sit in blocks that only
  855. /// some lanes run (`all` is [`all_lane_blocks`]): per IR block, whether the host waves meet (a
  856. /// group barrier) at its start and before its exit. `None` if barriers cannot keep the
  857. /// console's order.
  858. ///
  859. /// The console runs the wave's lanes in step, so an LDS write is seen by every later read. Two
  860. /// host waves keep that order if they meet between any two accesses of which one writes. A
  861. /// barrier must be run by every thread, so it cannot stand in a lane branch's region; but
  862. /// every way into and out of such a region passes a block all lanes run, and the waves meet
  863. /// there: before the exit of an all-lane block into a region with LDS accesses, and at the
  864. /// start of an all-lane block entered from one. Accesses in all-lane blocks get their own
  865. /// barrier as before. What that cannot order is a write and a read inside one region (blocks
  866. /// joined without an all-lane block between them): refused.
  867. /// shortcut: two writes in one region are taken not to hit the same dword from both halves.
  868. fn lds_meetings(p: &crate::ir::Program, st: &Structured, all: &[bool]) -> Option<Vec<(bool, bool)>> {
  869. let n = st.exits.len();
  870. let succ = |b: usize| -> Vec<usize> {
  871. match st.exits[b] {
  872. LaneExit::Jump(t) => vec![t],
  873. LaneExit::Branch { taken, not_taken, .. } => vec![taken, not_taken],
  874. LaneExit::End | LaneExit::Indirect => Vec::new(),
  875. }
  876. };
  877. // regions: blocks not every lane runs, joined by the edges between them
  878. let mut region: Vec<usize> = (0..n).collect();
  879. fn find(region: &mut [usize], mut b: usize) -> usize {
  880. while region[b] != b {
  881. region[b] = region[region[b]];
  882. b = region[b];
  883. }
  884. b
  885. }
  886. for b in 0..n {
  887. for t in succ(b) {
  888. if !all[b] && !all[t] {
  889. let (x, y) = (find(&mut region, b), find(&mut region, t));
  890. region[x] = y;
  891. }
  892. }
  893. }
  894. // per region: LDS reads, LDS writes
  895. let mut reads = vec![false; n];
  896. let mut writes = vec![false; n];
  897. for (b, block) in p.blocks.iter().enumerate().take(n) {
  898. if all[b] {
  899. continue;
  900. }
  901. let r = find(&mut region, b);
  902. for i in &block.insts {
  903. let name = i.name();
  904. if !matches!(i.fields, Fields::Ds { .. }) || name.starts_with("ds_swizzle") || name.contains("permute") {
  905. continue;
  906. }
  907. if name.starts_with("ds_read") {
  908. reads[r] = true;
  909. } else {
  910. writes[r] = true;
  911. }
  912. }
  913. }
  914. if (0..n).any(|r| reads[r] && writes[r]) {
  915. return None;
  916. }
  917. let mut meet = vec![(false, false); n];
  918. for b in 0..n {
  919. for t in succ(b) {
  920. if all[b] && !all[t] {
  921. let r = find(&mut region, t);
  922. meet[b].1 |= reads[r] || writes[r];
  923. } else if !all[b] && all[t] {
  924. let r = find(&mut region, b);
  925. meet[t].0 |= reads[r] || writes[r];
  926. }
  927. }
  928. }
  929. Some(meet)
  930. }
  931. /// Masks held as numbers or constant lane sets in guards or lane branches: the lane tests its
  932. /// own bit by its console lane.
  933. fn lane_constant_masks(st: &Structured) -> bool {
  934. let whens = st.exits.iter().filter_map(|e| match *e {
  935. LaneExit::Branch { when, .. } => Some(when),
  936. _ => None,
  937. });
  938. let mut work: Vec<Bool> = st.guards.iter().flatten().flatten().copied().chain(whens).collect();
  939. // Through lane-mask joins too: an edge that brings a number or a constant lane set needs
  940. // the lane's own bit of it.
  941. // shortcut: masks only selects read (`v_cndmask_b32`, carries in) are not followed; such
  942. // a program still stops with "a constant lane mask" or "an opaque lane mask".
  943. let (mut seen, mut joins) = (HashSet::new(), HashSet::new());
  944. while let Some(g) = work.pop() {
  945. if !seen.insert(g) {
  946. continue;
  947. }
  948. for a in st.bools.support(g) {
  949. match a {
  950. Atom::Opaque(_) | Atom::Constant(_) => return true,
  951. Atom::Phi(id) if joins.insert(id) => {
  952. if let Some(edges) = st.phi_masks.get(&id) {
  953. work.extend(edges.iter().copied());
  954. }
  955. }
  956. _ => {}
  957. }
  958. }
  959. }
  960. false
  961. }
  962. /// The widest wave the host GPU runs (0: not known – no host-specific forms); see
  963. /// [`set_host_max_wave`].
  964. static HOST_MAX_WAVE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  965. /// The host GPU's `WaveLaneCountMax`: 32 lets console wave64 compute programs whose cross-lane
  966. /// code stays inside 32-lane halves run in waves of 32 instead of being refused.
  967. pub fn set_host_max_wave(lanes: u32) {
  968. HOST_MAX_WAVE.store(lanes, std::sync::atomic::Ordering::Relaxed);
  969. }
  970. thread_local! {
  971. /// See [`take_needs`].
  972. static NEEDS: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
  973. /// See [`with_local_waves`].
  974. static LOCAL_WAVES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
  975. /// See [`with_local_waves_any`].
  976. static LOCAL_ANY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
  977. }
  978. /// As [`with_local_waves`], with every other use of a lane mask as a number
  979. /// and every lane read and write taken per host wave too: the program runs
  980. /// as it would on a console of 32-lane waves, lanes numbered 0..31 or
  981. /// 32..63 by half. Right for code that only relies on what HLSL's wave
  982. /// operations promise; a program that takes one wave to be its whole
  983. /// thread group gets per-half results. The last resort for programs that
  984. /// do not translate otherwise.
  985. pub(super) fn with_local_waves_any<R>(f: impl FnOnce() -> R) -> R {
  986. let was = LOCAL_ANY.replace(true);
  987. let r = with_local_waves(f);
  988. LOCAL_ANY.set(was);
  989. r
  990. }
  991. /// Runs `f` with console wave64 programs on 32-lane hosts lowered with each
  992. /// host wave as a wave of its own ("local"): no exchange between the two
  993. /// halves of a console wave, so no barriers and no need for every lane to
  994. /// reach the code. What HLSL's wave operations promise holds for any
  995. /// division of the threads into waves, and the idiom the title's compute
  996. /// programs use them for does not care which wave a thread is in: count or
  997. /// sum over the wave, the first lane reserves that many slots with an atomic
  998. /// add, every lane takes the base (`WaveReadLaneFirst`) plus its prefix.
  999. /// Each lane still gets a slot of its own; only the order differs.
  1000. /// Only that idiom's operations are lowered this way: a lane mask read as
  1001. /// a number by anything but a bit count, a first-set-bit or `v_mbcnt`, and
  1002. /// lane reads and writes outside whole-wave sections, stop the translation.
  1003. /// shortcut: where a count or sum goes is not checked. A program that uses
  1004. /// a wave-wide result as data for the whole console wave (a tile's maximum,
  1005. /// say, with one wave per thread group) gets its half's result. It is used
  1006. /// only for programs that do not translate otherwise.
  1007. pub(super) fn with_local_waves<R>(f: impl FnOnce() -> R) -> R {
  1008. let was = LOCAL_WAVES.replace(true);
  1009. let r = f();
  1010. LOCAL_WAVES.set(was);
  1011. r
  1012. }
  1013. /// `VICTORY_F16_NEAREST=1`: the results of 16-bit float operations (`v_add_f16`,
  1014. /// `v_mul_f16`, `v_cvt_f16_f32` ...) are rounded to nearest as the console rounds them
  1015. /// ([`Lower::f16_nearest`]) instead of as the host's `f32tof16` does (toward zero on NVIDIA:
  1016. /// the last place of a result that is not exact is then one lower than the console's).
  1017. /// Off by default: it is exact but untried in a game run, and adds instructions to every
  1018. /// such operation. The wave sum of 16-bit floats ([`Lower::half_sum`]) is always exact.
  1019. fn f16_nearest_on() -> bool {
  1020. #[cfg(test)]
  1021. if let Some(on) = TEST_F16_NEAREST.get() {
  1022. return on;
  1023. }
  1024. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1025. *ON.get_or_init(|| std::env::var_os("VICTORY_F16_NEAREST").is_some_and(|v| v == "1"))
  1026. }
  1027. #[cfg(test)]
  1028. thread_local! {
  1029. /// A test's choice for [`f16_nearest_on`], for its thread only.
  1030. pub(super) static TEST_F16_NEAREST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
  1031. }
  1032. /// `VICTORY_WAVE_OWN_BITS=0`: a wave OR where not every lane runs is refused as before
  1033. /// ([`super::own_bits`]).
  1034. fn own_bits_on() -> bool {
  1035. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1036. *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0"))
  1037. }
  1038. /// What the translator was told of the host, for a cache's key: the widest
  1039. /// wave and the view heap's limit.
  1040. pub fn host_settings() -> [u32; 2] {
  1041. [host_max_wave(), super::shader::view_heap_limit()]
  1042. }
  1043. pub(super) fn host_max_wave() -> u32 {
  1044. #[cfg(test)]
  1045. if let Some(lanes) = TEST_HOST_WAVE.get() {
  1046. return lanes;
  1047. }
  1048. HOST_MAX_WAVE.load(std::sync::atomic::Ordering::Relaxed)
  1049. }
  1050. #[cfg(test)]
  1051. thread_local! {
  1052. /// A test's host wave size, for its thread only ([`set_host_max_wave`] is the process's).
  1053. pub(super) static TEST_HOST_WAVE: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
  1054. }
  1055. pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool {
  1056. let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
  1057. let ops: Vec<&Operand> = match &i.fields {
  1058. // A mask operation (its result a mask) is no data use.
  1059. Fields::Sop { .. }
  1060. if i.writes
  1061. .iter()
  1062. .any(|&(r, w)| matches!(r, Reg::S(_)) && is_mask(w)) =>
  1063. {
  1064. return false;
  1065. }
  1066. Fields::Sop { src, .. } => src.iter().collect(),
  1067. Fields::Valu(v)
  1068. if !matches!(i.name(), "v_cndmask_b32") && !i.name().contains("_co_ci_") =>
  1069. {
  1070. v.src.iter().collect()
  1071. }
  1072. _ => return false,
  1073. };
  1074. ops.into_iter().any(|op| match *op {
  1075. Operand::Scalar { code, .. } if code != NULL => i.read(Reg::S(code)).is_some_and(is_mask),
  1076. _ => false,
  1077. })
  1078. }
  1079. /// The parameters packing 16-bit rows two per dword and where each lays
  1080. /// its elements out: (first row, [(dword, register, column, columns)]).
  1081. ///
  1082. /// The console gives every 16-bit element whole dwords. A parameter leads
  1083. /// with the first element of its first row, then the first element of its
  1084. /// second row. An element that shares a register behind another one (the
  1085. /// signature packs a short element into the free columns of an earlier
  1086. /// register) is NOT in that row's halves: it follows in the first
  1087. /// parameter, in row order, that has whole dwords left.
  1088. /// The title's packed pedestrian shaders show both cases: TEXCOORD7 (register 1,
  1089. /// columns 2-3, behind the two columns of TEXCOORD0) is exported in dword 3
  1090. /// of parameter 0, after TEXCOORD1's two dwords; TEXCOORD6 (register 4,
  1091. /// column 3, behind the three columns of TEXCOORD4) in dword 3 of
  1092. /// parameter 3, after TEXCOORD5 and TEXCOORD7, while the high half of
  1093. /// TEXCOORD4's second dword stays zero.
  1094. type PackedLayout = Vec<(u8, Vec<(u8, u8, u8, u8)>)>;
  1095. fn packed_layout(elements: &[SigElement], packs: &[(u8, Option<u8>)]) -> PackedLayout {
  1096. let of_row = |r: u8| {
  1097. let mut of: Vec<&SigElement> = elements
  1098. .iter()
  1099. .filter(|e| e.row == Some(u32::from(r)))
  1100. .collect();
  1101. of.sort_by_key(|e| e.col);
  1102. of
  1103. };
  1104. let mut packs = packs.to_vec();
  1105. packs.sort_unstable();
  1106. packs.dedup_by_key(|p| p.0);
  1107. // Per parameter: its first row, the dwords used, the elements.
  1108. let mut layout: Vec<(u8, u8, Vec<(u8, u8, u8, u8)>)> = Vec::new();
  1109. let mut behind = Vec::new();
  1110. for &(a, b) in &packs {
  1111. let mut placed = Vec::new();
  1112. let mut at = 0u8;
  1113. if !of_row(a).is_empty() {
  1114. for r in [Some(a), b].into_iter().flatten() {
  1115. let of = of_row(r);
  1116. let Some((lead, more)) = of.split_first() else {
  1117. continue;
  1118. };
  1119. placed.push((at, r, lead.col, lead.cols));
  1120. at += lead.cols.div_ceil(2);
  1121. behind.extend(more.iter().map(|e| (r, e.col, e.cols)));
  1122. }
  1123. }
  1124. layout.push((a, at, placed));
  1125. }
  1126. behind.sort_unstable();
  1127. for (r, col, cols) in behind {
  1128. let need = cols.div_ceil(2);
  1129. if let Some(p) = layout.iter_mut().find(|p| p.1 + need <= 4) {
  1130. p.2.push((p.1, r, col, cols));
  1131. p.1 += need;
  1132. }
  1133. }
  1134. layout.into_iter().map(|(a, _, of)| (a, of)).collect()
  1135. }
  1136. /// Where half `h` (dword h / 2, the high half when odd) of the parameter
  1137. /// whose first 16-bit row is `a` comes from: a register and column of
  1138. /// `elements`, none for padding ([`packed_layout`]; `packs` lists every
  1139. /// parameter packing two 16-bit rows per dword).
  1140. fn packed_half(
  1141. elements: &[SigElement],
  1142. packs: &[(u8, Option<u8>)],
  1143. a: u8,
  1144. h: u8,
  1145. ) -> Option<(u8, u8)> {
  1146. let layout = packed_layout(elements, packs);
  1147. let (_, of) = layout.iter().find(|p| p.0 == a)?;
  1148. of.iter().find_map(|&(dword, row, col, cols)| {
  1149. let k = h.checked_sub(2 * dword)?;
  1150. (k < cols).then_some((row, col + k))
  1151. })
  1152. }
  1153. /// The pixel inputs packing two 16-bit rows per dword, as (first row,
  1154. /// second row) ([`packed_layout`]).
  1155. fn input_packs(io: &StageIo, inputs: &[SigElement]) -> Vec<(u8, Option<u8>)> {
  1156. let StageIo::Ps {
  1157. inputs: entries, ..
  1158. } = io
  1159. else {
  1160. return Vec::new();
  1161. };
  1162. let partners = half_input_partners(io, inputs);
  1163. entries
  1164. .iter()
  1165. .filter(|i| i.fp16 && i.pack2)
  1166. .map(|i| {
  1167. let b = if i.row2 != i.row {
  1168. Some(i.row2)
  1169. } else {
  1170. partners.get(&i.row).copied()
  1171. };
  1172. (i.row, b)
  1173. })
  1174. .collect()
  1175. }
  1176. /// Vertex or mesh outputs of 16-bit values (see [`Lower::half_outputs`]):
  1177. /// a packed row's partner is the next 16-bit row of the signature that no
  1178. /// output entry names, taken in row order.
  1179. fn half_outputs(io: &StageIo, outputs: &[SigElement]) -> HashMap<u8, (bool, Option<u8>)> {
  1180. let entries = match io {
  1181. StageIo::Vs { outputs, .. } => outputs,
  1182. StageIo::Ms(ms) => &ms.outputs,
  1183. _ => return HashMap::new(),
  1184. };
  1185. let per_vertex = || entries.iter().filter(|o| o.param & 0x80 == 0);
  1186. let mut free: Vec<u8> = outputs
  1187. .iter()
  1188. .filter(|e| e.half && e.kind == 0)
  1189. .filter_map(|e| u8::try_from(e.row?).ok())
  1190. .filter(|&r| !per_vertex().any(|o| o.row == r))
  1191. .collect();
  1192. free.sort_unstable();
  1193. free.dedup();
  1194. let mut halves: Vec<_> = per_vertex().filter(|o| o.fp16).collect();
  1195. halves.sort_by_key(|o| o.row);
  1196. halves
  1197. .into_iter()
  1198. .map(|o| {
  1199. let b = o
  1200. .pack2
  1201. .then(|| free.iter().position(|&r| r > o.row))
  1202. .flatten();
  1203. (o.row, (o.pack2, b.map(|i| free.remove(i))))
  1204. })
  1205. .collect()
  1206. }
  1207. /// Pixel inputs packing two 16-bit rows per dword whose second row the
  1208. /// metadata leaves out (`row2` = `row`): as for outputs
  1209. /// ([`half_outputs`]), the next 16-bit row of the signature that no input
  1210. /// entry names, taken in row order (rows the metadata does give are taken
  1211. /// first).
  1212. fn half_input_partners(io: &StageIo, inputs: &[SigElement]) -> HashMap<u8, u8> {
  1213. let StageIo::Ps {
  1214. inputs: entries, ..
  1215. } = io
  1216. else {
  1217. return HashMap::new();
  1218. };
  1219. let packed = || entries.iter().filter(|i| i.fp16 && i.pack2);
  1220. let mut free: Vec<u8> = inputs
  1221. .iter()
  1222. .filter(|e| e.half && e.kind == 0)
  1223. .filter_map(|e| u8::try_from(e.row?).ok())
  1224. .filter(|&r| !entries.iter().any(|i| i.row == r))
  1225. .filter(|&r| !packed().any(|i| i.row2 != i.row && i.row2 == r))
  1226. .collect();
  1227. free.sort_unstable();
  1228. free.dedup();
  1229. let mut missing: Vec<_> = packed().filter(|i| i.row2 == i.row).collect();
  1230. missing.sort_by_key(|i| i.row);
  1231. let mut partners = HashMap::new();
  1232. for i in missing {
  1233. if let Some(k) = free.iter().position(|&r| r > i.row) {
  1234. partners.insert(i.row, free.remove(k));
  1235. }
  1236. }
  1237. partners
  1238. }
  1239. fn unsupported(offset: usize, what: Why) -> Stop {
  1240. Stop::Fail(ShaderError::Unsupported { offset, what })
  1241. }
  1242. impl<'a> Lower<'a> {
  1243. fn new(x: &'a Parts<'a>, bad: &'a HashMap<Value, Why>) -> Self {
  1244. let p = x.p;
  1245. let mut phi_at = HashMap::new();
  1246. for (b, block) in p.blocks.iter().enumerate() {
  1247. for (i, phi) in block.phis.iter().enumerate() {
  1248. phi_at.insert(phi.value, (b, i));
  1249. }
  1250. }
  1251. let mut s = Shader::new(x.native.stage == HwStage::Ps);
  1252. s.inputs = x.inputs.clone();
  1253. s.outputs = x.outputs.clone();
  1254. let insts = || p.blocks.iter().flat_map(|b| &b.insts);
  1255. let writes_uavs = insts().any(|i| {
  1256. matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. })
  1257. && (i.name().contains("store") || i.name().contains("atomic"))
  1258. });
  1259. let mut console_lanes = false;
  1260. // LDS accesses get a group barrier each (a console wave split in two host waves)
  1261. let mut split_lds = false;
  1262. // with `split_lds`, LDS accesses in lane branches: the blocks every lane runs, and
  1263. // where the host waves meet around those branches (`lds_meetings`)
  1264. let mut lds_meet: Option<(Vec<bool>, Vec<(bool, bool)>)> = None;
  1265. // a console wave64 program in two host waves of 32 (`exchange`)
  1266. let mut exchange: Option<(u32, bool, Vec<bool>)> = None;
  1267. // a console wave64 program in host waves of 32: the LDS dword of `wave_base`'s counter
  1268. let mut halves: Option<u32> = None;
  1269. if let StageIo::Cs(cs) = x.native.io {
  1270. s.threads = Some(cs.threads);
  1271. s.lds_dwords = cs.lds_bytes() / 4;
  1272. // Code reading other lanes needs the console's wave size and
  1273. // lane order; so do lane masks read as numbers, and LDS shared
  1274. // within one wave, where the console compiler leaves out barriers.
  1275. console_lanes = insts().any(|i| {
  1276. let n = i.name();
  1277. n.starts_with("ds_swizzle")
  1278. || n.contains("permute")
  1279. || n.starts_with("v_permlane")
  1280. || n.starts_with("v_mbcnt")
  1281. || matches!(n, "v_readlane_b32" | "v_writelane_b32")
  1282. || matches!(&i.fields, Fields::Valu(v) if v.dpp.is_some())
  1283. || reads_mask_as_data(x.st, i)
  1284. }) || lane_constant_masks(x.st)
  1285. // (a branch the wave takes together asks the wave)
  1286. || !x.st.wide.is_empty();
  1287. let mut wave = if x.native.wave64 { 64 } else { 32 };
  1288. let group = cs.threads.iter().product::<u32>();
  1289. let one_wave = group <= wave;
  1290. // A host whose waves are at most 32 lanes (NVIDIA) refuses `WaveSize(64)`. A console
  1291. // wave64 program whose cross-lane code stays inside 32-lane halves – DPP rows,
  1292. // `ds_swizzle`, `v_permlane16` / `v_permlanex16`, which the ISA confines there – runs
  1293. // exactly in waves of 32: the thread relabelling makes each host wave one half of a
  1294. // console wave (lanes 32k..32k+31). Not when it crosses halves (`v_mbcnt`,
  1295. // `v_readlane`, `v_writelane`, `ds_(b)permute`, masks as numbers or lane-constant
  1296. // masks), nor when LDS may be shared within the console wave without barriers (a
  1297. // group over 32 threads with LDS): those still need 64-lane waves.
  1298. if wave == 64 && host_max_wave() == 32 && (console_lanes || one_wave && s.lds_dwords > 0) {
  1299. let crosses = insts().any(|i| {
  1300. let n = i.name();
  1301. n.starts_with("v_mbcnt")
  1302. || matches!(n, "v_readlane_b32" | "v_writelane_b32")
  1303. || n.starts_with("ds_permute")
  1304. || n.starts_with("ds_bpermute")
  1305. || reads_mask_as_data(x.st, i)
  1306. }) || lane_constant_masks(x.st)
  1307. || !x.st.wide.is_empty();
  1308. if !crosses && (s.lds_dwords == 0 || group <= 32) {
  1309. wave = 32;
  1310. } else {
  1311. // (Groups of several console waves too: each console wave is two host
  1312. // waves, which exchange through their own pair of dwords.)
  1313. // LDS the console shares within its one wave without barriers: split into
  1314. // two waves of 32, a group barrier before every LDS access keeps their order
  1315. // – where every thread of the group gets there (no lane branch around it,
  1316. // no guard), else a barrier would hang the group
  1317. let lds = |i: &Inst| {
  1318. matches!(i.fields, Fields::Ds { .. })
  1319. && !(i.name().starts_with("ds_swizzle") || i.name().contains("permute"))
  1320. };
  1321. if let Some(all) = all_lane_blocks(x.st) {
  1322. let ok = p.blocks.iter().enumerate().all(|(b, blk)| {
  1323. blk.insts.iter().all(|inst| {
  1324. !lds(inst) || all.get(b).copied().unwrap_or(false)
  1325. })
  1326. });
  1327. let mut lds_ok = !(s.lds_dwords > 0 && group > 32) || ok;
  1328. if !lds_ok && let Some(meet) = lds_meetings(p, x.st, &all) {
  1329. lds_meet = Some((all.clone(), meet));
  1330. lds_ok = true;
  1331. }
  1332. if !lds_ok {
  1333. // (the blocks whose LDS accesses not every lane runs: with the
  1334. // branches around them taken wave-wide they get their barriers)
  1335. for (b, blk) in p.blocks.iter().enumerate() {
  1336. if !all.get(b).copied().unwrap_or(false) && blk.insts.iter().any(lds) {
  1337. need(b);
  1338. }
  1339. }
  1340. }
  1341. if lds_ok {
  1342. wave = 32;
  1343. split_lds = s.lds_dwords > 0 && group > 32;
  1344. if crosses {
  1345. // lanes 32..63 are the other host wave: masks, lane reads and lane
  1346. // numbers go through two exchange dwords past the program's LDS
  1347. exchange = Some((s.lds_dwords, group <= 32, all));
  1348. s.lds_dwords += 2 * group.div_ceil(64);
  1349. }
  1350. }
  1351. }
  1352. }
  1353. // `VICTORY_WAVE_WHY=1`: why a program keeps 64-lane waves (one line per reason)
  1354. if wave == 64 && std::env::var_os("VICTORY_WAVE_WHY").is_some() {
  1355. let mut why: Vec<&str> = Vec::new();
  1356. for i in insts() {
  1357. let n = i.name();
  1358. let r = if n.starts_with("v_mbcnt") {
  1359. "v_mbcnt"
  1360. } else if n == "v_readlane_b32" {
  1361. "v_readlane"
  1362. } else if n == "v_writelane_b32" {
  1363. "v_writelane"
  1364. } else if n.starts_with("ds_permute") || n.starts_with("ds_bpermute") {
  1365. "ds_(b)permute"
  1366. } else if reads_mask_as_data(x.st, i) {
  1367. "mask as data"
  1368. } else {
  1369. continue;
  1370. };
  1371. if !why.contains(&r) {
  1372. why.push(r);
  1373. }
  1374. }
  1375. if lane_constant_masks(x.st) {
  1376. why.push("lane-constant mask");
  1377. }
  1378. if s.lds_dwords > 0 && group > 32 {
  1379. why.push("LDS in a group over 32");
  1380. match all_lane_blocks(x.st) {
  1381. None => why.push("an indirect exit"),
  1382. Some(all) if lds_meetings(p, x.st, &all).is_none() => {
  1383. why.push("an LDS read and write in one lane-branch region")
  1384. }
  1385. Some(_) => {}
  1386. }
  1387. }
  1388. why.sort_unstable();
  1389. eprintln!("WAVE64-WHY group={group} lds={} [{}]", s.lds_dwords > 0, why.join(", "));
  1390. }
  1391. }
  1392. if wave == 32 && x.native.wave64 {
  1393. // console threads go to host waves in the order the waves take them (`wave_base`)
  1394. halves = Some(s.lds_dwords);
  1395. s.lds_dwords += 1;
  1396. }
  1397. if console_lanes || one_wave && s.lds_dwords > 0 {
  1398. s.wave_size = Some(wave);
  1399. }
  1400. }
  1401. // The title's barriers a thread of the group may never reach, which
  1402. // leaves the others waiting on the host: those in blocks some lanes
  1403. // do not run, and all of them in a program with a loop closed by a
  1404. // plain jump (a lane still in it at the iteration limit leaves the
  1405. // program there, `abort_block`).
  1406. let fence_only: HashSet<usize> = if insts().any(|i| i.name() == "s_barrier") {
  1407. let order = crate::ir::reverse_postorder(&p.blocks);
  1408. let mut place = vec![usize::MAX; p.blocks.len()];
  1409. for (n, &b) in order.iter().enumerate() {
  1410. place[b] = n;
  1411. }
  1412. let back = |from: usize, to: usize| {
  1413. let at = |b: usize| place.get(b).copied().unwrap_or(usize::MAX);
  1414. at(from) != usize::MAX && at(to) <= at(from)
  1415. };
  1416. let cut_short = x
  1417. .st
  1418. .exits
  1419. .iter()
  1420. .enumerate()
  1421. .any(|(b, e)| matches!(*e, LaneExit::Jump(t) if back(b, t)));
  1422. let all = all_lane_blocks(x.st);
  1423. (0..p.blocks.len())
  1424. .filter(|&b| p.blocks[b].insts.iter().any(|i| i.name() == "s_barrier"))
  1425. .filter(|&b| {
  1426. cut_short
  1427. || all
  1428. .as_ref()
  1429. .is_none_or(|all| !all.get(b).copied().unwrap_or(false))
  1430. })
  1431. .collect()
  1432. } else {
  1433. HashSet::new()
  1434. };
  1435. let mut no_barrier = HashSet::new();
  1436. if let StageIo::Ms(ms) = &x.native.io {
  1437. s.prims = x.prims.clone();
  1438. s.threads = Some([ms.threads, 1, 1]);
  1439. s.lds_dwords = ms.lds_bytes.div_ceil(4);
  1440. s.mesh = Some(super::shader::Mesh {
  1441. max_vertices: ms.max_vertices,
  1442. max_primitives: ms.max_primitives,
  1443. topology: ms.topology,
  1444. });
  1445. // Barriers order the lanes' LDS accesses; the console's
  1446. // allocation request needs them too, but the host does not. One
  1447. // lane sends that request, and what it dominates (the path for
  1448. // counts out of range) runs in that lane alone, so its barrier
  1449. // would hang the host.
  1450. let order = crate::ir::reverse_postorder(&p.blocks);
  1451. let mut index = vec![usize::MAX; p.blocks.len()];
  1452. for (n, &b) in order.iter().enumerate() {
  1453. index[b] = n;
  1454. }
  1455. let idom = crate::ir::idoms(&p.blocks, &order, &index);
  1456. let alloc: Vec<usize> = (0..p.blocks.len())
  1457. .filter(|&b| {
  1458. p.blocks[b].insts.iter().any(|i| {
  1459. i.name() == "s_sendmsg"
  1460. && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == GS_ALLOC_REQ)
  1461. })
  1462. })
  1463. .collect();
  1464. for &b in &order {
  1465. let mut d = b;
  1466. let dominated = loop {
  1467. if alloc.contains(&d) {
  1468. break true;
  1469. }
  1470. if idom[d] == d || idom[d] == usize::MAX {
  1471. break false;
  1472. }
  1473. d = idom[d];
  1474. };
  1475. if ms.lds_bytes == 0 || dominated {
  1476. no_barrier.insert(b);
  1477. }
  1478. }
  1479. }
  1480. Lower {
  1481. s,
  1482. x,
  1483. bad,
  1484. lane_fail: HashMap::new(),
  1485. vals: HashMap::new(),
  1486. floats: HashMap::new(),
  1487. block: vec![None; p.blocks.len()],
  1488. cur: 0,
  1489. bools: HashMap::new(),
  1490. lane_bits: HashMap::new(),
  1491. phi_at,
  1492. mask_phis: HashMap::new(),
  1493. pending_masks: Vec::new(),
  1494. data_phis: Vec::new(),
  1495. read_phis: HashSet::new(),
  1496. stale: HashSet::new(),
  1497. ordered: if x.native.stage == HwStage::Ps {
  1498. ordered_section(p)
  1499. } else {
  1500. HashSet::new()
  1501. },
  1502. params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(),
  1503. user_data: None,
  1504. user_reads: BTreeMap::new(),
  1505. samplers: Vec::new(),
  1506. descriptors: x
  1507. .res
  1508. .descriptors
  1509. .iter()
  1510. .map(|d| ((d.site, d.role == Role::Sampler), &d.source))
  1511. .collect(),
  1512. scalar: x.res.scalar.iter().copied().collect(),
  1513. exports: x.io.exports.iter().map(|e| (e.site, e)).collect(),
  1514. interps: {
  1515. let mut m: HashMap<Site, &Interp> = x.io.interps.iter().map(|(s, i)| (*s, i)).collect();
  1516. // A first half whose result is also read as data (an f16 second half keeps
  1517. // the other half of its dst, PS_DeferredTextured): evaluated as the pair it
  1518. // starts. Approximate for those other bits (P0 + i P10 on the console); a
  1519. // first half only the second half reads is gone before lowering.
  1520. if std::env::var_os("VICTORY_FIRST_HALF").is_none_or(|v| v != "0") {
  1521. for (_, i) in &x.io.interps {
  1522. if let Interp::Interpolated { first, .. } = i {
  1523. for s in first {
  1524. m.entry(*s).or_insert(i);
  1525. }
  1526. }
  1527. }
  1528. }
  1529. m
  1530. },
  1531. handles: HashMap::new(),
  1532. strides: HashMap::new(),
  1533. edges: HashMap::new(),
  1534. exported: vec![false; p.blocks.len()],
  1535. rpo: vec![usize::MAX; p.blocks.len()],
  1536. tail: vec![None; p.blocks.len()],
  1537. writes_uavs,
  1538. src0: None,
  1539. console_lanes,
  1540. split_lds,
  1541. lds_meet,
  1542. local: exchange.is_some() && LOCAL_WAVES.get(),
  1543. local_ok: false,
  1544. local_any: LOCAL_ANY.get(),
  1545. uniform: match &exchange {
  1546. Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all),
  1547. _ => HashSet::new(),
  1548. },
  1549. own_bits: match &exchange {
  1550. Some((_, false, _)) if !LOCAL_WAVES.get() && own_bits_on() => {
  1551. super::own_bits::find(p, x.st, std::env::var_os("VICTORY_WAVE_WHY").is_some())
  1552. }
  1553. _ => Default::default(),
  1554. },
  1555. exchange,
  1556. clane: None,
  1557. pair: None,
  1558. halves,
  1559. wave_base: None,
  1560. flat: None,
  1561. no_barrier,
  1562. fence_only,
  1563. half_outputs: half_outputs(&x.native.io, &x.outputs),
  1564. mask_data: match x.native.stage {
  1565. HwStage::Cs => MaskData::Console,
  1566. HwStage::Ps | HwStage::Vs => MaskData::Host,
  1567. _ => MaskData::None,
  1568. },
  1569. mask_ok: false,
  1570. ballots: HashMap::new(),
  1571. balloting: HashSet::new(),
  1572. def_block: p
  1573. .blocks
  1574. .iter()
  1575. .enumerate()
  1576. .flat_map(|(b, block)| {
  1577. block
  1578. .insts
  1579. .iter()
  1580. .flat_map(move |i| i.writes.iter().map(move |w| (w.1, b)))
  1581. .chain(block.phis.iter().map(move |phi| (phi.value, b)))
  1582. })
  1583. .collect(),
  1584. cur_ir: 0,
  1585. sections: HashMap::new(),
  1586. section_out: HashSet::new(),
  1587. code_table: None,
  1588. counters: HashMap::new(),
  1589. abort: None,
  1590. }
  1591. }
  1592. /// The dword of the program's code at byte `byte` (a constant table
  1593. /// the compiler appends to the code), as an internal constant array.
  1594. // shortcut: an index outside the table reads its last dword (the
  1595. // console would read whatever memory follows the code).
  1596. fn code_dword(&mut self, byte: V) -> Result<V, Why> {
  1597. let (g, base, len) = match self.code_table {
  1598. Some(t) => t,
  1599. None => {
  1600. let first = self
  1601. .x
  1602. .res
  1603. .scalar
  1604. .iter()
  1605. .map(|s| s.1)
  1606. .chain(self.x.res.descriptors.iter().flat_map(|d| {
  1607. d.source.leaves().into_iter().filter_map(|l| match l {
  1608. Source::Built { address, .. } => Some(*address),
  1609. _ => None,
  1610. })
  1611. }))
  1612. .filter(|a| a.param == CODE)
  1613. .map(|a| a.offset & !3)
  1614. .min()
  1615. .ok_or("a code table")?;
  1616. let code = &self.x.native.code;
  1617. let words: Vec<u32> = code
  1618. .get(first as usize..)
  1619. .ok_or("a code table past the code")?
  1620. .chunks(4)
  1621. .map(|c| {
  1622. let mut w = [0u8; 4];
  1623. w[..c.len()].copy_from_slice(c);
  1624. u32::from_le_bytes(w)
  1625. })
  1626. .collect();
  1627. if words.is_empty() {
  1628. return Err("a code table past the code");
  1629. }
  1630. let elems: Vec<V> = words.iter().map(|&w| self.s.m.i32(w)).collect();
  1631. let arr = self.s.m.array(words.len() as u32, self.s.t.i32);
  1632. let init = self.s.m.aggregate(arr, &elems);
  1633. let g = self.s.m.constant_global("code", init);
  1634. let t = (g, first, words.len() as u32);
  1635. self.code_table = Some(t);
  1636. t
  1637. }
  1638. };
  1639. let c = self.cur;
  1640. let k = self.s.m.i32(base);
  1641. let rel = self.s.m.bin(c, Bin::Sub, byte, k);
  1642. let two = self.s.m.i32(2);
  1643. let index = self.s.m.bin(c, Bin::LShr, rel, two);
  1644. let last = self.s.m.i32(len - 1);
  1645. let over = self.s.m.cmp(c, pred::IUGT, index, last);
  1646. let index = self.s.m.select(c, over, last, index);
  1647. let at = self.s.m.element(c, g, index);
  1648. Ok(self.s.m.load(c, at))
  1649. }
  1650. /// A global memory load (`global_load_*`): from the program's constant
  1651. /// table, or from a root SRV at the address the title sets.
  1652. fn flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  1653. let Fields::Flat { dst, .. } = &inst.fields else {
  1654. unreachable!()
  1655. };
  1656. let name = inst.name();
  1657. if self.scalar.get(&(b, i)).is_some_and(|a| a.param == MEMORY) {
  1658. return self.memory_flat(inst, b, i);
  1659. }
  1660. let rest = name
  1661. .strip_prefix("global_load_")
  1662. .ok_or("a global memory write")?;
  1663. let (n, sub) = match rest {
  1664. "dword" => (1, None),
  1665. "dwordx2" => (2, None),
  1666. "dwordx3" => (3, None),
  1667. "dwordx4" => (4, None),
  1668. "ubyte" => (1, Some((8, false))),
  1669. "sbyte" => (1, Some((8, true))),
  1670. "ushort" => (1, Some((16, false))),
  1671. "sshort" => (1, Some((16, true))),
  1672. _ => return Err(name),
  1673. };
  1674. let a = *self
  1675. .scalar
  1676. .get(&(b, i))
  1677. .ok_or("an untracked global address")?;
  1678. let guard = self.guard(b, i)?;
  1679. let Some(Operand::Vector { reg, .. }) = *dst else {
  1680. return Err("a global load result");
  1681. };
  1682. let c = self.cur;
  1683. let mut off = self.s.m.i32(a.offset);
  1684. if let Some(d) = a.dynamic {
  1685. let d = self.i32_of(d)?;
  1686. off = self.s.m.bin(c, Bin::Add, off, d);
  1687. }
  1688. let h = if a.param == CODE {
  1689. None
  1690. } else {
  1691. let src = Source::Built {
  1692. address: a,
  1693. bits: 0,
  1694. words: [0, 0],
  1695. };
  1696. if let Some(bias) = self.root_bias(a.param) {
  1697. off = self.s.m.bin(c, Bin::Add, off, bias);
  1698. }
  1699. Some(self.handle((b, i), &src, false, (11, 0))?)
  1700. };
  1701. let dword = |l: &mut Self, byte: V| -> Result<V, Why> {
  1702. match h {
  1703. None => l.code_dword(byte),
  1704. Some(h) => {
  1705. let c = l.cur;
  1706. let (u, mask, al) = (l.s.m.undef(l.s.t.i32), l.s.m.i8(1), l.s.m.i32(4));
  1707. let r = l.s.op(
  1708. c,
  1709. "rawBufferLoad.f32",
  1710. Attr::ReadOnly,
  1711. l.s.t.res_ret,
  1712. 139,
  1713. &[h, byte, u, mask, al],
  1714. );
  1715. let x = l.s.m.extract(c, r, 0);
  1716. Ok(l.as_int(x))
  1717. }
  1718. }
  1719. };
  1720. for k in 0..n {
  1721. let x = match sub {
  1722. None => {
  1723. let four = self.s.m.i32(4 * k);
  1724. let at = self.s.m.bin(c, Bin::Add, off, four);
  1725. dword(self, at)?
  1726. }
  1727. Some((width, signed)) => {
  1728. // shortcut: the field is taken not to cross a dword.
  1729. let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3));
  1730. let at = self.s.m.bin(c, Bin::And, off, not3);
  1731. let w = dword(self, at)?;
  1732. let byte = self.s.m.bin(c, Bin::And, off, three);
  1733. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  1734. let x = self.s.m.bin(c, Bin::LShr, w, sh);
  1735. let left = self.s.m.i32(32 - width);
  1736. let x = self.s.m.bin(c, Bin::Shl, x, left);
  1737. self.s
  1738. .m
  1739. .bin(c, if signed { Bin::AShr } else { Bin::LShr }, x, left)
  1740. }
  1741. };
  1742. self.write(inst, Reg::V(reg + k as u8), x, guard);
  1743. }
  1744. Ok(())
  1745. }
  1746. /// Finds the whole-wave sections and the values they leave.
  1747. fn find_sections(&mut self) {
  1748. let p = self.x.p;
  1749. let mut inside: HashMap<Value, (usize, usize, usize)> = HashMap::new();
  1750. for b in 0..p.blocks.len() {
  1751. let found = super::wave::sections(p, b);
  1752. for (&start, sec) in &found {
  1753. for i in start + 1..sec.end {
  1754. for &(_, w) in &p.blocks[b].insts[i].writes {
  1755. inside.insert(w, (b, start, sec.end));
  1756. }
  1757. }
  1758. }
  1759. if !found.is_empty() {
  1760. self.sections.insert(b, found);
  1761. }
  1762. }
  1763. if inside.is_empty() {
  1764. return;
  1765. }
  1766. for (b, block) in p.blocks.iter().enumerate() {
  1767. for phi in &block.phis {
  1768. self.section_out
  1769. .extend(phi.args.iter().filter(|a| inside.contains_key(a)));
  1770. }
  1771. for (i, inst) in block.insts.iter().enumerate() {
  1772. for &(_, r) in &inst.reads {
  1773. if let Some(&(sb, start, end)) = inside.get(&r)
  1774. && !(sb == b && i > start && i < end)
  1775. {
  1776. self.section_out.insert(r);
  1777. }
  1778. }
  1779. }
  1780. }
  1781. }
  1782. /// An instruction inside a whole-wave section: the values that leave
  1783. /// the section are made from what the simulation found them to be.
  1784. fn section_inst(&mut self, b: usize, i: usize, start: usize) {
  1785. const UNKNOWN: Why = "a whole-wave section step the simulation does not follow";
  1786. let inst = &self.x.p.blocks[b].insts[i];
  1787. for &(_, w) in &inst.writes {
  1788. let val = if self.section_out.contains(&w) {
  1789. let shape = self.sections[&b][&start].shapes.get(&w).copied();
  1790. let own = self.own_bits.totals.contains(&w);
  1791. match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh, own)) {
  1792. Ok(x) => Val::I32(x),
  1793. Err(why) => Val::Missing(why),
  1794. }
  1795. } else {
  1796. Val::Missing(UNKNOWN)
  1797. };
  1798. self.vals.insert(w, val);
  1799. }
  1800. }
  1801. /// A value a whole-wave section leaves, as DXIL wave operations over the
  1802. /// host's active lanes: the console's result with console lanes; on
  1803. /// another wave size, what the HLSL wave operation the console compiler
  1804. /// expanded gives on that wave.
  1805. ///
  1806. /// `own`: a wave OR that only steers a loop over each lane's own bits
  1807. /// ([`super::own_bits`]); where two host waves cannot exchange their halves' ORs it is
  1808. /// this host wave's.
  1809. fn shape(&mut self, shape: super::wave::Shape, own: bool) -> Result<V, Why> {
  1810. use super::wave::{Op, Shape};
  1811. let (op, src, mask, ident, prefix) = match shape {
  1812. Shape::K(k) => return Ok(self.s.m.i32(k)),
  1813. Shape::Value(v) => return self.i32_of(v),
  1814. Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None),
  1815. Shape::ActiveF64(lo, hi, mask, high) => {
  1816. return self.active_f64_sum(lo, hi, mask, high);
  1817. }
  1818. Shape::Masked(src, mask, ident) => {
  1819. let c = self.cur;
  1820. let &m = self
  1821. .x
  1822. .st
  1823. .masks
  1824. .get(&mask)
  1825. .ok_or("a wave reduction's untracked mask")?;
  1826. let on = self.boolean(m, c)?;
  1827. let x = self.i32_of(src)?;
  1828. let id = self.s.m.i32(ident);
  1829. return Ok(self.s.m.select(c, on, x, id));
  1830. }
  1831. Shape::Prefix(op, src, mask, ident, inclusive) => {
  1832. (op, src, mask, ident, Some(inclusive))
  1833. }
  1834. };
  1835. // Mesh: no host wave size can be declared, so a reduction is over this host wave
  1836. // only. A minimum or maximum is taken that way: the compiler's "next distinct
  1837. // value" loop (the wave's minimum, then the lanes that hold it) serves every
  1838. // lane however the lanes are divided into waves. A sum, a bit reduction or a
  1839. // prefix would be of part of a console wave: still refused.
  1840. if self.mask_data == MaskData::None
  1841. && (prefix.is_some()
  1842. || !matches!(
  1843. op,
  1844. Op::MinU | Op::MaxU | Op::MinI | Op::MaxI | Op::MinF | Op::MaxF
  1845. ))
  1846. {
  1847. return Err("a wave reduction in a mesh shader");
  1848. }
  1849. let c = self.cur;
  1850. let &m = self
  1851. .x
  1852. .st
  1853. .masks
  1854. .get(&mask)
  1855. .ok_or("a wave reduction's untracked mask")?;
  1856. let on = self.boolean(m, c)?;
  1857. let x = self.i32_of(src)?;
  1858. let id = self.s.m.i32(ident);
  1859. let x = self.s.m.select(c, on, x, id);
  1860. self.s.flags |= flags::WAVE_OPS;
  1861. if op == Op::AddH {
  1862. return match prefix {
  1863. Some(_) => Err("a wave prefix of an operation other than a sum"),
  1864. None => self.half_sum(x),
  1865. };
  1866. }
  1867. let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF);
  1868. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  1869. let arg = if float { self.as_float(x) } else { x };
  1870. let ty = if float { f32t } else { i32t };
  1871. let sfx = if float { "f32" } else { "i32" };
  1872. let r = match (op, prefix) {
  1873. (Op::AddU | Op::AddF, Some(inclusive)) => {
  1874. let (k0, k1) = (self.s.m.i8(0), self.s.m.i8(1));
  1875. let r = self.s.op(
  1876. c,
  1877. &format!("wavePrefixOp.{sfx}"),
  1878. Attr::NoUnwind,
  1879. ty,
  1880. 121,
  1881. &[arg, k0, k1],
  1882. );
  1883. if inclusive {
  1884. self.s.m.bin(c, Bin::Add, r, arg)
  1885. } else {
  1886. r
  1887. }
  1888. }
  1889. (_, Some(_)) => return Err("a wave prefix of an operation other than a sum"),
  1890. (Op::Or | Op::And | Op::Xor, None) => {
  1891. let k = self.s.m.i8(match op {
  1892. Op::And => 0,
  1893. Op::Or => 1,
  1894. _ => 2,
  1895. });
  1896. self.s
  1897. .op(c, "waveActiveBit.i32", Attr::NoUnwind, i32t, 120, &[arg, k])
  1898. }
  1899. (_, None) => {
  1900. let (code, unsigned) = match op {
  1901. Op::AddU => (0, 1),
  1902. Op::AddF => (0, 0),
  1903. Op::MinU => (2, 1),
  1904. Op::MaxU => (3, 1),
  1905. Op::MinI | Op::MinF => (2, 0),
  1906. _ => (3, 0),
  1907. };
  1908. let (k, u) = (self.s.m.i8(code), self.s.m.i8(unsigned));
  1909. self.s.op(
  1910. c,
  1911. &format!("waveActiveOp.{sfx}"),
  1912. Attr::NoUnwind,
  1913. ty,
  1914. 119,
  1915. &[arg, k, u],
  1916. )
  1917. }
  1918. };
  1919. // two host waves of 32 hold the console's 64 lanes: their results combine
  1920. let r = if self.local || self.exchange.as_ref().is_some_and(|e| e.1) {
  1921. // this host wave's own result (and prefix): each wave on its own, or a group of
  1922. // 32 threads or fewer, which one host wave holds whole (combining with the 0 a
  1923. // missing half "gives" broke AND, MIN and signed MAX)
  1924. r
  1925. } else if own && prefix.is_none() && op == Op::Or && !self.all_lanes(self.cur_ir) {
  1926. // each thread walks the bits of this value and works only at its own, which the
  1927. // host wave's OR holds: the same run as with the console wave's OR
  1928. r
  1929. } else if self.exchange.is_some() {
  1930. if !self.all_lanes(self.cur_ir) {
  1931. need(self.cur_ir);
  1932. return Err("a wave reduction where not every lane runs");
  1933. }
  1934. let bits = |l: &mut Self, v: V| if float { l.as_int(v) } else { v };
  1935. let back = |l: &mut Self, v: V| if float { l.as_float(v) } else { v };
  1936. match prefix {
  1937. Some(_) => {
  1938. // the upper half adds the lower half's total to its prefix
  1939. let (k0, ku) = (self.s.m.i8(0), self.s.m.i8(u8::from(!float)));
  1940. let total = self.s.op(c, &format!("waveActiveOp.{sfx}"), Attr::NoUnwind, ty, 119, &[arg, k0, ku]);
  1941. let tb = bits(self, total);
  1942. let c = self.cur;
  1943. let (lo, _) = self.exchange_halves(c, tb);
  1944. let lo = back(self, lo);
  1945. let cl = self.console_lane();
  1946. let k32 = self.s.m.i32(32);
  1947. let upper = self.s.m.cmp(c, pred::IUGE, cl, k32);
  1948. let zero = if float { self.s.m.f32(0) } else { self.s.m.i32(0) };
  1949. let add = self.s.m.select(c, upper, lo, zero);
  1950. self.s.m.bin(c, Bin::Add, r, add)
  1951. }
  1952. None => {
  1953. let rb = bits(self, r);
  1954. let c = self.cur;
  1955. let (lo, hi) = self.exchange_halves(c, rb);
  1956. let (lo, hi) = (back(self, lo), back(self, hi));
  1957. match op {
  1958. Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, lo, hi),
  1959. Op::Or => self.s.m.bin(c, Bin::Or, lo, hi),
  1960. Op::And => self.s.m.bin(c, Bin::And, lo, hi),
  1961. Op::Xor => self.s.m.bin(c, Bin::Xor, lo, hi),
  1962. _ => {
  1963. // FMax 35, FMin 36, IMax 37, IMin 38, UMax 39, UMin 40
  1964. let code = match op {
  1965. Op::MaxF => 35,
  1966. Op::MinF => 36,
  1967. Op::MinU => 40,
  1968. Op::MaxU => 39,
  1969. Op::MinI => 38,
  1970. _ => 37,
  1971. };
  1972. self.s.op(c, &format!("binary.{sfx}"), Attr::ReadNone, ty, code, &[lo, hi])
  1973. }
  1974. }
  1975. }
  1976. }
  1977. } else {
  1978. r
  1979. };
  1980. Ok(if float { self.as_int(r) } else { r })
  1981. }
  1982. /// `WaveActiveSum` of 64-bit floats (`f64(lo, hi)` in active lanes, `+0.0` elsewhere),
  1983. /// returning the low (`!high`) or high (`high`) 32-bit word.
  1984. fn active_f64_sum(
  1985. &mut self,
  1986. lo: Value,
  1987. hi: Value,
  1988. mask: Value,
  1989. high: bool,
  1990. ) -> Result<V, Why> {
  1991. if self.mask_data == MaskData::None {
  1992. return Err("a wave reduction in a mesh shader");
  1993. }
  1994. let c = self.cur;
  1995. let &m = self
  1996. .x
  1997. .st
  1998. .masks
  1999. .get(&mask)
  2000. .ok_or("a wave reduction's untracked mask")?;
  2001. let on = self.boolean(m, c)?;
  2002. let lo = self.i32_of(lo)?;
  2003. let hi = self.i32_of(hi)?;
  2004. let z = self.s.m.i32(0);
  2005. let lo = self.s.m.select(c, on, lo, z);
  2006. let hi = self.s.m.select(c, on, hi, z);
  2007. self.s.flags |= flags::WAVE_OPS | flags::DOUBLES;
  2008. let f64t = self.s.m.double();
  2009. let i32t = self.s.t.i32;
  2010. let split_ty = self
  2011. .s
  2012. .m
  2013. .named_struct("dx.types.splitdouble", vec![i32t, i32t]);
  2014. let arg = self
  2015. .s
  2016. .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]);
  2017. let (k0, k0b) = (self.s.m.i8(0), self.s.m.i8(0));
  2018. let sum = self
  2019. .s
  2020. .op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[arg, k0, k0b]);
  2021. let split = self
  2022. .s
  2023. .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[sum]);
  2024. let mut r_lo = self.s.m.extract(c, split, 0);
  2025. let mut r_hi = self.s.m.extract(c, split, 1);
  2026. if self.exchange.is_some() {
  2027. if !self.all_lanes(self.cur_ir) {
  2028. need(self.cur_ir);
  2029. return Err("a wave reduction where not every lane runs");
  2030. }
  2031. let (lo0, lo1) = self.exchange_halves(self.cur, r_lo);
  2032. let (hi0, hi1) = self.exchange_halves(self.cur, r_hi);
  2033. let c = self.cur;
  2034. let d0 = self
  2035. .s
  2036. .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo0, hi0]);
  2037. let d1 = self
  2038. .s
  2039. .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo1, hi1]);
  2040. let total = self.s.m.bin(c, Bin::Add, d0, d1);
  2041. let split = self
  2042. .s
  2043. .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[total]);
  2044. r_lo = self.s.m.extract(c, split, 0);
  2045. r_hi = self.s.m.extract(c, split, 1);
  2046. }
  2047. Ok(if high { r_hi } else { r_lo })
  2048. }
  2049. /// The sum of two 16-bit floats (the low halves of `a` and `b`) as the console's
  2050. /// `v_add_f16` gives it: added in f32 and rounded to 16 bits, to nearest
  2051. /// ([`Self::f16_nearest`]).
  2052. fn add_halves(&mut self, a: V, b: V) -> V {
  2053. let c = self.cur;
  2054. let f32t = self.s.t.f32;
  2055. let low = self.s.m.i32(0xFFFF);
  2056. let wide = |l: &mut Self, x: V| {
  2057. let h = l.s.m.bin(c, Bin::And, x, low);
  2058. l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h])
  2059. };
  2060. let (fa, fb) = (wide(self, a), wide(self, b));
  2061. let f = self.s.m.bin(c, Bin::Add, fa, fb);
  2062. self.f16_nearest(f)
  2063. }
  2064. /// `WaveActiveSum` of 16-bit floats (`x`: each lane's term in its low half, +0 in the
  2065. /// lanes outside the mask), bit for bit as the console adds it: every addition rounds to
  2066. /// 16 bits, so the order counts, and the compiler's is the balanced tree over the lanes
  2067. /// in their order (lanes 2k and 2k+1, then pairs, ... then the wave's two halves;
  2068. /// [`super::wave::buddies`]). Each lane adds its partner's partial sum, read from the
  2069. /// lane whose number differs in one bit, step by step; two host waves of 32 then exchange
  2070. /// their halves' sums for the last addition. The high half of the result is lane 0's,
  2071. /// which no `v_add_f16` writes.
  2072. /// On a host wave of 64 lanes where not every lane runs, the lanes that are elsewhere
  2073. /// count as the console's do (it masks them to +0): a partner's partial sum is read from
  2074. /// the first lane there is of the partner's run of lanes, and is +0 without one. Two host
  2075. /// waves of 32 can only exchange where every lane runs: refused elsewhere, in a thread
  2076. /// group that does not fill its waves, and for each half-wave on its own (half a sum is
  2077. /// no sum).
  2078. fn half_sum(&mut self, x: V) -> Result<V, Why> {
  2079. const WHERE: Why = "a wave sum of 16-bit floats where not every lane runs";
  2080. let threads = self.s.threads.ok_or("a wave sum of 16-bit floats outside compute")?;
  2081. if threads.iter().product::<u32>() % 64 != 0 {
  2082. return Err("a wave sum of 16-bit floats in a wave that is not full");
  2083. }
  2084. if self.local {
  2085. return Err("a wave sum of 16-bit floats in a half-wave");
  2086. }
  2087. // two host waves of 32 that exchange, or one host wave of 64 lanes
  2088. let halves = match (&self.exchange, self.s.wave_size) {
  2089. (Some((_, false, _)), _) => true,
  2090. (None, Some(64)) if self.x.p.wave64 => false,
  2091. _ => return Err("a wave sum of 16-bit floats on these waves"),
  2092. };
  2093. let every = if halves {
  2094. self.all_lanes(self.cur_ir)
  2095. } else {
  2096. all_lane_blocks(self.x.st).is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false))
  2097. };
  2098. if !every && halves {
  2099. need(self.cur_ir);
  2100. return Err(WHERE);
  2101. }
  2102. let c = self.cur;
  2103. let i32t = self.s.t.i32;
  2104. let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  2105. let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0));
  2106. // the lanes that are here, when not all are
  2107. let here = (!every).then(|| {
  2108. self.s.flags |= flags::WAVE_OPS;
  2109. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  2110. let yes = self.s.m.bool(true);
  2111. let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[yes]);
  2112. (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1))
  2113. });
  2114. // `v` of the first lane here of the `n` (a power of two) lanes from `base`: +0 of none
  2115. let first_of = |l: &mut Self, v: V, base: V, n: u32| {
  2116. let Some((lo, hi)) = here else {
  2117. return l.read_lane(v, base);
  2118. };
  2119. let (k31, k32) = (l.s.m.i32(31), l.s.m.i32(32));
  2120. let lower = l.s.m.cmp(c, pred::IULT, base, k32);
  2121. let word = l.s.m.select(c, lower, lo, hi);
  2122. let shift = l.s.m.bin(c, Bin::And, base, k31);
  2123. let word = l.s.m.bin(c, Bin::LShr, word, shift);
  2124. let run = l.s.m.i32(u32::MAX >> (32 - n));
  2125. let word = l.s.m.bin(c, Bin::And, word, run);
  2126. let any = l.s.m.cmp(c, pred::NE, word, zero);
  2127. let nth = l.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[word]);
  2128. let from = l.s.m.bin(c, Bin::Add, base, nth);
  2129. // (no lane there: this one, which is here; the read is not used)
  2130. let from = l.s.m.select(c, any, from, lane);
  2131. let got = l.read_lane(v, from);
  2132. l.s.m.select(c, any, got, zero)
  2133. };
  2134. let mut sum = x;
  2135. for step in 0..if halves { 5 } else { 6 } {
  2136. let bit = self.s.m.i32(1 << step);
  2137. let mut partner = self.s.m.bin(c, Bin::Xor, lane, bit);
  2138. if !every {
  2139. let run = self.s.m.i32(!((1 << step) - 1));
  2140. partner = self.s.m.bin(c, Bin::And, partner, run);
  2141. }
  2142. let theirs = first_of(self, sum, partner, 1 << step);
  2143. sum = self.add_halves(sum, theirs);
  2144. }
  2145. let first = first_of(self, x, zero, 1);
  2146. let first = self.s.m.bin(c, Bin::And, first, high);
  2147. let sum = self.s.m.bin(c, Bin::And, sum, low);
  2148. let mine = self.s.m.bin(c, Bin::Or, first, sum);
  2149. if !halves {
  2150. return Ok(mine);
  2151. }
  2152. let (lo, hi) = self.exchange_halves(c, mine);
  2153. let c = self.cur;
  2154. let total = self.add_halves(lo, hi);
  2155. let total = self.s.m.bin(c, Bin::And, total, low);
  2156. let first = self.s.m.bin(c, Bin::And, lo, high);
  2157. Ok(self.s.m.bin(c, Bin::Or, first, total))
  2158. }
  2159. fn run(mut self) -> Result<Lowered, Stop> {
  2160. let p = self.x.p;
  2161. let order = crate::ir::reverse_postorder(&p.blocks);
  2162. for (n, &b) in order.iter().enumerate() {
  2163. self.rpo[b] = n;
  2164. }
  2165. for (n, &b) in order.iter().enumerate() {
  2166. self.block[b] = Some(if n == 0 {
  2167. self.s.entry
  2168. } else {
  2169. self.s.m.new_block()
  2170. });
  2171. }
  2172. // Loop headers count iterations (`LOOP_LIMIT`).
  2173. for &b in &order {
  2174. let header = p.blocks[b]
  2175. .preds
  2176. .iter()
  2177. .any(|&q| self.block[q].is_some() && self.rpo[b] <= self.rpo[q]);
  2178. if header {
  2179. let blk = self.block[b].expect("reachable");
  2180. let phi = self.s.m.phi(blk, self.s.t.i32);
  2181. self.counters.insert(b, (phi, Vec::new()));
  2182. }
  2183. }
  2184. self.cur = self.s.entry;
  2185. self.find_sections();
  2186. self.inputs()?;
  2187. if let Some(mesh) = self.s.mesh {
  2188. self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?;
  2189. self.block[order[0]] = Some(self.cur);
  2190. }
  2191. for &b in &order {
  2192. self.cur = self.block[b].expect("reachable");
  2193. self.cur_ir = b;
  2194. let preds: Vec<usize> = p.blocks[b]
  2195. .preds
  2196. .iter()
  2197. .copied()
  2198. .filter(|&q| self.block[q].is_some())
  2199. .collect();
  2200. self.exported[b] = !preds.is_empty() && preds.iter().all(|&q| self.exported_out(q));
  2201. for (i, phi) in p.blocks[b].phis.iter().enumerate() {
  2202. let val = match phi.reg {
  2203. Reg::S(c) if c == EXEC || c == EXEC + 1 => Val::Missing("a lane mask"),
  2204. _ if self.bad.contains_key(&phi.value) => Val::Missing(self.bad[&phi.value]),
  2205. Reg::Scc => {
  2206. let v = self.s.m.phi(self.cur, self.s.t.i1);
  2207. self.data_phis.push((v, b, i));
  2208. Val::Bit(v)
  2209. }
  2210. _ => {
  2211. let v = self.s.m.phi(self.cur, self.s.t.i32);
  2212. self.data_phis.push((v, b, i));
  2213. Val::I32(v)
  2214. }
  2215. };
  2216. self.vals.insert(phi.value, val);
  2217. }
  2218. if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].0) {
  2219. self.lds_meeting();
  2220. }
  2221. let mut i = 0;
  2222. while i < p.blocks[b].insts.len() {
  2223. self.inst(b, i)?;
  2224. if let Some(end) = self.sections.get(&b).and_then(|s| s.get(&i)).map(|s| s.end) {
  2225. for j in i + 1..end {
  2226. self.section_inst(b, j, i);
  2227. }
  2228. i = end;
  2229. continue;
  2230. }
  2231. i += 1;
  2232. }
  2233. self.mask_ok = self.mask_data == MaskData::Console;
  2234. if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].1) {
  2235. self.lds_meeting();
  2236. }
  2237. self.tail[b] = Some(self.cur);
  2238. self.exit(b)?;
  2239. }
  2240. self.fill_phis()?;
  2241. let user_data = self.user_reads.values().copied().collect();
  2242. self.s.samplers = self.samplers.len() as u32;
  2243. let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect();
  2244. let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect();
  2245. let root_uavs = self.s.root_uavs.iter().map(|r| r.0).collect();
  2246. let cmp_samplers = self.s.cmp_samplers;
  2247. let wave_size = self.s.wave_size;
  2248. Ok(Lowered {
  2249. wave_size,
  2250. cmp_samplers,
  2251. root_cbvs,
  2252. root_srvs,
  2253. root_uavs,
  2254. #[cfg(test)]
  2255. nonuniform_handles: self.s.nonuniform_handles,
  2256. #[cfg(test)]
  2257. wave_ops: self.s.flags & flags::WAVE_OPS != 0,
  2258. dxil: self.s.finish(),
  2259. user_data,
  2260. samplers: self.samplers,
  2261. })
  2262. }
  2263. fn exported_out(&self, b: usize) -> bool {
  2264. self.exported[b] || self.has_done_export(b)
  2265. }
  2266. fn has_done_export(&self, b: usize) -> bool {
  2267. (0..self.x.p.blocks[b].insts.len())
  2268. .any(|i| self.exports.get(&(b, i)).is_some_and(|e| e.done))
  2269. }
  2270. /// Values of the program's input registers.
  2271. fn inputs(&mut self) -> Result<(), Stop> {
  2272. let io_inputs: HashMap<Value, Input> = self.x.io.inputs.iter().copied().collect();
  2273. for &(reg, v) in &self.x.p.inputs {
  2274. let val = match reg {
  2275. Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use
  2276. // Most programs only interpolate with them: loaded on first
  2277. // use as a value (`get`).
  2278. Reg::V(_) if matches!(io_inputs.get(&v), Some(Input::Barycentric { .. })) => {
  2279. continue;
  2280. }
  2281. Reg::S(n) => match io_inputs.get(&v) {
  2282. Some(&input) => self.input(input),
  2283. // Above the SGPRs the hardware initializes, a register
  2284. // holds what the last wave left, so no program depends
  2285. // on it: a read the paths only seem to allow (a branch
  2286. // past the write, taken only with one past the read)
  2287. // reads zero, as VGPRs do.
  2288. None if n <= 105 && self.x.io.initialized_sgprs.is_some_and(|k| n >= k) => {
  2289. Val::I32(self.s.m.i32(0))
  2290. }
  2291. // A scalar parked in a VGPR lane (`ir::unspill`), read where the
  2292. // paths only seem to allow it before any save: the lane of a VGPR
  2293. // nobody wrote, and VGPRs nobody set read as zero.
  2294. None if n >= crate::ir::PARKED => Val::I32(self.s.m.i32(0)),
  2295. // No wave overlaps this one (see `ordered_section`).
  2296. None if self.pops_collision(v) => Val::I32(self.s.m.i32(0)),
  2297. None => Val::Missing("a hardware SGPR input"),
  2298. },
  2299. Reg::Scc => Val::Missing("SCC on entry"),
  2300. Reg::V(_) => match io_inputs.get(&v) {
  2301. Some(&input) => self.input(input),
  2302. // Registers no one set read as zero (the validator
  2303. // refuses reads of undef).
  2304. None => Val::I32(self.s.m.i32(0)),
  2305. },
  2306. };
  2307. self.vals.insert(v, val);
  2308. }
  2309. Ok(())
  2310. }
  2311. /// Whether the input SGPR `v` is the POPS collision wave id: a program
  2312. /// with an ordered section only takes its fields apart (bit 31 says
  2313. /// that the wave overlaps another, the others which packer and waves).
  2314. fn pops_collision(&self, v: Value) -> bool {
  2315. if self.ordered.is_empty() {
  2316. return false;
  2317. }
  2318. let mut packer = false;
  2319. for block in &self.x.p.blocks {
  2320. if block.phis.iter().any(|p| p.args.contains(&v)) {
  2321. return false;
  2322. }
  2323. for i in &block.insts {
  2324. if !i.reads.iter().any(|r| r.1 == v) {
  2325. continue;
  2326. }
  2327. let Fields::Sop { src, .. } = &i.fields else {
  2328. return false;
  2329. };
  2330. match (i.name(), src.get(1)) {
  2331. // bits 28 and 29: the packer
  2332. ("s_bfe_u32", Some(Operand::Literal(0x0002_001C))) => packer = true,
  2333. ("s_bfe_u32" | "s_lshr_b32", _) => {}
  2334. _ => return false,
  2335. }
  2336. }
  2337. }
  2338. packer
  2339. }
  2340. fn input(&mut self, input: Input) -> Val {
  2341. let (kind, col) = match input {
  2342. Input::VertexId => (1, 0),
  2343. Input::InstanceId => (2, 0),
  2344. Input::Position(c) => (3, c),
  2345. Input::Attribute { row, channel } => {
  2346. return match self.find_input(row, channel) {
  2347. Some((id, col)) => self.load_input(id, col),
  2348. None => Val::Missing("a vertex input the signature lacks"),
  2349. };
  2350. }
  2351. Input::Barycentric { kind, index } => return self.barycentric(kind, index),
  2352. Input::PrimitiveId => return Val::Missing("the primitive id"),
  2353. // The console code tests it against 0 (`v_cmp_ne_u32`), as the
  2354. // host's value can be.
  2355. Input::FrontFace => (13, 0),
  2356. Input::ThreadIdInGroup(c) => return self.thread_id(c),
  2357. Input::GroupId(c) => return self.compute_id("groupId.i32", 94, c),
  2358. Input::GroupInfo => return Val::Missing("the thread-group info SGPR"),
  2359. Input::MeshGroup => {
  2360. let Val::I32(g) = self.compute_id("groupId.i32", 94, 0) else {
  2361. unreachable!()
  2362. };
  2363. let n = self.s.m.i32(self.x.mesh_stride);
  2364. return Val::I32(self.s.m.bin(self.s.entry, Bin::Mul, g, n));
  2365. }
  2366. Input::MergedWaveInfo => {
  2367. // shortcut: only the wave index (bits 24-27) is set; the
  2368. // console's other bits (lane counts) are read by no program.
  2369. let f = self.mesh_thread();
  2370. let shift = self.s.m.i32(self.wave().trailing_zeros());
  2371. let w = self.s.m.bin(self.s.entry, Bin::LShr, f, shift);
  2372. let k24 = self.s.m.i32(24);
  2373. return Val::I32(self.s.m.bin(self.s.entry, Bin::Shl, w, k24));
  2374. }
  2375. _ => return Val::Missing("a pixel system input"),
  2376. };
  2377. let free = self
  2378. .s
  2379. .inputs
  2380. .iter()
  2381. .filter_map(|e| e.row)
  2382. .map(|r| r + 1)
  2383. .max()
  2384. .unwrap_or(0);
  2385. let id = match self.s.inputs.iter().position(|e| e.kind == kind) {
  2386. Some(id) => {
  2387. if kind != 3 {
  2388. self.s.inputs[id].row.get_or_insert(free);
  2389. }
  2390. id
  2391. }
  2392. None if kind >= 3 => return Val::Missing("a pixel system input the signature lacks"),
  2393. None => {
  2394. // The console signature leaves out vertex and instance ids; PC
  2395. // gives them a row after the others.
  2396. let row = self
  2397. .s
  2398. .inputs
  2399. .iter()
  2400. .filter_map(|e| e.row)
  2401. .map(|r| r + 1)
  2402. .max()
  2403. .unwrap_or(0);
  2404. self.s.inputs.push(SigElement {
  2405. name: ["", "SV_VertexID", "SV_InstanceID"][kind as usize].into(),
  2406. index: 0,
  2407. kind,
  2408. comp: 5,
  2409. interp: 0,
  2410. row: Some(row),
  2411. col: 0,
  2412. cols: 1,
  2413. usage: 0,
  2414. half: false,
  2415. });
  2416. self.s.inputs.len() - 1
  2417. }
  2418. };
  2419. self.load_input(id, col)
  2420. }
  2421. /// A component of a compute thread or group id, read in the entry block.
  2422. fn compute_id(&mut self, name: &str, opcode: u32, c: u8) -> Val {
  2423. let (entry, c) = (self.s.entry, self.s.m.i32(u32::from(c)));
  2424. Val::I32(
  2425. self.s
  2426. .op(entry, name, Attr::ReadNone, self.s.t.i32, opcode, &[c]),
  2427. )
  2428. }
  2429. fn find_input(&self, row: u8, channel: u8) -> Option<(usize, u8)> {
  2430. self.s.inputs.iter().enumerate().find_map(|(id, e)| {
  2431. let r = e.row?;
  2432. // `then`, not `then_some`: the channel is only past `col` when
  2433. // the condition holds.
  2434. (r == u32::from(row) && channel >= e.col && channel < e.col + e.cols)
  2435. .then(|| (id, channel - e.col))
  2436. })
  2437. }
  2438. fn load_input(&mut self, id: usize, col: u8) -> Val {
  2439. if self.s.inputs[id].half {
  2440. // shortcut: 16-bit vertex inputs (the fetch routine's) are not
  2441. // unpacked; pixel inputs are (`interp`).
  2442. return Val::Missing("a 16-bit input");
  2443. }
  2444. self.load_any_input(id, col)
  2445. }
  2446. /// An input element's channel as declared (16-bit ones as 32-bit floats).
  2447. fn load_any_input(&mut self, id: usize, col: u8) -> Val {
  2448. let e = &mut self.s.inputs[id];
  2449. e.usage |= 1 << col;
  2450. let (int, bit) = (e.comp != 9, e.comp == 1);
  2451. let ty = if bit {
  2452. self.s.t.i1
  2453. } else if int {
  2454. self.s.t.i32
  2455. } else {
  2456. self.s.t.f32
  2457. };
  2458. let suffix = if bit {
  2459. ".i1"
  2460. } else if int {
  2461. ".i32"
  2462. } else {
  2463. ".f32"
  2464. };
  2465. let entry = self.s.entry;
  2466. let args = [
  2467. self.s.m.i32(id as u32),
  2468. self.s.m.i32(0),
  2469. self.s.m.i8(col),
  2470. self.s.m.undef(self.s.t.i32),
  2471. ];
  2472. let v = self.s.op(
  2473. entry,
  2474. &format!("loadInput{suffix}"),
  2475. Attr::ReadNone,
  2476. ty,
  2477. 4,
  2478. &args,
  2479. );
  2480. if bit {
  2481. let z = self.s.m.cast(entry, Cast::ZExt, v, self.s.t.i32);
  2482. Val::I32(z)
  2483. } else if int {
  2484. Val::I32(v)
  2485. } else {
  2486. Val::I32(self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.i32))
  2487. }
  2488. }
  2489. /// The DXIL form of an IR value.
  2490. fn get(&mut self, v: Value) -> Result<Val, Why> {
  2491. if self.phi_at.contains_key(&v) {
  2492. self.read_phis.insert(v);
  2493. }
  2494. let is_mask = self.x.st.masks.contains_key(&v) || self.x.st.highs.contains_key(&v);
  2495. match self.vals.get(&v) {
  2496. Some(&Val::Missing(_)) | None if self.mask_ok && is_mask => {
  2497. return self.mask_dword(v).map(Val::I32);
  2498. }
  2499. Some(&Val::Missing(w)) => return Err(w),
  2500. Some(&val) => return Ok(val),
  2501. None => {}
  2502. }
  2503. if let Some(&(param, dword)) = self.params.get(&v) {
  2504. let val = self.user(param, dword);
  2505. self.vals.insert(v, val);
  2506. return Ok(val);
  2507. }
  2508. if let Some(loaded) = self.lazy_barycentric(v) {
  2509. loaded?;
  2510. return Ok(self.vals[&v]);
  2511. }
  2512. Err("a value defined after its use")
  2513. }
  2514. /// Loads `v` if it is a barycentric input VGPR not loaded yet (see
  2515. /// `inputs`): `None` if it is not one.
  2516. fn lazy_barycentric(&mut self, v: Value) -> Option<Result<(), Why>> {
  2517. let (kind, index) = self.x.io.inputs.iter().find_map(|&(w, i)| match i {
  2518. Input::Barycentric { kind, index } if w == v => Some((kind, index)),
  2519. _ => None,
  2520. })?;
  2521. let val = self.barycentric(kind, index);
  2522. self.vals.insert(v, val);
  2523. Some(match val {
  2524. Val::Missing(w) => Err(w),
  2525. _ => Ok(()),
  2526. })
  2527. }
  2528. /// Barycentric `index` (0 i, 1 j) of `kind` as a value: a channel of
  2529. /// `SV_Barycentrics` declared with the same interpolation mode.
  2530. ///
  2531. /// GFX10 interpolates P0 + i (P1 - P0) + j (P2 - P0), so i and j are
  2532. /// the weights of vertices 1 and 2. The host's weights (x, y, z) are
  2533. /// those of vertices 0, 1 and 2, vertex 0 being the provoking vertex,
  2534. /// which is the console's P0 (`v_interp_mov` P0 is lowered to a flat
  2535. /// input): i is y and j is z.
  2536. /// shortcut: triangles only; on lines and points the console's i and j
  2537. /// are not checked against the host's weights.
  2538. fn barycentric(&mut self, kind: Barycentric, index: u8) -> Val {
  2539. let Some(mode) = interp_mode(kind) else {
  2540. return Val::Missing("pull-model barycentrics");
  2541. };
  2542. if index > 1 {
  2543. return Val::Missing("pull-model barycentrics");
  2544. }
  2545. // One element per interpolation mode (the console's own, if its
  2546. // signature declares one): DXIL allows two.
  2547. let bary = |e: &SigElement| e.kind == 28;
  2548. let id = match self
  2549. .s
  2550. .inputs
  2551. .iter()
  2552. .position(|e| bary(e) && (e.interp == mode || e.usage == 0))
  2553. {
  2554. Some(id) => id,
  2555. None => {
  2556. let index = self.s.inputs.iter().filter(|e| bary(e)).count() as u32;
  2557. if index >= 2 {
  2558. return Val::Missing("barycentrics of a third interpolation mode");
  2559. }
  2560. // A system value the validator wants unpacked (packing
  2561. // location -1), like other non-packed system values.
  2562. self.s.inputs.push(SigElement {
  2563. name: "SV_Barycentrics".into(),
  2564. index,
  2565. kind: 28,
  2566. comp: 9,
  2567. interp: mode,
  2568. row: None,
  2569. col: 0,
  2570. cols: 3,
  2571. usage: 0,
  2572. half: false,
  2573. });
  2574. self.s.inputs.len() - 1
  2575. }
  2576. };
  2577. let e = &mut self.s.inputs[id];
  2578. if e.col != 0 || e.cols < 3 {
  2579. return Val::Missing("a console barycentrics element without i and j");
  2580. }
  2581. e.row = None;
  2582. e.interp = mode;
  2583. self.s.flags |= flags::BARYCENTRICS;
  2584. self.load_any_input(id, index + 1)
  2585. }
  2586. fn i32_of(&mut self, v: Value) -> Result<V, Why> {
  2587. match self.get(v)? {
  2588. Val::I32(x) => Ok(x),
  2589. Val::Bit(x) => Ok(self.s.m.cast(self.cur, Cast::ZExt, x, self.s.t.i32)),
  2590. Val::Missing(w) => Err(w),
  2591. }
  2592. }
  2593. /// A user-data dword: a root parameter's value.
  2594. fn user(&mut self, param: usize, dword: u32) -> Val {
  2595. let rp = self.x.native.layout[param];
  2596. match rp.root {
  2597. RootType::ResourceHeap | RootType::SamplerHeap => return Val::I32(self.s.m.i32(0)),
  2598. RootType::Constants | RootType::Table => {}
  2599. _ => return Val::Missing("a root descriptor"),
  2600. }
  2601. let index = u32::from(rp.user_data) + dword - self.user_first();
  2602. self.user_reads.insert(
  2603. index,
  2604. UserData {
  2605. index,
  2606. slot: rp.slot,
  2607. root: rp.root,
  2608. dword,
  2609. },
  2610. );
  2611. Val::I32(self.user_at(index))
  2612. }
  2613. /// The user-data index that is dword 0 of the host's user data: 0, or
  2614. /// 16 for a program with a spilled user-data table, whose parameters
  2615. /// all sit at 16 and above. (The host's root signature has 64 dwords:
  2616. /// a builder stage with constants up to index 45, eight root views,
  2617. /// their biases and the memory directory would not fit with 16 dwords
  2618. /// nothing reads in front.)
  2619. fn user_first(&self) -> u32 {
  2620. if crate::spill::is_spilled(self.x.native) {
  2621. 16
  2622. } else {
  2623. 0
  2624. }
  2625. }
  2626. /// A user-data dword no register of the console's holds: one the host
  2627. /// computes when it binds (`root` says what, an `Other` code of
  2628. /// `shader.rs`), placed after the layout's own dwords.
  2629. fn host_word(&mut self, root: RootType, slot: u8, dword: u32) -> V {
  2630. let known = self
  2631. .user_reads
  2632. .values()
  2633. .find(|u| u.root == root && u.slot == slot && u.dword == dword)
  2634. .map(|u| u.index);
  2635. let index = match known {
  2636. Some(index) => index,
  2637. None => {
  2638. let first = self.user_first();
  2639. let layout = &self.x.native.layout;
  2640. let mut index = layout
  2641. .iter()
  2642. .map(|e| u32::from(e.user_data) + e.sgprs)
  2643. .max()
  2644. .unwrap_or(0)
  2645. .saturating_sub(first);
  2646. while self.user_reads.contains_key(&index) {
  2647. index += 1;
  2648. }
  2649. self.user_reads.insert(
  2650. index,
  2651. UserData {
  2652. index,
  2653. slot,
  2654. root,
  2655. dword,
  2656. },
  2657. );
  2658. index
  2659. }
  2660. };
  2661. self.user_at(index)
  2662. }
  2663. /// User-data dword `index`, loaded in the entry block.
  2664. fn user_at(&mut self, index: u32) -> V {
  2665. self.s.user_data = self.s.user_data.max(index + 1);
  2666. let h = match self.user_data {
  2667. Some(h) => h,
  2668. None => {
  2669. let h = self.s.user_data_handle();
  2670. self.user_data = Some(h);
  2671. h
  2672. }
  2673. };
  2674. let entry = self.s.entry;
  2675. let row = self.s.m.i32(index / 4);
  2676. let r = self.s.op(
  2677. entry,
  2678. "cbufferLoadLegacy.i32",
  2679. Attr::ReadOnly,
  2680. self.s.t.cbuf_ret,
  2681. 59,
  2682. &[h, row],
  2683. );
  2684. self.s.m.extract(entry, r, index % 4)
  2685. }
  2686. /// Whether some instruction reads `v` as a number (or may, through a
  2687. /// join), rather than in a descriptor operand.
  2688. fn read_as_number(&self, v: Value) -> bool {
  2689. self.x.p.blocks.iter().any(|b| {
  2690. b.phis.iter().any(|p| p.args.contains(&v))
  2691. || b.insts.iter().any(|i| {
  2692. matches!(i.fields, Fields::Sop { .. } | Fields::Valu(_))
  2693. && i.reads.iter().any(|r| r.1 == v)
  2694. })
  2695. })
  2696. }
  2697. /// Whether some instruction computes with `v` (scalar or vector
  2698. /// arithmetic), rather than only naming it in a descriptor operand,
  2699. /// moving it (at most `depth` moves are followed) or comparing it: a
  2700. /// waterfall loop keeps a descriptor's dwords per lane, reads the first
  2701. /// lane's back and compares the lanes' with them.
  2702. fn computed_with(&self, v: Value, depth: u32) -> bool {
  2703. self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| {
  2704. if !i.reads.iter().any(|r| r.1 == v) {
  2705. return false;
  2706. }
  2707. let name = i.name();
  2708. let moves = matches!(
  2709. name,
  2710. "s_mov_b32"
  2711. | "s_mov_b64"
  2712. | "v_mov_b32"
  2713. | "v_readfirstlane_b32"
  2714. | "v_readlane_b32"
  2715. | "v_writelane_b32"
  2716. | "v_cndmask_b32"
  2717. );
  2718. match &i.fields {
  2719. Fields::Sop { .. } | Fields::Valu(_) if moves => {
  2720. depth > 0 && i.writes.iter().any(|w| self.computed_with(w.1, depth - 1))
  2721. }
  2722. Fields::Sop { .. } | Fields::Valu(_) => {
  2723. !(name.starts_with("v_cmp") || name.starts_with("s_cmp"))
  2724. }
  2725. _ => false,
  2726. }
  2727. })
  2728. }
  2729. /// Whether the image `src` names is one of 32-bit integers (one channel):
  2730. /// the program has an integer atomic on the same table entry, which
  2731. /// takes no other view.
  2732. fn is_counter(&self, src: &Source) -> bool {
  2733. let entry = |s: &Source| match s {
  2734. Source::Loaded { load, first } => self
  2735. .scalar
  2736. .get(load)
  2737. .filter(|a| a.dynamic.is_none())
  2738. .map(|a| (a.param, a.offset + 4 * u32::from(*first))),
  2739. _ => None,
  2740. };
  2741. let Some(this) = entry(src) else {
  2742. return false;
  2743. };
  2744. self.x.res.descriptors.iter().any(|d| {
  2745. let i = &self.x.p.blocks[d.site.0].insts[d.site.1];
  2746. d.role == Role::Resource
  2747. && matches!(i.fields, Fields::Image { dmask: 1, .. })
  2748. && matches!(
  2749. i.name(),
  2750. "image_atomic_add"
  2751. | "image_atomic_sub"
  2752. | "image_atomic_and"
  2753. | "image_atomic_or"
  2754. | "image_atomic_xor"
  2755. | "image_atomic_smin"
  2756. | "image_atomic_smax"
  2757. | "image_atomic_umin"
  2758. | "image_atomic_umax"
  2759. )
  2760. && entry(&d.source) == Some(this)
  2761. })
  2762. }
  2763. /// The kind of a view no instruction uses (in this program, or through
  2764. /// another load of its address), by what the code reads of the
  2765. /// descriptor the load `inst` at `site` writes to the SGPRs from `code`:
  2766. /// `Some(true)` for a 2D image, read only for its size, `Some(false)`
  2767. /// for a structured buffer, read only for its record count.
  2768. ///
  2769. /// - Eight dwords are an image's. `GetDimensions` of a 2D one reads the
  2770. /// width (dwords 1 and 2), the height (dword 2, bits 14-29, with one
  2771. /// `s_bfe_u32`) and the base level or the last (dword 3); of an array,
  2772. /// a cube or a volume also dword 4.
  2773. /// - Four dwords at a table entry the used resources list as an SRV or
  2774. /// UAV are a buffer's. A stride above 4 bytes there is an element's
  2775. /// (a typed or raw view has at most 4): a test for a null view reads
  2776. /// the record count, nothing else.
  2777. fn sized_view(&self, inst: &Inst, site: Site, code: u8, count: u32) -> Option<bool> {
  2778. let dword = |k: u8| inst.write(Reg::S(code + k));
  2779. let read = |v: Value| {
  2780. self.x.p.blocks.iter().any(|b| {
  2781. b.insts.iter().any(|i| i.reads.iter().any(|r| r.1 == v))
  2782. || b.phis.iter().any(|p| p.args.contains(&v))
  2783. })
  2784. };
  2785. let only = |allowed: &[u8]| {
  2786. (0..count as u8).all(|k| allowed.contains(&k) || !dword(k).is_some_and(read))
  2787. };
  2788. match count {
  2789. 8 => {
  2790. const HEIGHT: u32 = 16 << 16 | 14;
  2791. let v = dword(2)?;
  2792. let height = self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| {
  2793. i.name() == "s_bfe_u32"
  2794. && i.reads.iter().any(|r| r.1 == v)
  2795. && matches!(&i.fields, Fields::Sop { src, .. }
  2796. if matches!(src.get(1), Some(Operand::Literal(HEIGHT))))
  2797. });
  2798. (height && only(&[1, 2, 3])).then_some(true)
  2799. }
  2800. 4 => {
  2801. let used = self.used_kind(&Source::Loaded { load: site, first: 0 })?;
  2802. let a = self.scalar.get(&site)?;
  2803. let buffer = used.dwords == 4
  2804. && a.dynamic.is_none()
  2805. && used.table_offset_dwords == a.offset / 4
  2806. && matches!(used.kind, ResourceType::Srv | ResourceType::Uav)
  2807. && used.stride > 4
  2808. && used.stride.is_multiple_of(4);
  2809. (buffer && only(&[2])).then_some(false)
  2810. }
  2811. _ => None,
  2812. }
  2813. }
  2814. /// The title address (low dword, bits from 32 up) of the buffer view
  2815. /// whose descriptor the scalar load at `site` reads from the start of
  2816. /// a table entry, as the host tells it when it binds (`shader.rs`
  2817. /// `USER_VIEW_ADDRESS`); none for anything else. (The console's
  2818. /// descriptor holds more in the second dword, the stride from bit 16
  2819. /// up; code that takes the address masks those away.)
  2820. fn view_address(&mut self, site: Site) -> Option<(V, V)> {
  2821. use super::shader::USER_VIEW_ADDRESS;
  2822. let a = self.scalar.get(&site).copied()?;
  2823. let rp = *self.x.native.layout.get(a.param)?;
  2824. if rp.root != RootType::Table || a.dynamic.is_some() || a.offset % 32 != 0 {
  2825. return None;
  2826. }
  2827. let dword = a.offset / 4;
  2828. let used = self
  2829. .x
  2830. .native
  2831. .used
  2832. .iter()
  2833. .filter(|u| {
  2834. u.root == RootType::Table
  2835. && u.user_data == rp.user_data
  2836. && u.table_offset_dwords <= dword
  2837. })
  2838. .max_by_key(|u| u.table_offset_dwords)?;
  2839. if used.dwords != 4 || !matches!(used.kind, ResourceType::Srv | ResourceType::Uav) {
  2840. return None;
  2841. }
  2842. let lo = self.host_word(RootType::Other(USER_VIEW_ADDRESS), rp.slot, dword);
  2843. let hi = self.host_word(RootType::Other(USER_VIEW_ADDRESS + 1), rp.slot, dword);
  2844. Some((lo, hi))
  2845. }
  2846. /// `lo`, `hi` plus the instruction's byte offset `off`, with the carry.
  2847. fn address_plus(&mut self, lo: V, hi: V, off: i32) -> (V, V) {
  2848. if off == 0 {
  2849. return (lo, hi);
  2850. }
  2851. let c = self.cur;
  2852. let i32t = self.s.t.i32;
  2853. let k = self.s.m.i32(off as u32);
  2854. let sum = self.s.m.bin(c, Bin::Add, lo, k);
  2855. // Up: a carry when the sum wrapped below `lo`. Down: a borrow when
  2856. // it wrapped above.
  2857. let wrapped = self
  2858. .s
  2859. .m
  2860. .cmp(c, if off > 0 { pred::IULT } else { pred::IUGT }, sum, lo);
  2861. let one = self.s.m.cast(c, Cast::ZExt, wrapped, i32t);
  2862. let hi = self.s.m.bin(c, if off > 0 { Bin::Add } else { Bin::Sub }, hi, one);
  2863. (sum, hi)
  2864. }
  2865. /// Title memory at the 40-bit address `lo`, `hi` (`shader.rs`
  2866. /// `SLOT_MEMORY`): the handle of the raw view of the host copy holding
  2867. /// it and the byte in that view. A page without a copy reads zeros
  2868. /// (and drops writes) through the null view at the first slot, and its
  2869. /// number is left for the host, for lanes that run (`guard`).
  2870. fn memory(&mut self, lo: V, hi: V, guard: Option<V>) -> (V, V) {
  2871. use super::shader::{MEMORY_FAULTS, MEMORY_PAGES, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE};
  2872. let c = self.cur;
  2873. let (i32t, res) = (self.s.t.i32, self.s.t.res_ret);
  2874. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  2875. let (k16, k8) = (k(self, 16), k(self, 0xFF));
  2876. let low = self.s.m.bin(c, Bin::LShr, lo, k16);
  2877. let high = self.s.m.bin(c, Bin::And, hi, k8);
  2878. let high = self.s.m.bin(c, Bin::Shl, high, k16);
  2879. let page = self.s.m.bin(c, Bin::Or, low, high);
  2880. // Inside the directory whatever the address (lanes that do not run
  2881. // compute one too); its last entry is never filled.
  2882. let last = k(self, MEMORY_PAGES - 1);
  2883. let page = self
  2884. .s
  2885. .op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[page, last]);
  2886. self.s.m.tag(page, Tag::Clamp);
  2887. let k3 = k(self, 3);
  2888. let at = self.s.m.bin(c, Bin::Shl, page, k3);
  2889. let directory = self.s.root_srv_handle(SLOT_MEMORY);
  2890. let (iu, both, align) = (self.s.m.undef(i32t), self.s.m.i8(3), k(self, 4));
  2891. let entry = self.s.op(
  2892. c,
  2893. "rawBufferLoad.f32",
  2894. Attr::ReadOnly,
  2895. res,
  2896. 139,
  2897. &[directory, at, iu, both, align],
  2898. );
  2899. let (copy, start) = (self.s.m.extract(c, entry, 0), self.s.m.extract(c, entry, 1));
  2900. let (copy, start) = (self.as_int(copy), self.as_int(start));
  2901. // A page without a copy: its number, at a place by the number, or
  2902. // at the sink for lanes that do not run and pages that have one.
  2903. let zero = k(self, 0);
  2904. let mut missing = self.s.m.cmp(c, pred::EQ, copy, zero);
  2905. if let Some(g) = guard {
  2906. missing = self.s.m.bin(c, Bin::And, missing, g);
  2907. }
  2908. let places = k(self, MEMORY_FAULTS - 1);
  2909. let place = self.s.m.bin(c, Bin::URem, page, places);
  2910. let one = k(self, 1);
  2911. let place = self.s.m.bin(c, Bin::Add, place, one);
  2912. let k2 = k(self, 2);
  2913. let place = self.s.m.bin(c, Bin::Shl, place, k2);
  2914. let place = self.s.m.select(c, missing, place, zero);
  2915. let faults = self.s.root_uav_handle(SLOT_FAULTS);
  2916. let void = self.s.t.void;
  2917. let mask = self.s.m.i8(1);
  2918. self.s.op(
  2919. c,
  2920. "rawBufferStore.i32",
  2921. Attr::NoUnwind,
  2922. void,
  2923. 140,
  2924. &[faults, place, iu, page, iu, iu, iu, mask, align],
  2925. );
  2926. let base = self.host_word(RootType::Other(USER_MEMORY_BASE), 0, 0);
  2927. let slot = self.s.m.bin(c, Bin::Add, base, copy);
  2928. let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000, 0));
  2929. let k64k = k(self, 0xFFFF);
  2930. let within = self.s.m.bin(c, Bin::And, lo, k64k);
  2931. let byte = self.s.m.bin(c, Bin::Add, start, within);
  2932. (h, byte)
  2933. }
  2934. /// `global_load_*`, `global_store_*` and `global_atomic_*` on title
  2935. /// memory by address (`resource::MEMORY`): the address is the VGPR
  2936. /// pair, each lane its own.
  2937. fn memory_flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  2938. let Fields::Flat {
  2939. dst,
  2940. addr,
  2941. data,
  2942. saddr,
  2943. offset,
  2944. lds,
  2945. cache,
  2946. } = &inst.fields
  2947. else {
  2948. unreachable!()
  2949. };
  2950. if *lds || !matches!(saddr, None | Some(Operand::Scalar { code: NULL, .. })) {
  2951. return Err("a global address with a scalar base");
  2952. }
  2953. let Some(Operand::Vector { reg: areg, .. }) = *addr else {
  2954. return Err("a global address not in VGPRs");
  2955. };
  2956. let word = |l: &mut Self, k: u8| -> Result<V, Why> {
  2957. let v = inst.read(Reg::V(areg + k)).ok_or("a global address")?;
  2958. l.i32_of(v)
  2959. };
  2960. let (lo, hi) = (word(self, 0)?, word(self, 1)?);
  2961. let (lo, hi) = self.address_plus(lo, hi, i32::from(*offset));
  2962. let guard = self.guard(b, i)?;
  2963. let c = self.cur;
  2964. let (i32t, res, void) = (self.s.t.i32, self.s.t.res_ret, self.s.t.void);
  2965. let iu = self.s.m.undef(i32t);
  2966. let align = self.s.m.i32(4);
  2967. let name = inst.name();
  2968. let count = |rest: &str| match rest {
  2969. "dword" => Ok(1u8),
  2970. "dwordx2" => Ok(2),
  2971. "dwordx3" => Ok(3),
  2972. "dwordx4" => Ok(4),
  2973. _ => Err(name),
  2974. };
  2975. if let Some(rest) = name.strip_prefix("global_load_") {
  2976. let n = count(rest)?;
  2977. let Some(Operand::Vector { reg, .. }) = *dst else {
  2978. return Err("a global load result");
  2979. };
  2980. let (h, byte) = self.memory(lo, hi, guard);
  2981. let mask = self.s.m.i8((1u8 << n) - 1);
  2982. let r = self.s.op(
  2983. c,
  2984. "rawBufferLoad.f32",
  2985. Attr::ReadOnly,
  2986. res,
  2987. 139,
  2988. &[h, byte, iu, mask, align],
  2989. );
  2990. for k in 0..n {
  2991. let x = self.s.m.extract(c, r, u32::from(k));
  2992. let x = self.as_int(x);
  2993. self.write(inst, Reg::V(reg + k), x, guard);
  2994. }
  2995. return Ok(());
  2996. }
  2997. if let Some(rest) = name.strip_prefix("global_store_") {
  2998. let n = count(rest)?;
  2999. let d = data.as_ref().ok_or("global store data")?;
  3000. let vals = self.vgprs(inst, d, n)?;
  3001. let (h, byte) = self.memory(lo, hi, guard);
  3002. let mut args = vec![h, byte, iu];
  3003. args.extend(&vals);
  3004. args.resize(3 + 4, iu);
  3005. args.push(self.s.m.i8((1u8 << n) - 1));
  3006. args.push(align);
  3007. let at = self.begin_guarded(guard);
  3008. self.s
  3009. .op(self.cur, "rawBufferStore.i32", Attr::NoUnwind, void, 140, &args);
  3010. self.end_guarded(at, &[]);
  3011. return Ok(());
  3012. }
  3013. let Some(op) = name.strip_prefix("global_atomic_") else {
  3014. return Err(name);
  3015. };
  3016. let d = data.as_ref().ok_or("global atomic data")?;
  3017. let v = self.vgprs(inst, d, 1)?[0];
  3018. // With `glc` the value from before comes back, in the result
  3019. // register the instruction names.
  3020. let back = match (*dst, cache.glc) {
  3021. (Some(Operand::Vector { reg, .. }), true) => Some(reg),
  3022. _ => None,
  3023. };
  3024. let old = match back.and_then(|reg| inst.read(Reg::V(reg))) {
  3025. Some(x) => self.i32_of(x)?,
  3026. None => self.s.m.i32(0),
  3027. };
  3028. let (h, byte) = self.memory(lo, hi, guard);
  3029. // DXIL's atomic operations: add 0, and 1, or 2, xor 3, signed
  3030. // minimum 4 and maximum 5, unsigned 6 and 7, exchange 8.
  3031. let simple = match op {
  3032. "add" => Some((0, v)),
  3033. "sub" => {
  3034. let zero = self.s.m.i32(0);
  3035. Some((0, self.s.m.bin(c, Bin::Sub, zero, v)))
  3036. }
  3037. "and" => Some((1, v)),
  3038. "or" => Some((2, v)),
  3039. "xor" => Some((3, v)),
  3040. "smin" => Some((4, v)),
  3041. "smax" => Some((5, v)),
  3042. "umin" => Some((6, v)),
  3043. "umax" => Some((7, v)),
  3044. "swap" => Some((8, v)),
  3045. "fmin" | "fmax" => None,
  3046. _ => return Err(name),
  3047. };
  3048. let at = self.begin_guarded(guard);
  3049. let was = match simple {
  3050. Some((code, x)) => {
  3051. let code = self.s.m.i32(code);
  3052. self.s.op(
  3053. self.cur,
  3054. "atomicBinOp.i32",
  3055. Attr::NoUnwind,
  3056. i32t,
  3057. 78,
  3058. &[h, code, byte, iu, iu, x],
  3059. )
  3060. }
  3061. None => {
  3062. // A float minimum or maximum has no atomic operation on
  3063. // the host: the dword is exchanged for the smaller (larger)
  3064. // of itself and the value until no other thread got in
  3065. // between. Each failed pass means another one's succeeded;
  3066. // the limit only keeps a broken card from hanging.
  3067. let head = self.cur;
  3068. let mask = self.s.m.i8(1);
  3069. let first = self.s.op(
  3070. head,
  3071. "rawBufferLoad.f32",
  3072. Attr::ReadOnly,
  3073. res,
  3074. 139,
  3075. &[h, byte, iu, mask, align],
  3076. );
  3077. let first = self.s.m.extract(head, first, 0);
  3078. let first = self.as_int(first);
  3079. let (pass, done) = (self.s.m.new_block(), self.s.m.new_block());
  3080. self.s.m.terminate(head, Term::Br(pass));
  3081. self.cur = pass;
  3082. let seen = self.s.m.phi(pass, i32t);
  3083. let n = self.s.m.phi(pass, i32t);
  3084. let (f32t, fv) = (self.s.t.f32, self.as_float(v));
  3085. let fseen = self.as_float(seen);
  3086. // `dx.op.binary`: FMax 35, FMin 36.
  3087. let pick = if op == "fmin" { 36 } else { 35 };
  3088. let wanted = self
  3089. .s
  3090. .op(pass, "binary.f32", Attr::ReadNone, f32t, pick, &[fseen, fv]);
  3091. let wanted = self.as_int(wanted);
  3092. let found = self.s.op(
  3093. pass,
  3094. "atomicCompareExchange.i32",
  3095. Attr::NoUnwind,
  3096. i32t,
  3097. 79,
  3098. &[h, byte, iu, iu, seen, wanted],
  3099. );
  3100. let one = self.s.m.i32(1);
  3101. let n1 = self.s.m.bin(pass, Bin::Add, n, one);
  3102. let lost = self.s.m.cmp(pass, pred::NE, found, seen);
  3103. let limit = self.s.m.i32(1 << 16);
  3104. let more = self.s.m.cmp(pass, pred::IULT, n1, limit);
  3105. let again = self.s.m.bin(pass, Bin::And, lost, more);
  3106. self.s.m.terminate(pass, Term::CondBr(again, pass, done));
  3107. let zero = self.s.m.i32(0);
  3108. self.s.m.set_phi(seen, vec![(first, head), (found, pass)]);
  3109. self.s.m.set_phi(n, vec![(zero, head), (n1, pass)]);
  3110. self.cur = done;
  3111. found
  3112. }
  3113. };
  3114. let was = self.end_guarded(at, &[(was, old)])[0];
  3115. if let Some(reg) = back {
  3116. self.write(inst, Reg::V(reg), was, None);
  3117. }
  3118. Ok(())
  3119. }
  3120. /// `s_load_dword*` from title memory by address (`resource::MEMORY`):
  3121. /// the SGPR pair plus the instruction's offsets.
  3122. fn memory_smem(&mut self, inst: &Inst) -> Result<(), Why> {
  3123. let Fields::Smem {
  3124. data: Some(Operand::Scalar { code, .. }),
  3125. base: Operand::Scalar { code: base, .. },
  3126. offset,
  3127. soffset,
  3128. ..
  3129. } = inst.fields
  3130. else {
  3131. return Err("a scalar load from memory");
  3132. };
  3133. let count = match inst.name().strip_prefix("s_load_dword") {
  3134. Some("") => 1u8,
  3135. Some("x2") => 2,
  3136. Some("x4") => 4,
  3137. Some("x8") => 8,
  3138. Some("x16") => 16,
  3139. _ => return Err("a scalar memory access by address"),
  3140. };
  3141. let word = |l: &mut Self, k: u8| -> Result<V, Why> {
  3142. let v = inst.read(Reg::S(base + k)).ok_or("an address not in SGPRs")?;
  3143. l.i32_of(v)
  3144. };
  3145. let (mut lo, mut hi) = (word(self, 0)?, word(self, 1)?);
  3146. let c = self.cur;
  3147. let (i32t, res) = (self.s.t.i32, self.s.t.res_ret);
  3148. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  3149. // An offset register counts up from the address.
  3150. let so = self.operand(inst, &soffset)?;
  3151. let sum = self.s.m.bin(c, Bin::Add, lo, so);
  3152. let carry = self.s.m.cmp(c, pred::IULT, sum, lo);
  3153. let carry = self.s.m.cast(c, Cast::ZExt, carry, i32t);
  3154. hi = self.s.m.bin(c, Bin::Add, hi, carry);
  3155. lo = sum;
  3156. }
  3157. let (iu, align) = (self.s.m.undef(i32t), self.s.m.i32(4));
  3158. for first in (0..count).step_by(4) {
  3159. let n = (count - first).min(4);
  3160. let (lo, hi) = self.address_plus(lo, hi, offset + 4 * i32::from(first));
  3161. let (h, byte) = self.memory(lo, hi, None);
  3162. let mask = self.s.m.i8((1u8 << n) - 1);
  3163. let r = self.s.op(
  3164. c,
  3165. "rawBufferLoad.f32",
  3166. Attr::ReadOnly,
  3167. res,
  3168. 139,
  3169. &[h, byte, iu, mask, align],
  3170. );
  3171. for k in 0..n {
  3172. let x = self.s.m.extract(c, r, u32::from(k));
  3173. let x = self.as_int(x);
  3174. self.write(inst, Reg::S(code + first + k), x, None);
  3175. }
  3176. }
  3177. Ok(())
  3178. }
  3179. /// A dword of a lane mask as a number: the ballot of the lanes' bits,
  3180. /// taken in the block that writes the mask (see [`MaskData`]).
  3181. fn mask_dword(&mut self, v: Value) -> Result<V, Why> {
  3182. let (lo, high) = match self.x.st.highs.get(&v) {
  3183. Some(&lo) => (lo, true),
  3184. None => (v, false),
  3185. };
  3186. let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?;
  3187. // A mask that holds lanes outside EXEC where it is written (the complement of one,
  3188. // say) is the ballot of the lanes that are there: all of them, where two exchanging
  3189. // host waves know every lane runs that block.
  3190. let made = self.def_block.get(&lo).copied();
  3191. let whole = self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b));
  3192. if !self.x.st.active.contains(&lo) && !whole {
  3193. if self.exchange.is_some() && !self.local {
  3194. need(made.unwrap_or(0));
  3195. }
  3196. if std::env::var_os("VICTORY_DESC_WHY").is_some() {
  3197. let by = made.map(|b| &self.x.p.blocks[b]);
  3198. let def = by.and_then(|b| b.insts.iter().find(|i| i.writes.iter().any(|w| w.1 == lo)));
  3199. eprintln!("MASK-WHY {v:?} made in {made:?} by {:?} at {:x?}; read in block at {:#x}; phi {}", def.map(|i| i.name()), def.map(|i| i.machine.offset), self.x.p.blocks[self.cur_ir].offset, self.phi_at.contains_key(&lo));
  3200. }
  3201. return Err(MASK_ELSEWHERE);
  3202. }
  3203. let (x, y) = match self.ballots.get(&lo) {
  3204. Some(&xy) => xy,
  3205. None => {
  3206. let at = match self.def_block.get(&lo) {
  3207. // Program inputs (EXEC on entry).
  3208. None => self.s.entry,
  3209. Some(&b) if b == self.cur_ir => self.cur,
  3210. Some(&b) => self.tail[b].ok_or("a lane mask written after its use")?,
  3211. };
  3212. if !self.balloting.insert(lo) {
  3213. return Err("a lane mask whose lanes depend on its own value");
  3214. }
  3215. let bit = self.boolean(m, at);
  3216. self.balloting.remove(&lo);
  3217. let bit = bit?;
  3218. let i32t = self.s.t.i32;
  3219. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  3220. let r = self
  3221. .s
  3222. .op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, &[bit]);
  3223. self.s.flags |= flags::WAVE_OPS;
  3224. let mut xy = (self.s.m.extract(at, r, 0), self.s.m.extract(at, r, 1));
  3225. if self.exchange.is_some() {
  3226. // a host wave's ballot is its half's 32 bits: the halves exchange them
  3227. let b = self.def_block.get(&lo).copied();
  3228. if self.local {
  3229. if !self.local_ok && !self.local_any {
  3230. return Err("a lane mask read as data in a half-wave");
  3231. }
  3232. } else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) {
  3233. // (a group of 32 or fewer has no other half to exchange with)
  3234. need(b.unwrap_or(0));
  3235. return Err("a lane mask exchanged where not every lane runs");
  3236. }
  3237. xy = self.exchange_halves(at, xy.0);
  3238. }
  3239. self.ballots.insert(lo, xy);
  3240. xy
  3241. }
  3242. };
  3243. Ok(if high { y } else { x })
  3244. }
  3245. // ---- operands ----
  3246. fn operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> {
  3247. match *op {
  3248. Operand::Scalar { code: NULL, .. } => Ok(self.s.m.i32(0)),
  3249. Operand::Scalar { code, .. } => {
  3250. let v = inst.read(Reg::S(code)).ok_or("an unread operand")?;
  3251. self.i32_of(v)
  3252. }
  3253. Operand::Vector { reg, .. } => {
  3254. let v = inst.read(Reg::V(reg)).ok_or("an unread operand")?;
  3255. self.i32_of(v)
  3256. }
  3257. // src_scc: SCC as 0 or 1 (VIctory upstream 0b35b7f, as the dot
  3258. // products and packed multiply-adds below).
  3259. Operand::Const(253) => {
  3260. let bit = self.scc_in(inst)?;
  3261. Ok(self.s.m.cast(self.cur, Cast::ZExt, bit, self.s.t.i32))
  3262. }
  3263. // Nothing to wait for (see `ordered_section`).
  3264. Operand::Const(POPS_EXITING) if !self.ordered.is_empty() => Ok(self.s.m.i32(0)),
  3265. Operand::Const(c) => crate::resource::inline(c)
  3266. .map(|x| self.s.m.i32(x))
  3267. .ok_or("a special operand (vccz, execz, scc, lds_direct)"),
  3268. Operand::Literal(x) => Ok(self.s.m.i32(x)),
  3269. Operand::Attr { .. } => Err("an attribute operand"),
  3270. }
  3271. }
  3272. /// An operand read as f16 data: GFX10 puts an inline f16 constant in
  3273. /// the low half of the operand (upstream PR #637, checked there against
  3274. /// the instruction encodings; the half-and-half reading taken from PR
  3275. /// #458 gave the high half the constant too).
  3276. fn f16_operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> {
  3277. match *op {
  3278. Operand::Const(c @ 240..=248) => Ok(self.s.m.i32(inline_f16(c))),
  3279. _ => self.operand(inst, op),
  3280. }
  3281. }
  3282. fn as_float(&mut self, x: V) -> V {
  3283. self.s.m.cast(self.cur, Cast::Bitcast, x, self.s.t.f32)
  3284. }
  3285. fn as_int(&mut self, f: V) -> V {
  3286. self.s.m.cast(self.cur, Cast::Bitcast, f, self.s.t.i32)
  3287. }
  3288. /// The SDWA operand selection of source `k`: a byte or word of the
  3289. /// dword, zero- or sign-extended (none: the whole dword).
  3290. fn sdwa_src(inst: &Inst, k: usize) -> Option<(u8, bool)> {
  3291. let Fields::Valu(v) = &inst.fields else {
  3292. return None;
  3293. };
  3294. let s = v.sdwa?;
  3295. let sel = *s.src_sel.get(k)?;
  3296. let sext = s.sext >> k & 1 != 0;
  3297. (sel < 6).then_some((sel, sext))
  3298. }
  3299. /// Bits `sel` (0-3 a byte, 4-5 a word) of `x`, extended.
  3300. fn select_bits(&mut self, x: V, sel: u8, sext: bool) -> V {
  3301. let c = self.cur;
  3302. let (width, at) = if sel < 4 {
  3303. (8, 8 * sel)
  3304. } else {
  3305. (16, 16 * (sel - 4))
  3306. };
  3307. let left = self.s.m.i32(u32::from(32 - width - at));
  3308. let t = self.s.m.bin(c, Bin::Shl, x, left);
  3309. let right = self.s.m.i32(32 - u32::from(width));
  3310. let op = if sext { Bin::AShr } else { Bin::LShr };
  3311. self.s.m.bin(c, op, t, right)
  3312. }
  3313. /// A float source with its abs/neg modifiers.
  3314. fn fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  3315. let Fields::Valu(v) = &inst.fields else {
  3316. unreachable!()
  3317. };
  3318. let op = *v.src.get(k).ok_or("a missing operand")?;
  3319. let selected = Self::sdwa_src(inst, k);
  3320. let mut f = match op {
  3321. _ if selected.is_some() => {
  3322. let (sel, sext) = selected.expect("checked");
  3323. let x = self.operand(inst, &op)?;
  3324. let x = self.select_bits(x, sel, sext);
  3325. self.as_float(x)
  3326. }
  3327. _ if k == 0 && self.src0.is_some() => {
  3328. let x = self.src0.expect("checked");
  3329. self.as_float(x)
  3330. }
  3331. Operand::Vector { reg, .. } | Operand::Scalar { code: reg, .. }
  3332. if !matches!(op, Operand::Scalar { code: NULL, .. }) =>
  3333. {
  3334. let r = if matches!(op, Operand::Vector { .. }) {
  3335. Reg::V(reg)
  3336. } else {
  3337. Reg::S(reg)
  3338. };
  3339. let val = inst.read(r).ok_or("an unread operand")?;
  3340. match self.floats.get(&val) {
  3341. Some(&f) => f,
  3342. None => {
  3343. let x = self.i32_of(val)?;
  3344. self.as_float(x)
  3345. }
  3346. }
  3347. }
  3348. _ => {
  3349. let x = self.operand(inst, &op)?;
  3350. self.as_float(x)
  3351. }
  3352. };
  3353. if v.abs >> k & 1 != 0 {
  3354. f = self.unary(6, f);
  3355. }
  3356. if v.neg >> k & 1 != 0 {
  3357. let z = self.s.m.f32(0x8000_0000);
  3358. f = self.s.m.bin(self.cur, Bin::Sub, z, f);
  3359. }
  3360. Ok(f)
  3361. }
  3362. fn src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  3363. let Fields::Valu(v) = &inst.fields else {
  3364. unreachable!()
  3365. };
  3366. let op = *v.src.get(k).ok_or("a missing operand")?;
  3367. if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 {
  3368. return Err("integer operand modifiers");
  3369. }
  3370. match self.src0 {
  3371. Some(x) if k == 0 => Ok(x),
  3372. _ => {
  3373. let x = self.operand(inst, &op)?;
  3374. Ok(match Self::sdwa_src(inst, k) {
  3375. Some((sel, sext)) => self.select_bits(x, sel, sext),
  3376. None => x,
  3377. })
  3378. }
  3379. }
  3380. }
  3381. fn unary(&mut self, op: u32, f: V) -> V {
  3382. self.s.op(
  3383. self.cur,
  3384. "unary.f32",
  3385. Attr::ReadNone,
  3386. self.s.t.f32,
  3387. op,
  3388. &[f],
  3389. )
  3390. }
  3391. fn binary(&mut self, op: u32, a: V, b: V) -> V {
  3392. self.s.op(
  3393. self.cur,
  3394. "binary.f32",
  3395. Attr::ReadNone,
  3396. self.s.t.f32,
  3397. op,
  3398. &[a, b],
  3399. )
  3400. }
  3401. /// The hardware's maximum (`max`) or minimum of two floats: as DXIL's
  3402. /// FMax/FMin, but -0 orders below +0 (RDNA2 ISA, `v_max_f32`), where
  3403. /// the compare and select DXIL specifies gives either zero.
  3404. fn max_min(&mut self, max: bool, a: V, b: V) -> V {
  3405. let c = self.cur;
  3406. let r = self.binary(if max { 35 } else { 36 }, a, b);
  3407. let (ia, ib) = (self.as_int(a), self.as_int(b));
  3408. let either = self.s.m.bin(c, Bin::Or, ia, ib);
  3409. let magnitude = self.s.m.i32(0x7FFF_FFFF);
  3410. let either = self.s.m.bin(c, Bin::And, either, magnitude);
  3411. let zero = self.s.m.i32(0);
  3412. let zeros = self.s.m.cmp(c, pred::EQ, either, zero);
  3413. // Of two zeros, +0 unless both are -0 (max), -0 unless neither (min).
  3414. let op = if max { Bin::And } else { Bin::Or };
  3415. let sign = self.s.m.bin(c, op, ia, ib);
  3416. let signed = self.as_float(sign);
  3417. self.s.m.select(c, zeros, signed, r)
  3418. }
  3419. fn fmad(&mut self, a: V, b: V, c: V) -> V {
  3420. self.s.op(
  3421. self.cur,
  3422. "tertiary.f32",
  3423. Attr::ReadNone,
  3424. self.s.t.f32,
  3425. 46,
  3426. &[a, b, c],
  3427. )
  3428. }
  3429. /// `f` as an f16 in the low bits, rounded toward zero: the nearest-even
  3430. /// conversion, one step back toward zero where it rounded away (which
  3431. /// also turns an overflow to infinity into the largest finite half).
  3432. fn f16_toward_zero(&mut self, f: V) -> V {
  3433. let c = self.cur;
  3434. let i32t = self.s.t.i32;
  3435. let h = self
  3436. .s
  3437. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
  3438. let back = self
  3439. .s
  3440. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]);
  3441. let (fa, ba) = (self.unary(6, f), self.unary(6, back));
  3442. // Ordered: never for NaN.
  3443. let away = self.s.m.cmp(c, pred::OGT, ba, fa);
  3444. let one = self.s.m.i32(1);
  3445. let stepped = self.s.m.bin(c, Bin::Sub, h, one);
  3446. self.s.m.select(c, away, stepped, h)
  3447. }
  3448. /// `f` as an f16 in the low bits, rounded to nearest, ties to even, as the console's
  3449. /// 16-bit float operations round, whatever the host's own conversion does: D3D lets
  3450. /// `f32tof16` round toward zero, and the NVIDIA driver's does (measured on an RTX 4070:
  3451. /// `wave64_tests`). The conversion toward zero, or the next half away from zero where
  3452. /// that one is nearer, or as near and the first one odd. Past the largest half the next
  3453. /// one counts as 2^16, the bound IEEE rounds by, so 65520 and up become infinity.
  3454. /// (`f` is an f32 result of two halves here; rounding it again to 16 bits gives the
  3455. /// rounding of the exact result, 24 bits being more than twice 11 and two.)
  3456. fn f16_nearest(&mut self, f: V) -> V {
  3457. let c = self.cur;
  3458. let f32t = self.s.t.f32;
  3459. let lo = self.f16_toward_zero(f);
  3460. let (one, zero) = (self.s.m.i32(1), self.s.m.i32(0));
  3461. let hi = self.s.m.bin(c, Bin::Add, lo, one);
  3462. let size = |l: &mut Self, h: V| {
  3463. let w = l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  3464. l.unary(6, w)
  3465. };
  3466. let (below, above) = (size(self, lo), size(self, hi));
  3467. let (magnitude, infinity) = (self.s.m.i32(0x7FFF), self.s.m.i32(0x7C00));
  3468. let m = self.s.m.bin(c, Bin::And, hi, magnitude);
  3469. let top = self.s.m.cmp(c, pred::EQ, m, infinity);
  3470. let bound = self.s.m.f32(65536.0f32.to_bits());
  3471. let above = self.s.m.select(c, top, bound, above);
  3472. let fa = self.unary(6, f);
  3473. // (both differences are exact: the three values lie within one half's step)
  3474. let under = self.s.m.bin(c, Bin::Sub, fa, below);
  3475. let over = self.s.m.bin(c, Bin::Sub, above, fa);
  3476. // Ordered: never for NaN, which stays what the conversion made of it.
  3477. let nearer = self.s.m.cmp(c, pred::OLT, over, under);
  3478. let tie = self.s.m.cmp(c, pred::OEQ, over, under);
  3479. let odd = self.s.m.bin(c, Bin::And, lo, one);
  3480. let odd = self.s.m.cmp(c, pred::NE, odd, zero);
  3481. let tie = self.s.m.bin(c, Bin::And, tie, odd);
  3482. let up = self.s.m.bin(c, Bin::Or, nearer, tie);
  3483. self.s.m.select(c, up, hi, lo)
  3484. }
  3485. /// `(a >> off[4:0]) & ((1 << width) - 1)`, sign-extended from the field's
  3486. /// top bit when `signed`; widths from 32 on take every bit. A signed
  3487. /// field that runs past bit 31 extends from bit 31, as the hardware
  3488. /// does: the shift is arithmetic then.
  3489. fn bfe(&mut self, a: V, off: V, width: V, signed: bool) -> V {
  3490. let c = self.cur;
  3491. let (k31, k32, zero, one, ones) = (
  3492. self.s.m.i32(31),
  3493. self.s.m.i32(32),
  3494. self.s.m.i32(0),
  3495. self.s.m.i32(1),
  3496. self.s.m.i32(u32::MAX),
  3497. );
  3498. let off = self.s.m.bin(c, Bin::And, off, k31);
  3499. let shift = if signed { Bin::AShr } else { Bin::LShr };
  3500. let shifted = self.s.m.bin(c, shift, a, off);
  3501. let full = self.s.m.cmp(c, pred::IUGE, width, k32);
  3502. let w = self.s.m.bin(c, Bin::And, width, k31);
  3503. let mask = self.s.m.bin(c, Bin::Shl, one, w);
  3504. let mask = self.s.m.bin(c, Bin::Sub, mask, one);
  3505. let mask = self.s.m.select(c, full, ones, mask);
  3506. let r = self.s.m.bin(c, Bin::And, shifted, mask);
  3507. if !signed {
  3508. return r;
  3509. }
  3510. // Sign-extend a field narrower than 32 bits (none for width 0).
  3511. let left = self.s.m.bin(c, Bin::Sub, k32, w);
  3512. let left = self.s.m.bin(c, Bin::And, left, k31);
  3513. let t = self.s.m.bin(c, Bin::Shl, r, left);
  3514. let t = self.s.m.bin(c, Bin::AShr, t, left);
  3515. let is0 = self.s.m.cmp(c, pred::EQ, w, zero);
  3516. let keep = self.s.m.bin(c, Bin::Or, full, is0);
  3517. self.s.m.select(c, keep, r, t)
  3518. }
  3519. /// Whether an f32 value is NaN, tested in integer arithmetic so host
  3520. /// drivers (such as NVIDIA) do not fold `fcmp uno` away under fast-math.
  3521. fn is_nan_f32(&mut self, f: V) -> V {
  3522. let c = self.cur;
  3523. let bits = self.as_int(f);
  3524. let mask = self.s.m.i32(0x7FFF_FFFF);
  3525. let abs = self.s.m.bin(c, Bin::And, bits, mask);
  3526. let inf = self.s.m.i32(0x7F80_0000);
  3527. self.s.m.cmp(c, pred::IUGT, abs, inf)
  3528. }
  3529. /// The median of three. With a NaN among them the hardware gives the
  3530. /// minimum of the three instead (the host's minimum skips NaNs, so that
  3531. /// is the smallest number among them).
  3532. fn med3(&mut self, a: V, b: V, third: V) -> V {
  3533. let c = self.cur;
  3534. let lo = self.binary(36, a, b);
  3535. let hi = self.binary(35, a, b);
  3536. let t = self.binary(36, hi, third);
  3537. let median = self.binary(35, lo, t);
  3538. let least = self.binary(36, lo, third);
  3539. let nan_a = self.is_nan_f32(a);
  3540. let nan_b = self.is_nan_f32(b);
  3541. let nan_3 = self.is_nan_f32(third);
  3542. let nan_ab = self.s.m.bin(c, Bin::Or, nan_a, nan_b);
  3543. let nan = self.s.m.bin(c, Bin::Or, nan_ab, nan_3);
  3544. self.s.m.select(c, nan, least, median)
  3545. }
  3546. /// `a - floor(a)`, which on the hardware never reaches 1.0: where it
  3547. /// would round to it (a tiny negative `a`), the result is `below_one`,
  3548. /// the largest value under 1.0 in the operation's width. Hosts differ
  3549. /// here (some give 1.0). Comparing against a `threshold` distinct from
  3550. /// `below_one` prevents drivers (observed on NVIDIA) from folding
  3551. /// `r > k ? k : r` into `minNum` (`FMNMX`) and swallowing NaN.
  3552. fn fract(&mut self, a: V, threshold: f32, below_one: f32) -> V {
  3553. let c = self.cur;
  3554. let r = self.unary(22, a);
  3555. let limit = self.s.m.f32(threshold.to_bits());
  3556. let k = self.s.m.f32(below_one.to_bits());
  3557. let over = self.s.m.cmp(c, pred::OGE, r, limit);
  3558. self.s.m.select(c, over, k, r)
  3559. }
  3560. /// Sine, or cosine, of an angle in turns, as the hardware takes it. The
  3561. /// whole turns are taken off first (`x - round_even(x)`, exact, within
  3562. /// half a turn), so a large angle keeps its fraction; scaling to radians
  3563. /// first rounds it away. A zero passes unreduced (the sine of -0 is -0).
  3564. /// The sine of a half turn and the cosine of a quarter turn are exactly
  3565. /// +0 on the hardware, where the host's function of the rounded angle
  3566. /// gives about 1e-7. Infinities and NaN give NaN.
  3567. /// shortcut: below 2^-12 turns the hardware scales by a slightly
  3568. /// different constant than 2π (a last-place difference).
  3569. fn trig_turns(&mut self, x: V, cosine: bool) -> V {
  3570. let c = self.cur;
  3571. let zero = self.s.m.f32(0);
  3572. let whole = self.unary(26, x);
  3573. let part = self.s.m.bin(c, Bin::Sub, x, whole);
  3574. let is_zero = self.s.m.cmp(c, pred::OEQ, x, zero);
  3575. let part = self.s.m.select(c, is_zero, x, part);
  3576. let k = self.s.m.f32(TWO_PI.to_bits());
  3577. let angle = self.s.m.bin(c, Bin::Mul, part, k);
  3578. let r = self.unary(if cosine { 12 } else { 13 }, angle);
  3579. let at = if cosine { 0.25f32 } else { 0.5 };
  3580. let at = self.s.m.f32(at.to_bits());
  3581. let size = self.unary(6, part);
  3582. let exact = self.s.m.cmp(c, pred::OEQ, size, at);
  3583. self.s.m.select(c, exact, zero, r)
  3584. }
  3585. /// The high dword of a 32 × 32-bit product.
  3586. fn mul_hi(&mut self, a: V, b: V, signed: bool) -> V {
  3587. let c = self.cur;
  3588. let i64t = self.s.m.int(64);
  3589. let ext = if signed { Cast::SExt } else { Cast::ZExt };
  3590. let a = self.s.m.cast(c, ext, a, i64t);
  3591. let b = self.s.m.cast(c, ext, b, i64t);
  3592. let m = self.s.m.bin(c, Bin::Mul, a, b);
  3593. let k32 = self.s.m.int_const(i64t, 32);
  3594. let hi = self.s.m.bin(c, Bin::LShr, m, k32);
  3595. self.s.flags |= flags::INT64;
  3596. self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32)
  3597. }
  3598. /// `0 × anything = 0`, as in D3D9.
  3599. fn legacy_mul(&mut self, a: V, b: V) -> V {
  3600. let c = self.cur;
  3601. let m = self.s.m.bin(c, Bin::Mul, a, b);
  3602. let zero = self.s.m.f32(0);
  3603. let az = self.s.m.cmp(c, pred::OEQ, a, zero);
  3604. let bz = self.s.m.cmp(c, pred::OEQ, b, zero);
  3605. let z = self.s.m.bin(c, Bin::Or, az, bz);
  3606. self.s.m.select(c, z, zero, m)
  3607. }
  3608. // ---- lane booleans ----
  3609. fn boolean(&mut self, b: Bool, at: usize) -> Result<V, Why> {
  3610. if b == Bool::TRUE || b == Bool::FALSE {
  3611. return Ok(self.s.m.bool(b == Bool::TRUE));
  3612. }
  3613. if let Some(&v) = self.bools.get(&(at, b)) {
  3614. return Ok(v);
  3615. }
  3616. let (atom, lo, hi) = self.x.st.bools.node(b).expect("not a constant");
  3617. let a = self.atom(atom, at)?;
  3618. let m = &mut self.s.m;
  3619. let v = match (lo, hi) {
  3620. (Bool::FALSE, Bool::TRUE) => a,
  3621. (Bool::TRUE, Bool::FALSE) => {
  3622. let t = m.bool(true);
  3623. m.bin(at, Bin::Xor, a, t)
  3624. }
  3625. (Bool::FALSE, h) => {
  3626. let h = self.boolean(h, at)?;
  3627. self.s.m.bin(at, Bin::And, a, h)
  3628. }
  3629. (l, Bool::TRUE) => {
  3630. let l = self.boolean(l, at)?;
  3631. self.s.m.bin(at, Bin::Or, a, l)
  3632. }
  3633. (l, h) => {
  3634. let l = self.boolean(l, at)?;
  3635. let h = self.boolean(h, at)?;
  3636. self.s.m.select(at, a, h, l)
  3637. }
  3638. };
  3639. self.bools.insert((at, b), v);
  3640. Ok(v)
  3641. }
  3642. fn atom(&mut self, atom: Atom, at: usize) -> Result<V, Why> {
  3643. match atom {
  3644. Atom::Lane(v) => self.lane_bits.get(&v).copied().ok_or_else(|| {
  3645. self.lane_fail
  3646. .get(&v)
  3647. .copied()
  3648. .unwrap_or("a lane mask from a carry")
  3649. }),
  3650. Atom::Uniform(v) => match self.get(v)? {
  3651. Val::Bit(x) => Ok(x),
  3652. Val::I32(x) => {
  3653. let z = self.s.m.i32(0);
  3654. Ok(self.s.m.cmp(at, pred::NE, x, z))
  3655. }
  3656. Val::Missing(w) => Err(w),
  3657. },
  3658. Atom::Phi(id) => {
  3659. if let Some(&v) = self.mask_phis.get(&id) {
  3660. return Ok(v);
  3661. }
  3662. let &(b, i) = self
  3663. .phi_at
  3664. .get(&id)
  3665. .ok_or("a lane-mask join without a phi")?;
  3666. let blk = self.block[b].ok_or("an unreachable join")?;
  3667. let v = self.s.m.phi(blk, self.s.t.i1);
  3668. self.mask_phis.insert(id, v);
  3669. self.pending_masks.push((v, b, i));
  3670. Ok(v)
  3671. }
  3672. // shortcut: "some lane of the quad is set" is taken as true: the
  3673. // lanes it adds only feed derivatives, and exports keep their own
  3674. // masks. Wrong if such a section had a side effect.
  3675. Atom::Quad(_) => Ok(self.s.m.bool(true)),
  3676. // With console lanes, a mask held as a number is the console's:
  3677. // the lane tests its own bit.
  3678. Atom::Opaque(v) if self.console_lanes => {
  3679. let hi = match self.pair_high(v) {
  3680. Some(h) => Some(self.get(h)?),
  3681. None => None,
  3682. };
  3683. let lo = self.get(v)?;
  3684. let word = |w: Val| match w {
  3685. Val::I32(x) => Ok(x),
  3686. _ => Err("an opaque lane mask"),
  3687. };
  3688. let lo = word(lo)?;
  3689. let hi = hi.map(word).transpose()?;
  3690. Ok(self.lane_bit(at, lo, hi))
  3691. }
  3692. Atom::Constant(k) if self.console_lanes => {
  3693. let lo = self.s.m.i32(k as u32);
  3694. let hi = self.s.m.i32((k >> 32) as u32);
  3695. Ok(self.lane_bit(at, lo, Some(hi)))
  3696. }
  3697. Atom::Opaque(_) => Err("an opaque lane mask"),
  3698. Atom::Constant(_) => Err("a constant lane mask"),
  3699. }
  3700. }
  3701. /// A console wave64 program in host waves of 32: the first console thread of this host wave
  3702. /// (0, 32, 64, ...). A GPU need not give a host wave consecutive thread indices (NVIDIA's
  3703. /// 8 x 8 groups), so each wave takes the next 32 from an LDS counter instead: every thread
  3704. /// zeroes it, the group meets, each wave's first lane adds 32 and the wave takes what it
  3705. /// found. Branch-free, in the entry block, which every thread runs.
  3706. fn wave_base(&mut self) -> Option<V> {
  3707. let slot = self.halves?;
  3708. if let Some(v) = self.wave_base {
  3709. return Some(v);
  3710. }
  3711. let (e, i32t) = (self.s.entry, self.s.t.i32);
  3712. let lds = self.s.lds();
  3713. let k = self.s.m.i32(slot);
  3714. let ptr = self.s.m.element(e, lds, k);
  3715. let zero = self.s.m.i32(0);
  3716. self.s.m.store(e, ptr, zero);
  3717. self.group_sync(e);
  3718. let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  3719. let first = self.s.m.cmp(e, pred::EQ, lane, zero);
  3720. let k32 = self.s.m.i32(32);
  3721. let add = self.s.m.select(e, first, k32, zero);
  3722. let ptr = self.s.m.element(e, lds, k);
  3723. let old = self.s.m.atomic(e, Rmw::Add, ptr, add);
  3724. let base = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[old]);
  3725. self.s.flags |= flags::WAVE_OPS;
  3726. self.wave_base = Some(base);
  3727. Some(base)
  3728. }
  3729. /// The console thread index of this thread in the group: `wave_base` plus the host lane
  3730. /// (host waves of 32), else the wave's first thread index rounded down plus the lane.
  3731. fn console_thread(&mut self) -> V {
  3732. let (e, i32t) = (self.s.entry, self.s.t.i32);
  3733. let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  3734. if let Some(base) = self.wave_base() {
  3735. return self.s.m.bin(e, Bin::Add, base, lane);
  3736. }
  3737. let flat = self.s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, &[]);
  3738. let first = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[flat]);
  3739. let wave = self.s.wave_size.unwrap_or(32);
  3740. let mask = self.s.m.i32(!(wave - 1));
  3741. let base = self.s.m.bin(e, Bin::And, first, mask);
  3742. self.s.m.bin(e, Bin::Add, base, lane)
  3743. }
  3744. /// This thread's console lane (0..63): its relabelled thread index (`thread_id`), whose host
  3745. /// wave holds a 32-aligned run of console lanes. Without `exchange`: the host lane.
  3746. fn console_lane(&mut self) -> V {
  3747. if self.exchange.is_none() {
  3748. return self.lane_index();
  3749. }
  3750. if let Some(v) = self.clane {
  3751. return v;
  3752. }
  3753. let (e, i32t) = (self.s.entry, self.s.t.i32);
  3754. let f = self.console_thread();
  3755. let _ = i32t;
  3756. let k63 = self.s.m.i32(63);
  3757. let cl = self.s.m.bin(e, Bin::And, f, k63);
  3758. self.s.flags |= flags::WAVE_OPS;
  3759. self.clane = Some(cl);
  3760. cl
  3761. }
  3762. /// A group barrier with an LDS fence in `block`.
  3763. fn group_sync(&mut self, block: usize) {
  3764. let mode = self.s.m.i32(meeting_mode());
  3765. let void = self.s.t.void;
  3766. self.s.op(block, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  3767. }
  3768. /// `exchange`: each host wave gives `mine` (the same in all its lanes) for its half; both get
  3769. /// (lower half's, upper half's). A group with no upper half gets 0 for it.
  3770. fn exchange_halves(&mut self, at: usize, mine: V) -> (V, V) {
  3771. let Some((slot, small, _)) = self.exchange.as_ref().map(|(a, b, _)| (*a, *b, ())) else {
  3772. let z = self.s.m.i32(0);
  3773. return (mine, z);
  3774. };
  3775. if small {
  3776. let z = self.s.m.i32(0);
  3777. return (mine, z);
  3778. }
  3779. if self.local {
  3780. // each host wave on its own: its half holds `mine`, the other nothing
  3781. let cl = self.console_lane();
  3782. let (k32, z) = (self.s.m.i32(32), self.s.m.i32(0));
  3783. let upper = self.s.m.cmp(at, pred::IUGE, cl, k32);
  3784. let lo = self.s.m.select(at, upper, z, mine);
  3785. let hi = self.s.m.select(at, upper, mine, z);
  3786. return (lo, hi);
  3787. }
  3788. // the pair of dwords of this thread's console wave: its half's, then both
  3789. let pair = self.exchange_pair(slot);
  3790. let cl = self.console_lane();
  3791. let five = self.s.m.i32(5);
  3792. let half = self.s.m.bin(at, Bin::LShr, cl, five);
  3793. let index = self.s.m.bin(at, Bin::Add, pair, half);
  3794. let lds = self.s.lds();
  3795. let ptr = self.s.m.element(at, lds, index);
  3796. self.s.m.store(at, ptr, mine);
  3797. self.group_sync(at);
  3798. let one = self.s.m.i32(1);
  3799. let k1 = self.s.m.bin(at, Bin::Add, pair, one);
  3800. let p0 = self.s.m.element(at, lds, pair);
  3801. let p1 = self.s.m.element(at, lds, k1);
  3802. let lo = self.s.m.load(at, p0);
  3803. let hi = self.s.m.load(at, p1);
  3804. // the slots are written again only after every thread read them
  3805. self.group_sync(at);
  3806. (lo, hi)
  3807. }
  3808. /// The first of the two exchange dwords of this thread's console wave (made in the entry
  3809. /// block): a group of several console waves has a pair for each.
  3810. fn exchange_pair(&mut self, slot: u32) -> V {
  3811. if let Some(v) = self.pair {
  3812. return v;
  3813. }
  3814. let e = self.s.entry;
  3815. let thread = self.console_thread();
  3816. let six = self.s.m.i32(6);
  3817. let wave = self.s.m.bin(e, Bin::LShr, thread, six);
  3818. let one = self.s.m.i32(1);
  3819. let twice = self.s.m.bin(e, Bin::Shl, wave, one);
  3820. let base = self.s.m.i32(slot);
  3821. let v = self.s.m.bin(e, Bin::Add, base, twice);
  3822. self.pair = Some(v);
  3823. v
  3824. }
  3825. /// The console's decision of the branch closing IR block `b`, which the wave takes
  3826. /// together ([`Structured::wide`]): `when` is the lane's own bit, and the branch is taken
  3827. /// when some lane's `when` holds (`execnz`, `vccnz`, SCC of a mask operation set) or
  3828. /// when every lane's does (`execz`, `vccz`, that SCC clear), [`Structured::wave_any`].
  3829. /// Each host wave asks its lanes and the halves exchange the answers, so both go the
  3830. /// same way and can meet again inside the branch.
  3831. /// SCC of a mask operation as data ([`Structured::scc_some`]): whether some lane of the
  3832. /// console wave has its bit of the result, asked where the operation stands. The lanes
  3833. /// that are elsewhere have no bit (the result is ANDed with EXEC or is EXEC), so with
  3834. /// the console's waves the host wave's answer is the console's; two host waves of 32
  3835. /// exchange theirs, which needs every lane there.
  3836. fn scc_some(&mut self, scc: Value) -> Result<V, Why> {
  3837. let &m = self.x.st.scc_some.get(&scc).ok_or(LANE_MASK)?;
  3838. // (not for a console wave cut into host waves that do not exchange)
  3839. if !self.console_lanes || self.local || self.exchange.is_none() && self.halves.is_some() {
  3840. return Err(LANE_MASK);
  3841. }
  3842. let made = self.def_block.get(&scc).copied();
  3843. let at = match made {
  3844. None => self.s.entry,
  3845. Some(b) if b == self.cur_ir => self.cur,
  3846. Some(b) => self.tail[b].ok_or("a lane mask written after its use")?,
  3847. };
  3848. let bit = self.boolean(m, at)?;
  3849. let (i1t, i32t) = (self.s.t.i1, self.s.t.i32);
  3850. let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]);
  3851. self.s.flags |= flags::WAVE_OPS;
  3852. if !self.exchange.as_ref().is_some_and(|e| !e.1) {
  3853. return Ok(some);
  3854. }
  3855. if !made.is_none_or(|b| self.all_lanes(b)) {
  3856. need(made.unwrap_or(0));
  3857. return Err("a lane mask exchanged where not every lane runs");
  3858. }
  3859. let some = self.s.m.cast(at, Cast::ZExt, some, i32t);
  3860. let (lo, hi) = self.exchange_halves(at, some);
  3861. let both = self.s.m.bin(at, Bin::Or, lo, hi);
  3862. let z = self.s.m.i32(0);
  3863. Ok(self.s.m.cmp(at, pred::NE, both, z))
  3864. }
  3865. fn wave_wide(&mut self, b: usize, when: Bool) -> Result<V, Why> {
  3866. const WHY: Why = "a wave-wide branch where not every lane runs";
  3867. let any = self.x.st.wave_any.get(b).copied().flatten().ok_or("a wave-wide branch on a scalar condition")?;
  3868. if self.exchange.is_none() && self.halves.is_none() && self.console_lanes && self.mask_data == MaskData::Console {
  3869. // The host's waves are the console's: the wave's own answer. The lanes that are
  3870. // elsewhere have no bit set, as on the console, so "some lane" needs no one but
  3871. // the lanes here, and "every lane's bit is clear" is true of the others anyway.
  3872. let c = self.cur;
  3873. let mine = self.boolean(when, c)?;
  3874. let i1t = self.s.t.i1;
  3875. self.s.flags |= flags::WAVE_OPS;
  3876. let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) };
  3877. return Ok(self.s.op(c, name, Attr::NoUnwind, i1t, code, &[mine]));
  3878. }
  3879. if self.local || !self.exchange.as_ref().is_some_and(|e| !e.1) {
  3880. return Err(WHY);
  3881. }
  3882. if !self.all_lanes(b) {
  3883. need(b);
  3884. return Err(WHY);
  3885. }
  3886. let c = self.cur;
  3887. let mine = self.boolean(when, c)?;
  3888. // what the halves exchange is "some lane speaks against" either way (for `any`:
  3889. // some lane's `when` holds; else: some lane's does not), so a half with no lane says
  3890. // nothing
  3891. let set = if any {
  3892. mine
  3893. } else {
  3894. let t = self.s.m.bool(true);
  3895. self.s.m.bin(c, Bin::Xor, mine, t)
  3896. };
  3897. let (i1t, i32t) = (self.s.t.i1, self.s.t.i32);
  3898. let some = self.s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]);
  3899. self.s.flags |= flags::WAVE_OPS;
  3900. let some = self.s.m.cast(c, Cast::ZExt, some, i32t);
  3901. let (lo, hi) = self.exchange_halves(c, some);
  3902. let c = self.cur;
  3903. let both = self.s.m.bin(c, Bin::Or, lo, hi);
  3904. let z = self.s.m.i32(0);
  3905. Ok(self.s.m.cmp(c, if any { pred::NE } else { pred::EQ }, both, z))
  3906. }
  3907. /// Whether every lane runs IR block `b` (always true without `exchange`).
  3908. fn all_lanes(&self, b: usize) -> bool {
  3909. self.exchange.as_ref().is_none_or(|(_, _, all)| all.get(b).copied().unwrap_or(false))
  3910. }
  3911. /// This lane's bit of the mask `lo`, `hi` (wave64).
  3912. fn lane_bit(&mut self, at: usize, lo: V, hi: Option<V>) -> V {
  3913. self.s.flags |= flags::WAVE_OPS;
  3914. let lane = if self.exchange.is_some() {
  3915. self.console_lane()
  3916. } else {
  3917. self.s.op(at, "waveGetLaneIndex", Attr::ReadOnly, self.s.t.i32, 111, &[])
  3918. };
  3919. let (k31, k32, one, z) = (
  3920. self.s.m.i32(31),
  3921. self.s.m.i32(32),
  3922. self.s.m.i32(1),
  3923. self.s.m.i32(0),
  3924. );
  3925. let word = match hi {
  3926. Some(hi) => {
  3927. let low = self.s.m.cmp(at, pred::IULT, lane, k32);
  3928. self.s.m.select(at, low, lo, hi)
  3929. }
  3930. None => lo,
  3931. };
  3932. let sh = self.s.m.bin(at, Bin::And, lane, k31);
  3933. let t = self.s.m.bin(at, Bin::LShr, word, sh);
  3934. let t = self.s.m.bin(at, Bin::And, t, one);
  3935. self.s.m.cmp(at, pred::NE, t, z)
  3936. }
  3937. /// The value of the high dword of the wave64 register pair whose low
  3938. /// dword holds `lo` (none in wave32).
  3939. fn pair_high(&self, lo: Value) -> Option<Value> {
  3940. if !self.x.native.wave64 {
  3941. return None;
  3942. }
  3943. let p = self.x.p;
  3944. let pick = |reg: Reg| match reg {
  3945. Reg::S(c) => Some(Reg::S(c + 1)),
  3946. _ => None,
  3947. };
  3948. if let Some(&(reg, _)) = p.inputs.iter().find(|i| i.1 == lo) {
  3949. let h = pick(reg)?;
  3950. return p.inputs.iter().find(|i| i.0 == h).map(|i| i.1);
  3951. }
  3952. if let Some(&(b, i)) = self.phi_at.get(&lo) {
  3953. let h = pick(p.blocks[b].phis[i].reg)?;
  3954. return p.blocks[b]
  3955. .phis
  3956. .iter()
  3957. .find(|q| q.reg == h)
  3958. .map(|q| q.value);
  3959. }
  3960. let b = *self.def_block.get(&lo)?;
  3961. let inst = p.blocks[b]
  3962. .insts
  3963. .iter()
  3964. .find(|i| i.writes.iter().any(|w| w.1 == lo))?;
  3965. let &(reg, _) = inst.writes.iter().find(|w| w.1 == lo)?;
  3966. inst.write(pick(reg)?)
  3967. }
  3968. fn guard(&mut self, b: usize, i: usize) -> Result<Option<V>, Why> {
  3969. match self.x.st.guards[b][i] {
  3970. None => Ok(None),
  3971. Some(g) => Ok(Some(self.boolean(g, self.cur)?)),
  3972. }
  3973. }
  3974. // ---- results ----
  3975. fn set(&mut self, v: Option<Value>, val: Val) {
  3976. if let Some(v) = v {
  3977. self.vals.insert(v, val);
  3978. }
  3979. }
  3980. /// Writes VGPR `reg` (or the SGPR of a lane read), under `guard`.
  3981. fn write(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) {
  3982. let x = match (Self::sdwa_dst(inst), reg) {
  3983. (Some((sel, unused)), Reg::V(_)) => self.place_bits(inst, reg, x, sel, unused),
  3984. _ => x,
  3985. };
  3986. self.write_placed(inst, reg, x, guard);
  3987. }
  3988. /// [`Self::write`] of a dword already placed (SDWA applied).
  3989. fn write_placed(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) {
  3990. let Some(new) = inst.write(reg) else { return };
  3991. let x = match (guard, reg) {
  3992. (Some(g), Reg::V(_)) => {
  3993. let old = match inst.read(reg).map(|o| self.i32_of(o)) {
  3994. Some(Ok(o)) => o,
  3995. // The validator refuses reads of undef.
  3996. _ => self.s.m.i32(0),
  3997. };
  3998. let v = self.s.m.select(self.cur, g, x, old);
  3999. self.s.m.tag(v, Tag::Guard);
  4000. v
  4001. }
  4002. _ => x,
  4003. };
  4004. self.vals.insert(new, Val::I32(x));
  4005. }
  4006. /// The SDWA destination selection: a byte or word, and what the other
  4007. /// bits get (0 zeros, 1 the sign above the field, 2 the old bits).
  4008. fn sdwa_dst(inst: &Inst) -> Option<(u8, u8)> {
  4009. let Fields::Valu(v) = &inst.fields else {
  4010. return None;
  4011. };
  4012. let s = v.sdwa?;
  4013. (s.dst_sel < 6).then_some((s.dst_sel, s.dst_unused))
  4014. }
  4015. /// The low byte or word of `x` placed at `sel` in VGPR `reg`.
  4016. fn place_bits(&mut self, inst: &Inst, reg: Reg, x: V, sel: u8, unused: u8) -> V {
  4017. let c = self.cur;
  4018. let (width, at) = if sel < 4 {
  4019. (8u32, 8 * u32::from(sel))
  4020. } else {
  4021. (16, 16 * u32::from(sel - 4))
  4022. };
  4023. let left = self.s.m.i32(32 - width);
  4024. let t = self.s.m.bin(c, Bin::Shl, x, left);
  4025. let right = self.s.m.i32(32 - width - at);
  4026. if unused == 1 {
  4027. // Bits below the field shift in as zeros.
  4028. return self.s.m.bin(c, Bin::AShr, t, right);
  4029. }
  4030. let field = self.s.m.bin(c, Bin::LShr, t, right);
  4031. if unused != 2 {
  4032. return field;
  4033. }
  4034. let old = match inst.read(reg).map(|o| self.i32_of(o)) {
  4035. Some(Ok(o)) => o,
  4036. _ => self.s.m.i32(0),
  4037. };
  4038. let keep = self.s.m.i32(!((((1u64 << width) - 1) as u32) << at));
  4039. let old = self.s.m.bin(c, Bin::And, old, keep);
  4040. self.s.m.bin(c, Bin::Or, old, field)
  4041. }
  4042. fn write_f(&mut self, inst: &Inst, f: V, guard: Option<V>) -> Result<(), Why> {
  4043. let Fields::Valu(v) = &inst.fields else {
  4044. unreachable!()
  4045. };
  4046. let mut f = f;
  4047. match v.omod {
  4048. 0 => {}
  4049. k => {
  4050. let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)];
  4051. let c = self.s.m.f32(factor.to_bits());
  4052. f = self.s.m.bin(self.cur, Bin::Mul, f, c);
  4053. }
  4054. }
  4055. if v.clamp {
  4056. f = self.unary(7, f);
  4057. }
  4058. let Some(Operand::Vector { reg, .. }) = v.dst else {
  4059. return Err("a float result outside a VGPR");
  4060. };
  4061. let x = self.as_int(f);
  4062. self.write(inst, Reg::V(reg), x, guard);
  4063. if guard.is_none()
  4064. && Self::sdwa_dst(inst).is_none()
  4065. && let Some(new) = inst.write(Reg::V(reg))
  4066. {
  4067. self.floats.insert(new, f);
  4068. }
  4069. Ok(())
  4070. }
  4071. fn write_i(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> {
  4072. let Fields::Valu(v) = &inst.fields else {
  4073. unreachable!()
  4074. };
  4075. if v.clamp || v.omod != 0 {
  4076. return Err("integer output modifiers");
  4077. }
  4078. match v.dst {
  4079. Some(Operand::Vector { reg, .. }) => self.write(inst, Reg::V(reg), x, guard),
  4080. Some(Operand::Scalar { code, .. }) => self.write(inst, Reg::S(code), x, None),
  4081. _ => return Err("a result without a register"),
  4082. }
  4083. Ok(())
  4084. }
  4085. /// Starts code only the lanes where `guard` holds run (a store under a
  4086. /// lane guard): returns where it started and the join block.
  4087. fn begin_guarded(&mut self, guard: Option<V>) -> Option<(usize, usize)> {
  4088. let g = guard?;
  4089. let (then, join) = (self.s.m.new_block(), self.s.m.new_block());
  4090. self.s.m.terminate(self.cur, Term::CondBr(g, then, join));
  4091. let head = self.cur;
  4092. self.cur = then;
  4093. Some((head, join))
  4094. }
  4095. /// Ends guarded code; each (value inside, value outside) becomes a phi.
  4096. fn end_guarded(&mut self, at: Option<(usize, usize)>, values: &[(V, V)]) -> Vec<V> {
  4097. let Some((head, join)) = at else {
  4098. return values.iter().map(|v| v.0).collect();
  4099. };
  4100. let then = self.cur;
  4101. self.s.m.terminate(then, Term::Br(join));
  4102. self.cur = join;
  4103. values
  4104. .iter()
  4105. .map(|&(inside, outside)| {
  4106. let ty = self.s.m.type_of(inside);
  4107. let phi = self.s.m.phi(join, ty);
  4108. self.s.m.set_phi(phi, vec![(inside, then), (outside, head)]);
  4109. phi
  4110. })
  4111. .collect()
  4112. }
  4113. /// Code that depends on the lane layout: wave operations, and in compute
  4114. /// the console's wave size (lanes are thread ids in group order there).
  4115. /// Pixel lanes match only within a quad.
  4116. fn cross_lane(&mut self, quad: bool) -> Result<(), Why> {
  4117. if self.s.mesh.is_some() {
  4118. // shortcut: no wave size for mesh shaders in SM 6.6, so host
  4119. // lanes cannot follow the console's; emulate through group-shared
  4120. // memory if mesh programs turn out to need these.
  4121. return Err("a cross-lane operation in a mesh shader");
  4122. }
  4123. if self.s.threads.is_none() && !(quad && self.s.pixel) {
  4124. return Err("a cross-lane operation outside compute");
  4125. }
  4126. debug_assert!(self.s.threads.is_none() || self.console_lanes);
  4127. self.s.flags |= flags::WAVE_OPS;
  4128. Ok(())
  4129. }
  4130. /// Component `c` of the thread id in the group. With console lanes, the
  4131. /// thread is relabelled so that its host lane is its console lane: the
  4132. /// flat id is the wave's first lane's, rounded down to the wave size,
  4133. /// plus the lane index. (A bijection while each host wave holds a
  4134. /// wave-aligned run of flat ids, as the console's waves do.)
  4135. fn thread_id(&mut self, c: u8) -> Val {
  4136. if !self.console_lanes {
  4137. return self.compute_id("threadIdInGroup.i32", 95, c);
  4138. }
  4139. let [x, y, _] = self.s.threads.expect("compute");
  4140. let e = self.s.entry;
  4141. let i32t = self.s.t.i32;
  4142. if self.halves.is_some() {
  4143. let f = self.console_thread();
  4144. self.s.flags |= flags::WAVE_OPS;
  4145. let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y));
  4146. return Val::I32(match c {
  4147. 0 => self.s.m.bin(e, Bin::URem, f, xk),
  4148. 1 => {
  4149. let t = self.s.m.bin(e, Bin::UDiv, f, xk);
  4150. self.s.m.bin(e, Bin::URem, t, yk)
  4151. }
  4152. _ => self.s.m.bin(e, Bin::UDiv, f, xy),
  4153. });
  4154. }
  4155. let flat = self.s.op(
  4156. e,
  4157. "flattenedThreadIdInGroup.i32",
  4158. Attr::ReadNone,
  4159. i32t,
  4160. 96,
  4161. &[],
  4162. );
  4163. let first = self.s.op(
  4164. e,
  4165. "waveReadLaneFirst.i32",
  4166. Attr::NoUnwind,
  4167. i32t,
  4168. 118,
  4169. &[flat],
  4170. );
  4171. let wave = self.s.wave_size.expect("set with console lanes");
  4172. let mask = self.s.m.i32(!(wave - 1));
  4173. let base = self.s.m.bin(e, Bin::And, first, mask);
  4174. let lane = self.lane_index();
  4175. let f = self.s.m.bin(e, Bin::Add, base, lane);
  4176. self.s.flags |= flags::WAVE_OPS;
  4177. let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y));
  4178. Val::I32(match c {
  4179. 0 => self.s.m.bin(e, Bin::URem, f, xk),
  4180. 1 => {
  4181. let t = self.s.m.bin(e, Bin::UDiv, f, xk);
  4182. self.s.m.bin(e, Bin::URem, t, yk)
  4183. }
  4184. _ => self.s.m.bin(e, Bin::UDiv, f, xy),
  4185. })
  4186. }
  4187. /// Mesh: the counts and the primitives no lane exports. The console's
  4188. /// counts come from one lane's allocation request, which DXIL cannot
  4189. /// express (one call, dominating every output write).
  4190. // shortcut: the counts are the declared maxima and each lane first culls
  4191. // its primitive (all indices 0, zero area), so primitives past the
  4192. // program's count are culled and vertices past it unused; this costs
  4193. // the host the unused vertex and primitive slots. Pass the program's own
  4194. // counts if that shows in frame time.
  4195. fn mesh_prologue(&mut self, mut mesh: super::shader::Mesh) -> Result<(), Why> {
  4196. let threads = self.s.threads.expect("mesh")[0];
  4197. if mesh.topology != 2 {
  4198. return Err("a mesh shader not drawing triangles");
  4199. }
  4200. if threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256 {
  4201. return Err("a mesh shader beyond the host's limits");
  4202. }
  4203. // D3D12 caps the outputs of the declared maxima at 32 KiB. Lane n
  4204. // writes only vertex n and primitive n, so maxima past the lanes are
  4205. // never reached: they come down to the lane count when the outputs
  4206. // do not fit.
  4207. use super::container::{MESH_OUTPUT_LIMIT, mesh_output_bytes};
  4208. let (outputs, prims) = (&self.s.outputs, &self.s.prims);
  4209. let fits = |m: super::shader::Mesh| {
  4210. mesh_output_bytes(outputs, prims, m.max_vertices, m.max_primitives) <= MESH_OUTPUT_LIMIT
  4211. };
  4212. if !fits(mesh) {
  4213. mesh.max_vertices = mesh.max_vertices.min(threads);
  4214. mesh.max_primitives = mesh.max_primitives.min(threads);
  4215. // shortcut: outputs past the cap even at the lane count are
  4216. // still emitted with the lower maxima (drivers take them);
  4217. // refuse them here if one hangs.
  4218. // Experiment (`VICTORY_MESH_OUTPUT_STRICT=1`): they are refused.
  4219. if !fits(mesh) && std::env::var_os("VICTORY_MESH_OUTPUT_STRICT").is_some() {
  4220. return Err("a mesh shader whose outputs pass the host's 32 KiB");
  4221. }
  4222. self.s.mesh = Some(mesh);
  4223. }
  4224. let e = self.s.entry;
  4225. let void = self.s.t.void;
  4226. let (v, p) = (
  4227. self.s.m.i32(mesh.max_vertices),
  4228. self.s.m.i32(mesh.max_primitives),
  4229. );
  4230. self.s
  4231. .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]);
  4232. let flat = self.mesh_thread();
  4233. let z = self.s.m.i32(0);
  4234. // Every primitive of the declared count starts culled, also those
  4235. // past the lanes (a count of 256 with 128 lanes): lane n culls
  4236. // primitives n, n + lanes, ... The host draws all it was promised,
  4237. // and one never written has whatever indices its memory held: long
  4238. // triangles over the whole target, each pixel of them shaded.
  4239. let passes = mesh.max_primitives.div_ceil(threads.max(1));
  4240. for pass in 0..passes {
  4241. let index = if pass == 0 {
  4242. flat
  4243. } else {
  4244. let past = self.s.m.i32(pass * threads);
  4245. self.s.m.bin(self.cur, Bin::Add, flat, past)
  4246. };
  4247. let guard = ((pass + 1) * threads > mesh.max_primitives)
  4248. .then(|| self.s.m.cmp(self.cur, pred::IULT, index, p));
  4249. let at = self.begin_guarded(guard);
  4250. self.s.op(
  4251. self.cur,
  4252. "emitIndices",
  4253. Attr::NoUnwind,
  4254. void,
  4255. 169,
  4256. &[index, z, z, z],
  4257. );
  4258. self.end_guarded(at, &[]);
  4259. }
  4260. Ok(())
  4261. }
  4262. /// Mesh: the thread's index in the group, which is its vertex and
  4263. /// primitive index.
  4264. fn mesh_thread(&mut self) -> V {
  4265. if let Some(f) = self.flat {
  4266. return f;
  4267. }
  4268. let e = self.s.entry;
  4269. let f = self.s.op(
  4270. e,
  4271. "flattenedThreadIdInGroup.i32",
  4272. Attr::ReadNone,
  4273. self.s.t.i32,
  4274. 96,
  4275. &[],
  4276. );
  4277. self.flat = Some(f);
  4278. f
  4279. }
  4280. /// The console wave size.
  4281. fn wave(&self) -> u32 {
  4282. if self.x.native.wave64 { 64 } else { 32 }
  4283. }
  4284. fn lane_index(&mut self) -> V {
  4285. if self.s.mesh.is_some() {
  4286. // The console's lane: mesh code reads no other lanes, so host
  4287. // waves need not match the console's.
  4288. let f = self.mesh_thread();
  4289. let m = self.s.m.i32(self.wave() - 1);
  4290. return self.s.m.bin(self.s.entry, Bin::And, f, m);
  4291. }
  4292. self.s.op(
  4293. self.cur,
  4294. "waveGetLaneIndex",
  4295. Attr::ReadOnly,
  4296. self.s.t.i32,
  4297. 111,
  4298. &[],
  4299. )
  4300. }
  4301. /// `x` of lane `src` (in this lane's quad) through quad reads, whose
  4302. /// lane must be a constant.
  4303. fn quad_pick(&mut self, x: V, src: V) -> V {
  4304. self.s.flags |= flags::WAVE_OPS;
  4305. let c = self.cur;
  4306. let three = self.s.m.i32(3);
  4307. let q = self.s.m.bin(c, Bin::And, src, three);
  4308. let mut r = x;
  4309. for n in 0..4 {
  4310. let kn = self.s.m.i32(n);
  4311. let read = self.s.op(
  4312. c,
  4313. "quadReadLaneAt.i32",
  4314. Attr::NoUnwind,
  4315. self.s.t.i32,
  4316. 122,
  4317. &[x, kn],
  4318. );
  4319. let is = self.s.m.cmp(c, pred::EQ, q, kn);
  4320. r = self.s.m.select(c, is, read, r);
  4321. }
  4322. r
  4323. }
  4324. /// `x` in the first lane of this host wave where `guard` holds, and whether it has such a
  4325. /// lane: the console reads the first lane of EXEC, and a lane that got here with EXEC clear
  4326. /// (a guard, not a branch) is not one. With none, `x` of the wave's first lane here.
  4327. ///
  4328. /// A helper lane of a pixel shader takes its own value: the console's whole-quad mode has
  4329. /// helper lanes in EXEC, so a waterfall loop serves them too, and the host's wave operations
  4330. /// leave them out. Once only helper lanes are left in such a loop none of them ever matched:
  4331. /// they ran to the iteration limit, and left with no sample for their quad's derivatives,
  4332. /// along every triangle's edges (upstream #908, the fix of #1733 for this tree's form).
  4333. fn first_lane(&mut self, x: V, guard: Option<V>) -> (V, V) {
  4334. let (first, any) = self.first_live_lane(x, guard);
  4335. if !self.s.pixel || !super::helper_own() {
  4336. return (first, any);
  4337. }
  4338. let helper = self.helper_lane();
  4339. let c = self.cur;
  4340. let yes = self.s.m.bool(true);
  4341. (self.s.m.select(c, helper, x, first), self.s.m.select(c, helper, yes, any))
  4342. }
  4343. /// Whether this lane of a pixel shader is a helper lane.
  4344. fn helper_lane(&mut self) -> V {
  4345. let i1t = self.s.t.i1;
  4346. self.s.op(self.cur, "isHelperLane.i1", Attr::ReadOnly, i1t, 221, &[])
  4347. }
  4348. fn first_live_lane(&mut self, x: V, guard: Option<V>) -> (V, V) {
  4349. let c = self.cur;
  4350. let i32t = self.s.t.i32;
  4351. self.s.flags |= flags::WAVE_OPS;
  4352. let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[x]);
  4353. let Some(g) = guard else {
  4354. return (first, self.s.m.bool(true));
  4355. };
  4356. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  4357. let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[g]);
  4358. let (lo, hi) = (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1));
  4359. let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32));
  4360. // FirstbitLo (dx.op 32): the lowest set bit
  4361. let flo = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[lo]);
  4362. let fhi = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[hi]);
  4363. let fhi = self.s.m.bin(c, Bin::Add, fhi, k32);
  4364. let in_lo = self.s.m.cmp(c, pred::NE, lo, z);
  4365. let in_hi = self.s.m.cmp(c, pred::NE, hi, z);
  4366. let any = self.s.m.bin(c, Bin::Or, in_lo, in_hi);
  4367. let lane = self.s.m.select(c, in_lo, flo, fhi);
  4368. // no lane in EXEC: read this lane (one that is here); the read is not used
  4369. let me = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
  4370. let lane = self.s.m.select(c, any, lane, me);
  4371. let at = self.read_lane(x, lane);
  4372. (self.s.m.select(c, any, at, first), any)
  4373. }
  4374. fn read_lane(&mut self, x: V, lane: V) -> V {
  4375. self.s.op(
  4376. self.cur,
  4377. "waveReadLaneAt.i32",
  4378. Attr::NoUnwind,
  4379. self.s.t.i32,
  4380. 117,
  4381. &[x, lane],
  4382. )
  4383. }
  4384. /// The float value of a register value.
  4385. fn float_of(&mut self, v: Value) -> Result<V, Why> {
  4386. if let Some(&f) = self.floats.get(&v) {
  4387. return Ok(f);
  4388. }
  4389. let x = self.i32_of(v)?;
  4390. Ok(self.as_float(x))
  4391. }
  4392. /// The values of VGPRs `reg..reg + n` as `inst` reads them.
  4393. fn vgprs(&mut self, inst: &Inst, op: &Operand, n: u8) -> Result<Vec<V>, Why> {
  4394. let Operand::Vector { reg, .. } = *op else {
  4395. return Err("a vector operand");
  4396. };
  4397. (0..n)
  4398. .map(|k| {
  4399. let v = inst.read(Reg::V(reg + k)).ok_or("an unread operand")?;
  4400. self.i32_of(v)
  4401. })
  4402. .collect()
  4403. }
  4404. /// LDS (thread-group shared memory) and `ds_swizzle`.
  4405. fn ds(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  4406. let Fields::Ds {
  4407. dst,
  4408. addr,
  4409. data,
  4410. offset0,
  4411. offset1,
  4412. gds,
  4413. } = &inst.fields
  4414. else {
  4415. unreachable!()
  4416. };
  4417. if *gds {
  4418. return Err("GDS");
  4419. }
  4420. let name = inst.name();
  4421. let guard = self.guard(b, i)?;
  4422. let c = self.cur;
  4423. let offset = u32::from(*offset0) | u32::from(*offset1) << 8;
  4424. let dst_reg = match dst {
  4425. Some(Operand::Vector { reg, .. }) => Some(*reg),
  4426. _ => None,
  4427. };
  4428. if name == "ds_swizzle_b32" {
  4429. // Bit 15 set: each lane of a quad picks a lane of it; else lanes
  4430. // of each group of 32 combine their index with and/or/xor masks.
  4431. let quad = offset & 0x8000 != 0
  4432. || offset & 0x1C == 0x1C && offset & 0x380 == 0 && offset >> 10 & 0x1F < 4;
  4433. // Mesh: host quads are threads 4n..4n+3 of a 1D group, as the
  4434. // console's, so quad-local swizzles read through quad operations.
  4435. let mesh_quad = self.s.mesh.is_some() && quad;
  4436. if !mesh_quad {
  4437. self.cross_lane(quad)?;
  4438. }
  4439. // The source sits in the address field.
  4440. let x = self.vgprs(inst, addr.as_ref().ok_or("a swizzle source")?, 1)?[0];
  4441. let lane = self.lane_index();
  4442. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  4443. let src = if offset & 0x8000 != 0 {
  4444. let (three, one) = (k(self, 3), k(self, 1));
  4445. let sel = self.s.m.bin(c, Bin::And, lane, three);
  4446. let sh = self.s.m.bin(c, Bin::Shl, sel, one);
  4447. let pattern = k(self, offset & 0xFF);
  4448. let pick = self.s.m.bin(c, Bin::LShr, pattern, sh);
  4449. let pick = self.s.m.bin(c, Bin::And, pick, three);
  4450. let not3 = k(self, !3);
  4451. let base = self.s.m.bin(c, Bin::And, lane, not3);
  4452. self.s.m.bin(c, Bin::Or, base, pick)
  4453. } else {
  4454. let and = k(self, offset & 0x1F | !0x1F);
  4455. let or = k(self, offset >> 5 & 0x1F);
  4456. let xor = k(self, offset >> 10 & 0x1F);
  4457. let t = self.s.m.bin(c, Bin::And, lane, and);
  4458. let t = self.s.m.bin(c, Bin::Or, t, or);
  4459. self.s.m.bin(c, Bin::Xor, t, xor)
  4460. };
  4461. let r = if mesh_quad {
  4462. self.quad_pick(x, src)
  4463. } else {
  4464. self.read_lane(x, src)
  4465. };
  4466. let reg = dst_reg.ok_or("a swizzle result")?;
  4467. self.write(inst, Reg::V(reg), r, guard);
  4468. return Ok(());
  4469. }
  4470. if name == "ds_bpermute_b32" {
  4471. // Backward permute: no LDS is touched. Each lane takes the data
  4472. // register of the lane its address names, (address + offset) / 4
  4473. // within the wave; a source lane outside EXEC gives 0. (
  4474. // the title's checkerboard shadow-mask generators read their
  4475. // neighbours' samples with it; without them every shadowed light
  4476. // was multiplied by an empty mask.)
  4477. // shortcut: a source lane that is not at this instruction on the
  4478. // host (it left through a branch, not a guard) is read as the
  4479. // host gives it; the console reads 0.
  4480. self.cross_lane(false)?;
  4481. if self.exchange.as_ref().is_some_and(|e| !e.1) {
  4482. // a console wave of 64 run as two host waves: the lane named
  4483. // may be in the other one
  4484. return Err("a lane permute across two host waves");
  4485. }
  4486. let at = self.vgprs(inst, addr.as_ref().ok_or("a permute address")?, 1)?[0];
  4487. let x = self.vgprs(inst, data.first().ok_or("a permute source")?, 1)?[0];
  4488. let o = self.s.m.i32(offset);
  4489. let at = self.s.m.bin(c, Bin::Add, at, o);
  4490. let two = self.s.m.i32(2);
  4491. let src = self.s.m.bin(c, Bin::LShr, at, two);
  4492. let last = self.s.m.i32(self.wave() - 1);
  4493. let src = self.s.m.bin(c, Bin::And, src, last);
  4494. let x = match guard {
  4495. Some(g) => {
  4496. let z = self.s.m.i32(0);
  4497. self.s.m.select(c, g, x, z)
  4498. }
  4499. None => x,
  4500. };
  4501. let r = self.read_lane(x, src);
  4502. let reg = dst_reg.ok_or("a permute result")?;
  4503. self.write(inst, Reg::V(reg), r, guard);
  4504. return Ok(());
  4505. }
  4506. if self.s.lds_dwords == 0 {
  4507. return Err("LDS the program does not allocate");
  4508. }
  4509. let a = self.vgprs(inst, addr.as_ref().ok_or("an LDS address")?, 1)?[0];
  4510. // shortcut: LDS addresses are taken as dword-aligned and in bounds
  4511. // (out-of-bounds console accesses read 0 and drop writes).
  4512. let dword = |l: &mut Self, bytes: u32| -> V {
  4513. let c = l.cur;
  4514. let o = l.s.m.i32(bytes);
  4515. let at = l.s.m.bin(c, Bin::Add, a, o);
  4516. let two = l.s.m.i32(2);
  4517. let index = l.s.m.bin(c, Bin::LShr, at, two);
  4518. let lds = l.s.lds();
  4519. l.s.m.element(c, lds, index)
  4520. };
  4521. let width = |n: &str| match n.rsplit('_').next() {
  4522. Some("b64") => 2,
  4523. Some("b96") => 3,
  4524. Some("b128") => 4,
  4525. _ => 1,
  4526. };
  4527. // (byte offset, dwords) per element; read2/write2 scale their two
  4528. // offsets by the element size (×64 for st64).
  4529. let pair = |n: &str| -> Vec<(u32, u32)> {
  4530. let w = width(n);
  4531. let scale = 4 * w * if n.contains("st64") { 64 } else { 1 };
  4532. vec![
  4533. (u32::from(*offset0) * scale, w),
  4534. (u32::from(*offset1) * scale, w),
  4535. ]
  4536. };
  4537. // Bytes and halves: the dword holding them, and their bit position
  4538. // in it (naturally aligned, so they never straddle dwords).
  4539. // `_d16` reads fill a register's low half (`_d16_hi` its high half)
  4540. // and keep the other; `_d16_hi` writes take the data's high half.
  4541. let base = name.trim_end_matches("_hi").trim_end_matches("_d16");
  4542. let sub = match base {
  4543. "ds_read_u8" | "ds_read_i8" | "ds_write_b8" => Some(8u32),
  4544. "ds_read_u16" | "ds_read_i16" | "ds_write_b16" => Some(16),
  4545. _ => None,
  4546. };
  4547. let sub = sub.filter(|_| {
  4548. base == name
  4549. || name.ends_with("_d16") && base.starts_with("ds_read")
  4550. || name.ends_with("_d16_hi")
  4551. });
  4552. if let Some(bits) = sub {
  4553. let p = dword(self, offset);
  4554. let o = self.s.m.i32(offset);
  4555. let at = self.s.m.bin(c, Bin::Add, a, o);
  4556. let three = self.s.m.i32(3);
  4557. let byte = self.s.m.bin(c, Bin::And, at, three);
  4558. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  4559. let mask = self.s.m.i32((1u32 << bits) - 1);
  4560. if name.starts_with("ds_read") {
  4561. let reg = dst_reg.ok_or("an LDS read result")?;
  4562. let w = self.s.m.load(c, p);
  4563. let x = self.s.m.bin(c, Bin::LShr, w, sh);
  4564. let x = if base.contains("_i") {
  4565. let k = self.s.m.i32(32 - bits);
  4566. let x = self.s.m.bin(c, Bin::Shl, x, k);
  4567. self.s.m.bin(c, Bin::AShr, x, k)
  4568. } else {
  4569. self.s.m.bin(c, Bin::And, x, mask)
  4570. };
  4571. let x = if base == name {
  4572. x
  4573. } else {
  4574. let old = match inst.read(Reg::V(reg)) {
  4575. Some(v) => self.i32_of(v)?,
  4576. None => self.s.m.i32(0),
  4577. };
  4578. let half = self.s.m.i32(0xFFFF);
  4579. let x = self.s.m.bin(c, Bin::And, x, half);
  4580. let (x, keep) = if name.ends_with("_hi") {
  4581. let k16 = self.s.m.i32(16);
  4582. (self.s.m.bin(c, Bin::Shl, x, k16), half)
  4583. } else {
  4584. (x, self.s.m.i32(0xFFFF_0000))
  4585. };
  4586. let old = self.s.m.bin(c, Bin::And, old, keep);
  4587. self.s.m.bin(c, Bin::Or, old, x)
  4588. };
  4589. self.write(inst, Reg::V(reg), x, guard);
  4590. } else {
  4591. // Clear, then set: two atomics, so lanes writing other
  4592. // bytes of the dword keep theirs.
  4593. let mut x = self.vgprs(inst, data.first().ok_or("an LDS write")?, 1)?[0];
  4594. if name != base {
  4595. // The data's high half.
  4596. let k16 = self.s.m.i32(16);
  4597. x = self.s.m.bin(c, Bin::LShr, x, k16);
  4598. }
  4599. let x = self.s.m.bin(c, Bin::And, x, mask);
  4600. let x = self.s.m.bin(c, Bin::Shl, x, sh);
  4601. let m = self.s.m.bin(c, Bin::Shl, mask, sh);
  4602. let ones = self.s.m.i32(u32::MAX);
  4603. let keep = self.s.m.bin(c, Bin::Xor, m, ones);
  4604. use super::bitcode::Rmw;
  4605. let at = self.begin_guarded(guard);
  4606. self.s.m.atomic(self.cur, Rmw::And, p, keep);
  4607. self.s.m.atomic(self.cur, Rmw::Or, p, x);
  4608. self.end_guarded(at, &[]);
  4609. }
  4610. return Ok(());
  4611. }
  4612. if let Some(rest) = name.strip_prefix("ds_read") {
  4613. let elements = if rest.starts_with('2') {
  4614. pair(name)
  4615. } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") {
  4616. vec![(offset, width(name))]
  4617. } else {
  4618. return Err("an LDS read of bytes or halves");
  4619. };
  4620. let reg = dst_reg.ok_or("an LDS read result")?;
  4621. let mut n = 0;
  4622. for (off, w) in elements {
  4623. for k in 0..w {
  4624. let p = dword(self, off + 4 * k);
  4625. let x = self.s.m.load(self.cur, p);
  4626. self.write(inst, Reg::V(reg + n), x, guard);
  4627. n += 1;
  4628. }
  4629. }
  4630. return Ok(());
  4631. }
  4632. if let Some(rest) = name.strip_prefix("ds_write") {
  4633. let elements = if rest.starts_with('2') {
  4634. pair(name)
  4635. } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") {
  4636. vec![(offset, width(name))]
  4637. } else {
  4638. return Err("an LDS write of bytes or halves");
  4639. };
  4640. let mut stores = Vec::new();
  4641. for (e, (off, w)) in elements.into_iter().enumerate() {
  4642. let vals = self.vgprs(inst, data.get(e).ok_or("an LDS write")?, w as u8)?;
  4643. for (k, x) in vals.into_iter().enumerate() {
  4644. stores.push((off + 4 * k as u32, x));
  4645. }
  4646. }
  4647. let at = self.begin_guarded(guard);
  4648. for (off, x) in stores {
  4649. let p = dword(self, off);
  4650. self.s.m.store(self.cur, p, x);
  4651. }
  4652. self.end_guarded(at, &[]);
  4653. return Ok(());
  4654. }
  4655. // Atomics: the old value returns with `_rtn`.
  4656. let op = name
  4657. .strip_prefix("ds_")
  4658. .map(|n| n.replace("_rtn", ""))
  4659. .ok_or("an LDS operation")?;
  4660. use super::bitcode::Rmw;
  4661. let rmw = match op.as_str() {
  4662. "add_u32" => Some(Rmw::Add),
  4663. "sub_u32" => Some(Rmw::Sub),
  4664. "and_b32" => Some(Rmw::And),
  4665. "or_b32" => Some(Rmw::Or),
  4666. "xor_b32" => Some(Rmw::Xor),
  4667. "min_i32" => Some(Rmw::Min),
  4668. "max_i32" => Some(Rmw::Max),
  4669. "min_u32" => Some(Rmw::UMin),
  4670. "max_u32" => Some(Rmw::UMax),
  4671. "wrxchg_b32" => Some(Rmw::Xchg),
  4672. "cmpst_b32" | "max_f32" | "min_f32" => None,
  4673. _ => return Err("an LDS operation"),
  4674. };
  4675. let v0 = self.vgprs(inst, data.first().ok_or("an LDS atomic")?, 1)?[0];
  4676. let v1 = match data.get(1) {
  4677. Some(d) => Some(self.vgprs(inst, d, 1)?[0]),
  4678. None => None,
  4679. };
  4680. let old_reg = dst_reg.and_then(|r| inst.read(Reg::V(r)).map(|v| (r, v)));
  4681. let outside = match old_reg {
  4682. Some((_, v)) => self.i32_of(v).unwrap_or(self.s.m.i32(0)),
  4683. None => self.s.m.i32(0),
  4684. };
  4685. let p = dword(self, offset);
  4686. if let Some(max) = match op.as_str() {
  4687. "max_f32" => Some(true),
  4688. "min_f32" => Some(false),
  4689. _ => None,
  4690. } {
  4691. let at = self.begin_guarded(guard);
  4692. let r = self.lds_float_min_max(p, v0, max);
  4693. let r = self.end_guarded(at, &[(r, outside)])[0];
  4694. if let Some(reg) = dst_reg {
  4695. self.write(inst, Reg::V(reg), r, None);
  4696. }
  4697. return Ok(());
  4698. }
  4699. let at = self.begin_guarded(guard);
  4700. let r = match rmw {
  4701. Some(op) => self.s.m.atomic(self.cur, op, p, v0),
  4702. // Compare with data0, store data1.
  4703. None => self
  4704. .s
  4705. .m
  4706. .cmpxchg(self.cur, p, v0, v1.ok_or("an LDS compare")?),
  4707. };
  4708. let r = self.end_guarded(at, &[(r, outside)])[0];
  4709. if let Some(reg) = dst_reg {
  4710. self.write(inst, Reg::V(reg), r, None);
  4711. }
  4712. Ok(())
  4713. }
  4714. /// `ds_max_f32` (`max`) or `ds_min_f32` on the LDS dword at `p` with
  4715. /// the float bits `data`; the old bits return.
  4716. ///
  4717. /// DXIL has no float atomics on group-shared memory, so this is a
  4718. /// compare-exchange loop around [`Lower::lds_float_pick`], which gives
  4719. /// what RDNA2 writes (measured on gfx1036, reported on the pull
  4720. /// request): an sNaN, data first, then memory, is written quieted;
  4721. /// otherwise a NaN loses to a number (two quiet NaNs give the data);
  4722. /// numbers compare as floats with -0 below +0.
  4723. // shortcut: f32 denormals compare as kept; with the console's MODE
  4724. // flushing them they would order as ±0 first (MODE is not modelled).
  4725. fn lds_float_min_max(&mut self, p: V, data: V, max: bool) -> V {
  4726. let pre = self.cur;
  4727. let init = self.s.m.load(pre, p);
  4728. let (lp, exit) = (self.s.m.new_block(), self.s.m.new_block());
  4729. self.s.m.terminate(pre, Term::Br(lp));
  4730. let i32t = self.s.t.i32;
  4731. let old = self.s.m.phi(lp, i32t);
  4732. self.cur = lp;
  4733. let new = self.lds_float_pick(old, data, max);
  4734. let prev = self.s.m.cmpxchg(lp, p, old, new);
  4735. let done = self.s.m.cmp(lp, pred::EQ, prev, old);
  4736. self.s.m.set_phi(old, vec![(init, pre), (prev, lp)]);
  4737. self.s.m.terminate(lp, Term::CondBr(done, exit, lp));
  4738. self.cur = exit;
  4739. old
  4740. }
  4741. /// What `ds_max_f32` (`max`) or `ds_min_f32` writes over the dword
  4742. /// `mem` with `data` (float bits; see [`Lower::lds_float_min_max`]).
  4743. fn lds_float_pick(&mut self, mem: V, data: V, max: bool) -> V {
  4744. let c = self.cur;
  4745. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  4746. let (abs_mask, inf, quiet, zero) = (
  4747. k(self, 0x7FFF_FFFF),
  4748. k(self, 0x7F80_0000),
  4749. k(self, 0x40_0000),
  4750. k(self, 0),
  4751. );
  4752. let nan = |l: &mut Self, x: V| {
  4753. let m = l.s.m.bin(c, Bin::And, x, abs_mask);
  4754. l.s.m.cmp(c, pred::IUGT, m, inf)
  4755. };
  4756. let snan = |l: &mut Self, x: V| {
  4757. let n = nan(l, x);
  4758. let q = l.s.m.bin(c, Bin::And, x, quiet);
  4759. let sig = l.s.m.cmp(c, pred::EQ, q, zero);
  4760. l.s.m.bin(c, Bin::And, n, sig)
  4761. };
  4762. // A total order of the numbers as signed integers, -0 below +0:
  4763. // negative floats' magnitude bits reversed.
  4764. let key = |l: &mut Self, x: V| {
  4765. let k31 = l.s.m.i32(31);
  4766. let sign = l.s.m.bin(c, Bin::AShr, x, k31);
  4767. let flip = l.s.m.bin(c, Bin::And, sign, abs_mask);
  4768. l.s.m.bin(c, Bin::Xor, x, flip)
  4769. };
  4770. let (dk, mk) = (key(self, data), key(self, mem));
  4771. let take = self
  4772. .s
  4773. .m
  4774. .cmp(c, if max { pred::SGT } else { pred::SLT }, dk, mk);
  4775. let r = self.s.m.select(c, take, data, mem);
  4776. let (dn, mn) = (nan(self, data), nan(self, mem));
  4777. // One NaN: the number; two quiet NaNs: the data.
  4778. let r = self.s.m.select(c, mn, data, r);
  4779. let both = self.s.m.bin(c, Bin::And, dn, mn);
  4780. let only_data = {
  4781. let t = self.s.m.bool(true);
  4782. let not_both = self.s.m.bin(c, Bin::Xor, both, t);
  4783. self.s.m.bin(c, Bin::And, dn, not_both)
  4784. };
  4785. let r = self.s.m.select(c, only_data, mem, r);
  4786. // Signalling NaNs win, quieted: the data's first.
  4787. let qm = self.s.m.bin(c, Bin::Or, mem, quiet);
  4788. let sm = snan(self, mem);
  4789. let r = self.s.m.select(c, sm, qm, r);
  4790. let qd = self.s.m.bin(c, Bin::Or, data, quiet);
  4791. let sd = snan(self, data);
  4792. self.s.m.select(c, sd, qd, r)
  4793. }
  4794. // ---- instructions ----
  4795. // ---- instructions ----
  4796. fn inst(&mut self, b: usize, i: usize) -> Result<(), Stop> {
  4797. let inst: &'a Inst = &self.x.p.blocks[b].insts[i];
  4798. let offset = inst.machine.offset;
  4799. let name = inst.name();
  4800. self.local_ok = name.starts_with("s_bcnt1_i32_")
  4801. || name.starts_with("s_ff1_i32_")
  4802. || name.starts_with("v_mbcnt_");
  4803. self.mask_ok = match self.mask_data {
  4804. MaskData::Console => true,
  4805. MaskData::Host => {
  4806. name.starts_with("s_bcnt1_i32_")
  4807. || name.starts_with("s_ff1_i32_")
  4808. || name.starts_with("v_mbcnt_")
  4809. || matches!(
  4810. name,
  4811. "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_u64" | "s_cmp_lg_u64"
  4812. )
  4813. }
  4814. // Mesh: only "do all lanes hold the first lane's value?" (`uniform_test`), which
  4815. // each host wave answers for itself.
  4816. MaskData::None => self.uniform_test(inst),
  4817. };
  4818. let effect = matches!(inst.fields, Fields::Exp { .. })
  4819. || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
  4820. || name.contains("store")
  4821. || name.contains("atomic")
  4822. || name == "s_barrier"
  4823. || matches!(inst.fields, Fields::Ds { .. })
  4824. && !(name.starts_with("ds_read")
  4825. || name.starts_with("ds_swizzle")
  4826. || name.contains("permute"));
  4827. if self.split_lds
  4828. && matches!(inst.fields, Fields::Ds { .. })
  4829. && !(name.starts_with("ds_swizzle") || name.contains("permute"))
  4830. && self.lds_meet.as_ref().is_none_or(|(all, _)| all[b])
  4831. {
  4832. // the two host waves of a console wave meet before each LDS access: what the other
  4833. // half wrote is visible, and what it still reads is not overwritten
  4834. let mode = self.s.m.i32(meeting_mode());
  4835. let void = self.s.t.void;
  4836. self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  4837. }
  4838. let r = match &inst.fields {
  4839. Fields::Sop { .. } => self.sop(inst),
  4840. Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()),
  4841. Fields::Sopp { .. } if name == "s_barrier" => {
  4842. // Thread-group sync with a shared-memory fence, and a UAV
  4843. // fence when the program writes UAVs (the waits before an
  4844. // s_barrier make those writes visible on the console).
  4845. let mut mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 };
  4846. // Without the wait for the group (bit 0) where not every
  4847. // lane arrives, or where the switch says so.
  4848. let waits = match super::group_sync() {
  4849. 0 => false,
  4850. 1 => !self.fence_only.contains(&b),
  4851. _ => true,
  4852. };
  4853. if !waits {
  4854. mode &= !1;
  4855. }
  4856. let mode = self.s.m.i32(mode);
  4857. let void = self.s.t.void;
  4858. self.s
  4859. .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  4860. Ok(())
  4861. }
  4862. Fields::Sopp { .. } => Ok(()),
  4863. Fields::Smem { .. } => self.smem(inst, (b, i)),
  4864. Fields::Valu(_) if name.starts_with("v_interp_") => self.interp(inst, (b, i)),
  4865. Fields::Valu(_) => self.valu(inst, b, i),
  4866. Fields::Vintrp { .. } => self.interp(inst, (b, i)),
  4867. // The ray and node test. A failure is a refusal at once: an
  4868. // instruction without a side effect otherwise only stops the
  4869. // program where its results are needed, and two trace programs
  4870. // came out without their test that way.
  4871. Fields::Image { .. } if name.starts_with("image_bvh") => {
  4872. return self
  4873. .bvh(inst, b, i)
  4874. .map_err(|why| unsupported(offset, why));
  4875. }
  4876. Fields::Image { .. } => self.image(inst, b, i),
  4877. Fields::Buffer { .. } => self.buffer(inst, b, i),
  4878. Fields::Exp { .. } => self.export(b, i),
  4879. Fields::Ds { .. } => self.ds(inst, b, i),
  4880. Fields::Flat { .. } if name.starts_with("global_") => self.flat(inst, b, i),
  4881. Fields::Flat { .. } => Err("flat memory"),
  4882. };
  4883. match r {
  4884. Ok(()) => Ok(()),
  4885. Err(why) if effect => Err(unsupported(offset, why)),
  4886. Err(why) => {
  4887. for &(_, v) in &inst.writes {
  4888. self.vals.insert(v, Val::Missing(why));
  4889. }
  4890. Ok(())
  4891. }
  4892. }
  4893. }
  4894. /// The two host waves of a console wave meet (a group barrier with a shared-memory
  4895. /// fence): LDS writes before are seen by reads after.
  4896. fn lds_meeting(&mut self) {
  4897. let mode = self.s.m.i32(meeting_mode());
  4898. let void = self.s.t.void;
  4899. self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  4900. }
  4901. /// Whether `v` is a register no program reads as a number: a descriptor dword without
  4902. /// a host value ([`Self::stale`]), a lane mask's dword (outside compute, where a ballot
  4903. /// gives the mask as data), or a join of only such values. Compiled code joins numbers
  4904. /// with numbers: where one of these meets numbers at a join, the register is dead on
  4905. /// that path (a variable set in one arm of a branch, its use behind a flag kept in a
  4906. /// VGPR).
  4907. fn dead(&self, v: Value, seen: &mut Vec<Value>) -> bool {
  4908. if self.stale.contains(&v) {
  4909. return true;
  4910. }
  4911. let st = self.x.st;
  4912. if self.mask_data != MaskData::Console
  4913. && (st.masks.contains_key(&v) || st.highs.contains_key(&v))
  4914. {
  4915. return true;
  4916. }
  4917. let Some(&(b, i)) = self.phi_at.get(&v) else {
  4918. return false;
  4919. };
  4920. if seen.contains(&v) {
  4921. return true;
  4922. }
  4923. seen.push(v);
  4924. self.x.p.blocks[b].phis[i]
  4925. .args
  4926. .iter()
  4927. .all(|&a| self.dead(a, seen))
  4928. }
  4929. /// `s_bcnt1_i32_b*` of the lanes that differ from the first lane's value:
  4930. /// `v_readfirstlane_b32 s, v`, `v_cmp_eq_u32 m, s, v`, `s_xor_b* d, m, exec`. The
  4931. /// compiler tests a value for being the same in the whole wave this way, to take a
  4932. /// scalar path; both paths give each lane the same result, so the lanes of a host
  4933. /// wave may ask it of their own first lane, whatever the wave's size.
  4934. fn uniform_test(&self, inst: &Inst) -> bool {
  4935. let p = self.x.p;
  4936. let writer = |v: Value| -> Option<&'a Inst> {
  4937. let b = *self.def_block.get(&v)?;
  4938. p.blocks[b]
  4939. .insts
  4940. .iter()
  4941. .find(|i| i.writes.iter().any(|w| w.1 == v))
  4942. };
  4943. let scalar = |i: &Inst, op: &Operand| match *op {
  4944. Operand::Scalar { code, .. } if code != NULL && code != EXEC => i.read(Reg::S(code)),
  4945. _ => None,
  4946. };
  4947. if !inst.name().starts_with("s_bcnt1_i32_") {
  4948. return false;
  4949. }
  4950. let Fields::Sop { src, .. } = &inst.fields else {
  4951. return false;
  4952. };
  4953. let Some(xor) = src.first().and_then(|o| scalar(inst, o)).and_then(writer) else {
  4954. return false;
  4955. };
  4956. let Fields::Sop { src, .. } = &xor.fields else {
  4957. return false;
  4958. };
  4959. if !matches!(xor.name(), "s_xor_b64" | "s_xor_b32")
  4960. || !src
  4961. .iter()
  4962. .any(|o| matches!(o, Operand::Scalar { code: EXEC, .. }))
  4963. {
  4964. return false;
  4965. }
  4966. let Some(cmp) = src.iter().find_map(|o| scalar(xor, o)).and_then(writer) else {
  4967. return false;
  4968. };
  4969. let Fields::Valu(f) = &cmp.fields else {
  4970. return false;
  4971. };
  4972. if !matches!(cmp.name(), "v_cmp_eq_u32" | "v_cmp_eq_i32") || f.sdwa.is_some() || f.dpp.is_some() {
  4973. return false;
  4974. }
  4975. let lanes = f.src.iter().find_map(|o| match *o {
  4976. Operand::Vector { reg, .. } => cmp.read(Reg::V(reg)),
  4977. _ => None,
  4978. });
  4979. let first = f.src.iter().find_map(|o| scalar(cmp, o)).and_then(writer);
  4980. lanes.is_some()
  4981. && first.is_some_and(|fl| {
  4982. fl.name() == "v_readfirstlane_b32"
  4983. && matches!(&fl.fields, Fields::Valu(g)
  4984. if matches!(g.src.first(), Some(&Operand::Vector { reg, .. })
  4985. if fl.read(Reg::V(reg)) == lanes))
  4986. })
  4987. }
  4988. fn is_mask(&self, v: Option<Value>) -> bool {
  4989. v.is_some_and(|v| self.x.st.masks.contains_key(&v))
  4990. }
  4991. fn sop(&mut self, inst: &Inst) -> Result<(), Why> {
  4992. let Fields::Sop { dst, src, imm } = &inst.fields else {
  4993. unreachable!()
  4994. };
  4995. let name = inst.name();
  4996. let scc = inst.write(Reg::Scc);
  4997. let dst_code = match dst {
  4998. Some(Operand::Scalar { code, .. }) => Some(*code),
  4999. _ => None,
  5000. };
  5001. let lo = dst_code.and_then(|c| inst.write(Reg::S(c)));
  5002. if inst.write(Reg::S(EXEC)).is_some() || self.is_mask(lo) {
  5003. return Err(LANE_MASK);
  5004. }
  5005. if matches!(
  5006. name,
  5007. "s_setreg_imm32_b32" | "s_setreg_b32" | "s_swappc_b64" | "s_version"
  5008. ) || name.starts_with("s_waitcnt")
  5009. {
  5010. // shortcut: the float MODE register is not modelled; s_swappc_b64 is the
  5011. // vertex fetch call, whose results arrive as inputs.
  5012. return Err("a register the emitter does not model");
  5013. }
  5014. if name == "s_getpc_b64" {
  5015. // The address of the next instruction is no number the host has: tables in
  5016. // the code are read by their tracked address. As a number the counter is
  5017. // that instruction's offset in the code, so an address paths join before
  5018. // one load is the byte in the code, whichever table each path took
  5019. // (resource tracking gives such a join as the computed term, with no base).
  5020. let z = self.s.m.i32(0);
  5021. let at = self.s.m.i32(inst.machine.offset as u32 + 4);
  5022. let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1)));
  5023. self.set(lo, Val::I32(at));
  5024. self.set(hi, Val::I32(z));
  5025. return Ok(());
  5026. }
  5027. let c = self.cur;
  5028. let src32 = |l: &mut Self, k: usize| -> Result<V, Why> {
  5029. // SOPK arithmetic reads its destination as the first source.
  5030. if k == 0 && matches!(name, "s_addk_i32" | "s_mulk_i32") {
  5031. let d = dst.as_ref().ok_or("a missing operand")?;
  5032. return l.operand(inst, d);
  5033. }
  5034. let op = src.get(k).ok_or("a missing operand")?;
  5035. l.operand(inst, op)
  5036. };
  5037. let sext16 = |l: &mut Self| l.s.m.i32(i32::from(imm.unwrap_or(0) as i16) as u32);
  5038. // Dword `h` of 64-bit source `k` (inline constants sign-extend).
  5039. let half = |l: &mut Self, k: usize, h: u8| -> Result<V, Why> {
  5040. match src.get(k) {
  5041. Some(&Operand::Scalar { code, .. }) if code != NULL => {
  5042. let v = inst.read(Reg::S(code + h)).ok_or("an unread operand")?;
  5043. l.i32_of(v)
  5044. }
  5045. Some(op) if h == 0 => l.operand(inst, op),
  5046. Some(Operand::Const(k)) => {
  5047. let x = crate::resource::inline(*k).ok_or("a special operand")?;
  5048. Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 }))
  5049. }
  5050. _ => Ok(l.s.m.i32(0)),
  5051. }
  5052. };
  5053. if let Some(op) = name.strip_prefix("s_bitcmp") {
  5054. // SCC is whether bit src1 (mod 32, or mod 64 for the 64-bit form)
  5055. // of src0 is clear (bitcmp0) or set (bitcmp1).
  5056. let (bit, k31) = (src32(self, 1)?, self.s.m.i32(31));
  5057. let idx = self.s.m.bin(c, Bin::And, bit, k31);
  5058. let word = if op.ends_with("_b64") {
  5059. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5060. let k32 = self.s.m.i32(32);
  5061. let upper = self.s.m.bin(c, Bin::And, bit, k32);
  5062. let z = self.s.m.i32(0);
  5063. let upper = self.s.m.cmp(c, pred::NE, upper, z);
  5064. self.s.m.select(c, upper, b, a)
  5065. } else {
  5066. src32(self, 0)?
  5067. };
  5068. let shifted = self.s.m.bin(c, Bin::LShr, word, idx);
  5069. let one = self.s.m.i32(1);
  5070. let tested = self.s.m.bin(c, Bin::And, shifted, one);
  5071. let want = self.s.m.i32(u32::from(op.starts_with('1')));
  5072. let r = self.s.m.cmp(c, pred::EQ, tested, want);
  5073. self.set(scc, Val::Bit(r));
  5074. return Ok(());
  5075. }
  5076. if let Some(op) = name.strip_prefix("s_cmp_").filter(|o| o.ends_with("_u64")) {
  5077. // eq and lg only: both dwords.
  5078. let mut r = None;
  5079. for h in 0..2 {
  5080. let (a, b) = (half(self, 0, h)?, half(self, 1, h)?);
  5081. let e = self.s.m.cmp(c, pred::EQ, a, b);
  5082. r = Some(match r {
  5083. Some(x) => self.s.m.bin(c, Bin::And, x, e),
  5084. None => e,
  5085. });
  5086. }
  5087. let mut r = r.expect("two dwords");
  5088. if op.starts_with("lg") {
  5089. let t = self.s.m.bool(true);
  5090. r = self.s.m.bin(c, Bin::Xor, r, t);
  5091. }
  5092. self.set(scc, Val::Bit(r));
  5093. return Ok(());
  5094. }
  5095. if let Some(op) = name.strip_prefix("s_cmp_").or(name.strip_prefix("s_cmpk_")) {
  5096. let (a, b) = if name.starts_with("s_cmpk_") {
  5097. let b = if op.ends_with("_i32") {
  5098. sext16(self)
  5099. } else {
  5100. self.s.m.i32(u32::from(imm.unwrap_or(0)))
  5101. };
  5102. (src32(self, 0)?, b)
  5103. } else {
  5104. if op.ends_with("64") {
  5105. return Err("a 64-bit scalar compare");
  5106. }
  5107. (src32(self, 0)?, src32(self, 1)?)
  5108. };
  5109. let signed = op.ends_with("_i32");
  5110. let p = match &op[..2] {
  5111. "eq" => pred::EQ,
  5112. "lg" => pred::NE,
  5113. "gt" if signed => pred::SGT,
  5114. "ge" if signed => pred::SGE,
  5115. "lt" if signed => pred::SLT,
  5116. "le" if signed => pred::SLE,
  5117. "gt" => pred::IUGT,
  5118. "ge" => pred::IUGE,
  5119. "lt" => pred::IULT,
  5120. "le" => pred::IULE,
  5121. _ => return Err("a scalar compare"),
  5122. };
  5123. let r = self.s.m.cmp(c, p, a, b);
  5124. self.set(scc, Val::Bit(r));
  5125. return Ok(());
  5126. }
  5127. let wide = name.ends_with("_b64") || name.ends_with("_u64") || name.ends_with("_i64");
  5128. if wide {
  5129. let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1)));
  5130. let nonzero = |l: &mut Self, a: V, b: V| {
  5131. let o = l.s.m.bin(c, Bin::Or, a, b);
  5132. let z = l.s.m.i32(0);
  5133. l.s.m.cmp(c, pred::NE, o, z)
  5134. };
  5135. return match name {
  5136. "s_bcnt1_i32_b64" => {
  5137. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5138. let i32t = self.s.t.i32;
  5139. let na = self
  5140. .s
  5141. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[a]);
  5142. let nb = self
  5143. .s
  5144. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[b]);
  5145. let r = self.s.m.bin(c, Bin::Add, na, nb);
  5146. self.set(lo, Val::I32(r));
  5147. let z = self.s.m.i32(0);
  5148. let s = self.s.m.cmp(c, pred::NE, r, z);
  5149. self.set(scc, Val::Bit(s));
  5150. Ok(())
  5151. }
  5152. "s_ff1_i32_b64" => {
  5153. // The lowest set bit; -1 for none (as DXIL's first bit low).
  5154. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5155. let i32t = self.s.t.i32;
  5156. let fa = self
  5157. .s
  5158. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[a]);
  5159. let fb = self
  5160. .s
  5161. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[b]);
  5162. let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32));
  5163. let fb32 = self.s.m.bin(c, Bin::Add, fb, k32);
  5164. let none = self.s.m.cmp(c, pred::EQ, b, z);
  5165. let fb = self.s.m.select(c, none, fb, fb32);
  5166. let low = self.s.m.cmp(c, pred::NE, a, z);
  5167. let r = self.s.m.select(c, low, fa, fb);
  5168. self.set(lo, Val::I32(r));
  5169. Ok(())
  5170. }
  5171. "s_and_b64" | "s_or_b64" | "s_xor_b64" | "s_andn2_b64" | "s_orn2_b64"
  5172. | "s_nand_b64" | "s_nor_b64" | "s_xnor_b64" | "s_not_b64" => {
  5173. let ones = self.s.m.i32(u32::MAX);
  5174. let mut r = Vec::new();
  5175. for h in 0..2u8 {
  5176. let a = half(self, 0, h)?;
  5177. let x = if name == "s_not_b64" {
  5178. self.s.m.bin(c, Bin::Xor, a, ones)
  5179. } else {
  5180. let mut b = half(self, 1, h)?;
  5181. if name.contains("n2") {
  5182. b = self.s.m.bin(c, Bin::Xor, b, ones);
  5183. }
  5184. let op = match &name[2..5] {
  5185. "and" | "nan" => Bin::And,
  5186. "or_" | "orn" | "nor" => Bin::Or,
  5187. _ => Bin::Xor,
  5188. };
  5189. let x = self.s.m.bin(c, op, a, b);
  5190. if matches!(name, "s_nand_b64" | "s_nor_b64" | "s_xnor_b64") {
  5191. self.s.m.bin(c, Bin::Xor, x, ones)
  5192. } else {
  5193. x
  5194. }
  5195. };
  5196. r.push(x);
  5197. }
  5198. self.set(lo, Val::I32(r[0]));
  5199. self.set(hi, Val::I32(r[1]));
  5200. let s = nonzero(self, r[0], r[1]);
  5201. self.set(scc, Val::Bit(s));
  5202. Ok(())
  5203. }
  5204. "s_lshl_b64" | "s_lshr_b64" | "s_ashr_i64" => {
  5205. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  5206. let n = src32(self, 1)?;
  5207. let i64t = self.s.m.int(64);
  5208. self.s.flags |= flags::INT64;
  5209. let a = self.s.m.cast(c, Cast::ZExt, a, i64t);
  5210. let b = self.s.m.cast(c, Cast::ZExt, b, i64t);
  5211. let k32 = self.s.m.int_const(i64t, 32);
  5212. let b = self.s.m.bin(c, Bin::Shl, b, k32);
  5213. let x = self.s.m.bin(c, Bin::Or, a, b);
  5214. let k63 = self.s.m.i32(63);
  5215. let n = self.s.m.bin(c, Bin::And, n, k63);
  5216. let n = self.s.m.cast(c, Cast::ZExt, n, i64t);
  5217. let op = match name {
  5218. "s_lshl_b64" => Bin::Shl,
  5219. "s_lshr_b64" => Bin::LShr,
  5220. _ => Bin::AShr,
  5221. };
  5222. let r = self.s.m.bin(c, op, x, n);
  5223. let rl = self.s.m.cast(c, Cast::Trunc, r, self.s.t.i32);
  5224. let rh = self.s.m.bin(c, Bin::LShr, r, k32);
  5225. let rh = self.s.m.cast(c, Cast::Trunc, rh, self.s.t.i32);
  5226. self.set(lo, Val::I32(rl));
  5227. self.set(hi, Val::I32(rh));
  5228. let s = nonzero(self, rl, rh);
  5229. self.set(scc, Val::Bit(s));
  5230. Ok(())
  5231. }
  5232. "s_mov_b64" => {
  5233. // Each half by itself: two numbers that travel as a pair (two scalars
  5234. // parked in neighbouring VGPR lanes, say) need not both have a value.
  5235. for (h, v) in [(0, lo), (1, hi)] {
  5236. let val = match half(self, 0, h) {
  5237. Ok(a) => Val::I32(a),
  5238. Err(why) => Val::Missing(why),
  5239. };
  5240. self.set(v, val);
  5241. }
  5242. Ok(())
  5243. }
  5244. "s_cselect_b64" => {
  5245. let cond = self.scc_in(inst)?;
  5246. for (h, v) in [(0, lo), (1, hi)] {
  5247. let (a, b) = (half(self, 0, h)?, half(self, 1, h)?);
  5248. let r = self.s.m.select(c, cond, a, b);
  5249. self.set(v, Val::I32(r));
  5250. }
  5251. Ok(())
  5252. }
  5253. _ => Err(name),
  5254. };
  5255. }
  5256. let m = &mut self.s.m;
  5257. let _ = m;
  5258. let (r, carry): (V, Option<V>) = match name {
  5259. "s_mov_b32" => (src32(self, 0)?, None),
  5260. "s_movk_i32" => (sext16(self), None),
  5261. "s_cselect_b32" => {
  5262. let cond = self.scc_in(inst)?;
  5263. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5264. (self.s.m.select(c, cond, a, b), None)
  5265. }
  5266. "s_brev_b32" => {
  5267. let a = src32(self, 0)?;
  5268. let r = self
  5269. .s
  5270. .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a]);
  5271. (r, None)
  5272. }
  5273. "s_not_b32" => {
  5274. let a = src32(self, 0)?;
  5275. let ones = self.s.m.i32(u32::MAX);
  5276. (self.s.m.bin(c, Bin::Xor, a, ones), None)
  5277. }
  5278. "s_add_u32" | "s_add_i32" | "s_addk_i32" => {
  5279. let a = src32(self, 0)?;
  5280. let b = if name == "s_addk_i32" {
  5281. sext16(self)
  5282. } else {
  5283. src32(self, 1)?
  5284. };
  5285. let r = self.s.m.bin(c, Bin::Add, a, b);
  5286. let carry = if name == "s_add_u32" {
  5287. Some(self.s.m.cmp(c, pred::IULT, r, a))
  5288. } else {
  5289. None
  5290. };
  5291. (r, carry)
  5292. }
  5293. "s_sub_u32" | "s_sub_i32" => {
  5294. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5295. let r = self.s.m.bin(c, Bin::Sub, a, b);
  5296. let carry = (name == "s_sub_u32").then(|| self.s.m.cmp(c, pred::IULT, a, b));
  5297. (r, carry)
  5298. }
  5299. "s_addc_u32" | "s_subb_u32" => {
  5300. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5301. let cin = self.scc_in(inst)?;
  5302. let (r, carry) = self.add_sub_carry(c, name == "s_addc_u32", a, b, Some(cin));
  5303. (r, Some(carry))
  5304. }
  5305. "s_mul_i32" | "s_mulk_i32" => {
  5306. let a = src32(self, 0)?;
  5307. let b = if name == "s_mulk_i32" {
  5308. sext16(self)
  5309. } else {
  5310. src32(self, 1)?
  5311. };
  5312. (self.s.m.bin(c, Bin::Mul, a, b), None)
  5313. }
  5314. "s_mul_hi_u32" | "s_mul_hi_i32" => {
  5315. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5316. (self.mul_hi(a, b, name.ends_with("i32")), None)
  5317. }
  5318. "s_flbit_i32_b32" | "s_flbit_i32" => {
  5319. // The first bit from the top (differing from the sign for
  5320. // the signed form), -1 for none: DXIL's first-bit-high.
  5321. let a = src32(self, 0)?;
  5322. let op = if name == "s_flbit_i32_b32" { 33 } else { 34 };
  5323. let r = self
  5324. .s
  5325. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  5326. (r, None)
  5327. }
  5328. "s_ff1_i32_b32" | "s_bcnt1_i32_b32" => {
  5329. // First set bit (-1 for zero, as DXIL's), or the bit count.
  5330. let a = src32(self, 0)?;
  5331. let op = if name == "s_ff1_i32_b32" { 32 } else { 31 };
  5332. let r = self
  5333. .s
  5334. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  5335. (r, None)
  5336. }
  5337. "s_bfe_u32" | "s_bfe_i32" => {
  5338. // src1: offset in bits 0-4, width in bits 16-22.
  5339. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5340. let (k16, k127) = (self.s.m.i32(16), self.s.m.i32(0x7F));
  5341. let w = self.s.m.bin(c, Bin::LShr, b, k16);
  5342. let w = self.s.m.bin(c, Bin::And, w, k127);
  5343. (self.bfe(a, b, w, name == "s_bfe_i32"), None)
  5344. }
  5345. "s_and_b32" | "s_or_b32" | "s_xor_b32" | "s_andn2_b32" | "s_orn2_b32"
  5346. | "s_nand_b32" | "s_nor_b32" | "s_xnor_b32" => {
  5347. let (a, mut b) = (src32(self, 0)?, src32(self, 1)?);
  5348. let ones = self.s.m.i32(u32::MAX);
  5349. if name.contains("n2") {
  5350. b = self.s.m.bin(c, Bin::Xor, b, ones);
  5351. }
  5352. let op = match &name[2..5] {
  5353. "and" | "nan" => Bin::And,
  5354. "or_" | "orn" | "nor" => Bin::Or,
  5355. _ => Bin::Xor,
  5356. };
  5357. let mut r = self.s.m.bin(c, op, a, b);
  5358. if matches!(name, "s_nand_b32" | "s_nor_b32" | "s_xnor_b32") {
  5359. r = self.s.m.bin(c, Bin::Xor, r, ones);
  5360. }
  5361. (r, None)
  5362. }
  5363. "s_lshl_b32" | "s_lshr_b32" | "s_ashr_i32" => {
  5364. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5365. let k31 = self.s.m.i32(31);
  5366. let b = self.s.m.bin(c, Bin::And, b, k31);
  5367. let op = match name {
  5368. "s_lshl_b32" => Bin::Shl,
  5369. "s_lshr_b32" => Bin::LShr,
  5370. _ => Bin::AShr,
  5371. };
  5372. (self.s.m.bin(c, op, a, b), None)
  5373. }
  5374. "s_lshl1_add_u32" | "s_lshl2_add_u32" | "s_lshl3_add_u32" | "s_lshl4_add_u32" => {
  5375. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5376. let k = self.s.m.i32(u32::from(name.as_bytes()[6] - b'0'));
  5377. let t = self.s.m.bin(c, Bin::Shl, a, k);
  5378. (self.s.m.bin(c, Bin::Add, t, b), None)
  5379. }
  5380. "s_min_u32" | "s_max_u32" | "s_min_i32" | "s_max_i32" => {
  5381. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5382. let p = match name {
  5383. "s_min_u32" => pred::IULT,
  5384. "s_max_u32" => pred::IUGT,
  5385. "s_min_i32" => pred::SLT,
  5386. _ => pred::SGT,
  5387. };
  5388. let t = self.s.m.cmp(c, p, a, b);
  5389. (self.s.m.select(c, t, a, b), None)
  5390. }
  5391. "s_abs_i32" => {
  5392. let a = src32(self, 0)?;
  5393. let z = self.s.m.i32(0);
  5394. let neg = self.s.m.cmp(c, pred::SLT, a, z);
  5395. let n = self.s.m.bin(c, Bin::Sub, z, a);
  5396. (self.s.m.select(c, neg, n, a), None)
  5397. }
  5398. "s_bitset0_b32" | "s_bitset1_b32" => {
  5399. // Sets (clears) bit src[4:0] of the destination it reads.
  5400. let old = self.operand(inst, dst.as_ref().ok_or("a missing operand")?)?;
  5401. let a = src32(self, 0)?;
  5402. let (k31, one) = (self.s.m.i32(31), self.s.m.i32(1));
  5403. let a = self.s.m.bin(c, Bin::And, a, k31);
  5404. let bit = self.s.m.bin(c, Bin::Shl, one, a);
  5405. if name == "s_bitset1_b32" {
  5406. (self.s.m.bin(c, Bin::Or, old, bit), None)
  5407. } else {
  5408. let ones = self.s.m.i32(u32::MAX);
  5409. let nb = self.s.m.bin(c, Bin::Xor, bit, ones);
  5410. (self.s.m.bin(c, Bin::And, old, nb), None)
  5411. }
  5412. }
  5413. "s_bfm_b32" => {
  5414. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  5415. let k31 = self.s.m.i32(31);
  5416. let one = self.s.m.i32(1);
  5417. let a = self.s.m.bin(c, Bin::And, a, k31);
  5418. let b = self.s.m.bin(c, Bin::And, b, k31);
  5419. let m = self.s.m.bin(c, Bin::Shl, one, a);
  5420. let m = self.s.m.bin(c, Bin::Sub, m, one);
  5421. (self.s.m.bin(c, Bin::Shl, m, b), None)
  5422. }
  5423. _ => return Err(name),
  5424. };
  5425. self.set(lo, Val::I32(r));
  5426. if let Some(scc) = scc {
  5427. let val = match carry {
  5428. Some(k) => Val::Bit(k),
  5429. None if matches!(
  5430. name,
  5431. "s_mov_b32"
  5432. | "s_movk_i32"
  5433. | "s_cselect_b32"
  5434. | "s_brev_b32"
  5435. | "s_mul_i32"
  5436. | "s_mulk_i32"
  5437. ) =>
  5438. {
  5439. return Ok(());
  5440. }
  5441. None if name.starts_with("s_add") || name.starts_with("s_sub") => {
  5442. Val::Missing("the carry of a scalar operation")
  5443. }
  5444. None => {
  5445. let z = self.s.m.i32(0);
  5446. Val::Bit(self.s.m.cmp(c, pred::NE, r, z))
  5447. }
  5448. };
  5449. self.vals.insert(scc, val);
  5450. }
  5451. Ok(())
  5452. }
  5453. /// `a + b (+ cin)` or `a - b (- cin)` with the carry (borrow) out, as the
  5454. /// scalar and vector add-with-carry instructions set it.
  5455. fn add_sub_carry(&mut self, c: usize, add: bool, a: V, b: V, cin: Option<V>) -> (V, V) {
  5456. let op = if add { Bin::Add } else { Bin::Sub };
  5457. let mut r = self.s.m.bin(c, op, a, b);
  5458. // Without a carry in: a + b wraps below a; a - b borrows when a < b.
  5459. let mut carry = if add {
  5460. self.s.m.cmp(c, pred::IULT, r, a)
  5461. } else {
  5462. self.s.m.cmp(c, pred::IULT, a, b)
  5463. };
  5464. if let Some(cin) = cin {
  5465. let one = self.s.m.cast(c, Cast::ZExt, cin, self.s.t.i32);
  5466. let t = r;
  5467. r = self.s.m.bin(c, op, t, one);
  5468. // The carry in carries on when the partial result is all ones
  5469. // (add) or zero (sub).
  5470. let edge = self.s.m.i32(if add { u32::MAX } else { 0 });
  5471. let at_edge = self.s.m.cmp(c, pred::EQ, t, edge);
  5472. let more = self.s.m.bin(c, Bin::And, cin, at_edge);
  5473. carry = self.s.m.bin(c, Bin::Or, carry, more);
  5474. }
  5475. (r, carry)
  5476. }
  5477. fn scc_in(&mut self, inst: &Inst) -> Result<V, Why> {
  5478. let v = inst.read(Reg::Scc).ok_or("an unread SCC")?;
  5479. match self.get(v) {
  5480. Ok(Val::Bit(x)) => Ok(x),
  5481. Ok(_) => Err("SCC without a value"),
  5482. // Of a mask operation whose result lies within EXEC: whether
  5483. // some lane is left.
  5484. Err(LANE_MASK) if self.within_exec(v) => self.scc_some(v),
  5485. Err(why) => Err(why),
  5486. }
  5487. }
  5488. /// Whether the mask operation that sets the SCC value `scc` gives no
  5489. /// lane outside EXEC a bit.
  5490. fn within_exec(&self, scc: Value) -> bool {
  5491. let Some(&b) = self.def_block.get(&scc) else {
  5492. return false;
  5493. };
  5494. let by = self.x.p.blocks[b].insts.iter().find(|i| i.write(Reg::Scc) == Some(scc));
  5495. by.is_some_and(|i| {
  5496. i.write(Reg::S(EXEC)).is_some()
  5497. || matches!(&i.fields, Fields::Sop { dst: Some(Operand::Scalar { code, .. }), .. }
  5498. if i.write(Reg::S(*code)).is_some_and(|lo| self.x.st.active.contains(&lo)))
  5499. })
  5500. }
  5501. fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  5502. let Fields::Smem {
  5503. data,
  5504. offset,
  5505. soffset,
  5506. ..
  5507. } = &inst.fields
  5508. else {
  5509. unreachable!()
  5510. };
  5511. let name = inst.name();
  5512. if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) {
  5513. return self.code_smem(inst, a);
  5514. }
  5515. if self.scalar.get(&site).is_some_and(|a| a.param == MEMORY) {
  5516. return self.memory_smem(inst);
  5517. }
  5518. let Some(rest) = name.strip_prefix("s_buffer_load_dword") else {
  5519. return self.descriptor_data(inst, site);
  5520. };
  5521. let count = match rest {
  5522. "" => 1,
  5523. "x2" => 2,
  5524. "x4" => 4,
  5525. "x8" => 8,
  5526. "x16" => 16,
  5527. _ => return Err("a scalar buffer load"),
  5528. };
  5529. let Some(Operand::Scalar { code, .. }) = *data else {
  5530. return Err("a scalar buffer load");
  5531. };
  5532. let src = self
  5533. .descriptors
  5534. .get(&(site, false))
  5535. .copied()
  5536. .ok_or("an untracked descriptor")?;
  5537. let kind = self.used_kind(src);
  5538. let c = self.cur;
  5539. let (base, extra) = self.built_offset(src)?;
  5540. let offset = &((*offset as u32).wrapping_add(base) as i32);
  5541. let mut addr = self.s.m.i32(*offset as u32);
  5542. if let Some(x) = extra {
  5543. addr = self.s.m.bin(c, Bin::Add, addr, x);
  5544. }
  5545. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  5546. let so = self.operand(inst, soffset)?;
  5547. addr = self.s.m.bin(c, Bin::Add, addr, so);
  5548. }
  5549. if matches!(src, Source::Built { address, .. } if address.param == CODE) {
  5550. // A descriptor built around a table in the code.
  5551. for k in 0..count {
  5552. let off = self.s.m.i32(4 * k);
  5553. let a = self.s.m.bin(c, Bin::Add, addr, off);
  5554. let x = self.code_dword(a)?;
  5555. self.write(inst, Reg::S(code + k as u8), x, None);
  5556. }
  5557. return Ok(());
  5558. }
  5559. // A buffer the program picks from the view heap by an index it
  5560. // computes (`ResourceHeap`) has no used-resource entry, and the
  5561. // heap holds a buffer view there, not a constant buffer: read as
  5562. // raw bytes, as a table's SRV is below. Read as a constant buffer
  5563. // (the host's validation: "Descriptor Type in Heap: SRV, Register
  5564. // Type: CBV", heap index 17) the loads gave nothing:
  5565. // the title's meshlet culling (BatchCullMeshlets,
  5566. // BatchCullPreSkinnedMeshlets, BatchCullBatchCSMeshlets) reads its
  5567. // batch records, mesh headers and instance transforms this way, so
  5568. // it passed no meshlet and every indirect mesh draw ran empty.
  5569. // The host's table of strides by heap slot tells a buffer view
  5570. // (not 0) from anything else, which is still read as a constant
  5571. // buffer; only the load that fits the slot runs.
  5572. let picked = match kind {
  5573. None => self.slot_stride(src)?,
  5574. Some(_) => None,
  5575. };
  5576. if let Some(stride) = picked {
  5577. let zero = self.s.m.i32(0);
  5578. let is_buffer = self.s.m.cmp(self.cur, pred::NE, stride, zero);
  5579. let at = self.begin_guarded(Some(is_buffer));
  5580. let h = self.handle(site, src, false, (11, 0))?;
  5581. let mut raw = Vec::new();
  5582. for k in 0..count {
  5583. let b = self.cur;
  5584. let off = self.s.m.i32(4 * k);
  5585. let a = self.s.m.bin(b, Bin::Add, addr, off);
  5586. let mask = self.s.m.i8(1);
  5587. let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  5588. let r = self.s.op(
  5589. b,
  5590. "rawBufferLoad.f32",
  5591. Attr::ReadOnly,
  5592. self.s.t.res_ret,
  5593. 139,
  5594. &[h, a, u, mask, al],
  5595. );
  5596. let x = self.s.m.extract(b, r, 0);
  5597. let x = self.as_int(x);
  5598. raw.push((x, zero));
  5599. }
  5600. let raw = self.end_guarded(at, &raw);
  5601. let other = self.s.m.cmp(self.cur, pred::EQ, stride, zero);
  5602. let at = self.begin_guarded(Some(other));
  5603. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  5604. let mut both = Vec::new();
  5605. for (k, &r) in raw.iter().enumerate() {
  5606. let b = self.cur;
  5607. let off = self.s.m.i32(4 * k as u32);
  5608. let a = self.s.m.bin(b, Bin::Add, addr, off);
  5609. let x = self.cbuffer_dword(h, a);
  5610. both.push((x, r));
  5611. }
  5612. let both = self.end_guarded(at, &both);
  5613. for (k, x) in both.into_iter().enumerate() {
  5614. self.write(inst, Reg::S(code + k as u8), x, None);
  5615. }
  5616. return Ok(());
  5617. }
  5618. if matches!(kind, Some(u) if u.kind == ResourceType::Srv) {
  5619. let h = self.handle(site, src, false, (11, 0))?;
  5620. for k in 0..count {
  5621. let off = self.s.m.i32(4 * k);
  5622. let a = self.s.m.bin(c, Bin::Add, addr, off);
  5623. let mask = self.s.m.i8(1);
  5624. let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  5625. let r = self.s.op(
  5626. c,
  5627. "rawBufferLoad.f32",
  5628. Attr::ReadOnly,
  5629. self.s.t.res_ret,
  5630. 139,
  5631. &[h, a, u, mask, al],
  5632. );
  5633. let x = self.s.m.extract(c, r, 0);
  5634. let x = self.as_int(x);
  5635. self.write(inst, Reg::S(code + k as u8), x, None);
  5636. }
  5637. return Ok(());
  5638. }
  5639. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  5640. let constant = match addr {
  5641. V::Const(_)
  5642. if matches!(soffset, Operand::Scalar { code: NULL, .. }) && extra.is_none() =>
  5643. {
  5644. Some(*offset as u32)
  5645. }
  5646. _ => None,
  5647. };
  5648. let mut rows: HashMap<u32, V> = HashMap::new();
  5649. for k in 0..count {
  5650. let x = match constant {
  5651. Some(base) => {
  5652. let byte = base + 4 * k;
  5653. let row = match rows.get(&(byte >> 4)) {
  5654. Some(&r) => r,
  5655. None => {
  5656. let ri = self.s.m.i32(byte >> 4);
  5657. let r = self.s.op(
  5658. c,
  5659. "cbufferLoadLegacy.i32",
  5660. Attr::ReadOnly,
  5661. self.s.t.cbuf_ret,
  5662. 59,
  5663. &[h, ri],
  5664. );
  5665. rows.insert(byte >> 4, r);
  5666. r
  5667. }
  5668. };
  5669. self.s.m.extract(c, row, (byte >> 2) & 3)
  5670. }
  5671. None => {
  5672. let off = self.s.m.i32(4 * k);
  5673. let a = self.s.m.bin(c, Bin::Add, addr, off);
  5674. self.cbuffer_dword(h, a)
  5675. }
  5676. };
  5677. self.write(inst, Reg::S(code + k as u8), x, None);
  5678. }
  5679. Ok(())
  5680. }
  5681. /// A descriptor load (`s_load_dword*` from a table or heap) whose dwords
  5682. /// the code also reads as numbers: the console compiler computes sizes
  5683. /// from descriptor bits (an image's width, height, depth, levels; a
  5684. /// buffer's record count) instead of querying them. Those fields are
  5685. /// rebuilt from the host view's dimensions in the GFX10 layout (image
  5686. /// dword 1 bits 30-31 and dword 2 bits 0-13 width - 1, dword 2 bits
  5687. /// 14-29 height - 1, dword 3 identity swizzle, last level at 16, type at
  5688. /// 28, dword 4 depth or layers - 1; buffer dword 2 the record count).
  5689. // shortcut: the base level reads 0 (the host view starts at its own
  5690. // level 0, so sizes the code shifts by it come out right) and the other
  5691. // dwords (addresses, formats, tiling) have no host value: reading them
  5692. // stops the program.
  5693. fn descriptor_data(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  5694. const OTHER: Why = "a descriptor's address or format read as data";
  5695. let Fields::Smem {
  5696. data: Some(Operand::Scalar { code, .. }),
  5697. ..
  5698. } = inst.fields
  5699. else {
  5700. return Err("a scalar memory read as data");
  5701. };
  5702. let count = match inst.name().strip_prefix("s_load_dword") {
  5703. Some("") => 1u32,
  5704. Some("x2") => 2,
  5705. Some("x4") => 4,
  5706. Some("x8") => 8,
  5707. Some("x16") => 16,
  5708. _ => return Err("a scalar memory read as data"),
  5709. };
  5710. // How the program uses the descriptor tells the view's kind: an image or buffer
  5711. // instruction before a scalar buffer load, which reads any buffer.
  5712. let x = self.x;
  5713. let uses = |of: Site| {
  5714. x.res
  5715. .descriptors
  5716. .iter()
  5717. .filter(|d| d.role == Role::Resource)
  5718. .filter_map(move |d| {
  5719. d.source.leaves().into_iter().find_map(|l| match *l {
  5720. Source::Loaded { load, first } if load == of => Some((d.site, first)),
  5721. _ => None,
  5722. })
  5723. })
  5724. };
  5725. let by_scalar_load = |u: &(Site, u8)| {
  5726. matches!(x.p.blocks[u.0.0].insts[u.0.1].fields, Fields::Smem { .. })
  5727. };
  5728. let use_of = |of: Site| uses(of).find(|u| !by_scalar_load(u)).or_else(|| uses(of).next());
  5729. // The console compiler loads a descriptor again wherever it needs it, and for a
  5730. // size it reads the dwords of a load that nothing uses as a descriptor (a texture
  5731. // picked from the heap by an index held per lane: one load for its width, one for
  5732. // its base level, one for each read of the image). Another load of as many dwords
  5733. // from the same address reads the same descriptor, so what uses that one tells
  5734. // this one's kind. The handle is still made from this load's own operands, which
  5735. // hold here.
  5736. let address = self.scalar.get(&site).copied();
  5737. let twin = || {
  5738. let a = address?;
  5739. let same = |s: Site| x.p.blocks[s.0].insts[s.1].name() == inst.name();
  5740. x.res
  5741. .scalar
  5742. .iter()
  5743. .filter(|(s, b)| *s != site && *b == a && same(*s))
  5744. .find_map(|(s, _)| use_of(*s))
  5745. };
  5746. let use_at = use_of(site).or_else(twin);
  5747. // A view whose kind no use tells, but what is read of it does.
  5748. let sized = match use_at {
  5749. Some(_) => None,
  5750. None => self.sized_view(inst, site, code, count),
  5751. };
  5752. let Some((at, first)) = use_at.or(sized.map(|_| (site, 0))) else {
  5753. // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only
  5754. // copies its dwords and compares them, lane against first lane, and every load
  5755. // that reaches those lanes reads one address. Each dword stands in as its place
  5756. // in the table, so the lanes compare equal as they do on the console.
  5757. if self.x.res.lane_copied.contains(&site)
  5758. && let Some(a) = self.scalar.get(&site).copied()
  5759. {
  5760. for k in 0..count {
  5761. let x = self.s.m.i32(a.offset / 4 + k);
  5762. self.write(inst, Reg::S(code + k as u8), x, None);
  5763. }
  5764. return Ok(());
  5765. }
  5766. // A sampler's descriptor: no program reads its dwords as numbers, so where one
  5767. // meets numbers at a join the register is dead on that path (`dead`), as a
  5768. // descriptor's address or format is.
  5769. let sampler = x.res.descriptors.iter().any(|d| {
  5770. d.role == Role::Sampler
  5771. && d.source.leaves().into_iter().any(
  5772. |l| matches!(*l, Source::Loaded { load, .. } if load == site),
  5773. )
  5774. });
  5775. if sampler {
  5776. self.stale.extend(inst.writes.iter().map(|w| w.1));
  5777. return Err("a sampler's descriptor read as data");
  5778. }
  5779. // A buffer view the code only takes the address of, to walk
  5780. // the memory behind it (a ray-tracing structure): the address
  5781. // from the host, the other dwords have no value.
  5782. if count <= 4
  5783. && let Some((lo, hi)) = self.view_address(site)
  5784. {
  5785. for k in 0..count {
  5786. let reg = Reg::S(code + k as u8);
  5787. match k {
  5788. 0 => self.write(inst, reg, lo, None),
  5789. 1 => self.write(inst, reg, hi, None),
  5790. _ => {
  5791. if let Some(v) = inst.write(reg) {
  5792. self.vals.insert(v, Val::Missing(OTHER));
  5793. self.stale.insert(v);
  5794. }
  5795. }
  5796. }
  5797. }
  5798. return Ok(());
  5799. }
  5800. if std::env::var_os("VICTORY_DESC_WHY").is_some() {
  5801. eprintln!(
  5802. "DESC-WHY {:#x} {} scalar={:?} lane_copied={}",
  5803. inst.machine.offset,
  5804. inst.name(),
  5805. address,
  5806. self.x.res.lane_copied.contains(&site)
  5807. );
  5808. }
  5809. return Err("a descriptor read only as data");
  5810. };
  5811. let src = Source::Loaded { load: site, first };
  5812. let used = self.used_kind(&src);
  5813. let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1];
  5814. let un = ui.name();
  5815. let uav = un.contains("store")
  5816. || un.contains("atomic")
  5817. || used.is_some_and(|u| u.kind == ResourceType::Uav);
  5818. let u = if uav { 0x1000 } else { 0 };
  5819. let (props, image) = match &ui.fields {
  5820. _ if sized.is_some_and(|image| image) => ((2 | u, 0x409), Some(2)),
  5821. _ if sized.is_some() => ((11 | u, 0), None),
  5822. // A ray-tracing structure in a buffer of the host: read raw.
  5823. Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None),
  5824. Fields::Image { dim, .. } => {
  5825. let kind = match dim {
  5826. 0 => 1,
  5827. 1 => 2,
  5828. 2 => 4,
  5829. 4 => 6,
  5830. 5 => 7,
  5831. _ => return Err("an image dimension (cube or MSAA)"),
  5832. };
  5833. ((kind | u, 0x409), Some(kind))
  5834. }
  5835. Fields::Buffer { idxen, format, .. } => {
  5836. let stride = used.map_or(0, |u| u.stride);
  5837. let counted = inst
  5838. .write(Reg::S(code + first + 2))
  5839. .is_some_and(|v| self.read_as_number(v));
  5840. let props = if un.starts_with("buffer_load_format")
  5841. || un.starts_with("buffer_store_format")
  5842. {
  5843. (10 | u, 0x409)
  5844. } else if !counted
  5845. && *idxen
  5846. && format.is_none()
  5847. && stride >= 4
  5848. && stride.is_multiple_of(4)
  5849. {
  5850. // Nothing reads the count: the query is cleaned up.
  5851. (12 | u, stride)
  5852. } else {
  5853. // Structured ones too: the host's views of them are raw
  5854. // (see `buffer`), which count bytes, and a size asked
  5855. // for as a structured view's is that count on AMD.
  5856. (11 | u, 0)
  5857. };
  5858. if used.is_some_and(|u| u.kind == ResourceType::Cbv) {
  5859. self.stale.extend(inst.writes.iter().map(|w| w.1));
  5860. return Err("a constant buffer's descriptor read as data");
  5861. }
  5862. (props, None)
  5863. }
  5864. // Read by scalar buffer loads alone: the raw view `smem` reads it through.
  5865. Fields::Smem { .. } if used.is_some_and(|u| u.kind == ResourceType::Srv) => {
  5866. ((11, 0), None)
  5867. }
  5868. // A constant buffer: nothing of its descriptor is a number.
  5869. Fields::Smem { .. } => {
  5870. self.stale.extend(inst.writes.iter().map(|w| w.1));
  5871. return Err("a constant buffer's descriptor read as data");
  5872. }
  5873. _ => return Err("a scalar memory read as data"),
  5874. };
  5875. let h = self.handle(site, &src, false, props)?;
  5876. let c = self.cur;
  5877. let i32t = self.s.t.i32;
  5878. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  5879. let mip = if image.is_some() && !uav {
  5880. self.s.m.i32(0)
  5881. } else {
  5882. self.s.m.undef(i32t)
  5883. };
  5884. let d = self
  5885. .s
  5886. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  5887. let field = |l: &mut Self, k: u32| l.s.m.extract(c, d, k);
  5888. let words: Vec<(u32, V)> = match image {
  5889. Some(kind) => {
  5890. let one = self.s.m.i32(1);
  5891. let w = field(self, 0);
  5892. let (height, depth) = match kind {
  5893. 1 => (one, one),
  5894. 2 => (field(self, 1), one),
  5895. 6 => (one, field(self, 1)),
  5896. _ => (field(self, 1), field(self, 2)),
  5897. };
  5898. let levels = if uav { one } else { field(self, 3) };
  5899. let less = |l: &mut Self, x: V| l.s.m.bin(c, Bin::Sub, x, one);
  5900. let (w, height, depth, levels) = (
  5901. less(self, w),
  5902. less(self, height),
  5903. less(self, depth),
  5904. less(self, levels),
  5905. );
  5906. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  5907. let (k30, k2, k14, k16, mask) = (
  5908. k(self, 30),
  5909. k(self, 2),
  5910. k(self, 14),
  5911. k(self, 16),
  5912. k(self, 0x3FFF),
  5913. );
  5914. let d1 = self.s.m.bin(c, Bin::Shl, w, k30);
  5915. let hi = self.s.m.bin(c, Bin::LShr, w, k2);
  5916. let hi = self.s.m.bin(c, Bin::And, hi, mask);
  5917. let ht = self.s.m.bin(c, Bin::Shl, height, k14);
  5918. let d2 = self.s.m.bin(c, Bin::Or, hi, ht);
  5919. let ty = [0, 8, 9, 0, 10, 0, 12, 13][kind as usize];
  5920. let base = k(self, 0xFAC | ty << 28);
  5921. let last = self.s.m.bin(c, Bin::Shl, levels, k16);
  5922. let d3 = self.s.m.bin(c, Bin::Or, base, last);
  5923. vec![(1, d1), (2, d2), (3, d3), (4, depth)]
  5924. }
  5925. None => {
  5926. // A raw view counts bytes; the descriptor's record count is in elements.
  5927. let n = field(self, 0);
  5928. let stride = used.map_or(0, |u| u.stride);
  5929. let n = if props.0 & 0xFF == 11 && stride > 1 {
  5930. let k = self.s.m.i32(stride);
  5931. self.s.m.bin(c, Bin::UDiv, n, k)
  5932. } else {
  5933. n
  5934. };
  5935. let mut words = vec![(2, n)];
  5936. // Its address too, where the code computes with it and the
  5937. // host can tell it.
  5938. let computed = (0..2u8).any(|k| {
  5939. inst.write(Reg::S(code + first + k))
  5940. .is_some_and(|v| self.computed_with(v, 6))
  5941. });
  5942. if first == 0
  5943. && computed
  5944. && let Some((lo, hi)) = self.view_address(site)
  5945. {
  5946. words.extend([(0, lo), (1, hi)]);
  5947. }
  5948. words
  5949. }
  5950. };
  5951. for k in 0..count {
  5952. let rel = k.wrapping_sub(u32::from(first));
  5953. match words.iter().find(|w| w.0 == rel) {
  5954. Some(&(_, x)) => self.write(inst, Reg::S(code + k as u8), x, None),
  5955. None => {
  5956. if let Some(v) = inst.write(Reg::S(code + k as u8)) {
  5957. self.vals.insert(v, Val::Missing(OTHER));
  5958. self.stale.insert(v);
  5959. }
  5960. }
  5961. }
  5962. }
  5963. Ok(())
  5964. }
  5965. /// `s_load_dword*` from the program's constant table.
  5966. fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> {
  5967. let Fields::Smem {
  5968. data: Some(Operand::Scalar { code, .. }),
  5969. ..
  5970. } = inst.fields
  5971. else {
  5972. return Err("a scalar load");
  5973. };
  5974. let count = match inst.name().strip_prefix("s_load_dword") {
  5975. Some("") => 1u32,
  5976. Some("x2") => 2,
  5977. Some("x4") => 4,
  5978. Some("x8") => 8,
  5979. Some("x16") => 16,
  5980. _ => return Err("a scalar load from the code"),
  5981. };
  5982. let c = self.cur;
  5983. let mut addr = self.s.m.i32(a.offset);
  5984. if let Some(value) = a.dynamic {
  5985. let mut d = self.i32_of(value)?;
  5986. // A term held per lane reached the address through
  5987. // `v_readfirstlane_b32`: the first lane's.
  5988. let per_lane = self.def_block.get(&value).is_some_and(|&b| {
  5989. let writes = |i: &Inst| i.writes.iter().any(|w| w.1 == value && matches!(w.0, Reg::V(_)));
  5990. self.x.p.blocks[b].insts.iter().any(writes)
  5991. });
  5992. if per_lane {
  5993. self.s.flags |= flags::WAVE_OPS;
  5994. let i32t = self.s.t.i32;
  5995. let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[d]);
  5996. d = if self.s.pixel && super::helper_own() {
  5997. let helper = self.helper_lane();
  5998. self.s.m.select(c, helper, d, first)
  5999. } else {
  6000. first
  6001. };
  6002. }
  6003. addr = self.s.m.bin(c, Bin::Add, addr, d);
  6004. }
  6005. for k in 0..count {
  6006. let off = self.s.m.i32(4 * k);
  6007. let at = self.s.m.bin(c, Bin::Add, addr, off);
  6008. let x = self.code_dword(at)?;
  6009. self.write(inst, Reg::S(code + k as u8), x, None);
  6010. }
  6011. Ok(())
  6012. }
  6013. /// The dword at a computed byte address of a constant buffer.
  6014. fn cbuffer_dword(&mut self, h: V, a: V) -> V {
  6015. let c = self.cur;
  6016. let four = self.s.m.i32(4);
  6017. let ri = self.s.m.bin(c, Bin::LShr, a, four);
  6018. let r = self.s.op(
  6019. c,
  6020. "cbufferLoadLegacy.i32",
  6021. Attr::ReadOnly,
  6022. self.s.t.cbuf_ret,
  6023. 59,
  6024. &[h, ri],
  6025. );
  6026. let two = self.s.m.i32(2);
  6027. let three = self.s.m.i32(3);
  6028. let comp = self.s.m.bin(c, Bin::LShr, a, two);
  6029. let comp = self.s.m.bin(c, Bin::And, comp, three);
  6030. let mut x = self.s.m.extract(c, r, 0);
  6031. for j in 1..4 {
  6032. let e = self.s.m.extract(c, r, j);
  6033. let jc = self.s.m.i32(j);
  6034. let is = self.s.m.cmp(c, pred::EQ, comp, jc);
  6035. x = self.s.m.select(c, is, e, x);
  6036. }
  6037. x
  6038. }
  6039. /// `channels` channels of the element at byte `off` of raw buffer `h`,
  6040. /// converted from the GFX10 buffer format `format` as the hardware's
  6041. /// typed loads do (channels past the format's read 0, 0, 0, 1).
  6042. // shortcut: the descriptor's channel swizzle is taken as the identity
  6043. // (it is for raw views and the descriptors code builds), elements of 4
  6044. // bytes or more as dword-aligned. Norm formats divide, which the AMD
  6045. // driver does 1 ULP off the hardware's correctly rounded conversion for
  6046. // some values; correct it with an integer check if a title compares
  6047. // converted values exactly.
  6048. fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result<Vec<V>, Why> {
  6049. let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?;
  6050. let c = self.cur;
  6051. let total: u32 = bits.iter().sum();
  6052. let (u, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  6053. let load = |l: &mut Self, at: V, n: u32| -> Vec<V> {
  6054. let mask = l.s.m.i8((1u8 << n) - 1);
  6055. let r = l.s.op(
  6056. c,
  6057. "rawBufferLoad.f32",
  6058. Attr::ReadOnly,
  6059. l.s.t.res_ret,
  6060. 139,
  6061. &[h, at, u, mask, align],
  6062. );
  6063. (0..n)
  6064. .map(|k| {
  6065. let x = l.s.m.extract(c, r, k);
  6066. l.as_int(x)
  6067. })
  6068. .collect()
  6069. };
  6070. let words = if total < 32 {
  6071. // A byte or half inside the dword that holds it.
  6072. let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3));
  6073. let at = self.s.m.bin(c, Bin::And, off, not3);
  6074. let w = load(self, at, 1)[0];
  6075. let byte = self.s.m.bin(c, Bin::And, off, three);
  6076. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  6077. vec![self.s.m.bin(c, Bin::LShr, w, sh)]
  6078. } else {
  6079. load(self, off, total / 32)
  6080. };
  6081. let float = |l: &mut Self, f: V| l.as_int(f);
  6082. let mut out = Vec::new();
  6083. let mut at = 0;
  6084. for &w in bits {
  6085. let word = words[(at / 32) as usize];
  6086. let field = if w == 32 {
  6087. word
  6088. } else {
  6089. let sh = self.s.m.i32(at % 32);
  6090. let t = self.s.m.bin(c, Bin::LShr, word, sh);
  6091. let m = self.s.m.i32((1 << w) - 1);
  6092. self.s.m.bin(c, Bin::And, t, m)
  6093. };
  6094. at += w;
  6095. // Sign-extended from the field's top bit.
  6096. let signed = |l: &mut Self| {
  6097. if w == 32 {
  6098. return field;
  6099. }
  6100. let k = l.s.m.i32(32 - w);
  6101. let t = l.s.m.bin(c, Bin::Shl, field, k);
  6102. l.s.m.bin(c, Bin::AShr, t, k)
  6103. };
  6104. let f32t = self.s.t.f32;
  6105. let x = match numeric {
  6106. Numeric::Unorm => {
  6107. let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
  6108. let max = self.s.m.f32((((1u64 << w) - 1) as f32).to_bits());
  6109. let q = self.s.m.bin(c, Bin::SDiv, f, max);
  6110. float(self, q)
  6111. }
  6112. Numeric::Snorm => {
  6113. let s = signed(self);
  6114. let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
  6115. let max = self.s.m.f32((((1u64 << (w - 1)) - 1) as f32).to_bits());
  6116. let q = self.s.m.bin(c, Bin::SDiv, f, max);
  6117. let lo = self.s.m.f32((-1.0f32).to_bits());
  6118. let q = self.binary(35, q, lo);
  6119. float(self, q)
  6120. }
  6121. Numeric::Uscaled => {
  6122. let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
  6123. float(self, f)
  6124. }
  6125. Numeric::Sscaled => {
  6126. let s = signed(self);
  6127. let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
  6128. float(self, f)
  6129. }
  6130. Numeric::Uint => field,
  6131. Numeric::Sint => signed(self),
  6132. Numeric::Float if w == 32 => field,
  6133. Numeric::Float => {
  6134. let h = match half_shift(w) {
  6135. 0 => field,
  6136. k => {
  6137. let sh = self.s.m.i32(k);
  6138. self.s.m.bin(c, Bin::Shl, field, sh)
  6139. }
  6140. };
  6141. let f = self
  6142. .s
  6143. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  6144. float(self, f)
  6145. }
  6146. };
  6147. out.push(x);
  6148. }
  6149. let one = match numeric {
  6150. Numeric::Uint | Numeric::Sint => 1,
  6151. _ => 1.0f32.to_bits(),
  6152. };
  6153. for k in out.len() as u32..channels {
  6154. out.push(self.s.m.i32(if k == 3 { one } else { 0 }));
  6155. }
  6156. out.truncate(channels as usize);
  6157. Ok(out)
  6158. }
  6159. /// The byte offset a buffer descriptor built around a root descriptor adds
  6160. /// (constant and computed parts); none for other descriptors.
  6161. fn built_offset(&mut self, src: &Source) -> Result<(u32, Option<V>), Why> {
  6162. match src {
  6163. Source::Built { address, .. } => {
  6164. let mut x = match address.dynamic {
  6165. Some(v) => Some(self.i32_of(v)?),
  6166. None => None,
  6167. };
  6168. if let Some(bias) = self.root_bias(address.param) {
  6169. x = Some(match x {
  6170. Some(d) => self.s.m.bin(self.cur, Bin::Add, d, bias),
  6171. None => bias,
  6172. });
  6173. }
  6174. Ok((address.offset, x))
  6175. }
  6176. _ => Ok((0, None)),
  6177. }
  6178. }
  6179. /// For a root view the host binds as a raw view that may begin before
  6180. /// the title's address (`shader.rs` `USER_VIEW_BIAS`): the bytes to add
  6181. /// to offsets through it. Every root UAV, and the root SRVs of programs
  6182. /// with a spilled user-data table (the others keep the views they
  6183. /// have).
  6184. fn root_bias(&mut self, param: usize) -> Option<V> {
  6185. use super::shader::USER_VIEW_BIAS;
  6186. let rp = *self.x.native.layout.get(param)?;
  6187. if rp.root != RootType::Descriptor {
  6188. return None;
  6189. }
  6190. let kind = self
  6191. .x
  6192. .native
  6193. .used
  6194. .iter()
  6195. .find(|u| u.user_data == rp.user_data)
  6196. .map(|u| u.kind);
  6197. let biased = match kind {
  6198. Some(ResourceType::Uav) => true,
  6199. Some(ResourceType::Srv) => crate::spill::is_spilled(self.x.native),
  6200. _ => false,
  6201. };
  6202. biased.then(|| self.host_word(RootType::Other(USER_VIEW_BIAS), rp.slot, 0))
  6203. }
  6204. /// The used-resource entry a descriptor loaded from a table falls in.
  6205. fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> {
  6206. if let Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } =
  6207. src
  6208. {
  6209. return self.used_kind(args.first()?);
  6210. }
  6211. if let Source::LanePhi { args, .. } = src {
  6212. return args.iter().flatten().find_map(|a| self.used_kind(a));
  6213. }
  6214. if let Source::Built { address, .. } = src {
  6215. let rp = self.x.native.layout.get(address.param)?;
  6216. return self
  6217. .x
  6218. .native
  6219. .used
  6220. .iter()
  6221. .find(|u| u.root == RootType::Descriptor && u.user_data == rp.user_data);
  6222. }
  6223. let (Source::Loaded { load, first } | Source::Fetched { load, first }) = src else {
  6224. return None;
  6225. };
  6226. let a = self.scalar.get(load)?;
  6227. let rp = self.x.native.layout.get(a.param)?;
  6228. if rp.root != RootType::Table {
  6229. return None;
  6230. }
  6231. let dword = (a.offset / 4) + u32::from(*first);
  6232. self.x
  6233. .native
  6234. .used
  6235. .iter()
  6236. .filter(|u| {
  6237. u.root == RootType::Table
  6238. && u.user_data == rp.user_data
  6239. && u.table_offset_dwords <= dword
  6240. })
  6241. .max_by_key(|u| u.table_offset_dwords)
  6242. }
  6243. /// A handle for the descriptor `src` read at `site`.
  6244. fn handle(
  6245. &mut self,
  6246. site: Site,
  6247. src: &Source,
  6248. sampler: bool,
  6249. props: (u32, u32),
  6250. ) -> Result<V, Why> {
  6251. match src {
  6252. Source::Loaded { load, first } => {
  6253. let key = (self.cur, *load, *first, sampler, props);
  6254. if let Some(&h) = self.handles.get(&key) {
  6255. return Ok(h);
  6256. }
  6257. let index = self.heap_index(*load, *first, sampler)?;
  6258. // A waterfall loop's load at the first lane's offset reads
  6259. // each lane's own entry (see `resource::Waterfall`).
  6260. let per_lane = self.x.res.waterfall.loads.contains(load);
  6261. let h = self
  6262. .s
  6263. .heap_handle(self.cur, index, sampler, per_lane, props);
  6264. self.handles.insert(key, h);
  6265. Ok(h)
  6266. }
  6267. Source::Constant(words) if sampler => {
  6268. let words: [u32; 4] = words
  6269. .get(..4)
  6270. .and_then(|w| w.try_into().ok())
  6271. .ok_or("a sampler constant")?;
  6272. let n = match self.samplers.iter().position(|w| *w == words) {
  6273. Some(n) => n,
  6274. None => {
  6275. self.samplers.push(words);
  6276. self.samplers.len() - 1
  6277. }
  6278. };
  6279. if props.0 & 0x8000 != 0 {
  6280. // shortcut: one sampler used with and without comparison
  6281. // would need two static samplers; it becomes a comparison one.
  6282. self.s.cmp_samplers |= 1 << n;
  6283. }
  6284. Ok(self.s.sampler_handle(self.cur, n as u32))
  6285. }
  6286. Source::Constant(_) => Err("a constant resource descriptor"),
  6287. Source::Built { address, .. } => {
  6288. let rp = *self
  6289. .x
  6290. .native
  6291. .layout
  6292. .get(address.param)
  6293. .ok_or("a descriptor built around a table in the code")?;
  6294. let kind = self
  6295. .x
  6296. .native
  6297. .used
  6298. .iter()
  6299. .find(|u| u.user_data == rp.user_data)
  6300. .map(|u| u.kind);
  6301. match (rp.root, kind, props.0) {
  6302. (RootType::Descriptor, Some(ResourceType::Cbv) | None, 13) => {
  6303. Ok(self.s.root_cbv_handle(rp.slot))
  6304. }
  6305. (RootType::Descriptor, Some(ResourceType::Srv), 11) => {
  6306. Ok(self.s.root_srv_handle(rp.slot))
  6307. }
  6308. // A root UAV: a raw buffer whether the access reads
  6309. // (11) or writes (11 with the UAV bit). Indexed
  6310. // accesses reach here as raw ones at index times the
  6311. // entry's stride (`buffer`).
  6312. (RootType::Descriptor, Some(ResourceType::Uav), 11 | 0x100b) => {
  6313. Ok(self.s.root_uav_handle(rp.slot))
  6314. }
  6315. (RootType::Descriptor, Some(ResourceType::Srv), 0x100b) => {
  6316. Err("a write through a root SRV")
  6317. }
  6318. _ => Err("a typed root view"),
  6319. }
  6320. }
  6321. Source::Phi { block, args } => {
  6322. let _ = site;
  6323. let phi = self.descriptor_phi(*block, args, sampler, 8)?;
  6324. Ok(self.s.heap_handle(self.cur, phi, sampler, false, props))
  6325. }
  6326. Source::Select { scc, args } => {
  6327. // The heap index of each choice, picked by SCC (uniform).
  6328. let [
  6329. Source::Loaded { load: a, first: fa },
  6330. Source::Loaded { load: b, first: fb },
  6331. ] = args[..]
  6332. else {
  6333. return Err("a descriptor chosen by a condition");
  6334. };
  6335. let cond = match self.get(*scc)? {
  6336. Val::Bit(x) => x,
  6337. _ => return Err("SCC without a value"),
  6338. };
  6339. let set = self.heap_index(a, fa, sampler)?;
  6340. let clear = self.heap_index(b, fb, sampler)?;
  6341. let index = self.s.m.select(self.cur, cond, set, clear);
  6342. Ok(self.s.heap_handle(self.cur, index, sampler, false, props))
  6343. }
  6344. Source::Fetched { .. } | Source::Lanes { .. } | Source::LanePhi { .. } => {
  6345. // A descriptor each lane has its own of (a waterfall loop
  6346. // reads it from the first active lane): each lane's heap
  6347. // index, non-uniform.
  6348. let index = self.lane_heap_index(src, sampler)?;
  6349. Ok(self.s.heap_handle(self.cur, index, sampler, true, props))
  6350. }
  6351. }
  6352. }
  6353. /// The heap index a descriptor phi picks. Each predecessor computes its
  6354. /// heap index at its end and the join picks one with a phi; a
  6355. /// predecessor whose descriptor is itself chosen by control flow (a
  6356. /// phi of an earlier join, which dominates it) gives that join's phi,
  6357. /// at most `depth` joins deep.
  6358. fn descriptor_phi(
  6359. &mut self,
  6360. block: usize,
  6361. args: &[Source],
  6362. sampler: bool,
  6363. depth: u32,
  6364. ) -> Result<V, Why> {
  6365. const WHY: Why = "a descriptor chosen by control flow";
  6366. let p = self.x.p;
  6367. let mut incoming = Vec::new();
  6368. for (&q, arg) in p.blocks[block].preds.iter().zip(args) {
  6369. if self.block[q].is_none() {
  6370. continue;
  6371. }
  6372. let tail = self.tail[q].ok_or(WHY)?;
  6373. let at = self.edges.get(&(q, block)).copied().unwrap_or(tail);
  6374. let index = match arg {
  6375. Source::Loaded { load, first } => {
  6376. let here = std::mem::replace(&mut self.cur, at);
  6377. let index = self.heap_index(*load, *first, sampler);
  6378. self.cur = here;
  6379. index?
  6380. }
  6381. Source::Phi { block: inner, args: inner_args } if depth > 0 => {
  6382. self.descriptor_phi(*inner, inner_args, sampler, depth - 1)?
  6383. }
  6384. _ => return Err(WHY),
  6385. };
  6386. incoming.push((index, at));
  6387. }
  6388. let join = self.block[block].ok_or(WHY)?;
  6389. let phi = self.s.m.phi(join, self.s.t.i32);
  6390. self.s.m.set_phi(phi, incoming);
  6391. Ok(phi)
  6392. }
  6393. /// Registers an immediate sampler constant and returns its slot index.
  6394. fn register_sampler(&mut self, words: &[u32], cmp: bool) -> Result<u32, Why> {
  6395. let words: [u32; 4] = words
  6396. .get(..4)
  6397. .and_then(|w| w.try_into().ok())
  6398. .ok_or("a sampler constant")?;
  6399. let n = match self.samplers.iter().position(|w| *w == words) {
  6400. Some(n) => n,
  6401. None => {
  6402. self.samplers.push(words);
  6403. self.samplers.len() - 1
  6404. }
  6405. };
  6406. if cmp && n < 64 {
  6407. self.s.cmp_samplers |= 1 << n;
  6408. }
  6409. Ok(n as u32)
  6410. }
  6411. /// Resolves a control-flow phi of immediate sampler constants into either a
  6412. /// single static sampler register (`One`) or a uniform `i32` phi index over
  6413. /// `regs` (`Many`) for branch dispatch at the sample site.
  6414. fn sampler_phi_choice(
  6415. &mut self,
  6416. block: usize,
  6417. args: &[Source],
  6418. cmp: bool,
  6419. depth: u32,
  6420. ) -> Result<(Option<V>, Vec<u32>), Why> {
  6421. const WHY: Why = "a descriptor chosen by control flow";
  6422. let mut distinct: Vec<[u32; 4]> = Vec::new();
  6423. self.collect_constant_samplers(block, args, depth, &mut distinct)?;
  6424. if distinct.is_empty() {
  6425. return Err(WHY);
  6426. }
  6427. let mut regs = Vec::with_capacity(distinct.len());
  6428. for w in &distinct {
  6429. regs.push(self.register_sampler(w, cmp)?);
  6430. }
  6431. if regs.len() == 1 {
  6432. return Ok((None, regs));
  6433. }
  6434. let idx = self.sampler_index_phi(block, args, 0, &distinct, depth)?;
  6435. Ok((Some(idx), regs))
  6436. }
  6437. fn collect_constant_samplers(
  6438. &self,
  6439. block: usize,
  6440. args: &[Source],
  6441. depth: u32,
  6442. distinct: &mut Vec<[u32; 4]>,
  6443. ) -> Result<(), Why> {
  6444. const WHY: Why = "a descriptor chosen by control flow";
  6445. let p = self.x.p;
  6446. for (&q, arg) in p.blocks[block].preds.iter().zip(args) {
  6447. if self.block[q].is_none() {
  6448. continue;
  6449. }
  6450. match arg {
  6451. Source::Constant(w) if w.len() >= 4 => {
  6452. let k: [u32; 4] = w[..4].try_into().unwrap();
  6453. if !distinct.contains(&k) {
  6454. distinct.push(k);
  6455. }
  6456. }
  6457. Source::Phi {
  6458. block: inner,
  6459. args: inner_args,
  6460. } if depth > 0 => {
  6461. self.collect_constant_samplers(*inner, inner_args, depth - 1, distinct)?;
  6462. }
  6463. _ => return Err(WHY),
  6464. }
  6465. }
  6466. Ok(())
  6467. }
  6468. fn sampler_index_phi(
  6469. &mut self,
  6470. block: usize,
  6471. args: &[Source],
  6472. lower: u32,
  6473. distinct: &[[u32; 4]],
  6474. depth: u32,
  6475. ) -> Result<V, Why> {
  6476. const WHY: Why = "a descriptor chosen by control flow";
  6477. let p = self.x.p;
  6478. let mut incoming = Vec::new();
  6479. for (&q, arg) in p.blocks[block].preds.iter().zip(args) {
  6480. if self.block[q].is_none() {
  6481. continue;
  6482. }
  6483. let tail = self.tail[q].ok_or(WHY)?;
  6484. let at = self.edges.get(&(q, block)).copied().unwrap_or(tail);
  6485. let idx = match arg {
  6486. Source::Constant(w) if w.len() >= 4 => {
  6487. let k: [u32; 4] = w[..4].try_into().unwrap();
  6488. let pos = distinct.iter().position(|d| *d == k).ok_or(WHY)? as u32;
  6489. self.s.m.i32(lower + pos)
  6490. }
  6491. Source::Phi {
  6492. block: inner,
  6493. args: inner_args,
  6494. } if depth > 0 => {
  6495. self.sampler_index_phi(*inner, inner_args, lower, distinct, depth - 1)?
  6496. }
  6497. _ => return Err(WHY),
  6498. };
  6499. incoming.push((idx, at));
  6500. }
  6501. let join = self.block[block].ok_or(WHY)?;
  6502. let phi = self.s.m.phi(join, self.s.t.i32);
  6503. self.s.m.set_phi(phi, incoming);
  6504. Ok(phi)
  6505. }
  6506. /// The bytes per element of the buffer view `src` names, if the program
  6507. /// picks it from the view heap at an index it computes (root type
  6508. /// `ResourceHeap`): read from the host's table by heap slot in the
  6509. /// current block.
  6510. fn slot_stride(&mut self, src: &Source) -> Result<Option<V>, Why> {
  6511. let Source::Loaded { load, first } = src else {
  6512. return Ok(None);
  6513. };
  6514. let heap = self
  6515. .scalar
  6516. .get(load)
  6517. .and_then(|a| self.x.native.layout.get(a.param))
  6518. .is_some_and(|p| p.root == RootType::ResourceHeap);
  6519. if !heap {
  6520. return Ok(None);
  6521. }
  6522. let key = (self.cur, *load, *first);
  6523. if let Some(&v) = self.strides.get(&key) {
  6524. return Ok(Some(v));
  6525. }
  6526. let c = self.cur;
  6527. let slot = self.heap_index(*load, *first, false)?;
  6528. // Inside the table whatever the index (lanes that do not run
  6529. // compute one too): a root view has no bounds of its own.
  6530. let last = self.s.m.i32(super::shader::SLOT_STRIDES_COUNT - 1);
  6531. let i32t = self.s.t.i32;
  6532. let slot = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[slot, last]);
  6533. self.s.m.tag(slot, Tag::Clamp);
  6534. let two = self.s.m.i32(2);
  6535. let byte = self.s.m.bin(c, Bin::Shl, slot, two);
  6536. let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES);
  6537. let iu = self.s.m.undef(self.s.t.i32);
  6538. let mask = self.s.m.i8(1);
  6539. let align = self.s.m.i32(4);
  6540. let r = self.s.op(
  6541. c,
  6542. "rawBufferLoad.f32",
  6543. Attr::ReadOnly,
  6544. self.s.t.res_ret,
  6545. 139,
  6546. &[h, byte, iu, mask, align],
  6547. );
  6548. let f = self.s.m.extract(c, r, 0);
  6549. let v = self.as_int(f);
  6550. self.strides.insert(key, v);
  6551. Ok(Some(v))
  6552. }
  6553. /// The heap index of a descriptor that may differ between lanes,
  6554. /// computed in the current block (or, chosen by control flow, at the
  6555. /// join).
  6556. fn lane_heap_index(&mut self, src: &Source, sampler: bool) -> Result<V, Why> {
  6557. match src {
  6558. Source::Loaded { load, first } => self.heap_index(*load, *first, sampler),
  6559. Source::Fetched { load, first } => self.fetched_index(*load, *first, sampler),
  6560. Source::Lanes { mask, args } | Source::Select { scc: mask, args } => {
  6561. let [a, b] = &args[..] else {
  6562. return Err("a descriptor chosen per lane");
  6563. };
  6564. let cond = if matches!(src, Source::Lanes { .. }) {
  6565. let &m = self
  6566. .x
  6567. .st
  6568. .masks
  6569. .get(mask)
  6570. .ok_or("a descriptor chosen per lane by an untracked mask")?;
  6571. self.boolean(m, self.cur)?
  6572. } else {
  6573. match self.get(*mask)? {
  6574. Val::Bit(x) => x,
  6575. _ => return Err("SCC without a value"),
  6576. }
  6577. };
  6578. let set = self.lane_heap_index(a, sampler)?;
  6579. let clear = self.lane_heap_index(b, sampler)?;
  6580. Ok(self.s.m.select(self.cur, cond, set, clear))
  6581. }
  6582. Source::LanePhi { block, args } => {
  6583. // Each predecessor computes its heap index at its end (what
  6584. // it reads is there: the dwords are, on that edge); the join
  6585. // picks the one of the edge the lane came by. An edge no
  6586. // lane reading it takes gives index 0.
  6587. let join =
  6588. self.block[*block].ok_or("a per-lane descriptor chosen by control flow")?;
  6589. let mut incoming = Vec::new();
  6590. for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) {
  6591. if self.block[q].is_none() {
  6592. continue;
  6593. }
  6594. let tail =
  6595. self.tail[q].ok_or("a per-lane descriptor joined from a later block")?;
  6596. let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail);
  6597. let index = match arg {
  6598. Some(arg) => {
  6599. let here = std::mem::replace(&mut self.cur, at);
  6600. let index = self.lane_heap_index(arg, sampler);
  6601. self.cur = here;
  6602. index?
  6603. }
  6604. None => self.s.m.i32(0),
  6605. };
  6606. incoming.push((index, at));
  6607. }
  6608. let phi = self.s.m.phi(join, self.s.t.i32);
  6609. self.s.m.set_phi(phi, incoming);
  6610. Ok(phi)
  6611. }
  6612. _ => Err("a per-lane descriptor from neither a heap load nor a choice of them"),
  6613. }
  6614. }
  6615. /// The heap index of the descriptor at dword `first` of what the global
  6616. /// load at `load` reads, in each lane: its address (base plus offsets)
  6617. /// over the descriptor size.
  6618. fn fetched_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> {
  6619. const WHY: Why = "a per-lane descriptor load";
  6620. let a = *self
  6621. .scalar
  6622. .get(&load)
  6623. .ok_or("an untracked descriptor load")?;
  6624. match self.x.native.layout.get(a.param).map(|p| p.root) {
  6625. Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {}
  6626. _ => return Err("a descriptor outside the heaps"),
  6627. }
  6628. let li: &Inst = &self.x.p.blocks[load.0].insts[load.1];
  6629. let Fields::Flat {
  6630. addr: Some(Operand::Vector { reg, .. }),
  6631. saddr,
  6632. offset,
  6633. ..
  6634. } = li.fields
  6635. else {
  6636. return Err(WHY);
  6637. };
  6638. let c = self.cur;
  6639. // The low dword of the address: SGPR base plus VGPR offset, or the
  6640. // VGPR pair's low half (heap addresses fit in 32 bits).
  6641. let mut at = self.i32_of(li.read(Reg::V(reg)).ok_or(WHY)?)?;
  6642. if let Some(Operand::Scalar { code, .. }) = saddr
  6643. && code != NULL
  6644. {
  6645. let base = self.i32_of(li.read(Reg::S(code)).ok_or(WHY)?)?;
  6646. at = self.s.m.bin(c, Bin::Add, base, at);
  6647. }
  6648. let k = self
  6649. .s
  6650. .m
  6651. .i32((offset as i32 as u32).wrapping_add(4 * u32::from(first)));
  6652. at = self.s.m.bin(c, Bin::Add, at, k);
  6653. let shift = self.s.m.i32(if sampler { 4 } else { 5 });
  6654. Ok(self.s.m.bin(c, Bin::LShr, at, shift))
  6655. }
  6656. /// The heap index of the descriptor at dword `first` of what the scalar
  6657. /// load at `load` reads, computed in the current block.
  6658. fn heap_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> {
  6659. let a = *self
  6660. .scalar
  6661. .get(&load)
  6662. .ok_or("an untracked descriptor load")?;
  6663. match self.x.native.layout.get(a.param).map(|p| p.root) {
  6664. Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {}
  6665. _ => return Err("a descriptor outside the heaps"),
  6666. }
  6667. let li: &Inst = &self.x.p.blocks[load.0].insts[load.1];
  6668. let Fields::Smem {
  6669. base,
  6670. offset,
  6671. soffset,
  6672. ..
  6673. } = &li.fields
  6674. else {
  6675. return Err("a descriptor load");
  6676. };
  6677. let Operand::Scalar { code, .. } = *base else {
  6678. return Err("a descriptor load");
  6679. };
  6680. let c = self.cur;
  6681. let base = li.read(Reg::S(code)).ok_or("a descriptor load")?;
  6682. let mut addr = self.i32_of(base)?;
  6683. let k = self
  6684. .s
  6685. .m
  6686. .i32((*offset as u32).wrapping_add(4 * u32::from(first)));
  6687. addr = self.s.m.bin(c, Bin::Add, addr, k);
  6688. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  6689. let so = self.operand(li, soffset)?;
  6690. addr = self.s.m.bin(c, Bin::Add, addr, so);
  6691. }
  6692. let shift = self.s.m.i32(if sampler { 4 } else { 5 });
  6693. Ok(self.s.m.bin(c, Bin::LShr, addr, shift))
  6694. }
  6695. fn valu(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  6696. let Fields::Valu(v) = &inst.fields else {
  6697. unreachable!()
  6698. };
  6699. let name = inst.name();
  6700. if self.x.res.waterfall.compares.contains(&(b, i)) {
  6701. // The first lane's dwords of a waterfall loop are each lane's
  6702. // own (see `resource::Waterfall`).
  6703. self.lane(inst, Some(true));
  6704. return Ok(());
  6705. }
  6706. // One lane of a VGPR a whole-wave section left.
  6707. if name == "v_readlane_b32"
  6708. && let Some(&(_, w)) = inst.writes.first()
  6709. && let Some(sh) = self.sections.get(&b).and_then(|s| {
  6710. s.iter().filter(|s| s.1.end < i).find_map(|s| s.1.reads.get(&w).copied())
  6711. })
  6712. {
  6713. let x = self.shape(sh, false)?;
  6714. self.vals.insert(w, Val::I32(x));
  6715. return Ok(());
  6716. }
  6717. if let Some(rest) = name.strip_prefix("v_cmp_").or(name.strip_prefix("v_cmpx_")) {
  6718. let r = if v.dpp.is_some() {
  6719. Err("a compare with DPP")
  6720. } else {
  6721. self.compare(inst, rest)
  6722. };
  6723. if let Err(why) = r {
  6724. for &(_, w) in &inst.writes {
  6725. self.lane_fail.insert(w, why);
  6726. }
  6727. }
  6728. return r;
  6729. }
  6730. let mut guard = self.guard(b, i)?;
  6731. if let Some(d) = v.dpp {
  6732. let (x, enable) = self.dpp(inst, d)?;
  6733. guard = match (guard, enable) {
  6734. (Some(g), Some(e)) => Some(self.s.m.bin(self.cur, Bin::And, g, e)),
  6735. (g, e) => g.or(e),
  6736. };
  6737. self.src0 = Some(x);
  6738. }
  6739. let r = self.valu_op(inst, guard);
  6740. self.src0 = None;
  6741. r
  6742. }
  6743. /// DPP: src0 as read from another lane, and which lanes write their
  6744. /// result (none: all).
  6745. fn dpp(&mut self, inst: &Inst, dpp: Dpp) -> Result<(V, Option<V>), Why> {
  6746. let Fields::Valu(v) = &inst.fields else {
  6747. unreachable!()
  6748. };
  6749. let Some(&Operand::Vector { reg, .. }) = v.src.first() else {
  6750. return Err("a DPP operand");
  6751. };
  6752. let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("a DPP operand")?)?;
  6753. // Quad permutations and DPP8 stay in groups the pixel layout shares.
  6754. let quad = matches!(dpp, Dpp::Row { ctrl: 0..=0xFF, .. });
  6755. let mesh_quad = self.s.mesh.is_some() && quad;
  6756. if !mesh_quad {
  6757. self.cross_lane(quad)?;
  6758. }
  6759. let c = self.cur;
  6760. let lane = self.lane_index();
  6761. let k = |l: &mut Self, n: u32| l.s.m.i32(n);
  6762. let (sixteen_mask, low) = (k(self, !15), k(self, 15));
  6763. let row = self.s.m.bin(c, Bin::And, lane, sixteen_mask);
  6764. let pos = self.s.m.bin(c, Bin::And, lane, low);
  6765. // Source lane, and whether it lies in the row.
  6766. let (src, inside, masks, zero) = match dpp {
  6767. Dpp::Lanes { sel, .. } => {
  6768. let (seven, not7, three) = (k(self, 7), k(self, !7), k(self, 3));
  6769. let p = self.s.m.bin(c, Bin::And, lane, seven);
  6770. let sh = self.s.m.bin(c, Bin::Mul, p, three);
  6771. let sel = k(self, sel);
  6772. let pick = self.s.m.bin(c, Bin::LShr, sel, sh);
  6773. let pick = self.s.m.bin(c, Bin::And, pick, seven);
  6774. let base = self.s.m.bin(c, Bin::And, lane, not7);
  6775. (self.s.m.bin(c, Bin::Or, base, pick), None, None, false)
  6776. }
  6777. Dpp::Row {
  6778. ctrl,
  6779. row_mask,
  6780. bank_mask,
  6781. bound_ctrl,
  6782. ..
  6783. } => {
  6784. let n = u32::from(ctrl & 15);
  6785. let (src, inside) = match ctrl {
  6786. 0..=0xFF => {
  6787. let (three, one, not3) = (k(self, 3), k(self, 1), k(self, !3));
  6788. let p = self.s.m.bin(c, Bin::And, lane, three);
  6789. let sh = self.s.m.bin(c, Bin::Shl, p, one);
  6790. let perm = k(self, u32::from(ctrl));
  6791. let pick = self.s.m.bin(c, Bin::LShr, perm, sh);
  6792. let pick = self.s.m.bin(c, Bin::And, pick, three);
  6793. let base = self.s.m.bin(c, Bin::And, lane, not3);
  6794. (self.s.m.bin(c, Bin::Or, base, pick), None)
  6795. }
  6796. 0x101..=0x10F | 0x111..=0x11F => {
  6797. let nn = k(self, n);
  6798. let left = ctrl < 0x110;
  6799. let (op, p) = if left {
  6800. (Bin::Add, pred::IULT)
  6801. } else {
  6802. (Bin::Sub, pred::IUGE)
  6803. };
  6804. let s = self.s.m.bin(c, op, lane, nn);
  6805. // Left: pos + n < 16; right: pos >= n.
  6806. let bound = if left { k(self, 16 - n) } else { nn };
  6807. (s, Some(self.s.m.cmp(c, p, pos, bound)))
  6808. }
  6809. 0x121..=0x12F => {
  6810. let nn = k(self, n);
  6811. let t = self.s.m.bin(c, Bin::Sub, pos, nn);
  6812. let t = self.s.m.bin(c, Bin::And, t, low);
  6813. (self.s.m.bin(c, Bin::Or, row, t), None)
  6814. }
  6815. 0x140 | 0x141 => {
  6816. let m = k(self, if ctrl == 0x140 { 15 } else { 7 });
  6817. let t = self.s.m.bin(c, Bin::Xor, lane, m);
  6818. (t, None)
  6819. }
  6820. 0x150..=0x15F => {
  6821. let nn = k(self, n);
  6822. (self.s.m.bin(c, Bin::Or, row, nn), None)
  6823. }
  6824. 0x160..=0x16F => {
  6825. let nn = k(self, n);
  6826. (self.s.m.bin(c, Bin::Xor, lane, nn), None)
  6827. }
  6828. _ => return Err("a DPP lane pattern"),
  6829. };
  6830. let masks = (row_mask != 0xF || bank_mask != 0xF).then_some((row_mask, bank_mask));
  6831. (src, inside, masks, bound_ctrl)
  6832. }
  6833. };
  6834. let mut r = if mesh_quad {
  6835. self.quad_pick(x, src)
  6836. } else {
  6837. self.read_lane(x, src)
  6838. };
  6839. let mut enable = None;
  6840. if let Some(inside) = inside {
  6841. if zero {
  6842. let z = k(self, 0);
  6843. r = self.s.m.select(c, inside, r, z);
  6844. } else {
  6845. enable = Some(inside);
  6846. }
  6847. }
  6848. if let Some((rows, banks)) = masks {
  6849. // Row (16 lanes) and bank (4 lanes of a row) write masks.
  6850. let (four, two, three) = (k(self, 4), k(self, 2), k(self, 3));
  6851. let ri = self.s.m.bin(c, Bin::LShr, lane, four);
  6852. let ri = self.s.m.bin(c, Bin::And, ri, three);
  6853. let bi = self.s.m.bin(c, Bin::LShr, lane, two);
  6854. let bi = self.s.m.bin(c, Bin::And, bi, three);
  6855. let (rm, bm) = (k(self, u32::from(rows)), k(self, u32::from(banks)));
  6856. let rb = self.s.m.bin(c, Bin::LShr, rm, ri);
  6857. let bb = self.s.m.bin(c, Bin::LShr, bm, bi);
  6858. let both = self.s.m.bin(c, Bin::And, rb, bb);
  6859. let (one, z) = (k(self, 1), k(self, 0));
  6860. let both = self.s.m.bin(c, Bin::And, both, one);
  6861. let on = self.s.m.cmp(c, pred::NE, both, z);
  6862. enable = Some(match enable {
  6863. Some(e) => self.s.m.bin(c, Bin::And, e, on),
  6864. None => on,
  6865. });
  6866. }
  6867. Ok((r, enable))
  6868. }
  6869. fn valu_op(&mut self, inst: &Inst, guard: Option<V>) -> Result<(), Why> {
  6870. let Fields::Valu(v) = &inst.fields else {
  6871. unreachable!()
  6872. };
  6873. let name = inst.name();
  6874. let c = self.cur;
  6875. let f = |l: &mut Self, k| l.fsrc(inst, k);
  6876. let s = |l: &mut Self, k| l.src(inst, k);
  6877. let float = |l: &mut Self, r: V| l.write_f(inst, r, guard);
  6878. let int = |l: &mut Self, r: V| l.write_i(inst, r, guard);
  6879. if let Some(r) = self.valu16(inst, name, guard) {
  6880. return r;
  6881. }
  6882. if let Some(op) = name.strip_prefix("v_pk_") {
  6883. return self.packed16(inst, op, guard);
  6884. }
  6885. match name {
  6886. "v_mad_u64_u32" => {
  6887. // a * b + c, c and the result 64 bits wide; the carry out
  6888. // of the sum is this lane's bit of the mask it names.
  6889. let (a, b) = (s(self, 0)?, s(self, 1)?);
  6890. let x = self.src64(inst, 2)?;
  6891. let i64t = self.s.m.int(64);
  6892. self.s.flags |= flags::INT64;
  6893. let a = self.s.m.cast(c, Cast::ZExt, a, i64t);
  6894. let b = self.s.m.cast(c, Cast::ZExt, b, i64t);
  6895. let product = self.s.m.bin(c, Bin::Mul, a, b);
  6896. let r = self.s.m.bin(c, Bin::Add, product, x);
  6897. let carry = self.s.m.cmp(c, pred::IULT, r, x);
  6898. let Some(Operand::Vector { reg, .. }) = v.dst else {
  6899. return Err("a 64-bit result");
  6900. };
  6901. let (lo, hi) = self.split64(r);
  6902. self.write(inst, Reg::V(reg), lo, guard);
  6903. self.write(inst, Reg::V(reg + 1), hi, guard);
  6904. if let Some(Operand::Scalar { code, .. }) = v.carry
  6905. && let Some(w) = inst.write(Reg::S(code))
  6906. {
  6907. self.lane_bits.insert(w, carry);
  6908. }
  6909. for &(_, w) in &inst.writes {
  6910. self.vals
  6911. .entry(w)
  6912. .or_insert(Val::Missing("a lane mask read as data"));
  6913. }
  6914. Ok(())
  6915. }
  6916. "v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => {
  6917. let n = s(self, 0)?;
  6918. let x = self.src64(inst, 1)?;
  6919. let i64t = self.s.m.int(64);
  6920. let k63 = self.s.m.i32(63);
  6921. let n = self.s.m.bin(c, Bin::And, n, k63);
  6922. let n = self.s.m.cast(c, Cast::ZExt, n, i64t);
  6923. let op = match name {
  6924. "v_lshlrev_b64" => Bin::Shl,
  6925. "v_lshrrev_b64" => Bin::LShr,
  6926. _ => Bin::AShr,
  6927. };
  6928. let r = self.s.m.bin(c, op, x, n);
  6929. let Some(Operand::Vector { reg, .. }) = v.dst else {
  6930. return Err("a 64-bit result");
  6931. };
  6932. let (lo, hi) = self.split64(r);
  6933. self.write(inst, Reg::V(reg), lo, guard);
  6934. self.write(inst, Reg::V(reg + 1), hi, guard);
  6935. Ok(())
  6936. }
  6937. "v_cubeid_f32" | "v_cubesc_f32" | "v_cubetc_f32" | "v_cubema_f32" => {
  6938. // Cube-map face coordinates (AMD's ISA): the major axis is z
  6939. // when |z| >= |x| and |z| >= |y|, else y when |y| >= |x|,
  6940. // else x.
  6941. let (x, y, z) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  6942. let (ax, ay, az) = (self.unary(6, x), self.unary(6, y), self.unary(6, z));
  6943. let zx = self.s.m.cmp(c, pred::OGE, az, ax);
  6944. let zy = self.s.m.cmp(c, pred::OGE, az, ay);
  6945. let zmaj = self.s.m.bin(c, Bin::And, zx, zy);
  6946. let ymaj = self.s.m.cmp(c, pred::OGE, ay, ax);
  6947. let zero = self.s.m.f32(0);
  6948. let neg = |l: &mut Self, v: V| l.s.m.cmp(c, pred::OLT, v, zero);
  6949. let minus = |l: &mut Self, v: V| {
  6950. let z = l.s.m.f32(0x8000_0000);
  6951. l.s.m.bin(c, Bin::Sub, z, v)
  6952. };
  6953. let pick = |l: &mut Self, zv: V, yv: V, xv: V| {
  6954. let t = l.s.m.select(c, ymaj, yv, xv);
  6955. l.s.m.select(c, zmaj, zv, t)
  6956. };
  6957. let r = match name {
  6958. "v_cubeid_f32" => {
  6959. let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits());
  6960. let (nz, ny, nx) = (neg(self, z), neg(self, y), neg(self, x));
  6961. let (f5, f4, f3, f2, f1, f0) = (
  6962. k(self, 5.0),
  6963. k(self, 4.0),
  6964. k(self, 3.0),
  6965. k(self, 2.0),
  6966. k(self, 1.0),
  6967. k(self, 0.0),
  6968. );
  6969. let zf = self.s.m.select(c, nz, f5, f4);
  6970. let yf = self.s.m.select(c, ny, f3, f2);
  6971. let xf = self.s.m.select(c, nx, f1, f0);
  6972. pick(self, zf, yf, xf)
  6973. }
  6974. "v_cubesc_f32" => {
  6975. let (nz, nx) = (neg(self, z), neg(self, x));
  6976. let (mx, mz) = (minus(self, x), minus(self, z));
  6977. let zf = self.s.m.select(c, nz, mx, x);
  6978. let xf = self.s.m.select(c, nx, z, mz);
  6979. pick(self, zf, x, xf)
  6980. }
  6981. "v_cubetc_f32" => {
  6982. let ny = neg(self, y);
  6983. let (my, mz) = (minus(self, y), minus(self, z));
  6984. let yf = self.s.m.select(c, ny, mz, z);
  6985. pick(self, my, yf, my)
  6986. }
  6987. _ => {
  6988. let t = pick(self, z, y, x);
  6989. let two = self.s.m.f32(2.0f32.to_bits());
  6990. self.s.m.bin(c, Bin::Mul, t, two)
  6991. }
  6992. };
  6993. float(self, r)
  6994. }
  6995. "v_movrels_b32" | "v_movreld_b32" | "v_movrelsd_b32" => {
  6996. // M0 indexes the source (movrels), the destination (movreld)
  6997. // or both, from the encoded register up to the program's
  6998. // VGPR count (the registers the instruction reads or writes).
  6999. let m0 = self.i32_of(inst.read(Reg::S(crate::ir::M0)).ok_or("M0")?)?;
  7000. let (
  7001. Some(&Operand::Vector { reg: sreg, .. }),
  7002. Some(Operand::Vector { reg: dreg, .. }),
  7003. ) = (v.src.first(), v.dst)
  7004. else {
  7005. return Err("an M0-relative move");
  7006. };
  7007. let indexed_src = name != "v_movreld_b32";
  7008. let value = if indexed_src {
  7009. let mut r = self.s.m.i32(0);
  7010. for k in 0..=255u8.saturating_sub(sreg) {
  7011. let Some(x) = inst.read(Reg::V(sreg + k)) else {
  7012. break;
  7013. };
  7014. let x = self.i32_of(x)?;
  7015. let kk = self.s.m.i32(u32::from(k));
  7016. let is = self.s.m.cmp(c, pred::EQ, m0, kk);
  7017. r = self.s.m.select(c, is, x, r);
  7018. }
  7019. r
  7020. } else {
  7021. s(self, 0)?
  7022. };
  7023. if name == "v_movrels_b32" {
  7024. return int(self, value);
  7025. }
  7026. for k in 0..=255u8.saturating_sub(dreg) {
  7027. let Some(_) = inst.write(Reg::V(dreg + k)) else {
  7028. break;
  7029. };
  7030. let old = match inst.read(Reg::V(dreg + k)) {
  7031. Some(o) => self.i32_of(o)?,
  7032. None => self.s.m.i32(0),
  7033. };
  7034. let kk = self.s.m.i32(u32::from(k));
  7035. let is = self.s.m.cmp(c, pred::EQ, m0, kk);
  7036. let x = self.s.m.select(c, is, value, old);
  7037. self.write_placed(inst, Reg::V(dreg + k), x, guard);
  7038. }
  7039. Ok(())
  7040. }
  7041. "v_swap_b32" => {
  7042. let (
  7043. Some(&Operand::Vector { reg: sreg, .. }),
  7044. Some(Operand::Vector { reg: dreg, .. }),
  7045. ) = (v.src.first(), v.dst)
  7046. else {
  7047. return Err("v_swap_b32");
  7048. };
  7049. let a = self.i32_of(inst.read(Reg::V(dreg)).ok_or("v_swap_b32")?)?;
  7050. let b = self.i32_of(inst.read(Reg::V(sreg)).ok_or("v_swap_b32")?)?;
  7051. self.write_placed(inst, Reg::V(dreg), b, guard);
  7052. if dreg != sreg {
  7053. self.write_placed(inst, Reg::V(sreg), a, guard);
  7054. }
  7055. Ok(())
  7056. }
  7057. "v_ffbh_u32" | "v_ffbh_i32" => {
  7058. // Counted from the top bit, -1 when none (DXIL's too).
  7059. let a = s(self, 0)?;
  7060. let op = if name == "v_ffbh_u32" { 33 } else { 34 };
  7061. let r = self
  7062. .s
  7063. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  7064. int(self, r)
  7065. }
  7066. "v_dot4c_i32_i8" => {
  7067. // D += the dot product of four signed bytes, wrapping: DXIL's
  7068. // Dot4AddI8Packed.
  7069. let (a, bb) = (s(self, 0)?, s(self, 1)?);
  7070. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7071. return Err("an accumulator");
  7072. };
  7073. let acc = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?;
  7074. let i32_ty = self.s.t.i32;
  7075. let r = self.s.op(
  7076. c,
  7077. "dot4AddPacked.i32",
  7078. Attr::ReadNone,
  7079. i32_ty,
  7080. 163,
  7081. &[acc, a, bb],
  7082. );
  7083. int(self, r)
  7084. }
  7085. "v_dot4_i32_i8" => {
  7086. // VOP3P: op_sel picks the half each multiplicand's low half
  7087. // reads, op_sel_hi its high half's; the accumulator is read
  7088. // whole (as AMD's compilers fold constants into it).
  7089. if v.clamp || v.neg_hi != 0 {
  7090. return Err("a saturating or negated dot product");
  7091. }
  7092. let mut xs = Vec::new();
  7093. for k in 0..2 {
  7094. let x = s(self, k)?;
  7095. let (lo, hi) = (v.opsel >> k & 1 != 0, v.opsel_hi >> k & 1 != 0);
  7096. if (lo, hi) == (false, true) {
  7097. xs.push(x);
  7098. continue;
  7099. }
  7100. let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
  7101. let top = self.s.m.bin(c, Bin::LShr, x, k16);
  7102. let bottom = self.s.m.bin(c, Bin::And, x, low);
  7103. let hi = self
  7104. .s
  7105. .m
  7106. .bin(c, Bin::Shl, if hi { top } else { bottom }, k16);
  7107. xs.push(self.s.m.bin(c, Bin::Or, if lo { top } else { bottom }, hi));
  7108. }
  7109. let acc = s(self, 2)?;
  7110. let i32_ty = self.s.t.i32;
  7111. let r = self.s.op(
  7112. c,
  7113. "dot4AddPacked.i32",
  7114. Attr::ReadNone,
  7115. i32_ty,
  7116. 163,
  7117. &[acc, xs[0], xs[1]],
  7118. );
  7119. int(self, r)
  7120. }
  7121. "v_mov_b32" => {
  7122. if v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 {
  7123. let a = f(self, 0)?;
  7124. return float(self, a);
  7125. }
  7126. let a = s(self, 0)?;
  7127. int(self, a)
  7128. }
  7129. "v_add_f32" | "v_sub_f32" | "v_subrev_f32" | "v_mul_f32" | "v_mul_legacy_f32"
  7130. | "v_max_f32" | "v_min_f32" => {
  7131. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  7132. let r = match name {
  7133. "v_add_f32" => self.s.m.bin(c, Bin::Add, a, bb),
  7134. "v_sub_f32" => self.s.m.bin(c, Bin::Sub, a, bb),
  7135. "v_subrev_f32" => self.s.m.bin(c, Bin::Sub, bb, a),
  7136. "v_mul_f32" => self.s.m.bin(c, Bin::Mul, a, bb),
  7137. "v_mul_legacy_f32" => self.legacy_mul(a, bb),
  7138. "v_max_f32" => self.max_min(true, a, bb),
  7139. _ => self.max_min(false, a, bb),
  7140. };
  7141. float(self, r)
  7142. }
  7143. "v_fma_f32" | "v_fmaak_f32" | "v_fmamk_f32" => {
  7144. // shortcut: DXIL has no fused f32 multiply-add; FMad lets the driver fuse.
  7145. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7146. let r = self.fmad(a, bb, cc);
  7147. float(self, r)
  7148. }
  7149. "v_div_scale_f32" => {
  7150. // RDNA2 ISA: src0 = value to scale, src1 = denominator, src2 = numerator.
  7151. let (a, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7152. let (ai, ni, di) = (self.as_int(a), self.as_int(num), self.as_int(den));
  7153. let (k23, k255, kabs) = (
  7154. self.s.m.i32(23),
  7155. self.s.m.i32(0xFF),
  7156. self.s.m.i32(0x7FFF_FFFF),
  7157. );
  7158. let (zero, k23_exp, k232_exp, k96) = (
  7159. self.s.m.i32(0),
  7160. self.s.m.i32(23),
  7161. self.s.m.i32(232),
  7162. self.s.m.i32(96),
  7163. );
  7164. let exp_of = |l: &mut Self, x: V| {
  7165. let s = l.s.m.bin(c, Bin::LShr, x, k23);
  7166. l.s.m.bin(c, Bin::And, s, k255)
  7167. };
  7168. let (e1, e2) = (exp_of(self, ni), exp_of(self, di));
  7169. let n_abs = self.s.m.bin(c, Bin::And, ni, kabs);
  7170. let d_abs = self.s.m.bin(c, Bin::And, di, kabs);
  7171. let z1 = self.s.m.cmp(c, pred::EQ, n_abs, zero);
  7172. let z2 = self.s.m.cmp(c, pred::EQ, d_abs, zero);
  7173. let any_zero = self.s.m.bin(c, Bin::Or, z1, z2);
  7174. let special = {
  7175. let s1 = self.s.m.cmp(c, pred::EQ, e1, k255);
  7176. let s2 = self.s.m.cmp(c, pred::EQ, e2, k255);
  7177. let a12 = self.s.m.bin(c, Bin::Or, s1, s2);
  7178. self.s.m.bin(c, Bin::Or, a12, any_zero)
  7179. };
  7180. let is_den = self.s.m.cmp(c, pred::EQ, ai, di);
  7181. let diff = self.s.m.bin(c, Bin::Sub, e2, e1);
  7182. let den_tiny = self.s.m.cmp(c, pred::IULE, e2, k23_exp);
  7183. let den_huge = self.s.m.cmp(c, pred::IUGE, e2, k232_exp);
  7184. let num_tiny_exp = self.s.m.cmp(c, pred::IULE, e1, k23_exp);
  7185. let num_huge = self.s.m.cmp(c, pred::IUGE, e1, k232_exp);
  7186. let num_gap = self.s.m.cmp(c, pred::SGE, diff, k96);
  7187. let not_den_huge = {
  7188. let t = self.s.m.bool(true);
  7189. self.s.m.bin(c, Bin::Xor, den_huge, t)
  7190. };
  7191. let num_gap = self.s.m.bin(c, Bin::And, num_gap, not_den_huge);
  7192. let num_tiny = self.s.m.bin(c, Bin::Or, num_tiny_exp, num_gap);
  7193. let up_raw = self.s.m.select(c, is_den, den_tiny, num_tiny);
  7194. let dn_raw = self.s.m.select(c, is_den, den_huge, num_huge);
  7195. let not_special = {
  7196. let t = self.s.m.bool(true);
  7197. self.s.m.bin(c, Bin::Xor, special, t)
  7198. };
  7199. let up = self.s.m.bin(c, Bin::And, up_raw, not_special);
  7200. let dn = self.s.m.bin(c, Bin::And, dn_raw, not_special);
  7201. let uncancelled = {
  7202. let x_tiny = self.s.m.bin(c, Bin::Xor, den_tiny, num_tiny);
  7203. let x_huge = self.s.m.bin(c, Bin::Xor, den_huge, num_huge);
  7204. self.s.m.bin(c, Bin::Or, x_tiny, x_huge)
  7205. };
  7206. let flag_raw = self.s.m.select(c, is_den, uncancelled, up_raw);
  7207. let flag = self.s.m.bin(c, Bin::And, flag_raw, not_special);
  7208. let k_up = self.s.m.f32(0x5F80_0000);
  7209. let k_dn = self.s.m.f32(0x1F80_0000);
  7210. let a_up = self.s.m.bin(c, Bin::Mul, a, k_up);
  7211. let a_dn = self.s.m.bin(c, Bin::Mul, a, k_dn);
  7212. let r = self.s.m.select(c, dn, a_dn, a);
  7213. let r = self.s.m.select(c, up, a_up, r);
  7214. let qnan = self.s.m.f32(0x7FC0_0000);
  7215. let r = self.s.m.select(c, any_zero, qnan, r);
  7216. float(self, r)?;
  7217. if let Some(Operand::Scalar { code, .. }) = v.carry
  7218. && let Some(w) = inst.write(Reg::S(code))
  7219. {
  7220. self.lane_bits.insert(w, flag);
  7221. }
  7222. for &(_, w) in &inst.writes {
  7223. self.vals
  7224. .entry(w)
  7225. .or_insert(Val::Missing("a lane mask read as data"));
  7226. }
  7227. Ok(())
  7228. }
  7229. "v_div_fmas_f32" => {
  7230. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7231. let m = inst
  7232. .read(Reg::S(crate::ir::VCC))
  7233. .and_then(|v| self.x.st.masks.get(&v).copied())
  7234. .ok_or("v_div_fmas_f32 without VCC")?;
  7235. let vcc = self.boolean(m, c)?;
  7236. let tmp = self.fmad(a, bb, cc);
  7237. let ci = self.as_int(cc);
  7238. let (k23, k255, k128) = (self.s.m.i32(23), self.s.m.i32(0xFF), self.s.m.i32(128));
  7239. let sh = self.s.m.bin(c, Bin::LShr, ci, k23);
  7240. let exp = self.s.m.bin(c, Bin::And, sh, k255);
  7241. let exp_ge = self.s.m.cmp(c, pred::IUGE, exp, k128);
  7242. let (k_up, k_dn) = (self.s.m.f32(0x5F80_0000), self.s.m.f32(0x1F80_0000));
  7243. let scale = self.s.m.select(c, exp_ge, k_up, k_dn);
  7244. let scaled = self.s.m.bin(c, Bin::Mul, tmp, scale);
  7245. let r = self.s.m.select(c, vcc, scaled, tmp);
  7246. float(self, r)
  7247. }
  7248. "v_div_fixup_f32" => {
  7249. let (q, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7250. let (qi, di, ni) = (self.as_int(q), self.as_int(den), self.as_int(num));
  7251. let (ksign, kabs, kinf) = (
  7252. self.s.m.i32(0x8000_0000),
  7253. self.s.m.i32(0x7FFF_FFFF),
  7254. self.s.m.i32(0x7F80_0000),
  7255. );
  7256. let (kqnan_bit, kneg_qnan, zero) = (
  7257. self.s.m.i32(0x0040_0000),
  7258. self.s.m.i32(0xFFC0_0000),
  7259. self.s.m.i32(0),
  7260. );
  7261. let sign = {
  7262. let x = self.s.m.bin(c, Bin::Xor, ni, di);
  7263. self.s.m.bin(c, Bin::And, x, ksign)
  7264. };
  7265. let q_abs = self.s.m.bin(c, Bin::And, qi, kabs);
  7266. let d_abs = self.s.m.bin(c, Bin::And, di, kabs);
  7267. let n_abs = self.s.m.bin(c, Bin::And, ni, kabs);
  7268. let q_nan = self.s.m.cmp(c, pred::IUGT, q_abs, kinf);
  7269. let d_nan = self.s.m.cmp(c, pred::IUGT, d_abs, kinf);
  7270. let n_nan = self.s.m.cmp(c, pred::IUGT, n_abs, kinf);
  7271. let d_inf = self.s.m.cmp(c, pred::EQ, d_abs, kinf);
  7272. let n_inf = self.s.m.cmp(c, pred::EQ, n_abs, kinf);
  7273. let d_zero = self.s.m.cmp(c, pred::EQ, d_abs, zero);
  7274. let n_zero = self.s.m.cmp(c, pred::EQ, n_abs, zero);
  7275. let both_inf = self.s.m.bin(c, Bin::And, n_inf, d_inf);
  7276. let both_zero = self.s.m.bin(c, Bin::And, n_zero, d_zero);
  7277. let invalid = self.s.m.bin(c, Bin::Or, both_inf, both_zero);
  7278. let make_inf = {
  7279. let t = self.s.m.bin(c, Bin::Or, n_inf, d_zero);
  7280. self.s.m.bin(c, Bin::Or, t, q_nan)
  7281. };
  7282. let make_zero = self.s.m.bin(c, Bin::Or, d_inf, n_zero);
  7283. let signed_q = self.s.m.bin(c, Bin::Or, sign, q_abs);
  7284. let signed_inf = self.s.m.bin(c, Bin::Or, sign, kinf);
  7285. let n_qnan = self.s.m.bin(c, Bin::Or, ni, kqnan_bit);
  7286. let d_qnan = self.s.m.bin(c, Bin::Or, di, kqnan_bit);
  7287. let r = self.s.m.select(c, make_zero, sign, signed_q);
  7288. let r = self.s.m.select(c, make_inf, signed_inf, r);
  7289. let r = self.s.m.select(c, invalid, kneg_qnan, r);
  7290. let r = self.s.m.select(c, d_nan, d_qnan, r);
  7291. let r = self.s.m.select(c, n_nan, n_qnan, r);
  7292. let rf = self.as_float(r);
  7293. float(self, rf)
  7294. }
  7295. "v_fmac_f32" | "v_mac_f32" | "v_mac_legacy_f32" => {
  7296. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  7297. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7298. return Err("an accumulator");
  7299. };
  7300. let acc = inst.read(Reg::V(reg)).ok_or("an accumulator")?;
  7301. let acc = match self.floats.get(&acc) {
  7302. Some(&x) => x,
  7303. None => {
  7304. let x = self.i32_of(acc)?;
  7305. self.as_float(x)
  7306. }
  7307. };
  7308. let r = match name {
  7309. "v_fmac_f32" => self.fmad(a, bb, acc),
  7310. "v_mac_f32" => {
  7311. let m = self.s.m.bin(c, Bin::Mul, a, bb);
  7312. self.s.m.bin(c, Bin::Add, m, acc)
  7313. }
  7314. _ => {
  7315. let m = self.legacy_mul(a, bb);
  7316. self.s.m.bin(c, Bin::Add, m, acc)
  7317. }
  7318. };
  7319. float(self, r)
  7320. }
  7321. "v_mad_f32" | "v_madak_f32" | "v_madmk_f32" | "v_mad_legacy_f32" => {
  7322. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7323. let m = if name == "v_mad_legacy_f32" {
  7324. self.legacy_mul(a, bb)
  7325. } else {
  7326. self.s.m.bin(c, Bin::Mul, a, bb)
  7327. };
  7328. let r = self.s.m.bin(c, Bin::Add, m, cc);
  7329. float(self, r)
  7330. }
  7331. "v_max3_f32" | "v_min3_f32" | "v_med3_f32" => {
  7332. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  7333. let r = match name {
  7334. "v_max3_f32" => {
  7335. let t = self.max_min(true, a, bb);
  7336. self.max_min(true, t, cc)
  7337. }
  7338. "v_min3_f32" => {
  7339. let t = self.max_min(false, a, bb);
  7340. self.max_min(false, t, cc)
  7341. }
  7342. _ => self.med3(a, bb, cc),
  7343. };
  7344. float(self, r)
  7345. }
  7346. "v_rcp_f32" | "v_rcp_iflag_f32" => {
  7347. // shortcut: the hardware reciprocal is approximate (1 ULP); this divides.
  7348. let a = f(self, 0)?;
  7349. let one = self.s.m.f32(1.0f32.to_bits());
  7350. let r = self.s.m.bin(c, Bin::SDiv, one, a);
  7351. float(self, r)
  7352. }
  7353. "v_rsq_f32" | "v_sqrt_f32" | "v_log_f32" | "v_exp_f32" | "v_fract_f32"
  7354. | "v_trunc_f32" | "v_floor_f32" | "v_ceil_f32" | "v_rndne_f32" | "v_sin_f32"
  7355. | "v_cos_f32" => {
  7356. let a = f(self, 0)?;
  7357. let op = match name {
  7358. "v_rsq_f32" => 25,
  7359. "v_sqrt_f32" => 24,
  7360. "v_log_f32" => 23,
  7361. "v_exp_f32" => 21,
  7362. "v_fract_f32" => 22,
  7363. "v_trunc_f32" => 29,
  7364. "v_floor_f32" => 27,
  7365. "v_ceil_f32" => 28,
  7366. "v_rndne_f32" => 26,
  7367. "v_sin_f32" => 13,
  7368. _ => 12,
  7369. };
  7370. let r = match op {
  7371. 12 | 13 => self.trig_turns(a, op == 12),
  7372. 22 => self.fract(a, 1.0, f32::from_bits(0x3F7F_FFFF)),
  7373. _ => self.unary(op, a),
  7374. };
  7375. float(self, r)
  7376. }
  7377. "v_cvt_i32_f32" | "v_cvt_u32_f32" | "v_cvt_flr_i32_f32" | "v_cvt_rpi_i32_f32" => {
  7378. let mut a = f(self, 0)?;
  7379. if name == "v_cvt_rpi_i32_f32" {
  7380. let h = self.s.m.f32(0.5f32.to_bits());
  7381. a = self.s.m.bin(c, Bin::Add, a, h);
  7382. }
  7383. if name != "v_cvt_i32_f32" && name != "v_cvt_u32_f32" {
  7384. a = self.unary(27, a);
  7385. }
  7386. // D3D's conversions saturate and give 0 for NaN, as the
  7387. // hardware does (checked on the RX 6700 XT and WARP).
  7388. let op = if name == "v_cvt_u32_f32" {
  7389. Cast::FpToUi
  7390. } else {
  7391. Cast::FpToSi
  7392. };
  7393. let r = self.s.m.cast(c, op, a, self.s.t.i32);
  7394. int(self, r)
  7395. }
  7396. "v_cvt_f32_f64" => {
  7397. let (lo, hi) = self.f64_pair(inst, 0)?;
  7398. let bits = self.f64_to_f32_bits(lo, hi);
  7399. let r = self.as_float(bits);
  7400. float(self, r)
  7401. }
  7402. "v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1"
  7403. | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => {
  7404. let mut a = s(self, 0)?;
  7405. if let Some(n) = name.strip_prefix("v_cvt_f32_ubyte") {
  7406. let sh = self.s.m.i32(8 * u32::from(n.as_bytes()[0] - b'0'));
  7407. let ff = self.s.m.i32(0xff);
  7408. a = self.s.m.bin(c, Bin::LShr, a, sh);
  7409. a = self.s.m.bin(c, Bin::And, a, ff);
  7410. }
  7411. let op = if name == "v_cvt_f32_i32" {
  7412. Cast::SiToFp
  7413. } else {
  7414. Cast::UiToFp
  7415. };
  7416. let r = self.s.m.cast(c, op, a, self.s.t.f32);
  7417. float(self, r)
  7418. }
  7419. "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => {
  7420. // Each source is f32, or with op_sel_hi the low (op_sel: high)
  7421. // f16 half; neg_hi is the absolute value here.
  7422. let mut xs = Vec::new();
  7423. for i in 0..3 {
  7424. let op = v.src.get(i).ok_or("a missing operand")?;
  7425. let mut x = if v.opsel_hi >> i & 1 != 0 {
  7426. let x = self.f16_operand(inst, op)?;
  7427. let h = if v.opsel >> i & 1 != 0 {
  7428. let k16 = self.s.m.i32(16);
  7429. self.s.m.bin(c, Bin::LShr, x, k16)
  7430. } else {
  7431. x
  7432. };
  7433. self.s
  7434. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h])
  7435. } else {
  7436. let x = self.operand(inst, op)?;
  7437. self.as_float(x)
  7438. };
  7439. if v.neg_hi >> i & 1 != 0 {
  7440. x = self.unary(6, x);
  7441. }
  7442. if v.neg >> i & 1 != 0 {
  7443. let z = self.s.m.f32(0x8000_0000);
  7444. x = self.s.m.bin(c, Bin::Sub, z, x);
  7445. }
  7446. xs.push(x);
  7447. }
  7448. let mut r = self.fmad(xs[0], xs[1], xs[2]);
  7449. if name == "v_fma_mix_f32" {
  7450. return float(self, r);
  7451. }
  7452. if v.clamp {
  7453. r = self.unary(7, r);
  7454. }
  7455. // The f16 result goes to one half; the other half stays.
  7456. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7457. return Err("a mixed-precision result");
  7458. };
  7459. let old = match inst.read(Reg::V(reg)) {
  7460. Some(o) => self.i32_of(o)?,
  7461. None => self.s.m.i32(0),
  7462. };
  7463. let h = self
  7464. .s
  7465. .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[r]);
  7466. let (keep, h) = if name == "v_fma_mixhi_f16" {
  7467. let k16 = self.s.m.i32(16);
  7468. (0xFFFF, self.s.m.bin(c, Bin::Shl, h, k16))
  7469. } else {
  7470. (0xFFFF_0000, h)
  7471. };
  7472. let keep = self.s.m.i32(keep);
  7473. let old = self.s.m.bin(c, Bin::And, old, keep);
  7474. let x = self.s.m.bin(c, Bin::Or, old, h);
  7475. self.write(inst, Reg::V(reg), x, guard);
  7476. Ok(())
  7477. }
  7478. "v_cvt_pkrtz_f16_f32" => {
  7479. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  7480. let lo = self.f16_toward_zero(a);
  7481. let hi = self.f16_toward_zero(bb);
  7482. let sh = self.s.m.i32(16);
  7483. let hi = self.s.m.bin(c, Bin::Shl, hi, sh);
  7484. let r = self.s.m.bin(c, Bin::Or, lo, hi);
  7485. int(self, r)
  7486. }
  7487. "v_cvt_f16_f32" if v.opsel == 0 => {
  7488. // Rounded to nearest even (the MODE default) into the low half.
  7489. let a = f(self, 0)?;
  7490. let r = self
  7491. .s
  7492. .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[a]);
  7493. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7494. return Err("a 16-bit result outside a VGPR");
  7495. };
  7496. let r = self.low_half(inst, reg, r);
  7497. int(self, r)
  7498. }
  7499. "v_pack_b32_f16" => {
  7500. // Two f16 sources (op_sel: their high halves; abs and neg on
  7501. // the sign bit) into the low and high half.
  7502. let mut halves = Vec::new();
  7503. for k in 0..2 {
  7504. let op = v.src.get(k).ok_or("a missing operand")?;
  7505. let mut x = self.f16_operand(inst, op)?;
  7506. if v.opsel >> k & 1 != 0 {
  7507. let k16 = self.s.m.i32(16);
  7508. x = self.s.m.bin(c, Bin::LShr, x, k16);
  7509. }
  7510. let mask = if v.abs >> k & 1 != 0 { 0x7FFF } else { 0xFFFF };
  7511. let mask = self.s.m.i32(mask);
  7512. x = self.s.m.bin(c, Bin::And, x, mask);
  7513. if v.neg >> k & 1 != 0 {
  7514. let sign = self.s.m.i32(0x8000);
  7515. x = self.s.m.bin(c, Bin::Xor, x, sign);
  7516. }
  7517. halves.push(x);
  7518. }
  7519. let k16 = self.s.m.i32(16);
  7520. let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16);
  7521. let r = self.s.m.bin(c, Bin::Or, halves[0], hi);
  7522. int(self, r)
  7523. }
  7524. "v_cvt_f32_f16" if v.opsel == 0 => {
  7525. let a = s(self, 0)?;
  7526. let r = self
  7527. .s
  7528. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[a]);
  7529. float(self, r)
  7530. }
  7531. "v_cndmask_b32" => {
  7532. let mask = match v.src.get(2) {
  7533. Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
  7534. _ => None,
  7535. };
  7536. const UNTRACKED: Why = "a select on an untracked mask";
  7537. let cond = match mask.and_then(|m| self.x.st.masks.get(&m).copied()) {
  7538. Some(m) => self.boolean(m, c)?,
  7539. // A mask the code holds as a number (a constant bit
  7540. // pattern: every other lane, every other pair...):
  7541. // this lane's bit of it. Exact where host lanes are
  7542. // the console's.
  7543. None if self.mask_data == MaskData::Console => {
  7544. // Each host wave taken as a wave of its own has no
  7545. // console lane numbers to pick the bits by.
  7546. if self.local {
  7547. return Err("a constant lane mask in a half-wave");
  7548. }
  7549. let m = mask.ok_or(UNTRACKED)?;
  7550. let lo = self.i32_of(m).map_err(|_| UNTRACKED)?;
  7551. // wave64: the register after it holds lanes 32-63.
  7552. let high = match v.src.get(2) {
  7553. Some(&Operand::Scalar { code, .. }) if self.x.native.wave64 => {
  7554. Some(inst.read(Reg::S(code + 1)).ok_or(UNTRACKED)?)
  7555. }
  7556. _ => None,
  7557. };
  7558. let hi = match high {
  7559. Some(h) => Some(self.i32_of(h).map_err(|_| UNTRACKED)?),
  7560. None => None,
  7561. };
  7562. self.cross_lane(false)?;
  7563. self.lane_bit(c, lo, hi)
  7564. }
  7565. None => return Err(UNTRACKED),
  7566. };
  7567. if v.abs != 0 || v.neg != 0 {
  7568. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  7569. let r = self.s.m.select(c, cond, bb, a);
  7570. return float(self, r);
  7571. }
  7572. let (a, bb) = (s(self, 0)?, s(self, 1)?);
  7573. let r = self.s.m.select(c, cond, bb, a);
  7574. int(self, r)
  7575. }
  7576. "v_add_co_u32" | "v_sub_co_u32" | "v_subrev_co_u32" | "v_add_co_ci_u32"
  7577. | "v_sub_co_ci_u32" | "v_subrev_co_ci_u32" => {
  7578. // The carry (borrow) out is a lane mask: this lane's bit.
  7579. let (mut a, mut bb) = (s(self, 0)?, s(self, 1)?);
  7580. if name.contains("subrev") {
  7581. std::mem::swap(&mut a, &mut bb);
  7582. }
  7583. let cin = if name.ends_with("_ci_u32") {
  7584. let m = match v.src.get(2) {
  7585. Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
  7586. _ => None,
  7587. };
  7588. let m = m
  7589. .and_then(|m| self.x.st.masks.get(&m).copied())
  7590. .ok_or("a carry-in from an untracked mask")?;
  7591. Some(self.boolean(m, c)?)
  7592. } else {
  7593. None
  7594. };
  7595. let (r, carry) = self.add_sub_carry(c, name.starts_with("v_add"), a, bb, cin);
  7596. int(self, r)?;
  7597. if let Some(Operand::Scalar { code, .. }) = v.carry
  7598. && let Some(w) = inst.write(Reg::S(code))
  7599. {
  7600. self.lane_bits.insert(w, carry);
  7601. }
  7602. for &(_, w) in &inst.writes {
  7603. self.vals
  7604. .entry(w)
  7605. .or_insert(Val::Missing("a lane mask read as data"));
  7606. }
  7607. Ok(())
  7608. }
  7609. "v_permlane16_b32" | "v_permlanex16_b32" => {
  7610. // RDNA2 ISA 12.12: each nibble of {src2, src1} selects a lane
  7611. // in this row of 16, or the other row of the same 32-lane half.
  7612. // OP_SEL[0:1] are fetch-inactive and bound-control, not half selects.
  7613. if v.abs != 0 || v.neg != 0 || v.opsel & !3 != 0 {
  7614. return Err("permlane input modifiers");
  7615. }
  7616. self.cross_lane(false)?;
  7617. let fetch_inactive = v.opsel & 1 != 0;
  7618. if fetch_inactive
  7619. && !all_lane_blocks(self.x.st).is_some_and(|all| all[self.cur_ir])
  7620. {
  7621. // DXIL cannot read the last VGPR value of a host invocation
  7622. // that has left through a lane branch. A guard keeps it here.
  7623. return Err("a permlane fetch from lanes outside the host branch");
  7624. }
  7625. let (x, lo, hi) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  7626. let lane = self.lane_index();
  7627. let (k7, k8, k15, k16, k31, k32, k4, one, zero) = (
  7628. self.s.m.i32(7),
  7629. self.s.m.i32(8),
  7630. self.s.m.i32(15),
  7631. self.s.m.i32(16),
  7632. self.s.m.i32(31),
  7633. self.s.m.i32(32),
  7634. self.s.m.i32(4),
  7635. self.s.m.i32(1),
  7636. self.s.m.i32(0),
  7637. );
  7638. let pos = self.s.m.bin(c, Bin::And, lane, k15);
  7639. let lower = self.s.m.cmp(c, pred::IULT, pos, k8);
  7640. let packed = self.s.m.select(c, lower, lo, hi);
  7641. let shift = self.s.m.bin(c, Bin::And, pos, k7);
  7642. let shift = self.s.m.bin(c, Bin::Mul, shift, k4);
  7643. let pick = self.s.m.bin(c, Bin::LShr, packed, shift);
  7644. let pick = self.s.m.bin(c, Bin::And, pick, k15);
  7645. let not15 = self.s.m.i32(!15);
  7646. let mut row = self.s.m.bin(c, Bin::And, lane, not15);
  7647. if name == "v_permlanex16_b32" {
  7648. row = self.s.m.bin(c, Bin::Xor, row, k16);
  7649. }
  7650. let src = self.s.m.bin(c, Bin::Or, row, pick);
  7651. let r = if fetch_inactive {
  7652. self.read_lane(x, src)
  7653. } else {
  7654. // Ballot the console EXEC guard as well as the host's active
  7655. // invocations. Never shuffle from an inactive host lane.
  7656. let enabled = guard.unwrap_or_else(|| self.s.m.bool(true));
  7657. let i32t = self.s.t.i32;
  7658. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  7659. let mask = self.s.op(
  7660. c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[enabled],
  7661. );
  7662. let lo = self.s.m.extract(c, mask, 0);
  7663. let hi = self.s.m.extract(c, mask, 1);
  7664. let lower = self.s.m.cmp(c, pred::IULT, src, k32);
  7665. let word = self.s.m.select(c, lower, lo, hi);
  7666. let bit = self.s.m.bin(c, Bin::And, src, k31);
  7667. let bit = self.s.m.bin(c, Bin::LShr, word, bit);
  7668. let bit = self.s.m.bin(c, Bin::And, bit, one);
  7669. let active = self.s.m.cmp(c, pred::NE, bit, zero);
  7670. let safe = self.s.m.select(c, active, src, lane);
  7671. let read = self.read_lane(x, safe);
  7672. let fallback = if v.opsel & 2 != 0 {
  7673. zero
  7674. } else {
  7675. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7676. return Err("a permlane result outside a VGPR");
  7677. };
  7678. self.i32_of(inst.read(Reg::V(reg)).ok_or("a permlane old value")?)?
  7679. };
  7680. self.s.m.select(c, active, read, fallback)
  7681. };
  7682. int(self, r)
  7683. }
  7684. "v_readlane_b32" => {
  7685. let (a, lane) = (s(self, 0)?, s(self, 1)?);
  7686. // A computed lane in a pixel or vertex program is a host lane
  7687. // (from a mask or `v_mbcnt`); a constant one is the console's.
  7688. if self.mask_data == MaskData::Host && !matches!(lane, V::Const(_)) {
  7689. self.s.flags |= flags::WAVE_OPS;
  7690. } else {
  7691. self.cross_lane(false)?;
  7692. }
  7693. if let Some(slot) = self.exchange.as_ref().map(|e| e.0) {
  7694. if self.local && self.local_any {
  7695. // this host wave's lane of that number (lanes 32..63 are 0..31 here)
  7696. let k31 = self.s.m.i32(31);
  7697. let here = self.s.m.bin(self.cur, Bin::And, lane, k31);
  7698. let r = self.read_lane(a, here);
  7699. return int(self, r);
  7700. }
  7701. if self.local {
  7702. return Err("a lane read in a half-wave");
  7703. }
  7704. if self.exchange.as_ref().is_some_and(|e| e.1) {
  7705. // a group of 32 or fewer: the lane is in this host wave
  7706. let r = self.read_lane(a, lane);
  7707. return int(self, r);
  7708. }
  7709. // the lane that holds it may be in the other host wave: it gives it through LDS
  7710. if !self.all_lanes(self.cur_ir) {
  7711. need(self.cur_ir);
  7712. return Err("a lane read where not every lane runs");
  7713. }
  7714. let cl = self.console_lane();
  7715. let is = self.s.m.cmp(self.cur, pred::EQ, cl, lane);
  7716. let k = self.exchange_pair(slot);
  7717. let at = self.begin_guarded(Some(is));
  7718. let lds = self.s.lds();
  7719. let ptr = self.s.m.element(self.cur, lds, k);
  7720. self.s.m.store(self.cur, ptr, a);
  7721. self.end_guarded(at, &[]);
  7722. let c2 = self.cur;
  7723. self.group_sync(c2);
  7724. let ptr = self.s.m.element(c2, lds, k);
  7725. let r = self.s.m.load(c2, ptr);
  7726. self.group_sync(c2);
  7727. return int(self, r);
  7728. }
  7729. let r = self.read_lane(a, lane);
  7730. int(self, r)
  7731. }
  7732. "v_writelane_b32" => {
  7733. // The lane given takes the scalar; the others keep their value.
  7734. let (a, lane) = (s(self, 0)?, s(self, 1)?);
  7735. let Some(Operand::Vector { reg, .. }) = v.dst else {
  7736. return Err("a lane write");
  7737. };
  7738. let old = match inst.read(Reg::V(reg)) {
  7739. Some(o) => self.i32_of(o)?,
  7740. None => self.s.m.i32(0),
  7741. };
  7742. self.cross_lane(false)?;
  7743. if self.local && !self.local_any {
  7744. return Err("a lane write in a half-wave");
  7745. }
  7746. let me = self.console_lane();
  7747. let is = self.s.m.cmp(c, pred::EQ, me, lane);
  7748. let r = self.s.m.select(c, is, a, old);
  7749. int(self, r)
  7750. }
  7751. "v_readfirstlane_b32"
  7752. if inst
  7753. .writes
  7754. .first()
  7755. .is_some_and(|w| self.x.res.waterfall.reads.contains(&w.1)) =>
  7756. {
  7757. // A waterfall loop's read of a descriptor dword: the lane's own.
  7758. let a = s(self, 0)?;
  7759. int(self, a)
  7760. }
  7761. "v_readfirstlane_b32"
  7762. if matches!(v.src.first(), Some(&Operand::Vector { reg, .. })
  7763. if inst.read(Reg::V(reg)).is_some_and(|x| self.own_bits.alike.contains(&x))) =>
  7764. {
  7765. // The bits a loop over a wave OR has still to visit (`own_bits`): every lane of
  7766. // the host wave holds the same, so the first lane's is the lane's own.
  7767. let a = s(self, 0)?;
  7768. int(self, a)
  7769. }
  7770. "v_readfirstlane_b32" => {
  7771. let a = s(self, 0)?;
  7772. let (mine, any) = self.first_lane(a, guard);
  7773. // two host waves that exchange: the console's first lane may be in the other
  7774. // one, unless every lane holds the same value
  7775. let alike = match v.src.first() {
  7776. Some(&Operand::Vector { reg, .. }) => {
  7777. inst.read(Reg::V(reg)).is_some_and(|x| self.uniform.contains(&x))
  7778. }
  7779. _ => true,
  7780. };
  7781. let halves = self.exchange.as_ref().is_some_and(|e| !e.1) && !self.local;
  7782. let r = if halves && !alike {
  7783. if !self.all_lanes(self.cur_ir) {
  7784. // shortcut: `VICTORY_FIRSTLANE_OWN=1` takes the host wave's own
  7785. // first lane, exact when the value is the same in every lane of
  7786. // the console wave (the ray-tracing builder's scans read a sum of
  7787. // scalars this way, inside a loop whose exit is per console wave).
  7788. static OWN: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  7789. if *OWN.get_or_init(|| std::env::var_os("VICTORY_FIRSTLANE_OWN").is_some_and(|v| v == "1")) {
  7790. return int(self, mine);
  7791. }
  7792. need(self.cur_ir);
  7793. return Err("a first-lane read where not every lane runs");
  7794. }
  7795. let c = self.cur;
  7796. if guard.is_none() && super::shader_opt() & super::bitcode::opt::FIRST != 0 {
  7797. // Every lane is in EXEC: the console's first lane is
  7798. // lane 0, which the lower half of every console wave
  7799. // has. No half needs to ask the other whether it has
  7800. // a lane (an exchange of the constant 1: two group
  7801. // barriers), and the lower half's value is the answer.
  7802. let (lo, _) = self.exchange_halves(c, mine);
  7803. lo
  7804. } else {
  7805. let i32t = self.s.t.i32;
  7806. let has = self.s.m.cast(c, Cast::ZExt, any, i32t);
  7807. let (lo_has, hi_has) = self.exchange_halves(c, has);
  7808. let (lo, hi) = self.exchange_halves(c, mine);
  7809. let z = self.s.m.i32(0);
  7810. let in_lo = self.s.m.cmp(c, pred::NE, lo_has, z);
  7811. let in_hi = self.s.m.cmp(c, pred::NE, hi_has, z);
  7812. // neither half has a lane in EXEC: the console reads lane 0
  7813. let hi = self.s.m.select(c, in_hi, hi, lo);
  7814. self.s.m.select(c, in_lo, lo, hi)
  7815. }
  7816. } else {
  7817. mine
  7818. };
  7819. int(self, r)
  7820. }
  7821. _ => {
  7822. let r = self.integer(inst, name)?;
  7823. int(self, r)
  7824. }
  7825. }
  7826. }
  7827. /// A 64-bit source (a register pair; inline constants sign-extend).
  7828. fn src64(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  7829. let Fields::Valu(v) = &inst.fields else {
  7830. unreachable!()
  7831. };
  7832. if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 || v.sdwa.is_some() || v.dpp.is_some() {
  7833. return Err("64-bit operand modifiers");
  7834. }
  7835. let c = self.cur;
  7836. let i64t = self.s.m.int(64);
  7837. self.s.flags |= flags::INT64;
  7838. let op = *v.src.get(k).ok_or("a missing operand")?;
  7839. let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<V, Why> {
  7840. let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?;
  7841. let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?;
  7842. Ok(l.join64(lo, hi))
  7843. };
  7844. match op {
  7845. Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1)),
  7846. Operand::Scalar { code, .. } if code != NULL => {
  7847. pair(self, Reg::S(code), Reg::S(code + 1))
  7848. }
  7849. Operand::Const(k @ 128..=208) => {
  7850. let x = crate::resource::inline(k).ok_or("a special operand")?;
  7851. Ok(self.s.m.int_const(i64t, i64::from(x as i32)))
  7852. }
  7853. _ => {
  7854. // Literals and the null register: zero-extended.
  7855. let x = self.operand(inst, &op)?;
  7856. Ok(self.s.m.cast(c, Cast::ZExt, x, i64t))
  7857. }
  7858. }
  7859. }
  7860. /// Reads an IEEE-754 binary64 operand as `(lo, hi)` 32-bit words, applying
  7861. /// `abs` and `neg` input modifiers on operand `k`.
  7862. fn f64_pair(&mut self, inst: &Inst, k: usize) -> Result<(V, V), Why> {
  7863. let Fields::Valu(v) = &inst.fields else {
  7864. unreachable!()
  7865. };
  7866. if v.sdwa.is_some() || v.dpp.is_some() {
  7867. return Err("64-bit operand modifiers");
  7868. }
  7869. let op = *v.src.get(k).ok_or("a missing operand")?;
  7870. let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<(V, V), Why> {
  7871. let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?;
  7872. let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?;
  7873. Ok((lo, hi))
  7874. };
  7875. let (lo, mut hi) = match op {
  7876. Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1))?,
  7877. Operand::Scalar { code, .. } if code != NULL => {
  7878. pair(self, Reg::S(code), Reg::S(code + 1))?
  7879. }
  7880. Operand::Const(128) => (self.s.m.i32(0), self.s.m.i32(0)),
  7881. Operand::Const(c @ 240..=248) => {
  7882. const INLINE_F64: [f64; 9] = [
  7883. 0.5,
  7884. -0.5,
  7885. 1.0,
  7886. -1.0,
  7887. 2.0,
  7888. -2.0,
  7889. 4.0,
  7890. -4.0,
  7891. 1.0 / std::f64::consts::TAU,
  7892. ];
  7893. let bits = INLINE_F64[(c - 240) as usize].to_bits();
  7894. (self.s.m.i32(bits as u32), self.s.m.i32((bits >> 32) as u32))
  7895. }
  7896. // GFX10 places a 32-bit literal in the high 32 bits of a 64-bit float operand.
  7897. Operand::Literal(x) => (self.s.m.i32(0), self.s.m.i32(x)),
  7898. _ => return Err("a 64-bit float operand"),
  7899. };
  7900. let c = self.cur;
  7901. if v.abs >> k & 1 != 0 {
  7902. let mask = self.s.m.i32(0x7FFF_FFFF);
  7903. hi = self.s.m.bin(c, Bin::And, hi, mask);
  7904. }
  7905. if v.neg >> k & 1 != 0 {
  7906. let sign = self.s.m.i32(0x8000_0000);
  7907. hi = self.s.m.bin(c, Bin::Xor, hi, sign);
  7908. }
  7909. Ok((lo, hi))
  7910. }
  7911. /// Converts IEEE-754 binary64 `(lo, hi)` to binary32 bits with round-to-nearest-even,
  7912. /// without requiring host `DOUBLES` (`f64`) support.
  7913. fn f64_to_f32_bits(&mut self, lo: V, hi: V) -> V {
  7914. let c = self.cur;
  7915. let k0 = self.s.m.i32(0);
  7916. let k1 = self.s.m.i32(1);
  7917. let sign_mask = self.s.m.i32(0x8000_0000);
  7918. let sign = self.s.m.bin(c, Bin::And, hi, sign_mask);
  7919. let k20 = self.s.m.i32(20);
  7920. let k7ff = self.s.m.i32(0x7FF);
  7921. let exp64 = self.s.m.bin(c, Bin::LShr, hi, k20);
  7922. let exp64 = self.s.m.bin(c, Bin::And, exp64, k7ff);
  7923. let frac_mask = self.s.m.i32(0x000F_FFFF);
  7924. let frac_hi = self.s.m.bin(c, Bin::And, hi, frac_mask);
  7925. let frac_any = self.s.m.bin(c, Bin::Or, frac_hi, lo);
  7926. let frac_nz = self.s.m.cmp(c, pred::NE, frac_any, k0);
  7927. let k3 = self.s.m.i32(3);
  7928. let k29 = self.s.m.i32(29);
  7929. let m23_hi = self.s.m.bin(c, Bin::Shl, frac_hi, k3);
  7930. let m23_lo = self.s.m.bin(c, Bin::LShr, lo, k29);
  7931. let m23 = self.s.m.bin(c, Bin::Or, m23_hi, m23_lo);
  7932. let rem_mask = self.s.m.i32(0x1FFF_FFFF);
  7933. let rem = self.s.m.bin(c, Bin::And, lo, rem_mask);
  7934. let half_rem = self.s.m.i32(0x1000_0000);
  7935. let gt_half = self.s.m.cmp(c, pred::IUGT, rem, half_rem);
  7936. let eq_half = self.s.m.cmp(c, pred::EQ, rem, half_rem);
  7937. let m23_odd_bit = self.s.m.bin(c, Bin::And, m23, k1);
  7938. let m23_odd = self.s.m.cmp(c, pred::NE, m23_odd_bit, k0);
  7939. let tie_up = self.s.m.bin(c, Bin::And, eq_half, m23_odd);
  7940. let norm_round = self.s.m.bin(c, Bin::Or, gt_half, tie_up);
  7941. let norm_inc = self.s.m.select(c, norm_round, k1, k0);
  7942. // Normal range: exp64 in [897, 1150] -> exp32 in [1, 254].
  7943. let k896 = self.s.m.i32(896);
  7944. let k23 = self.s.m.i32(23);
  7945. let exp32 = self.s.m.bin(c, Bin::Sub, exp64, k896);
  7946. let exp32_sh = self.s.m.bin(c, Bin::Shl, exp32, k23);
  7947. let norm_body = self.s.m.bin(c, Bin::Add, exp32_sh, m23);
  7948. let norm_body = self.s.m.bin(c, Bin::Add, norm_body, norm_inc);
  7949. let norm_res = self.s.m.bin(c, Bin::Or, sign, norm_body);
  7950. // Subnormal range: exp64 in [874, 896] -> shift in [1, 23].
  7951. let k897 = self.s.m.i32(897);
  7952. let k32 = self.s.m.i32(32);
  7953. let k31 = self.s.m.i32(31);
  7954. let imp = self.s.m.i32(0x0080_0000);
  7955. let sig24 = self.s.m.bin(c, Bin::Or, imp, m23);
  7956. let raw_shift = self.s.m.bin(c, Bin::Sub, k897, exp64);
  7957. // Clamp shift to [1, 23] so shifts never produce poison outside the subnormal branch.
  7958. let lt1 = self.s.m.cmp(c, pred::IULT, raw_shift, k1);
  7959. let shift = self.s.m.select(c, lt1, k1, raw_shift);
  7960. let gt23 = self.s.m.cmp(c, pred::IUGT, shift, k23);
  7961. let shift = self.s.m.select(c, gt23, k23, shift);
  7962. let sub_m = self.s.m.bin(c, Bin::LShr, sig24, shift);
  7963. let inv_shift = self.s.m.bin(c, Bin::Sub, k32, shift);
  7964. let lost = self.s.m.bin(c, Bin::Shl, sig24, inv_shift);
  7965. let round_bit = self.s.m.bin(c, Bin::LShr, lost, k31);
  7966. let round_on = self.s.m.cmp(c, pred::NE, round_bit, k0);
  7967. let low31 = self.s.m.i32(0x7FFF_FFFF);
  7968. let lost_lo = self.s.m.bin(c, Bin::And, lost, low31);
  7969. let sticky = self.s.m.bin(c, Bin::Or, lost_lo, rem);
  7970. let sticky_on = self.s.m.cmp(c, pred::NE, sticky, k0);
  7971. let sub_odd_bit = self.s.m.bin(c, Bin::And, sub_m, k1);
  7972. let sub_odd = self.s.m.cmp(c, pred::NE, sub_odd_bit, k0);
  7973. let sub_tie = self.s.m.bin(c, Bin::Or, sticky_on, sub_odd);
  7974. let sub_round = self.s.m.bin(c, Bin::And, round_on, sub_tie);
  7975. let sub_inc = self.s.m.select(c, sub_round, k1, k0);
  7976. let sub_body = self.s.m.bin(c, Bin::Add, sub_m, sub_inc);
  7977. let sub_res = self.s.m.bin(c, Bin::Or, sign, sub_body);
  7978. // Underflow range: exp64 < 874. Only exp64 == 873 with non-zero fraction rounds up to min subnormal (1).
  7979. let k873 = self.s.m.i32(873);
  7980. let eq873 = self.s.m.cmp(c, pred::EQ, exp64, k873);
  7981. let round_min = self.s.m.bin(c, Bin::And, eq873, frac_nz);
  7982. let min_bit = self.s.m.select(c, round_min, k1, k0);
  7983. let under_res = self.s.m.bin(c, Bin::Or, sign, min_bit);
  7984. // Overflow / Inf / NaN: exp64 >= 1151.
  7985. let is_exp_all = self.s.m.cmp(c, pred::EQ, exp64, k7ff);
  7986. let is_nan = self.s.m.bin(c, Bin::And, is_exp_all, frac_nz);
  7987. let inf_bits = self.s.m.i32(0x7F80_0000);
  7988. let qnan_bits = self.s.m.i32(0x7FC0_0000);
  7989. let nan_body = self.s.m.bin(c, Bin::Or, qnan_bits, m23);
  7990. let over_body = self.s.m.select(c, is_nan, nan_body, inf_bits);
  7991. let over_res = self.s.m.bin(c, Bin::Or, sign, over_body);
  7992. // Select final result by exponent range.
  7993. let k874 = self.s.m.i32(874);
  7994. let k1151 = self.s.m.i32(1151);
  7995. let is_under = self.s.m.cmp(c, pred::IULT, exp64, k874);
  7996. let is_sub = self.s.m.cmp(c, pred::IULT, exp64, k897);
  7997. let is_over = self.s.m.cmp(c, pred::IUGE, exp64, k1151);
  7998. let r = self.s.m.select(c, is_over, over_res, norm_res);
  7999. let r = self.s.m.select(c, is_sub, sub_res, r);
  8000. self.s.m.select(c, is_under, under_res, r)
  8001. }
  8002. fn join64(&mut self, lo: V, hi: V) -> V {
  8003. let c = self.cur;
  8004. let ty = self.s.m.int(64);
  8005. let lo = self.s.m.cast(c, Cast::ZExt, lo, ty);
  8006. let hi = self.s.m.cast(c, Cast::ZExt, hi, ty);
  8007. let shift = self.s.m.int_const(ty, 32);
  8008. let hi = self.s.m.bin(c, Bin::Shl, hi, shift);
  8009. self.s.m.bin(c, Bin::Or, lo, hi)
  8010. }
  8011. /// The bits of the float nearest the double whose dwords are `lo` and
  8012. /// `hi`, on 32-bit integers: round to nearest even, infinities and NaN
  8013. /// kept (a NaN stays quiet), a result below the smallest normal float
  8014. /// signed zero (flushed, as the console's default float mode does).
  8015. // The flush-to-zero form of v_cvt_f32_f64: kept beside the IEEE form in use until the console's
  8016. // float mode for this instruction is checked.
  8017. #[allow(dead_code)]
  8018. fn f64_bits_to_f32_bits(&mut self, lo: V, hi: V) -> V {
  8019. let c = self.cur;
  8020. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  8021. let (k20, k29, k3, k23) = (k(self, 20), k(self, 29), k(self, 3), k(self, 23));
  8022. let sign_mask = k(self, 0x8000_0000);
  8023. let sign = self.s.m.bin(c, Bin::And, hi, sign_mask);
  8024. let e = self.s.m.bin(c, Bin::LShr, hi, k20);
  8025. let e_mask = k(self, 0x7ff);
  8026. let e = self.s.m.bin(c, Bin::And, e, e_mask);
  8027. // The top 23 bits of the 52-bit mantissa, and the 29 below them.
  8028. let m_mask = k(self, 0x000f_ffff);
  8029. let mh = self.s.m.bin(c, Bin::And, hi, m_mask);
  8030. let mh = self.s.m.bin(c, Bin::Shl, mh, k3);
  8031. let ml = self.s.m.bin(c, Bin::LShr, lo, k29);
  8032. let m = self.s.m.bin(c, Bin::Or, mh, ml);
  8033. let rest_mask = k(self, 0x1fff_ffff);
  8034. let rest = self.s.m.bin(c, Bin::And, lo, rest_mask);
  8035. // Round to nearest even: up past half, or at half when odd.
  8036. let half = k(self, 0x1000_0000);
  8037. let one = k(self, 1);
  8038. let above = self.s.m.cmp(c, pred::IUGT, rest, half);
  8039. let at = self.s.m.cmp(c, pred::EQ, rest, half);
  8040. let odd = self.s.m.bin(c, Bin::And, m, one);
  8041. let zero = k(self, 0);
  8042. let odd = self.s.m.cmp(c, pred::NE, odd, zero);
  8043. let tie = self.s.m.bin(c, Bin::And, at, odd);
  8044. let up = self.s.m.bin(c, Bin::Or, above, tie);
  8045. let up = self.s.m.select(c, up, one, zero);
  8046. // Rebias the exponent (1023 → 127); a carry out of the mantissa
  8047. // steps the exponent, up to infinity.
  8048. let bias = k(self, 1023 - 127);
  8049. let e32 = self.s.m.bin(c, Bin::Sub, e, bias);
  8050. let ex = self.s.m.bin(c, Bin::Shl, e32, k23);
  8051. let normal = self.s.m.bin(c, Bin::Add, ex, m);
  8052. let normal = self.s.m.bin(c, Bin::Add, normal, up);
  8053. let normal = self.s.m.bin(c, Bin::Or, normal, sign);
  8054. // Exponents out of the float's range (signed, after rebiasing).
  8055. let inf = k(self, 0x7f80_0000);
  8056. let inf = self.s.m.bin(c, Bin::Or, inf, sign);
  8057. let k255 = k(self, 255);
  8058. let big = self.s.m.cmp(c, pred::SGE, e32, k255);
  8059. let small = self.s.m.cmp(c, pred::SLE, e32, zero);
  8060. let r = self.s.m.select(c, big, inf, normal);
  8061. let r = self.s.m.select(c, small, sign, r);
  8062. // Infinity and NaN (a NaN with any mantissa bit set stays a NaN).
  8063. let all = k(self, 0x7ff);
  8064. let special = self.s.m.cmp(c, pred::EQ, e, all);
  8065. let any = self.s.m.bin(c, Bin::Or, mh, ml);
  8066. let any = self.s.m.bin(c, Bin::Or, any, rest);
  8067. let nan = self.s.m.cmp(c, pred::NE, any, zero);
  8068. let quiet = k(self, 0x0040_0000);
  8069. let quiet = self.s.m.select(c, nan, quiet, zero);
  8070. let special_bits = self.s.m.bin(c, Bin::Or, inf, quiet);
  8071. self.s.m.select(c, special, special_bits, r)
  8072. }
  8073. /// The low and high dwords of an i64.
  8074. fn split64(&mut self, x: V) -> (V, V) {
  8075. let c = self.cur;
  8076. let i64t = self.s.m.int(64);
  8077. let k32 = self.s.m.int_const(i64t, 32);
  8078. let lo = self.s.m.cast(c, Cast::Trunc, x, self.s.t.i32);
  8079. let hi = self.s.m.bin(c, Bin::LShr, x, k32);
  8080. let hi = self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32);
  8081. (lo, hi)
  8082. }
  8083. /// Source `k` of a 16-bit operation in the low 16 bits (the rest 0):
  8084. /// op_sel (or an SDWA word select) picks the high half; inline float
  8085. /// constants are f16 values here.
  8086. fn half_src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  8087. let Fields::Valu(v) = &inst.fields else {
  8088. unreachable!()
  8089. };
  8090. let op = *v.src.get(k).ok_or("a missing operand")?;
  8091. let mut high = v.opsel >> k & 1 != 0;
  8092. if let Some(sd) = v.sdwa {
  8093. match sd.src_sel.get(k).copied().unwrap_or(6) {
  8094. 4 => {}
  8095. 5 => high = true,
  8096. 6 => {}
  8097. _ => return Err("a byte select on a 16-bit operation"),
  8098. }
  8099. }
  8100. let x = match self.src0 {
  8101. Some(x) if k == 0 => x,
  8102. _ => self.f16_operand(inst, &op)?,
  8103. };
  8104. let c = self.cur;
  8105. let x = if high {
  8106. let k16 = self.s.m.i32(16);
  8107. self.s.m.bin(c, Bin::LShr, x, k16)
  8108. } else {
  8109. x
  8110. };
  8111. let m = self.s.m.i32(0xFFFF);
  8112. Ok(self.s.m.bin(c, Bin::And, x, m))
  8113. }
  8114. /// An f16 source as an f32 (exact), with its abs/neg modifiers.
  8115. fn half_fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  8116. let Fields::Valu(v) = &inst.fields else {
  8117. unreachable!()
  8118. };
  8119. let h = self.half_src(inst, k)?;
  8120. let f32t = self.s.t.f32;
  8121. let mut f = self
  8122. .s
  8123. .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  8124. if v.abs >> k & 1 != 0 {
  8125. f = self.unary(6, f);
  8126. }
  8127. if v.neg >> k & 1 != 0 {
  8128. let z = self.s.m.f32(0x8000_0000);
  8129. f = self.s.m.bin(self.cur, Bin::Sub, z, f);
  8130. }
  8131. Ok(f)
  8132. }
  8133. /// Writes a 16-bit result (low bits of `x`) into the destination's low
  8134. /// half, or its high half with op_sel bit 3 (or an SDWA WORD_1 select);
  8135. /// the other half is kept (GFX10).
  8136. fn write_half(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> {
  8137. let Fields::Valu(v) = &inst.fields else {
  8138. unreachable!()
  8139. };
  8140. let Some(Operand::Vector { reg, .. }) = v.dst else {
  8141. return Err("a 16-bit result outside a VGPR");
  8142. };
  8143. let mut high = v.opsel >> 3 & 1 != 0;
  8144. // SDWA: the word written, the other one kept (preserve) or zero
  8145. // (pad; a sign extension above the high word adds nothing).
  8146. let mut keep = true;
  8147. if let Some(sd) = v.sdwa {
  8148. match (sd.dst_sel, sd.dst_unused) {
  8149. (4, 2) => {}
  8150. (5, 2) => high = true,
  8151. (4 | 6, _) => keep = false,
  8152. (5, _) => (high, keep) = (true, false),
  8153. _ => return Err("an SDWA destination of a 16-bit operation"),
  8154. }
  8155. }
  8156. let c = self.cur;
  8157. let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) {
  8158. Some(Ok(o)) if keep => o,
  8159. _ => self.s.m.i32(0),
  8160. };
  8161. let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
  8162. let x = self.s.m.bin(c, Bin::And, x, low);
  8163. let r = if high {
  8164. let o = self.s.m.bin(c, Bin::And, old, low);
  8165. let x = self.s.m.bin(c, Bin::Shl, x, k16);
  8166. self.s.m.bin(c, Bin::Or, o, x)
  8167. } else {
  8168. let keep = self.s.m.i32(0xFFFF_0000);
  8169. let o = self.s.m.bin(c, Bin::And, old, keep);
  8170. self.s.m.bin(c, Bin::Or, o, x)
  8171. };
  8172. self.write_placed(inst, Reg::V(reg), r, guard);
  8173. Ok(())
  8174. }
  8175. /// 16-bit operations, computed in f32 or i32: f16 sums, differences and
  8176. /// products are exact there and round once to f16 (f32 has the 2 x 11 +
  8177. /// 2 bits that make double rounding harmless); `None` if `name` is none.
  8178. fn valu16(&mut self, inst: &Inst, name: &str, guard: Option<V>) -> Option<Result<(), Why>> {
  8179. const FLOAT2: &[&str] = &[
  8180. "v_add_f16",
  8181. "v_sub_f16",
  8182. "v_subrev_f16",
  8183. "v_mul_f16",
  8184. "v_max_f16",
  8185. "v_min_f16",
  8186. ];
  8187. const FLOAT3: &[&str] = &[
  8188. "v_fma_f16",
  8189. "v_mad_f16",
  8190. "v_fmac_f16",
  8191. "v_mac_f16",
  8192. "v_max3_f16",
  8193. "v_min3_f16",
  8194. "v_med3_f16",
  8195. ];
  8196. const FLOAT1: &[&str] = &[
  8197. "v_rcp_f16",
  8198. "v_sqrt_f16",
  8199. "v_rsq_f16",
  8200. "v_log_f16",
  8201. "v_exp_f16",
  8202. "v_fract_f16",
  8203. "v_trunc_f16",
  8204. "v_floor_f16",
  8205. "v_ceil_f16",
  8206. "v_rndne_f16",
  8207. "v_sin_f16",
  8208. "v_cos_f16",
  8209. "v_cvt_f16_u16",
  8210. "v_cvt_f16_i16",
  8211. ];
  8212. const INT: &[&str] = &[
  8213. "v_add_nc_u16",
  8214. "v_sub_nc_u16",
  8215. "v_subrev_nc_u16",
  8216. "v_mul_lo_u16",
  8217. "v_lshlrev_b16",
  8218. "v_lshrrev_b16",
  8219. "v_ashrrev_i16",
  8220. "v_max_u16",
  8221. "v_max_i16",
  8222. "v_min_u16",
  8223. "v_min_i16",
  8224. "v_cvt_u16_f16",
  8225. "v_cvt_i16_f16",
  8226. "v_cvt_norm_i16_f16",
  8227. "v_cvt_norm_u16_f16",
  8228. ];
  8229. let all = [FLOAT1, FLOAT2, FLOAT3, INT];
  8230. if !all.iter().any(|l| l.contains(&name))
  8231. && !matches!(name, "v_cvt_f16_f32" | "v_cvt_f32_f16")
  8232. {
  8233. return None;
  8234. }
  8235. Some(self.valu16_op(inst, name, guard, FLOAT1, FLOAT2, FLOAT3))
  8236. }
  8237. #[allow(clippy::too_many_arguments)]
  8238. fn valu16_op(
  8239. &mut self,
  8240. inst: &Inst,
  8241. name: &str,
  8242. guard: Option<V>,
  8243. float1: &[&str],
  8244. float2: &[&str],
  8245. float3: &[&str],
  8246. ) -> Result<(), Why> {
  8247. let Fields::Valu(v) = &inst.fields else {
  8248. unreachable!()
  8249. };
  8250. let c = self.cur;
  8251. let i32t = self.s.t.i32;
  8252. let f32t = self.s.t.f32;
  8253. if name == "v_cvt_f32_f16" {
  8254. let f = self.half_fsrc(inst, 0)?;
  8255. return self.write_f(inst, f, guard);
  8256. }
  8257. let float_result = |l: &mut Self, mut f: V| -> Result<(), Why> {
  8258. match v.omod {
  8259. 0 => {}
  8260. k => {
  8261. let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)];
  8262. let k = l.s.m.f32(factor.to_bits());
  8263. f = l.s.m.bin(l.cur, Bin::Mul, f, k);
  8264. }
  8265. }
  8266. if v.clamp {
  8267. f = l.unary(7, f);
  8268. }
  8269. // The console rounds to nearest; the host's conversion may round toward zero
  8270. // (NVIDIA's does), one step of the last place lower where the two differ.
  8271. // shortcut: the host's conversion unless `VICTORY_F16_NEAREST=1`
  8272. // ([`f16_nearest_on`]), which costs a dozen instructions per result.
  8273. let h = if f16_nearest_on() {
  8274. l.f16_nearest(f)
  8275. } else {
  8276. l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  8277. };
  8278. l.write_half(inst, h, guard)
  8279. };
  8280. if name == "v_cvt_f16_f32" {
  8281. let f = self.fsrc(inst, 0)?;
  8282. return float_result(self, f);
  8283. }
  8284. if float2.contains(&name) {
  8285. let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?);
  8286. let r = match name {
  8287. "v_add_f16" => self.s.m.bin(c, Bin::Add, a, b),
  8288. "v_sub_f16" => self.s.m.bin(c, Bin::Sub, a, b),
  8289. "v_subrev_f16" => self.s.m.bin(c, Bin::Sub, b, a),
  8290. "v_mul_f16" => self.s.m.bin(c, Bin::Mul, a, b),
  8291. "v_max_f16" => self.max_min(true, a, b),
  8292. _ => self.max_min(false, a, b),
  8293. };
  8294. return float_result(self, r);
  8295. }
  8296. if float3.contains(&name) {
  8297. let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?);
  8298. let acc = if matches!(name, "v_fmac_f16" | "v_mac_f16") {
  8299. // The accumulator is the destination's half that is written.
  8300. let Some(Operand::Vector { reg, .. }) = v.dst else {
  8301. return Err("an accumulator");
  8302. };
  8303. let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?;
  8304. let x = if v.opsel >> 3 & 1 != 0 {
  8305. let k16 = self.s.m.i32(16);
  8306. self.s.m.bin(c, Bin::LShr, x, k16)
  8307. } else {
  8308. x
  8309. };
  8310. let m = self.s.m.i32(0xFFFF);
  8311. let x = self.s.m.bin(c, Bin::And, x, m);
  8312. self.s
  8313. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x])
  8314. } else {
  8315. self.half_fsrc(inst, 2)?
  8316. };
  8317. let r = match name {
  8318. // shortcut: fused f16 multiply-adds as FMad in f32 (the
  8319. // product is exact; the sum rounds twice).
  8320. "v_fma_f16" | "v_fmac_f16" | "v_mad_f16" | "v_mac_f16" => self.fmad(a, b, acc),
  8321. "v_max3_f16" => {
  8322. let t = self.max_min(true, a, b);
  8323. self.max_min(true, t, acc)
  8324. }
  8325. "v_min3_f16" => {
  8326. let t = self.max_min(false, a, b);
  8327. self.max_min(false, t, acc)
  8328. }
  8329. _ => self.med3(a, b, acc),
  8330. };
  8331. return float_result(self, r);
  8332. }
  8333. if float1.contains(&name) {
  8334. let r = match name {
  8335. "v_cvt_f16_u16" | "v_cvt_f16_i16" => {
  8336. let mut x = self.half_src(inst, 0)?;
  8337. let op = if name == "v_cvt_f16_i16" {
  8338. let k16 = self.s.m.i32(16);
  8339. let t = self.s.m.bin(c, Bin::Shl, x, k16);
  8340. x = self.s.m.bin(c, Bin::AShr, t, k16);
  8341. Cast::SiToFp
  8342. } else {
  8343. Cast::UiToFp
  8344. };
  8345. self.s.m.cast(c, op, x, f32t)
  8346. }
  8347. "v_rcp_f16" => {
  8348. let a = self.half_fsrc(inst, 0)?;
  8349. let one = self.s.m.f32(1.0f32.to_bits());
  8350. self.s.m.bin(c, Bin::SDiv, one, a)
  8351. }
  8352. _ => {
  8353. let a = self.half_fsrc(inst, 0)?;
  8354. let op = match name {
  8355. "v_sqrt_f16" => 24,
  8356. "v_rsq_f16" => 25,
  8357. "v_log_f16" => 23,
  8358. "v_exp_f16" => 21,
  8359. "v_fract_f16" => 22,
  8360. "v_trunc_f16" => 29,
  8361. "v_floor_f16" => 27,
  8362. "v_ceil_f16" => 28,
  8363. "v_rndne_f16" => 26,
  8364. "v_sin_f16" => 13,
  8365. _ => 12,
  8366. };
  8367. match op {
  8368. 12 | 13 => self.trig_turns(a, op == 12),
  8369. // Any f16 in (-2^-11, 0) has fract >= 1 - 2^-12; clamp to 0x3bff (1 - 2^-11).
  8370. 22 => self.fract(a, 1.0 - 1.0 / 4096.0, 1.0 - 1.0 / 2048.0),
  8371. _ => self.unary(op, a),
  8372. }
  8373. }
  8374. };
  8375. return float_result(self, r);
  8376. }
  8377. if matches!(name, "v_cvt_u16_f16" | "v_cvt_i16_f16") {
  8378. if v.clamp || v.omod != 0 {
  8379. return Err("modifiers on a 16-bit integer operation");
  8380. }
  8381. // Toward zero, saturating at the 16-bit range (infinities
  8382. // included); NaN gives 0. Clamped in f32 first, where every
  8383. // f16 is exact, so the conversion never leaves i32's range
  8384. // (upstream PR #384's arithmetic; the source's abs and neg
  8385. // modifiers are applied by `half_fsrc`, as before).
  8386. let a = self.half_fsrc(inst, 0)?;
  8387. let (lo, hi) = if name == "v_cvt_u16_f16" {
  8388. (0.0f32, 65535.0f32)
  8389. } else {
  8390. (-32768.0, 32767.0)
  8391. };
  8392. let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits()));
  8393. let t = self.binary(35, a, lo);
  8394. let t = self.binary(36, t, hi);
  8395. let r = self.s.m.cast(c, Cast::FpToSi, t, i32t);
  8396. let nan = self.s.m.cmp(c, pred::UNO, a, a);
  8397. let z = self.s.m.i32(0);
  8398. let r = self.s.m.select(c, nan, z, r);
  8399. return self.write_half(inst, r, guard);
  8400. }
  8401. if matches!(name, "v_cvt_norm_i16_f16" | "v_cvt_norm_u16_f16") {
  8402. if v.clamp || v.omod != 0 {
  8403. return Err("modifiers on a 16-bit integer operation");
  8404. }
  8405. let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?;
  8406. return self.write_half(inst, r, guard);
  8407. }
  8408. // 16-bit integers: computed on the low halves, the low 16 bits kept.
  8409. if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 {
  8410. return Err("modifiers on a 16-bit integer operation");
  8411. }
  8412. let r = {
  8413. let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
  8414. let k16 = self.s.m.i32(16);
  8415. let sext = |l: &mut Self, x: V| {
  8416. let t = l.s.m.bin(c, Bin::Shl, x, k16);
  8417. l.s.m.bin(c, Bin::AShr, t, k16)
  8418. };
  8419. if name.ends_with("_i16") {
  8420. a = sext(self, a);
  8421. b = sext(self, b);
  8422. }
  8423. let k15 = self.s.m.i32(15);
  8424. match name {
  8425. "v_add_nc_u16" => self.s.m.bin(c, Bin::Add, a, b),
  8426. "v_sub_nc_u16" => self.s.m.bin(c, Bin::Sub, a, b),
  8427. "v_subrev_nc_u16" => self.s.m.bin(c, Bin::Sub, b, a),
  8428. "v_mul_lo_u16" => self.s.m.bin(c, Bin::Mul, a, b),
  8429. "v_lshlrev_b16" | "v_lshrrev_b16" | "v_ashrrev_i16" => {
  8430. // src0 is the shift (4 bits), src1 the value.
  8431. let sh = self.s.m.bin(c, Bin::And, a, k15);
  8432. let x = if name == "v_ashrrev_i16" {
  8433. sext(self, b)
  8434. } else {
  8435. b
  8436. };
  8437. let op = match name {
  8438. "v_lshlrev_b16" => Bin::Shl,
  8439. "v_lshrrev_b16" => Bin::LShr,
  8440. _ => Bin::AShr,
  8441. };
  8442. self.s.m.bin(c, op, x, sh)
  8443. }
  8444. _ => {
  8445. let p = match name {
  8446. "v_max_u16" => pred::IUGT,
  8447. "v_min_u16" => pred::IULT,
  8448. "v_max_i16" => pred::SGT,
  8449. _ => pred::SLT,
  8450. };
  8451. let t = self.s.m.cmp(c, p, a, b);
  8452. self.s.m.select(c, t, a, b)
  8453. }
  8454. }
  8455. };
  8456. self.write_half(inst, r, guard)
  8457. }
  8458. /// `v_cvt_norm_i16_f16` / `v_cvt_norm_u16_f16`: the f16 source (with its
  8459. /// abs/neg modifiers) clamped to [-1, 1] or [0, 1], times 32767 or 65535,
  8460. /// rounded to nearest even once from the exact product; NaN gives 0.
  8461. /// Worked on the f16's bits in integers, because in f32 the product
  8462. /// (up to 26 significant bits) would round before the rounding to an
  8463. /// integer.
  8464. fn cvt_norm16(&mut self, inst: &Inst, signed: bool) -> Result<V, Why> {
  8465. let Fields::Valu(v) = &inst.fields else {
  8466. unreachable!()
  8467. };
  8468. let c = self.cur;
  8469. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  8470. let mut h = self.half_src(inst, 0)?;
  8471. if v.abs & 1 != 0 {
  8472. let m = k(self, 0x7FFF);
  8473. h = self.s.m.bin(c, Bin::And, h, m);
  8474. }
  8475. if v.neg & 1 != 0 {
  8476. let m = k(self, 0x8000);
  8477. h = self.s.m.bin(c, Bin::Xor, h, m);
  8478. }
  8479. let scale = if signed { 0x7FFF } else { 0xFFFF };
  8480. let (k0, k1, k10) = (k(self, 0), k(self, 1), k(self, 10));
  8481. let mag_mask = k(self, 0x7FFF);
  8482. let mag = self.s.m.bin(c, Bin::And, h, mag_mask);
  8483. let k15 = k(self, 15);
  8484. let neg = self.s.m.bin(c, Bin::LShr, h, k15);
  8485. let neg = self.s.m.cmp(c, pred::NE, neg, k0);
  8486. // |x| < 1: x = m * 2^-s with m < 2^11 and 11 <= s <= 24.
  8487. let exp = self.s.m.bin(c, Bin::LShr, mag, k10);
  8488. let man_mask = k(self, 0x3FF);
  8489. let man = self.s.m.bin(c, Bin::And, mag, man_mask);
  8490. let implicit = k(self, 0x400);
  8491. let normal = self.s.m.bin(c, Bin::Or, man, implicit);
  8492. let sub = self.s.m.cmp(c, pred::EQ, exp, k0);
  8493. let m = self.s.m.select(c, sub, man, normal);
  8494. let k25 = k(self, 25);
  8495. let s_norm = self.s.m.bin(c, Bin::Sub, k25, exp);
  8496. let k24 = k(self, 24);
  8497. let sh = self.s.m.select(c, sub, k24, s_norm);
  8498. let ks = k(self, scale);
  8499. let p = self.s.m.bin(c, Bin::Mul, m, ks);
  8500. let q = self.s.m.bin(c, Bin::LShr, p, sh);
  8501. let one_s = self.s.m.bin(c, Bin::Shl, k1, sh);
  8502. let low_mask = self.s.m.bin(c, Bin::Sub, one_s, k1);
  8503. let rem = self.s.m.bin(c, Bin::And, p, low_mask);
  8504. let half = self.s.m.bin(c, Bin::LShr, one_s, k1);
  8505. let above = self.s.m.cmp(c, pred::IUGT, rem, half);
  8506. let tie = self.s.m.cmp(c, pred::EQ, rem, half);
  8507. let odd = self.s.m.bin(c, Bin::And, q, k1);
  8508. let odd = self.s.m.cmp(c, pred::NE, odd, k0);
  8509. let tie_up = self.s.m.bin(c, Bin::And, tie, odd);
  8510. let up = self.s.m.bin(c, Bin::Or, above, tie_up);
  8511. let r = self.s.m.select(c, up, k1, k0);
  8512. let r = self.s.m.bin(c, Bin::Add, q, r);
  8513. // |x| >= 1 (and infinity) saturates; NaN gives 0.
  8514. let one_h = k(self, 0x3C00);
  8515. let big = self.s.m.cmp(c, pred::IUGE, mag, one_h);
  8516. let r = self.s.m.select(c, big, ks, r);
  8517. let inf = k(self, 0x7C00);
  8518. let nan = self.s.m.cmp(c, pred::IUGT, mag, inf);
  8519. let r = self.s.m.select(c, nan, k0, r);
  8520. let r = if signed {
  8521. let n = self.s.m.bin(c, Bin::Sub, k0, r);
  8522. self.s.m.select(c, neg, n, r)
  8523. } else {
  8524. self.s.m.select(c, neg, k0, r)
  8525. };
  8526. let m16 = k(self, 0xFFFF);
  8527. Ok(self.s.m.bin(c, Bin::And, r, m16))
  8528. }
  8529. /// Half `high` of source `k` of a packed (VOP3P) operation, in the low
  8530. /// 16 bits: op_sel picks the half the low result reads, op_sel_hi the
  8531. /// half the high result reads. Packed integer instructions see the f32
  8532. /// bits of an inline float constant.
  8533. fn packed_src(&mut self, inst: &Inst, k: usize, high: bool, float: bool) -> Result<V, Why> {
  8534. let Fields::Valu(v) = &inst.fields else {
  8535. unreachable!()
  8536. };
  8537. let op = *v.src.get(k).ok_or("a missing operand")?;
  8538. let sel = if high { v.opsel_hi } else { v.opsel } >> k & 1 != 0;
  8539. let x = if float {
  8540. self.f16_operand(inst, &op)?
  8541. } else {
  8542. self.operand(inst, &op)?
  8543. };
  8544. let c = self.cur;
  8545. let x = if sel {
  8546. let k16 = self.s.m.i32(16);
  8547. self.s.m.bin(c, Bin::LShr, x, k16)
  8548. } else {
  8549. x
  8550. };
  8551. let m = self.s.m.i32(0xFFFF);
  8552. Ok(self.s.m.bin(c, Bin::And, x, m))
  8553. }
  8554. /// Half `high` of source `k` of `v_pk_fmac_f16`, in the low 16 bits: a
  8555. /// VOP2 operation (no op_sel) whose third source is its destination.
  8556. fn fmac_half(&mut self, inst: &Inst, k: usize, high: bool) -> Result<V, Why> {
  8557. let Fields::Valu(v) = &inst.fields else {
  8558. unreachable!()
  8559. };
  8560. let op = if k == 2 { v.dst } else { v.src.get(k).copied() };
  8561. let op = op.ok_or("a missing operand")?;
  8562. if matches!(op, Operand::Const(_) | Operand::Literal(_)) {
  8563. // shortcut: no constant operand seen; its high half is not known.
  8564. return Err("a constant operand of v_pk_fmac_f16");
  8565. }
  8566. let x = self.operand(inst, &op)?;
  8567. let c = self.cur;
  8568. let x = if high {
  8569. let k16 = self.s.m.i32(16);
  8570. self.s.m.bin(c, Bin::LShr, x, k16)
  8571. } else {
  8572. x
  8573. };
  8574. let m = self.s.m.i32(0xFFFF);
  8575. Ok(self.s.m.bin(c, Bin::And, x, m))
  8576. }
  8577. /// Packed 16-bit operations (`v_pk_*`): each half computed as the
  8578. /// 16-bit operation does, f16 through f32 as in [`Self::valu16`].
  8579. fn packed16(&mut self, inst: &Inst, op: &str, guard: Option<V>) -> Result<(), Why> {
  8580. let Fields::Valu(v) = &inst.fields else {
  8581. unreachable!()
  8582. };
  8583. let float = op.ends_with("_f16");
  8584. let n = match op {
  8585. "fma_f16" | "fmac_f16" | "mad_u16" | "mad_i16" => 3,
  8586. "add_f16" | "mul_f16" | "min_f16" | "max_f16" | "add_u16" | "sub_u16" | "add_i16"
  8587. | "sub_i16" | "mul_lo_u16" | "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16"
  8588. | "max_u16" | "min_u16" | "max_i16" | "min_i16" => 2,
  8589. _ => return Err("a packed 16-bit operation"),
  8590. };
  8591. if v.omod != 0 || !float && (v.clamp || v.neg != 0 || v.neg_hi != 0) {
  8592. return Err("modifiers on a packed integer operation");
  8593. }
  8594. let c = self.cur;
  8595. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  8596. let mut halves = Vec::new();
  8597. for high in [false, true] {
  8598. let mut xs = Vec::new();
  8599. for k in 0..n {
  8600. let h = if op == "fmac_f16" {
  8601. self.fmac_half(inst, k, high)?
  8602. } else {
  8603. self.packed_src(inst, k, high, float)?
  8604. };
  8605. if float {
  8606. let mut f = self
  8607. .s
  8608. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  8609. let neg = if high { v.neg_hi } else { v.neg };
  8610. if neg >> k & 1 != 0 {
  8611. let z = self.s.m.f32(0x8000_0000);
  8612. f = self.s.m.bin(c, Bin::Sub, z, f);
  8613. }
  8614. xs.push(f);
  8615. } else {
  8616. xs.push(h);
  8617. }
  8618. }
  8619. let r = if float {
  8620. let mut f = match op {
  8621. "add_f16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
  8622. "mul_f16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
  8623. "min_f16" => self.max_min(false, xs[0], xs[1]),
  8624. "max_f16" => self.max_min(true, xs[0], xs[1]),
  8625. // shortcut: FMad in f32, as v_fma_f16.
  8626. _ => self.fmad(xs[0], xs[1], xs[2]),
  8627. };
  8628. if v.clamp {
  8629. f = self.unary(7, f);
  8630. }
  8631. self.s
  8632. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  8633. } else {
  8634. let k16 = self.s.m.i32(16);
  8635. let sext = |l: &mut Self, x: V| {
  8636. let t = l.s.m.bin(c, Bin::Shl, x, k16);
  8637. l.s.m.bin(c, Bin::AShr, t, k16)
  8638. };
  8639. if op.ends_with("_i16") {
  8640. for x in &mut xs {
  8641. *x = sext(self, *x);
  8642. }
  8643. }
  8644. let k15 = self.s.m.i32(15);
  8645. match op {
  8646. "add_u16" | "add_i16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
  8647. "sub_u16" | "sub_i16" => self.s.m.bin(c, Bin::Sub, xs[0], xs[1]),
  8648. "mul_lo_u16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
  8649. "mad_u16" | "mad_i16" => {
  8650. let m = self.s.m.bin(c, Bin::Mul, xs[0], xs[1]);
  8651. self.s.m.bin(c, Bin::Add, m, xs[2])
  8652. }
  8653. "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16" => {
  8654. let sh = self.s.m.bin(c, Bin::And, xs[0], k15);
  8655. let o = match op {
  8656. "lshlrev_b16" => Bin::Shl,
  8657. "lshrrev_b16" => Bin::LShr,
  8658. _ => Bin::AShr,
  8659. };
  8660. let x = if op == "ashrrev_i16" {
  8661. sext(self, xs[1])
  8662. } else {
  8663. xs[1]
  8664. };
  8665. self.s.m.bin(c, o, x, sh)
  8666. }
  8667. _ => {
  8668. let p = match op {
  8669. "max_u16" => pred::IUGT,
  8670. "min_u16" => pred::IULT,
  8671. "max_i16" => pred::SGT,
  8672. _ => pred::SLT,
  8673. };
  8674. let t = self.s.m.cmp(c, p, xs[0], xs[1]);
  8675. self.s.m.select(c, t, xs[0], xs[1])
  8676. }
  8677. }
  8678. };
  8679. let m = self.s.m.i32(0xFFFF);
  8680. halves.push(self.s.m.bin(c, Bin::And, r, m));
  8681. }
  8682. let k16 = self.s.m.i32(16);
  8683. let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16);
  8684. let r = self.s.m.bin(c, Bin::Or, halves[0], hi);
  8685. let Some(Operand::Vector { reg, .. }) = v.dst else {
  8686. return Err("a packed result outside a VGPR");
  8687. };
  8688. self.write(inst, Reg::V(reg), r, guard);
  8689. Ok(())
  8690. }
  8691. fn integer(&mut self, inst: &Inst, name: &'static str) -> Result<V, Why> {
  8692. let c = self.cur;
  8693. let s = |l: &mut Self, k| l.src(inst, k);
  8694. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  8695. let m31 = |l: &mut Self, x: V| {
  8696. let k31 = l.s.m.i32(31);
  8697. l.s.m.bin(c, Bin::And, x, k31)
  8698. };
  8699. Ok(match name {
  8700. "v_and_b32" | "v_or_b32" | "v_xor_b32" | "v_add_nc_u32" | "v_sub_nc_u32"
  8701. | "v_subrev_nc_u32" | "v_mul_lo_u32" => {
  8702. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8703. let (op, a, b) = match name {
  8704. "v_and_b32" => (Bin::And, a, b),
  8705. "v_or_b32" => (Bin::Or, a, b),
  8706. "v_xor_b32" => (Bin::Xor, a, b),
  8707. "v_add_nc_u32" => (Bin::Add, a, b),
  8708. "v_sub_nc_u32" => (Bin::Sub, a, b),
  8709. "v_subrev_nc_u32" => (Bin::Sub, b, a),
  8710. _ => (Bin::Mul, a, b),
  8711. };
  8712. self.s.m.bin(c, op, a, b)
  8713. }
  8714. "v_xnor_b32" => {
  8715. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8716. let x = self.s.m.bin(c, Bin::Xor, a, b);
  8717. let ones = k(self, u32::MAX);
  8718. self.s.m.bin(c, Bin::Xor, x, ones)
  8719. }
  8720. "v_not_b32" => {
  8721. let a = s(self, 0)?;
  8722. let ones = k(self, u32::MAX);
  8723. self.s.m.bin(c, Bin::Xor, a, ones)
  8724. }
  8725. "v_lshlrev_b32" | "v_lshrrev_b32" | "v_ashrrev_i32" => {
  8726. let (sh, a) = (s(self, 0)?, s(self, 1)?);
  8727. let sh = m31(self, sh);
  8728. let op = match name {
  8729. "v_lshlrev_b32" => Bin::Shl,
  8730. "v_lshrrev_b32" => Bin::LShr,
  8731. _ => Bin::AShr,
  8732. };
  8733. self.s.m.bin(c, op, a, sh)
  8734. }
  8735. "v_lshl_add_u32" | "v_lshl_or_b32" | "v_add_lshl_u32" | "v_and_or_b32"
  8736. | "v_or3_b32" | "v_xad_u32" | "v_add3_u32" | "v_xor3_b32" => {
  8737. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8738. match name {
  8739. "v_lshl_add_u32" | "v_lshl_or_b32" => {
  8740. let b = m31(self, b);
  8741. let t = self.s.m.bin(c, Bin::Shl, a, b);
  8742. let op = if name == "v_lshl_add_u32" {
  8743. Bin::Add
  8744. } else {
  8745. Bin::Or
  8746. };
  8747. self.s.m.bin(c, op, t, d)
  8748. }
  8749. "v_add_lshl_u32" => {
  8750. let t = self.s.m.bin(c, Bin::Add, a, b);
  8751. let d = m31(self, d);
  8752. self.s.m.bin(c, Bin::Shl, t, d)
  8753. }
  8754. _ => {
  8755. let (o1, o2) = match name {
  8756. "v_and_or_b32" => (Bin::And, Bin::Or),
  8757. "v_or3_b32" => (Bin::Or, Bin::Or),
  8758. "v_xad_u32" => (Bin::Xor, Bin::Add),
  8759. "v_add3_u32" => (Bin::Add, Bin::Add),
  8760. _ => (Bin::Xor, Bin::Xor),
  8761. };
  8762. let t = self.s.m.bin(c, o1, a, b);
  8763. self.s.m.bin(c, o2, t, d)
  8764. }
  8765. }
  8766. }
  8767. "v_mul_u32_u24" | "v_mul_i32_i24" => {
  8768. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8769. let (sh, op) = (
  8770. k(self, 8),
  8771. if name == "v_mul_i32_i24" {
  8772. Bin::AShr
  8773. } else {
  8774. Bin::LShr
  8775. },
  8776. );
  8777. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  8778. let a = self.s.m.bin(c, op, a, sh);
  8779. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  8780. let b = self.s.m.bin(c, op, b, sh);
  8781. self.s.m.bin(c, Bin::Mul, a, b)
  8782. }
  8783. "v_bfe_u32" | "v_bfe_i32" => {
  8784. let (a, off, w) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8785. let w = m31(self, w);
  8786. self.bfe(a, off, w, name == "v_bfe_i32")
  8787. }
  8788. "v_bfi_b32" => {
  8789. let (m, a, b) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8790. let ones = k(self, u32::MAX);
  8791. let nm = self.s.m.bin(c, Bin::Xor, m, ones);
  8792. let x = self.s.m.bin(c, Bin::And, m, a);
  8793. let y = self.s.m.bin(c, Bin::And, nm, b);
  8794. self.s.m.bin(c, Bin::Or, x, y)
  8795. }
  8796. "v_max_i32" | "v_min_i32" | "v_max_u32" | "v_min_u32" => {
  8797. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8798. let p = match name {
  8799. "v_max_i32" => pred::SGT,
  8800. "v_min_i32" => pred::SLT,
  8801. "v_max_u32" => pred::IUGT,
  8802. _ => pred::IULT,
  8803. };
  8804. let t = self.s.m.cmp(c, p, a, b);
  8805. self.s.m.select(c, t, a, b)
  8806. }
  8807. "v_mul_hi_u32" | "v_mul_hi_i32" => {
  8808. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8809. self.mul_hi(a, b, name == "v_mul_hi_i32")
  8810. }
  8811. "v_alignbit_b32" | "v_alignbyte_b32" => {
  8812. // The low dword of {a, b} >> shift.
  8813. let (a, b, sh) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8814. let sh = if name == "v_alignbyte_b32" {
  8815. let three = k(self, 3);
  8816. let t = self.s.m.bin(c, Bin::And, sh, three);
  8817. let k3 = k(self, 3);
  8818. self.s.m.bin(c, Bin::Shl, t, k3)
  8819. } else {
  8820. m31(self, sh)
  8821. };
  8822. let k32 = k(self, 32);
  8823. let lo = self.s.m.bin(c, Bin::LShr, b, sh);
  8824. let left = self.s.m.bin(c, Bin::Sub, k32, sh);
  8825. let left = m31(self, left);
  8826. let hi = self.s.m.bin(c, Bin::Shl, a, left);
  8827. let zero = k(self, 0);
  8828. let none = self.s.m.cmp(c, pred::EQ, sh, zero);
  8829. let hi = self.s.m.select(c, none, zero, hi);
  8830. self.s.m.bin(c, Bin::Or, lo, hi)
  8831. }
  8832. "v_bfrev_b32" => {
  8833. let a = s(self, 0)?;
  8834. self.s
  8835. .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a])
  8836. }
  8837. "v_bcnt_u32_b32" => {
  8838. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8839. let n = self
  8840. .s
  8841. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[a]);
  8842. self.s.m.bin(c, Bin::Add, n, b)
  8843. }
  8844. "v_mad_u32_u24" | "v_mad_i32_i24" => {
  8845. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8846. let (sh, op) = (
  8847. k(self, 8),
  8848. if name == "v_mad_i32_i24" {
  8849. Bin::AShr
  8850. } else {
  8851. Bin::LShr
  8852. },
  8853. );
  8854. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  8855. let a = self.s.m.bin(c, op, a, sh);
  8856. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  8857. let b = self.s.m.bin(c, op, b, sh);
  8858. let m = self.s.m.bin(c, Bin::Mul, a, b);
  8859. self.s.m.bin(c, Bin::Add, m, d)
  8860. }
  8861. "v_min3_i32" | "v_max3_i32" | "v_min3_u32" | "v_max3_u32" | "v_med3_i32"
  8862. | "v_med3_u32" => {
  8863. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8864. let signed = name.ends_with("i32");
  8865. let (lt, gt) = if signed {
  8866. (pred::SLT, pred::SGT)
  8867. } else {
  8868. (pred::IULT, pred::IUGT)
  8869. };
  8870. let pick = |l: &mut Self, p, x, y| {
  8871. let t = l.s.m.cmp(c, p, x, y);
  8872. l.s.m.select(c, t, x, y)
  8873. };
  8874. match &name[2..6] {
  8875. "min3" => {
  8876. let t = pick(self, lt, a, b);
  8877. pick(self, lt, t, d)
  8878. }
  8879. "max3" => {
  8880. let t = pick(self, gt, a, b);
  8881. pick(self, gt, t, d)
  8882. }
  8883. _ => {
  8884. let lo = pick(self, lt, a, b);
  8885. let hi = pick(self, gt, a, b);
  8886. let t = pick(self, lt, hi, d);
  8887. pick(self, gt, lo, t)
  8888. }
  8889. }
  8890. }
  8891. "v_perm_b32" => {
  8892. // Byte i of the result is byte S of {src0, src1} (src1 the
  8893. // low dword) for selector byte S below 8; 8-11 repeat the
  8894. // sign of bytes 1 and 3 of src1, then of src0; 12 is 0x00,
  8895. // higher 0xFF.
  8896. let Fields::Valu(v) = &inst.fields else {
  8897. unreachable!()
  8898. };
  8899. let sel = match v.src.get(2) {
  8900. Some(&Operand::Literal(x)) => x,
  8901. Some(&Operand::Const(k)) => crate::resource::inline(k).ok_or(name)?,
  8902. _ => {
  8903. // A computed selector: each byte picked at run time.
  8904. let (a, b, sv) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  8905. let mut r = k(self, 0);
  8906. for i in 0..4u32 {
  8907. let (sh, ff) = (k(self, 8 * i), k(self, 0xFF));
  8908. let sel = self.s.m.bin(c, Bin::LShr, sv, sh);
  8909. let sel = self.s.m.bin(c, Bin::And, sel, ff);
  8910. // Select a dword and a byte within it.
  8911. // Later selects handle codes 8 and above.
  8912. let four = k(self, 4);
  8913. let zero = k(self, 0);
  8914. let high = self.s.m.bin(c, Bin::And, sel, four);
  8915. let high = self.s.m.cmp(c, pred::NE, high, zero);
  8916. let word = self.s.m.select(c, high, a, b);
  8917. let three = k(self, 3);
  8918. let index = self.s.m.bin(c, Bin::And, sel, three);
  8919. let bits = self.s.m.bin(c, Bin::Shl, index, three);
  8920. let x = self.s.m.bin(c, Bin::LShr, word, bits);
  8921. let mut byte = self.s.m.bin(c, Bin::And, x, ff);
  8922. // 8-11: the sign of bytes 1, 3 of src1, then of src0.
  8923. for (n, src, bit) in [(8, b, 15), (9, b, 31), (10, a, 15), (11, a, 31)]
  8924. {
  8925. let left = k(self, 31 - bit);
  8926. let t = self.s.m.bin(c, Bin::Shl, src, left);
  8927. let k31 = k(self, 31);
  8928. let t = self.s.m.bin(c, Bin::AShr, t, k31);
  8929. let t = self.s.m.bin(c, Bin::And, t, ff);
  8930. let kn = k(self, n);
  8931. let is = self.s.m.cmp(c, pred::EQ, sel, kn);
  8932. byte = self.s.m.select(c, is, t, byte);
  8933. }
  8934. let (k12, z) = (k(self, 12), k(self, 0));
  8935. let is12 = self.s.m.cmp(c, pred::EQ, sel, k12);
  8936. byte = self.s.m.select(c, is12, z, byte);
  8937. let above = self.s.m.cmp(c, pred::IUGT, sel, k12);
  8938. byte = self.s.m.select(c, above, ff, byte);
  8939. let at = k(self, 8 * i);
  8940. let byte = self.s.m.bin(c, Bin::Shl, byte, at);
  8941. r = self.s.m.bin(c, Bin::Or, r, byte);
  8942. }
  8943. return Ok(r);
  8944. }
  8945. };
  8946. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8947. let mut r = k(self, 0);
  8948. for i in 0..4 {
  8949. let pick = sel >> (8 * i) & 0xFF;
  8950. let byte = match pick {
  8951. 0..=7 => {
  8952. let (src, n) = if pick < 4 { (b, pick) } else { (a, pick - 4) };
  8953. let sh = k(self, 8 * n);
  8954. let t = self.s.m.bin(c, Bin::LShr, src, sh);
  8955. let ff = k(self, 0xFF);
  8956. self.s.m.bin(c, Bin::And, t, ff)
  8957. }
  8958. 8..=11 => {
  8959. let src = if pick < 10 { b } else { a };
  8960. let bit = if pick % 2 == 0 { 15 } else { 31 };
  8961. let left = k(self, 31 - bit);
  8962. let t = self.s.m.bin(c, Bin::Shl, src, left);
  8963. let k31 = k(self, 31);
  8964. let t = self.s.m.bin(c, Bin::AShr, t, k31);
  8965. let ff = k(self, 0xFF);
  8966. self.s.m.bin(c, Bin::And, t, ff)
  8967. }
  8968. 12 => continue,
  8969. _ => k(self, 0xFF),
  8970. };
  8971. let at = k(self, 8 * i);
  8972. let byte = self.s.m.bin(c, Bin::Shl, byte, at);
  8973. r = self.s.m.bin(c, Bin::Or, r, byte);
  8974. }
  8975. r
  8976. }
  8977. "v_bfm_b32" => {
  8978. // ((1 << src0[4:0]) - 1) << src1[4:0]
  8979. let (a, b) = (s(self, 0)?, s(self, 1)?);
  8980. let one = k(self, 1);
  8981. let (a, b) = (m31(self, a), m31(self, b));
  8982. let m = self.s.m.bin(c, Bin::Shl, one, a);
  8983. let m = self.s.m.bin(c, Bin::Sub, m, one);
  8984. self.s.m.bin(c, Bin::Shl, m, b)
  8985. }
  8986. "v_cvt_pk_u8_f32" => {
  8987. // src0 rounded to nearest even and saturated to a byte, into
  8988. // byte src1[1:0] of src2.
  8989. let f = self.fsrc(inst, 0)?;
  8990. let (b, d) = (s(self, 1)?, s(self, 2)?);
  8991. let f = self.unary(26, f);
  8992. let (zero, max) = (self.s.m.f32(0), self.s.m.f32(255.0f32.to_bits()));
  8993. let f = self.binary(35, f, zero);
  8994. let f = self.binary(36, f, max);
  8995. let x = self.s.m.cast(c, Cast::FpToUi, f, self.s.t.i32);
  8996. let (three, k3) = (k(self, 3), k(self, 3));
  8997. let sh = self.s.m.bin(c, Bin::And, b, three);
  8998. let sh = self.s.m.bin(c, Bin::Shl, sh, k3);
  8999. let x = self.s.m.bin(c, Bin::Shl, x, sh);
  9000. let ff = k(self, 0xFF);
  9001. let hole = self.s.m.bin(c, Bin::Shl, ff, sh);
  9002. let ones = k(self, u32::MAX);
  9003. let hole = self.s.m.bin(c, Bin::Xor, hole, ones);
  9004. let d = self.s.m.bin(c, Bin::And, d, hole);
  9005. self.s.m.bin(c, Bin::Or, d, x)
  9006. }
  9007. "v_ffbl_b32" => {
  9008. // -1 for zero, as DXIL's first-bit-low.
  9009. let a = s(self, 0)?;
  9010. self.s
  9011. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 32, &[a])
  9012. }
  9013. "v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32" => {
  9014. // Bits of the mask's low (high) half below this lane, plus src1:
  9015. // with an all-ones mask, the lane index.
  9016. let (a, b) = (s(self, 0)?, s(self, 1)?);
  9017. // Mesh lanes are the console's by construction; pixel and
  9018. // vertex lanes are the host's, as their masks are.
  9019. if self.mask_data == MaskData::Host {
  9020. // Host lanes: the mask must be one (a ballot) or all lanes.
  9021. let Fields::Valu(v) = &inst.fields else {
  9022. unreachable!()
  9023. };
  9024. let host = match v.src.first() {
  9025. Some(&Operand::Const(193)) => true,
  9026. Some(&Operand::Scalar { code, .. }) => {
  9027. inst.read(Reg::S(code)).is_some_and(|m| {
  9028. self.x.st.masks.contains_key(&m) || self.x.st.highs.contains_key(&m)
  9029. })
  9030. }
  9031. _ => false,
  9032. };
  9033. if !host {
  9034. return Err("v_mbcnt of a mask that is no ballot (console lane layout)");
  9035. }
  9036. self.s.flags |= flags::WAVE_OPS;
  9037. } else if self.s.mesh.is_none() {
  9038. self.cross_lane(false)?;
  9039. }
  9040. let lane = self.console_lane();
  9041. let below = if name == "v_mbcnt_lo_u32_b32" {
  9042. lane
  9043. } else {
  9044. let (k32, z) = (k(self, 32), k(self, 0));
  9045. let t = self.s.m.bin(c, Bin::Sub, lane, k32);
  9046. let low = self.s.m.cmp(c, pred::IULT, lane, k32);
  9047. self.s.m.select(c, low, z, t)
  9048. };
  9049. // (1 << below) - 1, all ones from 32 on.
  9050. let (one, k32, ones) = (k(self, 1), k(self, 32), k(self, u32::MAX));
  9051. let sh = m31(self, below);
  9052. let m = self.s.m.bin(c, Bin::Shl, one, sh);
  9053. let m = self.s.m.bin(c, Bin::Sub, m, one);
  9054. let full = self.s.m.cmp(c, pred::IUGE, below, k32);
  9055. let m = self.s.m.select(c, full, ones, m);
  9056. let x = self.s.m.bin(c, Bin::And, a, m);
  9057. let n = self
  9058. .s
  9059. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[x]);
  9060. self.s.m.bin(c, Bin::Add, n, b)
  9061. }
  9062. _ => return Err(name),
  9063. })
  9064. }
  9065. fn compare(&mut self, inst: &Inst, rest: &str) -> Result<(), Why> {
  9066. let (op, ty) = rest.rsplit_once('_').ok_or("a compare")?;
  9067. let c = self.cur;
  9068. let r = match ty {
  9069. "f32" | "f16" if op == "class" => {
  9070. // Bit k of src1 tests class k: signalling NaN, quiet NaN,
  9071. // -inf, -normal, -denormal, -0, +0, +denormal, +normal, +inf.
  9072. let f16 = ty == "f16";
  9073. let x = if f16 {
  9074. let Fields::Valu(v) = &inst.fields else {
  9075. unreachable!()
  9076. };
  9077. let mut h = self.half_src(inst, 0)?;
  9078. if v.abs & 1 != 0 {
  9079. let m = self.s.m.i32(0x7FFF);
  9080. h = self.s.m.bin(c, Bin::And, h, m);
  9081. }
  9082. if v.neg & 1 != 0 {
  9083. let s = self.s.m.i32(0x8000);
  9084. h = self.s.m.bin(c, Bin::Xor, h, s);
  9085. }
  9086. h
  9087. } else {
  9088. let x = self.fsrc(inst, 0)?;
  9089. self.as_int(x)
  9090. };
  9091. let mask = self.src(inst, 1)?;
  9092. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  9093. let (exp_sh, sign_sh, exp_mask, mant_mask, quiet_bit) = if f16 {
  9094. (10, 15, 0x1F, 0x03FF, 0x0200)
  9095. } else {
  9096. (23, 31, 0xFF, 0x7F_FFFF, 0x40_0000)
  9097. };
  9098. let (k_exp, k_sign, k_emax, mant, quiet) = (
  9099. k(self, exp_sh),
  9100. k(self, sign_sh),
  9101. k(self, exp_mask),
  9102. k(self, mant_mask),
  9103. k(self, quiet_bit),
  9104. );
  9105. let e = self.s.m.bin(c, Bin::LShr, x, k_exp);
  9106. let e = self.s.m.bin(c, Bin::And, e, k_emax);
  9107. let m = self.s.m.bin(c, Bin::And, x, mant);
  9108. let neg = self.s.m.bin(c, Bin::LShr, x, k_sign);
  9109. let zero = k(self, 0);
  9110. let (e0, emax) = (
  9111. self.s.m.cmp(c, pred::EQ, e, zero),
  9112. self.s.m.cmp(c, pred::EQ, e, k_emax),
  9113. );
  9114. let m0 = self.s.m.cmp(c, pred::EQ, m, zero);
  9115. let q = self.s.m.bin(c, Bin::And, x, quiet);
  9116. let q = self.s.m.cmp(c, pred::NE, q, zero);
  9117. // Positive classes 6-9; negative ones are 11 minus those.
  9118. let (normal, inf, zero_c, denorm) =
  9119. (k(self, 8), k(self, 9), k(self, 6), k(self, 7));
  9120. let t = self.s.m.select(c, m0, zero_c, denorm);
  9121. let t = self.s.m.select(c, e0, t, normal);
  9122. let t = self.s.m.select(c, emax, inf, t);
  9123. let eleven = k(self, 11);
  9124. let mirrored = self.s.m.bin(c, Bin::Sub, eleven, t);
  9125. let is_neg = self.s.m.cmp(c, pred::NE, neg, zero);
  9126. let t = self.s.m.select(c, is_neg, mirrored, t);
  9127. let (one, snan) = (k(self, 1), k(self, 0));
  9128. let nan_class = self.s.m.select(c, q, one, snan);
  9129. let yes = self.s.m.bool(true);
  9130. let nan = self.s.m.bin(c, Bin::Xor, m0, yes);
  9131. let nan = self.s.m.bin(c, Bin::And, nan, emax);
  9132. let t = self.s.m.select(c, nan, nan_class, t);
  9133. let bit = self.s.m.bin(c, Bin::LShr, mask, t);
  9134. let bit = self.s.m.bin(c, Bin::And, bit, one);
  9135. self.s.m.cmp(c, pred::NE, bit, zero)
  9136. }
  9137. "f32" | "f16" => {
  9138. let (a, b) = if ty == "f16" {
  9139. (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?)
  9140. } else {
  9141. (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?)
  9142. };
  9143. if op == "lg" {
  9144. // Ordered and not equal, false for a NaN, as `olt | ogt`.
  9145. // `fcmp one` means the same, but the AMD D3D12 driver
  9146. // runs it as unordered (true for a NaN) where NVIDIA
  9147. // and WARP do not; olt and ogt agree on all three.
  9148. let lt = self.s.m.cmp(c, pred::OLT, a, b);
  9149. let gt = self.s.m.cmp(c, pred::OGT, a, b);
  9150. self.s.m.bin(c, Bin::Or, lt, gt)
  9151. } else {
  9152. let p = match op {
  9153. "f" => pred::FALSE,
  9154. "lt" => pred::OLT,
  9155. "eq" => pred::OEQ,
  9156. "le" => pred::OLE,
  9157. "gt" => pred::OGT,
  9158. "ge" => pred::OGE,
  9159. "o" => pred::ORD,
  9160. "u" => pred::UNO,
  9161. "nge" => pred::ULT,
  9162. "nlg" => pred::UEQ,
  9163. "ngt" => pred::ULE,
  9164. "nle" => pred::UGT,
  9165. "neq" => pred::UNE,
  9166. "nlt" => pred::UGE,
  9167. "tru" => pred::TRUE,
  9168. _ => return Err(inst.name()),
  9169. };
  9170. self.s.m.cmp(c, p, a, b)
  9171. }
  9172. }
  9173. "u64" | "i64" => {
  9174. let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?);
  9175. let signed = ty == "i64";
  9176. let p = match op {
  9177. "eq" => pred::EQ,
  9178. "ne" | "lg" => pred::NE,
  9179. "lt" if signed => pred::SLT,
  9180. "le" if signed => pred::SLE,
  9181. "gt" if signed => pred::SGT,
  9182. "ge" if signed => pred::SGE,
  9183. "lt" => pred::IULT,
  9184. "le" => pred::IULE,
  9185. "gt" => pred::IUGT,
  9186. "ge" => pred::IUGE,
  9187. _ => return Err("a 64-bit compare"),
  9188. };
  9189. self.s.m.cmp(c, p, a, b)
  9190. }
  9191. "u32" | "i32" | "u16" | "i16" => {
  9192. let (a, b) = if ty.ends_with("16") {
  9193. let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
  9194. if ty == "i16" {
  9195. let k16 = self.s.m.i32(16);
  9196. for x in [&mut a, &mut b] {
  9197. let t = self.s.m.bin(c, Bin::Shl, *x, k16);
  9198. *x = self.s.m.bin(c, Bin::AShr, t, k16);
  9199. }
  9200. }
  9201. (a, b)
  9202. } else {
  9203. (self.src(inst, 0)?, self.src(inst, 1)?)
  9204. };
  9205. let signed = ty == "i32" || ty == "i16";
  9206. let p = match op {
  9207. "eq" => pred::EQ,
  9208. "ne" | "lg" => pred::NE,
  9209. "lt" if signed => pred::SLT,
  9210. "le" if signed => pred::SLE,
  9211. "gt" if signed => pred::SGT,
  9212. "ge" if signed => pred::SGE,
  9213. "lt" => pred::IULT,
  9214. "le" => pred::IULE,
  9215. "gt" => pred::IUGT,
  9216. "ge" => pred::IUGE,
  9217. "f" | "t" => {
  9218. self.lane(inst, Some(op == "t"));
  9219. return Ok(());
  9220. }
  9221. _ => return Err("an integer compare"),
  9222. };
  9223. self.s.m.cmp(c, p, a, b)
  9224. }
  9225. _ => return Err(inst.name()),
  9226. };
  9227. self.lane_bits_for(inst, r);
  9228. Ok(())
  9229. }
  9230. fn lane(&mut self, inst: &Inst, value: Option<bool>) {
  9231. let b = self.s.m.bool(value == Some(true));
  9232. self.lane_bits_for(inst, b);
  9233. }
  9234. fn lane_bits_for(&mut self, inst: &Inst, r: V) {
  9235. let Fields::Valu(v) = &inst.fields else {
  9236. return;
  9237. };
  9238. let code = if inst.name().starts_with("v_cmpx") {
  9239. Some(EXEC)
  9240. } else {
  9241. match v.dst {
  9242. Some(Operand::Scalar { code, .. }) => Some(code),
  9243. _ => None,
  9244. }
  9245. };
  9246. if let Some(lo) = code.and_then(|c| inst.write(Reg::S(c))) {
  9247. self.lane_bits.insert(lo, r);
  9248. }
  9249. for &(_, w) in &inst.writes {
  9250. self.vals
  9251. .entry(w)
  9252. .or_insert(Val::Missing("a lane mask read as data"));
  9253. }
  9254. }
  9255. fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  9256. let Some(&interp) = self.interps.get(&site) else {
  9257. return Err("the first half of an interpolation");
  9258. };
  9259. let name = inst.name();
  9260. let (dst, src) = match &inst.fields {
  9261. Fields::Vintrp { dst, src, .. } => (*dst, Some(*src)),
  9262. Fields::Valu(v) => {
  9263. if v.abs != 0 || v.neg != 0 {
  9264. return Err("interpolation operand modifiers");
  9265. }
  9266. (v.dst.ok_or("an interpolation")?, v.src.get(1).copied())
  9267. }
  9268. _ => unreachable!(),
  9269. };
  9270. let Operand::Vector { reg, .. } = dst else {
  9271. return Err("an interpolation");
  9272. };
  9273. // A float operand of the instruction.
  9274. let float = |l: &mut Self, op: Option<Operand>| -> Result<V, Why> {
  9275. let x = l.operand(inst, &op.ok_or("an interpolation operand")?)?;
  9276. Ok(l.as_float(x))
  9277. };
  9278. // What the result adds to the evaluated channel (a second half's
  9279. // first half, when the halves evaluate on their own).
  9280. let mut add = None;
  9281. let (attribute, eval) = match *interp {
  9282. Interp::Interpolated {
  9283. attribute,
  9284. barycentric,
  9285. ..
  9286. } => {
  9287. let mode = interp_mode(barycentric).ok_or("pull-model interpolation")?;
  9288. let eval = if self.per_vertex(attribute.row) {
  9289. // The element is read per vertex elsewhere, so it is
  9290. // constant: weigh its vertices with SV_Barycentrics.
  9291. let mut ij = [None; 2];
  9292. for (index, w) in ij.iter_mut().enumerate() {
  9293. let x = match self.barycentric(barycentric, index as u8) {
  9294. Val::I32(x) => x,
  9295. Val::Missing(w) => return Err(w),
  9296. Val::Bit(_) => unreachable!(),
  9297. };
  9298. *w = Some(self.as_float(x));
  9299. }
  9300. Eval::Weights {
  9301. p0: true,
  9302. i: ij[0],
  9303. j: ij[1],
  9304. }
  9305. } else {
  9306. Eval::Mode(mode)
  9307. };
  9308. (attribute, eval)
  9309. }
  9310. // P0, the provoking vertex: a flat (nointerpolation) input.
  9311. Interp::Vertex {
  9312. attribute,
  9313. vertex: 2,
  9314. } => (attribute, Eval::Mode(1)),
  9315. // P10 and P20: what the first and second halves weigh, P1 - P0
  9316. // and P2 - P0, which is what the hardware holds for an
  9317. // attribute the program also interpolates.
  9318. Interp::Vertex { attribute, vertex } if self.interpolated(attribute.row) => {
  9319. let one = Some(self.s.m.f32(1f32.to_bits()));
  9320. let (i, j) = if vertex == 0 {
  9321. (one, None)
  9322. } else {
  9323. (None, one)
  9324. };
  9325. (attribute, Eval::Weights { p0: false, i, j })
  9326. }
  9327. Interp::Vertex { .. } => return Err("a non-provoking vertex value"),
  9328. // A half of an interpolation with computed i or j: P0 + i P10,
  9329. // or the old dst (f16: the third operand) + j P20.
  9330. Interp::Weighted { attribute } if name.starts_with("v_interp_p1") => {
  9331. let i = Some(float(self, src)?);
  9332. (
  9333. attribute,
  9334. Eval::Weights {
  9335. p0: true,
  9336. i,
  9337. j: None,
  9338. },
  9339. )
  9340. }
  9341. Interp::Weighted { attribute } => {
  9342. let old = match &inst.fields {
  9343. Fields::Valu(v) => v.src.get(2).copied(),
  9344. _ => Some(dst),
  9345. };
  9346. add = Some(float(self, old)?);
  9347. let j = Some(float(self, src)?);
  9348. (
  9349. attribute,
  9350. Eval::Weights {
  9351. p0: false,
  9352. i: None,
  9353. j,
  9354. },
  9355. )
  9356. }
  9357. };
  9358. let packing = match &self.x.native.io {
  9359. StageIo::Ps { inputs, .. } => inputs
  9360. .iter()
  9361. .find(|i| i.row == attribute.row && i.fp16)
  9362. .map(|i| {
  9363. let packs = if i.pack2 {
  9364. input_packs(&self.x.native.io, &self.s.inputs)
  9365. } else {
  9366. Vec::new()
  9367. };
  9368. (i.pack2, packs)
  9369. }),
  9370. _ => None,
  9371. };
  9372. let f16 = name.ends_with("_f16");
  9373. // The evaluated channel plus `add`, as a float.
  9374. let total = |l: &mut Self, row: u8, ch: u8| -> Result<V, Why> {
  9375. let x = l.eval_channel(row, ch, eval)?;
  9376. let x = l.as_float(x);
  9377. Ok(match add {
  9378. Some(a) => l.s.m.bin(l.cur, Bin::Add, a, x),
  9379. None => x,
  9380. })
  9381. };
  9382. let x = match packing {
  9383. None if f16 || attribute.high => return Err("a 16-bit read of a 32-bit input"),
  9384. None => {
  9385. let x = total(self, attribute.row, attribute.channel)?;
  9386. self.as_int(x)
  9387. }
  9388. Some((pack2, packs)) => {
  9389. // 16-bit values: one in the low half of each dword, or two
  9390. // per dword (`packed_half`); the host's are 32-bit floats.
  9391. let half = |l: &mut Self, h: u8| -> Result<Option<V>, Why> {
  9392. let src = if pack2 {
  9393. packed_half(&l.s.inputs, &packs, attribute.row, h)
  9394. } else {
  9395. h.is_multiple_of(2).then_some((attribute.row, h / 2))
  9396. };
  9397. match src {
  9398. Some((row, ch)) => total(l, row, ch).map(Some),
  9399. None => Ok(None),
  9400. }
  9401. };
  9402. let to_f16 = |l: &mut Self, f: V| {
  9403. let i32t = l.s.t.i32;
  9404. l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  9405. };
  9406. let h = 2 * attribute.channel + u8::from(attribute.high);
  9407. let c = self.cur;
  9408. if name == "v_interp_p1ll_f16" {
  9409. // An f32 result from 16-bit vertex values.
  9410. let f = half(self, h)?.ok_or("a packed input half no element holds")?;
  9411. self.as_int(f)
  9412. } else if f16 {
  9413. let f = half(self, h)?.ok_or("a packed input half no element holds")?;
  9414. let lo = to_f16(self, f);
  9415. self.low_half(inst, reg, lo)
  9416. } else if matches!(eval, Eval::Mode(1)) {
  9417. // The whole dword of a flat input: both halves.
  9418. let h = 2 * attribute.channel;
  9419. let z = self.s.m.i32(0);
  9420. let lo = match half(self, h)? {
  9421. Some(f) => to_f16(self, f),
  9422. None => z,
  9423. };
  9424. let hi = match half(self, h + 1)? {
  9425. Some(f) => to_f16(self, f),
  9426. None => z,
  9427. };
  9428. let k16 = self.s.m.i32(16);
  9429. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  9430. self.s.m.bin(c, Bin::Or, lo, hi)
  9431. } else {
  9432. return Err("32-bit interpolation of a 16-bit input");
  9433. }
  9434. }
  9435. };
  9436. // A pixel interpolates in every lane; guards only hide inactive ones.
  9437. self.write(inst, Reg::V(reg), x, None);
  9438. Ok(())
  9439. }
  9440. /// Whether the program reads attribute row `row` per vertex (an
  9441. /// interpolation with computed barycentrics, or P10 or P20): then its
  9442. /// element is declared constant and read with `attributeAtVertex`.
  9443. fn per_vertex(&self, row: u8) -> bool {
  9444. self.x.io.interps.iter().any(|(_, i)| match *i {
  9445. Interp::Weighted { attribute } => attribute.row == row,
  9446. Interp::Vertex { attribute, vertex } => {
  9447. attribute.row == row && vertex != 2 && self.interpolated(row)
  9448. }
  9449. Interp::Interpolated { .. } => false,
  9450. })
  9451. }
  9452. /// Whether the program interpolates attribute row `row` (so the
  9453. /// hardware holds P1 - P0 and P2 - P0 for it).
  9454. fn interpolated(&self, row: u8) -> bool {
  9455. self.x.io.interps.iter().any(|(_, i)| match *i {
  9456. Interp::Interpolated { attribute, .. } | Interp::Weighted { attribute } => {
  9457. attribute.row == row
  9458. }
  9459. Interp::Vertex { .. } => false,
  9460. })
  9461. }
  9462. /// Channel `ch` of input row `row` evaluated as `eval` says, as raw bits.
  9463. fn eval_channel(&mut self, row: u8, ch: u8, eval: Eval) -> Result<V, Why> {
  9464. let (id, col) = self
  9465. .find_input(row, ch)
  9466. .ok_or("an input the signature lacks")?;
  9467. let mode = match eval {
  9468. Eval::Mode(mode) => mode,
  9469. Eval::Weights { .. } => 1,
  9470. };
  9471. let e = &mut self.s.inputs[id];
  9472. if e.interp != mode && e.usage != 0 {
  9473. return Err("one input interpolated two ways");
  9474. }
  9475. e.interp = mode;
  9476. let Eval::Weights { p0, i, j } = eval else {
  9477. return match self.load_any_input(id, col) {
  9478. Val::I32(x) => Ok(x),
  9479. _ => Err("an input"),
  9480. };
  9481. };
  9482. let v0 = self.vertex_input(id, col, 0);
  9483. let c = self.cur;
  9484. let mut acc = p0.then_some(v0);
  9485. for (k, w) in [(1, i), (2, j)] {
  9486. let Some(w) = w else { continue };
  9487. let vk = self.vertex_input(id, col, k);
  9488. let d = self.s.m.bin(c, Bin::Sub, vk, v0);
  9489. acc = Some(match acc {
  9490. Some(a) => self.fmad(w, d, a),
  9491. None => self.s.m.bin(c, Bin::Mul, w, d),
  9492. });
  9493. }
  9494. let acc = acc.ok_or("an interpolation")?;
  9495. Ok(self.as_int(acc))
  9496. }
  9497. /// Vertex `k` (0 the provoking vertex, as `barycentric` orders them)
  9498. /// of a constant input element's channel, as a float.
  9499. fn vertex_input(&mut self, id: usize, col: u8, k: u8) -> V {
  9500. let e = &mut self.s.inputs[id];
  9501. e.usage |= 1 << col;
  9502. let int = e.comp != 9;
  9503. let (ty, suffix) = if int {
  9504. (self.s.t.i32, ".i32")
  9505. } else {
  9506. (self.s.t.f32, ".f32")
  9507. };
  9508. self.s.flags |= flags::BARYCENTRICS;
  9509. let entry = self.s.entry;
  9510. let args = [
  9511. self.s.m.i32(id as u32),
  9512. self.s.m.i32(0),
  9513. self.s.m.i8(col),
  9514. self.s.m.i8(k),
  9515. ];
  9516. let v = self.s.op(
  9517. entry,
  9518. &format!("attributeAtVertex{suffix}"),
  9519. Attr::ReadNone,
  9520. ty,
  9521. 137,
  9522. &args,
  9523. );
  9524. if int {
  9525. self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.f32)
  9526. } else {
  9527. v
  9528. }
  9529. }
  9530. /// `x` (an f16 in the low bits) as the low half of VGPR `reg`: 16-bit
  9531. /// results keep the register's high half (GFX10).
  9532. fn low_half(&mut self, inst: &Inst, reg: u8, x: V) -> V {
  9533. let c = self.cur;
  9534. let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) {
  9535. Some(Ok(o)) => o,
  9536. _ => self.s.m.i32(0),
  9537. };
  9538. let (high, low) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF));
  9539. let old = self.s.m.bin(c, Bin::And, old, high);
  9540. let x = self.s.m.bin(c, Bin::And, x, low);
  9541. self.s.m.bin(c, Bin::Or, old, x)
  9542. }
  9543. fn image(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  9544. let Fields::Image {
  9545. data,
  9546. addr,
  9547. dmask,
  9548. dim,
  9549. unorm,
  9550. a16,
  9551. d16,
  9552. tfe,
  9553. lwe,
  9554. ..
  9555. } = &inst.fields
  9556. else {
  9557. unreachable!()
  9558. };
  9559. if *tfe || *lwe {
  9560. return Err("an image access with tfe or lwe");
  9561. }
  9562. let name = inst.name();
  9563. // A load or sample with no channel enabled returns the first.
  9564. let dmask = if *dmask == 0 { &1 } else { dmask };
  9565. let site = (b, i);
  9566. let guard = self.guard(b, i)?;
  9567. let c = self.cur;
  9568. let (kind, coords) = match dim {
  9569. 0 => (1, 1),
  9570. 1 => (2, 2),
  9571. 2 => (4, 3),
  9572. // Sampled (face coordinates and face, see `cube_direction`) or
  9573. // sized only.
  9574. 3 if name.starts_with("image_sample")
  9575. || name.starts_with("image_gather")
  9576. || name == "image_get_resinfo" =>
  9577. {
  9578. (5, 3)
  9579. }
  9580. 4 => (6, 2),
  9581. 5 => (7, 3),
  9582. _ => return Err("an image dimension (cube loads or MSAA)"),
  9583. };
  9584. // Address VGPRs in order.
  9585. let mut regs = Vec::new();
  9586. for a in addr {
  9587. if let Operand::Vector { reg, dwords } = *a {
  9588. regs.extend((0..dwords).map(|k| reg + k));
  9589. }
  9590. }
  9591. // Full 32-bit address VGPR at `reg_idx` (offset, bias, z-compare).
  9592. let addr_u32 = |l: &mut Self, reg_idx: usize| -> Result<V, Why> {
  9593. let r = *regs.get(reg_idx).ok_or("an image address")?;
  9594. let v = inst.read(Reg::V(r)).ok_or("an image address")?;
  9595. l.i32_of(v)
  9596. };
  9597. // With a16, two 16-bit components per VGPR starting at `base_reg`, low half first.
  9598. let addr_packed = |l: &mut Self, base_reg: usize, k: usize| -> Result<V, Why> {
  9599. let x = addr_u32(l, base_reg + if *a16 { k / 2 } else { k })?;
  9600. if !*a16 {
  9601. return Ok(x);
  9602. }
  9603. let c = l.cur;
  9604. let (sh, mask) = (l.s.m.i32(16 * (k as u32 % 2)), l.s.m.i32(0xFFFF));
  9605. let x = l.s.m.bin(c, Bin::LShr, x, sh);
  9606. Ok(l.s.m.bin(c, Bin::And, x, mask))
  9607. };
  9608. let addr_val = |l: &mut Self, k: usize| -> Result<V, Why> { addr_packed(l, 0, k) };
  9609. let src = self
  9610. .descriptors
  9611. .get(&(site, false))
  9612. .copied()
  9613. .ok_or("an untracked image")?;
  9614. let store = name.starts_with("image_store");
  9615. let uav = store
  9616. || self
  9617. .used_kind(src)
  9618. .is_some_and(|u| u.kind == ResourceType::Uav);
  9619. // A UAV inside an ordered section is a rasterizer ordered view.
  9620. let ordered = uav && self.ordered.contains(&site);
  9621. if ordered {
  9622. self.s.flags |= flags::ROVS;
  9623. }
  9624. let rov = if ordered { 0x2000 } else { 0 };
  9625. let props = (kind | if uav { 0x1000 } else { 0 } | rov, 0x409);
  9626. if let Some(op) = name.strip_prefix("image_atomic_") {
  9627. // GLC returns the old value. DXIL implements subtraction by adding
  9628. // the two's complement of the operand at the same width.
  9629. let code = match op {
  9630. "add" | "sub" => 0,
  9631. "and" => 1,
  9632. "or" => 2,
  9633. "xor" => 3,
  9634. "smin" => 4,
  9635. "smax" => 5,
  9636. "umin" => 6,
  9637. "umax" => 7,
  9638. "swap" => 8,
  9639. "cmpswap" => u32::MAX,
  9640. _ => return Err(name),
  9641. };
  9642. let Fields::Image { cache, .. } = &inst.fields else {
  9643. unreachable!()
  9644. };
  9645. // 16-bit coordinates (a16) are read as `addr_val` reads them.
  9646. if *d16 {
  9647. return Err("a 16-bit image atomic");
  9648. }
  9649. // Compare-exchange consumes a replacement followed by a comparand.
  9650. let compare = code == u32::MAX;
  9651. let wide = match (compare, *dmask) {
  9652. (false, 1) | (true, 3) => false,
  9653. (false, 3) | (true, 15) => true,
  9654. _ => return Err("an image atomic data mask"),
  9655. };
  9656. let iu = self.s.m.undef(self.s.t.i32);
  9657. let mut cs = vec![iu; 3];
  9658. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  9659. *slot = addr_val(self, k)?;
  9660. }
  9661. let Operand::Vector { reg, .. } = *data else {
  9662. return Err("image atomic data");
  9663. };
  9664. let width = if wide { 2 } else { 1 };
  9665. let vals = self.vgprs(inst, data, if compare { 2 * width } else { width })?;
  9666. let (ty, component) = if wide {
  9667. self.s.flags |= flags::INT64 | flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64;
  9668. (self.s.m.int(64), 0x107) // one uint64_t in an R32G32_UINT view
  9669. } else {
  9670. (self.s.t.i32, 0x105)
  9671. };
  9672. let original = if wide {
  9673. self.join64(vals[0], vals[1])
  9674. } else {
  9675. vals[0]
  9676. };
  9677. let value = if op == "sub" {
  9678. let zero = self.s.m.int_const(ty, 0);
  9679. self.s.m.bin(c, Bin::Sub, zero, original)
  9680. } else {
  9681. original
  9682. };
  9683. let h = self.handle(site, src, false, (kind | 0x1000 | rov, component))?;
  9684. let mut args = vec![h];
  9685. let (intrinsic, opcode) = if compare {
  9686. let comparand = if wide {
  9687. self.join64(vals[2], vals[3])
  9688. } else {
  9689. vals[1]
  9690. };
  9691. args.extend(cs);
  9692. args.extend([comparand, value]);
  9693. let intrinsic = if wide {
  9694. "atomicCompareExchange.i64"
  9695. } else {
  9696. "atomicCompareExchange.i32"
  9697. };
  9698. (intrinsic, 79)
  9699. } else {
  9700. args.push(self.s.m.i32(code));
  9701. args.extend(cs);
  9702. args.push(value);
  9703. (
  9704. if wide {
  9705. "atomicBinOp.i64"
  9706. } else {
  9707. "atomicBinOp.i32"
  9708. },
  9709. 78,
  9710. )
  9711. };
  9712. let at = self.begin_guarded(guard);
  9713. let r = self
  9714. .s
  9715. .op(self.cur, intrinsic, Attr::NoUnwind, ty, opcode, &args);
  9716. if cache.glc {
  9717. let old = self.end_guarded(at, &[(r, original)])[0];
  9718. if wide {
  9719. let (lo, hi) = self.split64(old);
  9720. self.write(inst, Reg::V(reg), lo, None);
  9721. self.write(inst, Reg::V(reg + 1), hi, None);
  9722. } else {
  9723. self.write(inst, Reg::V(reg), old, None);
  9724. }
  9725. } else {
  9726. self.end_guarded(at, &[]);
  9727. }
  9728. return Ok(());
  9729. }
  9730. if store {
  9731. if name != "image_store" {
  9732. return Err("an image store to a mip level");
  9733. }
  9734. // shortcut: stores are taken to write all four channels of a
  9735. // float format (the console converts by the view's format).
  9736. // One channel goes into a view the program also counts in.
  9737. let counter = *dmask == 1 && self.is_counter(src);
  9738. if *dmask != 0xF && !counter {
  9739. return Err("an image store of some channels");
  9740. }
  9741. let iu = self.s.m.undef(self.s.t.i32);
  9742. let mut cs = vec![iu; 3];
  9743. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  9744. *slot = addr_val(self, k)?;
  9745. }
  9746. let Operand::Vector { reg, .. } = *data else {
  9747. return Err("image store data");
  9748. };
  9749. if counter {
  9750. let v = inst.read(Reg::V(reg)).ok_or("image store data")?;
  9751. let x = self.i32_of(v)?;
  9752. // A 16-bit integer, extended by the view's sign: the same
  9753. // number either way only if it is known to be small.
  9754. if *d16 && !self.s.m.int_k(x).is_some_and(|(_, k)| k < 0x8000) {
  9755. return Err("a 16-bit image store of one channel");
  9756. }
  9757. let h = self.handle(site, src, false, (kind | 0x1000 | rov, 0x105))?;
  9758. let at = self.begin_guarded(guard);
  9759. // All four channels are written (the validator wants them
  9760. // all): the view has the first alone.
  9761. let mut args = vec![h];
  9762. args.extend(cs);
  9763. args.extend([x; 4]);
  9764. args.push(self.s.m.i8(0xF));
  9765. let void = self.s.t.void;
  9766. self.s.op(
  9767. self.cur,
  9768. "textureStore.i32",
  9769. Attr::NoUnwind,
  9770. void,
  9771. 67,
  9772. &args,
  9773. );
  9774. self.end_guarded(at, &[]);
  9775. return Ok(());
  9776. }
  9777. let mut vals = Vec::new();
  9778. for k in 0..4u8 {
  9779. // d16: two f16 channels per VGPR, low half first.
  9780. let r = if *d16 { k / 2 } else { k };
  9781. let v = inst.read(Reg::V(reg + r)).ok_or("image store data")?;
  9782. vals.push(if *d16 {
  9783. let mut x = self.i32_of(v)?;
  9784. if k % 2 == 1 {
  9785. let k16 = self.s.m.i32(16);
  9786. x = self.s.m.bin(self.cur, Bin::LShr, x, k16);
  9787. }
  9788. let f32t = self.s.t.f32;
  9789. self.s
  9790. .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x])
  9791. } else {
  9792. self.float_of(v)?
  9793. });
  9794. }
  9795. let h = self.handle(site, src, false, props)?;
  9796. let at = self.begin_guarded(guard);
  9797. let mut args = vec![h];
  9798. args.extend(cs);
  9799. args.extend(vals);
  9800. args.push(self.s.m.i8(0xF));
  9801. let void = self.s.t.void;
  9802. self.s.op(
  9803. self.cur,
  9804. "textureStore.f32",
  9805. Attr::NoUnwind,
  9806. void,
  9807. 67,
  9808. &args,
  9809. );
  9810. self.end_guarded(at, &[]);
  9811. return Ok(());
  9812. }
  9813. let has_cl = name.ends_with("_cl");
  9814. let (op, sample) = match name {
  9815. "image_sample" | "image_sample_o" | "image_sample_cl" => (60, true),
  9816. "image_sample_lz" | "image_sample_l" | "image_sample_lz_o" => (62, true),
  9817. "image_sample_b" | "image_sample_b_cl" => (61, true),
  9818. "image_sample_c_lz" => (65, true),
  9819. "image_sample_d" | "image_sample_d_cl" => (63, true),
  9820. "image_get_lod" if self.s.pixel => (81, true),
  9821. // Implicit derivatives: pixel shaders only.
  9822. "image_sample_c" if self.s.pixel => (64, true),
  9823. "image_sample_c_cl" if self.s.pixel => (64, true),
  9824. "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" | "image_gather4_l" | "image_gather4_l_o" => (73, true),
  9825. "image_load" | "image_load_mip" => (66, false),
  9826. "image_get_resinfo" => (72, false),
  9827. _ => return Err(name),
  9828. };
  9829. if op == 72 {
  9830. // Width, height, depth or layers, levels (per dmask) of the level
  9831. // in the first address: DXIL's dimensions; a channel DXIL leaves
  9832. // out reads 1 (UAVs: one level).
  9833. let h = self.handle(site, src, false, props)?;
  9834. let mip = if uav {
  9835. self.s.m.undef(self.s.t.i32)
  9836. } else {
  9837. addr_val(self, 0)?
  9838. };
  9839. let i32t = self.s.t.i32;
  9840. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  9841. let d = self
  9842. .s
  9843. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  9844. let one = self.s.m.i32(1);
  9845. let present = match kind {
  9846. 1 => [true, false, false, true],
  9847. 2 | 5 | 6 => [true, true, false, true],
  9848. _ => [true, true, true, true],
  9849. };
  9850. let Operand::Vector { reg, .. } = *data else {
  9851. return Err("an image result");
  9852. };
  9853. for (k, ch) in (0..4u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() {
  9854. let x = if ch == 3 && uav || !present[ch as usize] {
  9855. one
  9856. } else {
  9857. self.s.m.extract(c, d, ch)
  9858. };
  9859. self.write(inst, Reg::V(reg + k as u8), x, guard);
  9860. }
  9861. return Ok(());
  9862. }
  9863. if uav && op != 66 {
  9864. return Err("sampling a UAV");
  9865. }
  9866. let h = self.handle(site, src, false, props)?;
  9867. let fu = self.s.m.undef(self.s.t.f32);
  9868. let iu = self.s.m.undef(self.s.t.i32);
  9869. // A gather at a named level, done as four texel reads (below).
  9870. let mut gathered: Option<[V; 4]> = None;
  9871. let r = if sample {
  9872. let ss = self
  9873. .descriptors
  9874. .get(&(site, true))
  9875. .copied()
  9876. .ok_or("an untracked sampler")?;
  9877. // Comparison: the reference value is the first address after
  9878. // the bias, and the sampler is a comparison sampler.
  9879. let cmp = matches!(op, 64 | 65);
  9880. if cmp && (*a16 || dmask.count_ones() != 1) {
  9881. return Err("a comparison sample of 16-bit coordinates or several channels");
  9882. }
  9883. let mut sampler_choice: Option<(V, Vec<u32>)> = None;
  9884. let sh = match ss {
  9885. Source::Phi { block, args } => {
  9886. match self.sampler_phi_choice(*block, args, cmp, 8) {
  9887. Ok((None, regs)) => self.s.sampler_handle(self.cur, regs[0]),
  9888. Ok((Some(idx), regs)) => {
  9889. let first = self.s.sampler_handle(self.cur, regs[0]);
  9890. sampler_choice = Some((idx, regs));
  9891. first
  9892. }
  9893. Err(_) => {
  9894. self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?
  9895. }
  9896. }
  9897. }
  9898. _ => self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?,
  9899. };
  9900. // Texel offsets (`_o`) come first: x in bits 0-5, y in 8-13,
  9901. // signed (programmable offsets: gathers only).
  9902. let offset_word = name.ends_with("_o");
  9903. let first = usize::from(offset_word)
  9904. + usize::from(name.starts_with("image_sample_b"))
  9905. + usize::from(cmp);
  9906. // Coordinates the size divides (not the array slice); explicit
  9907. // gradients (x then y) come before the coordinates.
  9908. let spatial = coords - usize::from(kind == 6 || kind == 7);
  9909. // A cube's gradients are the two of its face coordinates.
  9910. let grads = if kind == 5 { 2 } else { spatial };
  9911. let deriv_regs = if op == 63 {
  9912. if *a16 {
  9913. grads.div_ceil(2)
  9914. } else {
  9915. grads
  9916. }
  9917. } else {
  9918. 0
  9919. };
  9920. let coord_base = first + 2 * deriv_regs;
  9921. let mut cs = vec![fu; 4];
  9922. // With a16, sampling coordinates, gradients, LOD and clamp are f16.
  9923. let to_float = |l: &mut Self, x: V| {
  9924. if *a16 {
  9925. let f = l.s.t.f32;
  9926. l.s.op(l.cur, "legacyF16ToF32", Attr::ReadNone, f, 131, &[x])
  9927. } else {
  9928. l.as_float(x)
  9929. }
  9930. };
  9931. if kind == 5 && (*unorm || op == 81) {
  9932. return Err("a cube sample with texel coordinates or a level query");
  9933. }
  9934. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  9935. let x = addr_packed(self, coord_base, k)?;
  9936. *slot = to_float(self, x);
  9937. }
  9938. if kind == 5 {
  9939. let dir = self.cube_direction(cs[0], cs[1], cs[2]);
  9940. cs[..3].copy_from_slice(&dir);
  9941. }
  9942. if *unorm {
  9943. // Texel coordinates: divided by the size of level 0.
  9944. let i32t = self.s.t.i32;
  9945. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  9946. let z = self.s.m.i32(0);
  9947. let d = self
  9948. .s
  9949. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]);
  9950. for (k, slot) in cs.iter_mut().enumerate().take(spatial) {
  9951. let n = self.s.m.extract(c, d, k as u32);
  9952. let n = self.s.m.cast(c, Cast::UiToFp, n, self.s.t.f32);
  9953. *slot = self.s.m.bin(c, Bin::SDiv, *slot, n);
  9954. }
  9955. }
  9956. if op == 81 {
  9957. // The clamped then the unclamped level of detail.
  9958. let Operand::Vector { reg, .. } = *data else {
  9959. return Err("an image result");
  9960. };
  9961. let f32t = self.s.t.f32;
  9962. for (k, ch) in (0..2u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() {
  9963. let clamped = self.s.m.bool(ch == 0);
  9964. let lod = self.s.op(
  9965. c,
  9966. "calculateLOD.f32",
  9967. Attr::ReadOnly,
  9968. f32t,
  9969. 81,
  9970. &[h, sh, cs[0], cs[1], cs[2], clamped],
  9971. );
  9972. let x = self.as_int(lod);
  9973. self.write(inst, Reg::V(reg + k as u8), x, guard);
  9974. }
  9975. return Ok(());
  9976. }
  9977. let offsets = if kind == 5 {
  9978. 0
  9979. } else {
  9980. (coords - usize::from(kind == 6 || kind == 7)).min(3)
  9981. };
  9982. let zero = self.s.m.i32(0);
  9983. let mut os = vec![iu; 3];
  9984. for o in os.iter_mut().take(offsets) {
  9985. *o = zero;
  9986. }
  9987. if offset_word && offsets > 0 {
  9988. let w = addr_val(self, 0)?;
  9989. for (k, at) in [(0, 26), (1, 18)].into_iter().take(offsets.min(2)) {
  9990. // Bits at..at+5 sign-extended: shift up, then down.
  9991. let left = self.s.m.i32(at);
  9992. let t = self.s.m.bin(c, Bin::Shl, w, left);
  9993. let k26 = self.s.m.i32(26);
  9994. os[k] = self.s.m.bin(c, Bin::AShr, t, k26);
  9995. }
  9996. }
  9997. let mut args = vec![h, sh];
  9998. args.extend(&cs);
  9999. let clamp = if has_cl {
  10000. let x = addr_packed(self, coord_base, coords)?;
  10001. to_float(self, x)
  10002. } else {
  10003. fu
  10004. };
  10005. let call_sample = |l: &mut Self,
  10006. intrinsic: &str,
  10007. opcode: u32,
  10008. args: &[V],
  10009. gathered: &mut Option<[V; 4]>|
  10010. -> V {
  10011. let Some((idx, ref regs)) = sampler_choice else {
  10012. return l
  10013. .s
  10014. .op(c, intrinsic, Attr::ReadOnly, l.s.t.res_ret, opcode, args);
  10015. };
  10016. let merge = l.s.m.new_block();
  10017. let mut cur_test = c;
  10018. let mut per_ch: [Vec<(V, usize)>; 4] = Default::default();
  10019. let mut last_r = args[0];
  10020. for (i, &reg) in regs.iter().enumerate() {
  10021. let arm = if i + 1 == regs.len() {
  10022. cur_test
  10023. } else {
  10024. let arm = l.s.m.new_block();
  10025. let next = l.s.m.new_block();
  10026. let k = l.s.m.i32(i as u32);
  10027. let cond = l.s.m.cmp(cur_test, pred::EQ, idx, k);
  10028. l.s.m.terminate(cur_test, Term::CondBr(cond, arm, next));
  10029. cur_test = next;
  10030. arm
  10031. };
  10032. let mut arm_args = args.to_vec();
  10033. arm_args[1] = l.s.sampler_handle(arm, reg);
  10034. let r_i = l.s.op(
  10035. arm,
  10036. intrinsic,
  10037. Attr::ReadOnly,
  10038. l.s.t.res_ret,
  10039. opcode,
  10040. &arm_args,
  10041. );
  10042. for (ch, slot) in per_ch.iter_mut().enumerate() {
  10043. let v = l.s.m.extract(arm, r_i, ch as u32);
  10044. slot.push((v, arm));
  10045. }
  10046. l.s.m.terminate(arm, Term::Br(merge));
  10047. last_r = r_i;
  10048. }
  10049. let mut phis = [fu; 4];
  10050. for (ch, incoming) in per_ch.into_iter().enumerate() {
  10051. let phi = l.s.m.phi(merge, l.s.t.f32);
  10052. l.s.m.set_phi(phi, incoming);
  10053. phis[ch] = phi;
  10054. }
  10055. *gathered = Some(phis);
  10056. l.cur = merge;
  10057. last_r
  10058. };
  10059. match op {
  10060. // Outside a pixel shader there are no screen derivatives:
  10061. // the validator refuses `sample` there ("features
  10062. // incompatible with the shader stage": 730 compute programs,
  10063. // among them the G-buffer resolves and the sky), and what a
  10064. // driver does with it is its own affair.
  10065. // shortcut: such a sample reads level 0 (a bias: that
  10066. // level). The console takes derivatives from neighbouring
  10067. // lanes there; compute them from the lanes if a resolve
  10068. // shows the wrong mip.
  10069. 60 if !self.s.pixel => {
  10070. args.extend(&os);
  10071. args.push(self.s.m.f32(0));
  10072. call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
  10073. }
  10074. 60 => {
  10075. if offset_word {
  10076. // DXIL wants immediate offsets in -8..=7 here; the
  10077. // console's are 6-bit and may be computed. A
  10078. // constant word in range becomes immediates
  10079. // (upstream PR #634); anything else keeps the
  10080. // offsets computed above (upstream refuses those).
  10081. let w = addr_val(self, 0)?;
  10082. if let Some(w) = self.s.m.int_value(w) {
  10083. let w = w as u32;
  10084. let field = |k: usize| {
  10085. let x = (w >> (8 * k) & 0x3F) as i32;
  10086. if x >= 32 { x - 64 } else { x }
  10087. };
  10088. let n = offsets.min(2);
  10089. if (0..n).all(|k| (-8..=7).contains(&field(k))) {
  10090. for (k, o) in os.iter_mut().enumerate().take(n) {
  10091. *o = self.s.m.i32(field(k) as u32);
  10092. }
  10093. }
  10094. }
  10095. }
  10096. args.extend(&os);
  10097. args.push(clamp);
  10098. call_sample(self, "sample.f32", 60, &args, &mut gathered)
  10099. }
  10100. 61 => {
  10101. // With a16 the bias is an f16 in the low half of its
  10102. // word (the word is whole, the value is not).
  10103. let bias = addr_u32(self, usize::from(offset_word))?;
  10104. let bias = if *a16 {
  10105. let low = self.s.m.i32(0xFFFF);
  10106. let bias = self.s.m.bin(c, Bin::And, bias, low);
  10107. to_float(self, bias)
  10108. } else {
  10109. self.as_float(bias)
  10110. };
  10111. args.extend(&os);
  10112. if self.s.pixel {
  10113. args.extend([bias, clamp]);
  10114. call_sample(self, "sampleBias.f32", 61, &args, &mut gathered)
  10115. } else {
  10116. // As above: the bias is the level.
  10117. args.push(bias);
  10118. call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
  10119. }
  10120. }
  10121. 63 if kind == 5 => {
  10122. // A cube with explicit gradients: the host wants them
  10123. // as changes of the direction, the console gives the
  10124. // changes of the face coordinates (the face is one
  10125. // unit wide). The level they select is taken from the
  10126. // longer of the two, in texels, and sampled directly.
  10127. // shortcut: no anisotropic filtering for these samples
  10128. // (the longer axis alone decides the level).
  10129. let mut len = [fu; 2];
  10130. for (axis, slot) in len.iter_mut().enumerate() {
  10131. let mut sum = self.s.m.f32(0);
  10132. for k in 0..2 {
  10133. let x = addr_packed(self, first + axis * deriv_regs, k)?;
  10134. let x = to_float(self, x);
  10135. let sq = self.s.m.bin(c, Bin::Mul, x, x);
  10136. sum = self.s.m.bin(c, Bin::Add, sum, sq);
  10137. }
  10138. *slot = self.unary(24, sum); // square root
  10139. }
  10140. let longer = self.binary(35, len[0], len[1]); // maximum
  10141. let i32t = self.s.t.i32;
  10142. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  10143. let z = self.s.m.i32(0);
  10144. let d = self
  10145. .s
  10146. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]);
  10147. let width = self.s.m.extract(c, d, 0);
  10148. let width = self.s.m.cast(c, Cast::UiToFp, width, self.s.t.f32);
  10149. let texels = self.s.m.bin(c, Bin::Mul, longer, width);
  10150. // log2 = natural logarithm / ln 2; a length of 0 gives
  10151. // minus infinity, which the sampler clamps to level 0.
  10152. let ln = self.unary(23, texels);
  10153. let per_ln2 = self.s.m.f32(std::f32::consts::LOG2_E.to_bits());
  10154. let lod = self.s.m.bin(c, Bin::Mul, ln, per_ln2);
  10155. args.extend(&os);
  10156. args.push(lod);
  10157. call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
  10158. }
  10159. 63 => {
  10160. let mut g = vec![fu; 6];
  10161. for k in 0..spatial {
  10162. let x = addr_packed(self, first, k)?;
  10163. g[k] = to_float(self, x);
  10164. let y = addr_packed(self, first + deriv_regs, k)?;
  10165. g[3 + k] = to_float(self, y);
  10166. }
  10167. args.extend(&os);
  10168. args.extend(g);
  10169. args.push(clamp);
  10170. call_sample(self, "sampleGrad.f32", 63, &args, &mut gathered)
  10171. }
  10172. 64 | 65 => {
  10173. let reference = addr_u32(self, first - 1)?;
  10174. let reference = self.as_float(reference);
  10175. args.extend(&os);
  10176. args.push(reference);
  10177. let name = if op == 64 {
  10178. args.push(clamp);
  10179. "sampleCmp.f32"
  10180. } else {
  10181. "sampleCmpLevelZero.f32"
  10182. };
  10183. call_sample(self, name, op, &args, &mut gathered)
  10184. }
  10185. 62 => {
  10186. let lod = if name == "image_sample_l" {
  10187. let x = addr_packed(self, coord_base, coords)?;
  10188. to_float(self, x)
  10189. } else {
  10190. self.s.m.f32(0)
  10191. };
  10192. args.extend(&os);
  10193. args.push(lod);
  10194. call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
  10195. }
  10196. _ => {
  10197. if name == "image_gather4" {
  10198. return Err("a gather with implicit level");
  10199. }
  10200. if dmask.count_ones() != 1 {
  10201. return Err("a gather of several channels");
  10202. }
  10203. if matches!(name, "image_gather4_l" | "image_gather4_l_o")
  10204. && coords == 2
  10205. && spatial == 2
  10206. {
  10207. // The host's gather has no level: it read level 0
  10208. // where the title names one (the depth pyramid its
  10209. // occlusion tests read: most of the world was
  10210. // culled against the wrong depths). The four texels
  10211. // are read at the level instead, in the gather's
  10212. // order: (u0,v1) (u1,v1) (u1,v0) (u0,v0).
  10213. // With an offset too (`image_gather4_l_o`): the
  10214. // offset is in texels of that level.
  10215. // The title's meshlet culling takes a 4x4 block of
  10216. // the pyramid as one gather and three offset ones
  10217. // ((2,0), (0,2), (2,2)); the three read level 0,
  10218. // two texels beside the first one's place, so a
  10219. // meshlet three or four texels wide was tested
  10220. // against a quarter of what it covers.
  10221. // shortcut: the level is rounded to a whole one and
  10222. // coordinates past the edge are clamped, whatever
  10223. // the sampler says.
  10224. let lod = addr_packed(self, coord_base, coords)?;
  10225. let lod = to_float(self, lod);
  10226. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  10227. let zero = self.s.m.f32(0);
  10228. let lod = self.binary(35, lod, zero); // maximum
  10229. let lod = self.unary(26, lod); // round to nearest
  10230. let mip = self.s.m.cast(c, Cast::FpToUi, lod, i32t);
  10231. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  10232. let d = self
  10233. .s
  10234. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  10235. let half = self.s.m.f32(0.5f32.to_bits());
  10236. let one = self.s.m.f32(1.0f32.to_bits());
  10237. let (mut lo, mut hi) = ([iu; 2], [iu; 2]);
  10238. for k in 0..2 {
  10239. let n = self.s.m.extract(c, d, k as u32);
  10240. let n = self.s.m.cast(c, Cast::UiToFp, n, f32t);
  10241. let last = self.s.m.bin(c, Bin::Sub, n, one);
  10242. let t = self.s.m.bin(c, Bin::Mul, cs[k], n);
  10243. let t = self.s.m.bin(c, Bin::Sub, t, half);
  10244. let first = self.unary(27, t); // round down
  10245. // The offset word's field (0 without one).
  10246. let by = self.s.m.cast(c, Cast::SiToFp, os[k], f32t);
  10247. let first = self.s.m.bin(c, Bin::Add, first, by);
  10248. let next = self.s.m.bin(c, Bin::Add, first, one);
  10249. for (slot, x) in [(&mut lo[k], first), (&mut hi[k], next)] {
  10250. let x = self.binary(35, x, zero); // maximum
  10251. let x = self.binary(36, x, last); // minimum
  10252. *slot = self.s.m.cast(c, Cast::FpToSi, x, i32t);
  10253. }
  10254. }
  10255. let ch = dmask.trailing_zeros();
  10256. let mut g = [fu; 4];
  10257. let mut read = None;
  10258. let texels = [(lo[0], hi[1]), (hi[0], hi[1]), (hi[0], lo[1]), (lo[0], lo[1])];
  10259. for (slot, (x, y)) in g.iter_mut().zip(texels) {
  10260. let r = self.s.op(
  10261. c,
  10262. "textureLoad.f32",
  10263. Attr::ReadOnly,
  10264. self.s.t.res_ret,
  10265. 66,
  10266. &[h, mip, x, y, iu, iu, iu, iu],
  10267. );
  10268. *slot = self.s.m.extract(c, r, ch);
  10269. read = Some(r);
  10270. }
  10271. gathered = Some(g);
  10272. read.expect("four reads")
  10273. } else {
  10274. args.extend(&os[..2]);
  10275. args.push(self.s.m.i32(dmask.trailing_zeros()));
  10276. call_sample(self, "textureGather.f32", 73, &args, &mut gathered)
  10277. }
  10278. }
  10279. }
  10280. } else {
  10281. let mut cs = vec![iu; 3];
  10282. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  10283. *slot = addr_val(self, k)?;
  10284. }
  10285. let mip = if name == "image_load_mip" {
  10286. addr_val(self, coords)?
  10287. } else if uav {
  10288. // Our declarations have four channels.
  10289. self.s.flags |= flags::TYPED_UAV_LOADS;
  10290. iu
  10291. } else {
  10292. self.s.m.i32(0)
  10293. };
  10294. let mut args = vec![h, mip];
  10295. args.extend(&cs);
  10296. args.extend([iu, iu, iu]);
  10297. self.s.op(
  10298. c,
  10299. "textureLoad.f32",
  10300. Attr::ReadOnly,
  10301. self.s.t.res_ret,
  10302. 66,
  10303. &args,
  10304. )
  10305. };
  10306. let Operand::Vector { reg, .. } = *data else {
  10307. return Err("an image result");
  10308. };
  10309. let channels: Vec<u32> = if op == 73 {
  10310. vec![0, 1, 2, 3]
  10311. } else {
  10312. (0..4).filter(|ch| dmask >> ch & 1 != 0).collect()
  10313. };
  10314. let mut xs = Vec::new();
  10315. for ch in channels {
  10316. let x = match gathered {
  10317. Some(g) => g[ch as usize],
  10318. None => self.s.m.extract(c, r, ch),
  10319. };
  10320. xs.push(if *d16 {
  10321. // shortcut: d16 results are taken as floats (rounded to
  10322. // nearest even); integer formats would keep 16 bits.
  10323. let i32t = self.s.t.i32;
  10324. self.s
  10325. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x])
  10326. } else {
  10327. self.as_int(x)
  10328. });
  10329. }
  10330. if *d16 {
  10331. // Two channels per VGPR, low half first (an odd last high half 0).
  10332. let k16 = self.s.m.i32(16);
  10333. xs = xs
  10334. .chunks(2)
  10335. .map(|p| match *p {
  10336. [lo, hi] => {
  10337. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  10338. self.s.m.bin(c, Bin::Or, lo, hi)
  10339. }
  10340. _ => p[0],
  10341. })
  10342. .collect();
  10343. }
  10344. for (k, x) in xs.into_iter().enumerate() {
  10345. self.write(inst, Reg::V(reg + k as u8), x, guard);
  10346. }
  10347. Ok(())
  10348. }
  10349. /// The direction a cube sample's face coordinates stand for: the
  10350. /// console takes s and t in [1, 2] (`v_cubesc`/`v_cubetc` over
  10351. /// `|v_cubema|`, plus 1.5) and the face id (`v_cubeid`), which the
  10352. /// host's cube sampling turns back into the same texel.
  10353. // shortcut: the view is taken as a cube, not a cube array (whose face
  10354. // operand adds 8 × the slice).
  10355. fn cube_direction(&mut self, s: V, t: V, face: V) -> [V; 3] {
  10356. let c = self.cur;
  10357. let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits());
  10358. let (two, three) = (k(self, 2.0), k(self, 3.0));
  10359. let u = self.s.m.bin(c, Bin::Mul, s, two);
  10360. let u = self.s.m.bin(c, Bin::Sub, u, three);
  10361. let v = self.s.m.bin(c, Bin::Mul, t, two);
  10362. let v = self.s.m.bin(c, Bin::Sub, v, three);
  10363. let z = self.s.m.f32(0x8000_0000);
  10364. let (nu, nv) = (
  10365. self.s.m.bin(c, Bin::Sub, z, u),
  10366. self.s.m.bin(c, Bin::Sub, z, v),
  10367. );
  10368. let (one, mone) = (k(self, 1.0), k(self, -1.0));
  10369. let f = self.s.m.cast(c, Cast::FpToUi, face, self.s.t.i32);
  10370. // Per face +x, -x, +y, -y, +z, -z.
  10371. let table = [
  10372. [one, mone, u, u, u, nu],
  10373. [nv, nv, one, mone, nv, nv],
  10374. [nu, u, v, nv, one, mone],
  10375. ];
  10376. table.map(|row| {
  10377. let mut r = row[0];
  10378. for (n, &x) in row.iter().enumerate().skip(1) {
  10379. let kn = self.s.m.i32(n as u32);
  10380. let is = self.s.m.cmp(c, pred::EQ, f, kn);
  10381. r = self.s.m.select(c, is, x, r);
  10382. }
  10383. r
  10384. })
  10385. }
  10386. fn buffer(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  10387. let Fields::Buffer {
  10388. data,
  10389. addr,
  10390. soffset,
  10391. offset,
  10392. offen,
  10393. idxen,
  10394. format,
  10395. lds,
  10396. tfe,
  10397. ..
  10398. } = &inst.fields
  10399. else {
  10400. unreachable!()
  10401. };
  10402. let name = inst.name();
  10403. if name == "buffer_gl0_inv" || name == "buffer_gl1_inv" {
  10404. // The host has no console buffer cache to invalidate.
  10405. return Ok(());
  10406. }
  10407. if *lds || *tfe {
  10408. return Err("a buffer access to LDS or with tfe");
  10409. }
  10410. if format.is_some() && !name.starts_with("tbuffer_load_format_") {
  10411. return Err(name);
  10412. }
  10413. let site = (b, i);
  10414. let guard = self.guard(b, i)?;
  10415. let c = self.cur;
  10416. let store = name.starts_with("buffer_store_");
  10417. // DXIL atomic operations: add, and, or, xor, signed and unsigned
  10418. // min and max, exchange; compare-exchange apart.
  10419. let atomic = match name.strip_prefix("buffer_atomic_") {
  10420. None => None,
  10421. Some("add") => Some(0),
  10422. Some("and") => Some(1),
  10423. Some("or") => Some(2),
  10424. Some("xor") => Some(3),
  10425. Some("smin") => Some(4),
  10426. Some("smax") => Some(5),
  10427. Some("umin") => Some(6),
  10428. Some("umax") => Some(7),
  10429. Some("swap") => Some(8),
  10430. Some("cmpswap") => Some(u32::MAX),
  10431. Some(_) => return Err(name),
  10432. };
  10433. // Byte and 16-bit accesses: bits, and whether a load sign-extends.
  10434. let narrow = match name {
  10435. "buffer_load_ubyte" | "buffer_store_byte" => Some((8, false)),
  10436. "buffer_load_sbyte" => Some((8, true)),
  10437. "buffer_load_ushort" | "buffer_store_short" => Some((16, false)),
  10438. "buffer_load_sshort" => Some((16, true)),
  10439. _ => None,
  10440. };
  10441. // d16: two 16-bit channels per VGPR, low half first.
  10442. let d16 = name.starts_with("buffer_") && name.contains("_format_d16_");
  10443. let plain = name.replace("_format_d16_", "_format_");
  10444. let (typed, count) = match plain
  10445. .strip_prefix("buffer_load_")
  10446. .or(plain.strip_prefix("buffer_store_"))
  10447. .or(plain.strip_prefix("tbuffer_load_"))
  10448. {
  10449. _ if atomic.is_some() || narrow.is_some() => (false, 1),
  10450. Some("dword") => (false, 1),
  10451. Some("dwordx2") => (false, 2),
  10452. Some("dwordx3") => (false, 3),
  10453. Some("dwordx4") => (false, 4),
  10454. Some("format_x") => (true, 1),
  10455. Some("format_xy") => (true, 2),
  10456. Some("format_xyz") => (true, 3),
  10457. Some("format_xyzw") => (true, 4),
  10458. _ => return Err(name),
  10459. };
  10460. let Operand::Vector { reg: areg, .. } = *addr else {
  10461. return Err("a buffer address");
  10462. };
  10463. let vaddr = |l: &mut Self, k: u8| -> Result<V, Why> {
  10464. let v = inst.read(Reg::V(areg + k)).ok_or("a buffer address")?;
  10465. l.i32_of(v)
  10466. };
  10467. let index = if *idxen { Some(vaddr(self, 0)?) } else { None };
  10468. let mut off = self.s.m.i32(u32::from(*offset));
  10469. if *offen {
  10470. let o = vaddr(self, u8::from(*idxen))?;
  10471. off = self.s.m.bin(c, Bin::Add, off, o);
  10472. }
  10473. if !matches!(
  10474. soffset,
  10475. Operand::Scalar { code: NULL, .. } | Operand::Const(128)
  10476. ) {
  10477. let so = self.operand(inst, soffset)?;
  10478. off = self.s.m.bin(c, Bin::Add, off, so);
  10479. }
  10480. let src = self
  10481. .descriptors
  10482. .get(&(site, false))
  10483. .copied()
  10484. .ok_or("an untracked buffer")?;
  10485. let used = self.used_kind(src);
  10486. let (base, extra) = self.built_offset(src)?;
  10487. if base != 0 {
  10488. let b = self.s.m.i32(base);
  10489. off = self.s.m.bin(c, Bin::Add, off, b);
  10490. }
  10491. if let Some(x) = extra {
  10492. off = self.s.m.bin(c, Bin::Add, off, x);
  10493. }
  10494. // A buffer the program picks from the view heap by an index it
  10495. // computes: no used-resource entry gives its stride, the host's
  10496. // table by heap slot does; the access becomes a raw one at the
  10497. // element's byte. (Also tells the host this shader reads such
  10498. // buffers.)
  10499. let mut index = index;
  10500. if let Some(stride) = self.slot_stride(src)?
  10501. && let Some(element) = index
  10502. && !typed
  10503. && used.is_none()
  10504. {
  10505. let at = self.s.m.bin(c, Bin::Mul, element, stride);
  10506. off = self.s.m.bin(c, Bin::Add, at, off);
  10507. index = None;
  10508. }
  10509. // A structured buffer by its used-resource entry's stride: raw
  10510. // bytes too. The host makes its buffer views raw (a raw read
  10511. // through a structured view gives zeros on NVIDIA), and one kind
  10512. // of view can then serve every shader that reads the buffer.
  10513. if let (Some(element), Some(u)) = (index, used)
  10514. && !typed
  10515. && u.kind != ResourceType::Cbv
  10516. && u.stride >= 4
  10517. && u.stride.is_multiple_of(4)
  10518. {
  10519. let k = self.s.m.i32(u.stride);
  10520. let at = self.s.m.bin(c, Bin::Mul, element, k);
  10521. off = self.s.m.bin(c, Bin::Add, at, off);
  10522. index = None;
  10523. }
  10524. if used.is_some_and(|u| u.kind == ResourceType::Cbv) && !typed {
  10525. // A constant buffer read per lane (a dynamically indexed array).
  10526. // shortcut: the console's CBV descriptor is taken to have a 16-byte
  10527. // stride, as the vector loads of whole rows suggest.
  10528. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  10529. let byte = match index {
  10530. Some(i) => {
  10531. let sixteen = self.s.m.i32(16);
  10532. let rows = self.s.m.bin(c, Bin::Mul, i, sixteen);
  10533. self.s.m.bin(c, Bin::Add, rows, off)
  10534. }
  10535. None => off,
  10536. };
  10537. let Some(Operand::Vector { reg, .. }) = *data else {
  10538. return Err("a buffer result");
  10539. };
  10540. for k in 0..count {
  10541. let four = self.s.m.i32(4 * k);
  10542. let a = self.s.m.bin(c, Bin::Add, byte, four);
  10543. let x = self.cbuffer_dword(h, a);
  10544. self.write(inst, Reg::V(reg + k as u8), x, guard);
  10545. }
  10546. return Ok(());
  10547. }
  10548. let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav);
  10549. let u = if uav { 0x1000 } else { 0 };
  10550. let iu = self.s.m.undef(self.s.t.i32);
  10551. if let Some((bits, signed)) = narrow {
  10552. // Below a dword: raw buffers are read and written in dwords on
  10553. // 4 bytes, so the dword that holds the value is read and
  10554. // shifted, or changed with two atomic operations that touch
  10555. // only the value's own bits (other lanes may write the rest of
  10556. // the dword at the same time). A 16-bit value at a dword's
  10557. // last byte continues in the next dword.
  10558. let byte = match index {
  10559. None => off,
  10560. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  10561. self.s.m.bin(c, Bin::Add, index, off)
  10562. }
  10563. Some(_) => return Err("a byte or 16-bit buffer access by index"),
  10564. };
  10565. let h = self.handle(site, src, false, (11 | u, 0))?;
  10566. let k3 = self.s.m.i32(3);
  10567. let within = self.s.m.bin(c, Bin::And, byte, k3);
  10568. let aligned = self.s.m.bin(c, Bin::Sub, byte, within);
  10569. let shift = self.s.m.bin(c, Bin::Shl, within, k3);
  10570. let four = self.s.m.i32(4);
  10571. let next = self.s.m.bin(c, Bin::Add, aligned, four);
  10572. let ones = self.s.m.i32(if bits == 8 { 0xff } else { 0xffff });
  10573. let zero = self.s.m.i32(0);
  10574. let k8 = self.s.m.i32(8);
  10575. let straddles = self.s.m.cmp(c, pred::EQ, within, k3);
  10576. if !store {
  10577. let mask = self.s.m.i8(1);
  10578. let align = self.s.m.i32(4);
  10579. let dword = |l: &mut Self, at: V| {
  10580. let r = l.s.op(
  10581. c,
  10582. "rawBufferLoad.f32",
  10583. Attr::ReadOnly,
  10584. l.s.t.res_ret,
  10585. 139,
  10586. &[h, at, iu, mask, align],
  10587. );
  10588. let f = l.s.m.extract(c, r, 0);
  10589. l.as_int(f)
  10590. };
  10591. let low = dword(self, aligned);
  10592. let mut x = self.s.m.bin(c, Bin::LShr, low, shift);
  10593. if bits == 16 {
  10594. let high = dword(self, next);
  10595. let high = self.s.m.bin(c, Bin::Shl, high, k8);
  10596. let high = self.s.m.select(c, straddles, high, zero);
  10597. x = self.s.m.bin(c, Bin::Or, x, high);
  10598. }
  10599. x = self.s.m.bin(c, Bin::And, x, ones);
  10600. if signed {
  10601. let up = self.s.m.i32(32 - bits);
  10602. x = self.s.m.bin(c, Bin::Shl, x, up);
  10603. x = self.s.m.bin(c, Bin::AShr, x, up);
  10604. }
  10605. let Some(Operand::Vector { reg, .. }) = *data else {
  10606. return Err("a buffer result");
  10607. };
  10608. self.write(inst, Reg::V(reg), x, guard);
  10609. return Ok(());
  10610. }
  10611. let d = data.as_ref().ok_or("buffer store data")?;
  10612. let v = self.vgprs(inst, d, 1)?[0];
  10613. let v = self.s.m.bin(c, Bin::And, v, ones);
  10614. let all = self.s.m.i32(u32::MAX);
  10615. let clear = self.s.m.bin(c, Bin::Shl, ones, shift);
  10616. let keep = self.s.m.bin(c, Bin::Xor, clear, all);
  10617. let set = self.s.m.bin(c, Bin::Shl, v, shift);
  10618. let keep_next = self.s.m.i32(0xffff_ff00);
  10619. let set_next = self.s.m.bin(c, Bin::LShr, v, k8);
  10620. let (and, or) = (self.s.m.i32(1), self.s.m.i32(2));
  10621. let i32t = self.s.t.i32;
  10622. let at = self.begin_guarded(guard);
  10623. for (op, x) in [(and, keep), (or, set)] {
  10624. let args = [h, op, aligned, iu, iu, x];
  10625. self.s
  10626. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args);
  10627. }
  10628. if bits == 16 {
  10629. let second = self.begin_guarded(Some(straddles));
  10630. for (op, x) in [(and, keep_next), (or, set_next)] {
  10631. let args = [h, op, next, iu, iu, x];
  10632. self.s
  10633. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args);
  10634. }
  10635. self.end_guarded(second, &[]);
  10636. }
  10637. self.end_guarded(at, &[]);
  10638. return Ok(());
  10639. }
  10640. if let Some(op) = atomic {
  10641. let d = data.as_ref().ok_or("buffer atomic data")?;
  10642. let vals = self.vgprs(inst, d, if op == u32::MAX { 2 } else { 1 })?;
  10643. let (h, coords) = match index {
  10644. // A raw buffer (stride 1) read by index: the index is the byte.
  10645. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  10646. let byte = self.s.m.bin(c, Bin::Add, index, off);
  10647. (self.handle(site, src, false, (11 | u, 0))?, [byte, iu, iu])
  10648. }
  10649. Some(index) => {
  10650. let stride = used.map_or(0, |u| u.stride);
  10651. if stride < 4 || !stride.is_multiple_of(4) {
  10652. return Err("a structured buffer of unknown stride");
  10653. }
  10654. let h = self.handle(site, src, false, (12 | u, stride))?;
  10655. (h, [index, off, iu])
  10656. }
  10657. None => (self.handle(site, src, false, (11 | u, 0))?, [off, iu, iu]),
  10658. };
  10659. let Operand::Vector { reg, .. } = *d else {
  10660. return Err("buffer atomic data");
  10661. };
  10662. let returns = matches!(inst.fields, Fields::Buffer { cache, .. } if cache.glc);
  10663. let old = match inst.read(Reg::V(reg)) {
  10664. Some(v) if returns => self.i32_of(v)?,
  10665. _ => self.s.m.i32(0),
  10666. };
  10667. let at = self.begin_guarded(guard);
  10668. let i32t = self.s.t.i32;
  10669. let r = if op == u32::MAX {
  10670. // cmpswap: data is (new, compare).
  10671. let mut args = vec![h];
  10672. args.extend(coords);
  10673. args.extend([vals[1], vals[0]]);
  10674. self.s.op(
  10675. self.cur,
  10676. "atomicCompareExchange.i32",
  10677. Attr::NoUnwind,
  10678. i32t,
  10679. 79,
  10680. &args,
  10681. )
  10682. } else {
  10683. let mut args = vec![h, self.s.m.i32(op)];
  10684. args.extend(coords);
  10685. args.push(vals[0]);
  10686. self.s
  10687. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args)
  10688. };
  10689. let r = self.end_guarded(at, &[(r, old)])[0];
  10690. if returns {
  10691. self.write(inst, Reg::V(reg), r, None);
  10692. }
  10693. return Ok(());
  10694. }
  10695. if store {
  10696. let regs = if d16 { count.div_ceil(2) } else { count };
  10697. let mut vals =
  10698. self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?;
  10699. if d16 {
  10700. // shortcut: d16 data is taken as f16 (integer formats would
  10701. // keep 16 bits), widened for the 32-bit float store.
  10702. let mut wide = Vec::new();
  10703. for k in 0..count {
  10704. let mut x = vals[(k / 2) as usize];
  10705. if k % 2 == 1 {
  10706. let k16 = self.s.m.i32(16);
  10707. x = self.s.m.bin(c, Bin::LShr, x, k16);
  10708. }
  10709. let f32t = self.s.t.f32;
  10710. let f = self
  10711. .s
  10712. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
  10713. wide.push(self.as_int(f));
  10714. }
  10715. vals = wide;
  10716. }
  10717. let mut args = Vec::new();
  10718. let (op, name) = if typed {
  10719. // shortcut: typed stores are taken to write all four channels
  10720. // of a float format.
  10721. if count != 4 || *offen || *offset != 0 {
  10722. return Err("a typed buffer store of some channels or at an offset");
  10723. }
  10724. args.push(self.handle(site, src, false, (10 | u, 0x409))?);
  10725. args.extend([index.unwrap_or(self.s.m.i32(0)), iu]);
  10726. for x in vals {
  10727. args.push(self.as_float(x));
  10728. }
  10729. (69, "bufferStore.f32")
  10730. } else {
  10731. match index {
  10732. // A raw buffer (stride 1) written by index: the index is the byte.
  10733. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  10734. let byte = self.s.m.bin(c, Bin::Add, index, off);
  10735. args.push(self.handle(site, src, false, (11 | u, 0))?);
  10736. args.extend([byte, iu]);
  10737. }
  10738. Some(index) => {
  10739. let stride = used.map_or(0, |u| u.stride);
  10740. if stride < 4 || !stride.is_multiple_of(4) {
  10741. return Err("a structured buffer of unknown stride");
  10742. }
  10743. args.push(self.handle(site, src, false, (12 | u, stride))?);
  10744. args.extend([index, off]);
  10745. }
  10746. None => {
  10747. args.push(self.handle(site, src, false, (11 | u, 0))?);
  10748. args.extend([off, iu]);
  10749. }
  10750. }
  10751. args.extend(&vals);
  10752. args.resize(3 + 4, iu);
  10753. (140, "rawBufferStore.i32")
  10754. };
  10755. args.push(self.s.m.i8(if typed { 0xF } else { (1u8 << count) - 1 }));
  10756. if !typed {
  10757. args.push(self.s.m.i32(4));
  10758. }
  10759. let at = self.begin_guarded(guard);
  10760. let void = self.s.t.void;
  10761. self.s.op(self.cur, name, Attr::NoUnwind, void, op, &args);
  10762. self.end_guarded(at, &[]);
  10763. return Ok(());
  10764. }
  10765. if let Some(f) = *format {
  10766. if index.is_some() {
  10767. return Err("a typed-format load by index");
  10768. }
  10769. let h = self.handle(site, src, false, (11 | u, 0))?;
  10770. let Some(Operand::Vector { reg, .. }) = *data else {
  10771. return Err("a buffer result");
  10772. };
  10773. for (k, x) in self.format_load(h, off, f, count)?.into_iter().enumerate() {
  10774. self.write(inst, Reg::V(reg + k as u8), x, guard);
  10775. }
  10776. return Ok(());
  10777. }
  10778. let r = if typed {
  10779. if *offen || matches!(off, V::Inst(_)) || *offset != 0 {
  10780. return Err("a typed buffer load at an offset");
  10781. }
  10782. if uav {
  10783. self.s.flags |= flags::TYPED_UAV_LOADS;
  10784. }
  10785. let h = self.handle(site, src, false, (10 | u, 0x409))?;
  10786. let index = index.unwrap_or(self.s.m.i32(0));
  10787. self.s.op(
  10788. c,
  10789. "bufferLoad.f32",
  10790. Attr::ReadOnly,
  10791. self.s.t.res_ret,
  10792. 68,
  10793. &[h, index, iu],
  10794. )
  10795. } else {
  10796. let mask = self.s.m.i8((1u8 << count) - 1);
  10797. let align = self.s.m.i32(4);
  10798. match index {
  10799. // A raw buffer (stride 1) read by index: the index is the byte.
  10800. Some(index) if used.is_some_and(|u| u.stride == 1) => {
  10801. let byte = self.s.m.bin(c, Bin::Add, index, off);
  10802. let h = self.handle(site, src, false, (11 | u, 0))?;
  10803. self.s.op(
  10804. c,
  10805. "rawBufferLoad.f32",
  10806. Attr::ReadOnly,
  10807. self.s.t.res_ret,
  10808. 139,
  10809. &[h, byte, iu, mask, align],
  10810. )
  10811. }
  10812. Some(index) => {
  10813. let stride = used.map_or(0, |u| u.stride);
  10814. if stride < 4 || !stride.is_multiple_of(4) {
  10815. return Err("a structured buffer of unknown stride");
  10816. }
  10817. let h = self.handle(site, src, false, (12 | u, stride))?;
  10818. self.s.op(
  10819. c,
  10820. "rawBufferLoad.f32",
  10821. Attr::ReadOnly,
  10822. self.s.t.res_ret,
  10823. 139,
  10824. &[h, index, off, mask, align],
  10825. )
  10826. }
  10827. None => {
  10828. let h = self.handle(site, src, false, (11 | u, 0))?;
  10829. self.s.op(
  10830. c,
  10831. "rawBufferLoad.f32",
  10832. Attr::ReadOnly,
  10833. self.s.t.res_ret,
  10834. 139,
  10835. &[h, off, iu, mask, align],
  10836. )
  10837. }
  10838. }
  10839. };
  10840. let Some(Operand::Vector { reg, .. }) = *data else {
  10841. return Err("a buffer result");
  10842. };
  10843. if d16 {
  10844. // Two f16 channels per VGPR (an odd last high half 0).
  10845. let k16 = self.s.m.i32(16);
  10846. let i32t = self.s.t.i32;
  10847. for k in 0..count.div_ceil(2) {
  10848. let mut x = None;
  10849. for ch in (2 * k..(2 * k + 2).min(count)).rev() {
  10850. let f = self.s.m.extract(c, r, ch);
  10851. let h = self
  10852. .s
  10853. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
  10854. x = Some(match x {
  10855. Some(hi) => {
  10856. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  10857. self.s.m.bin(c, Bin::Or, h, hi)
  10858. }
  10859. None => h,
  10860. });
  10861. }
  10862. self.write(inst, Reg::V(reg + k as u8), x.expect("a channel"), guard);
  10863. }
  10864. return Ok(());
  10865. }
  10866. for k in 0..count {
  10867. let x = self.s.m.extract(c, r, k);
  10868. let x = self.as_int(x);
  10869. self.write(inst, Reg::V(reg + k as u8), x, guard);
  10870. }
  10871. Ok(())
  10872. }
  10873. fn export(&mut self, b: usize, i: usize) -> Result<(), Why> {
  10874. let e = *self
  10875. .exports
  10876. .get(&(b, i))
  10877. .ok_or("an export I/O raising did not see")?;
  10878. if e.compressed {
  10879. return Err("a compressed export");
  10880. }
  10881. let guard = self.guard(b, i)?;
  10882. let mesh = self.s.mesh.is_some();
  10883. let c = self.cur;
  10884. if let Some(g) = guard
  10885. && !mesh
  10886. {
  10887. if !(e.done && self.s.pixel) {
  10888. return Err("a conditional export");
  10889. }
  10890. let t = self.s.m.bool(true);
  10891. let kill = self.s.m.bin(c, Bin::Xor, g, t);
  10892. self.s
  10893. .op(c, "discard", Attr::NoUnwind, self.s.t.void, 82, &[kill]);
  10894. }
  10895. if mesh && e.target == Target::Primitive {
  10896. return self.emit_indices(e, guard);
  10897. }
  10898. let param_row = |usage: Usage, row: u8| match usage {
  10899. // The 2020 compiler leaves a mesh program's first entry zeroed
  10900. // (usage "position"): its row is the one no other entry names.
  10901. Usage::Other(0) if mesh => self.unnamed_row(),
  10902. _ => Some(row),
  10903. };
  10904. // (output element, channel) per exported channel; per-primitive
  10905. // outputs are elements of `prims`.
  10906. let mut stores = Vec::new();
  10907. let primitive = matches!(e.target, Target::PrimitiveParam { .. });
  10908. let outputs = if primitive {
  10909. &self.s.prims
  10910. } else {
  10911. &self.s.outputs
  10912. };
  10913. let by_kind = |kind: u8| outputs.iter().position(|o| o.kind == kind);
  10914. // 16-bit vertex outputs: the halves each dword carries, as (output
  10915. // element, channel, high half) per channel.
  10916. let halves = match e.target {
  10917. Target::Param { usage, row } => {
  10918. param_row(usage, row).and_then(|r| self.half_outputs.get(&r).map(|&h| (r, h)))
  10919. }
  10920. _ => None,
  10921. };
  10922. if let Some((row, (pack2, _))) = halves {
  10923. let packs: Vec<(u8, Option<u8>)> = self
  10924. .half_outputs
  10925. .iter()
  10926. .filter(|(_, h)| h.0)
  10927. .map(|(&r, h)| (r, h.1))
  10928. .collect();
  10929. for ch in 0..4u8 {
  10930. let Some(value) = e.values[usize::from(ch)] else {
  10931. continue;
  10932. };
  10933. for high in [false, true] {
  10934. let h = 2 * ch + u8::from(high);
  10935. let src = if pack2 {
  10936. packed_half(outputs, &packs, row, h)
  10937. } else {
  10938. (!high).then_some((row, ch))
  10939. };
  10940. let found = src.and_then(|(r, c)| {
  10941. outputs.iter().position(|o| {
  10942. o.row == Some(u32::from(r)) && c >= o.col && c < o.col + o.cols
  10943. })
  10944. });
  10945. if let Some(id) = found {
  10946. let col = src.expect("found").1 - outputs[id].col;
  10947. stores.push((id, col, value, Some(high)));
  10948. }
  10949. }
  10950. }
  10951. }
  10952. for ch in 0..4u8 {
  10953. let Some(value) = e.values[usize::from(ch)] else {
  10954. continue;
  10955. };
  10956. if halves.is_some() {
  10957. break;
  10958. }
  10959. let found = match e.target {
  10960. Target::Color(n) => outputs
  10961. .iter()
  10962. .position(|o| o.kind == 16 && o.row == Some(u32::from(n)))
  10963. .map(|id| (id, ch)),
  10964. Target::Position(0) => by_kind(3).map(|id| (id, ch)),
  10965. Target::Depth => match ch {
  10966. 0 => by_kind(17)
  10967. .or(by_kind(18))
  10968. .or(by_kind(19))
  10969. .map(|id| (id, 0)),
  10970. 1 => by_kind(20).map(|id| (id, 0)),
  10971. 2 => by_kind(14).map(|id| (id, 0)),
  10972. _ => None,
  10973. },
  10974. Target::Param { usage, row } | Target::PrimitiveParam { usage, row } => {
  10975. let row = param_row(usage, row);
  10976. outputs
  10977. .iter()
  10978. .position(|o| {
  10979. row.is_some_and(|r| o.row == Some(u32::from(r)))
  10980. && ch >= o.col
  10981. && ch < o.col + o.cols
  10982. })
  10983. .map(|id| (id, ch - outputs[id].col))
  10984. }
  10985. Target::Null | Target::Unread => None,
  10986. Target::Position(n @ 1..=2) => {
  10987. // shortcut: without the misc vector (point size, render
  10988. // target or viewport index) pos1 and pos2 carry the clip
  10989. // then cull distances, in semantic order.
  10990. if outputs.iter().any(|o| matches!(o.kind, 4 | 5)) {
  10991. return Err("render-target or viewport index exports");
  10992. }
  10993. let mut dists: Vec<usize> = (0..outputs.len())
  10994. .filter(|&i| matches!(outputs[i].kind, 6 | 7))
  10995. .collect();
  10996. dists.sort_by_key(|&i| (outputs[i].kind, outputs[i].index));
  10997. let flat: Vec<(usize, u8)> = dists
  10998. .iter()
  10999. .flat_map(|&i| (0..outputs[i].cols).map(move |c| (i, c)))
  11000. .collect();
  11001. // Channels past the distances the signature declares are
  11002. // ones the clipper does not enable (`PA_CL_VS_OUT_CNTL`).
  11003. let k = usize::from(n - 1) * 4 + usize::from(ch);
  11004. flat.get(k).copied()
  11005. }
  11006. Target::Position(_) => return Err("clip, cull or point-size exports"),
  11007. Target::Primitive => return Err("a primitive export"),
  11008. };
  11009. if let Some((id, col)) = found {
  11010. stores.push((id, col, value, None));
  11011. }
  11012. }
  11013. fn elements<'l>(l: &'l mut Lower, primitive: bool) -> &'l mut Vec<SigElement> {
  11014. if primitive {
  11015. &mut l.s.prims
  11016. } else {
  11017. &mut l.s.outputs
  11018. }
  11019. }
  11020. if stores
  11021. .iter()
  11022. .any(|s| s.3.is_none() && elements(self, primitive)[s.0].half)
  11023. {
  11024. return Err("a 16-bit output the stage data does not mark");
  11025. }
  11026. // A mesh lane writes its own vertex or primitive, where it exports.
  11027. let at = if mesh {
  11028. let flat = self.mesh_thread();
  11029. let limit = if let Some(m) = self.s.mesh {
  11030. if primitive {
  11031. m.max_primitives
  11032. } else {
  11033. m.max_vertices
  11034. }
  11035. } else {
  11036. 0
  11037. };
  11038. let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX);
  11039. let mesh_guard = if limit > 0 && threads > limit {
  11040. let lim = self.s.m.i32(limit);
  11041. let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, lim);
  11042. match guard {
  11043. Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)),
  11044. None => Some(in_bounds),
  11045. }
  11046. } else {
  11047. guard
  11048. };
  11049. self.begin_guarded(mesh_guard)
  11050. } else {
  11051. None
  11052. };
  11053. let (name, opcode) = match (mesh, primitive) {
  11054. (false, _) => ("storeOutput", 5),
  11055. (true, false) => ("storeVertexOutput", 171),
  11056. (true, true) => ("storePrimitiveOutput", 172),
  11057. };
  11058. for (id, col, value, half) in stores {
  11059. let mut x = self.i32_of(value)?;
  11060. if let Some(high) = half {
  11061. // An f16 half, declared a 32-bit float on the host.
  11062. let c = self.cur;
  11063. if high {
  11064. let k16 = self.s.m.i32(16);
  11065. x = self.s.m.bin(c, Bin::LShr, x, k16);
  11066. }
  11067. let f32t = self.s.t.f32;
  11068. let f = self
  11069. .s
  11070. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
  11071. x = self.as_int(f);
  11072. }
  11073. let el = &mut elements(self, primitive)[id];
  11074. el.usage |= 1 << col;
  11075. let (suffix, x) = match el.comp {
  11076. 9 if half.is_some() => (".f32", self.as_float(x)),
  11077. 9 => {
  11078. let f = match self.floats.get(&value) {
  11079. Some(&f) => f,
  11080. None => self.as_float(x),
  11081. };
  11082. (".f32", f)
  11083. }
  11084. _ => (".i32", x),
  11085. };
  11086. let mut args = vec![
  11087. self.s.m.i32(id as u32),
  11088. self.s.m.i32(0),
  11089. self.s.m.i8(col),
  11090. x,
  11091. ];
  11092. if mesh {
  11093. args.push(self.mesh_thread());
  11094. }
  11095. let void = self.s.t.void;
  11096. self.s.op(
  11097. self.cur,
  11098. &format!("{name}{suffix}"),
  11099. Attr::NoUnwind,
  11100. void,
  11101. opcode,
  11102. &args,
  11103. );
  11104. }
  11105. self.end_guarded(at, &[]);
  11106. Ok(())
  11107. }
  11108. /// Mesh: `exp prim` as the lane's primitive. Bit 31 culls it (all
  11109. /// indices 0: no area).
  11110. fn emit_indices(&mut self, e: &Export, guard: Option<V>) -> Result<(), Why> {
  11111. let v = e.values[0].ok_or("a primitive export without its indices")?;
  11112. let x = self.i32_of(v)?;
  11113. let flat = self.mesh_thread();
  11114. let guard = if let Some(mesh) = self.s.mesh {
  11115. let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX);
  11116. if threads > mesh.max_primitives {
  11117. let p = self.s.m.i32(mesh.max_primitives);
  11118. let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, p);
  11119. match guard {
  11120. Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)),
  11121. None => Some(in_bounds),
  11122. }
  11123. } else {
  11124. guard
  11125. }
  11126. } else {
  11127. guard
  11128. };
  11129. let at = self.begin_guarded(guard);
  11130. let c = self.cur;
  11131. let z = self.s.m.i32(0);
  11132. let mut culled = self.s.m.cmp(c, pred::SLT, x, z);
  11133. // A primitive that names a vertex past the declared count, or one
  11134. // no lane writes (lane n writes vertex n alone), is culled too: the
  11135. // host would read a vertex nothing set, at any position.
  11136. let written = self.s.mesh.map(|m| {
  11137. m.max_vertices
  11138. .min(self.s.threads.map_or(u32::MAX, |t| t[0]))
  11139. });
  11140. let mut indices = [z; 3];
  11141. for (k, slot) in indices.iter_mut().enumerate() {
  11142. let (shift, mask) = (self.s.m.i32(10 * k as u32), self.s.m.i32(0x3FF));
  11143. let i = self.s.m.bin(c, Bin::LShr, x, shift);
  11144. let i = self.s.m.bin(c, Bin::And, i, mask);
  11145. if let Some(n) = written {
  11146. let n = self.s.m.i32(n);
  11147. let past = self.s.m.cmp(c, pred::IUGE, i, n);
  11148. culled = self.s.m.bin(c, Bin::Or, culled, past);
  11149. }
  11150. *slot = i;
  11151. }
  11152. let mut args = vec![flat];
  11153. for i in indices {
  11154. args.push(self.s.m.select(c, culled, z, i));
  11155. }
  11156. let void = self.s.t.void;
  11157. self.s
  11158. .op(c, "emitIndices", Attr::NoUnwind, void, 169, &args);
  11159. self.end_guarded(at, &[]);
  11160. Ok(())
  11161. }
  11162. /// The per-vertex arbitrary row no mesh output entry names but one
  11163. /// (the 2020 compiler's zeroed entry).
  11164. fn unnamed_row(&self) -> Option<u8> {
  11165. let StageIo::Ms(ms) = &self.x.native.io else {
  11166. return None;
  11167. };
  11168. let named = |r: u32| {
  11169. ms.outputs
  11170. .iter()
  11171. .any(|o| o.param & 0x80 == 0 && o.usage != Usage::Other(0) && u32::from(o.row) == r)
  11172. };
  11173. let free: std::collections::BTreeSet<u32> = self
  11174. .s
  11175. .outputs
  11176. .iter()
  11177. .filter(|o| o.kind == 0)
  11178. .filter_map(|o| o.row)
  11179. .filter(|&r| !named(r))
  11180. .collect();
  11181. match free.into_iter().collect::<Vec<_>>()[..] {
  11182. [r] => u8::try_from(r).ok(),
  11183. _ => None,
  11184. }
  11185. }
  11186. fn exit(&mut self, b: usize) -> Result<(), Stop> {
  11187. let offset = self.x.p.blocks[b]
  11188. .insts
  11189. .last()
  11190. .map_or(self.x.p.blocks[b].offset, |i| i.machine.offset);
  11191. let term = match self.x.st.exits[b] {
  11192. LaneExit::Jump(t) if self.counters.contains_key(&t) && self.rpo[t] <= self.rpo[b] => {
  11193. let ok = self.count_iteration(t, pred::IULT);
  11194. let abort = self.abort_block();
  11195. Term::CondBr(ok, self.block[t].expect("reachable"), abort)
  11196. }
  11197. LaneExit::Jump(t) => {
  11198. self.enter_loop(b, t, self.cur);
  11199. Term::Br(self.block[t].expect("reachable"))
  11200. }
  11201. LaneExit::Branch {
  11202. when,
  11203. taken,
  11204. not_taken,
  11205. } => {
  11206. // A negated condition branches the other way round.
  11207. let (cond, taken, not_taken) = match self.x.st.bools.node(when) {
  11208. _ if self.x.st.wide.contains(&b) => {
  11209. let c = self.wave_wide(b, when).map_err(|w| unsupported(offset, w))?;
  11210. (c, taken, not_taken)
  11211. }
  11212. Some((atom, Bool::TRUE, Bool::FALSE)) => {
  11213. let a = self
  11214. .atom(atom, self.cur)
  11215. .map_err(|w| unsupported(offset, w))?;
  11216. (a, not_taken, taken)
  11217. }
  11218. _ => {
  11219. let c = self
  11220. .boolean(when, self.cur)
  11221. .map_err(|w| unsupported(offset, w))?;
  11222. (c, taken, not_taken)
  11223. }
  11224. };
  11225. // A back edge is taken only below the iteration limit.
  11226. let back =
  11227. |l: &Self, to: usize| l.counters.contains_key(&to) && l.rpo[to] <= l.rpo[b];
  11228. // (No `xor` of a compare: a loop exit testing one hung the
  11229. // AMD driver.)
  11230. let cond = if back(self, taken) {
  11231. let ok = self.count_iteration(taken, pred::IULT);
  11232. self.s.m.bin(self.cur, Bin::And, cond, ok)
  11233. } else if back(self, not_taken) {
  11234. let stop = self.count_iteration(not_taken, pred::IUGE);
  11235. self.s.m.bin(self.cur, Bin::Or, cond, stop)
  11236. } else {
  11237. cond
  11238. };
  11239. // Critical edges get a block of their own, so loops have
  11240. // dedicated exits and preheaders as DXC emits them.
  11241. let (t, f) = (self.edge(b, taken), self.edge(b, not_taken));
  11242. for (to, via) in [(taken, t), (not_taken, f)] {
  11243. if !back(self, to) {
  11244. // From an edge block, or from here.
  11245. let from = if Some(via) == self.block[to] {
  11246. self.cur
  11247. } else {
  11248. via
  11249. };
  11250. self.enter_loop(b, to, from);
  11251. }
  11252. }
  11253. Term::CondBr(cond, t, f)
  11254. }
  11255. LaneExit::End => {
  11256. if self.s.pixel && !self.exported[b] && !self.has_done_export(b) {
  11257. // A lane leaving without its final export was killed.
  11258. let t = self.s.m.bool(true);
  11259. self.s
  11260. .op(self.cur, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]);
  11261. }
  11262. Term::Ret
  11263. }
  11264. LaneExit::Indirect => return Err(unsupported(offset, "an indirect jump")),
  11265. };
  11266. let _ = Exit::End;
  11267. self.s.m.terminate(self.cur, term);
  11268. Ok(())
  11269. }
  11270. /// A forward edge into loop header `to` (from DXIL block `via`) starts
  11271. /// its count at 0.
  11272. fn enter_loop(&mut self, _from: usize, to: usize, via: usize) {
  11273. if let Some((_, incoming)) = self.counters.get_mut(&to) {
  11274. let z = self.s.m.i32(0);
  11275. incoming.push((z, via));
  11276. }
  11277. }
  11278. /// A back edge to header `to` (a back edge keeps its block, no
  11279. /// critical-edge block): the count goes up; the result compares it with
  11280. /// [`LOOP_LIMIT`] by `p` (below: go on; at or above: stop).
  11281. fn count_iteration(&mut self, to: usize, p: u8) -> V {
  11282. let c = self.cur;
  11283. let (phi, _) = self.counters[&to];
  11284. let one = self.s.m.i32(1);
  11285. let next = self.s.m.bin(c, Bin::Add, phi, one);
  11286. self.s.m.tag(phi, Tag::Counter);
  11287. self.s.m.tag(next, Tag::Counter);
  11288. // Per stage unless the switch names one: a loop that never meets its
  11289. // exit (a count read from a buffer the host has not got yet, say)
  11290. // runs to the limit in every lane. A million iterations a pixel
  11291. // hung the GPU for seconds a draw until Windows reset it
  11292. // (PS_Textured_Eight, 2026-11-24, run 12).
  11293. // shortcut: a pixel loop past 128 iterations, a vertex or mesh loop
  11294. // past 256 or a compute loop past 4,096 is cut short. (They were
  11295. // 1,024, 4,096 and 65,536: the opening cutscene then lost the card
  11296. // 14-25 frames in, in a minimap or shadow mesh draw; with every
  11297. // loop cut at 64 it ran 90 frames. Raise them again once shaders
  11298. // stop reading data that is not there yet.)
  11299. let limit = match super::loop_limit() {
  11300. LOOP_LIMIT if self.s.pixel => 1 << 7,
  11301. LOOP_LIMIT if self.s.mesh.is_some() || self.s.threads.is_none() => 1 << 8,
  11302. LOOP_LIMIT => 1 << 12,
  11303. named => named,
  11304. };
  11305. let limit = self.s.m.i32(limit);
  11306. self.counters
  11307. .get_mut(&to)
  11308. .expect("header")
  11309. .1
  11310. .push((next, c));
  11311. let over = self.s.m.cmp(c, p, next, limit);
  11312. self.s.m.tag(over, Tag::Counter);
  11313. over
  11314. }
  11315. /// The block a lane stopped by [`LOOP_LIMIT`] leaves through.
  11316. fn abort_block(&mut self) -> usize {
  11317. if let Some(a) = self.abort {
  11318. return a;
  11319. }
  11320. let a = self.s.m.new_block();
  11321. if self.s.pixel {
  11322. let t = self.s.m.bool(true);
  11323. self.s
  11324. .op(a, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]);
  11325. }
  11326. self.s.m.terminate(a, Term::Ret);
  11327. self.abort = Some(a);
  11328. a
  11329. }
  11330. /// The DXIL block a branch from IR block `from` to `to` goes to.
  11331. fn edge(&mut self, from: usize, to: usize) -> usize {
  11332. let target = self.block[to].expect("reachable");
  11333. let preds = self.x.p.blocks[to]
  11334. .preds
  11335. .iter()
  11336. .filter(|&&q| self.block[q].is_some())
  11337. .count();
  11338. // Back edges stay as they are: the exiting block is the latch.
  11339. if preds < 2 || self.rpo[to] <= self.rpo[from] {
  11340. return target;
  11341. }
  11342. let e = self.s.m.new_block();
  11343. self.s.m.terminate(e, Term::Br(target));
  11344. self.edges.insert((from, to), e);
  11345. e
  11346. }
  11347. fn fill_phis(&mut self) -> Result<(), Stop> {
  11348. let p = self.x.p;
  11349. // Lane-mask joins first (what an edge brings may ask for more joins,
  11350. // of masks and of numbers): each edge's mask as the structure
  11351. // tracked it, a constant or a scalar-built one included.
  11352. let st = self.x.st;
  11353. while let Some((v, b, i)) = self.pending_masks.pop() {
  11354. let phi = &p.blocks[b].phis[i];
  11355. let offset = p.blocks[b].offset;
  11356. let args = st
  11357. .phi_masks
  11358. .get(&phi.value)
  11359. .ok_or_else(|| unsupported(offset, "a lane-mask join of an untracked mask"))?;
  11360. let mut incoming = Vec::new();
  11361. for (n, &q) in p.blocks[b].preds.iter().enumerate() {
  11362. let Some(qb) = self.tail[q] else { continue };
  11363. let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb);
  11364. let x = self.boolean(args[n], qb).map_err(|w| unsupported(offset, w))?;
  11365. incoming.push((x, qb));
  11366. }
  11367. self.s.m.set_phi(v, incoming);
  11368. }
  11369. // A join that only another join reads is read wherever that one is. Left
  11370. // unmarked, a value without a DXIL form coming into it became zero without a
  11371. // word (the looked-up tint of the material resolve programs, whose size
  11372. // computation had no value, was zero in every lane that way).
  11373. // shortcut: only with `VICTORY_STRICT_JOINS` set (the offline pack
  11374. // listing sets it to count them): 40 programs that translate today
  11375. // stop by name with it (vehicle paint pixel shaders at "the first
  11376. // half of an interpolation", foliage mesh shaders); until those are
  11377. // lowered they keep drawing with that zero.
  11378. static STRICT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  11379. let strict = *STRICT.get_or_init(|| std::env::var_os("VICTORY_STRICT_JOINS").is_some());
  11380. let mut work: Vec<Value> = if strict {
  11381. self.read_phis.iter().copied().collect()
  11382. } else {
  11383. Vec::new()
  11384. };
  11385. while let Some(v) = work.pop() {
  11386. let Some(&(b, i)) = self.phi_at.get(&v) else {
  11387. continue;
  11388. };
  11389. for &a in &p.blocks[b].phis[i].args {
  11390. if self.phi_at.contains_key(&a) && self.read_phis.insert(a) {
  11391. work.push(a);
  11392. }
  11393. }
  11394. }
  11395. for (v, b, i) in std::mem::take(&mut self.data_phis) {
  11396. let phi = &p.blocks[b].phis[i];
  11397. let bit = phi.reg == Reg::Scc;
  11398. // A join of numbers with dead registers (`dead`): the paths that bring those
  11399. // never read the result, so they bring zero. Not for a join that is itself a
  11400. // lane mask (a ballot gives that one as data).
  11401. let st = self.x.st;
  11402. let numbers = !bit
  11403. && !st.masks.contains_key(&phi.value)
  11404. && !st.highs.contains_key(&phi.value)
  11405. && phi
  11406. .args
  11407. .iter()
  11408. .any(|a| matches!(self.vals.get(a), Some(Val::I32(_))));
  11409. let mut incoming = Vec::new();
  11410. for (n, &q) in p.blocks[b].preds.iter().enumerate() {
  11411. let Some(qb) = self.tail[q] else { continue };
  11412. let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb);
  11413. let arg = phi.args[n];
  11414. if self.read_phis.contains(&phi.value) && !self.vals.contains_key(&arg) {
  11415. let _ = self.lazy_barycentric(arg);
  11416. // A root parameter nothing read before the join (user
  11417. // data is loaded on first use, in the entry block).
  11418. if !self.vals.contains_key(&arg)
  11419. && let Some(&(param, dword)) = self.params.get(&arg)
  11420. {
  11421. let val = self.user(param, dword);
  11422. self.vals.insert(arg, val);
  11423. }
  11424. }
  11425. let x = match (self.vals.get(&arg).copied(), bit) {
  11426. (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x,
  11427. (Some(Val::Missing(_)) | None, false)
  11428. if numbers && self.dead(arg, &mut Vec::new()) =>
  11429. {
  11430. self.s.m.i32(0)
  11431. }
  11432. // A lane mask joined with numbers (a traversal that keeps its lanes' masks on
  11433. // a stack with its node numbers): the mask comes as the number it is, the
  11434. // ballot of its lanes where it is written.
  11435. (Some(Val::Missing(_)) | None, false)
  11436. if self.read_phis.contains(&phi.value)
  11437. && self.mask_data == MaskData::Console
  11438. && (st.masks.contains_key(&arg) || st.highs.contains_key(&arg)) =>
  11439. {
  11440. match self.mask_dword(arg) {
  11441. Ok(x) => x,
  11442. Err(why) => return Err(Stop::Retry(phi.value, why)),
  11443. }
  11444. }
  11445. // SCC of a mask operation ("some lane is left") joined with a scalar test:
  11446. // the compiler branches around code that sets SCC and tests SCC after it,
  11447. // the skip bringing "no lane" along. As data it is "some lane of the wave
  11448. // has the bit" - right only if the wave took that skip together, as the
  11449. // console does: a lane that skipped alone would bring "some lane" where the
  11450. // console has the skipped code's SCC. So the branch must be one the wave
  11451. // takes together; else its region is named for `emit`'s retry to widen it.
  11452. (Some(Val::Missing(_)) | None, true)
  11453. if self.read_phis.contains(&phi.value)
  11454. && self.mask_data == MaskData::Console
  11455. && st.scc_some.contains_key(&arg) =>
  11456. {
  11457. let per_lane = !st.wide.contains(&q)
  11458. && matches!(st.exits[q], LaneExit::Branch { when, .. }
  11459. if !st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))));
  11460. if per_lane {
  11461. for &other in p.blocks[b].preds.iter().filter(|&&o| o != q) {
  11462. need(other);
  11463. }
  11464. return Err(Stop::Retry(phi.value, LANE_MASK));
  11465. }
  11466. match self.scc_some(arg) {
  11467. Ok(x) => x,
  11468. Err(why) => return Err(Stop::Retry(phi.value, why)),
  11469. }
  11470. }
  11471. (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => {
  11472. return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values"));
  11473. }
  11474. (Some(Val::Missing(why)), _) if self.read_phis.contains(&phi.value) => {
  11475. return Err(Stop::Retry(phi.value, why));
  11476. }
  11477. _ if self.read_phis.contains(&phi.value) => {
  11478. return Err(Stop::Retry(phi.value, "a join of mismatched values"));
  11479. }
  11480. _ if bit => self.s.m.bool(false),
  11481. _ => self.s.m.i32(0),
  11482. };
  11483. incoming.push((x, qb));
  11484. }
  11485. self.s.m.set_phi(v, incoming);
  11486. }
  11487. for (phi, incoming) in std::mem::take(&mut self.counters).into_values() {
  11488. self.s.m.set_phi(phi, incoming);
  11489. }
  11490. Ok(())
  11491. }
  11492. }
  11493. /// The DXIL interpolation mode of a kind of barycentrics (none for the
  11494. /// pull model).
  11495. fn interp_mode(kind: Barycentric) -> Option<u8> {
  11496. Some(match kind {
  11497. Barycentric::PerspectiveCenter => 2,
  11498. Barycentric::PerspectiveCentroid => 3,
  11499. Barycentric::PerspectiveSample => 6,
  11500. Barycentric::LinearCenter => 4,
  11501. Barycentric::LinearCentroid => 5,
  11502. Barycentric::LinearSample => 7,
  11503. Barycentric::PerspectivePullModel => return None,
  11504. })
  11505. }
  11506. #[cfg(test)]
  11507. mod tests {
  11508. use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower};
  11509. use crate::native::{
  11510. ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
  11511. };
  11512. use crate::{io, ir, resource, structure};
  11513. const S_ENDPGM: u32 = 0xBF81_0000;
  11514. #[test]
  11515. fn packed_pixel_inputs_find_their_second_row() {
  11516. use super::super::container::SigElement;
  11517. use super::half_input_partners;
  11518. use crate::native::{PsInput, Usage};
  11519. let entry = |row, row2, pack2| PsInput {
  11520. usage: Usage::Generic,
  11521. row,
  11522. mask: 0xF,
  11523. attr: row,
  11524. flat: false,
  11525. fp16: true,
  11526. pack2,
  11527. row2,
  11528. };
  11529. let element = |row| SigElement {
  11530. name: "TEXCOORD".into(),
  11531. index: row,
  11532. kind: 0,
  11533. comp: 9,
  11534. interp: 2,
  11535. row: Some(row),
  11536. col: 0,
  11537. cols: 4,
  11538. usage: 0,
  11539. half: true,
  11540. };
  11541. // Rows 0 and 3 pack and leave their second row out; 5 names its
  11542. // own (6). Unnamed 16-bit rows: 1, 4, 6, 7.
  11543. let io = StageIo::Ps {
  11544. inputs: vec![entry(0, 0, true), entry(3, 3, true), entry(5, 6, true)],
  11545. input_addr: 0,
  11546. db_shader_control: 0,
  11547. patches: vec![],
  11548. };
  11549. let sig: Vec<_> = [0, 1, 3, 4, 5, 6, 7].map(element).into();
  11550. let p = half_input_partners(&io, &sig);
  11551. assert_eq!(p.get(&0), Some(&1));
  11552. assert_eq!(p.get(&3), Some(&4));
  11553. assert_eq!(p.get(&5), None);
  11554. }
  11555. /// The packed pedestrian layouts of the title: an element
  11556. /// behind another one in its register follows in the first parameter
  11557. /// with a dword left, and is not a half of its register's row.
  11558. #[test]
  11559. fn packed_elements_behind_another_take_the_first_free_dword() {
  11560. use super::super::container::SigElement;
  11561. use super::packed_half;
  11562. let element = |index, row, col, cols| SigElement {
  11563. name: "TEXCOORD".into(),
  11564. index,
  11565. kind: 0,
  11566. comp: 9,
  11567. interp: 2,
  11568. row: Some(row),
  11569. col,
  11570. cols,
  11571. usage: 0,
  11572. half: true,
  11573. };
  11574. // MS_VS_PedTransformPreSkinD_Packed 005fe88ec1bdc0c7 and its pixel
  11575. // shader 93667197d3d05e1c: TEXCOORD6 is one value at register 4
  11576. // column 3; parameter 3 (rows 6 and 7) carries it in dword 3.
  11577. let sig = vec![
  11578. element(1, 2, 0, 4),
  11579. element(2, 3, 0, 4),
  11580. element(4, 4, 0, 3),
  11581. element(6, 4, 3, 1),
  11582. element(3, 5, 0, 4),
  11583. element(5, 6, 0, 4),
  11584. element(7, 7, 0, 2),
  11585. element(9, 9, 0, 3),
  11586. element(11, 10, 0, 3),
  11587. element(15, 12, 0, 4),
  11588. ];
  11589. let packs = [
  11590. (2, Some(3)),
  11591. (4, Some(5)),
  11592. (6, Some(7)),
  11593. (9, Some(10)),
  11594. (12, None),
  11595. ];
  11596. let at = |a, h| packed_half(&sig, &packs, a, h);
  11597. // Parameter 2: TEXCOORD4's three values, a zero half, TEXCOORD3.
  11598. assert_eq!(at(4, 2), Some((4, 2)));
  11599. assert_eq!(at(4, 3), None);
  11600. assert_eq!(at(4, 4), Some((5, 0)));
  11601. assert_eq!(at(4, 7), Some((5, 3)));
  11602. // Parameter 3: TEXCOORD5, TEXCOORD7, then TEXCOORD6 alone.
  11603. assert_eq!(at(6, 3), Some((6, 3)));
  11604. assert_eq!(at(6, 5), Some((7, 1)));
  11605. assert_eq!(at(6, 6), Some((4, 3)));
  11606. assert_eq!(at(6, 7), None);
  11607. // Parameters without such an element are as before.
  11608. assert_eq!(at(9, 3), None);
  11609. assert_eq!(at(9, 4), Some((10, 0)));
  11610. assert_eq!(at(12, 3), Some((12, 3)));
  11611. assert_eq!(at(12, 4), None);
  11612. // The common layout (29805d23a495cdf8): TEXCOORD7 is two values at
  11613. // register 1 columns 2-3; parameter 0 is TEXCOORD0, TEXCOORD1,
  11614. // TEXCOORD7.
  11615. let sig = vec![
  11616. element(0, 1, 0, 2),
  11617. element(7, 1, 2, 2),
  11618. element(1, 2, 0, 4),
  11619. element(2, 3, 0, 4),
  11620. element(4, 4, 0, 3),
  11621. ];
  11622. let packs = [(3, Some(4)), (1, Some(2))];
  11623. let at = |a, h| packed_half(&sig, &packs, a, h);
  11624. assert_eq!(at(1, 1), Some((1, 1)));
  11625. assert_eq!(at(1, 2), Some((2, 0)));
  11626. assert_eq!(at(1, 5), Some((2, 3)));
  11627. assert_eq!(at(1, 6), Some((1, 2)));
  11628. assert_eq!(at(1, 7), Some((1, 3)));
  11629. assert_eq!(at(3, 6), Some((4, 2)));
  11630. assert_eq!(at(3, 7), None);
  11631. // A row no element holds gives nothing, as before.
  11632. assert_eq!(packed_half(&sig, &[(8, None)], 8, 0), None);
  11633. }
  11634. /// Whether a synthetic compute program translates with these input registers.
  11635. fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> {
  11636. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  11637. let native = NativeProgram {
  11638. stage: HwStage::Cs,
  11639. wave64: false,
  11640. vgprs: 256,
  11641. layout: vec![],
  11642. used: vec![],
  11643. io: StageIo::Cs(ComputeIo {
  11644. rsrc2,
  11645. threads: [1, 1, 1],
  11646. }),
  11647. code,
  11648. };
  11649. let p = ir::build(&native.code, false, 256).unwrap();
  11650. let st = structure::structure(&p).unwrap();
  11651. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  11652. let io = io::raise(&p, &native).unwrap();
  11653. lower(&Parts {
  11654. native: &native,
  11655. p: &p,
  11656. st: &st,
  11657. io: &io,
  11658. res: &res,
  11659. inputs: vec![],
  11660. outputs: vec![],
  11661. prims: vec![],
  11662. mesh_stride: 0,
  11663. })
  11664. .map(|_| ())
  11665. }
  11666. /// Lowers a compute program with the root parameters `layout` (in user
  11667. /// SGPRs from s0 on) and the used resources `used`.
  11668. fn lower_with(
  11669. words: &[u32],
  11670. layout: Vec<RootParam>,
  11671. used: Vec<UsedResource>,
  11672. ) -> Result<Lowered, crate::ShaderError> {
  11673. lower_wave(words, layout, used, false)
  11674. }
  11675. /// [`lower_with`] in wave64 if `wave64`.
  11676. fn lower_wave(
  11677. words: &[u32],
  11678. layout: Vec<RootParam>,
  11679. used: Vec<UsedResource>,
  11680. wave64: bool,
  11681. ) -> Result<Lowered, crate::ShaderError> {
  11682. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  11683. let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum();
  11684. let native = NativeProgram {
  11685. stage: HwStage::Cs,
  11686. wave64,
  11687. vgprs: 256,
  11688. layout,
  11689. used,
  11690. io: StageIo::Cs(ComputeIo {
  11691. // The layout's user SGPRs (at least two), 512 bytes of LDS.
  11692. rsrc2: 1 << 15 | sgprs.max(2) << 1,
  11693. threads: [1, 1, 1],
  11694. }),
  11695. code,
  11696. };
  11697. let p = ir::build(&native.code, wave64, 256).unwrap();
  11698. let st = structure::structure(&p).unwrap();
  11699. let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
  11700. let io = io::raise(&p, &native).unwrap();
  11701. lower(&Parts {
  11702. native: &native,
  11703. p: &p,
  11704. st: &st,
  11705. io: &io,
  11706. res: &res,
  11707. inputs: vec![],
  11708. outputs: vec![],
  11709. prims: vec![],
  11710. mesh_stride: 0,
  11711. })
  11712. }
  11713. /// Root parameter `slot` in user SGPRs from `user_data` on.
  11714. fn root(root: RootType, user_data: u8, slot: u8) -> RootParam {
  11715. RootParam {
  11716. root,
  11717. table_offset_dwords: 0,
  11718. sgprs: if root == RootType::Descriptor { 2 } else { 1 },
  11719. base_register: 0,
  11720. user_data,
  11721. slot,
  11722. }
  11723. }
  11724. #[test]
  11725. fn buffer_cache_invalidations_lower_as_no_ops() {
  11726. // MUBUF opcode 0x071/0x072 with no data operand: the title asks the
  11727. // host to invalidate its cached view of a buffer.
  11728. assert!(lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl0_inv");
  11729. assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv");
  11730. }
  11731. #[test]
  11732. fn a_scalar_carry_chain_reaches_the_select() {
  11733. // The high dword of a 64-bit add or subtract, then a select on the
  11734. // carry (borrow) the high half leaves in SCC, and a branch on it
  11735. // (only code with an effect needs its operands).
  11736. let add = [
  11737. 0xBE80_03C1, // s_mov_b32 s0, -1
  11738. 0xBE81_0380, // s_mov_b32 s1, 0
  11739. 0x8000_8100, // s_add_u32 s0, s0, 1
  11740. 0x8201_8001, // s_addc_u32 s1, s1, 0
  11741. 0x8502_0001, // s_cselect_b32 s2, s1, s0
  11742. 0xBF07_8002, // s_cmp_lg_u32 s2, 0
  11743. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  11744. 0xBE83_0380, // s_mov_b32 s3, 0
  11745. S_ENDPGM,
  11746. ];
  11747. let sub = [
  11748. 0xBE80_0380, // s_mov_b32 s0, 0
  11749. 0xBE81_0380, // s_mov_b32 s1, 0
  11750. 0x8080_8100, // s_sub_u32 s0, s0, 1
  11751. 0x8281_8001, // s_subb_u32 s1, s1, 0
  11752. 0x8502_0001, // s_cselect_b32 s2, s1, s0
  11753. 0xBF07_8002, // s_cmp_lg_u32 s2, 0
  11754. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  11755. 0xBE83_0380, // s_mov_b32 s3, 0
  11756. S_ENDPGM,
  11757. ];
  11758. for words in [add, sub] {
  11759. lowers(&words, 0).unwrap();
  11760. }
  11761. }
  11762. fn perm_features(selector: u32) -> u64 {
  11763. // Synthetic compute shader:
  11764. // v0 is the thread ID and can supply a dynamic selector.
  11765. // Store the result in LDS to keep the permutation live.
  11766. let words = [
  11767. 0x7E02_02FFu32,
  11768. 0x817F_34AB,
  11769. 0x7E04_02FF,
  11770. 0xFE01_56CD,
  11771. 0xD744_0003,
  11772. 257 | (258 << 9) | (selector << 18),
  11773. 0x3408_0082,
  11774. 0xD834_0000,
  11775. 0x0000_0304,
  11776. S_ENDPGM,
  11777. ];
  11778. let code: Vec<u8> = words.iter()
  11779. .flat_map(|w| w.to_le_bytes())
  11780. .collect();
  11781. let native = NativeProgram {
  11782. stage: HwStage::Cs,
  11783. wave64: false,
  11784. vgprs: 256,
  11785. layout: vec![],
  11786. used: vec![],
  11787. io: StageIo::Cs(ComputeIo {
  11788. rsrc2: 1 << 15,
  11789. threads: [64, 1, 1],
  11790. }),
  11791. code,
  11792. };
  11793. let p = ir::build(&native.code, false, 256).unwrap();
  11794. assert!(p.blocks.iter()
  11795. .flat_map(|b| &b.insts)
  11796. .any(|i| i.name() == "v_perm_b32"));
  11797. let st = structure::structure(&p).unwrap();
  11798. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  11799. let io = io::raise(&p, &native).unwrap();
  11800. let emitted = lower(&Parts {
  11801. native: &native,
  11802. p: &p,
  11803. st: &st,
  11804. io: &io,
  11805. res: &res,
  11806. inputs: vec![],
  11807. outputs: vec![],
  11808. prims: vec![],
  11809. mesh_stride: 0,
  11810. }).unwrap();
  11811. let container =
  11812. crate::Container::parse(&emitted.dxil).unwrap();
  11813. let features =
  11814. container.part(crate::FourCC::SFI0).unwrap();
  11815. u64::from_le_bytes(features.data.try_into().unwrap())
  11816. }
  11817. #[test]
  11818. fn perm_constant_selector_needs_no_int64() {
  11819. assert_eq!(perm_features(128) & 0x8000, 0);
  11820. }
  11821. #[test]
  11822. fn perm_dynamic_selector_needs_no_int64() {
  11823. assert_eq!(
  11824. perm_features(256) & 0x8000,
  11825. 0,
  11826. "dynamic v_perm_b32 must not require INT64"
  11827. );
  11828. }
  11829. #[test]
  11830. fn a_descriptor_selected_by_scc_picks_its_heap_index() {
  11831. // Two buffer descriptors loaded from the table at s0, one picked by
  11832. // a root constant (s1) with s_cselect_b64 per half, and loaded
  11833. // through by index and stored to LDS so the load is needed.
  11834. let words = [
  11835. 0xBE84_0300, // s_mov_b32 s4, s0
  11836. 0xBE85_0380, // s_mov_b32 s5, 0
  11837. 0xF408_0202,
  11838. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null
  11839. 0xF408_0302,
  11840. 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10
  11841. 0xBF06_8001, // s_cmp_eq_u32 s1, 0
  11842. 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13]
  11843. 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15]
  11844. 0xE030_2000,
  11845. 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen
  11846. 0xD834_0000,
  11847. 0x0000_0100, // ds_write_b32 v0, v1
  11848. S_ENDPGM,
  11849. ];
  11850. let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)];
  11851. // Both are structured buffers of dwords in the table's range.
  11852. let used = || {
  11853. vec![UsedResource {
  11854. kind: ResourceType::Srv,
  11855. root: RootType::Table,
  11856. table_offset_dwords: 0,
  11857. lower_bound: 0,
  11858. stride: 4,
  11859. dwords: 4,
  11860. user_data: 0,
  11861. slot: 0,
  11862. }]
  11863. };
  11864. lower_with(&words, layout(), used()).unwrap();
  11865. }
  11866. /// Tables of 2D textures at s0 and samplers at s1.
  11867. fn texture_tables() -> (Vec<RootParam>, Vec<UsedResource>) {
  11868. let range = |kind, user_data, slot| UsedResource {
  11869. kind,
  11870. root: RootType::Table,
  11871. table_offset_dwords: 0,
  11872. lower_bound: 0,
  11873. stride: 0,
  11874. dwords: if kind == ResourceType::Sampler { 4 } else { 8 },
  11875. user_data,
  11876. slot,
  11877. };
  11878. (
  11879. vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)],
  11880. vec![
  11881. range(ResourceType::Srv, 0, 0),
  11882. range(ResourceType::Sampler, 1, 1),
  11883. ],
  11884. )
  11885. }
  11886. #[test]
  11887. fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() {
  11888. use crate::resource::tests::{
  11889. WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32,
  11890. };
  11891. for (words, wave64) in [
  11892. (WATERFALL_FETCHED_WAVE32, false),
  11893. (WATERFALL_FETCHED_WAVE64, true),
  11894. (WATERFALL_PICKED_WAVE32, false),
  11895. ] {
  11896. let (layout, used) = texture_tables();
  11897. let l = lower_wave(words, layout, used, wave64).unwrap();
  11898. // The loop's reads of the first lane became each lane's own
  11899. // dwords: no wave operation is left.
  11900. assert_eq!(l.nonuniform_handles, 1);
  11901. assert!(!l.wave_ops);
  11902. }
  11903. }
  11904. /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first.
  11905. pub(crate) fn texture_and_uav_tables() -> (Vec<RootParam>, Vec<UsedResource>) {
  11906. let (layout, mut used) = texture_tables();
  11907. used.push(UsedResource {
  11908. kind: ResourceType::Uav,
  11909. root: RootType::Table,
  11910. table_offset_dwords: 16,
  11911. lower_bound: 0,
  11912. stride: 0,
  11913. dwords: 4,
  11914. user_data: 0,
  11915. slot: 0,
  11916. });
  11917. (layout, used)
  11918. }
  11919. #[test]
  11920. fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() {
  11921. use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32};
  11922. for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] {
  11923. let (layout, used) = texture_and_uav_tables();
  11924. let l = lower_wave(words, layout, used, false).unwrap();
  11925. // One image handle, from the join's per-lane heap index.
  11926. assert_eq!(l.nonuniform_handles, 1);
  11927. assert!(!l.wave_ops);
  11928. }
  11929. }
  11930. #[test]
  11931. fn scalar_bit_tests_lower() {
  11932. // Each tests one bit of a constant into SCC and branches on it (only
  11933. // code with an effect needs its operands).
  11934. let tail = [
  11935. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  11936. 0xBE84_0380, // s_mov_b32 s4, 0
  11937. S_ENDPGM,
  11938. ];
  11939. let bit_tests: [&[u32]; 4] = [
  11940. &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3
  11941. &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3
  11942. &[
  11943. 0xBE80_0387, // s_mov_b32 s0, 7
  11944. 0xBE81_0380, // s_mov_b32 s1, 0
  11945. 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3
  11946. ],
  11947. &[
  11948. 0xBE80_0387, // s_mov_b32 s0, 7
  11949. 0xBE81_0380, // s_mov_b32 s1, 0
  11950. 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3
  11951. ],
  11952. ];
  11953. for head in bit_tests {
  11954. let words: Vec<u32> = head.iter().chain(&tail).copied().collect();
  11955. lowers(&words, 0).unwrap();
  11956. }
  11957. }
  11958. #[test]
  11959. #[ignore = "ours marks joins read through joins only with VICTORY_STRICT_JOINS (40 programs stop otherwise)"]
  11960. fn a_missing_value_stays_missing_through_two_live_joins() {
  11961. let mut words = [
  11962. 0xF490_0180,
  11963. 0, // s_memtime s[6:7]
  11964. 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X)
  11965. 0xBF85_0001, // skip the first overwrite
  11966. 0xBE86_0380, // s_mov_b32 s6, 0
  11967. 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y)
  11968. 0xBF85_0001, // skip the second overwrite
  11969. 0xBE86_0381, // s_mov_b32 s6, 1
  11970. 0xBF07_8006, // s_cmp_lg_u32 s6, 0
  11971. 0xBF85_0001, // use the result to branch
  11972. 0xBE83_0380,
  11973. S_ENDPGM,
  11974. ];
  11975. let group_ids_xy = 3 << 7;
  11976. // Compare to a direct read so future timestamp support works in both cases.
  11977. let refusal = |code: &[u32]| match lowers(code, group_ids_xy) {
  11978. Ok(()) => None,
  11979. Err(crate::ShaderError::Unsupported { what, .. }) => Some(what),
  11980. Err(error) => panic!("{error}"),
  11981. };
  11982. let direct = [&words[..2], &words[8..]].concat();
  11983. assert_eq!(refusal(&words), refusal(&direct));
  11984. words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead
  11985. lowers(&words, group_ids_xy).expect("dead timestamp");
  11986. }
  11987. #[test]
  11988. fn buffer_formats_by_number() {
  11989. // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM,
  11990. // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT.
  11991. assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm)));
  11992. assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm)));
  11993. assert_eq!(
  11994. buffer_format(50),
  11995. Some((&[10, 10, 10, 2][..], Numeric::Unorm))
  11996. );
  11997. assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float)));
  11998. assert_eq!(
  11999. buffer_format(77),
  12000. Some((&[32, 32, 32, 32][..], Numeric::Float))
  12001. );
  12002. // Invalid, past the table.
  12003. assert_eq!(buffer_format(0), None);
  12004. assert_eq!(buffer_format(78), None);
  12005. }
  12006. #[test]
  12007. fn packed_buffer_formats_by_number() {
  12008. // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43,
  12009. // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT
  12010. // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first.
  12011. assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm)));
  12012. assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float)));
  12013. assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm)));
  12014. assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float)));
  12015. assert_eq!(
  12016. buffer_format(44),
  12017. Some((&[2, 10, 10, 10][..], Numeric::Unorm))
  12018. );
  12019. assert_eq!(
  12020. buffer_format(45),
  12021. Some((&[2, 10, 10, 10][..], Numeric::Snorm))
  12022. );
  12023. assert_eq!(
  12024. buffer_format(46),
  12025. Some((&[2, 10, 10, 10][..], Numeric::Uscaled))
  12026. );
  12027. assert_eq!(
  12028. buffer_format(47),
  12029. Some((&[2, 10, 10, 10][..], Numeric::Sscaled))
  12030. );
  12031. assert_eq!(
  12032. buffer_format(48),
  12033. Some((&[2, 10, 10, 10][..], Numeric::Uint))
  12034. );
  12035. assert_eq!(
  12036. buffer_format(49),
  12037. Some((&[2, 10, 10, 10][..], Numeric::Sint))
  12038. );
  12039. }
  12040. /// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as
  12041. /// `legacyF16ToF32` widens it.
  12042. fn half(h: u32) -> f32 {
  12043. let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023);
  12044. let v = match e {
  12045. 0 => m as f32 * 2f32.powi(-24),
  12046. 31 if m == 0 => f32::INFINITY,
  12047. 31 => f32::NAN,
  12048. _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25),
  12049. };
  12050. if s == 1 { -v } else { v }
  12051. }
  12052. #[test]
  12053. fn small_floats_widen_as_halves() {
  12054. // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a
  12055. // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec.
  12056. let f11 = |x: u32| half(x << half_shift(11));
  12057. let f10 = |x: u32| half(x << half_shift(10));
  12058. assert_eq!(f11(0), 0.0);
  12059. assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal
  12060. assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal
  12061. assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal
  12062. assert_eq!(f11(0x3C0), 1.0);
  12063. assert_eq!(f11(0x3E0), 1.5);
  12064. assert_eq!(f11(0x7BF), 65024.0); // largest
  12065. assert_eq!(f11(0x7C0), f32::INFINITY);
  12066. assert!(f11(0x7C1).is_nan());
  12067. assert_eq!(f10(0x001), 2f32.powi(-19));
  12068. assert_eq!(f10(0x020), 2f32.powi(-14));
  12069. assert_eq!(f10(0x1E0), 1.0);
  12070. assert_eq!(f10(0x3DF), 64512.0);
  12071. assert_eq!(f10(0x3E0), f32::INFINITY);
  12072. assert!(f10(0x3FF).is_nan());
  12073. // A 16-bit float is a half already, sign included.
  12074. assert_eq!(half(0xBC00 << half_shift(16)), -1.0);
  12075. }
  12076. }