DxilContainerReflection.cpp 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilContainerReflection.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. // Provides support for reading DXIL container structures. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #include "llvm/ADT/STLExtras.h"
  12. #include "llvm/Bitcode/ReaderWriter.h"
  13. #include "llvm/IR/LLVMContext.h"
  14. #include "llvm/IR/InstIterator.h"
  15. #include "llvm/IR/Operator.h"
  16. #include "dxc/DxilContainer/DxilContainer.h"
  17. #include "dxc/DXIL/DxilModule.h"
  18. #include "dxc/DXIL/DxilShaderModel.h"
  19. #include "dxc/DXIL/DxilOperations.h"
  20. #include "dxc/DXIL/DxilInstructions.h"
  21. #include "dxc/Support/Global.h"
  22. #include "dxc/Support/Unicode.h"
  23. #include "dxc/Support/WinIncludes.h"
  24. #include "dxc/Support/microcom.h"
  25. #include "dxc/Support/FileIOHelper.h"
  26. #include "dxc/Support/dxcapi.impl.h"
  27. #include "dxc/DXIL/DxilFunctionProps.h"
  28. #include "dxc/DXIL/DxilPDB.h"
  29. #include "dxc/DXIL/DxilUtil.h"
  30. #include "dxc/HLSL/HLMatrixType.h"
  31. #include <unordered_set>
  32. #include "llvm/ADT/SetVector.h"
  33. #include "dxc/dxcapi.h"
  34. #ifdef LLVM_ON_WIN32
  35. #include "d3d12shader.h" // for compatibility
  36. #include "d3d11shader.h" // for compatibility
  37. #include "dxc/DxilContainer/DxilRuntimeReflection.h"
  38. const GUID IID_ID3D11ShaderReflection_43 = {
  39. 0x0a233719,
  40. 0x3960,
  41. 0x4578,
  42. {0x9d, 0x7c, 0x20, 0x3b, 0x8b, 0x1d, 0x9c, 0xc1}};
  43. const GUID IID_ID3D11ShaderReflection_47 = {
  44. 0x8d536ca1,
  45. 0x0cca,
  46. 0x4956,
  47. {0xa8, 0x37, 0x78, 0x69, 0x63, 0x75, 0x55, 0x84}};
  48. using namespace llvm;
  49. using namespace hlsl;
  50. using namespace hlsl::DXIL;
  51. class DxilContainerReflection : public IDxcContainerReflection {
  52. private:
  53. DXC_MICROCOM_TM_REF_FIELDS()
  54. CComPtr<IDxcBlob> m_container;
  55. const DxilContainerHeader *m_pHeader = nullptr;
  56. uint32_t m_headerLen = 0;
  57. bool IsLoaded() const { return m_pHeader != nullptr; }
  58. public:
  59. DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
  60. DXC_MICROCOM_TM_CTOR(DxilContainerReflection)
  61. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) {
  62. return DoBasicQueryInterface<IDxcContainerReflection>(this, iid, ppvObject);
  63. }
  64. HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pContainer) override;
  65. HRESULT STDMETHODCALLTYPE GetPartCount(_Out_ UINT32 *pResult) override;
  66. HRESULT STDMETHODCALLTYPE GetPartKind(UINT32 idx, _Out_ UINT32 *pResult) override;
  67. HRESULT STDMETHODCALLTYPE GetPartContent(UINT32 idx, _COM_Outptr_ IDxcBlob **ppResult) override;
  68. HRESULT STDMETHODCALLTYPE FindFirstPartKind(UINT32 kind, _Out_ UINT32 *pResult) override;
  69. HRESULT STDMETHODCALLTYPE GetPartReflection(UINT32 idx, REFIID iid, _COM_Outptr_ void **ppvObject) override;
  70. };
  71. class CShaderReflectionConstantBuffer;
  72. class CShaderReflectionType;
  73. enum class PublicAPI { D3D12 = 0, D3D11_47 = 1, D3D11_43 = 2 };
  74. class DxilModuleReflection {
  75. public:
  76. hlsl::RDAT::DxilRuntimeData m_RDAT;
  77. LLVMContext Context;
  78. std::unique_ptr<Module> m_pModule; // Must come after LLVMContext, otherwise unique_ptr will over-delete.
  79. DxilModule *m_pDxilModule = nullptr;
  80. bool m_bUsageInMetadata = false;
  81. std::vector<std::unique_ptr<CShaderReflectionConstantBuffer>> m_CBs;
  82. std::vector<D3D12_SHADER_INPUT_BIND_DESC> m_Resources;
  83. std::vector<std::unique_ptr<CShaderReflectionType>> m_Types;
  84. void CreateReflectionObjects();
  85. void CreateReflectionObjectForResource(DxilResourceBase *R);
  86. HRESULT LoadRDAT(const DxilPartHeader *pPart);
  87. HRESULT LoadModule(const DxilPartHeader *pPart);
  88. // Common code
  89. ID3D12ShaderReflectionConstantBuffer* _GetConstantBufferByIndex(UINT Index);
  90. ID3D12ShaderReflectionConstantBuffer* _GetConstantBufferByName(LPCSTR Name);
  91. HRESULT _GetResourceBindingDesc(UINT ResourceIndex,
  92. _Out_ D3D12_SHADER_INPUT_BIND_DESC *pDesc,
  93. PublicAPI api = PublicAPI::D3D12);
  94. ID3D12ShaderReflectionVariable* _GetVariableByName(LPCSTR Name);
  95. HRESULT _GetResourceBindingDescByName(LPCSTR Name,
  96. D3D12_SHADER_INPUT_BIND_DESC *pDesc,
  97. PublicAPI api = PublicAPI::D3D12);
  98. };
  99. class DxilShaderReflection : public DxilModuleReflection, public ID3D12ShaderReflection {
  100. private:
  101. DXC_MICROCOM_TM_REF_FIELDS()
  102. std::vector<D3D12_SIGNATURE_PARAMETER_DESC> m_InputSignature;
  103. std::vector<D3D12_SIGNATURE_PARAMETER_DESC> m_OutputSignature;
  104. std::vector<D3D12_SIGNATURE_PARAMETER_DESC> m_PatchConstantSignature;
  105. std::vector<std::unique_ptr<char[]>> m_UpperCaseNames;
  106. void SetCBufferUsage();
  107. void CreateReflectionObjectsForSignature(
  108. const DxilSignature &Sig,
  109. std::vector<D3D12_SIGNATURE_PARAMETER_DESC> &Descs);
  110. LPCSTR CreateUpperCase(LPCSTR pValue);
  111. void MarkUsedSignatureElements();
  112. public:
  113. PublicAPI m_PublicAPI;
  114. void SetPublicAPI(PublicAPI value) { m_PublicAPI = value; }
  115. static PublicAPI IIDToAPI(REFIID iid) {
  116. PublicAPI api = PublicAPI::D3D12;
  117. if (IsEqualIID(IID_ID3D11ShaderReflection_43, iid))
  118. api = PublicAPI::D3D11_43;
  119. else if (IsEqualIID(IID_ID3D11ShaderReflection_47, iid))
  120. api = PublicAPI::D3D11_47;
  121. return api;
  122. }
  123. DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
  124. DXC_MICROCOM_TM_CTOR(DxilShaderReflection)
  125. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) {
  126. HRESULT hr = DoBasicQueryInterface<ID3D12ShaderReflection>(this, iid, ppvObject);
  127. if (hr == E_NOINTERFACE) {
  128. // ID3D11ShaderReflection is identical to ID3D12ShaderReflection, except
  129. // for some shorter data structures in some out parameters.
  130. PublicAPI api = IIDToAPI(iid);
  131. if (api == m_PublicAPI) {
  132. *ppvObject = (ID3D12ShaderReflection *)this;
  133. this->AddRef();
  134. hr = S_OK;
  135. }
  136. }
  137. return hr;
  138. }
  139. HRESULT Load(const DxilPartHeader *pModulePart, const DxilPartHeader *pRDATPart);
  140. // ID3D12ShaderReflection
  141. STDMETHODIMP GetDesc(THIS_ _Out_ D3D12_SHADER_DESC *pDesc);
  142. STDMETHODIMP_(ID3D12ShaderReflectionConstantBuffer*) GetConstantBufferByIndex(THIS_ _In_ UINT Index);
  143. STDMETHODIMP_(ID3D12ShaderReflectionConstantBuffer*) GetConstantBufferByName(THIS_ _In_ LPCSTR Name);
  144. STDMETHODIMP GetResourceBindingDesc(THIS_ _In_ UINT ResourceIndex,
  145. _Out_ D3D12_SHADER_INPUT_BIND_DESC *pDesc);
  146. STDMETHODIMP GetInputParameterDesc(THIS_ _In_ UINT ParameterIndex,
  147. _Out_ D3D12_SIGNATURE_PARAMETER_DESC *pDesc);
  148. STDMETHODIMP GetOutputParameterDesc(THIS_ _In_ UINT ParameterIndex,
  149. _Out_ D3D12_SIGNATURE_PARAMETER_DESC *pDesc);
  150. STDMETHODIMP GetPatchConstantParameterDesc(THIS_ _In_ UINT ParameterIndex,
  151. _Out_ D3D12_SIGNATURE_PARAMETER_DESC *pDesc);
  152. STDMETHODIMP_(ID3D12ShaderReflectionVariable*) GetVariableByName(THIS_ _In_ LPCSTR Name);
  153. STDMETHODIMP GetResourceBindingDescByName(THIS_ _In_ LPCSTR Name,
  154. _Out_ D3D12_SHADER_INPUT_BIND_DESC *pDesc);
  155. STDMETHODIMP_(UINT) GetMovInstructionCount(THIS);
  156. STDMETHODIMP_(UINT) GetMovcInstructionCount(THIS);
  157. STDMETHODIMP_(UINT) GetConversionInstructionCount(THIS);
  158. STDMETHODIMP_(UINT) GetBitwiseInstructionCount(THIS);
  159. STDMETHODIMP_(D3D_PRIMITIVE) GetGSInputPrimitive(THIS);
  160. STDMETHODIMP_(BOOL) IsSampleFrequencyShader(THIS);
  161. STDMETHODIMP_(UINT) GetNumInterfaceSlots(THIS);
  162. STDMETHODIMP GetMinFeatureLevel(THIS_ _Out_ enum D3D_FEATURE_LEVEL* pLevel);
  163. STDMETHODIMP_(UINT) GetThreadGroupSize(THIS_
  164. _Out_opt_ UINT* pSizeX,
  165. _Out_opt_ UINT* pSizeY,
  166. _Out_opt_ UINT* pSizeZ);
  167. STDMETHODIMP_(UINT64) GetRequiresFlags(THIS);
  168. };
  169. class CFunctionReflection;
  170. class DxilLibraryReflection : public DxilModuleReflection, public ID3D12LibraryReflection {
  171. private:
  172. DXC_MICROCOM_TM_REF_FIELDS()
  173. // Storage, and function by name:
  174. typedef DenseMap<StringRef, std::unique_ptr<CFunctionReflection> > FunctionMap;
  175. typedef DenseMap<const Function*, CFunctionReflection*> FunctionsByPtr;
  176. FunctionMap m_FunctionMap;
  177. FunctionsByPtr m_FunctionsByPtr;
  178. // Enable indexing into functions in deterministic order:
  179. std::vector<CFunctionReflection*> m_FunctionVector;
  180. void AddResourceDependencies();
  181. void SetCBufferUsage();
  182. public:
  183. DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
  184. DXC_MICROCOM_TM_CTOR(DxilLibraryReflection)
  185. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) {
  186. return DoBasicQueryInterface<ID3D12LibraryReflection>(this, iid, ppvObject);
  187. }
  188. HRESULT Load(const DxilPartHeader *pModulePart, const DxilPartHeader *pDXILPart);
  189. // ID3D12LibraryReflection
  190. STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_LIBRARY_DESC * pDesc);
  191. STDMETHOD_(ID3D12FunctionReflection *, GetFunctionByIndex)(THIS_ _In_ INT FunctionIndex);
  192. };
  193. namespace hlsl {
  194. HRESULT CreateDxilShaderReflection(const DxilPartHeader *pModulePart, const DxilPartHeader *pRDATPart, REFIID iid, void **ppvObject) {
  195. if (!ppvObject)
  196. return E_INVALIDARG;
  197. CComPtr<DxilShaderReflection> pReflection = DxilShaderReflection::Alloc(DxcGetThreadMallocNoRef());
  198. IFROOM(pReflection.p);
  199. PublicAPI api = DxilShaderReflection::IIDToAPI(iid);
  200. pReflection->SetPublicAPI(api);
  201. // pRDATPart to be used for transition.
  202. IFR(pReflection->Load(pModulePart, pRDATPart));
  203. IFR(pReflection.p->QueryInterface(iid, ppvObject));
  204. return S_OK;
  205. }
  206. HRESULT CreateDxilLibraryReflection(const DxilPartHeader *pModulePart, const DxilPartHeader *pRDATPart, REFIID iid, void **ppvObject) {
  207. if (!ppvObject)
  208. return E_INVALIDARG;
  209. CComPtr<DxilLibraryReflection> pReflection = DxilLibraryReflection::Alloc(DxcGetThreadMallocNoRef());
  210. IFROOM(pReflection.p);
  211. // pRDATPart used for resource usage per-function.
  212. IFR(pReflection->Load(pModulePart, pRDATPart));
  213. IFR(pReflection.p->QueryInterface(iid, ppvObject));
  214. return S_OK;
  215. }
  216. }
  217. _Use_decl_annotations_
  218. HRESULT DxilContainerReflection::Load(IDxcBlob *pContainer) {
  219. CComPtr<IDxcBlob> pPDBContainer;
  220. {
  221. DxcThreadMalloc DxcMalloc(m_pMalloc);
  222. CComPtr<IStream> pStream;
  223. IFR(hlsl::CreateReadOnlyBlobStream(pContainer, &pStream));
  224. if (SUCCEEDED(hlsl::pdb::LoadDataFromStream(m_pMalloc, pStream, &pPDBContainer))) {
  225. pContainer = pPDBContainer;
  226. }
  227. }
  228. if (pContainer == nullptr) {
  229. m_container.Release();
  230. m_pHeader = nullptr;
  231. m_headerLen = 0;
  232. return S_OK;
  233. }
  234. uint32_t bufLen = pContainer->GetBufferSize();
  235. const DxilContainerHeader *pHeader =
  236. IsDxilContainerLike(pContainer->GetBufferPointer(), bufLen);
  237. if (pHeader == nullptr) {
  238. return E_INVALIDARG;
  239. }
  240. if (!IsValidDxilContainer(pHeader, bufLen)) {
  241. return E_INVALIDARG;
  242. }
  243. m_container = pContainer;
  244. m_headerLen = bufLen;
  245. m_pHeader = pHeader;
  246. return S_OK;
  247. }
  248. _Use_decl_annotations_
  249. HRESULT DxilContainerReflection::GetPartCount(UINT32 *pResult) {
  250. if (pResult == nullptr) return E_POINTER;
  251. if (!IsLoaded()) return E_NOT_VALID_STATE;
  252. *pResult = m_pHeader->PartCount;
  253. return S_OK;
  254. }
  255. _Use_decl_annotations_
  256. HRESULT DxilContainerReflection::GetPartKind(UINT32 idx, _Out_ UINT32 *pResult) {
  257. if (pResult == nullptr) return E_POINTER;
  258. if (!IsLoaded()) return E_NOT_VALID_STATE;
  259. if (idx >= m_pHeader->PartCount) return E_BOUNDS;
  260. const DxilPartHeader *pPart = GetDxilContainerPart(m_pHeader, idx);
  261. *pResult = pPart->PartFourCC;
  262. return S_OK;
  263. }
  264. _Use_decl_annotations_
  265. HRESULT DxilContainerReflection::GetPartContent(UINT32 idx, _COM_Outptr_ IDxcBlob **ppResult) {
  266. if (ppResult == nullptr) return E_POINTER;
  267. *ppResult = nullptr;
  268. if (!IsLoaded()) return E_NOT_VALID_STATE;
  269. if (idx >= m_pHeader->PartCount) return E_BOUNDS;
  270. const DxilPartHeader *pPart = GetDxilContainerPart(m_pHeader, idx);
  271. const char *pData = GetDxilPartData(pPart);
  272. uint32_t offset = (uint32_t)(pData - (char*)m_container->GetBufferPointer()); // Offset from the beginning.
  273. uint32_t length = pPart->PartSize;
  274. DxcThreadMalloc TM(m_pMalloc);
  275. return DxcCreateBlobFromBlob(m_container, offset, length, ppResult);
  276. }
  277. _Use_decl_annotations_
  278. HRESULT DxilContainerReflection::FindFirstPartKind(UINT32 kind, _Out_ UINT32 *pResult) {
  279. if (pResult == nullptr) return E_POINTER;
  280. *pResult = 0;
  281. if (!IsLoaded()) return E_NOT_VALID_STATE;
  282. DxilPartIterator it = std::find_if(begin(m_pHeader), end(m_pHeader), DxilPartIsType(kind));
  283. if (it == end(m_pHeader)) return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
  284. *pResult = it.index;
  285. return S_OK;
  286. }
  287. _Use_decl_annotations_
  288. HRESULT DxilContainerReflection::GetPartReflection(UINT32 idx, REFIID iid, void **ppvObject) {
  289. if (ppvObject == nullptr) return E_POINTER;
  290. *ppvObject = nullptr;
  291. if (!IsLoaded()) return E_NOT_VALID_STATE;
  292. if (idx >= m_pHeader->PartCount) return E_BOUNDS;
  293. const DxilPartHeader *pPart = GetDxilContainerPart(m_pHeader, idx);
  294. if (pPart->PartFourCC != DFCC_DXIL && pPart->PartFourCC != DFCC_ShaderDebugInfoDXIL &&
  295. pPart->PartFourCC != DFCC_ShaderStatistics) {
  296. return E_NOTIMPL;
  297. }
  298. // Use DFCC_ShaderStatistics for reflection instead of DXIL part, until switch
  299. // to using RDAT for reflection instead of module.
  300. const DxilPartHeader *pRDATPart = nullptr;
  301. for (idx = 0; idx < m_pHeader->PartCount; ++idx) {
  302. const DxilPartHeader *pPartTest = GetDxilContainerPart(m_pHeader, idx);
  303. if (pPartTest->PartFourCC == DFCC_RuntimeData) {
  304. pRDATPart = pPartTest;
  305. }
  306. if (pPart->PartFourCC != DFCC_ShaderStatistics) {
  307. if (pPartTest->PartFourCC == DFCC_ShaderStatistics) {
  308. const DxilProgramHeader *pProgramHeaderTest =
  309. reinterpret_cast<const DxilProgramHeader*>(GetDxilPartData(pPartTest));
  310. if (IsValidDxilProgramHeader(pProgramHeaderTest, pPartTest->PartSize)) {
  311. pPart = pPartTest;
  312. continue;
  313. }
  314. }
  315. }
  316. }
  317. const DxilProgramHeader *pProgramHeader =
  318. reinterpret_cast<const DxilProgramHeader*>(GetDxilPartData(pPart));
  319. if (!IsValidDxilProgramHeader(pProgramHeader, pPart->PartSize)) {
  320. return E_INVALIDARG;
  321. }
  322. DxcThreadMalloc TM(m_pMalloc);
  323. HRESULT hr = S_OK;
  324. DXIL::ShaderKind SK = GetVersionShaderType(pProgramHeader->ProgramVersion);
  325. if (SK == DXIL::ShaderKind::Library) {
  326. IFC(hlsl::CreateDxilLibraryReflection(pPart, pRDATPart, iid, ppvObject));
  327. } else {
  328. IFC(hlsl::CreateDxilShaderReflection(pPart, pRDATPart, iid, ppvObject));
  329. }
  330. Cleanup:
  331. return hr;
  332. }
  333. void hlsl::CreateDxcContainerReflection(IDxcContainerReflection **ppResult) {
  334. CComPtr<DxilContainerReflection> pReflection = DxilContainerReflection::Alloc(DxcGetThreadMallocNoRef());
  335. *ppResult = pReflection.Detach();
  336. if (*ppResult == nullptr) throw std::bad_alloc();
  337. }
  338. ///////////////////////////////////////////////////////////////////////////////
  339. // DxilShaderReflection implementation - helper objects. //
  340. class CShaderReflectionType;
  341. class CShaderReflectionVariable;
  342. class CShaderReflectionConstantBuffer;
  343. class CShaderReflection;
  344. struct D3D11_INTERNALSHADER_RESOURCE_DEF;
  345. class CShaderReflectionType : public ID3D12ShaderReflectionType
  346. {
  347. friend class CShaderReflectionConstantBuffer;
  348. protected:
  349. D3D12_SHADER_TYPE_DESC m_Desc;
  350. UINT m_SizeInCBuffer;
  351. std::string m_Name;
  352. std::vector<StringRef> m_MemberNames;
  353. std::vector<CShaderReflectionType*> m_MemberTypes;
  354. CShaderReflectionType* m_pSubType;
  355. CShaderReflectionType* m_pBaseClass;
  356. std::vector<CShaderReflectionType*> m_Interfaces;
  357. ULONG_PTR m_Identity;
  358. public:
  359. // Internal
  360. HRESULT InitializeEmpty();
  361. HRESULT Initialize(
  362. DxilModule &M,
  363. llvm::Type *type,
  364. DxilFieldAnnotation &typeAnnotation,
  365. unsigned int baseOffset,
  366. std::vector<std::unique_ptr<CShaderReflectionType>>& allTypes,
  367. bool isCBuffer);
  368. // ID3D12ShaderReflectionType
  369. STDMETHOD(GetDesc)(D3D12_SHADER_TYPE_DESC *pDesc);
  370. STDMETHOD_(ID3D12ShaderReflectionType*, GetMemberTypeByIndex)(UINT Index);
  371. STDMETHOD_(ID3D12ShaderReflectionType*, GetMemberTypeByName)(LPCSTR Name);
  372. STDMETHOD_(LPCSTR, GetMemberTypeName)(UINT Index);
  373. STDMETHOD(IsEqual)(THIS_ ID3D12ShaderReflectionType* pType);
  374. STDMETHOD_(ID3D12ShaderReflectionType*, GetSubType)(THIS);
  375. STDMETHOD_(ID3D12ShaderReflectionType*, GetBaseClass)(THIS);
  376. STDMETHOD_(UINT, GetNumInterfaces)(THIS);
  377. STDMETHOD_(ID3D12ShaderReflectionType*, GetInterfaceByIndex)(THIS_ UINT uIndex);
  378. STDMETHOD(IsOfType)(THIS_ ID3D12ShaderReflectionType* pType);
  379. STDMETHOD(ImplementsInterface)(THIS_ ID3D12ShaderReflectionType* pBase);
  380. bool CheckEqual(_In_ CShaderReflectionType *pOther) {
  381. return m_Identity == pOther->m_Identity;
  382. }
  383. UINT GetCBufferSize() { return m_SizeInCBuffer; }
  384. };
  385. class CShaderReflectionVariable : public ID3D12ShaderReflectionVariable
  386. {
  387. protected:
  388. D3D12_SHADER_VARIABLE_DESC m_Desc;
  389. CShaderReflectionType *m_pType;
  390. CShaderReflectionConstantBuffer *m_pBuffer;
  391. BYTE *m_pDefaultValue;
  392. public:
  393. void Initialize(CShaderReflectionConstantBuffer *pBuffer,
  394. D3D12_SHADER_VARIABLE_DESC *pDesc,
  395. CShaderReflectionType *pType, BYTE *pDefaultValue);
  396. LPCSTR GetName() { return m_Desc.Name; }
  397. // ID3D12ShaderReflectionVariable
  398. STDMETHOD(GetDesc)(D3D12_SHADER_VARIABLE_DESC *pDesc);
  399. STDMETHOD_(ID3D12ShaderReflectionType*, GetType)();
  400. STDMETHOD_(ID3D12ShaderReflectionConstantBuffer*, GetBuffer)();
  401. STDMETHOD_(UINT, GetInterfaceSlot)(THIS_ UINT uArrayIndex);
  402. };
  403. class CShaderReflectionConstantBuffer : public ID3D12ShaderReflectionConstantBuffer
  404. {
  405. protected:
  406. D3D12_SHADER_BUFFER_DESC m_Desc;
  407. std::vector<CShaderReflectionVariable> m_Variables;
  408. // For StructuredBuffer arrays, Name will have [0] appended for each dimension to match fxc behavior.
  409. std::string m_ReflectionName;
  410. public:
  411. CShaderReflectionConstantBuffer() = default;
  412. CShaderReflectionConstantBuffer(CShaderReflectionConstantBuffer &&other) {
  413. m_Desc = other.m_Desc;
  414. std::swap(m_Variables, other.m_Variables);
  415. }
  416. void Initialize(DxilModule &M,
  417. DxilCBuffer &CB,
  418. std::vector<std::unique_ptr<CShaderReflectionType>>& allTypes,
  419. bool bUsageInMetadata);
  420. void InitializeStructuredBuffer(DxilModule &M,
  421. DxilResource &R,
  422. std::vector<std::unique_ptr<CShaderReflectionType>>& allTypes);
  423. LPCSTR GetName() { return m_Desc.Name; }
  424. // ID3D12ShaderReflectionConstantBuffer
  425. STDMETHOD(GetDesc)(D3D12_SHADER_BUFFER_DESC *pDesc);
  426. STDMETHOD_(ID3D12ShaderReflectionVariable*, GetVariableByIndex)(UINT Index);
  427. STDMETHOD_(ID3D12ShaderReflectionVariable*, GetVariableByName)(LPCSTR Name);
  428. };
  429. // Invalid type sentinel definitions
  430. class CInvalidSRType;
  431. class CInvalidSRVariable;
  432. class CInvalidSRConstantBuffer;
  433. class CInvalidSRLibraryFunction;
  434. class CInvalidSRFunctionParameter;
  435. class CInvalidSRType : public ID3D12ShaderReflectionType {
  436. STDMETHOD(GetDesc)(D3D12_SHADER_TYPE_DESC *pDesc) { return E_FAIL; }
  437. STDMETHOD_(ID3D12ShaderReflectionType*, GetMemberTypeByIndex)(UINT Index);
  438. STDMETHOD_(ID3D12ShaderReflectionType*, GetMemberTypeByName)(LPCSTR Name);
  439. STDMETHOD_(LPCSTR, GetMemberTypeName)(UINT Index) { return "$Invalid"; }
  440. STDMETHOD(IsEqual)(THIS_ ID3D12ShaderReflectionType* pType) { return E_FAIL; }
  441. STDMETHOD_(ID3D12ShaderReflectionType*, GetSubType)(THIS);
  442. STDMETHOD_(ID3D12ShaderReflectionType*, GetBaseClass)(THIS);
  443. STDMETHOD_(UINT, GetNumInterfaces)(THIS) { return 0; }
  444. STDMETHOD_(ID3D12ShaderReflectionType*, GetInterfaceByIndex)(THIS_ UINT uIndex);
  445. STDMETHOD(IsOfType)(THIS_ ID3D12ShaderReflectionType* pType) { return E_FAIL; }
  446. STDMETHOD(ImplementsInterface)(THIS_ ID3D12ShaderReflectionType* pBase) { return E_FAIL; }
  447. };
  448. static CInvalidSRType g_InvalidSRType;
  449. ID3D12ShaderReflectionType* CInvalidSRType::GetMemberTypeByIndex(UINT) { return &g_InvalidSRType; }
  450. ID3D12ShaderReflectionType* CInvalidSRType::GetMemberTypeByName(LPCSTR) { return &g_InvalidSRType; }
  451. ID3D12ShaderReflectionType* CInvalidSRType::GetSubType() { return &g_InvalidSRType; }
  452. ID3D12ShaderReflectionType* CInvalidSRType::GetBaseClass() { return &g_InvalidSRType; }
  453. ID3D12ShaderReflectionType* CInvalidSRType::GetInterfaceByIndex(UINT) { return &g_InvalidSRType; }
  454. class CInvalidSRVariable : public ID3D12ShaderReflectionVariable {
  455. STDMETHOD(GetDesc)(D3D12_SHADER_VARIABLE_DESC *pDesc) { return E_FAIL; }
  456. STDMETHOD_(ID3D12ShaderReflectionType*, GetType)() { return &g_InvalidSRType; }
  457. STDMETHOD_(ID3D12ShaderReflectionConstantBuffer*, GetBuffer)();
  458. STDMETHOD_(UINT, GetInterfaceSlot)(THIS_ UINT uIndex) { return UINT_MAX; }
  459. };
  460. static CInvalidSRVariable g_InvalidSRVariable;
  461. class CInvalidSRConstantBuffer : public ID3D12ShaderReflectionConstantBuffer {
  462. STDMETHOD(GetDesc)(D3D12_SHADER_BUFFER_DESC *pDesc) { return E_FAIL; }
  463. STDMETHOD_(ID3D12ShaderReflectionVariable*, GetVariableByIndex)(UINT Index) { return &g_InvalidSRVariable; }
  464. STDMETHOD_(ID3D12ShaderReflectionVariable*, GetVariableByName)(LPCSTR Name) { return &g_InvalidSRVariable; }
  465. };
  466. static CInvalidSRConstantBuffer g_InvalidSRConstantBuffer;
  467. class CInvalidFunctionParameter : public ID3D12FunctionParameterReflection {
  468. STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_PARAMETER_DESC * pDesc) { return E_FAIL; }
  469. };
  470. CInvalidFunctionParameter g_InvalidFunctionParameter;
  471. class CInvalidFunction : public ID3D12FunctionReflection {
  472. STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_FUNCTION_DESC * pDesc) { return E_FAIL; }
  473. STDMETHOD_(ID3D12ShaderReflectionConstantBuffer *, GetConstantBufferByIndex)(THIS_ _In_ UINT BufferIndex) { return &g_InvalidSRConstantBuffer; }
  474. STDMETHOD_(ID3D12ShaderReflectionConstantBuffer *, GetConstantBufferByName)(THIS_ _In_ LPCSTR Name) { return &g_InvalidSRConstantBuffer; }
  475. STDMETHOD(GetResourceBindingDesc)(THIS_ _In_ UINT ResourceIndex,
  476. _Out_ D3D12_SHADER_INPUT_BIND_DESC * pDesc) { return E_FAIL; }
  477. STDMETHOD_(ID3D12ShaderReflectionVariable *, GetVariableByName)(THIS_ _In_ LPCSTR Name) { return nullptr; }
  478. STDMETHOD(GetResourceBindingDescByName)(THIS_ _In_ LPCSTR Name,
  479. _Out_ D3D12_SHADER_INPUT_BIND_DESC * pDesc) { return E_FAIL; }
  480. // Use D3D_RETURN_PARAMETER_INDEX to get description of the return value.
  481. STDMETHOD_(ID3D12FunctionParameterReflection *, GetFunctionParameter)(THIS_ _In_ INT ParameterIndex) { return &g_InvalidFunctionParameter; }
  482. };
  483. CInvalidFunction g_InvalidFunction;
  484. void CShaderReflectionVariable::Initialize(
  485. CShaderReflectionConstantBuffer *pBuffer, D3D12_SHADER_VARIABLE_DESC *pDesc,
  486. CShaderReflectionType *pType, BYTE *pDefaultValue) {
  487. m_pBuffer = pBuffer;
  488. memcpy(&m_Desc, pDesc, sizeof(m_Desc));
  489. m_pType = pType;
  490. m_pDefaultValue = pDefaultValue;
  491. }
  492. HRESULT CShaderReflectionVariable::GetDesc(D3D12_SHADER_VARIABLE_DESC *pDesc) {
  493. if (!pDesc) return E_POINTER;
  494. memcpy(pDesc, &m_Desc, sizeof(m_Desc));
  495. return S_OK;
  496. }
  497. ID3D12ShaderReflectionType *CShaderReflectionVariable::GetType() {
  498. return m_pType;
  499. }
  500. ID3D12ShaderReflectionConstantBuffer *CShaderReflectionVariable::GetBuffer() {
  501. return m_pBuffer;
  502. }
  503. UINT CShaderReflectionVariable::GetInterfaceSlot(UINT uArrayIndex) {
  504. return UINT_MAX;
  505. }
  506. ID3D12ShaderReflectionConstantBuffer *CInvalidSRVariable::GetBuffer() {
  507. return &g_InvalidSRConstantBuffer;
  508. }
  509. STDMETHODIMP CShaderReflectionType::GetDesc(D3D12_SHADER_TYPE_DESC *pDesc)
  510. {
  511. if (!pDesc) return E_POINTER;
  512. memcpy(pDesc, &m_Desc, sizeof(m_Desc));
  513. return S_OK;
  514. }
  515. STDMETHODIMP_(ID3D12ShaderReflectionType*) CShaderReflectionType::GetMemberTypeByIndex(UINT Index)
  516. {
  517. if (Index >= m_MemberTypes.size()) {
  518. return &g_InvalidSRType;
  519. }
  520. return m_MemberTypes[Index];
  521. }
  522. STDMETHODIMP_(LPCSTR) CShaderReflectionType::GetMemberTypeName(UINT Index)
  523. {
  524. if (Index >= m_MemberTypes.size()) {
  525. return nullptr;
  526. }
  527. return (LPCSTR) m_MemberNames[Index].bytes_begin();
  528. }
  529. STDMETHODIMP_(ID3D12ShaderReflectionType*) CShaderReflectionType::GetMemberTypeByName(LPCSTR Name)
  530. {
  531. UINT memberCount = m_Desc.Members;
  532. for( UINT mm = 0; mm < memberCount; ++mm ) {
  533. if( m_MemberNames[mm] == Name ) {
  534. return m_MemberTypes[mm];
  535. }
  536. }
  537. return nullptr;
  538. }
  539. STDMETHODIMP CShaderReflectionType::IsEqual(THIS_ ID3D12ShaderReflectionType* pType)
  540. {
  541. // TODO: implement this check, if users actually depend on it
  542. return S_FALSE;
  543. }
  544. STDMETHODIMP_(ID3D12ShaderReflectionType*) CShaderReflectionType::GetSubType(THIS)
  545. {
  546. // TODO: implement `class`-related features, if requested
  547. return nullptr;
  548. }
  549. STDMETHODIMP_(ID3D12ShaderReflectionType*) CShaderReflectionType::GetBaseClass(THIS)
  550. {
  551. // TODO: implement `class`-related features, if requested
  552. return nullptr;
  553. }
  554. STDMETHODIMP_(UINT) CShaderReflectionType::GetNumInterfaces(THIS)
  555. {
  556. // HLSL interfaces have been deprecated
  557. return 0;
  558. }
  559. STDMETHODIMP_(ID3D12ShaderReflectionType*) CShaderReflectionType::GetInterfaceByIndex(THIS_ UINT uIndex)
  560. {
  561. // HLSL interfaces have been deprecated
  562. return nullptr;
  563. }
  564. STDMETHODIMP CShaderReflectionType::IsOfType(THIS_ ID3D12ShaderReflectionType* pType)
  565. {
  566. // TODO: implement `class`-related features, if requested
  567. return S_FALSE;
  568. }
  569. STDMETHODIMP CShaderReflectionType::ImplementsInterface(THIS_ ID3D12ShaderReflectionType* pBase)
  570. {
  571. // HLSL interfaces have been deprecated
  572. return S_FALSE;
  573. }
  574. // Helper routine for types that don't have an obvious mapping
  575. // to the existing shader reflection interface.
  576. static bool ProcessUnhandledObjectType(
  577. llvm::StructType *structType,
  578. D3D_SHADER_VARIABLE_TYPE *outObjectType)
  579. {
  580. // Don't actually make this a hard error, but instead report the problem using a suitable debug message.
  581. #ifdef DBG
  582. OutputDebugFormatA("DxilContainerReflection.cpp: error: unhandled object type '%s'.\n", structType->getName().str().c_str());
  583. #endif
  584. *outObjectType = D3D_SVT_VOID;
  585. return true;
  586. }
  587. // Helper routine to try to detect if a type represents an HLSL "object" type
  588. // (a texture, sampler, buffer, etc.), and to extract the coresponding shader
  589. // reflection type.
  590. static bool TryToDetectObjectType(
  591. llvm::StructType *structType,
  592. D3D_SHADER_VARIABLE_TYPE *outObjectType)
  593. {
  594. // Note: This logic is largely duplicated from `dxilutil::IsHLSLObjectType`
  595. // with the addition of returning the appropriate reflection type tag.
  596. //
  597. // That logic looks error-prone, since it relies on string tests against
  598. // type names, including cases that just test against a prefix.
  599. // This code doesn't try to be any more robust.
  600. StringRef name = structType->getName();
  601. if(name.startswith("dx.types.wave_t") )
  602. {
  603. return ProcessUnhandledObjectType(structType, outObjectType);
  604. }
  605. // Strip off some prefixes we are likely to see.
  606. name = name.ltrim("class.");
  607. name = name.ltrim("struct.");
  608. // Slice types occur as intermediates (they aren not objects)
  609. if(name.endswith("_slice_type")) { return false; }
  610. // We might check for an exact name match, or a prefix match
  611. #define EXACT_MATCH(NAME, TAG) \
  612. else if(name == #NAME) do { *outObjectType = TAG; return true; } while(0)
  613. #define PREFIX_MATCH(NAME, TAG) \
  614. else if(name.startswith(#NAME)) do { *outObjectType = TAG; return true; } while(0)
  615. if(0) {}
  616. EXACT_MATCH(SamplerState, D3D_SVT_SAMPLER);
  617. EXACT_MATCH(SamplerComparisonState, D3D_SVT_SAMPLER);
  618. // Note: GS output stream types are supported in the reflection interface.
  619. else if(name.startswith("TriangleStream")) { return ProcessUnhandledObjectType(structType, outObjectType); }
  620. else if(name.startswith("PointStream")) { return ProcessUnhandledObjectType(structType, outObjectType); }
  621. else if(name.startswith("LineStream")) { return ProcessUnhandledObjectType(structType, outObjectType); }
  622. PREFIX_MATCH(AppendStructuredBuffer, D3D_SVT_APPEND_STRUCTURED_BUFFER);
  623. PREFIX_MATCH(ConsumeStructuredBuffer, D3D_SVT_CONSUME_STRUCTURED_BUFFER);
  624. PREFIX_MATCH(ConstantBuffer, D3D_SVT_CBUFFER);
  625. // Note: the `HLModule` code does this trick to avoid checking more names
  626. // than it has to, but it doesn't seem 100% correct to do this.
  627. // TODO: consider just listing the `RasterizerOrdered` cases explicitly,
  628. // just as we do for the `RW` cases already.
  629. name = name.ltrim("RasterizerOrdered");
  630. if(0) {}
  631. EXACT_MATCH(ByteAddressBuffer, D3D_SVT_BYTEADDRESS_BUFFER);
  632. EXACT_MATCH(RWByteAddressBuffer, D3D_SVT_RWBYTEADDRESS_BUFFER);
  633. PREFIX_MATCH(Buffer, D3D_SVT_BUFFER);
  634. PREFIX_MATCH(RWBuffer, D3D_SVT_RWBUFFER);
  635. PREFIX_MATCH(StructuredBuffer, D3D_SVT_STRUCTURED_BUFFER);
  636. PREFIX_MATCH(RWStructuredBuffer, D3D_SVT_RWSTRUCTURED_BUFFER);
  637. PREFIX_MATCH(Texture1D, D3D_SVT_TEXTURE1D);
  638. PREFIX_MATCH(RWTexture1D, D3D_SVT_RWTEXTURE1D);
  639. PREFIX_MATCH(Texture1DArray, D3D_SVT_TEXTURE1DARRAY);
  640. PREFIX_MATCH(RWTexture1DArray, D3D_SVT_RWTEXTURE1DARRAY);
  641. PREFIX_MATCH(Texture2D, D3D_SVT_TEXTURE2D);
  642. PREFIX_MATCH(RWTexture2D, D3D_SVT_RWTEXTURE2D);
  643. PREFIX_MATCH(Texture2DArray, D3D_SVT_TEXTURE2DARRAY);
  644. PREFIX_MATCH(RWTexture2DArray, D3D_SVT_RWTEXTURE2DARRAY);
  645. PREFIX_MATCH(Texture3D, D3D_SVT_TEXTURE3D);
  646. PREFIX_MATCH(RWTexture3D, D3D_SVT_RWTEXTURE3D);
  647. PREFIX_MATCH(TextureCube, D3D_SVT_TEXTURECUBE);
  648. PREFIX_MATCH(TextureCubeArray, D3D_SVT_TEXTURECUBEARRAY);
  649. PREFIX_MATCH(Texture2DMS, D3D_SVT_TEXTURE2DMS);
  650. PREFIX_MATCH(Texture2DMSArray, D3D_SVT_TEXTURE2DMSARRAY);
  651. #undef EXACT_MATCH
  652. #undef PREFIX_MATCH
  653. // Default: not an object type
  654. return false;
  655. }
  656. // Helper to determine if an LLVM type represents an HLSL
  657. // object type (uses the `TryToDetectObjectType()` function
  658. // defined previously).
  659. static bool IsObjectType(
  660. llvm::Type* inType)
  661. {
  662. llvm::Type* type = inType;
  663. while(type->isArrayTy())
  664. {
  665. type = type->getArrayElementType();
  666. }
  667. llvm::StructType* structType = dyn_cast<StructType>(type);
  668. if(!structType)
  669. return false;
  670. D3D_SHADER_VARIABLE_TYPE ignored;
  671. return TryToDetectObjectType(structType, &ignored);
  672. }
  673. HRESULT CShaderReflectionType::InitializeEmpty()
  674. {
  675. ZeroMemory(&m_Desc, sizeof(m_Desc));
  676. return S_OK;
  677. }
  678. // Main logic for translating an LLVM type and associated
  679. // annotations into a D3D shader reflection type.
  680. HRESULT CShaderReflectionType::Initialize(
  681. DxilModule &M,
  682. llvm::Type *inType,
  683. DxilFieldAnnotation &typeAnnotation,
  684. unsigned int baseOffset,
  685. std::vector<std::unique_ptr<CShaderReflectionType>>& allTypes,
  686. bool isCBuffer)
  687. {
  688. DXASSERT_NOMSG(inType);
  689. // Set a bunch of fields to default values, to avoid duplication.
  690. m_Desc.Rows = 0;
  691. m_Desc.Columns = 0;
  692. m_Desc.Elements = 0;
  693. m_Desc.Members = 0;
  694. m_SizeInCBuffer = 0;
  695. // Used for calculating size later
  696. unsigned cbRows = 1;
  697. unsigned cbCols = 1;
  698. unsigned cbCompSize = 4; // or 8 for 64-bit types.
  699. unsigned cbRowStride = 16; // or 32 if 64-bit and cols > 2.
  700. if (isCBuffer) {
  701. // Extract offset relative to parent.
  702. // Note: the `baseOffset` is used in the case where the type in
  703. // question is a field in a constant buffer, since then both the
  704. // field and the variable store the same offset information, and
  705. // we need to zero out the value in the type to avoid the user
  706. // of the reflection interface seeing 2x the correct value.
  707. m_Desc.Offset = typeAnnotation.GetCBufferOffset() - baseOffset;
  708. } else {
  709. m_Desc.Offset = baseOffset;
  710. }
  711. // Arrays don't seem to be represented directly in the reflection
  712. // data, but only as the `Elements` field being non-zero.
  713. // We "unwrap" any array type here, and then proceed to look
  714. // at the element type.
  715. llvm::Type* type = inType;
  716. while(type->isArrayTy())
  717. {
  718. llvm::Type* elementType = type->getArrayElementType();
  719. // Note: At this point an HLSL matrix type may appear as an ordinary
  720. // array (not wrapped in a `struct`), so `dxilutil::IsHLSLMatrixType()`
  721. // is not sufficient. Instead we need to check the field annotation.
  722. //
  723. // We might have an array of matrices, though, so we only exit if
  724. // the field annotation says we have a matrix, and we've bottomed
  725. // out and the element type isn't itself an array.
  726. //
  727. // For libraries however, we may have unlowered matrix types, so
  728. // we have to check for HLMatrixType so we don't skip counting the
  729. // inner-most matrix array size.
  730. if(typeAnnotation.HasMatrixAnnotation() && !elementType->isArrayTy() &&
  731. !HLMatrixType::isa(elementType))
  732. {
  733. break;
  734. }
  735. // Non-array types should have `Elements` be zero, so as soon as we
  736. // find that we have our first real array (not a matrix), we initialize `Elements`
  737. if(!m_Desc.Elements) m_Desc.Elements = 1;
  738. // It isn't clear what is the desired behavior for multi-dimensional arrays,
  739. // but for now we do the expedient thing of multiplying out all their
  740. // dimensions.
  741. m_Desc.Elements *= type->getArrayNumElements();
  742. type = elementType;
  743. }
  744. // Default to a scalar type, just to avoid some duplication later.
  745. m_Desc.Class = D3D_SVC_SCALAR;
  746. // Look at the annotation to try to determine the basic type of value.
  747. //
  748. // Note that DXIL supports some types that don't currently have equivalents
  749. // in the reflection interface, so we try to muddle through here.
  750. bool bMinPrec = M.GetUseMinPrecision();
  751. D3D_SHADER_VARIABLE_TYPE componentType = D3D_SVT_VOID;
  752. switch(typeAnnotation.GetCompType().GetKind())
  753. {
  754. case hlsl::DXIL::ComponentType::Invalid:
  755. break;
  756. case hlsl::DXIL::ComponentType::I1:
  757. componentType = D3D_SVT_BOOL;
  758. m_Name = "bool";
  759. break;
  760. case hlsl::DXIL::ComponentType::I16:
  761. componentType = D3D_SVT_MIN16INT;
  762. if (bMinPrec) {
  763. m_Name = "min16int";
  764. } else {
  765. m_Name = "int16_t";
  766. cbCompSize = 2;
  767. }
  768. break;
  769. case hlsl::DXIL::ComponentType::U16:
  770. componentType = D3D_SVT_MIN16UINT;
  771. if (bMinPrec) {
  772. m_Name = "min16uint";
  773. } else {
  774. m_Name = "uint16_t";
  775. cbCompSize = 2;
  776. }
  777. break;
  778. case hlsl::DXIL::ComponentType::I64:
  779. cbCompSize = 8;
  780. #ifdef DBG
  781. OutputDebugStringA("DxilContainerReflection.cpp: warning: component of type 'I64' being reflected as if 'I32'\n");
  782. #endif
  783. case hlsl::DXIL::ComponentType::I32:
  784. componentType = D3D_SVT_INT;
  785. m_Name = "int";
  786. break;
  787. case hlsl::DXIL::ComponentType::U64:
  788. cbCompSize = 8;
  789. #ifdef DBG
  790. OutputDebugStringA("DxilContainerReflection.cpp: warning: component of type 'U64' being reflected as if 'U32'\n");
  791. #endif
  792. case hlsl::DXIL::ComponentType::U32:
  793. componentType = D3D_SVT_UINT;
  794. m_Name = "uint";
  795. break;
  796. case hlsl::DXIL::ComponentType::F16:
  797. case hlsl::DXIL::ComponentType::SNormF16:
  798. case hlsl::DXIL::ComponentType::UNormF16:
  799. componentType = D3D_SVT_MIN16FLOAT;
  800. if (bMinPrec) {
  801. m_Name = "min16float";
  802. } else {
  803. m_Name = "float16_t";
  804. cbCompSize = 2;
  805. }
  806. break;
  807. case hlsl::DXIL::ComponentType::F32:
  808. case hlsl::DXIL::ComponentType::SNormF32:
  809. case hlsl::DXIL::ComponentType::UNormF32:
  810. componentType = D3D_SVT_FLOAT;
  811. m_Name = "float";
  812. break;
  813. case hlsl::DXIL::ComponentType::F64:
  814. case hlsl::DXIL::ComponentType::SNormF64:
  815. case hlsl::DXIL::ComponentType::UNormF64:
  816. cbCompSize = 8;
  817. componentType = D3D_SVT_DOUBLE;
  818. m_Name = "double";
  819. break;
  820. default:
  821. #ifdef DBG
  822. OutputDebugStringA("DxilContainerReflection.cpp: error: unknown component type\n");
  823. #endif
  824. break;
  825. }
  826. m_Desc.Type = componentType;
  827. // A matrix type is encoded as a vector type, plus annotations, so we
  828. // need to check for this case before other vector cases.
  829. if(typeAnnotation.HasMatrixAnnotation())
  830. {
  831. // We can extract the details from the annotation.
  832. DxilMatrixAnnotation const& matrixAnnotation = typeAnnotation.GetMatrixAnnotation();
  833. switch(matrixAnnotation.Orientation)
  834. {
  835. default:
  836. #ifdef DBG
  837. OutputDebugStringA("DxilContainerReflection.cpp: error: unknown matrix orientation\n");
  838. #endif
  839. // Note: column-major layout is the default
  840. case hlsl::MatrixOrientation::Undefined:
  841. case hlsl::MatrixOrientation::ColumnMajor:
  842. m_Desc.Class = D3D_SVC_MATRIX_COLUMNS;
  843. break;
  844. case hlsl::MatrixOrientation::RowMajor:
  845. m_Desc.Class = D3D_SVC_MATRIX_ROWS;
  846. break;
  847. }
  848. m_Desc.Rows = matrixAnnotation.Rows;
  849. m_Desc.Columns = matrixAnnotation.Cols;
  850. m_Name += std::to_string(matrixAnnotation.Rows) + "x" + std::to_string(matrixAnnotation.Cols);
  851. cbRows = m_Desc.Rows;
  852. cbCols = m_Desc.Columns;
  853. if (m_Desc.Class == D3D_SVC_MATRIX_COLUMNS) {
  854. std::swap(cbRows, cbCols);
  855. }
  856. }
  857. else if( type->isVectorTy() )
  858. {
  859. // We assume that LLVM vectors either represent matrices (handled above)
  860. // or HLSL vectors.
  861. //
  862. // Note: the reflection interface encodes an N-vector as if it had 1 row
  863. // and N columns.
  864. m_Desc.Class = D3D_SVC_VECTOR;
  865. m_Desc.Rows = 1;
  866. m_Desc.Columns = type->getVectorNumElements();
  867. m_Name += std::to_string(type->getVectorNumElements());
  868. cbRows = m_Desc.Rows;
  869. cbCols = m_Desc.Columns;
  870. }
  871. else if( type->isStructTy() )
  872. {
  873. // A struct type might be an ordinary user-defined `struct`,
  874. // or one of the builtin in HLSL "object" types.
  875. StructType *structType = cast<StructType>(type);
  876. const StructLayout *structLayout = isCBuffer ? nullptr :
  877. M.GetModule()->getDataLayout().getStructLayout(structType);
  878. // We use our function to try to detect an object type
  879. // based on its name.
  880. if(TryToDetectObjectType(structType, &m_Desc.Type))
  881. {
  882. m_Desc.Class = D3D_SVC_OBJECT;
  883. }
  884. else
  885. {
  886. // Otherwise we have a struct and need to recurse on its fields.
  887. m_Desc.Class = D3D_SVC_STRUCT;
  888. m_Desc.Rows = 1;
  889. // Try to "clean" the type name for use in reflection data
  890. llvm::StringRef name = structType->getName();
  891. name = name.ltrim("dx.alignment.legacy.");
  892. name = name.ltrim("struct.");
  893. m_Name = name;
  894. // Fields may have annotations, and we need to look at these
  895. // in order to decode their types properly.
  896. DxilTypeSystem &typeSys = M.GetTypeSystem();
  897. DxilStructAnnotation *structAnnotation = typeSys.GetStructAnnotation(structType);
  898. // There is no annotation for empty structs
  899. unsigned int fieldCount = 0;
  900. if (structAnnotation)
  901. fieldCount = type->getStructNumElements();
  902. // The DXBC reflection info computes `Columns` for a
  903. // `struct` type from the fields (see below)
  904. UINT columnCounter = 0;
  905. CShaderReflectionType *fieldReflectionType = nullptr;
  906. for(unsigned int ff = 0; ff < fieldCount; ++ff)
  907. {
  908. DxilFieldAnnotation& fieldAnnotation = structAnnotation->GetFieldAnnotation(ff);
  909. llvm::Type* fieldType = structType->getStructElementType(ff);
  910. // Skip fields with object types, since these are not part of constant buffers,
  911. // and are not allowed in other buffer types.
  912. if( IsObjectType(fieldType) )
  913. {
  914. continue;
  915. }
  916. fieldReflectionType = new CShaderReflectionType();
  917. allTypes.push_back(std::unique_ptr<CShaderReflectionType>(fieldReflectionType));
  918. unsigned int elementOffset = structLayout ? (unsigned int)structLayout->getElementOffset(ff) : 0;
  919. fieldReflectionType->Initialize(M, fieldType, fieldAnnotation, elementOffset, allTypes, isCBuffer);
  920. m_MemberTypes.push_back(fieldReflectionType);
  921. m_MemberNames.push_back(fieldAnnotation.GetFieldName().c_str());
  922. // Effectively, we want to add one to `Columns` for every scalar nested recursively
  923. // inside this `struct` type (ignoring objects, which we filtered above). We should
  924. // be able to compute this as the product of the `Columns`, `Rows` and `Elements`
  925. // of each field, with the caveat that some of these may be zero, but shoud be
  926. // treated as one.
  927. columnCounter +=
  928. (fieldReflectionType->m_Desc.Columns ? fieldReflectionType->m_Desc.Columns : 1)
  929. * (fieldReflectionType->m_Desc.Rows ? fieldReflectionType->m_Desc.Rows : 1)
  930. * (fieldReflectionType->m_Desc.Elements ? fieldReflectionType->m_Desc.Elements : 1);
  931. }
  932. m_Desc.Columns = columnCounter;
  933. if (fieldReflectionType) {
  934. // Set our size based on the last fields offset + size:
  935. m_SizeInCBuffer = fieldReflectionType->m_Desc.Offset + fieldReflectionType->m_SizeInCBuffer;
  936. if (m_Desc.Elements > 1) {
  937. unsigned alignedSize = ((m_SizeInCBuffer + 15) & ~0xF);
  938. m_SizeInCBuffer += (m_Desc.Elements - 1) * alignedSize;
  939. }
  940. }
  941. // Because we might have skipped fields during enumeration,
  942. // the `Members` count in the description might not be the same
  943. // as the field count of the original LLVM type.
  944. m_Desc.Members = m_MemberTypes.size();
  945. }
  946. }
  947. else if( type->isPointerTy() )
  948. {
  949. #ifdef DBG
  950. OutputDebugStringA("DxilContainerReflection.cpp: error: cannot reflect pointer type\n");
  951. #endif
  952. }
  953. else if( type->isVoidTy() )
  954. {
  955. // Name for `void` wasn't handle in the component-type `switch` above
  956. m_Name = "void";
  957. m_Desc.Class = D3D_SVC_SCALAR;
  958. m_Desc.Rows = 1;
  959. m_Desc.Columns = 1;
  960. }
  961. else
  962. {
  963. // Assume we have a scalar at this point.
  964. m_Desc.Class = D3D_SVC_SCALAR;
  965. m_Desc.Rows = 1;
  966. m_Desc.Columns = 1;
  967. // Special-case naming
  968. switch(m_Desc.Type)
  969. {
  970. default:
  971. break;
  972. case D3D_SVT_UINT:
  973. // Scalar `uint` gets reflected as `dword`, while vectors/matrices use `uint`...
  974. m_Name = "dword";
  975. break;
  976. }
  977. cbRows = 1;
  978. cbCols = 1;
  979. }
  980. // TODO: are there other cases to be handled?
  981. // Compute our cbuffer size for member reflection
  982. switch (m_Desc.Class) {
  983. case D3D_SVC_SCALAR:
  984. case D3D_SVC_MATRIX_COLUMNS:
  985. case D3D_SVC_MATRIX_ROWS:
  986. case D3D_SVC_VECTOR:
  987. if (m_Desc.Elements > 1)
  988. cbRows = cbRows * m_Desc.Elements;
  989. if (cbCompSize > 4 && cbCols > 2)
  990. cbRowStride = 32;
  991. m_SizeInCBuffer = cbRowStride * (cbRows - 1) + cbCompSize * cbCols;
  992. break;
  993. }
  994. m_Desc.Name = m_Name.c_str();
  995. return S_OK;
  996. }
  997. void CShaderReflectionConstantBuffer::Initialize(
  998. DxilModule &M,
  999. DxilCBuffer &CB,
  1000. std::vector<std::unique_ptr<CShaderReflectionType>>& allTypes,
  1001. bool bUsageInMetadata) {
  1002. ZeroMemory(&m_Desc, sizeof(m_Desc));
  1003. m_Desc.Name = CB.GetGlobalName().c_str();
  1004. m_Desc.Size = CB.GetSize();
  1005. m_Desc.Size = (m_Desc.Size + 0x0f) & ~(0x0f); // Round up to 16 bytes for reflection.
  1006. m_Desc.Type = D3D_CT_CBUFFER;
  1007. m_Desc.uFlags = 0;
  1008. // For ConstantBuffer<> buf[2], the array size is in Resource binding count
  1009. // part.
  1010. Type *Ty = dxilutil::StripArrayTypes(
  1011. CB.GetGlobalSymbol()->getType()->getPointerElementType());
  1012. DxilTypeSystem &typeSys = M.GetTypeSystem();
  1013. StructType *ST = cast<StructType>(Ty);
  1014. DxilStructAnnotation *annotation =
  1015. typeSys.GetStructAnnotation(cast<StructType>(ST));
  1016. // Dxil from dxbc doesn't have annotation.
  1017. if (!annotation)
  1018. return;
  1019. m_Desc.Variables = ST->getNumContainedTypes();
  1020. if (CB.GetRangeSize() > 1) {
  1021. DXASSERT(m_Desc.Variables == 1, "otherwise, assumption is wrong");
  1022. }
  1023. // If only one member, it's used if it's here.
  1024. bool bAllUsed = ST->getNumContainedTypes() < 2;
  1025. bAllUsed |= !bUsageInMetadata; // Will update in SetCBufferUsage.
  1026. for (unsigned i = 0; i < ST->getNumContainedTypes(); ++i) {
  1027. DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(i);
  1028. D3D12_SHADER_VARIABLE_DESC VarDesc;
  1029. ZeroMemory(&VarDesc, sizeof(VarDesc));
  1030. VarDesc.uFlags = (bAllUsed || fieldAnnotation.IsCBVarUsed()) ? D3D_SVF_USED : 0;
  1031. CShaderReflectionVariable Var;
  1032. //Create reflection type.
  1033. CShaderReflectionType *pVarType = new CShaderReflectionType();
  1034. allTypes.push_back(std::unique_ptr<CShaderReflectionType>(pVarType));
  1035. pVarType->Initialize(M, ST->getContainedType(i), fieldAnnotation, fieldAnnotation.GetCBufferOffset(), allTypes, true);
  1036. // Replicate fxc bug, where Elements == 1 for inner struct of CB array, instead of 0.
  1037. if (CB.GetRangeSize() > 1) {
  1038. DXASSERT(pVarType->m_Desc.Elements == 0, "otherwise, assumption is wrong");
  1039. pVarType->m_Desc.Elements = 1;
  1040. }
  1041. BYTE *pDefaultValue = nullptr;
  1042. VarDesc.Name = fieldAnnotation.GetFieldName().c_str();
  1043. VarDesc.StartOffset = fieldAnnotation.GetCBufferOffset();
  1044. VarDesc.Size = pVarType->GetCBufferSize();
  1045. Var.Initialize(this, &VarDesc, pVarType, pDefaultValue);
  1046. m_Variables.push_back(Var);
  1047. }
  1048. }
  1049. static unsigned CalcTypeSize(Type *Ty) {
  1050. // Assume aligned values.
  1051. if (Ty->isIntegerTy() || Ty->isFloatTy()) {
  1052. return Ty->getPrimitiveSizeInBits() / 8;
  1053. }
  1054. else if (Ty->isArrayTy()) {
  1055. ArrayType *AT = dyn_cast<ArrayType>(Ty);
  1056. return AT->getNumElements() * CalcTypeSize(AT->getArrayElementType());
  1057. }
  1058. else if (Ty->isStructTy()) {
  1059. StructType *ST = dyn_cast<StructType>(Ty);
  1060. unsigned i = 0, c = ST->getStructNumElements();
  1061. unsigned result = 0;
  1062. for (; i < c; ++i) {
  1063. result += CalcTypeSize(ST->getStructElementType(i));
  1064. // TODO: align!
  1065. }
  1066. return result;
  1067. }
  1068. else if (Ty->isVectorTy()) {
  1069. VectorType *VT = dyn_cast<VectorType>(Ty);
  1070. return VT->getVectorNumElements() * CalcTypeSize(VT->getVectorElementType());
  1071. }
  1072. else {
  1073. DXASSERT_NOMSG(false);
  1074. return 0;
  1075. }
  1076. }
  1077. static unsigned CalcResTypeSize(DxilModule &M, DxilResource &R) {
  1078. UNREFERENCED_PARAMETER(M);
  1079. Type *Ty = R.GetGlobalSymbol()->getType()->getPointerElementType();
  1080. if (R.IsStructuredBuffer()) {
  1081. Ty = dxilutil::StripArrayTypes(Ty);
  1082. }
  1083. return CalcTypeSize(Ty);
  1084. }
  1085. void CShaderReflectionConstantBuffer::InitializeStructuredBuffer(
  1086. DxilModule &M,
  1087. DxilResource &R,
  1088. std::vector<std::unique_ptr<CShaderReflectionType>>& allTypes) {
  1089. ZeroMemory(&m_Desc, sizeof(m_Desc));
  1090. m_ReflectionName = R.GetGlobalName();
  1091. m_Desc.Type = D3D11_CT_RESOURCE_BIND_INFO;
  1092. m_Desc.uFlags = 0;
  1093. m_Desc.Variables = 1;
  1094. D3D12_SHADER_VARIABLE_DESC VarDesc;
  1095. ZeroMemory(&VarDesc, sizeof(VarDesc));
  1096. VarDesc.Name = "$Element";
  1097. VarDesc.Size = CalcResTypeSize(M, R);
  1098. VarDesc.StartTexture = UINT_MAX;
  1099. VarDesc.StartSampler = UINT_MAX;
  1100. VarDesc.uFlags |= D3D_SVF_USED;
  1101. CShaderReflectionVariable Var;
  1102. // First type is an empty type: returned if no annotation available.
  1103. CShaderReflectionType *pVarType = allTypes[0].get();
  1104. // Create reflection type, if we have the necessary annotation info
  1105. // Extract the `struct` that wraps element type of the buffer resource
  1106. Type *Ty = R.GetGlobalSymbol()->getType()->getPointerElementType();
  1107. SmallVector<unsigned, 4> arrayDims;
  1108. Ty = dxilutil::StripArrayTypes(Ty, &arrayDims);
  1109. for (unsigned i = 0; i < arrayDims.size(); ++i) {
  1110. m_ReflectionName += "[0]";
  1111. }
  1112. m_Desc.Name = m_ReflectionName.c_str();
  1113. StructType *ST = cast<StructType>(Ty);
  1114. // Look up struct type annotation on the element type
  1115. DxilTypeSystem &typeSys = M.GetTypeSystem();
  1116. DxilStructAnnotation *annotation =
  1117. typeSys.GetStructAnnotation(cast<StructType>(ST));
  1118. // Dxil from dxbc doesn't have annotation.
  1119. if(annotation)
  1120. {
  1121. // Actually create the reflection type.
  1122. pVarType = new CShaderReflectionType();
  1123. allTypes.push_back(std::unique_ptr<CShaderReflectionType>(pVarType));
  1124. // The user-visible element type is the first field of the wrapepr `struct`
  1125. Type *fieldType = ST->getElementType(0);
  1126. DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(0);
  1127. pVarType->Initialize(M, fieldType, fieldAnnotation, 0, allTypes, false);
  1128. }
  1129. BYTE *pDefaultValue = nullptr;
  1130. Var.Initialize(this, &VarDesc, pVarType, pDefaultValue);
  1131. m_Variables.push_back(Var);
  1132. m_Desc.Size = VarDesc.Size;
  1133. }
  1134. HRESULT CShaderReflectionConstantBuffer::GetDesc(D3D12_SHADER_BUFFER_DESC *pDesc) {
  1135. if (!pDesc)
  1136. return E_POINTER;
  1137. memcpy(pDesc, &m_Desc, sizeof(m_Desc));
  1138. return S_OK;
  1139. }
  1140. ID3D12ShaderReflectionVariable *
  1141. CShaderReflectionConstantBuffer::GetVariableByIndex(UINT Index) {
  1142. if (Index >= m_Variables.size()) {
  1143. return &g_InvalidSRVariable;
  1144. }
  1145. return &m_Variables[Index];
  1146. }
  1147. ID3D12ShaderReflectionVariable *
  1148. CShaderReflectionConstantBuffer::GetVariableByName(LPCSTR Name) {
  1149. UINT index;
  1150. if (NULL == Name) {
  1151. return &g_InvalidSRVariable;
  1152. }
  1153. for (index = 0; index < m_Variables.size(); ++index) {
  1154. if (0 == strcmp(m_Variables[index].GetName(), Name)) {
  1155. return &m_Variables[index];
  1156. }
  1157. }
  1158. return &g_InvalidSRVariable;
  1159. }
  1160. ///////////////////////////////////////////////////////////////////////////////
  1161. // DxilShaderReflection implementation. //
  1162. static DxilResource *DxilResourceFromBase(DxilResourceBase *RB) {
  1163. DxilResourceBase::Class C = RB->GetClass();
  1164. if (C == DXIL::ResourceClass::UAV || C == DXIL::ResourceClass::SRV)
  1165. return (DxilResource *)RB;
  1166. return nullptr;
  1167. }
  1168. static D3D_SHADER_INPUT_TYPE ResourceToShaderInputType(DxilResourceBase *RB) {
  1169. DxilResource *R = DxilResourceFromBase(RB);
  1170. bool isUAV = RB->GetClass() == DxilResourceBase::Class::UAV;
  1171. switch (RB->GetKind()) {
  1172. case DxilResource::Kind::CBuffer:
  1173. return D3D_SIT_CBUFFER;
  1174. case DxilResource::Kind::Sampler:
  1175. return D3D_SIT_SAMPLER;
  1176. case DxilResource::Kind::RawBuffer:
  1177. return isUAV ? D3D_SIT_UAV_RWBYTEADDRESS : D3D_SIT_BYTEADDRESS;
  1178. case DxilResource::Kind::StructuredBuffer:
  1179. case DxilResource::Kind::StructuredBufferWithCounter: {
  1180. if (!isUAV) return D3D_SIT_STRUCTURED;
  1181. // TODO: D3D_SIT_UAV_CONSUME_STRUCTURED, D3D_SIT_UAV_APPEND_STRUCTURED?
  1182. if (R->HasCounter()) return D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER;
  1183. return D3D_SIT_UAV_RWSTRUCTURED;
  1184. }
  1185. case DxilResource::Kind::TBuffer:
  1186. case DxilResource::Kind::TypedBuffer:
  1187. case DxilResource::Kind::Texture1D:
  1188. case DxilResource::Kind::Texture1DArray:
  1189. case DxilResource::Kind::Texture2D:
  1190. case DxilResource::Kind::Texture2DArray:
  1191. case DxilResource::Kind::Texture2DMS:
  1192. case DxilResource::Kind::Texture2DMSArray:
  1193. case DxilResource::Kind::Texture3D:
  1194. case DxilResource::Kind::TextureCube:
  1195. case DxilResource::Kind::TextureCubeArray:
  1196. return isUAV ? D3D_SIT_UAV_RWTYPED : D3D_SIT_TEXTURE;
  1197. case DxilResource::Kind::RTAccelerationStructure:
  1198. return (D3D_SHADER_INPUT_TYPE)(D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER + 1); // D3D_SIT_RTACCELERATIONSTRUCTURE
  1199. case DxilResource::Kind::FeedbackTexture2D:
  1200. case DxilResource::Kind::FeedbackTexture2DArray:
  1201. return (D3D_SHADER_INPUT_TYPE)(D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER + 2); // D3D_SIT_UAV_FEEDBACKTEXTURE
  1202. default:
  1203. return (D3D_SHADER_INPUT_TYPE)-1;
  1204. }
  1205. }
  1206. static D3D_RESOURCE_RETURN_TYPE ResourceToReturnType(DxilResourceBase *RB) {
  1207. DxilResource *R = DxilResourceFromBase(RB);
  1208. if (R != nullptr) {
  1209. CompType CT = R->GetCompType();
  1210. if (CT.GetKind() == CompType::Kind::F64) return D3D_RETURN_TYPE_DOUBLE;
  1211. if (CT.IsUNorm()) return D3D_RETURN_TYPE_UNORM;
  1212. if (CT.IsSNorm()) return D3D_RETURN_TYPE_SNORM;
  1213. if (CT.IsSIntTy()) return D3D_RETURN_TYPE_SINT;
  1214. if (CT.IsUIntTy()) return D3D_RETURN_TYPE_UINT;
  1215. if (CT.IsFloatTy()) return D3D_RETURN_TYPE_FLOAT;
  1216. // D3D_RETURN_TYPE_CONTINUED: Return type is a multiple-dword type, such as a
  1217. // double or uint64, and the component is continued from the previous
  1218. // component that was declared. The first component represents the lower bits.
  1219. return D3D_RETURN_TYPE_MIXED;
  1220. }
  1221. return (D3D_RESOURCE_RETURN_TYPE)0;
  1222. }
  1223. static D3D_SRV_DIMENSION ResourceToDimension(DxilResourceBase *RB) {
  1224. switch (RB->GetKind()) {
  1225. case DxilResource::Kind::StructuredBuffer:
  1226. case DxilResource::Kind::TypedBuffer:
  1227. case DxilResource::Kind::TBuffer:
  1228. return D3D_SRV_DIMENSION_BUFFER;
  1229. case DxilResource::Kind::Texture1D:
  1230. return D3D_SRV_DIMENSION_TEXTURE1D;
  1231. case DxilResource::Kind::Texture1DArray:
  1232. return D3D_SRV_DIMENSION_TEXTURE1DARRAY;
  1233. case DxilResource::Kind::Texture2D:
  1234. case DxilResource::Kind::FeedbackTexture2D:
  1235. return D3D_SRV_DIMENSION_TEXTURE2D;
  1236. case DxilResource::Kind::Texture2DArray:
  1237. case DxilResource::Kind::FeedbackTexture2DArray:
  1238. return D3D_SRV_DIMENSION_TEXTURE2DARRAY;
  1239. case DxilResource::Kind::Texture2DMS:
  1240. return D3D_SRV_DIMENSION_TEXTURE2DMS;
  1241. case DxilResource::Kind::Texture2DMSArray:
  1242. return D3D_SRV_DIMENSION_TEXTURE2DMSARRAY;
  1243. case DxilResource::Kind::Texture3D:
  1244. return D3D_SRV_DIMENSION_TEXTURE3D;
  1245. case DxilResource::Kind::TextureCube:
  1246. return D3D_SRV_DIMENSION_TEXTURECUBE;
  1247. case DxilResource::Kind::TextureCubeArray:
  1248. return D3D_SRV_DIMENSION_TEXTURECUBEARRAY;
  1249. case DxilResource::Kind::RawBuffer:
  1250. return D3D11_SRV_DIMENSION_BUFFER; // D3D11_SRV_DIMENSION_BUFFEREX?
  1251. default:
  1252. return D3D_SRV_DIMENSION_UNKNOWN;
  1253. }
  1254. }
  1255. static UINT ResourceToFlags(DxilResourceBase *RB) {
  1256. UINT result = 0;
  1257. DxilResource *R = DxilResourceFromBase(RB);
  1258. if (R != nullptr &&
  1259. (R->IsAnyTexture() || R->GetKind() == DXIL::ResourceKind::TypedBuffer)) {
  1260. llvm::Type *RetTy = R->GetRetType();
  1261. if (VectorType *VT = dyn_cast<VectorType>(RetTy)) {
  1262. unsigned vecSize = VT->getNumElements();
  1263. switch (vecSize) {
  1264. case 4:
  1265. result |= D3D_SIF_TEXTURE_COMPONENTS;
  1266. break;
  1267. case 3:
  1268. result |= D3D_SIF_TEXTURE_COMPONENT_1;
  1269. break;
  1270. case 2:
  1271. result |= D3D_SIF_TEXTURE_COMPONENT_0;
  1272. break;
  1273. }
  1274. }
  1275. }
  1276. // D3D_SIF_USERPACKED
  1277. if (RB->GetClass() == DXIL::ResourceClass::Sampler) {
  1278. DxilSampler *S = static_cast<DxilSampler *>(RB);
  1279. if (S->GetSamplerKind() == DXIL::SamplerKind::Comparison)
  1280. result |= D3D_SIF_COMPARISON_SAMPLER;
  1281. }
  1282. return result;
  1283. }
  1284. void DxilModuleReflection::CreateReflectionObjectForResource(DxilResourceBase *RB) {
  1285. DxilResourceBase::Class C = RB->GetClass();
  1286. DxilResource *R =
  1287. (C == DXIL::ResourceClass::UAV || C == DXIL::ResourceClass::SRV)
  1288. ? (DxilResource *)RB
  1289. : nullptr;
  1290. D3D12_SHADER_INPUT_BIND_DESC inputBind;
  1291. ZeroMemory(&inputBind, sizeof(inputBind));
  1292. inputBind.BindCount = RB->GetRangeSize();
  1293. // FXC Bug: For Unbounded range, CBuffers say bind count is UINT_MAX, but all others report 0!
  1294. if (RB->GetRangeSize() == UINT_MAX && C != DXIL::ResourceClass::CBuffer)
  1295. inputBind.BindCount = 0;
  1296. inputBind.BindPoint = RB->GetLowerBound();
  1297. inputBind.Dimension = ResourceToDimension(RB);
  1298. inputBind.Name = RB->GetGlobalName().c_str();
  1299. inputBind.Type = ResourceToShaderInputType(RB);
  1300. if (R == nullptr) {
  1301. inputBind.NumSamples = 0;
  1302. }
  1303. else {
  1304. inputBind.NumSamples = R->GetSampleCount();
  1305. if (inputBind.NumSamples == 0) {
  1306. if (R->IsStructuredBuffer()) {
  1307. inputBind.NumSamples = CalcResTypeSize(*m_pDxilModule, *R);
  1308. }
  1309. else if (!R->IsRawBuffer()) {
  1310. inputBind.NumSamples = 0xFFFFFFFF;
  1311. }
  1312. }
  1313. }
  1314. inputBind.ReturnType = ResourceToReturnType(RB);
  1315. inputBind.Space = RB->GetSpaceID();
  1316. inputBind.uFlags = ResourceToFlags(RB);
  1317. inputBind.uID = RB->GetID();
  1318. m_Resources.push_back(inputBind);
  1319. }
  1320. // Find the imm offset part from a value.
  1321. // It must exist unless offset is 0.
  1322. static unsigned GetCBOffset(Value *V) {
  1323. if (ConstantInt *Imm = dyn_cast<ConstantInt>(V))
  1324. return Imm->getLimitedValue();
  1325. else if (UnaryInstruction *UI = dyn_cast<UnaryInstruction>(V)) {
  1326. return 0;
  1327. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V)) {
  1328. switch (BO->getOpcode()) {
  1329. case Instruction::Add: {
  1330. unsigned left = GetCBOffset(BO->getOperand(0));
  1331. unsigned right = GetCBOffset(BO->getOperand(1));
  1332. return left + right;
  1333. } break;
  1334. case Instruction::Or: {
  1335. unsigned left = GetCBOffset(BO->getOperand(0));
  1336. unsigned right = GetCBOffset(BO->getOperand(1));
  1337. return left | right;
  1338. } break;
  1339. default:
  1340. return 0;
  1341. }
  1342. } else {
  1343. return 0;
  1344. }
  1345. }
  1346. static unsigned GetOffsetForCBExtractValue(ExtractValueInst *EV, bool bMinPrecision) {
  1347. DXASSERT(EV->getNumIndices() == 1, "otherwise, unexpected indices/type for extractvalue");
  1348. unsigned typeSize = 4;
  1349. unsigned bits = EV->getType()->getScalarSizeInBits();
  1350. if (bits == 64)
  1351. typeSize = 8;
  1352. else if (bits == 16 && !bMinPrecision)
  1353. typeSize = 2;
  1354. return (EV->getIndices().front() * typeSize);
  1355. }
  1356. static void CollectInPhiChain(PHINode *cbUser, std::vector<unsigned> &cbufUsage,
  1357. unsigned offset, std::unordered_set<Value *> &userSet,
  1358. bool bMinPrecision) {
  1359. if (userSet.count(cbUser) > 0)
  1360. return;
  1361. userSet.insert(cbUser);
  1362. for (User *cbU : cbUser->users()) {
  1363. if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(cbU)) {
  1364. cbufUsage.emplace_back(offset + GetOffsetForCBExtractValue(EV, bMinPrecision));
  1365. } else {
  1366. PHINode *phi = cast<PHINode>(cbU);
  1367. CollectInPhiChain(phi, cbufUsage, offset, userSet, bMinPrecision);
  1368. }
  1369. }
  1370. }
  1371. static void CollectCBufUsage(Value *cbHandle,
  1372. std::vector<unsigned> &cbufUsage,
  1373. bool bMinPrecision) {
  1374. for (User *U : cbHandle->users()) {
  1375. CallInst *CI = cast<CallInst>(U);
  1376. ConstantInt *opcodeV =
  1377. cast<ConstantInt>(CI->getArgOperand(DXIL::OperandIndex::kOpcodeIdx));
  1378. DXIL::OpCode opcode = static_cast<DXIL::OpCode>(opcodeV->getLimitedValue());
  1379. if (opcode == DXIL::OpCode::CBufferLoadLegacy) {
  1380. DxilInst_CBufferLoadLegacy cbload(CI);
  1381. Value *resIndex = cbload.get_regIndex();
  1382. unsigned offset = GetCBOffset(resIndex);
  1383. // 16 bytes align.
  1384. offset <<= 4;
  1385. for (User *cbU : U->users()) {
  1386. if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(cbU)) {
  1387. cbufUsage.emplace_back(offset + GetOffsetForCBExtractValue(EV, bMinPrecision));
  1388. } else {
  1389. PHINode *phi = cast<PHINode>(cbU);
  1390. std::unordered_set<Value *> userSet;
  1391. CollectInPhiChain(phi, cbufUsage, offset, userSet, bMinPrecision);
  1392. }
  1393. }
  1394. } else if (opcode == DXIL::OpCode::CBufferLoad) {
  1395. DxilInst_CBufferLoad cbload(CI);
  1396. Value *byteOffset = cbload.get_byteOffset();
  1397. unsigned offset = GetCBOffset(byteOffset);
  1398. cbufUsage.emplace_back(offset);
  1399. } else if (opcode == DXIL::OpCode::AnnotateHandle) {
  1400. DxilInst_AnnotateHandle annotateHandle(CI);
  1401. Value *annotatedHandle = annotateHandle.get_res();
  1402. CollectCBufUsage(annotatedHandle, cbufUsage, bMinPrecision);
  1403. } else {
  1404. //
  1405. DXASSERT(0, "invalid opcode");
  1406. }
  1407. }
  1408. }
  1409. static void SetCBufVarUsage(CShaderReflectionConstantBuffer &cb,
  1410. std::vector<unsigned> &usage) {
  1411. D3D12_SHADER_BUFFER_DESC Desc;
  1412. if (FAILED(cb.GetDesc(&Desc)))
  1413. return;
  1414. unsigned size = Desc.Variables;
  1415. std::sort(usage.begin(), usage.end());
  1416. for (unsigned i = 0; i < size; i++) {
  1417. ID3D12ShaderReflectionVariable *pVar = cb.GetVariableByIndex(i);
  1418. D3D12_SHADER_VARIABLE_DESC VarDesc;
  1419. if (FAILED(pVar->GetDesc(&VarDesc)))
  1420. continue;
  1421. if (!pVar)
  1422. continue;
  1423. unsigned begin = VarDesc.StartOffset;
  1424. unsigned end = begin + VarDesc.Size;
  1425. auto beginIt = std::find_if(usage.begin(), usage.end(),
  1426. [&](unsigned v) { return v >= begin; });
  1427. auto endIt = std::find_if(usage.begin(), usage.end(),
  1428. [&](unsigned v) { return v >= end; });
  1429. bool used = beginIt != endIt;
  1430. // Clear used.
  1431. if (!used) {
  1432. CShaderReflectionType *pVarType = (CShaderReflectionType *)pVar->GetType();
  1433. BYTE *pDefaultValue = nullptr;
  1434. VarDesc.uFlags &= ~D3D_SVF_USED;
  1435. CShaderReflectionVariable *pCVarDesc = (CShaderReflectionVariable*)pVar;
  1436. pCVarDesc->Initialize(&cb, &VarDesc, pVarType, pDefaultValue);
  1437. }
  1438. }
  1439. }
  1440. void DxilShaderReflection::SetCBufferUsage() {
  1441. hlsl::OP *hlslOP = m_pDxilModule->GetOP();
  1442. LLVMContext &Ctx = m_pDxilModule->GetCtx();
  1443. // Indexes >= cbuffer size from DxilModule are SRV or UAV structured buffers.
  1444. // We only collect usage for actual cbuffers, so don't go clearing usage on other buffers.
  1445. unsigned cbSize = std::min(m_CBs.size(), m_pDxilModule->GetCBuffers().size());
  1446. std::vector< std::vector<unsigned> > cbufUsage(cbSize);
  1447. Function *createHandle = hlslOP->GetOpFunc(DXIL::OpCode::CreateHandle, Type::getVoidTy(Ctx));
  1448. if (createHandle->user_empty()) {
  1449. createHandle->eraseFromParent();
  1450. return;
  1451. }
  1452. // Find all cb handles.
  1453. for (User *U : createHandle->users()) {
  1454. DxilInst_CreateHandle handle(cast<CallInst>(U));
  1455. Value *resClass = handle.get_resourceClass();
  1456. ConstantInt *immResClass = cast<ConstantInt>(resClass);
  1457. if (immResClass->getLimitedValue() == (unsigned)DXIL::ResourceClass::CBuffer) {
  1458. ConstantInt *cbID = cast<ConstantInt>(handle.get_rangeId());
  1459. CollectCBufUsage(U, cbufUsage[cbID->getLimitedValue()], m_pDxilModule->GetUseMinPrecision());
  1460. }
  1461. }
  1462. for (unsigned i=0;i<cbSize;i++) {
  1463. SetCBufVarUsage(*m_CBs[i], cbufUsage[i]);
  1464. }
  1465. }
  1466. void DxilModuleReflection::CreateReflectionObjects() {
  1467. DXASSERT_NOMSG(m_pDxilModule != nullptr);
  1468. {
  1469. // Add empty type for when no type info is available, instead of returning nullptr.
  1470. DXASSERT_NOMSG(m_Types.empty());
  1471. CShaderReflectionType *pEmptyType = new CShaderReflectionType();
  1472. m_Types.push_back(std::unique_ptr<CShaderReflectionType>(pEmptyType));
  1473. pEmptyType->InitializeEmpty();
  1474. }
  1475. // Create constant buffers, resources and signatures.
  1476. for (auto && cb : m_pDxilModule->GetCBuffers()) {
  1477. std::unique_ptr<CShaderReflectionConstantBuffer> rcb(new CShaderReflectionConstantBuffer());
  1478. rcb->Initialize(*m_pDxilModule, *(cb.get()), m_Types, m_bUsageInMetadata);
  1479. m_CBs.emplace_back(std::move(rcb));
  1480. }
  1481. // TODO: add tbuffers into m_CBs
  1482. for (auto && uav : m_pDxilModule->GetUAVs()) {
  1483. if (!DXIL::IsStructuredBuffer(uav->GetKind())) {
  1484. continue;
  1485. }
  1486. std::unique_ptr<CShaderReflectionConstantBuffer> rcb(new CShaderReflectionConstantBuffer());
  1487. rcb->InitializeStructuredBuffer(*m_pDxilModule, *(uav.get()), m_Types);
  1488. m_CBs.emplace_back(std::move(rcb));
  1489. }
  1490. for (auto && srv : m_pDxilModule->GetSRVs()) {
  1491. if (srv->GetKind() != DxilResource::Kind::StructuredBuffer) {
  1492. continue;
  1493. }
  1494. std::unique_ptr<CShaderReflectionConstantBuffer> rcb(new CShaderReflectionConstantBuffer());
  1495. rcb->InitializeStructuredBuffer(*m_pDxilModule, *(srv.get()), m_Types);
  1496. m_CBs.emplace_back(std::move(rcb));
  1497. }
  1498. // Populate all resources.
  1499. for (auto && cbRes : m_pDxilModule->GetCBuffers()) {
  1500. CreateReflectionObjectForResource(cbRes.get());
  1501. }
  1502. for (auto && samplerRes : m_pDxilModule->GetSamplers()) {
  1503. CreateReflectionObjectForResource(samplerRes.get());
  1504. }
  1505. for (auto && srvRes : m_pDxilModule->GetSRVs()) {
  1506. CreateReflectionObjectForResource(srvRes.get());
  1507. }
  1508. for (auto && uavRes : m_pDxilModule->GetUAVs()) {
  1509. CreateReflectionObjectForResource(uavRes.get());
  1510. }
  1511. }
  1512. static D3D_REGISTER_COMPONENT_TYPE CompTypeToRegisterComponentType(CompType CT) {
  1513. switch (CT.GetKind()) {
  1514. case DXIL::ComponentType::F16:
  1515. case DXIL::ComponentType::F32:
  1516. return D3D_REGISTER_COMPONENT_FLOAT32;
  1517. case DXIL::ComponentType::I1:
  1518. case DXIL::ComponentType::U16:
  1519. case DXIL::ComponentType::U32:
  1520. return D3D_REGISTER_COMPONENT_UINT32;
  1521. case DXIL::ComponentType::I16:
  1522. case DXIL::ComponentType::I32:
  1523. return D3D_REGISTER_COMPONENT_SINT32;
  1524. default:
  1525. return D3D_REGISTER_COMPONENT_UNKNOWN;
  1526. }
  1527. }
  1528. static D3D_MIN_PRECISION CompTypeToMinPrecision(CompType CT) {
  1529. switch (CT.GetKind()) {
  1530. case DXIL::ComponentType::F16:
  1531. return D3D_MIN_PRECISION_FLOAT_16;
  1532. case DXIL::ComponentType::I16:
  1533. return D3D_MIN_PRECISION_SINT_16;
  1534. case DXIL::ComponentType::U16:
  1535. return D3D_MIN_PRECISION_UINT_16;
  1536. default:
  1537. return D3D_MIN_PRECISION_DEFAULT;
  1538. }
  1539. }
  1540. D3D_NAME SemanticToSystemValueType(const Semantic *S, DXIL::TessellatorDomain domain) {
  1541. switch (S->GetKind()) {
  1542. case Semantic::Kind::ClipDistance:
  1543. return D3D_NAME_CLIP_DISTANCE;
  1544. case Semantic::Kind::Arbitrary:
  1545. return D3D_NAME_UNDEFINED;
  1546. case Semantic::Kind::VertexID:
  1547. return D3D_NAME_VERTEX_ID;
  1548. case Semantic::Kind::InstanceID:
  1549. return D3D_NAME_INSTANCE_ID;
  1550. case Semantic::Kind::Position:
  1551. return D3D_NAME_POSITION;
  1552. case Semantic::Kind::Coverage:
  1553. return D3D_NAME_COVERAGE;
  1554. case Semantic::Kind::InnerCoverage:
  1555. return D3D_NAME_INNER_COVERAGE;
  1556. case Semantic::Kind::PrimitiveID:
  1557. return D3D_NAME_PRIMITIVE_ID;
  1558. case Semantic::Kind::SampleIndex:
  1559. return D3D_NAME_SAMPLE_INDEX;
  1560. case Semantic::Kind::IsFrontFace:
  1561. return D3D_NAME_IS_FRONT_FACE;
  1562. case Semantic::Kind::RenderTargetArrayIndex:
  1563. return D3D_NAME_RENDER_TARGET_ARRAY_INDEX;
  1564. case Semantic::Kind::ViewPortArrayIndex:
  1565. return D3D_NAME_VIEWPORT_ARRAY_INDEX;
  1566. case Semantic::Kind::CullDistance:
  1567. return D3D_NAME_CULL_DISTANCE;
  1568. case Semantic::Kind::Target:
  1569. return D3D_NAME_TARGET;
  1570. case Semantic::Kind::Depth:
  1571. return D3D_NAME_DEPTH;
  1572. case Semantic::Kind::DepthLessEqual:
  1573. return D3D_NAME_DEPTH_LESS_EQUAL;
  1574. case Semantic::Kind::DepthGreaterEqual:
  1575. return D3D_NAME_DEPTH_GREATER_EQUAL;
  1576. case Semantic::Kind::StencilRef:
  1577. return D3D_NAME_STENCIL_REF;
  1578. case Semantic::Kind::TessFactor: {
  1579. switch (domain) {
  1580. case DXIL::TessellatorDomain::IsoLine:
  1581. return D3D_NAME_FINAL_LINE_DETAIL_TESSFACTOR;
  1582. case DXIL::TessellatorDomain::Tri:
  1583. return D3D_NAME_FINAL_TRI_EDGE_TESSFACTOR;
  1584. case DXIL::TessellatorDomain::Quad:
  1585. return D3D_NAME_FINAL_QUAD_EDGE_TESSFACTOR;
  1586. default:
  1587. return D3D_NAME_UNDEFINED;
  1588. }
  1589. case Semantic::Kind::ShadingRate:
  1590. return (D3D_NAME)DxilProgramSigSemantic::ShadingRate;
  1591. case Semantic::Kind::CullPrimitive:
  1592. return (D3D_NAME)DxilProgramSigSemantic::CullPrimitive;
  1593. }
  1594. case Semantic::Kind::InsideTessFactor:
  1595. switch (domain) {
  1596. case DXIL::TessellatorDomain::Tri:
  1597. return D3D_NAME_FINAL_TRI_INSIDE_TESSFACTOR;
  1598. case DXIL::TessellatorDomain::Quad:
  1599. return D3D_NAME_FINAL_QUAD_INSIDE_TESSFACTOR;
  1600. default:
  1601. return D3D_NAME_UNDEFINED;
  1602. }
  1603. case Semantic::Kind::DispatchThreadID:
  1604. case Semantic::Kind::GroupID:
  1605. case Semantic::Kind::GroupIndex:
  1606. case Semantic::Kind::GroupThreadID:
  1607. case Semantic::Kind::DomainLocation:
  1608. case Semantic::Kind::OutputControlPointID:
  1609. case Semantic::Kind::GSInstanceID:
  1610. case Semantic::Kind::Invalid:
  1611. default:
  1612. return D3D_NAME_UNDEFINED;
  1613. }
  1614. }
  1615. static uint8_t NegMask(uint8_t V) {
  1616. V ^= 0xF;
  1617. return V & 0xF;
  1618. }
  1619. void DxilShaderReflection::CreateReflectionObjectsForSignature(
  1620. const DxilSignature &Sig,
  1621. std::vector<D3D12_SIGNATURE_PARAMETER_DESC> &Descs) {
  1622. for (auto && SigElem : Sig.GetElements()) {
  1623. D3D12_SIGNATURE_PARAMETER_DESC Desc;
  1624. Desc.ComponentType = CompTypeToRegisterComponentType(SigElem->GetCompType());
  1625. Desc.Mask = SigElem->GetColsAsMask();
  1626. // D3D11_43 does not have MinPrecison.
  1627. if (m_PublicAPI != PublicAPI::D3D11_43)
  1628. Desc.MinPrecision = CompTypeToMinPrecision(SigElem->GetCompType());
  1629. if (m_bUsageInMetadata) {
  1630. unsigned UsageMask = SigElem->GetUsageMask();
  1631. if (SigElem->IsAllocated())
  1632. UsageMask <<= SigElem->GetStartCol();
  1633. Desc.ReadWriteMask = Sig.IsInput() ? UsageMask : NegMask(UsageMask);
  1634. } else {
  1635. Desc.ReadWriteMask = Sig.IsInput() ? 0 : Desc.Mask; // Start with output-never-written/input-never-read.
  1636. }
  1637. Desc.Register = SigElem->GetStartRow();
  1638. Desc.Stream = SigElem->GetOutputStream();
  1639. Desc.SystemValueType = SemanticToSystemValueType(SigElem->GetSemantic(), m_pDxilModule->GetTessellatorDomain());
  1640. Desc.SemanticName = SigElem->GetName();
  1641. if (!SigElem->GetSemantic()->IsArbitrary())
  1642. Desc.SemanticName = CreateUpperCase(Desc.SemanticName);
  1643. const std::vector<unsigned> &indexVec = SigElem->GetSemanticIndexVec();
  1644. for (unsigned semIdx = 0; semIdx < indexVec.size(); ++semIdx) {
  1645. Desc.SemanticIndex = indexVec[semIdx];
  1646. if (Desc.SystemValueType == D3D_NAME_FINAL_LINE_DETAIL_TESSFACTOR &&
  1647. Desc.SemanticIndex == 1)
  1648. Desc.SystemValueType = D3D_NAME_FINAL_LINE_DETAIL_TESSFACTOR;
  1649. Descs.push_back(Desc);
  1650. }
  1651. }
  1652. }
  1653. LPCSTR DxilShaderReflection::CreateUpperCase(LPCSTR pValue) {
  1654. // Restricted only to [a-z] ASCII.
  1655. LPCSTR pCursor = pValue;
  1656. while (*pCursor != '\0') {
  1657. if ('a' <= *pCursor && *pCursor <= 'z') {
  1658. break;
  1659. }
  1660. ++pCursor;
  1661. }
  1662. if (*pCursor == '\0')
  1663. return pValue;
  1664. std::unique_ptr<char[]> pUpperStr = llvm::make_unique<char[]>(strlen(pValue) + 1);
  1665. char *pWrite = pUpperStr.get();
  1666. pCursor = pValue;
  1667. for (;;) {
  1668. *pWrite = *pCursor;
  1669. if ('a' <= *pWrite && *pWrite <= 'z') {
  1670. *pWrite += ('A' - 'a');
  1671. }
  1672. if (*pWrite == '\0') break;
  1673. ++pWrite;
  1674. ++pCursor;
  1675. }
  1676. m_UpperCaseNames.push_back(std::move(pUpperStr));
  1677. return m_UpperCaseNames.back().get();
  1678. }
  1679. HRESULT DxilModuleReflection::LoadRDAT(const DxilPartHeader *pPart) {
  1680. if (pPart) {
  1681. IFRBOOL(m_RDAT.InitFromRDAT(GetDxilPartData(pPart), pPart->PartSize), DXC_E_CONTAINER_INVALID);
  1682. }
  1683. return S_OK;
  1684. }
  1685. HRESULT DxilModuleReflection::LoadModule(const DxilPartHeader *pShaderPart) {
  1686. if (pShaderPart == nullptr)
  1687. return E_INVALIDARG;
  1688. const char *pData = GetDxilPartData(pShaderPart);
  1689. try {
  1690. const char *pBitcode;
  1691. uint32_t bitcodeLength;
  1692. GetDxilProgramBitcode((DxilProgramHeader *)pData, &pBitcode, &bitcodeLength);
  1693. std::unique_ptr<MemoryBuffer> pMemBuffer =
  1694. MemoryBuffer::getMemBufferCopy(StringRef(pBitcode, bitcodeLength));
  1695. bool bBitcodeLoadError = false;
  1696. auto errorHandler = [&bBitcodeLoadError](const DiagnosticInfo &diagInfo) {
  1697. bBitcodeLoadError |= diagInfo.getSeverity() == DS_Error;
  1698. };
  1699. #if 0 // We materialize eagerly, because we'll need to walk instructions to look for usage information.
  1700. ErrorOr<std::unique_ptr<Module>> mod =
  1701. getLazyBitcodeModule(std::move(pMemBuffer), Context, errorHandler);
  1702. #else
  1703. ErrorOr<std::unique_ptr<Module>> mod =
  1704. parseBitcodeFile(pMemBuffer->getMemBufferRef(), Context, errorHandler);
  1705. #endif
  1706. if (!mod || bBitcodeLoadError) {
  1707. return E_INVALIDARG;
  1708. }
  1709. std::swap(m_pModule, mod.get());
  1710. m_pDxilModule = &m_pModule->GetOrCreateDxilModule();
  1711. unsigned ValMajor, ValMinor;
  1712. m_pDxilModule->GetValidatorVersion(ValMajor, ValMinor);
  1713. m_bUsageInMetadata = hlsl::DXIL::CompareVersions(ValMajor, ValMinor, 1, 5) >= 0;
  1714. CreateReflectionObjects();
  1715. return S_OK;
  1716. }
  1717. CATCH_CPP_RETURN_HRESULT();
  1718. };
  1719. HRESULT DxilShaderReflection::Load(const DxilPartHeader *pModulePart,
  1720. const DxilPartHeader *pRDATPart) {
  1721. IFR(LoadRDAT(pRDATPart));
  1722. IFR(LoadModule(pModulePart));
  1723. try {
  1724. // Set cbuf usage.
  1725. if (!m_bUsageInMetadata)
  1726. SetCBufferUsage();
  1727. // Populate input/output/patch constant signatures.
  1728. CreateReflectionObjectsForSignature(m_pDxilModule->GetInputSignature(), m_InputSignature);
  1729. CreateReflectionObjectsForSignature(m_pDxilModule->GetOutputSignature(), m_OutputSignature);
  1730. CreateReflectionObjectsForSignature(m_pDxilModule->GetPatchConstOrPrimSignature(), m_PatchConstantSignature);
  1731. if (!m_bUsageInMetadata)
  1732. MarkUsedSignatureElements();
  1733. return S_OK;
  1734. }
  1735. CATCH_CPP_RETURN_HRESULT();
  1736. }
  1737. _Use_decl_annotations_
  1738. HRESULT DxilShaderReflection::GetDesc(D3D12_SHADER_DESC *pDesc) {
  1739. IFR(ZeroMemoryToOut(pDesc));
  1740. const DxilModule &M = *m_pDxilModule;
  1741. const ShaderModel *pSM = M.GetShaderModel();
  1742. pDesc->Version = EncodeVersion(pSM->GetKind(), pSM->GetMajor(), pSM->GetMinor());
  1743. // Unset: LPCSTR Creator; // Creator string
  1744. // Unset: UINT Flags; // Shader compilation/parse flags
  1745. pDesc->ConstantBuffers = m_CBs.size();
  1746. pDesc->BoundResources = m_Resources.size();
  1747. pDesc->InputParameters = m_InputSignature.size();
  1748. pDesc->OutputParameters = m_OutputSignature.size();
  1749. pDesc->PatchConstantParameters = m_PatchConstantSignature.size();
  1750. // Unset: UINT InstructionCount; // Number of emitted instructions
  1751. // Unset: UINT TempRegisterCount; // Number of temporary registers used
  1752. // Unset: UINT TempArrayCount; // Number of temporary arrays used
  1753. // Unset: UINT DefCount; // Number of constant defines
  1754. // Unset: UINT DclCount; // Number of declarations (input + output)
  1755. // Unset: UINT TextureNormalInstructions; // Number of non-categorized texture instructions
  1756. // Unset: UINT TextureLoadInstructions; // Number of texture load instructions
  1757. // Unset: UINT TextureCompInstructions; // Number of texture comparison instructions
  1758. // Unset: UINT TextureBiasInstructions; // Number of texture bias instructions
  1759. // Unset: UINT TextureGradientInstructions; // Number of texture gradient instructions
  1760. // Unset: UINT FloatInstructionCount; // Number of floating point arithmetic instructions used
  1761. // Unset: UINT IntInstructionCount; // Number of signed integer arithmetic instructions used
  1762. // Unset: UINT UintInstructionCount; // Number of unsigned integer arithmetic instructions used
  1763. // Unset: UINT StaticFlowControlCount; // Number of static flow control instructions used
  1764. // Unset: UINT DynamicFlowControlCount; // Number of dynamic flow control instructions used
  1765. // Unset: UINT MacroInstructionCount; // Number of macro instructions used
  1766. // Unset: UINT ArrayInstructionCount; // Number of array instructions used
  1767. // Unset: UINT CutInstructionCount; // Number of cut instructions used
  1768. // Unset: UINT EmitInstructionCount; // Number of emit instructions used
  1769. pDesc->GSOutputTopology = (D3D_PRIMITIVE_TOPOLOGY)M.GetStreamPrimitiveTopology();
  1770. pDesc->GSMaxOutputVertexCount = M.GetMaxVertexCount();
  1771. if (pSM->IsHS())
  1772. pDesc->InputPrimitive = (D3D_PRIMITIVE)(D3D_PRIMITIVE_1_CONTROL_POINT_PATCH + M.GetInputControlPointCount() - 1);
  1773. else
  1774. pDesc->InputPrimitive = (D3D_PRIMITIVE)M.GetInputPrimitive();
  1775. pDesc->cGSInstanceCount = M.GetGSInstanceCount();
  1776. if (pSM->IsHS())
  1777. pDesc->cControlPoints = M.GetOutputControlPointCount();
  1778. else if (pSM->IsDS())
  1779. pDesc->cControlPoints = M.GetInputControlPointCount();
  1780. pDesc->HSOutputPrimitive = (D3D_TESSELLATOR_OUTPUT_PRIMITIVE)M.GetTessellatorOutputPrimitive();
  1781. pDesc->HSPartitioning = (D3D_TESSELLATOR_PARTITIONING)M.GetTessellatorPartitioning();
  1782. pDesc->TessellatorDomain = (D3D_TESSELLATOR_DOMAIN)M.GetTessellatorDomain();
  1783. // instruction counts
  1784. // Unset: UINT cBarrierInstructions; // Number of barrier instructions in a compute shader
  1785. // Unset: UINT cInterlockedInstructions; // Number of interlocked instructions
  1786. // Unset: UINT cTextureStoreInstructions; // Number of texture writes
  1787. return S_OK;
  1788. }
  1789. static bool GetUnsignedVal(Value *V, uint32_t *pValue) {
  1790. ConstantInt *CI = dyn_cast<ConstantInt>(V);
  1791. if (!CI) return false;
  1792. uint64_t u = CI->getZExtValue();
  1793. if (u > UINT32_MAX) return false;
  1794. *pValue = (uint32_t)u;
  1795. return true;
  1796. }
  1797. void DxilShaderReflection::MarkUsedSignatureElements() {
  1798. Function *F = m_pDxilModule->GetEntryFunction();
  1799. DXASSERT(F != nullptr, "else module load should have failed");
  1800. // For every loadInput/storeOutput, update the corresponding ReadWriteMask.
  1801. // F is a pointer to a Function instance
  1802. unsigned elementCount = m_InputSignature.size() + m_OutputSignature.size() +
  1803. m_PatchConstantSignature.size();
  1804. unsigned markedElementCount = 0;
  1805. for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
  1806. DxilInst_LoadInput LI(&*I);
  1807. DxilInst_StoreOutput SO(&*I);
  1808. DxilInst_LoadPatchConstant LPC(&*I);
  1809. DxilInst_StorePatchConstant SPC(&*I);
  1810. DxilInst_StoreVertexOutput SVO(&*I);
  1811. DxilInst_StorePrimitiveOutput SPO(&*I);
  1812. std::vector<D3D12_SIGNATURE_PARAMETER_DESC> *pDescs;
  1813. const DxilSignature *pSig;
  1814. uint32_t col, row, sigId;
  1815. if (LI) {
  1816. if (!GetUnsignedVal(LI.get_inputSigId(), &sigId)) continue;
  1817. if (!GetUnsignedVal(LI.get_colIndex(), &col)) continue;
  1818. GetUnsignedVal(LI.get_rowIndex(), &row);
  1819. pDescs = &m_InputSignature;
  1820. pSig = &m_pDxilModule->GetInputSignature();
  1821. }
  1822. else if (SO) {
  1823. if (!GetUnsignedVal(SO.get_outputSigId(), &sigId)) continue;
  1824. if (!GetUnsignedVal(SO.get_colIndex(), &col)) continue;
  1825. GetUnsignedVal(SO.get_rowIndex(), &row);
  1826. pDescs = &m_OutputSignature;
  1827. pSig = &m_pDxilModule->GetOutputSignature();
  1828. }
  1829. else if (SPC) {
  1830. if (!GetUnsignedVal(SPC.get_outputSigID(), &sigId)) continue;
  1831. if (!GetUnsignedVal(SPC.get_col(), &col)) continue;
  1832. GetUnsignedVal(SPC.get_row(), &row);
  1833. pDescs = &m_PatchConstantSignature;
  1834. pSig = &m_pDxilModule->GetPatchConstOrPrimSignature();
  1835. }
  1836. else if (LPC) {
  1837. if (!GetUnsignedVal(LPC.get_inputSigId(), &sigId)) continue;
  1838. if (!GetUnsignedVal(LPC.get_col(), &col)) continue;
  1839. GetUnsignedVal(LPC.get_row(), &row);
  1840. pDescs = &m_PatchConstantSignature;
  1841. pSig = &m_pDxilModule->GetPatchConstOrPrimSignature();
  1842. }
  1843. else if (SVO) {
  1844. if (!GetUnsignedVal(SVO.get_outputSigId(), &sigId)) continue;
  1845. if (!GetUnsignedVal(SVO.get_colIndex(), &col)) continue;
  1846. GetUnsignedVal(SVO.get_rowIndex(), &row);
  1847. pSig = &m_pDxilModule->GetOutputSignature();
  1848. }
  1849. else if (SPO) {
  1850. if (!GetUnsignedVal(SPO.get_outputSigId(), &sigId)) continue;
  1851. if (!GetUnsignedVal(SPO.get_colIndex(), &col)) continue;
  1852. GetUnsignedVal(SPO.get_rowIndex(), &row);
  1853. pSig = &m_pDxilModule->GetPatchConstOrPrimSignature();
  1854. }
  1855. else {
  1856. continue;
  1857. }
  1858. if (sigId >= pDescs->size()) continue;
  1859. D3D12_SIGNATURE_PARAMETER_DESC *pDesc = &(*pDescs)[sigId];
  1860. // Consider being more fine-grained about masks.
  1861. // We report sometimes-read on input as always-read.
  1862. unsigned UsedMask = pSig->IsInput() ? pDesc->Mask : NegMask(pDesc->Mask);
  1863. if (pDesc->ReadWriteMask == UsedMask)
  1864. continue;
  1865. pDesc->ReadWriteMask = UsedMask;
  1866. ++markedElementCount;
  1867. if (markedElementCount == elementCount)
  1868. return;
  1869. }
  1870. }
  1871. _Use_decl_annotations_
  1872. ID3D12ShaderReflectionConstantBuffer* DxilShaderReflection::GetConstantBufferByIndex(UINT Index) {
  1873. return DxilModuleReflection::_GetConstantBufferByIndex(Index);
  1874. }
  1875. ID3D12ShaderReflectionConstantBuffer* DxilModuleReflection::_GetConstantBufferByIndex(UINT Index) {
  1876. if (Index >= m_CBs.size()) {
  1877. return &g_InvalidSRConstantBuffer;
  1878. }
  1879. return m_CBs[Index].get();
  1880. }
  1881. _Use_decl_annotations_
  1882. ID3D12ShaderReflectionConstantBuffer* DxilShaderReflection::GetConstantBufferByName(LPCSTR Name) {
  1883. return DxilModuleReflection::_GetConstantBufferByName(Name);
  1884. }
  1885. ID3D12ShaderReflectionConstantBuffer* DxilModuleReflection::_GetConstantBufferByName(LPCSTR Name) {
  1886. if (!Name) {
  1887. return &g_InvalidSRConstantBuffer;
  1888. }
  1889. for (UINT index = 0; index < m_CBs.size(); ++index) {
  1890. if (0 == strcmp(m_CBs[index]->GetName(), Name)) {
  1891. return m_CBs[index].get();
  1892. }
  1893. }
  1894. return &g_InvalidSRConstantBuffer;
  1895. }
  1896. _Use_decl_annotations_
  1897. HRESULT DxilShaderReflection::GetResourceBindingDesc(UINT ResourceIndex,
  1898. _Out_ D3D12_SHADER_INPUT_BIND_DESC *pDesc) {
  1899. return DxilModuleReflection::_GetResourceBindingDesc(ResourceIndex, pDesc, m_PublicAPI);
  1900. }
  1901. HRESULT DxilModuleReflection::_GetResourceBindingDesc(UINT ResourceIndex,
  1902. _Out_ D3D12_SHADER_INPUT_BIND_DESC *pDesc, PublicAPI api) {
  1903. IFRBOOL(pDesc != nullptr, E_INVALIDARG);
  1904. IFRBOOL(ResourceIndex < m_Resources.size(), E_INVALIDARG);
  1905. if (api != PublicAPI::D3D12) {
  1906. memcpy(pDesc, &m_Resources[ResourceIndex], sizeof(D3D11_SHADER_INPUT_BIND_DESC));
  1907. }
  1908. else {
  1909. *pDesc = m_Resources[ResourceIndex];
  1910. }
  1911. return S_OK;
  1912. }
  1913. _Use_decl_annotations_
  1914. HRESULT DxilShaderReflection::GetInputParameterDesc(UINT ParameterIndex,
  1915. _Out_ D3D12_SIGNATURE_PARAMETER_DESC *pDesc) {
  1916. IFRBOOL(pDesc != nullptr, E_INVALIDARG);
  1917. IFRBOOL(ParameterIndex < m_InputSignature.size(), E_INVALIDARG);
  1918. if (m_PublicAPI != PublicAPI::D3D11_43)
  1919. *pDesc = m_InputSignature[ParameterIndex];
  1920. else
  1921. memcpy(pDesc, &m_InputSignature[ParameterIndex],
  1922. // D3D11_43 does not have MinPrecison.
  1923. sizeof(D3D12_SIGNATURE_PARAMETER_DESC) - sizeof(D3D_MIN_PRECISION));
  1924. return S_OK;
  1925. }
  1926. _Use_decl_annotations_
  1927. HRESULT DxilShaderReflection::GetOutputParameterDesc(UINT ParameterIndex,
  1928. D3D12_SIGNATURE_PARAMETER_DESC *pDesc) {
  1929. IFRBOOL(pDesc != nullptr, E_INVALIDARG);
  1930. IFRBOOL(ParameterIndex < m_OutputSignature.size(), E_INVALIDARG);
  1931. if (m_PublicAPI != PublicAPI::D3D11_43)
  1932. *pDesc = m_OutputSignature[ParameterIndex];
  1933. else
  1934. memcpy(pDesc, &m_OutputSignature[ParameterIndex],
  1935. // D3D11_43 does not have MinPrecison.
  1936. sizeof(D3D12_SIGNATURE_PARAMETER_DESC) - sizeof(D3D_MIN_PRECISION));
  1937. return S_OK;
  1938. }
  1939. _Use_decl_annotations_
  1940. HRESULT DxilShaderReflection::GetPatchConstantParameterDesc(UINT ParameterIndex,
  1941. D3D12_SIGNATURE_PARAMETER_DESC *pDesc) {
  1942. IFRBOOL(pDesc != nullptr, E_INVALIDARG);
  1943. IFRBOOL(ParameterIndex < m_PatchConstantSignature.size(), E_INVALIDARG);
  1944. if (m_PublicAPI != PublicAPI::D3D11_43)
  1945. *pDesc = m_PatchConstantSignature[ParameterIndex];
  1946. else
  1947. memcpy(pDesc, &m_PatchConstantSignature[ParameterIndex],
  1948. // D3D11_43 does not have MinPrecison.
  1949. sizeof(D3D12_SIGNATURE_PARAMETER_DESC) - sizeof(D3D_MIN_PRECISION));
  1950. return S_OK;
  1951. }
  1952. _Use_decl_annotations_
  1953. ID3D12ShaderReflectionVariable* DxilShaderReflection::GetVariableByName(LPCSTR Name) {
  1954. return DxilModuleReflection::_GetVariableByName(Name);
  1955. }
  1956. ID3D12ShaderReflectionVariable* DxilModuleReflection::_GetVariableByName(LPCSTR Name) {
  1957. if (Name != nullptr) {
  1958. // Iterate through all cbuffers to find the variable.
  1959. for (UINT i = 0; i < m_CBs.size(); i++) {
  1960. ID3D12ShaderReflectionVariable *pVar = m_CBs[i]->GetVariableByName(Name);
  1961. if (pVar != &g_InvalidSRVariable) {
  1962. return pVar;
  1963. }
  1964. }
  1965. }
  1966. return &g_InvalidSRVariable;
  1967. }
  1968. _Use_decl_annotations_
  1969. HRESULT DxilShaderReflection::GetResourceBindingDescByName(LPCSTR Name,
  1970. D3D12_SHADER_INPUT_BIND_DESC *pDesc) {
  1971. return DxilModuleReflection::_GetResourceBindingDescByName(Name, pDesc, m_PublicAPI);
  1972. }
  1973. HRESULT DxilModuleReflection::_GetResourceBindingDescByName(LPCSTR Name,
  1974. D3D12_SHADER_INPUT_BIND_DESC *pDesc, PublicAPI api) {
  1975. IFRBOOL(Name != nullptr, E_INVALIDARG);
  1976. for (UINT i = 0; i < m_Resources.size(); i++) {
  1977. if (strcmp(m_Resources[i].Name, Name) == 0) {
  1978. if (api != PublicAPI::D3D12) {
  1979. memcpy(pDesc, &m_Resources[i], sizeof(D3D11_SHADER_INPUT_BIND_DESC));
  1980. }
  1981. else {
  1982. *pDesc = m_Resources[i];
  1983. }
  1984. return S_OK;
  1985. }
  1986. }
  1987. return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
  1988. }
  1989. UINT DxilShaderReflection::GetMovInstructionCount() { return 0; }
  1990. UINT DxilShaderReflection::GetMovcInstructionCount() { return 0; }
  1991. UINT DxilShaderReflection::GetConversionInstructionCount() { return 0; }
  1992. UINT DxilShaderReflection::GetBitwiseInstructionCount() { return 0; }
  1993. D3D_PRIMITIVE DxilShaderReflection::GetGSInputPrimitive() {
  1994. if (!m_pDxilModule->GetShaderModel()->IsGS())
  1995. return D3D_PRIMITIVE::D3D10_PRIMITIVE_UNDEFINED;
  1996. return (D3D_PRIMITIVE)m_pDxilModule->GetInputPrimitive();
  1997. }
  1998. BOOL DxilShaderReflection::IsSampleFrequencyShader() {
  1999. // TODO: determine correct value
  2000. return FALSE;
  2001. }
  2002. UINT DxilShaderReflection::GetNumInterfaceSlots() { return 0; }
  2003. _Use_decl_annotations_
  2004. HRESULT DxilShaderReflection::GetMinFeatureLevel(enum D3D_FEATURE_LEVEL* pLevel) {
  2005. IFR(AssignToOut(D3D_FEATURE_LEVEL_12_0, pLevel));
  2006. return S_OK;
  2007. }
  2008. _Use_decl_annotations_
  2009. UINT DxilShaderReflection::GetThreadGroupSize(UINT *pSizeX, UINT *pSizeY, UINT *pSizeZ) {
  2010. if (!m_pDxilModule->GetShaderModel()->IsCS()) {
  2011. AssignToOutOpt((UINT)0, pSizeX);
  2012. AssignToOutOpt((UINT)0, pSizeY);
  2013. AssignToOutOpt((UINT)0, pSizeZ);
  2014. return 0;
  2015. }
  2016. unsigned x = m_pDxilModule->GetNumThreads(0);
  2017. unsigned y = m_pDxilModule->GetNumThreads(1);
  2018. unsigned z = m_pDxilModule->GetNumThreads(2);
  2019. AssignToOutOpt(x, pSizeX);
  2020. AssignToOutOpt(y, pSizeY);
  2021. AssignToOutOpt(z, pSizeZ);
  2022. return x * y * z;
  2023. }
  2024. UINT64 DxilShaderReflection::GetRequiresFlags() {
  2025. UINT64 result = m_pDxilModule->m_ShaderFlags.GetFeatureInfo();
  2026. // FeatureInfo flags are identical, with the exception of a collision between:
  2027. // SHADER_FEATURE_COMPUTE_SHADERS_PLUS_RAW_AND_STRUCTURED_BUFFERS_VIA_SHADER_4_X
  2028. // and D3D_SHADER_REQUIRES_EARLY_DEPTH_STENCIL
  2029. // We keep track of the flag elsewhere, so use that instead.
  2030. result &= ~(UINT64)D3D_SHADER_REQUIRES_EARLY_DEPTH_STENCIL;
  2031. if (m_pDxilModule->m_ShaderFlags.GetForceEarlyDepthStencil())
  2032. result |= D3D_SHADER_REQUIRES_EARLY_DEPTH_STENCIL;
  2033. return result;
  2034. }
  2035. // ID3D12FunctionReflection
  2036. class CFunctionReflection : public ID3D12FunctionReflection {
  2037. protected:
  2038. DxilLibraryReflection * m_pLibraryReflection = nullptr;
  2039. const Function *m_pFunction;
  2040. const DxilFunctionProps *m_pProps; // nullptr if non-shader library function or patch constant function
  2041. std::string m_Name;
  2042. typedef SmallSetVector<UINT32, 8> ResourceUseSet;
  2043. ResourceUseSet m_UsedResources;
  2044. ResourceUseSet m_UsedCBs;
  2045. public:
  2046. void Initialize(DxilLibraryReflection* pLibraryReflection, Function *pFunction) {
  2047. DXASSERT_NOMSG(pLibraryReflection);
  2048. DXASSERT_NOMSG(pFunction);
  2049. m_pLibraryReflection = pLibraryReflection;
  2050. m_pFunction = pFunction;
  2051. const DxilModule &M = *m_pLibraryReflection->m_pDxilModule;
  2052. m_Name = m_pFunction->getName().str();
  2053. m_pProps = nullptr;
  2054. if (M.HasDxilFunctionProps(m_pFunction)) {
  2055. m_pProps = &M.GetDxilFunctionProps(m_pFunction);
  2056. }
  2057. }
  2058. void AddResourceReference(UINT resIndex) {
  2059. m_UsedResources.insert(resIndex);
  2060. }
  2061. void AddCBReference(UINT cbIndex) {
  2062. m_UsedCBs.insert(cbIndex);
  2063. }
  2064. // ID3D12FunctionReflection
  2065. STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_FUNCTION_DESC * pDesc);
  2066. // BufferIndex relative to used constant buffers here
  2067. STDMETHOD_(ID3D12ShaderReflectionConstantBuffer *, GetConstantBufferByIndex)(THIS_ _In_ UINT BufferIndex);
  2068. STDMETHOD_(ID3D12ShaderReflectionConstantBuffer *, GetConstantBufferByName)(THIS_ _In_ LPCSTR Name);
  2069. STDMETHOD(GetResourceBindingDesc)(THIS_ _In_ UINT ResourceIndex,
  2070. _Out_ D3D12_SHADER_INPUT_BIND_DESC * pDesc);
  2071. STDMETHOD_(ID3D12ShaderReflectionVariable *, GetVariableByName)(THIS_ _In_ LPCSTR Name);
  2072. STDMETHOD(GetResourceBindingDescByName)(THIS_ _In_ LPCSTR Name,
  2073. _Out_ D3D12_SHADER_INPUT_BIND_DESC * pDesc);
  2074. // Use D3D_RETURN_PARAMETER_INDEX to get description of the return value.
  2075. STDMETHOD_(ID3D12FunctionParameterReflection *, GetFunctionParameter)(THIS_ _In_ INT ParameterIndex) {
  2076. return &g_InvalidFunctionParameter;
  2077. }
  2078. };
  2079. _Use_decl_annotations_
  2080. HRESULT CFunctionReflection::GetDesc(D3D12_FUNCTION_DESC *pDesc) {
  2081. DXASSERT_NOMSG(m_pLibraryReflection);
  2082. IFR(ZeroMemoryToOut(pDesc));
  2083. const ShaderModel* pSM = m_pLibraryReflection->m_pDxilModule->GetShaderModel();
  2084. DXIL::ShaderKind kind = DXIL::ShaderKind::Library;
  2085. if (m_pProps) {
  2086. kind = m_pProps->shaderKind;
  2087. }
  2088. pDesc->Version = EncodeVersion(kind, pSM->GetMajor(), pSM->GetMinor());
  2089. //Unset: LPCSTR Creator; // Creator string
  2090. //Unset: UINT Flags; // Shader compilation/parse flags
  2091. pDesc->ConstantBuffers = (UINT)m_UsedCBs.size();
  2092. pDesc->BoundResources = (UINT)m_UsedResources.size();
  2093. //Unset: UINT InstructionCount; // Number of emitted instructions
  2094. //Unset: UINT TempRegisterCount; // Number of temporary registers used
  2095. //Unset: UINT TempArrayCount; // Number of temporary arrays used
  2096. //Unset: UINT DefCount; // Number of constant defines
  2097. //Unset: UINT DclCount; // Number of declarations (input + output)
  2098. //Unset: UINT TextureNormalInstructions; // Number of non-categorized texture instructions
  2099. //Unset: UINT TextureLoadInstructions; // Number of texture load instructions
  2100. //Unset: UINT TextureCompInstructions; // Number of texture comparison instructions
  2101. //Unset: UINT TextureBiasInstructions; // Number of texture bias instructions
  2102. //Unset: UINT TextureGradientInstructions; // Number of texture gradient instructions
  2103. //Unset: UINT FloatInstructionCount; // Number of floating point arithmetic instructions used
  2104. //Unset: UINT IntInstructionCount; // Number of signed integer arithmetic instructions used
  2105. //Unset: UINT UintInstructionCount; // Number of unsigned integer arithmetic instructions used
  2106. //Unset: UINT StaticFlowControlCount; // Number of static flow control instructions used
  2107. //Unset: UINT DynamicFlowControlCount; // Number of dynamic flow control instructions used
  2108. //Unset: UINT MacroInstructionCount; // Number of macro instructions used
  2109. //Unset: UINT ArrayInstructionCount; // Number of array instructions used
  2110. //Unset: UINT MovInstructionCount; // Number of mov instructions used
  2111. //Unset: UINT MovcInstructionCount; // Number of movc instructions used
  2112. //Unset: UINT ConversionInstructionCount; // Number of type conversion instructions used
  2113. //Unset: UINT BitwiseInstructionCount; // Number of bitwise arithmetic instructions used
  2114. //Unset: D3D_FEATURE_LEVEL MinFeatureLevel; // Min target of the function byte code
  2115. //Unset: UINT64 RequiredFeatureFlags; // Required feature flags
  2116. pDesc->Name = m_Name.c_str();
  2117. //Unset: INT FunctionParameterCount; // Number of logical parameters in the function signature (not including return)
  2118. //Unset: BOOL HasReturn; // TRUE, if function returns a value, false - it is a subroutine
  2119. //Unset: BOOL Has10Level9VertexShader; // TRUE, if there is a 10L9 VS blob
  2120. //Unset: BOOL Has10Level9PixelShader; // TRUE, if there is a 10L9 PS blob
  2121. return S_OK;
  2122. }
  2123. // BufferIndex is relative to used constant buffers here
  2124. ID3D12ShaderReflectionConstantBuffer *CFunctionReflection::GetConstantBufferByIndex(UINT BufferIndex) {
  2125. DXASSERT_NOMSG(m_pLibraryReflection);
  2126. if (BufferIndex >= m_UsedCBs.size())
  2127. return &g_InvalidSRConstantBuffer;
  2128. return m_pLibraryReflection->_GetConstantBufferByIndex(m_UsedCBs[BufferIndex]);
  2129. }
  2130. ID3D12ShaderReflectionConstantBuffer *CFunctionReflection::GetConstantBufferByName(LPCSTR Name) {
  2131. DXASSERT_NOMSG(m_pLibraryReflection);
  2132. return m_pLibraryReflection->_GetConstantBufferByName(Name);
  2133. }
  2134. HRESULT CFunctionReflection::GetResourceBindingDesc(UINT ResourceIndex,
  2135. D3D12_SHADER_INPUT_BIND_DESC * pDesc) {
  2136. DXASSERT_NOMSG(m_pLibraryReflection);
  2137. if (ResourceIndex >= m_UsedResources.size())
  2138. return E_INVALIDARG;
  2139. return m_pLibraryReflection->_GetResourceBindingDesc(m_UsedResources[ResourceIndex], pDesc);
  2140. }
  2141. ID3D12ShaderReflectionVariable * CFunctionReflection::GetVariableByName(LPCSTR Name) {
  2142. DXASSERT_NOMSG(m_pLibraryReflection);
  2143. return m_pLibraryReflection->_GetVariableByName(Name);
  2144. }
  2145. HRESULT CFunctionReflection::GetResourceBindingDescByName(LPCSTR Name,
  2146. D3D12_SHADER_INPUT_BIND_DESC * pDesc) {
  2147. DXASSERT_NOMSG(m_pLibraryReflection);
  2148. return m_pLibraryReflection->_GetResourceBindingDescByName(Name, pDesc);
  2149. }
  2150. // DxilLibraryReflection
  2151. void DxilLibraryReflection::AddResourceDependencies() {
  2152. RDAT::FunctionTableReader *functionTable = m_RDAT.GetFunctionTableReader();
  2153. m_FunctionVector.clear();
  2154. m_FunctionVector.reserve(functionTable->GetNumFunctions());
  2155. std::map<StringRef, CFunctionReflection*> orderedMap;
  2156. RDAT::ResourceTableReader *resourceTable = m_RDAT.GetResourceTableReader();
  2157. unsigned SamplersStart = resourceTable->GetNumCBuffers();
  2158. unsigned SRVsStart = SamplersStart + resourceTable->GetNumSamplers();
  2159. unsigned UAVsStart = SRVsStart + resourceTable->GetNumSRVs();
  2160. IFTBOOL(resourceTable->GetNumResources() == m_Resources.size(),
  2161. DXC_E_INCORRECT_DXIL_METADATA);
  2162. for (unsigned iFunc = 0; iFunc < functionTable->GetNumFunctions(); ++iFunc) {
  2163. RDAT::FunctionReader FR = functionTable->GetItem(iFunc);
  2164. auto &func = m_FunctionMap[FR.GetName()];
  2165. DXASSERT(!func.get(), "otherwise duplicate named functions");
  2166. Function *F = m_pModule->getFunction(FR.GetName());
  2167. func.reset(new CFunctionReflection());
  2168. func->Initialize(this, F);
  2169. m_FunctionsByPtr[F] = func.get();
  2170. orderedMap[FR.GetName()] = func.get();
  2171. for (unsigned iRes = 0; iRes < FR.GetNumResources(); ++iRes) {
  2172. RDAT::ResourceReader RR = FR.GetResource(iRes);
  2173. unsigned id = RR.GetID();
  2174. switch (RR.GetResourceClass()) {
  2175. case DXIL::ResourceClass::CBuffer:
  2176. func->AddResourceReference(id);
  2177. func->AddCBReference(id);
  2178. break;
  2179. case DXIL::ResourceClass::Sampler:
  2180. func->AddResourceReference(SamplersStart + id);
  2181. break;
  2182. case DXIL::ResourceClass::SRV:
  2183. func->AddResourceReference(SRVsStart + id);
  2184. break;
  2185. case DXIL::ResourceClass::UAV:
  2186. func->AddResourceReference(UAVsStart + id);
  2187. break;
  2188. default:
  2189. DXASSERT(false, "Unrecognized ResourceClass in RDAT");
  2190. }
  2191. }
  2192. }
  2193. for (auto &it : orderedMap) {
  2194. m_FunctionVector.push_back(it.second);
  2195. }
  2196. }
  2197. static void CollectCBufUsageForLib(Value *V, std::vector<unsigned> &cbufUsage, bool bMinPrecision) {
  2198. for (auto user : V->users()) {
  2199. Value *V = user;
  2200. if (auto *CI = dyn_cast<CallInst>(V)) {
  2201. if (hlsl::OP::IsDxilOpFuncCallInst(CI, hlsl::OP::OpCode::CreateHandleForLib)) {
  2202. CollectCBufUsage(CI, cbufUsage, bMinPrecision);
  2203. }
  2204. } else if (isa<GEPOperator>(V) ||
  2205. isa<LoadInst>(V)) {
  2206. CollectCBufUsageForLib(user, cbufUsage, bMinPrecision);
  2207. }
  2208. }
  2209. }
  2210. void DxilLibraryReflection::SetCBufferUsage() {
  2211. unsigned cbSize = std::min(m_CBs.size(), m_pDxilModule->GetCBuffers().size());
  2212. for (unsigned i=0;i<cbSize;i++) {
  2213. std::vector<unsigned> cbufUsage;
  2214. CollectCBufUsageForLib(m_pDxilModule->GetCBuffer(i).GetGlobalSymbol(), cbufUsage, m_pDxilModule->GetUseMinPrecision());
  2215. SetCBufVarUsage(*m_CBs[i], cbufUsage);
  2216. }
  2217. }
  2218. // ID3D12LibraryReflection
  2219. HRESULT DxilLibraryReflection::Load(const DxilPartHeader *pModulePart,
  2220. const DxilPartHeader *pRDATPart) {
  2221. IFR(LoadRDAT(pRDATPart));
  2222. IFR(LoadModule(pModulePart));
  2223. try {
  2224. AddResourceDependencies();
  2225. if (!m_bUsageInMetadata)
  2226. SetCBufferUsage();
  2227. return S_OK;
  2228. }
  2229. CATCH_CPP_RETURN_HRESULT();
  2230. }
  2231. _Use_decl_annotations_
  2232. HRESULT DxilLibraryReflection::GetDesc(D3D12_LIBRARY_DESC * pDesc) {
  2233. IFR(ZeroMemoryToOut(pDesc));
  2234. //Unset: LPCSTR Creator; // The name of the originator of the library.
  2235. //Unset: UINT Flags; // Compilation flags.
  2236. //UINT FunctionCount; // Number of functions exported from the library.
  2237. pDesc->FunctionCount = (UINT)m_FunctionVector.size();
  2238. return S_OK;
  2239. }
  2240. _Use_decl_annotations_
  2241. ID3D12FunctionReflection *DxilLibraryReflection::GetFunctionByIndex(INT FunctionIndex) {
  2242. if ((UINT)FunctionIndex >= m_FunctionVector.size())
  2243. return &g_InvalidFunction;
  2244. return m_FunctionVector[FunctionIndex];
  2245. }
  2246. #else // LLVM_ON_WIN32
  2247. void hlsl::CreateDxcContainerReflection(IDxcContainerReflection **ppResult) {
  2248. *ppResult = nullptr;
  2249. }
  2250. DEFINE_CROSS_PLATFORM_UUIDOF(IDxcContainerReflection)
  2251. #endif // LLVM_ON_WIN32