fuzzer_pass_adjust_selection_controls.cpp 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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_adjust_selection_controls.h"
  15. #include "source/fuzz/transformation_set_selection_control.h"
  16. namespace spvtools {
  17. namespace fuzz {
  18. FuzzerPassAdjustSelectionControls::FuzzerPassAdjustSelectionControls(
  19. opt::IRContext* ir_context, TransformationContext* transformation_context,
  20. FuzzerContext* fuzzer_context,
  21. protobufs::TransformationSequence* transformations)
  22. : FuzzerPass(ir_context, transformation_context, fuzzer_context,
  23. transformations) {}
  24. FuzzerPassAdjustSelectionControls::~FuzzerPassAdjustSelectionControls() =
  25. default;
  26. void FuzzerPassAdjustSelectionControls::Apply() {
  27. // Consider every merge instruction in the module (via looking through all
  28. // functions and blocks).
  29. for (auto& function : *GetIRContext()->module()) {
  30. for (auto& block : function) {
  31. if (auto merge_inst = block.GetMergeInst()) {
  32. // Ignore the instruction if it is not a selection merge.
  33. if (merge_inst->opcode() != SpvOpSelectionMerge) {
  34. continue;
  35. }
  36. // Choose randomly whether to change the selection control for this
  37. // instruction.
  38. if (!GetFuzzerContext()->ChoosePercentage(
  39. GetFuzzerContext()->GetChanceOfAdjustingSelectionControl())) {
  40. continue;
  41. }
  42. // The choices to change the selection control to are the set of valid
  43. // controls, minus the current control.
  44. std::vector<uint32_t> choices;
  45. for (auto control :
  46. {SpvSelectionControlMaskNone, SpvSelectionControlFlattenMask,
  47. SpvSelectionControlDontFlattenMask}) {
  48. if (control == merge_inst->GetSingleWordOperand(1)) {
  49. continue;
  50. }
  51. choices.push_back(control);
  52. }
  53. // Apply the transformation and add it to the output transformation
  54. // sequence.
  55. TransformationSetSelectionControl transformation(
  56. block.id(), choices[GetFuzzerContext()->RandomIndex(choices)]);
  57. ApplyTransformation(transformation);
  58. }
  59. }
  60. }
  61. }
  62. } // namespace fuzz
  63. } // namespace spvtools