DxilModule.cpp 54 KB

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