FileCheckerTest.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  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, llvm::SmallString<32> &Hash, 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. CComPtr<IDxcBlob> pBitcodeBlob;
  238. IFT(GetDxilBitcode(DllSupport, pCompiledBlob, &pBitcodeBlob));
  239. CComPtr<IDxcBlob> pReassembledBlob;
  240. IFT(ReAssembleTo(DllSupport, pBitcodeBlob->GetBufferPointer(), pBitcodeBlob->GetBufferSize(), &pReassembledBlob));
  241. CComPtr<IDxcBlobEncoding> pDisassembly;
  242. IFT(pCompiler->Disassemble(pReassembledBlob, &pDisassembly));
  243. output = BlobToUtf8(pDisassembly);
  244. // For now, just has the disassembly. Once we fix the bitcode differences, we'll switch to that.
  245. llvm::ArrayRef<uint8_t> Data((uint8_t *)pDisassembly->GetBufferPointer(), pDisassembly->GetBufferSize());
  246. llvm::MD5 md5;
  247. llvm::MD5::MD5Result md5Result;
  248. md5.update(Data);
  249. md5.final(md5Result);
  250. md5.stringifyResult(md5Result, Hash);
  251. // Test that PDB is generated correctly.
  252. // This test needs to be done elsewhere later, ideally a fully
  253. // customizable test on all our test set with different compile options.
  254. if (pPDBBlob) {
  255. IFT(pReflection->Load(pPDBBlob));
  256. UINT32 uDebugInfoIndex = 0;
  257. IFT(pReflection->FindFirstPartKind(hlsl::DFCC_ShaderDebugInfoDXIL, &uDebugInfoIndex));
  258. }
  259. return S_OK;
  260. }
  261. else {
  262. CComPtr<IDxcBlobEncoding> pErrors;
  263. IFT(pResult->GetErrorBuffer(&pErrors));
  264. const char *errors = (char *)pErrors->GetBufferPointer();
  265. output = errors;
  266. return resultStatus;
  267. }
  268. }
  269. FileRunCommandResult FileRunCommandPart::RunDxcHashTest(dxc::DxcDllSupport &DllSupport) {
  270. hlsl::options::MainArgs args;
  271. hlsl::options::DxcOpts opts;
  272. ReadOptsForDxc(args, opts);
  273. std::vector<std::wstring> argWStrings;
  274. CopyArgsToWStrings(opts.Args, hlsl::options::CoreOption, argWStrings);
  275. // Extract the vanilla flags for the test (i.e. no debug or ast-dump)
  276. std::vector<LPCWSTR> original_flags;
  277. for (const std::wstring &a : argWStrings) {
  278. if (a.find(L"ast-dump") != std::wstring::npos) continue;
  279. if (a.find(L"Zi") != std::wstring::npos) continue;
  280. original_flags.push_back(a.data());
  281. }
  282. std::string originalOutput;
  283. llvm::SmallString<32> originalHash;
  284. // If failed the original compilation, just pass the test. The original test was likely
  285. // testing for failure.
  286. if (FAILED(CompileForHash(opts, CommandFileName, DllSupport, original_flags, originalHash, originalOutput)))
  287. return FileRunCommandResult::Success();
  288. // Results of our compilations
  289. llvm::SmallString<32> Hash1;
  290. std::string Output0;
  291. llvm::SmallString<32> Hash0;
  292. std::string Output1;
  293. // Fail if -Qstrip_reflect failed the compilation
  294. std::vector<LPCWSTR> normal_flags = original_flags;
  295. normal_flags.push_back(L"-Qstrip_reflect");
  296. std::string StdErr;
  297. if (FAILED(CompileForHash(opts, CommandFileName, DllSupport, normal_flags, Hash0, Output0))) {
  298. StdErr += "Adding Qstrip_reflect failed compilation.";
  299. StdErr += originalOutput;
  300. StdErr += Output0;
  301. return FileRunCommandResult::Error(StdErr);
  302. }
  303. // Fail if -Qstrip_reflect failed the compilation
  304. std::vector<LPCWSTR> dbg_flags = original_flags;
  305. dbg_flags.push_back(L"/Zi");
  306. dbg_flags.push_back(L"-Qstrip_reflect");
  307. if (FAILED(CompileForHash(opts, CommandFileName, DllSupport, dbg_flags, Hash1, Output1))) {
  308. return FileRunCommandResult::Error("Adding Qstrip_reflect and Zi failed compilation.");
  309. }
  310. if (Hash0 != Hash1) {
  311. StdErr = "Hashes do not match between normal and debug!!!\n";
  312. StdErr += Output0;
  313. StdErr += Output1;
  314. return FileRunCommandResult::Error(StdErr);
  315. }
  316. return FileRunCommandResult::Success();
  317. }
  318. FileRunCommandResult FileRunCommandPart::RunDxc(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior) {
  319. // Support piping stdin from prior if needed.
  320. UNREFERENCED_PARAMETER(Prior);
  321. hlsl::options::MainArgs args;
  322. hlsl::options::DxcOpts opts;
  323. FileRunCommandResult readOptsResult = ReadOptsForDxc(args, opts);
  324. if (readOptsResult.ExitCode) return readOptsResult;
  325. std::wstring entry =
  326. Unicode::UTF8ToUTF16StringOrThrow(opts.EntryPoint.str().c_str());
  327. std::wstring profile =
  328. Unicode::UTF8ToUTF16StringOrThrow(opts.TargetProfile.str().c_str());
  329. std::vector<LPCWSTR> flags;
  330. if (opts.CodeGenHighLevel) {
  331. flags.push_back(L"-fcgl");
  332. }
  333. std::vector<std::wstring> argWStrings;
  334. CopyArgsToWStrings(opts.Args, hlsl::options::CoreOption, argWStrings);
  335. for (const std::wstring &a : argWStrings)
  336. flags.push_back(a.data());
  337. CComPtr<IDxcLibrary> pLibrary;
  338. CComPtr<IDxcCompiler> pCompiler;
  339. CComPtr<IDxcOperationResult> pResult;
  340. CComPtr<IDxcBlobEncoding> pSource;
  341. CComPtr<IDxcBlobEncoding> pDisassembly;
  342. CComPtr<IDxcBlob> pCompiledBlob;
  343. CComPtr<IDxcIncludeHandler> pIncludeHandler;
  344. HRESULT resultStatus;
  345. IFT(DllSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  346. IFT(pLibrary->CreateBlobFromFile(CommandFileName, nullptr, &pSource));
  347. IFT(pLibrary->CreateIncludeHandler(&pIncludeHandler));
  348. IFT(DllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler));
  349. IFT(pCompiler->Compile(pSource, CommandFileName, entry.c_str(), profile.c_str(),
  350. flags.data(), flags.size(), nullptr, 0, pIncludeHandler, &pResult));
  351. IFT(pResult->GetStatus(&resultStatus));
  352. FileRunCommandResult result = {};
  353. if (SUCCEEDED(resultStatus)) {
  354. IFT(pResult->GetResult(&pCompiledBlob));
  355. if (!opts.AstDump) {
  356. IFT(pCompiler->Disassemble(pCompiledBlob, &pDisassembly));
  357. result.StdOut = BlobToUtf8(pDisassembly);
  358. } else {
  359. result.StdOut = BlobToUtf8(pCompiledBlob);
  360. }
  361. CComPtr<IDxcBlobEncoding> pStdErr;
  362. IFT(pResult->GetErrorBuffer(&pStdErr));
  363. result.StdErr = BlobToUtf8(pStdErr);
  364. result.ExitCode = 0;
  365. }
  366. else {
  367. IFT(pResult->GetErrorBuffer(&pDisassembly));
  368. result.StdErr = BlobToUtf8(pDisassembly);
  369. result.ExitCode = resultStatus;
  370. }
  371. result.OpResult = pResult;
  372. return result;
  373. }
  374. FileRunCommandResult FileRunCommandPart::RunDxv(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior) {
  375. std::string args(strtrim(Arguments));
  376. const char *inputPos = strstr(args.c_str(), "%s");
  377. if (inputPos == nullptr) {
  378. return FileRunCommandResult::Error("Only supported pattern includes input file as argument");
  379. }
  380. args.erase(inputPos - args.c_str(), strlen("%s"));
  381. llvm::StringRef argsRef = args;
  382. llvm::SmallVector<llvm::StringRef, 8> splitArgs;
  383. argsRef.split(splitArgs, " ");
  384. IFTMSG(splitArgs.size()==1, "wrong arg num for dxv");
  385. CComPtr<IDxcLibrary> pLibrary;
  386. CComPtr<IDxcAssembler> pAssembler;
  387. CComPtr<IDxcValidator> pValidator;
  388. CComPtr<IDxcOperationResult> pResult;
  389. CComPtr<IDxcBlobEncoding> pSource;
  390. CComPtr<IDxcBlob> pContainerBlob;
  391. HRESULT resultStatus;
  392. IFT(DllSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  393. IFT(pLibrary->CreateBlobFromFile(CommandFileName, nullptr, &pSource));
  394. IFT(DllSupport.CreateInstance(CLSID_DxcAssembler, &pAssembler));
  395. IFT(pAssembler->AssembleToContainer(pSource, &pResult));
  396. IFT(pResult->GetStatus(&resultStatus));
  397. if (FAILED(resultStatus)) {
  398. CComPtr<IDxcBlobEncoding> pAssembleBlob;
  399. IFT(pResult->GetErrorBuffer(&pAssembleBlob));
  400. return FileRunCommandResult::Error(resultStatus, BlobToUtf8(pAssembleBlob));
  401. }
  402. IFT(pResult->GetResult(&pContainerBlob));
  403. IFT(DllSupport.CreateInstance(CLSID_DxcValidator, &pValidator));
  404. CComPtr<IDxcOperationResult> pValidationResult;
  405. IFT(pValidator->Validate(pContainerBlob, DxcValidatorFlags_InPlaceEdit,
  406. &pValidationResult));
  407. IFT(pValidationResult->GetStatus(&resultStatus));
  408. if (FAILED(resultStatus)) {
  409. CComPtr<IDxcBlobEncoding> pValidateBlob;
  410. IFT(pValidationResult->GetErrorBuffer(&pValidateBlob));
  411. return FileRunCommandResult::Success(BlobToUtf8(pValidateBlob));
  412. }
  413. return FileRunCommandResult::Success("");
  414. }
  415. FileRunCommandResult FileRunCommandPart::RunOpt(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior) {
  416. std::string args(strtrim(Arguments));
  417. const char *inputPos = strstr(args.c_str(), "%s");
  418. if (inputPos == nullptr && Prior == nullptr) {
  419. return FileRunCommandResult::Error("Only supported patterns are input file as argument or prior "
  420. "command with disassembly");
  421. }
  422. CComPtr<IDxcLibrary> pLibrary;
  423. CComPtr<IDxcOptimizer> pOptimizer;
  424. CComPtr<IDxcBlobEncoding> pSource;
  425. CComPtr<IDxcBlobEncoding> pOutputText;
  426. CComPtr<IDxcBlob> pOutputModule;
  427. IFT(DllSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  428. IFT(DllSupport.CreateInstance(CLSID_DxcOptimizer, &pOptimizer));
  429. if (inputPos != nullptr) {
  430. args.erase(inputPos - args.c_str(), strlen("%s"));
  431. IFT(pLibrary->CreateBlobFromFile(CommandFileName, nullptr, &pSource));
  432. }
  433. else {
  434. assert(Prior != nullptr && "else early check should have returned");
  435. CComPtr<IDxcAssembler> pAssembler;
  436. IFT(DllSupport.CreateInstance(CLSID_DxcAssembler, &pAssembler));
  437. IFT(pLibrary->CreateBlobWithEncodingFromPinned(
  438. Prior->StdOut.c_str(), Prior->StdOut.size(), CP_UTF8,
  439. &pSource));
  440. }
  441. args = strtrim(args);
  442. llvm::StringRef argsRef = args;
  443. llvm::SmallVector<llvm::StringRef, 8> splitArgs;
  444. argsRef.split(splitArgs, " ");
  445. std::vector<LPCWSTR> options;
  446. std::vector<std::wstring> optionStrings;
  447. for (llvm::StringRef S : splitArgs) {
  448. optionStrings.push_back(
  449. Unicode::UTF8ToUTF16StringOrThrow(strtrim(S.str()).c_str()));
  450. }
  451. // Add the options outside the above loop in case the vector is resized.
  452. for (const std::wstring& str : optionStrings)
  453. options.push_back(str.c_str());
  454. IFT(pOptimizer->RunOptimizer(pSource, options.data(), options.size(),
  455. &pOutputModule, &pOutputText));
  456. return FileRunCommandResult::Success(BlobToUtf8(pOutputText));
  457. }
  458. FileRunCommandResult FileRunCommandPart::RunD3DReflect(dxc::DxcDllSupport &DllSupport, const FileRunCommandResult *Prior) {
  459. std::string args(strtrim(Arguments));
  460. if (args != "%s")
  461. return FileRunCommandResult::Error("Only supported pattern is a plain input file");
  462. if (!Prior)
  463. return FileRunCommandResult::Error("Prior command required to generate stdin");
  464. CComPtr<IDxcLibrary> pLibrary;
  465. CComPtr<IDxcBlobEncoding> pSource;
  466. CComPtr<IDxcAssembler> pAssembler;
  467. CComPtr<IDxcOperationResult> pResult;
  468. CComPtr<ID3D12ShaderReflection> pShaderReflection;
  469. CComPtr<ID3D12LibraryReflection> pLibraryReflection;
  470. CComPtr<IDxcContainerReflection> containerReflection;
  471. uint32_t partCount;
  472. CComPtr<IDxcBlob> pContainerBlob;
  473. HRESULT resultStatus;
  474. bool blobFound = false;
  475. std::ostringstream ss;
  476. D3DReflectionDumper dumper(ss);
  477. IFT(DllSupport.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  478. IFT(DllSupport.CreateInstance(CLSID_DxcAssembler, &pAssembler));
  479. IFT(pLibrary->CreateBlobWithEncodingFromPinned(
  480. (LPBYTE)Prior->StdOut.c_str(), Prior->StdOut.size(), CP_UTF8,
  481. &pSource));
  482. IFT(pAssembler->AssembleToContainer(pSource, &pResult));
  483. IFT(pResult->GetStatus(&resultStatus));
  484. if (FAILED(resultStatus)) {
  485. CComPtr<IDxcBlobEncoding> pAssembleBlob;
  486. IFT(pResult->GetErrorBuffer(&pAssembleBlob));
  487. return FileRunCommandResult::Error(resultStatus, BlobToUtf8(pAssembleBlob));
  488. }
  489. IFT(pResult->GetResult(&pContainerBlob));
  490. VERIFY_SUCCEEDED(DllSupport.CreateInstance(CLSID_DxcContainerReflection, &containerReflection));
  491. VERIFY_SUCCEEDED(containerReflection->Load(pContainerBlob));
  492. VERIFY_SUCCEEDED(containerReflection->GetPartCount(&partCount));
  493. for (uint32_t i = 0; i < partCount; ++i) {
  494. uint32_t kind;
  495. VERIFY_SUCCEEDED(containerReflection->GetPartKind(i, &kind));
  496. if (kind == (uint32_t)hlsl::DxilFourCC::DFCC_DXIL) {
  497. blobFound = true;
  498. CComPtr<IDxcBlob> pPart;
  499. IFT(containerReflection->GetPartContent(i, &pPart));
  500. const hlsl::DxilProgramHeader *pProgramHeader =
  501. reinterpret_cast<const hlsl::DxilProgramHeader*>(pPart->GetBufferPointer());
  502. VERIFY_IS_TRUE(IsValidDxilProgramHeader(pProgramHeader, (uint32_t)pPart->GetBufferSize()));
  503. hlsl::DXIL::ShaderKind SK = hlsl::GetVersionShaderType(pProgramHeader->ProgramVersion);
  504. if (SK == hlsl::DXIL::ShaderKind::Library)
  505. VERIFY_SUCCEEDED(containerReflection->GetPartReflection(i, IID_PPV_ARGS(&pLibraryReflection)));
  506. else
  507. VERIFY_SUCCEEDED(containerReflection->GetPartReflection(i, IID_PPV_ARGS(&pShaderReflection)));
  508. break;
  509. }
  510. }
  511. if (!blobFound) {
  512. return FileRunCommandResult::Error("Unable to find DXIL part");
  513. } else if (pShaderReflection) {
  514. dumper.Dump(pShaderReflection);
  515. } else if (pLibraryReflection) {
  516. dumper.Dump(pLibraryReflection);
  517. }
  518. ss.flush();
  519. return FileRunCommandResult::Success(ss.str());
  520. }
  521. FileRunCommandResult FileRunCommandPart::RunTee(const FileRunCommandResult *Prior) {
  522. if (Prior == nullptr) {
  523. return FileRunCommandResult::Error("tee requires a prior command");
  524. }
  525. // Ignore commands for now - simply log out through test framework.
  526. {
  527. CA2W outWide(Prior->StdOut.c_str(), CP_UTF8);
  528. WEX::Logging::Log::Comment(outWide.m_psz);
  529. }
  530. if (!Prior->StdErr.empty()) {
  531. CA2W errWide(Prior->StdErr.c_str(), CP_UTF8);
  532. WEX::Logging::Log::Comment(L"<stderr>");
  533. WEX::Logging::Log::Comment(errWide.m_psz);
  534. }
  535. return *Prior;
  536. }
  537. FileRunCommandResult FileRunCommandPart::RunXFail(const FileRunCommandResult *Prior) {
  538. if (Prior == nullptr)
  539. return FileRunCommandResult::Error("XFail requires a prior command");
  540. if (Prior->ExitCode == 0) {
  541. return FileRunCommandResult::Error("XFail expected a failure from previous command");
  542. } else {
  543. return FileRunCommandResult::Success("");
  544. }
  545. }
  546. FileRunCommandResult FileRunCommandPart::RunDxilVer(dxc::DxcDllSupport& DllSupport, const FileRunCommandResult* Prior) {
  547. Arguments = strtrim(Arguments);
  548. if (Arguments.size() != 3 || !std::isdigit(Arguments[0]) || Arguments[1] != '.' || !std::isdigit(Arguments[2])) {
  549. return FileRunCommandResult::Error("Invalid dxil version format");
  550. }
  551. unsigned RequiredDxilMajor = Arguments[0] - '0';
  552. unsigned RequiredDxilMinor = Arguments[2] - '0';
  553. bool Supported = RequiredDxilMajor >= 1;
  554. CComPtr<IDxcCompiler> pCompiler;
  555. // If the following fails, we have Dxil 1.0 compiler
  556. if (SUCCEEDED(DllSupport.CreateInstance(CLSID_DxcCompiler, &pCompiler))) {
  557. CComPtr<IDxcVersionInfo> pVersionInfo;
  558. IFT(pCompiler.QueryInterface(&pVersionInfo));
  559. unsigned DxilMajor, DxilMinor;
  560. IFT(pVersionInfo->GetVersion(&DxilMajor, &DxilMinor));
  561. if (DxilMajor < RequiredDxilMajor || (DxilMajor == RequiredDxilMajor && DxilMinor < RequiredDxilMinor))
  562. Supported = false;
  563. }
  564. CComPtr<IDxcValidator> pValidator;
  565. if (SUCCEEDED(DllSupport.CreateInstance(CLSID_DxcValidator, &pValidator))) {
  566. CComPtr<IDxcVersionInfo> pVersionInfo;
  567. IFT(pValidator.QueryInterface(&pVersionInfo));
  568. unsigned DxilMajor, DxilMinor;
  569. VERIFY_SUCCEEDED(pVersionInfo->GetVersion(&DxilMajor, &DxilMinor));
  570. if (DxilMajor < RequiredDxilMajor || (DxilMajor == RequiredDxilMajor && DxilMinor < RequiredDxilMinor))
  571. Supported = false;
  572. }
  573. if (!Supported) {
  574. FileRunCommandResult result {};
  575. result.StdErr = "Skipping test due to unsupported dxil version";
  576. result.ExitCode = 0; // Succeed the test
  577. result.AbortPipeline = true;
  578. return result;
  579. }
  580. return FileRunCommandResult::Success();
  581. }
  582. class FileRunTestResultImpl : public FileRunTestResult {
  583. dxc::DxcDllSupport &m_support;
  584. void RunHashTestFromCommands(LPCSTR commands, LPCWSTR fileName) {
  585. std::vector<FileRunCommandPart> parts;
  586. ParseCommandParts(commands, fileName, parts);
  587. FileRunCommandResult result;
  588. bool ran = false;
  589. for (FileRunCommandPart & part : parts) {
  590. result = part.RunHashTests(m_support);
  591. ran = true;
  592. break;
  593. }
  594. if (ran) {
  595. this->RunResult = result.ExitCode;
  596. this->ErrorMessage = result.StdErr;
  597. }
  598. else {
  599. this->RunResult = 0;
  600. }
  601. }
  602. void RunFileCheckFromCommands(LPCSTR commands, LPCWSTR fileName) {
  603. std::vector<FileRunCommandPart> parts;
  604. ParseCommandParts(commands, fileName, parts);
  605. if (parts.empty()) {
  606. this->RunResult = 1;
  607. this->ErrorMessage = "FileCheck found no commands to run";
  608. return;
  609. }
  610. FileRunCommandResult result;
  611. FileRunCommandResult* previousResult = nullptr;
  612. for (FileRunCommandPart & part : parts) {
  613. result = part.Run(m_support, previousResult);
  614. previousResult = &result;
  615. if (result.AbortPipeline) break;
  616. }
  617. this->RunResult = result.ExitCode;
  618. this->ErrorMessage = result.StdErr;
  619. }
  620. public:
  621. FileRunTestResultImpl(dxc::DxcDllSupport &support) : m_support(support) {}
  622. void RunFileCheckFromFileCommands(LPCWSTR fileName) {
  623. // Assume UTF-8 files.
  624. std::string commands(GetFirstLine(fileName));
  625. return RunFileCheckFromCommands(commands.c_str(), fileName);
  626. }
  627. void RunHashTestFromFileCommands(LPCWSTR fileName) {
  628. // Assume UTF-8 files.
  629. std::string commands(GetFirstLine(fileName));
  630. return RunHashTestFromCommands(commands.c_str(), fileName);
  631. }
  632. };
  633. FileRunTestResult FileRunTestResult::RunHashTestFromFileCommands(LPCWSTR fileName) {
  634. dxc::DxcDllSupport dllSupport;
  635. IFT(dllSupport.Initialize());
  636. FileRunTestResultImpl result(dllSupport);
  637. result.RunHashTestFromFileCommands(fileName);
  638. return result;
  639. }
  640. FileRunTestResult FileRunTestResult::RunFromFileCommands(LPCWSTR fileName) {
  641. dxc::DxcDllSupport dllSupport;
  642. IFT(dllSupport.Initialize());
  643. FileRunTestResultImpl result(dllSupport);
  644. result.RunFileCheckFromFileCommands(fileName);
  645. return result;
  646. }
  647. FileRunTestResult FileRunTestResult::RunFromFileCommands(LPCWSTR fileName, dxc::DxcDllSupport &dllSupport) {
  648. FileRunTestResultImpl result(dllSupport);
  649. result.RunFileCheckFromFileCommands(fileName);
  650. return result;
  651. }
  652. void ParseCommandParts(LPCSTR commands, LPCWSTR fileName,
  653. std::vector<FileRunCommandPart> &parts) {
  654. // Barely enough parsing here.
  655. commands = strstr(commands, "RUN: ");
  656. if (!commands) {
  657. return;
  658. }
  659. commands += strlen("RUN: ");
  660. LPCSTR endCommands = strchr(commands, '\0');
  661. while (commands != endCommands) {
  662. LPCSTR nextStart;
  663. LPCSTR thisEnd = strchr(commands, '|');
  664. if (!thisEnd) {
  665. nextStart = thisEnd = endCommands;
  666. } else {
  667. nextStart = thisEnd + 2;
  668. }
  669. LPCSTR commandEnd = strchr(commands, ' ');
  670. if (!commandEnd)
  671. commandEnd = endCommands;
  672. parts.emplace_back(std::string(commands, commandEnd),
  673. std::string(commandEnd, thisEnd), fileName);
  674. commands = nextStart;
  675. }
  676. }
  677. void ParseCommandPartsFromFile(LPCWSTR fileName,
  678. std::vector<FileRunCommandPart> &parts) {
  679. // Assume UTF-8 files.
  680. std::string commands(GetFirstLine(fileName));
  681. ParseCommandParts(commands.c_str(), fileName, parts);
  682. }