DxilModule.cpp 53 KB

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