FileCheckerTest.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // FileCheckerTest.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 that are based on FileChecker. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #ifndef UNICODE
  12. #define UNICODE
  13. #endif
  14. #include <memory>
  15. #include <vector>
  16. #include <string>
  17. #include <cctype>
  18. #include <cassert>
  19. #include <algorithm>
  20. #include "dxc/Support/WinIncludes.h"
  21. #include "dxc/dxcapi.h"
  22. #ifdef _WIN32
  23. #include <atlfile.h>
  24. #endif
  25. #include "HLSLTestData.h"
  26. #include "HlslTestUtils.h"
  27. #include "DxcTestUtils.h"
  28. #include "llvm/Support/raw_os_ostream.h"
  29. #include "llvm/Support/MD5.h"
  30. #include "dxc/Support/Global.h"
  31. #include "dxc/Support/dxcapi.use.h"
  32. #include "dxc/Support/HLSLOptions.h"
  33. #include "dxc/Support/Unicode.h"
  34. #include "dxc/DxilContainer/DxilContainer.h"
  35. #include "D3DReflectionDumper.h"
  36. #include "d3d12shader.h"
  37. using namespace std;
  38. using namespace hlsl_test;
  39. static constexpr char whitespaceChars[] = " \t\r\n";
  40. static std::string strltrim(const std::string &value) {
  41. size_t first = value.find_first_not_of(whitespaceChars);
  42. return first == string::npos ? value : value.substr(first);
  43. }
  44. static std::string strrtrim(const std::string &value) {
  45. size_t last = value.find_last_not_of(whitespaceChars);
  46. return last == string::npos ? value : value.substr(0, last + 1);
  47. }
  48. static std::string strtrim(const std::string &value) {
  49. return strltrim(strrtrim(value));
  50. }
  51. static bool strstartswith(const std::string& value, const char* pattern) {
  52. for (size_t i = 0; ; ++i) {
  53. if (pattern[i] == '\0') return true;
  54. if (i == value.size() || value[i] != pattern[i]) return false;
  55. }
  56. }
  57. static std::vector<std::string> strtok(const std::string &value, const char *delimiters = whitespaceChars) {
  58. size_t searchOffset = 0;
  59. std::vector<std::string> tokens;
  60. while (searchOffset != value.size()) {
  61. size_t tokenStartIndex = value.find_first_not_of(delimiters, searchOffset);
  62. if (tokenStartIndex == std::string::npos) break;
  63. size_t tokenEndIndex = value.find_first_of(delimiters, tokenStartIndex);
  64. if (tokenEndIndex == std::string::npos) tokenEndIndex = value.size();
  65. tokens.emplace_back(value.substr(tokenStartIndex, tokenEndIndex - tokenStartIndex));
  66. searchOffset = tokenEndIndex;
  67. }
  68. return tokens;
  69. }
  70. FileRunCommandPart::FileRunCommandPart(const std::string &command, const std::string &arguments, LPCWSTR commandFileName) :
  71. Command(command), Arguments(arguments), CommandFileName(commandFileName) { }
  72. FileRunCommandResult FileRunCommandPart::RunHashTests(dxc::DxcDllSupport &DllSupport) {
  73. if (0 == _stricmp(Command.c_str(), "%dxc")) {
  74. return RunDxcHashTest(DllSupport);
  75. }
  76. else {
  77. return FileRunCommandResult::Success();
  78. }
  79. }
  80. FileRunCommandResult FileRunCommandPart::Run(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior) {
  81. bool isFileCheck =
  82. 0 == _stricmp(Command.c_str(), "FileCheck") ||
  83. 0 == _stricmp(Command.c_str(), "%FileCheck");
  84. bool isXFail = 0 == _stricmp(Command.c_str(), "xfail");
  85. bool consumeErrors = isFileCheck || isXFail;
  86. // Stop the pipeline if on errors unless the command can consume them.
  87. if (Prior != nullptr && Prior->ExitCode && !consumeErrors) {
  88. FileRunCommandResult result = *Prior;
  89. result.AbortPipeline = true;
  90. return result;
  91. }
  92. // We would add support for 'not' and 'llc' here.
  93. if (isFileCheck) {
  94. return RunFileChecker(Prior);
  95. }
  96. else if (isXFail) {
  97. return RunXFail(Prior);
  98. }
  99. else if (0 == _stricmp(Command.c_str(), "tee")) {
  100. return RunTee(Prior);
  101. }
  102. else if (0 == _stricmp(Command.c_str(), "%dxilver")) {
  103. return RunDxilVer(DllSupport, Prior);
  104. }
  105. else if (0 == _stricmp(Command.c_str(), "%dxc")) {
  106. return RunDxc(DllSupport, Prior);
  107. }
  108. else if (0 == _stricmp(Command.c_str(), "%dxv")) {
  109. return RunDxv(DllSupport, Prior);
  110. }
  111. else if (0 == _stricmp(Command.c_str(), "%opt")) {
  112. return RunOpt(DllSupport, Prior);
  113. }
  114. else if (0 == _stricmp(Command.c_str(), "%D3DReflect")) {
  115. return RunD3DReflect(DllSupport, Prior);
  116. }
  117. else {
  118. FileRunCommandResult result {};
  119. result.ExitCode = 1;
  120. result.StdErr = "Unrecognized command ";
  121. result.StdErr += Command;
  122. return result;
  123. }
  124. }
  125. FileRunCommandResult FileRunCommandPart::RunFileChecker(const FileRunCommandResult *Prior) {
  126. if (!Prior) return FileRunCommandResult::Error("Prior command required to generate stdin");
  127. FileCheckForTest t;
  128. t.CheckFilename = CW2A(CommandFileName, CP_UTF8);
  129. t.InputForStdin = Prior->ExitCode ? Prior->StdErr : Prior->StdOut;
  130. // Parse command arguments
  131. static constexpr char checkPrefixStr[] = "-check-prefix=";
  132. bool hasInputFilename = false;
  133. for (const std::string& arg : strtok(Arguments)) {
  134. if (arg == "%s") hasInputFilename = true;
  135. else if (arg == "-input=stderr") t.InputForStdin = Prior->StdErr;
  136. else if (strstartswith(arg, checkPrefixStr))
  137. t.CheckPrefixes.emplace_back(arg.substr(sizeof(checkPrefixStr) - 1));
  138. else return FileRunCommandResult::Error("Invalid argument");
  139. }
  140. if (!hasInputFilename) return FileRunCommandResult::Error("Missing input filename");
  141. FileRunCommandResult result {};
  142. // Run
  143. result.ExitCode = t.Run();
  144. result.StdOut = t.test_outs;
  145. result.StdErr = t.test_errs;
  146. // Capture the input as well.
  147. if (result.ExitCode != 0 && Prior != nullptr) {
  148. result.StdErr += "\n<full input to FileCheck>\n";
  149. result.StdErr += t.InputForStdin;
  150. }
  151. return result;
  152. }
  153. FileRunCommandResult FileRunCommandPart::ReadOptsForDxc(
  154. hlsl::options::MainArgs &argStrings, hlsl::options::DxcOpts &Opts) {
  155. std::string args(strtrim(Arguments));
  156. const char *inputPos = strstr(args.c_str(), "%s");
  157. if (inputPos == nullptr)
  158. return FileRunCommandResult::Error("Only supported pattern includes input file as argument");
  159. args.erase(inputPos - args.c_str(), strlen("%s"));
  160. llvm::StringRef argsRef = args;
  161. llvm::SmallVector<llvm::StringRef, 8> splitArgs;
  162. argsRef.split(splitArgs, " ");
  163. argStrings = hlsl::options::MainArgs(splitArgs);
  164. std::string errorString;
  165. llvm::raw_string_ostream errorStream(errorString);
  166. int RunResult = ReadDxcOpts(hlsl::options::getHlslOptTable(), /*flagsToInclude*/ 0,
  167. argStrings, Opts, errorStream);
  168. errorStream.flush();
  169. if (RunResult)
  170. return FileRunCommandResult::Error(RunResult, errorString);
  171. return FileRunCommandResult::Success("");
  172. }
  173. static HRESULT ReAssembleTo(dxc::DxcDllSupport &DllSupport, void *bitcode, UINT32 size, IDxcBlob **pBlob) {
  174. CComPtr<IDxcAssembler> pAssembler;
  175. CComPtr<IDxcLibrary> pLibrary;
  176. IFT(DllSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  177. IFT(DllSupport.CreateInstance(CLSID_DxcAssembler, &pAssembler));
  178. CComPtr<IDxcBlobEncoding> pInBlob;
  179. IFT(pLibrary->CreateBlobWithEncodingFromPinned(bitcode, size, 0, &pInBlob));
  180. CComPtr<IDxcOperationResult> pResult;
  181. pAssembler->AssembleToContainer(pInBlob, &pResult);
  182. HRESULT Result = 0;
  183. IFT(pResult->GetStatus(&Result));
  184. IFT(Result);
  185. IFT(pResult->GetResult(pBlob));
  186. return S_OK;
  187. }
  188. static HRESULT GetDxilBitcode(dxc::DxcDllSupport &DllSupport, IDxcBlob *pCompiledBlob, IDxcBlob **pBitcodeBlob) {
  189. CComPtr<IDxcContainerReflection> pReflection;
  190. CComPtr<IDxcLibrary> pLibrary;
  191. IFT(DllSupport.CreateInstance(CLSID_DxcContainerReflection, &pReflection));
  192. IFT(DllSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  193. IFT(pReflection->Load(pCompiledBlob));
  194. UINT32 uIndex = 0;
  195. IFT(pReflection->FindFirstPartKind(hlsl::DFCC_DXIL, &uIndex));
  196. CComPtr<IDxcBlob> pPart;
  197. IFT(pReflection->GetPartContent(uIndex, &pPart));
  198. auto header = (hlsl::DxilProgramHeader*)pPart->GetBufferPointer();
  199. void *bitcode = (char *)&header->BitcodeHeader + header->BitcodeHeader.BitcodeOffset;
  200. UINT32 bitcode_size = header->BitcodeHeader.BitcodeSize;
  201. CComPtr<IDxcBlobEncoding> pBlob;
  202. IFT(pLibrary->CreateBlobWithEncodingFromPinned(bitcode, bitcode_size, 0, &pBlob));
  203. *pBitcodeBlob = pBlob.Detach();
  204. return S_OK;
  205. }
  206. static HRESULT CompileForHash(hlsl::options::DxcOpts &opts, LPCWSTR CommandFileName, dxc::DxcDllSupport &DllSupport, std::vector<LPCWSTR> &flags, IDxcBlob **ppHashBlob, std::string &output) {
  207. CComPtr<IDxcLibrary> pLibrary;
  208. CComPtr<IDxcCompiler> pCompiler;
  209. CComPtr<IDxcCompiler2> pCompiler2;
  210. CComPtr<IDxcOperationResult> pResult;
  211. CComPtr<IDxcBlobEncoding> pSource;
  212. CComPtr<IDxcBlob> pCompiledBlob;
  213. CComPtr<IDxcBlob> pCompiledName;
  214. CComPtr<IDxcIncludeHandler> pIncludeHandler;
  215. WCHAR *pDebugName = nullptr;
  216. CComPtr<IDxcBlob> pPDBBlob;
  217. std::wstring entry =
  218. Unicode::UTF8ToUTF16StringOrThrow(opts.EntryPoint.str().c_str());
  219. std::wstring profile =
  220. Unicode::UTF8ToUTF16StringOrThrow(opts.TargetProfile.str().c_str());
  221. IFT(DllSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  222. IFT(pLibrary->CreateBlobFromFile(CommandFileName, nullptr, &pSource));
  223. IFT(pLibrary->CreateIncludeHandler(&pIncludeHandler));
  224. IFT(DllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler));
  225. IFT(pCompiler.QueryInterface(&pCompiler2));
  226. IFT(pCompiler2->CompileWithDebug(pSource, CommandFileName, entry.c_str(), profile.c_str(),
  227. flags.data(), flags.size(), nullptr, 0, pIncludeHandler, &pResult, &pDebugName, &pPDBBlob));
  228. HRESULT resultStatus = 0;
  229. IFT(pResult->GetStatus(&resultStatus));
  230. if (SUCCEEDED(resultStatus)) {
  231. IFT(pResult->GetResult(&pCompiledBlob));
  232. CComPtr<IDxcContainerReflection> pReflection;
  233. IFT(DllSupport.CreateInstance(CLSID_DxcContainerReflection, &pReflection));
  234. // If failed to load here, it's likely some non-compile operation thing. Just fail the hash generation.
  235. if (FAILED(pReflection->Load(pCompiledBlob)))
  236. return E_FAIL;
  237. *ppHashBlob = nullptr;
  238. UINT32 uHashIdx = 0;
  239. if (SUCCEEDED(pReflection->FindFirstPartKind(hlsl::DFCC_ShaderHash, &uHashIdx))) {
  240. CComPtr<IDxcBlob> pHashBlob;
  241. IFT(pReflection->GetPartContent(uHashIdx, &pHashBlob));
  242. *ppHashBlob = pHashBlob.Detach();
  243. }
  244. // Test that PDB is generated correctly.
  245. // This test needs to be done elsewhere later, ideally a fully
  246. // customizable test on all our test set with different compile options.
  247. if (pPDBBlob) {
  248. IFT(pReflection->Load(pPDBBlob));
  249. UINT32 uDebugInfoIndex = 0;
  250. IFT(pReflection->FindFirstPartKind(hlsl::DFCC_ShaderDebugInfoDXIL, &uDebugInfoIndex));
  251. }
  252. return S_OK;
  253. }
  254. else {
  255. CComPtr<IDxcBlobEncoding> pErrors;
  256. IFT(pResult->GetErrorBuffer(&pErrors));
  257. const char *errors = (char *)pErrors->GetBufferPointer();
  258. output = errors;
  259. return resultStatus;
  260. }
  261. }
  262. FileRunCommandResult FileRunCommandPart::RunDxcHashTest(dxc::DxcDllSupport &DllSupport) {
  263. hlsl::options::MainArgs args;
  264. hlsl::options::DxcOpts opts;
  265. ReadOptsForDxc(args, opts);
  266. std::vector<std::wstring> argWStrings;
  267. CopyArgsToWStrings(opts.Args, hlsl::options::CoreOption, argWStrings);
  268. // Extract the vanilla flags for the test (i.e. no debug or ast-dump)
  269. std::vector<LPCWSTR> original_flags;
  270. for (const std::wstring &a : argWStrings) {
  271. if (a.find(L"ast-dump") != std::wstring::npos) continue;
  272. if (a.find(L"Zi") != std::wstring::npos) continue;
  273. original_flags.push_back(a.data());
  274. }
  275. std::string originalOutput;
  276. CComPtr<IDxcBlob> pOriginalHash;
  277. // If failed the original compilation, just pass the test. The original test was likely
  278. // testing for failure.
  279. if (FAILED(CompileForHash(opts, CommandFileName, DllSupport, original_flags, &pOriginalHash, originalOutput)))
  280. return FileRunCommandResult::Success();
  281. // Results of our compilations
  282. CComPtr<IDxcBlob> pHash1;
  283. std::string Output0;
  284. CComPtr<IDxcBlob> pHash0;
  285. std::string Output1;
  286. // Fail if -Qstrip_reflect failed the compilation
  287. std::vector<LPCWSTR> normal_flags = original_flags;
  288. normal_flags.push_back(L"-Qstrip_reflect");
  289. normal_flags.push_back(L"-Zsb");
  290. std::string StdErr;
  291. if (FAILED(CompileForHash(opts, CommandFileName, DllSupport, normal_flags, &pHash0, Output0))) {
  292. StdErr += "Adding Qstrip_reflect failed compilation.";
  293. StdErr += originalOutput;
  294. StdErr += Output0;
  295. return FileRunCommandResult::Error(StdErr);
  296. }
  297. // Fail if -Qstrip_reflect failed the compilation
  298. std::vector<LPCWSTR> dbg_flags = original_flags;
  299. dbg_flags.push_back(L"/Zi");
  300. dbg_flags.push_back(L"-Qstrip_reflect");
  301. dbg_flags.push_back(L"-Zsb");
  302. if (FAILED(CompileForHash(opts, CommandFileName, DllSupport, dbg_flags, &pHash1, Output1))) {
  303. return FileRunCommandResult::Error("Adding Qstrip_reflect and Zi failed compilation.");
  304. }
  305. if (pHash0->GetBufferSize() != pHash1->GetBufferSize() || 0 != memcmp(pHash0->GetBufferPointer(), pHash0->GetBufferPointer(), pHash1->GetBufferSize())) {
  306. StdErr = "Hashes do not match between normal and debug!!!\n";
  307. StdErr += Output0;
  308. StdErr += Output1;
  309. return FileRunCommandResult::Error(StdErr);
  310. }
  311. return FileRunCommandResult::Success();
  312. }
  313. FileRunCommandResult FileRunCommandPart::RunDxc(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior) {
  314. // Support piping stdin from prior if needed.
  315. UNREFERENCED_PARAMETER(Prior);
  316. hlsl::options::MainArgs args;
  317. hlsl::options::DxcOpts opts;
  318. FileRunCommandResult readOptsResult = ReadOptsForDxc(args, opts);
  319. if (readOptsResult.ExitCode) return readOptsResult;
  320. std::wstring entry =
  321. Unicode::UTF8ToUTF16StringOrThrow(opts.EntryPoint.str().c_str());
  322. std::wstring profile =
  323. Unicode::UTF8ToUTF16StringOrThrow(opts.TargetProfile.str().c_str());
  324. std::vector<LPCWSTR> flags;
  325. if (opts.CodeGenHighLevel) {
  326. flags.push_back(L"-fcgl");
  327. }
  328. std::vector<std::wstring> argWStrings;
  329. CopyArgsToWStrings(opts.Args, hlsl::options::CoreOption, argWStrings);
  330. for (const std::wstring &a : argWStrings)
  331. flags.push_back(a.data());
  332. CComPtr<IDxcLibrary> pLibrary;
  333. CComPtr<IDxcCompiler> pCompiler;
  334. CComPtr<IDxcOperationResult> pResult;
  335. CComPtr<IDxcBlobEncoding> pSource;
  336. CComPtr<IDxcBlobEncoding> pDisassembly;
  337. CComPtr<IDxcBlob> pCompiledBlob;
  338. CComPtr<IDxcIncludeHandler> pIncludeHandler;
  339. HRESULT resultStatus;
  340. IFT(DllSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  341. IFT(pLibrary->CreateBlobFromFile(CommandFileName, nullptr, &pSource));
  342. IFT(pLibrary->CreateIncludeHandler(&pIncludeHandler));
  343. IFT(DllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler));
  344. IFT(pCompiler->Compile(pSource, CommandFileName, entry.c_str(), profile.c_str(),
  345. flags.data(), flags.size(), nullptr, 0, pIncludeHandler, &pResult));
  346. IFT(pResult->GetStatus(&resultStatus));
  347. FileRunCommandResult result = {};
  348. if (SUCCEEDED(resultStatus)) {
  349. IFT(pResult->GetResult(&pCompiledBlob));
  350. if (!opts.AstDump) {
  351. IFT(pCompiler->Disassemble(pCompiledBlob, &pDisassembly));
  352. result.StdOut = BlobToUtf8(pDisassembly);
  353. } else {
  354. result.StdOut = BlobToUtf8(pCompiledBlob);
  355. }
  356. CComPtr<IDxcBlobEncoding> pStdErr;
  357. IFT(pResult->GetErrorBuffer(&pStdErr));
  358. result.StdErr = BlobToUtf8(pStdErr);
  359. result.ExitCode = 0;
  360. }
  361. else {
  362. IFT(pResult->GetErrorBuffer(&pDisassembly));
  363. result.StdErr = BlobToUtf8(pDisassembly);
  364. result.ExitCode = resultStatus;
  365. }
  366. result.OpResult = pResult;
  367. return result;
  368. }
  369. FileRunCommandResult FileRunCommandPart::RunDxv(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior) {
  370. std::string args(strtrim(Arguments));
  371. const char *inputPos = strstr(args.c_str(), "%s");
  372. if (inputPos == nullptr) {
  373. return FileRunCommandResult::Error("Only supported pattern includes input file as argument");
  374. }
  375. args.erase(inputPos - args.c_str(), strlen("%s"));
  376. llvm::StringRef argsRef = args;
  377. llvm::SmallVector<llvm::StringRef, 8> splitArgs;
  378. argsRef.split(splitArgs, " ");
  379. IFTMSG(splitArgs.size()==1, "wrong arg num for dxv");
  380. CComPtr<IDxcLibrary> pLibrary;
  381. CComPtr<IDxcAssembler> pAssembler;
  382. CComPtr<IDxcValidator> pValidator;
  383. CComPtr<IDxcOperationResult> pResult;
  384. CComPtr<IDxcBlobEncoding> pSource;
  385. CComPtr<IDxcBlob> pContainerBlob;
  386. HRESULT resultStatus;
  387. IFT(DllSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  388. IFT(pLibrary->CreateBlobFromFile(CommandFileName, nullptr, &pSource));
  389. IFT(DllSupport.CreateInstance(CLSID_DxcAssembler, &pAssembler));
  390. IFT(pAssembler->AssembleToContainer(pSource, &pResult));
  391. IFT(pResult->GetStatus(&resultStatus));
  392. if (FAILED(resultStatus)) {
  393. CComPtr<IDxcBlobEncoding> pAssembleBlob;
  394. IFT(pResult->GetErrorBuffer(&pAssembleBlob));
  395. return FileRunCommandResult::Error(resultStatus, BlobToUtf8(pAssembleBlob));
  396. }
  397. IFT(pResult->GetResult(&pContainerBlob));
  398. IFT(DllSupport.CreateInstance(CLSID_DxcValidator, &pValidator));
  399. CComPtr<IDxcOperationResult> pValidationResult;
  400. IFT(pValidator->Validate(pContainerBlob, DxcValidatorFlags_InPlaceEdit,
  401. &pValidationResult));
  402. IFT(pValidationResult->GetStatus(&resultStatus));
  403. if (FAILED(resultStatus)) {
  404. CComPtr<IDxcBlobEncoding> pValidateBlob;
  405. IFT(pValidationResult->GetErrorBuffer(&pValidateBlob));
  406. return FileRunCommandResult::Success(BlobToUtf8(pValidateBlob));
  407. }
  408. return FileRunCommandResult::Success("");
  409. }
  410. FileRunCommandResult FileRunCommandPart::RunOpt(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior) {
  411. std::string args(strtrim(Arguments));
  412. const char *inputPos = strstr(args.c_str(), "%s");
  413. if (inputPos == nullptr && Prior == nullptr) {
  414. return FileRunCommandResult::Error("Only supported patterns are input file as argument or prior "
  415. "command with disassembly");
  416. }
  417. CComPtr<IDxcLibrary> pLibrary;
  418. CComPtr<IDxcOptimizer> pOptimizer;
  419. CComPtr<IDxcBlobEncoding> pSource;
  420. CComPtr<IDxcBlobEncoding> pOutputText;
  421. CComPtr<IDxcBlob> pOutputModule;
  422. IFT(DllSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  423. IFT(DllSupport.CreateInstance(CLSID_DxcOptimizer, &pOptimizer));
  424. if (inputPos != nullptr) {
  425. args.erase(inputPos - args.c_str(), strlen("%s"));
  426. IFT(pLibrary->CreateBlobFromFile(CommandFileName, nullptr, &pSource));
  427. }
  428. else {
  429. assert(Prior != nullptr && "else early check should have returned");
  430. CComPtr<IDxcAssembler> pAssembler;
  431. IFT(DllSupport.CreateInstance(CLSID_DxcAssembler, &pAssembler));
  432. IFT(pLibrary->CreateBlobWithEncodingFromPinned(
  433. Prior->StdOut.c_str(), Prior->StdOut.size(), CP_UTF8,
  434. &pSource));
  435. }
  436. args = strtrim(args);
  437. llvm::StringRef argsRef = args;
  438. llvm::SmallVector<llvm::StringRef, 8> splitArgs;
  439. argsRef.split(splitArgs, " ");
  440. std::vector<LPCWSTR> options;
  441. std::vector<std::wstring> optionStrings;
  442. for (llvm::StringRef S : splitArgs) {
  443. optionStrings.push_back(
  444. Unicode::UTF8ToUTF16StringOrThrow(strtrim(S.str()).c_str()));
  445. }
  446. // Add the options outside the above loop in case the vector is resized.
  447. for (const std::wstring& str : optionStrings)
  448. options.push_back(str.c_str());
  449. IFT(pOptimizer->RunOptimizer(pSource, options.data(), options.size(),
  450. &pOutputModule, &pOutputText));
  451. return FileRunCommandResult::Success(BlobToUtf8(pOutputText));
  452. }
  453. FileRunCommandResult FileRunCommandPart::RunD3DReflect(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior) {
  454. std::string args(strtrim(Arguments));
  455. if (args != "%s")
  456. return FileRunCommandResult::Error("Only supported pattern is a plain input file");
  457. if (!Prior)
  458. return FileRunCommandResult::Error("Prior command required to generate stdin");
  459. CComPtr<IDxcLibrary> pLibrary;
  460. CComPtr<IDxcBlobEncoding> pSource;
  461. CComPtr<IDxcAssembler> pAssembler;
  462. CComPtr<IDxcOperationResult> pResult;
  463. CComPtr<ID3D12ShaderReflection> pShaderReflection;
  464. CComPtr<ID3D12LibraryReflection> pLibraryReflection;
  465. CComPtr<IDxcContainerReflection> containerReflection;
  466. uint32_t partCount;
  467. CComPtr<IDxcBlob> pContainerBlob;
  468. HRESULT resultStatus;
  469. bool blobFound = false;
  470. std::ostringstream ss;
  471. D3DReflectionDumper dumper(ss);
  472. IFT(DllSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  473. IFT(DllSupport.CreateInstance(CLSID_DxcAssembler, &pAssembler));
  474. IFT(pLibrary->CreateBlobWithEncodingFromPinned(
  475. (LPBYTE)Prior->StdOut.c_str(), Prior->StdOut.size(), CP_UTF8,
  476. &pSource));
  477. IFT(pAssembler->AssembleToContainer(pSource, &pResult));
  478. IFT(pResult->GetStatus(&resultStatus));
  479. if (FAILED(resultStatus)) {
  480. CComPtr<IDxcBlobEncoding> pAssembleBlob;
  481. IFT(pResult->GetErrorBuffer(&pAssembleBlob));
  482. return FileRunCommandResult::Error(resultStatus, BlobToUtf8(pAssembleBlob));
  483. }
  484. IFT(pResult->GetResult(&pContainerBlob));
  485. VERIFY_SUCCEEDED(DllSupport.CreateInstance(CLSID_DxcContainerReflection, &containerReflection));
  486. VERIFY_SUCCEEDED(containerReflection->Load(pContainerBlob));
  487. VERIFY_SUCCEEDED(containerReflection->GetPartCount(&partCount));
  488. for (uint32_t i = 0; i < partCount; ++i) {
  489. uint32_t kind;
  490. VERIFY_SUCCEEDED(containerReflection->GetPartKind(i, &kind));
  491. if (kind == (uint32_t)hlsl::DxilFourCC::DFCC_DXIL) {
  492. blobFound = true;
  493. CComPtr<IDxcBlob> pPart;
  494. IFT(containerReflection->GetPartContent(i, &pPart));
  495. const hlsl::DxilProgramHeader *pProgramHeader =
  496. reinterpret_cast<const hlsl::DxilProgramHeader*>(pPart->GetBufferPointer());
  497. VERIFY_IS_TRUE(IsValidDxilProgramHeader(pProgramHeader, (uint32_t)pPart->GetBufferSize()));
  498. hlsl::DXIL::ShaderKind SK = hlsl::GetVersionShaderType(pProgramHeader->ProgramVersion);
  499. if (SK == hlsl::DXIL::ShaderKind::Library)
  500. VERIFY_SUCCEEDED(containerReflection->GetPartReflection(i, IID_PPV_ARGS(&pLibraryReflection)));
  501. else
  502. VERIFY_SUCCEEDED(containerReflection->GetPartReflection(i, IID_PPV_ARGS(&pShaderReflection)));
  503. break;
  504. }
  505. }
  506. if (!blobFound) {
  507. return FileRunCommandResult::Error("Unable to find DXIL part");
  508. } else if (pShaderReflection) {
  509. dumper.Dump(pShaderReflection);
  510. } else if (pLibraryReflection) {
  511. dumper.Dump(pLibraryReflection);
  512. }
  513. ss.flush();
  514. return FileRunCommandResult::Success(ss.str());
  515. }
  516. FileRunCommandResult FileRunCommandPart::RunTee(const FileRunCommandResult *Prior) {
  517. if (Prior == nullptr) {
  518. return FileRunCommandResult::Error("tee requires a prior command");
  519. }
  520. // Ignore commands for now - simply log out through test framework.
  521. {
  522. CA2W outWide(Prior->StdOut.c_str(), CP_UTF8);
  523. WEX::Logging::Log::Comment(outWide.m_psz);
  524. }
  525. if (!Prior->StdErr.empty()) {
  526. CA2W errWide(Prior->StdErr.c_str(), CP_UTF8);
  527. WEX::Logging::Log::Comment(L"<stderr>");
  528. WEX::Logging::Log::Comment(errWide.m_psz);
  529. }
  530. return *Prior;
  531. }
  532. FileRunCommandResult FileRunCommandPart::RunXFail(const FileRunCommandResult *Prior) {
  533. if (Prior == nullptr)
  534. return FileRunCommandResult::Error("XFail requires a prior command");
  535. if (Prior->ExitCode == 0) {
  536. return FileRunCommandResult::Error("XFail expected a failure from previous command");
  537. } else {
  538. return FileRunCommandResult::Success("");
  539. }
  540. }
  541. FileRunCommandResult FileRunCommandPart::RunDxilVer(dxc::DxcDllSupport& DllSupport, const FileRunCommandResult* Prior) {
  542. Arguments = strtrim(Arguments);
  543. if (Arguments.size() != 3 || !std::isdigit(Arguments[0]) || Arguments[1] != '.' || !std::isdigit(Arguments[2])) {
  544. return FileRunCommandResult::Error("Invalid dxil version format");
  545. }
  546. unsigned RequiredDxilMajor = Arguments[0] - '0';
  547. unsigned RequiredDxilMinor = Arguments[2] - '0';
  548. bool Supported = RequiredDxilMajor >= 1;
  549. CComPtr<IDxcCompiler> pCompiler;
  550. // If the following fails, we have Dxil 1.0 compiler
  551. if (SUCCEEDED(DllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler))) {
  552. CComPtr<IDxcVersionInfo> pVersionInfo;
  553. IFT(pCompiler.QueryInterface(&pVersionInfo));
  554. unsigned DxilMajor, DxilMinor;
  555. IFT(pVersionInfo->GetVersion(&DxilMajor, &DxilMinor));
  556. if (DxilMajor < RequiredDxilMajor || (DxilMajor == RequiredDxilMajor && DxilMinor < RequiredDxilMinor))
  557. Supported = false;
  558. }
  559. CComPtr<IDxcValidator> pValidator;
  560. if (SUCCEEDED(DllSupport.CreateInstance(CLSID_DxcValidator, &pValidator))) {
  561. CComPtr<IDxcVersionInfo> pVersionInfo;
  562. IFT(pValidator.QueryInterface(&pVersionInfo));
  563. unsigned DxilMajor, DxilMinor;
  564. VERIFY_SUCCEEDED(pVersionInfo->GetVersion(&DxilMajor, &DxilMinor));
  565. if (DxilMajor < RequiredDxilMajor || (DxilMajor == RequiredDxilMajor && DxilMinor < RequiredDxilMinor))
  566. Supported = false;
  567. }
  568. if (!Supported) {
  569. FileRunCommandResult result {};
  570. result.StdErr = "Skipping test due to unsupported dxil version";
  571. result.ExitCode = 0; // Succeed the test
  572. result.AbortPipeline = true;
  573. return result;
  574. }
  575. return FileRunCommandResult::Success();
  576. }
  577. class FileRunTestResultImpl : public FileRunTestResult {
  578. dxc::DxcDllSupport &m_support;
  579. void RunHashTestFromCommands(LPCSTR commands, LPCWSTR fileName) {
  580. std::vector<FileRunCommandPart> parts;
  581. ParseCommandParts(commands, fileName, parts);
  582. FileRunCommandResult result;
  583. bool ran = false;
  584. for (FileRunCommandPart & part : parts) {
  585. result = part.RunHashTests(m_support);
  586. ran = true;
  587. break;
  588. }
  589. if (ran) {
  590. this->RunResult = result.ExitCode;
  591. this->ErrorMessage = result.StdErr;
  592. }
  593. else {
  594. this->RunResult = 0;
  595. }
  596. }
  597. void RunFileCheckFromCommands(LPCSTR commands, LPCWSTR fileName) {
  598. std::vector<FileRunCommandPart> parts;
  599. ParseCommandParts(commands, fileName, parts);
  600. if (parts.empty()) {
  601. this->RunResult = 1;
  602. this->ErrorMessage = "FileCheck found no commands to run";
  603. return;
  604. }
  605. FileRunCommandResult result;
  606. FileRunCommandResult* previousResult = nullptr;
  607. for (FileRunCommandPart & part : parts) {
  608. result = part.Run(m_support, previousResult);
  609. previousResult = &result;
  610. if (result.AbortPipeline) break;
  611. }
  612. this->RunResult = result.ExitCode;
  613. this->ErrorMessage = result.StdErr;
  614. }
  615. public:
  616. FileRunTestResultImpl(dxc::DxcDllSupport &support) : m_support(support) {}
  617. void RunFileCheckFromFileCommands(LPCWSTR fileName) {
  618. // Assume UTF-8 files.
  619. std::string commands(GetFirstLine(fileName));
  620. return RunFileCheckFromCommands(commands.c_str(), fileName);
  621. }
  622. void RunHashTestFromFileCommands(LPCWSTR fileName) {
  623. // Assume UTF-8 files.
  624. std::string commands(GetFirstLine(fileName));
  625. return RunHashTestFromCommands(commands.c_str(), fileName);
  626. }
  627. };
  628. FileRunTestResult FileRunTestResult::RunHashTestFromFileCommands(LPCWSTR fileName) {
  629. dxc::DxcDllSupport dllSupport;
  630. IFT(dllSupport.Initialize());
  631. FileRunTestResultImpl result(dllSupport);
  632. result.RunHashTestFromFileCommands(fileName);
  633. return result;
  634. }
  635. FileRunTestResult FileRunTestResult::RunFromFileCommands(LPCWSTR fileName) {
  636. dxc::DxcDllSupport dllSupport;
  637. IFT(dllSupport.Initialize());
  638. FileRunTestResultImpl result(dllSupport);
  639. result.RunFileCheckFromFileCommands(fileName);
  640. return result;
  641. }
  642. FileRunTestResult FileRunTestResult::RunFromFileCommands(LPCWSTR fileName, dxc::DxcDllSupport &dllSupport) {
  643. FileRunTestResultImpl result(dllSupport);
  644. result.RunFileCheckFromFileCommands(fileName);
  645. return result;
  646. }
  647. void ParseCommandParts(LPCSTR commands, LPCWSTR fileName,
  648. std::vector<FileRunCommandPart> &parts) {
  649. // Barely enough parsing here.
  650. commands = strstr(commands, "RUN: ");
  651. if (!commands) {
  652. return;
  653. }
  654. commands += strlen("RUN: ");
  655. LPCSTR endCommands = strchr(commands, '\0');
  656. while (commands != endCommands) {
  657. LPCSTR nextStart;
  658. LPCSTR thisEnd = strchr(commands, '|');
  659. if (!thisEnd) {
  660. nextStart = thisEnd = endCommands;
  661. } else {
  662. nextStart = thisEnd + 2;
  663. }
  664. LPCSTR commandEnd = strchr(commands, ' ');
  665. if (!commandEnd)
  666. commandEnd = endCommands;
  667. parts.emplace_back(std::string(commands, commandEnd),
  668. std::string(commandEnd, thisEnd), fileName);
  669. commands = nextStart;
  670. }
  671. }
  672. void ParseCommandPartsFromFile(LPCWSTR fileName,
  673. std::vector<FileRunCommandPart> &parts) {
  674. // Assume UTF-8 files.
  675. std::string commands(GetFirstLine(fileName));
  676. ParseCommandParts(commands.c_str(), fileName, parts);
  677. }