reducer.cpp 10.0 KB

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