id_descriptor.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. #ifndef SOURCE_ID_DESCRIPTOR_H_
  15. #define SOURCE_ID_DESCRIPTOR_H_
  16. #include <unordered_map>
  17. #include <vector>
  18. #include "spirv-tools/libspirv.hpp"
  19. namespace spvtools {
  20. using CustomHashFunc = std::function<uint32_t(const std::vector<uint32_t>&)>;
  21. // Computes and stores id descriptors.
  22. //
  23. // Descriptors are computed as hash of all words in the instruction where ids
  24. // were substituted with previously computed descriptors.
  25. class IdDescriptorCollection {
  26. public:
  27. explicit IdDescriptorCollection(
  28. CustomHashFunc custom_hash_func = CustomHashFunc())
  29. : custom_hash_func_(custom_hash_func) {
  30. words_.reserve(16);
  31. }
  32. // Computes descriptor for the result id of the given instruction and
  33. // registers it in id_to_descriptor_. Returns the computed descriptor.
  34. // This function needs to be sequentially called for every instruction in the
  35. // module.
  36. uint32_t ProcessInstruction(const spv_parsed_instruction_t& inst);
  37. // Returns a previously computed descriptor id.
  38. uint32_t GetDescriptor(uint32_t id) const {
  39. const auto it = id_to_descriptor_.find(id);
  40. if (it == id_to_descriptor_.end()) return 0;
  41. return it->second;
  42. }
  43. private:
  44. std::unordered_map<uint32_t, uint32_t> id_to_descriptor_;
  45. std::function<uint32_t(const std::vector<uint32_t>&)> custom_hash_func_;
  46. // Scratch buffer used for hashing. Class member to optimize on allocation.
  47. std::vector<uint32_t> words_;
  48. };
  49. } // namespace spvtools
  50. #endif // SOURCE_ID_DESCRIPTOR_H_