spirv_stats.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 "spirv_stats.h"
  15. #include <cassert>
  16. #include <algorithm>
  17. #include <memory>
  18. #include <string>
  19. #include <vector>
  20. #include "binary.h"
  21. #include "diagnostic.h"
  22. #include "enum_string_mapping.h"
  23. #include "extensions.h"
  24. #include "id_descriptor.h"
  25. #include "instruction.h"
  26. #include "opcode.h"
  27. #include "operand.h"
  28. #include "spirv-tools/libspirv.h"
  29. #include "spirv_endian.h"
  30. #include "spirv_validator_options.h"
  31. #include "val/instruction.h"
  32. #include "val/validation_state.h"
  33. #include "validate.h"
  34. using libspirv::IdDescriptorCollection;
  35. using libspirv::Instruction;
  36. using libspirv::SpirvStats;
  37. using libspirv::ValidationState_t;
  38. namespace {
  39. // Helper class for stats aggregation. Receives as in/out parameter.
  40. // Constructs ValidationState and updates it by running validator for each
  41. // instruction.
  42. class StatsAggregator {
  43. public:
  44. StatsAggregator(SpirvStats* in_out_stats, const spv_const_context context) {
  45. stats_ = in_out_stats;
  46. vstate_.reset(new ValidationState_t(context, &validator_options_));
  47. }
  48. // Collects header statistics and sets correct id_bound.
  49. spv_result_t ProcessHeader(spv_endianness_t /* endian */,
  50. uint32_t /* magic */, uint32_t version,
  51. uint32_t generator, uint32_t id_bound,
  52. uint32_t /* schema */) {
  53. vstate_->setIdBound(id_bound);
  54. ++stats_->version_hist[version];
  55. ++stats_->generator_hist[generator];
  56. return SPV_SUCCESS;
  57. }
  58. // Runs validator to validate the instruction and update vstate_,
  59. // then procession the instruction to collect stats.
  60. spv_result_t ProcessInstruction(const spv_parsed_instruction_t* inst) {
  61. const spv_result_t validation_result =
  62. spvtools::ValidateInstructionAndUpdateValidationState(vstate_.get(),
  63. inst);
  64. if (validation_result != SPV_SUCCESS) return validation_result;
  65. ProcessOpcode();
  66. ProcessCapability();
  67. ProcessExtension();
  68. ProcessConstant();
  69. ProcessEnums();
  70. ProcessLiteralStrings();
  71. ProcessNonIdWords();
  72. ProcessIdDescriptors();
  73. return SPV_SUCCESS;
  74. }
  75. // Collects statistics of descriptors generated by IdDescriptorCollection.
  76. void ProcessIdDescriptors() {
  77. const Instruction& inst = GetCurrentInstruction();
  78. const uint32_t new_descriptor =
  79. id_descriptors_.ProcessInstruction(inst.c_inst());
  80. if (new_descriptor) {
  81. std::stringstream ss;
  82. ss << spvOpcodeString(inst.opcode());
  83. for (size_t i = 1; i < inst.words().size(); ++i) {
  84. ss << " " << inst.word(i);
  85. }
  86. stats_->id_descriptor_labels.emplace(new_descriptor, ss.str());
  87. }
  88. uint32_t index = 0;
  89. for (const auto& operand : inst.operands()) {
  90. if (spvIsIdType(operand.type)) {
  91. const uint32_t descriptor =
  92. id_descriptors_.GetDescriptor(inst.word(operand.offset));
  93. if (descriptor) {
  94. ++stats_->id_descriptor_hist[descriptor];
  95. ++stats_
  96. ->operand_slot_id_descriptor_hist[std::pair<uint32_t, uint32_t>(
  97. inst.opcode(), index)][descriptor];
  98. }
  99. }
  100. ++index;
  101. }
  102. }
  103. // Collects statistics of enum words for operands of specific types.
  104. void ProcessEnums() {
  105. const Instruction& inst = GetCurrentInstruction();
  106. for (const auto& operand : inst.operands()) {
  107. switch (operand.type) {
  108. case SPV_OPERAND_TYPE_SOURCE_LANGUAGE:
  109. case SPV_OPERAND_TYPE_EXECUTION_MODEL:
  110. case SPV_OPERAND_TYPE_ADDRESSING_MODEL:
  111. case SPV_OPERAND_TYPE_MEMORY_MODEL:
  112. case SPV_OPERAND_TYPE_EXECUTION_MODE:
  113. case SPV_OPERAND_TYPE_STORAGE_CLASS:
  114. case SPV_OPERAND_TYPE_DIMENSIONALITY:
  115. case SPV_OPERAND_TYPE_SAMPLER_ADDRESSING_MODE:
  116. case SPV_OPERAND_TYPE_SAMPLER_FILTER_MODE:
  117. case SPV_OPERAND_TYPE_SAMPLER_IMAGE_FORMAT:
  118. case SPV_OPERAND_TYPE_IMAGE_CHANNEL_ORDER:
  119. case SPV_OPERAND_TYPE_IMAGE_CHANNEL_DATA_TYPE:
  120. case SPV_OPERAND_TYPE_FP_ROUNDING_MODE:
  121. case SPV_OPERAND_TYPE_LINKAGE_TYPE:
  122. case SPV_OPERAND_TYPE_ACCESS_QUALIFIER:
  123. case SPV_OPERAND_TYPE_FUNCTION_PARAMETER_ATTRIBUTE:
  124. case SPV_OPERAND_TYPE_DECORATION:
  125. case SPV_OPERAND_TYPE_BUILT_IN:
  126. case SPV_OPERAND_TYPE_GROUP_OPERATION:
  127. case SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS:
  128. case SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO:
  129. case SPV_OPERAND_TYPE_CAPABILITY: {
  130. ++stats_->enum_hist[operand.type][inst.word(operand.offset)];
  131. break;
  132. }
  133. default:
  134. break;
  135. }
  136. }
  137. }
  138. // Collects statistics of literal strings used by opcodes.
  139. void ProcessLiteralStrings() {
  140. const Instruction& inst = GetCurrentInstruction();
  141. for (const auto& operand : inst.operands()) {
  142. if (operand.type == SPV_OPERAND_TYPE_LITERAL_STRING) {
  143. const std::string str =
  144. reinterpret_cast<const char*>(&inst.words()[operand.offset]);
  145. ++stats_->literal_strings_hist[inst.opcode()][str];
  146. }
  147. }
  148. }
  149. // Collects statistics of all single word non-id operand slots.
  150. void ProcessNonIdWords() {
  151. const Instruction& inst = GetCurrentInstruction();
  152. uint32_t index = 0;
  153. for (const auto& operand : inst.operands()) {
  154. if (operand.num_words == 1 && !spvIsIdType(operand.type)) {
  155. ++stats_->operand_slot_non_id_words_hist[std::pair<uint32_t, uint32_t>(
  156. inst.opcode(), index)][inst.word(operand.offset)];
  157. }
  158. ++index;
  159. }
  160. }
  161. // Collects OpCapability statistics.
  162. void ProcessCapability() {
  163. const Instruction& inst = GetCurrentInstruction();
  164. if (inst.opcode() != SpvOpCapability) return;
  165. const uint32_t capability = inst.word(inst.operands()[0].offset);
  166. ++stats_->capability_hist[capability];
  167. }
  168. // Collects OpExtension statistics.
  169. void ProcessExtension() {
  170. const Instruction& inst = GetCurrentInstruction();
  171. if (inst.opcode() != SpvOpExtension) return;
  172. const std::string extension = libspirv::GetExtensionString(&inst.c_inst());
  173. ++stats_->extension_hist[extension];
  174. }
  175. // Collects OpCode statistics.
  176. void ProcessOpcode() {
  177. auto inst_it = vstate_->ordered_instructions().rbegin();
  178. const SpvOp opcode = inst_it->opcode();
  179. ++stats_->opcode_hist[opcode];
  180. const uint32_t opcode_and_num_operands =
  181. (uint32_t(inst_it->operands().size()) << 16) | uint32_t(opcode);
  182. ++stats_->opcode_and_num_operands_hist[opcode_and_num_operands];
  183. ++inst_it;
  184. if (inst_it != vstate_->ordered_instructions().rend()) {
  185. const SpvOp prev_opcode = inst_it->opcode();
  186. ++stats_->opcode_and_num_operands_markov_hist[prev_opcode]
  187. [opcode_and_num_operands];
  188. }
  189. auto step_it = stats_->opcode_markov_hist.begin();
  190. for (; inst_it != vstate_->ordered_instructions().rend() &&
  191. step_it != stats_->opcode_markov_hist.end();
  192. ++inst_it, ++step_it) {
  193. auto& hist = (*step_it)[inst_it->opcode()];
  194. ++hist[opcode];
  195. }
  196. }
  197. // Collects OpConstant statistics.
  198. void ProcessConstant() {
  199. const Instruction& inst = GetCurrentInstruction();
  200. if (inst.opcode() != SpvOpConstant) return;
  201. const uint32_t type_id = inst.GetOperandAs<uint32_t>(0);
  202. const auto type_decl_it = vstate_->all_definitions().find(type_id);
  203. assert(type_decl_it != vstate_->all_definitions().end());
  204. const Instruction& type_decl_inst = *type_decl_it->second;
  205. const SpvOp type_op = type_decl_inst.opcode();
  206. if (type_op == SpvOpTypeInt) {
  207. const uint32_t bit_width = type_decl_inst.GetOperandAs<uint32_t>(1);
  208. const uint32_t is_signed = type_decl_inst.GetOperandAs<uint32_t>(2);
  209. assert(is_signed == 0 || is_signed == 1);
  210. if (bit_width == 16) {
  211. if (is_signed)
  212. ++stats_->s16_constant_hist[inst.GetOperandAs<int16_t>(2)];
  213. else
  214. ++stats_->u16_constant_hist[inst.GetOperandAs<uint16_t>(2)];
  215. } else if (bit_width == 32) {
  216. if (is_signed)
  217. ++stats_->s32_constant_hist[inst.GetOperandAs<int32_t>(2)];
  218. else
  219. ++stats_->u32_constant_hist[inst.GetOperandAs<uint32_t>(2)];
  220. } else if (bit_width == 64) {
  221. if (is_signed)
  222. ++stats_->s64_constant_hist[inst.GetOperandAs<int64_t>(2)];
  223. else
  224. ++stats_->u64_constant_hist[inst.GetOperandAs<uint64_t>(2)];
  225. } else {
  226. assert(false && "TypeInt bit width is not 16, 32 or 64");
  227. }
  228. } else if (type_op == SpvOpTypeFloat) {
  229. const uint32_t bit_width = type_decl_inst.GetOperandAs<uint32_t>(1);
  230. if (bit_width == 32) {
  231. ++stats_->f32_constant_hist[inst.GetOperandAs<float>(2)];
  232. } else if (bit_width == 64) {
  233. ++stats_->f64_constant_hist[inst.GetOperandAs<double>(2)];
  234. } else {
  235. assert(bit_width == 16);
  236. }
  237. }
  238. }
  239. SpirvStats* stats() { return stats_; }
  240. private:
  241. // Returns the current instruction (the one last processed by the validator).
  242. const Instruction& GetCurrentInstruction() const {
  243. return vstate_->ordered_instructions().back();
  244. }
  245. SpirvStats* stats_;
  246. spv_validator_options_t validator_options_;
  247. std::unique_ptr<ValidationState_t> vstate_;
  248. IdDescriptorCollection id_descriptors_;
  249. };
  250. spv_result_t ProcessHeader(void* user_data, spv_endianness_t endian,
  251. uint32_t magic, uint32_t version, uint32_t generator,
  252. uint32_t id_bound, uint32_t schema) {
  253. StatsAggregator* stats_aggregator =
  254. reinterpret_cast<StatsAggregator*>(user_data);
  255. return stats_aggregator->ProcessHeader(endian, magic, version, generator,
  256. id_bound, schema);
  257. }
  258. spv_result_t ProcessInstruction(void* user_data,
  259. const spv_parsed_instruction_t* inst) {
  260. StatsAggregator* stats_aggregator =
  261. reinterpret_cast<StatsAggregator*>(user_data);
  262. return stats_aggregator->ProcessInstruction(inst);
  263. }
  264. } // namespace
  265. namespace libspirv {
  266. spv_result_t AggregateStats(const spv_context_t& context, const uint32_t* words,
  267. const size_t num_words, spv_diagnostic* pDiagnostic,
  268. SpirvStats* stats) {
  269. spv_const_binary_t binary = {words, num_words};
  270. spv_endianness_t endian;
  271. spv_position_t position = {};
  272. if (spvBinaryEndianness(&binary, &endian)) {
  273. return libspirv::DiagnosticStream(position, context.consumer,
  274. SPV_ERROR_INVALID_BINARY)
  275. << "Invalid SPIR-V magic number.";
  276. }
  277. spv_header_t header;
  278. if (spvBinaryHeaderGet(&binary, endian, &header)) {
  279. return libspirv::DiagnosticStream(position, context.consumer,
  280. SPV_ERROR_INVALID_BINARY)
  281. << "Invalid SPIR-V header.";
  282. }
  283. StatsAggregator stats_aggregator(stats, &context);
  284. return spvBinaryParse(&context, &stats_aggregator, words, num_words,
  285. ProcessHeader, ProcessInstruction, pDiagnostic);
  286. }
  287. } // namespace libspirv