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_add_dead_breaks.h"
16 
17 #include "source/fuzz/fuzzer_util.h"
18 #include "source/fuzz/transformation_add_dead_break.h"
19 #include "source/opt/ir_context.h"
20 
21 namespace spvtools {
22 namespace fuzz {
23 
FuzzerPassAddDeadBreaks(opt::IRContext * ir_context,TransformationContext * transformation_context,FuzzerContext * fuzzer_context,protobufs::TransformationSequence * transformations)24 FuzzerPassAddDeadBreaks::FuzzerPassAddDeadBreaks(
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 FuzzerPassAddDeadBreaks::~FuzzerPassAddDeadBreaks() = default;
32 
Apply()33 void FuzzerPassAddDeadBreaks::Apply() {
34   // We first collect up lots of possibly-applicable transformations.
35   std::vector<TransformationAddDeadBreak> candidate_transformations;
36   // We consider each function separately.
37   for (auto& function : *GetIRContext()->module()) {
38     // For a given function, we find all the merge blocks in that function.
39     std::vector<opt::BasicBlock*> merge_blocks;
40     for (auto& block : function) {
41       auto maybe_merge_id = block.MergeBlockIdIfAny();
42       if (maybe_merge_id) {
43         auto merge_block =
44             fuzzerutil::MaybeFindBlock(GetIRContext(), maybe_merge_id);
45 
46         assert(merge_block && "Merge block can't be null");
47 
48         merge_blocks.push_back(merge_block);
49       }
50     }
51     // We rather aggressively consider the possibility of adding a break from
52     // every block in the function to every merge block.  Many of these will be
53     // inapplicable as they would be illegal.  That's OK - we later discard the
54     // ones that turn out to be no good.
55     for (auto& block : function) {
56       for (auto* merge_block : merge_blocks) {
57         // Populate this vector with ids that are available at the branch point
58         // of this basic block. We will use these ids to update OpPhi
59         // instructions later.
60         std::vector<uint32_t> phi_ids;
61 
62         // Determine how we need to adjust OpPhi instructions' operands
63         // for this transformation to be valid.
64         //
65         // If |block| has a branch to |merge_block|, the latter must have all of
66         // its OpPhi instructions set up correctly - we don't need to adjust
67         // anything.
68         if (!block.IsSuccessor(merge_block)) {
69           merge_block->ForEachPhiInst([this, &phi_ids](opt::Instruction* phi) {
70             // Add an additional operand for OpPhi instruction.  Use a constant
71             // if possible, and an undef otherwise.
72             if (fuzzerutil::CanCreateConstant(GetIRContext(), phi->type_id())) {
73               // We mark the constant as irrelevant so that we can replace it
74               // with a more interesting value later.
75               phi_ids.push_back(FindOrCreateZeroConstant(phi->type_id(), true));
76             } else {
77               phi_ids.push_back(FindOrCreateGlobalUndef(phi->type_id()));
78             }
79           });
80         }
81 
82         // Make sure the module has a required boolean constant to be used in
83         // OpBranchConditional instruction.
84         auto break_condition = GetFuzzerContext()->ChooseEven();
85         FindOrCreateBoolConstant(break_condition, false);
86 
87         auto candidate_transformation = TransformationAddDeadBreak(
88             block.id(), merge_block->id(), break_condition, std::move(phi_ids));
89         if (candidate_transformation.IsApplicable(
90                 GetIRContext(), *GetTransformationContext())) {
91           // Only consider a transformation as a candidate if it is applicable.
92           candidate_transformations.push_back(
93               std::move(candidate_transformation));
94         }
95       }
96     }
97   }
98 
99   // Go through the candidate transformations that were accumulated,
100   // probabilistically deciding whether to consider each one further and
101   // applying the still-applicable ones that are considered further.
102   //
103   // We iterate through the candidate transformations in a random order by
104   // repeatedly removing a random candidate transformation from the sequence
105   // until no candidate transformations remain.  This is done because
106   // transformations can potentially disable one another, so that iterating
107   // through them in order would lead to a higher probability of
108   // transformations appearing early in the sequence being applied compared
109   // with later transformations.
110   while (!candidate_transformations.empty()) {
111     // Choose a random index into the sequence of remaining candidate
112     // transformations.
113     auto index = GetFuzzerContext()->RandomIndex(candidate_transformations);
114     // Remove the transformation at the chosen index from the sequence.
115     auto transformation = std::move(candidate_transformations[index]);
116     candidate_transformations.erase(candidate_transformations.begin() + index);
117     // Probabilistically decide whether to try to apply it vs. ignore it, in the
118     // case that it is applicable.
119     if (GetFuzzerContext()->ChoosePercentage(
120             GetFuzzerContext()->GetChanceOfAddingDeadBreak())) {
121       MaybeApplyTransformation(transformation);
122     }
123   }
124 }
125 
126 }  // namespace fuzz
127 }  // namespace spvtools
128