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