DxilGenerationPass.cpp 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilGenerationPass.cpp //
  4. // Copyright (C) Microsoft Corporation. All rights reserved. //
  5. // This file is distributed under the University of Illinois Open Source //
  6. // License. See LICENSE.TXT for details. //
  7. // //
  8. // DxilGenerationPass implementation. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #include "dxc/HLSL/DxilGenerationPass.h"
  12. #include "dxc/HLSL/DxilOperations.h"
  13. #include "dxc/HLSL/DxilSignatureElement.h"
  14. #include "dxc/HLSL/DxilSigPoint.h"
  15. #include "dxc/HLSL/DxilModule.h"
  16. #include "dxc/HLSL/HLModule.h"
  17. #include "dxc/HLSL/HLOperations.h"
  18. #include "dxc/HLSL/HLMatrixLowerHelper.h"
  19. #include "dxc/HlslIntrinsicOp.h"
  20. #include "dxc/Support/Global.h"
  21. #include "dxc/HLSL/DxilTypeSystem.h"
  22. #include "dxc/HLSL/HLOperationLower.h"
  23. #include "llvm/IR/GetElementPtrTypeIterator.h"
  24. #include "llvm/IR/IRBuilder.h"
  25. #include "llvm/IR/Instructions.h"
  26. #include "llvm/IR/InstIterator.h"
  27. #include "llvm/IR/IntrinsicInst.h"
  28. #include "llvm/IR/Module.h"
  29. #include "llvm/IR/DebugInfo.h"
  30. #include "llvm/IR/PassManager.h"
  31. #include "llvm/ADT/BitVector.h"
  32. #include "llvm/Pass.h"
  33. #include "llvm/Transforms/Utils/Local.h"
  34. #include "llvm/Transforms/Utils/SSAUpdater.h"
  35. #include "llvm/Analysis/AssumptionCache.h"
  36. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  37. #include <memory>
  38. #include <unordered_set>
  39. using namespace llvm;
  40. using namespace hlsl;
  41. // TODO: use hlsl namespace for the most of this file.
  42. namespace {
  43. // Collect unused phi of resources and remove them.
  44. class ResourceRemover : public LoadAndStorePromoter {
  45. AllocaInst *AI;
  46. mutable std::unordered_set<PHINode *> unusedPhis;
  47. public:
  48. ResourceRemover(ArrayRef<Instruction *> Insts, SSAUpdater &S)
  49. : LoadAndStorePromoter(Insts, S), AI(nullptr) {}
  50. void run(AllocaInst *AI, const SmallVectorImpl<Instruction *> &Insts) {
  51. // Remember which alloca we're promoting (for isInstInList).
  52. this->AI = AI;
  53. LoadAndStorePromoter::run(Insts);
  54. for (PHINode *P : unusedPhis) {
  55. P->eraseFromParent();
  56. }
  57. }
  58. bool
  59. isInstInList(Instruction *I,
  60. const SmallVectorImpl<Instruction *> &Insts) const override {
  61. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  62. return LI->getOperand(0) == AI;
  63. return cast<StoreInst>(I)->getPointerOperand() == AI;
  64. }
  65. void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
  66. if (PHINode *PHI = dyn_cast<PHINode>(V)) {
  67. if (PHI->user_empty())
  68. unusedPhis.insert(PHI);
  69. }
  70. LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
  71. }
  72. };
  73. void InitResourceBase(const DxilResourceBase *pSource, DxilResourceBase *pDest) {
  74. DXASSERT_NOMSG(pSource->GetClass() == pDest->GetClass());
  75. pDest->SetKind(pSource->GetKind());
  76. pDest->SetID(pSource->GetID());
  77. pDest->SetSpaceID(pSource->GetSpaceID());
  78. pDest->SetLowerBound(pSource->GetLowerBound());
  79. pDest->SetRangeSize(pSource->GetRangeSize());
  80. pDest->SetGlobalSymbol(pSource->GetGlobalSymbol());
  81. pDest->SetGlobalName(pSource->GetGlobalName());
  82. pDest->SetHandle(pSource->GetHandle());
  83. }
  84. void InitResource(const DxilResource *pSource, DxilResource *pDest) {
  85. pDest->SetCompType(pSource->GetCompType());
  86. pDest->SetSampleCount(pSource->GetSampleCount());
  87. pDest->SetElementStride(pSource->GetElementStride());
  88. pDest->SetGloballyCoherent(pSource->IsGloballyCoherent());
  89. pDest->SetHasCounter(pSource->HasCounter());
  90. pDest->SetRW(pSource->IsRW());
  91. pDest->SetROV(pSource->IsROV());
  92. InitResourceBase(pSource, pDest);
  93. }
  94. void InitDxilModuleFromHLModule(HLModule &H, DxilModule &M, bool HasDebugInfo) {
  95. // Subsystems.
  96. unsigned ValMajor, ValMinor;
  97. H.GetValidatorVersion(ValMajor, ValMinor);
  98. M.SetValidatorVersion(ValMajor, ValMinor);
  99. M.SetShaderModel(H.GetShaderModel());
  100. // Entry function.
  101. Function *EntryFn = H.GetEntryFunction();
  102. HLFunctionProps *FnProps = H.HasHLFunctionProps(EntryFn) ? &H.GetHLFunctionProps(EntryFn) : nullptr;
  103. M.SetEntryFunction(EntryFn);
  104. M.SetEntryFunctionName(H.GetEntryFunctionName());
  105. std::vector<GlobalVariable* > &LLVMUsed = M.GetLLVMUsed();
  106. // Resources
  107. for (auto && C : H.GetCBuffers()) {
  108. auto b = make_unique<DxilCBuffer>();
  109. InitResourceBase(C.get(), b.get());
  110. b->SetSize(C->GetSize());
  111. if (HasDebugInfo)
  112. LLVMUsed.emplace_back(cast<GlobalVariable>(b->GetGlobalSymbol()));
  113. b->SetGlobalSymbol(UndefValue::get(b->GetGlobalSymbol()->getType()));
  114. M.AddCBuffer(std::move(b));
  115. }
  116. for (auto && C : H.GetUAVs()) {
  117. auto b = make_unique<DxilResource>();
  118. InitResource(C.get(), b.get());
  119. if (HasDebugInfo)
  120. LLVMUsed.emplace_back(cast<GlobalVariable>(b->GetGlobalSymbol()));
  121. b->SetGlobalSymbol(UndefValue::get(b->GetGlobalSymbol()->getType()));
  122. M.AddUAV(std::move(b));
  123. }
  124. for (auto && C : H.GetSRVs()) {
  125. auto b = make_unique<DxilResource>();
  126. InitResource(C.get(), b.get());
  127. if (HasDebugInfo)
  128. LLVMUsed.emplace_back(cast<GlobalVariable>(b->GetGlobalSymbol()));
  129. b->SetGlobalSymbol(UndefValue::get(b->GetGlobalSymbol()->getType()));
  130. M.AddSRV(std::move(b));
  131. }
  132. for (auto && C : H.GetSamplers()) {
  133. auto b = make_unique<DxilSampler>();
  134. InitResourceBase(C.get(), b.get());
  135. b->SetSamplerKind(C->GetSamplerKind());
  136. if (HasDebugInfo)
  137. LLVMUsed.emplace_back(cast<GlobalVariable>(b->GetGlobalSymbol()));
  138. b->SetGlobalSymbol(UndefValue::get(b->GetGlobalSymbol()->getType()));
  139. M.AddSampler(std::move(b));
  140. }
  141. // Signatures.
  142. M.ResetInputSignature(H.ReleaseInputSignature());
  143. M.ResetOutputSignature(H.ReleaseOutputSignature());
  144. M.ResetPatchConstantSignature(H.ReleasePatchConstantSignature());
  145. M.ResetRootSignature(H.ReleaseRootSignature());
  146. // Shader properties.
  147. //bool m_bDisableOptimizations;
  148. M.m_ShaderFlags.SetDisableOptimizations(H.GetHLOptions().bDisableOptimizations);
  149. //bool m_bDisableMathRefactoring;
  150. //bool m_bEnableDoublePrecision;
  151. //bool m_bEnableDoubleExtensions;
  152. //bool m_bEnableMinPrecision;
  153. //M.CollectShaderFlags();
  154. //bool m_bForceEarlyDepthStencil;
  155. //bool m_bEnableRawAndStructuredBuffers;
  156. //bool m_bEnableMSAD;
  157. //M.m_ShaderFlags.SetAllResourcesBound(H.GetHLOptions().bAllResourcesBound);
  158. // Compute shader.
  159. if (FnProps != nullptr && FnProps->shaderKind == DXIL::ShaderKind::Compute) {
  160. auto &CS = FnProps->ShaderProps.CS;
  161. for (size_t i = 0; i < _countof(M.m_NumThreads); ++i)
  162. M.m_NumThreads[i] = CS.numThreads[i];
  163. }
  164. // Geometry shader.
  165. if (FnProps != nullptr && FnProps->shaderKind == DXIL::ShaderKind::Geometry) {
  166. auto &GS = FnProps->ShaderProps.GS;
  167. M.SetInputPrimitive(GS.inputPrimitive);
  168. M.SetMaxVertexCount(GS.maxVertexCount);
  169. for (size_t i = 0; i < _countof(GS.streamPrimitiveTopologies); ++i) {
  170. if (GS.streamPrimitiveTopologies[i] != DXIL::PrimitiveTopology::Undefined) {
  171. M.SetStreamActive(i, true);
  172. DXASSERT_NOMSG(M.GetStreamPrimitiveTopology() ==
  173. DXIL::PrimitiveTopology::Undefined ||
  174. M.GetStreamPrimitiveTopology() ==
  175. GS.streamPrimitiveTopologies[i]);
  176. M.SetStreamPrimitiveTopology(GS.streamPrimitiveTopologies[i]);
  177. }
  178. }
  179. M.SetGSInstanceCount(GS.instanceCount);
  180. }
  181. // Hull and Domain shaders.
  182. if (FnProps != nullptr && FnProps->shaderKind == DXIL::ShaderKind::Domain) {
  183. auto &DS = FnProps->ShaderProps.DS;
  184. M.SetTessellatorDomain(DS.domain);
  185. M.SetInputControlPointCount(DS.inputControlPoints);
  186. }
  187. // Hull shader.
  188. if (FnProps != nullptr && FnProps->shaderKind == DXIL::ShaderKind::Hull) {
  189. auto &HS = FnProps->ShaderProps.HS;
  190. M.SetPatchConstantFunction(HS.patchConstantFunc);
  191. M.SetTessellatorDomain(HS.domain);
  192. M.SetTessellatorPartitioning(HS.partition);
  193. M.SetTessellatorOutputPrimitive(HS.outputPrimitive);
  194. M.SetInputControlPointCount(HS.inputControlPoints);
  195. M.SetOutputControlPointCount(HS.outputControlPoints);
  196. M.SetMaxTessellationFactor(HS.maxTessFactor);
  197. }
  198. // Pixel shader.
  199. if (FnProps != nullptr && FnProps->shaderKind == DXIL::ShaderKind::Pixel) {
  200. auto &PS = FnProps->ShaderProps.PS;
  201. M.m_ShaderFlags.SetForceEarlyDepthStencil(PS.EarlyDepthStencil);
  202. }
  203. // DXIL type system.
  204. M.ResetTypeSystem(H.ReleaseTypeSystem());
  205. // Dxil OP.
  206. M.ResetOP(H.ReleaseOP());
  207. // Keep llvm used.
  208. M.EmitLLVMUsed();
  209. M.m_ShaderFlags.SetAllResourcesBound(H.GetHLOptions().bAllResourcesBound);
  210. // Update Validator Version
  211. M.UpgradeToMinValidatorVersion();
  212. }
  213. class DxilGenerationPass : public ModulePass {
  214. HLModule *m_pHLModule;
  215. bool m_HasDbgInfo;
  216. HLSLExtensionsCodegenHelper *m_extensionsCodegenHelper;
  217. public:
  218. static char ID; // Pass identification, replacement for typeid
  219. explicit DxilGenerationPass(bool NoOpt = false)
  220. : ModulePass(ID), m_pHLModule(nullptr), NotOptimized(NoOpt), m_extensionsCodegenHelper(nullptr) {}
  221. const char *getPassName() const override { return "DXIL Generator"; }
  222. void SetExtensionsHelper(HLSLExtensionsCodegenHelper *helper) {
  223. m_extensionsCodegenHelper = helper;
  224. }
  225. bool runOnModule(Module &M) override {
  226. m_pHLModule = &M.GetOrCreateHLModule();
  227. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  228. // Load up debug information, to cross-reference values and the instructions
  229. // used to load them.
  230. m_HasDbgInfo = getDebugMetadataVersionFromModule(M) != 0;
  231. if (!SM->IsCS()) {
  232. CreateDxilSignatures();
  233. // Allocate input output.
  234. AllocateDxilInputOutputs();
  235. GenerateDxilInputs();
  236. GenerateDxilOutputs();
  237. } else
  238. GenerateDxilCSInputs();
  239. if (SM->IsDS() || SM->IsHS())
  240. GenerateDxilPatchConstantLdSt();
  241. if (SM->IsHS())
  242. GenerateDxilPatchConstantFunctionInputs();
  243. std::unordered_set<LoadInst *> UpdateCounterSet;
  244. std::unordered_set<Value *> NonUniformSet;
  245. GenerateDxilOperations(M, UpdateCounterSet, NonUniformSet);
  246. std::unordered_map<Instruction *, Value *> handleMap;
  247. GenerateDxilCBufferHandles(NonUniformSet);
  248. GenerateParamDxilResourceHandles(handleMap);
  249. GenerateDxilResourceHandles(UpdateCounterSet, NonUniformSet);
  250. AddCreateHandleForPhiNodeAndSelect(m_pHLModule->GetOP());
  251. // For module which not promote mem2reg.
  252. // Remove local resource alloca/load/store/phi.
  253. for (auto It = M.begin(); It != M.end();) {
  254. Function &F = *(It++);
  255. if (!F.isDeclaration()) {
  256. RemoveLocalDxilResourceAllocas(&F);
  257. if (hlsl::GetHLOpcodeGroupByName(&F) == HLOpcodeGroup::HLCreateHandle) {
  258. if (F.user_empty()) {
  259. F.eraseFromParent();
  260. } else {
  261. M.getContext().emitError("Fail to lower createHandle.");
  262. }
  263. }
  264. }
  265. }
  266. // Translate precise on allocas into function call to keep the information after mem2reg.
  267. // The function calls will be removed after propagate precise attribute.
  268. TranslatePreciseAttribute();
  269. // Change struct type to legacy layout for cbuf and struct buf.
  270. UpdateStructTypeForLegacyLayout();
  271. // High-level metadata should now be turned into low-level metadata.
  272. const bool SkipInit = true;
  273. hlsl::DxilModule &DxilMod = M.GetOrCreateDxilModule(SkipInit);
  274. InitDxilModuleFromHLModule(*m_pHLModule, DxilMod, m_HasDbgInfo);
  275. HLModule::ClearHLMetadata(M);
  276. M.ResetHLModule();
  277. // Remove debug code when not debug info.
  278. if (!m_HasDbgInfo)
  279. DxilMod.StripDebugRelatedCode();
  280. return true;
  281. }
  282. private:
  283. void ProcessArgument(Function *func, DxilFunctionAnnotation *EntryAnnotation, Argument &arg, bool isPatchConstantFunction, bool forceOut, bool &hasClipPlane);
  284. void CreateDxilSignatures();
  285. // Allocate DXIL input/output.
  286. void AllocateDxilInputOutputs();
  287. // generate DXIL input load, output store
  288. void GenerateDxilInputs();
  289. void GenerateDxilOutputs();
  290. void GenerateDxilInputsOutputs(bool bInput);
  291. void GenerateDxilCSInputs();
  292. void GenerateDxilPatchConstantLdSt();
  293. void GenerateDxilPatchConstantFunctionInputs();
  294. void GenerateClipPlanesForVS(Value *outPosition);
  295. bool HasClipPlanes();
  296. void RemoveLocalDxilResourceAllocas(Function *F);
  297. void
  298. TranslateDxilResourceUses(DxilResourceBase &res,
  299. std::unordered_set<LoadInst *> &UpdateCounterSet,
  300. std::unordered_set<Value *> &NonUniformSet);
  301. void
  302. GenerateDxilResourceHandles(std::unordered_set<LoadInst *> &UpdateCounterSet,
  303. std::unordered_set<Value *> &NonUniformSet);
  304. void AddCreateHandleForPhiNodeAndSelect(OP *hlslOP);
  305. void TranslateParamDxilResourceHandles(Function *F, std::unordered_map<Instruction *, Value *> &handleMap);
  306. void GenerateParamDxilResourceHandles(
  307. std::unordered_map<Instruction *, Value *> &handleMap);
  308. // Generate DXIL cbuffer handles.
  309. void
  310. GenerateDxilCBufferHandles(std::unordered_set<Value *> &NonUniformSet);
  311. // Generate DXIL stream output operation.
  312. void GenerateStreamOutputOperation(Value *streamVal, unsigned streamID);
  313. // Generate DXIL stream output operations.
  314. void GenerateStreamOutputOperations();
  315. // change built-in funtion into DXIL operations
  316. void GenerateDxilOperations(Module &M,
  317. std::unordered_set<LoadInst *> &UpdateCounterSet,
  318. std::unordered_set<Value *> &NonUniformSet);
  319. // Change struct type to legacy layout for cbuf and struct buf.
  320. void UpdateStructTypeForLegacyLayout();
  321. // Translate precise attribute into HL function call.
  322. void TranslatePreciseAttribute();
  323. // SignatureElement to Value map.
  324. std::unordered_map<DxilSignatureElement *, Value *> m_sigValueMap;
  325. // Set to save inout arguments.
  326. std::unordered_set<Value *> m_inoutArgSet;
  327. // SignatureElement which has precise attribute.
  328. std::unordered_set<DxilSignatureElement *> m_preciseSigSet;
  329. // Patch constant function inputs to signature element map.
  330. std::unordered_map<unsigned, DxilSignatureElement *> m_patchConstantInputsSigMap;
  331. // Input module is not optimized.
  332. bool NotOptimized;
  333. // For validation
  334. std::unordered_map<unsigned, std::unordered_set<unsigned> > m_InputSemanticsUsed,
  335. m_OutputSemanticsUsed[4], m_PatchConstantSemanticsUsed, m_OtherSemanticsUsed;
  336. };
  337. class SimplifyInst : public FunctionPass {
  338. public:
  339. static char ID;
  340. SimplifyInst() : FunctionPass(ID) {
  341. initializeScalarizerPass(*PassRegistry::getPassRegistry());
  342. }
  343. bool runOnFunction(Function &F) override;
  344. private:
  345. };
  346. }
  347. char SimplifyInst::ID = 0;
  348. FunctionPass *llvm::createSimplifyInstPass() { return new SimplifyInst(); }
  349. INITIALIZE_PASS(SimplifyInst, "simplify-inst", "Simplify Instructions", false, false)
  350. bool SimplifyInst::runOnFunction(Function &F) {
  351. for (Function::iterator BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
  352. BasicBlock *BB = BBI;
  353. llvm::SimplifyInstructionsInBlock(BB, nullptr);
  354. }
  355. return true;
  356. }
  357. // Decompose semantic name (eg FOO1=>FOO,1), change interp mode for SV_Position.
  358. // Return semantic index.
  359. static unsigned UpateSemanticAndInterpMode(StringRef &semName,
  360. DXIL::InterpolationMode &mode,
  361. DXIL::SigPointKind kind,
  362. LLVMContext &Context) {
  363. llvm::StringRef baseSemName; // The 'FOO' in 'FOO1'.
  364. uint32_t semIndex; // The '1' in 'FOO1'
  365. // Split semName and index.
  366. Semantic::DecomposeNameAndIndex(semName, &baseSemName, &semIndex);
  367. semName = baseSemName;
  368. const Semantic *semantic = Semantic::GetByName(semName, kind);
  369. if (semantic && semantic->GetKind() == Semantic::Kind::Position) {
  370. // Update interp mode to no_perspective version for SV_Position.
  371. switch (mode) {
  372. case InterpolationMode::Kind::LinearCentroid:
  373. mode = InterpolationMode::Kind::LinearNoperspectiveCentroid;
  374. break;
  375. case InterpolationMode::Kind::LinearSample:
  376. mode = InterpolationMode::Kind::LinearNoperspectiveSample;
  377. break;
  378. case InterpolationMode::Kind::Linear:
  379. mode = InterpolationMode::Kind::LinearNoperspective;
  380. break;
  381. case InterpolationMode::Kind::Constant: {
  382. Context.emitError("invalid interpolation mode for SV_Position");
  383. } break;
  384. }
  385. }
  386. return semIndex;
  387. }
  388. static DxilSignatureElement *FindArgInSignature(Argument &arg, llvm::StringRef semantic, DXIL::InterpolationMode interpMode, DXIL::SigPointKind kind,
  389. DxilSignature &sig) {
  390. // Match output ID.
  391. unsigned semIndex =
  392. UpateSemanticAndInterpMode(semantic, interpMode, kind, arg.getContext());
  393. for (uint32_t i = 0; i < sig.GetElements().size(); i++) {
  394. DxilSignatureElement &SE = sig.GetElement(i);
  395. bool semNameMatch = semantic.equals_lower(SE.GetName());
  396. bool semIndexMatch = semIndex == SE.GetSemanticIndexVec()[0];
  397. if (semNameMatch && semIndexMatch) {
  398. // Find a match.
  399. return &SE;
  400. }
  401. }
  402. return nullptr;
  403. }
  404. static void replaceInputOutputWithIntrinsic(DXIL::SemanticKind semKind, Value * GV, OP * hlslOP, IRBuilder<>& Builder);
  405. void DxilGenerationPass::ProcessArgument(Function *func,
  406. DxilFunctionAnnotation *funcAnnotation,
  407. Argument &arg,
  408. bool isPatchConstantFunction,
  409. bool forceOut, bool &hasClipPlane) {
  410. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  411. Type *Ty = arg.getType();
  412. DxilParameterAnnotation &paramAnnotation =
  413. funcAnnotation->GetParameterAnnotation(arg.getArgNo());
  414. hlsl::DxilParamInputQual qual =
  415. forceOut ? DxilParamInputQual::Out : paramAnnotation.GetParamInputQual();
  416. bool isInout = qual == DxilParamInputQual::Inout;
  417. // If this was an inout param, do the output side first
  418. if (isInout) {
  419. DXASSERT(!isPatchConstantFunction,
  420. "Patch Constant function should not have inout param");
  421. m_inoutArgSet.insert(&arg);
  422. ProcessArgument(func, funcAnnotation, arg, isPatchConstantFunction,
  423. /*forceOut*/ true, hasClipPlane);
  424. qual = DxilParamInputQual::In;
  425. }
  426. // Get stream index
  427. unsigned streamIdx = 0;
  428. switch (qual) {
  429. case DxilParamInputQual::OutStream1:
  430. streamIdx = 1;
  431. break;
  432. case DxilParamInputQual::OutStream2:
  433. streamIdx = 2;
  434. break;
  435. case DxilParamInputQual::OutStream3:
  436. streamIdx = 3;
  437. break;
  438. default:
  439. // Use streamIdx = 0 by default.
  440. break;
  441. }
  442. const SigPoint *sigPoint = SigPoint::GetSigPoint(
  443. SigPointFromInputQual(qual, SM->GetKind(), isPatchConstantFunction));
  444. unsigned rows, cols;
  445. HLModule::GetParameterRowsAndCols(Ty, rows, cols, paramAnnotation);
  446. CompType EltTy = paramAnnotation.GetCompType();
  447. DXIL::InterpolationMode interpMode =
  448. paramAnnotation.GetInterpolationMode().GetKind();
  449. // Set undefined interpMode.
  450. if (!sigPoint->NeedsInterpMode())
  451. interpMode = InterpolationMode::Kind::Undefined;
  452. else if (interpMode == InterpolationMode::Kind::Undefined) {
  453. // Type-based default: linear for floats, constant for others.
  454. if (EltTy.IsFloatTy())
  455. interpMode = InterpolationMode::Kind::Linear;
  456. else
  457. interpMode = InterpolationMode::Kind::Constant;
  458. }
  459. llvm::StringRef semanticStr = paramAnnotation.GetSemanticString();
  460. if (semanticStr.empty()) {
  461. m_pHLModule->GetModule()->getContext().emitError(
  462. "Semantic must be defined for all parameters of an entry function or "
  463. "patch constant function");
  464. return;
  465. }
  466. UpateSemanticAndInterpMode(semanticStr, interpMode, sigPoint->GetKind(),
  467. arg.getContext());
  468. // Get Semantic interpretation, skipping if not in signature
  469. const Semantic *pSemantic = Semantic::GetByName(semanticStr);
  470. DXIL::SemanticInterpretationKind interpretation =
  471. SigPoint::GetInterpretation(pSemantic->GetKind(), sigPoint->GetKind(),
  472. SM->GetMajor(), SM->GetMinor());
  473. // Verify system value semantics do not overlap.
  474. // Note: Arbitrary are always in the signature and will be verified with a different mechanism.
  475. // For patch constant function, only validate patch constant elements (others already validated on hull function)
  476. if (pSemantic->GetKind() != DXIL::SemanticKind::Arbitrary &&
  477. (!isPatchConstantFunction || (!sigPoint->IsInput() && !sigPoint->IsOutput()))) {
  478. auto &SemanticUseMap = sigPoint->IsInput() ? m_InputSemanticsUsed :
  479. (sigPoint->IsOutput() ? m_OutputSemanticsUsed[streamIdx] :
  480. (sigPoint->IsPatchConstant() ? m_PatchConstantSemanticsUsed : m_OtherSemanticsUsed));
  481. if (SemanticUseMap.count((unsigned)pSemantic->GetKind()) > 0) {
  482. auto &SemanticIndexSet = SemanticUseMap[(unsigned)pSemantic->GetKind()];
  483. for (unsigned idx : paramAnnotation.GetSemanticIndexVec()) {
  484. if (SemanticIndexSet.count(idx) > 0) {
  485. m_pHLModule->GetModule()->getContext().emitError(
  486. Twine("Parameter with semantic ") + semanticStr +
  487. Twine(" has overlapping semantic index at ") + Twine(idx));
  488. return;
  489. }
  490. }
  491. }
  492. auto &SemanticIndexSet = SemanticUseMap[(unsigned)pSemantic->GetKind()];
  493. for (unsigned idx : paramAnnotation.GetSemanticIndexVec()) {
  494. SemanticIndexSet.emplace(idx);
  495. }
  496. // Enforce Coverage and InnerCoverage input mutual exclusivity
  497. if (sigPoint->IsInput()) {
  498. if ((pSemantic->GetKind() == DXIL::SemanticKind::Coverage && SemanticUseMap.count((unsigned)DXIL::SemanticKind::InnerCoverage) > 0) ||
  499. (pSemantic->GetKind() == DXIL::SemanticKind::InnerCoverage && SemanticUseMap.count((unsigned)DXIL::SemanticKind::Coverage) > 0)) {
  500. m_pHLModule->GetModule()->getContext().emitError(
  501. "Pixel shader inputs SV_Coverage and SV_InnerCoverage are mutually exclusive");
  502. return;
  503. }
  504. }
  505. }
  506. // Validate interpretation and replace argument usage with load/store
  507. // intrinsics
  508. {
  509. switch (interpretation) {
  510. case DXIL::SemanticInterpretationKind::NA:
  511. m_pHLModule->GetModule()->getContext().emitError(
  512. Twine("Semantic ") + semanticStr +
  513. Twine(" is invalid for shader model: ") + SM->GetKindName());
  514. return;
  515. case DXIL::SemanticInterpretationKind::NotInSig:
  516. case DXIL::SemanticInterpretationKind::Shadow: {
  517. IRBuilder<> funcBuilder(func->getEntryBlock().getFirstInsertionPt());
  518. if (DbgDeclareInst *DDI = llvm::FindAllocaDbgDeclare(&arg)) {
  519. funcBuilder.SetCurrentDebugLocation(DDI->getDebugLoc());
  520. }
  521. replaceInputOutputWithIntrinsic(pSemantic->GetKind(), &arg,
  522. m_pHLModule->GetOP(), funcBuilder);
  523. if (interpretation == DXIL::SemanticInterpretationKind::NotInSig)
  524. return; // This argument should not be included in the signature
  525. break;
  526. }
  527. case DXIL::SemanticInterpretationKind::SV:
  528. case DXIL::SemanticInterpretationKind::SGV:
  529. case DXIL::SemanticInterpretationKind::Arb:
  530. case DXIL::SemanticInterpretationKind::Target:
  531. case DXIL::SemanticInterpretationKind::TessFactor:
  532. case DXIL::SemanticInterpretationKind::NotPacked:
  533. // Will be replaced with load/store intrinsics in
  534. // GenerateDxilInputsOutputs
  535. break;
  536. default:
  537. DXASSERT(false, "Unexpected SemanticInterpretationKind");
  538. return;
  539. }
  540. }
  541. // Determine signature this argument belongs in, if any
  542. DxilSignature *pSig = nullptr;
  543. DXIL::SignatureKind sigKind = sigPoint->GetSignatureKindWithFallback();
  544. switch (sigKind) {
  545. case DXIL::SignatureKind::Input:
  546. pSig = &m_pHLModule->GetInputSignature();
  547. break;
  548. case DXIL::SignatureKind::Output:
  549. pSig = &m_pHLModule->GetOutputSignature();
  550. break;
  551. case DXIL::SignatureKind::PatchConstant:
  552. pSig = &m_pHLModule->GetPatchConstantSignature();
  553. break;
  554. default:
  555. DXASSERT(false, "Expected real signature kind at this point");
  556. return; // No corresponding signature
  557. }
  558. // Create and add element to signature
  559. DxilSignatureElement *pSE = nullptr;
  560. {
  561. // Add signature element to appropriate maps
  562. if (isPatchConstantFunction &&
  563. sigKind != DXIL::SignatureKind::PatchConstant) {
  564. pSE = FindArgInSignature(arg, paramAnnotation.GetSemanticString(),
  565. interpMode, sigPoint->GetKind(), *pSig);
  566. if (!pSE) {
  567. m_pHLModule->GetModule()->getContext().emitError(
  568. Twine("Signature element ") + semanticStr +
  569. Twine(", referred to by patch constant function, is not found in corresponding hull shader ") +
  570. (sigKind == DXIL::SignatureKind::Input ? "input." : "output."));
  571. return;
  572. }
  573. m_patchConstantInputsSigMap[arg.getArgNo()] = pSE;
  574. } else {
  575. std::unique_ptr<DxilSignatureElement> SE = pSig->CreateElement();
  576. pSE = SE.get();
  577. pSig->AppendElement(std::move(SE));
  578. pSE->SetSigPointKind(sigPoint->GetKind());
  579. pSE->Initialize(semanticStr, EltTy, interpMode, rows, cols,
  580. Semantic::kUndefinedRow, Semantic::kUndefinedCol,
  581. pSE->GetID(), paramAnnotation.GetSemanticIndexVec());
  582. m_sigValueMap[pSE] = &arg;
  583. }
  584. }
  585. if (paramAnnotation.IsPrecise())
  586. m_preciseSigSet.insert(pSE);
  587. if (sigKind == DXIL::SignatureKind::Output &&
  588. pSemantic->GetKind() == Semantic::Kind::Position && hasClipPlane) {
  589. GenerateClipPlanesForVS(&arg);
  590. hasClipPlane = false;
  591. }
  592. // Set Output Stream.
  593. if (streamIdx > 0)
  594. pSE->SetOutputStream(streamIdx);
  595. }
  596. void DxilGenerationPass::CreateDxilSignatures() {
  597. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  598. Function *EntryFunc = m_pHLModule->GetEntryFunction();
  599. DXASSERT(EntryFunc->getReturnType()->isVoidTy(), "Should changed in SROA_Parameter_HLSL");
  600. DxilFunctionAnnotation *EntryAnnotation = m_pHLModule->GetFunctionAnnotation(EntryFunc);
  601. DXASSERT(EntryAnnotation, "must have function annotation for entry function");
  602. bool bHasClipPlane = SM->IsVS() ? HasClipPlanes() : false;
  603. for (Argument &arg : EntryFunc->getArgumentList()) {
  604. Type *Ty = arg.getType();
  605. // Skip streamout obj.
  606. if (HLModule::IsStreamOutputPtrType(Ty))
  607. continue;
  608. ProcessArgument(EntryFunc, EntryAnnotation, arg, /*isPatchConstantFunction*/false, /*forceOut*/false, bHasClipPlane);
  609. }
  610. if (bHasClipPlane) {
  611. EntryFunc->getContext().emitError("Cannot use clipplanes attribute without "
  612. "specifying a 4-component SV_Position "
  613. "output");
  614. }
  615. m_OtherSemanticsUsed.clear();
  616. if (SM->IsHS()) {
  617. HLFunctionProps &EntryProps = m_pHLModule->GetHLFunctionProps(EntryFunc);
  618. Function *patchConstantFunc = EntryProps.ShaderProps.HS.patchConstantFunc;
  619. if (patchConstantFunc == nullptr) {
  620. EntryFunc->getContext().emitError("Patch constant function is not specified.");
  621. }
  622. DxilFunctionAnnotation *patchFuncAnnotation = m_pHLModule->GetFunctionAnnotation(patchConstantFunc);
  623. DXASSERT(patchFuncAnnotation, "must have function annotation for patch constant function");
  624. for (Argument &arg : patchConstantFunc->getArgumentList()) {
  625. ProcessArgument(patchConstantFunc, patchFuncAnnotation, arg, /*isPatchConstantFunction*/true, /*forceOut*/false, bHasClipPlane);
  626. }
  627. }
  628. }
  629. // Allocate input/output slots
  630. void DxilGenerationPass::AllocateDxilInputOutputs() {
  631. const HLOptions &opts = m_pHLModule->GetHLOptions();
  632. DXASSERT_NOMSG(opts.PackingStrategy < (unsigned)DXIL::PackingStrategy::Invalid);
  633. DXIL::PackingStrategy packing = (DXIL::PackingStrategy)opts.PackingStrategy;
  634. if (packing == DXIL::PackingStrategy::Default)
  635. packing = m_pHLModule->GetShaderModel()->GetDefaultPackingStrategy();
  636. m_pHLModule->GetInputSignature().PackElements(packing);
  637. if (!m_pHLModule->GetInputSignature().IsFullyAllocated()) {
  638. m_pHLModule->GetCtx().emitError("Failed to allocate all input signature elements in available space.");
  639. }
  640. m_pHLModule->GetOutputSignature().PackElements(packing);
  641. if (!m_pHLModule->GetOutputSignature().IsFullyAllocated()) {
  642. m_pHLModule->GetCtx().emitError("Failed to allocate all output signature elements in available space.");
  643. }
  644. if (m_pHLModule->GetShaderModel()->IsHS() ||
  645. m_pHLModule->GetShaderModel()->IsDS()) {
  646. m_pHLModule->GetPatchConstantSignature().PackElements(packing);
  647. if (!m_pHLModule->GetPatchConstantSignature().IsFullyAllocated()) {
  648. m_pHLModule->GetCtx().emitError("Failed to allocate all patch constant signature elements in available space.");
  649. }
  650. }
  651. }
  652. void DxilGenerationPass::GenerateDxilInputs() {
  653. GenerateDxilInputsOutputs(/*bInput*/ true);
  654. }
  655. void DxilGenerationPass::GenerateDxilOutputs() {
  656. GenerateDxilInputsOutputs(/*bInput*/ false);
  657. }
  658. static void GenerateStOutput(Function *stOutput, MutableArrayRef<Value *> args,
  659. IRBuilder<> &Builder, bool cast) {
  660. if (cast) {
  661. Value *value = args[DXIL::OperandIndex::kStoreOutputValOpIdx];
  662. args[DXIL::OperandIndex::kStoreOutputValOpIdx] =
  663. Builder.CreateZExt(value, Builder.getInt32Ty());
  664. }
  665. Builder.CreateCall(stOutput, args);
  666. }
  667. static void replaceStWithStOutput(Function *stOutput, StoreInst *stInst,
  668. Constant *OpArg, Constant *outputID,
  669. Value *idx, unsigned cols, bool bI1Cast) {
  670. IRBuilder<> Builder(stInst);
  671. Value *val = stInst->getValueOperand();
  672. if (VectorType *VT = dyn_cast<VectorType>(val->getType())) {
  673. DXASSERT(cols == VT->getNumElements(), "vec size must match");
  674. for (unsigned col = 0; col < cols; col++) {
  675. Value *subVal = Builder.CreateExtractElement(val, col);
  676. Value *colIdx = Builder.getInt8(col);
  677. Value *args[] = {OpArg, outputID, idx, colIdx, subVal};
  678. GenerateStOutput(stOutput, args, Builder, bI1Cast);
  679. }
  680. // remove stInst
  681. stInst->eraseFromParent();
  682. } else if (!val->getType()->isArrayTy()) {
  683. // TODO: support case cols not 1
  684. DXASSERT(cols == 1, "only support scalar here");
  685. Value *colIdx = Builder.getInt8(0);
  686. Value *args[] = {OpArg, outputID, idx, colIdx, val};
  687. GenerateStOutput(stOutput, args, Builder, bI1Cast);
  688. // remove stInst
  689. stInst->eraseFromParent();
  690. } else {
  691. DXASSERT(0, "not support array yet");
  692. // TODO: support array.
  693. Value *colIdx = Builder.getInt8(0);
  694. ArrayType *AT = cast<ArrayType>(val->getType());
  695. Value *args[] = {OpArg, outputID, idx, colIdx, /*val*/nullptr};
  696. args;
  697. AT;
  698. }
  699. }
  700. static Value *GenerateLdInput(Function *loadInput, ArrayRef<Value *> args,
  701. IRBuilder<> &Builder, Value *zero, bool bCast, Type *Ty) {
  702. Value *input = Builder.CreateCall(loadInput, args);
  703. if (!bCast)
  704. return input;
  705. else {
  706. Value *bVal = Builder.CreateICmpNE(input, zero);
  707. IntegerType *IT = cast<IntegerType>(Ty);
  708. if (IT->getBitWidth() == 1)
  709. return bVal;
  710. else
  711. return Builder.CreateZExt(bVal, Ty);
  712. }
  713. }
  714. static Value *replaceLdWithLdInput(Function *loadInput,
  715. LoadInst *ldInst,
  716. unsigned cols,
  717. MutableArrayRef<Value *>args,
  718. bool bCast) {
  719. IRBuilder<> Builder(ldInst);
  720. Type *Ty = ldInst->getType();
  721. Type *EltTy = Ty->getScalarType();
  722. // Change i1 to i32 for load input.
  723. Value *zero = Builder.getInt32(0);
  724. if (VectorType *VT = dyn_cast<VectorType>(Ty)) {
  725. Value *newVec = llvm::UndefValue::get(VT);
  726. DXASSERT(cols == VT->getNumElements(), "vec size must match");
  727. for (unsigned col = 0; col < cols; col++) {
  728. Value *colIdx = Builder.getInt8(col);
  729. args[DXIL::OperandIndex::kLoadInputColOpIdx] = colIdx;
  730. Value *input = GenerateLdInput(loadInput, args, Builder, zero, bCast, EltTy);
  731. newVec = Builder.CreateInsertElement(newVec, input, col);
  732. }
  733. ldInst->replaceAllUsesWith(newVec);
  734. ldInst->eraseFromParent();
  735. return newVec;
  736. } else {
  737. Value *colIdx = args[DXIL::OperandIndex::kLoadInputColOpIdx];
  738. if (colIdx == nullptr) {
  739. DXASSERT(cols == 1, "only support scalar here");
  740. colIdx = Builder.getInt8(0);
  741. } else {
  742. if (colIdx->getType() == Builder.getInt32Ty()) {
  743. colIdx = Builder.CreateTrunc(colIdx, Builder.getInt8Ty());
  744. }
  745. }
  746. if (isa<ConstantInt>(colIdx)) {
  747. args[DXIL::OperandIndex::kLoadInputColOpIdx] = colIdx;
  748. Value *input = GenerateLdInput(loadInput, args, Builder, zero, bCast, EltTy);
  749. ldInst->replaceAllUsesWith(input);
  750. ldInst->eraseFromParent();
  751. return input;
  752. }
  753. else {
  754. // Vector indexing.
  755. // Load to array.
  756. ArrayType *AT = ArrayType::get(ldInst->getType(), cols);
  757. Value *arrayVec = Builder.CreateAlloca(AT);
  758. Value *zeroIdx = Builder.getInt32(0);
  759. for (unsigned col = 0; col < cols; col++) {
  760. Value *colIdx = Builder.getInt8(col);
  761. args[DXIL::OperandIndex::kLoadInputColOpIdx] = colIdx;
  762. Value *input = GenerateLdInput(loadInput, args, Builder, zero, bCast, EltTy);
  763. Value *GEP = Builder.CreateInBoundsGEP(arrayVec, {zeroIdx, colIdx});
  764. Builder.CreateStore(input, GEP);
  765. }
  766. Value *vecIndexingPtr = Builder.CreateInBoundsGEP(arrayVec, {zeroIdx, colIdx});
  767. Value *input = Builder.CreateLoad(vecIndexingPtr);
  768. ldInst->replaceAllUsesWith(input);
  769. ldInst->eraseFromParent();
  770. return input;
  771. }
  772. }
  773. }
  774. static void replaceDirectInputParameter(Value *param, Function *loadInput,
  775. unsigned cols,
  776. MutableArrayRef<Value *>args, bool bCast,
  777. OP *hlslOP, IRBuilder<> &Builder) {
  778. Value *zero = hlslOP->GetU32Const(0);
  779. Type *Ty = param->getType();
  780. Type *EltTy = Ty->getScalarType();
  781. if (VectorType *VT = dyn_cast<VectorType>(Ty)) {
  782. Value *newVec = llvm::UndefValue::get(VT);
  783. DXASSERT(cols == VT->getNumElements(), "vec size must match");
  784. for (unsigned col = 0; col < cols; col++) {
  785. Value *colIdx = hlslOP->GetU8Const(col);
  786. args[DXIL::OperandIndex::kLoadInputColOpIdx] = colIdx;
  787. Value *input = GenerateLdInput(loadInput, args, Builder, zero, bCast, EltTy);
  788. newVec = Builder.CreateInsertElement(newVec, input, col);
  789. }
  790. param->replaceAllUsesWith(newVec);
  791. } else if (!Ty->isArrayTy() && !HLMatrixLower::IsMatrixType(Ty)) {
  792. DXASSERT(cols == 1, "only support scalar here");
  793. Value *colIdx = hlslOP->GetU8Const(0);
  794. args[DXIL::OperandIndex::kLoadInputColOpIdx] = colIdx;
  795. Value *input = GenerateLdInput(loadInput, args, Builder, zero, bCast, EltTy);
  796. param->replaceAllUsesWith(input);
  797. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  798. Value *colIdx = hlslOP->GetU8Const(0);
  799. colIdx;
  800. DXASSERT(param->hasOneUse(), "matrix arg should only has one use as matrix to vec");
  801. CallInst *CI = cast<CallInst>(param->user_back());
  802. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  803. DXASSERT_LOCALVAR(group, group == HLOpcodeGroup::HLCast, "must be hlcast here");
  804. unsigned opcode = GetHLOpcode(CI);
  805. HLCastOpcode matOp = static_cast<HLCastOpcode>(opcode);
  806. switch (matOp) {
  807. case HLCastOpcode::ColMatrixToVecCast: {
  808. IRBuilder<> LocalBuilder(CI);
  809. Type *matTy = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx)
  810. ->getType();
  811. unsigned col, row;
  812. Type *EltTy = HLMatrixLower::GetMatrixInfo(matTy, col, row);
  813. std::vector<Value *> matElts(col * row);
  814. for (unsigned c = 0; c < col; c++) {
  815. Value *rowIdx = hlslOP->GetI32Const(c);
  816. args[DXIL::OperandIndex::kLoadInputRowOpIdx] = rowIdx;
  817. for (unsigned r = 0; r < row; r++) {
  818. Value *colIdx = hlslOP->GetU8Const(r);
  819. args[DXIL::OperandIndex::kLoadInputColOpIdx] = colIdx;
  820. Value *input = GenerateLdInput(loadInput, args, Builder, zero, bCast, EltTy);
  821. unsigned matIdx = c * row + r;
  822. matElts[matIdx] = input;
  823. }
  824. }
  825. Value *newVec =
  826. HLMatrixLower::BuildVector(EltTy, col * row, matElts, LocalBuilder);
  827. CI->replaceAllUsesWith(newVec);
  828. CI->eraseFromParent();
  829. } break;
  830. case HLCastOpcode::RowMatrixToVecCast: {
  831. IRBuilder<> LocalBuilder(CI);
  832. Type *matTy = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx)
  833. ->getType();
  834. unsigned col, row;
  835. Type *EltTy = HLMatrixLower::GetMatrixInfo(matTy, col, row);
  836. std::vector<Value *> matElts(col * row);
  837. for (unsigned r = 0; r < row; r++) {
  838. Value *rowIdx = hlslOP->GetI32Const(r);
  839. args[DXIL::OperandIndex::kLoadInputRowOpIdx] = rowIdx;
  840. for (unsigned c = 0; c < col; c++) {
  841. Value *colIdx = hlslOP->GetU8Const(c);
  842. args[DXIL::OperandIndex::kLoadInputColOpIdx] = colIdx;
  843. Value *input = GenerateLdInput(loadInput, args, Builder, zero, bCast, EltTy);
  844. unsigned matIdx = r * col + c;
  845. matElts[matIdx] = input;
  846. }
  847. }
  848. Value *newVec =
  849. HLMatrixLower::BuildVector(EltTy, col * row, matElts, LocalBuilder);
  850. CI->replaceAllUsesWith(newVec);
  851. CI->eraseFromParent();
  852. } break;
  853. }
  854. } else {
  855. DXASSERT(0, "invalid type for direct input");
  856. }
  857. }
  858. namespace {
  859. struct InputOutputAccessInfo {
  860. // For input output which has only 1 row, idx is 0.
  861. Value *idx;
  862. // VertexID for HS/DS/GS input.
  863. Value *vertexID;
  864. // Vector index.
  865. Value *vectorIdx;
  866. // Load/Store/LoadMat/StoreMat on input/output.
  867. Instruction *user;
  868. InputOutputAccessInfo(Value *index, Instruction *I)
  869. : idx(index), user(I), vertexID(nullptr), vectorIdx(nullptr) {}
  870. InputOutputAccessInfo(Value *index, Instruction *I, Value *ID, Value *vecIdx)
  871. : idx(index), user(I), vertexID(ID), vectorIdx(vecIdx) {}
  872. };
  873. }
  874. static void collectInputOutputAccessInfo(Value *GV, Constant *constZero,
  875. std::vector<InputOutputAccessInfo> &accessInfoList,
  876. bool hasVertexID, bool bInput) {
  877. auto User = GV->user_begin();
  878. auto UserE = GV->user_end();
  879. for (; User != UserE;) {
  880. Value *I = *(User++);
  881. if (LoadInst *ldInst = dyn_cast<LoadInst>(I)) {
  882. if (bInput) {
  883. InputOutputAccessInfo info = {constZero, ldInst};
  884. accessInfoList.push_back(info);
  885. }
  886. } else if (StoreInst *stInst = dyn_cast<StoreInst>(I)) {
  887. if (!bInput) {
  888. InputOutputAccessInfo info = {constZero, stInst};
  889. accessInfoList.push_back(info);
  890. }
  891. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
  892. // Vector indexing may has more indices.
  893. // Vector indexing changed to array indexing in SROA_HLSL.
  894. auto idx = GEP->idx_begin();
  895. DXASSERT_LOCALVAR(idx, idx->get() == constZero,
  896. "only support 0 offset for input pointer");
  897. Value *vertexID = nullptr;
  898. Value *vectorIdx = nullptr;
  899. gep_type_iterator GEPIt = gep_type_begin(GEP), E = gep_type_end(GEP);
  900. // Skip first pointer idx which must be 0.
  901. GEPIt++;
  902. if (hasVertexID) {
  903. // Save vertexID.
  904. vertexID = GEPIt.getOperand();
  905. GEPIt++;
  906. }
  907. // Start from first index.
  908. Value *rowIdx = GEPIt.getOperand();
  909. if (GEPIt != E) {
  910. if ((*GEPIt)->isVectorTy()) {
  911. // Vector indexing.
  912. rowIdx = constZero;
  913. vectorIdx = GEPIt.getOperand();
  914. DXASSERT_NOMSG((++GEPIt) == E);
  915. } else {
  916. // Array which may have vector indexing.
  917. GEPIt++;
  918. IRBuilder<> Builder(GEP);
  919. Type *idxTy = rowIdx->getType();
  920. for (; GEPIt != E; ++GEPIt) {
  921. DXASSERT(!GEPIt->isStructTy(),
  922. "Struct should be flattened SROA_Parameter_HLSL");
  923. DXASSERT(!GEPIt->isPointerTy(),
  924. "not support pointer type in middle of GEP");
  925. if (GEPIt->isArrayTy()) {
  926. Constant *arraySize =
  927. ConstantInt::get(idxTy, GEPIt->getArrayNumElements());
  928. rowIdx = Builder.CreateMul(rowIdx, arraySize);
  929. rowIdx = Builder.CreateAdd(rowIdx, GEPIt.getOperand());
  930. } else {
  931. Type *Ty = *GEPIt;
  932. DXASSERT_LOCALVAR(Ty, Ty->isVectorTy(),
  933. "must be vector type here to index");
  934. // Save vector idx.
  935. vectorIdx = GEPIt.getOperand();
  936. }
  937. }
  938. }
  939. } else
  940. rowIdx = constZero;
  941. auto GepUser = GEP->user_begin();
  942. auto GepUserE = GEP->user_end();
  943. Value *idxVal = rowIdx;
  944. for (; GepUser != GepUserE;) {
  945. auto GepUserIt = GepUser++;
  946. if (LoadInst *ldInst = dyn_cast<LoadInst>(*GepUserIt)) {
  947. if (bInput) {
  948. InputOutputAccessInfo info = {idxVal, ldInst, vertexID, vectorIdx};
  949. accessInfoList.push_back(info);
  950. }
  951. } else if (StoreInst *stInst = dyn_cast<StoreInst>(*GepUserIt)) {
  952. if (!bInput) {
  953. InputOutputAccessInfo info = {idxVal, stInst, vertexID, vectorIdx};
  954. accessInfoList.push_back(info);
  955. }
  956. } else if (CallInst *CI = dyn_cast<CallInst>(*GepUserIt)) {
  957. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  958. DXASSERT_LOCALVAR(group, group == HLOpcodeGroup::HLMatLoadStore,
  959. "input/output should only used by ld/st");
  960. HLMatLoadStoreOpcode opcode = (HLMatLoadStoreOpcode)GetHLOpcode(CI);
  961. if ((opcode == HLMatLoadStoreOpcode::ColMatLoad || opcode == HLMatLoadStoreOpcode::RowMatLoad) ? bInput : !bInput) {
  962. InputOutputAccessInfo info = {idxVal, CI, vertexID, vectorIdx};
  963. accessInfoList.push_back(info);
  964. }
  965. } else
  966. DXASSERT(0, "input output should only used by ld/st");
  967. }
  968. } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
  969. InputOutputAccessInfo info = {constZero, CI};
  970. accessInfoList.push_back(info);
  971. } else
  972. DXASSERT(0, "input output should only used by ld/st");
  973. }
  974. }
  975. static void replaceInputOutputWithIntrinsic(DXIL::SemanticKind semKind, Value *GV, OP *hlslOP, IRBuilder<> &Builder) {
  976. Type *Ty = GV->getType();
  977. if (Ty->isPointerTy())
  978. Ty = Ty->getPointerElementType();
  979. OP::OpCode opcode;
  980. switch (semKind) {
  981. case Semantic::Kind::DomainLocation: opcode = OP::OpCode::DomainLocation; break;
  982. case Semantic::Kind::OutputControlPointID: opcode = OP::OpCode::OutputControlPointID; break;
  983. case Semantic::Kind::GSInstanceID: opcode = OP::OpCode::GSInstanceID; break;
  984. case Semantic::Kind::PrimitiveID: opcode = OP::OpCode::PrimitiveID; break;
  985. case Semantic::Kind::SampleIndex: opcode = OP::OpCode::SampleIndex; break;
  986. case Semantic::Kind::Coverage: opcode = OP::OpCode::Coverage; break;
  987. case Semantic::Kind::InnerCoverage: opcode = OP::OpCode::InnerCoverage; break;
  988. case Semantic::Kind::ViewID: opcode = OP::OpCode::ViewID; break;
  989. default:
  990. DXASSERT(0, "invalid semantic");
  991. return;
  992. }
  993. Function *dxilFunc = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  994. Constant *OpArg = hlslOP->GetU32Const((unsigned)opcode);
  995. Value *newArg = nullptr;
  996. if (semKind == Semantic::Kind::DomainLocation) {
  997. unsigned vecSize = 1;
  998. if (Ty->isVectorTy())
  999. vecSize = Ty->getVectorNumElements();
  1000. newArg = Builder.CreateCall(dxilFunc, {OpArg, hlslOP->GetU8Const(0)});
  1001. if (vecSize > 1) {
  1002. Value *result = UndefValue::get(Ty);
  1003. result = Builder.CreateInsertElement(result, newArg, (uint64_t)0);
  1004. for (unsigned i = 1; i < vecSize; i++) {
  1005. Value *newElt =
  1006. Builder.CreateCall(dxilFunc, {OpArg, hlslOP->GetU8Const(i)});
  1007. result = Builder.CreateInsertElement(result, newElt, i);
  1008. }
  1009. newArg = result;
  1010. }
  1011. } else {
  1012. newArg = Builder.CreateCall(dxilFunc, {OpArg});
  1013. }
  1014. if (newArg->getType() != GV->getType()) {
  1015. DXASSERT_NOMSG(GV->getType()->isPointerTy());
  1016. for (User *U : GV->users()) {
  1017. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  1018. LI->replaceAllUsesWith(newArg);
  1019. }
  1020. }
  1021. } else {
  1022. GV->replaceAllUsesWith(newArg);
  1023. }
  1024. }
  1025. void GenerateInputOutputUserCall(InputOutputAccessInfo &info, Value *undefVertexIdx,
  1026. Function *ldStFunc, Constant *OpArg, Constant *ID, unsigned cols, bool bI1Cast,
  1027. Constant *columnConsts[],
  1028. bool bNeedVertexID, bool isArrayTy, bool bInput, bool bIsInout) {
  1029. Value *idxVal = info.idx;
  1030. Value *vertexID = undefVertexIdx;
  1031. if (bNeedVertexID && isArrayTy) {
  1032. vertexID = info.vertexID;
  1033. }
  1034. if (LoadInst *ldInst = dyn_cast<LoadInst>(info.user)) {
  1035. SmallVector<Value *, 4> args = {OpArg, ID, idxVal, info.vectorIdx};
  1036. if (vertexID)
  1037. args.emplace_back(vertexID);
  1038. replaceLdWithLdInput(ldStFunc, ldInst, cols, args, bI1Cast);
  1039. } else if (StoreInst *stInst = dyn_cast<StoreInst>(info.user)) {
  1040. if (bInput) {
  1041. DXASSERT_LOCALVAR(bIsInout, bIsInout, "input should not have store use.");
  1042. } else {
  1043. if (!info.vectorIdx) {
  1044. replaceStWithStOutput(ldStFunc, stInst, OpArg, ID, idxVal, cols,
  1045. bI1Cast);
  1046. } else {
  1047. Value *V = stInst->getValueOperand();
  1048. Type *Ty = V->getType();
  1049. DXASSERT(Ty == Ty->getScalarType() && !Ty->isAggregateType(),
  1050. "only support scalar here");
  1051. if (ConstantInt *ColIdx = dyn_cast<ConstantInt>(info.vectorIdx)) {
  1052. IRBuilder<> Builder(stInst);
  1053. if (ColIdx->getType()->getBitWidth() != 8) {
  1054. ColIdx = Builder.getInt8(ColIdx->getValue().getLimitedValue());
  1055. }
  1056. Value *args[] = {OpArg, ID, idxVal, ColIdx, V};
  1057. GenerateStOutput(ldStFunc, args, Builder, bI1Cast);
  1058. } else {
  1059. BasicBlock *BB = stInst->getParent();
  1060. BasicBlock *EndBB = BB->splitBasicBlock(stInst);
  1061. TerminatorInst *TI = BB->getTerminator();
  1062. IRBuilder<> SwitchBuilder(TI);
  1063. LLVMContext &Ctx = stInst->getContext();
  1064. SwitchInst *Switch =
  1065. SwitchBuilder.CreateSwitch(info.vectorIdx, EndBB, cols);
  1066. TI->eraseFromParent();
  1067. Function *F = EndBB->getParent();
  1068. for (unsigned i = 0; i < cols; i++) {
  1069. BasicBlock *CaseBB = BasicBlock::Create(Ctx, "case", F, EndBB);
  1070. Switch->addCase(SwitchBuilder.getInt32(i), CaseBB);
  1071. IRBuilder<> CaseBuilder(CaseBB);
  1072. ConstantInt *CaseIdx = SwitchBuilder.getInt8(i);
  1073. Value *args[] = {OpArg, ID, idxVal, CaseIdx, V};
  1074. GenerateStOutput(ldStFunc, args, CaseBuilder, bI1Cast);
  1075. CaseBuilder.CreateBr(EndBB);
  1076. }
  1077. }
  1078. // remove stInst
  1079. stInst->eraseFromParent();
  1080. }
  1081. }
  1082. } else if (CallInst *CI = dyn_cast<CallInst>(info.user)) {
  1083. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  1084. // Intrinsic will be translated later.
  1085. if (group == HLOpcodeGroup::HLIntrinsic)
  1086. return;
  1087. unsigned opcode = GetHLOpcode(CI);
  1088. DXASSERT(group == HLOpcodeGroup::HLMatLoadStore, "");
  1089. HLMatLoadStoreOpcode matOp = static_cast<HLMatLoadStoreOpcode>(opcode);
  1090. switch (matOp) {
  1091. case HLMatLoadStoreOpcode::ColMatLoad: {
  1092. IRBuilder<> LocalBuilder(CI);
  1093. Type *matTy = CI->getArgOperand(HLOperandIndex::kMatLoadPtrOpIdx)
  1094. ->getType()
  1095. ->getPointerElementType();
  1096. unsigned col, row;
  1097. Type *EltTy = HLMatrixLower::GetMatrixInfo(matTy, col, row);
  1098. std::vector<Value *> matElts(col * row);
  1099. for (unsigned c = 0; c < col; c++) {
  1100. Constant *constRowIdx = LocalBuilder.getInt32(c);
  1101. Value *rowIdx = LocalBuilder.CreateAdd(idxVal, constRowIdx);
  1102. for (unsigned r = 0; r < row; r++) {
  1103. SmallVector<Value *, 4> args = {OpArg, ID, rowIdx, columnConsts[r]};
  1104. if (vertexID)
  1105. args.emplace_back(vertexID);
  1106. Value *input = LocalBuilder.CreateCall(ldStFunc, args);
  1107. unsigned matIdx = c * row + r;
  1108. matElts[matIdx] = input;
  1109. }
  1110. }
  1111. Value *newVec =
  1112. HLMatrixLower::BuildVector(EltTy, col * row, matElts, LocalBuilder);
  1113. CI->replaceAllUsesWith(newVec);
  1114. CI->eraseFromParent();
  1115. } break;
  1116. case HLMatLoadStoreOpcode::RowMatLoad: {
  1117. IRBuilder<> LocalBuilder(CI);
  1118. Type *matTy = CI->getArgOperand(HLOperandIndex::kMatLoadPtrOpIdx)
  1119. ->getType()
  1120. ->getPointerElementType();
  1121. unsigned col, row;
  1122. Type *EltTy = HLMatrixLower::GetMatrixInfo(matTy, col, row);
  1123. std::vector<Value *> matElts(col * row);
  1124. for (unsigned r = 0; r < row; r++) {
  1125. Constant *constRowIdx = LocalBuilder.getInt32(r);
  1126. Value *rowIdx = LocalBuilder.CreateAdd(idxVal, constRowIdx);
  1127. for (unsigned c = 0; c < col; c++) {
  1128. SmallVector<Value *, 4> args = {OpArg, ID, rowIdx, columnConsts[c]};
  1129. if (vertexID)
  1130. args.emplace_back(vertexID);
  1131. Value *input = LocalBuilder.CreateCall(ldStFunc, args);
  1132. unsigned matIdx = r * col + c;
  1133. matElts[matIdx] = input;
  1134. }
  1135. }
  1136. Value *newVec =
  1137. HLMatrixLower::BuildVector(EltTy, col * row, matElts, LocalBuilder);
  1138. CI->replaceAllUsesWith(newVec);
  1139. CI->eraseFromParent();
  1140. } break;
  1141. case HLMatLoadStoreOpcode::ColMatStore: {
  1142. IRBuilder<> LocalBuilder(CI);
  1143. Value *Val = CI->getArgOperand(HLOperandIndex::kMatStoreValOpIdx);
  1144. Type *matTy = CI->getArgOperand(HLOperandIndex::kMatStoreDstPtrOpIdx)
  1145. ->getType()
  1146. ->getPointerElementType();
  1147. unsigned col, row;
  1148. HLMatrixLower::GetMatrixInfo(matTy, col, row);
  1149. for (unsigned c = 0; c < col; c++) {
  1150. Constant *constColIdx = LocalBuilder.getInt32(c);
  1151. Value *colIdx = LocalBuilder.CreateAdd(idxVal, constColIdx);
  1152. for (unsigned r = 0; r < row; r++) {
  1153. unsigned matIdx = HLMatrixLower::GetColMajorIdx(r, c, row);
  1154. Value *Elt = LocalBuilder.CreateExtractElement(Val, matIdx);
  1155. LocalBuilder.CreateCall(ldStFunc,
  1156. {OpArg, ID, colIdx, columnConsts[r], Elt});
  1157. }
  1158. }
  1159. CI->eraseFromParent();
  1160. } break;
  1161. case HLMatLoadStoreOpcode::RowMatStore: {
  1162. IRBuilder<> LocalBuilder(CI);
  1163. Value *Val = CI->getArgOperand(HLOperandIndex::kMatStoreValOpIdx);
  1164. Type *matTy = CI->getArgOperand(HLOperandIndex::kMatStoreDstPtrOpIdx)
  1165. ->getType()
  1166. ->getPointerElementType();
  1167. unsigned col, row;
  1168. HLMatrixLower::GetMatrixInfo(matTy, col, row);
  1169. for (unsigned r = 0; r < row; r++) {
  1170. Constant *constRowIdx = LocalBuilder.getInt32(r);
  1171. Value *rowIdx = LocalBuilder.CreateAdd(idxVal, constRowIdx);
  1172. for (unsigned c = 0; c < col; c++) {
  1173. unsigned matIdx = HLMatrixLower::GetRowMajorIdx(r, c, col);
  1174. Value *Elt = LocalBuilder.CreateExtractElement(Val, matIdx);
  1175. LocalBuilder.CreateCall(ldStFunc,
  1176. {OpArg, ID, rowIdx, columnConsts[c], Elt});
  1177. }
  1178. }
  1179. CI->eraseFromParent();
  1180. } break;
  1181. }
  1182. } else
  1183. DXASSERT(0, "invalid operation on input output");
  1184. }
  1185. void DxilGenerationPass::GenerateDxilInputsOutputs(bool bInput) {
  1186. OP *hlslOP = m_pHLModule->GetOP();
  1187. const ShaderModel *pSM = m_pHLModule->GetShaderModel();
  1188. Module &M = *(m_pHLModule->GetModule());
  1189. OP::OpCode opcode = bInput ? OP::OpCode::LoadInput : OP::OpCode::StoreOutput;
  1190. bool bNeedVertexID = bInput && (pSM->IsGS() || pSM->IsDS() || pSM->IsHS());
  1191. Constant *OpArg = hlslOP->GetU32Const((unsigned)opcode);
  1192. Constant *columnConsts[] = {
  1193. hlslOP->GetU8Const(0), hlslOP->GetU8Const(1), hlslOP->GetU8Const(2),
  1194. hlslOP->GetU8Const(3), hlslOP->GetU8Const(4), hlslOP->GetU8Const(5),
  1195. hlslOP->GetU8Const(6), hlslOP->GetU8Const(7), hlslOP->GetU8Const(8),
  1196. hlslOP->GetU8Const(9), hlslOP->GetU8Const(10), hlslOP->GetU8Const(11),
  1197. hlslOP->GetU8Const(12), hlslOP->GetU8Const(13), hlslOP->GetU8Const(14),
  1198. hlslOP->GetU8Const(15)};
  1199. Constant *constZero = hlslOP->GetU32Const(0);
  1200. Value *undefVertexIdx =
  1201. UndefValue::get(Type::getInt32Ty(m_pHLModule->GetCtx()));
  1202. DxilSignature &Sig = bInput ? m_pHLModule->GetInputSignature()
  1203. : m_pHLModule->GetOutputSignature();
  1204. Function *EntryFunc = m_pHLModule->GetEntryFunction();
  1205. Type *i1Ty = Type::getInt1Ty(constZero->getContext());
  1206. Type *i32Ty = constZero->getType();
  1207. llvm::SmallVector<unsigned, 8> removeIndices;
  1208. for (unsigned i = 0; i < Sig.GetElements().size(); i++) {
  1209. DxilSignatureElement *SE = &Sig.GetElement(i);
  1210. llvm::Type *Ty = SE->GetCompType().GetLLVMType(m_pHLModule->GetCtx());
  1211. // Cast i1 to i32 for load input.
  1212. bool bI1Cast = false;
  1213. if (Ty == i1Ty) {
  1214. bI1Cast = true;
  1215. Ty = i32Ty;
  1216. }
  1217. if (!hlslOP->IsOverloadLegal(opcode, Ty)) {
  1218. std::string O;
  1219. raw_string_ostream OSS(O);
  1220. Ty->print(OSS);
  1221. OSS << "(type for " << SE->GetName() << ")";
  1222. OSS << " cannot be used as shader inputs or outputs.";
  1223. OSS.flush();
  1224. M.getContext().emitError(O);
  1225. continue;
  1226. }
  1227. Function *dxilFunc = hlslOP->GetOpFunc(opcode, Ty);
  1228. Constant *ID = hlslOP->GetU32Const(i);
  1229. unsigned cols = SE->GetCols();
  1230. Value *GV = m_sigValueMap[SE];
  1231. bool bIsInout = m_inoutArgSet.count(GV) > 0;
  1232. IRBuilder<> EntryBuilder(EntryFunc->getEntryBlock().getFirstInsertionPt());
  1233. if (DbgDeclareInst *DDI = llvm::FindAllocaDbgDeclare(GV)) {
  1234. EntryBuilder.SetCurrentDebugLocation(DDI->getDebugLoc());
  1235. }
  1236. DXIL::SemanticInterpretationKind SI = SE->GetInterpretation();
  1237. DXASSERT_NOMSG(SI < DXIL::SemanticInterpretationKind::Invalid);
  1238. DXASSERT_NOMSG(SI != DXIL::SemanticInterpretationKind::NA);
  1239. DXASSERT_NOMSG(SI != DXIL::SemanticInterpretationKind::NotInSig);
  1240. if (SI == DXIL::SemanticInterpretationKind::Shadow)
  1241. continue; // Handled in ProcessArgument
  1242. if (!GV->getType()->isPointerTy()) {
  1243. DXASSERT(bInput, "direct parameter must be input");
  1244. Value *vertexID = undefVertexIdx;
  1245. Value *args[] = {OpArg, ID, /*rowIdx*/constZero, /*colIdx*/nullptr, vertexID};
  1246. replaceDirectInputParameter(GV, dxilFunc, cols, args, bI1Cast, hlslOP, EntryBuilder);
  1247. continue;
  1248. }
  1249. bool bIsArrayTy = GV->getType()->getPointerElementType()->isArrayTy();
  1250. bool bIsPrecise = m_preciseSigSet.count(SE);
  1251. if (bIsPrecise)
  1252. HLModule::MarkPreciseAttributeOnPtrWithFunctionCall(GV, M);
  1253. std::vector<InputOutputAccessInfo> accessInfoList;
  1254. collectInputOutputAccessInfo(GV, constZero, accessInfoList, bNeedVertexID && bIsArrayTy, bInput);
  1255. for (InputOutputAccessInfo &info : accessInfoList) {
  1256. GenerateInputOutputUserCall(info, undefVertexIdx, dxilFunc, OpArg, ID,
  1257. cols, bI1Cast, columnConsts, bNeedVertexID,
  1258. bIsArrayTy, bInput, bIsInout);
  1259. }
  1260. }
  1261. }
  1262. void DxilGenerationPass::GenerateDxilCSInputs() {
  1263. OP *hlslOP = m_pHLModule->GetOP();
  1264. Function *entry = m_pHLModule->GetEntryFunction();
  1265. DxilFunctionAnnotation *funcAnnotation = m_pHLModule->GetFunctionAnnotation(entry);
  1266. DXASSERT(funcAnnotation, "must find annotation for entry function");
  1267. IRBuilder<> Builder(entry->getEntryBlock().getFirstInsertionPt());
  1268. for (Argument &arg : entry->args()) {
  1269. DxilParameterAnnotation &paramAnnotation = funcAnnotation->GetParameterAnnotation(arg.getArgNo());
  1270. llvm::StringRef semanticStr = paramAnnotation.GetSemanticString();
  1271. if (semanticStr.empty()) {
  1272. m_pHLModule->GetCtx().emitError(
  1273. "Semantic must be defined for all parameters of an entry function or patch constant function");
  1274. return;
  1275. }
  1276. const Semantic *semantic =
  1277. Semantic::GetByName(semanticStr, DXIL::SigPointKind::CSIn);
  1278. OP::OpCode opcode;
  1279. switch (semantic->GetKind()) {
  1280. case Semantic::Kind::GroupThreadID:
  1281. opcode = OP::OpCode::ThreadIdInGroup;
  1282. break;
  1283. case Semantic::Kind::GroupID:
  1284. opcode = OP::OpCode::GroupId;
  1285. break;
  1286. case Semantic::Kind::DispatchThreadID:
  1287. opcode = OP::OpCode::ThreadId;
  1288. break;
  1289. case Semantic::Kind::GroupIndex:
  1290. opcode = OP::OpCode::FlattenedThreadIdInGroup;
  1291. break;
  1292. default:
  1293. DXASSERT(semantic->IsInvalid(), "else compute shader semantics out-of-date");
  1294. this->m_pHLModule->GetCtx().emitError("invalid semantic found in CS");
  1295. return;
  1296. }
  1297. Constant *OpArg = hlslOP->GetU32Const((unsigned)opcode);
  1298. Type *Ty = arg.getType();
  1299. if (Ty->isPointerTy())
  1300. Ty = Ty->getPointerElementType();
  1301. Function *dxilFunc = hlslOP->GetOpFunc(opcode, Ty->getScalarType());
  1302. Value *newArg = nullptr;
  1303. if (opcode == OP::OpCode::FlattenedThreadIdInGroup) {
  1304. newArg = Builder.CreateCall(dxilFunc, {OpArg});
  1305. } else {
  1306. unsigned vecSize = 1;
  1307. if (Ty->isVectorTy())
  1308. vecSize = Ty->getVectorNumElements();
  1309. newArg = Builder.CreateCall(dxilFunc, {OpArg, hlslOP->GetU32Const(0)});
  1310. if (vecSize > 1) {
  1311. Value *result = UndefValue::get(Ty);
  1312. result = Builder.CreateInsertElement(result, newArg, (uint64_t)0);
  1313. for (unsigned i = 1; i < vecSize; i++) {
  1314. Value *newElt =
  1315. Builder.CreateCall(dxilFunc, {OpArg, hlslOP->GetU32Const(i)});
  1316. result = Builder.CreateInsertElement(result, newElt, i);
  1317. }
  1318. newArg = result;
  1319. }
  1320. }
  1321. if (newArg->getType() != arg.getType()) {
  1322. DXASSERT_NOMSG(arg.getType()->isPointerTy());
  1323. for (User *U : arg.users()) {
  1324. LoadInst *LI = cast<LoadInst>(U);
  1325. LI->replaceAllUsesWith(newArg);
  1326. }
  1327. } else {
  1328. arg.replaceAllUsesWith(newArg);
  1329. }
  1330. }
  1331. }
  1332. void DxilGenerationPass::GenerateDxilPatchConstantLdSt() {
  1333. OP *hlslOP = m_pHLModule->GetOP();
  1334. Module &M = *(m_pHLModule->GetModule());
  1335. Constant *constZero = hlslOP->GetU32Const(0);
  1336. DxilSignature &Sig = m_pHLModule->GetPatchConstantSignature();
  1337. Function *EntryFunc = m_pHLModule->GetEntryFunction();
  1338. auto InsertPt = EntryFunc->getEntryBlock().getFirstInsertionPt();
  1339. const bool bIsHs = m_pHLModule->GetShaderModel()->IsHS();
  1340. const bool bIsInput = !bIsHs;
  1341. const bool bIsInout = false;
  1342. const bool bNeedVertexID = false;
  1343. if (bIsHs) {
  1344. HLFunctionProps &EntryQual = m_pHLModule->GetHLFunctionProps(EntryFunc);
  1345. Function *patchConstantFunc = EntryQual.ShaderProps.HS.patchConstantFunc;
  1346. InsertPt = patchConstantFunc->getEntryBlock().getFirstInsertionPt();
  1347. }
  1348. IRBuilder<> Builder(InsertPt);
  1349. Type *i1Ty = Builder.getInt1Ty();
  1350. Type *i32Ty = Builder.getInt32Ty();
  1351. // LoadPatchConst don't have vertexIdx operand.
  1352. Value *undefVertexIdx = nullptr;
  1353. Constant *columnConsts[] = {
  1354. hlslOP->GetU8Const(0), hlslOP->GetU8Const(1), hlslOP->GetU8Const(2),
  1355. hlslOP->GetU8Const(3), hlslOP->GetU8Const(4), hlslOP->GetU8Const(5),
  1356. hlslOP->GetU8Const(6), hlslOP->GetU8Const(7), hlslOP->GetU8Const(8),
  1357. hlslOP->GetU8Const(9), hlslOP->GetU8Const(10), hlslOP->GetU8Const(11),
  1358. hlslOP->GetU8Const(12), hlslOP->GetU8Const(13), hlslOP->GetU8Const(14),
  1359. hlslOP->GetU8Const(15)};
  1360. OP::OpCode opcode =
  1361. bIsInput ? OP::OpCode::LoadPatchConstant : OP::OpCode::StorePatchConstant;
  1362. Constant *OpArg = hlslOP->GetU32Const((unsigned)opcode);
  1363. for (unsigned i = 0; i < Sig.GetElements().size(); i++) {
  1364. DxilSignatureElement *SE = &Sig.GetElement(i);
  1365. Value *GV = m_sigValueMap[SE];
  1366. DXIL::SemanticInterpretationKind SI = SE->GetInterpretation();
  1367. DXASSERT_NOMSG(SI < DXIL::SemanticInterpretationKind::Invalid);
  1368. DXASSERT_NOMSG(SI != DXIL::SemanticInterpretationKind::NA);
  1369. DXASSERT_NOMSG(SI != DXIL::SemanticInterpretationKind::NotInSig);
  1370. if (SI == DXIL::SemanticInterpretationKind::Shadow)
  1371. continue; // Handled in ProcessArgument
  1372. Constant *ID = hlslOP->GetU32Const(i);
  1373. // Generate LoadPatchConstant.
  1374. Type *Ty = SE->GetCompType().GetLLVMType(m_pHLModule->GetCtx());
  1375. // Cast i1 to i32 for load input.
  1376. bool bI1Cast = false;
  1377. if (Ty == i1Ty) {
  1378. bI1Cast = true;
  1379. Ty = i32Ty;
  1380. }
  1381. unsigned cols = SE->GetCols();
  1382. Function *dxilFunc = hlslOP->GetOpFunc(opcode, Ty);
  1383. if (!GV->getType()->isPointerTy()) {
  1384. DXASSERT(bIsInput, "Must be DS input.");
  1385. Constant *OpArg = hlslOP->GetU32Const(static_cast<unsigned>(OP::OpCode::LoadPatchConstant));
  1386. Value *args[] = {OpArg, ID, /*rowIdx*/constZero, /*colIdx*/nullptr};
  1387. replaceDirectInputParameter(GV, dxilFunc, cols, args, bI1Cast, hlslOP, Builder);
  1388. continue;
  1389. }
  1390. std::vector<InputOutputAccessInfo> accessInfoList;
  1391. collectInputOutputAccessInfo(GV, constZero, accessInfoList, bNeedVertexID,
  1392. bIsInput);
  1393. bool bIsArrayTy = GV->getType()->getPointerElementType()->isArrayTy();
  1394. bool isPrecise = m_preciseSigSet.count(SE);
  1395. if (isPrecise)
  1396. HLModule::MarkPreciseAttributeOnPtrWithFunctionCall(GV, M);
  1397. for (InputOutputAccessInfo &info : accessInfoList) {
  1398. GenerateInputOutputUserCall(info, undefVertexIdx, dxilFunc, OpArg, ID,
  1399. cols, bI1Cast, columnConsts, bNeedVertexID,
  1400. bIsArrayTy, bIsInput, bIsInout);
  1401. }
  1402. }
  1403. }
  1404. void DxilGenerationPass::GenerateDxilPatchConstantFunctionInputs() {
  1405. // Map input patch, to input sig
  1406. // LoadOutputControlPoint for output patch .
  1407. OP *hlslOP = m_pHLModule->GetOP();
  1408. Constant *constZero = hlslOP->GetU32Const(0);
  1409. Function *EntryFunc = m_pHLModule->GetEntryFunction();
  1410. HLFunctionProps &EntryQual = m_pHLModule->GetHLFunctionProps(EntryFunc);
  1411. Function *patchConstantFunc = EntryQual.ShaderProps.HS.patchConstantFunc;
  1412. DxilFunctionAnnotation *patchFuncAnnotation = m_pHLModule->GetFunctionAnnotation(patchConstantFunc);
  1413. DXASSERT(patchFuncAnnotation, "must find annotation for patch constant function");
  1414. Type *i1Ty = Type::getInt1Ty(constZero->getContext());
  1415. Type *i32Ty = constZero->getType();
  1416. for (Argument &arg : patchConstantFunc->args()) {
  1417. DxilParameterAnnotation &paramAnnotation =
  1418. patchFuncAnnotation->GetParameterAnnotation(arg.getArgNo());
  1419. DxilParamInputQual inputQual = paramAnnotation.GetParamInputQual();
  1420. if (inputQual == DxilParamInputQual::InputPatch ||
  1421. inputQual == DxilParamInputQual::OutputPatch) {
  1422. DxilSignatureElement *SE = m_patchConstantInputsSigMap[arg.getArgNo()];
  1423. if (!SE) // Error should have been reported at an earlier stage.
  1424. continue;
  1425. Constant *inputID = hlslOP->GetU32Const(SE->GetID());
  1426. unsigned cols = SE->GetCols();
  1427. Type *Ty = SE->GetCompType().GetLLVMType(m_pHLModule->GetCtx());
  1428. // Cast i1 to i32 for load input.
  1429. bool bI1Cast = false;
  1430. if (Ty == i1Ty) {
  1431. bI1Cast = true;
  1432. Ty = i32Ty;
  1433. }
  1434. OP::OpCode opcode = inputQual == DxilParamInputQual::InputPatch?
  1435. OP::OpCode::LoadInput : OP::OpCode::LoadOutputControlPoint;
  1436. Function *dxilLdFunc = hlslOP->GetOpFunc(opcode, Ty);
  1437. std::vector<InputOutputAccessInfo> accessInfoList;
  1438. collectInputOutputAccessInfo(&arg, constZero, accessInfoList, /*hasVertexID*/ true, true);
  1439. for (InputOutputAccessInfo &info : accessInfoList) {
  1440. if (LoadInst *ldInst = dyn_cast<LoadInst>(info.user)) {
  1441. Constant *OpArg = hlslOP->GetU32Const((unsigned)opcode);
  1442. Value *args[] = {OpArg, inputID, info.idx, info.vectorIdx, info.vertexID};
  1443. replaceLdWithLdInput(dxilLdFunc, ldInst, cols, args, bI1Cast);
  1444. } else
  1445. DXASSERT(0, "input should only be ld");
  1446. }
  1447. }
  1448. }
  1449. }
  1450. bool DxilGenerationPass::HasClipPlanes() {
  1451. Function *EntryFunc = m_pHLModule->GetEntryFunction();
  1452. if (!m_pHLModule->HasHLFunctionProps(EntryFunc))
  1453. return false;
  1454. HLFunctionProps &EntryQual = m_pHLModule->GetHLFunctionProps(EntryFunc);
  1455. auto &VS = EntryQual.ShaderProps.VS;
  1456. unsigned numClipPlanes = 0;
  1457. for (unsigned i=0;i<DXIL::kNumClipPlanes;i++) {
  1458. if (!VS.clipPlanes[i])
  1459. break;
  1460. numClipPlanes++;
  1461. }
  1462. return numClipPlanes != 0;
  1463. }
  1464. void DxilGenerationPass::GenerateClipPlanesForVS(Value *outPosition) {
  1465. Function *EntryFunc = m_pHLModule->GetEntryFunction();
  1466. HLFunctionProps &EntryQual = m_pHLModule->GetHLFunctionProps(EntryFunc);
  1467. auto &VS = EntryQual.ShaderProps.VS;
  1468. unsigned numClipPlanes = 0;
  1469. for (unsigned i=0;i<DXIL::kNumClipPlanes;i++) {
  1470. if (!VS.clipPlanes[i])
  1471. break;
  1472. numClipPlanes++;
  1473. }
  1474. if (!numClipPlanes)
  1475. return;
  1476. LLVMContext &Ctx = EntryFunc->getContext();
  1477. Function *dp4 = m_pHLModule->GetOP()->GetOpFunc(DXIL::OpCode::Dot4, Type::getFloatTy(Ctx));
  1478. Value *dp4Args[] = {
  1479. ConstantInt::get(Type::getInt32Ty(Ctx), static_cast<unsigned>(DXIL::OpCode::Dot4)),
  1480. nullptr, nullptr, nullptr, nullptr,
  1481. nullptr, nullptr, nullptr, nullptr,
  1482. };
  1483. // out SV_Position should only have StoreInst use.
  1484. // Done by LegalizeDxilInputOutputs in ScalarReplAggregatesHLSL.cpp
  1485. for (User *U : outPosition->users()) {
  1486. StoreInst *ST = cast<StoreInst>(U);
  1487. Value *posVal = ST->getValueOperand();
  1488. DXASSERT(posVal->getType()->isVectorTy(), "SV_Position must be a vector");
  1489. IRBuilder<> Builder(ST);
  1490. // Put position to args.
  1491. for (unsigned i=0;i<4;i++)
  1492. dp4Args[i+1] = Builder.CreateExtractElement(posVal, i);
  1493. // For each clip plane.
  1494. // clipDistance = dp4 position, clipPlane.
  1495. auto argIt = EntryFunc->getArgumentList().rbegin();
  1496. for (int clipIdx = numClipPlanes - 1; clipIdx >= 0; clipIdx--) {
  1497. Constant *GV = VS.clipPlanes[clipIdx];
  1498. DXASSERT_NOMSG(GV->hasOneUse());
  1499. StoreInst *ST = cast<StoreInst>(GV->user_back());
  1500. Value *clipPlane = ST->getValueOperand();
  1501. ST->eraseFromParent();
  1502. Argument &arg = *(argIt++);
  1503. // Put clipPlane to args.
  1504. for (unsigned i = 0; i < 4; i++)
  1505. dp4Args[i + 5] = Builder.CreateExtractElement(clipPlane, i);
  1506. Value *clipDistance = Builder.CreateCall(dp4, dp4Args);
  1507. Builder.CreateStore(clipDistance, &arg);
  1508. }
  1509. }
  1510. }
  1511. static Value *MergeImmResClass(Value *resClass) {
  1512. if (ConstantInt *Imm = dyn_cast<ConstantInt>(resClass)) {
  1513. return resClass;
  1514. } else {
  1515. PHINode *phi = cast<PHINode>(resClass);
  1516. Value *immResClass = MergeImmResClass(phi->getIncomingValue(0));
  1517. unsigned numOperands = phi->getNumOperands();
  1518. for (unsigned i=0;i<numOperands;i++)
  1519. phi->setIncomingValue(i, immResClass);
  1520. return immResClass;
  1521. }
  1522. }
  1523. static const StringRef kResourceMapErrorMsg = "local resource not guaranteed to map to unique global resource.";
  1524. static Value *SelectOnOperand(Value *Cond, CallInst *CIT, CallInst *CIF,
  1525. unsigned idx, IRBuilder<> &Builder) {
  1526. Value *OpT = CIT->getArgOperand(idx);
  1527. Value *OpF = CIF->getArgOperand(idx);
  1528. Value *OpSel = OpT;
  1529. if (OpT != OpF) {
  1530. OpSel = Builder.CreateSelect(Cond, OpT, OpF);
  1531. }
  1532. return OpSel;
  1533. }
  1534. static void ReplaceResourceUserWithHandle(LoadInst *Res, Value *handle) {
  1535. for (auto resUser = Res->user_begin(); resUser != Res->user_end();) {
  1536. CallInst *CI = dyn_cast<CallInst>(*(resUser++));
  1537. DXASSERT(GetHLOpcodeGroupByName(CI->getCalledFunction()) ==
  1538. HLOpcodeGroup::HLCreateHandle,
  1539. "must be createHandle");
  1540. CI->replaceAllUsesWith(handle);
  1541. CI->eraseFromParent();
  1542. }
  1543. Res->eraseFromParent();
  1544. }
  1545. static bool IsResourceType(Type *Ty) {
  1546. bool isResource = HLModule::IsHLSLObjectType(Ty);
  1547. if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  1548. Type *EltTy = AT->getElementType();
  1549. while (isa<ArrayType>(EltTy)) {
  1550. EltTy = EltTy->getArrayElementType();
  1551. }
  1552. isResource = HLModule::IsHLSLObjectType(EltTy);
  1553. // TODO: support local resource array.
  1554. DXASSERT(!isResource, "local resource array");
  1555. }
  1556. return isResource;
  1557. }
  1558. void DxilGenerationPass::RemoveLocalDxilResourceAllocas(Function *F) {
  1559. BasicBlock &BB = F->getEntryBlock(); // Get the entry node for the function
  1560. std::unordered_set<AllocaInst *> localResources;
  1561. for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
  1562. if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) { // Is it an alloca?
  1563. if (IsResourceType(AI->getAllocatedType())) {
  1564. localResources.insert(AI);
  1565. }
  1566. }
  1567. SSAUpdater SSA;
  1568. SmallVector<Instruction *, 4> Insts;
  1569. for (AllocaInst *AI : localResources) {
  1570. // Build list of instructions to promote.
  1571. for (User *U : AI->users())
  1572. Insts.emplace_back(cast<Instruction>(U));
  1573. ResourceRemover(Insts, SSA).run(AI, Insts);
  1574. Insts.clear();
  1575. }
  1576. }
  1577. void DxilGenerationPass::TranslateParamDxilResourceHandles(Function *F, std::unordered_map<Instruction *, Value *> &handleMap) {
  1578. Type *handleTy = m_pHLModule->GetOP()->GetHandleType();
  1579. IRBuilder<> Builder(F->getEntryBlock().getFirstInsertionPt());
  1580. for (Argument &arg : F->args()) {
  1581. Type *Ty = arg.getType();
  1582. if (isa<PointerType>(Ty))
  1583. Ty = Ty->getPointerElementType();
  1584. SmallVector<unsigned,4> arraySizeList;
  1585. while (isa<ArrayType>(Ty)) {
  1586. arraySizeList.push_back(Ty->getArrayNumElements());
  1587. Ty = Ty->getArrayElementType();
  1588. }
  1589. DXIL::ResourceClass RC = m_pHLModule->GetResourceClass(Ty);
  1590. if (RC != DXIL::ResourceClass::Invalid) {
  1591. Type *curTy = handleTy;
  1592. for (auto it = arraySizeList.rbegin(), E = arraySizeList.rend(); it != E;
  1593. it++) {
  1594. curTy = ArrayType::get(curTy, *it);
  1595. }
  1596. curTy = PointerType::get(curTy, 0);
  1597. CallInst *castToHandle = cast<CallInst>(HLModule::EmitHLOperationCall(
  1598. Builder, HLOpcodeGroup::HLCast, 0, curTy,
  1599. {UndefValue::get(arg.getType())}, *F->getParent()));
  1600. for (User *U : arg.users()) {
  1601. Instruction *I = cast<Instruction>(U);
  1602. IRBuilder<> userBuilder(I);
  1603. if (LoadInst *ldInst = dyn_cast<LoadInst>(U)) {
  1604. Value *handleLd = userBuilder.CreateLoad(castToHandle);
  1605. handleMap[ldInst] = handleLd;
  1606. } else if (StoreInst *stInst = dyn_cast<StoreInst>(U)) {
  1607. Value *res = stInst->getValueOperand();
  1608. Value *handle = HLModule::EmitHLOperationCall(
  1609. userBuilder, HLOpcodeGroup::HLCast, 0, handleTy, {res},
  1610. *F->getParent());
  1611. userBuilder.CreateStore(handle, castToHandle);
  1612. } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
  1613. // Don't flatten argument here.
  1614. continue;
  1615. } else {
  1616. DXASSERT(
  1617. dyn_cast<GEPOperator>(U) != nullptr,
  1618. "else AddOpcodeParamForIntrinsic in CodeGen did not patch uses "
  1619. "to only have ld/st refer to temp object");
  1620. GEPOperator *GEP = cast<GEPOperator>(U);
  1621. std::vector<Value *> idxList(GEP->idx_begin(), GEP->idx_end());
  1622. Value *handleGEP = userBuilder.CreateGEP(castToHandle, idxList);
  1623. for (auto GEPU : GEP->users()) {
  1624. Instruction *GEPI = cast<Instruction>(GEPU);
  1625. IRBuilder<> gepUserBuilder(GEPI);
  1626. if (LoadInst *ldInst = dyn_cast<LoadInst>(GEPU)) {
  1627. handleMap[ldInst] = gepUserBuilder.CreateLoad(handleGEP);
  1628. } else {
  1629. StoreInst *stInst = cast<StoreInst>(GEPU);
  1630. Value *res = stInst->getValueOperand();
  1631. Value *handle = HLModule::EmitHLOperationCall(
  1632. gepUserBuilder, HLOpcodeGroup::HLCast, 0, handleTy, {res},
  1633. *F->getParent());
  1634. gepUserBuilder.CreateStore(handle, handleGEP);
  1635. }
  1636. }
  1637. }
  1638. }
  1639. castToHandle->setArgOperand(0, &arg);
  1640. }
  1641. }
  1642. }
  1643. void DxilGenerationPass::GenerateParamDxilResourceHandles(
  1644. std::unordered_map<Instruction *, Value *> &handleMap) {
  1645. Module &M = *m_pHLModule->GetModule();
  1646. for (Function &F : M.functions()) {
  1647. if (!F.isDeclaration())
  1648. TranslateParamDxilResourceHandles(&F, handleMap);
  1649. }
  1650. }
  1651. void DxilGenerationPass::TranslateDxilResourceUses(
  1652. DxilResourceBase &res, std::unordered_set<LoadInst *> &UpdateCounterSet,
  1653. std::unordered_set<Value *> &NonUniformSet) {
  1654. OP *hlslOP = m_pHLModule->GetOP();
  1655. Function *createHandle = hlslOP->GetOpFunc(
  1656. OP::OpCode::CreateHandle, llvm::Type::getVoidTy(m_pHLModule->GetCtx()));
  1657. Value *opArg = hlslOP->GetU32Const((unsigned)OP::OpCode::CreateHandle);
  1658. bool isViewResource = res.GetClass() == DXIL::ResourceClass::SRV || res.GetClass() == DXIL::ResourceClass::UAV;
  1659. bool isROV = isViewResource && static_cast<DxilResource &>(res).IsROV();
  1660. std::string handleName = (res.GetGlobalName() + Twine("_") + Twine(res.GetResClassName())).str();
  1661. if (isViewResource)
  1662. handleName += (Twine("_") + Twine(res.GetResDimName())).str();
  1663. if (isROV)
  1664. handleName += "_ROV";
  1665. Value *resClassArg = hlslOP->GetU8Const(
  1666. static_cast<std::underlying_type<DxilResourceBase::Class>::type>(
  1667. res.GetClass()));
  1668. Value *resIDArg = hlslOP->GetU32Const(res.GetID());
  1669. // resLowerBound will be added after allocation in DxilCondenseResources.
  1670. Value *resLowerBound = hlslOP->GetU32Const(0);
  1671. // TODO: Set Non-uniform resource bit based on whether index comes from IOP_NonUniformResourceIndex.
  1672. Value *isUniformRes = hlslOP->GetI1Const(0);
  1673. Value *GV = res.GetGlobalSymbol();
  1674. Module *pM = m_pHLModule->GetModule();
  1675. // TODO: add debug info to create handle.
  1676. DIVariable *DIV = nullptr;
  1677. DILocation *DL = nullptr;
  1678. if (m_HasDbgInfo) {
  1679. DebugInfoFinder &Finder = m_pHLModule->GetOrCreateDebugInfoFinder();
  1680. DIV =
  1681. HLModule::FindGlobalVariableDebugInfo(cast<GlobalVariable>(GV), Finder);
  1682. if (DIV)
  1683. // TODO: how to get col?
  1684. DL =
  1685. DILocation::get(pM->getContext(), DIV->getLine(), 1, DIV->getScope());
  1686. }
  1687. bool isResArray = res.GetRangeSize() > 1;
  1688. std::unordered_map<Function *, Instruction *> handleMapOnFunction;
  1689. Value *createHandleArgs[] = {opArg, resClassArg, resIDArg, resLowerBound,
  1690. isUniformRes};
  1691. for (iplist<Function>::iterator F : pM->getFunctionList()) {
  1692. if (!F->isDeclaration()) {
  1693. if (!isResArray) {
  1694. IRBuilder<> Builder(F->getEntryBlock().getFirstInsertionPt());
  1695. if (m_HasDbgInfo) {
  1696. // TODO: set debug info.
  1697. //Builder.SetCurrentDebugLocation(DL);
  1698. }
  1699. handleMapOnFunction[F] = Builder.CreateCall(createHandle, createHandleArgs, handleName);
  1700. }
  1701. }
  1702. }
  1703. for (auto U = GV->user_begin(), E = GV->user_end(); U != E; ) {
  1704. User *user = *(U++);
  1705. // Skip unused user.
  1706. if (user->user_empty())
  1707. continue;
  1708. if (LoadInst *ldInst = dyn_cast<LoadInst>(user)) {
  1709. if (UpdateCounterSet.count(ldInst)) {
  1710. DxilResource *resource = llvm::dyn_cast<DxilResource>(&res);
  1711. DXASSERT_NOMSG(resource);
  1712. DXASSERT_NOMSG(resource->GetClass() == DXIL::ResourceClass::UAV);
  1713. resource->SetHasCounter(true);
  1714. }
  1715. Function *userF = ldInst->getParent()->getParent();
  1716. DXASSERT(handleMapOnFunction.count(userF), "must exist");
  1717. Value *handle = handleMapOnFunction[userF];
  1718. ReplaceResourceUserWithHandle(ldInst, handle);
  1719. } else {
  1720. DXASSERT(dyn_cast<GEPOperator>(user) != nullptr,
  1721. "else AddOpcodeParamForIntrinsic in CodeGen did not patch uses "
  1722. "to only have ld/st refer to temp object");
  1723. GEPOperator *GEP = cast<GEPOperator>(user);
  1724. Value *idx = nullptr;
  1725. if (GEP->getNumIndices() == 2) {
  1726. // one dim array of resource
  1727. idx = (GEP->idx_begin() + 1)->get();
  1728. } else {
  1729. gep_type_iterator GEPIt = gep_type_begin(GEP), E = gep_type_end(GEP);
  1730. // Must be instruction for multi dim array.
  1731. std::unique_ptr<IRBuilder<> > Builder;
  1732. if (GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(GEP)) {
  1733. Builder = std::make_unique<IRBuilder<> >(GEPInst);
  1734. } else {
  1735. Builder = std::make_unique<IRBuilder<> >(GV->getContext());
  1736. }
  1737. for (; GEPIt != E; ++GEPIt) {
  1738. if (GEPIt->isArrayTy()) {
  1739. unsigned arraySize = GEPIt->getArrayNumElements();
  1740. Value * tmpIdx = GEPIt.getOperand();
  1741. if (idx == nullptr)
  1742. idx = tmpIdx;
  1743. else {
  1744. idx = Builder->CreateMul(idx, Builder->getInt32(arraySize));
  1745. idx = Builder->CreateAdd(idx, tmpIdx);
  1746. }
  1747. }
  1748. }
  1749. }
  1750. createHandleArgs[DXIL::OperandIndex::kCreateHandleResIndexOpIdx] = idx;
  1751. if (!NonUniformSet.count(idx))
  1752. createHandleArgs[DXIL::OperandIndex::kCreateHandleIsUniformOpIdx] =
  1753. isUniformRes;
  1754. else
  1755. createHandleArgs[DXIL::OperandIndex::kCreateHandleIsUniformOpIdx] =
  1756. hlslOP->GetI1Const(1);
  1757. Value *handle = nullptr;
  1758. if (GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(GEP)) {
  1759. IRBuilder<> Builder = IRBuilder<>(GEPInst);
  1760. handle = Builder.CreateCall(createHandle, createHandleArgs, handleName);
  1761. }
  1762. for (auto GEPU = GEP->user_begin(), GEPE = GEP->user_end(); GEPU != GEPE; ) {
  1763. // Must be load inst.
  1764. LoadInst *ldInst = cast<LoadInst>(*(GEPU++));
  1765. if (UpdateCounterSet.count(ldInst)) {
  1766. DxilResource *resource = dyn_cast<DxilResource>(&res);
  1767. DXASSERT_NOMSG(resource);
  1768. DXASSERT_NOMSG(resource->GetClass() == DXIL::ResourceClass::UAV);
  1769. resource->SetHasCounter(true);
  1770. }
  1771. if (handle) {
  1772. ReplaceResourceUserWithHandle(ldInst, handle);
  1773. }
  1774. else {
  1775. IRBuilder<> Builder = IRBuilder<>(ldInst);
  1776. Value *localHandle = Builder.CreateCall(createHandle, createHandleArgs, handleName);
  1777. ReplaceResourceUserWithHandle(ldInst, localHandle);
  1778. }
  1779. }
  1780. }
  1781. }
  1782. // Erase unused handle.
  1783. for (auto It : handleMapOnFunction) {
  1784. Instruction *I = It.second;
  1785. if (I->user_empty())
  1786. I->eraseFromParent();
  1787. }
  1788. }
  1789. void DxilGenerationPass::GenerateDxilResourceHandles(
  1790. std::unordered_set<LoadInst *> &UpdateCounterSet,
  1791. std::unordered_set<Value *> &NonUniformSet) {
  1792. // Create sampler handle first, may be used by SRV operations.
  1793. for (size_t i = 0; i < m_pHLModule->GetSamplers().size(); i++) {
  1794. DxilSampler &S = m_pHLModule->GetSampler(i);
  1795. TranslateDxilResourceUses(S, UpdateCounterSet, NonUniformSet);
  1796. }
  1797. for (size_t i = 0; i < m_pHLModule->GetSRVs().size(); i++) {
  1798. HLResource &SRV = m_pHLModule->GetSRV(i);
  1799. TranslateDxilResourceUses(SRV, UpdateCounterSet, NonUniformSet);
  1800. }
  1801. for (size_t i = 0; i < m_pHLModule->GetUAVs().size(); i++) {
  1802. HLResource &UAV = m_pHLModule->GetUAV(i);
  1803. TranslateDxilResourceUses(UAV, UpdateCounterSet, NonUniformSet);
  1804. }
  1805. }
  1806. static void
  1807. AddResourceToSet(Instruction *Res, std::unordered_set<Instruction *> &resSet) {
  1808. unsigned startOpIdx = 0;
  1809. // Skip Cond for Select.
  1810. if (isa<SelectInst>(Res))
  1811. startOpIdx = 1;
  1812. else if (!isa<PHINode>(Res))
  1813. // Only check phi and select here.
  1814. return;
  1815. // Already add.
  1816. if (resSet.count(Res))
  1817. return;
  1818. resSet.insert(Res);
  1819. // Scan operand to add resource node which only used by phi/select.
  1820. unsigned numOperands = Res->getNumOperands();
  1821. for (unsigned i = startOpIdx; i < numOperands; i++) {
  1822. Value *V = Res->getOperand(i);
  1823. if (Instruction *I = dyn_cast<Instruction>(V)) {
  1824. AddResourceToSet(I, resSet);
  1825. }
  1826. }
  1827. }
  1828. // Transform
  1829. //
  1830. // %g_texture_texture_2d1 = call %dx.types.Handle @dx.op.createHandle(i32 57, i8 0, i32 0, i32 0, i1 false)
  1831. // %g_texture_texture_2d = call %dx.types.Handle @dx.op.createHandle(i32 57, i8 0, i32 0, i32 2, i1 false)
  1832. // %13 = select i1 %cmp, %dx.types.Handle %g_texture_texture_2d1, %dx.types.Handle %g_texture_texture_2d
  1833. // Into
  1834. // %11 = select i1 %cmp, i32 0, i32 2
  1835. // %12 = call %dx.types.Handle @dx.op.createHandle(i32 57, i8 0, i32 0, i32 %11, i1 false)
  1836. //
  1837. static bool MergeHandleOpWithSameValue(Instruction *HandleOp,
  1838. unsigned startOpIdx,
  1839. unsigned numOperands) {
  1840. Value *op0 = nullptr;
  1841. for (unsigned i = startOpIdx; i < numOperands; i++) {
  1842. Value *op = HandleOp->getOperand(i);
  1843. if (i == startOpIdx) {
  1844. op0 = op;
  1845. } else {
  1846. if (op0 != op)
  1847. op0 = nullptr;
  1848. }
  1849. }
  1850. if (op0) {
  1851. HandleOp->replaceAllUsesWith(op0);
  1852. return true;
  1853. }
  1854. return false;
  1855. }
  1856. static void
  1857. UpdateHandleOperands(Instruction *Res,
  1858. std::unordered_map<Instruction *, CallInst *> &handleMap,
  1859. std::unordered_set<Instruction *> &nonUniformOps) {
  1860. unsigned numOperands = Res->getNumOperands();
  1861. unsigned startOpIdx = 0;
  1862. // Skip Cond for Select.
  1863. if (SelectInst *Sel = dyn_cast<SelectInst>(Res))
  1864. startOpIdx = 1;
  1865. CallInst *Handle = handleMap[Res];
  1866. Instruction *resClass = cast<Instruction>(
  1867. Handle->getArgOperand(DXIL::OperandIndex::kCreateHandleResClassOpIdx));
  1868. Instruction *resID = cast<Instruction>(
  1869. Handle->getArgOperand(DXIL::OperandIndex::kCreateHandleResIDOpIdx));
  1870. Instruction *resAddr = cast<Instruction>(
  1871. Handle->getArgOperand(DXIL::OperandIndex::kCreateHandleResIndexOpIdx));
  1872. for (unsigned i = startOpIdx; i < numOperands; i++) {
  1873. if (!isa<Instruction>(Res->getOperand(i))) {
  1874. Res->getContext().emitError(Res, kResourceMapErrorMsg);
  1875. continue;
  1876. }
  1877. Instruction *ResOp = cast<Instruction>(Res->getOperand(i));
  1878. CallInst *HandleOp = dyn_cast<CallInst>(ResOp);
  1879. if (!HandleOp) {
  1880. if (handleMap.count(ResOp)) {
  1881. Res->getContext().emitError(Res, kResourceMapErrorMsg);
  1882. continue;
  1883. }
  1884. HandleOp = handleMap[ResOp];
  1885. }
  1886. Value *resClassOp =
  1887. HandleOp->getArgOperand(DXIL::OperandIndex::kCreateHandleResClassOpIdx);
  1888. Value *resIDOp =
  1889. HandleOp->getArgOperand(DXIL::OperandIndex::kCreateHandleResIDOpIdx);
  1890. Value *resAddrOp =
  1891. HandleOp->getArgOperand(DXIL::OperandIndex::kCreateHandleResIndexOpIdx);
  1892. resClass->setOperand(i, resClassOp);
  1893. resID->setOperand(i, resIDOp);
  1894. resAddr->setOperand(i, resAddrOp);
  1895. }
  1896. if (!MergeHandleOpWithSameValue(resClass, startOpIdx, numOperands))
  1897. nonUniformOps.insert(resClass);
  1898. if (!MergeHandleOpWithSameValue(resID, startOpIdx, numOperands))
  1899. nonUniformOps.insert(resID);
  1900. MergeHandleOpWithSameValue(resAddr, startOpIdx, numOperands);
  1901. }
  1902. void DxilGenerationPass::AddCreateHandleForPhiNodeAndSelect(OP *hlslOP) {
  1903. Function *createHandle = hlslOP->GetOpFunc(
  1904. OP::OpCode::CreateHandle, llvm::Type::getVoidTy(hlslOP->GetCtx()));
  1905. std::unordered_set<PHINode *> objPhiList;
  1906. std::unordered_set<SelectInst *> objSelectList;
  1907. std::unordered_set<Instruction *> resSelectSet;
  1908. for (User *U : createHandle->users()) {
  1909. for (User *HandleU : U->users()) {
  1910. Instruction *I = cast<Instruction>(HandleU);
  1911. if (!isa<CallInst>(I))
  1912. AddResourceToSet(I, resSelectSet);
  1913. }
  1914. }
  1915. // Generate Handle inst for Res inst.
  1916. FunctionType *FT = createHandle->getFunctionType();
  1917. Value *opArg = hlslOP->GetU32Const((unsigned)OP::OpCode::CreateHandle);
  1918. Type *resClassTy =
  1919. FT->getParamType(DXIL::OperandIndex::kCreateHandleResClassOpIdx);
  1920. Type *resIDTy = FT->getParamType(DXIL::OperandIndex::kCreateHandleResIDOpIdx);
  1921. Type *resAddrTy =
  1922. FT->getParamType(DXIL::OperandIndex::kCreateHandleResIndexOpIdx);
  1923. Value *UndefResClass = UndefValue::get(resClassTy);
  1924. Value *UndefResID = UndefValue::get(resIDTy);
  1925. Value *UndefResAddr = UndefValue::get(resAddrTy);
  1926. // phi/select node resource is not uniform
  1927. Value *nonUniformRes = hlslOP->GetI1Const(1);
  1928. std::unordered_map<Instruction *, CallInst *> handleMap;
  1929. for (Instruction *Res : resSelectSet) {
  1930. unsigned numOperands = Res->getNumOperands();
  1931. IRBuilder<> Builder(Res);
  1932. unsigned startOpIdx = 0;
  1933. // Skip Cond for Select.
  1934. if (SelectInst *Sel = dyn_cast<SelectInst>(Res)) {
  1935. startOpIdx = 1;
  1936. Value *Cond = Sel->getCondition();
  1937. Value *resClassSel =
  1938. Builder.CreateSelect(Cond, UndefResClass, UndefResClass);
  1939. Value *resIDSel = Builder.CreateSelect(Cond, UndefResID, UndefResID);
  1940. Value *resAddrSel =
  1941. Builder.CreateSelect(Cond, UndefResAddr, UndefResAddr);
  1942. CallInst *HandleSel =
  1943. Builder.CreateCall(createHandle, {opArg, resClassSel, resIDSel,
  1944. resAddrSel, nonUniformRes});
  1945. handleMap[Res] = HandleSel;
  1946. Res->replaceAllUsesWith(HandleSel);
  1947. } else {
  1948. PHINode *Phi = cast<PHINode>(Res); // res class must be same.
  1949. PHINode *resClassPhi = Builder.CreatePHI(resClassTy, numOperands);
  1950. PHINode *resIDPhi = Builder.CreatePHI(resIDTy, numOperands);
  1951. PHINode *resAddrPhi = Builder.CreatePHI(resAddrTy, numOperands);
  1952. for (unsigned i = 0; i < numOperands; i++) {
  1953. BasicBlock *BB = Phi->getIncomingBlock(i);
  1954. resClassPhi->addIncoming(UndefResClass, BB);
  1955. resIDPhi->addIncoming(UndefResID, BB);
  1956. resAddrPhi->addIncoming(UndefResAddr, BB);
  1957. }
  1958. IRBuilder<> HandleBuilder(Phi->getParent()->getFirstNonPHI());
  1959. CallInst *HandlePhi =
  1960. HandleBuilder.CreateCall(createHandle, {opArg, resClassPhi, resIDPhi,
  1961. resAddrPhi, nonUniformRes});
  1962. handleMap[Res] = HandlePhi;
  1963. Res->replaceAllUsesWith(HandlePhi);
  1964. }
  1965. }
  1966. // Update operand for Handle phi/select.
  1967. // If ResClass or ResID is phi/select, save to nonUniformOps.
  1968. std::unordered_set<Instruction *> nonUniformOps;
  1969. for (Instruction *Res : resSelectSet) {
  1970. UpdateHandleOperands(Res, handleMap, nonUniformOps);
  1971. }
  1972. // ResClass and ResID must be uniform.
  1973. // Try to merge res class, res id into imm.
  1974. while (1) {
  1975. bool bUpdated = false;
  1976. for (auto It = nonUniformOps.begin(); It != nonUniformOps.end();) {
  1977. Instruction *I = *(It++);
  1978. unsigned numOperands = I->getNumOperands();
  1979. unsigned startOpIdx = 0;
  1980. // Skip Cond for Select.
  1981. if (SelectInst *Sel = dyn_cast<SelectInst>(I))
  1982. startOpIdx = 1;
  1983. if (MergeHandleOpWithSameValue(I, startOpIdx, numOperands)) {
  1984. nonUniformOps.erase(I);
  1985. bUpdated = true;
  1986. }
  1987. }
  1988. if (!bUpdated) {
  1989. if (!nonUniformOps.empty()) {
  1990. for (Instruction *I : nonUniformOps) {
  1991. // Non uniform res class or res id.
  1992. FT->getContext().emitError(I, kResourceMapErrorMsg);
  1993. }
  1994. return;
  1995. }
  1996. break;
  1997. }
  1998. }
  1999. // Remove useless select/phi.
  2000. for (Instruction *Res : resSelectSet) {
  2001. Res->eraseFromParent();
  2002. }
  2003. }
  2004. void DxilGenerationPass::GenerateDxilCBufferHandles(
  2005. std::unordered_set<Value *> &NonUniformSet) {
  2006. // For CBuffer, handle are mapped to HLCreateHandle.
  2007. OP *hlslOP = m_pHLModule->GetOP();
  2008. Function *createHandle = hlslOP->GetOpFunc(
  2009. OP::OpCode::CreateHandle, llvm::Type::getVoidTy(m_pHLModule->GetCtx()));
  2010. Value *opArg = hlslOP->GetU32Const((unsigned)OP::OpCode::CreateHandle);
  2011. Value *resClassArg = hlslOP->GetU8Const(
  2012. static_cast<std::underlying_type<DxilResourceBase::Class>::type>(
  2013. DXIL::ResourceClass::CBuffer));
  2014. for (size_t i = 0; i < m_pHLModule->GetCBuffers().size(); i++) {
  2015. DxilCBuffer &CB = m_pHLModule->GetCBuffer(i);
  2016. GlobalVariable *GV = cast<GlobalVariable>(CB.GetGlobalSymbol());
  2017. // Remove GEP created in HLObjectOperationLowerHelper::UniformCbPtr.
  2018. GV->removeDeadConstantUsers();
  2019. std::string handleName = std::string(GV->getName()) + "_buffer";
  2020. Value *args[] = {opArg, resClassArg, nullptr, nullptr,
  2021. hlslOP->GetI1Const(0)};
  2022. DIVariable *DIV = nullptr;
  2023. DILocation *DL = nullptr;
  2024. if (m_HasDbgInfo) {
  2025. DebugInfoFinder &Finder = m_pHLModule->GetOrCreateDebugInfoFinder();
  2026. DIV = HLModule::FindGlobalVariableDebugInfo(GV, Finder);
  2027. if (DIV)
  2028. // TODO: how to get col?
  2029. DL = DILocation::get(createHandle->getContext(), DIV->getLine(), 1,
  2030. DIV->getScope());
  2031. }
  2032. Value *resIDArg = hlslOP->GetU32Const(CB.GetID());
  2033. args[DXIL::OperandIndex::kCreateHandleResIDOpIdx] = resIDArg;
  2034. // resLowerBound will be added after allocation in DxilCondenseResources.
  2035. Value *resLowerBound = hlslOP->GetU32Const(0);
  2036. if (CB.GetRangeSize() == 1) {
  2037. args[DXIL::OperandIndex::kCreateHandleResIndexOpIdx] = resLowerBound;
  2038. for (auto U = GV->user_begin(); U != GV->user_end(); ) {
  2039. // Must HLCreateHandle.
  2040. CallInst *CI = cast<CallInst>(*(U++));
  2041. // Put createHandle to entry block.
  2042. auto InsertPt =
  2043. CI->getParent()->getParent()->getEntryBlock().getFirstInsertionPt();
  2044. IRBuilder<> Builder(InsertPt);
  2045. CallInst *handle = Builder.CreateCall(createHandle, args, handleName);
  2046. if (m_HasDbgInfo) {
  2047. // TODO: add debug info.
  2048. //handle->setDebugLoc(DL);
  2049. }
  2050. CI->replaceAllUsesWith(handle);
  2051. CI->eraseFromParent();
  2052. }
  2053. } else {
  2054. for (auto U = GV->user_begin(); U != GV->user_end(); ) {
  2055. // Must HLCreateHandle.
  2056. CallInst *CI = cast<CallInst>(*(U++));
  2057. IRBuilder<> Builder(CI);
  2058. Value *CBIndex = CI->getArgOperand(HLOperandIndex::kCreateHandleIndexOpIdx);
  2059. args[DXIL::OperandIndex::kCreateHandleResIndexOpIdx] =
  2060. CBIndex;
  2061. if (isa<ConstantInt>(CBIndex)) {
  2062. // Put createHandle to entry block for const index.
  2063. auto InsertPt = CI->getParent()
  2064. ->getParent()
  2065. ->getEntryBlock()
  2066. .getFirstInsertionPt();
  2067. Builder.SetInsertPoint(InsertPt);
  2068. }
  2069. if (!NonUniformSet.count(CBIndex))
  2070. args[DXIL::OperandIndex::kCreateHandleIsUniformOpIdx] =
  2071. hlslOP->GetI1Const(0);
  2072. else
  2073. args[DXIL::OperandIndex::kCreateHandleIsUniformOpIdx] =
  2074. hlslOP->GetI1Const(1);
  2075. CallInst *handle = Builder.CreateCall(createHandle, args, handleName);
  2076. CI->replaceAllUsesWith(handle);
  2077. CI->eraseFromParent();
  2078. }
  2079. }
  2080. }
  2081. }
  2082. static void GenerateStOutput(Function *stOutput, Value *eltVal, Value *outputID,
  2083. Value *rowIdx, Value *colIdx, OP *hlslOP,
  2084. IRBuilder<> Builder) {
  2085. Constant *OpArg = hlslOP->GetU32Const((unsigned)OP::OpCode::StoreOutput);
  2086. Builder.CreateCall(stOutput, {OpArg, outputID, rowIdx, colIdx, eltVal});
  2087. }
  2088. static Value *TranslateStreamAppend(CallInst *CI, unsigned ID, hlsl::OP *OP) {
  2089. Function *DxilFunc = OP->GetOpFunc(OP::OpCode::EmitStream, CI->getType());
  2090. // TODO: generate a emit which has the data being emited as its argment.
  2091. // Value *data = CI->getArgOperand(HLOperandIndex::kStreamAppendDataOpIndex);
  2092. Constant *opArg = OP->GetU32Const((unsigned)OP::OpCode::EmitStream);
  2093. IRBuilder<> Builder(CI);
  2094. Constant *streamID = OP->GetU8Const(ID);
  2095. Value *args[] = {opArg, streamID};
  2096. return Builder.CreateCall(DxilFunc, args);
  2097. }
  2098. static Value *TranslateStreamCut(CallInst *CI, unsigned ID, hlsl::OP *OP) {
  2099. Function *DxilFunc = OP->GetOpFunc(OP::OpCode::CutStream, CI->getType());
  2100. // TODO: generate a emit which has the data being emited as its argment.
  2101. // Value *data = CI->getArgOperand(HLOperandIndex::kStreamAppendDataOpIndex);
  2102. Constant *opArg = OP->GetU32Const((unsigned)OP::OpCode::CutStream);
  2103. IRBuilder<> Builder(CI);
  2104. Constant *streamID = OP->GetU8Const(ID);
  2105. Value *args[] = {opArg, streamID};
  2106. return Builder.CreateCall(DxilFunc, args);
  2107. }
  2108. // Generate DXIL stream output operation.
  2109. void DxilGenerationPass::GenerateStreamOutputOperation(Value *streamVal, unsigned ID) {
  2110. OP * hlslOP = m_pHLModule->GetOP();
  2111. for (auto U = streamVal->user_begin(); U != streamVal->user_end();) {
  2112. Value *user = *(U++);
  2113. // Should only used by append, restartStrip .
  2114. CallInst *CI = cast<CallInst>(user);
  2115. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  2116. unsigned opcode = GetHLOpcode(CI);
  2117. DXASSERT_LOCALVAR(group, group == HLOpcodeGroup::HLIntrinsic, "");
  2118. IntrinsicOp IOP = static_cast<IntrinsicOp>(opcode);
  2119. switch (IOP) {
  2120. case IntrinsicOp::MOP_Append:
  2121. TranslateStreamAppend(CI, ID, hlslOP);
  2122. break;
  2123. case IntrinsicOp::MOP_RestartStrip:
  2124. TranslateStreamCut(CI, ID, hlslOP);
  2125. break;
  2126. default:
  2127. DXASSERT(0, "invalid operation on stream");
  2128. }
  2129. CI->eraseFromParent();
  2130. }
  2131. }
  2132. // Generate DXIL stream output operations.
  2133. void DxilGenerationPass::GenerateStreamOutputOperations() {
  2134. Function *EntryFunc = m_pHLModule->GetEntryFunction();
  2135. DxilFunctionAnnotation *EntryAnnotation = m_pHLModule->GetFunctionAnnotation(EntryFunc);
  2136. DXASSERT(EntryAnnotation, "must find annotation for entry function");
  2137. for (Argument &arg : EntryFunc->getArgumentList()) {
  2138. if (HLModule::IsStreamOutputPtrType(arg.getType())) {
  2139. unsigned streamID = 0;
  2140. DxilParameterAnnotation &paramAnnotation = EntryAnnotation->GetParameterAnnotation(arg.getArgNo());
  2141. DxilParamInputQual inputQual = paramAnnotation.GetParamInputQual();
  2142. switch (inputQual) {
  2143. case DxilParamInputQual::OutStream0:
  2144. streamID = 0;
  2145. break;
  2146. case DxilParamInputQual::OutStream1:
  2147. streamID = 1;
  2148. break;
  2149. case DxilParamInputQual::OutStream2:
  2150. streamID = 2;
  2151. break;
  2152. case DxilParamInputQual::OutStream3:
  2153. default:
  2154. DXASSERT(inputQual == DxilParamInputQual::OutStream3, "invalid input qual.");
  2155. streamID = 3;
  2156. break;
  2157. }
  2158. GenerateStreamOutputOperation(&arg, streamID);
  2159. }
  2160. }
  2161. }
  2162. void DxilGenerationPass::GenerateDxilOperations(
  2163. Module &M, std::unordered_set<LoadInst *> &UpdateCounterSet,
  2164. std::unordered_set<Value *> &NonUniformSet) {
  2165. // remove all functions except entry function
  2166. Function *entry = m_pHLModule->GetEntryFunction();
  2167. const ShaderModel *pSM = m_pHLModule->GetShaderModel();
  2168. Function *patchConstantFunc = nullptr;
  2169. if (pSM->IsHS()) {
  2170. HLFunctionProps &funcProps = m_pHLModule->GetHLFunctionProps(entry);
  2171. patchConstantFunc = funcProps.ShaderProps.HS.patchConstantFunc;
  2172. }
  2173. for (auto F = M.begin(); F != M.end();) {
  2174. Function *func = F++;
  2175. if (func->isDeclaration())
  2176. continue;
  2177. if (func == entry)
  2178. continue;
  2179. if (func == patchConstantFunc)
  2180. continue;
  2181. if (func->user_empty())
  2182. func->eraseFromParent();
  2183. }
  2184. TranslateBuiltinOperations(*m_pHLModule, m_extensionsCodegenHelper,
  2185. UpdateCounterSet, NonUniformSet);
  2186. if (pSM->IsGS())
  2187. GenerateStreamOutputOperations();
  2188. // Remove unused HL Operation functions.
  2189. std::vector<Function *> deadList;
  2190. for (iplist<Function>::iterator F : M.getFunctionList()) {
  2191. if (F->isDeclaration()) {
  2192. hlsl::HLOpcodeGroup group = hlsl::GetHLOpcodeGroupByName(F);
  2193. if (group != HLOpcodeGroup::NotHL || F->isIntrinsic())
  2194. if (F->user_empty())
  2195. deadList.emplace_back(F);
  2196. }
  2197. }
  2198. for (Function *F : deadList)
  2199. F->eraseFromParent();
  2200. }
  2201. static void TranslatePreciseAttributeOnFunction(Function &F, Module &M) {
  2202. BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
  2203. // Find allocas that has precise attribute, by looking at all instructions in
  2204. // the entry node
  2205. for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E;) {
  2206. Instruction *Inst = (I++);
  2207. if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst)) {
  2208. if (HLModule::HasPreciseAttributeWithMetadata(AI)) {
  2209. HLModule::MarkPreciseAttributeOnPtrWithFunctionCall(AI, M);
  2210. }
  2211. } else {
  2212. DXASSERT(!HLModule::HasPreciseAttributeWithMetadata(Inst), "Only alloca can has precise metadata.");
  2213. }
  2214. }
  2215. FastMathFlags FMF;
  2216. FMF.setUnsafeAlgebra();
  2217. // Set fast math for all FPMathOperators.
  2218. // Already set FastMath in options. But that only enable things like fadd.
  2219. // Every inst which type is float can be cast to FPMathOperator.
  2220. for (Function::iterator BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
  2221. BasicBlock *BB = BBI;
  2222. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  2223. if (FPMathOperator *FPMath = dyn_cast<FPMathOperator>(I)) {
  2224. I->copyFastMathFlags(FMF);
  2225. }
  2226. }
  2227. }
  2228. }
  2229. void DxilGenerationPass::TranslatePreciseAttribute() {
  2230. bool bIEEEStrict = m_pHLModule->GetHLOptions().bIEEEStrict;
  2231. // If IEEE strict, everying is precise, don't need to mark it.
  2232. if (bIEEEStrict)
  2233. return;
  2234. Module &M = *m_pHLModule->GetModule();
  2235. // TODO: If not inline every function, for function has call site with precise
  2236. // argument and call site without precise argument, need to clone the function
  2237. // to propagate the precise for the precise call site.
  2238. // This should be done at CGMSHLSLRuntime::FinishCodeGen.
  2239. Function *EntryFn = m_pHLModule->GetEntryFunction();
  2240. TranslatePreciseAttributeOnFunction(*EntryFn, M);
  2241. if (m_pHLModule->GetShaderModel()->IsHS()) {
  2242. HLFunctionProps &EntryQual = m_pHLModule->GetHLFunctionProps(EntryFn);
  2243. Function *patchConstantFunc = EntryQual.ShaderProps.HS.patchConstantFunc;
  2244. TranslatePreciseAttributeOnFunction(*patchConstantFunc, M);
  2245. }
  2246. }
  2247. char DxilGenerationPass::ID = 0;
  2248. ModulePass *llvm::createDxilGenerationPass(bool NotOptimized, hlsl::HLSLExtensionsCodegenHelper *extensionsHelper) {
  2249. DxilGenerationPass *dxilPass = new DxilGenerationPass(NotOptimized);
  2250. dxilPass->SetExtensionsHelper(extensionsHelper);
  2251. return dxilPass;
  2252. }
  2253. INITIALIZE_PASS(DxilGenerationPass, "dxilgen", "HLSL DXIL Generation", false, false)
  2254. ///////////////////////////////////////////////////////////////////////////////
  2255. namespace {
  2256. StructType *UpdateStructTypeForLegacyLayout(StructType *ST, bool IsCBuf,
  2257. DxilTypeSystem &TypeSys, Module &M);
  2258. Type *UpdateFieldTypeForLegacyLayout(Type *Ty, bool IsCBuf, DxilFieldAnnotation &annotation,
  2259. DxilTypeSystem &TypeSys, Module &M) {
  2260. DXASSERT(!Ty->isPointerTy(), "struct field should not be a pointer");
  2261. if (Ty->isArrayTy()) {
  2262. Type *EltTy = Ty->getArrayElementType();
  2263. Type *UpdatedTy = UpdateFieldTypeForLegacyLayout(EltTy, IsCBuf, annotation, TypeSys, M);
  2264. if (EltTy == UpdatedTy)
  2265. return Ty;
  2266. else
  2267. return ArrayType::get(UpdatedTy, Ty->getArrayNumElements());
  2268. } else if (HLMatrixLower::IsMatrixType(Ty)) {
  2269. DXASSERT(annotation.HasMatrixAnnotation(), "must a matrix");
  2270. unsigned rows, cols;
  2271. Type *EltTy = HLMatrixLower::GetMatrixInfo(Ty, cols, rows);
  2272. // Get cols and rows from annotation.
  2273. const DxilMatrixAnnotation &matrix = annotation.GetMatrixAnnotation();
  2274. if (matrix.Orientation == MatrixOrientation::RowMajor) {
  2275. rows = matrix.Rows;
  2276. cols = matrix.Cols;
  2277. } else {
  2278. DXASSERT(matrix.Orientation == MatrixOrientation::ColumnMajor, "");
  2279. cols = matrix.Rows;
  2280. rows = matrix.Cols;
  2281. }
  2282. // CBuffer matrix must 4 * 4 bytes align.
  2283. if (IsCBuf)
  2284. cols = 4;
  2285. EltTy = UpdateFieldTypeForLegacyLayout(EltTy, IsCBuf, annotation, TypeSys, M);
  2286. Type *rowTy = VectorType::get(EltTy, cols);
  2287. return ArrayType::get(rowTy, rows);
  2288. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  2289. return UpdateStructTypeForLegacyLayout(ST, IsCBuf, TypeSys, M);
  2290. } else if (Ty->isVectorTy()) {
  2291. Type *EltTy = Ty->getVectorElementType();
  2292. Type *UpdatedTy = UpdateFieldTypeForLegacyLayout(EltTy, IsCBuf, annotation, TypeSys, M);
  2293. if (EltTy == UpdatedTy)
  2294. return Ty;
  2295. else
  2296. return VectorType::get(UpdatedTy, Ty->getVectorNumElements());
  2297. } else {
  2298. Type *i32Ty = Type::getInt32Ty(Ty->getContext());
  2299. // Basic types.
  2300. if (Ty->isHalfTy()) {
  2301. return Type::getFloatTy(Ty->getContext());
  2302. } else if (IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
  2303. if (ITy->getBitWidth() <= 32)
  2304. return i32Ty;
  2305. else
  2306. return Ty;
  2307. } else
  2308. return Ty;
  2309. }
  2310. }
  2311. StructType *UpdateStructTypeForLegacyLayout(StructType *ST, bool IsCBuf,
  2312. DxilTypeSystem &TypeSys, Module &M) {
  2313. bool bUpdated = false;
  2314. unsigned fieldsCount = ST->getNumElements();
  2315. std::vector<Type *> fieldTypes(fieldsCount);
  2316. DxilStructAnnotation *SA = TypeSys.GetStructAnnotation(ST);
  2317. DXASSERT(SA, "must have annotation for struct type");
  2318. for (unsigned i = 0; i < fieldsCount; i++) {
  2319. Type *EltTy = ST->getElementType(i);
  2320. Type *UpdatedTy =
  2321. UpdateFieldTypeForLegacyLayout(EltTy, IsCBuf, SA->GetFieldAnnotation(i), TypeSys, M);
  2322. fieldTypes[i] = UpdatedTy;
  2323. if (EltTy != UpdatedTy)
  2324. bUpdated = true;
  2325. }
  2326. if (!bUpdated) {
  2327. return ST;
  2328. } else {
  2329. std::string legacyName = "dx.alignment.legacy." + ST->getName().str();
  2330. if (StructType *legacyST = M.getTypeByName(legacyName))
  2331. return legacyST;
  2332. StructType *NewST = StructType::create(ST->getContext(), fieldTypes, legacyName);
  2333. DxilStructAnnotation *NewSA = TypeSys.AddStructAnnotation(NewST);
  2334. // Clone annotation.
  2335. *NewSA = *SA;
  2336. return NewST;
  2337. }
  2338. }
  2339. void UpdateStructTypeForLegacyLayout(DxilResourceBase &Res, DxilTypeSystem &TypeSys, Module &M) {
  2340. GlobalVariable *GV = cast<GlobalVariable>(Res.GetGlobalSymbol());
  2341. Type *Ty = GV->getType()->getPointerElementType();
  2342. bool IsResourceArray = Res.GetRangeSize() != 1;
  2343. if (IsResourceArray) {
  2344. // Support Array of struct buffer.
  2345. if (Ty->isArrayTy())
  2346. Ty = Ty->getArrayElementType();
  2347. }
  2348. StructType *ST = cast<StructType>(Ty);
  2349. if (ST->isOpaque()) {
  2350. DXASSERT(Res.GetClass() == DxilResourceBase::Class::CBuffer,
  2351. "Only cbuffer can have opaque struct.");
  2352. return;
  2353. }
  2354. Type *UpdatedST = UpdateStructTypeForLegacyLayout(ST, IsResourceArray, TypeSys, M);
  2355. if (ST != UpdatedST) {
  2356. Type *Ty = GV->getType()->getPointerElementType();
  2357. if (IsResourceArray) {
  2358. // Support Array of struct buffer.
  2359. if (Ty->isArrayTy()) {
  2360. UpdatedST = ArrayType::get(UpdatedST, Ty->getArrayNumElements());
  2361. }
  2362. }
  2363. GlobalVariable *NewGV = cast<GlobalVariable>(M.getOrInsertGlobal(GV->getName().str() + "_legacy", UpdatedST));
  2364. Res.SetGlobalSymbol(NewGV);
  2365. // Delete old GV.
  2366. for (auto UserIt = GV->user_begin(); UserIt != GV->user_end(); ) {
  2367. Value *User = *(UserIt++);
  2368. if (Instruction *I = dyn_cast<Instruction>(User)) {
  2369. if (!User->user_empty())
  2370. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  2371. I->eraseFromParent();
  2372. } else {
  2373. ConstantExpr *CE = cast<ConstantExpr>(User);
  2374. if (!CE->user_empty())
  2375. CE->replaceAllUsesWith(UndefValue::get(CE->getType()));
  2376. }
  2377. }
  2378. GV->removeDeadConstantUsers();
  2379. GV->eraseFromParent();
  2380. }
  2381. }
  2382. void UpdateStructTypeForLegacyLayoutOnHLM(HLModule &HLM) {
  2383. DxilTypeSystem &TypeSys = HLM.GetTypeSystem();
  2384. Module &M = *HLM.GetModule();
  2385. for (auto &CBuf : HLM.GetCBuffers()) {
  2386. UpdateStructTypeForLegacyLayout(*CBuf.get(), TypeSys, M);
  2387. }
  2388. for (auto &UAV : HLM.GetUAVs()) {
  2389. if (UAV->GetKind() == DxilResourceBase::Kind::StructuredBuffer)
  2390. UpdateStructTypeForLegacyLayout(*UAV.get(), TypeSys, M);
  2391. }
  2392. for (auto &SRV : HLM.GetSRVs()) {
  2393. if (SRV->GetKind() == DxilResourceBase::Kind::StructuredBuffer)
  2394. UpdateStructTypeForLegacyLayout(*SRV.get(), TypeSys, M);
  2395. }
  2396. }
  2397. }
  2398. void DxilGenerationPass::UpdateStructTypeForLegacyLayout() {
  2399. UpdateStructTypeForLegacyLayoutOnHLM(*m_pHLModule);
  2400. }
  2401. ///////////////////////////////////////////////////////////////////////////////
  2402. namespace {
  2403. class HLEmitMetadata : public ModulePass {
  2404. public:
  2405. static char ID; // Pass identification, replacement for typeid
  2406. explicit HLEmitMetadata() : ModulePass(ID) {}
  2407. const char *getPassName() const override { return "HLSL High-Level Metadata Emit"; }
  2408. bool runOnModule(Module &M) override {
  2409. if (M.HasHLModule()) {
  2410. M.GetHLModule().EmitHLMetadata();
  2411. return true;
  2412. }
  2413. return false;
  2414. }
  2415. };
  2416. }
  2417. char HLEmitMetadata::ID = 0;
  2418. ModulePass *llvm::createHLEmitMetadataPass() {
  2419. return new HLEmitMetadata();
  2420. }
  2421. INITIALIZE_PASS(HLEmitMetadata, "hlsl-hlemit", "HLSL High-Level Metadata Emit", false, false)
  2422. ///////////////////////////////////////////////////////////////////////////////
  2423. namespace {
  2424. class HLEnsureMetadata : public ModulePass {
  2425. public:
  2426. static char ID; // Pass identification, replacement for typeid
  2427. explicit HLEnsureMetadata() : ModulePass(ID) {}
  2428. const char *getPassName() const override { return "HLSL High-Level Metadata Ensure"; }
  2429. bool runOnModule(Module &M) override {
  2430. if (!M.HasHLModule()) {
  2431. M.GetOrCreateHLModule();
  2432. return true;
  2433. }
  2434. return false;
  2435. }
  2436. };
  2437. }
  2438. char HLEnsureMetadata::ID = 0;
  2439. ModulePass *llvm::createHLEnsureMetadataPass() {
  2440. return new HLEnsureMetadata();
  2441. }
  2442. INITIALIZE_PASS(HLEnsureMetadata, "hlsl-hlensure", "HLSL High-Level Metadata Ensure", false, false)
  2443. ///////////////////////////////////////////////////////////////////////////////
  2444. namespace {
  2445. class DxilLoadMetadata : public ModulePass {
  2446. public:
  2447. static char ID; // Pass identification, replacement for typeid
  2448. explicit DxilLoadMetadata () : ModulePass(ID) {}
  2449. const char *getPassName() const override { return "HLSL load DxilModule from metadata"; }
  2450. bool runOnModule(Module &M) override {
  2451. if (!M.HasDxilModule()) {
  2452. (void)M.GetOrCreateDxilModule();
  2453. return true;
  2454. }
  2455. return false;
  2456. }
  2457. };
  2458. }
  2459. char DxilLoadMetadata::ID = 0;
  2460. ModulePass *llvm::createDxilLoadMetadataPass() {
  2461. return new DxilLoadMetadata();
  2462. }
  2463. INITIALIZE_PASS(DxilLoadMetadata, "hlsl-dxilload", "HLSL load DxilModule from metadata", false, false)
  2464. ///////////////////////////////////////////////////////////////////////////////
  2465. namespace {
  2466. Function *StripFunctionParameter(Function *F, DxilModule &DM,
  2467. DenseMap<const Function *, DISubprogram *> &FunctionDIs) {
  2468. Module &M = *DM.GetModule();
  2469. Type *VoidTy = Type::getVoidTy(M.getContext());
  2470. FunctionType *FT = FunctionType::get(VoidTy, false);
  2471. for (auto &arg : F->args()) {
  2472. if (!arg.user_empty())
  2473. return nullptr;
  2474. DbgDeclareInst *DDI = llvm::FindAllocaDbgDeclare(&arg);
  2475. if (DDI) {
  2476. DDI->eraseFromParent();
  2477. }
  2478. }
  2479. Function *NewFunc = Function::Create(FT, F->getLinkage(), F->getName());
  2480. M.getFunctionList().insert(F, NewFunc);
  2481. // Splice the body of the old function right into the new function.
  2482. NewFunc->getBasicBlockList().splice(NewFunc->begin(), F->getBasicBlockList());
  2483. // Patch the pointer to LLVM function in debug info descriptor.
  2484. auto DI = FunctionDIs.find(F);
  2485. if (DI != FunctionDIs.end()) {
  2486. DISubprogram *SP = DI->second;
  2487. SP->replaceFunction(NewFunc);
  2488. // Ensure the map is updated so it can be reused on subsequent argument
  2489. // promotions of the same function.
  2490. FunctionDIs.erase(DI);
  2491. FunctionDIs[NewFunc] = SP;
  2492. }
  2493. NewFunc->takeName(F);
  2494. DM.GetTypeSystem().EraseFunctionAnnotation(F);
  2495. F->eraseFromParent();
  2496. DM.GetTypeSystem().AddFunctionAnnotation(NewFunc);
  2497. return NewFunc;
  2498. }
  2499. void CheckInBoundForTGSM(GlobalVariable &GV, const DataLayout &DL) {
  2500. for (User *U : GV.users()) {
  2501. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
  2502. bool allImmIndex = true;
  2503. for (auto Idx = GEP->idx_begin(), E = GEP->idx_end(); Idx != E; Idx++) {
  2504. if (!isa<ConstantInt>(Idx)) {
  2505. allImmIndex = false;
  2506. break;
  2507. }
  2508. }
  2509. if (!allImmIndex)
  2510. GEP->setIsInBounds(false);
  2511. else {
  2512. Value *Ptr = GEP->getPointerOperand();
  2513. unsigned size =
  2514. DL.getTypeAllocSize(Ptr->getType()->getPointerElementType());
  2515. unsigned valSize =
  2516. DL.getTypeAllocSize(GEP->getType()->getPointerElementType());
  2517. SmallVector<Value *, 8> Indices(GEP->idx_begin(), GEP->idx_end());
  2518. unsigned offset =
  2519. DL.getIndexedOffset(GEP->getPointerOperandType(), Indices);
  2520. if ((offset + valSize) > size)
  2521. GEP->setIsInBounds(false);
  2522. }
  2523. }
  2524. }
  2525. }
  2526. class DxilFinalizeModule : public ModulePass {
  2527. public:
  2528. static char ID; // Pass identification, replacement for typeid
  2529. explicit DxilFinalizeModule() : ModulePass(ID) {}
  2530. const char *getPassName() const override { return "HLSL DXIL Metadata Emit"; }
  2531. void patchSM60(Module &M) {
  2532. for (iplist<Function>::iterator F : M.getFunctionList()) {
  2533. for (Function::iterator BBI = F->begin(), BBE = F->end(); BBI != BBE;
  2534. ++BBI) {
  2535. BasicBlock *BB = BBI;
  2536. for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
  2537. ++II) {
  2538. Instruction *I = II;
  2539. if (I->getMetadata(LLVMContext::MD_noalias)) {
  2540. I->setMetadata(LLVMContext::MD_noalias, nullptr);
  2541. }
  2542. }
  2543. }
  2544. }
  2545. }
  2546. bool runOnModule(Module &M) override {
  2547. if (M.HasDxilModule()) {
  2548. // Remove store undef output.
  2549. hlsl::OP *hlslOP = M.GetDxilModule().GetOP();
  2550. bool bIsSM61Plus = M.GetDxilModule().GetShaderModel()->IsSM61Plus();
  2551. if (!bIsSM61Plus) {
  2552. patchSM60(M);
  2553. }
  2554. for (iplist<Function>::iterator F : M.getFunctionList()) {
  2555. if (!hlslOP->IsDxilOpFunc(F))
  2556. continue;
  2557. // Check store output.
  2558. FunctionType *FT = F->getFunctionType();
  2559. // Num params not match.
  2560. if (FT->getNumParams() !=
  2561. (DXIL::OperandIndex::kStoreOutputValOpIdx + 1))
  2562. continue;
  2563. Type *overloadTy =
  2564. FT->getParamType(DXIL::OperandIndex::kStoreOutputValOpIdx);
  2565. // overload illegal.
  2566. if (!hlslOP->IsOverloadLegal(DXIL::OpCode::StoreOutput, overloadTy))
  2567. continue;
  2568. Function *storeOutput =
  2569. hlslOP->GetOpFunc(DXIL::OpCode::StoreOutput, overloadTy);
  2570. // Not store output.
  2571. if (storeOutput != F)
  2572. continue;
  2573. for (auto it = F->user_begin(); it != F->user_end();) {
  2574. CallInst *CI = dyn_cast<CallInst>(*(it++));
  2575. if (!CI)
  2576. continue;
  2577. Value *V =
  2578. CI->getArgOperand(DXIL::OperandIndex::kStoreOutputValOpIdx);
  2579. // Remove the store of undef.
  2580. if (isa<UndefValue>(V))
  2581. CI->eraseFromParent();
  2582. }
  2583. }
  2584. // Remove unused external functions.
  2585. std::vector<Function *> deadList;
  2586. for (iplist<Function>::iterator F : M.getFunctionList()) {
  2587. if (F->isDeclaration()) {
  2588. if (F->user_empty())
  2589. deadList.emplace_back(F);
  2590. }
  2591. }
  2592. for (Function *F : deadList)
  2593. F->eraseFromParent();
  2594. // Remove unused internal global.
  2595. std::vector<GlobalVariable *> staticGVs;
  2596. for (GlobalVariable &GV : M.globals()) {
  2597. if (HLModule::IsStaticGlobal(&GV) ||
  2598. HLModule::IsSharedMemoryGlobal(&GV)) {
  2599. staticGVs.emplace_back(&GV);
  2600. }
  2601. }
  2602. for (GlobalVariable *GV : staticGVs) {
  2603. bool onlyStoreUse = true;
  2604. for (User *user : GV->users()) {
  2605. if (isa<StoreInst>(user))
  2606. continue;
  2607. if (isa<ConstantExpr>(user) && user->user_empty())
  2608. continue;
  2609. onlyStoreUse = false;
  2610. break;
  2611. }
  2612. if (onlyStoreUse) {
  2613. for (auto UserIt = GV->user_begin(); UserIt != GV->user_end();) {
  2614. Value *User = *(UserIt++);
  2615. if (Instruction *I = dyn_cast<Instruction>(User)) {
  2616. I->eraseFromParent();
  2617. } else {
  2618. ConstantExpr *CE = cast<ConstantExpr>(User);
  2619. CE->dropAllReferences();
  2620. }
  2621. }
  2622. GV->eraseFromParent();
  2623. }
  2624. }
  2625. const DataLayout &DL = M.getDataLayout();
  2626. // Clear inbound for GEP which has none-const index.
  2627. for (GlobalVariable &GV : M.globals()) {
  2628. if (HLModule::IsSharedMemoryGlobal(&GV)) {
  2629. CheckInBoundForTGSM(GV, DL);
  2630. }
  2631. }
  2632. DxilModule &DM = M.GetDxilModule();
  2633. DenseMap<const Function *, DISubprogram *> FunctionDIs =
  2634. makeSubprogramMap(M);
  2635. if (Function *PatchConstantFunc = DM.GetPatchConstantFunction()) {
  2636. PatchConstantFunc =
  2637. StripFunctionParameter(PatchConstantFunc, DM, FunctionDIs);
  2638. if (PatchConstantFunc)
  2639. DM.SetPatchConstantFunction(PatchConstantFunc);
  2640. }
  2641. if (Function *EntryFunc = DM.GetEntryFunction()) {
  2642. StringRef Name = DM.GetEntryFunctionName();
  2643. EntryFunc->setName(Name);
  2644. EntryFunc = StripFunctionParameter(EntryFunc, DM, FunctionDIs);
  2645. if (EntryFunc)
  2646. DM.SetEntryFunction(EntryFunc);
  2647. }
  2648. DM.CollectShaderFlags(); // Update flags to reflect any changes.
  2649. // Update Validator Version
  2650. DM.UpgradeToMinValidatorVersion();
  2651. return true;
  2652. }
  2653. return false;
  2654. }
  2655. };
  2656. }
  2657. char DxilFinalizeModule::ID = 0;
  2658. ModulePass *llvm::createDxilFinalizeModulePass() {
  2659. return new DxilFinalizeModule();
  2660. }
  2661. INITIALIZE_PASS(DxilFinalizeModule, "hlsl-dxilfinalize", "HLSL DXIL Finalize Module", false, false)
  2662. ///////////////////////////////////////////////////////////////////////////////
  2663. namespace {
  2664. class DxilEmitMetadata : public ModulePass {
  2665. public:
  2666. static char ID; // Pass identification, replacement for typeid
  2667. explicit DxilEmitMetadata() : ModulePass(ID) {}
  2668. const char *getPassName() const override { return "HLSL DXIL Metadata Emit"; }
  2669. bool runOnModule(Module &M) override {
  2670. if (M.HasDxilModule()) {
  2671. M.GetDxilModule().EmitDxilMetadata();
  2672. return true;
  2673. }
  2674. return false;
  2675. }
  2676. };
  2677. }
  2678. char DxilEmitMetadata::ID = 0;
  2679. ModulePass *llvm::createDxilEmitMetadataPass() {
  2680. return new DxilEmitMetadata();
  2681. }
  2682. INITIALIZE_PASS(DxilEmitMetadata, "hlsl-dxilemit", "HLSL DXIL Metadata Emit", false, false)
  2683. ///////////////////////////////////////////////////////////////////////////////
  2684. // Precise propagate.
  2685. namespace {
  2686. class DxilPrecisePropagatePass : public ModulePass {
  2687. HLModule *m_pHLModule;
  2688. public:
  2689. static char ID; // Pass identification, replacement for typeid
  2690. explicit DxilPrecisePropagatePass() : ModulePass(ID), m_pHLModule(nullptr) {}
  2691. const char *getPassName() const override { return "DXIL Precise Propagate"; }
  2692. bool runOnModule(Module &M) override {
  2693. DxilModule &dxilModule = M.GetOrCreateDxilModule();
  2694. DxilTypeSystem &typeSys = dxilModule.GetTypeSystem();
  2695. std::vector<Function*> deadList;
  2696. for (Function &F : M.functions()) {
  2697. if (HLModule::HasPreciseAttribute(&F)) {
  2698. PropagatePreciseOnFunctionUser(F, typeSys);
  2699. deadList.emplace_back(&F);
  2700. }
  2701. }
  2702. for (Function *F : deadList)
  2703. F->eraseFromParent();
  2704. return true;
  2705. }
  2706. private:
  2707. void PropagatePreciseOnFunctionUser(Function &F, DxilTypeSystem &typeSys);
  2708. };
  2709. char DxilPrecisePropagatePass::ID = 0;
  2710. }
  2711. static void PropagatePreciseAttribute(Instruction *I, DxilTypeSystem &typeSys);
  2712. static void PropagatePreciseAttributeOnOperand(Value *V, DxilTypeSystem &typeSys, LLVMContext &Context) {
  2713. Instruction *I = dyn_cast<Instruction>(V);
  2714. // Skip none inst.
  2715. if (!I)
  2716. return;
  2717. FPMathOperator *FPMath = dyn_cast<FPMathOperator>(I);
  2718. // Skip none FPMath
  2719. if (!FPMath)
  2720. return;
  2721. // Skip inst already marked.
  2722. if (!I->hasUnsafeAlgebra())
  2723. return;
  2724. // TODO: skip precise on integer type, sample instruction...
  2725. // Clear fast math.
  2726. I->copyFastMathFlags(FastMathFlags());
  2727. // Fast math not work on call, use metadata.
  2728. if (CallInst *CI = dyn_cast<CallInst>(I))
  2729. HLModule::MarkPreciseAttributeWithMetadata(CI);
  2730. PropagatePreciseAttribute(I, typeSys);
  2731. }
  2732. static void PropagatePreciseAttributeOnPointer(Value *Ptr, DxilTypeSystem &typeSys, LLVMContext &Context) {
  2733. // Find all store and propagate on the val operand of store.
  2734. // For CallInst, if Ptr is used as out parameter, mark it.
  2735. for (User *U : Ptr->users()) {
  2736. Instruction *user = cast<Instruction>(U);
  2737. if (StoreInst *stInst = dyn_cast<StoreInst>(user)) {
  2738. Value *val = stInst->getValueOperand();
  2739. PropagatePreciseAttributeOnOperand(val, typeSys, Context);
  2740. }
  2741. else if (CallInst *CI = dyn_cast<CallInst>(user)) {
  2742. bool bReadOnly = true;
  2743. Function *F = CI->getCalledFunction();
  2744. const DxilFunctionAnnotation *funcAnnotation = typeSys.GetFunctionAnnotation(F);
  2745. for (unsigned i = 0; i < CI->getNumArgOperands(); ++i) {
  2746. if (Ptr != CI->getArgOperand(i))
  2747. continue;
  2748. const DxilParameterAnnotation &paramAnnotation =
  2749. funcAnnotation->GetParameterAnnotation(i);
  2750. // OutputPatch and OutputStream will be checked after scalar repl.
  2751. // Here only check out/inout
  2752. if (paramAnnotation.GetParamInputQual() == DxilParamInputQual::Out ||
  2753. paramAnnotation.GetParamInputQual() == DxilParamInputQual::Inout) {
  2754. bReadOnly = false;
  2755. break;
  2756. }
  2757. }
  2758. if (!bReadOnly)
  2759. PropagatePreciseAttributeOnOperand(CI, typeSys, Context);
  2760. }
  2761. }
  2762. }
  2763. static void PropagatePreciseAttribute(Instruction *I, DxilTypeSystem &typeSys) {
  2764. LLVMContext &Context = I->getContext();
  2765. if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
  2766. PropagatePreciseAttributeOnPointer(AI, typeSys, Context);
  2767. } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
  2768. // Propagate every argument.
  2769. // TODO: only propagate precise argument.
  2770. for (Value *src : I->operands())
  2771. PropagatePreciseAttributeOnOperand(src, typeSys, Context);
  2772. } else if (FPMathOperator *FPMath = dyn_cast<FPMathOperator>(I)) {
  2773. // TODO: only propagate precise argument.
  2774. for (Value *src : I->operands())
  2775. PropagatePreciseAttributeOnOperand(src, typeSys, Context);
  2776. }
  2777. else if (LoadInst *ldInst = dyn_cast<LoadInst>(I)) {
  2778. Value *Ptr = ldInst->getPointerOperand();
  2779. PropagatePreciseAttributeOnPointer(Ptr, typeSys, Context);
  2780. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
  2781. PropagatePreciseAttributeOnPointer(GEP, typeSys, Context);
  2782. // TODO: support more case which need
  2783. }
  2784. void DxilPrecisePropagatePass::PropagatePreciseOnFunctionUser(Function &F, DxilTypeSystem &typeSys) {
  2785. LLVMContext &Context = F.getContext();
  2786. for (auto U=F.user_begin(), E=F.user_end();U!=E;) {
  2787. CallInst *CI = cast<CallInst>(*(U++));
  2788. Value *V = CI->getArgOperand(0);
  2789. PropagatePreciseAttributeOnOperand(V, typeSys, Context);
  2790. CI->eraseFromParent();
  2791. }
  2792. }
  2793. ModulePass *llvm::createDxilPrecisePropagatePass() {
  2794. return new DxilPrecisePropagatePass();
  2795. }
  2796. INITIALIZE_PASS(DxilPrecisePropagatePass, "hlsl-dxil-precise", "DXIL precise attribute propagate", false, false)
  2797. ///////////////////////////////////////////////////////////////////////////////
  2798. // Legalize resource use.
  2799. // Map local or static global resource to global resource.
  2800. // Require inline for static global resource.
  2801. namespace {
  2802. class DxilLegalizeStaticResourceUsePass : public ModulePass {
  2803. public:
  2804. static char ID; // Pass identification, replacement for typeid
  2805. explicit DxilLegalizeStaticResourceUsePass()
  2806. : ModulePass(ID) {}
  2807. const char *getPassName() const override {
  2808. return "DXIL Legalize Static Resource Use";
  2809. }
  2810. bool runOnModule(Module &M) override {
  2811. HLModule &HLM = M.GetOrCreateHLModule();
  2812. OP *hlslOP = HLM.GetOP();
  2813. Type *HandleTy = hlslOP->GetHandleType();
  2814. // Promote static global variables.
  2815. PromoteStaticGlobalResources(M);
  2816. // Lower handle cast.
  2817. for (Function &F : M.functions()) {
  2818. if (!F.isDeclaration())
  2819. continue;
  2820. HLOpcodeGroup group = hlsl::GetHLOpcodeGroupByName(&F);
  2821. if (group != HLOpcodeGroup::HLCast)
  2822. continue;
  2823. Type *Ty = F.getFunctionType()->getReturnType();
  2824. if (Ty->isPointerTy())
  2825. Ty = Ty->getPointerElementType();
  2826. if (HLModule::IsHLSLObjectType(Ty)) {
  2827. TransformHandleCast(F);
  2828. }
  2829. }
  2830. Value *UndefHandle = UndefValue::get(HandleTy);
  2831. if (!UndefHandle->user_empty()) {
  2832. for (User *U : UndefHandle->users()) {
  2833. // Report error if undef handle used for function call.
  2834. if (isa<CallInst>(U)) {
  2835. M.getContext().emitError(kResourceMapErrorMsg);
  2836. }
  2837. }
  2838. }
  2839. return true;
  2840. }
  2841. private:
  2842. void PromoteStaticGlobalResources(Module &M);
  2843. void TransformHandleCast(Function &F);
  2844. };
  2845. char DxilLegalizeStaticResourceUsePass::ID = 0;
  2846. class DxilLegalizeResourceUsePass : public FunctionPass {
  2847. HLModule *m_pHLModule;
  2848. void getAnalysisUsage(AnalysisUsage &AU) const override;
  2849. public:
  2850. static char ID; // Pass identification, replacement for typeid
  2851. explicit DxilLegalizeResourceUsePass()
  2852. : FunctionPass(ID), m_pHLModule(nullptr) {}
  2853. const char *getPassName() const override {
  2854. return "DXIL Legalize Resource Use";
  2855. }
  2856. bool runOnFunction(Function &F) override {
  2857. // Promote local resource first.
  2858. PromoteLocalResource(F);
  2859. return true;
  2860. }
  2861. private:
  2862. void PromoteLocalResource(Function &F);
  2863. };
  2864. char DxilLegalizeResourceUsePass::ID = 0;
  2865. }
  2866. void DxilLegalizeResourceUsePass::getAnalysisUsage(AnalysisUsage &AU) const {
  2867. AU.addRequired<AssumptionCacheTracker>();
  2868. AU.addRequired<DominatorTreeWrapperPass>();
  2869. AU.setPreservesAll();
  2870. }
  2871. void DxilLegalizeResourceUsePass::PromoteLocalResource(Function &F) {
  2872. std::vector<AllocaInst *> Allocas;
  2873. DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  2874. AssumptionCache &AC =
  2875. getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  2876. HLModule &HLM = F.getParent()->GetOrCreateHLModule();
  2877. OP *hlslOP = HLM.GetOP();
  2878. Type *HandleTy = hlslOP->GetHandleType();
  2879. BasicBlock &BB = F.getEntryBlock();
  2880. unsigned allocaSize = 0;
  2881. while (1) {
  2882. Allocas.clear();
  2883. // Find allocas that are safe to promote, by looking at all instructions in
  2884. // the entry node
  2885. for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
  2886. if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) { // Is it an alloca?
  2887. if (HandleTy == HLModule::GetArrayEltTy(AI->getAllocatedType()))
  2888. Allocas.push_back(AI);
  2889. }
  2890. if (Allocas.empty())
  2891. break;
  2892. // No update.
  2893. // Report error and break.
  2894. if (allocaSize == Allocas.size()) {
  2895. F.getContext().emitError(kResourceMapErrorMsg);
  2896. break;
  2897. }
  2898. allocaSize = Allocas.size();
  2899. PromoteMemToReg(Allocas, *DT, nullptr, &AC);
  2900. }
  2901. return;
  2902. }
  2903. FunctionPass *llvm::createDxilLegalizeResourceUsePass() {
  2904. return new DxilLegalizeResourceUsePass();
  2905. }
  2906. INITIALIZE_PASS_BEGIN(DxilLegalizeResourceUsePass,
  2907. "hlsl-dxil-legalize-resource-use",
  2908. "DXIL legalize resource use", false, true)
  2909. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  2910. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  2911. INITIALIZE_PASS_END(DxilLegalizeResourceUsePass,
  2912. "hlsl-dxil-legalize-resource-use",
  2913. "DXIL legalize resource use", false, true)
  2914. void DxilLegalizeStaticResourceUsePass::PromoteStaticGlobalResources(
  2915. Module &M) {
  2916. HLModule &HLM = M.GetOrCreateHLModule();
  2917. Type *HandleTy = HLM.GetOP()->GetHandleType();
  2918. std::set<GlobalVariable *> staticResources;
  2919. for (auto &GV : M.globals()) {
  2920. if (GV.getLinkage() == GlobalValue::LinkageTypes::InternalLinkage &&
  2921. HandleTy == HLModule::GetArrayEltTy(GV.getType())) {
  2922. staticResources.insert(&GV);
  2923. }
  2924. }
  2925. SSAUpdater SSA;
  2926. SmallVector<Instruction *, 4> Insts;
  2927. // Make sure every resource load has mapped to global variable.
  2928. while (!staticResources.empty()) {
  2929. bool bUpdated = false;
  2930. for (auto it = staticResources.begin(); it != staticResources.end();) {
  2931. GlobalVariable *GV = *(it++);
  2932. // Build list of instructions to promote.
  2933. for (User *U : GV->users()) {
  2934. Instruction *I = cast<Instruction>(U);
  2935. Insts.emplace_back(I);
  2936. }
  2937. LoadAndStorePromoter(Insts, SSA).run(Insts);
  2938. if (GV->user_empty()) {
  2939. bUpdated = true;
  2940. staticResources.erase(GV);
  2941. }
  2942. Insts.clear();
  2943. }
  2944. if (!bUpdated) {
  2945. M.getContext().emitError(kResourceMapErrorMsg);
  2946. break;
  2947. }
  2948. }
  2949. }
  2950. static void ReplaceResUseWithHandle(Instruction *Res, Value *Handle) {
  2951. Type *HandleTy = Handle->getType();
  2952. for (auto ResU = Res->user_begin(); ResU != Res->user_end();) {
  2953. Instruction *I = cast<Instruction>(*(ResU++));
  2954. if (isa<LoadInst>(I)) {
  2955. ReplaceResUseWithHandle(I, Handle);
  2956. } else if (isa<CallInst>(I)) {
  2957. if (I->getType() == HandleTy)
  2958. I->replaceAllUsesWith(Handle);
  2959. else
  2960. DXASSERT(0, "must createHandle here");
  2961. } else {
  2962. DXASSERT(0, "should only used by load and createHandle");
  2963. }
  2964. if (I->user_empty()) {
  2965. I->eraseFromParent();
  2966. }
  2967. }
  2968. }
  2969. void DxilLegalizeStaticResourceUsePass::TransformHandleCast(Function &F) {
  2970. for (auto U = F.user_begin(); U != F.user_end(); ) {
  2971. CallInst *CI = cast<CallInst>(*(U++));
  2972. Value *Handle = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  2973. ReplaceResUseWithHandle(CI, Handle);
  2974. if (CI->user_empty())
  2975. CI->eraseFromParent();
  2976. }
  2977. }
  2978. ModulePass *llvm::createDxilLegalizeStaticResourceUsePass() {
  2979. return new DxilLegalizeStaticResourceUsePass();
  2980. }
  2981. INITIALIZE_PASS(DxilLegalizeStaticResourceUsePass,
  2982. "hlsl-dxil-legalize-static-resource-use",
  2983. "DXIL legalize static resource use", false, false)
  2984. ///////////////////////////////////////////////////////////////////////////////
  2985. // Legalize EvalOperations.
  2986. // Make sure src of EvalOperations are from function parameter.
  2987. // This is needed in order to translate EvaluateAttribute operations that traces
  2988. // back to LoadInput operations during translation stage. Promoting load/store
  2989. // instructions beforehand will allow us to easily trace back to loadInput from
  2990. // function call.
  2991. namespace {
  2992. class DxilLegalizeEvalOperations : public ModulePass {
  2993. public:
  2994. static char ID; // Pass identification, replacement for typeid
  2995. explicit DxilLegalizeEvalOperations() : ModulePass(ID) {}
  2996. const char *getPassName() const override {
  2997. return "DXIL Legalize EvalOperations";
  2998. }
  2999. bool runOnModule(Module &M) override {
  3000. for (Function &F : M.getFunctionList()) {
  3001. hlsl::HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(&F);
  3002. if (group != HLOpcodeGroup::NotHL) {
  3003. std::vector<CallInst *> EvalFunctionCalls;
  3004. // Find all EvaluateAttribute calls
  3005. for (User *U : F.users()) {
  3006. if (CallInst *CI = dyn_cast<CallInst>(U)) {
  3007. IntrinsicOp evalOp =
  3008. static_cast<IntrinsicOp>(hlsl::GetHLOpcode(CI));
  3009. if (evalOp == IntrinsicOp::IOP_EvaluateAttributeAtSample ||
  3010. evalOp == IntrinsicOp::IOP_EvaluateAttributeCentroid ||
  3011. evalOp == IntrinsicOp::IOP_EvaluateAttributeSnapped) {
  3012. EvalFunctionCalls.push_back(CI);
  3013. }
  3014. }
  3015. }
  3016. if (EvalFunctionCalls.empty()) {
  3017. continue;
  3018. }
  3019. // Start from the call instruction, find all allocas that this call
  3020. // uses.
  3021. std::unordered_set<AllocaInst *> allocas;
  3022. for (CallInst *CI : EvalFunctionCalls) {
  3023. FindAllocasForEvalOperations(CI, allocas);
  3024. }
  3025. SSAUpdater SSA;
  3026. SmallVector<Instruction *, 4> Insts;
  3027. for (AllocaInst *AI : allocas) {
  3028. for (User *user : AI->users()) {
  3029. if (isa<LoadInst>(user) || isa<StoreInst>(user)) {
  3030. Insts.emplace_back(cast<Instruction>(user));
  3031. }
  3032. }
  3033. LoadAndStorePromoter(Insts, SSA).run(Insts);
  3034. Insts.clear();
  3035. }
  3036. }
  3037. }
  3038. return true;
  3039. }
  3040. private:
  3041. void FindAllocasForEvalOperations(Value *val,
  3042. std::unordered_set<AllocaInst *> &allocas);
  3043. };
  3044. char DxilLegalizeEvalOperations::ID = 0;
  3045. // Find allocas for EvaluateAttribute operations
  3046. void DxilLegalizeEvalOperations::FindAllocasForEvalOperations(
  3047. Value *val, std::unordered_set<AllocaInst *> &allocas) {
  3048. Value *CurVal = val;
  3049. while (!isa<AllocaInst>(CurVal)) {
  3050. if (CallInst *CI = dyn_cast<CallInst>(CurVal)) {
  3051. CurVal = CI->getOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  3052. } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(CurVal)) {
  3053. Value *arg0 =
  3054. IE->getOperand(0); // Could be another insertelement or undef
  3055. Value *arg1 = IE->getOperand(1);
  3056. FindAllocasForEvalOperations(arg0, allocas);
  3057. CurVal = arg1;
  3058. } else if (ShuffleVectorInst *SV = dyn_cast<ShuffleVectorInst>(CurVal)) {
  3059. Value *arg0 = SV->getOperand(0);
  3060. Value *arg1 = SV->getOperand(1);
  3061. FindAllocasForEvalOperations(
  3062. arg0, allocas); // Shuffle vector could come from different allocas
  3063. CurVal = arg1;
  3064. } else if (ExtractElementInst *EE = dyn_cast<ExtractElementInst>(CurVal)) {
  3065. CurVal = EE->getOperand(0);
  3066. } else if (LoadInst *LI = dyn_cast<LoadInst>(CurVal)) {
  3067. CurVal = LI->getOperand(0);
  3068. } else {
  3069. break;
  3070. }
  3071. }
  3072. if (AllocaInst *AI = dyn_cast<AllocaInst>(CurVal)) {
  3073. allocas.insert(AI);
  3074. }
  3075. }
  3076. } // namespace
  3077. ModulePass *llvm::createDxilLegalizeEvalOperationsPass() {
  3078. return new DxilLegalizeEvalOperations();
  3079. }
  3080. INITIALIZE_PASS(DxilLegalizeEvalOperations,
  3081. "hlsl-dxil-legalize-eval-operations",
  3082. "DXIL legalize eval operations", false, false)