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_blocks.h"
16
17 #include "source/fuzz/fuzzer_util.h"
18 #include "source/fuzz/transformation_add_dead_block.h"
19
20 namespace spvtools {
21 namespace fuzz {
22
FuzzerPassAddDeadBlocks(opt::IRContext * ir_context,TransformationContext * transformation_context,FuzzerContext * fuzzer_context,protobufs::TransformationSequence * transformations)23 FuzzerPassAddDeadBlocks::FuzzerPassAddDeadBlocks(
24 opt::IRContext* ir_context, TransformationContext* transformation_context,
25 FuzzerContext* fuzzer_context,
26 protobufs::TransformationSequence* transformations)
27 : FuzzerPass(ir_context, transformation_context, fuzzer_context,
28 transformations) {}
29
30 FuzzerPassAddDeadBlocks::~FuzzerPassAddDeadBlocks() = default;
31
Apply()32 void FuzzerPassAddDeadBlocks::Apply() {
33 // We iterate over all blocks in the module collecting up those at which we
34 // might add a branch to a new dead block. We then loop over all such
35 // candidates and actually apply transformations. This separation is to
36 // avoid modifying the module as we traverse it.
37 std::vector<TransformationAddDeadBlock> candidate_transformations;
38 for (auto& function : *GetIRContext()->module()) {
39 for (auto& block : function) {
40 if (!GetFuzzerContext()->ChoosePercentage(
41 GetFuzzerContext()->GetChanceOfAddingDeadBlock())) {
42 continue;
43 }
44
45 // Make sure the module contains a boolean constant equal to
46 // |condition_value|.
47 bool condition_value = GetFuzzerContext()->ChooseEven();
48 FindOrCreateBoolConstant(condition_value, false);
49
50 // We speculatively create a transformation, and then apply it (below) if
51 // it turns out to be applicable. This avoids duplicating the logic for
52 // applicability checking.
53 //
54 // It means that fresh ids for transformations that turn out not to be
55 // applicable end up being unused.
56 candidate_transformations.emplace_back(TransformationAddDeadBlock(
57 GetFuzzerContext()->GetFreshId(), block.id(), condition_value));
58 }
59 }
60 // Apply all those transformations that are in fact applicable.
61 for (auto& transformation : candidate_transformations) {
62 MaybeApplyTransformation(transformation);
63 }
64 }
65
66 } // namespace fuzz
67 } // namespace spvtools
68