1 //===- RegionInfo.cpp - SESE region detection analysis --------------------===//
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 #define DEBUG_TYPE "region"
13 #include "llvm/Analysis/RegionInfo.h"
14 #include "llvm/ADT/PostOrderIterator.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/LoopInfo.h"
17 #include "llvm/Analysis/RegionIterator.h"
18 #include "llvm/Assembly/Writer.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/Debug.h"
27 // Always verify if expensive checking is enabled.
29 static bool VerifyRegionInfo = true;
31 static bool VerifyRegionInfo = false;
34 static cl::opt<bool,true>
35 VerifyRegionInfoX("verify-region-info", cl::location(VerifyRegionInfo),
36 cl::desc("Verify region info (time consuming)"));
38 STATISTIC(numRegions, "The # of regions");
39 STATISTIC(numSimpleRegions, "The # of simple regions");
41 static cl::opt<enum Region::PrintStyle> printStyle("print-region-style",
43 cl::desc("style of printing regions"),
45 clEnumValN(Region::PrintNone, "none", "print no details"),
46 clEnumValN(Region::PrintBB, "bb",
47 "print regions in detail with block_iterator"),
48 clEnumValN(Region::PrintRN, "rn",
49 "print regions in detail with element_iterator"),
51 //===----------------------------------------------------------------------===//
52 /// Region Implementation
53 Region::Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RInfo,
54 DominatorTree *dt, Region *Parent)
55 : RegionNode(Parent, Entry, 1), RI(RInfo), DT(dt), exit(Exit) {}
58 // Free the cached nodes.
59 for (BBNodeMapT::iterator it = BBNodeMap.begin(),
60 ie = BBNodeMap.end(); it != ie; ++it)
63 // Only clean the cache for this Region. Caches of child Regions will be
64 // cleaned when the child Regions are deleted.
67 for (iterator I = begin(), E = end(); I != E; ++I)
71 void Region::replaceEntry(BasicBlock *BB) {
75 void Region::replaceExit(BasicBlock *BB) {
76 assert(exit && "No exit to replace!");
80 void Region::replaceEntryRecursive(BasicBlock *NewEntry) {
81 std::vector<Region *> RegionQueue;
82 BasicBlock *OldEntry = getEntry();
84 RegionQueue.push_back(this);
85 while (!RegionQueue.empty()) {
86 Region *R = RegionQueue.back();
87 RegionQueue.pop_back();
89 R->replaceEntry(NewEntry);
90 for (Region::const_iterator RI = R->begin(), RE = R->end(); RI != RE; ++RI)
91 if ((*RI)->getEntry() == OldEntry)
92 RegionQueue.push_back(*RI);
96 void Region::replaceExitRecursive(BasicBlock *NewExit) {
97 std::vector<Region *> RegionQueue;
98 BasicBlock *OldExit = getExit();
100 RegionQueue.push_back(this);
101 while (!RegionQueue.empty()) {
102 Region *R = RegionQueue.back();
103 RegionQueue.pop_back();
105 R->replaceExit(NewExit);
106 for (Region::const_iterator RI = R->begin(), RE = R->end(); RI != RE; ++RI)
107 if ((*RI)->getExit() == OldExit)
108 RegionQueue.push_back(*RI);
112 bool Region::contains(const BasicBlock *B) const {
113 BasicBlock *BB = const_cast<BasicBlock*>(B);
115 if (!DT->getNode(BB))
118 BasicBlock *entry = getEntry(), *exit = getExit();
124 return (DT->dominates(entry, BB)
125 && !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
128 bool Region::contains(const Loop *L) const {
129 // BBs that are not part of any loop are element of the Loop
130 // described by the NULL pointer. This loop is not part of any region,
131 // except if the region describes the whole function.
133 return getExit() == 0;
135 if (!contains(L->getHeader()))
138 SmallVector<BasicBlock *, 8> ExitingBlocks;
139 L->getExitingBlocks(ExitingBlocks);
141 for (SmallVectorImpl<BasicBlock*>::iterator BI = ExitingBlocks.begin(),
142 BE = ExitingBlocks.end(); BI != BE; ++BI)
149 Loop *Region::outermostLoopInRegion(Loop *L) const {
153 while (L && contains(L->getParentLoop())) {
154 L = L->getParentLoop();
160 Loop *Region::outermostLoopInRegion(LoopInfo *LI, BasicBlock* BB) const {
161 assert(LI && BB && "LI and BB cannot be null!");
162 Loop *L = LI->getLoopFor(BB);
163 return outermostLoopInRegion(L);
166 BasicBlock *Region::getEnteringBlock() const {
167 BasicBlock *entry = getEntry();
169 BasicBlock *enteringBlock = 0;
171 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
174 if (DT->getNode(Pred) && !contains(Pred)) {
178 enteringBlock = Pred;
182 return enteringBlock;
185 BasicBlock *Region::getExitingBlock() const {
186 BasicBlock *exit = getExit();
188 BasicBlock *exitingBlock = 0;
193 for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
196 if (contains(Pred)) {
207 bool Region::isSimple() const {
208 return !isTopLevelRegion() && getEnteringBlock() && getExitingBlock();
211 std::string Region::getNameStr() const {
212 std::string exitName;
213 std::string entryName;
215 if (getEntry()->getName().empty()) {
216 raw_string_ostream OS(entryName);
218 WriteAsOperand(OS, getEntry(), false);
220 entryName = getEntry()->getName();
223 if (getExit()->getName().empty()) {
224 raw_string_ostream OS(exitName);
226 WriteAsOperand(OS, getExit(), false);
228 exitName = getExit()->getName();
230 exitName = "<Function Return>";
232 return entryName + " => " + exitName;
235 void Region::verifyBBInRegion(BasicBlock *BB) const {
237 llvm_unreachable("Broken region found!");
239 BasicBlock *entry = getEntry(), *exit = getExit();
241 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
242 if (!contains(*SI) && exit != *SI)
243 llvm_unreachable("Broken region found!");
246 for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB); SI != SE; ++SI)
248 llvm_unreachable("Broken region found!");
251 void Region::verifyWalk(BasicBlock *BB, std::set<BasicBlock*> *visited) const {
252 BasicBlock *exit = getExit();
256 verifyBBInRegion(BB);
258 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
259 if (*SI != exit && visited->find(*SI) == visited->end())
260 verifyWalk(*SI, visited);
263 void Region::verifyRegion() const {
264 // Only do verification when user wants to, otherwise this expensive
265 // check will be invoked by PassManager.
266 if (!VerifyRegionInfo) return;
268 std::set<BasicBlock*> visited;
269 verifyWalk(getEntry(), &visited);
272 void Region::verifyRegionNest() const {
273 for (Region::const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
274 (*RI)->verifyRegionNest();
279 Region::element_iterator Region::element_begin() {
280 return GraphTraits<Region*>::nodes_begin(this);
283 Region::element_iterator Region::element_end() {
284 return GraphTraits<Region*>::nodes_end(this);
287 Region::const_element_iterator Region::element_begin() const {
288 return GraphTraits<const Region*>::nodes_begin(this);
291 Region::const_element_iterator Region::element_end() const {
292 return GraphTraits<const Region*>::nodes_end(this);
295 Region* Region::getSubRegionNode(BasicBlock *BB) const {
296 Region *R = RI->getRegionFor(BB);
301 // If we pass the BB out of this region, that means our code is broken.
302 assert(contains(R) && "BB not in current region!");
304 while (contains(R->getParent()) && R->getParent() != this)
307 if (R->getEntry() != BB)
313 RegionNode* Region::getBBNode(BasicBlock *BB) const {
314 assert(contains(BB) && "Can get BB node out of this region!");
316 BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
318 if (at != BBNodeMap.end())
321 RegionNode *NewNode = new RegionNode(const_cast<Region*>(this), BB);
322 BBNodeMap.insert(std::make_pair(BB, NewNode));
326 RegionNode* Region::getNode(BasicBlock *BB) const {
327 assert(contains(BB) && "Can get BB node out of this region!");
328 if (Region* Child = getSubRegionNode(BB))
329 return Child->getNode();
331 return getBBNode(BB);
334 void Region::transferChildrenTo(Region *To) {
335 for (iterator I = begin(), E = end(); I != E; ++I) {
337 To->children.push_back(*I);
342 void Region::addSubRegion(Region *SubRegion, bool moveChildren) {
343 assert(SubRegion->parent == 0 && "SubRegion already has a parent!");
344 assert(std::find(begin(), end(), SubRegion) == children.end()
345 && "Subregion already exists!");
347 SubRegion->parent = this;
348 children.push_back(SubRegion);
353 assert(SubRegion->children.size() == 0
354 && "SubRegions that contain children are not supported");
356 for (element_iterator I = element_begin(), E = element_end(); I != E; ++I)
357 if (!(*I)->isSubRegion()) {
358 BasicBlock *BB = (*I)->getNodeAs<BasicBlock>();
360 if (SubRegion->contains(BB))
361 RI->setRegionFor(BB, SubRegion);
364 std::vector<Region*> Keep;
365 for (iterator I = begin(), E = end(); I != E; ++I)
366 if (SubRegion->contains(*I) && *I != SubRegion) {
367 SubRegion->children.push_back(*I);
368 (*I)->parent = SubRegion;
373 children.insert(children.begin(), Keep.begin(), Keep.end());
377 Region *Region::removeSubRegion(Region *Child) {
378 assert(Child->parent == this && "Child is not a child of this region!");
380 RegionSet::iterator I = std::find(children.begin(), children.end(), Child);
381 assert(I != children.end() && "Region does not exit. Unable to remove.");
382 children.erase(children.begin()+(I-begin()));
386 unsigned Region::getDepth() const {
389 for (Region *R = parent; R != 0; R = R->parent)
395 Region *Region::getExpandedRegion() const {
396 unsigned NumSuccessors = exit->getTerminator()->getNumSuccessors();
398 if (NumSuccessors == 0)
401 for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
403 if (!DT->dominates(getEntry(), *PI))
406 Region *R = RI->getRegionFor(exit);
408 if (R->getEntry() != exit) {
409 if (exit->getTerminator()->getNumSuccessors() == 1)
410 return new Region(getEntry(), *succ_begin(exit), RI, DT);
415 while (R->getParent() && R->getParent()->getEntry() == exit)
418 if (!DT->dominates(getEntry(), R->getExit()))
419 for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
421 if (!DT->dominates(R->getExit(), *PI))
424 return new Region(getEntry(), R->getExit(), RI, DT);
427 void Region::print(raw_ostream &OS, bool print_tree, unsigned level,
428 enum PrintStyle Style) const {
430 OS.indent(level*2) << "[" << level << "] " << getNameStr();
432 OS.indent(level*2) << getNameStr();
437 if (Style != PrintNone) {
438 OS.indent(level*2) << "{\n";
439 OS.indent(level*2 + 2);
441 if (Style == PrintBB) {
442 for (const_block_iterator I = block_begin(), E = block_end(); I != E; ++I)
443 OS << (*I)->getName() << ", "; // TODO: remove the last ","
444 } else if (Style == PrintRN) {
445 for (const_element_iterator I = element_begin(), E = element_end(); I!=E; ++I)
446 OS << **I << ", "; // TODO: remove the last ",
453 for (const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
454 (*RI)->print(OS, print_tree, level+1, Style);
456 if (Style != PrintNone)
457 OS.indent(level*2) << "} \n";
460 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
461 void Region::dump() const {
462 print(dbgs(), true, getDepth(), printStyle.getValue());
466 void Region::clearNodeCache() {
467 // Free the cached nodes.
468 for (BBNodeMapT::iterator I = BBNodeMap.begin(),
469 IE = BBNodeMap.end(); I != IE; ++I)
473 for (Region::iterator RI = begin(), RE = end(); RI != RE; ++RI)
474 (*RI)->clearNodeCache();
477 //===----------------------------------------------------------------------===//
478 // RegionInfo implementation
481 bool RegionInfo::isCommonDomFrontier(BasicBlock *BB, BasicBlock *entry,
482 BasicBlock *exit) const {
483 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
485 if (DT->dominates(entry, P) && !DT->dominates(exit, P))
491 bool RegionInfo::isRegion(BasicBlock *entry, BasicBlock *exit) const {
492 assert(entry && exit && "entry and exit must not be null!");
493 typedef DominanceFrontier::DomSetType DST;
495 DST *entrySuccs = &DF->find(entry)->second;
497 // Exit is the header of a loop that contains the entry. In this case,
498 // the dominance frontier must only contain the exit.
499 if (!DT->dominates(entry, exit)) {
500 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
502 if (*SI != exit && *SI != entry)
508 DST *exitSuccs = &DF->find(exit)->second;
510 // Do not allow edges leaving the region.
511 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
513 if (*SI == exit || *SI == entry)
515 if (exitSuccs->find(*SI) == exitSuccs->end())
517 if (!isCommonDomFrontier(*SI, entry, exit))
521 // Do not allow edges pointing into the region.
522 for (DST::iterator SI = exitSuccs->begin(), SE = exitSuccs->end();
524 if (DT->properlyDominates(entry, *SI) && *SI != exit)
531 void RegionInfo::insertShortCut(BasicBlock *entry, BasicBlock *exit,
532 BBtoBBMap *ShortCut) const {
533 assert(entry && exit && "entry and exit must not be null!");
535 BBtoBBMap::iterator e = ShortCut->find(exit);
537 if (e == ShortCut->end())
538 // No further region at exit available.
539 (*ShortCut)[entry] = exit;
541 // We found a region e that starts at exit. Therefore (entry, e->second)
542 // is also a region, that is larger than (entry, exit). Insert the
544 BasicBlock *BB = e->second;
545 (*ShortCut)[entry] = BB;
549 DomTreeNode* RegionInfo::getNextPostDom(DomTreeNode* N,
550 BBtoBBMap *ShortCut) const {
551 BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
553 if (e == ShortCut->end())
556 return PDT->getNode(e->second)->getIDom();
559 bool RegionInfo::isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const {
560 assert(entry && exit && "entry and exit must not be null!");
562 unsigned num_successors = succ_end(entry) - succ_begin(entry);
564 if (num_successors <= 1 && exit == *(succ_begin(entry)))
570 void RegionInfo::updateStatistics(Region *R) {
573 // TODO: Slow. Should only be enabled if -stats is used.
574 if (R->isSimple()) ++numSimpleRegions;
577 Region *RegionInfo::createRegion(BasicBlock *entry, BasicBlock *exit) {
578 assert(entry && exit && "entry and exit must not be null!");
580 if (isTrivialRegion(entry, exit))
583 Region *region = new Region(entry, exit, this, DT);
584 BBtoRegion.insert(std::make_pair(entry, region));
587 region->verifyRegion();
589 DEBUG(region->verifyRegion());
592 updateStatistics(region);
596 void RegionInfo::findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut) {
599 DomTreeNode *N = PDT->getNode(entry);
604 Region *lastRegion= 0;
605 BasicBlock *lastExit = entry;
607 // As only a BasicBlock that postdominates entry can finish a region, walk the
608 // post dominance tree upwards.
609 while ((N = getNextPostDom(N, ShortCut))) {
610 BasicBlock *exit = N->getBlock();
615 if (isRegion(entry, exit)) {
616 Region *newRegion = createRegion(entry, exit);
619 newRegion->addSubRegion(lastRegion);
621 lastRegion = newRegion;
625 // This can never be a region, so stop the search.
626 if (!DT->dominates(entry, exit))
630 // Tried to create regions from entry to lastExit. Next time take a
631 // shortcut from entry to lastExit.
632 if (lastExit != entry)
633 insertShortCut(entry, lastExit, ShortCut);
636 void RegionInfo::scanForRegions(Function &F, BBtoBBMap *ShortCut) {
637 BasicBlock *entry = &(F.getEntryBlock());
638 DomTreeNode *N = DT->getNode(entry);
640 // Iterate over the dominance tree in post order to start with the small
641 // regions from the bottom of the dominance tree. If the small regions are
642 // detected first, detection of bigger regions is faster, as we can jump
643 // over the small regions.
644 for (po_iterator<DomTreeNode*> FI = po_begin(N), FE = po_end(N); FI != FE;
646 findRegionsWithEntry(FI->getBlock(), ShortCut);
650 Region *RegionInfo::getTopMostParent(Region *region) {
651 while (region->parent)
652 region = region->getParent();
657 void RegionInfo::buildRegionsTree(DomTreeNode *N, Region *region) {
658 BasicBlock *BB = N->getBlock();
660 // Passed region exit
661 while (BB == region->getExit())
662 region = region->getParent();
664 BBtoRegionMap::iterator it = BBtoRegion.find(BB);
666 // This basic block is a start block of a region. It is already in the
667 // BBtoRegion relation. Only the child basic blocks have to be updated.
668 if (it != BBtoRegion.end()) {
669 Region *newRegion = it->second;
670 region->addSubRegion(getTopMostParent(newRegion));
673 BBtoRegion[BB] = region;
676 for (DomTreeNode::iterator CI = N->begin(), CE = N->end(); CI != CE; ++CI)
677 buildRegionsTree(*CI, region);
680 void RegionInfo::releaseMemory() {
683 delete TopLevelRegion;
687 RegionInfo::RegionInfo() : FunctionPass(ID) {
688 initializeRegionInfoPass(*PassRegistry::getPassRegistry());
692 RegionInfo::~RegionInfo() {
696 void RegionInfo::Calculate(Function &F) {
697 // ShortCut a function where for every BB the exit of the largest region
698 // starting with BB is stored. These regions can be threated as single BBS.
699 // This improves performance on linear CFGs.
702 scanForRegions(F, &ShortCut);
703 BasicBlock *BB = &F.getEntryBlock();
704 buildRegionsTree(DT->getNode(BB), TopLevelRegion);
707 bool RegionInfo::runOnFunction(Function &F) {
710 DT = &getAnalysis<DominatorTree>();
711 PDT = &getAnalysis<PostDominatorTree>();
712 DF = &getAnalysis<DominanceFrontier>();
714 TopLevelRegion = new Region(&F.getEntryBlock(), 0, this, DT, 0);
715 updateStatistics(TopLevelRegion);
722 void RegionInfo::getAnalysisUsage(AnalysisUsage &AU) const {
723 AU.setPreservesAll();
724 AU.addRequiredTransitive<DominatorTree>();
725 AU.addRequired<PostDominatorTree>();
726 AU.addRequired<DominanceFrontier>();
729 void RegionInfo::print(raw_ostream &OS, const Module *) const {
730 OS << "Region tree:\n";
731 TopLevelRegion->print(OS, true, 0, printStyle.getValue());
732 OS << "End region tree\n";
735 void RegionInfo::verifyAnalysis() const {
736 // Only do verification when user wants to, otherwise this expensive check
737 // will be invoked by PMDataManager::verifyPreservedAnalysis when
738 // a regionpass (marked PreservedAll) finish.
739 if (!VerifyRegionInfo) return;
741 TopLevelRegion->verifyRegionNest();
744 // Region pass manager support.
745 Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
746 BBtoRegionMap::const_iterator I=
748 return I != BBtoRegion.end() ? I->second : 0;
751 void RegionInfo::setRegionFor(BasicBlock *BB, Region *R) {
755 Region *RegionInfo::operator[](BasicBlock *BB) const {
756 return getRegionFor(BB);
759 BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
760 BasicBlock *Exit = NULL;
763 // Get largest region that starts at BB.
764 Region *R = getRegionFor(BB);
765 while (R && R->getParent() && R->getParent()->getEntry() == BB)
768 // Get the single exit of BB.
769 if (R && R->getEntry() == BB)
771 else if (++succ_begin(BB) == succ_end(BB))
772 Exit = *succ_begin(BB);
773 else // No single exit exists.
776 // Get largest region that starts at Exit.
777 Region *ExitR = getRegionFor(Exit);
778 while (ExitR && ExitR->getParent()
779 && ExitR->getParent()->getEntry() == Exit)
780 ExitR = ExitR->getParent();
782 for (pred_iterator PI = pred_begin(Exit), PE = pred_end(Exit); PI != PE;
784 if (!R->contains(*PI) && !ExitR->contains(*PI))
787 // This stops infinite cycles.
788 if (DT->dominates(Exit, BB))
798 RegionInfo::getCommonRegion(Region *A, Region *B) const {
799 assert (A && B && "One of the Regions is NULL");
801 if (A->contains(B)) return A;
803 while (!B->contains(A))
810 RegionInfo::getCommonRegion(SmallVectorImpl<Region*> &Regions) const {
811 Region* ret = Regions.back();
814 for (SmallVectorImpl<Region*>::const_iterator I = Regions.begin(),
815 E = Regions.end(); I != E; ++I)
816 ret = getCommonRegion(ret, *I);
822 RegionInfo::getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const {
823 Region* ret = getRegionFor(BBs.back());
826 for (SmallVectorImpl<BasicBlock*>::const_iterator I = BBs.begin(),
827 E = BBs.end(); I != E; ++I)
828 ret = getCommonRegion(ret, getRegionFor(*I));
833 void RegionInfo::splitBlock(BasicBlock* NewBB, BasicBlock *OldBB)
835 Region *R = getRegionFor(OldBB);
837 setRegionFor(NewBB, R);
839 while (R->getEntry() == OldBB && !R->isTopLevelRegion()) {
840 R->replaceEntry(NewBB);
844 setRegionFor(OldBB, R);
847 char RegionInfo::ID = 0;
848 INITIALIZE_PASS_BEGIN(RegionInfo, "regions",
849 "Detect single entry single exit regions", true, true)
850 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
851 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
852 INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
853 INITIALIZE_PASS_END(RegionInfo, "regions",
854 "Detect single entry single exit regions", true, true)
856 // Create methods available outside of this file, to use them
857 // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
858 // the link time optimization.
861 FunctionPass *createRegionInfoPass() {
862 return new RegionInfo();