DxilModule.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. const DxilTypeSystem &GetTypeSystem() const;
  143. /// Emit llvm.used array to make sure that optimizations do not remove unreferenced globals.
  144. void EmitLLVMUsed();
  145. std::vector<llvm::GlobalVariable* > &GetLLVMUsed();
  146. void ClearLLVMUsed();
  147. // ViewId state.
  148. std::vector<unsigned> &GetSerializedViewIdState();
  149. const std::vector<unsigned> &GetSerializedViewIdState() const;
  150. // DXIL metadata manipulation.
  151. /// Clear all DXIL data that exists in in-memory form.
  152. static void ClearDxilMetadata(llvm::Module &M);
  153. /// Serialize DXIL in-memory form to metadata form.
  154. void EmitDxilMetadata();
  155. /// Update resource metadata.
  156. /// Note: this method not update Metadata for ViewIdState.
  157. void ReEmitDxilResources();
  158. /// Deserialize DXIL metadata form into in-memory form.
  159. void LoadDxilMetadata();
  160. /// Return true if non-fatal metadata error was detected.
  161. bool HasMetadataErrors();
  162. void EmitDxilCounters();
  163. void LoadDxilCounters(DxilCounters &counters) const;
  164. /// Check if a Named meta data node is known by dxil module.
  165. static bool IsKnownNamedMetaData(llvm::NamedMDNode &Node);
  166. // Reset functions used to transfer ownership.
  167. void ResetEntrySignature(DxilEntrySignature *pValue);
  168. void ResetSerializedRootSignature(std::vector<uint8_t> &Value);
  169. void ResetTypeSystem(DxilTypeSystem *pValue);
  170. void ResetOP(hlsl::OP *hlslOP);
  171. void ResetEntryPropsMap(DxilEntryPropsMap &&PropMap);
  172. bool StripReflection();
  173. void StripDebugRelatedCode();
  174. // Helper to remove dx.* metadata with source and compile options.
  175. // If the parameter `bReplaceWithDummyData` is true, the named metadata
  176. // are replaced with valid empty data that satisfy tools.
  177. void StripShaderSourcesAndCompileOptions(bool bReplaceWithDummyData=false);
  178. llvm::DebugInfoFinder &GetOrCreateDebugInfoFinder();
  179. static DxilModule *TryGetDxilModule(llvm::Module *pModule);
  180. // Helpers for working with precise.
  181. // Return true if the instruction should be considered precise.
  182. //
  183. // An instruction can be marked precise in the following ways:
  184. //
  185. // 1. Global refactoring is disabled.
  186. // 2. The instruction has a precise metadata annotation.
  187. // 3. The instruction has precise fast math flags set.
  188. //
  189. bool IsPrecise(const llvm::Instruction *inst) const;
  190. // Check if the instruction has fast math flags configured to indicate
  191. // the instruction is precise.
  192. static bool HasPreciseFastMathFlags(const llvm::Instruction *inst);
  193. // Set fast math flags configured to indicate the instruction is precise.
  194. static void SetPreciseFastMathFlags(llvm::Instruction *inst);
  195. // True if fast math flags are preserved across serialize/deserialize.
  196. static bool PreservesFastMathFlags(const llvm::Instruction *inst);
  197. public:
  198. ShaderFlags m_ShaderFlags;
  199. void CollectShaderFlagsForModule(ShaderFlags &Flags);
  200. // Check if DxilModule contains multi component UAV Loads.
  201. // This funciton must be called after unused resources are removed from DxilModule
  202. bool ModuleHasMulticomponentUAVLoads();
  203. // Compute/Mesh/Amplification shader.
  204. void SetNumThreads(unsigned x, unsigned y, unsigned z);
  205. unsigned GetNumThreads(unsigned idx) const;
  206. // Compute shader
  207. void SetWaveSize(unsigned size);
  208. unsigned GetWaveSize() const;
  209. // Geometry shader.
  210. DXIL::InputPrimitive GetInputPrimitive() const;
  211. void SetInputPrimitive(DXIL::InputPrimitive IP);
  212. unsigned GetMaxVertexCount() const;
  213. void SetMaxVertexCount(unsigned Count);
  214. DXIL::PrimitiveTopology GetStreamPrimitiveTopology() const;
  215. void SetStreamPrimitiveTopology(DXIL::PrimitiveTopology Topology);
  216. bool HasMultipleOutputStreams() const;
  217. unsigned GetOutputStream() const;
  218. unsigned GetGSInstanceCount() const;
  219. void SetGSInstanceCount(unsigned Count);
  220. bool IsStreamActive(unsigned Stream) const;
  221. void SetStreamActive(unsigned Stream, bool bActive);
  222. void SetActiveStreamMask(unsigned Mask);
  223. unsigned GetActiveStreamMask() const;
  224. // Language options
  225. // UseMinPrecision must be set at SetShaderModel time.
  226. bool GetUseMinPrecision() const;
  227. void SetDisableOptimization(bool disableOptimization);
  228. bool GetDisableOptimization() const;
  229. void SetAllResourcesBound(bool resourcesBound);
  230. bool GetAllResourcesBound() const;
  231. // Intermediate options that do not make it to DXIL
  232. void SetLegacyResourceReservation(bool legacyResourceReservation);
  233. bool GetLegacyResourceReservation() const;
  234. void ClearIntermediateOptions();
  235. // Hull and Domain shaders.
  236. unsigned GetInputControlPointCount() const;
  237. void SetInputControlPointCount(unsigned NumICPs);
  238. DXIL::TessellatorDomain GetTessellatorDomain() const;
  239. void SetTessellatorDomain(DXIL::TessellatorDomain TessDomain);
  240. // Hull shader.
  241. unsigned GetOutputControlPointCount() const;
  242. void SetOutputControlPointCount(unsigned NumOCPs);
  243. DXIL::TessellatorPartitioning GetTessellatorPartitioning() const;
  244. void SetTessellatorPartitioning(DXIL::TessellatorPartitioning TessPartitioning);
  245. DXIL::TessellatorOutputPrimitive GetTessellatorOutputPrimitive() const;
  246. void SetTessellatorOutputPrimitive(DXIL::TessellatorOutputPrimitive TessOutputPrimitive);
  247. float GetMaxTessellationFactor() const;
  248. void SetMaxTessellationFactor(float MaxTessellationFactor);
  249. // Mesh shader
  250. unsigned GetMaxOutputVertices() const;
  251. void SetMaxOutputVertices(unsigned NumOVs);
  252. unsigned GetMaxOutputPrimitives() const;
  253. void SetMaxOutputPrimitives(unsigned NumOPs);
  254. DXIL::MeshOutputTopology GetMeshOutputTopology() const;
  255. void SetMeshOutputTopology(DXIL::MeshOutputTopology MeshOutputTopology);
  256. unsigned GetPayloadSizeInBytes() const;
  257. void SetPayloadSizeInBytes(unsigned Size);
  258. // AutoBindingSpace also enables automatic binding for libraries if set.
  259. // UINT_MAX == unset
  260. void SetAutoBindingSpace(uint32_t Space);
  261. uint32_t GetAutoBindingSpace() const;
  262. void SetShaderProperties(DxilFunctionProps *props);
  263. DxilSubobjects *GetSubobjects();
  264. const DxilSubobjects *GetSubobjects() const;
  265. DxilSubobjects *ReleaseSubobjects();
  266. void ResetSubobjects(DxilSubobjects *subobjects);
  267. private:
  268. // Signatures.
  269. std::vector<uint8_t> m_SerializedRootSignature;
  270. // Shader resources.
  271. std::vector<std::unique_ptr<DxilResource> > m_SRVs;
  272. std::vector<std::unique_ptr<DxilResource> > m_UAVs;
  273. std::vector<std::unique_ptr<DxilCBuffer> > m_CBuffers;
  274. std::vector<std::unique_ptr<DxilSampler> > m_Samplers;
  275. // Geometry shader.
  276. DXIL::PrimitiveTopology m_StreamPrimitiveTopology;
  277. unsigned m_ActiveStreamMask;
  278. private:
  279. enum IntermediateFlags : uint32_t {
  280. LegacyResourceReservation = 1 << 0,
  281. };
  282. private:
  283. llvm::LLVMContext &m_Ctx;
  284. llvm::Module *m_pModule;
  285. llvm::Function *m_pEntryFunc;
  286. std::string m_EntryName;
  287. std::unique_ptr<DxilMDHelper> m_pMDHelper;
  288. std::unique_ptr<llvm::DebugInfoFinder> m_pDebugInfoFinder;
  289. const ShaderModel *m_pSM;
  290. unsigned m_DxilMajor;
  291. unsigned m_DxilMinor;
  292. unsigned m_ValMajor;
  293. unsigned m_ValMinor;
  294. bool m_ForceZeroStoreLifetimes;
  295. std::unique_ptr<OP> m_pOP;
  296. size_t m_pUnused;
  297. // LLVM used.
  298. std::vector<llvm::GlobalVariable*> m_LLVMUsed;
  299. // Type annotations.
  300. std::unique_ptr<DxilTypeSystem> m_pTypeSystem;
  301. // EntryProps for shader functions.
  302. DxilEntryPropsMap m_DxilEntryPropsMap;
  303. // Keeps track of patch constant functions used by hull shaders
  304. std::unordered_set<const llvm::Function *> m_PatchConstantFunctions;
  305. // Serialized ViewId state.
  306. std::vector<unsigned> m_SerializedState;
  307. // DXIL metadata serialization/deserialization.
  308. llvm::MDTuple *EmitDxilResources();
  309. void LoadDxilResources(const llvm::MDOperand &MDO);
  310. // Helpers.
  311. template<typename T> unsigned AddResource(std::vector<std::unique_ptr<T> > &Vec, std::unique_ptr<T> pRes);
  312. void LoadDxilSignature(const llvm::MDTuple *pSigTuple, DxilSignature &Sig, bool bInput);
  313. // properties from HLModule preserved as ShaderFlags
  314. bool m_bDisableOptimizations;
  315. bool m_bUseMinPrecision;
  316. bool m_bAllResourcesBound;
  317. // properties from HLModule that should not make it to the final DXIL
  318. uint32_t m_IntermediateFlags;
  319. uint32_t m_AutoBindingSpace;
  320. // porperties infered from the DXILTypeSystem
  321. bool m_bHasPayloadQualifiers;
  322. std::unique_ptr<DxilSubobjects> m_pSubobjects;
  323. // m_bMetadataErrors is true if non-fatal metadata errors were encountered.
  324. // Validator will fail in this case, but should not block module load.
  325. bool m_bMetadataErrors;
  326. };
  327. } // namespace hlsl