local_redundancy_elimination.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright (c) 2017 Google Inc.
  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/opt/local_redundancy_elimination.h"
  15. #include "source/opt/value_number_table.h"
  16. namespace spvtools {
  17. namespace opt {
  18. Pass::Status LocalRedundancyEliminationPass::Process() {
  19. bool modified = false;
  20. ValueNumberTable vnTable(context());
  21. for (auto& func : *get_module()) {
  22. for (auto& bb : func) {
  23. // Keeps track of all ids that contain a given value number. We keep
  24. // track of multiple values because they could have the same value, but
  25. // different decorations.
  26. std::map<uint32_t, uint32_t> value_to_ids;
  27. if (EliminateRedundanciesInBB(&bb, vnTable, &value_to_ids))
  28. modified = true;
  29. }
  30. }
  31. return (modified ? Status::SuccessWithChange : Status::SuccessWithoutChange);
  32. }
  33. bool LocalRedundancyEliminationPass::EliminateRedundanciesInBB(
  34. BasicBlock* block, const ValueNumberTable& vnTable,
  35. std::map<uint32_t, uint32_t>* value_to_ids) {
  36. bool modified = false;
  37. auto func = [this, &vnTable, &modified, value_to_ids](Instruction* inst) {
  38. if (inst->result_id() == 0) {
  39. return;
  40. }
  41. uint32_t value = vnTable.GetValueNumber(inst);
  42. if (value == 0) {
  43. return;
  44. }
  45. auto candidate = value_to_ids->insert({value, inst->result_id()});
  46. if (!candidate.second) {
  47. context()->KillNamesAndDecorates(inst);
  48. context()->ReplaceAllUsesWith(inst->result_id(), candidate.first->second);
  49. context()->KillInst(inst);
  50. modified = true;
  51. }
  52. };
  53. block->ForEachInst(func);
  54. return modified;
  55. }
  56. } // namespace opt
  57. } // namespace spvtools