markv.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. // Copyright (c) 2017 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 <cstdio>
  17. #include <cstring>
  18. #include <functional>
  19. #include <iostream>
  20. #include <memory>
  21. #include <string>
  22. #include <utility>
  23. #include <vector>
  24. #include "source/comp/markv.h"
  25. #include "source/spirv_target_env.h"
  26. #include "source/table.h"
  27. #include "spirv-tools/optimizer.hpp"
  28. #include "tools/comp/markv_model_factory.h"
  29. #include "tools/io.h"
  30. namespace {
  31. const auto kSpvEnv = SPV_ENV_UNIVERSAL_1_2;
  32. enum Task {
  33. kNoTask = 0,
  34. kEncode,
  35. kDecode,
  36. kTest,
  37. };
  38. struct ScopedContext {
  39. ScopedContext(spv_target_env env) : context(spvContextCreate(env)) {}
  40. ~ScopedContext() { spvContextDestroy(context); }
  41. spv_context context;
  42. };
  43. void print_usage(char* argv0) {
  44. printf(
  45. R"(%s - Encodes or decodes a SPIR-V binary to or from a MARK-V binary.
  46. USAGE: %s [e|d|t] [options] [<filename>]
  47. The input binary is read from <filename>. If no file is specified,
  48. or if the filename is "-", then the binary is read from standard input.
  49. If no output is specified then the output is printed to stdout in a human
  50. readable format.
  51. WIP: MARK-V codec is in early stages of development. At the moment it only
  52. can encode and decode some SPIR-V files and only if exacly the same build of
  53. software is used (is doesn't write or handle version numbers yet).
  54. Tasks:
  55. e Encode SPIR-V to MARK-V.
  56. d Decode MARK-V to SPIR-V.
  57. t Test the codec by first encoding the given SPIR-V file to
  58. MARK-V, then decoding it back to SPIR-V and comparing results.
  59. Options:
  60. -h, --help Print this help.
  61. --comments Write codec comments to stderr.
  62. --version Display MARK-V codec version.
  63. --validate Validate SPIR-V while encoding or decoding.
  64. --model=<model-name>
  65. Compression model, possible values:
  66. shader_lite - fast, poor compression ratio
  67. shader_mid - balanced
  68. shader_max - best compression ratio
  69. Default: shader_lite
  70. -o <filename> Set the output filename.
  71. Output goes to standard output if this option is
  72. not specified, or if the filename is "-".
  73. Not needed for 't' task (testing).
  74. )",
  75. argv0, argv0);
  76. }
  77. void DiagnosticsMessageHandler(spv_message_level_t level, const char*,
  78. const spv_position_t& position,
  79. const char* message) {
  80. switch (level) {
  81. case SPV_MSG_FATAL:
  82. case SPV_MSG_INTERNAL_ERROR:
  83. case SPV_MSG_ERROR:
  84. std::cerr << "error: " << position.index << ": " << message << std::endl;
  85. break;
  86. case SPV_MSG_WARNING:
  87. std::cerr << "warning: " << position.index << ": " << message
  88. << std::endl;
  89. break;
  90. case SPV_MSG_INFO:
  91. std::cerr << "info: " << position.index << ": " << message << std::endl;
  92. break;
  93. default:
  94. break;
  95. }
  96. }
  97. } // namespace
  98. int main(int argc, char** argv) {
  99. const char* input_filename = nullptr;
  100. const char* output_filename = nullptr;
  101. Task task = kNoTask;
  102. if (argc < 3) {
  103. print_usage(argv[0]);
  104. return 0;
  105. }
  106. const char* task_char = argv[1];
  107. if (0 == strcmp("e", task_char)) {
  108. task = kEncode;
  109. } else if (0 == strcmp("d", task_char)) {
  110. task = kDecode;
  111. } else if (0 == strcmp("t", task_char)) {
  112. task = kTest;
  113. }
  114. if (task == kNoTask) {
  115. print_usage(argv[0]);
  116. return 1;
  117. }
  118. bool want_comments = false;
  119. bool validate_spirv_binary = false;
  120. spvtools::comp::MarkvModelType model_type =
  121. spvtools::comp::kMarkvModelUnknown;
  122. for (int argi = 2; argi < argc; ++argi) {
  123. if ('-' == argv[argi][0]) {
  124. switch (argv[argi][1]) {
  125. case 'h':
  126. print_usage(argv[0]);
  127. return 0;
  128. case 'o': {
  129. if (!output_filename && argi + 1 < argc &&
  130. (task == kEncode || task == kDecode)) {
  131. output_filename = argv[++argi];
  132. } else {
  133. print_usage(argv[0]);
  134. return 1;
  135. }
  136. } break;
  137. case '-': {
  138. if (0 == strcmp(argv[argi], "--help")) {
  139. print_usage(argv[0]);
  140. return 0;
  141. } else if (0 == strcmp(argv[argi], "--comments")) {
  142. want_comments = true;
  143. } else if (0 == strcmp(argv[argi], "--version")) {
  144. fprintf(stderr, "error: Not implemented\n");
  145. return 1;
  146. } else if (0 == strcmp(argv[argi], "--validate")) {
  147. validate_spirv_binary = true;
  148. } else if (0 == strcmp(argv[argi], "--model=shader_lite")) {
  149. if (model_type != spvtools::comp::kMarkvModelUnknown)
  150. fprintf(stderr, "error: More than one model specified\n");
  151. model_type = spvtools::comp::kMarkvModelShaderLite;
  152. } else if (0 == strcmp(argv[argi], "--model=shader_mid")) {
  153. if (model_type != spvtools::comp::kMarkvModelUnknown)
  154. fprintf(stderr, "error: More than one model specified\n");
  155. model_type = spvtools::comp::kMarkvModelShaderMid;
  156. } else if (0 == strcmp(argv[argi], "--model=shader_max")) {
  157. if (model_type != spvtools::comp::kMarkvModelUnknown)
  158. fprintf(stderr, "error: More than one model specified\n");
  159. model_type = spvtools::comp::kMarkvModelShaderMax;
  160. } else {
  161. print_usage(argv[0]);
  162. return 1;
  163. }
  164. } break;
  165. case '\0': {
  166. // Setting a filename of "-" to indicate stdin.
  167. if (!input_filename) {
  168. input_filename = argv[argi];
  169. } else {
  170. fprintf(stderr, "error: More than one input file specified\n");
  171. return 1;
  172. }
  173. } break;
  174. default:
  175. print_usage(argv[0]);
  176. return 1;
  177. }
  178. } else {
  179. if (!input_filename) {
  180. input_filename = argv[argi];
  181. } else {
  182. fprintf(stderr, "error: More than one input file specified\n");
  183. return 1;
  184. }
  185. }
  186. }
  187. if (model_type == spvtools::comp::kMarkvModelUnknown)
  188. model_type = spvtools::comp::kMarkvModelShaderLite;
  189. const auto no_comments = spvtools::comp::MarkvLogConsumer();
  190. const auto output_to_stderr = [](const std::string& str) {
  191. std::cerr << str;
  192. };
  193. ScopedContext ctx(kSpvEnv);
  194. std::unique_ptr<spvtools::comp::MarkvModel> model =
  195. spvtools::comp::CreateMarkvModel(model_type);
  196. std::vector<uint32_t> spirv;
  197. std::vector<uint8_t> markv;
  198. spvtools::comp::MarkvCodecOptions options;
  199. options.validate_spirv_binary = validate_spirv_binary;
  200. if (task == kEncode) {
  201. if (!ReadFile<uint32_t>(input_filename, "rb", &spirv)) return 1;
  202. assert(!spirv.empty());
  203. if (SPV_SUCCESS != spvtools::comp::SpirvToMarkv(
  204. ctx.context, spirv, options, *model,
  205. DiagnosticsMessageHandler,
  206. want_comments ? output_to_stderr : no_comments,
  207. spvtools::comp::MarkvDebugConsumer(), &markv)) {
  208. std::cerr << "error: Failed to encode " << input_filename << " to MARK-V "
  209. << std::endl;
  210. return 1;
  211. }
  212. if (!WriteFile<uint8_t>(output_filename, "wb", markv.data(), markv.size()))
  213. return 1;
  214. } else if (task == kDecode) {
  215. if (!ReadFile<uint8_t>(input_filename, "rb", &markv)) return 1;
  216. assert(!markv.empty());
  217. if (SPV_SUCCESS != spvtools::comp::MarkvToSpirv(
  218. ctx.context, markv, options, *model,
  219. DiagnosticsMessageHandler,
  220. want_comments ? output_to_stderr : no_comments,
  221. spvtools::comp::MarkvDebugConsumer(), &spirv)) {
  222. std::cerr << "error: Failed to decode " << input_filename << " to SPIR-V "
  223. << std::endl;
  224. return 1;
  225. }
  226. if (!WriteFile<uint32_t>(output_filename, "wb", spirv.data(), spirv.size()))
  227. return 1;
  228. } else if (task == kTest) {
  229. if (!ReadFile<uint32_t>(input_filename, "rb", &spirv)) return 1;
  230. assert(!spirv.empty());
  231. std::vector<uint32_t> spirv_before;
  232. spvtools::Optimizer optimizer(kSpvEnv);
  233. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  234. if (!optimizer.Run(spirv.data(), spirv.size(), &spirv_before)) {
  235. std::cerr << "error: Optimizer failure on: " << input_filename
  236. << std::endl;
  237. }
  238. std::vector<std::string> encoder_instruction_bits;
  239. std::vector<std::string> encoder_instruction_comments;
  240. std::vector<std::vector<uint32_t>> encoder_instruction_words;
  241. std::vector<std::string> decoder_instruction_bits;
  242. std::vector<std::string> decoder_instruction_comments;
  243. std::vector<std::vector<uint32_t>> decoder_instruction_words;
  244. const auto encoder_debug_consumer = [&](const std::vector<uint32_t>& words,
  245. const std::string& bits,
  246. const std::string& comment) {
  247. encoder_instruction_words.push_back(words);
  248. encoder_instruction_bits.push_back(bits);
  249. encoder_instruction_comments.push_back(comment);
  250. return true;
  251. };
  252. if (SPV_SUCCESS != spvtools::comp::SpirvToMarkv(
  253. ctx.context, spirv_before, options, *model,
  254. DiagnosticsMessageHandler,
  255. want_comments ? output_to_stderr : no_comments,
  256. encoder_debug_consumer, &markv)) {
  257. std::cerr << "error: Failed to encode " << input_filename << " to MARK-V "
  258. << std::endl;
  259. return 1;
  260. }
  261. const auto write_bug_report = [&]() {
  262. for (size_t inst_index = 0; inst_index < decoder_instruction_words.size();
  263. ++inst_index) {
  264. std::cerr << "\nInstruction #" << inst_index << std::endl;
  265. std::cerr << "\nEncoder words: ";
  266. for (uint32_t word : encoder_instruction_words[inst_index])
  267. std::cerr << word << " ";
  268. std::cerr << "\nDecoder words: ";
  269. for (uint32_t word : decoder_instruction_words[inst_index])
  270. std::cerr << word << " ";
  271. std::cerr << std::endl;
  272. std::cerr << "\nEncoder bits: " << encoder_instruction_bits[inst_index];
  273. std::cerr << "\nDecoder bits: " << decoder_instruction_bits[inst_index];
  274. std::cerr << std::endl;
  275. std::cerr << "\nEncoder comments:\n"
  276. << encoder_instruction_comments[inst_index];
  277. std::cerr << "Decoder comments:\n"
  278. << decoder_instruction_comments[inst_index];
  279. std::cerr << std::endl;
  280. }
  281. };
  282. const auto decoder_debug_consumer = [&](const std::vector<uint32_t>& words,
  283. const std::string& bits,
  284. const std::string& comment) {
  285. const size_t inst_index = decoder_instruction_words.size();
  286. if (inst_index >= encoder_instruction_words.size()) {
  287. write_bug_report();
  288. std::cerr << "error: Decoder has more instructions than encoder: "
  289. << input_filename << std::endl;
  290. return false;
  291. }
  292. decoder_instruction_words.push_back(words);
  293. decoder_instruction_bits.push_back(bits);
  294. decoder_instruction_comments.push_back(comment);
  295. if (encoder_instruction_words[inst_index] !=
  296. decoder_instruction_words[inst_index]) {
  297. write_bug_report();
  298. std::cerr << "error: Words of the last decoded instruction differ from "
  299. "reference: "
  300. << input_filename << std::endl;
  301. return false;
  302. }
  303. if (encoder_instruction_bits[inst_index] !=
  304. decoder_instruction_bits[inst_index]) {
  305. write_bug_report();
  306. std::cerr << "error: Bits of the last decoded instruction differ from "
  307. "reference: "
  308. << input_filename << std::endl;
  309. return false;
  310. }
  311. return true;
  312. };
  313. std::vector<uint32_t> spirv_after;
  314. const spv_result_t decoding_result = spvtools::comp::MarkvToSpirv(
  315. ctx.context, markv, options, *model, DiagnosticsMessageHandler,
  316. want_comments ? output_to_stderr : no_comments, decoder_debug_consumer,
  317. &spirv_after);
  318. if (decoding_result == SPV_REQUESTED_TERMINATION) {
  319. std::cerr << "error: Decoding interrupted by the debugger: "
  320. << input_filename << std::endl;
  321. return 1;
  322. }
  323. if (decoding_result != SPV_SUCCESS) {
  324. std::cerr << "error: Failed to decode encoded " << input_filename
  325. << " back to SPIR-V " << std::endl;
  326. return 1;
  327. }
  328. assert(spirv_before.size() == spirv_after.size());
  329. assert(std::mismatch(std::next(spirv_before.begin(), 5), spirv_before.end(),
  330. std::next(spirv_after.begin(), 5)) ==
  331. std::make_pair(spirv_before.end(), spirv_after.end()));
  332. }
  333. return 0;
  334. }