dominator_analysis.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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/opt/dominator_analysis.h"
  15. #include <unordered_set>
  16. #include "source/opt/ir_context.h"
  17. namespace spvtools {
  18. namespace opt {
  19. BasicBlock* DominatorAnalysisBase::CommonDominator(BasicBlock* b1,
  20. BasicBlock* b2) const {
  21. if (!b1 || !b2) return nullptr;
  22. std::unordered_set<BasicBlock*> seen;
  23. BasicBlock* block = b1;
  24. while (block && seen.insert(block).second) {
  25. block = ImmediateDominator(block);
  26. }
  27. block = b2;
  28. while (block && !seen.count(block)) {
  29. block = ImmediateDominator(block);
  30. }
  31. return block;
  32. }
  33. bool DominatorAnalysisBase::Dominates(Instruction* a, Instruction* b) const {
  34. if (!a || !b) {
  35. return false;
  36. }
  37. if (a == b) {
  38. return true;
  39. }
  40. BasicBlock* bb_a = a->context()->get_instr_block(a);
  41. BasicBlock* bb_b = b->context()->get_instr_block(b);
  42. if (bb_a != bb_b) {
  43. return tree_.Dominates(bb_a, bb_b);
  44. }
  45. const Instruction* current = a;
  46. const Instruction* other = b;
  47. if (tree_.IsPostDominator()) {
  48. std::swap(current, other);
  49. }
  50. // We handle OpLabel instructions explicitly since they are not stored in the
  51. // instruction list.
  52. if (current->opcode() == spv::Op::OpLabel) {
  53. return true;
  54. }
  55. while ((current = current->NextNode())) {
  56. if (current == other) {
  57. return true;
  58. }
  59. }
  60. return false;
  61. }
  62. } // namespace opt
  63. } // namespace spvtools