reducer.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. // Copyright (c) 2018 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/reduce/reducer.h"
  15. #include <cassert>
  16. #include <sstream>
  17. #include "source/reduce/conditional_branch_to_simple_conditional_branch_opportunity_finder.h"
  18. #include "source/reduce/merge_blocks_reduction_opportunity_finder.h"
  19. #include "source/reduce/operand_to_const_reduction_opportunity_finder.h"
  20. #include "source/reduce/operand_to_dominating_id_reduction_opportunity_finder.h"
  21. #include "source/reduce/operand_to_undef_reduction_opportunity_finder.h"
  22. #include "source/reduce/remove_block_reduction_opportunity_finder.h"
  23. #include "source/reduce/remove_function_reduction_opportunity_finder.h"
  24. #include "source/reduce/remove_selection_reduction_opportunity_finder.h"
  25. #include "source/reduce/remove_unused_instruction_reduction_opportunity_finder.h"
  26. #include "source/reduce/remove_unused_struct_member_reduction_opportunity_finder.h"
  27. #include "source/reduce/simple_conditional_branch_to_branch_opportunity_finder.h"
  28. #include "source/reduce/structured_loop_to_selection_reduction_opportunity_finder.h"
  29. #include "source/spirv_reducer_options.h"
  30. namespace spvtools {
  31. namespace reduce {
  32. Reducer::Reducer(spv_target_env target_env) : target_env_(target_env) {}
  33. Reducer::~Reducer() = default;
  34. void Reducer::SetMessageConsumer(MessageConsumer c) {
  35. for (auto& pass : passes_) {
  36. pass->SetMessageConsumer(c);
  37. }
  38. for (auto& pass : cleanup_passes_) {
  39. pass->SetMessageConsumer(c);
  40. }
  41. consumer_ = std::move(c);
  42. }
  43. void Reducer::SetInterestingnessFunction(
  44. Reducer::InterestingnessFunction interestingness_function) {
  45. interestingness_function_ = std::move(interestingness_function);
  46. }
  47. Reducer::ReductionResultStatus Reducer::Run(
  48. std::vector<uint32_t>&& binary_in, std::vector<uint32_t>* binary_out,
  49. spv_const_reducer_options options,
  50. spv_validator_options validator_options) {
  51. std::vector<uint32_t> current_binary(std::move(binary_in));
  52. spvtools::SpirvTools tools(target_env_);
  53. assert(tools.IsValid() && "Failed to create SPIRV-Tools interface");
  54. // Keeps track of how many reduction attempts have been tried. Reduction
  55. // bails out if this reaches a given limit.
  56. uint32_t reductions_applied = 0;
  57. // Initial state should be valid.
  58. if (!tools.Validate(&current_binary[0], current_binary.size(),
  59. validator_options)) {
  60. consumer_(SPV_MSG_INFO, nullptr, {},
  61. "Initial binary is invalid; stopping.");
  62. return Reducer::ReductionResultStatus::kInitialStateInvalid;
  63. }
  64. // Initial state should be interesting.
  65. if (!interestingness_function_(current_binary, reductions_applied)) {
  66. consumer_(SPV_MSG_INFO, nullptr, {},
  67. "Initial state was not interesting; stopping.");
  68. return Reducer::ReductionResultStatus::kInitialStateNotInteresting;
  69. }
  70. Reducer::ReductionResultStatus result =
  71. RunPasses(&passes_, options, validator_options, tools, &current_binary,
  72. &reductions_applied);
  73. if (result == Reducer::ReductionResultStatus::kComplete) {
  74. // Cleanup passes.
  75. result = RunPasses(&cleanup_passes_, options, validator_options, tools,
  76. &current_binary, &reductions_applied);
  77. }
  78. if (result == Reducer::ReductionResultStatus::kComplete) {
  79. consumer_(SPV_MSG_INFO, nullptr, {}, "No more to reduce; stopping.");
  80. }
  81. // Even if the reduction has failed by this point (e.g. due to producing an
  82. // invalid binary), we still update the output binary for better debugging.
  83. *binary_out = std::move(current_binary);
  84. return result;
  85. }
  86. void Reducer::AddDefaultReductionPasses() {
  87. AddReductionPass(
  88. spvtools::MakeUnique<RemoveUnusedInstructionReductionOpportunityFinder>(
  89. false));
  90. AddReductionPass(
  91. spvtools::MakeUnique<OperandToUndefReductionOpportunityFinder>());
  92. AddReductionPass(
  93. spvtools::MakeUnique<OperandToConstReductionOpportunityFinder>());
  94. AddReductionPass(
  95. spvtools::MakeUnique<OperandToDominatingIdReductionOpportunityFinder>());
  96. AddReductionPass(spvtools::MakeUnique<
  97. StructuredLoopToSelectionReductionOpportunityFinder>());
  98. AddReductionPass(
  99. spvtools::MakeUnique<MergeBlocksReductionOpportunityFinder>());
  100. AddReductionPass(
  101. spvtools::MakeUnique<RemoveFunctionReductionOpportunityFinder>());
  102. AddReductionPass(
  103. spvtools::MakeUnique<RemoveBlockReductionOpportunityFinder>());
  104. AddReductionPass(
  105. spvtools::MakeUnique<RemoveSelectionReductionOpportunityFinder>());
  106. AddReductionPass(
  107. spvtools::MakeUnique<
  108. ConditionalBranchToSimpleConditionalBranchOpportunityFinder>());
  109. AddReductionPass(
  110. spvtools::MakeUnique<SimpleConditionalBranchToBranchOpportunityFinder>());
  111. AddReductionPass(spvtools::MakeUnique<
  112. RemoveUnusedStructMemberReductionOpportunityFinder>());
  113. // Cleanup passes.
  114. AddCleanupReductionPass(
  115. spvtools::MakeUnique<RemoveUnusedInstructionReductionOpportunityFinder>(
  116. true));
  117. }
  118. void Reducer::AddReductionPass(
  119. std::unique_ptr<ReductionOpportunityFinder>&& finder) {
  120. passes_.push_back(
  121. spvtools::MakeUnique<ReductionPass>(target_env_, std::move(finder)));
  122. }
  123. void Reducer::AddCleanupReductionPass(
  124. std::unique_ptr<ReductionOpportunityFinder>&& finder) {
  125. cleanup_passes_.push_back(
  126. spvtools::MakeUnique<ReductionPass>(target_env_, std::move(finder)));
  127. }
  128. bool Reducer::ReachedStepLimit(uint32_t current_step,
  129. spv_const_reducer_options options) {
  130. return current_step >= options->step_limit;
  131. }
  132. Reducer::ReductionResultStatus Reducer::RunPasses(
  133. std::vector<std::unique_ptr<ReductionPass>>* passes,
  134. spv_const_reducer_options options, spv_validator_options validator_options,
  135. const SpirvTools& tools, std::vector<uint32_t>* current_binary,
  136. uint32_t* const reductions_applied) {
  137. // Determines whether, on completing one round of reduction passes, it is
  138. // worthwhile trying a further round.
  139. bool another_round_worthwhile = true;
  140. // Apply round after round of reduction passes until we hit the reduction
  141. // step limit, or deem that another round is not going to be worthwhile.
  142. while (!ReachedStepLimit(*reductions_applied, options) &&
  143. another_round_worthwhile) {
  144. // At the start of a round of reduction passes, assume another round will
  145. // not be worthwhile unless we find evidence to the contrary.
  146. another_round_worthwhile = false;
  147. // Iterate through the available passes.
  148. for (auto& pass : *passes) {
  149. // If this pass hasn't reached its minimum granularity then it's
  150. // worth eventually doing another round of reductions, in order to
  151. // try this pass at a finer granularity.
  152. another_round_worthwhile |= !pass->ReachedMinimumGranularity();
  153. // Keep applying this pass at its current granularity until it stops
  154. // working or we hit the reduction step limit.
  155. consumer_(SPV_MSG_INFO, nullptr, {},
  156. ("Trying pass " + pass->GetName() + ".").c_str());
  157. do {
  158. auto maybe_result = pass->TryApplyReduction(*current_binary);
  159. if (maybe_result.empty()) {
  160. // For this round, the pass has no more opportunities (chunks) to
  161. // apply, so move on to the next pass.
  162. consumer_(
  163. SPV_MSG_INFO, nullptr, {},
  164. ("Pass " + pass->GetName() + " did not make a reduction step.")
  165. .c_str());
  166. break;
  167. }
  168. bool interesting = false;
  169. std::stringstream stringstream;
  170. (*reductions_applied)++;
  171. stringstream << "Pass " << pass->GetName() << " made reduction step "
  172. << *reductions_applied << ".";
  173. consumer_(SPV_MSG_INFO, nullptr, {}, (stringstream.str().c_str()));
  174. if (!tools.Validate(&maybe_result[0], maybe_result.size(),
  175. validator_options)) {
  176. // The reduction step went wrong and an invalid binary was produced.
  177. // By design, this shouldn't happen; this is a safeguard to stop an
  178. // invalid binary from being regarded as interesting.
  179. consumer_(SPV_MSG_INFO, nullptr, {},
  180. "Reduction step produced an invalid binary.");
  181. if (options->fail_on_validation_error) {
  182. // In this mode, we fail, so we update the current binary so it is
  183. // output for debugging.
  184. *current_binary = std::move(maybe_result);
  185. return Reducer::ReductionResultStatus::kStateInvalid;
  186. }
  187. } else if (interestingness_function_(maybe_result,
  188. *reductions_applied)) {
  189. // Success! The binary produced by this reduction step is
  190. // interesting, so make it the binary of interest henceforth, and
  191. // note that it's worth doing another round of reduction passes.
  192. consumer_(SPV_MSG_INFO, nullptr, {}, "Reduction step succeeded.");
  193. *current_binary = std::move(maybe_result);
  194. interesting = true;
  195. another_round_worthwhile = true;
  196. }
  197. // We must call this before the next call to TryApplyReduction.
  198. pass->NotifyInteresting(interesting);
  199. // Bail out if the reduction step limit has been reached.
  200. } while (!ReachedStepLimit(*reductions_applied, options));
  201. }
  202. }
  203. // Report whether reduction completed, or bailed out early due to reaching
  204. // the step limit.
  205. if (ReachedStepLimit(*reductions_applied, options)) {
  206. consumer_(SPV_MSG_INFO, nullptr, {},
  207. "Reached reduction step limit; stopping.");
  208. return Reducer::ReductionResultStatus::kReachedStepLimit;
  209. }
  210. // The passes completed successfully, although we may still run more passes.
  211. return Reducer::ReductionResultStatus::kComplete;
  212. }
  213. } // namespace reduce
  214. } // namespace spvtools