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/Analysis/RegionIterator.h"
15 #include "llvm/ADT/PostOrderIterator.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Assembly/Writer.h"
22 #define DEBUG_TYPE "region"
23 #include "llvm/Support/Debug.h"
30 // Always verify if expensive checking is enabled.
32 static bool VerifyRegionInfo = true;
34 static bool VerifyRegionInfo = false;
37 static cl::opt<bool,true>
38 VerifyRegionInfoX("verify-region-info", cl::location(VerifyRegionInfo),
39 cl::desc("Verify region info (time consuming)"));
41 STATISTIC(numRegions, "The # of regions");
42 STATISTIC(numSimpleRegions, "The # of simple regions");
44 //===----------------------------------------------------------------------===//
45 /// PrintStyle - Print region in difference ways.
46 enum PrintStyle { PrintNone, PrintBB, PrintRN };
48 static cl::opt<enum PrintStyle> printStyle("print-region-style", cl::Hidden,
49 cl::desc("style of printing regions"),
51 clEnumValN(PrintNone, "none", "print no details"),
52 clEnumValN(PrintBB, "bb", "print regions in detail with block_iterator"),
53 clEnumValN(PrintRN, "rn", "print regions in detail with element_iterator"),
55 //===----------------------------------------------------------------------===//
56 /// Region Implementation
57 Region::Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RInfo,
58 DominatorTree *dt, Region *Parent)
59 : RegionNode(Parent, Entry, 1), RI(RInfo), DT(dt), exit(Exit) {}
62 // Free the cached nodes.
63 for (BBNodeMapT::iterator it = BBNodeMap.begin(),
64 ie = BBNodeMap.end(); it != ie; ++it)
67 // Only clean the cache for this Region. Caches of child Regions will be
68 // cleaned when the child Regions are deleted.
71 for (iterator I = begin(), E = end(); I != E; ++I)
75 void Region::replaceEntry(BasicBlock *BB) {
79 void Region::replaceExit(BasicBlock *BB) {
80 assert(exit && "No exit to replace!");
84 bool Region::contains(const BasicBlock *B) const {
85 BasicBlock *BB = const_cast<BasicBlock*>(B);
87 assert(DT->getNode(BB) && "BB not part of the dominance tree");
89 BasicBlock *entry = getEntry(), *exit = getExit();
95 return (DT->dominates(entry, BB)
96 && !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
99 bool Region::contains(const Loop *L) const {
100 // BBs that are not part of any loop are element of the Loop
101 // described by the NULL pointer. This loop is not part of any region,
102 // except if the region describes the whole function.
104 return getExit() == 0;
106 if (!contains(L->getHeader()))
109 SmallVector<BasicBlock *, 8> ExitingBlocks;
110 L->getExitingBlocks(ExitingBlocks);
112 for (SmallVectorImpl<BasicBlock*>::iterator BI = ExitingBlocks.begin(),
113 BE = ExitingBlocks.end(); BI != BE; ++BI)
120 Loop *Region::outermostLoopInRegion(Loop *L) const {
124 while (L && contains(L->getParentLoop())) {
125 L = L->getParentLoop();
131 Loop *Region::outermostLoopInRegion(LoopInfo *LI, BasicBlock* BB) const {
132 assert(LI && BB && "LI and BB cannot be null!");
133 Loop *L = LI->getLoopFor(BB);
134 return outermostLoopInRegion(L);
137 BasicBlock *Region::getEnteringBlock() const {
138 BasicBlock *entry = getEntry();
140 BasicBlock *enteringBlock = 0;
142 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
145 if (DT->getNode(Pred) && !contains(Pred)) {
149 enteringBlock = Pred;
153 return enteringBlock;
156 BasicBlock *Region::getExitingBlock() const {
157 BasicBlock *exit = getExit();
159 BasicBlock *exitingBlock = 0;
164 for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
167 if (contains(Pred)) {
178 bool Region::isSimple() const {
179 return !isTopLevelRegion() && getEnteringBlock() && getExitingBlock();
182 std::string Region::getNameStr() const {
183 std::string exitName;
184 std::string entryName;
186 if (getEntry()->getName().empty()) {
187 raw_string_ostream OS(entryName);
189 WriteAsOperand(OS, getEntry(), false);
190 entryName = OS.str();
192 entryName = getEntry()->getNameStr();
195 if (getExit()->getName().empty()) {
196 raw_string_ostream OS(exitName);
198 WriteAsOperand(OS, getExit(), false);
201 exitName = getExit()->getNameStr();
203 exitName = "<Function Return>";
205 return entryName + " => " + exitName;
208 void Region::verifyBBInRegion(BasicBlock *BB) const {
210 llvm_unreachable("Broken region found!");
212 BasicBlock *entry = getEntry(), *exit = getExit();
214 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
215 if (!contains(*SI) && exit != *SI)
216 llvm_unreachable("Broken region found!");
219 for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB); SI != SE; ++SI)
221 llvm_unreachable("Broken region found!");
224 void Region::verifyWalk(BasicBlock *BB, std::set<BasicBlock*> *visited) const {
225 BasicBlock *exit = getExit();
229 verifyBBInRegion(BB);
231 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
232 if (*SI != exit && visited->find(*SI) == visited->end())
233 verifyWalk(*SI, visited);
236 void Region::verifyRegion() const {
237 // Only do verification when user wants to, otherwise this expensive
238 // check will be invoked by PassManager.
239 if (!VerifyRegionInfo) return;
241 std::set<BasicBlock*> visited;
242 verifyWalk(getEntry(), &visited);
245 void Region::verifyRegionNest() const {
246 for (Region::const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
247 (*RI)->verifyRegionNest();
252 Region::block_iterator Region::block_begin() {
253 return GraphTraits<FlatIt<Region*> >::nodes_begin(this);
256 Region::block_iterator Region::block_end() {
257 return GraphTraits<FlatIt<Region*> >::nodes_end(this);
260 Region::const_block_iterator Region::block_begin() const {
261 return GraphTraits<FlatIt<const Region*> >::nodes_begin(this);
264 Region::const_block_iterator Region::block_end() const {
265 return GraphTraits<FlatIt<const Region*> >::nodes_end(this);
268 Region::element_iterator Region::element_begin() {
269 return GraphTraits<Region*>::nodes_begin(this);
272 Region::element_iterator Region::element_end() {
273 return GraphTraits<Region*>::nodes_end(this);
276 Region::const_element_iterator Region::element_begin() const {
277 return GraphTraits<const Region*>::nodes_begin(this);
280 Region::const_element_iterator Region::element_end() const {
281 return GraphTraits<const Region*>::nodes_end(this);
284 Region* Region::getSubRegionNode(BasicBlock *BB) const {
285 Region *R = RI->getRegionFor(BB);
290 // If we pass the BB out of this region, that means our code is broken.
291 assert(contains(R) && "BB not in current region!");
293 while (contains(R->getParent()) && R->getParent() != this)
296 if (R->getEntry() != BB)
302 RegionNode* Region::getBBNode(BasicBlock *BB) const {
303 assert(contains(BB) && "Can get BB node out of this region!");
305 BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
307 if (at != BBNodeMap.end())
310 RegionNode *NewNode = new RegionNode(const_cast<Region*>(this), BB);
311 BBNodeMap.insert(std::make_pair(BB, NewNode));
315 RegionNode* Region::getNode(BasicBlock *BB) const {
316 assert(contains(BB) && "Can get BB node out of this region!");
317 if (Region* Child = getSubRegionNode(BB))
318 return Child->getNode();
320 return getBBNode(BB);
323 void Region::transferChildrenTo(Region *To) {
324 for (iterator I = begin(), E = end(); I != E; ++I) {
326 To->children.push_back(*I);
331 void Region::addSubRegion(Region *SubRegion, bool moveChildren) {
332 assert(SubRegion->parent == 0 && "SubRegion already has a parent!");
333 assert(std::find(begin(), end(), SubRegion) == children.end()
334 && "Subregion already exists!");
336 SubRegion->parent = this;
337 children.push_back(SubRegion);
342 assert(SubRegion->children.size() == 0
343 && "SubRegions that contain children are not supported");
345 for (element_iterator I = element_begin(), E = element_end(); I != E; ++I)
346 if (!(*I)->isSubRegion()) {
347 BasicBlock *BB = (*I)->getNodeAs<BasicBlock>();
349 if (SubRegion->contains(BB))
350 RI->setRegionFor(BB, SubRegion);
353 std::vector<Region*> Keep;
354 for (iterator I = begin(), E = end(); I != E; ++I)
355 if (SubRegion->contains(*I) && *I != SubRegion) {
356 SubRegion->children.push_back(*I);
357 (*I)->parent = SubRegion;
362 children.insert(children.begin(), Keep.begin(), Keep.end());
366 Region *Region::removeSubRegion(Region *Child) {
367 assert(Child->parent == this && "Child is not a child of this region!");
369 RegionSet::iterator I = std::find(children.begin(), children.end(), Child);
370 assert(I != children.end() && "Region does not exit. Unable to remove.");
371 children.erase(children.begin()+(I-begin()));
375 unsigned Region::getDepth() const {
378 for (Region *R = parent; R != 0; R = R->parent)
384 Region *Region::getExpandedRegion() const {
385 unsigned NumSuccessors = exit->getTerminator()->getNumSuccessors();
387 if (NumSuccessors == 0)
390 for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
392 if (!DT->dominates(getEntry(), *PI))
395 Region *R = RI->getRegionFor(exit);
397 if (R->getEntry() != exit) {
398 if (exit->getTerminator()->getNumSuccessors() == 1)
399 return new Region(getEntry(), *succ_begin(exit), RI, DT);
404 while (R->getParent() && R->getParent()->getEntry() == exit)
407 if (!DT->dominates(getEntry(), R->getExit()))
408 for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
410 if (!DT->dominates(R->getExit(), *PI))
413 return new Region(getEntry(), R->getExit(), RI, DT);
416 void Region::print(raw_ostream &OS, bool print_tree, unsigned level) const {
418 OS.indent(level*2) << "[" << level << "] " << getNameStr();
420 OS.indent(level*2) << getNameStr();
425 if (printStyle != PrintNone) {
426 OS.indent(level*2) << "{\n";
427 OS.indent(level*2 + 2);
429 if (printStyle == PrintBB) {
430 for (const_block_iterator I = block_begin(), E = block_end(); I!=E; ++I)
431 OS << **I << ", "; // TODO: remove the last ","
432 } else if (printStyle == PrintRN) {
433 for (const_element_iterator I = element_begin(), E = element_end(); I!=E; ++I)
434 OS << **I << ", "; // TODO: remove the last ",
441 for (const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
442 (*RI)->print(OS, print_tree, level+1);
444 if (printStyle != PrintNone)
445 OS.indent(level*2) << "} \n";
448 void Region::dump() const {
449 print(dbgs(), true, getDepth());
452 void Region::clearNodeCache() {
453 // Free the cached nodes.
454 for (BBNodeMapT::iterator I = BBNodeMap.begin(),
455 IE = BBNodeMap.end(); I != IE; ++I)
459 for (Region::iterator RI = begin(), RE = end(); RI != RE; ++RI)
460 (*RI)->clearNodeCache();
463 //===----------------------------------------------------------------------===//
464 // RegionInfo implementation
467 bool RegionInfo::isCommonDomFrontier(BasicBlock *BB, BasicBlock *entry,
468 BasicBlock *exit) const {
469 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
471 if (DT->dominates(entry, P) && !DT->dominates(exit, P))
477 bool RegionInfo::isRegion(BasicBlock *entry, BasicBlock *exit) const {
478 assert(entry && exit && "entry and exit must not be null!");
479 typedef DominanceFrontier::DomSetType DST;
481 DST *entrySuccs = &DF->find(entry)->second;
483 // Exit is the header of a loop that contains the entry. In this case,
484 // the dominance frontier must only contain the exit.
485 if (!DT->dominates(entry, exit)) {
486 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
488 if (*SI != exit && *SI != entry)
494 DST *exitSuccs = &DF->find(exit)->second;
496 // Do not allow edges leaving the region.
497 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
499 if (*SI == exit || *SI == entry)
501 if (exitSuccs->find(*SI) == exitSuccs->end())
503 if (!isCommonDomFrontier(*SI, entry, exit))
507 // Do not allow edges pointing into the region.
508 for (DST::iterator SI = exitSuccs->begin(), SE = exitSuccs->end();
510 if (DT->properlyDominates(entry, *SI) && *SI != exit)
517 void RegionInfo::insertShortCut(BasicBlock *entry, BasicBlock *exit,
518 BBtoBBMap *ShortCut) const {
519 assert(entry && exit && "entry and exit must not be null!");
521 BBtoBBMap::iterator e = ShortCut->find(exit);
523 if (e == ShortCut->end())
524 // No further region at exit available.
525 (*ShortCut)[entry] = exit;
527 // We found a region e that starts at exit. Therefore (entry, e->second)
528 // is also a region, that is larger than (entry, exit). Insert the
530 BasicBlock *BB = e->second;
531 (*ShortCut)[entry] = BB;
535 DomTreeNode* RegionInfo::getNextPostDom(DomTreeNode* N,
536 BBtoBBMap *ShortCut) const {
537 BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
539 if (e == ShortCut->end())
542 return PDT->getNode(e->second)->getIDom();
545 bool RegionInfo::isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const {
546 assert(entry && exit && "entry and exit must not be null!");
548 unsigned num_successors = succ_end(entry) - succ_begin(entry);
550 if (num_successors <= 1 && exit == *(succ_begin(entry)))
556 void RegionInfo::updateStatistics(Region *R) {
559 // TODO: Slow. Should only be enabled if -stats is used.
560 if (R->isSimple()) ++numSimpleRegions;
563 Region *RegionInfo::createRegion(BasicBlock *entry, BasicBlock *exit) {
564 assert(entry && exit && "entry and exit must not be null!");
566 if (isTrivialRegion(entry, exit))
569 Region *region = new Region(entry, exit, this, DT);
570 BBtoRegion.insert(std::make_pair(entry, region));
573 region->verifyRegion();
575 DEBUG(region->verifyRegion());
578 updateStatistics(region);
582 void RegionInfo::findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut) {
585 DomTreeNode *N = PDT->getNode(entry);
590 Region *lastRegion= 0;
591 BasicBlock *lastExit = entry;
593 // As only a BasicBlock that postdominates entry can finish a region, walk the
594 // post dominance tree upwards.
595 while ((N = getNextPostDom(N, ShortCut))) {
596 BasicBlock *exit = N->getBlock();
601 if (isRegion(entry, exit)) {
602 Region *newRegion = createRegion(entry, exit);
605 newRegion->addSubRegion(lastRegion);
607 lastRegion = newRegion;
611 // This can never be a region, so stop the search.
612 if (!DT->dominates(entry, exit))
616 // Tried to create regions from entry to lastExit. Next time take a
617 // shortcut from entry to lastExit.
618 if (lastExit != entry)
619 insertShortCut(entry, lastExit, ShortCut);
622 void RegionInfo::scanForRegions(Function &F, BBtoBBMap *ShortCut) {
623 BasicBlock *entry = &(F.getEntryBlock());
624 DomTreeNode *N = DT->getNode(entry);
626 // Iterate over the dominance tree in post order to start with the small
627 // regions from the bottom of the dominance tree. If the small regions are
628 // detected first, detection of bigger regions is faster, as we can jump
629 // over the small regions.
630 for (po_iterator<DomTreeNode*> FI = po_begin(N), FE = po_end(N); FI != FE;
632 findRegionsWithEntry(FI->getBlock(), ShortCut);
636 Region *RegionInfo::getTopMostParent(Region *region) {
637 while (region->parent)
638 region = region->getParent();
643 void RegionInfo::buildRegionsTree(DomTreeNode *N, Region *region) {
644 BasicBlock *BB = N->getBlock();
646 // Passed region exit
647 while (BB == region->getExit())
648 region = region->getParent();
650 BBtoRegionMap::iterator it = BBtoRegion.find(BB);
652 // This basic block is a start block of a region. It is already in the
653 // BBtoRegion relation. Only the child basic blocks have to be updated.
654 if (it != BBtoRegion.end()) {
655 Region *newRegion = it->second;;
656 region->addSubRegion(getTopMostParent(newRegion));
659 BBtoRegion[BB] = region;
662 for (DomTreeNode::iterator CI = N->begin(), CE = N->end(); CI != CE; ++CI)
663 buildRegionsTree(*CI, region);
666 void RegionInfo::releaseMemory() {
669 delete TopLevelRegion;
673 RegionInfo::RegionInfo() : FunctionPass(ID) {
674 initializeRegionInfoPass(*PassRegistry::getPassRegistry());
678 RegionInfo::~RegionInfo() {
682 void RegionInfo::Calculate(Function &F) {
683 // ShortCut a function where for every BB the exit of the largest region
684 // starting with BB is stored. These regions can be threated as single BBS.
685 // This improves performance on linear CFGs.
688 scanForRegions(F, &ShortCut);
689 BasicBlock *BB = &F.getEntryBlock();
690 buildRegionsTree(DT->getNode(BB), TopLevelRegion);
693 bool RegionInfo::runOnFunction(Function &F) {
696 DT = &getAnalysis<DominatorTree>();
697 PDT = &getAnalysis<PostDominatorTree>();
698 DF = &getAnalysis<DominanceFrontier>();
700 TopLevelRegion = new Region(&F.getEntryBlock(), 0, this, DT, 0);
701 updateStatistics(TopLevelRegion);
708 void RegionInfo::getAnalysisUsage(AnalysisUsage &AU) const {
709 AU.setPreservesAll();
710 AU.addRequiredTransitive<DominatorTree>();
711 AU.addRequired<PostDominatorTree>();
712 AU.addRequired<DominanceFrontier>();
715 void RegionInfo::print(raw_ostream &OS, const Module *) const {
716 OS << "Region tree:\n";
717 TopLevelRegion->print(OS, true, 0);
718 OS << "End region tree\n";
721 void RegionInfo::verifyAnalysis() const {
722 // Only do verification when user wants to, otherwise this expensive check
723 // will be invoked by PMDataManager::verifyPreservedAnalysis when
724 // a regionpass (marked PreservedAll) finish.
725 if (!VerifyRegionInfo) return;
727 TopLevelRegion->verifyRegionNest();
730 // Region pass manager support.
731 Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
732 BBtoRegionMap::const_iterator I=
734 return I != BBtoRegion.end() ? I->second : 0;
737 void RegionInfo::setRegionFor(BasicBlock *BB, Region *R) {
741 Region *RegionInfo::operator[](BasicBlock *BB) const {
742 return getRegionFor(BB);
745 BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
746 BasicBlock *Exit = NULL;
749 // Get largest region that starts at BB.
750 Region *R = getRegionFor(BB);
751 while (R && R->getParent() && R->getParent()->getEntry() == BB)
754 // Get the single exit of BB.
755 if (R && R->getEntry() == BB)
757 else if (++succ_begin(BB) == succ_end(BB))
758 Exit = *succ_begin(BB);
759 else // No single exit exists.
762 // Get largest region that starts at Exit.
763 Region *ExitR = getRegionFor(Exit);
764 while (ExitR && ExitR->getParent()
765 && ExitR->getParent()->getEntry() == Exit)
766 ExitR = ExitR->getParent();
768 for (pred_iterator PI = pred_begin(Exit), PE = pred_end(Exit); PI != PE;
770 if (!R->contains(*PI) && !ExitR->contains(*PI))
773 // This stops infinite cycles.
774 if (DT->dominates(Exit, BB))
784 RegionInfo::getCommonRegion(Region *A, Region *B) const {
785 assert (A && B && "One of the Regions is NULL");
787 if (A->contains(B)) return A;
789 while (!B->contains(A))
796 RegionInfo::getCommonRegion(SmallVectorImpl<Region*> &Regions) const {
797 Region* ret = Regions.back();
800 for (SmallVectorImpl<Region*>::const_iterator I = Regions.begin(),
801 E = Regions.end(); I != E; ++I)
802 ret = getCommonRegion(ret, *I);
808 RegionInfo::getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const {
809 Region* ret = getRegionFor(BBs.back());
812 for (SmallVectorImpl<BasicBlock*>::const_iterator I = BBs.begin(),
813 E = BBs.end(); I != E; ++I)
814 ret = getCommonRegion(ret, getRegionFor(*I));
819 void RegionInfo::splitBlock(BasicBlock* NewBB, BasicBlock *OldBB)
821 Region *R = getRegionFor(OldBB);
823 setRegionFor(NewBB, R);
825 while (R->getEntry() == OldBB && !R->isTopLevelRegion()) {
826 R->replaceEntry(NewBB);
830 setRegionFor(OldBB, R);
833 char RegionInfo::ID = 0;
834 INITIALIZE_PASS_BEGIN(RegionInfo, "regions",
835 "Detect single entry single exit regions", true, true)
836 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
837 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
838 INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
839 INITIALIZE_PASS_END(RegionInfo, "regions",
840 "Detect single entry single exit regions", true, true)
842 // Create methods available outside of this file, to use them
843 // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
844 // the link time optimization.
847 FunctionPass *createRegionInfoPass() {
848 return new RegionInfo();