reduce.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. // Copyright (c) 2018 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <cassert>
  15. #include <cerrno>
  16. #include <cstdlib>
  17. #include <cstring>
  18. #include <functional>
  19. #include <sstream>
  20. #include "source/opt/build_module.h"
  21. #include "source/opt/ir_context.h"
  22. #include "source/opt/log.h"
  23. #include "source/reduce/reducer.h"
  24. #include "source/spirv_reducer_options.h"
  25. #include "source/util/string_utils.h"
  26. #include "tools/io.h"
  27. #include "tools/util/cli_consumer.h"
  28. namespace {
  29. // Execute a command using the shell.
  30. // Returns true if and only if the command's exit status was 0.
  31. bool ExecuteCommand(const std::string& command) {
  32. errno = 0;
  33. int status = std::system(command.c_str());
  34. assert(errno == 0 && "failed to execute command");
  35. // The result returned by 'system' is implementation-defined, but is
  36. // usually the case that the returned value is 0 when the command's exit
  37. // code was 0. We are assuming that here, and that's all we depend on.
  38. return status == 0;
  39. }
  40. // Status and actions to perform after parsing command-line arguments.
  41. enum ReduceActions { REDUCE_CONTINUE, REDUCE_STOP };
  42. struct ReduceStatus {
  43. ReduceActions action;
  44. int code;
  45. };
  46. void PrintUsage(const char* program) {
  47. // NOTE: Please maintain flags in lexicographical order.
  48. printf(
  49. R"(%s - Reduce a SPIR-V binary file with respect to a user-provided
  50. interestingness test.
  51. USAGE: %s [options] <input.spv> -o <output.spv> -- <interestingness_test> [args...]
  52. The SPIR-V binary is read from <input.spv>. The reduced SPIR-V binary is
  53. written to <output.spv>.
  54. Whether a binary is interesting is determined by <interestingness_test>, which
  55. should be the path to a script. The "--" characters are optional but denote
  56. that all arguments that follow are positional arguments and thus will be
  57. forwarded to the interestingness test, and not parsed by %s.
  58. * The script must be executable.
  59. * The script should take the path to a SPIR-V binary file (.spv) as an
  60. argument, and exit with code 0 if and only if the binary file is
  61. interesting. The binary will be passed to the script as an argument after
  62. any other provided arguments [args...].
  63. * Example: an interestingness test for reducing a SPIR-V binary file that
  64. causes tool "foo" to exit with error code 1 and print "Fatal error: bar" to
  65. standard error should:
  66. - invoke "foo" on the binary passed as the script argument;
  67. - capture the return code and standard error from "bar";
  68. - exit with code 0 if and only if the return code of "foo" was 1 and the
  69. standard error from "bar" contained "Fatal error: bar".
  70. * The reducer does not place a time limit on how long the interestingness test
  71. takes to run, so it is advisable to use per-command timeouts inside the
  72. script when invoking SPIR-V-processing tools (such as "foo" in the above
  73. example).
  74. NOTE: The reducer is a work in progress.
  75. Options (in lexicographical order):
  76. --fail-on-validation-error
  77. Stop reduction with an error if any reduction step produces a
  78. SPIR-V module that fails to validate.
  79. -h, --help
  80. Print this help.
  81. --step-limit=
  82. 32-bit unsigned integer specifying maximum number of steps the
  83. reducer will take before giving up.
  84. --target-function=
  85. 32-bit unsigned integer specifying the id of a function in the
  86. input module. The reducer will restrict attention to this
  87. function, and will not make changes to other functions or to
  88. instructions outside of functions, except that some global
  89. instructions may be added in support of reducing the target
  90. function. If 0 is specified (the default) then all functions are
  91. reduced.
  92. --temp-file-prefix=
  93. Specifies a temporary file prefix that will be used to output
  94. temporary shader files during reduction. A number and .spv
  95. extension will be added. The default is "temp_", which will
  96. cause files like "temp_0001.spv" to be output to the current
  97. directory.
  98. --version
  99. Display reducer version information.
  100. Supported validator options are as follows. See `spirv-val --help` for details.
  101. --before-hlsl-legalization
  102. --relax-block-layout
  103. --relax-logical-pointer
  104. --relax-struct-store
  105. --scalar-block-layout
  106. --skip-block-layout
  107. )",
  108. program, program, program);
  109. }
  110. // Message consumer for this tool. Used to emit diagnostics during
  111. // initialization and setup. Note that |source| and |position| are irrelevant
  112. // here because we are still not processing a SPIR-V input file.
  113. void ReduceDiagnostic(spv_message_level_t level, const char* /*source*/,
  114. const spv_position_t& /*position*/, const char* message) {
  115. if (level == SPV_MSG_ERROR) {
  116. fprintf(stderr, "error: ");
  117. }
  118. fprintf(stderr, "%s\n", message);
  119. }
  120. ReduceStatus ParseFlags(int argc, const char** argv,
  121. std::string* in_binary_file,
  122. std::string* out_binary_file,
  123. std::vector<std::string>* interestingness_test,
  124. std::string* temp_file_prefix,
  125. spvtools::ReducerOptions* reducer_options,
  126. spvtools::ValidatorOptions* validator_options) {
  127. uint32_t positional_arg_index = 0;
  128. bool only_positional_arguments_remain = false;
  129. for (int argi = 1; argi < argc; ++argi) {
  130. const char* cur_arg = argv[argi];
  131. if ('-' == cur_arg[0] && !only_positional_arguments_remain) {
  132. if (0 == strcmp(cur_arg, "--version")) {
  133. spvtools::Logf(ReduceDiagnostic, SPV_MSG_INFO, nullptr, {}, "%s\n",
  134. spvSoftwareVersionDetailsString());
  135. return {REDUCE_STOP, 0};
  136. } else if (0 == strcmp(cur_arg, "--help") || 0 == strcmp(cur_arg, "-h")) {
  137. PrintUsage(argv[0]);
  138. return {REDUCE_STOP, 0};
  139. } else if (0 == strcmp(cur_arg, "-o")) {
  140. if (out_binary_file->empty() && argi + 1 < argc) {
  141. *out_binary_file = std::string(argv[++argi]);
  142. } else {
  143. PrintUsage(argv[0]);
  144. return {REDUCE_STOP, 1};
  145. }
  146. } else if (0 == strncmp(cur_arg,
  147. "--step-limit=", sizeof("--step-limit=") - 1)) {
  148. const auto split_flag = spvtools::utils::SplitFlagArgs(cur_arg);
  149. char* end = nullptr;
  150. errno = 0;
  151. const auto step_limit =
  152. static_cast<uint32_t>(strtol(split_flag.second.c_str(), &end, 10));
  153. assert(end != split_flag.second.c_str() && errno == 0);
  154. reducer_options->set_step_limit(step_limit);
  155. } else if (0 == strncmp(cur_arg, "--target-function=",
  156. sizeof("--target-function=") - 1)) {
  157. const auto split_flag = spvtools::utils::SplitFlagArgs(cur_arg);
  158. char* end = nullptr;
  159. errno = 0;
  160. const auto target_function =
  161. static_cast<uint32_t>(strtol(split_flag.second.c_str(), &end, 10));
  162. assert(end != split_flag.second.c_str() && errno == 0);
  163. reducer_options->set_target_function(target_function);
  164. } else if (0 == strcmp(cur_arg, "--fail-on-validation-error")) {
  165. reducer_options->set_fail_on_validation_error(true);
  166. } else if (0 == strcmp(cur_arg, "--before-hlsl-legalization")) {
  167. validator_options->SetBeforeHlslLegalization(true);
  168. } else if (0 == strcmp(cur_arg, "--relax-logical-pointer")) {
  169. validator_options->SetRelaxLogicalPointer(true);
  170. } else if (0 == strcmp(cur_arg, "--relax-block-layout")) {
  171. validator_options->SetRelaxBlockLayout(true);
  172. } else if (0 == strcmp(cur_arg, "--scalar-block-layout")) {
  173. validator_options->SetScalarBlockLayout(true);
  174. } else if (0 == strcmp(cur_arg, "--skip-block-layout")) {
  175. validator_options->SetSkipBlockLayout(true);
  176. } else if (0 == strcmp(cur_arg, "--relax-struct-store")) {
  177. validator_options->SetRelaxStructStore(true);
  178. } else if (0 == strncmp(cur_arg, "--temp-file-prefix=",
  179. sizeof("--temp-file-prefix=") - 1)) {
  180. const auto split_flag = spvtools::utils::SplitFlagArgs(cur_arg);
  181. *temp_file_prefix = std::string(split_flag.second);
  182. } else if (0 == strcmp(cur_arg, "--")) {
  183. only_positional_arguments_remain = true;
  184. } else {
  185. std::stringstream ss;
  186. ss << "Unrecognized argument: " << cur_arg << std::endl;
  187. spvtools::Error(ReduceDiagnostic, nullptr, {}, ss.str().c_str());
  188. PrintUsage(argv[0]);
  189. return {REDUCE_STOP, 1};
  190. }
  191. } else if (positional_arg_index == 0) {
  192. // Binary input file name
  193. assert(in_binary_file->empty());
  194. *in_binary_file = std::string(cur_arg);
  195. positional_arg_index++;
  196. } else {
  197. interestingness_test->push_back(std::string(cur_arg));
  198. }
  199. }
  200. if (in_binary_file->empty()) {
  201. spvtools::Error(ReduceDiagnostic, nullptr, {}, "No input file specified");
  202. return {REDUCE_STOP, 1};
  203. }
  204. if (out_binary_file->empty()) {
  205. spvtools::Error(ReduceDiagnostic, nullptr, {}, "-o required");
  206. return {REDUCE_STOP, 1};
  207. }
  208. if (interestingness_test->empty()) {
  209. spvtools::Error(ReduceDiagnostic, nullptr, {},
  210. "No interestingness test specified");
  211. return {REDUCE_STOP, 1};
  212. }
  213. return {REDUCE_CONTINUE, 0};
  214. }
  215. } // namespace
  216. // Dumps |binary| to file |filename|. Useful for interactive debugging.
  217. void DumpShader(const std::vector<uint32_t>& binary, const char* filename) {
  218. auto write_file_succeeded =
  219. WriteFile(filename, "wb", &binary[0], binary.size());
  220. if (!write_file_succeeded) {
  221. std::cerr << "Failed to dump shader" << std::endl;
  222. }
  223. }
  224. // Dumps the SPIRV-V module in |context| to file |filename|. Useful for
  225. // interactive debugging.
  226. void DumpShader(spvtools::opt::IRContext* context, const char* filename) {
  227. std::vector<uint32_t> binary;
  228. context->module()->ToBinary(&binary, false);
  229. DumpShader(binary, filename);
  230. }
  231. const auto kDefaultEnvironment = SPV_ENV_UNIVERSAL_1_6;
  232. int main(int argc, const char** argv) {
  233. std::string in_binary_file;
  234. std::string out_binary_file;
  235. std::vector<std::string> interestingness_test;
  236. std::string temp_file_prefix = "temp_";
  237. spv_target_env target_env = kDefaultEnvironment;
  238. spvtools::ReducerOptions reducer_options;
  239. spvtools::ValidatorOptions validator_options;
  240. ReduceStatus status = ParseFlags(
  241. argc, argv, &in_binary_file, &out_binary_file, &interestingness_test,
  242. &temp_file_prefix, &reducer_options, &validator_options);
  243. if (status.action == REDUCE_STOP) {
  244. return status.code;
  245. }
  246. spvtools::reduce::Reducer reducer(target_env);
  247. std::stringstream joined;
  248. joined << interestingness_test[0];
  249. for (size_t i = 1, size = interestingness_test.size(); i < size; ++i) {
  250. joined << " " << interestingness_test[i];
  251. }
  252. std::string interestingness_command_joined = joined.str();
  253. reducer.SetInterestingnessFunction(
  254. [interestingness_command_joined, temp_file_prefix](
  255. std::vector<uint32_t> binary, uint32_t reductions_applied) -> bool {
  256. std::stringstream ss;
  257. ss << temp_file_prefix << std::setw(4) << std::setfill('0')
  258. << reductions_applied << ".spv";
  259. const auto spv_file = ss.str();
  260. const std::string command =
  261. interestingness_command_joined + " " + spv_file;
  262. auto write_file_succeeded =
  263. WriteFile(spv_file.c_str(), "wb", &binary[0], binary.size());
  264. (void)(write_file_succeeded);
  265. assert(write_file_succeeded);
  266. return ExecuteCommand(command);
  267. });
  268. reducer.AddDefaultReductionPasses();
  269. reducer.SetMessageConsumer(spvtools::utils::CLIMessageConsumer);
  270. std::vector<uint32_t> binary_in;
  271. if (!ReadBinaryFile(in_binary_file.c_str(), &binary_in)) {
  272. return 1;
  273. }
  274. const uint32_t target_function = (*reducer_options).target_function;
  275. if (target_function) {
  276. // A target function was specified; check that it exists.
  277. std::unique_ptr<spvtools::opt::IRContext> context = spvtools::BuildModule(
  278. kDefaultEnvironment, spvtools::utils::CLIMessageConsumer,
  279. binary_in.data(), binary_in.size());
  280. bool found_target_function = false;
  281. for (auto& function : *context->module()) {
  282. if (function.result_id() == target_function) {
  283. found_target_function = true;
  284. break;
  285. }
  286. }
  287. if (!found_target_function) {
  288. std::stringstream strstr;
  289. strstr << "Target function with id " << target_function
  290. << " was requested, but not found in the module; stopping.";
  291. spvtools::utils::CLIMessageConsumer(SPV_MSG_ERROR, nullptr, {},
  292. strstr.str().c_str());
  293. return 1;
  294. }
  295. }
  296. std::vector<uint32_t> binary_out;
  297. const auto reduction_status = reducer.Run(std::move(binary_in), &binary_out,
  298. reducer_options, validator_options);
  299. // Always try to write the output file, even if the reduction failed.
  300. if (!WriteFile<uint32_t>(out_binary_file.c_str(), "wb", binary_out.data(),
  301. binary_out.size())) {
  302. return 1;
  303. }
  304. // These are the only successful statuses.
  305. switch (reduction_status) {
  306. case spvtools::reduce::Reducer::ReductionResultStatus::kComplete:
  307. case spvtools::reduce::Reducer::ReductionResultStatus::kReachedStepLimit:
  308. return 0;
  309. default:
  310. break;
  311. }
  312. return 1;
  313. }