DxilContainerTest.cpp 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilContainerTest.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 tests for container formatting and validation. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #ifndef UNICODE
  12. #define UNICODE
  13. #endif
  14. #ifdef __APPLE__
  15. // Workaround for ambiguous wcsstr on Mac
  16. #define _WCHAR_H_CPLUSPLUS_98_CONFORMANCE_
  17. #endif
  18. #include <memory>
  19. #include <vector>
  20. #include <string>
  21. #include <tuple>
  22. #include <cassert>
  23. #include <sstream>
  24. #include <algorithm>
  25. #include <unordered_set>
  26. #include "dxc/Support/WinIncludes.h"
  27. #include "dxc/dxcapi.h"
  28. #ifdef _WIN32
  29. #include <atlfile.h>
  30. #include <d3dcompiler.h>
  31. #pragma comment(lib, "d3dcompiler.lib")
  32. #include <filesystem>
  33. #endif
  34. #include "HLSLTestData.h"
  35. #include "HlslTestUtils.h"
  36. #include "DxcTestUtils.h"
  37. #include "dxc/Support/Global.h"
  38. #include "dxc/Support/dxcapi.use.h"
  39. #include "dxc/Support/HLSLOptions.h"
  40. #include "dxc/DxilContainer/DxilContainer.h"
  41. #include "dxc/DxilContainer/DxilRuntimeReflection.h"
  42. #include "dxc/DXIL/DxilShaderFlags.h"
  43. #include "dxc/DXIL/DxilUtil.h"
  44. #include <fstream>
  45. #include <chrono>
  46. #include <codecvt>
  47. using namespace std;
  48. using namespace hlsl_test;
  49. #ifdef _WIN32
  50. using namespace std::experimental::filesystem;
  51. static uint8_t MaskCount(uint8_t V) {
  52. DXASSERT_NOMSG(0 <= V && V <= 0xF);
  53. static const uint8_t Count[16] = {
  54. 0, 1, 1, 2,
  55. 1, 2, 2, 3,
  56. 1, 2, 2, 3,
  57. 2, 3, 3, 4
  58. };
  59. return Count[V];
  60. }
  61. #endif
  62. #ifdef _WIN32
  63. class DxilContainerTest {
  64. #else
  65. class DxilContainerTest : public ::testing::Test {
  66. #endif
  67. public:
  68. BEGIN_TEST_CLASS(DxilContainerTest)
  69. TEST_CLASS_PROPERTY(L"Parallel", L"true")
  70. TEST_METHOD_PROPERTY(L"Priority", L"0")
  71. END_TEST_CLASS()
  72. TEST_CLASS_SETUP(InitSupport);
  73. TEST_METHOD(CompileWhenDebugSourceThenSourceMatters)
  74. TEST_METHOD(CompileWhenOkThenCheckRDAT)
  75. TEST_METHOD(CompileWhenOkThenCheckRDAT2)
  76. TEST_METHOD(CompileWhenOkThenCheckReflection1)
  77. TEST_METHOD(CompileWhenOKThenIncludesFeatureInfo)
  78. TEST_METHOD(CompileWhenOKThenIncludesSignatures)
  79. TEST_METHOD(CompileWhenSigSquareThenIncludeSplit)
  80. TEST_METHOD(DisassemblyWhenMissingThenFails)
  81. TEST_METHOD(DisassemblyWhenBCInvalidThenFails)
  82. TEST_METHOD(DisassemblyWhenInvalidThenFails)
  83. TEST_METHOD(DisassemblyWhenValidThenOK)
  84. TEST_METHOD(ValidateFromLL_Abs2)
  85. TEST_METHOD(DxilContainerUnitTest)
  86. TEST_METHOD(ReflectionMatchesDXBC_CheckIn)
  87. BEGIN_TEST_METHOD(ReflectionMatchesDXBC_Full)
  88. TEST_METHOD_PROPERTY(L"Priority", L"1")
  89. END_TEST_METHOD()
  90. dxc::DxcDllSupport m_dllSupport;
  91. VersionSupportInfo m_ver;
  92. void CreateBlobPinned(_In_bytecount_(size) LPCVOID data, SIZE_T size,
  93. UINT32 codePage, _Outptr_ IDxcBlobEncoding **ppBlob) {
  94. CComPtr<IDxcLibrary> library;
  95. IFT(m_dllSupport.CreateInstance(CLSID_DxcLibrary, &library));
  96. IFT(library->CreateBlobWithEncodingFromPinned((LPBYTE)data, size, codePage,
  97. ppBlob));
  98. }
  99. void CreateBlobFromText(_In_z_ const char *pText,
  100. _Outptr_ IDxcBlobEncoding **ppBlob) {
  101. CreateBlobPinned(pText, strlen(pText), CP_UTF8, ppBlob);
  102. }
  103. HRESULT CreateCompiler(IDxcCompiler **ppResult) {
  104. if (!m_dllSupport.IsEnabled()) {
  105. VERIFY_SUCCEEDED(m_dllSupport.Initialize());
  106. }
  107. return m_dllSupport.CreateInstance(CLSID_DxcCompiler, ppResult);
  108. }
  109. #ifdef _WIN32 // - Reflection Unsupported
  110. void CompareShaderInputBindDesc(D3D12_SHADER_INPUT_BIND_DESC *pTestDesc,
  111. D3D12_SHADER_INPUT_BIND_DESC *pBaseDesc) {
  112. VERIFY_ARE_EQUAL(pTestDesc->BindCount, pBaseDesc->BindCount);
  113. VERIFY_ARE_EQUAL(pTestDesc->BindPoint, pBaseDesc->BindPoint);
  114. VERIFY_ARE_EQUAL(pTestDesc->Dimension, pBaseDesc->Dimension);
  115. VERIFY_ARE_EQUAL_STR(pTestDesc->Name, pBaseDesc->Name);
  116. VERIFY_ARE_EQUAL(pTestDesc->NumSamples, pBaseDesc->NumSamples);
  117. VERIFY_ARE_EQUAL(pTestDesc->ReturnType, pBaseDesc->ReturnType);
  118. VERIFY_ARE_EQUAL(pTestDesc->Space, pBaseDesc->Space);
  119. if (pBaseDesc->Type == D3D_SIT_UAV_APPEND_STRUCTURED ||
  120. pBaseDesc->Type == D3D_SIT_UAV_CONSUME_STRUCTURED) {
  121. // dxil only have rw with counter.
  122. VERIFY_ARE_EQUAL(pTestDesc->Type, D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER);
  123. } else if (pTestDesc->Type == D3D_SIT_STRUCTURED &&
  124. pBaseDesc->Type != D3D_SIT_STRUCTURED) {
  125. VERIFY_ARE_EQUAL(pBaseDesc->Type, D3D_SIT_TEXTURE);
  126. } else
  127. VERIFY_ARE_EQUAL(pTestDesc->Type, pBaseDesc->Type);
  128. // D3D_SIF_USERPACKED is never set in dxil.
  129. UINT unusedFlag = D3D_SIF_USERPACKED;
  130. VERIFY_ARE_EQUAL(pTestDesc->uFlags, pBaseDesc->uFlags & ~unusedFlag);
  131. // VERIFY_ARE_EQUAL(pTestDesc->uID, pBaseDesc->uID); // Like register, this can vary.
  132. }
  133. void CompareParameterDesc(D3D12_SIGNATURE_PARAMETER_DESC *pTestDesc,
  134. D3D12_SIGNATURE_PARAMETER_DESC *pBaseDesc, bool isInput) {
  135. VERIFY_ARE_EQUAL(0, _stricmp(pTestDesc->SemanticName, pBaseDesc->SemanticName));
  136. if (pTestDesc->SystemValueType == D3D_NAME_CLIP_DISTANCE) return; // currently generating multiple clip distance params, one per component
  137. VERIFY_ARE_EQUAL(pTestDesc->ComponentType, pBaseDesc->ComponentType);
  138. VERIFY_ARE_EQUAL(MaskCount(pTestDesc->Mask), MaskCount(pBaseDesc->Mask));
  139. VERIFY_ARE_EQUAL(pTestDesc->MinPrecision, pBaseDesc->MinPrecision);
  140. if (!isInput)
  141. VERIFY_ARE_EQUAL(pTestDesc->ReadWriteMask != 0, pBaseDesc->ReadWriteMask != 0); // VERIFY_ARE_EQUAL(pTestDesc->ReadWriteMask, pBaseDesc->ReadWriteMask);
  142. // VERIFY_ARE_EQUAL(pTestDesc->Register, pBaseDesc->Register);
  143. //VERIFY_ARE_EQUAL(pTestDesc->SemanticIndex, pBaseDesc->SemanticIndex);
  144. VERIFY_ARE_EQUAL(pTestDesc->Stream, pBaseDesc->Stream);
  145. VERIFY_ARE_EQUAL(pTestDesc->SystemValueType, pBaseDesc->SystemValueType);
  146. }
  147. void CompareType(ID3D12ShaderReflectionType *pTest,
  148. ID3D12ShaderReflectionType *pBase,
  149. bool shouldSuppressOffsetChecks = false)
  150. {
  151. D3D12_SHADER_TYPE_DESC testDesc, baseDesc;
  152. VERIFY_SUCCEEDED(pTest->GetDesc(&testDesc));
  153. VERIFY_SUCCEEDED(pBase->GetDesc(&baseDesc));
  154. VERIFY_ARE_EQUAL(testDesc.Class, baseDesc.Class);
  155. VERIFY_ARE_EQUAL(testDesc.Type, baseDesc.Type);
  156. VERIFY_ARE_EQUAL(testDesc.Rows, baseDesc.Rows);
  157. VERIFY_ARE_EQUAL(testDesc.Columns, baseDesc.Columns);
  158. VERIFY_ARE_EQUAL(testDesc.Elements, baseDesc.Elements);
  159. VERIFY_ARE_EQUAL(testDesc.Members, baseDesc.Members);
  160. if(!shouldSuppressOffsetChecks)
  161. {
  162. VERIFY_ARE_EQUAL(testDesc.Offset, baseDesc.Offset);
  163. }
  164. VERIFY_ARE_EQUAL(0, strcmp(testDesc.Name, baseDesc.Name));
  165. for (UINT i = 0; i < baseDesc.Members; ++i) {
  166. ID3D12ShaderReflectionType* testMemberType = pTest->GetMemberTypeByIndex(i);
  167. ID3D12ShaderReflectionType* baseMemberType = pBase->GetMemberTypeByIndex(i);
  168. VERIFY_IS_NOT_NULL(testMemberType);
  169. VERIFY_IS_NOT_NULL(baseMemberType);
  170. CompareType(testMemberType, baseMemberType, shouldSuppressOffsetChecks);
  171. LPCSTR testMemberName = pTest->GetMemberTypeName(i);
  172. LPCSTR baseMemberName = pBase->GetMemberTypeName(i);
  173. VERIFY_ARE_EQUAL(0, strcmp(testMemberName, baseMemberName));
  174. }
  175. }
  176. typedef HRESULT (__stdcall ID3D12ShaderReflection::*GetParameterDescFn)(UINT, D3D12_SIGNATURE_PARAMETER_DESC*);
  177. void SortNameIdxVector(std::vector<std::tuple<LPCSTR, UINT, UINT>> &value) {
  178. struct FirstPredT {
  179. bool operator()(std::tuple<LPCSTR, UINT, UINT> &l,
  180. std::tuple<LPCSTR, UINT, UINT> &r) {
  181. int strResult = strcmp(std::get<0>(l), std::get<0>(r));
  182. return (strResult < 0 ) || (strResult == 0 && std::get<1>(l) < std::get<1>(r));
  183. }
  184. } FirstPred;
  185. std::sort(value.begin(), value.end(), FirstPred);
  186. }
  187. void CompareParameterDescs(UINT count, ID3D12ShaderReflection *pTest,
  188. ID3D12ShaderReflection *pBase,
  189. GetParameterDescFn Fn, bool isInput) {
  190. std::vector<std::tuple<LPCSTR, UINT, UINT>> testParams, baseParams;
  191. testParams.reserve(count);
  192. baseParams.reserve(count);
  193. for (UINT i = 0; i < count; ++i) {
  194. D3D12_SIGNATURE_PARAMETER_DESC D;
  195. VERIFY_SUCCEEDED((pTest->*Fn)(i, &D));
  196. testParams.push_back(std::make_tuple(D.SemanticName, D.SemanticIndex, i));
  197. VERIFY_SUCCEEDED((pBase->*Fn)(i, &D));
  198. baseParams.push_back(std::make_tuple(D.SemanticName, D.SemanticIndex, i));
  199. }
  200. SortNameIdxVector(testParams);
  201. SortNameIdxVector(baseParams);
  202. for (UINT i = 0; i < count; ++i) {
  203. D3D12_SIGNATURE_PARAMETER_DESC testParamDesc, baseParamDesc;
  204. VERIFY_SUCCEEDED(
  205. (pTest->*Fn)(std::get<2>(testParams[i]), &testParamDesc));
  206. VERIFY_SUCCEEDED(
  207. (pBase->*Fn)(std::get<2>(baseParams[i]), &baseParamDesc));
  208. CompareParameterDesc(&testParamDesc, &baseParamDesc, isInput);
  209. }
  210. }
  211. void CompareReflection(ID3D12ShaderReflection *pTest, ID3D12ShaderReflection *pBase) {
  212. D3D12_SHADER_DESC testDesc, baseDesc;
  213. VERIFY_SUCCEEDED(pTest->GetDesc(&testDesc));
  214. VERIFY_SUCCEEDED(pBase->GetDesc(&baseDesc));
  215. VERIFY_ARE_EQUAL(D3D12_SHVER_GET_TYPE(testDesc.Version), D3D12_SHVER_GET_TYPE(baseDesc.Version));
  216. VERIFY_ARE_EQUAL(testDesc.ConstantBuffers, baseDesc.ConstantBuffers);
  217. VERIFY_ARE_EQUAL(testDesc.BoundResources, baseDesc.BoundResources);
  218. VERIFY_ARE_EQUAL(testDesc.InputParameters, baseDesc.InputParameters);
  219. VERIFY_ARE_EQUAL(testDesc.OutputParameters, baseDesc.OutputParameters);
  220. VERIFY_ARE_EQUAL(testDesc.PatchConstantParameters, baseDesc.PatchConstantParameters);
  221. {
  222. for (UINT i = 0; i < testDesc.ConstantBuffers; ++i) {
  223. ID3D12ShaderReflectionConstantBuffer *pTestCB, *pBaseCB;
  224. D3D12_SHADER_BUFFER_DESC testCB, baseCB;
  225. pTestCB = pTest->GetConstantBufferByIndex(i);
  226. VERIFY_SUCCEEDED(pTestCB->GetDesc(&testCB));
  227. pBaseCB = pBase->GetConstantBufferByName(testCB.Name);
  228. VERIFY_SUCCEEDED(pBaseCB->GetDesc(&baseCB));
  229. VERIFY_ARE_EQUAL_STR(testCB.Name, baseCB.Name);
  230. VERIFY_ARE_EQUAL(testCB.Type, baseCB.Type);
  231. VERIFY_ARE_EQUAL(testCB.Variables, baseCB.Variables);
  232. VERIFY_ARE_EQUAL(testCB.Size, baseCB.Size);
  233. VERIFY_ARE_EQUAL(testCB.uFlags, baseCB.uFlags);
  234. llvm::StringMap<D3D12_SHADER_VARIABLE_DESC> variableMap;
  235. llvm::StringMap<ID3D12ShaderReflectionType*> variableTypeMap;
  236. for (UINT vi = 0; vi < testCB.Variables; ++vi) {
  237. ID3D12ShaderReflectionVariable *pBaseConst;
  238. D3D12_SHADER_VARIABLE_DESC baseConst;
  239. pBaseConst = pBaseCB->GetVariableByIndex(vi);
  240. VERIFY_SUCCEEDED(pBaseConst->GetDesc(&baseConst));
  241. variableMap[baseConst.Name] = baseConst;
  242. ID3D12ShaderReflectionType* pBaseType = pBaseConst->GetType();
  243. VERIFY_IS_NOT_NULL(pBaseType);
  244. variableTypeMap[baseConst.Name] = pBaseType;
  245. }
  246. for (UINT vi = 0; vi < testCB.Variables; ++vi) {
  247. ID3D12ShaderReflectionVariable *pTestConst;
  248. D3D12_SHADER_VARIABLE_DESC testConst;
  249. pTestConst = pTestCB->GetVariableByIndex(vi);
  250. VERIFY_SUCCEEDED(pTestConst->GetDesc(&testConst));
  251. VERIFY_ARE_EQUAL(variableMap.count(testConst.Name), 1);
  252. D3D12_SHADER_VARIABLE_DESC baseConst = variableMap[testConst.Name];
  253. VERIFY_ARE_EQUAL(testConst.uFlags, baseConst.uFlags);
  254. VERIFY_ARE_EQUAL(testConst.StartOffset, baseConst.StartOffset);
  255. VERIFY_ARE_EQUAL(testConst.Size, baseConst.Size);
  256. ID3D12ShaderReflectionType* pTestType = pTestConst->GetType();
  257. VERIFY_IS_NOT_NULL(pTestType);
  258. VERIFY_ARE_EQUAL(variableTypeMap.count(testConst.Name), 1);
  259. ID3D12ShaderReflectionType* pBaseType = variableTypeMap[testConst.Name];
  260. // Note: we suppress comparing offsets for structured buffers, because dxc and fxc don't
  261. // seem to agree in that case.
  262. //
  263. // The information in the `D3D12_SHADER_BUFFER_DESC` doesn't give us enough to
  264. // be able to isolate structured buffers, so we do the test negatively: suppress
  265. // offset checks *unless* we are looking at a `cbuffer` or `tbuffer`.
  266. bool shouldSuppressOffsetChecks = true;
  267. switch( baseCB.Type )
  268. {
  269. default:
  270. break;
  271. case D3D_CT_CBUFFER:
  272. case D3D_CT_TBUFFER:
  273. shouldSuppressOffsetChecks = false;
  274. break;
  275. }
  276. CompareType(pTestType, pBaseType, shouldSuppressOffsetChecks);
  277. }
  278. }
  279. }
  280. for (UINT i = 0; i < testDesc.BoundResources; ++i) {
  281. D3D12_SHADER_INPUT_BIND_DESC testParamDesc, baseParamDesc;
  282. VERIFY_SUCCEEDED(pTest->GetResourceBindingDesc(i, &testParamDesc), WStrFmt(L"i=%u", i));
  283. VERIFY_SUCCEEDED(pBase->GetResourceBindingDescByName(testParamDesc.Name, &baseParamDesc));
  284. CompareShaderInputBindDesc(&testParamDesc, &baseParamDesc);
  285. }
  286. CompareParameterDescs(testDesc.InputParameters, pTest, pBase, &ID3D12ShaderReflection::GetInputParameterDesc, true);
  287. CompareParameterDescs(testDesc.OutputParameters, pTest, pBase,
  288. &ID3D12ShaderReflection::GetOutputParameterDesc,
  289. false);
  290. bool isHs = testDesc.HSPartitioning != D3D_TESSELLATOR_PARTITIONING::D3D11_TESSELLATOR_PARTITIONING_UNDEFINED;
  291. CompareParameterDescs(
  292. testDesc.PatchConstantParameters, pTest, pBase,
  293. &ID3D12ShaderReflection::GetPatchConstantParameterDesc, !isHs);
  294. {
  295. UINT32 testTotal, testX, testY, testZ;
  296. UINT32 baseTotal, baseX, baseY, baseZ;
  297. testTotal = pTest->GetThreadGroupSize(&testX, &testY, &testZ);
  298. baseTotal = pBase->GetThreadGroupSize(&baseX, &baseY, &baseZ);
  299. VERIFY_ARE_EQUAL(testTotal, baseTotal);
  300. VERIFY_ARE_EQUAL(testX, baseX);
  301. VERIFY_ARE_EQUAL(testY, baseY);
  302. VERIFY_ARE_EQUAL(testZ, baseZ);
  303. }
  304. }
  305. #endif // _WIN32 - Reflection unsupported
  306. #ifdef _WIN32 // - Reflection unsupported
  307. HRESULT CompileFromFile(LPCWSTR path, bool useDXBC, IDxcBlob **ppBlob) {
  308. std::vector<FileRunCommandPart> parts;
  309. ParseCommandPartsFromFile(path, parts);
  310. VERIFY_IS_TRUE(parts.size() > 0);
  311. VERIFY_ARE_EQUAL_STR(parts[0].Command.c_str(), "%dxc");
  312. FileRunCommandPart &dxc = parts[0];
  313. m_dllSupport.Initialize();
  314. hlsl::options::MainArgs args;
  315. hlsl::options::DxcOpts opts;
  316. dxc.ReadOptsForDxc(args, opts);
  317. if (opts.CodeGenHighLevel) return E_FAIL; // skip for now
  318. if (useDXBC) {
  319. // Consider supporting defines and flags if/when needed.
  320. std::string TargetProfile(opts.TargetProfile.str());
  321. TargetProfile[3] = '5'; TargetProfile[5] = '1';
  322. CComPtr<ID3DBlob> pDxbcBlob;
  323. CComPtr<ID3DBlob> pDxbcErrors;
  324. UINT unboundDescTab = (1 << 20);
  325. IFR(D3DCompileFromFile(path, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE,
  326. opts.EntryPoint.str().c_str(),
  327. TargetProfile.c_str(),
  328. unboundDescTab, 0, &pDxbcBlob, &pDxbcErrors));
  329. IFR(pDxbcBlob.QueryInterface(ppBlob));
  330. }
  331. else {
  332. dxc.Run(m_dllSupport, nullptr);
  333. IFRBOOL(dxc.RunResult == 0, E_FAIL);
  334. IFR(dxc.OpResult->GetResult(ppBlob));
  335. }
  336. return S_OK;
  337. }
  338. void CreateReflectionFromBlob(IDxcBlob *pBlob, ID3D12ShaderReflection **ppReflection) {
  339. CComPtr<IDxcContainerReflection> pReflection;
  340. UINT32 shaderIdx;
  341. m_dllSupport.CreateInstance(CLSID_DxcContainerReflection, &pReflection);
  342. VERIFY_SUCCEEDED(pReflection->Load(pBlob));
  343. VERIFY_SUCCEEDED(pReflection->FindFirstPartKind(hlsl::DFCC_DXIL, &shaderIdx));
  344. VERIFY_SUCCEEDED(pReflection->GetPartReflection(shaderIdx, __uuidof(ID3D12ShaderReflection), (void**)ppReflection));
  345. }
  346. void CreateReflectionFromDXBC(IDxcBlob *pBlob, ID3D12ShaderReflection **ppReflection) {
  347. VERIFY_SUCCEEDED(
  348. D3DReflect(pBlob->GetBufferPointer(), pBlob->GetBufferSize(),
  349. __uuidof(ID3D12ShaderReflection), (void **)ppReflection));
  350. }
  351. #endif // _WIN32 - Reflection unsupported
  352. void CompileToProgram(LPCSTR program, LPCWSTR entryPoint, LPCWSTR target,
  353. LPCWSTR *pArguments, UINT32 argCount,
  354. IDxcBlob **ppProgram) {
  355. CComPtr<IDxcCompiler> pCompiler;
  356. CComPtr<IDxcBlobEncoding> pSource;
  357. CComPtr<IDxcBlob> pProgram;
  358. CComPtr<IDxcOperationResult> pResult;
  359. VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
  360. CreateBlobFromText(program, &pSource);
  361. VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", entryPoint,
  362. target, pArguments, argCount, nullptr,
  363. 0, nullptr, &pResult));
  364. VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
  365. *ppProgram = pProgram.Detach();
  366. }
  367. bool DoesValidatorSupportDebugName() {
  368. CComPtr<IDxcVersionInfo> pVersionInfo;
  369. UINT Major, Minor;
  370. HRESULT hrVer = m_dllSupport.CreateInstance(CLSID_DxcValidator, &pVersionInfo);
  371. if (hrVer == E_NOINTERFACE) return false;
  372. VERIFY_SUCCEEDED(hrVer);
  373. VERIFY_SUCCEEDED(pVersionInfo->GetVersion(&Major, &Minor));
  374. return Major == 1 && (Minor >= 1);
  375. }
  376. std::string CompileToDebugName(LPCSTR program, LPCWSTR entryPoint,
  377. LPCWSTR target, LPCWSTR *pArguments, UINT32 argCount) {
  378. CComPtr<IDxcBlob> pProgram;
  379. CComPtr<IDxcBlob> pNameBlob;
  380. CComPtr<IDxcContainerReflection> pContainer;
  381. UINT32 index;
  382. CompileToProgram(program, entryPoint, target, pArguments, argCount, &pProgram);
  383. VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection, &pContainer));
  384. VERIFY_SUCCEEDED(pContainer->Load(pProgram));
  385. if (FAILED(pContainer->FindFirstPartKind(hlsl::DFCC_ShaderDebugName, &index))) {
  386. return std::string();
  387. }
  388. VERIFY_SUCCEEDED(pContainer->GetPartContent(index, &pNameBlob));
  389. const hlsl::DxilShaderDebugName *pDebugName = (hlsl::DxilShaderDebugName *)pNameBlob->GetBufferPointer();
  390. return std::string((const char *)(pDebugName + 1));
  391. }
  392. std::string DisassembleProgram(LPCSTR program, LPCWSTR entryPoint,
  393. LPCWSTR target) {
  394. CComPtr<IDxcCompiler> pCompiler;
  395. CComPtr<IDxcBlob> pProgram;
  396. CComPtr<IDxcBlobEncoding> pDisassembly;
  397. CompileToProgram(program, entryPoint, target, nullptr, 0, &pProgram);
  398. VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
  399. VERIFY_SUCCEEDED(pCompiler->Disassemble(pProgram, &pDisassembly));
  400. return BlobToUtf8(pDisassembly);
  401. }
  402. void SetupBasicHeader(hlsl::DxilContainerHeader *pHeader,
  403. uint32_t partCount = 0) {
  404. ZeroMemory(pHeader, sizeof(*pHeader));
  405. pHeader->HeaderFourCC = hlsl::DFCC_Container;
  406. pHeader->Version.Major = 1;
  407. pHeader->Version.Minor = 0;
  408. pHeader->PartCount = partCount;
  409. pHeader->ContainerSizeInBytes =
  410. sizeof(hlsl::DxilContainerHeader) +
  411. sizeof(uint32_t) * partCount +
  412. sizeof(hlsl::DxilPartHeader) * partCount;
  413. }
  414. void CodeGenTestCheck(LPCWSTR name) {
  415. std::wstring fullPath = hlsl_test::GetPathToHlslDataFile(name);
  416. FileRunTestResult t = FileRunTestResult::RunFromFileCommands(fullPath.c_str());
  417. if (t.RunResult != 0) {
  418. CA2W commentWide(t.ErrorMessage.c_str(), CP_UTF8);
  419. WEX::Logging::Log::Comment(commentWide);
  420. WEX::Logging::Log::Error(L"Run result is not zero");
  421. }
  422. }
  423. #ifdef _WIN32 // Reflection unsupported
  424. WEX::Common::String WStrFmt(const wchar_t* msg, ...) {
  425. va_list args;
  426. va_start(args, msg);
  427. WEX::Common::String result = WEX::Common::String().FormatV(msg, args);
  428. va_end(args);
  429. return result;
  430. }
  431. void ReflectionTest(LPCWSTR name, bool ignoreIfDXBCFails) {
  432. WEX::Logging::Log::Comment(WEX::Common::String().Format(L"Reflection comparison for %s", name));
  433. CComPtr<IDxcBlob> pProgram;
  434. CComPtr<IDxcBlob> pProgramDXBC;
  435. HRESULT hrDXBC = CompileFromFile(name, true, &pProgramDXBC);
  436. if (FAILED(hrDXBC)) {
  437. WEX::Logging::Log::Comment(L"Failed to compile DXBC blob.");
  438. if (ignoreIfDXBCFails) return;
  439. VERIFY_FAIL();
  440. }
  441. if (FAILED(CompileFromFile(name, false, &pProgram))) {
  442. WEX::Logging::Log::Comment(L"Failed to compile DXIL blob.");
  443. if (ignoreIfDXBCFails) return;
  444. VERIFY_FAIL();
  445. }
  446. CComPtr<ID3D12ShaderReflection> pProgramReflection;
  447. CComPtr<ID3D12ShaderReflection> pProgramReflectionDXBC;
  448. CreateReflectionFromBlob(pProgram, &pProgramReflection);
  449. CreateReflectionFromDXBC(pProgramDXBC, &pProgramReflectionDXBC);
  450. CompareReflection(pProgramReflection, pProgramReflectionDXBC);
  451. }
  452. #endif // _WIN32 - Reflection unsupported
  453. };
  454. bool DxilContainerTest::InitSupport() {
  455. if (!m_dllSupport.IsEnabled()) {
  456. VERIFY_SUCCEEDED(m_dllSupport.Initialize());
  457. m_ver.Initialize(m_dllSupport);
  458. }
  459. return true;
  460. }
  461. #ifdef _WIN32
  462. TEST_F(DxilContainerTest, CompileWhenDebugSourceThenSourceMatters) {
  463. char program1[] = "float4 main() : SV_Target { return 0; }";
  464. char program2[] = " float4 main() : SV_Target { return 0; } ";
  465. LPCWSTR Zi[] = { L"/Zi", L"/Qembed_debug" };
  466. LPCWSTR ZiZss[] = { L"/Zi", L"/Qembed_debug", L"/Zss" };
  467. LPCWSTR ZiZsb[] = { L"/Zi", L"/Qembed_debug", L"/Zsb" };
  468. // No debug info, no debug name...
  469. std::string noName = CompileToDebugName(program1, L"main", L"ps_6_0", nullptr, 0);
  470. VERIFY_IS_TRUE(noName.empty());
  471. if (!DoesValidatorSupportDebugName())
  472. return;
  473. // Debug info, default to source name.
  474. std::string sourceName1 = CompileToDebugName(program1, L"main", L"ps_6_0", Zi, _countof(Zi));
  475. VERIFY_IS_FALSE(sourceName1.empty());
  476. // Deterministic naming.
  477. std::string sourceName1Again = CompileToDebugName(program1, L"main", L"ps_6_0", Zi, _countof(Zi));
  478. VERIFY_ARE_EQUAL_STR(sourceName1.c_str(), sourceName1Again.c_str());
  479. // Changes in source become changes in name.
  480. std::string sourceName2 = CompileToDebugName(program2, L"main", L"ps_6_0", Zi, _countof(Zi));
  481. VERIFY_IS_FALSE(0 == strcmp(sourceName2.c_str(), sourceName1.c_str()));
  482. // Source again, different because different switches are specified.
  483. std::string sourceName1Zss = CompileToDebugName(program1, L"main", L"ps_6_0", ZiZss, _countof(ZiZss));
  484. VERIFY_IS_FALSE(0 == strcmp(sourceName1Zss.c_str(), sourceName1.c_str()));
  485. // Binary program 1 and 2 should be different from source and equal to each other.
  486. std::string binName1 = CompileToDebugName(program1, L"main", L"ps_6_0", ZiZsb, _countof(ZiZsb));
  487. std::string binName2 = CompileToDebugName(program2, L"main", L"ps_6_0", ZiZsb, _countof(ZiZsb));
  488. VERIFY_ARE_EQUAL_STR(binName1.c_str(), binName2.c_str());
  489. VERIFY_IS_FALSE(0 == strcmp(sourceName1Zss.c_str(), binName1.c_str()));
  490. }
  491. #endif // _WIN32
  492. TEST_F(DxilContainerTest, CompileWhenOKThenIncludesSignatures) {
  493. char program[] =
  494. "struct PSInput {\r\n"
  495. " float4 position : SV_POSITION;\r\n"
  496. " float4 color : COLOR;\r\n"
  497. "};\r\n"
  498. "PSInput VSMain(float4 position : POSITION, float4 color : COLOR) {\r\n"
  499. " PSInput result;\r\n"
  500. " result.position = position;\r\n"
  501. " result.color = color;\r\n"
  502. " return result;\r\n"
  503. "}\r\n"
  504. "float4 PSMain(PSInput input) : SV_TARGET {\r\n"
  505. " return input.color;\r\n"
  506. "}";
  507. {
  508. std::string s = DisassembleProgram(program, L"VSMain", L"vs_6_0");
  509. // NOTE: this will change when proper packing is done, and when 'always-writes' is accurately implemented.
  510. const char expected[] =
  511. ";\n"
  512. "; Input signature:\n"
  513. ";\n"
  514. "; Name Index Mask Register SysValue Format Used\n"
  515. "; -------------------- ----- ------ -------- -------- ------- ------\n"
  516. "; POSITION 0 xyzw 0 NONE float \n" // should read 'xyzw' in Used
  517. "; COLOR 0 xyzw 1 NONE float \n" // should read '1' in register
  518. ";\n"
  519. ";\n"
  520. "; Output signature:\n"
  521. ";\n"
  522. "; Name Index Mask Register SysValue Format Used\n"
  523. "; -------------------- ----- ------ -------- -------- ------- ------\n"
  524. "; SV_Position 0 xyzw 0 POS float xyzw\n" // could read SV_POSITION
  525. "; COLOR 0 xyzw 1 NONE float xyzw\n"; // should read '1' in register
  526. std::string start(s.c_str(), strlen(expected));
  527. VERIFY_ARE_EQUAL_STR(expected, start.c_str());
  528. }
  529. {
  530. std::string s = DisassembleProgram(program, L"PSMain", L"ps_6_0");
  531. // NOTE: this will change when proper packing is done, and when 'always-writes' is accurately implemented.
  532. const char expected[] =
  533. ";\n"
  534. "; Input signature:\n"
  535. ";\n"
  536. "; Name Index Mask Register SysValue Format Used\n"
  537. "; -------------------- ----- ------ -------- -------- ------- ------\n"
  538. "; SV_Position 0 xyzw 0 POS float \n" // could read SV_POSITION
  539. "; COLOR 0 xyzw 1 NONE float \n" // should read '1' in register, xyzw in Used
  540. ";\n"
  541. ";\n"
  542. "; Output signature:\n"
  543. ";\n"
  544. "; Name Index Mask Register SysValue Format Used\n"
  545. "; -------------------- ----- ------ -------- -------- ------- ------\n"
  546. "; SV_Target 0 xyzw 0 TARGET float xyzw\n";// could read SV_TARGET
  547. std::string start(s.c_str(), strlen(expected));
  548. VERIFY_ARE_EQUAL_STR(expected, start.c_str());
  549. }
  550. }
  551. TEST_F(DxilContainerTest, CompileWhenSigSquareThenIncludeSplit) {
  552. #if 0 // TODO: reenable test when multiple rows are supported.
  553. const char program[] =
  554. "float main(float4x4 a : A, int4 b : B) : SV_Target {\n"
  555. " return a[b.x][b.y];\n"
  556. "}";
  557. std::string s = DisassembleProgram(program, L"main", L"ps_6_0");
  558. const char expected[] =
  559. "// Input signature:\n"
  560. "//\n"
  561. "// Name Index Mask Register SysValue Format Used\n"
  562. "// -------------------- ----- ------ -------- -------- ------- ------\n"
  563. "// A 0 xyzw 0 NONE float xyzw\n"
  564. "// A 1 xyzw 1 NONE float xyzw\n"
  565. "// A 2 xyzw 2 NONE float xyzw\n"
  566. "// A 3 xyzw 3 NONE float xyzw\n"
  567. "// B 0 xyzw 4 NONE int xy\n"
  568. "//\n"
  569. "//\n"
  570. "// Output signature:\n"
  571. "//\n"
  572. "// Name Index Mask Register SysValue Format Used\n"
  573. "// -------------------- ----- ------ -------- -------- ------- ------\n"
  574. "// SV_Target 0 x 0 TARGET float x\n";
  575. std::string start(s.c_str(), strlen(expected));
  576. VERIFY_ARE_EQUAL_STR(expected, start.c_str());
  577. #endif
  578. }
  579. TEST_F(DxilContainerTest, CompileWhenOkThenCheckRDAT) {
  580. if (m_ver.SkipDxilVersion(1, 3)) return;
  581. const char *shader = "float c_buf;"
  582. "RWTexture1D<int4> tex : register(u5);"
  583. "Texture1D<float4> tex2 : register(t0);"
  584. "RWByteAddressBuffer b_buf;"
  585. "struct Foo { float2 f2; int2 i2; };"
  586. "AppendStructuredBuffer<Foo> append_buf;"
  587. "ConsumeStructuredBuffer<Foo> consume_buf;"
  588. "RasterizerOrderedByteAddressBuffer rov_buf;"
  589. "globallycoherent RWByteAddressBuffer gc_buf;"
  590. "float function_import(float x);"
  591. "export float function0(min16float x) { "
  592. " return x + 1 + tex[0].x; }"
  593. "export float function1(float x, min12int i) {"
  594. " return x + c_buf + b_buf.Load(x) + tex2[i].x; }"
  595. "export float function2(float x) { return x + function_import(x); }"
  596. "export void function3(int i) {"
  597. " Foo f = consume_buf.Consume();"
  598. " f.f2 += 0.5; append_buf.Append(f);"
  599. " rov_buf.Store(i, f.i2.x);"
  600. " gc_buf.Store(i, f.i2.y);"
  601. " b_buf.Store(i, f.i2.x + f.i2.y); }";
  602. CComPtr<IDxcCompiler> pCompiler;
  603. CComPtr<IDxcBlobEncoding> pSource;
  604. CComPtr<IDxcBlob> pProgram;
  605. CComPtr<IDxcBlobEncoding> pDisassembly;
  606. CComPtr<IDxcOperationResult> pResult;
  607. struct CheckResFlagInfo { std::string name; hlsl::DXIL::ResourceKind kind; hlsl::RDAT::DxilResourceFlag flag; };
  608. const unsigned numResFlagCheck = 5;
  609. CheckResFlagInfo resFlags[numResFlagCheck] = {
  610. { "b_buf", hlsl::DXIL::ResourceKind::RawBuffer, hlsl::RDAT::DxilResourceFlag::None },
  611. { "append_buf", hlsl::DXIL::ResourceKind::StructuredBuffer, hlsl::RDAT::DxilResourceFlag::UAVCounter },
  612. { "consume_buf", hlsl::DXIL::ResourceKind::StructuredBuffer, hlsl::RDAT::DxilResourceFlag::UAVCounter },
  613. { "gc_buf", hlsl::DXIL::ResourceKind::RawBuffer, hlsl::RDAT::DxilResourceFlag::UAVGloballyCoherent },
  614. { "rov_buf", hlsl::DXIL::ResourceKind::RawBuffer, hlsl::RDAT::DxilResourceFlag::UAVRasterizerOrderedView }
  615. };
  616. VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
  617. CreateBlobFromText(shader, &pSource);
  618. VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main",
  619. L"lib_6_3", nullptr, 0, nullptr, 0,
  620. nullptr, &pResult));
  621. HRESULT hrStatus;
  622. VERIFY_SUCCEEDED(pResult->GetStatus(&hrStatus));
  623. VERIFY_SUCCEEDED(hrStatus);
  624. VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
  625. CComPtr<IDxcContainerReflection> containerReflection;
  626. uint32_t partCount;
  627. IFT(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection, &containerReflection));
  628. IFT(containerReflection->Load(pProgram));
  629. IFT(containerReflection->GetPartCount(&partCount));
  630. bool blobFound = false;
  631. for (uint32_t i = 0; i < partCount; ++i) {
  632. uint32_t kind;
  633. IFT(containerReflection->GetPartKind(i, &kind));
  634. if (kind == (uint32_t)hlsl::DxilFourCC::DFCC_RuntimeData) {
  635. blobFound = true;
  636. using namespace hlsl::RDAT;
  637. CComPtr<IDxcBlob> pBlob;
  638. IFT(containerReflection->GetPartContent(i, &pBlob));
  639. // Validate using DxilRuntimeData
  640. DxilRuntimeData context;
  641. context.InitFromRDAT((char *)pBlob->GetBufferPointer(), pBlob->GetBufferSize());
  642. FunctionTableReader *funcTableReader = context.GetFunctionTableReader();
  643. ResourceTableReader *resTableReader = context.GetResourceTableReader();
  644. VERIFY_ARE_EQUAL(funcTableReader->GetNumFunctions(), 4);
  645. std::string str("function");
  646. for (uint32_t j = 0; j < funcTableReader->GetNumFunctions(); ++j) {
  647. FunctionReader funcReader = funcTableReader->GetItem(j);
  648. std::string funcName(funcReader.GetUnmangledName());
  649. VERIFY_IS_TRUE(str.compare(funcName.substr(0,8)) == 0);
  650. std::string cur_str = str;
  651. cur_str.push_back('0' + j);
  652. if (cur_str.compare("function0") == 0) {
  653. VERIFY_ARE_EQUAL(funcReader.GetNumResources(), 1);
  654. hlsl::ShaderFlags flag;
  655. flag.SetUAVLoadAdditionalFormats(true);
  656. flag.SetLowPrecisionPresent(true);
  657. uint64_t rawFlag = flag.GetFeatureInfo();
  658. VERIFY_ARE_EQUAL(funcReader.GetFeatureFlag(), rawFlag);
  659. ResourceReader resReader = funcReader.GetResource(0);
  660. VERIFY_ARE_EQUAL(resReader.GetResourceClass(), hlsl::DXIL::ResourceClass::UAV);
  661. VERIFY_ARE_EQUAL(resReader.GetResourceKind(), hlsl::DXIL::ResourceKind::Texture1D);
  662. }
  663. else if (cur_str.compare("function1") == 0) {
  664. hlsl::ShaderFlags flag;
  665. flag.SetLowPrecisionPresent(true);
  666. uint64_t rawFlag = flag.GetFeatureInfo();
  667. VERIFY_ARE_EQUAL(funcReader.GetFeatureFlag(), rawFlag);
  668. VERIFY_ARE_EQUAL(funcReader.GetNumResources(), 3);
  669. }
  670. else if (cur_str.compare("function2") == 0) {
  671. VERIFY_ARE_EQUAL(funcReader.GetFeatureFlag() & 0xffffffffffffffff, 0);
  672. VERIFY_ARE_EQUAL(funcReader.GetNumResources(), 0);
  673. std::string dependency = funcReader.GetDependency(0);
  674. VERIFY_IS_TRUE(dependency.find("function_import") != std::string::npos);
  675. }
  676. else if (cur_str.compare("function3") == 0) {
  677. VERIFY_ARE_EQUAL(funcReader.GetFeatureFlag() & 0xffffffffffffffff, 0);
  678. VERIFY_ARE_EQUAL(funcReader.GetNumResources(), numResFlagCheck);
  679. for (unsigned i = 0; i < funcReader.GetNumResources(); ++i) {
  680. ResourceReader resReader = funcReader.GetResource(0);
  681. VERIFY_ARE_EQUAL(resReader.GetResourceClass(), hlsl::DXIL::ResourceClass::UAV);
  682. unsigned j = 0;
  683. for (; j < numResFlagCheck; ++j) {
  684. if (resFlags[j].name.compare(resReader.GetName()) == 0)
  685. break;
  686. }
  687. VERIFY_IS_LESS_THAN(j, numResFlagCheck);
  688. VERIFY_ARE_EQUAL(resReader.GetResourceKind(), resFlags[j].kind);
  689. VERIFY_ARE_EQUAL(resReader.GetFlags(), static_cast<uint32_t>(resFlags[j].flag));
  690. }
  691. }
  692. else {
  693. IFTBOOLMSG(false, E_FAIL, "unknown function name");
  694. }
  695. }
  696. VERIFY_ARE_EQUAL(resTableReader->GetNumResources(), 8);
  697. // This is validation test for DxilRuntimeReflection implemented on DxilRuntimeReflection.inl
  698. unique_ptr<DxilRuntimeReflection> pReflection(CreateDxilRuntimeReflection());
  699. VERIFY_IS_TRUE(pReflection->InitFromRDAT(pBlob->GetBufferPointer(), pBlob->GetBufferSize()));
  700. DxilLibraryDesc lib_reflection = pReflection->GetLibraryReflection();
  701. VERIFY_ARE_EQUAL(lib_reflection.NumFunctions, 4);
  702. for (uint32_t j = 0; j < 3; ++j) {
  703. DxilFunctionDesc function = lib_reflection.pFunction[j];
  704. std::string cur_str = str;
  705. cur_str.push_back('0' + j);
  706. if (cur_str.compare("function0") == 0) {
  707. hlsl::ShaderFlags flag;
  708. flag.SetUAVLoadAdditionalFormats(true);
  709. flag.SetLowPrecisionPresent(true);
  710. uint64_t rawFlag = flag.GetFeatureInfo();
  711. uint64_t featureFlag = static_cast<uint64_t>(function.FeatureInfo2) << 32;
  712. featureFlag |= static_cast<uint64_t>(function.FeatureInfo1);
  713. VERIFY_ARE_EQUAL(featureFlag, rawFlag);
  714. VERIFY_ARE_EQUAL(function.NumResources, 1);
  715. VERIFY_ARE_EQUAL(function.NumFunctionDependencies, 0);
  716. const DxilResourceDesc &resource = *function.Resources[0];
  717. VERIFY_ARE_EQUAL(resource.Class, (uint32_t)hlsl::DXIL::ResourceClass::UAV);
  718. VERIFY_ARE_EQUAL(resource.Kind, (uint32_t)hlsl::DXIL::ResourceKind::Texture1D);
  719. std::wstring wName = resource.Name;
  720. VERIFY_ARE_EQUAL(wName.compare(L"tex"), 0);
  721. }
  722. else if (cur_str.compare("function1") == 0) {
  723. hlsl::ShaderFlags flag;
  724. flag.SetLowPrecisionPresent(true);
  725. uint64_t rawFlag = flag.GetFeatureInfo();
  726. uint64_t featureFlag = static_cast<uint64_t>(function.FeatureInfo2) << 32;
  727. featureFlag |= static_cast<uint64_t>(function.FeatureInfo1);
  728. VERIFY_ARE_EQUAL(featureFlag, rawFlag);
  729. VERIFY_ARE_EQUAL(function.NumResources, 3);
  730. VERIFY_ARE_EQUAL(function.NumFunctionDependencies, 0);
  731. std::unordered_set<std::wstring> stringSet = { L"$Globals", L"b_buf", L"tex2" };
  732. for (uint32_t j = 0; j < 3; ++j) {
  733. const DxilResourceDesc &resource = *function.Resources[j];
  734. std::wstring compareName = resource.Name;
  735. VERIFY_IS_TRUE(stringSet.find(compareName) != stringSet.end());
  736. }
  737. }
  738. else if (cur_str.compare("function2") == 0) {
  739. VERIFY_ARE_EQUAL(function.FeatureInfo1, 0);
  740. VERIFY_ARE_EQUAL(function.FeatureInfo2, 0);
  741. VERIFY_ARE_EQUAL(function.NumResources, 0);
  742. VERIFY_ARE_EQUAL(function.NumFunctionDependencies, 1);
  743. std::wstring dependency = function.FunctionDependencies[0];
  744. VERIFY_IS_TRUE(dependency.find(L"function_import") != std::wstring::npos);
  745. }
  746. else if (cur_str.compare("function3") == 0) {
  747. VERIFY_ARE_EQUAL(function.FeatureInfo1, 0);
  748. VERIFY_ARE_EQUAL(function.FeatureInfo2, 0);
  749. VERIFY_ARE_EQUAL(function.NumResources, numResFlagCheck);
  750. VERIFY_ARE_EQUAL(function.NumFunctionDependencies, 0);
  751. for (unsigned i = 0; i < function.NumResources; ++i) {
  752. const DxilResourceDesc *res = function.Resources[i];
  753. VERIFY_ARE_EQUAL(res->Class, static_cast<uint32_t>(hlsl::DXIL::ResourceClass::UAV));
  754. unsigned j = 0;
  755. for (; j < numResFlagCheck; ++j) {
  756. CA2W WName(resFlags[j].name.c_str());
  757. std::wstring compareName(WName);
  758. if (compareName.compare(res->Name) == 0)
  759. break;
  760. }
  761. VERIFY_IS_LESS_THAN(j, numResFlagCheck);
  762. VERIFY_ARE_EQUAL(res->Kind, static_cast<uint32_t>(resFlags[j].kind));
  763. VERIFY_ARE_EQUAL(res->Flags, static_cast<uint32_t>(resFlags[j].flag));
  764. }
  765. }
  766. else {
  767. IFTBOOLMSG(false, E_FAIL, "unknown function name");
  768. }
  769. }
  770. VERIFY_IS_TRUE(lib_reflection.NumResources == 8);
  771. }
  772. }
  773. IFTBOOLMSG(blobFound, E_FAIL, "failed to find RDAT blob after compiling");
  774. }
  775. TEST_F(DxilContainerTest, CompileWhenOkThenCheckRDAT2) {
  776. if (m_ver.SkipDxilVersion(1, 3)) return;
  777. // This is a case when the user of resource is a constant, not instruction.
  778. // Compiler generates the following load instruction for texture.
  779. // load %class.Texture2D, %class.Texture2D* getelementptr inbounds ([3 x
  780. // %class.Texture2D], [3 x %class.Texture2D]*
  781. // @"\01?ThreeTextures@@3PAV?$Texture2D@M@@A", i32 0, i32 0), align 4
  782. const char *shader =
  783. "SamplerState Sampler : register(s0); RWBuffer<float> Uav : "
  784. "register(u0); Texture2D<float> ThreeTextures[3] : register(t0); "
  785. "float function1();"
  786. "[shader(\"raygeneration\")] void RayGenMain() { Uav[0] = "
  787. "ThreeTextures[0].SampleLevel(Sampler, float2(0, 0), 0) + "
  788. "ThreeTextures[2].SampleLevel(Sampler, float2(0, 0), 0) + function1(); }";
  789. CComPtr<IDxcCompiler> pCompiler;
  790. CComPtr<IDxcBlobEncoding> pSource;
  791. CComPtr<IDxcBlob> pProgram;
  792. CComPtr<IDxcBlobEncoding> pDisassembly;
  793. CComPtr<IDxcOperationResult> pResult;
  794. HRESULT status;
  795. VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
  796. CreateBlobFromText(shader, &pSource);
  797. VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main",
  798. L"lib_6_3", nullptr, 0, nullptr, 0,
  799. nullptr, &pResult));
  800. VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
  801. VERIFY_SUCCEEDED(pResult->GetStatus(&status));
  802. VERIFY_SUCCEEDED(status);
  803. CComPtr<IDxcContainerReflection> pReflection;
  804. uint32_t partCount;
  805. IFT(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection, &pReflection));
  806. IFT(pReflection->Load(pProgram));
  807. IFT(pReflection->GetPartCount(&partCount));
  808. bool blobFound = false;
  809. for (uint32_t i = 0; i < partCount; ++i) {
  810. uint32_t kind;
  811. IFT(pReflection->GetPartKind(i, &kind));
  812. if (kind == (uint32_t)hlsl::DxilFourCC::DFCC_RuntimeData) {
  813. blobFound = true;
  814. using namespace hlsl::RDAT;
  815. CComPtr<IDxcBlob> pBlob;
  816. IFT(pReflection->GetPartContent(i, &pBlob));
  817. DxilRuntimeData context;
  818. context.InitFromRDAT((char *)pBlob->GetBufferPointer(), pBlob->GetBufferSize());
  819. FunctionTableReader *funcTableReader = context.GetFunctionTableReader();
  820. ResourceTableReader *resTableReader = context.GetResourceTableReader();
  821. VERIFY_IS_TRUE(funcTableReader->GetNumFunctions() == 1);
  822. VERIFY_IS_TRUE(resTableReader->GetNumResources() == 3);
  823. FunctionReader funcReader = funcTableReader->GetItem(0);
  824. llvm::StringRef name(funcReader.GetUnmangledName());
  825. VERIFY_IS_TRUE(name.compare("RayGenMain") == 0);
  826. VERIFY_IS_TRUE(funcReader.GetShaderKind() ==
  827. hlsl::DXIL::ShaderKind::RayGeneration);
  828. VERIFY_IS_TRUE(funcReader.GetNumResources() == 3);
  829. VERIFY_IS_TRUE(funcReader.GetNumDependencies() == 1);
  830. llvm::StringRef dependencyName =
  831. hlsl::dxilutil::DemangleFunctionName(funcReader.GetDependency(0));
  832. VERIFY_IS_TRUE(dependencyName.compare("function1") == 0);
  833. }
  834. }
  835. IFTBOOLMSG(blobFound, E_FAIL, "failed to find RDAT blob after compiling");
  836. }
  837. static uint32_t EncodedVersion_lib_6_3 = hlsl::EncodeVersion(hlsl::DXIL::ShaderKind::Library, 6, 3);
  838. static uint32_t EncodedVersion_vs_6_3 = hlsl::EncodeVersion(hlsl::DXIL::ShaderKind::Vertex, 6, 3);
  839. static void Ref1_CheckCBuffer_Globals(ID3D12ShaderReflectionConstantBuffer *pCBReflection, D3D12_SHADER_BUFFER_DESC &cbDesc) {
  840. std::string cbName = cbDesc.Name;
  841. VERIFY_IS_TRUE(cbName.compare("$Globals") == 0);
  842. VERIFY_ARE_EQUAL(cbDesc.Size, 16);
  843. VERIFY_ARE_EQUAL(cbDesc.Type, D3D_CT_CBUFFER);
  844. VERIFY_ARE_EQUAL(cbDesc.Variables, 1);
  845. // cbval1
  846. ID3D12ShaderReflectionVariable *pVar = pCBReflection->GetVariableByIndex(0);
  847. D3D12_SHADER_VARIABLE_DESC varDesc;
  848. VERIFY_SUCCEEDED(pVar->GetDesc(&varDesc));
  849. VERIFY_ARE_EQUAL_STR(varDesc.Name, "cbval1");
  850. VERIFY_ARE_EQUAL(varDesc.StartOffset, 0);
  851. VERIFY_ARE_EQUAL(varDesc.Size, 4);
  852. // TODO: verify rest of variable
  853. ID3D12ShaderReflectionType *pType = pVar->GetType();
  854. D3D12_SHADER_TYPE_DESC tyDesc;
  855. VERIFY_SUCCEEDED(pType->GetDesc(&tyDesc));
  856. VERIFY_ARE_EQUAL(tyDesc.Class, D3D_SVC_SCALAR);
  857. VERIFY_ARE_EQUAL(tyDesc.Type, D3D_SVT_FLOAT);
  858. // TODO: verify rest of type
  859. }
  860. static void Ref1_CheckCBuffer_MyCB(ID3D12ShaderReflectionConstantBuffer *pCBReflection, D3D12_SHADER_BUFFER_DESC &cbDesc) {
  861. std::string cbName = cbDesc.Name;
  862. VERIFY_IS_TRUE(cbName.compare("MyCB") == 0);
  863. VERIFY_ARE_EQUAL(cbDesc.Size, 32);
  864. VERIFY_ARE_EQUAL(cbDesc.Type, D3D_CT_CBUFFER);
  865. VERIFY_ARE_EQUAL(cbDesc.Variables, 2);
  866. // cbval2
  867. {
  868. ID3D12ShaderReflectionVariable *pVar = pCBReflection->GetVariableByIndex(0);
  869. D3D12_SHADER_VARIABLE_DESC varDesc;
  870. VERIFY_SUCCEEDED(pVar->GetDesc(&varDesc));
  871. VERIFY_ARE_EQUAL_STR(varDesc.Name, "cbval2");
  872. VERIFY_ARE_EQUAL(varDesc.StartOffset, 0);
  873. VERIFY_ARE_EQUAL(varDesc.Size, 16);
  874. // TODO: verify rest of variable
  875. ID3D12ShaderReflectionType *pType = pVar->GetType();
  876. D3D12_SHADER_TYPE_DESC tyDesc;
  877. VERIFY_SUCCEEDED(pType->GetDesc(&tyDesc));
  878. VERIFY_ARE_EQUAL(tyDesc.Class, D3D_SVC_VECTOR);
  879. VERIFY_ARE_EQUAL(tyDesc.Type, D3D_SVT_INT);
  880. // TODO: verify rest of type
  881. }
  882. // cbval3
  883. {
  884. ID3D12ShaderReflectionVariable *pVar = pCBReflection->GetVariableByIndex(1);
  885. D3D12_SHADER_VARIABLE_DESC varDesc;
  886. VERIFY_SUCCEEDED(pVar->GetDesc(&varDesc));
  887. VERIFY_ARE_EQUAL_STR(varDesc.Name, "cbval3");
  888. VERIFY_ARE_EQUAL(varDesc.StartOffset, 16);
  889. VERIFY_ARE_EQUAL(varDesc.Size, 16);
  890. // TODO: verify rest of variable
  891. ID3D12ShaderReflectionType *pType = pVar->GetType();
  892. D3D12_SHADER_TYPE_DESC tyDesc;
  893. VERIFY_SUCCEEDED(pType->GetDesc(&tyDesc));
  894. VERIFY_ARE_EQUAL(tyDesc.Class, D3D_SVC_VECTOR);
  895. VERIFY_ARE_EQUAL(tyDesc.Type, D3D_SVT_INT);
  896. // TODO: verify rest of type
  897. }
  898. }
  899. static void Ref1_CheckBinding_Globals(D3D12_SHADER_INPUT_BIND_DESC &resDesc) {
  900. std::string resName = resDesc.Name;
  901. VERIFY_IS_TRUE(resName.compare("$Globals") == 0);
  902. VERIFY_ARE_EQUAL(resDesc.Type, D3D_SIT_CBUFFER);
  903. // not explicitly bound:
  904. VERIFY_ARE_EQUAL(resDesc.BindPoint, 4294967295);
  905. VERIFY_ARE_EQUAL(resDesc.Space, 0);
  906. VERIFY_ARE_EQUAL(resDesc.BindCount, 1);
  907. }
  908. static void Ref1_CheckBinding_MyCB(D3D12_SHADER_INPUT_BIND_DESC &resDesc) {
  909. std::string resName = resDesc.Name;
  910. VERIFY_IS_TRUE(resName.compare("MyCB") == 0);
  911. VERIFY_ARE_EQUAL(resDesc.Type, D3D_SIT_CBUFFER);
  912. VERIFY_ARE_EQUAL(resDesc.BindPoint, 11);
  913. VERIFY_ARE_EQUAL(resDesc.Space, 2);
  914. VERIFY_ARE_EQUAL(resDesc.BindCount, 1);
  915. }
  916. static void Ref1_CheckBinding_tex(D3D12_SHADER_INPUT_BIND_DESC &resDesc) {
  917. std::string resName = resDesc.Name;
  918. VERIFY_IS_TRUE(resName.compare("tex") == 0);
  919. VERIFY_ARE_EQUAL(resDesc.Type, D3D_SIT_UAV_RWTYPED);
  920. VERIFY_ARE_EQUAL(resDesc.BindPoint, 5);
  921. VERIFY_ARE_EQUAL(resDesc.Space, 0);
  922. VERIFY_ARE_EQUAL(resDesc.BindCount, 1);
  923. }
  924. static void Ref1_CheckBinding_tex2(D3D12_SHADER_INPUT_BIND_DESC &resDesc) {
  925. std::string resName = resDesc.Name;
  926. VERIFY_IS_TRUE(resName.compare("tex2") == 0);
  927. VERIFY_ARE_EQUAL(resDesc.Type, D3D_SIT_TEXTURE);
  928. VERIFY_ARE_EQUAL(resDesc.BindPoint, 0);
  929. VERIFY_ARE_EQUAL(resDesc.Space, 0);
  930. VERIFY_ARE_EQUAL(resDesc.BindCount, 1);
  931. }
  932. static void Ref1_CheckBinding_samp(D3D12_SHADER_INPUT_BIND_DESC &resDesc) {
  933. std::string resName = resDesc.Name;
  934. VERIFY_IS_TRUE(resName.compare("samp") == 0);
  935. VERIFY_ARE_EQUAL(resDesc.Type, D3D_SIT_SAMPLER);
  936. VERIFY_ARE_EQUAL(resDesc.BindPoint, 7);
  937. VERIFY_ARE_EQUAL(resDesc.Space, 0);
  938. VERIFY_ARE_EQUAL(resDesc.BindCount, 1);
  939. }
  940. static void Ref1_CheckBinding_b_buf(D3D12_SHADER_INPUT_BIND_DESC &resDesc) {
  941. std::string resName = resDesc.Name;
  942. VERIFY_IS_TRUE(resName.compare("b_buf") == 0);
  943. VERIFY_ARE_EQUAL(resDesc.Type, D3D_SIT_UAV_RWBYTEADDRESS);
  944. // not explicitly bound:
  945. VERIFY_ARE_EQUAL(resDesc.BindPoint, 4294967295);
  946. VERIFY_ARE_EQUAL(resDesc.Space, 0);
  947. VERIFY_ARE_EQUAL(resDesc.BindCount, 1);
  948. }
  949. TEST_F(DxilContainerTest, CompileWhenOkThenCheckReflection1) {
  950. if (m_ver.SkipDxilVersion(1, 3)) return;
  951. const char *shader =
  952. "float cbval1;"
  953. "cbuffer MyCB : register(b11, space2) { int4 cbval2, cbval3; }"
  954. "RWTexture1D<int4> tex : register(u5);"
  955. "Texture1D<float4> tex2 : register(t0);"
  956. "SamplerState samp : register(s7);"
  957. "RWByteAddressBuffer b_buf;"
  958. "export float function0(min16float x) { "
  959. " return x + cbval2.x + tex[0].x; }"
  960. "export float function1(float x, min12int i) {"
  961. " return x + cbval1 + b_buf.Load(x) + tex2.Sample(samp, x).x; }"
  962. "[shader(\"vertex\")]"
  963. "float function2(float4 x : POSITION) : SV_Position { return x + cbval1 + cbval3.x; }";
  964. CComPtr<IDxcCompiler> pCompiler;
  965. CComPtr<IDxcBlobEncoding> pSource;
  966. CComPtr<IDxcBlob> pProgram;
  967. CComPtr<IDxcBlobEncoding> pDisassembly;
  968. CComPtr<IDxcOperationResult> pResult;
  969. CComPtr<ID3D12LibraryReflection> pLibraryReflection;
  970. VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
  971. CreateBlobFromText(shader, &pSource);
  972. VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"",
  973. L"lib_6_3", nullptr, 0, nullptr, 0,
  974. nullptr, &pResult));
  975. VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
  976. CComPtr<IDxcContainerReflection> containerReflection;
  977. uint32_t partCount;
  978. VERIFY_SUCCEEDED(m_dllSupport.CreateInstance(CLSID_DxcContainerReflection, &containerReflection));
  979. VERIFY_SUCCEEDED(containerReflection->Load(pProgram));
  980. VERIFY_SUCCEEDED(containerReflection->GetPartCount(&partCount));
  981. bool blobFound = false;
  982. for (uint32_t i = 0; i < partCount; ++i) {
  983. uint32_t kind;
  984. VERIFY_SUCCEEDED(containerReflection->GetPartKind(i, &kind));
  985. if (kind == (uint32_t)hlsl::DxilFourCC::DFCC_DXIL) {
  986. blobFound = true;
  987. VERIFY_SUCCEEDED(containerReflection->GetPartReflection(i, IID_PPV_ARGS(&pLibraryReflection)));
  988. D3D12_LIBRARY_DESC LibDesc;
  989. VERIFY_SUCCEEDED(pLibraryReflection->GetDesc(&LibDesc));
  990. VERIFY_ARE_EQUAL(LibDesc.FunctionCount, 3);
  991. for (INT iFn = 0; iFn < (INT)LibDesc.FunctionCount; iFn++) {
  992. ID3D12FunctionReflection *pFunctionReflection = pLibraryReflection->GetFunctionByIndex(iFn);
  993. D3D12_FUNCTION_DESC FnDesc;
  994. pFunctionReflection->GetDesc(&FnDesc);
  995. std::string Name = FnDesc.Name;
  996. if (Name.compare("\01?function0@@YAM$min16f@@Z") == 0) {
  997. VERIFY_ARE_EQUAL(FnDesc.Version, EncodedVersion_lib_6_3);
  998. VERIFY_ARE_EQUAL(FnDesc.ConstantBuffers, 1);
  999. VERIFY_ARE_EQUAL(FnDesc.BoundResources, 2);
  1000. D3D12_SHADER_BUFFER_DESC cbDesc;
  1001. ID3D12ShaderReflectionConstantBuffer *pCBReflection = pFunctionReflection->GetConstantBufferByIndex(0);
  1002. VERIFY_SUCCEEDED(pCBReflection->GetDesc(&cbDesc));
  1003. std::string cbName = cbDesc.Name;
  1004. (void)(cbName);
  1005. Ref1_CheckCBuffer_MyCB(pCBReflection, cbDesc);
  1006. for (INT iRes = 0; iRes < (INT)FnDesc.BoundResources; iRes++) {
  1007. D3D12_SHADER_INPUT_BIND_DESC resDesc;
  1008. pFunctionReflection->GetResourceBindingDesc(iRes, &resDesc);
  1009. std::string resName = resDesc.Name;
  1010. if (resName.compare("$Globals") == 0) {
  1011. Ref1_CheckBinding_Globals(resDesc);
  1012. } else if (resName.compare("MyCB") == 0) {
  1013. Ref1_CheckBinding_MyCB(resDesc);
  1014. } else if (resName.compare("samp") == 0) {
  1015. Ref1_CheckBinding_samp(resDesc);
  1016. } else if (resName.compare("tex") == 0) {
  1017. Ref1_CheckBinding_tex(resDesc);
  1018. } else if (resName.compare("tex2") == 0) {
  1019. Ref1_CheckBinding_tex2(resDesc);
  1020. } else if (resName.compare("b_buf") == 0) {
  1021. Ref1_CheckBinding_b_buf(resDesc);
  1022. } else {
  1023. VERIFY_FAIL(L"Unexpected resource used");
  1024. }
  1025. }
  1026. } else if (Name.compare("\01?function1@@YAMM$min12i@@Z") == 0) {
  1027. VERIFY_ARE_EQUAL(FnDesc.Version, EncodedVersion_lib_6_3);
  1028. VERIFY_ARE_EQUAL(FnDesc.ConstantBuffers, 1);
  1029. VERIFY_ARE_EQUAL(FnDesc.BoundResources, 4);
  1030. D3D12_SHADER_BUFFER_DESC cbDesc;
  1031. ID3D12ShaderReflectionConstantBuffer *pCBReflection = pFunctionReflection->GetConstantBufferByIndex(0);
  1032. VERIFY_SUCCEEDED(pCBReflection->GetDesc(&cbDesc));
  1033. std::string cbName = cbDesc.Name;
  1034. (void)(cbName);
  1035. Ref1_CheckCBuffer_Globals(pCBReflection, cbDesc);
  1036. for (INT iRes = 0; iRes < (INT)FnDesc.BoundResources; iRes++) {
  1037. D3D12_SHADER_INPUT_BIND_DESC resDesc;
  1038. pFunctionReflection->GetResourceBindingDesc(iRes, &resDesc);
  1039. std::string resName = resDesc.Name;
  1040. if (resName.compare("$Globals") == 0) {
  1041. Ref1_CheckBinding_Globals(resDesc);
  1042. } else if (resName.compare("MyCB") == 0) {
  1043. Ref1_CheckBinding_MyCB(resDesc);
  1044. } else if (resName.compare("samp") == 0) {
  1045. Ref1_CheckBinding_samp(resDesc);
  1046. } else if (resName.compare("tex") == 0) {
  1047. Ref1_CheckBinding_tex(resDesc);
  1048. } else if (resName.compare("tex2") == 0) {
  1049. Ref1_CheckBinding_tex2(resDesc);
  1050. } else if (resName.compare("b_buf") == 0) {
  1051. Ref1_CheckBinding_b_buf(resDesc);
  1052. } else {
  1053. VERIFY_FAIL(L"Unexpected resource used");
  1054. }
  1055. }
  1056. } else if (Name.compare("function2") == 0) {
  1057. // shader function with unmangled name
  1058. VERIFY_ARE_EQUAL(FnDesc.Version, EncodedVersion_vs_6_3);
  1059. VERIFY_ARE_EQUAL(FnDesc.ConstantBuffers, 2);
  1060. VERIFY_ARE_EQUAL(FnDesc.BoundResources, 2);
  1061. for (INT iCB = 0; iCB < (INT)FnDesc.BoundResources; iCB++) {
  1062. D3D12_SHADER_BUFFER_DESC cbDesc;
  1063. ID3D12ShaderReflectionConstantBuffer *pCBReflection = pFunctionReflection->GetConstantBufferByIndex(0);
  1064. VERIFY_SUCCEEDED(pCBReflection->GetDesc(&cbDesc));
  1065. std::string cbName = cbDesc.Name;
  1066. if (cbName.compare("$Globals") == 0) {
  1067. Ref1_CheckCBuffer_Globals(pCBReflection, cbDesc);
  1068. } else if (cbName.compare("MyCB") == 0) {
  1069. Ref1_CheckCBuffer_MyCB(pCBReflection, cbDesc);
  1070. }
  1071. }
  1072. for (INT iRes = 0; iRes < (INT)FnDesc.BoundResources; iRes++) {
  1073. D3D12_SHADER_INPUT_BIND_DESC resDesc;
  1074. pFunctionReflection->GetResourceBindingDesc(iRes, &resDesc);
  1075. std::string resName = resDesc.Name;
  1076. if (resName.compare("$Globals") == 0) {
  1077. Ref1_CheckBinding_Globals(resDesc);
  1078. } else if (resName.compare("MyCB") == 0) {
  1079. Ref1_CheckBinding_MyCB(resDesc);
  1080. } else {
  1081. VERIFY_FAIL(L"Unexpected resource used");
  1082. }
  1083. }
  1084. } else {
  1085. VERIFY_FAIL(L"Unexpected function");
  1086. }
  1087. }
  1088. // TODO: FINISH THIS
  1089. }
  1090. }
  1091. IFTBOOLMSG(blobFound, E_FAIL, "failed to find RDAT blob after compiling");
  1092. }
  1093. TEST_F(DxilContainerTest, CompileWhenOKThenIncludesFeatureInfo) {
  1094. CComPtr<IDxcCompiler> pCompiler;
  1095. CComPtr<IDxcBlobEncoding> pSource;
  1096. CComPtr<IDxcBlob> pProgram;
  1097. CComPtr<IDxcBlobEncoding> pDisassembly;
  1098. CComPtr<IDxcOperationResult> pResult;
  1099. hlsl::DxilContainerHeader *pHeader;
  1100. hlsl::DxilPartIterator pPartIter(nullptr, 0);
  1101. VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
  1102. CreateBlobFromText("float4 main() : SV_Target { return 0; }", &pSource);
  1103. VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main", L"ps_6_0",
  1104. nullptr, 0, nullptr, 0, nullptr,
  1105. &pResult));
  1106. VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
  1107. // Now mess with the program bitcode.
  1108. pHeader = (hlsl::DxilContainerHeader *)pProgram->GetBufferPointer();
  1109. pPartIter = std::find_if(hlsl::begin(pHeader), hlsl::end(pHeader),
  1110. hlsl::DxilPartIsType(hlsl::DFCC_FeatureInfo));
  1111. VERIFY_ARE_NOT_EQUAL(hlsl::end(pHeader), pPartIter);
  1112. VERIFY_ARE_EQUAL(sizeof(uint64_t), (*pPartIter)->PartSize);
  1113. VERIFY_ARE_EQUAL(0U, *(const uint64_t *)hlsl::GetDxilPartData(*pPartIter));
  1114. }
  1115. TEST_F(DxilContainerTest, DisassemblyWhenBCInvalidThenFails) {
  1116. CComPtr<IDxcCompiler> pCompiler;
  1117. CComPtr<IDxcBlobEncoding> pSource;
  1118. CComPtr<IDxcBlob> pProgram;
  1119. CComPtr<IDxcBlobEncoding> pDisassembly;
  1120. CComPtr<IDxcOperationResult> pResult;
  1121. hlsl::DxilContainerHeader *pHeader;
  1122. hlsl::DxilPartHeader *pPart;
  1123. VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
  1124. CreateBlobFromText("float4 main() : SV_Target { return 0; }", &pSource);
  1125. VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main", L"ps_6_0",
  1126. nullptr, 0, nullptr, 0, nullptr,
  1127. &pResult));
  1128. VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
  1129. // Now mess with the program bitcode.
  1130. pHeader = (hlsl::DxilContainerHeader *)pProgram->GetBufferPointer();
  1131. pPart = const_cast<hlsl::DxilPartHeader *>(
  1132. *std::find_if(hlsl::begin(pHeader), hlsl::end(pHeader),
  1133. hlsl::DxilPartIsType(hlsl::DFCC_DXIL)));
  1134. strcpy_s(hlsl::GetDxilPartData(pPart), pPart->PartSize, "corruption");
  1135. VERIFY_FAILED(pCompiler->Disassemble(pProgram, &pDisassembly));
  1136. }
  1137. TEST_F(DxilContainerTest, DisassemblyWhenMissingThenFails) {
  1138. CComPtr<IDxcCompiler> pCompiler;
  1139. CComPtr<IDxcBlobEncoding> pSource;
  1140. CComPtr<IDxcBlobEncoding> pDisassembly;
  1141. hlsl::DxilContainerHeader header;
  1142. SetupBasicHeader(&header);
  1143. VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
  1144. CreateBlobPinned(&header, header.ContainerSizeInBytes, CP_UTF8, &pSource);
  1145. VERIFY_FAILED(pCompiler->Disassemble(pSource, &pDisassembly));
  1146. }
  1147. TEST_F(DxilContainerTest, DisassemblyWhenInvalidThenFails) {
  1148. CComPtr<IDxcCompiler> pCompiler;
  1149. CComPtr<IDxcBlobEncoding> pDisassembly;
  1150. uint8_t scratch[1024];
  1151. hlsl::DxilContainerHeader *pHeader = (hlsl::DxilContainerHeader *)scratch;
  1152. VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
  1153. // Too small to contain header.
  1154. {
  1155. CComPtr<IDxcBlobEncoding> pSource;
  1156. SetupBasicHeader(pHeader);
  1157. CreateBlobPinned(pHeader, sizeof(hlsl::DxilContainerHeader) - 4, CP_UTF8,
  1158. &pSource);
  1159. VERIFY_FAILED(pCompiler->Disassemble(pSource, &pDisassembly));
  1160. }
  1161. // Wrong major version.
  1162. {
  1163. CComPtr<IDxcBlobEncoding> pSource;
  1164. SetupBasicHeader(pHeader);
  1165. pHeader->Version.Major = 100;
  1166. CreateBlobPinned(pHeader, pHeader->ContainerSizeInBytes, CP_UTF8, &pSource);
  1167. VERIFY_FAILED(pCompiler->Disassemble(pSource, &pDisassembly));
  1168. }
  1169. // Size out of bounds.
  1170. {
  1171. CComPtr<IDxcBlobEncoding> pSource;
  1172. SetupBasicHeader(pHeader);
  1173. pHeader->ContainerSizeInBytes = 1024;
  1174. CreateBlobPinned(pHeader, sizeof(hlsl::DxilContainerHeader), CP_UTF8,
  1175. &pSource);
  1176. VERIFY_FAILED(pCompiler->Disassemble(pSource, &pDisassembly));
  1177. }
  1178. // Size too large as per spec limit.
  1179. {
  1180. CComPtr<IDxcBlobEncoding> pSource;
  1181. SetupBasicHeader(pHeader);
  1182. pHeader->ContainerSizeInBytes = hlsl::DxilContainerMaxSize + 1;
  1183. CreateBlobPinned(pHeader, pHeader->ContainerSizeInBytes, CP_UTF8, &pSource);
  1184. VERIFY_FAILED(pCompiler->Disassemble(pSource, &pDisassembly));
  1185. }
  1186. // Not large enough to hold offset table.
  1187. {
  1188. CComPtr<IDxcBlobEncoding> pSource;
  1189. SetupBasicHeader(pHeader);
  1190. pHeader->PartCount = 1;
  1191. CreateBlobPinned(pHeader, pHeader->ContainerSizeInBytes, CP_UTF8, &pSource);
  1192. VERIFY_FAILED(pCompiler->Disassemble(pSource, &pDisassembly));
  1193. }
  1194. // Part offset out of bounds.
  1195. {
  1196. CComPtr<IDxcBlobEncoding> pSource;
  1197. SetupBasicHeader(pHeader);
  1198. pHeader->PartCount = 1;
  1199. *((uint32_t *)(pHeader + 1)) = 1024;
  1200. pHeader->ContainerSizeInBytes += sizeof(uint32_t);
  1201. CreateBlobPinned(pHeader, pHeader->ContainerSizeInBytes, CP_UTF8, &pSource);
  1202. VERIFY_FAILED(pCompiler->Disassemble(pSource, &pDisassembly));
  1203. }
  1204. // Part size out of bounds.
  1205. {
  1206. CComPtr<IDxcBlobEncoding> pSource;
  1207. SetupBasicHeader(pHeader);
  1208. pHeader->PartCount = 1;
  1209. *((uint32_t *)(pHeader + 1)) = sizeof(*pHeader) + sizeof(uint32_t);
  1210. pHeader->ContainerSizeInBytes += sizeof(uint32_t);
  1211. hlsl::GetDxilContainerPart(pHeader, 0)->PartSize = 1024;
  1212. pHeader->ContainerSizeInBytes += sizeof(hlsl::DxilPartHeader);
  1213. CreateBlobPinned(pHeader, pHeader->ContainerSizeInBytes, CP_UTF8, &pSource);
  1214. VERIFY_FAILED(pCompiler->Disassemble(pSource, &pDisassembly));
  1215. }
  1216. }
  1217. TEST_F(DxilContainerTest, DisassemblyWhenValidThenOK) {
  1218. CComPtr<IDxcCompiler> pCompiler;
  1219. CComPtr<IDxcBlobEncoding> pSource;
  1220. CComPtr<IDxcBlob> pProgram;
  1221. CComPtr<IDxcBlobEncoding> pDisassembly;
  1222. CComPtr<IDxcOperationResult> pResult;
  1223. hlsl::DxilContainerHeader header;
  1224. SetupBasicHeader(&header);
  1225. VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
  1226. CreateBlobFromText("float4 main() : SV_Target { return 0; }", &pSource);
  1227. VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main", L"ps_6_0",
  1228. nullptr, 0, nullptr, 0, nullptr,
  1229. &pResult));
  1230. VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
  1231. VERIFY_SUCCEEDED(pCompiler->Disassemble(pProgram, &pDisassembly));
  1232. std::string disassembleString(BlobToUtf8(pDisassembly));
  1233. VERIFY_ARE_NOT_EQUAL(0U, disassembleString.size());
  1234. }
  1235. class HlslFileVariables {
  1236. private:
  1237. std::wstring m_Entry;
  1238. std::wstring m_Mode;
  1239. std::wstring m_Target;
  1240. std::vector<std::wstring> m_Arguments;
  1241. std::vector<LPCWSTR> m_ArgumentPtrs;
  1242. public:
  1243. HlslFileVariables(HlslFileVariables &other) = delete;
  1244. const LPCWSTR *GetArguments() const { return m_ArgumentPtrs.data(); }
  1245. UINT32 GetArgumentCount() const { return m_ArgumentPtrs.size(); }
  1246. LPCWSTR GetEntry() const { return m_Entry.c_str(); }
  1247. LPCWSTR GetMode() const { return m_Mode.c_str(); }
  1248. LPCWSTR GetTarget() const { return m_Target.c_str(); }
  1249. void Reset();
  1250. HRESULT SetFromText(_In_count_(len) const char *pText, size_t len);
  1251. };
  1252. void HlslFileVariables::Reset() {
  1253. m_Entry.resize(0);
  1254. m_Mode.resize(0);
  1255. m_Target.resize(0);
  1256. m_Arguments.resize(0);
  1257. m_ArgumentPtrs.resize(0);
  1258. }
  1259. #include <codecvt>
  1260. static bool wcsneq(const wchar_t *pValue, const wchar_t *pCheck) {
  1261. return 0 == wcsncmp(pValue, pCheck, wcslen(pCheck));
  1262. }
  1263. HRESULT HlslFileVariables::SetFromText(_In_count_(len) const char *pText, size_t len) {
  1264. // Look for the line of interest.
  1265. const char *pEnd = pText + len;
  1266. const char *pLineEnd = pText;
  1267. while (pLineEnd < pEnd && *pLineEnd != '\n') pLineEnd++;
  1268. // Create a UTF-16-backing store.
  1269. std::wstring_convert<std::codecvt_utf8_utf16<wchar_t> > w;
  1270. std::wstring line = w.from_bytes(pText, pLineEnd);
  1271. // Find starting and ending '-*-' delimiters.
  1272. const wchar_t *pWText = line.c_str();
  1273. const wchar_t *pVarStart = wcsstr(pWText, L"-*-");
  1274. if (!pVarStart) return E_INVALIDARG;
  1275. pVarStart += 3;
  1276. const wchar_t *pVarEnd = wcsstr(pVarStart, L"-*-");
  1277. if (!pVarEnd) return E_INVALIDARG;
  1278. for (;;) {
  1279. // Find 'name' ':' 'value' ';'
  1280. const wchar_t *pVarNameStart = pVarStart;
  1281. while (pVarNameStart < pVarEnd && L' ' == *pVarNameStart) ++pVarNameStart;
  1282. if (pVarNameStart == pVarEnd) break;
  1283. const wchar_t *pVarValDelim = pVarNameStart;
  1284. while (pVarValDelim < pVarEnd && L':' != *pVarValDelim) ++pVarValDelim;
  1285. if (pVarValDelim == pVarEnd) break;
  1286. const wchar_t *pVarValStart = pVarValDelim + 1;
  1287. while (pVarValStart < pVarEnd && L' ' == *pVarValStart) ++pVarValStart;
  1288. if (pVarValStart == pVarEnd) break;
  1289. const wchar_t *pVarValEnd = pVarValStart;
  1290. while (pVarValEnd < pVarEnd && L';' != *pVarValEnd) ++pVarValEnd;
  1291. if (wcsneq(pVarNameStart, L"mode")) {
  1292. m_Mode.assign(pVarValStart, pVarValEnd - pVarValStart - 1);
  1293. }
  1294. else if (wcsneq(pVarNameStart, L"hlsl-entry")) {
  1295. m_Entry.assign(pVarValStart, pVarValEnd - pVarValStart - 1);
  1296. }
  1297. else if (wcsneq(pVarNameStart, L"hlsl-target")) {
  1298. m_Target.assign(pVarValStart, pVarValEnd - pVarValStart - 1);
  1299. }
  1300. else if (wcsneq(pVarNameStart, L"hlsl-args")) {
  1301. // skip for now
  1302. }
  1303. }
  1304. return S_OK;
  1305. }
  1306. #ifdef _WIN32 // Reflection unsupported
  1307. TEST_F(DxilContainerTest, ReflectionMatchesDXBC_CheckIn) {
  1308. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  1309. ReflectionTest(hlsl_test::GetPathToHlslDataFile(L"..\\CodeGenHLSL\\container\\SimpleBezier11DS.hlsl").c_str(), false);
  1310. ReflectionTest(hlsl_test::GetPathToHlslDataFile(L"..\\CodeGenHLSL\\container\\SubD11_SmoothPS.hlsl").c_str(), false);
  1311. }
  1312. TEST_F(DxilContainerTest, ReflectionMatchesDXBC_Full) {
  1313. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  1314. std::wstring codeGenPath = hlsl_test::GetPathToHlslDataFile(L"..\\CodeGenHLSL\\Samples");
  1315. // This test was running at about three minutes; that can be enabled with TestAll=True,
  1316. // otherwise the much shorter list is used.
  1317. const bool TestAll = false;
  1318. LPCWSTR PreApprovedPaths[] = {
  1319. L"2DQuadShaders_VS.hlsl",
  1320. L"BC6HEncode_TryModeLE10CS.hlsl",
  1321. L"DepthViewerVS.hlsl",
  1322. L"DetailTessellation11_DS.hlsl",
  1323. L"GenerateHistogramCS.hlsl",
  1324. L"OIT_PS.hlsl",
  1325. L"PNTriangles11_DS.hlsl",
  1326. L"PerfGraphPS.hlsl",
  1327. L"PerfGraphVS.hlsl",
  1328. L"ScreenQuadVS.hlsl",
  1329. L"SimpleBezier11HS.hlsl"
  1330. };
  1331. for (auto &p: recursive_directory_iterator(path(codeGenPath))) {
  1332. if (is_regular_file(p)) {
  1333. LPCWSTR fullPath = p.path().c_str();
  1334. if (wcsstr(fullPath, L".hlsli") != nullptr) continue;
  1335. if (wcsstr(fullPath, L"TessellatorCS40_defines.h") != nullptr) continue;
  1336. // Skip failed tests.
  1337. if (wcsstr(fullPath, L"SubD11_SubDToBezierHS") != nullptr) continue;
  1338. if (!TestAll) {
  1339. bool shouldTest = false;
  1340. LPCWSTR *PreApprovedEnd = PreApprovedPaths + _countof(PreApprovedPaths);
  1341. shouldTest = PreApprovedEnd == std::find_if(PreApprovedPaths, PreApprovedEnd,
  1342. [&](LPCWSTR candidate) { return nullptr != wcsstr(fullPath, candidate); });
  1343. if (!shouldTest) {
  1344. break;
  1345. }
  1346. }
  1347. auto start = std::chrono::system_clock::now();
  1348. ReflectionTest(fullPath, true);
  1349. if (TestAll) {
  1350. // If testing all cases, print out their timing.
  1351. auto end = std::chrono::system_clock::now();
  1352. auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  1353. LogCommentFmt(L"%s,%u", fullPath, (unsigned)dur.count());
  1354. }
  1355. }
  1356. }
  1357. }
  1358. #endif // _WIN32 - Reflection unsupported
  1359. TEST_F(DxilContainerTest, ValidateFromLL_Abs2) {
  1360. CodeGenTestCheck(L"..\\CodeGenHLSL\\container\\abs2_m.ll");
  1361. }
  1362. TEST_F(DxilContainerTest, DxilContainerUnitTest) {
  1363. CComPtr<IDxcCompiler> pCompiler;
  1364. CComPtr<IDxcBlobEncoding> pSource;
  1365. CComPtr<IDxcBlob> pProgram;
  1366. CComPtr<IDxcBlobEncoding> pDisassembly;
  1367. CComPtr<IDxcOperationResult> pResult;
  1368. std::vector<LPCWSTR> arguments;
  1369. arguments.emplace_back(L"/Zi");
  1370. arguments.emplace_back(L"/Qembed_debug");
  1371. VERIFY_SUCCEEDED(CreateCompiler(&pCompiler));
  1372. CreateBlobFromText("float4 main() : SV_Target { return 0; }", &pSource);
  1373. // Test DxilContainer with ShaderDebugInfoDXIL
  1374. VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main", L"ps_6_0", arguments.data(), arguments.size(), nullptr, 0, nullptr, &pResult));
  1375. VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
  1376. const hlsl::DxilContainerHeader *pHeader = static_cast<const hlsl::DxilContainerHeader *> (pProgram->GetBufferPointer());
  1377. VERIFY_IS_TRUE(hlsl::IsValidDxilContainer(pHeader, pProgram->GetBufferSize()));
  1378. VERIFY_IS_NOT_NULL(hlsl::IsDxilContainerLike(pHeader, pProgram->GetBufferSize()));
  1379. VERIFY_IS_NOT_NULL(hlsl::GetDxilProgramHeader(pHeader, hlsl::DxilFourCC::DFCC_DXIL));
  1380. VERIFY_IS_NOT_NULL(hlsl::GetDxilProgramHeader(pHeader, hlsl::DxilFourCC::DFCC_ShaderDebugInfoDXIL));
  1381. VERIFY_IS_NOT_NULL(hlsl::GetDxilPartByType(pHeader, hlsl::DxilFourCC::DFCC_DXIL));
  1382. VERIFY_IS_NOT_NULL(hlsl::GetDxilPartByType(pHeader, hlsl::DxilFourCC::DFCC_ShaderDebugInfoDXIL));
  1383. pResult.Release();
  1384. pProgram.Release();
  1385. // Test DxilContainer without ShaderDebugInfoDXIL
  1386. VERIFY_SUCCEEDED(pCompiler->Compile(pSource, L"hlsl.hlsl", L"main", L"ps_6_0", nullptr, 0, nullptr, 0, nullptr, &pResult));
  1387. VERIFY_SUCCEEDED(pResult->GetResult(&pProgram));
  1388. pHeader = static_cast<const hlsl::DxilContainerHeader *> (pProgram->GetBufferPointer());
  1389. VERIFY_IS_TRUE(hlsl::IsValidDxilContainer(pHeader, pProgram->GetBufferSize()));
  1390. VERIFY_IS_NOT_NULL(hlsl::IsDxilContainerLike(pHeader, pProgram->GetBufferSize()));
  1391. VERIFY_IS_NOT_NULL(hlsl::GetDxilProgramHeader(pHeader, hlsl::DxilFourCC::DFCC_DXIL));
  1392. VERIFY_IS_NULL(hlsl::GetDxilProgramHeader(pHeader, hlsl::DxilFourCC::DFCC_ShaderDebugInfoDXIL));
  1393. VERIFY_IS_NOT_NULL(hlsl::GetDxilPartByType(pHeader, hlsl::DxilFourCC::DFCC_DXIL));
  1394. VERIFY_IS_NULL(hlsl::GetDxilPartByType(pHeader, hlsl::DxilFourCC::DFCC_ShaderDebugInfoDXIL));
  1395. // Test Empty DxilContainer
  1396. hlsl::DxilContainerHeader header;
  1397. SetupBasicHeader(&header);
  1398. VERIFY_IS_TRUE(hlsl::IsValidDxilContainer(&header, header.ContainerSizeInBytes));
  1399. VERIFY_IS_NOT_NULL(hlsl::IsDxilContainerLike(&header, header.ContainerSizeInBytes));
  1400. VERIFY_IS_NULL(hlsl::GetDxilProgramHeader(&header, hlsl::DxilFourCC::DFCC_DXIL));
  1401. VERIFY_IS_NULL(hlsl::GetDxilPartByType(&header, hlsl::DxilFourCC::DFCC_DXIL));
  1402. }