DxilModule.cpp 54 KB

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