DxilModule.cpp 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilModule.cpp //
  4. // Copyright (C) Microsoft Corporation. All rights reserved. //
  5. // This file is distributed under the University of Illinois Open Source //
  6. // License. See LICENSE.TXT for details. //
  7. // //
  8. ///////////////////////////////////////////////////////////////////////////////
  9. #include "dxc/Support/Global.h"
  10. #include "dxc/HLSL/DxilOperations.h"
  11. #include "dxc/HLSL/DxilModule.h"
  12. #include "dxc/HLSL/DxilShaderModel.h"
  13. #include "dxc/HLSL/DxilSignatureElement.h"
  14. #include "dxc/HLSL/DxilContainer.h"
  15. #include "dxc/HLSL/DxilRootSignature.h"
  16. #include "dxc/HLSL/DxilFunctionProps.h"
  17. #include "llvm/IR/Constants.h"
  18. #include "llvm/IR/Function.h"
  19. #include "llvm/IR/Instructions.h"
  20. #include "llvm/IR/LLVMContext.h"
  21. #include "llvm/IR/Metadata.h"
  22. #include "llvm/IR/Module.h"
  23. #include "llvm/IR/Operator.h"
  24. #include "llvm/IR/DebugInfo.h"
  25. #include "llvm/IR/DiagnosticInfo.h"
  26. #include "llvm/IR/DiagnosticPrinter.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include <unordered_set>
  29. using namespace llvm;
  30. using std::string;
  31. using std::vector;
  32. using std::unique_ptr;
  33. namespace {
  34. class DxilErrorDiagnosticInfo : public DiagnosticInfo {
  35. private:
  36. const char *m_message;
  37. public:
  38. DxilErrorDiagnosticInfo(const char *str)
  39. : DiagnosticInfo(DK_FirstPluginKind, DiagnosticSeverity::DS_Error),
  40. m_message(str) { }
  41. __override void print(DiagnosticPrinter &DP) const {
  42. DP << m_message;
  43. }
  44. };
  45. } // anon namespace
  46. namespace hlsl {
  47. //------------------------------------------------------------------------------
  48. //
  49. // DxilModule methods.
  50. //
  51. DxilModule::DxilModule(Module *pModule)
  52. : m_Ctx(pModule->getContext())
  53. , m_pModule(pModule)
  54. , m_pOP(std::make_unique<OP>(pModule->getContext(), pModule))
  55. , m_pTypeSystem(std::make_unique<DxilTypeSystem>(pModule))
  56. , m_pViewIdState(std::make_unique<DxilViewIdState>(this))
  57. , m_pMDHelper(std::make_unique<DxilMDHelper>(pModule, std::make_unique<DxilExtraPropertyHelper>(pModule)))
  58. , m_pDebugInfoFinder(nullptr)
  59. , m_pEntryFunc(nullptr)
  60. , m_EntryName("")
  61. , m_pPatchConstantFunc(nullptr)
  62. , m_pSM(nullptr)
  63. , m_DxilMajor(DXIL::kDxilMajor)
  64. , m_DxilMinor(DXIL::kDxilMinor)
  65. , m_ValMajor(1)
  66. , m_ValMinor(0)
  67. , m_InputPrimitive(DXIL::InputPrimitive::Undefined)
  68. , m_MaxVertexCount(0)
  69. , m_StreamPrimitiveTopology(DXIL::PrimitiveTopology::Undefined)
  70. , m_ActiveStreamMask(0)
  71. , m_NumGSInstances(1)
  72. , m_InputControlPointCount(0)
  73. , m_TessellatorDomain(DXIL::TessellatorDomain::Undefined)
  74. , m_OutputControlPointCount(0)
  75. , m_TessellatorPartitioning(DXIL::TessellatorPartitioning::Undefined)
  76. , m_TessellatorOutputPrimitive(DXIL::TessellatorOutputPrimitive::Undefined)
  77. , m_MaxTessellationFactor(0.f)
  78. , m_RootSignature(nullptr) {
  79. DXASSERT_NOMSG(m_pModule != nullptr);
  80. m_NumThreads[0] = m_NumThreads[1] = m_NumThreads[2] = 0;
  81. #if defined(_DEBUG) || defined(DBG)
  82. // Pin LLVM dump methods.
  83. void (__thiscall Module::*pfnModuleDump)() const = &Module::dump;
  84. void (__thiscall Type::*pfnTypeDump)() const = &Type::dump;
  85. void (__thiscall Function::*pfnViewCFGOnly)() const = &Function::viewCFGOnly;
  86. m_pUnused = (char *)&pfnModuleDump - (char *)&pfnTypeDump;
  87. m_pUnused -= (size_t)&pfnViewCFGOnly;
  88. #endif
  89. }
  90. DxilModule::~DxilModule() {
  91. }
  92. DxilModule::ShaderFlags::ShaderFlags():
  93. m_bDisableOptimizations(false)
  94. , m_bDisableMathRefactoring(false)
  95. , m_bEnableDoublePrecision(false)
  96. , m_bForceEarlyDepthStencil(false)
  97. , m_bEnableRawAndStructuredBuffers(false)
  98. , m_bLowPrecisionPresent(false)
  99. , m_bEnableDoubleExtensions(false)
  100. , m_bEnableMSAD(false)
  101. , m_bAllResourcesBound(false)
  102. , m_bViewportAndRTArrayIndex(false)
  103. , m_bInnerCoverage(false)
  104. , m_bStencilRef(false)
  105. , m_bTiledResources(false)
  106. , m_bUAVLoadAdditionalFormats(false)
  107. , m_bLevel9ComparisonFiltering(false)
  108. , m_bCSRawAndStructuredViaShader4X(false)
  109. , m_b64UAVs(false)
  110. , m_UAVsAtEveryStage(false)
  111. , m_bROVS(false)
  112. , m_bWaveOps(false)
  113. , m_bInt64Ops(false)
  114. , m_bViewID(false)
  115. , m_bBarycentrics(false)
  116. , m_bUseNativeLowPrecision(false)
  117. , m_align0(0)
  118. , m_align1(0)
  119. {}
  120. LLVMContext &DxilModule::GetCtx() const { return m_Ctx; }
  121. Module *DxilModule::GetModule() const { return m_pModule; }
  122. OP *DxilModule::GetOP() const { return m_pOP.get(); }
  123. void DxilModule::SetShaderModel(const ShaderModel *pSM) {
  124. DXASSERT(m_pSM == nullptr || (pSM != nullptr && *m_pSM == *pSM), "shader model must not change for the module");
  125. DXASSERT(pSM != nullptr && pSM->IsValidForDxil(), "shader model must be valid");
  126. DXASSERT(pSM->IsValidForModule(), "shader model must be valid for top-level module use");
  127. m_pSM = pSM;
  128. m_pSM->GetDxilVersion(m_DxilMajor, m_DxilMinor);
  129. m_pMDHelper->SetShaderModel(m_pSM);
  130. DXIL::ShaderKind shaderKind = pSM->GetKind();
  131. m_EntrySignature = llvm::make_unique<DxilEntrySignature>(shaderKind, !m_ShaderFlags.GetUseNativeLowPrecision());
  132. m_RootSignature.reset(new RootSignatureHandle());
  133. }
  134. const ShaderModel *DxilModule::GetShaderModel() const {
  135. return m_pSM;
  136. }
  137. void DxilModule::GetDxilVersion(unsigned &DxilMajor, unsigned &DxilMinor) const {
  138. DxilMajor = m_DxilMajor;
  139. DxilMinor = m_DxilMinor;
  140. }
  141. void DxilModule::SetValidatorVersion(unsigned ValMajor, unsigned ValMinor) {
  142. m_ValMajor = ValMajor;
  143. m_ValMinor = ValMinor;
  144. }
  145. bool DxilModule::UpgradeValidatorVersion(unsigned ValMajor, unsigned ValMinor) {
  146. // Don't upgrade if validation was disabled.
  147. if (m_ValMajor == 0 && m_ValMinor == 0) {
  148. return false;
  149. }
  150. if (ValMajor > m_ValMajor || (ValMajor == m_ValMajor && ValMinor > m_ValMinor)) {
  151. // Module requires higher validator version than previously set
  152. SetValidatorVersion(ValMajor, ValMinor);
  153. return true;
  154. }
  155. return false;
  156. }
  157. void DxilModule::GetValidatorVersion(unsigned &ValMajor, unsigned &ValMinor) const {
  158. ValMajor = m_ValMajor;
  159. ValMinor = m_ValMinor;
  160. }
  161. bool DxilModule::GetMinValidatorVersion(unsigned &ValMajor, unsigned &ValMinor) const {
  162. if (!m_pSM)
  163. return false;
  164. m_pSM->GetMinValidatorVersion(ValMajor, ValMinor);
  165. if (ValMajor == 1 && ValMinor == 0 && (m_ShaderFlags.GetFeatureInfo() & hlsl::ShaderFeatureInfo_ViewID))
  166. ValMinor = 1;
  167. return true;
  168. }
  169. bool DxilModule::UpgradeToMinValidatorVersion() {
  170. unsigned ValMajor = 1, ValMinor = 0;
  171. if (GetMinValidatorVersion(ValMajor, ValMinor)) {
  172. return UpgradeValidatorVersion(ValMajor, ValMinor);
  173. }
  174. return false;
  175. }
  176. Function *DxilModule::GetEntryFunction() {
  177. return m_pEntryFunc;
  178. }
  179. const Function *DxilModule::GetEntryFunction() const {
  180. return m_pEntryFunc;
  181. }
  182. void DxilModule::SetEntryFunction(Function *pEntryFunc) {
  183. m_pEntryFunc = pEntryFunc;
  184. }
  185. const string &DxilModule::GetEntryFunctionName() const {
  186. return m_EntryName;
  187. }
  188. void DxilModule::SetEntryFunctionName(const string &name) {
  189. m_EntryName = name;
  190. }
  191. llvm::Function *DxilModule::GetPatchConstantFunction() {
  192. return m_pPatchConstantFunc;
  193. }
  194. const llvm::Function *DxilModule::GetPatchConstantFunction() const {
  195. return m_pPatchConstantFunc;
  196. }
  197. void DxilModule::SetPatchConstantFunction(llvm::Function *pFunc) {
  198. m_pPatchConstantFunc = pFunc;
  199. }
  200. unsigned DxilModule::ShaderFlags::GetGlobalFlags() const {
  201. unsigned Flags = 0;
  202. Flags |= m_bDisableOptimizations ? DXIL::kDisableOptimizations : 0;
  203. Flags |= m_bDisableMathRefactoring ? DXIL::kDisableMathRefactoring : 0;
  204. Flags |= m_bEnableDoublePrecision ? DXIL::kEnableDoublePrecision : 0;
  205. Flags |= m_bForceEarlyDepthStencil ? DXIL::kForceEarlyDepthStencil : 0;
  206. Flags |= m_bEnableRawAndStructuredBuffers ? DXIL::kEnableRawAndStructuredBuffers : 0;
  207. Flags |= m_bLowPrecisionPresent && !m_bUseNativeLowPrecision? DXIL::kEnableMinPrecision : 0;
  208. Flags |= m_bEnableDoubleExtensions ? DXIL::kEnableDoubleExtensions : 0;
  209. Flags |= m_bEnableMSAD ? DXIL::kEnableMSAD : 0;
  210. Flags |= m_bAllResourcesBound ? DXIL::kAllResourcesBound : 0;
  211. return Flags;
  212. }
  213. uint64_t DxilModule::ShaderFlags::GetFeatureInfo() const {
  214. uint64_t Flags = 0;
  215. Flags |= m_bEnableDoublePrecision ? hlsl::ShaderFeatureInfo_Doubles : 0;
  216. Flags |= m_bLowPrecisionPresent && !m_bUseNativeLowPrecision ? hlsl::ShaderFeatureInfo_MinimumPrecision: 0;
  217. Flags |= m_bLowPrecisionPresent && m_bUseNativeLowPrecision ? hlsl::ShaderFeatureInfo_NativeLowPrecision : 0;
  218. Flags |= m_bEnableDoubleExtensions ? hlsl::ShaderFeatureInfo_11_1_DoubleExtensions : 0;
  219. Flags |= m_bWaveOps ? hlsl::ShaderFeatureInfo_WaveOps : 0;
  220. Flags |= m_bInt64Ops ? hlsl::ShaderFeatureInfo_Int64Ops : 0;
  221. Flags |= m_bROVS ? hlsl::ShaderFeatureInfo_ROVs : 0;
  222. Flags |= m_bViewportAndRTArrayIndex ? hlsl::ShaderFeatureInfo_ViewportAndRTArrayIndexFromAnyShaderFeedingRasterizer : 0;
  223. Flags |= m_bInnerCoverage ? hlsl::ShaderFeatureInfo_InnerCoverage : 0;
  224. Flags |= m_bStencilRef ? hlsl::ShaderFeatureInfo_StencilRef : 0;
  225. Flags |= m_bTiledResources ? hlsl::ShaderFeatureInfo_TiledResources : 0;
  226. Flags |= m_bEnableMSAD ? hlsl::ShaderFeatureInfo_11_1_ShaderExtensions : 0;
  227. Flags |= m_bCSRawAndStructuredViaShader4X ? hlsl::ShaderFeatureInfo_ComputeShadersPlusRawAndStructuredBuffersViaShader4X : 0;
  228. Flags |= m_UAVsAtEveryStage ? hlsl::ShaderFeatureInfo_UAVsAtEveryStage : 0;
  229. Flags |= m_b64UAVs ? hlsl::ShaderFeatureInfo_64UAVs : 0;
  230. Flags |= m_bLevel9ComparisonFiltering ? hlsl::ShaderFeatureInfo_LEVEL9ComparisonFiltering : 0;
  231. Flags |= m_bUAVLoadAdditionalFormats ? hlsl::ShaderFeatureInfo_TypedUAVLoadAdditionalFormats : 0;
  232. Flags |= m_bViewID ? hlsl::ShaderFeatureInfo_ViewID : 0;
  233. Flags |= m_bBarycentrics ? hlsl::ShaderFeatureInfo_Barycentrics : 0;
  234. return Flags;
  235. }
  236. uint64_t DxilModule::ShaderFlags::GetShaderFlagsRaw() const {
  237. union Cast {
  238. Cast(const DxilModule::ShaderFlags &flags) {
  239. shaderFlags = flags;
  240. }
  241. DxilModule::ShaderFlags shaderFlags;
  242. uint64_t rawData;
  243. };
  244. static_assert(sizeof(uint64_t) == sizeof(DxilModule::ShaderFlags),
  245. "size must match to make sure no undefined bits when cast");
  246. Cast rawCast(*this);
  247. return rawCast.rawData;
  248. }
  249. void DxilModule::ShaderFlags::SetShaderFlagsRaw(uint64_t data) {
  250. union Cast {
  251. Cast(uint64_t data) {
  252. rawData = data;
  253. }
  254. DxilModule::ShaderFlags shaderFlags;
  255. uint64_t rawData;
  256. };
  257. Cast rawCast(data);
  258. *this = rawCast.shaderFlags;
  259. }
  260. unsigned DxilModule::GetGlobalFlags() const {
  261. unsigned Flags = m_ShaderFlags.GetGlobalFlags();
  262. return Flags;
  263. }
  264. static bool IsResourceSingleComponent(llvm::Type *Ty) {
  265. if (llvm::ArrayType *arrType = llvm::dyn_cast<llvm::ArrayType>(Ty)) {
  266. if (arrType->getArrayNumElements() > 1) {
  267. return false;
  268. }
  269. return IsResourceSingleComponent(arrType->getArrayElementType());
  270. } else if (llvm::StructType *structType =
  271. llvm::dyn_cast<llvm::StructType>(Ty)) {
  272. if (structType->getStructNumElements() > 1) {
  273. return false;
  274. }
  275. return IsResourceSingleComponent(structType->getStructElementType(0));
  276. } else if (llvm::VectorType *vectorType =
  277. llvm::dyn_cast<llvm::VectorType>(Ty)) {
  278. if (vectorType->getNumElements() > 1) {
  279. return false;
  280. }
  281. return IsResourceSingleComponent(vectorType->getVectorElementType());
  282. }
  283. return true;
  284. }
  285. // Given a CreateHandle call, returns arbitrary ConstantInt rangeID
  286. // Note: HLSL is currently assuming that rangeID is a constant value, but this code is assuming
  287. // that it can be either constant, phi node, or select instruction
  288. static ConstantInt *GetArbitraryConstantRangeID(CallInst *handleCall) {
  289. Value *rangeID =
  290. handleCall->getArgOperand(DXIL::OperandIndex::kCreateHandleResIDOpIdx);
  291. ConstantInt *ConstantRangeID = dyn_cast<ConstantInt>(rangeID);
  292. while (ConstantRangeID == nullptr) {
  293. if (ConstantInt *CI = dyn_cast<ConstantInt>(rangeID)) {
  294. ConstantRangeID = CI;
  295. } else if (PHINode *PN = dyn_cast<PHINode>(rangeID)) {
  296. rangeID = PN->getIncomingValue(0);
  297. } else if (SelectInst *SI = dyn_cast<SelectInst>(rangeID)) {
  298. rangeID = SI->getTrueValue();
  299. } else {
  300. return nullptr;
  301. }
  302. }
  303. return ConstantRangeID;
  304. }
  305. void DxilModule::CollectShaderFlags(ShaderFlags &Flags) {
  306. bool hasDouble = false;
  307. // ddiv dfma drcp d2i d2u i2d u2d.
  308. // fma has dxil op. Others should check IR instruction div/cast.
  309. bool hasDoubleExtension = false;
  310. bool has64Int = false;
  311. bool has16 = false;
  312. bool hasWaveOps = false;
  313. bool hasCheckAccessFully = false;
  314. bool hasMSAD = false;
  315. bool hasInnerCoverage = false;
  316. bool hasViewID = false;
  317. bool hasMulticomponentUAVLoads = false;
  318. bool hasMulticomponentUAVLoadsBackCompat = false;
  319. // Try to maintain compatibility with a v1.0 validator if that's what we have.
  320. {
  321. unsigned valMajor, valMinor;
  322. GetValidatorVersion(valMajor, valMinor);
  323. hasMulticomponentUAVLoadsBackCompat = valMajor <= 1 && valMinor == 0;
  324. }
  325. Type *int16Ty = Type::getInt16Ty(GetCtx());
  326. Type *int64Ty = Type::getInt64Ty(GetCtx());
  327. for (Function &F : GetModule()->functions()) {
  328. for (BasicBlock &BB : F.getBasicBlockList()) {
  329. for (Instruction &I : BB.getInstList()) {
  330. // Skip none dxil function call.
  331. if (CallInst *CI = dyn_cast<CallInst>(&I)) {
  332. if (!OP::IsDxilOpFunc(CI->getCalledFunction()))
  333. continue;
  334. }
  335. Type *Ty = I.getType();
  336. bool isDouble = Ty->isDoubleTy();
  337. bool isHalf = Ty->isHalfTy();
  338. bool isInt16 = Ty == int16Ty;
  339. bool isInt64 = Ty == int64Ty;
  340. if (isa<ExtractElementInst>(&I) ||
  341. isa<InsertElementInst>(&I))
  342. continue;
  343. for (Value *operand : I.operands()) {
  344. Type *Ty = operand->getType();
  345. isDouble |= Ty->isDoubleTy();
  346. isHalf |= Ty->isHalfTy();
  347. isInt16 |= Ty == int16Ty;
  348. isInt64 |= Ty == int64Ty;
  349. }
  350. if (isDouble) {
  351. hasDouble = true;
  352. switch (I.getOpcode()) {
  353. case Instruction::FDiv:
  354. case Instruction::UIToFP:
  355. case Instruction::SIToFP:
  356. case Instruction::FPToUI:
  357. case Instruction::FPToSI:
  358. hasDoubleExtension = true;
  359. break;
  360. }
  361. }
  362. has16 |= isHalf;
  363. has16 |= isInt16;
  364. has64Int |= isInt64;
  365. if (CallInst *CI = dyn_cast<CallInst>(&I)) {
  366. if (!OP::IsDxilOpFunc(CI->getCalledFunction()))
  367. continue;
  368. Value *opcodeArg = CI->getArgOperand(DXIL::OperandIndex::kOpcodeIdx);
  369. ConstantInt *opcodeConst = dyn_cast<ConstantInt>(opcodeArg);
  370. DXASSERT(opcodeConst, "DXIL opcode arg must be immediate");
  371. unsigned opcode = opcodeConst->getLimitedValue();
  372. DXASSERT(opcode < static_cast<unsigned>(DXIL::OpCode::NumOpCodes),
  373. "invalid DXIL opcode");
  374. DXIL::OpCode dxilOp = static_cast<DXIL::OpCode>(opcode);
  375. if (hlsl::OP::IsDxilOpWave(dxilOp))
  376. hasWaveOps = true;
  377. switch (dxilOp) {
  378. case DXIL::OpCode::CheckAccessFullyMapped:
  379. hasCheckAccessFully = true;
  380. break;
  381. case DXIL::OpCode::Msad:
  382. hasMSAD = true;
  383. break;
  384. case DXIL::OpCode::BufferLoad:
  385. case DXIL::OpCode::TextureLoad: {
  386. if (hasMulticomponentUAVLoads) continue;
  387. // This is the old-style computation (overestimating requirements).
  388. Value *resHandle = CI->getArgOperand(DXIL::OperandIndex::kBufferStoreHandleOpIdx);
  389. CallInst *handleCall = cast<CallInst>(resHandle);
  390. if (ConstantInt *resClassArg =
  391. dyn_cast<ConstantInt>(handleCall->getArgOperand(
  392. DXIL::OperandIndex::kCreateHandleResClassOpIdx))) {
  393. DXIL::ResourceClass resClass = static_cast<DXIL::ResourceClass>(
  394. resClassArg->getLimitedValue());
  395. if (resClass == DXIL::ResourceClass::UAV) {
  396. // Validator 1.0 assumes that all uav load is multi component load.
  397. if (hasMulticomponentUAVLoadsBackCompat) {
  398. hasMulticomponentUAVLoads = true;
  399. continue;
  400. }
  401. else {
  402. ConstantInt *rangeID = GetArbitraryConstantRangeID(handleCall);
  403. if (rangeID) {
  404. DxilResource resource = GetUAV(rangeID->getLimitedValue());
  405. if ((resource.IsTypedBuffer() ||
  406. resource.IsAnyTexture()) &&
  407. !IsResourceSingleComponent(resource.GetRetType())) {
  408. hasMulticomponentUAVLoads = true;
  409. }
  410. }
  411. }
  412. }
  413. }
  414. else {
  415. DXASSERT(false, "Resource class must be constant.");
  416. }
  417. } break;
  418. case DXIL::OpCode::Fma:
  419. hasDoubleExtension |= isDouble;
  420. break;
  421. case DXIL::OpCode::InnerCoverage:
  422. hasInnerCoverage = true;
  423. break;
  424. case DXIL::OpCode::ViewID:
  425. hasViewID = true;
  426. break;
  427. default:
  428. // Normal opcodes.
  429. break;
  430. }
  431. }
  432. }
  433. }
  434. }
  435. Flags.SetEnableDoublePrecision(hasDouble);
  436. Flags.SetInt64Ops(has64Int);
  437. Flags.SetLowPrecisionPresent(has16);
  438. Flags.SetEnableDoubleExtensions(hasDoubleExtension);
  439. Flags.SetWaveOps(hasWaveOps);
  440. Flags.SetTiledResources(hasCheckAccessFully);
  441. Flags.SetEnableMSAD(hasMSAD);
  442. Flags.SetUAVLoadAdditionalFormats(hasMulticomponentUAVLoads);
  443. Flags.SetViewID(hasViewID);
  444. const ShaderModel *SM = GetShaderModel();
  445. if (SM->IsPS()) {
  446. bool hasStencilRef = false;
  447. DxilSignature &outS = GetOutputSignature();
  448. for (auto &&E : outS.GetElements()) {
  449. if (E->GetKind() == Semantic::Kind::StencilRef) {
  450. hasStencilRef = true;
  451. } else if (E->GetKind() == Semantic::Kind::InnerCoverage) {
  452. hasInnerCoverage = true;
  453. }
  454. }
  455. Flags.SetStencilRef(hasStencilRef);
  456. Flags.SetInnerCoverage(hasInnerCoverage);
  457. }
  458. bool checkInputRTArrayIndex =
  459. SM->IsGS() || SM->IsDS() || SM->IsHS() || SM->IsPS();
  460. if (checkInputRTArrayIndex) {
  461. bool hasViewportArrayIndex = false;
  462. bool hasRenderTargetArrayIndex = false;
  463. DxilSignature &inS = GetInputSignature();
  464. for (auto &E : inS.GetElements()) {
  465. if (E->GetKind() == Semantic::Kind::ViewPortArrayIndex) {
  466. hasViewportArrayIndex = true;
  467. } else if (E->GetKind() == Semantic::Kind::RenderTargetArrayIndex) {
  468. hasRenderTargetArrayIndex = true;
  469. }
  470. }
  471. Flags.SetViewportAndRTArrayIndex(hasViewportArrayIndex |
  472. hasRenderTargetArrayIndex);
  473. }
  474. bool checkOutputRTArrayIndex =
  475. SM->IsVS() || SM->IsDS() || SM->IsHS() || SM->IsPS();
  476. if (checkOutputRTArrayIndex) {
  477. bool hasViewportArrayIndex = false;
  478. bool hasRenderTargetArrayIndex = false;
  479. DxilSignature &outS = GetOutputSignature();
  480. for (auto &E : outS.GetElements()) {
  481. if (E->GetKind() == Semantic::Kind::ViewPortArrayIndex) {
  482. hasViewportArrayIndex = true;
  483. } else if (E->GetKind() == Semantic::Kind::RenderTargetArrayIndex) {
  484. hasRenderTargetArrayIndex = true;
  485. }
  486. }
  487. Flags.SetViewportAndRTArrayIndex(hasViewportArrayIndex |
  488. hasRenderTargetArrayIndex);
  489. }
  490. unsigned NumUAVs = m_UAVs.size();
  491. const unsigned kSmallUAVCount = 8;
  492. if (NumUAVs > kSmallUAVCount)
  493. Flags.Set64UAVs(true);
  494. if (NumUAVs && !(SM->IsCS() || SM->IsPS()))
  495. Flags.SetUAVsAtEveryStage(true);
  496. bool hasRawAndStructuredBuffer = false;
  497. for (auto &UAV : m_UAVs) {
  498. if (UAV->IsROV())
  499. Flags.SetROVs(true);
  500. switch (UAV->GetKind()) {
  501. case DXIL::ResourceKind::RawBuffer:
  502. case DXIL::ResourceKind::StructuredBuffer:
  503. hasRawAndStructuredBuffer = true;
  504. break;
  505. default:
  506. // Not raw/structured.
  507. break;
  508. }
  509. }
  510. for (auto &SRV : m_SRVs) {
  511. switch (SRV->GetKind()) {
  512. case DXIL::ResourceKind::RawBuffer:
  513. case DXIL::ResourceKind::StructuredBuffer:
  514. hasRawAndStructuredBuffer = true;
  515. break;
  516. default:
  517. // Not raw/structured.
  518. break;
  519. }
  520. }
  521. Flags.SetEnableRawAndStructuredBuffers(hasRawAndStructuredBuffer);
  522. bool hasCSRawAndStructuredViaShader4X =
  523. hasRawAndStructuredBuffer && m_pSM->GetMajor() == 4 && m_pSM->IsCS();
  524. Flags.SetCSRawAndStructuredViaShader4X(hasCSRawAndStructuredViaShader4X);
  525. }
  526. void DxilModule::CollectShaderFlags() {
  527. CollectShaderFlags(m_ShaderFlags);
  528. }
  529. uint64_t DxilModule::ShaderFlags::GetShaderFlagsRawForCollection() {
  530. // This should be all the flags that can be set by DxilModule::CollectShaderFlags.
  531. ShaderFlags Flags;
  532. Flags.SetEnableDoublePrecision(true);
  533. Flags.SetInt64Ops(true);
  534. Flags.SetLowPrecisionPresent(true);
  535. Flags.SetEnableDoubleExtensions(true);
  536. Flags.SetWaveOps(true);
  537. Flags.SetTiledResources(true);
  538. Flags.SetEnableMSAD(true);
  539. Flags.SetUAVLoadAdditionalFormats(true);
  540. Flags.SetStencilRef(true);
  541. Flags.SetInnerCoverage(true);
  542. Flags.SetViewportAndRTArrayIndex(true);
  543. Flags.Set64UAVs(true);
  544. Flags.SetUAVsAtEveryStage(true);
  545. Flags.SetEnableRawAndStructuredBuffers(true);
  546. Flags.SetCSRawAndStructuredViaShader4X(true);
  547. Flags.SetViewID(true);
  548. Flags.SetBarycentrics(true);
  549. return Flags.GetShaderFlagsRaw();
  550. }
  551. DXIL::InputPrimitive DxilModule::GetInputPrimitive() const {
  552. return m_InputPrimitive;
  553. }
  554. void DxilModule::SetInputPrimitive(DXIL::InputPrimitive IP) {
  555. DXASSERT_NOMSG(m_InputPrimitive == DXIL::InputPrimitive::Undefined);
  556. DXASSERT_NOMSG(DXIL::InputPrimitive::Undefined < IP && IP < DXIL::InputPrimitive::LastEntry);
  557. m_InputPrimitive = IP;
  558. }
  559. unsigned DxilModule::GetMaxVertexCount() const {
  560. DXASSERT_NOMSG(m_MaxVertexCount != 0);
  561. return m_MaxVertexCount;
  562. }
  563. void DxilModule::SetMaxVertexCount(unsigned Count) {
  564. DXASSERT_NOMSG(m_MaxVertexCount == 0);
  565. m_MaxVertexCount = Count;
  566. }
  567. DXIL::PrimitiveTopology DxilModule::GetStreamPrimitiveTopology() const {
  568. return m_StreamPrimitiveTopology;
  569. }
  570. void DxilModule::SetStreamPrimitiveTopology(DXIL::PrimitiveTopology Topology) {
  571. m_StreamPrimitiveTopology = Topology;
  572. }
  573. bool DxilModule::HasMultipleOutputStreams() const {
  574. if (!m_pSM->IsGS()) {
  575. return false;
  576. } else {
  577. unsigned NumStreams = (m_ActiveStreamMask & 0x1) +
  578. ((m_ActiveStreamMask & 0x2) >> 1) +
  579. ((m_ActiveStreamMask & 0x4) >> 2) +
  580. ((m_ActiveStreamMask & 0x8) >> 3);
  581. DXASSERT_NOMSG(NumStreams <= DXIL::kNumOutputStreams);
  582. return NumStreams > 1;
  583. }
  584. }
  585. unsigned DxilModule::GetOutputStream() const {
  586. if (!m_pSM->IsGS()) {
  587. return 0;
  588. } else {
  589. DXASSERT_NOMSG(!HasMultipleOutputStreams());
  590. switch (m_ActiveStreamMask) {
  591. case 0x1: return 0;
  592. case 0x2: return 1;
  593. case 0x4: return 2;
  594. case 0x8: return 3;
  595. default: DXASSERT_NOMSG(false);
  596. }
  597. return (unsigned)(-1);
  598. }
  599. }
  600. unsigned DxilModule::GetGSInstanceCount() const {
  601. return m_NumGSInstances;
  602. }
  603. void DxilModule::SetGSInstanceCount(unsigned Count) {
  604. m_NumGSInstances = Count;
  605. }
  606. bool DxilModule::IsStreamActive(unsigned Stream) const {
  607. return (m_ActiveStreamMask & (1<<Stream)) != 0;
  608. }
  609. void DxilModule::SetStreamActive(unsigned Stream, bool bActive) {
  610. if (bActive) {
  611. m_ActiveStreamMask |= (1<<Stream);
  612. } else {
  613. m_ActiveStreamMask &= ~(1<<Stream);
  614. }
  615. }
  616. void DxilModule::SetActiveStreamMask(unsigned Mask) {
  617. m_ActiveStreamMask = Mask;
  618. }
  619. unsigned DxilModule::GetActiveStreamMask() const {
  620. return m_ActiveStreamMask;
  621. }
  622. unsigned DxilModule::GetInputControlPointCount() const {
  623. return m_InputControlPointCount;
  624. }
  625. void DxilModule::SetInputControlPointCount(unsigned NumICPs) {
  626. m_InputControlPointCount = NumICPs;
  627. }
  628. DXIL::TessellatorDomain DxilModule::GetTessellatorDomain() const {
  629. return m_TessellatorDomain;
  630. }
  631. void DxilModule::SetTessellatorDomain(DXIL::TessellatorDomain TessDomain) {
  632. m_TessellatorDomain = TessDomain;
  633. }
  634. unsigned DxilModule::GetOutputControlPointCount() const {
  635. return m_OutputControlPointCount;
  636. }
  637. void DxilModule::SetOutputControlPointCount(unsigned NumOCPs) {
  638. m_OutputControlPointCount = NumOCPs;
  639. }
  640. DXIL::TessellatorPartitioning DxilModule::GetTessellatorPartitioning() const {
  641. return m_TessellatorPartitioning;
  642. }
  643. void DxilModule::SetTessellatorPartitioning(DXIL::TessellatorPartitioning TessPartitioning) {
  644. m_TessellatorPartitioning = TessPartitioning;
  645. }
  646. DXIL::TessellatorOutputPrimitive DxilModule::GetTessellatorOutputPrimitive() const {
  647. return m_TessellatorOutputPrimitive;
  648. }
  649. void DxilModule::SetTessellatorOutputPrimitive(DXIL::TessellatorOutputPrimitive TessOutputPrimitive) {
  650. m_TessellatorOutputPrimitive = TessOutputPrimitive;
  651. }
  652. float DxilModule::GetMaxTessellationFactor() const {
  653. return m_MaxTessellationFactor;
  654. }
  655. void DxilModule::SetMaxTessellationFactor(float MaxTessellationFactor) {
  656. m_MaxTessellationFactor = MaxTessellationFactor;
  657. }
  658. void DxilModule::SetShaderProperties(DxilFunctionProps *props) {
  659. if (!props)
  660. return;
  661. switch (props->shaderKind) {
  662. case DXIL::ShaderKind::Pixel: {
  663. auto &PS = props->ShaderProps.PS;
  664. m_ShaderFlags.SetForceEarlyDepthStencil(PS.EarlyDepthStencil);
  665. } break;
  666. case DXIL::ShaderKind::Compute: {
  667. auto &CS = props->ShaderProps.CS;
  668. for (size_t i = 0; i < _countof(m_NumThreads); ++i)
  669. m_NumThreads[i] = CS.numThreads[i];
  670. } break;
  671. case DXIL::ShaderKind::Domain: {
  672. auto &DS = props->ShaderProps.DS;
  673. SetTessellatorDomain(DS.domain);
  674. SetInputControlPointCount(DS.inputControlPoints);
  675. } break;
  676. case DXIL::ShaderKind::Hull: {
  677. auto &HS = props->ShaderProps.HS;
  678. SetPatchConstantFunction(HS.patchConstantFunc);
  679. SetTessellatorDomain(HS.domain);
  680. SetTessellatorPartitioning(HS.partition);
  681. SetTessellatorOutputPrimitive(HS.outputPrimitive);
  682. SetInputControlPointCount(HS.inputControlPoints);
  683. SetOutputControlPointCount(HS.outputControlPoints);
  684. SetMaxTessellationFactor(HS.maxTessFactor);
  685. } break;
  686. case DXIL::ShaderKind::Vertex:
  687. break;
  688. default: {
  689. DXASSERT(props->shaderKind == DXIL::ShaderKind::Geometry,
  690. "else invalid shader kind");
  691. auto &GS = props->ShaderProps.GS;
  692. SetInputPrimitive(GS.inputPrimitive);
  693. SetMaxVertexCount(GS.maxVertexCount);
  694. for (size_t i = 0; i < _countof(GS.streamPrimitiveTopologies); ++i) {
  695. if (GS.streamPrimitiveTopologies[i] !=
  696. DXIL::PrimitiveTopology::Undefined) {
  697. SetStreamActive(i, true);
  698. DXASSERT_NOMSG(GetStreamPrimitiveTopology() ==
  699. DXIL::PrimitiveTopology::Undefined ||
  700. GetStreamPrimitiveTopology() ==
  701. GS.streamPrimitiveTopologies[i]);
  702. SetStreamPrimitiveTopology(GS.streamPrimitiveTopologies[i]);
  703. }
  704. }
  705. SetGSInstanceCount(GS.instanceCount);
  706. } break;
  707. }
  708. }
  709. template<typename T> unsigned
  710. DxilModule::AddResource(vector<unique_ptr<T> > &Vec, unique_ptr<T> pRes) {
  711. DXASSERT_NOMSG((unsigned)Vec.size() < UINT_MAX);
  712. unsigned Id = (unsigned)Vec.size();
  713. Vec.emplace_back(std::move(pRes));
  714. return Id;
  715. }
  716. unsigned DxilModule::AddCBuffer(unique_ptr<DxilCBuffer> pCB) {
  717. return AddResource<DxilCBuffer>(m_CBuffers, std::move(pCB));
  718. }
  719. DxilCBuffer &DxilModule::GetCBuffer(unsigned idx) {
  720. return *m_CBuffers[idx];
  721. }
  722. const DxilCBuffer &DxilModule::GetCBuffer(unsigned idx) const {
  723. return *m_CBuffers[idx];
  724. }
  725. const vector<unique_ptr<DxilCBuffer> > &DxilModule::GetCBuffers() const {
  726. return m_CBuffers;
  727. }
  728. unsigned DxilModule::AddSampler(unique_ptr<DxilSampler> pSampler) {
  729. return AddResource<DxilSampler>(m_Samplers, std::move(pSampler));
  730. }
  731. DxilSampler &DxilModule::GetSampler(unsigned idx) {
  732. return *m_Samplers[idx];
  733. }
  734. const DxilSampler &DxilModule::GetSampler(unsigned idx) const {
  735. return *m_Samplers[idx];
  736. }
  737. const vector<unique_ptr<DxilSampler> > &DxilModule::GetSamplers() const {
  738. return m_Samplers;
  739. }
  740. unsigned DxilModule::AddSRV(unique_ptr<DxilResource> pSRV) {
  741. return AddResource<DxilResource>(m_SRVs, std::move(pSRV));
  742. }
  743. DxilResource &DxilModule::GetSRV(unsigned idx) {
  744. return *m_SRVs[idx];
  745. }
  746. const DxilResource &DxilModule::GetSRV(unsigned idx) const {
  747. return *m_SRVs[idx];
  748. }
  749. const vector<unique_ptr<DxilResource> > &DxilModule::GetSRVs() const {
  750. return m_SRVs;
  751. }
  752. unsigned DxilModule::AddUAV(unique_ptr<DxilResource> pUAV) {
  753. return AddResource<DxilResource>(m_UAVs, std::move(pUAV));
  754. }
  755. DxilResource &DxilModule::GetUAV(unsigned idx) {
  756. return *m_UAVs[idx];
  757. }
  758. const DxilResource &DxilModule::GetUAV(unsigned idx) const {
  759. return *m_UAVs[idx];
  760. }
  761. const vector<unique_ptr<DxilResource> > &DxilModule::GetUAVs() const {
  762. return m_UAVs;
  763. }
  764. void DxilModule::LoadDxilResourceBaseFromMDNode(MDNode *MD, DxilResourceBase &R) {
  765. return m_pMDHelper->LoadDxilResourceBaseFromMDNode(MD, R);
  766. }
  767. void DxilModule::LoadDxilResourceFromMDNode(llvm::MDNode *MD, DxilResource &R) {
  768. return m_pMDHelper->LoadDxilResourceFromMDNode(MD, R);
  769. }
  770. void DxilModule::LoadDxilSamplerFromMDNode(llvm::MDNode *MD, DxilSampler &S) {
  771. return m_pMDHelper->LoadDxilSamplerFromMDNode(MD, S);
  772. }
  773. template <typename TResource>
  774. static void RemoveResources(std::vector<std::unique_ptr<TResource>> &vec,
  775. std::unordered_set<unsigned> &immResID) {
  776. for (std::vector<std::unique_ptr<TResource>>::iterator p = vec.begin(); p != vec.end();) {
  777. std::vector<std::unique_ptr<TResource>>::iterator c = p++;
  778. if (immResID.count((*c)->GetID()) == 0) {
  779. p = vec.erase(c);
  780. }
  781. }
  782. }
  783. static void CollectUsedResource(Value *resID,
  784. std::unordered_set<Value *> &usedResID) {
  785. if (usedResID.count(resID) > 0)
  786. return;
  787. usedResID.insert(resID);
  788. if (ConstantInt *cResID = dyn_cast<ConstantInt>(resID)) {
  789. // Do nothing
  790. } else if (ZExtInst *ZEI = dyn_cast<ZExtInst>(resID)) {
  791. if (ZEI->getSrcTy()->isIntegerTy()) {
  792. IntegerType *ITy = cast<IntegerType>(ZEI->getSrcTy());
  793. if (ITy->getBitWidth() == 1) {
  794. usedResID.insert(ConstantInt::get(ZEI->getDestTy(), 0));
  795. usedResID.insert(ConstantInt::get(ZEI->getDestTy(), 1));
  796. }
  797. }
  798. } else if (SelectInst *SI = dyn_cast<SelectInst>(resID)) {
  799. CollectUsedResource(SI->getTrueValue(), usedResID);
  800. CollectUsedResource(SI->getFalseValue(), usedResID);
  801. } else if (PHINode *Phi = dyn_cast<PHINode>(resID)) {
  802. for (Use &U : Phi->incoming_values()) {
  803. CollectUsedResource(U.get(), usedResID);
  804. }
  805. }
  806. // TODO: resID could be other types of instructions depending on the compiler optimization.
  807. }
  808. static void ConvertUsedResource(std::unordered_set<unsigned> &immResID,
  809. std::unordered_set<Value *> &usedResID) {
  810. for (Value *V : usedResID) {
  811. if (ConstantInt *cResID = dyn_cast<ConstantInt>(V)) {
  812. immResID.insert(cResID->getLimitedValue());
  813. }
  814. }
  815. }
  816. void DxilModule::RemoveFunction(llvm::Function *F) {
  817. DXASSERT_NOMSG(F != nullptr);
  818. m_DxilFunctionPropsMap.erase(F);
  819. m_DxilEntrySignatureMap.erase(F);
  820. if (m_pTypeSystem.get()->GetFunctionAnnotation(F))
  821. m_pTypeSystem.get()->EraseFunctionAnnotation(F);
  822. m_pOP->RemoveFunction(F);
  823. }
  824. void DxilModule::RemoveUnusedResources() {
  825. DXASSERT(!m_pSM->IsLib(), "this function not work on library");
  826. hlsl::OP *hlslOP = GetOP();
  827. Function *createHandleFunc = hlslOP->GetOpFunc(DXIL::OpCode::CreateHandle, Type::getVoidTy(GetCtx()));
  828. if (createHandleFunc->user_empty()) {
  829. m_CBuffers.clear();
  830. m_UAVs.clear();
  831. m_SRVs.clear();
  832. m_Samplers.clear();
  833. createHandleFunc->eraseFromParent();
  834. return;
  835. }
  836. std::unordered_set<Value *> usedUAVID;
  837. std::unordered_set<Value *> usedSRVID;
  838. std::unordered_set<Value *> usedSamplerID;
  839. std::unordered_set<Value *> usedCBufID;
  840. // Collect used ID.
  841. for (User *U : createHandleFunc->users()) {
  842. CallInst *CI = cast<CallInst>(U);
  843. Value *vResClass =
  844. CI->getArgOperand(DXIL::OperandIndex::kCreateHandleResClassOpIdx);
  845. ConstantInt *cResClass = cast<ConstantInt>(vResClass);
  846. DXIL::ResourceClass resClass =
  847. static_cast<DXIL::ResourceClass>(cResClass->getLimitedValue());
  848. // Skip unused resource handle.
  849. if (CI->user_empty())
  850. continue;
  851. Value *resID =
  852. CI->getArgOperand(DXIL::OperandIndex::kCreateHandleResIDOpIdx);
  853. switch (resClass) {
  854. case DXIL::ResourceClass::CBuffer:
  855. CollectUsedResource(resID, usedCBufID);
  856. break;
  857. case DXIL::ResourceClass::Sampler:
  858. CollectUsedResource(resID, usedSamplerID);
  859. break;
  860. case DXIL::ResourceClass::SRV:
  861. CollectUsedResource(resID, usedSRVID);
  862. break;
  863. case DXIL::ResourceClass::UAV:
  864. CollectUsedResource(resID, usedUAVID);
  865. break;
  866. default:
  867. DXASSERT(0, "invalid res class");
  868. break;
  869. }
  870. }
  871. std::unordered_set<unsigned> immUAVID;
  872. std::unordered_set<unsigned> immSRVID;
  873. std::unordered_set<unsigned> immSamplerID;
  874. std::unordered_set<unsigned> immCBufID;
  875. ConvertUsedResource(immUAVID, usedUAVID);
  876. RemoveResources(m_UAVs, immUAVID);
  877. ConvertUsedResource(immSRVID, usedSRVID);
  878. ConvertUsedResource(immSamplerID, usedSamplerID);
  879. ConvertUsedResource(immCBufID, usedCBufID);
  880. RemoveResources(m_SRVs, immSRVID);
  881. RemoveResources(m_Samplers, immSamplerID);
  882. RemoveResources(m_CBuffers, immCBufID);
  883. }
  884. namespace {
  885. template <typename TResource>
  886. static void RemoveResourceSymbols(std::vector<std::unique_ptr<TResource>> &vec) {
  887. unsigned resID = 0;
  888. for (std::vector<std::unique_ptr<TResource>>::iterator p = vec.begin(); p != vec.end();) {
  889. std::vector<std::unique_ptr<TResource>>::iterator c = p++;
  890. GlobalVariable *GV = cast<GlobalVariable>((*c)->GetGlobalSymbol());
  891. GV->removeDeadConstantUsers();
  892. if (GV->user_empty()) {
  893. p = vec.erase(c);
  894. GV->eraseFromParent();
  895. continue;
  896. }
  897. if ((*c)->GetID() != resID) {
  898. (*c)->SetID(resID);
  899. }
  900. resID++;
  901. }
  902. }
  903. }
  904. void DxilModule::RemoveUnusedResourceSymbols() {
  905. RemoveResourceSymbols(m_SRVs);
  906. RemoveResourceSymbols(m_UAVs);
  907. RemoveResourceSymbols(m_CBuffers);
  908. RemoveResourceSymbols(m_Samplers);
  909. }
  910. DxilSignature &DxilModule::GetInputSignature() {
  911. return m_EntrySignature->InputSignature;
  912. }
  913. const DxilSignature &DxilModule::GetInputSignature() const {
  914. return m_EntrySignature->InputSignature;
  915. }
  916. DxilSignature &DxilModule::GetOutputSignature() {
  917. return m_EntrySignature->OutputSignature;
  918. }
  919. const DxilSignature &DxilModule::GetOutputSignature() const {
  920. return m_EntrySignature->OutputSignature;
  921. }
  922. DxilSignature &DxilModule::GetPatchConstantSignature() {
  923. return m_EntrySignature->PatchConstantSignature;
  924. }
  925. const DxilSignature &DxilModule::GetPatchConstantSignature() const {
  926. return m_EntrySignature->PatchConstantSignature;
  927. }
  928. const RootSignatureHandle &DxilModule::GetRootSignature() const {
  929. return *m_RootSignature;
  930. }
  931. bool DxilModule::HasDxilEntrySignature(llvm::Function *F) const {
  932. return m_DxilEntrySignatureMap.find(F) != m_DxilEntrySignatureMap.end();
  933. }
  934. DxilEntrySignature &DxilModule::GetDxilEntrySignature(llvm::Function *F) {
  935. DXASSERT(m_DxilEntrySignatureMap.count(F) != 0, "cannot find F in map");
  936. return *m_DxilEntrySignatureMap[F];
  937. }
  938. void DxilModule::ReplaceDxilEntrySignature(llvm::Function *F,
  939. llvm::Function *NewF) {
  940. DXASSERT(m_DxilEntrySignatureMap.count(F) != 0, "cannot find F in map");
  941. std::unique_ptr<DxilEntrySignature> Sig =
  942. std::move(m_DxilEntrySignatureMap[F]);
  943. m_DxilEntrySignatureMap.erase(F);
  944. m_DxilEntrySignatureMap[NewF] = std::move(Sig);
  945. }
  946. bool DxilModule::HasDxilFunctionProps(const llvm::Function *F) const {
  947. return m_DxilFunctionPropsMap.find(F) != m_DxilFunctionPropsMap.end();
  948. }
  949. DxilFunctionProps &DxilModule::GetDxilFunctionProps(const llvm::Function *F) {
  950. return const_cast<DxilFunctionProps &>(
  951. static_cast<const DxilModule *>(this)->GetDxilFunctionProps(F));
  952. }
  953. const DxilFunctionProps &
  954. DxilModule::GetDxilFunctionProps(const llvm::Function *F) const {
  955. DXASSERT(m_DxilFunctionPropsMap.count(F) != 0, "cannot find F in map");
  956. return *(m_DxilFunctionPropsMap.find(F))->second.get();
  957. }
  958. void DxilModule::AddDxilFunctionProps(
  959. const llvm::Function *F, std::unique_ptr<DxilFunctionProps> &info) {
  960. DXASSERT(m_DxilFunctionPropsMap.count(F) == 0,
  961. "F already in map, info will be overwritten");
  962. DXASSERT_NOMSG(info->shaderKind != DXIL::ShaderKind::Invalid);
  963. m_DxilFunctionPropsMap[F] = std::move(info);
  964. }
  965. void DxilModule::ReplaceDxilFunctionProps(llvm::Function *F,
  966. llvm::Function *NewF) {
  967. DXASSERT(m_DxilFunctionPropsMap.count(F) != 0, "cannot find F in map");
  968. std::unique_ptr<DxilFunctionProps> props =
  969. std::move(m_DxilFunctionPropsMap[F]);
  970. m_DxilFunctionPropsMap.erase(F);
  971. m_DxilFunctionPropsMap[NewF] = std::move(props);
  972. }
  973. void DxilModule::SetPatchConstantFunctionForHS(llvm::Function *hullShaderFunc, llvm::Function *patchConstantFunc) {
  974. auto propIter = m_DxilFunctionPropsMap.find(hullShaderFunc);
  975. DXASSERT(propIter != m_DxilFunctionPropsMap.end(), "Hull shader must already have function props!");
  976. DxilFunctionProps &props = *(propIter->second);
  977. DXASSERT(props.IsHS(), "else hullShaderFunc is not a Hull Shader");
  978. if (props.ShaderProps.HS.patchConstantFunc)
  979. m_PatchConstantFunctions.erase(props.ShaderProps.HS.patchConstantFunc);
  980. props.ShaderProps.HS.patchConstantFunc = patchConstantFunc;
  981. if (patchConstantFunc)
  982. m_PatchConstantFunctions.insert(patchConstantFunc);
  983. }
  984. bool DxilModule::IsGraphicsShader(const llvm::Function *F) const {
  985. return HasDxilFunctionProps(F) && GetDxilFunctionProps(F).IsGraphics();
  986. }
  987. bool DxilModule::IsPatchConstantShader(const llvm::Function *F) const {
  988. return m_PatchConstantFunctions.count(F) != 0;
  989. }
  990. bool DxilModule::IsComputeShader(const llvm::Function *F) const {
  991. return HasDxilFunctionProps(F) && GetDxilFunctionProps(F).IsCS();
  992. }
  993. bool DxilModule::IsEntryThatUsesSignatures(const llvm::Function *F) const {
  994. auto propIter = m_DxilFunctionPropsMap.find(F);
  995. if (propIter != m_DxilFunctionPropsMap.end()) {
  996. DxilFunctionProps &props = *(propIter->second);
  997. return props.IsGraphics() || props.IsCS();
  998. }
  999. // Otherwise, return true if patch constant function
  1000. return IsPatchConstantShader(F);
  1001. }
  1002. void DxilModule::StripRootSignatureFromMetadata() {
  1003. NamedMDNode *pRootSignatureNamedMD = GetModule()->getNamedMetadata(DxilMDHelper::kDxilRootSignatureMDName);
  1004. if (pRootSignatureNamedMD) {
  1005. GetModule()->eraseNamedMetadata(pRootSignatureNamedMD);
  1006. }
  1007. }
  1008. void DxilModule::UpdateValidatorVersionMetadata() {
  1009. m_pMDHelper->EmitValidatorVersion(m_ValMajor, m_ValMinor);
  1010. }
  1011. void DxilModule::ResetEntrySignature(DxilEntrySignature *pValue) {
  1012. m_EntrySignature.reset(pValue);
  1013. }
  1014. void DxilModule::ResetRootSignature(RootSignatureHandle *pValue) {
  1015. m_RootSignature.reset(pValue);
  1016. }
  1017. DxilTypeSystem &DxilModule::GetTypeSystem() {
  1018. return *m_pTypeSystem;
  1019. }
  1020. DxilViewIdState &DxilModule::GetViewIdState() {
  1021. return *m_pViewIdState;
  1022. }
  1023. const DxilViewIdState &DxilModule::GetViewIdState() const {
  1024. return *m_pViewIdState;
  1025. }
  1026. void DxilModule::ResetTypeSystem(DxilTypeSystem *pValue) {
  1027. m_pTypeSystem.reset(pValue);
  1028. }
  1029. void DxilModule::ResetOP(hlsl::OP *hlslOP) { m_pOP.reset(hlslOP); }
  1030. void DxilModule::ResetFunctionPropsMap(DxilFunctionPropsMap &&propsMap) {
  1031. m_DxilFunctionPropsMap = std::move(propsMap);
  1032. }
  1033. void DxilModule::ResetEntrySignatureMap(DxilEntrySignatureMap &&SigMap) {
  1034. m_DxilEntrySignatureMap = std::move(SigMap);
  1035. }
  1036. static const StringRef llvmUsedName = "llvm.used";
  1037. void DxilModule::EmitLLVMUsed() {
  1038. if (GlobalVariable *oldGV = m_pModule->getGlobalVariable(llvmUsedName)) {
  1039. oldGV->eraseFromParent();
  1040. }
  1041. if (m_LLVMUsed.empty())
  1042. return;
  1043. vector<llvm::Constant *> GVs;
  1044. Type *pI8PtrType = Type::getInt8PtrTy(m_Ctx, DXIL::kDefaultAddrSpace);
  1045. GVs.resize(m_LLVMUsed.size());
  1046. for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
  1047. Constant *pConst = cast<Constant>(&*m_LLVMUsed[i]);
  1048. PointerType *pPtrType = dyn_cast<PointerType>(pConst->getType());
  1049. if (pPtrType->getPointerAddressSpace() != DXIL::kDefaultAddrSpace) {
  1050. // Cast pointer to addrspace 0, as LLVMUsed elements must have the same
  1051. // type.
  1052. GVs[i] = ConstantExpr::getAddrSpaceCast(pConst, pI8PtrType);
  1053. } else {
  1054. GVs[i] = ConstantExpr::getPointerCast(pConst, pI8PtrType);
  1055. }
  1056. }
  1057. ArrayType *pATy = ArrayType::get(pI8PtrType, GVs.size());
  1058. GlobalVariable *pGV =
  1059. new GlobalVariable(*m_pModule, pATy, false, GlobalValue::AppendingLinkage,
  1060. ConstantArray::get(pATy, GVs), llvmUsedName);
  1061. pGV->setSection("llvm.metadata");
  1062. }
  1063. void DxilModule::ClearLLVMUsed() {
  1064. if (GlobalVariable *oldGV = m_pModule->getGlobalVariable(llvmUsedName)) {
  1065. oldGV->eraseFromParent();
  1066. }
  1067. if (m_LLVMUsed.empty())
  1068. return;
  1069. for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
  1070. Constant *pConst = cast<Constant>(&*m_LLVMUsed[i]);
  1071. pConst->removeDeadConstantUsers();
  1072. }
  1073. m_LLVMUsed.clear();
  1074. }
  1075. vector<GlobalVariable* > &DxilModule::GetLLVMUsed() {
  1076. return m_LLVMUsed;
  1077. }
  1078. // DXIL metadata serialization/deserialization.
  1079. void DxilModule::ClearDxilMetadata(Module &M) {
  1080. // Delete: DXIL version, validator version, DXIL shader model,
  1081. // entry point tuples (shader properties, signatures, resources)
  1082. // type system, view ID state, LLVM used, entry point tuples,
  1083. // root signature, function properties.
  1084. // Other cases for libs pending.
  1085. // LLVM used is a global variable - handle separately.
  1086. Module::named_metadata_iterator
  1087. b = M.named_metadata_begin(),
  1088. e = M.named_metadata_end();
  1089. SmallVector<NamedMDNode*, 8> nodes;
  1090. for (; b != e; ++b) {
  1091. StringRef name = b->getName();
  1092. if (name == DxilMDHelper::kDxilVersionMDName ||
  1093. name == DxilMDHelper::kDxilValidatorVersionMDName ||
  1094. name == DxilMDHelper::kDxilShaderModelMDName ||
  1095. name == DxilMDHelper::kDxilEntryPointsMDName ||
  1096. name == DxilMDHelper::kDxilRootSignatureMDName ||
  1097. name == DxilMDHelper::kDxilResourcesMDName ||
  1098. name == DxilMDHelper::kDxilTypeSystemMDName ||
  1099. name == DxilMDHelper::kDxilViewIdStateMDName ||
  1100. name == DxilMDHelper::kDxilFunctionPropertiesMDName || // used in libraries
  1101. name == DxilMDHelper::kDxilEntrySignaturesMDName || // used in libraries
  1102. name == DxilMDHelper::kDxilResourcesLinkInfoMDName || // used in libraries
  1103. name.startswith(DxilMDHelper::kDxilTypeSystemHelperVariablePrefix)) {
  1104. nodes.push_back(b);
  1105. }
  1106. }
  1107. for (size_t i = 0; i < nodes.size(); ++i) {
  1108. M.eraseNamedMetadata(nodes[i]);
  1109. }
  1110. }
  1111. void DxilModule::EmitDxilMetadata() {
  1112. m_pMDHelper->EmitDxilVersion(m_DxilMajor, m_DxilMinor);
  1113. m_pMDHelper->EmitValidatorVersion(m_ValMajor, m_ValMinor);
  1114. m_pMDHelper->EmitDxilShaderModel(m_pSM);
  1115. MDTuple *pMDProperties = EmitDxilShaderProperties();
  1116. MDTuple *pMDSignatures = m_pMDHelper->EmitDxilSignatures(*m_EntrySignature);
  1117. MDTuple *pMDResources = EmitDxilResources();
  1118. if (pMDResources)
  1119. m_pMDHelper->EmitDxilResources(pMDResources);
  1120. m_pMDHelper->EmitDxilTypeSystem(GetTypeSystem(), m_LLVMUsed);
  1121. if (!m_pSM->IsLib() && !m_pSM->IsCS() &&
  1122. ((m_ValMajor == 0 && m_ValMinor == 0) ||
  1123. (m_ValMajor > 1 || (m_ValMajor == 1 && m_ValMinor >= 1)))) {
  1124. m_pMDHelper->EmitDxilViewIdState(GetViewIdState());
  1125. }
  1126. EmitLLVMUsed();
  1127. MDTuple *pEntry = m_pMDHelper->EmitDxilEntryPointTuple(GetEntryFunction(), m_EntryName, pMDSignatures, pMDResources, pMDProperties);
  1128. vector<MDNode *> Entries;
  1129. Entries.emplace_back(pEntry);
  1130. m_pMDHelper->EmitDxilEntryPoints(Entries);
  1131. if (!m_RootSignature->IsEmpty()) {
  1132. m_pMDHelper->EmitRootSignature(*m_RootSignature.get());
  1133. }
  1134. if (m_pSM->IsLib()) {
  1135. NamedMDNode *fnProps = m_pModule->getOrInsertNamedMetadata(
  1136. DxilMDHelper::kDxilFunctionPropertiesMDName);
  1137. // Sort functions by name to keep metadata deterministic
  1138. vector<Function *> funcOrder;
  1139. funcOrder.reserve(std::max(m_DxilFunctionPropsMap.size(),
  1140. m_DxilEntrySignatureMap.size()));
  1141. std::transform( m_DxilFunctionPropsMap.begin(),
  1142. m_DxilFunctionPropsMap.end(),
  1143. std::back_inserter(funcOrder),
  1144. [](auto &p) -> Function* { return p.first; } );
  1145. std::sort(funcOrder.begin(), funcOrder.end(), [](Function *F1, Function *F2) {
  1146. return F1->getName() < F2->getName();
  1147. });
  1148. for (auto F : funcOrder) {
  1149. MDTuple *pProps = m_pMDHelper->EmitDxilFunctionProps(&GetDxilFunctionProps(F), F);
  1150. fnProps->addOperand(pProps);
  1151. }
  1152. funcOrder.clear();
  1153. NamedMDNode *entrySigs = m_pModule->getOrInsertNamedMetadata(
  1154. DxilMDHelper::kDxilEntrySignaturesMDName);
  1155. // Sort functions by name to keep metadata deterministic
  1156. std::transform( m_DxilEntrySignatureMap.begin(),
  1157. m_DxilEntrySignatureMap.end(),
  1158. std::back_inserter(funcOrder),
  1159. [](auto &p) -> Function* { return p.first; } );
  1160. std::sort(funcOrder.begin(), funcOrder.end(), [](Function *F1, Function *F2) {
  1161. return F1->getName() < F2->getName();
  1162. });
  1163. for (auto F : funcOrder) {
  1164. DxilEntrySignature *Sig = &GetDxilEntrySignature(F);
  1165. MDTuple *pSig = m_pMDHelper->EmitDxilSignatures(*Sig);
  1166. entrySigs->addOperand(
  1167. MDTuple::get(m_Ctx, {ValueAsMetadata::get(F), pSig}));
  1168. }
  1169. }
  1170. }
  1171. bool DxilModule::IsKnownNamedMetaData(llvm::NamedMDNode &Node) {
  1172. return DxilMDHelper::IsKnownNamedMetaData(Node);
  1173. }
  1174. void DxilModule::LoadDxilMetadata() {
  1175. m_pMDHelper->LoadDxilVersion(m_DxilMajor, m_DxilMinor);
  1176. m_pMDHelper->LoadValidatorVersion(m_ValMajor, m_ValMinor);
  1177. const ShaderModel *loadedModule;
  1178. m_pMDHelper->LoadDxilShaderModel(loadedModule);
  1179. SetShaderModel(loadedModule);
  1180. DXASSERT(m_EntrySignature != nullptr, "else SetShaderModel didn't create entry signature");
  1181. const llvm::NamedMDNode *pEntries = m_pMDHelper->GetDxilEntryPoints();
  1182. IFTBOOL(pEntries->getNumOperands() == 1, DXC_E_INCORRECT_DXIL_METADATA);
  1183. Function *pEntryFunc;
  1184. string EntryName;
  1185. const llvm::MDOperand *pSignatures, *pResources, *pProperties;
  1186. m_pMDHelper->GetDxilEntryPoint(pEntries->getOperand(0), pEntryFunc, EntryName, pSignatures, pResources, pProperties);
  1187. SetEntryFunction(pEntryFunc);
  1188. SetEntryFunctionName(EntryName);
  1189. LoadDxilShaderProperties(*pProperties);
  1190. m_pMDHelper->LoadDxilSignatures(*pSignatures, *m_EntrySignature);
  1191. LoadDxilResources(*pResources);
  1192. m_pMDHelper->LoadDxilTypeSystem(*m_pTypeSystem.get());
  1193. m_pMDHelper->LoadRootSignature(*m_RootSignature.get());
  1194. m_pMDHelper->LoadDxilViewIdState(*m_pViewIdState.get());
  1195. if (loadedModule->IsLib()) {
  1196. NamedMDNode *fnProps = m_pModule->getNamedMetadata(
  1197. DxilMDHelper::kDxilFunctionPropertiesMDName);
  1198. size_t propIdx = 0;
  1199. while (propIdx < fnProps->getNumOperands()) {
  1200. MDTuple *pProps = dyn_cast<MDTuple>(fnProps->getOperand(propIdx++));
  1201. std::unique_ptr<hlsl::DxilFunctionProps> props =
  1202. llvm::make_unique<hlsl::DxilFunctionProps>();
  1203. Function *F = m_pMDHelper->LoadDxilFunctionProps(pProps, props.get());
  1204. if (props->IsHS() && props->ShaderProps.HS.patchConstantFunc) {
  1205. // Add patch constant function to m_PatchConstantFunctions
  1206. m_PatchConstantFunctions.insert(props->ShaderProps.HS.patchConstantFunc);
  1207. }
  1208. m_DxilFunctionPropsMap[F] = std::move(props);
  1209. }
  1210. NamedMDNode *entrySigs = m_pModule->getOrInsertNamedMetadata(
  1211. DxilMDHelper::kDxilEntrySignaturesMDName);
  1212. size_t sigIdx = 0;
  1213. while (sigIdx < entrySigs->getNumOperands()) {
  1214. MDTuple *pSig = dyn_cast<MDTuple>(entrySigs->getOperand(sigIdx++));
  1215. unsigned idx = 0;
  1216. Function *F = dyn_cast<Function>(
  1217. dyn_cast<ValueAsMetadata>(pSig->getOperand(idx++))->getValue());
  1218. // Entry must have props.
  1219. IFTBOOL(m_DxilFunctionPropsMap.count(F), DXC_E_INCORRECT_DXIL_METADATA);
  1220. DXIL::ShaderKind shaderKind = m_DxilFunctionPropsMap[F]->shaderKind;
  1221. std::unique_ptr<hlsl::DxilEntrySignature> Sig =
  1222. llvm::make_unique<hlsl::DxilEntrySignature>(shaderKind, !m_ShaderFlags.GetUseNativeLowPrecision());
  1223. m_pMDHelper->LoadDxilSignatures(pSig->getOperand(idx), *Sig);
  1224. m_DxilEntrySignatureMap[F] = std::move(Sig);
  1225. }
  1226. }
  1227. }
  1228. MDTuple *DxilModule::EmitDxilResources() {
  1229. // Emit SRV records.
  1230. MDTuple *pTupleSRVs = nullptr;
  1231. if (!m_SRVs.empty()) {
  1232. vector<Metadata *> MDVals;
  1233. for (size_t i = 0; i < m_SRVs.size(); i++) {
  1234. MDVals.emplace_back(m_pMDHelper->EmitDxilSRV(*m_SRVs[i]));
  1235. }
  1236. pTupleSRVs = MDNode::get(m_Ctx, MDVals);
  1237. }
  1238. // Emit UAV records.
  1239. MDTuple *pTupleUAVs = nullptr;
  1240. if (!m_UAVs.empty()) {
  1241. vector<Metadata *> MDVals;
  1242. for (size_t i = 0; i < m_UAVs.size(); i++) {
  1243. MDVals.emplace_back(m_pMDHelper->EmitDxilUAV(*m_UAVs[i]));
  1244. }
  1245. pTupleUAVs = MDNode::get(m_Ctx, MDVals);
  1246. }
  1247. // Emit CBuffer records.
  1248. MDTuple *pTupleCBuffers = nullptr;
  1249. if (!m_CBuffers.empty()) {
  1250. vector<Metadata *> MDVals;
  1251. for (size_t i = 0; i < m_CBuffers.size(); i++) {
  1252. MDVals.emplace_back(m_pMDHelper->EmitDxilCBuffer(*m_CBuffers[i]));
  1253. }
  1254. pTupleCBuffers = MDNode::get(m_Ctx, MDVals);
  1255. }
  1256. // Emit Sampler records.
  1257. MDTuple *pTupleSamplers = nullptr;
  1258. if (!m_Samplers.empty()) {
  1259. vector<Metadata *> MDVals;
  1260. for (size_t i = 0; i < m_Samplers.size(); i++) {
  1261. MDVals.emplace_back(m_pMDHelper->EmitDxilSampler(*m_Samplers[i]));
  1262. }
  1263. pTupleSamplers = MDNode::get(m_Ctx, MDVals);
  1264. }
  1265. if (pTupleSRVs != nullptr || pTupleUAVs != nullptr || pTupleCBuffers != nullptr || pTupleSamplers != nullptr) {
  1266. return m_pMDHelper->EmitDxilResourceTuple(pTupleSRVs, pTupleUAVs, pTupleCBuffers, pTupleSamplers);
  1267. } else {
  1268. return nullptr;
  1269. }
  1270. }
  1271. void DxilModule::ReEmitDxilResources() {
  1272. ClearDxilMetadata(*m_pModule);
  1273. if (!m_pSM->IsCS() && !m_pSM->IsLib())
  1274. m_pViewIdState->Compute();
  1275. EmitDxilMetadata();
  1276. }
  1277. void DxilModule::LoadDxilResources(const llvm::MDOperand &MDO) {
  1278. if (MDO.get() == nullptr)
  1279. return;
  1280. const llvm::MDTuple *pSRVs, *pUAVs, *pCBuffers, *pSamplers;
  1281. m_pMDHelper->GetDxilResources(MDO, pSRVs, pUAVs, pCBuffers, pSamplers);
  1282. // Load SRV records.
  1283. if (pSRVs != nullptr) {
  1284. for (unsigned i = 0; i < pSRVs->getNumOperands(); i++) {
  1285. unique_ptr<DxilResource> pSRV(new DxilResource);
  1286. m_pMDHelper->LoadDxilSRV(pSRVs->getOperand(i), *pSRV);
  1287. AddSRV(std::move(pSRV));
  1288. }
  1289. }
  1290. // Load UAV records.
  1291. if (pUAVs != nullptr) {
  1292. for (unsigned i = 0; i < pUAVs->getNumOperands(); i++) {
  1293. unique_ptr<DxilResource> pUAV(new DxilResource);
  1294. m_pMDHelper->LoadDxilUAV(pUAVs->getOperand(i), *pUAV);
  1295. AddUAV(std::move(pUAV));
  1296. }
  1297. }
  1298. // Load CBuffer records.
  1299. if (pCBuffers != nullptr) {
  1300. for (unsigned i = 0; i < pCBuffers->getNumOperands(); i++) {
  1301. unique_ptr<DxilCBuffer> pCB(new DxilCBuffer);
  1302. m_pMDHelper->LoadDxilCBuffer(pCBuffers->getOperand(i), *pCB);
  1303. AddCBuffer(std::move(pCB));
  1304. }
  1305. }
  1306. // Load Sampler records.
  1307. if (pSamplers != nullptr) {
  1308. for (unsigned i = 0; i < pSamplers->getNumOperands(); i++) {
  1309. unique_ptr<DxilSampler> pSampler(new DxilSampler);
  1310. m_pMDHelper->LoadDxilSampler(pSamplers->getOperand(i), *pSampler);
  1311. AddSampler(std::move(pSampler));
  1312. }
  1313. }
  1314. }
  1315. MDTuple *DxilModule::EmitDxilShaderProperties() {
  1316. vector<Metadata *> MDVals;
  1317. // DXIL shader flags.
  1318. uint64_t flag = m_ShaderFlags.GetShaderFlagsRaw();
  1319. if (flag != 0) {
  1320. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilShaderFlagsTag));
  1321. MDVals.emplace_back(m_pMDHelper->Uint64ToConstMD(flag));
  1322. }
  1323. // Compute shader.
  1324. if (m_pSM->IsCS()) {
  1325. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilNumThreadsTag));
  1326. vector<Metadata *> NumThreadVals;
  1327. NumThreadVals.emplace_back(m_pMDHelper->Uint32ToConstMD(m_NumThreads[0]));
  1328. NumThreadVals.emplace_back(m_pMDHelper->Uint32ToConstMD(m_NumThreads[1]));
  1329. NumThreadVals.emplace_back(m_pMDHelper->Uint32ToConstMD(m_NumThreads[2]));
  1330. MDVals.emplace_back(MDNode::get(m_Ctx, NumThreadVals));
  1331. }
  1332. // Geometry shader.
  1333. if (m_pSM->IsGS()) {
  1334. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilGSStateTag));
  1335. MDTuple *pMDTuple = m_pMDHelper->EmitDxilGSState(m_InputPrimitive,
  1336. m_MaxVertexCount,
  1337. GetActiveStreamMask(),
  1338. m_StreamPrimitiveTopology,
  1339. m_NumGSInstances);
  1340. MDVals.emplace_back(pMDTuple);
  1341. }
  1342. // Domain shader.
  1343. if (m_pSM->IsDS()) {
  1344. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilDSStateTag));
  1345. MDTuple *pMDTuple = m_pMDHelper->EmitDxilDSState(m_TessellatorDomain,
  1346. m_InputControlPointCount);
  1347. MDVals.emplace_back(pMDTuple);
  1348. }
  1349. // Hull shader.
  1350. if (m_pSM->IsHS()) {
  1351. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilHSStateTag));
  1352. MDTuple *pMDTuple = m_pMDHelper->EmitDxilHSState(m_pPatchConstantFunc,
  1353. m_InputControlPointCount,
  1354. m_OutputControlPointCount,
  1355. m_TessellatorDomain,
  1356. m_TessellatorPartitioning,
  1357. m_TessellatorOutputPrimitive,
  1358. m_MaxTessellationFactor);
  1359. MDVals.emplace_back(pMDTuple);
  1360. }
  1361. if (!MDVals.empty())
  1362. return MDNode::get(m_Ctx, MDVals);
  1363. else
  1364. return nullptr;
  1365. }
  1366. void DxilModule::LoadDxilShaderProperties(const MDOperand &MDO) {
  1367. if (MDO.get() == nullptr)
  1368. return;
  1369. const MDTuple *pTupleMD = dyn_cast<MDTuple>(MDO.get());
  1370. IFTBOOL(pTupleMD != nullptr, DXC_E_INCORRECT_DXIL_METADATA);
  1371. IFTBOOL((pTupleMD->getNumOperands() & 0x1) == 0, DXC_E_INCORRECT_DXIL_METADATA);
  1372. for (unsigned iNode = 0; iNode < pTupleMD->getNumOperands(); iNode += 2) {
  1373. unsigned Tag = DxilMDHelper::ConstMDToUint32(pTupleMD->getOperand(iNode));
  1374. const MDOperand &MDO = pTupleMD->getOperand(iNode + 1);
  1375. IFTBOOL(MDO.get() != nullptr, DXC_E_INCORRECT_DXIL_METADATA);
  1376. switch (Tag) {
  1377. case DxilMDHelper::kDxilShaderFlagsTag:
  1378. m_ShaderFlags.SetShaderFlagsRaw(DxilMDHelper::ConstMDToUint64(MDO));
  1379. break;
  1380. case DxilMDHelper::kDxilNumThreadsTag: {
  1381. MDNode *pNode = cast<MDNode>(MDO.get());
  1382. m_NumThreads[0] = DxilMDHelper::ConstMDToUint32(pNode->getOperand(0));
  1383. m_NumThreads[1] = DxilMDHelper::ConstMDToUint32(pNode->getOperand(1));
  1384. m_NumThreads[2] = DxilMDHelper::ConstMDToUint32(pNode->getOperand(2));
  1385. break;
  1386. }
  1387. case DxilMDHelper::kDxilGSStateTag: {
  1388. m_pMDHelper->LoadDxilGSState(MDO, m_InputPrimitive, m_MaxVertexCount, m_ActiveStreamMask,
  1389. m_StreamPrimitiveTopology, m_NumGSInstances);
  1390. break;
  1391. }
  1392. case DxilMDHelper::kDxilDSStateTag:
  1393. m_pMDHelper->LoadDxilDSState(MDO, m_TessellatorDomain, m_InputControlPointCount);
  1394. break;
  1395. case DxilMDHelper::kDxilHSStateTag:
  1396. m_pMDHelper->LoadDxilHSState(MDO,
  1397. m_pPatchConstantFunc,
  1398. m_InputControlPointCount,
  1399. m_OutputControlPointCount,
  1400. m_TessellatorDomain,
  1401. m_TessellatorPartitioning,
  1402. m_TessellatorOutputPrimitive,
  1403. m_MaxTessellationFactor);
  1404. break;
  1405. default:
  1406. DXASSERT(false, "Unknown extended shader properties tag");
  1407. break;
  1408. }
  1409. }
  1410. }
  1411. void DxilModule::StripDebugRelatedCode() {
  1412. // Remove all users of global resources.
  1413. for (GlobalVariable &GV : m_pModule->globals()) {
  1414. if (GV.hasInternalLinkage())
  1415. continue;
  1416. if (GV.getType()->getPointerAddressSpace() == DXIL::kTGSMAddrSpace)
  1417. continue;
  1418. for (auto git = GV.user_begin(); git != GV.user_end();) {
  1419. User *U = *(git++);
  1420. // Try to remove load of GV.
  1421. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  1422. for (auto it = LI->user_begin(); it != LI->user_end();) {
  1423. Instruction *LIUser = cast<Instruction>(*(it++));
  1424. if (StoreInst *SI = dyn_cast<StoreInst>(LIUser)) {
  1425. Value *Ptr = SI->getPointerOperand();
  1426. SI->eraseFromParent();
  1427. if (Instruction *PtrInst = dyn_cast<Instruction>(Ptr)) {
  1428. if (Ptr->user_empty())
  1429. PtrInst->eraseFromParent();
  1430. }
  1431. }
  1432. }
  1433. if (LI->user_empty())
  1434. LI->eraseFromParent();
  1435. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
  1436. for (auto GEPIt = GEP->user_begin(); GEPIt != GEP->user_end();) {
  1437. User *GEPU = *(GEPIt++);
  1438. // Try to remove load of GEP.
  1439. if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
  1440. for (auto it = LI->user_begin(); it != LI->user_end();) {
  1441. Instruction *LIUser = cast<Instruction>(*(it++));
  1442. if (StoreInst *SI = dyn_cast<StoreInst>(LIUser)) {
  1443. Value *Ptr = SI->getPointerOperand();
  1444. SI->eraseFromParent();
  1445. if (Instruction *PtrInst = dyn_cast<Instruction>(Ptr)) {
  1446. if (Ptr->user_empty())
  1447. PtrInst->eraseFromParent();
  1448. }
  1449. }
  1450. if (LI->user_empty())
  1451. LI->eraseFromParent();
  1452. }
  1453. }
  1454. }
  1455. if (GEP->user_empty())
  1456. GEP->eraseFromParent();
  1457. }
  1458. }
  1459. }
  1460. }
  1461. DebugInfoFinder &DxilModule::GetOrCreateDebugInfoFinder() {
  1462. if (m_pDebugInfoFinder == nullptr) {
  1463. m_pDebugInfoFinder = std::make_unique<llvm::DebugInfoFinder>();
  1464. m_pDebugInfoFinder->processModule(*m_pModule);
  1465. }
  1466. return *m_pDebugInfoFinder;
  1467. }
  1468. hlsl::DxilModule *hlsl::DxilModule::TryGetDxilModule(llvm::Module *pModule) {
  1469. LLVMContext &Ctx = pModule->getContext();
  1470. std::string diagStr;
  1471. raw_string_ostream diagStream(diagStr);
  1472. hlsl::DxilModule *pDxilModule = nullptr;
  1473. // TODO: add detail error in DxilMDHelper.
  1474. try {
  1475. pDxilModule = &pModule->GetOrCreateDxilModule();
  1476. } catch (const ::hlsl::Exception &hlslException) {
  1477. diagStream << "load dxil metadata failed -";
  1478. try {
  1479. const char *msg = hlslException.what();
  1480. if (msg == nullptr || *msg == '\0')
  1481. diagStream << " error code " << hlslException.hr << "\n";
  1482. else
  1483. diagStream << msg;
  1484. } catch (...) {
  1485. diagStream << " unable to retrieve error message.\n";
  1486. }
  1487. Ctx.diagnose(DxilErrorDiagnosticInfo(diagStream.str().c_str()));
  1488. } catch (...) {
  1489. Ctx.diagnose(DxilErrorDiagnosticInfo("load dxil metadata failed - unknown error.\n"));
  1490. }
  1491. return pDxilModule;
  1492. }
  1493. // Check if the instruction has fast math flags configured to indicate
  1494. // the instruction is precise.
  1495. // Precise fast math flags means none of the fast math flags are set.
  1496. bool DxilModule::HasPreciseFastMathFlags(const Instruction *inst) {
  1497. return isa<FPMathOperator>(inst) && !inst->getFastMathFlags().any();
  1498. }
  1499. // Set fast math flags configured to indicate the instruction is precise.
  1500. void DxilModule::SetPreciseFastMathFlags(llvm::Instruction *inst) {
  1501. assert(isa<FPMathOperator>(inst));
  1502. inst->copyFastMathFlags(FastMathFlags());
  1503. }
  1504. // True if fast math flags are preserved across serialization/deserialization
  1505. // of the dxil module.
  1506. //
  1507. // We need to check for this when querying fast math flags for preciseness
  1508. // otherwise we will be overly conservative by reporting instructions precise
  1509. // because their fast math flags were not preserved.
  1510. //
  1511. // Currently we restrict it to the instruction types that have fast math
  1512. // preserved in the bitcode. We can expand this by converting fast math
  1513. // flags to dx.precise metadata during serialization and back to fast
  1514. // math flags during deserialization.
  1515. bool DxilModule::PreservesFastMathFlags(const llvm::Instruction *inst) {
  1516. return
  1517. isa<FPMathOperator>(inst) && (isa<BinaryOperator>(inst) || isa<FCmpInst>(inst));
  1518. }
  1519. bool DxilModule::IsPrecise(const Instruction *inst) const {
  1520. if (m_ShaderFlags.GetDisableMathRefactoring())
  1521. return true;
  1522. else if (DxilMDHelper::IsMarkedPrecise(inst))
  1523. return true;
  1524. else if (PreservesFastMathFlags(inst))
  1525. return HasPreciseFastMathFlags(inst);
  1526. else
  1527. return false;
  1528. }
  1529. } // namespace hlsl
  1530. namespace llvm {
  1531. hlsl::DxilModule &Module::GetOrCreateDxilModule(bool skipInit) {
  1532. std::unique_ptr<hlsl::DxilModule> M;
  1533. if (!HasDxilModule()) {
  1534. M = std::make_unique<hlsl::DxilModule>(this);
  1535. if (!skipInit) {
  1536. M->LoadDxilMetadata();
  1537. }
  1538. SetDxilModule(M.release());
  1539. }
  1540. return GetDxilModule();
  1541. }
  1542. void Module::ResetDxilModule() {
  1543. if (HasDxilModule()) {
  1544. delete TheDxilModule;
  1545. TheDxilModule = nullptr;
  1546. }
  1547. }
  1548. }