• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_outline_functions.h"
16 
17 #include <vector>
18 
19 #include "source/fuzz/fuzzer_util.h"
20 #include "source/fuzz/instruction_descriptor.h"
21 #include "source/fuzz/transformation_outline_function.h"
22 #include "source/fuzz/transformation_split_block.h"
23 
24 namespace spvtools {
25 namespace fuzz {
26 
FuzzerPassOutlineFunctions(opt::IRContext * ir_context,TransformationContext * transformation_context,FuzzerContext * fuzzer_context,protobufs::TransformationSequence * transformations,bool ignore_inapplicable_transformations)27 FuzzerPassOutlineFunctions::FuzzerPassOutlineFunctions(
28     opt::IRContext* ir_context, TransformationContext* transformation_context,
29     FuzzerContext* fuzzer_context,
30     protobufs::TransformationSequence* transformations,
31     bool ignore_inapplicable_transformations)
32     : FuzzerPass(ir_context, transformation_context, fuzzer_context,
33                  transformations, ignore_inapplicable_transformations) {}
34 
Apply()35 void FuzzerPassOutlineFunctions::Apply() {
36   std::vector<opt::Function*> original_functions;
37   for (auto& function : *GetIRContext()->module()) {
38     original_functions.push_back(&function);
39   }
40   for (auto& function : original_functions) {
41     if (!GetFuzzerContext()->ChoosePercentage(
42             GetFuzzerContext()->GetChanceOfOutliningFunction())) {
43       continue;
44     }
45     std::vector<opt::BasicBlock*> blocks;
46     for (auto& block : *function) {
47       blocks.push_back(&block);
48     }
49     auto entry_block = MaybeGetEntryBlockSuitableForOutlining(
50         blocks[GetFuzzerContext()->RandomIndex(blocks)]);
51 
52     if (!entry_block) {
53       // The chosen block is not suitable to be the entry block of a region that
54       // will be outlined.
55       continue;
56     }
57 
58     auto dominator_analysis = GetIRContext()->GetDominatorAnalysis(function);
59     auto postdominator_analysis =
60         GetIRContext()->GetPostDominatorAnalysis(function);
61     std::vector<opt::BasicBlock*> candidate_exit_blocks;
62     for (auto postdominates_entry_block = entry_block;
63          postdominates_entry_block != nullptr;
64          postdominates_entry_block = postdominator_analysis->ImmediateDominator(
65              postdominates_entry_block)) {
66       // Consider the block if it is dominated by the entry block, ignore it if
67       // it is a continue target.
68       if (dominator_analysis->Dominates(entry_block,
69                                         postdominates_entry_block) &&
70           !GetIRContext()->GetStructuredCFGAnalysis()->IsContinueBlock(
71               postdominates_entry_block->id())) {
72         candidate_exit_blocks.push_back(postdominates_entry_block);
73       }
74     }
75     if (candidate_exit_blocks.empty()) {
76       continue;
77     }
78     auto exit_block = MaybeGetExitBlockSuitableForOutlining(
79         candidate_exit_blocks[GetFuzzerContext()->RandomIndex(
80             candidate_exit_blocks)]);
81 
82     if (!exit_block) {
83       // The block chosen is not suitable
84       continue;
85     }
86 
87     auto region_blocks = TransformationOutlineFunction::GetRegionBlocks(
88         GetIRContext(), entry_block, exit_block);
89     std::map<uint32_t, uint32_t> input_id_to_fresh_id;
90     for (auto id : TransformationOutlineFunction::GetRegionInputIds(
91              GetIRContext(), region_blocks, exit_block)) {
92       input_id_to_fresh_id[id] = GetFuzzerContext()->GetFreshId();
93     }
94     std::map<uint32_t, uint32_t> output_id_to_fresh_id;
95     for (auto id : TransformationOutlineFunction::GetRegionOutputIds(
96              GetIRContext(), region_blocks, exit_block)) {
97       output_id_to_fresh_id[id] = GetFuzzerContext()->GetFreshId();
98     }
99     TransformationOutlineFunction transformation(
100         entry_block->id(), exit_block->id(),
101         /*new_function_struct_return_type_id*/
102         GetFuzzerContext()->GetFreshId(),
103         /*new_function_type_id*/ GetFuzzerContext()->GetFreshId(),
104         /*new_function_id*/ GetFuzzerContext()->GetFreshId(),
105         /*new_function_region_entry_block*/
106         GetFuzzerContext()->GetFreshId(),
107         /*new_caller_result_id*/ GetFuzzerContext()->GetFreshId(),
108         /*new_callee_result_id*/ GetFuzzerContext()->GetFreshId(),
109         /*input_id_to_fresh_id*/ input_id_to_fresh_id,
110         /*output_id_to_fresh_id*/ output_id_to_fresh_id);
111     MaybeApplyTransformation(transformation);
112   }
113 }
114 
115 opt::BasicBlock*
MaybeGetEntryBlockSuitableForOutlining(opt::BasicBlock * entry_block)116 FuzzerPassOutlineFunctions::MaybeGetEntryBlockSuitableForOutlining(
117     opt::BasicBlock* entry_block) {
118   // If the entry block is a loop header, we need to get or create its
119   // preheader and make it the entry block, if possible.
120   if (entry_block->IsLoopHeader()) {
121     auto predecessors =
122         GetIRContext()->cfg()->preds(entry_block->GetLabel()->result_id());
123 
124     if (predecessors.size() < 2) {
125       // The header only has one predecessor (the back-edge block) and thus
126       // it is unreachable. The block cannot be adjusted to be suitable for
127       // outlining.
128       return nullptr;
129     }
130 
131     // Get or create a suitable preheader and make it become the entry block.
132     entry_block =
133         GetOrCreateSimpleLoopPreheader(entry_block->GetLabel()->result_id());
134   }
135 
136   assert(!entry_block->IsLoopHeader() &&
137          "The entry block cannot be a loop header at this point.");
138 
139   // If the entry block starts with OpPhi or OpVariable, try to split it.
140   if (entry_block->begin()->opcode() == SpvOpPhi ||
141       entry_block->begin()->opcode() == SpvOpVariable) {
142     // Find the first non-OpPhi and non-OpVariable instruction.
143     auto non_phi_or_var_inst = &*entry_block->begin();
144     while (non_phi_or_var_inst->opcode() == SpvOpPhi ||
145            non_phi_or_var_inst->opcode() == SpvOpVariable) {
146       non_phi_or_var_inst = non_phi_or_var_inst->NextNode();
147     }
148 
149     // Split the block.
150     uint32_t new_block_id = GetFuzzerContext()->GetFreshId();
151     ApplyTransformation(TransformationSplitBlock(
152         MakeInstructionDescriptor(GetIRContext(), non_phi_or_var_inst),
153         new_block_id));
154 
155     // The new entry block is the newly-created block.
156     entry_block = &*entry_block->GetParent()->FindBlock(new_block_id);
157   }
158 
159   return entry_block;
160 }
161 
162 opt::BasicBlock*
MaybeGetExitBlockSuitableForOutlining(opt::BasicBlock * exit_block)163 FuzzerPassOutlineFunctions::MaybeGetExitBlockSuitableForOutlining(
164     opt::BasicBlock* exit_block) {
165   // The exit block must not be a continue target.
166   assert(!GetIRContext()->GetStructuredCFGAnalysis()->IsContinueBlock(
167              exit_block->id()) &&
168          "A candidate exit block cannot be a continue target.");
169 
170   // If the exit block is a merge block, try to split it and return the second
171   // block in the pair as the exit block.
172   if (GetIRContext()->GetStructuredCFGAnalysis()->IsMergeBlock(
173           exit_block->id())) {
174     uint32_t new_block_id = GetFuzzerContext()->GetFreshId();
175 
176     // Find the first non-OpPhi instruction, after which to split.
177     auto split_before = &*exit_block->begin();
178     while (split_before->opcode() == SpvOpPhi) {
179       split_before = split_before->NextNode();
180     }
181 
182     if (!MaybeApplyTransformation(TransformationSplitBlock(
183             MakeInstructionDescriptor(GetIRContext(), split_before),
184             new_block_id))) {
185       return nullptr;
186     }
187 
188     return &*exit_block->GetParent()->FindBlock(new_block_id);
189   }
190 
191   return exit_block;
192 }
193 
194 }  // namespace fuzz
195 }  // namespace spvtools
196