DxilModule.cpp 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilModule.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. ///////////////////////////////////////////////////////////////////////////////
  9. #include "dxc/Support/Global.h"
  10. #include "dxc/DXIL/DxilOperations.h"
  11. #include "dxc/DXIL/DxilModule.h"
  12. #include "dxc/DXIL/DxilConstants.h"
  13. #include "dxc/DXIL/DxilShaderModel.h"
  14. #include "dxc/DXIL/DxilSignatureElement.h"
  15. #include "dxc/DXIL/DxilFunctionProps.h"
  16. #include "dxc/Support/WinAdapter.h"
  17. #include "dxc/DXIL/DxilEntryProps.h"
  18. #include "dxc/DXIL/DxilSubobject.h"
  19. #include "llvm/IR/Constants.h"
  20. #include "llvm/IR/Function.h"
  21. #include "llvm/IR/Instructions.h"
  22. #include "llvm/IR/LLVMContext.h"
  23. #include "llvm/IR/Metadata.h"
  24. #include "llvm/IR/Module.h"
  25. #include "llvm/IR/Operator.h"
  26. #include "llvm/IR/DebugInfo.h"
  27. #include "llvm/IR/DiagnosticInfo.h"
  28. #include "llvm/IR/DiagnosticPrinter.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include "llvm/ADT/STLExtras.h"
  31. #include <unordered_set>
  32. using namespace llvm;
  33. using std::string;
  34. using std::vector;
  35. using std::unique_ptr;
  36. namespace {
  37. class DxilErrorDiagnosticInfo : public DiagnosticInfo {
  38. private:
  39. const char *m_message;
  40. public:
  41. DxilErrorDiagnosticInfo(const char *str)
  42. : DiagnosticInfo(DK_FirstPluginKind, DiagnosticSeverity::DS_Error),
  43. m_message(str) { }
  44. void print(DiagnosticPrinter &DP) const override {
  45. DP << m_message;
  46. }
  47. };
  48. } // anon namespace
  49. namespace hlsl {
  50. namespace DXIL {
  51. // Define constant variables exposed in DxilConstants.h
  52. // TODO: revisit data layout descriptions for the following:
  53. // - x64 pointers?
  54. // - Keep elf manging(m:e)?
  55. // For legacy data layout, everything less than 32 align to 32.
  56. const char* kLegacyLayoutString = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64";
  57. // New data layout with native low precision types
  58. const char* kNewLayoutString = "e-m:e-p:32:32-i1:32-i8:8-i16:16-i32:32-i64:64-f16:16-f32:32-f64:64-n8:16:32:64";
  59. // Function Attributes
  60. // TODO: consider generating attributes from hctdb
  61. const char* kFP32DenormKindString = "fp32-denorm-mode";
  62. const char* kFP32DenormValueAnyString = "any";
  63. const char* kFP32DenormValuePreserveString = "preserve";
  64. const char* kFP32DenormValueFtzString = "ftz";
  65. }
  66. // Avoid dependency on DxilModule from llvm::Module using this:
  67. void DxilModule_RemoveGlobal(llvm::Module* M, llvm::GlobalObject* G) {
  68. if (M && G && M->HasDxilModule()) {
  69. if (llvm::Function *F = dyn_cast<llvm::Function>(G))
  70. M->GetDxilModule().RemoveFunction(F);
  71. }
  72. }
  73. void DxilModule_ResetModule(llvm::Module* M) {
  74. if (M && M->HasDxilModule())
  75. delete &M->GetDxilModule();
  76. M->SetDxilModule(nullptr);
  77. }
  78. //------------------------------------------------------------------------------
  79. //
  80. // DxilModule methods.
  81. //
  82. DxilModule::DxilModule(Module *pModule)
  83. : m_StreamPrimitiveTopology(DXIL::PrimitiveTopology::Undefined)
  84. , m_ActiveStreamMask(0)
  85. , m_Ctx(pModule->getContext())
  86. , m_pModule(pModule)
  87. , m_pEntryFunc(nullptr)
  88. , m_EntryName("")
  89. , m_pMDHelper(llvm::make_unique<DxilMDHelper>(pModule, llvm::make_unique<DxilExtraPropertyHelper>(pModule)))
  90. , m_pDebugInfoFinder(nullptr)
  91. , m_pSM(nullptr)
  92. , m_DxilMajor(DXIL::kDxilMajor)
  93. , m_DxilMinor(DXIL::kDxilMinor)
  94. , m_ValMajor(1)
  95. , m_ValMinor(0)
  96. , m_pOP(llvm::make_unique<OP>(pModule->getContext(), pModule))
  97. , m_pTypeSystem(llvm::make_unique<DxilTypeSystem>(pModule))
  98. , m_bDisableOptimizations(false)
  99. , m_bUseMinPrecision(true) // use min precision by default
  100. , m_bAllResourcesBound(false)
  101. , m_IntermediateFlags(0)
  102. , m_AutoBindingSpace(UINT_MAX)
  103. , m_pSubobjects(nullptr)
  104. {
  105. DXASSERT_NOMSG(m_pModule != nullptr);
  106. m_pModule->pfnRemoveGlobal = &DxilModule_RemoveGlobal;
  107. m_pModule->pfnResetDxilModule = &DxilModule_ResetModule;
  108. #if defined(_DEBUG) || defined(DBG)
  109. // Pin LLVM dump methods.
  110. void (__thiscall Module::*pfnModuleDump)() const = &Module::dump;
  111. void (__thiscall Type::*pfnTypeDump)() const = &Type::dump;
  112. void (__thiscall Function::*pfnViewCFGOnly)() const = &Function::viewCFGOnly;
  113. m_pUnused = (char *)&pfnModuleDump - (char *)&pfnTypeDump;
  114. m_pUnused -= (size_t)&pfnViewCFGOnly;
  115. #endif
  116. }
  117. DxilModule::~DxilModule() {
  118. if (m_pModule->pfnRemoveGlobal == &DxilModule_RemoveGlobal)
  119. m_pModule->pfnRemoveGlobal = nullptr;
  120. }
  121. LLVMContext &DxilModule::GetCtx() const { return m_Ctx; }
  122. Module *DxilModule::GetModule() const { return m_pModule; }
  123. OP *DxilModule::GetOP() const { return m_pOP.get(); }
  124. void DxilModule::SetShaderModel(const ShaderModel *pSM, bool bUseMinPrecision) {
  125. DXASSERT(m_pSM == nullptr || (pSM != nullptr && *m_pSM == *pSM), "shader model must not change for the module");
  126. DXASSERT(pSM != nullptr && pSM->IsValidForDxil(), "shader model must be valid");
  127. DXASSERT(pSM->IsValidForModule(), "shader model must be valid for top-level module use");
  128. m_pSM = pSM;
  129. m_pSM->GetDxilVersion(m_DxilMajor, m_DxilMinor);
  130. m_pMDHelper->SetShaderModel(m_pSM);
  131. m_bUseMinPrecision = bUseMinPrecision;
  132. m_pOP->SetMinPrecision(m_bUseMinPrecision);
  133. m_pTypeSystem->SetMinPrecision(m_bUseMinPrecision);
  134. if (!m_pSM->IsLib()) {
  135. // Always have valid entry props for non-lib case from this point on.
  136. DxilFunctionProps props;
  137. props.shaderKind = m_pSM->GetKind();
  138. m_DxilEntryPropsMap[nullptr] =
  139. llvm::make_unique<DxilEntryProps>(props, m_bUseMinPrecision);
  140. }
  141. m_SerializedRootSignature.clear();
  142. }
  143. const ShaderModel *DxilModule::GetShaderModel() const {
  144. return m_pSM;
  145. }
  146. void DxilModule::GetDxilVersion(unsigned &DxilMajor, unsigned &DxilMinor) const {
  147. DxilMajor = m_DxilMajor;
  148. DxilMinor = m_DxilMinor;
  149. }
  150. void DxilModule::SetValidatorVersion(unsigned ValMajor, unsigned ValMinor) {
  151. m_ValMajor = ValMajor;
  152. m_ValMinor = ValMinor;
  153. }
  154. bool DxilModule::UpgradeValidatorVersion(unsigned ValMajor, unsigned ValMinor) {
  155. // Don't upgrade if validation was disabled.
  156. if (m_ValMajor == 0 && m_ValMinor == 0) {
  157. return false;
  158. }
  159. if (ValMajor > m_ValMajor || (ValMajor == m_ValMajor && ValMinor > m_ValMinor)) {
  160. // Module requires higher validator version than previously set
  161. SetValidatorVersion(ValMajor, ValMinor);
  162. return true;
  163. }
  164. return false;
  165. }
  166. void DxilModule::GetValidatorVersion(unsigned &ValMajor, unsigned &ValMinor) const {
  167. ValMajor = m_ValMajor;
  168. ValMinor = m_ValMinor;
  169. }
  170. bool DxilModule::GetMinValidatorVersion(unsigned &ValMajor, unsigned &ValMinor) const {
  171. if (!m_pSM)
  172. return false;
  173. m_pSM->GetMinValidatorVersion(ValMajor, ValMinor);
  174. if (ValMajor == 1 && ValMinor == 0 &&
  175. (m_ShaderFlags.GetFeatureInfo() & hlsl::DXIL::ShaderFeatureInfo_ViewID))
  176. ValMinor = 1;
  177. return true;
  178. }
  179. bool DxilModule::UpgradeToMinValidatorVersion() {
  180. unsigned ValMajor = 1, ValMinor = 0;
  181. if (GetMinValidatorVersion(ValMajor, ValMinor)) {
  182. return UpgradeValidatorVersion(ValMajor, ValMinor);
  183. }
  184. return false;
  185. }
  186. Function *DxilModule::GetEntryFunction() {
  187. return m_pEntryFunc;
  188. }
  189. const Function *DxilModule::GetEntryFunction() const {
  190. return m_pEntryFunc;
  191. }
  192. void DxilModule::SetEntryFunction(Function *pEntryFunc) {
  193. if (m_pSM->IsLib()) {
  194. DXASSERT(pEntryFunc == nullptr,
  195. "Otherwise, trying to set an entry function on library");
  196. m_pEntryFunc = nullptr;
  197. return;
  198. }
  199. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  200. m_pEntryFunc = pEntryFunc;
  201. // Move entry props to new function in order to preserve them.
  202. std::unique_ptr<DxilEntryProps> Props = std::move(m_DxilEntryPropsMap.begin()->second);
  203. m_DxilEntryPropsMap.clear();
  204. m_DxilEntryPropsMap[m_pEntryFunc] = std::move(Props);
  205. }
  206. const string &DxilModule::GetEntryFunctionName() const {
  207. return m_EntryName;
  208. }
  209. void DxilModule::SetEntryFunctionName(const string &name) {
  210. m_EntryName = name;
  211. }
  212. llvm::Function *DxilModule::GetPatchConstantFunction() {
  213. if (!m_pSM->IsHS())
  214. return nullptr;
  215. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  216. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  217. DXASSERT(props.IsHS(), "Must be HS profile");
  218. return props.ShaderProps.HS.patchConstantFunc;
  219. }
  220. const llvm::Function *DxilModule::GetPatchConstantFunction() const {
  221. if (!m_pSM->IsHS())
  222. return nullptr;
  223. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  224. const DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  225. DXASSERT(props.IsHS(), "Must be HS profile");
  226. return props.ShaderProps.HS.patchConstantFunc;
  227. }
  228. void DxilModule::SetPatchConstantFunction(llvm::Function *patchConstantFunc) {
  229. if (!m_pSM->IsHS())
  230. return;
  231. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  232. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  233. DXASSERT(props.IsHS(), "Must be HS profile");
  234. auto &HS = props.ShaderProps.HS;
  235. if (HS.patchConstantFunc != patchConstantFunc) {
  236. if (HS.patchConstantFunc)
  237. m_PatchConstantFunctions.erase(HS.patchConstantFunc);
  238. HS.patchConstantFunc = patchConstantFunc;
  239. if (patchConstantFunc)
  240. m_PatchConstantFunctions.insert(patchConstantFunc);
  241. }
  242. }
  243. unsigned DxilModule::GetGlobalFlags() const {
  244. unsigned Flags = m_ShaderFlags.GetGlobalFlags();
  245. return Flags;
  246. }
  247. void DxilModule::CollectShaderFlagsForModule(ShaderFlags &Flags) {
  248. for (Function &F : GetModule()->functions()) {
  249. ShaderFlags funcFlags = ShaderFlags::CollectShaderFlags(&F, this);
  250. Flags.CombineShaderFlags(funcFlags);
  251. };
  252. const ShaderModel *SM = GetShaderModel();
  253. unsigned NumUAVs = m_UAVs.size();
  254. const unsigned kSmallUAVCount = 8;
  255. if (NumUAVs > kSmallUAVCount)
  256. Flags.Set64UAVs(true);
  257. if (NumUAVs && !(SM->IsCS() || SM->IsPS()))
  258. Flags.SetUAVsAtEveryStage(true);
  259. bool hasRawAndStructuredBuffer = false;
  260. for (auto &UAV : m_UAVs) {
  261. if (UAV->IsROV())
  262. Flags.SetROVs(true);
  263. switch (UAV->GetKind()) {
  264. case DXIL::ResourceKind::RawBuffer:
  265. case DXIL::ResourceKind::StructuredBuffer:
  266. hasRawAndStructuredBuffer = true;
  267. break;
  268. default:
  269. // Not raw/structured.
  270. break;
  271. }
  272. }
  273. for (auto &SRV : m_SRVs) {
  274. switch (SRV->GetKind()) {
  275. case DXIL::ResourceKind::RawBuffer:
  276. case DXIL::ResourceKind::StructuredBuffer:
  277. hasRawAndStructuredBuffer = true;
  278. break;
  279. default:
  280. // Not raw/structured.
  281. break;
  282. }
  283. }
  284. Flags.SetEnableRawAndStructuredBuffers(hasRawAndStructuredBuffer);
  285. bool hasCSRawAndStructuredViaShader4X =
  286. hasRawAndStructuredBuffer && m_pSM->GetMajor() == 4 && m_pSM->IsCS();
  287. Flags.SetCSRawAndStructuredViaShader4X(hasCSRawAndStructuredViaShader4X);
  288. }
  289. void DxilModule::CollectShaderFlagsForModule() {
  290. CollectShaderFlagsForModule(m_ShaderFlags);
  291. }
  292. void DxilModule::SetNumThreads(unsigned x, unsigned y, unsigned z) {
  293. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsCS(),
  294. "only works for CS profile");
  295. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  296. DXASSERT(props.IsCS(), "Must be CS profile");
  297. unsigned *numThreads = props.ShaderProps.CS.numThreads;
  298. numThreads[0] = x;
  299. numThreads[1] = y;
  300. numThreads[2] = z;
  301. }
  302. unsigned DxilModule::GetNumThreads(unsigned idx) const {
  303. DXASSERT(idx < 3, "Thread dimension index must be 0-2");
  304. if (!m_pSM->IsCS())
  305. return 0;
  306. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  307. __analysis_assume(idx < 3);
  308. const DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  309. DXASSERT(props.IsCS(), "Must be CS profile");
  310. return props.ShaderProps.CS.numThreads[idx];
  311. }
  312. DXIL::InputPrimitive DxilModule::GetInputPrimitive() const {
  313. if (!m_pSM->IsGS())
  314. return DXIL::InputPrimitive::Undefined;
  315. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  316. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  317. DXASSERT(props.IsGS(), "Must be GS profile");
  318. return props.ShaderProps.GS.inputPrimitive;
  319. }
  320. void DxilModule::SetInputPrimitive(DXIL::InputPrimitive IP) {
  321. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsGS(),
  322. "only works for GS profile");
  323. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  324. DXASSERT(props.IsGS(), "Must be GS profile");
  325. auto &GS = props.ShaderProps.GS;
  326. DXASSERT_NOMSG(DXIL::InputPrimitive::Undefined < IP && IP < DXIL::InputPrimitive::LastEntry);
  327. GS.inputPrimitive = IP;
  328. }
  329. unsigned DxilModule::GetMaxVertexCount() const {
  330. if (!m_pSM->IsGS())
  331. return 0;
  332. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  333. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  334. DXASSERT(props.IsGS(), "Must be GS profile");
  335. auto &GS = props.ShaderProps.GS;
  336. DXASSERT_NOMSG(GS.maxVertexCount != 0);
  337. return GS.maxVertexCount;
  338. }
  339. void DxilModule::SetMaxVertexCount(unsigned Count) {
  340. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsGS(),
  341. "only works for GS profile");
  342. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  343. DXASSERT(props.IsGS(), "Must be GS profile");
  344. auto &GS = props.ShaderProps.GS;
  345. GS.maxVertexCount = Count;
  346. }
  347. DXIL::PrimitiveTopology DxilModule::GetStreamPrimitiveTopology() const {
  348. return m_StreamPrimitiveTopology;
  349. }
  350. void DxilModule::SetStreamPrimitiveTopology(DXIL::PrimitiveTopology Topology) {
  351. m_StreamPrimitiveTopology = Topology;
  352. SetActiveStreamMask(m_ActiveStreamMask); // Update props
  353. }
  354. bool DxilModule::HasMultipleOutputStreams() const {
  355. if (!m_pSM->IsGS()) {
  356. return false;
  357. } else {
  358. unsigned NumStreams = (m_ActiveStreamMask & 0x1) +
  359. ((m_ActiveStreamMask & 0x2) >> 1) +
  360. ((m_ActiveStreamMask & 0x4) >> 2) +
  361. ((m_ActiveStreamMask & 0x8) >> 3);
  362. DXASSERT_NOMSG(NumStreams <= DXIL::kNumOutputStreams);
  363. return NumStreams > 1;
  364. }
  365. }
  366. unsigned DxilModule::GetOutputStream() const {
  367. if (!m_pSM->IsGS()) {
  368. return 0;
  369. } else {
  370. DXASSERT_NOMSG(!HasMultipleOutputStreams());
  371. switch (m_ActiveStreamMask) {
  372. case 0x1: return 0;
  373. case 0x2: return 1;
  374. case 0x4: return 2;
  375. case 0x8: return 3;
  376. default: DXASSERT_NOMSG(false);
  377. }
  378. return (unsigned)(-1);
  379. }
  380. }
  381. unsigned DxilModule::GetGSInstanceCount() const {
  382. if (!m_pSM->IsGS())
  383. return 0;
  384. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  385. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  386. DXASSERT(props.IsGS(), "Must be GS profile");
  387. return props.ShaderProps.GS.instanceCount;
  388. }
  389. void DxilModule::SetGSInstanceCount(unsigned Count) {
  390. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsGS(),
  391. "only works for GS profile");
  392. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  393. DXASSERT(props.IsGS(), "Must be GS profile");
  394. props.ShaderProps.GS.instanceCount = Count;
  395. }
  396. bool DxilModule::IsStreamActive(unsigned Stream) const {
  397. return (m_ActiveStreamMask & (1<<Stream)) != 0;
  398. }
  399. void DxilModule::SetStreamActive(unsigned Stream, bool bActive) {
  400. if (bActive) {
  401. m_ActiveStreamMask |= (1<<Stream);
  402. } else {
  403. m_ActiveStreamMask &= ~(1<<Stream);
  404. }
  405. SetActiveStreamMask(m_ActiveStreamMask);
  406. }
  407. void DxilModule::SetActiveStreamMask(unsigned Mask) {
  408. m_ActiveStreamMask = Mask;
  409. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsGS(),
  410. "only works for GS profile");
  411. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  412. DXASSERT(props.IsGS(), "Must be GS profile");
  413. for (unsigned i = 0; i < 4; i++) {
  414. if (IsStreamActive(i))
  415. props.ShaderProps.GS.streamPrimitiveTopologies[i] = m_StreamPrimitiveTopology;
  416. else
  417. props.ShaderProps.GS.streamPrimitiveTopologies[i] = DXIL::PrimitiveTopology::Undefined;
  418. }
  419. }
  420. unsigned DxilModule::GetActiveStreamMask() const {
  421. return m_ActiveStreamMask;
  422. }
  423. bool DxilModule::GetUseMinPrecision() const {
  424. return m_bUseMinPrecision;
  425. }
  426. void DxilModule::SetDisableOptimization(bool DisableOptimization) {
  427. m_bDisableOptimizations = DisableOptimization;
  428. }
  429. bool DxilModule::GetDisableOptimization() const {
  430. return m_bDisableOptimizations;
  431. }
  432. void DxilModule::SetAllResourcesBound(bool ResourcesBound) {
  433. m_bAllResourcesBound = ResourcesBound;
  434. }
  435. bool DxilModule::GetAllResourcesBound() const {
  436. return m_bAllResourcesBound;
  437. }
  438. void DxilModule::SetLegacyResourceReservation(bool legacyResourceReservation) {
  439. m_IntermediateFlags &= ~LegacyResourceReservation;
  440. if (legacyResourceReservation) m_IntermediateFlags |= LegacyResourceReservation;
  441. }
  442. bool DxilModule::GetLegacyResourceReservation() const {
  443. return (m_IntermediateFlags & LegacyResourceReservation) != 0;
  444. }
  445. void DxilModule::ClearIntermediateOptions() {
  446. m_IntermediateFlags = 0;
  447. }
  448. unsigned DxilModule::GetInputControlPointCount() const {
  449. if (!(m_pSM->IsHS() || m_pSM->IsDS()))
  450. return 0;
  451. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  452. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  453. DXASSERT(props.IsHS() || props.IsDS(), "Must be HS or DS profile");
  454. if (props.IsHS())
  455. return props.ShaderProps.HS.inputControlPoints;
  456. else
  457. return props.ShaderProps.DS.inputControlPoints;
  458. }
  459. void DxilModule::SetInputControlPointCount(unsigned NumICPs) {
  460. DXASSERT(m_DxilEntryPropsMap.size() == 1
  461. && (m_pSM->IsHS() || m_pSM->IsDS()),
  462. "only works for non-lib profile");
  463. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  464. DXASSERT(props.IsHS() || props.IsDS(), "Must be HS or DS profile");
  465. if (props.IsHS())
  466. props.ShaderProps.HS.inputControlPoints = NumICPs;
  467. else
  468. props.ShaderProps.DS.inputControlPoints = NumICPs;
  469. }
  470. DXIL::TessellatorDomain DxilModule::GetTessellatorDomain() const {
  471. if (!(m_pSM->IsHS() || m_pSM->IsDS()))
  472. return DXIL::TessellatorDomain::Undefined;
  473. DXASSERT_NOMSG(m_DxilEntryPropsMap.size() == 1);
  474. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  475. if (props.IsHS())
  476. return props.ShaderProps.HS.domain;
  477. else
  478. return props.ShaderProps.DS.domain;
  479. }
  480. void DxilModule::SetTessellatorDomain(DXIL::TessellatorDomain TessDomain) {
  481. DXASSERT(m_DxilEntryPropsMap.size() == 1
  482. && (m_pSM->IsHS() || m_pSM->IsDS()),
  483. "only works for HS or DS profile");
  484. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  485. DXASSERT(props.IsHS() || props.IsDS(), "Must be HS or DS profile");
  486. if (props.IsHS())
  487. props.ShaderProps.HS.domain = TessDomain;
  488. else
  489. props.ShaderProps.DS.domain = TessDomain;
  490. }
  491. unsigned DxilModule::GetOutputControlPointCount() const {
  492. if (!m_pSM->IsHS())
  493. return 0;
  494. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  495. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  496. DXASSERT(props.IsHS(), "Must be HS profile");
  497. return props.ShaderProps.HS.outputControlPoints;
  498. }
  499. void DxilModule::SetOutputControlPointCount(unsigned NumOCPs) {
  500. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsHS(),
  501. "only works for HS profile");
  502. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  503. DXASSERT(props.IsHS(), "Must be HS profile");
  504. props.ShaderProps.HS.outputControlPoints = NumOCPs;
  505. }
  506. DXIL::TessellatorPartitioning DxilModule::GetTessellatorPartitioning() const {
  507. if (!m_pSM->IsHS())
  508. return DXIL::TessellatorPartitioning::Undefined;
  509. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  510. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  511. DXASSERT(props.IsHS(), "Must be HS profile");
  512. return props.ShaderProps.HS.partition;
  513. }
  514. void DxilModule::SetTessellatorPartitioning(DXIL::TessellatorPartitioning TessPartitioning) {
  515. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsHS(),
  516. "only works for HS profile");
  517. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  518. DXASSERT(props.IsHS(), "Must be HS profile");
  519. props.ShaderProps.HS.partition = TessPartitioning;
  520. }
  521. DXIL::TessellatorOutputPrimitive DxilModule::GetTessellatorOutputPrimitive() const {
  522. if (!m_pSM->IsHS())
  523. return DXIL::TessellatorOutputPrimitive::Undefined;
  524. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  525. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  526. DXASSERT(props.IsHS(), "Must be HS profile");
  527. return props.ShaderProps.HS.outputPrimitive;
  528. }
  529. void DxilModule::SetTessellatorOutputPrimitive(DXIL::TessellatorOutputPrimitive TessOutputPrimitive) {
  530. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsHS(),
  531. "only works for HS profile");
  532. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  533. DXASSERT(props.IsHS(), "Must be HS profile");
  534. props.ShaderProps.HS.outputPrimitive = TessOutputPrimitive;
  535. }
  536. float DxilModule::GetMaxTessellationFactor() const {
  537. if (!m_pSM->IsHS())
  538. return 0.0F;
  539. DXASSERT(m_DxilEntryPropsMap.size() == 1, "should have one entry prop");
  540. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  541. DXASSERT(props.IsHS(), "Must be HS profile");
  542. return props.ShaderProps.HS.maxTessFactor;
  543. }
  544. void DxilModule::SetMaxTessellationFactor(float MaxTessellationFactor) {
  545. DXASSERT(m_DxilEntryPropsMap.size() == 1 && m_pSM->IsHS(),
  546. "only works for HS profile");
  547. DxilFunctionProps &props = m_DxilEntryPropsMap.begin()->second->props;
  548. DXASSERT(props.IsHS(), "Must be HS profile");
  549. props.ShaderProps.HS.maxTessFactor = MaxTessellationFactor;
  550. }
  551. void DxilModule::SetAutoBindingSpace(uint32_t Space) {
  552. m_AutoBindingSpace = Space;
  553. }
  554. uint32_t DxilModule::GetAutoBindingSpace() const {
  555. return m_AutoBindingSpace;
  556. }
  557. void DxilModule::SetShaderProperties(DxilFunctionProps *props) {
  558. if (!props)
  559. return;
  560. DxilFunctionProps &ourProps = GetDxilFunctionProps(GetEntryFunction());
  561. if (props != &ourProps) {
  562. ourProps.shaderKind = props->shaderKind;
  563. ourProps.ShaderProps = props->ShaderProps;
  564. }
  565. switch (props->shaderKind) {
  566. case DXIL::ShaderKind::Pixel: {
  567. auto &PS = props->ShaderProps.PS;
  568. m_ShaderFlags.SetForceEarlyDepthStencil(PS.EarlyDepthStencil);
  569. } break;
  570. case DXIL::ShaderKind::Compute:
  571. case DXIL::ShaderKind::Domain:
  572. case DXIL::ShaderKind::Hull:
  573. case DXIL::ShaderKind::Vertex:
  574. break;
  575. default: {
  576. DXASSERT(props->shaderKind == DXIL::ShaderKind::Geometry,
  577. "else invalid shader kind");
  578. auto &GS = props->ShaderProps.GS;
  579. m_ActiveStreamMask = 0;
  580. for (size_t i = 0; i < _countof(GS.streamPrimitiveTopologies); ++i) {
  581. if (GS.streamPrimitiveTopologies[i] !=
  582. DXIL::PrimitiveTopology::Undefined) {
  583. m_ActiveStreamMask |= (1 << i);
  584. DXASSERT_NOMSG(m_StreamPrimitiveTopology ==
  585. DXIL::PrimitiveTopology::Undefined ||
  586. m_StreamPrimitiveTopology ==
  587. GS.streamPrimitiveTopologies[i]);
  588. m_StreamPrimitiveTopology = GS.streamPrimitiveTopologies[i];
  589. }
  590. }
  591. // Refresh props:
  592. SetActiveStreamMask(m_ActiveStreamMask);
  593. } break;
  594. }
  595. }
  596. template<typename T> unsigned
  597. DxilModule::AddResource(vector<unique_ptr<T> > &Vec, unique_ptr<T> pRes) {
  598. DXASSERT_NOMSG((unsigned)Vec.size() < UINT_MAX);
  599. unsigned Id = (unsigned)Vec.size();
  600. Vec.emplace_back(std::move(pRes));
  601. return Id;
  602. }
  603. unsigned DxilModule::AddCBuffer(unique_ptr<DxilCBuffer> pCB) {
  604. return AddResource<DxilCBuffer>(m_CBuffers, std::move(pCB));
  605. }
  606. DxilCBuffer &DxilModule::GetCBuffer(unsigned idx) {
  607. return *m_CBuffers[idx];
  608. }
  609. const DxilCBuffer &DxilModule::GetCBuffer(unsigned idx) const {
  610. return *m_CBuffers[idx];
  611. }
  612. const vector<unique_ptr<DxilCBuffer> > &DxilModule::GetCBuffers() const {
  613. return m_CBuffers;
  614. }
  615. unsigned DxilModule::AddSampler(unique_ptr<DxilSampler> pSampler) {
  616. return AddResource<DxilSampler>(m_Samplers, std::move(pSampler));
  617. }
  618. DxilSampler &DxilModule::GetSampler(unsigned idx) {
  619. return *m_Samplers[idx];
  620. }
  621. const DxilSampler &DxilModule::GetSampler(unsigned idx) const {
  622. return *m_Samplers[idx];
  623. }
  624. const vector<unique_ptr<DxilSampler> > &DxilModule::GetSamplers() const {
  625. return m_Samplers;
  626. }
  627. unsigned DxilModule::AddSRV(unique_ptr<DxilResource> pSRV) {
  628. return AddResource<DxilResource>(m_SRVs, std::move(pSRV));
  629. }
  630. DxilResource &DxilModule::GetSRV(unsigned idx) {
  631. return *m_SRVs[idx];
  632. }
  633. const DxilResource &DxilModule::GetSRV(unsigned idx) const {
  634. return *m_SRVs[idx];
  635. }
  636. const vector<unique_ptr<DxilResource> > &DxilModule::GetSRVs() const {
  637. return m_SRVs;
  638. }
  639. unsigned DxilModule::AddUAV(unique_ptr<DxilResource> pUAV) {
  640. return AddResource<DxilResource>(m_UAVs, std::move(pUAV));
  641. }
  642. DxilResource &DxilModule::GetUAV(unsigned idx) {
  643. return *m_UAVs[idx];
  644. }
  645. const DxilResource &DxilModule::GetUAV(unsigned idx) const {
  646. return *m_UAVs[idx];
  647. }
  648. const vector<unique_ptr<DxilResource> > &DxilModule::GetUAVs() const {
  649. return m_UAVs;
  650. }
  651. void DxilModule::LoadDxilResourceBaseFromMDNode(MDNode *MD, DxilResourceBase &R) {
  652. return m_pMDHelper->LoadDxilResourceBaseFromMDNode(MD, R);
  653. }
  654. void DxilModule::LoadDxilResourceFromMDNode(llvm::MDNode *MD, DxilResource &R) {
  655. return m_pMDHelper->LoadDxilResourceFromMDNode(MD, R);
  656. }
  657. void DxilModule::LoadDxilSamplerFromMDNode(llvm::MDNode *MD, DxilSampler &S) {
  658. return m_pMDHelper->LoadDxilSamplerFromMDNode(MD, S);
  659. }
  660. template <typename TResource>
  661. static void RemoveResources(std::vector<std::unique_ptr<TResource>> &vec,
  662. std::unordered_set<unsigned> &immResID) {
  663. for (auto p = vec.begin(); p != vec.end();) {
  664. auto c = p++;
  665. if (immResID.count((*c)->GetID()) == 0) {
  666. p = vec.erase(c);
  667. }
  668. }
  669. }
  670. static void CollectUsedResource(Value *resID,
  671. std::unordered_set<Value *> &usedResID) {
  672. if (usedResID.count(resID) > 0)
  673. return;
  674. usedResID.insert(resID);
  675. if (dyn_cast<ConstantInt>(resID)) {
  676. // Do nothing
  677. } else if (ZExtInst *ZEI = dyn_cast<ZExtInst>(resID)) {
  678. if (ZEI->getSrcTy()->isIntegerTy()) {
  679. IntegerType *ITy = cast<IntegerType>(ZEI->getSrcTy());
  680. if (ITy->getBitWidth() == 1) {
  681. usedResID.insert(ConstantInt::get(ZEI->getDestTy(), 0));
  682. usedResID.insert(ConstantInt::get(ZEI->getDestTy(), 1));
  683. }
  684. }
  685. } else if (SelectInst *SI = dyn_cast<SelectInst>(resID)) {
  686. CollectUsedResource(SI->getTrueValue(), usedResID);
  687. CollectUsedResource(SI->getFalseValue(), usedResID);
  688. } else if (PHINode *Phi = dyn_cast<PHINode>(resID)) {
  689. for (Use &U : Phi->incoming_values()) {
  690. CollectUsedResource(U.get(), usedResID);
  691. }
  692. }
  693. // TODO: resID could be other types of instructions depending on the compiler optimization.
  694. }
  695. static void ConvertUsedResource(std::unordered_set<unsigned> &immResID,
  696. std::unordered_set<Value *> &usedResID) {
  697. for (Value *V : usedResID) {
  698. if (ConstantInt *cResID = dyn_cast<ConstantInt>(V)) {
  699. immResID.insert(cResID->getLimitedValue());
  700. }
  701. }
  702. }
  703. void DxilModule::RemoveFunction(llvm::Function *F) {
  704. DXASSERT_NOMSG(F != nullptr);
  705. m_DxilEntryPropsMap.erase(F);
  706. if (m_pTypeSystem.get()->GetFunctionAnnotation(F))
  707. m_pTypeSystem.get()->EraseFunctionAnnotation(F);
  708. m_pOP->RemoveFunction(F);
  709. }
  710. void DxilModule::RemoveUnusedResources() {
  711. DXASSERT(!m_pSM->IsLib(), "this function does not work on libraries");
  712. hlsl::OP *hlslOP = GetOP();
  713. Function *createHandleFunc = hlslOP->GetOpFunc(DXIL::OpCode::CreateHandle, Type::getVoidTy(GetCtx()));
  714. if (createHandleFunc->user_empty()) {
  715. m_CBuffers.clear();
  716. m_UAVs.clear();
  717. m_SRVs.clear();
  718. m_Samplers.clear();
  719. createHandleFunc->eraseFromParent();
  720. return;
  721. }
  722. std::unordered_set<Value *> usedUAVID;
  723. std::unordered_set<Value *> usedSRVID;
  724. std::unordered_set<Value *> usedSamplerID;
  725. std::unordered_set<Value *> usedCBufID;
  726. // Collect used ID.
  727. for (User *U : createHandleFunc->users()) {
  728. CallInst *CI = cast<CallInst>(U);
  729. Value *vResClass =
  730. CI->getArgOperand(DXIL::OperandIndex::kCreateHandleResClassOpIdx);
  731. ConstantInt *cResClass = cast<ConstantInt>(vResClass);
  732. DXIL::ResourceClass resClass =
  733. static_cast<DXIL::ResourceClass>(cResClass->getLimitedValue());
  734. // Skip unused resource handle.
  735. if (CI->user_empty())
  736. continue;
  737. Value *resID =
  738. CI->getArgOperand(DXIL::OperandIndex::kCreateHandleResIDOpIdx);
  739. switch (resClass) {
  740. case DXIL::ResourceClass::CBuffer:
  741. CollectUsedResource(resID, usedCBufID);
  742. break;
  743. case DXIL::ResourceClass::Sampler:
  744. CollectUsedResource(resID, usedSamplerID);
  745. break;
  746. case DXIL::ResourceClass::SRV:
  747. CollectUsedResource(resID, usedSRVID);
  748. break;
  749. case DXIL::ResourceClass::UAV:
  750. CollectUsedResource(resID, usedUAVID);
  751. break;
  752. default:
  753. DXASSERT(0, "invalid res class");
  754. break;
  755. }
  756. }
  757. std::unordered_set<unsigned> immUAVID;
  758. std::unordered_set<unsigned> immSRVID;
  759. std::unordered_set<unsigned> immSamplerID;
  760. std::unordered_set<unsigned> immCBufID;
  761. ConvertUsedResource(immUAVID, usedUAVID);
  762. ConvertUsedResource(immSRVID, usedSRVID);
  763. ConvertUsedResource(immSamplerID, usedSamplerID);
  764. ConvertUsedResource(immCBufID, usedCBufID);
  765. RemoveResources(m_UAVs, immUAVID);
  766. RemoveResources(m_SRVs, immSRVID);
  767. RemoveResources(m_Samplers, immSamplerID);
  768. RemoveResources(m_CBuffers, immCBufID);
  769. }
  770. namespace {
  771. template <typename TResource>
  772. static void RemoveResourcesWithUnusedSymbolsHelper(std::vector<std::unique_ptr<TResource>> &vec) {
  773. unsigned resID = 0;
  774. for (auto p = vec.begin(); p != vec.end();) {
  775. auto c = p++;
  776. Constant *symbol = (*c)->GetGlobalSymbol();
  777. symbol->removeDeadConstantUsers();
  778. if (symbol->user_empty()) {
  779. p = vec.erase(c);
  780. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(symbol))
  781. GV->eraseFromParent();
  782. continue;
  783. }
  784. if ((*c)->GetID() != resID) {
  785. (*c)->SetID(resID);
  786. }
  787. resID++;
  788. }
  789. }
  790. }
  791. void DxilModule::RemoveResourcesWithUnusedSymbols() {
  792. RemoveResourcesWithUnusedSymbolsHelper(m_SRVs);
  793. RemoveResourcesWithUnusedSymbolsHelper(m_UAVs);
  794. RemoveResourcesWithUnusedSymbolsHelper(m_CBuffers);
  795. RemoveResourcesWithUnusedSymbolsHelper(m_Samplers);
  796. }
  797. DxilSignature &DxilModule::GetInputSignature() {
  798. DXASSERT(m_DxilEntryPropsMap.size() == 1 && !m_pSM->IsLib(),
  799. "only works for non-lib profile");
  800. return m_DxilEntryPropsMap.begin()->second->sig.InputSignature;
  801. }
  802. const DxilSignature &DxilModule::GetInputSignature() const {
  803. DXASSERT(m_DxilEntryPropsMap.size() == 1 && !m_pSM->IsLib(),
  804. "only works for non-lib profile");
  805. return m_DxilEntryPropsMap.begin()->second->sig.InputSignature;
  806. }
  807. DxilSignature &DxilModule::GetOutputSignature() {
  808. DXASSERT(m_DxilEntryPropsMap.size() == 1 && !m_pSM->IsLib(),
  809. "only works for non-lib profile");
  810. return m_DxilEntryPropsMap.begin()->second->sig.OutputSignature;
  811. }
  812. const DxilSignature &DxilModule::GetOutputSignature() const {
  813. DXASSERT(m_DxilEntryPropsMap.size() == 1 && !m_pSM->IsLib(),
  814. "only works for non-lib profile");
  815. return m_DxilEntryPropsMap.begin()->second->sig.OutputSignature;
  816. }
  817. DxilSignature &DxilModule::GetPatchConstantSignature() {
  818. DXASSERT(m_DxilEntryPropsMap.size() == 1 && !m_pSM->IsLib(),
  819. "only works for non-lib profile");
  820. return m_DxilEntryPropsMap.begin()->second->sig.PatchConstantSignature;
  821. }
  822. const DxilSignature &DxilModule::GetPatchConstantSignature() const {
  823. DXASSERT(m_DxilEntryPropsMap.size() == 1 && !m_pSM->IsLib(),
  824. "only works for non-lib profile");
  825. return m_DxilEntryPropsMap.begin()->second->sig.PatchConstantSignature;
  826. }
  827. const std::vector<uint8_t> &DxilModule::GetSerializedRootSignature() const {
  828. return m_SerializedRootSignature;
  829. }
  830. std::vector<uint8_t> &DxilModule::GetSerializedRootSignature() {
  831. return m_SerializedRootSignature;
  832. }
  833. // Entry props.
  834. bool DxilModule::HasDxilEntrySignature(const llvm::Function *F) const {
  835. return m_DxilEntryPropsMap.find(F) != m_DxilEntryPropsMap.end();
  836. }
  837. DxilEntrySignature &DxilModule::GetDxilEntrySignature(const llvm::Function *F) {
  838. DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
  839. return m_DxilEntryPropsMap[F].get()->sig;
  840. }
  841. void DxilModule::ReplaceDxilEntryProps(llvm::Function *F,
  842. llvm::Function *NewF) {
  843. DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
  844. std::unique_ptr<DxilEntryProps> Props = std::move(m_DxilEntryPropsMap[F]);
  845. m_DxilEntryPropsMap.erase(F);
  846. m_DxilEntryPropsMap[NewF] = std::move(Props);
  847. }
  848. void DxilModule::CloneDxilEntryProps(llvm::Function *F, llvm::Function *NewF) {
  849. DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
  850. std::unique_ptr<DxilEntryProps> Props =
  851. llvm::make_unique<DxilEntryProps>(*m_DxilEntryPropsMap[F]);
  852. m_DxilEntryPropsMap[NewF] = std::move(Props);
  853. }
  854. bool DxilModule::HasDxilEntryProps(const llvm::Function *F) const {
  855. return m_DxilEntryPropsMap.find(F) != m_DxilEntryPropsMap.end();
  856. }
  857. DxilEntryProps &DxilModule::GetDxilEntryProps(const llvm::Function *F) {
  858. DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
  859. return *m_DxilEntryPropsMap.find(F)->second.get();
  860. }
  861. const DxilEntryProps &DxilModule::GetDxilEntryProps(const llvm::Function *F) const {
  862. DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
  863. return *m_DxilEntryPropsMap.find(F)->second.get();
  864. }
  865. bool DxilModule::HasDxilFunctionProps(const llvm::Function *F) const {
  866. return m_DxilEntryPropsMap.find(F) != m_DxilEntryPropsMap.end();
  867. }
  868. DxilFunctionProps &DxilModule::GetDxilFunctionProps(const llvm::Function *F) {
  869. return const_cast<DxilFunctionProps &>(
  870. static_cast<const DxilModule *>(this)->GetDxilFunctionProps(F));
  871. }
  872. const DxilFunctionProps &
  873. DxilModule::GetDxilFunctionProps(const llvm::Function *F) const {
  874. DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
  875. return m_DxilEntryPropsMap.find(F)->second.get()->props;
  876. }
  877. void DxilModule::SetPatchConstantFunctionForHS(llvm::Function *hullShaderFunc, llvm::Function *patchConstantFunc) {
  878. auto propIter = m_DxilEntryPropsMap.find(hullShaderFunc);
  879. DXASSERT(propIter != m_DxilEntryPropsMap.end(),
  880. "Hull shader must already have function props!");
  881. DxilFunctionProps &props = propIter->second->props;
  882. DXASSERT(props.IsHS(), "else hullShaderFunc is not a Hull Shader");
  883. auto &HS = props.ShaderProps.HS;
  884. if (HS.patchConstantFunc != patchConstantFunc) {
  885. if (HS.patchConstantFunc)
  886. m_PatchConstantFunctions.erase(HS.patchConstantFunc);
  887. HS.patchConstantFunc = patchConstantFunc;
  888. if (patchConstantFunc)
  889. m_PatchConstantFunctions.insert(patchConstantFunc);
  890. }
  891. }
  892. bool DxilModule::IsGraphicsShader(const llvm::Function *F) const {
  893. return HasDxilFunctionProps(F) && GetDxilFunctionProps(F).IsGraphics();
  894. }
  895. bool DxilModule::IsPatchConstantShader(const llvm::Function *F) const {
  896. return m_PatchConstantFunctions.count(F) != 0;
  897. }
  898. bool DxilModule::IsComputeShader(const llvm::Function *F) const {
  899. return HasDxilFunctionProps(F) && GetDxilFunctionProps(F).IsCS();
  900. }
  901. bool DxilModule::IsEntryThatUsesSignatures(const llvm::Function *F) const {
  902. auto propIter = m_DxilEntryPropsMap.find(F);
  903. if (propIter != m_DxilEntryPropsMap.end()) {
  904. DxilFunctionProps &props = propIter->second->props;
  905. return props.IsGraphics() || props.IsCS();
  906. }
  907. // Otherwise, return true if patch constant function
  908. return IsPatchConstantShader(F);
  909. }
  910. bool DxilModule::StripRootSignatureFromMetadata() {
  911. NamedMDNode *pRootSignatureNamedMD = GetModule()->getNamedMetadata(DxilMDHelper::kDxilRootSignatureMDName);
  912. if (pRootSignatureNamedMD) {
  913. GetModule()->eraseNamedMetadata(pRootSignatureNamedMD);
  914. return true;
  915. }
  916. return false;
  917. }
  918. DxilSubobjects *DxilModule::GetSubobjects() {
  919. return m_pSubobjects.get();
  920. }
  921. const DxilSubobjects *DxilModule::GetSubobjects() const {
  922. return m_pSubobjects.get();
  923. }
  924. DxilSubobjects *DxilModule::ReleaseSubobjects() {
  925. return m_pSubobjects.release();
  926. }
  927. void DxilModule::ResetSubobjects(DxilSubobjects *subobjects) {
  928. m_pSubobjects.reset(subobjects);
  929. }
  930. bool DxilModule::StripSubobjectsFromMetadata() {
  931. NamedMDNode *pSubobjectsNamedMD = GetModule()->getNamedMetadata(DxilMDHelper::kDxilSubobjectsMDName);
  932. if (pSubobjectsNamedMD) {
  933. GetModule()->eraseNamedMetadata(pSubobjectsNamedMD);
  934. return true;
  935. }
  936. return false;
  937. }
  938. void DxilModule::UpdateValidatorVersionMetadata() {
  939. m_pMDHelper->EmitValidatorVersion(m_ValMajor, m_ValMinor);
  940. }
  941. void DxilModule::ResetSerializedRootSignature(std::vector<uint8_t> &Value) {
  942. m_SerializedRootSignature.clear();
  943. m_SerializedRootSignature.reserve(Value.size());
  944. m_SerializedRootSignature.assign(Value.begin(), Value.end());
  945. }
  946. DxilTypeSystem &DxilModule::GetTypeSystem() {
  947. return *m_pTypeSystem;
  948. }
  949. std::vector<unsigned> &DxilModule::GetSerializedViewIdState() {
  950. return m_SerializedState;
  951. }
  952. const std::vector<unsigned> &DxilModule::GetSerializedViewIdState() const {
  953. return m_SerializedState;
  954. }
  955. void DxilModule::ResetTypeSystem(DxilTypeSystem *pValue) {
  956. m_pTypeSystem.reset(pValue);
  957. }
  958. void DxilModule::ResetOP(hlsl::OP *hlslOP) { m_pOP.reset(hlslOP); }
  959. void DxilModule::ResetEntryPropsMap(DxilEntryPropsMap &&PropMap) {
  960. m_DxilEntryPropsMap.clear();
  961. std::move(PropMap.begin(), PropMap.end(),
  962. inserter(m_DxilEntryPropsMap, m_DxilEntryPropsMap.begin()));
  963. }
  964. static const StringRef llvmUsedName = "llvm.used";
  965. void DxilModule::EmitLLVMUsed() {
  966. if (GlobalVariable *oldGV = m_pModule->getGlobalVariable(llvmUsedName)) {
  967. oldGV->eraseFromParent();
  968. }
  969. if (m_LLVMUsed.empty())
  970. return;
  971. vector<llvm::Constant *> GVs;
  972. Type *pI8PtrType = Type::getInt8PtrTy(m_Ctx, DXIL::kDefaultAddrSpace);
  973. GVs.resize(m_LLVMUsed.size());
  974. for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
  975. Constant *pConst = cast<Constant>(&*m_LLVMUsed[i]);
  976. PointerType *pPtrType = dyn_cast<PointerType>(pConst->getType());
  977. if (pPtrType->getPointerAddressSpace() != DXIL::kDefaultAddrSpace) {
  978. // Cast pointer to addrspace 0, as LLVMUsed elements must have the same
  979. // type.
  980. GVs[i] = ConstantExpr::getAddrSpaceCast(pConst, pI8PtrType);
  981. } else {
  982. GVs[i] = ConstantExpr::getPointerCast(pConst, pI8PtrType);
  983. }
  984. }
  985. ArrayType *pATy = ArrayType::get(pI8PtrType, GVs.size());
  986. GlobalVariable *pGV =
  987. new GlobalVariable(*m_pModule, pATy, false, GlobalValue::AppendingLinkage,
  988. ConstantArray::get(pATy, GVs), llvmUsedName);
  989. pGV->setSection("llvm.metadata");
  990. }
  991. void DxilModule::ClearLLVMUsed() {
  992. if (GlobalVariable *oldGV = m_pModule->getGlobalVariable(llvmUsedName)) {
  993. oldGV->eraseFromParent();
  994. }
  995. if (m_LLVMUsed.empty())
  996. return;
  997. for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
  998. Constant *pConst = cast<Constant>(&*m_LLVMUsed[i]);
  999. pConst->removeDeadConstantUsers();
  1000. }
  1001. m_LLVMUsed.clear();
  1002. }
  1003. vector<GlobalVariable* > &DxilModule::GetLLVMUsed() {
  1004. return m_LLVMUsed;
  1005. }
  1006. // DXIL metadata serialization/deserialization.
  1007. void DxilModule::ClearDxilMetadata(Module &M) {
  1008. // Delete: DXIL version, validator version, DXIL shader model,
  1009. // entry point tuples (shader properties, signatures, resources)
  1010. // type system, view ID state, LLVM used, entry point tuples,
  1011. // root signature, function properties.
  1012. // Other cases for libs pending.
  1013. // LLVM used is a global variable - handle separately.
  1014. SmallVector<NamedMDNode*, 8> nodes;
  1015. for (NamedMDNode &b : M.named_metadata()) {
  1016. StringRef name = b.getName();
  1017. if (name == DxilMDHelper::kDxilVersionMDName ||
  1018. name == DxilMDHelper::kDxilValidatorVersionMDName ||
  1019. name == DxilMDHelper::kDxilShaderModelMDName ||
  1020. name == DxilMDHelper::kDxilEntryPointsMDName ||
  1021. name == DxilMDHelper::kDxilRootSignatureMDName ||
  1022. name == DxilMDHelper::kDxilIntermediateOptionsMDName ||
  1023. name == DxilMDHelper::kDxilResourcesMDName ||
  1024. name == DxilMDHelper::kDxilTypeSystemMDName ||
  1025. name == DxilMDHelper::kDxilViewIdStateMDName ||
  1026. name == DxilMDHelper::kDxilSubobjectsMDName ||
  1027. name.startswith(DxilMDHelper::kDxilTypeSystemHelperVariablePrefix)) {
  1028. nodes.push_back(&b);
  1029. }
  1030. }
  1031. for (size_t i = 0; i < nodes.size(); ++i) {
  1032. M.eraseNamedMetadata(nodes[i]);
  1033. }
  1034. }
  1035. void DxilModule::EmitDxilMetadata() {
  1036. m_pMDHelper->EmitDxilVersion(m_DxilMajor, m_DxilMinor);
  1037. m_pMDHelper->EmitValidatorVersion(m_ValMajor, m_ValMinor);
  1038. m_pMDHelper->EmitDxilShaderModel(m_pSM);
  1039. m_pMDHelper->EmitDxilIntermediateOptions(m_IntermediateFlags);
  1040. MDTuple *pMDProperties = nullptr;
  1041. uint64_t flag = m_ShaderFlags.GetShaderFlagsRaw();
  1042. if (m_pSM->IsLib()) {
  1043. DxilFunctionProps props;
  1044. props.shaderKind = DXIL::ShaderKind::Library;
  1045. pMDProperties = m_pMDHelper->EmitDxilEntryProperties(flag, props,
  1046. GetAutoBindingSpace());
  1047. } else {
  1048. pMDProperties = m_pMDHelper->EmitDxilEntryProperties(
  1049. flag, m_DxilEntryPropsMap.begin()->second->props,
  1050. GetAutoBindingSpace());
  1051. }
  1052. MDTuple *pMDSignatures = nullptr;
  1053. if (!m_pSM->IsLib()) {
  1054. pMDSignatures = m_pMDHelper->EmitDxilSignatures(
  1055. m_DxilEntryPropsMap.begin()->second->sig);
  1056. }
  1057. MDTuple *pMDResources = EmitDxilResources();
  1058. if (pMDResources)
  1059. m_pMDHelper->EmitDxilResources(pMDResources);
  1060. m_pMDHelper->EmitDxilTypeSystem(GetTypeSystem(), m_LLVMUsed);
  1061. if (!m_pSM->IsLib() && !m_pSM->IsCS() &&
  1062. ((m_ValMajor == 0 && m_ValMinor == 0) ||
  1063. (m_ValMajor > 1 || (m_ValMajor == 1 && m_ValMinor >= 1)))) {
  1064. m_pMDHelper->EmitDxilViewIdState(m_SerializedState);
  1065. }
  1066. EmitLLVMUsed();
  1067. MDTuple *pEntry = m_pMDHelper->EmitDxilEntryPointTuple(GetEntryFunction(), m_EntryName, pMDSignatures, pMDResources, pMDProperties);
  1068. vector<MDNode *> Entries;
  1069. Entries.emplace_back(pEntry);
  1070. if (m_pSM->IsLib()) {
  1071. // Sort functions by name to keep metadata deterministic
  1072. vector<const Function *> funcOrder;
  1073. funcOrder.reserve(m_DxilEntryPropsMap.size());
  1074. std::transform( m_DxilEntryPropsMap.begin(),
  1075. m_DxilEntryPropsMap.end(),
  1076. std::back_inserter(funcOrder),
  1077. [](const std::pair<const llvm::Function * const, std::unique_ptr<DxilEntryProps>> &p) -> const Function* { return p.first; } );
  1078. std::sort(funcOrder.begin(), funcOrder.end(), [](const Function *F1, const Function *F2) {
  1079. return F1->getName() < F2->getName();
  1080. });
  1081. for (auto F : funcOrder) {
  1082. auto &entryProps = m_DxilEntryPropsMap[F];
  1083. MDTuple *pProps = m_pMDHelper->EmitDxilEntryProperties(0, entryProps->props, 0);
  1084. MDTuple *pSig = m_pMDHelper->EmitDxilSignatures(entryProps->sig);
  1085. MDTuple *pSubEntry = m_pMDHelper->EmitDxilEntryPointTuple(
  1086. const_cast<Function *>(F), F->getName(), pSig, nullptr, pProps);
  1087. Entries.emplace_back(pSubEntry);
  1088. }
  1089. funcOrder.clear();
  1090. // Save Subobjects
  1091. if (GetSubobjects()) {
  1092. m_pMDHelper->EmitSubobjects(*GetSubobjects());
  1093. }
  1094. }
  1095. m_pMDHelper->EmitDxilEntryPoints(Entries);
  1096. if (!m_SerializedRootSignature.empty()) {
  1097. m_pMDHelper->EmitRootSignature(m_SerializedRootSignature);
  1098. }
  1099. }
  1100. bool DxilModule::IsKnownNamedMetaData(llvm::NamedMDNode &Node) {
  1101. return DxilMDHelper::IsKnownNamedMetaData(Node);
  1102. }
  1103. void DxilModule::LoadDxilMetadata() {
  1104. m_pMDHelper->LoadDxilVersion(m_DxilMajor, m_DxilMinor);
  1105. m_pMDHelper->LoadValidatorVersion(m_ValMajor, m_ValMinor);
  1106. const ShaderModel *loadedSM;
  1107. m_pMDHelper->LoadDxilShaderModel(loadedSM);
  1108. m_pMDHelper->LoadDxilIntermediateOptions(m_IntermediateFlags);
  1109. // This must be set before LoadDxilEntryProperties
  1110. m_pMDHelper->SetShaderModel(loadedSM);
  1111. // Setting module shader model requires UseMinPrecision flag,
  1112. // which requires loading m_ShaderFlags,
  1113. // which requires global entry properties,
  1114. // so load entry properties first, then set the shader model
  1115. const llvm::NamedMDNode *pEntries = m_pMDHelper->GetDxilEntryPoints();
  1116. if (!loadedSM->IsLib()) {
  1117. IFTBOOL(pEntries->getNumOperands() == 1, DXC_E_INCORRECT_DXIL_METADATA);
  1118. }
  1119. Function *pEntryFunc;
  1120. string EntryName;
  1121. const llvm::MDOperand *pEntrySignatures, *pEntryResources, *pEntryProperties;
  1122. m_pMDHelper->GetDxilEntryPoint(pEntries->getOperand(0),
  1123. pEntryFunc, EntryName,
  1124. pEntrySignatures, pEntryResources,
  1125. pEntryProperties);
  1126. uint64_t rawShaderFlags = 0;
  1127. DxilFunctionProps entryFuncProps;
  1128. entryFuncProps.shaderKind = loadedSM->GetKind();
  1129. m_pMDHelper->LoadDxilEntryProperties(*pEntryProperties, rawShaderFlags,
  1130. entryFuncProps, m_AutoBindingSpace);
  1131. m_bUseMinPrecision = true;
  1132. if (rawShaderFlags) {
  1133. m_ShaderFlags.SetShaderFlagsRaw(rawShaderFlags);
  1134. m_bUseMinPrecision = !m_ShaderFlags.GetUseNativeLowPrecision();
  1135. m_bDisableOptimizations = m_ShaderFlags.GetDisableOptimizations();
  1136. m_bAllResourcesBound = m_ShaderFlags.GetAllResourcesBound();
  1137. }
  1138. // Now that we have the UseMinPrecision flag, set shader model:
  1139. SetShaderModel(loadedSM, m_bUseMinPrecision);
  1140. if (loadedSM->IsLib()) {
  1141. for (unsigned i = 1; i < pEntries->getNumOperands(); i++) {
  1142. Function *pFunc;
  1143. string Name;
  1144. const llvm::MDOperand *pSignatures, *pResources, *pProperties;
  1145. m_pMDHelper->GetDxilEntryPoint(pEntries->getOperand(i), pFunc, Name,
  1146. pSignatures, pResources, pProperties);
  1147. DxilFunctionProps props;
  1148. uint64_t rawShaderFlags = 0;
  1149. unsigned autoBindingSpace = 0;
  1150. m_pMDHelper->LoadDxilEntryProperties(
  1151. *pProperties, rawShaderFlags, props, autoBindingSpace);
  1152. if (props.IsHS() && props.ShaderProps.HS.patchConstantFunc) {
  1153. // Add patch constant function to m_PatchConstantFunctions
  1154. m_PatchConstantFunctions.insert(props.ShaderProps.HS.patchConstantFunc);
  1155. }
  1156. std::unique_ptr<DxilEntryProps> pEntryProps =
  1157. llvm::make_unique<DxilEntryProps>(props, m_bUseMinPrecision);
  1158. m_pMDHelper->LoadDxilSignatures(*pSignatures, pEntryProps->sig);
  1159. m_DxilEntryPropsMap[pFunc] = std::move(pEntryProps);
  1160. }
  1161. // Load Subobjects
  1162. std::unique_ptr<DxilSubobjects> pSubobjects(new DxilSubobjects());
  1163. m_pMDHelper->LoadSubobjects(*pSubobjects);
  1164. if (pSubobjects->GetSubobjects().size()) {
  1165. ResetSubobjects(pSubobjects.release());
  1166. }
  1167. } else {
  1168. std::unique_ptr<DxilEntryProps> pEntryProps =
  1169. llvm::make_unique<DxilEntryProps>(entryFuncProps, m_bUseMinPrecision);
  1170. DxilFunctionProps *pFuncProps = &pEntryProps->props;
  1171. m_pMDHelper->LoadDxilSignatures(*pEntrySignatures, pEntryProps->sig);
  1172. m_DxilEntryPropsMap.clear();
  1173. m_DxilEntryPropsMap[pEntryFunc] = std::move(pEntryProps);
  1174. SetEntryFunction(pEntryFunc);
  1175. SetEntryFunctionName(EntryName);
  1176. SetShaderProperties(pFuncProps);
  1177. }
  1178. LoadDxilResources(*pEntryResources);
  1179. m_pMDHelper->LoadDxilTypeSystem(*m_pTypeSystem.get());
  1180. m_pMDHelper->LoadRootSignature(m_SerializedRootSignature);
  1181. m_pMDHelper->LoadDxilViewIdState(m_SerializedState);
  1182. }
  1183. MDTuple *DxilModule::EmitDxilResources() {
  1184. // Emit SRV records.
  1185. MDTuple *pTupleSRVs = nullptr;
  1186. if (!m_SRVs.empty()) {
  1187. vector<Metadata *> MDVals;
  1188. for (size_t i = 0; i < m_SRVs.size(); i++) {
  1189. MDVals.emplace_back(m_pMDHelper->EmitDxilSRV(*m_SRVs[i]));
  1190. }
  1191. pTupleSRVs = MDNode::get(m_Ctx, MDVals);
  1192. }
  1193. // Emit UAV records.
  1194. MDTuple *pTupleUAVs = nullptr;
  1195. if (!m_UAVs.empty()) {
  1196. vector<Metadata *> MDVals;
  1197. for (size_t i = 0; i < m_UAVs.size(); i++) {
  1198. MDVals.emplace_back(m_pMDHelper->EmitDxilUAV(*m_UAVs[i]));
  1199. }
  1200. pTupleUAVs = MDNode::get(m_Ctx, MDVals);
  1201. }
  1202. // Emit CBuffer records.
  1203. MDTuple *pTupleCBuffers = nullptr;
  1204. if (!m_CBuffers.empty()) {
  1205. vector<Metadata *> MDVals;
  1206. for (size_t i = 0; i < m_CBuffers.size(); i++) {
  1207. MDVals.emplace_back(m_pMDHelper->EmitDxilCBuffer(*m_CBuffers[i]));
  1208. }
  1209. pTupleCBuffers = MDNode::get(m_Ctx, MDVals);
  1210. }
  1211. // Emit Sampler records.
  1212. MDTuple *pTupleSamplers = nullptr;
  1213. if (!m_Samplers.empty()) {
  1214. vector<Metadata *> MDVals;
  1215. for (size_t i = 0; i < m_Samplers.size(); i++) {
  1216. MDVals.emplace_back(m_pMDHelper->EmitDxilSampler(*m_Samplers[i]));
  1217. }
  1218. pTupleSamplers = MDNode::get(m_Ctx, MDVals);
  1219. }
  1220. if (pTupleSRVs != nullptr || pTupleUAVs != nullptr || pTupleCBuffers != nullptr || pTupleSamplers != nullptr) {
  1221. return m_pMDHelper->EmitDxilResourceTuple(pTupleSRVs, pTupleUAVs, pTupleCBuffers, pTupleSamplers);
  1222. } else {
  1223. return nullptr;
  1224. }
  1225. }
  1226. void DxilModule::ReEmitDxilResources() {
  1227. ClearDxilMetadata(*m_pModule);
  1228. EmitDxilMetadata();
  1229. }
  1230. template <typename TResource>
  1231. static void
  1232. StripResourcesReflection(std::vector<std::unique_ptr<TResource>> &vec) {
  1233. for (auto &p : vec) {
  1234. p->SetGlobalName("");
  1235. // Cannot remove global symbol which used by validation.
  1236. }
  1237. }
  1238. void DxilModule::StripReflection() {
  1239. // Remove names.
  1240. for (Function &F : m_pModule->functions()) {
  1241. for (BasicBlock &BB : F) {
  1242. if (BB.hasName())
  1243. BB.setName("");
  1244. for (Instruction &I : BB) {
  1245. if (I.hasName())
  1246. I.setName("");
  1247. }
  1248. }
  1249. }
  1250. // Remove struct annotation.
  1251. // FunctionAnnotation is used later, so keep it.
  1252. m_pTypeSystem->GetStructAnnotationMap().clear();
  1253. // Resource
  1254. if (!GetShaderModel()->IsLib()) {
  1255. StripResourcesReflection(m_CBuffers);
  1256. StripResourcesReflection(m_UAVs);
  1257. StripResourcesReflection(m_SRVs);
  1258. StripResourcesReflection(m_Samplers);
  1259. }
  1260. // Unused global.
  1261. SmallVector<GlobalVariable *,2> UnusedGlobals;
  1262. for (GlobalVariable &GV : m_pModule->globals()) {
  1263. if (GV.use_empty())
  1264. UnusedGlobals.emplace_back(&GV);
  1265. }
  1266. for (GlobalVariable *GV : UnusedGlobals) {
  1267. GV->eraseFromParent();
  1268. }
  1269. // ReEmit meta.
  1270. ReEmitDxilResources();
  1271. }
  1272. void DxilModule::LoadDxilResources(const llvm::MDOperand &MDO) {
  1273. if (MDO.get() == nullptr)
  1274. return;
  1275. const llvm::MDTuple *pSRVs, *pUAVs, *pCBuffers, *pSamplers;
  1276. m_pMDHelper->GetDxilResources(MDO, pSRVs, pUAVs, pCBuffers, pSamplers);
  1277. // Load SRV records.
  1278. if (pSRVs != nullptr) {
  1279. for (unsigned i = 0; i < pSRVs->getNumOperands(); i++) {
  1280. unique_ptr<DxilResource> pSRV(new DxilResource);
  1281. m_pMDHelper->LoadDxilSRV(pSRVs->getOperand(i), *pSRV);
  1282. AddSRV(std::move(pSRV));
  1283. }
  1284. }
  1285. // Load UAV records.
  1286. if (pUAVs != nullptr) {
  1287. for (unsigned i = 0; i < pUAVs->getNumOperands(); i++) {
  1288. unique_ptr<DxilResource> pUAV(new DxilResource);
  1289. m_pMDHelper->LoadDxilUAV(pUAVs->getOperand(i), *pUAV);
  1290. AddUAV(std::move(pUAV));
  1291. }
  1292. }
  1293. // Load CBuffer records.
  1294. if (pCBuffers != nullptr) {
  1295. for (unsigned i = 0; i < pCBuffers->getNumOperands(); i++) {
  1296. unique_ptr<DxilCBuffer> pCB(new DxilCBuffer);
  1297. m_pMDHelper->LoadDxilCBuffer(pCBuffers->getOperand(i), *pCB);
  1298. AddCBuffer(std::move(pCB));
  1299. }
  1300. }
  1301. // Load Sampler records.
  1302. if (pSamplers != nullptr) {
  1303. for (unsigned i = 0; i < pSamplers->getNumOperands(); i++) {
  1304. unique_ptr<DxilSampler> pSampler(new DxilSampler);
  1305. m_pMDHelper->LoadDxilSampler(pSamplers->getOperand(i), *pSampler);
  1306. AddSampler(std::move(pSampler));
  1307. }
  1308. }
  1309. }
  1310. void DxilModule::StripDebugRelatedCode() {
  1311. // Remove all users of global resources.
  1312. for (GlobalVariable &GV : m_pModule->globals()) {
  1313. if (GV.hasInternalLinkage())
  1314. continue;
  1315. if (GV.getType()->getPointerAddressSpace() == DXIL::kTGSMAddrSpace)
  1316. continue;
  1317. for (auto git = GV.user_begin(); git != GV.user_end();) {
  1318. User *U = *(git++);
  1319. // Try to remove load of GV.
  1320. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  1321. for (auto it = LI->user_begin(); it != LI->user_end();) {
  1322. Instruction *LIUser = cast<Instruction>(*(it++));
  1323. if (StoreInst *SI = dyn_cast<StoreInst>(LIUser)) {
  1324. Value *Ptr = SI->getPointerOperand();
  1325. SI->eraseFromParent();
  1326. if (Instruction *PtrInst = dyn_cast<Instruction>(Ptr)) {
  1327. if (Ptr->user_empty())
  1328. PtrInst->eraseFromParent();
  1329. }
  1330. }
  1331. }
  1332. if (LI->user_empty())
  1333. LI->eraseFromParent();
  1334. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
  1335. for (auto GEPIt = GEP->user_begin(); GEPIt != GEP->user_end();) {
  1336. User *GEPU = *(GEPIt++);
  1337. // Try to remove load of GEP.
  1338. if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
  1339. for (auto it = LI->user_begin(); it != LI->user_end();) {
  1340. Instruction *LIUser = cast<Instruction>(*(it++));
  1341. if (StoreInst *SI = dyn_cast<StoreInst>(LIUser)) {
  1342. Value *Ptr = SI->getPointerOperand();
  1343. SI->eraseFromParent();
  1344. if (Instruction *PtrInst = dyn_cast<Instruction>(Ptr)) {
  1345. if (Ptr->user_empty())
  1346. PtrInst->eraseFromParent();
  1347. }
  1348. }
  1349. if (LI->user_empty())
  1350. LI->eraseFromParent();
  1351. }
  1352. }
  1353. }
  1354. if (GEP->user_empty())
  1355. GEP->eraseFromParent();
  1356. }
  1357. }
  1358. }
  1359. // Remove dx.source metadata.
  1360. if (NamedMDNode *contents = m_pModule->getNamedMetadata(
  1361. DxilMDHelper::kDxilSourceContentsMDName)) {
  1362. contents->eraseFromParent();
  1363. }
  1364. if (NamedMDNode *defines =
  1365. m_pModule->getNamedMetadata(DxilMDHelper::kDxilSourceDefinesMDName)) {
  1366. defines->eraseFromParent();
  1367. }
  1368. if (NamedMDNode *mainFileName = m_pModule->getNamedMetadata(
  1369. DxilMDHelper::kDxilSourceMainFileNameMDName)) {
  1370. mainFileName->eraseFromParent();
  1371. }
  1372. if (NamedMDNode *arguments =
  1373. m_pModule->getNamedMetadata(DxilMDHelper::kDxilSourceArgsMDName)) {
  1374. arguments->eraseFromParent();
  1375. }
  1376. }
  1377. DebugInfoFinder &DxilModule::GetOrCreateDebugInfoFinder() {
  1378. if (m_pDebugInfoFinder == nullptr) {
  1379. m_pDebugInfoFinder = llvm::make_unique<llvm::DebugInfoFinder>();
  1380. m_pDebugInfoFinder->processModule(*m_pModule);
  1381. }
  1382. return *m_pDebugInfoFinder;
  1383. }
  1384. hlsl::DxilModule *hlsl::DxilModule::TryGetDxilModule(llvm::Module *pModule) {
  1385. LLVMContext &Ctx = pModule->getContext();
  1386. std::string diagStr;
  1387. raw_string_ostream diagStream(diagStr);
  1388. hlsl::DxilModule *pDxilModule = nullptr;
  1389. // TODO: add detail error in DxilMDHelper.
  1390. try {
  1391. pDxilModule = &pModule->GetOrCreateDxilModule();
  1392. } catch (const ::hlsl::Exception &hlslException) {
  1393. diagStream << "load dxil metadata failed -";
  1394. try {
  1395. const char *msg = hlslException.what();
  1396. if (msg == nullptr || *msg == '\0')
  1397. diagStream << " error code " << hlslException.hr << "\n";
  1398. else
  1399. diagStream << msg;
  1400. } catch (...) {
  1401. diagStream << " unable to retrieve error message.\n";
  1402. }
  1403. Ctx.diagnose(DxilErrorDiagnosticInfo(diagStream.str().c_str()));
  1404. } catch (...) {
  1405. Ctx.diagnose(DxilErrorDiagnosticInfo("load dxil metadata failed - unknown error.\n"));
  1406. }
  1407. return pDxilModule;
  1408. }
  1409. // Check if the instruction has fast math flags configured to indicate
  1410. // the instruction is precise.
  1411. // Precise fast math flags means none of the fast math flags are set.
  1412. bool DxilModule::HasPreciseFastMathFlags(const Instruction *inst) {
  1413. return isa<FPMathOperator>(inst) && !inst->getFastMathFlags().any();
  1414. }
  1415. // Set fast math flags configured to indicate the instruction is precise.
  1416. void DxilModule::SetPreciseFastMathFlags(llvm::Instruction *inst) {
  1417. assert(isa<FPMathOperator>(inst));
  1418. inst->copyFastMathFlags(FastMathFlags());
  1419. }
  1420. // True if fast math flags are preserved across serialization/deserialization
  1421. // of the dxil module.
  1422. //
  1423. // We need to check for this when querying fast math flags for preciseness
  1424. // otherwise we will be overly conservative by reporting instructions precise
  1425. // because their fast math flags were not preserved.
  1426. //
  1427. // Currently we restrict it to the instruction types that have fast math
  1428. // preserved in the bitcode. We can expand this by converting fast math
  1429. // flags to dx.precise metadata during serialization and back to fast
  1430. // math flags during deserialization.
  1431. bool DxilModule::PreservesFastMathFlags(const llvm::Instruction *inst) {
  1432. return
  1433. isa<FPMathOperator>(inst) && (isa<BinaryOperator>(inst) || isa<FCmpInst>(inst));
  1434. }
  1435. bool DxilModule::IsPrecise(const Instruction *inst) const {
  1436. if (m_ShaderFlags.GetDisableMathRefactoring())
  1437. return true;
  1438. else if (DxilMDHelper::IsMarkedPrecise(inst))
  1439. return true;
  1440. else if (PreservesFastMathFlags(inst))
  1441. return HasPreciseFastMathFlags(inst);
  1442. else
  1443. return false;
  1444. }
  1445. } // namespace hlsl
  1446. namespace llvm {
  1447. hlsl::DxilModule &Module::GetOrCreateDxilModule(bool skipInit) {
  1448. std::unique_ptr<hlsl::DxilModule> M;
  1449. if (!HasDxilModule()) {
  1450. M = llvm::make_unique<hlsl::DxilModule>(this);
  1451. if (!skipInit) {
  1452. M->LoadDxilMetadata();
  1453. }
  1454. SetDxilModule(M.release());
  1455. }
  1456. return GetDxilModule();
  1457. }
  1458. }