transformation_swap_two_functions.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright (c) 2021 Shiyu Liu
  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/transformation_swap_two_functions.h"
  15. #include "source/opt/function.h"
  16. #include "source/opt/module.h"
  17. #include "source/fuzz/fuzzer_util.h"
  18. namespace spvtools {
  19. namespace fuzz {
  20. TransformationSwapTwoFunctions::TransformationSwapTwoFunctions(
  21. protobufs::TransformationSwapTwoFunctions message)
  22. : message_(std::move(message)) {}
  23. TransformationSwapTwoFunctions::TransformationSwapTwoFunctions(uint32_t id1,
  24. uint32_t id2) {
  25. assert(id1 != id2 && "The two function ids cannot be the same.");
  26. message_.set_function_id1(id1);
  27. message_.set_function_id2(id2);
  28. }
  29. bool TransformationSwapTwoFunctions::IsApplicable(
  30. opt::IRContext* ir_context, const TransformationContext& /*unused*/) const {
  31. auto func1_ptr = ir_context->GetFunction(message_.function_id1());
  32. auto func2_ptr = ir_context->GetFunction(message_.function_id2());
  33. return func1_ptr != nullptr && func2_ptr != nullptr;
  34. }
  35. void TransformationSwapTwoFunctions::Apply(
  36. opt::IRContext* ir_context, TransformationContext* /*unused*/) const {
  37. opt::Module::iterator func1_it =
  38. fuzzerutil::GetFunctionIterator(ir_context, message_.function_id1());
  39. opt::Module::iterator func2_it =
  40. fuzzerutil::GetFunctionIterator(ir_context, message_.function_id2());
  41. assert(func1_it != ir_context->module()->end() &&
  42. "Could not find function 1.");
  43. assert(func2_it != ir_context->module()->end() &&
  44. "Could not find function 2.");
  45. // Two function pointers are all set, swap the two functions within the
  46. // module.
  47. std::iter_swap(func1_it.Get(), func2_it.Get());
  48. }
  49. protobufs::Transformation TransformationSwapTwoFunctions::ToMessage() const {
  50. protobufs::Transformation result;
  51. *result.mutable_swap_two_functions() = message_;
  52. return result;
  53. }
  54. std::unordered_set<uint32_t> TransformationSwapTwoFunctions::GetFreshIds()
  55. const {
  56. return std::unordered_set<uint32_t>();
  57. }
  58. } // namespace fuzz
  59. } // namespace spvtools