lower.rs 279 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995
  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, 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, Resources, Role, Site, Source};
  19. use crate::structure::{Atom, Bool, LaneExit, Structured};
  20. type Why = &'static str;
  21. #[derive(Debug, Clone, Copy)]
  22. enum Val {
  23. I32(V),
  24. Bit(V),
  25. Missing(Why),
  26. }
  27. pub(crate) struct Lowered {
  28. pub dxil: Vec<u8>,
  29. /// Bit n: immediate sampler n is used for comparisons.
  30. pub cmp_samplers: u64,
  31. pub root_cbvs: Vec<u8>,
  32. pub root_srvs: Vec<u8>,
  33. pub user_data: Vec<UserData>,
  34. pub samplers: Vec<[u32; 4]>,
  35. }
  36. pub(crate) struct Parts<'a> {
  37. pub native: &'a NativeProgram,
  38. pub p: &'a Program,
  39. pub st: &'a Structured,
  40. pub io: &'a Io,
  41. pub res: &'a Resources,
  42. pub inputs: Vec<SigElement>,
  43. pub outputs: Vec<SigElement>,
  44. pub prims: Vec<SigElement>,
  45. /// Mesh: what the group id arrives multiplied by.
  46. pub mesh_stride: u32,
  47. }
  48. enum Stop {
  49. /// A phi whose incoming value has no DXIL form was read: redo with it missing.
  50. Retry(Value, Why),
  51. Fail(ShaderError),
  52. }
  53. pub(crate) fn lower(parts: &Parts) -> Result<Lowered, ShaderError> {
  54. let mut bad = HashMap::new();
  55. loop {
  56. match Lower::new(parts, &bad).run() {
  57. Ok(l) => return Ok(l),
  58. Err(Stop::Retry(v, why)) => {
  59. if bad.insert(v, why).is_some() {
  60. return Err(ShaderError::Unsupported {
  61. offset: 0,
  62. what: "a phi that does not settle",
  63. });
  64. }
  65. }
  66. Err(Stop::Fail(e)) => return Err(e),
  67. }
  68. }
  69. }
  70. const TWO_PI: f32 = std::f32::consts::TAU;
  71. /// `s_sendmsg` id of a mesh or NGG stage's output allocation request.
  72. const GS_ALLOC_REQ: u16 = 9;
  73. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  74. enum Numeric {
  75. Unorm,
  76. Snorm,
  77. Uscaled,
  78. Sscaled,
  79. Uint,
  80. Sint,
  81. Float,
  82. }
  83. /// A GFX10 buffer format (the unified format of typed buffer loads): the
  84. /// channel widths from the lowest bits up, and how the channels convert.
  85. /// Formats are numbered in families (`8`, `16`, `8_8`, ...: AMD names
  86. /// list channels from the highest bits), each with its numeric formats in
  87. /// the order unorm, snorm, uscaled, sscaled, uint, sint, float.
  88. fn buffer_format(format: u8) -> Option<(&'static [u32], Numeric)> {
  89. use Numeric::*;
  90. const NORM: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint];
  91. const ALL: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint, Float];
  92. const WIDE: &[Numeric] = &[Uint, Sint, Float];
  93. // Numbers and order from LLVM's `UfmtGFX10` (`SIDefines.h`); the GFX10
  94. // buffer formats have no 5_9_9_9. Channel order from Mesa
  95. // (`ac_formats.c`): R11G11B10_FLOAT is 10_11_11, and 10_10_10_2 has
  96. // its 2-bit channel in the lowest bits.
  97. const FAMILIES: [(&[u32], &[Numeric]); 14] = [
  98. (&[8], NORM),
  99. (&[16], ALL),
  100. (&[8, 8], NORM),
  101. (&[32], WIDE),
  102. (&[16, 16], ALL),
  103. (&[11, 11, 10], ALL), // 10_11_11
  104. (&[10, 11, 11], ALL), // 11_11_10
  105. (&[2, 10, 10, 10], NORM), // 10_10_10_2
  106. (&[10, 10, 10, 2], NORM), // 2_10_10_10
  107. (&[8, 8, 8, 8], NORM),
  108. (&[32, 32], WIDE),
  109. (&[16, 16, 16, 16], ALL),
  110. (&[32, 32, 32], WIDE),
  111. (&[32, 32, 32, 32], WIDE),
  112. ];
  113. let mut n = usize::from(format.checked_sub(1)?);
  114. for (bits, numerics) in FAMILIES {
  115. if n < numerics.len() {
  116. return Some((bits, numerics[n]));
  117. }
  118. n -= numerics.len();
  119. }
  120. None
  121. }
  122. /// How far a float channel of `width` bits (16, or the unsigned 11- and
  123. /// 10-bit floats of the packed formats) shifts up to be a half:
  124. /// the small floats are a half's exponent (5 bits, biased 15) and the top
  125. /// of its mantissa, without the sign, so `legacyF16ToF32` widens them
  126. /// exactly, denormals, infinities and NaNs included.
  127. fn half_shift(width: u32) -> u32 {
  128. debug_assert!(matches!(width, 10 | 11 | 16), "{width}-bit float");
  129. if width == 16 { 0 } else { 15 - width }
  130. }
  131. struct Lower<'a> {
  132. s: Shader,
  133. x: &'a Parts<'a>,
  134. bad: &'a HashMap<Value, Why>,
  135. lane_fail: HashMap<Value, Why>,
  136. vals: HashMap<Value, Val>,
  137. floats: HashMap<Value, V>,
  138. /// DXIL block per IR block (unreachable: none).
  139. block: Vec<Option<usize>>,
  140. cur: usize,
  141. bools: HashMap<(usize, Bool), V>,
  142. lane_bits: HashMap<Value, V>,
  143. /// IR phi location by value.
  144. phi_at: HashMap<Value, (usize, usize)>,
  145. mask_phis: HashMap<Value, V>,
  146. pending_masks: Vec<(V, usize, usize)>,
  147. data_phis: Vec<(V, usize, usize)>,
  148. read_phis: HashSet<Value>,
  149. params: HashMap<Value, (usize, u32)>,
  150. user_data: Option<V>,
  151. user_reads: BTreeMap<u32, UserData>,
  152. samplers: Vec<[u32; 4]>,
  153. descriptors: HashMap<(Site, bool), &'a Source>,
  154. scalar: HashMap<Site, Address>,
  155. exports: HashMap<Site, &'a Export>,
  156. interps: HashMap<Site, &'a Interp>,
  157. handles: HashMap<(usize, Site, u8, bool, u32), V>,
  158. /// Blocks splitting the edge from one IR block to another.
  159. edges: HashMap<(usize, usize), usize>,
  160. /// Per IR block: a `done` export is behind every lane entering it.
  161. exported: Vec<bool>,
  162. /// Reverse-postorder index per IR block.
  163. rpo: Vec<usize>,
  164. /// DXIL block each IR block ends in (guarded stores split blocks).
  165. tail: Vec<Option<usize>>,
  166. /// The program writes UAVs: barriers fence them too.
  167. writes_uavs: bool,
  168. /// src0 of the current instruction as DPP fetched it.
  169. src0: Option<V>,
  170. /// Compute code that reads other lanes: thread ids follow the host
  171. /// lanes, so lane n is console lane n.
  172. console_lanes: bool,
  173. /// Mesh: the thread index in the group (made in the entry block).
  174. flat: Option<V>,
  175. /// Mesh: IR blocks whose `s_barrier` is left out.
  176. no_barrier: HashSet<usize>,
  177. /// Vertex and mesh outputs holding 16-bit values: row, whether two per
  178. /// dword, and the row packed after it.
  179. half_outputs: HashMap<u8, (bool, Option<u8>)>,
  180. /// How lane masks become data.
  181. mask_data: MaskData,
  182. /// The instruction being lowered may read lane masks as data.
  183. mask_ok: bool,
  184. /// Ballots of masks read as data, by low dword: (low, high).
  185. ballots: HashMap<Value, (V, V)>,
  186. /// Masks whose ballot is being built: a mask whose lane bit needs its
  187. /// own value as a number (an opaque mask keyed by a dword it shares
  188. /// with another) would otherwise recurse until the stack overflows.
  189. balloting: HashSet<Value>,
  190. /// Block writing each value.
  191. def_block: HashMap<Value, usize>,
  192. /// IR block being lowered.
  193. cur_ir: usize,
  194. /// Whole-wave sections by block and start index.
  195. sections: HashMap<usize, HashMap<usize, super::wave::Section>>,
  196. /// Values written in a section that code outside it reads.
  197. section_out: HashSet<Value>,
  198. /// The program's constant table (the code from the first byte read
  199. /// through `s_getpc_b64` on): global, first byte, dwords.
  200. code_table: Option<(V, u32, u32)>,
  201. /// Loop headers' iteration counters (see [`LOOP_LIMIT`]): the phi by
  202. /// IR block, and its incoming (value, DXIL block) pairs.
  203. counters: HashMap<usize, (V, Vec<(V, usize)>)>,
  204. /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from.
  205. abort: Option<usize>,
  206. }
  207. /// Iterations after which a loop is left (per entry into it), unless
  208. /// [`super::loop_limit`] says otherwise. The console runs a loop as long as
  209. /// its data says; data the host has not mirrored yet (a null view reads
  210. /// zeros) can make that four billion iterations, which hangs the host GPU
  211. /// until the driver resets it. A lane that reaches the limit leaves the
  212. /// program as killed (a pixel discards).
  213. // shortcut: a genuine loop of more iterations than this is cut short too.
  214. pub(super) const LOOP_LIMIT: u32 = 1 << 20;
  215. /// Lane masks read as numbers (`s_bcnt1`, `s_ff1`, `v_mbcnt`, scalar
  216. /// compares, bit tests) are ballots of the lanes' booleans, taken where the
  217. /// mask is written: structurisation's `active` masks hold only lanes that
  218. /// reach that block, so the ballot misses none.
  219. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  220. enum MaskData {
  221. /// Compute: host lane n is console lane n (the program declares the
  222. /// console's wave size), so ballots are the console's masks bit for bit
  223. /// and any use is exact.
  224. Console,
  225. /// Pixel and vertex programs: ballots over the host's wave, whatever its
  226. /// size. Only uses that mean the same on any wave are allowed: counts,
  227. /// the first lane, the count below a lane, equality (the HLSL wave
  228. /// operations the console compiler expands). Lane numbers stay host
  229. /// lanes throughout (`v_mbcnt`, `v_readlane` at a computed lane).
  230. Host,
  231. /// Mesh programs: their lanes and waves (LDS per console wave) are the
  232. /// console's but no host wave size can be declared.
  233. None,
  234. }
  235. /// What a value holding a lane mask read as a number stops with.
  236. const LANE_MASK: Why = "a lane mask read as data";
  237. /// Instructions that read a lane mask (not EXEC implicitly, not a lane's
  238. /// bit) as a number.
  239. fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool {
  240. let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
  241. let ops: Vec<&Operand> = match &i.fields {
  242. // A mask operation (its result a mask) is no data use.
  243. Fields::Sop { .. }
  244. if i.writes
  245. .iter()
  246. .any(|&(r, w)| matches!(r, Reg::S(_)) && is_mask(w)) =>
  247. {
  248. return false;
  249. }
  250. Fields::Sop { src, .. } => src.iter().collect(),
  251. Fields::Valu(v)
  252. if !matches!(i.name(), "v_cndmask_b32") && !i.name().contains("_co_ci_") =>
  253. {
  254. v.src.iter().collect()
  255. }
  256. _ => return false,
  257. };
  258. ops.into_iter().any(|op| match *op {
  259. Operand::Scalar { code, .. } if code != NULL => i.read(Reg::S(code)).is_some_and(is_mask),
  260. _ => false,
  261. })
  262. }
  263. /// Where half `h` (dword h / 2, the high half when odd) of a parameter
  264. /// packing 16-bit rows `a` and `b` two per dword comes from: a row and
  265. /// channel of `elements`, none for padding. Channel c of `a` is half c;
  266. /// `b` starts at the dword after `a`'s last channel.
  267. fn packed_half(elements: &[SigElement], a: u8, b: Option<u8>, h: u8) -> Option<(u8, u8)> {
  268. let extent = |r: u8| {
  269. elements
  270. .iter()
  271. .filter(|e| e.row == Some(u32::from(r)))
  272. .map(|e| e.col + e.cols)
  273. .max()
  274. };
  275. let na = extent(a)?;
  276. let a_halves = na.div_ceil(2) * 2;
  277. if h < a_halves {
  278. return (h < na).then_some((a, h));
  279. }
  280. let b = b?;
  281. let c = h - a_halves;
  282. (c < extent(b)?).then_some((b, c))
  283. }
  284. /// Vertex or mesh outputs of 16-bit values (see [`Lower::half_outputs`]):
  285. /// a packed row's partner is the next 16-bit row of the signature that no
  286. /// output entry names, taken in row order.
  287. fn half_outputs(io: &StageIo, outputs: &[SigElement]) -> HashMap<u8, (bool, Option<u8>)> {
  288. let entries = match io {
  289. StageIo::Vs { outputs, .. } => outputs,
  290. StageIo::Ms(ms) => &ms.outputs,
  291. _ => return HashMap::new(),
  292. };
  293. let per_vertex = || entries.iter().filter(|o| o.param & 0x80 == 0);
  294. let mut free: Vec<u8> = outputs
  295. .iter()
  296. .filter(|e| e.half && e.kind == 0)
  297. .filter_map(|e| u8::try_from(e.row?).ok())
  298. .filter(|&r| !per_vertex().any(|o| o.row == r))
  299. .collect();
  300. free.sort_unstable();
  301. free.dedup();
  302. let mut halves: Vec<_> = per_vertex().filter(|o| o.fp16).collect();
  303. halves.sort_by_key(|o| o.row);
  304. halves
  305. .into_iter()
  306. .map(|o| {
  307. let b = o
  308. .pack2
  309. .then(|| free.iter().position(|&r| r > o.row))
  310. .flatten();
  311. (o.row, (o.pack2, b.map(|i| free.remove(i))))
  312. })
  313. .collect()
  314. }
  315. fn unsupported(offset: usize, what: Why) -> Stop {
  316. Stop::Fail(ShaderError::Unsupported { offset, what })
  317. }
  318. impl<'a> Lower<'a> {
  319. fn new(x: &'a Parts<'a>, bad: &'a HashMap<Value, Why>) -> Self {
  320. let p = x.p;
  321. let mut phi_at = HashMap::new();
  322. for (b, block) in p.blocks.iter().enumerate() {
  323. for (i, phi) in block.phis.iter().enumerate() {
  324. phi_at.insert(phi.value, (b, i));
  325. }
  326. }
  327. let mut s = Shader::new(x.native.stage == HwStage::Ps);
  328. s.inputs = x.inputs.clone();
  329. s.outputs = x.outputs.clone();
  330. let insts = || p.blocks.iter().flat_map(|b| &b.insts);
  331. let writes_uavs = insts().any(|i| {
  332. matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. })
  333. && (i.name().contains("store") || i.name().contains("atomic"))
  334. });
  335. let mut console_lanes = false;
  336. if let StageIo::Cs(cs) = x.native.io {
  337. s.threads = Some(cs.threads);
  338. s.lds_dwords = cs.lds_bytes() / 4;
  339. // Code reading other lanes needs the console's wave size and
  340. // lane order; so do lane masks read as numbers, and LDS shared
  341. // within one wave, where the console compiler leaves out barriers.
  342. console_lanes = insts().any(|i| {
  343. let n = i.name();
  344. n.starts_with("ds_swizzle")
  345. || n.contains("permute")
  346. || n.starts_with("v_mbcnt")
  347. || matches!(n, "v_readlane_b32" | "v_writelane_b32")
  348. || matches!(&i.fields, Fields::Valu(v) if v.dpp.is_some())
  349. || reads_mask_as_data(x.st, i)
  350. }) || {
  351. // Masks held as numbers or constant lane sets: the lane
  352. // tests its own bit by its console lane.
  353. let whens = x.st.exits.iter().filter_map(|e| match *e {
  354. LaneExit::Branch { when, .. } => Some(when),
  355. _ => None,
  356. });
  357. let mut all: Vec<Bool> =
  358. x.st.guards
  359. .iter()
  360. .flatten()
  361. .flatten()
  362. .copied()
  363. .chain(whens)
  364. .collect();
  365. all.sort_unstable();
  366. all.dedup();
  367. all.into_iter().any(|g| {
  368. x.st.bools
  369. .support(g)
  370. .iter()
  371. .any(|a| matches!(a, Atom::Opaque(_) | Atom::Constant(_)))
  372. })
  373. };
  374. let wave = if x.native.wave64 { 64 } else { 32 };
  375. let one_wave = cs.threads.iter().product::<u32>() <= wave;
  376. if console_lanes || one_wave && s.lds_dwords > 0 {
  377. s.wave_size = Some(wave);
  378. }
  379. }
  380. let mut no_barrier = HashSet::new();
  381. if let StageIo::Ms(ms) = &x.native.io {
  382. s.prims = x.prims.clone();
  383. s.threads = Some([ms.threads, 1, 1]);
  384. s.lds_dwords = ms.lds_bytes.div_ceil(4);
  385. s.mesh = Some(super::shader::Mesh {
  386. max_vertices: ms.max_vertices,
  387. max_primitives: ms.max_primitives,
  388. topology: ms.topology,
  389. });
  390. // Barriers order the lanes' LDS accesses; the console's
  391. // allocation request needs them too, but the host does not. One
  392. // lane sends that request, and what it dominates (the path for
  393. // counts out of range) runs in that lane alone, so its barrier
  394. // would hang the host.
  395. let order = crate::ir::reverse_postorder(&p.blocks);
  396. let mut index = vec![usize::MAX; p.blocks.len()];
  397. for (n, &b) in order.iter().enumerate() {
  398. index[b] = n;
  399. }
  400. let idom = crate::ir::idoms(&p.blocks, &order, &index);
  401. let alloc: Vec<usize> = (0..p.blocks.len())
  402. .filter(|&b| {
  403. p.blocks[b].insts.iter().any(|i| {
  404. i.name() == "s_sendmsg"
  405. && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == GS_ALLOC_REQ)
  406. })
  407. })
  408. .collect();
  409. for &b in &order {
  410. let mut d = b;
  411. let dominated = loop {
  412. if alloc.contains(&d) {
  413. break true;
  414. }
  415. if idom[d] == d || idom[d] == usize::MAX {
  416. break false;
  417. }
  418. d = idom[d];
  419. };
  420. if ms.lds_bytes == 0 || dominated {
  421. no_barrier.insert(b);
  422. }
  423. }
  424. }
  425. Lower {
  426. s,
  427. x,
  428. bad,
  429. lane_fail: HashMap::new(),
  430. vals: HashMap::new(),
  431. floats: HashMap::new(),
  432. block: vec![None; p.blocks.len()],
  433. cur: 0,
  434. bools: HashMap::new(),
  435. lane_bits: HashMap::new(),
  436. phi_at,
  437. mask_phis: HashMap::new(),
  438. pending_masks: Vec::new(),
  439. data_phis: Vec::new(),
  440. read_phis: HashSet::new(),
  441. params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(),
  442. user_data: None,
  443. user_reads: BTreeMap::new(),
  444. samplers: Vec::new(),
  445. descriptors: x
  446. .res
  447. .descriptors
  448. .iter()
  449. .map(|d| ((d.site, d.role == Role::Sampler), &d.source))
  450. .collect(),
  451. scalar: x.res.scalar.iter().copied().collect(),
  452. exports: x.io.exports.iter().map(|e| (e.site, e)).collect(),
  453. interps: x.io.interps.iter().map(|(s, i)| (*s, i)).collect(),
  454. handles: HashMap::new(),
  455. edges: HashMap::new(),
  456. exported: vec![false; p.blocks.len()],
  457. rpo: vec![usize::MAX; p.blocks.len()],
  458. tail: vec![None; p.blocks.len()],
  459. writes_uavs,
  460. src0: None,
  461. console_lanes,
  462. flat: None,
  463. no_barrier,
  464. half_outputs: half_outputs(&x.native.io, &x.outputs),
  465. mask_data: match x.native.stage {
  466. HwStage::Cs => MaskData::Console,
  467. HwStage::Ps | HwStage::Vs => MaskData::Host,
  468. _ => MaskData::None,
  469. },
  470. mask_ok: false,
  471. ballots: HashMap::new(),
  472. balloting: HashSet::new(),
  473. def_block: p
  474. .blocks
  475. .iter()
  476. .enumerate()
  477. .flat_map(|(b, block)| {
  478. block
  479. .insts
  480. .iter()
  481. .flat_map(move |i| i.writes.iter().map(move |w| (w.1, b)))
  482. .chain(block.phis.iter().map(move |phi| (phi.value, b)))
  483. })
  484. .collect(),
  485. cur_ir: 0,
  486. sections: HashMap::new(),
  487. section_out: HashSet::new(),
  488. code_table: None,
  489. counters: HashMap::new(),
  490. abort: None,
  491. }
  492. }
  493. /// The dword of the program's code at byte `byte` (a constant table
  494. /// the compiler appends to the code), as an internal constant array.
  495. // shortcut: an index outside the table reads its last dword (the
  496. // console would read whatever memory follows the code).
  497. fn code_dword(&mut self, byte: V) -> Result<V, Why> {
  498. let (g, base, len) = match self.code_table {
  499. Some(t) => t,
  500. None => {
  501. let first = self
  502. .x
  503. .res
  504. .scalar
  505. .iter()
  506. .map(|s| s.1)
  507. .chain(self.x.res.descriptors.iter().flat_map(|d| {
  508. d.source.leaves().into_iter().filter_map(|l| match l {
  509. Source::Built { address, .. } => Some(*address),
  510. _ => None,
  511. })
  512. }))
  513. .filter(|a| a.param == CODE)
  514. .map(|a| a.offset & !3)
  515. .min()
  516. .ok_or("a code table")?;
  517. let code = &self.x.native.code;
  518. let words: Vec<u32> = code
  519. .get(first as usize..)
  520. .ok_or("a code table past the code")?
  521. .chunks(4)
  522. .map(|c| {
  523. let mut w = [0u8; 4];
  524. w[..c.len()].copy_from_slice(c);
  525. u32::from_le_bytes(w)
  526. })
  527. .collect();
  528. if words.is_empty() {
  529. return Err("a code table past the code");
  530. }
  531. let elems: Vec<V> = words.iter().map(|&w| self.s.m.i32(w)).collect();
  532. let arr = self.s.m.array(words.len() as u32, self.s.t.i32);
  533. let init = self.s.m.aggregate(arr, &elems);
  534. let g = self.s.m.constant_global("code", init);
  535. let t = (g, first, words.len() as u32);
  536. self.code_table = Some(t);
  537. t
  538. }
  539. };
  540. let c = self.cur;
  541. let k = self.s.m.i32(base);
  542. let rel = self.s.m.bin(c, Bin::Sub, byte, k);
  543. let two = self.s.m.i32(2);
  544. let index = self.s.m.bin(c, Bin::LShr, rel, two);
  545. let last = self.s.m.i32(len - 1);
  546. let over = self.s.m.cmp(c, pred::IUGT, index, last);
  547. let index = self.s.m.select(c, over, last, index);
  548. let at = self.s.m.element(c, g, index);
  549. Ok(self.s.m.load(c, at))
  550. }
  551. /// A global memory load (`global_load_*`): from the program's constant
  552. /// table, or from a root SRV at the address the title sets.
  553. fn flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  554. let Fields::Flat { dst, .. } = &inst.fields else {
  555. unreachable!()
  556. };
  557. let name = inst.name();
  558. let rest = name
  559. .strip_prefix("global_load_")
  560. .ok_or("a global memory write")?;
  561. let (n, sub) = match rest {
  562. "dword" => (1, None),
  563. "dwordx2" => (2, None),
  564. "dwordx3" => (3, None),
  565. "dwordx4" => (4, None),
  566. "ubyte" => (1, Some((8, false))),
  567. "sbyte" => (1, Some((8, true))),
  568. "ushort" => (1, Some((16, false))),
  569. "sshort" => (1, Some((16, true))),
  570. _ => return Err(name),
  571. };
  572. let a = *self
  573. .scalar
  574. .get(&(b, i))
  575. .ok_or("an untracked global address")?;
  576. let guard = self.guard(b, i)?;
  577. let Some(Operand::Vector { reg, .. }) = *dst else {
  578. return Err("a global load result");
  579. };
  580. let c = self.cur;
  581. let mut off = self.s.m.i32(a.offset);
  582. if let Some(d) = a.dynamic {
  583. let d = self.i32_of(d)?;
  584. off = self.s.m.bin(c, Bin::Add, off, d);
  585. }
  586. let h = if a.param == CODE {
  587. None
  588. } else {
  589. let src = Source::Built {
  590. address: a,
  591. bits: 0,
  592. words: [0, 0],
  593. };
  594. Some(self.handle((b, i), &src, false, (11, 0))?)
  595. };
  596. let dword = |l: &mut Self, byte: V| -> Result<V, Why> {
  597. match h {
  598. None => l.code_dword(byte),
  599. Some(h) => {
  600. let c = l.cur;
  601. let (u, mask, al) = (l.s.m.undef(l.s.t.i32), l.s.m.i8(1), l.s.m.i32(4));
  602. let r = l.s.op(
  603. c,
  604. "rawBufferLoad.f32",
  605. Attr::ReadOnly,
  606. l.s.t.res_ret,
  607. 139,
  608. &[h, byte, u, mask, al],
  609. );
  610. let x = l.s.m.extract(c, r, 0);
  611. Ok(l.as_int(x))
  612. }
  613. }
  614. };
  615. for k in 0..n {
  616. let x = match sub {
  617. None => {
  618. let four = self.s.m.i32(4 * k);
  619. let at = self.s.m.bin(c, Bin::Add, off, four);
  620. dword(self, at)?
  621. }
  622. Some((width, signed)) => {
  623. // shortcut: the field is taken not to cross a dword.
  624. let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3));
  625. let at = self.s.m.bin(c, Bin::And, off, not3);
  626. let w = dword(self, at)?;
  627. let byte = self.s.m.bin(c, Bin::And, off, three);
  628. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  629. let x = self.s.m.bin(c, Bin::LShr, w, sh);
  630. let left = self.s.m.i32(32 - width);
  631. let x = self.s.m.bin(c, Bin::Shl, x, left);
  632. self.s
  633. .m
  634. .bin(c, if signed { Bin::AShr } else { Bin::LShr }, x, left)
  635. }
  636. };
  637. self.write(inst, Reg::V(reg + k as u8), x, guard);
  638. }
  639. Ok(())
  640. }
  641. /// Finds the whole-wave sections and the values they leave.
  642. fn find_sections(&mut self) {
  643. let p = self.x.p;
  644. let mut inside: HashMap<Value, (usize, usize, usize)> = HashMap::new();
  645. for b in 0..p.blocks.len() {
  646. let found = super::wave::sections(p, b);
  647. for (&start, sec) in &found {
  648. for i in start + 1..sec.end {
  649. for &(_, w) in &p.blocks[b].insts[i].writes {
  650. inside.insert(w, (b, start, sec.end));
  651. }
  652. }
  653. }
  654. if !found.is_empty() {
  655. self.sections.insert(b, found);
  656. }
  657. }
  658. if inside.is_empty() {
  659. return;
  660. }
  661. for (b, block) in p.blocks.iter().enumerate() {
  662. for phi in &block.phis {
  663. self.section_out
  664. .extend(phi.args.iter().filter(|a| inside.contains_key(a)));
  665. }
  666. for (i, inst) in block.insts.iter().enumerate() {
  667. for &(_, r) in &inst.reads {
  668. if let Some(&(sb, start, end)) = inside.get(&r)
  669. && !(sb == b && i > start && i < end)
  670. {
  671. self.section_out.insert(r);
  672. }
  673. }
  674. }
  675. }
  676. }
  677. /// An instruction inside a whole-wave section: the values that leave
  678. /// the section are made from what the simulation found them to be.
  679. fn section_inst(&mut self, b: usize, i: usize, start: usize) {
  680. const UNKNOWN: Why = "a whole-wave section step the simulation does not follow";
  681. let inst = &self.x.p.blocks[b].insts[i];
  682. for &(_, w) in &inst.writes {
  683. let val = if self.section_out.contains(&w) {
  684. let shape = self.sections[&b][&start].shapes.get(&w).copied();
  685. match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh)) {
  686. Ok(x) => Val::I32(x),
  687. Err(why) => Val::Missing(why),
  688. }
  689. } else {
  690. Val::Missing(UNKNOWN)
  691. };
  692. self.vals.insert(w, val);
  693. }
  694. }
  695. /// A value a whole-wave section leaves, as DXIL wave operations over the
  696. /// host's active lanes: the console's result with console lanes; on
  697. /// another wave size, what the HLSL wave operation the console compiler
  698. /// expanded gives on that wave.
  699. fn shape(&mut self, shape: super::wave::Shape) -> Result<V, Why> {
  700. use super::wave::{Op, Shape};
  701. let (op, src, mask, ident, prefix) = match shape {
  702. Shape::K(k) => return Ok(self.s.m.i32(k)),
  703. Shape::Value(v) => return self.i32_of(v),
  704. Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None),
  705. Shape::Masked(src, mask, ident) => {
  706. let c = self.cur;
  707. let &m = self
  708. .x
  709. .st
  710. .masks
  711. .get(&mask)
  712. .ok_or("a wave reduction's untracked mask")?;
  713. let on = self.boolean(m, c)?;
  714. let x = self.i32_of(src)?;
  715. let id = self.s.m.i32(ident);
  716. return Ok(self.s.m.select(c, on, x, id));
  717. }
  718. Shape::Prefix(op, src, mask, ident, inclusive) => {
  719. (op, src, mask, ident, Some(inclusive))
  720. }
  721. };
  722. if self.mask_data == MaskData::None {
  723. return Err("a wave reduction in a mesh shader");
  724. }
  725. let c = self.cur;
  726. let &m = self
  727. .x
  728. .st
  729. .masks
  730. .get(&mask)
  731. .ok_or("a wave reduction's untracked mask")?;
  732. let on = self.boolean(m, c)?;
  733. let x = self.i32_of(src)?;
  734. let id = self.s.m.i32(ident);
  735. let x = self.s.m.select(c, on, x, id);
  736. self.s.flags |= flags::WAVE_OPS;
  737. let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF);
  738. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  739. let arg = if float { self.as_float(x) } else { x };
  740. let ty = if float { f32t } else { i32t };
  741. let sfx = if float { "f32" } else { "i32" };
  742. let r = match (op, prefix) {
  743. (Op::AddU | Op::AddF, Some(inclusive)) => {
  744. let (k0, k1) = (self.s.m.i8(0), self.s.m.i8(1));
  745. let r = self.s.op(
  746. c,
  747. &format!("wavePrefixOp.{sfx}"),
  748. Attr::NoUnwind,
  749. ty,
  750. 121,
  751. &[arg, k0, k1],
  752. );
  753. if inclusive {
  754. self.s.m.bin(c, Bin::Add, r, arg)
  755. } else {
  756. r
  757. }
  758. }
  759. (_, Some(_)) => return Err("a wave prefix of an operation other than a sum"),
  760. (Op::Or | Op::And | Op::Xor, None) => {
  761. let k = self.s.m.i8(match op {
  762. Op::And => 0,
  763. Op::Or => 1,
  764. _ => 2,
  765. });
  766. self.s
  767. .op(c, "waveActiveBit.i32", Attr::NoUnwind, i32t, 120, &[arg, k])
  768. }
  769. (_, None) => {
  770. let (code, unsigned) = match op {
  771. Op::AddU => (0, 1),
  772. Op::AddF => (0, 0),
  773. Op::MinU => (2, 1),
  774. Op::MaxU => (3, 1),
  775. Op::MinI | Op::MinF => (2, 0),
  776. _ => (3, 0),
  777. };
  778. let (k, u) = (self.s.m.i8(code), self.s.m.i8(unsigned));
  779. self.s.op(
  780. c,
  781. &format!("waveActiveOp.{sfx}"),
  782. Attr::NoUnwind,
  783. ty,
  784. 119,
  785. &[arg, k, u],
  786. )
  787. }
  788. };
  789. Ok(if float { self.as_int(r) } else { r })
  790. }
  791. fn run(mut self) -> Result<Lowered, Stop> {
  792. let p = self.x.p;
  793. let order = crate::ir::reverse_postorder(&p.blocks);
  794. for (n, &b) in order.iter().enumerate() {
  795. self.rpo[b] = n;
  796. }
  797. for (n, &b) in order.iter().enumerate() {
  798. self.block[b] = Some(if n == 0 {
  799. self.s.entry
  800. } else {
  801. self.s.m.new_block()
  802. });
  803. }
  804. // Loop headers count iterations (`LOOP_LIMIT`).
  805. for &b in &order {
  806. let header = p.blocks[b]
  807. .preds
  808. .iter()
  809. .any(|&q| self.block[q].is_some() && self.rpo[b] <= self.rpo[q]);
  810. if header {
  811. let blk = self.block[b].expect("reachable");
  812. let phi = self.s.m.phi(blk, self.s.t.i32);
  813. self.counters.insert(b, (phi, Vec::new()));
  814. }
  815. }
  816. self.cur = self.s.entry;
  817. self.find_sections();
  818. self.inputs()?;
  819. if let Some(mesh) = self.s.mesh {
  820. self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?;
  821. self.block[order[0]] = Some(self.cur);
  822. }
  823. for &b in &order {
  824. self.cur = self.block[b].expect("reachable");
  825. self.cur_ir = b;
  826. let preds: Vec<usize> = p.blocks[b]
  827. .preds
  828. .iter()
  829. .copied()
  830. .filter(|&q| self.block[q].is_some())
  831. .collect();
  832. self.exported[b] = !preds.is_empty() && preds.iter().all(|&q| self.exported_out(q));
  833. for (i, phi) in p.blocks[b].phis.iter().enumerate() {
  834. let val = match phi.reg {
  835. Reg::S(c) if c == EXEC || c == EXEC + 1 => Val::Missing("a lane mask"),
  836. _ if self.bad.contains_key(&phi.value) => Val::Missing(self.bad[&phi.value]),
  837. Reg::Scc => {
  838. let v = self.s.m.phi(self.cur, self.s.t.i1);
  839. self.data_phis.push((v, b, i));
  840. Val::Bit(v)
  841. }
  842. _ => {
  843. let v = self.s.m.phi(self.cur, self.s.t.i32);
  844. self.data_phis.push((v, b, i));
  845. Val::I32(v)
  846. }
  847. };
  848. self.vals.insert(phi.value, val);
  849. }
  850. let mut i = 0;
  851. while i < p.blocks[b].insts.len() {
  852. self.inst(b, i)?;
  853. if let Some(end) = self.sections.get(&b).and_then(|s| s.get(&i)).map(|s| s.end) {
  854. for j in i + 1..end {
  855. self.section_inst(b, j, i);
  856. }
  857. i = end;
  858. continue;
  859. }
  860. i += 1;
  861. }
  862. self.mask_ok = self.mask_data == MaskData::Console;
  863. self.tail[b] = Some(self.cur);
  864. self.exit(b)?;
  865. }
  866. self.fill_phis()?;
  867. let user_data = self.user_reads.values().copied().collect();
  868. self.s.samplers = self.samplers.len() as u32;
  869. let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect();
  870. let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect();
  871. let cmp_samplers = self.s.cmp_samplers;
  872. Ok(Lowered {
  873. cmp_samplers,
  874. root_cbvs,
  875. root_srvs,
  876. dxil: self.s.finish(),
  877. user_data,
  878. samplers: self.samplers,
  879. })
  880. }
  881. fn exported_out(&self, b: usize) -> bool {
  882. self.exported[b] || self.has_done_export(b)
  883. }
  884. fn has_done_export(&self, b: usize) -> bool {
  885. (0..self.x.p.blocks[b].insts.len())
  886. .any(|i| self.exports.get(&(b, i)).is_some_and(|e| e.done))
  887. }
  888. /// Values of the program's input registers.
  889. fn inputs(&mut self) -> Result<(), Stop> {
  890. let io_inputs: HashMap<Value, Input> = self.x.io.inputs.iter().copied().collect();
  891. for &(reg, v) in &self.x.p.inputs {
  892. let val = match reg {
  893. Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use
  894. Reg::S(n) => match io_inputs.get(&v) {
  895. Some(&input) => self.input(input),
  896. // Above the SGPRs the hardware initializes, a register
  897. // holds what the last wave left, so no program depends
  898. // on it: a read the paths only seem to allow (a branch
  899. // past the write, taken only with one past the read)
  900. // reads zero, as VGPRs do.
  901. None if n <= 105 && self.x.io.initialized_sgprs.is_some_and(|k| n >= k) => {
  902. Val::I32(self.s.m.i32(0))
  903. }
  904. None => Val::Missing("a hardware SGPR input"),
  905. },
  906. Reg::Scc => Val::Missing("SCC on entry"),
  907. Reg::V(_) => match io_inputs.get(&v) {
  908. Some(&input) => self.input(input),
  909. // Registers no one set read as zero (the validator
  910. // refuses reads of undef).
  911. None => Val::I32(self.s.m.i32(0)),
  912. },
  913. };
  914. self.vals.insert(v, val);
  915. }
  916. Ok(())
  917. }
  918. fn input(&mut self, input: Input) -> Val {
  919. let (kind, col) = match input {
  920. Input::VertexId => (1, 0),
  921. Input::InstanceId => (2, 0),
  922. Input::Position(c) => (3, c),
  923. Input::Attribute { row, channel } => {
  924. return match self.find_input(row, channel) {
  925. Some((id, col)) => self.load_input(id, col),
  926. None => Val::Missing("a vertex input the signature lacks"),
  927. };
  928. }
  929. Input::Barycentric { .. } => return Val::Missing("barycentrics read directly"),
  930. Input::PrimitiveId => return Val::Missing("the primitive id"),
  931. // The console code tests it against 0 (`v_cmp_ne_u32`), as the
  932. // host's value can be.
  933. Input::FrontFace => (13, 0),
  934. Input::ThreadIdInGroup(c) => return self.thread_id(c),
  935. Input::GroupId(c) => return self.compute_id("groupId.i32", 94, c),
  936. Input::GroupInfo => return Val::Missing("the thread-group info SGPR"),
  937. Input::MeshGroup => {
  938. let Val::I32(g) = self.compute_id("groupId.i32", 94, 0) else {
  939. unreachable!()
  940. };
  941. let n = self.s.m.i32(self.x.mesh_stride);
  942. return Val::I32(self.s.m.bin(self.s.entry, Bin::Mul, g, n));
  943. }
  944. Input::MergedWaveInfo => {
  945. // shortcut: only the wave index (bits 24-27) is set; the
  946. // console's other bits (lane counts) are read by no program.
  947. let f = self.mesh_thread();
  948. let shift = self.s.m.i32(self.wave().trailing_zeros());
  949. let w = self.s.m.bin(self.s.entry, Bin::LShr, f, shift);
  950. let k24 = self.s.m.i32(24);
  951. return Val::I32(self.s.m.bin(self.s.entry, Bin::Shl, w, k24));
  952. }
  953. _ => return Val::Missing("a pixel system input"),
  954. };
  955. let free = self
  956. .s
  957. .inputs
  958. .iter()
  959. .filter_map(|e| e.row)
  960. .map(|r| r + 1)
  961. .max()
  962. .unwrap_or(0);
  963. let id = match self.s.inputs.iter().position(|e| e.kind == kind) {
  964. Some(id) => {
  965. if kind != 3 {
  966. self.s.inputs[id].row.get_or_insert(free);
  967. }
  968. id
  969. }
  970. None if kind >= 3 => return Val::Missing("a pixel system input the signature lacks"),
  971. None => {
  972. // The console signature leaves out vertex and instance ids; PC
  973. // gives them a row after the others.
  974. let row = self
  975. .s
  976. .inputs
  977. .iter()
  978. .filter_map(|e| e.row)
  979. .map(|r| r + 1)
  980. .max()
  981. .unwrap_or(0);
  982. self.s.inputs.push(SigElement {
  983. name: ["", "SV_VertexID", "SV_InstanceID"][kind as usize].into(),
  984. index: 0,
  985. kind,
  986. comp: 5,
  987. interp: 0,
  988. row: Some(row),
  989. col: 0,
  990. cols: 1,
  991. usage: 0,
  992. half: false,
  993. });
  994. self.s.inputs.len() - 1
  995. }
  996. };
  997. self.load_input(id, col)
  998. }
  999. /// A component of a compute thread or group id, read in the entry block.
  1000. fn compute_id(&mut self, name: &str, opcode: u32, c: u8) -> Val {
  1001. let (entry, c) = (self.s.entry, self.s.m.i32(u32::from(c)));
  1002. Val::I32(
  1003. self.s
  1004. .op(entry, name, Attr::ReadNone, self.s.t.i32, opcode, &[c]),
  1005. )
  1006. }
  1007. fn find_input(&self, row: u8, channel: u8) -> Option<(usize, u8)> {
  1008. self.s.inputs.iter().enumerate().find_map(|(id, e)| {
  1009. let r = e.row?;
  1010. // `then`, not `then_some`: the channel is only past `col` when
  1011. // the condition holds.
  1012. (r == u32::from(row) && channel >= e.col && channel < e.col + e.cols)
  1013. .then(|| (id, channel - e.col))
  1014. })
  1015. }
  1016. fn load_input(&mut self, id: usize, col: u8) -> Val {
  1017. if self.s.inputs[id].half {
  1018. // shortcut: 16-bit vertex inputs (the fetch routine's) are not
  1019. // unpacked; pixel inputs are (`interp`).
  1020. return Val::Missing("a 16-bit input");
  1021. }
  1022. self.load_any_input(id, col)
  1023. }
  1024. /// An input element's channel as declared (16-bit ones as 32-bit floats).
  1025. fn load_any_input(&mut self, id: usize, col: u8) -> Val {
  1026. let e = &mut self.s.inputs[id];
  1027. e.usage |= 1 << col;
  1028. let (int, bit) = (e.comp != 9, e.comp == 1);
  1029. let ty = if bit {
  1030. self.s.t.i1
  1031. } else if int {
  1032. self.s.t.i32
  1033. } else {
  1034. self.s.t.f32
  1035. };
  1036. let suffix = if bit {
  1037. ".i1"
  1038. } else if int {
  1039. ".i32"
  1040. } else {
  1041. ".f32"
  1042. };
  1043. let entry = self.s.entry;
  1044. let args = [
  1045. self.s.m.i32(id as u32),
  1046. self.s.m.i32(0),
  1047. self.s.m.i8(col),
  1048. self.s.m.undef(self.s.t.i32),
  1049. ];
  1050. let v = self.s.op(
  1051. entry,
  1052. &format!("loadInput{suffix}"),
  1053. Attr::ReadNone,
  1054. ty,
  1055. 4,
  1056. &args,
  1057. );
  1058. if bit {
  1059. let z = self.s.m.cast(entry, Cast::ZExt, v, self.s.t.i32);
  1060. Val::I32(z)
  1061. } else if int {
  1062. Val::I32(v)
  1063. } else {
  1064. Val::I32(self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.i32))
  1065. }
  1066. }
  1067. /// The DXIL form of an IR value.
  1068. fn get(&mut self, v: Value) -> Result<Val, Why> {
  1069. if self.phi_at.contains_key(&v) {
  1070. self.read_phis.insert(v);
  1071. }
  1072. let is_mask = self.x.st.masks.contains_key(&v) || self.x.st.highs.contains_key(&v);
  1073. match self.vals.get(&v) {
  1074. Some(&Val::Missing(_)) | None if self.mask_ok && is_mask => {
  1075. return self.mask_dword(v).map(Val::I32);
  1076. }
  1077. Some(&Val::Missing(w)) => return Err(w),
  1078. Some(&val) => return Ok(val),
  1079. None => {}
  1080. }
  1081. if let Some(&(param, dword)) = self.params.get(&v) {
  1082. let val = self.user(param, dword);
  1083. self.vals.insert(v, val);
  1084. return Ok(val);
  1085. }
  1086. Err("a value defined after its use")
  1087. }
  1088. fn i32_of(&mut self, v: Value) -> Result<V, Why> {
  1089. match self.get(v)? {
  1090. Val::I32(x) => Ok(x),
  1091. Val::Bit(x) => Ok(self.s.m.cast(self.cur, Cast::ZExt, x, self.s.t.i32)),
  1092. Val::Missing(w) => Err(w),
  1093. }
  1094. }
  1095. /// A user-data dword: a root parameter's value.
  1096. fn user(&mut self, param: usize, dword: u32) -> Val {
  1097. let rp = self.x.native.layout[param];
  1098. match rp.root {
  1099. RootType::ResourceHeap | RootType::SamplerHeap => return Val::I32(self.s.m.i32(0)),
  1100. RootType::Constants | RootType::Table => {}
  1101. _ => return Val::Missing("a root descriptor"),
  1102. }
  1103. let index = u32::from(rp.user_data) + dword;
  1104. self.user_reads.insert(
  1105. index,
  1106. UserData {
  1107. index,
  1108. slot: rp.slot,
  1109. root: rp.root,
  1110. dword,
  1111. },
  1112. );
  1113. self.s.user_data = self.s.user_data.max(index + 1);
  1114. let h = match self.user_data {
  1115. Some(h) => h,
  1116. None => {
  1117. let h = self.s.user_data_handle();
  1118. self.user_data = Some(h);
  1119. h
  1120. }
  1121. };
  1122. let entry = self.s.entry;
  1123. let row = self.s.m.i32(index / 4);
  1124. let r = self.s.op(
  1125. entry,
  1126. "cbufferLoadLegacy.i32",
  1127. Attr::ReadOnly,
  1128. self.s.t.cbuf_ret,
  1129. 59,
  1130. &[h, row],
  1131. );
  1132. Val::I32(self.s.m.extract(entry, r, index % 4))
  1133. }
  1134. /// A dword of a lane mask as a number: the ballot of the lanes' bits,
  1135. /// taken in the block that writes the mask (see [`MaskData`]).
  1136. fn mask_dword(&mut self, v: Value) -> Result<V, Why> {
  1137. let (lo, high) = match self.x.st.highs.get(&v) {
  1138. Some(&lo) => (lo, true),
  1139. None => (v, false),
  1140. };
  1141. let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?;
  1142. if !self.x.st.active.contains(&lo) {
  1143. return Err("a lane mask holding lanes elsewhere read as data");
  1144. }
  1145. let (x, y) = match self.ballots.get(&lo) {
  1146. Some(&xy) => xy,
  1147. None => {
  1148. let at = match self.def_block.get(&lo) {
  1149. // Program inputs (EXEC on entry).
  1150. None => self.s.entry,
  1151. Some(&b) if b == self.cur_ir => self.cur,
  1152. Some(&b) => self.tail[b].ok_or("a lane mask written after its use")?,
  1153. };
  1154. if !self.balloting.insert(lo) {
  1155. return Err("a lane mask whose lanes depend on its own value");
  1156. }
  1157. let bit = self.boolean(m, at);
  1158. self.balloting.remove(&lo);
  1159. let bit = bit?;
  1160. let i32t = self.s.t.i32;
  1161. let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
  1162. let r = self
  1163. .s
  1164. .op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, &[bit]);
  1165. self.s.flags |= flags::WAVE_OPS;
  1166. let xy = (self.s.m.extract(at, r, 0), self.s.m.extract(at, r, 1));
  1167. self.ballots.insert(lo, xy);
  1168. xy
  1169. }
  1170. };
  1171. Ok(if high { y } else { x })
  1172. }
  1173. // ---- operands ----
  1174. fn operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> {
  1175. match *op {
  1176. Operand::Scalar { code: NULL, .. } => Ok(self.s.m.i32(0)),
  1177. Operand::Scalar { code, .. } => {
  1178. let v = inst.read(Reg::S(code)).ok_or("an unread operand")?;
  1179. self.i32_of(v)
  1180. }
  1181. Operand::Vector { reg, .. } => {
  1182. let v = inst.read(Reg::V(reg)).ok_or("an unread operand")?;
  1183. self.i32_of(v)
  1184. }
  1185. Operand::Const(c) => crate::resource::inline(c)
  1186. .map(|x| self.s.m.i32(x))
  1187. .ok_or("a special operand (vccz, execz, scc, lds_direct)"),
  1188. Operand::Literal(x) => Ok(self.s.m.i32(x)),
  1189. Operand::Attr { .. } => Err("an attribute operand"),
  1190. }
  1191. }
  1192. fn as_float(&mut self, x: V) -> V {
  1193. self.s.m.cast(self.cur, Cast::Bitcast, x, self.s.t.f32)
  1194. }
  1195. fn as_int(&mut self, f: V) -> V {
  1196. self.s.m.cast(self.cur, Cast::Bitcast, f, self.s.t.i32)
  1197. }
  1198. /// The SDWA operand selection of source `k`: a byte or word of the
  1199. /// dword, zero- or sign-extended (none: the whole dword).
  1200. fn sdwa_src(inst: &Inst, k: usize) -> Option<(u8, bool)> {
  1201. let Fields::Valu(v) = &inst.fields else {
  1202. return None;
  1203. };
  1204. let s = v.sdwa?;
  1205. let sel = *s.src_sel.get(k)?;
  1206. let sext = s.sext >> k & 1 != 0;
  1207. (sel < 6).then_some((sel, sext))
  1208. }
  1209. /// Bits `sel` (0-3 a byte, 4-5 a word) of `x`, extended.
  1210. fn select_bits(&mut self, x: V, sel: u8, sext: bool) -> V {
  1211. let c = self.cur;
  1212. let (width, at) = if sel < 4 {
  1213. (8, 8 * sel)
  1214. } else {
  1215. (16, 16 * (sel - 4))
  1216. };
  1217. let left = self.s.m.i32(u32::from(32 - width - at));
  1218. let t = self.s.m.bin(c, Bin::Shl, x, left);
  1219. let right = self.s.m.i32(32 - u32::from(width));
  1220. let op = if sext { Bin::AShr } else { Bin::LShr };
  1221. self.s.m.bin(c, op, t, right)
  1222. }
  1223. /// A float source with its abs/neg modifiers.
  1224. fn fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  1225. let Fields::Valu(v) = &inst.fields else {
  1226. unreachable!()
  1227. };
  1228. let op = *v.src.get(k).ok_or("a missing operand")?;
  1229. let selected = Self::sdwa_src(inst, k);
  1230. let mut f = match op {
  1231. _ if selected.is_some() => {
  1232. let (sel, sext) = selected.expect("checked");
  1233. let x = self.operand(inst, &op)?;
  1234. let x = self.select_bits(x, sel, sext);
  1235. self.as_float(x)
  1236. }
  1237. _ if k == 0 && self.src0.is_some() => {
  1238. let x = self.src0.expect("checked");
  1239. self.as_float(x)
  1240. }
  1241. Operand::Vector { reg, .. } | Operand::Scalar { code: reg, .. }
  1242. if !matches!(op, Operand::Scalar { code: NULL, .. }) =>
  1243. {
  1244. let r = if matches!(op, Operand::Vector { .. }) {
  1245. Reg::V(reg)
  1246. } else {
  1247. Reg::S(reg)
  1248. };
  1249. let val = inst.read(r).ok_or("an unread operand")?;
  1250. match self.floats.get(&val) {
  1251. Some(&f) => f,
  1252. None => {
  1253. let x = self.i32_of(val)?;
  1254. self.as_float(x)
  1255. }
  1256. }
  1257. }
  1258. _ => {
  1259. let x = self.operand(inst, &op)?;
  1260. self.as_float(x)
  1261. }
  1262. };
  1263. if v.abs >> k & 1 != 0 {
  1264. f = self.unary(6, f);
  1265. }
  1266. if v.neg >> k & 1 != 0 {
  1267. let z = self.s.m.f32(0x8000_0000);
  1268. f = self.s.m.bin(self.cur, Bin::Sub, z, f);
  1269. }
  1270. Ok(f)
  1271. }
  1272. fn src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  1273. let Fields::Valu(v) = &inst.fields else {
  1274. unreachable!()
  1275. };
  1276. let op = *v.src.get(k).ok_or("a missing operand")?;
  1277. if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 {
  1278. return Err("integer operand modifiers");
  1279. }
  1280. match self.src0 {
  1281. Some(x) if k == 0 => Ok(x),
  1282. _ => {
  1283. let x = self.operand(inst, &op)?;
  1284. Ok(match Self::sdwa_src(inst, k) {
  1285. Some((sel, sext)) => self.select_bits(x, sel, sext),
  1286. None => x,
  1287. })
  1288. }
  1289. }
  1290. }
  1291. fn unary(&mut self, op: u32, f: V) -> V {
  1292. self.s.op(
  1293. self.cur,
  1294. "unary.f32",
  1295. Attr::ReadNone,
  1296. self.s.t.f32,
  1297. op,
  1298. &[f],
  1299. )
  1300. }
  1301. fn binary(&mut self, op: u32, a: V, b: V) -> V {
  1302. self.s.op(
  1303. self.cur,
  1304. "binary.f32",
  1305. Attr::ReadNone,
  1306. self.s.t.f32,
  1307. op,
  1308. &[a, b],
  1309. )
  1310. }
  1311. fn fmad(&mut self, a: V, b: V, c: V) -> V {
  1312. self.s.op(
  1313. self.cur,
  1314. "tertiary.f32",
  1315. Attr::ReadNone,
  1316. self.s.t.f32,
  1317. 46,
  1318. &[a, b, c],
  1319. )
  1320. }
  1321. /// `f` as an f16 in the low bits, rounded toward zero: the nearest-even
  1322. /// conversion, one step back toward zero where it rounded away (which
  1323. /// also turns an overflow to infinity into the largest finite half).
  1324. fn f16_toward_zero(&mut self, f: V) -> V {
  1325. let c = self.cur;
  1326. let i32t = self.s.t.i32;
  1327. let h = self
  1328. .s
  1329. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
  1330. let back = self
  1331. .s
  1332. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]);
  1333. let (fa, ba) = (self.unary(6, f), self.unary(6, back));
  1334. // Ordered: never for NaN.
  1335. let away = self.s.m.cmp(c, pred::OGT, ba, fa);
  1336. let one = self.s.m.i32(1);
  1337. let stepped = self.s.m.bin(c, Bin::Sub, h, one);
  1338. self.s.m.select(c, away, stepped, h)
  1339. }
  1340. /// `(a >> off[4:0]) & ((1 << width) - 1)`, sign-extended from the field's
  1341. /// top bit when `signed`; widths from 32 on take every bit. A signed
  1342. /// field that runs past bit 31 extends from bit 31, as the hardware
  1343. /// does: the shift is arithmetic then.
  1344. fn bfe(&mut self, a: V, off: V, width: V, signed: bool) -> V {
  1345. let c = self.cur;
  1346. let (k31, k32, zero, one, ones) = (
  1347. self.s.m.i32(31),
  1348. self.s.m.i32(32),
  1349. self.s.m.i32(0),
  1350. self.s.m.i32(1),
  1351. self.s.m.i32(u32::MAX),
  1352. );
  1353. let off = self.s.m.bin(c, Bin::And, off, k31);
  1354. let shift = if signed { Bin::AShr } else { Bin::LShr };
  1355. let shifted = self.s.m.bin(c, shift, a, off);
  1356. let full = self.s.m.cmp(c, pred::IUGE, width, k32);
  1357. let w = self.s.m.bin(c, Bin::And, width, k31);
  1358. let mask = self.s.m.bin(c, Bin::Shl, one, w);
  1359. let mask = self.s.m.bin(c, Bin::Sub, mask, one);
  1360. let mask = self.s.m.select(c, full, ones, mask);
  1361. let r = self.s.m.bin(c, Bin::And, shifted, mask);
  1362. if !signed {
  1363. return r;
  1364. }
  1365. // Sign-extend a field narrower than 32 bits (none for width 0).
  1366. let left = self.s.m.bin(c, Bin::Sub, k32, w);
  1367. let left = self.s.m.bin(c, Bin::And, left, k31);
  1368. let t = self.s.m.bin(c, Bin::Shl, r, left);
  1369. let t = self.s.m.bin(c, Bin::AShr, t, left);
  1370. let is0 = self.s.m.cmp(c, pred::EQ, w, zero);
  1371. let keep = self.s.m.bin(c, Bin::Or, full, is0);
  1372. self.s.m.select(c, keep, r, t)
  1373. }
  1374. /// The median of three. With a NaN among them the hardware gives the
  1375. /// minimum of the three instead (the host's minimum skips NaNs, so that
  1376. /// is the smallest number among them).
  1377. fn med3(&mut self, a: V, b: V, third: V) -> V {
  1378. let c = self.cur;
  1379. let lo = self.binary(36, a, b);
  1380. let hi = self.binary(35, a, b);
  1381. let t = self.binary(36, hi, third);
  1382. let median = self.binary(35, lo, t);
  1383. let least = self.binary(36, lo, third);
  1384. let ab = self.s.m.cmp(c, pred::UNO, a, b);
  1385. let nan3 = self.s.m.cmp(c, pred::UNO, third, third);
  1386. let nan = self.s.m.bin(c, Bin::Or, ab, nan3);
  1387. self.s.m.select(c, nan, least, median)
  1388. }
  1389. /// `a - floor(a)`, which on the hardware never reaches 1.0: where it
  1390. /// would round to it (a tiny negative `a`), the result is `below_one`,
  1391. /// the largest value under 1.0 in the operation's width. Hosts differ
  1392. /// here (some give 1.0). Comparing against a `threshold` distinct from
  1393. /// `below_one` prevents drivers (observed on NVIDIA) from folding
  1394. /// `r > k ? k : r` into `minNum` (`FMNMX`) and swallowing NaN.
  1395. fn fract(&mut self, a: V, threshold: f32, below_one: f32) -> V {
  1396. let c = self.cur;
  1397. let r = self.unary(22, a);
  1398. let limit = self.s.m.f32(threshold.to_bits());
  1399. let k = self.s.m.f32(below_one.to_bits());
  1400. let over = self.s.m.cmp(c, pred::OGE, r, limit);
  1401. self.s.m.select(c, over, k, r)
  1402. }
  1403. /// Sine, or cosine, of an angle in turns, as the hardware takes it. The
  1404. /// whole turns are taken off first (`x - round_even(x)`, exact, within
  1405. /// half a turn), so a large angle keeps its fraction; scaling to radians
  1406. /// first rounds it away. A zero passes unreduced (the sine of -0 is -0).
  1407. /// The sine of a half turn and the cosine of a quarter turn are exactly
  1408. /// +0 on the hardware, where the host's function of the rounded angle
  1409. /// gives about 1e-7. Infinities and NaN give NaN.
  1410. /// shortcut: below 2^-12 turns the hardware scales by a slightly
  1411. /// different constant than 2π (a last-place difference).
  1412. fn trig_turns(&mut self, x: V, cosine: bool) -> V {
  1413. let c = self.cur;
  1414. let zero = self.s.m.f32(0);
  1415. let whole = self.unary(26, x);
  1416. let part = self.s.m.bin(c, Bin::Sub, x, whole);
  1417. let is_zero = self.s.m.cmp(c, pred::OEQ, x, zero);
  1418. let part = self.s.m.select(c, is_zero, x, part);
  1419. let k = self.s.m.f32(TWO_PI.to_bits());
  1420. let angle = self.s.m.bin(c, Bin::Mul, part, k);
  1421. let r = self.unary(if cosine { 12 } else { 13 }, angle);
  1422. let at = if cosine { 0.25f32 } else { 0.5 };
  1423. let at = self.s.m.f32(at.to_bits());
  1424. let size = self.unary(6, part);
  1425. let exact = self.s.m.cmp(c, pred::OEQ, size, at);
  1426. self.s.m.select(c, exact, zero, r)
  1427. }
  1428. /// The high dword of a 32 × 32-bit product.
  1429. fn mul_hi(&mut self, a: V, b: V, signed: bool) -> V {
  1430. let c = self.cur;
  1431. let i64t = self.s.m.int(64);
  1432. let ext = if signed { Cast::SExt } else { Cast::ZExt };
  1433. let a = self.s.m.cast(c, ext, a, i64t);
  1434. let b = self.s.m.cast(c, ext, b, i64t);
  1435. let m = self.s.m.bin(c, Bin::Mul, a, b);
  1436. let k32 = self.s.m.int_const(i64t, 32);
  1437. let hi = self.s.m.bin(c, Bin::LShr, m, k32);
  1438. self.s.flags |= flags::INT64;
  1439. self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32)
  1440. }
  1441. /// `0 × anything = 0`, as in D3D9.
  1442. fn legacy_mul(&mut self, a: V, b: V) -> V {
  1443. let c = self.cur;
  1444. let m = self.s.m.bin(c, Bin::Mul, a, b);
  1445. let zero = self.s.m.f32(0);
  1446. let az = self.s.m.cmp(c, pred::OEQ, a, zero);
  1447. let bz = self.s.m.cmp(c, pred::OEQ, b, zero);
  1448. let z = self.s.m.bin(c, Bin::Or, az, bz);
  1449. self.s.m.select(c, z, zero, m)
  1450. }
  1451. // ---- lane booleans ----
  1452. fn boolean(&mut self, b: Bool, at: usize) -> Result<V, Why> {
  1453. if b == Bool::TRUE || b == Bool::FALSE {
  1454. return Ok(self.s.m.bool(b == Bool::TRUE));
  1455. }
  1456. if let Some(&v) = self.bools.get(&(at, b)) {
  1457. return Ok(v);
  1458. }
  1459. let (atom, lo, hi) = self.x.st.bools.node(b).expect("not a constant");
  1460. let a = self.atom(atom, at)?;
  1461. let m = &mut self.s.m;
  1462. let v = match (lo, hi) {
  1463. (Bool::FALSE, Bool::TRUE) => a,
  1464. (Bool::TRUE, Bool::FALSE) => {
  1465. let t = m.bool(true);
  1466. m.bin(at, Bin::Xor, a, t)
  1467. }
  1468. (Bool::FALSE, h) => {
  1469. let h = self.boolean(h, at)?;
  1470. self.s.m.bin(at, Bin::And, a, h)
  1471. }
  1472. (l, Bool::TRUE) => {
  1473. let l = self.boolean(l, at)?;
  1474. self.s.m.bin(at, Bin::Or, a, l)
  1475. }
  1476. (l, h) => {
  1477. let l = self.boolean(l, at)?;
  1478. let h = self.boolean(h, at)?;
  1479. self.s.m.select(at, a, h, l)
  1480. }
  1481. };
  1482. self.bools.insert((at, b), v);
  1483. Ok(v)
  1484. }
  1485. fn atom(&mut self, atom: Atom, at: usize) -> Result<V, Why> {
  1486. match atom {
  1487. Atom::Lane(v) => self.lane_bits.get(&v).copied().ok_or_else(|| {
  1488. self.lane_fail
  1489. .get(&v)
  1490. .copied()
  1491. .unwrap_or("a lane mask from a carry")
  1492. }),
  1493. Atom::Uniform(v) => match self.get(v)? {
  1494. Val::Bit(x) => Ok(x),
  1495. Val::I32(x) => {
  1496. let z = self.s.m.i32(0);
  1497. Ok(self.s.m.cmp(at, pred::NE, x, z))
  1498. }
  1499. Val::Missing(w) => Err(w),
  1500. },
  1501. Atom::Phi(id) => {
  1502. if let Some(&v) = self.mask_phis.get(&id) {
  1503. return Ok(v);
  1504. }
  1505. let &(b, i) = self
  1506. .phi_at
  1507. .get(&id)
  1508. .ok_or("a lane-mask join without a phi")?;
  1509. let blk = self.block[b].ok_or("an unreachable join")?;
  1510. let v = self.s.m.phi(blk, self.s.t.i1);
  1511. self.mask_phis.insert(id, v);
  1512. self.pending_masks.push((v, b, i));
  1513. Ok(v)
  1514. }
  1515. // shortcut: "some lane of the quad is set" is taken as true: the
  1516. // lanes it adds only feed derivatives, and exports keep their own
  1517. // masks. Wrong if such a section had a side effect.
  1518. Atom::Quad(_) => Ok(self.s.m.bool(true)),
  1519. // With console lanes, a mask held as a number is the console's:
  1520. // the lane tests its own bit.
  1521. Atom::Opaque(v) if self.console_lanes => {
  1522. let hi = match self.pair_high(v) {
  1523. Some(h) => Some(self.get(h)?),
  1524. None => None,
  1525. };
  1526. let lo = self.get(v)?;
  1527. let word = |w: Val| match w {
  1528. Val::I32(x) => Ok(x),
  1529. _ => Err("an opaque lane mask"),
  1530. };
  1531. let lo = word(lo)?;
  1532. let hi = hi.map(word).transpose()?;
  1533. Ok(self.lane_bit(at, lo, hi))
  1534. }
  1535. Atom::Constant(k) if self.console_lanes => {
  1536. let lo = self.s.m.i32(k as u32);
  1537. let hi = self.s.m.i32((k >> 32) as u32);
  1538. Ok(self.lane_bit(at, lo, Some(hi)))
  1539. }
  1540. Atom::Opaque(_) => Err("an opaque lane mask"),
  1541. Atom::Constant(_) => Err("a constant lane mask"),
  1542. }
  1543. }
  1544. /// This lane's bit of the mask `lo`, `hi` (wave64).
  1545. fn lane_bit(&mut self, at: usize, lo: V, hi: Option<V>) -> V {
  1546. let lane = self.s.op(
  1547. at,
  1548. "waveGetLaneIndex",
  1549. Attr::ReadOnly,
  1550. self.s.t.i32,
  1551. 111,
  1552. &[],
  1553. );
  1554. let (k31, k32, one, z) = (
  1555. self.s.m.i32(31),
  1556. self.s.m.i32(32),
  1557. self.s.m.i32(1),
  1558. self.s.m.i32(0),
  1559. );
  1560. let word = match hi {
  1561. Some(hi) => {
  1562. let low = self.s.m.cmp(at, pred::IULT, lane, k32);
  1563. self.s.m.select(at, low, lo, hi)
  1564. }
  1565. None => lo,
  1566. };
  1567. let sh = self.s.m.bin(at, Bin::And, lane, k31);
  1568. let t = self.s.m.bin(at, Bin::LShr, word, sh);
  1569. let t = self.s.m.bin(at, Bin::And, t, one);
  1570. self.s.m.cmp(at, pred::NE, t, z)
  1571. }
  1572. /// The value of the high dword of the wave64 register pair whose low
  1573. /// dword holds `lo` (none in wave32).
  1574. fn pair_high(&self, lo: Value) -> Option<Value> {
  1575. if !self.x.native.wave64 {
  1576. return None;
  1577. }
  1578. let p = self.x.p;
  1579. let pick = |reg: Reg| match reg {
  1580. Reg::S(c) => Some(Reg::S(c + 1)),
  1581. _ => None,
  1582. };
  1583. if let Some(&(reg, _)) = p.inputs.iter().find(|i| i.1 == lo) {
  1584. let h = pick(reg)?;
  1585. return p.inputs.iter().find(|i| i.0 == h).map(|i| i.1);
  1586. }
  1587. if let Some(&(b, i)) = self.phi_at.get(&lo) {
  1588. let h = pick(p.blocks[b].phis[i].reg)?;
  1589. return p.blocks[b]
  1590. .phis
  1591. .iter()
  1592. .find(|q| q.reg == h)
  1593. .map(|q| q.value);
  1594. }
  1595. let b = *self.def_block.get(&lo)?;
  1596. let inst = p.blocks[b]
  1597. .insts
  1598. .iter()
  1599. .find(|i| i.writes.iter().any(|w| w.1 == lo))?;
  1600. let &(reg, _) = inst.writes.iter().find(|w| w.1 == lo)?;
  1601. inst.write(pick(reg)?)
  1602. }
  1603. fn guard(&mut self, b: usize, i: usize) -> Result<Option<V>, Why> {
  1604. match self.x.st.guards[b][i] {
  1605. None => Ok(None),
  1606. Some(g) => Ok(Some(self.boolean(g, self.cur)?)),
  1607. }
  1608. }
  1609. // ---- results ----
  1610. fn set(&mut self, v: Option<Value>, val: Val) {
  1611. if let Some(v) = v {
  1612. self.vals.insert(v, val);
  1613. }
  1614. }
  1615. /// Writes VGPR `reg` (or the SGPR of a lane read), under `guard`.
  1616. fn write(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) {
  1617. let x = match (Self::sdwa_dst(inst), reg) {
  1618. (Some((sel, unused)), Reg::V(_)) => self.place_bits(inst, reg, x, sel, unused),
  1619. _ => x,
  1620. };
  1621. self.write_placed(inst, reg, x, guard);
  1622. }
  1623. /// [`Self::write`] of a dword already placed (SDWA applied).
  1624. fn write_placed(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) {
  1625. let Some(new) = inst.write(reg) else { return };
  1626. let x = match (guard, reg) {
  1627. (Some(g), Reg::V(_)) => {
  1628. let old = match inst.read(reg).map(|o| self.i32_of(o)) {
  1629. Some(Ok(o)) => o,
  1630. // The validator refuses reads of undef.
  1631. _ => self.s.m.i32(0),
  1632. };
  1633. self.s.m.select(self.cur, g, x, old)
  1634. }
  1635. _ => x,
  1636. };
  1637. self.vals.insert(new, Val::I32(x));
  1638. }
  1639. /// The SDWA destination selection: a byte or word, and what the other
  1640. /// bits get (0 zeros, 1 the sign above the field, 2 the old bits).
  1641. fn sdwa_dst(inst: &Inst) -> Option<(u8, u8)> {
  1642. let Fields::Valu(v) = &inst.fields else {
  1643. return None;
  1644. };
  1645. let s = v.sdwa?;
  1646. (s.dst_sel < 6).then_some((s.dst_sel, s.dst_unused))
  1647. }
  1648. /// The low byte or word of `x` placed at `sel` in VGPR `reg`.
  1649. fn place_bits(&mut self, inst: &Inst, reg: Reg, x: V, sel: u8, unused: u8) -> V {
  1650. let c = self.cur;
  1651. let (width, at) = if sel < 4 {
  1652. (8u32, 8 * u32::from(sel))
  1653. } else {
  1654. (16, 16 * u32::from(sel - 4))
  1655. };
  1656. let left = self.s.m.i32(32 - width);
  1657. let t = self.s.m.bin(c, Bin::Shl, x, left);
  1658. let right = self.s.m.i32(32 - width - at);
  1659. if unused == 1 {
  1660. // Bits below the field shift in as zeros.
  1661. return self.s.m.bin(c, Bin::AShr, t, right);
  1662. }
  1663. let field = self.s.m.bin(c, Bin::LShr, t, right);
  1664. if unused != 2 {
  1665. return field;
  1666. }
  1667. let old = match inst.read(reg).map(|o| self.i32_of(o)) {
  1668. Some(Ok(o)) => o,
  1669. _ => self.s.m.i32(0),
  1670. };
  1671. let keep = self.s.m.i32(!((((1u64 << width) - 1) as u32) << at));
  1672. let old = self.s.m.bin(c, Bin::And, old, keep);
  1673. self.s.m.bin(c, Bin::Or, old, field)
  1674. }
  1675. fn write_f(&mut self, inst: &Inst, f: V, guard: Option<V>) -> Result<(), Why> {
  1676. let Fields::Valu(v) = &inst.fields else {
  1677. unreachable!()
  1678. };
  1679. let mut f = f;
  1680. match v.omod {
  1681. 0 => {}
  1682. k => {
  1683. let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)];
  1684. let c = self.s.m.f32(factor.to_bits());
  1685. f = self.s.m.bin(self.cur, Bin::Mul, f, c);
  1686. }
  1687. }
  1688. if v.clamp {
  1689. f = self.unary(7, f);
  1690. }
  1691. let Some(Operand::Vector { reg, .. }) = v.dst else {
  1692. return Err("a float result outside a VGPR");
  1693. };
  1694. let x = self.as_int(f);
  1695. self.write(inst, Reg::V(reg), x, guard);
  1696. if guard.is_none()
  1697. && Self::sdwa_dst(inst).is_none()
  1698. && let Some(new) = inst.write(Reg::V(reg))
  1699. {
  1700. self.floats.insert(new, f);
  1701. }
  1702. Ok(())
  1703. }
  1704. fn write_i(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> {
  1705. let Fields::Valu(v) = &inst.fields else {
  1706. unreachable!()
  1707. };
  1708. if v.clamp || v.omod != 0 {
  1709. return Err("integer output modifiers");
  1710. }
  1711. match v.dst {
  1712. Some(Operand::Vector { reg, .. }) => self.write(inst, Reg::V(reg), x, guard),
  1713. Some(Operand::Scalar { code, .. }) => self.write(inst, Reg::S(code), x, None),
  1714. _ => return Err("a result without a register"),
  1715. }
  1716. Ok(())
  1717. }
  1718. /// Starts code only the lanes where `guard` holds run (a store under a
  1719. /// lane guard): returns where it started and the join block.
  1720. fn begin_guarded(&mut self, guard: Option<V>) -> Option<(usize, usize)> {
  1721. let g = guard?;
  1722. let (then, join) = (self.s.m.new_block(), self.s.m.new_block());
  1723. self.s.m.terminate(self.cur, Term::CondBr(g, then, join));
  1724. let head = self.cur;
  1725. self.cur = then;
  1726. Some((head, join))
  1727. }
  1728. /// Ends guarded code; each (value inside, value outside) becomes a phi.
  1729. fn end_guarded(&mut self, at: Option<(usize, usize)>, values: &[(V, V)]) -> Vec<V> {
  1730. let Some((head, join)) = at else {
  1731. return values.iter().map(|v| v.0).collect();
  1732. };
  1733. let then = self.cur;
  1734. self.s.m.terminate(then, Term::Br(join));
  1735. self.cur = join;
  1736. values
  1737. .iter()
  1738. .map(|&(inside, outside)| {
  1739. let ty = self.s.m.type_of(inside);
  1740. let phi = self.s.m.phi(join, ty);
  1741. self.s.m.set_phi(phi, vec![(inside, then), (outside, head)]);
  1742. phi
  1743. })
  1744. .collect()
  1745. }
  1746. /// Code that depends on the lane layout: wave operations, and in compute
  1747. /// the console's wave size (lanes are thread ids in group order there).
  1748. /// Pixel lanes match only within a quad.
  1749. fn cross_lane(&mut self, quad: bool) -> Result<(), Why> {
  1750. if self.s.mesh.is_some() {
  1751. // shortcut: no wave size for mesh shaders in SM 6.6, so host
  1752. // lanes cannot follow the console's; emulate through group-shared
  1753. // memory if mesh programs turn out to need these.
  1754. return Err("a cross-lane operation in a mesh shader");
  1755. }
  1756. if self.s.threads.is_none() && !(quad && self.s.pixel) {
  1757. return Err("a cross-lane operation outside compute");
  1758. }
  1759. debug_assert!(self.s.threads.is_none() || self.console_lanes);
  1760. self.s.flags |= flags::WAVE_OPS;
  1761. Ok(())
  1762. }
  1763. /// Component `c` of the thread id in the group. With console lanes, the
  1764. /// thread is relabelled so that its host lane is its console lane: the
  1765. /// flat id is the wave's first lane's, rounded down to the wave size,
  1766. /// plus the lane index. (A bijection while each host wave holds a
  1767. /// wave-aligned run of flat ids, as the console's waves do.)
  1768. fn thread_id(&mut self, c: u8) -> Val {
  1769. if !self.console_lanes {
  1770. return self.compute_id("threadIdInGroup.i32", 95, c);
  1771. }
  1772. let [x, y, _] = self.s.threads.expect("compute");
  1773. let e = self.s.entry;
  1774. let i32t = self.s.t.i32;
  1775. let flat = self.s.op(
  1776. e,
  1777. "flattenedThreadIdInGroup.i32",
  1778. Attr::ReadNone,
  1779. i32t,
  1780. 96,
  1781. &[],
  1782. );
  1783. let first = self.s.op(
  1784. e,
  1785. "waveReadLaneFirst.i32",
  1786. Attr::NoUnwind,
  1787. i32t,
  1788. 118,
  1789. &[flat],
  1790. );
  1791. let wave = self.s.wave_size.expect("set with console lanes");
  1792. let mask = self.s.m.i32(!(wave - 1));
  1793. let base = self.s.m.bin(e, Bin::And, first, mask);
  1794. let lane = self.lane_index();
  1795. let f = self.s.m.bin(e, Bin::Add, base, lane);
  1796. self.s.flags |= flags::WAVE_OPS;
  1797. let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y));
  1798. Val::I32(match c {
  1799. 0 => self.s.m.bin(e, Bin::URem, f, xk),
  1800. 1 => {
  1801. let t = self.s.m.bin(e, Bin::UDiv, f, xk);
  1802. self.s.m.bin(e, Bin::URem, t, yk)
  1803. }
  1804. _ => self.s.m.bin(e, Bin::UDiv, f, xy),
  1805. })
  1806. }
  1807. /// Mesh: the counts and the primitives no lane exports. The console's
  1808. /// counts come from one lane's allocation request, which DXIL cannot
  1809. /// express (one call, dominating every output write).
  1810. // shortcut: the counts are the declared maxima and each lane first culls
  1811. // its primitive (all indices 0, zero area), so primitives past the
  1812. // program's count are culled and vertices past it unused; this costs
  1813. // the host the unused vertex and primitive slots. Pass the program's own
  1814. // counts if that shows in frame time.
  1815. fn mesh_prologue(&mut self, mesh: super::shader::Mesh) -> Result<(), Why> {
  1816. let threads = self.s.threads.expect("mesh")[0];
  1817. if mesh.topology != 2 {
  1818. return Err("a mesh shader not drawing triangles");
  1819. }
  1820. if threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256 {
  1821. return Err("a mesh shader beyond the host's limits");
  1822. }
  1823. let e = self.s.entry;
  1824. let void = self.s.t.void;
  1825. let (v, p) = (
  1826. self.s.m.i32(mesh.max_vertices),
  1827. self.s.m.i32(mesh.max_primitives),
  1828. );
  1829. self.s
  1830. .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]);
  1831. let flat = self.mesh_thread();
  1832. let guard = (threads > mesh.max_primitives).then(|| self.s.m.cmp(e, pred::IULT, flat, p));
  1833. let at = self.begin_guarded(guard);
  1834. let z = self.s.m.i32(0);
  1835. self.s.op(
  1836. self.cur,
  1837. "emitIndices",
  1838. Attr::NoUnwind,
  1839. void,
  1840. 169,
  1841. &[flat, z, z, z],
  1842. );
  1843. self.end_guarded(at, &[]);
  1844. Ok(())
  1845. }
  1846. /// Mesh: the thread's index in the group, which is its vertex and
  1847. /// primitive index.
  1848. fn mesh_thread(&mut self) -> V {
  1849. if let Some(f) = self.flat {
  1850. return f;
  1851. }
  1852. let e = self.s.entry;
  1853. let f = self.s.op(
  1854. e,
  1855. "flattenedThreadIdInGroup.i32",
  1856. Attr::ReadNone,
  1857. self.s.t.i32,
  1858. 96,
  1859. &[],
  1860. );
  1861. self.flat = Some(f);
  1862. f
  1863. }
  1864. /// The console wave size.
  1865. fn wave(&self) -> u32 {
  1866. if self.x.native.wave64 { 64 } else { 32 }
  1867. }
  1868. fn lane_index(&mut self) -> V {
  1869. if self.s.mesh.is_some() {
  1870. // The console's lane: mesh code reads no other lanes, so host
  1871. // waves need not match the console's.
  1872. let f = self.mesh_thread();
  1873. let m = self.s.m.i32(self.wave() - 1);
  1874. return self.s.m.bin(self.s.entry, Bin::And, f, m);
  1875. }
  1876. self.s.op(
  1877. self.cur,
  1878. "waveGetLaneIndex",
  1879. Attr::ReadOnly,
  1880. self.s.t.i32,
  1881. 111,
  1882. &[],
  1883. )
  1884. }
  1885. /// `x` of lane `src` (in this lane's quad) through quad reads, whose
  1886. /// lane must be a constant.
  1887. fn quad_pick(&mut self, x: V, src: V) -> V {
  1888. self.s.flags |= flags::WAVE_OPS;
  1889. let c = self.cur;
  1890. let three = self.s.m.i32(3);
  1891. let q = self.s.m.bin(c, Bin::And, src, three);
  1892. let mut r = x;
  1893. for n in 0..4 {
  1894. let kn = self.s.m.i32(n);
  1895. let read = self.s.op(
  1896. c,
  1897. "quadReadLaneAt.i32",
  1898. Attr::NoUnwind,
  1899. self.s.t.i32,
  1900. 122,
  1901. &[x, kn],
  1902. );
  1903. let is = self.s.m.cmp(c, pred::EQ, q, kn);
  1904. r = self.s.m.select(c, is, read, r);
  1905. }
  1906. r
  1907. }
  1908. fn read_lane(&mut self, x: V, lane: V) -> V {
  1909. self.s.op(
  1910. self.cur,
  1911. "waveReadLaneAt.i32",
  1912. Attr::NoUnwind,
  1913. self.s.t.i32,
  1914. 117,
  1915. &[x, lane],
  1916. )
  1917. }
  1918. /// The float value of a register value.
  1919. fn float_of(&mut self, v: Value) -> Result<V, Why> {
  1920. if let Some(&f) = self.floats.get(&v) {
  1921. return Ok(f);
  1922. }
  1923. let x = self.i32_of(v)?;
  1924. Ok(self.as_float(x))
  1925. }
  1926. /// The values of VGPRs `reg..reg + n` as `inst` reads them.
  1927. fn vgprs(&mut self, inst: &Inst, op: &Operand, n: u8) -> Result<Vec<V>, Why> {
  1928. let Operand::Vector { reg, .. } = *op else {
  1929. return Err("a vector operand");
  1930. };
  1931. (0..n)
  1932. .map(|k| {
  1933. let v = inst.read(Reg::V(reg + k)).ok_or("an unread operand")?;
  1934. self.i32_of(v)
  1935. })
  1936. .collect()
  1937. }
  1938. /// LDS (thread-group shared memory) and `ds_swizzle`.
  1939. fn ds(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  1940. let Fields::Ds {
  1941. dst,
  1942. addr,
  1943. data,
  1944. offset0,
  1945. offset1,
  1946. gds,
  1947. } = &inst.fields
  1948. else {
  1949. unreachable!()
  1950. };
  1951. if *gds {
  1952. return Err("GDS");
  1953. }
  1954. let name = inst.name();
  1955. let guard = self.guard(b, i)?;
  1956. let c = self.cur;
  1957. let offset = u32::from(*offset0) | u32::from(*offset1) << 8;
  1958. let dst_reg = match dst {
  1959. Some(Operand::Vector { reg, .. }) => Some(*reg),
  1960. _ => None,
  1961. };
  1962. if name == "ds_swizzle_b32" {
  1963. // Bit 15 set: each lane of a quad picks a lane of it; else lanes
  1964. // of each group of 32 combine their index with and/or/xor masks.
  1965. let quad = offset & 0x8000 != 0
  1966. || offset & 0x1C == 0x1C && offset & 0x380 == 0 && offset >> 10 & 0x1F < 4;
  1967. // Mesh: host quads are threads 4n..4n+3 of a 1D group, as the
  1968. // console's, so quad-local swizzles read through quad operations.
  1969. let mesh_quad = self.s.mesh.is_some() && quad;
  1970. if !mesh_quad {
  1971. self.cross_lane(quad)?;
  1972. }
  1973. // The source sits in the address field.
  1974. let x = self.vgprs(inst, addr.as_ref().ok_or("a swizzle source")?, 1)?[0];
  1975. let lane = self.lane_index();
  1976. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  1977. let src = if offset & 0x8000 != 0 {
  1978. let (three, one) = (k(self, 3), k(self, 1));
  1979. let sel = self.s.m.bin(c, Bin::And, lane, three);
  1980. let sh = self.s.m.bin(c, Bin::Shl, sel, one);
  1981. let pattern = k(self, offset & 0xFF);
  1982. let pick = self.s.m.bin(c, Bin::LShr, pattern, sh);
  1983. let pick = self.s.m.bin(c, Bin::And, pick, three);
  1984. let not3 = k(self, !3);
  1985. let base = self.s.m.bin(c, Bin::And, lane, not3);
  1986. self.s.m.bin(c, Bin::Or, base, pick)
  1987. } else {
  1988. let and = k(self, offset & 0x1F | !0x1F);
  1989. let or = k(self, offset >> 5 & 0x1F);
  1990. let xor = k(self, offset >> 10 & 0x1F);
  1991. let t = self.s.m.bin(c, Bin::And, lane, and);
  1992. let t = self.s.m.bin(c, Bin::Or, t, or);
  1993. self.s.m.bin(c, Bin::Xor, t, xor)
  1994. };
  1995. let r = if mesh_quad {
  1996. self.quad_pick(x, src)
  1997. } else {
  1998. self.read_lane(x, src)
  1999. };
  2000. let reg = dst_reg.ok_or("a swizzle result")?;
  2001. self.write(inst, Reg::V(reg), r, guard);
  2002. return Ok(());
  2003. }
  2004. if self.s.lds_dwords == 0 {
  2005. return Err("LDS the program does not allocate");
  2006. }
  2007. let a = self.vgprs(inst, addr.as_ref().ok_or("an LDS address")?, 1)?[0];
  2008. // shortcut: LDS addresses are taken as dword-aligned and in bounds
  2009. // (out-of-bounds console accesses read 0 and drop writes).
  2010. let dword = |l: &mut Self, bytes: u32| -> V {
  2011. let c = l.cur;
  2012. let o = l.s.m.i32(bytes);
  2013. let at = l.s.m.bin(c, Bin::Add, a, o);
  2014. let two = l.s.m.i32(2);
  2015. let index = l.s.m.bin(c, Bin::LShr, at, two);
  2016. let lds = l.s.lds();
  2017. l.s.m.element(c, lds, index)
  2018. };
  2019. let width = |n: &str| match n.rsplit('_').next() {
  2020. Some("b64") => 2,
  2021. Some("b96") => 3,
  2022. Some("b128") => 4,
  2023. _ => 1,
  2024. };
  2025. // (byte offset, dwords) per element; read2/write2 scale their two
  2026. // offsets by the element size (×64 for st64).
  2027. let pair = |n: &str| -> Vec<(u32, u32)> {
  2028. let w = width(n);
  2029. let scale = 4 * w * if n.contains("st64") { 64 } else { 1 };
  2030. vec![
  2031. (u32::from(*offset0) * scale, w),
  2032. (u32::from(*offset1) * scale, w),
  2033. ]
  2034. };
  2035. if let Some(rest) = name.strip_prefix("ds_read") {
  2036. let elements = if rest.starts_with('2') {
  2037. pair(name)
  2038. } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") {
  2039. vec![(offset, width(name))]
  2040. } else {
  2041. return Err("an LDS read of bytes or halves");
  2042. };
  2043. let reg = dst_reg.ok_or("an LDS read result")?;
  2044. let mut n = 0;
  2045. for (off, w) in elements {
  2046. for k in 0..w {
  2047. let p = dword(self, off + 4 * k);
  2048. let x = self.s.m.load(self.cur, p);
  2049. self.write(inst, Reg::V(reg + n), x, guard);
  2050. n += 1;
  2051. }
  2052. }
  2053. return Ok(());
  2054. }
  2055. if let Some(rest) = name.strip_prefix("ds_write") {
  2056. let elements = if rest.starts_with('2') {
  2057. pair(name)
  2058. } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") {
  2059. vec![(offset, width(name))]
  2060. } else {
  2061. return Err("an LDS write of bytes or halves");
  2062. };
  2063. let mut stores = Vec::new();
  2064. for (e, (off, w)) in elements.into_iter().enumerate() {
  2065. let vals = self.vgprs(inst, data.get(e).ok_or("an LDS write")?, w as u8)?;
  2066. for (k, x) in vals.into_iter().enumerate() {
  2067. stores.push((off + 4 * k as u32, x));
  2068. }
  2069. }
  2070. let at = self.begin_guarded(guard);
  2071. for (off, x) in stores {
  2072. let p = dword(self, off);
  2073. self.s.m.store(self.cur, p, x);
  2074. }
  2075. self.end_guarded(at, &[]);
  2076. return Ok(());
  2077. }
  2078. // Atomics: the old value returns with `_rtn`.
  2079. let op = name
  2080. .strip_prefix("ds_")
  2081. .map(|n| n.replace("_rtn", ""))
  2082. .ok_or("an LDS operation")?;
  2083. use super::bitcode::Rmw;
  2084. let rmw = match op.as_str() {
  2085. "add_u32" => Some(Rmw::Add),
  2086. "sub_u32" => Some(Rmw::Sub),
  2087. "and_b32" => Some(Rmw::And),
  2088. "or_b32" => Some(Rmw::Or),
  2089. "xor_b32" => Some(Rmw::Xor),
  2090. "min_i32" => Some(Rmw::Min),
  2091. "max_i32" => Some(Rmw::Max),
  2092. "min_u32" => Some(Rmw::UMin),
  2093. "max_u32" => Some(Rmw::UMax),
  2094. "wrxchg_b32" => Some(Rmw::Xchg),
  2095. "cmpst_b32" => None,
  2096. _ => return Err("an LDS operation"),
  2097. };
  2098. let v0 = self.vgprs(inst, data.first().ok_or("an LDS atomic")?, 1)?[0];
  2099. let v1 = match data.get(1) {
  2100. Some(d) => Some(self.vgprs(inst, d, 1)?[0]),
  2101. None => None,
  2102. };
  2103. let old_reg = dst_reg.and_then(|r| inst.read(Reg::V(r)).map(|v| (r, v)));
  2104. let outside = match old_reg {
  2105. Some((_, v)) => self.i32_of(v).unwrap_or(self.s.m.i32(0)),
  2106. None => self.s.m.i32(0),
  2107. };
  2108. let p = dword(self, offset);
  2109. let at = self.begin_guarded(guard);
  2110. let r = match rmw {
  2111. Some(op) => self.s.m.atomic(self.cur, op, p, v0),
  2112. // Compare with data0, store data1.
  2113. None => self
  2114. .s
  2115. .m
  2116. .cmpxchg(self.cur, p, v0, v1.ok_or("an LDS compare")?),
  2117. };
  2118. let r = self.end_guarded(at, &[(r, outside)])[0];
  2119. if let Some(reg) = dst_reg {
  2120. self.write(inst, Reg::V(reg), r, None);
  2121. }
  2122. Ok(())
  2123. }
  2124. // ---- instructions ----
  2125. fn inst(&mut self, b: usize, i: usize) -> Result<(), Stop> {
  2126. let inst: &'a Inst = &self.x.p.blocks[b].insts[i];
  2127. let offset = inst.machine.offset;
  2128. let name = inst.name();
  2129. self.mask_ok = match self.mask_data {
  2130. MaskData::Console => true,
  2131. MaskData::Host => {
  2132. name.starts_with("s_bcnt1_i32_")
  2133. || name.starts_with("s_ff1_i32_")
  2134. || name.starts_with("v_mbcnt_")
  2135. || matches!(
  2136. name,
  2137. "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_u64" | "s_cmp_lg_u64"
  2138. )
  2139. }
  2140. MaskData::None => false,
  2141. };
  2142. let effect = matches!(inst.fields, Fields::Exp { .. })
  2143. || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
  2144. || name.contains("store")
  2145. || name.contains("atomic")
  2146. || name == "s_barrier"
  2147. || matches!(inst.fields, Fields::Ds { .. })
  2148. && !(name.starts_with("ds_read")
  2149. || name.starts_with("ds_swizzle")
  2150. || name.contains("permute"));
  2151. let r = match &inst.fields {
  2152. Fields::Sop { .. } => self.sop(inst),
  2153. Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()),
  2154. Fields::Sopp { .. } if name == "s_barrier" => {
  2155. // Thread-group sync with a shared-memory fence, and a UAV
  2156. // fence when the program writes UAVs (the waits before an
  2157. // s_barrier make those writes visible on the console).
  2158. let mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 };
  2159. let mode = self.s.m.i32(mode);
  2160. let void = self.s.t.void;
  2161. self.s
  2162. .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
  2163. Ok(())
  2164. }
  2165. Fields::Sopp { .. } => Ok(()),
  2166. Fields::Smem { .. } => self.smem(inst, (b, i)),
  2167. Fields::Valu(_) if name.starts_with("v_interp_") => self.interp(inst, (b, i)),
  2168. Fields::Valu(_) => self.valu(inst, b, i),
  2169. Fields::Vintrp { .. } => self.interp(inst, (b, i)),
  2170. Fields::Image { .. } => self.image(inst, b, i),
  2171. Fields::Buffer { .. } => self.buffer(inst, b, i),
  2172. Fields::Exp { .. } => self.export(b, i),
  2173. Fields::Ds { .. } => self.ds(inst, b, i),
  2174. Fields::Flat { .. } if name.starts_with("global_") => self.flat(inst, b, i),
  2175. Fields::Flat { .. } => Err("flat memory"),
  2176. };
  2177. match r {
  2178. Ok(()) => Ok(()),
  2179. Err(why) if effect => Err(unsupported(offset, why)),
  2180. Err(why) => {
  2181. for &(_, v) in &inst.writes {
  2182. self.vals.insert(v, Val::Missing(why));
  2183. }
  2184. Ok(())
  2185. }
  2186. }
  2187. }
  2188. fn is_mask(&self, v: Option<Value>) -> bool {
  2189. v.is_some_and(|v| self.x.st.masks.contains_key(&v))
  2190. }
  2191. fn sop(&mut self, inst: &Inst) -> Result<(), Why> {
  2192. let Fields::Sop { dst, src, imm } = &inst.fields else {
  2193. unreachable!()
  2194. };
  2195. let name = inst.name();
  2196. let scc = inst.write(Reg::Scc);
  2197. let dst_code = match dst {
  2198. Some(Operand::Scalar { code, .. }) => Some(*code),
  2199. _ => None,
  2200. };
  2201. let lo = dst_code.and_then(|c| inst.write(Reg::S(c)));
  2202. if inst.write(Reg::S(EXEC)).is_some() || self.is_mask(lo) {
  2203. return Err(LANE_MASK);
  2204. }
  2205. if matches!(
  2206. name,
  2207. "s_setreg_imm32_b32" | "s_setreg_b32" | "s_swappc_b64" | "s_version"
  2208. ) || name.starts_with("s_waitcnt")
  2209. {
  2210. // shortcut: the float MODE register is not modelled; s_swappc_b64 is the
  2211. // vertex fetch call, whose results arrive as inputs.
  2212. return Err("a register the emitter does not model");
  2213. }
  2214. let c = self.cur;
  2215. let src32 = |l: &mut Self, k: usize| -> Result<V, Why> {
  2216. // SOPK arithmetic reads its destination as the first source.
  2217. if k == 0 && matches!(name, "s_addk_i32" | "s_mulk_i32") {
  2218. let d = dst.as_ref().ok_or("a missing operand")?;
  2219. return l.operand(inst, d);
  2220. }
  2221. let op = src.get(k).ok_or("a missing operand")?;
  2222. l.operand(inst, op)
  2223. };
  2224. let sext16 = |l: &mut Self| l.s.m.i32(i32::from(imm.unwrap_or(0) as i16) as u32);
  2225. // Dword `h` of 64-bit source `k` (inline constants sign-extend).
  2226. let half = |l: &mut Self, k: usize, h: u8| -> Result<V, Why> {
  2227. match src.get(k) {
  2228. Some(&Operand::Scalar { code, .. }) if code != NULL => {
  2229. let v = inst.read(Reg::S(code + h)).ok_or("an unread operand")?;
  2230. l.i32_of(v)
  2231. }
  2232. Some(op) if h == 0 => l.operand(inst, op),
  2233. Some(Operand::Const(k)) => {
  2234. let x = crate::resource::inline(*k).ok_or("a special operand")?;
  2235. Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 }))
  2236. }
  2237. _ => Ok(l.s.m.i32(0)),
  2238. }
  2239. };
  2240. if let Some(op) = name.strip_prefix("s_bitcmp") {
  2241. // SCC is whether bit src1 (mod 32, or mod 64 for the 64-bit form)
  2242. // of src0 is clear (bitcmp0) or set (bitcmp1).
  2243. let (bit, k31) = (src32(self, 1)?, self.s.m.i32(31));
  2244. let idx = self.s.m.bin(c, Bin::And, bit, k31);
  2245. let word = if op.ends_with("_b64") {
  2246. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  2247. let k32 = self.s.m.i32(32);
  2248. let upper = self.s.m.bin(c, Bin::And, bit, k32);
  2249. let z = self.s.m.i32(0);
  2250. let upper = self.s.m.cmp(c, pred::NE, upper, z);
  2251. self.s.m.select(c, upper, b, a)
  2252. } else {
  2253. src32(self, 0)?
  2254. };
  2255. let shifted = self.s.m.bin(c, Bin::LShr, word, idx);
  2256. let one = self.s.m.i32(1);
  2257. let tested = self.s.m.bin(c, Bin::And, shifted, one);
  2258. let want = self.s.m.i32(u32::from(op.starts_with('1')));
  2259. let r = self.s.m.cmp(c, pred::EQ, tested, want);
  2260. self.set(scc, Val::Bit(r));
  2261. return Ok(());
  2262. }
  2263. if let Some(op) = name.strip_prefix("s_cmp_").filter(|o| o.ends_with("_u64")) {
  2264. // eq and lg only: both dwords.
  2265. let mut r = None;
  2266. for h in 0..2 {
  2267. let (a, b) = (half(self, 0, h)?, half(self, 1, h)?);
  2268. let e = self.s.m.cmp(c, pred::EQ, a, b);
  2269. r = Some(match r {
  2270. Some(x) => self.s.m.bin(c, Bin::And, x, e),
  2271. None => e,
  2272. });
  2273. }
  2274. let mut r = r.expect("two dwords");
  2275. if op.starts_with("lg") {
  2276. let t = self.s.m.bool(true);
  2277. r = self.s.m.bin(c, Bin::Xor, r, t);
  2278. }
  2279. self.set(scc, Val::Bit(r));
  2280. return Ok(());
  2281. }
  2282. if let Some(op) = name.strip_prefix("s_cmp_").or(name.strip_prefix("s_cmpk_")) {
  2283. let (a, b) = if name.starts_with("s_cmpk_") {
  2284. let b = if op.ends_with("_i32") {
  2285. sext16(self)
  2286. } else {
  2287. self.s.m.i32(u32::from(imm.unwrap_or(0)))
  2288. };
  2289. (src32(self, 0)?, b)
  2290. } else {
  2291. if op.ends_with("64") {
  2292. return Err("a 64-bit scalar compare");
  2293. }
  2294. (src32(self, 0)?, src32(self, 1)?)
  2295. };
  2296. let signed = op.ends_with("_i32");
  2297. let p = match &op[..2] {
  2298. "eq" => pred::EQ,
  2299. "lg" => pred::NE,
  2300. "gt" if signed => pred::SGT,
  2301. "ge" if signed => pred::SGE,
  2302. "lt" if signed => pred::SLT,
  2303. "le" if signed => pred::SLE,
  2304. "gt" => pred::IUGT,
  2305. "ge" => pred::IUGE,
  2306. "lt" => pred::IULT,
  2307. "le" => pred::IULE,
  2308. _ => return Err("a scalar compare"),
  2309. };
  2310. let r = self.s.m.cmp(c, p, a, b);
  2311. self.set(scc, Val::Bit(r));
  2312. return Ok(());
  2313. }
  2314. let wide = name.ends_with("_b64") || name.ends_with("_u64") || name.ends_with("_i64");
  2315. if wide {
  2316. let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1)));
  2317. let nonzero = |l: &mut Self, a: V, b: V| {
  2318. let o = l.s.m.bin(c, Bin::Or, a, b);
  2319. let z = l.s.m.i32(0);
  2320. l.s.m.cmp(c, pred::NE, o, z)
  2321. };
  2322. return match name {
  2323. "s_bcnt1_i32_b64" => {
  2324. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  2325. let i32t = self.s.t.i32;
  2326. let na = self
  2327. .s
  2328. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[a]);
  2329. let nb = self
  2330. .s
  2331. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[b]);
  2332. let r = self.s.m.bin(c, Bin::Add, na, nb);
  2333. self.set(lo, Val::I32(r));
  2334. let z = self.s.m.i32(0);
  2335. let s = self.s.m.cmp(c, pred::NE, r, z);
  2336. self.set(scc, Val::Bit(s));
  2337. Ok(())
  2338. }
  2339. "s_ff1_i32_b64" => {
  2340. // The lowest set bit; -1 for none (as DXIL's first bit low).
  2341. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  2342. let i32t = self.s.t.i32;
  2343. let fa = self
  2344. .s
  2345. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[a]);
  2346. let fb = self
  2347. .s
  2348. .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[b]);
  2349. let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32));
  2350. let fb32 = self.s.m.bin(c, Bin::Add, fb, k32);
  2351. let none = self.s.m.cmp(c, pred::EQ, b, z);
  2352. let fb = self.s.m.select(c, none, fb, fb32);
  2353. let low = self.s.m.cmp(c, pred::NE, a, z);
  2354. let r = self.s.m.select(c, low, fa, fb);
  2355. self.set(lo, Val::I32(r));
  2356. Ok(())
  2357. }
  2358. "s_and_b64" | "s_or_b64" | "s_xor_b64" | "s_andn2_b64" | "s_orn2_b64"
  2359. | "s_nand_b64" | "s_nor_b64" | "s_xnor_b64" | "s_not_b64" => {
  2360. let ones = self.s.m.i32(u32::MAX);
  2361. let mut r = Vec::new();
  2362. for h in 0..2u8 {
  2363. let a = half(self, 0, h)?;
  2364. let x = if name == "s_not_b64" {
  2365. self.s.m.bin(c, Bin::Xor, a, ones)
  2366. } else {
  2367. let mut b = half(self, 1, h)?;
  2368. if name.contains("n2") {
  2369. b = self.s.m.bin(c, Bin::Xor, b, ones);
  2370. }
  2371. let op = match &name[2..5] {
  2372. "and" | "nan" => Bin::And,
  2373. "or_" | "orn" | "nor" => Bin::Or,
  2374. _ => Bin::Xor,
  2375. };
  2376. let x = self.s.m.bin(c, op, a, b);
  2377. if matches!(name, "s_nand_b64" | "s_nor_b64" | "s_xnor_b64") {
  2378. self.s.m.bin(c, Bin::Xor, x, ones)
  2379. } else {
  2380. x
  2381. }
  2382. };
  2383. r.push(x);
  2384. }
  2385. self.set(lo, Val::I32(r[0]));
  2386. self.set(hi, Val::I32(r[1]));
  2387. let s = nonzero(self, r[0], r[1]);
  2388. self.set(scc, Val::Bit(s));
  2389. Ok(())
  2390. }
  2391. "s_lshl_b64" | "s_lshr_b64" | "s_ashr_i64" => {
  2392. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  2393. let n = src32(self, 1)?;
  2394. let i64t = self.s.m.int(64);
  2395. self.s.flags |= flags::INT64;
  2396. let a = self.s.m.cast(c, Cast::ZExt, a, i64t);
  2397. let b = self.s.m.cast(c, Cast::ZExt, b, i64t);
  2398. let k32 = self.s.m.int_const(i64t, 32);
  2399. let b = self.s.m.bin(c, Bin::Shl, b, k32);
  2400. let x = self.s.m.bin(c, Bin::Or, a, b);
  2401. let k63 = self.s.m.i32(63);
  2402. let n = self.s.m.bin(c, Bin::And, n, k63);
  2403. let n = self.s.m.cast(c, Cast::ZExt, n, i64t);
  2404. let op = match name {
  2405. "s_lshl_b64" => Bin::Shl,
  2406. "s_lshr_b64" => Bin::LShr,
  2407. _ => Bin::AShr,
  2408. };
  2409. let r = self.s.m.bin(c, op, x, n);
  2410. let rl = self.s.m.cast(c, Cast::Trunc, r, self.s.t.i32);
  2411. let rh = self.s.m.bin(c, Bin::LShr, r, k32);
  2412. let rh = self.s.m.cast(c, Cast::Trunc, rh, self.s.t.i32);
  2413. self.set(lo, Val::I32(rl));
  2414. self.set(hi, Val::I32(rh));
  2415. let s = nonzero(self, rl, rh);
  2416. self.set(scc, Val::Bit(s));
  2417. Ok(())
  2418. }
  2419. "s_mov_b64" => {
  2420. let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
  2421. self.set(lo, Val::I32(a));
  2422. self.set(hi, Val::I32(b));
  2423. Ok(())
  2424. }
  2425. "s_cselect_b64" => {
  2426. let cond = self.scc_in(inst)?;
  2427. for (h, v) in [(0, lo), (1, hi)] {
  2428. let (a, b) = (half(self, 0, h)?, half(self, 1, h)?);
  2429. let r = self.s.m.select(c, cond, a, b);
  2430. self.set(v, Val::I32(r));
  2431. }
  2432. Ok(())
  2433. }
  2434. _ => Err(name),
  2435. };
  2436. }
  2437. let m = &mut self.s.m;
  2438. let _ = m;
  2439. let (r, carry): (V, Option<V>) = match name {
  2440. "s_mov_b32" => (src32(self, 0)?, None),
  2441. "s_movk_i32" => (sext16(self), None),
  2442. "s_cselect_b32" => {
  2443. let cond = self.scc_in(inst)?;
  2444. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  2445. (self.s.m.select(c, cond, a, b), None)
  2446. }
  2447. "s_brev_b32" => {
  2448. let a = src32(self, 0)?;
  2449. let r = self
  2450. .s
  2451. .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a]);
  2452. (r, None)
  2453. }
  2454. "s_not_b32" => {
  2455. let a = src32(self, 0)?;
  2456. let ones = self.s.m.i32(u32::MAX);
  2457. (self.s.m.bin(c, Bin::Xor, a, ones), None)
  2458. }
  2459. "s_add_u32" | "s_add_i32" | "s_addk_i32" => {
  2460. let a = src32(self, 0)?;
  2461. let b = if name == "s_addk_i32" {
  2462. sext16(self)
  2463. } else {
  2464. src32(self, 1)?
  2465. };
  2466. let r = self.s.m.bin(c, Bin::Add, a, b);
  2467. let carry = if name == "s_add_u32" {
  2468. Some(self.s.m.cmp(c, pred::IULT, r, a))
  2469. } else {
  2470. None
  2471. };
  2472. (r, carry)
  2473. }
  2474. "s_sub_u32" | "s_sub_i32" => {
  2475. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  2476. let r = self.s.m.bin(c, Bin::Sub, a, b);
  2477. let carry = (name == "s_sub_u32").then(|| self.s.m.cmp(c, pred::IULT, a, b));
  2478. (r, carry)
  2479. }
  2480. "s_addc_u32" | "s_subb_u32" => {
  2481. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  2482. let cin = self.scc_in(inst)?;
  2483. let (r, carry) = self.add_sub_carry(c, name == "s_addc_u32", a, b, Some(cin));
  2484. (r, Some(carry))
  2485. }
  2486. "s_mul_i32" | "s_mulk_i32" => {
  2487. let a = src32(self, 0)?;
  2488. let b = if name == "s_mulk_i32" {
  2489. sext16(self)
  2490. } else {
  2491. src32(self, 1)?
  2492. };
  2493. (self.s.m.bin(c, Bin::Mul, a, b), None)
  2494. }
  2495. "s_mul_hi_u32" | "s_mul_hi_i32" => {
  2496. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  2497. (self.mul_hi(a, b, name.ends_with("i32")), None)
  2498. }
  2499. "s_flbit_i32_b32" | "s_flbit_i32" => {
  2500. // The first bit from the top (differing from the sign for
  2501. // the signed form), -1 for none: DXIL's first-bit-high.
  2502. let a = src32(self, 0)?;
  2503. let op = if name == "s_flbit_i32_b32" { 33 } else { 34 };
  2504. let r = self
  2505. .s
  2506. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  2507. (r, None)
  2508. }
  2509. "s_ff1_i32_b32" | "s_bcnt1_i32_b32" => {
  2510. // First set bit (-1 for zero, as DXIL's), or the bit count.
  2511. let a = src32(self, 0)?;
  2512. let op = if name == "s_ff1_i32_b32" { 32 } else { 31 };
  2513. let r = self
  2514. .s
  2515. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  2516. (r, None)
  2517. }
  2518. "s_bfe_u32" | "s_bfe_i32" => {
  2519. // src1: offset in bits 0-4, width in bits 16-22.
  2520. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  2521. let (k16, k127) = (self.s.m.i32(16), self.s.m.i32(0x7F));
  2522. let w = self.s.m.bin(c, Bin::LShr, b, k16);
  2523. let w = self.s.m.bin(c, Bin::And, w, k127);
  2524. (self.bfe(a, b, w, name == "s_bfe_i32"), None)
  2525. }
  2526. "s_and_b32" | "s_or_b32" | "s_xor_b32" | "s_andn2_b32" | "s_orn2_b32"
  2527. | "s_nand_b32" | "s_nor_b32" | "s_xnor_b32" => {
  2528. let (a, mut b) = (src32(self, 0)?, src32(self, 1)?);
  2529. let ones = self.s.m.i32(u32::MAX);
  2530. if name.contains("n2") {
  2531. b = self.s.m.bin(c, Bin::Xor, b, ones);
  2532. }
  2533. let op = match &name[2..5] {
  2534. "and" | "nan" => Bin::And,
  2535. "or_" | "orn" | "nor" => Bin::Or,
  2536. _ => Bin::Xor,
  2537. };
  2538. let mut r = self.s.m.bin(c, op, a, b);
  2539. if matches!(name, "s_nand_b32" | "s_nor_b32" | "s_xnor_b32") {
  2540. r = self.s.m.bin(c, Bin::Xor, r, ones);
  2541. }
  2542. (r, None)
  2543. }
  2544. "s_lshl_b32" | "s_lshr_b32" | "s_ashr_i32" => {
  2545. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  2546. let k31 = self.s.m.i32(31);
  2547. let b = self.s.m.bin(c, Bin::And, b, k31);
  2548. let op = match name {
  2549. "s_lshl_b32" => Bin::Shl,
  2550. "s_lshr_b32" => Bin::LShr,
  2551. _ => Bin::AShr,
  2552. };
  2553. (self.s.m.bin(c, op, a, b), None)
  2554. }
  2555. "s_lshl1_add_u32" | "s_lshl2_add_u32" | "s_lshl3_add_u32" | "s_lshl4_add_u32" => {
  2556. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  2557. let k = self.s.m.i32(u32::from(name.as_bytes()[6] - b'0'));
  2558. let t = self.s.m.bin(c, Bin::Shl, a, k);
  2559. (self.s.m.bin(c, Bin::Add, t, b), None)
  2560. }
  2561. "s_min_u32" | "s_max_u32" | "s_min_i32" | "s_max_i32" => {
  2562. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  2563. let p = match name {
  2564. "s_min_u32" => pred::IULT,
  2565. "s_max_u32" => pred::IUGT,
  2566. "s_min_i32" => pred::SLT,
  2567. _ => pred::SGT,
  2568. };
  2569. let t = self.s.m.cmp(c, p, a, b);
  2570. (self.s.m.select(c, t, a, b), None)
  2571. }
  2572. "s_abs_i32" => {
  2573. let a = src32(self, 0)?;
  2574. let z = self.s.m.i32(0);
  2575. let neg = self.s.m.cmp(c, pred::SLT, a, z);
  2576. let n = self.s.m.bin(c, Bin::Sub, z, a);
  2577. (self.s.m.select(c, neg, n, a), None)
  2578. }
  2579. "s_bitset0_b32" | "s_bitset1_b32" => {
  2580. // Sets (clears) bit src[4:0] of the destination it reads.
  2581. let old = self.operand(inst, dst.as_ref().ok_or("a missing operand")?)?;
  2582. let a = src32(self, 0)?;
  2583. let (k31, one) = (self.s.m.i32(31), self.s.m.i32(1));
  2584. let a = self.s.m.bin(c, Bin::And, a, k31);
  2585. let bit = self.s.m.bin(c, Bin::Shl, one, a);
  2586. if name == "s_bitset1_b32" {
  2587. (self.s.m.bin(c, Bin::Or, old, bit), None)
  2588. } else {
  2589. let ones = self.s.m.i32(u32::MAX);
  2590. let nb = self.s.m.bin(c, Bin::Xor, bit, ones);
  2591. (self.s.m.bin(c, Bin::And, old, nb), None)
  2592. }
  2593. }
  2594. "s_bfm_b32" => {
  2595. let (a, b) = (src32(self, 0)?, src32(self, 1)?);
  2596. let k31 = self.s.m.i32(31);
  2597. let one = self.s.m.i32(1);
  2598. let a = self.s.m.bin(c, Bin::And, a, k31);
  2599. let b = self.s.m.bin(c, Bin::And, b, k31);
  2600. let m = self.s.m.bin(c, Bin::Shl, one, a);
  2601. let m = self.s.m.bin(c, Bin::Sub, m, one);
  2602. (self.s.m.bin(c, Bin::Shl, m, b), None)
  2603. }
  2604. _ => return Err(name),
  2605. };
  2606. self.set(lo, Val::I32(r));
  2607. if let Some(scc) = scc {
  2608. let val = match carry {
  2609. Some(k) => Val::Bit(k),
  2610. None if matches!(
  2611. name,
  2612. "s_mov_b32"
  2613. | "s_movk_i32"
  2614. | "s_cselect_b32"
  2615. | "s_brev_b32"
  2616. | "s_mul_i32"
  2617. | "s_mulk_i32"
  2618. ) =>
  2619. {
  2620. return Ok(());
  2621. }
  2622. None if name.starts_with("s_add") || name.starts_with("s_sub") => {
  2623. Val::Missing("the carry of a scalar operation")
  2624. }
  2625. None => {
  2626. let z = self.s.m.i32(0);
  2627. Val::Bit(self.s.m.cmp(c, pred::NE, r, z))
  2628. }
  2629. };
  2630. self.vals.insert(scc, val);
  2631. }
  2632. Ok(())
  2633. }
  2634. /// `a + b (+ cin)` or `a - b (- cin)` with the carry (borrow) out, as the
  2635. /// scalar and vector add-with-carry instructions set it.
  2636. fn add_sub_carry(&mut self, c: usize, add: bool, a: V, b: V, cin: Option<V>) -> (V, V) {
  2637. let op = if add { Bin::Add } else { Bin::Sub };
  2638. let mut r = self.s.m.bin(c, op, a, b);
  2639. // Without a carry in: a + b wraps below a; a - b borrows when a < b.
  2640. let mut carry = if add {
  2641. self.s.m.cmp(c, pred::IULT, r, a)
  2642. } else {
  2643. self.s.m.cmp(c, pred::IULT, a, b)
  2644. };
  2645. if let Some(cin) = cin {
  2646. let one = self.s.m.cast(c, Cast::ZExt, cin, self.s.t.i32);
  2647. let t = r;
  2648. r = self.s.m.bin(c, op, t, one);
  2649. // The carry in carries on when the partial result is all ones
  2650. // (add) or zero (sub).
  2651. let edge = self.s.m.i32(if add { u32::MAX } else { 0 });
  2652. let at_edge = self.s.m.cmp(c, pred::EQ, t, edge);
  2653. let more = self.s.m.bin(c, Bin::And, cin, at_edge);
  2654. carry = self.s.m.bin(c, Bin::Or, carry, more);
  2655. }
  2656. (r, carry)
  2657. }
  2658. fn scc_in(&mut self, inst: &Inst) -> Result<V, Why> {
  2659. let v = inst.read(Reg::Scc).ok_or("an unread SCC")?;
  2660. match self.get(v)? {
  2661. Val::Bit(x) => Ok(x),
  2662. _ => Err("SCC without a value"),
  2663. }
  2664. }
  2665. fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  2666. let Fields::Smem {
  2667. data,
  2668. offset,
  2669. soffset,
  2670. ..
  2671. } = &inst.fields
  2672. else {
  2673. unreachable!()
  2674. };
  2675. let name = inst.name();
  2676. if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) {
  2677. return self.code_smem(inst, a);
  2678. }
  2679. let Some(rest) = name.strip_prefix("s_buffer_load_dword") else {
  2680. return self.descriptor_data(inst, site);
  2681. };
  2682. let count = match rest {
  2683. "" => 1,
  2684. "x2" => 2,
  2685. "x4" => 4,
  2686. "x8" => 8,
  2687. "x16" => 16,
  2688. _ => return Err("a scalar buffer load"),
  2689. };
  2690. let Some(Operand::Scalar { code, .. }) = *data else {
  2691. return Err("a scalar buffer load");
  2692. };
  2693. let src = self
  2694. .descriptors
  2695. .get(&(site, false))
  2696. .copied()
  2697. .ok_or("an untracked descriptor")?;
  2698. let kind = self.used_kind(src);
  2699. let c = self.cur;
  2700. let (base, extra) = self.built_offset(src)?;
  2701. let offset = &((*offset as u32).wrapping_add(base) as i32);
  2702. let mut addr = self.s.m.i32(*offset as u32);
  2703. if let Some(x) = extra {
  2704. addr = self.s.m.bin(c, Bin::Add, addr, x);
  2705. }
  2706. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  2707. let so = self.operand(inst, soffset)?;
  2708. addr = self.s.m.bin(c, Bin::Add, addr, so);
  2709. }
  2710. if matches!(src, Source::Built { address, .. } if address.param == CODE) {
  2711. // A descriptor built around a table in the code.
  2712. for k in 0..count {
  2713. let off = self.s.m.i32(4 * k);
  2714. let a = self.s.m.bin(c, Bin::Add, addr, off);
  2715. let x = self.code_dword(a)?;
  2716. self.write(inst, Reg::S(code + k as u8), x, None);
  2717. }
  2718. return Ok(());
  2719. }
  2720. if matches!(kind, Some(u) if u.kind == ResourceType::Srv) {
  2721. let h = self.handle(site, src, false, (11, 0))?;
  2722. for k in 0..count {
  2723. let off = self.s.m.i32(4 * k);
  2724. let a = self.s.m.bin(c, Bin::Add, addr, off);
  2725. let mask = self.s.m.i8(1);
  2726. let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  2727. let r = self.s.op(
  2728. c,
  2729. "rawBufferLoad.f32",
  2730. Attr::ReadOnly,
  2731. self.s.t.res_ret,
  2732. 139,
  2733. &[h, a, u, mask, al],
  2734. );
  2735. let x = self.s.m.extract(c, r, 0);
  2736. let x = self.as_int(x);
  2737. self.write(inst, Reg::S(code + k as u8), x, None);
  2738. }
  2739. return Ok(());
  2740. }
  2741. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  2742. let constant = match addr {
  2743. V::Const(_)
  2744. if matches!(soffset, Operand::Scalar { code: NULL, .. }) && extra.is_none() =>
  2745. {
  2746. Some(*offset as u32)
  2747. }
  2748. _ => None,
  2749. };
  2750. let mut rows: HashMap<u32, V> = HashMap::new();
  2751. for k in 0..count {
  2752. let x = match constant {
  2753. Some(base) => {
  2754. let byte = base + 4 * k;
  2755. let row = match rows.get(&(byte >> 4)) {
  2756. Some(&r) => r,
  2757. None => {
  2758. let ri = self.s.m.i32(byte >> 4);
  2759. let r = self.s.op(
  2760. c,
  2761. "cbufferLoadLegacy.i32",
  2762. Attr::ReadOnly,
  2763. self.s.t.cbuf_ret,
  2764. 59,
  2765. &[h, ri],
  2766. );
  2767. rows.insert(byte >> 4, r);
  2768. r
  2769. }
  2770. };
  2771. self.s.m.extract(c, row, (byte >> 2) & 3)
  2772. }
  2773. None => {
  2774. let off = self.s.m.i32(4 * k);
  2775. let a = self.s.m.bin(c, Bin::Add, addr, off);
  2776. self.cbuffer_dword(h, a)
  2777. }
  2778. };
  2779. self.write(inst, Reg::S(code + k as u8), x, None);
  2780. }
  2781. Ok(())
  2782. }
  2783. /// A descriptor load (`s_load_dword*` from a table or heap) whose dwords
  2784. /// the code also reads as numbers: the console compiler computes sizes
  2785. /// from descriptor bits (an image's width, height, depth, levels; a
  2786. /// buffer's record count) instead of querying them. Those fields are
  2787. /// rebuilt from the host view's dimensions in the GFX10 layout (image
  2788. /// dword 1 bits 30-31 and dword 2 bits 0-13 width - 1, dword 2 bits
  2789. /// 14-29 height - 1, dword 3 identity swizzle, last level at 16, type at
  2790. /// 28, dword 4 depth or layers - 1; buffer dword 2 the record count).
  2791. // shortcut: the base level reads 0 (the host view starts at its own
  2792. // level 0, so sizes the code shifts by it come out right) and the other
  2793. // dwords (addresses, formats, tiling) have no host value: reading them
  2794. // stops the program.
  2795. fn descriptor_data(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  2796. const OTHER: Why = "a descriptor's address or format read as data";
  2797. let Fields::Smem {
  2798. data: Some(Operand::Scalar { code, .. }),
  2799. ..
  2800. } = inst.fields
  2801. else {
  2802. return Err("a scalar memory read as data");
  2803. };
  2804. let count = match inst.name().strip_prefix("s_load_dword") {
  2805. Some("") => 1u32,
  2806. Some("x2") => 2,
  2807. Some("x4") => 4,
  2808. Some("x8") => 8,
  2809. Some("x16") => 16,
  2810. _ => return Err("a scalar memory read as data"),
  2811. };
  2812. // How the program uses the descriptor tells the view's kind.
  2813. let use_at = self
  2814. .x
  2815. .res
  2816. .descriptors
  2817. .iter()
  2818. .filter(|d| d.role == Role::Resource)
  2819. .find_map(|d| {
  2820. d.source.leaves().into_iter().find_map(|l| match *l {
  2821. Source::Loaded { load, first } if load == site => Some((d.site, first)),
  2822. _ => None,
  2823. })
  2824. });
  2825. let Some((at, first)) = use_at else {
  2826. return Err("a descriptor read only as data");
  2827. };
  2828. let src = Source::Loaded { load: site, first };
  2829. let used = self.used_kind(&src);
  2830. let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1];
  2831. let un = ui.name();
  2832. let uav = un.contains("store")
  2833. || un.contains("atomic")
  2834. || used.is_some_and(|u| u.kind == ResourceType::Uav);
  2835. let u = if uav { 0x1000 } else { 0 };
  2836. let (props, image) = match &ui.fields {
  2837. Fields::Image { dim, .. } => {
  2838. let kind = match dim {
  2839. 0 => 1,
  2840. 1 => 2,
  2841. 2 => 4,
  2842. 4 => 6,
  2843. 5 => 7,
  2844. _ => return Err("an image dimension (cube or MSAA)"),
  2845. };
  2846. ((kind | u, 0x409), Some(kind))
  2847. }
  2848. Fields::Buffer { idxen, format, .. } => {
  2849. let stride = used.map_or(0, |u| u.stride);
  2850. let props = if un.starts_with("buffer_load_format")
  2851. || un.starts_with("buffer_store_format")
  2852. {
  2853. (10 | u, 0x409)
  2854. } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) {
  2855. (12 | u, stride)
  2856. } else {
  2857. (11 | u, 0)
  2858. };
  2859. if used.is_some_and(|u| u.kind == ResourceType::Cbv) {
  2860. return Err("a constant buffer's descriptor read as data");
  2861. }
  2862. (props, None)
  2863. }
  2864. _ => return Err("a scalar memory read as data"),
  2865. };
  2866. let h = self.handle(site, &src, false, props)?;
  2867. let c = self.cur;
  2868. let i32t = self.s.t.i32;
  2869. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  2870. let mip = if image.is_some() && !uav {
  2871. self.s.m.i32(0)
  2872. } else {
  2873. self.s.m.undef(i32t)
  2874. };
  2875. let d = self
  2876. .s
  2877. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  2878. let field = |l: &mut Self, k: u32| l.s.m.extract(c, d, k);
  2879. let words: Vec<(u32, V)> = match image {
  2880. Some(kind) => {
  2881. let one = self.s.m.i32(1);
  2882. let w = field(self, 0);
  2883. let (height, depth) = match kind {
  2884. 1 => (one, one),
  2885. 2 => (field(self, 1), one),
  2886. 6 => (one, field(self, 1)),
  2887. _ => (field(self, 1), field(self, 2)),
  2888. };
  2889. let levels = if uav { one } else { field(self, 3) };
  2890. let less = |l: &mut Self, x: V| l.s.m.bin(c, Bin::Sub, x, one);
  2891. let (w, height, depth, levels) = (
  2892. less(self, w),
  2893. less(self, height),
  2894. less(self, depth),
  2895. less(self, levels),
  2896. );
  2897. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  2898. let (k30, k2, k14, k16, mask) = (
  2899. k(self, 30),
  2900. k(self, 2),
  2901. k(self, 14),
  2902. k(self, 16),
  2903. k(self, 0x3FFF),
  2904. );
  2905. let d1 = self.s.m.bin(c, Bin::Shl, w, k30);
  2906. let hi = self.s.m.bin(c, Bin::LShr, w, k2);
  2907. let hi = self.s.m.bin(c, Bin::And, hi, mask);
  2908. let ht = self.s.m.bin(c, Bin::Shl, height, k14);
  2909. let d2 = self.s.m.bin(c, Bin::Or, hi, ht);
  2910. let ty = [0, 8, 9, 0, 10, 0, 12, 13][kind as usize];
  2911. let base = k(self, 0xFAC | ty << 28);
  2912. let last = self.s.m.bin(c, Bin::Shl, levels, k16);
  2913. let d3 = self.s.m.bin(c, Bin::Or, base, last);
  2914. vec![(1, d1), (2, d2), (3, d3), (4, depth)]
  2915. }
  2916. None => vec![(2, field(self, 0))],
  2917. };
  2918. for k in 0..count {
  2919. let rel = k.wrapping_sub(u32::from(first));
  2920. match words.iter().find(|w| w.0 == rel) {
  2921. Some(&(_, x)) => self.write(inst, Reg::S(code + k as u8), x, None),
  2922. None => {
  2923. if let Some(v) = inst.write(Reg::S(code + k as u8)) {
  2924. self.vals.insert(v, Val::Missing(OTHER));
  2925. }
  2926. }
  2927. }
  2928. }
  2929. Ok(())
  2930. }
  2931. /// `s_load_dword*` from the program's constant table.
  2932. fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> {
  2933. let Fields::Smem {
  2934. data: Some(Operand::Scalar { code, .. }),
  2935. ..
  2936. } = inst.fields
  2937. else {
  2938. return Err("a scalar load");
  2939. };
  2940. let count = match inst.name().strip_prefix("s_load_dword") {
  2941. Some("") => 1u32,
  2942. Some("x2") => 2,
  2943. Some("x4") => 4,
  2944. Some("x8") => 8,
  2945. Some("x16") => 16,
  2946. _ => return Err("a scalar load from the code"),
  2947. };
  2948. let c = self.cur;
  2949. let mut addr = self.s.m.i32(a.offset);
  2950. if let Some(d) = a.dynamic {
  2951. let d = self.i32_of(d)?;
  2952. addr = self.s.m.bin(c, Bin::Add, addr, d);
  2953. }
  2954. for k in 0..count {
  2955. let off = self.s.m.i32(4 * k);
  2956. let at = self.s.m.bin(c, Bin::Add, addr, off);
  2957. let x = self.code_dword(at)?;
  2958. self.write(inst, Reg::S(code + k as u8), x, None);
  2959. }
  2960. Ok(())
  2961. }
  2962. /// The dword at a computed byte address of a constant buffer.
  2963. fn cbuffer_dword(&mut self, h: V, a: V) -> V {
  2964. let c = self.cur;
  2965. let four = self.s.m.i32(4);
  2966. let ri = self.s.m.bin(c, Bin::LShr, a, four);
  2967. let r = self.s.op(
  2968. c,
  2969. "cbufferLoadLegacy.i32",
  2970. Attr::ReadOnly,
  2971. self.s.t.cbuf_ret,
  2972. 59,
  2973. &[h, ri],
  2974. );
  2975. let two = self.s.m.i32(2);
  2976. let three = self.s.m.i32(3);
  2977. let comp = self.s.m.bin(c, Bin::LShr, a, two);
  2978. let comp = self.s.m.bin(c, Bin::And, comp, three);
  2979. let mut x = self.s.m.extract(c, r, 0);
  2980. for j in 1..4 {
  2981. let e = self.s.m.extract(c, r, j);
  2982. let jc = self.s.m.i32(j);
  2983. let is = self.s.m.cmp(c, pred::EQ, comp, jc);
  2984. x = self.s.m.select(c, is, e, x);
  2985. }
  2986. x
  2987. }
  2988. /// `channels` channels of the element at byte `off` of raw buffer `h`,
  2989. /// converted from the GFX10 buffer format `format` as the hardware's
  2990. /// typed loads do (channels past the format's read 0, 0, 0, 1).
  2991. // shortcut: the descriptor's channel swizzle is taken as the identity
  2992. // (it is for raw views and the descriptors code builds), elements of 4
  2993. // bytes or more as dword-aligned. Norm formats divide, which the AMD
  2994. // driver does 1 ULP off the hardware's correctly rounded conversion for
  2995. // some values; correct it with an integer check if a title compares
  2996. // converted values exactly.
  2997. fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result<Vec<V>, Why> {
  2998. let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?;
  2999. let c = self.cur;
  3000. let total: u32 = bits.iter().sum();
  3001. let (u, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  3002. let load = |l: &mut Self, at: V, n: u32| -> Vec<V> {
  3003. let mask = l.s.m.i8((1u8 << n) - 1);
  3004. let r = l.s.op(
  3005. c,
  3006. "rawBufferLoad.f32",
  3007. Attr::ReadOnly,
  3008. l.s.t.res_ret,
  3009. 139,
  3010. &[h, at, u, mask, align],
  3011. );
  3012. (0..n)
  3013. .map(|k| {
  3014. let x = l.s.m.extract(c, r, k);
  3015. l.as_int(x)
  3016. })
  3017. .collect()
  3018. };
  3019. let words = if total < 32 {
  3020. // A byte or half inside the dword that holds it.
  3021. let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3));
  3022. let at = self.s.m.bin(c, Bin::And, off, not3);
  3023. let w = load(self, at, 1)[0];
  3024. let byte = self.s.m.bin(c, Bin::And, off, three);
  3025. let sh = self.s.m.bin(c, Bin::Shl, byte, three);
  3026. vec![self.s.m.bin(c, Bin::LShr, w, sh)]
  3027. } else {
  3028. load(self, off, total / 32)
  3029. };
  3030. let float = |l: &mut Self, f: V| l.as_int(f);
  3031. let mut out = Vec::new();
  3032. let mut at = 0;
  3033. for &w in bits {
  3034. let word = words[(at / 32) as usize];
  3035. let field = if w == 32 {
  3036. word
  3037. } else {
  3038. let sh = self.s.m.i32(at % 32);
  3039. let t = self.s.m.bin(c, Bin::LShr, word, sh);
  3040. let m = self.s.m.i32((1 << w) - 1);
  3041. self.s.m.bin(c, Bin::And, t, m)
  3042. };
  3043. at += w;
  3044. // Sign-extended from the field's top bit.
  3045. let signed = |l: &mut Self| {
  3046. if w == 32 {
  3047. return field;
  3048. }
  3049. let k = l.s.m.i32(32 - w);
  3050. let t = l.s.m.bin(c, Bin::Shl, field, k);
  3051. l.s.m.bin(c, Bin::AShr, t, k)
  3052. };
  3053. let f32t = self.s.t.f32;
  3054. let x = match numeric {
  3055. Numeric::Unorm => {
  3056. let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
  3057. let max = self.s.m.f32((((1u64 << w) - 1) as f32).to_bits());
  3058. let q = self.s.m.bin(c, Bin::SDiv, f, max);
  3059. float(self, q)
  3060. }
  3061. Numeric::Snorm => {
  3062. let s = signed(self);
  3063. let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
  3064. let max = self.s.m.f32((((1u64 << (w - 1)) - 1) as f32).to_bits());
  3065. let q = self.s.m.bin(c, Bin::SDiv, f, max);
  3066. let lo = self.s.m.f32((-1.0f32).to_bits());
  3067. let q = self.binary(35, q, lo);
  3068. float(self, q)
  3069. }
  3070. Numeric::Uscaled => {
  3071. let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
  3072. float(self, f)
  3073. }
  3074. Numeric::Sscaled => {
  3075. let s = signed(self);
  3076. let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
  3077. float(self, f)
  3078. }
  3079. Numeric::Uint => field,
  3080. Numeric::Sint => signed(self),
  3081. Numeric::Float if w == 32 => field,
  3082. Numeric::Float => {
  3083. let h = match half_shift(w) {
  3084. 0 => field,
  3085. k => {
  3086. let sh = self.s.m.i32(k);
  3087. self.s.m.bin(c, Bin::Shl, field, sh)
  3088. }
  3089. };
  3090. let f = self
  3091. .s
  3092. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  3093. float(self, f)
  3094. }
  3095. };
  3096. out.push(x);
  3097. }
  3098. let one = match numeric {
  3099. Numeric::Uint | Numeric::Sint => 1,
  3100. _ => 1.0f32.to_bits(),
  3101. };
  3102. for k in out.len() as u32..channels {
  3103. out.push(self.s.m.i32(if k == 3 { one } else { 0 }));
  3104. }
  3105. out.truncate(channels as usize);
  3106. Ok(out)
  3107. }
  3108. /// The byte offset a buffer descriptor built around a root descriptor adds
  3109. /// (constant and computed parts); none for other descriptors.
  3110. fn built_offset(&mut self, src: &Source) -> Result<(u32, Option<V>), Why> {
  3111. match src {
  3112. Source::Built { address, .. } => {
  3113. let x = match address.dynamic {
  3114. Some(v) => Some(self.i32_of(v)?),
  3115. None => None,
  3116. };
  3117. Ok((address.offset, x))
  3118. }
  3119. _ => Ok((0, None)),
  3120. }
  3121. }
  3122. /// The used-resource entry a descriptor loaded from a table falls in.
  3123. fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> {
  3124. if let Source::Phi { args, .. } = src {
  3125. return self.used_kind(args.first()?);
  3126. }
  3127. if let Source::Built { address, .. } = src {
  3128. let rp = self.x.native.layout.get(address.param)?;
  3129. return self
  3130. .x
  3131. .native
  3132. .used
  3133. .iter()
  3134. .find(|u| u.root == RootType::Descriptor && u.user_data == rp.user_data);
  3135. }
  3136. let Source::Loaded { load, first } = src else {
  3137. return None;
  3138. };
  3139. let a = self.scalar.get(load)?;
  3140. let rp = self.x.native.layout.get(a.param)?;
  3141. if rp.root != RootType::Table {
  3142. return None;
  3143. }
  3144. let dword = (a.offset / 4) + u32::from(*first);
  3145. self.x
  3146. .native
  3147. .used
  3148. .iter()
  3149. .filter(|u| {
  3150. u.root == RootType::Table
  3151. && u.user_data == rp.user_data
  3152. && u.table_offset_dwords <= dword
  3153. })
  3154. .max_by_key(|u| u.table_offset_dwords)
  3155. }
  3156. /// A handle for the descriptor `src` read at `site`.
  3157. fn handle(
  3158. &mut self,
  3159. site: Site,
  3160. src: &Source,
  3161. sampler: bool,
  3162. props: (u32, u32),
  3163. ) -> Result<V, Why> {
  3164. match src {
  3165. Source::Loaded { load, first } => {
  3166. let key = (self.cur, *load, *first, sampler, props.0);
  3167. if let Some(&h) = self.handles.get(&key) {
  3168. return Ok(h);
  3169. }
  3170. let index = self.heap_index(*load, *first, sampler)?;
  3171. let h = self.s.heap_handle(self.cur, index, sampler, props);
  3172. self.handles.insert(key, h);
  3173. Ok(h)
  3174. }
  3175. Source::Constant(words) if sampler => {
  3176. let words: [u32; 4] = words
  3177. .get(..4)
  3178. .and_then(|w| w.try_into().ok())
  3179. .ok_or("a sampler constant")?;
  3180. let n = match self.samplers.iter().position(|w| *w == words) {
  3181. Some(n) => n,
  3182. None => {
  3183. self.samplers.push(words);
  3184. self.samplers.len() - 1
  3185. }
  3186. };
  3187. if props.0 & 0x8000 != 0 {
  3188. // shortcut: one sampler used with and without comparison
  3189. // would need two static samplers; it becomes a comparison one.
  3190. self.s.cmp_samplers |= 1 << n;
  3191. }
  3192. Ok(self.s.sampler_handle(self.cur, n as u32))
  3193. }
  3194. Source::Constant(_) => Err("a constant resource descriptor"),
  3195. Source::Built { address, .. } => {
  3196. let rp = *self
  3197. .x
  3198. .native
  3199. .layout
  3200. .get(address.param)
  3201. .ok_or("a descriptor built around a table in the code")?;
  3202. let kind = self
  3203. .x
  3204. .native
  3205. .used
  3206. .iter()
  3207. .find(|u| u.user_data == rp.user_data)
  3208. .map(|u| u.kind);
  3209. match (rp.root, kind, props.0) {
  3210. (RootType::Descriptor, Some(ResourceType::Cbv) | None, 13) => {
  3211. Ok(self.s.root_cbv_handle(rp.slot))
  3212. }
  3213. (RootType::Descriptor, Some(ResourceType::Srv), 11) => {
  3214. Ok(self.s.root_srv_handle(rp.slot))
  3215. }
  3216. _ => Err("a root UAV or typed root view"),
  3217. }
  3218. }
  3219. Source::Phi { block, args } => {
  3220. // Each predecessor computes its heap index at its end; the
  3221. // join picks one with a phi.
  3222. let _ = site;
  3223. let mut incoming = Vec::new();
  3224. for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) {
  3225. if self.block[q].is_none() {
  3226. continue;
  3227. }
  3228. let (Some(tail), Source::Loaded { load, first }) = (self.tail[q], arg) else {
  3229. return Err("a descriptor chosen by control flow");
  3230. };
  3231. let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail);
  3232. let here = std::mem::replace(&mut self.cur, at);
  3233. let index = self.heap_index(*load, *first, sampler);
  3234. self.cur = here;
  3235. incoming.push((index?, at));
  3236. }
  3237. let join = self.block[*block].ok_or("a descriptor chosen by control flow")?;
  3238. let phi = self.s.m.phi(join, self.s.t.i32);
  3239. self.s.m.set_phi(phi, incoming);
  3240. Ok(self.s.heap_handle(self.cur, phi, sampler, props))
  3241. }
  3242. }
  3243. }
  3244. /// The heap index of the descriptor at dword `first` of what the scalar
  3245. /// load at `load` reads, computed in the current block.
  3246. fn heap_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> {
  3247. let a = *self
  3248. .scalar
  3249. .get(&load)
  3250. .ok_or("an untracked descriptor load")?;
  3251. match self.x.native.layout.get(a.param).map(|p| p.root) {
  3252. Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {}
  3253. _ => return Err("a descriptor outside the heaps"),
  3254. }
  3255. let li: &Inst = &self.x.p.blocks[load.0].insts[load.1];
  3256. let Fields::Smem {
  3257. base,
  3258. offset,
  3259. soffset,
  3260. ..
  3261. } = &li.fields
  3262. else {
  3263. return Err("a descriptor load");
  3264. };
  3265. let Operand::Scalar { code, .. } = *base else {
  3266. return Err("a descriptor load");
  3267. };
  3268. let c = self.cur;
  3269. let base = li.read(Reg::S(code)).ok_or("a descriptor load")?;
  3270. let mut addr = self.i32_of(base)?;
  3271. let k = self
  3272. .s
  3273. .m
  3274. .i32((*offset as u32).wrapping_add(4 * u32::from(first)));
  3275. addr = self.s.m.bin(c, Bin::Add, addr, k);
  3276. if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
  3277. let so = self.operand(li, soffset)?;
  3278. addr = self.s.m.bin(c, Bin::Add, addr, so);
  3279. }
  3280. let shift = self.s.m.i32(if sampler { 4 } else { 5 });
  3281. Ok(self.s.m.bin(c, Bin::LShr, addr, shift))
  3282. }
  3283. fn valu(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  3284. let Fields::Valu(v) = &inst.fields else {
  3285. unreachable!()
  3286. };
  3287. let name = inst.name();
  3288. if let Some(rest) = name.strip_prefix("v_cmp_").or(name.strip_prefix("v_cmpx_")) {
  3289. let r = if v.dpp.is_some() {
  3290. Err("a compare with DPP")
  3291. } else {
  3292. self.compare(inst, rest)
  3293. };
  3294. if let Err(why) = r {
  3295. for &(_, w) in &inst.writes {
  3296. self.lane_fail.insert(w, why);
  3297. }
  3298. }
  3299. return r;
  3300. }
  3301. let mut guard = self.guard(b, i)?;
  3302. if let Some(d) = v.dpp {
  3303. let (x, enable) = self.dpp(inst, d)?;
  3304. guard = match (guard, enable) {
  3305. (Some(g), Some(e)) => Some(self.s.m.bin(self.cur, Bin::And, g, e)),
  3306. (g, e) => g.or(e),
  3307. };
  3308. self.src0 = Some(x);
  3309. }
  3310. let r = self.valu_op(inst, guard);
  3311. self.src0 = None;
  3312. r
  3313. }
  3314. /// DPP: src0 as read from another lane, and which lanes write their
  3315. /// result (none: all).
  3316. fn dpp(&mut self, inst: &Inst, dpp: Dpp) -> Result<(V, Option<V>), Why> {
  3317. let Fields::Valu(v) = &inst.fields else {
  3318. unreachable!()
  3319. };
  3320. let Some(&Operand::Vector { reg, .. }) = v.src.first() else {
  3321. return Err("a DPP operand");
  3322. };
  3323. let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("a DPP operand")?)?;
  3324. // Quad permutations and DPP8 stay in groups the pixel layout shares.
  3325. let quad = matches!(dpp, Dpp::Row { ctrl: 0..=0xFF, .. });
  3326. let mesh_quad = self.s.mesh.is_some() && quad;
  3327. if !mesh_quad {
  3328. self.cross_lane(quad)?;
  3329. }
  3330. let c = self.cur;
  3331. let lane = self.lane_index();
  3332. let k = |l: &mut Self, n: u32| l.s.m.i32(n);
  3333. let (sixteen_mask, low) = (k(self, !15), k(self, 15));
  3334. let row = self.s.m.bin(c, Bin::And, lane, sixteen_mask);
  3335. let pos = self.s.m.bin(c, Bin::And, lane, low);
  3336. // Source lane, and whether it lies in the row.
  3337. let (src, inside, masks, zero) = match dpp {
  3338. Dpp::Lanes { sel, .. } => {
  3339. let (seven, not7, three) = (k(self, 7), k(self, !7), k(self, 3));
  3340. let p = self.s.m.bin(c, Bin::And, lane, seven);
  3341. let sh = self.s.m.bin(c, Bin::Mul, p, three);
  3342. let sel = k(self, sel);
  3343. let pick = self.s.m.bin(c, Bin::LShr, sel, sh);
  3344. let pick = self.s.m.bin(c, Bin::And, pick, seven);
  3345. let base = self.s.m.bin(c, Bin::And, lane, not7);
  3346. (self.s.m.bin(c, Bin::Or, base, pick), None, None, false)
  3347. }
  3348. Dpp::Row {
  3349. ctrl,
  3350. row_mask,
  3351. bank_mask,
  3352. bound_ctrl,
  3353. ..
  3354. } => {
  3355. let n = u32::from(ctrl & 15);
  3356. let (src, inside) = match ctrl {
  3357. 0..=0xFF => {
  3358. let (three, one, not3) = (k(self, 3), k(self, 1), k(self, !3));
  3359. let p = self.s.m.bin(c, Bin::And, lane, three);
  3360. let sh = self.s.m.bin(c, Bin::Shl, p, one);
  3361. let perm = k(self, u32::from(ctrl));
  3362. let pick = self.s.m.bin(c, Bin::LShr, perm, sh);
  3363. let pick = self.s.m.bin(c, Bin::And, pick, three);
  3364. let base = self.s.m.bin(c, Bin::And, lane, not3);
  3365. (self.s.m.bin(c, Bin::Or, base, pick), None)
  3366. }
  3367. 0x101..=0x10F | 0x111..=0x11F => {
  3368. let nn = k(self, n);
  3369. let left = ctrl < 0x110;
  3370. let (op, p) = if left {
  3371. (Bin::Add, pred::IULT)
  3372. } else {
  3373. (Bin::Sub, pred::IUGE)
  3374. };
  3375. let s = self.s.m.bin(c, op, lane, nn);
  3376. // Left: pos + n < 16; right: pos >= n.
  3377. let bound = if left { k(self, 16 - n) } else { nn };
  3378. (s, Some(self.s.m.cmp(c, p, pos, bound)))
  3379. }
  3380. 0x121..=0x12F => {
  3381. let nn = k(self, n);
  3382. let t = self.s.m.bin(c, Bin::Sub, pos, nn);
  3383. let t = self.s.m.bin(c, Bin::And, t, low);
  3384. (self.s.m.bin(c, Bin::Or, row, t), None)
  3385. }
  3386. 0x140 | 0x141 => {
  3387. let m = k(self, if ctrl == 0x140 { 15 } else { 7 });
  3388. let t = self.s.m.bin(c, Bin::Xor, lane, m);
  3389. (t, None)
  3390. }
  3391. 0x150..=0x15F => {
  3392. let nn = k(self, n);
  3393. (self.s.m.bin(c, Bin::Or, row, nn), None)
  3394. }
  3395. 0x160..=0x16F => {
  3396. let nn = k(self, n);
  3397. (self.s.m.bin(c, Bin::Xor, lane, nn), None)
  3398. }
  3399. _ => return Err("a DPP lane pattern"),
  3400. };
  3401. let masks = (row_mask != 0xF || bank_mask != 0xF).then_some((row_mask, bank_mask));
  3402. (src, inside, masks, bound_ctrl)
  3403. }
  3404. };
  3405. let mut r = if mesh_quad {
  3406. self.quad_pick(x, src)
  3407. } else {
  3408. self.read_lane(x, src)
  3409. };
  3410. let mut enable = None;
  3411. if let Some(inside) = inside {
  3412. if zero {
  3413. let z = k(self, 0);
  3414. r = self.s.m.select(c, inside, r, z);
  3415. } else {
  3416. enable = Some(inside);
  3417. }
  3418. }
  3419. if let Some((rows, banks)) = masks {
  3420. // Row (16 lanes) and bank (4 lanes of a row) write masks.
  3421. let (four, two, three) = (k(self, 4), k(self, 2), k(self, 3));
  3422. let ri = self.s.m.bin(c, Bin::LShr, lane, four);
  3423. let ri = self.s.m.bin(c, Bin::And, ri, three);
  3424. let bi = self.s.m.bin(c, Bin::LShr, lane, two);
  3425. let bi = self.s.m.bin(c, Bin::And, bi, three);
  3426. let (rm, bm) = (k(self, u32::from(rows)), k(self, u32::from(banks)));
  3427. let rb = self.s.m.bin(c, Bin::LShr, rm, ri);
  3428. let bb = self.s.m.bin(c, Bin::LShr, bm, bi);
  3429. let both = self.s.m.bin(c, Bin::And, rb, bb);
  3430. let (one, z) = (k(self, 1), k(self, 0));
  3431. let both = self.s.m.bin(c, Bin::And, both, one);
  3432. let on = self.s.m.cmp(c, pred::NE, both, z);
  3433. enable = Some(match enable {
  3434. Some(e) => self.s.m.bin(c, Bin::And, e, on),
  3435. None => on,
  3436. });
  3437. }
  3438. Ok((r, enable))
  3439. }
  3440. fn valu_op(&mut self, inst: &Inst, guard: Option<V>) -> Result<(), Why> {
  3441. let Fields::Valu(v) = &inst.fields else {
  3442. unreachable!()
  3443. };
  3444. let name = inst.name();
  3445. let c = self.cur;
  3446. let f = |l: &mut Self, k| l.fsrc(inst, k);
  3447. let s = |l: &mut Self, k| l.src(inst, k);
  3448. let float = |l: &mut Self, r: V| l.write_f(inst, r, guard);
  3449. let int = |l: &mut Self, r: V| l.write_i(inst, r, guard);
  3450. if let Some(r) = self.valu16(inst, name, guard) {
  3451. return r;
  3452. }
  3453. if let Some(op) = name.strip_prefix("v_pk_") {
  3454. return self.packed16(inst, op, guard);
  3455. }
  3456. match name {
  3457. "v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => {
  3458. let n = s(self, 0)?;
  3459. let x = self.src64(inst, 1)?;
  3460. let i64t = self.s.m.int(64);
  3461. let k63 = self.s.m.i32(63);
  3462. let n = self.s.m.bin(c, Bin::And, n, k63);
  3463. let n = self.s.m.cast(c, Cast::ZExt, n, i64t);
  3464. let op = match name {
  3465. "v_lshlrev_b64" => Bin::Shl,
  3466. "v_lshrrev_b64" => Bin::LShr,
  3467. _ => Bin::AShr,
  3468. };
  3469. let r = self.s.m.bin(c, op, x, n);
  3470. let Some(Operand::Vector { reg, .. }) = v.dst else {
  3471. return Err("a 64-bit result");
  3472. };
  3473. let (lo, hi) = self.split64(r);
  3474. self.write(inst, Reg::V(reg), lo, guard);
  3475. self.write(inst, Reg::V(reg + 1), hi, guard);
  3476. Ok(())
  3477. }
  3478. "v_cubeid_f32" | "v_cubesc_f32" | "v_cubetc_f32" | "v_cubema_f32" => {
  3479. // Cube-map face coordinates (AMD's ISA): the major axis is z
  3480. // when |z| >= |x| and |z| >= |y|, else y when |y| >= |x|,
  3481. // else x.
  3482. let (x, y, z) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  3483. let (ax, ay, az) = (self.unary(6, x), self.unary(6, y), self.unary(6, z));
  3484. let zx = self.s.m.cmp(c, pred::OGE, az, ax);
  3485. let zy = self.s.m.cmp(c, pred::OGE, az, ay);
  3486. let zmaj = self.s.m.bin(c, Bin::And, zx, zy);
  3487. let ymaj = self.s.m.cmp(c, pred::OGE, ay, ax);
  3488. let zero = self.s.m.f32(0);
  3489. let neg = |l: &mut Self, v: V| l.s.m.cmp(c, pred::OLT, v, zero);
  3490. let minus = |l: &mut Self, v: V| {
  3491. let z = l.s.m.f32(0x8000_0000);
  3492. l.s.m.bin(c, Bin::Sub, z, v)
  3493. };
  3494. let pick = |l: &mut Self, zv: V, yv: V, xv: V| {
  3495. let t = l.s.m.select(c, ymaj, yv, xv);
  3496. l.s.m.select(c, zmaj, zv, t)
  3497. };
  3498. let r = match name {
  3499. "v_cubeid_f32" => {
  3500. let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits());
  3501. let (nz, ny, nx) = (neg(self, z), neg(self, y), neg(self, x));
  3502. let (f5, f4, f3, f2, f1, f0) = (
  3503. k(self, 5.0),
  3504. k(self, 4.0),
  3505. k(self, 3.0),
  3506. k(self, 2.0),
  3507. k(self, 1.0),
  3508. k(self, 0.0),
  3509. );
  3510. let zf = self.s.m.select(c, nz, f5, f4);
  3511. let yf = self.s.m.select(c, ny, f3, f2);
  3512. let xf = self.s.m.select(c, nx, f1, f0);
  3513. pick(self, zf, yf, xf)
  3514. }
  3515. "v_cubesc_f32" => {
  3516. let (nz, nx) = (neg(self, z), neg(self, x));
  3517. let (mx, mz) = (minus(self, x), minus(self, z));
  3518. let zf = self.s.m.select(c, nz, mx, x);
  3519. let xf = self.s.m.select(c, nx, z, mz);
  3520. pick(self, zf, x, xf)
  3521. }
  3522. "v_cubetc_f32" => {
  3523. let ny = neg(self, y);
  3524. let (my, mz) = (minus(self, y), minus(self, z));
  3525. let yf = self.s.m.select(c, ny, mz, z);
  3526. pick(self, my, yf, my)
  3527. }
  3528. _ => {
  3529. let t = pick(self, z, y, x);
  3530. let two = self.s.m.f32(2.0f32.to_bits());
  3531. self.s.m.bin(c, Bin::Mul, t, two)
  3532. }
  3533. };
  3534. float(self, r)
  3535. }
  3536. "v_movrels_b32" | "v_movreld_b32" | "v_movrelsd_b32" => {
  3537. // M0 indexes the source (movrels), the destination (movreld)
  3538. // or both, from the encoded register up to the program's
  3539. // VGPR count (the registers the instruction reads or writes).
  3540. let m0 = self.i32_of(inst.read(Reg::S(crate::ir::M0)).ok_or("M0")?)?;
  3541. let (
  3542. Some(&Operand::Vector { reg: sreg, .. }),
  3543. Some(Operand::Vector { reg: dreg, .. }),
  3544. ) = (v.src.first(), v.dst)
  3545. else {
  3546. return Err("an M0-relative move");
  3547. };
  3548. let indexed_src = name != "v_movreld_b32";
  3549. let value = if indexed_src {
  3550. let mut r = self.s.m.i32(0);
  3551. for k in 0..=255u8.saturating_sub(sreg) {
  3552. let Some(x) = inst.read(Reg::V(sreg + k)) else {
  3553. break;
  3554. };
  3555. let x = self.i32_of(x)?;
  3556. let kk = self.s.m.i32(u32::from(k));
  3557. let is = self.s.m.cmp(c, pred::EQ, m0, kk);
  3558. r = self.s.m.select(c, is, x, r);
  3559. }
  3560. r
  3561. } else {
  3562. s(self, 0)?
  3563. };
  3564. if name == "v_movrels_b32" {
  3565. return int(self, value);
  3566. }
  3567. for k in 0..=255u8.saturating_sub(dreg) {
  3568. let Some(_) = inst.write(Reg::V(dreg + k)) else {
  3569. break;
  3570. };
  3571. let old = match inst.read(Reg::V(dreg + k)) {
  3572. Some(o) => self.i32_of(o)?,
  3573. None => self.s.m.i32(0),
  3574. };
  3575. let kk = self.s.m.i32(u32::from(k));
  3576. let is = self.s.m.cmp(c, pred::EQ, m0, kk);
  3577. let x = self.s.m.select(c, is, value, old);
  3578. self.write_placed(inst, Reg::V(dreg + k), x, guard);
  3579. }
  3580. Ok(())
  3581. }
  3582. "v_swap_b32" => {
  3583. let (
  3584. Some(&Operand::Vector { reg: sreg, .. }),
  3585. Some(Operand::Vector { reg: dreg, .. }),
  3586. ) = (v.src.first(), v.dst)
  3587. else {
  3588. return Err("v_swap_b32");
  3589. };
  3590. let a = self.i32_of(inst.read(Reg::V(dreg)).ok_or("v_swap_b32")?)?;
  3591. let b = self.i32_of(inst.read(Reg::V(sreg)).ok_or("v_swap_b32")?)?;
  3592. self.write_placed(inst, Reg::V(dreg), b, guard);
  3593. if dreg != sreg {
  3594. self.write_placed(inst, Reg::V(sreg), a, guard);
  3595. }
  3596. Ok(())
  3597. }
  3598. "v_ffbh_u32" | "v_ffbh_i32" => {
  3599. // Counted from the top bit, -1 when none (DXIL's too).
  3600. let a = s(self, 0)?;
  3601. let op = if name == "v_ffbh_u32" { 33 } else { 34 };
  3602. let r = self
  3603. .s
  3604. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
  3605. int(self, r)
  3606. }
  3607. "v_mov_b32" => {
  3608. if v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 {
  3609. let a = f(self, 0)?;
  3610. return float(self, a);
  3611. }
  3612. let a = s(self, 0)?;
  3613. int(self, a)
  3614. }
  3615. "v_add_f32" | "v_sub_f32" | "v_subrev_f32" | "v_mul_f32" | "v_mul_legacy_f32"
  3616. | "v_max_f32" | "v_min_f32" => {
  3617. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  3618. let r = match name {
  3619. "v_add_f32" => self.s.m.bin(c, Bin::Add, a, bb),
  3620. "v_sub_f32" => self.s.m.bin(c, Bin::Sub, a, bb),
  3621. "v_subrev_f32" => self.s.m.bin(c, Bin::Sub, bb, a),
  3622. "v_mul_f32" => self.s.m.bin(c, Bin::Mul, a, bb),
  3623. "v_mul_legacy_f32" => self.legacy_mul(a, bb),
  3624. "v_max_f32" => self.binary(35, a, bb),
  3625. _ => self.binary(36, a, bb),
  3626. };
  3627. float(self, r)
  3628. }
  3629. "v_fma_f32" | "v_fmaak_f32" | "v_fmamk_f32" => {
  3630. // shortcut: DXIL has no fused f32 multiply-add; FMad lets the driver fuse.
  3631. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  3632. let r = self.fmad(a, bb, cc);
  3633. float(self, r)
  3634. }
  3635. "v_fmac_f32" | "v_mac_f32" | "v_mac_legacy_f32" => {
  3636. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  3637. let Some(Operand::Vector { reg, .. }) = v.dst else {
  3638. return Err("an accumulator");
  3639. };
  3640. let acc = inst.read(Reg::V(reg)).ok_or("an accumulator")?;
  3641. let acc = match self.floats.get(&acc) {
  3642. Some(&x) => x,
  3643. None => {
  3644. let x = self.i32_of(acc)?;
  3645. self.as_float(x)
  3646. }
  3647. };
  3648. let r = match name {
  3649. "v_fmac_f32" => self.fmad(a, bb, acc),
  3650. "v_mac_f32" => {
  3651. let m = self.s.m.bin(c, Bin::Mul, a, bb);
  3652. self.s.m.bin(c, Bin::Add, m, acc)
  3653. }
  3654. _ => {
  3655. let m = self.legacy_mul(a, bb);
  3656. self.s.m.bin(c, Bin::Add, m, acc)
  3657. }
  3658. };
  3659. float(self, r)
  3660. }
  3661. "v_mad_f32" | "v_madak_f32" | "v_madmk_f32" | "v_mad_legacy_f32" => {
  3662. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  3663. let m = if name == "v_mad_legacy_f32" {
  3664. self.legacy_mul(a, bb)
  3665. } else {
  3666. self.s.m.bin(c, Bin::Mul, a, bb)
  3667. };
  3668. let r = self.s.m.bin(c, Bin::Add, m, cc);
  3669. float(self, r)
  3670. }
  3671. "v_max3_f32" | "v_min3_f32" | "v_med3_f32" => {
  3672. let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
  3673. let r = match name {
  3674. "v_max3_f32" => {
  3675. let t = self.binary(35, a, bb);
  3676. self.binary(35, t, cc)
  3677. }
  3678. "v_min3_f32" => {
  3679. let t = self.binary(36, a, bb);
  3680. self.binary(36, t, cc)
  3681. }
  3682. _ => self.med3(a, bb, cc),
  3683. };
  3684. float(self, r)
  3685. }
  3686. "v_rcp_f32" | "v_rcp_iflag_f32" => {
  3687. // shortcut: the hardware reciprocal is approximate (1 ULP); this divides.
  3688. let a = f(self, 0)?;
  3689. let one = self.s.m.f32(1.0f32.to_bits());
  3690. let r = self.s.m.bin(c, Bin::SDiv, one, a);
  3691. float(self, r)
  3692. }
  3693. "v_rsq_f32" | "v_sqrt_f32" | "v_log_f32" | "v_exp_f32" | "v_fract_f32"
  3694. | "v_trunc_f32" | "v_floor_f32" | "v_ceil_f32" | "v_rndne_f32" | "v_sin_f32"
  3695. | "v_cos_f32" => {
  3696. let a = f(self, 0)?;
  3697. let op = match name {
  3698. "v_rsq_f32" => 25,
  3699. "v_sqrt_f32" => 24,
  3700. "v_log_f32" => 23,
  3701. "v_exp_f32" => 21,
  3702. "v_fract_f32" => 22,
  3703. "v_trunc_f32" => 29,
  3704. "v_floor_f32" => 27,
  3705. "v_ceil_f32" => 28,
  3706. "v_rndne_f32" => 26,
  3707. "v_sin_f32" => 13,
  3708. _ => 12,
  3709. };
  3710. let r = match op {
  3711. 12 | 13 => self.trig_turns(a, op == 12),
  3712. 22 => self.fract(a, 1.0, f32::from_bits(0x3F7F_FFFF)),
  3713. _ => self.unary(op, a),
  3714. };
  3715. float(self, r)
  3716. }
  3717. "v_cvt_i32_f32" | "v_cvt_u32_f32" | "v_cvt_flr_i32_f32" | "v_cvt_rpi_i32_f32" => {
  3718. let mut a = f(self, 0)?;
  3719. if name == "v_cvt_rpi_i32_f32" {
  3720. let h = self.s.m.f32(0.5f32.to_bits());
  3721. a = self.s.m.bin(c, Bin::Add, a, h);
  3722. }
  3723. if name != "v_cvt_i32_f32" && name != "v_cvt_u32_f32" {
  3724. a = self.unary(27, a);
  3725. }
  3726. // D3D's conversions saturate and give 0 for NaN, as the
  3727. // hardware does (checked on the RX 6700 XT and WARP).
  3728. let op = if name == "v_cvt_u32_f32" {
  3729. Cast::FpToUi
  3730. } else {
  3731. Cast::FpToSi
  3732. };
  3733. let r = self.s.m.cast(c, op, a, self.s.t.i32);
  3734. int(self, r)
  3735. }
  3736. "v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1"
  3737. | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => {
  3738. let mut a = s(self, 0)?;
  3739. if let Some(n) = name.strip_prefix("v_cvt_f32_ubyte") {
  3740. let sh = self.s.m.i32(8 * u32::from(n.as_bytes()[0] - b'0'));
  3741. let ff = self.s.m.i32(0xff);
  3742. a = self.s.m.bin(c, Bin::LShr, a, sh);
  3743. a = self.s.m.bin(c, Bin::And, a, ff);
  3744. }
  3745. let op = if name == "v_cvt_f32_i32" {
  3746. Cast::SiToFp
  3747. } else {
  3748. Cast::UiToFp
  3749. };
  3750. let r = self.s.m.cast(c, op, a, self.s.t.f32);
  3751. float(self, r)
  3752. }
  3753. "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => {
  3754. // Each source is f32, or with op_sel_hi the low (op_sel: high)
  3755. // f16 half; neg_hi is the absolute value here.
  3756. let mut xs = Vec::new();
  3757. for i in 0..3 {
  3758. let op = v.src.get(i).ok_or("a missing operand")?;
  3759. let x = self.operand(inst, op)?;
  3760. let mut x = if v.opsel_hi >> i & 1 != 0 {
  3761. let h = if v.opsel >> i & 1 != 0 {
  3762. let k16 = self.s.m.i32(16);
  3763. self.s.m.bin(c, Bin::LShr, x, k16)
  3764. } else {
  3765. x
  3766. };
  3767. self.s
  3768. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h])
  3769. } else {
  3770. self.as_float(x)
  3771. };
  3772. if v.neg_hi >> i & 1 != 0 {
  3773. x = self.unary(6, x);
  3774. }
  3775. if v.neg >> i & 1 != 0 {
  3776. let z = self.s.m.f32(0x8000_0000);
  3777. x = self.s.m.bin(c, Bin::Sub, z, x);
  3778. }
  3779. xs.push(x);
  3780. }
  3781. let mut r = self.fmad(xs[0], xs[1], xs[2]);
  3782. if name == "v_fma_mix_f32" {
  3783. return float(self, r);
  3784. }
  3785. if v.clamp {
  3786. r = self.unary(7, r);
  3787. }
  3788. // The f16 result goes to one half; the other half stays.
  3789. let Some(Operand::Vector { reg, .. }) = v.dst else {
  3790. return Err("a mixed-precision result");
  3791. };
  3792. let old = match inst.read(Reg::V(reg)) {
  3793. Some(o) => self.i32_of(o)?,
  3794. None => self.s.m.i32(0),
  3795. };
  3796. let h = self
  3797. .s
  3798. .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[r]);
  3799. let (keep, h) = if name == "v_fma_mixhi_f16" {
  3800. let k16 = self.s.m.i32(16);
  3801. (0xFFFF, self.s.m.bin(c, Bin::Shl, h, k16))
  3802. } else {
  3803. (0xFFFF_0000, h)
  3804. };
  3805. let keep = self.s.m.i32(keep);
  3806. let old = self.s.m.bin(c, Bin::And, old, keep);
  3807. let x = self.s.m.bin(c, Bin::Or, old, h);
  3808. self.write(inst, Reg::V(reg), x, guard);
  3809. Ok(())
  3810. }
  3811. "v_cvt_pkrtz_f16_f32" => {
  3812. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  3813. let lo = self.f16_toward_zero(a);
  3814. let hi = self.f16_toward_zero(bb);
  3815. let sh = self.s.m.i32(16);
  3816. let hi = self.s.m.bin(c, Bin::Shl, hi, sh);
  3817. let r = self.s.m.bin(c, Bin::Or, lo, hi);
  3818. int(self, r)
  3819. }
  3820. "v_cvt_f16_f32" if v.opsel == 0 => {
  3821. // Rounded to nearest even (the MODE default) into the low half.
  3822. let a = f(self, 0)?;
  3823. let r = self
  3824. .s
  3825. .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[a]);
  3826. let Some(Operand::Vector { reg, .. }) = v.dst else {
  3827. return Err("a 16-bit result outside a VGPR");
  3828. };
  3829. let r = self.low_half(inst, reg, r);
  3830. int(self, r)
  3831. }
  3832. "v_pack_b32_f16" => {
  3833. // Two f16 sources (op_sel: their high halves; abs and neg on
  3834. // the sign bit) into the low and high half.
  3835. let mut halves = Vec::new();
  3836. for k in 0..2 {
  3837. let op = v.src.get(k).ok_or("a missing operand")?;
  3838. let mut x = self.operand(inst, op)?;
  3839. if v.opsel >> k & 1 != 0 {
  3840. let k16 = self.s.m.i32(16);
  3841. x = self.s.m.bin(c, Bin::LShr, x, k16);
  3842. }
  3843. let mask = if v.abs >> k & 1 != 0 { 0x7FFF } else { 0xFFFF };
  3844. let mask = self.s.m.i32(mask);
  3845. x = self.s.m.bin(c, Bin::And, x, mask);
  3846. if v.neg >> k & 1 != 0 {
  3847. let sign = self.s.m.i32(0x8000);
  3848. x = self.s.m.bin(c, Bin::Xor, x, sign);
  3849. }
  3850. halves.push(x);
  3851. }
  3852. let k16 = self.s.m.i32(16);
  3853. let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16);
  3854. let r = self.s.m.bin(c, Bin::Or, halves[0], hi);
  3855. int(self, r)
  3856. }
  3857. "v_cvt_f32_f16" if v.opsel == 0 => {
  3858. let a = s(self, 0)?;
  3859. let r = self
  3860. .s
  3861. .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[a]);
  3862. float(self, r)
  3863. }
  3864. "v_cndmask_b32" => {
  3865. let mask = match v.src.get(2) {
  3866. Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
  3867. _ => None,
  3868. };
  3869. let m = mask
  3870. .and_then(|m| self.x.st.masks.get(&m).copied())
  3871. .ok_or("a select on an untracked mask")?;
  3872. let cond = self.boolean(m, c)?;
  3873. if v.abs != 0 || v.neg != 0 {
  3874. let (a, bb) = (f(self, 0)?, f(self, 1)?);
  3875. let r = self.s.m.select(c, cond, bb, a);
  3876. return float(self, r);
  3877. }
  3878. let (a, bb) = (s(self, 0)?, s(self, 1)?);
  3879. let r = self.s.m.select(c, cond, bb, a);
  3880. int(self, r)
  3881. }
  3882. "v_add_co_u32" | "v_sub_co_u32" | "v_subrev_co_u32" | "v_add_co_ci_u32"
  3883. | "v_sub_co_ci_u32" | "v_subrev_co_ci_u32" => {
  3884. // The carry (borrow) out is a lane mask: this lane's bit.
  3885. let (mut a, mut bb) = (s(self, 0)?, s(self, 1)?);
  3886. if name.contains("subrev") {
  3887. std::mem::swap(&mut a, &mut bb);
  3888. }
  3889. let cin = if name.ends_with("_ci_u32") {
  3890. let m = match v.src.get(2) {
  3891. Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
  3892. _ => None,
  3893. };
  3894. let m = m
  3895. .and_then(|m| self.x.st.masks.get(&m).copied())
  3896. .ok_or("a carry-in from an untracked mask")?;
  3897. Some(self.boolean(m, c)?)
  3898. } else {
  3899. None
  3900. };
  3901. let (r, carry) = self.add_sub_carry(c, name.starts_with("v_add"), a, bb, cin);
  3902. int(self, r)?;
  3903. if let Some(Operand::Scalar { code, .. }) = v.carry
  3904. && let Some(w) = inst.write(Reg::S(code))
  3905. {
  3906. self.lane_bits.insert(w, carry);
  3907. }
  3908. for &(_, w) in &inst.writes {
  3909. self.vals
  3910. .entry(w)
  3911. .or_insert(Val::Missing("a lane mask read as data"));
  3912. }
  3913. Ok(())
  3914. }
  3915. "v_readlane_b32" => {
  3916. let (a, lane) = (s(self, 0)?, s(self, 1)?);
  3917. // A computed lane in a pixel or vertex program is a host lane
  3918. // (from a mask or `v_mbcnt`); a constant one is the console's.
  3919. if self.mask_data == MaskData::Host && !matches!(lane, V::Const(_)) {
  3920. self.s.flags |= flags::WAVE_OPS;
  3921. } else {
  3922. self.cross_lane(false)?;
  3923. }
  3924. let r = self.read_lane(a, lane);
  3925. int(self, r)
  3926. }
  3927. "v_writelane_b32" => {
  3928. // The lane given takes the scalar; the others keep their value.
  3929. let (a, lane) = (s(self, 0)?, s(self, 1)?);
  3930. let Some(Operand::Vector { reg, .. }) = v.dst else {
  3931. return Err("a lane write");
  3932. };
  3933. let old = match inst.read(Reg::V(reg)) {
  3934. Some(o) => self.i32_of(o)?,
  3935. None => self.s.m.i32(0),
  3936. };
  3937. self.cross_lane(false)?;
  3938. let me = self.lane_index();
  3939. let is = self.s.m.cmp(c, pred::EQ, me, lane);
  3940. let r = self.s.m.select(c, is, a, old);
  3941. int(self, r)
  3942. }
  3943. "v_readfirstlane_b32" => {
  3944. let a = s(self, 0)?;
  3945. self.s.flags |= flags::WAVE_OPS;
  3946. let r = self.s.op(
  3947. c,
  3948. "waveReadLaneFirst.i32",
  3949. Attr::NoUnwind,
  3950. self.s.t.i32,
  3951. 118,
  3952. &[a],
  3953. );
  3954. int(self, r)
  3955. }
  3956. _ => {
  3957. let r = self.integer(inst, name)?;
  3958. int(self, r)
  3959. }
  3960. }
  3961. }
  3962. /// A 64-bit source (a register pair; inline constants sign-extend).
  3963. fn src64(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  3964. let Fields::Valu(v) = &inst.fields else {
  3965. unreachable!()
  3966. };
  3967. if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 || v.sdwa.is_some() || v.dpp.is_some() {
  3968. return Err("64-bit operand modifiers");
  3969. }
  3970. let c = self.cur;
  3971. let i64t = self.s.m.int(64);
  3972. self.s.flags |= flags::INT64;
  3973. let op = *v.src.get(k).ok_or("a missing operand")?;
  3974. let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<V, Why> {
  3975. let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?;
  3976. let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?;
  3977. let lo = l.s.m.cast(c, Cast::ZExt, lo, i64t);
  3978. let hi = l.s.m.cast(c, Cast::ZExt, hi, i64t);
  3979. let k32 = l.s.m.int_const(i64t, 32);
  3980. let hi = l.s.m.bin(c, Bin::Shl, hi, k32);
  3981. Ok(l.s.m.bin(c, Bin::Or, lo, hi))
  3982. };
  3983. match op {
  3984. Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1)),
  3985. Operand::Scalar { code, .. } if code != NULL => {
  3986. pair(self, Reg::S(code), Reg::S(code + 1))
  3987. }
  3988. Operand::Const(k @ 128..=208) => {
  3989. let x = crate::resource::inline(k).ok_or("a special operand")?;
  3990. Ok(self.s.m.int_const(i64t, i64::from(x as i32)))
  3991. }
  3992. _ => {
  3993. // Literals and the null register: zero-extended.
  3994. let x = self.operand(inst, &op)?;
  3995. Ok(self.s.m.cast(c, Cast::ZExt, x, i64t))
  3996. }
  3997. }
  3998. }
  3999. /// The low and high dwords of an i64.
  4000. fn split64(&mut self, x: V) -> (V, V) {
  4001. let c = self.cur;
  4002. let i64t = self.s.m.int(64);
  4003. let k32 = self.s.m.int_const(i64t, 32);
  4004. let lo = self.s.m.cast(c, Cast::Trunc, x, self.s.t.i32);
  4005. let hi = self.s.m.bin(c, Bin::LShr, x, k32);
  4006. let hi = self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32);
  4007. (lo, hi)
  4008. }
  4009. /// Source `k` of a 16-bit operation in the low 16 bits (the rest 0):
  4010. /// op_sel (or an SDWA word select) picks the high half; inline float
  4011. /// constants are f16 values here.
  4012. fn half_src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  4013. let Fields::Valu(v) = &inst.fields else {
  4014. unreachable!()
  4015. };
  4016. let op = *v.src.get(k).ok_or("a missing operand")?;
  4017. let mut high = v.opsel >> k & 1 != 0;
  4018. if let Some(sd) = v.sdwa {
  4019. match sd.src_sel.get(k).copied().unwrap_or(6) {
  4020. 4 => {}
  4021. 5 => high = true,
  4022. 6 => {}
  4023. _ => return Err("a byte select on a 16-bit operation"),
  4024. }
  4025. }
  4026. let x = match (op, self.src0) {
  4027. (_, Some(x)) if k == 0 => x,
  4028. (Operand::Const(c @ 240..=248), _) => {
  4029. let h = [
  4030. 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118,
  4031. ][usize::from(c - 240)];
  4032. self.s.m.i32(h)
  4033. }
  4034. _ => self.operand(inst, &op)?,
  4035. };
  4036. let c = self.cur;
  4037. let x = if high {
  4038. let k16 = self.s.m.i32(16);
  4039. self.s.m.bin(c, Bin::LShr, x, k16)
  4040. } else {
  4041. x
  4042. };
  4043. let m = self.s.m.i32(0xFFFF);
  4044. Ok(self.s.m.bin(c, Bin::And, x, m))
  4045. }
  4046. /// An f16 source as an f32 (exact), with its abs/neg modifiers.
  4047. fn half_fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
  4048. let Fields::Valu(v) = &inst.fields else {
  4049. unreachable!()
  4050. };
  4051. let h = self.half_src(inst, k)?;
  4052. let f32t = self.s.t.f32;
  4053. let mut f = self
  4054. .s
  4055. .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  4056. if v.abs >> k & 1 != 0 {
  4057. f = self.unary(6, f);
  4058. }
  4059. if v.neg >> k & 1 != 0 {
  4060. let z = self.s.m.f32(0x8000_0000);
  4061. f = self.s.m.bin(self.cur, Bin::Sub, z, f);
  4062. }
  4063. Ok(f)
  4064. }
  4065. /// Writes a 16-bit result (low bits of `x`) into the destination's low
  4066. /// half, or its high half with op_sel bit 3 (or an SDWA WORD_1 select);
  4067. /// the other half is kept (GFX10).
  4068. fn write_half(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> {
  4069. let Fields::Valu(v) = &inst.fields else {
  4070. unreachable!()
  4071. };
  4072. let Some(Operand::Vector { reg, .. }) = v.dst else {
  4073. return Err("a 16-bit result outside a VGPR");
  4074. };
  4075. let mut high = v.opsel >> 3 & 1 != 0;
  4076. // SDWA: the word written, the other one kept (preserve) or zero
  4077. // (pad; a sign extension above the high word adds nothing).
  4078. let mut keep = true;
  4079. if let Some(sd) = v.sdwa {
  4080. match (sd.dst_sel, sd.dst_unused) {
  4081. (4, 2) => {}
  4082. (5, 2) => high = true,
  4083. (4 | 6, _) => keep = false,
  4084. (5, _) => (high, keep) = (true, false),
  4085. _ => return Err("an SDWA destination of a 16-bit operation"),
  4086. }
  4087. }
  4088. let c = self.cur;
  4089. let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) {
  4090. Some(Ok(o)) if keep => o,
  4091. _ => self.s.m.i32(0),
  4092. };
  4093. let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
  4094. let x = self.s.m.bin(c, Bin::And, x, low);
  4095. let r = if high {
  4096. let o = self.s.m.bin(c, Bin::And, old, low);
  4097. let x = self.s.m.bin(c, Bin::Shl, x, k16);
  4098. self.s.m.bin(c, Bin::Or, o, x)
  4099. } else {
  4100. let keep = self.s.m.i32(0xFFFF_0000);
  4101. let o = self.s.m.bin(c, Bin::And, old, keep);
  4102. self.s.m.bin(c, Bin::Or, o, x)
  4103. };
  4104. self.write_placed(inst, Reg::V(reg), r, guard);
  4105. Ok(())
  4106. }
  4107. /// 16-bit operations, computed in f32 or i32: f16 sums, differences and
  4108. /// products are exact there and round once to f16 (f32 has the 2 x 11 +
  4109. /// 2 bits that make double rounding harmless); `None` if `name` is none.
  4110. fn valu16(&mut self, inst: &Inst, name: &str, guard: Option<V>) -> Option<Result<(), Why>> {
  4111. const FLOAT2: &[&str] = &[
  4112. "v_add_f16",
  4113. "v_sub_f16",
  4114. "v_subrev_f16",
  4115. "v_mul_f16",
  4116. "v_max_f16",
  4117. "v_min_f16",
  4118. ];
  4119. const FLOAT3: &[&str] = &[
  4120. "v_fma_f16",
  4121. "v_mad_f16",
  4122. "v_fmac_f16",
  4123. "v_mac_f16",
  4124. "v_max3_f16",
  4125. "v_min3_f16",
  4126. "v_med3_f16",
  4127. ];
  4128. const FLOAT1: &[&str] = &[
  4129. "v_rcp_f16",
  4130. "v_sqrt_f16",
  4131. "v_rsq_f16",
  4132. "v_log_f16",
  4133. "v_exp_f16",
  4134. "v_fract_f16",
  4135. "v_trunc_f16",
  4136. "v_floor_f16",
  4137. "v_ceil_f16",
  4138. "v_rndne_f16",
  4139. "v_sin_f16",
  4140. "v_cos_f16",
  4141. "v_cvt_f16_u16",
  4142. "v_cvt_f16_i16",
  4143. ];
  4144. const INT: &[&str] = &[
  4145. "v_add_nc_u16",
  4146. "v_sub_nc_u16",
  4147. "v_subrev_nc_u16",
  4148. "v_mul_lo_u16",
  4149. "v_lshlrev_b16",
  4150. "v_lshrrev_b16",
  4151. "v_ashrrev_i16",
  4152. "v_max_u16",
  4153. "v_max_i16",
  4154. "v_min_u16",
  4155. "v_min_i16",
  4156. "v_cvt_u16_f16",
  4157. "v_cvt_i16_f16",
  4158. "v_cvt_norm_i16_f16",
  4159. "v_cvt_norm_u16_f16",
  4160. ];
  4161. let all = [FLOAT1, FLOAT2, FLOAT3, INT];
  4162. if !all.iter().any(|l| l.contains(&name))
  4163. && !matches!(name, "v_cvt_f16_f32" | "v_cvt_f32_f16")
  4164. {
  4165. return None;
  4166. }
  4167. Some(self.valu16_op(inst, name, guard, FLOAT1, FLOAT2, FLOAT3))
  4168. }
  4169. #[allow(clippy::too_many_arguments)]
  4170. fn valu16_op(
  4171. &mut self,
  4172. inst: &Inst,
  4173. name: &str,
  4174. guard: Option<V>,
  4175. float1: &[&str],
  4176. float2: &[&str],
  4177. float3: &[&str],
  4178. ) -> Result<(), Why> {
  4179. let Fields::Valu(v) = &inst.fields else {
  4180. unreachable!()
  4181. };
  4182. let c = self.cur;
  4183. let i32t = self.s.t.i32;
  4184. let f32t = self.s.t.f32;
  4185. if name == "v_cvt_f32_f16" {
  4186. let f = self.half_fsrc(inst, 0)?;
  4187. return self.write_f(inst, f, guard);
  4188. }
  4189. let float_result = |l: &mut Self, mut f: V| -> Result<(), Why> {
  4190. if v.omod != 0 {
  4191. return Err("an output modifier on a 16-bit operation");
  4192. }
  4193. if v.clamp {
  4194. f = l.unary(7, f);
  4195. }
  4196. let h =
  4197. l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
  4198. l.write_half(inst, h, guard)
  4199. };
  4200. if name == "v_cvt_f16_f32" {
  4201. let f = self.fsrc(inst, 0)?;
  4202. return float_result(self, f);
  4203. }
  4204. if float2.contains(&name) {
  4205. let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?);
  4206. let r = match name {
  4207. "v_add_f16" => self.s.m.bin(c, Bin::Add, a, b),
  4208. "v_sub_f16" => self.s.m.bin(c, Bin::Sub, a, b),
  4209. "v_subrev_f16" => self.s.m.bin(c, Bin::Sub, b, a),
  4210. "v_mul_f16" => self.s.m.bin(c, Bin::Mul, a, b),
  4211. "v_max_f16" => self.binary(35, a, b),
  4212. _ => self.binary(36, a, b),
  4213. };
  4214. return float_result(self, r);
  4215. }
  4216. if float3.contains(&name) {
  4217. let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?);
  4218. let acc = if matches!(name, "v_fmac_f16" | "v_mac_f16") {
  4219. // The accumulator is the destination's half that is written.
  4220. let Some(Operand::Vector { reg, .. }) = v.dst else {
  4221. return Err("an accumulator");
  4222. };
  4223. let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?;
  4224. let x = if v.opsel >> 3 & 1 != 0 {
  4225. let k16 = self.s.m.i32(16);
  4226. self.s.m.bin(c, Bin::LShr, x, k16)
  4227. } else {
  4228. x
  4229. };
  4230. let m = self.s.m.i32(0xFFFF);
  4231. let x = self.s.m.bin(c, Bin::And, x, m);
  4232. self.s
  4233. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x])
  4234. } else {
  4235. self.half_fsrc(inst, 2)?
  4236. };
  4237. let r = match name {
  4238. // shortcut: fused f16 multiply-adds as FMad in f32 (the
  4239. // product is exact; the sum rounds twice).
  4240. "v_fma_f16" | "v_fmac_f16" | "v_mad_f16" | "v_mac_f16" => self.fmad(a, b, acc),
  4241. "v_max3_f16" => {
  4242. let t = self.binary(35, a, b);
  4243. self.binary(35, t, acc)
  4244. }
  4245. "v_min3_f16" => {
  4246. let t = self.binary(36, a, b);
  4247. self.binary(36, t, acc)
  4248. }
  4249. _ => self.med3(a, b, acc),
  4250. };
  4251. return float_result(self, r);
  4252. }
  4253. if float1.contains(&name) {
  4254. let r = match name {
  4255. "v_cvt_f16_u16" | "v_cvt_f16_i16" => {
  4256. let mut x = self.half_src(inst, 0)?;
  4257. let op = if name == "v_cvt_f16_i16" {
  4258. let k16 = self.s.m.i32(16);
  4259. let t = self.s.m.bin(c, Bin::Shl, x, k16);
  4260. x = self.s.m.bin(c, Bin::AShr, t, k16);
  4261. Cast::SiToFp
  4262. } else {
  4263. Cast::UiToFp
  4264. };
  4265. self.s.m.cast(c, op, x, f32t)
  4266. }
  4267. "v_rcp_f16" => {
  4268. let a = self.half_fsrc(inst, 0)?;
  4269. let one = self.s.m.f32(1.0f32.to_bits());
  4270. self.s.m.bin(c, Bin::SDiv, one, a)
  4271. }
  4272. _ => {
  4273. let a = self.half_fsrc(inst, 0)?;
  4274. let op = match name {
  4275. "v_sqrt_f16" => 24,
  4276. "v_rsq_f16" => 25,
  4277. "v_log_f16" => 23,
  4278. "v_exp_f16" => 21,
  4279. "v_fract_f16" => 22,
  4280. "v_trunc_f16" => 29,
  4281. "v_floor_f16" => 27,
  4282. "v_ceil_f16" => 28,
  4283. "v_rndne_f16" => 26,
  4284. "v_sin_f16" => 13,
  4285. _ => 12,
  4286. };
  4287. match op {
  4288. 12 | 13 => self.trig_turns(a, op == 12),
  4289. // Any f16 in (-2^-11, 0) has fract >= 1 - 2^-12; clamp to 0x3bff (1 - 2^-11).
  4290. 22 => self.fract(a, 1.0 - 1.0 / 4096.0, 1.0 - 1.0 / 2048.0),
  4291. _ => self.unary(op, a),
  4292. }
  4293. }
  4294. };
  4295. return float_result(self, r);
  4296. }
  4297. if matches!(name, "v_cvt_norm_i16_f16" | "v_cvt_norm_u16_f16") {
  4298. if v.clamp || v.omod != 0 {
  4299. return Err("modifiers on a 16-bit integer operation");
  4300. }
  4301. let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?;
  4302. return self.write_half(inst, r, guard);
  4303. }
  4304. // 16-bit integers: computed on the low halves, the low 16 bits kept.
  4305. if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 {
  4306. return Err("modifiers on a 16-bit integer operation");
  4307. }
  4308. let r = match name {
  4309. "v_cvt_u16_f16" | "v_cvt_i16_f16" => {
  4310. // Toward zero, saturating at the 16-bit range (infinities
  4311. // included); NaN gives 0. Clamped in f32 first, where every
  4312. // f16 is exact, so the conversion never leaves i32's range.
  4313. let a = self.half_fsrc(inst, 0)?;
  4314. let (lo, hi) = if name == "v_cvt_u16_f16" {
  4315. (0.0f32, 65535.0f32)
  4316. } else {
  4317. (-32768.0, 32767.0)
  4318. };
  4319. let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits()));
  4320. let t = self.binary(35, a, lo);
  4321. let t = self.binary(36, t, hi);
  4322. let r = self.s.m.cast(c, Cast::FpToSi, t, i32t);
  4323. let nan = self.s.m.cmp(c, pred::UNO, a, a);
  4324. let z = self.s.m.i32(0);
  4325. self.s.m.select(c, nan, z, r)
  4326. }
  4327. _ => {
  4328. let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
  4329. let k16 = self.s.m.i32(16);
  4330. let sext = |l: &mut Self, x: V| {
  4331. let t = l.s.m.bin(c, Bin::Shl, x, k16);
  4332. l.s.m.bin(c, Bin::AShr, t, k16)
  4333. };
  4334. if name.ends_with("_i16") {
  4335. a = sext(self, a);
  4336. b = sext(self, b);
  4337. }
  4338. let k15 = self.s.m.i32(15);
  4339. match name {
  4340. "v_add_nc_u16" => self.s.m.bin(c, Bin::Add, a, b),
  4341. "v_sub_nc_u16" => self.s.m.bin(c, Bin::Sub, a, b),
  4342. "v_subrev_nc_u16" => self.s.m.bin(c, Bin::Sub, b, a),
  4343. "v_mul_lo_u16" => self.s.m.bin(c, Bin::Mul, a, b),
  4344. "v_lshlrev_b16" | "v_lshrrev_b16" | "v_ashrrev_i16" => {
  4345. // src0 is the shift (4 bits), src1 the value.
  4346. let sh = self.s.m.bin(c, Bin::And, a, k15);
  4347. let x = if name == "v_ashrrev_i16" {
  4348. sext(self, b)
  4349. } else {
  4350. b
  4351. };
  4352. let op = match name {
  4353. "v_lshlrev_b16" => Bin::Shl,
  4354. "v_lshrrev_b16" => Bin::LShr,
  4355. _ => Bin::AShr,
  4356. };
  4357. self.s.m.bin(c, op, x, sh)
  4358. }
  4359. _ => {
  4360. let p = match name {
  4361. "v_max_u16" => pred::IUGT,
  4362. "v_min_u16" => pred::IULT,
  4363. "v_max_i16" => pred::SGT,
  4364. _ => pred::SLT,
  4365. };
  4366. let t = self.s.m.cmp(c, p, a, b);
  4367. self.s.m.select(c, t, a, b)
  4368. }
  4369. }
  4370. }
  4371. };
  4372. self.write_half(inst, r, guard)
  4373. }
  4374. /// `v_cvt_norm_i16_f16` / `v_cvt_norm_u16_f16`: the f16 source (with its
  4375. /// abs/neg modifiers) clamped to [-1, 1] or [0, 1], times 32767 or 65535,
  4376. /// rounded to nearest even once from the exact product; NaN gives 0.
  4377. /// Worked on the f16's bits in integers, because in f32 the product
  4378. /// (up to 26 significant bits) would round before the rounding to an
  4379. /// integer.
  4380. fn cvt_norm16(&mut self, inst: &Inst, signed: bool) -> Result<V, Why> {
  4381. let Fields::Valu(v) = &inst.fields else {
  4382. unreachable!()
  4383. };
  4384. let c = self.cur;
  4385. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  4386. let mut h = self.half_src(inst, 0)?;
  4387. if v.abs & 1 != 0 {
  4388. let m = k(self, 0x7FFF);
  4389. h = self.s.m.bin(c, Bin::And, h, m);
  4390. }
  4391. if v.neg & 1 != 0 {
  4392. let m = k(self, 0x8000);
  4393. h = self.s.m.bin(c, Bin::Xor, h, m);
  4394. }
  4395. let scale = if signed { 0x7FFF } else { 0xFFFF };
  4396. let (k0, k1, k10) = (k(self, 0), k(self, 1), k(self, 10));
  4397. let mag_mask = k(self, 0x7FFF);
  4398. let mag = self.s.m.bin(c, Bin::And, h, mag_mask);
  4399. let k15 = k(self, 15);
  4400. let neg = self.s.m.bin(c, Bin::LShr, h, k15);
  4401. let neg = self.s.m.cmp(c, pred::NE, neg, k0);
  4402. // |x| < 1: x = m * 2^-s with m < 2^11 and 11 <= s <= 24.
  4403. let exp = self.s.m.bin(c, Bin::LShr, mag, k10);
  4404. let man_mask = k(self, 0x3FF);
  4405. let man = self.s.m.bin(c, Bin::And, mag, man_mask);
  4406. let implicit = k(self, 0x400);
  4407. let normal = self.s.m.bin(c, Bin::Or, man, implicit);
  4408. let sub = self.s.m.cmp(c, pred::EQ, exp, k0);
  4409. let m = self.s.m.select(c, sub, man, normal);
  4410. let k25 = k(self, 25);
  4411. let s_norm = self.s.m.bin(c, Bin::Sub, k25, exp);
  4412. let k24 = k(self, 24);
  4413. let sh = self.s.m.select(c, sub, k24, s_norm);
  4414. let ks = k(self, scale);
  4415. let p = self.s.m.bin(c, Bin::Mul, m, ks);
  4416. let q = self.s.m.bin(c, Bin::LShr, p, sh);
  4417. let one_s = self.s.m.bin(c, Bin::Shl, k1, sh);
  4418. let low_mask = self.s.m.bin(c, Bin::Sub, one_s, k1);
  4419. let rem = self.s.m.bin(c, Bin::And, p, low_mask);
  4420. let half = self.s.m.bin(c, Bin::LShr, one_s, k1);
  4421. let above = self.s.m.cmp(c, pred::IUGT, rem, half);
  4422. let tie = self.s.m.cmp(c, pred::EQ, rem, half);
  4423. let odd = self.s.m.bin(c, Bin::And, q, k1);
  4424. let odd = self.s.m.cmp(c, pred::NE, odd, k0);
  4425. let tie_up = self.s.m.bin(c, Bin::And, tie, odd);
  4426. let up = self.s.m.bin(c, Bin::Or, above, tie_up);
  4427. let r = self.s.m.select(c, up, k1, k0);
  4428. let r = self.s.m.bin(c, Bin::Add, q, r);
  4429. // |x| >= 1 (and infinity) saturates; NaN gives 0.
  4430. let one_h = k(self, 0x3C00);
  4431. let big = self.s.m.cmp(c, pred::IUGE, mag, one_h);
  4432. let r = self.s.m.select(c, big, ks, r);
  4433. let inf = k(self, 0x7C00);
  4434. let nan = self.s.m.cmp(c, pred::IUGT, mag, inf);
  4435. let r = self.s.m.select(c, nan, k0, r);
  4436. let r = if signed {
  4437. let n = self.s.m.bin(c, Bin::Sub, k0, r);
  4438. self.s.m.select(c, neg, n, r)
  4439. } else {
  4440. self.s.m.select(c, neg, k0, r)
  4441. };
  4442. let m16 = k(self, 0xFFFF);
  4443. Ok(self.s.m.bin(c, Bin::And, r, m16))
  4444. }
  4445. /// Half `high` of source `k` of a packed (VOP3P) operation, in the low
  4446. /// 16 bits: op_sel picks the half the low result reads, op_sel_hi the
  4447. /// half the high result reads. Inline float constants are f16 values.
  4448. fn packed_src(&mut self, inst: &Inst, k: usize, high: bool) -> Result<V, Why> {
  4449. let Fields::Valu(v) = &inst.fields else {
  4450. unreachable!()
  4451. };
  4452. let op = *v.src.get(k).ok_or("a missing operand")?;
  4453. let sel = if high { v.opsel_hi } else { v.opsel } >> k & 1 != 0;
  4454. let x = match op {
  4455. Operand::Const(c @ 240..=248) => {
  4456. let h = [
  4457. 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118,
  4458. ][usize::from(c - 240)];
  4459. // shortcut: taken to fill both halves.
  4460. self.s.m.i32(h | h << 16)
  4461. }
  4462. _ => self.operand(inst, &op)?,
  4463. };
  4464. let c = self.cur;
  4465. let x = if sel {
  4466. let k16 = self.s.m.i32(16);
  4467. self.s.m.bin(c, Bin::LShr, x, k16)
  4468. } else {
  4469. x
  4470. };
  4471. let m = self.s.m.i32(0xFFFF);
  4472. Ok(self.s.m.bin(c, Bin::And, x, m))
  4473. }
  4474. /// Packed 16-bit operations (`v_pk_*`): each half computed as the
  4475. /// 16-bit operation does, f16 through f32 as in [`Self::valu16`].
  4476. fn packed16(&mut self, inst: &Inst, op: &str, guard: Option<V>) -> Result<(), Why> {
  4477. let Fields::Valu(v) = &inst.fields else {
  4478. unreachable!()
  4479. };
  4480. let float = op.ends_with("_f16");
  4481. let n = match op {
  4482. "fma_f16" | "mad_u16" | "mad_i16" => 3,
  4483. "add_f16" | "mul_f16" | "min_f16" | "max_f16" | "add_u16" | "sub_u16" | "add_i16"
  4484. | "sub_i16" | "mul_lo_u16" | "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16"
  4485. | "max_u16" | "min_u16" | "max_i16" | "min_i16" => 2,
  4486. _ => return Err("a packed 16-bit operation"),
  4487. };
  4488. if v.omod != 0 || !float && (v.clamp || v.neg != 0 || v.neg_hi != 0) {
  4489. return Err("modifiers on a packed integer operation");
  4490. }
  4491. let c = self.cur;
  4492. let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
  4493. let mut halves = Vec::new();
  4494. for high in [false, true] {
  4495. let mut xs = Vec::new();
  4496. for k in 0..n {
  4497. let h = self.packed_src(inst, k, high)?;
  4498. if float {
  4499. let mut f = self
  4500. .s
  4501. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
  4502. let neg = if high { v.neg_hi } else { v.neg };
  4503. if neg >> k & 1 != 0 {
  4504. let z = self.s.m.f32(0x8000_0000);
  4505. f = self.s.m.bin(c, Bin::Sub, z, f);
  4506. }
  4507. xs.push(f);
  4508. } else {
  4509. xs.push(h);
  4510. }
  4511. }
  4512. let r = if float {
  4513. let mut f = match op {
  4514. "add_f16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
  4515. "mul_f16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
  4516. "min_f16" => self.binary(36, xs[0], xs[1]),
  4517. "max_f16" => self.binary(35, xs[0], xs[1]),
  4518. // shortcut: FMad in f32, as v_fma_f16.
  4519. _ => self.fmad(xs[0], xs[1], xs[2]),
  4520. };
  4521. if v.clamp {
  4522. f = self.unary(7, f);
  4523. }
  4524. self.s
  4525. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
  4526. } else {
  4527. let k16 = self.s.m.i32(16);
  4528. let sext = |l: &mut Self, x: V| {
  4529. let t = l.s.m.bin(c, Bin::Shl, x, k16);
  4530. l.s.m.bin(c, Bin::AShr, t, k16)
  4531. };
  4532. if op.ends_with("_i16") {
  4533. for x in &mut xs {
  4534. *x = sext(self, *x);
  4535. }
  4536. }
  4537. let k15 = self.s.m.i32(15);
  4538. match op {
  4539. "add_u16" | "add_i16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
  4540. "sub_u16" | "sub_i16" => self.s.m.bin(c, Bin::Sub, xs[0], xs[1]),
  4541. "mul_lo_u16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
  4542. "mad_u16" | "mad_i16" => {
  4543. let m = self.s.m.bin(c, Bin::Mul, xs[0], xs[1]);
  4544. self.s.m.bin(c, Bin::Add, m, xs[2])
  4545. }
  4546. "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16" => {
  4547. let sh = self.s.m.bin(c, Bin::And, xs[0], k15);
  4548. let o = match op {
  4549. "lshlrev_b16" => Bin::Shl,
  4550. "lshrrev_b16" => Bin::LShr,
  4551. _ => Bin::AShr,
  4552. };
  4553. let x = if op == "ashrrev_i16" {
  4554. sext(self, xs[1])
  4555. } else {
  4556. xs[1]
  4557. };
  4558. self.s.m.bin(c, o, x, sh)
  4559. }
  4560. _ => {
  4561. let p = match op {
  4562. "max_u16" => pred::IUGT,
  4563. "min_u16" => pred::IULT,
  4564. "max_i16" => pred::SGT,
  4565. _ => pred::SLT,
  4566. };
  4567. let t = self.s.m.cmp(c, p, xs[0], xs[1]);
  4568. self.s.m.select(c, t, xs[0], xs[1])
  4569. }
  4570. }
  4571. };
  4572. let m = self.s.m.i32(0xFFFF);
  4573. halves.push(self.s.m.bin(c, Bin::And, r, m));
  4574. }
  4575. let k16 = self.s.m.i32(16);
  4576. let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16);
  4577. let r = self.s.m.bin(c, Bin::Or, halves[0], hi);
  4578. let Some(Operand::Vector { reg, .. }) = v.dst else {
  4579. return Err("a packed result outside a VGPR");
  4580. };
  4581. self.write(inst, Reg::V(reg), r, guard);
  4582. Ok(())
  4583. }
  4584. fn integer(&mut self, inst: &Inst, name: &'static str) -> Result<V, Why> {
  4585. let c = self.cur;
  4586. let s = |l: &mut Self, k| l.src(inst, k);
  4587. let k = |l: &mut Self, x: u32| l.s.m.i32(x);
  4588. let m31 = |l: &mut Self, x: V| {
  4589. let k31 = l.s.m.i32(31);
  4590. l.s.m.bin(c, Bin::And, x, k31)
  4591. };
  4592. Ok(match name {
  4593. "v_and_b32" | "v_or_b32" | "v_xor_b32" | "v_add_nc_u32" | "v_sub_nc_u32"
  4594. | "v_subrev_nc_u32" | "v_mul_lo_u32" => {
  4595. let (a, b) = (s(self, 0)?, s(self, 1)?);
  4596. let (op, a, b) = match name {
  4597. "v_and_b32" => (Bin::And, a, b),
  4598. "v_or_b32" => (Bin::Or, a, b),
  4599. "v_xor_b32" => (Bin::Xor, a, b),
  4600. "v_add_nc_u32" => (Bin::Add, a, b),
  4601. "v_sub_nc_u32" => (Bin::Sub, a, b),
  4602. "v_subrev_nc_u32" => (Bin::Sub, b, a),
  4603. _ => (Bin::Mul, a, b),
  4604. };
  4605. self.s.m.bin(c, op, a, b)
  4606. }
  4607. "v_xnor_b32" => {
  4608. let (a, b) = (s(self, 0)?, s(self, 1)?);
  4609. let x = self.s.m.bin(c, Bin::Xor, a, b);
  4610. let ones = k(self, u32::MAX);
  4611. self.s.m.bin(c, Bin::Xor, x, ones)
  4612. }
  4613. "v_not_b32" => {
  4614. let a = s(self, 0)?;
  4615. let ones = k(self, u32::MAX);
  4616. self.s.m.bin(c, Bin::Xor, a, ones)
  4617. }
  4618. "v_lshlrev_b32" | "v_lshrrev_b32" | "v_ashrrev_i32" => {
  4619. let (sh, a) = (s(self, 0)?, s(self, 1)?);
  4620. let sh = m31(self, sh);
  4621. let op = match name {
  4622. "v_lshlrev_b32" => Bin::Shl,
  4623. "v_lshrrev_b32" => Bin::LShr,
  4624. _ => Bin::AShr,
  4625. };
  4626. self.s.m.bin(c, op, a, sh)
  4627. }
  4628. "v_lshl_add_u32" | "v_lshl_or_b32" | "v_add_lshl_u32" | "v_and_or_b32"
  4629. | "v_or3_b32" | "v_xad_u32" | "v_add3_u32" | "v_xor3_b32" => {
  4630. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  4631. match name {
  4632. "v_lshl_add_u32" | "v_lshl_or_b32" => {
  4633. let b = m31(self, b);
  4634. let t = self.s.m.bin(c, Bin::Shl, a, b);
  4635. let op = if name == "v_lshl_add_u32" {
  4636. Bin::Add
  4637. } else {
  4638. Bin::Or
  4639. };
  4640. self.s.m.bin(c, op, t, d)
  4641. }
  4642. "v_add_lshl_u32" => {
  4643. let t = self.s.m.bin(c, Bin::Add, a, b);
  4644. let d = m31(self, d);
  4645. self.s.m.bin(c, Bin::Shl, t, d)
  4646. }
  4647. _ => {
  4648. let (o1, o2) = match name {
  4649. "v_and_or_b32" => (Bin::And, Bin::Or),
  4650. "v_or3_b32" => (Bin::Or, Bin::Or),
  4651. "v_xad_u32" => (Bin::Xor, Bin::Add),
  4652. "v_add3_u32" => (Bin::Add, Bin::Add),
  4653. _ => (Bin::Xor, Bin::Xor),
  4654. };
  4655. let t = self.s.m.bin(c, o1, a, b);
  4656. self.s.m.bin(c, o2, t, d)
  4657. }
  4658. }
  4659. }
  4660. "v_mul_u32_u24" | "v_mul_i32_i24" => {
  4661. let (a, b) = (s(self, 0)?, s(self, 1)?);
  4662. let (sh, op) = (
  4663. k(self, 8),
  4664. if name == "v_mul_i32_i24" {
  4665. Bin::AShr
  4666. } else {
  4667. Bin::LShr
  4668. },
  4669. );
  4670. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  4671. let a = self.s.m.bin(c, op, a, sh);
  4672. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  4673. let b = self.s.m.bin(c, op, b, sh);
  4674. self.s.m.bin(c, Bin::Mul, a, b)
  4675. }
  4676. "v_bfe_u32" | "v_bfe_i32" => {
  4677. let (a, off, w) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  4678. let w = m31(self, w);
  4679. self.bfe(a, off, w, name == "v_bfe_i32")
  4680. }
  4681. "v_bfi_b32" => {
  4682. let (m, a, b) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  4683. let ones = k(self, u32::MAX);
  4684. let nm = self.s.m.bin(c, Bin::Xor, m, ones);
  4685. let x = self.s.m.bin(c, Bin::And, m, a);
  4686. let y = self.s.m.bin(c, Bin::And, nm, b);
  4687. self.s.m.bin(c, Bin::Or, x, y)
  4688. }
  4689. "v_max_i32" | "v_min_i32" | "v_max_u32" | "v_min_u32" => {
  4690. let (a, b) = (s(self, 0)?, s(self, 1)?);
  4691. let p = match name {
  4692. "v_max_i32" => pred::SGT,
  4693. "v_min_i32" => pred::SLT,
  4694. "v_max_u32" => pred::IUGT,
  4695. _ => pred::IULT,
  4696. };
  4697. let t = self.s.m.cmp(c, p, a, b);
  4698. self.s.m.select(c, t, a, b)
  4699. }
  4700. "v_mul_hi_u32" | "v_mul_hi_i32" => {
  4701. let (a, b) = (s(self, 0)?, s(self, 1)?);
  4702. self.mul_hi(a, b, name == "v_mul_hi_i32")
  4703. }
  4704. "v_alignbit_b32" | "v_alignbyte_b32" => {
  4705. // The low dword of {a, b} >> shift.
  4706. let (a, b, sh) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  4707. let sh = if name == "v_alignbyte_b32" {
  4708. let three = k(self, 3);
  4709. let t = self.s.m.bin(c, Bin::And, sh, three);
  4710. let k3 = k(self, 3);
  4711. self.s.m.bin(c, Bin::Shl, t, k3)
  4712. } else {
  4713. m31(self, sh)
  4714. };
  4715. let k32 = k(self, 32);
  4716. let lo = self.s.m.bin(c, Bin::LShr, b, sh);
  4717. let left = self.s.m.bin(c, Bin::Sub, k32, sh);
  4718. let left = m31(self, left);
  4719. let hi = self.s.m.bin(c, Bin::Shl, a, left);
  4720. let zero = k(self, 0);
  4721. let none = self.s.m.cmp(c, pred::EQ, sh, zero);
  4722. let hi = self.s.m.select(c, none, zero, hi);
  4723. self.s.m.bin(c, Bin::Or, lo, hi)
  4724. }
  4725. "v_bfrev_b32" => {
  4726. let a = s(self, 0)?;
  4727. self.s
  4728. .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a])
  4729. }
  4730. "v_bcnt_u32_b32" => {
  4731. let (a, b) = (s(self, 0)?, s(self, 1)?);
  4732. let n = self
  4733. .s
  4734. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[a]);
  4735. self.s.m.bin(c, Bin::Add, n, b)
  4736. }
  4737. "v_mad_u32_u24" | "v_mad_i32_i24" => {
  4738. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  4739. let (sh, op) = (
  4740. k(self, 8),
  4741. if name == "v_mad_i32_i24" {
  4742. Bin::AShr
  4743. } else {
  4744. Bin::LShr
  4745. },
  4746. );
  4747. let a = self.s.m.bin(c, Bin::Shl, a, sh);
  4748. let a = self.s.m.bin(c, op, a, sh);
  4749. let b = self.s.m.bin(c, Bin::Shl, b, sh);
  4750. let b = self.s.m.bin(c, op, b, sh);
  4751. let m = self.s.m.bin(c, Bin::Mul, a, b);
  4752. self.s.m.bin(c, Bin::Add, m, d)
  4753. }
  4754. "v_min3_i32" | "v_max3_i32" | "v_min3_u32" | "v_max3_u32" | "v_med3_i32"
  4755. | "v_med3_u32" => {
  4756. let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  4757. let signed = name.ends_with("i32");
  4758. let (lt, gt) = if signed {
  4759. (pred::SLT, pred::SGT)
  4760. } else {
  4761. (pred::IULT, pred::IUGT)
  4762. };
  4763. let pick = |l: &mut Self, p, x, y| {
  4764. let t = l.s.m.cmp(c, p, x, y);
  4765. l.s.m.select(c, t, x, y)
  4766. };
  4767. match &name[2..6] {
  4768. "min3" => {
  4769. let t = pick(self, lt, a, b);
  4770. pick(self, lt, t, d)
  4771. }
  4772. "max3" => {
  4773. let t = pick(self, gt, a, b);
  4774. pick(self, gt, t, d)
  4775. }
  4776. _ => {
  4777. let lo = pick(self, lt, a, b);
  4778. let hi = pick(self, gt, a, b);
  4779. let t = pick(self, lt, hi, d);
  4780. pick(self, gt, lo, t)
  4781. }
  4782. }
  4783. }
  4784. "v_perm_b32" => {
  4785. // Byte i of the result is byte S of {src0, src1} (src1 the
  4786. // low dword) for selector byte S below 8; 8-11 repeat the
  4787. // sign of bytes 1 and 3 of src1, then of src0; 12 is 0x00,
  4788. // higher 0xFF.
  4789. let Fields::Valu(v) = &inst.fields else {
  4790. unreachable!()
  4791. };
  4792. let sel = match v.src.get(2) {
  4793. Some(&Operand::Literal(x)) => x,
  4794. Some(&Operand::Const(k)) => crate::resource::inline(k).ok_or(name)?,
  4795. _ => {
  4796. // A computed selector: each byte picked at run time.
  4797. let (a, b, sv) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
  4798. let mut r = k(self, 0);
  4799. for i in 0..4u32 {
  4800. let (sh, ff) = (k(self, 8 * i), k(self, 0xFF));
  4801. let sel = self.s.m.bin(c, Bin::LShr, sv, sh);
  4802. let sel = self.s.m.bin(c, Bin::And, sel, ff);
  4803. // Select a dword and a byte within it.
  4804. // Later selects handle codes 8 and above.
  4805. let four = k(self, 4);
  4806. let zero = k(self, 0);
  4807. let high = self.s.m.bin(c, Bin::And, sel, four);
  4808. let high = self.s.m.cmp(c, pred::NE, high, zero);
  4809. let word = self.s.m.select(c, high, a, b);
  4810. let three = k(self, 3);
  4811. let index = self.s.m.bin(c, Bin::And, sel, three);
  4812. let bits = self.s.m.bin(c, Bin::Shl, index, three);
  4813. let x = self.s.m.bin(c, Bin::LShr, word, bits);
  4814. let mut byte = self.s.m.bin(c, Bin::And, x, ff);
  4815. // 8-11: the sign of bytes 1, 3 of src1, then of src0.
  4816. for (n, src, bit) in [(8, b, 15), (9, b, 31), (10, a, 15), (11, a, 31)]
  4817. {
  4818. let left = k(self, 31 - bit);
  4819. let t = self.s.m.bin(c, Bin::Shl, src, left);
  4820. let k31 = k(self, 31);
  4821. let t = self.s.m.bin(c, Bin::AShr, t, k31);
  4822. let t = self.s.m.bin(c, Bin::And, t, ff);
  4823. let kn = k(self, n);
  4824. let is = self.s.m.cmp(c, pred::EQ, sel, kn);
  4825. byte = self.s.m.select(c, is, t, byte);
  4826. }
  4827. let (k12, z) = (k(self, 12), k(self, 0));
  4828. let is12 = self.s.m.cmp(c, pred::EQ, sel, k12);
  4829. byte = self.s.m.select(c, is12, z, byte);
  4830. let above = self.s.m.cmp(c, pred::IUGT, sel, k12);
  4831. byte = self.s.m.select(c, above, ff, byte);
  4832. let at = k(self, 8 * i);
  4833. let byte = self.s.m.bin(c, Bin::Shl, byte, at);
  4834. r = self.s.m.bin(c, Bin::Or, r, byte);
  4835. }
  4836. return Ok(r);
  4837. }
  4838. };
  4839. let (a, b) = (s(self, 0)?, s(self, 1)?);
  4840. let mut r = k(self, 0);
  4841. for i in 0..4 {
  4842. let pick = sel >> (8 * i) & 0xFF;
  4843. let byte = match pick {
  4844. 0..=7 => {
  4845. let (src, n) = if pick < 4 { (b, pick) } else { (a, pick - 4) };
  4846. let sh = k(self, 8 * n);
  4847. let t = self.s.m.bin(c, Bin::LShr, src, sh);
  4848. let ff = k(self, 0xFF);
  4849. self.s.m.bin(c, Bin::And, t, ff)
  4850. }
  4851. 8..=11 => {
  4852. let src = if pick < 10 { b } else { a };
  4853. let bit = if pick % 2 == 0 { 15 } else { 31 };
  4854. let left = k(self, 31 - bit);
  4855. let t = self.s.m.bin(c, Bin::Shl, src, left);
  4856. let k31 = k(self, 31);
  4857. let t = self.s.m.bin(c, Bin::AShr, t, k31);
  4858. let ff = k(self, 0xFF);
  4859. self.s.m.bin(c, Bin::And, t, ff)
  4860. }
  4861. 12 => continue,
  4862. _ => k(self, 0xFF),
  4863. };
  4864. let at = k(self, 8 * i);
  4865. let byte = self.s.m.bin(c, Bin::Shl, byte, at);
  4866. r = self.s.m.bin(c, Bin::Or, r, byte);
  4867. }
  4868. r
  4869. }
  4870. "v_bfm_b32" => {
  4871. // ((1 << src0[4:0]) - 1) << src1[4:0]
  4872. let (a, b) = (s(self, 0)?, s(self, 1)?);
  4873. let one = k(self, 1);
  4874. let (a, b) = (m31(self, a), m31(self, b));
  4875. let m = self.s.m.bin(c, Bin::Shl, one, a);
  4876. let m = self.s.m.bin(c, Bin::Sub, m, one);
  4877. self.s.m.bin(c, Bin::Shl, m, b)
  4878. }
  4879. "v_cvt_pk_u8_f32" => {
  4880. // src0 rounded to nearest even and saturated to a byte, into
  4881. // byte src1[1:0] of src2.
  4882. let f = self.fsrc(inst, 0)?;
  4883. let (b, d) = (s(self, 1)?, s(self, 2)?);
  4884. let f = self.unary(26, f);
  4885. let (zero, max) = (self.s.m.f32(0), self.s.m.f32(255.0f32.to_bits()));
  4886. let f = self.binary(35, f, zero);
  4887. let f = self.binary(36, f, max);
  4888. let x = self.s.m.cast(c, Cast::FpToUi, f, self.s.t.i32);
  4889. let (three, k3) = (k(self, 3), k(self, 3));
  4890. let sh = self.s.m.bin(c, Bin::And, b, three);
  4891. let sh = self.s.m.bin(c, Bin::Shl, sh, k3);
  4892. let x = self.s.m.bin(c, Bin::Shl, x, sh);
  4893. let ff = k(self, 0xFF);
  4894. let hole = self.s.m.bin(c, Bin::Shl, ff, sh);
  4895. let ones = k(self, u32::MAX);
  4896. let hole = self.s.m.bin(c, Bin::Xor, hole, ones);
  4897. let d = self.s.m.bin(c, Bin::And, d, hole);
  4898. self.s.m.bin(c, Bin::Or, d, x)
  4899. }
  4900. "v_ffbl_b32" => {
  4901. // -1 for zero, as DXIL's first-bit-low.
  4902. let a = s(self, 0)?;
  4903. self.s
  4904. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 32, &[a])
  4905. }
  4906. "v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32" => {
  4907. // Bits of the mask's low (high) half below this lane, plus src1:
  4908. // with an all-ones mask, the lane index.
  4909. let (a, b) = (s(self, 0)?, s(self, 1)?);
  4910. // Mesh lanes are the console's by construction; pixel and
  4911. // vertex lanes are the host's, as their masks are.
  4912. if self.mask_data == MaskData::Host {
  4913. // Host lanes: the mask must be one (a ballot) or all lanes.
  4914. let Fields::Valu(v) = &inst.fields else {
  4915. unreachable!()
  4916. };
  4917. let host = match v.src.first() {
  4918. Some(&Operand::Const(193)) => true,
  4919. Some(&Operand::Scalar { code, .. }) => {
  4920. inst.read(Reg::S(code)).is_some_and(|m| {
  4921. self.x.st.masks.contains_key(&m) || self.x.st.highs.contains_key(&m)
  4922. })
  4923. }
  4924. _ => false,
  4925. };
  4926. if !host {
  4927. return Err("v_mbcnt of a mask that is no ballot (console lane layout)");
  4928. }
  4929. self.s.flags |= flags::WAVE_OPS;
  4930. } else if self.s.mesh.is_none() {
  4931. self.cross_lane(false)?;
  4932. }
  4933. let lane = self.lane_index();
  4934. let below = if name == "v_mbcnt_lo_u32_b32" {
  4935. lane
  4936. } else {
  4937. let (k32, z) = (k(self, 32), k(self, 0));
  4938. let t = self.s.m.bin(c, Bin::Sub, lane, k32);
  4939. let low = self.s.m.cmp(c, pred::IULT, lane, k32);
  4940. self.s.m.select(c, low, z, t)
  4941. };
  4942. // (1 << below) - 1, all ones from 32 on.
  4943. let (one, k32, ones) = (k(self, 1), k(self, 32), k(self, u32::MAX));
  4944. let sh = m31(self, below);
  4945. let m = self.s.m.bin(c, Bin::Shl, one, sh);
  4946. let m = self.s.m.bin(c, Bin::Sub, m, one);
  4947. let full = self.s.m.cmp(c, pred::IUGE, below, k32);
  4948. let m = self.s.m.select(c, full, ones, m);
  4949. let x = self.s.m.bin(c, Bin::And, a, m);
  4950. let n = self
  4951. .s
  4952. .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[x]);
  4953. self.s.m.bin(c, Bin::Add, n, b)
  4954. }
  4955. _ => return Err(name),
  4956. })
  4957. }
  4958. fn compare(&mut self, inst: &Inst, rest: &str) -> Result<(), Why> {
  4959. let (op, ty) = rest.rsplit_once('_').ok_or("a compare")?;
  4960. let c = self.cur;
  4961. let r = match ty {
  4962. "f32" | "f16" if op == "class" => {
  4963. // Bit k of src1 tests class k: signalling NaN, quiet NaN,
  4964. // -inf, -normal, -denormal, -0, +0, +denormal, +normal, +inf.
  4965. let f16 = ty == "f16";
  4966. let x = if f16 {
  4967. let Fields::Valu(v) = &inst.fields else {
  4968. unreachable!()
  4969. };
  4970. let mut h = self.half_src(inst, 0)?;
  4971. if v.abs & 1 != 0 {
  4972. let m = self.s.m.i32(0x7FFF);
  4973. h = self.s.m.bin(c, Bin::And, h, m);
  4974. }
  4975. if v.neg & 1 != 0 {
  4976. let s = self.s.m.i32(0x8000);
  4977. h = self.s.m.bin(c, Bin::Xor, h, s);
  4978. }
  4979. h
  4980. } else {
  4981. let x = self.fsrc(inst, 0)?;
  4982. self.as_int(x)
  4983. };
  4984. let mask = self.src(inst, 1)?;
  4985. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  4986. let (exp_sh, sign_sh, exp_mask, mant_mask, quiet_bit) = if f16 {
  4987. (10, 15, 0x1F, 0x03FF, 0x0200)
  4988. } else {
  4989. (23, 31, 0xFF, 0x7F_FFFF, 0x40_0000)
  4990. };
  4991. let (k_exp, k_sign, k_emax, mant, quiet) = (
  4992. k(self, exp_sh),
  4993. k(self, sign_sh),
  4994. k(self, exp_mask),
  4995. k(self, mant_mask),
  4996. k(self, quiet_bit),
  4997. );
  4998. let e = self.s.m.bin(c, Bin::LShr, x, k_exp);
  4999. let e = self.s.m.bin(c, Bin::And, e, k_emax);
  5000. let m = self.s.m.bin(c, Bin::And, x, mant);
  5001. let neg = self.s.m.bin(c, Bin::LShr, x, k_sign);
  5002. let zero = k(self, 0);
  5003. let (e0, emax) = (
  5004. self.s.m.cmp(c, pred::EQ, e, zero),
  5005. self.s.m.cmp(c, pred::EQ, e, k_emax),
  5006. );
  5007. let m0 = self.s.m.cmp(c, pred::EQ, m, zero);
  5008. let q = self.s.m.bin(c, Bin::And, x, quiet);
  5009. let q = self.s.m.cmp(c, pred::NE, q, zero);
  5010. // Positive classes 6-9; negative ones are 11 minus those.
  5011. let (normal, inf, zero_c, denorm) =
  5012. (k(self, 8), k(self, 9), k(self, 6), k(self, 7));
  5013. let t = self.s.m.select(c, m0, zero_c, denorm);
  5014. let t = self.s.m.select(c, e0, t, normal);
  5015. let t = self.s.m.select(c, emax, inf, t);
  5016. let eleven = k(self, 11);
  5017. let mirrored = self.s.m.bin(c, Bin::Sub, eleven, t);
  5018. let is_neg = self.s.m.cmp(c, pred::NE, neg, zero);
  5019. let t = self.s.m.select(c, is_neg, mirrored, t);
  5020. let (one, snan) = (k(self, 1), k(self, 0));
  5021. let nan_class = self.s.m.select(c, q, one, snan);
  5022. let yes = self.s.m.bool(true);
  5023. let nan = self.s.m.bin(c, Bin::Xor, m0, yes);
  5024. let nan = self.s.m.bin(c, Bin::And, nan, emax);
  5025. let t = self.s.m.select(c, nan, nan_class, t);
  5026. let bit = self.s.m.bin(c, Bin::LShr, mask, t);
  5027. let bit = self.s.m.bin(c, Bin::And, bit, one);
  5028. self.s.m.cmp(c, pred::NE, bit, zero)
  5029. }
  5030. "f32" | "f16" => {
  5031. let (a, b) = if ty == "f16" {
  5032. (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?)
  5033. } else {
  5034. (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?)
  5035. };
  5036. let p = match op {
  5037. "f" => pred::FALSE,
  5038. "lt" => pred::OLT,
  5039. "eq" => pred::OEQ,
  5040. "le" => pred::OLE,
  5041. "gt" => pred::OGT,
  5042. "lg" => pred::ONE,
  5043. "ge" => pred::OGE,
  5044. "o" => pred::ORD,
  5045. "u" => pred::UNO,
  5046. "nge" => pred::ULT,
  5047. "nlg" => pred::UEQ,
  5048. "ngt" => pred::ULE,
  5049. "nle" => pred::UGT,
  5050. "neq" => pred::UNE,
  5051. "nlt" => pred::UGE,
  5052. "tru" => pred::TRUE,
  5053. _ => return Err(inst.name()),
  5054. };
  5055. self.s.m.cmp(c, p, a, b)
  5056. }
  5057. "u64" | "i64" => {
  5058. let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?);
  5059. let signed = ty == "i64";
  5060. let p = match op {
  5061. "eq" => pred::EQ,
  5062. "ne" | "lg" => pred::NE,
  5063. "lt" if signed => pred::SLT,
  5064. "le" if signed => pred::SLE,
  5065. "gt" if signed => pred::SGT,
  5066. "ge" if signed => pred::SGE,
  5067. "lt" => pred::IULT,
  5068. "le" => pred::IULE,
  5069. "gt" => pred::IUGT,
  5070. "ge" => pred::IUGE,
  5071. _ => return Err("a 64-bit compare"),
  5072. };
  5073. self.s.m.cmp(c, p, a, b)
  5074. }
  5075. "u32" | "i32" | "u16" | "i16" => {
  5076. let (a, b) = if ty.ends_with("16") {
  5077. let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
  5078. if ty == "i16" {
  5079. let k16 = self.s.m.i32(16);
  5080. for x in [&mut a, &mut b] {
  5081. let t = self.s.m.bin(c, Bin::Shl, *x, k16);
  5082. *x = self.s.m.bin(c, Bin::AShr, t, k16);
  5083. }
  5084. }
  5085. (a, b)
  5086. } else {
  5087. (self.src(inst, 0)?, self.src(inst, 1)?)
  5088. };
  5089. let signed = ty == "i32" || ty == "i16";
  5090. let p = match op {
  5091. "eq" => pred::EQ,
  5092. "ne" | "lg" => pred::NE,
  5093. "lt" if signed => pred::SLT,
  5094. "le" if signed => pred::SLE,
  5095. "gt" if signed => pred::SGT,
  5096. "ge" if signed => pred::SGE,
  5097. "lt" => pred::IULT,
  5098. "le" => pred::IULE,
  5099. "gt" => pred::IUGT,
  5100. "ge" => pred::IUGE,
  5101. "f" | "t" => {
  5102. self.lane(inst, Some(op == "t"));
  5103. return Ok(());
  5104. }
  5105. _ => return Err("an integer compare"),
  5106. };
  5107. self.s.m.cmp(c, p, a, b)
  5108. }
  5109. _ => return Err(inst.name()),
  5110. };
  5111. self.lane_bits_for(inst, r);
  5112. Ok(())
  5113. }
  5114. fn lane(&mut self, inst: &Inst, value: Option<bool>) {
  5115. let b = self.s.m.bool(value == Some(true));
  5116. self.lane_bits_for(inst, b);
  5117. }
  5118. fn lane_bits_for(&mut self, inst: &Inst, r: V) {
  5119. let Fields::Valu(v) = &inst.fields else {
  5120. return;
  5121. };
  5122. let code = if inst.name().starts_with("v_cmpx") {
  5123. Some(EXEC)
  5124. } else {
  5125. match v.dst {
  5126. Some(Operand::Scalar { code, .. }) => Some(code),
  5127. _ => None,
  5128. }
  5129. };
  5130. if let Some(lo) = code.and_then(|c| inst.write(Reg::S(c))) {
  5131. self.lane_bits.insert(lo, r);
  5132. }
  5133. for &(_, w) in &inst.writes {
  5134. self.vals
  5135. .entry(w)
  5136. .or_insert(Val::Missing("a lane mask read as data"));
  5137. }
  5138. }
  5139. fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
  5140. let Some(&interp) = self.interps.get(&site) else {
  5141. return Err("the first half of an interpolation");
  5142. };
  5143. let (attribute, mode) = match interp {
  5144. Interp::Interpolated {
  5145. attribute,
  5146. barycentric,
  5147. ..
  5148. } => (
  5149. attribute,
  5150. match barycentric {
  5151. Barycentric::PerspectiveCenter => 2,
  5152. Barycentric::PerspectiveCentroid => 3,
  5153. Barycentric::PerspectiveSample => 6,
  5154. Barycentric::LinearCenter => 4,
  5155. Barycentric::LinearCentroid => 5,
  5156. Barycentric::LinearSample => 7,
  5157. Barycentric::PerspectivePullModel => return Err("pull-model interpolation"),
  5158. },
  5159. ),
  5160. // P0, the provoking vertex: a flat (nointerpolation) input.
  5161. Interp::Vertex {
  5162. attribute,
  5163. vertex: 2,
  5164. } => (attribute, 1),
  5165. Interp::Vertex { .. } => return Err("a non-provoking vertex value"),
  5166. };
  5167. let dst = match &inst.fields {
  5168. Fields::Vintrp { dst, .. } => *dst,
  5169. Fields::Valu(v) => v.dst.ok_or("an interpolation")?,
  5170. _ => unreachable!(),
  5171. };
  5172. let Operand::Vector { reg, .. } = dst else {
  5173. return Err("an interpolation");
  5174. };
  5175. // A channel of an input element, interpolated as `mode` says.
  5176. let channel = |l: &mut Self, row: u8, ch: u8| -> Result<V, Why> {
  5177. let (id, col) = l
  5178. .find_input(row, ch)
  5179. .ok_or("an input the signature lacks")?;
  5180. let e = &mut l.s.inputs[id];
  5181. if e.interp != mode && e.usage != 0 {
  5182. return Err("one input interpolated two ways");
  5183. }
  5184. e.interp = mode;
  5185. match l.load_any_input(id, col) {
  5186. Val::I32(x) => Ok(x),
  5187. _ => Err("an input"),
  5188. }
  5189. };
  5190. let packing = match &self.x.native.io {
  5191. StageIo::Ps { inputs, .. } => inputs
  5192. .iter()
  5193. .find(|i| i.row == attribute.row && i.fp16)
  5194. .map(|i| (i.pack2, (i.row2 != i.row).then_some(i.row2))),
  5195. _ => None,
  5196. };
  5197. let f16 = inst.name().ends_with("_f16");
  5198. let x = match packing {
  5199. None if f16 || attribute.high => return Err("a 16-bit read of a 32-bit input"),
  5200. None => channel(self, attribute.row, attribute.channel)?,
  5201. Some((pack2, b)) => {
  5202. // 16-bit values: one in the low half of each dword, or two
  5203. // per dword (`packed_half`); the host's are 32-bit floats.
  5204. let half = |l: &mut Self, h: u8| -> Result<Option<V>, Why> {
  5205. let src = if pack2 {
  5206. packed_half(&l.s.inputs, attribute.row, b, h)
  5207. } else {
  5208. h.is_multiple_of(2).then_some((attribute.row, h / 2))
  5209. };
  5210. let Some((row, ch)) = src else {
  5211. return Ok(None);
  5212. };
  5213. let x = channel(l, row, ch)?;
  5214. let f = l.as_float(x);
  5215. let i32t = l.s.t.i32;
  5216. Ok(Some(l.s.op(
  5217. l.cur,
  5218. "legacyF32ToF16",
  5219. Attr::ReadNone,
  5220. i32t,
  5221. 130,
  5222. &[f],
  5223. )))
  5224. };
  5225. let h = 2 * attribute.channel;
  5226. let c = self.cur;
  5227. if f16 {
  5228. let lo = half(self, h + u8::from(attribute.high))?
  5229. .ok_or("a packed input half no element holds")?;
  5230. self.low_half(inst, reg, lo)
  5231. } else if mode == 1 {
  5232. // The whole dword of a flat input: both halves.
  5233. let z = self.s.m.i32(0);
  5234. let lo = half(self, h)?.unwrap_or(z);
  5235. let hi = half(self, h + 1)?.unwrap_or(z);
  5236. let k16 = self.s.m.i32(16);
  5237. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  5238. self.s.m.bin(c, Bin::Or, lo, hi)
  5239. } else {
  5240. return Err("32-bit interpolation of a 16-bit input");
  5241. }
  5242. }
  5243. };
  5244. // A pixel interpolates in every lane; guards only hide inactive ones.
  5245. self.write(inst, Reg::V(reg), x, None);
  5246. Ok(())
  5247. }
  5248. /// `x` (an f16 in the low bits) as the low half of VGPR `reg`: 16-bit
  5249. /// results keep the register's high half (GFX10).
  5250. fn low_half(&mut self, inst: &Inst, reg: u8, x: V) -> V {
  5251. let c = self.cur;
  5252. let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) {
  5253. Some(Ok(o)) => o,
  5254. _ => self.s.m.i32(0),
  5255. };
  5256. let (high, low) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF));
  5257. let old = self.s.m.bin(c, Bin::And, old, high);
  5258. let x = self.s.m.bin(c, Bin::And, x, low);
  5259. self.s.m.bin(c, Bin::Or, old, x)
  5260. }
  5261. fn image(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  5262. let Fields::Image {
  5263. data,
  5264. addr,
  5265. dmask,
  5266. dim,
  5267. unorm,
  5268. a16,
  5269. d16,
  5270. tfe,
  5271. lwe,
  5272. ..
  5273. } = &inst.fields
  5274. else {
  5275. unreachable!()
  5276. };
  5277. if *tfe || *lwe {
  5278. return Err("an image access with tfe or lwe");
  5279. }
  5280. let name = inst.name();
  5281. if *a16 && name.starts_with("image_sample_b") {
  5282. return Err("a biased image sample with 16-bit coordinates");
  5283. }
  5284. // A load or sample with no channel enabled returns the first.
  5285. let dmask = if *dmask == 0 { &1 } else { dmask };
  5286. let site = (b, i);
  5287. let guard = self.guard(b, i)?;
  5288. let c = self.cur;
  5289. let (kind, coords) = match dim {
  5290. 0 => (1, 1),
  5291. 1 => (2, 2),
  5292. 2 => (4, 3),
  5293. // Sampled (face coordinates and face, see `cube_direction`) or
  5294. // sized only.
  5295. 3 if name.starts_with("image_sample")
  5296. || name.starts_with("image_gather")
  5297. || name == "image_get_resinfo" =>
  5298. {
  5299. (5, 3)
  5300. }
  5301. 4 => (6, 2),
  5302. 5 => (7, 3),
  5303. _ => return Err("an image dimension (cube loads or MSAA)"),
  5304. };
  5305. // Address VGPRs in order.
  5306. let mut regs = Vec::new();
  5307. for a in addr {
  5308. if let Operand::Vector { reg, dwords } = *a {
  5309. regs.extend((0..dwords).map(|k| reg + k));
  5310. }
  5311. }
  5312. // With a16, two 16-bit components per VGPR, low half first.
  5313. let addr_val = |l: &mut Self, k: usize| -> Result<V, Why> {
  5314. let r = *regs
  5315. .get(if *a16 { k / 2 } else { k })
  5316. .ok_or("an image address")?;
  5317. let v = inst.read(Reg::V(r)).ok_or("an image address")?;
  5318. let x = l.i32_of(v)?;
  5319. if !*a16 {
  5320. return Ok(x);
  5321. }
  5322. let c = l.cur;
  5323. let (sh, mask) = (l.s.m.i32(16 * (k as u32 % 2)), l.s.m.i32(0xFFFF));
  5324. let x = l.s.m.bin(c, Bin::LShr, x, sh);
  5325. Ok(l.s.m.bin(c, Bin::And, x, mask))
  5326. };
  5327. let src = self
  5328. .descriptors
  5329. .get(&(site, false))
  5330. .copied()
  5331. .ok_or("an untracked image")?;
  5332. let store = name.starts_with("image_store");
  5333. let uav = store
  5334. || self
  5335. .used_kind(src)
  5336. .is_some_and(|u| u.kind == ResourceType::Uav);
  5337. let props = (kind | if uav { 0x1000 } else { 0 }, 0x409);
  5338. if let Some(op) = name.strip_prefix("image_atomic_") {
  5339. // DXIL's atomic operations on a 32-bit integer texture UAV; the
  5340. // old value returns with glc. Sub is the add of the negation.
  5341. let code = match op {
  5342. "add" | "sub" => 0,
  5343. "and" => 1,
  5344. "or" => 2,
  5345. "xor" => 3,
  5346. "smin" => 4,
  5347. "smax" => 5,
  5348. "umin" => 6,
  5349. "umax" => 7,
  5350. "swap" => 8,
  5351. "cmpswap" => u32::MAX,
  5352. _ => return Err(name),
  5353. };
  5354. let Fields::Image { cache, .. } = &inst.fields else {
  5355. unreachable!()
  5356. };
  5357. if *d16 || *a16 {
  5358. return Err("a 16-bit image atomic");
  5359. }
  5360. // dmask: the data dwords (cmpswap: twice the value's).
  5361. // shortcut: 64-bit image atomics (two dwords, an R32G32 view)
  5362. // need the host's 64-bit typed atomics; they stop the program.
  5363. if *dmask != if code == u32::MAX { 3 } else { 1 } {
  5364. return Err("a 64-bit image atomic");
  5365. }
  5366. let iu = self.s.m.undef(self.s.t.i32);
  5367. let mut cs = vec![iu; 3];
  5368. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  5369. *slot = addr_val(self, k)?;
  5370. }
  5371. let Operand::Vector { reg, .. } = *data else {
  5372. return Err("image atomic data");
  5373. };
  5374. let vals = self.vgprs(inst, data, if code == u32::MAX { 2 } else { 1 })?;
  5375. let mut value = vals[0];
  5376. if op == "sub" {
  5377. let z = self.s.m.i32(0);
  5378. value = self.s.m.bin(c, Bin::Sub, z, value);
  5379. }
  5380. let old = match inst.read(Reg::V(reg)) {
  5381. Some(v) if cache.glc => self.i32_of(v)?,
  5382. _ => self.s.m.i32(0),
  5383. };
  5384. let h = self.handle(site, src, false, (kind | 0x1000, 0x105))?;
  5385. let at = self.begin_guarded(guard);
  5386. let i32t = self.s.t.i32;
  5387. let mut args = vec![h];
  5388. let r = if code == u32::MAX {
  5389. // cmpswap: data is (new, compare).
  5390. args.extend(cs);
  5391. args.extend([vals[1], vals[0]]);
  5392. self.s.op(
  5393. self.cur,
  5394. "atomicCompareExchange.i32",
  5395. Attr::NoUnwind,
  5396. i32t,
  5397. 79,
  5398. &args,
  5399. )
  5400. } else {
  5401. args.push(self.s.m.i32(code));
  5402. args.extend(cs);
  5403. args.push(value);
  5404. self.s
  5405. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args)
  5406. };
  5407. let r = self.end_guarded(at, &[(r, old)])[0];
  5408. if cache.glc {
  5409. self.write(inst, Reg::V(reg), r, None);
  5410. }
  5411. return Ok(());
  5412. }
  5413. if store {
  5414. if name != "image_store" {
  5415. return Err("an image store to a mip level");
  5416. }
  5417. // shortcut: stores are taken to write all four channels of a
  5418. // float format (the console converts by the view's format).
  5419. if *dmask != 0xF {
  5420. return Err("an image store of some channels");
  5421. }
  5422. let iu = self.s.m.undef(self.s.t.i32);
  5423. let mut cs = vec![iu; 3];
  5424. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  5425. *slot = addr_val(self, k)?;
  5426. }
  5427. let Operand::Vector { reg, .. } = *data else {
  5428. return Err("image store data");
  5429. };
  5430. let mut vals = Vec::new();
  5431. for k in 0..4u8 {
  5432. // d16: two f16 channels per VGPR, low half first.
  5433. let r = if *d16 { k / 2 } else { k };
  5434. let v = inst.read(Reg::V(reg + r)).ok_or("image store data")?;
  5435. vals.push(if *d16 {
  5436. let mut x = self.i32_of(v)?;
  5437. if k % 2 == 1 {
  5438. let k16 = self.s.m.i32(16);
  5439. x = self.s.m.bin(self.cur, Bin::LShr, x, k16);
  5440. }
  5441. let f32t = self.s.t.f32;
  5442. self.s
  5443. .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x])
  5444. } else {
  5445. self.float_of(v)?
  5446. });
  5447. }
  5448. let h = self.handle(site, src, false, props)?;
  5449. let at = self.begin_guarded(guard);
  5450. let mut args = vec![h];
  5451. args.extend(cs);
  5452. args.extend(vals);
  5453. args.push(self.s.m.i8(0xF));
  5454. let void = self.s.t.void;
  5455. self.s.op(
  5456. self.cur,
  5457. "textureStore.f32",
  5458. Attr::NoUnwind,
  5459. void,
  5460. 67,
  5461. &args,
  5462. );
  5463. self.end_guarded(at, &[]);
  5464. return Ok(());
  5465. }
  5466. let (op, sample) = match name {
  5467. "image_sample" => (60, true),
  5468. "image_sample_lz" | "image_sample_l" => (62, true),
  5469. "image_sample_b" => (61, true),
  5470. "image_sample_c_lz" => (65, true),
  5471. "image_sample_d" => (63, true),
  5472. "image_get_lod" if self.s.pixel => (81, true),
  5473. // Implicit derivatives: pixel shaders only.
  5474. "image_sample_c" if self.s.pixel => (64, true),
  5475. "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" => (73, true),
  5476. "image_load" | "image_load_mip" => (66, false),
  5477. "image_get_resinfo" => (72, false),
  5478. _ => return Err(name),
  5479. };
  5480. if op == 72 {
  5481. // Width, height, depth or layers, levels (per dmask) of the level
  5482. // in the first address: DXIL's dimensions; a channel DXIL leaves
  5483. // out reads 1 (UAVs: one level).
  5484. let h = self.handle(site, src, false, props)?;
  5485. let mip = if uav {
  5486. self.s.m.undef(self.s.t.i32)
  5487. } else {
  5488. addr_val(self, 0)?
  5489. };
  5490. let i32t = self.s.t.i32;
  5491. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  5492. let d = self
  5493. .s
  5494. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
  5495. let one = self.s.m.i32(1);
  5496. let present = match kind {
  5497. 1 => [true, false, false, true],
  5498. 2 | 5 | 6 => [true, true, false, true],
  5499. _ => [true, true, true, true],
  5500. };
  5501. let Operand::Vector { reg, .. } = *data else {
  5502. return Err("an image result");
  5503. };
  5504. for (k, ch) in (0..4u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() {
  5505. let x = if ch == 3 && uav || !present[ch as usize] {
  5506. one
  5507. } else {
  5508. self.s.m.extract(c, d, ch)
  5509. };
  5510. self.write(inst, Reg::V(reg + k as u8), x, guard);
  5511. }
  5512. return Ok(());
  5513. }
  5514. if uav && op != 66 {
  5515. return Err("sampling a UAV");
  5516. }
  5517. let h = self.handle(site, src, false, props)?;
  5518. let fu = self.s.m.undef(self.s.t.f32);
  5519. let iu = self.s.m.undef(self.s.t.i32);
  5520. let r = if sample {
  5521. let ss = self
  5522. .descriptors
  5523. .get(&(site, true))
  5524. .copied()
  5525. .ok_or("an untracked sampler")?;
  5526. // Comparison: the reference value is the first address after
  5527. // the bias, and the sampler is a comparison sampler.
  5528. let cmp = matches!(op, 64 | 65);
  5529. if cmp && (*a16 || dmask.count_ones() != 1) {
  5530. return Err("a comparison sample of 16-bit coordinates or several channels");
  5531. }
  5532. let sh = self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?;
  5533. // Texel offsets (`_o`) come first: x in bits 0-5, y in 8-13,
  5534. // signed (programmable offsets: gathers only).
  5535. let offset_word = name.ends_with("_o");
  5536. let first =
  5537. usize::from(offset_word) + usize::from(name == "image_sample_b") + usize::from(cmp);
  5538. // Coordinates the size divides (not the array slice); explicit
  5539. // gradients (x then y) come before the coordinates.
  5540. let spatial = coords - usize::from(kind == 6 || kind == 7);
  5541. let grads = if op == 63 { 2 * spatial } else { 0 };
  5542. let mut cs = vec![fu; 4];
  5543. // With a16, sampling coordinates and LOD are f16.
  5544. let to_float = |l: &mut Self, x: V| {
  5545. if *a16 {
  5546. let f = l.s.t.f32;
  5547. l.s.op(l.cur, "legacyF16ToF32", Attr::ReadNone, f, 131, &[x])
  5548. } else {
  5549. l.as_float(x)
  5550. }
  5551. };
  5552. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  5553. let x = addr_val(self, first + grads + k)?;
  5554. *slot = to_float(self, x);
  5555. }
  5556. if kind == 5 {
  5557. if *unorm || op == 63 || op == 81 {
  5558. return Err("a cube sample with texel coordinates, gradients or a level query");
  5559. }
  5560. let dir = self.cube_direction(cs[0], cs[1], cs[2]);
  5561. cs[..3].copy_from_slice(&dir);
  5562. }
  5563. if *unorm {
  5564. // Texel coordinates: divided by the size of level 0.
  5565. let i32t = self.s.t.i32;
  5566. let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
  5567. let z = self.s.m.i32(0);
  5568. let d = self
  5569. .s
  5570. .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]);
  5571. for (k, slot) in cs.iter_mut().enumerate().take(spatial) {
  5572. let n = self.s.m.extract(c, d, k as u32);
  5573. let n = self.s.m.cast(c, Cast::UiToFp, n, self.s.t.f32);
  5574. *slot = self.s.m.bin(c, Bin::SDiv, *slot, n);
  5575. }
  5576. }
  5577. if op == 81 {
  5578. // The clamped then the unclamped level of detail.
  5579. let Operand::Vector { reg, .. } = *data else {
  5580. return Err("an image result");
  5581. };
  5582. let f32t = self.s.t.f32;
  5583. for (k, ch) in (0..2u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() {
  5584. let clamped = self.s.m.bool(ch == 0);
  5585. let lod = self.s.op(
  5586. c,
  5587. "calculateLOD.f32",
  5588. Attr::ReadOnly,
  5589. f32t,
  5590. 81,
  5591. &[h, sh, cs[0], cs[1], cs[2], clamped],
  5592. );
  5593. let x = self.as_int(lod);
  5594. self.write(inst, Reg::V(reg + k as u8), x, guard);
  5595. }
  5596. return Ok(());
  5597. }
  5598. let offsets = if kind == 5 {
  5599. 0
  5600. } else {
  5601. (coords - usize::from(kind == 6 || kind == 7)).min(3)
  5602. };
  5603. let zero = self.s.m.i32(0);
  5604. let mut os = vec![iu; 3];
  5605. for o in os.iter_mut().take(offsets) {
  5606. *o = zero;
  5607. }
  5608. let mut args = vec![h, sh];
  5609. args.extend(&cs);
  5610. match op {
  5611. 60 => {
  5612. args.extend(&os);
  5613. args.push(fu);
  5614. self.s
  5615. .op(c, "sample.f32", Attr::ReadOnly, self.s.t.res_ret, 60, &args)
  5616. }
  5617. 61 => {
  5618. let bias = addr_val(self, 0)?;
  5619. let bias = self.as_float(bias);
  5620. args.extend(&os);
  5621. args.extend([bias, fu]);
  5622. self.s.op(
  5623. c,
  5624. "sampleBias.f32",
  5625. Attr::ReadOnly,
  5626. self.s.t.res_ret,
  5627. 61,
  5628. &args,
  5629. )
  5630. }
  5631. 63 => {
  5632. let mut g = vec![fu; 6];
  5633. for k in 0..spatial {
  5634. let x = addr_val(self, first + k)?;
  5635. g[k] = to_float(self, x);
  5636. let y = addr_val(self, first + spatial + k)?;
  5637. g[3 + k] = to_float(self, y);
  5638. }
  5639. args.extend(&os);
  5640. args.extend(g);
  5641. args.push(fu);
  5642. self.s.op(
  5643. c,
  5644. "sampleGrad.f32",
  5645. Attr::ReadOnly,
  5646. self.s.t.res_ret,
  5647. 63,
  5648. &args,
  5649. )
  5650. }
  5651. 64 | 65 => {
  5652. let reference = addr_val(self, first - 1)?;
  5653. let reference = self.as_float(reference);
  5654. args.extend(&os);
  5655. args.push(reference);
  5656. let name = if op == 64 {
  5657. args.push(fu);
  5658. "sampleCmp.f32"
  5659. } else {
  5660. "sampleCmpLevelZero.f32"
  5661. };
  5662. self.s
  5663. .op(c, name, Attr::ReadOnly, self.s.t.res_ret, op, &args)
  5664. }
  5665. 62 => {
  5666. let lod = if name == "image_sample_l" {
  5667. let x = addr_val(self, coords)?;
  5668. to_float(self, x)
  5669. } else {
  5670. self.s.m.f32(0)
  5671. };
  5672. args.extend(&os);
  5673. args.push(lod);
  5674. self.s.op(
  5675. c,
  5676. "sampleLevel.f32",
  5677. Attr::ReadOnly,
  5678. self.s.t.res_ret,
  5679. 62,
  5680. &args,
  5681. )
  5682. }
  5683. _ => {
  5684. if name == "image_gather4" {
  5685. return Err("a gather with implicit level");
  5686. }
  5687. if dmask.count_ones() != 1 {
  5688. return Err("a gather of several channels");
  5689. }
  5690. if offset_word {
  5691. let w = addr_val(self, 0)?;
  5692. for (k, at) in [(0, 26), (1, 18)] {
  5693. // Bits at..at+5 sign-extended: shift up, then down.
  5694. let left = self.s.m.i32(at);
  5695. let t = self.s.m.bin(c, Bin::Shl, w, left);
  5696. let k26 = self.s.m.i32(26);
  5697. os[k] = self.s.m.bin(c, Bin::AShr, t, k26);
  5698. }
  5699. }
  5700. args.extend(&os[..2]);
  5701. args.push(self.s.m.i32(dmask.trailing_zeros()));
  5702. self.s.op(
  5703. c,
  5704. "textureGather.f32",
  5705. Attr::ReadOnly,
  5706. self.s.t.res_ret,
  5707. 73,
  5708. &args,
  5709. )
  5710. }
  5711. }
  5712. } else {
  5713. let mut cs = vec![iu; 3];
  5714. for (k, slot) in cs.iter_mut().enumerate().take(coords) {
  5715. *slot = addr_val(self, k)?;
  5716. }
  5717. let mip = if name == "image_load_mip" {
  5718. addr_val(self, coords)?
  5719. } else if uav {
  5720. // Our declarations have four channels.
  5721. self.s.flags |= flags::TYPED_UAV_LOADS;
  5722. iu
  5723. } else {
  5724. self.s.m.i32(0)
  5725. };
  5726. let mut args = vec![h, mip];
  5727. args.extend(&cs);
  5728. args.extend([iu, iu, iu]);
  5729. self.s.op(
  5730. c,
  5731. "textureLoad.f32",
  5732. Attr::ReadOnly,
  5733. self.s.t.res_ret,
  5734. 66,
  5735. &args,
  5736. )
  5737. };
  5738. let Operand::Vector { reg, .. } = *data else {
  5739. return Err("an image result");
  5740. };
  5741. let channels: Vec<u32> = if op == 73 {
  5742. vec![0, 1, 2, 3]
  5743. } else {
  5744. (0..4).filter(|ch| dmask >> ch & 1 != 0).collect()
  5745. };
  5746. let mut xs = Vec::new();
  5747. for ch in channels {
  5748. let x = self.s.m.extract(c, r, ch);
  5749. xs.push(if *d16 {
  5750. // shortcut: d16 results are taken as floats (rounded to
  5751. // nearest even); integer formats would keep 16 bits.
  5752. let i32t = self.s.t.i32;
  5753. self.s
  5754. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x])
  5755. } else {
  5756. self.as_int(x)
  5757. });
  5758. }
  5759. if *d16 {
  5760. // Two channels per VGPR, low half first (an odd last high half 0).
  5761. let k16 = self.s.m.i32(16);
  5762. xs = xs
  5763. .chunks(2)
  5764. .map(|p| match *p {
  5765. [lo, hi] => {
  5766. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  5767. self.s.m.bin(c, Bin::Or, lo, hi)
  5768. }
  5769. _ => p[0],
  5770. })
  5771. .collect();
  5772. }
  5773. for (k, x) in xs.into_iter().enumerate() {
  5774. self.write(inst, Reg::V(reg + k as u8), x, guard);
  5775. }
  5776. Ok(())
  5777. }
  5778. /// The direction a cube sample's face coordinates stand for: the
  5779. /// console takes s and t in [1, 2] (`v_cubesc`/`v_cubetc` over
  5780. /// `|v_cubema|`, plus 1.5) and the face id (`v_cubeid`), which the
  5781. /// host's cube sampling turns back into the same texel.
  5782. // shortcut: the view is taken as a cube, not a cube array (whose face
  5783. // operand adds 8 × the slice).
  5784. fn cube_direction(&mut self, s: V, t: V, face: V) -> [V; 3] {
  5785. let c = self.cur;
  5786. let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits());
  5787. let (two, three) = (k(self, 2.0), k(self, 3.0));
  5788. let u = self.s.m.bin(c, Bin::Mul, s, two);
  5789. let u = self.s.m.bin(c, Bin::Sub, u, three);
  5790. let v = self.s.m.bin(c, Bin::Mul, t, two);
  5791. let v = self.s.m.bin(c, Bin::Sub, v, three);
  5792. let z = self.s.m.f32(0x8000_0000);
  5793. let (nu, nv) = (
  5794. self.s.m.bin(c, Bin::Sub, z, u),
  5795. self.s.m.bin(c, Bin::Sub, z, v),
  5796. );
  5797. let (one, mone) = (k(self, 1.0), k(self, -1.0));
  5798. let f = self.s.m.cast(c, Cast::FpToUi, face, self.s.t.i32);
  5799. // Per face +x, -x, +y, -y, +z, -z.
  5800. let table = [
  5801. [one, mone, u, u, u, nu],
  5802. [nv, nv, one, mone, nv, nv],
  5803. [nu, u, v, nv, one, mone],
  5804. ];
  5805. table.map(|row| {
  5806. let mut r = row[0];
  5807. for (n, &x) in row.iter().enumerate().skip(1) {
  5808. let kn = self.s.m.i32(n as u32);
  5809. let is = self.s.m.cmp(c, pred::EQ, f, kn);
  5810. r = self.s.m.select(c, is, x, r);
  5811. }
  5812. r
  5813. })
  5814. }
  5815. fn buffer(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  5816. let Fields::Buffer {
  5817. data,
  5818. addr,
  5819. soffset,
  5820. offset,
  5821. offen,
  5822. idxen,
  5823. format,
  5824. lds,
  5825. tfe,
  5826. ..
  5827. } = &inst.fields
  5828. else {
  5829. unreachable!()
  5830. };
  5831. let name = inst.name();
  5832. if *lds || *tfe {
  5833. return Err("a buffer access to LDS or with tfe");
  5834. }
  5835. if format.is_some() && !name.starts_with("tbuffer_load_format_") {
  5836. return Err(name);
  5837. }
  5838. let site = (b, i);
  5839. let guard = self.guard(b, i)?;
  5840. let c = self.cur;
  5841. let store = name.starts_with("buffer_store_");
  5842. // DXIL atomic operations: add, and, or, xor, signed and unsigned
  5843. // min and max, exchange; compare-exchange apart.
  5844. let atomic = match name.strip_prefix("buffer_atomic_") {
  5845. None => None,
  5846. Some("add") => Some(0),
  5847. Some("and") => Some(1),
  5848. Some("or") => Some(2),
  5849. Some("xor") => Some(3),
  5850. Some("smin") => Some(4),
  5851. Some("smax") => Some(5),
  5852. Some("umin") => Some(6),
  5853. Some("umax") => Some(7),
  5854. Some("swap") => Some(8),
  5855. Some("cmpswap") => Some(u32::MAX),
  5856. Some(_) => return Err(name),
  5857. };
  5858. // d16: two 16-bit channels per VGPR, low half first.
  5859. let d16 = name.starts_with("buffer_") && name.contains("_format_d16_");
  5860. let plain = name.replace("_format_d16_", "_format_");
  5861. let (typed, count) = match plain
  5862. .strip_prefix("buffer_load_")
  5863. .or(plain.strip_prefix("buffer_store_"))
  5864. .or(plain.strip_prefix("tbuffer_load_"))
  5865. {
  5866. _ if atomic.is_some() => (false, 1),
  5867. Some("dword") => (false, 1),
  5868. Some("dwordx2") => (false, 2),
  5869. Some("dwordx3") => (false, 3),
  5870. Some("dwordx4") => (false, 4),
  5871. Some("format_x") => (true, 1),
  5872. Some("format_xy") => (true, 2),
  5873. Some("format_xyz") => (true, 3),
  5874. Some("format_xyzw") => (true, 4),
  5875. _ => return Err(name),
  5876. };
  5877. let Operand::Vector { reg: areg, .. } = *addr else {
  5878. return Err("a buffer address");
  5879. };
  5880. let vaddr = |l: &mut Self, k: u8| -> Result<V, Why> {
  5881. let v = inst.read(Reg::V(areg + k)).ok_or("a buffer address")?;
  5882. l.i32_of(v)
  5883. };
  5884. let index = if *idxen { Some(vaddr(self, 0)?) } else { None };
  5885. let mut off = self.s.m.i32(u32::from(*offset));
  5886. if *offen {
  5887. let o = vaddr(self, u8::from(*idxen))?;
  5888. off = self.s.m.bin(c, Bin::Add, off, o);
  5889. }
  5890. if !matches!(
  5891. soffset,
  5892. Operand::Scalar { code: NULL, .. } | Operand::Const(128)
  5893. ) {
  5894. let so = self.operand(inst, soffset)?;
  5895. off = self.s.m.bin(c, Bin::Add, off, so);
  5896. }
  5897. let src = self
  5898. .descriptors
  5899. .get(&(site, false))
  5900. .copied()
  5901. .ok_or("an untracked buffer")?;
  5902. let used = self.used_kind(src);
  5903. let (base, extra) = self.built_offset(src)?;
  5904. if base != 0 {
  5905. let b = self.s.m.i32(base);
  5906. off = self.s.m.bin(c, Bin::Add, off, b);
  5907. }
  5908. if let Some(x) = extra {
  5909. off = self.s.m.bin(c, Bin::Add, off, x);
  5910. }
  5911. if used.is_some_and(|u| u.kind == ResourceType::Cbv) && !typed {
  5912. // A constant buffer read per lane (a dynamically indexed array).
  5913. // shortcut: the console's CBV descriptor is taken to have a 16-byte
  5914. // stride, as the vector loads of whole rows suggest.
  5915. let h = self.handle(site, src, false, (13, 0x1_0000))?;
  5916. let byte = match index {
  5917. Some(i) => {
  5918. let sixteen = self.s.m.i32(16);
  5919. let rows = self.s.m.bin(c, Bin::Mul, i, sixteen);
  5920. self.s.m.bin(c, Bin::Add, rows, off)
  5921. }
  5922. None => off,
  5923. };
  5924. let Some(Operand::Vector { reg, .. }) = *data else {
  5925. return Err("a buffer result");
  5926. };
  5927. for k in 0..count {
  5928. let four = self.s.m.i32(4 * k);
  5929. let a = self.s.m.bin(c, Bin::Add, byte, four);
  5930. let x = self.cbuffer_dword(h, a);
  5931. self.write(inst, Reg::V(reg + k as u8), x, guard);
  5932. }
  5933. return Ok(());
  5934. }
  5935. let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav);
  5936. let u = if uav { 0x1000 } else { 0 };
  5937. let iu = self.s.m.undef(self.s.t.i32);
  5938. if let Some(op) = atomic {
  5939. let d = data.as_ref().ok_or("buffer atomic data")?;
  5940. let vals = self.vgprs(inst, d, if op == u32::MAX { 2 } else { 1 })?;
  5941. let (h, coords) = match index {
  5942. Some(index) => {
  5943. let stride = used.map_or(0, |u| u.stride);
  5944. if stride < 4 || !stride.is_multiple_of(4) {
  5945. return Err("a structured buffer of unknown stride");
  5946. }
  5947. let h = self.handle(site, src, false, (12 | u, stride))?;
  5948. (h, [index, off, iu])
  5949. }
  5950. None => (self.handle(site, src, false, (11 | u, 0))?, [off, iu, iu]),
  5951. };
  5952. let Operand::Vector { reg, .. } = *d else {
  5953. return Err("buffer atomic data");
  5954. };
  5955. let returns = matches!(inst.fields, Fields::Buffer { cache, .. } if cache.glc);
  5956. let old = match inst.read(Reg::V(reg)) {
  5957. Some(v) if returns => self.i32_of(v)?,
  5958. _ => self.s.m.i32(0),
  5959. };
  5960. let at = self.begin_guarded(guard);
  5961. let i32t = self.s.t.i32;
  5962. let r = if op == u32::MAX {
  5963. // cmpswap: data is (new, compare).
  5964. let mut args = vec![h];
  5965. args.extend(coords);
  5966. args.extend([vals[1], vals[0]]);
  5967. self.s.op(
  5968. self.cur,
  5969. "atomicCompareExchange.i32",
  5970. Attr::NoUnwind,
  5971. i32t,
  5972. 79,
  5973. &args,
  5974. )
  5975. } else {
  5976. let mut args = vec![h, self.s.m.i32(op)];
  5977. args.extend(coords);
  5978. args.push(vals[0]);
  5979. self.s
  5980. .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args)
  5981. };
  5982. let r = self.end_guarded(at, &[(r, old)])[0];
  5983. if returns {
  5984. self.write(inst, Reg::V(reg), r, None);
  5985. }
  5986. return Ok(());
  5987. }
  5988. if store {
  5989. let regs = if d16 { count.div_ceil(2) } else { count };
  5990. let mut vals =
  5991. self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?;
  5992. if d16 {
  5993. // shortcut: d16 data is taken as f16 (integer formats would
  5994. // keep 16 bits), widened for the 32-bit float store.
  5995. let mut wide = Vec::new();
  5996. for k in 0..count {
  5997. let mut x = vals[(k / 2) as usize];
  5998. if k % 2 == 1 {
  5999. let k16 = self.s.m.i32(16);
  6000. x = self.s.m.bin(c, Bin::LShr, x, k16);
  6001. }
  6002. let f32t = self.s.t.f32;
  6003. let f = self
  6004. .s
  6005. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
  6006. wide.push(self.as_int(f));
  6007. }
  6008. vals = wide;
  6009. }
  6010. let mut args = Vec::new();
  6011. let (op, name) = if typed {
  6012. // shortcut: typed stores are taken to write all four channels
  6013. // of a float format.
  6014. if count != 4 || *offen || *offset != 0 {
  6015. return Err("a typed buffer store of some channels or at an offset");
  6016. }
  6017. args.push(self.handle(site, src, false, (10 | u, 0x409))?);
  6018. args.extend([index.unwrap_or(self.s.m.i32(0)), iu]);
  6019. for x in vals {
  6020. args.push(self.as_float(x));
  6021. }
  6022. (69, "bufferStore.f32")
  6023. } else {
  6024. match index {
  6025. Some(index) => {
  6026. let stride = used.map_or(0, |u| u.stride);
  6027. if stride < 4 || !stride.is_multiple_of(4) {
  6028. return Err("a structured buffer of unknown stride");
  6029. }
  6030. args.push(self.handle(site, src, false, (12 | u, stride))?);
  6031. args.extend([index, off]);
  6032. }
  6033. None => {
  6034. args.push(self.handle(site, src, false, (11 | u, 0))?);
  6035. args.extend([off, iu]);
  6036. }
  6037. }
  6038. args.extend(&vals);
  6039. args.resize(3 + 4, iu);
  6040. (140, "rawBufferStore.i32")
  6041. };
  6042. args.push(self.s.m.i8(if typed { 0xF } else { (1u8 << count) - 1 }));
  6043. if !typed {
  6044. args.push(self.s.m.i32(4));
  6045. }
  6046. let at = self.begin_guarded(guard);
  6047. let void = self.s.t.void;
  6048. self.s.op(self.cur, name, Attr::NoUnwind, void, op, &args);
  6049. self.end_guarded(at, &[]);
  6050. return Ok(());
  6051. }
  6052. if let Some(f) = *format {
  6053. if index.is_some() {
  6054. return Err("a typed-format load by index");
  6055. }
  6056. let h = self.handle(site, src, false, (11 | u, 0))?;
  6057. let Some(Operand::Vector { reg, .. }) = *data else {
  6058. return Err("a buffer result");
  6059. };
  6060. for (k, x) in self.format_load(h, off, f, count)?.into_iter().enumerate() {
  6061. self.write(inst, Reg::V(reg + k as u8), x, guard);
  6062. }
  6063. return Ok(());
  6064. }
  6065. let r = if typed {
  6066. if *offen || matches!(off, V::Inst(_)) || *offset != 0 {
  6067. return Err("a typed buffer load at an offset");
  6068. }
  6069. if uav {
  6070. self.s.flags |= flags::TYPED_UAV_LOADS;
  6071. }
  6072. let h = self.handle(site, src, false, (10 | u, 0x409))?;
  6073. let index = index.unwrap_or(self.s.m.i32(0));
  6074. self.s.op(
  6075. c,
  6076. "bufferLoad.f32",
  6077. Attr::ReadOnly,
  6078. self.s.t.res_ret,
  6079. 68,
  6080. &[h, index, iu],
  6081. )
  6082. } else {
  6083. let mask = self.s.m.i8((1u8 << count) - 1);
  6084. let align = self.s.m.i32(4);
  6085. match index {
  6086. Some(index) => {
  6087. let stride = used.map_or(0, |u| u.stride);
  6088. if stride < 4 || !stride.is_multiple_of(4) {
  6089. return Err("a structured buffer of unknown stride");
  6090. }
  6091. let h = self.handle(site, src, false, (12 | u, stride))?;
  6092. self.s.op(
  6093. c,
  6094. "rawBufferLoad.f32",
  6095. Attr::ReadOnly,
  6096. self.s.t.res_ret,
  6097. 139,
  6098. &[h, index, off, mask, align],
  6099. )
  6100. }
  6101. None => {
  6102. let h = self.handle(site, src, false, (11 | u, 0))?;
  6103. self.s.op(
  6104. c,
  6105. "rawBufferLoad.f32",
  6106. Attr::ReadOnly,
  6107. self.s.t.res_ret,
  6108. 139,
  6109. &[h, off, iu, mask, align],
  6110. )
  6111. }
  6112. }
  6113. };
  6114. let Some(Operand::Vector { reg, .. }) = *data else {
  6115. return Err("a buffer result");
  6116. };
  6117. if d16 {
  6118. // Two f16 channels per VGPR (an odd last high half 0).
  6119. let k16 = self.s.m.i32(16);
  6120. let i32t = self.s.t.i32;
  6121. for k in 0..count.div_ceil(2) {
  6122. let mut x = None;
  6123. for ch in (2 * k..(2 * k + 2).min(count)).rev() {
  6124. let f = self.s.m.extract(c, r, ch);
  6125. let h = self
  6126. .s
  6127. .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
  6128. x = Some(match x {
  6129. Some(hi) => {
  6130. let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
  6131. self.s.m.bin(c, Bin::Or, h, hi)
  6132. }
  6133. None => h,
  6134. });
  6135. }
  6136. self.write(inst, Reg::V(reg + k as u8), x.expect("a channel"), guard);
  6137. }
  6138. return Ok(());
  6139. }
  6140. for k in 0..count {
  6141. let x = self.s.m.extract(c, r, k);
  6142. let x = self.as_int(x);
  6143. self.write(inst, Reg::V(reg + k as u8), x, guard);
  6144. }
  6145. Ok(())
  6146. }
  6147. fn export(&mut self, b: usize, i: usize) -> Result<(), Why> {
  6148. let e = *self
  6149. .exports
  6150. .get(&(b, i))
  6151. .ok_or("an export I/O raising did not see")?;
  6152. if e.compressed {
  6153. return Err("a compressed export");
  6154. }
  6155. let guard = self.guard(b, i)?;
  6156. let mesh = self.s.mesh.is_some();
  6157. let c = self.cur;
  6158. if let Some(g) = guard
  6159. && !mesh
  6160. {
  6161. if !(e.done && self.s.pixel) {
  6162. return Err("a conditional export");
  6163. }
  6164. let t = self.s.m.bool(true);
  6165. let kill = self.s.m.bin(c, Bin::Xor, g, t);
  6166. self.s
  6167. .op(c, "discard", Attr::NoUnwind, self.s.t.void, 82, &[kill]);
  6168. }
  6169. if mesh && e.target == Target::Primitive {
  6170. return self.emit_indices(e, guard);
  6171. }
  6172. let param_row = |usage: Usage, row: u8| match usage {
  6173. // The 2020 compiler leaves a mesh program's first entry zeroed
  6174. // (usage "position"): its row is the one no other entry names.
  6175. Usage::Other(0) if mesh => self.unnamed_row(),
  6176. _ => Some(row),
  6177. };
  6178. // (output element, channel) per exported channel; per-primitive
  6179. // outputs are elements of `prims`.
  6180. let mut stores = Vec::new();
  6181. let primitive = matches!(e.target, Target::PrimitiveParam { .. });
  6182. let outputs = if primitive {
  6183. &self.s.prims
  6184. } else {
  6185. &self.s.outputs
  6186. };
  6187. let by_kind = |kind: u8| outputs.iter().position(|o| o.kind == kind);
  6188. // 16-bit vertex outputs: the halves each dword carries, as (output
  6189. // element, channel, high half) per channel.
  6190. let halves = match e.target {
  6191. Target::Param { usage, row } => {
  6192. param_row(usage, row).and_then(|r| self.half_outputs.get(&r).map(|&h| (r, h)))
  6193. }
  6194. _ => None,
  6195. };
  6196. if let Some((row, (pack2, b))) = halves {
  6197. for ch in 0..4u8 {
  6198. let Some(value) = e.values[usize::from(ch)] else {
  6199. continue;
  6200. };
  6201. for high in [false, true] {
  6202. let h = 2 * ch + u8::from(high);
  6203. let src = if pack2 {
  6204. packed_half(outputs, row, b, h)
  6205. } else {
  6206. (!high).then_some((row, ch))
  6207. };
  6208. let found = src.and_then(|(r, c)| {
  6209. outputs.iter().position(|o| {
  6210. o.row == Some(u32::from(r)) && c >= o.col && c < o.col + o.cols
  6211. })
  6212. });
  6213. if let Some(id) = found {
  6214. let col = src.expect("found").1 - outputs[id].col;
  6215. stores.push((id, col, value, Some(high)));
  6216. }
  6217. }
  6218. }
  6219. }
  6220. for ch in 0..4u8 {
  6221. let Some(value) = e.values[usize::from(ch)] else {
  6222. continue;
  6223. };
  6224. if halves.is_some() {
  6225. break;
  6226. }
  6227. let found = match e.target {
  6228. Target::Color(n) => outputs
  6229. .iter()
  6230. .position(|o| o.kind == 16 && o.row == Some(u32::from(n)))
  6231. .map(|id| (id, ch)),
  6232. Target::Position(0) => by_kind(3).map(|id| (id, ch)),
  6233. Target::Depth => match ch {
  6234. 0 => by_kind(17)
  6235. .or(by_kind(18))
  6236. .or(by_kind(19))
  6237. .map(|id| (id, 0)),
  6238. 1 => by_kind(20).map(|id| (id, 0)),
  6239. 2 => by_kind(14).map(|id| (id, 0)),
  6240. _ => None,
  6241. },
  6242. Target::Param { usage, row } | Target::PrimitiveParam { usage, row } => {
  6243. let row = param_row(usage, row);
  6244. outputs
  6245. .iter()
  6246. .position(|o| {
  6247. row.is_some_and(|r| o.row == Some(u32::from(r)))
  6248. && ch >= o.col
  6249. && ch < o.col + o.cols
  6250. })
  6251. .map(|id| (id, ch - outputs[id].col))
  6252. }
  6253. Target::Null | Target::Unread => None,
  6254. Target::Position(n @ 1..=2) => {
  6255. // shortcut: without the misc vector (point size, render
  6256. // target or viewport index) pos1 and pos2 carry the clip
  6257. // then cull distances, in semantic order.
  6258. if outputs.iter().any(|o| matches!(o.kind, 4 | 5)) {
  6259. return Err("render-target or viewport index exports");
  6260. }
  6261. let mut dists: Vec<usize> = (0..outputs.len())
  6262. .filter(|&i| matches!(outputs[i].kind, 6 | 7))
  6263. .collect();
  6264. dists.sort_by_key(|&i| (outputs[i].kind, outputs[i].index));
  6265. let flat: Vec<(usize, u8)> = dists
  6266. .iter()
  6267. .flat_map(|&i| (0..outputs[i].cols).map(move |c| (i, c)))
  6268. .collect();
  6269. // Channels past the distances the signature declares are
  6270. // ones the clipper does not enable (`PA_CL_VS_OUT_CNTL`).
  6271. let k = usize::from(n - 1) * 4 + usize::from(ch);
  6272. flat.get(k).copied()
  6273. }
  6274. Target::Position(_) => return Err("clip, cull or point-size exports"),
  6275. Target::Primitive => return Err("a primitive export"),
  6276. };
  6277. if let Some((id, col)) = found {
  6278. stores.push((id, col, value, None));
  6279. }
  6280. }
  6281. fn elements<'l>(l: &'l mut Lower, primitive: bool) -> &'l mut Vec<SigElement> {
  6282. if primitive {
  6283. &mut l.s.prims
  6284. } else {
  6285. &mut l.s.outputs
  6286. }
  6287. }
  6288. if stores
  6289. .iter()
  6290. .any(|s| s.3.is_none() && elements(self, primitive)[s.0].half)
  6291. {
  6292. return Err("a 16-bit output the stage data does not mark");
  6293. }
  6294. // A mesh lane writes its own vertex or primitive, where it exports.
  6295. let at = if mesh {
  6296. self.begin_guarded(guard)
  6297. } else {
  6298. None
  6299. };
  6300. let (name, opcode) = match (mesh, primitive) {
  6301. (false, _) => ("storeOutput", 5),
  6302. (true, false) => ("storeVertexOutput", 171),
  6303. (true, true) => ("storePrimitiveOutput", 172),
  6304. };
  6305. for (id, col, value, half) in stores {
  6306. let mut x = self.i32_of(value)?;
  6307. if let Some(high) = half {
  6308. // An f16 half, declared a 32-bit float on the host.
  6309. let c = self.cur;
  6310. if high {
  6311. let k16 = self.s.m.i32(16);
  6312. x = self.s.m.bin(c, Bin::LShr, x, k16);
  6313. }
  6314. let f32t = self.s.t.f32;
  6315. let f = self
  6316. .s
  6317. .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
  6318. x = self.as_int(f);
  6319. }
  6320. let el = &mut elements(self, primitive)[id];
  6321. el.usage |= 1 << col;
  6322. let (suffix, x) = match el.comp {
  6323. 9 if half.is_some() => (".f32", self.as_float(x)),
  6324. 9 => {
  6325. let f = match self.floats.get(&value) {
  6326. Some(&f) => f,
  6327. None => self.as_float(x),
  6328. };
  6329. (".f32", f)
  6330. }
  6331. _ => (".i32", x),
  6332. };
  6333. let mut args = vec![
  6334. self.s.m.i32(id as u32),
  6335. self.s.m.i32(0),
  6336. self.s.m.i8(col),
  6337. x,
  6338. ];
  6339. if mesh {
  6340. args.push(self.mesh_thread());
  6341. }
  6342. let void = self.s.t.void;
  6343. self.s.op(
  6344. self.cur,
  6345. &format!("{name}{suffix}"),
  6346. Attr::NoUnwind,
  6347. void,
  6348. opcode,
  6349. &args,
  6350. );
  6351. }
  6352. self.end_guarded(at, &[]);
  6353. Ok(())
  6354. }
  6355. /// Mesh: `exp prim` as the lane's primitive. Bit 31 culls it (all
  6356. /// indices 0: no area).
  6357. fn emit_indices(&mut self, e: &Export, guard: Option<V>) -> Result<(), Why> {
  6358. let v = e.values[0].ok_or("a primitive export without its indices")?;
  6359. let x = self.i32_of(v)?;
  6360. let at = self.begin_guarded(guard);
  6361. let c = self.cur;
  6362. let z = self.s.m.i32(0);
  6363. let culled = self.s.m.cmp(c, pred::SLT, x, z);
  6364. let mut args = vec![self.mesh_thread()];
  6365. for k in 0..3 {
  6366. let (shift, mask) = (self.s.m.i32(10 * k), self.s.m.i32(0x3FF));
  6367. let i = self.s.m.bin(c, Bin::LShr, x, shift);
  6368. let i = self.s.m.bin(c, Bin::And, i, mask);
  6369. args.push(self.s.m.select(c, culled, z, i));
  6370. }
  6371. let void = self.s.t.void;
  6372. self.s
  6373. .op(c, "emitIndices", Attr::NoUnwind, void, 169, &args);
  6374. self.end_guarded(at, &[]);
  6375. Ok(())
  6376. }
  6377. /// The per-vertex arbitrary row no mesh output entry names but one
  6378. /// (the 2020 compiler's zeroed entry).
  6379. fn unnamed_row(&self) -> Option<u8> {
  6380. let StageIo::Ms(ms) = &self.x.native.io else {
  6381. return None;
  6382. };
  6383. let named = |r: u32| {
  6384. ms.outputs
  6385. .iter()
  6386. .any(|o| o.param & 0x80 == 0 && o.usage != Usage::Other(0) && u32::from(o.row) == r)
  6387. };
  6388. let free: std::collections::BTreeSet<u32> = self
  6389. .s
  6390. .outputs
  6391. .iter()
  6392. .filter(|o| o.kind == 0)
  6393. .filter_map(|o| o.row)
  6394. .filter(|&r| !named(r))
  6395. .collect();
  6396. match free.into_iter().collect::<Vec<_>>()[..] {
  6397. [r] => u8::try_from(r).ok(),
  6398. _ => None,
  6399. }
  6400. }
  6401. fn exit(&mut self, b: usize) -> Result<(), Stop> {
  6402. let offset = self.x.p.blocks[b]
  6403. .insts
  6404. .last()
  6405. .map_or(self.x.p.blocks[b].offset, |i| i.machine.offset);
  6406. let term = match self.x.st.exits[b] {
  6407. LaneExit::Jump(t) if self.counters.contains_key(&t) && self.rpo[t] <= self.rpo[b] => {
  6408. let ok = self.count_iteration(t, pred::IULT);
  6409. let abort = self.abort_block();
  6410. Term::CondBr(ok, self.block[t].expect("reachable"), abort)
  6411. }
  6412. LaneExit::Jump(t) => {
  6413. self.enter_loop(b, t, self.cur);
  6414. Term::Br(self.block[t].expect("reachable"))
  6415. }
  6416. LaneExit::Branch {
  6417. when,
  6418. taken,
  6419. not_taken,
  6420. } => {
  6421. // A negated condition branches the other way round.
  6422. let (cond, taken, not_taken) = match self.x.st.bools.node(when) {
  6423. Some((atom, Bool::TRUE, Bool::FALSE)) => {
  6424. let a = self
  6425. .atom(atom, self.cur)
  6426. .map_err(|w| unsupported(offset, w))?;
  6427. (a, not_taken, taken)
  6428. }
  6429. _ => {
  6430. let c = self
  6431. .boolean(when, self.cur)
  6432. .map_err(|w| unsupported(offset, w))?;
  6433. (c, taken, not_taken)
  6434. }
  6435. };
  6436. // A back edge is taken only below the iteration limit.
  6437. let back =
  6438. |l: &Self, to: usize| l.counters.contains_key(&to) && l.rpo[to] <= l.rpo[b];
  6439. // (No `xor` of a compare: a loop exit testing one hung the
  6440. // AMD driver.)
  6441. let cond = if back(self, taken) {
  6442. let ok = self.count_iteration(taken, pred::IULT);
  6443. self.s.m.bin(self.cur, Bin::And, cond, ok)
  6444. } else if back(self, not_taken) {
  6445. let stop = self.count_iteration(not_taken, pred::IUGE);
  6446. self.s.m.bin(self.cur, Bin::Or, cond, stop)
  6447. } else {
  6448. cond
  6449. };
  6450. // Critical edges get a block of their own, so loops have
  6451. // dedicated exits and preheaders as DXC emits them.
  6452. let (t, f) = (self.edge(b, taken), self.edge(b, not_taken));
  6453. for (to, via) in [(taken, t), (not_taken, f)] {
  6454. if !back(self, to) {
  6455. // From an edge block, or from here.
  6456. let from = if Some(via) == self.block[to] {
  6457. self.cur
  6458. } else {
  6459. via
  6460. };
  6461. self.enter_loop(b, to, from);
  6462. }
  6463. }
  6464. Term::CondBr(cond, t, f)
  6465. }
  6466. LaneExit::End => {
  6467. if self.s.pixel && !self.exported[b] && !self.has_done_export(b) {
  6468. // A lane leaving without its final export was killed.
  6469. let t = self.s.m.bool(true);
  6470. self.s
  6471. .op(self.cur, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]);
  6472. }
  6473. Term::Ret
  6474. }
  6475. LaneExit::Indirect => return Err(unsupported(offset, "an indirect jump")),
  6476. };
  6477. let _ = Exit::End;
  6478. self.s.m.terminate(self.cur, term);
  6479. Ok(())
  6480. }
  6481. /// A forward edge into loop header `to` (from DXIL block `via`) starts
  6482. /// its count at 0.
  6483. fn enter_loop(&mut self, _from: usize, to: usize, via: usize) {
  6484. if let Some((_, incoming)) = self.counters.get_mut(&to) {
  6485. let z = self.s.m.i32(0);
  6486. incoming.push((z, via));
  6487. }
  6488. }
  6489. /// A back edge to header `to` (a back edge keeps its block, no
  6490. /// critical-edge block): the count goes up; the result compares it with
  6491. /// [`LOOP_LIMIT`] by `p` (below: go on; at or above: stop).
  6492. fn count_iteration(&mut self, to: usize, p: u8) -> V {
  6493. let c = self.cur;
  6494. let (phi, _) = self.counters[&to];
  6495. let one = self.s.m.i32(1);
  6496. let next = self.s.m.bin(c, Bin::Add, phi, one);
  6497. let limit = self.s.m.i32(super::loop_limit());
  6498. self.counters
  6499. .get_mut(&to)
  6500. .expect("header")
  6501. .1
  6502. .push((next, c));
  6503. self.s.m.cmp(c, p, next, limit)
  6504. }
  6505. /// The block a lane stopped by [`LOOP_LIMIT`] leaves through.
  6506. fn abort_block(&mut self) -> usize {
  6507. if let Some(a) = self.abort {
  6508. return a;
  6509. }
  6510. let a = self.s.m.new_block();
  6511. if self.s.pixel {
  6512. let t = self.s.m.bool(true);
  6513. self.s
  6514. .op(a, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]);
  6515. }
  6516. self.s.m.terminate(a, Term::Ret);
  6517. self.abort = Some(a);
  6518. a
  6519. }
  6520. /// The DXIL block a branch from IR block `from` to `to` goes to.
  6521. fn edge(&mut self, from: usize, to: usize) -> usize {
  6522. let target = self.block[to].expect("reachable");
  6523. let preds = self.x.p.blocks[to]
  6524. .preds
  6525. .iter()
  6526. .filter(|&&q| self.block[q].is_some())
  6527. .count();
  6528. // Back edges stay as they are: the exiting block is the latch.
  6529. if preds < 2 || self.rpo[to] <= self.rpo[from] {
  6530. return target;
  6531. }
  6532. let e = self.s.m.new_block();
  6533. self.s.m.terminate(e, Term::Br(target));
  6534. self.edges.insert((from, to), e);
  6535. e
  6536. }
  6537. fn fill_phis(&mut self) -> Result<(), Stop> {
  6538. let p = self.x.p;
  6539. for (v, b, i) in std::mem::take(&mut self.data_phis) {
  6540. let phi = &p.blocks[b].phis[i];
  6541. let bit = phi.reg == Reg::Scc;
  6542. let mut incoming = Vec::new();
  6543. for (n, &q) in p.blocks[b].preds.iter().enumerate() {
  6544. let Some(qb) = self.tail[q] else { continue };
  6545. let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb);
  6546. let arg = phi.args[n];
  6547. let x = match (self.vals.get(&arg).copied(), bit) {
  6548. (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x,
  6549. (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => {
  6550. return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values"));
  6551. }
  6552. (Some(Val::Missing(why)), _) if self.read_phis.contains(&phi.value) => {
  6553. return Err(Stop::Retry(phi.value, why));
  6554. }
  6555. _ if self.read_phis.contains(&phi.value) => {
  6556. return Err(Stop::Retry(phi.value, "a join of mismatched values"));
  6557. }
  6558. _ if bit => self.s.m.bool(false),
  6559. _ => self.s.m.i32(0),
  6560. };
  6561. incoming.push((x, qb));
  6562. }
  6563. self.s.m.set_phi(v, incoming);
  6564. }
  6565. for (phi, incoming) in std::mem::take(&mut self.counters).into_values() {
  6566. self.s.m.set_phi(phi, incoming);
  6567. }
  6568. while let Some((v, b, i)) = self.pending_masks.pop() {
  6569. let phi = &p.blocks[b].phis[i];
  6570. let offset = p.blocks[b].offset;
  6571. let mut incoming = Vec::new();
  6572. for (n, &q) in p.blocks[b].preds.iter().enumerate() {
  6573. let Some(qb) = self.tail[q] else { continue };
  6574. let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb);
  6575. let m =
  6576. *self.x.st.masks.get(&phi.args[n]).ok_or_else(|| {
  6577. unsupported(offset, "a lane-mask join of an untracked mask")
  6578. })?;
  6579. let x = self.boolean(m, qb).map_err(|w| unsupported(offset, w))?;
  6580. incoming.push((x, qb));
  6581. }
  6582. self.s.m.set_phi(v, incoming);
  6583. }
  6584. Ok(())
  6585. }
  6586. }
  6587. #[cfg(test)]
  6588. mod tests {
  6589. use super::{Numeric, Parts, buffer_format, half_shift, lower};
  6590. use crate::native::{ComputeIo, HwStage, NativeProgram, StageIo};
  6591. use crate::{io, ir, resource, structure};
  6592. const S_ENDPGM: u32 = 0xBF81_0000;
  6593. /// Lowers a compute program of constants: whether it translates.
  6594. fn lowers(words: &[u32]) -> Result<(), crate::ShaderError> {
  6595. let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
  6596. let native = NativeProgram {
  6597. stage: HwStage::Cs,
  6598. wave64: false,
  6599. vgprs: 256,
  6600. layout: vec![],
  6601. used: vec![],
  6602. io: StageIo::Cs(ComputeIo {
  6603. rsrc2: 0,
  6604. threads: [1, 1, 1],
  6605. }),
  6606. code,
  6607. };
  6608. let p = ir::build(&native.code, false, 256).unwrap();
  6609. let res = resource::track(&p, &native.layout, native.stage).unwrap();
  6610. let io = io::raise(&p, &native).unwrap();
  6611. let st = structure::structure(&p).unwrap();
  6612. lower(&Parts {
  6613. native: &native,
  6614. p: &p,
  6615. st: &st,
  6616. io: &io,
  6617. res: &res,
  6618. inputs: vec![],
  6619. outputs: vec![],
  6620. prims: vec![],
  6621. mesh_stride: 0,
  6622. })
  6623. .map(|_| ())
  6624. }
  6625. #[test]
  6626. fn a_scalar_carry_chain_reaches_the_select() {
  6627. // The high dword of a 64-bit add or subtract, then a select on the
  6628. // carry (borrow) the high half leaves in SCC, and a branch on it
  6629. // (only code with an effect needs its operands).
  6630. let add = [
  6631. 0xBE80_03C1, // s_mov_b32 s0, -1
  6632. 0xBE81_0380, // s_mov_b32 s1, 0
  6633. 0x8000_8100, // s_add_u32 s0, s0, 1
  6634. 0x8201_8001, // s_addc_u32 s1, s1, 0
  6635. 0x8502_0001, // s_cselect_b32 s2, s1, s0
  6636. 0xBF07_8002, // s_cmp_lg_u32 s2, 0
  6637. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  6638. 0xBE83_0380, // s_mov_b32 s3, 0
  6639. S_ENDPGM,
  6640. ];
  6641. let sub = [
  6642. 0xBE80_0380, // s_mov_b32 s0, 0
  6643. 0xBE81_0380, // s_mov_b32 s1, 0
  6644. 0x8080_8100, // s_sub_u32 s0, s0, 1
  6645. 0x8281_8001, // s_subb_u32 s1, s1, 0
  6646. 0x8502_0001, // s_cselect_b32 s2, s1, s0
  6647. 0xBF07_8002, // s_cmp_lg_u32 s2, 0
  6648. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  6649. 0xBE83_0380, // s_mov_b32 s3, 0
  6650. S_ENDPGM,
  6651. ];
  6652. for words in [add, sub] {
  6653. lowers(&words).unwrap();
  6654. }
  6655. }
  6656. fn perm_features(selector: u32) -> u64 {
  6657. // Synthetic compute shader:
  6658. // v0 is the thread ID and can supply a dynamic selector.
  6659. // Store the result in LDS to keep the permutation live.
  6660. let words = [
  6661. 0x7E02_02FFu32,
  6662. 0x817F_34AB,
  6663. 0x7E04_02FF,
  6664. 0xFE01_56CD,
  6665. 0xD744_0003,
  6666. 257 | (258 << 9) | (selector << 18),
  6667. 0x3408_0082,
  6668. 0xD834_0000,
  6669. 0x0000_0304,
  6670. S_ENDPGM,
  6671. ];
  6672. let code: Vec<u8> = words.iter()
  6673. .flat_map(|w| w.to_le_bytes())
  6674. .collect();
  6675. let native = NativeProgram {
  6676. stage: HwStage::Cs,
  6677. wave64: false,
  6678. vgprs: 256,
  6679. layout: vec![],
  6680. used: vec![],
  6681. io: StageIo::Cs(ComputeIo {
  6682. rsrc2: 1 << 15,
  6683. threads: [64, 1, 1],
  6684. }),
  6685. code,
  6686. };
  6687. let p = ir::build(&native.code, false, 256).unwrap();
  6688. assert!(p.blocks.iter()
  6689. .flat_map(|b| &b.insts)
  6690. .any(|i| i.name() == "v_perm_b32"));
  6691. let res = resource::track(
  6692. &p, &native.layout, native.stage
  6693. ).unwrap();
  6694. let io = io::raise(&p, &native).unwrap();
  6695. let st = structure::structure(&p).unwrap();
  6696. let emitted = lower(&Parts {
  6697. native: &native,
  6698. p: &p,
  6699. st: &st,
  6700. io: &io,
  6701. res: &res,
  6702. inputs: vec![],
  6703. outputs: vec![],
  6704. prims: vec![],
  6705. mesh_stride: 0,
  6706. }).unwrap();
  6707. let container =
  6708. crate::Container::parse(&emitted.dxil).unwrap();
  6709. let features =
  6710. container.part(crate::FourCC::SFI0).unwrap();
  6711. u64::from_le_bytes(features.data.try_into().unwrap())
  6712. }
  6713. #[test]
  6714. fn perm_constant_selector_needs_no_int64() {
  6715. assert_eq!(perm_features(128) & 0x8000, 0);
  6716. }
  6717. #[test]
  6718. fn perm_dynamic_selector_needs_no_int64() {
  6719. assert_eq!(
  6720. perm_features(256) & 0x8000,
  6721. 0,
  6722. "dynamic v_perm_b32 must not require INT64"
  6723. );
  6724. }
  6725. #[test]
  6726. fn scalar_bit_tests_lower() {
  6727. // Each tests one bit of a constant into SCC and branches on it (only
  6728. // code with an effect needs its operands).
  6729. let tail = [
  6730. 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
  6731. 0xBE84_0380, // s_mov_b32 s4, 0
  6732. S_ENDPGM,
  6733. ];
  6734. let bit_tests: [&[u32]; 4] = [
  6735. &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3
  6736. &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3
  6737. &[
  6738. 0xBE80_0387, // s_mov_b32 s0, 7
  6739. 0xBE81_0380, // s_mov_b32 s1, 0
  6740. 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3
  6741. ],
  6742. &[
  6743. 0xBE80_0387, // s_mov_b32 s0, 7
  6744. 0xBE81_0380, // s_mov_b32 s1, 0
  6745. 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3
  6746. ],
  6747. ];
  6748. for head in bit_tests {
  6749. let words: Vec<u32> = head.iter().chain(&tail).copied().collect();
  6750. lowers(&words).unwrap();
  6751. }
  6752. }
  6753. #[test]
  6754. fn buffer_formats_by_number() {
  6755. // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM,
  6756. // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT.
  6757. assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm)));
  6758. assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm)));
  6759. assert_eq!(
  6760. buffer_format(50),
  6761. Some((&[10, 10, 10, 2][..], Numeric::Unorm))
  6762. );
  6763. assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float)));
  6764. assert_eq!(
  6765. buffer_format(77),
  6766. Some((&[32, 32, 32, 32][..], Numeric::Float))
  6767. );
  6768. // Invalid, past the table.
  6769. assert_eq!(buffer_format(0), None);
  6770. assert_eq!(buffer_format(78), None);
  6771. }
  6772. #[test]
  6773. fn packed_buffer_formats_by_number() {
  6774. // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43,
  6775. // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT
  6776. // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first.
  6777. assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm)));
  6778. assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float)));
  6779. assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm)));
  6780. assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float)));
  6781. assert_eq!(
  6782. buffer_format(44),
  6783. Some((&[2, 10, 10, 10][..], Numeric::Unorm))
  6784. );
  6785. assert_eq!(
  6786. buffer_format(45),
  6787. Some((&[2, 10, 10, 10][..], Numeric::Snorm))
  6788. );
  6789. assert_eq!(
  6790. buffer_format(46),
  6791. Some((&[2, 10, 10, 10][..], Numeric::Uscaled))
  6792. );
  6793. assert_eq!(
  6794. buffer_format(47),
  6795. Some((&[2, 10, 10, 10][..], Numeric::Sscaled))
  6796. );
  6797. assert_eq!(
  6798. buffer_format(48),
  6799. Some((&[2, 10, 10, 10][..], Numeric::Uint))
  6800. );
  6801. assert_eq!(
  6802. buffer_format(49),
  6803. Some((&[2, 10, 10, 10][..], Numeric::Sint))
  6804. );
  6805. }
  6806. /// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as
  6807. /// `legacyF16ToF32` widens it.
  6808. fn half(h: u32) -> f32 {
  6809. let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023);
  6810. let v = match e {
  6811. 0 => m as f32 * 2f32.powi(-24),
  6812. 31 if m == 0 => f32::INFINITY,
  6813. 31 => f32::NAN,
  6814. _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25),
  6815. };
  6816. if s == 1 { -v } else { v }
  6817. }
  6818. #[test]
  6819. fn small_floats_widen_as_halves() {
  6820. // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a
  6821. // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec.
  6822. let f11 = |x: u32| half(x << half_shift(11));
  6823. let f10 = |x: u32| half(x << half_shift(10));
  6824. assert_eq!(f11(0), 0.0);
  6825. assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal
  6826. assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal
  6827. assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal
  6828. assert_eq!(f11(0x3C0), 1.0);
  6829. assert_eq!(f11(0x3E0), 1.5);
  6830. assert_eq!(f11(0x7BF), 65024.0); // largest
  6831. assert_eq!(f11(0x7C0), f32::INFINITY);
  6832. assert!(f11(0x7C1).is_nan());
  6833. assert_eq!(f10(0x001), 2f32.powi(-19));
  6834. assert_eq!(f10(0x020), 2f32.powi(-14));
  6835. assert_eq!(f10(0x1E0), 1.0);
  6836. assert_eq!(f10(0x3DF), 64512.0);
  6837. assert_eq!(f10(0x3E0), f32::INFINITY);
  6838. assert!(f10(0x3FF).is_nan());
  6839. // A 16-bit float is a half already, sign included.
  6840. assert_eq!(half(0xBC00 << half_shift(16)), -1.0);
  6841. }
  6842. }