• 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.h"
16 
17 #include <set>
18 
19 #include "source/fuzz/fuzzer_util.h"
20 #include "source/fuzz/id_use_descriptor.h"
21 #include "source/fuzz/instruction_descriptor.h"
22 #include "source/fuzz/transformation_add_constant_boolean.h"
23 #include "source/fuzz/transformation_add_constant_composite.h"
24 #include "source/fuzz/transformation_add_constant_null.h"
25 #include "source/fuzz/transformation_add_constant_scalar.h"
26 #include "source/fuzz/transformation_add_global_undef.h"
27 #include "source/fuzz/transformation_add_global_variable.h"
28 #include "source/fuzz/transformation_add_local_variable.h"
29 #include "source/fuzz/transformation_add_loop_preheader.h"
30 #include "source/fuzz/transformation_add_type_boolean.h"
31 #include "source/fuzz/transformation_add_type_float.h"
32 #include "source/fuzz/transformation_add_type_function.h"
33 #include "source/fuzz/transformation_add_type_int.h"
34 #include "source/fuzz/transformation_add_type_matrix.h"
35 #include "source/fuzz/transformation_add_type_pointer.h"
36 #include "source/fuzz/transformation_add_type_struct.h"
37 #include "source/fuzz/transformation_add_type_vector.h"
38 #include "source/fuzz/transformation_split_block.h"
39 
40 namespace spvtools {
41 namespace fuzz {
42 
FuzzerPass(opt::IRContext * ir_context,TransformationContext * transformation_context,FuzzerContext * fuzzer_context,protobufs::TransformationSequence * transformations)43 FuzzerPass::FuzzerPass(opt::IRContext* ir_context,
44                        TransformationContext* transformation_context,
45                        FuzzerContext* fuzzer_context,
46                        protobufs::TransformationSequence* transformations)
47     : ir_context_(ir_context),
48       transformation_context_(transformation_context),
49       fuzzer_context_(fuzzer_context),
50       transformations_(transformations) {}
51 
52 FuzzerPass::~FuzzerPass() = default;
53 
FindAvailableInstructions(opt::Function * function,opt::BasicBlock * block,const opt::BasicBlock::iterator & inst_it,std::function<bool (opt::IRContext *,opt::Instruction *)> instruction_is_relevant) const54 std::vector<opt::Instruction*> FuzzerPass::FindAvailableInstructions(
55     opt::Function* function, opt::BasicBlock* block,
56     const opt::BasicBlock::iterator& inst_it,
57     std::function<bool(opt::IRContext*, opt::Instruction*)>
58         instruction_is_relevant) const {
59   // TODO(afd) The following is (relatively) simple, but may end up being
60   //  prohibitively inefficient, as it walks the whole dominator tree for
61   //  every instruction that is considered.
62 
63   std::vector<opt::Instruction*> result;
64   // Consider all global declarations
65   for (auto& global : GetIRContext()->module()->types_values()) {
66     if (instruction_is_relevant(GetIRContext(), &global)) {
67       result.push_back(&global);
68     }
69   }
70 
71   // Consider all function parameters
72   function->ForEachParam(
73       [this, &instruction_is_relevant, &result](opt::Instruction* param) {
74         if (instruction_is_relevant(GetIRContext(), param)) {
75           result.push_back(param);
76         }
77       });
78 
79   // Consider all previous instructions in this block
80   for (auto prev_inst_it = block->begin(); prev_inst_it != inst_it;
81        ++prev_inst_it) {
82     if (instruction_is_relevant(GetIRContext(), &*prev_inst_it)) {
83       result.push_back(&*prev_inst_it);
84     }
85   }
86 
87   // Walk the dominator tree to consider all instructions from dominating
88   // blocks
89   auto dominator_analysis = GetIRContext()->GetDominatorAnalysis(function);
90   for (auto next_dominator = dominator_analysis->ImmediateDominator(block);
91        next_dominator != nullptr;
92        next_dominator =
93            dominator_analysis->ImmediateDominator(next_dominator)) {
94     for (auto& dominating_inst : *next_dominator) {
95       if (instruction_is_relevant(GetIRContext(), &dominating_inst)) {
96         result.push_back(&dominating_inst);
97       }
98     }
99   }
100   return result;
101 }
102 
ForEachInstructionWithInstructionDescriptor(opt::Function * function,std::function<void (opt::BasicBlock * block,opt::BasicBlock::iterator inst_it,const protobufs::InstructionDescriptor & instruction_descriptor)> action)103 void FuzzerPass::ForEachInstructionWithInstructionDescriptor(
104     opt::Function* function,
105     std::function<
106         void(opt::BasicBlock* block, opt::BasicBlock::iterator inst_it,
107              const protobufs::InstructionDescriptor& instruction_descriptor)>
108         action) {
109   // Consider only reachable blocks. We do this in a separate loop to avoid
110   // recomputing the dominator analysis every time |action| changes the
111   // module.
112   std::vector<opt::BasicBlock*> reachable_blocks;
113 
114   for (auto& block : *function) {
115     if (GetIRContext()->IsReachable(block)) {
116       reachable_blocks.push_back(&block);
117     }
118   }
119 
120   for (auto* block : reachable_blocks) {
121     // We now consider every instruction in the block, randomly deciding
122     // whether to apply a transformation before it.
123 
124     // In order for transformations to insert new instructions, they need to
125     // be able to identify the instruction to insert before.  We describe an
126     // instruction via its opcode, 'opc', a base instruction 'base' that has a
127     // result id, and the number of instructions with opcode 'opc' that we
128     // should skip when searching from 'base' for the desired instruction.
129     // (An instruction that has a result id is represented by its own opcode,
130     // itself as 'base', and a skip-count of 0.)
131     std::vector<std::tuple<uint32_t, SpvOp, uint32_t>> base_opcode_skip_triples;
132 
133     // The initial base instruction is the block label.
134     uint32_t base = block->id();
135 
136     // Counts the number of times we have seen each opcode since we reset the
137     // base instruction.
138     std::map<SpvOp, uint32_t> skip_count;
139 
140     // Consider every instruction in the block.  The label is excluded: it is
141     // only necessary to consider it as a base in case the first instruction
142     // in the block does not have a result id.
143     for (auto inst_it = block->begin(); inst_it != block->end(); ++inst_it) {
144       if (inst_it->HasResultId()) {
145         // In the case that the instruction has a result id, we use the
146         // instruction as its own base, and clear the skip counts we have
147         // collected.
148         base = inst_it->result_id();
149         skip_count.clear();
150       }
151       const SpvOp opcode = inst_it->opcode();
152 
153       // Invoke the provided function, which might apply a transformation.
154       action(block, inst_it,
155              MakeInstructionDescriptor(
156                  base, opcode,
157                  skip_count.count(opcode) ? skip_count.at(opcode) : 0));
158 
159       if (!inst_it->HasResultId()) {
160         skip_count[opcode] =
161             skip_count.count(opcode) ? skip_count.at(opcode) + 1 : 1;
162       }
163     }
164   }
165 }
166 
ForEachInstructionWithInstructionDescriptor(std::function<void (opt::Function * function,opt::BasicBlock * block,opt::BasicBlock::iterator inst_it,const protobufs::InstructionDescriptor & instruction_descriptor)> action)167 void FuzzerPass::ForEachInstructionWithInstructionDescriptor(
168     std::function<
169         void(opt::Function* function, opt::BasicBlock* block,
170              opt::BasicBlock::iterator inst_it,
171              const protobufs::InstructionDescriptor& instruction_descriptor)>
172         action) {
173   // Consider every block in every function.
174   for (auto& function : *GetIRContext()->module()) {
175     ForEachInstructionWithInstructionDescriptor(
176         &function,
177         [&action, &function](
178             opt::BasicBlock* block, opt::BasicBlock::iterator inst_it,
179             const protobufs::InstructionDescriptor& instruction_descriptor) {
180           action(&function, block, inst_it, instruction_descriptor);
181         });
182   }
183 }
184 
ApplyTransformation(const Transformation & transformation)185 void FuzzerPass::ApplyTransformation(const Transformation& transformation) {
186   assert(transformation.IsApplicable(GetIRContext(),
187                                      *GetTransformationContext()) &&
188          "Transformation should be applicable by construction.");
189   transformation.Apply(GetIRContext(), GetTransformationContext());
190   auto transformation_message = transformation.ToMessage();
191   assert(transformation_message.transformation_case() !=
192              protobufs::Transformation::TRANSFORMATION_NOT_SET &&
193          "Bad transformation.");
194   *GetTransformations()->add_transformation() =
195       std::move(transformation_message);
196 }
197 
MaybeApplyTransformation(const Transformation & transformation)198 bool FuzzerPass::MaybeApplyTransformation(
199     const Transformation& transformation) {
200   if (transformation.IsApplicable(GetIRContext(),
201                                   *GetTransformationContext())) {
202     transformation.Apply(GetIRContext(), GetTransformationContext());
203     auto transformation_message = transformation.ToMessage();
204     assert(transformation_message.transformation_case() !=
205                protobufs::Transformation::TRANSFORMATION_NOT_SET &&
206            "Bad transformation.");
207     *GetTransformations()->add_transformation() =
208         std::move(transformation_message);
209     return true;
210   }
211   return false;
212 }
213 
FindOrCreateBoolType()214 uint32_t FuzzerPass::FindOrCreateBoolType() {
215   if (auto existing_id = fuzzerutil::MaybeGetBoolType(GetIRContext())) {
216     return existing_id;
217   }
218   auto result = GetFuzzerContext()->GetFreshId();
219   ApplyTransformation(TransformationAddTypeBoolean(result));
220   return result;
221 }
222 
FindOrCreateIntegerType(uint32_t width,bool is_signed)223 uint32_t FuzzerPass::FindOrCreateIntegerType(uint32_t width, bool is_signed) {
224   opt::analysis::Integer int_type(width, is_signed);
225   auto existing_id = GetIRContext()->get_type_mgr()->GetId(&int_type);
226   if (existing_id) {
227     return existing_id;
228   }
229   auto result = GetFuzzerContext()->GetFreshId();
230   ApplyTransformation(TransformationAddTypeInt(result, width, is_signed));
231   return result;
232 }
233 
FindOrCreateFloatType(uint32_t width)234 uint32_t FuzzerPass::FindOrCreateFloatType(uint32_t width) {
235   opt::analysis::Float float_type(width);
236   auto existing_id = GetIRContext()->get_type_mgr()->GetId(&float_type);
237   if (existing_id) {
238     return existing_id;
239   }
240   auto result = GetFuzzerContext()->GetFreshId();
241   ApplyTransformation(TransformationAddTypeFloat(result, width));
242   return result;
243 }
244 
FindOrCreateFunctionType(uint32_t return_type_id,const std::vector<uint32_t> & argument_id)245 uint32_t FuzzerPass::FindOrCreateFunctionType(
246     uint32_t return_type_id, const std::vector<uint32_t>& argument_id) {
247   // FindFunctionType has a sigle argument for OpTypeFunction operands
248   // so we will have to copy them all in this vector
249   std::vector<uint32_t> type_ids(argument_id.size() + 1);
250   type_ids[0] = return_type_id;
251   std::copy(argument_id.begin(), argument_id.end(), type_ids.begin() + 1);
252 
253   // Check if type exists
254   auto existing_id = fuzzerutil::FindFunctionType(GetIRContext(), type_ids);
255   if (existing_id) {
256     return existing_id;
257   }
258 
259   auto result = GetFuzzerContext()->GetFreshId();
260   ApplyTransformation(
261       TransformationAddTypeFunction(result, return_type_id, argument_id));
262   return result;
263 }
264 
FindOrCreateVectorType(uint32_t component_type_id,uint32_t component_count)265 uint32_t FuzzerPass::FindOrCreateVectorType(uint32_t component_type_id,
266                                             uint32_t component_count) {
267   assert(component_count >= 2 && component_count <= 4 &&
268          "Precondition: component count must be in range [2, 4].");
269   opt::analysis::Type* component_type =
270       GetIRContext()->get_type_mgr()->GetType(component_type_id);
271   assert(component_type && "Precondition: the component type must exist.");
272   opt::analysis::Vector vector_type(component_type, component_count);
273   auto existing_id = GetIRContext()->get_type_mgr()->GetId(&vector_type);
274   if (existing_id) {
275     return existing_id;
276   }
277   auto result = GetFuzzerContext()->GetFreshId();
278   ApplyTransformation(
279       TransformationAddTypeVector(result, component_type_id, component_count));
280   return result;
281 }
282 
FindOrCreateMatrixType(uint32_t column_count,uint32_t row_count)283 uint32_t FuzzerPass::FindOrCreateMatrixType(uint32_t column_count,
284                                             uint32_t row_count) {
285   assert(column_count >= 2 && column_count <= 4 &&
286          "Precondition: column count must be in range [2, 4].");
287   assert(row_count >= 2 && row_count <= 4 &&
288          "Precondition: row count must be in range [2, 4].");
289   uint32_t column_type_id =
290       FindOrCreateVectorType(FindOrCreateFloatType(32), row_count);
291   opt::analysis::Type* column_type =
292       GetIRContext()->get_type_mgr()->GetType(column_type_id);
293   opt::analysis::Matrix matrix_type(column_type, column_count);
294   auto existing_id = GetIRContext()->get_type_mgr()->GetId(&matrix_type);
295   if (existing_id) {
296     return existing_id;
297   }
298   auto result = GetFuzzerContext()->GetFreshId();
299   ApplyTransformation(
300       TransformationAddTypeMatrix(result, column_type_id, column_count));
301   return result;
302 }
303 
FindOrCreateStructType(const std::vector<uint32_t> & component_type_ids)304 uint32_t FuzzerPass::FindOrCreateStructType(
305     const std::vector<uint32_t>& component_type_ids) {
306   if (auto existing_id =
307           fuzzerutil::MaybeGetStructType(GetIRContext(), component_type_ids)) {
308     return existing_id;
309   }
310   auto new_id = GetFuzzerContext()->GetFreshId();
311   ApplyTransformation(TransformationAddTypeStruct(new_id, component_type_ids));
312   return new_id;
313 }
314 
FindOrCreatePointerType(uint32_t base_type_id,SpvStorageClass storage_class)315 uint32_t FuzzerPass::FindOrCreatePointerType(uint32_t base_type_id,
316                                              SpvStorageClass storage_class) {
317   // We do not use the type manager here, due to problems related to isomorphic
318   // but distinct structs not being regarded as different.
319   auto existing_id = fuzzerutil::MaybeGetPointerType(
320       GetIRContext(), base_type_id, storage_class);
321   if (existing_id) {
322     return existing_id;
323   }
324   auto result = GetFuzzerContext()->GetFreshId();
325   ApplyTransformation(
326       TransformationAddTypePointer(result, storage_class, base_type_id));
327   return result;
328 }
329 
FindOrCreatePointerToIntegerType(uint32_t width,bool is_signed,SpvStorageClass storage_class)330 uint32_t FuzzerPass::FindOrCreatePointerToIntegerType(
331     uint32_t width, bool is_signed, SpvStorageClass storage_class) {
332   return FindOrCreatePointerType(FindOrCreateIntegerType(width, is_signed),
333                                  storage_class);
334 }
335 
FindOrCreateIntegerConstant(const std::vector<uint32_t> & words,uint32_t width,bool is_signed,bool is_irrelevant)336 uint32_t FuzzerPass::FindOrCreateIntegerConstant(
337     const std::vector<uint32_t>& words, uint32_t width, bool is_signed,
338     bool is_irrelevant) {
339   auto int_type_id = FindOrCreateIntegerType(width, is_signed);
340   if (auto constant_id = fuzzerutil::MaybeGetScalarConstant(
341           GetIRContext(), *GetTransformationContext(), words, int_type_id,
342           is_irrelevant)) {
343     return constant_id;
344   }
345   auto result = GetFuzzerContext()->GetFreshId();
346   ApplyTransformation(TransformationAddConstantScalar(result, int_type_id,
347                                                       words, is_irrelevant));
348   return result;
349 }
350 
FindOrCreateFloatConstant(const std::vector<uint32_t> & words,uint32_t width,bool is_irrelevant)351 uint32_t FuzzerPass::FindOrCreateFloatConstant(
352     const std::vector<uint32_t>& words, uint32_t width, bool is_irrelevant) {
353   auto float_type_id = FindOrCreateFloatType(width);
354   if (auto constant_id = fuzzerutil::MaybeGetScalarConstant(
355           GetIRContext(), *GetTransformationContext(), words, float_type_id,
356           is_irrelevant)) {
357     return constant_id;
358   }
359   auto result = GetFuzzerContext()->GetFreshId();
360   ApplyTransformation(TransformationAddConstantScalar(result, float_type_id,
361                                                       words, is_irrelevant));
362   return result;
363 }
364 
FindOrCreateBoolConstant(bool value,bool is_irrelevant)365 uint32_t FuzzerPass::FindOrCreateBoolConstant(bool value, bool is_irrelevant) {
366   auto bool_type_id = FindOrCreateBoolType();
367   if (auto constant_id = fuzzerutil::MaybeGetScalarConstant(
368           GetIRContext(), *GetTransformationContext(), {value ? 1u : 0u},
369           bool_type_id, is_irrelevant)) {
370     return constant_id;
371   }
372   auto result = GetFuzzerContext()->GetFreshId();
373   ApplyTransformation(
374       TransformationAddConstantBoolean(result, value, is_irrelevant));
375   return result;
376 }
377 
FindOrCreateConstant(const std::vector<uint32_t> & words,uint32_t type_id,bool is_irrelevant)378 uint32_t FuzzerPass::FindOrCreateConstant(const std::vector<uint32_t>& words,
379                                           uint32_t type_id,
380                                           bool is_irrelevant) {
381   assert(type_id && "Constant's type id can't be 0.");
382 
383   const auto* type = GetIRContext()->get_type_mgr()->GetType(type_id);
384   assert(type && "Type does not exist.");
385 
386   if (type->AsBool()) {
387     assert(words.size() == 1);
388     return FindOrCreateBoolConstant(words[0], is_irrelevant);
389   } else if (const auto* integer = type->AsInteger()) {
390     return FindOrCreateIntegerConstant(words, integer->width(),
391                                        integer->IsSigned(), is_irrelevant);
392   } else if (const auto* floating = type->AsFloat()) {
393     return FindOrCreateFloatConstant(words, floating->width(), is_irrelevant);
394   }
395 
396   // This assertion will fail in debug build but not in release build
397   // so we return 0 to make compiler happy.
398   assert(false && "Constant type is not supported");
399   return 0;
400 }
401 
FindOrCreateCompositeConstant(const std::vector<uint32_t> & component_ids,uint32_t type_id,bool is_irrelevant)402 uint32_t FuzzerPass::FindOrCreateCompositeConstant(
403     const std::vector<uint32_t>& component_ids, uint32_t type_id,
404     bool is_irrelevant) {
405   if (auto existing_constant = fuzzerutil::MaybeGetCompositeConstant(
406           GetIRContext(), *GetTransformationContext(), component_ids, type_id,
407           is_irrelevant)) {
408     return existing_constant;
409   }
410   uint32_t result = GetFuzzerContext()->GetFreshId();
411   ApplyTransformation(TransformationAddConstantComposite(
412       result, type_id, component_ids, is_irrelevant));
413   return result;
414 }
415 
FindOrCreateGlobalUndef(uint32_t type_id)416 uint32_t FuzzerPass::FindOrCreateGlobalUndef(uint32_t type_id) {
417   for (auto& inst : GetIRContext()->types_values()) {
418     if (inst.opcode() == SpvOpUndef && inst.type_id() == type_id) {
419       return inst.result_id();
420     }
421   }
422   auto result = GetFuzzerContext()->GetFreshId();
423   ApplyTransformation(TransformationAddGlobalUndef(result, type_id));
424   return result;
425 }
426 
FindOrCreateNullConstant(uint32_t type_id)427 uint32_t FuzzerPass::FindOrCreateNullConstant(uint32_t type_id) {
428   // Find existing declaration
429   opt::analysis::NullConstant null_constant(
430       GetIRContext()->get_type_mgr()->GetType(type_id));
431   auto existing_constant =
432       GetIRContext()->get_constant_mgr()->FindConstant(&null_constant);
433 
434   // Return if found
435   if (existing_constant) {
436     return GetIRContext()
437         ->get_constant_mgr()
438         ->GetDefiningInstruction(existing_constant)
439         ->result_id();
440   }
441 
442   // Create new if not found
443   auto result = GetFuzzerContext()->GetFreshId();
444   ApplyTransformation(TransformationAddConstantNull(result, type_id));
445   return result;
446 }
447 
448 std::pair<std::vector<uint32_t>, std::map<uint32_t, std::vector<uint32_t>>>
GetAvailableBasicTypesAndPointers(SpvStorageClass storage_class) const449 FuzzerPass::GetAvailableBasicTypesAndPointers(
450     SpvStorageClass storage_class) const {
451   // Records all of the basic types available in the module.
452   std::set<uint32_t> basic_types;
453 
454   // For each basic type, records all the associated pointer types that target
455   // the basic type and that have |storage_class| as their storage class.
456   std::map<uint32_t, std::vector<uint32_t>> basic_type_to_pointers;
457 
458   for (auto& inst : GetIRContext()->types_values()) {
459     // For each basic type that we come across, record type, and the fact that
460     // we cannot yet have seen any pointers that use the basic type as its
461     // pointee type.
462     //
463     // For pointer types with basic pointee types, associate the pointer type
464     // with the basic type.
465     switch (inst.opcode()) {
466       case SpvOpTypeBool:
467       case SpvOpTypeFloat:
468       case SpvOpTypeInt:
469       case SpvOpTypeMatrix:
470       case SpvOpTypeVector:
471         // These are all basic types.
472         basic_types.insert(inst.result_id());
473         basic_type_to_pointers.insert({inst.result_id(), {}});
474         break;
475       case SpvOpTypeArray:
476         // An array type is basic if its base type is basic.
477         if (basic_types.count(inst.GetSingleWordInOperand(0))) {
478           basic_types.insert(inst.result_id());
479           basic_type_to_pointers.insert({inst.result_id(), {}});
480         }
481         break;
482       case SpvOpTypeStruct: {
483         // A struct type is basic if it does not have the Block/BufferBlock
484         // decoration, and if all of its members are basic.
485         if (!fuzzerutil::HasBlockOrBufferBlockDecoration(GetIRContext(),
486                                                          inst.result_id())) {
487           bool all_members_are_basic_types = true;
488           for (uint32_t i = 0; i < inst.NumInOperands(); i++) {
489             if (!basic_types.count(inst.GetSingleWordInOperand(i))) {
490               all_members_are_basic_types = false;
491               break;
492             }
493           }
494           if (all_members_are_basic_types) {
495             basic_types.insert(inst.result_id());
496             basic_type_to_pointers.insert({inst.result_id(), {}});
497           }
498         }
499         break;
500       }
501       case SpvOpTypePointer: {
502         // We are interested in the pointer if its pointee type is basic and it
503         // has the right storage class.
504         auto pointee_type = inst.GetSingleWordInOperand(1);
505         if (inst.GetSingleWordInOperand(0) == storage_class &&
506             basic_types.count(pointee_type)) {
507           // The pointer has the desired storage class, and its pointee type is
508           // a basic type, so we are interested in it.  Associate it with its
509           // basic type.
510           basic_type_to_pointers.at(pointee_type).push_back(inst.result_id());
511         }
512         break;
513       }
514       default:
515         break;
516     }
517   }
518   return {{basic_types.begin(), basic_types.end()}, basic_type_to_pointers};
519 }
520 
FindOrCreateZeroConstant(uint32_t scalar_or_composite_type_id,bool is_irrelevant)521 uint32_t FuzzerPass::FindOrCreateZeroConstant(
522     uint32_t scalar_or_composite_type_id, bool is_irrelevant) {
523   auto type_instruction =
524       GetIRContext()->get_def_use_mgr()->GetDef(scalar_or_composite_type_id);
525   assert(type_instruction && "The type instruction must exist.");
526   switch (type_instruction->opcode()) {
527     case SpvOpTypeBool:
528       return FindOrCreateBoolConstant(false, is_irrelevant);
529     case SpvOpTypeFloat: {
530       auto width = type_instruction->GetSingleWordInOperand(0);
531       auto num_words = (width + 32 - 1) / 32;
532       return FindOrCreateFloatConstant(std::vector<uint32_t>(num_words, 0),
533                                        width, is_irrelevant);
534     }
535     case SpvOpTypeInt: {
536       auto width = type_instruction->GetSingleWordInOperand(0);
537       auto num_words = (width + 32 - 1) / 32;
538       return FindOrCreateIntegerConstant(
539           std::vector<uint32_t>(num_words, 0), width,
540           type_instruction->GetSingleWordInOperand(1), is_irrelevant);
541     }
542     case SpvOpTypeArray: {
543       auto component_type_id = type_instruction->GetSingleWordInOperand(0);
544       auto num_components =
545           fuzzerutil::GetArraySize(*type_instruction, GetIRContext());
546       return FindOrCreateCompositeConstant(
547           std::vector<uint32_t>(
548               num_components,
549               FindOrCreateZeroConstant(component_type_id, is_irrelevant)),
550           scalar_or_composite_type_id, is_irrelevant);
551     }
552     case SpvOpTypeMatrix:
553     case SpvOpTypeVector: {
554       auto component_type_id = type_instruction->GetSingleWordInOperand(0);
555       auto num_components = type_instruction->GetSingleWordInOperand(1);
556       return FindOrCreateCompositeConstant(
557           std::vector<uint32_t>(
558               num_components,
559               FindOrCreateZeroConstant(component_type_id, is_irrelevant)),
560           scalar_or_composite_type_id, is_irrelevant);
561     }
562     case SpvOpTypeStruct: {
563       assert(!fuzzerutil::HasBlockOrBufferBlockDecoration(
564                  GetIRContext(), scalar_or_composite_type_id) &&
565              "We do not construct constants of struct types decorated with "
566              "Block or BufferBlock.");
567       std::vector<uint32_t> field_zero_ids;
568       for (uint32_t index = 0; index < type_instruction->NumInOperands();
569            index++) {
570         field_zero_ids.push_back(FindOrCreateZeroConstant(
571             type_instruction->GetSingleWordInOperand(index), is_irrelevant));
572       }
573       return FindOrCreateCompositeConstant(
574           field_zero_ids, scalar_or_composite_type_id, is_irrelevant);
575     }
576     default:
577       assert(false && "Unknown type.");
578       return 0;
579   }
580 }
581 
MaybeAddUseToReplace(opt::Instruction * use_inst,uint32_t use_index,uint32_t replacement_id,std::vector<std::pair<protobufs::IdUseDescriptor,uint32_t>> * uses_to_replace)582 void FuzzerPass::MaybeAddUseToReplace(
583     opt::Instruction* use_inst, uint32_t use_index, uint32_t replacement_id,
584     std::vector<std::pair<protobufs::IdUseDescriptor, uint32_t>>*
585         uses_to_replace) {
586   // Only consider this use if it is in a block
587   if (!GetIRContext()->get_instr_block(use_inst)) {
588     return;
589   }
590 
591   // Get the index of the operand restricted to input operands.
592   uint32_t in_operand_index =
593       fuzzerutil::InOperandIndexFromOperandIndex(*use_inst, use_index);
594   auto id_use_descriptor =
595       MakeIdUseDescriptorFromUse(GetIRContext(), use_inst, in_operand_index);
596   uses_to_replace->emplace_back(
597       std::make_pair(id_use_descriptor, replacement_id));
598 }
599 
GetOrCreateSimpleLoopPreheader(uint32_t header_id)600 opt::BasicBlock* FuzzerPass::GetOrCreateSimpleLoopPreheader(
601     uint32_t header_id) {
602   auto header_block = fuzzerutil::MaybeFindBlock(GetIRContext(), header_id);
603 
604   assert(header_block && header_block->IsLoopHeader() &&
605          "|header_id| should be the label id of a loop header");
606 
607   auto predecessors = GetIRContext()->cfg()->preds(header_id);
608 
609   assert(predecessors.size() >= 2 &&
610          "The block |header_id| should be reachable.");
611 
612   auto function = header_block->GetParent();
613 
614   if (predecessors.size() == 2) {
615     // The header has a single out-of-loop predecessor, which could be a
616     // preheader.
617 
618     opt::BasicBlock* maybe_preheader;
619 
620     if (GetIRContext()->GetDominatorAnalysis(function)->Dominates(
621             header_id, predecessors[0])) {
622       // The first predecessor is the back-edge block, because the header
623       // dominates it, so the second one is out of the loop.
624       maybe_preheader = &*function->FindBlock(predecessors[1]);
625     } else {
626       // The first predecessor is out of the loop.
627       maybe_preheader = &*function->FindBlock(predecessors[0]);
628     }
629 
630     // |maybe_preheader| is a preheader if it branches unconditionally to
631     // the header. We also require it not to be a loop header.
632     if (maybe_preheader->terminator()->opcode() == SpvOpBranch &&
633         !maybe_preheader->IsLoopHeader()) {
634       return maybe_preheader;
635     }
636   }
637 
638   // We need to add a preheader.
639 
640   // Get a fresh id for the preheader.
641   uint32_t preheader_id = GetFuzzerContext()->GetFreshId();
642 
643   // Get a fresh id for each OpPhi instruction, if there is more than one
644   // out-of-loop predecessor.
645   std::vector<uint32_t> phi_ids;
646   if (predecessors.size() > 2) {
647     header_block->ForEachPhiInst(
648         [this, &phi_ids](opt::Instruction* /* unused */) {
649           phi_ids.push_back(GetFuzzerContext()->GetFreshId());
650         });
651   }
652 
653   // Add the preheader.
654   ApplyTransformation(
655       TransformationAddLoopPreheader(header_id, preheader_id, phi_ids));
656 
657   // Make the newly-created preheader the new entry block.
658   return &*function->FindBlock(preheader_id);
659 }
660 
SplitBlockAfterOpPhiOrOpVariable(uint32_t block_id)661 opt::BasicBlock* FuzzerPass::SplitBlockAfterOpPhiOrOpVariable(
662     uint32_t block_id) {
663   auto block = fuzzerutil::MaybeFindBlock(GetIRContext(), block_id);
664   assert(block && "|block_id| must be a block label");
665   assert(!block->IsLoopHeader() && "|block_id| cannot be a loop header");
666 
667   // Find the first non-OpPhi and non-OpVariable instruction.
668   auto non_phi_or_var_inst = &*block->begin();
669   while (non_phi_or_var_inst->opcode() == SpvOpPhi ||
670          non_phi_or_var_inst->opcode() == SpvOpVariable) {
671     non_phi_or_var_inst = non_phi_or_var_inst->NextNode();
672   }
673 
674   // Split the block.
675   uint32_t new_block_id = GetFuzzerContext()->GetFreshId();
676   ApplyTransformation(TransformationSplitBlock(
677       MakeInstructionDescriptor(GetIRContext(), non_phi_or_var_inst),
678       new_block_id));
679 
680   // We need to return the newly-created block.
681   return &*block->GetParent()->FindBlock(new_block_id);
682 }
683 
FindOrCreateLocalVariable(uint32_t pointer_type_id,uint32_t function_id,bool pointee_value_is_irrelevant)684 uint32_t FuzzerPass::FindOrCreateLocalVariable(
685     uint32_t pointer_type_id, uint32_t function_id,
686     bool pointee_value_is_irrelevant) {
687   auto pointer_type = GetIRContext()->get_type_mgr()->GetType(pointer_type_id);
688   // No unused variables in release mode.
689   (void)pointer_type;
690   assert(pointer_type && pointer_type->AsPointer() &&
691          pointer_type->AsPointer()->storage_class() ==
692              SpvStorageClassFunction &&
693          "The pointer_type_id must refer to a defined pointer type with "
694          "storage class Function");
695   auto function = fuzzerutil::FindFunction(GetIRContext(), function_id);
696   assert(function && "The function must be defined.");
697 
698   // First we try to find a suitable existing variable.
699   // All of the local variable declarations are located in the first block.
700   for (auto& instruction : *function->begin()) {
701     if (instruction.opcode() != SpvOpVariable) {
702       continue;
703     }
704     // The existing OpVariable must have type |pointer_type_id|.
705     if (instruction.type_id() != pointer_type_id) {
706       continue;
707     }
708     // Check if the found variable is marked with PointeeValueIsIrrelevant
709     // according to |pointee_value_is_irrelevant|.
710     if (GetTransformationContext()->GetFactManager()->PointeeValueIsIrrelevant(
711             instruction.result_id()) != pointee_value_is_irrelevant) {
712       continue;
713     }
714     return instruction.result_id();
715   }
716 
717   // No such variable was found. Apply a transformation to get one.
718   uint32_t pointee_type_id = fuzzerutil::GetPointeeTypeIdFromPointerType(
719       GetIRContext(), pointer_type_id);
720   uint32_t result_id = GetFuzzerContext()->GetFreshId();
721   ApplyTransformation(TransformationAddLocalVariable(
722       result_id, pointer_type_id, function_id,
723       FindOrCreateZeroConstant(pointee_type_id, pointee_value_is_irrelevant),
724       pointee_value_is_irrelevant));
725   return result_id;
726 }
727 
FindOrCreateGlobalVariable(uint32_t pointer_type_id,bool pointee_value_is_irrelevant)728 uint32_t FuzzerPass::FindOrCreateGlobalVariable(
729     uint32_t pointer_type_id, bool pointee_value_is_irrelevant) {
730   auto pointer_type = GetIRContext()->get_type_mgr()->GetType(pointer_type_id);
731   // No unused variables in release mode.
732   (void)pointer_type;
733   assert(
734       pointer_type && pointer_type->AsPointer() &&
735       (pointer_type->AsPointer()->storage_class() == SpvStorageClassPrivate ||
736        pointer_type->AsPointer()->storage_class() ==
737            SpvStorageClassWorkgroup) &&
738       "The pointer_type_id must refer to a defined pointer type with storage "
739       "class Private or Workgroup");
740 
741   // First we try to find a suitable existing variable.
742   for (auto& instruction : GetIRContext()->module()->types_values()) {
743     if (instruction.opcode() != SpvOpVariable) {
744       continue;
745     }
746     // The existing OpVariable must have type |pointer_type_id|.
747     if (instruction.type_id() != pointer_type_id) {
748       continue;
749     }
750     // Check if the found variable is marked with PointeeValueIsIrrelevant
751     // according to |pointee_value_is_irrelevant|.
752     if (GetTransformationContext()->GetFactManager()->PointeeValueIsIrrelevant(
753             instruction.result_id()) != pointee_value_is_irrelevant) {
754       continue;
755     }
756     return instruction.result_id();
757   }
758 
759   // No such variable was found. Apply a transformation to get one.
760   uint32_t pointee_type_id = fuzzerutil::GetPointeeTypeIdFromPointerType(
761       GetIRContext(), pointer_type_id);
762   auto storage_class = fuzzerutil::GetStorageClassFromPointerType(
763       GetIRContext(), pointer_type_id);
764   uint32_t result_id = GetFuzzerContext()->GetFreshId();
765 
766   // A variable with storage class Workgroup shouldn't have an initializer.
767   if (storage_class == SpvStorageClassWorkgroup) {
768     ApplyTransformation(TransformationAddGlobalVariable(
769         result_id, pointer_type_id, SpvStorageClassWorkgroup, 0,
770         pointee_value_is_irrelevant));
771   } else {
772     ApplyTransformation(TransformationAddGlobalVariable(
773         result_id, pointer_type_id, SpvStorageClassPrivate,
774         FindOrCreateZeroConstant(pointee_type_id, pointee_value_is_irrelevant),
775         pointee_value_is_irrelevant));
776   }
777   return result_id;
778 }
779 
780 }  // namespace fuzz
781 }  // namespace spvtools
782