DxilModule.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607
  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. // Entry props.
  831. bool DxilModule::HasDxilEntrySignature(const llvm::Function *F) const {
  832. return m_DxilEntryPropsMap.find(F) != m_DxilEntryPropsMap.end();
  833. }
  834. DxilEntrySignature &DxilModule::GetDxilEntrySignature(const llvm::Function *F) {
  835. DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
  836. return m_DxilEntryPropsMap[F].get()->sig;
  837. }
  838. void DxilModule::ReplaceDxilEntryProps(llvm::Function *F,
  839. llvm::Function *NewF) {
  840. DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
  841. std::unique_ptr<DxilEntryProps> Props = std::move(m_DxilEntryPropsMap[F]);
  842. m_DxilEntryPropsMap.erase(F);
  843. m_DxilEntryPropsMap[NewF] = std::move(Props);
  844. }
  845. void DxilModule::CloneDxilEntryProps(llvm::Function *F, llvm::Function *NewF) {
  846. DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
  847. std::unique_ptr<DxilEntryProps> Props =
  848. llvm::make_unique<DxilEntryProps>(*m_DxilEntryPropsMap[F]);
  849. m_DxilEntryPropsMap[NewF] = std::move(Props);
  850. }
  851. bool DxilModule::HasDxilEntryProps(const llvm::Function *F) const {
  852. return m_DxilEntryPropsMap.find(F) != m_DxilEntryPropsMap.end();
  853. }
  854. DxilEntryProps &DxilModule::GetDxilEntryProps(const llvm::Function *F) {
  855. DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
  856. return *m_DxilEntryPropsMap.find(F)->second.get();
  857. }
  858. const DxilEntryProps &DxilModule::GetDxilEntryProps(const llvm::Function *F) const {
  859. DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
  860. return *m_DxilEntryPropsMap.find(F)->second.get();
  861. }
  862. bool DxilModule::HasDxilFunctionProps(const llvm::Function *F) const {
  863. return m_DxilEntryPropsMap.find(F) != m_DxilEntryPropsMap.end();
  864. }
  865. DxilFunctionProps &DxilModule::GetDxilFunctionProps(const llvm::Function *F) {
  866. return const_cast<DxilFunctionProps &>(
  867. static_cast<const DxilModule *>(this)->GetDxilFunctionProps(F));
  868. }
  869. const DxilFunctionProps &
  870. DxilModule::GetDxilFunctionProps(const llvm::Function *F) const {
  871. DXASSERT(m_DxilEntryPropsMap.count(F) != 0, "cannot find F in map");
  872. return m_DxilEntryPropsMap.find(F)->second.get()->props;
  873. }
  874. void DxilModule::SetPatchConstantFunctionForHS(llvm::Function *hullShaderFunc, llvm::Function *patchConstantFunc) {
  875. auto propIter = m_DxilEntryPropsMap.find(hullShaderFunc);
  876. DXASSERT(propIter != m_DxilEntryPropsMap.end(),
  877. "Hull shader must already have function props!");
  878. DxilFunctionProps &props = propIter->second->props;
  879. DXASSERT(props.IsHS(), "else hullShaderFunc is not a Hull Shader");
  880. auto &HS = props.ShaderProps.HS;
  881. if (HS.patchConstantFunc != patchConstantFunc) {
  882. if (HS.patchConstantFunc)
  883. m_PatchConstantFunctions.erase(HS.patchConstantFunc);
  884. HS.patchConstantFunc = patchConstantFunc;
  885. if (patchConstantFunc)
  886. m_PatchConstantFunctions.insert(patchConstantFunc);
  887. }
  888. }
  889. bool DxilModule::IsGraphicsShader(const llvm::Function *F) const {
  890. return HasDxilFunctionProps(F) && GetDxilFunctionProps(F).IsGraphics();
  891. }
  892. bool DxilModule::IsPatchConstantShader(const llvm::Function *F) const {
  893. return m_PatchConstantFunctions.count(F) != 0;
  894. }
  895. bool DxilModule::IsComputeShader(const llvm::Function *F) const {
  896. return HasDxilFunctionProps(F) && GetDxilFunctionProps(F).IsCS();
  897. }
  898. bool DxilModule::IsEntryThatUsesSignatures(const llvm::Function *F) const {
  899. auto propIter = m_DxilEntryPropsMap.find(F);
  900. if (propIter != m_DxilEntryPropsMap.end()) {
  901. DxilFunctionProps &props = propIter->second->props;
  902. return props.IsGraphics() || props.IsCS();
  903. }
  904. // Otherwise, return true if patch constant function
  905. return IsPatchConstantShader(F);
  906. }
  907. bool DxilModule::StripRootSignatureFromMetadata() {
  908. NamedMDNode *pRootSignatureNamedMD = GetModule()->getNamedMetadata(DxilMDHelper::kDxilRootSignatureMDName);
  909. if (pRootSignatureNamedMD) {
  910. GetModule()->eraseNamedMetadata(pRootSignatureNamedMD);
  911. return true;
  912. }
  913. return false;
  914. }
  915. DxilSubobjects *DxilModule::GetSubobjects() {
  916. return m_pSubobjects.get();
  917. }
  918. const DxilSubobjects *DxilModule::GetSubobjects() const {
  919. return m_pSubobjects.get();
  920. }
  921. DxilSubobjects *DxilModule::ReleaseSubobjects() {
  922. return m_pSubobjects.release();
  923. }
  924. void DxilModule::ResetSubobjects(DxilSubobjects *subobjects) {
  925. m_pSubobjects.reset(subobjects);
  926. }
  927. bool DxilModule::StripSubobjectsFromMetadata() {
  928. NamedMDNode *pSubobjectsNamedMD = GetModule()->getNamedMetadata(DxilMDHelper::kDxilSubobjectsMDName);
  929. if (pSubobjectsNamedMD) {
  930. GetModule()->eraseNamedMetadata(pSubobjectsNamedMD);
  931. return true;
  932. }
  933. return false;
  934. }
  935. void DxilModule::UpdateValidatorVersionMetadata() {
  936. m_pMDHelper->EmitValidatorVersion(m_ValMajor, m_ValMinor);
  937. }
  938. void DxilModule::ResetSerializedRootSignature(std::vector<uint8_t> &Value) {
  939. m_SerializedRootSignature.clear();
  940. m_SerializedRootSignature.reserve(Value.size());
  941. m_SerializedRootSignature.assign(Value.begin(), Value.end());
  942. }
  943. DxilTypeSystem &DxilModule::GetTypeSystem() {
  944. return *m_pTypeSystem;
  945. }
  946. std::vector<unsigned> &DxilModule::GetSerializedViewIdState() {
  947. return m_SerializedState;
  948. }
  949. const std::vector<unsigned> &DxilModule::GetSerializedViewIdState() const {
  950. return m_SerializedState;
  951. }
  952. void DxilModule::ResetTypeSystem(DxilTypeSystem *pValue) {
  953. m_pTypeSystem.reset(pValue);
  954. }
  955. void DxilModule::ResetOP(hlsl::OP *hlslOP) { m_pOP.reset(hlslOP); }
  956. void DxilModule::ResetEntryPropsMap(DxilEntryPropsMap &&PropMap) {
  957. m_DxilEntryPropsMap.clear();
  958. std::move(PropMap.begin(), PropMap.end(),
  959. inserter(m_DxilEntryPropsMap, m_DxilEntryPropsMap.begin()));
  960. }
  961. static const StringRef llvmUsedName = "llvm.used";
  962. void DxilModule::EmitLLVMUsed() {
  963. if (GlobalVariable *oldGV = m_pModule->getGlobalVariable(llvmUsedName)) {
  964. oldGV->eraseFromParent();
  965. }
  966. if (m_LLVMUsed.empty())
  967. return;
  968. vector<llvm::Constant *> GVs;
  969. Type *pI8PtrType = Type::getInt8PtrTy(m_Ctx, DXIL::kDefaultAddrSpace);
  970. GVs.resize(m_LLVMUsed.size());
  971. for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
  972. Constant *pConst = cast<Constant>(&*m_LLVMUsed[i]);
  973. PointerType *pPtrType = dyn_cast<PointerType>(pConst->getType());
  974. if (pPtrType->getPointerAddressSpace() != DXIL::kDefaultAddrSpace) {
  975. // Cast pointer to addrspace 0, as LLVMUsed elements must have the same
  976. // type.
  977. GVs[i] = ConstantExpr::getAddrSpaceCast(pConst, pI8PtrType);
  978. } else {
  979. GVs[i] = ConstantExpr::getPointerCast(pConst, pI8PtrType);
  980. }
  981. }
  982. ArrayType *pATy = ArrayType::get(pI8PtrType, GVs.size());
  983. GlobalVariable *pGV =
  984. new GlobalVariable(*m_pModule, pATy, false, GlobalValue::AppendingLinkage,
  985. ConstantArray::get(pATy, GVs), llvmUsedName);
  986. pGV->setSection("llvm.metadata");
  987. }
  988. void DxilModule::ClearLLVMUsed() {
  989. if (GlobalVariable *oldGV = m_pModule->getGlobalVariable(llvmUsedName)) {
  990. oldGV->eraseFromParent();
  991. }
  992. if (m_LLVMUsed.empty())
  993. return;
  994. for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
  995. Constant *pConst = cast<Constant>(&*m_LLVMUsed[i]);
  996. pConst->removeDeadConstantUsers();
  997. }
  998. m_LLVMUsed.clear();
  999. }
  1000. vector<GlobalVariable* > &DxilModule::GetLLVMUsed() {
  1001. return m_LLVMUsed;
  1002. }
  1003. // DXIL metadata serialization/deserialization.
  1004. void DxilModule::ClearDxilMetadata(Module &M) {
  1005. // Delete: DXIL version, validator version, DXIL shader model,
  1006. // entry point tuples (shader properties, signatures, resources)
  1007. // type system, view ID state, LLVM used, entry point tuples,
  1008. // root signature, function properties.
  1009. // Other cases for libs pending.
  1010. // LLVM used is a global variable - handle separately.
  1011. SmallVector<NamedMDNode*, 8> nodes;
  1012. for (NamedMDNode &b : M.named_metadata()) {
  1013. StringRef name = b.getName();
  1014. if (name == DxilMDHelper::kDxilVersionMDName ||
  1015. name == DxilMDHelper::kDxilValidatorVersionMDName ||
  1016. name == DxilMDHelper::kDxilShaderModelMDName ||
  1017. name == DxilMDHelper::kDxilEntryPointsMDName ||
  1018. name == DxilMDHelper::kDxilRootSignatureMDName ||
  1019. name == DxilMDHelper::kDxilIntermediateOptionsMDName ||
  1020. name == DxilMDHelper::kDxilResourcesMDName ||
  1021. name == DxilMDHelper::kDxilTypeSystemMDName ||
  1022. name == DxilMDHelper::kDxilViewIdStateMDName ||
  1023. name == DxilMDHelper::kDxilSubobjectsMDName ||
  1024. name.startswith(DxilMDHelper::kDxilTypeSystemHelperVariablePrefix)) {
  1025. nodes.push_back(&b);
  1026. }
  1027. }
  1028. for (size_t i = 0; i < nodes.size(); ++i) {
  1029. M.eraseNamedMetadata(nodes[i]);
  1030. }
  1031. }
  1032. void DxilModule::EmitDxilMetadata() {
  1033. m_pMDHelper->EmitDxilVersion(m_DxilMajor, m_DxilMinor);
  1034. m_pMDHelper->EmitValidatorVersion(m_ValMajor, m_ValMinor);
  1035. m_pMDHelper->EmitDxilShaderModel(m_pSM);
  1036. m_pMDHelper->EmitDxilIntermediateOptions(m_IntermediateFlags);
  1037. MDTuple *pMDProperties = nullptr;
  1038. uint64_t flag = m_ShaderFlags.GetShaderFlagsRaw();
  1039. if (m_pSM->IsLib()) {
  1040. DxilFunctionProps props;
  1041. props.shaderKind = DXIL::ShaderKind::Library;
  1042. pMDProperties = m_pMDHelper->EmitDxilEntryProperties(flag, props,
  1043. GetAutoBindingSpace());
  1044. } else {
  1045. pMDProperties = m_pMDHelper->EmitDxilEntryProperties(
  1046. flag, m_DxilEntryPropsMap.begin()->second->props,
  1047. GetAutoBindingSpace());
  1048. }
  1049. MDTuple *pMDSignatures = nullptr;
  1050. if (!m_pSM->IsLib()) {
  1051. pMDSignatures = m_pMDHelper->EmitDxilSignatures(
  1052. m_DxilEntryPropsMap.begin()->second->sig);
  1053. }
  1054. MDTuple *pMDResources = EmitDxilResources();
  1055. if (pMDResources)
  1056. m_pMDHelper->EmitDxilResources(pMDResources);
  1057. m_pMDHelper->EmitDxilTypeSystem(GetTypeSystem(), m_LLVMUsed);
  1058. if (!m_pSM->IsLib() && !m_pSM->IsCS() &&
  1059. ((m_ValMajor == 0 && m_ValMinor == 0) ||
  1060. (m_ValMajor > 1 || (m_ValMajor == 1 && m_ValMinor >= 1)))) {
  1061. m_pMDHelper->EmitDxilViewIdState(m_SerializedState);
  1062. }
  1063. EmitLLVMUsed();
  1064. MDTuple *pEntry = m_pMDHelper->EmitDxilEntryPointTuple(GetEntryFunction(), m_EntryName, pMDSignatures, pMDResources, pMDProperties);
  1065. vector<MDNode *> Entries;
  1066. Entries.emplace_back(pEntry);
  1067. if (m_pSM->IsLib()) {
  1068. // Sort functions by name to keep metadata deterministic
  1069. vector<const Function *> funcOrder;
  1070. funcOrder.reserve(m_DxilEntryPropsMap.size());
  1071. std::transform( m_DxilEntryPropsMap.begin(),
  1072. m_DxilEntryPropsMap.end(),
  1073. std::back_inserter(funcOrder),
  1074. [](const std::pair<const llvm::Function * const, std::unique_ptr<DxilEntryProps>> &p) -> const Function* { return p.first; } );
  1075. std::sort(funcOrder.begin(), funcOrder.end(), [](const Function *F1, const Function *F2) {
  1076. return F1->getName() < F2->getName();
  1077. });
  1078. for (auto F : funcOrder) {
  1079. auto &entryProps = m_DxilEntryPropsMap[F];
  1080. MDTuple *pProps = m_pMDHelper->EmitDxilEntryProperties(0, entryProps->props, 0);
  1081. MDTuple *pSig = m_pMDHelper->EmitDxilSignatures(entryProps->sig);
  1082. MDTuple *pSubEntry = m_pMDHelper->EmitDxilEntryPointTuple(
  1083. const_cast<Function *>(F), F->getName(), pSig, nullptr, pProps);
  1084. Entries.emplace_back(pSubEntry);
  1085. }
  1086. funcOrder.clear();
  1087. // Save Subobjects
  1088. if (GetSubobjects()) {
  1089. m_pMDHelper->EmitSubobjects(*GetSubobjects());
  1090. }
  1091. }
  1092. m_pMDHelper->EmitDxilEntryPoints(Entries);
  1093. if (!m_SerializedRootSignature.empty()) {
  1094. m_pMDHelper->EmitRootSignature(m_SerializedRootSignature);
  1095. }
  1096. }
  1097. bool DxilModule::IsKnownNamedMetaData(llvm::NamedMDNode &Node) {
  1098. return DxilMDHelper::IsKnownNamedMetaData(Node);
  1099. }
  1100. void DxilModule::LoadDxilMetadata() {
  1101. m_pMDHelper->LoadDxilVersion(m_DxilMajor, m_DxilMinor);
  1102. m_pMDHelper->LoadValidatorVersion(m_ValMajor, m_ValMinor);
  1103. const ShaderModel *loadedSM;
  1104. m_pMDHelper->LoadDxilShaderModel(loadedSM);
  1105. m_pMDHelper->LoadDxilIntermediateOptions(m_IntermediateFlags);
  1106. // This must be set before LoadDxilEntryProperties
  1107. m_pMDHelper->SetShaderModel(loadedSM);
  1108. // Setting module shader model requires UseMinPrecision flag,
  1109. // which requires loading m_ShaderFlags,
  1110. // which requires global entry properties,
  1111. // so load entry properties first, then set the shader model
  1112. const llvm::NamedMDNode *pEntries = m_pMDHelper->GetDxilEntryPoints();
  1113. if (!loadedSM->IsLib()) {
  1114. IFTBOOL(pEntries->getNumOperands() == 1, DXC_E_INCORRECT_DXIL_METADATA);
  1115. }
  1116. Function *pEntryFunc;
  1117. string EntryName;
  1118. const llvm::MDOperand *pEntrySignatures, *pEntryResources, *pEntryProperties;
  1119. m_pMDHelper->GetDxilEntryPoint(pEntries->getOperand(0),
  1120. pEntryFunc, EntryName,
  1121. pEntrySignatures, pEntryResources,
  1122. pEntryProperties);
  1123. uint64_t rawShaderFlags = 0;
  1124. DxilFunctionProps entryFuncProps;
  1125. entryFuncProps.shaderKind = loadedSM->GetKind();
  1126. m_pMDHelper->LoadDxilEntryProperties(*pEntryProperties, rawShaderFlags,
  1127. entryFuncProps, m_AutoBindingSpace);
  1128. m_bUseMinPrecision = true;
  1129. if (rawShaderFlags) {
  1130. m_ShaderFlags.SetShaderFlagsRaw(rawShaderFlags);
  1131. m_bUseMinPrecision = !m_ShaderFlags.GetUseNativeLowPrecision();
  1132. m_bDisableOptimizations = m_ShaderFlags.GetDisableOptimizations();
  1133. m_bAllResourcesBound = m_ShaderFlags.GetAllResourcesBound();
  1134. }
  1135. // Now that we have the UseMinPrecision flag, set shader model:
  1136. SetShaderModel(loadedSM, m_bUseMinPrecision);
  1137. if (loadedSM->IsLib()) {
  1138. for (unsigned i = 1; i < pEntries->getNumOperands(); i++) {
  1139. Function *pFunc;
  1140. string Name;
  1141. const llvm::MDOperand *pSignatures, *pResources, *pProperties;
  1142. m_pMDHelper->GetDxilEntryPoint(pEntries->getOperand(i), pFunc, Name,
  1143. pSignatures, pResources, pProperties);
  1144. DxilFunctionProps props;
  1145. uint64_t rawShaderFlags = 0;
  1146. unsigned autoBindingSpace = 0;
  1147. m_pMDHelper->LoadDxilEntryProperties(
  1148. *pProperties, rawShaderFlags, props, autoBindingSpace);
  1149. if (props.IsHS() && props.ShaderProps.HS.patchConstantFunc) {
  1150. // Add patch constant function to m_PatchConstantFunctions
  1151. m_PatchConstantFunctions.insert(props.ShaderProps.HS.patchConstantFunc);
  1152. }
  1153. std::unique_ptr<DxilEntryProps> pEntryProps =
  1154. llvm::make_unique<DxilEntryProps>(props, m_bUseMinPrecision);
  1155. m_pMDHelper->LoadDxilSignatures(*pSignatures, pEntryProps->sig);
  1156. m_DxilEntryPropsMap[pFunc] = std::move(pEntryProps);
  1157. }
  1158. // Load Subobjects
  1159. std::unique_ptr<DxilSubobjects> pSubobjects(new DxilSubobjects());
  1160. m_pMDHelper->LoadSubobjects(*pSubobjects);
  1161. if (pSubobjects->GetSubobjects().size()) {
  1162. ResetSubobjects(pSubobjects.release());
  1163. }
  1164. } else {
  1165. std::unique_ptr<DxilEntryProps> pEntryProps =
  1166. llvm::make_unique<DxilEntryProps>(entryFuncProps, m_bUseMinPrecision);
  1167. DxilFunctionProps *pFuncProps = &pEntryProps->props;
  1168. m_pMDHelper->LoadDxilSignatures(*pEntrySignatures, pEntryProps->sig);
  1169. m_DxilEntryPropsMap.clear();
  1170. m_DxilEntryPropsMap[pEntryFunc] = std::move(pEntryProps);
  1171. SetEntryFunction(pEntryFunc);
  1172. SetEntryFunctionName(EntryName);
  1173. SetShaderProperties(pFuncProps);
  1174. }
  1175. LoadDxilResources(*pEntryResources);
  1176. m_pMDHelper->LoadDxilTypeSystem(*m_pTypeSystem.get());
  1177. m_pMDHelper->LoadRootSignature(m_SerializedRootSignature);
  1178. m_pMDHelper->LoadDxilViewIdState(m_SerializedState);
  1179. }
  1180. MDTuple *DxilModule::EmitDxilResources() {
  1181. // Emit SRV records.
  1182. MDTuple *pTupleSRVs = nullptr;
  1183. if (!m_SRVs.empty()) {
  1184. vector<Metadata *> MDVals;
  1185. for (size_t i = 0; i < m_SRVs.size(); i++) {
  1186. MDVals.emplace_back(m_pMDHelper->EmitDxilSRV(*m_SRVs[i]));
  1187. }
  1188. pTupleSRVs = MDNode::get(m_Ctx, MDVals);
  1189. }
  1190. // Emit UAV records.
  1191. MDTuple *pTupleUAVs = nullptr;
  1192. if (!m_UAVs.empty()) {
  1193. vector<Metadata *> MDVals;
  1194. for (size_t i = 0; i < m_UAVs.size(); i++) {
  1195. MDVals.emplace_back(m_pMDHelper->EmitDxilUAV(*m_UAVs[i]));
  1196. }
  1197. pTupleUAVs = MDNode::get(m_Ctx, MDVals);
  1198. }
  1199. // Emit CBuffer records.
  1200. MDTuple *pTupleCBuffers = nullptr;
  1201. if (!m_CBuffers.empty()) {
  1202. vector<Metadata *> MDVals;
  1203. for (size_t i = 0; i < m_CBuffers.size(); i++) {
  1204. MDVals.emplace_back(m_pMDHelper->EmitDxilCBuffer(*m_CBuffers[i]));
  1205. }
  1206. pTupleCBuffers = MDNode::get(m_Ctx, MDVals);
  1207. }
  1208. // Emit Sampler records.
  1209. MDTuple *pTupleSamplers = nullptr;
  1210. if (!m_Samplers.empty()) {
  1211. vector<Metadata *> MDVals;
  1212. for (size_t i = 0; i < m_Samplers.size(); i++) {
  1213. MDVals.emplace_back(m_pMDHelper->EmitDxilSampler(*m_Samplers[i]));
  1214. }
  1215. pTupleSamplers = MDNode::get(m_Ctx, MDVals);
  1216. }
  1217. if (pTupleSRVs != nullptr || pTupleUAVs != nullptr || pTupleCBuffers != nullptr || pTupleSamplers != nullptr) {
  1218. return m_pMDHelper->EmitDxilResourceTuple(pTupleSRVs, pTupleUAVs, pTupleCBuffers, pTupleSamplers);
  1219. } else {
  1220. return nullptr;
  1221. }
  1222. }
  1223. void DxilModule::ReEmitDxilResources() {
  1224. ClearDxilMetadata(*m_pModule);
  1225. EmitDxilMetadata();
  1226. }
  1227. void DxilModule::LoadDxilResources(const llvm::MDOperand &MDO) {
  1228. if (MDO.get() == nullptr)
  1229. return;
  1230. const llvm::MDTuple *pSRVs, *pUAVs, *pCBuffers, *pSamplers;
  1231. m_pMDHelper->GetDxilResources(MDO, pSRVs, pUAVs, pCBuffers, pSamplers);
  1232. // Load SRV records.
  1233. if (pSRVs != nullptr) {
  1234. for (unsigned i = 0; i < pSRVs->getNumOperands(); i++) {
  1235. unique_ptr<DxilResource> pSRV(new DxilResource);
  1236. m_pMDHelper->LoadDxilSRV(pSRVs->getOperand(i), *pSRV);
  1237. AddSRV(std::move(pSRV));
  1238. }
  1239. }
  1240. // Load UAV records.
  1241. if (pUAVs != nullptr) {
  1242. for (unsigned i = 0; i < pUAVs->getNumOperands(); i++) {
  1243. unique_ptr<DxilResource> pUAV(new DxilResource);
  1244. m_pMDHelper->LoadDxilUAV(pUAVs->getOperand(i), *pUAV);
  1245. AddUAV(std::move(pUAV));
  1246. }
  1247. }
  1248. // Load CBuffer records.
  1249. if (pCBuffers != nullptr) {
  1250. for (unsigned i = 0; i < pCBuffers->getNumOperands(); i++) {
  1251. unique_ptr<DxilCBuffer> pCB(new DxilCBuffer);
  1252. m_pMDHelper->LoadDxilCBuffer(pCBuffers->getOperand(i), *pCB);
  1253. AddCBuffer(std::move(pCB));
  1254. }
  1255. }
  1256. // Load Sampler records.
  1257. if (pSamplers != nullptr) {
  1258. for (unsigned i = 0; i < pSamplers->getNumOperands(); i++) {
  1259. unique_ptr<DxilSampler> pSampler(new DxilSampler);
  1260. m_pMDHelper->LoadDxilSampler(pSamplers->getOperand(i), *pSampler);
  1261. AddSampler(std::move(pSampler));
  1262. }
  1263. }
  1264. }
  1265. void DxilModule::StripDebugRelatedCode() {
  1266. // Remove all users of global resources.
  1267. for (GlobalVariable &GV : m_pModule->globals()) {
  1268. if (GV.hasInternalLinkage())
  1269. continue;
  1270. if (GV.getType()->getPointerAddressSpace() == DXIL::kTGSMAddrSpace)
  1271. continue;
  1272. for (auto git = GV.user_begin(); git != GV.user_end();) {
  1273. User *U = *(git++);
  1274. // Try to remove load of GV.
  1275. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  1276. for (auto it = LI->user_begin(); it != LI->user_end();) {
  1277. Instruction *LIUser = cast<Instruction>(*(it++));
  1278. if (StoreInst *SI = dyn_cast<StoreInst>(LIUser)) {
  1279. Value *Ptr = SI->getPointerOperand();
  1280. SI->eraseFromParent();
  1281. if (Instruction *PtrInst = dyn_cast<Instruction>(Ptr)) {
  1282. if (Ptr->user_empty())
  1283. PtrInst->eraseFromParent();
  1284. }
  1285. }
  1286. }
  1287. if (LI->user_empty())
  1288. LI->eraseFromParent();
  1289. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
  1290. for (auto GEPIt = GEP->user_begin(); GEPIt != GEP->user_end();) {
  1291. User *GEPU = *(GEPIt++);
  1292. // Try to remove load of GEP.
  1293. if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
  1294. for (auto it = LI->user_begin(); it != LI->user_end();) {
  1295. Instruction *LIUser = cast<Instruction>(*(it++));
  1296. if (StoreInst *SI = dyn_cast<StoreInst>(LIUser)) {
  1297. Value *Ptr = SI->getPointerOperand();
  1298. SI->eraseFromParent();
  1299. if (Instruction *PtrInst = dyn_cast<Instruction>(Ptr)) {
  1300. if (Ptr->user_empty())
  1301. PtrInst->eraseFromParent();
  1302. }
  1303. }
  1304. if (LI->user_empty())
  1305. LI->eraseFromParent();
  1306. }
  1307. }
  1308. }
  1309. if (GEP->user_empty())
  1310. GEP->eraseFromParent();
  1311. }
  1312. }
  1313. }
  1314. // Remove dx.source metadata.
  1315. if (NamedMDNode *contents = m_pModule->getNamedMetadata(
  1316. DxilMDHelper::kDxilSourceContentsMDName)) {
  1317. contents->eraseFromParent();
  1318. }
  1319. if (NamedMDNode *defines =
  1320. m_pModule->getNamedMetadata(DxilMDHelper::kDxilSourceDefinesMDName)) {
  1321. defines->eraseFromParent();
  1322. }
  1323. if (NamedMDNode *mainFileName = m_pModule->getNamedMetadata(
  1324. DxilMDHelper::kDxilSourceMainFileNameMDName)) {
  1325. mainFileName->eraseFromParent();
  1326. }
  1327. if (NamedMDNode *arguments =
  1328. m_pModule->getNamedMetadata(DxilMDHelper::kDxilSourceArgsMDName)) {
  1329. arguments->eraseFromParent();
  1330. }
  1331. }
  1332. DebugInfoFinder &DxilModule::GetOrCreateDebugInfoFinder() {
  1333. if (m_pDebugInfoFinder == nullptr) {
  1334. m_pDebugInfoFinder = llvm::make_unique<llvm::DebugInfoFinder>();
  1335. m_pDebugInfoFinder->processModule(*m_pModule);
  1336. }
  1337. return *m_pDebugInfoFinder;
  1338. }
  1339. hlsl::DxilModule *hlsl::DxilModule::TryGetDxilModule(llvm::Module *pModule) {
  1340. LLVMContext &Ctx = pModule->getContext();
  1341. std::string diagStr;
  1342. raw_string_ostream diagStream(diagStr);
  1343. hlsl::DxilModule *pDxilModule = nullptr;
  1344. // TODO: add detail error in DxilMDHelper.
  1345. try {
  1346. pDxilModule = &pModule->GetOrCreateDxilModule();
  1347. } catch (const ::hlsl::Exception &hlslException) {
  1348. diagStream << "load dxil metadata failed -";
  1349. try {
  1350. const char *msg = hlslException.what();
  1351. if (msg == nullptr || *msg == '\0')
  1352. diagStream << " error code " << hlslException.hr << "\n";
  1353. else
  1354. diagStream << msg;
  1355. } catch (...) {
  1356. diagStream << " unable to retrieve error message.\n";
  1357. }
  1358. Ctx.diagnose(DxilErrorDiagnosticInfo(diagStream.str().c_str()));
  1359. } catch (...) {
  1360. Ctx.diagnose(DxilErrorDiagnosticInfo("load dxil metadata failed - unknown error.\n"));
  1361. }
  1362. return pDxilModule;
  1363. }
  1364. // Check if the instruction has fast math flags configured to indicate
  1365. // the instruction is precise.
  1366. // Precise fast math flags means none of the fast math flags are set.
  1367. bool DxilModule::HasPreciseFastMathFlags(const Instruction *inst) {
  1368. return isa<FPMathOperator>(inst) && !inst->getFastMathFlags().any();
  1369. }
  1370. // Set fast math flags configured to indicate the instruction is precise.
  1371. void DxilModule::SetPreciseFastMathFlags(llvm::Instruction *inst) {
  1372. assert(isa<FPMathOperator>(inst));
  1373. inst->copyFastMathFlags(FastMathFlags());
  1374. }
  1375. // True if fast math flags are preserved across serialization/deserialization
  1376. // of the dxil module.
  1377. //
  1378. // We need to check for this when querying fast math flags for preciseness
  1379. // otherwise we will be overly conservative by reporting instructions precise
  1380. // because their fast math flags were not preserved.
  1381. //
  1382. // Currently we restrict it to the instruction types that have fast math
  1383. // preserved in the bitcode. We can expand this by converting fast math
  1384. // flags to dx.precise metadata during serialization and back to fast
  1385. // math flags during deserialization.
  1386. bool DxilModule::PreservesFastMathFlags(const llvm::Instruction *inst) {
  1387. return
  1388. isa<FPMathOperator>(inst) && (isa<BinaryOperator>(inst) || isa<FCmpInst>(inst));
  1389. }
  1390. bool DxilModule::IsPrecise(const Instruction *inst) const {
  1391. if (m_ShaderFlags.GetDisableMathRefactoring())
  1392. return true;
  1393. else if (DxilMDHelper::IsMarkedPrecise(inst))
  1394. return true;
  1395. else if (PreservesFastMathFlags(inst))
  1396. return HasPreciseFastMathFlags(inst);
  1397. else
  1398. return false;
  1399. }
  1400. } // namespace hlsl
  1401. namespace llvm {
  1402. hlsl::DxilModule &Module::GetOrCreateDxilModule(bool skipInit) {
  1403. std::unique_ptr<hlsl::DxilModule> M;
  1404. if (!HasDxilModule()) {
  1405. M = llvm::make_unique<hlsl::DxilModule>(this);
  1406. if (!skipInit) {
  1407. M->LoadDxilMetadata();
  1408. }
  1409. SetDxilModule(M.release());
  1410. }
  1411. return GetDxilModule();
  1412. }
  1413. }