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_instructions.h"
16
17 #include "source/fuzz/fuzzer_context.h"
18 #include "source/fuzz/fuzzer_util.h"
19 #include "source/fuzz/instruction_descriptor.h"
20 #include "source/fuzz/transformation_move_instruction_down.h"
21
22 namespace spvtools {
23 namespace fuzz {
24
FuzzerPassPermuteInstructions(opt::IRContext * ir_context,TransformationContext * transformation_context,FuzzerContext * fuzzer_context,protobufs::TransformationSequence * transformations,bool ignore_inapplicable_transformations)25 FuzzerPassPermuteInstructions::FuzzerPassPermuteInstructions(
26 opt::IRContext* ir_context, TransformationContext* transformation_context,
27 FuzzerContext* fuzzer_context,
28 protobufs::TransformationSequence* transformations,
29 bool ignore_inapplicable_transformations)
30 : FuzzerPass(ir_context, transformation_context, fuzzer_context,
31 transformations, ignore_inapplicable_transformations) {}
32
Apply()33 void FuzzerPassPermuteInstructions::Apply() {
34 // We are iterating over all instructions in all basic blocks.
35 for (auto& function : *GetIRContext()->module()) {
36 for (auto& block : function) {
37 // We need to collect all instructions in the block into a separate vector
38 // since application of the transformation below might invalidate
39 // iterators.
40 std::vector<opt::Instruction*> instructions;
41 for (auto& instruction : block) {
42 instructions.push_back(&instruction);
43 }
44
45 // We consider all instructions in reverse to increase the possible number
46 // of applied transformations.
47 for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) {
48 if (!GetFuzzerContext()->ChoosePercentage(
49 GetFuzzerContext()->GetChanceOfPermutingInstructions())) {
50 continue;
51 }
52
53 while (MaybeApplyTransformation(TransformationMoveInstructionDown(
54 MakeInstructionDescriptor(GetIRContext(), *it)))) {
55 // Apply the transformation as many times as possible.
56 }
57 }
58 }
59 }
60 }
61
62 } // namespace fuzz
63 } // namespace spvtools
64