fuzzer_pass.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  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/id_use_descriptor.h"
  18. #include "source/fuzz/instruction_descriptor.h"
  19. #include "source/fuzz/transformation_add_constant_boolean.h"
  20. #include "source/fuzz/transformation_add_constant_composite.h"
  21. #include "source/fuzz/transformation_add_constant_null.h"
  22. #include "source/fuzz/transformation_add_constant_scalar.h"
  23. #include "source/fuzz/transformation_add_global_undef.h"
  24. #include "source/fuzz/transformation_add_global_variable.h"
  25. #include "source/fuzz/transformation_add_local_variable.h"
  26. #include "source/fuzz/transformation_add_loop_preheader.h"
  27. #include "source/fuzz/transformation_add_type_boolean.h"
  28. #include "source/fuzz/transformation_add_type_float.h"
  29. #include "source/fuzz/transformation_add_type_function.h"
  30. #include "source/fuzz/transformation_add_type_int.h"
  31. #include "source/fuzz/transformation_add_type_matrix.h"
  32. #include "source/fuzz/transformation_add_type_pointer.h"
  33. #include "source/fuzz/transformation_add_type_struct.h"
  34. #include "source/fuzz/transformation_add_type_vector.h"
  35. #include "source/fuzz/transformation_split_block.h"
  36. namespace spvtools {
  37. namespace fuzz {
  38. FuzzerPass::FuzzerPass(opt::IRContext* ir_context,
  39. TransformationContext* transformation_context,
  40. FuzzerContext* fuzzer_context,
  41. protobufs::TransformationSequence* transformations)
  42. : ir_context_(ir_context),
  43. transformation_context_(transformation_context),
  44. fuzzer_context_(fuzzer_context),
  45. transformations_(transformations) {}
  46. FuzzerPass::~FuzzerPass() = default;
  47. std::vector<opt::Instruction*> FuzzerPass::FindAvailableInstructions(
  48. opt::Function* function, opt::BasicBlock* block,
  49. const opt::BasicBlock::iterator& inst_it,
  50. std::function<bool(opt::IRContext*, opt::Instruction*)>
  51. instruction_is_relevant) const {
  52. // TODO(afd) The following is (relatively) simple, but may end up being
  53. // prohibitively inefficient, as it walks the whole dominator tree for
  54. // every instruction that is considered.
  55. std::vector<opt::Instruction*> result;
  56. // Consider all global declarations
  57. for (auto& global : GetIRContext()->module()->types_values()) {
  58. if (instruction_is_relevant(GetIRContext(), &global)) {
  59. result.push_back(&global);
  60. }
  61. }
  62. // Consider all function parameters
  63. function->ForEachParam(
  64. [this, &instruction_is_relevant, &result](opt::Instruction* param) {
  65. if (instruction_is_relevant(GetIRContext(), param)) {
  66. result.push_back(param);
  67. }
  68. });
  69. // Consider all previous instructions in this block
  70. for (auto prev_inst_it = block->begin(); prev_inst_it != inst_it;
  71. ++prev_inst_it) {
  72. if (instruction_is_relevant(GetIRContext(), &*prev_inst_it)) {
  73. result.push_back(&*prev_inst_it);
  74. }
  75. }
  76. // Walk the dominator tree to consider all instructions from dominating
  77. // blocks
  78. auto dominator_analysis = GetIRContext()->GetDominatorAnalysis(function);
  79. for (auto next_dominator = dominator_analysis->ImmediateDominator(block);
  80. next_dominator != nullptr;
  81. next_dominator =
  82. dominator_analysis->ImmediateDominator(next_dominator)) {
  83. for (auto& dominating_inst : *next_dominator) {
  84. if (instruction_is_relevant(GetIRContext(), &dominating_inst)) {
  85. result.push_back(&dominating_inst);
  86. }
  87. }
  88. }
  89. return result;
  90. }
  91. void FuzzerPass::ForEachInstructionWithInstructionDescriptor(
  92. opt::Function* function,
  93. std::function<
  94. void(opt::BasicBlock* block, opt::BasicBlock::iterator inst_it,
  95. const protobufs::InstructionDescriptor& instruction_descriptor)>
  96. action) {
  97. // Consider only reachable blocks. We do this in a separate loop to avoid
  98. // recomputing the dominator analysis every time |action| changes the
  99. // module.
  100. std::vector<opt::BasicBlock*> reachable_blocks;
  101. const auto* dominator_analysis =
  102. GetIRContext()->GetDominatorAnalysis(function);
  103. for (auto& block : *function) {
  104. if (dominator_analysis->IsReachable(&block)) {
  105. reachable_blocks.push_back(&block);
  106. }
  107. }
  108. for (auto* block : reachable_blocks) {
  109. // We now consider every instruction in the block, randomly deciding
  110. // whether to apply a transformation before it.
  111. // In order for transformations to insert new instructions, they need to
  112. // be able to identify the instruction to insert before. We describe an
  113. // instruction via its opcode, 'opc', a base instruction 'base' that has a
  114. // result id, and the number of instructions with opcode 'opc' that we
  115. // should skip when searching from 'base' for the desired instruction.
  116. // (An instruction that has a result id is represented by its own opcode,
  117. // itself as 'base', and a skip-count of 0.)
  118. std::vector<std::tuple<uint32_t, SpvOp, uint32_t>> base_opcode_skip_triples;
  119. // The initial base instruction is the block label.
  120. uint32_t base = block->id();
  121. // Counts the number of times we have seen each opcode since we reset the
  122. // base instruction.
  123. std::map<SpvOp, uint32_t> skip_count;
  124. // Consider every instruction in the block. The label is excluded: it is
  125. // only necessary to consider it as a base in case the first instruction
  126. // in the block does not have a result id.
  127. for (auto inst_it = block->begin(); inst_it != block->end(); ++inst_it) {
  128. if (inst_it->HasResultId()) {
  129. // In the case that the instruction has a result id, we use the
  130. // instruction as its own base, and clear the skip counts we have
  131. // collected.
  132. base = inst_it->result_id();
  133. skip_count.clear();
  134. }
  135. const SpvOp opcode = inst_it->opcode();
  136. // Invoke the provided function, which might apply a transformation.
  137. action(block, inst_it,
  138. MakeInstructionDescriptor(
  139. base, opcode,
  140. skip_count.count(opcode) ? skip_count.at(opcode) : 0));
  141. if (!inst_it->HasResultId()) {
  142. skip_count[opcode] =
  143. skip_count.count(opcode) ? skip_count.at(opcode) + 1 : 1;
  144. }
  145. }
  146. }
  147. }
  148. void FuzzerPass::ForEachInstructionWithInstructionDescriptor(
  149. std::function<
  150. void(opt::Function* function, opt::BasicBlock* block,
  151. opt::BasicBlock::iterator inst_it,
  152. const protobufs::InstructionDescriptor& instruction_descriptor)>
  153. action) {
  154. // Consider every block in every function.
  155. for (auto& function : *GetIRContext()->module()) {
  156. ForEachInstructionWithInstructionDescriptor(
  157. &function,
  158. [&action, &function](
  159. opt::BasicBlock* block, opt::BasicBlock::iterator inst_it,
  160. const protobufs::InstructionDescriptor& instruction_descriptor) {
  161. action(&function, block, inst_it, instruction_descriptor);
  162. });
  163. }
  164. }
  165. uint32_t FuzzerPass::FindOrCreateBoolType() {
  166. if (auto existing_id = fuzzerutil::MaybeGetBoolType(GetIRContext())) {
  167. return existing_id;
  168. }
  169. auto result = GetFuzzerContext()->GetFreshId();
  170. ApplyTransformation(TransformationAddTypeBoolean(result));
  171. return result;
  172. }
  173. uint32_t FuzzerPass::FindOrCreateIntegerType(uint32_t width, bool is_signed) {
  174. opt::analysis::Integer int_type(width, is_signed);
  175. auto existing_id = GetIRContext()->get_type_mgr()->GetId(&int_type);
  176. if (existing_id) {
  177. return existing_id;
  178. }
  179. auto result = GetFuzzerContext()->GetFreshId();
  180. ApplyTransformation(TransformationAddTypeInt(result, width, is_signed));
  181. return result;
  182. }
  183. uint32_t FuzzerPass::FindOrCreateFloatType(uint32_t width) {
  184. opt::analysis::Float float_type(width);
  185. auto existing_id = GetIRContext()->get_type_mgr()->GetId(&float_type);
  186. if (existing_id) {
  187. return existing_id;
  188. }
  189. auto result = GetFuzzerContext()->GetFreshId();
  190. ApplyTransformation(TransformationAddTypeFloat(result, width));
  191. return result;
  192. }
  193. uint32_t FuzzerPass::FindOrCreateFunctionType(
  194. uint32_t return_type_id, const std::vector<uint32_t>& argument_id) {
  195. // FindFunctionType has a sigle argument for OpTypeFunction operands
  196. // so we will have to copy them all in this vector
  197. std::vector<uint32_t> type_ids(argument_id.size() + 1);
  198. type_ids[0] = return_type_id;
  199. std::copy(argument_id.begin(), argument_id.end(), type_ids.begin() + 1);
  200. // Check if type exists
  201. auto existing_id = fuzzerutil::FindFunctionType(GetIRContext(), type_ids);
  202. if (existing_id) {
  203. return existing_id;
  204. }
  205. auto result = GetFuzzerContext()->GetFreshId();
  206. ApplyTransformation(
  207. TransformationAddTypeFunction(result, return_type_id, argument_id));
  208. return result;
  209. }
  210. uint32_t FuzzerPass::FindOrCreateVectorType(uint32_t component_type_id,
  211. uint32_t component_count) {
  212. assert(component_count >= 2 && component_count <= 4 &&
  213. "Precondition: component count must be in range [2, 4].");
  214. opt::analysis::Type* component_type =
  215. GetIRContext()->get_type_mgr()->GetType(component_type_id);
  216. assert(component_type && "Precondition: the component type must exist.");
  217. opt::analysis::Vector vector_type(component_type, component_count);
  218. auto existing_id = GetIRContext()->get_type_mgr()->GetId(&vector_type);
  219. if (existing_id) {
  220. return existing_id;
  221. }
  222. auto result = GetFuzzerContext()->GetFreshId();
  223. ApplyTransformation(
  224. TransformationAddTypeVector(result, component_type_id, component_count));
  225. return result;
  226. }
  227. uint32_t FuzzerPass::FindOrCreateMatrixType(uint32_t column_count,
  228. uint32_t row_count) {
  229. assert(column_count >= 2 && column_count <= 4 &&
  230. "Precondition: column count must be in range [2, 4].");
  231. assert(row_count >= 2 && row_count <= 4 &&
  232. "Precondition: row count must be in range [2, 4].");
  233. uint32_t column_type_id =
  234. FindOrCreateVectorType(FindOrCreateFloatType(32), row_count);
  235. opt::analysis::Type* column_type =
  236. GetIRContext()->get_type_mgr()->GetType(column_type_id);
  237. opt::analysis::Matrix matrix_type(column_type, column_count);
  238. auto existing_id = GetIRContext()->get_type_mgr()->GetId(&matrix_type);
  239. if (existing_id) {
  240. return existing_id;
  241. }
  242. auto result = GetFuzzerContext()->GetFreshId();
  243. ApplyTransformation(
  244. TransformationAddTypeMatrix(result, column_type_id, column_count));
  245. return result;
  246. }
  247. uint32_t FuzzerPass::FindOrCreateStructType(
  248. const std::vector<uint32_t>& component_type_ids) {
  249. if (auto existing_id =
  250. fuzzerutil::MaybeGetStructType(GetIRContext(), component_type_ids)) {
  251. return existing_id;
  252. }
  253. auto new_id = GetFuzzerContext()->GetFreshId();
  254. ApplyTransformation(TransformationAddTypeStruct(new_id, component_type_ids));
  255. return new_id;
  256. }
  257. uint32_t FuzzerPass::FindOrCreatePointerType(uint32_t base_type_id,
  258. SpvStorageClass storage_class) {
  259. // We do not use the type manager here, due to problems related to isomorphic
  260. // but distinct structs not being regarded as different.
  261. auto existing_id = fuzzerutil::MaybeGetPointerType(
  262. GetIRContext(), base_type_id, storage_class);
  263. if (existing_id) {
  264. return existing_id;
  265. }
  266. auto result = GetFuzzerContext()->GetFreshId();
  267. ApplyTransformation(
  268. TransformationAddTypePointer(result, storage_class, base_type_id));
  269. return result;
  270. }
  271. uint32_t FuzzerPass::FindOrCreatePointerToIntegerType(
  272. uint32_t width, bool is_signed, SpvStorageClass storage_class) {
  273. return FindOrCreatePointerType(FindOrCreateIntegerType(width, is_signed),
  274. storage_class);
  275. }
  276. uint32_t FuzzerPass::FindOrCreateIntegerConstant(
  277. const std::vector<uint32_t>& words, uint32_t width, bool is_signed,
  278. bool is_irrelevant) {
  279. auto int_type_id = FindOrCreateIntegerType(width, is_signed);
  280. if (auto constant_id = fuzzerutil::MaybeGetScalarConstant(
  281. GetIRContext(), *GetTransformationContext(), words, int_type_id,
  282. is_irrelevant)) {
  283. return constant_id;
  284. }
  285. auto result = GetFuzzerContext()->GetFreshId();
  286. ApplyTransformation(TransformationAddConstantScalar(result, int_type_id,
  287. words, is_irrelevant));
  288. return result;
  289. }
  290. uint32_t FuzzerPass::FindOrCreateFloatConstant(
  291. const std::vector<uint32_t>& words, uint32_t width, bool is_irrelevant) {
  292. auto float_type_id = FindOrCreateFloatType(width);
  293. if (auto constant_id = fuzzerutil::MaybeGetScalarConstant(
  294. GetIRContext(), *GetTransformationContext(), words, float_type_id,
  295. is_irrelevant)) {
  296. return constant_id;
  297. }
  298. auto result = GetFuzzerContext()->GetFreshId();
  299. ApplyTransformation(TransformationAddConstantScalar(result, float_type_id,
  300. words, is_irrelevant));
  301. return result;
  302. }
  303. uint32_t FuzzerPass::FindOrCreateBoolConstant(bool value, bool is_irrelevant) {
  304. auto bool_type_id = FindOrCreateBoolType();
  305. if (auto constant_id = fuzzerutil::MaybeGetScalarConstant(
  306. GetIRContext(), *GetTransformationContext(), {value ? 1u : 0u},
  307. bool_type_id, is_irrelevant)) {
  308. return constant_id;
  309. }
  310. auto result = GetFuzzerContext()->GetFreshId();
  311. ApplyTransformation(
  312. TransformationAddConstantBoolean(result, value, is_irrelevant));
  313. return result;
  314. }
  315. uint32_t FuzzerPass::FindOrCreateConstant(const std::vector<uint32_t>& words,
  316. uint32_t type_id,
  317. bool is_irrelevant) {
  318. assert(type_id && "Constant's type id can't be 0.");
  319. const auto* type = GetIRContext()->get_type_mgr()->GetType(type_id);
  320. assert(type && "Type does not exist.");
  321. if (type->AsBool()) {
  322. assert(words.size() == 1);
  323. return FindOrCreateBoolConstant(words[0], is_irrelevant);
  324. } else if (const auto* integer = type->AsInteger()) {
  325. return FindOrCreateIntegerConstant(words, integer->width(),
  326. integer->IsSigned(), is_irrelevant);
  327. } else if (const auto* floating = type->AsFloat()) {
  328. return FindOrCreateFloatConstant(words, floating->width(), is_irrelevant);
  329. }
  330. // This assertion will fail in debug build but not in release build
  331. // so we return 0 to make compiler happy.
  332. assert(false && "Constant type is not supported");
  333. return 0;
  334. }
  335. uint32_t FuzzerPass::FindOrCreateCompositeConstant(
  336. const std::vector<uint32_t>& component_ids, uint32_t type_id,
  337. bool is_irrelevant) {
  338. if (auto existing_constant = fuzzerutil::MaybeGetCompositeConstant(
  339. GetIRContext(), *GetTransformationContext(), component_ids, type_id,
  340. is_irrelevant)) {
  341. return existing_constant;
  342. }
  343. uint32_t result = GetFuzzerContext()->GetFreshId();
  344. ApplyTransformation(TransformationAddConstantComposite(
  345. result, type_id, component_ids, is_irrelevant));
  346. return result;
  347. }
  348. uint32_t FuzzerPass::FindOrCreateGlobalUndef(uint32_t type_id) {
  349. for (auto& inst : GetIRContext()->types_values()) {
  350. if (inst.opcode() == SpvOpUndef && inst.type_id() == type_id) {
  351. return inst.result_id();
  352. }
  353. }
  354. auto result = GetFuzzerContext()->GetFreshId();
  355. ApplyTransformation(TransformationAddGlobalUndef(result, type_id));
  356. return result;
  357. }
  358. uint32_t FuzzerPass::FindOrCreateNullConstant(uint32_t type_id) {
  359. // Find existing declaration
  360. opt::analysis::NullConstant null_constant(
  361. GetIRContext()->get_type_mgr()->GetType(type_id));
  362. auto existing_constant =
  363. GetIRContext()->get_constant_mgr()->FindConstant(&null_constant);
  364. // Return if found
  365. if (existing_constant) {
  366. return GetIRContext()
  367. ->get_constant_mgr()
  368. ->GetDefiningInstruction(existing_constant)
  369. ->result_id();
  370. }
  371. // Create new if not found
  372. auto result = GetFuzzerContext()->GetFreshId();
  373. ApplyTransformation(TransformationAddConstantNull(result, type_id));
  374. return result;
  375. }
  376. std::pair<std::vector<uint32_t>, std::map<uint32_t, std::vector<uint32_t>>>
  377. FuzzerPass::GetAvailableBasicTypesAndPointers(
  378. SpvStorageClass storage_class) const {
  379. // Records all of the basic types available in the module.
  380. std::set<uint32_t> basic_types;
  381. // For each basic type, records all the associated pointer types that target
  382. // the basic type and that have |storage_class| as their storage class.
  383. std::map<uint32_t, std::vector<uint32_t>> basic_type_to_pointers;
  384. for (auto& inst : GetIRContext()->types_values()) {
  385. // For each basic type that we come across, record type, and the fact that
  386. // we cannot yet have seen any pointers that use the basic type as its
  387. // pointee type.
  388. //
  389. // For pointer types with basic pointee types, associate the pointer type
  390. // with the basic type.
  391. switch (inst.opcode()) {
  392. case SpvOpTypeBool:
  393. case SpvOpTypeFloat:
  394. case SpvOpTypeInt:
  395. case SpvOpTypeMatrix:
  396. case SpvOpTypeVector:
  397. // These are all basic types.
  398. basic_types.insert(inst.result_id());
  399. basic_type_to_pointers.insert({inst.result_id(), {}});
  400. break;
  401. case SpvOpTypeArray:
  402. // An array type is basic if its base type is basic.
  403. if (basic_types.count(inst.GetSingleWordInOperand(0))) {
  404. basic_types.insert(inst.result_id());
  405. basic_type_to_pointers.insert({inst.result_id(), {}});
  406. }
  407. break;
  408. case SpvOpTypeStruct: {
  409. // A struct type is basic if it does not have the Block/BufferBlock
  410. // decoration, and if all of its members are basic.
  411. if (!fuzzerutil::HasBlockOrBufferBlockDecoration(GetIRContext(),
  412. inst.result_id())) {
  413. bool all_members_are_basic_types = true;
  414. for (uint32_t i = 0; i < inst.NumInOperands(); i++) {
  415. if (!basic_types.count(inst.GetSingleWordInOperand(i))) {
  416. all_members_are_basic_types = false;
  417. break;
  418. }
  419. }
  420. if (all_members_are_basic_types) {
  421. basic_types.insert(inst.result_id());
  422. basic_type_to_pointers.insert({inst.result_id(), {}});
  423. }
  424. }
  425. break;
  426. }
  427. case SpvOpTypePointer: {
  428. // We are interested in the pointer if its pointee type is basic and it
  429. // has the right storage class.
  430. auto pointee_type = inst.GetSingleWordInOperand(1);
  431. if (inst.GetSingleWordInOperand(0) == storage_class &&
  432. basic_types.count(pointee_type)) {
  433. // The pointer has the desired storage class, and its pointee type is
  434. // a basic type, so we are interested in it. Associate it with its
  435. // basic type.
  436. basic_type_to_pointers.at(pointee_type).push_back(inst.result_id());
  437. }
  438. break;
  439. }
  440. default:
  441. break;
  442. }
  443. }
  444. return {{basic_types.begin(), basic_types.end()}, basic_type_to_pointers};
  445. }
  446. uint32_t FuzzerPass::FindOrCreateZeroConstant(
  447. uint32_t scalar_or_composite_type_id, bool is_irrelevant) {
  448. auto type_instruction =
  449. GetIRContext()->get_def_use_mgr()->GetDef(scalar_or_composite_type_id);
  450. assert(type_instruction && "The type instruction must exist.");
  451. switch (type_instruction->opcode()) {
  452. case SpvOpTypeBool:
  453. return FindOrCreateBoolConstant(false, is_irrelevant);
  454. case SpvOpTypeFloat: {
  455. auto width = type_instruction->GetSingleWordInOperand(0);
  456. auto num_words = (width + 32 - 1) / 32;
  457. return FindOrCreateFloatConstant(std::vector<uint32_t>(num_words, 0),
  458. width, is_irrelevant);
  459. }
  460. case SpvOpTypeInt: {
  461. auto width = type_instruction->GetSingleWordInOperand(0);
  462. auto num_words = (width + 32 - 1) / 32;
  463. return FindOrCreateIntegerConstant(
  464. std::vector<uint32_t>(num_words, 0), width,
  465. type_instruction->GetSingleWordInOperand(1), is_irrelevant);
  466. }
  467. case SpvOpTypeArray: {
  468. auto component_type_id = type_instruction->GetSingleWordInOperand(0);
  469. auto num_components =
  470. fuzzerutil::GetArraySize(*type_instruction, GetIRContext());
  471. return FindOrCreateCompositeConstant(
  472. std::vector<uint32_t>(
  473. num_components,
  474. FindOrCreateZeroConstant(component_type_id, is_irrelevant)),
  475. scalar_or_composite_type_id, is_irrelevant);
  476. }
  477. case SpvOpTypeMatrix:
  478. case SpvOpTypeVector: {
  479. auto component_type_id = type_instruction->GetSingleWordInOperand(0);
  480. auto num_components = type_instruction->GetSingleWordInOperand(1);
  481. return FindOrCreateCompositeConstant(
  482. std::vector<uint32_t>(
  483. num_components,
  484. FindOrCreateZeroConstant(component_type_id, is_irrelevant)),
  485. scalar_or_composite_type_id, is_irrelevant);
  486. }
  487. case SpvOpTypeStruct: {
  488. assert(!fuzzerutil::HasBlockOrBufferBlockDecoration(
  489. GetIRContext(), scalar_or_composite_type_id) &&
  490. "We do not construct constants of struct types decorated with "
  491. "Block or BufferBlock.");
  492. std::vector<uint32_t> field_zero_ids;
  493. for (uint32_t index = 0; index < type_instruction->NumInOperands();
  494. index++) {
  495. field_zero_ids.push_back(FindOrCreateZeroConstant(
  496. type_instruction->GetSingleWordInOperand(index), is_irrelevant));
  497. }
  498. return FindOrCreateCompositeConstant(
  499. field_zero_ids, scalar_or_composite_type_id, is_irrelevant);
  500. }
  501. default:
  502. assert(false && "Unknown type.");
  503. return 0;
  504. }
  505. }
  506. void FuzzerPass::MaybeAddUseToReplace(
  507. opt::Instruction* use_inst, uint32_t use_index, uint32_t replacement_id,
  508. std::vector<std::pair<protobufs::IdUseDescriptor, uint32_t>>*
  509. uses_to_replace) {
  510. // Only consider this use if it is in a block
  511. if (!GetIRContext()->get_instr_block(use_inst)) {
  512. return;
  513. }
  514. // Get the index of the operand restricted to input operands.
  515. uint32_t in_operand_index =
  516. fuzzerutil::InOperandIndexFromOperandIndex(*use_inst, use_index);
  517. auto id_use_descriptor =
  518. MakeIdUseDescriptorFromUse(GetIRContext(), use_inst, in_operand_index);
  519. uses_to_replace->emplace_back(
  520. std::make_pair(id_use_descriptor, replacement_id));
  521. }
  522. opt::BasicBlock* FuzzerPass::GetOrCreateSimpleLoopPreheader(
  523. uint32_t header_id) {
  524. auto header_block = fuzzerutil::MaybeFindBlock(GetIRContext(), header_id);
  525. assert(header_block && header_block->IsLoopHeader() &&
  526. "|header_id| should be the label id of a loop header");
  527. auto predecessors = GetIRContext()->cfg()->preds(header_id);
  528. assert(predecessors.size() >= 2 &&
  529. "The block |header_id| should be reachable.");
  530. auto function = header_block->GetParent();
  531. if (predecessors.size() == 2) {
  532. // The header has a single out-of-loop predecessor, which could be a
  533. // preheader.
  534. opt::BasicBlock* maybe_preheader;
  535. if (GetIRContext()->GetDominatorAnalysis(function)->Dominates(
  536. header_id, predecessors[0])) {
  537. // The first predecessor is the back-edge block, because the header
  538. // dominates it, so the second one is out of the loop.
  539. maybe_preheader = &*function->FindBlock(predecessors[1]);
  540. } else {
  541. // The first predecessor is out of the loop.
  542. maybe_preheader = &*function->FindBlock(predecessors[0]);
  543. }
  544. // |maybe_preheader| is a preheader if it branches unconditionally to
  545. // the header. We also require it not to be a loop header.
  546. if (maybe_preheader->terminator()->opcode() == SpvOpBranch &&
  547. !maybe_preheader->IsLoopHeader()) {
  548. return maybe_preheader;
  549. }
  550. }
  551. // We need to add a preheader.
  552. // Get a fresh id for the preheader.
  553. uint32_t preheader_id = GetFuzzerContext()->GetFreshId();
  554. // Get a fresh id for each OpPhi instruction, if there is more than one
  555. // out-of-loop predecessor.
  556. std::vector<uint32_t> phi_ids;
  557. if (predecessors.size() > 2) {
  558. header_block->ForEachPhiInst(
  559. [this, &phi_ids](opt::Instruction* /* unused */) {
  560. phi_ids.push_back(GetFuzzerContext()->GetFreshId());
  561. });
  562. }
  563. // Add the preheader.
  564. ApplyTransformation(
  565. TransformationAddLoopPreheader(header_id, preheader_id, phi_ids));
  566. // Make the newly-created preheader the new entry block.
  567. return &*function->FindBlock(preheader_id);
  568. }
  569. opt::BasicBlock* FuzzerPass::SplitBlockAfterOpPhiOrOpVariable(
  570. uint32_t block_id) {
  571. auto block = fuzzerutil::MaybeFindBlock(GetIRContext(), block_id);
  572. assert(block && "|block_id| must be a block label");
  573. assert(!block->IsLoopHeader() && "|block_id| cannot be a loop header");
  574. // Find the first non-OpPhi and non-OpVariable instruction.
  575. auto non_phi_or_var_inst = &*block->begin();
  576. while (non_phi_or_var_inst->opcode() == SpvOpPhi ||
  577. non_phi_or_var_inst->opcode() == SpvOpVariable) {
  578. non_phi_or_var_inst = non_phi_or_var_inst->NextNode();
  579. }
  580. // Split the block.
  581. uint32_t new_block_id = GetFuzzerContext()->GetFreshId();
  582. ApplyTransformation(TransformationSplitBlock(
  583. MakeInstructionDescriptor(GetIRContext(), non_phi_or_var_inst),
  584. new_block_id));
  585. // We need to return the newly-created block.
  586. return &*block->GetParent()->FindBlock(new_block_id);
  587. }
  588. uint32_t FuzzerPass::FindOrCreateLocalVariable(
  589. uint32_t pointer_type_id, uint32_t function_id,
  590. bool pointee_value_is_irrelevant) {
  591. auto pointer_type = GetIRContext()->get_type_mgr()->GetType(pointer_type_id);
  592. // No unused variables in release mode.
  593. (void)pointer_type;
  594. assert(pointer_type && pointer_type->AsPointer() &&
  595. pointer_type->AsPointer()->storage_class() ==
  596. SpvStorageClassFunction &&
  597. "The pointer_type_id must refer to a defined pointer type with "
  598. "storage class Function");
  599. auto function = fuzzerutil::FindFunction(GetIRContext(), function_id);
  600. assert(function && "The function must be defined.");
  601. // First we try to find a suitable existing variable.
  602. // All of the local variable declarations are located in the first block.
  603. for (auto& instruction : *function->begin()) {
  604. if (instruction.opcode() != SpvOpVariable) {
  605. continue;
  606. }
  607. // The existing OpVariable must have type |pointer_type_id|.
  608. if (instruction.type_id() != pointer_type_id) {
  609. continue;
  610. }
  611. // Check if the found variable is marked with PointeeValueIsIrrelevant
  612. // according to |pointee_value_is_irrelevant|.
  613. if (GetTransformationContext()->GetFactManager()->PointeeValueIsIrrelevant(
  614. instruction.result_id()) != pointee_value_is_irrelevant) {
  615. continue;
  616. }
  617. return instruction.result_id();
  618. }
  619. // No such variable was found. Apply a transformation to get one.
  620. uint32_t pointee_type_id = fuzzerutil::GetPointeeTypeIdFromPointerType(
  621. GetIRContext(), pointer_type_id);
  622. uint32_t result_id = GetFuzzerContext()->GetFreshId();
  623. ApplyTransformation(TransformationAddLocalVariable(
  624. result_id, pointer_type_id, function_id,
  625. FindOrCreateZeroConstant(pointee_type_id, pointee_value_is_irrelevant),
  626. pointee_value_is_irrelevant));
  627. return result_id;
  628. }
  629. uint32_t FuzzerPass::FindOrCreateGlobalVariable(
  630. uint32_t pointer_type_id, bool pointee_value_is_irrelevant) {
  631. auto pointer_type = GetIRContext()->get_type_mgr()->GetType(pointer_type_id);
  632. // No unused variables in release mode.
  633. (void)pointer_type;
  634. assert(
  635. pointer_type && pointer_type->AsPointer() &&
  636. (pointer_type->AsPointer()->storage_class() == SpvStorageClassPrivate ||
  637. pointer_type->AsPointer()->storage_class() ==
  638. SpvStorageClassWorkgroup) &&
  639. "The pointer_type_id must refer to a defined pointer type with storage "
  640. "class Private or Workgroup");
  641. // First we try to find a suitable existing variable.
  642. for (auto& instruction : GetIRContext()->module()->types_values()) {
  643. if (instruction.opcode() != SpvOpVariable) {
  644. continue;
  645. }
  646. // The existing OpVariable must have type |pointer_type_id|.
  647. if (instruction.type_id() != pointer_type_id) {
  648. continue;
  649. }
  650. // Check if the found variable is marked with PointeeValueIsIrrelevant
  651. // according to |pointee_value_is_irrelevant|.
  652. if (GetTransformationContext()->GetFactManager()->PointeeValueIsIrrelevant(
  653. instruction.result_id()) != pointee_value_is_irrelevant) {
  654. continue;
  655. }
  656. return instruction.result_id();
  657. }
  658. // No such variable was found. Apply a transformation to get one.
  659. uint32_t pointee_type_id = fuzzerutil::GetPointeeTypeIdFromPointerType(
  660. GetIRContext(), pointer_type_id);
  661. auto storage_class = fuzzerutil::GetStorageClassFromPointerType(
  662. GetIRContext(), pointer_type_id);
  663. uint32_t result_id = GetFuzzerContext()->GetFreshId();
  664. // A variable with storage class Workgroup shouldn't have an initializer.
  665. if (storage_class == SpvStorageClassWorkgroup) {
  666. ApplyTransformation(TransformationAddGlobalVariable(
  667. result_id, pointer_type_id, SpvStorageClassWorkgroup, 0,
  668. pointee_value_is_irrelevant));
  669. } else {
  670. ApplyTransformation(TransformationAddGlobalVariable(
  671. result_id, pointer_type_id, SpvStorageClassPrivate,
  672. FindOrCreateZeroConstant(pointee_type_id, pointee_value_is_irrelevant),
  673. pointee_value_is_irrelevant));
  674. }
  675. return result_id;
  676. }
  677. } // namespace fuzz
  678. } // namespace spvtools