2
0

CGHLSLMS.cpp 238 KB

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