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 bool VerifyRegionInfo = true;
34 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 // Only clean the cache for this Region. Caches of child Regions will be
63 // cleaned when the child Regions are deleted.
66 for (iterator I = begin(), E = end(); I != E; ++I)
70 bool Region::contains(const BasicBlock *B) const {
71 BasicBlock *BB = const_cast<BasicBlock*>(B);
73 assert(DT->getNode(BB) && "BB not part of the dominance tree");
75 BasicBlock *entry = getEntry(), *exit = getExit();
81 return (DT->dominates(entry, BB)
82 && !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
85 bool Region::contains(const Loop *L) const {
86 // BBs that are not part of any loop are element of the Loop
87 // described by the NULL pointer. This loop is not part of any region,
88 // except if the region describes the whole function.
90 return getExit() == 0;
92 if (!contains(L->getHeader()))
95 SmallVector<BasicBlock *, 8> ExitingBlocks;
96 L->getExitingBlocks(ExitingBlocks);
98 for (SmallVectorImpl<BasicBlock*>::iterator BI = ExitingBlocks.begin(),
99 BE = ExitingBlocks.end(); BI != BE; ++BI)
106 Loop *Region::outermostLoopInRegion(Loop *L) const {
110 while (L && contains(L->getParentLoop())) {
111 L = L->getParentLoop();
117 Loop *Region::outermostLoopInRegion(LoopInfo *LI, BasicBlock* BB) const {
118 assert(LI && BB && "LI and BB cannot be null!");
119 Loop *L = LI->getLoopFor(BB);
120 return outermostLoopInRegion(L);
123 bool Region::isSimple() const {
124 bool isSimple = true;
127 BasicBlock *entry = getEntry(), *exit = getExit();
133 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
135 if (!contains(*PI)) {
145 for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
158 std::string Region::getNameStr() const {
159 std::string exitName;
160 std::string entryName;
162 if (getEntry()->getName().empty()) {
163 raw_string_ostream OS(entryName);
165 WriteAsOperand(OS, getEntry(), false);
166 entryName = OS.str();
168 entryName = getEntry()->getNameStr();
171 if (getExit()->getName().empty()) {
172 raw_string_ostream OS(exitName);
174 WriteAsOperand(OS, getExit(), false);
177 exitName = getExit()->getNameStr();
179 exitName = "<Function Return>";
181 return entryName + " => " + exitName;
184 void Region::verifyBBInRegion(BasicBlock *BB) const {
186 llvm_unreachable("Broken region found!");
188 BasicBlock *entry = getEntry(), *exit = getExit();
190 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
191 if (!contains(*SI) && exit != *SI)
192 llvm_unreachable("Broken region found!");
195 for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB); SI != SE; ++SI)
197 llvm_unreachable("Broken region found!");
200 void Region::verifyWalk(BasicBlock *BB, std::set<BasicBlock*> *visited) const {
201 BasicBlock *exit = getExit();
205 verifyBBInRegion(BB);
207 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
208 if (*SI != exit && visited->find(*SI) == visited->end())
209 verifyWalk(*SI, visited);
212 void Region::verifyRegion() const {
213 // Only do verification when user wants to, otherwise this expensive
214 // check will be invoked by PassManager.
215 if (!VerifyRegionInfo) return;
217 std::set<BasicBlock*> visited;
218 verifyWalk(getEntry(), &visited);
221 void Region::verifyRegionNest() const {
222 for (Region::const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
223 (*RI)->verifyRegionNest();
228 Region::block_iterator Region::block_begin() {
229 return GraphTraits<FlatIt<Region*> >::nodes_begin(this);
232 Region::block_iterator Region::block_end() {
233 return GraphTraits<FlatIt<Region*> >::nodes_end(this);
236 Region::const_block_iterator Region::block_begin() const {
237 return GraphTraits<FlatIt<const Region*> >::nodes_begin(this);
240 Region::const_block_iterator Region::block_end() const {
241 return GraphTraits<FlatIt<const Region*> >::nodes_end(this);
244 Region::element_iterator Region::element_begin() {
245 return GraphTraits<Region*>::nodes_begin(this);
248 Region::element_iterator Region::element_end() {
249 return GraphTraits<Region*>::nodes_end(this);
252 Region::const_element_iterator Region::element_begin() const {
253 return GraphTraits<const Region*>::nodes_begin(this);
256 Region::const_element_iterator Region::element_end() const {
257 return GraphTraits<const Region*>::nodes_end(this);
260 Region* Region::getSubRegionNode(BasicBlock *BB) const {
261 Region *R = RI->getRegionFor(BB);
266 // If we pass the BB out of this region, that means our code is broken.
267 assert(contains(R) && "BB not in current region!");
269 while (contains(R->getParent()) && R->getParent() != this)
272 if (R->getEntry() != BB)
278 RegionNode* Region::getBBNode(BasicBlock *BB) const {
279 assert(contains(BB) && "Can get BB node out of this region!");
281 BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
283 if (at != BBNodeMap.end())
286 RegionNode *NewNode = new RegionNode(const_cast<Region*>(this), BB);
287 BBNodeMap.insert(std::make_pair(BB, NewNode));
291 RegionNode* Region::getNode(BasicBlock *BB) const {
292 assert(contains(BB) && "Can get BB node out of this region!");
293 if (Region* Child = getSubRegionNode(BB))
294 return Child->getNode();
296 return getBBNode(BB);
299 void Region::transferChildrenTo(Region *To) {
300 for (iterator I = begin(), E = end(); I != E; ++I) {
302 To->children.push_back(*I);
307 void Region::addSubRegion(Region *SubRegion) {
308 assert(SubRegion->parent == 0 && "SubRegion already has a parent!");
309 SubRegion->parent = this;
310 // Set up the region node.
311 assert(std::find(children.begin(), children.end(), SubRegion) == children.end()
312 && "Node already exist!");
313 children.push_back(SubRegion);
317 Region *Region::removeSubRegion(Region *Child) {
318 assert(Child->parent == this && "Child is not a child of this region!");
320 RegionSet::iterator I = std::find(children.begin(), children.end(), Child);
321 assert(I != children.end() && "Region does not exit. Unable to remove.");
322 children.erase(children.begin()+(I-begin()));
326 unsigned Region::getDepth() const {
329 for (Region *R = parent; R != 0; R = R->parent)
335 void Region::print(raw_ostream &OS, bool print_tree, unsigned level) const {
337 OS.indent(level*2) << "[" << level << "] " << getNameStr();
339 OS.indent(level*2) << getNameStr();
344 if (printStyle != PrintNone) {
345 OS.indent(level*2) << "{\n";
346 OS.indent(level*2 + 2);
348 if (printStyle == PrintBB) {
349 for (const_block_iterator I = block_begin(), E = block_end(); I!=E; ++I)
350 OS << **I << ", "; // TODO: remove the last ","
351 } else if (printStyle == PrintRN) {
352 for (const_element_iterator I = element_begin(), E = element_end(); I!=E; ++I)
353 OS << **I << ", "; // TODO: remove the last ",
360 for (const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
361 (*RI)->print(OS, print_tree, level+1);
363 if (printStyle != PrintNone)
364 OS.indent(level*2) << "} \n";
367 void Region::dump() const {
368 print(dbgs(), true, getDepth());
371 void Region::clearNodeCache() {
373 for (Region::iterator RI = begin(), RE = end(); RI != RE; ++RI)
374 (*RI)->clearNodeCache();
377 //===----------------------------------------------------------------------===//
378 // RegionInfo implementation
381 bool RegionInfo::isCommonDomFrontier(BasicBlock *BB, BasicBlock *entry,
382 BasicBlock *exit) const {
383 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
385 if (DT->dominates(entry, P) && !DT->dominates(exit, P))
391 bool RegionInfo::isRegion(BasicBlock *entry, BasicBlock *exit) const {
392 assert(entry && exit && "entry and exit must not be null!");
393 typedef DominanceFrontier::DomSetType DST;
395 DST *entrySuccs = &DF->find(entry)->second;
397 // Exit is the header of a loop that contains the entry. In this case,
398 // the dominance frontier must only contain the exit.
399 if (!DT->dominates(entry, exit)) {
400 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
402 if (*SI != exit && *SI != entry)
408 DST *exitSuccs = &DF->find(exit)->second;
410 // Do not allow edges leaving the region.
411 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
413 if (*SI == exit || *SI == entry)
415 if (exitSuccs->find(*SI) == exitSuccs->end())
417 if (!isCommonDomFrontier(*SI, entry, exit))
421 // Do not allow edges pointing into the region.
422 for (DST::iterator SI = exitSuccs->begin(), SE = exitSuccs->end();
424 if (DT->properlyDominates(entry, *SI) && *SI != exit)
431 void RegionInfo::insertShortCut(BasicBlock *entry, BasicBlock *exit,
432 BBtoBBMap *ShortCut) const {
433 assert(entry && exit && "entry and exit must not be null!");
435 BBtoBBMap::iterator e = ShortCut->find(exit);
437 if (e == ShortCut->end())
438 // No further region at exit available.
439 (*ShortCut)[entry] = exit;
441 // We found a region e that starts at exit. Therefore (entry, e->second)
442 // is also a region, that is larger than (entry, exit). Insert the
444 BasicBlock *BB = e->second;
445 (*ShortCut)[entry] = BB;
449 DomTreeNode* RegionInfo::getNextPostDom(DomTreeNode* N,
450 BBtoBBMap *ShortCut) const {
451 BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
453 if (e == ShortCut->end())
456 return PDT->getNode(e->second)->getIDom();
459 bool RegionInfo::isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const {
460 assert(entry && exit && "entry and exit must not be null!");
462 unsigned num_successors = succ_end(entry) - succ_begin(entry);
464 if (num_successors <= 1 && exit == *(succ_begin(entry)))
470 void RegionInfo::updateStatistics(Region *R) {
473 // TODO: Slow. Should only be enabled if -stats is used.
474 if (R->isSimple()) ++numSimpleRegions;
477 Region *RegionInfo::createRegion(BasicBlock *entry, BasicBlock *exit) {
478 assert(entry && exit && "entry and exit must not be null!");
480 if (isTrivialRegion(entry, exit))
483 Region *region = new Region(entry, exit, this, DT);
484 BBtoRegion.insert(std::make_pair(entry, region));
487 region->verifyRegion();
489 DEBUG(region->verifyRegion());
492 updateStatistics(region);
496 void RegionInfo::findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut) {
499 DomTreeNode *N = PDT->getNode(entry);
504 Region *lastRegion= 0;
505 BasicBlock *lastExit = entry;
507 // As only a BasicBlock that postdominates entry can finish a region, walk the
508 // post dominance tree upwards.
509 while ((N = getNextPostDom(N, ShortCut))) {
510 BasicBlock *exit = N->getBlock();
515 if (isRegion(entry, exit)) {
516 Region *newRegion = createRegion(entry, exit);
519 newRegion->addSubRegion(lastRegion);
521 lastRegion = newRegion;
525 // This can never be a region, so stop the search.
526 if (!DT->dominates(entry, exit))
530 // Tried to create regions from entry to lastExit. Next time take a
531 // shortcut from entry to lastExit.
532 if (lastExit != entry)
533 insertShortCut(entry, lastExit, ShortCut);
536 void RegionInfo::scanForRegions(Function &F, BBtoBBMap *ShortCut) {
537 BasicBlock *entry = &(F.getEntryBlock());
538 DomTreeNode *N = DT->getNode(entry);
540 // Iterate over the dominance tree in post order to start with the small
541 // regions from the bottom of the dominance tree. If the small regions are
542 // detected first, detection of bigger regions is faster, as we can jump
543 // over the small regions.
544 for (po_iterator<DomTreeNode*> FI = po_begin(N), FE = po_end(N); FI != FE;
546 findRegionsWithEntry(FI->getBlock(), ShortCut);
550 Region *RegionInfo::getTopMostParent(Region *region) {
551 while (region->parent)
552 region = region->getParent();
557 void RegionInfo::buildRegionsTree(DomTreeNode *N, Region *region) {
558 BasicBlock *BB = N->getBlock();
560 // Passed region exit
561 while (BB == region->getExit())
562 region = region->getParent();
564 BBtoRegionMap::iterator it = BBtoRegion.find(BB);
566 // This basic block is a start block of a region. It is already in the
567 // BBtoRegion relation. Only the child basic blocks have to be updated.
568 if (it != BBtoRegion.end()) {
569 Region *newRegion = it->second;;
570 region->addSubRegion(getTopMostParent(newRegion));
573 BBtoRegion[BB] = region;
576 for (DomTreeNode::iterator CI = N->begin(), CE = N->end(); CI != CE; ++CI)
577 buildRegionsTree(*CI, region);
580 void RegionInfo::releaseMemory() {
583 delete TopLevelRegion;
587 RegionInfo::RegionInfo() : FunctionPass(&ID) {
591 RegionInfo::~RegionInfo() {
595 void RegionInfo::Calculate(Function &F) {
596 // ShortCut a function where for every BB the exit of the largest region
597 // starting with BB is stored. These regions can be threated as single BBS.
598 // This improves performance on linear CFGs.
601 scanForRegions(F, &ShortCut);
602 BasicBlock *BB = &F.getEntryBlock();
603 buildRegionsTree(DT->getNode(BB), TopLevelRegion);
606 bool RegionInfo::runOnFunction(Function &F) {
609 DT = &getAnalysis<DominatorTree>();
610 PDT = &getAnalysis<PostDominatorTree>();
611 DF = &getAnalysis<DominanceFrontier>();
613 TopLevelRegion = new Region(&F.getEntryBlock(), 0, this, DT, 0);
614 updateStatistics(TopLevelRegion);
621 void RegionInfo::getAnalysisUsage(AnalysisUsage &AU) const {
622 AU.setPreservesAll();
623 AU.addRequiredTransitive<DominatorTree>();
624 AU.addRequired<PostDominatorTree>();
625 AU.addRequired<DominanceFrontier>();
628 void RegionInfo::print(raw_ostream &OS, const Module *) const {
629 OS << "Region tree:\n";
630 TopLevelRegion->print(OS, true, 0);
631 OS << "End region tree\n";
634 void RegionInfo::verifyAnalysis() const {
635 // Only do verification when user wants to, otherwise this expensive check
636 // will be invoked by PMDataManager::verifyPreservedAnalysis when
637 // a regionpass (marked PreservedAll) finish.
638 if (!VerifyRegionInfo) return;
640 TopLevelRegion->verifyRegionNest();
643 // Region pass manager support.
644 Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
645 BBtoRegionMap::const_iterator I=
647 return I != BBtoRegion.end() ? I->second : 0;
650 Region *RegionInfo::operator[](BasicBlock *BB) const {
651 return getRegionFor(BB);
655 BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
656 BasicBlock *Exit = NULL;
659 // Get largest region that starts at BB.
660 Region *R = getRegionFor(BB);
661 while (R && R->getParent() && R->getParent()->getEntry() == BB)
664 // Get the single exit of BB.
665 if (R && R->getEntry() == BB)
667 else if (++succ_begin(BB) == succ_end(BB))
668 Exit = *succ_begin(BB);
669 else // No single exit exists.
672 // Get largest region that starts at Exit.
673 Region *ExitR = getRegionFor(Exit);
674 while (ExitR && ExitR->getParent()
675 && ExitR->getParent()->getEntry() == Exit)
676 ExitR = ExitR->getParent();
678 for (pred_iterator PI = pred_begin(Exit), PE = pred_end(Exit); PI != PE;
680 if (!R->contains(*PI) && !ExitR->contains(*PI))
683 // This stops infinite cycles.
684 if (DT->dominates(Exit, BB))
694 RegionInfo::getCommonRegion(Region *A, Region *B) const {
695 assert (A && B && "One of the Regions is NULL");
697 if (A->contains(B)) return A;
699 while (!B->contains(A))
706 RegionInfo::getCommonRegion(SmallVectorImpl<Region*> &Regions) const {
707 Region* ret = Regions.back();
710 for (SmallVectorImpl<Region*>::const_iterator I = Regions.begin(),
711 E = Regions.end(); I != E; ++I)
712 ret = getCommonRegion(ret, *I);
718 RegionInfo::getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const {
719 Region* ret = getRegionFor(BBs.back());
722 for (SmallVectorImpl<BasicBlock*>::const_iterator I = BBs.begin(),
723 E = BBs.end(); I != E; ++I)
724 ret = getCommonRegion(ret, getRegionFor(*I));
729 char RegionInfo::ID = 0;
730 INITIALIZE_PASS(RegionInfo, "regions",
731 "Detect single entry single exit regions", true, true);
733 // Create methods available outside of this file, to use them
734 // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
735 // the link time optimization.
738 FunctionPass *createRegionInfoPass() {
739 return new RegionInfo();