CGHLSLMS.cpp 230 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270
  1. //===----- CGHLSLMS.cpp - Interface to HLSL Runtime ----------------===//
  2. ///////////////////////////////////////////////////////////////////////////////
  3. // //
  4. // CGHLSLMS.cpp //
  5. // Copyright (C) Microsoft Corporation. All rights reserved. //
  6. // This file is distributed under the University of Illinois Open Source //
  7. // License. See LICENSE.TXT for details. //
  8. // //
  9. // This provides a class for HLSL code generation. //
  10. // //
  11. ///////////////////////////////////////////////////////////////////////////////
  12. #include "CGHLSLRuntime.h"
  13. #include "CodeGenFunction.h"
  14. #include "CodeGenModule.h"
  15. #include "CGRecordLayout.h"
  16. #include "dxc/HlslIntrinsicOp.h"
  17. #include "dxc/HLSL/HLMatrixLowerHelper.h"
  18. #include "dxc/HLSL/HLModule.h"
  19. #include "dxc/HLSL/DxilUtil.h"
  20. #include "dxc/HLSL/HLOperations.h"
  21. #include "dxc/HLSL/DxilOperations.h"
  22. #include "dxc/HLSL/DxilTypeSystem.h"
  23. #include "clang/AST/DeclTemplate.h"
  24. #include "clang/AST/HlslTypes.h"
  25. #include "clang/Frontend/CodeGenOptions.h"
  26. #include "clang/Lex/HLSLMacroExpander.h"
  27. #include "llvm/ADT/STLExtras.h"
  28. #include "llvm/ADT/StringSwitch.h"
  29. #include "llvm/IR/Constants.h"
  30. #include "llvm/IR/IRBuilder.h"
  31. #include "llvm/IR/GetElementPtrTypeIterator.h"
  32. #include "llvm/Transforms/Utils/Cloning.h"
  33. #include "llvm/IR/InstIterator.h"
  34. #include <memory>
  35. #include <unordered_map>
  36. #include <unordered_set>
  37. #include "dxc/HLSL/DxilRootSignature.h"
  38. #include "dxc/HLSL/DxilCBuffer.h"
  39. #include "clang/Parse/ParseHLSL.h" // root sig would be in Parser if part of lang
  40. #include "dxc/Support/WinIncludes.h" // stream support
  41. #include "dxc/dxcapi.h" // stream support
  42. #include "dxc/HLSL/HLSLExtensionsCodegenHelper.h"
  43. #include "dxc/HLSL/DxilGenerationPass.h" // support pause/resume passes
  44. using namespace clang;
  45. using namespace CodeGen;
  46. using namespace hlsl;
  47. using namespace llvm;
  48. using std::unique_ptr;
  49. static const bool KeepUndefinedTrue = true; // Keep interpolation mode undefined if not set explicitly.
  50. namespace {
  51. /// Use this class to represent HLSL cbuffer in high-level DXIL.
  52. class HLCBuffer : public DxilCBuffer {
  53. public:
  54. HLCBuffer() = default;
  55. virtual ~HLCBuffer() = default;
  56. void AddConst(std::unique_ptr<DxilResourceBase> &pItem);
  57. std::vector<std::unique_ptr<DxilResourceBase>> &GetConstants();
  58. private:
  59. std::vector<std::unique_ptr<DxilResourceBase>> constants; // constants inside const buffer
  60. };
  61. //------------------------------------------------------------------------------
  62. //
  63. // HLCBuffer methods.
  64. //
  65. void HLCBuffer::AddConst(std::unique_ptr<DxilResourceBase> &pItem) {
  66. pItem->SetID(constants.size());
  67. constants.push_back(std::move(pItem));
  68. }
  69. std::vector<std::unique_ptr<DxilResourceBase>> &HLCBuffer::GetConstants() {
  70. return constants;
  71. }
  72. class CGMSHLSLRuntime : public CGHLSLRuntime {
  73. private:
  74. /// Convenience reference to LLVM Context
  75. llvm::LLVMContext &Context;
  76. /// Convenience reference to the current module
  77. llvm::Module &TheModule;
  78. HLModule *m_pHLModule;
  79. llvm::Type *CBufferType;
  80. uint32_t globalCBIndex;
  81. // TODO: make sure how minprec works
  82. llvm::DataLayout dataLayout;
  83. // decl map to constant id for program
  84. llvm::DenseMap<HLSLBufferDecl *, uint32_t> constantBufMap;
  85. // Map for resource type to resource metadata value.
  86. std::unordered_map<llvm::Type *, MDNode*> resMetadataMap;
  87. bool m_bDebugInfo;
  88. bool m_bIsLib;
  89. HLCBuffer &GetGlobalCBuffer() {
  90. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(globalCBIndex)));
  91. }
  92. void AddConstant(VarDecl *constDecl, HLCBuffer &CB);
  93. uint32_t AddSampler(VarDecl *samplerDecl);
  94. uint32_t AddUAVSRV(VarDecl *decl, hlsl::DxilResourceBase::Class resClass);
  95. bool SetUAVSRV(SourceLocation loc, hlsl::DxilResourceBase::Class resClass,
  96. DxilResource *hlslRes, const RecordDecl *RD);
  97. uint32_t AddCBuffer(HLSLBufferDecl *D);
  98. hlsl::DxilResourceBase::Class TypeToClass(clang::QualType Ty);
  99. // Save the entryFunc so don't need to find it with original name.
  100. struct EntryFunctionInfo {
  101. clang::SourceLocation SL = clang::SourceLocation();
  102. llvm::Function *Func = nullptr;
  103. };
  104. EntryFunctionInfo Entry;
  105. // Map to save patch constant functions
  106. struct PatchConstantInfo {
  107. clang::SourceLocation SL = clang::SourceLocation();
  108. llvm::Function *Func = nullptr;
  109. std::uint32_t NumOverloads = 0;
  110. };
  111. StringMap<PatchConstantInfo> patchConstantFunctionMap;
  112. std::unordered_map<Function *, std::unique_ptr<DxilFunctionProps>>
  113. patchConstantFunctionPropsMap;
  114. bool IsPatchConstantFunction(const Function *F);
  115. std::unordered_map<Function *, const clang::HLSLPatchConstantFuncAttr *>
  116. HSEntryPatchConstantFuncAttr;
  117. // Map to save entry functions.
  118. StringMap<EntryFunctionInfo> entryFunctionMap;
  119. // Map to save static global init exp.
  120. std::unordered_map<Expr *, GlobalVariable *> staticConstGlobalInitMap;
  121. std::unordered_map<GlobalVariable *, std::vector<Constant *>>
  122. staticConstGlobalInitListMap;
  123. std::unordered_map<GlobalVariable *, Function *> staticConstGlobalCtorMap;
  124. // List for functions with clip plane.
  125. std::vector<Function *> clipPlaneFuncList;
  126. std::unordered_map<Value *, DebugLoc> debugInfoMap;
  127. DxilRootSignatureVersion rootSigVer;
  128. Value *EmitHLSLMatrixLoad(CGBuilderTy &Builder, Value *Ptr, QualType Ty);
  129. void EmitHLSLMatrixStore(CGBuilderTy &Builder, Value *Val, Value *DestPtr,
  130. QualType Ty);
  131. // Flatten the val into scalar val and push into elts and eltTys.
  132. void FlattenValToInitList(CodeGenFunction &CGF, SmallVector<Value *, 4> &elts,
  133. SmallVector<QualType, 4> &eltTys, QualType Ty,
  134. Value *val);
  135. // Push every value on InitListExpr into EltValList and EltTyList.
  136. void ScanInitList(CodeGenFunction &CGF, InitListExpr *E,
  137. SmallVector<Value *, 4> &EltValList,
  138. SmallVector<QualType, 4> &EltTyList);
  139. void FlattenAggregatePtrToGepList(CodeGenFunction &CGF, Value *Ptr,
  140. SmallVector<Value *, 4> &idxList,
  141. clang::QualType Type, llvm::Type *Ty,
  142. SmallVector<Value *, 4> &GepList,
  143. SmallVector<QualType, 4> &EltTyList);
  144. void LoadFlattenedGepList(CodeGenFunction &CGF, ArrayRef<Value *> GepList,
  145. ArrayRef<QualType> EltTyList,
  146. SmallVector<Value *, 4> &EltList);
  147. void StoreFlattenedGepList(CodeGenFunction &CGF, ArrayRef<Value *> GepList,
  148. ArrayRef<QualType> GepTyList,
  149. ArrayRef<Value *> EltValList,
  150. ArrayRef<QualType> SrcTyList);
  151. void EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  152. llvm::Value *DestPtr,
  153. SmallVector<Value *, 4> &idxList,
  154. clang::QualType SrcType,
  155. clang::QualType DestType,
  156. llvm::Type *Ty);
  157. void EmitHLSLFlatConversionToAggregate(CodeGenFunction &CGF, Value *SrcVal,
  158. llvm::Value *DestPtr,
  159. SmallVector<Value *, 4> &idxList,
  160. QualType Type, QualType SrcType,
  161. llvm::Type *Ty);
  162. void EmitHLSLRootSignature(CodeGenFunction &CGF, HLSLRootSignatureAttr *RSA,
  163. llvm::Function *Fn);
  164. void CheckParameterAnnotation(SourceLocation SLoc,
  165. const DxilParameterAnnotation &paramInfo,
  166. bool isPatchConstantFunction);
  167. void CheckParameterAnnotation(SourceLocation SLoc,
  168. DxilParamInputQual paramQual,
  169. llvm::StringRef semFullName,
  170. bool isPatchConstantFunction);
  171. void SetEntryFunction();
  172. SourceLocation SetSemantic(const NamedDecl *decl,
  173. DxilParameterAnnotation &paramInfo);
  174. hlsl::InterpolationMode GetInterpMode(const Decl *decl, CompType compType,
  175. bool bKeepUndefined);
  176. hlsl::CompType GetCompType(const BuiltinType *BT);
  177. // save intrinsic opcode
  178. std::vector<std::pair<Function *, unsigned>> m_IntrinsicMap;
  179. void AddHLSLIntrinsicOpcodeToFunction(Function *, unsigned opcode);
  180. // Type annotation related.
  181. unsigned ConstructStructAnnotation(DxilStructAnnotation *annotation,
  182. const RecordDecl *RD,
  183. DxilTypeSystem &dxilTypeSys);
  184. unsigned AddTypeAnnotation(QualType Ty, DxilTypeSystem &dxilTypeSys,
  185. unsigned &arrayEltSize);
  186. MDNode *GetOrAddResTypeMD(QualType resTy);
  187. void ConstructFieldAttributedAnnotation(DxilFieldAnnotation &fieldAnnotation,
  188. QualType fieldTy,
  189. bool bDefaultRowMajor);
  190. std::unordered_map<Constant*, DxilFieldAnnotation> m_ConstVarAnnotationMap;
  191. public:
  192. CGMSHLSLRuntime(CodeGenModule &CGM);
  193. bool IsHlslObjectType(llvm::Type * Ty) override;
  194. /// Add resouce to the program
  195. void addResource(Decl *D) override;
  196. void SetPatchConstantFunction(const EntryFunctionInfo &EntryFunc);
  197. void SetPatchConstantFunctionWithAttr(
  198. const EntryFunctionInfo &EntryFunc,
  199. const clang::HLSLPatchConstantFuncAttr *PatchConstantFuncAttr);
  200. void FinishCodeGen() override;
  201. bool IsTrivalInitListExpr(CodeGenFunction &CGF, InitListExpr *E) override;
  202. Value *EmitHLSLInitListExpr(CodeGenFunction &CGF, InitListExpr *E, Value *DestPtr) override;
  203. Constant *EmitHLSLConstInitListExpr(CodeGenModule &CGM, InitListExpr *E) override;
  204. RValue EmitHLSLBuiltinCallExpr(CodeGenFunction &CGF, const FunctionDecl *FD,
  205. const CallExpr *E,
  206. ReturnValueSlot ReturnValue) override;
  207. void EmitHLSLOutParamConversionInit(
  208. CodeGenFunction &CGF, const FunctionDecl *FD, const CallExpr *E,
  209. llvm::SmallVector<LValue, 8> &castArgList,
  210. llvm::SmallVector<const Stmt *, 8> &argList,
  211. const std::function<void(const VarDecl *, llvm::Value *)> &TmpArgMap)
  212. override;
  213. void EmitHLSLOutParamConversionCopyBack(
  214. CodeGenFunction &CGF, llvm::SmallVector<LValue, 8> &castArgList) override;
  215. Value *EmitHLSLMatrixOperationCall(CodeGenFunction &CGF, const clang::Expr *E,
  216. llvm::Type *RetType,
  217. ArrayRef<Value *> paramList) override;
  218. void EmitHLSLDiscard(CodeGenFunction &CGF) override;
  219. Value *EmitHLSLMatrixSubscript(CodeGenFunction &CGF, llvm::Type *RetType,
  220. Value *Ptr, Value *Idx, QualType Ty) override;
  221. Value *EmitHLSLMatrixElement(CodeGenFunction &CGF, llvm::Type *RetType,
  222. ArrayRef<Value *> paramList,
  223. QualType Ty) override;
  224. Value *EmitHLSLMatrixLoad(CodeGenFunction &CGF, Value *Ptr,
  225. QualType Ty) override;
  226. void EmitHLSLMatrixStore(CodeGenFunction &CGF, Value *Val, Value *DestPtr,
  227. QualType Ty) override;
  228. void EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  229. llvm::Value *DestPtr,
  230. clang::QualType Ty) override;
  231. void EmitHLSLAggregateStore(CodeGenFunction &CGF, llvm::Value *Val,
  232. llvm::Value *DestPtr,
  233. clang::QualType Ty) override;
  234. void EmitHLSLFlatConversionToAggregate(CodeGenFunction &CGF, Value *Val,
  235. Value *DestPtr,
  236. QualType Ty,
  237. QualType SrcTy) override;
  238. Value *EmitHLSLLiteralCast(CodeGenFunction &CGF, Value *Src, QualType SrcType,
  239. QualType DstType) override;
  240. void EmitHLSLFlatConversionAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  241. clang::QualType SrcTy,
  242. llvm::Value *DestPtr,
  243. clang::QualType DestTy) override;
  244. void AddHLSLFunctionInfo(llvm::Function *, const FunctionDecl *FD) override;
  245. void EmitHLSLFunctionProlog(llvm::Function *, const FunctionDecl *FD) override;
  246. void AddControlFlowHint(CodeGenFunction &CGF, const Stmt &S,
  247. llvm::TerminatorInst *TI,
  248. ArrayRef<const Attr *> Attrs) override;
  249. void FinishAutoVar(CodeGenFunction &CGF, const VarDecl &D, llvm::Value *V) override;
  250. /// Get or add constant to the program
  251. HLCBuffer &GetOrCreateCBuffer(HLSLBufferDecl *D);
  252. };
  253. }
  254. void clang::CompileRootSignature(
  255. StringRef rootSigStr, DiagnosticsEngine &Diags, SourceLocation SLoc,
  256. hlsl::DxilRootSignatureVersion rootSigVer,
  257. hlsl::RootSignatureHandle *pRootSigHandle) {
  258. std::string OSStr;
  259. llvm::raw_string_ostream OS(OSStr);
  260. hlsl::DxilVersionedRootSignatureDesc *D = nullptr;
  261. if (ParseHLSLRootSignature(rootSigStr.data(), rootSigStr.size(), rootSigVer,
  262. &D, SLoc, Diags)) {
  263. CComPtr<IDxcBlob> pSignature;
  264. CComPtr<IDxcBlobEncoding> pErrors;
  265. hlsl::SerializeRootSignature(D, &pSignature, &pErrors, false);
  266. if (pSignature == nullptr) {
  267. assert(pErrors != nullptr && "else serialize failed with no msg");
  268. ReportHLSLRootSigError(Diags, SLoc, (char *)pErrors->GetBufferPointer(),
  269. pErrors->GetBufferSize());
  270. hlsl::DeleteRootSignature(D);
  271. } else {
  272. pRootSigHandle->Assign(D, pSignature);
  273. }
  274. }
  275. }
  276. //------------------------------------------------------------------------------
  277. //
  278. // CGMSHLSLRuntime methods.
  279. //
  280. CGMSHLSLRuntime::CGMSHLSLRuntime(CodeGenModule &CGM)
  281. : CGHLSLRuntime(CGM), Context(CGM.getLLVMContext()), Entry(),
  282. TheModule(CGM.getModule()),
  283. dataLayout(CGM.getLangOpts().UseMinPrecision
  284. ? hlsl::DXIL::kLegacyLayoutString
  285. : hlsl::DXIL::kNewLayoutString),
  286. CBufferType(
  287. llvm::StructType::create(TheModule.getContext(), "ConstantBuffer")) {
  288. const hlsl::ShaderModel *SM =
  289. hlsl::ShaderModel::GetByName(CGM.getCodeGenOpts().HLSLProfile.c_str());
  290. // Only accept valid, 6.0 shader model.
  291. if (!SM->IsValid() || SM->GetMajor() != 6) {
  292. DiagnosticsEngine &Diags = CGM.getDiags();
  293. unsigned DiagID =
  294. Diags.getCustomDiagID(DiagnosticsEngine::Error, "invalid profile %0");
  295. Diags.Report(DiagID) << CGM.getCodeGenOpts().HLSLProfile;
  296. return;
  297. }
  298. m_bIsLib = SM->IsLib();
  299. // TODO: add AllResourceBound.
  300. if (CGM.getCodeGenOpts().HLSLAvoidControlFlow && !CGM.getCodeGenOpts().HLSLAllResourcesBound) {
  301. if (SM->IsSM51Plus()) {
  302. DiagnosticsEngine &Diags = CGM.getDiags();
  303. unsigned DiagID =
  304. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  305. "Gfa option cannot be used in SM_5_1+ unless "
  306. "all_resources_bound flag is specified");
  307. Diags.Report(DiagID);
  308. }
  309. }
  310. // Create HLModule.
  311. const bool skipInit = true;
  312. m_pHLModule = &TheModule.GetOrCreateHLModule(skipInit);
  313. // Set Option.
  314. HLOptions opts;
  315. opts.bIEEEStrict = CGM.getCodeGenOpts().UnsafeFPMath;
  316. opts.bDefaultRowMajor = CGM.getCodeGenOpts().HLSLDefaultRowMajor;
  317. opts.bDisableOptimizations = CGM.getCodeGenOpts().DisableLLVMOpts;
  318. opts.bLegacyCBufferLoad = !CGM.getCodeGenOpts().HLSLNotUseLegacyCBufLoad;
  319. opts.bAllResourcesBound = CGM.getCodeGenOpts().HLSLAllResourcesBound;
  320. opts.PackingStrategy = CGM.getCodeGenOpts().HLSLSignaturePackingStrategy;
  321. opts.bUseMinPrecision = CGM.getLangOpts().UseMinPrecision;
  322. m_pHLModule->SetHLOptions(opts);
  323. m_pHLModule->SetValidatorVersion(CGM.getCodeGenOpts().HLSLValidatorMajorVer, CGM.getCodeGenOpts().HLSLValidatorMinorVer);
  324. m_bDebugInfo = CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::FullDebugInfo;
  325. // set profile
  326. m_pHLModule->SetShaderModel(SM);
  327. // set entry name
  328. m_pHLModule->SetEntryFunctionName(CGM.getCodeGenOpts().HLSLEntryFunction);
  329. // set root signature version.
  330. if (CGM.getLangOpts().RootSigMinor == 0) {
  331. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_0;
  332. }
  333. else {
  334. DXASSERT(CGM.getLangOpts().RootSigMinor == 1,
  335. "else CGMSHLSLRuntime Constructor needs to be updated");
  336. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_1;
  337. }
  338. DXASSERT(CGM.getLangOpts().RootSigMajor == 1,
  339. "else CGMSHLSLRuntime Constructor needs to be updated");
  340. // add globalCB
  341. unique_ptr<HLCBuffer> CB = llvm::make_unique<HLCBuffer>();
  342. std::string globalCBName = "$Globals";
  343. CB->SetGlobalSymbol(nullptr);
  344. CB->SetGlobalName(globalCBName);
  345. globalCBIndex = m_pHLModule->GetCBuffers().size();
  346. CB->SetID(globalCBIndex);
  347. CB->SetRangeSize(1);
  348. CB->SetLowerBound(UINT_MAX);
  349. DXVERIFY_NOMSG(globalCBIndex == m_pHLModule->AddCBuffer(std::move(CB)));
  350. // set Float Denorm Mode
  351. m_pHLModule->SetFloat32DenormMode(CGM.getCodeGenOpts().HLSLFloat32DenormMode);
  352. }
  353. bool CGMSHLSLRuntime::IsHlslObjectType(llvm::Type *Ty) {
  354. return HLModule::IsHLSLObjectType(Ty);
  355. }
  356. void CGMSHLSLRuntime::AddHLSLIntrinsicOpcodeToFunction(Function *F,
  357. unsigned opcode) {
  358. m_IntrinsicMap.emplace_back(F,opcode);
  359. }
  360. void CGMSHLSLRuntime::CheckParameterAnnotation(
  361. SourceLocation SLoc, const DxilParameterAnnotation &paramInfo,
  362. bool isPatchConstantFunction) {
  363. if (!paramInfo.HasSemanticString()) {
  364. return;
  365. }
  366. llvm::StringRef semFullName = paramInfo.GetSemanticStringRef();
  367. DxilParamInputQual paramQual = paramInfo.GetParamInputQual();
  368. if (paramQual == DxilParamInputQual::Inout) {
  369. CheckParameterAnnotation(SLoc, DxilParamInputQual::In, semFullName, isPatchConstantFunction);
  370. CheckParameterAnnotation(SLoc, DxilParamInputQual::Out, semFullName, isPatchConstantFunction);
  371. return;
  372. }
  373. CheckParameterAnnotation(SLoc, paramQual, semFullName, isPatchConstantFunction);
  374. }
  375. void CGMSHLSLRuntime::CheckParameterAnnotation(
  376. SourceLocation SLoc, DxilParamInputQual paramQual, llvm::StringRef semFullName,
  377. bool isPatchConstantFunction) {
  378. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  379. DXIL::SigPointKind sigPoint = SigPointFromInputQual(
  380. paramQual, SM->GetKind(), isPatchConstantFunction);
  381. llvm::StringRef semName;
  382. unsigned semIndex;
  383. Semantic::DecomposeNameAndIndex(semFullName, &semName, &semIndex);
  384. const Semantic *pSemantic =
  385. Semantic::GetByName(semName, sigPoint, SM->GetMajor(), SM->GetMinor());
  386. if (pSemantic->IsInvalid()) {
  387. DiagnosticsEngine &Diags = CGM.getDiags();
  388. const ShaderModel *shader = m_pHLModule->GetShaderModel();
  389. unsigned DiagID =
  390. Diags.getCustomDiagID(DiagnosticsEngine::Error, "invalid semantic '%0' for %1 %2.%3");
  391. Diags.Report(SLoc, DiagID) << semName << shader->GetKindName() << shader->GetMajor() << shader->GetMinor();
  392. }
  393. }
  394. SourceLocation
  395. CGMSHLSLRuntime::SetSemantic(const NamedDecl *decl,
  396. DxilParameterAnnotation &paramInfo) {
  397. for (const hlsl::UnusualAnnotation *it : decl->getUnusualAnnotations()) {
  398. if (it->getKind() == hlsl::UnusualAnnotation::UA_SemanticDecl) {
  399. const hlsl::SemanticDecl *sd = cast<hlsl::SemanticDecl>(it);
  400. paramInfo.SetSemanticString(sd->SemanticName);
  401. return it->Loc;
  402. }
  403. }
  404. return SourceLocation();
  405. }
  406. static DXIL::TessellatorDomain StringToDomain(StringRef domain) {
  407. if (domain == "isoline")
  408. return DXIL::TessellatorDomain::IsoLine;
  409. if (domain == "tri")
  410. return DXIL::TessellatorDomain::Tri;
  411. if (domain == "quad")
  412. return DXIL::TessellatorDomain::Quad;
  413. return DXIL::TessellatorDomain::Undefined;
  414. }
  415. static DXIL::TessellatorPartitioning StringToPartitioning(StringRef partition) {
  416. if (partition == "integer")
  417. return DXIL::TessellatorPartitioning::Integer;
  418. if (partition == "pow2")
  419. return DXIL::TessellatorPartitioning::Pow2;
  420. if (partition == "fractional_even")
  421. return DXIL::TessellatorPartitioning::FractionalEven;
  422. if (partition == "fractional_odd")
  423. return DXIL::TessellatorPartitioning::FractionalOdd;
  424. return DXIL::TessellatorPartitioning::Undefined;
  425. }
  426. static DXIL::TessellatorOutputPrimitive
  427. StringToTessOutputPrimitive(StringRef primitive) {
  428. if (primitive == "point")
  429. return DXIL::TessellatorOutputPrimitive::Point;
  430. if (primitive == "line")
  431. return DXIL::TessellatorOutputPrimitive::Line;
  432. if (primitive == "triangle_cw")
  433. return DXIL::TessellatorOutputPrimitive::TriangleCW;
  434. if (primitive == "triangle_ccw")
  435. return DXIL::TessellatorOutputPrimitive::TriangleCCW;
  436. return DXIL::TessellatorOutputPrimitive::Undefined;
  437. }
  438. static unsigned RoundToAlign(unsigned num, unsigned mod) {
  439. // round num to next highest mod
  440. if (mod != 0)
  441. return mod * ((num + mod - 1) / mod);
  442. return num;
  443. }
  444. // Align cbuffer offset in legacy mode (16 bytes per row).
  445. static unsigned AlignBufferOffsetInLegacy(unsigned offset, unsigned size,
  446. unsigned scalarSizeInBytes,
  447. bool bNeedNewRow) {
  448. if (unsigned remainder = (offset & 0xf)) {
  449. // Start from new row
  450. if (remainder + size > 16 || bNeedNewRow) {
  451. return offset + 16 - remainder;
  452. }
  453. // If not, naturally align data
  454. return RoundToAlign(offset, scalarSizeInBytes);
  455. }
  456. return offset;
  457. }
  458. static unsigned AlignBaseOffset(unsigned baseOffset, unsigned size,
  459. QualType Ty, bool bDefaultRowMajor) {
  460. bool needNewAlign = Ty->isArrayType();
  461. if (IsHLSLMatType(Ty)) {
  462. bool bColMajor = !bDefaultRowMajor;
  463. if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
  464. switch (AT->getAttrKind()) {
  465. case AttributedType::Kind::attr_hlsl_column_major:
  466. bColMajor = true;
  467. break;
  468. case AttributedType::Kind::attr_hlsl_row_major:
  469. bColMajor = false;
  470. break;
  471. default:
  472. // Do nothing
  473. break;
  474. }
  475. }
  476. unsigned row, col;
  477. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  478. needNewAlign |= bColMajor && col > 1;
  479. needNewAlign |= !bColMajor && row > 1;
  480. }
  481. unsigned scalarSizeInBytes = 4;
  482. const clang::BuiltinType *BT = Ty->getAs<clang::BuiltinType>();
  483. if (hlsl::IsHLSLVecMatType(Ty)) {
  484. BT = CGHLSLRuntime::GetHLSLVecMatElementType(Ty)->getAs<clang::BuiltinType>();
  485. }
  486. if (BT) {
  487. if (BT->getKind() == clang::BuiltinType::Kind::Double ||
  488. BT->getKind() == clang::BuiltinType::Kind::LongLong)
  489. scalarSizeInBytes = 8;
  490. else if (BT->getKind() == clang::BuiltinType::Kind::Half ||
  491. BT->getKind() == clang::BuiltinType::Kind::Short ||
  492. BT->getKind() == clang::BuiltinType::Kind::UShort)
  493. scalarSizeInBytes = 2;
  494. }
  495. return AlignBufferOffsetInLegacy(baseOffset, size, scalarSizeInBytes, needNewAlign);
  496. }
  497. static unsigned AlignBaseOffset(QualType Ty, unsigned baseOffset,
  498. bool bDefaultRowMajor,
  499. CodeGen::CodeGenModule &CGM,
  500. llvm::DataLayout &layout) {
  501. QualType paramTy = Ty.getCanonicalType();
  502. if (const ReferenceType *RefType = dyn_cast<ReferenceType>(paramTy))
  503. paramTy = RefType->getPointeeType();
  504. // Get size.
  505. llvm::Type *Type = CGM.getTypes().ConvertType(paramTy);
  506. unsigned size = layout.getTypeAllocSize(Type);
  507. return AlignBaseOffset(baseOffset, size, paramTy, bDefaultRowMajor);
  508. }
  509. static unsigned GetMatrixSizeInCB(QualType Ty, bool defaultRowMajor,
  510. bool b64Bit) {
  511. bool bColMajor = !defaultRowMajor;
  512. if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
  513. switch (AT->getAttrKind()) {
  514. case AttributedType::Kind::attr_hlsl_column_major:
  515. bColMajor = true;
  516. break;
  517. case AttributedType::Kind::attr_hlsl_row_major:
  518. bColMajor = false;
  519. break;
  520. default:
  521. // Do nothing
  522. break;
  523. }
  524. }
  525. unsigned row, col;
  526. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  527. unsigned EltSize = b64Bit ? 8 : 4;
  528. // Align to 4 * 4bytes.
  529. unsigned alignment = 4 * 4;
  530. if (bColMajor) {
  531. unsigned rowSize = EltSize * row;
  532. // 3x64bit or 4x64bit align to 32 bytes.
  533. if (rowSize > alignment)
  534. alignment <<= 1;
  535. return alignment * (col - 1) + row * EltSize;
  536. } else {
  537. unsigned rowSize = EltSize * col;
  538. // 3x64bit or 4x64bit align to 32 bytes.
  539. if (rowSize > alignment)
  540. alignment <<= 1;
  541. return alignment * (row - 1) + col * EltSize;
  542. }
  543. }
  544. static CompType::Kind BuiltinTyToCompTy(const BuiltinType *BTy, bool bSNorm,
  545. bool bUNorm) {
  546. CompType::Kind kind = CompType::Kind::Invalid;
  547. switch (BTy->getKind()) {
  548. case BuiltinType::UInt:
  549. kind = CompType::Kind::U32;
  550. break;
  551. case BuiltinType::UShort:
  552. kind = CompType::Kind::U16;
  553. break;
  554. case BuiltinType::ULongLong:
  555. kind = CompType::Kind::U64;
  556. break;
  557. case BuiltinType::Int:
  558. kind = CompType::Kind::I32;
  559. break;
  560. case BuiltinType::Min12Int:
  561. case BuiltinType::Short:
  562. kind = CompType::Kind::I16;
  563. break;
  564. case BuiltinType::LongLong:
  565. kind = CompType::Kind::I64;
  566. break;
  567. case BuiltinType::Min10Float:
  568. case BuiltinType::Half:
  569. if (bSNorm)
  570. kind = CompType::Kind::SNormF16;
  571. else if (bUNorm)
  572. kind = CompType::Kind::UNormF16;
  573. else
  574. kind = CompType::Kind::F16;
  575. break;
  576. case BuiltinType::Float:
  577. if (bSNorm)
  578. kind = CompType::Kind::SNormF32;
  579. else if (bUNorm)
  580. kind = CompType::Kind::UNormF32;
  581. else
  582. kind = CompType::Kind::F32;
  583. break;
  584. case BuiltinType::Double:
  585. if (bSNorm)
  586. kind = CompType::Kind::SNormF64;
  587. else if (bUNorm)
  588. kind = CompType::Kind::UNormF64;
  589. else
  590. kind = CompType::Kind::F64;
  591. break;
  592. case BuiltinType::Bool:
  593. kind = CompType::Kind::I1;
  594. break;
  595. }
  596. return kind;
  597. }
  598. static DxilSampler::SamplerKind KeywordToSamplerKind(llvm::StringRef keyword) {
  599. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  600. // compare)
  601. return llvm::StringSwitch<DxilSampler::SamplerKind>(keyword)
  602. .Case("SamplerState", DxilSampler::SamplerKind::Default)
  603. .Case("SamplerComparisonState", DxilSampler::SamplerKind::Comparison)
  604. .Default(DxilSampler::SamplerKind::Invalid);
  605. }
  606. MDNode *CGMSHLSLRuntime::GetOrAddResTypeMD(QualType resTy) {
  607. const RecordType *RT = resTy->getAs<RecordType>();
  608. if (!RT)
  609. return nullptr;
  610. RecordDecl *RD = RT->getDecl();
  611. SourceLocation loc = RD->getLocation();
  612. hlsl::DxilResourceBase::Class resClass = TypeToClass(resTy);
  613. llvm::Type *Ty = CGM.getTypes().ConvertType(resTy);
  614. auto it = resMetadataMap.find(Ty);
  615. if (it != resMetadataMap.end())
  616. return it->second;
  617. // Save resource type metadata.
  618. switch (resClass) {
  619. case DXIL::ResourceClass::UAV: {
  620. DxilResource UAV;
  621. // TODO: save globalcoherent to variable in EmitHLSLBuiltinCallExpr.
  622. SetUAVSRV(loc, resClass, &UAV, RD);
  623. // Set global symbol to save type.
  624. UAV.SetGlobalSymbol(UndefValue::get(Ty));
  625. MDNode *MD = m_pHLModule->DxilUAVToMDNode(UAV);
  626. resMetadataMap[Ty] = MD;
  627. return MD;
  628. } break;
  629. case DXIL::ResourceClass::SRV: {
  630. DxilResource SRV;
  631. SetUAVSRV(loc, resClass, &SRV, RD);
  632. // Set global symbol to save type.
  633. SRV.SetGlobalSymbol(UndefValue::get(Ty));
  634. MDNode *MD = m_pHLModule->DxilSRVToMDNode(SRV);
  635. resMetadataMap[Ty] = MD;
  636. return MD;
  637. } break;
  638. case DXIL::ResourceClass::Sampler: {
  639. DxilSampler S;
  640. DxilSampler::SamplerKind kind = KeywordToSamplerKind(RD->getName());
  641. S.SetSamplerKind(kind);
  642. // Set global symbol to save type.
  643. S.SetGlobalSymbol(UndefValue::get(Ty));
  644. MDNode *MD = m_pHLModule->DxilSamplerToMDNode(S);
  645. resMetadataMap[Ty] = MD;
  646. return MD;
  647. }
  648. default:
  649. // Skip OutputStream for GS.
  650. return nullptr;
  651. }
  652. }
  653. void CGMSHLSLRuntime::ConstructFieldAttributedAnnotation(
  654. DxilFieldAnnotation &fieldAnnotation, QualType fieldTy,
  655. bool bDefaultRowMajor) {
  656. QualType Ty = fieldTy;
  657. if (Ty->isReferenceType())
  658. Ty = Ty.getNonReferenceType();
  659. // Get element type.
  660. if (Ty->isArrayType()) {
  661. while (isa<clang::ArrayType>(Ty)) {
  662. const clang::ArrayType *ATy = dyn_cast<clang::ArrayType>(Ty);
  663. Ty = ATy->getElementType();
  664. }
  665. }
  666. QualType EltTy = Ty;
  667. if (hlsl::IsHLSLMatType(Ty)) {
  668. DxilMatrixAnnotation Matrix;
  669. Matrix.Orientation = bDefaultRowMajor ? MatrixOrientation::RowMajor
  670. : MatrixOrientation::ColumnMajor;
  671. if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
  672. switch (AT->getAttrKind()) {
  673. case AttributedType::Kind::attr_hlsl_column_major:
  674. Matrix.Orientation = MatrixOrientation::ColumnMajor;
  675. break;
  676. case AttributedType::Kind::attr_hlsl_row_major:
  677. Matrix.Orientation = MatrixOrientation::RowMajor;
  678. break;
  679. default:
  680. // Do nothing
  681. break;
  682. }
  683. }
  684. hlsl::GetHLSLMatRowColCount(Ty, Matrix.Rows, Matrix.Cols);
  685. fieldAnnotation.SetMatrixAnnotation(Matrix);
  686. EltTy = hlsl::GetHLSLMatElementType(Ty);
  687. }
  688. if (hlsl::IsHLSLVecType(Ty))
  689. EltTy = hlsl::GetHLSLVecElementType(Ty);
  690. if (IsHLSLResourceType(Ty)) {
  691. MDNode *MD = GetOrAddResTypeMD(Ty);
  692. fieldAnnotation.SetResourceAttribute(MD);
  693. }
  694. bool bSNorm = false;
  695. bool bUNorm = false;
  696. if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
  697. switch (AT->getAttrKind()) {
  698. case AttributedType::Kind::attr_hlsl_snorm:
  699. bSNorm = true;
  700. break;
  701. case AttributedType::Kind::attr_hlsl_unorm:
  702. bUNorm = true;
  703. break;
  704. default:
  705. // Do nothing
  706. break;
  707. }
  708. }
  709. if (EltTy->isBuiltinType()) {
  710. const BuiltinType *BTy = EltTy->getAs<BuiltinType>();
  711. CompType::Kind kind = BuiltinTyToCompTy(BTy, bSNorm, bUNorm);
  712. fieldAnnotation.SetCompType(kind);
  713. } else if (EltTy->isEnumeralType()) {
  714. const EnumType *ETy = EltTy->getAs<EnumType>();
  715. QualType type = ETy->getDecl()->getIntegerType();
  716. if (const BuiltinType *BTy =
  717. dyn_cast<BuiltinType>(type->getCanonicalTypeInternal()))
  718. fieldAnnotation.SetCompType(BuiltinTyToCompTy(BTy, bSNorm, bUNorm));
  719. } else
  720. DXASSERT(!bSNorm && !bUNorm,
  721. "snorm/unorm on invalid type, validate at handleHLSLTypeAttr");
  722. }
  723. static void ConstructFieldInterpolation(DxilFieldAnnotation &fieldAnnotation,
  724. FieldDecl *fieldDecl) {
  725. // Keep undefined for interpMode here.
  726. InterpolationMode InterpMode = {fieldDecl->hasAttr<HLSLNoInterpolationAttr>(),
  727. fieldDecl->hasAttr<HLSLLinearAttr>(),
  728. fieldDecl->hasAttr<HLSLNoPerspectiveAttr>(),
  729. fieldDecl->hasAttr<HLSLCentroidAttr>(),
  730. fieldDecl->hasAttr<HLSLSampleAttr>()};
  731. if (InterpMode.GetKind() != InterpolationMode::Kind::Undefined)
  732. fieldAnnotation.SetInterpolationMode(InterpMode);
  733. }
  734. unsigned CGMSHLSLRuntime::ConstructStructAnnotation(DxilStructAnnotation *annotation,
  735. const RecordDecl *RD,
  736. DxilTypeSystem &dxilTypeSys) {
  737. unsigned fieldIdx = 0;
  738. unsigned offset = 0;
  739. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  740. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  741. if (CXXRD->getNumBases()) {
  742. // Add base as field.
  743. for (const auto &I : CXXRD->bases()) {
  744. const CXXRecordDecl *BaseDecl =
  745. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  746. std::string fieldSemName = "";
  747. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  748. // Align offset.
  749. offset = AlignBaseOffset(parentTy, offset, bDefaultRowMajor, CGM,
  750. dataLayout);
  751. unsigned CBufferOffset = offset;
  752. unsigned arrayEltSize = 0;
  753. // Process field to make sure the size of field is ready.
  754. unsigned size =
  755. AddTypeAnnotation(parentTy, dxilTypeSys, arrayEltSize);
  756. // Update offset.
  757. offset += size;
  758. if (size > 0) {
  759. DxilFieldAnnotation &fieldAnnotation =
  760. annotation->GetFieldAnnotation(fieldIdx++);
  761. fieldAnnotation.SetCBufferOffset(CBufferOffset);
  762. fieldAnnotation.SetFieldName(BaseDecl->getNameAsString());
  763. }
  764. }
  765. }
  766. }
  767. for (auto fieldDecl : RD->fields()) {
  768. std::string fieldSemName = "";
  769. QualType fieldTy = fieldDecl->getType();
  770. // Align offset.
  771. offset = AlignBaseOffset(fieldTy, offset, bDefaultRowMajor, CGM, dataLayout);
  772. unsigned CBufferOffset = offset;
  773. bool userOffset = false;
  774. // Try to get info from fieldDecl.
  775. for (const hlsl::UnusualAnnotation *it :
  776. fieldDecl->getUnusualAnnotations()) {
  777. switch (it->getKind()) {
  778. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  779. const hlsl::SemanticDecl *sd = cast<hlsl::SemanticDecl>(it);
  780. fieldSemName = sd->SemanticName;
  781. } break;
  782. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  783. const hlsl::ConstantPacking *cp = cast<hlsl::ConstantPacking>(it);
  784. CBufferOffset = cp->Subcomponent << 2;
  785. CBufferOffset += cp->ComponentOffset;
  786. // Change to byte.
  787. CBufferOffset <<= 2;
  788. userOffset = true;
  789. } break;
  790. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  791. // register assignment only works on global constant.
  792. DiagnosticsEngine &Diags = CGM.getDiags();
  793. unsigned DiagID = Diags.getCustomDiagID(
  794. DiagnosticsEngine::Error,
  795. "location semantics cannot be specified on members.");
  796. Diags.Report(it->Loc, DiagID);
  797. return 0;
  798. } break;
  799. default:
  800. llvm_unreachable("only semantic for input/output");
  801. break;
  802. }
  803. }
  804. unsigned arrayEltSize = 0;
  805. // Process field to make sure the size of field is ready.
  806. unsigned size = AddTypeAnnotation(fieldDecl->getType(), dxilTypeSys, arrayEltSize);
  807. // Update offset.
  808. offset += size;
  809. DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(fieldIdx++);
  810. ConstructFieldAttributedAnnotation(fieldAnnotation, fieldTy, bDefaultRowMajor);
  811. ConstructFieldInterpolation(fieldAnnotation, fieldDecl);
  812. if (fieldDecl->hasAttr<HLSLPreciseAttr>())
  813. fieldAnnotation.SetPrecise();
  814. fieldAnnotation.SetCBufferOffset(CBufferOffset);
  815. fieldAnnotation.SetFieldName(fieldDecl->getName());
  816. if (!fieldSemName.empty())
  817. fieldAnnotation.SetSemanticString(fieldSemName);
  818. }
  819. annotation->SetCBufferSize(offset);
  820. if (offset == 0) {
  821. annotation->MarkEmptyStruct();
  822. }
  823. return offset;
  824. }
  825. static bool IsElementInputOutputType(QualType Ty) {
  826. return Ty->isBuiltinType() || hlsl::IsHLSLVecMatType(Ty) || Ty->isEnumeralType();
  827. }
  828. // Return the size for constant buffer of each decl.
  829. unsigned CGMSHLSLRuntime::AddTypeAnnotation(QualType Ty,
  830. DxilTypeSystem &dxilTypeSys,
  831. unsigned &arrayEltSize) {
  832. QualType paramTy = Ty.getCanonicalType();
  833. if (const ReferenceType *RefType = dyn_cast<ReferenceType>(paramTy))
  834. paramTy = RefType->getPointeeType();
  835. // Get size.
  836. llvm::Type *Type = CGM.getTypes().ConvertType(paramTy);
  837. unsigned size = dataLayout.getTypeAllocSize(Type);
  838. if (IsHLSLMatType(Ty)) {
  839. unsigned col, row;
  840. llvm::Type *EltTy = HLMatrixLower::GetMatrixInfo(Type, col, row);
  841. bool b64Bit = dataLayout.getTypeAllocSize(EltTy) == 8;
  842. size = GetMatrixSizeInCB(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor,
  843. b64Bit);
  844. }
  845. // Skip element types.
  846. if (IsElementInputOutputType(paramTy))
  847. return size;
  848. else if (IsHLSLStreamOutputType(Ty)) {
  849. return AddTypeAnnotation(GetHLSLOutputPatchElementType(Ty), dxilTypeSys,
  850. arrayEltSize);
  851. } else if (IsHLSLInputPatchType(Ty))
  852. return AddTypeAnnotation(GetHLSLInputPatchElementType(Ty), dxilTypeSys,
  853. arrayEltSize);
  854. else if (IsHLSLOutputPatchType(Ty))
  855. return AddTypeAnnotation(GetHLSLOutputPatchElementType(Ty), dxilTypeSys,
  856. arrayEltSize);
  857. else if (const RecordType *RT = paramTy->getAsStructureType()) {
  858. RecordDecl *RD = RT->getDecl();
  859. llvm::StructType *ST = CGM.getTypes().ConvertRecordDeclType(RD);
  860. // Skip if already created.
  861. if (DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST)) {
  862. unsigned structSize = annotation->GetCBufferSize();
  863. return structSize;
  864. }
  865. DxilStructAnnotation *annotation = dxilTypeSys.AddStructAnnotation(ST);
  866. return ConstructStructAnnotation(annotation, RD, dxilTypeSys);
  867. } else if (const RecordType *RT = dyn_cast<RecordType>(paramTy)) {
  868. // For this pointer.
  869. RecordDecl *RD = RT->getDecl();
  870. llvm::StructType *ST = CGM.getTypes().ConvertRecordDeclType(RD);
  871. // Skip if already created.
  872. if (DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST)) {
  873. unsigned structSize = annotation->GetCBufferSize();
  874. return structSize;
  875. }
  876. DxilStructAnnotation *annotation = dxilTypeSys.AddStructAnnotation(ST);
  877. return ConstructStructAnnotation(annotation, RD, dxilTypeSys);
  878. } else if (IsHLSLResourceType(Ty)) {
  879. // Save result type info.
  880. AddTypeAnnotation(GetHLSLResourceResultType(Ty), dxilTypeSys, arrayEltSize);
  881. // Resource don't count for cbuffer size.
  882. return 0;
  883. } else {
  884. unsigned arraySize = 0;
  885. QualType arrayElementTy = Ty;
  886. if (Ty->isConstantArrayType()) {
  887. const ConstantArrayType *arrayTy =
  888. CGM.getContext().getAsConstantArrayType(Ty);
  889. DXASSERT(arrayTy != nullptr, "Must array type here");
  890. arraySize = arrayTy->getSize().getLimitedValue();
  891. arrayElementTy = arrayTy->getElementType();
  892. }
  893. else if (Ty->isIncompleteArrayType()) {
  894. const IncompleteArrayType *arrayTy = CGM.getContext().getAsIncompleteArrayType(Ty);
  895. arrayElementTy = arrayTy->getElementType();
  896. } else
  897. DXASSERT(0, "Must array type here");
  898. unsigned elementSize = AddTypeAnnotation(arrayElementTy, dxilTypeSys, arrayEltSize);
  899. // Only set arrayEltSize once.
  900. if (arrayEltSize == 0)
  901. arrayEltSize = elementSize;
  902. // Align to 4 * 4bytes.
  903. unsigned alignedSize = (elementSize + 15) & 0xfffffff0;
  904. return alignedSize * (arraySize - 1) + elementSize;
  905. }
  906. }
  907. static DxilResource::Kind KeywordToKind(StringRef keyword) {
  908. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  909. // compare)
  910. if (keyword == "Texture1D" || keyword == "RWTexture1D" || keyword == "RasterizerOrderedTexture1D")
  911. return DxilResource::Kind::Texture1D;
  912. if (keyword == "Texture2D" || keyword == "RWTexture2D" || keyword == "RasterizerOrderedTexture2D")
  913. return DxilResource::Kind::Texture2D;
  914. if (keyword == "Texture2DMS" || keyword == "RWTexture2DMS")
  915. return DxilResource::Kind::Texture2DMS;
  916. if (keyword == "Texture3D" || keyword == "RWTexture3D" || keyword == "RasterizerOrderedTexture3D")
  917. return DxilResource::Kind::Texture3D;
  918. if (keyword == "TextureCube" || keyword == "RWTextureCube")
  919. return DxilResource::Kind::TextureCube;
  920. if (keyword == "Texture1DArray" || keyword == "RWTexture1DArray" || keyword == "RasterizerOrderedTexture1DArray")
  921. return DxilResource::Kind::Texture1DArray;
  922. if (keyword == "Texture2DArray" || keyword == "RWTexture2DArray" || keyword == "RasterizerOrderedTexture2DArray")
  923. return DxilResource::Kind::Texture2DArray;
  924. if (keyword == "Texture2DMSArray" || keyword == "RWTexture2DMSArray")
  925. return DxilResource::Kind::Texture2DMSArray;
  926. if (keyword == "TextureCubeArray" || keyword == "RWTextureCubeArray")
  927. return DxilResource::Kind::TextureCubeArray;
  928. if (keyword == "ByteAddressBuffer" || keyword == "RWByteAddressBuffer" || keyword == "RasterizerOrderedByteAddressBuffer")
  929. return DxilResource::Kind::RawBuffer;
  930. if (keyword == "StructuredBuffer" || keyword == "RWStructuredBuffer" || keyword == "RasterizerOrderedStructuredBuffer")
  931. return DxilResource::Kind::StructuredBuffer;
  932. if (keyword == "AppendStructuredBuffer" || keyword == "ConsumeStructuredBuffer")
  933. return DxilResource::Kind::StructuredBuffer;
  934. // TODO: this is not efficient.
  935. bool isBuffer = keyword == "Buffer";
  936. isBuffer |= keyword == "RWBuffer";
  937. isBuffer |= keyword == "RasterizerOrderedBuffer";
  938. if (isBuffer)
  939. return DxilResource::Kind::TypedBuffer;
  940. return DxilResource::Kind::Invalid;
  941. }
  942. void CGMSHLSLRuntime::AddHLSLFunctionInfo(Function *F, const FunctionDecl *FD) {
  943. // Add hlsl intrinsic attr
  944. unsigned intrinsicOpcode;
  945. StringRef intrinsicGroup;
  946. if (hlsl::GetIntrinsicOp(FD, intrinsicOpcode, intrinsicGroup)) {
  947. AddHLSLIntrinsicOpcodeToFunction(F, intrinsicOpcode);
  948. F->addFnAttr(hlsl::HLPrefix, intrinsicGroup);
  949. // Save resource type annotation.
  950. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  951. const CXXRecordDecl *RD = MD->getParent();
  952. // For nested case like sample_slice_type.
  953. if (const CXXRecordDecl *PRD =
  954. dyn_cast<CXXRecordDecl>(RD->getDeclContext())) {
  955. RD = PRD;
  956. }
  957. QualType recordTy = MD->getASTContext().getRecordType(RD);
  958. hlsl::DxilResourceBase::Class resClass = TypeToClass(recordTy);
  959. llvm::Type *Ty = CGM.getTypes().ConvertType(recordTy);
  960. llvm::FunctionType *FT = F->getFunctionType();
  961. // Save resource type metadata.
  962. switch (resClass) {
  963. case DXIL::ResourceClass::UAV: {
  964. MDNode *MD = GetOrAddResTypeMD(recordTy);
  965. DXASSERT(MD, "else invalid resource type");
  966. resMetadataMap[Ty] = MD;
  967. } break;
  968. case DXIL::ResourceClass::SRV: {
  969. MDNode *Meta = GetOrAddResTypeMD(recordTy);
  970. DXASSERT(Meta, "else invalid resource type");
  971. resMetadataMap[Ty] = Meta;
  972. if (FT->getNumParams() > 1) {
  973. QualType paramTy = MD->getParamDecl(0)->getType();
  974. // Add sampler type.
  975. if (TypeToClass(paramTy) == DXIL::ResourceClass::Sampler) {
  976. llvm::Type *Ty = FT->getParamType(1)->getPointerElementType();
  977. MDNode *MD = GetOrAddResTypeMD(paramTy);
  978. DXASSERT(MD, "else invalid resource type");
  979. resMetadataMap[Ty] = MD;
  980. }
  981. }
  982. } break;
  983. default:
  984. // Skip OutputStream for GS.
  985. break;
  986. }
  987. }
  988. StringRef lower;
  989. if (hlsl::GetIntrinsicLowering(FD, lower))
  990. hlsl::SetHLLowerStrategy(F, lower);
  991. // Don't need to add FunctionQual for intrinsic function.
  992. return;
  993. }
  994. if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::FTZ) {
  995. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValueFtzString);
  996. }
  997. else if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::Preserve) {
  998. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValuePreserveString);
  999. }
  1000. else if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::Any) {
  1001. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValueAnyString);
  1002. }
  1003. // Set entry function
  1004. const std::string &entryName = m_pHLModule->GetEntryFunctionName();
  1005. bool isEntry = FD->getNameAsString() == entryName;
  1006. if (isEntry) {
  1007. Entry.Func = F;
  1008. Entry.SL = FD->getLocation();
  1009. }
  1010. DiagnosticsEngine &Diags = CGM.getDiags();
  1011. std::unique_ptr<DxilFunctionProps> funcProps =
  1012. llvm::make_unique<DxilFunctionProps>();
  1013. funcProps->shaderKind = DXIL::ShaderKind::Invalid;
  1014. bool isCS = false;
  1015. bool isGS = false;
  1016. bool isHS = false;
  1017. bool isDS = false;
  1018. bool isVS = false;
  1019. bool isPS = false;
  1020. if (const HLSLShaderAttr *Attr = FD->getAttr<HLSLShaderAttr>()) {
  1021. // Stage is already validate in HandleDeclAttributeForHLSL.
  1022. // Here just check first letter.
  1023. switch (Attr->getStage()[0]) {
  1024. case 'c':
  1025. isCS = true;
  1026. funcProps->shaderKind = DXIL::ShaderKind::Compute;
  1027. break;
  1028. case 'v':
  1029. isVS = true;
  1030. funcProps->shaderKind = DXIL::ShaderKind::Vertex;
  1031. break;
  1032. case 'h':
  1033. isHS = true;
  1034. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1035. break;
  1036. case 'd':
  1037. isDS = true;
  1038. funcProps->shaderKind = DXIL::ShaderKind::Domain;
  1039. break;
  1040. case 'g':
  1041. isGS = true;
  1042. funcProps->shaderKind = DXIL::ShaderKind::Geometry;
  1043. break;
  1044. case 'p':
  1045. isPS = true;
  1046. funcProps->shaderKind = DXIL::ShaderKind::Pixel;
  1047. break;
  1048. default: {
  1049. unsigned DiagID = Diags.getCustomDiagID(
  1050. DiagnosticsEngine::Error, "Invalid profile for shader attribute");
  1051. Diags.Report(Attr->getLocation(), DiagID);
  1052. } break;
  1053. }
  1054. }
  1055. // Save patch constant function to patchConstantFunctionMap.
  1056. bool isPatchConstantFunction = false;
  1057. if (!isEntry && CGM.getContext().IsPatchConstantFunctionDecl(FD)) {
  1058. isPatchConstantFunction = true;
  1059. auto &PCI = patchConstantFunctionMap[FD->getName()];
  1060. PCI.SL = FD->getLocation();
  1061. PCI.Func = F;
  1062. ++PCI.NumOverloads;
  1063. for (ParmVarDecl *parmDecl : FD->parameters()) {
  1064. QualType Ty = parmDecl->getType();
  1065. if (IsHLSLOutputPatchType(Ty)) {
  1066. funcProps->ShaderProps.HS.outputControlPoints =
  1067. GetHLSLOutputPatchCount(parmDecl->getType());
  1068. } else if (IsHLSLInputPatchType(Ty)) {
  1069. funcProps->ShaderProps.HS.inputControlPoints =
  1070. GetHLSLInputPatchCount(parmDecl->getType());
  1071. }
  1072. }
  1073. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1074. }
  1075. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  1076. if (isEntry) {
  1077. funcProps->shaderKind = SM->GetKind();
  1078. }
  1079. // Geometry shader.
  1080. if (const HLSLMaxVertexCountAttr *Attr =
  1081. FD->getAttr<HLSLMaxVertexCountAttr>()) {
  1082. isGS = true;
  1083. funcProps->shaderKind = DXIL::ShaderKind::Geometry;
  1084. funcProps->ShaderProps.GS.maxVertexCount = Attr->getCount();
  1085. funcProps->ShaderProps.GS.inputPrimitive = DXIL::InputPrimitive::Undefined;
  1086. if (isEntry && !SM->IsGS()) {
  1087. unsigned DiagID =
  1088. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1089. "attribute maxvertexcount only valid for GS.");
  1090. Diags.Report(Attr->getLocation(), DiagID);
  1091. return;
  1092. }
  1093. }
  1094. if (const HLSLInstanceAttr *Attr = FD->getAttr<HLSLInstanceAttr>()) {
  1095. unsigned instanceCount = Attr->getCount();
  1096. funcProps->ShaderProps.GS.instanceCount = instanceCount;
  1097. if (isEntry && !SM->IsGS()) {
  1098. unsigned DiagID =
  1099. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1100. "attribute maxvertexcount only valid for GS.");
  1101. Diags.Report(Attr->getLocation(), DiagID);
  1102. return;
  1103. }
  1104. } else {
  1105. // Set default instance count.
  1106. if (isGS)
  1107. funcProps->ShaderProps.GS.instanceCount = 1;
  1108. }
  1109. // Computer shader.
  1110. if (const HLSLNumThreadsAttr *Attr = FD->getAttr<HLSLNumThreadsAttr>()) {
  1111. isCS = true;
  1112. funcProps->shaderKind = DXIL::ShaderKind::Compute;
  1113. funcProps->ShaderProps.CS.numThreads[0] = Attr->getX();
  1114. funcProps->ShaderProps.CS.numThreads[1] = Attr->getY();
  1115. funcProps->ShaderProps.CS.numThreads[2] = Attr->getZ();
  1116. if (isEntry && !SM->IsCS()) {
  1117. unsigned DiagID = Diags.getCustomDiagID(
  1118. DiagnosticsEngine::Error, "attribute numthreads only valid for CS.");
  1119. Diags.Report(Attr->getLocation(), DiagID);
  1120. return;
  1121. }
  1122. }
  1123. // Hull shader.
  1124. if (const HLSLPatchConstantFuncAttr *Attr =
  1125. FD->getAttr<HLSLPatchConstantFuncAttr>()) {
  1126. if (isEntry && !SM->IsHS()) {
  1127. unsigned DiagID = Diags.getCustomDiagID(
  1128. DiagnosticsEngine::Error,
  1129. "attribute patchconstantfunc only valid for HS.");
  1130. Diags.Report(Attr->getLocation(), DiagID);
  1131. return;
  1132. }
  1133. isHS = true;
  1134. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1135. HSEntryPatchConstantFuncAttr[F] = Attr;
  1136. } else {
  1137. // TODO: This is a duplicate check. We also have this check in
  1138. // hlsl::DiagnoseTranslationUnit(clang::Sema*).
  1139. if (isEntry && SM->IsHS()) {
  1140. unsigned DiagID = Diags.getCustomDiagID(
  1141. DiagnosticsEngine::Error,
  1142. "HS entry point must have the patchconstantfunc attribute");
  1143. Diags.Report(FD->getLocation(), DiagID);
  1144. return;
  1145. }
  1146. }
  1147. if (const HLSLOutputControlPointsAttr *Attr =
  1148. FD->getAttr<HLSLOutputControlPointsAttr>()) {
  1149. if (isHS) {
  1150. funcProps->ShaderProps.HS.outputControlPoints = Attr->getCount();
  1151. } else if (isEntry && !SM->IsHS()) {
  1152. unsigned DiagID = Diags.getCustomDiagID(
  1153. DiagnosticsEngine::Error,
  1154. "attribute outputcontrolpoints only valid for HS.");
  1155. Diags.Report(Attr->getLocation(), DiagID);
  1156. return;
  1157. }
  1158. }
  1159. if (const HLSLPartitioningAttr *Attr = FD->getAttr<HLSLPartitioningAttr>()) {
  1160. if (isHS) {
  1161. DXIL::TessellatorPartitioning partition =
  1162. StringToPartitioning(Attr->getScheme());
  1163. funcProps->ShaderProps.HS.partition = partition;
  1164. } else if (isEntry && !SM->IsHS()) {
  1165. unsigned DiagID =
  1166. Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  1167. "attribute partitioning only valid for HS.");
  1168. Diags.Report(Attr->getLocation(), DiagID);
  1169. }
  1170. }
  1171. if (const HLSLOutputTopologyAttr *Attr =
  1172. FD->getAttr<HLSLOutputTopologyAttr>()) {
  1173. if (isHS) {
  1174. DXIL::TessellatorOutputPrimitive primitive =
  1175. StringToTessOutputPrimitive(Attr->getTopology());
  1176. funcProps->ShaderProps.HS.outputPrimitive = primitive;
  1177. } else if (isEntry && !SM->IsHS()) {
  1178. unsigned DiagID =
  1179. Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  1180. "attribute outputtopology only valid for HS.");
  1181. Diags.Report(Attr->getLocation(), DiagID);
  1182. }
  1183. }
  1184. if (isHS) {
  1185. funcProps->ShaderProps.HS.maxTessFactor = DXIL::kHSMaxTessFactorUpperBound;
  1186. }
  1187. if (const HLSLMaxTessFactorAttr *Attr =
  1188. FD->getAttr<HLSLMaxTessFactorAttr>()) {
  1189. if (isHS) {
  1190. // TODO: change getFactor to return float.
  1191. llvm::APInt intV(32, Attr->getFactor());
  1192. funcProps->ShaderProps.HS.maxTessFactor = intV.bitsToFloat();
  1193. } else if (isEntry && !SM->IsHS()) {
  1194. unsigned DiagID =
  1195. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1196. "attribute maxtessfactor only valid for HS.");
  1197. Diags.Report(Attr->getLocation(), DiagID);
  1198. return;
  1199. }
  1200. }
  1201. // Hull or domain shader.
  1202. if (const HLSLDomainAttr *Attr = FD->getAttr<HLSLDomainAttr>()) {
  1203. if (isEntry && !SM->IsHS() && !SM->IsDS()) {
  1204. unsigned DiagID =
  1205. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1206. "attribute domain only valid for HS or DS.");
  1207. Diags.Report(Attr->getLocation(), DiagID);
  1208. return;
  1209. }
  1210. isDS = !isHS;
  1211. if (isDS)
  1212. funcProps->shaderKind = DXIL::ShaderKind::Domain;
  1213. DXIL::TessellatorDomain domain = StringToDomain(Attr->getDomainType());
  1214. if (isHS)
  1215. funcProps->ShaderProps.HS.domain = domain;
  1216. else
  1217. funcProps->ShaderProps.DS.domain = domain;
  1218. }
  1219. // Vertex shader.
  1220. if (const HLSLClipPlanesAttr *Attr = FD->getAttr<HLSLClipPlanesAttr>()) {
  1221. if (isEntry && !SM->IsVS()) {
  1222. unsigned DiagID = Diags.getCustomDiagID(
  1223. DiagnosticsEngine::Error, "attribute clipplane only valid for VS.");
  1224. Diags.Report(Attr->getLocation(), DiagID);
  1225. return;
  1226. }
  1227. isVS = true;
  1228. // The real job is done at EmitHLSLFunctionProlog where debug info is
  1229. // available. Only set shader kind here.
  1230. funcProps->shaderKind = DXIL::ShaderKind::Vertex;
  1231. }
  1232. // Pixel shader.
  1233. if (const HLSLEarlyDepthStencilAttr *Attr =
  1234. FD->getAttr<HLSLEarlyDepthStencilAttr>()) {
  1235. if (isEntry && !SM->IsPS()) {
  1236. unsigned DiagID = Diags.getCustomDiagID(
  1237. DiagnosticsEngine::Error,
  1238. "attribute earlydepthstencil only valid for PS.");
  1239. Diags.Report(Attr->getLocation(), DiagID);
  1240. return;
  1241. }
  1242. isPS = true;
  1243. funcProps->ShaderProps.PS.EarlyDepthStencil = true;
  1244. funcProps->shaderKind = DXIL::ShaderKind::Pixel;
  1245. }
  1246. const unsigned profileAttributes = isCS + isHS + isDS + isGS + isVS + isPS;
  1247. // TODO: check this in front-end and report error.
  1248. DXASSERT(profileAttributes < 2, "profile attributes are mutual exclusive");
  1249. if (isEntry) {
  1250. switch (funcProps->shaderKind) {
  1251. case ShaderModel::Kind::Compute:
  1252. case ShaderModel::Kind::Hull:
  1253. case ShaderModel::Kind::Domain:
  1254. case ShaderModel::Kind::Geometry:
  1255. case ShaderModel::Kind::Vertex:
  1256. case ShaderModel::Kind::Pixel:
  1257. DXASSERT(funcProps->shaderKind == SM->GetKind(),
  1258. "attribute profile not match entry function profile");
  1259. break;
  1260. }
  1261. }
  1262. DxilFunctionAnnotation *FuncAnnotation =
  1263. m_pHLModule->AddFunctionAnnotation(F);
  1264. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  1265. // Param Info
  1266. unsigned streamIndex = 0;
  1267. unsigned inputPatchCount = 0;
  1268. unsigned outputPatchCount = 0;
  1269. unsigned ArgNo = 0;
  1270. unsigned ParmIdx = 0;
  1271. if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FD)) {
  1272. QualType ThisTy = MethodDecl->getThisType(FD->getASTContext());
  1273. DxilParameterAnnotation &paramAnnotation =
  1274. FuncAnnotation->GetParameterAnnotation(ArgNo++);
  1275. // Construct annoation for this pointer.
  1276. ConstructFieldAttributedAnnotation(paramAnnotation, ThisTy,
  1277. bDefaultRowMajor);
  1278. }
  1279. // Ret Info
  1280. QualType retTy = FD->getReturnType();
  1281. DxilParameterAnnotation *pRetTyAnnotation = nullptr;
  1282. if (F->getReturnType()->isVoidTy() && !retTy->isVoidType()) {
  1283. // SRet.
  1284. pRetTyAnnotation = &FuncAnnotation->GetParameterAnnotation(ArgNo++);
  1285. } else {
  1286. pRetTyAnnotation = &FuncAnnotation->GetRetTypeAnnotation();
  1287. }
  1288. DxilParameterAnnotation &retTyAnnotation = *pRetTyAnnotation;
  1289. // keep Undefined here, we cannot decide for struct
  1290. retTyAnnotation.SetInterpolationMode(
  1291. GetInterpMode(FD, CompType::Kind::Invalid, /*bKeepUndefined*/ true)
  1292. .GetKind());
  1293. SourceLocation retTySemanticLoc = SetSemantic(FD, retTyAnnotation);
  1294. retTyAnnotation.SetParamInputQual(DxilParamInputQual::Out);
  1295. if (isEntry) {
  1296. CheckParameterAnnotation(retTySemanticLoc, retTyAnnotation,
  1297. /*isPatchConstantFunction*/ false);
  1298. }
  1299. ConstructFieldAttributedAnnotation(retTyAnnotation, retTy, bDefaultRowMajor);
  1300. if (FD->hasAttr<HLSLPreciseAttr>())
  1301. retTyAnnotation.SetPrecise();
  1302. for (; ArgNo < F->arg_size(); ++ArgNo, ++ParmIdx) {
  1303. DxilParameterAnnotation &paramAnnotation =
  1304. FuncAnnotation->GetParameterAnnotation(ArgNo);
  1305. const ParmVarDecl *parmDecl = FD->getParamDecl(ParmIdx);
  1306. ConstructFieldAttributedAnnotation(paramAnnotation, parmDecl->getType(),
  1307. bDefaultRowMajor);
  1308. if (parmDecl->hasAttr<HLSLPreciseAttr>())
  1309. paramAnnotation.SetPrecise();
  1310. // keep Undefined here, we cannot decide for struct
  1311. InterpolationMode paramIM =
  1312. GetInterpMode(parmDecl, CompType::Kind::Invalid, KeepUndefinedTrue);
  1313. paramAnnotation.SetInterpolationMode(paramIM);
  1314. SourceLocation paramSemanticLoc = SetSemantic(parmDecl, paramAnnotation);
  1315. DxilParamInputQual dxilInputQ = DxilParamInputQual::In;
  1316. if (parmDecl->hasAttr<HLSLInOutAttr>())
  1317. dxilInputQ = DxilParamInputQual::Inout;
  1318. else if (parmDecl->hasAttr<HLSLOutAttr>())
  1319. dxilInputQ = DxilParamInputQual::Out;
  1320. if (parmDecl->hasAttr<HLSLOutAttr>() && parmDecl->hasAttr<HLSLInAttr>())
  1321. dxilInputQ = DxilParamInputQual::Inout;
  1322. DXIL::InputPrimitive inputPrimitive = DXIL::InputPrimitive::Undefined;
  1323. if (IsHLSLOutputPatchType(parmDecl->getType())) {
  1324. outputPatchCount++;
  1325. if (dxilInputQ != DxilParamInputQual::In) {
  1326. unsigned DiagID = Diags.getCustomDiagID(
  1327. DiagnosticsEngine::Error,
  1328. "OutputPatch should not be out/inout parameter");
  1329. Diags.Report(parmDecl->getLocation(), DiagID);
  1330. continue;
  1331. }
  1332. dxilInputQ = DxilParamInputQual::OutputPatch;
  1333. if (isDS)
  1334. funcProps->ShaderProps.DS.inputControlPoints =
  1335. GetHLSLOutputPatchCount(parmDecl->getType());
  1336. } else if (IsHLSLInputPatchType(parmDecl->getType())) {
  1337. inputPatchCount++;
  1338. if (dxilInputQ != DxilParamInputQual::In) {
  1339. unsigned DiagID = Diags.getCustomDiagID(
  1340. DiagnosticsEngine::Error,
  1341. "InputPatch should not be out/inout parameter");
  1342. Diags.Report(parmDecl->getLocation(), DiagID);
  1343. continue;
  1344. }
  1345. dxilInputQ = DxilParamInputQual::InputPatch;
  1346. if (isHS) {
  1347. funcProps->ShaderProps.HS.inputControlPoints =
  1348. GetHLSLInputPatchCount(parmDecl->getType());
  1349. } else if (isGS) {
  1350. inputPrimitive = (DXIL::InputPrimitive)(
  1351. (unsigned)DXIL::InputPrimitive::ControlPointPatch1 +
  1352. GetHLSLInputPatchCount(parmDecl->getType()) - 1);
  1353. }
  1354. } else if (IsHLSLStreamOutputType(parmDecl->getType())) {
  1355. // TODO: validation this at ASTContext::getFunctionType in
  1356. // AST/ASTContext.cpp
  1357. DXASSERT(dxilInputQ == DxilParamInputQual::Inout,
  1358. "stream output parameter must be inout");
  1359. switch (streamIndex) {
  1360. case 0:
  1361. dxilInputQ = DxilParamInputQual::OutStream0;
  1362. break;
  1363. case 1:
  1364. dxilInputQ = DxilParamInputQual::OutStream1;
  1365. break;
  1366. case 2:
  1367. dxilInputQ = DxilParamInputQual::OutStream2;
  1368. break;
  1369. case 3:
  1370. default:
  1371. // TODO: validation this at ASTContext::getFunctionType in
  1372. // AST/ASTContext.cpp
  1373. DXASSERT(streamIndex == 3, "stream number out of bound");
  1374. dxilInputQ = DxilParamInputQual::OutStream3;
  1375. break;
  1376. }
  1377. DXIL::PrimitiveTopology &streamTopology =
  1378. funcProps->ShaderProps.GS.streamPrimitiveTopologies[streamIndex];
  1379. if (IsHLSLPointStreamType(parmDecl->getType()))
  1380. streamTopology = DXIL::PrimitiveTopology::PointList;
  1381. else if (IsHLSLLineStreamType(parmDecl->getType()))
  1382. streamTopology = DXIL::PrimitiveTopology::LineStrip;
  1383. else {
  1384. DXASSERT(IsHLSLTriangleStreamType(parmDecl->getType()),
  1385. "invalid StreamType");
  1386. streamTopology = DXIL::PrimitiveTopology::TriangleStrip;
  1387. }
  1388. if (streamIndex > 0) {
  1389. bool bAllPoint =
  1390. streamTopology == DXIL::PrimitiveTopology::PointList &&
  1391. funcProps->ShaderProps.GS.streamPrimitiveTopologies[0] ==
  1392. DXIL::PrimitiveTopology::PointList;
  1393. if (!bAllPoint) {
  1394. DiagnosticsEngine &Diags = CGM.getDiags();
  1395. unsigned DiagID = Diags.getCustomDiagID(
  1396. DiagnosticsEngine::Error, "when multiple GS output streams are "
  1397. "used they must be pointlists.");
  1398. Diags.Report(FD->getLocation(), DiagID);
  1399. }
  1400. }
  1401. streamIndex++;
  1402. }
  1403. unsigned GsInputArrayDim = 0;
  1404. if (parmDecl->hasAttr<HLSLTriangleAttr>()) {
  1405. inputPrimitive = DXIL::InputPrimitive::Triangle;
  1406. GsInputArrayDim = 3;
  1407. } else if (parmDecl->hasAttr<HLSLTriangleAdjAttr>()) {
  1408. inputPrimitive = DXIL::InputPrimitive::TriangleWithAdjacency;
  1409. GsInputArrayDim = 6;
  1410. } else if (parmDecl->hasAttr<HLSLPointAttr>()) {
  1411. inputPrimitive = DXIL::InputPrimitive::Point;
  1412. GsInputArrayDim = 1;
  1413. } else if (parmDecl->hasAttr<HLSLLineAdjAttr>()) {
  1414. inputPrimitive = DXIL::InputPrimitive::LineWithAdjacency;
  1415. GsInputArrayDim = 4;
  1416. } else if (parmDecl->hasAttr<HLSLLineAttr>()) {
  1417. inputPrimitive = DXIL::InputPrimitive::Line;
  1418. GsInputArrayDim = 2;
  1419. }
  1420. if (inputPrimitive != DXIL::InputPrimitive::Undefined) {
  1421. // Set to InputPrimitive for GS.
  1422. dxilInputQ = DxilParamInputQual::InputPrimitive;
  1423. if (funcProps->ShaderProps.GS.inputPrimitive ==
  1424. DXIL::InputPrimitive::Undefined) {
  1425. funcProps->ShaderProps.GS.inputPrimitive = inputPrimitive;
  1426. } else if (funcProps->ShaderProps.GS.inputPrimitive != inputPrimitive) {
  1427. DiagnosticsEngine &Diags = CGM.getDiags();
  1428. unsigned DiagID = Diags.getCustomDiagID(
  1429. DiagnosticsEngine::Error, "input parameter conflicts with geometry "
  1430. "specifier of previous input parameters");
  1431. Diags.Report(parmDecl->getLocation(), DiagID);
  1432. }
  1433. }
  1434. if (GsInputArrayDim != 0) {
  1435. QualType Ty = parmDecl->getType();
  1436. if (!Ty->isConstantArrayType()) {
  1437. DiagnosticsEngine &Diags = CGM.getDiags();
  1438. unsigned DiagID = Diags.getCustomDiagID(
  1439. DiagnosticsEngine::Error,
  1440. "input types for geometry shader must be constant size arrays");
  1441. Diags.Report(parmDecl->getLocation(), DiagID);
  1442. } else {
  1443. const ConstantArrayType *CAT = cast<ConstantArrayType>(Ty);
  1444. if (CAT->getSize().getLimitedValue() != GsInputArrayDim) {
  1445. StringRef primtiveNames[] = {
  1446. "invalid", // 0
  1447. "point", // 1
  1448. "line", // 2
  1449. "triangle", // 3
  1450. "lineadj", // 4
  1451. "invalid", // 5
  1452. "triangleadj", // 6
  1453. };
  1454. DXASSERT(GsInputArrayDim < llvm::array_lengthof(primtiveNames),
  1455. "Invalid array dim");
  1456. DiagnosticsEngine &Diags = CGM.getDiags();
  1457. unsigned DiagID = Diags.getCustomDiagID(
  1458. DiagnosticsEngine::Error, "array dimension for %0 must be %1");
  1459. Diags.Report(parmDecl->getLocation(), DiagID)
  1460. << primtiveNames[GsInputArrayDim] << GsInputArrayDim;
  1461. }
  1462. }
  1463. }
  1464. paramAnnotation.SetParamInputQual(dxilInputQ);
  1465. if (isEntry) {
  1466. CheckParameterAnnotation(paramSemanticLoc, paramAnnotation,
  1467. /*isPatchConstantFunction*/ false);
  1468. }
  1469. }
  1470. if (inputPatchCount > 1) {
  1471. DiagnosticsEngine &Diags = CGM.getDiags();
  1472. unsigned DiagID = Diags.getCustomDiagID(
  1473. DiagnosticsEngine::Error, "may only have one InputPatch parameter");
  1474. Diags.Report(FD->getLocation(), DiagID);
  1475. }
  1476. if (outputPatchCount > 1) {
  1477. DiagnosticsEngine &Diags = CGM.getDiags();
  1478. unsigned DiagID = Diags.getCustomDiagID(
  1479. DiagnosticsEngine::Error, "may only have one OutputPatch parameter");
  1480. Diags.Report(FD->getLocation(), DiagID);
  1481. }
  1482. // Type annotation for parameters and return type.
  1483. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  1484. unsigned arrayEltSize = 0;
  1485. AddTypeAnnotation(FD->getReturnType(), dxilTypeSys, arrayEltSize);
  1486. // Type annotation for this pointer.
  1487. if (const CXXMethodDecl *MFD = dyn_cast<CXXMethodDecl>(FD)) {
  1488. const CXXRecordDecl *RD = MFD->getParent();
  1489. QualType Ty = CGM.getContext().getTypeDeclType(RD);
  1490. AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  1491. }
  1492. for (const ValueDecl *param : FD->params()) {
  1493. QualType Ty = param->getType();
  1494. AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  1495. }
  1496. // Only add functionProps when exist.
  1497. if (profileAttributes || isEntry)
  1498. m_pHLModule->AddDxilFunctionProps(F, funcProps);
  1499. if (isPatchConstantFunction)
  1500. patchConstantFunctionPropsMap[F] = std::move(funcProps);
  1501. // Save F to entry map.
  1502. if (profileAttributes) {
  1503. if (entryFunctionMap.count(FD->getName())) {
  1504. DiagnosticsEngine &Diags = CGM.getDiags();
  1505. unsigned DiagID = Diags.getCustomDiagID(
  1506. DiagnosticsEngine::Error,
  1507. "redefinition of %0");
  1508. Diags.Report(FD->getLocStart(), DiagID) << FD->getName();
  1509. }
  1510. auto &Entry = entryFunctionMap[FD->getNameAsString()];
  1511. Entry.SL = FD->getLocation();
  1512. Entry.Func= F;
  1513. }
  1514. // Add target-dependent experimental function attributes
  1515. for (const auto &Attr : FD->specific_attrs<HLSLExperimentalAttr>()) {
  1516. F->addFnAttr(Twine("exp-", Attr->getName()).str(), Attr->getValue());
  1517. }
  1518. }
  1519. void CGMSHLSLRuntime::EmitHLSLFunctionProlog(Function *F, const FunctionDecl *FD) {
  1520. // Support clip plane need debug info which not available when create function attribute.
  1521. if (const HLSLClipPlanesAttr *Attr = FD->getAttr<HLSLClipPlanesAttr>()) {
  1522. DxilFunctionProps &funcProps = m_pHLModule->GetDxilFunctionProps(F);
  1523. // Initialize to null.
  1524. memset(funcProps.ShaderProps.VS.clipPlanes, 0, sizeof(funcProps.ShaderProps.VS.clipPlanes));
  1525. // Create global for each clip plane, and use the clip plane val as init val.
  1526. auto AddClipPlane = [&](Expr *clipPlane, unsigned idx) {
  1527. if (DeclRefExpr *decl = dyn_cast<DeclRefExpr>(clipPlane)) {
  1528. const VarDecl *VD = cast<VarDecl>(decl->getDecl());
  1529. Constant *clipPlaneVal = CGM.GetAddrOfGlobalVar(VD);
  1530. funcProps.ShaderProps.VS.clipPlanes[idx] = clipPlaneVal;
  1531. if (m_bDebugInfo) {
  1532. CodeGenFunction CGF(CGM);
  1533. ApplyDebugLocation applyDebugLoc(CGF, clipPlane);
  1534. debugInfoMap[clipPlaneVal] = CGF.Builder.getCurrentDebugLocation();
  1535. }
  1536. } else {
  1537. // Must be a MemberExpr.
  1538. const MemberExpr *ME = cast<MemberExpr>(clipPlane);
  1539. CodeGenFunction CGF(CGM);
  1540. CodeGen::LValue LV = CGF.EmitMemberExpr(ME);
  1541. Value *addr = LV.getAddress();
  1542. funcProps.ShaderProps.VS.clipPlanes[idx] = cast<Constant>(addr);
  1543. if (m_bDebugInfo) {
  1544. CodeGenFunction CGF(CGM);
  1545. ApplyDebugLocation applyDebugLoc(CGF, clipPlane);
  1546. debugInfoMap[addr] = CGF.Builder.getCurrentDebugLocation();
  1547. }
  1548. }
  1549. };
  1550. if (Expr *clipPlane = Attr->getClipPlane1())
  1551. AddClipPlane(clipPlane, 0);
  1552. if (Expr *clipPlane = Attr->getClipPlane2())
  1553. AddClipPlane(clipPlane, 1);
  1554. if (Expr *clipPlane = Attr->getClipPlane3())
  1555. AddClipPlane(clipPlane, 2);
  1556. if (Expr *clipPlane = Attr->getClipPlane4())
  1557. AddClipPlane(clipPlane, 3);
  1558. if (Expr *clipPlane = Attr->getClipPlane5())
  1559. AddClipPlane(clipPlane, 4);
  1560. if (Expr *clipPlane = Attr->getClipPlane6())
  1561. AddClipPlane(clipPlane, 5);
  1562. clipPlaneFuncList.emplace_back(F);
  1563. }
  1564. }
  1565. void CGMSHLSLRuntime::AddControlFlowHint(CodeGenFunction &CGF, const Stmt &S,
  1566. llvm::TerminatorInst *TI,
  1567. ArrayRef<const Attr *> Attrs) {
  1568. // Build hints.
  1569. bool bNoBranchFlatten = true;
  1570. bool bBranch = false;
  1571. bool bFlatten = false;
  1572. std::vector<DXIL::ControlFlowHint> hints;
  1573. for (const auto *Attr : Attrs) {
  1574. if (isa<HLSLBranchAttr>(Attr)) {
  1575. hints.emplace_back(DXIL::ControlFlowHint::Branch);
  1576. bNoBranchFlatten = false;
  1577. bBranch = true;
  1578. }
  1579. else if (isa<HLSLFlattenAttr>(Attr)) {
  1580. hints.emplace_back(DXIL::ControlFlowHint::Flatten);
  1581. bNoBranchFlatten = false;
  1582. bFlatten = true;
  1583. } else if (isa<HLSLForceCaseAttr>(Attr)) {
  1584. if (isa<SwitchStmt>(&S)) {
  1585. hints.emplace_back(DXIL::ControlFlowHint::ForceCase);
  1586. }
  1587. }
  1588. // Ignore fastopt, allow_uav_condition and call for now.
  1589. }
  1590. if (bNoBranchFlatten) {
  1591. // CHECK control flow option.
  1592. if (CGF.CGM.getCodeGenOpts().HLSLPreferControlFlow)
  1593. hints.emplace_back(DXIL::ControlFlowHint::Branch);
  1594. else if (CGF.CGM.getCodeGenOpts().HLSLAvoidControlFlow)
  1595. hints.emplace_back(DXIL::ControlFlowHint::Flatten);
  1596. }
  1597. if (bFlatten && bBranch) {
  1598. DiagnosticsEngine &Diags = CGM.getDiags();
  1599. unsigned DiagID = Diags.getCustomDiagID(
  1600. DiagnosticsEngine::Error,
  1601. "can't use branch and flatten attributes together");
  1602. Diags.Report(S.getLocStart(), DiagID);
  1603. }
  1604. if (hints.size()) {
  1605. // Add meta data to the instruction.
  1606. MDNode *hintsNode = DxilMDHelper::EmitControlFlowHints(Context, hints);
  1607. TI->setMetadata(DxilMDHelper::kDxilControlFlowHintMDName, hintsNode);
  1608. }
  1609. }
  1610. void CGMSHLSLRuntime::FinishAutoVar(CodeGenFunction &CGF, const VarDecl &D, llvm::Value *V) {
  1611. if (D.hasAttr<HLSLPreciseAttr>()) {
  1612. AllocaInst *AI = cast<AllocaInst>(V);
  1613. HLModule::MarkPreciseAttributeWithMetadata(AI);
  1614. }
  1615. // Add type annotation for local variable.
  1616. DxilTypeSystem &typeSys = m_pHLModule->GetTypeSystem();
  1617. unsigned arrayEltSize = 0;
  1618. AddTypeAnnotation(D.getType(), typeSys, arrayEltSize);
  1619. }
  1620. hlsl::InterpolationMode CGMSHLSLRuntime::GetInterpMode(const Decl *decl,
  1621. CompType compType,
  1622. bool bKeepUndefined) {
  1623. InterpolationMode Interp(
  1624. decl->hasAttr<HLSLNoInterpolationAttr>(), decl->hasAttr<HLSLLinearAttr>(),
  1625. decl->hasAttr<HLSLNoPerspectiveAttr>(), decl->hasAttr<HLSLCentroidAttr>(),
  1626. decl->hasAttr<HLSLSampleAttr>());
  1627. DXASSERT(Interp.IsValid(), "otherwise front-end missing validation");
  1628. if (Interp.IsUndefined() && !bKeepUndefined) {
  1629. // Type-based default: linear for floats, constant for others.
  1630. if (compType.IsFloatTy())
  1631. Interp = InterpolationMode::Kind::Linear;
  1632. else
  1633. Interp = InterpolationMode::Kind::Constant;
  1634. }
  1635. return Interp;
  1636. }
  1637. hlsl::CompType CGMSHLSLRuntime::GetCompType(const BuiltinType *BT) {
  1638. hlsl::CompType ElementType = hlsl::CompType::getInvalid();
  1639. switch (BT->getKind()) {
  1640. case BuiltinType::Bool:
  1641. ElementType = hlsl::CompType::getI1();
  1642. break;
  1643. case BuiltinType::Double:
  1644. ElementType = hlsl::CompType::getF64();
  1645. break;
  1646. case BuiltinType::Float:
  1647. ElementType = hlsl::CompType::getF32();
  1648. break;
  1649. case BuiltinType::Min10Float:
  1650. case BuiltinType::Half:
  1651. ElementType = hlsl::CompType::getF16();
  1652. break;
  1653. case BuiltinType::Int:
  1654. ElementType = hlsl::CompType::getI32();
  1655. break;
  1656. case BuiltinType::LongLong:
  1657. ElementType = hlsl::CompType::getI64();
  1658. break;
  1659. case BuiltinType::Min12Int:
  1660. case BuiltinType::Short:
  1661. ElementType = hlsl::CompType::getI16();
  1662. break;
  1663. case BuiltinType::UInt:
  1664. ElementType = hlsl::CompType::getU32();
  1665. break;
  1666. case BuiltinType::ULongLong:
  1667. ElementType = hlsl::CompType::getU64();
  1668. break;
  1669. case BuiltinType::UShort:
  1670. ElementType = hlsl::CompType::getU16();
  1671. break;
  1672. default:
  1673. llvm_unreachable("unsupported type");
  1674. break;
  1675. }
  1676. return ElementType;
  1677. }
  1678. /// Add resouce to the program
  1679. void CGMSHLSLRuntime::addResource(Decl *D) {
  1680. if (HLSLBufferDecl *BD = dyn_cast<HLSLBufferDecl>(D))
  1681. GetOrCreateCBuffer(BD);
  1682. else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1683. hlsl::DxilResourceBase::Class resClass = TypeToClass(VD->getType());
  1684. // skip decl has init which is resource.
  1685. if (VD->hasInit() && resClass != DXIL::ResourceClass::Invalid)
  1686. return;
  1687. // skip static global.
  1688. if (!VD->isExternallyVisible()) {
  1689. if (VD->hasInit() && VD->getType().isConstQualified()) {
  1690. Expr* InitExp = VD->getInit();
  1691. GlobalVariable *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(VD));
  1692. // Only save const static global of struct type.
  1693. if (GV->getType()->getElementType()->isStructTy()) {
  1694. staticConstGlobalInitMap[InitExp] = GV;
  1695. }
  1696. }
  1697. return;
  1698. }
  1699. if (D->hasAttr<HLSLGroupSharedAttr>()) {
  1700. GlobalVariable *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(VD));
  1701. m_pHLModule->AddGroupSharedVariable(GV);
  1702. return;
  1703. }
  1704. switch (resClass) {
  1705. case hlsl::DxilResourceBase::Class::Sampler:
  1706. AddSampler(VD);
  1707. break;
  1708. case hlsl::DxilResourceBase::Class::UAV:
  1709. case hlsl::DxilResourceBase::Class::SRV:
  1710. AddUAVSRV(VD, resClass);
  1711. break;
  1712. case hlsl::DxilResourceBase::Class::Invalid: {
  1713. // normal global constant, add to global CB
  1714. HLCBuffer &globalCB = GetGlobalCBuffer();
  1715. AddConstant(VD, globalCB);
  1716. break;
  1717. }
  1718. case DXIL::ResourceClass::CBuffer:
  1719. DXASSERT(0, "cbuffer should not be here");
  1720. break;
  1721. }
  1722. }
  1723. }
  1724. // TODO: collect such helper utility functions in one place.
  1725. static DxilResourceBase::Class KeywordToClass(const std::string &keyword) {
  1726. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  1727. // compare)
  1728. if (keyword == "SamplerState")
  1729. return DxilResourceBase::Class::Sampler;
  1730. if (keyword == "SamplerComparisonState")
  1731. return DxilResourceBase::Class::Sampler;
  1732. if (keyword == "ConstantBuffer")
  1733. return DxilResourceBase::Class::CBuffer;
  1734. if (keyword == "TextureBuffer")
  1735. return DxilResourceBase::Class::SRV;
  1736. bool isSRV = keyword == "Buffer";
  1737. isSRV |= keyword == "ByteAddressBuffer";
  1738. isSRV |= keyword == "StructuredBuffer";
  1739. isSRV |= keyword == "Texture1D";
  1740. isSRV |= keyword == "Texture1DArray";
  1741. isSRV |= keyword == "Texture2D";
  1742. isSRV |= keyword == "Texture2DArray";
  1743. isSRV |= keyword == "Texture3D";
  1744. isSRV |= keyword == "TextureCube";
  1745. isSRV |= keyword == "TextureCubeArray";
  1746. isSRV |= keyword == "Texture2DMS";
  1747. isSRV |= keyword == "Texture2DMSArray";
  1748. if (isSRV)
  1749. return DxilResourceBase::Class::SRV;
  1750. bool isUAV = keyword == "RWBuffer";
  1751. isUAV |= keyword == "RWByteAddressBuffer";
  1752. isUAV |= keyword == "RWStructuredBuffer";
  1753. isUAV |= keyword == "RWTexture1D";
  1754. isUAV |= keyword == "RWTexture1DArray";
  1755. isUAV |= keyword == "RWTexture2D";
  1756. isUAV |= keyword == "RWTexture2DArray";
  1757. isUAV |= keyword == "RWTexture3D";
  1758. isUAV |= keyword == "RWTextureCube";
  1759. isUAV |= keyword == "RWTextureCubeArray";
  1760. isUAV |= keyword == "RWTexture2DMS";
  1761. isUAV |= keyword == "RWTexture2DMSArray";
  1762. isUAV |= keyword == "AppendStructuredBuffer";
  1763. isUAV |= keyword == "ConsumeStructuredBuffer";
  1764. isUAV |= keyword == "RasterizerOrderedBuffer";
  1765. isUAV |= keyword == "RasterizerOrderedByteAddressBuffer";
  1766. isUAV |= keyword == "RasterizerOrderedStructuredBuffer";
  1767. isUAV |= keyword == "RasterizerOrderedTexture1D";
  1768. isUAV |= keyword == "RasterizerOrderedTexture1DArray";
  1769. isUAV |= keyword == "RasterizerOrderedTexture2D";
  1770. isUAV |= keyword == "RasterizerOrderedTexture2DArray";
  1771. isUAV |= keyword == "RasterizerOrderedTexture3D";
  1772. if (isUAV)
  1773. return DxilResourceBase::Class::UAV;
  1774. return DxilResourceBase::Class::Invalid;
  1775. }
  1776. // This should probably be refactored to ASTContextHLSL, and follow types
  1777. // rather than do string comparisons.
  1778. DXIL::ResourceClass
  1779. hlsl::GetResourceClassForType(const clang::ASTContext &context,
  1780. clang::QualType Ty) {
  1781. Ty = Ty.getCanonicalType();
  1782. if (const clang::ArrayType *arrayType = context.getAsArrayType(Ty)) {
  1783. return GetResourceClassForType(context, arrayType->getElementType());
  1784. } else if (const RecordType *RT = Ty->getAsStructureType()) {
  1785. return KeywordToClass(RT->getDecl()->getName());
  1786. } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1787. if (const ClassTemplateSpecializationDecl *templateDecl =
  1788. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl())) {
  1789. return KeywordToClass(templateDecl->getName());
  1790. }
  1791. }
  1792. return hlsl::DxilResourceBase::Class::Invalid;
  1793. }
  1794. hlsl::DxilResourceBase::Class CGMSHLSLRuntime::TypeToClass(clang::QualType Ty) {
  1795. return hlsl::GetResourceClassForType(CGM.getContext(), Ty);
  1796. }
  1797. uint32_t CGMSHLSLRuntime::AddSampler(VarDecl *samplerDecl) {
  1798. llvm::Constant *val = CGM.GetAddrOfGlobalVar(samplerDecl);
  1799. unique_ptr<DxilSampler> hlslRes(new DxilSampler);
  1800. hlslRes->SetLowerBound(UINT_MAX);
  1801. hlslRes->SetGlobalSymbol(cast<llvm::GlobalVariable>(val));
  1802. hlslRes->SetGlobalName(samplerDecl->getName());
  1803. QualType VarTy = samplerDecl->getType();
  1804. if (const clang::ArrayType *arrayType =
  1805. CGM.getContext().getAsArrayType(VarTy)) {
  1806. if (arrayType->isConstantArrayType()) {
  1807. uint32_t arraySize =
  1808. cast<ConstantArrayType>(arrayType)->getSize().getLimitedValue();
  1809. hlslRes->SetRangeSize(arraySize);
  1810. } else {
  1811. hlslRes->SetRangeSize(UINT_MAX);
  1812. }
  1813. // use elementTy
  1814. VarTy = arrayType->getElementType();
  1815. // Support more dim.
  1816. while (const clang::ArrayType *arrayType =
  1817. CGM.getContext().getAsArrayType(VarTy)) {
  1818. unsigned rangeSize = hlslRes->GetRangeSize();
  1819. if (arrayType->isConstantArrayType()) {
  1820. uint32_t arraySize =
  1821. cast<ConstantArrayType>(arrayType)->getSize().getLimitedValue();
  1822. if (rangeSize != UINT_MAX)
  1823. hlslRes->SetRangeSize(rangeSize * arraySize);
  1824. } else
  1825. hlslRes->SetRangeSize(UINT_MAX);
  1826. // use elementTy
  1827. VarTy = arrayType->getElementType();
  1828. }
  1829. } else
  1830. hlslRes->SetRangeSize(1);
  1831. const RecordType *RT = VarTy->getAs<RecordType>();
  1832. DxilSampler::SamplerKind kind = KeywordToSamplerKind(RT->getDecl()->getName());
  1833. hlslRes->SetSamplerKind(kind);
  1834. for (hlsl::UnusualAnnotation *it : samplerDecl->getUnusualAnnotations()) {
  1835. switch (it->getKind()) {
  1836. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  1837. hlsl::RegisterAssignment *ra = cast<hlsl::RegisterAssignment>(it);
  1838. hlslRes->SetLowerBound(ra->RegisterNumber);
  1839. hlslRes->SetSpaceID(ra->RegisterSpace);
  1840. break;
  1841. }
  1842. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  1843. // Ignore Semantics
  1844. break;
  1845. case hlsl::UnusualAnnotation::UA_ConstantPacking:
  1846. // Should be handled by front-end
  1847. llvm_unreachable("packoffset on sampler");
  1848. break;
  1849. default:
  1850. llvm_unreachable("unknown UnusualAnnotation on sampler");
  1851. break;
  1852. }
  1853. }
  1854. hlslRes->SetID(m_pHLModule->GetSamplers().size());
  1855. return m_pHLModule->AddSampler(std::move(hlslRes));
  1856. }
  1857. static void CollectScalarTypes(std::vector<llvm::Type *> &scalarTys, llvm::Type *Ty) {
  1858. if (llvm::StructType *ST = dyn_cast<llvm::StructType>(Ty)) {
  1859. for (llvm::Type *EltTy : ST->elements()) {
  1860. CollectScalarTypes(scalarTys, EltTy);
  1861. }
  1862. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  1863. llvm::Type *EltTy = AT->getElementType();
  1864. for (unsigned i=0;i<AT->getNumElements();i++) {
  1865. CollectScalarTypes(scalarTys, EltTy);
  1866. }
  1867. } else if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  1868. llvm::Type *EltTy = VT->getElementType();
  1869. for (unsigned i=0;i<VT->getNumElements();i++) {
  1870. CollectScalarTypes(scalarTys, EltTy);
  1871. }
  1872. } else {
  1873. scalarTys.emplace_back(Ty);
  1874. }
  1875. }
  1876. static void CollectScalarTypes(std::vector<QualType> &ScalarTys, QualType Ty) {
  1877. if (Ty->isRecordType()) {
  1878. if (hlsl::IsHLSLMatType(Ty)) {
  1879. QualType EltTy = hlsl::GetHLSLMatElementType(Ty);
  1880. unsigned row = 0;
  1881. unsigned col = 0;
  1882. hlsl::GetRowsAndCols(Ty, row, col);
  1883. unsigned size = col*row;
  1884. for (unsigned i = 0; i < size; i++) {
  1885. CollectScalarTypes(ScalarTys, EltTy);
  1886. }
  1887. } else if (hlsl::IsHLSLVecType(Ty)) {
  1888. QualType EltTy = hlsl::GetHLSLVecElementType(Ty);
  1889. unsigned row = 0;
  1890. unsigned col = 0;
  1891. hlsl::GetRowsAndColsForAny(Ty, row, col);
  1892. unsigned size = col;
  1893. for (unsigned i = 0; i < size; i++) {
  1894. CollectScalarTypes(ScalarTys, EltTy);
  1895. }
  1896. } else {
  1897. const RecordType *RT = Ty->getAsStructureType();
  1898. // For CXXRecord.
  1899. if (!RT)
  1900. RT = Ty->getAs<RecordType>();
  1901. RecordDecl *RD = RT->getDecl();
  1902. for (FieldDecl *field : RD->fields())
  1903. CollectScalarTypes(ScalarTys, field->getType());
  1904. }
  1905. } else if (Ty->isArrayType()) {
  1906. const clang::ArrayType *AT = Ty->getAsArrayTypeUnsafe();
  1907. QualType EltTy = AT->getElementType();
  1908. // Set it to 5 for unsized array.
  1909. unsigned size = 5;
  1910. if (AT->isConstantArrayType()) {
  1911. size = cast<ConstantArrayType>(AT)->getSize().getLimitedValue();
  1912. }
  1913. for (unsigned i=0;i<size;i++) {
  1914. CollectScalarTypes(ScalarTys, EltTy);
  1915. }
  1916. } else {
  1917. ScalarTys.emplace_back(Ty);
  1918. }
  1919. }
  1920. bool CGMSHLSLRuntime::SetUAVSRV(SourceLocation loc,
  1921. hlsl::DxilResourceBase::Class resClass,
  1922. DxilResource *hlslRes, const RecordDecl *RD) {
  1923. hlsl::DxilResource::Kind kind = KeywordToKind(RD->getName());
  1924. hlslRes->SetKind(kind);
  1925. // Get the result type from handle field.
  1926. FieldDecl *FD = *(RD->field_begin());
  1927. DXASSERT(FD->getName() == "h", "must be handle field");
  1928. QualType resultTy = FD->getType();
  1929. // Type annotation for result type of resource.
  1930. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  1931. unsigned arrayEltSize = 0;
  1932. AddTypeAnnotation(QualType(RD->getTypeForDecl(),0), dxilTypeSys, arrayEltSize);
  1933. if (kind == hlsl::DxilResource::Kind::Texture2DMS ||
  1934. kind == hlsl::DxilResource::Kind::Texture2DMSArray) {
  1935. const ClassTemplateSpecializationDecl *templateDecl =
  1936. dyn_cast<ClassTemplateSpecializationDecl>(RD);
  1937. const clang::TemplateArgument &sampleCountArg =
  1938. templateDecl->getTemplateArgs()[1];
  1939. uint32_t sampleCount = sampleCountArg.getAsIntegral().getLimitedValue();
  1940. hlslRes->SetSampleCount(sampleCount);
  1941. }
  1942. if (kind != hlsl::DxilResource::Kind::StructuredBuffer) {
  1943. QualType Ty = resultTy;
  1944. QualType EltTy = Ty;
  1945. if (hlsl::IsHLSLVecType(Ty)) {
  1946. EltTy = hlsl::GetHLSLVecElementType(Ty);
  1947. } else if (hlsl::IsHLSLMatType(Ty)) {
  1948. EltTy = hlsl::GetHLSLMatElementType(Ty);
  1949. } else if (resultTy->isAggregateType()) {
  1950. // Struct or array in a none-struct resource.
  1951. std::vector<QualType> ScalarTys;
  1952. CollectScalarTypes(ScalarTys, resultTy);
  1953. unsigned size = ScalarTys.size();
  1954. if (size == 0) {
  1955. DiagnosticsEngine &Diags = CGM.getDiags();
  1956. unsigned DiagID = Diags.getCustomDiagID(
  1957. DiagnosticsEngine::Error,
  1958. "object's templated type must have at least one element");
  1959. Diags.Report(loc, DiagID);
  1960. return false;
  1961. }
  1962. if (size > 4) {
  1963. DiagnosticsEngine &Diags = CGM.getDiags();
  1964. unsigned DiagID = Diags.getCustomDiagID(
  1965. DiagnosticsEngine::Error, "elements of typed buffers and textures "
  1966. "must fit in four 32-bit quantities");
  1967. Diags.Report(loc, DiagID);
  1968. return false;
  1969. }
  1970. EltTy = ScalarTys[0];
  1971. for (QualType ScalarTy : ScalarTys) {
  1972. if (ScalarTy != EltTy) {
  1973. DiagnosticsEngine &Diags = CGM.getDiags();
  1974. unsigned DiagID = Diags.getCustomDiagID(
  1975. DiagnosticsEngine::Error,
  1976. "all template type components must have the same type");
  1977. Diags.Report(loc, DiagID);
  1978. return false;
  1979. }
  1980. }
  1981. }
  1982. EltTy = EltTy.getCanonicalType();
  1983. bool bSNorm = false;
  1984. bool bUNorm = false;
  1985. if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
  1986. switch (AT->getAttrKind()) {
  1987. case AttributedType::Kind::attr_hlsl_snorm:
  1988. bSNorm = true;
  1989. break;
  1990. case AttributedType::Kind::attr_hlsl_unorm:
  1991. bUNorm = true;
  1992. break;
  1993. default:
  1994. // Do nothing
  1995. break;
  1996. }
  1997. }
  1998. if (EltTy->isBuiltinType()) {
  1999. const BuiltinType *BTy = EltTy->getAs<BuiltinType>();
  2000. CompType::Kind kind = BuiltinTyToCompTy(BTy, bSNorm, bUNorm);
  2001. // 64bits types are implemented with u32.
  2002. if (kind == CompType::Kind::U64 || kind == CompType::Kind::I64 ||
  2003. kind == CompType::Kind::SNormF64 ||
  2004. kind == CompType::Kind::UNormF64 || kind == CompType::Kind::F64) {
  2005. kind = CompType::Kind::U32;
  2006. }
  2007. hlslRes->SetCompType(kind);
  2008. } else {
  2009. DXASSERT(!bSNorm && !bUNorm, "snorm/unorm on invalid type");
  2010. }
  2011. }
  2012. hlslRes->SetROV(RD->getName().startswith("RasterizerOrdered"));
  2013. if (kind == hlsl::DxilResource::Kind::TypedBuffer ||
  2014. kind == hlsl::DxilResource::Kind::StructuredBuffer) {
  2015. const ClassTemplateSpecializationDecl *templateDecl =
  2016. dyn_cast<ClassTemplateSpecializationDecl>(RD);
  2017. const clang::TemplateArgument &retTyArg =
  2018. templateDecl->getTemplateArgs()[0];
  2019. llvm::Type *retTy = CGM.getTypes().ConvertType(retTyArg.getAsType());
  2020. uint32_t strideInBytes = dataLayout.getTypeAllocSize(retTy);
  2021. hlslRes->SetElementStride(strideInBytes);
  2022. }
  2023. if (resClass == hlsl::DxilResourceBase::Class::SRV) {
  2024. if (hlslRes->IsGloballyCoherent()) {
  2025. DiagnosticsEngine &Diags = CGM.getDiags();
  2026. unsigned DiagID = Diags.getCustomDiagID(
  2027. DiagnosticsEngine::Error, "globallycoherent can only be used with "
  2028. "Unordered Access View buffers.");
  2029. Diags.Report(loc, DiagID);
  2030. return false;
  2031. }
  2032. hlslRes->SetRW(false);
  2033. hlslRes->SetID(m_pHLModule->GetSRVs().size());
  2034. } else {
  2035. hlslRes->SetRW(true);
  2036. hlslRes->SetID(m_pHLModule->GetUAVs().size());
  2037. }
  2038. return true;
  2039. }
  2040. uint32_t CGMSHLSLRuntime::AddUAVSRV(VarDecl *decl,
  2041. hlsl::DxilResourceBase::Class resClass) {
  2042. llvm::GlobalVariable *val =
  2043. cast<llvm::GlobalVariable>(CGM.GetAddrOfGlobalVar(decl));
  2044. QualType VarTy = decl->getType().getCanonicalType();
  2045. unique_ptr<HLResource> hlslRes(new HLResource);
  2046. hlslRes->SetLowerBound(UINT_MAX);
  2047. hlslRes->SetGlobalSymbol(val);
  2048. hlslRes->SetGlobalName(decl->getName());
  2049. if (const clang::ArrayType *arrayType =
  2050. CGM.getContext().getAsArrayType(VarTy)) {
  2051. if (arrayType->isConstantArrayType()) {
  2052. uint32_t arraySize =
  2053. cast<ConstantArrayType>(arrayType)->getSize().getLimitedValue();
  2054. hlslRes->SetRangeSize(arraySize);
  2055. } else
  2056. hlslRes->SetRangeSize(UINT_MAX);
  2057. // use elementTy
  2058. VarTy = arrayType->getElementType();
  2059. // Support more dim.
  2060. while (const clang::ArrayType *arrayType =
  2061. CGM.getContext().getAsArrayType(VarTy)) {
  2062. unsigned rangeSize = hlslRes->GetRangeSize();
  2063. if (arrayType->isConstantArrayType()) {
  2064. uint32_t arraySize =
  2065. cast<ConstantArrayType>(arrayType)->getSize().getLimitedValue();
  2066. if (rangeSize != UINT_MAX)
  2067. hlslRes->SetRangeSize(rangeSize * arraySize);
  2068. } else
  2069. hlslRes->SetRangeSize(UINT_MAX);
  2070. // use elementTy
  2071. VarTy = arrayType->getElementType();
  2072. }
  2073. } else
  2074. hlslRes->SetRangeSize(1);
  2075. for (hlsl::UnusualAnnotation *it : decl->getUnusualAnnotations()) {
  2076. switch (it->getKind()) {
  2077. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2078. hlsl::RegisterAssignment *ra = cast<hlsl::RegisterAssignment>(it);
  2079. hlslRes->SetLowerBound(ra->RegisterNumber);
  2080. hlslRes->SetSpaceID(ra->RegisterSpace);
  2081. break;
  2082. }
  2083. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2084. // Ignore Semantics
  2085. break;
  2086. case hlsl::UnusualAnnotation::UA_ConstantPacking:
  2087. // Should be handled by front-end
  2088. llvm_unreachable("packoffset on uav/srv");
  2089. break;
  2090. default:
  2091. llvm_unreachable("unknown UnusualAnnotation on uav/srv");
  2092. break;
  2093. }
  2094. }
  2095. const RecordType *RT = VarTy->getAs<RecordType>();
  2096. RecordDecl *RD = RT->getDecl();
  2097. if (decl->hasAttr<HLSLGloballyCoherentAttr>()) {
  2098. hlslRes->SetGloballyCoherent(true);
  2099. }
  2100. if (!SetUAVSRV(decl->getLocation(), resClass, hlslRes.get(), RD))
  2101. return 0;
  2102. if (resClass == hlsl::DxilResourceBase::Class::SRV) {
  2103. return m_pHLModule->AddSRV(std::move(hlslRes));
  2104. } else {
  2105. return m_pHLModule->AddUAV(std::move(hlslRes));
  2106. }
  2107. }
  2108. static bool IsResourceInType(const clang::ASTContext &context,
  2109. clang::QualType Ty) {
  2110. Ty = Ty.getCanonicalType();
  2111. if (const clang::ArrayType *arrayType = context.getAsArrayType(Ty)) {
  2112. return IsResourceInType(context, arrayType->getElementType());
  2113. } else if (const RecordType *RT = Ty->getAsStructureType()) {
  2114. if (KeywordToClass(RT->getDecl()->getName()) != DxilResourceBase::Class::Invalid)
  2115. return true;
  2116. const CXXRecordDecl* typeRecordDecl = RT->getAsCXXRecordDecl();
  2117. if (typeRecordDecl && !typeRecordDecl->isImplicit()) {
  2118. for (auto field : typeRecordDecl->fields()) {
  2119. if (IsResourceInType(context, field->getType()))
  2120. return true;
  2121. }
  2122. }
  2123. } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
  2124. if (const ClassTemplateSpecializationDecl *templateDecl =
  2125. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl())) {
  2126. if (KeywordToClass(templateDecl->getName()) != DxilResourceBase::Class::Invalid)
  2127. return true;
  2128. }
  2129. }
  2130. return false; // no resources found
  2131. }
  2132. void CGMSHLSLRuntime::AddConstant(VarDecl *constDecl, HLCBuffer &CB) {
  2133. if (constDecl->getStorageClass() == SC_Static) {
  2134. // For static inside cbuffer, take as global static.
  2135. // Don't add to cbuffer.
  2136. CGM.EmitGlobal(constDecl);
  2137. return;
  2138. }
  2139. // Search defined structure for resource objects and fail
  2140. if (CB.GetRangeSize() > 1 &&
  2141. IsResourceInType(CGM.getContext(), constDecl->getType())) {
  2142. DiagnosticsEngine &Diags = CGM.getDiags();
  2143. unsigned DiagID = Diags.getCustomDiagID(
  2144. DiagnosticsEngine::Error,
  2145. "object types not supported in cbuffer/tbuffer view arrays.");
  2146. Diags.Report(constDecl->getLocation(), DiagID);
  2147. return;
  2148. }
  2149. llvm::Constant *constVal = CGM.GetAddrOfGlobalVar(constDecl);
  2150. bool isGlobalCB = CB.GetID() == globalCBIndex;
  2151. uint32_t offset = 0;
  2152. bool userOffset = false;
  2153. for (hlsl::UnusualAnnotation *it : constDecl->getUnusualAnnotations()) {
  2154. switch (it->getKind()) {
  2155. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  2156. if (!isGlobalCB) {
  2157. // TODO: check cannot mix packoffset elements with nonpackoffset
  2158. // elements in a cbuffer.
  2159. hlsl::ConstantPacking *cp = cast<hlsl::ConstantPacking>(it);
  2160. offset = cp->Subcomponent << 2;
  2161. offset += cp->ComponentOffset;
  2162. // Change to byte.
  2163. offset <<= 2;
  2164. userOffset = true;
  2165. } else {
  2166. DiagnosticsEngine &Diags = CGM.getDiags();
  2167. unsigned DiagID = Diags.getCustomDiagID(
  2168. DiagnosticsEngine::Error,
  2169. "packoffset is only allowed in a constant buffer.");
  2170. Diags.Report(it->Loc, DiagID);
  2171. }
  2172. break;
  2173. }
  2174. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2175. if (isGlobalCB) {
  2176. RegisterAssignment *ra = cast<RegisterAssignment>(it);
  2177. offset = ra->RegisterNumber << 2;
  2178. // Change to byte.
  2179. offset <<= 2;
  2180. userOffset = true;
  2181. }
  2182. break;
  2183. }
  2184. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2185. // skip semantic on constant
  2186. break;
  2187. }
  2188. }
  2189. std::unique_ptr<DxilResourceBase> pHlslConst = llvm::make_unique<DxilResourceBase>(DXIL::ResourceClass::Invalid);
  2190. pHlslConst->SetLowerBound(UINT_MAX);
  2191. pHlslConst->SetGlobalSymbol(cast<llvm::GlobalVariable>(constVal));
  2192. pHlslConst->SetGlobalName(constDecl->getName());
  2193. if (userOffset) {
  2194. pHlslConst->SetLowerBound(offset);
  2195. }
  2196. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2197. // Just add type annotation here.
  2198. // Offset will be allocated later.
  2199. QualType Ty = constDecl->getType();
  2200. if (CB.GetRangeSize() != 1) {
  2201. while (Ty->isArrayType()) {
  2202. Ty = Ty->getAsArrayTypeUnsafe()->getElementType();
  2203. }
  2204. }
  2205. unsigned arrayEltSize = 0;
  2206. unsigned size = AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  2207. pHlslConst->SetRangeSize(size);
  2208. CB.AddConst(pHlslConst);
  2209. // Save fieldAnnotation for the const var.
  2210. DxilFieldAnnotation fieldAnnotation;
  2211. if (userOffset)
  2212. fieldAnnotation.SetCBufferOffset(offset);
  2213. // Get the nested element type.
  2214. if (Ty->isArrayType()) {
  2215. while (const ConstantArrayType *arrayTy =
  2216. CGM.getContext().getAsConstantArrayType(Ty)) {
  2217. Ty = arrayTy->getElementType();
  2218. }
  2219. }
  2220. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  2221. ConstructFieldAttributedAnnotation(fieldAnnotation, Ty, bDefaultRowMajor);
  2222. m_ConstVarAnnotationMap[constVal] = fieldAnnotation;
  2223. }
  2224. uint32_t CGMSHLSLRuntime::AddCBuffer(HLSLBufferDecl *D) {
  2225. unique_ptr<HLCBuffer> CB = llvm::make_unique<HLCBuffer>();
  2226. // setup the CB
  2227. CB->SetGlobalSymbol(nullptr);
  2228. CB->SetGlobalName(D->getNameAsString());
  2229. CB->SetLowerBound(UINT_MAX);
  2230. if (!D->isCBuffer()) {
  2231. CB->SetKind(DXIL::ResourceKind::TBuffer);
  2232. }
  2233. // the global variable will only used once by the createHandle?
  2234. // SetHandle(llvm::Value *pHandle);
  2235. for (hlsl::UnusualAnnotation *it : D->getUnusualAnnotations()) {
  2236. switch (it->getKind()) {
  2237. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2238. hlsl::RegisterAssignment *ra = cast<hlsl::RegisterAssignment>(it);
  2239. uint32_t regNum = ra->RegisterNumber;
  2240. uint32_t regSpace = ra->RegisterSpace;
  2241. CB->SetSpaceID(regSpace);
  2242. CB->SetLowerBound(regNum);
  2243. break;
  2244. }
  2245. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2246. // skip semantic on constant buffer
  2247. break;
  2248. case hlsl::UnusualAnnotation::UA_ConstantPacking:
  2249. llvm_unreachable("no packoffset on constant buffer");
  2250. break;
  2251. }
  2252. }
  2253. // Add constant
  2254. if (D->isConstantBufferView()) {
  2255. VarDecl *constDecl = cast<VarDecl>(*D->decls_begin());
  2256. CB->SetRangeSize(1);
  2257. QualType Ty = constDecl->getType();
  2258. if (Ty->isArrayType()) {
  2259. if (!Ty->isIncompleteArrayType()) {
  2260. unsigned arraySize = 1;
  2261. while (Ty->isArrayType()) {
  2262. Ty = Ty->getCanonicalTypeUnqualified();
  2263. const ConstantArrayType *AT = cast<ConstantArrayType>(Ty);
  2264. arraySize *= AT->getSize().getLimitedValue();
  2265. Ty = AT->getElementType();
  2266. }
  2267. CB->SetRangeSize(arraySize);
  2268. } else {
  2269. CB->SetRangeSize(UINT_MAX);
  2270. }
  2271. }
  2272. AddConstant(constDecl, *CB.get());
  2273. } else {
  2274. auto declsEnds = D->decls_end();
  2275. CB->SetRangeSize(1);
  2276. for (auto it = D->decls_begin(); it != declsEnds; it++) {
  2277. if (VarDecl *constDecl = dyn_cast<VarDecl>(*it))
  2278. AddConstant(constDecl, *CB.get());
  2279. else if (isa<EmptyDecl>(*it)) {
  2280. } else if (isa<CXXRecordDecl>(*it)) {
  2281. } else {
  2282. HLSLBufferDecl *inner = cast<HLSLBufferDecl>(*it);
  2283. GetOrCreateCBuffer(inner);
  2284. }
  2285. }
  2286. }
  2287. CB->SetID(m_pHLModule->GetCBuffers().size());
  2288. return m_pHLModule->AddCBuffer(std::move(CB));
  2289. }
  2290. HLCBuffer &CGMSHLSLRuntime::GetOrCreateCBuffer(HLSLBufferDecl *D) {
  2291. if (constantBufMap.count(D) != 0) {
  2292. uint32_t cbIndex = constantBufMap[D];
  2293. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(cbIndex)));
  2294. }
  2295. uint32_t cbID = AddCBuffer(D);
  2296. constantBufMap[D] = cbID;
  2297. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(cbID)));
  2298. }
  2299. bool CGMSHLSLRuntime::IsPatchConstantFunction(const Function *F) {
  2300. DXASSERT_NOMSG(F != nullptr);
  2301. for (auto && p : patchConstantFunctionMap) {
  2302. if (p.second.Func == F) return true;
  2303. }
  2304. return false;
  2305. }
  2306. void CGMSHLSLRuntime::SetEntryFunction() {
  2307. if (Entry.Func == nullptr) {
  2308. DiagnosticsEngine &Diags = CGM.getDiags();
  2309. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2310. "cannot find entry function %0");
  2311. Diags.Report(DiagID) << CGM.getCodeGenOpts().HLSLEntryFunction;
  2312. return;
  2313. }
  2314. m_pHLModule->SetEntryFunction(Entry.Func);
  2315. }
  2316. // Here the size is CB size. So don't need check type.
  2317. static unsigned AlignCBufferOffset(unsigned offset, unsigned size, llvm::Type *Ty) {
  2318. DXASSERT(!(offset & 1), "otherwise we have an invalid offset.");
  2319. bool bNeedNewRow = Ty->isArrayTy();
  2320. unsigned scalarSizeInBytes = Ty->getScalarSizeInBits() / 8;
  2321. return AlignBufferOffsetInLegacy(offset, size, scalarSizeInBytes, bNeedNewRow);
  2322. }
  2323. static unsigned AllocateDxilConstantBuffer(HLCBuffer &CB) {
  2324. unsigned offset = 0;
  2325. // Scan user allocated constants first.
  2326. // Update offset.
  2327. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2328. if (C->GetLowerBound() == UINT_MAX)
  2329. continue;
  2330. unsigned size = C->GetRangeSize();
  2331. unsigned nextOffset = size + C->GetLowerBound();
  2332. if (offset < nextOffset)
  2333. offset = nextOffset;
  2334. }
  2335. // Alloc after user allocated constants.
  2336. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2337. if (C->GetLowerBound() != UINT_MAX)
  2338. continue;
  2339. unsigned size = C->GetRangeSize();
  2340. llvm::Type *Ty = C->GetGlobalSymbol()->getType()->getPointerElementType();
  2341. // Align offset.
  2342. offset = AlignCBufferOffset(offset, size, Ty);
  2343. if (C->GetLowerBound() == UINT_MAX) {
  2344. C->SetLowerBound(offset);
  2345. }
  2346. offset += size;
  2347. }
  2348. return offset;
  2349. }
  2350. static void AllocateDxilConstantBuffers(HLModule *pHLModule) {
  2351. for (unsigned i = 0; i < pHLModule->GetCBuffers().size(); i++) {
  2352. HLCBuffer &CB = *static_cast<HLCBuffer*>(&(pHLModule->GetCBuffer(i)));
  2353. unsigned size = AllocateDxilConstantBuffer(CB);
  2354. CB.SetSize(size);
  2355. }
  2356. }
  2357. static void ReplaceUseInFunction(Value *V, Value *NewV, Function *F,
  2358. IRBuilder<> &Builder) {
  2359. for (auto U = V->user_begin(); U != V->user_end(); ) {
  2360. User *user = *(U++);
  2361. if (Instruction *I = dyn_cast<Instruction>(user)) {
  2362. if (I->getParent()->getParent() == F) {
  2363. // replace use with GEP if in F
  2364. for (unsigned i = 0; i < I->getNumOperands(); i++) {
  2365. if (I->getOperand(i) == V)
  2366. I->setOperand(i, NewV);
  2367. }
  2368. }
  2369. } else {
  2370. // For constant operator, create local clone which use GEP.
  2371. // Only support GEP and bitcast.
  2372. if (GEPOperator *GEPOp = dyn_cast<GEPOperator>(user)) {
  2373. std::vector<Value *> idxList(GEPOp->idx_begin(), GEPOp->idx_end());
  2374. Value *NewGEP = Builder.CreateInBoundsGEP(NewV, idxList);
  2375. ReplaceUseInFunction(GEPOp, NewGEP, F, Builder);
  2376. } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(user)) {
  2377. // Change the init val into NewV with Store.
  2378. GV->setInitializer(nullptr);
  2379. Builder.CreateStore(NewV, GV);
  2380. } else {
  2381. // Must be bitcast here.
  2382. BitCastOperator *BC = cast<BitCastOperator>(user);
  2383. Value *NewBC = Builder.CreateBitCast(NewV, BC->getType());
  2384. ReplaceUseInFunction(BC, NewBC, F, Builder);
  2385. }
  2386. }
  2387. }
  2388. }
  2389. void MarkUsedFunctionForConst(Value *V, std::unordered_set<Function*> &usedFunc) {
  2390. for (auto U = V->user_begin(); U != V->user_end();) {
  2391. User *user = *(U++);
  2392. if (Instruction *I = dyn_cast<Instruction>(user)) {
  2393. Function *F = I->getParent()->getParent();
  2394. usedFunc.insert(F);
  2395. } else {
  2396. // For constant operator, create local clone which use GEP.
  2397. // Only support GEP and bitcast.
  2398. if (GEPOperator *GEPOp = dyn_cast<GEPOperator>(user)) {
  2399. MarkUsedFunctionForConst(GEPOp, usedFunc);
  2400. } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(user)) {
  2401. MarkUsedFunctionForConst(GV, usedFunc);
  2402. } else {
  2403. // Must be bitcast here.
  2404. BitCastOperator *BC = cast<BitCastOperator>(user);
  2405. MarkUsedFunctionForConst(BC, usedFunc);
  2406. }
  2407. }
  2408. }
  2409. }
  2410. static Function * GetOrCreateHLCreateHandle(HLModule &HLM, llvm::Type *HandleTy,
  2411. ArrayRef<Value*> paramList, MDNode *MD) {
  2412. SmallVector<llvm::Type *, 4> paramTyList;
  2413. for (Value *param : paramList) {
  2414. paramTyList.emplace_back(param->getType());
  2415. }
  2416. llvm::FunctionType *funcTy =
  2417. llvm::FunctionType::get(HandleTy, paramTyList, false);
  2418. llvm::Module &M = *HLM.GetModule();
  2419. Function *CreateHandle = GetOrCreateHLFunctionWithBody(M, funcTy, HLOpcodeGroup::HLCreateHandle,
  2420. /*opcode*/ 0, "");
  2421. if (CreateHandle->empty()) {
  2422. // Add body.
  2423. BasicBlock *BB =
  2424. BasicBlock::Create(CreateHandle->getContext(), "Entry", CreateHandle);
  2425. IRBuilder<> Builder(BB);
  2426. // Just return undef to make a body.
  2427. Builder.CreateRet(UndefValue::get(HandleTy));
  2428. // Mark resource attribute.
  2429. HLM.MarkDxilResourceAttrib(CreateHandle, MD);
  2430. }
  2431. return CreateHandle;
  2432. }
  2433. static bool CreateCBufferVariable(HLCBuffer &CB,
  2434. HLModule &HLM, llvm::Type *HandleTy) {
  2435. bool bUsed = false;
  2436. // Build Struct for CBuffer.
  2437. SmallVector<llvm::Type*, 4> Elements;
  2438. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2439. Value *GV = C->GetGlobalSymbol();
  2440. if (GV->hasNUsesOrMore(1))
  2441. bUsed = true;
  2442. // Global variable must be pointer type.
  2443. llvm::Type *Ty = GV->getType()->getPointerElementType();
  2444. Elements.emplace_back(Ty);
  2445. }
  2446. // Don't create CBuffer variable for unused cbuffer.
  2447. if (!bUsed)
  2448. return false;
  2449. llvm::Module &M = *HLM.GetModule();
  2450. bool isCBArray = CB.GetRangeSize() != 1;
  2451. llvm::GlobalVariable *cbGV = nullptr;
  2452. llvm::Type *cbTy = nullptr;
  2453. unsigned cbIndexDepth = 0;
  2454. if (!isCBArray) {
  2455. llvm::StructType *CBStructTy =
  2456. llvm::StructType::create(Elements, CB.GetGlobalName());
  2457. cbGV = new llvm::GlobalVariable(M, CBStructTy, /*IsConstant*/ true,
  2458. llvm::GlobalValue::ExternalLinkage,
  2459. /*InitVal*/ nullptr, CB.GetGlobalName());
  2460. cbTy = cbGV->getType();
  2461. } else {
  2462. // For array of ConstantBuffer, create array of struct instead of struct of
  2463. // array.
  2464. DXASSERT(CB.GetConstants().size() == 1,
  2465. "ConstantBuffer should have 1 constant");
  2466. Value *GV = CB.GetConstants()[0]->GetGlobalSymbol();
  2467. llvm::Type *CBEltTy =
  2468. GV->getType()->getPointerElementType()->getArrayElementType();
  2469. cbIndexDepth = 1;
  2470. while (CBEltTy->isArrayTy()) {
  2471. CBEltTy = CBEltTy->getArrayElementType();
  2472. cbIndexDepth++;
  2473. }
  2474. // Add one level struct type to match normal case.
  2475. llvm::StructType *CBStructTy =
  2476. llvm::StructType::create({CBEltTy}, CB.GetGlobalName());
  2477. llvm::ArrayType *CBArrayTy =
  2478. llvm::ArrayType::get(CBStructTy, CB.GetRangeSize());
  2479. cbGV = new llvm::GlobalVariable(M, CBArrayTy, /*IsConstant*/ true,
  2480. llvm::GlobalValue::ExternalLinkage,
  2481. /*InitVal*/ nullptr, CB.GetGlobalName());
  2482. cbTy = llvm::PointerType::get(CBStructTy,
  2483. cbGV->getType()->getPointerAddressSpace());
  2484. }
  2485. CB.SetGlobalSymbol(cbGV);
  2486. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  2487. llvm::Type *idxTy = opcodeTy;
  2488. Constant *zeroIdx = ConstantInt::get(opcodeTy, 0);
  2489. MDNode *MD = HLM.DxilCBufferToMDNode(CB);
  2490. Value *HandleArgs[] = { zeroIdx, cbGV, zeroIdx };
  2491. Function *CreateHandleFunc = GetOrCreateHLCreateHandle(HLM, HandleTy, HandleArgs, MD);
  2492. llvm::FunctionType *SubscriptFuncTy =
  2493. llvm::FunctionType::get(cbTy, { opcodeTy, HandleTy, idxTy}, false);
  2494. Function *subscriptFunc =
  2495. GetOrCreateHLFunction(M, SubscriptFuncTy, HLOpcodeGroup::HLSubscript,
  2496. (unsigned)HLSubscriptOpcode::CBufferSubscript);
  2497. Constant *opArg = ConstantInt::get(opcodeTy, (unsigned)HLSubscriptOpcode::CBufferSubscript);
  2498. Value *args[] = { opArg, nullptr, zeroIdx };
  2499. llvm::LLVMContext &Context = M.getContext();
  2500. llvm::Type *i32Ty = llvm::Type::getInt32Ty(Context);
  2501. Value *zero = ConstantInt::get(i32Ty, (uint64_t)0);
  2502. std::vector<Value *> indexArray(CB.GetConstants().size());
  2503. std::vector<std::unordered_set<Function*>> constUsedFuncList(CB.GetConstants().size());
  2504. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2505. Value *idx = ConstantInt::get(i32Ty, C->GetID());
  2506. indexArray[C->GetID()] = idx;
  2507. Value *GV = C->GetGlobalSymbol();
  2508. MarkUsedFunctionForConst(GV, constUsedFuncList[C->GetID()]);
  2509. }
  2510. for (Function &F : M.functions()) {
  2511. if (F.isDeclaration())
  2512. continue;
  2513. if (GetHLOpcodeGroupByName(&F) != HLOpcodeGroup::NotHL)
  2514. continue;
  2515. IRBuilder<> Builder(F.getEntryBlock().getFirstInsertionPt());
  2516. // create HL subscript to make all the use of cbuffer start from it.
  2517. HandleArgs[HLOperandIndex::kCreateHandleResourceOpIdx] = cbGV;
  2518. CallInst *Handle = Builder.CreateCall(CreateHandleFunc, HandleArgs);
  2519. args[HLOperandIndex::kSubscriptObjectOpIdx] = Handle;
  2520. Instruction *cbSubscript =
  2521. cast<Instruction>(Builder.CreateCall(subscriptFunc, {args}));
  2522. // Replace constant var with GEP pGV
  2523. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2524. Value *GV = C->GetGlobalSymbol();
  2525. if (constUsedFuncList[C->GetID()].count(&F) == 0)
  2526. continue;
  2527. Value *idx = indexArray[C->GetID()];
  2528. if (!isCBArray) {
  2529. Instruction *GEP = cast<Instruction>(
  2530. Builder.CreateInBoundsGEP(cbSubscript, {zero, idx}));
  2531. // TODO: make sure the debug info is synced to GEP.
  2532. // GEP->setDebugLoc(GV);
  2533. ReplaceUseInFunction(GV, GEP, &F, Builder);
  2534. // Delete if no use in F.
  2535. if (GEP->user_empty())
  2536. GEP->eraseFromParent();
  2537. } else {
  2538. for (auto U = GV->user_begin(); U != GV->user_end();) {
  2539. User *user = *(U++);
  2540. if (user->user_empty())
  2541. continue;
  2542. Instruction *I = dyn_cast<Instruction>(user);
  2543. if (I && I->getParent()->getParent() != &F)
  2544. continue;
  2545. IRBuilder<> *instBuilder = &Builder;
  2546. unique_ptr<IRBuilder<>> B;
  2547. if (I) {
  2548. B = llvm::make_unique<IRBuilder<>>(I);
  2549. instBuilder = B.get();
  2550. }
  2551. GEPOperator *GEPOp = cast<GEPOperator>(user);
  2552. std::vector<Value *> idxList;
  2553. DXASSERT(GEPOp->getNumIndices() >= 1 + cbIndexDepth,
  2554. "must indexing ConstantBuffer array");
  2555. idxList.reserve(GEPOp->getNumIndices() - (cbIndexDepth - 1));
  2556. gep_type_iterator GI = gep_type_begin(*GEPOp),
  2557. E = gep_type_end(*GEPOp);
  2558. idxList.push_back(GI.getOperand());
  2559. // change array index with 0 for struct index.
  2560. idxList.push_back(zero);
  2561. GI++;
  2562. Value *arrayIdx = GI.getOperand();
  2563. GI++;
  2564. for (unsigned curIndex = 1; GI != E && curIndex < cbIndexDepth;
  2565. ++GI, ++curIndex) {
  2566. arrayIdx = instBuilder->CreateMul(
  2567. arrayIdx, Builder.getInt32(GI->getArrayNumElements()));
  2568. arrayIdx = instBuilder->CreateAdd(arrayIdx, GI.getOperand());
  2569. }
  2570. for (; GI != E; ++GI) {
  2571. idxList.push_back(GI.getOperand());
  2572. }
  2573. HandleArgs[HLOperandIndex::kCreateHandleIndexOpIdx] = arrayIdx;
  2574. CallInst *Handle =
  2575. instBuilder->CreateCall(CreateHandleFunc, HandleArgs);
  2576. args[HLOperandIndex::kSubscriptObjectOpIdx] = Handle;
  2577. args[HLOperandIndex::kSubscriptIndexOpIdx] = arrayIdx;
  2578. Instruction *cbSubscript =
  2579. cast<Instruction>(instBuilder->CreateCall(subscriptFunc, {args}));
  2580. Instruction *NewGEP = cast<Instruction>(
  2581. instBuilder->CreateInBoundsGEP(cbSubscript, idxList));
  2582. ReplaceUseInFunction(GEPOp, NewGEP, &F, *instBuilder);
  2583. }
  2584. }
  2585. }
  2586. // Delete if no use in F.
  2587. if (cbSubscript->user_empty()) {
  2588. cbSubscript->eraseFromParent();
  2589. Handle->eraseFromParent();
  2590. }
  2591. }
  2592. return true;
  2593. }
  2594. static void ConstructCBufferAnnotation(
  2595. HLCBuffer &CB, DxilTypeSystem &dxilTypeSys,
  2596. std::unordered_map<Constant *, DxilFieldAnnotation> &AnnotationMap) {
  2597. Value *GV = CB.GetGlobalSymbol();
  2598. llvm::StructType *CBStructTy =
  2599. dyn_cast<llvm::StructType>(GV->getType()->getPointerElementType());
  2600. if (!CBStructTy) {
  2601. // For Array of ConstantBuffer.
  2602. llvm::ArrayType *CBArrayTy =
  2603. cast<llvm::ArrayType>(GV->getType()->getPointerElementType());
  2604. CBStructTy = cast<llvm::StructType>(CBArrayTy->getArrayElementType());
  2605. }
  2606. DxilStructAnnotation *CBAnnotation =
  2607. dxilTypeSys.AddStructAnnotation(CBStructTy);
  2608. CBAnnotation->SetCBufferSize(CB.GetSize());
  2609. // Set fieldAnnotation for each constant var.
  2610. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2611. Constant *GV = C->GetGlobalSymbol();
  2612. DxilFieldAnnotation &fieldAnnotation =
  2613. CBAnnotation->GetFieldAnnotation(C->GetID());
  2614. fieldAnnotation = AnnotationMap[GV];
  2615. // This is after CBuffer allocation.
  2616. fieldAnnotation.SetCBufferOffset(C->GetLowerBound());
  2617. fieldAnnotation.SetFieldName(C->GetGlobalName());
  2618. }
  2619. }
  2620. static void ConstructCBuffer(
  2621. HLModule *pHLModule,
  2622. llvm::Type *CBufferType,
  2623. std::unordered_map<Constant *, DxilFieldAnnotation> &AnnotationMap) {
  2624. DxilTypeSystem &dxilTypeSys = pHLModule->GetTypeSystem();
  2625. llvm::Type *HandleTy = pHLModule->GetOP()->GetHandleType();
  2626. for (unsigned i = 0; i < pHLModule->GetCBuffers().size(); i++) {
  2627. HLCBuffer &CB = *static_cast<HLCBuffer*>(&(pHLModule->GetCBuffer(i)));
  2628. if (CB.GetConstants().size() == 0) {
  2629. // Create Fake variable for cbuffer which is empty.
  2630. llvm::GlobalVariable *pGV = new llvm::GlobalVariable(
  2631. *pHLModule->GetModule(), CBufferType, true,
  2632. llvm::GlobalValue::ExternalLinkage, nullptr, CB.GetGlobalName());
  2633. CB.SetGlobalSymbol(pGV);
  2634. } else {
  2635. bool bCreated =
  2636. CreateCBufferVariable(CB, *pHLModule, HandleTy);
  2637. if (bCreated)
  2638. ConstructCBufferAnnotation(CB, dxilTypeSys, AnnotationMap);
  2639. else {
  2640. // Create Fake variable for cbuffer which is unused.
  2641. llvm::GlobalVariable *pGV = new llvm::GlobalVariable(
  2642. *pHLModule->GetModule(), CBufferType, true,
  2643. llvm::GlobalValue::ExternalLinkage, nullptr, CB.GetGlobalName());
  2644. CB.SetGlobalSymbol(pGV);
  2645. }
  2646. }
  2647. // Clear the constants which useless now.
  2648. CB.GetConstants().clear();
  2649. }
  2650. }
  2651. static void ReplaceBoolVectorSubscript(CallInst *CI) {
  2652. Value *Ptr = CI->getArgOperand(0);
  2653. Value *Idx = CI->getArgOperand(1);
  2654. Value *IdxList[] = {ConstantInt::get(Idx->getType(), 0), Idx};
  2655. for (auto It = CI->user_begin(), E = CI->user_end(); It != E;) {
  2656. Instruction *user = cast<Instruction>(*(It++));
  2657. IRBuilder<> Builder(user);
  2658. Value *GEP = Builder.CreateInBoundsGEP(Ptr, IdxList);
  2659. if (LoadInst *LI = dyn_cast<LoadInst>(user)) {
  2660. Value *NewLd = Builder.CreateLoad(GEP);
  2661. Value *cast = Builder.CreateZExt(NewLd, LI->getType());
  2662. LI->replaceAllUsesWith(cast);
  2663. LI->eraseFromParent();
  2664. } else {
  2665. // Must be a store inst here.
  2666. StoreInst *SI = cast<StoreInst>(user);
  2667. Value *V = SI->getValueOperand();
  2668. Value *cast =
  2669. Builder.CreateICmpNE(V, llvm::ConstantInt::get(V->getType(), 0));
  2670. Builder.CreateStore(cast, GEP);
  2671. SI->eraseFromParent();
  2672. }
  2673. }
  2674. CI->eraseFromParent();
  2675. }
  2676. static void ReplaceBoolVectorSubscript(Function *F) {
  2677. for (auto It = F->user_begin(), E = F->user_end(); It != E; ) {
  2678. User *user = *(It++);
  2679. CallInst *CI = cast<CallInst>(user);
  2680. ReplaceBoolVectorSubscript(CI);
  2681. }
  2682. }
  2683. // Add function body for intrinsic if possible.
  2684. static Function *CreateOpFunction(llvm::Module &M, Function *F,
  2685. llvm::FunctionType *funcTy,
  2686. HLOpcodeGroup group, unsigned opcode) {
  2687. Function *opFunc = nullptr;
  2688. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  2689. if (group == HLOpcodeGroup::HLIntrinsic) {
  2690. IntrinsicOp intriOp = static_cast<IntrinsicOp>(opcode);
  2691. switch (intriOp) {
  2692. case IntrinsicOp::MOP_Append:
  2693. case IntrinsicOp::MOP_Consume: {
  2694. bool bAppend = intriOp == IntrinsicOp::MOP_Append;
  2695. llvm::Type *handleTy = funcTy->getParamType(HLOperandIndex::kHandleOpIdx);
  2696. // Don't generate body for OutputStream::Append.
  2697. if (bAppend && HLModule::IsStreamOutputPtrType(handleTy)) {
  2698. opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  2699. break;
  2700. }
  2701. opFunc = GetOrCreateHLFunctionWithBody(M, funcTy, group, opcode,
  2702. bAppend ? "append" : "consume");
  2703. llvm::Type *counterTy = llvm::Type::getInt32Ty(M.getContext());
  2704. llvm::FunctionType *IncCounterFuncTy =
  2705. llvm::FunctionType::get(counterTy, {opcodeTy, handleTy}, false);
  2706. unsigned counterOpcode = bAppend ? (unsigned)IntrinsicOp::MOP_IncrementCounter:
  2707. (unsigned)IntrinsicOp::MOP_DecrementCounter;
  2708. Function *incCounterFunc =
  2709. GetOrCreateHLFunction(M, IncCounterFuncTy, group,
  2710. counterOpcode);
  2711. llvm::Type *idxTy = counterTy;
  2712. llvm::Type *valTy = bAppend ?
  2713. funcTy->getParamType(HLOperandIndex::kAppendValOpIndex):funcTy->getReturnType();
  2714. llvm::Type *subscriptTy = valTy;
  2715. if (!valTy->isPointerTy()) {
  2716. // Return type for subscript should be pointer type.
  2717. subscriptTy = llvm::PointerType::get(valTy, 0);
  2718. }
  2719. llvm::FunctionType *SubscriptFuncTy =
  2720. llvm::FunctionType::get(subscriptTy, {opcodeTy, handleTy, idxTy}, false);
  2721. Function *subscriptFunc =
  2722. GetOrCreateHLFunction(M, SubscriptFuncTy, HLOpcodeGroup::HLSubscript,
  2723. (unsigned)HLSubscriptOpcode::DefaultSubscript);
  2724. BasicBlock *BB = BasicBlock::Create(opFunc->getContext(), "Entry", opFunc);
  2725. IRBuilder<> Builder(BB);
  2726. auto argIter = opFunc->args().begin();
  2727. // Skip the opcode arg.
  2728. argIter++;
  2729. Argument *thisArg = argIter++;
  2730. // int counter = IncrementCounter/DecrementCounter(Buf);
  2731. Value *incCounterOpArg =
  2732. ConstantInt::get(idxTy, counterOpcode);
  2733. Value *counter =
  2734. Builder.CreateCall(incCounterFunc, {incCounterOpArg, thisArg});
  2735. // Buf[counter];
  2736. Value *subscriptOpArg = ConstantInt::get(
  2737. idxTy, (unsigned)HLSubscriptOpcode::DefaultSubscript);
  2738. Value *subscript =
  2739. Builder.CreateCall(subscriptFunc, {subscriptOpArg, thisArg, counter});
  2740. if (bAppend) {
  2741. Argument *valArg = argIter;
  2742. // Buf[counter] = val;
  2743. if (valTy->isPointerTy()) {
  2744. unsigned size = M.getDataLayout().getTypeAllocSize(subscript->getType()->getPointerElementType());
  2745. Builder.CreateMemCpy(subscript, valArg, size, 1);
  2746. } else
  2747. Builder.CreateStore(valArg, subscript);
  2748. Builder.CreateRetVoid();
  2749. } else {
  2750. // return Buf[counter];
  2751. if (valTy->isPointerTy())
  2752. Builder.CreateRet(subscript);
  2753. else {
  2754. Value *retVal = Builder.CreateLoad(subscript);
  2755. Builder.CreateRet(retVal);
  2756. }
  2757. }
  2758. } break;
  2759. case IntrinsicOp::IOP_sincos: {
  2760. opFunc = GetOrCreateHLFunctionWithBody(M, funcTy, group, opcode, "sincos");
  2761. llvm::Type *valTy = funcTy->getParamType(HLOperandIndex::kTrinaryOpSrc0Idx);
  2762. llvm::FunctionType *sinFuncTy =
  2763. llvm::FunctionType::get(valTy, {opcodeTy, valTy}, false);
  2764. unsigned sinOp = static_cast<unsigned>(IntrinsicOp::IOP_sin);
  2765. unsigned cosOp = static_cast<unsigned>(IntrinsicOp::IOP_cos);
  2766. Function *sinFunc = GetOrCreateHLFunction(M, sinFuncTy, group, sinOp);
  2767. Function *cosFunc = GetOrCreateHLFunction(M, sinFuncTy, group, cosOp);
  2768. BasicBlock *BB = BasicBlock::Create(opFunc->getContext(), "Entry", opFunc);
  2769. IRBuilder<> Builder(BB);
  2770. auto argIter = opFunc->args().begin();
  2771. // Skip the opcode arg.
  2772. argIter++;
  2773. Argument *valArg = argIter++;
  2774. Argument *sinPtrArg = argIter++;
  2775. Argument *cosPtrArg = argIter++;
  2776. Value *sinOpArg =
  2777. ConstantInt::get(opcodeTy, sinOp);
  2778. Value *sinVal = Builder.CreateCall(sinFunc, {sinOpArg, valArg});
  2779. Builder.CreateStore(sinVal, sinPtrArg);
  2780. Value *cosOpArg =
  2781. ConstantInt::get(opcodeTy, cosOp);
  2782. Value *cosVal = Builder.CreateCall(cosFunc, {cosOpArg, valArg});
  2783. Builder.CreateStore(cosVal, cosPtrArg);
  2784. // Ret.
  2785. Builder.CreateRetVoid();
  2786. } break;
  2787. default:
  2788. opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  2789. break;
  2790. }
  2791. }
  2792. else if (group == HLOpcodeGroup::HLExtIntrinsic) {
  2793. llvm::StringRef fnName = F->getName();
  2794. llvm::StringRef groupName = GetHLOpcodeGroupNameByAttr(F);
  2795. opFunc = GetOrCreateHLFunction(M, funcTy, group, &groupName, &fnName, opcode);
  2796. }
  2797. else {
  2798. opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  2799. }
  2800. // Add attribute
  2801. if (F->hasFnAttribute(Attribute::ReadNone))
  2802. opFunc->addFnAttr(Attribute::ReadNone);
  2803. if (F->hasFnAttribute(Attribute::ReadOnly))
  2804. opFunc->addFnAttr(Attribute::ReadOnly);
  2805. return opFunc;
  2806. }
  2807. static Value *CreateHandleFromResPtr(
  2808. Value *ResPtr, HLModule &HLM, llvm::Type *HandleTy,
  2809. std::unordered_map<llvm::Type *, MDNode *> &resMetaMap,
  2810. IRBuilder<> &Builder) {
  2811. llvm::Type *objTy = ResPtr->getType()->getPointerElementType();
  2812. DXASSERT(resMetaMap.count(objTy), "cannot find resource type");
  2813. MDNode *MD = resMetaMap[objTy];
  2814. // Load to make sure resource only have Ld/St use so mem2reg could remove
  2815. // temp resource.
  2816. Value *ldObj = Builder.CreateLoad(ResPtr);
  2817. Value *opcode = Builder.getInt32(0);
  2818. Value *args[] = {opcode, ldObj};
  2819. Function *CreateHandle = GetOrCreateHLCreateHandle(HLM, HandleTy, args, MD);
  2820. CallInst *Handle = Builder.CreateCall(CreateHandle, args);
  2821. return Handle;
  2822. }
  2823. static void AddOpcodeParamForIntrinsic(HLModule &HLM, Function *F,
  2824. unsigned opcode, llvm::Type *HandleTy,
  2825. std::unordered_map<llvm::Type *, MDNode*> &resMetaMap) {
  2826. llvm::Module &M = *HLM.GetModule();
  2827. llvm::FunctionType *oldFuncTy = F->getFunctionType();
  2828. SmallVector<llvm::Type *, 4> paramTyList;
  2829. // Add the opcode param
  2830. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  2831. paramTyList.emplace_back(opcodeTy);
  2832. paramTyList.append(oldFuncTy->param_begin(), oldFuncTy->param_end());
  2833. for (unsigned i = 1; i < paramTyList.size(); i++) {
  2834. llvm::Type *Ty = paramTyList[i];
  2835. if (Ty->isPointerTy()) {
  2836. Ty = Ty->getPointerElementType();
  2837. if (HLModule::IsHLSLObjectType(Ty) &&
  2838. // StreamOutput don't need handle.
  2839. !HLModule::IsStreamOutputType(Ty)) {
  2840. // Use handle type for object type.
  2841. // This will make sure temp object variable only used by createHandle.
  2842. paramTyList[i] = HandleTy;
  2843. }
  2844. }
  2845. }
  2846. HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  2847. if (group == HLOpcodeGroup::HLSubscript &&
  2848. opcode == static_cast<unsigned>(HLSubscriptOpcode::VectorSubscript)) {
  2849. llvm::FunctionType *FT = F->getFunctionType();
  2850. llvm::Type *VecArgTy = FT->getParamType(0);
  2851. llvm::VectorType *VType =
  2852. cast<llvm::VectorType>(VecArgTy->getPointerElementType());
  2853. llvm::Type *Ty = VType->getElementType();
  2854. DXASSERT(Ty->isIntegerTy(), "Only bool could use VectorSubscript");
  2855. llvm::IntegerType *ITy = cast<IntegerType>(Ty);
  2856. DXASSERT_LOCALVAR(ITy, ITy->getBitWidth() == 1, "Only bool could use VectorSubscript");
  2857. // The return type is i8*.
  2858. // Replace all uses with i1*.
  2859. ReplaceBoolVectorSubscript(F);
  2860. return;
  2861. }
  2862. bool isDoubleSubscriptFunc = group == HLOpcodeGroup::HLSubscript &&
  2863. opcode == static_cast<unsigned>(HLSubscriptOpcode::DoubleSubscript);
  2864. llvm::Type *RetTy = oldFuncTy->getReturnType();
  2865. if (isDoubleSubscriptFunc) {
  2866. CallInst *doubleSub = cast<CallInst>(*F->user_begin());
  2867. // Change currentIdx type into coord type.
  2868. auto U = doubleSub->user_begin();
  2869. Value *user = *U;
  2870. CallInst *secSub = cast<CallInst>(user);
  2871. unsigned coordIdx = HLOperandIndex::kSubscriptIndexOpIdx;
  2872. // opcode operand not add yet, so the index need -1.
  2873. if (GetHLOpcodeGroupByName(secSub->getCalledFunction()) == HLOpcodeGroup::NotHL)
  2874. coordIdx -= 1;
  2875. Value *coord = secSub->getArgOperand(coordIdx);
  2876. llvm::Type *coordTy = coord->getType();
  2877. paramTyList[HLOperandIndex::kSubscriptIndexOpIdx] = coordTy;
  2878. // Add the sampleIdx or mipLevel parameter to the end.
  2879. paramTyList.emplace_back(opcodeTy);
  2880. // Change return type to be resource ret type.
  2881. // opcode operand not add yet, so the index need -1.
  2882. Value *objPtr = doubleSub->getArgOperand(HLOperandIndex::kSubscriptObjectOpIdx-1);
  2883. // Must be a GEP
  2884. GEPOperator *objGEP = cast<GEPOperator>(objPtr);
  2885. gep_type_iterator GEPIt = gep_type_begin(objGEP), E = gep_type_end(objGEP);
  2886. llvm::Type *resTy = nullptr;
  2887. while (GEPIt != E) {
  2888. if (HLModule::IsHLSLObjectType(*GEPIt)) {
  2889. resTy = *GEPIt;
  2890. break;
  2891. }
  2892. GEPIt++;
  2893. }
  2894. DXASSERT(resTy, "must find the resource type");
  2895. // Change object type to handle type.
  2896. paramTyList[HLOperandIndex::kSubscriptObjectOpIdx] = HandleTy;
  2897. // Change RetTy into pointer of resource reture type.
  2898. RetTy = cast<StructType>(resTy)->getElementType(0)->getPointerTo();
  2899. llvm::Type *sliceTy = objGEP->getType()->getPointerElementType();
  2900. DXIL::ResourceClass RC = HLM.GetResourceClass(sliceTy);
  2901. DXIL::ResourceKind RK = HLM.GetResourceKind(sliceTy);
  2902. HLM.AddResourceTypeAnnotation(resTy, RC, RK);
  2903. }
  2904. llvm::FunctionType *funcTy =
  2905. llvm::FunctionType::get(RetTy, paramTyList, false);
  2906. Function *opFunc = CreateOpFunction(M, F, funcTy, group, opcode);
  2907. StringRef lower = hlsl::GetHLLowerStrategy(F);
  2908. if (!lower.empty())
  2909. hlsl::SetHLLowerStrategy(opFunc, lower);
  2910. for (auto user = F->user_begin(); user != F->user_end();) {
  2911. // User must be a call.
  2912. CallInst *oldCI = cast<CallInst>(*(user++));
  2913. SmallVector<Value *, 4> opcodeParamList;
  2914. Value *opcodeConst = Constant::getIntegerValue(opcodeTy, APInt(32, opcode));
  2915. opcodeParamList.emplace_back(opcodeConst);
  2916. opcodeParamList.append(oldCI->arg_operands().begin(),
  2917. oldCI->arg_operands().end());
  2918. IRBuilder<> Builder(oldCI);
  2919. if (isDoubleSubscriptFunc) {
  2920. // Change obj to the resource pointer.
  2921. Value *objVal = opcodeParamList[HLOperandIndex::kSubscriptObjectOpIdx];
  2922. GEPOperator *objGEP = cast<GEPOperator>(objVal);
  2923. SmallVector<Value *, 8> IndexList;
  2924. IndexList.append(objGEP->idx_begin(), objGEP->idx_end());
  2925. Value *lastIndex = IndexList.back();
  2926. ConstantInt *constIndex = cast<ConstantInt>(lastIndex);
  2927. DXASSERT_LOCALVAR(constIndex, constIndex->getLimitedValue() == 1, "last index must 1");
  2928. // Remove the last index.
  2929. IndexList.pop_back();
  2930. objVal = objGEP->getPointerOperand();
  2931. if (IndexList.size() > 1)
  2932. objVal = Builder.CreateInBoundsGEP(objVal, IndexList);
  2933. Value *Handle =
  2934. CreateHandleFromResPtr(objVal, HLM, HandleTy, resMetaMap, Builder);
  2935. // Change obj to the resource pointer.
  2936. opcodeParamList[HLOperandIndex::kSubscriptObjectOpIdx] = Handle;
  2937. // Set idx and mipIdx.
  2938. Value *mipIdx = opcodeParamList[HLOperandIndex::kSubscriptIndexOpIdx];
  2939. auto U = oldCI->user_begin();
  2940. Value *user = *U;
  2941. CallInst *secSub = cast<CallInst>(user);
  2942. unsigned idxOpIndex = HLOperandIndex::kSubscriptIndexOpIdx;
  2943. if (GetHLOpcodeGroupByName(secSub->getCalledFunction()) == HLOpcodeGroup::NotHL)
  2944. idxOpIndex--;
  2945. Value *idx = secSub->getArgOperand(idxOpIndex);
  2946. DXASSERT(secSub->hasOneUse(), "subscript should only has one use");
  2947. // Add the sampleIdx or mipLevel parameter to the end.
  2948. opcodeParamList[HLOperandIndex::kSubscriptIndexOpIdx] = idx;
  2949. opcodeParamList.emplace_back(mipIdx);
  2950. // Insert new call before secSub to make sure idx is ready to use.
  2951. Builder.SetInsertPoint(secSub);
  2952. }
  2953. for (unsigned i = 1; i < opcodeParamList.size(); i++) {
  2954. Value *arg = opcodeParamList[i];
  2955. llvm::Type *Ty = arg->getType();
  2956. if (Ty->isPointerTy()) {
  2957. Ty = Ty->getPointerElementType();
  2958. if (HLModule::IsHLSLObjectType(Ty) &&
  2959. // StreamOutput don't need handle.
  2960. !HLModule::IsStreamOutputType(Ty)) {
  2961. // Use object type directly, not by pointer.
  2962. // This will make sure temp object variable only used by ld/st.
  2963. if (GEPOperator *argGEP = dyn_cast<GEPOperator>(arg)) {
  2964. std::vector<Value*> idxList(argGEP->idx_begin(), argGEP->idx_end());
  2965. // Create instruction to avoid GEPOperator.
  2966. GetElementPtrInst *GEP = GetElementPtrInst::CreateInBounds(argGEP->getPointerOperand(),
  2967. idxList);
  2968. Builder.Insert(GEP);
  2969. arg = GEP;
  2970. }
  2971. Value *Handle = CreateHandleFromResPtr(arg, HLM, HandleTy,
  2972. resMetaMap, Builder);
  2973. opcodeParamList[i] = Handle;
  2974. }
  2975. }
  2976. }
  2977. Value *CI = Builder.CreateCall(opFunc, opcodeParamList);
  2978. if (!isDoubleSubscriptFunc) {
  2979. // replace new call and delete the old call
  2980. oldCI->replaceAllUsesWith(CI);
  2981. oldCI->eraseFromParent();
  2982. } else {
  2983. // For double script.
  2984. // Replace single users use with new CI.
  2985. auto U = oldCI->user_begin();
  2986. Value *user = *U;
  2987. CallInst *secSub = cast<CallInst>(user);
  2988. secSub->replaceAllUsesWith(CI);
  2989. secSub->eraseFromParent();
  2990. oldCI->eraseFromParent();
  2991. }
  2992. }
  2993. // delete the function
  2994. F->eraseFromParent();
  2995. }
  2996. static void AddOpcodeParamForIntrinsics(HLModule &HLM
  2997. , std::vector<std::pair<Function *, unsigned>> &intrinsicMap,
  2998. std::unordered_map<llvm::Type *, MDNode*> &resMetaMap) {
  2999. llvm::Type *HandleTy = HLM.GetOP()->GetHandleType();
  3000. for (auto mapIter : intrinsicMap) {
  3001. Function *F = mapIter.first;
  3002. if (F->user_empty()) {
  3003. // delete the function
  3004. F->eraseFromParent();
  3005. continue;
  3006. }
  3007. unsigned opcode = mapIter.second;
  3008. AddOpcodeParamForIntrinsic(HLM, F, opcode, HandleTy, resMetaMap);
  3009. }
  3010. }
  3011. static Value *CastLdValue(Value *Ptr, llvm::Type *FromTy, llvm::Type *ToTy, IRBuilder<> &Builder) {
  3012. if (ToTy->isVectorTy()) {
  3013. unsigned vecSize = ToTy->getVectorNumElements();
  3014. if (vecSize == 1 && ToTy->getVectorElementType() == FromTy) {
  3015. Value *V = Builder.CreateLoad(Ptr);
  3016. // ScalarToVec1Splat
  3017. // Change scalar into vec1.
  3018. Value *Vec1 = UndefValue::get(ToTy);
  3019. return Builder.CreateInsertElement(Vec1, V, (uint64_t)0);
  3020. } else if (FromTy->isVectorTy() && vecSize == 1) {
  3021. Value *V = Builder.CreateLoad(Ptr);
  3022. // VectorTrunc
  3023. // Change vector into vec1.
  3024. return Builder.CreateShuffleVector(V, V, {0});
  3025. } else if (FromTy->isArrayTy()) {
  3026. llvm::Type *FromEltTy = FromTy->getArrayElementType();
  3027. llvm::Type *ToEltTy = ToTy->getVectorElementType();
  3028. if (FromTy->getArrayNumElements() == vecSize && FromEltTy == ToEltTy) {
  3029. // ArrayToVector.
  3030. Value *NewLd = UndefValue::get(ToTy);
  3031. Value *zeroIdx = Builder.getInt32(0);
  3032. for (unsigned i = 0; i < vecSize; i++) {
  3033. Value *GEP = Builder.CreateInBoundsGEP(
  3034. Ptr, {zeroIdx, Builder.getInt32(i)});
  3035. Value *Elt = Builder.CreateLoad(GEP);
  3036. NewLd = Builder.CreateInsertElement(NewLd, Elt, i);
  3037. }
  3038. return NewLd;
  3039. }
  3040. }
  3041. } else if (FromTy == Builder.getInt1Ty()) {
  3042. Value *V = Builder.CreateLoad(Ptr);
  3043. // BoolCast
  3044. DXASSERT_NOMSG(ToTy->isIntegerTy());
  3045. return Builder.CreateZExt(V, ToTy);
  3046. }
  3047. return nullptr;
  3048. }
  3049. static Value *CastStValue(Value *Ptr, Value *V, llvm::Type *FromTy, llvm::Type *ToTy, IRBuilder<> &Builder) {
  3050. if (ToTy->isVectorTy()) {
  3051. unsigned vecSize = ToTy->getVectorNumElements();
  3052. if (vecSize == 1 && ToTy->getVectorElementType() == FromTy) {
  3053. // ScalarToVec1Splat
  3054. // Change vec1 back to scalar.
  3055. Value *Elt = Builder.CreateExtractElement(V, (uint64_t)0);
  3056. return Elt;
  3057. } else if (FromTy->isVectorTy() && vecSize == 1) {
  3058. // VectorTrunc
  3059. // Change vec1 into vector.
  3060. // Should not happen.
  3061. // Reported error at Sema::ImpCastExprToType.
  3062. DXASSERT_NOMSG(0);
  3063. } else if (FromTy->isArrayTy()) {
  3064. llvm::Type *FromEltTy = FromTy->getArrayElementType();
  3065. llvm::Type *ToEltTy = ToTy->getVectorElementType();
  3066. if (FromTy->getArrayNumElements() == vecSize && FromEltTy == ToEltTy) {
  3067. // ArrayToVector.
  3068. Value *zeroIdx = Builder.getInt32(0);
  3069. for (unsigned i = 0; i < vecSize; i++) {
  3070. Value *Elt = Builder.CreateExtractElement(V, i);
  3071. Value *GEP = Builder.CreateInBoundsGEP(
  3072. Ptr, {zeroIdx, Builder.getInt32(i)});
  3073. Builder.CreateStore(Elt, GEP);
  3074. }
  3075. // The store already done.
  3076. // Return null to ignore use of the return value.
  3077. return nullptr;
  3078. }
  3079. }
  3080. } else if (FromTy == Builder.getInt1Ty()) {
  3081. // BoolCast
  3082. // Change i1 to ToTy.
  3083. DXASSERT_NOMSG(ToTy->isIntegerTy());
  3084. Value *CastV = Builder.CreateICmpNE(V, ConstantInt::get(V->getType(), 0));
  3085. return CastV;
  3086. }
  3087. return nullptr;
  3088. }
  3089. static bool SimplifyBitCastLoad(LoadInst *LI, llvm::Type *FromTy, llvm::Type *ToTy, Value *Ptr) {
  3090. IRBuilder<> Builder(LI);
  3091. // Cast FromLd to ToTy.
  3092. Value *CastV = CastLdValue(Ptr, FromTy, ToTy, Builder);
  3093. if (CastV) {
  3094. LI->replaceAllUsesWith(CastV);
  3095. return true;
  3096. } else {
  3097. return false;
  3098. }
  3099. }
  3100. static bool SimplifyBitCastStore(StoreInst *SI, llvm::Type *FromTy, llvm::Type *ToTy, Value *Ptr) {
  3101. IRBuilder<> Builder(SI);
  3102. Value *V = SI->getValueOperand();
  3103. // Cast Val to FromTy.
  3104. Value *CastV = CastStValue(Ptr, V, FromTy, ToTy, Builder);
  3105. if (CastV) {
  3106. Builder.CreateStore(CastV, Ptr);
  3107. return true;
  3108. } else {
  3109. return false;
  3110. }
  3111. }
  3112. static bool SimplifyBitCastGEP(GEPOperator *GEP, llvm::Type *FromTy, llvm::Type *ToTy, Value *Ptr) {
  3113. if (ToTy->isVectorTy()) {
  3114. unsigned vecSize = ToTy->getVectorNumElements();
  3115. if (vecSize == 1 && ToTy->getVectorElementType() == FromTy) {
  3116. // ScalarToVec1Splat
  3117. GEP->replaceAllUsesWith(Ptr);
  3118. return true;
  3119. } else if (FromTy->isVectorTy() && vecSize == 1) {
  3120. // VectorTrunc
  3121. DXASSERT_NOMSG(
  3122. !isa<llvm::VectorType>(GEP->getType()->getPointerElementType()));
  3123. IRBuilder<> Builder(FromTy->getContext());
  3124. if (Instruction *I = dyn_cast<Instruction>(GEP))
  3125. Builder.SetInsertPoint(I);
  3126. std::vector<Value *> idxList(GEP->idx_begin(), GEP->idx_end());
  3127. Value *NewGEP = Builder.CreateInBoundsGEP(Ptr, idxList);
  3128. GEP->replaceAllUsesWith(NewGEP);
  3129. return true;
  3130. } else if (FromTy->isArrayTy()) {
  3131. llvm::Type *FromEltTy = FromTy->getArrayElementType();
  3132. llvm::Type *ToEltTy = ToTy->getVectorElementType();
  3133. if (FromTy->getArrayNumElements() == vecSize && FromEltTy == ToEltTy) {
  3134. // ArrayToVector.
  3135. }
  3136. }
  3137. } else if (FromTy == llvm::Type::getInt1Ty(FromTy->getContext())) {
  3138. // BoolCast
  3139. }
  3140. return false;
  3141. }
  3142. static void SimplifyBitCast(BitCastOperator *BC, std::vector<Instruction *> &deadInsts) {
  3143. Value *Ptr = BC->getOperand(0);
  3144. llvm::Type *FromTy = Ptr->getType();
  3145. llvm::Type *ToTy = BC->getType();
  3146. if (!FromTy->isPointerTy() || !ToTy->isPointerTy())
  3147. return;
  3148. FromTy = FromTy->getPointerElementType();
  3149. ToTy = ToTy->getPointerElementType();
  3150. // Take care case like %2 = bitcast %struct.T* %1 to <1 x float>*.
  3151. if (FromTy->isStructTy()) {
  3152. IRBuilder<> Builder(FromTy->getContext());
  3153. if (Instruction *I = dyn_cast<Instruction>(BC))
  3154. Builder.SetInsertPoint(I);
  3155. Value *zeroIdx = Builder.getInt32(0);
  3156. unsigned nestLevel = 1;
  3157. while (llvm::StructType *ST = dyn_cast<llvm::StructType>(FromTy)) {
  3158. FromTy = ST->getElementType(0);
  3159. nestLevel++;
  3160. }
  3161. std::vector<Value *> idxList(nestLevel, zeroIdx);
  3162. Ptr = Builder.CreateGEP(Ptr, idxList);
  3163. }
  3164. for (User *U : BC->users()) {
  3165. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  3166. if (SimplifyBitCastLoad(LI, FromTy, ToTy, Ptr)) {
  3167. LI->dropAllReferences();
  3168. deadInsts.emplace_back(LI);
  3169. }
  3170. } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  3171. if (SimplifyBitCastStore(SI, FromTy, ToTy, Ptr)) {
  3172. SI->dropAllReferences();
  3173. deadInsts.emplace_back(SI);
  3174. }
  3175. } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  3176. if (SimplifyBitCastGEP(GEP, FromTy, ToTy, Ptr))
  3177. if (Instruction *I = dyn_cast<Instruction>(GEP)) {
  3178. I->dropAllReferences();
  3179. deadInsts.emplace_back(I);
  3180. }
  3181. } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
  3182. // Skip function call.
  3183. } else if (BitCastInst *Cast = dyn_cast<BitCastInst>(U)) {
  3184. // Skip bitcast.
  3185. } else {
  3186. DXASSERT(0, "not support yet");
  3187. }
  3188. }
  3189. }
  3190. typedef float(__cdecl *FloatUnaryEvalFuncType)(float);
  3191. typedef double(__cdecl *DoubleUnaryEvalFuncType)(double);
  3192. typedef float(__cdecl *FloatBinaryEvalFuncType)(float, float);
  3193. typedef double(__cdecl *DoubleBinaryEvalFuncType)(double, double);
  3194. static Value * EvalUnaryIntrinsic(CallInst *CI,
  3195. FloatUnaryEvalFuncType floatEvalFunc,
  3196. DoubleUnaryEvalFuncType doubleEvalFunc) {
  3197. Value *V = CI->getArgOperand(0);
  3198. ConstantFP *fpV = cast<ConstantFP>(V);
  3199. llvm::Type *Ty = CI->getType();
  3200. Value *Result = nullptr;
  3201. if (Ty->isDoubleTy()) {
  3202. double dV = fpV->getValueAPF().convertToDouble();
  3203. Value *dResult = ConstantFP::get(V->getType(), doubleEvalFunc(dV));
  3204. CI->replaceAllUsesWith(dResult);
  3205. Result = dResult;
  3206. } else {
  3207. DXASSERT_NOMSG(Ty->isFloatTy());
  3208. float fV = fpV->getValueAPF().convertToFloat();
  3209. Value *dResult = ConstantFP::get(V->getType(), floatEvalFunc(fV));
  3210. CI->replaceAllUsesWith(dResult);
  3211. Result = dResult;
  3212. }
  3213. CI->eraseFromParent();
  3214. return Result;
  3215. }
  3216. static Value * EvalBinaryIntrinsic(CallInst *CI,
  3217. FloatBinaryEvalFuncType floatEvalFunc,
  3218. DoubleBinaryEvalFuncType doubleEvalFunc) {
  3219. Value *V0 = CI->getArgOperand(0);
  3220. ConstantFP *fpV0 = cast<ConstantFP>(V0);
  3221. Value *V1 = CI->getArgOperand(1);
  3222. ConstantFP *fpV1 = cast<ConstantFP>(V1);
  3223. llvm::Type *Ty = CI->getType();
  3224. Value *Result = nullptr;
  3225. if (Ty->isDoubleTy()) {
  3226. double dV0 = fpV0->getValueAPF().convertToDouble();
  3227. double dV1 = fpV1->getValueAPF().convertToDouble();
  3228. Value *dResult = ConstantFP::get(V0->getType(), doubleEvalFunc(dV0, dV1));
  3229. CI->replaceAllUsesWith(dResult);
  3230. Result = dResult;
  3231. } else {
  3232. DXASSERT_NOMSG(Ty->isFloatTy());
  3233. float fV0 = fpV0->getValueAPF().convertToFloat();
  3234. float fV1 = fpV1->getValueAPF().convertToFloat();
  3235. Value *dResult = ConstantFP::get(V0->getType(), floatEvalFunc(fV0, fV1));
  3236. CI->replaceAllUsesWith(dResult);
  3237. Result = dResult;
  3238. }
  3239. CI->eraseFromParent();
  3240. return Result;
  3241. }
  3242. static Value * TryEvalIntrinsic(CallInst *CI, IntrinsicOp intriOp) {
  3243. switch (intriOp) {
  3244. case IntrinsicOp::IOP_tan: {
  3245. return EvalUnaryIntrinsic(CI, tanf, tan);
  3246. } break;
  3247. case IntrinsicOp::IOP_tanh: {
  3248. return EvalUnaryIntrinsic(CI, tanhf, tanh);
  3249. } break;
  3250. case IntrinsicOp::IOP_sin: {
  3251. return EvalUnaryIntrinsic(CI, sinf, sin);
  3252. } break;
  3253. case IntrinsicOp::IOP_sinh: {
  3254. return EvalUnaryIntrinsic(CI, sinhf, sinh);
  3255. } break;
  3256. case IntrinsicOp::IOP_cos: {
  3257. return EvalUnaryIntrinsic(CI, cosf, cos);
  3258. } break;
  3259. case IntrinsicOp::IOP_cosh: {
  3260. return EvalUnaryIntrinsic(CI, coshf, cosh);
  3261. } break;
  3262. case IntrinsicOp::IOP_asin: {
  3263. return EvalUnaryIntrinsic(CI, asinf, asin);
  3264. } break;
  3265. case IntrinsicOp::IOP_acos: {
  3266. return EvalUnaryIntrinsic(CI, acosf, acos);
  3267. } break;
  3268. case IntrinsicOp::IOP_atan: {
  3269. return EvalUnaryIntrinsic(CI, atanf, atan);
  3270. } break;
  3271. case IntrinsicOp::IOP_atan2: {
  3272. Value *V0 = CI->getArgOperand(0);
  3273. ConstantFP *fpV0 = cast<ConstantFP>(V0);
  3274. Value *V1 = CI->getArgOperand(1);
  3275. ConstantFP *fpV1 = cast<ConstantFP>(V1);
  3276. llvm::Type *Ty = CI->getType();
  3277. Value *Result = nullptr;
  3278. if (Ty->isDoubleTy()) {
  3279. double dV0 = fpV0->getValueAPF().convertToDouble();
  3280. double dV1 = fpV1->getValueAPF().convertToDouble();
  3281. Value *atanV = ConstantFP::get(CI->getType(), atan(dV0 / dV1));
  3282. CI->replaceAllUsesWith(atanV);
  3283. Result = atanV;
  3284. } else {
  3285. DXASSERT_NOMSG(Ty->isFloatTy());
  3286. float fV0 = fpV0->getValueAPF().convertToFloat();
  3287. float fV1 = fpV1->getValueAPF().convertToFloat();
  3288. Value *atanV = ConstantFP::get(CI->getType(), atanf(fV0 / fV1));
  3289. CI->replaceAllUsesWith(atanV);
  3290. Result = atanV;
  3291. }
  3292. CI->eraseFromParent();
  3293. return Result;
  3294. } break;
  3295. case IntrinsicOp::IOP_sqrt: {
  3296. return EvalUnaryIntrinsic(CI, sqrtf, sqrt);
  3297. } break;
  3298. case IntrinsicOp::IOP_rsqrt: {
  3299. auto rsqrtF = [](float v) -> float { return 1.0 / sqrtf(v); };
  3300. auto rsqrtD = [](double v) -> double { return 1.0 / sqrt(v); };
  3301. return EvalUnaryIntrinsic(CI, rsqrtF, rsqrtD);
  3302. } break;
  3303. case IntrinsicOp::IOP_exp: {
  3304. return EvalUnaryIntrinsic(CI, expf, exp);
  3305. } break;
  3306. case IntrinsicOp::IOP_exp2: {
  3307. return EvalUnaryIntrinsic(CI, exp2f, exp2);
  3308. } break;
  3309. case IntrinsicOp::IOP_log: {
  3310. return EvalUnaryIntrinsic(CI, logf, log);
  3311. } break;
  3312. case IntrinsicOp::IOP_log10: {
  3313. return EvalUnaryIntrinsic(CI, log10f, log10);
  3314. } break;
  3315. case IntrinsicOp::IOP_log2: {
  3316. return EvalUnaryIntrinsic(CI, log2f, log2);
  3317. } break;
  3318. case IntrinsicOp::IOP_pow: {
  3319. return EvalBinaryIntrinsic(CI, powf, pow);
  3320. } break;
  3321. case IntrinsicOp::IOP_max: {
  3322. auto maxF = [](float a, float b) -> float { return a > b ? a:b; };
  3323. auto maxD = [](double a, double b) -> double { return a > b ? a:b; };
  3324. return EvalBinaryIntrinsic(CI, maxF, maxD);
  3325. } break;
  3326. case IntrinsicOp::IOP_min: {
  3327. auto minF = [](float a, float b) -> float { return a < b ? a:b; };
  3328. auto minD = [](double a, double b) -> double { return a < b ? a:b; };
  3329. return EvalBinaryIntrinsic(CI, minF, minD);
  3330. } break;
  3331. case IntrinsicOp::IOP_rcp: {
  3332. auto rcpF = [](float v) -> float { return 1.0 / v; };
  3333. auto rcpD = [](double v) -> double { return 1.0 / v; };
  3334. return EvalUnaryIntrinsic(CI, rcpF, rcpD);
  3335. } break;
  3336. case IntrinsicOp::IOP_ceil: {
  3337. return EvalUnaryIntrinsic(CI, ceilf, ceil);
  3338. } break;
  3339. case IntrinsicOp::IOP_floor: {
  3340. return EvalUnaryIntrinsic(CI, floorf, floor);
  3341. } break;
  3342. case IntrinsicOp::IOP_round: {
  3343. return EvalUnaryIntrinsic(CI, roundf, round);
  3344. } break;
  3345. case IntrinsicOp::IOP_trunc: {
  3346. return EvalUnaryIntrinsic(CI, truncf, trunc);
  3347. } break;
  3348. case IntrinsicOp::IOP_frac: {
  3349. auto fracF = [](float v) -> float {
  3350. int exp = 0;
  3351. return frexpf(v, &exp);
  3352. };
  3353. auto fracD = [](double v) -> double {
  3354. int exp = 0;
  3355. return frexp(v, &exp);
  3356. };
  3357. return EvalUnaryIntrinsic(CI, fracF, fracD);
  3358. } break;
  3359. case IntrinsicOp::IOP_isnan: {
  3360. Value *V = CI->getArgOperand(0);
  3361. ConstantFP *fV = cast<ConstantFP>(V);
  3362. bool isNan = fV->getValueAPF().isNaN();
  3363. Constant *cNan = ConstantInt::get(CI->getType(), isNan ? 1 : 0);
  3364. CI->replaceAllUsesWith(cNan);
  3365. CI->eraseFromParent();
  3366. return cNan;
  3367. } break;
  3368. default:
  3369. return nullptr;
  3370. }
  3371. }
  3372. static void SimpleTransformForHLDXIR(Instruction *I,
  3373. std::vector<Instruction *> &deadInsts) {
  3374. unsigned opcode = I->getOpcode();
  3375. switch (opcode) {
  3376. case Instruction::BitCast: {
  3377. BitCastOperator *BCI = cast<BitCastOperator>(I);
  3378. SimplifyBitCast(BCI, deadInsts);
  3379. } break;
  3380. case Instruction::Load: {
  3381. LoadInst *ldInst = cast<LoadInst>(I);
  3382. DXASSERT(!HLMatrixLower::IsMatrixType(ldInst->getType()),
  3383. "matrix load should use HL LdStMatrix");
  3384. Value *Ptr = ldInst->getPointerOperand();
  3385. if (ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(Ptr)) {
  3386. if (BitCastOperator *BCO = dyn_cast<BitCastOperator>(CE)) {
  3387. SimplifyBitCast(BCO, deadInsts);
  3388. }
  3389. }
  3390. } break;
  3391. case Instruction::Store: {
  3392. StoreInst *stInst = cast<StoreInst>(I);
  3393. Value *V = stInst->getValueOperand();
  3394. DXASSERT_LOCALVAR(V, !HLMatrixLower::IsMatrixType(V->getType()),
  3395. "matrix store should use HL LdStMatrix");
  3396. Value *Ptr = stInst->getPointerOperand();
  3397. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
  3398. if (BitCastOperator *BCO = dyn_cast<BitCastOperator>(CE)) {
  3399. SimplifyBitCast(BCO, deadInsts);
  3400. }
  3401. }
  3402. } break;
  3403. case Instruction::LShr:
  3404. case Instruction::AShr:
  3405. case Instruction::Shl: {
  3406. llvm::BinaryOperator *BO = cast<llvm::BinaryOperator>(I);
  3407. Value *op2 = BO->getOperand(1);
  3408. IntegerType *Ty = cast<IntegerType>(BO->getType()->getScalarType());
  3409. unsigned bitWidth = Ty->getBitWidth();
  3410. // Clamp op2 to 0 ~ bitWidth-1
  3411. if (ConstantInt *cOp2 = dyn_cast<ConstantInt>(op2)) {
  3412. unsigned iOp2 = cOp2->getLimitedValue();
  3413. unsigned clampedOp2 = iOp2 & (bitWidth - 1);
  3414. if (iOp2 != clampedOp2) {
  3415. BO->setOperand(1, ConstantInt::get(op2->getType(), clampedOp2));
  3416. }
  3417. } else {
  3418. Value *mask = ConstantInt::get(op2->getType(), bitWidth - 1);
  3419. IRBuilder<> Builder(I);
  3420. op2 = Builder.CreateAnd(op2, mask);
  3421. BO->setOperand(1, op2);
  3422. }
  3423. } break;
  3424. }
  3425. }
  3426. // Do simple transform to make later lower pass easier.
  3427. static void SimpleTransformForHLDXIR(llvm::Module *pM) {
  3428. std::vector<Instruction *> deadInsts;
  3429. for (Function &F : pM->functions()) {
  3430. for (BasicBlock &BB : F.getBasicBlockList()) {
  3431. for (BasicBlock::iterator Iter = BB.begin(); Iter != BB.end(); ) {
  3432. Instruction *I = (Iter++);
  3433. SimpleTransformForHLDXIR(I, deadInsts);
  3434. }
  3435. }
  3436. }
  3437. for (Instruction * I : deadInsts)
  3438. I->dropAllReferences();
  3439. for (Instruction * I : deadInsts)
  3440. I->eraseFromParent();
  3441. deadInsts.clear();
  3442. for (GlobalVariable &GV : pM->globals()) {
  3443. if (dxilutil::IsStaticGlobal(&GV)) {
  3444. for (User *U : GV.users()) {
  3445. if (BitCastOperator *BCO = dyn_cast<BitCastOperator>(U)) {
  3446. SimplifyBitCast(BCO, deadInsts);
  3447. }
  3448. }
  3449. }
  3450. }
  3451. for (Instruction * I : deadInsts)
  3452. I->dropAllReferences();
  3453. for (Instruction * I : deadInsts)
  3454. I->eraseFromParent();
  3455. }
  3456. // Clone shader entry function to be called by other functions.
  3457. // The original function will be used as shader entry.
  3458. static void CloneShaderEntry(Function *ShaderF, StringRef EntryName,
  3459. HLModule &HLM) {
  3460. // Use mangled name for cloned one.
  3461. Function *F = Function::Create(ShaderF->getFunctionType(),
  3462. GlobalValue::LinkageTypes::ExternalLinkage,
  3463. "", HLM.GetModule());
  3464. F->takeName(ShaderF);
  3465. // Set to name before mangled.
  3466. ShaderF->setName(EntryName);
  3467. SmallVector<ReturnInst *, 2> Returns;
  3468. ValueToValueMapTy vmap;
  3469. // Map params.
  3470. auto entryParamIt = F->arg_begin();
  3471. for (Argument &param : ShaderF->args()) {
  3472. vmap[&param] = (entryParamIt++);
  3473. }
  3474. llvm::CloneFunctionInto(F, ShaderF, vmap, /*ModuleLevelChagnes*/ false,
  3475. Returns);
  3476. // Copy function annotation.
  3477. DxilFunctionAnnotation *shaderAnnot = HLM.GetFunctionAnnotation(ShaderF);
  3478. DxilFunctionAnnotation *annot = HLM.AddFunctionAnnotation(F);
  3479. DxilParameterAnnotation &retAnnot = shaderAnnot->GetRetTypeAnnotation();
  3480. DxilParameterAnnotation &cloneRetAnnot = annot->GetRetTypeAnnotation();
  3481. cloneRetAnnot = retAnnot;
  3482. // Clear semantic for cloned one.
  3483. cloneRetAnnot.SetSemanticString("");
  3484. cloneRetAnnot.SetSemanticIndexVec({});
  3485. for (unsigned i = 0; i < shaderAnnot->GetNumParameters(); i++) {
  3486. DxilParameterAnnotation &cloneParamAnnot = annot->GetParameterAnnotation(i);
  3487. DxilParameterAnnotation &paramAnnot =
  3488. shaderAnnot->GetParameterAnnotation(i);
  3489. cloneParamAnnot = paramAnnot;
  3490. // Clear semantic for cloned one.
  3491. cloneParamAnnot.SetSemanticString("");
  3492. cloneParamAnnot.SetSemanticIndexVec({});
  3493. }
  3494. }
  3495. // For case like:
  3496. //cbuffer A {
  3497. // float a;
  3498. // int b;
  3499. //}
  3500. //
  3501. //const static struct {
  3502. // float a;
  3503. // int b;
  3504. //} ST = { a, b };
  3505. // Replace user of ST with a and b.
  3506. static bool ReplaceConstStaticGlobalUser(GEPOperator *GEP,
  3507. std::vector<Constant *> &InitList,
  3508. IRBuilder<> &Builder) {
  3509. if (GEP->getNumIndices() < 2) {
  3510. // Don't use sub element.
  3511. return false;
  3512. }
  3513. SmallVector<Value *, 4> idxList;
  3514. auto iter = GEP->idx_begin();
  3515. idxList.emplace_back(*(iter++));
  3516. ConstantInt *subIdx = dyn_cast<ConstantInt>(*(iter++));
  3517. DXASSERT(subIdx, "else dynamic indexing on struct field");
  3518. unsigned subIdxImm = subIdx->getLimitedValue();
  3519. DXASSERT(subIdxImm < InitList.size(), "else struct index out of bound");
  3520. Constant *subPtr = InitList[subIdxImm];
  3521. // Move every idx to idxList except idx for InitList.
  3522. while (iter != GEP->idx_end()) {
  3523. idxList.emplace_back(*(iter++));
  3524. }
  3525. Value *NewGEP = Builder.CreateGEP(subPtr, idxList);
  3526. GEP->replaceAllUsesWith(NewGEP);
  3527. return true;
  3528. }
  3529. static void ReplaceConstStaticGlobals(
  3530. std::unordered_map<GlobalVariable *, std::vector<Constant *>>
  3531. &staticConstGlobalInitListMap,
  3532. std::unordered_map<GlobalVariable *, Function *>
  3533. &staticConstGlobalCtorMap) {
  3534. for (auto &iter : staticConstGlobalInitListMap) {
  3535. GlobalVariable *GV = iter.first;
  3536. std::vector<Constant *> &InitList = iter.second;
  3537. LLVMContext &Ctx = GV->getContext();
  3538. // Do the replace.
  3539. bool bPass = true;
  3540. for (User *U : GV->users()) {
  3541. IRBuilder<> Builder(Ctx);
  3542. if (GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(U)) {
  3543. Builder.SetInsertPoint(GEPInst);
  3544. bPass &= ReplaceConstStaticGlobalUser(cast<GEPOperator>(GEPInst), InitList, Builder);
  3545. } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  3546. bPass &= ReplaceConstStaticGlobalUser(GEP, InitList, Builder);
  3547. } else {
  3548. DXASSERT(false, "invalid user of const static global");
  3549. }
  3550. }
  3551. // Clear the Ctor which is useless now.
  3552. if (bPass) {
  3553. Function *Ctor = staticConstGlobalCtorMap[GV];
  3554. Ctor->getBasicBlockList().clear();
  3555. BasicBlock *Entry = BasicBlock::Create(Ctx, "", Ctor);
  3556. IRBuilder<> Builder(Entry);
  3557. Builder.CreateRetVoid();
  3558. }
  3559. }
  3560. }
  3561. bool BuildImmInit(Function *Ctor) {
  3562. GlobalVariable *GV = nullptr;
  3563. SmallVector<Constant *, 4> ImmList;
  3564. bool allConst = true;
  3565. for (inst_iterator I = inst_begin(Ctor), E = inst_end(Ctor); I != E; ++I) {
  3566. if (StoreInst *SI = dyn_cast<StoreInst>(&(*I))) {
  3567. Value *V = SI->getValueOperand();
  3568. if (!isa<Constant>(V) || V->getType()->isPointerTy()) {
  3569. allConst = false;
  3570. break;
  3571. }
  3572. ImmList.emplace_back(cast<Constant>(V));
  3573. Value *Ptr = SI->getPointerOperand();
  3574. if (GEPOperator *GepOp = dyn_cast<GEPOperator>(Ptr)) {
  3575. Ptr = GepOp->getPointerOperand();
  3576. if (GlobalVariable *pGV = dyn_cast<GlobalVariable>(Ptr)) {
  3577. if (GV == nullptr)
  3578. GV = pGV;
  3579. else
  3580. DXASSERT(GV == pGV, "else pointer mismatch");
  3581. }
  3582. }
  3583. } else {
  3584. if (!isa<ReturnInst>(*I)) {
  3585. allConst = false;
  3586. break;
  3587. }
  3588. }
  3589. }
  3590. if (!allConst)
  3591. return false;
  3592. if (!GV)
  3593. return false;
  3594. llvm::Type *Ty = GV->getType()->getElementType();
  3595. llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty);
  3596. // TODO: support other types.
  3597. if (!AT)
  3598. return false;
  3599. if (ImmList.size() != AT->getNumElements())
  3600. return false;
  3601. Constant *Init = llvm::ConstantArray::get(AT, ImmList);
  3602. GV->setInitializer(Init);
  3603. return true;
  3604. }
  3605. void ProcessCtorFunctions(llvm::Module &M, StringRef globalName,
  3606. Instruction *InsertPt) {
  3607. // add global call to entry func
  3608. GlobalVariable *GV = M.getGlobalVariable(globalName);
  3609. if (GV) {
  3610. if (ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer())) {
  3611. IRBuilder<> Builder(InsertPt);
  3612. for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e;
  3613. ++i) {
  3614. if (isa<ConstantAggregateZero>(*i))
  3615. continue;
  3616. ConstantStruct *CS = cast<ConstantStruct>(*i);
  3617. if (isa<ConstantPointerNull>(CS->getOperand(1)))
  3618. continue;
  3619. // Must have a function or null ptr.
  3620. if (!isa<Function>(CS->getOperand(1)))
  3621. continue;
  3622. Function *Ctor = cast<Function>(CS->getOperand(1));
  3623. DXASSERT(Ctor->getReturnType()->isVoidTy() && Ctor->arg_size() == 0,
  3624. "function type must be void (void)");
  3625. for (inst_iterator I = inst_begin(Ctor), E = inst_end(Ctor); I != E;
  3626. ++I) {
  3627. if (CallInst *CI = dyn_cast<CallInst>(&(*I))) {
  3628. Function *F = CI->getCalledFunction();
  3629. // Try to build imm initilizer.
  3630. // If not work, add global call to entry func.
  3631. if (BuildImmInit(F) == false) {
  3632. Builder.CreateCall(F);
  3633. }
  3634. } else {
  3635. DXASSERT(isa<ReturnInst>(&(*I)),
  3636. "else invalid Global constructor function");
  3637. }
  3638. }
  3639. }
  3640. // remove the GV
  3641. GV->eraseFromParent();
  3642. }
  3643. }
  3644. }
  3645. void CGMSHLSLRuntime::SetPatchConstantFunction(const EntryFunctionInfo &EntryFunc) {
  3646. auto AttrsIter = HSEntryPatchConstantFuncAttr.find(EntryFunc.Func);
  3647. DXASSERT(AttrsIter != HSEntryPatchConstantFuncAttr.end(),
  3648. "we have checked this in AddHLSLFunctionInfo()");
  3649. SetPatchConstantFunctionWithAttr(Entry, AttrsIter->second);
  3650. }
  3651. void CGMSHLSLRuntime::SetPatchConstantFunctionWithAttr(
  3652. const EntryFunctionInfo &EntryFunc,
  3653. const clang::HLSLPatchConstantFuncAttr *PatchConstantFuncAttr) {
  3654. StringRef funcName = PatchConstantFuncAttr->getFunctionName();
  3655. auto Entry = patchConstantFunctionMap.find(funcName);
  3656. if (Entry == patchConstantFunctionMap.end()) {
  3657. DiagnosticsEngine &Diags = CGM.getDiags();
  3658. unsigned DiagID =
  3659. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  3660. "Cannot find patchconstantfunc %0.");
  3661. Diags.Report(PatchConstantFuncAttr->getLocation(), DiagID)
  3662. << funcName;
  3663. return;
  3664. }
  3665. if (Entry->second.NumOverloads != 1) {
  3666. DiagnosticsEngine &Diags = CGM.getDiags();
  3667. unsigned DiagID =
  3668. Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  3669. "Multiple overloads of patchconstantfunc %0.");
  3670. unsigned NoteID =
  3671. Diags.getCustomDiagID(DiagnosticsEngine::Note,
  3672. "This overload was selected.");
  3673. Diags.Report(PatchConstantFuncAttr->getLocation(), DiagID)
  3674. << funcName;
  3675. Diags.Report(Entry->second.SL, NoteID);
  3676. }
  3677. Function *patchConstFunc = Entry->second.Func;
  3678. DxilFunctionProps *HSProps = &m_pHLModule->GetDxilFunctionProps(EntryFunc.Func);
  3679. DXASSERT(HSProps != nullptr,
  3680. " else AddHLSLFunctionInfo did not save the dxil function props for the "
  3681. "HS entry.");
  3682. HSProps->ShaderProps.HS.patchConstantFunc = patchConstFunc;
  3683. DXASSERT_NOMSG(patchConstantFunctionPropsMap.count(patchConstFunc));
  3684. // Check no inout parameter for patch constant function.
  3685. DxilFunctionAnnotation *patchConstFuncAnnotation =
  3686. m_pHLModule->GetFunctionAnnotation(patchConstFunc);
  3687. for (unsigned i = 0; i < patchConstFuncAnnotation->GetNumParameters(); i++) {
  3688. if (patchConstFuncAnnotation->GetParameterAnnotation(i)
  3689. .GetParamInputQual() == DxilParamInputQual::Inout) {
  3690. DiagnosticsEngine &Diags = CGM.getDiags();
  3691. unsigned DiagID = Diags.getCustomDiagID(
  3692. DiagnosticsEngine::Error,
  3693. "Patch Constant function %0 should not have inout param.");
  3694. Diags.Report(Entry->second.SL, DiagID) << funcName;
  3695. }
  3696. }
  3697. // Input/Output control point validation.
  3698. if (patchConstantFunctionPropsMap.count(patchConstFunc)) {
  3699. const DxilFunctionProps &patchProps =
  3700. *patchConstantFunctionPropsMap[patchConstFunc];
  3701. if (patchProps.ShaderProps.HS.inputControlPoints != 0 &&
  3702. patchProps.ShaderProps.HS.inputControlPoints !=
  3703. HSProps->ShaderProps.HS.inputControlPoints) {
  3704. DiagnosticsEngine &Diags = CGM.getDiags();
  3705. unsigned DiagID =
  3706. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  3707. "Patch constant function's input patch input "
  3708. "should have %0 elements, but has %1.");
  3709. Diags.Report(Entry->second.SL, DiagID)
  3710. << HSProps->ShaderProps.HS.inputControlPoints
  3711. << patchProps.ShaderProps.HS.inputControlPoints;
  3712. }
  3713. if (patchProps.ShaderProps.HS.outputControlPoints != 0 &&
  3714. patchProps.ShaderProps.HS.outputControlPoints !=
  3715. HSProps->ShaderProps.HS.outputControlPoints) {
  3716. DiagnosticsEngine &Diags = CGM.getDiags();
  3717. unsigned DiagID = Diags.getCustomDiagID(
  3718. DiagnosticsEngine::Error,
  3719. "Patch constant function's output patch input "
  3720. "should have %0 elements, but has %1.");
  3721. Diags.Report(Entry->second.SL, DiagID)
  3722. << HSProps->ShaderProps.HS.outputControlPoints
  3723. << patchProps.ShaderProps.HS.outputControlPoints;
  3724. }
  3725. }
  3726. }
  3727. void CGMSHLSLRuntime::FinishCodeGen() {
  3728. // Library don't have entry.
  3729. if (!m_bIsLib) {
  3730. SetEntryFunction();
  3731. // If at this point we haven't determined the entry function it's an error.
  3732. if (m_pHLModule->GetEntryFunction() == nullptr) {
  3733. assert(CGM.getDiags().hasErrorOccurred() &&
  3734. "else SetEntryFunction should have reported this condition");
  3735. return;
  3736. }
  3737. if (m_pHLModule->GetShaderModel()->IsHS()) {
  3738. SetPatchConstantFunction(Entry);
  3739. }
  3740. } else {
  3741. for (auto &it : entryFunctionMap) {
  3742. CloneShaderEntry(it.second.Func, it.getKey(), *m_pHLModule);
  3743. auto AttrIter = HSEntryPatchConstantFuncAttr.find(it.second.Func);
  3744. if (AttrIter != HSEntryPatchConstantFuncAttr.end()) {
  3745. SetPatchConstantFunctionWithAttr(it.second, AttrIter->second);
  3746. }
  3747. }
  3748. }
  3749. ReplaceConstStaticGlobals(staticConstGlobalInitListMap,
  3750. staticConstGlobalCtorMap);
  3751. // Create copy for clip plane.
  3752. for (Function *F : clipPlaneFuncList) {
  3753. DxilFunctionProps &props = m_pHLModule->GetDxilFunctionProps(F);
  3754. IRBuilder<> Builder(F->getEntryBlock().getFirstInsertionPt());
  3755. for (unsigned i = 0; i < DXIL::kNumClipPlanes; i++) {
  3756. Value *clipPlane = props.ShaderProps.VS.clipPlanes[i];
  3757. if (!clipPlane)
  3758. continue;
  3759. if (m_bDebugInfo) {
  3760. Builder.SetCurrentDebugLocation(debugInfoMap[clipPlane]);
  3761. }
  3762. llvm::Type *Ty = clipPlane->getType()->getPointerElementType();
  3763. // Constant *zeroInit = ConstantFP::get(Ty, 0);
  3764. GlobalVariable *GV = new llvm::GlobalVariable(
  3765. TheModule, Ty, /*IsConstant*/ false, // constant false to store.
  3766. llvm::GlobalValue::ExternalLinkage,
  3767. /*InitVal*/ nullptr, Twine("SV_ClipPlane") + Twine(i));
  3768. Value *initVal = Builder.CreateLoad(clipPlane);
  3769. Builder.CreateStore(initVal, GV);
  3770. props.ShaderProps.VS.clipPlanes[i] = GV;
  3771. }
  3772. }
  3773. // Allocate constant buffers.
  3774. AllocateDxilConstantBuffers(m_pHLModule);
  3775. // TODO: create temp variable for constant which has store use.
  3776. // Create Global variable and type annotation for each CBuffer.
  3777. ConstructCBuffer(m_pHLModule, CBufferType, m_ConstVarAnnotationMap);
  3778. if (!m_bIsLib) {
  3779. // need this for "llvm.global_dtors"?
  3780. ProcessCtorFunctions(TheModule ,"llvm.global_ctors",
  3781. Entry.Func->getEntryBlock().getFirstInsertionPt());
  3782. }
  3783. // translate opcode into parameter for intrinsic functions
  3784. AddOpcodeParamForIntrinsics(*m_pHLModule, m_IntrinsicMap, resMetadataMap);
  3785. // Pin entry point and constant buffers, mark everything else internal.
  3786. for (Function &f : m_pHLModule->GetModule()->functions()) {
  3787. if (!m_bIsLib) {
  3788. if (&f == m_pHLModule->GetEntryFunction() ||
  3789. IsPatchConstantFunction(&f) || f.isDeclaration()) {
  3790. f.setLinkage(GlobalValue::LinkageTypes::ExternalLinkage);
  3791. } else {
  3792. f.setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  3793. }
  3794. }
  3795. // Skip no inline functions.
  3796. if (f.hasFnAttribute(llvm::Attribute::NoInline))
  3797. continue;
  3798. // Always inline for used functions.
  3799. if (!f.user_empty())
  3800. f.addFnAttr(llvm::Attribute::AlwaysInline);
  3801. }
  3802. // Do simple transform to make later lower pass easier.
  3803. SimpleTransformForHLDXIR(m_pHLModule->GetModule());
  3804. // Handle lang extensions if provided.
  3805. if (CGM.getCodeGenOpts().HLSLExtensionsCodegen) {
  3806. // Add semantic defines for extensions if any are available.
  3807. HLSLExtensionsCodegenHelper::SemanticDefineErrorList errors =
  3808. CGM.getCodeGenOpts().HLSLExtensionsCodegen->WriteSemanticDefines(m_pHLModule->GetModule());
  3809. DiagnosticsEngine &Diags = CGM.getDiags();
  3810. for (const HLSLExtensionsCodegenHelper::SemanticDefineError& error : errors) {
  3811. DiagnosticsEngine::Level level = DiagnosticsEngine::Error;
  3812. if (error.IsWarning())
  3813. level = DiagnosticsEngine::Warning;
  3814. unsigned DiagID = Diags.getCustomDiagID(level, "%0");
  3815. Diags.Report(SourceLocation::getFromRawEncoding(error.Location()), DiagID) << error.Message();
  3816. }
  3817. // Add root signature from a #define. Overrides root signature in function attribute.
  3818. {
  3819. using Status = HLSLExtensionsCodegenHelper::CustomRootSignature::Status;
  3820. HLSLExtensionsCodegenHelper::CustomRootSignature customRootSig;
  3821. Status status = CGM.getCodeGenOpts().HLSLExtensionsCodegen->GetCustomRootSignature(&customRootSig);
  3822. if (status == Status::FOUND) {
  3823. CompileRootSignature(customRootSig.RootSignature, Diags,
  3824. SourceLocation::getFromRawEncoding(customRootSig.EncodedSourceLocation),
  3825. rootSigVer, &m_pHLModule->GetRootSignature());
  3826. }
  3827. }
  3828. }
  3829. // At this point, we have a high-level DXIL module - record this.
  3830. SetPauseResumePasses(*m_pHLModule->GetModule(), "hlsl-hlemit", "hlsl-hlensure");
  3831. }
  3832. RValue CGMSHLSLRuntime::EmitHLSLBuiltinCallExpr(CodeGenFunction &CGF,
  3833. const FunctionDecl *FD,
  3834. const CallExpr *E,
  3835. ReturnValueSlot ReturnValue) {
  3836. StringRef name = FD->getName();
  3837. const Decl *TargetDecl = E->getCalleeDecl();
  3838. llvm::Value *Callee = CGF.EmitScalarExpr(E->getCallee());
  3839. RValue RV = CGF.EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
  3840. TargetDecl);
  3841. if (RV.isScalar() && RV.getScalarVal() != nullptr) {
  3842. if (CallInst *CI = dyn_cast<CallInst>(RV.getScalarVal())) {
  3843. Function *F = CI->getCalledFunction();
  3844. HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  3845. if (group == HLOpcodeGroup::HLIntrinsic) {
  3846. bool allOperandImm = true;
  3847. for (auto &operand : CI->arg_operands()) {
  3848. bool isImm = isa<ConstantInt>(operand) || isa<ConstantFP>(operand);
  3849. if (!isImm) {
  3850. allOperandImm = false;
  3851. break;
  3852. } else if (operand->getType()->isHalfTy()) {
  3853. // Not support half Eval yet.
  3854. allOperandImm = false;
  3855. break;
  3856. }
  3857. }
  3858. if (allOperandImm) {
  3859. unsigned intrinsicOpcode;
  3860. StringRef intrinsicGroup;
  3861. hlsl::GetIntrinsicOp(FD, intrinsicOpcode, intrinsicGroup);
  3862. IntrinsicOp opcode = static_cast<IntrinsicOp>(intrinsicOpcode);
  3863. if (Value *Result = TryEvalIntrinsic(CI, opcode)) {
  3864. RV = RValue::get(Result);
  3865. }
  3866. }
  3867. }
  3868. }
  3869. }
  3870. return RV;
  3871. }
  3872. static HLOpcodeGroup GetHLOpcodeGroup(const clang::Stmt::StmtClass stmtClass) {
  3873. switch (stmtClass) {
  3874. case Stmt::CStyleCastExprClass:
  3875. case Stmt::ImplicitCastExprClass:
  3876. case Stmt::CXXFunctionalCastExprClass:
  3877. return HLOpcodeGroup::HLCast;
  3878. case Stmt::InitListExprClass:
  3879. return HLOpcodeGroup::HLInit;
  3880. case Stmt::BinaryOperatorClass:
  3881. case Stmt::CompoundAssignOperatorClass:
  3882. return HLOpcodeGroup::HLBinOp;
  3883. case Stmt::UnaryOperatorClass:
  3884. return HLOpcodeGroup::HLUnOp;
  3885. case Stmt::ExtMatrixElementExprClass:
  3886. return HLOpcodeGroup::HLSubscript;
  3887. case Stmt::CallExprClass:
  3888. return HLOpcodeGroup::HLIntrinsic;
  3889. case Stmt::ConditionalOperatorClass:
  3890. return HLOpcodeGroup::HLSelect;
  3891. default:
  3892. llvm_unreachable("not support operation");
  3893. }
  3894. }
  3895. // NOTE: This table must match BinaryOperator::Opcode
  3896. static const HLBinaryOpcode BinaryOperatorKindMap[] = {
  3897. HLBinaryOpcode::Invalid, // PtrMemD
  3898. HLBinaryOpcode::Invalid, // PtrMemI
  3899. HLBinaryOpcode::Mul, HLBinaryOpcode::Div, HLBinaryOpcode::Rem,
  3900. HLBinaryOpcode::Add, HLBinaryOpcode::Sub, HLBinaryOpcode::Shl,
  3901. HLBinaryOpcode::Shr, HLBinaryOpcode::LT, HLBinaryOpcode::GT,
  3902. HLBinaryOpcode::LE, HLBinaryOpcode::GE, HLBinaryOpcode::EQ,
  3903. HLBinaryOpcode::NE, HLBinaryOpcode::And, HLBinaryOpcode::Xor,
  3904. HLBinaryOpcode::Or, HLBinaryOpcode::LAnd, HLBinaryOpcode::LOr,
  3905. HLBinaryOpcode::Invalid, // Assign,
  3906. // The assign part is done by matrix store
  3907. HLBinaryOpcode::Mul, // MulAssign
  3908. HLBinaryOpcode::Div, // DivAssign
  3909. HLBinaryOpcode::Rem, // RemAssign
  3910. HLBinaryOpcode::Add, // AddAssign
  3911. HLBinaryOpcode::Sub, // SubAssign
  3912. HLBinaryOpcode::Shl, // ShlAssign
  3913. HLBinaryOpcode::Shr, // ShrAssign
  3914. HLBinaryOpcode::And, // AndAssign
  3915. HLBinaryOpcode::Xor, // XorAssign
  3916. HLBinaryOpcode::Or, // OrAssign
  3917. HLBinaryOpcode::Invalid, // Comma
  3918. };
  3919. // NOTE: This table must match UnaryOperator::Opcode
  3920. static const HLUnaryOpcode UnaryOperatorKindMap[] = {
  3921. HLUnaryOpcode::PostInc, HLUnaryOpcode::PostDec,
  3922. HLUnaryOpcode::PreInc, HLUnaryOpcode::PreDec,
  3923. HLUnaryOpcode::Invalid, // AddrOf,
  3924. HLUnaryOpcode::Invalid, // Deref,
  3925. HLUnaryOpcode::Plus, HLUnaryOpcode::Minus,
  3926. HLUnaryOpcode::Not, HLUnaryOpcode::LNot,
  3927. HLUnaryOpcode::Invalid, // Real,
  3928. HLUnaryOpcode::Invalid, // Imag,
  3929. HLUnaryOpcode::Invalid, // Extension
  3930. };
  3931. static bool IsRowMajorMatrix(QualType Ty, bool bDefaultRowMajor) {
  3932. if (const AttributedType *AT = Ty->getAs<AttributedType>()) {
  3933. if (AT->getAttrKind() == AttributedType::attr_hlsl_row_major)
  3934. return true;
  3935. else if (AT->getAttrKind() == AttributedType::attr_hlsl_column_major)
  3936. return false;
  3937. else
  3938. return bDefaultRowMajor;
  3939. } else {
  3940. return bDefaultRowMajor;
  3941. }
  3942. }
  3943. static bool IsUnsigned(QualType Ty) {
  3944. Ty = Ty.getCanonicalType().getNonReferenceType();
  3945. if (hlsl::IsHLSLVecMatType(Ty))
  3946. Ty = CGHLSLRuntime::GetHLSLVecMatElementType(Ty);
  3947. if (Ty->isExtVectorType())
  3948. Ty = Ty->getAs<clang::ExtVectorType>()->getElementType();
  3949. return Ty->isUnsignedIntegerType();
  3950. }
  3951. static unsigned GetHLOpcode(const Expr *E) {
  3952. switch (E->getStmtClass()) {
  3953. case Stmt::CompoundAssignOperatorClass:
  3954. case Stmt::BinaryOperatorClass: {
  3955. const clang::BinaryOperator *binOp = cast<clang::BinaryOperator>(E);
  3956. HLBinaryOpcode binOpcode = BinaryOperatorKindMap[binOp->getOpcode()];
  3957. if (HasUnsignedOpcode(binOpcode)) {
  3958. if (IsUnsigned(binOp->getLHS()->getType())) {
  3959. binOpcode = GetUnsignedOpcode(binOpcode);
  3960. }
  3961. }
  3962. return static_cast<unsigned>(binOpcode);
  3963. }
  3964. case Stmt::UnaryOperatorClass: {
  3965. const UnaryOperator *unOp = cast<clang::UnaryOperator>(E);
  3966. HLUnaryOpcode unOpcode = UnaryOperatorKindMap[unOp->getOpcode()];
  3967. return static_cast<unsigned>(unOpcode);
  3968. }
  3969. case Stmt::ImplicitCastExprClass:
  3970. case Stmt::CStyleCastExprClass: {
  3971. const CastExpr *CE = cast<CastExpr>(E);
  3972. bool toUnsigned = IsUnsigned(E->getType());
  3973. bool fromUnsigned = IsUnsigned(CE->getSubExpr()->getType());
  3974. if (toUnsigned && fromUnsigned)
  3975. return static_cast<unsigned>(HLCastOpcode::UnsignedUnsignedCast);
  3976. else if (toUnsigned)
  3977. return static_cast<unsigned>(HLCastOpcode::ToUnsignedCast);
  3978. else if (fromUnsigned)
  3979. return static_cast<unsigned>(HLCastOpcode::FromUnsignedCast);
  3980. else
  3981. return static_cast<unsigned>(HLCastOpcode::DefaultCast);
  3982. }
  3983. default:
  3984. return 0;
  3985. }
  3986. }
  3987. static Value *
  3988. EmitHLSLMatrixOperationCallImp(CGBuilderTy &Builder, HLOpcodeGroup group,
  3989. unsigned opcode, llvm::Type *RetType,
  3990. ArrayRef<Value *> paramList, llvm::Module &M) {
  3991. SmallVector<llvm::Type *, 4> paramTyList;
  3992. // Add the opcode param
  3993. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  3994. paramTyList.emplace_back(opcodeTy);
  3995. for (Value *param : paramList) {
  3996. paramTyList.emplace_back(param->getType());
  3997. }
  3998. llvm::FunctionType *funcTy =
  3999. llvm::FunctionType::get(RetType, paramTyList, false);
  4000. Function *opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  4001. SmallVector<Value *, 4> opcodeParamList;
  4002. Value *opcodeConst = Constant::getIntegerValue(opcodeTy, APInt(32, opcode));
  4003. opcodeParamList.emplace_back(opcodeConst);
  4004. opcodeParamList.append(paramList.begin(), paramList.end());
  4005. return Builder.CreateCall(opFunc, opcodeParamList);
  4006. }
  4007. static Value *EmitHLSLArrayInit(CGBuilderTy &Builder, HLOpcodeGroup group,
  4008. unsigned opcode, llvm::Type *RetType,
  4009. ArrayRef<Value *> paramList, llvm::Module &M) {
  4010. // It's a matrix init.
  4011. if (!RetType->isVoidTy())
  4012. return EmitHLSLMatrixOperationCallImp(Builder, group, opcode, RetType,
  4013. paramList, M);
  4014. Value *arrayPtr = paramList[0];
  4015. llvm::ArrayType *AT =
  4016. cast<llvm::ArrayType>(arrayPtr->getType()->getPointerElementType());
  4017. // Avoid the arrayPtr.
  4018. unsigned paramSize = paramList.size() - 1;
  4019. // Support simple case here.
  4020. if (paramSize == AT->getArrayNumElements()) {
  4021. bool typeMatch = true;
  4022. llvm::Type *EltTy = AT->getArrayElementType();
  4023. if (EltTy->isAggregateType()) {
  4024. // Aggregate Type use pointer in initList.
  4025. EltTy = llvm::PointerType::get(EltTy, 0);
  4026. }
  4027. for (unsigned i = 1; i < paramList.size(); i++) {
  4028. if (paramList[i]->getType() != EltTy) {
  4029. typeMatch = false;
  4030. break;
  4031. }
  4032. }
  4033. // Both size and type match.
  4034. if (typeMatch) {
  4035. bool isPtr = EltTy->isPointerTy();
  4036. llvm::Type *i32Ty = llvm::Type::getInt32Ty(EltTy->getContext());
  4037. Constant *zero = ConstantInt::get(i32Ty, 0);
  4038. for (unsigned i = 1; i < paramList.size(); i++) {
  4039. Constant *idx = ConstantInt::get(i32Ty, i - 1);
  4040. Value *GEP = Builder.CreateInBoundsGEP(arrayPtr, {zero, idx});
  4041. Value *Elt = paramList[i];
  4042. if (isPtr) {
  4043. Elt = Builder.CreateLoad(Elt);
  4044. }
  4045. Builder.CreateStore(Elt, GEP);
  4046. }
  4047. // The return value will not be used.
  4048. return nullptr;
  4049. }
  4050. }
  4051. // Other case will be lowered in later pass.
  4052. return EmitHLSLMatrixOperationCallImp(Builder, group, opcode, RetType,
  4053. paramList, M);
  4054. }
  4055. void CGMSHLSLRuntime::FlattenValToInitList(CodeGenFunction &CGF, SmallVector<Value *, 4> &elts,
  4056. SmallVector<QualType, 4> &eltTys,
  4057. QualType Ty, Value *val) {
  4058. CGBuilderTy &Builder = CGF.Builder;
  4059. llvm::Type *valTy = val->getType();
  4060. if (valTy->isPointerTy()) {
  4061. llvm::Type *valEltTy = valTy->getPointerElementType();
  4062. if (valEltTy->isVectorTy() ||
  4063. valEltTy->isSingleValueType()) {
  4064. Value *ldVal = Builder.CreateLoad(val);
  4065. FlattenValToInitList(CGF, elts, eltTys, Ty, ldVal);
  4066. } else if (HLMatrixLower::IsMatrixType(valEltTy)) {
  4067. Value *ldVal = EmitHLSLMatrixLoad(Builder, val, Ty);
  4068. FlattenValToInitList(CGF, elts, eltTys, Ty, ldVal);
  4069. } else {
  4070. llvm::Type *i32Ty = llvm::Type::getInt32Ty(valTy->getContext());
  4071. Value *zero = ConstantInt::get(i32Ty, 0);
  4072. if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(valEltTy)) {
  4073. QualType EltTy = Ty->getAsArrayTypeUnsafe()->getElementType();
  4074. for (unsigned i = 0; i < AT->getArrayNumElements(); i++) {
  4075. Value *gepIdx = ConstantInt::get(i32Ty, i);
  4076. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  4077. FlattenValToInitList(CGF, elts, eltTys, EltTy,EltPtr);
  4078. }
  4079. } else {
  4080. // Struct.
  4081. StructType *ST = cast<StructType>(valEltTy);
  4082. if (HLModule::IsHLSLObjectType(ST)) {
  4083. // Save object directly like basic type.
  4084. elts.emplace_back(Builder.CreateLoad(val));
  4085. eltTys.emplace_back(Ty);
  4086. } else {
  4087. RecordDecl *RD = Ty->getAsStructureType()->getDecl();
  4088. const CGRecordLayout& RL = CGF.getTypes().getCGRecordLayout(RD);
  4089. // Take care base.
  4090. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4091. if (CXXRD->getNumBases()) {
  4092. for (const auto &I : CXXRD->bases()) {
  4093. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  4094. I.getType()->castAs<RecordType>()->getDecl());
  4095. if (BaseDecl->field_empty())
  4096. continue;
  4097. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4098. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  4099. Value *gepIdx = ConstantInt::get(i32Ty, i);
  4100. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  4101. FlattenValToInitList(CGF, elts, eltTys, parentTy, EltPtr);
  4102. }
  4103. }
  4104. }
  4105. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  4106. fieldIter != fieldEnd; ++fieldIter) {
  4107. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  4108. Value *gepIdx = ConstantInt::get(i32Ty, i);
  4109. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  4110. FlattenValToInitList(CGF, elts, eltTys, fieldIter->getType(), EltPtr);
  4111. }
  4112. }
  4113. }
  4114. }
  4115. } else {
  4116. if (HLMatrixLower::IsMatrixType(valTy)) {
  4117. unsigned col, row;
  4118. llvm::Type *EltTy = HLMatrixLower::GetMatrixInfo(valTy, col, row);
  4119. // All matrix Value should be row major.
  4120. // Init list is row major in scalar.
  4121. // So the order is match here, just cast to vector.
  4122. unsigned matSize = col * row;
  4123. bool isRowMajor = IsRowMajorMatrix(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4124. HLCastOpcode opcode = isRowMajor ? HLCastOpcode::RowMatrixToVecCast
  4125. : HLCastOpcode::ColMatrixToVecCast;
  4126. // Cast to vector.
  4127. val = EmitHLSLMatrixOperationCallImp(
  4128. Builder, HLOpcodeGroup::HLCast,
  4129. static_cast<unsigned>(opcode),
  4130. llvm::VectorType::get(EltTy, matSize), {val}, TheModule);
  4131. valTy = val->getType();
  4132. }
  4133. if (valTy->isVectorTy()) {
  4134. QualType EltTy = GetHLSLVecMatElementType(Ty);
  4135. unsigned vecSize = valTy->getVectorNumElements();
  4136. for (unsigned i = 0; i < vecSize; i++) {
  4137. Value *Elt = Builder.CreateExtractElement(val, i);
  4138. elts.emplace_back(Elt);
  4139. eltTys.emplace_back(EltTy);
  4140. }
  4141. } else {
  4142. DXASSERT(valTy->isSingleValueType(), "must be single value type here");
  4143. elts.emplace_back(val);
  4144. eltTys.emplace_back(Ty);
  4145. }
  4146. }
  4147. }
  4148. // Cast elements in initlist if not match the target type.
  4149. // idx is current element index in initlist, Ty is target type.
  4150. static void AddMissingCastOpsInInitList(SmallVector<Value *, 4> &elts, SmallVector<QualType, 4> &eltTys, unsigned &idx, QualType Ty, CodeGenFunction &CGF) {
  4151. if (Ty->isArrayType()) {
  4152. const clang::ArrayType *AT = Ty->getAsArrayTypeUnsafe();
  4153. // Must be ConstantArrayType here.
  4154. unsigned arraySize = cast<ConstantArrayType>(AT)->getSize().getLimitedValue();
  4155. QualType EltTy = AT->getElementType();
  4156. for (unsigned i = 0; i < arraySize; i++)
  4157. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  4158. } else if (IsHLSLVecType(Ty)) {
  4159. QualType EltTy = GetHLSLVecElementType(Ty);
  4160. unsigned vecSize = GetHLSLVecSize(Ty);
  4161. for (unsigned i=0;i< vecSize;i++)
  4162. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  4163. } else if (IsHLSLMatType(Ty)) {
  4164. QualType EltTy = GetHLSLMatElementType(Ty);
  4165. unsigned row, col;
  4166. GetHLSLMatRowColCount(Ty, row, col);
  4167. unsigned matSize = row*col;
  4168. for (unsigned i = 0; i < matSize; i++)
  4169. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  4170. } else if (Ty->isRecordType()) {
  4171. if (HLModule::IsHLSLObjectType(CGF.ConvertType(Ty))) {
  4172. // Skip hlsl object.
  4173. idx++;
  4174. } else {
  4175. const RecordType *RT = Ty->getAsStructureType();
  4176. // For CXXRecord.
  4177. if (!RT)
  4178. RT = Ty->getAs<RecordType>();
  4179. RecordDecl *RD = RT->getDecl();
  4180. // Take care base.
  4181. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4182. if (CXXRD->getNumBases()) {
  4183. for (const auto &I : CXXRD->bases()) {
  4184. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  4185. I.getType()->castAs<RecordType>()->getDecl());
  4186. if (BaseDecl->field_empty())
  4187. continue;
  4188. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4189. AddMissingCastOpsInInitList(elts, eltTys, idx, parentTy, CGF);
  4190. }
  4191. }
  4192. }
  4193. for (FieldDecl *field : RD->fields())
  4194. AddMissingCastOpsInInitList(elts, eltTys, idx, field->getType(), CGF);
  4195. }
  4196. }
  4197. else {
  4198. // Basic type.
  4199. Value *val = elts[idx];
  4200. llvm::Type *srcTy = val->getType();
  4201. llvm::Type *dstTy = CGF.ConvertType(Ty);
  4202. if (srcTy != dstTy) {
  4203. Instruction::CastOps castOp =
  4204. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  4205. IsUnsigned(eltTys[idx]), IsUnsigned(Ty), srcTy, dstTy));
  4206. elts[idx] = CGF.Builder.CreateCast(castOp, val, dstTy);
  4207. }
  4208. idx++;
  4209. }
  4210. }
  4211. static void StoreInitListToDestPtr(Value *DestPtr,
  4212. SmallVector<Value *, 4> &elts, unsigned &idx,
  4213. QualType Type, CodeGenTypes &Types, bool bDefaultRowMajor,
  4214. CGBuilderTy &Builder, llvm::Module &M) {
  4215. llvm::Type *Ty = DestPtr->getType()->getPointerElementType();
  4216. llvm::Type *i32Ty = llvm::Type::getInt32Ty(Ty->getContext());
  4217. if (Ty->isVectorTy()) {
  4218. Value *Result = UndefValue::get(Ty);
  4219. for (unsigned i = 0; i < Ty->getVectorNumElements(); i++)
  4220. Result = Builder.CreateInsertElement(Result, elts[idx + i], i);
  4221. Builder.CreateStore(Result, DestPtr);
  4222. idx += Ty->getVectorNumElements();
  4223. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  4224. bool isRowMajor =
  4225. IsRowMajorMatrix(Type, bDefaultRowMajor);
  4226. unsigned row, col;
  4227. HLMatrixLower::GetMatrixInfo(Ty, col, row);
  4228. std::vector<Value *> matInitList(col * row);
  4229. for (unsigned i = 0; i < col; i++) {
  4230. for (unsigned r = 0; r < row; r++) {
  4231. unsigned matIdx = i * row + r;
  4232. matInitList[matIdx] = elts[idx + matIdx];
  4233. }
  4234. }
  4235. idx += row * col;
  4236. Value *matVal =
  4237. EmitHLSLMatrixOperationCallImp(Builder, HLOpcodeGroup::HLInit,
  4238. /*opcode*/ 0, Ty, matInitList, M);
  4239. // matVal return from HLInit is row major.
  4240. // If DestPtr is row major, just store it directly.
  4241. if (!isRowMajor) {
  4242. // ColMatStore need a col major value.
  4243. // Cast row major matrix into col major.
  4244. // Then store it.
  4245. Value *colMatVal = EmitHLSLMatrixOperationCallImp(
  4246. Builder, HLOpcodeGroup::HLCast,
  4247. static_cast<unsigned>(HLCastOpcode::RowMatrixToColMatrix), Ty,
  4248. {matVal}, M);
  4249. EmitHLSLMatrixOperationCallImp(
  4250. Builder, HLOpcodeGroup::HLMatLoadStore,
  4251. static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatStore), Ty,
  4252. {DestPtr, colMatVal}, M);
  4253. } else {
  4254. EmitHLSLMatrixOperationCallImp(
  4255. Builder, HLOpcodeGroup::HLMatLoadStore,
  4256. static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatStore), Ty,
  4257. {DestPtr, matVal}, M);
  4258. }
  4259. } else if (Ty->isStructTy()) {
  4260. if (HLModule::IsHLSLObjectType(Ty)) {
  4261. Builder.CreateStore(elts[idx], DestPtr);
  4262. idx++;
  4263. } else {
  4264. Constant *zero = ConstantInt::get(i32Ty, 0);
  4265. const RecordType *RT = Type->getAsStructureType();
  4266. // For CXXRecord.
  4267. if (!RT)
  4268. RT = Type->getAs<RecordType>();
  4269. RecordDecl *RD = RT->getDecl();
  4270. const CGRecordLayout &RL = Types.getCGRecordLayout(RD);
  4271. // Take care base.
  4272. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4273. if (CXXRD->getNumBases()) {
  4274. for (const auto &I : CXXRD->bases()) {
  4275. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  4276. I.getType()->castAs<RecordType>()->getDecl());
  4277. if (BaseDecl->field_empty())
  4278. continue;
  4279. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4280. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  4281. Constant *gepIdx = ConstantInt::get(i32Ty, i);
  4282. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  4283. StoreInitListToDestPtr(GEP, elts, idx, parentTy, Types,
  4284. bDefaultRowMajor, Builder, M);
  4285. }
  4286. }
  4287. }
  4288. for (FieldDecl *field : RD->fields()) {
  4289. unsigned i = RL.getLLVMFieldNo(field);
  4290. Constant *gepIdx = ConstantInt::get(i32Ty, i);
  4291. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  4292. StoreInitListToDestPtr(GEP, elts, idx, field->getType(), Types,
  4293. bDefaultRowMajor, Builder, M);
  4294. }
  4295. }
  4296. } else if (Ty->isArrayTy()) {
  4297. Constant *zero = ConstantInt::get(i32Ty, 0);
  4298. QualType EltType = Type->getAsArrayTypeUnsafe()->getElementType();
  4299. for (unsigned i = 0; i < Ty->getArrayNumElements(); i++) {
  4300. Constant *gepIdx = ConstantInt::get(i32Ty, i);
  4301. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  4302. StoreInitListToDestPtr(GEP, elts, idx, EltType, Types, bDefaultRowMajor,
  4303. Builder, M);
  4304. }
  4305. } else {
  4306. DXASSERT(Ty->isSingleValueType(), "invalid type");
  4307. llvm::Type *i1Ty = Builder.getInt1Ty();
  4308. Value *V = elts[idx];
  4309. if (V->getType() == i1Ty &&
  4310. DestPtr->getType()->getPointerElementType() != i1Ty) {
  4311. V = Builder.CreateZExt(V, DestPtr->getType()->getPointerElementType());
  4312. }
  4313. Builder.CreateStore(V, DestPtr);
  4314. idx++;
  4315. }
  4316. }
  4317. void CGMSHLSLRuntime::ScanInitList(CodeGenFunction &CGF, InitListExpr *E,
  4318. SmallVector<Value *, 4> &EltValList,
  4319. SmallVector<QualType, 4> &EltTyList) {
  4320. unsigned NumInitElements = E->getNumInits();
  4321. for (unsigned i = 0; i != NumInitElements; ++i) {
  4322. Expr *init = E->getInit(i);
  4323. QualType iType = init->getType();
  4324. if (InitListExpr *initList = dyn_cast<InitListExpr>(init)) {
  4325. ScanInitList(CGF, initList, EltValList, EltTyList);
  4326. } else if (CodeGenFunction::hasScalarEvaluationKind(iType)) {
  4327. llvm::Value *initVal = CGF.EmitScalarExpr(init);
  4328. FlattenValToInitList(CGF, EltValList, EltTyList, iType, initVal);
  4329. } else {
  4330. AggValueSlot Slot =
  4331. CGF.CreateAggTemp(init->getType(), "Agg.InitList.tmp");
  4332. CGF.EmitAggExpr(init, Slot);
  4333. llvm::Value *aggPtr = Slot.getAddr();
  4334. FlattenValToInitList(CGF, EltValList, EltTyList, iType, aggPtr);
  4335. }
  4336. }
  4337. }
  4338. // Is Type of E match Ty.
  4339. static bool ExpTypeMatch(Expr *E, QualType Ty, ASTContext &Ctx, CodeGenTypes &Types) {
  4340. if (InitListExpr *initList = dyn_cast<InitListExpr>(E)) {
  4341. unsigned NumInitElements = initList->getNumInits();
  4342. // Skip vector and matrix type.
  4343. if (Ty->isVectorType())
  4344. return false;
  4345. if (hlsl::IsHLSLVecMatType(Ty))
  4346. return false;
  4347. if (Ty->isStructureOrClassType()) {
  4348. RecordDecl *record = Ty->castAs<RecordType>()->getDecl();
  4349. bool bMatch = true;
  4350. auto It = record->field_begin();
  4351. auto ItEnd = record->field_end();
  4352. unsigned i = 0;
  4353. for (auto it = record->field_begin(), end = record->field_end();
  4354. it != end; it++) {
  4355. if (i == NumInitElements) {
  4356. bMatch = false;
  4357. break;
  4358. }
  4359. Expr *init = initList->getInit(i++);
  4360. QualType EltTy = it->getType();
  4361. bMatch &= ExpTypeMatch(init, EltTy, Ctx, Types);
  4362. if (!bMatch)
  4363. break;
  4364. }
  4365. bMatch &= i == NumInitElements;
  4366. if (bMatch && initList->getType()->isVoidType()) {
  4367. initList->setType(Ty);
  4368. }
  4369. return bMatch;
  4370. } else if (Ty->isArrayType() && !Ty->isIncompleteArrayType()) {
  4371. const ConstantArrayType *AT = Ctx.getAsConstantArrayType(Ty);
  4372. QualType EltTy = AT->getElementType();
  4373. unsigned size = AT->getSize().getZExtValue();
  4374. if (size != NumInitElements)
  4375. return false;
  4376. bool bMatch = true;
  4377. for (unsigned i = 0; i != NumInitElements; ++i) {
  4378. Expr *init = initList->getInit(i);
  4379. bMatch &= ExpTypeMatch(init, EltTy, Ctx, Types);
  4380. if (!bMatch)
  4381. break;
  4382. }
  4383. if (bMatch && initList->getType()->isVoidType()) {
  4384. initList->setType(Ty);
  4385. }
  4386. return bMatch;
  4387. } else {
  4388. return false;
  4389. }
  4390. } else {
  4391. llvm::Type *ExpTy = Types.ConvertType(E->getType());
  4392. llvm::Type *TargetTy = Types.ConvertType(Ty);
  4393. return ExpTy == TargetTy;
  4394. }
  4395. }
  4396. bool CGMSHLSLRuntime::IsTrivalInitListExpr(CodeGenFunction &CGF,
  4397. InitListExpr *E) {
  4398. QualType Ty = E->getType();
  4399. bool result = ExpTypeMatch(E, Ty, CGF.getContext(), CGF.getTypes());
  4400. if (result) {
  4401. auto iter = staticConstGlobalInitMap.find(E);
  4402. if (iter != staticConstGlobalInitMap.end()) {
  4403. GlobalVariable * GV = iter->second;
  4404. auto &InitConstants = staticConstGlobalInitListMap[GV];
  4405. // Add Constant to InitList.
  4406. for (unsigned i=0;i<E->getNumInits();i++) {
  4407. Expr *Expr = E->getInit(i);
  4408. LValue LV = CGF.EmitLValue(Expr);
  4409. if (LV.isSimple()) {
  4410. Constant *SrcPtr = dyn_cast<Constant>(LV.getAddress());
  4411. if (SrcPtr && !isa<UndefValue>(SrcPtr)) {
  4412. InitConstants.emplace_back(SrcPtr);
  4413. continue;
  4414. }
  4415. }
  4416. // Only support simple LV and Constant Ptr case.
  4417. // Other case just go normal path.
  4418. InitConstants.clear();
  4419. break;
  4420. }
  4421. if (InitConstants.empty())
  4422. staticConstGlobalInitListMap.erase(GV);
  4423. else
  4424. staticConstGlobalCtorMap[GV] = CGF.CurFn;
  4425. }
  4426. }
  4427. return result;
  4428. }
  4429. Value *CGMSHLSLRuntime::EmitHLSLInitListExpr(CodeGenFunction &CGF, InitListExpr *E,
  4430. // The destPtr when emiting aggregate init, for normal case, it will be null.
  4431. Value *DestPtr) {
  4432. if (DestPtr && E->getNumInits() == 1) {
  4433. llvm::Type *ExpTy = CGF.ConvertType(E->getType());
  4434. llvm::Type *TargetTy = CGF.ConvertType(E->getInit(0)->getType());
  4435. if (ExpTy == TargetTy) {
  4436. Expr *Expr = E->getInit(0);
  4437. LValue LV = CGF.EmitLValue(Expr);
  4438. if (LV.isSimple()) {
  4439. Value *SrcPtr = LV.getAddress();
  4440. SmallVector<Value *, 4> idxList;
  4441. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, Expr->getType(),
  4442. E->getType(), SrcPtr->getType());
  4443. return nullptr;
  4444. }
  4445. }
  4446. }
  4447. SmallVector<Value *, 4> EltValList;
  4448. SmallVector<QualType, 4> EltTyList;
  4449. ScanInitList(CGF, E, EltValList, EltTyList);
  4450. QualType ResultTy = E->getType();
  4451. unsigned idx = 0;
  4452. // Create cast if need.
  4453. AddMissingCastOpsInInitList(EltValList, EltTyList, idx, ResultTy, CGF);
  4454. DXASSERT(idx == EltValList.size(), "size must match");
  4455. llvm::Type *RetTy = CGF.ConvertType(ResultTy);
  4456. if (DestPtr) {
  4457. SmallVector<Value *, 4> ParamList;
  4458. DXASSERT(RetTy->isAggregateType(), "");
  4459. ParamList.emplace_back(DestPtr);
  4460. ParamList.append(EltValList.begin(), EltValList.end());
  4461. idx = 0;
  4462. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  4463. StoreInitListToDestPtr(DestPtr, EltValList, idx, ResultTy, CGF.getTypes(),
  4464. bDefaultRowMajor, CGF.Builder, TheModule);
  4465. return nullptr;
  4466. }
  4467. if (IsHLSLVecType(ResultTy)) {
  4468. Value *Result = UndefValue::get(RetTy);
  4469. for (unsigned i = 0; i < RetTy->getVectorNumElements(); i++)
  4470. Result = CGF.Builder.CreateInsertElement(Result, EltValList[i], i);
  4471. return Result;
  4472. } else {
  4473. // Must be matrix here.
  4474. DXASSERT(IsHLSLMatType(ResultTy), "must be matrix type here.");
  4475. return EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLInit,
  4476. /*opcode*/ 0, RetTy, EltValList,
  4477. TheModule);
  4478. }
  4479. }
  4480. static void FlatConstToList(Constant *C, SmallVector<Constant *, 4> &EltValList,
  4481. QualType Type, CodeGenTypes &Types,
  4482. bool bDefaultRowMajor) {
  4483. llvm::Type *Ty = C->getType();
  4484. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  4485. // Type is only for matrix. Keep use Type to next level.
  4486. for (unsigned i = 0; i < VT->getNumElements(); i++) {
  4487. FlatConstToList(C->getAggregateElement(i), EltValList, Type, Types,
  4488. bDefaultRowMajor);
  4489. }
  4490. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  4491. bool isRowMajor = IsRowMajorMatrix(Type, bDefaultRowMajor);
  4492. // matrix type is struct { vector<Ty, row> [col] };
  4493. // Strip the struct level here.
  4494. Constant *matVal = C->getAggregateElement((unsigned)0);
  4495. const RecordType *RT = Type->getAs<RecordType>();
  4496. RecordDecl *RD = RT->getDecl();
  4497. QualType EltTy = RD->field_begin()->getType();
  4498. // When scan, init list scalars is row major.
  4499. if (isRowMajor) {
  4500. // Don't change the major for row major value.
  4501. FlatConstToList(matVal, EltValList, EltTy, Types, bDefaultRowMajor);
  4502. } else {
  4503. // Save to tmp list.
  4504. SmallVector<Constant *, 4> matEltList;
  4505. FlatConstToList(matVal, matEltList, EltTy, Types, bDefaultRowMajor);
  4506. unsigned row, col;
  4507. HLMatrixLower::GetMatrixInfo(Ty, col, row);
  4508. // Change col major value to row major.
  4509. for (unsigned r = 0; r < row; r++)
  4510. for (unsigned c = 0; c < col; c++) {
  4511. unsigned colMajorIdx = c * row + r;
  4512. EltValList.emplace_back(matEltList[colMajorIdx]);
  4513. }
  4514. }
  4515. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  4516. QualType EltTy = Type->getAsArrayTypeUnsafe()->getElementType();
  4517. for (unsigned i = 0; i < AT->getNumElements(); i++) {
  4518. FlatConstToList(C->getAggregateElement(i), EltValList, EltTy, Types,
  4519. bDefaultRowMajor);
  4520. }
  4521. } else if (llvm::StructType *ST = dyn_cast<llvm::StructType>(Ty)) {
  4522. RecordDecl *RD = Type->getAsStructureType()->getDecl();
  4523. const CGRecordLayout &RL = Types.getCGRecordLayout(RD);
  4524. // Take care base.
  4525. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4526. if (CXXRD->getNumBases()) {
  4527. for (const auto &I : CXXRD->bases()) {
  4528. const CXXRecordDecl *BaseDecl =
  4529. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  4530. if (BaseDecl->field_empty())
  4531. continue;
  4532. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4533. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  4534. FlatConstToList(C->getAggregateElement(i), EltValList, parentTy,
  4535. Types, bDefaultRowMajor);
  4536. }
  4537. }
  4538. }
  4539. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  4540. fieldIter != fieldEnd; ++fieldIter) {
  4541. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  4542. FlatConstToList(C->getAggregateElement(i), EltValList,
  4543. fieldIter->getType(), Types, bDefaultRowMajor);
  4544. }
  4545. } else {
  4546. EltValList.emplace_back(C);
  4547. }
  4548. }
  4549. static bool ScanConstInitList(CodeGenModule &CGM, InitListExpr *E,
  4550. SmallVector<Constant *, 4> &EltValList,
  4551. CodeGenTypes &Types, bool bDefaultRowMajor) {
  4552. unsigned NumInitElements = E->getNumInits();
  4553. for (unsigned i = 0; i != NumInitElements; ++i) {
  4554. Expr *init = E->getInit(i);
  4555. QualType iType = init->getType();
  4556. if (InitListExpr *initList = dyn_cast<InitListExpr>(init)) {
  4557. if (!ScanConstInitList(CGM, initList, EltValList, Types,
  4558. bDefaultRowMajor))
  4559. return false;
  4560. } else if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(init)) {
  4561. if (VarDecl *D = dyn_cast<VarDecl>(ref->getDecl())) {
  4562. if (!D->hasInit())
  4563. return false;
  4564. if (Constant *initVal = CGM.EmitConstantInit(*D)) {
  4565. FlatConstToList(initVal, EltValList, iType, Types, bDefaultRowMajor);
  4566. } else {
  4567. return false;
  4568. }
  4569. } else {
  4570. return false;
  4571. }
  4572. } else if (hlsl::IsHLSLMatType(iType)) {
  4573. return false;
  4574. } else if (CodeGenFunction::hasScalarEvaluationKind(iType)) {
  4575. if (Constant *initVal = CGM.EmitConstantExpr(init, iType)) {
  4576. FlatConstToList(initVal, EltValList, iType, Types, bDefaultRowMajor);
  4577. } else {
  4578. return false;
  4579. }
  4580. } else {
  4581. return false;
  4582. }
  4583. }
  4584. return true;
  4585. }
  4586. static Constant *BuildConstInitializer(QualType Type, unsigned &offset,
  4587. SmallVector<Constant *, 4> &EltValList,
  4588. CodeGenTypes &Types,
  4589. bool bDefaultRowMajor);
  4590. static Constant *BuildConstVector(llvm::VectorType *VT, unsigned &offset,
  4591. SmallVector<Constant *, 4> &EltValList,
  4592. QualType Type, CodeGenTypes &Types) {
  4593. SmallVector<Constant *, 4> Elts;
  4594. QualType EltTy = hlsl::GetHLSLVecElementType(Type);
  4595. for (unsigned i = 0; i < VT->getNumElements(); i++) {
  4596. Elts.emplace_back(BuildConstInitializer(EltTy, offset, EltValList, Types,
  4597. // Vector don't need major.
  4598. /*bDefaultRowMajor*/ false));
  4599. }
  4600. return llvm::ConstantVector::get(Elts);
  4601. }
  4602. static Constant *BuildConstMatrix(llvm::Type *Ty, unsigned &offset,
  4603. SmallVector<Constant *, 4> &EltValList,
  4604. QualType Type, CodeGenTypes &Types,
  4605. bool bDefaultRowMajor) {
  4606. QualType EltTy = hlsl::GetHLSLMatElementType(Type);
  4607. unsigned col, row;
  4608. HLMatrixLower::GetMatrixInfo(Ty, col, row);
  4609. llvm::ArrayType *AT = cast<llvm::ArrayType>(Ty->getStructElementType(0));
  4610. // Save initializer elements first.
  4611. // Matrix initializer is row major.
  4612. SmallVector<Constant *, 16> elts;
  4613. for (unsigned i = 0; i < col * row; i++) {
  4614. elts.emplace_back(BuildConstInitializer(EltTy, offset, EltValList, Types,
  4615. bDefaultRowMajor));
  4616. }
  4617. bool isRowMajor = IsRowMajorMatrix(Type, bDefaultRowMajor);
  4618. SmallVector<Constant *, 16> majorElts(elts.begin(), elts.end());
  4619. if (!isRowMajor) {
  4620. // cast row major to col major.
  4621. for (unsigned c = 0; c < col; c++) {
  4622. SmallVector<Constant *, 4> rows;
  4623. for (unsigned r = 0; r < row; r++) {
  4624. unsigned rowMajorIdx = r * col + c;
  4625. unsigned colMajorIdx = c * row + r;
  4626. majorElts[colMajorIdx] = elts[rowMajorIdx];
  4627. }
  4628. }
  4629. }
  4630. // The type is vector<element, col>[row].
  4631. SmallVector<Constant *, 4> rows;
  4632. unsigned idx = 0;
  4633. for (unsigned r = 0; r < row; r++) {
  4634. SmallVector<Constant *, 4> cols;
  4635. for (unsigned c = 0; c < col; c++) {
  4636. cols.emplace_back(majorElts[idx++]);
  4637. }
  4638. rows.emplace_back(llvm::ConstantVector::get(cols));
  4639. }
  4640. Constant *mat = llvm::ConstantArray::get(AT, rows);
  4641. return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), mat);
  4642. }
  4643. static Constant *BuildConstArray(llvm::ArrayType *AT, unsigned &offset,
  4644. SmallVector<Constant *, 4> &EltValList,
  4645. QualType Type, CodeGenTypes &Types,
  4646. bool bDefaultRowMajor) {
  4647. SmallVector<Constant *, 4> Elts;
  4648. QualType EltType = QualType(Type->getArrayElementTypeNoTypeQual(), 0);
  4649. for (unsigned i = 0; i < AT->getNumElements(); i++) {
  4650. Elts.emplace_back(BuildConstInitializer(EltType, offset, EltValList, Types,
  4651. bDefaultRowMajor));
  4652. }
  4653. return llvm::ConstantArray::get(AT, Elts);
  4654. }
  4655. static Constant *BuildConstStruct(llvm::StructType *ST, unsigned &offset,
  4656. SmallVector<Constant *, 4> &EltValList,
  4657. QualType Type, CodeGenTypes &Types,
  4658. bool bDefaultRowMajor) {
  4659. SmallVector<Constant *, 4> Elts;
  4660. const RecordType *RT = Type->getAsStructureType();
  4661. if (!RT)
  4662. RT = Type->getAs<RecordType>();
  4663. const RecordDecl *RD = RT->getDecl();
  4664. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4665. if (CXXRD->getNumBases()) {
  4666. // Add base as field.
  4667. for (const auto &I : CXXRD->bases()) {
  4668. const CXXRecordDecl *BaseDecl =
  4669. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  4670. // Skip empty struct.
  4671. if (BaseDecl->field_empty())
  4672. continue;
  4673. // Add base as a whole constant. Not as element.
  4674. Elts.emplace_back(BuildConstInitializer(I.getType(), offset, EltValList,
  4675. Types, bDefaultRowMajor));
  4676. }
  4677. }
  4678. }
  4679. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  4680. fieldIter != fieldEnd; ++fieldIter) {
  4681. Elts.emplace_back(BuildConstInitializer(
  4682. fieldIter->getType(), offset, EltValList, Types, bDefaultRowMajor));
  4683. }
  4684. return llvm::ConstantStruct::get(ST, Elts);
  4685. }
  4686. static Constant *BuildConstInitializer(QualType Type, unsigned &offset,
  4687. SmallVector<Constant *, 4> &EltValList,
  4688. CodeGenTypes &Types,
  4689. bool bDefaultRowMajor) {
  4690. llvm::Type *Ty = Types.ConvertType(Type);
  4691. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  4692. return BuildConstVector(VT, offset, EltValList, Type, Types);
  4693. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  4694. return BuildConstArray(AT, offset, EltValList, Type, Types,
  4695. bDefaultRowMajor);
  4696. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  4697. return BuildConstMatrix(Ty, offset, EltValList, Type, Types,
  4698. bDefaultRowMajor);
  4699. } else if (StructType *ST = dyn_cast<llvm::StructType>(Ty)) {
  4700. return BuildConstStruct(ST, offset, EltValList, Type, Types,
  4701. bDefaultRowMajor);
  4702. } else {
  4703. // Scalar basic types.
  4704. Constant *Val = EltValList[offset++];
  4705. if (Val->getType() == Ty) {
  4706. return Val;
  4707. } else {
  4708. IRBuilder<> Builder(Ty->getContext());
  4709. // Don't cast int to bool. bool only for scalar.
  4710. if (Ty == Builder.getInt1Ty() && Val->getType() == Builder.getInt32Ty())
  4711. return Val;
  4712. Instruction::CastOps castOp =
  4713. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  4714. IsUnsigned(Type), IsUnsigned(Type), Val->getType(), Ty));
  4715. return cast<Constant>(Builder.CreateCast(castOp, Val, Ty));
  4716. }
  4717. }
  4718. }
  4719. Constant *CGMSHLSLRuntime::EmitHLSLConstInitListExpr(CodeGenModule &CGM,
  4720. InitListExpr *E) {
  4721. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  4722. SmallVector<Constant *, 4> EltValList;
  4723. if (!ScanConstInitList(CGM, E, EltValList, CGM.getTypes(), bDefaultRowMajor))
  4724. return nullptr;
  4725. QualType Type = E->getType();
  4726. unsigned offset = 0;
  4727. return BuildConstInitializer(Type, offset, EltValList, CGM.getTypes(),
  4728. bDefaultRowMajor);
  4729. }
  4730. Value *CGMSHLSLRuntime::EmitHLSLMatrixOperationCall(
  4731. CodeGenFunction &CGF, const clang::Expr *E, llvm::Type *RetType,
  4732. ArrayRef<Value *> paramList) {
  4733. HLOpcodeGroup group = GetHLOpcodeGroup(E->getStmtClass());
  4734. unsigned opcode = GetHLOpcode(E);
  4735. if (group == HLOpcodeGroup::HLInit)
  4736. return EmitHLSLArrayInit(CGF.Builder, group, opcode, RetType, paramList,
  4737. TheModule);
  4738. else
  4739. return EmitHLSLMatrixOperationCallImp(CGF.Builder, group, opcode, RetType,
  4740. paramList, TheModule);
  4741. }
  4742. void CGMSHLSLRuntime::EmitHLSLDiscard(CodeGenFunction &CGF) {
  4743. EmitHLSLMatrixOperationCallImp(
  4744. CGF.Builder, HLOpcodeGroup::HLIntrinsic,
  4745. static_cast<unsigned>(IntrinsicOp::IOP_clip),
  4746. llvm::Type::getVoidTy(CGF.getLLVMContext()),
  4747. {ConstantFP::get(llvm::Type::getFloatTy(CGF.getLLVMContext()), -1.0f)},
  4748. TheModule);
  4749. }
  4750. Value *CGMSHLSLRuntime::EmitHLSLLiteralCast(CodeGenFunction &CGF, Value *Src,
  4751. QualType SrcType,
  4752. QualType DstType) {
  4753. auto &Builder = CGF.Builder;
  4754. llvm::Type *DstTy = CGF.ConvertType(DstType);
  4755. bool bDstSigned = DstType->isSignedIntegerType();
  4756. if (ConstantInt *CI = dyn_cast<ConstantInt>(Src)) {
  4757. APInt v = CI->getValue();
  4758. if (llvm::IntegerType *IT = dyn_cast<llvm::IntegerType>(DstTy)) {
  4759. v = v.trunc(IT->getBitWidth());
  4760. switch (IT->getBitWidth()) {
  4761. case 32:
  4762. return Builder.getInt32(v.getLimitedValue());
  4763. case 64:
  4764. return Builder.getInt64(v.getLimitedValue());
  4765. case 16:
  4766. return Builder.getInt16(v.getLimitedValue());
  4767. case 8:
  4768. return Builder.getInt8(v.getLimitedValue());
  4769. default:
  4770. return nullptr;
  4771. }
  4772. } else {
  4773. DXASSERT_NOMSG(DstTy->isFloatingPointTy());
  4774. int64_t val = v.getLimitedValue();
  4775. if (v.isNegative())
  4776. val = 0-v.abs().getLimitedValue();
  4777. if (DstTy->isDoubleTy())
  4778. return ConstantFP::get(DstTy, (double)val);
  4779. else if (DstTy->isFloatTy())
  4780. return ConstantFP::get(DstTy, (float)val);
  4781. else {
  4782. if (bDstSigned)
  4783. return Builder.CreateSIToFP(Src, DstTy);
  4784. else
  4785. return Builder.CreateUIToFP(Src, DstTy);
  4786. }
  4787. }
  4788. } else if (ConstantFP *CF = dyn_cast<ConstantFP>(Src)) {
  4789. APFloat v = CF->getValueAPF();
  4790. double dv = v.convertToDouble();
  4791. if (llvm::IntegerType *IT = dyn_cast<llvm::IntegerType>(DstTy)) {
  4792. switch (IT->getBitWidth()) {
  4793. case 32:
  4794. return Builder.getInt32(dv);
  4795. case 64:
  4796. return Builder.getInt64(dv);
  4797. case 16:
  4798. return Builder.getInt16(dv);
  4799. case 8:
  4800. return Builder.getInt8(dv);
  4801. default:
  4802. return nullptr;
  4803. }
  4804. } else {
  4805. if (DstTy->isFloatTy()) {
  4806. float fv = dv;
  4807. return ConstantFP::get(DstTy->getContext(), APFloat(fv));
  4808. } else {
  4809. return Builder.CreateFPTrunc(Src, DstTy);
  4810. }
  4811. }
  4812. } else if (UndefValue *UV = dyn_cast<UndefValue>(Src)) {
  4813. return UndefValue::get(DstTy);
  4814. } else {
  4815. Instruction *I = cast<Instruction>(Src);
  4816. if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
  4817. Value *T = SI->getTrueValue();
  4818. Value *F = SI->getFalseValue();
  4819. Value *Cond = SI->getCondition();
  4820. if (isa<llvm::ConstantInt>(T) && isa<llvm::ConstantInt>(F)) {
  4821. llvm::APInt lhs = cast<llvm::ConstantInt>(T)->getValue();
  4822. llvm::APInt rhs = cast<llvm::ConstantInt>(F)->getValue();
  4823. if (DstTy == Builder.getInt32Ty()) {
  4824. T = Builder.getInt32(lhs.getLimitedValue());
  4825. F = Builder.getInt32(rhs.getLimitedValue());
  4826. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4827. return Sel;
  4828. } else if (DstTy->isFloatingPointTy()) {
  4829. T = ConstantFP::get(DstTy, int64_t(lhs.getLimitedValue()));
  4830. F = ConstantFP::get(DstTy, int64_t(rhs.getLimitedValue()));
  4831. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4832. return Sel;
  4833. }
  4834. } else if (isa<llvm::ConstantFP>(T) && isa<llvm::ConstantFP>(F)) {
  4835. llvm::APFloat lhs = cast<llvm::ConstantFP>(T)->getValueAPF();
  4836. llvm::APFloat rhs = cast<llvm::ConstantFP>(F)->getValueAPF();
  4837. double ld = lhs.convertToDouble();
  4838. double rd = rhs.convertToDouble();
  4839. if (DstTy->isFloatTy()) {
  4840. float lf = ld;
  4841. float rf = rd;
  4842. T = ConstantFP::get(DstTy->getContext(), APFloat(lf));
  4843. F = ConstantFP::get(DstTy->getContext(), APFloat(rf));
  4844. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4845. return Sel;
  4846. } else if (DstTy == Builder.getInt32Ty()) {
  4847. T = Builder.getInt32(ld);
  4848. F = Builder.getInt32(rd);
  4849. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4850. return Sel;
  4851. } else if (DstTy == Builder.getInt64Ty()) {
  4852. T = Builder.getInt64(ld);
  4853. F = Builder.getInt64(rd);
  4854. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4855. return Sel;
  4856. }
  4857. }
  4858. }
  4859. // TODO: support other opcode if need.
  4860. return nullptr;
  4861. }
  4862. }
  4863. Value *CGMSHLSLRuntime::EmitHLSLMatrixSubscript(CodeGenFunction &CGF,
  4864. llvm::Type *RetType,
  4865. llvm::Value *Ptr,
  4866. llvm::Value *Idx,
  4867. clang::QualType Ty) {
  4868. bool isRowMajor =
  4869. IsRowMajorMatrix(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4870. unsigned opcode =
  4871. isRowMajor ? static_cast<unsigned>(HLSubscriptOpcode::RowMatSubscript)
  4872. : static_cast<unsigned>(HLSubscriptOpcode::ColMatSubscript);
  4873. Value *matBase = Ptr;
  4874. DXASSERT(matBase->getType()->isPointerTy(),
  4875. "matrix subscript should return pointer");
  4876. RetType =
  4877. llvm::PointerType::get(RetType->getPointerElementType(),
  4878. matBase->getType()->getPointerAddressSpace());
  4879. // Lower mat[Idx] into real idx.
  4880. SmallVector<Value *, 8> args;
  4881. args.emplace_back(Ptr);
  4882. unsigned row, col;
  4883. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  4884. if (isRowMajor) {
  4885. Value *cCol = ConstantInt::get(Idx->getType(), col);
  4886. Value *Base = CGF.Builder.CreateMul(cCol, Idx);
  4887. for (unsigned i = 0; i < col; i++) {
  4888. Value *c = ConstantInt::get(Idx->getType(), i);
  4889. // r * col + c
  4890. Value *matIdx = CGF.Builder.CreateAdd(Base, c);
  4891. args.emplace_back(matIdx);
  4892. }
  4893. } else {
  4894. for (unsigned i = 0; i < col; i++) {
  4895. Value *cMulRow = ConstantInt::get(Idx->getType(), i * row);
  4896. // c * row + r
  4897. Value *matIdx = CGF.Builder.CreateAdd(cMulRow, Idx);
  4898. args.emplace_back(matIdx);
  4899. }
  4900. }
  4901. Value *matSub =
  4902. EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLSubscript,
  4903. opcode, RetType, args, TheModule);
  4904. return matSub;
  4905. }
  4906. Value *CGMSHLSLRuntime::EmitHLSLMatrixElement(CodeGenFunction &CGF,
  4907. llvm::Type *RetType,
  4908. ArrayRef<Value *> paramList,
  4909. QualType Ty) {
  4910. bool isRowMajor =
  4911. IsRowMajorMatrix(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4912. unsigned opcode =
  4913. isRowMajor ? static_cast<unsigned>(HLSubscriptOpcode::RowMatElement)
  4914. : static_cast<unsigned>(HLSubscriptOpcode::ColMatElement);
  4915. Value *matBase = paramList[0];
  4916. DXASSERT(matBase->getType()->isPointerTy(),
  4917. "matrix element should return pointer");
  4918. RetType =
  4919. llvm::PointerType::get(RetType->getPointerElementType(),
  4920. matBase->getType()->getPointerAddressSpace());
  4921. Value *idx = paramList[HLOperandIndex::kMatSubscriptSubOpIdx-1];
  4922. // Lower _m00 into real idx.
  4923. // -1 to avoid opcode param which is added in EmitHLSLMatrixOperationCallImp.
  4924. Value *args[] = {paramList[HLOperandIndex::kMatSubscriptMatOpIdx - 1],
  4925. paramList[HLOperandIndex::kMatSubscriptSubOpIdx - 1]};
  4926. // For all zero idx. Still all zero idx.
  4927. if (ConstantAggregateZero *zeros = dyn_cast<ConstantAggregateZero>(idx)) {
  4928. Constant *zero = zeros->getAggregateElement((unsigned)0);
  4929. std::vector<Constant *> elts(zeros->getNumElements() >> 1, zero);
  4930. args[HLOperandIndex::kMatSubscriptSubOpIdx - 1] = ConstantVector::get(elts);
  4931. } else {
  4932. ConstantDataSequential *elts = cast<ConstantDataSequential>(idx);
  4933. unsigned count = elts->getNumElements();
  4934. unsigned row, col;
  4935. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  4936. std::vector<Constant *> idxs(count >> 1);
  4937. for (unsigned i = 0; i < count; i += 2) {
  4938. unsigned rowIdx = elts->getElementAsInteger(i);
  4939. unsigned colIdx = elts->getElementAsInteger(i + 1);
  4940. unsigned matIdx = 0;
  4941. if (isRowMajor) {
  4942. matIdx = rowIdx * col + colIdx;
  4943. } else {
  4944. matIdx = colIdx * row + rowIdx;
  4945. }
  4946. idxs[i >> 1] = CGF.Builder.getInt32(matIdx);
  4947. }
  4948. args[HLOperandIndex::kMatSubscriptSubOpIdx - 1] = ConstantVector::get(idxs);
  4949. }
  4950. return EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLSubscript,
  4951. opcode, RetType, args, TheModule);
  4952. }
  4953. Value *CGMSHLSLRuntime::EmitHLSLMatrixLoad(CGBuilderTy &Builder, Value *Ptr,
  4954. QualType Ty) {
  4955. bool isRowMajor =
  4956. IsRowMajorMatrix(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4957. unsigned opcode =
  4958. isRowMajor
  4959. ? static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatLoad)
  4960. : static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatLoad);
  4961. Value *matVal = EmitHLSLMatrixOperationCallImp(
  4962. Builder, HLOpcodeGroup::HLMatLoadStore, opcode,
  4963. Ptr->getType()->getPointerElementType(), {Ptr}, TheModule);
  4964. if (!isRowMajor) {
  4965. // ColMatLoad will return a col major matrix.
  4966. // All matrix Value should be row major.
  4967. // Cast it to row major.
  4968. matVal = EmitHLSLMatrixOperationCallImp(
  4969. Builder, HLOpcodeGroup::HLCast,
  4970. static_cast<unsigned>(HLCastOpcode::ColMatrixToRowMatrix),
  4971. matVal->getType(), {matVal}, TheModule);
  4972. }
  4973. return matVal;
  4974. }
  4975. void CGMSHLSLRuntime::EmitHLSLMatrixStore(CGBuilderTy &Builder, Value *Val,
  4976. Value *DestPtr, QualType Ty) {
  4977. bool isRowMajor =
  4978. IsRowMajorMatrix(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4979. unsigned opcode =
  4980. isRowMajor
  4981. ? static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatStore)
  4982. : static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatStore);
  4983. if (!isRowMajor) {
  4984. Value *ColVal = nullptr;
  4985. // If Val is casted from col major. Just use the original col major val.
  4986. if (CallInst *CI = dyn_cast<CallInst>(Val)) {
  4987. hlsl::HLOpcodeGroup group =
  4988. hlsl::GetHLOpcodeGroupByName(CI->getCalledFunction());
  4989. if (group == HLOpcodeGroup::HLCast) {
  4990. HLCastOpcode castOp = static_cast<HLCastOpcode>(hlsl::GetHLOpcode(CI));
  4991. if (castOp == HLCastOpcode::ColMatrixToRowMatrix) {
  4992. ColVal = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  4993. }
  4994. }
  4995. }
  4996. if (ColVal) {
  4997. Val = ColVal;
  4998. } else {
  4999. // All matrix Value should be row major.
  5000. // ColMatStore need a col major value.
  5001. // Cast it to row major.
  5002. Val = EmitHLSLMatrixOperationCallImp(
  5003. Builder, HLOpcodeGroup::HLCast,
  5004. static_cast<unsigned>(HLCastOpcode::RowMatrixToColMatrix),
  5005. Val->getType(), {Val}, TheModule);
  5006. }
  5007. }
  5008. EmitHLSLMatrixOperationCallImp(Builder, HLOpcodeGroup::HLMatLoadStore, opcode,
  5009. Val->getType(), {DestPtr, Val}, TheModule);
  5010. }
  5011. Value *CGMSHLSLRuntime::EmitHLSLMatrixLoad(CodeGenFunction &CGF, Value *Ptr,
  5012. QualType Ty) {
  5013. return EmitHLSLMatrixLoad(CGF.Builder, Ptr, Ty);
  5014. }
  5015. void CGMSHLSLRuntime::EmitHLSLMatrixStore(CodeGenFunction &CGF, Value *Val,
  5016. Value *DestPtr, QualType Ty) {
  5017. EmitHLSLMatrixStore(CGF.Builder, Val, DestPtr, Ty);
  5018. }
  5019. // Copy data from srcPtr to destPtr.
  5020. static void SimplePtrCopy(Value *DestPtr, Value *SrcPtr,
  5021. ArrayRef<Value *> idxList, CGBuilderTy &Builder) {
  5022. if (idxList.size() > 1) {
  5023. DestPtr = Builder.CreateInBoundsGEP(DestPtr, idxList);
  5024. SrcPtr = Builder.CreateInBoundsGEP(SrcPtr, idxList);
  5025. }
  5026. llvm::LoadInst *ld = Builder.CreateLoad(SrcPtr);
  5027. Builder.CreateStore(ld, DestPtr);
  5028. }
  5029. // Get Element val from SrvVal with extract value.
  5030. static Value *GetEltVal(Value *SrcVal, ArrayRef<Value*> idxList,
  5031. CGBuilderTy &Builder) {
  5032. Value *Val = SrcVal;
  5033. // Skip beginning pointer type.
  5034. for (unsigned i = 1; i < idxList.size(); i++) {
  5035. ConstantInt *idx = cast<ConstantInt>(idxList[i]);
  5036. llvm::Type *Ty = Val->getType();
  5037. if (Ty->isAggregateType()) {
  5038. Val = Builder.CreateExtractValue(Val, idx->getLimitedValue());
  5039. }
  5040. }
  5041. return Val;
  5042. }
  5043. // Copy srcVal to destPtr.
  5044. static void SimpleValCopy(Value *DestPtr, Value *SrcVal,
  5045. ArrayRef<Value*> idxList,
  5046. CGBuilderTy &Builder) {
  5047. Value *DestGEP = Builder.CreateInBoundsGEP(DestPtr, idxList);
  5048. Value *Val = GetEltVal(SrcVal, idxList, Builder);
  5049. Builder.CreateStore(Val, DestGEP);
  5050. }
  5051. static void SimpleCopy(Value *Dest, Value *Src,
  5052. ArrayRef<Value *> idxList,
  5053. CGBuilderTy &Builder) {
  5054. if (Src->getType()->isPointerTy())
  5055. SimplePtrCopy(Dest, Src, idxList, Builder);
  5056. else
  5057. SimpleValCopy(Dest, Src, idxList, Builder);
  5058. }
  5059. void CGMSHLSLRuntime::FlattenAggregatePtrToGepList(
  5060. CodeGenFunction &CGF, Value *Ptr, SmallVector<Value *, 4> &idxList,
  5061. clang::QualType Type, llvm::Type *Ty, SmallVector<Value *, 4> &GepList,
  5062. SmallVector<QualType, 4> &EltTyList) {
  5063. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  5064. Constant *idx = Constant::getIntegerValue(
  5065. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  5066. idxList.emplace_back(idx);
  5067. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, Type, PT->getElementType(),
  5068. GepList, EltTyList);
  5069. idxList.pop_back();
  5070. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  5071. // Use matLd/St for matrix.
  5072. unsigned col, row;
  5073. llvm::Type *EltTy = HLMatrixLower::GetMatrixInfo(Ty, col, row);
  5074. llvm::PointerType *EltPtrTy =
  5075. llvm::PointerType::get(EltTy, Ptr->getType()->getPointerAddressSpace());
  5076. QualType EltQualTy = hlsl::GetHLSLMatElementType(Type);
  5077. Value *matPtr = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  5078. // Flatten matrix to elements.
  5079. for (unsigned r = 0; r < row; r++) {
  5080. for (unsigned c = 0; c < col; c++) {
  5081. ConstantInt *cRow = CGF.Builder.getInt32(r);
  5082. ConstantInt *cCol = CGF.Builder.getInt32(c);
  5083. Constant *CV = llvm::ConstantVector::get({cRow, cCol});
  5084. GepList.push_back(
  5085. EmitHLSLMatrixElement(CGF, EltPtrTy, {matPtr, CV}, Type));
  5086. EltTyList.push_back(EltQualTy);
  5087. }
  5088. }
  5089. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  5090. if (HLModule::IsHLSLObjectType(ST)) {
  5091. // Avoid split HLSL object.
  5092. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  5093. GepList.push_back(GEP);
  5094. EltTyList.push_back(Type);
  5095. return;
  5096. }
  5097. const clang::RecordType *RT = Type->getAsStructureType();
  5098. RecordDecl *RD = RT->getDecl();
  5099. auto fieldIter = RD->field_begin();
  5100. const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
  5101. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5102. if (CXXRD->getNumBases()) {
  5103. // Add base as field.
  5104. for (const auto &I : CXXRD->bases()) {
  5105. const CXXRecordDecl *BaseDecl =
  5106. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  5107. // Skip empty struct.
  5108. if (BaseDecl->field_empty())
  5109. continue;
  5110. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  5111. llvm::Type *parentType = CGF.ConvertType(parentTy);
  5112. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  5113. Constant *idx = llvm::Constant::getIntegerValue(
  5114. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5115. idxList.emplace_back(idx);
  5116. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, parentTy, parentType,
  5117. GepList, EltTyList);
  5118. idxList.pop_back();
  5119. }
  5120. }
  5121. }
  5122. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  5123. fieldIter != fieldEnd; ++fieldIter) {
  5124. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  5125. llvm::Type *ET = ST->getElementType(i);
  5126. Constant *idx = llvm::Constant::getIntegerValue(
  5127. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5128. idxList.emplace_back(idx);
  5129. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, fieldIter->getType(), ET,
  5130. GepList, EltTyList);
  5131. idxList.pop_back();
  5132. }
  5133. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  5134. llvm::Type *ET = AT->getElementType();
  5135. QualType EltType = CGF.getContext().getBaseElementType(Type);
  5136. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  5137. Constant *idx = Constant::getIntegerValue(
  5138. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5139. idxList.emplace_back(idx);
  5140. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, EltType, ET, GepList,
  5141. EltTyList);
  5142. idxList.pop_back();
  5143. }
  5144. } else if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  5145. // Flatten vector too.
  5146. QualType EltTy = hlsl::GetHLSLVecElementType(Type);
  5147. for (uint32_t i = 0; i < VT->getNumElements(); i++) {
  5148. Constant *idx = CGF.Builder.getInt32(i);
  5149. idxList.emplace_back(idx);
  5150. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  5151. GepList.push_back(GEP);
  5152. EltTyList.push_back(EltTy);
  5153. idxList.pop_back();
  5154. }
  5155. } else {
  5156. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  5157. GepList.push_back(GEP);
  5158. EltTyList.push_back(Type);
  5159. }
  5160. }
  5161. void CGMSHLSLRuntime::LoadFlattenedGepList(CodeGenFunction &CGF,
  5162. ArrayRef<Value *> GepList,
  5163. ArrayRef<QualType> EltTyList,
  5164. SmallVector<Value *, 4> &EltList) {
  5165. unsigned eltSize = GepList.size();
  5166. for (unsigned i = 0; i < eltSize; i++) {
  5167. Value *Ptr = GepList[i];
  5168. QualType Type = EltTyList[i];
  5169. // Everying is element type.
  5170. EltList.push_back(CGF.Builder.CreateLoad(Ptr));
  5171. }
  5172. }
  5173. void CGMSHLSLRuntime::StoreFlattenedGepList(CodeGenFunction &CGF, ArrayRef<Value *> GepList,
  5174. ArrayRef<QualType> GepTyList, ArrayRef<Value *> EltValList, ArrayRef<QualType> SrcTyList) {
  5175. unsigned eltSize = GepList.size();
  5176. for (unsigned i = 0; i < eltSize; i++) {
  5177. Value *Ptr = GepList[i];
  5178. QualType DestType = GepTyList[i];
  5179. Value *Val = EltValList[i];
  5180. QualType SrcType = SrcTyList[i];
  5181. llvm::Type *Ty = Ptr->getType()->getPointerElementType();
  5182. // Everything is element type.
  5183. if (Ty != Val->getType()) {
  5184. Instruction::CastOps castOp =
  5185. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  5186. IsUnsigned(SrcType), IsUnsigned(DestType), Val->getType(), Ty));
  5187. Val = CGF.Builder.CreateCast(castOp, Val, Ty);
  5188. }
  5189. CGF.Builder.CreateStore(Val, Ptr);
  5190. }
  5191. }
  5192. // Copy data from SrcPtr to DestPtr.
  5193. // For matrix, use MatLoad/MatStore.
  5194. // For matrix array, EmitHLSLAggregateCopy on each element.
  5195. // For struct or array, use memcpy.
  5196. // Other just load/store.
  5197. void CGMSHLSLRuntime::EmitHLSLAggregateCopy(
  5198. CodeGenFunction &CGF, llvm::Value *SrcPtr, llvm::Value *DestPtr,
  5199. SmallVector<Value *, 4> &idxList, clang::QualType SrcType,
  5200. clang::QualType DestType, llvm::Type *Ty) {
  5201. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  5202. Constant *idx = Constant::getIntegerValue(
  5203. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  5204. idxList.emplace_back(idx);
  5205. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, SrcType, DestType,
  5206. PT->getElementType());
  5207. idxList.pop_back();
  5208. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  5209. // Use matLd/St for matrix.
  5210. Value *srcGEP = CGF.Builder.CreateInBoundsGEP(SrcPtr, idxList);
  5211. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  5212. Value *ldMat = EmitHLSLMatrixLoad(CGF, srcGEP, SrcType);
  5213. EmitHLSLMatrixStore(CGF, ldMat, dstGEP, DestType);
  5214. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  5215. if (HLModule::IsHLSLObjectType(ST)) {
  5216. // Avoid split HLSL object.
  5217. SimpleCopy(DestPtr, SrcPtr, idxList, CGF.Builder);
  5218. return;
  5219. }
  5220. Value *srcGEP = CGF.Builder.CreateInBoundsGEP(SrcPtr, idxList);
  5221. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  5222. unsigned size = this->TheModule.getDataLayout().getTypeAllocSize(ST);
  5223. // Memcpy struct.
  5224. CGF.Builder.CreateMemCpy(dstGEP, srcGEP, size, 1);
  5225. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  5226. if (!HLMatrixLower::IsMatrixArrayPointer(llvm::PointerType::get(Ty,0))) {
  5227. Value *srcGEP = CGF.Builder.CreateInBoundsGEP(SrcPtr, idxList);
  5228. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  5229. unsigned size = this->TheModule.getDataLayout().getTypeAllocSize(AT);
  5230. // Memcpy non-matrix array.
  5231. CGF.Builder.CreateMemCpy(dstGEP, srcGEP, size, 1);
  5232. } else {
  5233. llvm::Type *ET = AT->getElementType();
  5234. QualType EltDestType = CGF.getContext().getBaseElementType(DestType);
  5235. QualType EltSrcType = CGF.getContext().getBaseElementType(SrcType);
  5236. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  5237. Constant *idx = Constant::getIntegerValue(
  5238. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5239. idxList.emplace_back(idx);
  5240. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, EltSrcType,
  5241. EltDestType, ET);
  5242. idxList.pop_back();
  5243. }
  5244. }
  5245. } else {
  5246. SimpleCopy(DestPtr, SrcPtr, idxList, CGF.Builder);
  5247. }
  5248. }
  5249. void CGMSHLSLRuntime::EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  5250. llvm::Value *DestPtr,
  5251. clang::QualType Ty) {
  5252. SmallVector<Value *, 4> idxList;
  5253. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, Ty, Ty, SrcPtr->getType());
  5254. }
  5255. void CGMSHLSLRuntime::EmitHLSLFlatConversionAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  5256. clang::QualType SrcTy,
  5257. llvm::Value *DestPtr,
  5258. clang::QualType DestTy) {
  5259. llvm::Type *SrcPtrTy = SrcPtr->getType()->getPointerElementType();
  5260. llvm::Type *DestPtrTy = DestPtr->getType()->getPointerElementType();
  5261. if (SrcPtrTy == DestPtrTy) {
  5262. // Memcpy if type is match.
  5263. unsigned size = TheModule.getDataLayout().getTypeAllocSize(SrcPtrTy);
  5264. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, size, 1);
  5265. return;
  5266. } else if (HLModule::IsHLSLObjectType(dxilutil::GetArrayEltTy(SrcPtrTy)) &&
  5267. HLModule::IsHLSLObjectType(dxilutil::GetArrayEltTy(DestPtrTy))) {
  5268. unsigned sizeSrc = TheModule.getDataLayout().getTypeAllocSize(SrcPtrTy);
  5269. unsigned sizeDest = TheModule.getDataLayout().getTypeAllocSize(DestPtrTy);
  5270. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, std::max(sizeSrc, sizeDest), 1);
  5271. return;
  5272. }
  5273. // It is possiable to implement EmitHLSLAggregateCopy, EmitHLSLAggregateStore
  5274. // the same way. But split value to scalar will generate many instruction when
  5275. // src type is same as dest type.
  5276. SmallVector<Value *, 4> idxList;
  5277. SmallVector<Value *, 4> SrcGEPList;
  5278. SmallVector<QualType, 4> SrcEltTyList;
  5279. FlattenAggregatePtrToGepList(CGF, SrcPtr, idxList, SrcTy, SrcPtr->getType(),
  5280. SrcGEPList, SrcEltTyList);
  5281. SmallVector<Value *, 4> LdEltList;
  5282. LoadFlattenedGepList(CGF, SrcGEPList, SrcEltTyList, LdEltList);
  5283. idxList.clear();
  5284. SmallVector<Value *, 4> DestGEPList;
  5285. SmallVector<QualType, 4> DestEltTyList;
  5286. FlattenAggregatePtrToGepList(CGF, DestPtr, idxList, DestTy,
  5287. DestPtr->getType(), DestGEPList, DestEltTyList);
  5288. StoreFlattenedGepList(CGF, DestGEPList, DestEltTyList, LdEltList,
  5289. SrcEltTyList);
  5290. }
  5291. void CGMSHLSLRuntime::EmitHLSLAggregateStore(CodeGenFunction &CGF, llvm::Value *SrcVal,
  5292. llvm::Value *DestPtr,
  5293. clang::QualType Ty) {
  5294. DXASSERT(0, "aggregate return type will use SRet, no aggregate store should exist");
  5295. }
  5296. static void SimpleFlatValCopy(Value *DestPtr, Value *SrcVal, QualType Ty,
  5297. QualType SrcTy, ArrayRef<Value *> idxList,
  5298. CGBuilderTy &Builder) {
  5299. Value *DestGEP = Builder.CreateInBoundsGEP(DestPtr, idxList);
  5300. llvm::Type *ToTy = DestGEP->getType()->getPointerElementType();
  5301. llvm::Type *EltToTy = ToTy;
  5302. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(ToTy)) {
  5303. EltToTy = VT->getElementType();
  5304. }
  5305. if (EltToTy != SrcVal->getType()) {
  5306. Instruction::CastOps castOp =
  5307. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  5308. IsUnsigned(SrcTy), IsUnsigned(Ty), SrcVal->getType(), ToTy));
  5309. SrcVal = Builder.CreateCast(castOp, SrcVal, EltToTy);
  5310. }
  5311. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(ToTy)) {
  5312. llvm::VectorType *VT1 = llvm::VectorType::get(EltToTy, 1);
  5313. Value *V1 =
  5314. Builder.CreateInsertElement(UndefValue::get(VT1), SrcVal, (uint64_t)0);
  5315. std::vector<int> shufIdx(VT->getNumElements(), 0);
  5316. Value *Vec = Builder.CreateShuffleVector(V1, V1, shufIdx);
  5317. Builder.CreateStore(Vec, DestGEP);
  5318. } else
  5319. Builder.CreateStore(SrcVal, DestGEP);
  5320. }
  5321. void CGMSHLSLRuntime::EmitHLSLFlatConversionToAggregate(
  5322. CodeGenFunction &CGF, Value *SrcVal, llvm::Value *DestPtr,
  5323. SmallVector<Value *, 4> &idxList, QualType Type, QualType SrcType,
  5324. llvm::Type *Ty) {
  5325. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  5326. Constant *idx = Constant::getIntegerValue(
  5327. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  5328. idxList.emplace_back(idx);
  5329. EmitHLSLFlatConversionToAggregate(CGF, SrcVal, DestPtr, idxList, Type,
  5330. SrcType, PT->getElementType());
  5331. idxList.pop_back();
  5332. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  5333. // Use matLd/St for matrix.
  5334. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  5335. unsigned row, col;
  5336. llvm::Type *EltTy = HLMatrixLower::GetMatrixInfo(Ty, col, row);
  5337. llvm::VectorType *VT1 = llvm::VectorType::get(EltTy, 1);
  5338. if (EltTy != SrcVal->getType()) {
  5339. Instruction::CastOps castOp =
  5340. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  5341. IsUnsigned(SrcType), IsUnsigned(Type), SrcVal->getType(), EltTy));
  5342. SrcVal = CGF.Builder.CreateCast(castOp, SrcVal, EltTy);
  5343. }
  5344. Value *V1 = CGF.Builder.CreateInsertElement(UndefValue::get(VT1), SrcVal,
  5345. (uint64_t)0);
  5346. std::vector<int> shufIdx(col * row, 0);
  5347. Value *VecMat = CGF.Builder.CreateShuffleVector(V1, V1, shufIdx);
  5348. Value *MatInit = EmitHLSLMatrixOperationCallImp(
  5349. CGF.Builder, HLOpcodeGroup::HLInit, 0, Ty, {VecMat}, TheModule);
  5350. EmitHLSLMatrixStore(CGF, MatInit, dstGEP, Type);
  5351. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  5352. DXASSERT(!HLModule::IsHLSLObjectType(ST), "cannot cast to hlsl object, Sema should reject");
  5353. const clang::RecordType *RT = Type->getAsStructureType();
  5354. RecordDecl *RD = RT->getDecl();
  5355. auto fieldIter = RD->field_begin();
  5356. const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
  5357. // Take care base.
  5358. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5359. if (CXXRD->getNumBases()) {
  5360. for (const auto &I : CXXRD->bases()) {
  5361. const CXXRecordDecl *BaseDecl =
  5362. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  5363. if (BaseDecl->field_empty())
  5364. continue;
  5365. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  5366. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  5367. llvm::Type *ET = ST->getElementType(i);
  5368. Constant *idx = llvm::Constant::getIntegerValue(
  5369. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5370. idxList.emplace_back(idx);
  5371. EmitHLSLFlatConversionToAggregate(CGF, SrcVal, DestPtr, idxList,
  5372. parentTy, SrcType, ET);
  5373. idxList.pop_back();
  5374. }
  5375. }
  5376. }
  5377. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  5378. fieldIter != fieldEnd; ++fieldIter) {
  5379. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  5380. llvm::Type *ET = ST->getElementType(i);
  5381. Constant *idx = llvm::Constant::getIntegerValue(
  5382. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5383. idxList.emplace_back(idx);
  5384. EmitHLSLFlatConversionToAggregate(CGF, SrcVal, DestPtr, idxList,
  5385. fieldIter->getType(), SrcType, ET);
  5386. idxList.pop_back();
  5387. }
  5388. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  5389. llvm::Type *ET = AT->getElementType();
  5390. QualType EltType = CGF.getContext().getBaseElementType(Type);
  5391. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  5392. Constant *idx = Constant::getIntegerValue(
  5393. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5394. idxList.emplace_back(idx);
  5395. EmitHLSLFlatConversionToAggregate(CGF, SrcVal, DestPtr, idxList, EltType,
  5396. SrcType, ET);
  5397. idxList.pop_back();
  5398. }
  5399. } else {
  5400. SimpleFlatValCopy(DestPtr, SrcVal, Type, SrcType, idxList, CGF.Builder);
  5401. }
  5402. }
  5403. void CGMSHLSLRuntime::EmitHLSLFlatConversionToAggregate(CodeGenFunction &CGF,
  5404. Value *Val,
  5405. Value *DestPtr,
  5406. QualType Ty,
  5407. QualType SrcTy) {
  5408. if (SrcTy->isBuiltinType()) {
  5409. SmallVector<Value *, 4> idxList;
  5410. // Add first 0 for DestPtr.
  5411. Constant *idx = Constant::getIntegerValue(
  5412. IntegerType::get(Val->getContext(), 32), APInt(32, 0));
  5413. idxList.emplace_back(idx);
  5414. EmitHLSLFlatConversionToAggregate(
  5415. CGF, Val, DestPtr, idxList, Ty, SrcTy,
  5416. DestPtr->getType()->getPointerElementType());
  5417. }
  5418. else {
  5419. SmallVector<Value *, 4> idxList;
  5420. SmallVector<Value *, 4> DestGEPList;
  5421. SmallVector<QualType, 4> DestEltTyList;
  5422. FlattenAggregatePtrToGepList(CGF, DestPtr, idxList, Ty, DestPtr->getType(), DestGEPList, DestEltTyList);
  5423. SmallVector<Value *, 4> EltList;
  5424. SmallVector<QualType, 4> EltTyList;
  5425. FlattenValToInitList(CGF, EltList, EltTyList, SrcTy, Val);
  5426. StoreFlattenedGepList(CGF, DestGEPList, DestEltTyList, EltList, EltTyList);
  5427. }
  5428. }
  5429. void CGMSHLSLRuntime::EmitHLSLRootSignature(CodeGenFunction &CGF,
  5430. HLSLRootSignatureAttr *RSA,
  5431. Function *Fn) {
  5432. // Only parse root signature for entry function.
  5433. if (Fn != Entry.Func)
  5434. return;
  5435. StringRef StrRef = RSA->getSignatureName();
  5436. DiagnosticsEngine &Diags = CGF.getContext().getDiagnostics();
  5437. SourceLocation SLoc = RSA->getLocation();
  5438. clang::CompileRootSignature(StrRef, Diags, SLoc, rootSigVer, &m_pHLModule->GetRootSignature());
  5439. }
  5440. void CGMSHLSLRuntime::EmitHLSLOutParamConversionInit(
  5441. CodeGenFunction &CGF, const FunctionDecl *FD, const CallExpr *E,
  5442. llvm::SmallVector<LValue, 8> &castArgList,
  5443. llvm::SmallVector<const Stmt *, 8> &argList,
  5444. const std::function<void(const VarDecl *, llvm::Value *)> &TmpArgMap) {
  5445. // Special case: skip first argument of CXXOperatorCall (it is "this").
  5446. unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(E) ? 1 : 0;
  5447. for (uint32_t i = 0; i < FD->getNumParams(); i++) {
  5448. const ParmVarDecl *Param = FD->getParamDecl(i);
  5449. const Expr *Arg = E->getArg(i+ArgsToSkip);
  5450. QualType ParamTy = Param->getType().getNonReferenceType();
  5451. bool RValOnRef = false;
  5452. if (!Param->isModifierOut()) {
  5453. if (!ParamTy->isAggregateType() || hlsl::IsHLSLMatType(ParamTy)) {
  5454. if (Arg->isRValue() && Param->getType()->isReferenceType()) {
  5455. // RValue on a reference type.
  5456. if (const CStyleCastExpr *cCast = dyn_cast<CStyleCastExpr>(Arg)) {
  5457. // TODO: Evolving this to warn then fail in future language versions.
  5458. // Allow special case like cast uint to uint for back-compat.
  5459. if (cCast->getCastKind() == CastKind::CK_NoOp) {
  5460. if (const ImplicitCastExpr *cast =
  5461. dyn_cast<ImplicitCastExpr>(cCast->getSubExpr())) {
  5462. if (cast->getCastKind() == CastKind::CK_LValueToRValue) {
  5463. // update the arg
  5464. argList[i] = cast->getSubExpr();
  5465. continue;
  5466. }
  5467. }
  5468. }
  5469. }
  5470. // EmitLValue will report error.
  5471. // Mark RValOnRef to create tmpArg for it.
  5472. RValOnRef = true;
  5473. } else {
  5474. continue;
  5475. }
  5476. }
  5477. }
  5478. // get original arg
  5479. LValue argLV = CGF.EmitLValue(Arg);
  5480. if (!Param->isModifierOut() && !RValOnRef) {
  5481. bool isDefaultAddrSpace = true;
  5482. if (argLV.isSimple()) {
  5483. isDefaultAddrSpace =
  5484. argLV.getAddress()->getType()->getPointerAddressSpace() ==
  5485. DXIL::kDefaultAddrSpace;
  5486. }
  5487. bool isHLSLIntrinsic = false;
  5488. if (const FunctionDecl *Callee = E->getDirectCallee()) {
  5489. isHLSLIntrinsic = Callee->hasAttr<HLSLIntrinsicAttr>();
  5490. }
  5491. // Copy in arg which is not default address space and not on hlsl intrinsic.
  5492. if (isDefaultAddrSpace || isHLSLIntrinsic)
  5493. continue;
  5494. }
  5495. // create temp Var
  5496. VarDecl *tmpArg =
  5497. VarDecl::Create(CGF.getContext(), const_cast<FunctionDecl *>(FD),
  5498. SourceLocation(), SourceLocation(),
  5499. /*IdentifierInfo*/ nullptr, ParamTy,
  5500. CGF.getContext().getTrivialTypeSourceInfo(ParamTy),
  5501. StorageClass::SC_Auto);
  5502. // Aggregate type will be indirect param convert to pointer type.
  5503. // So don't update to ReferenceType, use RValue for it.
  5504. bool isAggregateType = (ParamTy->isArrayType() || ParamTy->isRecordType()) &&
  5505. !hlsl::IsHLSLVecMatType(ParamTy);
  5506. const DeclRefExpr *tmpRef = DeclRefExpr::Create(
  5507. CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), tmpArg,
  5508. /*enclosing*/ false, tmpArg->getLocation(), ParamTy,
  5509. isAggregateType ? VK_RValue : VK_LValue);
  5510. // update the arg
  5511. argList[i] = tmpRef;
  5512. // create alloc for the tmp arg
  5513. Value *tmpArgAddr = nullptr;
  5514. BasicBlock *InsertBlock = CGF.Builder.GetInsertBlock();
  5515. Function *F = InsertBlock->getParent();
  5516. BasicBlock *EntryBlock = &F->getEntryBlock();
  5517. if (ParamTy->isBooleanType()) {
  5518. // Create i32 for bool.
  5519. ParamTy = CGM.getContext().IntTy;
  5520. }
  5521. // Make sure the alloca is in entry block to stop inline create stacksave.
  5522. IRBuilder<> Builder(EntryBlock->getFirstInsertionPt());
  5523. tmpArgAddr = Builder.CreateAlloca(CGF.ConvertType(ParamTy));
  5524. // add it to local decl map
  5525. TmpArgMap(tmpArg, tmpArgAddr);
  5526. LValue tmpLV = LValue::MakeAddr(tmpArgAddr, ParamTy, argLV.getAlignment(),
  5527. CGF.getContext());
  5528. // save for cast after call
  5529. if (Param->isModifierOut()) {
  5530. castArgList.emplace_back(tmpLV);
  5531. castArgList.emplace_back(argLV);
  5532. }
  5533. bool isObject = HLModule::IsHLSLObjectType(
  5534. tmpArgAddr->getType()->getPointerElementType());
  5535. // cast before the call
  5536. if (Param->isModifierIn() &&
  5537. // Don't copy object
  5538. !isObject) {
  5539. QualType ArgTy = Arg->getType();
  5540. Value *outVal = nullptr;
  5541. bool isAggrageteTy = ParamTy->isAggregateType();
  5542. isAggrageteTy &= !IsHLSLVecMatType(ParamTy);
  5543. if (!isAggrageteTy) {
  5544. if (!IsHLSLMatType(ParamTy)) {
  5545. RValue outRVal = CGF.EmitLoadOfLValue(argLV, SourceLocation());
  5546. outVal = outRVal.getScalarVal();
  5547. } else {
  5548. Value *argAddr = argLV.getAddress();
  5549. outVal = EmitHLSLMatrixLoad(CGF, argAddr, ArgTy);
  5550. }
  5551. llvm::Type *ToTy = tmpArgAddr->getType()->getPointerElementType();
  5552. Instruction::CastOps castOp =
  5553. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  5554. IsUnsigned(argLV.getType()), IsUnsigned(tmpLV.getType()),
  5555. outVal->getType(), ToTy));
  5556. Value *castVal = CGF.Builder.CreateCast(castOp, outVal, ToTy);
  5557. if (!HLMatrixLower::IsMatrixType(ToTy))
  5558. CGF.Builder.CreateStore(castVal, tmpArgAddr);
  5559. else
  5560. EmitHLSLMatrixStore(CGF, castVal, tmpArgAddr, ParamTy);
  5561. } else {
  5562. SmallVector<Value *, 4> idxList;
  5563. EmitHLSLAggregateCopy(CGF, argLV.getAddress(), tmpLV.getAddress(),
  5564. idxList, ArgTy, ParamTy,
  5565. argLV.getAddress()->getType());
  5566. }
  5567. }
  5568. }
  5569. }
  5570. void CGMSHLSLRuntime::EmitHLSLOutParamConversionCopyBack(
  5571. CodeGenFunction &CGF, llvm::SmallVector<LValue, 8> &castArgList) {
  5572. for (uint32_t i = 0; i < castArgList.size(); i += 2) {
  5573. // cast after the call
  5574. LValue tmpLV = castArgList[i];
  5575. LValue argLV = castArgList[i + 1];
  5576. QualType ArgTy = argLV.getType().getNonReferenceType();
  5577. QualType ParamTy = tmpLV.getType().getNonReferenceType();
  5578. Value *tmpArgAddr = tmpLV.getAddress();
  5579. Value *outVal = nullptr;
  5580. bool isAggrageteTy = ArgTy->isAggregateType();
  5581. isAggrageteTy &= !IsHLSLVecMatType(ArgTy);
  5582. bool isObject = HLModule::IsHLSLObjectType(
  5583. tmpArgAddr->getType()->getPointerElementType());
  5584. if (!isObject) {
  5585. if (!isAggrageteTy) {
  5586. if (!IsHLSLMatType(ParamTy))
  5587. outVal = CGF.Builder.CreateLoad(tmpArgAddr);
  5588. else
  5589. outVal = EmitHLSLMatrixLoad(CGF, tmpArgAddr, ParamTy);
  5590. llvm::Type *ToTy = CGF.ConvertType(ArgTy);
  5591. llvm::Type *FromTy = outVal->getType();
  5592. Value *castVal = outVal;
  5593. if (ToTy == FromTy) {
  5594. // Don't need cast.
  5595. } else if (ToTy->getScalarType() == FromTy->getScalarType()) {
  5596. if (ToTy->getScalarType() == ToTy) {
  5597. DXASSERT(FromTy->isVectorTy() &&
  5598. FromTy->getVectorNumElements() == 1,
  5599. "must be vector of 1 element");
  5600. castVal = CGF.Builder.CreateExtractElement(outVal, (uint64_t)0);
  5601. } else {
  5602. DXASSERT(!FromTy->isVectorTy(), "must be scalar type");
  5603. DXASSERT(ToTy->isVectorTy() && ToTy->getVectorNumElements() == 1,
  5604. "must be vector of 1 element");
  5605. castVal = UndefValue::get(ToTy);
  5606. castVal =
  5607. CGF.Builder.CreateInsertElement(castVal, outVal, (uint64_t)0);
  5608. }
  5609. } else {
  5610. Instruction::CastOps castOp =
  5611. static_cast<Instruction::CastOps>(HLModule::FindCastOp(
  5612. IsUnsigned(tmpLV.getType()), IsUnsigned(argLV.getType()),
  5613. outVal->getType(), ToTy));
  5614. castVal = CGF.Builder.CreateCast(castOp, outVal, ToTy);
  5615. }
  5616. if (!HLMatrixLower::IsMatrixType(ToTy))
  5617. CGF.EmitStoreThroughLValue(RValue::get(castVal), argLV);
  5618. else {
  5619. Value *destPtr = argLV.getAddress();
  5620. EmitHLSLMatrixStore(CGF, castVal, destPtr, ArgTy);
  5621. }
  5622. } else {
  5623. SmallVector<Value *, 4> idxList;
  5624. EmitHLSLAggregateCopy(CGF, tmpLV.getAddress(), argLV.getAddress(),
  5625. idxList, ParamTy, ArgTy,
  5626. argLV.getAddress()->getType());
  5627. }
  5628. } else
  5629. tmpArgAddr->replaceAllUsesWith(argLV.getAddress());
  5630. }
  5631. }
  5632. CGHLSLRuntime *CodeGen::CreateMSHLSLRuntime(CodeGenModule &CGM) {
  5633. return new CGMSHLSLRuntime(CGM);
  5634. }