DxilModule.cpp 68 KB

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