DxilModule.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838
  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. static void CreateResourceLinkConstant(Module &M, DxilResourceBase *pRes,
  765. std::vector<DxilModule::ResourceLinkInfo> &resLinkInfo) {
  766. Type *i32Ty = Type::getInt32Ty(M.getContext());
  767. const bool IsConstantTrue = true;
  768. Constant *NullInitVal = nullptr;
  769. GlobalVariable *rangeID = new GlobalVariable(
  770. M, i32Ty, IsConstantTrue, llvm::GlobalValue::ExternalLinkage, NullInitVal,
  771. pRes->GetGlobalName() + "_rangeID");
  772. resLinkInfo.emplace_back(DxilModule::ResourceLinkInfo{rangeID});
  773. }
  774. void DxilModule::CreateResourceLinkInfo() {
  775. DXASSERT(GetShaderModel()->IsLib(), "only for library profile");
  776. DXASSERT(m_SRVsLinkInfo.empty() && m_UAVsLinkInfo.empty() &&
  777. m_CBuffersLinkInfo.empty() && m_SamplersLinkInfo.empty(),
  778. "else resource link info was already created");
  779. Module &M = *m_pModule;
  780. for (auto &SRV : m_SRVs) {
  781. CreateResourceLinkConstant(M, SRV.get(), m_SRVsLinkInfo);
  782. }
  783. for (auto &UAV : m_UAVs) {
  784. CreateResourceLinkConstant(M, UAV.get(), m_UAVsLinkInfo);
  785. }
  786. for (auto &CBuffer : m_CBuffers) {
  787. CreateResourceLinkConstant(M, CBuffer.get(), m_CBuffersLinkInfo);
  788. }
  789. for (auto &Sampler : m_Samplers) {
  790. CreateResourceLinkConstant(M, Sampler.get(), m_SamplersLinkInfo);
  791. }
  792. }
  793. const DxilModule::ResourceLinkInfo &
  794. DxilModule::GetResourceLinkInfo(DXIL::ResourceClass resClass,
  795. unsigned rangeID) const {
  796. switch (resClass) {
  797. case DXIL::ResourceClass::UAV:
  798. return m_UAVsLinkInfo[rangeID];
  799. case DXIL::ResourceClass::CBuffer:
  800. return m_CBuffersLinkInfo[rangeID];
  801. case DXIL::ResourceClass::Sampler:
  802. return m_SamplersLinkInfo[rangeID];
  803. default:
  804. DXASSERT(DXIL::ResourceClass::SRV == resClass,
  805. "else invalid resource class");
  806. return m_SRVsLinkInfo[rangeID];
  807. }
  808. }
  809. void DxilModule::LoadDxilResourceBaseFromMDNode(MDNode *MD, DxilResourceBase &R) {
  810. return m_pMDHelper->LoadDxilResourceBaseFromMDNode(MD, R);
  811. }
  812. void DxilModule::LoadDxilResourceFromMDNode(llvm::MDNode *MD, DxilResource &R) {
  813. return m_pMDHelper->LoadDxilResourceFromMDNode(MD, R);
  814. }
  815. void DxilModule::LoadDxilSamplerFromMDNode(llvm::MDNode *MD, DxilSampler &S) {
  816. return m_pMDHelper->LoadDxilSamplerFromMDNode(MD, S);
  817. }
  818. template <typename TResource>
  819. static void RemoveResources(std::vector<std::unique_ptr<TResource>> &vec,
  820. std::unordered_set<unsigned> &immResID) {
  821. for (std::vector<std::unique_ptr<TResource>>::iterator p = vec.begin(); p != vec.end();) {
  822. std::vector<std::unique_ptr<TResource>>::iterator c = p++;
  823. if (immResID.count((*c)->GetID()) == 0) {
  824. p = vec.erase(c);
  825. }
  826. }
  827. }
  828. static void CollectUsedResource(Value *resID,
  829. std::unordered_set<Value *> &usedResID) {
  830. if (usedResID.count(resID) > 0)
  831. return;
  832. usedResID.insert(resID);
  833. if (ConstantInt *cResID = dyn_cast<ConstantInt>(resID)) {
  834. // Do nothing
  835. } else if (ZExtInst *ZEI = dyn_cast<ZExtInst>(resID)) {
  836. if (ZEI->getSrcTy()->isIntegerTy()) {
  837. IntegerType *ITy = cast<IntegerType>(ZEI->getSrcTy());
  838. if (ITy->getBitWidth() == 1) {
  839. usedResID.insert(ConstantInt::get(ZEI->getDestTy(), 0));
  840. usedResID.insert(ConstantInt::get(ZEI->getDestTy(), 1));
  841. }
  842. }
  843. } else if (SelectInst *SI = dyn_cast<SelectInst>(resID)) {
  844. CollectUsedResource(SI->getTrueValue(), usedResID);
  845. CollectUsedResource(SI->getFalseValue(), usedResID);
  846. } else if (PHINode *Phi = dyn_cast<PHINode>(resID)) {
  847. for (Use &U : Phi->incoming_values()) {
  848. CollectUsedResource(U.get(), usedResID);
  849. }
  850. }
  851. // TODO: resID could be other types of instructions depending on the compiler optimization.
  852. }
  853. static void ConvertUsedResource(std::unordered_set<unsigned> &immResID,
  854. std::unordered_set<Value *> &usedResID) {
  855. for (Value *V : usedResID) {
  856. if (ConstantInt *cResID = dyn_cast<ConstantInt>(V)) {
  857. immResID.insert(cResID->getLimitedValue());
  858. }
  859. }
  860. }
  861. void DxilModule::RemoveFunction(llvm::Function *F) {
  862. DXASSERT_NOMSG(F != nullptr);
  863. m_DxilFunctionPropsMap.erase(F);
  864. m_DxilEntrySignatureMap.erase(F);
  865. if (m_pTypeSystem.get()->GetFunctionAnnotation(F))
  866. m_pTypeSystem.get()->EraseFunctionAnnotation(F);
  867. m_pOP->RemoveFunction(F);
  868. }
  869. void DxilModule::RemoveUnusedResources() {
  870. hlsl::OP *hlslOP = GetOP();
  871. Function *createHandleFunc = hlslOP->GetOpFunc(DXIL::OpCode::CreateHandle, Type::getVoidTy(GetCtx()));
  872. if (createHandleFunc->user_empty()) {
  873. m_CBuffers.clear();
  874. m_UAVs.clear();
  875. m_SRVs.clear();
  876. m_Samplers.clear();
  877. createHandleFunc->eraseFromParent();
  878. return;
  879. }
  880. std::unordered_set<Value *> usedUAVID;
  881. std::unordered_set<Value *> usedSRVID;
  882. std::unordered_set<Value *> usedSamplerID;
  883. std::unordered_set<Value *> usedCBufID;
  884. // Collect used ID.
  885. for (User *U : createHandleFunc->users()) {
  886. CallInst *CI = cast<CallInst>(U);
  887. Value *vResClass =
  888. CI->getArgOperand(DXIL::OperandIndex::kCreateHandleResClassOpIdx);
  889. ConstantInt *cResClass = cast<ConstantInt>(vResClass);
  890. DXIL::ResourceClass resClass =
  891. static_cast<DXIL::ResourceClass>(cResClass->getLimitedValue());
  892. // Skip unused resource handle.
  893. if (CI->user_empty())
  894. continue;
  895. Value *resID =
  896. CI->getArgOperand(DXIL::OperandIndex::kCreateHandleResIDOpIdx);
  897. switch (resClass) {
  898. case DXIL::ResourceClass::CBuffer:
  899. CollectUsedResource(resID, usedCBufID);
  900. break;
  901. case DXIL::ResourceClass::Sampler:
  902. CollectUsedResource(resID, usedSamplerID);
  903. break;
  904. case DXIL::ResourceClass::SRV:
  905. CollectUsedResource(resID, usedSRVID);
  906. break;
  907. case DXIL::ResourceClass::UAV:
  908. CollectUsedResource(resID, usedUAVID);
  909. break;
  910. default:
  911. DXASSERT(0, "invalid res class");
  912. break;
  913. }
  914. }
  915. std::unordered_set<unsigned> immUAVID;
  916. std::unordered_set<unsigned> immSRVID;
  917. std::unordered_set<unsigned> immSamplerID;
  918. std::unordered_set<unsigned> immCBufID;
  919. ConvertUsedResource(immUAVID, usedUAVID);
  920. RemoveResources(m_UAVs, immUAVID);
  921. ConvertUsedResource(immSRVID, usedSRVID);
  922. ConvertUsedResource(immSamplerID, usedSamplerID);
  923. ConvertUsedResource(immCBufID, usedCBufID);
  924. RemoveResources(m_SRVs, immSRVID);
  925. RemoveResources(m_Samplers, immSamplerID);
  926. RemoveResources(m_CBuffers, immCBufID);
  927. }
  928. namespace {
  929. template <typename TResource>
  930. static void RemoveResourceSymbols(std::vector<std::unique_ptr<TResource>> &vec) {
  931. for (std::vector<std::unique_ptr<TResource>>::iterator p = vec.begin(); p != vec.end();) {
  932. std::vector<std::unique_ptr<TResource>>::iterator c = p++;
  933. GlobalVariable *GV = cast<GlobalVariable>((*c)->GetGlobalSymbol());
  934. GV->removeDeadConstantUsers();
  935. if (GV->user_empty()) {
  936. p = vec.erase(c);
  937. }
  938. }
  939. }
  940. }
  941. void DxilModule::RemoveUnusedResourceSymbols() {
  942. RemoveResourceSymbols(m_SRVs);
  943. RemoveResourceSymbols(m_UAVs);
  944. RemoveResourceSymbols(m_CBuffers);
  945. RemoveResourceSymbols(m_Samplers);
  946. }
  947. DxilSignature &DxilModule::GetInputSignature() {
  948. return m_EntrySignature->InputSignature;
  949. }
  950. const DxilSignature &DxilModule::GetInputSignature() const {
  951. return m_EntrySignature->InputSignature;
  952. }
  953. DxilSignature &DxilModule::GetOutputSignature() {
  954. return m_EntrySignature->OutputSignature;
  955. }
  956. const DxilSignature &DxilModule::GetOutputSignature() const {
  957. return m_EntrySignature->OutputSignature;
  958. }
  959. DxilSignature &DxilModule::GetPatchConstantSignature() {
  960. return m_EntrySignature->PatchConstantSignature;
  961. }
  962. const DxilSignature &DxilModule::GetPatchConstantSignature() const {
  963. return m_EntrySignature->PatchConstantSignature;
  964. }
  965. const RootSignatureHandle &DxilModule::GetRootSignature() const {
  966. return *m_RootSignature;
  967. }
  968. bool DxilModule::HasDxilEntrySignature(llvm::Function *F) const {
  969. return m_DxilEntrySignatureMap.find(F) != m_DxilEntrySignatureMap.end();
  970. }
  971. DxilEntrySignature &DxilModule::GetDxilEntrySignature(llvm::Function *F) {
  972. DXASSERT(m_DxilEntrySignatureMap.count(F) != 0, "cannot find F in map");
  973. return *m_DxilEntrySignatureMap[F];
  974. }
  975. void DxilModule::ReplaceDxilEntrySignature(llvm::Function *F,
  976. llvm::Function *NewF) {
  977. DXASSERT(m_DxilEntrySignatureMap.count(F) != 0, "cannot find F in map");
  978. std::unique_ptr<DxilEntrySignature> Sig =
  979. std::move(m_DxilEntrySignatureMap[F]);
  980. m_DxilEntrySignatureMap.erase(F);
  981. m_DxilEntrySignatureMap[NewF] = std::move(Sig);
  982. }
  983. bool DxilModule::HasDxilFunctionProps(llvm::Function *F) const {
  984. return m_DxilFunctionPropsMap.find(F) != m_DxilFunctionPropsMap.end();
  985. }
  986. DxilFunctionProps &DxilModule::GetDxilFunctionProps(llvm::Function *F) {
  987. DXASSERT(m_DxilFunctionPropsMap.count(F) != 0, "cannot find F in map");
  988. return *m_DxilFunctionPropsMap[F];
  989. }
  990. void DxilModule::ReplaceDxilFunctionProps(llvm::Function *F,
  991. llvm::Function *NewF) {
  992. DXASSERT(m_DxilFunctionPropsMap.count(F) != 0, "cannot find F in map");
  993. std::unique_ptr<DxilFunctionProps> props =
  994. std::move(m_DxilFunctionPropsMap[F]);
  995. m_DxilFunctionPropsMap.erase(F);
  996. m_DxilFunctionPropsMap[NewF] = std::move(props);
  997. }
  998. void DxilModule::SetPatchConstantFunctionForHS(llvm::Function *hullShaderFunc, llvm::Function *patchConstantFunc) {
  999. auto propIter = m_DxilFunctionPropsMap.find(hullShaderFunc);
  1000. DXASSERT(propIter != m_DxilFunctionPropsMap.end(), "Hull shader must already have function props!");
  1001. DxilFunctionProps &props = *(propIter->second);
  1002. DXASSERT(props.IsHS(), "else hullShaderFunc is not a Hull Shader");
  1003. if (props.ShaderProps.HS.patchConstantFunc)
  1004. m_PatchConstantFunctions.erase(props.ShaderProps.HS.patchConstantFunc);
  1005. props.ShaderProps.HS.patchConstantFunc = patchConstantFunc;
  1006. if (patchConstantFunc)
  1007. m_PatchConstantFunctions.insert(patchConstantFunc);
  1008. }
  1009. bool DxilModule::IsGraphicsShader(llvm::Function *F) {
  1010. return HasDxilFunctionProps(F) && GetDxilFunctionProps(F).IsGraphics();
  1011. }
  1012. bool DxilModule::IsPatchConstantShader(llvm::Function *F) {
  1013. return m_PatchConstantFunctions.count(F) != 0;
  1014. }
  1015. bool DxilModule::IsComputeShader(llvm::Function *F) {
  1016. return HasDxilFunctionProps(F) && GetDxilFunctionProps(F).IsCS();
  1017. }
  1018. bool DxilModule::IsEntryThatUsesSignatures(llvm::Function *F) {
  1019. auto propIter = m_DxilFunctionPropsMap.find(F);
  1020. if (propIter != m_DxilFunctionPropsMap.end()) {
  1021. DxilFunctionProps &props = *(propIter->second);
  1022. return props.IsGraphics() || props.IsCS();
  1023. }
  1024. // Otherwise, return true if patch constant function
  1025. return IsPatchConstantShader(F);
  1026. }
  1027. void DxilModule::StripRootSignatureFromMetadata() {
  1028. NamedMDNode *pRootSignatureNamedMD = GetModule()->getNamedMetadata(DxilMDHelper::kDxilRootSignatureMDName);
  1029. if (pRootSignatureNamedMD) {
  1030. GetModule()->eraseNamedMetadata(pRootSignatureNamedMD);
  1031. }
  1032. }
  1033. void DxilModule::UpdateValidatorVersionMetadata() {
  1034. m_pMDHelper->EmitValidatorVersion(m_ValMajor, m_ValMinor);
  1035. }
  1036. void DxilModule::ResetEntrySignature(DxilEntrySignature *pValue) {
  1037. m_EntrySignature.reset(pValue);
  1038. }
  1039. void DxilModule::ResetRootSignature(RootSignatureHandle *pValue) {
  1040. m_RootSignature.reset(pValue);
  1041. }
  1042. DxilTypeSystem &DxilModule::GetTypeSystem() {
  1043. return *m_pTypeSystem;
  1044. }
  1045. DxilViewIdState &DxilModule::GetViewIdState() {
  1046. return *m_pViewIdState;
  1047. }
  1048. const DxilViewIdState &DxilModule::GetViewIdState() const {
  1049. return *m_pViewIdState;
  1050. }
  1051. void DxilModule::ResetTypeSystem(DxilTypeSystem *pValue) {
  1052. m_pTypeSystem.reset(pValue);
  1053. }
  1054. void DxilModule::ResetOP(hlsl::OP *hlslOP) { m_pOP.reset(hlslOP); }
  1055. void DxilModule::ResetFunctionPropsMap(
  1056. std::unordered_map<llvm::Function *, std::unique_ptr<DxilFunctionProps>>
  1057. &&propsMap) {
  1058. m_DxilFunctionPropsMap = std::move(propsMap);
  1059. }
  1060. void DxilModule::ResetEntrySignatureMap(
  1061. std::unordered_map<llvm::Function *, std::unique_ptr<DxilEntrySignature>>
  1062. &&SigMap) {
  1063. m_DxilEntrySignatureMap = std::move(SigMap);
  1064. }
  1065. void DxilModule::EmitLLVMUsed() {
  1066. if (m_LLVMUsed.empty())
  1067. return;
  1068. vector<llvm::Constant*> GVs;
  1069. Type *pI8PtrType = Type::getInt8PtrTy(m_Ctx, DXIL::kDefaultAddrSpace);
  1070. GVs.resize(m_LLVMUsed.size());
  1071. for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
  1072. Constant *pConst = cast<Constant>(&*m_LLVMUsed[i]);
  1073. PointerType * pPtrType = dyn_cast<PointerType>(pConst->getType());
  1074. if (pPtrType->getPointerAddressSpace() != DXIL::kDefaultAddrSpace) {
  1075. // Cast pointer to addrspace 0, as LLVMUsed elements must have the same type.
  1076. GVs[i] = ConstantExpr::getAddrSpaceCast(pConst, pI8PtrType);
  1077. } else {
  1078. GVs[i] = ConstantExpr::getPointerCast(pConst, pI8PtrType);
  1079. }
  1080. }
  1081. ArrayType *pATy = ArrayType::get(pI8PtrType, GVs.size());
  1082. StringRef llvmUsedName = "llvm.used";
  1083. if (GlobalVariable *oldGV = m_pModule->getGlobalVariable(llvmUsedName)) {
  1084. oldGV->eraseFromParent();
  1085. }
  1086. GlobalVariable *pGV = new GlobalVariable(*m_pModule, pATy, false,
  1087. GlobalValue::AppendingLinkage,
  1088. ConstantArray::get(pATy, GVs),
  1089. llvmUsedName);
  1090. pGV->setSection("llvm.metadata");
  1091. }
  1092. vector<GlobalVariable* > &DxilModule::GetLLVMUsed() {
  1093. return m_LLVMUsed;
  1094. }
  1095. // DXIL metadata serialization/deserialization.
  1096. void DxilModule::ClearDxilMetadata(Module &M) {
  1097. // Delete: DXIL version, validator version, DXIL shader model,
  1098. // entry point tuples (shader properties, signatures, resources)
  1099. // type system, view ID state, LLVM used, entry point tuples,
  1100. // root signature, function properties.
  1101. // Other cases for libs pending.
  1102. // LLVM used is a global variable - handle separately.
  1103. Module::named_metadata_iterator
  1104. b = M.named_metadata_begin(),
  1105. e = M.named_metadata_end();
  1106. SmallVector<NamedMDNode*, 8> nodes;
  1107. for (; b != e; ++b) {
  1108. StringRef name = b->getName();
  1109. if (name == DxilMDHelper::kDxilVersionMDName ||
  1110. name == DxilMDHelper::kDxilValidatorVersionMDName ||
  1111. name == DxilMDHelper::kDxilShaderModelMDName ||
  1112. name == DxilMDHelper::kDxilEntryPointsMDName ||
  1113. name == DxilMDHelper::kDxilRootSignatureMDName ||
  1114. name == DxilMDHelper::kDxilResourcesMDName ||
  1115. name == DxilMDHelper::kDxilTypeSystemMDName ||
  1116. name == DxilMDHelper::kDxilViewIdStateMDName ||
  1117. name == DxilMDHelper::kDxilFunctionPropertiesMDName || // used in libraries
  1118. name == DxilMDHelper::kDxilEntrySignaturesMDName || // used in libraries
  1119. name == DxilMDHelper::kDxilResourcesLinkInfoMDName || // used in libraries
  1120. name.startswith(DxilMDHelper::kDxilTypeSystemHelperVariablePrefix)) {
  1121. nodes.push_back(b);
  1122. }
  1123. }
  1124. for (size_t i = 0; i < nodes.size(); ++i) {
  1125. M.eraseNamedMetadata(nodes[i]);
  1126. }
  1127. }
  1128. void DxilModule::EmitDxilMetadata() {
  1129. m_pMDHelper->EmitDxilVersion(m_DxilMajor, m_DxilMinor);
  1130. m_pMDHelper->EmitValidatorVersion(m_ValMajor, m_ValMinor);
  1131. m_pMDHelper->EmitDxilShaderModel(m_pSM);
  1132. MDTuple *pMDProperties = EmitDxilShaderProperties();
  1133. MDTuple *pMDSignatures = m_pMDHelper->EmitDxilSignatures(*m_EntrySignature);
  1134. MDTuple *pMDResources = EmitDxilResources();
  1135. if (pMDResources)
  1136. m_pMDHelper->EmitDxilResources(pMDResources);
  1137. m_pMDHelper->EmitDxilTypeSystem(GetTypeSystem(), m_LLVMUsed);
  1138. if (!m_pSM->IsLib() && !m_pSM->IsCS() &&
  1139. ((m_ValMajor == 0 && m_ValMinor == 0) ||
  1140. (m_ValMajor > 1 || (m_ValMajor == 1 && m_ValMinor >= 1)))) {
  1141. m_pMDHelper->EmitDxilViewIdState(GetViewIdState());
  1142. }
  1143. EmitLLVMUsed();
  1144. MDTuple *pEntry = m_pMDHelper->EmitDxilEntryPointTuple(GetEntryFunction(), m_EntryName, pMDSignatures, pMDResources, pMDProperties);
  1145. vector<MDNode *> Entries;
  1146. Entries.emplace_back(pEntry);
  1147. m_pMDHelper->EmitDxilEntryPoints(Entries);
  1148. if (!m_RootSignature->IsEmpty()) {
  1149. m_pMDHelper->EmitRootSignature(*m_RootSignature.get());
  1150. }
  1151. if (m_pSM->IsLib()) {
  1152. EmitDxilResourcesLinkInfo();
  1153. NamedMDNode *fnProps = m_pModule->getOrInsertNamedMetadata(
  1154. DxilMDHelper::kDxilFunctionPropertiesMDName);
  1155. for (auto &&pair : m_DxilFunctionPropsMap) {
  1156. const hlsl::DxilFunctionProps *props = pair.second.get();
  1157. MDTuple *pProps = m_pMDHelper->EmitDxilFunctionProps(props, pair.first);
  1158. fnProps->addOperand(pProps);
  1159. }
  1160. NamedMDNode *entrySigs = m_pModule->getOrInsertNamedMetadata(
  1161. DxilMDHelper::kDxilEntrySignaturesMDName);
  1162. for (auto &&pair : m_DxilEntrySignatureMap) {
  1163. Function *F = pair.first;
  1164. DxilEntrySignature *Sig = pair.second.get();
  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. LoadDxilResourcesLinkInfo();
  1197. NamedMDNode *fnProps = m_pModule->getNamedMetadata(
  1198. DxilMDHelper::kDxilFunctionPropertiesMDName);
  1199. size_t propIdx = 0;
  1200. while (propIdx < fnProps->getNumOperands()) {
  1201. MDTuple *pProps = dyn_cast<MDTuple>(fnProps->getOperand(propIdx++));
  1202. std::unique_ptr<hlsl::DxilFunctionProps> props =
  1203. llvm::make_unique<hlsl::DxilFunctionProps>();
  1204. Function *F = m_pMDHelper->LoadDxilFunctionProps(pProps, props.get());
  1205. if (props->IsHS() && props->ShaderProps.HS.patchConstantFunc) {
  1206. // Add patch constant function to m_PatchConstantFunctions
  1207. m_PatchConstantFunctions.insert(props->ShaderProps.HS.patchConstantFunc);
  1208. }
  1209. m_DxilFunctionPropsMap[F] = std::move(props);
  1210. }
  1211. NamedMDNode *entrySigs = m_pModule->getOrInsertNamedMetadata(
  1212. DxilMDHelper::kDxilEntrySignaturesMDName);
  1213. size_t sigIdx = 0;
  1214. while (sigIdx < entrySigs->getNumOperands()) {
  1215. MDTuple *pSig = dyn_cast<MDTuple>(entrySigs->getOperand(sigIdx++));
  1216. unsigned idx = 0;
  1217. Function *F = dyn_cast<Function>(
  1218. dyn_cast<ValueAsMetadata>(pSig->getOperand(idx++))->getValue());
  1219. // Entry must have props.
  1220. IFTBOOL(m_DxilFunctionPropsMap.count(F), DXC_E_INCORRECT_DXIL_METADATA);
  1221. DXIL::ShaderKind shaderKind = m_DxilFunctionPropsMap[F]->shaderKind;
  1222. std::unique_ptr<hlsl::DxilEntrySignature> Sig =
  1223. llvm::make_unique<hlsl::DxilEntrySignature>(shaderKind, !m_ShaderFlags.GetUseNativeLowPrecision());
  1224. m_pMDHelper->LoadDxilSignatures(pSig->getOperand(idx), *Sig);
  1225. m_DxilEntrySignatureMap[F] = std::move(Sig);
  1226. }
  1227. }
  1228. }
  1229. MDTuple *DxilModule::EmitDxilResources() {
  1230. // Emit SRV records.
  1231. MDTuple *pTupleSRVs = nullptr;
  1232. if (!m_SRVs.empty()) {
  1233. vector<Metadata *> MDVals;
  1234. for (size_t i = 0; i < m_SRVs.size(); i++) {
  1235. MDVals.emplace_back(m_pMDHelper->EmitDxilSRV(*m_SRVs[i]));
  1236. }
  1237. pTupleSRVs = MDNode::get(m_Ctx, MDVals);
  1238. }
  1239. // Emit UAV records.
  1240. MDTuple *pTupleUAVs = nullptr;
  1241. if (!m_UAVs.empty()) {
  1242. vector<Metadata *> MDVals;
  1243. for (size_t i = 0; i < m_UAVs.size(); i++) {
  1244. MDVals.emplace_back(m_pMDHelper->EmitDxilUAV(*m_UAVs[i]));
  1245. }
  1246. pTupleUAVs = MDNode::get(m_Ctx, MDVals);
  1247. }
  1248. // Emit CBuffer records.
  1249. MDTuple *pTupleCBuffers = nullptr;
  1250. if (!m_CBuffers.empty()) {
  1251. vector<Metadata *> MDVals;
  1252. for (size_t i = 0; i < m_CBuffers.size(); i++) {
  1253. MDVals.emplace_back(m_pMDHelper->EmitDxilCBuffer(*m_CBuffers[i]));
  1254. }
  1255. pTupleCBuffers = MDNode::get(m_Ctx, MDVals);
  1256. }
  1257. // Emit Sampler records.
  1258. MDTuple *pTupleSamplers = nullptr;
  1259. if (!m_Samplers.empty()) {
  1260. vector<Metadata *> MDVals;
  1261. for (size_t i = 0; i < m_Samplers.size(); i++) {
  1262. MDVals.emplace_back(m_pMDHelper->EmitDxilSampler(*m_Samplers[i]));
  1263. }
  1264. pTupleSamplers = MDNode::get(m_Ctx, MDVals);
  1265. }
  1266. if (pTupleSRVs != nullptr || pTupleUAVs != nullptr || pTupleCBuffers != nullptr || pTupleSamplers != nullptr) {
  1267. return m_pMDHelper->EmitDxilResourceTuple(pTupleSRVs, pTupleUAVs, pTupleCBuffers, pTupleSamplers);
  1268. } else {
  1269. return nullptr;
  1270. }
  1271. }
  1272. void DxilModule::ReEmitDxilResources() {
  1273. ClearDxilMetadata(*m_pModule);
  1274. if (!m_pSM->IsCS() && !m_pSM->IsLib())
  1275. m_pViewIdState->Compute();
  1276. EmitDxilMetadata();
  1277. }
  1278. void DxilModule::LoadDxilResources(const llvm::MDOperand &MDO) {
  1279. if (MDO.get() == nullptr)
  1280. return;
  1281. const llvm::MDTuple *pSRVs, *pUAVs, *pCBuffers, *pSamplers;
  1282. m_pMDHelper->GetDxilResources(MDO, pSRVs, pUAVs, pCBuffers, pSamplers);
  1283. // Load SRV records.
  1284. if (pSRVs != nullptr) {
  1285. for (unsigned i = 0; i < pSRVs->getNumOperands(); i++) {
  1286. unique_ptr<DxilResource> pSRV(new DxilResource);
  1287. m_pMDHelper->LoadDxilSRV(pSRVs->getOperand(i), *pSRV);
  1288. AddSRV(std::move(pSRV));
  1289. }
  1290. }
  1291. // Load UAV records.
  1292. if (pUAVs != nullptr) {
  1293. for (unsigned i = 0; i < pUAVs->getNumOperands(); i++) {
  1294. unique_ptr<DxilResource> pUAV(new DxilResource);
  1295. m_pMDHelper->LoadDxilUAV(pUAVs->getOperand(i), *pUAV);
  1296. AddUAV(std::move(pUAV));
  1297. }
  1298. }
  1299. // Load CBuffer records.
  1300. if (pCBuffers != nullptr) {
  1301. for (unsigned i = 0; i < pCBuffers->getNumOperands(); i++) {
  1302. unique_ptr<DxilCBuffer> pCB(new DxilCBuffer);
  1303. m_pMDHelper->LoadDxilCBuffer(pCBuffers->getOperand(i), *pCB);
  1304. AddCBuffer(std::move(pCB));
  1305. }
  1306. }
  1307. // Load Sampler records.
  1308. if (pSamplers != nullptr) {
  1309. for (unsigned i = 0; i < pSamplers->getNumOperands(); i++) {
  1310. unique_ptr<DxilSampler> pSampler(new DxilSampler);
  1311. m_pMDHelper->LoadDxilSampler(pSamplers->getOperand(i), *pSampler);
  1312. AddSampler(std::move(pSampler));
  1313. }
  1314. }
  1315. }
  1316. static MDTuple *CreateResourcesLinkInfo(std::vector<DxilModule::ResourceLinkInfo> &LinkInfoList,
  1317. unsigned size, LLVMContext &Ctx) {
  1318. DXASSERT(size == LinkInfoList.size(), "link info size must match resource size");
  1319. if (LinkInfoList.empty())
  1320. return nullptr;
  1321. vector<Metadata *> MDVals;
  1322. for (size_t i = 0; i < size; i++) {
  1323. MDVals.emplace_back(ValueAsMetadata::get(LinkInfoList[i].ResRangeID));
  1324. }
  1325. return MDNode::get(Ctx, MDVals);
  1326. }
  1327. void DxilModule::EmitDxilResourcesLinkInfo() {
  1328. // Emit SRV base records.
  1329. MDTuple *pTupleSRVs =
  1330. CreateResourcesLinkInfo(m_SRVsLinkInfo, m_SRVs.size(), m_Ctx);
  1331. // Emit UAV base records.
  1332. MDTuple *pTupleUAVs =
  1333. CreateResourcesLinkInfo(m_UAVsLinkInfo, m_UAVs.size(), m_Ctx);
  1334. // Emit CBuffer base records.
  1335. MDTuple *pTupleCBuffers =
  1336. CreateResourcesLinkInfo(m_CBuffersLinkInfo, m_CBuffers.size(), m_Ctx);
  1337. // Emit Sampler records.
  1338. MDTuple *pTupleSamplers =
  1339. CreateResourcesLinkInfo(m_SamplersLinkInfo, m_Samplers.size(), m_Ctx);
  1340. if (pTupleSRVs != nullptr || pTupleUAVs != nullptr ||
  1341. pTupleCBuffers != nullptr || pTupleSamplers != nullptr) {
  1342. m_pMDHelper->EmitDxilResourceLinkInfoTuple(pTupleSRVs, pTupleUAVs,
  1343. pTupleCBuffers, pTupleSamplers);
  1344. }
  1345. }
  1346. static void
  1347. LoadResourcesLinkInfo(const llvm::MDTuple *pMD,
  1348. std::vector<DxilModule::ResourceLinkInfo> &LinkInfoList,
  1349. unsigned size, DxilMDHelper *pMDHelper) {
  1350. if (!pMD) {
  1351. IFTBOOL(size == 0, DXC_E_INCORRECT_DXIL_METADATA);
  1352. return;
  1353. }
  1354. unsigned operandSize = pMD->getNumOperands();
  1355. IFTBOOL(operandSize == size, DXC_E_INCORRECT_DXIL_METADATA);
  1356. for (unsigned i = 0; i < operandSize; i++) {
  1357. Constant *rangeID =
  1358. dyn_cast<Constant>(pMDHelper->ValueMDToValue(pMD->getOperand(i)));
  1359. LinkInfoList.emplace_back(DxilModule::ResourceLinkInfo{rangeID});
  1360. }
  1361. }
  1362. void DxilModule::LoadDxilResourcesLinkInfo() {
  1363. const llvm::MDTuple *pSRVs, *pUAVs, *pCBuffers, *pSamplers;
  1364. m_pMDHelper->LoadDxilResourceLinkInfoTuple(pSRVs, pUAVs, pCBuffers,
  1365. pSamplers);
  1366. // Load SRV base records.
  1367. LoadResourcesLinkInfo(pSRVs, m_SRVsLinkInfo, m_SRVs.size(),
  1368. m_pMDHelper.get());
  1369. // Load UAV base records.
  1370. LoadResourcesLinkInfo(pUAVs, m_UAVsLinkInfo, m_UAVs.size(),
  1371. m_pMDHelper.get());
  1372. // Load CBuffer records.
  1373. LoadResourcesLinkInfo(pCBuffers, m_CBuffersLinkInfo, m_CBuffers.size(),
  1374. m_pMDHelper.get());
  1375. // Load Sampler records.
  1376. LoadResourcesLinkInfo(pSamplers, m_SamplersLinkInfo, m_Samplers.size(),
  1377. m_pMDHelper.get());
  1378. }
  1379. MDTuple *DxilModule::EmitDxilShaderProperties() {
  1380. vector<Metadata *> MDVals;
  1381. // DXIL shader flags.
  1382. uint64_t flag = m_ShaderFlags.GetShaderFlagsRaw();
  1383. if (flag != 0) {
  1384. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilShaderFlagsTag));
  1385. MDVals.emplace_back(m_pMDHelper->Uint64ToConstMD(flag));
  1386. }
  1387. // Compute shader.
  1388. if (m_pSM->IsCS()) {
  1389. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilNumThreadsTag));
  1390. vector<Metadata *> NumThreadVals;
  1391. NumThreadVals.emplace_back(m_pMDHelper->Uint32ToConstMD(m_NumThreads[0]));
  1392. NumThreadVals.emplace_back(m_pMDHelper->Uint32ToConstMD(m_NumThreads[1]));
  1393. NumThreadVals.emplace_back(m_pMDHelper->Uint32ToConstMD(m_NumThreads[2]));
  1394. MDVals.emplace_back(MDNode::get(m_Ctx, NumThreadVals));
  1395. }
  1396. // Geometry shader.
  1397. if (m_pSM->IsGS()) {
  1398. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilGSStateTag));
  1399. MDTuple *pMDTuple = m_pMDHelper->EmitDxilGSState(m_InputPrimitive,
  1400. m_MaxVertexCount,
  1401. GetActiveStreamMask(),
  1402. m_StreamPrimitiveTopology,
  1403. m_NumGSInstances);
  1404. MDVals.emplace_back(pMDTuple);
  1405. }
  1406. // Domain shader.
  1407. if (m_pSM->IsDS()) {
  1408. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilDSStateTag));
  1409. MDTuple *pMDTuple = m_pMDHelper->EmitDxilDSState(m_TessellatorDomain,
  1410. m_InputControlPointCount);
  1411. MDVals.emplace_back(pMDTuple);
  1412. }
  1413. // Hull shader.
  1414. if (m_pSM->IsHS()) {
  1415. MDVals.emplace_back(m_pMDHelper->Uint32ToConstMD(DxilMDHelper::kDxilHSStateTag));
  1416. MDTuple *pMDTuple = m_pMDHelper->EmitDxilHSState(m_pPatchConstantFunc,
  1417. m_InputControlPointCount,
  1418. m_OutputControlPointCount,
  1419. m_TessellatorDomain,
  1420. m_TessellatorPartitioning,
  1421. m_TessellatorOutputPrimitive,
  1422. m_MaxTessellationFactor);
  1423. MDVals.emplace_back(pMDTuple);
  1424. }
  1425. if (!MDVals.empty())
  1426. return MDNode::get(m_Ctx, MDVals);
  1427. else
  1428. return nullptr;
  1429. }
  1430. void DxilModule::LoadDxilShaderProperties(const MDOperand &MDO) {
  1431. if (MDO.get() == nullptr)
  1432. return;
  1433. const MDTuple *pTupleMD = dyn_cast<MDTuple>(MDO.get());
  1434. IFTBOOL(pTupleMD != nullptr, DXC_E_INCORRECT_DXIL_METADATA);
  1435. IFTBOOL((pTupleMD->getNumOperands() & 0x1) == 0, DXC_E_INCORRECT_DXIL_METADATA);
  1436. for (unsigned iNode = 0; iNode < pTupleMD->getNumOperands(); iNode += 2) {
  1437. unsigned Tag = DxilMDHelper::ConstMDToUint32(pTupleMD->getOperand(iNode));
  1438. const MDOperand &MDO = pTupleMD->getOperand(iNode + 1);
  1439. IFTBOOL(MDO.get() != nullptr, DXC_E_INCORRECT_DXIL_METADATA);
  1440. switch (Tag) {
  1441. case DxilMDHelper::kDxilShaderFlagsTag:
  1442. m_ShaderFlags.SetShaderFlagsRaw(DxilMDHelper::ConstMDToUint64(MDO));
  1443. break;
  1444. case DxilMDHelper::kDxilNumThreadsTag: {
  1445. MDNode *pNode = cast<MDNode>(MDO.get());
  1446. m_NumThreads[0] = DxilMDHelper::ConstMDToUint32(pNode->getOperand(0));
  1447. m_NumThreads[1] = DxilMDHelper::ConstMDToUint32(pNode->getOperand(1));
  1448. m_NumThreads[2] = DxilMDHelper::ConstMDToUint32(pNode->getOperand(2));
  1449. break;
  1450. }
  1451. case DxilMDHelper::kDxilGSStateTag: {
  1452. m_pMDHelper->LoadDxilGSState(MDO, m_InputPrimitive, m_MaxVertexCount, m_ActiveStreamMask,
  1453. m_StreamPrimitiveTopology, m_NumGSInstances);
  1454. break;
  1455. }
  1456. case DxilMDHelper::kDxilDSStateTag:
  1457. m_pMDHelper->LoadDxilDSState(MDO, m_TessellatorDomain, m_InputControlPointCount);
  1458. break;
  1459. case DxilMDHelper::kDxilHSStateTag:
  1460. m_pMDHelper->LoadDxilHSState(MDO,
  1461. m_pPatchConstantFunc,
  1462. m_InputControlPointCount,
  1463. m_OutputControlPointCount,
  1464. m_TessellatorDomain,
  1465. m_TessellatorPartitioning,
  1466. m_TessellatorOutputPrimitive,
  1467. m_MaxTessellationFactor);
  1468. break;
  1469. default:
  1470. DXASSERT(false, "Unknown extended shader properties tag");
  1471. break;
  1472. }
  1473. }
  1474. }
  1475. void DxilModule::StripDebugRelatedCode() {
  1476. // Remove all users of global resources.
  1477. for (GlobalVariable &GV : m_pModule->globals()) {
  1478. if (GV.hasInternalLinkage())
  1479. continue;
  1480. if (GV.getType()->getPointerAddressSpace() == DXIL::kTGSMAddrSpace)
  1481. continue;
  1482. for (auto git = GV.user_begin(); git != GV.user_end();) {
  1483. User *U = *(git++);
  1484. // Try to remove load of GV.
  1485. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  1486. for (auto it = LI->user_begin(); it != LI->user_end();) {
  1487. Instruction *LIUser = cast<Instruction>(*(it++));
  1488. if (StoreInst *SI = dyn_cast<StoreInst>(LIUser)) {
  1489. Value *Ptr = SI->getPointerOperand();
  1490. SI->eraseFromParent();
  1491. if (Instruction *PtrInst = dyn_cast<Instruction>(Ptr)) {
  1492. if (Ptr->user_empty())
  1493. PtrInst->eraseFromParent();
  1494. }
  1495. }
  1496. }
  1497. if (LI->user_empty())
  1498. LI->eraseFromParent();
  1499. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
  1500. for (auto GEPIt = GEP->user_begin(); GEPIt != GEP->user_end();) {
  1501. User *GEPU = *(GEPIt++);
  1502. // Try to remove load of GEP.
  1503. if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
  1504. for (auto it = LI->user_begin(); it != LI->user_end();) {
  1505. Instruction *LIUser = cast<Instruction>(*(it++));
  1506. if (StoreInst *SI = dyn_cast<StoreInst>(LIUser)) {
  1507. Value *Ptr = SI->getPointerOperand();
  1508. SI->eraseFromParent();
  1509. if (Instruction *PtrInst = dyn_cast<Instruction>(Ptr)) {
  1510. if (Ptr->user_empty())
  1511. PtrInst->eraseFromParent();
  1512. }
  1513. }
  1514. if (LI->user_empty())
  1515. LI->eraseFromParent();
  1516. }
  1517. }
  1518. }
  1519. if (GEP->user_empty())
  1520. GEP->eraseFromParent();
  1521. }
  1522. }
  1523. }
  1524. }
  1525. DebugInfoFinder &DxilModule::GetOrCreateDebugInfoFinder() {
  1526. if (m_pDebugInfoFinder == nullptr) {
  1527. m_pDebugInfoFinder = std::make_unique<llvm::DebugInfoFinder>();
  1528. m_pDebugInfoFinder->processModule(*m_pModule);
  1529. }
  1530. return *m_pDebugInfoFinder;
  1531. }
  1532. hlsl::DxilModule *hlsl::DxilModule::TryGetDxilModule(llvm::Module *pModule) {
  1533. LLVMContext &Ctx = pModule->getContext();
  1534. std::string diagStr;
  1535. raw_string_ostream diagStream(diagStr);
  1536. hlsl::DxilModule *pDxilModule = nullptr;
  1537. // TODO: add detail error in DxilMDHelper.
  1538. try {
  1539. pDxilModule = &pModule->GetOrCreateDxilModule();
  1540. } catch (const ::hlsl::Exception &hlslException) {
  1541. diagStream << "load dxil metadata failed -";
  1542. try {
  1543. const char *msg = hlslException.what();
  1544. if (msg == nullptr || *msg == '\0')
  1545. diagStream << " error code " << hlslException.hr << "\n";
  1546. else
  1547. diagStream << msg;
  1548. } catch (...) {
  1549. diagStream << " unable to retrieve error message.\n";
  1550. }
  1551. Ctx.diagnose(DxilErrorDiagnosticInfo(diagStream.str().c_str()));
  1552. } catch (...) {
  1553. Ctx.diagnose(DxilErrorDiagnosticInfo("load dxil metadata failed - unknown error.\n"));
  1554. }
  1555. return pDxilModule;
  1556. }
  1557. // Check if the instruction has fast math flags configured to indicate
  1558. // the instruction is precise.
  1559. // Precise fast math flags means none of the fast math flags are set.
  1560. bool DxilModule::HasPreciseFastMathFlags(const Instruction *inst) {
  1561. return isa<FPMathOperator>(inst) && !inst->getFastMathFlags().any();
  1562. }
  1563. // Set fast math flags configured to indicate the instruction is precise.
  1564. void DxilModule::SetPreciseFastMathFlags(llvm::Instruction *inst) {
  1565. assert(isa<FPMathOperator>(inst));
  1566. inst->copyFastMathFlags(FastMathFlags());
  1567. }
  1568. // True if fast math flags are preserved across serialization/deserialization
  1569. // of the dxil module.
  1570. //
  1571. // We need to check for this when querying fast math flags for preciseness
  1572. // otherwise we will be overly conservative by reporting instructions precise
  1573. // because their fast math flags were not preserved.
  1574. //
  1575. // Currently we restrict it to the instruction types that have fast math
  1576. // preserved in the bitcode. We can expand this by converting fast math
  1577. // flags to dx.precise metadata during serialization and back to fast
  1578. // math flags during deserialization.
  1579. bool DxilModule::PreservesFastMathFlags(const llvm::Instruction *inst) {
  1580. return
  1581. isa<FPMathOperator>(inst) && (isa<BinaryOperator>(inst) || isa<FCmpInst>(inst));
  1582. }
  1583. bool DxilModule::IsPrecise(const Instruction *inst) const {
  1584. if (m_ShaderFlags.GetDisableMathRefactoring())
  1585. return true;
  1586. else if (DxilMDHelper::IsMarkedPrecise(inst))
  1587. return true;
  1588. else if (PreservesFastMathFlags(inst))
  1589. return HasPreciseFastMathFlags(inst);
  1590. else
  1591. return false;
  1592. }
  1593. } // namespace hlsl
  1594. namespace llvm {
  1595. hlsl::DxilModule &Module::GetOrCreateDxilModule(bool skipInit) {
  1596. std::unique_ptr<hlsl::DxilModule> M;
  1597. if (!HasDxilModule()) {
  1598. M = std::make_unique<hlsl::DxilModule>(this);
  1599. if (!skipInit) {
  1600. M->LoadDxilMetadata();
  1601. }
  1602. SetDxilModule(M.release());
  1603. }
  1604. return GetDxilModule();
  1605. }
  1606. void Module::ResetDxilModule() {
  1607. if (HasDxilModule()) {
  1608. delete TheDxilModule;
  1609. TheDxilModule = nullptr;
  1610. }
  1611. }
  1612. }