lower.rs 266 KB

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