• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2020 André Perez Maselco
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_push_ids_through_variables.h"
16 
17 #include "source/fuzz/fuzzer_util.h"
18 #include "source/fuzz/instruction_descriptor.h"
19 #include "source/fuzz/transformation_push_id_through_variable.h"
20 
21 namespace spvtools {
22 namespace fuzz {
23 
FuzzerPassPushIdsThroughVariables(opt::IRContext * ir_context,TransformationContext * transformation_context,FuzzerContext * fuzzer_context,protobufs::TransformationSequence * transformations)24 FuzzerPassPushIdsThroughVariables::FuzzerPassPushIdsThroughVariables(
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 
Apply()31 void FuzzerPassPushIdsThroughVariables::Apply() {
32   ForEachInstructionWithInstructionDescriptor(
33       [this](opt::Function* function, opt::BasicBlock* block,
34              opt::BasicBlock::iterator instruction_iterator,
35              const protobufs::InstructionDescriptor& instruction_descriptor)
36           -> void {
37         assert(instruction_iterator->opcode() ==
38                    instruction_descriptor.target_instruction_opcode() &&
39                "The opcode of the instruction we might insert before must be "
40                "the same as the opcode in the descriptor for the instruction");
41 
42         // Randomly decide whether to try pushing an id through a variable.
43         if (!GetFuzzerContext()->ChoosePercentage(
44                 GetFuzzerContext()->GetChanceOfPushingIdThroughVariable())) {
45           return;
46         }
47 
48         // The block containing the instruction we are going to insert before
49         // must be reachable.
50         if (!fuzzerutil::BlockIsReachableInItsFunction(GetIRContext(), block)) {
51           return;
52         }
53 
54         // It must be valid to insert OpStore and OpLoad instructions
55         // before the instruction to insert before.
56         if (!fuzzerutil::CanInsertOpcodeBeforeInstruction(
57                 SpvOpStore, instruction_iterator) ||
58             !fuzzerutil::CanInsertOpcodeBeforeInstruction(
59                 SpvOpLoad, instruction_iterator)) {
60           return;
61         }
62 
63         // Randomly decides whether a global or local variable will be added.
64         auto variable_storage_class = GetFuzzerContext()->ChooseEven()
65                                           ? SpvStorageClassPrivate
66                                           : SpvStorageClassFunction;
67 
68         // Gets the available basic and pointer types.
69         auto basic_type_ids_and_pointers =
70             GetAvailableBasicTypesAndPointers(variable_storage_class);
71         auto& basic_types = basic_type_ids_and_pointers.first;
72         uint32_t basic_type_id =
73             basic_types[GetFuzzerContext()->RandomIndex(basic_types)];
74 
75         // Looks for ids that we might wish to consider pushing through a
76         // variable.
77         std::vector<opt::Instruction*> value_instructions =
78             FindAvailableInstructions(
79                 function, block, instruction_iterator,
80                 [this, basic_type_id, instruction_descriptor](
81                     opt::IRContext* ir_context,
82                     opt::Instruction* instruction) -> bool {
83                   if (!instruction->result_id() || !instruction->type_id()) {
84                     return false;
85                   }
86 
87                   if (instruction->type_id() != basic_type_id) {
88                     return false;
89                   }
90 
91                   // If the id is irrelevant, we can use it since it will not
92                   // participate in DataSynonym fact. Otherwise, we should be
93                   // able to produce a synonym out of the id.
94                   if (!GetTransformationContext()
95                            ->GetFactManager()
96                            ->IdIsIrrelevant(instruction->result_id()) &&
97                       !fuzzerutil::CanMakeSynonymOf(ir_context,
98                                                     *GetTransformationContext(),
99                                                     instruction)) {
100                     return false;
101                   }
102 
103                   return fuzzerutil::IdIsAvailableBeforeInstruction(
104                       ir_context,
105                       FindInstruction(instruction_descriptor, ir_context),
106                       instruction->result_id());
107                 });
108 
109         if (value_instructions.empty()) {
110           return;
111         }
112 
113         // If the pointer type does not exist, then create it.
114         FindOrCreatePointerType(basic_type_id, variable_storage_class);
115 
116         // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3403):
117         //  type support here is limited by the FindOrCreateZeroConstant
118         //  function.
119         const auto* type_inst =
120             GetIRContext()->get_def_use_mgr()->GetDef(basic_type_id);
121         assert(type_inst);
122         switch (type_inst->opcode()) {
123           case SpvOpTypeBool:
124           case SpvOpTypeFloat:
125           case SpvOpTypeInt:
126           case SpvOpTypeArray:
127           case SpvOpTypeMatrix:
128           case SpvOpTypeVector:
129           case SpvOpTypeStruct:
130             break;
131           default:
132             return;
133         }
134 
135         // Create a constant to initialize the variable from. This might update
136         // module's id bound so it must be done before any fresh ids are
137         // computed.
138         auto initializer_id = FindOrCreateZeroConstant(basic_type_id, false);
139 
140         // Applies the push id through variable transformation.
141         ApplyTransformation(TransformationPushIdThroughVariable(
142             value_instructions[GetFuzzerContext()->RandomIndex(
143                                    value_instructions)]
144                 ->result_id(),
145             GetFuzzerContext()->GetFreshId(), GetFuzzerContext()->GetFreshId(),
146             variable_storage_class, initializer_id, instruction_descriptor));
147       });
148 }
149 
150 }  // namespace fuzz
151 }  // namespace spvtools
152