transformation_replace_params_with_struct.cpp 12 KB

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