CGHLSLMS.cpp 268 KB

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