1 // Copyright (c) 2020 Vasyl Teliman
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/fuzzer_pass_permute_phi_operands.h"
16
17 #include <numeric>
18 #include <vector>
19
20 #include "source/fuzz/fuzzer_context.h"
21 #include "source/fuzz/fuzzer_util.h"
22 #include "source/fuzz/instruction_descriptor.h"
23 #include "source/fuzz/transformation_permute_phi_operands.h"
24
25 namespace spvtools {
26 namespace fuzz {
27
FuzzerPassPermutePhiOperands(opt::IRContext * ir_context,TransformationContext * transformation_context,FuzzerContext * fuzzer_context,protobufs::TransformationSequence * transformations,bool ignore_inapplicable_transformations)28 FuzzerPassPermutePhiOperands::FuzzerPassPermutePhiOperands(
29 opt::IRContext* ir_context, TransformationContext* transformation_context,
30 FuzzerContext* fuzzer_context,
31 protobufs::TransformationSequence* transformations,
32 bool ignore_inapplicable_transformations)
33 : FuzzerPass(ir_context, transformation_context, fuzzer_context,
34 transformations, ignore_inapplicable_transformations) {}
35
Apply()36 void FuzzerPassPermutePhiOperands::Apply() {
37 ForEachInstructionWithInstructionDescriptor(
38 [this](opt::Function* /*unused*/, opt::BasicBlock* /*unused*/,
39 opt::BasicBlock::iterator inst_it,
40 const protobufs::InstructionDescriptor& /*unused*/) {
41 const auto& inst = *inst_it;
42
43 if (inst.opcode() != SpvOpPhi) {
44 return;
45 }
46
47 if (!GetFuzzerContext()->ChoosePercentage(
48 GetFuzzerContext()->GetChanceOfPermutingPhiOperands())) {
49 return;
50 }
51
52 // Create a vector of indices for each pair of operands in the |inst|.
53 // OpPhi always has an even number of operands.
54 std::vector<uint32_t> permutation(inst.NumInOperands() / 2);
55 std::iota(permutation.begin(), permutation.end(), 0);
56 GetFuzzerContext()->Shuffle(&permutation);
57
58 ApplyTransformation(TransformationPermutePhiOperands(
59 inst.result_id(), std::move(permutation)));
60 });
61 }
62
63 } // namespace fuzz
64 } // namespace spvtools
65