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