| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205 |
- //! IR to DXIL, one machine instruction at a time (decision 0003).
- //!
- //! Every register dword is an `i32` (SCC an `i1`); float operations bitcast
- //! their operands. Lane masks exist only as the per-lane booleans of
- //! structurisation; branches and guards are built from them. A value the
- //! emitter cannot express is `Missing` with a reason, and only fails the
- //! program when something with an effect (an export, a branch) needs it.
- use std::collections::{BTreeMap, HashMap, HashSet};
- use super::UserData;
- use super::bitcode::{Attr, Bin, Cast, Rmw, Tag, Term, V, pred};
- use super::container::SigElement;
- use super::shader::{Shader, flags};
- use crate::ShaderError;
- use crate::gfx10::{Dpp, Fields, NULL, Operand};
- use crate::io::{Barycentric, Export, Input, Interp, Io, Target};
- use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value};
- use crate::native::{HwStage, NativeProgram, ResourceType, RootType, StageIo, Usage, UsedResource};
- use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source};
- use crate::structure::{Atom, Bool, LaneExit, Structured};
- /// The ray-tracing node test (`image_bvh_intersect_ray`), a child module so
- /// it shares the emitter's state.
- #[path = "intersect.rs"]
- pub(super) mod intersect;
- type Why = &'static str;
- /// How an interpolation evaluates an input channel.
- #[derive(Debug, Clone, Copy)]
- enum Eval {
- /// Loaded with this DXIL interpolation mode (1: constant, P0).
- Mode(u8),
- /// From the vertex values of a constant element: P0 when `p0`, plus
- /// i (P1 - P0), plus j (P2 - P0), weights as floats.
- Weights {
- p0: bool,
- i: Option<V>,
- j: Option<V>,
- },
- }
- #[derive(Debug, Clone, Copy)]
- enum Val {
- I32(V),
- Bit(V),
- Missing(Why),
- }
- pub(crate) struct Lowered {
- pub dxil: Vec<u8>,
- /// Bit n: immediate sampler n is a comparison sampler.
- pub cmp_samplers: u64,
- pub root_cbvs: Vec<u8>,
- pub root_srvs: Vec<u8>,
- pub root_uavs: Vec<u8>,
- pub user_data: Vec<UserData>,
- pub samplers: Vec<[u32; 4]>,
- /// The wave size the shader requires of the host, if any.
- pub wave_size: Option<u32>,
- /// Heap handles made with a non-uniform index.
- #[cfg(test)]
- pub nonuniform_handles: u32,
- /// Whether the program uses wave operations.
- #[cfg(test)]
- pub wave_ops: bool,
- }
- pub(crate) struct Parts<'a> {
- pub native: &'a NativeProgram,
- pub p: &'a Program,
- pub st: &'a Structured,
- pub io: &'a Io,
- pub res: &'a Resources,
- pub inputs: Vec<SigElement>,
- pub outputs: Vec<SigElement>,
- pub prims: Vec<SigElement>,
- /// Mesh: what the group id arrives multiplied by.
- pub mesh_stride: u32,
- }
- enum Stop {
- /// A phi whose incoming value has no DXIL form was read: redo with it missing.
- Retry(Value, Why),
- Fail(ShaderError),
- }
- pub(crate) fn lower(parts: &Parts) -> Result<Lowered, ShaderError> {
- lower_counted(parts, counted_in_threads(parts))
- }
- /// Whether the title dispatches the program by a count of threads whose last
- /// group may be partial: the structure builder's programs of one dimension.
- /// Their lanes past the count must not run (they count the lanes of a wave
- /// and store). Not where a group barrier would wait for lanes that left, nor
- /// where two host waves of 32 stand for a console wave (they exchange, which
- /// takes all lanes).
- fn counted_in_threads(parts: &Parts) -> bool {
- let crate::native::StageIo::Cs(cs) = &parts.native.io else {
- return false;
- };
- cs.threads[0] > 1
- && cs.threads[1..] == [1, 1]
- && crate::spill::is_spilled(parts.native)
- && (!parts.native.wave64 || host_max_wave() >= 64)
- && !parts.p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "s_barrier")
- }
- /// [`lower`]; `counted`: the lanes past a dispatch's count of threads leave
- /// at once (`shader.rs` `USER_DISPATCH_THREADS_X`; after DexNom/VIctory
- /// bc3cd4b0, which does so for two of the programs by their digests).
- pub(super) fn lower_counted(parts: &Parts, counted: bool) -> Result<Lowered, ShaderError> {
- let mut bad = HashMap::new();
- loop {
- match Lower::new(parts, &bad).run(counted) {
- Ok(l) => return Ok(l),
- Err(Stop::Retry(v, why)) => {
- if bad.insert(v, why).is_some() {
- return Err(ShaderError::Unsupported {
- offset: 0,
- what: "a phi that does not settle",
- });
- }
- }
- Err(Stop::Fail(e)) => return Err(e),
- }
- }
- }
- const TWO_PI: f32 = std::f32::consts::TAU;
- /// `s_sendmsg` id of a mesh or NGG stage's output allocation request.
- const GS_ALLOC_REQ: u16 = 9;
- /// `s_sendmsg` id that ends a pixel wave's ordered section.
- const ORDERED_PS_DONE: u16 = 7;
- /// Hardware register (of `s_setreg_b32`) a pixel wave names its packer in
- /// before it waits for the waves it overlaps.
- const POPS_PACKER: u16 = 25;
- /// The operand `src_pops_exiting_wave_id`.
- const POPS_EXITING: u8 = 239;
- /// The instructions inside a pixel program's ordered section
- /// (primitive-ordered pixel shading, which the console compiler makes of
- /// rasterizer ordered views): from the write of `POPS_PACKER`, along every
- /// path, to the message that ends the section or the program's end. The
- /// console waits there until the waves holding earlier primitives' samples
- /// of the same pixels have left their sections; a host's rasterizer ordered
- /// views wait by themselves, at their first access. Empty for a program
- /// without such a section.
- fn ordered_section(p: &Program) -> HashSet<Site> {
- let starts = |i: &Inst| {
- i.name() == "s_setreg_b32"
- && matches!(i.fields, Fields::Sop { imm: Some(imm), .. } if imm & 0x3F == POPS_PACKER)
- };
- let ends = |i: &Inst| {
- i.name() == "s_sendmsg"
- && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == ORDERED_PS_DONE)
- };
- let mut section = HashSet::new();
- let mut entered = vec![false; p.blocks.len()];
- let mut work: Vec<Site> = p
- .blocks
- .iter()
- .enumerate()
- .flat_map(|(b, block)| {
- (0..block.insts.len())
- .filter(|&i| starts(&block.insts[i]))
- .map(move |i| (b, i))
- })
- .collect();
- while let Some((b, from)) = work.pop() {
- let block = &p.blocks[b];
- let mut done = false;
- for i in from..block.insts.len() {
- if ends(&block.insts[i]) {
- done = true;
- break;
- }
- section.insert((b, i));
- }
- if done {
- continue;
- }
- for (t, next) in p.blocks.iter().enumerate() {
- if next.preds.contains(&b) && !std::mem::replace(&mut entered[t], true) {
- work.push((t, 0));
- }
- }
- }
- section
- }
- /// The f16 bits of inline float constant `c` (240..=248: 0.5, -0.5, 1.0,
- /// -1.0, 2.0, -2.0, 4.0, -4.0, 1/(2 pi)).
- fn inline_f16(c: u8) -> u32 {
- [
- 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118,
- ][usize::from(c - 240)]
- }
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
- enum Numeric {
- Unorm,
- Snorm,
- Uscaled,
- Sscaled,
- Uint,
- Sint,
- Float,
- }
- /// A GFX10 buffer format (the unified format of typed buffer loads): the
- /// channel widths from the lowest bits up, and how the channels convert.
- /// Formats are numbered in families (`8`, `16`, `8_8`, ...: AMD names
- /// list channels from the highest bits), each with its numeric formats in
- /// the order unorm, snorm, uscaled, sscaled, uint, sint, float.
- fn buffer_format(format: u8) -> Option<(&'static [u32], Numeric)> {
- use Numeric::*;
- const NORM: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint];
- const ALL: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint, Float];
- const WIDE: &[Numeric] = &[Uint, Sint, Float];
- // Numbers and order from LLVM's `UfmtGFX10` (`SIDefines.h`); the GFX10
- // buffer formats have no 5_9_9_9. Channel order from Mesa
- // (`ac_formats.c`): R11G11B10_FLOAT is 10_11_11, and 10_10_10_2 has
- // its 2-bit channel in the lowest bits.
- const FAMILIES: [(&[u32], &[Numeric]); 14] = [
- (&[8], NORM),
- (&[16], ALL),
- (&[8, 8], NORM),
- (&[32], WIDE),
- (&[16, 16], ALL),
- (&[11, 11, 10], ALL), // 10_11_11
- (&[10, 11, 11], ALL), // 11_11_10
- (&[2, 10, 10, 10], NORM), // 10_10_10_2
- (&[10, 10, 10, 2], NORM), // 2_10_10_10
- (&[8, 8, 8, 8], NORM),
- (&[32, 32], WIDE),
- (&[16, 16, 16, 16], ALL),
- (&[32, 32, 32], WIDE),
- (&[32, 32, 32, 32], WIDE),
- ];
- let mut n = usize::from(format.checked_sub(1)?);
- for (bits, numerics) in FAMILIES {
- if n < numerics.len() {
- return Some((bits, numerics[n]));
- }
- n -= numerics.len();
- }
- None
- }
- /// How far a float channel of `width` bits (16, or the unsigned 11- and
- /// 10-bit floats of the packed formats) shifts up to be a half:
- /// the small floats are a half's exponent (5 bits, biased 15) and the top
- /// of its mantissa, without the sign, so `legacyF16ToF32` widens them
- /// exactly, denormals, infinities and NaNs included.
- fn half_shift(width: u32) -> u32 {
- debug_assert!(matches!(width, 10 | 11 | 16), "{width}-bit float");
- if width == 16 { 0 } else { 15 - width }
- }
- struct Lower<'a> {
- s: Shader,
- x: &'a Parts<'a>,
- bad: &'a HashMap<Value, Why>,
- lane_fail: HashMap<Value, Why>,
- vals: HashMap<Value, Val>,
- floats: HashMap<Value, V>,
- /// DXIL block per IR block (unreachable: none).
- block: Vec<Option<usize>>,
- cur: usize,
- bools: HashMap<(usize, Bool), V>,
- lane_bits: HashMap<Value, V>,
- /// IR phi location by value.
- phi_at: HashMap<Value, (usize, usize)>,
- /// Descriptor dwords with no host value (addresses, formats, all of a constant
- /// buffer's): no program reads them as numbers ([`Self::dead`]).
- stale: HashSet<Value>,
- /// See [`ordered_section`] (pixel programs).
- ordered: HashSet<Site>,
- /// Raw UAV buffers (see [`Lower::entry`]) the program loads from past its
- /// wave's cache (GLC): other groups write what it waits for. On the host
- /// they are globally coherent; a load in a loop that only waits would
- /// be made once otherwise.
- coherent: HashSet<(usize, u32)>,
- /// In the instruction being lowered: the host copy its root view's bytes
- /// are in ([`Lower::root_memory`]).
- root_copy: Option<V>,
- /// Whether the page [`Lower::memory`] last looked for has a copy.
- page_there: Option<V>,
- mask_phis: HashMap<Value, V>,
- pending_masks: Vec<(V, usize, usize)>,
- data_phis: Vec<(V, usize, usize)>,
- read_phis: HashSet<Value>,
- params: HashMap<Value, (usize, u32)>,
- user_data: Option<V>,
- user_reads: BTreeMap<u32, UserData>,
- samplers: Vec<[u32; 4]>,
- descriptors: HashMap<(Site, bool), &'a Source>,
- scalar: HashMap<Site, Address>,
- exports: HashMap<Site, &'a Export>,
- interps: HashMap<Site, &'a Interp>,
- handles: HashMap<(usize, Site, u8, bool, (u32, u32)), V>,
- /// Element strides read from the host's table by heap slot
- /// ([`super::shader::SLOT_STRIDES`]), by block and descriptor load.
- strides: HashMap<(usize, Site, u8), V>,
- /// Blocks splitting the edge from one IR block to another.
- edges: HashMap<(usize, usize), usize>,
- /// Per IR block: a `done` export is behind every lane entering it.
- exported: Vec<bool>,
- /// Reverse-postorder index per IR block.
- rpo: Vec<usize>,
- /// DXIL block each IR block ends in (guarded stores split blocks).
- tail: Vec<Option<usize>>,
- /// The program writes UAVs: barriers fence them too.
- writes_uavs: bool,
- /// src0 of the current instruction as DPP fetched it.
- src0: Option<V>,
- /// Compute code that reads other lanes: thread ids follow the host
- /// lanes, so lane n is console lane n.
- console_lanes: bool,
- /// Mesh: the thread index in the group (made in the entry block).
- flat: Option<V>,
- /// Mesh: IR blocks whose `s_barrier` is left out.
- no_barrier: HashSet<usize>,
- /// IR blocks whose `s_barrier` not every lane is sure to reach (a lane
- /// branch lies between the entry and the block, or the program has a
- /// loop a lane can be cut out of): the barrier there keeps its fences
- /// and does not wait for the group ([`super::group_sync`]).
- fence_only: HashSet<usize>,
- /// A group barrier before every LDS access (a console wave run as two host waves).
- split_lds: bool,
- /// With `split_lds`, LDS accesses in lane branches: per IR block whether every lane runs
- /// it, and whether the host waves meet at its start and before its exit ([`lds_meetings`]).
- lds_meet: Option<(Vec<bool>, Vec<(bool, bool)>)>,
- /// A console wave64 program run as two host waves of 32 that exchange through LDS: the first
- /// of two exchange dwords, whether the group has no upper half (32 threads or fewer), and per
- /// IR block whether every lane runs it (exchanges need both halves there).
- exchange: Option<(u32, bool, Vec<bool>)>,
- /// With `exchange`: nothing is exchanged, each host wave acts as a wave
- /// of its own ([`with_local_waves`]).
- local: bool,
- /// The instruction being lowered may read a lane mask as a number under
- /// `local` (a bit count, a first set bit, `v_mbcnt`).
- local_ok: bool,
- /// With `local`: every mask read and lane read is taken per host wave
- /// ([`with_local_waves_any`]).
- local_any: bool,
- /// With `exchange`: VGPR values every lane holds alike ([`lane_uniform`]); a first-lane
- /// read of one needs nothing from the other host wave.
- uniform: HashSet<Value>,
- /// With `exchange`: the wave ORs that only steer a loop over each lane's own bits, which
- /// a host wave takes over its own lanes wherever they stand ([`super::own_bits`]).
- own_bits: super::own_bits::OwnBits,
- /// The console lane (0..63) of this thread, made in the entry block.
- clane: Option<V>,
- /// The first exchange dword of this thread's console wave ([`Self::exchange_pair`]).
- pair: Option<V>,
- /// A console wave64 program in host waves of 32: the LDS dword counting the console threads
- /// handed to host waves (`wave_base`), and the base made in the entry block.
- halves: Option<u32>,
- wave_base: Option<V>,
- /// Vertex and mesh outputs holding 16-bit values: row, whether two per
- /// dword, and the row packed after it.
- half_outputs: HashMap<u8, (bool, Option<u8>)>,
- /// How lane masks become data.
- mask_data: MaskData,
- /// The instruction being lowered may read lane masks as data.
- mask_ok: bool,
- /// Ballots of masks read as data, by low dword: (low, high).
- ballots: HashMap<Value, (V, V)>,
- /// Masks whose ballot is being built: a mask whose lane bit needs its
- /// own value as a number (an opaque mask keyed by a dword it shares
- /// with another) would otherwise recurse until the stack overflows.
- balloting: HashSet<Value>,
- /// Block writing each value.
- def_block: HashMap<Value, usize>,
- /// IR block being lowered.
- cur_ir: usize,
- /// Whole-wave sections by block and start index.
- sections: HashMap<usize, HashMap<usize, super::wave::Section>>,
- /// Values written in a section that code outside it reads.
- section_out: HashSet<Value>,
- /// The program's constant table (the code from the first byte read
- /// through `s_getpc_b64` on): global, first byte, dwords.
- code_table: Option<(V, u32, u32)>,
- /// Loop headers' iteration counters (see [`LOOP_LIMIT`]): the phi by
- /// IR block, and its incoming (value, DXIL block) pairs.
- counters: HashMap<usize, (V, Vec<(V, usize)>)>,
- /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from.
- abort: Option<usize>,
- }
- /// Iterations after which a loop is left (per entry into it), unless
- /// [`super::loop_limit`] says otherwise. The console runs a loop as long as
- /// its data says; data the host has not mirrored yet (a null view reads
- /// zeros) can make that four billion iterations, which hangs the host GPU
- /// until the driver resets it. A lane that reaches the limit leaves the
- /// program as killed (a pixel discards).
- // shortcut: a genuine loop of more iterations than this is cut short too.
- pub(super) const LOOP_LIMIT: u32 = 1 << 20;
- /// Lane masks read as numbers (`s_bcnt1`, `s_ff1`, `v_mbcnt`, scalar
- /// compares, bit tests) are ballots of the lanes' booleans, taken where the
- /// mask is written: structurisation's `active` masks hold only lanes that
- /// reach that block, so the ballot misses none.
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
- enum MaskData {
- /// Compute: host lane n is console lane n (the program declares the
- /// console's wave size), so ballots are the console's masks bit for bit
- /// and any use is exact.
- Console,
- /// Pixel and vertex programs: ballots over the host's wave, whatever its
- /// size. Only uses that mean the same on any wave are allowed: counts,
- /// the first lane, the count below a lane, equality (the HLSL wave
- /// operations the console compiler expands). Lane numbers stay host
- /// lanes throughout (`v_mbcnt`, `v_readlane` at a computed lane).
- Host,
- /// Mesh programs: their lanes and waves (LDS per console wave) are the
- /// console's but no host wave size can be declared.
- None,
- }
- /// What a value holding a lane mask read as a number stops with.
- pub(super) const LANE_MASK: Why = "a lane mask read as data";
- /// A mask with lanes outside EXEC where it is written, read as a number where the lanes that
- /// run that block are not all of the wave.
- pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data";
- /// Instructions that read a lane mask (not EXEC implicitly, not a lane's
- /// bit) as a number.
- /// Per IR block: every lane of the wave that started the program runs it – no per-lane branch
- /// separates it from the entry (it lies in no lane branch's region: the blocks reachable from
- /// the branch that do not post-dominate it). None with an indirect exit (not followed).
- fn all_lane_blocks(st: &Structured) -> Option<Vec<bool>> {
- let n = st.exits.len();
- let mut all = vec![true; n];
- for (_, region) in lane_regions(st)? {
- for b in (0..n).filter(|&b| region[b]) {
- all[b] = false;
- }
- }
- Some(all)
- }
- /// Every per-lane branch (by its block) with its region: the blocks reachable from it that do
- /// not post-dominate it, which only some lanes run. Not the branches the wave takes together
- /// ([`Structured::wide`]), nor those on scalar conditions. None with an indirect exit.
- fn lane_regions(st: &Structured) -> Option<Vec<(usize, Vec<bool>)>> {
- let n = st.exits.len();
- let mut succ: Vec<Vec<usize>> = vec![Vec::new(); n];
- for (b, e) in st.exits.iter().enumerate() {
- match *e {
- LaneExit::Jump(t) => succ[b].push(t),
- LaneExit::Branch { taken, not_taken, .. } => {
- succ[b].push(taken);
- succ[b].push(not_taken);
- }
- LaneExit::End => {}
- LaneExit::Indirect => return None,
- }
- }
- // post-dominators (bitsets; a virtual exit after every End)
- let words = n.div_ceil(64);
- let full = vec![u64::MAX; words];
- let mut pdom: Vec<Vec<u64>> = (0..n).map(|b| if succ[b].is_empty() { let mut v = vec![0; words]; v[b / 64] |= 1 << (b % 64); v } else { full.clone() }).collect();
- let mut changed = true;
- while changed {
- changed = false;
- for b in (0..n).rev() {
- if succ[b].is_empty() {
- continue;
- }
- let mut v = full.clone();
- for &t in &succ[b] {
- for w in 0..words {
- v[w] &= pdom[t][w];
- }
- }
- v[b / 64] |= 1 << (b % 64);
- if v != pdom[b] {
- pdom[b] = v;
- changed = true;
- }
- }
- }
- let mut regions = Vec::new();
- for (d, e) in st.exits.iter().enumerate() {
- let LaneExit::Branch { when, .. } = *e else { continue };
- if st.wide.contains(&d) || st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) {
- continue; // a wave-wide or uniform branch: all lanes go the same way
- }
- // blocks reachable from the lane branch that do not post-dominate it
- let mut seen = vec![false; n];
- let mut stack: Vec<usize> = succ[d].clone();
- while let Some(b) = stack.pop() {
- if seen[b] || pdom[d][b / 64] >> (b % 64) & 1 == 1 {
- continue;
- }
- seen[b] = true;
- stack.extend(succ[b].iter().copied());
- }
- regions.push((d, seen));
- }
- Some(regions)
- }
- /// The per-lane branches (by block) whose regions hold a block of `needs` (blocks where two
- /// host waves must meet, [`take_needs`]): the ones to take wave-wide
- /// ([`crate::structure::structure_wide`]) so that every lane runs those blocks. None if one
- /// of them is a branch whose wave-wide meaning is not known ([`Structured::wave_any`]).
- pub(super) fn branches_around(st: &Structured, needs: &[usize]) -> Option<Vec<usize>> {
- let mut out = Vec::new();
- for (d, region) in lane_regions(st)? {
- if needs.iter().any(|&b| region.get(b).copied().unwrap_or(false)) {
- st.wave_any.get(d).copied().flatten()?;
- out.push(d);
- }
- }
- Some(out)
- }
- /// Whether a refusal is of code that needs every lane of the wave where it stands (two host
- /// waves meeting there), which the other forms of the program may give it.
- pub(super) fn needs_every_lane(what: &str) -> bool {
- what.ends_with("where not every lane runs") || what == MASK_ELSEWHERE
- }
- /// The blocks where the last lowering on this thread wanted every lane and did not have it
- /// (its "... where not every lane runs" refusals), which it forgets.
- pub(super) fn take_needs() -> Vec<usize> {
- NEEDS.take()
- }
- fn need(block: usize) {
- NEEDS.with_borrow_mut(|n| {
- if !n.contains(&block) {
- n.push(block);
- }
- });
- }
- /// VGPR values that are the same in every lane holding them (`all` is [`all_lane_blocks`]):
- /// written by an instruction every arriving lane runs (no guard), lane by lane, from scalars,
- /// constants and such values; or loaded from an address made of them. The compiler keeps
- /// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`.
- /// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes
- /// run (no lane branch can have split the arriving lanes); loop-carried values never do.
- fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet<Value> {
- let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
- let mut same: HashSet<Value> = HashSet::new();
- for b in crate::ir::reverse_postorder(&p.blocks) {
- let block = &p.blocks[b];
- let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false));
- for phi in &block.phis {
- if matches!(phi.reg, Reg::V(_)) && whole && phi.args.iter().all(|a| same.contains(a)) {
- same.insert(phi.value);
- }
- }
- for (i, inst) in block.insts.iter().enumerate() {
- let name = inst.name();
- let ops: Vec<Operand> = match &inst.fields {
- Fields::Valu(v)
- if v.dpp.is_none()
- && v.sdwa.is_none()
- && !name.starts_with("v_mbcnt")
- && !name.starts_with("v_cmpx")
- && !name.contains("lane") =>
- {
- v.src.clone()
- }
- _ => continue,
- };
- if st.guards[b][i].is_some() {
- continue; // lanes outside EXEC keep another value
- }
- let alike = ops.iter().all(|op| match *op {
- Operand::Vector { reg, .. } => {
- // every dword of the operand the instruction reads from that register on
- let read: Vec<Value> =
- inst.reads.iter().filter(|r| matches!(r.0, Reg::V(x) if x >= reg)).map(|r| r.1).collect();
- !read.is_empty() && read.iter().all(|x| same.contains(x))
- }
- // a scalar is one value; a lane mask is not, unless a compare of such values made it
- Operand::Scalar { code, .. } if code != NULL => {
- inst.read(Reg::S(code)).is_none_or(|x| !is_mask(x) || same.contains(&x))
- }
- _ => true,
- });
- if alike {
- same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1));
- }
- }
- }
- same
- }
- /// What a register value holds, for [`wave_local`].
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
- enum Wave {
- /// Nothing that depends on how the threads are divided into waves.
- Plain,
- /// The number of the wave's first lane in a mask (`s_ff1`).
- First,
- /// A reduction over the wave's lanes: a count, a sum, a minimum...
- Total(super::wave::Op),
- /// A count or sum over the lanes below this one.
- Prefix,
- /// Derived from what a first-lane atomic returned: the slots the wave reserved.
- Base,
- /// A mix the idiom does not make.
- Mixed,
- }
- /// Whether a console wave64 program may run with each host wave as a wave of its own
- /// ([`with_local_waves`]): its wave-wide values are used only as the allocation idiom uses
- /// them, which does not care how the threads are divided into waves. A first-lane number only
- /// picks the first lane; a count or sum only goes into that lane's atomic on a shared counter;
- /// a prefix only goes onto the base that atomic returned; the first lane does nothing else.
- /// Anything else done with them takes one wave to be the whole thread group (a tile's result,
- /// say) and is refused, with the offset and what was found.
- /// Lane masks read as numbers by other instructions and lane reads outside whole-wave sections
- /// are stopped by the lowering itself.
- // shortcut: `v_readfirstlane` of a value that differs between lanes is taken as it is (this
- // host wave's first lane), and a guarded write of a plain value over a wave-dependent one is
- // the only mix of old and new lanes that is looked at.
- pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'static str)> {
- use super::wave::{Op, Shape};
- const FIRST: Why = "a wave's first-lane number used as data";
- const TOTAL: Why = "a count or sum over the wave used as data";
- const PREFIX: Why = "a count or sum over the lanes below used without a reserved base";
- const MIXED: Why = "a value that depends on the wave on some paths only";
- const EFFECT: Why = "a write by the wave's first lane other than its reservation";
- fn of(kind: &HashMap<Value, Wave>, v: Option<Value>) -> Wave {
- v.and_then(|v| kind.get(&v).copied()).unwrap_or(Wave::Plain)
- }
- fn put(kind: &mut HashMap<Value, Wave>, v: Value, k: Wave) {
- if k == Wave::Plain {
- kind.remove(&v);
- } else {
- kind.insert(v, k);
- }
- }
- let wild = |k: Wave| !matches!(k, Wave::Plain | Wave::Base);
- let why = |k: Wave| match k {
- Wave::First => FIRST,
- Wave::Total(_) => TOTAL,
- Wave::Prefix => PREFIX,
- _ => MIXED,
- };
- // a mask (by its low dword) under which only a wave's first lane runs
- let first_mask = |firsts: &HashSet<Value>, m: Option<Value>| {
- m.and_then(|m| st.masks.get(&m)).is_some_and(|&b| {
- st.bools
- .support(b)
- .iter()
- .any(|a| matches!(a, Atom::Lane(v) if firsts.contains(v)))
- })
- };
- // One instruction outside a section: the kind of what it writes, and whether it is a
- // first lane's reservation.
- let step = |inst: &Inst, kind: &HashMap<Value, Wave>, firsts: &mut HashSet<Value>| -> Result<(Wave, bool), Why> {
- let name = inst.name();
- let val = |op: &Operand| match *op {
- Operand::Vector { reg, .. } => inst.read(Reg::V(reg)),
- Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)),
- _ => None,
- };
- let ops: Vec<Operand> = match &inst.fields {
- Fields::Valu(v) => v.src.clone(),
- Fields::Sop { dst, src, .. } => {
- let mut o = src.clone();
- if matches!(name, "s_addk_i32" | "s_mulk_i32") {
- o.extend(dst.iter().copied());
- }
- o
- }
- Fields::Buffer { data, .. } if name.contains("_atomic_") || name.contains("_store_") => {
- data.iter().copied().collect()
- }
- _ => Vec::new(),
- };
- let kinds: Vec<Wave> = ops.iter().map(|o| of(kind, val(o))).collect();
- // Everything else it reads (addresses, descriptors, SCC, the high dwords of wide
- // operands) must not depend on the wave. Not EXEC, and not the old value of a VGPR it
- // writes, which only the lanes outside EXEC keep.
- let named: Vec<Value> = ops.iter().filter_map(&val).collect();
- for &(r, v) in &inst.reads {
- let kept = matches!(r, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == r);
- if matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) || kept || named.contains(&v) {
- continue;
- }
- let k = of(kind, Some(v));
- if wild(k) {
- return Err(why(k));
- }
- }
- let w = kinds.iter().copied().find(|&k| wild(k)).unwrap_or(Wave::Mixed);
- let sum = |k: Wave| k == Wave::Total(Op::AddU);
- let is_mask = |o: &Operand| {
- val(o).is_some_and(|v| st.masks.contains_key(&v) || st.highs.contains_key(&v))
- };
- let mut reserved = false;
- let out = match (name, &kinds[..]) {
- ("s_ff1_i32_b64" | "s_ff1_i32_b32", _) if ops.first().is_some_and(is_mask) => Wave::First,
- ("s_bcnt1_i32_b64" | "s_bcnt1_i32_b32", _) if ops.first().is_some_and(is_mask) => {
- Wave::Total(Op::AddU)
- }
- // bits of a mask below the lane; with -1 for the mask, the lane's number
- ("v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32", [_, b]) => {
- match (matches!(ops[0], Operand::Scalar { .. }), *b) {
- (_, Wave::Prefix) | (true, Wave::Plain | Wave::Base) => Wave::Prefix,
- (false, Wave::Plain | Wave::Base) => Wave::Plain,
- (_, k) => return Err(why(k)),
- }
- }
- // nothing wave-dependent goes in; what derives from a reserved base stays marked
- _ if !kinds.iter().any(|&k| wild(k)) => {
- let derives = matches!(inst.fields, Fields::Valu(_) | Fields::Sop { .. });
- if derives && kinds.contains(&Wave::Base) { Wave::Base } else { Wave::Plain }
- }
- ("v_mov_b32" | "s_mov_b32", [k]) => *k,
- ("v_cmp_eq_i32" | "v_cmp_eq_u32" | "v_cmpx_eq_i32" | "v_cmpx_eq_u32", [a, b]) => {
- // the lane whose own number is the first lane's
- let lane = match (*a, *b) {
- (Wave::First, k) if !wild(k) => &ops[1],
- (k, Wave::First) if !wild(k) => &ops[0],
- _ => return Err(why(w)),
- };
- if !matches!(lane, Operand::Vector { .. }) {
- return Err(FIRST);
- }
- let mask = match &inst.fields {
- _ if name.starts_with("v_cmpx") => inst.write(Reg::S(EXEC)),
- Fields::Valu(v) => match v.dst {
- Some(Operand::Scalar { code, .. }) => inst.write(Reg::S(code)),
- _ => None,
- },
- _ => None,
- };
- firsts.extend(mask);
- Wave::Plain
- }
- ("v_add_nc_u32" | "s_add_i32", [a, b]) => match (*a, *b) {
- (Wave::Prefix, Wave::Base) | (Wave::Base, Wave::Prefix) => Wave::Base,
- (Wave::Prefix, Wave::Plain | Wave::Prefix) | (Wave::Plain, Wave::Prefix) => Wave::Prefix,
- (x, y) if sum(x) && sum(y) => x,
- _ => return Err(why(w)),
- },
- ("v_sub_nc_u32" | "s_sub_i32", [a, b]) => match (*a, *b) {
- (Wave::Base, Wave::Prefix) => Wave::Base,
- (Wave::Prefix, Wave::Plain) => Wave::Prefix,
- (Wave::Plain, y) if sum(y) && matches!(ops[0], Operand::Const(128)) => y,
- _ => return Err(why(w)),
- },
- ("s_mul_i32" | "v_mul_lo_u32" | "v_mul_u32_u24", [a, b]) => match (*a, *b) {
- (x, Wave::Plain) | (Wave::Plain, x) if sum(x) || x == Wave::Prefix => x,
- _ => return Err(why(w)),
- },
- ("s_lshl_b32", [x, Wave::Plain]) | ("v_lshlrev_b32", [Wave::Plain, x])
- if sum(*x) || *x == Wave::Prefix =>
- {
- *x
- }
- ("v_lshl_add_u32", [Wave::Prefix, Wave::Plain, c]) if !wild(*c) => {
- if *c == Wave::Base { Wave::Base } else { Wave::Prefix }
- }
- // the reservation: the first lane adds its wave's total to a shared counter
- (_, [Wave::Total(op)]) if name.contains("_atomic_") => {
- let want = match op {
- Op::AddU => "buffer_atomic_add",
- Op::MinU => "buffer_atomic_umin",
- Op::MaxU => "buffer_atomic_umax",
- Op::MinI => "buffer_atomic_smin",
- Op::MaxI => "buffer_atomic_smax",
- Op::Or => "buffer_atomic_or",
- Op::And => "buffer_atomic_and",
- Op::Xor => "buffer_atomic_xor",
- _ => "",
- };
- if name != want || !first_mask(firsts, inst.read(Reg::S(EXEC))) {
- return Err(TOTAL);
- }
- reserved = true;
- Wave::Base
- }
- _ => return Err(why(w)),
- };
- Ok((out, reserved))
- };
- let sections: Vec<_> = (0..p.blocks.len()).map(|b| super::wave::sections(p, b)).collect();
- let order = crate::ir::reverse_postorder(&p.blocks);
- let pass = |kind: &mut HashMap<Value, Wave>, firsts: &mut HashSet<Value>, check: bool| -> Result<(), (usize, Why)> {
- for &b in &order {
- let block = &p.blocks[b];
- for phi in &block.phis {
- let mut k = Wave::Plain;
- for (n, &a) in phi.args.iter().enumerate() {
- let x = of(kind, Some(a));
- k = match (k, x) {
- _ if n == 0 => x,
- (k, x) if k == x => k,
- (Wave::Plain, m @ (Wave::Base | Wave::Prefix))
- | (m @ (Wave::Base | Wave::Prefix), Wave::Plain) => m,
- _ => Wave::Mixed,
- };
- }
- put(kind, phi.value, k);
- }
- for (i, inst) in block.insts.iter().enumerate() {
- // inside a whole-wave section: what the simulation found each value to be
- if let Some((_, sec)) = sections[b].iter().find(|(s, sec)| i > **s && i < sec.end) {
- for &(_, w) in &inst.writes {
- let k = match sec.shapes.get(&w) {
- None => Wave::Mixed,
- Some(&Shape::K(_)) => Wave::Plain,
- Some(&Shape::Value(v)) => of(kind, Some(v)),
- Some(&Shape::Masked(src, _, _)) => of(kind, Some(src)),
- Some(&Shape::Active(op, src, mask, _)) => match of(kind, Some(src)) {
- Wave::Plain | Wave::Base => Wave::Total(op),
- // the first lane's own sum of a total is that total
- Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => Wave::Total(op),
- _ => Wave::Mixed,
- },
- Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => match of(kind, Some(src)) {
- Wave::Plain | Wave::Base => Wave::Prefix,
- Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => Wave::Prefix,
- _ => Wave::Mixed,
- },
- Some(_) => Wave::Mixed,
- };
- put(kind, w, k);
- }
- continue;
- }
- let name = inst.name();
- if name.starts_with("s_cbranch") {
- continue; // with the block's exit, below
- }
- let (k, reserved) = match step(inst, kind, firsts) {
- Ok(r) => r,
- Err(why) if check => return Err((inst.machine.offset, why)),
- Err(_) => (Wave::Mixed, false),
- };
- // the same test as `Lower::inst`'s `effect`
- let effect = matches!(inst.fields, Fields::Exp { .. })
- || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
- || name.contains("store")
- || name.contains("atomic")
- || matches!(inst.fields, Fields::Ds { .. })
- && !(name.starts_with("ds_read")
- || name.starts_with("ds_swizzle")
- || name.contains("permute"));
- if check && effect && !reserved && first_mask(firsts, inst.read(Reg::S(EXEC))) {
- return Err((inst.machine.offset, EFFECT));
- }
- let guarded = st.guards[b][i].is_some();
- for &(r, w) in &inst.writes {
- let mut kw = match r {
- // "some lane is counted" keeps the count's kind; any other SCC is one bit of data
- Reg::Scc if !name.starts_with("s_bcnt1") => {
- if wild(k) { Wave::Mixed } else { Wave::Plain }
- }
- _ => k,
- };
- // a guarded write leaves the old value in the lanes outside EXEC
- if guarded
- && matches!(r, Reg::V(_))
- && kw == Wave::Plain
- && matches!(of(kind, inst.read(r)), Wave::First | Wave::Total(_) | Wave::Prefix)
- {
- kw = Wave::Mixed;
- }
- put(kind, w, kw);
- }
- }
- // a branch on "some lane is counted": fine where the structure made it the lane's
- // own bit (the mask is EXEC under a scalar condition)
- if check
- && let Some(last) = block.insts.last()
- && last.name().starts_with("s_cbranch_scc")
- && let Some(scc) = last.read(Reg::Scc)
- && wild(of(kind, Some(scc)))
- {
- let own = matches!(st.exits[b], LaneExit::Branch { when, .. }
- if !st.bools.support(when).iter().any(|a| matches!(a, Atom::Uniform(v) if *v == scc)));
- if !own {
- return Err((last.machine.offset, TOTAL));
- }
- }
- }
- Ok(())
- };
- let mut kind: HashMap<Value, Wave> = HashMap::new();
- let mut firsts: HashSet<Value> = HashSet::new();
- // to a fixpoint (values carried around loops), then once more to say what is wrong
- let mut settled = false;
- for _ in 0..16 {
- let before = (kind.clone(), firsts.len());
- pass(&mut kind, &mut firsts, false)?;
- if (&before.0, before.1) == (&kind, firsts.len()) {
- settled = true;
- break;
- }
- }
- if !settled {
- return Err((0, MIXED));
- }
- pass(&mut kind, &mut firsts, true)
- }
- /// The mode of a group barrier the translation adds (host waves meeting):
- /// a wait for the group with a shared-memory fence; the fence alone with
- /// `VICTORY_GROUP_SYNC=0` ([`super::group_sync`]).
- fn meeting_mode() -> u32 {
- if super::group_sync() == 0 { 8 } else { 1 | 8 }
- }
- /// LDS accesses of a console wave run as two host waves, where some sit in blocks that only
- /// some lanes run (`all` is [`all_lane_blocks`]): per IR block, whether the host waves meet (a
- /// group barrier) at its start and before its exit. `None` if barriers cannot keep the
- /// console's order.
- ///
- /// The console runs the wave's lanes in step, so an LDS write is seen by every later read. Two
- /// host waves keep that order if they meet between any two accesses of which one writes. A
- /// barrier must be run by every thread, so it cannot stand in a lane branch's region; but
- /// every way into and out of such a region passes a block all lanes run, and the waves meet
- /// there: before the exit of an all-lane block into a region with LDS accesses, and at the
- /// start of an all-lane block entered from one. Accesses in all-lane blocks get their own
- /// barrier as before. What that cannot order is a write and a read inside one region (blocks
- /// joined without an all-lane block between them): refused.
- /// shortcut: two writes in one region are taken not to hit the same dword from both halves.
- fn lds_meetings(p: &crate::ir::Program, st: &Structured, all: &[bool]) -> Option<Vec<(bool, bool)>> {
- let n = st.exits.len();
- let succ = |b: usize| -> Vec<usize> {
- match st.exits[b] {
- LaneExit::Jump(t) => vec![t],
- LaneExit::Branch { taken, not_taken, .. } => vec![taken, not_taken],
- LaneExit::End | LaneExit::Indirect => Vec::new(),
- }
- };
- // regions: blocks not every lane runs, joined by the edges between them
- let mut region: Vec<usize> = (0..n).collect();
- fn find(region: &mut [usize], mut b: usize) -> usize {
- while region[b] != b {
- region[b] = region[region[b]];
- b = region[b];
- }
- b
- }
- for b in 0..n {
- for t in succ(b) {
- if !all[b] && !all[t] {
- let (x, y) = (find(&mut region, b), find(&mut region, t));
- region[x] = y;
- }
- }
- }
- // per region: LDS reads, LDS writes
- let mut reads = vec![false; n];
- let mut writes = vec![false; n];
- for (b, block) in p.blocks.iter().enumerate().take(n) {
- if all[b] {
- continue;
- }
- let r = find(&mut region, b);
- for i in &block.insts {
- let name = i.name();
- if !matches!(i.fields, Fields::Ds { .. }) || name.starts_with("ds_swizzle") || name.contains("permute") {
- continue;
- }
- if name.starts_with("ds_read") {
- reads[r] = true;
- } else {
- writes[r] = true;
- }
- }
- }
- if (0..n).any(|r| reads[r] && writes[r]) {
- return None;
- }
- let mut meet = vec![(false, false); n];
- for b in 0..n {
- for t in succ(b) {
- if all[b] && !all[t] {
- let r = find(&mut region, t);
- meet[b].1 |= reads[r] || writes[r];
- } else if !all[b] && all[t] {
- let r = find(&mut region, b);
- meet[t].0 |= reads[r] || writes[r];
- }
- }
- }
- Some(meet)
- }
- /// Masks held as numbers or constant lane sets in guards or lane branches: the lane tests its
- /// own bit by its console lane.
- fn lane_constant_masks(st: &Structured) -> bool {
- let whens = st.exits.iter().filter_map(|e| match *e {
- LaneExit::Branch { when, .. } => Some(when),
- _ => None,
- });
- let mut work: Vec<Bool> = st.guards.iter().flatten().flatten().copied().chain(whens).collect();
- // Through lane-mask joins too: an edge that brings a number or a constant lane set needs
- // the lane's own bit of it.
- // shortcut: masks only selects read (`v_cndmask_b32`, carries in) are not followed; such
- // a program still stops with "a constant lane mask" or "an opaque lane mask".
- let (mut seen, mut joins) = (HashSet::new(), HashSet::new());
- while let Some(g) = work.pop() {
- if !seen.insert(g) {
- continue;
- }
- for a in st.bools.support(g) {
- match a {
- Atom::Opaque(_) | Atom::Constant(_) => return true,
- Atom::Phi(id) if joins.insert(id) => {
- if let Some(edges) = st.phi_masks.get(&id) {
- work.extend(edges.iter().copied());
- }
- }
- _ => {}
- }
- }
- }
- false
- }
- /// The widest wave the host GPU runs (0: not known – no host-specific forms); see
- /// [`set_host_max_wave`].
- static HOST_MAX_WAVE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
- /// The host GPU's `WaveLaneCountMax`: 32 lets console wave64 compute programs whose cross-lane
- /// code stays inside 32-lane halves run in waves of 32 instead of being refused.
- pub fn set_host_max_wave(lanes: u32) {
- HOST_MAX_WAVE.store(lanes, std::sync::atomic::Ordering::Relaxed);
- }
- thread_local! {
- /// See [`take_needs`].
- static NEEDS: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
- /// See [`with_local_waves`].
- static LOCAL_WAVES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
- /// See [`with_local_waves_any`].
- static LOCAL_ANY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
- }
- /// As [`with_local_waves`], with every other use of a lane mask as a number
- /// and every lane read and write taken per host wave too: the program runs
- /// as it would on a console of 32-lane waves, lanes numbered 0..31 or
- /// 32..63 by half. Right for code that only relies on what HLSL's wave
- /// operations promise; a program that takes one wave to be its whole
- /// thread group gets per-half results. The last resort for programs that
- /// do not translate otherwise.
- pub(super) fn with_local_waves_any<R>(f: impl FnOnce() -> R) -> R {
- let was = LOCAL_ANY.replace(true);
- let r = with_local_waves(f);
- LOCAL_ANY.set(was);
- r
- }
- /// Runs `f` with console wave64 programs on 32-lane hosts lowered with each
- /// host wave as a wave of its own ("local"): no exchange between the two
- /// halves of a console wave, so no barriers and no need for every lane to
- /// reach the code. What HLSL's wave operations promise holds for any
- /// division of the threads into waves, and the idiom the title's compute
- /// programs use them for does not care which wave a thread is in: count or
- /// sum over the wave, the first lane reserves that many slots with an atomic
- /// add, every lane takes the base (`WaveReadLaneFirst`) plus its prefix.
- /// Each lane still gets a slot of its own; only the order differs.
- /// Only that idiom's operations are lowered this way: a lane mask read as
- /// a number by anything but a bit count, a first-set-bit or `v_mbcnt`, and
- /// lane reads and writes outside whole-wave sections, stop the translation.
- /// shortcut: where a count or sum goes is not checked. A program that uses
- /// a wave-wide result as data for the whole console wave (a tile's maximum,
- /// say, with one wave per thread group) gets its half's result. It is used
- /// only for programs that do not translate otherwise.
- pub(super) fn with_local_waves<R>(f: impl FnOnce() -> R) -> R {
- let was = LOCAL_WAVES.replace(true);
- let r = f();
- LOCAL_WAVES.set(was);
- r
- }
- /// `VICTORY_F16_NEAREST=1`: the results of 16-bit float operations (`v_add_f16`,
- /// `v_mul_f16`, `v_cvt_f16_f32` ...) are rounded to nearest as the console rounds them
- /// ([`Lower::f16_nearest`]) instead of as the host's `f32tof16` does (toward zero on NVIDIA:
- /// the last place of a result that is not exact is then one lower than the console's).
- /// Off by default: it is exact but untried in a game run, and adds instructions to every
- /// such operation. The wave sum of 16-bit floats ([`Lower::half_sum`]) is always exact.
- fn f16_nearest_on() -> bool {
- #[cfg(test)]
- if let Some(on) = TEST_F16_NEAREST.get() {
- return on;
- }
- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
- *ON.get_or_init(|| std::env::var_os("VICTORY_F16_NEAREST").is_some_and(|v| v == "1"))
- }
- #[cfg(test)]
- thread_local! {
- /// A test's choice for [`f16_nearest_on`], for its thread only.
- pub(super) static TEST_F16_NEAREST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
- }
- /// `VICTORY_WAVE_OWN_BITS=0`: a wave OR where not every lane runs is refused as before
- /// ([`super::own_bits`]).
- fn own_bits_on() -> bool {
- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
- *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0"))
- }
- /// What the translator was told of the host, for a cache's key: the widest
- /// wave, the view heap's limit and where the raw twins of its views start.
- pub fn host_settings() -> [u32; 3] {
- [host_max_wave(), super::shader::view_heap_limit(), super::shader::raw_views()]
- }
- /// The refusal of a first half of an interpolation whose result is read
- /// as data ([`Lower::interp`]).
- pub(super) const FIRST_HALF: &str = "the first half of an interpolation";
- thread_local! {
- /// Whether first halves of interpolations are evaluated as the pair
- /// they start ([`with_first_half_pairs`]).
- static FIRST_HALF_PAIRS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
- }
- /// Runs `translate` with first halves of interpolations evaluated as the
- /// pair they start: the translation of a program refused with
- /// [`FIRST_HALF`] (`VICTORY_FIRST_HALF=0`: refused again, as before).
- pub(super) fn with_first_half_pairs<R>(translate: impl FnOnce() -> R) -> R {
- let before = FIRST_HALF_PAIRS.replace(true);
- let result = translate();
- FIRST_HALF_PAIRS.set(before);
- result
- }
- pub(super) fn host_max_wave() -> u32 {
- #[cfg(test)]
- if let Some(lanes) = TEST_HOST_WAVE.get() {
- return lanes;
- }
- HOST_MAX_WAVE.load(std::sync::atomic::Ordering::Relaxed)
- }
- #[cfg(test)]
- thread_local! {
- /// A test's host wave size, for its thread only ([`set_host_max_wave`] is the process's).
- pub(super) static TEST_HOST_WAVE: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
- }
- pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool {
- let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
- let ops: Vec<&Operand> = match &i.fields {
- // A mask operation (its result a mask) is no data use.
- Fields::Sop { .. }
- if i.writes
- .iter()
- .any(|&(r, w)| matches!(r, Reg::S(_)) && is_mask(w)) =>
- {
- return false;
- }
- Fields::Sop { src, .. } => src.iter().collect(),
- Fields::Valu(v)
- if !matches!(i.name(), "v_cndmask_b32") && !i.name().contains("_co_ci_") =>
- {
- v.src.iter().collect()
- }
- _ => return false,
- };
- ops.into_iter().any(|op| match *op {
- Operand::Scalar { code, .. } if code != NULL => i.read(Reg::S(code)).is_some_and(is_mask),
- _ => false,
- })
- }
- /// The parameters packing 16-bit rows two per dword and where each lays
- /// its elements out: (first row, [(dword, register, column, columns)]).
- ///
- /// The console gives every 16-bit element whole dwords. A parameter leads
- /// with the first element of its first row, then the first element of its
- /// second row. An element that shares a register behind another one (the
- /// signature packs a short element into the free columns of an earlier
- /// register) is NOT in that row's halves: it follows in the first
- /// parameter, in row order, that has whole dwords left.
- /// The title's packed pedestrian shaders show both cases: TEXCOORD7 (register 1,
- /// columns 2-3, behind the two columns of TEXCOORD0) is exported in dword 3
- /// of parameter 0, after TEXCOORD1's two dwords; TEXCOORD6 (register 4,
- /// column 3, behind the three columns of TEXCOORD4) in dword 3 of
- /// parameter 3, after TEXCOORD5 and TEXCOORD7, while the high half of
- /// TEXCOORD4's second dword stays zero.
- type PackedLayout = Vec<(u8, Vec<(u8, u8, u8, u8)>)>;
- fn packed_layout(elements: &[SigElement], packs: &[(u8, Option<u8>)]) -> PackedLayout {
- let of_row = |r: u8| {
- let mut of: Vec<&SigElement> = elements
- .iter()
- .filter(|e| e.row == Some(u32::from(r)))
- .collect();
- of.sort_by_key(|e| e.col);
- of
- };
- let mut packs = packs.to_vec();
- packs.sort_unstable();
- packs.dedup_by_key(|p| p.0);
- // Per parameter: its first row, the dwords used, the elements.
- let mut layout: Vec<(u8, u8, Vec<(u8, u8, u8, u8)>)> = Vec::new();
- let mut behind = Vec::new();
- for &(a, b) in &packs {
- let mut placed = Vec::new();
- let mut at = 0u8;
- if !of_row(a).is_empty() {
- for r in [Some(a), b].into_iter().flatten() {
- let of = of_row(r);
- let Some((lead, more)) = of.split_first() else {
- continue;
- };
- placed.push((at, r, lead.col, lead.cols));
- at += lead.cols.div_ceil(2);
- behind.extend(more.iter().map(|e| (r, e.col, e.cols)));
- }
- }
- layout.push((a, at, placed));
- }
- behind.sort_unstable();
- for (r, col, cols) in behind {
- let need = cols.div_ceil(2);
- if let Some(p) = layout.iter_mut().find(|p| p.1 + need <= 4) {
- p.2.push((p.1, r, col, cols));
- p.1 += need;
- }
- }
- layout.into_iter().map(|(a, _, of)| (a, of)).collect()
- }
- /// Where half `h` (dword h / 2, the high half when odd) of the parameter
- /// whose first 16-bit row is `a` comes from: a register and column of
- /// `elements`, none for padding ([`packed_layout`]; `packs` lists every
- /// parameter packing two 16-bit rows per dword).
- fn packed_half(
- elements: &[SigElement],
- packs: &[(u8, Option<u8>)],
- a: u8,
- h: u8,
- ) -> Option<(u8, u8)> {
- let layout = packed_layout(elements, packs);
- let (_, of) = layout.iter().find(|p| p.0 == a)?;
- of.iter().find_map(|&(dword, row, col, cols)| {
- let k = h.checked_sub(2 * dword)?;
- (k < cols).then_some((row, col + k))
- })
- }
- /// The pixel inputs packing two 16-bit rows per dword, as (first row,
- /// second row) ([`packed_layout`]).
- fn input_packs(io: &StageIo, inputs: &[SigElement]) -> Vec<(u8, Option<u8>)> {
- let StageIo::Ps {
- inputs: entries, ..
- } = io
- else {
- return Vec::new();
- };
- let partners = half_input_partners(io, inputs);
- entries
- .iter()
- .filter(|i| i.fp16 && i.pack2)
- .map(|i| {
- let b = if i.row2 != i.row {
- Some(i.row2)
- } else {
- partners.get(&i.row).copied()
- };
- (i.row, b)
- })
- .collect()
- }
- /// Vertex or mesh outputs of 16-bit values (see [`Lower::half_outputs`]):
- /// a packed row's partner is the next 16-bit row of the signature that no
- /// output entry names, taken in row order.
- fn half_outputs(io: &StageIo, outputs: &[SigElement]) -> HashMap<u8, (bool, Option<u8>)> {
- let entries = match io {
- StageIo::Vs { outputs, .. } => outputs,
- StageIo::Ms(ms) => &ms.outputs,
- _ => return HashMap::new(),
- };
- let per_vertex = || entries.iter().filter(|o| o.param & 0x80 == 0);
- let mut free: Vec<u8> = outputs
- .iter()
- .filter(|e| e.half && e.kind == 0)
- .filter_map(|e| u8::try_from(e.row?).ok())
- .filter(|&r| !per_vertex().any(|o| o.row == r))
- .collect();
- free.sort_unstable();
- free.dedup();
- let mut halves: Vec<_> = per_vertex().filter(|o| o.fp16).collect();
- halves.sort_by_key(|o| o.row);
- halves
- .into_iter()
- .map(|o| {
- let b = o
- .pack2
- .then(|| free.iter().position(|&r| r > o.row))
- .flatten();
- (o.row, (o.pack2, b.map(|i| free.remove(i))))
- })
- .collect()
- }
- /// Pixel inputs packing two 16-bit rows per dword whose second row the
- /// metadata leaves out (`row2` = `row`): as for outputs
- /// ([`half_outputs`]), the next 16-bit row of the signature that no input
- /// entry names, taken in row order (rows the metadata does give are taken
- /// first).
- fn half_input_partners(io: &StageIo, inputs: &[SigElement]) -> HashMap<u8, u8> {
- let StageIo::Ps {
- inputs: entries, ..
- } = io
- else {
- return HashMap::new();
- };
- let packed = || entries.iter().filter(|i| i.fp16 && i.pack2);
- let mut free: Vec<u8> = inputs
- .iter()
- .filter(|e| e.half && e.kind == 0)
- .filter_map(|e| u8::try_from(e.row?).ok())
- .filter(|&r| !entries.iter().any(|i| i.row == r))
- .filter(|&r| !packed().any(|i| i.row2 != i.row && i.row2 == r))
- .collect();
- free.sort_unstable();
- free.dedup();
- let mut missing: Vec<_> = packed().filter(|i| i.row2 == i.row).collect();
- missing.sort_by_key(|i| i.row);
- let mut partners = HashMap::new();
- for i in missing {
- if let Some(k) = free.iter().position(|&r| r > i.row) {
- partners.insert(i.row, free.remove(k));
- }
- }
- partners
- }
- fn unsupported(offset: usize, what: Why) -> Stop {
- Stop::Fail(ShaderError::Unsupported { offset, what })
- }
- impl<'a> Lower<'a> {
- fn new(x: &'a Parts<'a>, bad: &'a HashMap<Value, Why>) -> Self {
- let p = x.p;
- let mut phi_at = HashMap::new();
- for (b, block) in p.blocks.iter().enumerate() {
- for (i, phi) in block.phis.iter().enumerate() {
- phi_at.insert(phi.value, (b, i));
- }
- }
- let mut s = Shader::new(x.native.stage == HwStage::Ps);
- s.inputs = x.inputs.clone();
- s.outputs = x.outputs.clone();
- let insts = || p.blocks.iter().flat_map(|b| &b.insts);
- let writes_uavs = insts().any(|i| {
- matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. })
- && (i.name().contains("store") || i.name().contains("atomic"))
- });
- let mut console_lanes = false;
- // LDS accesses get a group barrier each (a console wave split in two host waves)
- let mut split_lds = false;
- // with `split_lds`, LDS accesses in lane branches: the blocks every lane runs, and
- // where the host waves meet around those branches (`lds_meetings`)
- let mut lds_meet: Option<(Vec<bool>, Vec<(bool, bool)>)> = None;
- // a console wave64 program in two host waves of 32 (`exchange`)
- let mut exchange: Option<(u32, bool, Vec<bool>)> = None;
- // a console wave64 program in host waves of 32: the LDS dword of `wave_base`'s counter
- let mut halves: Option<u32> = None;
- if let StageIo::Cs(cs) = x.native.io {
- s.threads = Some(cs.threads);
- s.lds_dwords = cs.lds_bytes() / 4;
- // Code reading other lanes needs the console's wave size and
- // lane order; so do lane masks read as numbers, and LDS shared
- // within one wave, where the console compiler leaves out barriers.
- console_lanes = insts().any(|i| {
- let n = i.name();
- n.starts_with("ds_swizzle")
- || n.contains("permute")
- || n.starts_with("v_permlane")
- || n.starts_with("v_mbcnt")
- || matches!(n, "v_readlane_b32" | "v_writelane_b32")
- || matches!(&i.fields, Fields::Valu(v) if v.dpp.is_some())
- || reads_mask_as_data(x.st, i)
- }) || lane_constant_masks(x.st)
- // (a branch the wave takes together asks the wave)
- || !x.st.wide.is_empty();
- let mut wave = if x.native.wave64 { 64 } else { 32 };
- let group = cs.threads.iter().product::<u32>();
- let one_wave = group <= wave;
- // A host whose waves are at most 32 lanes (NVIDIA) refuses `WaveSize(64)`. A console
- // wave64 program whose cross-lane code stays inside 32-lane halves – DPP rows,
- // `ds_swizzle`, `v_permlane16` / `v_permlanex16`, which the ISA confines there – runs
- // exactly in waves of 32: the thread relabelling makes each host wave one half of a
- // console wave (lanes 32k..32k+31). Not when it crosses halves (`v_mbcnt`,
- // `v_readlane`, `v_writelane`, `ds_(b)permute`, masks as numbers or lane-constant
- // masks), nor when LDS may be shared within the console wave without barriers (a
- // group over 32 threads with LDS): those still need 64-lane waves.
- if wave == 64 && host_max_wave() == 32 && (console_lanes || one_wave && s.lds_dwords > 0) {
- let crosses = insts().any(|i| {
- let n = i.name();
- n.starts_with("v_mbcnt")
- || matches!(n, "v_readlane_b32" | "v_writelane_b32")
- || n.starts_with("ds_permute")
- || n.starts_with("ds_bpermute")
- || reads_mask_as_data(x.st, i)
- }) || lane_constant_masks(x.st)
- || !x.st.wide.is_empty();
- if !crosses && (s.lds_dwords == 0 || group <= 32) {
- wave = 32;
- } else {
- // (Groups of several console waves too: each console wave is two host
- // waves, which exchange through their own pair of dwords.)
- // LDS the console shares within its one wave without barriers: split into
- // two waves of 32, a group barrier before every LDS access keeps their order
- // – where every thread of the group gets there (no lane branch around it,
- // no guard), else a barrier would hang the group
- let lds = |i: &Inst| {
- matches!(i.fields, Fields::Ds { .. })
- && !(i.name().starts_with("ds_swizzle") || i.name().contains("permute"))
- };
- if let Some(all) = all_lane_blocks(x.st) {
- let ok = p.blocks.iter().enumerate().all(|(b, blk)| {
- blk.insts.iter().all(|inst| {
- !lds(inst) || all.get(b).copied().unwrap_or(false)
- })
- });
- let mut lds_ok = !(s.lds_dwords > 0 && group > 32) || ok;
- if !lds_ok && let Some(meet) = lds_meetings(p, x.st, &all) {
- lds_meet = Some((all.clone(), meet));
- lds_ok = true;
- }
- if !lds_ok {
- // (the blocks whose LDS accesses not every lane runs: with the
- // branches around them taken wave-wide they get their barriers)
- for (b, blk) in p.blocks.iter().enumerate() {
- if !all.get(b).copied().unwrap_or(false) && blk.insts.iter().any(lds) {
- need(b);
- }
- }
- }
- if lds_ok {
- wave = 32;
- split_lds = s.lds_dwords > 0 && group > 32;
- if crosses {
- // lanes 32..63 are the other host wave: masks, lane reads and lane
- // numbers go through two exchange dwords past the program's LDS
- exchange = Some((s.lds_dwords, group <= 32, all));
- s.lds_dwords += 2 * group.div_ceil(64);
- }
- }
- }
- }
- // `VICTORY_WAVE_WHY=1`: why a program keeps 64-lane waves (one line per reason)
- if wave == 64 && std::env::var_os("VICTORY_WAVE_WHY").is_some() {
- let mut why: Vec<&str> = Vec::new();
- for i in insts() {
- let n = i.name();
- let r = if n.starts_with("v_mbcnt") {
- "v_mbcnt"
- } else if n == "v_readlane_b32" {
- "v_readlane"
- } else if n == "v_writelane_b32" {
- "v_writelane"
- } else if n.starts_with("ds_permute") || n.starts_with("ds_bpermute") {
- "ds_(b)permute"
- } else if reads_mask_as_data(x.st, i) {
- "mask as data"
- } else {
- continue;
- };
- if !why.contains(&r) {
- why.push(r);
- }
- }
- if lane_constant_masks(x.st) {
- why.push("lane-constant mask");
- }
- if s.lds_dwords > 0 && group > 32 {
- why.push("LDS in a group over 32");
- match all_lane_blocks(x.st) {
- None => why.push("an indirect exit"),
- Some(all) if lds_meetings(p, x.st, &all).is_none() => {
- why.push("an LDS read and write in one lane-branch region")
- }
- Some(_) => {}
- }
- }
- why.sort_unstable();
- eprintln!("WAVE64-WHY group={group} lds={} [{}]", s.lds_dwords > 0, why.join(", "));
- }
- }
- if wave == 32 && x.native.wave64 {
- // console threads go to host waves in the order the waves take them (`wave_base`)
- halves = Some(s.lds_dwords);
- s.lds_dwords += 1;
- }
- if console_lanes || one_wave && s.lds_dwords > 0 {
- s.wave_size = Some(wave);
- }
- }
- // The title's barriers a thread of the group may never reach, which
- // leaves the others waiting on the host: those in blocks some lanes
- // do not run, and all of them in a program with a loop closed by a
- // plain jump (a lane still in it at the iteration limit leaves the
- // program there, `abort_block`).
- let fence_only: HashSet<usize> = if insts().any(|i| i.name() == "s_barrier") {
- let order = crate::ir::reverse_postorder(&p.blocks);
- let mut place = vec![usize::MAX; p.blocks.len()];
- for (n, &b) in order.iter().enumerate() {
- place[b] = n;
- }
- let back = |from: usize, to: usize| {
- let at = |b: usize| place.get(b).copied().unwrap_or(usize::MAX);
- at(from) != usize::MAX && at(to) <= at(from)
- };
- let cut_short = x
- .st
- .exits
- .iter()
- .enumerate()
- .any(|(b, e)| matches!(*e, LaneExit::Jump(t) if back(b, t)));
- let all = all_lane_blocks(x.st);
- (0..p.blocks.len())
- .filter(|&b| p.blocks[b].insts.iter().any(|i| i.name() == "s_barrier"))
- .filter(|&b| {
- cut_short
- || all
- .as_ref()
- .is_none_or(|all| !all.get(b).copied().unwrap_or(false))
- })
- .collect()
- } else {
- HashSet::new()
- };
- let mut no_barrier = HashSet::new();
- if let StageIo::Ms(ms) = &x.native.io {
- s.prims = x.prims.clone();
- s.threads = Some([ms.threads, 1, 1]);
- s.lds_dwords = ms.lds_bytes.div_ceil(4);
- s.mesh = Some(super::shader::Mesh {
- max_vertices: ms.max_vertices,
- max_primitives: ms.max_primitives,
- topology: ms.topology,
- });
- // Barriers order the lanes' LDS accesses; the console's
- // allocation request needs them too, but the host does not. One
- // lane sends that request, and what it dominates (the path for
- // counts out of range) runs in that lane alone, so its barrier
- // would hang the host.
- let order = crate::ir::reverse_postorder(&p.blocks);
- let mut index = vec![usize::MAX; p.blocks.len()];
- for (n, &b) in order.iter().enumerate() {
- index[b] = n;
- }
- let idom = crate::ir::idoms(&p.blocks, &order, &index);
- let alloc: Vec<usize> = (0..p.blocks.len())
- .filter(|&b| {
- p.blocks[b].insts.iter().any(|i| {
- i.name() == "s_sendmsg"
- && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == GS_ALLOC_REQ)
- })
- })
- .collect();
- for &b in &order {
- let mut d = b;
- let dominated = loop {
- if alloc.contains(&d) {
- break true;
- }
- if idom[d] == d || idom[d] == usize::MAX {
- break false;
- }
- d = idom[d];
- };
- if ms.lds_bytes == 0 || dominated {
- no_barrier.insert(b);
- }
- }
- }
- Lower {
- s,
- x,
- bad,
- lane_fail: HashMap::new(),
- vals: HashMap::new(),
- floats: HashMap::new(),
- block: vec![None; p.blocks.len()],
- cur: 0,
- bools: HashMap::new(),
- lane_bits: HashMap::new(),
- phi_at,
- mask_phis: HashMap::new(),
- pending_masks: Vec::new(),
- data_phis: Vec::new(),
- read_phis: HashSet::new(),
- stale: HashSet::new(),
- coherent: HashSet::new(),
- root_copy: None,
- page_there: None,
- ordered: if x.native.stage == HwStage::Ps {
- ordered_section(p)
- } else {
- HashSet::new()
- },
- params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(),
- user_data: None,
- user_reads: BTreeMap::new(),
- samplers: Vec::new(),
- descriptors: x
- .res
- .descriptors
- .iter()
- .map(|d| ((d.site, d.role == Role::Sampler), &d.source))
- .collect(),
- scalar: x.res.scalar.iter().copied().collect(),
- exports: x.io.exports.iter().map(|e| (e.site, e)).collect(),
- interps: {
- let mut m: HashMap<Site, &Interp> = x.io.interps.iter().map(|(s, i)| (*s, i)).collect();
- // A first half whose result is also read as data (an f16 second half keeps
- // the other half of its dst, PS_DeferredTextured): evaluated as the pair it
- // starts. Approximate for those other bits (P0 + i P10 on the console); a
- // first half only the second half reads is gone before lowering.
- // Only in the second translation of a program the first
- // one refused for it ([`with_first_half_pairs`]).
- if FIRST_HALF_PAIRS.get() && std::env::var_os("VICTORY_FIRST_HALF").is_none_or(|v| v != "0") {
- for (_, i) in &x.io.interps {
- if let Interp::Interpolated { first, .. } = i {
- for s in first {
- m.entry(*s).or_insert(i);
- }
- }
- }
- }
- m
- },
- handles: HashMap::new(),
- strides: HashMap::new(),
- edges: HashMap::new(),
- exported: vec![false; p.blocks.len()],
- rpo: vec![usize::MAX; p.blocks.len()],
- tail: vec![None; p.blocks.len()],
- writes_uavs,
- src0: None,
- console_lanes,
- split_lds,
- lds_meet,
- local: exchange.is_some() && LOCAL_WAVES.get(),
- local_ok: false,
- local_any: LOCAL_ANY.get(),
- uniform: match &exchange {
- Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all),
- _ => HashSet::new(),
- },
- own_bits: match &exchange {
- Some((_, false, _)) if !LOCAL_WAVES.get() && own_bits_on() => {
- super::own_bits::find(p, x.st, std::env::var_os("VICTORY_WAVE_WHY").is_some())
- }
- _ => Default::default(),
- },
- exchange,
- clane: None,
- pair: None,
- halves,
- wave_base: None,
- flat: None,
- no_barrier,
- fence_only,
- half_outputs: half_outputs(&x.native.io, &x.outputs),
- mask_data: match x.native.stage {
- HwStage::Cs => MaskData::Console,
- HwStage::Ps | HwStage::Vs => MaskData::Host,
- _ => MaskData::None,
- },
- mask_ok: false,
- ballots: HashMap::new(),
- balloting: HashSet::new(),
- def_block: p
- .blocks
- .iter()
- .enumerate()
- .flat_map(|(b, block)| {
- block
- .insts
- .iter()
- .flat_map(move |i| i.writes.iter().map(move |w| (w.1, b)))
- .chain(block.phis.iter().map(move |phi| (phi.value, b)))
- })
- .collect(),
- cur_ir: 0,
- sections: HashMap::new(),
- section_out: HashSet::new(),
- code_table: None,
- counters: HashMap::new(),
- abort: None,
- }
- }
- /// The dword of the program's code at byte `byte` (a constant table
- /// the compiler appends to the code), as an internal constant array.
- // shortcut: an index outside the table reads its last dword (the
- // console would read whatever memory follows the code).
- fn code_dword(&mut self, byte: V) -> Result<V, Why> {
- let (g, base, len) = match self.code_table {
- Some(t) => t,
- None => {
- let first = self
- .x
- .res
- .scalar
- .iter()
- .map(|s| s.1)
- .chain(self.x.res.descriptors.iter().flat_map(|d| {
- d.source.leaves().into_iter().filter_map(|l| match l {
- Source::Built { address, .. } => Some(*address),
- _ => None,
- })
- }))
- .filter(|a| a.param == CODE)
- .map(|a| a.offset & !3)
- .min()
- .ok_or("a code table")?;
- let code = &self.x.native.code;
- let words: Vec<u32> = code
- .get(first as usize..)
- .ok_or("a code table past the code")?
- .chunks(4)
- .map(|c| {
- let mut w = [0u8; 4];
- w[..c.len()].copy_from_slice(c);
- u32::from_le_bytes(w)
- })
- .collect();
- if words.is_empty() {
- return Err("a code table past the code");
- }
- let elems: Vec<V> = words.iter().map(|&w| self.s.m.i32(w)).collect();
- let arr = self.s.m.array(words.len() as u32, self.s.t.i32);
- let init = self.s.m.aggregate(arr, &elems);
- let g = self.s.m.constant_global("code", init);
- let t = (g, first, words.len() as u32);
- self.code_table = Some(t);
- t
- }
- };
- let c = self.cur;
- let k = self.s.m.i32(base);
- let rel = self.s.m.bin(c, Bin::Sub, byte, k);
- let two = self.s.m.i32(2);
- let index = self.s.m.bin(c, Bin::LShr, rel, two);
- let last = self.s.m.i32(len - 1);
- let over = self.s.m.cmp(c, pred::IUGT, index, last);
- let index = self.s.m.select(c, over, last, index);
- let at = self.s.m.element(c, g, index);
- Ok(self.s.m.load(c, at))
- }
- /// A global memory load (`global_load_*`): from the program's constant
- /// table, or from a root SRV at the address the title sets.
- fn flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
- let Fields::Flat { dst, .. } = &inst.fields else {
- unreachable!()
- };
- self.root_copy = None;
- let name = inst.name();
- if self.scalar.get(&(b, i)).is_some_and(|a| a.param == MEMORY) {
- return self.memory_flat(inst, b, i);
- }
- let rest = name
- .strip_prefix("global_load_")
- .ok_or("a global memory write")?;
- let (n, sub) = match rest {
- "dword" => (1, None),
- "dwordx2" => (2, None),
- "dwordx3" => (3, None),
- "dwordx4" => (4, None),
- "ubyte" => (1, Some((8, false))),
- "sbyte" => (1, Some((8, true))),
- "ushort" => (1, Some((16, false))),
- "sshort" => (1, Some((16, true))),
- _ => return Err(name),
- };
- let a = *self
- .scalar
- .get(&(b, i))
- .ok_or("an untracked global address")?;
- let guard = self.guard(b, i)?;
- let Some(Operand::Vector { reg, .. }) = *dst else {
- return Err("a global load result");
- };
- let c = self.cur;
- let mut off = self.s.m.i32(a.offset);
- if let Some(d) = a.dynamic {
- let d = self.i32_of(d)?;
- off = self.s.m.bin(c, Bin::Add, off, d);
- }
- let h = if a.param == CODE {
- None
- } else {
- let src = Source::Built {
- address: a,
- bits: 0,
- words: [0, 0],
- };
- if let Some(bias) = self.root_bias(a.param) {
- off = self.s.m.bin(c, Bin::Add, off, bias);
- }
- match self.root_memory(&src, off, guard, false) {
- Some((h, byte)) => {
- off = byte;
- Some(h)
- }
- None => Some(self.handle((b, i), &src, false, (11, 0))?),
- }
- };
- let c = self.cur;
- let dword = |l: &mut Self, byte: V| -> Result<V, Why> {
- match h {
- None => l.code_dword(byte),
- Some(h) => {
- let c = l.cur;
- let (u, mask, al) = (l.s.m.undef(l.s.t.i32), l.s.m.i8(1), l.s.m.i32(4));
- let r = l.s.op(
- c,
- "rawBufferLoad.f32",
- Attr::ReadOnly,
- l.s.t.res_ret,
- 139,
- &[h, byte, u, mask, al],
- );
- let x = l.s.m.extract(c, r, 0);
- Ok(l.as_int(x))
- }
- }
- };
- for k in 0..n {
- let x = match sub {
- None => {
- let four = self.s.m.i32(4 * k);
- let at = self.s.m.bin(c, Bin::Add, off, four);
- dword(self, at)?
- }
- Some((width, signed)) => {
- // shortcut: the field is taken not to cross a dword.
- let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3));
- let at = self.s.m.bin(c, Bin::And, off, not3);
- let w = dword(self, at)?;
- let byte = self.s.m.bin(c, Bin::And, off, three);
- let sh = self.s.m.bin(c, Bin::Shl, byte, three);
- let x = self.s.m.bin(c, Bin::LShr, w, sh);
- let left = self.s.m.i32(32 - width);
- let x = self.s.m.bin(c, Bin::Shl, x, left);
- self.s
- .m
- .bin(c, if signed { Bin::AShr } else { Bin::LShr }, x, left)
- }
- };
- self.write(inst, Reg::V(reg + k as u8), x, guard);
- }
- Ok(())
- }
- /// Finds the whole-wave sections and the values they leave.
- fn find_sections(&mut self) {
- let p = self.x.p;
- let mut inside: HashMap<Value, (usize, usize, usize)> = HashMap::new();
- for b in 0..p.blocks.len() {
- let found = super::wave::sections(p, b);
- for (&start, sec) in &found {
- for i in start + 1..sec.end {
- for &(_, w) in &p.blocks[b].insts[i].writes {
- inside.insert(w, (b, start, sec.end));
- }
- }
- }
- if !found.is_empty() {
- self.sections.insert(b, found);
- }
- }
- if inside.is_empty() {
- return;
- }
- for (b, block) in p.blocks.iter().enumerate() {
- for phi in &block.phis {
- self.section_out
- .extend(phi.args.iter().filter(|a| inside.contains_key(a)));
- }
- for (i, inst) in block.insts.iter().enumerate() {
- for &(_, r) in &inst.reads {
- if let Some(&(sb, start, end)) = inside.get(&r)
- && !(sb == b && i > start && i < end)
- {
- self.section_out.insert(r);
- }
- }
- }
- }
- }
- /// An instruction inside a whole-wave section: the values that leave
- /// the section are made from what the simulation found them to be.
- fn section_inst(&mut self, b: usize, i: usize, start: usize) {
- const UNKNOWN: Why = "a whole-wave section step the simulation does not follow";
- let inst = &self.x.p.blocks[b].insts[i];
- for &(_, w) in &inst.writes {
- let val = if self.section_out.contains(&w) {
- let shape = self.sections[&b][&start].shapes.get(&w).copied();
- let own = self.own_bits.totals.contains(&w);
- match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh, own)) {
- Ok(x) => Val::I32(x),
- Err(why) => Val::Missing(why),
- }
- } else {
- Val::Missing(UNKNOWN)
- };
- self.vals.insert(w, val);
- }
- }
- /// A value a whole-wave section leaves, as DXIL wave operations over the
- /// host's active lanes: the console's result with console lanes; on
- /// another wave size, what the HLSL wave operation the console compiler
- /// expanded gives on that wave.
- ///
- /// `own`: a wave OR that only steers a loop over each lane's own bits
- /// ([`super::own_bits`]); where two host waves cannot exchange their halves' ORs it is
- /// this host wave's.
- fn shape(&mut self, shape: super::wave::Shape, own: bool) -> Result<V, Why> {
- use super::wave::{Op, Shape};
- let (op, src, mask, ident, prefix) = match shape {
- Shape::K(k) => return Ok(self.s.m.i32(k)),
- Shape::Value(v) => return self.i32_of(v),
- Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None),
- Shape::ActiveF64(lo, hi, mask, high) => {
- return self.active_f64_sum(lo, hi, mask, high);
- }
- Shape::Masked(src, mask, ident) => {
- let c = self.cur;
- let &m = self
- .x
- .st
- .masks
- .get(&mask)
- .ok_or("a wave reduction's untracked mask")?;
- let on = self.boolean(m, c)?;
- let x = self.i32_of(src)?;
- let id = self.s.m.i32(ident);
- return Ok(self.s.m.select(c, on, x, id));
- }
- Shape::Prefix(op, src, mask, ident, inclusive) => {
- (op, src, mask, ident, Some(inclusive))
- }
- };
- // Mesh: no host wave size can be declared, so a reduction is over this host wave
- // only. A minimum or maximum is taken that way: the compiler's "next distinct
- // value" loop (the wave's minimum, then the lanes that hold it) serves every
- // lane however the lanes are divided into waves. A sum, a bit reduction or a
- // prefix would be of part of a console wave: still refused.
- if self.mask_data == MaskData::None
- && (prefix.is_some()
- || !matches!(
- op,
- Op::MinU | Op::MaxU | Op::MinI | Op::MaxI | Op::MinF | Op::MaxF
- ))
- {
- return Err("a wave reduction in a mesh shader");
- }
- let c = self.cur;
- let &m = self
- .x
- .st
- .masks
- .get(&mask)
- .ok_or("a wave reduction's untracked mask")?;
- let on = self.boolean(m, c)?;
- let x = self.i32_of(src)?;
- let id = self.s.m.i32(ident);
- let x = self.s.m.select(c, on, x, id);
- self.s.flags |= flags::WAVE_OPS;
- if op == Op::AddH {
- return match prefix {
- Some(_) => Err("a wave prefix of an operation other than a sum"),
- None => self.half_sum(x),
- };
- }
- let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF);
- let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
- let arg = if float { self.as_float(x) } else { x };
- let ty = if float { f32t } else { i32t };
- let sfx = if float { "f32" } else { "i32" };
- let r = match (op, prefix) {
- (Op::AddU | Op::AddF, Some(inclusive)) => {
- let (k0, k1) = (self.s.m.i8(0), self.s.m.i8(1));
- let r = self.s.op(
- c,
- &format!("wavePrefixOp.{sfx}"),
- Attr::NoUnwind,
- ty,
- 121,
- &[arg, k0, k1],
- );
- if inclusive {
- self.s.m.bin(c, Bin::Add, r, arg)
- } else {
- r
- }
- }
- (_, Some(_)) => return Err("a wave prefix of an operation other than a sum"),
- (Op::Or | Op::And | Op::Xor, None) => {
- let k = self.s.m.i8(match op {
- Op::And => 0,
- Op::Or => 1,
- _ => 2,
- });
- self.s
- .op(c, "waveActiveBit.i32", Attr::NoUnwind, i32t, 120, &[arg, k])
- }
- (_, None) => {
- let (code, unsigned) = match op {
- Op::AddU => (0, 1),
- Op::AddF => (0, 0),
- Op::MinU => (2, 1),
- Op::MaxU => (3, 1),
- Op::MinI | Op::MinF => (2, 0),
- _ => (3, 0),
- };
- let (k, u) = (self.s.m.i8(code), self.s.m.i8(unsigned));
- self.s.op(
- c,
- &format!("waveActiveOp.{sfx}"),
- Attr::NoUnwind,
- ty,
- 119,
- &[arg, k, u],
- )
- }
- };
- // two host waves of 32 hold the console's 64 lanes: their results combine
- let r = if self.local || self.exchange.as_ref().is_some_and(|e| e.1) {
- // this host wave's own result (and prefix): each wave on its own, or a group of
- // 32 threads or fewer, which one host wave holds whole (combining with the 0 a
- // missing half "gives" broke AND, MIN and signed MAX)
- r
- } else if own && prefix.is_none() && op == Op::Or && !self.all_lanes(self.cur_ir) {
- // each thread walks the bits of this value and works only at its own, which the
- // host wave's OR holds: the same run as with the console wave's OR
- r
- } else if self.exchange.is_some() {
- if !self.all_lanes(self.cur_ir) {
- need(self.cur_ir);
- return Err("a wave reduction where not every lane runs");
- }
- let bits = |l: &mut Self, v: V| if float { l.as_int(v) } else { v };
- let back = |l: &mut Self, v: V| if float { l.as_float(v) } else { v };
- match prefix {
- Some(_) => {
- // the upper half adds the lower half's total to its prefix
- let (k0, ku) = (self.s.m.i8(0), self.s.m.i8(u8::from(!float)));
- let total = self.s.op(c, &format!("waveActiveOp.{sfx}"), Attr::NoUnwind, ty, 119, &[arg, k0, ku]);
- let tb = bits(self, total);
- let c = self.cur;
- let (lo, _) = self.exchange_halves(c, tb);
- let lo = back(self, lo);
- let cl = self.console_lane();
- let k32 = self.s.m.i32(32);
- let upper = self.s.m.cmp(c, pred::IUGE, cl, k32);
- let zero = if float { self.s.m.f32(0) } else { self.s.m.i32(0) };
- let add = self.s.m.select(c, upper, lo, zero);
- self.s.m.bin(c, Bin::Add, r, add)
- }
- None => {
- let rb = bits(self, r);
- let c = self.cur;
- let (lo, hi) = self.exchange_halves(c, rb);
- let (lo, hi) = (back(self, lo), back(self, hi));
- match op {
- Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, lo, hi),
- Op::Or => self.s.m.bin(c, Bin::Or, lo, hi),
- Op::And => self.s.m.bin(c, Bin::And, lo, hi),
- Op::Xor => self.s.m.bin(c, Bin::Xor, lo, hi),
- _ => {
- // FMax 35, FMin 36, IMax 37, IMin 38, UMax 39, UMin 40
- let code = match op {
- Op::MaxF => 35,
- Op::MinF => 36,
- Op::MinU => 40,
- Op::MaxU => 39,
- Op::MinI => 38,
- _ => 37,
- };
- self.s.op(c, &format!("binary.{sfx}"), Attr::ReadNone, ty, code, &[lo, hi])
- }
- }
- }
- }
- } else {
- r
- };
- Ok(if float { self.as_int(r) } else { r })
- }
- /// `WaveActiveSum` of 64-bit floats (`f64(lo, hi)` in active lanes, `+0.0` elsewhere),
- /// returning the low (`!high`) or high (`high`) 32-bit word.
- fn active_f64_sum(
- &mut self,
- lo: Value,
- hi: Value,
- mask: Value,
- high: bool,
- ) -> Result<V, Why> {
- if self.mask_data == MaskData::None {
- return Err("a wave reduction in a mesh shader");
- }
- let c = self.cur;
- let &m = self
- .x
- .st
- .masks
- .get(&mask)
- .ok_or("a wave reduction's untracked mask")?;
- let on = self.boolean(m, c)?;
- let lo = self.i32_of(lo)?;
- let hi = self.i32_of(hi)?;
- let z = self.s.m.i32(0);
- let lo = self.s.m.select(c, on, lo, z);
- let hi = self.s.m.select(c, on, hi, z);
- self.s.flags |= flags::WAVE_OPS | flags::DOUBLES;
- let f64t = self.s.m.double();
- let i32t = self.s.t.i32;
- let split_ty = self
- .s
- .m
- .named_struct("dx.types.splitdouble", vec![i32t, i32t]);
- let arg = self
- .s
- .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]);
- let (k0, k0b) = (self.s.m.i8(0), self.s.m.i8(0));
- let sum = self
- .s
- .op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[arg, k0, k0b]);
- let split = self
- .s
- .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[sum]);
- let mut r_lo = self.s.m.extract(c, split, 0);
- let mut r_hi = self.s.m.extract(c, split, 1);
- if self.exchange.is_some() {
- if !self.all_lanes(self.cur_ir) {
- need(self.cur_ir);
- return Err("a wave reduction where not every lane runs");
- }
- let (lo0, lo1) = self.exchange_halves(self.cur, r_lo);
- let (hi0, hi1) = self.exchange_halves(self.cur, r_hi);
- let c = self.cur;
- let d0 = self
- .s
- .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo0, hi0]);
- let d1 = self
- .s
- .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo1, hi1]);
- let total = self.s.m.bin(c, Bin::Add, d0, d1);
- let split = self
- .s
- .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[total]);
- r_lo = self.s.m.extract(c, split, 0);
- r_hi = self.s.m.extract(c, split, 1);
- }
- Ok(if high { r_hi } else { r_lo })
- }
- /// The sum of two 16-bit floats (the low halves of `a` and `b`) as the console's
- /// `v_add_f16` gives it: added in f32 and rounded to 16 bits, to nearest
- /// ([`Self::f16_nearest`]).
- fn add_halves(&mut self, a: V, b: V) -> V {
- let c = self.cur;
- let f32t = self.s.t.f32;
- let low = self.s.m.i32(0xFFFF);
- let wide = |l: &mut Self, x: V| {
- let h = l.s.m.bin(c, Bin::And, x, low);
- l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h])
- };
- let (fa, fb) = (wide(self, a), wide(self, b));
- let f = self.s.m.bin(c, Bin::Add, fa, fb);
- self.f16_nearest(f)
- }
- /// `WaveActiveSum` of 16-bit floats (`x`: each lane's term in its low half, +0 in the
- /// lanes outside the mask), bit for bit as the console adds it: every addition rounds to
- /// 16 bits, so the order counts, and the compiler's is the balanced tree over the lanes
- /// in their order (lanes 2k and 2k+1, then pairs, ... then the wave's two halves;
- /// [`super::wave::buddies`]). Each lane adds its partner's partial sum, read from the
- /// lane whose number differs in one bit, step by step; two host waves of 32 then exchange
- /// their halves' sums for the last addition. The high half of the result is lane 0's,
- /// which no `v_add_f16` writes.
- /// On a host wave of 64 lanes where not every lane runs, the lanes that are elsewhere
- /// count as the console's do (it masks them to +0): a partner's partial sum is read from
- /// the first lane there is of the partner's run of lanes, and is +0 without one. Two host
- /// waves of 32 can only exchange where every lane runs: refused elsewhere, in a thread
- /// group that does not fill its waves, and for each half-wave on its own (half a sum is
- /// no sum).
- fn half_sum(&mut self, x: V) -> Result<V, Why> {
- const WHERE: Why = "a wave sum of 16-bit floats where not every lane runs";
- let threads = self.s.threads.ok_or("a wave sum of 16-bit floats outside compute")?;
- if threads.iter().product::<u32>() % 64 != 0 {
- return Err("a wave sum of 16-bit floats in a wave that is not full");
- }
- if self.local {
- return Err("a wave sum of 16-bit floats in a half-wave");
- }
- // two host waves of 32 that exchange, or one host wave of 64 lanes
- let halves = match (&self.exchange, self.s.wave_size) {
- (Some((_, false, _)), _) => true,
- (None, Some(64)) if self.x.p.wave64 => false,
- _ => return Err("a wave sum of 16-bit floats on these waves"),
- };
- let every = if halves {
- self.all_lanes(self.cur_ir)
- } else {
- all_lane_blocks(self.x.st).is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false))
- };
- if !every && halves {
- need(self.cur_ir);
- return Err(WHERE);
- }
- let c = self.cur;
- let i32t = self.s.t.i32;
- let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
- let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0));
- // the lanes that are here, when not all are
- let here = (!every).then(|| {
- self.s.flags |= flags::WAVE_OPS;
- let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
- let yes = self.s.m.bool(true);
- let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[yes]);
- (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1))
- });
- // `v` of the first lane here of the `n` (a power of two) lanes from `base`: +0 of none
- let first_of = |l: &mut Self, v: V, base: V, n: u32| {
- let Some((lo, hi)) = here else {
- return l.read_lane(v, base);
- };
- let (k31, k32) = (l.s.m.i32(31), l.s.m.i32(32));
- let lower = l.s.m.cmp(c, pred::IULT, base, k32);
- let word = l.s.m.select(c, lower, lo, hi);
- let shift = l.s.m.bin(c, Bin::And, base, k31);
- let word = l.s.m.bin(c, Bin::LShr, word, shift);
- let run = l.s.m.i32(u32::MAX >> (32 - n));
- let word = l.s.m.bin(c, Bin::And, word, run);
- let any = l.s.m.cmp(c, pred::NE, word, zero);
- let nth = l.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[word]);
- let from = l.s.m.bin(c, Bin::Add, base, nth);
- // (no lane there: this one, which is here; the read is not used)
- let from = l.s.m.select(c, any, from, lane);
- let got = l.read_lane(v, from);
- l.s.m.select(c, any, got, zero)
- };
- let mut sum = x;
- for step in 0..if halves { 5 } else { 6 } {
- let bit = self.s.m.i32(1 << step);
- let mut partner = self.s.m.bin(c, Bin::Xor, lane, bit);
- if !every {
- let run = self.s.m.i32(!((1 << step) - 1));
- partner = self.s.m.bin(c, Bin::And, partner, run);
- }
- let theirs = first_of(self, sum, partner, 1 << step);
- sum = self.add_halves(sum, theirs);
- }
- let first = first_of(self, x, zero, 1);
- let first = self.s.m.bin(c, Bin::And, first, high);
- let sum = self.s.m.bin(c, Bin::And, sum, low);
- let mine = self.s.m.bin(c, Bin::Or, first, sum);
- if !halves {
- return Ok(mine);
- }
- let (lo, hi) = self.exchange_halves(c, mine);
- let c = self.cur;
- let total = self.add_halves(lo, hi);
- let total = self.s.m.bin(c, Bin::And, total, low);
- let first = self.s.m.bin(c, Bin::And, lo, high);
- Ok(self.s.m.bin(c, Bin::Or, first, total))
- }
- fn run(mut self, counted: bool) -> Result<Lowered, Stop> {
- let p = self.x.p;
- if counted {
- // Before anything else, so that wave counts, reads of the first
- // lane and stores know only the lanes that run.
- let original = self.s.entry;
- let width = self.s.threads.expect("compute thread count")[0];
- let limit = self.host_word(RootType::Other(super::shader::USER_DISPATCH_THREADS_X), 0, width);
- let Val::I32(group) = self.compute_id("groupId.i32", 94, 0) else {
- unreachable!()
- };
- let Val::I32(thread) = self.thread_id(0) else {
- unreachable!()
- };
- let width = self.s.m.i32(width);
- let first = self.s.m.bin(original, Bin::Mul, group, width);
- let x = self.s.m.bin(original, Bin::Add, first, thread);
- let zero = self.s.m.i32(0);
- let all = self.s.m.cmp(original, pred::EQ, limit, zero);
- let inside = self.s.m.cmp(original, pred::IULT, x, limit);
- let runs = self.s.m.bin(original, Bin::Or, all, inside);
- let (body, done) = (self.s.m.new_block(), self.s.m.new_block());
- self.s.m.terminate(original, Term::CondBr(runs, body, done));
- self.s.m.terminate(done, Term::Ret);
- self.s.entry = body;
- }
- self.find_coherent();
- let order = crate::ir::reverse_postorder(&p.blocks);
- for (n, &b) in order.iter().enumerate() {
- self.rpo[b] = n;
- }
- for (n, &b) in order.iter().enumerate() {
- self.block[b] = Some(if n == 0 {
- self.s.entry
- } else {
- self.s.m.new_block()
- });
- }
- // Loop headers count iterations (`LOOP_LIMIT`).
- for &b in &order {
- let header = p.blocks[b]
- .preds
- .iter()
- .any(|&q| self.block[q].is_some() && self.rpo[b] <= self.rpo[q]);
- if header {
- let blk = self.block[b].expect("reachable");
- let phi = self.s.m.phi(blk, self.s.t.i32);
- self.counters.insert(b, (phi, Vec::new()));
- }
- }
- self.cur = self.s.entry;
- self.find_sections();
- self.inputs()?;
- if let Some(mesh) = self.s.mesh {
- self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?;
- self.block[order[0]] = Some(self.cur);
- }
- for &b in &order {
- self.cur = self.block[b].expect("reachable");
- self.cur_ir = b;
- let preds: Vec<usize> = p.blocks[b]
- .preds
- .iter()
- .copied()
- .filter(|&q| self.block[q].is_some())
- .collect();
- self.exported[b] = !preds.is_empty() && preds.iter().all(|&q| self.exported_out(q));
- for (i, phi) in p.blocks[b].phis.iter().enumerate() {
- let val = match phi.reg {
- Reg::S(c) if c == EXEC || c == EXEC + 1 => Val::Missing("a lane mask"),
- _ if self.bad.contains_key(&phi.value) => Val::Missing(self.bad[&phi.value]),
- Reg::Scc => {
- let v = self.s.m.phi(self.cur, self.s.t.i1);
- self.data_phis.push((v, b, i));
- Val::Bit(v)
- }
- _ => {
- let v = self.s.m.phi(self.cur, self.s.t.i32);
- self.data_phis.push((v, b, i));
- Val::I32(v)
- }
- };
- self.vals.insert(phi.value, val);
- }
- if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].0) {
- self.lds_meeting();
- }
- let mut i = 0;
- while i < p.blocks[b].insts.len() {
- self.inst(b, i)?;
- if let Some(end) = self.sections.get(&b).and_then(|s| s.get(&i)).map(|s| s.end) {
- for j in i + 1..end {
- self.section_inst(b, j, i);
- }
- i = end;
- continue;
- }
- i += 1;
- }
- self.mask_ok = self.mask_data == MaskData::Console;
- if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].1) {
- self.lds_meeting();
- }
- self.tail[b] = Some(self.cur);
- self.exit(b)?;
- }
- self.fill_phis()?;
- let user_data = self.user_reads.values().copied().collect();
- self.s.samplers = self.samplers.len() as u32;
- let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect();
- let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect();
- let root_uavs = self.s.root_uavs.iter().map(|r| r.0).collect();
- let cmp_samplers = self.s.cmp_samplers;
- let wave_size = self.s.wave_size;
- Ok(Lowered {
- wave_size,
- cmp_samplers,
- root_cbvs,
- root_srvs,
- root_uavs,
- #[cfg(test)]
- nonuniform_handles: self.s.nonuniform_handles,
- #[cfg(test)]
- wave_ops: self.s.flags & flags::WAVE_OPS != 0,
- dxil: self.s.finish(),
- user_data,
- samplers: self.samplers,
- })
- }
- fn exported_out(&self, b: usize) -> bool {
- self.exported[b] || self.has_done_export(b)
- }
- fn has_done_export(&self, b: usize) -> bool {
- (0..self.x.p.blocks[b].insts.len())
- .any(|i| self.exports.get(&(b, i)).is_some_and(|e| e.done))
- }
- /// Values of the program's input registers.
- fn inputs(&mut self) -> Result<(), Stop> {
- let io_inputs: HashMap<Value, Input> = self.x.io.inputs.iter().copied().collect();
- for &(reg, v) in &self.x.p.inputs {
- let val = match reg {
- Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use
- // Most programs only interpolate with them: loaded on first
- // use as a value (`get`).
- Reg::V(_) if matches!(io_inputs.get(&v), Some(Input::Barycentric { .. })) => {
- continue;
- }
- Reg::S(n) => match io_inputs.get(&v) {
- Some(&input) => self.input(input),
- // Above the SGPRs the hardware initializes, a register
- // holds what the last wave left, so no program depends
- // on it: a read the paths only seem to allow (a branch
- // past the write, taken only with one past the read)
- // reads zero, as VGPRs do.
- None if n <= 105 && self.x.io.initialized_sgprs.is_some_and(|k| n >= k) => {
- Val::I32(self.s.m.i32(0))
- }
- // A scalar parked in a VGPR lane (`ir::unspill`), read where the
- // paths only seem to allow it before any save: the lane of a VGPR
- // nobody wrote, and VGPRs nobody set read as zero.
- None if n >= crate::ir::PARKED => Val::I32(self.s.m.i32(0)),
- // No wave overlaps this one (see `ordered_section`).
- None if self.pops_collision(v) => Val::I32(self.s.m.i32(0)),
- None => Val::Missing("a hardware SGPR input"),
- },
- Reg::Scc => Val::Missing("SCC on entry"),
- Reg::V(_) => match io_inputs.get(&v) {
- Some(&input) => self.input(input),
- // Registers no one set read as zero (the validator
- // refuses reads of undef).
- None => Val::I32(self.s.m.i32(0)),
- },
- };
- self.vals.insert(v, val);
- }
- Ok(())
- }
- /// Whether the input SGPR `v` is the POPS collision wave id: a program
- /// with an ordered section only takes its fields apart (bit 31 says
- /// that the wave overlaps another, the others which packer and waves).
- fn pops_collision(&self, v: Value) -> bool {
- if self.ordered.is_empty() {
- return false;
- }
- let mut packer = false;
- for block in &self.x.p.blocks {
- if block.phis.iter().any(|p| p.args.contains(&v)) {
- return false;
- }
- for i in &block.insts {
- if !i.reads.iter().any(|r| r.1 == v) {
- continue;
- }
- let Fields::Sop { src, .. } = &i.fields else {
- return false;
- };
- match (i.name(), src.get(1)) {
- // bits 28 and 29: the packer
- ("s_bfe_u32", Some(Operand::Literal(0x0002_001C))) => packer = true,
- ("s_bfe_u32" | "s_lshr_b32", _) => {}
- _ => return false,
- }
- }
- }
- packer
- }
- fn input(&mut self, input: Input) -> Val {
- let (kind, col) = match input {
- Input::VertexId => (1, 0),
- Input::InstanceId => (2, 0),
- Input::Position(c) => (3, c),
- Input::Attribute { row, channel } => {
- return match self.find_input(row, channel) {
- Some((id, col)) => self.load_input(id, col),
- None => Val::Missing("a vertex input the signature lacks"),
- };
- }
- Input::Barycentric { kind, index } => return self.barycentric(kind, index),
- Input::PrimitiveId => return Val::Missing("the primitive id"),
- // The console code tests it against 0 (`v_cmp_ne_u32`), as the
- // host's value can be.
- Input::FrontFace => (13, 0),
- Input::ThreadIdInGroup(c) => return self.thread_id(c),
- Input::GroupId(c) => return self.compute_id("groupId.i32", 94, c),
- Input::GroupInfo => return Val::Missing("the thread-group info SGPR"),
- Input::MeshGroup => {
- let Val::I32(g) = self.compute_id("groupId.i32", 94, 0) else {
- unreachable!()
- };
- let n = self.s.m.i32(self.x.mesh_stride);
- return Val::I32(self.s.m.bin(self.s.entry, Bin::Mul, g, n));
- }
- Input::MergedWaveInfo => {
- // shortcut: only the wave index (bits 24-27) is set; the
- // console's other bits (lane counts) are read by no program.
- let f = self.mesh_thread();
- let shift = self.s.m.i32(self.wave().trailing_zeros());
- let w = self.s.m.bin(self.s.entry, Bin::LShr, f, shift);
- let k24 = self.s.m.i32(24);
- return Val::I32(self.s.m.bin(self.s.entry, Bin::Shl, w, k24));
- }
- _ => return Val::Missing("a pixel system input"),
- };
- let free = self
- .s
- .inputs
- .iter()
- .filter_map(|e| e.row)
- .map(|r| r + 1)
- .max()
- .unwrap_or(0);
- let id = match self.s.inputs.iter().position(|e| e.kind == kind) {
- Some(id) => {
- if kind != 3 {
- self.s.inputs[id].row.get_or_insert(free);
- }
- id
- }
- None if kind >= 3 => return Val::Missing("a pixel system input the signature lacks"),
- None => {
- // The console signature leaves out vertex and instance ids; PC
- // gives them a row after the others.
- let row = self
- .s
- .inputs
- .iter()
- .filter_map(|e| e.row)
- .map(|r| r + 1)
- .max()
- .unwrap_or(0);
- self.s.inputs.push(SigElement {
- name: ["", "SV_VertexID", "SV_InstanceID"][kind as usize].into(),
- index: 0,
- kind,
- comp: 5,
- interp: 0,
- row: Some(row),
- col: 0,
- cols: 1,
- usage: 0,
- half: false,
- });
- self.s.inputs.len() - 1
- }
- };
- self.load_input(id, col)
- }
- /// A component of a compute thread or group id, read in the entry block.
- fn compute_id(&mut self, name: &str, opcode: u32, c: u8) -> Val {
- let (entry, c) = (self.s.entry, self.s.m.i32(u32::from(c)));
- Val::I32(
- self.s
- .op(entry, name, Attr::ReadNone, self.s.t.i32, opcode, &[c]),
- )
- }
- fn find_input(&self, row: u8, channel: u8) -> Option<(usize, u8)> {
- self.s.inputs.iter().enumerate().find_map(|(id, e)| {
- let r = e.row?;
- // `then`, not `then_some`: the channel is only past `col` when
- // the condition holds.
- (r == u32::from(row) && channel >= e.col && channel < e.col + e.cols)
- .then(|| (id, channel - e.col))
- })
- }
- fn load_input(&mut self, id: usize, col: u8) -> Val {
- if self.s.inputs[id].half {
- // shortcut: 16-bit vertex inputs (the fetch routine's) are not
- // unpacked; pixel inputs are (`interp`).
- return Val::Missing("a 16-bit input");
- }
- self.load_any_input(id, col)
- }
- /// An input element's channel as declared (16-bit ones as 32-bit floats).
- fn load_any_input(&mut self, id: usize, col: u8) -> Val {
- let e = &mut self.s.inputs[id];
- e.usage |= 1 << col;
- let (int, bit) = (e.comp != 9, e.comp == 1);
- let ty = if bit {
- self.s.t.i1
- } else if int {
- self.s.t.i32
- } else {
- self.s.t.f32
- };
- let suffix = if bit {
- ".i1"
- } else if int {
- ".i32"
- } else {
- ".f32"
- };
- let entry = self.s.entry;
- let args = [
- self.s.m.i32(id as u32),
- self.s.m.i32(0),
- self.s.m.i8(col),
- self.s.m.undef(self.s.t.i32),
- ];
- let v = self.s.op(
- entry,
- &format!("loadInput{suffix}"),
- Attr::ReadNone,
- ty,
- 4,
- &args,
- );
- if bit {
- let z = self.s.m.cast(entry, Cast::ZExt, v, self.s.t.i32);
- Val::I32(z)
- } else if int {
- Val::I32(v)
- } else {
- Val::I32(self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.i32))
- }
- }
- /// The DXIL form of an IR value.
- fn get(&mut self, v: Value) -> Result<Val, Why> {
- if self.phi_at.contains_key(&v) {
- self.read_phis.insert(v);
- }
- let is_mask = self.x.st.masks.contains_key(&v) || self.x.st.highs.contains_key(&v);
- match self.vals.get(&v) {
- Some(&Val::Missing(_)) | None if self.mask_ok && is_mask => {
- return self.mask_dword(v).map(Val::I32);
- }
- Some(&Val::Missing(w)) => return Err(w),
- Some(&val) => return Ok(val),
- None => {}
- }
- if let Some(&(param, dword)) = self.params.get(&v) {
- let val = self.user(param, dword);
- self.vals.insert(v, val);
- return Ok(val);
- }
- if let Some(loaded) = self.lazy_barycentric(v) {
- loaded?;
- return Ok(self.vals[&v]);
- }
- Err("a value defined after its use")
- }
- /// Loads `v` if it is a barycentric input VGPR not loaded yet (see
- /// `inputs`): `None` if it is not one.
- fn lazy_barycentric(&mut self, v: Value) -> Option<Result<(), Why>> {
- let (kind, index) = self.x.io.inputs.iter().find_map(|&(w, i)| match i {
- Input::Barycentric { kind, index } if w == v => Some((kind, index)),
- _ => None,
- })?;
- let val = self.barycentric(kind, index);
- self.vals.insert(v, val);
- Some(match val {
- Val::Missing(w) => Err(w),
- _ => Ok(()),
- })
- }
- /// Barycentric `index` (0 i, 1 j) of `kind` as a value: a channel of
- /// `SV_Barycentrics` declared with the same interpolation mode.
- ///
- /// GFX10 interpolates P0 + i (P1 - P0) + j (P2 - P0), so i and j are
- /// the weights of vertices 1 and 2. The host's weights (x, y, z) are
- /// those of vertices 0, 1 and 2, vertex 0 being the provoking vertex,
- /// which is the console's P0 (`v_interp_mov` P0 is lowered to a flat
- /// input): i is y and j is z.
- /// shortcut: triangles only; on lines and points the console's i and j
- /// are not checked against the host's weights.
- fn barycentric(&mut self, kind: Barycentric, index: u8) -> Val {
- let Some(mode) = interp_mode(kind) else {
- return Val::Missing("pull-model barycentrics");
- };
- if index > 1 {
- return Val::Missing("pull-model barycentrics");
- }
- // One element per interpolation mode (the console's own, if its
- // signature declares one): DXIL allows two.
- let bary = |e: &SigElement| e.kind == 28;
- let id = match self
- .s
- .inputs
- .iter()
- .position(|e| bary(e) && (e.interp == mode || e.usage == 0))
- {
- Some(id) => id,
- None => {
- let index = self.s.inputs.iter().filter(|e| bary(e)).count() as u32;
- if index >= 2 {
- return Val::Missing("barycentrics of a third interpolation mode");
- }
- // A system value the validator wants unpacked (packing
- // location -1), like other non-packed system values.
- self.s.inputs.push(SigElement {
- name: "SV_Barycentrics".into(),
- index,
- kind: 28,
- comp: 9,
- interp: mode,
- row: None,
- col: 0,
- cols: 3,
- usage: 0,
- half: false,
- });
- self.s.inputs.len() - 1
- }
- };
- let e = &mut self.s.inputs[id];
- if e.col != 0 || e.cols < 3 {
- return Val::Missing("a console barycentrics element without i and j");
- }
- e.row = None;
- e.interp = mode;
- self.s.flags |= flags::BARYCENTRICS;
- self.load_any_input(id, index + 1)
- }
- fn i32_of(&mut self, v: Value) -> Result<V, Why> {
- match self.get(v)? {
- Val::I32(x) => Ok(x),
- Val::Bit(x) => Ok(self.s.m.cast(self.cur, Cast::ZExt, x, self.s.t.i32)),
- Val::Missing(w) => Err(w),
- }
- }
- /// A user-data dword: a root parameter's value.
- fn user(&mut self, param: usize, dword: u32) -> Val {
- let rp = self.x.native.layout[param];
- match rp.root {
- RootType::ResourceHeap | RootType::SamplerHeap => return Val::I32(self.s.m.i32(0)),
- RootType::Constants | RootType::Table => {}
- _ => return Val::Missing("a root descriptor"),
- }
- let index = u32::from(rp.user_data) + dword - self.user_first();
- self.user_reads.insert(
- index,
- UserData {
- index,
- slot: rp.slot,
- root: rp.root,
- dword,
- },
- );
- Val::I32(self.user_at(index))
- }
- /// The user-data index that is dword 0 of the host's user data: 0, or
- /// 16 for a program with a spilled user-data table, whose parameters
- /// all sit at 16 and above. (The host's root signature has 64 dwords:
- /// a builder stage with constants up to index 45, eight root views,
- /// their biases and the memory directory would not fit with 16 dwords
- /// nothing reads in front.)
- fn user_first(&self) -> u32 {
- if crate::spill::is_spilled(self.x.native) {
- 16
- } else {
- 0
- }
- }
- /// A user-data dword no register of the console's holds: one the host
- /// computes when it binds (`root` says what, an `Other` code of
- /// `shader.rs`), placed after the layout's own dwords.
- fn host_word(&mut self, root: RootType, slot: u8, dword: u32) -> V {
- let known = self
- .user_reads
- .values()
- .find(|u| u.root == root && u.slot == slot && u.dword == dword)
- .map(|u| u.index);
- let index = match known {
- Some(index) => index,
- None => {
- let first = self.user_first();
- let layout = &self.x.native.layout;
- let mut index = layout
- .iter()
- .map(|e| u32::from(e.user_data) + e.sgprs)
- .max()
- .unwrap_or(0)
- .saturating_sub(first);
- while self.user_reads.contains_key(&index) {
- index += 1;
- }
- self.user_reads.insert(
- index,
- UserData {
- index,
- slot,
- root,
- dword,
- },
- );
- index
- }
- };
- self.user_at(index)
- }
- /// User-data dword `index`, loaded in the entry block.
- fn user_at(&mut self, index: u32) -> V {
- self.s.user_data = self.s.user_data.max(index + 1);
- let h = match self.user_data {
- Some(h) => h,
- None => {
- let h = self.s.user_data_handle();
- self.user_data = Some(h);
- h
- }
- };
- let entry = self.s.entry;
- let row = self.s.m.i32(index / 4);
- let r = self.s.op(
- entry,
- "cbufferLoadLegacy.i32",
- Attr::ReadOnly,
- self.s.t.cbuf_ret,
- 59,
- &[h, row],
- );
- self.s.m.extract(entry, r, index % 4)
- }
- /// Whether some instruction reads `v` as a number (or may, through a
- /// join), rather than in a descriptor operand.
- fn read_as_number(&self, v: Value) -> bool {
- self.x.p.blocks.iter().any(|b| {
- b.phis.iter().any(|p| p.args.contains(&v))
- || b.insts.iter().any(|i| {
- matches!(i.fields, Fields::Sop { .. } | Fields::Valu(_))
- && i.reads.iter().any(|r| r.1 == v)
- })
- })
- }
- /// Whether some instruction computes with `v` (scalar or vector
- /// arithmetic), rather than only naming it in a descriptor operand,
- /// moving it (at most `depth` moves are followed) or comparing it: a
- /// waterfall loop keeps a descriptor's dwords per lane, reads the first
- /// lane's back and compares the lanes' with them.
- fn computed_with(&self, v: Value, depth: u32) -> bool {
- self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| {
- if !i.reads.iter().any(|r| r.1 == v) {
- return false;
- }
- let name = i.name();
- let moves = matches!(
- name,
- "s_mov_b32"
- | "s_mov_b64"
- | "v_mov_b32"
- | "v_readfirstlane_b32"
- | "v_readlane_b32"
- | "v_writelane_b32"
- | "v_cndmask_b32"
- );
- match &i.fields {
- Fields::Sop { .. } | Fields::Valu(_) if moves => {
- depth > 0 && i.writes.iter().any(|w| self.computed_with(w.1, depth - 1))
- }
- Fields::Sop { .. } | Fields::Valu(_) => {
- !(name.starts_with("v_cmp") || name.starts_with("s_cmp"))
- }
- _ => false,
- }
- })
- }
- /// Whether the image `src` names is one of 32-bit integers (one channel):
- /// the program has an integer atomic on the same table entry, which
- /// takes no other view.
- fn is_counter(&self, src: &Source) -> bool {
- let Some(this) = self.entry(src) else {
- return false;
- };
- self.x.res.descriptors.iter().any(|d| {
- let i = &self.x.p.blocks[d.site.0].insts[d.site.1];
- d.role == Role::Resource
- && matches!(i.fields, Fields::Image { dmask: 1, .. })
- && matches!(
- i.name(),
- "image_atomic_add"
- | "image_atomic_sub"
- | "image_atomic_and"
- | "image_atomic_or"
- | "image_atomic_xor"
- | "image_atomic_smin"
- | "image_atomic_smax"
- | "image_atomic_umin"
- | "image_atomic_umax"
- )
- && self.entry(&d.source) == Some(this)
- })
- }
- /// Which table entry `src` is loaded from: its root parameter and byte.
- fn entry(&self, src: &Source) -> Option<(usize, u32)> {
- let Source::Loaded { load, first } = src else {
- return None;
- };
- let a = self.scalar.get(load).filter(|a| a.dynamic.is_none())?;
- Some((a.param, a.offset + 4 * u32::from(*first)))
- }
- /// See [`Lower::coherent`].
- fn find_coherent(&mut self) {
- let found: Vec<_> = self
- .x
- .res
- .descriptors
- .iter()
- .filter(|d| {
- let i = &self.x.p.blocks[d.site.0].insts[d.site.1];
- matches!(&i.fields, Fields::Buffer { cache, .. } if cache.glc)
- && i.name().starts_with("buffer_load_dword")
- && self.used_kind(&d.source).is_some_and(|u| u.kind == ResourceType::Uav)
- })
- .filter_map(|d| self.entry(&d.source))
- .collect();
- self.coherent.extend(found);
- }
- /// The kind of a view no instruction uses (in this program, or through
- /// another load of its address), by what the code reads of the
- /// descriptor the load `inst` at `site` writes to the SGPRs from `code`:
- /// `Some(true)` for a 2D image, read only for its size, `Some(false)`
- /// for a structured buffer, read only for its record count.
- ///
- /// - Eight dwords are an image's. `GetDimensions` of a 2D one reads the
- /// width (dwords 1 and 2), the height (dword 2, bits 14-29, with one
- /// `s_bfe_u32`) and the base level or the last (dword 3); of an array,
- /// a cube or a volume also dword 4.
- /// - Four dwords at a table entry the used resources list as an SRV or
- /// UAV are a buffer's. A stride above 4 bytes there is an element's
- /// (a typed or raw view has at most 4): a test for a null view reads
- /// the record count, nothing else.
- fn sized_view(&self, inst: &Inst, site: Site, code: u8, count: u32) -> Option<bool> {
- let dword = |k: u8| inst.write(Reg::S(code + k));
- let read = |v: Value| {
- self.x.p.blocks.iter().any(|b| {
- b.insts.iter().any(|i| i.reads.iter().any(|r| r.1 == v))
- || b.phis.iter().any(|p| p.args.contains(&v))
- })
- };
- let only = |allowed: &[u8]| {
- (0..count as u8).all(|k| allowed.contains(&k) || !dword(k).is_some_and(read))
- };
- match count {
- 8 => {
- const HEIGHT: u32 = 16 << 16 | 14;
- let v = dword(2)?;
- let height = self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| {
- i.name() == "s_bfe_u32"
- && i.reads.iter().any(|r| r.1 == v)
- && matches!(&i.fields, Fields::Sop { src, .. }
- if matches!(src.get(1), Some(Operand::Literal(HEIGHT))))
- });
- (height && only(&[1, 2, 3])).then_some(true)
- }
- 4 => {
- let used = self.used_kind(&Source::Loaded { load: site, first: 0 })?;
- let a = self.scalar.get(&site)?;
- let buffer = used.dwords == 4
- && a.dynamic.is_none()
- && used.table_offset_dwords == a.offset / 4
- && matches!(used.kind, ResourceType::Srv | ResourceType::Uav)
- && used.stride > 4
- && used.stride.is_multiple_of(4);
- (buffer && only(&[2])).then_some(false)
- }
- _ => None,
- }
- }
- /// The title address (low dword, bits from 32 up) of the buffer view
- /// whose descriptor the scalar load at `site` reads from the start of
- /// a table entry, as the host tells it when it binds (`shader.rs`
- /// `USER_VIEW_ADDRESS`); none for anything else. (The console's
- /// descriptor holds more in the second dword, the stride from bit 16
- /// up; code that takes the address masks those away.)
- fn view_address(&mut self, site: Site) -> Option<(V, V)> {
- use super::shader::USER_VIEW_ADDRESS;
- let a = self.scalar.get(&site).copied()?;
- let rp = *self.x.native.layout.get(a.param)?;
- if rp.root != RootType::Table || a.dynamic.is_some() || a.offset % 32 != 0 {
- return None;
- }
- let dword = a.offset / 4;
- let used = self
- .x
- .native
- .used
- .iter()
- .filter(|u| {
- u.root == RootType::Table
- && u.user_data == rp.user_data
- && u.table_offset_dwords <= dword
- })
- .max_by_key(|u| u.table_offset_dwords)?;
- if used.dwords != 4 || !matches!(used.kind, ResourceType::Srv | ResourceType::Uav) {
- return None;
- }
- let lo = self.host_word(RootType::Other(USER_VIEW_ADDRESS), rp.slot, dword);
- let hi = self.host_word(RootType::Other(USER_VIEW_ADDRESS + 1), rp.slot, dword);
- Some((lo, hi))
- }
- /// `lo`, `hi` plus the instruction's byte offset `off`, with the carry.
- fn address_plus(&mut self, lo: V, hi: V, off: i32) -> (V, V) {
- if off == 0 {
- return (lo, hi);
- }
- let c = self.cur;
- let i32t = self.s.t.i32;
- let k = self.s.m.i32(off as u32);
- let sum = self.s.m.bin(c, Bin::Add, lo, k);
- // Up: a carry when the sum wrapped below `lo`. Down: a borrow when
- // it wrapped above.
- let wrapped = self
- .s
- .m
- .cmp(c, if off > 0 { pred::IULT } else { pred::IUGT }, sum, lo);
- let one = self.s.m.cast(c, Cast::ZExt, wrapped, i32t);
- let hi = self.s.m.bin(c, if off > 0 { Bin::Add } else { Bin::Sub }, hi, one);
- (sum, hi)
- }
- /// Title memory at the 40-bit address `lo`, `hi` (`shader.rs`
- /// `SLOT_MEMORY`): the handle of the raw view of the host copy holding
- /// it and the byte in that view. A page without a copy reads zeros
- /// (and drops writes) through the null view at the first slot, and its
- /// number is left for the host, for lanes that run (`guard`). Goes on in
- /// another block.
- /// With `store`, a page that is not to be written ([`super::shader::MEMORY_READ_ONLY`])
- /// is the null view.
- fn memory(&mut self, lo: V, hi: V, guard: Option<V>, store: bool) -> (V, V) {
- use super::shader::{MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE};
- let c = self.cur;
- let (i32t, res) = (self.s.t.i32, self.s.t.res_ret);
- let k = |l: &mut Self, v: u32| l.s.m.i32(v);
- let (k16, k8) = (k(self, 16), k(self, 0xFF));
- let low = self.s.m.bin(c, Bin::LShr, lo, k16);
- let high = self.s.m.bin(c, Bin::And, hi, k8);
- let high = self.s.m.bin(c, Bin::Shl, high, k16);
- let page = self.s.m.bin(c, Bin::Or, low, high);
- // Inside the directory whatever the address (lanes that do not run
- // compute one too); its last entry is never filled.
- let last = k(self, MEMORY_PAGES - 1);
- let page = self
- .s
- .op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[page, last]);
- self.s.m.tag(page, Tag::Clamp);
- let k3 = k(self, 3);
- let at = self.s.m.bin(c, Bin::Shl, page, k3);
- let directory = self.s.root_srv_handle(SLOT_MEMORY);
- let (iu, both, align) = (self.s.m.undef(i32t), self.s.m.i8(3), k(self, 4));
- let entry = self.s.op(
- c,
- "rawBufferLoad.f32",
- Attr::ReadOnly,
- res,
- 139,
- &[directory, at, iu, both, align],
- );
- let (copy, start) = (self.s.m.extract(c, entry, 0), self.s.m.extract(c, entry, 1));
- let (number, start) = (self.as_int(copy), self.as_int(start));
- let mask = k(self, !MEMORY_READ_ONLY);
- let copy = self.s.m.bin(c, Bin::And, number, mask);
- // A page without a copy: its number, at a place by the number. In a
- // branch: the notes lie in the PC's memory, and a store there with
- // every node of every ray would be most of what a trace does.
- let zero = k(self, 0);
- let mut missing = self.s.m.cmp(c, pred::EQ, copy, zero);
- if let Some(g) = guard {
- missing = self.s.m.bin(c, Bin::And, missing, g);
- }
- let places = k(self, MEMORY_FAULTS - 1);
- let faults = self.s.root_uav_handle(SLOT_FAULTS);
- let noting = self.begin_guarded(Some(missing));
- let c = self.cur;
- let place = self.s.m.bin(c, Bin::URem, page, places);
- let one = k(self, 1);
- let place = self.s.m.bin(c, Bin::Add, place, one);
- let k2 = k(self, 2);
- let place = self.s.m.bin(c, Bin::Shl, place, k2);
- let void = self.s.t.void;
- let mask = self.s.m.i8(1);
- self.s.op(
- c,
- "rawBufferStore.i32",
- Attr::NoUnwind,
- void,
- 140,
- &[faults, place, iu, page, iu, iu, iu, mask, align],
- );
- self.end_guarded(noting, &[]);
- let c = self.cur;
- self.page_there = Some(self.s.m.cmp(c, pred::NE, copy, zero));
- let copy = if store {
- let closed = self.s.m.cmp(c, pred::SLT, number, zero);
- self.s.m.select(c, closed, zero, copy)
- } else {
- copy
- };
- let base = self.host_word(RootType::Other(USER_MEMORY_BASE), 0, 0);
- let slot = self.s.m.bin(c, Bin::Add, base, copy);
- // The builder's threads read what others of the dispatch wrote (a
- // refit climbs from children to parents): globally coherent.
- let coherent = if crate::spill::is_spilled(self.x.native) { 0x4000 } else { 0 };
- let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000 | coherent, 0));
- let k64k = k(self, 0xFFFF);
- let within = self.s.m.bin(c, Bin::And, lo, k64k);
- let byte = self.s.m.bin(c, Bin::Add, start, within);
- (h, byte)
- }
- /// The title address in the root view `src` is built around, in a program
- /// with a spilled user-data table (`shader.rs` `USER_ROOT_ADDRESS`).
- fn root_address(&mut self, src: &Source) -> Option<(V, V)> {
- use super::shader::USER_ROOT_ADDRESS;
- let Source::Built { address, .. } = src else {
- return None;
- };
- let rp = *self.x.native.layout.get(address.param)?;
- if rp.root != RootType::Descriptor || !crate::spill::is_spilled(self.x.native) {
- return None;
- }
- let used = self.x.native.used.iter().find(|u| u.user_data == rp.user_data)?;
- if !matches!(used.kind, ResourceType::Srv | ResourceType::Uav) {
- return None;
- }
- let lo = self.host_word(RootType::Other(USER_ROOT_ADDRESS), rp.slot, 0);
- let hi = self.host_word(RootType::Other(USER_ROOT_ADDRESS + 1), rp.slot, 0);
- Some((lo, hi))
- }
- /// For an access through such a root view: the raw view of the host copy
- /// and the byte in it of the view's byte `off` (signed: an offset below
- /// the address stays below it). [`Lower::handle`] gives the same view for
- /// the rest of the instruction. None for any other source. Goes on in
- /// another block.
- /// shortcut: an access of several dwords is taken not to cross the end
- /// of a host copy (the builder's records lie on their size).
- fn root_memory(&mut self, src: &Source, off: V, guard: Option<V>, store: bool) -> Option<(V, V)> {
- let (lo, hi) = self.root_address(src)?;
- let c = self.cur;
- let i32t = self.s.t.i32;
- let sum = self.s.m.bin(c, Bin::Add, lo, off);
- let wrapped = self.s.m.cmp(c, pred::IULT, sum, lo);
- let carry = self.s.m.cast(c, Cast::ZExt, wrapped, i32t);
- let k31 = self.s.m.i32(31);
- let sign = self.s.m.bin(c, Bin::AShr, off, k31);
- let hi = self.s.m.bin(c, Bin::Add, hi, carry);
- let hi = self.s.m.bin(c, Bin::Add, hi, sign);
- let (h, byte) = self.memory(sum, hi, guard, store);
- self.root_copy = Some(h);
- Some((h, byte))
- }
- /// `global_load_*`, `global_store_*` and `global_atomic_*` on title
- /// memory by address (`resource::MEMORY`): the address is the VGPR
- /// pair, each lane its own.
- fn memory_flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
- let Fields::Flat {
- dst,
- addr,
- data,
- saddr,
- offset,
- lds,
- cache,
- } = &inst.fields
- else {
- unreachable!()
- };
- if *lds || !matches!(saddr, None | Some(Operand::Scalar { code: NULL, .. })) {
- return Err("a global address with a scalar base");
- }
- let Some(Operand::Vector { reg: areg, .. }) = *addr else {
- return Err("a global address not in VGPRs");
- };
- let word = |l: &mut Self, k: u8| -> Result<V, Why> {
- let v = inst.read(Reg::V(areg + k)).ok_or("a global address")?;
- l.i32_of(v)
- };
- let (lo, hi) = (word(self, 0)?, word(self, 1)?);
- let (lo, hi) = self.address_plus(lo, hi, i32::from(*offset));
- let guard = self.guard(b, i)?;
- let (i32t, res, void) = (self.s.t.i32, self.s.t.res_ret, self.s.t.void);
- let iu = self.s.m.undef(i32t);
- let align = self.s.m.i32(4);
- let name = inst.name();
- let count = |rest: &str| match rest {
- "dword" => Ok(1u8),
- "dwordx2" => Ok(2),
- "dwordx3" => Ok(3),
- "dwordx4" => Ok(4),
- _ => Err(name),
- };
- if let Some(rest) = name.strip_prefix("global_load_") {
- let n = count(rest)?;
- let Some(Operand::Vector { reg, .. }) = *dst else {
- return Err("a global load result");
- };
- let (h, byte) = self.memory(lo, hi, guard, false);
- let c = self.cur;
- let mask = self.s.m.i8((1u8 << n) - 1);
- let r = self.s.op(
- c,
- "rawBufferLoad.f32",
- Attr::ReadOnly,
- res,
- 139,
- &[h, byte, iu, mask, align],
- );
- for k in 0..n {
- let x = self.s.m.extract(c, r, u32::from(k));
- let x = self.as_int(x);
- self.write(inst, Reg::V(reg + k), x, guard);
- }
- return Ok(());
- }
- if let Some(rest) = name.strip_prefix("global_store_") {
- let n = count(rest)?;
- let d = data.as_ref().ok_or("global store data")?;
- let vals = self.vgprs(inst, d, n)?;
- let (h, byte) = self.memory(lo, hi, guard, true);
- let mut args = vec![h, byte, iu];
- args.extend(&vals);
- args.resize(3 + 4, iu);
- args.push(self.s.m.i8((1u8 << n) - 1));
- args.push(align);
- let at = self.begin_guarded(guard);
- self.s
- .op(self.cur, "rawBufferStore.i32", Attr::NoUnwind, void, 140, &args);
- self.end_guarded(at, &[]);
- return Ok(());
- }
- let Some(op) = name.strip_prefix("global_atomic_") else {
- return Err(name);
- };
- let d = data.as_ref().ok_or("global atomic data")?;
- let v = self.vgprs(inst, d, 1)?[0];
- // With `glc` the value from before comes back, in the result
- // register the instruction names.
- let back = match (*dst, cache.glc) {
- (Some(Operand::Vector { reg, .. }), true) => Some(reg),
- _ => None,
- };
- let old = match back.and_then(|reg| inst.read(Reg::V(reg))) {
- Some(x) => self.i32_of(x)?,
- None => self.s.m.i32(0),
- };
- let (h, byte) = self.memory(lo, hi, guard, true);
- let c = self.cur;
- // DXIL's atomic operations: add 0, and 1, or 2, xor 3, signed
- // minimum 4 and maximum 5, unsigned 6 and 7, exchange 8.
- let simple = match op {
- "add" => Some((0, v)),
- "sub" => {
- let zero = self.s.m.i32(0);
- Some((0, self.s.m.bin(c, Bin::Sub, zero, v)))
- }
- "and" => Some((1, v)),
- "or" => Some((2, v)),
- "xor" => Some((3, v)),
- "smin" => Some((4, v)),
- "smax" => Some((5, v)),
- "umin" => Some((6, v)),
- "umax" => Some((7, v)),
- "swap" => Some((8, v)),
- "fmin" | "fmax" => None,
- _ => return Err(name),
- };
- let at = self.begin_guarded(guard);
- let was = match simple {
- Some((code, x)) => {
- let code = self.s.m.i32(code);
- self.s.op(
- self.cur,
- "atomicBinOp.i32",
- Attr::NoUnwind,
- i32t,
- 78,
- &[h, code, byte, iu, iu, x],
- )
- }
- None => {
- // A float minimum or maximum has no atomic operation on
- // the host: the dword is exchanged for the smaller (larger)
- // of itself and the value until no other thread got in
- // between. Each failed pass means another one's succeeded;
- // the limit only keeps a broken card from hanging.
- let head = self.cur;
- let mask = self.s.m.i8(1);
- let first = self.s.op(
- head,
- "rawBufferLoad.f32",
- Attr::ReadOnly,
- res,
- 139,
- &[h, byte, iu, mask, align],
- );
- let first = self.s.m.extract(head, first, 0);
- let first = self.as_int(first);
- let (pass, done) = (self.s.m.new_block(), self.s.m.new_block());
- self.s.m.terminate(head, Term::Br(pass));
- self.cur = pass;
- let seen = self.s.m.phi(pass, i32t);
- let n = self.s.m.phi(pass, i32t);
- let (f32t, fv) = (self.s.t.f32, self.as_float(v));
- let fseen = self.as_float(seen);
- // `dx.op.binary`: FMax 35, FMin 36.
- let pick = if op == "fmin" { 36 } else { 35 };
- let wanted = self
- .s
- .op(pass, "binary.f32", Attr::ReadNone, f32t, pick, &[fseen, fv]);
- let wanted = self.as_int(wanted);
- let found = self.s.op(
- pass,
- "atomicCompareExchange.i32",
- Attr::NoUnwind,
- i32t,
- 79,
- &[h, byte, iu, iu, seen, wanted],
- );
- let one = self.s.m.i32(1);
- let n1 = self.s.m.bin(pass, Bin::Add, n, one);
- let lost = self.s.m.cmp(pass, pred::NE, found, seen);
- let limit = self.s.m.i32(1 << 16);
- let more = self.s.m.cmp(pass, pred::IULT, n1, limit);
- let again = self.s.m.bin(pass, Bin::And, lost, more);
- self.s.m.terminate(pass, Term::CondBr(again, pass, done));
- let zero = self.s.m.i32(0);
- self.s.m.set_phi(seen, vec![(first, head), (found, pass)]);
- self.s.m.set_phi(n, vec![(zero, head), (n1, pass)]);
- self.cur = done;
- found
- }
- };
- let was = self.end_guarded(at, &[(was, old)])[0];
- if let Some(reg) = back {
- self.write(inst, Reg::V(reg), was, None);
- }
- Ok(())
- }
- /// `s_load_dword*` from title memory by address (`resource::MEMORY`):
- /// the SGPR pair plus the instruction's offsets.
- fn memory_smem(&mut self, inst: &Inst) -> Result<(), Why> {
- let Fields::Smem {
- data: Some(Operand::Scalar { code, .. }),
- base: Operand::Scalar { code: base, .. },
- offset,
- soffset,
- ..
- } = inst.fields
- else {
- return Err("a scalar load from memory");
- };
- let count = match inst.name().strip_prefix("s_load_dword") {
- Some("") => 1u8,
- Some("x2") => 2,
- Some("x4") => 4,
- Some("x8") => 8,
- Some("x16") => 16,
- _ => return Err("a scalar memory access by address"),
- };
- let word = |l: &mut Self, k: u8| -> Result<V, Why> {
- let v = inst.read(Reg::S(base + k)).ok_or("an address not in SGPRs")?;
- l.i32_of(v)
- };
- let (mut lo, mut hi) = (word(self, 0)?, word(self, 1)?);
- let c = self.cur;
- let (i32t, res) = (self.s.t.i32, self.s.t.res_ret);
- if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
- // An offset register counts up from the address.
- let so = self.operand(inst, &soffset)?;
- let sum = self.s.m.bin(c, Bin::Add, lo, so);
- let carry = self.s.m.cmp(c, pred::IULT, sum, lo);
- let carry = self.s.m.cast(c, Cast::ZExt, carry, i32t);
- hi = self.s.m.bin(c, Bin::Add, hi, carry);
- lo = sum;
- }
- let (iu, align) = (self.s.m.undef(i32t), self.s.m.i32(4));
- for first in (0..count).step_by(4) {
- let n = (count - first).min(4);
- let (lo, hi) = self.address_plus(lo, hi, offset + 4 * i32::from(first));
- let (h, byte) = self.memory(lo, hi, None, false);
- let c = self.cur;
- let mask = self.s.m.i8((1u8 << n) - 1);
- let r = self.s.op(
- c,
- "rawBufferLoad.f32",
- Attr::ReadOnly,
- res,
- 139,
- &[h, byte, iu, mask, align],
- );
- for k in 0..n {
- let x = self.s.m.extract(c, r, u32::from(k));
- let x = self.as_int(x);
- self.write(inst, Reg::S(code + first + k), x, None);
- }
- }
- Ok(())
- }
- /// A dword of a lane mask as a number: the ballot of the lanes' bits,
- /// taken in the block that writes the mask (see [`MaskData`]).
- fn mask_dword(&mut self, v: Value) -> Result<V, Why> {
- let (lo, high) = match self.x.st.highs.get(&v) {
- Some(&lo) => (lo, true),
- None => (v, false),
- };
- let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?;
- // A mask that holds lanes outside EXEC where it is written (the complement of one,
- // say) is the ballot of the lanes that are there: all of them, where two exchanging
- // host waves know every lane runs that block.
- let made = self.def_block.get(&lo).copied();
- let whole = self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b));
- if !self.x.st.active.contains(&lo) && !whole {
- if self.exchange.is_some() && !self.local {
- need(made.unwrap_or(0));
- }
- return Err(MASK_ELSEWHERE);
- }
- let (x, y) = match self.ballots.get(&lo) {
- Some(&xy) => xy,
- None => {
- let at = match self.def_block.get(&lo) {
- // Program inputs (EXEC on entry).
- None => self.s.entry,
- Some(&b) if b == self.cur_ir => self.cur,
- Some(&b) => self.tail[b].ok_or("a lane mask written after its use")?,
- };
- if !self.balloting.insert(lo) {
- return Err("a lane mask whose lanes depend on its own value");
- }
- let bit = self.boolean(m, at);
- self.balloting.remove(&lo);
- let bit = bit?;
- let i32t = self.s.t.i32;
- let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
- let r = self
- .s
- .op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, &[bit]);
- self.s.flags |= flags::WAVE_OPS;
- let mut xy = (self.s.m.extract(at, r, 0), self.s.m.extract(at, r, 1));
- if self.exchange.is_some() {
- // a host wave's ballot is its half's 32 bits: the halves exchange them
- let b = self.def_block.get(&lo).copied();
- if self.local {
- if !self.local_ok && !self.local_any {
- return Err("a lane mask read as data in a half-wave");
- }
- } else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) {
- // (a group of 32 or fewer has no other half to exchange with)
- need(b.unwrap_or(0));
- return Err("a lane mask exchanged where not every lane runs");
- }
- xy = self.exchange_halves(at, xy.0);
- }
- self.ballots.insert(lo, xy);
- xy
- }
- };
- Ok(if high { y } else { x })
- }
- // ---- operands ----
- fn operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> {
- match *op {
- Operand::Scalar { code: NULL, .. } => Ok(self.s.m.i32(0)),
- Operand::Scalar { code, .. } => {
- let v = inst.read(Reg::S(code)).ok_or("an unread operand")?;
- self.i32_of(v)
- }
- Operand::Vector { reg, .. } => {
- let v = inst.read(Reg::V(reg)).ok_or("an unread operand")?;
- self.i32_of(v)
- }
- // src_scc: SCC as 0 or 1 (VIctory upstream 0b35b7f, as the dot
- // products and packed multiply-adds below).
- Operand::Const(253) => {
- let bit = self.scc_in(inst)?;
- Ok(self.s.m.cast(self.cur, Cast::ZExt, bit, self.s.t.i32))
- }
- // Nothing to wait for (see `ordered_section`).
- Operand::Const(POPS_EXITING) if !self.ordered.is_empty() => Ok(self.s.m.i32(0)),
- Operand::Const(c) => crate::resource::inline(c)
- .map(|x| self.s.m.i32(x))
- .ok_or("a special operand (vccz, execz, scc, lds_direct)"),
- Operand::Literal(x) => Ok(self.s.m.i32(x)),
- Operand::Attr { .. } => Err("an attribute operand"),
- }
- }
- /// An operand read as f16 data: GFX10 puts an inline f16 constant in
- /// the low half of the operand (upstream PR #637, checked there against
- /// the instruction encodings; the half-and-half reading taken from PR
- /// #458 gave the high half the constant too).
- fn f16_operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> {
- match *op {
- Operand::Const(c @ 240..=248) => Ok(self.s.m.i32(inline_f16(c))),
- _ => self.operand(inst, op),
- }
- }
- fn as_float(&mut self, x: V) -> V {
- self.s.m.cast(self.cur, Cast::Bitcast, x, self.s.t.f32)
- }
- fn as_int(&mut self, f: V) -> V {
- self.s.m.cast(self.cur, Cast::Bitcast, f, self.s.t.i32)
- }
- /// The SDWA operand selection of source `k`: a byte or word of the
- /// dword, zero- or sign-extended (none: the whole dword).
- fn sdwa_src(inst: &Inst, k: usize) -> Option<(u8, bool)> {
- let Fields::Valu(v) = &inst.fields else {
- return None;
- };
- let s = v.sdwa?;
- let sel = *s.src_sel.get(k)?;
- let sext = s.sext >> k & 1 != 0;
- (sel < 6).then_some((sel, sext))
- }
- /// Bits `sel` (0-3 a byte, 4-5 a word) of `x`, extended.
- fn select_bits(&mut self, x: V, sel: u8, sext: bool) -> V {
- let c = self.cur;
- let (width, at) = if sel < 4 {
- (8, 8 * sel)
- } else {
- (16, 16 * (sel - 4))
- };
- let left = self.s.m.i32(u32::from(32 - width - at));
- let t = self.s.m.bin(c, Bin::Shl, x, left);
- let right = self.s.m.i32(32 - u32::from(width));
- let op = if sext { Bin::AShr } else { Bin::LShr };
- self.s.m.bin(c, op, t, right)
- }
- /// A float source with its abs/neg modifiers.
- fn fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- let op = *v.src.get(k).ok_or("a missing operand")?;
- let selected = Self::sdwa_src(inst, k);
- let mut f = match op {
- _ if selected.is_some() => {
- let (sel, sext) = selected.expect("checked");
- let x = self.operand(inst, &op)?;
- let x = self.select_bits(x, sel, sext);
- self.as_float(x)
- }
- _ if k == 0 && self.src0.is_some() => {
- let x = self.src0.expect("checked");
- self.as_float(x)
- }
- Operand::Vector { reg, .. } | Operand::Scalar { code: reg, .. }
- if !matches!(op, Operand::Scalar { code: NULL, .. }) =>
- {
- let r = if matches!(op, Operand::Vector { .. }) {
- Reg::V(reg)
- } else {
- Reg::S(reg)
- };
- let val = inst.read(r).ok_or("an unread operand")?;
- match self.floats.get(&val) {
- Some(&f) => f,
- None => {
- let x = self.i32_of(val)?;
- self.as_float(x)
- }
- }
- }
- _ => {
- let x = self.operand(inst, &op)?;
- self.as_float(x)
- }
- };
- if v.abs >> k & 1 != 0 {
- f = self.unary(6, f);
- }
- if v.neg >> k & 1 != 0 {
- let z = self.s.m.f32(0x8000_0000);
- f = self.s.m.bin(self.cur, Bin::Sub, z, f);
- }
- Ok(f)
- }
- fn src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- let op = *v.src.get(k).ok_or("a missing operand")?;
- if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 {
- return Err("integer operand modifiers");
- }
- match self.src0 {
- Some(x) if k == 0 => Ok(x),
- _ => {
- let x = self.operand(inst, &op)?;
- Ok(match Self::sdwa_src(inst, k) {
- Some((sel, sext)) => self.select_bits(x, sel, sext),
- None => x,
- })
- }
- }
- }
- fn unary(&mut self, op: u32, f: V) -> V {
- self.s.op(
- self.cur,
- "unary.f32",
- Attr::ReadNone,
- self.s.t.f32,
- op,
- &[f],
- )
- }
- fn binary(&mut self, op: u32, a: V, b: V) -> V {
- self.s.op(
- self.cur,
- "binary.f32",
- Attr::ReadNone,
- self.s.t.f32,
- op,
- &[a, b],
- )
- }
- /// The hardware's maximum (`max`) or minimum of two floats: as DXIL's
- /// FMax/FMin, but -0 orders below +0 (RDNA2 ISA, `v_max_f32`), where
- /// the compare and select DXIL specifies gives either zero.
- fn max_min(&mut self, max: bool, a: V, b: V) -> V {
- let c = self.cur;
- let r = self.binary(if max { 35 } else { 36 }, a, b);
- let (ia, ib) = (self.as_int(a), self.as_int(b));
- let either = self.s.m.bin(c, Bin::Or, ia, ib);
- let magnitude = self.s.m.i32(0x7FFF_FFFF);
- let either = self.s.m.bin(c, Bin::And, either, magnitude);
- let zero = self.s.m.i32(0);
- let zeros = self.s.m.cmp(c, pred::EQ, either, zero);
- // Of two zeros, +0 unless both are -0 (max), -0 unless neither (min).
- let op = if max { Bin::And } else { Bin::Or };
- let sign = self.s.m.bin(c, op, ia, ib);
- let signed = self.as_float(sign);
- self.s.m.select(c, zeros, signed, r)
- }
- fn fmad(&mut self, a: V, b: V, c: V) -> V {
- self.s.op(
- self.cur,
- "tertiary.f32",
- Attr::ReadNone,
- self.s.t.f32,
- 46,
- &[a, b, c],
- )
- }
- /// `f` as an f16 in the low bits, rounded toward zero: the nearest-even
- /// conversion, one step back toward zero where it rounded away (which
- /// also turns an overflow to infinity into the largest finite half).
- fn f16_toward_zero(&mut self, f: V) -> V {
- let c = self.cur;
- let i32t = self.s.t.i32;
- let h = self
- .s
- .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
- let back = self
- .s
- .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]);
- let (fa, ba) = (self.unary(6, f), self.unary(6, back));
- // Ordered: never for NaN.
- let away = self.s.m.cmp(c, pred::OGT, ba, fa);
- let one = self.s.m.i32(1);
- let stepped = self.s.m.bin(c, Bin::Sub, h, one);
- self.s.m.select(c, away, stepped, h)
- }
- /// `f` as an f16 in the low bits, rounded to nearest, ties to even, as the console's
- /// 16-bit float operations round, whatever the host's own conversion does: D3D lets
- /// `f32tof16` round toward zero, and the NVIDIA driver's does (measured on an RTX 4070:
- /// `wave64_tests`). The conversion toward zero, or the next half away from zero where
- /// that one is nearer, or as near and the first one odd. Past the largest half the next
- /// one counts as 2^16, the bound IEEE rounds by, so 65520 and up become infinity.
- /// (`f` is an f32 result of two halves here; rounding it again to 16 bits gives the
- /// rounding of the exact result, 24 bits being more than twice 11 and two.)
- fn f16_nearest(&mut self, f: V) -> V {
- let c = self.cur;
- let f32t = self.s.t.f32;
- let lo = self.f16_toward_zero(f);
- let (one, zero) = (self.s.m.i32(1), self.s.m.i32(0));
- let hi = self.s.m.bin(c, Bin::Add, lo, one);
- let size = |l: &mut Self, h: V| {
- let w = l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
- l.unary(6, w)
- };
- let (below, above) = (size(self, lo), size(self, hi));
- let (magnitude, infinity) = (self.s.m.i32(0x7FFF), self.s.m.i32(0x7C00));
- let m = self.s.m.bin(c, Bin::And, hi, magnitude);
- let top = self.s.m.cmp(c, pred::EQ, m, infinity);
- let bound = self.s.m.f32(65536.0f32.to_bits());
- let above = self.s.m.select(c, top, bound, above);
- let fa = self.unary(6, f);
- // (both differences are exact: the three values lie within one half's step)
- let under = self.s.m.bin(c, Bin::Sub, fa, below);
- let over = self.s.m.bin(c, Bin::Sub, above, fa);
- // Ordered: never for NaN, which stays what the conversion made of it.
- let nearer = self.s.m.cmp(c, pred::OLT, over, under);
- let tie = self.s.m.cmp(c, pred::OEQ, over, under);
- let odd = self.s.m.bin(c, Bin::And, lo, one);
- let odd = self.s.m.cmp(c, pred::NE, odd, zero);
- let tie = self.s.m.bin(c, Bin::And, tie, odd);
- let up = self.s.m.bin(c, Bin::Or, nearer, tie);
- self.s.m.select(c, up, hi, lo)
- }
- /// `(a >> off[4:0]) & ((1 << width) - 1)`, sign-extended from the field's
- /// top bit when `signed`; widths from 32 on take every bit. A signed
- /// field that runs past bit 31 extends from bit 31, as the hardware
- /// does: the shift is arithmetic then.
- fn bfe(&mut self, a: V, off: V, width: V, signed: bool) -> V {
- let c = self.cur;
- let (k31, k32, zero, one, ones) = (
- self.s.m.i32(31),
- self.s.m.i32(32),
- self.s.m.i32(0),
- self.s.m.i32(1),
- self.s.m.i32(u32::MAX),
- );
- let off = self.s.m.bin(c, Bin::And, off, k31);
- let shift = if signed { Bin::AShr } else { Bin::LShr };
- let shifted = self.s.m.bin(c, shift, a, off);
- let full = self.s.m.cmp(c, pred::IUGE, width, k32);
- let w = self.s.m.bin(c, Bin::And, width, k31);
- let mask = self.s.m.bin(c, Bin::Shl, one, w);
- let mask = self.s.m.bin(c, Bin::Sub, mask, one);
- let mask = self.s.m.select(c, full, ones, mask);
- let r = self.s.m.bin(c, Bin::And, shifted, mask);
- if !signed {
- return r;
- }
- // Sign-extend a field narrower than 32 bits (none for width 0).
- let left = self.s.m.bin(c, Bin::Sub, k32, w);
- let left = self.s.m.bin(c, Bin::And, left, k31);
- let t = self.s.m.bin(c, Bin::Shl, r, left);
- let t = self.s.m.bin(c, Bin::AShr, t, left);
- let is0 = self.s.m.cmp(c, pred::EQ, w, zero);
- let keep = self.s.m.bin(c, Bin::Or, full, is0);
- self.s.m.select(c, keep, r, t)
- }
- /// Whether an f32 value is NaN, tested in integer arithmetic so host
- /// drivers (such as NVIDIA) do not fold `fcmp uno` away under fast-math.
- fn is_nan_f32(&mut self, f: V) -> V {
- let c = self.cur;
- let bits = self.as_int(f);
- let mask = self.s.m.i32(0x7FFF_FFFF);
- let abs = self.s.m.bin(c, Bin::And, bits, mask);
- let inf = self.s.m.i32(0x7F80_0000);
- self.s.m.cmp(c, pred::IUGT, abs, inf)
- }
- /// The median of three. With a NaN among them the hardware gives the
- /// minimum of the three instead (the host's minimum skips NaNs, so that
- /// is the smallest number among them).
- fn med3(&mut self, a: V, b: V, third: V) -> V {
- let c = self.cur;
- let lo = self.binary(36, a, b);
- let hi = self.binary(35, a, b);
- let t = self.binary(36, hi, third);
- let median = self.binary(35, lo, t);
- let least = self.binary(36, lo, third);
- let nan_a = self.is_nan_f32(a);
- let nan_b = self.is_nan_f32(b);
- let nan_3 = self.is_nan_f32(third);
- let nan_ab = self.s.m.bin(c, Bin::Or, nan_a, nan_b);
- let nan = self.s.m.bin(c, Bin::Or, nan_ab, nan_3);
- self.s.m.select(c, nan, least, median)
- }
- /// `a - floor(a)`, which on the hardware never reaches 1.0: where it
- /// would round to it (a tiny negative `a`), the result is `below_one`,
- /// the largest value under 1.0 in the operation's width. Hosts differ
- /// here (some give 1.0). Comparing against a `threshold` distinct from
- /// `below_one` prevents drivers (observed on NVIDIA) from folding
- /// `r > k ? k : r` into `minNum` (`FMNMX`) and swallowing NaN.
- fn fract(&mut self, a: V, threshold: f32, below_one: f32) -> V {
- let c = self.cur;
- let r = self.unary(22, a);
- let limit = self.s.m.f32(threshold.to_bits());
- let k = self.s.m.f32(below_one.to_bits());
- let over = self.s.m.cmp(c, pred::OGE, r, limit);
- self.s.m.select(c, over, k, r)
- }
- /// Sine, or cosine, of an angle in turns, as the hardware takes it. The
- /// whole turns are taken off first (`x - round_even(x)`, exact, within
- /// half a turn), so a large angle keeps its fraction; scaling to radians
- /// first rounds it away. A zero passes unreduced (the sine of -0 is -0).
- /// The sine of a half turn and the cosine of a quarter turn are exactly
- /// +0 on the hardware, where the host's function of the rounded angle
- /// gives about 1e-7. Infinities and NaN give NaN.
- /// shortcut: below 2^-12 turns the hardware scales by a slightly
- /// different constant than 2π (a last-place difference).
- fn trig_turns(&mut self, x: V, cosine: bool) -> V {
- let c = self.cur;
- let zero = self.s.m.f32(0);
- let whole = self.unary(26, x);
- let part = self.s.m.bin(c, Bin::Sub, x, whole);
- let is_zero = self.s.m.cmp(c, pred::OEQ, x, zero);
- let part = self.s.m.select(c, is_zero, x, part);
- let k = self.s.m.f32(TWO_PI.to_bits());
- let angle = self.s.m.bin(c, Bin::Mul, part, k);
- let r = self.unary(if cosine { 12 } else { 13 }, angle);
- let at = if cosine { 0.25f32 } else { 0.5 };
- let at = self.s.m.f32(at.to_bits());
- let size = self.unary(6, part);
- let exact = self.s.m.cmp(c, pred::OEQ, size, at);
- self.s.m.select(c, exact, zero, r)
- }
- /// The high dword of a 32 × 32-bit product.
- fn mul_hi(&mut self, a: V, b: V, signed: bool) -> V {
- let c = self.cur;
- let i64t = self.s.m.int(64);
- let ext = if signed { Cast::SExt } else { Cast::ZExt };
- let a = self.s.m.cast(c, ext, a, i64t);
- let b = self.s.m.cast(c, ext, b, i64t);
- let m = self.s.m.bin(c, Bin::Mul, a, b);
- let k32 = self.s.m.int_const(i64t, 32);
- let hi = self.s.m.bin(c, Bin::LShr, m, k32);
- self.s.flags |= flags::INT64;
- self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32)
- }
- /// `0 × anything = 0`, as in D3D9.
- fn legacy_mul(&mut self, a: V, b: V) -> V {
- let c = self.cur;
- let m = self.s.m.bin(c, Bin::Mul, a, b);
- let zero = self.s.m.f32(0);
- let az = self.s.m.cmp(c, pred::OEQ, a, zero);
- let bz = self.s.m.cmp(c, pred::OEQ, b, zero);
- let z = self.s.m.bin(c, Bin::Or, az, bz);
- self.s.m.select(c, z, zero, m)
- }
- // ---- lane booleans ----
- fn boolean(&mut self, b: Bool, at: usize) -> Result<V, Why> {
- if b == Bool::TRUE || b == Bool::FALSE {
- return Ok(self.s.m.bool(b == Bool::TRUE));
- }
- if let Some(&v) = self.bools.get(&(at, b)) {
- return Ok(v);
- }
- let (atom, lo, hi) = self.x.st.bools.node(b).expect("not a constant");
- let a = self.atom(atom, at)?;
- let m = &mut self.s.m;
- let v = match (lo, hi) {
- (Bool::FALSE, Bool::TRUE) => a,
- (Bool::TRUE, Bool::FALSE) => {
- let t = m.bool(true);
- m.bin(at, Bin::Xor, a, t)
- }
- (Bool::FALSE, h) => {
- let h = self.boolean(h, at)?;
- self.s.m.bin(at, Bin::And, a, h)
- }
- (l, Bool::TRUE) => {
- let l = self.boolean(l, at)?;
- self.s.m.bin(at, Bin::Or, a, l)
- }
- (l, h) => {
- let l = self.boolean(l, at)?;
- let h = self.boolean(h, at)?;
- self.s.m.select(at, a, h, l)
- }
- };
- self.bools.insert((at, b), v);
- Ok(v)
- }
- fn atom(&mut self, atom: Atom, at: usize) -> Result<V, Why> {
- match atom {
- Atom::Lane(v) => self.lane_bits.get(&v).copied().ok_or_else(|| {
- self.lane_fail
- .get(&v)
- .copied()
- .unwrap_or("a lane mask from a carry")
- }),
- Atom::Uniform(v) => match self.get(v)? {
- Val::Bit(x) => Ok(x),
- Val::I32(x) => {
- let z = self.s.m.i32(0);
- Ok(self.s.m.cmp(at, pred::NE, x, z))
- }
- Val::Missing(w) => Err(w),
- },
- Atom::Phi(id) => {
- if let Some(&v) = self.mask_phis.get(&id) {
- return Ok(v);
- }
- let &(b, i) = self
- .phi_at
- .get(&id)
- .ok_or("a lane-mask join without a phi")?;
- let blk = self.block[b].ok_or("an unreachable join")?;
- let v = self.s.m.phi(blk, self.s.t.i1);
- self.mask_phis.insert(id, v);
- self.pending_masks.push((v, b, i));
- Ok(v)
- }
- // shortcut: "some lane of the quad is set" is taken as true: the
- // lanes it adds only feed derivatives, and exports keep their own
- // masks. Wrong if such a section had a side effect.
- Atom::Quad(_) => Ok(self.s.m.bool(true)),
- // With console lanes, a mask held as a number is the console's:
- // the lane tests its own bit.
- Atom::Opaque(v) if self.console_lanes => {
- let hi = match self.pair_high(v) {
- Some(h) => Some(self.get(h)?),
- None => None,
- };
- let lo = self.get(v)?;
- let word = |w: Val| match w {
- Val::I32(x) => Ok(x),
- _ => Err("an opaque lane mask"),
- };
- let lo = word(lo)?;
- let hi = hi.map(word).transpose()?;
- Ok(self.lane_bit(at, lo, hi))
- }
- Atom::Constant(k) if self.console_lanes => {
- let lo = self.s.m.i32(k as u32);
- let hi = self.s.m.i32((k >> 32) as u32);
- Ok(self.lane_bit(at, lo, Some(hi)))
- }
- Atom::Opaque(_) => Err("an opaque lane mask"),
- Atom::Constant(_) => Err("a constant lane mask"),
- }
- }
- /// A console wave64 program in host waves of 32: the first console thread of this host wave
- /// (0, 32, 64, ...). A GPU need not give a host wave consecutive thread indices (NVIDIA's
- /// 8 x 8 groups), so each wave takes the next 32 from an LDS counter instead: every thread
- /// zeroes it, the group meets, each wave's first lane adds 32 and the wave takes what it
- /// found. Branch-free, in the entry block, which every thread runs.
- fn wave_base(&mut self) -> Option<V> {
- let slot = self.halves?;
- if let Some(v) = self.wave_base {
- return Some(v);
- }
- let (e, i32t) = (self.s.entry, self.s.t.i32);
- let lds = self.s.lds();
- let k = self.s.m.i32(slot);
- let ptr = self.s.m.element(e, lds, k);
- let zero = self.s.m.i32(0);
- self.s.m.store(e, ptr, zero);
- self.group_sync(e);
- let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
- let first = self.s.m.cmp(e, pred::EQ, lane, zero);
- let k32 = self.s.m.i32(32);
- let add = self.s.m.select(e, first, k32, zero);
- let ptr = self.s.m.element(e, lds, k);
- let old = self.s.m.atomic(e, Rmw::Add, ptr, add);
- let base = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[old]);
- self.s.flags |= flags::WAVE_OPS;
- self.wave_base = Some(base);
- Some(base)
- }
- /// The console thread index of this thread in the group: `wave_base` plus the host lane
- /// (host waves of 32), else the wave's first thread index rounded down plus the lane.
- fn console_thread(&mut self) -> V {
- let (e, i32t) = (self.s.entry, self.s.t.i32);
- let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
- if let Some(base) = self.wave_base() {
- return self.s.m.bin(e, Bin::Add, base, lane);
- }
- let flat = self.s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, &[]);
- let first = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[flat]);
- let wave = self.s.wave_size.unwrap_or(32);
- let mask = self.s.m.i32(!(wave - 1));
- let base = self.s.m.bin(e, Bin::And, first, mask);
- self.s.m.bin(e, Bin::Add, base, lane)
- }
- /// This thread's console lane (0..63): its relabelled thread index (`thread_id`), whose host
- /// wave holds a 32-aligned run of console lanes. Without `exchange`: the host lane.
- fn console_lane(&mut self) -> V {
- if self.exchange.is_none() {
- return self.lane_index();
- }
- if let Some(v) = self.clane {
- return v;
- }
- let (e, i32t) = (self.s.entry, self.s.t.i32);
- let f = self.console_thread();
- let _ = i32t;
- let k63 = self.s.m.i32(63);
- let cl = self.s.m.bin(e, Bin::And, f, k63);
- self.s.flags |= flags::WAVE_OPS;
- self.clane = Some(cl);
- cl
- }
- /// A group barrier with an LDS fence in `block`.
- fn group_sync(&mut self, block: usize) {
- let mode = self.s.m.i32(meeting_mode());
- let void = self.s.t.void;
- self.s.op(block, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
- }
- /// `exchange`: each host wave gives `mine` (the same in all its lanes) for its half; both get
- /// (lower half's, upper half's). A group with no upper half gets 0 for it.
- fn exchange_halves(&mut self, at: usize, mine: V) -> (V, V) {
- let Some((slot, small, _)) = self.exchange.as_ref().map(|(a, b, _)| (*a, *b, ())) else {
- let z = self.s.m.i32(0);
- return (mine, z);
- };
- if small {
- let z = self.s.m.i32(0);
- return (mine, z);
- }
- if self.local {
- // each host wave on its own: its half holds `mine`, the other nothing
- let cl = self.console_lane();
- let (k32, z) = (self.s.m.i32(32), self.s.m.i32(0));
- let upper = self.s.m.cmp(at, pred::IUGE, cl, k32);
- let lo = self.s.m.select(at, upper, z, mine);
- let hi = self.s.m.select(at, upper, mine, z);
- return (lo, hi);
- }
- // the pair of dwords of this thread's console wave: its half's, then both
- let pair = self.exchange_pair(slot);
- let cl = self.console_lane();
- let five = self.s.m.i32(5);
- let half = self.s.m.bin(at, Bin::LShr, cl, five);
- let index = self.s.m.bin(at, Bin::Add, pair, half);
- let lds = self.s.lds();
- let ptr = self.s.m.element(at, lds, index);
- self.s.m.store(at, ptr, mine);
- self.group_sync(at);
- let one = self.s.m.i32(1);
- let k1 = self.s.m.bin(at, Bin::Add, pair, one);
- let p0 = self.s.m.element(at, lds, pair);
- let p1 = self.s.m.element(at, lds, k1);
- let lo = self.s.m.load(at, p0);
- let hi = self.s.m.load(at, p1);
- // the slots are written again only after every thread read them
- self.group_sync(at);
- (lo, hi)
- }
- /// The first of the two exchange dwords of this thread's console wave (made in the entry
- /// block): a group of several console waves has a pair for each.
- fn exchange_pair(&mut self, slot: u32) -> V {
- if let Some(v) = self.pair {
- return v;
- }
- let e = self.s.entry;
- let thread = self.console_thread();
- let six = self.s.m.i32(6);
- let wave = self.s.m.bin(e, Bin::LShr, thread, six);
- let one = self.s.m.i32(1);
- let twice = self.s.m.bin(e, Bin::Shl, wave, one);
- let base = self.s.m.i32(slot);
- let v = self.s.m.bin(e, Bin::Add, base, twice);
- self.pair = Some(v);
- v
- }
- /// The console's decision of the branch closing IR block `b`, which the wave takes
- /// together ([`Structured::wide`]): `when` is the lane's own bit, and the branch is taken
- /// when some lane's `when` holds (`execnz`, `vccnz`, SCC of a mask operation set) or
- /// when every lane's does (`execz`, `vccz`, that SCC clear), [`Structured::wave_any`].
- /// Each host wave asks its lanes and the halves exchange the answers, so both go the
- /// same way and can meet again inside the branch.
- /// SCC of a mask operation as data ([`Structured::scc_some`]): whether some lane of the
- /// console wave has its bit of the result, asked where the operation stands. The lanes
- /// that are elsewhere have no bit (the result is ANDed with EXEC or is EXEC), so with
- /// the console's waves the host wave's answer is the console's; two host waves of 32
- /// exchange theirs, which needs every lane there.
- fn scc_some(&mut self, scc: Value) -> Result<V, Why> {
- let &m = self.x.st.scc_some.get(&scc).ok_or(LANE_MASK)?;
- // (not for a console wave cut into host waves that do not exchange)
- if !self.console_lanes || self.local || self.exchange.is_none() && self.halves.is_some() {
- return Err(LANE_MASK);
- }
- let made = self.def_block.get(&scc).copied();
- let at = match made {
- None => self.s.entry,
- Some(b) if b == self.cur_ir => self.cur,
- Some(b) => self.tail[b].ok_or("a lane mask written after its use")?,
- };
- let bit = self.boolean(m, at)?;
- let (i1t, i32t) = (self.s.t.i1, self.s.t.i32);
- let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]);
- self.s.flags |= flags::WAVE_OPS;
- if !self.exchange.as_ref().is_some_and(|e| !e.1) {
- return Ok(some);
- }
- if !made.is_none_or(|b| self.all_lanes(b)) {
- need(made.unwrap_or(0));
- return Err("a lane mask exchanged where not every lane runs");
- }
- let some = self.s.m.cast(at, Cast::ZExt, some, i32t);
- let (lo, hi) = self.exchange_halves(at, some);
- let both = self.s.m.bin(at, Bin::Or, lo, hi);
- let z = self.s.m.i32(0);
- Ok(self.s.m.cmp(at, pred::NE, both, z))
- }
- fn wave_wide(&mut self, b: usize, when: Bool) -> Result<V, Why> {
- const WHY: Why = "a wave-wide branch where not every lane runs";
- let any = self.x.st.wave_any.get(b).copied().flatten().ok_or("a wave-wide branch on a scalar condition")?;
- if self.exchange.is_none() && self.halves.is_none() && self.console_lanes && self.mask_data == MaskData::Console {
- // The host's waves are the console's: the wave's own answer. The lanes that are
- // elsewhere have no bit set, as on the console, so "some lane" needs no one but
- // the lanes here, and "every lane's bit is clear" is true of the others anyway.
- let c = self.cur;
- let mine = self.boolean(when, c)?;
- let i1t = self.s.t.i1;
- self.s.flags |= flags::WAVE_OPS;
- let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) };
- return Ok(self.s.op(c, name, Attr::NoUnwind, i1t, code, &[mine]));
- }
- if self.local || !self.exchange.as_ref().is_some_and(|e| !e.1) {
- return Err(WHY);
- }
- if !self.all_lanes(b) {
- need(b);
- return Err(WHY);
- }
- let c = self.cur;
- let mine = self.boolean(when, c)?;
- // what the halves exchange is "some lane speaks against" either way (for `any`:
- // some lane's `when` holds; else: some lane's does not), so a half with no lane says
- // nothing
- let set = if any {
- mine
- } else {
- let t = self.s.m.bool(true);
- self.s.m.bin(c, Bin::Xor, mine, t)
- };
- let (i1t, i32t) = (self.s.t.i1, self.s.t.i32);
- let some = self.s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]);
- self.s.flags |= flags::WAVE_OPS;
- let some = self.s.m.cast(c, Cast::ZExt, some, i32t);
- let (lo, hi) = self.exchange_halves(c, some);
- let c = self.cur;
- let both = self.s.m.bin(c, Bin::Or, lo, hi);
- let z = self.s.m.i32(0);
- Ok(self.s.m.cmp(c, if any { pred::NE } else { pred::EQ }, both, z))
- }
- /// Whether every lane runs IR block `b` (always true without `exchange`).
- fn all_lanes(&self, b: usize) -> bool {
- self.exchange.as_ref().is_none_or(|(_, _, all)| all.get(b).copied().unwrap_or(false))
- }
- /// This lane's bit of the mask `lo`, `hi` (wave64).
- fn lane_bit(&mut self, at: usize, lo: V, hi: Option<V>) -> V {
- self.s.flags |= flags::WAVE_OPS;
- let lane = if self.exchange.is_some() {
- self.console_lane()
- } else {
- self.s.op(at, "waveGetLaneIndex", Attr::ReadOnly, self.s.t.i32, 111, &[])
- };
- let (k31, k32, one, z) = (
- self.s.m.i32(31),
- self.s.m.i32(32),
- self.s.m.i32(1),
- self.s.m.i32(0),
- );
- let word = match hi {
- Some(hi) => {
- let low = self.s.m.cmp(at, pred::IULT, lane, k32);
- self.s.m.select(at, low, lo, hi)
- }
- None => lo,
- };
- let sh = self.s.m.bin(at, Bin::And, lane, k31);
- let t = self.s.m.bin(at, Bin::LShr, word, sh);
- let t = self.s.m.bin(at, Bin::And, t, one);
- self.s.m.cmp(at, pred::NE, t, z)
- }
- /// The value of the high dword of the wave64 register pair whose low
- /// dword holds `lo` (none in wave32).
- fn pair_high(&self, lo: Value) -> Option<Value> {
- if !self.x.native.wave64 {
- return None;
- }
- let p = self.x.p;
- let pick = |reg: Reg| match reg {
- Reg::S(c) => Some(Reg::S(c + 1)),
- _ => None,
- };
- if let Some(&(reg, _)) = p.inputs.iter().find(|i| i.1 == lo) {
- let h = pick(reg)?;
- return p.inputs.iter().find(|i| i.0 == h).map(|i| i.1);
- }
- if let Some(&(b, i)) = self.phi_at.get(&lo) {
- let h = pick(p.blocks[b].phis[i].reg)?;
- return p.blocks[b]
- .phis
- .iter()
- .find(|q| q.reg == h)
- .map(|q| q.value);
- }
- let b = *self.def_block.get(&lo)?;
- let inst = p.blocks[b]
- .insts
- .iter()
- .find(|i| i.writes.iter().any(|w| w.1 == lo))?;
- let &(reg, _) = inst.writes.iter().find(|w| w.1 == lo)?;
- inst.write(pick(reg)?)
- }
- fn guard(&mut self, b: usize, i: usize) -> Result<Option<V>, Why> {
- match self.x.st.guards[b][i] {
- None => Ok(None),
- Some(g) => Ok(Some(self.boolean(g, self.cur)?)),
- }
- }
- // ---- results ----
- fn set(&mut self, v: Option<Value>, val: Val) {
- if let Some(v) = v {
- self.vals.insert(v, val);
- }
- }
- /// Writes VGPR `reg` (or the SGPR of a lane read), under `guard`.
- fn write(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) {
- let x = match (Self::sdwa_dst(inst), reg) {
- (Some((sel, unused)), Reg::V(_)) => self.place_bits(inst, reg, x, sel, unused),
- _ => x,
- };
- self.write_placed(inst, reg, x, guard);
- }
- /// [`Self::write`] of a dword already placed (SDWA applied).
- fn write_placed(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) {
- let Some(new) = inst.write(reg) else { return };
- let x = match (guard, reg) {
- (Some(g), Reg::V(_)) => {
- let old = match inst.read(reg).map(|o| self.i32_of(o)) {
- Some(Ok(o)) => o,
- // The validator refuses reads of undef.
- _ => self.s.m.i32(0),
- };
- let v = self.s.m.select(self.cur, g, x, old);
- self.s.m.tag(v, Tag::Guard);
- v
- }
- _ => x,
- };
- self.vals.insert(new, Val::I32(x));
- }
- /// The SDWA destination selection: a byte or word, and what the other
- /// bits get (0 zeros, 1 the sign above the field, 2 the old bits).
- fn sdwa_dst(inst: &Inst) -> Option<(u8, u8)> {
- let Fields::Valu(v) = &inst.fields else {
- return None;
- };
- let s = v.sdwa?;
- (s.dst_sel < 6).then_some((s.dst_sel, s.dst_unused))
- }
- /// The low byte or word of `x` placed at `sel` in VGPR `reg`.
- fn place_bits(&mut self, inst: &Inst, reg: Reg, x: V, sel: u8, unused: u8) -> V {
- let c = self.cur;
- let (width, at) = if sel < 4 {
- (8u32, 8 * u32::from(sel))
- } else {
- (16, 16 * u32::from(sel - 4))
- };
- let left = self.s.m.i32(32 - width);
- let t = self.s.m.bin(c, Bin::Shl, x, left);
- let right = self.s.m.i32(32 - width - at);
- if unused == 1 {
- // Bits below the field shift in as zeros.
- return self.s.m.bin(c, Bin::AShr, t, right);
- }
- let field = self.s.m.bin(c, Bin::LShr, t, right);
- if unused != 2 {
- return field;
- }
- let old = match inst.read(reg).map(|o| self.i32_of(o)) {
- Some(Ok(o)) => o,
- _ => self.s.m.i32(0),
- };
- let keep = self.s.m.i32(!((((1u64 << width) - 1) as u32) << at));
- let old = self.s.m.bin(c, Bin::And, old, keep);
- self.s.m.bin(c, Bin::Or, old, field)
- }
- fn write_f(&mut self, inst: &Inst, f: V, guard: Option<V>) -> Result<(), Why> {
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- let mut f = f;
- match v.omod {
- 0 => {}
- k => {
- let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)];
- let c = self.s.m.f32(factor.to_bits());
- f = self.s.m.bin(self.cur, Bin::Mul, f, c);
- }
- }
- if v.clamp {
- f = self.unary(7, f);
- }
- let Some(Operand::Vector { reg, .. }) = v.dst else {
- return Err("a float result outside a VGPR");
- };
- let x = self.as_int(f);
- self.write(inst, Reg::V(reg), x, guard);
- if guard.is_none()
- && Self::sdwa_dst(inst).is_none()
- && let Some(new) = inst.write(Reg::V(reg))
- {
- self.floats.insert(new, f);
- }
- Ok(())
- }
- fn write_i(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> {
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- if v.clamp || v.omod != 0 {
- return Err("integer output modifiers");
- }
- match v.dst {
- Some(Operand::Vector { reg, .. }) => self.write(inst, Reg::V(reg), x, guard),
- Some(Operand::Scalar { code, .. }) => self.write(inst, Reg::S(code), x, None),
- _ => return Err("a result without a register"),
- }
- Ok(())
- }
- /// Starts code only the lanes where `guard` holds run (a store under a
- /// lane guard): returns where it started and the join block.
- fn begin_guarded(&mut self, guard: Option<V>) -> Option<(usize, usize)> {
- let g = guard?;
- let (then, join) = (self.s.m.new_block(), self.s.m.new_block());
- self.s.m.terminate(self.cur, Term::CondBr(g, then, join));
- let head = self.cur;
- self.cur = then;
- Some((head, join))
- }
- /// Ends guarded code; each (value inside, value outside) becomes a phi.
- fn end_guarded(&mut self, at: Option<(usize, usize)>, values: &[(V, V)]) -> Vec<V> {
- let Some((head, join)) = at else {
- return values.iter().map(|v| v.0).collect();
- };
- let then = self.cur;
- self.s.m.terminate(then, Term::Br(join));
- self.cur = join;
- values
- .iter()
- .map(|&(inside, outside)| {
- let ty = self.s.m.type_of(inside);
- let phi = self.s.m.phi(join, ty);
- self.s.m.set_phi(phi, vec![(inside, then), (outside, head)]);
- phi
- })
- .collect()
- }
- /// Code that depends on the lane layout: wave operations, and in compute
- /// the console's wave size (lanes are thread ids in group order there).
- /// Pixel lanes match only within a quad.
- fn cross_lane(&mut self, quad: bool) -> Result<(), Why> {
- if self.s.mesh.is_some() {
- // shortcut: no wave size for mesh shaders in SM 6.6, so host
- // lanes cannot follow the console's; emulate through group-shared
- // memory if mesh programs turn out to need these.
- return Err("a cross-lane operation in a mesh shader");
- }
- if self.s.threads.is_none() && !(quad && self.s.pixel) {
- return Err("a cross-lane operation outside compute");
- }
- debug_assert!(self.s.threads.is_none() || self.console_lanes);
- self.s.flags |= flags::WAVE_OPS;
- Ok(())
- }
- /// Component `c` of the thread id in the group. With console lanes, the
- /// thread is relabelled so that its host lane is its console lane: the
- /// flat id is the wave's first lane's, rounded down to the wave size,
- /// plus the lane index. (A bijection while each host wave holds a
- /// wave-aligned run of flat ids, as the console's waves do.)
- fn thread_id(&mut self, c: u8) -> Val {
- if !self.console_lanes {
- return self.compute_id("threadIdInGroup.i32", 95, c);
- }
- let [x, y, _] = self.s.threads.expect("compute");
- let e = self.s.entry;
- let i32t = self.s.t.i32;
- if self.halves.is_some() {
- let f = self.console_thread();
- self.s.flags |= flags::WAVE_OPS;
- let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y));
- return Val::I32(match c {
- 0 => self.s.m.bin(e, Bin::URem, f, xk),
- 1 => {
- let t = self.s.m.bin(e, Bin::UDiv, f, xk);
- self.s.m.bin(e, Bin::URem, t, yk)
- }
- _ => self.s.m.bin(e, Bin::UDiv, f, xy),
- });
- }
- let flat = self.s.op(
- e,
- "flattenedThreadIdInGroup.i32",
- Attr::ReadNone,
- i32t,
- 96,
- &[],
- );
- let first = self.s.op(
- e,
- "waveReadLaneFirst.i32",
- Attr::NoUnwind,
- i32t,
- 118,
- &[flat],
- );
- let wave = self.s.wave_size.expect("set with console lanes");
- let mask = self.s.m.i32(!(wave - 1));
- let base = self.s.m.bin(e, Bin::And, first, mask);
- let lane = self.lane_index();
- let f = self.s.m.bin(e, Bin::Add, base, lane);
- self.s.flags |= flags::WAVE_OPS;
- let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y));
- Val::I32(match c {
- 0 => self.s.m.bin(e, Bin::URem, f, xk),
- 1 => {
- let t = self.s.m.bin(e, Bin::UDiv, f, xk);
- self.s.m.bin(e, Bin::URem, t, yk)
- }
- _ => self.s.m.bin(e, Bin::UDiv, f, xy),
- })
- }
- /// Mesh: the counts and the primitives no lane exports. The console's
- /// counts come from one lane's allocation request, which DXIL cannot
- /// express (one call, dominating every output write).
- // shortcut: the counts are the declared maxima and each lane first culls
- // its primitive (all indices 0, zero area), so primitives past the
- // program's count are culled and vertices past it unused; this costs
- // the host the unused vertex and primitive slots. Pass the program's own
- // counts if that shows in frame time.
- fn mesh_prologue(&mut self, mut mesh: super::shader::Mesh) -> Result<(), Why> {
- let threads = self.s.threads.expect("mesh")[0];
- if mesh.topology != 2 {
- return Err("a mesh shader not drawing triangles");
- }
- if threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256 {
- return Err("a mesh shader beyond the host's limits");
- }
- // D3D12 caps the outputs of the declared maxima at 32 KiB. Lane n
- // writes only vertex n and primitive n, so maxima past the lanes are
- // never reached: they come down to the lane count when the outputs
- // do not fit.
- use super::container::{MESH_OUTPUT_LIMIT, mesh_output_bytes};
- let (outputs, prims) = (&self.s.outputs, &self.s.prims);
- let fits = |m: super::shader::Mesh| {
- mesh_output_bytes(outputs, prims, m.max_vertices, m.max_primitives) <= MESH_OUTPUT_LIMIT
- };
- if !fits(mesh) {
- mesh.max_vertices = mesh.max_vertices.min(threads);
- mesh.max_primitives = mesh.max_primitives.min(threads);
- // shortcut: outputs past the cap even at the lane count are
- // still emitted with the lower maxima (drivers take them);
- // refuse them here if one hangs.
- // Experiment (`VICTORY_MESH_OUTPUT_STRICT=1`): they are refused.
- if !fits(mesh) && std::env::var_os("VICTORY_MESH_OUTPUT_STRICT").is_some() {
- return Err("a mesh shader whose outputs pass the host's 32 KiB");
- }
- self.s.mesh = Some(mesh);
- }
- let e = self.s.entry;
- let void = self.s.t.void;
- let (v, p) = (
- self.s.m.i32(mesh.max_vertices),
- self.s.m.i32(mesh.max_primitives),
- );
- self.s
- .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]);
- let flat = self.mesh_thread();
- let z = self.s.m.i32(0);
- // Every primitive of the declared count starts culled, also those
- // past the lanes (a count of 256 with 128 lanes): lane n culls
- // primitives n, n + lanes, ... The host draws all it was promised,
- // and one never written has whatever indices its memory held: long
- // triangles over the whole target, each pixel of them shaded.
- let passes = mesh.max_primitives.div_ceil(threads.max(1));
- for pass in 0..passes {
- let index = if pass == 0 {
- flat
- } else {
- let past = self.s.m.i32(pass * threads);
- self.s.m.bin(self.cur, Bin::Add, flat, past)
- };
- let guard = ((pass + 1) * threads > mesh.max_primitives)
- .then(|| self.s.m.cmp(self.cur, pred::IULT, index, p));
- let at = self.begin_guarded(guard);
- self.s.op(
- self.cur,
- "emitIndices",
- Attr::NoUnwind,
- void,
- 169,
- &[index, z, z, z],
- );
- self.end_guarded(at, &[]);
- }
- Ok(())
- }
- /// Mesh: the thread's index in the group, which is its vertex and
- /// primitive index.
- fn mesh_thread(&mut self) -> V {
- if let Some(f) = self.flat {
- return f;
- }
- let e = self.s.entry;
- let f = self.s.op(
- e,
- "flattenedThreadIdInGroup.i32",
- Attr::ReadNone,
- self.s.t.i32,
- 96,
- &[],
- );
- self.flat = Some(f);
- f
- }
- /// The console wave size.
- fn wave(&self) -> u32 {
- if self.x.native.wave64 { 64 } else { 32 }
- }
- fn lane_index(&mut self) -> V {
- if self.s.mesh.is_some() {
- // The console's lane: mesh code reads no other lanes, so host
- // waves need not match the console's.
- let f = self.mesh_thread();
- let m = self.s.m.i32(self.wave() - 1);
- return self.s.m.bin(self.s.entry, Bin::And, f, m);
- }
- self.s.op(
- self.cur,
- "waveGetLaneIndex",
- Attr::ReadOnly,
- self.s.t.i32,
- 111,
- &[],
- )
- }
- /// `x` of lane `src` (in this lane's quad) through quad reads, whose
- /// lane must be a constant.
- fn quad_pick(&mut self, x: V, src: V) -> V {
- self.s.flags |= flags::WAVE_OPS;
- let c = self.cur;
- let three = self.s.m.i32(3);
- let q = self.s.m.bin(c, Bin::And, src, three);
- let mut r = x;
- for n in 0..4 {
- let kn = self.s.m.i32(n);
- let read = self.s.op(
- c,
- "quadReadLaneAt.i32",
- Attr::NoUnwind,
- self.s.t.i32,
- 122,
- &[x, kn],
- );
- let is = self.s.m.cmp(c, pred::EQ, q, kn);
- r = self.s.m.select(c, is, read, r);
- }
- r
- }
- /// Whether a quad-local read takes its lane with the host's quad
- /// operations: in a pixel program always. Lanes of a quad the primitive
- /// does not cover, or that were discarded, are helpers on the host;
- /// wave reads leave those out (AMD gives 0 from them), quad reads are
- /// what reaches them.
- fn helpers_read(&self, quad: bool) -> bool {
- quad && self.s.pixel
- }
- /// `x` of the lane of this lane's quad that `lanes` names for each of
- /// the quad's four, by the host's quad operations.
- fn quad_read(&mut self, x: V, lanes: [u8; 4]) -> V {
- self.s.flags |= flags::WAVE_OPS;
- let c = self.cur;
- let i32t = self.s.t.i32;
- if lanes == [0, 1, 2, 3] {
- return x;
- }
- // One lane for all.
- if lanes.iter().all(|&l| l == lanes[0]) {
- let n = self.s.m.i32(lanes[0].into());
- return self.s.op(
- c,
- "quadReadLaneAt.i32",
- Attr::NoUnwind,
- i32t,
- 122,
- &[x, n],
- );
- }
- // Else each lane's own, its neighbour across in x (1) or y (2), or
- // the diagonal one (3).
- let across = |i: usize| i as u8 ^ lanes[i];
- let mut r = None;
- for by in 0..4u8 {
- if !(0..4).any(|i| across(i) == by) {
- continue;
- }
- let read = if by == 0 {
- x
- } else {
- // QuadReadAcrossX, Y, Diagonal.
- let kind = self.s.m.i8(by - 1);
- self.s
- .op(c, "quadOp.i32", Attr::NoUnwind, i32t, 123, &[x, kind])
- };
- r = Some(match r {
- None => read,
- Some(r) => {
- let mut here = self.s.m.bool(false);
- let lane = self.lane_index();
- let three = self.s.m.i32(3);
- let at = self.s.m.bin(c, Bin::And, lane, three);
- for i in (0..4).filter(|&i| across(i) == by) {
- let k = self.s.m.i32(i as u32);
- let is = self.s.m.cmp(c, pred::EQ, at, k);
- here = self.s.m.bin(c, Bin::Or, here, is);
- }
- self.s.m.select(c, here, read, r)
- }
- });
- }
- r.unwrap_or(x)
- }
- /// `x` in the first lane of this host wave where `guard` holds, and whether it has such a
- /// lane: the console reads the first lane of EXEC, and a lane that got here with EXEC clear
- /// (a guard, not a branch) is not one. With none, `x` of the wave's first lane here.
- ///
- /// A helper lane of a pixel shader takes its own value: the console's whole-quad mode has
- /// helper lanes in EXEC, so a waterfall loop serves them too, and the host's wave operations
- /// leave them out. Once only helper lanes are left in such a loop none of them ever matched:
- /// they ran to the iteration limit, and left with no sample for their quad's derivatives,
- /// along every triangle's edges (upstream #908, the fix of #1733 for this tree's form).
- fn first_lane(&mut self, x: V, guard: Option<V>) -> (V, V) {
- let (first, any) = self.first_live_lane(x, guard);
- if !self.s.pixel || !super::helper_own() {
- return (first, any);
- }
- let helper = self.helper_lane();
- let c = self.cur;
- let yes = self.s.m.bool(true);
- (self.s.m.select(c, helper, x, first), self.s.m.select(c, helper, yes, any))
- }
- /// Whether this lane of a pixel shader is a helper lane.
- fn helper_lane(&mut self) -> V {
- let i1t = self.s.t.i1;
- self.s.op(self.cur, "isHelperLane.i1", Attr::ReadOnly, i1t, 221, &[])
- }
- fn first_live_lane(&mut self, x: V, guard: Option<V>) -> (V, V) {
- let c = self.cur;
- let i32t = self.s.t.i32;
- self.s.flags |= flags::WAVE_OPS;
- let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[x]);
- let Some(g) = guard else {
- return (first, self.s.m.bool(true));
- };
- let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
- let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[g]);
- let (lo, hi) = (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1));
- let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32));
- // FirstbitLo (dx.op 32): the lowest set bit
- let flo = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[lo]);
- let fhi = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[hi]);
- let fhi = self.s.m.bin(c, Bin::Add, fhi, k32);
- let in_lo = self.s.m.cmp(c, pred::NE, lo, z);
- let in_hi = self.s.m.cmp(c, pred::NE, hi, z);
- let any = self.s.m.bin(c, Bin::Or, in_lo, in_hi);
- let lane = self.s.m.select(c, in_lo, flo, fhi);
- // no lane in EXEC: read this lane (one that is here); the read is not used
- let me = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
- let lane = self.s.m.select(c, any, lane, me);
- let at = self.read_lane(x, lane);
- (self.s.m.select(c, any, at, first), any)
- }
- fn read_lane(&mut self, x: V, lane: V) -> V {
- self.s.op(
- self.cur,
- "waveReadLaneAt.i32",
- Attr::NoUnwind,
- self.s.t.i32,
- 117,
- &[x, lane],
- )
- }
- /// The float value of a register value.
- fn float_of(&mut self, v: Value) -> Result<V, Why> {
- if let Some(&f) = self.floats.get(&v) {
- return Ok(f);
- }
- let x = self.i32_of(v)?;
- Ok(self.as_float(x))
- }
- /// The values of VGPRs `reg..reg + n` as `inst` reads them.
- fn vgprs(&mut self, inst: &Inst, op: &Operand, n: u8) -> Result<Vec<V>, Why> {
- let Operand::Vector { reg, .. } = *op else {
- return Err("a vector operand");
- };
- (0..n)
- .map(|k| {
- let v = inst.read(Reg::V(reg + k)).ok_or("an unread operand")?;
- self.i32_of(v)
- })
- .collect()
- }
- /// LDS (thread-group shared memory) and `ds_swizzle`.
- fn ds(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
- let Fields::Ds {
- dst,
- addr,
- data,
- offset0,
- offset1,
- gds,
- } = &inst.fields
- else {
- unreachable!()
- };
- if *gds {
- return Err("GDS");
- }
- let name = inst.name();
- let guard = self.guard(b, i)?;
- let c = self.cur;
- let offset = u32::from(*offset0) | u32::from(*offset1) << 8;
- let dst_reg = match dst {
- Some(Operand::Vector { reg, .. }) => Some(*reg),
- _ => None,
- };
- if name == "ds_swizzle_b32" {
- // Bit 15 set: each lane of a quad picks a lane of it; else lanes
- // of each group of 32 combine their index with and/or/xor masks.
- let quad = offset & 0x8000 != 0
- || offset & 0x1C == 0x1C && offset & 0x380 == 0 && offset >> 10 & 0x1F < 4;
- // Mesh: host quads are threads 4n..4n+3 of a 1D group, as the
- // console's, so quad-local swizzles read through quad operations.
- let mesh_quad = self.s.mesh.is_some() && quad;
- if !mesh_quad {
- self.cross_lane(quad)?;
- }
- // The source sits in the address field.
- let x = self.vgprs(inst, addr.as_ref().ok_or("a swizzle source")?, 1)?[0];
- let lane = self.lane_index();
- let k = |l: &mut Self, v: u32| l.s.m.i32(v);
- let src = if offset & 0x8000 != 0 {
- let (three, one) = (k(self, 3), k(self, 1));
- let sel = self.s.m.bin(c, Bin::And, lane, three);
- let sh = self.s.m.bin(c, Bin::Shl, sel, one);
- let pattern = k(self, offset & 0xFF);
- let pick = self.s.m.bin(c, Bin::LShr, pattern, sh);
- let pick = self.s.m.bin(c, Bin::And, pick, three);
- let not3 = k(self, !3);
- let base = self.s.m.bin(c, Bin::And, lane, not3);
- self.s.m.bin(c, Bin::Or, base, pick)
- } else {
- let and = k(self, offset & 0x1F | !0x1F);
- let or = k(self, offset >> 5 & 0x1F);
- let xor = k(self, offset >> 10 & 0x1F);
- let t = self.s.m.bin(c, Bin::And, lane, and);
- let t = self.s.m.bin(c, Bin::Or, t, or);
- self.s.m.bin(c, Bin::Xor, t, xor)
- };
- let r = if mesh_quad {
- self.quad_pick(x, src)
- } else if self.helpers_read(quad) {
- let lanes = if offset & 0x8000 != 0 {
- [0, 1, 2, 3].map(|i| (offset >> (2 * i) & 3) as u8)
- } else {
- [0, 1, 2, 3].map(|i| ((i & offset | offset >> 5 & 3) ^ offset >> 10 & 3) as u8 & 3)
- };
- self.quad_read(x, lanes)
- } else {
- self.read_lane(x, src)
- };
- let reg = dst_reg.ok_or("a swizzle result")?;
- self.write(inst, Reg::V(reg), r, guard);
- return Ok(());
- }
- if name == "ds_bpermute_b32" {
- // Backward permute: no LDS is touched. Each lane takes the data
- // register of the lane its address names, (address + offset) / 4
- // within the wave; a source lane outside EXEC gives 0. (
- // the title's checkerboard shadow-mask generators read their
- // neighbours' samples with it; without them every shadowed light
- // was multiplied by an empty mask.)
- // shortcut: a source lane that is not at this instruction on the
- // host (it left through a branch, not a guard) is read as the
- // host gives it; the console reads 0.
- self.cross_lane(false)?;
- if self.exchange.as_ref().is_some_and(|e| !e.1) {
- // a console wave of 64 run as two host waves: the lane named
- // may be in the other one
- return Err("a lane permute across two host waves");
- }
- let at = self.vgprs(inst, addr.as_ref().ok_or("a permute address")?, 1)?[0];
- let x = self.vgprs(inst, data.first().ok_or("a permute source")?, 1)?[0];
- let o = self.s.m.i32(offset);
- let at = self.s.m.bin(c, Bin::Add, at, o);
- let two = self.s.m.i32(2);
- let src = self.s.m.bin(c, Bin::LShr, at, two);
- let last = self.s.m.i32(self.wave() - 1);
- let src = self.s.m.bin(c, Bin::And, src, last);
- let x = match guard {
- Some(g) => {
- let z = self.s.m.i32(0);
- self.s.m.select(c, g, x, z)
- }
- None => x,
- };
- let r = self.read_lane(x, src);
- let reg = dst_reg.ok_or("a permute result")?;
- self.write(inst, Reg::V(reg), r, guard);
- return Ok(());
- }
- if self.s.lds_dwords == 0 {
- return Err("LDS the program does not allocate");
- }
- let a = self.vgprs(inst, addr.as_ref().ok_or("an LDS address")?, 1)?[0];
- // shortcut: LDS addresses are taken as dword-aligned and in bounds
- // (out-of-bounds console accesses read 0 and drop writes).
- let dword = |l: &mut Self, bytes: u32| -> V {
- let c = l.cur;
- let o = l.s.m.i32(bytes);
- let at = l.s.m.bin(c, Bin::Add, a, o);
- let two = l.s.m.i32(2);
- let index = l.s.m.bin(c, Bin::LShr, at, two);
- let lds = l.s.lds();
- l.s.m.element(c, lds, index)
- };
- let width = |n: &str| match n.rsplit('_').next() {
- Some("b64") => 2,
- Some("b96") => 3,
- Some("b128") => 4,
- _ => 1,
- };
- // (byte offset, dwords) per element; read2/write2 scale their two
- // offsets by the element size (×64 for st64).
- let pair = |n: &str| -> Vec<(u32, u32)> {
- let w = width(n);
- let scale = 4 * w * if n.contains("st64") { 64 } else { 1 };
- vec![
- (u32::from(*offset0) * scale, w),
- (u32::from(*offset1) * scale, w),
- ]
- };
- // Bytes and halves: the dword holding them, and their bit position
- // in it (naturally aligned, so they never straddle dwords).
- // `_d16` reads fill a register's low half (`_d16_hi` its high half)
- // and keep the other; `_d16_hi` writes take the data's high half.
- let base = name.trim_end_matches("_hi").trim_end_matches("_d16");
- let sub = match base {
- "ds_read_u8" | "ds_read_i8" | "ds_write_b8" => Some(8u32),
- "ds_read_u16" | "ds_read_i16" | "ds_write_b16" => Some(16),
- _ => None,
- };
- let sub = sub.filter(|_| {
- base == name
- || name.ends_with("_d16") && base.starts_with("ds_read")
- || name.ends_with("_d16_hi")
- });
- if let Some(bits) = sub {
- let p = dword(self, offset);
- let o = self.s.m.i32(offset);
- let at = self.s.m.bin(c, Bin::Add, a, o);
- let three = self.s.m.i32(3);
- let byte = self.s.m.bin(c, Bin::And, at, three);
- let sh = self.s.m.bin(c, Bin::Shl, byte, three);
- let mask = self.s.m.i32((1u32 << bits) - 1);
- if name.starts_with("ds_read") {
- let reg = dst_reg.ok_or("an LDS read result")?;
- let w = self.s.m.load(c, p);
- let x = self.s.m.bin(c, Bin::LShr, w, sh);
- let x = if base.contains("_i") {
- let k = self.s.m.i32(32 - bits);
- let x = self.s.m.bin(c, Bin::Shl, x, k);
- self.s.m.bin(c, Bin::AShr, x, k)
- } else {
- self.s.m.bin(c, Bin::And, x, mask)
- };
- let x = if base == name {
- x
- } else {
- let old = match inst.read(Reg::V(reg)) {
- Some(v) => self.i32_of(v)?,
- None => self.s.m.i32(0),
- };
- let half = self.s.m.i32(0xFFFF);
- let x = self.s.m.bin(c, Bin::And, x, half);
- let (x, keep) = if name.ends_with("_hi") {
- let k16 = self.s.m.i32(16);
- (self.s.m.bin(c, Bin::Shl, x, k16), half)
- } else {
- (x, self.s.m.i32(0xFFFF_0000))
- };
- let old = self.s.m.bin(c, Bin::And, old, keep);
- self.s.m.bin(c, Bin::Or, old, x)
- };
- self.write(inst, Reg::V(reg), x, guard);
- } else {
- // Clear, then set: two atomics, so lanes writing other
- // bytes of the dword keep theirs.
- let mut x = self.vgprs(inst, data.first().ok_or("an LDS write")?, 1)?[0];
- if name != base {
- // The data's high half.
- let k16 = self.s.m.i32(16);
- x = self.s.m.bin(c, Bin::LShr, x, k16);
- }
- let x = self.s.m.bin(c, Bin::And, x, mask);
- let x = self.s.m.bin(c, Bin::Shl, x, sh);
- let m = self.s.m.bin(c, Bin::Shl, mask, sh);
- let ones = self.s.m.i32(u32::MAX);
- let keep = self.s.m.bin(c, Bin::Xor, m, ones);
- use super::bitcode::Rmw;
- let at = self.begin_guarded(guard);
- self.s.m.atomic(self.cur, Rmw::And, p, keep);
- self.s.m.atomic(self.cur, Rmw::Or, p, x);
- self.end_guarded(at, &[]);
- }
- return Ok(());
- }
- if let Some(rest) = name.strip_prefix("ds_read") {
- let elements = if rest.starts_with('2') {
- pair(name)
- } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") {
- vec![(offset, width(name))]
- } else {
- return Err("an LDS read of bytes or halves");
- };
- let reg = dst_reg.ok_or("an LDS read result")?;
- let mut n = 0;
- for (off, w) in elements {
- for k in 0..w {
- let p = dword(self, off + 4 * k);
- let x = self.s.m.load(self.cur, p);
- self.write(inst, Reg::V(reg + n), x, guard);
- n += 1;
- }
- }
- return Ok(());
- }
- if let Some(rest) = name.strip_prefix("ds_write") {
- let elements = if rest.starts_with('2') {
- pair(name)
- } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") {
- vec![(offset, width(name))]
- } else {
- return Err("an LDS write of bytes or halves");
- };
- let mut stores = Vec::new();
- for (e, (off, w)) in elements.into_iter().enumerate() {
- let vals = self.vgprs(inst, data.get(e).ok_or("an LDS write")?, w as u8)?;
- for (k, x) in vals.into_iter().enumerate() {
- stores.push((off + 4 * k as u32, x));
- }
- }
- let at = self.begin_guarded(guard);
- for (off, x) in stores {
- let p = dword(self, off);
- self.s.m.store(self.cur, p, x);
- }
- self.end_guarded(at, &[]);
- return Ok(());
- }
- // Atomics: the old value returns with `_rtn`.
- let op = name
- .strip_prefix("ds_")
- .map(|n| n.replace("_rtn", ""))
- .ok_or("an LDS operation")?;
- use super::bitcode::Rmw;
- let rmw = match op.as_str() {
- "add_u32" => Some(Rmw::Add),
- "sub_u32" => Some(Rmw::Sub),
- "and_b32" => Some(Rmw::And),
- "or_b32" => Some(Rmw::Or),
- "xor_b32" => Some(Rmw::Xor),
- "min_i32" => Some(Rmw::Min),
- "max_i32" => Some(Rmw::Max),
- "min_u32" => Some(Rmw::UMin),
- "max_u32" => Some(Rmw::UMax),
- "wrxchg_b32" => Some(Rmw::Xchg),
- "cmpst_b32" | "max_f32" | "min_f32" => None,
- _ => return Err("an LDS operation"),
- };
- let v0 = self.vgprs(inst, data.first().ok_or("an LDS atomic")?, 1)?[0];
- let v1 = match data.get(1) {
- Some(d) => Some(self.vgprs(inst, d, 1)?[0]),
- None => None,
- };
- let old_reg = dst_reg.and_then(|r| inst.read(Reg::V(r)).map(|v| (r, v)));
- let outside = match old_reg {
- Some((_, v)) => self.i32_of(v).unwrap_or(self.s.m.i32(0)),
- None => self.s.m.i32(0),
- };
- let p = dword(self, offset);
- if let Some(max) = match op.as_str() {
- "max_f32" => Some(true),
- "min_f32" => Some(false),
- _ => None,
- } {
- let at = self.begin_guarded(guard);
- let r = self.lds_float_min_max(p, v0, max);
- let r = self.end_guarded(at, &[(r, outside)])[0];
- if let Some(reg) = dst_reg {
- self.write(inst, Reg::V(reg), r, None);
- }
- return Ok(());
- }
- let at = self.begin_guarded(guard);
- let r = match rmw {
- Some(op) => self.s.m.atomic(self.cur, op, p, v0),
- // Compare with data0, store data1.
- None => self
- .s
- .m
- .cmpxchg(self.cur, p, v0, v1.ok_or("an LDS compare")?),
- };
- let r = self.end_guarded(at, &[(r, outside)])[0];
- if let Some(reg) = dst_reg {
- self.write(inst, Reg::V(reg), r, None);
- }
- Ok(())
- }
- /// `ds_max_f32` (`max`) or `ds_min_f32` on the LDS dword at `p` with
- /// the float bits `data`; the old bits return.
- ///
- /// DXIL has no float atomics on group-shared memory, so this is a
- /// compare-exchange loop around [`Lower::lds_float_pick`], which gives
- /// what RDNA2 writes (measured on gfx1036, reported on the pull
- /// request): an sNaN, data first, then memory, is written quieted;
- /// otherwise a NaN loses to a number (two quiet NaNs give the data);
- /// numbers compare as floats with -0 below +0.
- // shortcut: f32 denormals compare as kept; with the console's MODE
- // flushing them they would order as ±0 first (MODE is not modelled).
- fn lds_float_min_max(&mut self, p: V, data: V, max: bool) -> V {
- let pre = self.cur;
- let init = self.s.m.load(pre, p);
- let (lp, exit) = (self.s.m.new_block(), self.s.m.new_block());
- self.s.m.terminate(pre, Term::Br(lp));
- let i32t = self.s.t.i32;
- let old = self.s.m.phi(lp, i32t);
- self.cur = lp;
- let new = self.lds_float_pick(old, data, max);
- let prev = self.s.m.cmpxchg(lp, p, old, new);
- let done = self.s.m.cmp(lp, pred::EQ, prev, old);
- self.s.m.set_phi(old, vec![(init, pre), (prev, lp)]);
- self.s.m.terminate(lp, Term::CondBr(done, exit, lp));
- self.cur = exit;
- old
- }
- /// What `ds_max_f32` (`max`) or `ds_min_f32` writes over the dword
- /// `mem` with `data` (float bits; see [`Lower::lds_float_min_max`]).
- fn lds_float_pick(&mut self, mem: V, data: V, max: bool) -> V {
- let c = self.cur;
- let k = |l: &mut Self, v: u32| l.s.m.i32(v);
- let (abs_mask, inf, quiet, zero) = (
- k(self, 0x7FFF_FFFF),
- k(self, 0x7F80_0000),
- k(self, 0x40_0000),
- k(self, 0),
- );
- let nan = |l: &mut Self, x: V| {
- let m = l.s.m.bin(c, Bin::And, x, abs_mask);
- l.s.m.cmp(c, pred::IUGT, m, inf)
- };
- let snan = |l: &mut Self, x: V| {
- let n = nan(l, x);
- let q = l.s.m.bin(c, Bin::And, x, quiet);
- let sig = l.s.m.cmp(c, pred::EQ, q, zero);
- l.s.m.bin(c, Bin::And, n, sig)
- };
- // A total order of the numbers as signed integers, -0 below +0:
- // negative floats' magnitude bits reversed.
- let key = |l: &mut Self, x: V| {
- let k31 = l.s.m.i32(31);
- let sign = l.s.m.bin(c, Bin::AShr, x, k31);
- let flip = l.s.m.bin(c, Bin::And, sign, abs_mask);
- l.s.m.bin(c, Bin::Xor, x, flip)
- };
- let (dk, mk) = (key(self, data), key(self, mem));
- let take = self
- .s
- .m
- .cmp(c, if max { pred::SGT } else { pred::SLT }, dk, mk);
- let r = self.s.m.select(c, take, data, mem);
- let (dn, mn) = (nan(self, data), nan(self, mem));
- // One NaN: the number; two quiet NaNs: the data.
- let r = self.s.m.select(c, mn, data, r);
- let both = self.s.m.bin(c, Bin::And, dn, mn);
- let only_data = {
- let t = self.s.m.bool(true);
- let not_both = self.s.m.bin(c, Bin::Xor, both, t);
- self.s.m.bin(c, Bin::And, dn, not_both)
- };
- let r = self.s.m.select(c, only_data, mem, r);
- // Signalling NaNs win, quieted: the data's first.
- let qm = self.s.m.bin(c, Bin::Or, mem, quiet);
- let sm = snan(self, mem);
- let r = self.s.m.select(c, sm, qm, r);
- let qd = self.s.m.bin(c, Bin::Or, data, quiet);
- let sd = snan(self, data);
- self.s.m.select(c, sd, qd, r)
- }
- // ---- instructions ----
- // ---- instructions ----
- fn inst(&mut self, b: usize, i: usize) -> Result<(), Stop> {
- let inst: &'a Inst = &self.x.p.blocks[b].insts[i];
- let offset = inst.machine.offset;
- let name = inst.name();
- self.local_ok = name.starts_with("s_bcnt1_i32_")
- || name.starts_with("s_ff1_i32_")
- || name.starts_with("v_mbcnt_");
- self.mask_ok = match self.mask_data {
- MaskData::Console => true,
- MaskData::Host => {
- name.starts_with("s_bcnt1_i32_")
- || name.starts_with("s_ff1_i32_")
- || name.starts_with("v_mbcnt_")
- || matches!(
- name,
- "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_u64" | "s_cmp_lg_u64"
- )
- }
- // Mesh: only "do all lanes hold the first lane's value?" (`uniform_test`), which
- // each host wave answers for itself.
- MaskData::None => self.uniform_test(inst),
- };
- let effect = matches!(inst.fields, Fields::Exp { .. })
- || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
- || name.contains("store")
- || name.contains("atomic")
- || name == "s_barrier"
- || matches!(inst.fields, Fields::Ds { .. })
- && !(name.starts_with("ds_read")
- || name.starts_with("ds_swizzle")
- || name.contains("permute"));
- if self.split_lds
- && matches!(inst.fields, Fields::Ds { .. })
- && !(name.starts_with("ds_swizzle") || name.contains("permute"))
- && self.lds_meet.as_ref().is_none_or(|(all, _)| all[b])
- {
- // the two host waves of a console wave meet before each LDS access: what the other
- // half wrote is visible, and what it still reads is not overwritten
- let mode = self.s.m.i32(meeting_mode());
- let void = self.s.t.void;
- self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
- }
- let r = match &inst.fields {
- Fields::Sop { .. } => self.sop(inst),
- Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()),
- Fields::Sopp { .. } if name == "s_barrier" => {
- // Thread-group sync with a shared-memory fence, and a UAV
- // fence when the program writes UAVs (the waits before an
- // s_barrier make those writes visible on the console).
- let mut mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 };
- // Without the wait for the group (bit 0) where not every
- // lane arrives, or where the switch says so.
- let waits = match super::group_sync() {
- 0 => false,
- 1 => !self.fence_only.contains(&b),
- _ => true,
- };
- if !waits {
- mode &= !1;
- }
- let mode = self.s.m.i32(mode);
- let void = self.s.t.void;
- self.s
- .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
- Ok(())
- }
- Fields::Sopp { .. } => Ok(()),
- Fields::Smem { .. } => self.smem(inst, (b, i)),
- Fields::Valu(_) if name.starts_with("v_interp_") => self.interp(inst, (b, i)),
- Fields::Valu(_) => self.valu(inst, b, i),
- Fields::Vintrp { .. } => self.interp(inst, (b, i)),
- // The ray and node test. A failure is a refusal at once: an
- // instruction without a side effect otherwise only stops the
- // program where its results are needed, and two trace programs
- // came out without their test that way.
- Fields::Image { .. } if name.starts_with("image_bvh") => {
- return self
- .bvh(inst, b, i)
- .map_err(|why| unsupported(offset, why));
- }
- Fields::Image { .. } => self.image(inst, b, i),
- Fields::Buffer { .. } => self.buffer(inst, b, i),
- Fields::Exp { .. } => self.export(b, i),
- Fields::Ds { .. } => self.ds(inst, b, i),
- Fields::Flat { .. } if name.starts_with("global_") => self.flat(inst, b, i),
- Fields::Flat { .. } => Err("flat memory"),
- };
- match r {
- Ok(()) => Ok(()),
- Err(why) if effect => Err(unsupported(offset, why)),
- Err(why) => {
- for &(_, v) in &inst.writes {
- self.vals.insert(v, Val::Missing(why));
- }
- Ok(())
- }
- }
- }
- /// The two host waves of a console wave meet (a group barrier with a shared-memory
- /// fence): LDS writes before are seen by reads after.
- fn lds_meeting(&mut self) {
- let mode = self.s.m.i32(meeting_mode());
- let void = self.s.t.void;
- self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
- }
- /// Whether `v` is a register no program reads as a number: a descriptor dword without
- /// a host value ([`Self::stale`]), a lane mask's dword (outside compute, where a ballot
- /// gives the mask as data), or a join of only such values. Compiled code joins numbers
- /// with numbers: where one of these meets numbers at a join, the register is dead on
- /// that path (a variable set in one arm of a branch, its use behind a flag kept in a
- /// VGPR).
- fn dead(&self, v: Value, seen: &mut Vec<Value>) -> bool {
- if self.stale.contains(&v) {
- return true;
- }
- let st = self.x.st;
- if self.mask_data != MaskData::Console
- && (st.masks.contains_key(&v) || st.highs.contains_key(&v))
- {
- return true;
- }
- let Some(&(b, i)) = self.phi_at.get(&v) else {
- return false;
- };
- if seen.contains(&v) {
- return true;
- }
- seen.push(v);
- self.x.p.blocks[b].phis[i]
- .args
- .iter()
- .all(|&a| self.dead(a, seen))
- }
- /// `s_bcnt1_i32_b*` of the lanes that differ from the first lane's value:
- /// `v_readfirstlane_b32 s, v`, `v_cmp_eq_u32 m, s, v`, `s_xor_b* d, m, exec`. The
- /// compiler tests a value for being the same in the whole wave this way, to take a
- /// scalar path; both paths give each lane the same result, so the lanes of a host
- /// wave may ask it of their own first lane, whatever the wave's size.
- fn uniform_test(&self, inst: &Inst) -> bool {
- let p = self.x.p;
- let writer = |v: Value| -> Option<&'a Inst> {
- let b = *self.def_block.get(&v)?;
- p.blocks[b]
- .insts
- .iter()
- .find(|i| i.writes.iter().any(|w| w.1 == v))
- };
- let scalar = |i: &Inst, op: &Operand| match *op {
- Operand::Scalar { code, .. } if code != NULL && code != EXEC => i.read(Reg::S(code)),
- _ => None,
- };
- if !inst.name().starts_with("s_bcnt1_i32_") {
- return false;
- }
- let Fields::Sop { src, .. } = &inst.fields else {
- return false;
- };
- let Some(xor) = src.first().and_then(|o| scalar(inst, o)).and_then(writer) else {
- return false;
- };
- let Fields::Sop { src, .. } = &xor.fields else {
- return false;
- };
- if !matches!(xor.name(), "s_xor_b64" | "s_xor_b32")
- || !src
- .iter()
- .any(|o| matches!(o, Operand::Scalar { code: EXEC, .. }))
- {
- return false;
- }
- let Some(cmp) = src.iter().find_map(|o| scalar(xor, o)).and_then(writer) else {
- return false;
- };
- let Fields::Valu(f) = &cmp.fields else {
- return false;
- };
- if !matches!(cmp.name(), "v_cmp_eq_u32" | "v_cmp_eq_i32") || f.sdwa.is_some() || f.dpp.is_some() {
- return false;
- }
- let lanes = f.src.iter().find_map(|o| match *o {
- Operand::Vector { reg, .. } => cmp.read(Reg::V(reg)),
- _ => None,
- });
- let first = f.src.iter().find_map(|o| scalar(cmp, o)).and_then(writer);
- lanes.is_some()
- && first.is_some_and(|fl| {
- fl.name() == "v_readfirstlane_b32"
- && matches!(&fl.fields, Fields::Valu(g)
- if matches!(g.src.first(), Some(&Operand::Vector { reg, .. })
- if fl.read(Reg::V(reg)) == lanes))
- })
- }
- fn is_mask(&self, v: Option<Value>) -> bool {
- v.is_some_and(|v| self.x.st.masks.contains_key(&v))
- }
- fn sop(&mut self, inst: &Inst) -> Result<(), Why> {
- let Fields::Sop { dst, src, imm } = &inst.fields else {
- unreachable!()
- };
- let name = inst.name();
- let scc = inst.write(Reg::Scc);
- let dst_code = match dst {
- Some(Operand::Scalar { code, .. }) => Some(*code),
- _ => None,
- };
- let lo = dst_code.and_then(|c| inst.write(Reg::S(c)));
- if inst.write(Reg::S(EXEC)).is_some() || self.is_mask(lo) {
- return Err(LANE_MASK);
- }
- if matches!(
- name,
- "s_setreg_imm32_b32" | "s_setreg_b32" | "s_swappc_b64" | "s_version"
- ) || name.starts_with("s_waitcnt")
- {
- // shortcut: the float MODE register is not modelled; s_swappc_b64 is the
- // vertex fetch call, whose results arrive as inputs.
- return Err("a register the emitter does not model");
- }
- if name == "s_getpc_b64" {
- // The address of the next instruction is no number the host has: tables in
- // the code are read by their tracked address. As a number the counter is
- // that instruction's offset in the code, so an address paths join before
- // one load is the byte in the code, whichever table each path took
- // (resource tracking gives such a join as the computed term, with no base).
- let z = self.s.m.i32(0);
- let at = self.s.m.i32(inst.machine.offset as u32 + 4);
- let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1)));
- self.set(lo, Val::I32(at));
- self.set(hi, Val::I32(z));
- return Ok(());
- }
- let c = self.cur;
- let src32 = |l: &mut Self, k: usize| -> Result<V, Why> {
- // SOPK arithmetic reads its destination as the first source.
- if k == 0 && matches!(name, "s_addk_i32" | "s_mulk_i32") {
- let d = dst.as_ref().ok_or("a missing operand")?;
- return l.operand(inst, d);
- }
- let op = src.get(k).ok_or("a missing operand")?;
- l.operand(inst, op)
- };
- let sext16 = |l: &mut Self| l.s.m.i32(i32::from(imm.unwrap_or(0) as i16) as u32);
- // Dword `h` of 64-bit source `k` (inline constants sign-extend).
- let half = |l: &mut Self, k: usize, h: u8| -> Result<V, Why> {
- match src.get(k) {
- Some(&Operand::Scalar { code, .. }) if code != NULL => {
- let v = inst.read(Reg::S(code + h)).ok_or("an unread operand")?;
- l.i32_of(v)
- }
- Some(op) if h == 0 => l.operand(inst, op),
- Some(Operand::Const(k)) => {
- let x = crate::resource::inline(*k).ok_or("a special operand")?;
- Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 }))
- }
- // Of a signed operand, a literal sign-extends too.
- Some(&Operand::Literal(x)) if name.ends_with("_i64") => {
- Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 }))
- }
- _ => Ok(l.s.m.i32(0)),
- }
- };
- if let Some(op) = name.strip_prefix("s_bitcmp") {
- // SCC is whether bit src1 (mod 32, or mod 64 for the 64-bit form)
- // of src0 is clear (bitcmp0) or set (bitcmp1).
- let (bit, k31) = (src32(self, 1)?, self.s.m.i32(31));
- let idx = self.s.m.bin(c, Bin::And, bit, k31);
- let word = if op.ends_with("_b64") {
- let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
- let k32 = self.s.m.i32(32);
- let upper = self.s.m.bin(c, Bin::And, bit, k32);
- let z = self.s.m.i32(0);
- let upper = self.s.m.cmp(c, pred::NE, upper, z);
- self.s.m.select(c, upper, b, a)
- } else {
- src32(self, 0)?
- };
- let shifted = self.s.m.bin(c, Bin::LShr, word, idx);
- let one = self.s.m.i32(1);
- let tested = self.s.m.bin(c, Bin::And, shifted, one);
- let want = self.s.m.i32(u32::from(op.starts_with('1')));
- let r = self.s.m.cmp(c, pred::EQ, tested, want);
- self.set(scc, Val::Bit(r));
- return Ok(());
- }
- if let Some(op) = name.strip_prefix("s_cmp_").filter(|o| o.ends_with("_u64")) {
- // eq and lg only: both dwords.
- let mut r = None;
- for h in 0..2 {
- let (a, b) = (half(self, 0, h)?, half(self, 1, h)?);
- let e = self.s.m.cmp(c, pred::EQ, a, b);
- r = Some(match r {
- Some(x) => self.s.m.bin(c, Bin::And, x, e),
- None => e,
- });
- }
- let mut r = r.expect("two dwords");
- if op.starts_with("lg") {
- let t = self.s.m.bool(true);
- r = self.s.m.bin(c, Bin::Xor, r, t);
- }
- self.set(scc, Val::Bit(r));
- return Ok(());
- }
- if let Some(op) = name.strip_prefix("s_cmp_").or(name.strip_prefix("s_cmpk_")) {
- let (a, b) = if name.starts_with("s_cmpk_") {
- let b = if op.ends_with("_i32") {
- sext16(self)
- } else {
- self.s.m.i32(u32::from(imm.unwrap_or(0)))
- };
- (src32(self, 0)?, b)
- } else {
- if op.ends_with("64") {
- return Err("a 64-bit scalar compare");
- }
- (src32(self, 0)?, src32(self, 1)?)
- };
- let signed = op.ends_with("_i32");
- let p = match &op[..2] {
- "eq" => pred::EQ,
- "lg" => pred::NE,
- "gt" if signed => pred::SGT,
- "ge" if signed => pred::SGE,
- "lt" if signed => pred::SLT,
- "le" if signed => pred::SLE,
- "gt" => pred::IUGT,
- "ge" => pred::IUGE,
- "lt" => pred::IULT,
- "le" => pred::IULE,
- _ => return Err("a scalar compare"),
- };
- let r = self.s.m.cmp(c, p, a, b);
- self.set(scc, Val::Bit(r));
- return Ok(());
- }
- let wide = name.ends_with("_b64") || name.ends_with("_u64") || name.ends_with("_i64");
- if wide {
- let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1)));
- let nonzero = |l: &mut Self, a: V, b: V| {
- let o = l.s.m.bin(c, Bin::Or, a, b);
- let z = l.s.m.i32(0);
- l.s.m.cmp(c, pred::NE, o, z)
- };
- return match name {
- "s_quadmask_b64" => {
- let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
- let low = self.quad_mask(a);
- let high = self.quad_mask(b);
- let k8 = self.s.m.i32(8);
- let high = self.s.m.bin(c, Bin::Shl, high, k8);
- let mask = self.s.m.bin(c, Bin::Or, low, high);
- let zero = self.s.m.i32(0);
- self.set(lo, Val::I32(mask));
- self.set(hi, Val::I32(zero));
- let nonzero = self.s.m.cmp(c, pred::NE, mask, zero);
- self.set(scc, Val::Bit(nonzero));
- Ok(())
- }
- "s_bcnt1_i32_b64" => {
- let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
- let i32t = self.s.t.i32;
- let na = self
- .s
- .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[a]);
- let nb = self
- .s
- .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[b]);
- let r = self.s.m.bin(c, Bin::Add, na, nb);
- self.set(lo, Val::I32(r));
- let z = self.s.m.i32(0);
- let s = self.s.m.cmp(c, pred::NE, r, z);
- self.set(scc, Val::Bit(s));
- Ok(())
- }
- "s_ff1_i32_b64" => {
- // The lowest set bit; -1 for none (as DXIL's first bit low).
- let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
- let i32t = self.s.t.i32;
- let fa = self
- .s
- .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[a]);
- let fb = self
- .s
- .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[b]);
- let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32));
- let fb32 = self.s.m.bin(c, Bin::Add, fb, k32);
- let none = self.s.m.cmp(c, pred::EQ, b, z);
- let fb = self.s.m.select(c, none, fb, fb32);
- let low = self.s.m.cmp(c, pred::NE, a, z);
- let r = self.s.m.select(c, low, fa, fb);
- self.set(lo, Val::I32(r));
- Ok(())
- }
- "s_and_b64" | "s_or_b64" | "s_xor_b64" | "s_andn2_b64" | "s_orn2_b64"
- | "s_nand_b64" | "s_nor_b64" | "s_xnor_b64" | "s_not_b64" => {
- let ones = self.s.m.i32(u32::MAX);
- let mut r = Vec::new();
- for h in 0..2u8 {
- let a = half(self, 0, h)?;
- let x = if name == "s_not_b64" {
- self.s.m.bin(c, Bin::Xor, a, ones)
- } else {
- let mut b = half(self, 1, h)?;
- if name.contains("n2") {
- b = self.s.m.bin(c, Bin::Xor, b, ones);
- }
- let op = match &name[2..5] {
- "and" | "nan" => Bin::And,
- "or_" | "orn" | "nor" => Bin::Or,
- _ => Bin::Xor,
- };
- let x = self.s.m.bin(c, op, a, b);
- if matches!(name, "s_nand_b64" | "s_nor_b64" | "s_xnor_b64") {
- self.s.m.bin(c, Bin::Xor, x, ones)
- } else {
- x
- }
- };
- r.push(x);
- }
- self.set(lo, Val::I32(r[0]));
- self.set(hi, Val::I32(r[1]));
- let s = nonzero(self, r[0], r[1]);
- self.set(scc, Val::Bit(s));
- Ok(())
- }
- "s_lshl_b64" | "s_lshr_b64" | "s_ashr_i64" => {
- let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
- let n = src32(self, 1)?;
- let i64t = self.s.m.int(64);
- self.s.flags |= flags::INT64;
- let a = self.s.m.cast(c, Cast::ZExt, a, i64t);
- let b = self.s.m.cast(c, Cast::ZExt, b, i64t);
- let k32 = self.s.m.int_const(i64t, 32);
- let b = self.s.m.bin(c, Bin::Shl, b, k32);
- let x = self.s.m.bin(c, Bin::Or, a, b);
- let k63 = self.s.m.i32(63);
- let n = self.s.m.bin(c, Bin::And, n, k63);
- let n = self.s.m.cast(c, Cast::ZExt, n, i64t);
- let op = match name {
- "s_lshl_b64" => Bin::Shl,
- "s_lshr_b64" => Bin::LShr,
- _ => Bin::AShr,
- };
- let r = self.s.m.bin(c, op, x, n);
- let rl = self.s.m.cast(c, Cast::Trunc, r, self.s.t.i32);
- let rh = self.s.m.bin(c, Bin::LShr, r, k32);
- let rh = self.s.m.cast(c, Cast::Trunc, rh, self.s.t.i32);
- self.set(lo, Val::I32(rl));
- self.set(hi, Val::I32(rh));
- let s = nonzero(self, rl, rh);
- self.set(scc, Val::Bit(s));
- Ok(())
- }
- "s_mov_b64" => {
- // Each half by itself: two numbers that travel as a pair (two scalars
- // parked in neighbouring VGPR lanes, say) need not both have a value.
- for (h, v) in [(0, lo), (1, hi)] {
- let val = match half(self, 0, h) {
- Ok(a) => Val::I32(a),
- Err(why) => Val::Missing(why),
- };
- self.set(v, val);
- }
- Ok(())
- }
- "s_cselect_b64" => {
- let cond = self.scc_in(inst)?;
- for (h, v) in [(0, lo), (1, hi)] {
- let (a, b) = (half(self, 0, h)?, half(self, 1, h)?);
- let r = self.s.m.select(c, cond, a, b);
- self.set(v, Val::I32(r));
- }
- Ok(())
- }
- _ => Err(name),
- };
- }
- let m = &mut self.s.m;
- let _ = m;
- let (r, carry): (V, Option<V>) = match name {
- "s_mov_b32" => (src32(self, 0)?, None),
- "s_movk_i32" => (sext16(self), None),
- "s_quadmask_b32" => {
- let pixels = src32(self, 0)?;
- (self.quad_mask(pixels), None)
- }
- "s_cselect_b32" => {
- let cond = self.scc_in(inst)?;
- let (a, b) = (src32(self, 0)?, src32(self, 1)?);
- (self.s.m.select(c, cond, a, b), None)
- }
- "s_brev_b32" => {
- let a = src32(self, 0)?;
- let r = self
- .s
- .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a]);
- (r, None)
- }
- "s_not_b32" => {
- let a = src32(self, 0)?;
- let ones = self.s.m.i32(u32::MAX);
- (self.s.m.bin(c, Bin::Xor, a, ones), None)
- }
- "s_add_u32" | "s_add_i32" | "s_addk_i32" => {
- let a = src32(self, 0)?;
- let b = if name == "s_addk_i32" {
- sext16(self)
- } else {
- src32(self, 1)?
- };
- let r = self.s.m.bin(c, Bin::Add, a, b);
- let carry = if name == "s_add_u32" {
- Some(self.s.m.cmp(c, pred::IULT, r, a))
- } else {
- None
- };
- (r, carry)
- }
- "s_sub_u32" | "s_sub_i32" => {
- let (a, b) = (src32(self, 0)?, src32(self, 1)?);
- let r = self.s.m.bin(c, Bin::Sub, a, b);
- let carry = (name == "s_sub_u32").then(|| self.s.m.cmp(c, pred::IULT, a, b));
- (r, carry)
- }
- "s_addc_u32" | "s_subb_u32" => {
- let (a, b) = (src32(self, 0)?, src32(self, 1)?);
- let cin = self.scc_in(inst)?;
- let (r, carry) = self.add_sub_carry(c, name == "s_addc_u32", a, b, Some(cin));
- (r, Some(carry))
- }
- "s_mul_i32" | "s_mulk_i32" => {
- let a = src32(self, 0)?;
- let b = if name == "s_mulk_i32" {
- sext16(self)
- } else {
- src32(self, 1)?
- };
- (self.s.m.bin(c, Bin::Mul, a, b), None)
- }
- "s_mul_hi_u32" | "s_mul_hi_i32" => {
- let (a, b) = (src32(self, 0)?, src32(self, 1)?);
- (self.mul_hi(a, b, name.ends_with("i32")), None)
- }
- "s_flbit_i32_b32" | "s_flbit_i32" => {
- // The first bit from the top (differing from the sign for
- // the signed form), -1 for none: DXIL's first-bit-high.
- let a = src32(self, 0)?;
- let op = if name == "s_flbit_i32_b32" { 33 } else { 34 };
- let r = self
- .s
- .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
- (r, None)
- }
- "s_ff1_i32_b32" | "s_bcnt1_i32_b32" => {
- // First set bit (-1 for zero, as DXIL's), or the bit count.
- let a = src32(self, 0)?;
- let op = if name == "s_ff1_i32_b32" { 32 } else { 31 };
- let r = self
- .s
- .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
- (r, None)
- }
- "s_bfe_u32" | "s_bfe_i32" => {
- // src1: offset in bits 0-4, width in bits 16-22.
- let (a, b) = (src32(self, 0)?, src32(self, 1)?);
- let (k16, k127) = (self.s.m.i32(16), self.s.m.i32(0x7F));
- let w = self.s.m.bin(c, Bin::LShr, b, k16);
- let w = self.s.m.bin(c, Bin::And, w, k127);
- (self.bfe(a, b, w, name == "s_bfe_i32"), None)
- }
- "s_and_b32" | "s_or_b32" | "s_xor_b32" | "s_andn2_b32" | "s_orn2_b32"
- | "s_nand_b32" | "s_nor_b32" | "s_xnor_b32" => {
- let (a, mut b) = (src32(self, 0)?, src32(self, 1)?);
- let ones = self.s.m.i32(u32::MAX);
- if name.contains("n2") {
- b = self.s.m.bin(c, Bin::Xor, b, ones);
- }
- let op = match &name[2..5] {
- "and" | "nan" => Bin::And,
- "or_" | "orn" | "nor" => Bin::Or,
- _ => Bin::Xor,
- };
- let mut r = self.s.m.bin(c, op, a, b);
- if matches!(name, "s_nand_b32" | "s_nor_b32" | "s_xnor_b32") {
- r = self.s.m.bin(c, Bin::Xor, r, ones);
- }
- (r, None)
- }
- "s_lshl_b32" | "s_lshr_b32" | "s_ashr_i32" => {
- let (a, b) = (src32(self, 0)?, src32(self, 1)?);
- let k31 = self.s.m.i32(31);
- let b = self.s.m.bin(c, Bin::And, b, k31);
- let op = match name {
- "s_lshl_b32" => Bin::Shl,
- "s_lshr_b32" => Bin::LShr,
- _ => Bin::AShr,
- };
- (self.s.m.bin(c, op, a, b), None)
- }
- "s_lshl1_add_u32" | "s_lshl2_add_u32" | "s_lshl3_add_u32" | "s_lshl4_add_u32" => {
- let (a, b) = (src32(self, 0)?, src32(self, 1)?);
- let k = self.s.m.i32(u32::from(name.as_bytes()[6] - b'0'));
- let t = self.s.m.bin(c, Bin::Shl, a, k);
- (self.s.m.bin(c, Bin::Add, t, b), None)
- }
- "s_min_u32" | "s_max_u32" | "s_min_i32" | "s_max_i32" => {
- let (a, b) = (src32(self, 0)?, src32(self, 1)?);
- let p = match name {
- "s_min_u32" => pred::IULT,
- "s_max_u32" => pred::IUGT,
- "s_min_i32" => pred::SLT,
- _ => pred::SGT,
- };
- let t = self.s.m.cmp(c, p, a, b);
- (self.s.m.select(c, t, a, b), None)
- }
- "s_abs_i32" => {
- let a = src32(self, 0)?;
- let z = self.s.m.i32(0);
- let neg = self.s.m.cmp(c, pred::SLT, a, z);
- let n = self.s.m.bin(c, Bin::Sub, z, a);
- (self.s.m.select(c, neg, n, a), None)
- }
- "s_bitset0_b32" | "s_bitset1_b32" => {
- // Sets (clears) bit src[4:0] of the destination it reads.
- let old = self.operand(inst, dst.as_ref().ok_or("a missing operand")?)?;
- let a = src32(self, 0)?;
- let (k31, one) = (self.s.m.i32(31), self.s.m.i32(1));
- let a = self.s.m.bin(c, Bin::And, a, k31);
- let bit = self.s.m.bin(c, Bin::Shl, one, a);
- if name == "s_bitset1_b32" {
- (self.s.m.bin(c, Bin::Or, old, bit), None)
- } else {
- let ones = self.s.m.i32(u32::MAX);
- let nb = self.s.m.bin(c, Bin::Xor, bit, ones);
- (self.s.m.bin(c, Bin::And, old, nb), None)
- }
- }
- "s_bfm_b32" => {
- let (a, b) = (src32(self, 0)?, src32(self, 1)?);
- let k31 = self.s.m.i32(31);
- let one = self.s.m.i32(1);
- let a = self.s.m.bin(c, Bin::And, a, k31);
- let b = self.s.m.bin(c, Bin::And, b, k31);
- let m = self.s.m.bin(c, Bin::Shl, one, a);
- let m = self.s.m.bin(c, Bin::Sub, m, one);
- (self.s.m.bin(c, Bin::Shl, m, b), None)
- }
- _ => return Err(name),
- };
- self.set(lo, Val::I32(r));
- if let Some(scc) = scc {
- let val = match carry {
- Some(k) => Val::Bit(k),
- None if matches!(
- name,
- "s_mov_b32"
- | "s_movk_i32"
- | "s_cselect_b32"
- | "s_brev_b32"
- | "s_mul_i32"
- | "s_mulk_i32"
- ) =>
- {
- return Ok(());
- }
- None if name.starts_with("s_add") || name.starts_with("s_sub") => {
- Val::Missing("the carry of a scalar operation")
- }
- None => {
- let z = self.s.m.i32(0);
- Val::Bit(self.s.m.cmp(c, pred::NE, r, z))
- }
- };
- self.vals.insert(scc, val);
- }
- Ok(())
- }
- /// Packs whether each consecutive group of four pixels has a set bit.
- fn quad_mask(&mut self, pixels: V) -> V {
- let c = self.cur;
- let one = self.s.m.i32(1);
- let shifted = self.s.m.bin(c, Bin::LShr, pixels, one);
- let mut mask = self.s.m.bin(c, Bin::Or, pixels, shifted);
- // Fold each nibble into its bottom bit, then gather those bits into
- // the low byte in three stages without needing a 64-bit operation.
- for (distance, keep) in [
- (2, 0x1111_1111),
- (3, 0x0303_0303),
- (6, 0x000f_000f),
- (12, 0x0000_00ff),
- ] {
- let distance = self.s.m.i32(distance);
- let shifted = self.s.m.bin(c, Bin::LShr, mask, distance);
- let combined = self.s.m.bin(c, Bin::Or, mask, shifted);
- let keep = self.s.m.i32(keep);
- mask = self.s.m.bin(c, Bin::And, combined, keep);
- }
- mask
- }
- /// `a + b (+ cin)` or `a - b (- cin)` with the carry (borrow) out, as the
- /// scalar and vector add-with-carry instructions set it.
- fn add_sub_carry(&mut self, c: usize, add: bool, a: V, b: V, cin: Option<V>) -> (V, V) {
- let op = if add { Bin::Add } else { Bin::Sub };
- let mut r = self.s.m.bin(c, op, a, b);
- // Without a carry in: a + b wraps below a; a - b borrows when a < b.
- let mut carry = if add {
- self.s.m.cmp(c, pred::IULT, r, a)
- } else {
- self.s.m.cmp(c, pred::IULT, a, b)
- };
- if let Some(cin) = cin {
- let one = self.s.m.cast(c, Cast::ZExt, cin, self.s.t.i32);
- let t = r;
- r = self.s.m.bin(c, op, t, one);
- // The carry in carries on when the partial result is all ones
- // (add) or zero (sub).
- let edge = self.s.m.i32(if add { u32::MAX } else { 0 });
- let at_edge = self.s.m.cmp(c, pred::EQ, t, edge);
- let more = self.s.m.bin(c, Bin::And, cin, at_edge);
- carry = self.s.m.bin(c, Bin::Or, carry, more);
- }
- (r, carry)
- }
- fn scc_in(&mut self, inst: &Inst) -> Result<V, Why> {
- let v = inst.read(Reg::Scc).ok_or("an unread SCC")?;
- match self.get(v) {
- Ok(Val::Bit(x)) => Ok(x),
- Ok(_) => Err("SCC without a value"),
- // Of a mask operation whose result lies within EXEC: whether
- // some lane is left.
- Err(LANE_MASK) if self.within_exec(v) => self.scc_some(v),
- Err(why) => Err(why),
- }
- }
- /// Whether the mask operation that sets the SCC value `scc` gives no
- /// lane outside EXEC a bit.
- fn within_exec(&self, scc: Value) -> bool {
- let Some(&b) = self.def_block.get(&scc) else {
- return false;
- };
- let by = self.x.p.blocks[b].insts.iter().find(|i| i.write(Reg::Scc) == Some(scc));
- by.is_some_and(|i| {
- i.write(Reg::S(EXEC)).is_some()
- || matches!(&i.fields, Fields::Sop { dst: Some(Operand::Scalar { code, .. }), .. }
- if i.write(Reg::S(*code)).is_some_and(|lo| self.x.st.active.contains(&lo)))
- })
- }
- fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
- let Fields::Smem {
- data,
- offset,
- soffset,
- ..
- } = &inst.fields
- else {
- unreachable!()
- };
- self.root_copy = None;
- let name = inst.name();
- if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) {
- return self.code_smem(inst, a);
- }
- if self.scalar.get(&site).is_some_and(|a| a.param == MEMORY) {
- return self.memory_smem(inst);
- }
- let Some(rest) = name.strip_prefix("s_buffer_load_dword") else {
- return self.descriptor_data(inst, site);
- };
- let count = match rest {
- "" => 1,
- "x2" => 2,
- "x4" => 4,
- "x8" => 8,
- "x16" => 16,
- _ => return Err("a scalar buffer load"),
- };
- let Some(Operand::Scalar { code, .. }) = *data else {
- return Err("a scalar buffer load");
- };
- let src = self
- .descriptors
- .get(&(site, false))
- .copied()
- .ok_or("an untracked descriptor")?;
- let kind = self.used_kind(src);
- let c = self.cur;
- let (base, extra) = self.built_offset(src)?;
- let offset = &((*offset as u32).wrapping_add(base) as i32);
- let mut addr = self.s.m.i32(*offset as u32);
- if let Some(x) = extra {
- addr = self.s.m.bin(c, Bin::Add, addr, x);
- }
- if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
- let so = self.operand(inst, soffset)?;
- addr = self.s.m.bin(c, Bin::Add, addr, so);
- }
- if matches!(src, Source::Built { address, .. } if address.param == CODE) {
- // A descriptor built around a table in the code.
- for k in 0..count {
- let off = self.s.m.i32(4 * k);
- let a = self.s.m.bin(c, Bin::Add, addr, off);
- let x = self.code_dword(a)?;
- self.write(inst, Reg::S(code + k as u8), x, None);
- }
- return Ok(());
- }
- // A buffer the program picks from the view heap by an index it
- // computes (`ResourceHeap`) has no used-resource entry, and the
- // heap holds a buffer view there, not a constant buffer: read as
- // raw bytes, as a table's SRV is below. Read as a constant buffer
- // (the host's validation: "Descriptor Type in Heap: SRV, Register
- // Type: CBV", heap index 17) the loads gave nothing:
- // the title's meshlet culling (BatchCullMeshlets,
- // BatchCullPreSkinnedMeshlets, BatchCullBatchCSMeshlets) reads its
- // batch records, mesh headers and instance transforms this way, so
- // it passed no meshlet and every indirect mesh draw ran empty.
- // The host's table of strides by heap slot tells a buffer view
- // (not 0) from anything else, which is still read as a constant
- // buffer; only the load that fits the slot runs.
- let picked = match kind {
- None => self.slot_stride(src)?,
- Some(_) => None,
- };
- if let Some(stride) = picked {
- let zero = self.s.m.i32(0);
- let is_buffer = self.s.m.cmp(self.cur, pred::NE, stride, zero);
- let at = self.begin_guarded(Some(is_buffer));
- let h = self.handle(site, src, false, (11, 0))?;
- let mut raw = Vec::new();
- for k in 0..count {
- let b = self.cur;
- let off = self.s.m.i32(4 * k);
- let a = self.s.m.bin(b, Bin::Add, addr, off);
- let mask = self.s.m.i8(1);
- let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
- let r = self.s.op(
- b,
- "rawBufferLoad.f32",
- Attr::ReadOnly,
- self.s.t.res_ret,
- 139,
- &[h, a, u, mask, al],
- );
- let x = self.s.m.extract(b, r, 0);
- let x = self.as_int(x);
- raw.push((x, zero));
- }
- let raw = self.end_guarded(at, &raw);
- let other = self.s.m.cmp(self.cur, pred::EQ, stride, zero);
- let at = self.begin_guarded(Some(other));
- let h = self.handle(site, src, false, (13, 0x1_0000))?;
- let mut both = Vec::new();
- for (k, &r) in raw.iter().enumerate() {
- let b = self.cur;
- let off = self.s.m.i32(4 * k as u32);
- let a = self.s.m.bin(b, Bin::Add, addr, off);
- let x = self.cbuffer_dword(h, a);
- both.push((x, r));
- }
- let both = self.end_guarded(at, &both);
- for (k, x) in both.into_iter().enumerate() {
- self.write(inst, Reg::S(code + k as u8), x, None);
- }
- return Ok(());
- }
- if matches!(kind, Some(u) if u.kind == ResourceType::Srv) {
- let h = match self.root_memory(src, addr, None, false) {
- Some((h, byte)) => {
- addr = byte;
- h
- }
- None => self.handle(site, src, false, (11, 0))?,
- };
- let c = self.cur;
- for k in 0..count {
- let off = self.s.m.i32(4 * k);
- let a = self.s.m.bin(c, Bin::Add, addr, off);
- let mask = self.s.m.i8(1);
- let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
- let r = self.s.op(
- c,
- "rawBufferLoad.f32",
- Attr::ReadOnly,
- self.s.t.res_ret,
- 139,
- &[h, a, u, mask, al],
- );
- let x = self.s.m.extract(c, r, 0);
- let x = self.as_int(x);
- self.write(inst, Reg::S(code + k as u8), x, None);
- }
- return Ok(());
- }
- let h = self.handle(site, src, false, (13, 0x1_0000))?;
- let constant = match addr {
- V::Const(_)
- if matches!(soffset, Operand::Scalar { code: NULL, .. }) && extra.is_none() =>
- {
- Some(*offset as u32)
- }
- _ => None,
- };
- let mut rows: HashMap<u32, V> = HashMap::new();
- for k in 0..count {
- let x = match constant {
- Some(base) => {
- let byte = base + 4 * k;
- let row = match rows.get(&(byte >> 4)) {
- Some(&r) => r,
- None => {
- let ri = self.s.m.i32(byte >> 4);
- let r = self.s.op(
- c,
- "cbufferLoadLegacy.i32",
- Attr::ReadOnly,
- self.s.t.cbuf_ret,
- 59,
- &[h, ri],
- );
- rows.insert(byte >> 4, r);
- r
- }
- };
- self.s.m.extract(c, row, (byte >> 2) & 3)
- }
- None => {
- let off = self.s.m.i32(4 * k);
- let a = self.s.m.bin(c, Bin::Add, addr, off);
- self.cbuffer_dword(h, a)
- }
- };
- self.write(inst, Reg::S(code + k as u8), x, None);
- }
- Ok(())
- }
- /// A descriptor load (`s_load_dword*` from a table or heap) whose dwords
- /// the code also reads as numbers: the console compiler computes sizes
- /// from descriptor bits (an image's width, height, depth, levels; a
- /// buffer's record count) instead of querying them. Those fields are
- /// rebuilt from the host view's dimensions in the GFX10 layout (image
- /// dword 1 bits 30-31 and dword 2 bits 0-13 width - 1, dword 2 bits
- /// 14-29 height - 1, dword 3 identity swizzle, last level at 16, type at
- /// 28, dword 4 depth or layers - 1; buffer dword 2 the record count).
- // shortcut: the base level reads 0 (the host view starts at its own
- // level 0, so sizes the code shifts by it come out right) and the other
- // dwords (addresses, formats, tiling) have no host value: reading them
- // stops the program.
- fn descriptor_data(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
- const OTHER: Why = "a descriptor's address or format read as data";
- let Fields::Smem {
- data: Some(Operand::Scalar { code, .. }),
- ..
- } = inst.fields
- else {
- return Err("a scalar memory read as data");
- };
- let count = match inst.name().strip_prefix("s_load_dword") {
- Some("") => 1u32,
- Some("x2") => 2,
- Some("x4") => 4,
- Some("x8") => 8,
- Some("x16") => 16,
- _ => return Err("a scalar memory read as data"),
- };
- // How the program uses the descriptor tells the view's kind: an image or buffer
- // instruction before a scalar buffer load, which reads any buffer.
- let x = self.x;
- let uses = |of: Site| {
- x.res
- .descriptors
- .iter()
- .filter(|d| d.role == Role::Resource)
- .filter_map(move |d| {
- d.source.leaves().into_iter().find_map(|l| match *l {
- Source::Loaded { load, first } if load == of => Some((d.site, first)),
- _ => None,
- })
- })
- };
- let by_scalar_load = |u: &(Site, u8)| {
- matches!(x.p.blocks[u.0.0].insts[u.0.1].fields, Fields::Smem { .. })
- };
- let use_of = |of: Site| uses(of).find(|u| !by_scalar_load(u)).or_else(|| uses(of).next());
- // The console compiler loads a descriptor again wherever it needs it, and for a
- // size it reads the dwords of a load that nothing uses as a descriptor (a texture
- // picked from the heap by an index held per lane: one load for its width, one for
- // its base level, one for each read of the image). Another load of as many dwords
- // from the same address reads the same descriptor, so what uses that one tells
- // this one's kind. The handle is still made from this load's own operands, which
- // hold here.
- let address = self.scalar.get(&site).copied();
- let twin = || {
- let a = address?;
- let same = |s: Site| x.p.blocks[s.0].insts[s.1].name() == inst.name();
- x.res
- .scalar
- .iter()
- .filter(|(s, b)| *s != site && *b == a && same(*s))
- .find_map(|(s, _)| use_of(*s))
- };
- let use_at = use_of(site).or_else(twin);
- // A view whose kind no use tells, but what is read of it does.
- let sized = match use_at {
- Some(_) => None,
- None => self.sized_view(inst, site, code, count),
- };
- // A descriptor nothing uses as one, whose size the code reads all the same (a
- // texture picked from the heap by an index in a constant buffer, its width and
- // height turned into a texel size): the kind from its dwords and its used-resource
- // entry. Only an image whose layers or depth (dword 4) are not read: those are no 2D
- // texture's; and no buffer `sized_view` did not take (a stride of 4 or less may be a
- // typed view's component count, and the address is `view_address`'s below).
- let layers = inst.write(Reg::S(code + 4)).is_some_and(|v| self.read_as_number(v));
- let unused = if use_at.is_none() && sized.is_none() && count == 8 && !layers {
- self.unused_descriptor_kind(inst, site, code, count)
- } else {
- None
- };
- let (first, props, image, uav, used) = if let Some(kind) = unused {
- kind
- } else {
- let Some((at, first)) = use_at.or(sized.map(|_| (site, 0))) else {
- // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only
- // copies its dwords and compares them, lane against first lane, and every load
- // that reaches those lanes reads one address. Each dword stands in as its place
- // in the table, so the lanes compare equal as they do on the console.
- if self.x.res.lane_copied.contains(&site)
- && let Some(a) = self.scalar.get(&site).copied()
- {
- for k in 0..count {
- let x = self.s.m.i32(a.offset / 4 + k);
- self.write(inst, Reg::S(code + k as u8), x, None);
- }
- return Ok(());
- }
- // A sampler's descriptor: no program reads its dwords as numbers, so where one
- // meets numbers at a join the register is dead on that path (`dead`), as a
- // descriptor's address or format is.
- let sampler = x.res.descriptors.iter().any(|d| {
- d.role == Role::Sampler
- && d.source.leaves().into_iter().any(
- |l| matches!(*l, Source::Loaded { load, .. } if load == site),
- )
- });
- if sampler {
- self.stale.extend(inst.writes.iter().map(|w| w.1));
- return Err("a sampler's descriptor read as data");
- }
- // A buffer view the code only takes the address of, to walk
- // the memory behind it (a ray-tracing structure): the address
- // from the host, the other dwords have no value.
- if count <= 4
- && let Some((lo, hi)) = self.view_address(site)
- {
- for k in 0..count {
- let reg = Reg::S(code + k as u8);
- match k {
- 0 => self.write(inst, reg, lo, None),
- 1 => self.write(inst, reg, hi, None),
- _ => {
- if let Some(v) = inst.write(reg) {
- self.vals.insert(v, Val::Missing(OTHER));
- self.stale.insert(v);
- }
- }
- }
- }
- return Ok(());
- }
- if std::env::var_os("VICTORY_DESC_WHY").is_some() {
- eprintln!(
- "DESC-WHY {:#x} {} scalar={:?} lane_copied={}",
- inst.machine.offset,
- inst.name(),
- address,
- self.x.res.lane_copied.contains(&site)
- );
- }
- return Err("a descriptor read only as data");
- };
- let src = Source::Loaded { load: site, first };
- let used = self.used_kind(&src);
- let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1];
- let un = ui.name();
- let uav = un.contains("store")
- || un.contains("atomic")
- || used.is_some_and(|u| u.kind == ResourceType::Uav);
- let u = if uav { 0x1000 } else { 0 };
- let (props, image) = match &ui.fields {
- _ if sized.is_some_and(|image| image) => ((2 | u, 0x409), Some(2)),
- _ if sized.is_some() => ((11 | u, 0), None),
- // A ray-tracing structure in a buffer of the host: read raw.
- Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None),
- Fields::Image { dim, .. } => {
- let kind = match dim {
- 0 => 1,
- 1 => 2,
- 2 => 4,
- 4 => 6,
- 5 => 7,
- _ => return Err("an image dimension (cube or MSAA)"),
- };
- ((kind | u, 0x409), Some(kind))
- }
- Fields::Buffer { idxen, format, .. } => {
- let stride = used.map_or(0, |u| u.stride);
- let counted = inst
- .write(Reg::S(code + first + 2))
- .is_some_and(|v| self.read_as_number(v));
- let props = if un.starts_with("buffer_load_format")
- || un.starts_with("buffer_store_format")
- {
- (10 | u, 0x409)
- } else if !counted
- && *idxen
- && format.is_none()
- && stride >= 4
- && stride.is_multiple_of(4)
- {
- // Nothing reads the count: the query is cleaned up.
- (12 | u, stride)
- } else {
- // Structured ones too: the host's views of them are raw
- // (see `buffer`), which count bytes, and a size asked
- // for as a structured view's is that count on AMD.
- (11 | u, 0)
- };
- if used.is_some_and(|u| u.kind == ResourceType::Cbv) {
- self.stale.extend(inst.writes.iter().map(|w| w.1));
- return Err("a constant buffer's descriptor read as data");
- }
- (props, None)
- }
- // Read by scalar buffer loads alone: the raw view `smem` reads it through.
- Fields::Smem { .. } if used.is_some_and(|u| u.kind == ResourceType::Srv) => {
- ((11, 0), None)
- }
- // A constant buffer: nothing of its descriptor is a number.
- Fields::Smem { .. } => {
- self.stale.extend(inst.writes.iter().map(|w| w.1));
- return Err("a constant buffer's descriptor read as data");
- }
- _ => return Err("a scalar memory read as data"),
- };
- (first, props, image, uav, used)
- };
- let src = Source::Loaded { load: site, first };
- let h = self.handle(site, &src, false, props)?;
- let c = self.cur;
- let i32t = self.s.t.i32;
- let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
- let mip = if image.is_some() && !uav {
- self.s.m.i32(0)
- } else {
- self.s.m.undef(i32t)
- };
- let d = self
- .s
- .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
- let field = |l: &mut Self, k: u32| l.s.m.extract(c, d, k);
- let words: Vec<(u32, V)> = match image {
- Some(kind) => {
- let one = self.s.m.i32(1);
- let w = field(self, 0);
- let (height, depth) = match kind {
- 1 => (one, one),
- 2 => (field(self, 1), one),
- 6 => (one, field(self, 1)),
- _ => (field(self, 1), field(self, 2)),
- };
- let levels = if uav { one } else { field(self, 3) };
- let less = |l: &mut Self, x: V| l.s.m.bin(c, Bin::Sub, x, one);
- let (w, height, depth, levels) = (
- less(self, w),
- less(self, height),
- less(self, depth),
- less(self, levels),
- );
- let k = |l: &mut Self, v: u32| l.s.m.i32(v);
- let (k30, k2, k14, k16, mask) = (
- k(self, 30),
- k(self, 2),
- k(self, 14),
- k(self, 16),
- k(self, 0x3FFF),
- );
- let d1 = self.s.m.bin(c, Bin::Shl, w, k30);
- let hi = self.s.m.bin(c, Bin::LShr, w, k2);
- let hi = self.s.m.bin(c, Bin::And, hi, mask);
- let ht = self.s.m.bin(c, Bin::Shl, height, k14);
- let d2 = self.s.m.bin(c, Bin::Or, hi, ht);
- let ty = [0, 8, 9, 0, 10, 0, 12, 13][kind as usize];
- let base = k(self, 0xFAC | ty << 28);
- let last = self.s.m.bin(c, Bin::Shl, levels, k16);
- let d3 = self.s.m.bin(c, Bin::Or, base, last);
- vec![(1, d1), (2, d2), (3, d3), (4, depth)]
- }
- None => {
- // A raw view counts bytes; the descriptor's record count is in elements.
- let n = field(self, 0);
- let stride = used.map_or(0, |u| u.stride);
- let counted = inst
- .write(Reg::S(code + first + 2))
- .is_some_and(|v| self.read_as_number(v));
- let n = if props.0 & 0xFF == 11 && stride > 1 {
- let k = self.s.m.i32(stride);
- self.s.m.bin(c, Bin::UDiv, n, k)
- } else if props.0 & 0xFF == 11
- && counted
- && let Some(stride) = self.slot_stride(&src)?
- {
- // Picked from the heap: the host's table has the stride.
- let (i32t, one) = (self.s.t.i32, self.s.m.i32(1));
- let k = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 39, &[stride, one]);
- self.s.m.bin(c, Bin::UDiv, n, k)
- } else {
- n
- };
- let mut words = vec![(2, n)];
- // Its address too, where the code computes with it and the
- // host can tell it.
- let computed = (0..2u8).any(|k| {
- inst.write(Reg::S(code + first + k))
- .is_some_and(|v| self.computed_with(v, 6))
- });
- // (A descriptor nothing uses as one gets it whenever the host can tell it, as
- // a buffer whose address alone is read does.)
- if first == 0
- && (computed || unused.is_some())
- && let Some((lo, hi)) = self.view_address(site)
- {
- words.extend([(0, lo), (1, hi)]);
- }
- words
- }
- };
- for k in 0..count {
- let rel = k.wrapping_sub(u32::from(first));
- match words.iter().find(|w| w.0 == rel) {
- Some(&(_, x)) => self.write(inst, Reg::S(code + k as u8), x, None),
- None => {
- if let Some(v) = inst.write(Reg::S(code + k as u8)) {
- self.vals.insert(v, Val::Missing(OTHER));
- self.stale.insert(v);
- }
- }
- }
- }
- Ok(())
- }
- /// What [`Self::descriptor_data`] makes of a descriptor load that nothing uses as a
- /// descriptor but whose dwords the code reads: the first dword, the handle properties,
- /// the image kind (none for a buffer), whether it is an unordered view, and its
- /// used-resource entry. An image's eight dwords read as a 2D texture's, a buffer's four
- /// as a raw view's where the code reads its record count (dword 2); none for anything
- /// else (a constant buffer, a sampler, a buffer whose address alone is read).
- // shortcut: an image whose kind nothing tells is taken for a 2D texture (the title's
- // reads are texel sizes of 2D textures: puddle masks, shadow masks); a host view of
- // another kind would answer its own sizes.
- #[allow(clippy::type_complexity)]
- fn unused_descriptor_kind(
- &self,
- inst: &Inst,
- site: Site,
- code: u8,
- count: u32,
- ) -> Option<(u8, (u32, u32), Option<u32>, bool, Option<&'a UsedResource>)> {
- // Kept per lane and compared (`Resources::lane_copied`), or a sampler's: the cases
- // `descriptor_data` handles on their own.
- if self.x.res.lane_copied.contains(&site)
- || self.x.res.descriptors.iter().any(|d| {
- d.role == Role::Sampler
- && d.source.leaves().into_iter().any(
- |l| matches!(*l, Source::Loaded { load, .. } if load == site),
- )
- })
- {
- return None;
- }
- let used = self.used_kind(&Source::Loaded {
- load: site,
- first: 0,
- });
- if used.is_some_and(|u| !matches!(u.kind, ResourceType::Srv | ResourceType::Uav)) {
- return None;
- }
- let read = |k: u32| {
- inst.write(Reg::S(code + k as u8)).is_some_and(|v| {
- self.x
- .p
- .blocks
- .iter()
- .flat_map(|b| &b.insts)
- .any(|i| i.reads.iter().any(|r| r.1 == v))
- })
- };
- let uav = used.is_some_and(|u| u.kind == ResourceType::Uav);
- let u = if uav { 0x1000 } else { 0 };
- match count {
- // width (dwords 1-2), height (2), levels (3), depth (4)
- 8 if (1..5).any(read) && used.is_none_or(|u| u.dwords == 8) => {
- Some((0, (2 | u, 0x409), Some(2), uav, used))
- }
- // the record count
- 4 if read(2) && used.is_none_or(|u| u.dwords == 4) => {
- Some((0, (11 | u, 0), None, uav, used))
- }
- _ => None,
- }
- }
- /// `s_load_dword*` from the program's constant table.
- fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> {
- let Fields::Smem {
- data: Some(Operand::Scalar { code, .. }),
- ..
- } = inst.fields
- else {
- return Err("a scalar load");
- };
- let count = match inst.name().strip_prefix("s_load_dword") {
- Some("") => 1u32,
- Some("x2") => 2,
- Some("x4") => 4,
- Some("x8") => 8,
- Some("x16") => 16,
- _ => return Err("a scalar load from the code"),
- };
- let c = self.cur;
- let mut addr = self.s.m.i32(a.offset);
- if let Some(value) = a.dynamic {
- let mut d = self.i32_of(value)?;
- // A term held per lane reached the address through
- // `v_readfirstlane_b32`: the first lane's.
- let per_lane = self.def_block.get(&value).is_some_and(|&b| {
- let writes = |i: &Inst| i.writes.iter().any(|w| w.1 == value && matches!(w.0, Reg::V(_)));
- self.x.p.blocks[b].insts.iter().any(writes)
- });
- if per_lane {
- self.s.flags |= flags::WAVE_OPS;
- let i32t = self.s.t.i32;
- let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[d]);
- d = if self.s.pixel && super::helper_own() {
- let helper = self.helper_lane();
- self.s.m.select(c, helper, d, first)
- } else {
- first
- };
- }
- addr = self.s.m.bin(c, Bin::Add, addr, d);
- }
- for k in 0..count {
- let off = self.s.m.i32(4 * k);
- let at = self.s.m.bin(c, Bin::Add, addr, off);
- let x = self.code_dword(at)?;
- self.write(inst, Reg::S(code + k as u8), x, None);
- }
- Ok(())
- }
- /// The dword at a computed byte address of a constant buffer.
- fn cbuffer_dword(&mut self, h: V, a: V) -> V {
- let c = self.cur;
- let four = self.s.m.i32(4);
- let ri = self.s.m.bin(c, Bin::LShr, a, four);
- let r = self.s.op(
- c,
- "cbufferLoadLegacy.i32",
- Attr::ReadOnly,
- self.s.t.cbuf_ret,
- 59,
- &[h, ri],
- );
- let two = self.s.m.i32(2);
- let three = self.s.m.i32(3);
- let comp = self.s.m.bin(c, Bin::LShr, a, two);
- let comp = self.s.m.bin(c, Bin::And, comp, three);
- let mut x = self.s.m.extract(c, r, 0);
- for j in 1..4 {
- let e = self.s.m.extract(c, r, j);
- let jc = self.s.m.i32(j);
- let is = self.s.m.cmp(c, pred::EQ, comp, jc);
- x = self.s.m.select(c, is, e, x);
- }
- x
- }
- /// `channels` channels of the element at byte `off` of raw buffer `h`,
- /// converted from the GFX10 buffer format `format` as the hardware's
- /// typed loads do (channels past the format's read 0, 0, 0, 1).
- // shortcut: the descriptor's channel swizzle is taken as the identity
- // (it is for raw views and the descriptors code builds), elements of 4
- // bytes or more as dword-aligned.
- fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result<Vec<V>, Why> {
- let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?;
- let c = self.cur;
- let total: u32 = bits.iter().sum();
- let (u, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
- let load = |l: &mut Self, at: V, n: u32| -> Vec<V> {
- let mask = l.s.m.i8((1u8 << n) - 1);
- let r = l.s.op(
- c,
- "rawBufferLoad.f32",
- Attr::ReadOnly,
- l.s.t.res_ret,
- 139,
- &[h, at, u, mask, align],
- );
- (0..n)
- .map(|k| {
- let x = l.s.m.extract(c, r, k);
- l.as_int(x)
- })
- .collect()
- };
- let words = if total < 32 {
- // A byte or half inside the dword that holds it.
- let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3));
- let at = self.s.m.bin(c, Bin::And, off, not3);
- let w = load(self, at, 1)[0];
- let byte = self.s.m.bin(c, Bin::And, off, three);
- let sh = self.s.m.bin(c, Bin::Shl, byte, three);
- vec![self.s.m.bin(c, Bin::LShr, w, sh)]
- } else {
- load(self, off, total / 32)
- };
- let float = |l: &mut Self, f: V| l.as_int(f);
- let mut out = Vec::new();
- let mut at = 0;
- for &w in bits {
- let word = words[(at / 32) as usize];
- let field = if w == 32 {
- word
- } else {
- let sh = self.s.m.i32(at % 32);
- let t = self.s.m.bin(c, Bin::LShr, word, sh);
- let m = self.s.m.i32((1 << w) - 1);
- self.s.m.bin(c, Bin::And, t, m)
- };
- at += w;
- // Sign-extended from the field's top bit.
- let signed = |l: &mut Self| {
- if w == 32 {
- return field;
- }
- let k = l.s.m.i32(32 - w);
- let t = l.s.m.bin(c, Bin::Shl, field, k);
- l.s.m.bin(c, Bin::AShr, t, k)
- };
- let f32t = self.s.t.f32;
- // A normalized format's ends are exactly 1.0 and -1.0. The host
- // may divide through a reciprocal and land just below 1.0: RDNA
- // 4 loaded 16_16_UNORM's 65535 as the half 0x3BFF, not 0x3C00.
- let x = match numeric {
- Numeric::Unorm => {
- let top = (1u64 << w) - 1;
- let q = if w <= 16 {
- let q = self.norm_quotient(field, w);
- self.as_float(q)
- } else {
- let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
- let max = self.s.m.f32((top as f32).to_bits());
- self.s.m.bin(c, Bin::SDiv, f, max)
- };
- let (high, one) = (self.s.m.i32(top as u32), self.s.m.f32(1.0f32.to_bits()));
- let at_top = self.s.m.cmp(c, pred::EQ, field, high);
- let q = self.s.m.select(c, at_top, one, q);
- float(self, q)
- }
- Numeric::Snorm => {
- let s = signed(self);
- let top = (1u32 << (w - 1)) - 1;
- let q = if w <= 17 {
- // The magnitude's quotient, signed (codes at and
- // below -top are -1.0 below).
- let (zero, sign) = (self.s.m.i32(0), self.s.m.i32(0x8000_0000));
- let neg = self.s.m.cmp(c, pred::SLT, s, zero);
- let minus = self.s.m.bin(c, Bin::Sub, zero, s);
- let m = self.s.m.select(c, neg, minus, s);
- let q = self.norm_quotient(m, w - 1);
- let sign = self.s.m.select(c, neg, sign, zero);
- let q = self.s.m.bin(c, Bin::Or, q, sign);
- self.as_float(q)
- } else {
- let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
- let max = self.s.m.f32((top as f32).to_bits());
- self.s.m.bin(c, Bin::SDiv, f, max)
- };
- // The lowest value is -1.0 too, as is the one above it.
- let (high, one) = (self.s.m.i32(top), self.s.m.f32(1.0f32.to_bits()));
- let at_top = self.s.m.cmp(c, pred::SGE, s, high);
- let q = self.s.m.select(c, at_top, one, q);
- let low = self.s.m.i32(top.wrapping_neg());
- let minus_one = self.s.m.f32((-1.0f32).to_bits());
- let at_bottom = self.s.m.cmp(c, pred::SLE, s, low);
- let q = self.s.m.select(c, at_bottom, minus_one, q);
- float(self, q)
- }
- Numeric::Uscaled => {
- let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
- float(self, f)
- }
- Numeric::Sscaled => {
- let s = signed(self);
- let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
- float(self, f)
- }
- Numeric::Uint => field,
- Numeric::Sint => signed(self),
- Numeric::Float if w == 32 => field,
- Numeric::Float => {
- let h = match half_shift(w) {
- 0 => field,
- k => {
- let sh = self.s.m.i32(k);
- self.s.m.bin(c, Bin::Shl, field, sh)
- }
- };
- let f = self
- .s
- .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
- float(self, f)
- }
- };
- out.push(x);
- }
- let one = match numeric {
- Numeric::Uint | Numeric::Sint => 1,
- _ => 1.0f32.to_bits(),
- };
- for k in out.len() as u32..channels {
- out.push(self.s.m.i32(if k == 3 { one } else { 0 }));
- }
- out.truncate(channels as usize);
- Ok(out)
- }
- /// The bits of the float nearest to `a / d`, `d = 2^w - 1`, for codes
- /// `0 <= a < d` and `w <= 16`: what the console's buffer unit gives for
- /// a normalized code. The host's division is not exact (the RX 6700 XT
- /// returns 8-bit codes one ulp high and some 16-bit codes one ulp low),
- /// and titles truncate `x * d` back to the code (a material index in a
- /// vertex colour's alpha), which a quotient one ulp low turns into the
- /// code below.
- ///
- /// `Q = floor(a * 2^32 / d) = a * K + floor(a * r / d)` with `K =
- /// floor(2^32 / d)` and `r = 2^32 mod d` (no division when `r` is 1:
- /// widths dividing 32). `a / d` is never exact for `0 < a < d` (`d`
- /// odd, `r` coprime to it), so `Q` rounds to 24 bits up exactly when
- /// its highest dropped bit is set, and the result is that integer (at
- /// most 2^24, so its conversion is exact on any host) scaled by a power
- /// of two; `Q` itself when it fits, the quotient's further bits then
- /// lying below half an ulp. That holds for every code of every width but
- /// 11 and 12 (checked for all codes of widths 2 to 16), which take
- /// [`Self::exact_norm`]. The host's conversion of a larger integer is
- /// not relied on: WARP rounds those above 2^31 otherwise.
- fn norm_quotient(&mut self, a: V, w: u32) -> V {
- if matches!(w, 11 | 12) {
- return self.exact_norm(a, w);
- }
- let c = self.cur;
- let d = (1u64 << w) - 1;
- let (kk, r) = ((1u64 << 32) / d, (1u64 << 32) % d);
- let k = |l: &mut Self, v: u64| l.s.m.i32(v as u32);
- let (one, kv) = (k(self, 1), k(self, kk));
- let mut q = self.s.m.bin(c, Bin::Mul, a, kv);
- if r != 1 {
- let (rv, dv) = (k(self, r), k(self, d));
- let t = self.s.m.bin(c, Bin::Mul, a, rv);
- let more = self.s.m.bin(c, Bin::UDiv, t, dv);
- q = self.s.m.bin(c, Bin::Add, q, more);
- }
- // The bits to drop (1 to 8) from the exponent of `q >> 8`, which
- // converts exactly (fewer than 25 bits); none when `q` fits.
- let k8 = k(self, 8);
- let top = self.s.m.bin(c, Bin::LShr, q, k8);
- let top = self.s.m.cast(c, Cast::UiToFp, top, self.s.t.f32);
- let top = self.as_int(top);
- let k23 = k(self, 23);
- let e = self.s.m.bin(c, Bin::LShr, top, k23);
- let bias = k(self, 127 + 15);
- let shift = self.s.m.bin(c, Bin::Sub, e, bias);
- let (zero, b24) = (k(self, 0), k(self, 1 << 24));
- let fits = self.s.m.cmp(c, pred::IULT, q, b24);
- let shift = self.s.m.select(c, fits, zero, shift);
- // Rounded up when the highest dropped bit is set: `a / d` is never
- // exact, so a dropped half is more than half, never a tie.
- let up = self.s.m.bin(c, Bin::Shl, q, one);
- let up = self.s.m.bin(c, Bin::LShr, up, shift);
- let up = self.s.m.bin(c, Bin::And, up, one);
- let m = self.s.m.bin(c, Bin::LShr, q, shift);
- let m = self.s.m.bin(c, Bin::Add, m, up);
- // At most 2^24: exact as a float, and so its scale by 2^(shift - 32).
- let f = self.s.m.cast(c, Cast::UiToFp, m, self.s.t.f32);
- let b95 = k(self, 127 - 32);
- let scale = self.s.m.bin(c, Bin::Add, shift, b95);
- let scale = self.s.m.bin(c, Bin::Shl, scale, k23);
- let scale = self.as_float(scale);
- let f = self.s.m.bin(c, Bin::Mul, f, scale);
- self.as_int(f)
- }
- /// [`Self::norm_quotient`] in integers only, for any width up to 16: `Q`
- /// as there, 8 more bits when that leaves fewer than 25 (codes of wide
- /// formats near 0), then rounded to 24 bits to nearest even with the
- /// remainder as sticky bit, and assembled as float bits.
- fn exact_norm(&mut self, a: V, w: u32) -> V {
- let c = self.cur;
- let d = (1u64 << w) - 1;
- let (kk, r) = ((1u64 << 32) / d, (1u64 << 32) % d);
- let k = |l: &mut Self, v: u64| l.s.m.i32(v as u32);
- let (one, zero, dv, k8) = (k(self, 1), k(self, 0), k(self, d), k(self, 8));
- let kv = k(self, kk);
- let mut q = self.s.m.bin(c, Bin::Mul, a, kv);
- let mut rem = a;
- if r != 1 {
- let rv = k(self, r);
- let t = self.s.m.bin(c, Bin::Mul, a, rv);
- let more = self.s.m.bin(c, Bin::UDiv, t, dv);
- q = self.s.m.bin(c, Bin::Add, q, more);
- rem = self.s.m.bin(c, Bin::URem, t, dv);
- }
- // The exponent's bias less the 32 (or 40) fraction bits of `q`; the
- // shift below is added.
- let mut bias = k(self, 127 + 23 - 32);
- if kk < 1 << 24 {
- // Fewer than 25 bits for the smallest codes: 8 more.
- let t = self.s.m.bin(c, Bin::Shl, rem, k8);
- let more = self.s.m.bin(c, Bin::UDiv, t, dv);
- let rest = self.s.m.bin(c, Bin::URem, t, dv);
- let wide = self.s.m.bin(c, Bin::Shl, q, k8);
- let wide = self.s.m.bin(c, Bin::Or, wide, more);
- let limit = k(self, 1 << 24);
- let small = self.s.m.cmp(c, pred::IULT, q, limit);
- q = self.s.m.select(c, small, wide, q);
- rem = self.s.m.select(c, small, rest, rem);
- let b40 = k(self, 127 + 23 - 40);
- bias = self.s.m.select(c, small, b40, bias);
- }
- // Bits to drop: the bit length less 24, 1 to 8.
- let mut shift = one;
- for bit in 25..32 {
- let at = k(self, 1 << bit);
- let ge = self.s.m.cmp(c, pred::IUGE, q, at);
- let add = self.s.m.select(c, ge, one, zero);
- shift = self.s.m.bin(c, Bin::Add, shift, add);
- }
- let mant = self.s.m.bin(c, Bin::LShr, q, shift);
- let below = self.s.m.bin(c, Bin::Sub, shift, one);
- let half = self.s.m.bin(c, Bin::LShr, q, below);
- let half = self.s.m.bin(c, Bin::And, half, one);
- let low = self.s.m.bin(c, Bin::Shl, one, below);
- let low = self.s.m.bin(c, Bin::Sub, low, one);
- let low = self.s.m.bin(c, Bin::And, q, low);
- let rest = self.s.m.bin(c, Bin::Or, low, rem);
- let sticky = self.s.m.cmp(c, pred::NE, rest, zero);
- let odd = self.s.m.bin(c, Bin::And, mant, one);
- let tie = self.s.m.select(c, sticky, one, odd);
- let up = self.s.m.bin(c, Bin::And, half, tie);
- let mant = self.s.m.bin(c, Bin::Add, mant, up);
- // Rounding up to 2^24 moves to the next exponent.
- let k24 = k(self, 24);
- let carry = self.s.m.bin(c, Bin::LShr, mant, k24);
- let mant = self.s.m.bin(c, Bin::LShr, mant, carry);
- let e = self.s.m.bin(c, Bin::Add, bias, shift);
- let e = self.s.m.bin(c, Bin::Add, e, carry);
- let k23 = k(self, 23);
- let e = self.s.m.bin(c, Bin::Shl, e, k23);
- let fraction = k(self, 0x7F_FFFF);
- let m = self.s.m.bin(c, Bin::And, mant, fraction);
- let bits = self.s.m.bin(c, Bin::Or, e, m);
- let is_zero = self.s.m.cmp(c, pred::EQ, a, zero);
- self.s.m.select(c, is_zero, zero, bits)
- }
- /// Channels of buffer format `format`, as [`Self::format_load`] gives
- /// them, as d16 data: 16 bits each, two per dword, low half first (an
- /// odd last high half 0). Integer formats keep their low 16 bits; the
- /// others become f16.
- fn d16_channels(&mut self, format: u8, channels: Vec<V>) -> Result<Vec<V>, Why> {
- let (_, numeric) = buffer_format(format).ok_or("a buffer format")?;
- let c = self.cur;
- let mut halves = Vec::new();
- for x in channels {
- halves.push(if matches!(numeric, Numeric::Uint | Numeric::Sint) {
- let m = self.s.m.i32(0xFFFF);
- self.s.m.bin(c, Bin::And, x, m)
- } else {
- let (f, i32t) = (self.as_float(x), self.s.t.i32);
- self.s
- .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
- });
- }
- let mut out = Vec::new();
- for pair in halves.chunks(2) {
- out.push(match *pair {
- [lo, hi] => {
- let k16 = self.s.m.i32(16);
- let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
- self.s.m.bin(c, Bin::Or, lo, hi)
- }
- [lo] => lo,
- _ => unreachable!("chunks of one or two"),
- });
- }
- Ok(out)
- }
- /// The byte offset a buffer descriptor built around a root descriptor adds
- /// (constant and computed parts); none for other descriptors.
- fn built_offset(&mut self, src: &Source) -> Result<(u32, Option<V>), Why> {
- match src {
- Source::Built { address, .. } => {
- let mut x = match address.dynamic {
- Some(v) => Some(self.i32_of(v)?),
- None => None,
- };
- if let Some(bias) = self.root_bias(address.param) {
- x = Some(match x {
- Some(d) => self.s.m.bin(self.cur, Bin::Add, d, bias),
- None => bias,
- });
- }
- Ok((address.offset, x))
- }
- _ => Ok((0, None)),
- }
- }
- /// For a root view the host binds as a raw view that may begin before
- /// the title's address (`shader.rs` `USER_VIEW_BIAS`): the bytes to add
- /// to offsets through it. Every root UAV (root SRVs keep the views they
- /// have).
- fn root_bias(&mut self, param: usize) -> Option<V> {
- use super::shader::USER_VIEW_BIAS;
- let rp = *self.x.native.layout.get(param)?;
- // (Title memory by address where the user-data table is spilled:
- // [`Lower::root_memory`].)
- if rp.root != RootType::Descriptor || crate::spill::is_spilled(self.x.native) {
- return None;
- }
- let kind = self
- .x
- .native
- .used
- .iter()
- .find(|u| u.user_data == rp.user_data)
- .map(|u| u.kind);
- (kind == Some(ResourceType::Uav)).then(|| self.host_word(RootType::Other(USER_VIEW_BIAS), rp.slot, 0))
- }
- /// The used-resource entry a descriptor loaded from a table falls in.
- fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> {
- if let Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } =
- src
- {
- return self.used_kind(args.first()?);
- }
- if let Source::LanePhi { args, .. } = src {
- return args.iter().flatten().find_map(|a| self.used_kind(a));
- }
- if let Source::Built { address, .. } = src {
- let rp = self.x.native.layout.get(address.param)?;
- return self
- .x
- .native
- .used
- .iter()
- .find(|u| u.root == RootType::Descriptor && u.user_data == rp.user_data);
- }
- let (Source::Loaded { load, first } | Source::Fetched { load, first }) = src else {
- return None;
- };
- let a = self.scalar.get(load)?;
- let rp = self.x.native.layout.get(a.param)?;
- if rp.root != RootType::Table {
- return None;
- }
- let dword = (a.offset / 4) + u32::from(*first);
- self.x
- .native
- .used
- .iter()
- .filter(|u| {
- u.root == RootType::Table
- && u.user_data == rp.user_data
- && u.table_offset_dwords <= dword
- })
- .max_by_key(|u| u.table_offset_dwords)
- }
- /// A handle for the descriptor `src` read at `site`.
- fn handle(
- &mut self,
- site: Site,
- src: &Source,
- sampler: bool,
- props: (u32, u32),
- ) -> Result<V, Why> {
- match src {
- Source::Loaded { load, first } => {
- let key = (self.cur, *load, *first, sampler, props);
- if let Some(&h) = self.handles.get(&key) {
- return Ok(h);
- }
- let index = self.heap_index(*load, *first, sampler)?;
- let (index, bounded) = self.raw_twin(src, index, sampler, props);
- // A waterfall loop's load at the first lane's offset reads
- // each lane's own entry (see `resource::Waterfall`).
- let per_lane = self.x.res.waterfall.loads.contains(load);
- let h = self
- .s
- .heap_handle_at(self.cur, index, sampler, per_lane, props, bounded);
- self.handles.insert(key, h);
- Ok(h)
- }
- Source::Constant(words) if sampler => {
- let n = self.register_sampler(words, props.0 & 0x8000 != 0)?;
- Ok(self.s.sampler_handle(self.cur, n))
- }
- Source::Constant(_) => Err("a constant resource descriptor"),
- Source::Built { .. } if self.root_copy.is_some() => self.root_copy.ok_or("no copy"),
- Source::Built { address, .. } => {
- let rp = *self
- .x
- .native
- .layout
- .get(address.param)
- .ok_or("a descriptor built around a table in the code")?;
- let kind = self
- .x
- .native
- .used
- .iter()
- .find(|u| u.user_data == rp.user_data)
- .map(|u| u.kind);
- match (rp.root, kind, props.0) {
- (RootType::Descriptor, Some(ResourceType::Cbv) | None, 13) => {
- Ok(self.s.root_cbv_handle(rp.slot))
- }
- (RootType::Descriptor, Some(ResourceType::Srv), 11) => {
- Ok(self.s.root_srv_handle(rp.slot))
- }
- // A root UAV: a raw buffer whether the access reads
- // (11) or writes (11 with the UAV bit). Indexed
- // accesses reach here as raw ones at index times the
- // entry's stride (`buffer`).
- (RootType::Descriptor, Some(ResourceType::Uav), 11 | 0x100b) => {
- Ok(self.s.root_uav_handle(rp.slot))
- }
- (RootType::Descriptor, Some(ResourceType::Srv), 0x100b) => {
- Err("a write through a root SRV")
- }
- _ => Err("a typed root view"),
- }
- }
- Source::Phi { block, args } => {
- let _ = site;
- let phi = self.descriptor_phi(*block, args, sampler, 8)?;
- let (index, bounded) = self.raw_twin(src, phi, sampler, props);
- Ok(self.s.heap_handle_at(self.cur, index, sampler, false, props, bounded))
- }
- Source::Select { scc, args } => {
- // The heap index of each choice, picked by SCC (uniform).
- let [
- Source::Loaded { load: a, first: fa },
- Source::Loaded { load: b, first: fb },
- ] = args[..]
- else {
- return Err("a descriptor chosen by a condition");
- };
- let cond = match self.get(*scc)? {
- Val::Bit(x) => x,
- _ => return Err("SCC without a value"),
- };
- let set = self.heap_index(a, fa, sampler)?;
- let clear = self.heap_index(b, fb, sampler)?;
- let index = self.s.m.select(self.cur, cond, set, clear);
- let (index, bounded) = self.raw_twin(src, index, sampler, props);
- Ok(self.s.heap_handle_at(self.cur, index, sampler, false, props, bounded))
- }
- Source::Fetched { .. } | Source::Lanes { .. } | Source::LanePhi { .. } => {
- // A descriptor each lane has its own of (a waterfall loop
- // reads it from the first active lane): each lane's heap
- // index, non-uniform.
- let index = self.lane_heap_index(src, sampler)?;
- let (index, bounded) = self.raw_twin(src, index, sampler, props);
- Ok(self.s.heap_handle_at(self.cur, index, sampler, true, props, bounded))
- }
- }
- }
- /// The heap index to read descriptor `src` at, `index` being the title's:
- /// for a buffer read as raw bytes, through a table or picked from the
- /// heap itself (or picked and read as a constant buffer), the host's raw
- /// twin of that slot ([`super::shader::raw_views`]), whose reads end where
- /// the view does. Everything else (textures, typed buffers, tables'
- /// constant buffers) stays in place. And whether it is a twin's (inside
- /// the host's heap).
- ///
- /// Tables too: a view that does not begin on 16 bytes cannot be raw, and
- /// a pixel program of the main pass (3711fdad456538a1, stopped at in the
- /// device losses of runs n03 and n04) reads a structured one of 8 byte
- /// elements at 8 as raw bytes per lane.
- fn raw_twin(&mut self, src: &Source, index: V, sampler: bool, props: (u32, u32)) -> (V, bool) {
- // Raw and constant buffers (DXIL resource kinds 11 and 13).
- const RAW: u32 = 11;
- const CONSTANT: u32 = 13;
- let first = super::shader::raw_views();
- let picked = |leaf: &&Source| {
- let (Source::Loaded { load, .. } | Source::Fetched { load, .. }) = leaf else {
- return false;
- };
- self.scalar
- .get(load)
- .and_then(|a| self.x.native.layout.get(a.param))
- .is_some_and(|p| {
- p.root == RootType::ResourceHeap || (p.root == RootType::Table && props.0 & 0xFF == RAW)
- })
- };
- if first == 0 || sampler || !matches!(props.0 & 0xFF, RAW | CONSTANT) || !src.leaves().iter().all(picked) {
- return (index, false);
- }
- let c = self.cur;
- let (last, first) = (self.s.m.i32(first - 1), self.s.m.i32(first));
- let i32t = self.s.t.i32;
- // (As `dx.op.binary` UMin, see `heap_handle`.)
- let index = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]);
- self.s.m.tag(index, Tag::Clamp);
- (self.s.m.bin(c, Bin::Or, index, first), true)
- }
- /// The heap index a descriptor phi picks. Each predecessor computes its
- /// heap index at its end and the join picks one with a phi; a
- /// predecessor whose descriptor is itself chosen by control flow (a
- /// phi of an earlier join, which dominates it) gives that join's phi,
- /// at most `depth` joins deep.
- fn descriptor_phi(
- &mut self,
- block: usize,
- args: &[Source],
- sampler: bool,
- depth: u32,
- ) -> Result<V, Why> {
- const WHY: Why = "a descriptor chosen by control flow";
- let p = self.x.p;
- let mut incoming = Vec::new();
- for (&q, arg) in p.blocks[block].preds.iter().zip(args) {
- if self.block[q].is_none() {
- continue;
- }
- let tail = self.tail[q].ok_or(WHY)?;
- let at = self.edges.get(&(q, block)).copied().unwrap_or(tail);
- let index = match arg {
- Source::Loaded { load, first } => {
- let here = std::mem::replace(&mut self.cur, at);
- let index = self.heap_index(*load, *first, sampler);
- self.cur = here;
- index?
- }
- Source::Phi { block: inner, args: inner_args } if depth > 0 => {
- self.descriptor_phi(*inner, inner_args, sampler, depth - 1)?
- }
- _ => return Err(WHY),
- };
- incoming.push((index, at));
- }
- let join = self.block[block].ok_or(WHY)?;
- let phi = self.s.m.phi(join, self.s.t.i32);
- self.s.m.set_phi(phi, incoming);
- Ok(phi)
- }
- /// Registers an immediate sampler constant and returns its slot index: a
- /// constant used with and without comparison takes one slot for each.
- fn register_sampler(&mut self, words: &[u32], cmp: bool) -> Result<u32, Why> {
- let words: [u32; 4] = words
- .get(..4)
- .and_then(|w| w.try_into().ok())
- .ok_or("a sampler constant")?;
- let slot = self
- .samplers
- .iter()
- .enumerate()
- .position(|(n, w)| *w == words && (self.s.cmp_samplers >> n & 1 != 0) == cmp);
- let n = match slot {
- Some(n) => n,
- None => {
- let n = self.samplers.len();
- if n >= u64::BITS as usize {
- return Err("more than 64 immediate sampler slots");
- }
- self.samplers.push(words);
- self.s.cmp_samplers |= u64::from(cmp) << n;
- n
- }
- };
- Ok(n as u32)
- }
- /// Resolves a control-flow phi of immediate sampler constants into either a
- /// single static sampler register (`One`) or a uniform `i32` phi index over
- /// `regs` (`Many`) for branch dispatch at the sample site.
- fn sampler_phi_choice(
- &mut self,
- block: usize,
- args: &[Source],
- cmp: bool,
- depth: u32,
- ) -> Result<(Option<V>, Vec<u32>), Why> {
- const WHY: Why = "a descriptor chosen by control flow";
- let mut distinct: Vec<[u32; 4]> = Vec::new();
- self.collect_constant_samplers(block, args, depth, &mut distinct)?;
- if distinct.is_empty() {
- return Err(WHY);
- }
- let mut regs = Vec::with_capacity(distinct.len());
- for w in &distinct {
- regs.push(self.register_sampler(w, cmp)?);
- }
- if regs.len() == 1 {
- return Ok((None, regs));
- }
- let idx = self.sampler_index_phi(block, args, 0, &distinct, depth)?;
- Ok((Some(idx), regs))
- }
- fn collect_constant_samplers(
- &self,
- block: usize,
- args: &[Source],
- depth: u32,
- distinct: &mut Vec<[u32; 4]>,
- ) -> Result<(), Why> {
- const WHY: Why = "a descriptor chosen by control flow";
- let p = self.x.p;
- for (&q, arg) in p.blocks[block].preds.iter().zip(args) {
- if self.block[q].is_none() {
- continue;
- }
- match arg {
- Source::Constant(w) if w.len() >= 4 => {
- let k: [u32; 4] = w[..4].try_into().unwrap();
- if !distinct.contains(&k) {
- distinct.push(k);
- }
- }
- Source::Phi {
- block: inner,
- args: inner_args,
- } if depth > 0 => {
- self.collect_constant_samplers(*inner, inner_args, depth - 1, distinct)?;
- }
- _ => return Err(WHY),
- }
- }
- Ok(())
- }
- fn sampler_index_phi(
- &mut self,
- block: usize,
- args: &[Source],
- lower: u32,
- distinct: &[[u32; 4]],
- depth: u32,
- ) -> Result<V, Why> {
- const WHY: Why = "a descriptor chosen by control flow";
- let p = self.x.p;
- let mut incoming = Vec::new();
- for (&q, arg) in p.blocks[block].preds.iter().zip(args) {
- if self.block[q].is_none() {
- continue;
- }
- let tail = self.tail[q].ok_or(WHY)?;
- let at = self.edges.get(&(q, block)).copied().unwrap_or(tail);
- let idx = match arg {
- Source::Constant(w) if w.len() >= 4 => {
- let k: [u32; 4] = w[..4].try_into().unwrap();
- let pos = distinct.iter().position(|d| *d == k).ok_or(WHY)? as u32;
- self.s.m.i32(lower + pos)
- }
- Source::Phi {
- block: inner,
- args: inner_args,
- } if depth > 0 => {
- self.sampler_index_phi(*inner, inner_args, lower, distinct, depth - 1)?
- }
- _ => return Err(WHY),
- };
- incoming.push((idx, at));
- }
- let join = self.block[block].ok_or(WHY)?;
- let phi = self.s.m.phi(join, self.s.t.i32);
- self.s.m.set_phi(phi, incoming);
- Ok(phi)
- }
- /// The bytes per element of the buffer view `src` names, if the program
- /// picks it from the view heap at an index it computes (root type
- /// `ResourceHeap`): read from the host's table by heap slot in the
- /// current block.
- fn slot_stride(&mut self, src: &Source) -> Result<Option<V>, Why> {
- let word = self.slot_word(src)?;
- Ok(word.map(|word| {
- let bits = self.s.m.i32(super::shader::VIEW_STRIDE_BITS);
- self.s.m.bin(self.cur, Bin::And, word, bits)
- }))
- }
- /// Whether the typed buffer view `src` names is one of an integer format,
- /// and whether a signed one, as [`Self::slot_stride`] (`None`: a view the
- /// program does not pick from the heap).
- fn integer_view(&mut self, src: &Source) -> Result<Option<(V, V)>, Why> {
- let Some(word) = self.slot_word(src)? else {
- return Ok(None);
- };
- let c = self.cur;
- let zero = self.s.m.i32(0);
- let [int, signed] = [super::shader::VIEW_INTEGER, super::shader::VIEW_SIGNED].map(|bit| {
- let bit = self.s.m.i32(bit);
- let x = self.s.m.bin(c, Bin::And, word, bit);
- self.s.m.cmp(c, pred::NE, x, zero)
- });
- Ok(Some((int, signed)))
- }
- /// The host's word for the buffer view `src` names: its stride and
- /// format kind ([`super::shader::SLOT_STRIDES`]).
- fn slot_word(&mut self, src: &Source) -> Result<Option<V>, Why> {
- let Source::Loaded { load, first } = src else {
- return Ok(None);
- };
- let heap = self
- .scalar
- .get(load)
- .and_then(|a| self.x.native.layout.get(a.param))
- .is_some_and(|p| p.root == RootType::ResourceHeap);
- if !heap {
- return Ok(None);
- }
- let key = (self.cur, *load, *first);
- if let Some(&v) = self.strides.get(&key) {
- return Ok(Some(v));
- }
- let c = self.cur;
- let slot = self.heap_index(*load, *first, false)?;
- // Inside the table whatever the index (lanes that do not run
- // compute one too): a root view has no bounds of its own.
- let last = self.s.m.i32(super::shader::SLOT_STRIDES_COUNT - 1);
- let i32t = self.s.t.i32;
- let slot = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[slot, last]);
- self.s.m.tag(slot, Tag::Clamp);
- let two = self.s.m.i32(2);
- let byte = self.s.m.bin(c, Bin::Shl, slot, two);
- let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES);
- let iu = self.s.m.undef(self.s.t.i32);
- let mask = self.s.m.i8(1);
- let align = self.s.m.i32(4);
- let r = self.s.op(
- c,
- "rawBufferLoad.f32",
- Attr::ReadOnly,
- self.s.t.res_ret,
- 139,
- &[h, byte, iu, mask, align],
- );
- let f = self.s.m.extract(c, r, 0);
- let v = self.as_int(f);
- self.strides.insert(key, v);
- Ok(Some(v))
- }
- /// The heap index of a descriptor that may differ between lanes,
- /// computed in the current block (or, chosen by control flow, at the
- /// join).
- fn lane_heap_index(&mut self, src: &Source, sampler: bool) -> Result<V, Why> {
- match src {
- Source::Loaded { load, first } => self.heap_index(*load, *first, sampler),
- Source::Fetched { load, first } => self.fetched_index(*load, *first, sampler),
- Source::Lanes { mask, args } | Source::Select { scc: mask, args } => {
- let [a, b] = &args[..] else {
- return Err("a descriptor chosen per lane");
- };
- let cond = if matches!(src, Source::Lanes { .. }) {
- let &m = self
- .x
- .st
- .masks
- .get(mask)
- .ok_or("a descriptor chosen per lane by an untracked mask")?;
- self.boolean(m, self.cur)?
- } else {
- match self.get(*mask)? {
- Val::Bit(x) => x,
- _ => return Err("SCC without a value"),
- }
- };
- let set = self.lane_heap_index(a, sampler)?;
- let clear = self.lane_heap_index(b, sampler)?;
- Ok(self.s.m.select(self.cur, cond, set, clear))
- }
- Source::LanePhi { block, args } => {
- // Each predecessor computes its heap index at its end (what
- // it reads is there: the dwords are, on that edge); the join
- // picks the one of the edge the lane came by. An edge no
- // lane reading it takes gives index 0.
- let join =
- self.block[*block].ok_or("a per-lane descriptor chosen by control flow")?;
- let mut incoming = Vec::new();
- for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) {
- if self.block[q].is_none() {
- continue;
- }
- let tail =
- self.tail[q].ok_or("a per-lane descriptor joined from a later block")?;
- let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail);
- let index = match arg {
- Some(arg) => {
- let here = std::mem::replace(&mut self.cur, at);
- let index = self.lane_heap_index(arg, sampler);
- self.cur = here;
- index?
- }
- None => self.s.m.i32(0),
- };
- incoming.push((index, at));
- }
- let phi = self.s.m.phi(join, self.s.t.i32);
- self.s.m.set_phi(phi, incoming);
- Ok(phi)
- }
- _ => Err("a per-lane descriptor from neither a heap load nor a choice of them"),
- }
- }
- /// The heap index of the descriptor at dword `first` of what the global
- /// load at `load` reads, in each lane: its address (base plus offsets)
- /// over the descriptor size.
- fn fetched_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> {
- const WHY: Why = "a per-lane descriptor load";
- let a = *self
- .scalar
- .get(&load)
- .ok_or("an untracked descriptor load")?;
- match self.x.native.layout.get(a.param).map(|p| p.root) {
- Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {}
- _ => return Err("a descriptor outside the heaps"),
- }
- let li: &Inst = &self.x.p.blocks[load.0].insts[load.1];
- let Fields::Flat {
- addr: Some(Operand::Vector { reg, .. }),
- saddr,
- offset,
- ..
- } = li.fields
- else {
- return Err(WHY);
- };
- let c = self.cur;
- // The low dword of the address: SGPR base plus VGPR offset, or the
- // VGPR pair's low half (heap addresses fit in 32 bits).
- let mut at = self.i32_of(li.read(Reg::V(reg)).ok_or(WHY)?)?;
- if let Some(Operand::Scalar { code, .. }) = saddr
- && code != NULL
- {
- let base = self.i32_of(li.read(Reg::S(code)).ok_or(WHY)?)?;
- at = self.s.m.bin(c, Bin::Add, base, at);
- }
- let k = self
- .s
- .m
- .i32((offset as i32 as u32).wrapping_add(4 * u32::from(first)));
- at = self.s.m.bin(c, Bin::Add, at, k);
- let shift = self.s.m.i32(if sampler { 4 } else { 5 });
- Ok(self.s.m.bin(c, Bin::LShr, at, shift))
- }
- /// The heap index of the descriptor at dword `first` of what the scalar
- /// load at `load` reads, computed in the current block.
- fn heap_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> {
- let a = *self
- .scalar
- .get(&load)
- .ok_or("an untracked descriptor load")?;
- match self.x.native.layout.get(a.param).map(|p| p.root) {
- Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {}
- _ => return Err("a descriptor outside the heaps"),
- }
- let li: &Inst = &self.x.p.blocks[load.0].insts[load.1];
- let Fields::Smem {
- base,
- offset,
- soffset,
- ..
- } = &li.fields
- else {
- return Err("a descriptor load");
- };
- let Operand::Scalar { code, .. } = *base else {
- return Err("a descriptor load");
- };
- let c = self.cur;
- let base = li.read(Reg::S(code)).ok_or("a descriptor load")?;
- let mut addr = self.i32_of(base)?;
- let k = self
- .s
- .m
- .i32((*offset as u32).wrapping_add(4 * u32::from(first)));
- addr = self.s.m.bin(c, Bin::Add, addr, k);
- if !matches!(soffset, Operand::Scalar { code: NULL, .. }) {
- let so = self.operand(li, soffset)?;
- addr = self.s.m.bin(c, Bin::Add, addr, so);
- }
- let shift = self.s.m.i32(if sampler { 4 } else { 5 });
- Ok(self.s.m.bin(c, Bin::LShr, addr, shift))
- }
- fn valu(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- let name = inst.name();
- if self.x.res.waterfall.compares.contains(&(b, i)) {
- // The first lane's dwords of a waterfall loop are each lane's
- // own (see `resource::Waterfall`).
- self.lane(inst, Some(true));
- return Ok(());
- }
- // One lane of a VGPR a whole-wave section left.
- if name == "v_readlane_b32"
- && let Some(&(_, w)) = inst.writes.first()
- && let Some(sh) = self.sections.get(&b).and_then(|s| {
- s.iter().filter(|s| s.1.end < i).find_map(|s| s.1.reads.get(&w).copied())
- })
- {
- let x = self.shape(sh, false)?;
- self.vals.insert(w, Val::I32(x));
- return Ok(());
- }
- if let Some(rest) = name.strip_prefix("v_cmp_").or(name.strip_prefix("v_cmpx_")) {
- let r = if v.dpp.is_some() {
- Err("a compare with DPP")
- } else {
- self.compare(inst, rest)
- };
- if let Err(why) = r {
- for &(_, w) in &inst.writes {
- self.lane_fail.insert(w, why);
- }
- }
- return r;
- }
- let mut guard = self.guard(b, i)?;
- if let Some(d) = v.dpp {
- let (x, enable) = self.dpp(inst, d)?;
- guard = match (guard, enable) {
- (Some(g), Some(e)) => Some(self.s.m.bin(self.cur, Bin::And, g, e)),
- (g, e) => g.or(e),
- };
- self.src0 = Some(x);
- }
- let r = self.valu_op(inst, guard);
- self.src0 = None;
- r
- }
- /// DPP: src0 as read from another lane, and which lanes write their
- /// result (none: all).
- fn dpp(&mut self, inst: &Inst, dpp: Dpp) -> Result<(V, Option<V>), Why> {
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- let Some(&Operand::Vector { reg, .. }) = v.src.first() else {
- return Err("a DPP operand");
- };
- let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("a DPP operand")?)?;
- // Quad permutations and DPP8 stay in groups the pixel layout shares.
- let quad = matches!(dpp, Dpp::Row { ctrl: 0..=0xFF, .. });
- let mesh_quad = self.s.mesh.is_some() && quad;
- if !mesh_quad {
- self.cross_lane(quad)?;
- }
- let c = self.cur;
- let lane = self.lane_index();
- let k = |l: &mut Self, n: u32| l.s.m.i32(n);
- let (sixteen_mask, low) = (k(self, !15), k(self, 15));
- let row = self.s.m.bin(c, Bin::And, lane, sixteen_mask);
- let pos = self.s.m.bin(c, Bin::And, lane, low);
- // Source lane, and whether it lies in the row.
- let (src, inside, masks, zero) = match dpp {
- Dpp::Lanes { sel, .. } => {
- let (seven, not7, three) = (k(self, 7), k(self, !7), k(self, 3));
- let p = self.s.m.bin(c, Bin::And, lane, seven);
- let sh = self.s.m.bin(c, Bin::Mul, p, three);
- let sel = k(self, sel);
- let pick = self.s.m.bin(c, Bin::LShr, sel, sh);
- let pick = self.s.m.bin(c, Bin::And, pick, seven);
- let base = self.s.m.bin(c, Bin::And, lane, not7);
- (self.s.m.bin(c, Bin::Or, base, pick), None, None, false)
- }
- Dpp::Row {
- ctrl,
- row_mask,
- bank_mask,
- bound_ctrl,
- ..
- } => {
- let n = u32::from(ctrl & 15);
- let (src, inside) = match ctrl {
- 0..=0xFF => {
- let (three, one, not3) = (k(self, 3), k(self, 1), k(self, !3));
- let p = self.s.m.bin(c, Bin::And, lane, three);
- let sh = self.s.m.bin(c, Bin::Shl, p, one);
- let perm = k(self, u32::from(ctrl));
- let pick = self.s.m.bin(c, Bin::LShr, perm, sh);
- let pick = self.s.m.bin(c, Bin::And, pick, three);
- let base = self.s.m.bin(c, Bin::And, lane, not3);
- (self.s.m.bin(c, Bin::Or, base, pick), None)
- }
- 0x101..=0x10F | 0x111..=0x11F => {
- let nn = k(self, n);
- let left = ctrl < 0x110;
- let (op, p) = if left {
- (Bin::Add, pred::IULT)
- } else {
- (Bin::Sub, pred::IUGE)
- };
- let s = self.s.m.bin(c, op, lane, nn);
- // Left: pos + n < 16; right: pos >= n.
- let bound = if left { k(self, 16 - n) } else { nn };
- (s, Some(self.s.m.cmp(c, p, pos, bound)))
- }
- 0x121..=0x12F => {
- let nn = k(self, n);
- let t = self.s.m.bin(c, Bin::Sub, pos, nn);
- let t = self.s.m.bin(c, Bin::And, t, low);
- (self.s.m.bin(c, Bin::Or, row, t), None)
- }
- 0x140 | 0x141 => {
- let m = k(self, if ctrl == 0x140 { 15 } else { 7 });
- let t = self.s.m.bin(c, Bin::Xor, lane, m);
- (t, None)
- }
- 0x150..=0x15F => {
- let nn = k(self, n);
- (self.s.m.bin(c, Bin::Or, row, nn), None)
- }
- 0x160..=0x16F => {
- let nn = k(self, n);
- (self.s.m.bin(c, Bin::Xor, lane, nn), None)
- }
- _ => return Err("a DPP lane pattern"),
- };
- let masks = (row_mask != 0xF || bank_mask != 0xF).then_some((row_mask, bank_mask));
- (src, inside, masks, bound_ctrl)
- }
- };
- let mut r = if mesh_quad {
- self.quad_pick(x, src)
- } else if let Dpp::Row { ctrl, .. } = dpp
- && self.helpers_read(quad)
- {
- self.quad_read(x, [0, 1, 2, 3].map(|i| (ctrl >> (2 * i) & 3) as u8))
- } else {
- self.read_lane(x, src)
- };
- let mut enable = None;
- if let Some(inside) = inside {
- if zero {
- let z = k(self, 0);
- r = self.s.m.select(c, inside, r, z);
- } else {
- enable = Some(inside);
- }
- }
- if let Some((rows, banks)) = masks {
- // Row (16 lanes) and bank (4 lanes of a row) write masks.
- let (four, two, three) = (k(self, 4), k(self, 2), k(self, 3));
- let ri = self.s.m.bin(c, Bin::LShr, lane, four);
- let ri = self.s.m.bin(c, Bin::And, ri, three);
- let bi = self.s.m.bin(c, Bin::LShr, lane, two);
- let bi = self.s.m.bin(c, Bin::And, bi, three);
- let (rm, bm) = (k(self, u32::from(rows)), k(self, u32::from(banks)));
- let rb = self.s.m.bin(c, Bin::LShr, rm, ri);
- let bb = self.s.m.bin(c, Bin::LShr, bm, bi);
- let both = self.s.m.bin(c, Bin::And, rb, bb);
- let (one, z) = (k(self, 1), k(self, 0));
- let both = self.s.m.bin(c, Bin::And, both, one);
- let on = self.s.m.cmp(c, pred::NE, both, z);
- enable = Some(match enable {
- Some(e) => self.s.m.bin(c, Bin::And, e, on),
- None => on,
- });
- }
- Ok((r, enable))
- }
- fn valu_op(&mut self, inst: &Inst, guard: Option<V>) -> Result<(), Why> {
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- let name = inst.name();
- let c = self.cur;
- let f = |l: &mut Self, k| l.fsrc(inst, k);
- let s = |l: &mut Self, k| l.src(inst, k);
- let float = |l: &mut Self, r: V| l.write_f(inst, r, guard);
- let int = |l: &mut Self, r: V| l.write_i(inst, r, guard);
- if let Some(r) = self.valu16(inst, name, guard) {
- return r;
- }
- if let Some(op) = name.strip_prefix("v_pk_") {
- return self.packed16(inst, op, guard);
- }
- match name {
- "v_mad_u64_u32" => {
- // a * b + c, c and the result 64 bits wide; the carry out
- // of the sum is this lane's bit of the mask it names.
- let (a, b) = (s(self, 0)?, s(self, 1)?);
- let x = self.src64(inst, 2)?;
- let i64t = self.s.m.int(64);
- self.s.flags |= flags::INT64;
- let a = self.s.m.cast(c, Cast::ZExt, a, i64t);
- let b = self.s.m.cast(c, Cast::ZExt, b, i64t);
- let product = self.s.m.bin(c, Bin::Mul, a, b);
- let r = self.s.m.bin(c, Bin::Add, product, x);
- let carry = self.s.m.cmp(c, pred::IULT, r, x);
- let Some(Operand::Vector { reg, .. }) = v.dst else {
- return Err("a 64-bit result");
- };
- let (lo, hi) = self.split64(r);
- self.write(inst, Reg::V(reg), lo, guard);
- self.write(inst, Reg::V(reg + 1), hi, guard);
- if let Some(Operand::Scalar { code, .. }) = v.carry
- && let Some(w) = inst.write(Reg::S(code))
- {
- self.lane_bits.insert(w, carry);
- }
- for &(_, w) in &inst.writes {
- self.vals
- .entry(w)
- .or_insert(Val::Missing("a lane mask read as data"));
- }
- Ok(())
- }
- "v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => {
- let n = s(self, 0)?;
- let x = self.src64(inst, 1)?;
- let i64t = self.s.m.int(64);
- let k63 = self.s.m.i32(63);
- let n = self.s.m.bin(c, Bin::And, n, k63);
- let n = self.s.m.cast(c, Cast::ZExt, n, i64t);
- let op = match name {
- "v_lshlrev_b64" => Bin::Shl,
- "v_lshrrev_b64" => Bin::LShr,
- _ => Bin::AShr,
- };
- let r = self.s.m.bin(c, op, x, n);
- let Some(Operand::Vector { reg, .. }) = v.dst else {
- return Err("a 64-bit result");
- };
- let (lo, hi) = self.split64(r);
- self.write(inst, Reg::V(reg), lo, guard);
- self.write(inst, Reg::V(reg + 1), hi, guard);
- Ok(())
- }
- "v_cubeid_f32" | "v_cubesc_f32" | "v_cubetc_f32" | "v_cubema_f32" => {
- // Cube-map face coordinates (AMD's ISA): the major axis is z
- // when |z| >= |x| and |z| >= |y|, else y when |y| >= |x|,
- // else x.
- let (x, y, z) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
- let (ax, ay, az) = (self.unary(6, x), self.unary(6, y), self.unary(6, z));
- let zx = self.s.m.cmp(c, pred::OGE, az, ax);
- let zy = self.s.m.cmp(c, pred::OGE, az, ay);
- let zmaj = self.s.m.bin(c, Bin::And, zx, zy);
- let ymaj = self.s.m.cmp(c, pred::OGE, ay, ax);
- let zero = self.s.m.f32(0);
- let neg = |l: &mut Self, v: V| l.s.m.cmp(c, pred::OLT, v, zero);
- let minus = |l: &mut Self, v: V| {
- let z = l.s.m.f32(0x8000_0000);
- l.s.m.bin(c, Bin::Sub, z, v)
- };
- let pick = |l: &mut Self, zv: V, yv: V, xv: V| {
- let t = l.s.m.select(c, ymaj, yv, xv);
- l.s.m.select(c, zmaj, zv, t)
- };
- let r = match name {
- "v_cubeid_f32" => {
- let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits());
- let (nz, ny, nx) = (neg(self, z), neg(self, y), neg(self, x));
- let (f5, f4, f3, f2, f1, f0) = (
- k(self, 5.0),
- k(self, 4.0),
- k(self, 3.0),
- k(self, 2.0),
- k(self, 1.0),
- k(self, 0.0),
- );
- let zf = self.s.m.select(c, nz, f5, f4);
- let yf = self.s.m.select(c, ny, f3, f2);
- let xf = self.s.m.select(c, nx, f1, f0);
- pick(self, zf, yf, xf)
- }
- "v_cubesc_f32" => {
- let (nz, nx) = (neg(self, z), neg(self, x));
- let (mx, mz) = (minus(self, x), minus(self, z));
- let zf = self.s.m.select(c, nz, mx, x);
- let xf = self.s.m.select(c, nx, z, mz);
- pick(self, zf, x, xf)
- }
- "v_cubetc_f32" => {
- let ny = neg(self, y);
- let (my, mz) = (minus(self, y), minus(self, z));
- let yf = self.s.m.select(c, ny, mz, z);
- pick(self, my, yf, my)
- }
- _ => {
- let t = pick(self, z, y, x);
- let two = self.s.m.f32(2.0f32.to_bits());
- self.s.m.bin(c, Bin::Mul, t, two)
- }
- };
- float(self, r)
- }
- "v_movrels_b32" | "v_movreld_b32" | "v_movrelsd_b32" => {
- // M0 indexes the source (movrels), the destination (movreld)
- // or both, from the encoded register up to the program's
- // VGPR count (the registers the instruction reads or writes).
- let m0 = self.i32_of(inst.read(Reg::S(crate::ir::M0)).ok_or("M0")?)?;
- let (
- Some(&Operand::Vector { reg: sreg, .. }),
- Some(Operand::Vector { reg: dreg, .. }),
- ) = (v.src.first(), v.dst)
- else {
- return Err("an M0-relative move");
- };
- let indexed_src = name != "v_movreld_b32";
- let value = if indexed_src {
- let mut r = self.s.m.i32(0);
- for k in 0..=255u8.saturating_sub(sreg) {
- let Some(x) = inst.read(Reg::V(sreg + k)) else {
- break;
- };
- let x = self.i32_of(x)?;
- let kk = self.s.m.i32(u32::from(k));
- let is = self.s.m.cmp(c, pred::EQ, m0, kk);
- r = self.s.m.select(c, is, x, r);
- }
- r
- } else {
- s(self, 0)?
- };
- if name == "v_movrels_b32" {
- return int(self, value);
- }
- for k in 0..=255u8.saturating_sub(dreg) {
- let Some(_) = inst.write(Reg::V(dreg + k)) else {
- break;
- };
- let old = match inst.read(Reg::V(dreg + k)) {
- Some(o) => self.i32_of(o)?,
- None => self.s.m.i32(0),
- };
- let kk = self.s.m.i32(u32::from(k));
- let is = self.s.m.cmp(c, pred::EQ, m0, kk);
- let x = self.s.m.select(c, is, value, old);
- self.write_placed(inst, Reg::V(dreg + k), x, guard);
- }
- Ok(())
- }
- "v_swap_b32" => {
- let (
- Some(&Operand::Vector { reg: sreg, .. }),
- Some(Operand::Vector { reg: dreg, .. }),
- ) = (v.src.first(), v.dst)
- else {
- return Err("v_swap_b32");
- };
- let a = self.i32_of(inst.read(Reg::V(dreg)).ok_or("v_swap_b32")?)?;
- let b = self.i32_of(inst.read(Reg::V(sreg)).ok_or("v_swap_b32")?)?;
- self.write_placed(inst, Reg::V(dreg), b, guard);
- if dreg != sreg {
- self.write_placed(inst, Reg::V(sreg), a, guard);
- }
- Ok(())
- }
- "v_ffbh_u32" | "v_ffbh_i32" => {
- // Counted from the top bit, -1 when none (DXIL's too).
- let a = s(self, 0)?;
- let op = if name == "v_ffbh_u32" { 33 } else { 34 };
- let r = self
- .s
- .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
- int(self, r)
- }
- "v_dot4c_i32_i8" => {
- // D += the dot product of four signed bytes, wrapping: DXIL's
- // Dot4AddI8Packed.
- let (a, bb) = (s(self, 0)?, s(self, 1)?);
- let Some(Operand::Vector { reg, .. }) = v.dst else {
- return Err("an accumulator");
- };
- let acc = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?;
- let i32_ty = self.s.t.i32;
- let r = self.s.op(
- c,
- "dot4AddPacked.i32",
- Attr::ReadNone,
- i32_ty,
- 163,
- &[acc, a, bb],
- );
- int(self, r)
- }
- "v_dot4_i32_i8" => {
- // VOP3P: op_sel picks the half each multiplicand's low half
- // reads, op_sel_hi its high half's; the accumulator is read
- // whole (as AMD's compilers fold constants into it).
- if v.clamp || v.neg_hi != 0 {
- return Err("a saturating or negated dot product");
- }
- let mut xs = Vec::new();
- for k in 0..2 {
- let x = s(self, k)?;
- let (lo, hi) = (v.opsel >> k & 1 != 0, v.opsel_hi >> k & 1 != 0);
- if (lo, hi) == (false, true) {
- xs.push(x);
- continue;
- }
- let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
- let top = self.s.m.bin(c, Bin::LShr, x, k16);
- let bottom = self.s.m.bin(c, Bin::And, x, low);
- let hi = self
- .s
- .m
- .bin(c, Bin::Shl, if hi { top } else { bottom }, k16);
- xs.push(self.s.m.bin(c, Bin::Or, if lo { top } else { bottom }, hi));
- }
- let acc = s(self, 2)?;
- let i32_ty = self.s.t.i32;
- let r = self.s.op(
- c,
- "dot4AddPacked.i32",
- Attr::ReadNone,
- i32_ty,
- 163,
- &[acc, xs[0], xs[1]],
- );
- int(self, r)
- }
- "v_mov_b32" => {
- if v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 {
- let a = f(self, 0)?;
- return float(self, a);
- }
- let a = s(self, 0)?;
- int(self, a)
- }
- "v_add_f32" | "v_sub_f32" | "v_subrev_f32" | "v_mul_f32" | "v_mul_legacy_f32"
- | "v_max_f32" | "v_min_f32" => {
- let (a, bb) = (f(self, 0)?, f(self, 1)?);
- let r = match name {
- "v_add_f32" => self.s.m.bin(c, Bin::Add, a, bb),
- "v_sub_f32" => self.s.m.bin(c, Bin::Sub, a, bb),
- "v_subrev_f32" => self.s.m.bin(c, Bin::Sub, bb, a),
- "v_mul_f32" => self.s.m.bin(c, Bin::Mul, a, bb),
- "v_mul_legacy_f32" => self.legacy_mul(a, bb),
- "v_max_f32" => self.max_min(true, a, bb),
- _ => self.max_min(false, a, bb),
- };
- float(self, r)
- }
- "v_fma_f32" | "v_fmaak_f32" | "v_fmamk_f32" => {
- // shortcut: DXIL has no fused f32 multiply-add; FMad lets the driver fuse.
- let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
- let r = self.fmad(a, bb, cc);
- float(self, r)
- }
- "v_div_scale_f32" => {
- // RDNA2 ISA: src0 = value to scale, src1 = denominator, src2 = numerator.
- let (a, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
- let (ai, ni, di) = (self.as_int(a), self.as_int(num), self.as_int(den));
- let (k23, k255, kabs) = (
- self.s.m.i32(23),
- self.s.m.i32(0xFF),
- self.s.m.i32(0x7FFF_FFFF),
- );
- let (zero, k23_exp, k232_exp, k96) = (
- self.s.m.i32(0),
- self.s.m.i32(23),
- self.s.m.i32(232),
- self.s.m.i32(96),
- );
- let exp_of = |l: &mut Self, x: V| {
- let s = l.s.m.bin(c, Bin::LShr, x, k23);
- l.s.m.bin(c, Bin::And, s, k255)
- };
- let (e1, e2) = (exp_of(self, ni), exp_of(self, di));
- let n_abs = self.s.m.bin(c, Bin::And, ni, kabs);
- let d_abs = self.s.m.bin(c, Bin::And, di, kabs);
- let z1 = self.s.m.cmp(c, pred::EQ, n_abs, zero);
- let z2 = self.s.m.cmp(c, pred::EQ, d_abs, zero);
- let any_zero = self.s.m.bin(c, Bin::Or, z1, z2);
- let special = {
- let s1 = self.s.m.cmp(c, pred::EQ, e1, k255);
- let s2 = self.s.m.cmp(c, pred::EQ, e2, k255);
- let a12 = self.s.m.bin(c, Bin::Or, s1, s2);
- self.s.m.bin(c, Bin::Or, a12, any_zero)
- };
- let is_den = self.s.m.cmp(c, pred::EQ, ai, di);
- let diff = self.s.m.bin(c, Bin::Sub, e2, e1);
- let den_tiny = self.s.m.cmp(c, pred::IULE, e2, k23_exp);
- let den_huge = self.s.m.cmp(c, pred::IUGE, e2, k232_exp);
- let num_tiny_exp = self.s.m.cmp(c, pred::IULE, e1, k23_exp);
- let num_huge = self.s.m.cmp(c, pred::IUGE, e1, k232_exp);
- let num_gap = self.s.m.cmp(c, pred::SGE, diff, k96);
- let not_den_huge = {
- let t = self.s.m.bool(true);
- self.s.m.bin(c, Bin::Xor, den_huge, t)
- };
- let num_gap = self.s.m.bin(c, Bin::And, num_gap, not_den_huge);
- let num_tiny = self.s.m.bin(c, Bin::Or, num_tiny_exp, num_gap);
- let up_raw = self.s.m.select(c, is_den, den_tiny, num_tiny);
- let dn_raw = self.s.m.select(c, is_den, den_huge, num_huge);
- let not_special = {
- let t = self.s.m.bool(true);
- self.s.m.bin(c, Bin::Xor, special, t)
- };
- let up = self.s.m.bin(c, Bin::And, up_raw, not_special);
- let dn = self.s.m.bin(c, Bin::And, dn_raw, not_special);
- let uncancelled = {
- let x_tiny = self.s.m.bin(c, Bin::Xor, den_tiny, num_tiny);
- let x_huge = self.s.m.bin(c, Bin::Xor, den_huge, num_huge);
- self.s.m.bin(c, Bin::Or, x_tiny, x_huge)
- };
- let flag_raw = self.s.m.select(c, is_den, uncancelled, up_raw);
- let flag = self.s.m.bin(c, Bin::And, flag_raw, not_special);
- let k_up = self.s.m.f32(0x5F80_0000);
- let k_dn = self.s.m.f32(0x1F80_0000);
- let a_up = self.s.m.bin(c, Bin::Mul, a, k_up);
- let a_dn = self.s.m.bin(c, Bin::Mul, a, k_dn);
- let r = self.s.m.select(c, dn, a_dn, a);
- let r = self.s.m.select(c, up, a_up, r);
- let qnan = self.s.m.f32(0x7FC0_0000);
- let r = self.s.m.select(c, any_zero, qnan, r);
- float(self, r)?;
- if let Some(Operand::Scalar { code, .. }) = v.carry
- && let Some(w) = inst.write(Reg::S(code))
- {
- self.lane_bits.insert(w, flag);
- }
- for &(_, w) in &inst.writes {
- self.vals
- .entry(w)
- .or_insert(Val::Missing("a lane mask read as data"));
- }
- Ok(())
- }
- "v_div_fmas_f32" => {
- let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
- let m = inst
- .read(Reg::S(crate::ir::VCC))
- .and_then(|v| self.x.st.masks.get(&v).copied())
- .ok_or("v_div_fmas_f32 without VCC")?;
- let vcc = self.boolean(m, c)?;
- let tmp = self.fmad(a, bb, cc);
- let ci = self.as_int(cc);
- let (k23, k255, k128) = (self.s.m.i32(23), self.s.m.i32(0xFF), self.s.m.i32(128));
- let sh = self.s.m.bin(c, Bin::LShr, ci, k23);
- let exp = self.s.m.bin(c, Bin::And, sh, k255);
- let exp_ge = self.s.m.cmp(c, pred::IUGE, exp, k128);
- let (k_up, k_dn) = (self.s.m.f32(0x5F80_0000), self.s.m.f32(0x1F80_0000));
- let scale = self.s.m.select(c, exp_ge, k_up, k_dn);
- let scaled = self.s.m.bin(c, Bin::Mul, tmp, scale);
- let r = self.s.m.select(c, vcc, scaled, tmp);
- float(self, r)
- }
- "v_div_fixup_f32" => {
- let (q, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
- let (qi, di, ni) = (self.as_int(q), self.as_int(den), self.as_int(num));
- let (ksign, kabs, kinf) = (
- self.s.m.i32(0x8000_0000),
- self.s.m.i32(0x7FFF_FFFF),
- self.s.m.i32(0x7F80_0000),
- );
- let (kqnan_bit, kneg_qnan, zero) = (
- self.s.m.i32(0x0040_0000),
- self.s.m.i32(0xFFC0_0000),
- self.s.m.i32(0),
- );
- let sign = {
- let x = self.s.m.bin(c, Bin::Xor, ni, di);
- self.s.m.bin(c, Bin::And, x, ksign)
- };
- let q_abs = self.s.m.bin(c, Bin::And, qi, kabs);
- let d_abs = self.s.m.bin(c, Bin::And, di, kabs);
- let n_abs = self.s.m.bin(c, Bin::And, ni, kabs);
- let q_nan = self.s.m.cmp(c, pred::IUGT, q_abs, kinf);
- let d_nan = self.s.m.cmp(c, pred::IUGT, d_abs, kinf);
- let n_nan = self.s.m.cmp(c, pred::IUGT, n_abs, kinf);
- let d_inf = self.s.m.cmp(c, pred::EQ, d_abs, kinf);
- let n_inf = self.s.m.cmp(c, pred::EQ, n_abs, kinf);
- let d_zero = self.s.m.cmp(c, pred::EQ, d_abs, zero);
- let n_zero = self.s.m.cmp(c, pred::EQ, n_abs, zero);
- let both_inf = self.s.m.bin(c, Bin::And, n_inf, d_inf);
- let both_zero = self.s.m.bin(c, Bin::And, n_zero, d_zero);
- let invalid = self.s.m.bin(c, Bin::Or, both_inf, both_zero);
- let make_inf = {
- let t = self.s.m.bin(c, Bin::Or, n_inf, d_zero);
- self.s.m.bin(c, Bin::Or, t, q_nan)
- };
- let make_zero = self.s.m.bin(c, Bin::Or, d_inf, n_zero);
- let signed_q = self.s.m.bin(c, Bin::Or, sign, q_abs);
- let signed_inf = self.s.m.bin(c, Bin::Or, sign, kinf);
- let n_qnan = self.s.m.bin(c, Bin::Or, ni, kqnan_bit);
- let d_qnan = self.s.m.bin(c, Bin::Or, di, kqnan_bit);
- let r = self.s.m.select(c, make_zero, sign, signed_q);
- let r = self.s.m.select(c, make_inf, signed_inf, r);
- let r = self.s.m.select(c, invalid, kneg_qnan, r);
- let r = self.s.m.select(c, d_nan, d_qnan, r);
- let r = self.s.m.select(c, n_nan, n_qnan, r);
- let rf = self.as_float(r);
- float(self, rf)
- }
- "v_fmac_f32" | "v_mac_f32" | "v_mac_legacy_f32" => {
- let (a, bb) = (f(self, 0)?, f(self, 1)?);
- let Some(Operand::Vector { reg, .. }) = v.dst else {
- return Err("an accumulator");
- };
- let acc = inst.read(Reg::V(reg)).ok_or("an accumulator")?;
- let acc = match self.floats.get(&acc) {
- Some(&x) => x,
- None => {
- let x = self.i32_of(acc)?;
- self.as_float(x)
- }
- };
- let r = match name {
- "v_fmac_f32" => self.fmad(a, bb, acc),
- "v_mac_f32" => {
- let m = self.s.m.bin(c, Bin::Mul, a, bb);
- self.s.m.bin(c, Bin::Add, m, acc)
- }
- _ => {
- let m = self.legacy_mul(a, bb);
- self.s.m.bin(c, Bin::Add, m, acc)
- }
- };
- float(self, r)
- }
- "v_mad_f32" | "v_madak_f32" | "v_madmk_f32" | "v_mad_legacy_f32" => {
- let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
- let m = if name == "v_mad_legacy_f32" {
- self.legacy_mul(a, bb)
- } else {
- self.s.m.bin(c, Bin::Mul, a, bb)
- };
- let r = self.s.m.bin(c, Bin::Add, m, cc);
- float(self, r)
- }
- "v_max3_f32" | "v_min3_f32" | "v_med3_f32" => {
- let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?);
- let r = match name {
- "v_max3_f32" => {
- let t = self.max_min(true, a, bb);
- self.max_min(true, t, cc)
- }
- "v_min3_f32" => {
- let t = self.max_min(false, a, bb);
- self.max_min(false, t, cc)
- }
- _ => self.med3(a, bb, cc),
- };
- float(self, r)
- }
- "v_rcp_f32" | "v_rcp_iflag_f32" => {
- // shortcut: the hardware reciprocal is approximate (1 ULP); this divides.
- let a = f(self, 0)?;
- let one = self.s.m.f32(1.0f32.to_bits());
- let r = self.s.m.bin(c, Bin::SDiv, one, a);
- float(self, r)
- }
- "v_rsq_f32" | "v_sqrt_f32" | "v_log_f32" | "v_exp_f32" | "v_fract_f32"
- | "v_trunc_f32" | "v_floor_f32" | "v_ceil_f32" | "v_rndne_f32" | "v_sin_f32"
- | "v_cos_f32" => {
- let a = f(self, 0)?;
- let op = match name {
- "v_rsq_f32" => 25,
- "v_sqrt_f32" => 24,
- "v_log_f32" => 23,
- "v_exp_f32" => 21,
- "v_fract_f32" => 22,
- "v_trunc_f32" => 29,
- "v_floor_f32" => 27,
- "v_ceil_f32" => 28,
- "v_rndne_f32" => 26,
- "v_sin_f32" => 13,
- _ => 12,
- };
- let r = match op {
- 12 | 13 => self.trig_turns(a, op == 12),
- 22 => self.fract(a, 1.0, f32::from_bits(0x3F7F_FFFF)),
- _ => self.unary(op, a),
- };
- float(self, r)
- }
- "v_cvt_i32_f32" | "v_cvt_u32_f32" | "v_cvt_flr_i32_f32" | "v_cvt_rpi_i32_f32" => {
- let mut a = f(self, 0)?;
- if name == "v_cvt_rpi_i32_f32" {
- let h = self.s.m.f32(0.5f32.to_bits());
- a = self.s.m.bin(c, Bin::Add, a, h);
- }
- if name != "v_cvt_i32_f32" && name != "v_cvt_u32_f32" {
- a = self.unary(27, a);
- }
- // D3D's conversions saturate and give 0 for NaN, as the
- // hardware does (checked on the RX 6700 XT and WARP).
- let op = if name == "v_cvt_u32_f32" {
- Cast::FpToUi
- } else {
- Cast::FpToSi
- };
- let r = self.s.m.cast(c, op, a, self.s.t.i32);
- int(self, r)
- }
- "v_cvt_f32_f64" => {
- let (lo, hi) = self.f64_pair(inst, 0)?;
- let bits = self.f64_to_f32_bits(lo, hi);
- let r = self.as_float(bits);
- float(self, r)
- }
- "v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1"
- | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => {
- let mut a = s(self, 0)?;
- if let Some(n) = name.strip_prefix("v_cvt_f32_ubyte") {
- let sh = self.s.m.i32(8 * u32::from(n.as_bytes()[0] - b'0'));
- let ff = self.s.m.i32(0xff);
- a = self.s.m.bin(c, Bin::LShr, a, sh);
- a = self.s.m.bin(c, Bin::And, a, ff);
- }
- let op = if name == "v_cvt_f32_i32" {
- Cast::SiToFp
- } else {
- Cast::UiToFp
- };
- let r = self.s.m.cast(c, op, a, self.s.t.f32);
- float(self, r)
- }
- "v_cvt_off_f32_i4" => {
- // The low nibble as a signed 4-bit integer, over 16.
- let a = s(self, 0)?;
- let k28 = self.s.m.i32(28);
- let a = self.s.m.bin(c, Bin::Shl, a, k28);
- let a = self.s.m.bin(c, Bin::AShr, a, k28);
- let f = self.s.m.cast(c, Cast::SiToFp, a, self.s.t.f32);
- let k = self.s.m.f32(0.0625f32.to_bits());
- let r = self.s.m.bin(c, Bin::Mul, f, k);
- float(self, r)
- }
- "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => {
- // Each source is f32, or with op_sel_hi the low (op_sel: high)
- // f16 half; neg_hi is the absolute value here.
- let mut xs = Vec::new();
- for i in 0..3 {
- let op = v.src.get(i).ok_or("a missing operand")?;
- let mut x = if v.opsel_hi >> i & 1 != 0 {
- let x = self.f16_operand(inst, op)?;
- let h = if v.opsel >> i & 1 != 0 {
- let k16 = self.s.m.i32(16);
- self.s.m.bin(c, Bin::LShr, x, k16)
- } else {
- x
- };
- self.s
- .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h])
- } else {
- let x = self.operand(inst, op)?;
- self.as_float(x)
- };
- if v.neg_hi >> i & 1 != 0 {
- x = self.unary(6, x);
- }
- if v.neg >> i & 1 != 0 {
- let z = self.s.m.f32(0x8000_0000);
- x = self.s.m.bin(c, Bin::Sub, z, x);
- }
- xs.push(x);
- }
- let mut r = self.fmad(xs[0], xs[1], xs[2]);
- if name == "v_fma_mix_f32" {
- return float(self, r);
- }
- if v.clamp {
- r = self.unary(7, r);
- }
- // The f16 result goes to one half; the other half stays.
- let Some(Operand::Vector { reg, .. }) = v.dst else {
- return Err("a mixed-precision result");
- };
- let old = match inst.read(Reg::V(reg)) {
- Some(o) => self.i32_of(o)?,
- None => self.s.m.i32(0),
- };
- let h = self
- .s
- .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[r]);
- let (keep, h) = if name == "v_fma_mixhi_f16" {
- let k16 = self.s.m.i32(16);
- (0xFFFF, self.s.m.bin(c, Bin::Shl, h, k16))
- } else {
- (0xFFFF_0000, h)
- };
- let keep = self.s.m.i32(keep);
- let old = self.s.m.bin(c, Bin::And, old, keep);
- let x = self.s.m.bin(c, Bin::Or, old, h);
- self.write(inst, Reg::V(reg), x, guard);
- Ok(())
- }
- "v_cvt_pkrtz_f16_f32" => {
- let (a, bb) = (f(self, 0)?, f(self, 1)?);
- let lo = self.f16_toward_zero(a);
- let hi = self.f16_toward_zero(bb);
- let sh = self.s.m.i32(16);
- let hi = self.s.m.bin(c, Bin::Shl, hi, sh);
- let r = self.s.m.bin(c, Bin::Or, lo, hi);
- int(self, r)
- }
- "v_cvt_f16_f32" if v.opsel == 0 => {
- // Rounded to nearest even (the MODE default) into the low half.
- let a = f(self, 0)?;
- let r = self
- .s
- .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[a]);
- let Some(Operand::Vector { reg, .. }) = v.dst else {
- return Err("a 16-bit result outside a VGPR");
- };
- let r = self.low_half(inst, reg, r);
- int(self, r)
- }
- "v_pack_b32_f16" => {
- // Two f16 sources (op_sel: their high halves; abs and neg on
- // the sign bit) into the low and high half.
- let mut halves = Vec::new();
- for k in 0..2 {
- let op = v.src.get(k).ok_or("a missing operand")?;
- let mut x = self.f16_operand(inst, op)?;
- if v.opsel >> k & 1 != 0 {
- let k16 = self.s.m.i32(16);
- x = self.s.m.bin(c, Bin::LShr, x, k16);
- }
- let mask = if v.abs >> k & 1 != 0 { 0x7FFF } else { 0xFFFF };
- let mask = self.s.m.i32(mask);
- x = self.s.m.bin(c, Bin::And, x, mask);
- if v.neg >> k & 1 != 0 {
- let sign = self.s.m.i32(0x8000);
- x = self.s.m.bin(c, Bin::Xor, x, sign);
- }
- halves.push(x);
- }
- let k16 = self.s.m.i32(16);
- let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16);
- let r = self.s.m.bin(c, Bin::Or, halves[0], hi);
- int(self, r)
- }
- "v_cvt_f32_f16" if v.opsel == 0 => {
- let a = s(self, 0)?;
- let r = self
- .s
- .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[a]);
- float(self, r)
- }
- "v_cndmask_b32" => {
- let mask = match v.src.get(2) {
- Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
- _ => None,
- };
- const UNTRACKED: Why = "a select on an untracked mask";
- let cond = match mask.and_then(|m| self.x.st.masks.get(&m).copied()) {
- Some(m) => self.boolean(m, c)?,
- // A mask the code holds as a number (a constant bit
- // pattern: every other lane, every other pair...):
- // this lane's bit of it. Exact where host lanes are
- // the console's.
- None if self.mask_data == MaskData::Console => {
- // Each host wave taken as a wave of its own has no
- // console lane numbers to pick the bits by.
- if self.local {
- return Err("a constant lane mask in a half-wave");
- }
- let m = mask.ok_or(UNTRACKED)?;
- let lo = self.i32_of(m).map_err(|_| UNTRACKED)?;
- // wave64: the register after it holds lanes 32-63.
- let high = match v.src.get(2) {
- Some(&Operand::Scalar { code, .. }) if self.x.native.wave64 => {
- Some(inst.read(Reg::S(code + 1)).ok_or(UNTRACKED)?)
- }
- _ => None,
- };
- let hi = match high {
- Some(h) => Some(self.i32_of(h).map_err(|_| UNTRACKED)?),
- None => None,
- };
- self.cross_lane(false)?;
- self.lane_bit(c, lo, hi)
- }
- None => return Err(UNTRACKED),
- };
- if v.abs != 0 || v.neg != 0 {
- let (a, bb) = (f(self, 0)?, f(self, 1)?);
- let r = self.s.m.select(c, cond, bb, a);
- return float(self, r);
- }
- let (a, bb) = (s(self, 0)?, s(self, 1)?);
- let r = self.s.m.select(c, cond, bb, a);
- int(self, r)
- }
- "v_add_co_u32" | "v_sub_co_u32" | "v_subrev_co_u32" | "v_add_co_ci_u32"
- | "v_sub_co_ci_u32" | "v_subrev_co_ci_u32" => {
- // The carry (borrow) out is a lane mask: this lane's bit.
- let (mut a, mut bb) = (s(self, 0)?, s(self, 1)?);
- if name.contains("subrev") {
- std::mem::swap(&mut a, &mut bb);
- }
- let cin = if name.ends_with("_ci_u32") {
- let m = match v.src.get(2) {
- Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
- _ => None,
- };
- let m = m
- .and_then(|m| self.x.st.masks.get(&m).copied())
- .ok_or("a carry-in from an untracked mask")?;
- Some(self.boolean(m, c)?)
- } else {
- None
- };
- let (r, carry) = self.add_sub_carry(c, name.starts_with("v_add"), a, bb, cin);
- int(self, r)?;
- if let Some(Operand::Scalar { code, .. }) = v.carry
- && let Some(w) = inst.write(Reg::S(code))
- {
- self.lane_bits.insert(w, carry);
- }
- for &(_, w) in &inst.writes {
- self.vals
- .entry(w)
- .or_insert(Val::Missing("a lane mask read as data"));
- }
- Ok(())
- }
- "v_permlane16_b32" | "v_permlanex16_b32" => {
- // RDNA2 ISA 12.12: each nibble of {src2, src1} selects a lane
- // in this row of 16, or the other row of the same 32-lane half.
- // OP_SEL[0:1] are fetch-inactive and bound-control, not half selects.
- if v.abs != 0 || v.neg != 0 || v.opsel & !3 != 0 {
- return Err("permlane input modifiers");
- }
- self.cross_lane(false)?;
- let fetch_inactive = v.opsel & 1 != 0;
- if fetch_inactive
- && !all_lane_blocks(self.x.st).is_some_and(|all| all[self.cur_ir])
- {
- // DXIL cannot read the last VGPR value of a host invocation
- // that has left through a lane branch. A guard keeps it here.
- return Err("a permlane fetch from lanes outside the host branch");
- }
- let (x, lo, hi) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
- let lane = self.lane_index();
- let (k7, k8, k15, k16, k31, k32, k4, one, zero) = (
- self.s.m.i32(7),
- self.s.m.i32(8),
- self.s.m.i32(15),
- self.s.m.i32(16),
- self.s.m.i32(31),
- self.s.m.i32(32),
- self.s.m.i32(4),
- self.s.m.i32(1),
- self.s.m.i32(0),
- );
- let pos = self.s.m.bin(c, Bin::And, lane, k15);
- let lower = self.s.m.cmp(c, pred::IULT, pos, k8);
- let packed = self.s.m.select(c, lower, lo, hi);
- let shift = self.s.m.bin(c, Bin::And, pos, k7);
- let shift = self.s.m.bin(c, Bin::Mul, shift, k4);
- let pick = self.s.m.bin(c, Bin::LShr, packed, shift);
- let pick = self.s.m.bin(c, Bin::And, pick, k15);
- let not15 = self.s.m.i32(!15);
- let mut row = self.s.m.bin(c, Bin::And, lane, not15);
- if name == "v_permlanex16_b32" {
- row = self.s.m.bin(c, Bin::Xor, row, k16);
- }
- let src = self.s.m.bin(c, Bin::Or, row, pick);
- let r = if fetch_inactive {
- self.read_lane(x, src)
- } else {
- // Ballot the console EXEC guard as well as the host's active
- // invocations. Never shuffle from an inactive host lane.
- let enabled = guard.unwrap_or_else(|| self.s.m.bool(true));
- let i32t = self.s.t.i32;
- let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
- let mask = self.s.op(
- c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[enabled],
- );
- let lo = self.s.m.extract(c, mask, 0);
- let hi = self.s.m.extract(c, mask, 1);
- let lower = self.s.m.cmp(c, pred::IULT, src, k32);
- let word = self.s.m.select(c, lower, lo, hi);
- let bit = self.s.m.bin(c, Bin::And, src, k31);
- let bit = self.s.m.bin(c, Bin::LShr, word, bit);
- let bit = self.s.m.bin(c, Bin::And, bit, one);
- let active = self.s.m.cmp(c, pred::NE, bit, zero);
- let safe = self.s.m.select(c, active, src, lane);
- let read = self.read_lane(x, safe);
- let fallback = if v.opsel & 2 != 0 {
- zero
- } else {
- let Some(Operand::Vector { reg, .. }) = v.dst else {
- return Err("a permlane result outside a VGPR");
- };
- self.i32_of(inst.read(Reg::V(reg)).ok_or("a permlane old value")?)?
- };
- self.s.m.select(c, active, read, fallback)
- };
- int(self, r)
- }
- "v_readlane_b32" => {
- let (a, lane) = (s(self, 0)?, s(self, 1)?);
- // A computed lane in a pixel or vertex program is a host lane
- // (from a mask or `v_mbcnt`); a constant one is the console's.
- if self.mask_data == MaskData::Host && !matches!(lane, V::Const(_)) {
- self.s.flags |= flags::WAVE_OPS;
- } else {
- self.cross_lane(false)?;
- }
- if let Some(slot) = self.exchange.as_ref().map(|e| e.0) {
- if self.local && self.local_any {
- // this host wave's lane of that number (lanes 32..63 are 0..31 here)
- let k31 = self.s.m.i32(31);
- let here = self.s.m.bin(self.cur, Bin::And, lane, k31);
- let r = self.read_lane(a, here);
- return int(self, r);
- }
- if self.local {
- return Err("a lane read in a half-wave");
- }
- if self.exchange.as_ref().is_some_and(|e| e.1) {
- // a group of 32 or fewer: the lane is in this host wave
- let r = self.read_lane(a, lane);
- return int(self, r);
- }
- // the lane that holds it may be in the other host wave: it gives it through LDS
- if !self.all_lanes(self.cur_ir) {
- need(self.cur_ir);
- return Err("a lane read where not every lane runs");
- }
- let cl = self.console_lane();
- let is = self.s.m.cmp(self.cur, pred::EQ, cl, lane);
- let k = self.exchange_pair(slot);
- let at = self.begin_guarded(Some(is));
- let lds = self.s.lds();
- let ptr = self.s.m.element(self.cur, lds, k);
- self.s.m.store(self.cur, ptr, a);
- self.end_guarded(at, &[]);
- let c2 = self.cur;
- self.group_sync(c2);
- let ptr = self.s.m.element(c2, lds, k);
- let r = self.s.m.load(c2, ptr);
- self.group_sync(c2);
- return int(self, r);
- }
- let r = self.read_lane(a, lane);
- int(self, r)
- }
- "v_writelane_b32" => {
- // The lane given takes the scalar; the others keep their value.
- let (a, lane) = (s(self, 0)?, s(self, 1)?);
- let Some(Operand::Vector { reg, .. }) = v.dst else {
- return Err("a lane write");
- };
- let old = match inst.read(Reg::V(reg)) {
- Some(o) => self.i32_of(o)?,
- None => self.s.m.i32(0),
- };
- self.cross_lane(false)?;
- if self.local && !self.local_any {
- return Err("a lane write in a half-wave");
- }
- let me = self.console_lane();
- let is = self.s.m.cmp(c, pred::EQ, me, lane);
- let r = self.s.m.select(c, is, a, old);
- int(self, r)
- }
- "v_readfirstlane_b32"
- if inst
- .writes
- .first()
- .is_some_and(|w| self.x.res.waterfall.reads.contains(&w.1)) =>
- {
- // A waterfall loop's read of a descriptor dword: the lane's own.
- let a = s(self, 0)?;
- int(self, a)
- }
- "v_readfirstlane_b32"
- if matches!(v.src.first(), Some(&Operand::Vector { reg, .. })
- if inst.read(Reg::V(reg)).is_some_and(|x| self.own_bits.alike.contains(&x))) =>
- {
- // The bits a loop over a wave OR has still to visit (`own_bits`): every lane of
- // the host wave holds the same, so the first lane's is the lane's own.
- let a = s(self, 0)?;
- int(self, a)
- }
- "v_readfirstlane_b32" => {
- let a = s(self, 0)?;
- let (mine, any) = self.first_lane(a, guard);
- // two host waves that exchange: the console's first lane may be in the other
- // one, unless every lane holds the same value
- let alike = match v.src.first() {
- Some(&Operand::Vector { reg, .. }) => {
- inst.read(Reg::V(reg)).is_some_and(|x| self.uniform.contains(&x))
- }
- _ => true,
- };
- let halves = self.exchange.as_ref().is_some_and(|e| !e.1) && !self.local;
- let r = if halves && !alike {
- if !self.all_lanes(self.cur_ir) {
- // shortcut: `VICTORY_FIRSTLANE_OWN=1` takes the host wave's own
- // first lane, exact when the value is the same in every lane of
- // the console wave (the ray-tracing builder's scans read a sum of
- // scalars this way, inside a loop whose exit is per console wave).
- static OWN: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
- if *OWN.get_or_init(|| std::env::var_os("VICTORY_FIRSTLANE_OWN").is_some_and(|v| v == "1")) {
- return int(self, mine);
- }
- need(self.cur_ir);
- return Err("a first-lane read where not every lane runs");
- }
- let c = self.cur;
- if guard.is_none() && super::shader_opt() & super::bitcode::opt::FIRST != 0 {
- // Every lane is in EXEC: the console's first lane is
- // lane 0, which the lower half of every console wave
- // has. No half needs to ask the other whether it has
- // a lane (an exchange of the constant 1: two group
- // barriers), and the lower half's value is the answer.
- let (lo, _) = self.exchange_halves(c, mine);
- lo
- } else {
- let i32t = self.s.t.i32;
- let has = self.s.m.cast(c, Cast::ZExt, any, i32t);
- let (lo_has, hi_has) = self.exchange_halves(c, has);
- let (lo, hi) = self.exchange_halves(c, mine);
- let z = self.s.m.i32(0);
- let in_lo = self.s.m.cmp(c, pred::NE, lo_has, z);
- let in_hi = self.s.m.cmp(c, pred::NE, hi_has, z);
- // neither half has a lane in EXEC: the console reads lane 0
- let hi = self.s.m.select(c, in_hi, hi, lo);
- self.s.m.select(c, in_lo, lo, hi)
- }
- } else {
- mine
- };
- int(self, r)
- }
- _ => {
- let r = self.integer(inst, name)?;
- int(self, r)
- }
- }
- }
- /// A 64-bit source (a register pair; inline constants sign-extend).
- fn src64(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 || v.sdwa.is_some() || v.dpp.is_some() {
- return Err("64-bit operand modifiers");
- }
- let c = self.cur;
- let i64t = self.s.m.int(64);
- self.s.flags |= flags::INT64;
- let op = *v.src.get(k).ok_or("a missing operand")?;
- let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<V, Why> {
- let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?;
- let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?;
- Ok(l.join64(lo, hi))
- };
- match op {
- Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1)),
- Operand::Scalar { code, .. } if code != NULL => {
- pair(self, Reg::S(code), Reg::S(code + 1))
- }
- Operand::Const(k @ 128..=208) => {
- let x = crate::resource::inline(k).ok_or("a special operand")?;
- Ok(self.s.m.int_const(i64t, i64::from(x as i32)))
- }
- // A signed 64-bit operand sign-extends its 32-bit literal, as
- // the hardware does (LLVM's AMDGPU operand rules).
- Operand::Literal(x) if inst.name().ends_with("_i64") => {
- Ok(self.s.m.int_const(i64t, i64::from(x as i32)))
- }
- _ => {
- // Literals (of unsigned and bit operands) and the null
- // register: zero-extended.
- let x = self.operand(inst, &op)?;
- Ok(self.s.m.cast(c, Cast::ZExt, x, i64t))
- }
- }
- }
- /// Reads an IEEE-754 binary64 operand as `(lo, hi)` 32-bit words, applying
- /// `abs` and `neg` input modifiers on operand `k`.
- fn f64_pair(&mut self, inst: &Inst, k: usize) -> Result<(V, V), Why> {
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- if v.sdwa.is_some() || v.dpp.is_some() {
- return Err("64-bit operand modifiers");
- }
- let op = *v.src.get(k).ok_or("a missing operand")?;
- let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<(V, V), Why> {
- let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?;
- let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?;
- Ok((lo, hi))
- };
- let (lo, mut hi) = match op {
- Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1))?,
- Operand::Scalar { code, .. } if code != NULL => {
- pair(self, Reg::S(code), Reg::S(code + 1))?
- }
- Operand::Const(128) => (self.s.m.i32(0), self.s.m.i32(0)),
- Operand::Const(c @ 240..=248) => {
- const INLINE_F64: [f64; 9] = [
- 0.5,
- -0.5,
- 1.0,
- -1.0,
- 2.0,
- -2.0,
- 4.0,
- -4.0,
- 1.0 / std::f64::consts::TAU,
- ];
- let bits = INLINE_F64[(c - 240) as usize].to_bits();
- (self.s.m.i32(bits as u32), self.s.m.i32((bits >> 32) as u32))
- }
- // GFX10 places a 32-bit literal in the high 32 bits of a 64-bit float operand.
- Operand::Literal(x) => (self.s.m.i32(0), self.s.m.i32(x)),
- _ => return Err("a 64-bit float operand"),
- };
- let c = self.cur;
- if v.abs >> k & 1 != 0 {
- let mask = self.s.m.i32(0x7FFF_FFFF);
- hi = self.s.m.bin(c, Bin::And, hi, mask);
- }
- if v.neg >> k & 1 != 0 {
- let sign = self.s.m.i32(0x8000_0000);
- hi = self.s.m.bin(c, Bin::Xor, hi, sign);
- }
- Ok((lo, hi))
- }
- /// Converts IEEE-754 binary64 `(lo, hi)` to binary32 bits with round-to-nearest-even,
- /// without requiring host `DOUBLES` (`f64`) support.
- fn f64_to_f32_bits(&mut self, lo: V, hi: V) -> V {
- let c = self.cur;
- let k0 = self.s.m.i32(0);
- let k1 = self.s.m.i32(1);
- let sign_mask = self.s.m.i32(0x8000_0000);
- let sign = self.s.m.bin(c, Bin::And, hi, sign_mask);
- let k20 = self.s.m.i32(20);
- let k7ff = self.s.m.i32(0x7FF);
- let exp64 = self.s.m.bin(c, Bin::LShr, hi, k20);
- let exp64 = self.s.m.bin(c, Bin::And, exp64, k7ff);
- let frac_mask = self.s.m.i32(0x000F_FFFF);
- let frac_hi = self.s.m.bin(c, Bin::And, hi, frac_mask);
- let frac_any = self.s.m.bin(c, Bin::Or, frac_hi, lo);
- let frac_nz = self.s.m.cmp(c, pred::NE, frac_any, k0);
- let k3 = self.s.m.i32(3);
- let k29 = self.s.m.i32(29);
- let m23_hi = self.s.m.bin(c, Bin::Shl, frac_hi, k3);
- let m23_lo = self.s.m.bin(c, Bin::LShr, lo, k29);
- let m23 = self.s.m.bin(c, Bin::Or, m23_hi, m23_lo);
- let rem_mask = self.s.m.i32(0x1FFF_FFFF);
- let rem = self.s.m.bin(c, Bin::And, lo, rem_mask);
- let half_rem = self.s.m.i32(0x1000_0000);
- let gt_half = self.s.m.cmp(c, pred::IUGT, rem, half_rem);
- let eq_half = self.s.m.cmp(c, pred::EQ, rem, half_rem);
- let m23_odd_bit = self.s.m.bin(c, Bin::And, m23, k1);
- let m23_odd = self.s.m.cmp(c, pred::NE, m23_odd_bit, k0);
- let tie_up = self.s.m.bin(c, Bin::And, eq_half, m23_odd);
- let norm_round = self.s.m.bin(c, Bin::Or, gt_half, tie_up);
- let norm_inc = self.s.m.select(c, norm_round, k1, k0);
- // Normal range: exp64 in [897, 1150] -> exp32 in [1, 254].
- let k896 = self.s.m.i32(896);
- let k23 = self.s.m.i32(23);
- let exp32 = self.s.m.bin(c, Bin::Sub, exp64, k896);
- let exp32_sh = self.s.m.bin(c, Bin::Shl, exp32, k23);
- let norm_body = self.s.m.bin(c, Bin::Add, exp32_sh, m23);
- let norm_body = self.s.m.bin(c, Bin::Add, norm_body, norm_inc);
- let norm_res = self.s.m.bin(c, Bin::Or, sign, norm_body);
- // Subnormal range: exp64 in [874, 896] -> shift in [1, 23].
- let k897 = self.s.m.i32(897);
- let k32 = self.s.m.i32(32);
- let k31 = self.s.m.i32(31);
- let imp = self.s.m.i32(0x0080_0000);
- let sig24 = self.s.m.bin(c, Bin::Or, imp, m23);
- let raw_shift = self.s.m.bin(c, Bin::Sub, k897, exp64);
- // Clamp shift to [1, 23] so shifts never produce poison outside the subnormal branch.
- let lt1 = self.s.m.cmp(c, pred::IULT, raw_shift, k1);
- let shift = self.s.m.select(c, lt1, k1, raw_shift);
- let gt23 = self.s.m.cmp(c, pred::IUGT, shift, k23);
- let shift = self.s.m.select(c, gt23, k23, shift);
- let sub_m = self.s.m.bin(c, Bin::LShr, sig24, shift);
- let inv_shift = self.s.m.bin(c, Bin::Sub, k32, shift);
- let lost = self.s.m.bin(c, Bin::Shl, sig24, inv_shift);
- let round_bit = self.s.m.bin(c, Bin::LShr, lost, k31);
- let round_on = self.s.m.cmp(c, pred::NE, round_bit, k0);
- let low31 = self.s.m.i32(0x7FFF_FFFF);
- let lost_lo = self.s.m.bin(c, Bin::And, lost, low31);
- let sticky = self.s.m.bin(c, Bin::Or, lost_lo, rem);
- let sticky_on = self.s.m.cmp(c, pred::NE, sticky, k0);
- let sub_odd_bit = self.s.m.bin(c, Bin::And, sub_m, k1);
- let sub_odd = self.s.m.cmp(c, pred::NE, sub_odd_bit, k0);
- let sub_tie = self.s.m.bin(c, Bin::Or, sticky_on, sub_odd);
- let sub_round = self.s.m.bin(c, Bin::And, round_on, sub_tie);
- let sub_inc = self.s.m.select(c, sub_round, k1, k0);
- let sub_body = self.s.m.bin(c, Bin::Add, sub_m, sub_inc);
- let sub_res = self.s.m.bin(c, Bin::Or, sign, sub_body);
- // Underflow range: exp64 < 874. Only exp64 == 873 with non-zero fraction rounds up to min subnormal (1).
- let k873 = self.s.m.i32(873);
- let eq873 = self.s.m.cmp(c, pred::EQ, exp64, k873);
- let round_min = self.s.m.bin(c, Bin::And, eq873, frac_nz);
- let min_bit = self.s.m.select(c, round_min, k1, k0);
- let under_res = self.s.m.bin(c, Bin::Or, sign, min_bit);
- // Overflow / Inf / NaN: exp64 >= 1151.
- let is_exp_all = self.s.m.cmp(c, pred::EQ, exp64, k7ff);
- let is_nan = self.s.m.bin(c, Bin::And, is_exp_all, frac_nz);
- let inf_bits = self.s.m.i32(0x7F80_0000);
- let qnan_bits = self.s.m.i32(0x7FC0_0000);
- let nan_body = self.s.m.bin(c, Bin::Or, qnan_bits, m23);
- let over_body = self.s.m.select(c, is_nan, nan_body, inf_bits);
- let over_res = self.s.m.bin(c, Bin::Or, sign, over_body);
- // Select final result by exponent range.
- let k874 = self.s.m.i32(874);
- let k1151 = self.s.m.i32(1151);
- let is_under = self.s.m.cmp(c, pred::IULT, exp64, k874);
- let is_sub = self.s.m.cmp(c, pred::IULT, exp64, k897);
- let is_over = self.s.m.cmp(c, pred::IUGE, exp64, k1151);
- let r = self.s.m.select(c, is_over, over_res, norm_res);
- let r = self.s.m.select(c, is_sub, sub_res, r);
- self.s.m.select(c, is_under, under_res, r)
- }
- fn join64(&mut self, lo: V, hi: V) -> V {
- let c = self.cur;
- let ty = self.s.m.int(64);
- let lo = self.s.m.cast(c, Cast::ZExt, lo, ty);
- let hi = self.s.m.cast(c, Cast::ZExt, hi, ty);
- let shift = self.s.m.int_const(ty, 32);
- let hi = self.s.m.bin(c, Bin::Shl, hi, shift);
- self.s.m.bin(c, Bin::Or, lo, hi)
- }
- /// The bits of the float nearest the double whose dwords are `lo` and
- /// `hi`, on 32-bit integers: round to nearest even, infinities and NaN
- /// kept (a NaN stays quiet), a result below the smallest normal float
- /// signed zero (flushed, as the console's default float mode does).
- // The flush-to-zero form of v_cvt_f32_f64: kept beside the IEEE form in use until the console's
- // float mode for this instruction is checked.
- #[allow(dead_code)]
- fn f64_bits_to_f32_bits(&mut self, lo: V, hi: V) -> V {
- let c = self.cur;
- let k = |l: &mut Self, x: u32| l.s.m.i32(x);
- let (k20, k29, k3, k23) = (k(self, 20), k(self, 29), k(self, 3), k(self, 23));
- let sign_mask = k(self, 0x8000_0000);
- let sign = self.s.m.bin(c, Bin::And, hi, sign_mask);
- let e = self.s.m.bin(c, Bin::LShr, hi, k20);
- let e_mask = k(self, 0x7ff);
- let e = self.s.m.bin(c, Bin::And, e, e_mask);
- // The top 23 bits of the 52-bit mantissa, and the 29 below them.
- let m_mask = k(self, 0x000f_ffff);
- let mh = self.s.m.bin(c, Bin::And, hi, m_mask);
- let mh = self.s.m.bin(c, Bin::Shl, mh, k3);
- let ml = self.s.m.bin(c, Bin::LShr, lo, k29);
- let m = self.s.m.bin(c, Bin::Or, mh, ml);
- let rest_mask = k(self, 0x1fff_ffff);
- let rest = self.s.m.bin(c, Bin::And, lo, rest_mask);
- // Round to nearest even: up past half, or at half when odd.
- let half = k(self, 0x1000_0000);
- let one = k(self, 1);
- let above = self.s.m.cmp(c, pred::IUGT, rest, half);
- let at = self.s.m.cmp(c, pred::EQ, rest, half);
- let odd = self.s.m.bin(c, Bin::And, m, one);
- let zero = k(self, 0);
- let odd = self.s.m.cmp(c, pred::NE, odd, zero);
- let tie = self.s.m.bin(c, Bin::And, at, odd);
- let up = self.s.m.bin(c, Bin::Or, above, tie);
- let up = self.s.m.select(c, up, one, zero);
- // Rebias the exponent (1023 → 127); a carry out of the mantissa
- // steps the exponent, up to infinity.
- let bias = k(self, 1023 - 127);
- let e32 = self.s.m.bin(c, Bin::Sub, e, bias);
- let ex = self.s.m.bin(c, Bin::Shl, e32, k23);
- let normal = self.s.m.bin(c, Bin::Add, ex, m);
- let normal = self.s.m.bin(c, Bin::Add, normal, up);
- let normal = self.s.m.bin(c, Bin::Or, normal, sign);
- // Exponents out of the float's range (signed, after rebiasing).
- let inf = k(self, 0x7f80_0000);
- let inf = self.s.m.bin(c, Bin::Or, inf, sign);
- let k255 = k(self, 255);
- let big = self.s.m.cmp(c, pred::SGE, e32, k255);
- let small = self.s.m.cmp(c, pred::SLE, e32, zero);
- let r = self.s.m.select(c, big, inf, normal);
- let r = self.s.m.select(c, small, sign, r);
- // Infinity and NaN (a NaN with any mantissa bit set stays a NaN).
- let all = k(self, 0x7ff);
- let special = self.s.m.cmp(c, pred::EQ, e, all);
- let any = self.s.m.bin(c, Bin::Or, mh, ml);
- let any = self.s.m.bin(c, Bin::Or, any, rest);
- let nan = self.s.m.cmp(c, pred::NE, any, zero);
- let quiet = k(self, 0x0040_0000);
- let quiet = self.s.m.select(c, nan, quiet, zero);
- let special_bits = self.s.m.bin(c, Bin::Or, inf, quiet);
- self.s.m.select(c, special, special_bits, r)
- }
- /// The low and high dwords of an i64.
- fn split64(&mut self, x: V) -> (V, V) {
- let c = self.cur;
- let i64t = self.s.m.int(64);
- let k32 = self.s.m.int_const(i64t, 32);
- let lo = self.s.m.cast(c, Cast::Trunc, x, self.s.t.i32);
- let hi = self.s.m.bin(c, Bin::LShr, x, k32);
- let hi = self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32);
- (lo, hi)
- }
- /// Source `k` of a 16-bit operation in the low 16 bits (the rest 0):
- /// op_sel (or an SDWA word select) picks the high half; inline float
- /// constants are f16 values here.
- fn half_src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- let op = *v.src.get(k).ok_or("a missing operand")?;
- let mut high = v.opsel >> k & 1 != 0;
- if let Some(sd) = v.sdwa {
- match sd.src_sel.get(k).copied().unwrap_or(6) {
- 4 => {}
- 5 => high = true,
- 6 => {}
- _ => return Err("a byte select on a 16-bit operation"),
- }
- }
- let x = match self.src0 {
- Some(x) if k == 0 => x,
- _ => self.f16_operand(inst, &op)?,
- };
- let c = self.cur;
- let x = if high {
- let k16 = self.s.m.i32(16);
- self.s.m.bin(c, Bin::LShr, x, k16)
- } else {
- x
- };
- let m = self.s.m.i32(0xFFFF);
- Ok(self.s.m.bin(c, Bin::And, x, m))
- }
- /// An f16 source as an f32 (exact), with its abs/neg modifiers.
- fn half_fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> {
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- let h = self.half_src(inst, k)?;
- let f32t = self.s.t.f32;
- let mut f = self
- .s
- .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
- if v.abs >> k & 1 != 0 {
- f = self.unary(6, f);
- }
- if v.neg >> k & 1 != 0 {
- let z = self.s.m.f32(0x8000_0000);
- f = self.s.m.bin(self.cur, Bin::Sub, z, f);
- }
- Ok(f)
- }
- /// Writes a 16-bit result (low bits of `x`) into the destination's low
- /// half, or its high half with op_sel bit 3 (or an SDWA WORD_1 select);
- /// the other half is kept (GFX10).
- fn write_half(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> {
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- let Some(Operand::Vector { reg, .. }) = v.dst else {
- return Err("a 16-bit result outside a VGPR");
- };
- let mut high = v.opsel >> 3 & 1 != 0;
- // SDWA: the word written, the other one kept (preserve) or zero
- // (pad; a sign extension above the high word adds nothing).
- let mut keep = true;
- if let Some(sd) = v.sdwa {
- match (sd.dst_sel, sd.dst_unused) {
- (4, 2) => {}
- (5, 2) => high = true,
- (4 | 6, _) => keep = false,
- (5, _) => (high, keep) = (true, false),
- _ => return Err("an SDWA destination of a 16-bit operation"),
- }
- }
- let c = self.cur;
- let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) {
- Some(Ok(o)) if keep => o,
- _ => self.s.m.i32(0),
- };
- let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
- let x = self.s.m.bin(c, Bin::And, x, low);
- let r = if high {
- let o = self.s.m.bin(c, Bin::And, old, low);
- let x = self.s.m.bin(c, Bin::Shl, x, k16);
- self.s.m.bin(c, Bin::Or, o, x)
- } else {
- let keep = self.s.m.i32(0xFFFF_0000);
- let o = self.s.m.bin(c, Bin::And, old, keep);
- self.s.m.bin(c, Bin::Or, o, x)
- };
- self.write_placed(inst, Reg::V(reg), r, guard);
- Ok(())
- }
- /// 16-bit operations, computed in f32 or i32: f16 sums, differences and
- /// products are exact there and round once to f16 (f32 has the 2 x 11 +
- /// 2 bits that make double rounding harmless); `None` if `name` is none.
- fn valu16(&mut self, inst: &Inst, name: &str, guard: Option<V>) -> Option<Result<(), Why>> {
- const FLOAT2: &[&str] = &[
- "v_add_f16",
- "v_sub_f16",
- "v_subrev_f16",
- "v_mul_f16",
- "v_max_f16",
- "v_min_f16",
- ];
- const FLOAT3: &[&str] = &[
- "v_fma_f16",
- "v_mad_f16",
- "v_fmac_f16",
- "v_mac_f16",
- "v_max3_f16",
- "v_min3_f16",
- "v_med3_f16",
- ];
- const FLOAT1: &[&str] = &[
- "v_rcp_f16",
- "v_sqrt_f16",
- "v_rsq_f16",
- "v_log_f16",
- "v_exp_f16",
- "v_fract_f16",
- "v_trunc_f16",
- "v_floor_f16",
- "v_ceil_f16",
- "v_rndne_f16",
- "v_sin_f16",
- "v_cos_f16",
- "v_cvt_f16_u16",
- "v_cvt_f16_i16",
- ];
- const INT: &[&str] = &[
- "v_add_nc_u16",
- "v_sub_nc_u16",
- "v_subrev_nc_u16",
- "v_mul_lo_u16",
- "v_lshlrev_b16",
- "v_lshrrev_b16",
- "v_ashrrev_i16",
- "v_max_u16",
- "v_max_i16",
- "v_min_u16",
- "v_min_i16",
- "v_cvt_u16_f16",
- "v_cvt_i16_f16",
- "v_cvt_norm_i16_f16",
- "v_cvt_norm_u16_f16",
- ];
- let all = [FLOAT1, FLOAT2, FLOAT3, INT];
- if !all.iter().any(|l| l.contains(&name))
- && !matches!(name, "v_cvt_f16_f32" | "v_cvt_f32_f16")
- {
- return None;
- }
- Some(self.valu16_op(inst, name, guard, FLOAT1, FLOAT2, FLOAT3))
- }
- #[allow(clippy::too_many_arguments)]
- fn valu16_op(
- &mut self,
- inst: &Inst,
- name: &str,
- guard: Option<V>,
- float1: &[&str],
- float2: &[&str],
- float3: &[&str],
- ) -> Result<(), Why> {
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- let c = self.cur;
- let i32t = self.s.t.i32;
- let f32t = self.s.t.f32;
- if name == "v_cvt_f32_f16" {
- let f = self.half_fsrc(inst, 0)?;
- return self.write_f(inst, f, guard);
- }
- let float_result = |l: &mut Self, mut f: V| -> Result<(), Why> {
- match v.omod {
- 0 => {}
- k => {
- let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)];
- let k = l.s.m.f32(factor.to_bits());
- f = l.s.m.bin(l.cur, Bin::Mul, f, k);
- }
- }
- if v.clamp {
- f = l.unary(7, f);
- }
- // The console rounds to nearest; the host's conversion may round toward zero
- // (NVIDIA's does), one step of the last place lower where the two differ.
- // shortcut: the host's conversion unless `VICTORY_F16_NEAREST=1`
- // ([`f16_nearest_on`]), which costs a dozen instructions per result.
- let h = if f16_nearest_on() {
- l.f16_nearest(f)
- } else {
- l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
- };
- l.write_half(inst, h, guard)
- };
- if name == "v_cvt_f16_f32" {
- let f = self.fsrc(inst, 0)?;
- return float_result(self, f);
- }
- if float2.contains(&name) {
- let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?);
- let r = match name {
- "v_add_f16" => self.s.m.bin(c, Bin::Add, a, b),
- "v_sub_f16" => self.s.m.bin(c, Bin::Sub, a, b),
- "v_subrev_f16" => self.s.m.bin(c, Bin::Sub, b, a),
- "v_mul_f16" => self.s.m.bin(c, Bin::Mul, a, b),
- "v_max_f16" => self.max_min(true, a, b),
- _ => self.max_min(false, a, b),
- };
- return float_result(self, r);
- }
- if float3.contains(&name) {
- let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?);
- let acc = if matches!(name, "v_fmac_f16" | "v_mac_f16") {
- // The accumulator is the destination's half that is written.
- let Some(Operand::Vector { reg, .. }) = v.dst else {
- return Err("an accumulator");
- };
- let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?;
- let x = if v.opsel >> 3 & 1 != 0 {
- let k16 = self.s.m.i32(16);
- self.s.m.bin(c, Bin::LShr, x, k16)
- } else {
- x
- };
- let m = self.s.m.i32(0xFFFF);
- let x = self.s.m.bin(c, Bin::And, x, m);
- self.s
- .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x])
- } else {
- self.half_fsrc(inst, 2)?
- };
- let r = match name {
- // shortcut: fused f16 multiply-adds as FMad in f32 (the
- // product is exact; the sum rounds twice).
- "v_fma_f16" | "v_fmac_f16" | "v_mad_f16" | "v_mac_f16" => self.fmad(a, b, acc),
- "v_max3_f16" => {
- let t = self.max_min(true, a, b);
- self.max_min(true, t, acc)
- }
- "v_min3_f16" => {
- let t = self.max_min(false, a, b);
- self.max_min(false, t, acc)
- }
- _ => self.med3(a, b, acc),
- };
- return float_result(self, r);
- }
- if float1.contains(&name) {
- let r = match name {
- "v_cvt_f16_u16" | "v_cvt_f16_i16" => {
- let mut x = self.half_src(inst, 0)?;
- let op = if name == "v_cvt_f16_i16" {
- let k16 = self.s.m.i32(16);
- let t = self.s.m.bin(c, Bin::Shl, x, k16);
- x = self.s.m.bin(c, Bin::AShr, t, k16);
- Cast::SiToFp
- } else {
- Cast::UiToFp
- };
- self.s.m.cast(c, op, x, f32t)
- }
- "v_rcp_f16" => {
- let a = self.half_fsrc(inst, 0)?;
- let one = self.s.m.f32(1.0f32.to_bits());
- self.s.m.bin(c, Bin::SDiv, one, a)
- }
- _ => {
- let a = self.half_fsrc(inst, 0)?;
- let op = match name {
- "v_sqrt_f16" => 24,
- "v_rsq_f16" => 25,
- "v_log_f16" => 23,
- "v_exp_f16" => 21,
- "v_fract_f16" => 22,
- "v_trunc_f16" => 29,
- "v_floor_f16" => 27,
- "v_ceil_f16" => 28,
- "v_rndne_f16" => 26,
- "v_sin_f16" => 13,
- _ => 12,
- };
- match op {
- 12 | 13 => self.trig_turns(a, op == 12),
- // Any f16 in (-2^-11, 0) has fract >= 1 - 2^-12; clamp to 0x3bff (1 - 2^-11).
- 22 => self.fract(a, 1.0 - 1.0 / 4096.0, 1.0 - 1.0 / 2048.0),
- _ => self.unary(op, a),
- }
- }
- };
- return float_result(self, r);
- }
- if matches!(name, "v_cvt_u16_f16" | "v_cvt_i16_f16") {
- if v.clamp || v.omod != 0 {
- return Err("modifiers on a 16-bit integer operation");
- }
- // Toward zero, saturating at the 16-bit range (infinities
- // included); NaN gives 0. Clamped in f32 first, where every
- // f16 is exact, so the conversion never leaves i32's range
- // (upstream PR #384's arithmetic; the source's abs and neg
- // modifiers are applied by `half_fsrc`, as before).
- let a = self.half_fsrc(inst, 0)?;
- let (lo, hi) = if name == "v_cvt_u16_f16" {
- (0.0f32, 65535.0f32)
- } else {
- (-32768.0, 32767.0)
- };
- let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits()));
- let t = self.binary(35, a, lo);
- let t = self.binary(36, t, hi);
- let r = self.s.m.cast(c, Cast::FpToSi, t, i32t);
- let nan = self.s.m.cmp(c, pred::UNO, a, a);
- let z = self.s.m.i32(0);
- let r = self.s.m.select(c, nan, z, r);
- return self.write_half(inst, r, guard);
- }
- if matches!(name, "v_cvt_norm_i16_f16" | "v_cvt_norm_u16_f16") {
- if v.clamp || v.omod != 0 {
- return Err("modifiers on a 16-bit integer operation");
- }
- let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?;
- return self.write_half(inst, r, guard);
- }
- // 16-bit integers: computed on the low halves, the low 16 bits kept.
- if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 {
- return Err("modifiers on a 16-bit integer operation");
- }
- let r = {
- let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
- let k16 = self.s.m.i32(16);
- let sext = |l: &mut Self, x: V| {
- let t = l.s.m.bin(c, Bin::Shl, x, k16);
- l.s.m.bin(c, Bin::AShr, t, k16)
- };
- if name.ends_with("_i16") {
- a = sext(self, a);
- b = sext(self, b);
- }
- let k15 = self.s.m.i32(15);
- match name {
- "v_add_nc_u16" => self.s.m.bin(c, Bin::Add, a, b),
- "v_sub_nc_u16" => self.s.m.bin(c, Bin::Sub, a, b),
- "v_subrev_nc_u16" => self.s.m.bin(c, Bin::Sub, b, a),
- "v_mul_lo_u16" => self.s.m.bin(c, Bin::Mul, a, b),
- "v_lshlrev_b16" | "v_lshrrev_b16" | "v_ashrrev_i16" => {
- // src0 is the shift (4 bits), src1 the value.
- let sh = self.s.m.bin(c, Bin::And, a, k15);
- let x = if name == "v_ashrrev_i16" {
- sext(self, b)
- } else {
- b
- };
- let op = match name {
- "v_lshlrev_b16" => Bin::Shl,
- "v_lshrrev_b16" => Bin::LShr,
- _ => Bin::AShr,
- };
- self.s.m.bin(c, op, x, sh)
- }
- _ => {
- let p = match name {
- "v_max_u16" => pred::IUGT,
- "v_min_u16" => pred::IULT,
- "v_max_i16" => pred::SGT,
- _ => pred::SLT,
- };
- let t = self.s.m.cmp(c, p, a, b);
- self.s.m.select(c, t, a, b)
- }
- }
- };
- self.write_half(inst, r, guard)
- }
- /// `v_cvt_norm_i16_f16` / `v_cvt_norm_u16_f16`: the f16 source (with its
- /// abs/neg modifiers) clamped to [-1, 1] or [0, 1], times 32767 or 65535,
- /// rounded to nearest even once from the exact product; NaN gives 0.
- /// Worked on the f16's bits in integers, because in f32 the product
- /// (up to 26 significant bits) would round before the rounding to an
- /// integer.
- fn cvt_norm16(&mut self, inst: &Inst, signed: bool) -> Result<V, Why> {
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- let c = self.cur;
- let k = |l: &mut Self, x: u32| l.s.m.i32(x);
- let mut h = self.half_src(inst, 0)?;
- if v.abs & 1 != 0 {
- let m = k(self, 0x7FFF);
- h = self.s.m.bin(c, Bin::And, h, m);
- }
- if v.neg & 1 != 0 {
- let m = k(self, 0x8000);
- h = self.s.m.bin(c, Bin::Xor, h, m);
- }
- let scale = if signed { 0x7FFF } else { 0xFFFF };
- let (k0, k1, k10) = (k(self, 0), k(self, 1), k(self, 10));
- let mag_mask = k(self, 0x7FFF);
- let mag = self.s.m.bin(c, Bin::And, h, mag_mask);
- let k15 = k(self, 15);
- let neg = self.s.m.bin(c, Bin::LShr, h, k15);
- let neg = self.s.m.cmp(c, pred::NE, neg, k0);
- // |x| < 1: x = m * 2^-s with m < 2^11 and 11 <= s <= 24.
- let exp = self.s.m.bin(c, Bin::LShr, mag, k10);
- let man_mask = k(self, 0x3FF);
- let man = self.s.m.bin(c, Bin::And, mag, man_mask);
- let implicit = k(self, 0x400);
- let normal = self.s.m.bin(c, Bin::Or, man, implicit);
- let sub = self.s.m.cmp(c, pred::EQ, exp, k0);
- let m = self.s.m.select(c, sub, man, normal);
- let k25 = k(self, 25);
- let s_norm = self.s.m.bin(c, Bin::Sub, k25, exp);
- let k24 = k(self, 24);
- let sh = self.s.m.select(c, sub, k24, s_norm);
- let ks = k(self, scale);
- let p = self.s.m.bin(c, Bin::Mul, m, ks);
- let q = self.s.m.bin(c, Bin::LShr, p, sh);
- let one_s = self.s.m.bin(c, Bin::Shl, k1, sh);
- let low_mask = self.s.m.bin(c, Bin::Sub, one_s, k1);
- let rem = self.s.m.bin(c, Bin::And, p, low_mask);
- let half = self.s.m.bin(c, Bin::LShr, one_s, k1);
- let above = self.s.m.cmp(c, pred::IUGT, rem, half);
- let tie = self.s.m.cmp(c, pred::EQ, rem, half);
- let odd = self.s.m.bin(c, Bin::And, q, k1);
- let odd = self.s.m.cmp(c, pred::NE, odd, k0);
- let tie_up = self.s.m.bin(c, Bin::And, tie, odd);
- let up = self.s.m.bin(c, Bin::Or, above, tie_up);
- let r = self.s.m.select(c, up, k1, k0);
- let r = self.s.m.bin(c, Bin::Add, q, r);
- // |x| >= 1 (and infinity) saturates; NaN gives 0.
- let one_h = k(self, 0x3C00);
- let big = self.s.m.cmp(c, pred::IUGE, mag, one_h);
- let r = self.s.m.select(c, big, ks, r);
- let inf = k(self, 0x7C00);
- let nan = self.s.m.cmp(c, pred::IUGT, mag, inf);
- let r = self.s.m.select(c, nan, k0, r);
- let r = if signed {
- let n = self.s.m.bin(c, Bin::Sub, k0, r);
- self.s.m.select(c, neg, n, r)
- } else {
- self.s.m.select(c, neg, k0, r)
- };
- let m16 = k(self, 0xFFFF);
- Ok(self.s.m.bin(c, Bin::And, r, m16))
- }
- /// Half `high` of source `k` of a packed (VOP3P) operation, in the low
- /// 16 bits: op_sel picks the half the low result reads, op_sel_hi the
- /// half the high result reads. Packed integer instructions see the f32
- /// bits of an inline float constant.
- fn packed_src(&mut self, inst: &Inst, k: usize, high: bool, float: bool) -> Result<V, Why> {
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- let op = *v.src.get(k).ok_or("a missing operand")?;
- let sel = if high { v.opsel_hi } else { v.opsel } >> k & 1 != 0;
- let x = if float {
- self.f16_operand(inst, &op)?
- } else {
- self.operand(inst, &op)?
- };
- let c = self.cur;
- let x = if sel {
- let k16 = self.s.m.i32(16);
- self.s.m.bin(c, Bin::LShr, x, k16)
- } else {
- x
- };
- let m = self.s.m.i32(0xFFFF);
- Ok(self.s.m.bin(c, Bin::And, x, m))
- }
- /// Half `high` of source `k` of `v_pk_fmac_f16`, in the low 16 bits: a
- /// VOP2 operation (no op_sel) whose third source is its destination.
- fn fmac_half(&mut self, inst: &Inst, k: usize, high: bool) -> Result<V, Why> {
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- let op = if k == 2 { v.dst } else { v.src.get(k).copied() };
- let op = op.ok_or("a missing operand")?;
- if matches!(op, Operand::Const(_) | Operand::Literal(_)) {
- // shortcut: no constant operand seen; its high half is not known.
- return Err("a constant operand of v_pk_fmac_f16");
- }
- let x = self.operand(inst, &op)?;
- let c = self.cur;
- let x = if high {
- let k16 = self.s.m.i32(16);
- self.s.m.bin(c, Bin::LShr, x, k16)
- } else {
- x
- };
- let m = self.s.m.i32(0xFFFF);
- Ok(self.s.m.bin(c, Bin::And, x, m))
- }
- /// Packed 16-bit operations (`v_pk_*`): each half computed as the
- /// 16-bit operation does, f16 through f32 as in [`Self::valu16`].
- fn packed16(&mut self, inst: &Inst, op: &str, guard: Option<V>) -> Result<(), Why> {
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- let float = op.ends_with("_f16");
- let n = match op {
- "fma_f16" | "fmac_f16" | "mad_u16" | "mad_i16" => 3,
- "add_f16" | "mul_f16" | "min_f16" | "max_f16" | "add_u16" | "sub_u16" | "add_i16"
- | "sub_i16" | "mul_lo_u16" | "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16"
- | "max_u16" | "min_u16" | "max_i16" | "min_i16" => 2,
- _ => return Err("a packed 16-bit operation"),
- };
- if v.omod != 0 || !float && (v.clamp || v.neg != 0 || v.neg_hi != 0) {
- return Err("modifiers on a packed integer operation");
- }
- let c = self.cur;
- let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
- let mut halves = Vec::new();
- for high in [false, true] {
- let mut xs = Vec::new();
- for k in 0..n {
- let h = if op == "fmac_f16" {
- self.fmac_half(inst, k, high)?
- } else {
- self.packed_src(inst, k, high, float)?
- };
- if float {
- let mut f = self
- .s
- .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
- let neg = if high { v.neg_hi } else { v.neg };
- if neg >> k & 1 != 0 {
- let z = self.s.m.f32(0x8000_0000);
- f = self.s.m.bin(c, Bin::Sub, z, f);
- }
- xs.push(f);
- } else {
- xs.push(h);
- }
- }
- let r = if float {
- let mut f = match op {
- "add_f16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
- "mul_f16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
- "min_f16" => self.max_min(false, xs[0], xs[1]),
- "max_f16" => self.max_min(true, xs[0], xs[1]),
- // shortcut: FMad in f32, as v_fma_f16.
- _ => self.fmad(xs[0], xs[1], xs[2]),
- };
- if v.clamp {
- f = self.unary(7, f);
- }
- self.s
- .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
- } else {
- let k16 = self.s.m.i32(16);
- let sext = |l: &mut Self, x: V| {
- let t = l.s.m.bin(c, Bin::Shl, x, k16);
- l.s.m.bin(c, Bin::AShr, t, k16)
- };
- if op.ends_with("_i16") {
- for x in &mut xs {
- *x = sext(self, *x);
- }
- }
- let k15 = self.s.m.i32(15);
- match op {
- "add_u16" | "add_i16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]),
- "sub_u16" | "sub_i16" => self.s.m.bin(c, Bin::Sub, xs[0], xs[1]),
- "mul_lo_u16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]),
- "mad_u16" | "mad_i16" => {
- let m = self.s.m.bin(c, Bin::Mul, xs[0], xs[1]);
- self.s.m.bin(c, Bin::Add, m, xs[2])
- }
- "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16" => {
- let sh = self.s.m.bin(c, Bin::And, xs[0], k15);
- let o = match op {
- "lshlrev_b16" => Bin::Shl,
- "lshrrev_b16" => Bin::LShr,
- _ => Bin::AShr,
- };
- let x = if op == "ashrrev_i16" {
- sext(self, xs[1])
- } else {
- xs[1]
- };
- self.s.m.bin(c, o, x, sh)
- }
- _ => {
- let p = match op {
- "max_u16" => pred::IUGT,
- "min_u16" => pred::IULT,
- "max_i16" => pred::SGT,
- _ => pred::SLT,
- };
- let t = self.s.m.cmp(c, p, xs[0], xs[1]);
- self.s.m.select(c, t, xs[0], xs[1])
- }
- }
- };
- let m = self.s.m.i32(0xFFFF);
- halves.push(self.s.m.bin(c, Bin::And, r, m));
- }
- let k16 = self.s.m.i32(16);
- let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16);
- let r = self.s.m.bin(c, Bin::Or, halves[0], hi);
- let Some(Operand::Vector { reg, .. }) = v.dst else {
- return Err("a packed result outside a VGPR");
- };
- self.write(inst, Reg::V(reg), r, guard);
- Ok(())
- }
- fn integer(&mut self, inst: &Inst, name: &'static str) -> Result<V, Why> {
- let c = self.cur;
- let s = |l: &mut Self, k| l.src(inst, k);
- let k = |l: &mut Self, x: u32| l.s.m.i32(x);
- let m31 = |l: &mut Self, x: V| {
- let k31 = l.s.m.i32(31);
- l.s.m.bin(c, Bin::And, x, k31)
- };
- Ok(match name {
- "v_and_b32" | "v_or_b32" | "v_xor_b32" | "v_add_nc_u32" | "v_sub_nc_u32"
- | "v_subrev_nc_u32" | "v_mul_lo_u32" => {
- let (a, b) = (s(self, 0)?, s(self, 1)?);
- let (op, a, b) = match name {
- "v_and_b32" => (Bin::And, a, b),
- "v_or_b32" => (Bin::Or, a, b),
- "v_xor_b32" => (Bin::Xor, a, b),
- "v_add_nc_u32" => (Bin::Add, a, b),
- "v_sub_nc_u32" => (Bin::Sub, a, b),
- "v_subrev_nc_u32" => (Bin::Sub, b, a),
- _ => (Bin::Mul, a, b),
- };
- self.s.m.bin(c, op, a, b)
- }
- "v_xnor_b32" => {
- let (a, b) = (s(self, 0)?, s(self, 1)?);
- let x = self.s.m.bin(c, Bin::Xor, a, b);
- let ones = k(self, u32::MAX);
- self.s.m.bin(c, Bin::Xor, x, ones)
- }
- "v_not_b32" => {
- let a = s(self, 0)?;
- let ones = k(self, u32::MAX);
- self.s.m.bin(c, Bin::Xor, a, ones)
- }
- "v_lshlrev_b32" | "v_lshrrev_b32" | "v_ashrrev_i32" => {
- let (sh, a) = (s(self, 0)?, s(self, 1)?);
- let sh = m31(self, sh);
- let op = match name {
- "v_lshlrev_b32" => Bin::Shl,
- "v_lshrrev_b32" => Bin::LShr,
- _ => Bin::AShr,
- };
- self.s.m.bin(c, op, a, sh)
- }
- "v_lshl_add_u32" | "v_lshl_or_b32" | "v_add_lshl_u32" | "v_and_or_b32"
- | "v_or3_b32" | "v_xad_u32" | "v_add3_u32" | "v_xor3_b32" => {
- let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
- match name {
- "v_lshl_add_u32" | "v_lshl_or_b32" => {
- let b = m31(self, b);
- let t = self.s.m.bin(c, Bin::Shl, a, b);
- let op = if name == "v_lshl_add_u32" {
- Bin::Add
- } else {
- Bin::Or
- };
- self.s.m.bin(c, op, t, d)
- }
- "v_add_lshl_u32" => {
- let t = self.s.m.bin(c, Bin::Add, a, b);
- let d = m31(self, d);
- self.s.m.bin(c, Bin::Shl, t, d)
- }
- _ => {
- let (o1, o2) = match name {
- "v_and_or_b32" => (Bin::And, Bin::Or),
- "v_or3_b32" => (Bin::Or, Bin::Or),
- "v_xad_u32" => (Bin::Xor, Bin::Add),
- "v_add3_u32" => (Bin::Add, Bin::Add),
- _ => (Bin::Xor, Bin::Xor),
- };
- let t = self.s.m.bin(c, o1, a, b);
- self.s.m.bin(c, o2, t, d)
- }
- }
- }
- "v_mul_u32_u24" | "v_mul_i32_i24" => {
- let (a, b) = (s(self, 0)?, s(self, 1)?);
- let (sh, op) = (
- k(self, 8),
- if name == "v_mul_i32_i24" {
- Bin::AShr
- } else {
- Bin::LShr
- },
- );
- let a = self.s.m.bin(c, Bin::Shl, a, sh);
- let a = self.s.m.bin(c, op, a, sh);
- let b = self.s.m.bin(c, Bin::Shl, b, sh);
- let b = self.s.m.bin(c, op, b, sh);
- self.s.m.bin(c, Bin::Mul, a, b)
- }
- "v_mul_hi_u32_u24" | "v_mul_hi_i32_i24" => {
- // The high dword of the same 48-bit product: the low 24 bits
- // of each operand, zero- or sign-extended, multiplied.
- let (a, b) = (s(self, 0)?, s(self, 1)?);
- let signed = name == "v_mul_hi_i32_i24";
- let (sh, op) = (k(self, 8), if signed { Bin::AShr } else { Bin::LShr });
- let a = self.s.m.bin(c, Bin::Shl, a, sh);
- let a = self.s.m.bin(c, op, a, sh);
- let b = self.s.m.bin(c, Bin::Shl, b, sh);
- let b = self.s.m.bin(c, op, b, sh);
- self.mul_hi(a, b, signed)
- }
- "v_bfe_u32" | "v_bfe_i32" => {
- let (a, off, w) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
- let w = m31(self, w);
- self.bfe(a, off, w, name == "v_bfe_i32")
- }
- "v_bfi_b32" => {
- let (m, a, b) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
- let ones = k(self, u32::MAX);
- let nm = self.s.m.bin(c, Bin::Xor, m, ones);
- let x = self.s.m.bin(c, Bin::And, m, a);
- let y = self.s.m.bin(c, Bin::And, nm, b);
- self.s.m.bin(c, Bin::Or, x, y)
- }
- "v_max_i32" | "v_min_i32" | "v_max_u32" | "v_min_u32" => {
- let (a, b) = (s(self, 0)?, s(self, 1)?);
- let p = match name {
- "v_max_i32" => pred::SGT,
- "v_min_i32" => pred::SLT,
- "v_max_u32" => pred::IUGT,
- _ => pred::IULT,
- };
- let t = self.s.m.cmp(c, p, a, b);
- self.s.m.select(c, t, a, b)
- }
- "v_mul_hi_u32" | "v_mul_hi_i32" => {
- let (a, b) = (s(self, 0)?, s(self, 1)?);
- self.mul_hi(a, b, name == "v_mul_hi_i32")
- }
- "v_alignbit_b32" | "v_alignbyte_b32" => {
- // The low dword of {a, b} >> shift.
- let (a, b, sh) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
- let sh = if name == "v_alignbyte_b32" {
- let three = k(self, 3);
- let t = self.s.m.bin(c, Bin::And, sh, three);
- let k3 = k(self, 3);
- self.s.m.bin(c, Bin::Shl, t, k3)
- } else {
- m31(self, sh)
- };
- let k32 = k(self, 32);
- let lo = self.s.m.bin(c, Bin::LShr, b, sh);
- let left = self.s.m.bin(c, Bin::Sub, k32, sh);
- let left = m31(self, left);
- let hi = self.s.m.bin(c, Bin::Shl, a, left);
- let zero = k(self, 0);
- let none = self.s.m.cmp(c, pred::EQ, sh, zero);
- let hi = self.s.m.select(c, none, zero, hi);
- self.s.m.bin(c, Bin::Or, lo, hi)
- }
- "v_bfrev_b32" => {
- let a = s(self, 0)?;
- self.s
- .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a])
- }
- "v_bcnt_u32_b32" => {
- let (a, b) = (s(self, 0)?, s(self, 1)?);
- let n = self
- .s
- .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[a]);
- self.s.m.bin(c, Bin::Add, n, b)
- }
- "v_mad_u32_u24" | "v_mad_i32_i24" => {
- let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
- let (sh, op) = (
- k(self, 8),
- if name == "v_mad_i32_i24" {
- Bin::AShr
- } else {
- Bin::LShr
- },
- );
- let a = self.s.m.bin(c, Bin::Shl, a, sh);
- let a = self.s.m.bin(c, op, a, sh);
- let b = self.s.m.bin(c, Bin::Shl, b, sh);
- let b = self.s.m.bin(c, op, b, sh);
- let m = self.s.m.bin(c, Bin::Mul, a, b);
- self.s.m.bin(c, Bin::Add, m, d)
- }
- "v_sad_u8" | "v_sad_hi_u8" | "v_sad_u16" | "v_sad_u32" | "v_msad_u8" => {
- // src2 plus the sum of the unsigned differences |a - b| of
- // the operands' bytes, halves or whole dwords, wrapping at 32
- // bits. v_sad_hi_u8 adds the sum shifted to the high half;
- // v_msad_u8 leaves out a byte whose mask byte (src1) is 0.
- let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
- let (width, parts) = match name {
- "v_sad_u16" => (16, 2),
- "v_sad_u32" => (32, 1),
- _ => (8, 4),
- };
- let zero = k(self, 0);
- let mut sum = zero;
- for i in 0..parts {
- let (mut x, mut y) = (a, b);
- if width < 32 {
- let (sh, mask) = (k(self, width * i), k(self, (1 << width) - 1));
- x = self.s.m.bin(c, Bin::LShr, x, sh);
- x = self.s.m.bin(c, Bin::And, x, mask);
- y = self.s.m.bin(c, Bin::LShr, y, sh);
- y = self.s.m.bin(c, Bin::And, y, mask);
- }
- let above = self.s.m.cmp(c, pred::IUGT, x, y);
- let hi = self.s.m.select(c, above, x, y);
- let lo = self.s.m.select(c, above, y, x);
- let mut diff = self.s.m.bin(c, Bin::Sub, hi, lo);
- if name == "v_msad_u8" {
- let masked = self.s.m.cmp(c, pred::NE, y, zero);
- diff = self.s.m.select(c, masked, diff, zero);
- }
- sum = self.s.m.bin(c, Bin::Add, sum, diff);
- }
- if name == "v_sad_hi_u8" {
- let k16 = k(self, 16);
- sum = self.s.m.bin(c, Bin::Shl, sum, k16);
- }
- self.s.m.bin(c, Bin::Add, sum, d)
- }
- "v_min3_i32" | "v_max3_i32" | "v_min3_u32" | "v_max3_u32" | "v_med3_i32"
- | "v_med3_u32" => {
- let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
- let signed = name.ends_with("i32");
- let (lt, gt) = if signed {
- (pred::SLT, pred::SGT)
- } else {
- (pred::IULT, pred::IUGT)
- };
- let pick = |l: &mut Self, p, x, y| {
- let t = l.s.m.cmp(c, p, x, y);
- l.s.m.select(c, t, x, y)
- };
- match &name[2..6] {
- "min3" => {
- let t = pick(self, lt, a, b);
- pick(self, lt, t, d)
- }
- "max3" => {
- let t = pick(self, gt, a, b);
- pick(self, gt, t, d)
- }
- _ => {
- let lo = pick(self, lt, a, b);
- let hi = pick(self, gt, a, b);
- let t = pick(self, lt, hi, d);
- pick(self, gt, lo, t)
- }
- }
- }
- "v_perm_b32" => {
- // Byte i of the result is byte S of {src0, src1} (src1 the
- // low dword) for selector byte S below 8; 8-11 repeat the
- // sign of bytes 1 and 3 of src1, then of src0; 12 is 0x00,
- // higher 0xFF.
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- let sel = match v.src.get(2) {
- Some(&Operand::Literal(x)) => x,
- Some(&Operand::Const(k)) => crate::resource::inline(k).ok_or(name)?,
- _ => {
- // A computed selector: each byte picked at run time.
- let (a, b, sv) = (s(self, 0)?, s(self, 1)?, s(self, 2)?);
- let mut r = k(self, 0);
- for i in 0..4u32 {
- let (sh, ff) = (k(self, 8 * i), k(self, 0xFF));
- let sel = self.s.m.bin(c, Bin::LShr, sv, sh);
- let sel = self.s.m.bin(c, Bin::And, sel, ff);
- // Select a dword and a byte within it.
- // Later selects handle codes 8 and above.
- let four = k(self, 4);
- let zero = k(self, 0);
- let high = self.s.m.bin(c, Bin::And, sel, four);
- let high = self.s.m.cmp(c, pred::NE, high, zero);
- let word = self.s.m.select(c, high, a, b);
- let three = k(self, 3);
- let index = self.s.m.bin(c, Bin::And, sel, three);
- let bits = self.s.m.bin(c, Bin::Shl, index, three);
- let x = self.s.m.bin(c, Bin::LShr, word, bits);
- let mut byte = self.s.m.bin(c, Bin::And, x, ff);
- // 8-11: the sign of bytes 1, 3 of src1, then of src0.
- for (n, src, bit) in [(8, b, 15), (9, b, 31), (10, a, 15), (11, a, 31)]
- {
- let left = k(self, 31 - bit);
- let t = self.s.m.bin(c, Bin::Shl, src, left);
- let k31 = k(self, 31);
- let t = self.s.m.bin(c, Bin::AShr, t, k31);
- let t = self.s.m.bin(c, Bin::And, t, ff);
- let kn = k(self, n);
- let is = self.s.m.cmp(c, pred::EQ, sel, kn);
- byte = self.s.m.select(c, is, t, byte);
- }
- let (k12, z) = (k(self, 12), k(self, 0));
- let is12 = self.s.m.cmp(c, pred::EQ, sel, k12);
- byte = self.s.m.select(c, is12, z, byte);
- let above = self.s.m.cmp(c, pred::IUGT, sel, k12);
- byte = self.s.m.select(c, above, ff, byte);
- let at = k(self, 8 * i);
- let byte = self.s.m.bin(c, Bin::Shl, byte, at);
- r = self.s.m.bin(c, Bin::Or, r, byte);
- }
- return Ok(r);
- }
- };
- let (a, b) = (s(self, 0)?, s(self, 1)?);
- let mut r = k(self, 0);
- for i in 0..4 {
- let pick = sel >> (8 * i) & 0xFF;
- let byte = match pick {
- 0..=7 => {
- let (src, n) = if pick < 4 { (b, pick) } else { (a, pick - 4) };
- let sh = k(self, 8 * n);
- let t = self.s.m.bin(c, Bin::LShr, src, sh);
- let ff = k(self, 0xFF);
- self.s.m.bin(c, Bin::And, t, ff)
- }
- 8..=11 => {
- let src = if pick < 10 { b } else { a };
- let bit = if pick % 2 == 0 { 15 } else { 31 };
- let left = k(self, 31 - bit);
- let t = self.s.m.bin(c, Bin::Shl, src, left);
- let k31 = k(self, 31);
- let t = self.s.m.bin(c, Bin::AShr, t, k31);
- let ff = k(self, 0xFF);
- self.s.m.bin(c, Bin::And, t, ff)
- }
- 12 => continue,
- _ => k(self, 0xFF),
- };
- let at = k(self, 8 * i);
- let byte = self.s.m.bin(c, Bin::Shl, byte, at);
- r = self.s.m.bin(c, Bin::Or, r, byte);
- }
- r
- }
- "v_bfm_b32" => {
- // ((1 << src0[4:0]) - 1) << src1[4:0]
- let (a, b) = (s(self, 0)?, s(self, 1)?);
- let one = k(self, 1);
- let (a, b) = (m31(self, a), m31(self, b));
- let m = self.s.m.bin(c, Bin::Shl, one, a);
- let m = self.s.m.bin(c, Bin::Sub, m, one);
- self.s.m.bin(c, Bin::Shl, m, b)
- }
- "v_cvt_pk_u8_f32" => {
- // src0 rounded to nearest even and saturated to a byte, into
- // byte src1[1:0] of src2.
- let f = self.fsrc(inst, 0)?;
- let (b, d) = (s(self, 1)?, s(self, 2)?);
- let f = self.unary(26, f);
- let (zero, max) = (self.s.m.f32(0), self.s.m.f32(255.0f32.to_bits()));
- let f = self.binary(35, f, zero);
- let f = self.binary(36, f, max);
- let x = self.s.m.cast(c, Cast::FpToUi, f, self.s.t.i32);
- let (three, k3) = (k(self, 3), k(self, 3));
- let sh = self.s.m.bin(c, Bin::And, b, three);
- let sh = self.s.m.bin(c, Bin::Shl, sh, k3);
- let x = self.s.m.bin(c, Bin::Shl, x, sh);
- let ff = k(self, 0xFF);
- let hole = self.s.m.bin(c, Bin::Shl, ff, sh);
- let ones = k(self, u32::MAX);
- let hole = self.s.m.bin(c, Bin::Xor, hole, ones);
- let d = self.s.m.bin(c, Bin::And, d, hole);
- self.s.m.bin(c, Bin::Or, d, x)
- }
- "v_ffbl_b32" => {
- // -1 for zero, as DXIL's first-bit-low.
- let a = s(self, 0)?;
- self.s
- .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 32, &[a])
- }
- "v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32" => {
- // Bits of the mask's low (high) half below this lane, plus src1:
- // with an all-ones mask, the lane index.
- let (a, b) = (s(self, 0)?, s(self, 1)?);
- // Mesh lanes are the console's by construction; pixel and
- // vertex lanes are the host's, as their masks are.
- if self.mask_data == MaskData::Host {
- // Host lanes: the mask must be one (a ballot) or all lanes.
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- let host = match v.src.first() {
- Some(&Operand::Const(193)) => true,
- Some(&Operand::Scalar { code, .. }) => {
- inst.read(Reg::S(code)).is_some_and(|m| {
- self.x.st.masks.contains_key(&m) || self.x.st.highs.contains_key(&m)
- })
- }
- _ => false,
- };
- if !host {
- return Err("v_mbcnt of a mask that is no ballot (console lane layout)");
- }
- self.s.flags |= flags::WAVE_OPS;
- } else if self.s.mesh.is_none() {
- self.cross_lane(false)?;
- }
- let lane = self.console_lane();
- let below = if name == "v_mbcnt_lo_u32_b32" {
- lane
- } else {
- let (k32, z) = (k(self, 32), k(self, 0));
- let t = self.s.m.bin(c, Bin::Sub, lane, k32);
- let low = self.s.m.cmp(c, pred::IULT, lane, k32);
- self.s.m.select(c, low, z, t)
- };
- // (1 << below) - 1, all ones from 32 on.
- let (one, k32, ones) = (k(self, 1), k(self, 32), k(self, u32::MAX));
- let sh = m31(self, below);
- let m = self.s.m.bin(c, Bin::Shl, one, sh);
- let m = self.s.m.bin(c, Bin::Sub, m, one);
- let full = self.s.m.cmp(c, pred::IUGE, below, k32);
- let m = self.s.m.select(c, full, ones, m);
- let x = self.s.m.bin(c, Bin::And, a, m);
- let n = self
- .s
- .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[x]);
- self.s.m.bin(c, Bin::Add, n, b)
- }
- _ => return Err(name),
- })
- }
- fn compare(&mut self, inst: &Inst, rest: &str) -> Result<(), Why> {
- let (op, ty) = rest.rsplit_once('_').ok_or("a compare")?;
- let c = self.cur;
- let r = match ty {
- "f32" | "f16" if op == "class" => {
- // Bit k of src1 tests class k: signalling NaN, quiet NaN,
- // -inf, -normal, -denormal, -0, +0, +denormal, +normal, +inf.
- let f16 = ty == "f16";
- let x = if f16 {
- let Fields::Valu(v) = &inst.fields else {
- unreachable!()
- };
- let mut h = self.half_src(inst, 0)?;
- if v.abs & 1 != 0 {
- let m = self.s.m.i32(0x7FFF);
- h = self.s.m.bin(c, Bin::And, h, m);
- }
- if v.neg & 1 != 0 {
- let s = self.s.m.i32(0x8000);
- h = self.s.m.bin(c, Bin::Xor, h, s);
- }
- h
- } else {
- let x = self.fsrc(inst, 0)?;
- self.as_int(x)
- };
- let mask = self.src(inst, 1)?;
- let k = |l: &mut Self, v: u32| l.s.m.i32(v);
- let (exp_sh, sign_sh, exp_mask, mant_mask, quiet_bit) = if f16 {
- (10, 15, 0x1F, 0x03FF, 0x0200)
- } else {
- (23, 31, 0xFF, 0x7F_FFFF, 0x40_0000)
- };
- let (k_exp, k_sign, k_emax, mant, quiet) = (
- k(self, exp_sh),
- k(self, sign_sh),
- k(self, exp_mask),
- k(self, mant_mask),
- k(self, quiet_bit),
- );
- let e = self.s.m.bin(c, Bin::LShr, x, k_exp);
- let e = self.s.m.bin(c, Bin::And, e, k_emax);
- let m = self.s.m.bin(c, Bin::And, x, mant);
- let neg = self.s.m.bin(c, Bin::LShr, x, k_sign);
- let zero = k(self, 0);
- let (e0, emax) = (
- self.s.m.cmp(c, pred::EQ, e, zero),
- self.s.m.cmp(c, pred::EQ, e, k_emax),
- );
- let m0 = self.s.m.cmp(c, pred::EQ, m, zero);
- let q = self.s.m.bin(c, Bin::And, x, quiet);
- let q = self.s.m.cmp(c, pred::NE, q, zero);
- // Positive classes 6-9; negative ones are 11 minus those.
- let (normal, inf, zero_c, denorm) =
- (k(self, 8), k(self, 9), k(self, 6), k(self, 7));
- let t = self.s.m.select(c, m0, zero_c, denorm);
- let t = self.s.m.select(c, e0, t, normal);
- let t = self.s.m.select(c, emax, inf, t);
- let eleven = k(self, 11);
- let mirrored = self.s.m.bin(c, Bin::Sub, eleven, t);
- let is_neg = self.s.m.cmp(c, pred::NE, neg, zero);
- let t = self.s.m.select(c, is_neg, mirrored, t);
- let (one, snan) = (k(self, 1), k(self, 0));
- let nan_class = self.s.m.select(c, q, one, snan);
- let yes = self.s.m.bool(true);
- let nan = self.s.m.bin(c, Bin::Xor, m0, yes);
- let nan = self.s.m.bin(c, Bin::And, nan, emax);
- let t = self.s.m.select(c, nan, nan_class, t);
- let bit = self.s.m.bin(c, Bin::LShr, mask, t);
- let bit = self.s.m.bin(c, Bin::And, bit, one);
- self.s.m.cmp(c, pred::NE, bit, zero)
- }
- "f32" | "f16" => {
- let (a, b) = if ty == "f16" {
- (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?)
- } else {
- (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?)
- };
- if op == "lg" {
- // Ordered and not equal, false for a NaN, as `olt | ogt`.
- // `fcmp one` means the same, but the AMD D3D12 driver
- // runs it as unordered (true for a NaN) where NVIDIA
- // and WARP do not; olt and ogt agree on all three.
- let lt = self.s.m.cmp(c, pred::OLT, a, b);
- let gt = self.s.m.cmp(c, pred::OGT, a, b);
- self.s.m.bin(c, Bin::Or, lt, gt)
- } else {
- let p = match op {
- "f" => pred::FALSE,
- "lt" => pred::OLT,
- "eq" => pred::OEQ,
- "le" => pred::OLE,
- "gt" => pred::OGT,
- "ge" => pred::OGE,
- "o" => pred::ORD,
- "u" => pred::UNO,
- "nge" => pred::ULT,
- "nlg" => pred::UEQ,
- "ngt" => pred::ULE,
- "nle" => pred::UGT,
- "neq" => pred::UNE,
- "nlt" => pred::UGE,
- "tru" => pred::TRUE,
- _ => return Err(inst.name()),
- };
- self.s.m.cmp(c, p, a, b)
- }
- }
- "u64" | "i64" => {
- let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?);
- let signed = ty == "i64";
- let p = match op {
- "eq" => pred::EQ,
- "ne" | "lg" => pred::NE,
- "lt" if signed => pred::SLT,
- "le" if signed => pred::SLE,
- "gt" if signed => pred::SGT,
- "ge" if signed => pred::SGE,
- "lt" => pred::IULT,
- "le" => pred::IULE,
- "gt" => pred::IUGT,
- "ge" => pred::IUGE,
- _ => return Err("a 64-bit compare"),
- };
- self.s.m.cmp(c, p, a, b)
- }
- "u32" | "i32" | "u16" | "i16" => {
- let (a, b) = if ty.ends_with("16") {
- let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
- if ty == "i16" {
- let k16 = self.s.m.i32(16);
- for x in [&mut a, &mut b] {
- let t = self.s.m.bin(c, Bin::Shl, *x, k16);
- *x = self.s.m.bin(c, Bin::AShr, t, k16);
- }
- }
- (a, b)
- } else {
- (self.src(inst, 0)?, self.src(inst, 1)?)
- };
- let signed = ty == "i32" || ty == "i16";
- let p = match op {
- "eq" => pred::EQ,
- "ne" | "lg" => pred::NE,
- "lt" if signed => pred::SLT,
- "le" if signed => pred::SLE,
- "gt" if signed => pred::SGT,
- "ge" if signed => pred::SGE,
- "lt" => pred::IULT,
- "le" => pred::IULE,
- "gt" => pred::IUGT,
- "ge" => pred::IUGE,
- "f" | "t" => {
- self.lane(inst, Some(op == "t"));
- return Ok(());
- }
- _ => return Err("an integer compare"),
- };
- self.s.m.cmp(c, p, a, b)
- }
- _ => return Err(inst.name()),
- };
- self.lane_bits_for(inst, r);
- Ok(())
- }
- fn lane(&mut self, inst: &Inst, value: Option<bool>) {
- let b = self.s.m.bool(value == Some(true));
- self.lane_bits_for(inst, b);
- }
- fn lane_bits_for(&mut self, inst: &Inst, r: V) {
- let Fields::Valu(v) = &inst.fields else {
- return;
- };
- let code = if inst.name().starts_with("v_cmpx") {
- Some(EXEC)
- } else {
- match v.dst {
- Some(Operand::Scalar { code, .. }) => Some(code),
- _ => None,
- }
- };
- if let Some(lo) = code.and_then(|c| inst.write(Reg::S(c))) {
- self.lane_bits.insert(lo, r);
- }
- for &(_, w) in &inst.writes {
- self.vals
- .entry(w)
- .or_insert(Val::Missing("a lane mask read as data"));
- }
- }
- fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
- let Some(&interp) = self.interps.get(&site) else {
- // The first half of a pair: its second half interpolates the
- // attribute itself, so nothing needs this half's partial sum.
- // But an f16 second half that writes the high half of the
- // register this one wrote keeps the low half as it was (the
- // console compiler reuses the register; the low half is not
- // read), so the register needs a value: 0.
- let name = inst.name();
- if name == "v_interp_p1_f32" || name == "v_interp_p1ll_f16" {
- let dst = match &inst.fields {
- Fields::Vintrp { dst, .. } => Some(*dst),
- Fields::Valu(v) => v.dst,
- _ => None,
- };
- if let Some(Operand::Vector { reg, .. }) = dst {
- let zero = self.s.m.i32(0);
- self.write(inst, Reg::V(reg), zero, None);
- return Ok(());
- }
- }
- return Err(FIRST_HALF);
- };
- let name = inst.name();
- let (dst, src) = match &inst.fields {
- Fields::Vintrp { dst, src, .. } => (*dst, Some(*src)),
- Fields::Valu(v) => {
- if v.abs != 0 || v.neg != 0 {
- return Err("interpolation operand modifiers");
- }
- (v.dst.ok_or("an interpolation")?, v.src.get(1).copied())
- }
- _ => unreachable!(),
- };
- let Operand::Vector { reg, .. } = dst else {
- return Err("an interpolation");
- };
- // A float operand of the instruction.
- let float = |l: &mut Self, op: Option<Operand>| -> Result<V, Why> {
- let x = l.operand(inst, &op.ok_or("an interpolation operand")?)?;
- Ok(l.as_float(x))
- };
- // What the result adds to the evaluated channel (a second half's
- // first half, when the halves evaluate on their own).
- let mut add = None;
- let (attribute, eval) = match *interp {
- Interp::Interpolated {
- attribute,
- barycentric,
- ..
- } => {
- let mode = interp_mode(barycentric).ok_or("pull-model interpolation")?;
- let eval = if self.per_vertex(attribute.row) {
- // The element is read per vertex elsewhere, so it is
- // constant: weigh its vertices with SV_Barycentrics.
- let mut ij = [None; 2];
- for (index, w) in ij.iter_mut().enumerate() {
- let x = match self.barycentric(barycentric, index as u8) {
- Val::I32(x) => x,
- Val::Missing(w) => return Err(w),
- Val::Bit(_) => unreachable!(),
- };
- *w = Some(self.as_float(x));
- }
- Eval::Weights {
- p0: true,
- i: ij[0],
- j: ij[1],
- }
- } else {
- Eval::Mode(mode)
- };
- (attribute, eval)
- }
- // P0, the provoking vertex: a flat (nointerpolation) input.
- Interp::Vertex {
- attribute,
- vertex: 2,
- } => (attribute, Eval::Mode(1)),
- // P10 and P20: what the first and second halves weigh, P1 - P0
- // and P2 - P0, which is what the hardware holds for an
- // attribute the program also interpolates.
- Interp::Vertex { attribute, vertex } if self.interpolated(attribute.row) => {
- let one = Some(self.s.m.f32(1f32.to_bits()));
- let (i, j) = if vertex == 0 {
- (one, None)
- } else {
- (None, one)
- };
- (attribute, Eval::Weights { p0: false, i, j })
- }
- Interp::Vertex { .. } => return Err("a non-provoking vertex value"),
- // A half of an interpolation with computed i or j: P0 + i P10,
- // or the old dst (f16: the third operand) + j P20.
- Interp::Weighted { attribute } if name.starts_with("v_interp_p1") => {
- let i = Some(float(self, src)?);
- (
- attribute,
- Eval::Weights {
- p0: true,
- i,
- j: None,
- },
- )
- }
- Interp::Weighted { attribute } => {
- let old = match &inst.fields {
- Fields::Valu(v) => v.src.get(2).copied(),
- _ => Some(dst),
- };
- add = Some(float(self, old)?);
- let j = Some(float(self, src)?);
- (
- attribute,
- Eval::Weights {
- p0: false,
- i: None,
- j,
- },
- )
- }
- };
- let packing = match &self.x.native.io {
- StageIo::Ps { inputs, .. } => inputs
- .iter()
- .find(|i| i.row == attribute.row && i.fp16)
- .map(|i| {
- let packs = if i.pack2 {
- input_packs(&self.x.native.io, &self.s.inputs)
- } else {
- Vec::new()
- };
- (i.pack2, packs)
- }),
- _ => None,
- };
- let f16 = name.ends_with("_f16");
- // The evaluated channel plus `add`, as a float.
- let total = |l: &mut Self, row: u8, ch: u8| -> Result<V, Why> {
- let x = l.eval_channel(row, ch, eval)?;
- let x = l.as_float(x);
- Ok(match add {
- Some(a) => l.s.m.bin(l.cur, Bin::Add, a, x),
- None => x,
- })
- };
- let x = match packing {
- None if f16 || attribute.high => return Err("a 16-bit read of a 32-bit input"),
- None => {
- let x = total(self, attribute.row, attribute.channel)?;
- self.as_int(x)
- }
- Some((pack2, packs)) => {
- // 16-bit values: one in the low half of each dword, or two
- // per dword (`packed_half`); the host's are 32-bit floats.
- let half = |l: &mut Self, h: u8| -> Result<Option<V>, Why> {
- let src = if pack2 {
- packed_half(&l.s.inputs, &packs, attribute.row, h)
- } else {
- h.is_multiple_of(2).then_some((attribute.row, h / 2))
- };
- match src {
- Some((row, ch)) => total(l, row, ch).map(Some),
- None => Ok(None),
- }
- };
- let to_f16 = |l: &mut Self, f: V| {
- let i32t = l.s.t.i32;
- l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
- };
- let h = 2 * attribute.channel + u8::from(attribute.high);
- let c = self.cur;
- if name == "v_interp_p1ll_f16" {
- // An f32 result from 16-bit vertex values.
- let f = half(self, h)?.ok_or("a packed input half no element holds")?;
- self.as_int(f)
- } else if f16 {
- let mut f = half(self, h)?.ok_or("a packed input half no element holds")?;
- if let Fields::Valu(v) = &inst.fields {
- // omod, then clamp, before the one rounding to 16 bits; op_sel[3]
- // picks the destination half (VIctory e29391f: the low half was
- // always written, the high one's value never arrived).
- let (omod, clamp) = (v.omod, v.clamp);
- if omod != 0 {
- let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(omod)];
- let k = self.s.m.f32(factor.to_bits());
- f = self.s.m.bin(c, Bin::Mul, f, k);
- }
- if clamp {
- f = self.unary(7, f);
- }
- let lo = to_f16(self, f);
- return self.write_half(inst, lo, None);
- }
- let lo = to_f16(self, f);
- self.low_half(inst, reg, lo)
- } else if matches!(eval, Eval::Mode(1)) {
- // The whole dword of a flat input: both halves.
- let h = 2 * attribute.channel;
- let z = self.s.m.i32(0);
- let lo = match half(self, h)? {
- Some(f) => to_f16(self, f),
- None => z,
- };
- let hi = match half(self, h + 1)? {
- Some(f) => to_f16(self, f),
- None => z,
- };
- let k16 = self.s.m.i32(16);
- let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
- self.s.m.bin(c, Bin::Or, lo, hi)
- } else {
- return Err("32-bit interpolation of a 16-bit input");
- }
- }
- };
- // A pixel interpolates in every lane; guards only hide inactive ones.
- self.write(inst, Reg::V(reg), x, None);
- Ok(())
- }
- /// Whether the program reads attribute row `row` per vertex (an
- /// interpolation with computed barycentrics, or P10 or P20): then its
- /// element is declared constant and read with `attributeAtVertex`.
- fn per_vertex(&self, row: u8) -> bool {
- self.x.io.interps.iter().any(|(_, i)| match *i {
- Interp::Weighted { attribute } => attribute.row == row,
- Interp::Vertex { attribute, vertex } => {
- attribute.row == row && vertex != 2 && self.interpolated(row)
- }
- Interp::Interpolated { .. } => false,
- })
- }
- /// Whether the program interpolates attribute row `row` (so the
- /// hardware holds P1 - P0 and P2 - P0 for it).
- fn interpolated(&self, row: u8) -> bool {
- self.x.io.interps.iter().any(|(_, i)| match *i {
- Interp::Interpolated { attribute, .. } | Interp::Weighted { attribute } => {
- attribute.row == row
- }
- Interp::Vertex { .. } => false,
- })
- }
- /// Channel `ch` of input row `row` evaluated as `eval` says, as raw bits.
- fn eval_channel(&mut self, row: u8, ch: u8, eval: Eval) -> Result<V, Why> {
- let (id, col) = self
- .find_input(row, ch)
- .ok_or("an input the signature lacks")?;
- let mode = match eval {
- Eval::Mode(mode) => mode,
- Eval::Weights { .. } => 1,
- };
- let e = &mut self.s.inputs[id];
- if e.interp != mode && e.usage != 0 {
- return Err("one input interpolated two ways");
- }
- e.interp = mode;
- let Eval::Weights { p0, i, j } = eval else {
- return match self.load_any_input(id, col) {
- Val::I32(x) => Ok(x),
- _ => Err("an input"),
- };
- };
- let v0 = self.vertex_input(id, col, 0);
- let c = self.cur;
- let mut acc = p0.then_some(v0);
- for (k, w) in [(1, i), (2, j)] {
- let Some(w) = w else { continue };
- let vk = self.vertex_input(id, col, k);
- let d = self.s.m.bin(c, Bin::Sub, vk, v0);
- acc = Some(match acc {
- Some(a) => self.fmad(w, d, a),
- None => self.s.m.bin(c, Bin::Mul, w, d),
- });
- }
- let acc = acc.ok_or("an interpolation")?;
- Ok(self.as_int(acc))
- }
- /// Vertex `k` (0 the provoking vertex, as `barycentric` orders them)
- /// of a constant input element's channel, as a float.
- fn vertex_input(&mut self, id: usize, col: u8, k: u8) -> V {
- let e = &mut self.s.inputs[id];
- e.usage |= 1 << col;
- let int = e.comp != 9;
- let (ty, suffix) = if int {
- (self.s.t.i32, ".i32")
- } else {
- (self.s.t.f32, ".f32")
- };
- self.s.flags |= flags::BARYCENTRICS;
- let entry = self.s.entry;
- let args = [
- self.s.m.i32(id as u32),
- self.s.m.i32(0),
- self.s.m.i8(col),
- self.s.m.i8(k),
- ];
- let v = self.s.op(
- entry,
- &format!("attributeAtVertex{suffix}"),
- Attr::ReadNone,
- ty,
- 137,
- &args,
- );
- if int {
- self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.f32)
- } else {
- v
- }
- }
- /// `x` (an f16 in the low bits) as the low half of VGPR `reg`: 16-bit
- /// results keep the register's high half (GFX10).
- fn low_half(&mut self, inst: &Inst, reg: u8, x: V) -> V {
- let c = self.cur;
- let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) {
- Some(Ok(o)) => o,
- _ => self.s.m.i32(0),
- };
- let (high, low) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF));
- let old = self.s.m.bin(c, Bin::And, old, high);
- let x = self.s.m.bin(c, Bin::And, x, low);
- self.s.m.bin(c, Bin::Or, old, x)
- }
- fn image(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
- let Fields::Image {
- data,
- addr,
- dmask,
- dim,
- unorm,
- a16,
- d16,
- tfe,
- lwe,
- ..
- } = &inst.fields
- else {
- unreachable!()
- };
- if *tfe || *lwe {
- return Err("an image access with tfe or lwe");
- }
- let name = inst.name();
- // A load or sample with no channel enabled returns the first.
- let dmask = if *dmask == 0 { &1 } else { dmask };
- let site = (b, i);
- let guard = self.guard(b, i)?;
- let c = self.cur;
- let (kind, coords) = match dim {
- 0 => (1, 1),
- 1 => (2, 2),
- 2 => (4, 3),
- // Sampled (face coordinates and face, see `cube_direction`) or
- // sized only.
- 3 if name.starts_with("image_sample")
- || name.starts_with("image_gather")
- || name == "image_get_resinfo" =>
- {
- (5, 3)
- }
- 4 => (6, 2),
- 5 => (7, 3),
- _ => return Err("an image dimension (cube loads or MSAA)"),
- };
- // Address VGPRs in order.
- let mut regs = Vec::new();
- for a in addr {
- if let Operand::Vector { reg, dwords } = *a {
- regs.extend((0..dwords).map(|k| reg + k));
- }
- }
- // Full 32-bit address VGPR at `reg_idx` (offset, bias, z-compare).
- let addr_u32 = |l: &mut Self, reg_idx: usize| -> Result<V, Why> {
- let r = *regs.get(reg_idx).ok_or("an image address")?;
- let v = inst.read(Reg::V(r)).ok_or("an image address")?;
- l.i32_of(v)
- };
- // With a16, two 16-bit components per VGPR starting at `base_reg`, low half first.
- let addr_packed = |l: &mut Self, base_reg: usize, k: usize| -> Result<V, Why> {
- let x = addr_u32(l, base_reg + if *a16 { k / 2 } else { k })?;
- if !*a16 {
- return Ok(x);
- }
- let c = l.cur;
- let (sh, mask) = (l.s.m.i32(16 * (k as u32 % 2)), l.s.m.i32(0xFFFF));
- let x = l.s.m.bin(c, Bin::LShr, x, sh);
- Ok(l.s.m.bin(c, Bin::And, x, mask))
- };
- let addr_val = |l: &mut Self, k: usize| -> Result<V, Why> { addr_packed(l, 0, k) };
- let src = self
- .descriptors
- .get(&(site, false))
- .copied()
- .ok_or("an untracked image")?;
- let store = name.starts_with("image_store");
- let uav = store
- || self
- .used_kind(src)
- .is_some_and(|u| u.kind == ResourceType::Uav);
- // A UAV inside an ordered section is a rasterizer ordered view.
- let ordered = uav && self.ordered.contains(&site);
- if ordered {
- self.s.flags |= flags::ROVS;
- }
- let rov = if ordered { 0x2000 } else { 0 };
- let props = (kind | if uav { 0x1000 } else { 0 } | rov, 0x409);
- if let Some(op) = name.strip_prefix("image_atomic_") {
- // GLC returns the old value. DXIL implements subtraction by adding
- // the two's complement of the operand at the same width.
- let code = match op {
- "add" | "sub" => 0,
- "and" => 1,
- "or" => 2,
- "xor" => 3,
- "smin" => 4,
- "smax" => 5,
- "umin" => 6,
- "umax" => 7,
- "swap" => 8,
- "cmpswap" => u32::MAX,
- _ => return Err(name),
- };
- let Fields::Image { cache, .. } = &inst.fields else {
- unreachable!()
- };
- // 16-bit coordinates (a16) are read as `addr_val` reads them.
- if *d16 {
- return Err("a 16-bit image atomic");
- }
- // Compare-exchange consumes a replacement followed by a comparand.
- let compare = code == u32::MAX;
- let wide = match (compare, *dmask) {
- (false, 1) | (true, 3) => false,
- (false, 3) | (true, 15) => true,
- _ => return Err("an image atomic data mask"),
- };
- let iu = self.s.m.undef(self.s.t.i32);
- let mut cs = vec![iu; 3];
- for (k, slot) in cs.iter_mut().enumerate().take(coords) {
- *slot = addr_val(self, k)?;
- }
- let Operand::Vector { reg, .. } = *data else {
- return Err("image atomic data");
- };
- let width = if wide { 2 } else { 1 };
- let vals = self.vgprs(inst, data, if compare { 2 * width } else { width })?;
- let (ty, component) = if wide {
- self.s.flags |= flags::INT64 | flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64;
- (self.s.m.int(64), 0x107) // one uint64_t in an R32G32_UINT view
- } else {
- (self.s.t.i32, 0x105)
- };
- let original = if wide {
- self.join64(vals[0], vals[1])
- } else {
- vals[0]
- };
- let value = if op == "sub" {
- let zero = self.s.m.int_const(ty, 0);
- self.s.m.bin(c, Bin::Sub, zero, original)
- } else {
- original
- };
- let h = self.handle(site, src, false, (kind | 0x1000 | rov, component))?;
- let mut args = vec![h];
- let (intrinsic, opcode) = if compare {
- let comparand = if wide {
- self.join64(vals[2], vals[3])
- } else {
- vals[1]
- };
- args.extend(cs);
- args.extend([comparand, value]);
- let intrinsic = if wide {
- "atomicCompareExchange.i64"
- } else {
- "atomicCompareExchange.i32"
- };
- (intrinsic, 79)
- } else {
- args.push(self.s.m.i32(code));
- args.extend(cs);
- args.push(value);
- (
- if wide {
- "atomicBinOp.i64"
- } else {
- "atomicBinOp.i32"
- },
- 78,
- )
- };
- let at = self.begin_guarded(guard);
- let r = self
- .s
- .op(self.cur, intrinsic, Attr::NoUnwind, ty, opcode, &args);
- if cache.glc {
- let old = self.end_guarded(at, &[(r, original)])[0];
- if wide {
- let (lo, hi) = self.split64(old);
- self.write(inst, Reg::V(reg), lo, None);
- self.write(inst, Reg::V(reg + 1), hi, None);
- } else {
- self.write(inst, Reg::V(reg), old, None);
- }
- } else {
- self.end_guarded(at, &[]);
- }
- return Ok(());
- }
- if store {
- if name != "image_store" {
- return Err("an image store to a mip level");
- }
- // shortcut: stores are taken to write all four channels of a
- // float format (the console converts by the view's format).
- // One channel goes into a view the program also counts in.
- let counter = *dmask == 1 && self.is_counter(src);
- if *dmask != 0xF && !counter {
- return Err("an image store of some channels");
- }
- let iu = self.s.m.undef(self.s.t.i32);
- let mut cs = vec![iu; 3];
- for (k, slot) in cs.iter_mut().enumerate().take(coords) {
- *slot = addr_val(self, k)?;
- }
- let Operand::Vector { reg, .. } = *data else {
- return Err("image store data");
- };
- if counter {
- let v = inst.read(Reg::V(reg)).ok_or("image store data")?;
- let x = self.i32_of(v)?;
- // A 16-bit integer, extended by the view's sign: the same
- // number either way only if it is known to be small.
- if *d16 && !self.s.m.int_k(x).is_some_and(|(_, k)| k < 0x8000) {
- return Err("a 16-bit image store of one channel");
- }
- let h = self.handle(site, src, false, (kind | 0x1000 | rov, 0x105))?;
- let at = self.begin_guarded(guard);
- // All four channels are written (the validator wants them
- // all): the view has the first alone.
- let mut args = vec![h];
- args.extend(cs);
- args.extend([x; 4]);
- args.push(self.s.m.i8(0xF));
- let void = self.s.t.void;
- self.s.op(
- self.cur,
- "textureStore.i32",
- Attr::NoUnwind,
- void,
- 67,
- &args,
- );
- self.end_guarded(at, &[]);
- return Ok(());
- }
- let mut vals = Vec::new();
- for k in 0..4u8 {
- // d16: two f16 channels per VGPR, low half first.
- let r = if *d16 { k / 2 } else { k };
- let v = inst.read(Reg::V(reg + r)).ok_or("image store data")?;
- vals.push(if *d16 {
- let mut x = self.i32_of(v)?;
- if k % 2 == 1 {
- let k16 = self.s.m.i32(16);
- x = self.s.m.bin(self.cur, Bin::LShr, x, k16);
- }
- let f32t = self.s.t.f32;
- self.s
- .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x])
- } else {
- self.float_of(v)?
- });
- }
- let h = self.handle(site, src, false, props)?;
- let at = self.begin_guarded(guard);
- let mut args = vec![h];
- args.extend(cs);
- args.extend(vals);
- args.push(self.s.m.i8(0xF));
- let void = self.s.t.void;
- self.s.op(
- self.cur,
- "textureStore.f32",
- Attr::NoUnwind,
- void,
- 67,
- &args,
- );
- self.end_guarded(at, &[]);
- return Ok(());
- }
- let has_cl = name.ends_with("_cl");
- let (op, sample) = match name {
- "image_sample" | "image_sample_o" | "image_sample_cl" => (60, true),
- "image_sample_lz" | "image_sample_l" | "image_sample_lz_o" => (62, true),
- "image_sample_b" | "image_sample_b_cl" => (61, true),
- "image_sample_c_lz" => (65, true),
- "image_sample_d" | "image_sample_d_cl" => (63, true),
- "image_get_lod" if self.s.pixel => (81, true),
- // Implicit derivatives: pixel shaders only.
- "image_sample_c" if self.s.pixel => (64, true),
- "image_sample_c_cl" if self.s.pixel => (64, true),
- "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" | "image_gather4_l" | "image_gather4_l_o" => (73, true),
- "image_load" | "image_load_mip" => (66, false),
- "image_get_resinfo" => (72, false),
- _ => return Err(name),
- };
- if op == 72 {
- // Width, height, depth or layers, levels (per dmask) of the level
- // in the first address: DXIL's dimensions; a channel DXIL leaves
- // out reads 1 (UAVs: one level).
- let h = self.handle(site, src, false, props)?;
- let mip = if uav {
- self.s.m.undef(self.s.t.i32)
- } else {
- addr_val(self, 0)?
- };
- let i32t = self.s.t.i32;
- let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
- let d = self
- .s
- .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
- let one = self.s.m.i32(1);
- let present = match kind {
- 1 => [true, false, false, true],
- 2 | 5 | 6 => [true, true, false, true],
- _ => [true, true, true, true],
- };
- let Operand::Vector { reg, .. } = *data else {
- return Err("an image result");
- };
- for (k, ch) in (0..4u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() {
- let x = if ch == 3 && uav || !present[ch as usize] {
- one
- } else {
- self.s.m.extract(c, d, ch)
- };
- self.write(inst, Reg::V(reg + k as u8), x, guard);
- }
- return Ok(());
- }
- if uav && op != 66 {
- return Err("sampling a UAV");
- }
- let h = self.handle(site, src, false, props)?;
- let fu = self.s.m.undef(self.s.t.f32);
- let iu = self.s.m.undef(self.s.t.i32);
- // A gather at a named level, done as four texel reads (below).
- let mut gathered: Option<[V; 4]> = None;
- let r = if sample {
- let ss = self
- .descriptors
- .get(&(site, true))
- .copied()
- .ok_or("an untracked sampler")?;
- // Comparison: the reference value is the first address after
- // the bias, and the sampler is a comparison sampler.
- let cmp = matches!(op, 64 | 65);
- if cmp && (*a16 || dmask.count_ones() != 1) {
- return Err("a comparison sample of 16-bit coordinates or several channels");
- }
- let mut sampler_choice: Option<(V, Vec<u32>)> = None;
- let sh = match ss {
- Source::Phi { block, args } => {
- match self.sampler_phi_choice(*block, args, cmp, 8) {
- Ok((None, regs)) => self.s.sampler_handle(self.cur, regs[0]),
- Ok((Some(idx), regs)) => {
- let first = self.s.sampler_handle(self.cur, regs[0]);
- sampler_choice = Some((idx, regs));
- first
- }
- Err(_) => {
- self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?
- }
- }
- }
- _ => self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?,
- };
- // Texel offsets (`_o`) come first: x in bits 0-5, y in 8-13,
- // signed (programmable offsets: gathers only).
- let offset_word = name.ends_with("_o");
- let first = usize::from(offset_word)
- + usize::from(name.starts_with("image_sample_b"))
- + usize::from(cmp);
- // Coordinates the size divides (not the array slice); explicit
- // gradients (x then y) come before the coordinates.
- let spatial = coords - usize::from(kind == 6 || kind == 7);
- // A cube's gradients are the two of its face coordinates.
- let grads = if kind == 5 { 2 } else { spatial };
- let deriv_regs = if op == 63 {
- if *a16 {
- grads.div_ceil(2)
- } else {
- grads
- }
- } else {
- 0
- };
- let coord_base = first + 2 * deriv_regs;
- let mut cs = vec![fu; 4];
- // With a16, sampling coordinates, gradients, LOD and clamp are f16.
- let to_float = |l: &mut Self, x: V| {
- if *a16 {
- let f = l.s.t.f32;
- l.s.op(l.cur, "legacyF16ToF32", Attr::ReadNone, f, 131, &[x])
- } else {
- l.as_float(x)
- }
- };
- if kind == 5 && (*unorm || op == 81) {
- return Err("a cube sample with texel coordinates or a level query");
- }
- for (k, slot) in cs.iter_mut().enumerate().take(coords) {
- let x = addr_packed(self, coord_base, k)?;
- *slot = to_float(self, x);
- }
- if kind == 5 {
- let dir = self.cube_direction(cs[0], cs[1], cs[2]);
- cs[..3].copy_from_slice(&dir);
- }
- if *unorm {
- // Texel coordinates: divided by the size of level 0.
- let i32t = self.s.t.i32;
- let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
- let z = self.s.m.i32(0);
- let d = self
- .s
- .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]);
- for (k, slot) in cs.iter_mut().enumerate().take(spatial) {
- let n = self.s.m.extract(c, d, k as u32);
- let n = self.s.m.cast(c, Cast::UiToFp, n, self.s.t.f32);
- *slot = self.s.m.bin(c, Bin::SDiv, *slot, n);
- }
- }
- if op == 81 {
- // The clamped then the unclamped level of detail.
- let Operand::Vector { reg, .. } = *data else {
- return Err("an image result");
- };
- let f32t = self.s.t.f32;
- for (k, ch) in (0..2u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() {
- let clamped = self.s.m.bool(ch == 0);
- let lod = self.s.op(
- c,
- "calculateLOD.f32",
- Attr::ReadOnly,
- f32t,
- 81,
- &[h, sh, cs[0], cs[1], cs[2], clamped],
- );
- let x = self.as_int(lod);
- self.write(inst, Reg::V(reg + k as u8), x, guard);
- }
- return Ok(());
- }
- let offsets = if kind == 5 {
- 0
- } else {
- (coords - usize::from(kind == 6 || kind == 7)).min(3)
- };
- let zero = self.s.m.i32(0);
- let mut os = vec![iu; 3];
- for o in os.iter_mut().take(offsets) {
- *o = zero;
- }
- if offset_word && offsets > 0 {
- let w = addr_val(self, 0)?;
- for (k, at) in [(0, 26), (1, 18)].into_iter().take(offsets.min(2)) {
- // Bits at..at+5 sign-extended: shift up, then down.
- let left = self.s.m.i32(at);
- let t = self.s.m.bin(c, Bin::Shl, w, left);
- let k26 = self.s.m.i32(26);
- os[k] = self.s.m.bin(c, Bin::AShr, t, k26);
- }
- }
- let mut args = vec![h, sh];
- args.extend(&cs);
- let clamp = if has_cl {
- let x = addr_packed(self, coord_base, coords)?;
- to_float(self, x)
- } else {
- fu
- };
- let call_sample = |l: &mut Self,
- intrinsic: &str,
- opcode: u32,
- args: &[V],
- gathered: &mut Option<[V; 4]>|
- -> V {
- let Some((idx, ref regs)) = sampler_choice else {
- return l
- .s
- .op(c, intrinsic, Attr::ReadOnly, l.s.t.res_ret, opcode, args);
- };
- let merge = l.s.m.new_block();
- let mut cur_test = c;
- let mut per_ch: [Vec<(V, usize)>; 4] = Default::default();
- let mut last_r = args[0];
- for (i, ®) in regs.iter().enumerate() {
- let arm = if i + 1 == regs.len() {
- cur_test
- } else {
- let arm = l.s.m.new_block();
- let next = l.s.m.new_block();
- let k = l.s.m.i32(i as u32);
- let cond = l.s.m.cmp(cur_test, pred::EQ, idx, k);
- l.s.m.terminate(cur_test, Term::CondBr(cond, arm, next));
- cur_test = next;
- arm
- };
- let mut arm_args = args.to_vec();
- arm_args[1] = l.s.sampler_handle(arm, reg);
- let r_i = l.s.op(
- arm,
- intrinsic,
- Attr::ReadOnly,
- l.s.t.res_ret,
- opcode,
- &arm_args,
- );
- for (ch, slot) in per_ch.iter_mut().enumerate() {
- let v = l.s.m.extract(arm, r_i, ch as u32);
- slot.push((v, arm));
- }
- l.s.m.terminate(arm, Term::Br(merge));
- last_r = r_i;
- }
- let mut phis = [fu; 4];
- for (ch, incoming) in per_ch.into_iter().enumerate() {
- let phi = l.s.m.phi(merge, l.s.t.f32);
- l.s.m.set_phi(phi, incoming);
- phis[ch] = phi;
- }
- *gathered = Some(phis);
- l.cur = merge;
- last_r
- };
- match op {
- // Outside a pixel shader there are no screen derivatives:
- // the validator refuses `sample` there ("features
- // incompatible with the shader stage": 730 compute programs,
- // among them the G-buffer resolves and the sky), and what a
- // driver does with it is its own affair.
- // shortcut: such a sample reads level 0 (a bias: that
- // level). The console takes derivatives from neighbouring
- // lanes there; compute them from the lanes if a resolve
- // shows the wrong mip.
- 60 if !self.s.pixel => {
- args.extend(&os);
- args.push(self.s.m.f32(0));
- call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
- }
- 60 => {
- if offset_word {
- // DXIL wants immediate offsets in -8..=7 here; the
- // console's are 6-bit and may be computed. A
- // constant word in range becomes immediates
- // (upstream PR #634); anything else keeps the
- // offsets computed above (upstream refuses those).
- let w = addr_val(self, 0)?;
- if let Some(w) = self.s.m.int_value(w) {
- let w = w as u32;
- let field = |k: usize| {
- let x = (w >> (8 * k) & 0x3F) as i32;
- if x >= 32 { x - 64 } else { x }
- };
- let n = offsets.min(2);
- if (0..n).all(|k| (-8..=7).contains(&field(k))) {
- for (k, o) in os.iter_mut().enumerate().take(n) {
- *o = self.s.m.i32(field(k) as u32);
- }
- }
- }
- }
- args.extend(&os);
- args.push(clamp);
- call_sample(self, "sample.f32", 60, &args, &mut gathered)
- }
- 61 => {
- // With a16 the bias is an f16 in the low half of its
- // word (the word is whole, the value is not).
- let bias = addr_u32(self, usize::from(offset_word))?;
- let bias = if *a16 {
- let low = self.s.m.i32(0xFFFF);
- let bias = self.s.m.bin(c, Bin::And, bias, low);
- to_float(self, bias)
- } else {
- self.as_float(bias)
- };
- args.extend(&os);
- if self.s.pixel {
- args.extend([bias, clamp]);
- call_sample(self, "sampleBias.f32", 61, &args, &mut gathered)
- } else {
- // As above: the bias is the level.
- args.push(bias);
- call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
- }
- }
- 63 if kind == 5 => {
- // A cube with explicit gradients: the host wants them
- // as changes of the direction, the console gives the
- // changes of the face coordinates (the face is one
- // unit wide). The level they select is taken from the
- // longer of the two, in texels, and sampled directly.
- // shortcut: no anisotropic filtering for these samples
- // (the longer axis alone decides the level).
- let mut len = [fu; 2];
- for (axis, slot) in len.iter_mut().enumerate() {
- let mut sum = self.s.m.f32(0);
- for k in 0..2 {
- let x = addr_packed(self, first + axis * deriv_regs, k)?;
- let x = to_float(self, x);
- let sq = self.s.m.bin(c, Bin::Mul, x, x);
- sum = self.s.m.bin(c, Bin::Add, sum, sq);
- }
- *slot = self.unary(24, sum); // square root
- }
- let longer = self.binary(35, len[0], len[1]); // maximum
- let i32t = self.s.t.i32;
- let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
- let z = self.s.m.i32(0);
- let d = self
- .s
- .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]);
- let width = self.s.m.extract(c, d, 0);
- let width = self.s.m.cast(c, Cast::UiToFp, width, self.s.t.f32);
- let texels = self.s.m.bin(c, Bin::Mul, longer, width);
- // DXIL's logarithm is the one to base 2 (it was taken for
- // the natural one: every level came out 1.44 times too
- // high; DexNom/VIctory 921d8d3b). A length of 0 gives
- // minus infinity, which the sampler clamps to level 0.
- // SampleLevel takes no clamp: the instruction's least
- // level is applied here.
- let lod = self.unary(23, texels);
- let lod = if has_cl { self.binary(35, lod, clamp) } else { lod };
- args.extend(&os);
- args.push(lod);
- call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
- }
- 63 => {
- let mut g = vec![fu; 6];
- for k in 0..spatial {
- let x = addr_packed(self, first, k)?;
- g[k] = to_float(self, x);
- let y = addr_packed(self, first + deriv_regs, k)?;
- g[3 + k] = to_float(self, y);
- }
- args.extend(&os);
- args.extend(g);
- args.push(clamp);
- call_sample(self, "sampleGrad.f32", 63, &args, &mut gathered)
- }
- 64 | 65 => {
- let reference = addr_u32(self, first - 1)?;
- let reference = self.as_float(reference);
- args.extend(&os);
- args.push(reference);
- let name = if op == 64 {
- args.push(clamp);
- "sampleCmp.f32"
- } else {
- "sampleCmpLevelZero.f32"
- };
- call_sample(self, name, op, &args, &mut gathered)
- }
- 62 => {
- let lod = if name == "image_sample_l" {
- let x = addr_packed(self, coord_base, coords)?;
- to_float(self, x)
- } else {
- self.s.m.f32(0)
- };
- args.extend(&os);
- args.push(lod);
- call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
- }
- _ => {
- if name == "image_gather4" {
- return Err("a gather with implicit level");
- }
- if dmask.count_ones() != 1 {
- return Err("a gather of several channels");
- }
- if matches!(name, "image_gather4_l" | "image_gather4_l_o")
- && coords == 2
- && spatial == 2
- {
- // The host's gather has no level: it read level 0
- // where the title names one (the depth pyramid its
- // occlusion tests read: most of the world was
- // culled against the wrong depths). The four texels
- // are read at the level instead, in the gather's
- // order: (u0,v1) (u1,v1) (u1,v0) (u0,v0).
- // With an offset too (`image_gather4_l_o`): the
- // offset is in texels of that level.
- // The title's meshlet culling takes a 4x4 block of
- // the pyramid as one gather and three offset ones
- // ((2,0), (0,2), (2,2)); the three read level 0,
- // two texels beside the first one's place, so a
- // meshlet three or four texels wide was tested
- // against a quarter of what it covers.
- // shortcut: the level is rounded to a whole one and
- // coordinates past the edge are clamped, whatever
- // the sampler says.
- let lod = addr_packed(self, coord_base, coords)?;
- let lod = to_float(self, lod);
- let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
- let zero = self.s.m.f32(0);
- let lod = self.binary(35, lod, zero); // maximum
- let lod = self.unary(26, lod); // round to nearest
- let mip = self.s.m.cast(c, Cast::FpToUi, lod, i32t);
- let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]);
- let d = self
- .s
- .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]);
- let half = self.s.m.f32(0.5f32.to_bits());
- let one = self.s.m.f32(1.0f32.to_bits());
- let (mut lo, mut hi) = ([iu; 2], [iu; 2]);
- for k in 0..2 {
- let n = self.s.m.extract(c, d, k as u32);
- let n = self.s.m.cast(c, Cast::UiToFp, n, f32t);
- let last = self.s.m.bin(c, Bin::Sub, n, one);
- let t = self.s.m.bin(c, Bin::Mul, cs[k], n);
- let t = self.s.m.bin(c, Bin::Sub, t, half);
- let first = self.unary(27, t); // round down
- // The offset word's field (0 without one).
- let by = self.s.m.cast(c, Cast::SiToFp, os[k], f32t);
- let first = self.s.m.bin(c, Bin::Add, first, by);
- let next = self.s.m.bin(c, Bin::Add, first, one);
- for (slot, x) in [(&mut lo[k], first), (&mut hi[k], next)] {
- let x = self.binary(35, x, zero); // maximum
- let x = self.binary(36, x, last); // minimum
- *slot = self.s.m.cast(c, Cast::FpToSi, x, i32t);
- }
- }
- let ch = dmask.trailing_zeros();
- let mut g = [fu; 4];
- let mut read = None;
- let texels = [(lo[0], hi[1]), (hi[0], hi[1]), (hi[0], lo[1]), (lo[0], lo[1])];
- for (slot, (x, y)) in g.iter_mut().zip(texels) {
- let r = self.s.op(
- c,
- "textureLoad.f32",
- Attr::ReadOnly,
- self.s.t.res_ret,
- 66,
- &[h, mip, x, y, iu, iu, iu, iu],
- );
- *slot = self.s.m.extract(c, r, ch);
- read = Some(r);
- }
- gathered = Some(g);
- read.expect("four reads")
- } else {
- args.extend(&os[..2]);
- args.push(self.s.m.i32(dmask.trailing_zeros()));
- call_sample(self, "textureGather.f32", 73, &args, &mut gathered)
- }
- }
- }
- } else {
- let mut cs = vec![iu; 3];
- for (k, slot) in cs.iter_mut().enumerate().take(coords) {
- *slot = addr_val(self, k)?;
- }
- let mip = if name == "image_load_mip" {
- addr_val(self, coords)?
- } else if uav {
- // Our declarations have four channels.
- self.s.flags |= flags::TYPED_UAV_LOADS;
- iu
- } else {
- self.s.m.i32(0)
- };
- let mut args = vec![h, mip];
- args.extend(&cs);
- args.extend([iu, iu, iu]);
- self.s.op(
- c,
- "textureLoad.f32",
- Attr::ReadOnly,
- self.s.t.res_ret,
- 66,
- &args,
- )
- };
- let Operand::Vector { reg, .. } = *data else {
- return Err("an image result");
- };
- let channels: Vec<u32> = if op == 73 {
- vec![0, 1, 2, 3]
- } else {
- (0..4).filter(|ch| dmask >> ch & 1 != 0).collect()
- };
- let mut xs = Vec::new();
- for ch in channels {
- let x = match gathered {
- Some(g) => g[ch as usize],
- None => self.s.m.extract(c, r, ch),
- };
- xs.push(if *d16 {
- // shortcut: d16 results are taken as floats (rounded to
- // nearest even); integer formats would keep 16 bits.
- let i32t = self.s.t.i32;
- self.s
- .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x])
- } else {
- self.as_int(x)
- });
- }
- if *d16 {
- // Two channels per VGPR, low half first (an odd last high half 0).
- let k16 = self.s.m.i32(16);
- xs = xs
- .chunks(2)
- .map(|p| match *p {
- [lo, hi] => {
- let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
- self.s.m.bin(c, Bin::Or, lo, hi)
- }
- _ => p[0],
- })
- .collect();
- }
- for (k, x) in xs.into_iter().enumerate() {
- self.write(inst, Reg::V(reg + k as u8), x, guard);
- }
- Ok(())
- }
- /// The direction a cube sample's face coordinates stand for: the
- /// console takes s and t in [1, 2] (`v_cubesc`/`v_cubetc` over
- /// `|v_cubema|`, plus 1.5) and the face id (`v_cubeid`), which the
- /// host's cube sampling turns back into the same texel.
- // shortcut: the view is taken as a cube, not a cube array (whose face
- // operand adds 8 × the slice).
- fn cube_direction(&mut self, s: V, t: V, face: V) -> [V; 3] {
- let c = self.cur;
- let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits());
- let (two, three) = (k(self, 2.0), k(self, 3.0));
- let u = self.s.m.bin(c, Bin::Mul, s, two);
- let u = self.s.m.bin(c, Bin::Sub, u, three);
- let v = self.s.m.bin(c, Bin::Mul, t, two);
- let v = self.s.m.bin(c, Bin::Sub, v, three);
- let z = self.s.m.f32(0x8000_0000);
- let (nu, nv) = (
- self.s.m.bin(c, Bin::Sub, z, u),
- self.s.m.bin(c, Bin::Sub, z, v),
- );
- let (one, mone) = (k(self, 1.0), k(self, -1.0));
- let f = self.s.m.cast(c, Cast::FpToUi, face, self.s.t.i32);
- // Per face +x, -x, +y, -y, +z, -z.
- let table = [
- [one, mone, u, u, u, nu],
- [nv, nv, one, mone, nv, nv],
- [nu, u, v, nv, one, mone],
- ];
- table.map(|row| {
- let mut r = row[0];
- for (n, &x) in row.iter().enumerate().skip(1) {
- let kn = self.s.m.i32(n as u32);
- let is = self.s.m.cmp(c, pred::EQ, f, kn);
- r = self.s.m.select(c, is, x, r);
- }
- r
- })
- }
- fn buffer(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
- self.root_copy = None;
- let Fields::Buffer {
- data,
- addr,
- soffset,
- offset,
- offen,
- idxen,
- format,
- lds,
- tfe,
- ..
- } = &inst.fields
- else {
- unreachable!()
- };
- let name = inst.name();
- if name == "buffer_gl0_inv" || name == "buffer_gl1_inv" {
- // The host has no console buffer cache to invalidate.
- return Ok(());
- }
- if *lds || *tfe {
- return Err("a buffer access to LDS or with tfe");
- }
- if format.is_some() && !name.starts_with("tbuffer_load_format_") {
- return Err(name);
- }
- let site = (b, i);
- let guard = self.guard(b, i)?;
- let c = self.cur;
- let store = name.starts_with("buffer_store_");
- // DXIL atomic operations: add, and, or, xor, signed and unsigned
- // min and max, exchange; compare-exchange apart.
- let atomic = match name.strip_prefix("buffer_atomic_") {
- None => None,
- Some("add") => Some(0),
- Some("and") => Some(1),
- Some("or") => Some(2),
- Some("xor") => Some(3),
- Some("smin") => Some(4),
- Some("smax") => Some(5),
- Some("umin") => Some(6),
- Some("umax") => Some(7),
- Some("swap") => Some(8),
- Some("cmpswap") => Some(u32::MAX),
- Some(_) => return Err(name),
- };
- // Byte and 16-bit accesses: bits, and whether a load sign-extends.
- let narrow = match name {
- "buffer_load_ubyte" | "buffer_store_byte" => Some((8, false)),
- "buffer_load_sbyte" => Some((8, true)),
- "buffer_load_ushort" | "buffer_store_short" => Some((16, false)),
- "buffer_load_sshort" => Some((16, true)),
- _ => None,
- };
- // d16: two 16-bit channels per VGPR, low half first (buffer and
- // tbuffer formats alike).
- let d16 = name.contains("_format_d16_");
- let plain = name.replace("_format_d16_", "_format_");
- let (typed, count) = match plain
- .strip_prefix("buffer_load_")
- .or(plain.strip_prefix("buffer_store_"))
- .or(plain.strip_prefix("tbuffer_load_"))
- {
- _ if atomic.is_some() || narrow.is_some() => (false, 1),
- Some("dword") => (false, 1),
- Some("dwordx2") => (false, 2),
- Some("dwordx3") => (false, 3),
- Some("dwordx4") => (false, 4),
- Some("format_x") => (true, 1),
- Some("format_xy") => (true, 2),
- Some("format_xyz") => (true, 3),
- Some("format_xyzw") => (true, 4),
- _ => return Err(name),
- };
- let Operand::Vector { reg: areg, .. } = *addr else {
- return Err("a buffer address");
- };
- let vaddr = |l: &mut Self, k: u8| -> Result<V, Why> {
- let v = inst.read(Reg::V(areg + k)).ok_or("a buffer address")?;
- l.i32_of(v)
- };
- let index = if *idxen { Some(vaddr(self, 0)?) } else { None };
- let mut off = self.s.m.i32(u32::from(*offset));
- if *offen {
- let o = vaddr(self, u8::from(*idxen))?;
- off = self.s.m.bin(c, Bin::Add, off, o);
- }
- if !matches!(
- soffset,
- Operand::Scalar { code: NULL, .. } | Operand::Const(128)
- ) {
- let so = self.operand(inst, soffset)?;
- off = self.s.m.bin(c, Bin::Add, off, so);
- }
- let src = self
- .descriptors
- .get(&(site, false))
- .copied()
- .ok_or("an untracked buffer")?;
- let used = self.used_kind(src);
- let (base, extra) = self.built_offset(src)?;
- if base != 0 {
- let b = self.s.m.i32(base);
- off = self.s.m.bin(c, Bin::Add, off, b);
- }
- if let Some(x) = extra {
- off = self.s.m.bin(c, Bin::Add, off, x);
- }
- // A buffer the program picks from the view heap by an index it
- // computes: no used-resource entry gives its stride, the host's
- // table by heap slot does; the access becomes a raw one at the
- // element's byte. (Also tells the host this shader reads such
- // buffers.)
- let mut index = index;
- if let Some(stride) = self.slot_stride(src)?
- && let Some(element) = index
- && !typed
- && used.is_none()
- {
- let at = self.s.m.bin(c, Bin::Mul, element, stride);
- off = self.s.m.bin(c, Bin::Add, at, off);
- index = None;
- }
- // A structured buffer by its used-resource entry's stride: raw
- // bytes too. The host makes its buffer views raw (a raw read
- // through a structured view gives zeros on NVIDIA), and one kind
- // of view can then serve every shader that reads the buffer.
- if let (Some(element), Some(u)) = (index, used)
- && !typed
- && u.kind != ResourceType::Cbv
- && u.stride >= 4
- && u.stride.is_multiple_of(4)
- {
- let k = self.s.m.i32(u.stride);
- let at = self.s.m.bin(c, Bin::Mul, element, k);
- off = self.s.m.bin(c, Bin::Add, at, off);
- index = None;
- }
- if used.is_some_and(|u| u.kind == ResourceType::Cbv) && !typed {
- // A constant buffer read per lane (a dynamically indexed array).
- // shortcut: the console's CBV descriptor is taken to have a 16-byte
- // stride, as the vector loads of whole rows suggest.
- let h = self.handle(site, src, false, (13, 0x1_0000))?;
- let byte = match index {
- Some(i) => {
- let sixteen = self.s.m.i32(16);
- let rows = self.s.m.bin(c, Bin::Mul, i, sixteen);
- self.s.m.bin(c, Bin::Add, rows, off)
- }
- None => off,
- };
- let Some(Operand::Vector { reg, .. }) = *data else {
- return Err("a buffer result");
- };
- for k in 0..count {
- let four = self.s.m.i32(4 * k);
- let a = self.s.m.bin(c, Bin::Add, byte, four);
- let x = self.cbuffer_dword(h, a);
- self.write(inst, Reg::V(reg + k as u8), x, guard);
- }
- return Ok(());
- }
- if self.root_address(src).is_some() {
- // Title memory by address: the byte in the host copy from here on.
- if let Some(element) = index {
- if used.is_none_or(|u| u.stride != 1) {
- return Err("an indexed access through a root view by address");
- }
- off = self.s.m.bin(c, Bin::Add, element, off);
- index = None;
- }
- if let Some((_, byte)) = self.root_memory(src, off, guard, store || atomic.is_some()) {
- off = byte;
- }
- }
- let c = self.cur;
- let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav);
- let mut u = if uav { 0x1000 } else { 0 };
- if uav && !typed && self.entry(src).is_some_and(|e| self.coherent.contains(&e)) {
- u |= 0x4000;
- }
- let iu = self.s.m.undef(self.s.t.i32);
- if let Some((bits, signed)) = narrow {
- // Below a dword: raw buffers are read and written in dwords on
- // 4 bytes, so the dword that holds the value is read and
- // shifted, or changed with two atomic operations that touch
- // only the value's own bits (other lanes may write the rest of
- // the dword at the same time). A 16-bit value at a dword's
- // last byte continues in the next dword.
- let byte = match index {
- None => off,
- Some(index) if used.is_some_and(|u| u.stride == 1) => {
- self.s.m.bin(c, Bin::Add, index, off)
- }
- Some(_) => return Err("a byte or 16-bit buffer access by index"),
- };
- let h = self.handle(site, src, false, (11 | u, 0))?;
- let k3 = self.s.m.i32(3);
- let within = self.s.m.bin(c, Bin::And, byte, k3);
- let aligned = self.s.m.bin(c, Bin::Sub, byte, within);
- let shift = self.s.m.bin(c, Bin::Shl, within, k3);
- let four = self.s.m.i32(4);
- let next = self.s.m.bin(c, Bin::Add, aligned, four);
- let ones = self.s.m.i32(if bits == 8 { 0xff } else { 0xffff });
- let zero = self.s.m.i32(0);
- let k8 = self.s.m.i32(8);
- let straddles = self.s.m.cmp(c, pred::EQ, within, k3);
- if !store {
- let mask = self.s.m.i8(1);
- let align = self.s.m.i32(4);
- let dword = |l: &mut Self, at: V| {
- let r = l.s.op(
- c,
- "rawBufferLoad.f32",
- Attr::ReadOnly,
- l.s.t.res_ret,
- 139,
- &[h, at, iu, mask, align],
- );
- let f = l.s.m.extract(c, r, 0);
- l.as_int(f)
- };
- let low = dword(self, aligned);
- let mut x = self.s.m.bin(c, Bin::LShr, low, shift);
- if bits == 16 {
- let high = dword(self, next);
- let high = self.s.m.bin(c, Bin::Shl, high, k8);
- let high = self.s.m.select(c, straddles, high, zero);
- x = self.s.m.bin(c, Bin::Or, x, high);
- }
- x = self.s.m.bin(c, Bin::And, x, ones);
- if signed {
- let up = self.s.m.i32(32 - bits);
- x = self.s.m.bin(c, Bin::Shl, x, up);
- x = self.s.m.bin(c, Bin::AShr, x, up);
- }
- let Some(Operand::Vector { reg, .. }) = *data else {
- return Err("a buffer result");
- };
- self.write(inst, Reg::V(reg), x, guard);
- return Ok(());
- }
- let d = data.as_ref().ok_or("buffer store data")?;
- let v = self.vgprs(inst, d, 1)?[0];
- let v = self.s.m.bin(c, Bin::And, v, ones);
- let all = self.s.m.i32(u32::MAX);
- let clear = self.s.m.bin(c, Bin::Shl, ones, shift);
- let keep = self.s.m.bin(c, Bin::Xor, clear, all);
- let set = self.s.m.bin(c, Bin::Shl, v, shift);
- let keep_next = self.s.m.i32(0xffff_ff00);
- let set_next = self.s.m.bin(c, Bin::LShr, v, k8);
- let (and, or) = (self.s.m.i32(1), self.s.m.i32(2));
- let i32t = self.s.t.i32;
- let at = self.begin_guarded(guard);
- for (op, x) in [(and, keep), (or, set)] {
- let args = [h, op, aligned, iu, iu, x];
- self.s
- .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args);
- }
- if bits == 16 {
- let second = self.begin_guarded(Some(straddles));
- for (op, x) in [(and, keep_next), (or, set_next)] {
- let args = [h, op, next, iu, iu, x];
- self.s
- .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args);
- }
- self.end_guarded(second, &[]);
- }
- self.end_guarded(at, &[]);
- return Ok(());
- }
- if let Some(op) = atomic {
- let d = data.as_ref().ok_or("buffer atomic data")?;
- let vals = self.vgprs(inst, d, if op == u32::MAX { 2 } else { 1 })?;
- let (h, coords) = match index {
- // A raw buffer (stride 1) read by index: the index is the byte.
- Some(index) if used.is_some_and(|u| u.stride == 1) => {
- let byte = self.s.m.bin(c, Bin::Add, index, off);
- (self.handle(site, src, false, (11 | u, 0))?, [byte, iu, iu])
- }
- Some(index) => {
- let stride = used.map_or(0, |u| u.stride);
- if stride < 4 || !stride.is_multiple_of(4) {
- return Err("a structured buffer of unknown stride");
- }
- let h = self.handle(site, src, false, (12 | u, stride))?;
- (h, [index, off, iu])
- }
- None => (self.handle(site, src, false, (11 | u, 0))?, [off, iu, iu]),
- };
- let Operand::Vector { reg, .. } = *d else {
- return Err("buffer atomic data");
- };
- let returns = matches!(inst.fields, Fields::Buffer { cache, .. } if cache.glc);
- let old = match inst.read(Reg::V(reg)) {
- Some(v) if returns => self.i32_of(v)?,
- _ => self.s.m.i32(0),
- };
- let at = self.begin_guarded(guard);
- let i32t = self.s.t.i32;
- let r = if op == u32::MAX {
- // cmpswap: data is (new, compare).
- let mut args = vec![h];
- args.extend(coords);
- args.extend([vals[1], vals[0]]);
- self.s.op(
- self.cur,
- "atomicCompareExchange.i32",
- Attr::NoUnwind,
- i32t,
- 79,
- &args,
- )
- } else {
- let mut args = vec![h, self.s.m.i32(op)];
- args.extend(coords);
- args.push(vals[0]);
- self.s
- .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args)
- };
- let r = self.end_guarded(at, &[(r, old)])[0];
- if returns {
- self.write(inst, Reg::V(reg), r, None);
- }
- return Ok(());
- }
- if store {
- let regs = if d16 { count.div_ceil(2) } else { count };
- let mut vals =
- self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?;
- if d16 {
- // d16 data is taken as f16, widened for the 32-bit float
- // store; through a view of an integer format it is a 16-bit
- // integer, zero- or sign-extended (VIctory 4243a96a: the face
- // network keeps its halves in UINT views; its output was
- // noise). shortcut: that is known of the views a program
- // picks from the heap, not of those in its tables; and the
- // handle stays a float one, whose bits the drivers pass.
- let integer = if typed { self.integer_view(src)? } else { None };
- let mut wide = Vec::new();
- for k in 0..count {
- let mut x = vals[(k / 2) as usize];
- if k % 2 == 1 {
- let k16 = self.s.m.i32(16);
- x = self.s.m.bin(c, Bin::LShr, x, k16);
- }
- let f32t = self.s.t.f32;
- let f = self
- .s
- .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
- let mut w = self.as_int(f);
- if let Some((int, signed)) = integer {
- let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
- let zero_ext = self.s.m.bin(c, Bin::And, x, low);
- let up = self.s.m.bin(c, Bin::Shl, x, k16);
- let sign_ext = self.s.m.bin(c, Bin::AShr, up, k16);
- let n = self.s.m.select(c, signed, sign_ext, zero_ext);
- w = self.s.m.select(c, int, n, w);
- }
- wide.push(w);
- }
- vals = wide;
- }
- let mut args = Vec::new();
- let (op, name) = if typed {
- // shortcut: typed stores are taken to write all four channels
- // of a float format.
- if count != 4 || *offen || *offset != 0 {
- return Err("a typed buffer store of some channels or at an offset");
- }
- args.push(self.handle(site, src, false, (10 | u, 0x409))?);
- args.extend([index.unwrap_or(self.s.m.i32(0)), iu]);
- for x in vals {
- args.push(self.as_float(x));
- }
- (69, "bufferStore.f32")
- } else {
- match index {
- // A raw buffer (stride 1) written by index: the index is the byte.
- Some(index) if used.is_some_and(|u| u.stride == 1) => {
- let byte = self.s.m.bin(c, Bin::Add, index, off);
- args.push(self.handle(site, src, false, (11 | u, 0))?);
- args.extend([byte, iu]);
- }
- Some(index) => {
- let stride = used.map_or(0, |u| u.stride);
- if stride < 4 || !stride.is_multiple_of(4) {
- return Err("a structured buffer of unknown stride");
- }
- args.push(self.handle(site, src, false, (12 | u, stride))?);
- args.extend([index, off]);
- }
- None => {
- args.push(self.handle(site, src, false, (11 | u, 0))?);
- args.extend([off, iu]);
- }
- }
- args.extend(&vals);
- args.resize(3 + 4, iu);
- (140, "rawBufferStore.i32")
- };
- args.push(self.s.m.i8(if typed { 0xF } else { (1u8 << count) - 1 }));
- if !typed {
- args.push(self.s.m.i32(4));
- }
- let at = self.begin_guarded(guard);
- let void = self.s.t.void;
- self.s.op(self.cur, name, Attr::NoUnwind, void, op, &args);
- self.end_guarded(at, &[]);
- return Ok(());
- }
- if let Some(f) = *format {
- if index.is_some() {
- return Err("a typed-format load by index");
- }
- let h = self.handle(site, src, false, (11 | u, 0))?;
- let Some(Operand::Vector { reg, .. }) = *data else {
- return Err("a buffer result");
- };
- let mut xs = self.format_load(h, off, f, count)?;
- if d16 {
- xs = self.d16_channels(f, xs)?;
- }
- for (k, x) in xs.into_iter().enumerate() {
- self.write(inst, Reg::V(reg + k as u8), x, guard);
- }
- return Ok(());
- }
- let r = if typed {
- if *offen || matches!(off, V::Inst(_)) || *offset != 0 {
- return Err("a typed buffer load at an offset");
- }
- if uav {
- self.s.flags |= flags::TYPED_UAV_LOADS;
- }
- let h = self.handle(site, src, false, (10 | u, 0x409))?;
- let index = index.unwrap_or(self.s.m.i32(0));
- self.s.op(
- c,
- "bufferLoad.f32",
- Attr::ReadOnly,
- self.s.t.res_ret,
- 68,
- &[h, index, iu],
- )
- } else {
- let mask = self.s.m.i8((1u8 << count) - 1);
- let align = self.s.m.i32(4);
- match index {
- // A raw buffer (stride 1) read by index: the index is the byte.
- Some(index) if used.is_some_and(|u| u.stride == 1) => {
- let byte = self.s.m.bin(c, Bin::Add, index, off);
- let h = self.handle(site, src, false, (11 | u, 0))?;
- self.s.op(
- c,
- "rawBufferLoad.f32",
- Attr::ReadOnly,
- self.s.t.res_ret,
- 139,
- &[h, byte, iu, mask, align],
- )
- }
- Some(index) => {
- let stride = used.map_or(0, |u| u.stride);
- if stride < 4 || !stride.is_multiple_of(4) {
- return Err("a structured buffer of unknown stride");
- }
- let h = self.handle(site, src, false, (12 | u, stride))?;
- self.s.op(
- c,
- "rawBufferLoad.f32",
- Attr::ReadOnly,
- self.s.t.res_ret,
- 139,
- &[h, index, off, mask, align],
- )
- }
- None => {
- let h = self.handle(site, src, false, (11 | u, 0))?;
- self.s.op(
- c,
- "rawBufferLoad.f32",
- Attr::ReadOnly,
- self.s.t.res_ret,
- 139,
- &[h, off, iu, mask, align],
- )
- }
- }
- };
- let Some(Operand::Vector { reg, .. }) = *data else {
- return Err("a buffer result");
- };
- if d16 {
- // Two f16 channels per VGPR (an odd last high half 0); the low
- // 16 bits of an integer view's (see the stores above).
- let integer = if typed { self.integer_view(src)? } else { None };
- let k16 = self.s.m.i32(16);
- let i32t = self.s.t.i32;
- for k in 0..count.div_ceil(2) {
- let mut x = None;
- for ch in (2 * k..(2 * k + 2).min(count)).rev() {
- let f = self.s.m.extract(c, r, ch);
- let mut h = self
- .s
- .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
- if let Some((int, _)) = integer {
- let bits = self.as_int(f);
- let low = self.s.m.i32(0xFFFF);
- let low = self.s.m.bin(c, Bin::And, bits, low);
- h = self.s.m.select(c, int, low, h);
- }
- x = Some(match x {
- Some(hi) => {
- let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
- self.s.m.bin(c, Bin::Or, h, hi)
- }
- None => h,
- });
- }
- self.write(inst, Reg::V(reg + k as u8), x.expect("a channel"), guard);
- }
- return Ok(());
- }
- for k in 0..count {
- let x = self.s.m.extract(c, r, k);
- let x = self.as_int(x);
- self.write(inst, Reg::V(reg + k as u8), x, guard);
- }
- Ok(())
- }
- fn export(&mut self, b: usize, i: usize) -> Result<(), Why> {
- let e = *self
- .exports
- .get(&(b, i))
- .ok_or("an export I/O raising did not see")?;
- if e.compressed {
- return Err("a compressed export");
- }
- let guard = self.guard(b, i)?;
- let mesh = self.s.mesh.is_some();
- let c = self.cur;
- if let Some(g) = guard
- && !mesh
- {
- if !(e.done && self.s.pixel) {
- return Err("a conditional export");
- }
- let t = self.s.m.bool(true);
- let kill = self.s.m.bin(c, Bin::Xor, g, t);
- self.s
- .op(c, "discard", Attr::NoUnwind, self.s.t.void, 82, &[kill]);
- }
- if mesh && e.target == Target::Primitive {
- return self.emit_indices(e, guard);
- }
- let param_row = |usage: Usage, row: u8| match usage {
- // The 2020 compiler leaves a mesh program's first entry zeroed
- // (usage "position"): its row is the one no other entry names.
- Usage::Other(0) if mesh => self.unnamed_row(),
- _ => Some(row),
- };
- // (output element, channel) per exported channel; per-primitive
- // outputs are elements of `prims`.
- let mut stores = Vec::new();
- let primitive = matches!(e.target, Target::PrimitiveParam { .. });
- let outputs = if primitive {
- &self.s.prims
- } else {
- &self.s.outputs
- };
- let by_kind = |kind: u8| outputs.iter().position(|o| o.kind == kind);
- // 16-bit vertex outputs: the halves each dword carries, as (output
- // element, channel, high half) per channel.
- let halves = match e.target {
- Target::Param { usage, row } => {
- param_row(usage, row).and_then(|r| self.half_outputs.get(&r).map(|&h| (r, h)))
- }
- _ => None,
- };
- if let Some((row, (pack2, _))) = halves {
- let packs: Vec<(u8, Option<u8>)> = self
- .half_outputs
- .iter()
- .filter(|(_, h)| h.0)
- .map(|(&r, h)| (r, h.1))
- .collect();
- for ch in 0..4u8 {
- let Some(value) = e.values[usize::from(ch)] else {
- continue;
- };
- for high in [false, true] {
- let h = 2 * ch + u8::from(high);
- let src = if pack2 {
- packed_half(outputs, &packs, row, h)
- } else {
- (!high).then_some((row, ch))
- };
- let found = src.and_then(|(r, c)| {
- outputs.iter().position(|o| {
- o.row == Some(u32::from(r)) && c >= o.col && c < o.col + o.cols
- })
- });
- if let Some(id) = found {
- let col = src.expect("found").1 - outputs[id].col;
- stores.push((id, col, value, Some(high)));
- }
- }
- }
- }
- for ch in 0..4u8 {
- let Some(value) = e.values[usize::from(ch)] else {
- continue;
- };
- if halves.is_some() {
- break;
- }
- let found = match e.target {
- Target::Color(n) => outputs
- .iter()
- .position(|o| o.kind == 16 && o.row == Some(u32::from(n)))
- .map(|id| (id, ch)),
- Target::Position(0) => by_kind(3).map(|id| (id, ch)),
- Target::Depth => match ch {
- 0 => by_kind(17)
- .or(by_kind(18))
- .or(by_kind(19))
- .map(|id| (id, 0)),
- 1 => by_kind(20).map(|id| (id, 0)),
- 2 => by_kind(14).map(|id| (id, 0)),
- _ => None,
- },
- Target::Param { usage, row } | Target::PrimitiveParam { usage, row } => {
- let row = param_row(usage, row);
- outputs
- .iter()
- .position(|o| {
- row.is_some_and(|r| o.row == Some(u32::from(r)))
- && ch >= o.col
- && ch < o.col + o.cols
- })
- .map(|id| (id, ch - outputs[id].col))
- }
- Target::Null | Target::Unread => None,
- Target::Position(n @ 1..=2) => {
- // shortcut: without the misc vector (point size, render
- // target or viewport index) pos1 and pos2 carry the clip
- // then cull distances, in semantic order.
- if outputs.iter().any(|o| matches!(o.kind, 4 | 5)) {
- return Err("render-target or viewport index exports");
- }
- let mut dists: Vec<usize> = (0..outputs.len())
- .filter(|&i| matches!(outputs[i].kind, 6 | 7))
- .collect();
- dists.sort_by_key(|&i| (outputs[i].kind, outputs[i].index));
- let flat: Vec<(usize, u8)> = dists
- .iter()
- .flat_map(|&i| (0..outputs[i].cols).map(move |c| (i, c)))
- .collect();
- // Channels past the distances the signature declares are
- // ones the clipper does not enable (`PA_CL_VS_OUT_CNTL`).
- let k = usize::from(n - 1) * 4 + usize::from(ch);
- flat.get(k).copied()
- }
- Target::Position(_) => return Err("clip, cull or point-size exports"),
- Target::Primitive => return Err("a primitive export"),
- };
- if let Some((id, col)) = found {
- stores.push((id, col, value, None));
- }
- }
- fn elements<'l>(l: &'l mut Lower, primitive: bool) -> &'l mut Vec<SigElement> {
- if primitive {
- &mut l.s.prims
- } else {
- &mut l.s.outputs
- }
- }
- if stores
- .iter()
- .any(|s| s.3.is_none() && elements(self, primitive)[s.0].half)
- {
- return Err("a 16-bit output the stage data does not mark");
- }
- // A mesh lane writes its own vertex or primitive, where it exports.
- let at = if mesh {
- let flat = self.mesh_thread();
- let limit = if let Some(m) = self.s.mesh {
- if primitive {
- m.max_primitives
- } else {
- m.max_vertices
- }
- } else {
- 0
- };
- let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX);
- let mesh_guard = if limit > 0 && threads > limit {
- let lim = self.s.m.i32(limit);
- let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, lim);
- match guard {
- Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)),
- None => Some(in_bounds),
- }
- } else {
- guard
- };
- self.begin_guarded(mesh_guard)
- } else {
- None
- };
- let (name, opcode) = match (mesh, primitive) {
- (false, _) => ("storeOutput", 5),
- (true, false) => ("storeVertexOutput", 171),
- (true, true) => ("storePrimitiveOutput", 172),
- };
- for (id, col, value, half) in stores {
- let mut x = self.i32_of(value)?;
- if let Some(high) = half {
- // An f16 half, declared a 32-bit float on the host.
- let c = self.cur;
- if high {
- let k16 = self.s.m.i32(16);
- x = self.s.m.bin(c, Bin::LShr, x, k16);
- }
- let f32t = self.s.t.f32;
- let f = self
- .s
- .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
- x = self.as_int(f);
- }
- let el = &mut elements(self, primitive)[id];
- el.usage |= 1 << col;
- let (suffix, x) = match el.comp {
- 9 if half.is_some() => (".f32", self.as_float(x)),
- 9 => {
- let f = match self.floats.get(&value) {
- Some(&f) => f,
- None => self.as_float(x),
- };
- (".f32", f)
- }
- _ => (".i32", x),
- };
- let mut args = vec![
- self.s.m.i32(id as u32),
- self.s.m.i32(0),
- self.s.m.i8(col),
- x,
- ];
- if mesh {
- args.push(self.mesh_thread());
- }
- let void = self.s.t.void;
- self.s.op(
- self.cur,
- &format!("{name}{suffix}"),
- Attr::NoUnwind,
- void,
- opcode,
- &args,
- );
- }
- self.end_guarded(at, &[]);
- Ok(())
- }
- /// Mesh: `exp prim` as the lane's primitive. Each corner takes ten
- /// bits: a 9-bit vertex index and, above it, its edge flag (bits 9, 19
- /// and 29), which only the console's edge-flag rasterisation reads and
- /// which is no part of the index. Bit 31 culls it (all indices 0: no
- /// area).
- fn emit_indices(&mut self, e: &Export, guard: Option<V>) -> Result<(), Why> {
- let v = e.values[0].ok_or("a primitive export without its indices")?;
- let x = self.i32_of(v)?;
- let flat = self.mesh_thread();
- let guard = if let Some(mesh) = self.s.mesh {
- let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX);
- if threads > mesh.max_primitives {
- let p = self.s.m.i32(mesh.max_primitives);
- let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, p);
- match guard {
- Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)),
- None => Some(in_bounds),
- }
- } else {
- guard
- }
- } else {
- guard
- };
- let at = self.begin_guarded(guard);
- let c = self.cur;
- let z = self.s.m.i32(0);
- let mut culled = self.s.m.cmp(c, pred::SLT, x, z);
- // A primitive that names a vertex past the declared count, or one
- // no lane writes (lane n writes vertex n alone), is culled too: the
- // host would read a vertex nothing set, at any position.
- let written = self.s.mesh.map(|m| {
- m.max_vertices
- .min(self.s.threads.map_or(u32::MAX, |t| t[0]))
- });
- let mut indices = [z; 3];
- for (k, slot) in indices.iter_mut().enumerate() {
- let (shift, mask) = (self.s.m.i32(10 * k as u32), self.s.m.i32(0x1FF));
- let i = self.s.m.bin(c, Bin::LShr, x, shift);
- let i = self.s.m.bin(c, Bin::And, i, mask);
- if let Some(n) = written {
- let n = self.s.m.i32(n);
- let past = self.s.m.cmp(c, pred::IUGE, i, n);
- culled = self.s.m.bin(c, Bin::Or, culled, past);
- }
- *slot = i;
- }
- let mut args = vec![flat];
- for i in indices {
- args.push(self.s.m.select(c, culled, z, i));
- }
- let void = self.s.t.void;
- self.s
- .op(c, "emitIndices", Attr::NoUnwind, void, 169, &args);
- self.end_guarded(at, &[]);
- Ok(())
- }
- /// The per-vertex arbitrary row no mesh output entry names but one
- /// (the 2020 compiler's zeroed entry).
- fn unnamed_row(&self) -> Option<u8> {
- let StageIo::Ms(ms) = &self.x.native.io else {
- return None;
- };
- let named = |r: u32| {
- ms.outputs
- .iter()
- .any(|o| o.param & 0x80 == 0 && o.usage != Usage::Other(0) && u32::from(o.row) == r)
- };
- let free: std::collections::BTreeSet<u32> = self
- .s
- .outputs
- .iter()
- .filter(|o| o.kind == 0)
- .filter_map(|o| o.row)
- .filter(|&r| !named(r))
- .collect();
- match free.into_iter().collect::<Vec<_>>()[..] {
- [r] => u8::try_from(r).ok(),
- _ => None,
- }
- }
- fn exit(&mut self, b: usize) -> Result<(), Stop> {
- let offset = self.x.p.blocks[b]
- .insts
- .last()
- .map_or(self.x.p.blocks[b].offset, |i| i.machine.offset);
- let term = match self.x.st.exits[b] {
- LaneExit::Jump(t) if self.counters.contains_key(&t) && self.rpo[t] <= self.rpo[b] => {
- let ok = self.count_iteration(t, pred::IULT);
- let abort = self.abort_block();
- Term::CondBr(ok, self.block[t].expect("reachable"), abort)
- }
- LaneExit::Jump(t) => {
- self.enter_loop(b, t, self.cur);
- Term::Br(self.block[t].expect("reachable"))
- }
- LaneExit::Branch {
- when,
- taken,
- not_taken,
- } => {
- // A negated condition branches the other way round.
- let (cond, taken, not_taken) = match self.x.st.bools.node(when) {
- _ if self.x.st.wide.contains(&b) => {
- let c = self.wave_wide(b, when).map_err(|w| unsupported(offset, w))?;
- (c, taken, not_taken)
- }
- Some((atom, Bool::TRUE, Bool::FALSE)) => {
- let a = self
- .atom(atom, self.cur)
- .map_err(|w| unsupported(offset, w))?;
- (a, not_taken, taken)
- }
- _ => {
- let c = self
- .boolean(when, self.cur)
- .map_err(|w| unsupported(offset, w))?;
- (c, taken, not_taken)
- }
- };
- // A back edge is taken only below the iteration limit.
- let back =
- |l: &Self, to: usize| l.counters.contains_key(&to) && l.rpo[to] <= l.rpo[b];
- // (No `xor` of a compare: a loop exit testing one hung the
- // AMD driver.)
- let cond = if back(self, taken) {
- let ok = self.count_iteration(taken, pred::IULT);
- self.s.m.bin(self.cur, Bin::And, cond, ok)
- } else if back(self, not_taken) {
- let stop = self.count_iteration(not_taken, pred::IUGE);
- self.s.m.bin(self.cur, Bin::Or, cond, stop)
- } else {
- cond
- };
- // Critical edges get a block of their own, so loops have
- // dedicated exits and preheaders as DXC emits them.
- let (t, f) = (self.edge(b, taken), self.edge(b, not_taken));
- for (to, via) in [(taken, t), (not_taken, f)] {
- if !back(self, to) {
- // From an edge block, or from here.
- let from = if Some(via) == self.block[to] {
- self.cur
- } else {
- via
- };
- self.enter_loop(b, to, from);
- }
- }
- Term::CondBr(cond, t, f)
- }
- LaneExit::End => {
- if self.s.pixel && !self.exported[b] && !self.has_done_export(b) {
- // A lane leaving without its final export was killed.
- let t = self.s.m.bool(true);
- self.s
- .op(self.cur, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]);
- }
- Term::Ret
- }
- LaneExit::Indirect => return Err(unsupported(offset, "an indirect jump")),
- };
- let _ = Exit::End;
- self.s.m.terminate(self.cur, term);
- Ok(())
- }
- /// A forward edge into loop header `to` (from DXIL block `via`) starts
- /// its count at 0.
- fn enter_loop(&mut self, _from: usize, to: usize, via: usize) {
- if let Some((_, incoming)) = self.counters.get_mut(&to) {
- let z = self.s.m.i32(0);
- incoming.push((z, via));
- }
- }
- /// A back edge to header `to` (a back edge keeps its block, no
- /// critical-edge block): the count goes up; the result compares it with
- /// [`LOOP_LIMIT`] by `p` (below: go on; at or above: stop).
- fn count_iteration(&mut self, to: usize, p: u8) -> V {
- let c = self.cur;
- let (phi, _) = self.counters[&to];
- let one = self.s.m.i32(1);
- let next = self.s.m.bin(c, Bin::Add, phi, one);
- self.s.m.tag(phi, Tag::Counter);
- self.s.m.tag(next, Tag::Counter);
- // Per stage unless the switch names one: a loop that never meets its
- // exit (a count read from a buffer the host has not got yet, say)
- // runs to the limit in every lane. A million iterations a pixel
- // hung the GPU for seconds a draw until Windows reset it
- // (PS_Textured_Eight, 2026-11-24, run 12).
- // shortcut: a pixel loop past 128 iterations, a vertex or mesh loop
- // past 256 or a compute loop past 4,096 is cut short. (They were
- // 1,024, 4,096 and 65,536: the opening cutscene then lost the card
- // 14-25 frames in, in a minimap or shadow mesh draw; with every
- // loop cut at 64 it ran 90 frames. Raise them again once shaders
- // stop reading data that is not there yet.)
- let limit = match super::loop_limit() {
- LOOP_LIMIT if self.s.pixel => 1 << 7,
- LOOP_LIMIT if self.s.mesh.is_some() || self.s.threads.is_none() => 1 << 8,
- LOOP_LIMIT => 1 << 12,
- named => named,
- };
- let limit = self.s.m.i32(limit);
- self.counters
- .get_mut(&to)
- .expect("header")
- .1
- .push((next, c));
- let over = self.s.m.cmp(c, p, next, limit);
- self.s.m.tag(over, Tag::Counter);
- over
- }
- /// The block a lane stopped by [`LOOP_LIMIT`] leaves through.
- fn abort_block(&mut self) -> usize {
- if let Some(a) = self.abort {
- return a;
- }
- let a = self.s.m.new_block();
- if self.s.pixel {
- let t = self.s.m.bool(true);
- self.s
- .op(a, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]);
- }
- self.s.m.terminate(a, Term::Ret);
- self.abort = Some(a);
- a
- }
- /// The DXIL block a branch from IR block `from` to `to` goes to.
- fn edge(&mut self, from: usize, to: usize) -> usize {
- let target = self.block[to].expect("reachable");
- let preds = self.x.p.blocks[to]
- .preds
- .iter()
- .filter(|&&q| self.block[q].is_some())
- .count();
- // Back edges stay as they are: the exiting block is the latch.
- if preds < 2 || self.rpo[to] <= self.rpo[from] {
- return target;
- }
- let e = self.s.m.new_block();
- self.s.m.terminate(e, Term::Br(target));
- self.edges.insert((from, to), e);
- e
- }
- fn fill_phis(&mut self) -> Result<(), Stop> {
- let p = self.x.p;
- // Lane-mask joins first (what an edge brings may ask for more joins,
- // of masks and of numbers): each edge's mask as the structure
- // tracked it, a constant or a scalar-built one included.
- let st = self.x.st;
- while let Some((v, b, i)) = self.pending_masks.pop() {
- let phi = &p.blocks[b].phis[i];
- let offset = p.blocks[b].offset;
- let args = st
- .phi_masks
- .get(&phi.value)
- .ok_or_else(|| unsupported(offset, "a lane-mask join of an untracked mask"))?;
- let mut incoming = Vec::new();
- for (n, &q) in p.blocks[b].preds.iter().enumerate() {
- let Some(qb) = self.tail[q] else { continue };
- let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb);
- let x = self.boolean(args[n], qb).map_err(|w| unsupported(offset, w))?;
- incoming.push((x, qb));
- }
- self.s.m.set_phi(v, incoming);
- }
- // A join that only another join reads is read wherever that one is. Left
- // unmarked, a value without a DXIL form coming into it became zero without a
- // word (the looked-up tint of the material resolve programs, whose size
- // computation had no value, was zero in every lane that way).
- // shortcut: only with `VICTORY_STRICT_JOINS` set (the offline pack
- // listing sets it to count them): 40 programs that translate today
- // stop by name with it (vehicle paint pixel shaders at "the first
- // half of an interpolation", foliage mesh shaders); until those are
- // lowered they keep drawing with that zero.
- static STRICT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
- let strict = *STRICT.get_or_init(|| std::env::var_os("VICTORY_STRICT_JOINS").is_some());
- let mut work: Vec<Value> = if strict {
- self.read_phis.iter().copied().collect()
- } else {
- Vec::new()
- };
- while let Some(v) = work.pop() {
- let Some(&(b, i)) = self.phi_at.get(&v) else {
- continue;
- };
- for &a in &p.blocks[b].phis[i].args {
- if self.phi_at.contains_key(&a) && self.read_phis.insert(a) {
- work.push(a);
- }
- }
- }
- for (v, b, i) in std::mem::take(&mut self.data_phis) {
- let phi = &p.blocks[b].phis[i];
- let bit = phi.reg == Reg::Scc;
- // A join of numbers with dead registers (`dead`): the paths that bring those
- // never read the result, so they bring zero. Not for a join that is itself a
- // lane mask (a ballot gives that one as data).
- let st = self.x.st;
- let numbers = !bit
- && !st.masks.contains_key(&phi.value)
- && !st.highs.contains_key(&phi.value)
- && phi
- .args
- .iter()
- .any(|a| matches!(self.vals.get(a), Some(Val::I32(_))));
- let mut incoming = Vec::new();
- for (n, &q) in p.blocks[b].preds.iter().enumerate() {
- let Some(qb) = self.tail[q] else { continue };
- let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb);
- let arg = phi.args[n];
- if self.read_phis.contains(&phi.value) && !self.vals.contains_key(&arg) {
- let _ = self.lazy_barycentric(arg);
- // A root parameter nothing read before the join (user
- // data is loaded on first use, in the entry block).
- if !self.vals.contains_key(&arg)
- && let Some(&(param, dword)) = self.params.get(&arg)
- {
- let val = self.user(param, dword);
- self.vals.insert(arg, val);
- }
- }
- let x = match (self.vals.get(&arg).copied(), bit) {
- (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x,
- (Some(Val::Missing(_)) | None, false)
- if numbers && self.dead(arg, &mut Vec::new()) =>
- {
- self.s.m.i32(0)
- }
- // A lane mask joined with numbers (a traversal that keeps its lanes' masks on
- // a stack with its node numbers): the mask comes as the number it is, the
- // ballot of its lanes where it is written.
- (Some(Val::Missing(_)) | None, false)
- if self.read_phis.contains(&phi.value)
- && self.mask_data == MaskData::Console
- && (st.masks.contains_key(&arg) || st.highs.contains_key(&arg)) =>
- {
- match self.mask_dword(arg) {
- Ok(x) => x,
- Err(why) => return Err(Stop::Retry(phi.value, why)),
- }
- }
- // SCC of a mask operation ("some lane is left") joined with a scalar test:
- // the compiler branches around code that sets SCC and tests SCC after it,
- // the skip bringing "no lane" along. As data it is "some lane of the wave
- // has the bit" - right only if the wave took that skip together, as the
- // console does: a lane that skipped alone would bring "some lane" where the
- // console has the skipped code's SCC. So the branch must be one the wave
- // takes together; else its region is named for `emit`'s retry to widen it.
- (Some(Val::Missing(_)) | None, true)
- if self.read_phis.contains(&phi.value)
- && self.mask_data == MaskData::Console
- && st.scc_some.contains_key(&arg) =>
- {
- let per_lane = !st.wide.contains(&q)
- && matches!(st.exits[q], LaneExit::Branch { when, .. }
- if !st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))));
- if per_lane {
- for &other in p.blocks[b].preds.iter().filter(|&&o| o != q) {
- need(other);
- }
- return Err(Stop::Retry(phi.value, LANE_MASK));
- }
- match self.scc_some(arg) {
- Ok(x) => x,
- Err(why) => return Err(Stop::Retry(phi.value, why)),
- }
- }
- (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => {
- return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values"));
- }
- (Some(Val::Missing(why)), _) if self.read_phis.contains(&phi.value) => {
- return Err(Stop::Retry(phi.value, why));
- }
- _ if self.read_phis.contains(&phi.value) => {
- return Err(Stop::Retry(phi.value, "a join of mismatched values"));
- }
- _ if bit => self.s.m.bool(false),
- _ => self.s.m.i32(0),
- };
- incoming.push((x, qb));
- }
- self.s.m.set_phi(v, incoming);
- }
- for (phi, incoming) in std::mem::take(&mut self.counters).into_values() {
- self.s.m.set_phi(phi, incoming);
- }
- Ok(())
- }
- }
- /// The DXIL interpolation mode of a kind of barycentrics (none for the
- /// pull model).
- fn interp_mode(kind: Barycentric) -> Option<u8> {
- Some(match kind {
- Barycentric::PerspectiveCenter => 2,
- Barycentric::PerspectiveCentroid => 3,
- Barycentric::PerspectiveSample => 6,
- Barycentric::LinearCenter => 4,
- Barycentric::LinearCentroid => 5,
- Barycentric::LinearSample => 7,
- Barycentric::PerspectivePullModel => return None,
- })
- }
- #[cfg(test)]
- mod tests {
- use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower};
- use crate::native::{
- ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
- };
- use crate::{io, ir, resource, structure};
- const S_ENDPGM: u32 = 0xBF81_0000;
- #[test]
- fn packed_pixel_inputs_find_their_second_row() {
- use super::super::container::SigElement;
- use super::half_input_partners;
- use crate::native::{PsInput, Usage};
- let entry = |row, row2, pack2| PsInput {
- usage: Usage::Generic,
- row,
- mask: 0xF,
- attr: row,
- flat: false,
- fp16: true,
- pack2,
- row2,
- };
- let element = |row| SigElement {
- name: "TEXCOORD".into(),
- index: row,
- kind: 0,
- comp: 9,
- interp: 2,
- row: Some(row),
- col: 0,
- cols: 4,
- usage: 0,
- half: true,
- };
- // Rows 0 and 3 pack and leave their second row out; 5 names its
- // own (6). Unnamed 16-bit rows: 1, 4, 6, 7.
- let io = StageIo::Ps {
- inputs: vec![entry(0, 0, true), entry(3, 3, true), entry(5, 6, true)],
- input_addr: 0,
- db_shader_control: 0,
- patches: vec![],
- };
- let sig: Vec<_> = [0, 1, 3, 4, 5, 6, 7].map(element).into();
- let p = half_input_partners(&io, &sig);
- assert_eq!(p.get(&0), Some(&1));
- assert_eq!(p.get(&3), Some(&4));
- assert_eq!(p.get(&5), None);
- }
- /// The packed pedestrian layouts of the title: an element
- /// behind another one in its register follows in the first parameter
- /// with a dword left, and is not a half of its register's row.
- #[test]
- fn packed_elements_behind_another_take_the_first_free_dword() {
- use super::super::container::SigElement;
- use super::packed_half;
- let element = |index, row, col, cols| SigElement {
- name: "TEXCOORD".into(),
- index,
- kind: 0,
- comp: 9,
- interp: 2,
- row: Some(row),
- col,
- cols,
- usage: 0,
- half: true,
- };
- // MS_VS_PedTransformPreSkinD_Packed 005fe88ec1bdc0c7 and its pixel
- // shader 93667197d3d05e1c: TEXCOORD6 is one value at register 4
- // column 3; parameter 3 (rows 6 and 7) carries it in dword 3.
- let sig = vec![
- element(1, 2, 0, 4),
- element(2, 3, 0, 4),
- element(4, 4, 0, 3),
- element(6, 4, 3, 1),
- element(3, 5, 0, 4),
- element(5, 6, 0, 4),
- element(7, 7, 0, 2),
- element(9, 9, 0, 3),
- element(11, 10, 0, 3),
- element(15, 12, 0, 4),
- ];
- let packs = [
- (2, Some(3)),
- (4, Some(5)),
- (6, Some(7)),
- (9, Some(10)),
- (12, None),
- ];
- let at = |a, h| packed_half(&sig, &packs, a, h);
- // Parameter 2: TEXCOORD4's three values, a zero half, TEXCOORD3.
- assert_eq!(at(4, 2), Some((4, 2)));
- assert_eq!(at(4, 3), None);
- assert_eq!(at(4, 4), Some((5, 0)));
- assert_eq!(at(4, 7), Some((5, 3)));
- // Parameter 3: TEXCOORD5, TEXCOORD7, then TEXCOORD6 alone.
- assert_eq!(at(6, 3), Some((6, 3)));
- assert_eq!(at(6, 5), Some((7, 1)));
- assert_eq!(at(6, 6), Some((4, 3)));
- assert_eq!(at(6, 7), None);
- // Parameters without such an element are as before.
- assert_eq!(at(9, 3), None);
- assert_eq!(at(9, 4), Some((10, 0)));
- assert_eq!(at(12, 3), Some((12, 3)));
- assert_eq!(at(12, 4), None);
- // The common layout (29805d23a495cdf8): TEXCOORD7 is two values at
- // register 1 columns 2-3; parameter 0 is TEXCOORD0, TEXCOORD1,
- // TEXCOORD7.
- let sig = vec![
- element(0, 1, 0, 2),
- element(7, 1, 2, 2),
- element(1, 2, 0, 4),
- element(2, 3, 0, 4),
- element(4, 4, 0, 3),
- ];
- let packs = [(3, Some(4)), (1, Some(2))];
- let at = |a, h| packed_half(&sig, &packs, a, h);
- assert_eq!(at(1, 1), Some((1, 1)));
- assert_eq!(at(1, 2), Some((2, 0)));
- assert_eq!(at(1, 5), Some((2, 3)));
- assert_eq!(at(1, 6), Some((1, 2)));
- assert_eq!(at(1, 7), Some((1, 3)));
- assert_eq!(at(3, 6), Some((4, 2)));
- assert_eq!(at(3, 7), None);
- // A row no element holds gives nothing, as before.
- assert_eq!(packed_half(&sig, &[(8, None)], 8, 0), None);
- }
- /// Whether a synthetic compute program translates with these input registers.
- fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> {
- let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
- let native = NativeProgram {
- stage: HwStage::Cs,
- wave64: false,
- vgprs: 256,
- layout: vec![],
- used: vec![],
- io: StageIo::Cs(ComputeIo {
- rsrc2,
- threads: [1, 1, 1],
- }),
- code,
- };
- let p = ir::build(&native.code, false, 256).unwrap();
- let st = structure::structure(&p).unwrap();
- let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
- let io = io::raise(&p, &native).unwrap();
- lower(&Parts {
- native: &native,
- p: &p,
- st: &st,
- io: &io,
- res: &res,
- inputs: vec![],
- outputs: vec![],
- prims: vec![],
- mesh_stride: 0,
- })
- .map(|_| ())
- }
- /// Lowers a compute program with the root parameters `layout` (in user
- /// SGPRs from s0 on) and the used resources `used`.
- fn lower_with(
- words: &[u32],
- layout: Vec<RootParam>,
- used: Vec<UsedResource>,
- ) -> Result<Lowered, crate::ShaderError> {
- lower_wave(words, layout, used, false)
- }
- /// [`lower_with`] in wave64 if `wave64`.
- fn lower_wave(
- words: &[u32],
- layout: Vec<RootParam>,
- used: Vec<UsedResource>,
- wave64: bool,
- ) -> Result<Lowered, crate::ShaderError> {
- let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
- let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum();
- let native = NativeProgram {
- stage: HwStage::Cs,
- wave64,
- vgprs: 256,
- layout,
- used,
- io: StageIo::Cs(ComputeIo {
- // The layout's user SGPRs (at least two), 512 bytes of LDS.
- rsrc2: 1 << 15 | sgprs.max(2) << 1,
- threads: [1, 1, 1],
- }),
- code,
- };
- let p = ir::build(&native.code, wave64, 256).unwrap();
- let st = structure::structure(&p).unwrap();
- let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
- let io = io::raise(&p, &native).unwrap();
- lower(&Parts {
- native: &native,
- p: &p,
- st: &st,
- io: &io,
- res: &res,
- inputs: vec![],
- outputs: vec![],
- prims: vec![],
- mesh_stride: 0,
- })
- }
- /// Root parameter `slot` in user SGPRs from `user_data` on.
- fn root(root: RootType, user_data: u8, slot: u8) -> RootParam {
- RootParam {
- root,
- table_offset_dwords: 0,
- sgprs: if root == RootType::Descriptor { 2 } else { 1 },
- base_register: 0,
- user_data,
- slot,
- }
- }
- /// Lowers a one-thread compute program that copies four root constants
- /// (s0..s3) into v1..v4, runs `body`, and stores v0 to a raw buffer from a
- /// descriptor table, so the vector instructions in `body` have an effect.
- fn lowers_valu(body: &[u32]) -> Result<(), crate::ShaderError> {
- let mut words = vec![
- 0xBE85_0380, // s_mov_b32 s5, 0
- 0xF408_0202, // s_load_dwordx4 s[8:11], s[4:5], 0
- 0xFA00_0000,
- ];
- // v_mov_b32 v1..v4, s0..s3
- words.extend((0..4u32).map(|i| 0x7E00_0200 | (i + 1) << 17 | i));
- words.extend_from_slice(body);
- words.extend_from_slice(&[
- 0xE070_0000, // buffer_store_dword v0, off, s[8:11], 0
- 0x8002_0000,
- S_ENDPGM,
- ]);
- let constants = RootParam {
- sgprs: 4,
- ..root(RootType::Constants, 0, 0)
- };
- let buffer = UsedResource {
- kind: ResourceType::Uav,
- root: RootType::Table,
- table_offset_dwords: 0,
- lower_bound: 0,
- stride: 0,
- dwords: 4,
- user_data: 4,
- slot: 1,
- };
- lower_with(
- &words,
- vec![constants, root(RootType::Table, 4, 1)],
- vec![buffer],
- )
- .map(|_| ())
- }
- #[test]
- fn the_24_bit_multiplies_lower_both_halves() {
- // VOP2 `op v0, v1, v2`: v_mul_i32_i24 and v_mul_u32_u24 (the low
- // dword) and v_mul_hi_i32_i24 and v_mul_hi_u32_u24 (the high one).
- for op in [0x09u32, 0x0A, 0x0B, 0x0C] {
- let word = op << 25 | 2 << 9 | 0x101;
- lowers_valu(&[word]).unwrap_or_else(|e| panic!("VOP2 {op:#x}: {e}"));
- }
- }
- #[test]
- fn buffer_cache_invalidations_lower_as_no_ops() {
- // MUBUF opcode 0x071/0x072 with no data operand: the title asks the
- // host to invalidate its cached view of a buffer.
- assert!(lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl0_inv");
- assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv");
- }
- #[test]
- fn sums_of_absolute_differences_lower() {
- // VOP3 `op v0, v1, v2, v3`: v_sad_u8, v_sad_hi_u8, v_sad_u16,
- // v_sad_u32 and v_msad_u8.
- for op in [0x15Au32, 0x15B, 0x15C, 0x15D, 0x171] {
- let words = [0xD400_0000 | op << 16, 0x101 | 0x102 << 9 | 0x103 << 18];
- lowers_valu(&words).unwrap_or_else(|e| panic!("VOP3 {op:#x}: {e}"));
- }
- }
- #[test]
- fn a_scalar_carry_chain_reaches_the_select() {
- // The high dword of a 64-bit add or subtract, then a select on the
- // carry (borrow) the high half leaves in SCC, and a branch on it
- // (only code with an effect needs its operands).
- let add = [
- 0xBE80_03C1, // s_mov_b32 s0, -1
- 0xBE81_0380, // s_mov_b32 s1, 0
- 0x8000_8100, // s_add_u32 s0, s0, 1
- 0x8201_8001, // s_addc_u32 s1, s1, 0
- 0x8502_0001, // s_cselect_b32 s2, s1, s0
- 0xBF07_8002, // s_cmp_lg_u32 s2, 0
- 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
- 0xBE83_0380, // s_mov_b32 s3, 0
- S_ENDPGM,
- ];
- let sub = [
- 0xBE80_0380, // s_mov_b32 s0, 0
- 0xBE81_0380, // s_mov_b32 s1, 0
- 0x8080_8100, // s_sub_u32 s0, s0, 1
- 0x8281_8001, // s_subb_u32 s1, s1, 0
- 0x8502_0001, // s_cselect_b32 s2, s1, s0
- 0xBF07_8002, // s_cmp_lg_u32 s2, 0
- 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
- 0xBE83_0380, // s_mov_b32 s3, 0
- S_ENDPGM,
- ];
- for words in [add, sub] {
- lowers(&words, 0).unwrap();
- }
- }
- fn perm_features(selector: u32) -> u64 {
- // Synthetic compute shader:
- // v0 is the thread ID and can supply a dynamic selector.
- // Store the result in LDS to keep the permutation live.
- let words = [
- 0x7E02_02FFu32,
- 0x817F_34AB,
- 0x7E04_02FF,
- 0xFE01_56CD,
- 0xD744_0003,
- 257 | (258 << 9) | (selector << 18),
- 0x3408_0082,
- 0xD834_0000,
- 0x0000_0304,
- S_ENDPGM,
- ];
- let code: Vec<u8> = words.iter()
- .flat_map(|w| w.to_le_bytes())
- .collect();
- let native = NativeProgram {
- stage: HwStage::Cs,
- wave64: false,
- vgprs: 256,
- layout: vec![],
- used: vec![],
- io: StageIo::Cs(ComputeIo {
- rsrc2: 1 << 15,
- threads: [64, 1, 1],
- }),
- code,
- };
- let p = ir::build(&native.code, false, 256).unwrap();
- assert!(p.blocks.iter()
- .flat_map(|b| &b.insts)
- .any(|i| i.name() == "v_perm_b32"));
- let st = structure::structure(&p).unwrap();
- let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
- let io = io::raise(&p, &native).unwrap();
- let emitted = lower(&Parts {
- native: &native,
- p: &p,
- st: &st,
- io: &io,
- res: &res,
- inputs: vec![],
- outputs: vec![],
- prims: vec![],
- mesh_stride: 0,
- }).unwrap();
- let container =
- crate::Container::parse(&emitted.dxil).unwrap();
- let features =
- container.part(crate::FourCC::SFI0).unwrap();
- u64::from_le_bytes(features.data.try_into().unwrap())
- }
- #[test]
- fn perm_constant_selector_needs_no_int64() {
- assert_eq!(perm_features(128) & 0x8000, 0);
- }
- #[test]
- fn perm_dynamic_selector_needs_no_int64() {
- assert_eq!(
- perm_features(256) & 0x8000,
- 0,
- "dynamic v_perm_b32 must not require INT64"
- );
- }
- #[test]
- fn a_descriptor_selected_by_scc_picks_its_heap_index() {
- // Two buffer descriptors loaded from the table at s0, one picked by
- // a root constant (s1) with s_cselect_b64 per half, and loaded
- // through by index and stored to LDS so the load is needed.
- let words = [
- 0xBE84_0300, // s_mov_b32 s4, s0
- 0xBE85_0380, // s_mov_b32 s5, 0
- 0xF408_0202,
- 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null
- 0xF408_0302,
- 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10
- 0xBF06_8001, // s_cmp_eq_u32 s1, 0
- 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13]
- 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15]
- 0xE030_2000,
- 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen
- 0xD834_0000,
- 0x0000_0100, // ds_write_b32 v0, v1
- S_ENDPGM,
- ];
- let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)];
- // Both are structured buffers of dwords in the table's range.
- let used = || {
- vec![UsedResource {
- kind: ResourceType::Srv,
- root: RootType::Table,
- table_offset_dwords: 0,
- lower_bound: 0,
- stride: 4,
- dwords: 4,
- user_data: 0,
- slot: 0,
- }]
- };
- lower_with(&words, layout(), used()).unwrap();
- }
- /// Tables of 2D textures at s0 and samplers at s1.
- fn texture_tables() -> (Vec<RootParam>, Vec<UsedResource>) {
- let range = |kind, user_data, slot| UsedResource {
- kind,
- root: RootType::Table,
- table_offset_dwords: 0,
- lower_bound: 0,
- stride: 0,
- dwords: if kind == ResourceType::Sampler { 4 } else { 8 },
- user_data,
- slot,
- };
- (
- vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)],
- vec![
- range(ResourceType::Srv, 0, 0),
- range(ResourceType::Sampler, 1, 1),
- ],
- )
- }
- #[test]
- fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() {
- use crate::resource::tests::{
- WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32,
- };
- for (words, wave64) in [
- (WATERFALL_FETCHED_WAVE32, false),
- (WATERFALL_FETCHED_WAVE64, true),
- (WATERFALL_PICKED_WAVE32, false),
- ] {
- let (layout, used) = texture_tables();
- let l = lower_wave(words, layout, used, wave64).unwrap();
- // The loop's reads of the first lane became each lane's own
- // dwords: no wave operation is left.
- assert_eq!(l.nonuniform_handles, 1);
- assert!(!l.wave_ops);
- }
- }
- /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first.
- pub(crate) fn texture_and_uav_tables() -> (Vec<RootParam>, Vec<UsedResource>) {
- let (layout, mut used) = texture_tables();
- used.push(UsedResource {
- kind: ResourceType::Uav,
- root: RootType::Table,
- table_offset_dwords: 16,
- lower_bound: 0,
- stride: 0,
- dwords: 4,
- user_data: 0,
- slot: 0,
- });
- (layout, used)
- }
- #[test]
- fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() {
- use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32};
- for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] {
- let (layout, used) = texture_and_uav_tables();
- let l = lower_wave(words, layout, used, false).unwrap();
- // One image handle, from the join's per-lane heap index.
- assert_eq!(l.nonuniform_handles, 1);
- assert!(!l.wave_ops);
- }
- }
- #[test]
- fn scalar_bit_tests_lower() {
- // Each tests one bit of a constant into SCC and branches on it (only
- // code with an effect needs its operands).
- let tail = [
- 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
- 0xBE84_0380, // s_mov_b32 s4, 0
- S_ENDPGM,
- ];
- let bit_tests: [&[u32]; 4] = [
- &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3
- &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3
- &[
- 0xBE80_0387, // s_mov_b32 s0, 7
- 0xBE81_0380, // s_mov_b32 s1, 0
- 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3
- ],
- &[
- 0xBE80_0387, // s_mov_b32 s0, 7
- 0xBE81_0380, // s_mov_b32 s1, 0
- 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3
- ],
- ];
- for head in bit_tests {
- let words: Vec<u32> = head.iter().chain(&tail).copied().collect();
- lowers(&words, 0).unwrap();
- }
- }
- #[test]
- #[ignore = "ours marks joins read through joins only with VICTORY_STRICT_JOINS (40 programs stop otherwise)"]
- fn a_missing_value_stays_missing_through_two_live_joins() {
- let mut words = [
- 0xF490_0180,
- 0, // s_memtime s[6:7]
- 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X)
- 0xBF85_0001, // skip the first overwrite
- 0xBE86_0380, // s_mov_b32 s6, 0
- 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y)
- 0xBF85_0001, // skip the second overwrite
- 0xBE86_0381, // s_mov_b32 s6, 1
- 0xBF07_8006, // s_cmp_lg_u32 s6, 0
- 0xBF85_0001, // use the result to branch
- 0xBE83_0380,
- S_ENDPGM,
- ];
- let group_ids_xy = 3 << 7;
- // Compare to a direct read so future timestamp support works in both cases.
- let refusal = |code: &[u32]| match lowers(code, group_ids_xy) {
- Ok(()) => None,
- Err(crate::ShaderError::Unsupported { what, .. }) => Some(what),
- Err(error) => panic!("{error}"),
- };
- let direct = [&words[..2], &words[8..]].concat();
- assert_eq!(refusal(&words), refusal(&direct));
- words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead
- lowers(&words, group_ids_xy).expect("dead timestamp");
- }
- #[test]
- fn buffer_formats_by_number() {
- // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM,
- // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT.
- assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm)));
- assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm)));
- assert_eq!(
- buffer_format(50),
- Some((&[10, 10, 10, 2][..], Numeric::Unorm))
- );
- assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float)));
- assert_eq!(
- buffer_format(77),
- Some((&[32, 32, 32, 32][..], Numeric::Float))
- );
- // Invalid, past the table.
- assert_eq!(buffer_format(0), None);
- assert_eq!(buffer_format(78), None);
- }
- #[test]
- fn packed_buffer_formats_by_number() {
- // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43,
- // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT
- // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first.
- assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm)));
- assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float)));
- assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm)));
- assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float)));
- assert_eq!(
- buffer_format(44),
- Some((&[2, 10, 10, 10][..], Numeric::Unorm))
- );
- assert_eq!(
- buffer_format(45),
- Some((&[2, 10, 10, 10][..], Numeric::Snorm))
- );
- assert_eq!(
- buffer_format(46),
- Some((&[2, 10, 10, 10][..], Numeric::Uscaled))
- );
- assert_eq!(
- buffer_format(47),
- Some((&[2, 10, 10, 10][..], Numeric::Sscaled))
- );
- assert_eq!(
- buffer_format(48),
- Some((&[2, 10, 10, 10][..], Numeric::Uint))
- );
- assert_eq!(
- buffer_format(49),
- Some((&[2, 10, 10, 10][..], Numeric::Sint))
- );
- }
- /// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as
- /// `legacyF16ToF32` widens it.
- fn half(h: u32) -> f32 {
- let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023);
- let v = match e {
- 0 => m as f32 * 2f32.powi(-24),
- 31 if m == 0 => f32::INFINITY,
- 31 => f32::NAN,
- _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25),
- };
- if s == 1 { -v } else { v }
- }
- #[test]
- fn small_floats_widen_as_halves() {
- // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a
- // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec.
- let f11 = |x: u32| half(x << half_shift(11));
- let f10 = |x: u32| half(x << half_shift(10));
- assert_eq!(f11(0), 0.0);
- assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal
- assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal
- assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal
- assert_eq!(f11(0x3C0), 1.0);
- assert_eq!(f11(0x3E0), 1.5);
- assert_eq!(f11(0x7BF), 65024.0); // largest
- assert_eq!(f11(0x7C0), f32::INFINITY);
- assert!(f11(0x7C1).is_nan());
- assert_eq!(f10(0x001), 2f32.powi(-19));
- assert_eq!(f10(0x020), 2f32.powi(-14));
- assert_eq!(f10(0x1E0), 1.0);
- assert_eq!(f10(0x3DF), 64512.0);
- assert_eq!(f10(0x3E0), f32::INFINITY);
- assert!(f10(0x3FF).is_nan());
- // A 16-bit float is a half already, sign included.
- assert_eq!(half(0xBC00 << half_shift(16)), -1.0);
- }
- }
|