CGHLSLMS.cpp 245 KB

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