TestFixture.h 31 KB

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