2
0

opt.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. // Copyright (c) 2016 Google Inc.
  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 <algorithm>
  15. #include <cassert>
  16. #include <cstring>
  17. #include <fstream>
  18. #include <iostream>
  19. #include <memory>
  20. #include <sstream>
  21. #include <string>
  22. #include <vector>
  23. #include "source/opt/log.h"
  24. #include "source/spirv_target_env.h"
  25. #include "source/util/string_utils.h"
  26. #include "spirv-tools/libspirv.hpp"
  27. #include "spirv-tools/optimizer.hpp"
  28. #include "tools/io.h"
  29. #include "tools/util/cli_consumer.h"
  30. namespace {
  31. // Status and actions to perform after parsing command-line arguments.
  32. enum OptActions { OPT_CONTINUE, OPT_STOP };
  33. struct OptStatus {
  34. OptActions action;
  35. int code;
  36. };
  37. // Message consumer for this tool. Used to emit diagnostics during
  38. // initialization and setup. Note that |source| and |position| are irrelevant
  39. // here because we are still not processing a SPIR-V input file.
  40. void opt_diagnostic(spv_message_level_t level, const char* /*source*/,
  41. const spv_position_t& /*positon*/, const char* message) {
  42. if (level == SPV_MSG_ERROR) {
  43. fprintf(stderr, "error: ");
  44. }
  45. fprintf(stderr, "%s\n", message);
  46. }
  47. std::string GetListOfPassesAsString(const spvtools::Optimizer& optimizer) {
  48. std::stringstream ss;
  49. for (const auto& name : optimizer.GetPassNames()) {
  50. ss << "\n\t\t" << name;
  51. }
  52. return ss.str();
  53. }
  54. const auto kDefaultEnvironment = SPV_ENV_UNIVERSAL_1_3;
  55. std::string GetLegalizationPasses() {
  56. spvtools::Optimizer optimizer(kDefaultEnvironment);
  57. optimizer.RegisterLegalizationPasses();
  58. return GetListOfPassesAsString(optimizer);
  59. }
  60. std::string GetOptimizationPasses() {
  61. spvtools::Optimizer optimizer(kDefaultEnvironment);
  62. optimizer.RegisterPerformancePasses();
  63. return GetListOfPassesAsString(optimizer);
  64. }
  65. std::string GetSizePasses() {
  66. spvtools::Optimizer optimizer(kDefaultEnvironment);
  67. optimizer.RegisterSizePasses();
  68. return GetListOfPassesAsString(optimizer);
  69. }
  70. std::string GetWebGPUPasses() {
  71. spvtools::Optimizer optimizer(SPV_ENV_WEBGPU_0);
  72. optimizer.RegisterWebGPUPasses();
  73. return GetListOfPassesAsString(optimizer);
  74. }
  75. void PrintUsage(const char* program) {
  76. // NOTE: Please maintain flags in lexicographical order.
  77. printf(
  78. R"(%s - Optimize a SPIR-V binary file.
  79. USAGE: %s [options] [<input>] -o <output>
  80. The SPIR-V binary is read from <input>. If no file is specified,
  81. or if <input> is "-", then the binary is read from standard input.
  82. if <output> is "-", then the optimized output is written to
  83. standard output.
  84. NOTE: The optimizer is a work in progress.
  85. Options (in lexicographical order):
  86. --ccp
  87. Apply the conditional constant propagation transform. This will
  88. propagate constant values throughout the program, and simplify
  89. expressions and conditional jumps with known predicate
  90. values. Performed on entry point call tree functions and
  91. exported functions.
  92. --cfg-cleanup
  93. Cleanup the control flow graph. This will remove any unnecessary
  94. code from the CFG like unreachable code. Performed on entry
  95. point call tree functions and exported functions.
  96. --combine-access-chains
  97. Combines chained access chains to produce a single instruction
  98. where possible.
  99. --compact-ids
  100. Remap result ids to a compact range starting from %%1 and without
  101. any gaps.
  102. --convert-local-access-chains
  103. Convert constant index access chain loads/stores into
  104. equivalent load/stores with inserts and extracts. Performed
  105. on function scope variables referenced only with load, store,
  106. and constant index access chains in entry point call tree
  107. functions.
  108. --copy-propagate-arrays
  109. Does propagation of memory references when an array is a copy of
  110. another. It will only propagate an array if the source is never
  111. written to, and the only store to the target is the copy.
  112. --eliminate-common-uniform
  113. Perform load/load elimination for duplicate uniform values.
  114. Converts any constant index access chain uniform loads into
  115. its equivalent load and extract. Some loads will be moved
  116. to facilitate sharing. Performed only on entry point
  117. call tree functions.
  118. --eliminate-dead-branches
  119. Convert conditional branches with constant condition to the
  120. indicated unconditional brranch. Delete all resulting dead
  121. code. Performed only on entry point call tree functions.
  122. --eliminate-dead-code-aggressive
  123. Delete instructions which do not contribute to a function's
  124. output. Performed only on entry point call tree functions.
  125. --eliminate-dead-const
  126. Eliminate dead constants.
  127. --eliminate-dead-functions
  128. Deletes functions that cannot be reached from entry points or
  129. exported functions.
  130. --eliminate-dead-inserts
  131. Deletes unreferenced inserts into composites, most notably
  132. unused stores to vector components, that are not removed by
  133. aggressive dead code elimination.
  134. --eliminate-dead-variables
  135. Deletes module scope variables that are not referenced.
  136. --eliminate-insert-extract
  137. DEPRECATED. This pass has been replaced by the simplification
  138. pass, and that pass will be run instead.
  139. See --simplify-instructions.
  140. --eliminate-local-multi-store
  141. Replace stores and loads of function scope variables that are
  142. stored multiple times. Performed on variables referenceed only
  143. with loads and stores. Performed only on entry point call tree
  144. functions.
  145. --eliminate-local-single-block
  146. Perform single-block store/load and load/load elimination.
  147. Performed only on function scope variables in entry point
  148. call tree functions.
  149. --eliminate-local-single-store
  150. Replace stores and loads of function scope variables that are
  151. only stored once. Performed on variables referenceed only with
  152. loads and stores. Performed only on entry point call tree
  153. functions.
  154. --flatten-decorations
  155. Replace decoration groups with repeated OpDecorate and
  156. OpMemberDecorate instructions.
  157. --fold-spec-const-op-composite
  158. Fold the spec constants defined by OpSpecConstantOp or
  159. OpSpecConstantComposite instructions to front-end constants
  160. when possible.
  161. --freeze-spec-const
  162. Freeze the values of specialization constants to their default
  163. values.
  164. --if-conversion
  165. Convert if-then-else like assignments into OpSelect.
  166. --inline-entry-points-exhaustive
  167. Exhaustively inline all function calls in entry point call tree
  168. functions. Currently does not inline calls to functions with
  169. early return in a loop.
  170. --legalize-hlsl
  171. Runs a series of optimizations that attempts to take SPIR-V
  172. generated by an HLSL front-end and generates legal Vulkan SPIR-V.
  173. The optimizations are:
  174. %s
  175. Note this does not guarantee legal code. This option passes the
  176. option --relax-logical-pointer to the validator.
  177. --local-redundancy-elimination
  178. Looks for instructions in the same basic block that compute the
  179. same value, and deletes the redundant ones.
  180. --loop-fission
  181. Splits any top level loops in which the register pressure has
  182. exceeded a given threshold. The threshold must follow the use of
  183. this flag and must be a positive integer value.
  184. --loop-fusion
  185. Identifies adjacent loops with the same lower and upper bound.
  186. If this is legal, then merge the loops into a single loop.
  187. Includes heuristics to ensure it does not increase number of
  188. registers too much, while reducing the number of loads from
  189. memory. Takes an additional positive integer argument to set
  190. the maximum number of registers.
  191. --loop-invariant-code-motion
  192. Identifies code in loops that has the same value for every
  193. iteration of the loop, and move it to the loop pre-header.
  194. --loop-unroll
  195. Fully unrolls loops marked with the Unroll flag
  196. --loop-unroll-partial
  197. Partially unrolls loops marked with the Unroll flag. Takes an
  198. additional non-0 integer argument to set the unroll factor, or
  199. how many times a loop body should be duplicated
  200. --loop-peeling
  201. Execute few first (respectively last) iterations before
  202. (respectively after) the loop if it can elide some branches.
  203. --loop-peeling-threshold
  204. Takes a non-0 integer argument to set the loop peeling code size
  205. growth threshold. The threshold prevents the loop peeling
  206. from happening if the code size increase created by
  207. the optimization is above the threshold.
  208. --max-id-bound=<n>
  209. Sets the maximum value for the id bound for the moudle. The
  210. default is the minimum value for this limit, 0x3FFFFF. See
  211. section 2.17 of the Spir-V specification.
  212. --merge-blocks
  213. Join two blocks into a single block if the second has the
  214. first as its only predecessor. Performed only on entry point
  215. call tree functions.
  216. --merge-return
  217. Changes functions that have multiple return statements so they
  218. have a single return statement.
  219. For structured control flow it is assumed that the only
  220. unreachable blocks in the function are trivial merge and continue
  221. blocks.
  222. A trivial merge block contains the label and an OpUnreachable
  223. instructions, nothing else. A trivial continue block contain a
  224. label and an OpBranch to the header, nothing else.
  225. These conditions are guaranteed to be met after running
  226. dead-branch elimination.
  227. --loop-unswitch
  228. Hoists loop-invariant conditionals out of loops by duplicating
  229. the loop on each branch of the conditional and adjusting each
  230. copy of the loop.
  231. -O
  232. Optimize for performance. Apply a sequence of transformations
  233. in an attempt to improve the performance of the generated
  234. code. For this version of the optimizer, this flag is equivalent
  235. to specifying the following optimization code names:
  236. %s
  237. -Os
  238. Optimize for size. Apply a sequence of transformations in an
  239. attempt to minimize the size of the generated code. For this
  240. version of the optimizer, this flag is equivalent to specifying
  241. the following optimization code names:
  242. %s
  243. NOTE: The specific transformations done by -O and -Os change
  244. from release to release.
  245. -Oconfig=<file>
  246. Apply the sequence of transformations indicated in <file>.
  247. This file contains a sequence of strings separated by whitespace
  248. (tabs, newlines or blanks). Each string is one of the flags
  249. accepted by spirv-opt. Optimizations will be applied in the
  250. sequence they appear in the file. This is equivalent to
  251. specifying all the flags on the command line. For example,
  252. given the file opts.cfg with the content:
  253. --inline-entry-points-exhaustive
  254. --eliminate-dead-code-aggressive
  255. The following two invocations to spirv-opt are equivalent:
  256. $ spirv-opt -Oconfig=opts.cfg program.spv
  257. $ spirv-opt --inline-entry-points-exhaustive \
  258. --eliminate-dead-code-aggressive program.spv
  259. Lines starting with the character '#' in the configuration
  260. file indicate a comment and will be ignored.
  261. The -O, -Os, and -Oconfig flags act as macros. Using one of them
  262. is equivalent to explicitly inserting the underlying flags at
  263. that position in the command line. For example, the invocation
  264. 'spirv-opt --merge-blocks -O ...' applies the transformation
  265. --merge-blocks followed by all the transformations implied by
  266. -O.
  267. --print-all
  268. Print SPIR-V assembly to standard error output before each pass
  269. and after the last pass.
  270. --private-to-local
  271. Change the scope of private variables that are used in a single
  272. function to that function.
  273. --reduce-load-size
  274. Replaces loads of composite objects where not every component is
  275. used by loads of just the elements that are used.
  276. --redundancy-elimination
  277. Looks for instructions in the same function that compute the
  278. same value, and deletes the redundant ones.
  279. --relax-struct-store
  280. Allow store from one struct type to a different type with
  281. compatible layout and members. This option is forwarded to the
  282. validator.
  283. --remove-duplicates
  284. Removes duplicate types, decorations, capabilities and extension
  285. instructions.
  286. --replace-invalid-opcode
  287. Replaces instructions whose opcode is valid for shader modules,
  288. but not for the current shader stage. To have an effect, all
  289. entry points must have the same execution model.
  290. --ssa-rewrite
  291. Replace loads and stores to function local variables with
  292. operations on SSA IDs.
  293. --scalar-replacement[=<n>]
  294. Replace aggregate function scope variables that are only accessed
  295. via their elements with new function variables representing each
  296. element. <n> is a limit on the size of the aggragates that will
  297. be replaced. 0 means there is no limit. The default value is
  298. 100.
  299. --set-spec-const-default-value "<spec id>:<default value> ..."
  300. Set the default values of the specialization constants with
  301. <spec id>:<default value> pairs specified in a double-quoted
  302. string. <spec id>:<default value> pairs must be separated by
  303. blank spaces, and in each pair, spec id and default value must
  304. be separated with colon ':' without any blank spaces in between.
  305. e.g.: --set-spec-const-default-value "1:100 2:400"
  306. --simplify-instructions
  307. Will simplify all instructions in the function as much as
  308. possible.
  309. --skip-validation
  310. Will not validate the SPIR-V before optimizing. If the SPIR-V
  311. is invalid, the optimizer may fail or generate incorrect code.
  312. This options should be used rarely, and with caution.
  313. --strength-reduction
  314. Replaces instructions with equivalent and less expensive ones.
  315. --strip-atomic-counter-memory
  316. Removes AtomicCountMemory bit from memory semantics values.
  317. --strip-debug
  318. Remove all debug instructions.
  319. --strip-reflect
  320. Remove all reflection information. For now, this covers
  321. reflection information defined by SPV_GOOGLE_hlsl_functionality1.
  322. --target-env=<env>
  323. Set the target environment. Without this flag the target
  324. enviroment defaults to spv1.3.
  325. <env> must be one of vulkan1.0, vulkan1.1, opencl2.2, spv1.0,
  326. spv1.1, spv1.2, spv1.3, or webgpu0.
  327. --time-report
  328. Print the resource utilization of each pass (e.g., CPU time,
  329. RSS) to standard error output. Currently it supports only Unix
  330. systems. This option is the same as -ftime-report in GCC. It
  331. prints CPU/WALL/USR/SYS time (and RSS if possible), but note that
  332. USR/SYS time are returned by getrusage() and can have a small
  333. error.
  334. --upgrade-memory-model
  335. Upgrades the Logical GLSL450 memory model to Logical VulkanKHR.
  336. Transforms memory, image, atomic and barrier operations to conform
  337. to that model's requirements.
  338. --vector-dce
  339. This pass looks for components of vectors that are unused, and
  340. removes them from the vector. Note this would still leave around
  341. lots of dead code that a pass of ADCE will be able to remove.
  342. --webgpu-mode
  343. Turns on the prescribed passes for WebGPU and sets the target
  344. environmet to webgpu0. Other passes may be turned on via
  345. additional flags, but such combinations are not tested.
  346. Using --target-env with this flag is not allowed.
  347. This flag is the equivalent of passing in --target-env=webgpu0
  348. and specifying the following optimization code names:
  349. %s
  350. NOTE: This flag is a WIP and its behaviour is subject to change.
  351. --workaround-1209
  352. Rewrites instructions for which there are known driver bugs to
  353. avoid triggering those bugs.
  354. Current workarounds: Avoid OpUnreachable in loops.
  355. --unify-const
  356. Remove the duplicated constants.
  357. --validate-after-all
  358. Validate the module after each pass is performed.
  359. -h, --help
  360. Print this help.
  361. --version
  362. Display optimizer version information.
  363. )",
  364. program, program, GetLegalizationPasses().c_str(),
  365. GetOptimizationPasses().c_str(), GetSizePasses().c_str(),
  366. GetWebGPUPasses().c_str());
  367. }
  368. // Reads command-line flags the file specified in |oconfig_flag|. This string
  369. // is assumed to have the form "-Oconfig=FILENAME". This function parses the
  370. // string and extracts the file name after the '=' sign.
  371. //
  372. // Flags found in |FILENAME| are pushed at the end of the vector |file_flags|.
  373. //
  374. // This function returns true on success, false on failure.
  375. bool ReadFlagsFromFile(const char* oconfig_flag,
  376. std::vector<std::string>* file_flags) {
  377. const char* fname = strchr(oconfig_flag, '=');
  378. if (fname == nullptr || fname[0] != '=') {
  379. spvtools::Errorf(opt_diagnostic, nullptr, {}, "Invalid -Oconfig flag %s",
  380. oconfig_flag);
  381. return false;
  382. }
  383. fname++;
  384. std::ifstream input_file;
  385. input_file.open(fname);
  386. if (input_file.fail()) {
  387. spvtools::Errorf(opt_diagnostic, nullptr, {}, "Could not open file '%s'",
  388. fname);
  389. return false;
  390. }
  391. std::string line;
  392. while (std::getline(input_file, line)) {
  393. // Ignore empty lines and lines starting with the comment marker '#'.
  394. if (line.length() == 0 || line[0] == '#') {
  395. continue;
  396. }
  397. // Tokenize the line. Add all found tokens to the list of found flags. This
  398. // mimics the way the shell will parse whitespace on the command line. NOTE:
  399. // This does not support quoting and it is not intended to.
  400. std::istringstream iss(line);
  401. while (!iss.eof()) {
  402. std::string flag;
  403. iss >> flag;
  404. file_flags->push_back(flag);
  405. }
  406. }
  407. return true;
  408. }
  409. OptStatus ParseFlags(int argc, const char** argv,
  410. spvtools::Optimizer* optimizer, const char** in_file,
  411. const char** out_file,
  412. spvtools::ValidatorOptions* validator_options,
  413. spvtools::OptimizerOptions* optimizer_options);
  414. // Parses and handles the -Oconfig flag. |prog_name| contains the name of
  415. // the spirv-opt binary (used to build a new argv vector for the recursive
  416. // invocation to ParseFlags). |opt_flag| contains the -Oconfig=FILENAME flag.
  417. // |optimizer|, |in_file|, |out_file|, |validator_options|, and
  418. // |optimizer_options| are as in ParseFlags.
  419. //
  420. // This returns the same OptStatus instance returned by ParseFlags.
  421. OptStatus ParseOconfigFlag(const char* prog_name, const char* opt_flag,
  422. spvtools::Optimizer* optimizer, const char** in_file,
  423. const char** out_file,
  424. spvtools::ValidatorOptions* validator_options,
  425. spvtools::OptimizerOptions* optimizer_options) {
  426. std::vector<std::string> flags;
  427. flags.push_back(prog_name);
  428. std::vector<std::string> file_flags;
  429. if (!ReadFlagsFromFile(opt_flag, &file_flags)) {
  430. spvtools::Error(opt_diagnostic, nullptr, {},
  431. "Could not read optimizer flags from configuration file");
  432. return {OPT_STOP, 1};
  433. }
  434. flags.insert(flags.end(), file_flags.begin(), file_flags.end());
  435. const char** new_argv = new const char*[flags.size()];
  436. for (size_t i = 0; i < flags.size(); i++) {
  437. if (flags[i].find("-Oconfig=") != std::string::npos) {
  438. spvtools::Error(
  439. opt_diagnostic, nullptr, {},
  440. "Flag -Oconfig= may not be used inside the configuration file");
  441. return {OPT_STOP, 1};
  442. }
  443. new_argv[i] = flags[i].c_str();
  444. }
  445. auto ret_val =
  446. ParseFlags(static_cast<int>(flags.size()), new_argv, optimizer, in_file,
  447. out_file, validator_options, optimizer_options);
  448. delete[] new_argv;
  449. return ret_val;
  450. }
  451. // Canonicalize the flag in |argv[argi]| of the form '--pass arg' into
  452. // '--pass=arg'. The optimizer only accepts arguments to pass names that use the
  453. // form '--pass_name=arg'. Since spirv-opt also accepts the other form, this
  454. // function makes the necessary conversion.
  455. //
  456. // Pass flags that require additional arguments should be handled here. Note
  457. // that additional arguments should be given as a single string. If the flag
  458. // requires more than one argument, the pass creator in
  459. // Optimizer::GetPassFromFlag() should parse it accordingly (e.g., see the
  460. // handler for --set-spec-const-default-value).
  461. //
  462. // If the argument requests one of the passes that need an additional argument,
  463. // |argi| is modified to point past the current argument, and the string
  464. // "argv[argi]=argv[argi + 1]" is returned. Otherwise, |argi| is unmodified and
  465. // the string "|argv[argi]|" is returned.
  466. std::string CanonicalizeFlag(const char** argv, int argc, int* argi) {
  467. const char* cur_arg = argv[*argi];
  468. const char* next_arg = (*argi + 1 < argc) ? argv[*argi + 1] : nullptr;
  469. std::ostringstream canonical_arg;
  470. canonical_arg << cur_arg;
  471. // NOTE: DO NOT ADD NEW FLAGS HERE.
  472. //
  473. // These flags are supported for backwards compatibility. When adding new
  474. // passes that need extra arguments in its command-line flag, please make them
  475. // use the syntax "--pass_name[=pass_arg].
  476. if (0 == strcmp(cur_arg, "--set-spec-const-default-value") ||
  477. 0 == strcmp(cur_arg, "--loop-fission") ||
  478. 0 == strcmp(cur_arg, "--loop-fusion") ||
  479. 0 == strcmp(cur_arg, "--loop-unroll-partial") ||
  480. 0 == strcmp(cur_arg, "--loop-peeling-threshold")) {
  481. if (next_arg) {
  482. canonical_arg << "=" << next_arg;
  483. ++(*argi);
  484. }
  485. }
  486. return canonical_arg.str();
  487. }
  488. // Parses command-line flags. |argc| contains the number of command-line flags.
  489. // |argv| points to an array of strings holding the flags. |optimizer| is the
  490. // Optimizer instance used to optimize the program.
  491. //
  492. // On return, this function stores the name of the input program in |in_file|.
  493. // The name of the output file in |out_file|. The return value indicates whether
  494. // optimization should continue and a status code indicating an error or
  495. // success.
  496. OptStatus ParseFlags(int argc, const char** argv,
  497. spvtools::Optimizer* optimizer, const char** in_file,
  498. const char** out_file,
  499. spvtools::ValidatorOptions* validator_options,
  500. spvtools::OptimizerOptions* optimizer_options) {
  501. std::vector<std::string> pass_flags;
  502. bool target_env_set = false;
  503. bool webgpu_mode_set = false;
  504. for (int argi = 1; argi < argc; ++argi) {
  505. const char* cur_arg = argv[argi];
  506. if ('-' == cur_arg[0]) {
  507. if (0 == strcmp(cur_arg, "--version")) {
  508. spvtools::Logf(opt_diagnostic, SPV_MSG_INFO, nullptr, {}, "%s\n",
  509. spvSoftwareVersionDetailsString());
  510. return {OPT_STOP, 0};
  511. } else if (0 == strcmp(cur_arg, "--help") || 0 == strcmp(cur_arg, "-h")) {
  512. PrintUsage(argv[0]);
  513. return {OPT_STOP, 0};
  514. } else if (0 == strcmp(cur_arg, "-o")) {
  515. if (!*out_file && argi + 1 < argc) {
  516. *out_file = argv[++argi];
  517. } else {
  518. PrintUsage(argv[0]);
  519. return {OPT_STOP, 1};
  520. }
  521. } else if ('\0' == cur_arg[1]) {
  522. // Setting a filename of "-" to indicate stdin.
  523. if (!*in_file) {
  524. *in_file = cur_arg;
  525. } else {
  526. spvtools::Error(opt_diagnostic, nullptr, {},
  527. "More than one input file specified");
  528. return {OPT_STOP, 1};
  529. }
  530. } else if (0 == strncmp(cur_arg, "-Oconfig=", sizeof("-Oconfig=") - 1)) {
  531. OptStatus status =
  532. ParseOconfigFlag(argv[0], cur_arg, optimizer, in_file, out_file,
  533. validator_options, optimizer_options);
  534. if (status.action != OPT_CONTINUE) {
  535. return status;
  536. }
  537. } else if (0 == strcmp(cur_arg, "--skip-validation")) {
  538. optimizer_options->set_run_validator(false);
  539. } else if (0 == strcmp(cur_arg, "--print-all")) {
  540. optimizer->SetPrintAll(&std::cerr);
  541. } else if (0 == strcmp(cur_arg, "--time-report")) {
  542. optimizer->SetTimeReport(&std::cerr);
  543. } else if (0 == strcmp(cur_arg, "--relax-struct-store")) {
  544. validator_options->SetRelaxStructStore(true);
  545. } else if (0 == strncmp(cur_arg, "--max-id-bound=",
  546. sizeof("--max-id-bound=") - 1)) {
  547. auto split_flag = spvtools::utils::SplitFlagArgs(cur_arg);
  548. // Will not allow values in the range [2^31,2^32).
  549. uint32_t max_id_bound =
  550. static_cast<uint32_t>(atoi(split_flag.second.c_str()));
  551. // That SPIR-V mandates the minimum value for max id bound but
  552. // implementations may allow higher minimum bounds.
  553. if (max_id_bound < kDefaultMaxIdBound) {
  554. spvtools::Error(opt_diagnostic, nullptr, {},
  555. "The max id bound must be at least 0x3FFFFF");
  556. return {OPT_STOP, 1};
  557. }
  558. optimizer_options->set_max_id_bound(max_id_bound);
  559. validator_options->SetUniversalLimit(spv_validator_limit_max_id_bound,
  560. max_id_bound);
  561. } else if (0 == strncmp(cur_arg,
  562. "--target-env=", sizeof("--target-env=") - 1)) {
  563. if (webgpu_mode_set) {
  564. spvtools::Error(opt_diagnostic, nullptr, {},
  565. "Cannot use both --webgpu-mode and --target-env at "
  566. "the same time");
  567. return {OPT_STOP, 1};
  568. }
  569. const auto split_flag = spvtools::utils::SplitFlagArgs(cur_arg);
  570. const auto target_env_str = split_flag.second.c_str();
  571. spv_target_env target_env;
  572. if (!spvParseTargetEnv(target_env_str, &target_env)) {
  573. spvtools::Error(opt_diagnostic, nullptr, {},
  574. "Invalid value passed to --target-env");
  575. return {OPT_STOP, 1};
  576. }
  577. optimizer->SetTargetEnv(target_env);
  578. } else if (0 == strcmp(cur_arg, "--webgpu-mode")) {
  579. if (target_env_set) {
  580. spvtools::Error(opt_diagnostic, nullptr, {},
  581. "Cannot use both --webgpu-mode and --target-env at "
  582. "the same time");
  583. return {OPT_STOP, 1};
  584. }
  585. optimizer->SetTargetEnv(SPV_ENV_WEBGPU_0);
  586. optimizer->RegisterWebGPUPasses();
  587. } else if (0 == strcmp(cur_arg, "--validate-after-all")) {
  588. optimizer->SetValidateAfterAll(true);
  589. } else {
  590. // Some passes used to accept the form '--pass arg', canonicalize them
  591. // to '--pass=arg'.
  592. pass_flags.push_back(CanonicalizeFlag(argv, argc, &argi));
  593. // If we were requested to legalize SPIR-V generated from the HLSL
  594. // front-end, skip validation.
  595. if (0 == strcmp(cur_arg, "--legalize-hlsl")) {
  596. validator_options->SetRelaxLogicalPointer(true);
  597. }
  598. }
  599. } else {
  600. if (!*in_file) {
  601. *in_file = cur_arg;
  602. } else {
  603. spvtools::Error(opt_diagnostic, nullptr, {},
  604. "More than one input file specified");
  605. return {OPT_STOP, 1};
  606. }
  607. }
  608. }
  609. if (!optimizer->RegisterPassesFromFlags(pass_flags)) {
  610. return {OPT_STOP, 1};
  611. }
  612. return {OPT_CONTINUE, 0};
  613. }
  614. } // namespace
  615. int main(int argc, const char** argv) {
  616. const char* in_file = nullptr;
  617. const char* out_file = nullptr;
  618. spv_target_env target_env = kDefaultEnvironment;
  619. spvtools::Optimizer optimizer(target_env);
  620. optimizer.SetMessageConsumer(spvtools::utils::CLIMessageConsumer);
  621. spvtools::ValidatorOptions validator_options;
  622. spvtools::OptimizerOptions optimizer_options;
  623. OptStatus status = ParseFlags(argc, argv, &optimizer, &in_file, &out_file,
  624. &validator_options, &optimizer_options);
  625. optimizer_options.set_validator_options(validator_options);
  626. if (status.action == OPT_STOP) {
  627. return status.code;
  628. }
  629. if (out_file == nullptr) {
  630. spvtools::Error(opt_diagnostic, nullptr, {}, "-o required");
  631. return 1;
  632. }
  633. std::vector<uint32_t> binary;
  634. if (!ReadFile<uint32_t>(in_file, "rb", &binary)) {
  635. return 1;
  636. }
  637. // By using the same vector as input and output, we save time in the case
  638. // that there was no change.
  639. bool ok =
  640. optimizer.Run(binary.data(), binary.size(), &binary, optimizer_options);
  641. if (!WriteFile<uint32_t>(out_file, "wb", binary.data(), binary.size())) {
  642. return 1;
  643. }
  644. return ok ? 0 : 1;
  645. }