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 static cl::opt<enum Region::PrintStyle> printStyle("print-region-style",
46 cl::desc("style of printing regions"),
48 clEnumValN(Region::PrintNone, "none", "print no details"),
49 clEnumValN(Region::PrintBB, "bb",
50 "print regions in detail with block_iterator"),
51 clEnumValN(Region::PrintRN, "rn",
52 "print regions in detail with element_iterator"),
54 //===----------------------------------------------------------------------===//
55 /// Region Implementation
56 Region::Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RInfo,
57 DominatorTree *dt, Region *Parent)
58 : RegionNode(Parent, Entry, 1), RI(RInfo), DT(dt), exit(Exit) {}
61 // Free the cached nodes.
62 for (BBNodeMapT::iterator it = BBNodeMap.begin(),
63 ie = BBNodeMap.end(); it != ie; ++it)
66 // Only clean the cache for this Region. Caches of child Regions will be
67 // cleaned when the child Regions are deleted.
70 for (iterator I = begin(), E = end(); I != E; ++I)
74 void Region::replaceEntry(BasicBlock *BB) {
78 void Region::replaceExit(BasicBlock *BB) {
79 assert(exit && "No exit to replace!");
83 bool Region::contains(const BasicBlock *B) const {
84 BasicBlock *BB = const_cast<BasicBlock*>(B);
86 assert(DT->getNode(BB) && "BB not part of the dominance tree");
88 BasicBlock *entry = getEntry(), *exit = getExit();
94 return (DT->dominates(entry, BB)
95 && !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
98 bool Region::contains(const Loop *L) const {
99 // BBs that are not part of any loop are element of the Loop
100 // described by the NULL pointer. This loop is not part of any region,
101 // except if the region describes the whole function.
103 return getExit() == 0;
105 if (!contains(L->getHeader()))
108 SmallVector<BasicBlock *, 8> ExitingBlocks;
109 L->getExitingBlocks(ExitingBlocks);
111 for (SmallVectorImpl<BasicBlock*>::iterator BI = ExitingBlocks.begin(),
112 BE = ExitingBlocks.end(); BI != BE; ++BI)
119 Loop *Region::outermostLoopInRegion(Loop *L) const {
123 while (L && contains(L->getParentLoop())) {
124 L = L->getParentLoop();
130 Loop *Region::outermostLoopInRegion(LoopInfo *LI, BasicBlock* BB) const {
131 assert(LI && BB && "LI and BB cannot be null!");
132 Loop *L = LI->getLoopFor(BB);
133 return outermostLoopInRegion(L);
136 BasicBlock *Region::getEnteringBlock() const {
137 BasicBlock *entry = getEntry();
139 BasicBlock *enteringBlock = 0;
141 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
144 if (DT->getNode(Pred) && !contains(Pred)) {
148 enteringBlock = Pred;
152 return enteringBlock;
155 BasicBlock *Region::getExitingBlock() const {
156 BasicBlock *exit = getExit();
158 BasicBlock *exitingBlock = 0;
163 for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
166 if (contains(Pred)) {
177 bool Region::isSimple() const {
178 return !isTopLevelRegion() && getEnteringBlock() && getExitingBlock();
181 std::string Region::getNameStr() const {
182 std::string exitName;
183 std::string entryName;
185 if (getEntry()->getName().empty()) {
186 raw_string_ostream OS(entryName);
188 WriteAsOperand(OS, getEntry(), false);
190 entryName = getEntry()->getName();
193 if (getExit()->getName().empty()) {
194 raw_string_ostream OS(exitName);
196 WriteAsOperand(OS, getExit(), false);
198 exitName = getExit()->getName();
200 exitName = "<Function Return>";
202 return entryName + " => " + exitName;
205 void Region::verifyBBInRegion(BasicBlock *BB) const {
207 llvm_unreachable("Broken region found!");
209 BasicBlock *entry = getEntry(), *exit = getExit();
211 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
212 if (!contains(*SI) && exit != *SI)
213 llvm_unreachable("Broken region found!");
216 for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB); SI != SE; ++SI)
218 llvm_unreachable("Broken region found!");
221 void Region::verifyWalk(BasicBlock *BB, std::set<BasicBlock*> *visited) const {
222 BasicBlock *exit = getExit();
226 verifyBBInRegion(BB);
228 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
229 if (*SI != exit && visited->find(*SI) == visited->end())
230 verifyWalk(*SI, visited);
233 void Region::verifyRegion() const {
234 // Only do verification when user wants to, otherwise this expensive
235 // check will be invoked by PassManager.
236 if (!VerifyRegionInfo) return;
238 std::set<BasicBlock*> visited;
239 verifyWalk(getEntry(), &visited);
242 void Region::verifyRegionNest() const {
243 for (Region::const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
244 (*RI)->verifyRegionNest();
249 Region::element_iterator Region::element_begin() {
250 return GraphTraits<Region*>::nodes_begin(this);
253 Region::element_iterator Region::element_end() {
254 return GraphTraits<Region*>::nodes_end(this);
257 Region::const_element_iterator Region::element_begin() const {
258 return GraphTraits<const Region*>::nodes_begin(this);
261 Region::const_element_iterator Region::element_end() const {
262 return GraphTraits<const Region*>::nodes_end(this);
265 Region* Region::getSubRegionNode(BasicBlock *BB) const {
266 Region *R = RI->getRegionFor(BB);
271 // If we pass the BB out of this region, that means our code is broken.
272 assert(contains(R) && "BB not in current region!");
274 while (contains(R->getParent()) && R->getParent() != this)
277 if (R->getEntry() != BB)
283 RegionNode* Region::getBBNode(BasicBlock *BB) const {
284 assert(contains(BB) && "Can get BB node out of this region!");
286 BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
288 if (at != BBNodeMap.end())
291 RegionNode *NewNode = new RegionNode(const_cast<Region*>(this), BB);
292 BBNodeMap.insert(std::make_pair(BB, NewNode));
296 RegionNode* Region::getNode(BasicBlock *BB) const {
297 assert(contains(BB) && "Can get BB node out of this region!");
298 if (Region* Child = getSubRegionNode(BB))
299 return Child->getNode();
301 return getBBNode(BB);
304 void Region::transferChildrenTo(Region *To) {
305 for (iterator I = begin(), E = end(); I != E; ++I) {
307 To->children.push_back(*I);
312 void Region::addSubRegion(Region *SubRegion, bool moveChildren) {
313 assert(SubRegion->parent == 0 && "SubRegion already has a parent!");
314 assert(std::find(begin(), end(), SubRegion) == children.end()
315 && "Subregion already exists!");
317 SubRegion->parent = this;
318 children.push_back(SubRegion);
323 assert(SubRegion->children.size() == 0
324 && "SubRegions that contain children are not supported");
326 for (element_iterator I = element_begin(), E = element_end(); I != E; ++I)
327 if (!(*I)->isSubRegion()) {
328 BasicBlock *BB = (*I)->getNodeAs<BasicBlock>();
330 if (SubRegion->contains(BB))
331 RI->setRegionFor(BB, SubRegion);
334 std::vector<Region*> Keep;
335 for (iterator I = begin(), E = end(); I != E; ++I)
336 if (SubRegion->contains(*I) && *I != SubRegion) {
337 SubRegion->children.push_back(*I);
338 (*I)->parent = SubRegion;
343 children.insert(children.begin(), Keep.begin(), Keep.end());
347 Region *Region::removeSubRegion(Region *Child) {
348 assert(Child->parent == this && "Child is not a child of this region!");
350 RegionSet::iterator I = std::find(children.begin(), children.end(), Child);
351 assert(I != children.end() && "Region does not exit. Unable to remove.");
352 children.erase(children.begin()+(I-begin()));
356 unsigned Region::getDepth() const {
359 for (Region *R = parent; R != 0; R = R->parent)
365 Region *Region::getExpandedRegion() const {
366 unsigned NumSuccessors = exit->getTerminator()->getNumSuccessors();
368 if (NumSuccessors == 0)
371 for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
373 if (!DT->dominates(getEntry(), *PI))
376 Region *R = RI->getRegionFor(exit);
378 if (R->getEntry() != exit) {
379 if (exit->getTerminator()->getNumSuccessors() == 1)
380 return new Region(getEntry(), *succ_begin(exit), RI, DT);
385 while (R->getParent() && R->getParent()->getEntry() == exit)
388 if (!DT->dominates(getEntry(), R->getExit()))
389 for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
391 if (!DT->dominates(R->getExit(), *PI))
394 return new Region(getEntry(), R->getExit(), RI, DT);
397 void Region::print(raw_ostream &OS, bool print_tree, unsigned level,
398 enum PrintStyle Style) const {
400 OS.indent(level*2) << "[" << level << "] " << getNameStr();
402 OS.indent(level*2) << getNameStr();
407 if (Style != PrintNone) {
408 OS.indent(level*2) << "{\n";
409 OS.indent(level*2 + 2);
411 if (Style == PrintBB) {
412 for (const_block_iterator I = block_begin(), E = block_end(); I != E; ++I)
413 OS << (*I)->getName() << ", "; // TODO: remove the last ","
414 } else if (Style == PrintRN) {
415 for (const_element_iterator I = element_begin(), E = element_end(); I!=E; ++I)
416 OS << **I << ", "; // TODO: remove the last ",
423 for (const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
424 (*RI)->print(OS, print_tree, level+1, Style);
426 if (Style != PrintNone)
427 OS.indent(level*2) << "} \n";
430 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
431 void Region::dump() const {
432 print(dbgs(), true, getDepth(), printStyle.getValue());
436 void Region::clearNodeCache() {
437 // Free the cached nodes.
438 for (BBNodeMapT::iterator I = BBNodeMap.begin(),
439 IE = BBNodeMap.end(); I != IE; ++I)
443 for (Region::iterator RI = begin(), RE = end(); RI != RE; ++RI)
444 (*RI)->clearNodeCache();
447 //===----------------------------------------------------------------------===//
448 // RegionInfo implementation
451 bool RegionInfo::isCommonDomFrontier(BasicBlock *BB, BasicBlock *entry,
452 BasicBlock *exit) const {
453 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
455 if (DT->dominates(entry, P) && !DT->dominates(exit, P))
461 bool RegionInfo::isRegion(BasicBlock *entry, BasicBlock *exit) const {
462 assert(entry && exit && "entry and exit must not be null!");
463 typedef DominanceFrontier::DomSetType DST;
465 DST *entrySuccs = &DF->find(entry)->second;
467 // Exit is the header of a loop that contains the entry. In this case,
468 // the dominance frontier must only contain the exit.
469 if (!DT->dominates(entry, exit)) {
470 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
472 if (*SI != exit && *SI != entry)
478 DST *exitSuccs = &DF->find(exit)->second;
480 // Do not allow edges leaving the region.
481 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
483 if (*SI == exit || *SI == entry)
485 if (exitSuccs->find(*SI) == exitSuccs->end())
487 if (!isCommonDomFrontier(*SI, entry, exit))
491 // Do not allow edges pointing into the region.
492 for (DST::iterator SI = exitSuccs->begin(), SE = exitSuccs->end();
494 if (DT->properlyDominates(entry, *SI) && *SI != exit)
501 void RegionInfo::insertShortCut(BasicBlock *entry, BasicBlock *exit,
502 BBtoBBMap *ShortCut) const {
503 assert(entry && exit && "entry and exit must not be null!");
505 BBtoBBMap::iterator e = ShortCut->find(exit);
507 if (e == ShortCut->end())
508 // No further region at exit available.
509 (*ShortCut)[entry] = exit;
511 // We found a region e that starts at exit. Therefore (entry, e->second)
512 // is also a region, that is larger than (entry, exit). Insert the
514 BasicBlock *BB = e->second;
515 (*ShortCut)[entry] = BB;
519 DomTreeNode* RegionInfo::getNextPostDom(DomTreeNode* N,
520 BBtoBBMap *ShortCut) const {
521 BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
523 if (e == ShortCut->end())
526 return PDT->getNode(e->second)->getIDom();
529 bool RegionInfo::isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const {
530 assert(entry && exit && "entry and exit must not be null!");
532 unsigned num_successors = succ_end(entry) - succ_begin(entry);
534 if (num_successors <= 1 && exit == *(succ_begin(entry)))
540 void RegionInfo::updateStatistics(Region *R) {
543 // TODO: Slow. Should only be enabled if -stats is used.
544 if (R->isSimple()) ++numSimpleRegions;
547 Region *RegionInfo::createRegion(BasicBlock *entry, BasicBlock *exit) {
548 assert(entry && exit && "entry and exit must not be null!");
550 if (isTrivialRegion(entry, exit))
553 Region *region = new Region(entry, exit, this, DT);
554 BBtoRegion.insert(std::make_pair(entry, region));
557 region->verifyRegion();
559 DEBUG(region->verifyRegion());
562 updateStatistics(region);
566 void RegionInfo::findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut) {
569 DomTreeNode *N = PDT->getNode(entry);
574 Region *lastRegion= 0;
575 BasicBlock *lastExit = entry;
577 // As only a BasicBlock that postdominates entry can finish a region, walk the
578 // post dominance tree upwards.
579 while ((N = getNextPostDom(N, ShortCut))) {
580 BasicBlock *exit = N->getBlock();
585 if (isRegion(entry, exit)) {
586 Region *newRegion = createRegion(entry, exit);
589 newRegion->addSubRegion(lastRegion);
591 lastRegion = newRegion;
595 // This can never be a region, so stop the search.
596 if (!DT->dominates(entry, exit))
600 // Tried to create regions from entry to lastExit. Next time take a
601 // shortcut from entry to lastExit.
602 if (lastExit != entry)
603 insertShortCut(entry, lastExit, ShortCut);
606 void RegionInfo::scanForRegions(Function &F, BBtoBBMap *ShortCut) {
607 BasicBlock *entry = &(F.getEntryBlock());
608 DomTreeNode *N = DT->getNode(entry);
610 // Iterate over the dominance tree in post order to start with the small
611 // regions from the bottom of the dominance tree. If the small regions are
612 // detected first, detection of bigger regions is faster, as we can jump
613 // over the small regions.
614 for (po_iterator<DomTreeNode*> FI = po_begin(N), FE = po_end(N); FI != FE;
616 findRegionsWithEntry(FI->getBlock(), ShortCut);
620 Region *RegionInfo::getTopMostParent(Region *region) {
621 while (region->parent)
622 region = region->getParent();
627 void RegionInfo::buildRegionsTree(DomTreeNode *N, Region *region) {
628 BasicBlock *BB = N->getBlock();
630 // Passed region exit
631 while (BB == region->getExit())
632 region = region->getParent();
634 BBtoRegionMap::iterator it = BBtoRegion.find(BB);
636 // This basic block is a start block of a region. It is already in the
637 // BBtoRegion relation. Only the child basic blocks have to be updated.
638 if (it != BBtoRegion.end()) {
639 Region *newRegion = it->second;
640 region->addSubRegion(getTopMostParent(newRegion));
643 BBtoRegion[BB] = region;
646 for (DomTreeNode::iterator CI = N->begin(), CE = N->end(); CI != CE; ++CI)
647 buildRegionsTree(*CI, region);
650 void RegionInfo::releaseMemory() {
653 delete TopLevelRegion;
657 RegionInfo::RegionInfo() : FunctionPass(ID) {
658 initializeRegionInfoPass(*PassRegistry::getPassRegistry());
662 RegionInfo::~RegionInfo() {
666 void RegionInfo::Calculate(Function &F) {
667 // ShortCut a function where for every BB the exit of the largest region
668 // starting with BB is stored. These regions can be threated as single BBS.
669 // This improves performance on linear CFGs.
672 scanForRegions(F, &ShortCut);
673 BasicBlock *BB = &F.getEntryBlock();
674 buildRegionsTree(DT->getNode(BB), TopLevelRegion);
677 bool RegionInfo::runOnFunction(Function &F) {
680 DT = &getAnalysis<DominatorTree>();
681 PDT = &getAnalysis<PostDominatorTree>();
682 DF = &getAnalysis<DominanceFrontier>();
684 TopLevelRegion = new Region(&F.getEntryBlock(), 0, this, DT, 0);
685 updateStatistics(TopLevelRegion);
692 void RegionInfo::getAnalysisUsage(AnalysisUsage &AU) const {
693 AU.setPreservesAll();
694 AU.addRequiredTransitive<DominatorTree>();
695 AU.addRequired<PostDominatorTree>();
696 AU.addRequired<DominanceFrontier>();
699 void RegionInfo::print(raw_ostream &OS, const Module *) const {
700 OS << "Region tree:\n";
701 TopLevelRegion->print(OS, true, 0, printStyle.getValue());
702 OS << "End region tree\n";
705 void RegionInfo::verifyAnalysis() const {
706 // Only do verification when user wants to, otherwise this expensive check
707 // will be invoked by PMDataManager::verifyPreservedAnalysis when
708 // a regionpass (marked PreservedAll) finish.
709 if (!VerifyRegionInfo) return;
711 TopLevelRegion->verifyRegionNest();
714 // Region pass manager support.
715 Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
716 BBtoRegionMap::const_iterator I=
718 return I != BBtoRegion.end() ? I->second : 0;
721 void RegionInfo::setRegionFor(BasicBlock *BB, Region *R) {
725 Region *RegionInfo::operator[](BasicBlock *BB) const {
726 return getRegionFor(BB);
729 BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
730 BasicBlock *Exit = NULL;
733 // Get largest region that starts at BB.
734 Region *R = getRegionFor(BB);
735 while (R && R->getParent() && R->getParent()->getEntry() == BB)
738 // Get the single exit of BB.
739 if (R && R->getEntry() == BB)
741 else if (++succ_begin(BB) == succ_end(BB))
742 Exit = *succ_begin(BB);
743 else // No single exit exists.
746 // Get largest region that starts at Exit.
747 Region *ExitR = getRegionFor(Exit);
748 while (ExitR && ExitR->getParent()
749 && ExitR->getParent()->getEntry() == Exit)
750 ExitR = ExitR->getParent();
752 for (pred_iterator PI = pred_begin(Exit), PE = pred_end(Exit); PI != PE;
754 if (!R->contains(*PI) && !ExitR->contains(*PI))
757 // This stops infinite cycles.
758 if (DT->dominates(Exit, BB))
768 RegionInfo::getCommonRegion(Region *A, Region *B) const {
769 assert (A && B && "One of the Regions is NULL");
771 if (A->contains(B)) return A;
773 while (!B->contains(A))
780 RegionInfo::getCommonRegion(SmallVectorImpl<Region*> &Regions) const {
781 Region* ret = Regions.back();
784 for (SmallVectorImpl<Region*>::const_iterator I = Regions.begin(),
785 E = Regions.end(); I != E; ++I)
786 ret = getCommonRegion(ret, *I);
792 RegionInfo::getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const {
793 Region* ret = getRegionFor(BBs.back());
796 for (SmallVectorImpl<BasicBlock*>::const_iterator I = BBs.begin(),
797 E = BBs.end(); I != E; ++I)
798 ret = getCommonRegion(ret, getRegionFor(*I));
803 void RegionInfo::splitBlock(BasicBlock* NewBB, BasicBlock *OldBB)
805 Region *R = getRegionFor(OldBB);
807 setRegionFor(NewBB, R);
809 while (R->getEntry() == OldBB && !R->isTopLevelRegion()) {
810 R->replaceEntry(NewBB);
814 setRegionFor(OldBB, R);
817 char RegionInfo::ID = 0;
818 INITIALIZE_PASS_BEGIN(RegionInfo, "regions",
819 "Detect single entry single exit regions", true, true)
820 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
821 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
822 INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
823 INITIALIZE_PASS_END(RegionInfo, "regions",
824 "Detect single entry single exit regions", true, true)
826 // Create methods available outside of this file, to use them
827 // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
828 // the link time optimization.
831 FunctionPass *createRegionInfoPass() {
832 return new RegionInfo();