fuzzer_pass.cpp 31 KB

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