DxilModule.cpp 56 KB

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