DxilModule.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilModule.h //
  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. // The main class to work with DXIL, similar to LLVM module. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #pragma once
  12. #include "dxc/DXIL/DxilConstants.h"
  13. #include "dxc/DXIL/DxilMetadataHelper.h"
  14. #include "dxc/DXIL/DxilCBuffer.h"
  15. #include "dxc/DXIL/DxilResource.h"
  16. #include "dxc/DXIL/DxilSampler.h"
  17. #include "dxc/DXIL/DxilShaderFlags.h"
  18. #include "dxc/DXIL/DxilSignature.h"
  19. #include "dxc/DXIL/DxilSubobject.h"
  20. #include "dxc/DXIL/DxilTypeSystem.h"
  21. #include <memory>
  22. #include <string>
  23. #include <vector>
  24. #include <unordered_map>
  25. #include <unordered_set>
  26. namespace llvm {
  27. class LLVMContext;
  28. class Module;
  29. class Function;
  30. class Instruction;
  31. class MDTuple;
  32. class MDOperand;
  33. class DebugInfoFinder;
  34. }
  35. namespace hlsl {
  36. class ShaderModel;
  37. class OP;
  38. struct DxilFunctionProps;
  39. class DxilEntryProps;
  40. using DxilEntryPropsMap =
  41. std::unordered_map<const llvm::Function *, std::unique_ptr<DxilEntryProps>>;
  42. /// Use this class to manipulate DXIL of a shader.
  43. class DxilModule {
  44. public:
  45. DxilModule(llvm::Module *pModule);
  46. ~DxilModule();
  47. // Subsystems.
  48. llvm::LLVMContext &GetCtx() const;
  49. llvm::Module *GetModule() const;
  50. OP *GetOP() const;
  51. void SetShaderModel(const ShaderModel *pSM, bool bUseMinPrecision = true);
  52. const ShaderModel *GetShaderModel() const;
  53. void GetDxilVersion(unsigned &DxilMajor, unsigned &DxilMinor) const;
  54. void SetValidatorVersion(unsigned ValMajor, unsigned ValMinor);
  55. bool UpgradeValidatorVersion(unsigned ValMajor, unsigned ValMinor);
  56. void GetValidatorVersion(unsigned &ValMajor, unsigned &ValMinor) const;
  57. void SetForceZeroStoreLifetimes(bool ForceZeroStoreLifetimes);
  58. bool GetForceZeroStoreLifetimes() const;
  59. // Return true on success, requires valid shader model and CollectShaderFlags to have been set
  60. bool GetMinValidatorVersion(unsigned &ValMajor, unsigned &ValMinor) const;
  61. // Update validator version to minimum if higher than current (ex: after CollectShaderFlags)
  62. bool UpgradeToMinValidatorVersion();
  63. // Entry functions.
  64. llvm::Function *GetEntryFunction();
  65. const llvm::Function *GetEntryFunction() const;
  66. void SetEntryFunction(llvm::Function *pEntryFunc);
  67. const std::string &GetEntryFunctionName() const;
  68. void SetEntryFunctionName(const std::string &name);
  69. llvm::Function *GetPatchConstantFunction();
  70. const llvm::Function *GetPatchConstantFunction() const;
  71. void SetPatchConstantFunction(llvm::Function *pFunc);
  72. bool IsEntryOrPatchConstantFunction(const llvm::Function* pFunc) const;
  73. // Flags.
  74. unsigned GetGlobalFlags() const;
  75. void CollectShaderFlagsForModule();
  76. // Resources.
  77. unsigned AddCBuffer(std::unique_ptr<DxilCBuffer> pCB);
  78. DxilCBuffer &GetCBuffer(unsigned idx);
  79. const DxilCBuffer &GetCBuffer(unsigned idx) const;
  80. const std::vector<std::unique_ptr<DxilCBuffer> > &GetCBuffers() const;
  81. unsigned AddSampler(std::unique_ptr<DxilSampler> pSampler);
  82. DxilSampler &GetSampler(unsigned idx);
  83. const DxilSampler &GetSampler(unsigned idx) const;
  84. const std::vector<std::unique_ptr<DxilSampler> > &GetSamplers() const;
  85. unsigned AddSRV(std::unique_ptr<DxilResource> pSRV);
  86. DxilResource &GetSRV(unsigned idx);
  87. const DxilResource &GetSRV(unsigned idx) const;
  88. const std::vector<std::unique_ptr<DxilResource> > &GetSRVs() const;
  89. unsigned AddUAV(std::unique_ptr<DxilResource> pUAV);
  90. DxilResource &GetUAV(unsigned idx);
  91. const DxilResource &GetUAV(unsigned idx) const;
  92. const std::vector<std::unique_ptr<DxilResource> > &GetUAVs() const;
  93. void LoadDxilResourceBaseFromMDNode(llvm::MDNode *MD, DxilResourceBase &R);
  94. void LoadDxilResourceFromMDNode(llvm::MDNode *MD, DxilResource &R);
  95. void LoadDxilSamplerFromMDNode(llvm::MDNode *MD, DxilSampler &S);
  96. void RemoveUnusedResources();
  97. void RemoveResourcesWithUnusedSymbols();
  98. void RemoveFunction(llvm::Function *F);
  99. bool RenameResourcesWithPrefix(const std::string &prefix);
  100. bool RenameResourceGlobalsWithBinding(bool bKeepName = true);
  101. // Signatures.
  102. DxilSignature &GetInputSignature();
  103. const DxilSignature &GetInputSignature() const;
  104. DxilSignature &GetOutputSignature();
  105. const DxilSignature &GetOutputSignature() const;
  106. DxilSignature &GetPatchConstOrPrimSignature();
  107. const DxilSignature &GetPatchConstOrPrimSignature() const;
  108. const std::vector<uint8_t> &GetSerializedRootSignature() const;
  109. std::vector<uint8_t> &GetSerializedRootSignature();
  110. bool HasDxilEntrySignature(const llvm::Function *F) const;
  111. DxilEntrySignature &GetDxilEntrySignature(const llvm::Function *F);
  112. // Move DxilEntryProps of F to NewF.
  113. void ReplaceDxilEntryProps(llvm::Function *F, llvm::Function *NewF);
  114. // Clone DxilEntryProps of F to NewF.
  115. void CloneDxilEntryProps(llvm::Function *F, llvm::Function *NewF);
  116. bool HasDxilEntryProps(const llvm::Function *F) const;
  117. DxilEntryProps &GetDxilEntryProps(const llvm::Function *F);
  118. const DxilEntryProps &GetDxilEntryProps(const llvm::Function *F) const;
  119. // DxilFunctionProps.
  120. bool HasDxilFunctionProps(const llvm::Function *F) const;
  121. DxilFunctionProps &GetDxilFunctionProps(const llvm::Function *F);
  122. const DxilFunctionProps &GetDxilFunctionProps(const llvm::Function *F) const;
  123. // Move DxilFunctionProps of F to NewF.
  124. void SetPatchConstantFunctionForHS(llvm::Function *hullShaderFunc, llvm::Function *patchConstantFunc);
  125. bool IsGraphicsShader(const llvm::Function *F) const; // vs,hs,ds,gs,ps
  126. bool IsPatchConstantShader(const llvm::Function *F) const;
  127. bool IsComputeShader(const llvm::Function *F) const;
  128. // Is an entry function that uses input/output signature conventions?
  129. // Includes: vs/hs/ds/gs/ps/cs as well as the patch constant function.
  130. bool IsEntryThatUsesSignatures(const llvm::Function *F) const ;
  131. // Is F an entry?
  132. // Includes: IsEntryThatUsesSignatures and all ray tracing shaders.
  133. bool IsEntry(const llvm::Function *F) const;
  134. // Remove Root Signature from module metadata, return true if changed
  135. bool StripRootSignatureFromMetadata();
  136. // Remove Subobjects from module metadata, return true if changed
  137. bool StripSubobjectsFromMetadata();
  138. // Update validator version metadata to current setting
  139. void UpdateValidatorVersionMetadata();
  140. // DXIL type system.
  141. DxilTypeSystem &GetTypeSystem();
  142. /// Emit llvm.used array to make sure that optimizations do not remove unreferenced globals.
  143. void EmitLLVMUsed();
  144. std::vector<llvm::GlobalVariable* > &GetLLVMUsed();
  145. void ClearLLVMUsed();
  146. // ViewId state.
  147. std::vector<unsigned> &GetSerializedViewIdState();
  148. const std::vector<unsigned> &GetSerializedViewIdState() const;
  149. // DXIL metadata manipulation.
  150. /// Clear all DXIL data that exists in in-memory form.
  151. static void ClearDxilMetadata(llvm::Module &M);
  152. /// Serialize DXIL in-memory form to metadata form.
  153. void EmitDxilMetadata();
  154. /// Update resource metadata.
  155. /// Note: this method not update Metadata for ViewIdState.
  156. void ReEmitDxilResources();
  157. /// Deserialize DXIL metadata form into in-memory form.
  158. void LoadDxilMetadata();
  159. /// Return true if non-fatal metadata error was detected.
  160. bool HasMetadataErrors();
  161. void EmitDxilCounters();
  162. void LoadDxilCounters(DxilCounters &counters) const;
  163. /// Check if a Named meta data node is known by dxil module.
  164. static bool IsKnownNamedMetaData(llvm::NamedMDNode &Node);
  165. // Reset functions used to transfer ownership.
  166. void ResetEntrySignature(DxilEntrySignature *pValue);
  167. void ResetSerializedRootSignature(std::vector<uint8_t> &Value);
  168. void ResetTypeSystem(DxilTypeSystem *pValue);
  169. void ResetOP(hlsl::OP *hlslOP);
  170. void ResetEntryPropsMap(DxilEntryPropsMap &&PropMap);
  171. bool StripReflection();
  172. void StripDebugRelatedCode();
  173. // Helper to remove dx.* metadata with source and compile options.
  174. // If the parameter `bReplaceWithDummyData` is true, the named metadata
  175. // are replaced with valid empty data that satisfy tools.
  176. void StripShaderSourcesAndCompileOptions(bool bReplaceWithDummyData=false);
  177. llvm::DebugInfoFinder &GetOrCreateDebugInfoFinder();
  178. static DxilModule *TryGetDxilModule(llvm::Module *pModule);
  179. // Helpers for working with precise.
  180. // Return true if the instruction should be considered precise.
  181. //
  182. // An instruction can be marked precise in the following ways:
  183. //
  184. // 1. Global refactoring is disabled.
  185. // 2. The instruction has a precise metadata annotation.
  186. // 3. The instruction has precise fast math flags set.
  187. //
  188. bool IsPrecise(const llvm::Instruction *inst) const;
  189. // Check if the instruction has fast math flags configured to indicate
  190. // the instruction is precise.
  191. static bool HasPreciseFastMathFlags(const llvm::Instruction *inst);
  192. // Set fast math flags configured to indicate the instruction is precise.
  193. static void SetPreciseFastMathFlags(llvm::Instruction *inst);
  194. // True if fast math flags are preserved across serialize/deserialize.
  195. static bool PreservesFastMathFlags(const llvm::Instruction *inst);
  196. public:
  197. ShaderFlags m_ShaderFlags;
  198. void CollectShaderFlagsForModule(ShaderFlags &Flags);
  199. // Check if DxilModule contains multi component UAV Loads.
  200. // This funciton must be called after unused resources are removed from DxilModule
  201. bool ModuleHasMulticomponentUAVLoads();
  202. // Compute/Mesh/Amplification shader.
  203. void SetNumThreads(unsigned x, unsigned y, unsigned z);
  204. unsigned GetNumThreads(unsigned idx) const;
  205. // Compute shader
  206. void SetWaveSize(unsigned size);
  207. unsigned GetWaveSize() const;
  208. // Geometry shader.
  209. DXIL::InputPrimitive GetInputPrimitive() const;
  210. void SetInputPrimitive(DXIL::InputPrimitive IP);
  211. unsigned GetMaxVertexCount() const;
  212. void SetMaxVertexCount(unsigned Count);
  213. DXIL::PrimitiveTopology GetStreamPrimitiveTopology() const;
  214. void SetStreamPrimitiveTopology(DXIL::PrimitiveTopology Topology);
  215. bool HasMultipleOutputStreams() const;
  216. unsigned GetOutputStream() const;
  217. unsigned GetGSInstanceCount() const;
  218. void SetGSInstanceCount(unsigned Count);
  219. bool IsStreamActive(unsigned Stream) const;
  220. void SetStreamActive(unsigned Stream, bool bActive);
  221. void SetActiveStreamMask(unsigned Mask);
  222. unsigned GetActiveStreamMask() const;
  223. // Language options
  224. // UseMinPrecision must be set at SetShaderModel time.
  225. bool GetUseMinPrecision() const;
  226. void SetDisableOptimization(bool disableOptimization);
  227. bool GetDisableOptimization() const;
  228. void SetAllResourcesBound(bool resourcesBound);
  229. bool GetAllResourcesBound() const;
  230. // Intermediate options that do not make it to DXIL
  231. void SetLegacyResourceReservation(bool legacyResourceReservation);
  232. bool GetLegacyResourceReservation() const;
  233. void ClearIntermediateOptions();
  234. // Hull and Domain shaders.
  235. unsigned GetInputControlPointCount() const;
  236. void SetInputControlPointCount(unsigned NumICPs);
  237. DXIL::TessellatorDomain GetTessellatorDomain() const;
  238. void SetTessellatorDomain(DXIL::TessellatorDomain TessDomain);
  239. // Hull shader.
  240. unsigned GetOutputControlPointCount() const;
  241. void SetOutputControlPointCount(unsigned NumOCPs);
  242. DXIL::TessellatorPartitioning GetTessellatorPartitioning() const;
  243. void SetTessellatorPartitioning(DXIL::TessellatorPartitioning TessPartitioning);
  244. DXIL::TessellatorOutputPrimitive GetTessellatorOutputPrimitive() const;
  245. void SetTessellatorOutputPrimitive(DXIL::TessellatorOutputPrimitive TessOutputPrimitive);
  246. float GetMaxTessellationFactor() const;
  247. void SetMaxTessellationFactor(float MaxTessellationFactor);
  248. // Mesh shader
  249. unsigned GetMaxOutputVertices() const;
  250. void SetMaxOutputVertices(unsigned NumOVs);
  251. unsigned GetMaxOutputPrimitives() const;
  252. void SetMaxOutputPrimitives(unsigned NumOPs);
  253. DXIL::MeshOutputTopology GetMeshOutputTopology() const;
  254. void SetMeshOutputTopology(DXIL::MeshOutputTopology MeshOutputTopology);
  255. unsigned GetPayloadSizeInBytes() const;
  256. void SetPayloadSizeInBytes(unsigned Size);
  257. // AutoBindingSpace also enables automatic binding for libraries if set.
  258. // UINT_MAX == unset
  259. void SetAutoBindingSpace(uint32_t Space);
  260. uint32_t GetAutoBindingSpace() const;
  261. void SetShaderProperties(DxilFunctionProps *props);
  262. DxilSubobjects *GetSubobjects();
  263. const DxilSubobjects *GetSubobjects() const;
  264. DxilSubobjects *ReleaseSubobjects();
  265. void ResetSubobjects(DxilSubobjects *subobjects);
  266. private:
  267. // Signatures.
  268. std::vector<uint8_t> m_SerializedRootSignature;
  269. // Shader resources.
  270. std::vector<std::unique_ptr<DxilResource> > m_SRVs;
  271. std::vector<std::unique_ptr<DxilResource> > m_UAVs;
  272. std::vector<std::unique_ptr<DxilCBuffer> > m_CBuffers;
  273. std::vector<std::unique_ptr<DxilSampler> > m_Samplers;
  274. // Geometry shader.
  275. DXIL::PrimitiveTopology m_StreamPrimitiveTopology;
  276. unsigned m_ActiveStreamMask;
  277. private:
  278. enum IntermediateFlags : uint32_t {
  279. LegacyResourceReservation = 1 << 0,
  280. };
  281. private:
  282. llvm::LLVMContext &m_Ctx;
  283. llvm::Module *m_pModule;
  284. llvm::Function *m_pEntryFunc;
  285. std::string m_EntryName;
  286. std::unique_ptr<DxilMDHelper> m_pMDHelper;
  287. std::unique_ptr<llvm::DebugInfoFinder> m_pDebugInfoFinder;
  288. const ShaderModel *m_pSM;
  289. unsigned m_DxilMajor;
  290. unsigned m_DxilMinor;
  291. unsigned m_ValMajor;
  292. unsigned m_ValMinor;
  293. bool m_ForceZeroStoreLifetimes;
  294. std::unique_ptr<OP> m_pOP;
  295. size_t m_pUnused;
  296. // LLVM used.
  297. std::vector<llvm::GlobalVariable*> m_LLVMUsed;
  298. // Type annotations.
  299. std::unique_ptr<DxilTypeSystem> m_pTypeSystem;
  300. // EntryProps for shader functions.
  301. DxilEntryPropsMap m_DxilEntryPropsMap;
  302. // Keeps track of patch constant functions used by hull shaders
  303. std::unordered_set<const llvm::Function *> m_PatchConstantFunctions;
  304. // Serialized ViewId state.
  305. std::vector<unsigned> m_SerializedState;
  306. // DXIL metadata serialization/deserialization.
  307. llvm::MDTuple *EmitDxilResources();
  308. void LoadDxilResources(const llvm::MDOperand &MDO);
  309. // Helpers.
  310. template<typename T> unsigned AddResource(std::vector<std::unique_ptr<T> > &Vec, std::unique_ptr<T> pRes);
  311. void LoadDxilSignature(const llvm::MDTuple *pSigTuple, DxilSignature &Sig, bool bInput);
  312. // properties from HLModule preserved as ShaderFlags
  313. bool m_bDisableOptimizations;
  314. bool m_bUseMinPrecision;
  315. bool m_bAllResourcesBound;
  316. // properties from HLModule that should not make it to the final DXIL
  317. uint32_t m_IntermediateFlags;
  318. uint32_t m_AutoBindingSpace;
  319. std::unique_ptr<DxilSubobjects> m_pSubobjects;
  320. // m_bMetadataErrors is true if non-fatal metadata errors were encountered.
  321. // Validator will fail in this case, but should not block module load.
  322. bool m_bMetadataErrors;
  323. };
  324. } // namespace hlsl