CGHLSLMS.cpp 223 KB

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