instruction_message.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright (c) 2019 Google LLC
  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 "source/fuzz/instruction_message.h"
  15. #include "source/fuzz/fuzzer_util.h"
  16. namespace spvtools {
  17. namespace fuzz {
  18. protobufs::Instruction MakeInstructionMessage(
  19. SpvOp opcode, uint32_t result_type_id, uint32_t result_id,
  20. const opt::Instruction::OperandList& input_operands) {
  21. protobufs::Instruction result;
  22. result.set_opcode(opcode);
  23. result.set_result_type_id(result_type_id);
  24. result.set_result_id(result_id);
  25. for (auto& operand : input_operands) {
  26. auto operand_message = result.add_input_operand();
  27. operand_message->set_operand_type(static_cast<uint32_t>(operand.type));
  28. for (auto operand_word : operand.words) {
  29. operand_message->add_operand_data(operand_word);
  30. }
  31. }
  32. return result;
  33. }
  34. std::unique_ptr<opt::Instruction> InstructionFromMessage(
  35. opt::IRContext* ir_context,
  36. const protobufs::Instruction& instruction_message) {
  37. // First, update the module's id bound with respect to the new instruction,
  38. // if it has a result id.
  39. if (instruction_message.result_id()) {
  40. fuzzerutil::UpdateModuleIdBound(ir_context,
  41. instruction_message.result_id());
  42. }
  43. // Now create a sequence of input operands from the input operand data in the
  44. // protobuf message.
  45. opt::Instruction::OperandList in_operands;
  46. for (auto& operand_message : instruction_message.input_operand()) {
  47. opt::Operand::OperandData operand_data;
  48. for (auto& word : operand_message.operand_data()) {
  49. operand_data.push_back(word);
  50. }
  51. in_operands.push_back(
  52. {static_cast<spv_operand_type_t>(operand_message.operand_type()),
  53. operand_data});
  54. }
  55. // Create and return the instruction.
  56. return MakeUnique<opt::Instruction>(
  57. ir_context, static_cast<SpvOp>(instruction_message.opcode()),
  58. instruction_message.result_type_id(), instruction_message.result_id(),
  59. in_operands);
  60. }
  61. } // namespace fuzz
  62. } // namespace spvtools