1 // Copyright (c) 2020 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_flatten_conditional_branches.h"
16 
17 #include "source/fuzz/comparator_deep_blocks_first.h"
18 #include "source/fuzz/instruction_descriptor.h"
19 #include "source/fuzz/transformation_flatten_conditional_branch.h"
20 
21 namespace spvtools {
22 namespace fuzz {
23 
24 // A fuzzer pass that randomly selects conditional branches to flatten and
25 // flattens them, if possible.
FuzzerPassFlattenConditionalBranches(opt::IRContext * ir_context,TransformationContext * transformation_context,FuzzerContext * fuzzer_context,protobufs::TransformationSequence * transformations)26 FuzzerPassFlattenConditionalBranches::FuzzerPassFlattenConditionalBranches(
27     opt::IRContext* ir_context, TransformationContext* transformation_context,
28     FuzzerContext* fuzzer_context,
29     protobufs::TransformationSequence* transformations)
30     : FuzzerPass(ir_context, transformation_context, fuzzer_context,
31                  transformations) {}
32 
33 FuzzerPassFlattenConditionalBranches::~FuzzerPassFlattenConditionalBranches() =
34     default;
35 
Apply()36 void FuzzerPassFlattenConditionalBranches::Apply() {
37   for (auto& function : *GetIRContext()->module()) {
38     // Get all the selection headers that we want to flatten. We need to collect
39     // all of them first, because, since we are changing the structure of the
40     // module, it's not safe to modify them while iterating.
41     std::vector<opt::BasicBlock*> selection_headers;
42 
43     for (auto& block : function) {
44       // Randomly decide whether to consider this block.
45       if (!GetFuzzerContext()->ChoosePercentage(
46               GetFuzzerContext()->GetChanceOfFlatteningConditionalBranch())) {
47         continue;
48       }
49 
50       // Only consider this block if it is the header of a conditional, with a
51       // non-irrelevant condition.
52       if (block.GetMergeInst() &&
53           block.GetMergeInst()->opcode() == SpvOpSelectionMerge &&
54           block.terminator()->opcode() == SpvOpBranchConditional &&
55           !GetTransformationContext()->GetFactManager()->IdIsIrrelevant(
56               block.terminator()->GetSingleWordInOperand(0))) {
57         selection_headers.emplace_back(&block);
58       }
59     }
60 
61     // Sort the headers so that those that are more deeply nested are considered
62     // first, possibly enabling outer conditionals to be flattened.
63     std::sort(selection_headers.begin(), selection_headers.end(),
64               ComparatorDeepBlocksFirst(GetIRContext()));
65 
66     // Apply the transformation to the headers which can be flattened.
67     for (auto header : selection_headers) {
68       // Make a set to keep track of the instructions that need fresh ids.
69       std::set<opt::Instruction*> instructions_that_need_ids;
70 
71       // Do not consider this header if the conditional cannot be flattened.
72       if (!TransformationFlattenConditionalBranch::
73               GetProblematicInstructionsIfConditionalCanBeFlattened(
74                   GetIRContext(), header, *GetTransformationContext(),
75                   &instructions_that_need_ids)) {
76         continue;
77       }
78 
79       uint32_t convergence_block_id =
80           TransformationFlattenConditionalBranch::FindConvergenceBlock(
81               GetIRContext(), *header);
82 
83       // If the SPIR-V version is restricted so that OpSelect can only work on
84       // scalar, pointer and vector types then we cannot apply this
85       // transformation to a header whose convergence block features OpPhi
86       // instructions on different types, as we cannot convert such instructions
87       // to OpSelect instructions.
88       if (TransformationFlattenConditionalBranch::
89               OpSelectArgumentsAreRestricted(GetIRContext())) {
90         if (!GetIRContext()
91                  ->cfg()
92                  ->block(convergence_block_id)
93                  ->WhileEachPhiInst(
94                      [this](opt::Instruction* phi_instruction) -> bool {
95                        switch (GetIRContext()
96                                    ->get_def_use_mgr()
97                                    ->GetDef(phi_instruction->type_id())
98                                    ->opcode()) {
99                          case SpvOpTypeBool:
100                          case SpvOpTypeInt:
101                          case SpvOpTypeFloat:
102                          case SpvOpTypePointer:
103                          case SpvOpTypeVector:
104                            return true;
105                          default:
106                            return false;
107                        }
108                      })) {
109           // An OpPhi is performed on a type not supported by OpSelect; we
110           // cannot flatten this selection.
111           continue;
112         }
113       }
114 
115       // If the construct's convergence block features OpPhi instructions with
116       // vector result types then we may be *forced*, by the SPIR-V version, to
117       // turn these into component-wise OpSelect instructions, or we might wish
118       // to do so anyway.  The following booleans capture whether we will opt
119       // to use a component-wise select even if we don't have to.
120       bool use_component_wise_2d_select_even_if_optional =
121           GetFuzzerContext()->ChooseEven();
122       bool use_component_wise_3d_select_even_if_optional =
123           GetFuzzerContext()->ChooseEven();
124       bool use_component_wise_4d_select_even_if_optional =
125           GetFuzzerContext()->ChooseEven();
126 
127       // If we do need to perform any component-wise selections, we will need a
128       // fresh id for a boolean vector representing the selection's condition
129       // repeated N times, where N is the vector dimension.
130       uint32_t fresh_id_for_bvec2_selector = 0;
131       uint32_t fresh_id_for_bvec3_selector = 0;
132       uint32_t fresh_id_for_bvec4_selector = 0;
133 
134       GetIRContext()
135           ->cfg()
136           ->block(convergence_block_id)
137           ->ForEachPhiInst([this, &fresh_id_for_bvec2_selector,
138                             &fresh_id_for_bvec3_selector,
139                             &fresh_id_for_bvec4_selector,
140                             use_component_wise_2d_select_even_if_optional,
141                             use_component_wise_3d_select_even_if_optional,
142                             use_component_wise_4d_select_even_if_optional](
143                                opt::Instruction* phi_instruction) {
144             opt::Instruction* type_instruction =
145                 GetIRContext()->get_def_use_mgr()->GetDef(
146                     phi_instruction->type_id());
147             switch (type_instruction->opcode()) {
148               case SpvOpTypeVector: {
149                 uint32_t dimension =
150                     type_instruction->GetSingleWordInOperand(1);
151                 switch (dimension) {
152                   case 2:
153                     PrepareForOpPhiOnVectors(
154                         dimension,
155                         use_component_wise_2d_select_even_if_optional,
156                         &fresh_id_for_bvec2_selector);
157                     break;
158                   case 3:
159                     PrepareForOpPhiOnVectors(
160                         dimension,
161                         use_component_wise_3d_select_even_if_optional,
162                         &fresh_id_for_bvec3_selector);
163                     break;
164                   case 4:
165                     PrepareForOpPhiOnVectors(
166                         dimension,
167                         use_component_wise_4d_select_even_if_optional,
168                         &fresh_id_for_bvec4_selector);
169                     break;
170                   default:
171                     assert(false && "Invalid vector dimension.");
172                 }
173                 break;
174               }
175               default:
176                 break;
177             }
178           });
179 
180       // Some instructions will require to be enclosed inside conditionals
181       // because they have side effects (for example, loads and stores). Some of
182       // this have no result id, so we require instruction descriptors to
183       // identify them. Each of them is associated with the necessary ids for it
184       // via a SideEffectWrapperInfo message.
185       std::vector<protobufs::SideEffectWrapperInfo> wrappers_info;
186 
187       for (auto instruction : instructions_that_need_ids) {
188         protobufs::SideEffectWrapperInfo wrapper_info;
189         *wrapper_info.mutable_instruction() =
190             MakeInstructionDescriptor(GetIRContext(), instruction);
191         wrapper_info.set_merge_block_id(GetFuzzerContext()->GetFreshId());
192         wrapper_info.set_execute_block_id(GetFuzzerContext()->GetFreshId());
193 
194         // If the instruction has a non-void result id, we need to define more
195         // fresh ids and provide an id of the suitable type whose value can be
196         // copied in order to create a placeholder id.
197         if (TransformationFlattenConditionalBranch::InstructionNeedsPlaceholder(
198                 GetIRContext(), *instruction)) {
199           wrapper_info.set_actual_result_id(GetFuzzerContext()->GetFreshId());
200           wrapper_info.set_alternative_block_id(
201               GetFuzzerContext()->GetFreshId());
202           wrapper_info.set_placeholder_result_id(
203               GetFuzzerContext()->GetFreshId());
204 
205           // The id will be a zero constant if the type allows it, and an
206           // OpUndef otherwise. We want to avoid using OpUndef, if possible, to
207           // avoid undefined behaviour in the module as much as possible.
208           if (fuzzerutil::CanCreateConstant(GetIRContext(),
209                                             instruction->type_id())) {
210             wrapper_info.set_value_to_copy_id(
211                 FindOrCreateZeroConstant(instruction->type_id(), true));
212           } else {
213             wrapper_info.set_value_to_copy_id(
214                 FindOrCreateGlobalUndef(instruction->type_id()));
215           }
216         }
217 
218         wrappers_info.push_back(std::move(wrapper_info));
219       }
220 
221       // Apply the transformation, evenly choosing whether to lay out the true
222       // branch or the false branch first.
223       ApplyTransformation(TransformationFlattenConditionalBranch(
224           header->id(), GetFuzzerContext()->ChooseEven(),
225           fresh_id_for_bvec2_selector, fresh_id_for_bvec3_selector,
226           fresh_id_for_bvec4_selector, wrappers_info));
227     }
228   }
229 }
230 
PrepareForOpPhiOnVectors(uint32_t vector_dimension,bool use_vector_select_if_optional,uint32_t * fresh_id_for_bvec_selector)231 void FuzzerPassFlattenConditionalBranches::PrepareForOpPhiOnVectors(
232     uint32_t vector_dimension, bool use_vector_select_if_optional,
233     uint32_t* fresh_id_for_bvec_selector) {
234   if (*fresh_id_for_bvec_selector != 0) {
235     // We already have a fresh id for a component-wise OpSelect of this
236     // dimension
237     return;
238   }
239   if (TransformationFlattenConditionalBranch::OpSelectArgumentsAreRestricted(
240           GetIRContext()) ||
241       use_vector_select_if_optional) {
242     // We either have to, or have chosen to, perform a component-wise select, so
243     // we ensure that the right boolean vector type is available, and grab a
244     // fresh id.
245     FindOrCreateVectorType(FindOrCreateBoolType(), vector_dimension);
246     *fresh_id_for_bvec_selector = GetFuzzerContext()->GetFreshId();
247   }
248 }
249 
250 }  // namespace fuzz
251 }  // namespace spvtools
252