fuzzer_pass.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. #include "source/fuzz/fuzzer_pass.h"
  15. #include <set>
  16. #include "source/fuzz/fuzzer_util.h"
  17. #include "source/fuzz/instruction_descriptor.h"
  18. #include "source/fuzz/transformation_add_constant_boolean.h"
  19. #include "source/fuzz/transformation_add_constant_composite.h"
  20. #include "source/fuzz/transformation_add_constant_scalar.h"
  21. #include "source/fuzz/transformation_add_global_undef.h"
  22. #include "source/fuzz/transformation_add_type_boolean.h"
  23. #include "source/fuzz/transformation_add_type_float.h"
  24. #include "source/fuzz/transformation_add_type_function.h"
  25. #include "source/fuzz/transformation_add_type_int.h"
  26. #include "source/fuzz/transformation_add_type_matrix.h"
  27. #include "source/fuzz/transformation_add_type_pointer.h"
  28. #include "source/fuzz/transformation_add_type_vector.h"
  29. namespace spvtools {
  30. namespace fuzz {
  31. FuzzerPass::FuzzerPass(opt::IRContext* ir_context,
  32. TransformationContext* transformation_context,
  33. FuzzerContext* fuzzer_context,
  34. protobufs::TransformationSequence* transformations)
  35. : ir_context_(ir_context),
  36. transformation_context_(transformation_context),
  37. fuzzer_context_(fuzzer_context),
  38. transformations_(transformations) {}
  39. FuzzerPass::~FuzzerPass() = default;
  40. std::vector<opt::Instruction*> FuzzerPass::FindAvailableInstructions(
  41. opt::Function* function, opt::BasicBlock* block,
  42. const opt::BasicBlock::iterator& inst_it,
  43. std::function<bool(opt::IRContext*, opt::Instruction*)>
  44. instruction_is_relevant) const {
  45. // TODO(afd) The following is (relatively) simple, but may end up being
  46. // prohibitively inefficient, as it walks the whole dominator tree for
  47. // every instruction that is considered.
  48. std::vector<opt::Instruction*> result;
  49. // Consider all global declarations
  50. for (auto& global : GetIRContext()->module()->types_values()) {
  51. if (instruction_is_relevant(GetIRContext(), &global)) {
  52. result.push_back(&global);
  53. }
  54. }
  55. // Consider all function parameters
  56. function->ForEachParam(
  57. [this, &instruction_is_relevant, &result](opt::Instruction* param) {
  58. if (instruction_is_relevant(GetIRContext(), param)) {
  59. result.push_back(param);
  60. }
  61. });
  62. // Consider all previous instructions in this block
  63. for (auto prev_inst_it = block->begin(); prev_inst_it != inst_it;
  64. ++prev_inst_it) {
  65. if (instruction_is_relevant(GetIRContext(), &*prev_inst_it)) {
  66. result.push_back(&*prev_inst_it);
  67. }
  68. }
  69. // Walk the dominator tree to consider all instructions from dominating
  70. // blocks
  71. auto dominator_analysis = GetIRContext()->GetDominatorAnalysis(function);
  72. for (auto next_dominator = dominator_analysis->ImmediateDominator(block);
  73. next_dominator != nullptr;
  74. next_dominator =
  75. dominator_analysis->ImmediateDominator(next_dominator)) {
  76. for (auto& dominating_inst : *next_dominator) {
  77. if (instruction_is_relevant(GetIRContext(), &dominating_inst)) {
  78. result.push_back(&dominating_inst);
  79. }
  80. }
  81. }
  82. return result;
  83. }
  84. void FuzzerPass::ForEachInstructionWithInstructionDescriptor(
  85. std::function<
  86. void(opt::Function* function, opt::BasicBlock* block,
  87. opt::BasicBlock::iterator inst_it,
  88. const protobufs::InstructionDescriptor& instruction_descriptor)>
  89. action) {
  90. // Consider every block in every function.
  91. for (auto& function : *GetIRContext()->module()) {
  92. for (auto& block : function) {
  93. // We now consider every instruction in the block, randomly deciding
  94. // whether to apply a transformation before it.
  95. // In order for transformations to insert new instructions, they need to
  96. // be able to identify the instruction to insert before. We describe an
  97. // instruction via its opcode, 'opc', a base instruction 'base' that has a
  98. // result id, and the number of instructions with opcode 'opc' that we
  99. // should skip when searching from 'base' for the desired instruction.
  100. // (An instruction that has a result id is represented by its own opcode,
  101. // itself as 'base', and a skip-count of 0.)
  102. std::vector<std::tuple<uint32_t, SpvOp, uint32_t>>
  103. base_opcode_skip_triples;
  104. // The initial base instruction is the block label.
  105. uint32_t base = block.id();
  106. // Counts the number of times we have seen each opcode since we reset the
  107. // base instruction.
  108. std::map<SpvOp, uint32_t> skip_count;
  109. // Consider every instruction in the block. The label is excluded: it is
  110. // only necessary to consider it as a base in case the first instruction
  111. // in the block does not have a result id.
  112. for (auto inst_it = block.begin(); inst_it != block.end(); ++inst_it) {
  113. if (inst_it->HasResultId()) {
  114. // In the case that the instruction has a result id, we use the
  115. // instruction as its own base, and clear the skip counts we have
  116. // collected.
  117. base = inst_it->result_id();
  118. skip_count.clear();
  119. }
  120. const SpvOp opcode = inst_it->opcode();
  121. // Invoke the provided function, which might apply a transformation.
  122. action(&function, &block, inst_it,
  123. MakeInstructionDescriptor(
  124. base, opcode,
  125. skip_count.count(opcode) ? skip_count.at(opcode) : 0));
  126. if (!inst_it->HasResultId()) {
  127. skip_count[opcode] =
  128. skip_count.count(opcode) ? skip_count.at(opcode) + 1 : 1;
  129. }
  130. }
  131. }
  132. }
  133. }
  134. uint32_t FuzzerPass::FindOrCreateBoolType() {
  135. opt::analysis::Bool bool_type;
  136. auto existing_id = GetIRContext()->get_type_mgr()->GetId(&bool_type);
  137. if (existing_id) {
  138. return existing_id;
  139. }
  140. auto result = GetFuzzerContext()->GetFreshId();
  141. ApplyTransformation(TransformationAddTypeBoolean(result));
  142. return result;
  143. }
  144. uint32_t FuzzerPass::FindOrCreateIntegerType(uint32_t width, bool is_signed) {
  145. opt::analysis::Integer int_type(width, is_signed);
  146. auto existing_id = GetIRContext()->get_type_mgr()->GetId(&int_type);
  147. if (existing_id) {
  148. return existing_id;
  149. }
  150. auto result = GetFuzzerContext()->GetFreshId();
  151. ApplyTransformation(TransformationAddTypeInt(result, width, is_signed));
  152. return result;
  153. }
  154. uint32_t FuzzerPass::FindOrCreateFloatType(uint32_t width) {
  155. opt::analysis::Float float_type(width);
  156. auto existing_id = GetIRContext()->get_type_mgr()->GetId(&float_type);
  157. if (existing_id) {
  158. return existing_id;
  159. }
  160. auto result = GetFuzzerContext()->GetFreshId();
  161. ApplyTransformation(TransformationAddTypeFloat(result, width));
  162. return result;
  163. }
  164. uint32_t FuzzerPass::FindOrCreateFunctionType(
  165. uint32_t return_type_id, const std::vector<uint32_t>& argument_id) {
  166. // FindFunctionType has a sigle argument for OpTypeFunction operands
  167. // so we will have to copy them all in this vector
  168. std::vector<uint32_t> type_ids(argument_id.size() + 1);
  169. type_ids[0] = return_type_id;
  170. std::copy(argument_id.begin(), argument_id.end(), type_ids.begin() + 1);
  171. // Check if type exists
  172. auto existing_id = fuzzerutil::FindFunctionType(GetIRContext(), type_ids);
  173. if (existing_id) {
  174. return existing_id;
  175. }
  176. auto result = GetFuzzerContext()->GetFreshId();
  177. ApplyTransformation(
  178. TransformationAddTypeFunction(result, return_type_id, argument_id));
  179. return result;
  180. }
  181. uint32_t FuzzerPass::FindOrCreateVectorType(uint32_t component_type_id,
  182. uint32_t component_count) {
  183. assert(component_count >= 2 && component_count <= 4 &&
  184. "Precondition: component count must be in range [2, 4].");
  185. opt::analysis::Type* component_type =
  186. GetIRContext()->get_type_mgr()->GetType(component_type_id);
  187. assert(component_type && "Precondition: the component type must exist.");
  188. opt::analysis::Vector vector_type(component_type, component_count);
  189. auto existing_id = GetIRContext()->get_type_mgr()->GetId(&vector_type);
  190. if (existing_id) {
  191. return existing_id;
  192. }
  193. auto result = GetFuzzerContext()->GetFreshId();
  194. ApplyTransformation(
  195. TransformationAddTypeVector(result, component_type_id, component_count));
  196. return result;
  197. }
  198. uint32_t FuzzerPass::FindOrCreateMatrixType(uint32_t column_count,
  199. uint32_t row_count) {
  200. assert(column_count >= 2 && column_count <= 4 &&
  201. "Precondition: column count must be in range [2, 4].");
  202. assert(row_count >= 2 && row_count <= 4 &&
  203. "Precondition: row count must be in range [2, 4].");
  204. uint32_t column_type_id =
  205. FindOrCreateVectorType(FindOrCreateFloatType(32), row_count);
  206. opt::analysis::Type* column_type =
  207. GetIRContext()->get_type_mgr()->GetType(column_type_id);
  208. opt::analysis::Matrix matrix_type(column_type, column_count);
  209. auto existing_id = GetIRContext()->get_type_mgr()->GetId(&matrix_type);
  210. if (existing_id) {
  211. return existing_id;
  212. }
  213. auto result = GetFuzzerContext()->GetFreshId();
  214. ApplyTransformation(
  215. TransformationAddTypeMatrix(result, column_type_id, column_count));
  216. return result;
  217. }
  218. uint32_t FuzzerPass::FindOrCreatePointerType(uint32_t base_type_id,
  219. SpvStorageClass storage_class) {
  220. // We do not use the type manager here, due to problems related to isomorphic
  221. // but distinct structs not being regarded as different.
  222. auto existing_id = fuzzerutil::MaybeGetPointerType(
  223. GetIRContext(), base_type_id, storage_class);
  224. if (existing_id) {
  225. return existing_id;
  226. }
  227. auto result = GetFuzzerContext()->GetFreshId();
  228. ApplyTransformation(
  229. TransformationAddTypePointer(result, storage_class, base_type_id));
  230. return result;
  231. }
  232. uint32_t FuzzerPass::FindOrCreatePointerToIntegerType(
  233. uint32_t width, bool is_signed, SpvStorageClass storage_class) {
  234. return FindOrCreatePointerType(FindOrCreateIntegerType(width, is_signed),
  235. storage_class);
  236. }
  237. uint32_t FuzzerPass::FindOrCreateIntegerConstant(
  238. const std::vector<uint32_t>& words, uint32_t width, bool is_signed) {
  239. auto int_type_id = FindOrCreateIntegerType(width, is_signed);
  240. opt::analysis::IntConstant int_constant(
  241. GetIRContext()->get_type_mgr()->GetType(int_type_id)->AsInteger(), words);
  242. auto existing_constant =
  243. GetIRContext()->get_constant_mgr()->FindConstant(&int_constant);
  244. if (existing_constant) {
  245. return GetIRContext()
  246. ->get_constant_mgr()
  247. ->GetDefiningInstruction(existing_constant)
  248. ->result_id();
  249. }
  250. auto result = GetFuzzerContext()->GetFreshId();
  251. ApplyTransformation(
  252. TransformationAddConstantScalar(result, int_type_id, words));
  253. return result;
  254. }
  255. uint32_t FuzzerPass::FindOrCreateFloatConstant(
  256. const std::vector<uint32_t>& words, uint32_t width) {
  257. auto float_type_id = FindOrCreateFloatType(width);
  258. opt::analysis::FloatConstant float_constant(
  259. GetIRContext()->get_type_mgr()->GetType(float_type_id)->AsFloat(), words);
  260. auto existing_constant =
  261. GetIRContext()->get_constant_mgr()->FindConstant(&float_constant);
  262. if (existing_constant) {
  263. return GetIRContext()
  264. ->get_constant_mgr()
  265. ->GetDefiningInstruction(existing_constant)
  266. ->result_id();
  267. }
  268. auto result = GetFuzzerContext()->GetFreshId();
  269. ApplyTransformation(
  270. TransformationAddConstantScalar(result, float_type_id, words));
  271. return result;
  272. }
  273. uint32_t FuzzerPass::FindOrCreateBoolConstant(bool value) {
  274. auto bool_type_id = FindOrCreateBoolType();
  275. opt::analysis::BoolConstant bool_constant(
  276. GetIRContext()->get_type_mgr()->GetType(bool_type_id)->AsBool(), value);
  277. auto existing_constant =
  278. GetIRContext()->get_constant_mgr()->FindConstant(&bool_constant);
  279. if (existing_constant) {
  280. return GetIRContext()
  281. ->get_constant_mgr()
  282. ->GetDefiningInstruction(existing_constant)
  283. ->result_id();
  284. }
  285. auto result = GetFuzzerContext()->GetFreshId();
  286. ApplyTransformation(TransformationAddConstantBoolean(result, value));
  287. return result;
  288. }
  289. uint32_t FuzzerPass::FindOrCreateConstant(const std::vector<uint32_t>& words,
  290. uint32_t type_id) {
  291. assert(type_id && "Constant's type id can't be 0.");
  292. const auto* type = GetIRContext()->get_type_mgr()->GetType(type_id);
  293. assert(type && "Type does not exist.");
  294. if (type->AsBool()) {
  295. assert(words.size() == 1);
  296. return FindOrCreateBoolConstant(words[0]);
  297. } else if (const auto* integer = type->AsInteger()) {
  298. return FindOrCreateIntegerConstant(words, integer->width(),
  299. integer->IsSigned());
  300. } else if (const auto* floating = type->AsFloat()) {
  301. return FindOrCreateFloatConstant(words, floating->width());
  302. }
  303. // This assertion will fail in debug build but not in release build
  304. // so we return 0 to make compiler happy.
  305. assert(false && "Constant type is not supported");
  306. return 0;
  307. }
  308. uint32_t FuzzerPass::FindOrCreateGlobalUndef(uint32_t type_id) {
  309. for (auto& inst : GetIRContext()->types_values()) {
  310. if (inst.opcode() == SpvOpUndef && inst.type_id() == type_id) {
  311. return inst.result_id();
  312. }
  313. }
  314. auto result = GetFuzzerContext()->GetFreshId();
  315. ApplyTransformation(TransformationAddGlobalUndef(result, type_id));
  316. return result;
  317. }
  318. std::pair<std::vector<uint32_t>, std::map<uint32_t, std::vector<uint32_t>>>
  319. FuzzerPass::GetAvailableBasicTypesAndPointers(
  320. SpvStorageClass storage_class) const {
  321. // Records all of the basic types available in the module.
  322. std::set<uint32_t> basic_types;
  323. // For each basic type, records all the associated pointer types that target
  324. // the basic type and that have |storage_class| as their storage class.
  325. std::map<uint32_t, std::vector<uint32_t>> basic_type_to_pointers;
  326. for (auto& inst : GetIRContext()->types_values()) {
  327. // For each basic type that we come across, record type, and the fact that
  328. // we cannot yet have seen any pointers that use the basic type as its
  329. // pointee type.
  330. //
  331. // For pointer types with basic pointee types, associate the pointer type
  332. // with the basic type.
  333. switch (inst.opcode()) {
  334. case SpvOpTypeBool:
  335. case SpvOpTypeFloat:
  336. case SpvOpTypeInt:
  337. case SpvOpTypeMatrix:
  338. case SpvOpTypeVector:
  339. // These are all basic types.
  340. basic_types.insert(inst.result_id());
  341. basic_type_to_pointers.insert({inst.result_id(), {}});
  342. break;
  343. case SpvOpTypeArray:
  344. // An array type is basic if its base type is basic.
  345. if (basic_types.count(inst.GetSingleWordInOperand(0))) {
  346. basic_types.insert(inst.result_id());
  347. basic_type_to_pointers.insert({inst.result_id(), {}});
  348. }
  349. break;
  350. case SpvOpTypeStruct: {
  351. // A struct type is basic if all of its members are basic.
  352. bool all_members_are_basic_types = true;
  353. for (uint32_t i = 0; i < inst.NumInOperands(); i++) {
  354. if (!basic_types.count(inst.GetSingleWordInOperand(i))) {
  355. all_members_are_basic_types = false;
  356. break;
  357. }
  358. }
  359. if (all_members_are_basic_types) {
  360. basic_types.insert(inst.result_id());
  361. basic_type_to_pointers.insert({inst.result_id(), {}});
  362. }
  363. break;
  364. }
  365. case SpvOpTypePointer: {
  366. // We are interested in the pointer if its pointee type is basic and it
  367. // has the right storage class.
  368. auto pointee_type = inst.GetSingleWordInOperand(1);
  369. if (inst.GetSingleWordInOperand(0) == storage_class &&
  370. basic_types.count(pointee_type)) {
  371. // The pointer has the desired storage class, and its pointee type is
  372. // a basic type, so we are interested in it. Associate it with its
  373. // basic type.
  374. basic_type_to_pointers.at(pointee_type).push_back(inst.result_id());
  375. }
  376. break;
  377. }
  378. default:
  379. break;
  380. }
  381. }
  382. return {{basic_types.begin(), basic_types.end()}, basic_type_to_pointers};
  383. }
  384. uint32_t FuzzerPass::FindOrCreateZeroConstant(
  385. uint32_t scalar_or_composite_type_id) {
  386. auto type_instruction =
  387. GetIRContext()->get_def_use_mgr()->GetDef(scalar_or_composite_type_id);
  388. assert(type_instruction && "The type instruction must exist.");
  389. switch (type_instruction->opcode()) {
  390. case SpvOpTypeBool:
  391. return FindOrCreateBoolConstant(false);
  392. case SpvOpTypeFloat: {
  393. auto width = type_instruction->GetSingleWordInOperand(0);
  394. auto num_words = (width + 32 - 1) / 32;
  395. return FindOrCreateFloatConstant(std::vector<uint32_t>(num_words, 0),
  396. width);
  397. }
  398. case SpvOpTypeInt: {
  399. auto width = type_instruction->GetSingleWordInOperand(0);
  400. auto num_words = (width + 32 - 1) / 32;
  401. return FindOrCreateIntegerConstant(
  402. std::vector<uint32_t>(num_words, 0), width,
  403. type_instruction->GetSingleWordInOperand(1));
  404. }
  405. case SpvOpTypeArray: {
  406. return GetZeroConstantForHomogeneousComposite(
  407. *type_instruction, type_instruction->GetSingleWordInOperand(0),
  408. fuzzerutil::GetArraySize(*type_instruction, GetIRContext()));
  409. }
  410. case SpvOpTypeMatrix:
  411. case SpvOpTypeVector: {
  412. return GetZeroConstantForHomogeneousComposite(
  413. *type_instruction, type_instruction->GetSingleWordInOperand(0),
  414. type_instruction->GetSingleWordInOperand(1));
  415. }
  416. case SpvOpTypeStruct: {
  417. std::vector<const opt::analysis::Constant*> field_zero_constants;
  418. std::vector<uint32_t> field_zero_ids;
  419. for (uint32_t index = 0; index < type_instruction->NumInOperands();
  420. index++) {
  421. uint32_t field_constant_id = FindOrCreateZeroConstant(
  422. type_instruction->GetSingleWordInOperand(index));
  423. field_zero_ids.push_back(field_constant_id);
  424. field_zero_constants.push_back(
  425. GetIRContext()->get_constant_mgr()->FindDeclaredConstant(
  426. field_constant_id));
  427. }
  428. return FindOrCreateCompositeConstant(
  429. *type_instruction, field_zero_constants, field_zero_ids);
  430. }
  431. default:
  432. assert(false && "Unknown type.");
  433. return 0;
  434. }
  435. }
  436. uint32_t FuzzerPass::FindOrCreateCompositeConstant(
  437. const opt::Instruction& composite_type_instruction,
  438. const std::vector<const opt::analysis::Constant*>& constants,
  439. const std::vector<uint32_t>& constant_ids) {
  440. assert(constants.size() == constant_ids.size() &&
  441. "Precondition: |constants| and |constant_ids| must be in "
  442. "correspondence.");
  443. opt::analysis::Type* composite_type = GetIRContext()->get_type_mgr()->GetType(
  444. composite_type_instruction.result_id());
  445. std::unique_ptr<opt::analysis::Constant> composite_constant;
  446. if (composite_type->AsArray()) {
  447. composite_constant = MakeUnique<opt::analysis::ArrayConstant>(
  448. composite_type->AsArray(), constants);
  449. } else if (composite_type->AsMatrix()) {
  450. composite_constant = MakeUnique<opt::analysis::MatrixConstant>(
  451. composite_type->AsMatrix(), constants);
  452. } else if (composite_type->AsStruct()) {
  453. composite_constant = MakeUnique<opt::analysis::StructConstant>(
  454. composite_type->AsStruct(), constants);
  455. } else if (composite_type->AsVector()) {
  456. composite_constant = MakeUnique<opt::analysis::VectorConstant>(
  457. composite_type->AsVector(), constants);
  458. } else {
  459. assert(false &&
  460. "Precondition: |composite_type| must declare a composite type.");
  461. return 0;
  462. }
  463. uint32_t existing_constant =
  464. GetIRContext()->get_constant_mgr()->FindDeclaredConstant(
  465. composite_constant.get(), composite_type_instruction.result_id());
  466. if (existing_constant) {
  467. return existing_constant;
  468. }
  469. uint32_t result = GetFuzzerContext()->GetFreshId();
  470. ApplyTransformation(TransformationAddConstantComposite(
  471. result, composite_type_instruction.result_id(), constant_ids));
  472. return result;
  473. }
  474. uint32_t FuzzerPass::GetZeroConstantForHomogeneousComposite(
  475. const opt::Instruction& composite_type_instruction,
  476. uint32_t component_type_id, uint32_t num_components) {
  477. std::vector<const opt::analysis::Constant*> zero_constants;
  478. std::vector<uint32_t> zero_ids;
  479. uint32_t zero_component = FindOrCreateZeroConstant(component_type_id);
  480. const opt::analysis::Constant* registered_zero_component =
  481. GetIRContext()->get_constant_mgr()->FindDeclaredConstant(zero_component);
  482. for (uint32_t i = 0; i < num_components; i++) {
  483. zero_constants.push_back(registered_zero_component);
  484. zero_ids.push_back(zero_component);
  485. }
  486. return FindOrCreateCompositeConstant(composite_type_instruction,
  487. zero_constants, zero_ids);
  488. }
  489. } // namespace fuzz
  490. } // namespace spvtools