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/Support/raw_ostream.h"
20 #include "llvm/Analysis/LoopInfo.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 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 bool Region::isSimple() const {
138 bool isSimple = true;
141 BasicBlock *entry = getEntry(), *exit = getExit();
147 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
149 BasicBlock *Pred = *PI;
150 if (DT->getNode(Pred) && !contains(Pred)) {
161 for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
174 std::string Region::getNameStr() const {
175 std::string exitName;
176 std::string entryName;
178 if (getEntry()->getName().empty()) {
179 raw_string_ostream OS(entryName);
181 WriteAsOperand(OS, getEntry(), false);
182 entryName = OS.str();
184 entryName = getEntry()->getNameStr();
187 if (getExit()->getName().empty()) {
188 raw_string_ostream OS(exitName);
190 WriteAsOperand(OS, getExit(), false);
193 exitName = getExit()->getNameStr();
195 exitName = "<Function Return>";
197 return entryName + " => " + exitName;
200 void Region::verifyBBInRegion(BasicBlock *BB) const {
202 llvm_unreachable("Broken region found!");
204 BasicBlock *entry = getEntry(), *exit = getExit();
206 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
207 if (!contains(*SI) && exit != *SI)
208 llvm_unreachable("Broken region found!");
211 for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB); SI != SE; ++SI)
213 llvm_unreachable("Broken region found!");
216 void Region::verifyWalk(BasicBlock *BB, std::set<BasicBlock*> *visited) const {
217 BasicBlock *exit = getExit();
221 verifyBBInRegion(BB);
223 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
224 if (*SI != exit && visited->find(*SI) == visited->end())
225 verifyWalk(*SI, visited);
228 void Region::verifyRegion() const {
229 // Only do verification when user wants to, otherwise this expensive
230 // check will be invoked by PassManager.
231 if (!VerifyRegionInfo) return;
233 std::set<BasicBlock*> visited;
234 verifyWalk(getEntry(), &visited);
237 void Region::verifyRegionNest() const {
238 for (Region::const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
239 (*RI)->verifyRegionNest();
244 Region::block_iterator Region::block_begin() {
245 return GraphTraits<FlatIt<Region*> >::nodes_begin(this);
248 Region::block_iterator Region::block_end() {
249 return GraphTraits<FlatIt<Region*> >::nodes_end(this);
252 Region::const_block_iterator Region::block_begin() const {
253 return GraphTraits<FlatIt<const Region*> >::nodes_begin(this);
256 Region::const_block_iterator Region::block_end() const {
257 return GraphTraits<FlatIt<const Region*> >::nodes_end(this);
260 Region::element_iterator Region::element_begin() {
261 return GraphTraits<Region*>::nodes_begin(this);
264 Region::element_iterator Region::element_end() {
265 return GraphTraits<Region*>::nodes_end(this);
268 Region::const_element_iterator Region::element_begin() const {
269 return GraphTraits<const Region*>::nodes_begin(this);
272 Region::const_element_iterator Region::element_end() const {
273 return GraphTraits<const Region*>::nodes_end(this);
276 Region* Region::getSubRegionNode(BasicBlock *BB) const {
277 Region *R = RI->getRegionFor(BB);
282 // If we pass the BB out of this region, that means our code is broken.
283 assert(contains(R) && "BB not in current region!");
285 while (contains(R->getParent()) && R->getParent() != this)
288 if (R->getEntry() != BB)
294 RegionNode* Region::getBBNode(BasicBlock *BB) const {
295 assert(contains(BB) && "Can get BB node out of this region!");
297 BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
299 if (at != BBNodeMap.end())
302 RegionNode *NewNode = new RegionNode(const_cast<Region*>(this), BB);
303 BBNodeMap.insert(std::make_pair(BB, NewNode));
307 RegionNode* Region::getNode(BasicBlock *BB) const {
308 assert(contains(BB) && "Can get BB node out of this region!");
309 if (Region* Child = getSubRegionNode(BB))
310 return Child->getNode();
312 return getBBNode(BB);
315 void Region::transferChildrenTo(Region *To) {
316 for (iterator I = begin(), E = end(); I != E; ++I) {
318 To->children.push_back(*I);
323 void Region::addSubRegion(Region *SubRegion, bool moveChildren) {
324 assert(SubRegion->parent == 0 && "SubRegion already has a parent!");
325 assert(std::find(begin(), end(), SubRegion) == children.end()
326 && "Subregion already exists!");
328 SubRegion->parent = this;
329 children.push_back(SubRegion);
334 assert(SubRegion->children.size() == 0
335 && "SubRegions that contain children are not supported");
337 for (element_iterator I = element_begin(), E = element_end(); I != E; ++I)
338 if (!(*I)->isSubRegion()) {
339 BasicBlock *BB = (*I)->getNodeAs<BasicBlock>();
341 if (SubRegion->contains(BB))
342 RI->setRegionFor(BB, SubRegion);
345 std::vector<Region*> Keep;
346 for (iterator I = begin(), E = end(); I != E; ++I)
347 if (SubRegion->contains(*I) && *I != SubRegion) {
348 SubRegion->children.push_back(*I);
349 (*I)->parent = SubRegion;
354 children.insert(children.begin(), Keep.begin(), Keep.end());
358 Region *Region::removeSubRegion(Region *Child) {
359 assert(Child->parent == this && "Child is not a child of this region!");
361 RegionSet::iterator I = std::find(children.begin(), children.end(), Child);
362 assert(I != children.end() && "Region does not exit. Unable to remove.");
363 children.erase(children.begin()+(I-begin()));
367 unsigned Region::getDepth() const {
370 for (Region *R = parent; R != 0; R = R->parent)
376 void Region::print(raw_ostream &OS, bool print_tree, unsigned level) const {
378 OS.indent(level*2) << "[" << level << "] " << getNameStr();
380 OS.indent(level*2) << getNameStr();
385 if (printStyle != PrintNone) {
386 OS.indent(level*2) << "{\n";
387 OS.indent(level*2 + 2);
389 if (printStyle == PrintBB) {
390 for (const_block_iterator I = block_begin(), E = block_end(); I!=E; ++I)
391 OS << **I << ", "; // TODO: remove the last ","
392 } else if (printStyle == PrintRN) {
393 for (const_element_iterator I = element_begin(), E = element_end(); I!=E; ++I)
394 OS << **I << ", "; // TODO: remove the last ",
401 for (const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
402 (*RI)->print(OS, print_tree, level+1);
404 if (printStyle != PrintNone)
405 OS.indent(level*2) << "} \n";
408 void Region::dump() const {
409 print(dbgs(), true, getDepth());
412 void Region::clearNodeCache() {
413 // Free the cached nodes.
414 for (BBNodeMapT::iterator I = BBNodeMap.begin(),
415 IE = BBNodeMap.end(); I != IE; ++IE)
419 for (Region::iterator RI = begin(), RE = end(); RI != RE; ++RI)
420 (*RI)->clearNodeCache();
423 //===----------------------------------------------------------------------===//
424 // RegionInfo implementation
427 bool RegionInfo::isCommonDomFrontier(BasicBlock *BB, BasicBlock *entry,
428 BasicBlock *exit) const {
429 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
431 if (DT->dominates(entry, P) && !DT->dominates(exit, P))
437 bool RegionInfo::isRegion(BasicBlock *entry, BasicBlock *exit) const {
438 assert(entry && exit && "entry and exit must not be null!");
439 typedef DominanceFrontier::DomSetType DST;
441 DST *entrySuccs = &DF->find(entry)->second;
443 // Exit is the header of a loop that contains the entry. In this case,
444 // the dominance frontier must only contain the exit.
445 if (!DT->dominates(entry, exit)) {
446 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
448 if (*SI != exit && *SI != entry)
454 DST *exitSuccs = &DF->find(exit)->second;
456 // Do not allow edges leaving the region.
457 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
459 if (*SI == exit || *SI == entry)
461 if (exitSuccs->find(*SI) == exitSuccs->end())
463 if (!isCommonDomFrontier(*SI, entry, exit))
467 // Do not allow edges pointing into the region.
468 for (DST::iterator SI = exitSuccs->begin(), SE = exitSuccs->end();
470 if (DT->properlyDominates(entry, *SI) && *SI != exit)
477 void RegionInfo::insertShortCut(BasicBlock *entry, BasicBlock *exit,
478 BBtoBBMap *ShortCut) const {
479 assert(entry && exit && "entry and exit must not be null!");
481 BBtoBBMap::iterator e = ShortCut->find(exit);
483 if (e == ShortCut->end())
484 // No further region at exit available.
485 (*ShortCut)[entry] = exit;
487 // We found a region e that starts at exit. Therefore (entry, e->second)
488 // is also a region, that is larger than (entry, exit). Insert the
490 BasicBlock *BB = e->second;
491 (*ShortCut)[entry] = BB;
495 DomTreeNode* RegionInfo::getNextPostDom(DomTreeNode* N,
496 BBtoBBMap *ShortCut) const {
497 BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
499 if (e == ShortCut->end())
502 return PDT->getNode(e->second)->getIDom();
505 bool RegionInfo::isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const {
506 assert(entry && exit && "entry and exit must not be null!");
508 unsigned num_successors = succ_end(entry) - succ_begin(entry);
510 if (num_successors <= 1 && exit == *(succ_begin(entry)))
516 void RegionInfo::updateStatistics(Region *R) {
519 // TODO: Slow. Should only be enabled if -stats is used.
520 if (R->isSimple()) ++numSimpleRegions;
523 Region *RegionInfo::createRegion(BasicBlock *entry, BasicBlock *exit) {
524 assert(entry && exit && "entry and exit must not be null!");
526 if (isTrivialRegion(entry, exit))
529 Region *region = new Region(entry, exit, this, DT);
530 BBtoRegion.insert(std::make_pair(entry, region));
533 region->verifyRegion();
535 DEBUG(region->verifyRegion());
538 updateStatistics(region);
542 void RegionInfo::findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut) {
545 DomTreeNode *N = PDT->getNode(entry);
550 Region *lastRegion= 0;
551 BasicBlock *lastExit = entry;
553 // As only a BasicBlock that postdominates entry can finish a region, walk the
554 // post dominance tree upwards.
555 while ((N = getNextPostDom(N, ShortCut))) {
556 BasicBlock *exit = N->getBlock();
561 if (isRegion(entry, exit)) {
562 Region *newRegion = createRegion(entry, exit);
565 newRegion->addSubRegion(lastRegion);
567 lastRegion = newRegion;
571 // This can never be a region, so stop the search.
572 if (!DT->dominates(entry, exit))
576 // Tried to create regions from entry to lastExit. Next time take a
577 // shortcut from entry to lastExit.
578 if (lastExit != entry)
579 insertShortCut(entry, lastExit, ShortCut);
582 void RegionInfo::scanForRegions(Function &F, BBtoBBMap *ShortCut) {
583 BasicBlock *entry = &(F.getEntryBlock());
584 DomTreeNode *N = DT->getNode(entry);
586 // Iterate over the dominance tree in post order to start with the small
587 // regions from the bottom of the dominance tree. If the small regions are
588 // detected first, detection of bigger regions is faster, as we can jump
589 // over the small regions.
590 for (po_iterator<DomTreeNode*> FI = po_begin(N), FE = po_end(N); FI != FE;
592 findRegionsWithEntry(FI->getBlock(), ShortCut);
596 Region *RegionInfo::getTopMostParent(Region *region) {
597 while (region->parent)
598 region = region->getParent();
603 void RegionInfo::buildRegionsTree(DomTreeNode *N, Region *region) {
604 BasicBlock *BB = N->getBlock();
606 // Passed region exit
607 while (BB == region->getExit())
608 region = region->getParent();
610 BBtoRegionMap::iterator it = BBtoRegion.find(BB);
612 // This basic block is a start block of a region. It is already in the
613 // BBtoRegion relation. Only the child basic blocks have to be updated.
614 if (it != BBtoRegion.end()) {
615 Region *newRegion = it->second;;
616 region->addSubRegion(getTopMostParent(newRegion));
619 BBtoRegion[BB] = region;
622 for (DomTreeNode::iterator CI = N->begin(), CE = N->end(); CI != CE; ++CI)
623 buildRegionsTree(*CI, region);
626 void RegionInfo::releaseMemory() {
629 delete TopLevelRegion;
633 RegionInfo::RegionInfo() : FunctionPass(ID) {
637 RegionInfo::~RegionInfo() {
641 void RegionInfo::Calculate(Function &F) {
642 // ShortCut a function where for every BB the exit of the largest region
643 // starting with BB is stored. These regions can be threated as single BBS.
644 // This improves performance on linear CFGs.
647 scanForRegions(F, &ShortCut);
648 BasicBlock *BB = &F.getEntryBlock();
649 buildRegionsTree(DT->getNode(BB), TopLevelRegion);
652 bool RegionInfo::runOnFunction(Function &F) {
655 DT = &getAnalysis<DominatorTree>();
656 PDT = &getAnalysis<PostDominatorTree>();
657 DF = &getAnalysis<DominanceFrontier>();
659 TopLevelRegion = new Region(&F.getEntryBlock(), 0, this, DT, 0);
660 updateStatistics(TopLevelRegion);
667 void RegionInfo::getAnalysisUsage(AnalysisUsage &AU) const {
668 AU.setPreservesAll();
669 AU.addRequiredTransitive<DominatorTree>();
670 AU.addRequired<PostDominatorTree>();
671 AU.addRequired<DominanceFrontier>();
674 void RegionInfo::print(raw_ostream &OS, const Module *) const {
675 OS << "Region tree:\n";
676 TopLevelRegion->print(OS, true, 0);
677 OS << "End region tree\n";
680 void RegionInfo::verifyAnalysis() const {
681 // Only do verification when user wants to, otherwise this expensive check
682 // will be invoked by PMDataManager::verifyPreservedAnalysis when
683 // a regionpass (marked PreservedAll) finish.
684 if (!VerifyRegionInfo) return;
686 TopLevelRegion->verifyRegionNest();
689 // Region pass manager support.
690 Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
691 BBtoRegionMap::const_iterator I=
693 return I != BBtoRegion.end() ? I->second : 0;
696 void RegionInfo::setRegionFor(BasicBlock *BB, Region *R) {
700 Region *RegionInfo::operator[](BasicBlock *BB) const {
701 return getRegionFor(BB);
704 BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
705 BasicBlock *Exit = NULL;
708 // Get largest region that starts at BB.
709 Region *R = getRegionFor(BB);
710 while (R && R->getParent() && R->getParent()->getEntry() == BB)
713 // Get the single exit of BB.
714 if (R && R->getEntry() == BB)
716 else if (++succ_begin(BB) == succ_end(BB))
717 Exit = *succ_begin(BB);
718 else // No single exit exists.
721 // Get largest region that starts at Exit.
722 Region *ExitR = getRegionFor(Exit);
723 while (ExitR && ExitR->getParent()
724 && ExitR->getParent()->getEntry() == Exit)
725 ExitR = ExitR->getParent();
727 for (pred_iterator PI = pred_begin(Exit), PE = pred_end(Exit); PI != PE;
729 if (!R->contains(*PI) && !ExitR->contains(*PI))
732 // This stops infinite cycles.
733 if (DT->dominates(Exit, BB))
743 RegionInfo::getCommonRegion(Region *A, Region *B) const {
744 assert (A && B && "One of the Regions is NULL");
746 if (A->contains(B)) return A;
748 while (!B->contains(A))
755 RegionInfo::getCommonRegion(SmallVectorImpl<Region*> &Regions) const {
756 Region* ret = Regions.back();
759 for (SmallVectorImpl<Region*>::const_iterator I = Regions.begin(),
760 E = Regions.end(); I != E; ++I)
761 ret = getCommonRegion(ret, *I);
767 RegionInfo::getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const {
768 Region* ret = getRegionFor(BBs.back());
771 for (SmallVectorImpl<BasicBlock*>::const_iterator I = BBs.begin(),
772 E = BBs.end(); I != E; ++I)
773 ret = getCommonRegion(ret, getRegionFor(*I));
778 char RegionInfo::ID = 0;
779 INITIALIZE_PASS_BEGIN(RegionInfo, "regions",
780 "Detect single entry single exit regions", true, true)
781 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
782 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
783 INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
784 INITIALIZE_PASS_END(RegionInfo, "regions",
785 "Detect single entry single exit regions", true, true)
787 // Create methods available outside of this file, to use them
788 // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
789 // the link time optimization.
792 FunctionPass *createRegionInfoPass() {
793 return new RegionInfo();