CGHLSLMS.cpp 272 KB

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