DxilContainerReflection.cpp 100 KB

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