1 //===- RegionInfoImpl.h - SESE region detection analysis --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 // Detects single entry single exit regions in the control flow graph.
10 //===----------------------------------------------------------------------===//
12 #ifndef LLVM_ANALYSIS_REGIONINFOIMPL_H
13 #define LLVM_ANALYSIS_REGIONINFOIMPL_H
15 #include "llvm/ADT/PostOrderIterator.h"
16 #include "llvm/Analysis/DominanceFrontier.h"
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/Analysis/PostDominators.h"
19 #include "llvm/Analysis/RegionInfo.h"
20 #include "llvm/Analysis/RegionIterator.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ErrorHandling.h"
29 #define DEBUG_TYPE "region"
31 //===----------------------------------------------------------------------===//
32 /// RegionBase Implementation
34 RegionBase<Tr>::RegionBase(BlockT *Entry, BlockT *Exit,
35 typename Tr::RegionInfoT *RInfo, DomTreeT *dt,
37 : RegionNodeBase<Tr>(Parent, Entry, 1), RI(RInfo), DT(dt), exit(Exit) {}
40 RegionBase<Tr>::~RegionBase() {
41 // Only clean the cache for this Region. Caches of child Regions will be
42 // cleaned when the child Regions are deleted.
47 void RegionBase<Tr>::replaceEntry(BlockT *BB) {
48 this->entry.setPointer(BB);
52 void RegionBase<Tr>::replaceExit(BlockT *BB) {
53 assert(exit && "No exit to replace!");
58 void RegionBase<Tr>::replaceEntryRecursive(BlockT *NewEntry) {
59 std::vector<RegionT *> RegionQueue;
60 BlockT *OldEntry = getEntry();
62 RegionQueue.push_back(static_cast<RegionT *>(this));
63 while (!RegionQueue.empty()) {
64 RegionT *R = RegionQueue.back();
65 RegionQueue.pop_back();
67 R->replaceEntry(NewEntry);
68 for (std::unique_ptr<RegionT> &Child : *R) {
69 if (Child->getEntry() == OldEntry)
70 RegionQueue.push_back(Child.get());
76 void RegionBase<Tr>::replaceExitRecursive(BlockT *NewExit) {
77 std::vector<RegionT *> RegionQueue;
78 BlockT *OldExit = getExit();
80 RegionQueue.push_back(static_cast<RegionT *>(this));
81 while (!RegionQueue.empty()) {
82 RegionT *R = RegionQueue.back();
83 RegionQueue.pop_back();
85 R->replaceExit(NewExit);
86 for (std::unique_ptr<RegionT> &Child : *R) {
87 if (Child->getExit() == OldExit)
88 RegionQueue.push_back(Child.get());
94 bool RegionBase<Tr>::contains(const BlockT *B) const {
95 BlockT *BB = const_cast<BlockT *>(B);
100 BlockT *entry = getEntry(), *exit = getExit();
106 return (DT->dominates(entry, BB) &&
107 !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
111 bool RegionBase<Tr>::contains(const LoopT *L) const {
112 // BBs that are not part of any loop are element of the Loop
113 // described by the NULL pointer. This loop is not part of any region,
114 // except if the region describes the whole function.
116 return getExit() == nullptr;
118 if (!contains(L->getHeader()))
121 SmallVector<BlockT *, 8> ExitingBlocks;
122 L->getExitingBlocks(ExitingBlocks);
124 for (BlockT *BB : ExitingBlocks) {
133 typename Tr::LoopT *RegionBase<Tr>::outermostLoopInRegion(LoopT *L) const {
137 while (L && contains(L->getParentLoop())) {
138 L = L->getParentLoop();
145 typename Tr::LoopT *RegionBase<Tr>::outermostLoopInRegion(LoopInfoT *LI,
147 assert(LI && BB && "LI and BB cannot be null!");
148 LoopT *L = LI->getLoopFor(BB);
149 return outermostLoopInRegion(L);
153 typename RegionBase<Tr>::BlockT *RegionBase<Tr>::getEnteringBlock() const {
154 BlockT *entry = getEntry();
155 BlockT *enteringBlock = nullptr;
157 for (BlockT *Pred : make_range(InvBlockTraits::child_begin(entry),
158 InvBlockTraits::child_end(entry))) {
159 if (DT->getNode(Pred) && !contains(Pred)) {
163 enteringBlock = Pred;
167 return enteringBlock;
171 typename RegionBase<Tr>::BlockT *RegionBase<Tr>::getExitingBlock() const {
172 BlockT *exit = getExit();
173 BlockT *exitingBlock = nullptr;
178 for (BlockT *Pred : make_range(InvBlockTraits::child_begin(exit),
179 InvBlockTraits::child_end(exit))) {
180 if (contains(Pred)) {
192 bool RegionBase<Tr>::isSimple() const {
193 return !isTopLevelRegion() && getEnteringBlock() && getExitingBlock();
197 std::string RegionBase<Tr>::getNameStr() const {
198 std::string exitName;
199 std::string entryName;
201 if (getEntry()->getName().empty()) {
202 raw_string_ostream OS(entryName);
204 getEntry()->printAsOperand(OS, false);
206 entryName = getEntry()->getName();
209 if (getExit()->getName().empty()) {
210 raw_string_ostream OS(exitName);
212 getExit()->printAsOperand(OS, false);
214 exitName = getExit()->getName();
216 exitName = "<Function Return>";
218 return entryName + " => " + exitName;
222 void RegionBase<Tr>::verifyBBInRegion(BlockT *BB) const {
224 llvm_unreachable("Broken region found: enumerated BB not in region!");
226 BlockT *entry = getEntry(), *exit = getExit();
229 make_range(BlockTraits::child_begin(BB), BlockTraits::child_end(BB))) {
230 if (!contains(Succ) && exit != Succ)
231 llvm_unreachable("Broken region found: edges leaving the region must go "
232 "to the exit node!");
236 for (BlockT *Pred : make_range(InvBlockTraits::child_begin(BB),
237 InvBlockTraits::child_end(BB))) {
239 llvm_unreachable("Broken region found: edges entering the region must "
240 "go to the entry node!");
246 void RegionBase<Tr>::verifyWalk(BlockT *BB, std::set<BlockT *> *visited) const {
247 BlockT *exit = getExit();
251 verifyBBInRegion(BB);
254 make_range(BlockTraits::child_begin(BB), BlockTraits::child_end(BB))) {
255 if (Succ != exit && visited->find(Succ) == visited->end())
256 verifyWalk(Succ, visited);
261 void RegionBase<Tr>::verifyRegion() const {
262 // Only do verification when user wants to, otherwise this expensive check
263 // will be invoked by PMDataManager::verifyPreservedAnalysis when
264 // a regionpass (marked PreservedAll) finish.
265 if (!RegionInfoBase<Tr>::VerifyRegionInfo)
268 std::set<BlockT *> visited;
269 verifyWalk(getEntry(), &visited);
273 void RegionBase<Tr>::verifyRegionNest() const {
274 for (const std::unique_ptr<RegionT> &R : *this)
275 R->verifyRegionNest();
281 typename RegionBase<Tr>::element_iterator RegionBase<Tr>::element_begin() {
282 return GraphTraits<RegionT *>::nodes_begin(static_cast<RegionT *>(this));
286 typename RegionBase<Tr>::element_iterator RegionBase<Tr>::element_end() {
287 return GraphTraits<RegionT *>::nodes_end(static_cast<RegionT *>(this));
291 typename RegionBase<Tr>::const_element_iterator
292 RegionBase<Tr>::element_begin() const {
293 return GraphTraits<const RegionT *>::nodes_begin(
294 static_cast<const RegionT *>(this));
298 typename RegionBase<Tr>::const_element_iterator
299 RegionBase<Tr>::element_end() const {
300 return GraphTraits<const RegionT *>::nodes_end(
301 static_cast<const RegionT *>(this));
305 typename Tr::RegionT *RegionBase<Tr>::getSubRegionNode(BlockT *BB) const {
306 typedef typename Tr::RegionT RegionT;
307 RegionT *R = RI->getRegionFor(BB);
312 // If we pass the BB out of this region, that means our code is broken.
313 assert(contains(R) && "BB not in current region!");
315 while (contains(R->getParent()) && R->getParent() != this)
318 if (R->getEntry() != BB)
325 typename Tr::RegionNodeT *RegionBase<Tr>::getBBNode(BlockT *BB) const {
326 assert(contains(BB) && "Can get BB node out of this region!");
328 typename BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
330 if (at == BBNodeMap.end()) {
331 auto Deconst = const_cast<RegionBase<Tr> *>(this);
332 typename BBNodeMapT::value_type V = {
333 BB, make_unique<RegionNodeT>(static_cast<RegionT *>(Deconst), BB)};
334 at = BBNodeMap.insert(std::move(V)).first;
336 return at->second.get();
340 typename Tr::RegionNodeT *RegionBase<Tr>::getNode(BlockT *BB) const {
341 assert(contains(BB) && "Can get BB node out of this region!");
342 if (RegionT *Child = getSubRegionNode(BB))
343 return Child->getNode();
345 return getBBNode(BB);
349 void RegionBase<Tr>::transferChildrenTo(RegionT *To) {
350 for (std::unique_ptr<RegionT> &R : *this) {
352 To->children.push_back(std::move(R));
358 void RegionBase<Tr>::addSubRegion(RegionT *SubRegion, bool moveChildren) {
359 assert(!SubRegion->parent && "SubRegion already has a parent!");
360 assert(find_if(*this,
361 [&](const std::unique_ptr<RegionT> &R) {
362 return R.get() == SubRegion;
363 }) == children.end() &&
364 "Subregion already exists!");
366 SubRegion->parent = static_cast<RegionT *>(this);
367 children.push_back(std::unique_ptr<RegionT>(SubRegion));
372 assert(SubRegion->children.empty() &&
373 "SubRegions that contain children are not supported");
375 for (RegionNodeT *Element : elements()) {
376 if (!Element->isSubRegion()) {
377 BlockT *BB = Element->template getNodeAs<BlockT>();
379 if (SubRegion->contains(BB))
380 RI->setRegionFor(BB, SubRegion);
384 std::vector<std::unique_ptr<RegionT>> Keep;
385 for (std::unique_ptr<RegionT> &R : *this) {
386 if (SubRegion->contains(R.get()) && R.get() != SubRegion) {
387 R->parent = SubRegion;
388 SubRegion->children.push_back(std::move(R));
390 Keep.push_back(std::move(R));
396 std::move_iterator<typename RegionSet::iterator>(Keep.begin()),
397 std::move_iterator<typename RegionSet::iterator>(Keep.end()));
401 typename Tr::RegionT *RegionBase<Tr>::removeSubRegion(RegionT *Child) {
402 assert(Child->parent == this && "Child is not a child of this region!");
403 Child->parent = nullptr;
404 typename RegionSet::iterator I =
405 find_if(children, [&](const std::unique_ptr<RegionT> &R) {
406 return R.get() == Child;
408 assert(I != children.end() && "Region does not exit. Unable to remove.");
409 children.erase(children.begin() + (I - begin()));
414 unsigned RegionBase<Tr>::getDepth() const {
417 for (RegionT *R = getParent(); R != nullptr; R = R->getParent())
424 typename Tr::RegionT *RegionBase<Tr>::getExpandedRegion() const {
425 unsigned NumSuccessors = Tr::getNumSuccessors(exit);
427 if (NumSuccessors == 0)
430 RegionT *R = RI->getRegionFor(exit);
432 if (R->getEntry() != exit) {
433 for (BlockT *Pred : make_range(InvBlockTraits::child_begin(getExit()),
434 InvBlockTraits::child_end(getExit())))
437 if (Tr::getNumSuccessors(exit) == 1)
438 return new RegionT(getEntry(), *BlockTraits::child_begin(exit), RI, DT);
442 while (R->getParent() && R->getParent()->getEntry() == exit)
445 for (BlockT *Pred : make_range(InvBlockTraits::child_begin(getExit()),
446 InvBlockTraits::child_end(getExit()))) {
447 if (!(contains(Pred) || R->contains(Pred)))
451 return new RegionT(getEntry(), R->getExit(), RI, DT);
455 void RegionBase<Tr>::print(raw_ostream &OS, bool print_tree, unsigned level,
456 PrintStyle Style) const {
458 OS.indent(level * 2) << '[' << level << "] " << getNameStr();
460 OS.indent(level * 2) << getNameStr();
464 if (Style != PrintNone) {
465 OS.indent(level * 2) << "{\n";
466 OS.indent(level * 2 + 2);
468 if (Style == PrintBB) {
469 for (const auto *BB : blocks())
470 OS << BB->getName() << ", "; // TODO: remove the last ","
471 } else if (Style == PrintRN) {
472 for (const RegionNodeT *Element : elements()) {
473 OS << *Element << ", "; // TODO: remove the last ",
481 for (const std::unique_ptr<RegionT> &R : *this)
482 R->print(OS, print_tree, level + 1, Style);
485 if (Style != PrintNone)
486 OS.indent(level * 2) << "} \n";
489 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
491 void RegionBase<Tr>::dump() const {
492 print(dbgs(), true, getDepth(), RegionInfoBase<Tr>::printStyle);
497 void RegionBase<Tr>::clearNodeCache() {
499 for (std::unique_ptr<RegionT> &R : *this)
503 //===----------------------------------------------------------------------===//
504 // RegionInfoBase implementation
508 RegionInfoBase<Tr>::RegionInfoBase()
509 : TopLevelRegion(nullptr) {}
512 RegionInfoBase<Tr>::~RegionInfoBase() {
517 void RegionInfoBase<Tr>::verifyBBMap(const RegionT *R) const {
518 assert(R && "Re must be non-null");
519 for (const typename Tr::RegionNodeT *Element : R->elements()) {
520 if (Element->isSubRegion()) {
521 const RegionT *SR = Element->template getNodeAs<RegionT>();
524 BlockT *BB = Element->template getNodeAs<BlockT>();
525 if (getRegionFor(BB) != R)
526 llvm_unreachable("BB map does not match region nesting");
532 bool RegionInfoBase<Tr>::isCommonDomFrontier(BlockT *BB, BlockT *entry,
533 BlockT *exit) const {
534 for (BlockT *P : make_range(InvBlockTraits::child_begin(BB),
535 InvBlockTraits::child_end(BB))) {
536 if (DT->dominates(entry, P) && !DT->dominates(exit, P))
544 bool RegionInfoBase<Tr>::isRegion(BlockT *entry, BlockT *exit) const {
545 assert(entry && exit && "entry and exit must not be null!");
546 typedef typename DomFrontierT::DomSetType DST;
548 DST *entrySuccs = &DF->find(entry)->second;
550 // Exit is the header of a loop that contains the entry. In this case,
551 // the dominance frontier must only contain the exit.
552 if (!DT->dominates(entry, exit)) {
553 for (typename DST::iterator SI = entrySuccs->begin(),
554 SE = entrySuccs->end();
556 if (*SI != exit && *SI != entry)
563 DST *exitSuccs = &DF->find(exit)->second;
565 // Do not allow edges leaving the region.
566 for (BlockT *Succ : *entrySuccs) {
567 if (Succ == exit || Succ == entry)
569 if (exitSuccs->find(Succ) == exitSuccs->end())
571 if (!isCommonDomFrontier(Succ, entry, exit))
575 // Do not allow edges pointing into the region.
576 for (BlockT *Succ : *exitSuccs) {
577 if (DT->properlyDominates(entry, Succ) && Succ != exit)
585 void RegionInfoBase<Tr>::insertShortCut(BlockT *entry, BlockT *exit,
586 BBtoBBMap *ShortCut) const {
587 assert(entry && exit && "entry and exit must not be null!");
589 typename BBtoBBMap::iterator e = ShortCut->find(exit);
591 if (e == ShortCut->end())
592 // No further region at exit available.
593 (*ShortCut)[entry] = exit;
595 // We found a region e that starts at exit. Therefore (entry, e->second)
596 // is also a region, that is larger than (entry, exit). Insert the
598 BlockT *BB = e->second;
599 (*ShortCut)[entry] = BB;
604 typename Tr::DomTreeNodeT *
605 RegionInfoBase<Tr>::getNextPostDom(DomTreeNodeT *N, BBtoBBMap *ShortCut) const {
606 typename BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
608 if (e == ShortCut->end())
611 return PDT->getNode(e->second)->getIDom();
615 bool RegionInfoBase<Tr>::isTrivialRegion(BlockT *entry, BlockT *exit) const {
616 assert(entry && exit && "entry and exit must not be null!");
618 unsigned num_successors =
619 BlockTraits::child_end(entry) - BlockTraits::child_begin(entry);
621 if (num_successors <= 1 && exit == *(BlockTraits::child_begin(entry)))
628 typename Tr::RegionT *RegionInfoBase<Tr>::createRegion(BlockT *entry,
630 assert(entry && exit && "entry and exit must not be null!");
632 if (isTrivialRegion(entry, exit))
636 new RegionT(entry, exit, static_cast<RegionInfoT *>(this), DT);
637 BBtoRegion.insert({entry, region});
639 #ifdef EXPENSIVE_CHECKS
640 region->verifyRegion();
642 DEBUG(region->verifyRegion());
645 updateStatistics(region);
650 void RegionInfoBase<Tr>::findRegionsWithEntry(BlockT *entry,
651 BBtoBBMap *ShortCut) {
654 DomTreeNodeT *N = PDT->getNode(entry);
658 RegionT *lastRegion = nullptr;
659 BlockT *lastExit = entry;
661 // As only a BasicBlock that postdominates entry can finish a region, walk the
662 // post dominance tree upwards.
663 while ((N = getNextPostDom(N, ShortCut))) {
664 BlockT *exit = N->getBlock();
669 if (isRegion(entry, exit)) {
670 RegionT *newRegion = createRegion(entry, exit);
673 newRegion->addSubRegion(lastRegion);
675 lastRegion = newRegion;
679 // This can never be a region, so stop the search.
680 if (!DT->dominates(entry, exit))
684 // Tried to create regions from entry to lastExit. Next time take a
685 // shortcut from entry to lastExit.
686 if (lastExit != entry)
687 insertShortCut(entry, lastExit, ShortCut);
691 void RegionInfoBase<Tr>::scanForRegions(FuncT &F, BBtoBBMap *ShortCut) {
692 typedef typename std::add_pointer<FuncT>::type FuncPtrT;
693 BlockT *entry = GraphTraits<FuncPtrT>::getEntryNode(&F);
694 DomTreeNodeT *N = DT->getNode(entry);
696 // Iterate over the dominance tree in post order to start with the small
697 // regions from the bottom of the dominance tree. If the small regions are
698 // detected first, detection of bigger regions is faster, as we can jump
699 // over the small regions.
700 for (auto DomNode : post_order(N))
701 findRegionsWithEntry(DomNode->getBlock(), ShortCut);
705 typename Tr::RegionT *RegionInfoBase<Tr>::getTopMostParent(RegionT *region) {
706 while (region->getParent())
707 region = region->getParent();
713 void RegionInfoBase<Tr>::buildRegionsTree(DomTreeNodeT *N, RegionT *region) {
714 BlockT *BB = N->getBlock();
716 // Passed region exit
717 while (BB == region->getExit())
718 region = region->getParent();
720 typename BBtoRegionMap::iterator it = BBtoRegion.find(BB);
722 // This basic block is a start block of a region. It is already in the
723 // BBtoRegion relation. Only the child basic blocks have to be updated.
724 if (it != BBtoRegion.end()) {
725 RegionT *newRegion = it->second;
726 region->addSubRegion(getTopMostParent(newRegion));
729 BBtoRegion[BB] = region;
732 for (DomTreeNodeBase<BlockT> *C : *N) {
733 buildRegionsTree(C, region);
737 #ifdef EXPENSIVE_CHECKS
739 bool RegionInfoBase<Tr>::VerifyRegionInfo = true;
742 bool RegionInfoBase<Tr>::VerifyRegionInfo = false;
746 typename Tr::RegionT::PrintStyle RegionInfoBase<Tr>::printStyle =
747 RegionBase<Tr>::PrintNone;
750 void RegionInfoBase<Tr>::print(raw_ostream &OS) const {
751 OS << "Region tree:\n";
752 TopLevelRegion->print(OS, true, 0, printStyle);
753 OS << "End region tree\n";
756 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
758 void RegionInfoBase<Tr>::dump() const { print(dbgs()); }
762 void RegionInfoBase<Tr>::releaseMemory() {
765 delete TopLevelRegion;
766 TopLevelRegion = nullptr;
770 void RegionInfoBase<Tr>::verifyAnalysis() const {
771 // Do only verify regions if explicitely activated using EXPENSIVE_CHECKS or
772 // -verify-region-info
773 if (!RegionInfoBase<Tr>::VerifyRegionInfo)
776 TopLevelRegion->verifyRegionNest();
778 verifyBBMap(TopLevelRegion);
781 // Region pass manager support.
783 typename Tr::RegionT *RegionInfoBase<Tr>::getRegionFor(BlockT *BB) const {
784 typename BBtoRegionMap::const_iterator I = BBtoRegion.find(BB);
785 return I != BBtoRegion.end() ? I->second : nullptr;
789 void RegionInfoBase<Tr>::setRegionFor(BlockT *BB, RegionT *R) {
794 typename Tr::RegionT *RegionInfoBase<Tr>::operator[](BlockT *BB) const {
795 return getRegionFor(BB);
799 typename RegionInfoBase<Tr>::BlockT *
800 RegionInfoBase<Tr>::getMaxRegionExit(BlockT *BB) const {
801 BlockT *Exit = nullptr;
804 // Get largest region that starts at BB.
805 RegionT *R = getRegionFor(BB);
806 while (R && R->getParent() && R->getParent()->getEntry() == BB)
809 // Get the single exit of BB.
810 if (R && R->getEntry() == BB)
812 else if (++BlockTraits::child_begin(BB) == BlockTraits::child_end(BB))
813 Exit = *BlockTraits::child_begin(BB);
814 else // No single exit exists.
817 // Get largest region that starts at Exit.
818 RegionT *ExitR = getRegionFor(Exit);
819 while (ExitR && ExitR->getParent() &&
820 ExitR->getParent()->getEntry() == Exit)
821 ExitR = ExitR->getParent();
823 for (BlockT *Pred : make_range(InvBlockTraits::child_begin(Exit),
824 InvBlockTraits::child_end(Exit))) {
825 if (!R->contains(Pred) && !ExitR->contains(Pred))
829 // This stops infinite cycles.
830 if (DT->dominates(Exit, BB))
840 typename Tr::RegionT *RegionInfoBase<Tr>::getCommonRegion(RegionT *A,
842 assert(A && B && "One of the Regions is NULL");
847 while (!B->contains(A))
854 typename Tr::RegionT *
855 RegionInfoBase<Tr>::getCommonRegion(SmallVectorImpl<RegionT *> &Regions) const {
856 RegionT *ret = Regions.back();
859 for (RegionT *R : Regions)
860 ret = getCommonRegion(ret, R);
866 typename Tr::RegionT *
867 RegionInfoBase<Tr>::getCommonRegion(SmallVectorImpl<BlockT *> &BBs) const {
868 RegionT *ret = getRegionFor(BBs.back());
871 for (BlockT *BB : BBs)
872 ret = getCommonRegion(ret, getRegionFor(BB));
878 void RegionInfoBase<Tr>::calculate(FuncT &F) {
879 typedef typename std::add_pointer<FuncT>::type FuncPtrT;
881 // ShortCut a function where for every BB the exit of the largest region
882 // starting with BB is stored. These regions can be threated as single BBS.
883 // This improves performance on linear CFGs.
886 scanForRegions(F, &ShortCut);
887 BlockT *BB = GraphTraits<FuncPtrT>::getEntryNode(&F);
888 buildRegionsTree(DT->getNode(BB), TopLevelRegion);
893 } // end namespace llvm