CGHLSLMS.cpp 196 KB

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