HLOperationLower.cpp 261 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // HLOperationLower.cpp //
  4. // Copyright (C) Microsoft Corporation. All rights reserved. //
  5. // This file is distributed under the University of Illinois Open Source //
  6. // License. See LICENSE.TXT for details. //
  7. // //
  8. // Lower functions to lower HL operations to DXIL operations. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #include "dxc/HLSL/DxilModule.h"
  12. #include "dxc/HLSL/DxilOperations.h"
  13. #include "dxc/HLSL/HLMatrixLowerHelper.h"
  14. #include "dxc/HLSL/HLModule.h"
  15. #include "dxc/HLSL/DxilUtil.h"
  16. #include "dxc/HLSL/HLOperationLower.h"
  17. #include "dxc/HLSL/HLOperationLowerExtension.h"
  18. #include "dxc/HLSL/HLOperations.h"
  19. #include "dxc/HlslIntrinsicOp.h"
  20. #include "llvm/IR/GetElementPtrTypeIterator.h"
  21. #include "llvm/IR/IRBuilder.h"
  22. #include "llvm/IR/Instructions.h"
  23. #include "llvm/IR/Module.h"
  24. #include <unordered_set>
  25. using namespace llvm;
  26. using namespace hlsl;
  27. struct HLOperationLowerHelper {
  28. OP &hlslOP;
  29. Type *voidTy;
  30. Type *f32Ty;
  31. Type *i32Ty;
  32. llvm::Type *i1Ty;
  33. Type *i8Ty;
  34. DxilTypeSystem &dxilTypeSys;
  35. DxilFunctionProps *functionProps;
  36. bool bLegacyCBufferLoad;
  37. DataLayout legacyDataLayout;
  38. HLOperationLowerHelper(HLModule &HLM);
  39. };
  40. HLOperationLowerHelper::HLOperationLowerHelper(HLModule &HLM)
  41. : hlslOP(*HLM.GetOP()), dxilTypeSys(HLM.GetTypeSystem()),
  42. legacyDataLayout(HLModule::GetLegacyDataLayoutDesc()) {
  43. llvm::LLVMContext &Ctx = HLM.GetCtx();
  44. voidTy = Type::getVoidTy(Ctx);
  45. f32Ty = Type::getFloatTy(Ctx);
  46. i32Ty = Type::getInt32Ty(Ctx);
  47. i1Ty = Type::getInt1Ty(Ctx);
  48. i8Ty = Type::getInt8Ty(Ctx);
  49. Function *EntryFunc = HLM.GetEntryFunction();
  50. functionProps = nullptr;
  51. if (HLM.HasDxilFunctionProps(EntryFunc))
  52. functionProps = &HLM.GetDxilFunctionProps(EntryFunc);
  53. bLegacyCBufferLoad = HLM.GetHLOptions().bLegacyCBufferLoad;
  54. }
  55. struct HLObjectOperationLowerHelper {
  56. private:
  57. // For object intrinsics.
  58. HLModule &HLM;
  59. struct ResAttribute {
  60. DXIL::ResourceClass RC;
  61. DXIL::ResourceKind RK;
  62. Type *ResourceType;
  63. };
  64. std::unordered_map<Value *, ResAttribute> HandleMetaMap;
  65. std::unordered_set<LoadInst *> &UpdateCounterSet;
  66. std::unordered_set<Value *> &NonUniformSet;
  67. // Map from pointer of cbuffer to pointer of resource.
  68. // For cbuffer like this:
  69. // cbuffer A {
  70. // Texture2D T;
  71. // };
  72. // A global resource Texture2D T2 will be created for Texture2D T.
  73. // CBPtrToResourceMap[T] will return T2.
  74. std::unordered_map<Value *, Value *> CBPtrToResourceMap;
  75. public:
  76. HLObjectOperationLowerHelper(HLModule &HLM,
  77. std::unordered_set<LoadInst *> &UpdateCounter,
  78. std::unordered_set<Value *> &NonUniform)
  79. : HLM(HLM), UpdateCounterSet(UpdateCounter), NonUniformSet(NonUniform) {}
  80. DXIL::ResourceClass GetRC(Value *Handle) {
  81. ResAttribute &Res = FindCreateHandleResourceBase(Handle);
  82. return Res.RC;
  83. }
  84. DXIL::ResourceKind GetRK(Value *Handle) {
  85. ResAttribute &Res = FindCreateHandleResourceBase(Handle);
  86. return Res.RK;
  87. }
  88. Type *GetResourceType(Value *Handle) {
  89. ResAttribute &Res = FindCreateHandleResourceBase(Handle);
  90. return Res.ResourceType;
  91. }
  92. void MarkHasCounter(Type *Ty, Value *handle) {
  93. DXIL::ResourceClass RC = GetRC(handle);
  94. DXASSERT_LOCALVAR(RC, RC == DXIL::ResourceClass::UAV,
  95. "must UAV for counter");
  96. std::unordered_set<Value *> resSet;
  97. MarkHasCounterOnCreateHandle(handle, resSet);
  98. }
  99. void MarkNonUniform(Value *V) { NonUniformSet.insert(V); }
  100. Value *GetOrCreateResourceForCbPtr(GetElementPtrInst *CbPtr,
  101. GlobalVariable *CbGV, MDNode *MD) {
  102. // Change array idx to 0 to make sure all array ptr share same key.
  103. Value *Key = UniformCbPtr(CbPtr, CbGV);
  104. if (CBPtrToResourceMap.count(Key))
  105. return CBPtrToResourceMap[Key];
  106. Value *Resource = CreateResourceForCbPtr(CbPtr, CbGV, MD);
  107. CBPtrToResourceMap[Key] = Resource;
  108. return Resource;
  109. }
  110. Value *LowerCbResourcePtr(GetElementPtrInst *CbPtr, Value *ResPtr) {
  111. // Simple case.
  112. if (ResPtr->getType() == CbPtr->getType())
  113. return ResPtr;
  114. // Array case.
  115. DXASSERT_NOMSG(ResPtr->getType()->getPointerElementType()->isArrayTy());
  116. IRBuilder<> Builder(CbPtr);
  117. gep_type_iterator GEPIt = gep_type_begin(CbPtr), E = gep_type_end(CbPtr);
  118. Value *arrayIdx = GEPIt.getOperand();
  119. // Only calc array idx and size.
  120. // Ignore struct type part.
  121. for (; GEPIt != E; ++GEPIt) {
  122. if (GEPIt->isArrayTy()) {
  123. arrayIdx = Builder.CreateMul(
  124. arrayIdx, Builder.getInt32(GEPIt->getArrayNumElements()));
  125. arrayIdx = Builder.CreateAdd(arrayIdx, GEPIt.getOperand());
  126. }
  127. }
  128. return Builder.CreateGEP(ResPtr, {Builder.getInt32(0), arrayIdx});
  129. }
  130. private:
  131. ResAttribute &FindCreateHandleResourceBase(Value *Handle) {
  132. if (HandleMetaMap.count(Handle))
  133. return HandleMetaMap[Handle];
  134. // Add invalid first to avoid dead loop.
  135. HandleMetaMap[Handle] = {DXIL::ResourceClass::Invalid,
  136. DXIL::ResourceKind::Invalid,
  137. StructType::get(Type::getVoidTy(HLM.GetCtx()))};
  138. if (Argument *Arg = dyn_cast<Argument>(Handle)) {
  139. MDNode *MD = HLM.GetDxilResourceAttrib(Arg);
  140. if (!MD) {
  141. Handle->getContext().emitError("cannot map resource to handle");
  142. return HandleMetaMap[Handle];
  143. }
  144. DxilResourceBase Res(DxilResource::Class::Invalid);
  145. HLM.LoadDxilResourceBaseFromMDNode(MD, Res);
  146. ResAttribute Attrib = {Res.GetClass(), Res.GetKind(),
  147. Res.GetGlobalSymbol()->getType()};
  148. HandleMetaMap[Handle] = Attrib;
  149. return HandleMetaMap[Handle];
  150. }
  151. if (LoadInst *LI = dyn_cast<LoadInst>(Handle)) {
  152. Value *Ptr = LI->getPointerOperand();
  153. for (User *U : Ptr->users()) {
  154. if (CallInst *CI = dyn_cast<CallInst>(U)) {
  155. DxilFunctionAnnotation *FnAnnot = HLM.GetFunctionAnnotation(CI->getCalledFunction());
  156. if (FnAnnot) {
  157. for (auto &arg : CI->arg_operands()) {
  158. if (arg == Ptr) {
  159. unsigned argNo = arg.getOperandNo();
  160. DxilParameterAnnotation &ParamAnnot = FnAnnot->GetParameterAnnotation(argNo);
  161. MDNode *MD = ParamAnnot.GetResourceAttribute();
  162. if (!MD) {
  163. Handle->getContext().emitError(
  164. "cannot map resource to handle");
  165. return HandleMetaMap[Handle];
  166. }
  167. DxilResourceBase Res(DxilResource::Class::Invalid);
  168. HLM.LoadDxilResourceBaseFromMDNode(MD, Res);
  169. ResAttribute Attrib = {Res.GetClass(), Res.GetKind(),
  170. Res.GetGlobalSymbol()->getType()};
  171. HandleMetaMap[Handle] = Attrib;
  172. return HandleMetaMap[Handle];
  173. }
  174. }
  175. }
  176. }
  177. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  178. Value *V = SI->getValueOperand();
  179. ResAttribute Attrib = FindCreateHandleResourceBase(V);
  180. HandleMetaMap[Handle] = Attrib;
  181. return HandleMetaMap[Handle];
  182. }
  183. }
  184. // Cannot find.
  185. Handle->getContext().emitError("cannot map resource to handle");
  186. return HandleMetaMap[Handle];
  187. }
  188. if (CallInst *CI = dyn_cast<CallInst>(Handle)) {
  189. MDNode *MD = HLM.GetDxilResourceAttrib(CI->getCalledFunction());
  190. if (!MD) {
  191. Handle->getContext().emitError("cannot map resource to handle");
  192. return HandleMetaMap[Handle];
  193. }
  194. DxilResourceBase Res(DxilResource::Class::Invalid);
  195. HLM.LoadDxilResourceBaseFromMDNode(MD, Res);
  196. ResAttribute Attrib = {Res.GetClass(), Res.GetKind(),
  197. Res.GetGlobalSymbol()->getType()};
  198. HandleMetaMap[Handle] = Attrib;
  199. return HandleMetaMap[Handle];
  200. }
  201. if (SelectInst *Sel = dyn_cast<SelectInst>(Handle)) {
  202. ResAttribute &ResT = FindCreateHandleResourceBase(Sel->getTrueValue());
  203. // Use MDT here, ResourceClass, ResourceID match is done at
  204. // DxilGenerationPass::AddCreateHandleForPhiNodeAndSelect.
  205. HandleMetaMap[Handle] = ResT;
  206. FindCreateHandleResourceBase(Sel->getFalseValue());
  207. return ResT;
  208. }
  209. if (PHINode *Phi = dyn_cast<PHINode>(Handle)) {
  210. if (Phi->getNumOperands() == 0) {
  211. Handle->getContext().emitError("cannot map resource to handle");
  212. return HandleMetaMap[Handle];
  213. }
  214. ResAttribute &Res0 = FindCreateHandleResourceBase(Phi->getOperand(0));
  215. // Use Res0 here, ResourceClass, ResourceID match is done at
  216. // DxilGenerationPass::AddCreateHandleForPhiNodeAndSelect.
  217. HandleMetaMap[Handle] = Res0;
  218. for (unsigned i = 1; i < Phi->getNumOperands(); i++) {
  219. FindCreateHandleResourceBase(Phi->getOperand(i));
  220. }
  221. return Res0;
  222. }
  223. Handle->getContext().emitError("cannot map resource to handle");
  224. return HandleMetaMap[Handle];
  225. }
  226. CallInst *FindCreateHandle(Value *handle,
  227. std::unordered_set<Value *> &resSet) {
  228. // Already checked.
  229. if (resSet.count(handle))
  230. return nullptr;
  231. resSet.insert(handle);
  232. if (CallInst *CI = dyn_cast<CallInst>(handle))
  233. return CI;
  234. if (SelectInst *Sel = dyn_cast<SelectInst>(handle)) {
  235. if (CallInst *CI = FindCreateHandle(Sel->getTrueValue(), resSet))
  236. return CI;
  237. if (CallInst *CI = FindCreateHandle(Sel->getFalseValue(), resSet))
  238. return CI;
  239. return nullptr;
  240. }
  241. if (PHINode *Phi = dyn_cast<PHINode>(handle)) {
  242. for (unsigned i = 0; i < Phi->getNumOperands(); i++) {
  243. if (CallInst *CI = FindCreateHandle(Phi->getOperand(i), resSet))
  244. return CI;
  245. }
  246. return nullptr;
  247. }
  248. return nullptr;
  249. }
  250. void MarkHasCounterOnCreateHandle(Value *handle,
  251. std::unordered_set<Value *> &resSet) {
  252. // Already checked.
  253. if (resSet.count(handle))
  254. return;
  255. resSet.insert(handle);
  256. if (CallInst *CI = dyn_cast<CallInst>(handle)) {
  257. Value *Res =
  258. CI->getArgOperand(HLOperandIndex::kCreateHandleResourceOpIdx);
  259. LoadInst *LdRes = dyn_cast<LoadInst>(Res);
  260. if (!LdRes) {
  261. CI->getContext().emitError(CI, "cannot map resource to handle");
  262. return;
  263. }
  264. UpdateCounterSet.insert(LdRes);
  265. return;
  266. }
  267. if (SelectInst *Sel = dyn_cast<SelectInst>(handle)) {
  268. MarkHasCounterOnCreateHandle(Sel->getTrueValue(), resSet);
  269. MarkHasCounterOnCreateHandle(Sel->getFalseValue(), resSet);
  270. }
  271. if (PHINode *Phi = dyn_cast<PHINode>(handle)) {
  272. for (unsigned i = 0; i < Phi->getNumOperands(); i++) {
  273. MarkHasCounterOnCreateHandle(Phi->getOperand(i), resSet);
  274. }
  275. }
  276. }
  277. Value *UniformCbPtr(GetElementPtrInst *CbPtr, GlobalVariable *CbGV) {
  278. gep_type_iterator GEPIt = gep_type_begin(CbPtr), E = gep_type_end(CbPtr);
  279. std::vector<Value *> idxList(CbPtr->idx_begin(), CbPtr->idx_end());
  280. unsigned i = 0;
  281. IRBuilder<> Builder(HLM.GetCtx());
  282. Value *zero = Builder.getInt32(0);
  283. for (; GEPIt != E; ++GEPIt, ++i) {
  284. if (GEPIt->isArrayTy()) {
  285. // Change array idx to 0 to make sure all array ptr share same key.
  286. idxList[i] = zero;
  287. }
  288. }
  289. Value *Key = Builder.CreateInBoundsGEP(CbGV, idxList);
  290. return Key;
  291. }
  292. Value *CreateResourceForCbPtr(GetElementPtrInst *CbPtr, GlobalVariable *CbGV,
  293. MDNode *MD) {
  294. Type *CbTy = CbPtr->getPointerOperandType();
  295. DXASSERT_LOCALVAR(CbTy, CbTy == CbGV->getType(), "else arg not point to var");
  296. gep_type_iterator GEPIt = gep_type_begin(CbPtr), E = gep_type_end(CbPtr);
  297. unsigned i = 0;
  298. IRBuilder<> Builder(HLM.GetCtx());
  299. unsigned arraySize = 1;
  300. DxilTypeSystem &typeSys = HLM.GetTypeSystem();
  301. std::string Name;
  302. for (; GEPIt != E; ++GEPIt, ++i) {
  303. if (GEPIt->isArrayTy()) {
  304. arraySize *= GEPIt->getArrayNumElements();
  305. } else if (GEPIt->isStructTy()) {
  306. DxilStructAnnotation *typeAnnot =
  307. typeSys.GetStructAnnotation(cast<StructType>(*GEPIt));
  308. DXASSERT_NOMSG(typeAnnot);
  309. unsigned idx = cast<ConstantInt>(GEPIt.getOperand())->getLimitedValue();
  310. DXASSERT_NOMSG(typeAnnot->GetNumFields() > idx);
  311. DxilFieldAnnotation &fieldAnnot = typeAnnot->GetFieldAnnotation(idx);
  312. if (!Name.empty())
  313. Name += ".";
  314. Name += fieldAnnot.GetFieldName();
  315. }
  316. }
  317. Type *Ty = CbPtr->getResultElementType();
  318. if (arraySize > 1) {
  319. Ty = ArrayType::get(Ty, arraySize);
  320. }
  321. return CreateResourceGV(Ty, Name, MD);
  322. }
  323. Value *CreateResourceGV(Type *Ty, StringRef Name, MDNode *MD) {
  324. Module &M = *HLM.GetModule();
  325. Constant *GV = M.getOrInsertGlobal(Name, Ty);
  326. // Create resource and set GV as globalSym.
  327. HLM.AddResourceWithGlobalVariableAndMDNode(GV, MD);
  328. return GV;
  329. }
  330. };
  331. using IntrinsicLowerFuncTy = Value *(CallInst *CI, IntrinsicOp IOP,
  332. DXIL::OpCode opcode,
  333. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated);
  334. struct IntrinsicLower {
  335. // Intrinsic opcode.
  336. IntrinsicOp IntriOpcode;
  337. // Lower function.
  338. IntrinsicLowerFuncTy &LowerFunc;
  339. // DXIL opcode if can direct map.
  340. DXIL::OpCode DxilOpcode;
  341. };
  342. // IOP intrinsics.
  343. namespace {
  344. Value *TrivialDxilOperation(Function *dxilFunc, OP::OpCode opcode, ArrayRef<Value *> refArgs,
  345. Type *Ty, Type *RetTy, OP *hlslOP,
  346. IRBuilder<> &Builder) {
  347. unsigned argNum = refArgs.size();
  348. std::vector<Value *> args = refArgs;
  349. if (Ty->isVectorTy()) {
  350. Value *retVal = llvm::UndefValue::get(RetTy);
  351. unsigned vecSize = Ty->getVectorNumElements();
  352. for (unsigned i = 0; i < vecSize; i++) {
  353. // Update vector args, skip known opcode arg.
  354. for (unsigned argIdx = HLOperandIndex::kUnaryOpSrc0Idx; argIdx < argNum;
  355. argIdx++) {
  356. if (refArgs[argIdx]->getType()->isVectorTy()) {
  357. Value *arg = refArgs[argIdx];
  358. args[argIdx] = Builder.CreateExtractElement(arg, i);
  359. }
  360. }
  361. Value *EltOP =
  362. Builder.CreateCall(dxilFunc, args, hlslOP->GetOpCodeName(opcode));
  363. retVal = Builder.CreateInsertElement(retVal, EltOP, i);
  364. }
  365. return retVal;
  366. } else {
  367. Value *retVal =
  368. Builder.CreateCall(dxilFunc, args, hlslOP->GetOpCodeName(opcode));
  369. return retVal;
  370. }
  371. }
  372. // Generates a DXIL operation over an overloaded type (Ty), returning a
  373. // RetTy value; when Ty is a vector, it will replicate per-element operations
  374. // into RetTy to rebuild it.
  375. Value *TrivialDxilOperation(OP::OpCode opcode, ArrayRef<Value *> refArgs,
  376. Type *Ty, Type *RetTy, OP *hlslOP,
  377. IRBuilder<> &Builder) {
  378. Type *EltTy = Ty->getScalarType();
  379. Function *dxilFunc = hlslOP->GetOpFunc(opcode, EltTy);
  380. return TrivialDxilOperation(dxilFunc, opcode, refArgs, Ty, RetTy, hlslOP, Builder);
  381. }
  382. Value *TrivialDxilOperation(OP::OpCode opcode, ArrayRef<Value *> refArgs,
  383. Type *Ty, Instruction *Inst, OP *hlslOP) {
  384. DXASSERT(refArgs.size() > 0, "else opcode isn't in signature");
  385. DXASSERT(refArgs[0] == nullptr,
  386. "else caller has already filled the value in");
  387. IRBuilder<> B(Inst);
  388. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  389. const_cast<llvm::Value **>(refArgs.data())[0] =
  390. opArg; // actually stack memory from caller
  391. return TrivialDxilOperation(opcode, refArgs, Ty, Inst->getType(), hlslOP, B);
  392. }
  393. Value *TrivialDxilUnaryOperationRet(OP::OpCode opcode, Value *src, Type *RetTy,
  394. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  395. Type *Ty = src->getType();
  396. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  397. Value *args[] = {opArg, src};
  398. return TrivialDxilOperation(opcode, args, Ty, RetTy, hlslOP, Builder);
  399. }
  400. Value *TrivialDxilUnaryOperation(OP::OpCode opcode, Value *src,
  401. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  402. return TrivialDxilUnaryOperationRet(opcode, src, src->getType(), hlslOP,
  403. Builder);
  404. }
  405. Value *TrivialDxilBinaryOperation(OP::OpCode opcode, Value *src0, Value *src1,
  406. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  407. Type *Ty = src0->getType();
  408. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  409. Value *args[] = {opArg, src0, src1};
  410. return TrivialDxilOperation(opcode, args, Ty, Ty, hlslOP, Builder);
  411. }
  412. Value *TrivialDxilTrinaryOperation(OP::OpCode opcode, Value *src0, Value *src1,
  413. Value *src2, hlsl::OP *hlslOP,
  414. IRBuilder<> &Builder) {
  415. Type *Ty = src0->getType();
  416. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  417. Value *args[] = {opArg, src0, src1, src2};
  418. return TrivialDxilOperation(opcode, args, Ty, Ty, hlslOP, Builder);
  419. }
  420. Value *TrivialUnaryOperation(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  421. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  422. Value *src0 = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  423. IRBuilder<> Builder(CI);
  424. hlsl::OP *hlslOP = &helper.hlslOP;
  425. Value *retVal = TrivialDxilUnaryOperationRet(opcode, src0, CI->getType(), hlslOP, Builder);
  426. return retVal;
  427. }
  428. Value *TrivialBinaryOperation(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  429. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  430. hlsl::OP *hlslOP = &helper.hlslOP;
  431. Value *src0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  432. Value *src1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  433. IRBuilder<> Builder(CI);
  434. Value *binOp =
  435. TrivialDxilBinaryOperation(opcode, src0, src1, hlslOP, Builder);
  436. return binOp;
  437. }
  438. Value *TrivialTrinaryOperation(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  439. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  440. hlsl::OP *hlslOP = &helper.hlslOP;
  441. Value *src0 = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc0Idx);
  442. Value *src1 = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc1Idx);
  443. Value *src2 = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc2Idx);
  444. IRBuilder<> Builder(CI);
  445. Value *triOp =
  446. TrivialDxilTrinaryOperation(opcode, src0, src1, src2, hlslOP, Builder);
  447. return triOp;
  448. }
  449. Value *TrivialIsSpecialFloat(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  450. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  451. hlsl::OP *hlslOP = &helper.hlslOP;
  452. Value *src = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  453. IRBuilder<> Builder(CI);
  454. Type *Ty = src->getType();
  455. Type *RetTy = Type::getInt1Ty(CI->getContext());
  456. if (Ty->isVectorTy())
  457. RetTy = VectorType::get(RetTy, Ty->getVectorNumElements());
  458. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  459. Value *args[] = {opArg, src};
  460. return TrivialDxilOperation(opcode, args, Ty, RetTy, hlslOP, Builder);
  461. }
  462. Value *TranslateNonUniformResourceIndex(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  463. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  464. for (User *U : CI->users()) {
  465. if (CastInst *I = dyn_cast<CastInst>(U)) {
  466. pObjHelper->MarkNonUniform(I);
  467. }
  468. }
  469. Value *V = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  470. pObjHelper->MarkNonUniform(V);
  471. CI->replaceAllUsesWith(V);
  472. return nullptr;
  473. }
  474. Value *TrivialBarrier(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  475. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  476. hlsl::OP *OP = &helper.hlslOP;
  477. Function *dxilFunc = OP->GetOpFunc(OP::OpCode::Barrier, CI->getType());
  478. Constant *opArg = OP->GetU32Const((unsigned)OP::OpCode::Barrier);
  479. unsigned uglobal = static_cast<unsigned>(DXIL::BarrierMode::UAVFenceGlobal);
  480. unsigned g = static_cast<unsigned>(DXIL::BarrierMode::TGSMFence);
  481. unsigned t = static_cast<unsigned>(DXIL::BarrierMode::SyncThreadGroup);
  482. // unsigned ut = static_cast<unsigned>(DXIL::BarrierMode::UAVFenceThreadGroup);
  483. unsigned barrierMode;
  484. switch (IOP) {
  485. case IntrinsicOp::IOP_AllMemoryBarrier:
  486. barrierMode = uglobal | g;
  487. break;
  488. case IntrinsicOp::IOP_AllMemoryBarrierWithGroupSync:
  489. barrierMode = uglobal | g | t;
  490. break;
  491. case IntrinsicOp::IOP_GroupMemoryBarrier:
  492. barrierMode = g;
  493. break;
  494. case IntrinsicOp::IOP_GroupMemoryBarrierWithGroupSync:
  495. barrierMode = g | t;
  496. break;
  497. case IntrinsicOp::IOP_DeviceMemoryBarrier:
  498. barrierMode = uglobal;
  499. break;
  500. case IntrinsicOp::IOP_DeviceMemoryBarrierWithGroupSync:
  501. barrierMode = uglobal | t;
  502. break;
  503. default:
  504. DXASSERT(0, "invalid opcode for barrier");
  505. break;
  506. }
  507. Value *src0 = OP->GetU32Const(static_cast<unsigned>(barrierMode));
  508. Value *args[] = {opArg, src0};
  509. IRBuilder<> Builder(CI);
  510. Builder.CreateCall(dxilFunc, args);
  511. return nullptr;
  512. }
  513. Value *TranslateD3DColorToUByte4(CallInst *CI, IntrinsicOp IOP,
  514. OP::OpCode opcode,
  515. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  516. hlsl::OP *hlslOP = &helper.hlslOP;
  517. IRBuilder<> Builder(CI);
  518. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  519. Type *Ty = val->getType();
  520. Constant *toByteConst = ConstantFP::get(Ty->getScalarType(), 255);
  521. if (Ty != Ty->getScalarType()) {
  522. toByteConst =
  523. ConstantVector::getSplat(Ty->getVectorNumElements(), toByteConst);
  524. }
  525. Value *byte4 = Builder.CreateFMul(toByteConst, val);
  526. byte4 =
  527. TrivialDxilUnaryOperation(OP::OpCode::Round_z, byte4, hlslOP, Builder);
  528. return Builder.CreateBitCast(byte4, CI->getType());
  529. }
  530. Value *TranslateAddUint64(CallInst *CI, IntrinsicOp IOP,
  531. OP::OpCode opcode,
  532. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  533. hlsl::OP *hlslOP = &helper.hlslOP;
  534. IRBuilder<> Builder(CI);
  535. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  536. Type *Ty = val->getType();
  537. VectorType *VT = dyn_cast<VectorType>(Ty);
  538. if (!VT) {
  539. CI->getContext().emitError(
  540. CI, "AddUint64 can only be applied to uint2 and uint4 operands");
  541. return UndefValue::get(Ty);
  542. }
  543. unsigned size = VT->getNumElements();
  544. if (size != 2 && size != 4) {
  545. CI->getContext().emitError(
  546. CI, "AddUint64 can only be applied to uint2 and uint4 operands");
  547. return UndefValue::get(Ty);
  548. }
  549. Value *op0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  550. Value *op1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  551. Value *RetVal = UndefValue::get(Ty);
  552. Function *AddC = hlslOP->GetOpFunc(DXIL::OpCode::UAddc, helper.i32Ty);
  553. Value *opArg = Builder.getInt32(static_cast<unsigned>(DXIL::OpCode::UAddc));
  554. for (unsigned i=0; i<size; i+=2) {
  555. Value *low0 = Builder.CreateExtractElement(op0, i);
  556. Value *low1 = Builder.CreateExtractElement(op1, i);
  557. Value *lowWithC = Builder.CreateCall(AddC, { opArg, low0, low1});
  558. Value *low = Builder.CreateExtractValue(lowWithC, 0);
  559. RetVal = Builder.CreateInsertElement(RetVal, low, i);
  560. Value *carry = Builder.CreateExtractValue(lowWithC, 1);
  561. // Ext i1 to i32
  562. carry = Builder.CreateZExt(carry, helper.i32Ty);
  563. Value *hi0 = Builder.CreateExtractElement(op0, i+1);
  564. Value *hi1 = Builder.CreateExtractElement(op1, i+1);
  565. Value *hi = Builder.CreateAdd(hi0, hi1);
  566. hi = Builder.CreateAdd(hi, carry);
  567. RetVal = Builder.CreateInsertElement(RetVal, hi, i+1);
  568. }
  569. return RetVal;
  570. }
  571. bool IsValidLoadInput(Value *V) {
  572. // Must be load input.
  573. // TODO: report this error on front-end
  574. if (!isa<CallInst>(V)) {
  575. V->getContext().emitError("attribute evaluation can only be done on values "
  576. "taken directly from inputs");
  577. return false;
  578. }
  579. CallInst *CI = cast<CallInst>(V);
  580. // Must be immediate.
  581. ConstantInt *opArg =
  582. cast<ConstantInt>(CI->getArgOperand(DXIL::OperandIndex::kOpcodeIdx));
  583. DXIL::OpCode op = static_cast<DXIL::OpCode>(opArg->getLimitedValue());
  584. if (op != DXIL::OpCode::LoadInput) {
  585. V->getContext().emitError("attribute evaluation can only be done on values "
  586. "taken directly from inputs");
  587. return false;
  588. }
  589. return true;
  590. }
  591. // Apply current shuffle vector mask on top of previous shuffle mask.
  592. // For example, if previous mask is (12,11,10,13) and current mask is (3,1,0,2)
  593. // new mask would be (13,11,12,10)
  594. Constant *AccumulateMask(Constant *curMask, Constant *prevMask) {
  595. if (curMask == nullptr) {
  596. return prevMask;
  597. }
  598. unsigned size = cast<VectorType>(curMask->getType())->getNumElements();
  599. SmallVector<uint32_t, 16> Elts;
  600. for (unsigned i = 0; i != size; ++i) {
  601. ConstantInt *Index = cast<ConstantInt>(curMask->getAggregateElement(i));
  602. ConstantInt *IVal =
  603. cast<ConstantInt>(prevMask->getAggregateElement(Index->getSExtValue()));
  604. Elts.emplace_back(IVal->getSExtValue());
  605. }
  606. return ConstantDataVector::get(curMask->getContext(), Elts);
  607. }
  608. Constant *GetLoadInputsForEvaluate(Value *V, std::vector<CallInst*> &loadList) {
  609. Constant *shufMask = nullptr;
  610. if (V->getType()->isVectorTy()) {
  611. // Must be insert element inst. Keeping track of masks for shuffle vector
  612. Value *Vec = V;
  613. while (ShuffleVectorInst *shuf = dyn_cast<ShuffleVectorInst>(Vec)) {
  614. shufMask = AccumulateMask(shufMask, shuf->getMask());
  615. Vec = shuf->getOperand(0);
  616. }
  617. // TODO: We are assuming that the operand of insertelement is a LoadInput.
  618. // This will fail on the case where we pass in matrix member using array subscript.
  619. while (!isa<UndefValue>(Vec)) {
  620. InsertElementInst *insertInst = cast<InsertElementInst>(Vec);
  621. Vec = insertInst->getOperand(0);
  622. Value *Elt = insertInst->getOperand(1);
  623. if (IsValidLoadInput(Elt)) {
  624. loadList.emplace_back(cast<CallInst>(Elt));
  625. }
  626. }
  627. } else {
  628. if (IsValidLoadInput(V)) {
  629. loadList.emplace_back(cast<CallInst>(V));
  630. }
  631. }
  632. return shufMask;
  633. }
  634. // Swizzle could reduce the dimensionality of the Type, but
  635. // for temporary insertelement instructions should maintain the existing size of the loadinput.
  636. // So we have to analyze the type of src in order to determine the actual size required.
  637. Type *GetInsertElementTypeForEvaluate(Value *src) {
  638. if (InsertElementInst *IE = dyn_cast<InsertElementInst>(src)) {
  639. return src->getType();
  640. }
  641. else if (ShuffleVectorInst *SV = dyn_cast<ShuffleVectorInst>(src)) {
  642. return SV->getOperand(0)->getType();
  643. }
  644. src->getContext().emitError("Invalid type call for EvaluateAttribute function");
  645. return nullptr;
  646. }
  647. Value *TranslateEvalSample(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  648. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  649. hlsl::OP *hlslOP = &helper.hlslOP;
  650. Value *val = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  651. Value *sampleIdx = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  652. IRBuilder<> Builder(CI);
  653. std::vector<CallInst*> loadList;
  654. Constant *shufMask = GetLoadInputsForEvaluate(val, loadList);
  655. unsigned size = loadList.size();
  656. OP::OpCode opcode = OP::OpCode::EvalSampleIndex;
  657. Value *opArg = hlslOP->GetU32Const((unsigned)opcode);
  658. Type *Ty = GetInsertElementTypeForEvaluate(val);
  659. Function *evalFunc = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  660. Value *result = UndefValue::get(Ty);
  661. for (unsigned i = 0; i < size; i++) {
  662. CallInst *loadInput = loadList[size-1-i];
  663. Value *inputElemID = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  664. Value *rowIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  665. Value *colIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  666. Value *Elt = Builder.CreateCall(evalFunc, { opArg, inputElemID, rowIdx, colIdx, sampleIdx });
  667. result = Builder.CreateInsertElement(result, Elt, i);
  668. }
  669. if (shufMask)
  670. result = Builder.CreateShuffleVector(result, UndefValue::get(Ty), shufMask);
  671. return result;
  672. }
  673. Value *TranslateEvalSnapped(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  674. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  675. hlsl::OP *hlslOP = &helper.hlslOP;
  676. Value *val = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  677. Value *offset = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  678. IRBuilder<> Builder(CI);
  679. Value *offsetX = Builder.CreateExtractElement(offset, (uint64_t)0);
  680. Value *offsetY = Builder.CreateExtractElement(offset, 1);
  681. std::vector<CallInst*> loadList;
  682. Constant *shufMask = GetLoadInputsForEvaluate(val, loadList);
  683. unsigned size = loadList.size();
  684. OP::OpCode opcode = OP::OpCode::EvalSnapped;
  685. Value *opArg = hlslOP->GetU32Const((unsigned)opcode);
  686. Type *Ty = GetInsertElementTypeForEvaluate(val);
  687. Function *evalFunc = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  688. Value *result = UndefValue::get(Ty);
  689. for (unsigned i = 0; i < size; i++) {
  690. CallInst *loadInput = loadList[size-1-i];
  691. Value *inputElemID = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  692. Value *rowIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  693. Value *colIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  694. Value *Elt = Builder.CreateCall(evalFunc, { opArg, inputElemID, rowIdx, colIdx, offsetX, offsetY });
  695. result = Builder.CreateInsertElement(result, Elt, i);
  696. }
  697. if (shufMask)
  698. result = Builder.CreateShuffleVector(result, UndefValue::get(Ty), shufMask);
  699. return result;
  700. }
  701. Value *TranslateEvalCentroid(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  702. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  703. hlsl::OP *hlslOP = &helper.hlslOP;
  704. Value *src = CI->getArgOperand(DXIL::OperandIndex::kUnarySrc0OpIdx);
  705. std::vector<CallInst*> loadList;
  706. Constant *shufMask = GetLoadInputsForEvaluate(src, loadList);
  707. unsigned size = loadList.size();
  708. IRBuilder<> Builder(CI);
  709. OP::OpCode opcode = OP::OpCode::EvalCentroid;
  710. Value *opArg = hlslOP->GetU32Const((unsigned)opcode);
  711. Type *Ty = GetInsertElementTypeForEvaluate(src);
  712. Function *evalFunc = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  713. Value *result = UndefValue::get(Ty);
  714. for (unsigned i = 0; i < size; i++) {
  715. CallInst *loadInput = loadList[size-1-i];
  716. Value *inputElemID = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  717. Value *rowIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  718. Value *colIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  719. Value *Elt = Builder.CreateCall(evalFunc, { opArg, inputElemID, rowIdx, colIdx });
  720. result = Builder.CreateInsertElement(result, Elt, i);
  721. }
  722. if (shufMask)
  723. result = Builder.CreateShuffleVector(result, UndefValue::get(Ty), shufMask);
  724. return result;
  725. }
  726. Value *TranslateGetAttributeAtVertex(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  727. HLOperationLowerHelper &helper,
  728. HLObjectOperationLowerHelper *pObjHelper,
  729. bool &Translated) {
  730. DXASSERT(op == OP::OpCode::AttributeAtVertex, "Wrong opcode to translate");
  731. hlsl::OP *hlslOP = &helper.hlslOP;
  732. IRBuilder<> Builder(CI);
  733. Type *Ty = CI->getType();
  734. Value *val = CI->getArgOperand(DXIL::OperandIndex::kBinarySrc0OpIdx);
  735. Value *vertexIdx = CI->getArgOperand(DXIL::OperandIndex::kBinarySrc1OpIdx);
  736. Value *vertexI8Idx = Builder.CreateTrunc(vertexIdx, Type::getInt8Ty(CI->getContext()));
  737. // Check the range of VertexID
  738. Value *vertex0 = Builder.getInt8(0);
  739. Value *vertex1 = Builder.getInt8(1);
  740. Value *vertex2 = Builder.getInt8(2);
  741. if (vertexI8Idx != vertex0 && vertexI8Idx != vertex1 && vertexI8Idx != vertex2) {
  742. CI->getContext().emitError(CI, "VertexID at GetAttributeAtVertex can only range from 0 to 2");
  743. return UndefValue::get(Ty);
  744. }
  745. std::vector<CallInst*> loadList;
  746. Constant *shufMask = GetLoadInputsForEvaluate(val, loadList);
  747. unsigned size = loadList.size();
  748. Value *opArg = hlslOP->GetU32Const((unsigned)op);
  749. Function *evalFunc = hlslOP->GetOpFunc(op, Ty->getScalarType());
  750. Value *result = UndefValue::get(Ty);
  751. for (unsigned i = 0; i < size; ++i) {
  752. CallInst *loadInput = loadList[size - 1 - i];
  753. Value *inputElemID = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  754. Value *rowIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  755. Value *colIdx = loadInput->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  756. Value *Elt = Builder.CreateCall(evalFunc, { opArg, inputElemID, rowIdx, colIdx, vertexI8Idx });
  757. result = Builder.CreateInsertElement(result, Elt, i);
  758. }
  759. if (shufMask)
  760. result = Builder.CreateShuffleVector(result, UndefValue::get(Ty), shufMask);
  761. return result;
  762. }
  763. Value *TrivialNoArgOperation(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  764. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  765. hlsl::OP *hlslOP = &helper.hlslOP;
  766. Type *Ty = Type::getVoidTy(CI->getContext());
  767. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  768. Value *args[] = {opArg};
  769. IRBuilder<> Builder(CI);
  770. Value *dxilOp = TrivialDxilOperation(opcode, args, Ty, Ty, hlslOP, Builder);
  771. return dxilOp;
  772. }
  773. Value *TranslateGetRTSamplePos(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  774. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  775. hlsl::OP *hlslOP = &helper.hlslOP;
  776. OP::OpCode opcode = OP::OpCode::RenderTargetGetSamplePosition;
  777. IRBuilder<> Builder(CI);
  778. Type *Ty = Type::getVoidTy(CI->getContext());
  779. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  780. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  781. Value *args[] = {opArg, val};
  782. Value *samplePos =
  783. TrivialDxilOperation(opcode, args, Ty, Ty, hlslOP, Builder);
  784. Value *result = UndefValue::get(CI->getType());
  785. Value *samplePosX = Builder.CreateExtractValue(samplePos, 0);
  786. Value *samplePosY = Builder.CreateExtractValue(samplePos, 1);
  787. result = Builder.CreateInsertElement(result, samplePosX, (uint64_t)0);
  788. result = Builder.CreateInsertElement(result, samplePosY, 1);
  789. return result;
  790. }
  791. // val QuadReadLaneAt(val, uint);
  792. Value *TranslateQuadReadLaneAt(CallInst *CI, IntrinsicOp IOP,
  793. OP::OpCode opcode,
  794. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  795. hlsl::OP *hlslOP = &helper.hlslOP;
  796. Value *refArgs[] = {nullptr, CI->getOperand(1), CI->getOperand(2)};
  797. return TrivialDxilOperation(DXIL::OpCode::QuadReadLaneAt, refArgs,
  798. CI->getOperand(1)->getType(), CI, hlslOP);
  799. }
  800. // Wave intrinsics of the form fn(val,QuadOpKind)->val
  801. Value *TranslateQuadReadAcross(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  802. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  803. hlsl::OP *hlslOP = &helper.hlslOP;
  804. DXIL::QuadOpKind opKind;
  805. switch (IOP) {
  806. case IntrinsicOp::IOP_QuadReadAcrossX: opKind = DXIL::QuadOpKind::ReadAcrossX; break;
  807. case IntrinsicOp::IOP_QuadReadAcrossY: opKind = DXIL::QuadOpKind::ReadAcrossY; break;
  808. default: DXASSERT_NOMSG(IOP == IntrinsicOp::IOP_QuadReadAcrossDiagonal);
  809. case IntrinsicOp::IOP_QuadReadAcrossDiagonal: opKind = DXIL::QuadOpKind::ReadAcrossDiagonal; break;
  810. }
  811. Constant *OpArg = hlslOP->GetI8Const((unsigned)opKind);
  812. Value *refArgs[] = {nullptr, CI->getOperand(1), OpArg};
  813. return TrivialDxilOperation(DXIL::OpCode::QuadOp, refArgs,
  814. CI->getOperand(1)->getType(), CI, hlslOP);
  815. }
  816. // WaveAllEqual(val<n>)->bool<n>
  817. Value *TranslateWaveAllEqual(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  818. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  819. hlsl::OP *hlslOP = &helper.hlslOP;
  820. Value *src = CI->getArgOperand(HLOperandIndex::kWaveAllEqualValueOpIdx);
  821. IRBuilder<> Builder(CI);
  822. Type *Ty = src->getType();
  823. Type *RetTy = Type::getInt1Ty(CI->getContext());
  824. if (Ty->isVectorTy())
  825. RetTy = VectorType::get(RetTy, Ty->getVectorNumElements());
  826. Constant *opArg = hlslOP->GetU32Const((unsigned)DXIL::OpCode::WaveActiveAllEqual);
  827. Value *args[] = {opArg, src};
  828. return TrivialDxilOperation(DXIL::OpCode::WaveActiveAllEqual, args, Ty, RetTy,
  829. hlslOP, Builder);
  830. }
  831. // Wave intrinsics of the form fn(valA)->valB, where no overloading takes place
  832. Value *TranslateWaveA2B(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  833. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  834. hlsl::OP *hlslOP = &helper.hlslOP;
  835. Value *refArgs[] = {nullptr, CI->getOperand(1)};
  836. return TrivialDxilOperation(opcode, refArgs, helper.voidTy, CI, hlslOP);
  837. }
  838. // Wave ballot intrinsic.
  839. Value *TranslateWaveBallot(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  840. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  841. // The high-level operation is uint4 ballot(i1).
  842. // The DXIL operation is struct.u4 ballot(i1).
  843. // To avoid updating users with more than a simple replace, we translate into
  844. // a call into struct.u4, then reassemble the vector.
  845. // Scalarization and constant propagation take care of cleanup.
  846. IRBuilder<> B(CI);
  847. // Make the DXIL call itself.
  848. hlsl::OP *hlslOP = &helper.hlslOP;
  849. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  850. Value *refArgs[] = { opArg, CI->getOperand(1) };
  851. Function *dxilFunc = hlslOP->GetOpFunc(opcode, Type::getVoidTy(CI->getContext()));
  852. Value *dxilVal = B.CreateCall(dxilFunc, refArgs, hlslOP->GetOpCodeName(opcode));
  853. // Assign from the call results into a vector.
  854. Type *ResTy = CI->getType();
  855. DXASSERT_NOMSG(ResTy->isVectorTy() && ResTy->getVectorNumElements() == 4);
  856. DXASSERT_NOMSG(dxilVal->getType()->isStructTy() &&
  857. dxilVal->getType()->getNumContainedTypes() == 4);
  858. // 'x' component is the first vector element, highest bits.
  859. Value *ResVal = llvm::UndefValue::get(ResTy);
  860. for (unsigned Idx = 0; Idx < 4; ++Idx) {
  861. ResVal = B.CreateInsertElement(
  862. ResVal, B.CreateExtractValue(dxilVal, ArrayRef<unsigned>(Idx)), Idx);
  863. }
  864. return ResVal;
  865. }
  866. static bool WaveIntrinsicNeedsSign(OP::OpCode opcode) {
  867. return opcode == OP::OpCode::WaveActiveOp ||
  868. opcode == OP::OpCode::WavePrefixOp;
  869. }
  870. static unsigned WaveIntrinsicToSignedOpKind(IntrinsicOp IOP) {
  871. if (IOP == IntrinsicOp::IOP_WaveActiveUMax ||
  872. IOP == IntrinsicOp::IOP_WaveActiveUMin ||
  873. IOP == IntrinsicOp::IOP_WaveActiveUSum ||
  874. IOP == IntrinsicOp::IOP_WaveActiveUProduct ||
  875. IOP == IntrinsicOp::IOP_WavePrefixUSum ||
  876. IOP == IntrinsicOp::IOP_WavePrefixUProduct)
  877. return (unsigned)DXIL::SignedOpKind::Unsigned;
  878. return (unsigned)DXIL::SignedOpKind::Signed;
  879. }
  880. static unsigned WaveIntrinsicToOpKind(IntrinsicOp IOP) {
  881. switch (IOP) {
  882. // Bit operations.
  883. case IntrinsicOp::IOP_WaveActiveBitOr:
  884. return (unsigned)DXIL::WaveBitOpKind::Or;
  885. case IntrinsicOp::IOP_WaveActiveBitAnd:
  886. return (unsigned)DXIL::WaveBitOpKind::And;
  887. case IntrinsicOp::IOP_WaveActiveBitXor:
  888. return (unsigned)DXIL::WaveBitOpKind::Xor;
  889. // Prefix operations.
  890. case IntrinsicOp::IOP_WavePrefixSum:
  891. case IntrinsicOp::IOP_WavePrefixUSum:
  892. return (unsigned)DXIL::WaveOpKind::Sum;
  893. case IntrinsicOp::IOP_WavePrefixProduct:
  894. case IntrinsicOp::IOP_WavePrefixUProduct:
  895. return (unsigned)DXIL::WaveOpKind::Product;
  896. // Numeric operations.
  897. case IntrinsicOp::IOP_WaveActiveMax:
  898. case IntrinsicOp::IOP_WaveActiveUMax:
  899. return (unsigned)DXIL::WaveOpKind::Max;
  900. case IntrinsicOp::IOP_WaveActiveMin:
  901. case IntrinsicOp::IOP_WaveActiveUMin:
  902. return (unsigned)DXIL::WaveOpKind::Min;
  903. case IntrinsicOp::IOP_WaveActiveSum:
  904. case IntrinsicOp::IOP_WaveActiveUSum:
  905. return (unsigned)DXIL::WaveOpKind::Sum;
  906. case IntrinsicOp::IOP_WaveActiveProduct:
  907. case IntrinsicOp::IOP_WaveActiveUProduct:
  908. default:
  909. DXASSERT(IOP == IntrinsicOp::IOP_WaveActiveProduct ||
  910. IOP == IntrinsicOp::IOP_WaveActiveUProduct,
  911. "else caller passed incorrect value");
  912. return (unsigned)DXIL::WaveOpKind::Product;
  913. }
  914. }
  915. // Wave intrinsics of the form fn(valA)->valA
  916. Value *TranslateWaveA2A(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  917. HLOperationLowerHelper &helper,
  918. HLObjectOperationLowerHelper *pObjHelper,
  919. bool &Translated) {
  920. hlsl::OP *hlslOP = &helper.hlslOP;
  921. Constant *kindValInt = hlslOP->GetI8Const(WaveIntrinsicToOpKind(IOP));
  922. Constant *signValInt = hlslOP->GetI8Const(WaveIntrinsicToSignedOpKind(IOP));
  923. Value *refArgs[] = {nullptr, CI->getOperand(1), kindValInt, signValInt};
  924. unsigned refArgCount = _countof(refArgs);
  925. if (!WaveIntrinsicNeedsSign(opcode))
  926. refArgCount--;
  927. return TrivialDxilOperation(opcode,
  928. llvm::ArrayRef<Value *>(refArgs, refArgCount),
  929. CI->getOperand(1)->getType(), CI, hlslOP);
  930. }
  931. // Wave intrinsics of the form fn()->val
  932. Value *TranslateWaveToVal(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  933. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  934. hlsl::OP *hlslOP = &helper.hlslOP;
  935. Value *refArgs[] = {nullptr};
  936. return TrivialDxilOperation(opcode, refArgs, helper.voidTy, CI, hlslOP);
  937. }
  938. // Wave intrinsics of the form fn(val,lane)->val
  939. Value *TranslateWaveReadLaneAt(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  940. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  941. hlsl::OP *hlslOP = &helper.hlslOP;
  942. Value *refArgs[] = {nullptr, CI->getOperand(1), CI->getOperand(2)};
  943. return TrivialDxilOperation(DXIL::OpCode::WaveReadLaneAt, refArgs,
  944. CI->getOperand(1)->getType(), CI, hlslOP);
  945. }
  946. // Wave intrinsics of the form fn(val)->val
  947. Value *TranslateWaveReadLaneFirst(CallInst *CI, IntrinsicOp IOP,
  948. OP::OpCode opcode,
  949. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  950. hlsl::OP *hlslOP = &helper.hlslOP;
  951. Value *refArgs[] = {nullptr, CI->getOperand(1)};
  952. return TrivialDxilOperation(DXIL::OpCode::WaveReadLaneFirst, refArgs,
  953. CI->getOperand(1)->getType(), CI, hlslOP);
  954. }
  955. Value *TranslateIAbs(CallInst *CI) {
  956. Type *Ty = CI->getType();
  957. Type *EltTy = Ty->getScalarType();
  958. unsigned bitWidth = EltTy->getIntegerBitWidth();
  959. uint64_t mask = ((uint64_t)1) << (bitWidth - 1);
  960. Constant *opMask = ConstantInt::get(EltTy, mask);
  961. if (Ty != EltTy) {
  962. unsigned size = Ty->getVectorNumElements();
  963. opMask = llvm::ConstantVector::getSplat(size, opMask);
  964. }
  965. IRBuilder<> Builder(CI);
  966. return Builder.CreateXor(CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx),
  967. opMask);
  968. }
  969. Value *TransalteAbs(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  970. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  971. hlsl::OP *hlslOP = &helper.hlslOP;
  972. Type *pOverloadTy = CI->getType()->getScalarType();
  973. if (pOverloadTy->isFloatingPointTy()) {
  974. Value *refArgs[] = {nullptr, CI->getOperand(1)};
  975. return TrivialDxilOperation(DXIL::OpCode::FAbs, refArgs, CI->getType(), CI,
  976. hlslOP);
  977. } else
  978. return TranslateIAbs(CI);
  979. }
  980. Value *GenerateCmpNEZero(Value *val, IRBuilder<> Builder) {
  981. Type *Ty = val->getType();
  982. Type *EltTy = Ty->getScalarType();
  983. Constant *zero = nullptr;
  984. if (EltTy->isFloatingPointTy())
  985. zero = ConstantFP::get(EltTy, 0);
  986. else
  987. zero = ConstantInt::get(EltTy, 0);
  988. if (Ty != EltTy) {
  989. zero = ConstantVector::getSplat(Ty->getVectorNumElements(), zero);
  990. }
  991. if (EltTy->isFloatingPointTy())
  992. return Builder.CreateFCmpUNE(val, zero);
  993. else
  994. return Builder.CreateICmpNE(val, zero);
  995. }
  996. Value *TranslateAllForValue(Value *val, IRBuilder<> &Builder) {
  997. Value *cond = GenerateCmpNEZero(val, Builder);
  998. Type *Ty = val->getType();
  999. Type *EltTy = Ty->getScalarType();
  1000. if (Ty != EltTy) {
  1001. Value *Result = Builder.CreateExtractElement(cond, (uint64_t)0);
  1002. for (unsigned i = 1; i < Ty->getVectorNumElements(); i++) {
  1003. Value *Elt = Builder.CreateExtractElement(cond, i);
  1004. Result = Builder.CreateAnd(Result, Elt);
  1005. }
  1006. return Result;
  1007. } else
  1008. return cond;
  1009. }
  1010. Value *TranslateAll(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1011. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1012. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1013. IRBuilder<> Builder(CI);
  1014. return TranslateAllForValue(val, Builder);
  1015. }
  1016. Value *TranslateAny(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1017. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1018. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1019. IRBuilder<> Builder(CI);
  1020. Value *cond = GenerateCmpNEZero(val, Builder);
  1021. Type *Ty = val->getType();
  1022. Type *EltTy = Ty->getScalarType();
  1023. if (Ty != EltTy) {
  1024. Value *Result = Builder.CreateExtractElement(cond, (uint64_t)0);
  1025. for (unsigned i = 1; i < Ty->getVectorNumElements(); i++) {
  1026. Value *Elt = Builder.CreateExtractElement(cond, i);
  1027. Result = Builder.CreateOr(Result, Elt);
  1028. }
  1029. return Result;
  1030. } else
  1031. return cond;
  1032. }
  1033. Value *TranslateBitcast(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1034. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1035. Type *Ty = CI->getType();
  1036. Value *op = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1037. IRBuilder<> Builder(CI);
  1038. return Builder.CreateBitCast(op, Ty);
  1039. }
  1040. Value *TranslateDoubleAsUint(Value *x, Value *lo, Value *hi,
  1041. IRBuilder<> &Builder, hlsl::OP *hlslOP) {
  1042. Type *Ty = x->getType();
  1043. Type *outTy = lo->getType()->getPointerElementType();
  1044. DXIL::OpCode opcode = DXIL::OpCode::SplitDouble;
  1045. Function *dxilFunc = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  1046. Value *opArg = hlslOP->GetU32Const(static_cast<unsigned>(opcode));
  1047. if (Ty->isVectorTy()) {
  1048. Value *retValLo = llvm::UndefValue::get(outTy);
  1049. Value *retValHi = llvm::UndefValue::get(outTy);
  1050. unsigned vecSize = Ty->getVectorNumElements();
  1051. for (unsigned i = 0; i < vecSize; i++) {
  1052. Value *Elt = Builder.CreateExtractElement(x, i);
  1053. Value *EltOP = Builder.CreateCall(dxilFunc, {opArg, Elt},
  1054. hlslOP->GetOpCodeName(opcode));
  1055. Value *EltLo = Builder.CreateExtractValue(EltOP, 0);
  1056. retValLo = Builder.CreateInsertElement(retValLo, EltLo, i);
  1057. Value *EltHi = Builder.CreateExtractValue(EltOP, 1);
  1058. retValHi = Builder.CreateInsertElement(retValHi, EltHi, i);
  1059. }
  1060. Builder.CreateStore(retValLo, lo);
  1061. Builder.CreateStore(retValHi, hi);
  1062. } else {
  1063. Value *retVal =
  1064. Builder.CreateCall(dxilFunc, {opArg, x}, hlslOP->GetOpCodeName(opcode));
  1065. Value *retValLo = Builder.CreateExtractValue(retVal, 0);
  1066. Value *retValHi = Builder.CreateExtractValue(retVal, 1);
  1067. Builder.CreateStore(retValLo, lo);
  1068. Builder.CreateStore(retValHi, hi);
  1069. }
  1070. return nullptr;
  1071. }
  1072. Value *TranslateAsUint(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1073. HLOperationLowerHelper &helper,
  1074. HLObjectOperationLowerHelper *pObjHelper,
  1075. bool &Translated) {
  1076. if (CI->getNumArgOperands() == 2) {
  1077. return TranslateBitcast(CI, IOP, opcode, helper, pObjHelper, Translated);
  1078. } else {
  1079. DXASSERT_NOMSG(CI->getNumArgOperands() == 4);
  1080. hlsl::OP *hlslOP = &helper.hlslOP;
  1081. Value *x = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc0Idx);
  1082. DXASSERT_NOMSG(x->getType()->getScalarType()->isDoubleTy());
  1083. Value *lo = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc1Idx);
  1084. Value *hi = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc2Idx);
  1085. IRBuilder<> Builder(CI);
  1086. return TranslateDoubleAsUint(x, lo, hi, Builder, hlslOP);
  1087. }
  1088. }
  1089. Value *TranslateAsDouble(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1090. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1091. hlsl::OP *hlslOP = &helper.hlslOP;
  1092. Value *x = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1093. Value *y = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1094. Value *opArg = hlslOP->GetU32Const(static_cast<unsigned>(opcode));
  1095. IRBuilder<> Builder(CI);
  1096. return TrivialDxilOperation(opcode, { opArg, x, y }, CI->getType(), CI->getType(), hlslOP, Builder);
  1097. }
  1098. Value *TranslateAtan2(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1099. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1100. hlsl::OP *hlslOP = &helper.hlslOP;
  1101. Value *y = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1102. Value *x = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1103. IRBuilder<> Builder(CI);
  1104. Value *tan = Builder.CreateFDiv(y, x);
  1105. return TrivialDxilUnaryOperation(OP::OpCode::Atan, tan, hlslOP, Builder);
  1106. }
  1107. Value *TranslateClamp(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1108. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1109. hlsl::OP *hlslOP = &helper.hlslOP;
  1110. Type *Ty = CI->getType();
  1111. Type *EltTy = Ty->getScalarType();
  1112. DXIL::OpCode maxOp = DXIL::OpCode::FMax;
  1113. DXIL::OpCode minOp = DXIL::OpCode::FMin;
  1114. if (IOP == IntrinsicOp::IOP_uclamp) {
  1115. maxOp = DXIL::OpCode::UMax;
  1116. minOp = DXIL::OpCode::UMin;
  1117. } else if (EltTy->isIntegerTy()) {
  1118. maxOp = DXIL::OpCode::IMax;
  1119. minOp = DXIL::OpCode::IMin;
  1120. }
  1121. Value *x = CI->getArgOperand(HLOperandIndex::kClampOpXIdx);
  1122. Value *maxVal = CI->getArgOperand(HLOperandIndex::kClampOpMaxIdx);
  1123. Value *minVal = CI->getArgOperand(HLOperandIndex::kClampOpMinIdx);
  1124. IRBuilder<> Builder(CI);
  1125. // min(max(x, minVal), maxVal).
  1126. Value *maxXMinVal =
  1127. TrivialDxilBinaryOperation(maxOp, x, minVal, hlslOP, Builder);
  1128. return TrivialDxilBinaryOperation(minOp, maxXMinVal, maxVal, hlslOP, Builder);
  1129. }
  1130. Value *TranslateClip(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1131. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1132. hlsl::OP *hlslOP = &helper.hlslOP;
  1133. Function *discard =
  1134. hlslOP->GetOpFunc(OP::OpCode::Discard, Type::getVoidTy(CI->getContext()));
  1135. IRBuilder<> Builder(CI);
  1136. Value *cond = nullptr;
  1137. Value *arg = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1138. if (VectorType *VT = dyn_cast<VectorType>(arg->getType())) {
  1139. Value *elt = Builder.CreateExtractElement(arg, (uint64_t)0);
  1140. cond = Builder.CreateFCmpOLT(elt, hlslOP->GetFloatConst(0));
  1141. for (unsigned i = 1; i < VT->getNumElements(); i++) {
  1142. Value *elt = Builder.CreateExtractElement(arg, i);
  1143. Value *eltCond = Builder.CreateFCmpOLT(elt, hlslOP->GetFloatConst(0));
  1144. cond = Builder.CreateOr(cond, eltCond);
  1145. }
  1146. } else
  1147. cond = Builder.CreateFCmpOLT(arg, hlslOP->GetFloatConst(0));
  1148. Constant *opArg = hlslOP->GetU32Const((unsigned)OP::OpCode::Discard);
  1149. Builder.CreateCall(discard, {opArg, cond});
  1150. return nullptr;
  1151. }
  1152. Value *TranslateCross(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1153. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1154. VectorType *VT = cast<VectorType>(CI->getType());
  1155. DXASSERT_NOMSG(VT->getNumElements() == 3);
  1156. Value *op0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1157. Value *op1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1158. IRBuilder<> Builder(CI);
  1159. Value *op0_x = Builder.CreateExtractElement(op0, (uint64_t)0);
  1160. Value *op0_y = Builder.CreateExtractElement(op0, 1);
  1161. Value *op0_z = Builder.CreateExtractElement(op0, 2);
  1162. Value *op1_x = Builder.CreateExtractElement(op1, (uint64_t)0);
  1163. Value *op1_y = Builder.CreateExtractElement(op1, 1);
  1164. Value *op1_z = Builder.CreateExtractElement(op1, 2);
  1165. auto MulSub = [&](Value *x0, Value *y0, Value *x1, Value *y1) -> Value * {
  1166. Value *xy = Builder.CreateFMul(x0, y1);
  1167. Value *yx = Builder.CreateFMul(y0, x1);
  1168. return Builder.CreateFSub(xy, yx);
  1169. };
  1170. Value *yz_zy = MulSub(op0_y, op0_z, op1_y, op1_z);
  1171. Value *zx_xz = MulSub(op0_z, op0_x, op1_z, op1_x);
  1172. Value *xy_yx = MulSub(op0_x, op0_y, op1_x, op1_y);
  1173. Value *cross = UndefValue::get(VT);
  1174. cross = Builder.CreateInsertElement(cross, yz_zy, (uint64_t)0);
  1175. cross = Builder.CreateInsertElement(cross, zx_xz, 1);
  1176. cross = Builder.CreateInsertElement(cross, xy_yx, 2);
  1177. return cross;
  1178. }
  1179. Value *TranslateDegrees(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1180. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1181. IRBuilder<> Builder(CI);
  1182. Type *Ty = CI->getType();
  1183. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1184. // 180/pi.
  1185. // TODO: include M_PI from math.h.
  1186. const double M_PI = 3.14159265358979323846;
  1187. Constant *toDegreeConst = ConstantFP::get(Ty->getScalarType(), 180 / M_PI);
  1188. if (Ty != Ty->getScalarType()) {
  1189. toDegreeConst =
  1190. ConstantVector::getSplat(Ty->getVectorNumElements(), toDegreeConst);
  1191. }
  1192. return Builder.CreateFMul(toDegreeConst, val);
  1193. }
  1194. Value *TranslateDst(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1195. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1196. Value *src0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1197. Value *src1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1198. Type *Ty = src1->getType();
  1199. IRBuilder<> Builder(CI);
  1200. Value *Result = UndefValue::get(Ty);
  1201. Constant *oneConst = ConstantFP::get(Ty->getScalarType(), 1);
  1202. // dest.x = 1;
  1203. Result = Builder.CreateInsertElement(Result, oneConst, (uint64_t)0);
  1204. // dest.y = src0.y * src1.y;
  1205. Value *src0_y = Builder.CreateExtractElement(src0, 1);
  1206. Value *src1_y = Builder.CreateExtractElement(src1, 1);
  1207. Value *yMuly = Builder.CreateFMul(src0_y, src1_y);
  1208. Result = Builder.CreateInsertElement(Result, yMuly, 1);
  1209. // dest.z = src0.z;
  1210. Value *src0_z = Builder.CreateExtractElement(src0, 2);
  1211. Result = Builder.CreateInsertElement(Result, src0_z, 2);
  1212. // dest.w = src1.w;
  1213. Value *src1_w = Builder.CreateExtractElement(src1, 3);
  1214. Result = Builder.CreateInsertElement(Result, src1_w, 3);
  1215. return Result;
  1216. }
  1217. Value *TranslateFirstbitHi(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1218. HLOperationLowerHelper &helper,
  1219. HLObjectOperationLowerHelper *pObjHelper,
  1220. bool &Translated) {
  1221. Value *firstbitHi =
  1222. TrivialUnaryOperation(CI, IOP, opcode, helper, pObjHelper, Translated);
  1223. // firstbitHi == -1? -1 : (bitWidth-1 -firstbitHi);
  1224. IRBuilder<> Builder(CI);
  1225. Constant *neg1 = Builder.getInt32(-1);
  1226. Value *src = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1227. Type *Ty = src->getType();
  1228. IntegerType *EltTy = cast<IntegerType>(Ty->getScalarType());
  1229. Constant *bitWidth = Builder.getInt32(EltTy->getBitWidth()-1);
  1230. if (Ty == Ty->getScalarType()) {
  1231. Value *sub = Builder.CreateSub(bitWidth, firstbitHi);
  1232. Value *cond = Builder.CreateICmpEQ(neg1, firstbitHi);
  1233. return Builder.CreateSelect(cond, neg1, sub);
  1234. } else {
  1235. Value *result = UndefValue::get(CI->getType());
  1236. unsigned vecSize = Ty->getVectorNumElements();
  1237. for (unsigned i = 0; i < vecSize; i++) {
  1238. Value *EltFirstBit = Builder.CreateExtractElement(firstbitHi, i);
  1239. Value *sub = Builder.CreateSub(bitWidth, EltFirstBit);
  1240. Value *cond = Builder.CreateICmpEQ(neg1, EltFirstBit);
  1241. Value *Elt = Builder.CreateSelect(cond, neg1, sub);
  1242. result = Builder.CreateInsertElement(result, Elt, i);
  1243. }
  1244. return result;
  1245. }
  1246. }
  1247. Value *TranslateFirstbitLo(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1248. HLOperationLowerHelper &helper,
  1249. HLObjectOperationLowerHelper *pObjHelper,
  1250. bool &Translated) {
  1251. Value *firstbitLo =
  1252. TrivialUnaryOperation(CI, IOP, opcode, helper, pObjHelper, Translated);
  1253. return firstbitLo;
  1254. }
  1255. Value *TranslateLit(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1256. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1257. Value *n_dot_l = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc0Idx);
  1258. Value *n_dot_h = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc1Idx);
  1259. Value *m = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc2Idx);
  1260. IRBuilder<> Builder(CI);
  1261. Type *Ty = m->getType();
  1262. Value *Result = UndefValue::get(VectorType::get(Ty, 4));
  1263. // Result = (ambient, diffuse, specular, 1)
  1264. // ambient = 1.
  1265. Constant *oneConst = ConstantFP::get(Ty, 1);
  1266. Result = Builder.CreateInsertElement(Result, oneConst, (uint64_t)0);
  1267. // Result.w = 1.
  1268. Result = Builder.CreateInsertElement(Result, oneConst, 3);
  1269. // diffuse = (n_dot_l < 0) ? 0 : n_dot_l.
  1270. Constant *zeroConst = ConstantFP::get(Ty, 0);
  1271. Value *nlCmp = Builder.CreateFCmpOLT(n_dot_l, zeroConst);
  1272. Value *diffuse = Builder.CreateSelect(nlCmp, zeroConst, n_dot_l);
  1273. Result = Builder.CreateInsertElement(Result, diffuse, 1);
  1274. // specular = ((n_dot_l < 0) || (n_dot_h < 0)) ? 0: (n_dot_h * m).
  1275. Value *nhCmp = Builder.CreateFCmpOLT(n_dot_h, zeroConst);
  1276. Value *specCond = Builder.CreateOr(nlCmp, nhCmp);
  1277. Value *nhMulM = Builder.CreateFMul(n_dot_h, m);
  1278. Value *spec = Builder.CreateSelect(specCond, zeroConst, nhMulM);
  1279. Result = Builder.CreateInsertElement(Result, spec, 2);
  1280. return Result;
  1281. }
  1282. Value *TranslateRadians(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1283. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1284. IRBuilder<> Builder(CI);
  1285. Type *Ty = CI->getType();
  1286. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1287. // pi/180.
  1288. // TODO: include M_PI from math.h.
  1289. const double M_PI = 3.14159265358979323846;
  1290. Constant *toRadianConst = ConstantFP::get(Ty->getScalarType(), M_PI / 180);
  1291. if (Ty != Ty->getScalarType()) {
  1292. toRadianConst =
  1293. ConstantVector::getSplat(Ty->getVectorNumElements(), toRadianConst);
  1294. }
  1295. return Builder.CreateFMul(toRadianConst, val);
  1296. }
  1297. Value *TranslateF16ToF32(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1298. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1299. IRBuilder<> Builder(CI);
  1300. Value *x = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1301. Type *Ty = CI->getType();
  1302. Function *f16tof32 =
  1303. helper.hlslOP.GetOpFunc(opcode, helper.voidTy);
  1304. return TrivialDxilOperation(
  1305. f16tof32, opcode, {Builder.getInt32(static_cast<unsigned>(opcode)), x},
  1306. x->getType(), Ty, &helper.hlslOP, Builder);
  1307. }
  1308. Value *TranslateF32ToF16(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1309. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1310. IRBuilder<> Builder(CI);
  1311. Value *x = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1312. Type *Ty = CI->getType();
  1313. Function *f32tof16 =
  1314. helper.hlslOP.GetOpFunc(opcode, helper.voidTy);
  1315. return TrivialDxilOperation(
  1316. f32tof16, opcode, {Builder.getInt32(static_cast<unsigned>(opcode)), x},
  1317. x->getType(), Ty, &helper.hlslOP, Builder);
  1318. }
  1319. Value *TranslateLength(CallInst *CI, Value *val, hlsl::OP *hlslOP) {
  1320. IRBuilder<> Builder(CI);
  1321. if (VectorType *VT = dyn_cast<VectorType>(val->getType())) {
  1322. Value *Elt = Builder.CreateExtractElement(val, (uint64_t)0);
  1323. unsigned size = VT->getNumElements();
  1324. if (size > 1) {
  1325. Value *Sum = Builder.CreateFMul(Elt, Elt);
  1326. for (unsigned i = 1; i < size; i++) {
  1327. Elt = Builder.CreateExtractElement(val, i);
  1328. Value *Mul = Builder.CreateFMul(Elt, Elt);
  1329. Sum = Builder.CreateFAdd(Sum, Mul);
  1330. }
  1331. DXIL::OpCode sqrt = DXIL::OpCode::Sqrt;
  1332. Function *dxilSqrt = hlslOP->GetOpFunc(sqrt, VT->getElementType());
  1333. Value *opArg = hlslOP->GetI32Const((unsigned)sqrt);
  1334. return Builder.CreateCall(dxilSqrt, {opArg, Sum},
  1335. hlslOP->GetOpCodeName(sqrt));
  1336. } else {
  1337. val = Elt;
  1338. }
  1339. }
  1340. DXIL::OpCode fabs = DXIL::OpCode::FAbs;
  1341. Function *dxilFAbs = hlslOP->GetOpFunc(fabs, val->getType());
  1342. Value *opArg = hlslOP->GetI32Const((unsigned)fabs);
  1343. return Builder.CreateCall(dxilFAbs, {opArg, val},
  1344. hlslOP->GetOpCodeName(fabs));
  1345. }
  1346. Value *TranslateLength(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1347. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1348. hlsl::OP *hlslOP = &helper.hlslOP;
  1349. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1350. return TranslateLength(CI, val, hlslOP);
  1351. }
  1352. Value *TranslateModF(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1353. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1354. hlsl::OP *hlslOP = &helper.hlslOP;
  1355. Value *val = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1356. Value *outIntPtr = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1357. IRBuilder<> Builder(CI);
  1358. Value *Result =
  1359. TrivialDxilUnaryOperation(OP::OpCode::Round_z, val, hlslOP, Builder);
  1360. Value *intPortion = Builder.CreateFSub(val, Result);
  1361. Builder.CreateStore(intPortion, outIntPtr);
  1362. return Result;
  1363. }
  1364. Value *TranslateDistance(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1365. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1366. hlsl::OP *hlslOP = &helper.hlslOP;
  1367. Value *src0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1368. Value *src1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1369. IRBuilder<> Builder(CI);
  1370. Value *sub = Builder.CreateFSub(src0, src1);
  1371. return TranslateLength(CI, sub, hlslOP);
  1372. }
  1373. Value *TranslateExp(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1374. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1375. hlsl::OP *hlslOP = &helper.hlslOP;
  1376. IRBuilder<> Builder(CI);
  1377. Type *Ty = CI->getType();
  1378. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1379. // TODO: include M_LOG2E from math.h.
  1380. const double M_LOG2E = 1.44269504088896340736;
  1381. Constant *log2eConst = ConstantFP::get(Ty->getScalarType(), M_LOG2E);
  1382. if (Ty != Ty->getScalarType()) {
  1383. log2eConst =
  1384. ConstantVector::getSplat(Ty->getVectorNumElements(), log2eConst);
  1385. }
  1386. val = Builder.CreateFMul(log2eConst, val);
  1387. Value *exp = TrivialDxilUnaryOperation(OP::OpCode::Exp, val, hlslOP, Builder);
  1388. return exp;
  1389. }
  1390. Value *TranslateLog(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1391. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1392. hlsl::OP *hlslOP = &helper.hlslOP;
  1393. IRBuilder<> Builder(CI);
  1394. Type *Ty = CI->getType();
  1395. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1396. // TODO: include M_LN2 from math.h.
  1397. const double M_LN2 = 0.693147180559945309417;
  1398. Constant *ln2Const = ConstantFP::get(Ty->getScalarType(), M_LN2);
  1399. if (Ty != Ty->getScalarType()) {
  1400. ln2Const = ConstantVector::getSplat(Ty->getVectorNumElements(), ln2Const);
  1401. }
  1402. Value *log = TrivialDxilUnaryOperation(OP::OpCode::Log, val, hlslOP, Builder);
  1403. return Builder.CreateFMul(ln2Const, log);
  1404. }
  1405. Value *TranslateLog10(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1406. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1407. hlsl::OP *hlslOP = &helper.hlslOP;
  1408. IRBuilder<> Builder(CI);
  1409. Type *Ty = CI->getType();
  1410. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1411. // TODO: include M_LN2 from math.h.
  1412. const double M_LN2 = 0.693147180559945309417;
  1413. const double M_LN10 = 2.30258509299404568402;
  1414. Constant *log2_10Const = ConstantFP::get(Ty->getScalarType(), M_LN2 / M_LN10);
  1415. if (Ty != Ty->getScalarType()) {
  1416. log2_10Const =
  1417. ConstantVector::getSplat(Ty->getVectorNumElements(), log2_10Const);
  1418. }
  1419. Value *log = TrivialDxilUnaryOperation(OP::OpCode::Log, val, hlslOP, Builder);
  1420. return Builder.CreateFMul(log2_10Const, log);
  1421. }
  1422. Value *TranslateFMod(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1423. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1424. hlsl::OP *hlslOP = &helper.hlslOP;
  1425. Value *src0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1426. Value *src1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1427. IRBuilder<> Builder(CI);
  1428. Value *div = Builder.CreateFDiv(src0, src1);
  1429. Value *negDiv = Builder.CreateFNeg(div);
  1430. Value *ge = Builder.CreateFCmpOGE(div, negDiv);
  1431. Value *absDiv =
  1432. TrivialDxilUnaryOperation(OP::OpCode::FAbs, div, hlslOP, Builder);
  1433. Value *frc =
  1434. TrivialDxilUnaryOperation(OP::OpCode::Frc, absDiv, hlslOP, Builder);
  1435. Value *negFrc = Builder.CreateFNeg(frc);
  1436. Value *realFrc = Builder.CreateSelect(ge, frc, negFrc);
  1437. return Builder.CreateFMul(realFrc, src1);
  1438. }
  1439. Value *TranslateFUIBinary(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1440. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1441. bool isFloat = CI->getType()->getScalarType()->isFloatingPointTy();
  1442. if (isFloat) {
  1443. switch (IOP) {
  1444. case IntrinsicOp::IOP_max:
  1445. opcode = OP::OpCode::FMax;
  1446. break;
  1447. case IntrinsicOp::IOP_min:
  1448. default:
  1449. DXASSERT(IOP == IntrinsicOp::IOP_min, "");
  1450. opcode = OP::OpCode::FMin;
  1451. break;
  1452. }
  1453. }
  1454. return TrivialBinaryOperation(CI, IOP, opcode, helper, pObjHelper, Translated);
  1455. }
  1456. Value *TranslateFUITrinary(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1457. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1458. bool isFloat = CI->getType()->getScalarType()->isFloatingPointTy();
  1459. if (isFloat) {
  1460. switch (IOP) {
  1461. case IntrinsicOp::IOP_mad:
  1462. default:
  1463. DXASSERT(IOP == IntrinsicOp::IOP_mad, "");
  1464. opcode = OP::OpCode::FMad;
  1465. break;
  1466. }
  1467. }
  1468. return TrivialTrinaryOperation(CI, IOP, opcode, helper, pObjHelper, Translated);
  1469. }
  1470. Value *TranslateFrexp(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1471. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1472. hlsl::OP *hlslOP = &helper.hlslOP;
  1473. Value *val = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1474. Value *expPtr = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1475. IRBuilder<> Builder(CI);
  1476. Type *i32Ty = Type::getInt32Ty(CI->getContext());
  1477. Constant *exponentMaskConst = ConstantInt::get(i32Ty, 0x7f800000);
  1478. Constant *mantisaMaskConst = ConstantInt::get(i32Ty, 0x007fffff);
  1479. Constant *exponentShiftConst = ConstantInt::get(i32Ty, 23);
  1480. Constant *mantisaOrConst = ConstantInt::get(i32Ty, 0x3f000000);
  1481. Constant *exponentBiasConst = ConstantInt::get(i32Ty, -(int)0x3f000000);
  1482. // bool ne = val != 0;
  1483. Value *notZero = Builder.CreateFCmpUNE(val, hlslOP->GetFloatConst(0));
  1484. notZero = Builder.CreateZExt(notZero, i32Ty);
  1485. // int iVal = asint(val);
  1486. Type *dstTy = i32Ty;
  1487. Type *Ty = val->getType();
  1488. if (Ty->isVectorTy()) {
  1489. unsigned vecSize = Ty->getVectorNumElements();
  1490. dstTy = VectorType::get(i32Ty, vecSize);
  1491. exponentMaskConst = ConstantVector::getSplat(vecSize, exponentMaskConst);
  1492. mantisaMaskConst = ConstantVector::getSplat(vecSize, mantisaMaskConst);
  1493. exponentShiftConst = ConstantVector::getSplat(vecSize, exponentShiftConst);
  1494. mantisaOrConst = ConstantVector::getSplat(vecSize, mantisaOrConst);
  1495. exponentBiasConst = ConstantVector::getSplat(vecSize, exponentBiasConst);
  1496. }
  1497. Value *intVal = Builder.CreateBitCast(val, i32Ty);
  1498. // temp = intVal & exponentMask;
  1499. Value *temp = Builder.CreateAnd(intVal, exponentMaskConst);
  1500. // temp = temp + exponentBias;
  1501. temp = Builder.CreateAdd(temp, exponentBiasConst);
  1502. // temp = temp & ne;
  1503. temp = Builder.CreateAnd(temp, notZero);
  1504. // temp = temp >> exponentShift;
  1505. temp = Builder.CreateAShr(temp, exponentShiftConst);
  1506. // exp = float(temp);
  1507. Value *exp = Builder.CreateSIToFP(temp, Ty);
  1508. Builder.CreateStore(exp, expPtr);
  1509. // temp = iVal & mantisaMask;
  1510. temp = Builder.CreateAnd(intVal, mantisaMaskConst);
  1511. // temp = temp | mantisaOr;
  1512. temp = Builder.CreateOr(temp, mantisaOrConst);
  1513. // mantisa = temp & ne;
  1514. Value *mantisa = Builder.CreateAnd(temp, notZero);
  1515. return Builder.CreateBitCast(mantisa, Ty);
  1516. }
  1517. Value *TranslateLdExp(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1518. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1519. hlsl::OP *hlslOP = &helper.hlslOP;
  1520. Value *src0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1521. Value *src1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1522. IRBuilder<> Builder(CI);
  1523. Value *exp =
  1524. TrivialDxilUnaryOperation(OP::OpCode::Exp, src1, hlslOP, Builder);
  1525. return Builder.CreateFMul(exp, src0);
  1526. }
  1527. Value *TranslateFWidth(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1528. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1529. hlsl::OP *hlslOP = &helper.hlslOP;
  1530. Value *src = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1531. IRBuilder<> Builder(CI);
  1532. Value *ddx =
  1533. TrivialDxilUnaryOperation(OP::OpCode::DerivCoarseX, src, hlslOP, Builder);
  1534. Value *absDdx =
  1535. TrivialDxilUnaryOperation(OP::OpCode::FAbs, ddx, hlslOP, Builder);
  1536. Value *ddy =
  1537. TrivialDxilUnaryOperation(OP::OpCode::DerivCoarseY, src, hlslOP, Builder);
  1538. Value *absDdy =
  1539. TrivialDxilUnaryOperation(OP::OpCode::FAbs, ddy, hlslOP, Builder);
  1540. return Builder.CreateFAdd(absDdx, absDdy);
  1541. }
  1542. Value *TranslateNormalize(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1543. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1544. hlsl::OP *hlslOP = &helper.hlslOP;
  1545. Type *Ty = CI->getType();
  1546. Value *op = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1547. IRBuilder<> Builder(CI);
  1548. Value *length = TranslateLength(CI, op, hlslOP);
  1549. if (Ty != length->getType()) {
  1550. VectorType *VT = cast<VectorType>(Ty);
  1551. Value *vecLength = UndefValue::get(VT);
  1552. for (unsigned i = 0; i < VT->getNumElements(); i++)
  1553. vecLength = Builder.CreateInsertElement(vecLength, length, i);
  1554. length = vecLength;
  1555. }
  1556. return Builder.CreateFDiv(op, length);
  1557. }
  1558. Value *TranslateLerp(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1559. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1560. // x + s(y-x)
  1561. Value *x = CI->getArgOperand(HLOperandIndex::kLerpOpXIdx);
  1562. Value *y = CI->getArgOperand(HLOperandIndex::kLerpOpYIdx);
  1563. IRBuilder<> Builder(CI);
  1564. Value *ySubx = Builder.CreateFSub(y, x);
  1565. Value *s = CI->getArgOperand(HLOperandIndex::kLerpOpSIdx);
  1566. Value *sMulSub = Builder.CreateFMul(s, ySubx);
  1567. return Builder.CreateFAdd(x, sMulSub);
  1568. }
  1569. Value *TrivialDotOperation(OP::OpCode opcode, Value *src0,
  1570. Value *src1, hlsl::OP *hlslOP,
  1571. IRBuilder<> &Builder) {
  1572. Type *Ty = src0->getType()->getScalarType();
  1573. Function *dxilFunc = hlslOP->GetOpFunc(opcode, Ty);
  1574. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  1575. SmallVector<Value *, 9> args;
  1576. args.emplace_back(opArg);
  1577. unsigned vecSize = src0->getType()->getVectorNumElements();
  1578. for (unsigned i = 0; i < vecSize; i++)
  1579. args.emplace_back(Builder.CreateExtractElement(src0, i));
  1580. for (unsigned i = 0; i < vecSize; i++)
  1581. args.emplace_back(Builder.CreateExtractElement(src1, i));
  1582. Value *dotOP = Builder.CreateCall(dxilFunc, args);
  1583. return dotOP;
  1584. }
  1585. Value *TranslateIDot(Value *arg0, Value *arg1, unsigned vecSize, hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  1586. Value *Elt0 = Builder.CreateExtractElement(arg0, (uint64_t)0);
  1587. Value *Elt1 = Builder.CreateExtractElement(arg1, (uint64_t)0);
  1588. Value *Result = Builder.CreateMul(Elt0, Elt1);
  1589. switch (vecSize) {
  1590. case 4:
  1591. Elt0 = Builder.CreateExtractElement(arg0, 3);
  1592. Elt1 = Builder.CreateExtractElement(arg1, 3);
  1593. Result = TrivialDxilTrinaryOperation(DXIL::OpCode::IMad, Elt0, Elt1, Result, hlslOP, Builder);
  1594. // Pass thru.
  1595. case 3:
  1596. Elt0 = Builder.CreateExtractElement(arg0, 2);
  1597. Elt1 = Builder.CreateExtractElement(arg1, 2);
  1598. Result = TrivialDxilTrinaryOperation(DXIL::OpCode::IMad, Elt0, Elt1, Result, hlslOP, Builder);
  1599. // Pass thru.
  1600. case 2:
  1601. Elt0 = Builder.CreateExtractElement(arg0, 1);
  1602. Elt1 = Builder.CreateExtractElement(arg1, 1);
  1603. Result = TrivialDxilTrinaryOperation(DXIL::OpCode::IMad, Elt0, Elt1, Result, hlslOP, Builder);
  1604. break;
  1605. default:
  1606. case 1:
  1607. DXASSERT(vecSize == 1, "invalid vector size.");
  1608. }
  1609. return Result;
  1610. }
  1611. Value *TranslateFDot(Value *arg0, Value *arg1, unsigned vecSize,
  1612. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  1613. switch (vecSize) {
  1614. case 2:
  1615. return TrivialDotOperation(OP::OpCode::Dot2, arg0, arg1, hlslOP, Builder);
  1616. break;
  1617. case 3:
  1618. return TrivialDotOperation(OP::OpCode::Dot3, arg0, arg1, hlslOP, Builder);
  1619. break;
  1620. case 4:
  1621. return TrivialDotOperation(OP::OpCode::Dot4, arg0, arg1, hlslOP, Builder);
  1622. break;
  1623. default:
  1624. DXASSERT(vecSize == 1, "wrong vector size");
  1625. {
  1626. Value *vecMul = Builder.CreateFMul(arg0, arg1);
  1627. return Builder.CreateExtractElement(vecMul, (uint64_t)0);
  1628. }
  1629. break;
  1630. }
  1631. }
  1632. Value *TranslateDot(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1633. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1634. hlsl::OP *hlslOP = &helper.hlslOP;
  1635. Value *arg0 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1636. Type *Ty = arg0->getType();
  1637. unsigned vecSize = Ty->getVectorNumElements();
  1638. Value *arg1 = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1639. IRBuilder<> Builder(CI);
  1640. if (Ty->getScalarType()->isFloatingPointTy()) {
  1641. return TranslateFDot(arg0, arg1, vecSize, hlslOP, Builder);
  1642. } else {
  1643. return TranslateIDot(arg0, arg1, vecSize, hlslOP, Builder);
  1644. }
  1645. }
  1646. Value *TranslateReflect(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  1647. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1648. hlsl::OP *hlslOP = &helper.hlslOP;
  1649. // v = i - 2 * n * dot(i•n).
  1650. IRBuilder<> Builder(CI);
  1651. Value *i = CI->getArgOperand(HLOperandIndex::kReflectOpIIdx);
  1652. Value *n = CI->getArgOperand(HLOperandIndex::kReflectOpNIdx);
  1653. VectorType *VT = cast<VectorType>(i->getType());
  1654. unsigned vecSize = VT->getNumElements();
  1655. Value *dot = TranslateFDot(i, n, vecSize, hlslOP, Builder);
  1656. // 2 * dot (i, n).
  1657. dot = Builder.CreateFMul(hlslOP->GetFloatConst(2), dot);
  1658. // 2 * n * dot(i, n).
  1659. Value *vecDot = Builder.CreateVectorSplat(vecSize, dot);
  1660. Value *nMulDot = Builder.CreateFMul(vecDot, n);
  1661. // i - 2 * n * dot(i, n).
  1662. return Builder.CreateFSub(i, nMulDot);
  1663. }
  1664. Value *TranslateRefract(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  1665. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1666. hlsl::OP *hlslOP = &helper.hlslOP;
  1667. // d = dot(i•n);
  1668. // t = 1 - eta * eta * ( 1 - d*d);
  1669. // cond = t >= 1;
  1670. // r = eta * i - (eta * d + sqrt(t)) * n;
  1671. // return cond ? r : 0;
  1672. IRBuilder<> Builder(CI);
  1673. Value *i = CI->getArgOperand(HLOperandIndex::kRefractOpIIdx);
  1674. Value *n = CI->getArgOperand(HLOperandIndex::kRefractOpNIdx);
  1675. Value *eta = CI->getArgOperand(HLOperandIndex::kRefractOpEtaIdx);
  1676. VectorType *VT = cast<VectorType>(i->getType());
  1677. unsigned vecSize = VT->getNumElements();
  1678. Value *dot = TranslateFDot(i, n, vecSize, hlslOP, Builder);
  1679. // eta * eta;
  1680. Value *eta2 = Builder.CreateFMul(eta, eta);
  1681. // d*d;
  1682. Value *dot2 = Builder.CreateFMul(dot, dot);
  1683. Constant *one = hlslOP->GetFloatConst(1);
  1684. Constant *zero = hlslOP->GetFloatConst(0);
  1685. // 1- d*d;
  1686. dot2 = Builder.CreateFSub(one, dot2);
  1687. // eta * eta * (1-d*d);
  1688. eta2 = Builder.CreateFMul(dot2, eta2);
  1689. // t = 1 - eta * eta * ( 1 - d*d);
  1690. Value *t = Builder.CreateFSub(one, eta2);
  1691. // cond = t >= 0;
  1692. Value *cond = Builder.CreateFCmpOGE(t, zero);
  1693. // eta * i;
  1694. Value *vecEta = UndefValue::get(VT);
  1695. for (unsigned i = 0; i < vecSize; i++)
  1696. vecEta = Builder.CreateInsertElement(vecEta, eta, i);
  1697. Value *etaMulI = Builder.CreateFMul(i, vecEta);
  1698. // sqrt(t);
  1699. Value *sqrt = TrivialDxilUnaryOperation(OP::OpCode::Sqrt, t, hlslOP, Builder);
  1700. // eta * d;
  1701. Value *etaMulD = Builder.CreateFMul(eta, dot);
  1702. // eta * d + sqrt(t);
  1703. Value *etaSqrt = Builder.CreateFAdd(etaMulD, sqrt);
  1704. // (eta * d + sqrt(t)) * n;
  1705. Value *vecEtaSqrt = Builder.CreateVectorSplat(vecSize, etaSqrt);
  1706. Value *r = Builder.CreateFMul(vecEtaSqrt, n);
  1707. // r = eta * i - (eta * d + sqrt(t)) * n;
  1708. r = Builder.CreateFSub(etaMulI, r);
  1709. Value *refract =
  1710. Builder.CreateSelect(cond, r, ConstantVector::getSplat(vecSize, zero));
  1711. return refract;
  1712. }
  1713. Value *TranslateSmoothStep(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1714. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1715. hlsl::OP *hlslOP = &helper.hlslOP;
  1716. // s = saturate((x-min)/(max-min)).
  1717. IRBuilder<> Builder(CI);
  1718. Value *minVal = CI->getArgOperand(HLOperandIndex::kSmoothStepOpMinIdx);
  1719. Value *maxVal = CI->getArgOperand(HLOperandIndex::kSmoothStepOpMaxIdx);
  1720. Value *maxSubMin = Builder.CreateFSub(maxVal, minVal);
  1721. Value *x = CI->getArgOperand(HLOperandIndex::kSmoothStepOpXIdx);
  1722. Value *xSubMin = Builder.CreateFSub(x, minVal);
  1723. Value *satVal = Builder.CreateFDiv(xSubMin, maxSubMin);
  1724. Value *s = TrivialDxilUnaryOperation(DXIL::OpCode::Saturate, satVal, hlslOP,
  1725. Builder);
  1726. // return s * s *(3-2*s).
  1727. Constant *c2 = hlslOP->GetFloatConst(2);
  1728. Constant *c3 = hlslOP->GetFloatConst(3);
  1729. if (s->getType()->isVectorTy()) {
  1730. unsigned vecSize = s->getType()->getVectorNumElements();
  1731. c2 = ConstantVector::getSplat(vecSize, c2);
  1732. c3 = ConstantVector::getSplat(vecSize, c3);
  1733. }
  1734. Value *sMul2 = Builder.CreateFMul(s, c2);
  1735. Value *result = Builder.CreateFSub(c3, sMul2);
  1736. result = Builder.CreateFMul(s, result);
  1737. result = Builder.CreateFMul(s, result);
  1738. return result;
  1739. }
  1740. Value *TranslateMSad4(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1741. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1742. hlsl::OP *hlslOP = &helper.hlslOP;
  1743. Value *ref = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc0Idx);
  1744. Value *src = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc1Idx);
  1745. Value *accum = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc2Idx);
  1746. Type *Ty = CI->getType();
  1747. IRBuilder<> Builder(CI);
  1748. Value *vecRef = UndefValue::get(Ty);
  1749. for (unsigned i = 0; i < 4; i++)
  1750. vecRef = Builder.CreateInsertElement(vecRef, ref, i);
  1751. Value *srcX = Builder.CreateExtractElement(src, (uint64_t)0);
  1752. Value *srcY = Builder.CreateExtractElement(src, 1);
  1753. Value *byteSrc = UndefValue::get(Ty);
  1754. byteSrc = Builder.CreateInsertElement(byteSrc, srcX, (uint64_t)0);
  1755. // ushr r0.yzw, srcX, l(0, 8, 16, 24)
  1756. // bfi r1.yzw, l(0, 8, 16, 24), l(0, 24, 16, 8), srcX, r0.yyzw
  1757. Value *bfiOpArg =
  1758. hlslOP->GetU32Const(static_cast<unsigned>(DXIL::OpCode::Bfi));
  1759. Value *imm8 = hlslOP->GetU32Const(8);
  1760. Value *imm16 = hlslOP->GetU32Const(16);
  1761. Value *imm24 = hlslOP->GetU32Const(24);
  1762. Ty = ref->getType();
  1763. // Get x[31:8].
  1764. Value *srcXShift = Builder.CreateLShr(srcX, imm8);
  1765. // y[0~7] x[31:8].
  1766. Value *byteSrcElt = TrivialDxilOperation(
  1767. DXIL::OpCode::Bfi, {bfiOpArg, imm8, imm24, srcY, srcXShift}, Ty, Ty,
  1768. hlslOP, Builder);
  1769. byteSrc = Builder.CreateInsertElement(byteSrc, byteSrcElt, 1);
  1770. // Get x[31:16].
  1771. srcXShift = Builder.CreateLShr(srcXShift, imm8);
  1772. // y[0~15] x[31:16].
  1773. byteSrcElt = TrivialDxilOperation(DXIL::OpCode::Bfi,
  1774. {bfiOpArg, imm16, imm16, srcY, srcXShift},
  1775. Ty, Ty, hlslOP, Builder);
  1776. byteSrc = Builder.CreateInsertElement(byteSrc, byteSrcElt, 2);
  1777. // Get x[31:24].
  1778. srcXShift = Builder.CreateLShr(srcXShift, imm8);
  1779. // y[0~23] x[31:24].
  1780. byteSrcElt = TrivialDxilOperation(DXIL::OpCode::Bfi,
  1781. {bfiOpArg, imm24, imm8, srcY, srcXShift},
  1782. Ty, Ty, hlslOP, Builder);
  1783. byteSrc = Builder.CreateInsertElement(byteSrc, byteSrcElt, 3);
  1784. // Msad on vecref and byteSrc.
  1785. return TrivialDxilTrinaryOperation(DXIL::OpCode::Msad, vecRef, byteSrc, accum,
  1786. hlslOP, Builder);
  1787. }
  1788. Value *TranslateRCP(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1789. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1790. Type *Ty = CI->getType();
  1791. Value *op = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1792. IRBuilder<> Builder(CI);
  1793. Constant *one = ConstantFP::get(Ty->getScalarType(), 1.0);
  1794. if (Ty != Ty->getScalarType()) {
  1795. one = ConstantVector::getSplat(Ty->getVectorNumElements(), one);
  1796. }
  1797. return Builder.CreateFDiv(one, op);
  1798. }
  1799. Value *TranslateSign(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1800. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1801. Value *val = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  1802. Type *Ty = val->getType();
  1803. Type *EltTy = Ty->getScalarType();
  1804. IRBuilder<> Builder(CI);
  1805. if (EltTy->isIntegerTy()) {
  1806. Constant *zero = ConstantInt::get(Ty->getScalarType(), 0);
  1807. if (Ty != EltTy) {
  1808. zero = ConstantVector::getSplat(Ty->getVectorNumElements(), zero);
  1809. }
  1810. Value *zeroLtVal = Builder.CreateICmpSLT(zero, val);
  1811. zeroLtVal = Builder.CreateZExt(zeroLtVal, CI->getType());
  1812. Value *valLtZero = Builder.CreateICmpSLT(val, zero);
  1813. valLtZero = Builder.CreateZExt(valLtZero, CI->getType());
  1814. return Builder.CreateSub(zeroLtVal, valLtZero);
  1815. } else {
  1816. Constant *zero = ConstantFP::get(Ty->getScalarType(), 0.0);
  1817. if (Ty != EltTy) {
  1818. zero = ConstantVector::getSplat(Ty->getVectorNumElements(), zero);
  1819. }
  1820. Value *zeroLtVal = Builder.CreateFCmpOLT(zero, val);
  1821. zeroLtVal = Builder.CreateZExt(zeroLtVal, CI->getType());
  1822. Value *valLtZero = Builder.CreateFCmpOLT(val, zero);
  1823. valLtZero = Builder.CreateZExt(valLtZero, CI->getType());
  1824. return Builder.CreateSub(zeroLtVal, valLtZero);
  1825. }
  1826. }
  1827. Value *TranslateStep(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1828. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1829. Value *edge = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1830. Value *x = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1831. Type *Ty = CI->getType();
  1832. IRBuilder<> Builder(CI);
  1833. Constant *one = ConstantFP::get(Ty->getScalarType(), 1.0);
  1834. Constant *zero = ConstantFP::get(Ty->getScalarType(), 0);
  1835. Value *cond = Builder.CreateFCmpOLT(x, edge);
  1836. if (Ty != Ty->getScalarType()) {
  1837. one = ConstantVector::getSplat(Ty->getVectorNumElements(), one);
  1838. zero = ConstantVector::getSplat(Ty->getVectorNumElements(), zero);
  1839. }
  1840. return Builder.CreateSelect(cond, zero, one);
  1841. }
  1842. Value *TranslatePow(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1843. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1844. hlsl::OP *hlslOP = &helper.hlslOP;
  1845. Value *x = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx);
  1846. Value *y = CI->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx);
  1847. IRBuilder<> Builder(CI);
  1848. // t = log(x);
  1849. Value *logX =
  1850. TrivialDxilUnaryOperation(DXIL::OpCode::Log, x, hlslOP, Builder);
  1851. // t = y * t;
  1852. Value *mulY = Builder.CreateFMul(logX, y);
  1853. // pow = exp(t);
  1854. return TrivialDxilUnaryOperation(DXIL::OpCode::Exp, mulY, hlslOP, Builder);
  1855. }
  1856. Value *TranslateFaceforward(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  1857. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1858. hlsl::OP *hlslOP = &helper.hlslOP;
  1859. Type *Ty = CI->getType();
  1860. Value *n = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc0Idx);
  1861. Value *i = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc1Idx);
  1862. Value *ng = CI->getArgOperand(HLOperandIndex::kTrinaryOpSrc2Idx);
  1863. IRBuilder<> Builder(CI);
  1864. unsigned vecSize = Ty->getVectorNumElements();
  1865. // -n x sign(dot(i, ng)).
  1866. Value *dotOp = TranslateFDot(i, ng, vecSize, hlslOP, Builder);
  1867. Constant *zero = ConstantFP::get(Ty->getScalarType(), 0);
  1868. Value *dotLtZero = Builder.CreateFCmpOLT(dotOp, zero);
  1869. Value *negN = Builder.CreateFNeg(n);
  1870. Value *faceforward = Builder.CreateSelect(dotLtZero, n, negN);
  1871. return faceforward;
  1872. }
  1873. }
  1874. // MOP intrinsics
  1875. namespace {
  1876. Value *TranslateGetSamplePosition(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  1877. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1878. hlsl::OP *hlslOP = &helper.hlslOP;
  1879. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  1880. IRBuilder<> Builder(CI);
  1881. Value *sampleIdx =
  1882. CI->getArgOperand(HLOperandIndex::kGetSamplePositionSampleIdxOpIndex);
  1883. OP::OpCode opcode = OP::OpCode::Texture2DMSGetSamplePosition;
  1884. llvm::Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  1885. Function *dxilFunc =
  1886. hlslOP->GetOpFunc(opcode, Type::getVoidTy(CI->getContext()));
  1887. Value *args[] = {opArg, handle, sampleIdx};
  1888. Value *samplePos = Builder.CreateCall(dxilFunc, args);
  1889. Value *result = UndefValue::get(CI->getType());
  1890. Value *samplePosX = Builder.CreateExtractValue(samplePos, 0);
  1891. Value *samplePosY = Builder.CreateExtractValue(samplePos, 1);
  1892. result = Builder.CreateInsertElement(result, samplePosX, (uint64_t)0);
  1893. result = Builder.CreateInsertElement(result, samplePosY, 1);
  1894. return result;
  1895. }
  1896. Value *TranslateGetDimensions(CallInst *CI, IntrinsicOp IOP, OP::OpCode op,
  1897. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1898. hlsl::OP *hlslOP = &helper.hlslOP;
  1899. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  1900. DxilResource::Kind RK = pObjHelper->GetRK(handle);
  1901. IRBuilder<> Builder(CI);
  1902. OP::OpCode opcode = OP::OpCode::GetDimensions;
  1903. llvm::Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  1904. Function *dxilFunc =
  1905. hlslOP->GetOpFunc(opcode, Type::getVoidTy(CI->getContext()));
  1906. Type *i32Ty = Type::getInt32Ty(CI->getContext());
  1907. Value *mipLevel = UndefValue::get(i32Ty);
  1908. unsigned widthOpIdx = HLOperandIndex::kGetDimensionsMipWidthOpIndex;
  1909. switch (RK) {
  1910. case DxilResource::Kind::Texture1D:
  1911. case DxilResource::Kind::Texture1DArray:
  1912. case DxilResource::Kind::Texture2D:
  1913. case DxilResource::Kind::Texture2DArray:
  1914. case DxilResource::Kind::TextureCube:
  1915. case DxilResource::Kind::TextureCubeArray:
  1916. case DxilResource::Kind::Texture3D: {
  1917. Value *opMipLevel =
  1918. CI->getArgOperand(HLOperandIndex::kGetDimensionsMipLevelOpIndex);
  1919. // mipLevel is in parameter, should not be pointer.
  1920. if (!opMipLevel->getType()->isPointerTy())
  1921. mipLevel = opMipLevel;
  1922. else {
  1923. // No mip level.
  1924. widthOpIdx = HLOperandIndex::kGetDimensionsNoMipWidthOpIndex;
  1925. mipLevel = ConstantInt::get(i32Ty, 0);
  1926. }
  1927. } break;
  1928. default:
  1929. widthOpIdx = HLOperandIndex::kGetDimensionsNoMipWidthOpIndex;
  1930. break;
  1931. }
  1932. Value *args[] = {opArg, handle, mipLevel};
  1933. Value *dims = Builder.CreateCall(dxilFunc, args);
  1934. unsigned dimensionIdx = 0;
  1935. Value *width = Builder.CreateExtractValue(dims, dimensionIdx++);
  1936. Value *widthPtr = CI->getArgOperand(widthOpIdx);
  1937. if (widthPtr->getType()->getPointerElementType()->isFloatTy())
  1938. width = Builder.CreateSIToFP(width,
  1939. widthPtr->getType()->getPointerElementType());
  1940. Builder.CreateStore(width, widthPtr);
  1941. if (RK == DxilResource::Kind::StructuredBuffer) {
  1942. // Set stride.
  1943. Value *stridePtr = CI->getArgOperand(widthOpIdx + 1);
  1944. const DataLayout &DL = helper.legacyDataLayout;
  1945. Value *buf = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  1946. Type *bufTy = buf->getType();
  1947. Type *bufRetTy = bufTy->getStructElementType(0);
  1948. unsigned stride = DL.getTypeAllocSize(bufRetTy);
  1949. Builder.CreateStore(hlslOP->GetU32Const(stride), stridePtr);
  1950. } else {
  1951. if (widthOpIdx == HLOperandIndex::kGetDimensionsMipWidthOpIndex ||
  1952. // Samples is in w channel too.
  1953. RK == DXIL::ResourceKind::Texture2DMS) {
  1954. // Has mip.
  1955. for (unsigned argIdx = widthOpIdx + 1;
  1956. argIdx < CI->getNumArgOperands() - 1; argIdx++) {
  1957. Value *dim = Builder.CreateExtractValue(dims, dimensionIdx++);
  1958. Value *ptr = CI->getArgOperand(argIdx);
  1959. if (ptr->getType()->getPointerElementType()->isFloatTy())
  1960. dim = Builder.CreateSIToFP(dim,
  1961. ptr->getType()->getPointerElementType());
  1962. Builder.CreateStore(dim, ptr);
  1963. }
  1964. // NumOfLevel is in w channel.
  1965. dimensionIdx = 3;
  1966. Value *dim = Builder.CreateExtractValue(dims, dimensionIdx);
  1967. Value *ptr = CI->getArgOperand(CI->getNumArgOperands() - 1);
  1968. if (ptr->getType()->getPointerElementType()->isFloatTy())
  1969. dim =
  1970. Builder.CreateSIToFP(dim, ptr->getType()->getPointerElementType());
  1971. Builder.CreateStore(dim, ptr);
  1972. } else {
  1973. for (unsigned argIdx = widthOpIdx + 1; argIdx < CI->getNumArgOperands();
  1974. argIdx++) {
  1975. Value *dim = Builder.CreateExtractValue(dims, dimensionIdx++);
  1976. Value *ptr = CI->getArgOperand(argIdx);
  1977. if (ptr->getType()->getPointerElementType()->isFloatTy())
  1978. dim = Builder.CreateSIToFP(dim,
  1979. ptr->getType()->getPointerElementType());
  1980. Builder.CreateStore(dim, ptr);
  1981. }
  1982. }
  1983. }
  1984. return nullptr;
  1985. }
  1986. Value *GenerateUpdateCounter(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  1987. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  1988. hlsl::OP *hlslOP = &helper.hlslOP;
  1989. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  1990. pObjHelper->MarkHasCounter(handle->getType(), handle);
  1991. bool bInc = IOP == IntrinsicOp::MOP_IncrementCounter;
  1992. IRBuilder<> Builder(CI);
  1993. OP::OpCode OpCode = OP::OpCode::BufferUpdateCounter;
  1994. Value *OpCodeArg = hlslOP->GetU32Const((unsigned)OpCode);
  1995. Value *IncVal = hlslOP->GetI8Const(bInc ? 1 : -1);
  1996. // Create BufferUpdateCounter call.
  1997. Value *Args[] = {OpCodeArg, handle, IncVal};
  1998. Function *F =
  1999. hlslOP->GetOpFunc(OpCode, Type::getVoidTy(handle->getContext()));
  2000. return Builder.CreateCall(F, Args);
  2001. }
  2002. Value *ScalarizeResRet(Type *RetTy, Value *ResRet, IRBuilder<> &Builder) {
  2003. // Extract value part.
  2004. Value *retVal = llvm::UndefValue::get(RetTy);
  2005. if (RetTy->isVectorTy()) {
  2006. for (unsigned i = 0; i < RetTy->getVectorNumElements(); i++) {
  2007. Value *retComp = Builder.CreateExtractValue(ResRet, i);
  2008. retVal = Builder.CreateInsertElement(retVal, retComp, i);
  2009. }
  2010. } else {
  2011. retVal = Builder.CreateExtractValue(ResRet, 0);
  2012. }
  2013. return retVal;
  2014. }
  2015. Value *ScalarizeElements(Type *RetTy, ArrayRef<Value*> Elts, IRBuilder<> &Builder) {
  2016. // Extract value part.
  2017. Value *retVal = llvm::UndefValue::get(RetTy);
  2018. if (RetTy->isVectorTy()) {
  2019. unsigned vecSize = RetTy->getVectorNumElements();
  2020. DXASSERT(vecSize <= Elts.size(), "vector size mismatch");
  2021. for (unsigned i = 0; i < vecSize; i++) {
  2022. Value *retComp = Elts[i];
  2023. retVal = Builder.CreateInsertElement(retVal, retComp, i);
  2024. }
  2025. } else {
  2026. retVal = Elts[0];
  2027. }
  2028. return retVal;
  2029. }
  2030. void UpdateStatus(Value *ResRet, Value *status, IRBuilder<> &Builder) {
  2031. if (status && !isa<UndefValue>(status)) {
  2032. Value *statusVal = Builder.CreateExtractValue(ResRet, 4);
  2033. Builder.CreateStore(statusVal, status);
  2034. }
  2035. }
  2036. Value *SplatToVector(Value *Elt, Type *DstTy, IRBuilder<> &Builder) {
  2037. Value *Result = UndefValue::get(DstTy);
  2038. for (unsigned i = 0; i < DstTy->getVectorNumElements(); i++)
  2039. Result = Builder.CreateInsertElement(Result, Elt, i);
  2040. return Result;
  2041. }
  2042. // Sample intrinsics.
  2043. struct SampleHelper {
  2044. SampleHelper(CallInst *CI, OP::OpCode op, HLObjectOperationLowerHelper *pObjHelper);
  2045. OP::OpCode opcode;
  2046. Value *texHandle;
  2047. Value *samplerHandle;
  2048. static const unsigned kMaxCoordDimensions = 4;
  2049. Value *coord[kMaxCoordDimensions];
  2050. Value *special; // For CompareValue, Bias, LOD.
  2051. // SampleGrad only.
  2052. static const unsigned kMaxDDXYDimensions = 3;
  2053. Value *ddx[kMaxDDXYDimensions];
  2054. Value *ddy[kMaxDDXYDimensions];
  2055. // Optional.
  2056. static const unsigned kMaxOffsetDimensions = 3;
  2057. Value *offset[kMaxOffsetDimensions];
  2058. Value *clamp;
  2059. Value *status;
  2060. void TranslateCoord(CallInst *CI, unsigned coordIdx,
  2061. unsigned coordDimensions) {
  2062. Value *coordArg = CI->getArgOperand(coordIdx);
  2063. IRBuilder<> Builder(CI);
  2064. for (unsigned i = 0; i < coordDimensions; i++)
  2065. coord[i] = Builder.CreateExtractElement(coordArg, i);
  2066. Value *undefF = UndefValue::get(Type::getFloatTy(CI->getContext()));
  2067. for (unsigned i = coordDimensions; i < kMaxCoordDimensions; i++)
  2068. coord[i] = undefF;
  2069. }
  2070. void TranslateOffset(CallInst *CI, unsigned offsetIdx,
  2071. unsigned offsetDimensions) {
  2072. Value *undefI = UndefValue::get(Type::getInt32Ty(CI->getContext()));
  2073. if (CI->getNumArgOperands() > offsetIdx) {
  2074. Value *offsetArg = CI->getArgOperand(offsetIdx);
  2075. IRBuilder<> Builder(CI);
  2076. for (unsigned i = 0; i < offsetDimensions; i++)
  2077. offset[i] = Builder.CreateExtractElement(offsetArg, i);
  2078. for (unsigned i = offsetDimensions; i < kMaxOffsetDimensions; i++)
  2079. offset[i] = undefI;
  2080. } else {
  2081. for (unsigned i = 0; i < kMaxOffsetDimensions; i++)
  2082. offset[i] = undefI;
  2083. }
  2084. }
  2085. void SetClamp(CallInst *CI, unsigned clampIdx) {
  2086. if (CI->getNumArgOperands() > clampIdx) {
  2087. clamp = CI->getArgOperand(clampIdx);
  2088. if (clamp->getType()->isVectorTy()) {
  2089. IRBuilder<> Builder(CI);
  2090. clamp = Builder.CreateExtractElement(clamp, (uint64_t)0);
  2091. }
  2092. } else
  2093. clamp = UndefValue::get(Type::getFloatTy(CI->getContext()));
  2094. }
  2095. void SetStatus(CallInst *CI, unsigned statusIdx) {
  2096. if (CI->getNumArgOperands() == (statusIdx + 1))
  2097. status = CI->getArgOperand(statusIdx);
  2098. else
  2099. status = nullptr;
  2100. }
  2101. void SetDDXY(CallInst *CI, MutableArrayRef<Value *> ddxy, Value *ddxyArg,
  2102. unsigned ddxySize) {
  2103. IRBuilder<> Builder(CI);
  2104. for (unsigned i = 0; i < ddxySize; i++)
  2105. ddxy[i] = Builder.CreateExtractElement(ddxyArg, i);
  2106. Value *undefF = UndefValue::get(Type::getFloatTy(CI->getContext()));
  2107. for (unsigned i = ddxySize; i < kMaxDDXYDimensions; i++)
  2108. ddxy[i] = undefF;
  2109. }
  2110. };
  2111. SampleHelper::SampleHelper(
  2112. CallInst *CI, OP::OpCode op, HLObjectOperationLowerHelper *pObjHelper)
  2113. : opcode(op) {
  2114. const unsigned thisIdx =
  2115. HLOperandIndex::kHandleOpIdx; // opcode takes arg0, this pointer is arg1.
  2116. const unsigned kSamplerArgIndex = HLOperandIndex::kSampleSamplerArgIndex;
  2117. IRBuilder<> Builder(CI);
  2118. texHandle = CI->getArgOperand(thisIdx);
  2119. samplerHandle = CI->getArgOperand(kSamplerArgIndex);
  2120. DXIL::ResourceKind RK = pObjHelper->GetRK(texHandle);
  2121. if (RK == DXIL::ResourceKind::Invalid) {
  2122. opcode = DXIL::OpCode::NumOpCodes;
  2123. return;
  2124. }
  2125. unsigned coordDimensions = DxilResource::GetNumCoords(RK);
  2126. unsigned offsetDimensions = DxilResource::GetNumOffsets(RK);
  2127. const unsigned kCoordArgIdx = HLOperandIndex::kSampleCoordArgIndex;
  2128. TranslateCoord(CI, kCoordArgIdx, coordDimensions);
  2129. special = nullptr;
  2130. switch (op) {
  2131. case OP::OpCode::Sample:
  2132. TranslateOffset(CI, HLOperandIndex::kSampleOffsetArgIndex,
  2133. offsetDimensions);
  2134. SetClamp(CI, HLOperandIndex::kSampleClampArgIndex);
  2135. SetStatus(CI, HLOperandIndex::kSampleStatusArgIndex);
  2136. break;
  2137. case OP::OpCode::SampleLevel:
  2138. special = CI->getArgOperand(HLOperandIndex::kSampleLLevelArgIndex);
  2139. TranslateOffset(CI, HLOperandIndex::kSampleLOffsetArgIndex,
  2140. offsetDimensions);
  2141. SetStatus(CI, HLOperandIndex::kSampleLStatusArgIndex);
  2142. break;
  2143. case OP::OpCode::SampleBias:
  2144. special = CI->getArgOperand(HLOperandIndex::kSampleBBiasArgIndex);
  2145. TranslateOffset(CI, HLOperandIndex::kSampleBOffsetArgIndex,
  2146. offsetDimensions);
  2147. SetClamp(CI, HLOperandIndex::kSampleBClampArgIndex);
  2148. SetStatus(CI, HLOperandIndex::kSampleBStatusArgIndex);
  2149. break;
  2150. case OP::OpCode::SampleCmp:
  2151. special = CI->getArgOperand(HLOperandIndex::kSampleCmpCmpValArgIndex);
  2152. TranslateOffset(CI, HLOperandIndex::kSampleCmpOffsetArgIndex,
  2153. offsetDimensions);
  2154. SetClamp(CI, HLOperandIndex::kSampleCmpClampArgIndex);
  2155. SetStatus(CI, HLOperandIndex::kSampleCmpStatusArgIndex);
  2156. break;
  2157. case OP::OpCode::SampleCmpLevelZero:
  2158. special = CI->getArgOperand(HLOperandIndex::kSampleCmpLZCmpValArgIndex);
  2159. TranslateOffset(CI, HLOperandIndex::kSampleCmpLZOffsetArgIndex,
  2160. offsetDimensions);
  2161. SetStatus(CI, HLOperandIndex::kSampleCmpLZStatusArgIndex);
  2162. break;
  2163. case OP::OpCode::SampleGrad:
  2164. SetDDXY(CI, ddx, CI->getArgOperand(HLOperandIndex::kSampleGDDXArgIndex),
  2165. offsetDimensions);
  2166. SetDDXY(CI, ddy, CI->getArgOperand(HLOperandIndex::kSampleGDDYArgIndex),
  2167. offsetDimensions);
  2168. TranslateOffset(CI, HLOperandIndex::kSampleGOffsetArgIndex,
  2169. offsetDimensions);
  2170. SetClamp(CI, HLOperandIndex::kSampleGClampArgIndex);
  2171. SetStatus(CI, HLOperandIndex::kSampleGStatusArgIndex);
  2172. break;
  2173. case OP::OpCode::CalculateLOD:
  2174. // Only need coord for LOD calculation.
  2175. break;
  2176. default:
  2177. DXASSERT(0, "invalid opcode for Sample");
  2178. break;
  2179. }
  2180. }
  2181. Value *TranslateCalculateLOD(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  2182. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  2183. hlsl::OP *hlslOP = &helper.hlslOP;
  2184. SampleHelper sampleHelper(CI, OP::OpCode::CalculateLOD, pObjHelper);
  2185. if (sampleHelper.opcode == DXIL::OpCode::NumOpCodes) {
  2186. Translated = false;
  2187. return nullptr;
  2188. }
  2189. bool bClamped = IOP == IntrinsicOp::MOP_CalculateLevelOfDetail;
  2190. IRBuilder<> Builder(CI);
  2191. Value *opArg =
  2192. hlslOP->GetU32Const(static_cast<unsigned>(OP::OpCode::CalculateLOD));
  2193. Value *clamped = hlslOP->GetI1Const(bClamped);
  2194. Value *args[] = {opArg,
  2195. sampleHelper.texHandle,
  2196. sampleHelper.samplerHandle,
  2197. sampleHelper.coord[0],
  2198. sampleHelper.coord[1],
  2199. sampleHelper.coord[2],
  2200. clamped};
  2201. Function *dxilFunc = hlslOP->GetOpFunc(OP::OpCode::CalculateLOD,
  2202. Type::getFloatTy(opArg->getContext()));
  2203. Value *LOD = Builder.CreateCall(dxilFunc, args);
  2204. return LOD;
  2205. }
  2206. void GenerateDxilSample(CallInst *CI, Function *F, ArrayRef<Value *> sampleArgs,
  2207. Value *status) {
  2208. IRBuilder<> Builder(CI);
  2209. CallInst *call = Builder.CreateCall(F, sampleArgs);
  2210. // extract value part
  2211. Value *retVal = ScalarizeResRet(CI->getType(), call, Builder);
  2212. // Replace ret val.
  2213. CI->replaceAllUsesWith(retVal);
  2214. // get status
  2215. if (status) {
  2216. UpdateStatus(call, status, Builder);
  2217. }
  2218. }
  2219. Value *TranslateSample(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  2220. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  2221. hlsl::OP *hlslOP = &helper.hlslOP;
  2222. SampleHelper sampleHelper(CI, opcode, pObjHelper);
  2223. if (sampleHelper.opcode == DXIL::OpCode::NumOpCodes) {
  2224. Translated = false;
  2225. return nullptr;
  2226. }
  2227. Type *Ty = CI->getType();
  2228. Function *F = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  2229. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  2230. switch (opcode) {
  2231. case OP::OpCode::Sample: {
  2232. Value *sampleArgs[] = {
  2233. opArg, sampleHelper.texHandle, sampleHelper.samplerHandle,
  2234. // Coord.
  2235. sampleHelper.coord[0], sampleHelper.coord[1], sampleHelper.coord[2],
  2236. sampleHelper.coord[3],
  2237. // Offset.
  2238. sampleHelper.offset[0], sampleHelper.offset[1], sampleHelper.offset[2],
  2239. // Clamp.
  2240. sampleHelper.clamp};
  2241. GenerateDxilSample(CI, F, sampleArgs, sampleHelper.status);
  2242. } break;
  2243. case OP::OpCode::SampleLevel: {
  2244. Value *sampleArgs[] = {
  2245. opArg, sampleHelper.texHandle, sampleHelper.samplerHandle,
  2246. // Coord.
  2247. sampleHelper.coord[0], sampleHelper.coord[1], sampleHelper.coord[2],
  2248. sampleHelper.coord[3],
  2249. // Offset.
  2250. sampleHelper.offset[0], sampleHelper.offset[1], sampleHelper.offset[2],
  2251. // LOD.
  2252. sampleHelper.special};
  2253. GenerateDxilSample(CI, F, sampleArgs, sampleHelper.status);
  2254. } break;
  2255. case OP::OpCode::SampleGrad: {
  2256. Value *sampleArgs[] = {
  2257. opArg, sampleHelper.texHandle, sampleHelper.samplerHandle,
  2258. // Coord.
  2259. sampleHelper.coord[0], sampleHelper.coord[1], sampleHelper.coord[2],
  2260. sampleHelper.coord[3],
  2261. // Offset.
  2262. sampleHelper.offset[0], sampleHelper.offset[1], sampleHelper.offset[2],
  2263. // Ddx.
  2264. sampleHelper.ddx[0], sampleHelper.ddx[1], sampleHelper.ddx[2],
  2265. // Ddy.
  2266. sampleHelper.ddy[0], sampleHelper.ddy[1], sampleHelper.ddy[2],
  2267. // Clamp.
  2268. sampleHelper.clamp};
  2269. GenerateDxilSample(CI, F, sampleArgs, sampleHelper.status);
  2270. } break;
  2271. case OP::OpCode::SampleBias: {
  2272. // Clamp bias for immediate.
  2273. Value *bias = sampleHelper.special;
  2274. if (ConstantFP *FP = dyn_cast<ConstantFP>(bias)) {
  2275. float v = FP->getValueAPF().convertToFloat();
  2276. if (v > DXIL::kMaxMipLodBias)
  2277. bias = ConstantFP::get(FP->getType(), DXIL::kMaxMipLodBias);
  2278. if (v < DXIL::kMinMipLodBias)
  2279. bias = ConstantFP::get(FP->getType(), DXIL::kMinMipLodBias);
  2280. }
  2281. Value *sampleArgs[] = {
  2282. opArg, sampleHelper.texHandle, sampleHelper.samplerHandle,
  2283. // Coord.
  2284. sampleHelper.coord[0], sampleHelper.coord[1], sampleHelper.coord[2],
  2285. sampleHelper.coord[3],
  2286. // Offset.
  2287. sampleHelper.offset[0], sampleHelper.offset[1], sampleHelper.offset[2],
  2288. // Bias.
  2289. bias,
  2290. // Clamp.
  2291. sampleHelper.clamp};
  2292. GenerateDxilSample(CI, F, sampleArgs, sampleHelper.status);
  2293. } break;
  2294. case OP::OpCode::SampleCmp: {
  2295. Value *sampleArgs[] = {
  2296. opArg, sampleHelper.texHandle, sampleHelper.samplerHandle,
  2297. // Coord.
  2298. sampleHelper.coord[0], sampleHelper.coord[1], sampleHelper.coord[2],
  2299. sampleHelper.coord[3],
  2300. // Offset.
  2301. sampleHelper.offset[0], sampleHelper.offset[1], sampleHelper.offset[2],
  2302. // CmpVal.
  2303. sampleHelper.special,
  2304. // Clamp.
  2305. sampleHelper.clamp};
  2306. GenerateDxilSample(CI, F, sampleArgs, sampleHelper.status);
  2307. } break;
  2308. case OP::OpCode::SampleCmpLevelZero:
  2309. default: {
  2310. DXASSERT(opcode == OP::OpCode::SampleCmpLevelZero, "invalid sample opcode");
  2311. Value *sampleArgs[] = {
  2312. opArg, sampleHelper.texHandle, sampleHelper.samplerHandle,
  2313. // Coord.
  2314. sampleHelper.coord[0], sampleHelper.coord[1], sampleHelper.coord[2],
  2315. sampleHelper.coord[3],
  2316. // Offset.
  2317. sampleHelper.offset[0], sampleHelper.offset[1], sampleHelper.offset[2],
  2318. // CmpVal.
  2319. sampleHelper.special};
  2320. GenerateDxilSample(CI, F, sampleArgs, sampleHelper.status);
  2321. } break;
  2322. }
  2323. // CI is replaced in GenerateDxilSample.
  2324. return nullptr;
  2325. }
  2326. // Gather intrinsics.
  2327. struct GatherHelper {
  2328. enum class GatherChannel {
  2329. GatherAll,
  2330. GatherRed,
  2331. GatherGreen,
  2332. GatherBlue,
  2333. GatherAlpha,
  2334. };
  2335. GatherHelper(CallInst *CI, OP::OpCode op, HLObjectOperationLowerHelper *pObjHelper,
  2336. GatherHelper::GatherChannel ch);
  2337. OP::OpCode opcode;
  2338. Value *texHandle;
  2339. Value *samplerHandle;
  2340. static const unsigned kMaxCoordDimensions = 4;
  2341. Value *coord[kMaxCoordDimensions];
  2342. unsigned channel;
  2343. Value *special; // For CompareValue, Bias, LOD.
  2344. // Optional.
  2345. static const unsigned kMaxOffsetDimensions = 2;
  2346. Value *offset[kMaxOffsetDimensions];
  2347. // For the overload send different offset for each sample.
  2348. // Only save 3 sampleOffsets because use offset for normal overload as first
  2349. // sample offset.
  2350. static const unsigned kSampleOffsetDimensions = 3;
  2351. Value *sampleOffsets[kSampleOffsetDimensions][kMaxOffsetDimensions];
  2352. Value *status;
  2353. bool hasSampleOffsets;
  2354. void TranslateCoord(CallInst *CI, unsigned coordIdx,
  2355. unsigned coordDimensions) {
  2356. Value *coordArg = CI->getArgOperand(coordIdx);
  2357. IRBuilder<> Builder(CI);
  2358. for (unsigned i = 0; i < coordDimensions; i++)
  2359. coord[i] = Builder.CreateExtractElement(coordArg, i);
  2360. Value *undefF = UndefValue::get(Type::getFloatTy(CI->getContext()));
  2361. for (unsigned i = coordDimensions; i < kMaxCoordDimensions; i++)
  2362. coord[i] = undefF;
  2363. }
  2364. void SetStatus(CallInst *CI, unsigned statusIdx) {
  2365. if (CI->getNumArgOperands() == (statusIdx + 1))
  2366. status = CI->getArgOperand(statusIdx);
  2367. else
  2368. status = nullptr;
  2369. }
  2370. void TranslateOffset(CallInst *CI, unsigned offsetIdx,
  2371. unsigned offsetDimensions) {
  2372. Value *undefI = UndefValue::get(Type::getInt32Ty(CI->getContext()));
  2373. if (CI->getNumArgOperands() > offsetIdx) {
  2374. Value *offsetArg = CI->getArgOperand(offsetIdx);
  2375. IRBuilder<> Builder(CI);
  2376. for (unsigned i = 0; i < offsetDimensions; i++)
  2377. offset[i] = Builder.CreateExtractElement(offsetArg, i);
  2378. for (unsigned i = offsetDimensions; i < kMaxOffsetDimensions; i++)
  2379. offset[i] = undefI;
  2380. } else {
  2381. for (unsigned i = 0; i < kMaxOffsetDimensions; i++)
  2382. offset[i] = undefI;
  2383. }
  2384. }
  2385. void TranslateSampleOffset(CallInst *CI, unsigned offsetIdx,
  2386. unsigned offsetDimensions) {
  2387. Value *undefI = UndefValue::get(Type::getInt32Ty(CI->getContext()));
  2388. if (CI->getNumArgOperands() >= (offsetIdx + kSampleOffsetDimensions)) {
  2389. hasSampleOffsets = true;
  2390. IRBuilder<> Builder(CI);
  2391. for (unsigned ch = 0; ch < kSampleOffsetDimensions; ch++) {
  2392. Value *offsetArg = CI->getArgOperand(offsetIdx + ch);
  2393. for (unsigned i = 0; i < offsetDimensions; i++)
  2394. sampleOffsets[ch][i] = Builder.CreateExtractElement(offsetArg, i);
  2395. for (unsigned i = offsetDimensions; i < kMaxOffsetDimensions; i++)
  2396. sampleOffsets[ch][i] = undefI;
  2397. }
  2398. }
  2399. }
  2400. // Update the offset args for gather with sample offset at sampleIdx.
  2401. void UpdateOffsetInGatherArgs(MutableArrayRef<Value *> gatherArgs,
  2402. unsigned sampleIdx) {
  2403. unsigned offsetBase = DXIL::OperandIndex::kTextureGatherOffset0OpIdx;
  2404. for (unsigned i = 0; i < kMaxOffsetDimensions; i++)
  2405. // -1 because offset for sample 0 is in GatherHelper::offset.
  2406. gatherArgs[offsetBase + i] = sampleOffsets[sampleIdx - 1][i];
  2407. }
  2408. };
  2409. GatherHelper::GatherHelper(
  2410. CallInst *CI, OP::OpCode op, HLObjectOperationLowerHelper *pObjHelper,
  2411. GatherHelper::GatherChannel ch)
  2412. : opcode(op), special(nullptr), hasSampleOffsets(false) {
  2413. const unsigned thisIdx =
  2414. HLOperandIndex::kHandleOpIdx; // opcode takes arg0, this pointer is arg1.
  2415. const unsigned kSamplerArgIndex = HLOperandIndex::kSampleSamplerArgIndex;
  2416. switch (ch) {
  2417. case GatherChannel::GatherAll:
  2418. channel = 0;
  2419. break;
  2420. case GatherChannel::GatherRed:
  2421. channel = 0;
  2422. break;
  2423. case GatherChannel::GatherGreen:
  2424. channel = 1;
  2425. break;
  2426. case GatherChannel::GatherBlue:
  2427. channel = 2;
  2428. break;
  2429. case GatherChannel::GatherAlpha:
  2430. channel = 3;
  2431. break;
  2432. }
  2433. IRBuilder<> Builder(CI);
  2434. texHandle = CI->getArgOperand(thisIdx);
  2435. samplerHandle = CI->getArgOperand(kSamplerArgIndex);
  2436. DXIL::ResourceKind RK = pObjHelper->GetRK(texHandle);
  2437. if (RK == DXIL::ResourceKind::Invalid) {
  2438. opcode = DXIL::OpCode::NumOpCodes;
  2439. return;
  2440. }
  2441. unsigned coordSize = DxilResource::GetNumCoords(RK);
  2442. unsigned offsetSize = DxilResource::GetNumOffsets(RK);
  2443. const unsigned kCoordArgIdx = HLOperandIndex::kSampleCoordArgIndex;
  2444. TranslateCoord(CI, kCoordArgIdx, coordSize);
  2445. switch (op) {
  2446. case OP::OpCode::TextureGather: {
  2447. TranslateOffset(CI, HLOperandIndex::kGatherOffsetArgIndex, offsetSize);
  2448. // Gather all don't have sample offset version overload.
  2449. if (ch != GatherChannel::GatherAll)
  2450. TranslateSampleOffset(CI, HLOperandIndex::kGatherSampleOffsetArgIndex,
  2451. offsetSize);
  2452. unsigned statusIdx =
  2453. hasSampleOffsets ? HLOperandIndex::kGatherStatusWithSampleOffsetArgIndex
  2454. : HLOperandIndex::kGatherStatusArgIndex;
  2455. SetStatus(CI, statusIdx);
  2456. } break;
  2457. case OP::OpCode::TextureGatherCmp: {
  2458. special = CI->getArgOperand(HLOperandIndex::kGatherCmpCmpValArgIndex);
  2459. TranslateOffset(CI, HLOperandIndex::kGatherCmpOffsetArgIndex, offsetSize);
  2460. // Gather all don't have sample offset version overload.
  2461. if (ch != GatherChannel::GatherAll)
  2462. TranslateSampleOffset(CI, HLOperandIndex::kGatherCmpSampleOffsetArgIndex,
  2463. offsetSize);
  2464. unsigned statusIdx =
  2465. hasSampleOffsets
  2466. ? HLOperandIndex::kGatherCmpStatusWithSampleOffsetArgIndex
  2467. : HLOperandIndex::kGatherCmpStatusArgIndex;
  2468. SetStatus(CI, statusIdx);
  2469. } break;
  2470. default:
  2471. DXASSERT(0, "invalid opcode for Gather");
  2472. break;
  2473. }
  2474. }
  2475. void GenerateDxilGather(CallInst *CI, Function *F,
  2476. MutableArrayRef<Value *> gatherArgs,
  2477. GatherHelper &helper) {
  2478. IRBuilder<> Builder(CI);
  2479. CallInst *call = Builder.CreateCall(F, gatherArgs);
  2480. if (!helper.hasSampleOffsets) {
  2481. // extract value part
  2482. Value *retVal = ScalarizeResRet(CI->getType(), call, Builder);
  2483. // Replace ret val.
  2484. CI->replaceAllUsesWith(retVal);
  2485. } else {
  2486. Value *retVal = UndefValue::get(CI->getType());
  2487. Value *elt = Builder.CreateExtractValue(call, (uint64_t)0);
  2488. retVal = Builder.CreateInsertElement(retVal, elt, (uint64_t)0);
  2489. helper.UpdateOffsetInGatherArgs(gatherArgs, /*sampleIdx*/ 1);
  2490. CallInst *callY = Builder.CreateCall(F, gatherArgs);
  2491. elt = Builder.CreateExtractValue(callY, (uint64_t)0);
  2492. retVal = Builder.CreateInsertElement(retVal, elt, 1);
  2493. helper.UpdateOffsetInGatherArgs(gatherArgs, /*sampleIdx*/ 2);
  2494. CallInst *callZ = Builder.CreateCall(F, gatherArgs);
  2495. elt = Builder.CreateExtractValue(callZ, (uint64_t)0);
  2496. retVal = Builder.CreateInsertElement(retVal, elt, 2);
  2497. helper.UpdateOffsetInGatherArgs(gatherArgs, /*sampleIdx*/ 3);
  2498. CallInst *callW = Builder.CreateCall(F, gatherArgs);
  2499. elt = Builder.CreateExtractValue(callW, (uint64_t)0);
  2500. retVal = Builder.CreateInsertElement(retVal, elt, 3);
  2501. // Replace ret val.
  2502. CI->replaceAllUsesWith(retVal);
  2503. // TODO: UpdateStatus for each gather call.
  2504. }
  2505. // Get status
  2506. if (helper.status) {
  2507. UpdateStatus(call, helper.status, Builder);
  2508. }
  2509. }
  2510. Value *TranslateGather(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  2511. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  2512. hlsl::OP *hlslOP = &helper.hlslOP;
  2513. GatherHelper::GatherChannel ch = GatherHelper::GatherChannel::GatherAll;
  2514. switch (IOP) {
  2515. case IntrinsicOp::MOP_Gather:
  2516. case IntrinsicOp::MOP_GatherCmp:
  2517. ch = GatherHelper::GatherChannel::GatherAll;
  2518. break;
  2519. case IntrinsicOp::MOP_GatherRed:
  2520. case IntrinsicOp::MOP_GatherCmpRed:
  2521. ch = GatherHelper::GatherChannel::GatherRed;
  2522. break;
  2523. case IntrinsicOp::MOP_GatherGreen:
  2524. case IntrinsicOp::MOP_GatherCmpGreen:
  2525. ch = GatherHelper::GatherChannel::GatherGreen;
  2526. break;
  2527. case IntrinsicOp::MOP_GatherBlue:
  2528. case IntrinsicOp::MOP_GatherCmpBlue:
  2529. ch = GatherHelper::GatherChannel::GatherBlue;
  2530. break;
  2531. case IntrinsicOp::MOP_GatherAlpha:
  2532. case IntrinsicOp::MOP_GatherCmpAlpha:
  2533. ch = GatherHelper::GatherChannel::GatherAlpha;
  2534. break;
  2535. default:
  2536. DXASSERT(0, "invalid gather intrinsic");
  2537. break;
  2538. }
  2539. GatherHelper gatherHelper(CI, opcode, pObjHelper, ch);
  2540. if (gatherHelper.opcode == DXIL::OpCode::NumOpCodes) {
  2541. Translated = false;
  2542. return nullptr;
  2543. }
  2544. Type *Ty = CI->getType();
  2545. Function *F = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  2546. Constant *opArg = hlslOP->GetU32Const((unsigned)opcode);
  2547. Value *channelArg = hlslOP->GetU32Const(gatherHelper.channel);
  2548. switch (opcode) {
  2549. case OP::OpCode::TextureGather: {
  2550. Value *gatherArgs[] = {
  2551. opArg, gatherHelper.texHandle, gatherHelper.samplerHandle,
  2552. // Coord.
  2553. gatherHelper.coord[0], gatherHelper.coord[1], gatherHelper.coord[2],
  2554. gatherHelper.coord[3],
  2555. // Offset.
  2556. gatherHelper.offset[0], gatherHelper.offset[1],
  2557. // Channel.
  2558. channelArg};
  2559. GenerateDxilGather(CI, F, gatherArgs, gatherHelper);
  2560. } break;
  2561. case OP::OpCode::TextureGatherCmp: {
  2562. Value *gatherArgs[] = {
  2563. opArg, gatherHelper.texHandle, gatherHelper.samplerHandle,
  2564. // Coord.
  2565. gatherHelper.coord[0], gatherHelper.coord[1], gatherHelper.coord[2],
  2566. gatherHelper.coord[3],
  2567. // Offset.
  2568. gatherHelper.offset[0], gatherHelper.offset[1],
  2569. // Channel.
  2570. channelArg,
  2571. // CmpVal.
  2572. gatherHelper.special};
  2573. GenerateDxilGather(CI, F, gatherArgs, gatherHelper);
  2574. } break;
  2575. default:
  2576. DXASSERT(0, "invalid opcode for Gather");
  2577. break;
  2578. }
  2579. // CI is replaced in GenerateDxilGather.
  2580. return nullptr;
  2581. }
  2582. // Load/Store intrinsics.
  2583. struct ResLoadHelper {
  2584. ResLoadHelper(CallInst *CI, DxilResource::Kind RK, DxilResourceBase::Class RC,
  2585. Value *h, bool bForSubscript=false);
  2586. ResLoadHelper(CallInst *CI, DxilResource::Kind RK, DxilResourceBase::Class RC,
  2587. Value *h, Value *mip);
  2588. // For double subscript.
  2589. ResLoadHelper(Instruction *ldInst, Value *h, Value *idx, Value *mip)
  2590. : opcode(OP::OpCode::TextureLoad), handle(h), retVal(ldInst), addr(idx),
  2591. offset(nullptr), status(nullptr), mipLevel(mip) {}
  2592. OP::OpCode opcode;
  2593. Value *handle;
  2594. Value *retVal;
  2595. Value *addr;
  2596. Value *offset;
  2597. Value *status;
  2598. Value *mipLevel;
  2599. };
  2600. ResLoadHelper::ResLoadHelper(CallInst *CI, DxilResource::Kind RK,
  2601. DxilResourceBase::Class RC, Value *hdl, bool bForSubscript)
  2602. : handle(hdl), offset(nullptr), status(nullptr) {
  2603. switch (RK) {
  2604. case DxilResource::Kind::RawBuffer:
  2605. case DxilResource::Kind::TypedBuffer:
  2606. case DxilResource::Kind::StructuredBuffer:
  2607. opcode = OP::OpCode::BufferLoad;
  2608. break;
  2609. case DxilResource::Kind::Invalid:
  2610. DXASSERT(0, "invalid resource kind");
  2611. break;
  2612. default:
  2613. opcode = OP::OpCode::TextureLoad;
  2614. break;
  2615. }
  2616. retVal = CI;
  2617. const unsigned kAddrIdx = HLOperandIndex::kBufLoadAddrOpIdx;
  2618. addr = CI->getArgOperand(kAddrIdx);
  2619. unsigned argc = CI->getNumArgOperands();
  2620. if (opcode == OP::OpCode::TextureLoad) {
  2621. // mip at last channel
  2622. unsigned coordSize = DxilResource::GetNumCoords(RK);
  2623. if (RC == DxilResourceBase::Class::SRV) {
  2624. if (bForSubscript) {
  2625. // Use 0 when access by [].
  2626. mipLevel = IRBuilder<>(CI).getInt32(0);
  2627. } else {
  2628. if (coordSize == 1 && !addr->getType()->isVectorTy()) {
  2629. // Use addr when access by Load.
  2630. mipLevel = addr;
  2631. } else {
  2632. mipLevel = IRBuilder<>(CI).CreateExtractElement(addr, coordSize);
  2633. }
  2634. }
  2635. } else {
  2636. // Set mip level to undef for UAV.
  2637. mipLevel = UndefValue::get(Type::getInt32Ty(addr->getContext()));
  2638. }
  2639. if (RC == DxilResourceBase::Class::SRV) {
  2640. unsigned offsetIdx = HLOperandIndex::kTexLoadOffsetOpIdx;
  2641. unsigned statusIdx = HLOperandIndex::kTexLoadStatusOpIdx;
  2642. if (RK == DxilResource::Kind::Texture2DMS ||
  2643. RK == DxilResource::Kind::Texture2DMSArray) {
  2644. offsetIdx = HLOperandIndex::kTex2DMSLoadOffsetOpIdx;
  2645. statusIdx = HLOperandIndex::kTex2DMSLoadStatusOpIdx;
  2646. mipLevel =
  2647. CI->getArgOperand(HLOperandIndex::kTex2DMSLoadSampleIdxOpIdx);
  2648. }
  2649. if (argc > offsetIdx)
  2650. offset = CI->getArgOperand(offsetIdx);
  2651. if (argc > statusIdx)
  2652. status = CI->getArgOperand(statusIdx);
  2653. } else {
  2654. const unsigned kStatusIdx = HLOperandIndex::kRWTexLoadStatusOpIdx;
  2655. if (argc > kStatusIdx)
  2656. status = CI->getArgOperand(kStatusIdx);
  2657. }
  2658. } else {
  2659. const unsigned kStatusIdx = HLOperandIndex::kBufLoadStatusOpIdx;
  2660. if (argc > kStatusIdx)
  2661. status = CI->getArgOperand(kStatusIdx);
  2662. }
  2663. }
  2664. ResLoadHelper::ResLoadHelper(CallInst *CI, DxilResource::Kind RK,
  2665. DxilResourceBase::Class RC, Value *hdl, Value *mip)
  2666. : handle(hdl), offset(nullptr), status(nullptr) {
  2667. DXASSERT(RK != DxilResource::Kind::RawBuffer &&
  2668. RK != DxilResource::Kind::TypedBuffer &&
  2669. RK != DxilResource::Kind::Invalid,
  2670. "invalid resource kind");
  2671. opcode = OP::OpCode::TextureLoad;
  2672. retVal = CI;
  2673. mipLevel = mip;
  2674. const unsigned kAddrIdx = HLOperandIndex::kMipLoadAddrOpIdx;
  2675. addr = CI->getArgOperand(kAddrIdx);
  2676. unsigned argc = CI->getNumArgOperands();
  2677. const unsigned kOffsetIdx = HLOperandIndex::kMipLoadOffsetOpIdx;
  2678. const unsigned kStatusIdx = HLOperandIndex::kMipLoadStatusOpIdx;
  2679. if (argc > kOffsetIdx)
  2680. offset = CI->getArgOperand(kOffsetIdx);
  2681. if (argc > kStatusIdx)
  2682. status = CI->getArgOperand(kStatusIdx);
  2683. }
  2684. void TranslateStructBufSubscript(CallInst *CI, Value *handle, Value *status,
  2685. hlsl::OP *OP, const DataLayout &DL);
  2686. // Create { v0, v1 } from { v0.lo, v0.hi, v1.lo, v1.hi }
  2687. void Make64bitResultForLoad(Type *EltTy, ArrayRef<Value *> resultElts32,
  2688. unsigned size, MutableArrayRef<Value *> resultElts,
  2689. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  2690. Type *i64Ty = Builder.getInt64Ty();
  2691. Type *doubleTy = Builder.getDoubleTy();
  2692. if (EltTy == doubleTy) {
  2693. Function *makeDouble =
  2694. hlslOP->GetOpFunc(DXIL::OpCode::MakeDouble, doubleTy);
  2695. Value *makeDoubleOpArg =
  2696. Builder.getInt32((unsigned)DXIL::OpCode::MakeDouble);
  2697. for (unsigned i = 0; i < size; i++) {
  2698. Value *lo = resultElts32[2 * i];
  2699. Value *hi = resultElts32[2 * i + 1];
  2700. Value *V = Builder.CreateCall(makeDouble, {makeDoubleOpArg, lo, hi});
  2701. resultElts[i] = V;
  2702. }
  2703. } else {
  2704. for (unsigned i = 0; i < size; i++) {
  2705. Value *lo = resultElts32[2 * i];
  2706. Value *hi = resultElts32[2 * i + 1];
  2707. lo = Builder.CreateZExt(lo, i64Ty);
  2708. hi = Builder.CreateZExt(hi, i64Ty);
  2709. hi = Builder.CreateShl(hi, 32);
  2710. resultElts[i] = Builder.CreateOr(lo, hi);
  2711. }
  2712. }
  2713. }
  2714. void TranslateLoad(ResLoadHelper &helper, HLResource::Kind RK,
  2715. IRBuilder<> &Builder, hlsl::OP *OP, const DataLayout &DL) {
  2716. Type *Ty = helper.retVal->getType();
  2717. if (Ty->isPointerTy()) {
  2718. TranslateStructBufSubscript(cast<CallInst>(helper.retVal), helper.handle,
  2719. helper.status, OP, DL);
  2720. return;
  2721. }
  2722. OP::OpCode opcode = helper.opcode;
  2723. Type *i32Ty = Builder.getInt32Ty();
  2724. Type *i64Ty = Builder.getInt64Ty();
  2725. Type *doubleTy = Builder.getDoubleTy();
  2726. Type *EltTy = Ty->getScalarType();
  2727. bool is64 = EltTy == i64Ty || EltTy == doubleTy;
  2728. if (is64) {
  2729. EltTy = i32Ty;
  2730. }
  2731. Function *F = OP->GetOpFunc(opcode, EltTy);
  2732. llvm::Constant *opArg = OP->GetU32Const((unsigned)opcode);
  2733. llvm::Value *undefI = llvm::UndefValue::get(i32Ty);
  2734. SmallVector<Value *, 12> loadArgs;
  2735. loadArgs.emplace_back(opArg); // opcode
  2736. loadArgs.emplace_back(helper.handle); // resource handle
  2737. if (opcode == OP::OpCode::TextureLoad) {
  2738. // set mip level
  2739. loadArgs.emplace_back(helper.mipLevel);
  2740. }
  2741. if (opcode == OP::OpCode::TextureLoad) {
  2742. // texture coord
  2743. unsigned coordSize = DxilResource::GetNumCoords(RK);
  2744. bool isVectorAddr = helper.addr->getType()->isVectorTy();
  2745. for (unsigned i = 0; i < 3; i++) {
  2746. if (i < coordSize) {
  2747. loadArgs.emplace_back(
  2748. isVectorAddr ? Builder.CreateExtractElement(helper.addr, i) : helper.addr);
  2749. }
  2750. else
  2751. loadArgs.emplace_back(undefI);
  2752. }
  2753. } else {
  2754. if (helper.addr->getType()->isVectorTy()) {
  2755. Value *scalarOffset =
  2756. Builder.CreateExtractElement(helper.addr, (uint64_t)0);
  2757. // TODO: calculate the real address based on opcode
  2758. loadArgs.emplace_back(scalarOffset); // offset
  2759. } else {
  2760. // TODO: calculate the real address based on opcode
  2761. loadArgs.emplace_back(helper.addr); // offset
  2762. }
  2763. }
  2764. // offset 0
  2765. if (opcode == OP::OpCode::TextureLoad) {
  2766. if (helper.offset && !isa<llvm::UndefValue>(helper.offset)) {
  2767. unsigned offsetSize = DxilResource::GetNumOffsets(RK);
  2768. for (unsigned i = 0; i < 3; i++) {
  2769. if (i < offsetSize)
  2770. loadArgs.emplace_back(Builder.CreateExtractElement(helper.offset, i));
  2771. else
  2772. loadArgs.emplace_back(undefI);
  2773. }
  2774. } else {
  2775. loadArgs.emplace_back(undefI);
  2776. loadArgs.emplace_back(undefI);
  2777. loadArgs.emplace_back(undefI);
  2778. }
  2779. }
  2780. // Offset 1
  2781. if (RK == DxilResource::Kind::RawBuffer ||
  2782. RK == DxilResource::Kind::TypedBuffer) {
  2783. loadArgs.emplace_back(undefI);
  2784. } else if (RK == DxilResource::Kind::StructuredBuffer)
  2785. loadArgs.emplace_back(
  2786. OP->GetU32Const(0)); // For case use built-in types in structure buffer.
  2787. Value *ResRet =
  2788. Builder.CreateCall(F, loadArgs, OP->GetOpCodeName(opcode));
  2789. Value *retValNew = nullptr;
  2790. if (!is64) {
  2791. retValNew = ScalarizeResRet(Ty, ResRet, Builder);
  2792. } else {
  2793. unsigned size = 1;
  2794. if (Ty->isVectorTy()) {
  2795. size = Ty->getVectorNumElements();
  2796. }
  2797. DXASSERT(size <= 2, "typed buffer only allow 4 dwords");
  2798. EltTy = Ty->getScalarType();
  2799. Value *Elts[2];
  2800. Make64bitResultForLoad(Ty->getScalarType(),
  2801. {
  2802. Builder.CreateExtractValue(ResRet, 0),
  2803. Builder.CreateExtractValue(ResRet, 1),
  2804. Builder.CreateExtractValue(ResRet, 2),
  2805. Builder.CreateExtractValue(ResRet, 3),
  2806. },
  2807. size, Elts, OP, Builder);
  2808. retValNew = ScalarizeElements(Ty, Elts, Builder);
  2809. }
  2810. // replace
  2811. helper.retVal->replaceAllUsesWith(retValNew);
  2812. // Save new ret val.
  2813. helper.retVal = retValNew;
  2814. // get status
  2815. UpdateStatus(ResRet, helper.status, Builder);
  2816. }
  2817. Value *TranslateResourceLoad(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  2818. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  2819. hlsl::OP *hlslOP = &helper.hlslOP;
  2820. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  2821. IRBuilder<> Builder(CI);
  2822. DXIL::ResourceClass RC = pObjHelper->GetRC(handle);
  2823. DXIL::ResourceKind RK = pObjHelper->GetRK(handle);
  2824. ResLoadHelper loadHelper(CI, RK, RC, handle);
  2825. TranslateLoad(loadHelper, RK, Builder, hlslOP, helper.legacyDataLayout);
  2826. // CI is replaced in TranslateLoad.
  2827. return nullptr;
  2828. }
  2829. // Split { v0, v1 } to { v0.lo, v0.hi, v1.lo, v1.hi }
  2830. void Split64bitValForStore(Type *EltTy, ArrayRef<Value *> vals, unsigned size,
  2831. MutableArrayRef<Value *> vals32, hlsl::OP *hlslOP,
  2832. IRBuilder<> &Builder) {
  2833. Type *i32Ty = Builder.getInt32Ty();
  2834. Type *doubleTy = Builder.getDoubleTy();
  2835. Value *undefI32 = UndefValue::get(i32Ty);
  2836. if (EltTy == doubleTy) {
  2837. Function *dToU = hlslOP->GetOpFunc(DXIL::OpCode::SplitDouble, doubleTy);
  2838. Value *dToUOpArg = Builder.getInt32((unsigned)DXIL::OpCode::SplitDouble);
  2839. for (unsigned i = 0; i < size; i++) {
  2840. if (isa<UndefValue>(vals[i])) {
  2841. vals32[2 * i] = undefI32;
  2842. vals32[2 * i + 1] = undefI32;
  2843. } else {
  2844. Value *retVal = Builder.CreateCall(dToU, {dToUOpArg, vals[i]});
  2845. Value *lo = Builder.CreateExtractValue(retVal, 0);
  2846. Value *hi = Builder.CreateExtractValue(retVal, 1);
  2847. vals32[2 * i] = lo;
  2848. vals32[2 * i + 1] = hi;
  2849. }
  2850. }
  2851. } else {
  2852. for (unsigned i = 0; i < size; i++) {
  2853. if (isa<UndefValue>(vals[i])) {
  2854. vals32[2 * i] = undefI32;
  2855. vals32[2 * i + 1] = undefI32;
  2856. } else {
  2857. Value *lo = Builder.CreateTrunc(vals[i], i32Ty);
  2858. Value *hi = Builder.CreateLShr(vals[i], 32);
  2859. hi = Builder.CreateTrunc(hi, i32Ty);
  2860. vals32[2 * i] = lo;
  2861. vals32[2 * i + 1] = hi;
  2862. }
  2863. }
  2864. }
  2865. }
  2866. void TranslateStore(DxilResource::Kind RK, Value *handle, Value *val,
  2867. Value *offset, IRBuilder<> &Builder, hlsl::OP *OP) {
  2868. Type *Ty = val->getType();
  2869. OP::OpCode opcode;
  2870. switch (RK) {
  2871. case DxilResource::Kind::RawBuffer:
  2872. case DxilResource::Kind::TypedBuffer:
  2873. opcode = OP::OpCode::BufferStore;
  2874. break;
  2875. case DxilResource::Kind::Invalid:
  2876. DXASSERT(0, "invalid resource kind");
  2877. break;
  2878. default:
  2879. opcode = OP::OpCode::TextureStore;
  2880. break;
  2881. }
  2882. Type *i32Ty = Builder.getInt32Ty();
  2883. Type *i64Ty = Builder.getInt64Ty();
  2884. Type *doubleTy = Builder.getDoubleTy();
  2885. Type *EltTy = Ty->getScalarType();
  2886. bool is64 = EltTy == i64Ty || EltTy == doubleTy;
  2887. if (is64) {
  2888. EltTy = i32Ty;
  2889. }
  2890. Function *F = OP->GetOpFunc(opcode, EltTy);
  2891. llvm::Constant *opArg = OP->GetU32Const((unsigned)opcode);
  2892. llvm::Value *undefI =
  2893. llvm::UndefValue::get(llvm::Type::getInt32Ty(Ty->getContext()));
  2894. llvm::Value *undefVal = llvm::UndefValue::get(Ty->getScalarType());
  2895. SmallVector<Value *, 13> storeArgs;
  2896. storeArgs.emplace_back(opArg); // opcode
  2897. storeArgs.emplace_back(handle); // resource handle
  2898. if (RK == DxilResource::Kind::RawBuffer ||
  2899. RK == DxilResource::Kind::TypedBuffer) {
  2900. // Offset 0
  2901. if (offset->getType()->isVectorTy()) {
  2902. Value *scalarOffset = Builder.CreateExtractElement(offset, (uint64_t)0);
  2903. storeArgs.emplace_back(scalarOffset); // offset
  2904. } else {
  2905. storeArgs.emplace_back(offset); // offset
  2906. }
  2907. // Offset 1
  2908. storeArgs.emplace_back(undefI);
  2909. } else {
  2910. // texture store
  2911. unsigned coordSize = DxilResource::GetNumCoords(RK);
  2912. // Set x first.
  2913. if (offset->getType()->isVectorTy())
  2914. storeArgs.emplace_back(Builder.CreateExtractElement(offset, (uint64_t)0));
  2915. else
  2916. storeArgs.emplace_back(offset);
  2917. for (unsigned i = 1; i < 3; i++) {
  2918. if (i < coordSize)
  2919. storeArgs.emplace_back(Builder.CreateExtractElement(offset, i));
  2920. else
  2921. storeArgs.emplace_back(undefI);
  2922. }
  2923. // TODO: support mip for texture ST
  2924. }
  2925. // values
  2926. bool isTyped = opcode == OP::OpCode::TextureStore ||
  2927. RK == DxilResource::Kind::TypedBuffer;
  2928. uint8_t mask = 0;
  2929. if (Ty->isVectorTy()) {
  2930. unsigned vecSize = Ty->getVectorNumElements();
  2931. Value *emptyVal = undefVal;
  2932. if (isTyped) {
  2933. mask = DXIL::kCompMask_All;
  2934. emptyVal = Builder.CreateExtractElement(val, (uint64_t)0);
  2935. }
  2936. for (unsigned i = 0; i < 4; i++) {
  2937. if (i < vecSize) {
  2938. storeArgs.emplace_back(Builder.CreateExtractElement(val, i));
  2939. mask |= (1<<i);
  2940. } else {
  2941. storeArgs.emplace_back(emptyVal);
  2942. }
  2943. }
  2944. } else {
  2945. if (isTyped) {
  2946. mask = DXIL::kCompMask_All;
  2947. storeArgs.emplace_back(val);
  2948. storeArgs.emplace_back(val);
  2949. storeArgs.emplace_back(val);
  2950. storeArgs.emplace_back(val);
  2951. } else {
  2952. storeArgs.emplace_back(val);
  2953. storeArgs.emplace_back(undefVal);
  2954. storeArgs.emplace_back(undefVal);
  2955. storeArgs.emplace_back(undefVal);
  2956. mask = DXIL::kCompMask_X;
  2957. }
  2958. }
  2959. if (is64) {
  2960. DXASSERT(mask == DXIL::kCompMask_All, "only typed buffer could have 64bit");
  2961. unsigned size = 1;
  2962. if (Ty->isVectorTy()) {
  2963. size = Ty->getVectorNumElements();
  2964. }
  2965. DXASSERT(size <= 2, "typed buffer only allow 4 dwords");
  2966. unsigned val0OpIdx = opcode == DXIL::OpCode::TextureStore
  2967. ? DXIL::OperandIndex::kTextureStoreVal0OpIdx
  2968. : DXIL::OperandIndex::kBufferStoreVal0OpIdx;
  2969. Value *V0 = storeArgs[val0OpIdx];
  2970. Value *V1 = storeArgs[val0OpIdx+1];
  2971. Value *vals32[4];
  2972. EltTy = Ty->getScalarType();
  2973. Split64bitValForStore(EltTy, {V0, V1}, size, vals32, OP, Builder);
  2974. // Fill the uninit vals.
  2975. if (size == 1) {
  2976. vals32[2] = vals32[0];
  2977. vals32[3] = vals32[1];
  2978. }
  2979. // Change valOp to 32 version.
  2980. for (unsigned i = 0; i < 4; i++) {
  2981. storeArgs[val0OpIdx + i] = vals32[i];
  2982. }
  2983. }
  2984. storeArgs.emplace_back(OP->GetU8Const(mask));
  2985. Builder.CreateCall(F, storeArgs);
  2986. }
  2987. Value *TranslateResourceStore(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  2988. HLOperationLowerHelper &helper,
  2989. HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  2990. hlsl::OP *hlslOP = &helper.hlslOP;
  2991. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  2992. IRBuilder<> Builder(CI);
  2993. DXIL::ResourceKind RK = pObjHelper->GetRK(handle);
  2994. Value *val = CI->getArgOperand(HLOperandIndex::kStoreValOpIdx);
  2995. Value *offset = CI->getArgOperand(HLOperandIndex::kStoreOffsetOpIdx);
  2996. TranslateStore(RK, handle, val, offset, Builder, hlslOP);
  2997. return nullptr;
  2998. }
  2999. }
  3000. // Atomic intrinsics.
  3001. namespace {
  3002. // Atomic intrinsics.
  3003. struct AtomicHelper {
  3004. AtomicHelper(CallInst *CI, OP::OpCode op, Value *h);
  3005. AtomicHelper(CallInst *CI, OP::OpCode op, Value *h, Value *bufIdx,
  3006. Value *baseOffset);
  3007. OP::OpCode opcode;
  3008. Value *handle;
  3009. Value *addr;
  3010. Value *offset; // Offset for structrued buffer.
  3011. Value *value;
  3012. Value *originalValue;
  3013. Value *compareValue;
  3014. };
  3015. // For MOP version of Interlocked*.
  3016. AtomicHelper::AtomicHelper(CallInst *CI, OP::OpCode op, Value *h)
  3017. : opcode(op), handle(h), offset(nullptr), originalValue(nullptr) {
  3018. addr = CI->getArgOperand(HLOperandIndex::kObjectInterlockedDestOpIndex);
  3019. if (op == OP::OpCode::AtomicCompareExchange) {
  3020. compareValue = CI->getArgOperand(
  3021. HLOperandIndex::kObjectInterlockedCmpCompareValueOpIndex);
  3022. value =
  3023. CI->getArgOperand(HLOperandIndex::kObjectInterlockedCmpValueOpIndex);
  3024. if (CI->getNumArgOperands() ==
  3025. (HLOperandIndex::kObjectInterlockedCmpOriginalValueOpIndex + 1))
  3026. originalValue = CI->getArgOperand(
  3027. HLOperandIndex::kObjectInterlockedCmpOriginalValueOpIndex);
  3028. } else {
  3029. value = CI->getArgOperand(HLOperandIndex::kObjectInterlockedValueOpIndex);
  3030. if (CI->getNumArgOperands() ==
  3031. (HLOperandIndex::kObjectInterlockedOriginalValueOpIndex + 1))
  3032. originalValue = CI->getArgOperand(
  3033. HLOperandIndex::kObjectInterlockedOriginalValueOpIndex);
  3034. }
  3035. }
  3036. // For IOP version of Interlocked*.
  3037. AtomicHelper::AtomicHelper(CallInst *CI, OP::OpCode op, Value *h, Value *bufIdx,
  3038. Value *baseOffset)
  3039. : opcode(op), handle(h), addr(bufIdx),
  3040. offset(baseOffset), originalValue(nullptr) {
  3041. if (op == OP::OpCode::AtomicCompareExchange) {
  3042. compareValue =
  3043. CI->getArgOperand(HLOperandIndex::kInterlockedCmpCompareValueOpIndex);
  3044. value = CI->getArgOperand(HLOperandIndex::kInterlockedCmpValueOpIndex);
  3045. if (CI->getNumArgOperands() ==
  3046. (HLOperandIndex::kInterlockedCmpOriginalValueOpIndex + 1))
  3047. originalValue = CI->getArgOperand(
  3048. HLOperandIndex::kInterlockedCmpOriginalValueOpIndex);
  3049. } else {
  3050. value = CI->getArgOperand(HLOperandIndex::kInterlockedValueOpIndex);
  3051. if (CI->getNumArgOperands() ==
  3052. (HLOperandIndex::kInterlockedOriginalValueOpIndex + 1))
  3053. originalValue =
  3054. CI->getArgOperand(HLOperandIndex::kInterlockedOriginalValueOpIndex);
  3055. }
  3056. }
  3057. void TranslateAtomicBinaryOperation(AtomicHelper &helper,
  3058. DXIL::AtomicBinOpCode atomicOp,
  3059. IRBuilder<> &Builder, hlsl::OP *hlslOP) {
  3060. Value *handle = helper.handle;
  3061. Value *addr = helper.addr;
  3062. Value *val = helper.value;
  3063. Type *Ty = val->getType();
  3064. Value *undefI = UndefValue::get(Type::getInt32Ty(Ty->getContext()));
  3065. Function *dxilAtomic = hlslOP->GetOpFunc(helper.opcode, Ty->getScalarType());
  3066. Value *opArg = hlslOP->GetU32Const(static_cast<unsigned>(helper.opcode));
  3067. Value *atomicOpArg = hlslOP->GetU32Const(static_cast<unsigned>(atomicOp));
  3068. Value *args[] = {opArg, handle, atomicOpArg,
  3069. undefI, undefI, undefI, // coordinates
  3070. val};
  3071. // Setup coordinates.
  3072. if (addr->getType()->isVectorTy()) {
  3073. unsigned vectorNumElements = addr->getType()->getVectorNumElements();
  3074. DXASSERT(vectorNumElements <= 3, "up to 3 elements for atomic binary op");
  3075. _Analysis_assume_(vectorNumElements <= 3);
  3076. for (unsigned i = 0; i < vectorNumElements; i++) {
  3077. Value *Elt = Builder.CreateExtractElement(addr, i);
  3078. args[DXIL::OperandIndex::kAtomicBinOpCoord0OpIdx + i] = Elt;
  3079. }
  3080. } else
  3081. args[DXIL::OperandIndex::kAtomicBinOpCoord0OpIdx] = addr;
  3082. // Set offset for structured buffer.
  3083. if (helper.offset)
  3084. args[DXIL::OperandIndex::kAtomicBinOpCoord1OpIdx] = helper.offset;
  3085. Value *origVal =
  3086. Builder.CreateCall(dxilAtomic, args, hlslOP->GetAtomicOpName(atomicOp));
  3087. if (helper.originalValue) {
  3088. Builder.CreateStore(origVal, helper.originalValue);
  3089. }
  3090. }
  3091. Value *TranslateMopAtomicBinaryOperation(CallInst *CI, IntrinsicOp IOP,
  3092. OP::OpCode opcode,
  3093. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3094. hlsl::OP *hlslOP = &helper.hlslOP;
  3095. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  3096. IRBuilder<> Builder(CI);
  3097. switch (IOP) {
  3098. case IntrinsicOp::MOP_InterlockedAdd: {
  3099. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3100. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Add, Builder,
  3101. hlslOP);
  3102. } break;
  3103. case IntrinsicOp::MOP_InterlockedAnd: {
  3104. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3105. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::And, Builder,
  3106. hlslOP);
  3107. } break;
  3108. case IntrinsicOp::MOP_InterlockedExchange: {
  3109. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3110. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Exchange,
  3111. Builder, hlslOP);
  3112. } break;
  3113. case IntrinsicOp::MOP_InterlockedMax: {
  3114. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3115. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::IMax, Builder,
  3116. hlslOP);
  3117. } break;
  3118. case IntrinsicOp::MOP_InterlockedMin: {
  3119. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3120. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::IMin, Builder,
  3121. hlslOP);
  3122. } break;
  3123. case IntrinsicOp::MOP_InterlockedUMax: {
  3124. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3125. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::UMax, Builder,
  3126. hlslOP);
  3127. } break;
  3128. case IntrinsicOp::MOP_InterlockedUMin: {
  3129. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3130. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::UMin, Builder,
  3131. hlslOP);
  3132. } break;
  3133. case IntrinsicOp::MOP_InterlockedOr: {
  3134. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3135. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Or, Builder,
  3136. hlslOP);
  3137. } break;
  3138. case IntrinsicOp::MOP_InterlockedXor: {
  3139. default:
  3140. DXASSERT(IOP == IntrinsicOp::MOP_InterlockedXor,
  3141. "invalid MOP atomic intrinsic");
  3142. AtomicHelper helper(CI, DXIL::OpCode::AtomicBinOp, handle);
  3143. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Xor, Builder,
  3144. hlslOP);
  3145. } break;
  3146. }
  3147. return nullptr;
  3148. }
  3149. void TranslateAtomicCmpXChg(AtomicHelper &helper, IRBuilder<> &Builder,
  3150. hlsl::OP *hlslOP) {
  3151. Value *handle = helper.handle;
  3152. Value *addr = helper.addr;
  3153. Value *val = helper.value;
  3154. Value *cmpVal = helper.compareValue;
  3155. Type *Ty = val->getType();
  3156. Value *undefI = UndefValue::get(Type::getInt32Ty(Ty->getContext()));
  3157. Function *dxilAtomic = hlslOP->GetOpFunc(helper.opcode, Ty->getScalarType());
  3158. Value *opArg = hlslOP->GetU32Const(static_cast<unsigned>(helper.opcode));
  3159. Value *args[] = {opArg, handle, undefI, undefI, undefI, // coordinates
  3160. cmpVal, val};
  3161. // Setup coordinates.
  3162. if (addr->getType()->isVectorTy()) {
  3163. unsigned vectorNumElements = addr->getType()->getVectorNumElements();
  3164. DXASSERT(vectorNumElements <= 3, "up to 3 elements in atomic op");
  3165. _Analysis_assume_(vectorNumElements <= 3);
  3166. for (unsigned i = 0; i < vectorNumElements; i++) {
  3167. Value *Elt = Builder.CreateExtractElement(addr, i);
  3168. args[DXIL::OperandIndex::kAtomicCmpExchangeCoord0OpIdx + i] = Elt;
  3169. }
  3170. } else
  3171. args[DXIL::OperandIndex::kAtomicCmpExchangeCoord0OpIdx] = addr;
  3172. // Set offset for structured buffer.
  3173. if (helper.offset)
  3174. args[DXIL::OperandIndex::kAtomicCmpExchangeCoord1OpIdx] = helper.offset;
  3175. Value *origVal = Builder.CreateCall(dxilAtomic, args);
  3176. if (helper.originalValue) {
  3177. Builder.CreateStore(origVal, helper.originalValue);
  3178. }
  3179. }
  3180. Value *TranslateMopAtomicCmpXChg(CallInst *CI, IntrinsicOp IOP,
  3181. OP::OpCode opcode,
  3182. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3183. hlsl::OP *hlslOP = &helper.hlslOP;
  3184. Value *handle = CI->getArgOperand(HLOperandIndex::kHandleOpIdx);
  3185. IRBuilder<> Builder(CI);
  3186. AtomicHelper atomicHelper(CI, OP::OpCode::AtomicCompareExchange, handle);
  3187. TranslateAtomicCmpXChg(atomicHelper, Builder, hlslOP);
  3188. return nullptr;
  3189. }
  3190. void TranslateSharedMemAtomicBinOp(CallInst *CI, IntrinsicOp IOP, Value *addr) {
  3191. AtomicRMWInst::BinOp Op;
  3192. switch (IOP) {
  3193. case IntrinsicOp::IOP_InterlockedAdd:
  3194. Op = AtomicRMWInst::BinOp::Add;
  3195. break;
  3196. case IntrinsicOp::IOP_InterlockedAnd:
  3197. Op = AtomicRMWInst::BinOp::And;
  3198. break;
  3199. case IntrinsicOp::IOP_InterlockedExchange:
  3200. Op = AtomicRMWInst::BinOp::Xchg;
  3201. break;
  3202. case IntrinsicOp::IOP_InterlockedMax:
  3203. Op = AtomicRMWInst::BinOp::Max;
  3204. break;
  3205. case IntrinsicOp::IOP_InterlockedUMax:
  3206. Op = AtomicRMWInst::BinOp::UMax;
  3207. break;
  3208. case IntrinsicOp::IOP_InterlockedMin:
  3209. Op = AtomicRMWInst::BinOp::Min;
  3210. break;
  3211. case IntrinsicOp::IOP_InterlockedUMin:
  3212. Op = AtomicRMWInst::BinOp::UMin;
  3213. break;
  3214. case IntrinsicOp::IOP_InterlockedOr:
  3215. Op = AtomicRMWInst::BinOp::Or;
  3216. break;
  3217. case IntrinsicOp::IOP_InterlockedXor:
  3218. default:
  3219. DXASSERT(IOP == IntrinsicOp::IOP_InterlockedXor, "Invalid Intrinsic");
  3220. Op = AtomicRMWInst::BinOp::Xor;
  3221. break;
  3222. }
  3223. Value *val = CI->getArgOperand(HLOperandIndex::kInterlockedValueOpIndex);
  3224. IRBuilder<> Builder(CI);
  3225. Value *Result = Builder.CreateAtomicRMW(
  3226. Op, addr, val, AtomicOrdering::SequentiallyConsistent);
  3227. if (CI->getNumArgOperands() >
  3228. HLOperandIndex::kInterlockedOriginalValueOpIndex)
  3229. Builder.CreateStore(
  3230. Result,
  3231. CI->getArgOperand(HLOperandIndex::kInterlockedOriginalValueOpIndex));
  3232. }
  3233. Value *TranslateIopAtomicBinaryOperation(CallInst *CI, IntrinsicOp IOP,
  3234. DXIL::OpCode opcode,
  3235. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3236. Value *addr = CI->getArgOperand(HLOperandIndex::kInterlockedDestOpIndex);
  3237. // Get the original addr from cast.
  3238. if (CastInst *castInst = dyn_cast<CastInst>(addr))
  3239. addr = castInst->getOperand(0);
  3240. else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(addr)) {
  3241. if (CE->getOpcode() == Instruction::AddrSpaceCast) {
  3242. addr = CE->getOperand(0);
  3243. }
  3244. }
  3245. unsigned addressSpace = addr->getType()->getPointerAddressSpace();
  3246. if (addressSpace == DXIL::kTGSMAddrSpace)
  3247. TranslateSharedMemAtomicBinOp(CI, IOP, addr);
  3248. else {
  3249. // buffer atomic translated in TranslateSubscript.
  3250. // Do nothing here.
  3251. // Mark not translated.
  3252. Translated = false;
  3253. }
  3254. return nullptr;
  3255. }
  3256. void TranslateSharedMemAtomicCmpXChg(CallInst *CI, Value *addr) {
  3257. Value *val = CI->getArgOperand(HLOperandIndex::kInterlockedCmpValueOpIndex);
  3258. Value *cmpVal =
  3259. CI->getArgOperand(HLOperandIndex::kInterlockedCmpCompareValueOpIndex);
  3260. IRBuilder<> Builder(CI);
  3261. Value *Result = Builder.CreateAtomicCmpXchg(
  3262. addr, cmpVal, val, AtomicOrdering::SequentiallyConsistent,
  3263. AtomicOrdering::SequentiallyConsistent);
  3264. if (CI->getNumArgOperands() >
  3265. HLOperandIndex::kInterlockedCmpOriginalValueOpIndex) {
  3266. Value *originVal = Builder.CreateExtractValue(Result, 0);
  3267. Builder.CreateStore(
  3268. originVal,
  3269. CI->getArgOperand(HLOperandIndex::kInterlockedCmpOriginalValueOpIndex));
  3270. }
  3271. }
  3272. Value *TranslateIopAtomicCmpXChg(CallInst *CI, IntrinsicOp IOP,
  3273. DXIL::OpCode opcode,
  3274. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3275. Value *addr = CI->getArgOperand(HLOperandIndex::kInterlockedDestOpIndex);
  3276. // Get the original addr from cast.
  3277. if (CastInst *castInst = dyn_cast<CastInst>(addr))
  3278. addr = castInst->getOperand(0);
  3279. unsigned addressSpace = addr->getType()->getPointerAddressSpace();
  3280. if (addressSpace == DXIL::kTGSMAddrSpace)
  3281. TranslateSharedMemAtomicCmpXChg(CI, addr);
  3282. else {
  3283. // buffer atomic translated in TranslateSubscript.
  3284. // Do nothing here.
  3285. // Mark not translated.
  3286. Translated = false;
  3287. }
  3288. return nullptr;
  3289. }
  3290. }
  3291. // Process Tess Factor.
  3292. namespace {
  3293. // Clamp to [0.0f..1.0f], NaN->0.0f.
  3294. Value *CleanupTessFactorScale(Value *input, hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3295. float fMin = 0;
  3296. float fMax = 1;
  3297. Type *f32Ty = input->getType()->getScalarType();
  3298. Value *minFactor = ConstantFP::get(f32Ty, fMin);
  3299. Value *maxFactor = ConstantFP::get(f32Ty, fMax);
  3300. Type *Ty = input->getType();
  3301. if (Ty->isVectorTy())
  3302. minFactor = SplatToVector(minFactor, input->getType(), Builder);
  3303. Value *temp = TrivialDxilBinaryOperation(DXIL::OpCode::FMax, input, minFactor, hlslOP, Builder);
  3304. if (Ty->isVectorTy())
  3305. maxFactor = SplatToVector(maxFactor, input->getType(), Builder);
  3306. return TrivialDxilBinaryOperation(DXIL::OpCode::FMin, temp, maxFactor, hlslOP, Builder);
  3307. }
  3308. // Clamp to [1.0f..Inf], NaN->1.0f.
  3309. Value *CleanupTessFactor(Value *input, hlsl::OP *hlslOP, IRBuilder<> &Builder)
  3310. {
  3311. float fMin = 1.0;
  3312. Type *f32Ty = input->getType()->getScalarType();
  3313. Value *minFactor = ConstantFP::get(f32Ty, fMin);
  3314. minFactor = SplatToVector(minFactor, input->getType(), Builder);
  3315. return TrivialDxilBinaryOperation(DXIL::OpCode::FMax, input, minFactor, hlslOP, Builder);
  3316. }
  3317. // Do partitioning-specific clamping.
  3318. Value *ClampTessFactor(Value *input, DXIL::TessellatorPartitioning partitionMode,
  3319. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3320. const unsigned kTESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR = 64;
  3321. const unsigned kTESSELLATOR_MAX_ODD_TESSELLATION_FACTOR = 63;
  3322. const unsigned kTESSELLATOR_MIN_EVEN_TESSELLATION_FACTOR = 2;
  3323. const unsigned kTESSELLATOR_MIN_ODD_TESSELLATION_FACTOR = 1;
  3324. const unsigned kTESSELLATOR_MAX_TESSELLATION_FACTOR = 64;
  3325. float fMin;
  3326. float fMax;
  3327. switch (partitionMode) {
  3328. case DXIL::TessellatorPartitioning::Integer:
  3329. fMin = kTESSELLATOR_MIN_ODD_TESSELLATION_FACTOR;
  3330. fMax = kTESSELLATOR_MAX_TESSELLATION_FACTOR;
  3331. break;
  3332. case DXIL::TessellatorPartitioning::Pow2:
  3333. fMin = kTESSELLATOR_MIN_ODD_TESSELLATION_FACTOR;
  3334. fMax = kTESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR;
  3335. break;
  3336. case DXIL::TessellatorPartitioning::FractionalOdd:
  3337. fMin = kTESSELLATOR_MIN_ODD_TESSELLATION_FACTOR;
  3338. fMax = kTESSELLATOR_MAX_ODD_TESSELLATION_FACTOR;
  3339. break;
  3340. case DXIL::TessellatorPartitioning::FractionalEven:
  3341. default:
  3342. DXASSERT(partitionMode == DXIL::TessellatorPartitioning::FractionalEven,
  3343. "invalid partition mode");
  3344. fMin = kTESSELLATOR_MIN_EVEN_TESSELLATION_FACTOR;
  3345. fMax = kTESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR;
  3346. break;
  3347. }
  3348. Type *f32Ty = input->getType()->getScalarType();
  3349. Value *minFactor = ConstantFP::get(f32Ty, fMin);
  3350. Value *maxFactor = ConstantFP::get(f32Ty, fMax);
  3351. Type *Ty = input->getType();
  3352. if (Ty->isVectorTy())
  3353. minFactor = SplatToVector(minFactor, input->getType(), Builder);
  3354. Value *temp = TrivialDxilBinaryOperation(DXIL::OpCode::FMax, input, minFactor, hlslOP, Builder);
  3355. if (Ty->isVectorTy())
  3356. maxFactor = SplatToVector(maxFactor, input->getType(), Builder);
  3357. return TrivialDxilBinaryOperation(DXIL::OpCode::FMin, temp, maxFactor, hlslOP, Builder);
  3358. }
  3359. // round up for integer/pow2 partitioning
  3360. // note that this code assumes the inputs should be in the range [1, inf),
  3361. // which should be enforced by the clamp above.
  3362. Value *RoundUpTessFactor(Value *input, DXIL::TessellatorPartitioning partitionMode,
  3363. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3364. switch (partitionMode) {
  3365. case DXIL::TessellatorPartitioning::Integer:
  3366. return TrivialDxilUnaryOperation(DXIL::OpCode::Round_pi, input, hlslOP, Builder);
  3367. case DXIL::TessellatorPartitioning::Pow2: {
  3368. const unsigned kExponentMask = 0x7f800000;
  3369. const unsigned kExponentLSB = 0x00800000;
  3370. const unsigned kMantissaMask = 0x007fffff;
  3371. Type *Ty = input->getType();
  3372. // (val = (asuint(val) & mantissamask) ?
  3373. // (asuint(val) & exponentmask) + exponentbump :
  3374. // asuint(val) & exponentmask;
  3375. Type *uintTy = Type::getInt32Ty(Ty->getContext());
  3376. if (Ty->isVectorTy())
  3377. uintTy = VectorType::get(uintTy, Ty->getVectorNumElements());
  3378. Value *uintVal = Builder.CreateCast(Instruction::CastOps::FPToUI, input, uintTy);
  3379. Value *mantMask = ConstantInt::get(uintTy->getScalarType(), kMantissaMask);
  3380. mantMask = SplatToVector(mantMask, uintTy, Builder);
  3381. Value *manVal = Builder.CreateAnd(uintVal, mantMask);
  3382. Value *expMask = ConstantInt::get(uintTy->getScalarType(), kExponentMask);
  3383. expMask = SplatToVector(expMask, uintTy, Builder);
  3384. Value *expVal = Builder.CreateAnd(uintVal, expMask);
  3385. Value *expLSB = ConstantInt::get(uintTy->getScalarType(), kExponentLSB);
  3386. expLSB = SplatToVector(expLSB, uintTy, Builder);
  3387. Value *newExpVal = Builder.CreateAdd(expVal, expLSB);
  3388. Value *manValNotZero = Builder.CreateICmpEQ(manVal, ConstantAggregateZero::get(uintTy));
  3389. Value *factors = Builder.CreateSelect(manValNotZero, newExpVal, expVal);
  3390. return Builder.CreateUIToFP(factors, Ty);
  3391. } break;
  3392. case DXIL::TessellatorPartitioning::FractionalEven:
  3393. case DXIL::TessellatorPartitioning::FractionalOdd:
  3394. return input;
  3395. default:
  3396. DXASSERT(0, "invalid partition mode");
  3397. return nullptr;
  3398. }
  3399. }
  3400. Value *TranslateProcessIsolineTessFactors(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  3401. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3402. hlsl::OP *hlslOP = &helper.hlslOP;
  3403. // Get partition mode
  3404. DXASSERT(helper.functionProps, "");
  3405. DXASSERT(helper.functionProps->shaderKind == ShaderModel::Kind::Hull, "must be hull shader");
  3406. DXIL::TessellatorPartitioning partition = helper.functionProps->ShaderProps.HS.partition;
  3407. IRBuilder<> Builder(CI);
  3408. Value *rawDetailFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRawDetailFactor);
  3409. rawDetailFactor = Builder.CreateExtractElement(rawDetailFactor, (uint64_t)0);
  3410. Value *rawDensityFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRawDensityFactor);
  3411. rawDensityFactor = Builder.CreateExtractElement(rawDensityFactor, (uint64_t)0);
  3412. Value *init = UndefValue::get(VectorType::get(helper.f32Ty, 2));
  3413. init = Builder.CreateInsertElement(init, rawDetailFactor, (uint64_t)0);
  3414. init = Builder.CreateInsertElement(init, rawDetailFactor, (uint64_t)1);
  3415. Value *clamped = ClampTessFactor(init, partition, hlslOP, Builder);
  3416. Value *rounded = RoundUpTessFactor(clamped, partition, hlslOP, Builder);
  3417. Value *roundedDetailFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRoundedDetailFactor);
  3418. Value *temp = UndefValue::get(VectorType::get(helper.f32Ty, 1));
  3419. Value *roundedX = Builder.CreateExtractElement(rounded, (uint64_t)0);
  3420. temp = Builder.CreateInsertElement(temp, roundedX, (uint64_t)0);
  3421. Builder.CreateStore(temp, roundedDetailFactor);
  3422. Value *roundedDensityFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRoundedDensityFactor);
  3423. Value *roundedY = Builder.CreateExtractElement(rounded, 1);
  3424. temp = Builder.CreateInsertElement(temp, roundedY, (uint64_t)0);
  3425. Builder.CreateStore(temp, roundedDensityFactor);
  3426. return nullptr;
  3427. }
  3428. // 3 inputs, 1 result
  3429. Value *ApplyTriTessFactorOp(Value *input, DXIL::OpCode opcode, hlsl::OP *hlslOP,
  3430. IRBuilder<> &Builder) {
  3431. Value *input0 = Builder.CreateExtractElement(input, (uint64_t)0);
  3432. Value *input1 = Builder.CreateExtractElement(input, 1);
  3433. Value *input2 = Builder.CreateExtractElement(input, 2);
  3434. if (opcode == DXIL::OpCode::FMax || opcode == DXIL::OpCode::FMin) {
  3435. Value *temp =
  3436. TrivialDxilBinaryOperation(opcode, input0, input1, hlslOP, Builder);
  3437. Value *combined =
  3438. TrivialDxilBinaryOperation(opcode, temp, input2, hlslOP, Builder);
  3439. return combined;
  3440. } else {
  3441. // Avg.
  3442. Value *temp = Builder.CreateFAdd(input0, input1);
  3443. Value *combined = Builder.CreateFAdd(temp, input2);
  3444. Value *rcp = ConstantFP::get(input0->getType(), 1.0 / 3.0);
  3445. combined = Builder.CreateFMul(combined, rcp);
  3446. return combined;
  3447. }
  3448. }
  3449. // 4 inputs, 1 result
  3450. Value *ApplyQuadTessFactorOp(Value *input, DXIL::OpCode opcode,
  3451. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3452. Value *input0 = Builder.CreateExtractElement(input, (uint64_t)0);
  3453. Value *input1 = Builder.CreateExtractElement(input, 1);
  3454. Value *input2 = Builder.CreateExtractElement(input, 2);
  3455. Value *input3 = Builder.CreateExtractElement(input, 3);
  3456. if (opcode == DXIL::OpCode::FMax || opcode == DXIL::OpCode::FMin) {
  3457. Value *temp0 =
  3458. TrivialDxilBinaryOperation(opcode, input0, input1, hlslOP, Builder);
  3459. Value *temp1 =
  3460. TrivialDxilBinaryOperation(opcode, input2, input3, hlslOP, Builder);
  3461. Value *combined =
  3462. TrivialDxilBinaryOperation(opcode, temp0, temp1, hlslOP, Builder);
  3463. return combined;
  3464. } else {
  3465. // Avg.
  3466. Value *temp0 = Builder.CreateFAdd(input0, input1);
  3467. Value *temp1 = Builder.CreateFAdd(input2, input3);
  3468. Value *combined = Builder.CreateFAdd(temp0, temp1);
  3469. Value *rcp = ConstantFP::get(input0->getType(), 0.25);
  3470. combined = Builder.CreateFMul(combined, rcp);
  3471. return combined;
  3472. }
  3473. }
  3474. // 4 inputs, 2 result
  3475. Value *Apply2DQuadTessFactorOp(Value *input, DXIL::OpCode opcode,
  3476. hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3477. Value *input0 = Builder.CreateExtractElement(input, (uint64_t)0);
  3478. Value *input1 = Builder.CreateExtractElement(input, 1);
  3479. Value *input2 = Builder.CreateExtractElement(input, 2);
  3480. Value *input3 = Builder.CreateExtractElement(input, 3);
  3481. if (opcode == DXIL::OpCode::FMax || opcode == DXIL::OpCode::FMin) {
  3482. Value *temp0 =
  3483. TrivialDxilBinaryOperation(opcode, input0, input1, hlslOP, Builder);
  3484. Value *temp1 =
  3485. TrivialDxilBinaryOperation(opcode, input2, input3, hlslOP, Builder);
  3486. Value *combined = UndefValue::get(VectorType::get(input0->getType(), 2));
  3487. combined = Builder.CreateInsertElement(combined, temp0, (uint64_t)0);
  3488. combined = Builder.CreateInsertElement(combined, temp1, 1);
  3489. return combined;
  3490. } else {
  3491. // Avg.
  3492. Value *temp0 = Builder.CreateFAdd(input0, input1);
  3493. Value *temp1 = Builder.CreateFAdd(input2, input3);
  3494. Value *combined = UndefValue::get(VectorType::get(input0->getType(), 2));
  3495. combined = Builder.CreateInsertElement(combined, temp0, (uint64_t)0);
  3496. combined = Builder.CreateInsertElement(combined, temp1, 1);
  3497. Constant *rcp = ConstantFP::get(input0->getType(), 0.5);
  3498. rcp = ConstantVector::getSplat(2, rcp);
  3499. combined = Builder.CreateFMul(combined, rcp);
  3500. return combined;
  3501. }
  3502. }
  3503. Value *ResolveSmallValue(Value **pClampedResult, Value *rounded, Value *averageUnscaled,
  3504. float cutoffVal, DXIL::TessellatorPartitioning partitionMode, hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3505. Value *clampedResult = *pClampedResult;
  3506. Value *clampedVal = clampedResult;
  3507. Value *roundedVal = rounded;
  3508. // Do partitioning-specific clamping.
  3509. Value *clampedAvg = ClampTessFactor(averageUnscaled, partitionMode, hlslOP, Builder);
  3510. Constant *cutoffVals = ConstantFP::get(Type::getFloatTy(rounded->getContext()), cutoffVal);
  3511. if (clampedAvg->getType()->isVectorTy())
  3512. cutoffVals = ConstantVector::getSplat(clampedAvg->getType()->getVectorNumElements(), cutoffVals);
  3513. // Limit the value.
  3514. clampedAvg = TrivialDxilBinaryOperation(DXIL::OpCode::FMin, clampedAvg, cutoffVals, hlslOP, Builder);
  3515. // Round up for integer/pow2 partitioning.
  3516. Value *roundedAvg = RoundUpTessFactor(clampedAvg, partitionMode, hlslOP, Builder);
  3517. if (rounded->getType() != cutoffVals->getType())
  3518. cutoffVals = ConstantVector::getSplat(rounded->getType()->getVectorNumElements(), cutoffVals);
  3519. // If the scaled value is less than three, then take the unscaled average.
  3520. Value *lt = Builder.CreateFCmpOLT(rounded, cutoffVals);
  3521. if (clampedAvg->getType() != clampedVal->getType())
  3522. clampedAvg = SplatToVector(clampedAvg, clampedVal->getType(), Builder);
  3523. *pClampedResult = Builder.CreateSelect(lt, clampedAvg, clampedVal);
  3524. if (roundedAvg->getType() != roundedVal->getType())
  3525. roundedAvg = SplatToVector(roundedAvg, roundedVal->getType(), Builder);
  3526. Value *result = Builder.CreateSelect(lt, roundedAvg, roundedVal);
  3527. return result;
  3528. }
  3529. void ResolveQuadAxes( Value **pFinalResult, Value **pClampedResult,
  3530. float cutoffVal, DXIL::TessellatorPartitioning partitionMode, hlsl::OP *hlslOP, IRBuilder<> &Builder) {
  3531. Value *finalResult = *pFinalResult;
  3532. Value *clampedResult = *pClampedResult;
  3533. Value *clampR = clampedResult;
  3534. Value *finalR = finalResult;
  3535. Type *f32Ty = Type::getFloatTy(finalR->getContext());
  3536. Constant *cutoffVals = ConstantFP::get(f32Ty, cutoffVal);
  3537. Value *minValsX = cutoffVals;
  3538. Value *minValsY = RoundUpTessFactor(cutoffVals, partitionMode, hlslOP, Builder);
  3539. Value *clampRX = Builder.CreateExtractElement(clampR, (uint64_t)0);
  3540. Value *clampRY = Builder.CreateExtractElement(clampR, 1);
  3541. Value *maxValsX = TrivialDxilBinaryOperation(DXIL::OpCode::FMax, clampRX, clampRY, hlslOP, Builder);
  3542. Value *finalRX = Builder.CreateExtractElement(finalR, (uint64_t)0);
  3543. Value *finalRY = Builder.CreateExtractElement(finalR, 1);
  3544. Value *maxValsY = TrivialDxilBinaryOperation(DXIL::OpCode::FMax, finalRX, finalRY, hlslOP, Builder);
  3545. // Don't go over our threshold ("final" one is rounded).
  3546. Value * optionX = TrivialDxilBinaryOperation(DXIL::OpCode::FMin, maxValsX, minValsX, hlslOP, Builder);
  3547. Value * optionY = TrivialDxilBinaryOperation(DXIL::OpCode::FMin, maxValsY, minValsY, hlslOP, Builder);
  3548. Value *clampL = SplatToVector(optionX, clampR->getType(), Builder);
  3549. Value *finalL = SplatToVector(optionY, finalR->getType(), Builder);
  3550. cutoffVals = ConstantVector::getSplat(2, cutoffVals);
  3551. Value *lt = Builder.CreateFCmpOLT(clampedResult, cutoffVals);
  3552. *pClampedResult = Builder.CreateSelect(lt, clampL, clampR);
  3553. *pFinalResult = Builder.CreateSelect(lt, finalL, finalR);
  3554. }
  3555. Value *TranslateProcessTessFactors(CallInst *CI, IntrinsicOp IOP, OP::OpCode opcode,
  3556. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3557. hlsl::OP *hlslOP = &helper.hlslOP;
  3558. // Get partition mode
  3559. DXASSERT(helper.functionProps, "");
  3560. DXASSERT(helper.functionProps->shaderKind == ShaderModel::Kind::Hull, "must be hull shader");
  3561. DXIL::TessellatorPartitioning partition = helper.functionProps->ShaderProps.HS.partition;
  3562. IRBuilder<> Builder(CI);
  3563. DXIL::OpCode tessFactorOp = DXIL::OpCode::NumOpCodes;
  3564. switch (IOP) {
  3565. case IntrinsicOp::IOP_Process2DQuadTessFactorsMax:
  3566. case IntrinsicOp::IOP_ProcessQuadTessFactorsMax:
  3567. case IntrinsicOp::IOP_ProcessTriTessFactorsMax:
  3568. tessFactorOp = DXIL::OpCode::FMax;
  3569. break;
  3570. case IntrinsicOp::IOP_Process2DQuadTessFactorsMin:
  3571. case IntrinsicOp::IOP_ProcessQuadTessFactorsMin:
  3572. case IntrinsicOp::IOP_ProcessTriTessFactorsMin:
  3573. tessFactorOp = DXIL::OpCode::FMin;
  3574. break;
  3575. default:
  3576. // Default is Avg.
  3577. break;
  3578. }
  3579. Value *rawEdgeFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRawEdgeFactor);
  3580. Value *insideScale = CI->getArgOperand(HLOperandIndex::kProcessTessFactorInsideScale);
  3581. // Clamp to [0.0f..1.0f], NaN->0.0f.
  3582. Value *scales = CleanupTessFactorScale(insideScale, hlslOP, Builder);
  3583. // Do partitioning-specific clamping.
  3584. Value *clamped = ClampTessFactor(rawEdgeFactor, partition, hlslOP, Builder);
  3585. // Round up for integer/pow2 partitioning.
  3586. Value *rounded = RoundUpTessFactor(clamped, partition, hlslOP, Builder);
  3587. // Store the output.
  3588. Value *roundedEdgeFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRoundedEdgeFactor);
  3589. Builder.CreateStore(rounded, roundedEdgeFactor);
  3590. // Clamp to [1.0f..Inf], NaN->1.0f.
  3591. bool isQuad = false;
  3592. Value *clean = CleanupTessFactor(rawEdgeFactor, hlslOP, Builder);
  3593. Value *factors = nullptr;
  3594. switch (IOP) {
  3595. case IntrinsicOp::IOP_Process2DQuadTessFactorsAvg:
  3596. case IntrinsicOp::IOP_Process2DQuadTessFactorsMax:
  3597. case IntrinsicOp::IOP_Process2DQuadTessFactorsMin:
  3598. factors = Apply2DQuadTessFactorOp(clean, tessFactorOp, hlslOP, Builder);
  3599. break;
  3600. case IntrinsicOp::IOP_ProcessQuadTessFactorsAvg:
  3601. case IntrinsicOp::IOP_ProcessQuadTessFactorsMax:
  3602. case IntrinsicOp::IOP_ProcessQuadTessFactorsMin:
  3603. factors = ApplyQuadTessFactorOp(clean, tessFactorOp, hlslOP, Builder);
  3604. isQuad = true;
  3605. break;
  3606. case IntrinsicOp::IOP_ProcessTriTessFactorsAvg:
  3607. case IntrinsicOp::IOP_ProcessTriTessFactorsMax:
  3608. case IntrinsicOp::IOP_ProcessTriTessFactorsMin:
  3609. factors = ApplyTriTessFactorOp(clean, tessFactorOp, hlslOP, Builder);
  3610. break;
  3611. default:
  3612. DXASSERT(0, "invalid opcode for ProcessTessFactor");
  3613. break;
  3614. }
  3615. Value *scaledI = nullptr;
  3616. if (scales->getType() == factors->getType())
  3617. scaledI = Builder.CreateFMul(factors, scales);
  3618. else {
  3619. Value *vecFactors = SplatToVector(factors, scales->getType(), Builder);
  3620. scaledI = Builder.CreateFMul(vecFactors, scales);
  3621. }
  3622. // Do partitioning-specific clamping.
  3623. Value *clampedI = ClampTessFactor(scaledI, partition, hlslOP, Builder);
  3624. // Round up for integer/pow2 partitioning.
  3625. Value *roundedI = RoundUpTessFactor(clampedI, partition, hlslOP, Builder);
  3626. Value *finalI = roundedI;
  3627. if (partition == DXIL::TessellatorPartitioning::FractionalOdd) {
  3628. // If not max, set to AVG.
  3629. if (tessFactorOp != DXIL::OpCode::FMax)
  3630. tessFactorOp = DXIL::OpCode::NumOpCodes;
  3631. bool b2D = false;
  3632. Value *avgFactorsI = nullptr;
  3633. switch (IOP) {
  3634. case IntrinsicOp::IOP_Process2DQuadTessFactorsAvg:
  3635. case IntrinsicOp::IOP_Process2DQuadTessFactorsMax:
  3636. case IntrinsicOp::IOP_Process2DQuadTessFactorsMin:
  3637. avgFactorsI = Apply2DQuadTessFactorOp(clean, tessFactorOp, hlslOP, Builder);
  3638. b2D = true;
  3639. break;
  3640. case IntrinsicOp::IOP_ProcessQuadTessFactorsAvg:
  3641. case IntrinsicOp::IOP_ProcessQuadTessFactorsMax:
  3642. case IntrinsicOp::IOP_ProcessQuadTessFactorsMin:
  3643. avgFactorsI = ApplyQuadTessFactorOp(clean, tessFactorOp, hlslOP, Builder);
  3644. break;
  3645. case IntrinsicOp::IOP_ProcessTriTessFactorsAvg:
  3646. case IntrinsicOp::IOP_ProcessTriTessFactorsMax:
  3647. case IntrinsicOp::IOP_ProcessTriTessFactorsMin:
  3648. avgFactorsI = ApplyTriTessFactorOp(clean, tessFactorOp, hlslOP, Builder);
  3649. break;
  3650. default:
  3651. DXASSERT(0, "invalid opcode for ProcessTessFactor");
  3652. break;
  3653. }
  3654. finalI =
  3655. ResolveSmallValue(/*inout*/&clampedI, roundedI, avgFactorsI, /*cufoff*/ 3.0,
  3656. partition, hlslOP, Builder);
  3657. if (b2D)
  3658. ResolveQuadAxes(/*inout*/&finalI, /*inout*/&clampedI, /*cutoff*/3.0, partition, hlslOP, Builder);
  3659. }
  3660. Value *unroundedInsideFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorUnRoundedInsideFactor);
  3661. Type *outFactorTy = unroundedInsideFactor->getType()->getPointerElementType();
  3662. if (outFactorTy != clampedI->getType()) {
  3663. DXASSERT(isQuad, "quad only write one channel of out factor");
  3664. clampedI = Builder.CreateExtractElement(clampedI, (uint64_t)0);
  3665. // Splat clampedI to float2.
  3666. clampedI = SplatToVector(clampedI, outFactorTy, Builder);
  3667. }
  3668. Builder.CreateStore(clampedI, unroundedInsideFactor);
  3669. Value *roundedInsideFactor = CI->getArgOperand(HLOperandIndex::kProcessTessFactorRoundedInsideFactor);
  3670. if (outFactorTy != finalI->getType()) {
  3671. DXASSERT(isQuad, "quad only write one channel of out factor");
  3672. finalI = Builder.CreateExtractElement(finalI, (uint64_t)0);
  3673. // Splat finalI to float2.
  3674. finalI = SplatToVector(finalI, outFactorTy, Builder);
  3675. }
  3676. Builder.CreateStore(finalI, roundedInsideFactor);
  3677. return nullptr;
  3678. }
  3679. }
  3680. // Lower table.
  3681. namespace {
  3682. Value *EmptyLower(CallInst *CI, IntrinsicOp IOP, DXIL::OpCode opcode,
  3683. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3684. DXASSERT(0, "unsupported intrinsic");
  3685. return nullptr;
  3686. }
  3687. Value *StreamOutputLower(CallInst *CI, IntrinsicOp IOP, DXIL::OpCode opcode,
  3688. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3689. // Translated in DxilGenerationPass::GenerateStreamOutputOperation.
  3690. // Do nothing here.
  3691. // Mark not translated.
  3692. Translated = false;
  3693. return nullptr;
  3694. }
  3695. IntrinsicLower gLowerTable[static_cast<unsigned>(IntrinsicOp::Num_Intrinsics)] = {
  3696. {IntrinsicOp::IOP_AddUint64, TranslateAddUint64, DXIL::OpCode::UAddc},
  3697. {IntrinsicOp::IOP_AllMemoryBarrier, TrivialBarrier, DXIL::OpCode::Barrier},
  3698. {IntrinsicOp::IOP_AllMemoryBarrierWithGroupSync, TrivialBarrier, DXIL::OpCode::Barrier},
  3699. {IntrinsicOp::IOP_CheckAccessFullyMapped, TrivialUnaryOperation, DXIL::OpCode::CheckAccessFullyMapped},
  3700. {IntrinsicOp::IOP_D3DCOLORtoUBYTE4, TranslateD3DColorToUByte4, DXIL::OpCode::NumOpCodes},
  3701. {IntrinsicOp::IOP_DeviceMemoryBarrier, TrivialBarrier, DXIL::OpCode::Barrier},
  3702. {IntrinsicOp::IOP_DeviceMemoryBarrierWithGroupSync, TrivialBarrier, DXIL::OpCode::Barrier},
  3703. {IntrinsicOp::IOP_EvaluateAttributeAtSample, TranslateEvalSample, DXIL::OpCode::NumOpCodes},
  3704. {IntrinsicOp::IOP_EvaluateAttributeCentroid, TranslateEvalCentroid, DXIL::OpCode::EvalCentroid},
  3705. {IntrinsicOp::IOP_EvaluateAttributeSnapped, TranslateEvalSnapped, DXIL::OpCode::NumOpCodes},
  3706. {IntrinsicOp::IOP_GetAttributeAtVertex, TranslateGetAttributeAtVertex, DXIL::OpCode::AttributeAtVertex},
  3707. {IntrinsicOp::IOP_GetRenderTargetSampleCount, TrivialNoArgOperation, DXIL::OpCode::RenderTargetGetSampleCount},
  3708. {IntrinsicOp::IOP_GetRenderTargetSamplePosition, TranslateGetRTSamplePos, DXIL::OpCode::NumOpCodes},
  3709. {IntrinsicOp::IOP_GroupMemoryBarrier, TrivialBarrier, DXIL::OpCode::Barrier},
  3710. {IntrinsicOp::IOP_GroupMemoryBarrierWithGroupSync, TrivialBarrier, DXIL::OpCode::Barrier},
  3711. {IntrinsicOp::IOP_InterlockedAdd, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3712. {IntrinsicOp::IOP_InterlockedAnd, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3713. {IntrinsicOp::IOP_InterlockedCompareExchange, TranslateIopAtomicCmpXChg, DXIL::OpCode::NumOpCodes},
  3714. {IntrinsicOp::IOP_InterlockedCompareStore, TranslateIopAtomicCmpXChg, DXIL::OpCode::NumOpCodes},
  3715. {IntrinsicOp::IOP_InterlockedExchange, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3716. {IntrinsicOp::IOP_InterlockedMax, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3717. {IntrinsicOp::IOP_InterlockedMin, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3718. {IntrinsicOp::IOP_InterlockedOr, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3719. {IntrinsicOp::IOP_InterlockedXor, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3720. {IntrinsicOp::IOP_NonUniformResourceIndex, TranslateNonUniformResourceIndex, DXIL::OpCode::NumOpCodes},
  3721. {IntrinsicOp::IOP_Process2DQuadTessFactorsAvg, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3722. {IntrinsicOp::IOP_Process2DQuadTessFactorsMax, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3723. {IntrinsicOp::IOP_Process2DQuadTessFactorsMin, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3724. {IntrinsicOp::IOP_ProcessIsolineTessFactors, TranslateProcessIsolineTessFactors, DXIL::OpCode::NumOpCodes},
  3725. {IntrinsicOp::IOP_ProcessQuadTessFactorsAvg, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3726. {IntrinsicOp::IOP_ProcessQuadTessFactorsMax, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3727. {IntrinsicOp::IOP_ProcessQuadTessFactorsMin, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3728. {IntrinsicOp::IOP_ProcessTriTessFactorsAvg, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3729. {IntrinsicOp::IOP_ProcessTriTessFactorsMax, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3730. {IntrinsicOp::IOP_ProcessTriTessFactorsMin, TranslateProcessTessFactors, DXIL::OpCode::NumOpCodes},
  3731. {IntrinsicOp::IOP_QuadReadAcrossDiagonal, TranslateQuadReadAcross, DXIL::OpCode::QuadOp},
  3732. {IntrinsicOp::IOP_QuadReadAcrossX, TranslateQuadReadAcross, DXIL::OpCode::QuadOp},
  3733. {IntrinsicOp::IOP_QuadReadAcrossY, TranslateQuadReadAcross, DXIL::OpCode::QuadOp},
  3734. {IntrinsicOp::IOP_QuadReadLaneAt, TranslateQuadReadLaneAt, DXIL::OpCode::NumOpCodes},
  3735. {IntrinsicOp::IOP_WaveActiveAllEqual, TranslateWaveAllEqual, DXIL::OpCode::WaveActiveAllEqual},
  3736. {IntrinsicOp::IOP_WaveActiveAllTrue, TranslateWaveA2B, DXIL::OpCode::WaveAllTrue},
  3737. {IntrinsicOp::IOP_WaveActiveAnyTrue, TranslateWaveA2B, DXIL::OpCode::WaveAnyTrue},
  3738. {IntrinsicOp::IOP_WaveActiveBallot, TranslateWaveBallot, DXIL::OpCode::WaveActiveBallot},
  3739. {IntrinsicOp::IOP_WaveActiveBitAnd, TranslateWaveA2A, DXIL::OpCode::WaveActiveBit},
  3740. {IntrinsicOp::IOP_WaveActiveBitOr, TranslateWaveA2A, DXIL::OpCode::WaveActiveBit},
  3741. {IntrinsicOp::IOP_WaveActiveBitXor, TranslateWaveA2A, DXIL::OpCode::WaveActiveBit},
  3742. {IntrinsicOp::IOP_WaveActiveCountBits, TranslateWaveA2B, DXIL::OpCode::WaveAllBitCount},
  3743. {IntrinsicOp::IOP_WaveActiveMax, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp},
  3744. {IntrinsicOp::IOP_WaveActiveMin, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp},
  3745. {IntrinsicOp::IOP_WaveActiveProduct, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp},
  3746. {IntrinsicOp::IOP_WaveActiveSum, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp},
  3747. {IntrinsicOp::IOP_WaveGetLaneCount, TranslateWaveToVal, DXIL::OpCode::WaveGetLaneCount},
  3748. {IntrinsicOp::IOP_WaveGetLaneIndex, TranslateWaveToVal, DXIL::OpCode::WaveGetLaneIndex},
  3749. {IntrinsicOp::IOP_WaveIsFirstLane, TranslateWaveToVal, DXIL::OpCode::WaveIsFirstLane},
  3750. {IntrinsicOp::IOP_WavePrefixCountBits, TranslateWaveA2B, DXIL::OpCode::WavePrefixBitCount},
  3751. {IntrinsicOp::IOP_WavePrefixProduct, TranslateWaveA2A, DXIL::OpCode::WavePrefixOp},
  3752. {IntrinsicOp::IOP_WavePrefixSum, TranslateWaveA2A, DXIL::OpCode::WavePrefixOp},
  3753. {IntrinsicOp::IOP_WaveReadLaneAt, TranslateWaveReadLaneAt, DXIL::OpCode::WaveReadLaneAt},
  3754. {IntrinsicOp::IOP_WaveReadLaneFirst, TranslateWaveReadLaneFirst, DXIL::OpCode::WaveReadLaneFirst},
  3755. {IntrinsicOp::IOP_abort, EmptyLower, DXIL::OpCode::NumOpCodes},
  3756. {IntrinsicOp::IOP_abs, TransalteAbs, DXIL::OpCode::NumOpCodes},
  3757. {IntrinsicOp::IOP_acos, TrivialUnaryOperation, DXIL::OpCode::Acos},
  3758. {IntrinsicOp::IOP_all, TranslateAll, DXIL::OpCode::NumOpCodes},
  3759. {IntrinsicOp::IOP_any, TranslateAny, DXIL::OpCode::NumOpCodes},
  3760. {IntrinsicOp::IOP_asdouble, TranslateAsDouble, DXIL::OpCode::MakeDouble},
  3761. {IntrinsicOp::IOP_asfloat, TranslateBitcast, DXIL::OpCode::NumOpCodes},
  3762. {IntrinsicOp::IOP_asin, TrivialUnaryOperation, DXIL::OpCode::Asin},
  3763. {IntrinsicOp::IOP_asint, TranslateBitcast, DXIL::OpCode::NumOpCodes},
  3764. {IntrinsicOp::IOP_asuint, TranslateAsUint, DXIL::OpCode::SplitDouble},
  3765. {IntrinsicOp::IOP_atan, TrivialUnaryOperation, DXIL::OpCode::Atan},
  3766. {IntrinsicOp::IOP_atan2, TranslateAtan2, DXIL::OpCode::NumOpCodes},
  3767. {IntrinsicOp::IOP_ceil, TrivialUnaryOperation, DXIL::OpCode::Round_pi},
  3768. {IntrinsicOp::IOP_clamp, TranslateClamp, DXIL::OpCode::NumOpCodes},
  3769. {IntrinsicOp::IOP_clip, TranslateClip, DXIL::OpCode::NumOpCodes},
  3770. {IntrinsicOp::IOP_cos, TrivialUnaryOperation, DXIL::OpCode::Cos},
  3771. {IntrinsicOp::IOP_cosh, TrivialUnaryOperation, DXIL::OpCode::Hcos},
  3772. {IntrinsicOp::IOP_countbits, TrivialUnaryOperation, DXIL::OpCode::Countbits},
  3773. {IntrinsicOp::IOP_cross, TranslateCross, DXIL::OpCode::NumOpCodes},
  3774. {IntrinsicOp::IOP_ddx, TrivialUnaryOperation, DXIL::OpCode::DerivCoarseX},
  3775. {IntrinsicOp::IOP_ddx_coarse, TrivialUnaryOperation, DXIL::OpCode::DerivCoarseX},
  3776. {IntrinsicOp::IOP_ddx_fine, TrivialUnaryOperation, DXIL::OpCode::DerivFineX},
  3777. {IntrinsicOp::IOP_ddy, TrivialUnaryOperation, DXIL::OpCode::DerivCoarseY},
  3778. {IntrinsicOp::IOP_ddy_coarse, TrivialUnaryOperation, DXIL::OpCode::DerivCoarseY},
  3779. {IntrinsicOp::IOP_ddy_fine, TrivialUnaryOperation, DXIL::OpCode::DerivFineY},
  3780. {IntrinsicOp::IOP_degrees, TranslateDegrees, DXIL::OpCode::NumOpCodes},
  3781. {IntrinsicOp::IOP_determinant, EmptyLower, DXIL::OpCode::NumOpCodes},
  3782. {IntrinsicOp::IOP_distance, TranslateDistance, DXIL::OpCode::NumOpCodes},
  3783. {IntrinsicOp::IOP_dot, TranslateDot, DXIL::OpCode::NumOpCodes},
  3784. {IntrinsicOp::IOP_dst, TranslateDst, DXIL::OpCode::NumOpCodes},
  3785. {IntrinsicOp::IOP_exp, TranslateExp, DXIL::OpCode::NumOpCodes},
  3786. {IntrinsicOp::IOP_exp2, TrivialUnaryOperation, DXIL::OpCode::Exp},
  3787. {IntrinsicOp::IOP_f16tof32, TranslateF16ToF32, DXIL::OpCode::LegacyF16ToF32},
  3788. {IntrinsicOp::IOP_f32tof16, TranslateF32ToF16, DXIL::OpCode::LegacyF32ToF16},
  3789. {IntrinsicOp::IOP_faceforward, TranslateFaceforward, DXIL::OpCode::NumOpCodes},
  3790. {IntrinsicOp::IOP_firstbithigh, TranslateFirstbitHi, DXIL::OpCode::FirstbitSHi},
  3791. {IntrinsicOp::IOP_firstbitlow, TranslateFirstbitLo, DXIL::OpCode::FirstbitLo},
  3792. {IntrinsicOp::IOP_floor, TrivialUnaryOperation, DXIL::OpCode::Round_ni},
  3793. {IntrinsicOp::IOP_fma, TrivialTrinaryOperation, DXIL::OpCode::Fma},
  3794. {IntrinsicOp::IOP_fmod, TranslateFMod, DXIL::OpCode::NumOpCodes},
  3795. {IntrinsicOp::IOP_frac, TrivialUnaryOperation, DXIL::OpCode::Frc},
  3796. {IntrinsicOp::IOP_frexp, TranslateFrexp, DXIL::OpCode::NumOpCodes},
  3797. {IntrinsicOp::IOP_fwidth, TranslateFWidth, DXIL::OpCode::NumOpCodes},
  3798. {IntrinsicOp::IOP_isfinite, TrivialIsSpecialFloat, DXIL::OpCode::IsFinite},
  3799. {IntrinsicOp::IOP_isinf, TrivialIsSpecialFloat, DXIL::OpCode::IsInf},
  3800. {IntrinsicOp::IOP_isnan, TrivialIsSpecialFloat, DXIL::OpCode::IsNaN},
  3801. {IntrinsicOp::IOP_ldexp, TranslateLdExp, DXIL::OpCode::NumOpCodes},
  3802. {IntrinsicOp::IOP_length, TranslateLength, DXIL::OpCode::NumOpCodes},
  3803. {IntrinsicOp::IOP_lerp, TranslateLerp, DXIL::OpCode::NumOpCodes},
  3804. {IntrinsicOp::IOP_lit, TranslateLit, DXIL::OpCode::NumOpCodes},
  3805. {IntrinsicOp::IOP_log, TranslateLog, DXIL::OpCode::NumOpCodes},
  3806. {IntrinsicOp::IOP_log10, TranslateLog10, DXIL::OpCode::NumOpCodes},
  3807. {IntrinsicOp::IOP_log2, TrivialUnaryOperation, DXIL::OpCode::Log},
  3808. {IntrinsicOp::IOP_mad, TranslateFUITrinary, DXIL::OpCode::IMad},
  3809. {IntrinsicOp::IOP_max, TranslateFUIBinary, DXIL::OpCode::IMax},
  3810. {IntrinsicOp::IOP_min, TranslateFUIBinary, DXIL::OpCode::IMin},
  3811. {IntrinsicOp::IOP_modf, TranslateModF, DXIL::OpCode::NumOpCodes},
  3812. {IntrinsicOp::IOP_msad4, TranslateMSad4, DXIL::OpCode::NumOpCodes},
  3813. {IntrinsicOp::IOP_mul, EmptyLower, DXIL::OpCode::NumOpCodes},
  3814. {IntrinsicOp::IOP_normalize, TranslateNormalize, DXIL::OpCode::NumOpCodes},
  3815. {IntrinsicOp::IOP_pow, TranslatePow, DXIL::OpCode::NumOpCodes},
  3816. {IntrinsicOp::IOP_radians, TranslateRadians, DXIL::OpCode::NumOpCodes},
  3817. {IntrinsicOp::IOP_rcp, TranslateRCP, DXIL::OpCode::NumOpCodes},
  3818. {IntrinsicOp::IOP_reflect, TranslateReflect, DXIL::OpCode::NumOpCodes},
  3819. {IntrinsicOp::IOP_refract, TranslateRefract, DXIL::OpCode::NumOpCodes},
  3820. {IntrinsicOp::IOP_reversebits, TrivialUnaryOperation, DXIL::OpCode::Bfrev},
  3821. {IntrinsicOp::IOP_round, TrivialUnaryOperation, DXIL::OpCode::Round_ne},
  3822. {IntrinsicOp::IOP_rsqrt, TrivialUnaryOperation, DXIL::OpCode::Rsqrt},
  3823. {IntrinsicOp::IOP_saturate, TrivialUnaryOperation, DXIL::OpCode::Saturate},
  3824. {IntrinsicOp::IOP_sign, TranslateSign, DXIL::OpCode::NumOpCodes},
  3825. {IntrinsicOp::IOP_sin, TrivialUnaryOperation, DXIL::OpCode::Sin},
  3826. {IntrinsicOp::IOP_sincos, EmptyLower, DXIL::OpCode::NumOpCodes},
  3827. {IntrinsicOp::IOP_sinh, TrivialUnaryOperation, DXIL::OpCode::Hsin},
  3828. {IntrinsicOp::IOP_smoothstep, TranslateSmoothStep, DXIL::OpCode::NumOpCodes},
  3829. {IntrinsicOp::IOP_source_mark, EmptyLower, DXIL::OpCode::NumOpCodes},
  3830. {IntrinsicOp::IOP_sqrt, TrivialUnaryOperation, DXIL::OpCode::Sqrt},
  3831. {IntrinsicOp::IOP_step, TranslateStep, DXIL::OpCode::NumOpCodes},
  3832. {IntrinsicOp::IOP_tan, TrivialUnaryOperation, DXIL::OpCode::Tan},
  3833. {IntrinsicOp::IOP_tanh, TrivialUnaryOperation, DXIL::OpCode::Htan},
  3834. {IntrinsicOp::IOP_tex1D, EmptyLower, DXIL::OpCode::NumOpCodes},
  3835. {IntrinsicOp::IOP_tex1Dbias, EmptyLower, DXIL::OpCode::NumOpCodes},
  3836. {IntrinsicOp::IOP_tex1Dgrad, EmptyLower, DXIL::OpCode::NumOpCodes},
  3837. {IntrinsicOp::IOP_tex1Dlod, EmptyLower, DXIL::OpCode::NumOpCodes},
  3838. {IntrinsicOp::IOP_tex1Dproj, EmptyLower, DXIL::OpCode::NumOpCodes},
  3839. {IntrinsicOp::IOP_tex2D, EmptyLower, DXIL::OpCode::NumOpCodes},
  3840. {IntrinsicOp::IOP_tex2Dbias, EmptyLower, DXIL::OpCode::NumOpCodes},
  3841. {IntrinsicOp::IOP_tex2Dgrad, EmptyLower, DXIL::OpCode::NumOpCodes},
  3842. {IntrinsicOp::IOP_tex2Dlod, EmptyLower, DXIL::OpCode::NumOpCodes},
  3843. {IntrinsicOp::IOP_tex2Dproj, EmptyLower, DXIL::OpCode::NumOpCodes},
  3844. {IntrinsicOp::IOP_tex3D, EmptyLower, DXIL::OpCode::NumOpCodes},
  3845. {IntrinsicOp::IOP_tex3Dbias, EmptyLower, DXIL::OpCode::NumOpCodes},
  3846. {IntrinsicOp::IOP_tex3Dgrad, EmptyLower, DXIL::OpCode::NumOpCodes},
  3847. {IntrinsicOp::IOP_tex3Dlod, EmptyLower, DXIL::OpCode::NumOpCodes},
  3848. {IntrinsicOp::IOP_tex3Dproj, EmptyLower, DXIL::OpCode::NumOpCodes},
  3849. {IntrinsicOp::IOP_texCUBE, EmptyLower, DXIL::OpCode::NumOpCodes},
  3850. {IntrinsicOp::IOP_texCUBEbias, EmptyLower, DXIL::OpCode::NumOpCodes},
  3851. {IntrinsicOp::IOP_texCUBEgrad, EmptyLower, DXIL::OpCode::NumOpCodes},
  3852. {IntrinsicOp::IOP_texCUBElod, EmptyLower, DXIL::OpCode::NumOpCodes},
  3853. {IntrinsicOp::IOP_texCUBEproj, EmptyLower, DXIL::OpCode::NumOpCodes},
  3854. {IntrinsicOp::IOP_transpose, EmptyLower, DXIL::OpCode::NumOpCodes},
  3855. {IntrinsicOp::IOP_trunc, TrivialUnaryOperation, DXIL::OpCode::Round_z},
  3856. {IntrinsicOp::MOP_Append, StreamOutputLower, DXIL::OpCode::EmitStream},
  3857. {IntrinsicOp::MOP_RestartStrip, StreamOutputLower, DXIL::OpCode::CutStream},
  3858. {IntrinsicOp::MOP_CalculateLevelOfDetail, TranslateCalculateLOD, DXIL::OpCode::NumOpCodes},
  3859. {IntrinsicOp::MOP_CalculateLevelOfDetailUnclamped, TranslateCalculateLOD, DXIL::OpCode::NumOpCodes},
  3860. {IntrinsicOp::MOP_GetDimensions, TranslateGetDimensions, DXIL::OpCode::NumOpCodes},
  3861. {IntrinsicOp::MOP_Load, TranslateResourceLoad, DXIL::OpCode::NumOpCodes},
  3862. {IntrinsicOp::MOP_Sample, TranslateSample, DXIL::OpCode::Sample},
  3863. {IntrinsicOp::MOP_SampleBias, TranslateSample, DXIL::OpCode::SampleBias},
  3864. {IntrinsicOp::MOP_SampleCmp, TranslateSample, DXIL::OpCode::SampleCmp},
  3865. {IntrinsicOp::MOP_SampleCmpLevelZero, TranslateSample, DXIL::OpCode::SampleCmpLevelZero},
  3866. {IntrinsicOp::MOP_SampleGrad, TranslateSample, DXIL::OpCode::SampleGrad},
  3867. {IntrinsicOp::MOP_SampleLevel, TranslateSample, DXIL::OpCode::SampleLevel},
  3868. {IntrinsicOp::MOP_Gather, TranslateGather, DXIL::OpCode::TextureGather},
  3869. {IntrinsicOp::MOP_GatherAlpha, TranslateGather, DXIL::OpCode::TextureGather},
  3870. {IntrinsicOp::MOP_GatherBlue, TranslateGather, DXIL::OpCode::TextureGather},
  3871. {IntrinsicOp::MOP_GatherCmp, TranslateGather, DXIL::OpCode::TextureGatherCmp},
  3872. {IntrinsicOp::MOP_GatherCmpAlpha, TranslateGather, DXIL::OpCode::TextureGatherCmp},
  3873. {IntrinsicOp::MOP_GatherCmpBlue, TranslateGather, DXIL::OpCode::TextureGatherCmp},
  3874. {IntrinsicOp::MOP_GatherCmpGreen, TranslateGather, DXIL::OpCode::TextureGatherCmp},
  3875. {IntrinsicOp::MOP_GatherCmpRed, TranslateGather, DXIL::OpCode::TextureGatherCmp},
  3876. {IntrinsicOp::MOP_GatherGreen, TranslateGather, DXIL::OpCode::TextureGather},
  3877. {IntrinsicOp::MOP_GatherRed, TranslateGather, DXIL::OpCode::TextureGather},
  3878. {IntrinsicOp::MOP_GetSamplePosition, TranslateGetSamplePosition, DXIL::OpCode::NumOpCodes},
  3879. {IntrinsicOp::MOP_Load2, TranslateResourceLoad, DXIL::OpCode::NumOpCodes},
  3880. {IntrinsicOp::MOP_Load3, TranslateResourceLoad, DXIL::OpCode::NumOpCodes},
  3881. {IntrinsicOp::MOP_Load4, TranslateResourceLoad, DXIL::OpCode::NumOpCodes},
  3882. {IntrinsicOp::MOP_InterlockedAdd, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3883. {IntrinsicOp::MOP_InterlockedAnd, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3884. {IntrinsicOp::MOP_InterlockedCompareExchange, TranslateMopAtomicCmpXChg, DXIL::OpCode::NumOpCodes},
  3885. {IntrinsicOp::MOP_InterlockedCompareStore, TranslateMopAtomicCmpXChg, DXIL::OpCode::NumOpCodes},
  3886. {IntrinsicOp::MOP_InterlockedExchange, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3887. {IntrinsicOp::MOP_InterlockedMax, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3888. {IntrinsicOp::MOP_InterlockedMin, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3889. {IntrinsicOp::MOP_InterlockedOr, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3890. {IntrinsicOp::MOP_InterlockedXor, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes},
  3891. {IntrinsicOp::MOP_Store, TranslateResourceStore, DXIL::OpCode::NumOpCodes},
  3892. {IntrinsicOp::MOP_Store2, TranslateResourceStore, DXIL::OpCode::NumOpCodes},
  3893. {IntrinsicOp::MOP_Store3, TranslateResourceStore, DXIL::OpCode::NumOpCodes},
  3894. {IntrinsicOp::MOP_Store4, TranslateResourceStore, DXIL::OpCode::NumOpCodes},
  3895. {IntrinsicOp::MOP_DecrementCounter, GenerateUpdateCounter, DXIL::OpCode::NumOpCodes},
  3896. {IntrinsicOp::MOP_IncrementCounter, GenerateUpdateCounter, DXIL::OpCode::NumOpCodes},
  3897. {IntrinsicOp::MOP_Consume, EmptyLower, DXIL::OpCode::NumOpCodes},
  3898. // Manully added part.
  3899. { IntrinsicOp::IOP_InterlockedUMax, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes },
  3900. { IntrinsicOp::IOP_InterlockedUMin, TranslateIopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes },
  3901. { IntrinsicOp::IOP_WaveActiveUMax, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp },
  3902. { IntrinsicOp::IOP_WaveActiveUMin, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp },
  3903. { IntrinsicOp::IOP_WaveActiveUProduct, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp },
  3904. { IntrinsicOp::IOP_WaveActiveUSum, TranslateWaveA2A, DXIL::OpCode::WaveActiveOp },
  3905. { IntrinsicOp::IOP_WavePrefixUProduct, TranslateWaveA2A, DXIL::OpCode::WavePrefixOp },
  3906. { IntrinsicOp::IOP_WavePrefixUSum, TranslateWaveA2A, DXIL::OpCode::WavePrefixOp },
  3907. { IntrinsicOp::IOP_uclamp, TranslateClamp, DXIL::OpCode::NumOpCodes },
  3908. { IntrinsicOp::IOP_ufirstbithigh, TranslateFirstbitHi, DXIL::OpCode::FirstbitHi },
  3909. { IntrinsicOp::IOP_umad, TranslateFUITrinary, DXIL::OpCode::UMad},
  3910. { IntrinsicOp::IOP_umax, TranslateFUIBinary, DXIL::OpCode::UMax},
  3911. { IntrinsicOp::IOP_umin, TranslateFUIBinary, DXIL::OpCode::UMin },
  3912. { IntrinsicOp::IOP_umul, TranslateFUIBinary, DXIL::OpCode::UMul },
  3913. { IntrinsicOp::MOP_InterlockedUMax, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes },
  3914. { IntrinsicOp::MOP_InterlockedUMin, TranslateMopAtomicBinaryOperation, DXIL::OpCode::NumOpCodes },
  3915. };
  3916. }
  3917. static void TranslateBuiltinIntrinsic(CallInst *CI,
  3918. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  3919. unsigned opcode = hlsl::GetHLOpcode(CI);
  3920. const IntrinsicLower &lower = gLowerTable[opcode];
  3921. Value *Result =
  3922. lower.LowerFunc(CI, lower.IntriOpcode, lower.DxilOpcode, helper, pObjHelper, Translated);
  3923. if (Result)
  3924. CI->replaceAllUsesWith(Result);
  3925. }
  3926. // SharedMem.
  3927. namespace {
  3928. bool IsSharedMemPtr(Value *Ptr) {
  3929. return Ptr->getType()->getPointerAddressSpace() == DXIL::kTGSMAddrSpace;
  3930. }
  3931. bool IsLocalVariablePtr(Value *Ptr) {
  3932. while (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
  3933. Ptr = GEP->getPointerOperand();
  3934. }
  3935. bool isAlloca = isa<AllocaInst>(Ptr);
  3936. if (isAlloca) return true;
  3937. GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr);
  3938. if (!GV) return false;
  3939. return GV->getLinkage() == GlobalValue::LinkageTypes::InternalLinkage;
  3940. }
  3941. }
  3942. // Constant buffer.
  3943. namespace {
  3944. unsigned GetEltTypeByteSizeForConstBuf(Type *EltType, const DataLayout &DL) {
  3945. DXASSERT(EltType->isIntegerTy() || EltType->isFloatingPointTy(),
  3946. "not an element type");
  3947. // TODO: Use real size after change constant buffer into linear layout.
  3948. if (DL.getTypeSizeInBits(EltType) <= 32) {
  3949. // Constant buffer is 4 bytes align.
  3950. return 4;
  3951. } else
  3952. return 8;
  3953. }
  3954. Value *GenerateCBLoad(Value *handle, Value *offset, Type *EltTy, OP *hlslOP,
  3955. IRBuilder<> &Builder) {
  3956. Constant *OpArg = hlslOP->GetU32Const((unsigned)OP::OpCode::CBufferLoad);
  3957. // Align to 8 bytes for now.
  3958. Constant *align = hlslOP->GetU32Const(8);
  3959. Type *i1Ty = Type::getInt1Ty(EltTy->getContext());
  3960. if (EltTy != i1Ty) {
  3961. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoad, EltTy);
  3962. return Builder.CreateCall(CBLoad, {OpArg, handle, offset, align});
  3963. } else {
  3964. Type *i32Ty = Type::getInt32Ty(EltTy->getContext());
  3965. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoad, i32Ty);
  3966. Value *Result = Builder.CreateCall(CBLoad, {OpArg, handle, offset, align});
  3967. return Builder.CreateICmpEQ(Result, hlslOP->GetU32Const(0));
  3968. }
  3969. }
  3970. Value *TranslateConstBufMatLd(Type *matType, Value *handle, Value *offset,
  3971. bool colMajor, OP *OP, const DataLayout &DL,
  3972. IRBuilder<> &Builder) {
  3973. unsigned col, row;
  3974. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  3975. unsigned matSize = col * row;
  3976. std::vector<Value *> elts(matSize);
  3977. Value *EltByteSize = ConstantInt::get(
  3978. offset->getType(), GetEltTypeByteSizeForConstBuf(EltTy, DL));
  3979. // TODO: use real size after change constant buffer into linear layout.
  3980. Value *baseOffset = offset;
  3981. for (unsigned i = 0; i < matSize; i++) {
  3982. elts[i] = GenerateCBLoad(handle, baseOffset, EltTy, OP, Builder);
  3983. baseOffset = Builder.CreateAdd(baseOffset, EltByteSize);
  3984. }
  3985. return HLMatrixLower::BuildVector(EltTy, col * row, elts, Builder);
  3986. }
  3987. void TranslateCBGep(GetElementPtrInst *GEP, Value *handle, Value *baseOffset,
  3988. hlsl::OP *hlslOP, IRBuilder<> &Builder,
  3989. DxilFieldAnnotation *prevFieldAnnotation,
  3990. const DataLayout &DL, DxilTypeSystem &dxilTypeSys);
  3991. Value *GenerateVecEltFromGEP(Value *ldData, GetElementPtrInst *GEP,
  3992. IRBuilder<> &Builder) {
  3993. DXASSERT(GEP->getNumIndices() == 2, "must have 2 level");
  3994. Value *baseIdx = (GEP->idx_begin())->get();
  3995. Value *zeroIdx = Builder.getInt32(0);
  3996. DXASSERT_LOCALVAR(baseIdx && zeroIdx, baseIdx == zeroIdx,
  3997. "base index must be 0");
  3998. Value *idx = (GEP->idx_begin() + 1)->get();
  3999. if (ConstantInt *cidx = dyn_cast<ConstantInt>(idx)) {
  4000. return Builder.CreateExtractElement(ldData, idx);
  4001. } else {
  4002. // Dynamic indexing.
  4003. // Copy vec to array.
  4004. Type *Ty = ldData->getType();
  4005. Type *EltTy = Ty->getVectorElementType();
  4006. unsigned vecSize = Ty->getVectorNumElements();
  4007. ArrayType *AT = ArrayType::get(EltTy, vecSize);
  4008. IRBuilder<> AllocaBuilder(
  4009. GEP->getParent()->getParent()->getEntryBlock().getFirstInsertionPt());
  4010. Value *tempArray = AllocaBuilder.CreateAlloca(AT);
  4011. Value *zero = Builder.getInt32(0);
  4012. for (unsigned int i = 0; i < vecSize; i++) {
  4013. Value *Elt = Builder.CreateExtractElement(ldData, Builder.getInt32(i));
  4014. Value *Ptr =
  4015. Builder.CreateInBoundsGEP(tempArray, {zero, Builder.getInt32(i)});
  4016. Builder.CreateStore(Elt, Ptr);
  4017. }
  4018. // Load from temp array.
  4019. Value *EltGEP = Builder.CreateInBoundsGEP(tempArray, {zero, idx});
  4020. return Builder.CreateLoad(EltGEP);
  4021. }
  4022. }
  4023. void TranslateCBAddressUser(Instruction *user, Value *handle, Value *baseOffset,
  4024. hlsl::OP *hlslOP,
  4025. DxilFieldAnnotation *prevFieldAnnotation,
  4026. DxilTypeSystem &dxilTypeSys, const DataLayout &DL) {
  4027. IRBuilder<> Builder(user);
  4028. if (CallInst *CI = dyn_cast<CallInst>(user)) {
  4029. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  4030. unsigned opcode = GetHLOpcode(CI);
  4031. if (group == HLOpcodeGroup::HLMatLoadStore) {
  4032. HLMatLoadStoreOpcode matOp = static_cast<HLMatLoadStoreOpcode>(opcode);
  4033. bool colMajor = matOp == HLMatLoadStoreOpcode::ColMatLoad;
  4034. DXASSERT(matOp == HLMatLoadStoreOpcode::ColMatLoad ||
  4035. matOp == HLMatLoadStoreOpcode::RowMatLoad,
  4036. "No store on cbuffer");
  4037. Type *matType = CI->getArgOperand(HLOperandIndex::kMatLoadPtrOpIdx)
  4038. ->getType()
  4039. ->getPointerElementType();
  4040. Value *newLd = TranslateConstBufMatLd(matType, handle, baseOffset,
  4041. colMajor, hlslOP, DL, Builder);
  4042. CI->replaceAllUsesWith(newLd);
  4043. CI->eraseFromParent();
  4044. } else if (group == HLOpcodeGroup::HLSubscript) {
  4045. HLSubscriptOpcode subOp = static_cast<HLSubscriptOpcode>(opcode);
  4046. Value *basePtr = CI->getArgOperand(HLOperandIndex::kMatSubscriptMatOpIdx);
  4047. Type *matType = basePtr->getType()->getPointerElementType();
  4048. unsigned col, row;
  4049. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  4050. Value *EltByteSize = ConstantInt::get(
  4051. baseOffset->getType(), GetEltTypeByteSizeForConstBuf(EltTy, DL));
  4052. Value *idx = CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx);
  4053. Type *resultType = CI->getType()->getPointerElementType();
  4054. unsigned resultSize = 1;
  4055. if (resultType->isVectorTy())
  4056. resultSize = resultType->getVectorNumElements();
  4057. DXASSERT(resultSize <= 16, "up to 4x4 elements in vector or matrix");
  4058. _Analysis_assume_(resultSize <= 16);
  4059. Value *idxList[16];
  4060. switch (subOp) {
  4061. case HLSubscriptOpcode::ColMatSubscript:
  4062. case HLSubscriptOpcode::RowMatSubscript: {
  4063. for (unsigned i = 0; i < resultSize; i++) {
  4064. Value *idx =
  4065. CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx + i);
  4066. Value *offset = Builder.CreateMul(idx, EltByteSize);
  4067. idxList[i] = Builder.CreateAdd(baseOffset, offset);
  4068. }
  4069. } break;
  4070. case HLSubscriptOpcode::RowMatElement:
  4071. case HLSubscriptOpcode::ColMatElement: {
  4072. Constant *EltIdxs = cast<Constant>(idx);
  4073. for (unsigned i = 0; i < resultSize; i++) {
  4074. Value *offset =
  4075. Builder.CreateMul(EltIdxs->getAggregateElement(i), EltByteSize);
  4076. idxList[i] = Builder.CreateAdd(baseOffset, offset);
  4077. }
  4078. } break;
  4079. default:
  4080. DXASSERT(0, "invalid operation on const buffer");
  4081. break;
  4082. }
  4083. Value *ldData = UndefValue::get(resultType);
  4084. if (resultType->isVectorTy()) {
  4085. for (unsigned i = 0; i < resultSize; i++) {
  4086. Value *eltData =
  4087. GenerateCBLoad(handle, idxList[i], EltTy, hlslOP, Builder);
  4088. ldData = Builder.CreateInsertElement(ldData, eltData, i);
  4089. }
  4090. } else {
  4091. ldData = GenerateCBLoad(handle, idxList[0], EltTy, hlslOP, Builder);
  4092. }
  4093. for (auto U = CI->user_begin(); U != CI->user_end();) {
  4094. Value *subsUser = *(U++);
  4095. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(subsUser)) {
  4096. Value *subData = GenerateVecEltFromGEP(ldData, GEP, Builder);
  4097. for (auto gepU = GEP->user_begin(); gepU != GEP->user_end();) {
  4098. Value *gepUser = *(gepU++);
  4099. // Must be load here;
  4100. LoadInst *ldUser = cast<LoadInst>(gepUser);
  4101. ldUser->replaceAllUsesWith(subData);
  4102. ldUser->eraseFromParent();
  4103. }
  4104. GEP->eraseFromParent();
  4105. } else {
  4106. // Must be load here.
  4107. LoadInst *ldUser = cast<LoadInst>(subsUser);
  4108. ldUser->replaceAllUsesWith(ldData);
  4109. ldUser->eraseFromParent();
  4110. }
  4111. }
  4112. CI->eraseFromParent();
  4113. } else {
  4114. DXASSERT(0, "not implemented yet");
  4115. }
  4116. } else if (LoadInst *ldInst = dyn_cast<LoadInst>(user)) {
  4117. Type *Ty = ldInst->getType();
  4118. Type *EltTy = Ty->getScalarType();
  4119. DXASSERT(!Ty->isAggregateType(), "should be flat in previous pass");
  4120. unsigned EltByteSize = GetEltTypeByteSizeForConstBuf(EltTy, DL);
  4121. Value *newLd = GenerateCBLoad(handle, baseOffset, EltTy, hlslOP, Builder);
  4122. if (Ty->isVectorTy()) {
  4123. Value *result = UndefValue::get(Ty);
  4124. result = Builder.CreateInsertElement(result, newLd, (uint64_t)0);
  4125. // Update offset by 4 bytes.
  4126. Value *offset =
  4127. Builder.CreateAdd(baseOffset, hlslOP->GetU32Const(EltByteSize));
  4128. for (unsigned i = 1; i < Ty->getVectorNumElements(); i++) {
  4129. Value *elt = GenerateCBLoad(handle, offset, EltTy, hlslOP, Builder);
  4130. result = Builder.CreateInsertElement(result, elt, i);
  4131. // Update offset by 4 bytes.
  4132. offset = Builder.CreateAdd(offset, hlslOP->GetU32Const(EltByteSize));
  4133. }
  4134. newLd = result;
  4135. }
  4136. ldInst->replaceAllUsesWith(newLd);
  4137. ldInst->eraseFromParent();
  4138. } else {
  4139. // Must be GEP here
  4140. GetElementPtrInst *GEP = cast<GetElementPtrInst>(user);
  4141. TranslateCBGep(GEP, handle, baseOffset, hlslOP, Builder,
  4142. prevFieldAnnotation, DL, dxilTypeSys);
  4143. GEP->eraseFromParent();
  4144. }
  4145. }
  4146. void TranslateCBGep(GetElementPtrInst *GEP, Value *handle, Value *baseOffset,
  4147. hlsl::OP *hlslOP, IRBuilder<> &Builder,
  4148. DxilFieldAnnotation *prevFieldAnnotation,
  4149. const DataLayout &DL, DxilTypeSystem &dxilTypeSys) {
  4150. SmallVector<Value *, 8> Indices(GEP->idx_begin(), GEP->idx_end());
  4151. Value *offset = baseOffset;
  4152. // update offset
  4153. DxilFieldAnnotation *fieldAnnotation = prevFieldAnnotation;
  4154. gep_type_iterator GEPIt = gep_type_begin(GEP), E = gep_type_end(GEP);
  4155. for (; GEPIt != E; GEPIt++) {
  4156. Value *idx = GEPIt.getOperand();
  4157. unsigned immIdx = 0;
  4158. bool bImmIdx = false;
  4159. if (Constant *constIdx = dyn_cast<Constant>(idx)) {
  4160. immIdx = constIdx->getUniqueInteger().getLimitedValue();
  4161. bImmIdx = true;
  4162. }
  4163. if (GEPIt->isPointerTy()) {
  4164. Type *EltTy = GEPIt->getPointerElementType();
  4165. unsigned size = 0;
  4166. if (StructType *ST = dyn_cast<StructType>(EltTy)) {
  4167. DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST);
  4168. size = annotation->GetCBufferSize();
  4169. } else {
  4170. DXASSERT(fieldAnnotation, "must be a field");
  4171. if (ArrayType *AT = dyn_cast<ArrayType>(EltTy)) {
  4172. unsigned EltSize = dxilutil::GetLegacyCBufferFieldElementSize(
  4173. *fieldAnnotation, EltTy, dxilTypeSys);
  4174. // Decide the nested array size.
  4175. unsigned nestedArraySize = 1;
  4176. Type *EltTy = AT->getArrayElementType();
  4177. // support multi level of array
  4178. while (EltTy->isArrayTy()) {
  4179. ArrayType *EltAT = cast<ArrayType>(EltTy);
  4180. nestedArraySize *= EltAT->getNumElements();
  4181. EltTy = EltAT->getElementType();
  4182. }
  4183. // Align to 4 * 4 bytes.
  4184. unsigned alignedSize = (EltSize + 15) & 0xfffffff0;
  4185. size = nestedArraySize * alignedSize;
  4186. } else {
  4187. size = DL.getTypeAllocSize(EltTy);
  4188. }
  4189. }
  4190. // Align to 4 * 4 bytes.
  4191. size = (size + 15) & 0xfffffff0;
  4192. if (bImmIdx) {
  4193. unsigned tempOffset = size * immIdx;
  4194. offset = Builder.CreateAdd(offset, hlslOP->GetU32Const(tempOffset));
  4195. } else {
  4196. Value *tempOffset = Builder.CreateMul(idx, hlslOP->GetU32Const(size));
  4197. offset = Builder.CreateAdd(offset, tempOffset);
  4198. }
  4199. } else if (GEPIt->isStructTy()) {
  4200. StructType *ST = cast<StructType>(*GEPIt);
  4201. DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST);
  4202. fieldAnnotation = &annotation->GetFieldAnnotation(immIdx);
  4203. unsigned structOffset = fieldAnnotation->GetCBufferOffset();
  4204. offset = Builder.CreateAdd(offset, hlslOP->GetU32Const(structOffset));
  4205. } else if (GEPIt->isArrayTy()) {
  4206. DXASSERT(fieldAnnotation != nullptr, "must a field");
  4207. unsigned EltSize = dxilutil::GetLegacyCBufferFieldElementSize(
  4208. *fieldAnnotation, *GEPIt, dxilTypeSys);
  4209. // Decide the nested array size.
  4210. unsigned nestedArraySize = 1;
  4211. Type *EltTy = GEPIt->getArrayElementType();
  4212. // support multi level of array
  4213. while (EltTy->isArrayTy()) {
  4214. ArrayType *EltAT = cast<ArrayType>(EltTy);
  4215. nestedArraySize *= EltAT->getNumElements();
  4216. EltTy = EltAT->getElementType();
  4217. }
  4218. // Align to 4 * 4 bytes.
  4219. unsigned alignedSize = (EltSize + 15) & 0xfffffff0;
  4220. unsigned size = nestedArraySize * alignedSize;
  4221. if (bImmIdx) {
  4222. unsigned tempOffset = size * immIdx;
  4223. offset = Builder.CreateAdd(offset, hlslOP->GetU32Const(tempOffset));
  4224. } else {
  4225. Value *tempOffset = Builder.CreateMul(idx, hlslOP->GetU32Const(size));
  4226. offset = Builder.CreateAdd(offset, tempOffset);
  4227. }
  4228. } else if (GEPIt->isVectorTy()) {
  4229. unsigned size = DL.getTypeAllocSize(GEPIt->getVectorElementType());
  4230. if (bImmIdx) {
  4231. unsigned tempOffset = size * immIdx;
  4232. offset = Builder.CreateAdd(offset, hlslOP->GetU32Const(tempOffset));
  4233. } else {
  4234. Value *tempOffset = Builder.CreateMul(idx, hlslOP->GetU32Const(size));
  4235. offset = Builder.CreateAdd(offset, tempOffset);
  4236. }
  4237. } else {
  4238. gep_type_iterator temp = GEPIt;
  4239. temp++;
  4240. DXASSERT(temp == E, "scalar type must be the last");
  4241. }
  4242. }
  4243. for (auto U = GEP->user_begin(); U != GEP->user_end();) {
  4244. Instruction *user = cast<Instruction>(*(U++));
  4245. TranslateCBAddressUser(user, handle, offset, hlslOP, fieldAnnotation,
  4246. dxilTypeSys, DL);
  4247. }
  4248. }
  4249. void TranslateCBOperations(Value *handle, Value *ptr, Value *offset, OP *hlslOP,
  4250. DxilTypeSystem &dxilTypeSys, const DataLayout &DL) {
  4251. auto User = ptr->user_begin();
  4252. auto UserE = ptr->user_end();
  4253. for (; User != UserE;) {
  4254. // Must be Instruction.
  4255. Instruction *I = cast<Instruction>(*(User++));
  4256. TranslateCBAddressUser(I, handle, offset, hlslOP,
  4257. /*prevFieldAnnotation*/ nullptr, dxilTypeSys, DL);
  4258. }
  4259. }
  4260. Value *GenerateCBLoadLegacy(Value *handle, Value *legacyIdx,
  4261. unsigned channelOffset, Type *EltTy, OP *hlslOP,
  4262. IRBuilder<> &Builder) {
  4263. DXASSERT((channelOffset) < 4, "legacy cbuffer don't across 16 bytes register.");
  4264. Constant *OpArg = hlslOP->GetU32Const((unsigned)OP::OpCode::CBufferLoadLegacy);
  4265. Type *i1Ty = Type::getInt1Ty(EltTy->getContext());
  4266. Type *doubleTy = Type::getDoubleTy(EltTy->getContext());
  4267. Type *i64Ty = Type::getInt64Ty(EltTy->getContext());
  4268. bool isBool = EltTy == i1Ty;
  4269. bool is64 = (EltTy == doubleTy) | (EltTy == i64Ty);
  4270. bool isNormal = !isBool && !is64;
  4271. if (isNormal) {
  4272. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, EltTy);
  4273. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4274. return Builder.CreateExtractValue(loadLegacy, channelOffset);
  4275. } else if (is64) {
  4276. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, EltTy);
  4277. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4278. DXASSERT((channelOffset&1)==0,"channel offset must be even for double");
  4279. unsigned eltIdx = channelOffset>>1;
  4280. Value *Result = Builder.CreateExtractValue(loadLegacy, eltIdx);
  4281. return Result;
  4282. } else {
  4283. DXASSERT(isBool, "bool should be i1");
  4284. Type *i32Ty = Type::getInt32Ty(EltTy->getContext());
  4285. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, i32Ty);
  4286. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4287. Value *Result = Builder.CreateExtractValue(loadLegacy, channelOffset);
  4288. return Builder.CreateICmpEQ(Result, hlslOP->GetU32Const(0));
  4289. }
  4290. }
  4291. Value *GenerateCBLoadLegacy(Value *handle, Value *legacyIdx,
  4292. unsigned channelOffset, Type *EltTy,
  4293. unsigned vecSize, OP *hlslOP,
  4294. IRBuilder<> &Builder) {
  4295. Constant *OpArg = hlslOP->GetU32Const((unsigned)OP::OpCode::CBufferLoadLegacy);
  4296. Type *i1Ty = Type::getInt1Ty(EltTy->getContext());
  4297. Type *doubleTy = Type::getDoubleTy(EltTy->getContext());
  4298. Type *i64Ty = Type::getInt64Ty(EltTy->getContext());
  4299. Type *halfTy = Type::getHalfTy(EltTy->getContext());
  4300. bool isBool = EltTy == i1Ty;
  4301. bool is64 = (EltTy == doubleTy) | (EltTy == i64Ty);
  4302. bool is16 = EltTy == halfTy && !hlslOP->UseMinPrecision();
  4303. bool isNormal = !isBool && !is64 && !is16;
  4304. DXASSERT(is16 || (channelOffset + vecSize) <= 4, "legacy cbuffer don't across 16 bytes register.");
  4305. if (isNormal) {
  4306. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, EltTy);
  4307. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4308. Value *Result = UndefValue::get(VectorType::get(EltTy, vecSize));
  4309. for (unsigned i = 0; i < vecSize; ++i) {
  4310. Value *NewElt = Builder.CreateExtractValue(loadLegacy, channelOffset+i);
  4311. Result = Builder.CreateInsertElement(Result, NewElt, i);
  4312. }
  4313. return Result;
  4314. } else if (is16) {
  4315. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, EltTy);
  4316. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4317. Value *Result = UndefValue::get(VectorType::get(EltTy, vecSize));
  4318. // index aligned by 2 bytes not 4 bytes
  4319. channelOffset *= 2;
  4320. for (unsigned i = 0; i < vecSize; ++i) {
  4321. Value *NewElt = Builder.CreateExtractValue(loadLegacy, channelOffset + i);
  4322. Result = Builder.CreateInsertElement(Result, NewElt, i);
  4323. }
  4324. return Result;
  4325. } else if (is64) {
  4326. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, EltTy);
  4327. Value *loadLegacy = Builder.CreateCall(CBLoad, { OpArg, handle, legacyIdx });
  4328. Value *Result = UndefValue::get(VectorType::get(EltTy, vecSize));
  4329. unsigned smallVecSize = 2;
  4330. if (vecSize < smallVecSize)
  4331. smallVecSize = vecSize;
  4332. for (unsigned i = 0; i < smallVecSize; ++i) {
  4333. Value *NewElt = Builder.CreateExtractValue(loadLegacy, channelOffset+i);
  4334. Result = Builder.CreateInsertElement(Result, NewElt, i);
  4335. }
  4336. if (vecSize > 2) {
  4337. // Got to next cb register.
  4338. legacyIdx = Builder.CreateAdd(legacyIdx, hlslOP->GetU32Const(1));
  4339. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4340. for (unsigned i = 2; i < vecSize; ++i) {
  4341. Value *NewElt =
  4342. Builder.CreateExtractValue(loadLegacy, i-2);
  4343. Result = Builder.CreateInsertElement(Result, NewElt, i);
  4344. }
  4345. }
  4346. return Result;
  4347. } else {
  4348. DXASSERT(isBool, "bool should be i1");
  4349. Type *i32Ty = Type::getInt32Ty(EltTy->getContext());
  4350. Function *CBLoad = hlslOP->GetOpFunc(OP::OpCode::CBufferLoadLegacy, i32Ty);
  4351. Value *loadLegacy = Builder.CreateCall(CBLoad, {OpArg, handle, legacyIdx});
  4352. Value *Result = UndefValue::get(VectorType::get(i32Ty, vecSize));
  4353. for (unsigned i = 0; i < vecSize; ++i) {
  4354. Value *NewElt = Builder.CreateExtractValue(loadLegacy, channelOffset+i);
  4355. Result = Builder.CreateInsertElement(Result, NewElt, i);
  4356. }
  4357. return Builder.CreateICmpEQ(Result, ConstantAggregateZero::get(Result->getType()));
  4358. }
  4359. }
  4360. Value *TranslateConstBufMatLdLegacy(Type *matType, Value *handle,
  4361. Value *legacyIdx, bool colMajor, OP *OP,
  4362. const DataLayout &DL,
  4363. IRBuilder<> &Builder) {
  4364. unsigned col, row;
  4365. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  4366. unsigned matSize = col * row;
  4367. std::vector<Value *> elts(matSize);
  4368. unsigned EltByteSize = GetEltTypeByteSizeForConstBuf(EltTy, DL);
  4369. if (colMajor) {
  4370. unsigned colByteSize = 4 * EltByteSize;
  4371. unsigned colRegSize = (colByteSize + 15) >> 4;
  4372. for (unsigned c = 0; c < col; c++) {
  4373. Value *col = GenerateCBLoadLegacy(handle, legacyIdx, /*channelOffset*/ 0,
  4374. EltTy, row, OP, Builder);
  4375. for (unsigned r = 0; r < row; r++) {
  4376. unsigned matIdx = HLMatrixLower::GetColMajorIdx(r, c, row);
  4377. elts[matIdx] = Builder.CreateExtractElement(col, r);
  4378. }
  4379. // Update offset for a column.
  4380. legacyIdx = Builder.CreateAdd(legacyIdx, OP->GetU32Const(colRegSize));
  4381. }
  4382. } else {
  4383. unsigned rowByteSize = 4 * EltByteSize;
  4384. unsigned rowRegSize = (rowByteSize + 15) >> 4;
  4385. for (unsigned r = 0; r < row; r++) {
  4386. Value *row = GenerateCBLoadLegacy(handle, legacyIdx, /*channelOffset*/ 0,
  4387. EltTy, col, OP, Builder);
  4388. for (unsigned c = 0; c < col; c++) {
  4389. unsigned matIdx = HLMatrixLower::GetRowMajorIdx(r, c, col);
  4390. elts[matIdx] = Builder.CreateExtractElement(row, c);
  4391. }
  4392. // Update offset for a row.
  4393. legacyIdx = Builder.CreateAdd(legacyIdx, OP->GetU32Const(rowRegSize));
  4394. }
  4395. }
  4396. return HLMatrixLower::BuildVector(EltTy, col * row, elts, Builder);
  4397. }
  4398. void TranslateCBGepLegacy(GetElementPtrInst *GEP, Value *handle,
  4399. Value *legacyIdx, unsigned channelOffset,
  4400. hlsl::OP *hlslOP, IRBuilder<> &Builder,
  4401. DxilFieldAnnotation *prevFieldAnnotation,
  4402. const DataLayout &DL, DxilTypeSystem &dxilTypeSys,
  4403. HLObjectOperationLowerHelper *pObjHelper);
  4404. void TranslateResourceInCB(LoadInst *LI,
  4405. HLObjectOperationLowerHelper *pObjHelper,
  4406. GlobalVariable *CbGV) {
  4407. if (LI->user_empty()) {
  4408. LI->eraseFromParent();
  4409. return;
  4410. }
  4411. GetElementPtrInst *Ptr = cast<GetElementPtrInst>(LI->getPointerOperand());
  4412. CallInst *CI = cast<CallInst>(LI->user_back());
  4413. MDNode *MD = HLModule::GetDxilResourceAttrib(CI->getCalledFunction());
  4414. Value *ResPtr = pObjHelper->GetOrCreateResourceForCbPtr(Ptr, CbGV, MD);
  4415. // Lower Ptr to GV base Ptr.
  4416. Value *GvPtr = pObjHelper->LowerCbResourcePtr(Ptr, ResPtr);
  4417. IRBuilder<> Builder(LI);
  4418. Value *GvLd = Builder.CreateLoad(GvPtr);
  4419. LI->replaceAllUsesWith(GvLd);
  4420. LI->eraseFromParent();
  4421. }
  4422. void TranslateCBAddressUserLegacy(Instruction *user, Value *handle,
  4423. Value *legacyIdx, unsigned channelOffset,
  4424. hlsl::OP *hlslOP,
  4425. DxilFieldAnnotation *prevFieldAnnotation,
  4426. DxilTypeSystem &dxilTypeSys,
  4427. const DataLayout &DL,
  4428. HLObjectOperationLowerHelper *pObjHelper) {
  4429. IRBuilder<> Builder(user);
  4430. if (CallInst *CI = dyn_cast<CallInst>(user)) {
  4431. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  4432. unsigned opcode = GetHLOpcode(CI);
  4433. if (group == HLOpcodeGroup::HLMatLoadStore) {
  4434. HLMatLoadStoreOpcode matOp = static_cast<HLMatLoadStoreOpcode>(opcode);
  4435. bool colMajor = matOp == HLMatLoadStoreOpcode::ColMatLoad;
  4436. DXASSERT(matOp == HLMatLoadStoreOpcode::ColMatLoad ||
  4437. matOp == HLMatLoadStoreOpcode::RowMatLoad,
  4438. "No store on cbuffer");
  4439. Type *matType = CI->getArgOperand(HLOperandIndex::kMatLoadPtrOpIdx)
  4440. ->getType()
  4441. ->getPointerElementType();
  4442. Value *newLd = TranslateConstBufMatLdLegacy(
  4443. matType, handle, legacyIdx, colMajor, hlslOP, DL, Builder);
  4444. CI->replaceAllUsesWith(newLd);
  4445. CI->eraseFromParent();
  4446. } else if (group == HLOpcodeGroup::HLSubscript) {
  4447. HLSubscriptOpcode subOp = static_cast<HLSubscriptOpcode>(opcode);
  4448. Value *basePtr = CI->getArgOperand(HLOperandIndex::kMatSubscriptMatOpIdx);
  4449. Type *matType = basePtr->getType()->getPointerElementType();
  4450. unsigned col, row;
  4451. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  4452. Value *idx = CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx);
  4453. Type *resultType = CI->getType()->getPointerElementType();
  4454. unsigned resultSize = 1;
  4455. if (resultType->isVectorTy())
  4456. resultSize = resultType->getVectorNumElements();
  4457. DXASSERT(resultSize <= 16, "up to 4x4 elements in vector or matrix");
  4458. _Analysis_assume_(resultSize <= 16);
  4459. Value *idxList[16];
  4460. bool colMajor = subOp == HLSubscriptOpcode::ColMatSubscript ||
  4461. subOp == HLSubscriptOpcode::ColMatElement;
  4462. bool dynamicIndexing = !isa<ConstantInt>(idx) &&
  4463. !isa<ConstantAggregateZero>(idx) &&
  4464. !isa<ConstantDataSequential>(idx);
  4465. Value *ldData = UndefValue::get(resultType);
  4466. if (!dynamicIndexing) {
  4467. Value *matLd = TranslateConstBufMatLdLegacy(
  4468. matType, handle, legacyIdx, colMajor, hlslOP, DL, Builder);
  4469. // The matLd is keep original layout, just use the idx calc in
  4470. // EmitHLSLMatrixElement and EmitHLSLMatrixSubscript.
  4471. switch (subOp) {
  4472. case HLSubscriptOpcode::RowMatSubscript:
  4473. case HLSubscriptOpcode::ColMatSubscript: {
  4474. for (unsigned i = 0; i < resultSize; i++) {
  4475. idxList[i] =
  4476. CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx + i);
  4477. }
  4478. } break;
  4479. case HLSubscriptOpcode::RowMatElement:
  4480. case HLSubscriptOpcode::ColMatElement: {
  4481. Constant *EltIdxs = cast<Constant>(idx);
  4482. for (unsigned i = 0; i < resultSize; i++) {
  4483. idxList[i] = EltIdxs->getAggregateElement(i);
  4484. }
  4485. } break;
  4486. default:
  4487. DXASSERT(0, "invalid operation on const buffer");
  4488. break;
  4489. }
  4490. if (resultType->isVectorTy()) {
  4491. for (unsigned i = 0; i < resultSize; i++) {
  4492. Value *eltData = Builder.CreateExtractElement(matLd, idxList[i]);
  4493. ldData = Builder.CreateInsertElement(ldData, eltData, i);
  4494. }
  4495. } else {
  4496. Value *eltData = Builder.CreateExtractElement(matLd, idxList[0]);
  4497. ldData = eltData;
  4498. }
  4499. } else {
  4500. // Must be matSub here.
  4501. Value *idx = CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx);
  4502. if (colMajor) {
  4503. // idx is c * row + r.
  4504. // For first col, c is 0, so idx is r.
  4505. Value *one = Builder.getInt32(1);
  4506. // row.x = c[0].[idx]
  4507. // row.y = c[1].[idx]
  4508. // row.z = c[2].[idx]
  4509. // row.w = c[3].[idx]
  4510. Value *Elts[4];
  4511. ArrayType *AT = ArrayType::get(EltTy, col);
  4512. IRBuilder<> AllocaBuilder(user->getParent()
  4513. ->getParent()
  4514. ->getEntryBlock()
  4515. .getFirstInsertionPt());
  4516. Value *tempArray = AllocaBuilder.CreateAlloca(AT);
  4517. Value *zero = AllocaBuilder.getInt32(0);
  4518. Value *cbufIdx = legacyIdx;
  4519. for (unsigned int c = 0; c < col; c++) {
  4520. Value *ColVal =
  4521. GenerateCBLoadLegacy(handle, cbufIdx, /*channelOffset*/ 0,
  4522. EltTy, row, hlslOP, Builder);
  4523. // Convert ColVal to array for indexing.
  4524. for (unsigned int r = 0; r < row; r++) {
  4525. Value *Elt =
  4526. Builder.CreateExtractElement(ColVal, Builder.getInt32(r));
  4527. Value *Ptr = Builder.CreateInBoundsGEP(
  4528. tempArray, {zero, Builder.getInt32(r)});
  4529. Builder.CreateStore(Elt, Ptr);
  4530. }
  4531. Value *Ptr = Builder.CreateInBoundsGEP(tempArray, {zero, idx});
  4532. Elts[c] = Builder.CreateLoad(Ptr);
  4533. // Update cbufIdx.
  4534. cbufIdx = Builder.CreateAdd(cbufIdx, one);
  4535. }
  4536. if (resultType->isVectorTy()) {
  4537. for (unsigned int c = 0; c < col; c++) {
  4538. ldData = Builder.CreateInsertElement(ldData, Elts[c], c);
  4539. }
  4540. } else {
  4541. ldData = Elts[0];
  4542. }
  4543. } else {
  4544. // idx is r * col + c;
  4545. // r = idx / col;
  4546. Value *cCol = ConstantInt::get(idx->getType(), col);
  4547. idx = Builder.CreateUDiv(idx, cCol);
  4548. idx = Builder.CreateAdd(idx, legacyIdx);
  4549. // Just return a row.
  4550. ldData = GenerateCBLoadLegacy(handle, idx, /*channelOffset*/ 0, EltTy,
  4551. row, hlslOP, Builder);
  4552. }
  4553. if (!resultType->isVectorTy()) {
  4554. ldData = Builder.CreateExtractElement(ldData, Builder.getInt32(0));
  4555. }
  4556. }
  4557. for (auto U = CI->user_begin(); U != CI->user_end();) {
  4558. Value *subsUser = *(U++);
  4559. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(subsUser)) {
  4560. Value *subData = GenerateVecEltFromGEP(ldData, GEP, Builder);
  4561. for (auto gepU = GEP->user_begin(); gepU != GEP->user_end();) {
  4562. Value *gepUser = *(gepU++);
  4563. // Must be load here;
  4564. LoadInst *ldUser = cast<LoadInst>(gepUser);
  4565. ldUser->replaceAllUsesWith(subData);
  4566. ldUser->eraseFromParent();
  4567. }
  4568. GEP->eraseFromParent();
  4569. } else {
  4570. // Must be load here.
  4571. LoadInst *ldUser = cast<LoadInst>(subsUser);
  4572. ldUser->replaceAllUsesWith(ldData);
  4573. ldUser->eraseFromParent();
  4574. }
  4575. }
  4576. CI->eraseFromParent();
  4577. } else {
  4578. DXASSERT(0, "not implemented yet");
  4579. }
  4580. } else if (LoadInst *ldInst = dyn_cast<LoadInst>(user)) {
  4581. Type *Ty = ldInst->getType();
  4582. Type *EltTy = Ty->getScalarType();
  4583. // Resource inside cbuffer is lowered after GenerateDxilOperations.
  4584. if (HLModule::IsHLSLObjectType(Ty)) {
  4585. CallInst *CI = cast<CallInst>(handle);
  4586. GlobalVariable *CbGV = cast<GlobalVariable>(
  4587. CI->getArgOperand(HLOperandIndex::kCreateHandleResourceOpIdx));
  4588. TranslateResourceInCB(ldInst, pObjHelper, CbGV);
  4589. return;
  4590. }
  4591. DXASSERT(!Ty->isAggregateType(), "should be flat in previous pass");
  4592. Value *newLd = nullptr;
  4593. if (Ty->isVectorTy())
  4594. newLd = GenerateCBLoadLegacy(handle, legacyIdx, channelOffset, EltTy,
  4595. Ty->getVectorNumElements(), hlslOP, Builder);
  4596. else
  4597. newLd = GenerateCBLoadLegacy(handle, legacyIdx, channelOffset, EltTy,
  4598. hlslOP, Builder);
  4599. ldInst->replaceAllUsesWith(newLd);
  4600. ldInst->eraseFromParent();
  4601. } else {
  4602. // Must be GEP here
  4603. GetElementPtrInst *GEP = cast<GetElementPtrInst>(user);
  4604. TranslateCBGepLegacy(GEP, handle, legacyIdx, channelOffset, hlslOP, Builder,
  4605. prevFieldAnnotation, DL, dxilTypeSys, pObjHelper);
  4606. GEP->eraseFromParent();
  4607. }
  4608. }
  4609. void TranslateCBGepLegacy(GetElementPtrInst *GEP, Value *handle,
  4610. Value *legacyIndex, unsigned channel,
  4611. hlsl::OP *hlslOP, IRBuilder<> &Builder,
  4612. DxilFieldAnnotation *prevFieldAnnotation,
  4613. const DataLayout &DL, DxilTypeSystem &dxilTypeSys,
  4614. HLObjectOperationLowerHelper *pObjHelper) {
  4615. SmallVector<Value *, 8> Indices(GEP->idx_begin(), GEP->idx_end());
  4616. // update offset
  4617. DxilFieldAnnotation *fieldAnnotation = prevFieldAnnotation;
  4618. gep_type_iterator GEPIt = gep_type_begin(GEP), E = gep_type_end(GEP);
  4619. for (; GEPIt != E; GEPIt++) {
  4620. Value *idx = GEPIt.getOperand();
  4621. unsigned immIdx = 0;
  4622. bool bImmIdx = false;
  4623. if (Constant *constIdx = dyn_cast<Constant>(idx)) {
  4624. immIdx = constIdx->getUniqueInteger().getLimitedValue();
  4625. bImmIdx = true;
  4626. }
  4627. if (GEPIt->isPointerTy()) {
  4628. Type *EltTy = GEPIt->getPointerElementType();
  4629. unsigned size = 0;
  4630. if (StructType *ST = dyn_cast<StructType>(EltTy)) {
  4631. DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST);
  4632. size = annotation->GetCBufferSize();
  4633. } else {
  4634. DXASSERT(fieldAnnotation, "must be a field");
  4635. if (ArrayType *AT = dyn_cast<ArrayType>(EltTy)) {
  4636. unsigned EltSize = dxilutil::GetLegacyCBufferFieldElementSize(
  4637. *fieldAnnotation, EltTy, dxilTypeSys);
  4638. // Decide the nested array size.
  4639. unsigned nestedArraySize = 1;
  4640. Type *EltTy = AT->getArrayElementType();
  4641. // support multi level of array
  4642. while (EltTy->isArrayTy()) {
  4643. ArrayType *EltAT = cast<ArrayType>(EltTy);
  4644. nestedArraySize *= EltAT->getNumElements();
  4645. EltTy = EltAT->getElementType();
  4646. }
  4647. // Align to 4 * 4 bytes.
  4648. unsigned alignedSize = (EltSize + 15) & 0xfffffff0;
  4649. size = nestedArraySize * alignedSize;
  4650. } else {
  4651. size = DL.getTypeAllocSize(EltTy);
  4652. }
  4653. }
  4654. // Skip 0 idx.
  4655. if (bImmIdx && immIdx == 0)
  4656. continue;
  4657. // Align to 4 * 4 bytes.
  4658. size = (size + 15) & 0xfffffff0;
  4659. // Take this as array idxing.
  4660. if (bImmIdx) {
  4661. unsigned tempOffset = size * immIdx;
  4662. unsigned idxInc = tempOffset >> 4;
  4663. legacyIndex = Builder.CreateAdd(legacyIndex, hlslOP->GetU32Const(idxInc));
  4664. } else {
  4665. Value *tempOffset = Builder.CreateMul(idx, hlslOP->GetU32Const(size));
  4666. Value *idxInc = Builder.CreateLShr(tempOffset, 4);
  4667. legacyIndex = Builder.CreateAdd(legacyIndex, idxInc);
  4668. }
  4669. // Array always start from x channel.
  4670. channel = 0;
  4671. } else if (GEPIt->isStructTy()) {
  4672. StructType *ST = cast<StructType>(*GEPIt);
  4673. DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST);
  4674. fieldAnnotation = &annotation->GetFieldAnnotation(immIdx);
  4675. unsigned structOffset = fieldAnnotation->GetCBufferOffset() >>2;
  4676. channel += structOffset;
  4677. unsigned idxInc = channel >> 2;
  4678. channel = channel & 3;
  4679. if (idxInc)
  4680. legacyIndex = Builder.CreateAdd(legacyIndex, hlslOP->GetU32Const(idxInc));
  4681. } else if (GEPIt->isArrayTy()) {
  4682. DXASSERT(fieldAnnotation != nullptr, "must a field");
  4683. unsigned EltSize = dxilutil::GetLegacyCBufferFieldElementSize(
  4684. *fieldAnnotation, *GEPIt, dxilTypeSys);
  4685. // Decide the nested array size.
  4686. unsigned nestedArraySize = 1;
  4687. Type *EltTy = GEPIt->getArrayElementType();
  4688. // support multi level of array
  4689. while (EltTy->isArrayTy()) {
  4690. ArrayType *EltAT = cast<ArrayType>(EltTy);
  4691. nestedArraySize *= EltAT->getNumElements();
  4692. EltTy = EltAT->getElementType();
  4693. }
  4694. // Align to 4 * 4 bytes.
  4695. unsigned alignedSize = (EltSize + 15) & 0xfffffff0;
  4696. unsigned size = nestedArraySize * alignedSize;
  4697. if (bImmIdx) {
  4698. unsigned tempOffset = size * immIdx;
  4699. unsigned idxInc = tempOffset >> 4;
  4700. legacyIndex = Builder.CreateAdd(legacyIndex, hlslOP->GetU32Const(idxInc));
  4701. } else {
  4702. Value *tempOffset = Builder.CreateMul(idx, hlslOP->GetU32Const(size));
  4703. Value *idxInc = Builder.CreateLShr(tempOffset, 4);
  4704. legacyIndex = Builder.CreateAdd(legacyIndex, idxInc);
  4705. }
  4706. // Array always start from x channel.
  4707. channel = 0;
  4708. } else if (GEPIt->isVectorTy()) {
  4709. unsigned size = DL.getTypeAllocSize(GEPIt->getVectorElementType());
  4710. // Indexing on vector.
  4711. if (bImmIdx) {
  4712. unsigned tempOffset = size * immIdx;
  4713. unsigned channelInc = tempOffset >> 2;
  4714. DXASSERT((channel + channelInc)<=4, "vector should not cross cb register");
  4715. channel += channelInc;
  4716. if (channel == 4) {
  4717. // Get to another row.
  4718. // Update index and channel.
  4719. channel = 0;
  4720. legacyIndex = Builder.CreateAdd(legacyIndex, Builder.getInt32(1));
  4721. }
  4722. } else {
  4723. Type *EltTy = GEPIt->getVectorElementType();
  4724. // Load the whole register.
  4725. Value *newLd = GenerateCBLoadLegacy(handle, legacyIndex,
  4726. /*channelOffset*/ 0, EltTy,
  4727. /*vecSize*/ 4, hlslOP, Builder);
  4728. // Copy to array.
  4729. IRBuilder<> AllocaBuilder(GEP->getParent()->getParent()->getEntryBlock().getFirstInsertionPt());
  4730. Value *tempArray = AllocaBuilder.CreateAlloca(ArrayType::get(EltTy, 4));
  4731. Value *zeroIdx = hlslOP->GetU32Const(0);
  4732. for (unsigned i = 0; i < 4; i++) {
  4733. Value *Elt = Builder.CreateExtractElement(newLd, i);
  4734. Value *EltGEP = Builder.CreateInBoundsGEP(tempArray, {zeroIdx, hlslOP->GetU32Const(i)});
  4735. Builder.CreateStore(Elt, EltGEP);
  4736. }
  4737. // Make sure this is the end of GEP.
  4738. gep_type_iterator temp = GEPIt;
  4739. temp++;
  4740. DXASSERT(temp == E, "scalar type must be the last");
  4741. // Replace the GEP with array GEP.
  4742. Value *ArrayGEP = Builder.CreateInBoundsGEP(tempArray, {zeroIdx, idx});
  4743. GEP->replaceAllUsesWith(ArrayGEP);
  4744. return;
  4745. }
  4746. } else {
  4747. gep_type_iterator temp = GEPIt;
  4748. temp++;
  4749. DXASSERT(temp == E, "scalar type must be the last");
  4750. }
  4751. }
  4752. for (auto U = GEP->user_begin(); U != GEP->user_end();) {
  4753. Instruction *user = cast<Instruction>(*(U++));
  4754. TranslateCBAddressUserLegacy(user, handle, legacyIndex, channel, hlslOP, fieldAnnotation,
  4755. dxilTypeSys, DL, pObjHelper);
  4756. }
  4757. }
  4758. void TranslateCBOperationsLegacy(Value *handle, Value *ptr, OP *hlslOP,
  4759. DxilTypeSystem &dxilTypeSys,
  4760. const DataLayout &DL,
  4761. HLObjectOperationLowerHelper *pObjHelper) {
  4762. auto User = ptr->user_begin();
  4763. auto UserE = ptr->user_end();
  4764. Value *zeroIdx = hlslOP->GetU32Const(0);
  4765. for (; User != UserE;) {
  4766. // Must be Instruction.
  4767. Instruction *I = cast<Instruction>(*(User++));
  4768. TranslateCBAddressUserLegacy(
  4769. I, handle, zeroIdx, /*channelOffset*/ 0, hlslOP,
  4770. /*prevFieldAnnotation*/ nullptr, dxilTypeSys, DL, pObjHelper);
  4771. }
  4772. }
  4773. }
  4774. // Structured buffer.
  4775. namespace {
  4776. // Calculate offset.
  4777. Value *GEPIdxToOffset(GetElementPtrInst *GEP, IRBuilder<> &Builder,
  4778. hlsl::OP *OP, const DataLayout &DL) {
  4779. SmallVector<Value *, 8> Indices(GEP->idx_begin(), GEP->idx_end());
  4780. Value *addr = nullptr;
  4781. // update offset
  4782. if (GEP->hasAllConstantIndices()) {
  4783. unsigned gepOffset =
  4784. DL.getIndexedOffset(GEP->getPointerOperandType(), Indices);
  4785. addr = OP->GetU32Const(gepOffset);
  4786. } else {
  4787. Value *offset = OP->GetU32Const(0);
  4788. gep_type_iterator GEPIt = gep_type_begin(GEP), E = gep_type_end(GEP);
  4789. for (; GEPIt != E; GEPIt++) {
  4790. Value *idx = GEPIt.getOperand();
  4791. unsigned immIdx = 0;
  4792. if (llvm::Constant *constIdx = dyn_cast<llvm::Constant>(idx)) {
  4793. immIdx = constIdx->getUniqueInteger().getLimitedValue();
  4794. if (immIdx == 0) {
  4795. continue;
  4796. }
  4797. }
  4798. if (GEPIt->isPointerTy()) {
  4799. unsigned size = DL.getTypeAllocSize(GEPIt->getPointerElementType());
  4800. if (immIdx) {
  4801. unsigned tempOffset = size * immIdx;
  4802. offset = Builder.CreateAdd(offset, OP->GetU32Const(tempOffset));
  4803. } else {
  4804. Value *tempOffset = Builder.CreateMul(idx, OP->GetU32Const(size));
  4805. offset = Builder.CreateAdd(offset, tempOffset);
  4806. }
  4807. } else if (GEPIt->isStructTy()) {
  4808. unsigned structOffset = 0;
  4809. for (unsigned i = 0; i < immIdx; i++) {
  4810. structOffset += DL.getTypeAllocSize(GEPIt->getStructElementType(i));
  4811. }
  4812. offset = Builder.CreateAdd(offset, OP->GetU32Const(structOffset));
  4813. } else if (GEPIt->isArrayTy()) {
  4814. unsigned size = DL.getTypeAllocSize(GEPIt->getArrayElementType());
  4815. if (immIdx) {
  4816. unsigned tempOffset = size * immIdx;
  4817. offset = Builder.CreateAdd(offset, OP->GetU32Const(tempOffset));
  4818. } else {
  4819. Value *tempOffset = Builder.CreateMul(idx, OP->GetU32Const(size));
  4820. offset = Builder.CreateAdd(offset, tempOffset);
  4821. }
  4822. } else if (GEPIt->isVectorTy()) {
  4823. unsigned size = DL.getTypeAllocSize(GEPIt->getVectorElementType());
  4824. if (immIdx) {
  4825. unsigned tempOffset = size * immIdx;
  4826. offset = Builder.CreateAdd(offset, OP->GetU32Const(tempOffset));
  4827. } else {
  4828. Value *tempOffset = Builder.CreateMul(idx, OP->GetU32Const(size));
  4829. offset = Builder.CreateAdd(offset, tempOffset);
  4830. }
  4831. } else {
  4832. gep_type_iterator temp = GEPIt;
  4833. temp++;
  4834. DXASSERT(temp == E, "scalar type must be the last");
  4835. }
  4836. };
  4837. addr = offset;
  4838. }
  4839. // TODO: x4 for byte address
  4840. return addr;
  4841. }
  4842. void GenerateStructBufLd(Value *handle, Value *bufIdx, Value *offset,
  4843. Value *status, Type *EltTy,
  4844. MutableArrayRef<Value *> resultElts, hlsl::OP *OP,
  4845. IRBuilder<> &Builder) {
  4846. OP::OpCode opcode = OP::OpCode::BufferLoad;
  4847. DXASSERT(resultElts.size() <= 4,
  4848. "buffer load cannot load more than 4 values");
  4849. Value *Args[] = {OP->GetU32Const((unsigned)opcode), handle, bufIdx, offset};
  4850. Type *i64Ty = Builder.getInt64Ty();
  4851. Type *doubleTy = Builder.getDoubleTy();
  4852. bool is64 = EltTy == i64Ty || EltTy == doubleTy;
  4853. if (!is64) {
  4854. Function *dxilF = OP->GetOpFunc(opcode, EltTy);
  4855. Value *Ld = Builder.CreateCall(dxilF, Args, OP::GetOpCodeName(opcode));
  4856. for (unsigned i = 0; i < resultElts.size(); i++) {
  4857. resultElts[i] = Builder.CreateExtractValue(Ld, i);
  4858. }
  4859. // status
  4860. UpdateStatus(Ld, status, Builder);
  4861. return;
  4862. } else {
  4863. // 64 bit.
  4864. Function *dxilF = OP->GetOpFunc(opcode, Builder.getInt32Ty());
  4865. Value *Ld = Builder.CreateCall(dxilF, Args, OP::GetOpCodeName(opcode));
  4866. Value *resultElts32[8];
  4867. unsigned size = resultElts.size();
  4868. unsigned eltBase = 0;
  4869. for (unsigned i = 0; i < size; i++) {
  4870. if (i == 2) {
  4871. // Update offset 4 by 4 bytes.
  4872. Args[DXIL::OperandIndex::kBufferLoadCoord1OpIdx] =
  4873. Builder.CreateAdd(offset, Builder.getInt32(4 * 4));
  4874. Ld = Builder.CreateCall(dxilF, Args, OP::GetOpCodeName(opcode));
  4875. eltBase = 4;
  4876. }
  4877. unsigned resBase = 2 * i;
  4878. resultElts32[resBase] = Builder.CreateExtractValue(Ld, resBase - eltBase);
  4879. resultElts32[resBase + 1] =
  4880. Builder.CreateExtractValue(Ld, resBase + 1 - eltBase);
  4881. }
  4882. Make64bitResultForLoad(EltTy, resultElts32, size, resultElts, OP, Builder);
  4883. // status
  4884. UpdateStatus(Ld, status, Builder);
  4885. return;
  4886. }
  4887. }
  4888. void GenerateStructBufSt(Value *handle, Value *bufIdx, Value *offset,
  4889. Type *EltTy, hlsl::OP *OP, IRBuilder<> &Builder,
  4890. ArrayRef<Value *> vals, uint8_t mask) {
  4891. OP::OpCode opcode = OP::OpCode::BufferStore;
  4892. DXASSERT(vals.size() == 4, "buffer store need 4 values");
  4893. Type *i64Ty = Builder.getInt64Ty();
  4894. Type *doubleTy = Builder.getDoubleTy();
  4895. bool is64 = EltTy == i64Ty || EltTy == doubleTy;
  4896. if (!is64) {
  4897. Value *Args[] = {OP->GetU32Const((unsigned)opcode),
  4898. handle,
  4899. bufIdx,
  4900. offset,
  4901. vals[0],
  4902. vals[1],
  4903. vals[2],
  4904. vals[3],
  4905. OP->GetU8Const(mask)};
  4906. Function *dxilF = OP->GetOpFunc(opcode, EltTy);
  4907. Builder.CreateCall(dxilF, Args);
  4908. } else {
  4909. Type *i32Ty = Builder.getInt32Ty();
  4910. Function *dxilF = OP->GetOpFunc(opcode, i32Ty);
  4911. Value *undefI32 = UndefValue::get(i32Ty);
  4912. Value *vals32[8] = {undefI32, undefI32, undefI32, undefI32,
  4913. undefI32, undefI32, undefI32, undefI32};
  4914. unsigned maskLo = 0;
  4915. unsigned maskHi = 0;
  4916. unsigned size = 0;
  4917. switch (mask) {
  4918. case 1:
  4919. maskLo = 3;
  4920. size = 1;
  4921. break;
  4922. case 3:
  4923. maskLo = 15;
  4924. size = 2;
  4925. break;
  4926. case 7:
  4927. maskLo = 15;
  4928. maskHi = 3;
  4929. size = 3;
  4930. break;
  4931. case 15:
  4932. maskLo = 15;
  4933. maskHi = 15;
  4934. size = 4;
  4935. break;
  4936. default:
  4937. DXASSERT(0, "invalid mask");
  4938. }
  4939. Split64bitValForStore(EltTy, vals, size, vals32, OP, Builder);
  4940. Value *Args[] = {OP->GetU32Const((unsigned)opcode),
  4941. handle,
  4942. bufIdx,
  4943. offset,
  4944. vals32[0],
  4945. vals32[1],
  4946. vals32[2],
  4947. vals32[3],
  4948. OP->GetU8Const(maskLo)};
  4949. Builder.CreateCall(dxilF, Args);
  4950. if (maskHi) {
  4951. // Update offset 4 by 4 bytes.
  4952. offset = Builder.CreateAdd(offset, Builder.getInt32(4 * 4));
  4953. Value *Args[] = {OP->GetU32Const((unsigned)opcode),
  4954. handle,
  4955. bufIdx,
  4956. offset,
  4957. vals32[4],
  4958. vals32[5],
  4959. vals32[6],
  4960. vals32[7],
  4961. OP->GetU8Const(maskHi)};
  4962. Builder.CreateCall(dxilF, Args);
  4963. }
  4964. }
  4965. }
  4966. Value *TranslateStructBufMatLd(Type *matType, IRBuilder<> &Builder,
  4967. Value *handle, hlsl::OP *OP, Value *status,
  4968. Value *bufIdx, Value *baseOffset,
  4969. bool colMajor) {
  4970. unsigned col, row;
  4971. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  4972. Value *offset = baseOffset;
  4973. if (baseOffset == nullptr)
  4974. offset = OP->GetU32Const(0);
  4975. unsigned matSize = col * row;
  4976. std::vector<Value *> elts(matSize);
  4977. unsigned rest = (matSize % 4);
  4978. if (rest) {
  4979. Value *ResultElts[4];
  4980. GenerateStructBufLd(handle, bufIdx, offset, status, EltTy, ResultElts, OP, Builder);
  4981. for (unsigned i = 0; i < rest; i++)
  4982. elts[i] = ResultElts[i];
  4983. offset = Builder.CreateAdd(offset, OP->GetU32Const(4 * rest));
  4984. }
  4985. for (unsigned i = rest; i < matSize; i += 4) {
  4986. Value *ResultElts[4];
  4987. GenerateStructBufLd(handle, bufIdx, offset, status, EltTy, ResultElts, OP, Builder);
  4988. elts[i] = ResultElts[0];
  4989. elts[i + 1] = ResultElts[1];
  4990. elts[i + 2] = ResultElts[2];
  4991. elts[i + 3] = ResultElts[3];
  4992. // Update offset by 4*4bytes.
  4993. offset = Builder.CreateAdd(offset, OP->GetU32Const(4 * 4));
  4994. }
  4995. return HLMatrixLower::BuildVector(EltTy, col * row, elts, Builder);
  4996. }
  4997. void TranslateStructBufMatSt(Type *matType, IRBuilder<> &Builder, Value *handle,
  4998. hlsl::OP *OP, Value *bufIdx, Value *baseOffset,
  4999. Value *val, bool colMajor) {
  5000. unsigned col, row;
  5001. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  5002. Value *offset = baseOffset;
  5003. if (baseOffset == nullptr)
  5004. offset = OP->GetU32Const(0);
  5005. unsigned matSize = col * row;
  5006. Value *undefElt = UndefValue::get(EltTy);
  5007. unsigned storeSize = matSize;
  5008. if (matSize % 4) {
  5009. storeSize = matSize + 4 - (matSize & 3);
  5010. }
  5011. std::vector<Value *> elts(storeSize, undefElt);
  5012. if (colMajor) {
  5013. for (unsigned i = 0; i < matSize; i++)
  5014. elts[i] = Builder.CreateExtractElement(val, i);
  5015. } else {
  5016. for (unsigned r = 0; r < row; r++)
  5017. for (unsigned c = 0; c < col; c++) {
  5018. unsigned rowMajorIdx = r * col + c;
  5019. unsigned colMajorIdx = c * row + r;
  5020. elts[rowMajorIdx] = Builder.CreateExtractElement(val, colMajorIdx);
  5021. }
  5022. }
  5023. for (unsigned i = 0; i < matSize; i += 4) {
  5024. uint8_t mask = 0;
  5025. for (unsigned j = 0; j < 4 && (i+j) < matSize; j++) {
  5026. if (elts[i+j] != undefElt)
  5027. mask |= (1<<j);
  5028. }
  5029. GenerateStructBufSt(handle, bufIdx, offset, EltTy, OP, Builder,
  5030. {elts[i], elts[i + 1], elts[i + 2], elts[i + 3]}, mask);
  5031. // Update offset by 4*4bytes.
  5032. offset = Builder.CreateAdd(offset, OP->GetU32Const(4 * 4));
  5033. }
  5034. }
  5035. void TranslateStructBufMatLdSt(CallInst *CI, Value *handle, hlsl::OP *OP,
  5036. Value *status, Value *bufIdx,
  5037. Value *baseOffset) {
  5038. IRBuilder<> Builder(CI);
  5039. HLOpcodeGroup group = hlsl::GetHLOpcodeGroupByName(CI->getCalledFunction());
  5040. unsigned opcode = GetHLOpcode(CI);
  5041. DXASSERT_LOCALVAR(group, group == HLOpcodeGroup::HLMatLoadStore,
  5042. "only translate matrix loadStore here.");
  5043. HLMatLoadStoreOpcode matOp = static_cast<HLMatLoadStoreOpcode>(opcode);
  5044. switch (matOp) {
  5045. case HLMatLoadStoreOpcode::ColMatLoad: {
  5046. Value *ptr = CI->getArgOperand(HLOperandIndex::kMatLoadPtrOpIdx);
  5047. Value *NewLd = TranslateStructBufMatLd(
  5048. ptr->getType()->getPointerElementType(), Builder, handle, OP, status,
  5049. bufIdx, baseOffset, /*colMajor*/ true);
  5050. CI->replaceAllUsesWith(NewLd);
  5051. } break;
  5052. case HLMatLoadStoreOpcode::RowMatLoad: {
  5053. Value *ptr = CI->getArgOperand(HLOperandIndex::kMatLoadPtrOpIdx);
  5054. Value *NewLd = TranslateStructBufMatLd(
  5055. ptr->getType()->getPointerElementType(), Builder, handle, OP, status,
  5056. bufIdx, baseOffset, /*colMajor*/ false);
  5057. CI->replaceAllUsesWith(NewLd);
  5058. } break;
  5059. case HLMatLoadStoreOpcode::ColMatStore: {
  5060. Value *ptr = CI->getArgOperand(HLOperandIndex::kMatStoreDstPtrOpIdx);
  5061. Value *val = CI->getArgOperand(HLOperandIndex::kMatStoreValOpIdx);
  5062. TranslateStructBufMatSt(ptr->getType()->getPointerElementType(), Builder,
  5063. handle, OP, bufIdx, baseOffset, val,
  5064. /*colMajor*/ true);
  5065. } break;
  5066. case HLMatLoadStoreOpcode::RowMatStore: {
  5067. Value *ptr = CI->getArgOperand(HLOperandIndex::kMatStoreDstPtrOpIdx);
  5068. Value *val = CI->getArgOperand(HLOperandIndex::kMatStoreValOpIdx);
  5069. TranslateStructBufMatSt(ptr->getType()->getPointerElementType(), Builder,
  5070. handle, OP, bufIdx, baseOffset, val,
  5071. /*colMajor*/ false);
  5072. } break;
  5073. }
  5074. CI->eraseFromParent();
  5075. }
  5076. void TranslateStructBufSubscriptUser(Instruction *user, Value *handle,
  5077. Value *bufIdx, Value *baseOffset,
  5078. Value *status, hlsl::OP *OP, const DataLayout &DL);
  5079. void TranslateStructBufMatSubscript(CallInst *CI, Value *handle,
  5080. hlsl::OP *hlslOP, Value *bufIdx,
  5081. Value *baseOffset, Value *status,
  5082. const DataLayout &DL) {
  5083. Value *zeroIdx = hlslOP->GetU32Const(0);
  5084. if (baseOffset == nullptr)
  5085. baseOffset = zeroIdx;
  5086. unsigned opcode = GetHLOpcode(CI);
  5087. IRBuilder<> subBuilder(CI);
  5088. HLSubscriptOpcode subOp = static_cast<HLSubscriptOpcode>(opcode);
  5089. Value *basePtr = CI->getArgOperand(HLOperandIndex::kMatSubscriptMatOpIdx);
  5090. Type *matType = basePtr->getType()->getPointerElementType();
  5091. unsigned col, row;
  5092. Type *EltTy = HLMatrixLower::GetMatrixInfo(matType, col, row);
  5093. Value *EltByteSize = ConstantInt::get(
  5094. baseOffset->getType(), GetEltTypeByteSizeForConstBuf(EltTy, DL));
  5095. Value *idx = CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx);
  5096. Type *resultType = CI->getType()->getPointerElementType();
  5097. unsigned resultSize = 1;
  5098. if (resultType->isVectorTy())
  5099. resultSize = resultType->getVectorNumElements();
  5100. DXASSERT(resultSize <= 16, "up to 4x4 elements in vector or matrix");
  5101. _Analysis_assume_(resultSize <= 16);
  5102. std::vector<Value *> idxList(resultSize);
  5103. switch (subOp) {
  5104. case HLSubscriptOpcode::ColMatSubscript:
  5105. case HLSubscriptOpcode::RowMatSubscript: {
  5106. for (unsigned i = 0; i < resultSize; i++) {
  5107. Value *offset =
  5108. CI->getArgOperand(HLOperandIndex::kMatSubscriptSubOpIdx + i);
  5109. offset = subBuilder.CreateMul(offset, EltByteSize);
  5110. idxList[i] = subBuilder.CreateAdd(baseOffset, offset);
  5111. }
  5112. } break;
  5113. case HLSubscriptOpcode::RowMatElement:
  5114. case HLSubscriptOpcode::ColMatElement: {
  5115. Constant *EltIdxs = cast<Constant>(idx);
  5116. for (unsigned i = 0; i < resultSize; i++) {
  5117. Value *offset =
  5118. subBuilder.CreateMul(EltIdxs->getAggregateElement(i), EltByteSize);
  5119. idxList[i] = subBuilder.CreateAdd(baseOffset, offset);
  5120. }
  5121. } break;
  5122. default:
  5123. DXASSERT(0, "invalid operation on const buffer");
  5124. break;
  5125. }
  5126. Value *undefElt = UndefValue::get(EltTy);
  5127. for (auto U = CI->user_begin(); U != CI->user_end();) {
  5128. Value *subsUser = *(U++);
  5129. if (resultSize == 1) {
  5130. TranslateStructBufSubscriptUser(cast<Instruction>(subsUser), handle,
  5131. bufIdx, idxList[0], status, hlslOP, DL);
  5132. continue;
  5133. }
  5134. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(subsUser)) {
  5135. Value *GEPOffset =
  5136. HLMatrixLower::LowerGEPOnMatIndexListToIndex(GEP, idxList);
  5137. for (auto gepU = GEP->user_begin(); gepU != GEP->user_end();) {
  5138. Instruction *gepUserInst = cast<Instruction>(*(gepU++));
  5139. TranslateStructBufSubscriptUser(gepUserInst, handle, bufIdx, GEPOffset,
  5140. status, hlslOP, DL);
  5141. }
  5142. GEP->eraseFromParent();
  5143. } else if (StoreInst *stUser = dyn_cast<StoreInst>(subsUser)) {
  5144. IRBuilder<> stBuilder(stUser);
  5145. Value *Val = stUser->getValueOperand();
  5146. if (Val->getType()->isVectorTy()) {
  5147. for (unsigned i = 0; i < resultSize; i++) {
  5148. Value *EltVal = stBuilder.CreateExtractElement(Val, i);
  5149. uint8_t mask = DXIL::kCompMask_X;
  5150. GenerateStructBufSt(handle, bufIdx, idxList[i], EltTy, hlslOP,
  5151. stBuilder, {EltVal, undefElt, undefElt, undefElt},
  5152. mask);
  5153. }
  5154. } else {
  5155. uint8_t mask = DXIL::kCompMask_X;
  5156. GenerateStructBufSt(handle, bufIdx, idxList[0], EltTy, hlslOP,
  5157. stBuilder, {Val, undefElt, undefElt, undefElt},
  5158. mask);
  5159. }
  5160. stUser->eraseFromParent();
  5161. } else {
  5162. // Must be load here.
  5163. LoadInst *ldUser = cast<LoadInst>(subsUser);
  5164. IRBuilder<> ldBuilder(ldUser);
  5165. Value *ldData = UndefValue::get(resultType);
  5166. if (resultType->isVectorTy()) {
  5167. for (unsigned i = 0; i < resultSize; i++) {
  5168. Value *ResultElt;
  5169. GenerateStructBufLd(handle, bufIdx, idxList[i],
  5170. /*status*/ nullptr, EltTy, ResultElt, hlslOP,
  5171. ldBuilder);
  5172. ldData = ldBuilder.CreateInsertElement(ldData, ResultElt, i);
  5173. }
  5174. } else {
  5175. GenerateStructBufLd(handle, bufIdx, idxList[0], /*status*/ nullptr,
  5176. EltTy, ldData, hlslOP, ldBuilder);
  5177. }
  5178. ldUser->replaceAllUsesWith(ldData);
  5179. ldUser->eraseFromParent();
  5180. }
  5181. }
  5182. CI->eraseFromParent();
  5183. }
  5184. void TranslateStructBufSubscriptUser(Instruction *user, Value *handle,
  5185. Value *bufIdx, Value *baseOffset,
  5186. Value *status, hlsl::OP *OP, const DataLayout &DL) {
  5187. IRBuilder<> Builder(user);
  5188. if (CallInst *userCall = dyn_cast<CallInst>(user)) {
  5189. HLOpcodeGroup group =
  5190. hlsl::GetHLOpcodeGroupByName(userCall->getCalledFunction());
  5191. unsigned opcode = GetHLOpcode(userCall);
  5192. // For case element type of structure buffer is not structure type.
  5193. if (baseOffset == nullptr)
  5194. baseOffset = OP->GetU32Const(0);
  5195. if (group == HLOpcodeGroup::HLIntrinsic) {
  5196. IntrinsicOp IOP = static_cast<IntrinsicOp>(opcode);
  5197. switch (IOP) {
  5198. case IntrinsicOp::MOP_Load: {
  5199. if (userCall->getType()->isPointerTy()) {
  5200. // Struct will return pointers which like []
  5201. } else {
  5202. // Use builtin types on structuredBuffer.
  5203. }
  5204. DXASSERT(0, "not implement yet");
  5205. } break;
  5206. case IntrinsicOp::IOP_InterlockedAdd: {
  5207. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5208. baseOffset);
  5209. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Add,
  5210. Builder, OP);
  5211. } break;
  5212. case IntrinsicOp::IOP_InterlockedAnd: {
  5213. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5214. baseOffset);
  5215. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::And,
  5216. Builder, OP);
  5217. } break;
  5218. case IntrinsicOp::IOP_InterlockedExchange: {
  5219. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5220. baseOffset);
  5221. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Exchange,
  5222. Builder, OP);
  5223. } break;
  5224. case IntrinsicOp::IOP_InterlockedMax: {
  5225. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5226. baseOffset);
  5227. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::IMax,
  5228. Builder, OP);
  5229. } break;
  5230. case IntrinsicOp::IOP_InterlockedMin: {
  5231. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5232. baseOffset);
  5233. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::IMin,
  5234. Builder, OP);
  5235. } break;
  5236. case IntrinsicOp::IOP_InterlockedUMax: {
  5237. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5238. baseOffset);
  5239. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::UMax,
  5240. Builder, OP);
  5241. } break;
  5242. case IntrinsicOp::IOP_InterlockedUMin: {
  5243. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5244. baseOffset);
  5245. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::UMin,
  5246. Builder, OP);
  5247. } break;
  5248. case IntrinsicOp::IOP_InterlockedOr: {
  5249. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5250. baseOffset);
  5251. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Or,
  5252. Builder, OP);
  5253. } break;
  5254. case IntrinsicOp::IOP_InterlockedXor: {
  5255. AtomicHelper helper(userCall, DXIL::OpCode::AtomicBinOp, handle, bufIdx,
  5256. baseOffset);
  5257. TranslateAtomicBinaryOperation(helper, DXIL::AtomicBinOpCode::Xor,
  5258. Builder, OP);
  5259. } break;
  5260. case IntrinsicOp::IOP_InterlockedCompareStore:
  5261. case IntrinsicOp::IOP_InterlockedCompareExchange: {
  5262. AtomicHelper helper(userCall, DXIL::OpCode::AtomicCompareExchange,
  5263. handle, bufIdx, baseOffset);
  5264. TranslateAtomicCmpXChg(helper, Builder, OP);
  5265. } break;
  5266. default:
  5267. DXASSERT(0, "invalid opcode");
  5268. break;
  5269. }
  5270. userCall->eraseFromParent();
  5271. } else if (group == HLOpcodeGroup::HLMatLoadStore)
  5272. // TODO: support 64 bit.
  5273. TranslateStructBufMatLdSt(userCall, handle, OP, status, bufIdx,
  5274. baseOffset);
  5275. else if (group == HLOpcodeGroup::HLSubscript) {
  5276. TranslateStructBufMatSubscript(userCall, handle, OP, bufIdx, baseOffset, status, DL);
  5277. }
  5278. } else if (isa<LoadInst>(user) || isa<StoreInst>(user)) {
  5279. LoadInst *ldInst = dyn_cast<LoadInst>(user);
  5280. StoreInst *stInst = dyn_cast<StoreInst>(user);
  5281. Type *Ty = isa<LoadInst>(user) ? ldInst->getType()
  5282. : stInst->getValueOperand()->getType();
  5283. Type *pOverloadTy = Ty->getScalarType();
  5284. Value *offset = baseOffset;
  5285. if (baseOffset == nullptr)
  5286. offset = OP->GetU32Const(0);
  5287. unsigned arraySize = 1;
  5288. Value *eltSize = nullptr;
  5289. if (pOverloadTy->isArrayTy()) {
  5290. arraySize = pOverloadTy->getArrayNumElements();
  5291. eltSize = OP->GetU32Const(
  5292. DL.getTypeAllocSize(pOverloadTy->getArrayElementType()));
  5293. pOverloadTy = pOverloadTy->getArrayElementType()->getScalarType();
  5294. }
  5295. if (ldInst) {
  5296. auto LdElement = [&](Value *offset, IRBuilder<> &Builder) -> Value * {
  5297. Value *ResultElts[4];
  5298. GenerateStructBufLd(handle, bufIdx, offset, status, pOverloadTy,
  5299. ResultElts, OP, Builder);
  5300. return ScalarizeElements(Ty, ResultElts, Builder);
  5301. };
  5302. Value *newLd = LdElement(offset, Builder);
  5303. if (arraySize > 1) {
  5304. newLd =
  5305. Builder.CreateInsertValue(UndefValue::get(Ty), newLd, (uint64_t)0);
  5306. for (unsigned i = 1; i < arraySize; i++) {
  5307. offset = Builder.CreateAdd(offset, eltSize);
  5308. Value *eltLd = LdElement(offset, Builder);
  5309. newLd = Builder.CreateInsertValue(newLd, eltLd, i);
  5310. }
  5311. }
  5312. ldInst->replaceAllUsesWith(newLd);
  5313. } else {
  5314. Value *val = stInst->getValueOperand();
  5315. auto StElement = [&](Value *offset, Value *val, IRBuilder<> &Builder) {
  5316. Value *undefVal = llvm::UndefValue::get(pOverloadTy);
  5317. Value *vals[] = {undefVal, undefVal, undefVal, undefVal};
  5318. uint8_t mask = 0;
  5319. if (Ty->isVectorTy()) {
  5320. unsigned vectorNumElements = Ty->getVectorNumElements();
  5321. DXASSERT(vectorNumElements <= 4, "up to 4 elements in vector");
  5322. _Analysis_assume_(vectorNumElements <= 4);
  5323. for (unsigned i = 0; i < vectorNumElements; i++) {
  5324. vals[i] = Builder.CreateExtractElement(val, i);
  5325. mask |= (1<<i);
  5326. }
  5327. } else {
  5328. vals[0] = val;
  5329. mask = DXIL::kCompMask_X;
  5330. }
  5331. GenerateStructBufSt(handle, bufIdx, offset, pOverloadTy, OP, Builder,
  5332. vals, mask);
  5333. };
  5334. if (arraySize > 1)
  5335. val = Builder.CreateExtractValue(val, 0);
  5336. StElement(offset, val, Builder);
  5337. if (arraySize > 1) {
  5338. val = stInst->getValueOperand();
  5339. for (unsigned i = 1; i < arraySize; i++) {
  5340. offset = Builder.CreateAdd(offset, eltSize);
  5341. Value *eltVal = Builder.CreateExtractValue(val, i);
  5342. StElement(offset, eltVal, Builder);
  5343. }
  5344. }
  5345. }
  5346. user->eraseFromParent();
  5347. } else {
  5348. // should only used by GEP
  5349. GetElementPtrInst *GEP = cast<GetElementPtrInst>(user);
  5350. Type *Ty = GEP->getType()->getPointerElementType();
  5351. Value *offset = GEPIdxToOffset(GEP, Builder, OP, DL);
  5352. DXASSERT_LOCALVAR(Ty, offset->getType() == Type::getInt32Ty(Ty->getContext()),
  5353. "else bitness is wrong");
  5354. if (baseOffset)
  5355. offset = Builder.CreateAdd(offset, baseOffset);
  5356. for (auto U = GEP->user_begin(); U != GEP->user_end();) {
  5357. Value *GEPUser = *(U++);
  5358. TranslateStructBufSubscriptUser(cast<Instruction>(GEPUser), handle,
  5359. bufIdx, offset, status, OP, DL);
  5360. }
  5361. // delete the inst
  5362. GEP->eraseFromParent();
  5363. }
  5364. }
  5365. void TranslateStructBufSubscript(CallInst *CI, Value *handle, Value *status,
  5366. hlsl::OP *OP, const DataLayout &DL) {
  5367. Value *bufIdx = CI->getArgOperand(HLOperandIndex::kSubscriptIndexOpIdx);
  5368. for (auto U = CI->user_begin(); U != CI->user_end();) {
  5369. Value *user = *(U++);
  5370. TranslateStructBufSubscriptUser(cast<Instruction>(user), handle, bufIdx,
  5371. /*baseOffset*/ nullptr, status, OP, DL);
  5372. }
  5373. }
  5374. }
  5375. // HLSubscript.
  5376. namespace {
  5377. Value *TranslateTypedBufLoad(CallInst *CI, DXIL::ResourceKind RK,
  5378. DXIL::ResourceClass RC, Value *handle,
  5379. LoadInst *ldInst, IRBuilder<> &Builder,
  5380. hlsl::OP *hlslOP, const DataLayout &DL) {
  5381. ResLoadHelper ldHelper(CI, RK, RC, handle, /*bForSubscript*/ true);
  5382. // Default sampleIdx for 2DMS textures.
  5383. if (RK == DxilResource::Kind::Texture2DMS ||
  5384. RK == DxilResource::Kind::Texture2DMSArray)
  5385. ldHelper.mipLevel = hlslOP->GetU32Const(0);
  5386. // use ldInst as retVal
  5387. ldHelper.retVal = ldInst;
  5388. TranslateLoad(ldHelper, RK, Builder, hlslOP, DL);
  5389. // delete the ld
  5390. ldInst->eraseFromParent();
  5391. return ldHelper.retVal;
  5392. }
  5393. Value *UpdateVectorElt(Value *VecVal, Value *EltVal, Value *EltIdx,
  5394. unsigned vectorSize, Instruction *InsertPt) {
  5395. IRBuilder<> Builder(InsertPt);
  5396. if (ConstantInt *CEltIdx = dyn_cast<ConstantInt>(EltIdx)) {
  5397. VecVal =
  5398. Builder.CreateInsertElement(VecVal, EltVal, CEltIdx->getLimitedValue());
  5399. } else {
  5400. BasicBlock *BB = InsertPt->getParent();
  5401. BasicBlock *EndBB = BB->splitBasicBlock(InsertPt);
  5402. TerminatorInst *TI = BB->getTerminator();
  5403. IRBuilder<> SwitchBuilder(TI);
  5404. LLVMContext &Ctx = InsertPt->getContext();
  5405. SwitchInst *Switch = SwitchBuilder.CreateSwitch(EltIdx, EndBB, vectorSize);
  5406. TI->eraseFromParent();
  5407. Function *F = EndBB->getParent();
  5408. IRBuilder<> endSwitchBuilder(EndBB->begin());
  5409. Type *Ty = VecVal->getType();
  5410. PHINode *VecPhi = endSwitchBuilder.CreatePHI(Ty, vectorSize + 1);
  5411. for (unsigned i = 0; i < vectorSize; i++) {
  5412. BasicBlock *CaseBB = BasicBlock::Create(Ctx, "case", F, EndBB);
  5413. Switch->addCase(SwitchBuilder.getInt32(i), CaseBB);
  5414. IRBuilder<> CaseBuilder(CaseBB);
  5415. Value *CaseVal = CaseBuilder.CreateInsertElement(VecVal, EltVal, i);
  5416. VecPhi->addIncoming(CaseVal, CaseBB);
  5417. CaseBuilder.CreateBr(EndBB);
  5418. }
  5419. VecPhi->addIncoming(VecVal, BB);
  5420. VecVal = VecPhi;
  5421. }
  5422. return VecVal;
  5423. }
  5424. void TranslateDefaultSubscript(CallInst *CI, HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  5425. auto U = CI->user_begin();
  5426. Value *ptr = CI->getArgOperand(HLOperandIndex::kSubscriptObjectOpIdx);
  5427. hlsl::OP *hlslOP = &helper.hlslOP;
  5428. // Resource ptr.
  5429. Value *handle = ptr;
  5430. DXIL::ResourceClass RC = pObjHelper->GetRC(handle);
  5431. DXIL::ResourceKind RK = pObjHelper->GetRK(handle);
  5432. Type *Ty = CI->getType()->getPointerElementType();
  5433. for (auto It = CI->user_begin(); It != CI->user_end(); ) {
  5434. User *user = *(It++);
  5435. Instruction *I = cast<Instruction>(user);
  5436. IRBuilder<> Builder(I);
  5437. if (LoadInst *ldInst = dyn_cast<LoadInst>(user)) {
  5438. TranslateTypedBufLoad(CI, RK, RC, handle, ldInst, Builder, hlslOP, helper.legacyDataLayout);
  5439. } else if (StoreInst *stInst = dyn_cast<StoreInst>(user)) {
  5440. Value *val = stInst->getValueOperand();
  5441. TranslateStore(RK, handle, val,
  5442. CI->getArgOperand(HLOperandIndex::kStoreOffsetOpIdx),
  5443. Builder, hlslOP);
  5444. // delete the st
  5445. stInst->eraseFromParent();
  5446. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(user)) {
  5447. // Must be vector type here.
  5448. unsigned vectorSize = Ty->getVectorNumElements();
  5449. DXASSERT(GEP->getNumIndices() == 2, "");
  5450. Use *GEPIdx = GEP->idx_begin();
  5451. GEPIdx++;
  5452. Value *EltIdx = *GEPIdx;
  5453. for (auto GEPIt = GEP->user_begin(); GEPIt != GEP->user_end();) {
  5454. User *GEPUser = *(GEPIt++);
  5455. if (StoreInst *SI = dyn_cast<StoreInst>(GEPUser)) {
  5456. IRBuilder<> StBuilder(SI);
  5457. // Generate Ld.
  5458. LoadInst *tmpLd = StBuilder.CreateLoad(CI);
  5459. Value *ldVal = TranslateTypedBufLoad(CI, RK, RC, handle, tmpLd, StBuilder,
  5460. hlslOP, helper.legacyDataLayout);
  5461. // Update vector.
  5462. ldVal = UpdateVectorElt(ldVal, SI->getValueOperand(), EltIdx,
  5463. vectorSize, SI);
  5464. // Generate St.
  5465. // Reset insert point, UpdateVectorElt may move SI to different block.
  5466. StBuilder.SetInsertPoint(SI);
  5467. TranslateStore(RK, handle, ldVal,
  5468. CI->getArgOperand(HLOperandIndex::kStoreOffsetOpIdx),
  5469. StBuilder, hlslOP);
  5470. SI->eraseFromParent();
  5471. continue;
  5472. }
  5473. if (!isa<CallInst>(GEPUser)) {
  5474. // Invalid operations.
  5475. Translated = false;
  5476. CI->getContext().emitError(GEP, "Invalid operation on typed buffer");
  5477. return;
  5478. }
  5479. CallInst *userCall = cast<CallInst>(GEPUser);
  5480. HLOpcodeGroup group =
  5481. hlsl::GetHLOpcodeGroupByName(userCall->getCalledFunction());
  5482. if (group != HLOpcodeGroup::HLIntrinsic) {
  5483. // Invalid operations.
  5484. Translated = false;
  5485. CI->getContext().emitError(userCall,
  5486. "Invalid operation on typed buffer");
  5487. return;
  5488. }
  5489. unsigned opcode = hlsl::GetHLOpcode(userCall);
  5490. IntrinsicOp IOP = static_cast<IntrinsicOp>(opcode);
  5491. switch (IOP) {
  5492. case IntrinsicOp::IOP_InterlockedAdd:
  5493. case IntrinsicOp::IOP_InterlockedAnd:
  5494. case IntrinsicOp::IOP_InterlockedExchange:
  5495. case IntrinsicOp::IOP_InterlockedMax:
  5496. case IntrinsicOp::IOP_InterlockedMin:
  5497. case IntrinsicOp::IOP_InterlockedUMax:
  5498. case IntrinsicOp::IOP_InterlockedUMin:
  5499. case IntrinsicOp::IOP_InterlockedOr:
  5500. case IntrinsicOp::IOP_InterlockedXor:
  5501. case IntrinsicOp::IOP_InterlockedCompareStore:
  5502. case IntrinsicOp::IOP_InterlockedCompareExchange: {
  5503. // Invalid operations.
  5504. Translated = false;
  5505. CI->getContext().emitError(
  5506. userCall, "Atomic operation on typed buffer is not supported");
  5507. return;
  5508. } break;
  5509. default:
  5510. // Invalid operations.
  5511. Translated = false;
  5512. CI->getContext().emitError(userCall,
  5513. "Invalid operation on typed buffer");
  5514. return;
  5515. break;
  5516. }
  5517. }
  5518. GEP->eraseFromParent();
  5519. } else {
  5520. CallInst *userCall = cast<CallInst>(user);
  5521. HLOpcodeGroup group =
  5522. hlsl::GetHLOpcodeGroupByName(userCall->getCalledFunction());
  5523. unsigned opcode = hlsl::GetHLOpcode(userCall);
  5524. if (group == HLOpcodeGroup::HLIntrinsic) {
  5525. IntrinsicOp IOP = static_cast<IntrinsicOp>(opcode);
  5526. if (RC == DXIL::ResourceClass::SRV) {
  5527. // Invalid operations.
  5528. Translated = false;
  5529. switch (IOP) {
  5530. case IntrinsicOp::IOP_InterlockedAdd:
  5531. case IntrinsicOp::IOP_InterlockedAnd:
  5532. case IntrinsicOp::IOP_InterlockedExchange:
  5533. case IntrinsicOp::IOP_InterlockedMax:
  5534. case IntrinsicOp::IOP_InterlockedMin:
  5535. case IntrinsicOp::IOP_InterlockedUMax:
  5536. case IntrinsicOp::IOP_InterlockedUMin:
  5537. case IntrinsicOp::IOP_InterlockedOr:
  5538. case IntrinsicOp::IOP_InterlockedXor:
  5539. case IntrinsicOp::IOP_InterlockedCompareStore:
  5540. case IntrinsicOp::IOP_InterlockedCompareExchange: {
  5541. CI->getContext().emitError(
  5542. userCall, "Atomic operation targets must be groupshared on UAV");
  5543. return;
  5544. } break;
  5545. default:
  5546. CI->getContext().emitError(userCall,
  5547. "Invalid operation on typed buffer");
  5548. return;
  5549. break;
  5550. }
  5551. }
  5552. switch (IOP) {
  5553. case IntrinsicOp::IOP_InterlockedAdd: {
  5554. ResLoadHelper helper(CI, RK, RC, handle);
  5555. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5556. helper.addr, /*offset*/ nullptr);
  5557. TranslateAtomicBinaryOperation(atomHelper, DXIL::AtomicBinOpCode::Add,
  5558. Builder, hlslOP);
  5559. } break;
  5560. case IntrinsicOp::IOP_InterlockedAnd: {
  5561. ResLoadHelper helper(CI, RK, RC, handle);
  5562. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5563. helper.addr, /*offset*/ nullptr);
  5564. TranslateAtomicBinaryOperation(atomHelper, DXIL::AtomicBinOpCode::And,
  5565. Builder, hlslOP);
  5566. } break;
  5567. case IntrinsicOp::IOP_InterlockedExchange: {
  5568. ResLoadHelper helper(CI, RK, RC, handle);
  5569. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5570. helper.addr, /*offset*/ nullptr);
  5571. TranslateAtomicBinaryOperation(
  5572. atomHelper, DXIL::AtomicBinOpCode::Exchange, Builder, hlslOP);
  5573. } break;
  5574. case IntrinsicOp::IOP_InterlockedMax: {
  5575. ResLoadHelper helper(CI, RK, RC, handle);
  5576. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5577. helper.addr, /*offset*/ nullptr);
  5578. TranslateAtomicBinaryOperation(
  5579. atomHelper, DXIL::AtomicBinOpCode::IMax, Builder, hlslOP);
  5580. } break;
  5581. case IntrinsicOp::IOP_InterlockedMin: {
  5582. ResLoadHelper helper(CI, RK, RC, handle);
  5583. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5584. helper.addr, /*offset*/ nullptr);
  5585. TranslateAtomicBinaryOperation(
  5586. atomHelper, DXIL::AtomicBinOpCode::IMin, Builder, hlslOP);
  5587. } break;
  5588. case IntrinsicOp::IOP_InterlockedUMax: {
  5589. ResLoadHelper helper(CI, RK, RC, handle);
  5590. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5591. helper.addr, /*offset*/ nullptr);
  5592. TranslateAtomicBinaryOperation(
  5593. atomHelper, DXIL::AtomicBinOpCode::UMax, Builder, hlslOP);
  5594. } break;
  5595. case IntrinsicOp::IOP_InterlockedUMin: {
  5596. ResLoadHelper helper(CI, RK, RC, handle);
  5597. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5598. helper.addr, /*offset*/ nullptr);
  5599. TranslateAtomicBinaryOperation(
  5600. atomHelper, DXIL::AtomicBinOpCode::UMin, Builder, hlslOP);
  5601. } break;
  5602. case IntrinsicOp::IOP_InterlockedOr: {
  5603. ResLoadHelper helper(CI, RK, RC, handle);
  5604. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5605. helper.addr, /*offset*/ nullptr);
  5606. TranslateAtomicBinaryOperation(atomHelper, DXIL::AtomicBinOpCode::Or,
  5607. Builder, hlslOP);
  5608. } break;
  5609. case IntrinsicOp::IOP_InterlockedXor: {
  5610. ResLoadHelper helper(CI, RK, RC, handle);
  5611. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicBinOp, handle,
  5612. helper.addr, /*offset*/ nullptr);
  5613. TranslateAtomicBinaryOperation(atomHelper, DXIL::AtomicBinOpCode::Xor,
  5614. Builder, hlslOP);
  5615. } break;
  5616. case IntrinsicOp::IOP_InterlockedCompareStore:
  5617. case IntrinsicOp::IOP_InterlockedCompareExchange: {
  5618. ResLoadHelper helper(CI, RK, RC, handle);
  5619. AtomicHelper atomHelper(userCall, DXIL::OpCode::AtomicCompareExchange,
  5620. handle, helper.addr, /*offset*/ nullptr);
  5621. TranslateAtomicCmpXChg(atomHelper, Builder, hlslOP);
  5622. } break;
  5623. default:
  5624. DXASSERT(0, "invalid opcode");
  5625. break;
  5626. }
  5627. } else {
  5628. DXASSERT(0, "invalid group");
  5629. }
  5630. userCall->eraseFromParent();
  5631. }
  5632. }
  5633. }
  5634. void TranslateHLSubscript(CallInst *CI, HLSubscriptOpcode opcode,
  5635. HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper, bool &Translated) {
  5636. if (CI->user_empty()) {
  5637. Translated = true;
  5638. return;
  5639. }
  5640. hlsl::OP *hlslOP = &helper.hlslOP;
  5641. Value *ptr = CI->getArgOperand(HLOperandIndex::kSubscriptObjectOpIdx);
  5642. if (opcode == HLSubscriptOpcode::CBufferSubscript) {
  5643. HLModule::MergeGepUse(CI);
  5644. // Resource ptr.
  5645. Value *handle = CI->getArgOperand(HLOperandIndex::kSubscriptObjectOpIdx);
  5646. if (helper.bLegacyCBufferLoad)
  5647. TranslateCBOperationsLegacy(handle, CI, hlslOP, helper.dxilTypeSys,
  5648. helper.legacyDataLayout, pObjHelper);
  5649. else {
  5650. TranslateCBOperations(handle, CI, /*offset*/ hlslOP->GetU32Const(0),
  5651. hlslOP, helper.dxilTypeSys,
  5652. CI->getModule()->getDataLayout());
  5653. }
  5654. Translated = true;
  5655. return;
  5656. } else if (opcode == HLSubscriptOpcode::DoubleSubscript) {
  5657. // Resource ptr.
  5658. Value *handle = ptr;
  5659. DXIL::ResourceKind RK = pObjHelper->GetRK(handle);
  5660. Value *coord = CI->getArgOperand(HLOperandIndex::kSubscriptIndexOpIdx);
  5661. Value *mipLevel =
  5662. CI->getArgOperand(HLOperandIndex::kDoubleSubscriptMipLevelOpIdx);
  5663. auto U = CI->user_begin();
  5664. DXASSERT(CI->hasOneUse(), "subscript should only has one use");
  5665. // TODO: support store.
  5666. Instruction *ldInst = cast<Instruction>(*U);
  5667. ResLoadHelper ldHelper(ldInst, handle, coord, mipLevel);
  5668. IRBuilder<> Builder(CI);
  5669. TranslateLoad(ldHelper, RK, Builder, hlslOP, helper.legacyDataLayout);
  5670. ldInst->eraseFromParent();
  5671. Translated = true;
  5672. return;
  5673. } else {
  5674. Type *HandleTy = hlslOP->GetHandleType();
  5675. if (ptr->getType() == HandleTy) {
  5676. // Resource ptr.
  5677. Value *handle = ptr;
  5678. DXIL::ResourceKind RK = pObjHelper->GetRK(handle);
  5679. if (RK == DxilResource::Kind::Invalid) {
  5680. Translated = false;
  5681. return;
  5682. }
  5683. Translated = true;
  5684. Type *ObjTy = pObjHelper->GetResourceType(handle);
  5685. Type *RetTy = ObjTy->getStructElementType(0);
  5686. if (RK == DxilResource::Kind::StructuredBuffer) {
  5687. TranslateStructBufSubscript(CI, handle, /*status*/ nullptr, hlslOP,
  5688. helper.legacyDataLayout);
  5689. } else if (RetTy->isAggregateType() &&
  5690. RK == DxilResource::Kind::TypedBuffer) {
  5691. TranslateStructBufSubscript(CI, handle, /*status*/ nullptr, hlslOP,
  5692. helper.legacyDataLayout);
  5693. // Clear offset for typed buf.
  5694. for (auto User : handle->users()) {
  5695. CallInst *CI = cast<CallInst>(User);
  5696. // Skip not lowered HL functions.
  5697. if (hlsl::GetHLOpcodeGroupByName(CI->getCalledFunction()) != HLOpcodeGroup::NotHL)
  5698. continue;
  5699. switch (hlslOP->GetDxilOpFuncCallInst(CI)) {
  5700. case DXIL::OpCode::BufferLoad: {
  5701. CI->setArgOperand(DXIL::OperandIndex::kBufferLoadCoord1OpIdx,
  5702. UndefValue::get(helper.i32Ty));
  5703. } break;
  5704. case DXIL::OpCode::BufferStore: {
  5705. CI->setArgOperand(DXIL::OperandIndex::kBufferStoreCoord1OpIdx,
  5706. UndefValue::get(helper.i32Ty));
  5707. } break;
  5708. case DXIL::OpCode::AtomicBinOp: {
  5709. CI->setArgOperand(DXIL::OperandIndex::kAtomicBinOpCoord1OpIdx,
  5710. UndefValue::get(helper.i32Ty));
  5711. } break;
  5712. case DXIL::OpCode::AtomicCompareExchange: {
  5713. CI->setArgOperand(DXIL::OperandIndex::kAtomicCmpExchangeCoord1OpIdx,
  5714. UndefValue::get(helper.i32Ty));
  5715. } break;
  5716. default:
  5717. DXASSERT(0, "Invalid operation on resource handle");
  5718. break;
  5719. }
  5720. }
  5721. } else {
  5722. TranslateDefaultSubscript(CI, helper, pObjHelper, Translated);
  5723. }
  5724. return;
  5725. }
  5726. }
  5727. Value *basePtr = CI->getArgOperand(HLOperandIndex::kMatSubscriptMatOpIdx);
  5728. if (IsLocalVariablePtr(basePtr) || IsSharedMemPtr(basePtr)) {
  5729. // Translate matrix into vector of array for share memory or local
  5730. // variable should be done in HLMatrixLowerPass
  5731. DXASSERT_NOMSG(0);
  5732. Translated = true;
  5733. return;
  5734. }
  5735. // Other case should be take care in TranslateStructBufSubscript or
  5736. // TranslateCBOperations.
  5737. Translated = false;
  5738. return;
  5739. }
  5740. }
  5741. void TranslateSubscriptOperation(Function *F, HLOperationLowerHelper &helper, HLObjectOperationLowerHelper *pObjHelper) {
  5742. for (auto U = F->user_begin(); U != F->user_end();) {
  5743. Value *user = *(U++);
  5744. if (!isa<Instruction>(user))
  5745. continue;
  5746. // must be call inst
  5747. CallInst *CI = cast<CallInst>(user);
  5748. unsigned opcode = GetHLOpcode(CI);
  5749. bool Translated = true;
  5750. TranslateHLSubscript(
  5751. CI, static_cast<HLSubscriptOpcode>(opcode), helper, pObjHelper, Translated);
  5752. if (Translated) {
  5753. // delete the call
  5754. DXASSERT(CI->use_empty(),
  5755. "else TranslateHLSubscript didn't replace/erase uses");
  5756. CI->eraseFromParent();
  5757. }
  5758. }
  5759. }
  5760. void TranslateHLBuiltinOperation(Function *F, HLOperationLowerHelper &helper,
  5761. hlsl::HLOpcodeGroup group, HLObjectOperationLowerHelper *pObjHelper) {
  5762. if (group == HLOpcodeGroup::HLIntrinsic) {
  5763. // map to dxil operations
  5764. for (auto U = F->user_begin(); U != F->user_end();) {
  5765. Value *User = *(U++);
  5766. if (!isa<Instruction>(User))
  5767. continue;
  5768. // must be call inst
  5769. CallInst *CI = cast<CallInst>(User);
  5770. // Keep the instruction to lower by other function.
  5771. bool Translated = true;
  5772. TranslateBuiltinIntrinsic(CI, helper, pObjHelper, Translated);
  5773. if (Translated) {
  5774. // delete the call
  5775. DXASSERT(CI->use_empty(),
  5776. "else TranslateBuiltinIntrinsic didn't replace/erase uses");
  5777. CI->eraseFromParent();
  5778. }
  5779. }
  5780. } else {
  5781. if (group == HLOpcodeGroup::HLMatLoadStore) {
  5782. // Both ld/st use arg1 for the pointer.
  5783. Type *PtrTy =
  5784. F->getFunctionType()->getParamType(HLOperandIndex::kMatLoadPtrOpIdx);
  5785. if (PtrTy->getPointerAddressSpace() == DXIL::kTGSMAddrSpace ||
  5786. // TODO: use DeviceAddressSpace for SRV/UAV and CBufferAddressSpace
  5787. // for CBuffer.
  5788. PtrTy->getPointerAddressSpace() == DXIL::kDefaultAddrSpace) {
  5789. // Translate matrix into vector of array for share memory or local
  5790. // variable should be done in HLMatrixLowerPass.
  5791. if (!F->user_empty())
  5792. F->getContext().emitError("Fail to lower matrix load/store.");
  5793. }
  5794. } else if (group == HLOpcodeGroup::HLSubscript) {
  5795. TranslateSubscriptOperation(F, helper, pObjHelper);
  5796. }
  5797. // map to math function or llvm ir
  5798. }
  5799. }
  5800. typedef std::unordered_map<llvm::Instruction *, llvm::Value *> HandleMap;
  5801. static void TranslateHLExtension(Function *F,
  5802. HLSLExtensionsCodegenHelper *helper,
  5803. OP& hlslOp) {
  5804. // Find all calls to the function F.
  5805. // Store the calls in a vector for now to be replaced the loop below.
  5806. // We use a two step "find then replace" to avoid removing uses while
  5807. // iterating.
  5808. SmallVector<CallInst *, 8> CallsToReplace;
  5809. for (User *U : F->users()) {
  5810. if (CallInst *CI = dyn_cast<CallInst>(U)) {
  5811. CallsToReplace.push_back(CI);
  5812. }
  5813. }
  5814. // Get the lowering strategy to use for this intrinsic.
  5815. llvm::StringRef LowerStrategy = GetHLLowerStrategy(F);
  5816. ExtensionLowering lower(LowerStrategy, helper, hlslOp);
  5817. // Replace all calls that were successfully translated.
  5818. for (CallInst *CI : CallsToReplace) {
  5819. Value *Result = lower.Translate(CI);
  5820. if (Result && Result != CI) {
  5821. CI->replaceAllUsesWith(Result);
  5822. CI->eraseFromParent();
  5823. }
  5824. }
  5825. }
  5826. namespace hlsl {
  5827. void TranslateBuiltinOperations(
  5828. HLModule &HLM, HLSLExtensionsCodegenHelper *extCodegenHelper,
  5829. std::unordered_set<LoadInst *> &UpdateCounterSet,
  5830. std::unordered_set<Value *> &NonUniformSet) {
  5831. HLOperationLowerHelper helper(HLM);
  5832. HLObjectOperationLowerHelper objHelper = {HLM, UpdateCounterSet,
  5833. NonUniformSet};
  5834. Module *M = HLM.GetModule();
  5835. // generate dxil operation
  5836. for (iplist<Function>::iterator F : M->getFunctionList()) {
  5837. if (!F->isDeclaration()) {
  5838. continue;
  5839. }
  5840. if (F->user_empty())
  5841. continue;
  5842. hlsl::HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  5843. if (group == HLOpcodeGroup::NotHL) {
  5844. // Nothing to do.
  5845. continue;
  5846. }
  5847. if (group == HLOpcodeGroup::HLExtIntrinsic) {
  5848. TranslateHLExtension(F, extCodegenHelper, helper.hlslOP);
  5849. continue;
  5850. }
  5851. if (group == HLOpcodeGroup::HLCreateHandle) {
  5852. // Will lower in later pass.
  5853. continue;
  5854. }
  5855. TranslateHLBuiltinOperation(F, helper, group, &objHelper);
  5856. }
  5857. }
  5858. }