CGHLSLMS.cpp 252 KB

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