TestFixture.h 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. //
  2. // Copyright (C) 2016 Google, Inc.
  3. //
  4. // All rights reserved.
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions
  8. // are met:
  9. //
  10. // Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. //
  13. // Redistributions in binary form must reproduce the above
  14. // copyright notice, this list of conditions and the following
  15. // disclaimer in the documentation and/or other materials provided
  16. // with the distribution.
  17. //
  18. // Neither the name of Google Inc. nor the names of its
  19. // contributors may be used to endorse or promote products derived
  20. // from this software without specific prior written permission.
  21. //
  22. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  25. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  26. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  27. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  28. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  29. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  30. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  31. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  32. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  33. // POSSIBILITY OF SUCH DAMAGE.
  34. #ifndef GLSLANG_GTESTS_TEST_FIXTURE_H
  35. #define GLSLANG_GTESTS_TEST_FIXTURE_H
  36. #include <cstdint>
  37. #include <fstream>
  38. #include <sstream>
  39. #include <streambuf>
  40. #include <tuple>
  41. #include <string>
  42. #include <gtest/gtest.h>
  43. #include "SPIRV/GlslangToSpv.h"
  44. #include "SPIRV/disassemble.h"
  45. #include "SPIRV/doc.h"
  46. #include "SPIRV/SPVRemapper.h"
  47. #include "StandAlone/ResourceLimits.h"
  48. #include "glslang/Public/ShaderLang.h"
  49. #include "Initializer.h"
  50. #include "Settings.h"
  51. namespace glslangtest {
  52. // This function is used to provide custom test name suffixes based on the
  53. // shader source file names. Otherwise, the test name suffixes will just be
  54. // numbers, which are not quite obvious.
  55. std::string FileNameAsCustomTestSuffix(
  56. const ::testing::TestParamInfo<std::string>& info);
  57. enum class Source {
  58. GLSL,
  59. HLSL,
  60. };
  61. // Enum for shader compilation semantics.
  62. enum class Semantics {
  63. OpenGL,
  64. Vulkan
  65. };
  66. // Enum for compilation target.
  67. enum class Target {
  68. AST,
  69. Spv,
  70. BothASTAndSpv,
  71. };
  72. EShLanguage GetShaderStage(const std::string& stage);
  73. EShMessages DeriveOptions(Source, Semantics, Target);
  74. // Reads the content of the file at the given |path|. On success, returns true
  75. // and the contents; otherwise, returns false and an empty string.
  76. std::pair<bool, std::string> ReadFile(const std::string& path);
  77. std::pair<bool, std::vector<std::uint32_t> > ReadSpvBinaryFile(const std::string& path);
  78. // Writes the given |contents| into the file at the given |path|. Returns true
  79. // on successful output.
  80. bool WriteFile(const std::string& path, const std::string& contents);
  81. // Returns the suffix of the given |name|.
  82. std::string GetSuffix(const std::string& name);
  83. // Base class for glslang integration tests. It contains many handy utility-like
  84. // methods such as reading shader source files, compiling into AST/SPIR-V, and
  85. // comparing with expected outputs.
  86. //
  87. // To write value-Parameterized tests:
  88. // using ValueParamTest = GlslangTest<::testing::TestWithParam<std::string>>;
  89. // To use as normal fixture:
  90. // using FixtureTest = GlslangTest<::testing::Test>;
  91. template <typename GT>
  92. class GlslangTest : public GT {
  93. public:
  94. GlslangTest()
  95. : defaultVersion(100),
  96. defaultProfile(ENoProfile),
  97. forceVersionProfile(false),
  98. isForwardCompatible(false) {
  99. // Perform validation by default.
  100. validatorOptions.validate = true;
  101. }
  102. // Tries to load the contents from the file at the given |path|. On success,
  103. // writes the contents into |contents|. On failure, errors out.
  104. void tryLoadFile(const std::string& path, const std::string& tag,
  105. std::string* contents)
  106. {
  107. bool fileReadOk;
  108. std::tie(fileReadOk, *contents) = ReadFile(path);
  109. ASSERT_TRUE(fileReadOk) << "Cannot open " << tag << " file: " << path;
  110. }
  111. // Tries to load the contents from the file at the given |path|. On success,
  112. // writes the contents into |contents|. On failure, errors out.
  113. void tryLoadSpvFile(const std::string& path, const std::string& tag,
  114. std::vector<uint32_t>& contents)
  115. {
  116. bool fileReadOk;
  117. std::tie(fileReadOk, contents) = ReadSpvBinaryFile(path);
  118. ASSERT_TRUE(fileReadOk) << "Cannot open " << tag << " file: " << path;
  119. }
  120. // Checks the equality of |expected| and |real|. If they are not equal,
  121. // write |real| to the given file named as |fname| if update mode is on.
  122. void checkEqAndUpdateIfRequested(const std::string& expected,
  123. const std::string& real,
  124. const std::string& fname,
  125. const std::string& errorsAndWarnings = "")
  126. {
  127. // In order to output the message we want under proper circumstances,
  128. // we need the following operator<< stuff.
  129. EXPECT_EQ(expected, real)
  130. << (GlobalTestSettings.updateMode
  131. ? ("Mismatch found and update mode turned on - "
  132. "flushing expected result output.\n")
  133. : "")
  134. << "The following warnings/errors occurred:\n"
  135. << errorsAndWarnings;
  136. // Update the expected output file if requested.
  137. // It looks weird to duplicate the comparison between expected_output
  138. // and stream.str(). However, if creating a variable for the comparison
  139. // result, we cannot have pretty print of the string diff in the above.
  140. if (GlobalTestSettings.updateMode && expected != real) {
  141. EXPECT_TRUE(WriteFile(fname, real)) << "Flushing failed";
  142. }
  143. }
  144. struct ShaderResult {
  145. std::string shaderName;
  146. std::string output;
  147. std::string error;
  148. };
  149. // A struct for holding all the information returned by glslang compilation
  150. // and linking.
  151. struct GlslangResult {
  152. std::vector<ShaderResult> shaderResults;
  153. std::string linkingOutput;
  154. std::string linkingError;
  155. bool validationResult;
  156. std::string spirvWarningsErrors;
  157. std::string spirv; // Optional SPIR-V disassembly text.
  158. };
  159. // Compiles and the given source |code| of the given shader |stage| into
  160. // the target under the semantics conveyed via |controls|. Returns true
  161. // and modifies |shader| on success.
  162. bool compile(glslang::TShader* shader, const std::string& code,
  163. const std::string& entryPointName, EShMessages controls,
  164. const TBuiltInResource* resources=nullptr,
  165. const std::string* shaderName=nullptr)
  166. {
  167. const char* shaderStrings = code.data();
  168. const int shaderLengths = static_cast<int>(code.size());
  169. const char* shaderNames = nullptr;
  170. if ((controls & EShMsgDebugInfo) && shaderName != nullptr) {
  171. shaderNames = shaderName->data();
  172. shader->setStringsWithLengthsAndNames(
  173. &shaderStrings, &shaderLengths, &shaderNames, 1);
  174. } else
  175. shader->setStringsWithLengths(&shaderStrings, &shaderLengths, 1);
  176. if (!entryPointName.empty()) shader->setEntryPoint(entryPointName.c_str());
  177. return shader->parse(
  178. (resources ? resources : &glslang::DefaultTBuiltInResource),
  179. defaultVersion, isForwardCompatible, controls);
  180. }
  181. // Compiles and links the given source |code| of the given shader
  182. // |stage| into the target under the semantics specified via |controls|.
  183. // Returns a GlslangResult instance containing all the information generated
  184. // during the process. If the target includes SPIR-V, also disassembles
  185. // the result and returns disassembly text.
  186. GlslangResult compileAndLink(
  187. const std::string& shaderName, const std::string& code,
  188. const std::string& entryPointName, EShMessages controls,
  189. glslang::EShTargetClientVersion clientTargetVersion,
  190. glslang::EShTargetLanguageVersion targetLanguageVersion,
  191. bool flattenUniformArrays = false,
  192. EShTextureSamplerTransformMode texSampTransMode = EShTexSampTransKeep,
  193. bool enableOptimizer = false,
  194. bool enableDebug = false,
  195. bool automap = true)
  196. {
  197. const EShLanguage stage = GetShaderStage(GetSuffix(shaderName));
  198. glslang::TShader shader(stage);
  199. if (automap) {
  200. shader.setAutoMapLocations(true);
  201. shader.setAutoMapBindings(true);
  202. }
  203. shader.setTextureSamplerTransformMode(texSampTransMode);
  204. #ifdef ENABLE_HLSL
  205. shader.setFlattenUniformArrays(flattenUniformArrays);
  206. #endif
  207. if (controls & EShMsgSpvRules) {
  208. if (controls & EShMsgVulkanRules) {
  209. shader.setEnvInput((controls & EShMsgReadHlsl) ? glslang::EShSourceHlsl
  210. : glslang::EShSourceGlsl,
  211. stage, glslang::EShClientVulkan, 100);
  212. shader.setEnvClient(glslang::EShClientVulkan, clientTargetVersion);
  213. shader.setEnvTarget(glslang::EShTargetSpv, targetLanguageVersion);
  214. } else {
  215. shader.setEnvInput((controls & EShMsgReadHlsl) ? glslang::EShSourceHlsl
  216. : glslang::EShSourceGlsl,
  217. stage, glslang::EShClientOpenGL, 100);
  218. shader.setEnvClient(glslang::EShClientOpenGL, clientTargetVersion);
  219. shader.setEnvTarget(glslang::EshTargetSpv, glslang::EShTargetSpv_1_0);
  220. }
  221. }
  222. bool success = compile(
  223. &shader, code, entryPointName, controls, nullptr, &shaderName);
  224. glslang::TProgram program;
  225. program.addShader(&shader);
  226. success &= program.link(controls);
  227. spv::SpvBuildLogger logger;
  228. if (success && (controls & EShMsgSpvRules)) {
  229. std::vector<uint32_t> spirv_binary;
  230. options().disableOptimizer = !enableOptimizer;
  231. options().generateDebugInfo = enableDebug;
  232. glslang::GlslangToSpv(*program.getIntermediate(stage),
  233. spirv_binary, &logger, &options());
  234. std::ostringstream disassembly_stream;
  235. spv::Parameterize();
  236. spv::Disassemble(disassembly_stream, spirv_binary);
  237. bool validation_result = !options().validate || logger.getAllMessages().empty();
  238. return {{{shaderName, shader.getInfoLog(), shader.getInfoDebugLog()},},
  239. program.getInfoLog(), program.getInfoDebugLog(),
  240. validation_result, logger.getAllMessages(), disassembly_stream.str()};
  241. } else {
  242. return {{{shaderName, shader.getInfoLog(), shader.getInfoDebugLog()},},
  243. program.getInfoLog(), program.getInfoDebugLog(), true, "", ""};
  244. }
  245. }
  246. // Compiles and links the given source |code| of the given shader
  247. // |stage| into the target under the semantics specified via |controls|.
  248. // Returns a GlslangResult instance containing all the information generated
  249. // during the process. If the target includes SPIR-V, also disassembles
  250. // the result and returns disassembly text.
  251. GlslangResult compileLinkIoMap(
  252. const std::string shaderName, const std::string& code,
  253. const std::string& entryPointName, EShMessages controls,
  254. int baseSamplerBinding,
  255. int baseTextureBinding,
  256. int baseImageBinding,
  257. int baseUboBinding,
  258. int baseSsboBinding,
  259. bool autoMapBindings,
  260. bool flattenUniformArrays)
  261. {
  262. const EShLanguage stage = GetShaderStage(GetSuffix(shaderName));
  263. glslang::TShader shader(stage);
  264. shader.setShiftSamplerBinding(baseSamplerBinding);
  265. shader.setShiftTextureBinding(baseTextureBinding);
  266. shader.setShiftImageBinding(baseImageBinding);
  267. shader.setShiftUboBinding(baseUboBinding);
  268. shader.setShiftSsboBinding(baseSsboBinding);
  269. shader.setAutoMapBindings(autoMapBindings);
  270. shader.setAutoMapLocations(true);
  271. #ifdef ENABLE_HLSL
  272. shader.setFlattenUniformArrays(flattenUniformArrays);
  273. #endif
  274. bool success = compile(&shader, code, entryPointName, controls);
  275. glslang::TProgram program;
  276. program.addShader(&shader);
  277. success &= program.link(controls);
  278. #ifndef GLSLANG_WEB
  279. success &= program.mapIO();
  280. #endif
  281. spv::SpvBuildLogger logger;
  282. if (success && (controls & EShMsgSpvRules)) {
  283. std::vector<uint32_t> spirv_binary;
  284. glslang::GlslangToSpv(*program.getIntermediate(stage),
  285. spirv_binary, &logger, &options());
  286. std::ostringstream disassembly_stream;
  287. spv::Parameterize();
  288. spv::Disassemble(disassembly_stream, spirv_binary);
  289. bool validation_result = !options().validate || logger.getAllMessages().empty();
  290. return {{{shaderName, shader.getInfoLog(), shader.getInfoDebugLog()},},
  291. program.getInfoLog(), program.getInfoDebugLog(),
  292. validation_result, logger.getAllMessages(), disassembly_stream.str()};
  293. } else {
  294. return {{{shaderName, shader.getInfoLog(), shader.getInfoDebugLog()},},
  295. program.getInfoLog(), program.getInfoDebugLog(), true, "", ""};
  296. }
  297. }
  298. // This is like compileAndLink but with remapping of the SPV binary
  299. // through spirvbin_t::remap(). While technically this could be merged
  300. // with compileAndLink() above (with the remap step optionally being a no-op)
  301. // it is given separately here for ease of future extraction.
  302. GlslangResult compileLinkRemap(
  303. const std::string shaderName, const std::string& code,
  304. const std::string& entryPointName, EShMessages controls,
  305. const unsigned int remapOptions = spv::spirvbin_t::NONE)
  306. {
  307. const EShLanguage stage = GetShaderStage(GetSuffix(shaderName));
  308. glslang::TShader shader(stage);
  309. shader.setAutoMapBindings(true);
  310. shader.setAutoMapLocations(true);
  311. bool success = compile(&shader, code, entryPointName, controls);
  312. glslang::TProgram program;
  313. program.addShader(&shader);
  314. success &= program.link(controls);
  315. spv::SpvBuildLogger logger;
  316. if (success && (controls & EShMsgSpvRules)) {
  317. std::vector<uint32_t> spirv_binary;
  318. glslang::GlslangToSpv(*program.getIntermediate(stage),
  319. spirv_binary, &logger, &options());
  320. spv::spirvbin_t(0 /*verbosity*/).remap(spirv_binary, remapOptions);
  321. std::ostringstream disassembly_stream;
  322. spv::Parameterize();
  323. spv::Disassemble(disassembly_stream, spirv_binary);
  324. bool validation_result = !options().validate || logger.getAllMessages().empty();
  325. return {{{shaderName, shader.getInfoLog(), shader.getInfoDebugLog()},},
  326. program.getInfoLog(), program.getInfoDebugLog(),
  327. validation_result, logger.getAllMessages(), disassembly_stream.str()};
  328. } else {
  329. return {{{shaderName, shader.getInfoLog(), shader.getInfoDebugLog()},},
  330. program.getInfoLog(), program.getInfoDebugLog(), true, "", ""};
  331. }
  332. }
  333. // remap the binary in 'code' with the options in remapOptions
  334. GlslangResult remap(
  335. const std::string shaderName, const std::vector<uint32_t>& code,
  336. EShMessages controls,
  337. const unsigned int remapOptions = spv::spirvbin_t::NONE)
  338. {
  339. if ((controls & EShMsgSpvRules)) {
  340. std::vector<uint32_t> spirv_binary(code); // scratch copy
  341. spv::spirvbin_t(0 /*verbosity*/).remap(spirv_binary, remapOptions);
  342. std::ostringstream disassembly_stream;
  343. spv::Parameterize();
  344. spv::Disassemble(disassembly_stream, spirv_binary);
  345. return {{{shaderName, "", ""},},
  346. "", "",
  347. true, "", disassembly_stream.str()};
  348. } else {
  349. return {{{shaderName, "", ""},}, "", "", true, "", ""};
  350. }
  351. }
  352. void outputResultToStream(std::ostringstream* stream,
  353. const GlslangResult& result,
  354. EShMessages controls)
  355. {
  356. const auto outputIfNotEmpty = [&stream](const std::string& str) {
  357. if (!str.empty()) *stream << str << "\n";
  358. };
  359. for (const auto& shaderResult : result.shaderResults) {
  360. *stream << shaderResult.shaderName << "\n";
  361. outputIfNotEmpty(shaderResult.output);
  362. outputIfNotEmpty(shaderResult.error);
  363. }
  364. outputIfNotEmpty(result.linkingOutput);
  365. outputIfNotEmpty(result.linkingError);
  366. if (!result.validationResult) {
  367. *stream << "Validation failed\n";
  368. }
  369. if (controls & EShMsgSpvRules) {
  370. *stream
  371. << (result.spirv.empty()
  372. ? "SPIR-V is not generated for failed compile or link\n"
  373. : result.spirv);
  374. }
  375. }
  376. void loadFileCompileAndCheck(const std::string& testDir,
  377. const std::string& testName,
  378. Source source,
  379. Semantics semantics,
  380. glslang::EShTargetClientVersion clientTargetVersion,
  381. glslang::EShTargetLanguageVersion targetLanguageVersion,
  382. Target target,
  383. bool automap = true,
  384. const std::string& entryPointName="",
  385. const std::string& baseDir="/baseResults/",
  386. const bool enableOptimizer = false,
  387. const bool enableDebug = false)
  388. {
  389. const std::string inputFname = testDir + "/" + testName;
  390. const std::string expectedOutputFname =
  391. testDir + baseDir + testName + ".out";
  392. std::string input, expectedOutput;
  393. tryLoadFile(inputFname, "input", &input);
  394. tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
  395. EShMessages controls = DeriveOptions(source, semantics, target);
  396. if (enableOptimizer)
  397. controls = static_cast<EShMessages>(controls & ~EShMsgHlslLegalization);
  398. if (enableDebug)
  399. controls = static_cast<EShMessages>(controls | EShMsgDebugInfo);
  400. GlslangResult result = compileAndLink(testName, input, entryPointName, controls, clientTargetVersion,
  401. targetLanguageVersion, false, EShTexSampTransKeep, enableOptimizer, enableDebug, automap);
  402. // Generate the hybrid output in the way of glslangValidator.
  403. std::ostringstream stream;
  404. outputResultToStream(&stream, result, controls);
  405. checkEqAndUpdateIfRequested(expectedOutput, stream.str(),
  406. expectedOutputFname, result.spirvWarningsErrors);
  407. }
  408. void loadFileCompileAndCheckWithOptions(const std::string &testDir,
  409. const std::string &testName,
  410. Source source,
  411. Semantics semantics,
  412. glslang::EShTargetClientVersion clientTargetVersion,
  413. glslang::EShTargetLanguageVersion targetLanguageVersion,
  414. Target target, bool automap = true, const std::string &entryPointName = "",
  415. const std::string &baseDir = "/baseResults/",
  416. const EShMessages additionalOptions = EShMessages::EShMsgDefault)
  417. {
  418. const std::string inputFname = testDir + "/" + testName;
  419. const std::string expectedOutputFname = testDir + baseDir + testName + ".out";
  420. std::string input, expectedOutput;
  421. tryLoadFile(inputFname, "input", &input);
  422. tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
  423. EShMessages controls = DeriveOptions(source, semantics, target);
  424. controls = static_cast<EShMessages>(controls | additionalOptions);
  425. GlslangResult result = compileAndLink(testName, input, entryPointName, controls, clientTargetVersion,
  426. targetLanguageVersion, false, EShTexSampTransKeep, false, automap);
  427. // Generate the hybrid output in the way of glslangValidator.
  428. std::ostringstream stream;
  429. outputResultToStream(&stream, result, controls);
  430. checkEqAndUpdateIfRequested(expectedOutput, stream.str(), expectedOutputFname);
  431. }
  432. void loadFileCompileFlattenUniformsAndCheck(const std::string& testDir,
  433. const std::string& testName,
  434. Source source,
  435. Semantics semantics,
  436. Target target,
  437. const std::string& entryPointName="")
  438. {
  439. const std::string inputFname = testDir + "/" + testName;
  440. const std::string expectedOutputFname =
  441. testDir + "/baseResults/" + testName + ".out";
  442. std::string input, expectedOutput;
  443. tryLoadFile(inputFname, "input", &input);
  444. tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
  445. const EShMessages controls = DeriveOptions(source, semantics, target);
  446. GlslangResult result = compileAndLink(testName, input, entryPointName, controls,
  447. glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0, true);
  448. // Generate the hybrid output in the way of glslangValidator.
  449. std::ostringstream stream;
  450. outputResultToStream(&stream, result, controls);
  451. checkEqAndUpdateIfRequested(expectedOutput, stream.str(),
  452. expectedOutputFname, result.spirvWarningsErrors);
  453. }
  454. void loadFileCompileIoMapAndCheck(const std::string& testDir,
  455. const std::string& testName,
  456. Source source,
  457. Semantics semantics,
  458. Target target,
  459. const std::string& entryPointName,
  460. int baseSamplerBinding,
  461. int baseTextureBinding,
  462. int baseImageBinding,
  463. int baseUboBinding,
  464. int baseSsboBinding,
  465. bool autoMapBindings,
  466. bool flattenUniformArrays)
  467. {
  468. const std::string inputFname = testDir + "/" + testName;
  469. const std::string expectedOutputFname =
  470. testDir + "/baseResults/" + testName + ".out";
  471. std::string input, expectedOutput;
  472. tryLoadFile(inputFname, "input", &input);
  473. tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
  474. const EShMessages controls = DeriveOptions(source, semantics, target);
  475. GlslangResult result = compileLinkIoMap(testName, input, entryPointName, controls,
  476. baseSamplerBinding, baseTextureBinding, baseImageBinding,
  477. baseUboBinding, baseSsboBinding,
  478. autoMapBindings,
  479. flattenUniformArrays);
  480. // Generate the hybrid output in the way of glslangValidator.
  481. std::ostringstream stream;
  482. outputResultToStream(&stream, result, controls);
  483. checkEqAndUpdateIfRequested(expectedOutput, stream.str(),
  484. expectedOutputFname, result.spirvWarningsErrors);
  485. }
  486. void loadFileCompileRemapAndCheck(const std::string& testDir,
  487. const std::string& testName,
  488. Source source,
  489. Semantics semantics,
  490. Target target,
  491. const std::string& entryPointName="",
  492. const unsigned int remapOptions = spv::spirvbin_t::NONE)
  493. {
  494. const std::string inputFname = testDir + "/" + testName;
  495. const std::string expectedOutputFname =
  496. testDir + "/baseResults/" + testName + ".out";
  497. std::string input, expectedOutput;
  498. tryLoadFile(inputFname, "input", &input);
  499. tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
  500. const EShMessages controls = DeriveOptions(source, semantics, target);
  501. GlslangResult result = compileLinkRemap(testName, input, entryPointName, controls, remapOptions);
  502. // Generate the hybrid output in the way of glslangValidator.
  503. std::ostringstream stream;
  504. outputResultToStream(&stream, result, controls);
  505. checkEqAndUpdateIfRequested(expectedOutput, stream.str(),
  506. expectedOutputFname, result.spirvWarningsErrors);
  507. }
  508. void loadFileRemapAndCheck(const std::string& testDir,
  509. const std::string& testName,
  510. Source source,
  511. Semantics semantics,
  512. Target target,
  513. const unsigned int remapOptions = spv::spirvbin_t::NONE)
  514. {
  515. const std::string inputFname = testDir + "/" + testName;
  516. const std::string expectedOutputFname =
  517. testDir + "/baseResults/" + testName + ".out";
  518. std::vector<std::uint32_t> input;
  519. std::string expectedOutput;
  520. tryLoadSpvFile(inputFname, "input", input);
  521. tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
  522. const EShMessages controls = DeriveOptions(source, semantics, target);
  523. GlslangResult result = remap(testName, input, controls, remapOptions);
  524. // Generate the hybrid output in the way of glslangValidator.
  525. std::ostringstream stream;
  526. outputResultToStream(&stream, result, controls);
  527. checkEqAndUpdateIfRequested(expectedOutput, stream.str(),
  528. expectedOutputFname, result.spirvWarningsErrors);
  529. }
  530. // Preprocesses the given |source| code. On success, returns true, the
  531. // preprocessed shader, and warning messages. Otherwise, returns false, an
  532. // empty string, and error messages.
  533. std::tuple<bool, std::string, std::string> preprocess(
  534. const std::string& source)
  535. {
  536. const char* shaderStrings = source.data();
  537. const int shaderLengths = static_cast<int>(source.size());
  538. glslang::TShader shader(EShLangVertex);
  539. shader.setStringsWithLengths(&shaderStrings, &shaderLengths, 1);
  540. std::string ppShader;
  541. glslang::TShader::ForbidIncluder includer;
  542. const bool success = shader.preprocess(
  543. &glslang::DefaultTBuiltInResource, defaultVersion, defaultProfile,
  544. forceVersionProfile, isForwardCompatible, (EShMessages)(EShMsgOnlyPreprocessor | EShMsgCascadingErrors),
  545. &ppShader, includer);
  546. std::string log = shader.getInfoLog();
  547. log += shader.getInfoDebugLog();
  548. if (success) {
  549. return std::make_tuple(true, ppShader, log);
  550. } else {
  551. return std::make_tuple(false, "", log);
  552. }
  553. }
  554. void loadFilePreprocessAndCheck(const std::string& testDir,
  555. const std::string& testName)
  556. {
  557. const std::string inputFname = testDir + "/" + testName;
  558. const std::string expectedOutputFname =
  559. testDir + "/baseResults/" + testName + ".out";
  560. const std::string expectedErrorFname =
  561. testDir + "/baseResults/" + testName + ".err";
  562. std::string input, expectedOutput, expectedError;
  563. tryLoadFile(inputFname, "input", &input);
  564. tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
  565. tryLoadFile(expectedErrorFname, "expected error", &expectedError);
  566. bool ppOk;
  567. std::string output, error;
  568. std::tie(ppOk, output, error) = preprocess(input);
  569. if (!output.empty()) output += '\n';
  570. if (!error.empty()) error += '\n';
  571. checkEqAndUpdateIfRequested(expectedOutput, output,
  572. expectedOutputFname);
  573. checkEqAndUpdateIfRequested(expectedError, error,
  574. expectedErrorFname);
  575. }
  576. void loadCompileUpgradeTextureToSampledTextureAndDropSamplersAndCheck(const std::string& testDir,
  577. const std::string& testName,
  578. Source source,
  579. Semantics semantics,
  580. Target target,
  581. const std::string& entryPointName = "")
  582. {
  583. const std::string inputFname = testDir + "/" + testName;
  584. const std::string expectedOutputFname = testDir + "/baseResults/" + testName + ".out";
  585. std::string input, expectedOutput;
  586. tryLoadFile(inputFname, "input", &input);
  587. tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
  588. const EShMessages controls = DeriveOptions(source, semantics, target);
  589. GlslangResult result = compileAndLink(testName, input, entryPointName, controls,
  590. glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0, false,
  591. EShTexSampTransUpgradeTextureRemoveSampler);
  592. // Generate the hybrid output in the way of glslangValidator.
  593. std::ostringstream stream;
  594. outputResultToStream(&stream, result, controls);
  595. checkEqAndUpdateIfRequested(expectedOutput, stream.str(),
  596. expectedOutputFname, result.spirvWarningsErrors);
  597. }
  598. glslang::SpvOptions& options() { return validatorOptions; }
  599. private:
  600. const int defaultVersion;
  601. const EProfile defaultProfile;
  602. const bool forceVersionProfile;
  603. const bool isForwardCompatible;
  604. glslang::SpvOptions validatorOptions;
  605. };
  606. } // namespace glslangtest
  607. #endif // GLSLANG_GTESTS_TEST_FIXTURE_H