transformation_replace_params_with_struct.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. const protobufs::TransformationReplaceParamsWithStruct& message)
  21. : message_(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. const auto* type = ir_context->get_type_mgr()->GetType(
  72. fuzzerutil::GetTypeId(ir_context, id));
  73. assert(type && "Parameter has invalid type");
  74. if (!IsParameterTypeSupported(*type)) {
  75. return false;
  76. }
  77. }
  78. // We already know that the function has at least |parameter_id.size()|
  79. // parameters.
  80. // Check that a relevant OpTypeStruct exists in the module.
  81. if (!MaybeGetRequiredStructType(ir_context)) {
  82. return false;
  83. }
  84. auto caller_id_to_fresh_composite_id = fuzzerutil::RepeatedUInt32PairToMap(
  85. message_.caller_id_to_fresh_composite_id());
  86. // Check that |callee_id_to_fresh_composite_id| is valid.
  87. for (const auto* inst :
  88. fuzzerutil::GetCallers(ir_context, function->result_id())) {
  89. // Check that the callee is present in the map. It's ok if the map contains
  90. // more ids that there are callees (those ids will not be used).
  91. if (!caller_id_to_fresh_composite_id.count(inst->result_id())) {
  92. return false;
  93. }
  94. }
  95. // Check that all fresh ids are unique and fresh.
  96. std::vector<uint32_t> fresh_ids = {message_.fresh_function_type_id(),
  97. message_.fresh_parameter_id()};
  98. for (const auto& entry : caller_id_to_fresh_composite_id) {
  99. fresh_ids.push_back(entry.second);
  100. }
  101. return !fuzzerutil::HasDuplicates(fresh_ids) &&
  102. std::all_of(fresh_ids.begin(), fresh_ids.end(),
  103. [ir_context](uint32_t id) {
  104. return fuzzerutil::IsFreshId(ir_context, id);
  105. });
  106. }
  107. void TransformationReplaceParamsWithStruct::Apply(
  108. opt::IRContext* ir_context, TransformationContext* /*unused*/) const {
  109. auto* function = fuzzerutil::GetFunctionFromParameterId(
  110. ir_context, message_.parameter_id(0));
  111. assert(function &&
  112. "All parameters' ids should've been checked in the IsApplicable");
  113. // Get a type id of the OpTypeStruct used as a type id of the new parameter.
  114. auto struct_type_id = MaybeGetRequiredStructType(ir_context);
  115. assert(struct_type_id &&
  116. "IsApplicable should've guaranteed that this value isn't equal to 0");
  117. // Add new parameter to the function.
  118. function->AddParameter(MakeUnique<opt::Instruction>(
  119. ir_context, SpvOpFunctionParameter, struct_type_id,
  120. message_.fresh_parameter_id(), opt::Instruction::OperandList()));
  121. fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_parameter_id());
  122. // Compute indices of replaced parameters. This will be used to adjust
  123. // OpFunctionCall instructions and create OpCompositeConstruct instructions at
  124. // every call site.
  125. std::vector<uint32_t> indices_of_replaced_params;
  126. {
  127. // We want to destroy |params| after the loop because it will contain
  128. // dangling pointers when we remove parameters from the function.
  129. auto params = fuzzerutil::GetParameters(ir_context, function->result_id());
  130. for (auto id : message_.parameter_id()) {
  131. auto it = std::find_if(params.begin(), params.end(),
  132. [id](const opt::Instruction* param) {
  133. return param->result_id() == id;
  134. });
  135. assert(it != params.end() && "Parameter's id is invalid");
  136. indices_of_replaced_params.push_back(
  137. static_cast<uint32_t>(it - params.begin()));
  138. }
  139. }
  140. auto caller_id_to_fresh_composite_id = fuzzerutil::RepeatedUInt32PairToMap(
  141. message_.caller_id_to_fresh_composite_id());
  142. // Update all function calls.
  143. for (auto* inst : fuzzerutil::GetCallers(ir_context, function->result_id())) {
  144. // Create a list of operands for the OpCompositeConstruct instruction.
  145. opt::Instruction::OperandList composite_components;
  146. for (auto index : indices_of_replaced_params) {
  147. // +1 since the first in operand to OpFunctionCall is the result id of
  148. // the function.
  149. composite_components.emplace_back(
  150. std::move(inst->GetInOperand(index + 1)));
  151. }
  152. // Remove arguments from the function call. We do it in a separate loop
  153. // and in reverse order to make sure we have removed correct operands.
  154. for (auto it = indices_of_replaced_params.rbegin();
  155. it != indices_of_replaced_params.rend(); ++it) {
  156. // +1 since the first in operand to OpFunctionCall is the result id of
  157. // the function.
  158. inst->RemoveInOperand(*it + 1);
  159. }
  160. // Insert OpCompositeConstruct before the function call.
  161. auto fresh_composite_id =
  162. caller_id_to_fresh_composite_id.at(inst->result_id());
  163. inst->InsertBefore(MakeUnique<opt::Instruction>(
  164. ir_context, SpvOpCompositeConstruct, struct_type_id, fresh_composite_id,
  165. std::move(composite_components)));
  166. // Add a new operand to the OpFunctionCall instruction.
  167. inst->AddOperand({SPV_OPERAND_TYPE_ID, {fresh_composite_id}});
  168. fuzzerutil::UpdateModuleIdBound(ir_context, fresh_composite_id);
  169. }
  170. // Insert OpCompositeExtract instructions into the entry point block of the
  171. // function and remove replaced parameters.
  172. for (int i = 0; i < message_.parameter_id_size(); ++i) {
  173. const auto* param_inst =
  174. ir_context->get_def_use_mgr()->GetDef(message_.parameter_id(i));
  175. assert(param_inst && "Parameter id is invalid");
  176. // Skip all OpVariable instructions.
  177. auto iter = function->begin()->begin();
  178. while (iter != function->begin()->end() &&
  179. !fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpCompositeExtract,
  180. iter)) {
  181. ++iter;
  182. }
  183. assert(fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpCompositeExtract,
  184. iter) &&
  185. "Can't extract parameter's value from the structure");
  186. // Insert OpCompositeExtract instructions to unpack parameters' values from
  187. // the struct type.
  188. iter.InsertBefore(MakeUnique<opt::Instruction>(
  189. ir_context, SpvOpCompositeExtract, param_inst->type_id(),
  190. param_inst->result_id(),
  191. opt::Instruction::OperandList{
  192. {SPV_OPERAND_TYPE_ID, {message_.fresh_parameter_id()}},
  193. {SPV_OPERAND_TYPE_LITERAL_INTEGER, {static_cast<uint32_t>(i)}}}));
  194. fuzzerutil::RemoveParameter(ir_context, param_inst->result_id());
  195. }
  196. // Update function's type.
  197. {
  198. // We use a separate scope here since |old_function_type| might become a
  199. // dangling pointer after the call to the fuzzerutil::UpdateFunctionType.
  200. auto* old_function_type = fuzzerutil::GetFunctionType(ir_context, function);
  201. assert(old_function_type && "Function has invalid type");
  202. // +1 since the first in operand to OpTypeFunction is the result type id
  203. // of the function.
  204. std::vector<uint32_t> parameter_type_ids;
  205. for (uint32_t i = 1; i < old_function_type->NumInOperands(); ++i) {
  206. if (std::find(indices_of_replaced_params.begin(),
  207. indices_of_replaced_params.end(),
  208. i - 1) == indices_of_replaced_params.end()) {
  209. parameter_type_ids.push_back(
  210. old_function_type->GetSingleWordInOperand(i));
  211. }
  212. }
  213. parameter_type_ids.push_back(struct_type_id);
  214. fuzzerutil::UpdateFunctionType(
  215. ir_context, function->result_id(), message_.fresh_function_type_id(),
  216. old_function_type->GetSingleWordInOperand(0), parameter_type_ids);
  217. }
  218. // Make sure our changes are analyzed
  219. ir_context->InvalidateAnalysesExceptFor(
  220. opt::IRContext::Analysis::kAnalysisNone);
  221. }
  222. protobufs::Transformation TransformationReplaceParamsWithStruct::ToMessage()
  223. const {
  224. protobufs::Transformation result;
  225. *result.mutable_replace_params_with_struct() = message_;
  226. return result;
  227. }
  228. bool TransformationReplaceParamsWithStruct::IsParameterTypeSupported(
  229. const opt::analysis::Type& param_type) {
  230. // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3403):
  231. // Consider adding support for more types of parameters.
  232. switch (param_type.kind()) {
  233. case opt::analysis::Type::kBool:
  234. case opt::analysis::Type::kInteger:
  235. case opt::analysis::Type::kFloat:
  236. case opt::analysis::Type::kArray:
  237. case opt::analysis::Type::kVector:
  238. case opt::analysis::Type::kMatrix:
  239. return true;
  240. case opt::analysis::Type::kStruct:
  241. return std::all_of(param_type.AsStruct()->element_types().begin(),
  242. param_type.AsStruct()->element_types().end(),
  243. [](const opt::analysis::Type* type) {
  244. return IsParameterTypeSupported(*type);
  245. });
  246. default:
  247. return false;
  248. }
  249. }
  250. uint32_t TransformationReplaceParamsWithStruct::MaybeGetRequiredStructType(
  251. opt::IRContext* ir_context) const {
  252. std::vector<uint32_t> component_type_ids;
  253. for (auto id : message_.parameter_id()) {
  254. component_type_ids.push_back(fuzzerutil::GetTypeId(ir_context, id));
  255. }
  256. return fuzzerutil::MaybeGetStructType(ir_context, component_type_ids);
  257. }
  258. } // namespace fuzz
  259. } // namespace spvtools