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 #include "llvm/Analysis/RegionInfo.h"
13 #include "llvm/ADT/PostOrderIterator.h"
14 #include "llvm/ADT/Statistic.h"
15 #include "llvm/Analysis/LoopInfo.h"
16 #include "llvm/Analysis/RegionIterator.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/ErrorHandling.h"
21 #define DEBUG_TYPE "region"
22 #include "llvm/Support/Debug.h"
29 // Always verify if expensive checking is enabled.
31 static bool VerifyRegionInfo = true;
33 static bool VerifyRegionInfo = false;
36 static cl::opt<bool,true>
37 VerifyRegionInfoX("verify-region-info", cl::location(VerifyRegionInfo),
38 cl::desc("Verify region info (time consuming)"));
40 STATISTIC(numRegions, "The # of regions");
41 STATISTIC(numSimpleRegions, "The # of simple regions");
43 static cl::opt<enum Region::PrintStyle> printStyle("print-region-style",
45 cl::desc("style of printing regions"),
47 clEnumValN(Region::PrintNone, "none", "print no details"),
48 clEnumValN(Region::PrintBB, "bb",
49 "print regions in detail with block_iterator"),
50 clEnumValN(Region::PrintRN, "rn",
51 "print regions in detail with element_iterator"),
53 //===----------------------------------------------------------------------===//
54 /// Region Implementation
55 Region::Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RInfo,
56 DominatorTree *dt, Region *Parent)
57 : RegionNode(Parent, Entry, 1), RI(RInfo), DT(dt), exit(Exit) {}
60 // Free the cached nodes.
61 for (BBNodeMapT::iterator it = BBNodeMap.begin(),
62 ie = BBNodeMap.end(); it != ie; ++it)
65 // Only clean the cache for this Region. Caches of child Regions will be
66 // cleaned when the child Regions are deleted.
69 for (iterator I = begin(), E = end(); I != E; ++I)
73 void Region::replaceEntry(BasicBlock *BB) {
77 void Region::replaceExit(BasicBlock *BB) {
78 assert(exit && "No exit to replace!");
82 bool Region::contains(const BasicBlock *B) const {
83 BasicBlock *BB = const_cast<BasicBlock*>(B);
85 assert(DT->getNode(BB) && "BB not part of the dominance tree");
87 BasicBlock *entry = getEntry(), *exit = getExit();
93 return (DT->dominates(entry, BB)
94 && !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
97 bool Region::contains(const Loop *L) const {
98 // BBs that are not part of any loop are element of the Loop
99 // described by the NULL pointer. This loop is not part of any region,
100 // except if the region describes the whole function.
102 return getExit() == 0;
104 if (!contains(L->getHeader()))
107 SmallVector<BasicBlock *, 8> ExitingBlocks;
108 L->getExitingBlocks(ExitingBlocks);
110 for (SmallVectorImpl<BasicBlock*>::iterator BI = ExitingBlocks.begin(),
111 BE = ExitingBlocks.end(); BI != BE; ++BI)
118 Loop *Region::outermostLoopInRegion(Loop *L) const {
122 while (L && contains(L->getParentLoop())) {
123 L = L->getParentLoop();
129 Loop *Region::outermostLoopInRegion(LoopInfo *LI, BasicBlock* BB) const {
130 assert(LI && BB && "LI and BB cannot be null!");
131 Loop *L = LI->getLoopFor(BB);
132 return outermostLoopInRegion(L);
135 BasicBlock *Region::getEnteringBlock() const {
136 BasicBlock *entry = getEntry();
138 BasicBlock *enteringBlock = 0;
140 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
143 if (DT->getNode(Pred) && !contains(Pred)) {
147 enteringBlock = Pred;
151 return enteringBlock;
154 BasicBlock *Region::getExitingBlock() const {
155 BasicBlock *exit = getExit();
157 BasicBlock *exitingBlock = 0;
162 for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
165 if (contains(Pred)) {
176 bool Region::isSimple() const {
177 return !isTopLevelRegion() && getEnteringBlock() && getExitingBlock();
180 std::string Region::getNameStr() const {
181 std::string exitName;
182 std::string entryName;
184 if (getEntry()->getName().empty()) {
185 raw_string_ostream OS(entryName);
187 WriteAsOperand(OS, getEntry(), false);
189 entryName = getEntry()->getName();
192 if (getExit()->getName().empty()) {
193 raw_string_ostream OS(exitName);
195 WriteAsOperand(OS, getExit(), false);
197 exitName = getExit()->getName();
199 exitName = "<Function Return>";
201 return entryName + " => " + exitName;
204 void Region::verifyBBInRegion(BasicBlock *BB) const {
206 llvm_unreachable("Broken region found!");
208 BasicBlock *entry = getEntry(), *exit = getExit();
210 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
211 if (!contains(*SI) && exit != *SI)
212 llvm_unreachable("Broken region found!");
215 for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB); SI != SE; ++SI)
217 llvm_unreachable("Broken region found!");
220 void Region::verifyWalk(BasicBlock *BB, std::set<BasicBlock*> *visited) const {
221 BasicBlock *exit = getExit();
225 verifyBBInRegion(BB);
227 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
228 if (*SI != exit && visited->find(*SI) == visited->end())
229 verifyWalk(*SI, visited);
232 void Region::verifyRegion() const {
233 // Only do verification when user wants to, otherwise this expensive
234 // check will be invoked by PassManager.
235 if (!VerifyRegionInfo) return;
237 std::set<BasicBlock*> visited;
238 verifyWalk(getEntry(), &visited);
241 void Region::verifyRegionNest() const {
242 for (Region::const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
243 (*RI)->verifyRegionNest();
248 Region::element_iterator Region::element_begin() {
249 return GraphTraits<Region*>::nodes_begin(this);
252 Region::element_iterator Region::element_end() {
253 return GraphTraits<Region*>::nodes_end(this);
256 Region::const_element_iterator Region::element_begin() const {
257 return GraphTraits<const Region*>::nodes_begin(this);
260 Region::const_element_iterator Region::element_end() const {
261 return GraphTraits<const Region*>::nodes_end(this);
264 Region* Region::getSubRegionNode(BasicBlock *BB) const {
265 Region *R = RI->getRegionFor(BB);
270 // If we pass the BB out of this region, that means our code is broken.
271 assert(contains(R) && "BB not in current region!");
273 while (contains(R->getParent()) && R->getParent() != this)
276 if (R->getEntry() != BB)
282 RegionNode* Region::getBBNode(BasicBlock *BB) const {
283 assert(contains(BB) && "Can get BB node out of this region!");
285 BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
287 if (at != BBNodeMap.end())
290 RegionNode *NewNode = new RegionNode(const_cast<Region*>(this), BB);
291 BBNodeMap.insert(std::make_pair(BB, NewNode));
295 RegionNode* Region::getNode(BasicBlock *BB) const {
296 assert(contains(BB) && "Can get BB node out of this region!");
297 if (Region* Child = getSubRegionNode(BB))
298 return Child->getNode();
300 return getBBNode(BB);
303 void Region::transferChildrenTo(Region *To) {
304 for (iterator I = begin(), E = end(); I != E; ++I) {
306 To->children.push_back(*I);
311 void Region::addSubRegion(Region *SubRegion, bool moveChildren) {
312 assert(SubRegion->parent == 0 && "SubRegion already has a parent!");
313 assert(std::find(begin(), end(), SubRegion) == children.end()
314 && "Subregion already exists!");
316 SubRegion->parent = this;
317 children.push_back(SubRegion);
322 assert(SubRegion->children.size() == 0
323 && "SubRegions that contain children are not supported");
325 for (element_iterator I = element_begin(), E = element_end(); I != E; ++I)
326 if (!(*I)->isSubRegion()) {
327 BasicBlock *BB = (*I)->getNodeAs<BasicBlock>();
329 if (SubRegion->contains(BB))
330 RI->setRegionFor(BB, SubRegion);
333 std::vector<Region*> Keep;
334 for (iterator I = begin(), E = end(); I != E; ++I)
335 if (SubRegion->contains(*I) && *I != SubRegion) {
336 SubRegion->children.push_back(*I);
337 (*I)->parent = SubRegion;
342 children.insert(children.begin(), Keep.begin(), Keep.end());
346 Region *Region::removeSubRegion(Region *Child) {
347 assert(Child->parent == this && "Child is not a child of this region!");
349 RegionSet::iterator I = std::find(children.begin(), children.end(), Child);
350 assert(I != children.end() && "Region does not exit. Unable to remove.");
351 children.erase(children.begin()+(I-begin()));
355 unsigned Region::getDepth() const {
358 for (Region *R = parent; R != 0; R = R->parent)
364 Region *Region::getExpandedRegion() const {
365 unsigned NumSuccessors = exit->getTerminator()->getNumSuccessors();
367 if (NumSuccessors == 0)
370 for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
372 if (!DT->dominates(getEntry(), *PI))
375 Region *R = RI->getRegionFor(exit);
377 if (R->getEntry() != exit) {
378 if (exit->getTerminator()->getNumSuccessors() == 1)
379 return new Region(getEntry(), *succ_begin(exit), RI, DT);
384 while (R->getParent() && R->getParent()->getEntry() == exit)
387 if (!DT->dominates(getEntry(), R->getExit()))
388 for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
390 if (!DT->dominates(R->getExit(), *PI))
393 return new Region(getEntry(), R->getExit(), RI, DT);
396 void Region::print(raw_ostream &OS, bool print_tree, unsigned level,
397 enum PrintStyle Style) const {
399 OS.indent(level*2) << "[" << level << "] " << getNameStr();
401 OS.indent(level*2) << getNameStr();
406 if (Style != PrintNone) {
407 OS.indent(level*2) << "{\n";
408 OS.indent(level*2 + 2);
410 if (Style == PrintBB) {
411 for (const_block_iterator I = block_begin(), E = block_end(); I != E; ++I)
412 OS << (*I)->getName() << ", "; // TODO: remove the last ","
413 } else if (Style == PrintRN) {
414 for (const_element_iterator I = element_begin(), E = element_end(); I!=E; ++I)
415 OS << **I << ", "; // TODO: remove the last ",
422 for (const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
423 (*RI)->print(OS, print_tree, level+1, Style);
425 if (Style != PrintNone)
426 OS.indent(level*2) << "} \n";
429 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
430 void Region::dump() const {
431 print(dbgs(), true, getDepth(), printStyle.getValue());
435 void Region::clearNodeCache() {
436 // Free the cached nodes.
437 for (BBNodeMapT::iterator I = BBNodeMap.begin(),
438 IE = BBNodeMap.end(); I != IE; ++I)
442 for (Region::iterator RI = begin(), RE = end(); RI != RE; ++RI)
443 (*RI)->clearNodeCache();
446 //===----------------------------------------------------------------------===//
447 // RegionInfo implementation
450 bool RegionInfo::isCommonDomFrontier(BasicBlock *BB, BasicBlock *entry,
451 BasicBlock *exit) const {
452 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
454 if (DT->dominates(entry, P) && !DT->dominates(exit, P))
460 bool RegionInfo::isRegion(BasicBlock *entry, BasicBlock *exit) const {
461 assert(entry && exit && "entry and exit must not be null!");
462 typedef DominanceFrontier::DomSetType DST;
464 DST *entrySuccs = &DF->find(entry)->second;
466 // Exit is the header of a loop that contains the entry. In this case,
467 // the dominance frontier must only contain the exit.
468 if (!DT->dominates(entry, exit)) {
469 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
471 if (*SI != exit && *SI != entry)
477 DST *exitSuccs = &DF->find(exit)->second;
479 // Do not allow edges leaving the region.
480 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
482 if (*SI == exit || *SI == entry)
484 if (exitSuccs->find(*SI) == exitSuccs->end())
486 if (!isCommonDomFrontier(*SI, entry, exit))
490 // Do not allow edges pointing into the region.
491 for (DST::iterator SI = exitSuccs->begin(), SE = exitSuccs->end();
493 if (DT->properlyDominates(entry, *SI) && *SI != exit)
500 void RegionInfo::insertShortCut(BasicBlock *entry, BasicBlock *exit,
501 BBtoBBMap *ShortCut) const {
502 assert(entry && exit && "entry and exit must not be null!");
504 BBtoBBMap::iterator e = ShortCut->find(exit);
506 if (e == ShortCut->end())
507 // No further region at exit available.
508 (*ShortCut)[entry] = exit;
510 // We found a region e that starts at exit. Therefore (entry, e->second)
511 // is also a region, that is larger than (entry, exit). Insert the
513 BasicBlock *BB = e->second;
514 (*ShortCut)[entry] = BB;
518 DomTreeNode* RegionInfo::getNextPostDom(DomTreeNode* N,
519 BBtoBBMap *ShortCut) const {
520 BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
522 if (e == ShortCut->end())
525 return PDT->getNode(e->second)->getIDom();
528 bool RegionInfo::isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const {
529 assert(entry && exit && "entry and exit must not be null!");
531 unsigned num_successors = succ_end(entry) - succ_begin(entry);
533 if (num_successors <= 1 && exit == *(succ_begin(entry)))
539 void RegionInfo::updateStatistics(Region *R) {
542 // TODO: Slow. Should only be enabled if -stats is used.
543 if (R->isSimple()) ++numSimpleRegions;
546 Region *RegionInfo::createRegion(BasicBlock *entry, BasicBlock *exit) {
547 assert(entry && exit && "entry and exit must not be null!");
549 if (isTrivialRegion(entry, exit))
552 Region *region = new Region(entry, exit, this, DT);
553 BBtoRegion.insert(std::make_pair(entry, region));
556 region->verifyRegion();
558 DEBUG(region->verifyRegion());
561 updateStatistics(region);
565 void RegionInfo::findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut) {
568 DomTreeNode *N = PDT->getNode(entry);
573 Region *lastRegion= 0;
574 BasicBlock *lastExit = entry;
576 // As only a BasicBlock that postdominates entry can finish a region, walk the
577 // post dominance tree upwards.
578 while ((N = getNextPostDom(N, ShortCut))) {
579 BasicBlock *exit = N->getBlock();
584 if (isRegion(entry, exit)) {
585 Region *newRegion = createRegion(entry, exit);
588 newRegion->addSubRegion(lastRegion);
590 lastRegion = newRegion;
594 // This can never be a region, so stop the search.
595 if (!DT->dominates(entry, exit))
599 // Tried to create regions from entry to lastExit. Next time take a
600 // shortcut from entry to lastExit.
601 if (lastExit != entry)
602 insertShortCut(entry, lastExit, ShortCut);
605 void RegionInfo::scanForRegions(Function &F, BBtoBBMap *ShortCut) {
606 BasicBlock *entry = &(F.getEntryBlock());
607 DomTreeNode *N = DT->getNode(entry);
609 // Iterate over the dominance tree in post order to start with the small
610 // regions from the bottom of the dominance tree. If the small regions are
611 // detected first, detection of bigger regions is faster, as we can jump
612 // over the small regions.
613 for (po_iterator<DomTreeNode*> FI = po_begin(N), FE = po_end(N); FI != FE;
615 findRegionsWithEntry(FI->getBlock(), ShortCut);
619 Region *RegionInfo::getTopMostParent(Region *region) {
620 while (region->parent)
621 region = region->getParent();
626 void RegionInfo::buildRegionsTree(DomTreeNode *N, Region *region) {
627 BasicBlock *BB = N->getBlock();
629 // Passed region exit
630 while (BB == region->getExit())
631 region = region->getParent();
633 BBtoRegionMap::iterator it = BBtoRegion.find(BB);
635 // This basic block is a start block of a region. It is already in the
636 // BBtoRegion relation. Only the child basic blocks have to be updated.
637 if (it != BBtoRegion.end()) {
638 Region *newRegion = it->second;
639 region->addSubRegion(getTopMostParent(newRegion));
642 BBtoRegion[BB] = region;
645 for (DomTreeNode::iterator CI = N->begin(), CE = N->end(); CI != CE; ++CI)
646 buildRegionsTree(*CI, region);
649 void RegionInfo::releaseMemory() {
652 delete TopLevelRegion;
656 RegionInfo::RegionInfo() : FunctionPass(ID) {
657 initializeRegionInfoPass(*PassRegistry::getPassRegistry());
661 RegionInfo::~RegionInfo() {
665 void RegionInfo::Calculate(Function &F) {
666 // ShortCut a function where for every BB the exit of the largest region
667 // starting with BB is stored. These regions can be threated as single BBS.
668 // This improves performance on linear CFGs.
671 scanForRegions(F, &ShortCut);
672 BasicBlock *BB = &F.getEntryBlock();
673 buildRegionsTree(DT->getNode(BB), TopLevelRegion);
676 bool RegionInfo::runOnFunction(Function &F) {
679 DT = &getAnalysis<DominatorTree>();
680 PDT = &getAnalysis<PostDominatorTree>();
681 DF = &getAnalysis<DominanceFrontier>();
683 TopLevelRegion = new Region(&F.getEntryBlock(), 0, this, DT, 0);
684 updateStatistics(TopLevelRegion);
691 void RegionInfo::getAnalysisUsage(AnalysisUsage &AU) const {
692 AU.setPreservesAll();
693 AU.addRequiredTransitive<DominatorTree>();
694 AU.addRequired<PostDominatorTree>();
695 AU.addRequired<DominanceFrontier>();
698 void RegionInfo::print(raw_ostream &OS, const Module *) const {
699 OS << "Region tree:\n";
700 TopLevelRegion->print(OS, true, 0, printStyle.getValue());
701 OS << "End region tree\n";
704 void RegionInfo::verifyAnalysis() const {
705 // Only do verification when user wants to, otherwise this expensive check
706 // will be invoked by PMDataManager::verifyPreservedAnalysis when
707 // a regionpass (marked PreservedAll) finish.
708 if (!VerifyRegionInfo) return;
710 TopLevelRegion->verifyRegionNest();
713 // Region pass manager support.
714 Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
715 BBtoRegionMap::const_iterator I=
717 return I != BBtoRegion.end() ? I->second : 0;
720 void RegionInfo::setRegionFor(BasicBlock *BB, Region *R) {
724 Region *RegionInfo::operator[](BasicBlock *BB) const {
725 return getRegionFor(BB);
728 BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
729 BasicBlock *Exit = NULL;
732 // Get largest region that starts at BB.
733 Region *R = getRegionFor(BB);
734 while (R && R->getParent() && R->getParent()->getEntry() == BB)
737 // Get the single exit of BB.
738 if (R && R->getEntry() == BB)
740 else if (++succ_begin(BB) == succ_end(BB))
741 Exit = *succ_begin(BB);
742 else // No single exit exists.
745 // Get largest region that starts at Exit.
746 Region *ExitR = getRegionFor(Exit);
747 while (ExitR && ExitR->getParent()
748 && ExitR->getParent()->getEntry() == Exit)
749 ExitR = ExitR->getParent();
751 for (pred_iterator PI = pred_begin(Exit), PE = pred_end(Exit); PI != PE;
753 if (!R->contains(*PI) && !ExitR->contains(*PI))
756 // This stops infinite cycles.
757 if (DT->dominates(Exit, BB))
767 RegionInfo::getCommonRegion(Region *A, Region *B) const {
768 assert (A && B && "One of the Regions is NULL");
770 if (A->contains(B)) return A;
772 while (!B->contains(A))
779 RegionInfo::getCommonRegion(SmallVectorImpl<Region*> &Regions) const {
780 Region* ret = Regions.back();
783 for (SmallVectorImpl<Region*>::const_iterator I = Regions.begin(),
784 E = Regions.end(); I != E; ++I)
785 ret = getCommonRegion(ret, *I);
791 RegionInfo::getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const {
792 Region* ret = getRegionFor(BBs.back());
795 for (SmallVectorImpl<BasicBlock*>::const_iterator I = BBs.begin(),
796 E = BBs.end(); I != E; ++I)
797 ret = getCommonRegion(ret, getRegionFor(*I));
802 void RegionInfo::splitBlock(BasicBlock* NewBB, BasicBlock *OldBB)
804 Region *R = getRegionFor(OldBB);
806 setRegionFor(NewBB, R);
808 while (R->getEntry() == OldBB && !R->isTopLevelRegion()) {
809 R->replaceEntry(NewBB);
813 setRegionFor(OldBB, R);
816 char RegionInfo::ID = 0;
817 INITIALIZE_PASS_BEGIN(RegionInfo, "regions",
818 "Detect single entry single exit regions", true, true)
819 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
820 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
821 INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
822 INITIALIZE_PASS_END(RegionInfo, "regions",
823 "Detect single entry single exit regions", true, true)
825 // Create methods available outside of this file, to use them
826 // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
827 // the link time optimization.
830 FunctionPass *createRegionInfoPass() {
831 return new RegionInfo();