• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2020 Vasyl Teliman
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/transformation_replace_params_with_struct.h"
16 
17 #include <vector>
18 
19 #include "source/fuzz/fuzzer_util.h"
20 
21 namespace spvtools {
22 namespace fuzz {
23 
TransformationReplaceParamsWithStruct(protobufs::TransformationReplaceParamsWithStruct message)24 TransformationReplaceParamsWithStruct::TransformationReplaceParamsWithStruct(
25     protobufs::TransformationReplaceParamsWithStruct message)
26     : message_(std::move(message)) {}
27 
TransformationReplaceParamsWithStruct(const std::vector<uint32_t> & parameter_id,uint32_t fresh_function_type_id,uint32_t fresh_parameter_id,const std::map<uint32_t,uint32_t> & caller_id_to_fresh_composite_id)28 TransformationReplaceParamsWithStruct::TransformationReplaceParamsWithStruct(
29     const std::vector<uint32_t>& parameter_id, uint32_t fresh_function_type_id,
30     uint32_t fresh_parameter_id,
31     const std::map<uint32_t, uint32_t>& caller_id_to_fresh_composite_id) {
32   message_.set_fresh_function_type_id(fresh_function_type_id);
33   message_.set_fresh_parameter_id(fresh_parameter_id);
34 
35   for (auto id : parameter_id) {
36     message_.add_parameter_id(id);
37   }
38 
39   *message_.mutable_caller_id_to_fresh_composite_id() =
40       fuzzerutil::MapToRepeatedUInt32Pair(caller_id_to_fresh_composite_id);
41 }
42 
IsApplicable(opt::IRContext * ir_context,const TransformationContext &) const43 bool TransformationReplaceParamsWithStruct::IsApplicable(
44     opt::IRContext* ir_context, const TransformationContext& /*unused*/) const {
45   std::vector<uint32_t> parameter_id(message_.parameter_id().begin(),
46                                      message_.parameter_id().end());
47 
48   // Check that |parameter_id| is neither empty nor it has duplicates.
49   if (parameter_id.empty() || fuzzerutil::HasDuplicates(parameter_id)) {
50     return false;
51   }
52 
53   // All ids must correspond to valid parameters of the same function.
54   // The function can't be an entry-point function.
55 
56   // fuzzerutil::GetFunctionFromParameterId requires a valid id.
57   if (!ir_context->get_def_use_mgr()->GetDef(parameter_id[0])) {
58     return false;
59   }
60 
61   const auto* function =
62       fuzzerutil::GetFunctionFromParameterId(ir_context, parameter_id[0]);
63   if (!function ||
64       fuzzerutil::FunctionIsEntryPoint(ir_context, function->result_id())) {
65     return false;
66   }
67 
68   // Compute all ids of the function's parameters.
69   std::unordered_set<uint32_t> all_parameter_ids;
70   for (const auto* param :
71        fuzzerutil::GetParameters(ir_context, function->result_id())) {
72     all_parameter_ids.insert(param->result_id());
73   }
74 
75   // Check that all elements in |parameter_id| are valid.
76   for (auto id : parameter_id) {
77     // fuzzerutil::GetFunctionFromParameterId requires a valid id.
78     if (!ir_context->get_def_use_mgr()->GetDef(id)) {
79       return false;
80     }
81 
82     // Check that |id| is a result id of one of the |function|'s parameters.
83     if (!all_parameter_ids.count(id)) {
84       return false;
85     }
86 
87     // Check that the parameter with result id |id| has supported type.
88     if (!IsParameterTypeSupported(ir_context,
89                                   fuzzerutil::GetTypeId(ir_context, id))) {
90       return false;
91     }
92   }
93 
94   // We already know that the function has at least |parameter_id.size()|
95   // parameters.
96 
97   // Check that a relevant OpTypeStruct exists in the module.
98   if (!MaybeGetRequiredStructType(ir_context)) {
99     return false;
100   }
101 
102   const auto caller_id_to_fresh_composite_id =
103       fuzzerutil::RepeatedUInt32PairToMap(
104           message_.caller_id_to_fresh_composite_id());
105 
106   // Check that |callee_id_to_fresh_composite_id| is valid.
107   for (const auto* inst :
108        fuzzerutil::GetCallers(ir_context, function->result_id())) {
109     // Check that the callee is present in the map. It's ok if the map contains
110     // more ids that there are callees (those ids will not be used).
111     if (!caller_id_to_fresh_composite_id.count(inst->result_id())) {
112       return false;
113     }
114   }
115 
116   // Check that all fresh ids are unique and fresh.
117   std::vector<uint32_t> fresh_ids = {message_.fresh_function_type_id(),
118                                      message_.fresh_parameter_id()};
119 
120   for (const auto& entry : caller_id_to_fresh_composite_id) {
121     fresh_ids.push_back(entry.second);
122   }
123 
124   return !fuzzerutil::HasDuplicates(fresh_ids) &&
125          std::all_of(fresh_ids.begin(), fresh_ids.end(),
126                      [ir_context](uint32_t id) {
127                        return fuzzerutil::IsFreshId(ir_context, id);
128                      });
129 }
130 
Apply(opt::IRContext * ir_context,TransformationContext *) const131 void TransformationReplaceParamsWithStruct::Apply(
132     opt::IRContext* ir_context, TransformationContext* /*unused*/) const {
133   auto* function = fuzzerutil::GetFunctionFromParameterId(
134       ir_context, message_.parameter_id(0));
135   assert(function &&
136          "All parameters' ids should've been checked in the IsApplicable");
137 
138   // Get a type id of the OpTypeStruct used as a type id of the new parameter.
139   auto struct_type_id = MaybeGetRequiredStructType(ir_context);
140   assert(struct_type_id &&
141          "IsApplicable should've guaranteed that this value isn't equal to 0");
142 
143   // Add new parameter to the function.
144   function->AddParameter(MakeUnique<opt::Instruction>(
145       ir_context, SpvOpFunctionParameter, struct_type_id,
146       message_.fresh_parameter_id(), opt::Instruction::OperandList()));
147 
148   fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_parameter_id());
149 
150   // Compute indices of replaced parameters. This will be used to adjust
151   // OpFunctionCall instructions and create OpCompositeConstruct instructions at
152   // every call site.
153   const auto indices_of_replaced_params =
154       ComputeIndicesOfReplacedParameters(ir_context);
155 
156   const auto caller_id_to_fresh_composite_id =
157       fuzzerutil::RepeatedUInt32PairToMap(
158           message_.caller_id_to_fresh_composite_id());
159 
160   // Update all function calls.
161   for (auto* inst : fuzzerutil::GetCallers(ir_context, function->result_id())) {
162     // Create a list of operands for the OpCompositeConstruct instruction.
163     opt::Instruction::OperandList composite_components;
164     for (auto index : indices_of_replaced_params) {
165       // +1 since the first in operand to OpFunctionCall is the result id of
166       // the function.
167       composite_components.emplace_back(
168           std::move(inst->GetInOperand(index + 1)));
169     }
170 
171     // Remove arguments from the function call. We do it in a separate loop
172     // and in decreasing order to make sure we have removed correct operands.
173     for (auto index : std::set<uint32_t, std::greater<uint32_t>>(
174              indices_of_replaced_params.begin(),
175              indices_of_replaced_params.end())) {
176       // +1 since the first in operand to OpFunctionCall is the result id of
177       // the function.
178       inst->RemoveInOperand(index + 1);
179     }
180 
181     // Insert OpCompositeConstruct before the function call.
182     auto fresh_composite_id =
183         caller_id_to_fresh_composite_id.at(inst->result_id());
184     inst->InsertBefore(MakeUnique<opt::Instruction>(
185         ir_context, SpvOpCompositeConstruct, struct_type_id, fresh_composite_id,
186         std::move(composite_components)));
187 
188     // Add a new operand to the OpFunctionCall instruction.
189     inst->AddOperand({SPV_OPERAND_TYPE_ID, {fresh_composite_id}});
190     fuzzerutil::UpdateModuleIdBound(ir_context, fresh_composite_id);
191   }
192 
193   // Insert OpCompositeExtract instructions into the entry point block of the
194   // function and remove replaced parameters.
195   for (int i = 0; i < message_.parameter_id_size(); ++i) {
196     const auto* param_inst =
197         ir_context->get_def_use_mgr()->GetDef(message_.parameter_id(i));
198     assert(param_inst && "Parameter id is invalid");
199 
200     // Skip all OpVariable instructions.
201     auto iter = function->begin()->begin();
202     while (iter != function->begin()->end() &&
203            !fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpCompositeExtract,
204                                                          iter)) {
205       ++iter;
206     }
207 
208     assert(fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpCompositeExtract,
209                                                         iter) &&
210            "Can't extract parameter's value from the structure");
211 
212     // Insert OpCompositeExtract instructions to unpack parameters' values from
213     // the struct type.
214     iter.InsertBefore(MakeUnique<opt::Instruction>(
215         ir_context, SpvOpCompositeExtract, param_inst->type_id(),
216         param_inst->result_id(),
217         opt::Instruction::OperandList{
218             {SPV_OPERAND_TYPE_ID, {message_.fresh_parameter_id()}},
219             {SPV_OPERAND_TYPE_LITERAL_INTEGER, {static_cast<uint32_t>(i)}}}));
220 
221     fuzzerutil::RemoveParameter(ir_context, param_inst->result_id());
222   }
223 
224   // Update function's type.
225   {
226     // We use a separate scope here since |old_function_type| might become a
227     // dangling pointer after the call to the fuzzerutil::UpdateFunctionType.
228 
229     auto* old_function_type = fuzzerutil::GetFunctionType(ir_context, function);
230     assert(old_function_type && "Function has invalid type");
231 
232     // +1 since the first in operand to OpTypeFunction is the result type id
233     // of the function.
234     std::vector<uint32_t> parameter_type_ids;
235     for (uint32_t i = 1; i < old_function_type->NumInOperands(); ++i) {
236       if (std::find(indices_of_replaced_params.begin(),
237                     indices_of_replaced_params.end(),
238                     i - 1) == indices_of_replaced_params.end()) {
239         parameter_type_ids.push_back(
240             old_function_type->GetSingleWordInOperand(i));
241       }
242     }
243 
244     parameter_type_ids.push_back(struct_type_id);
245 
246     fuzzerutil::UpdateFunctionType(
247         ir_context, function->result_id(), message_.fresh_function_type_id(),
248         old_function_type->GetSingleWordInOperand(0), parameter_type_ids);
249   }
250 
251   // Make sure our changes are analyzed
252   ir_context->InvalidateAnalysesExceptFor(
253       opt::IRContext::Analysis::kAnalysisNone);
254 }
255 
ToMessage() const256 protobufs::Transformation TransformationReplaceParamsWithStruct::ToMessage()
257     const {
258   protobufs::Transformation result;
259   *result.mutable_replace_params_with_struct() = message_;
260   return result;
261 }
262 
IsParameterTypeSupported(opt::IRContext * ir_context,uint32_t param_type_id)263 bool TransformationReplaceParamsWithStruct::IsParameterTypeSupported(
264     opt::IRContext* ir_context, uint32_t param_type_id) {
265   // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3403):
266   //  Consider adding support for more types of parameters.
267   return fuzzerutil::CanCreateConstant(ir_context, param_type_id);
268 }
269 
MaybeGetRequiredStructType(opt::IRContext * ir_context) const270 uint32_t TransformationReplaceParamsWithStruct::MaybeGetRequiredStructType(
271     opt::IRContext* ir_context) const {
272   std::vector<uint32_t> component_type_ids;
273   for (auto id : message_.parameter_id()) {
274     component_type_ids.push_back(fuzzerutil::GetTypeId(ir_context, id));
275   }
276 
277   return fuzzerutil::MaybeGetStructType(ir_context, component_type_ids);
278 }
279 
280 std::vector<uint32_t>
ComputeIndicesOfReplacedParameters(opt::IRContext * ir_context) const281 TransformationReplaceParamsWithStruct::ComputeIndicesOfReplacedParameters(
282     opt::IRContext* ir_context) const {
283   assert(!message_.parameter_id().empty() &&
284          "There must be at least one parameter to replace");
285 
286   const auto* function = fuzzerutil::GetFunctionFromParameterId(
287       ir_context, message_.parameter_id(0));
288   assert(function && "|parameter_id|s are invalid");
289 
290   std::vector<uint32_t> result;
291 
292   auto params = fuzzerutil::GetParameters(ir_context, function->result_id());
293   for (auto id : message_.parameter_id()) {
294     auto it = std::find_if(params.begin(), params.end(),
295                            [id](const opt::Instruction* param) {
296                              return param->result_id() == id;
297                            });
298     assert(it != params.end() && "Parameter's id is invalid");
299     result.push_back(static_cast<uint32_t>(it - params.begin()));
300   }
301 
302   return result;
303 }
304 
305 std::unordered_set<uint32_t>
GetFreshIds() const306 TransformationReplaceParamsWithStruct::GetFreshIds() const {
307   std::unordered_set<uint32_t> result = {message_.fresh_function_type_id(),
308                                          message_.fresh_parameter_id()};
309   for (auto& pair : message_.caller_id_to_fresh_composite_id()) {
310     result.insert(pair.second());
311   }
312   return result;
313 }
314 
315 }  // namespace fuzz
316 }  // namespace spvtools
317