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 bool Region::contains(const BasicBlock *B) const {
76 BasicBlock *BB = const_cast<BasicBlock*>(B);
78 assert(DT->getNode(BB) && "BB not part of the dominance tree");
80 BasicBlock *entry = getEntry(), *exit = getExit();
86 return (DT->dominates(entry, BB)
87 && !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
90 bool Region::contains(const Loop *L) const {
91 // BBs that are not part of any loop are element of the Loop
92 // described by the NULL pointer. This loop is not part of any region,
93 // except if the region describes the whole function.
95 return getExit() == 0;
97 if (!contains(L->getHeader()))
100 SmallVector<BasicBlock *, 8> ExitingBlocks;
101 L->getExitingBlocks(ExitingBlocks);
103 for (SmallVectorImpl<BasicBlock*>::iterator BI = ExitingBlocks.begin(),
104 BE = ExitingBlocks.end(); BI != BE; ++BI)
111 Loop *Region::outermostLoopInRegion(Loop *L) const {
115 while (L && contains(L->getParentLoop())) {
116 L = L->getParentLoop();
122 Loop *Region::outermostLoopInRegion(LoopInfo *LI, BasicBlock* BB) const {
123 assert(LI && BB && "LI and BB cannot be null!");
124 Loop *L = LI->getLoopFor(BB);
125 return outermostLoopInRegion(L);
128 bool Region::isSimple() const {
129 bool isSimple = true;
132 BasicBlock *entry = getEntry(), *exit = getExit();
138 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
140 BasicBlock *Pred = *PI;
141 if (DT->getNode(Pred) && !contains(Pred)) {
152 for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
165 std::string Region::getNameStr() const {
166 std::string exitName;
167 std::string entryName;
169 if (getEntry()->getName().empty()) {
170 raw_string_ostream OS(entryName);
172 WriteAsOperand(OS, getEntry(), false);
173 entryName = OS.str();
175 entryName = getEntry()->getNameStr();
178 if (getExit()->getName().empty()) {
179 raw_string_ostream OS(exitName);
181 WriteAsOperand(OS, getExit(), false);
184 exitName = getExit()->getNameStr();
186 exitName = "<Function Return>";
188 return entryName + " => " + exitName;
191 void Region::verifyBBInRegion(BasicBlock *BB) const {
193 llvm_unreachable("Broken region found!");
195 BasicBlock *entry = getEntry(), *exit = getExit();
197 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
198 if (!contains(*SI) && exit != *SI)
199 llvm_unreachable("Broken region found!");
202 for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB); SI != SE; ++SI)
204 llvm_unreachable("Broken region found!");
207 void Region::verifyWalk(BasicBlock *BB, std::set<BasicBlock*> *visited) const {
208 BasicBlock *exit = getExit();
212 verifyBBInRegion(BB);
214 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
215 if (*SI != exit && visited->find(*SI) == visited->end())
216 verifyWalk(*SI, visited);
219 void Region::verifyRegion() const {
220 // Only do verification when user wants to, otherwise this expensive
221 // check will be invoked by PassManager.
222 if (!VerifyRegionInfo) return;
224 std::set<BasicBlock*> visited;
225 verifyWalk(getEntry(), &visited);
228 void Region::verifyRegionNest() const {
229 for (Region::const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
230 (*RI)->verifyRegionNest();
235 Region::block_iterator Region::block_begin() {
236 return GraphTraits<FlatIt<Region*> >::nodes_begin(this);
239 Region::block_iterator Region::block_end() {
240 return GraphTraits<FlatIt<Region*> >::nodes_end(this);
243 Region::const_block_iterator Region::block_begin() const {
244 return GraphTraits<FlatIt<const Region*> >::nodes_begin(this);
247 Region::const_block_iterator Region::block_end() const {
248 return GraphTraits<FlatIt<const Region*> >::nodes_end(this);
251 Region::element_iterator Region::element_begin() {
252 return GraphTraits<Region*>::nodes_begin(this);
255 Region::element_iterator Region::element_end() {
256 return GraphTraits<Region*>::nodes_end(this);
259 Region::const_element_iterator Region::element_begin() const {
260 return GraphTraits<const Region*>::nodes_begin(this);
263 Region::const_element_iterator Region::element_end() const {
264 return GraphTraits<const Region*>::nodes_end(this);
267 Region* Region::getSubRegionNode(BasicBlock *BB) const {
268 Region *R = RI->getRegionFor(BB);
273 // If we pass the BB out of this region, that means our code is broken.
274 assert(contains(R) && "BB not in current region!");
276 while (contains(R->getParent()) && R->getParent() != this)
279 if (R->getEntry() != BB)
285 RegionNode* Region::getBBNode(BasicBlock *BB) const {
286 assert(contains(BB) && "Can get BB node out of this region!");
288 BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
290 if (at != BBNodeMap.end())
293 RegionNode *NewNode = new RegionNode(const_cast<Region*>(this), BB);
294 BBNodeMap.insert(std::make_pair(BB, NewNode));
298 RegionNode* Region::getNode(BasicBlock *BB) const {
299 assert(contains(BB) && "Can get BB node out of this region!");
300 if (Region* Child = getSubRegionNode(BB))
301 return Child->getNode();
303 return getBBNode(BB);
306 void Region::transferChildrenTo(Region *To) {
307 for (iterator I = begin(), E = end(); I != E; ++I) {
309 To->children.push_back(*I);
314 void Region::addSubRegion(Region *SubRegion) {
315 assert(SubRegion->parent == 0 && "SubRegion already has a parent!");
316 SubRegion->parent = this;
317 // Set up the region node.
318 assert(std::find(children.begin(), children.end(), SubRegion) == children.end()
319 && "Node already exist!");
320 children.push_back(SubRegion);
324 Region *Region::removeSubRegion(Region *Child) {
325 assert(Child->parent == this && "Child is not a child of this region!");
327 RegionSet::iterator I = std::find(children.begin(), children.end(), Child);
328 assert(I != children.end() && "Region does not exit. Unable to remove.");
329 children.erase(children.begin()+(I-begin()));
333 unsigned Region::getDepth() const {
336 for (Region *R = parent; R != 0; R = R->parent)
342 void Region::print(raw_ostream &OS, bool print_tree, unsigned level) const {
344 OS.indent(level*2) << "[" << level << "] " << getNameStr();
346 OS.indent(level*2) << getNameStr();
351 if (printStyle != PrintNone) {
352 OS.indent(level*2) << "{\n";
353 OS.indent(level*2 + 2);
355 if (printStyle == PrintBB) {
356 for (const_block_iterator I = block_begin(), E = block_end(); I!=E; ++I)
357 OS << **I << ", "; // TODO: remove the last ","
358 } else if (printStyle == PrintRN) {
359 for (const_element_iterator I = element_begin(), E = element_end(); I!=E; ++I)
360 OS << **I << ", "; // TODO: remove the last ",
367 for (const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
368 (*RI)->print(OS, print_tree, level+1);
370 if (printStyle != PrintNone)
371 OS.indent(level*2) << "} \n";
374 void Region::dump() const {
375 print(dbgs(), true, getDepth());
378 void Region::clearNodeCache() {
380 for (Region::iterator RI = begin(), RE = end(); RI != RE; ++RI)
381 (*RI)->clearNodeCache();
384 //===----------------------------------------------------------------------===//
385 // RegionInfo implementation
388 bool RegionInfo::isCommonDomFrontier(BasicBlock *BB, BasicBlock *entry,
389 BasicBlock *exit) const {
390 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
392 if (DT->dominates(entry, P) && !DT->dominates(exit, P))
398 bool RegionInfo::isRegion(BasicBlock *entry, BasicBlock *exit) const {
399 assert(entry && exit && "entry and exit must not be null!");
400 typedef DominanceFrontier::DomSetType DST;
402 DST *entrySuccs = &DF->find(entry)->second;
404 // Exit is the header of a loop that contains the entry. In this case,
405 // the dominance frontier must only contain the exit.
406 if (!DT->dominates(entry, exit)) {
407 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
409 if (*SI != exit && *SI != entry)
415 DST *exitSuccs = &DF->find(exit)->second;
417 // Do not allow edges leaving the region.
418 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
420 if (*SI == exit || *SI == entry)
422 if (exitSuccs->find(*SI) == exitSuccs->end())
424 if (!isCommonDomFrontier(*SI, entry, exit))
428 // Do not allow edges pointing into the region.
429 for (DST::iterator SI = exitSuccs->begin(), SE = exitSuccs->end();
431 if (DT->properlyDominates(entry, *SI) && *SI != exit)
438 void RegionInfo::insertShortCut(BasicBlock *entry, BasicBlock *exit,
439 BBtoBBMap *ShortCut) const {
440 assert(entry && exit && "entry and exit must not be null!");
442 BBtoBBMap::iterator e = ShortCut->find(exit);
444 if (e == ShortCut->end())
445 // No further region at exit available.
446 (*ShortCut)[entry] = exit;
448 // We found a region e that starts at exit. Therefore (entry, e->second)
449 // is also a region, that is larger than (entry, exit). Insert the
451 BasicBlock *BB = e->second;
452 (*ShortCut)[entry] = BB;
456 DomTreeNode* RegionInfo::getNextPostDom(DomTreeNode* N,
457 BBtoBBMap *ShortCut) const {
458 BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
460 if (e == ShortCut->end())
463 return PDT->getNode(e->second)->getIDom();
466 bool RegionInfo::isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const {
467 assert(entry && exit && "entry and exit must not be null!");
469 unsigned num_successors = succ_end(entry) - succ_begin(entry);
471 if (num_successors <= 1 && exit == *(succ_begin(entry)))
477 void RegionInfo::updateStatistics(Region *R) {
480 // TODO: Slow. Should only be enabled if -stats is used.
481 if (R->isSimple()) ++numSimpleRegions;
484 Region *RegionInfo::createRegion(BasicBlock *entry, BasicBlock *exit) {
485 assert(entry && exit && "entry and exit must not be null!");
487 if (isTrivialRegion(entry, exit))
490 Region *region = new Region(entry, exit, this, DT);
491 BBtoRegion.insert(std::make_pair(entry, region));
494 region->verifyRegion();
496 DEBUG(region->verifyRegion());
499 updateStatistics(region);
503 void RegionInfo::findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut) {
506 DomTreeNode *N = PDT->getNode(entry);
511 Region *lastRegion= 0;
512 BasicBlock *lastExit = entry;
514 // As only a BasicBlock that postdominates entry can finish a region, walk the
515 // post dominance tree upwards.
516 while ((N = getNextPostDom(N, ShortCut))) {
517 BasicBlock *exit = N->getBlock();
522 if (isRegion(entry, exit)) {
523 Region *newRegion = createRegion(entry, exit);
526 newRegion->addSubRegion(lastRegion);
528 lastRegion = newRegion;
532 // This can never be a region, so stop the search.
533 if (!DT->dominates(entry, exit))
537 // Tried to create regions from entry to lastExit. Next time take a
538 // shortcut from entry to lastExit.
539 if (lastExit != entry)
540 insertShortCut(entry, lastExit, ShortCut);
543 void RegionInfo::scanForRegions(Function &F, BBtoBBMap *ShortCut) {
544 BasicBlock *entry = &(F.getEntryBlock());
545 DomTreeNode *N = DT->getNode(entry);
547 // Iterate over the dominance tree in post order to start with the small
548 // regions from the bottom of the dominance tree. If the small regions are
549 // detected first, detection of bigger regions is faster, as we can jump
550 // over the small regions.
551 for (po_iterator<DomTreeNode*> FI = po_begin(N), FE = po_end(N); FI != FE;
553 findRegionsWithEntry(FI->getBlock(), ShortCut);
557 Region *RegionInfo::getTopMostParent(Region *region) {
558 while (region->parent)
559 region = region->getParent();
564 void RegionInfo::buildRegionsTree(DomTreeNode *N, Region *region) {
565 BasicBlock *BB = N->getBlock();
567 // Passed region exit
568 while (BB == region->getExit())
569 region = region->getParent();
571 BBtoRegionMap::iterator it = BBtoRegion.find(BB);
573 // This basic block is a start block of a region. It is already in the
574 // BBtoRegion relation. Only the child basic blocks have to be updated.
575 if (it != BBtoRegion.end()) {
576 Region *newRegion = it->second;;
577 region->addSubRegion(getTopMostParent(newRegion));
580 BBtoRegion[BB] = region;
583 for (DomTreeNode::iterator CI = N->begin(), CE = N->end(); CI != CE; ++CI)
584 buildRegionsTree(*CI, region);
587 void RegionInfo::releaseMemory() {
590 delete TopLevelRegion;
594 RegionInfo::RegionInfo() : FunctionPass(ID) {
598 RegionInfo::~RegionInfo() {
602 void RegionInfo::Calculate(Function &F) {
603 // ShortCut a function where for every BB the exit of the largest region
604 // starting with BB is stored. These regions can be threated as single BBS.
605 // This improves performance on linear CFGs.
608 scanForRegions(F, &ShortCut);
609 BasicBlock *BB = &F.getEntryBlock();
610 buildRegionsTree(DT->getNode(BB), TopLevelRegion);
613 bool RegionInfo::runOnFunction(Function &F) {
616 DT = &getAnalysis<DominatorTree>();
617 PDT = &getAnalysis<PostDominatorTree>();
618 DF = &getAnalysis<DominanceFrontier>();
620 TopLevelRegion = new Region(&F.getEntryBlock(), 0, this, DT, 0);
621 updateStatistics(TopLevelRegion);
628 void RegionInfo::getAnalysisUsage(AnalysisUsage &AU) const {
629 AU.setPreservesAll();
630 AU.addRequiredTransitive<DominatorTree>();
631 AU.addRequired<PostDominatorTree>();
632 AU.addRequired<DominanceFrontier>();
635 void RegionInfo::print(raw_ostream &OS, const Module *) const {
636 OS << "Region tree:\n";
637 TopLevelRegion->print(OS, true, 0);
638 OS << "End region tree\n";
641 void RegionInfo::verifyAnalysis() const {
642 // Only do verification when user wants to, otherwise this expensive check
643 // will be invoked by PMDataManager::verifyPreservedAnalysis when
644 // a regionpass (marked PreservedAll) finish.
645 if (!VerifyRegionInfo) return;
647 TopLevelRegion->verifyRegionNest();
650 // Region pass manager support.
651 Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
652 BBtoRegionMap::const_iterator I=
654 return I != BBtoRegion.end() ? I->second : 0;
657 Region *RegionInfo::operator[](BasicBlock *BB) const {
658 return getRegionFor(BB);
662 BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
663 BasicBlock *Exit = NULL;
666 // Get largest region that starts at BB.
667 Region *R = getRegionFor(BB);
668 while (R && R->getParent() && R->getParent()->getEntry() == BB)
671 // Get the single exit of BB.
672 if (R && R->getEntry() == BB)
674 else if (++succ_begin(BB) == succ_end(BB))
675 Exit = *succ_begin(BB);
676 else // No single exit exists.
679 // Get largest region that starts at Exit.
680 Region *ExitR = getRegionFor(Exit);
681 while (ExitR && ExitR->getParent()
682 && ExitR->getParent()->getEntry() == Exit)
683 ExitR = ExitR->getParent();
685 for (pred_iterator PI = pred_begin(Exit), PE = pred_end(Exit); PI != PE;
687 if (!R->contains(*PI) && !ExitR->contains(*PI))
690 // This stops infinite cycles.
691 if (DT->dominates(Exit, BB))
701 RegionInfo::getCommonRegion(Region *A, Region *B) const {
702 assert (A && B && "One of the Regions is NULL");
704 if (A->contains(B)) return A;
706 while (!B->contains(A))
713 RegionInfo::getCommonRegion(SmallVectorImpl<Region*> &Regions) const {
714 Region* ret = Regions.back();
717 for (SmallVectorImpl<Region*>::const_iterator I = Regions.begin(),
718 E = Regions.end(); I != E; ++I)
719 ret = getCommonRegion(ret, *I);
725 RegionInfo::getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const {
726 Region* ret = getRegionFor(BBs.back());
729 for (SmallVectorImpl<BasicBlock*>::const_iterator I = BBs.begin(),
730 E = BBs.end(); I != E; ++I)
731 ret = getCommonRegion(ret, getRegionFor(*I));
736 char RegionInfo::ID = 0;
737 INITIALIZE_PASS(RegionInfo, "regions",
738 "Detect single entry single exit regions", true, true);
740 // Create methods available outside of this file, to use them
741 // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
742 // the link time optimization.
745 FunctionPass *createRegionInfoPass() {
746 return new RegionInfo();