main.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. // This program demonstrates basic SPIR-V module processing using
  15. // SPIRV-Tools C++ API:
  16. // * Assembling
  17. // * Validating
  18. // * Optimizing
  19. // * Disassembling
  20. #include <iostream>
  21. #include <string>
  22. #include <vector>
  23. #include "spirv-tools/libspirv.hpp"
  24. #include "spirv-tools/optimizer.hpp"
  25. int main() {
  26. const std::string source =
  27. " OpCapability Linkage "
  28. " OpCapability Shader "
  29. " OpMemoryModel Logical GLSL450 "
  30. " OpSource GLSL 450 "
  31. " OpDecorate %spec SpecId 1 "
  32. " %int = OpTypeInt 32 1 "
  33. " %spec = OpSpecConstant %int 0 "
  34. "%const = OpConstant %int 42";
  35. spvtools::SpirvTools core(SPV_ENV_UNIVERSAL_1_3);
  36. spvtools::Optimizer opt(SPV_ENV_UNIVERSAL_1_3);
  37. auto print_msg_to_stderr = [](spv_message_level_t, const char*,
  38. const spv_position_t&, const char* m) {
  39. std::cerr << "error: " << m << std::endl;
  40. };
  41. core.SetMessageConsumer(print_msg_to_stderr);
  42. opt.SetMessageConsumer(print_msg_to_stderr);
  43. std::vector<uint32_t> spirv;
  44. if (!core.Assemble(source, &spirv)) return 1;
  45. if (!core.Validate(spirv)) return 1;
  46. opt.RegisterPass(spvtools::CreateSetSpecConstantDefaultValuePass({{1, "42"}}))
  47. .RegisterPass(spvtools::CreateFreezeSpecConstantValuePass())
  48. .RegisterPass(spvtools::CreateUnifyConstantPass())
  49. .RegisterPass(spvtools::CreateStripDebugInfoPass());
  50. if (!opt.Run(spirv.data(), spirv.size(), &spirv)) return 1;
  51. std::string disassembly;
  52. if (!core.Disassemble(spirv, &disassembly)) return 1;
  53. std::cout << disassembly << "\n";
  54. return 0;
  55. }