TestFixture.h 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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. shader.setFlattenUniformArrays(flattenUniformArrays);
  205. if (controls & EShMsgSpvRules) {
  206. if (controls & EShMsgVulkanRules) {
  207. shader.setEnvInput((controls & EShMsgReadHlsl) ? glslang::EShSourceHlsl
  208. : glslang::EShSourceGlsl,
  209. stage, glslang::EShClientVulkan, 100);
  210. shader.setEnvClient(glslang::EShClientVulkan, clientTargetVersion);
  211. shader.setEnvTarget(glslang::EShTargetSpv, targetLanguageVersion);
  212. } else {
  213. shader.setEnvInput((controls & EShMsgReadHlsl) ? glslang::EShSourceHlsl
  214. : glslang::EShSourceGlsl,
  215. stage, glslang::EShClientOpenGL, 100);
  216. shader.setEnvClient(glslang::EShClientOpenGL, clientTargetVersion);
  217. shader.setEnvTarget(glslang::EshTargetSpv, glslang::EShTargetSpv_1_0);
  218. }
  219. }
  220. bool success = compile(
  221. &shader, code, entryPointName, controls, nullptr, &shaderName);
  222. glslang::TProgram program;
  223. program.addShader(&shader);
  224. success &= program.link(controls);
  225. spv::SpvBuildLogger logger;
  226. if (success && (controls & EShMsgSpvRules)) {
  227. std::vector<uint32_t> spirv_binary;
  228. options().disableOptimizer = !enableOptimizer;
  229. options().generateDebugInfo = enableDebug;
  230. glslang::GlslangToSpv(*program.getIntermediate(stage),
  231. spirv_binary, &logger, &options());
  232. std::ostringstream disassembly_stream;
  233. spv::Parameterize();
  234. spv::Disassemble(disassembly_stream, spirv_binary);
  235. bool validation_result = !options().validate || logger.getAllMessages().empty();
  236. return {{{shaderName, shader.getInfoLog(), shader.getInfoDebugLog()},},
  237. program.getInfoLog(), program.getInfoDebugLog(),
  238. validation_result, logger.getAllMessages(), disassembly_stream.str()};
  239. } else {
  240. return {{{shaderName, shader.getInfoLog(), shader.getInfoDebugLog()},},
  241. program.getInfoLog(), program.getInfoDebugLog(), true, "", ""};
  242. }
  243. }
  244. // Compiles and links the given source |code| of the given shader
  245. // |stage| into the target under the semantics specified via |controls|.
  246. // Returns a GlslangResult instance containing all the information generated
  247. // during the process. If the target includes SPIR-V, also disassembles
  248. // the result and returns disassembly text.
  249. GlslangResult compileLinkIoMap(
  250. const std::string shaderName, const std::string& code,
  251. const std::string& entryPointName, EShMessages controls,
  252. int baseSamplerBinding,
  253. int baseTextureBinding,
  254. int baseImageBinding,
  255. int baseUboBinding,
  256. int baseSsboBinding,
  257. bool autoMapBindings,
  258. bool flattenUniformArrays)
  259. {
  260. const EShLanguage stage = GetShaderStage(GetSuffix(shaderName));
  261. glslang::TShader shader(stage);
  262. shader.setShiftSamplerBinding(baseSamplerBinding);
  263. shader.setShiftTextureBinding(baseTextureBinding);
  264. shader.setShiftImageBinding(baseImageBinding);
  265. shader.setShiftUboBinding(baseUboBinding);
  266. shader.setShiftSsboBinding(baseSsboBinding);
  267. shader.setAutoMapBindings(autoMapBindings);
  268. shader.setAutoMapLocations(true);
  269. shader.setFlattenUniformArrays(flattenUniformArrays);
  270. bool success = compile(&shader, code, entryPointName, controls);
  271. glslang::TProgram program;
  272. program.addShader(&shader);
  273. success &= program.link(controls);
  274. success &= program.mapIO();
  275. spv::SpvBuildLogger logger;
  276. if (success && (controls & EShMsgSpvRules)) {
  277. std::vector<uint32_t> spirv_binary;
  278. glslang::GlslangToSpv(*program.getIntermediate(stage),
  279. spirv_binary, &logger, &options());
  280. std::ostringstream disassembly_stream;
  281. spv::Parameterize();
  282. spv::Disassemble(disassembly_stream, spirv_binary);
  283. bool validation_result = !options().validate || logger.getAllMessages().empty();
  284. return {{{shaderName, shader.getInfoLog(), shader.getInfoDebugLog()},},
  285. program.getInfoLog(), program.getInfoDebugLog(),
  286. validation_result, logger.getAllMessages(), disassembly_stream.str()};
  287. } else {
  288. return {{{shaderName, shader.getInfoLog(), shader.getInfoDebugLog()},},
  289. program.getInfoLog(), program.getInfoDebugLog(), true, "", ""};
  290. }
  291. }
  292. // This is like compileAndLink but with remapping of the SPV binary
  293. // through spirvbin_t::remap(). While technically this could be merged
  294. // with compileAndLink() above (with the remap step optionally being a no-op)
  295. // it is given separately here for ease of future extraction.
  296. GlslangResult compileLinkRemap(
  297. const std::string shaderName, const std::string& code,
  298. const std::string& entryPointName, EShMessages controls,
  299. const unsigned int remapOptions = spv::spirvbin_t::NONE)
  300. {
  301. const EShLanguage stage = GetShaderStage(GetSuffix(shaderName));
  302. glslang::TShader shader(stage);
  303. shader.setAutoMapBindings(true);
  304. shader.setAutoMapLocations(true);
  305. bool success = compile(&shader, code, entryPointName, controls);
  306. glslang::TProgram program;
  307. program.addShader(&shader);
  308. success &= program.link(controls);
  309. spv::SpvBuildLogger logger;
  310. if (success && (controls & EShMsgSpvRules)) {
  311. std::vector<uint32_t> spirv_binary;
  312. glslang::GlslangToSpv(*program.getIntermediate(stage),
  313. spirv_binary, &logger, &options());
  314. spv::spirvbin_t(0 /*verbosity*/).remap(spirv_binary, remapOptions);
  315. std::ostringstream disassembly_stream;
  316. spv::Parameterize();
  317. spv::Disassemble(disassembly_stream, spirv_binary);
  318. bool validation_result = !options().validate || logger.getAllMessages().empty();
  319. return {{{shaderName, shader.getInfoLog(), shader.getInfoDebugLog()},},
  320. program.getInfoLog(), program.getInfoDebugLog(),
  321. validation_result, logger.getAllMessages(), disassembly_stream.str()};
  322. } else {
  323. return {{{shaderName, shader.getInfoLog(), shader.getInfoDebugLog()},},
  324. program.getInfoLog(), program.getInfoDebugLog(), true, "", ""};
  325. }
  326. }
  327. // remap the binary in 'code' with the options in remapOptions
  328. GlslangResult remap(
  329. const std::string shaderName, const std::vector<uint32_t>& code,
  330. EShMessages controls,
  331. const unsigned int remapOptions = spv::spirvbin_t::NONE)
  332. {
  333. if ((controls & EShMsgSpvRules)) {
  334. std::vector<uint32_t> spirv_binary(code); // scratch copy
  335. spv::spirvbin_t(0 /*verbosity*/).remap(spirv_binary, remapOptions);
  336. std::ostringstream disassembly_stream;
  337. spv::Parameterize();
  338. spv::Disassemble(disassembly_stream, spirv_binary);
  339. return {{{shaderName, "", ""},},
  340. "", "",
  341. true, "", disassembly_stream.str()};
  342. } else {
  343. return {{{shaderName, "", ""},}, "", "", true, "", ""};
  344. }
  345. }
  346. void outputResultToStream(std::ostringstream* stream,
  347. const GlslangResult& result,
  348. EShMessages controls)
  349. {
  350. const auto outputIfNotEmpty = [&stream](const std::string& str) {
  351. if (!str.empty()) *stream << str << "\n";
  352. };
  353. for (const auto& shaderResult : result.shaderResults) {
  354. *stream << shaderResult.shaderName << "\n";
  355. outputIfNotEmpty(shaderResult.output);
  356. outputIfNotEmpty(shaderResult.error);
  357. }
  358. outputIfNotEmpty(result.linkingOutput);
  359. outputIfNotEmpty(result.linkingError);
  360. if (!result.validationResult) {
  361. *stream << "Validation failed\n";
  362. }
  363. if (controls & EShMsgSpvRules) {
  364. *stream
  365. << (result.spirv.empty()
  366. ? "SPIR-V is not generated for failed compile or link\n"
  367. : result.spirv);
  368. }
  369. }
  370. void loadFileCompileAndCheck(const std::string& testDir,
  371. const std::string& testName,
  372. Source source,
  373. Semantics semantics,
  374. glslang::EShTargetClientVersion clientTargetVersion,
  375. glslang::EShTargetLanguageVersion targetLanguageVersion,
  376. Target target,
  377. bool automap = true,
  378. const std::string& entryPointName="",
  379. const std::string& baseDir="/baseResults/",
  380. const bool enableOptimizer = false,
  381. const bool enableDebug = false)
  382. {
  383. const std::string inputFname = testDir + "/" + testName;
  384. const std::string expectedOutputFname =
  385. testDir + baseDir + testName + ".out";
  386. std::string input, expectedOutput;
  387. tryLoadFile(inputFname, "input", &input);
  388. tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
  389. EShMessages controls = DeriveOptions(source, semantics, target);
  390. if (enableOptimizer)
  391. controls = static_cast<EShMessages>(controls & ~EShMsgHlslLegalization);
  392. if (enableDebug)
  393. controls = static_cast<EShMessages>(controls | EShMsgDebugInfo);
  394. GlslangResult result = compileAndLink(testName, input, entryPointName, controls, clientTargetVersion,
  395. targetLanguageVersion, false, EShTexSampTransKeep, enableOptimizer, enableDebug, automap);
  396. // Generate the hybrid output in the way of glslangValidator.
  397. std::ostringstream stream;
  398. outputResultToStream(&stream, result, controls);
  399. checkEqAndUpdateIfRequested(expectedOutput, stream.str(),
  400. expectedOutputFname, result.spirvWarningsErrors);
  401. }
  402. void loadFileCompileAndCheckWithOptions(const std::string &testDir,
  403. const std::string &testName,
  404. Source source,
  405. Semantics semantics,
  406. glslang::EShTargetClientVersion clientTargetVersion,
  407. glslang::EShTargetLanguageVersion targetLanguageVersion,
  408. Target target, bool automap = true, const std::string &entryPointName = "",
  409. const std::string &baseDir = "/baseResults/",
  410. const EShMessages additionalOptions = EShMessages::EShMsgDefault)
  411. {
  412. const std::string inputFname = testDir + "/" + testName;
  413. const std::string expectedOutputFname = testDir + baseDir + testName + ".out";
  414. std::string input, expectedOutput;
  415. tryLoadFile(inputFname, "input", &input);
  416. tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
  417. EShMessages controls = DeriveOptions(source, semantics, target);
  418. controls = static_cast<EShMessages>(controls | additionalOptions);
  419. GlslangResult result = compileAndLink(testName, input, entryPointName, controls, clientTargetVersion,
  420. targetLanguageVersion, false, EShTexSampTransKeep, false, automap);
  421. // Generate the hybrid output in the way of glslangValidator.
  422. std::ostringstream stream;
  423. outputResultToStream(&stream, result, controls);
  424. checkEqAndUpdateIfRequested(expectedOutput, stream.str(), expectedOutputFname);
  425. }
  426. void loadFileCompileFlattenUniformsAndCheck(const std::string& testDir,
  427. const std::string& testName,
  428. Source source,
  429. Semantics semantics,
  430. Target target,
  431. const std::string& entryPointName="")
  432. {
  433. const std::string inputFname = testDir + "/" + testName;
  434. const std::string expectedOutputFname =
  435. testDir + "/baseResults/" + testName + ".out";
  436. std::string input, expectedOutput;
  437. tryLoadFile(inputFname, "input", &input);
  438. tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
  439. const EShMessages controls = DeriveOptions(source, semantics, target);
  440. GlslangResult result = compileAndLink(testName, input, entryPointName, controls,
  441. glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0, true);
  442. // Generate the hybrid output in the way of glslangValidator.
  443. std::ostringstream stream;
  444. outputResultToStream(&stream, result, controls);
  445. checkEqAndUpdateIfRequested(expectedOutput, stream.str(),
  446. expectedOutputFname, result.spirvWarningsErrors);
  447. }
  448. void loadFileCompileIoMapAndCheck(const std::string& testDir,
  449. const std::string& testName,
  450. Source source,
  451. Semantics semantics,
  452. Target target,
  453. const std::string& entryPointName,
  454. int baseSamplerBinding,
  455. int baseTextureBinding,
  456. int baseImageBinding,
  457. int baseUboBinding,
  458. int baseSsboBinding,
  459. bool autoMapBindings,
  460. bool flattenUniformArrays)
  461. {
  462. const std::string inputFname = testDir + "/" + testName;
  463. const std::string expectedOutputFname =
  464. testDir + "/baseResults/" + testName + ".out";
  465. std::string input, expectedOutput;
  466. tryLoadFile(inputFname, "input", &input);
  467. tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
  468. const EShMessages controls = DeriveOptions(source, semantics, target);
  469. GlslangResult result = compileLinkIoMap(testName, input, entryPointName, controls,
  470. baseSamplerBinding, baseTextureBinding, baseImageBinding,
  471. baseUboBinding, baseSsboBinding,
  472. autoMapBindings,
  473. flattenUniformArrays);
  474. // Generate the hybrid output in the way of glslangValidator.
  475. std::ostringstream stream;
  476. outputResultToStream(&stream, result, controls);
  477. checkEqAndUpdateIfRequested(expectedOutput, stream.str(),
  478. expectedOutputFname, result.spirvWarningsErrors);
  479. }
  480. void loadFileCompileRemapAndCheck(const std::string& testDir,
  481. const std::string& testName,
  482. Source source,
  483. Semantics semantics,
  484. Target target,
  485. const std::string& entryPointName="",
  486. const unsigned int remapOptions = spv::spirvbin_t::NONE)
  487. {
  488. const std::string inputFname = testDir + "/" + testName;
  489. const std::string expectedOutputFname =
  490. testDir + "/baseResults/" + testName + ".out";
  491. std::string input, expectedOutput;
  492. tryLoadFile(inputFname, "input", &input);
  493. tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
  494. const EShMessages controls = DeriveOptions(source, semantics, target);
  495. GlslangResult result = compileLinkRemap(testName, input, entryPointName, controls, remapOptions);
  496. // Generate the hybrid output in the way of glslangValidator.
  497. std::ostringstream stream;
  498. outputResultToStream(&stream, result, controls);
  499. checkEqAndUpdateIfRequested(expectedOutput, stream.str(),
  500. expectedOutputFname, result.spirvWarningsErrors);
  501. }
  502. void loadFileRemapAndCheck(const std::string& testDir,
  503. const std::string& testName,
  504. Source source,
  505. Semantics semantics,
  506. Target target,
  507. const unsigned int remapOptions = spv::spirvbin_t::NONE)
  508. {
  509. const std::string inputFname = testDir + "/" + testName;
  510. const std::string expectedOutputFname =
  511. testDir + "/baseResults/" + testName + ".out";
  512. std::vector<std::uint32_t> input;
  513. std::string expectedOutput;
  514. tryLoadSpvFile(inputFname, "input", input);
  515. tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
  516. const EShMessages controls = DeriveOptions(source, semantics, target);
  517. GlslangResult result = remap(testName, input, controls, remapOptions);
  518. // Generate the hybrid output in the way of glslangValidator.
  519. std::ostringstream stream;
  520. outputResultToStream(&stream, result, controls);
  521. checkEqAndUpdateIfRequested(expectedOutput, stream.str(),
  522. expectedOutputFname, result.spirvWarningsErrors);
  523. }
  524. // Preprocesses the given |source| code. On success, returns true, the
  525. // preprocessed shader, and warning messages. Otherwise, returns false, an
  526. // empty string, and error messages.
  527. std::tuple<bool, std::string, std::string> preprocess(
  528. const std::string& source)
  529. {
  530. const char* shaderStrings = source.data();
  531. const int shaderLengths = static_cast<int>(source.size());
  532. glslang::TShader shader(EShLangVertex);
  533. shader.setStringsWithLengths(&shaderStrings, &shaderLengths, 1);
  534. std::string ppShader;
  535. glslang::TShader::ForbidIncluder includer;
  536. const bool success = shader.preprocess(
  537. &glslang::DefaultTBuiltInResource, defaultVersion, defaultProfile,
  538. forceVersionProfile, isForwardCompatible, (EShMessages)(EShMsgOnlyPreprocessor | EShMsgCascadingErrors),
  539. &ppShader, includer);
  540. std::string log = shader.getInfoLog();
  541. log += shader.getInfoDebugLog();
  542. if (success) {
  543. return std::make_tuple(true, ppShader, log);
  544. } else {
  545. return std::make_tuple(false, "", log);
  546. }
  547. }
  548. void loadFilePreprocessAndCheck(const std::string& testDir,
  549. const std::string& testName)
  550. {
  551. const std::string inputFname = testDir + "/" + testName;
  552. const std::string expectedOutputFname =
  553. testDir + "/baseResults/" + testName + ".out";
  554. const std::string expectedErrorFname =
  555. testDir + "/baseResults/" + testName + ".err";
  556. std::string input, expectedOutput, expectedError;
  557. tryLoadFile(inputFname, "input", &input);
  558. tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
  559. tryLoadFile(expectedErrorFname, "expected error", &expectedError);
  560. bool ppOk;
  561. std::string output, error;
  562. std::tie(ppOk, output, error) = preprocess(input);
  563. if (!output.empty()) output += '\n';
  564. if (!error.empty()) error += '\n';
  565. checkEqAndUpdateIfRequested(expectedOutput, output,
  566. expectedOutputFname);
  567. checkEqAndUpdateIfRequested(expectedError, error,
  568. expectedErrorFname);
  569. }
  570. void loadCompileUpgradeTextureToSampledTextureAndDropSamplersAndCheck(const std::string& testDir,
  571. const std::string& testName,
  572. Source source,
  573. Semantics semantics,
  574. Target target,
  575. const std::string& entryPointName = "")
  576. {
  577. const std::string inputFname = testDir + "/" + testName;
  578. const std::string expectedOutputFname = testDir + "/baseResults/" + testName + ".out";
  579. std::string input, expectedOutput;
  580. tryLoadFile(inputFname, "input", &input);
  581. tryLoadFile(expectedOutputFname, "expected output", &expectedOutput);
  582. const EShMessages controls = DeriveOptions(source, semantics, target);
  583. GlslangResult result = compileAndLink(testName, input, entryPointName, controls,
  584. glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0, false,
  585. EShTexSampTransUpgradeTextureRemoveSampler);
  586. // Generate the hybrid output in the way of glslangValidator.
  587. std::ostringstream stream;
  588. outputResultToStream(&stream, result, controls);
  589. checkEqAndUpdateIfRequested(expectedOutput, stream.str(),
  590. expectedOutputFname, result.spirvWarningsErrors);
  591. }
  592. glslang::SpvOptions& options() { return validatorOptions; }
  593. private:
  594. const int defaultVersion;
  595. const EProfile defaultProfile;
  596. const bool forceVersionProfile;
  597. const bool isForwardCompatible;
  598. glslang::SpvOptions validatorOptions;
  599. };
  600. } // namespace glslangtest
  601. #endif // GLSLANG_GTESTS_TEST_FIXTURE_H