lower.rs 272 KB

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