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 
15 #include "source/fuzz/fuzzer_pass_merge_blocks.h"
16 
17 #include <vector>
18 
19 #include "source/fuzz/transformation_merge_blocks.h"
20 
21 namespace spvtools {
22 namespace fuzz {
23 
FuzzerPassMergeBlocks(opt::IRContext * ir_context,TransformationContext * transformation_context,FuzzerContext * fuzzer_context,protobufs::TransformationSequence * transformations)24 FuzzerPassMergeBlocks::FuzzerPassMergeBlocks(
25     opt::IRContext* ir_context, TransformationContext* transformation_context,
26     FuzzerContext* fuzzer_context,
27     protobufs::TransformationSequence* transformations)
28     : FuzzerPass(ir_context, transformation_context, fuzzer_context,
29                  transformations) {}
30 
31 FuzzerPassMergeBlocks::~FuzzerPassMergeBlocks() = default;
32 
Apply()33 void FuzzerPassMergeBlocks::Apply() {
34   // First we populate a sequence of transformations that we might consider
35   // applying.
36   std::vector<TransformationMergeBlocks> potential_transformations;
37   // We do this by considering every block of every function.
38   for (auto& function : *GetIRContext()->module()) {
39     for (auto& block : function) {
40       // We probabilistically decide to ignore some blocks.
41       if (!GetFuzzerContext()->ChoosePercentage(
42               GetFuzzerContext()->GetChanceOfMergingBlocks())) {
43         continue;
44       }
45       // For other blocks, we add a transformation to merge the block into its
46       // predecessor if that transformation would be applicable.
47       TransformationMergeBlocks transformation(block.id());
48       if (transformation.IsApplicable(GetIRContext(),
49                                       *GetTransformationContext())) {
50         potential_transformations.push_back(transformation);
51       }
52     }
53   }
54 
55   while (!potential_transformations.empty()) {
56     auto transformation =
57         GetFuzzerContext()->RemoveAtRandomIndex(&potential_transformations);
58     MaybeApplyTransformation(transformation);
59   }
60 }
61 
62 }  // namespace fuzz
63 }  // namespace spvtools
64