CGHLSLMS.cpp 272 KB

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