LLVM API Documentation

RegionInfo.cpp
Go to the documentation of this file.
00001 //===- RegionInfo.cpp - SESE region detection analysis --------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 // Detects single entry single exit regions in the control flow graph.
00010 //===----------------------------------------------------------------------===//
00011 
00012 #define DEBUG_TYPE "region"
00013 #include "llvm/Analysis/RegionInfo.h"
00014 #include "llvm/ADT/PostOrderIterator.h"
00015 #include "llvm/ADT/Statistic.h"
00016 #include "llvm/Analysis/LoopInfo.h"
00017 #include "llvm/Analysis/RegionIterator.h"
00018 #include "llvm/Support/CommandLine.h"
00019 #include "llvm/Support/Debug.h"
00020 #include "llvm/Support/ErrorHandling.h"
00021 #include <algorithm>
00022 #include <iterator>
00023 #include <set>
00024 
00025 using namespace llvm;
00026 
00027 // Always verify if expensive checking is enabled.
00028 #ifdef XDEBUG
00029 static bool VerifyRegionInfo = true;
00030 #else
00031 static bool VerifyRegionInfo = false;
00032 #endif
00033 
00034 static cl::opt<bool,true>
00035 VerifyRegionInfoX("verify-region-info", cl::location(VerifyRegionInfo),
00036                 cl::desc("Verify region info (time consuming)"));
00037 
00038 STATISTIC(numRegions,       "The # of regions");
00039 STATISTIC(numSimpleRegions, "The # of simple regions");
00040 
00041 static cl::opt<enum Region::PrintStyle> printStyle("print-region-style",
00042   cl::Hidden,
00043   cl::desc("style of printing regions"),
00044   cl::values(
00045     clEnumValN(Region::PrintNone, "none",  "print no details"),
00046     clEnumValN(Region::PrintBB, "bb",
00047                "print regions in detail with block_iterator"),
00048     clEnumValN(Region::PrintRN, "rn",
00049                "print regions in detail with element_iterator"),
00050     clEnumValEnd));
00051 //===----------------------------------------------------------------------===//
00052 /// Region Implementation
00053 Region::Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RInfo,
00054                DominatorTree *dt, Region *Parent)
00055                : RegionNode(Parent, Entry, 1), RI(RInfo), DT(dt), exit(Exit) {}
00056 
00057 Region::~Region() {
00058   // Free the cached nodes.
00059   for (BBNodeMapT::iterator it = BBNodeMap.begin(),
00060          ie = BBNodeMap.end(); it != ie; ++it)
00061     delete it->second;
00062 
00063   // Only clean the cache for this Region. Caches of child Regions will be
00064   // cleaned when the child Regions are deleted.
00065   BBNodeMap.clear();
00066 }
00067 
00068 void Region::replaceEntry(BasicBlock *BB) {
00069   entry.setPointer(BB);
00070 }
00071 
00072 void Region::replaceExit(BasicBlock *BB) {
00073   assert(exit && "No exit to replace!");
00074   exit = BB;
00075 }
00076 
00077 void Region::replaceEntryRecursive(BasicBlock *NewEntry) {
00078   std::vector<Region *> RegionQueue;
00079   BasicBlock *OldEntry = getEntry();
00080 
00081   RegionQueue.push_back(this);
00082   while (!RegionQueue.empty()) {
00083     Region *R = RegionQueue.back();
00084     RegionQueue.pop_back();
00085 
00086     R->replaceEntry(NewEntry);
00087     for (Region::const_iterator RI = R->begin(), RE = R->end(); RI != RE; ++RI)
00088       if ((*RI)->getEntry() == OldEntry)
00089         RegionQueue.push_back(RI->get());
00090   }
00091 }
00092 
00093 void Region::replaceExitRecursive(BasicBlock *NewExit) {
00094   std::vector<Region *> RegionQueue;
00095   BasicBlock *OldExit = getExit();
00096 
00097   RegionQueue.push_back(this);
00098   while (!RegionQueue.empty()) {
00099     Region *R = RegionQueue.back();
00100     RegionQueue.pop_back();
00101 
00102     R->replaceExit(NewExit);
00103     for (Region::const_iterator RI = R->begin(), RE = R->end(); RI != RE; ++RI)
00104       if ((*RI)->getExit() == OldExit)
00105         RegionQueue.push_back(RI->get());
00106   }
00107 }
00108 
00109 bool Region::contains(const BasicBlock *B) const {
00110   BasicBlock *BB = const_cast<BasicBlock*>(B);
00111 
00112   if (!DT->getNode(BB))
00113     return false;
00114 
00115   BasicBlock *entry = getEntry(), *exit = getExit();
00116 
00117   // Toplevel region.
00118   if (!exit)
00119     return true;
00120 
00121   return (DT->dominates(entry, BB)
00122     && !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
00123 }
00124 
00125 bool Region::contains(const Loop *L) const {
00126   // BBs that are not part of any loop are element of the Loop
00127   // described by the NULL pointer. This loop is not part of any region,
00128   // except if the region describes the whole function.
00129   if (!L)
00130     return getExit() == nullptr;
00131 
00132   if (!contains(L->getHeader()))
00133     return false;
00134 
00135   SmallVector<BasicBlock *, 8> ExitingBlocks;
00136   L->getExitingBlocks(ExitingBlocks);
00137 
00138   for (SmallVectorImpl<BasicBlock*>::iterator BI = ExitingBlocks.begin(),
00139        BE = ExitingBlocks.end(); BI != BE; ++BI)
00140     if (!contains(*BI))
00141       return false;
00142 
00143   return true;
00144 }
00145 
00146 Loop *Region::outermostLoopInRegion(Loop *L) const {
00147   if (!contains(L))
00148     return nullptr;
00149 
00150   while (L && contains(L->getParentLoop())) {
00151     L = L->getParentLoop();
00152   }
00153 
00154   return L;
00155 }
00156 
00157 Loop *Region::outermostLoopInRegion(LoopInfo *LI, BasicBlock* BB) const {
00158   assert(LI && BB && "LI and BB cannot be null!");
00159   Loop *L = LI->getLoopFor(BB);
00160   return outermostLoopInRegion(L);
00161 }
00162 
00163 BasicBlock *Region::getEnteringBlock() const {
00164   BasicBlock *entry = getEntry();
00165   BasicBlock *Pred;
00166   BasicBlock *enteringBlock = nullptr;
00167 
00168   for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
00169        ++PI) {
00170     Pred = *PI;
00171     if (DT->getNode(Pred) && !contains(Pred)) {
00172       if (enteringBlock)
00173         return nullptr;
00174 
00175       enteringBlock = Pred;
00176     }
00177   }
00178 
00179   return enteringBlock;
00180 }
00181 
00182 BasicBlock *Region::getExitingBlock() const {
00183   BasicBlock *exit = getExit();
00184   BasicBlock *Pred;
00185   BasicBlock *exitingBlock = nullptr;
00186 
00187   if (!exit)
00188     return nullptr;
00189 
00190   for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
00191        ++PI) {
00192     Pred = *PI;
00193     if (contains(Pred)) {
00194       if (exitingBlock)
00195         return nullptr;
00196 
00197       exitingBlock = Pred;
00198     }
00199   }
00200 
00201   return exitingBlock;
00202 }
00203 
00204 bool Region::isSimple() const {
00205   return !isTopLevelRegion() && getEnteringBlock() && getExitingBlock();
00206 }
00207 
00208 std::string Region::getNameStr() const {
00209   std::string exitName;
00210   std::string entryName;
00211 
00212   if (getEntry()->getName().empty()) {
00213     raw_string_ostream OS(entryName);
00214 
00215     getEntry()->printAsOperand(OS, false);
00216   } else
00217     entryName = getEntry()->getName();
00218 
00219   if (getExit()) {
00220     if (getExit()->getName().empty()) {
00221       raw_string_ostream OS(exitName);
00222 
00223       getExit()->printAsOperand(OS, false);
00224     } else
00225       exitName = getExit()->getName();
00226   } else
00227     exitName = "<Function Return>";
00228 
00229   return entryName + " => " + exitName;
00230 }
00231 
00232 void Region::verifyBBInRegion(BasicBlock *BB) const {
00233   if (!contains(BB))
00234     llvm_unreachable("Broken region found!");
00235 
00236   BasicBlock *entry = getEntry(), *exit = getExit();
00237 
00238   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
00239     if (!contains(*SI) && exit != *SI)
00240       llvm_unreachable("Broken region found!");
00241 
00242   if (entry != BB)
00243     for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB); SI != SE; ++SI)
00244       if (!contains(*SI))
00245         llvm_unreachable("Broken region found!");
00246 }
00247 
00248 void Region::verifyWalk(BasicBlock *BB, std::set<BasicBlock*> *visited) const {
00249   BasicBlock *exit = getExit();
00250 
00251   visited->insert(BB);
00252 
00253   verifyBBInRegion(BB);
00254 
00255   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
00256     if (*SI != exit && visited->find(*SI) == visited->end())
00257         verifyWalk(*SI, visited);
00258 }
00259 
00260 void Region::verifyRegion() const {
00261   // Only do verification when user wants to, otherwise this expensive
00262   // check will be invoked by PassManager.
00263   if (!VerifyRegionInfo) return;
00264 
00265   std::set<BasicBlock*> visited;
00266   verifyWalk(getEntry(), &visited);
00267 }
00268 
00269 void Region::verifyRegionNest() const {
00270   for (Region::const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
00271     (*RI)->verifyRegionNest();
00272 
00273   verifyRegion();
00274 }
00275 
00276 Region::element_iterator Region::element_begin() {
00277   return GraphTraits<Region*>::nodes_begin(this);
00278 }
00279 
00280 Region::element_iterator Region::element_end() {
00281   return GraphTraits<Region*>::nodes_end(this);
00282 }
00283 
00284 Region::const_element_iterator Region::element_begin() const {
00285   return GraphTraits<const Region*>::nodes_begin(this);
00286 }
00287 
00288 Region::const_element_iterator Region::element_end() const {
00289   return GraphTraits<const Region*>::nodes_end(this);
00290 }
00291 
00292 Region* Region::getSubRegionNode(BasicBlock *BB) const {
00293   Region *R = RI->getRegionFor(BB);
00294 
00295   if (!R || R == this)
00296     return nullptr;
00297 
00298   // If we pass the BB out of this region, that means our code is broken.
00299   assert(contains(R) && "BB not in current region!");
00300 
00301   while (contains(R->getParent()) && R->getParent() != this)
00302     R = R->getParent();
00303 
00304   if (R->getEntry() != BB)
00305     return nullptr;
00306 
00307   return R;
00308 }
00309 
00310 RegionNode* Region::getBBNode(BasicBlock *BB) const {
00311   assert(contains(BB) && "Can get BB node out of this region!");
00312 
00313   BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
00314 
00315   if (at != BBNodeMap.end())
00316     return at->second;
00317 
00318   RegionNode *NewNode = new RegionNode(const_cast<Region*>(this), BB);
00319   BBNodeMap.insert(std::make_pair(BB, NewNode));
00320   return NewNode;
00321 }
00322 
00323 RegionNode* Region::getNode(BasicBlock *BB) const {
00324   assert(contains(BB) && "Can get BB node out of this region!");
00325   if (Region* Child = getSubRegionNode(BB))
00326     return Child->getNode();
00327 
00328   return getBBNode(BB);
00329 }
00330 
00331 void Region::transferChildrenTo(Region *To) {
00332   for (iterator I = begin(), E = end(); I != E; ++I) {
00333     (*I)->parent = To;
00334     To->children.push_back(std::move(*I));
00335   }
00336   children.clear();
00337 }
00338 
00339 void Region::addSubRegion(Region *SubRegion, bool moveChildren) {
00340   assert(!SubRegion->parent && "SubRegion already has a parent!");
00341   assert(std::find_if(begin(), end(), [&](const std::unique_ptr<Region> &R) {
00342            return R.get() == SubRegion;
00343          }) == children.end() &&
00344          "Subregion already exists!");
00345 
00346   SubRegion->parent = this;
00347   children.push_back(std::unique_ptr<Region>(SubRegion));
00348 
00349   if (!moveChildren)
00350     return;
00351 
00352   assert(SubRegion->children.size() == 0
00353          && "SubRegions that contain children are not supported");
00354 
00355   for (element_iterator I = element_begin(), E = element_end(); I != E; ++I)
00356     if (!(*I)->isSubRegion()) {
00357       BasicBlock *BB = (*I)->getNodeAs<BasicBlock>();
00358 
00359       if (SubRegion->contains(BB))
00360         RI->setRegionFor(BB, SubRegion);
00361     }
00362 
00363   std::vector<std::unique_ptr<Region>> Keep;
00364   for (iterator I = begin(), E = end(); I != E; ++I)
00365     if (SubRegion->contains(I->get()) && I->get() != SubRegion) {
00366       (*I)->parent = SubRegion;
00367       SubRegion->children.push_back(std::move(*I));
00368     } else
00369       Keep.push_back(std::move(*I));
00370 
00371   children.clear();
00372   children.insert(children.begin(),
00373                   std::move_iterator<RegionSet::iterator>(Keep.begin()),
00374                   std::move_iterator<RegionSet::iterator>(Keep.end()));
00375 }
00376 
00377 
00378 Region *Region::removeSubRegion(Region *Child) {
00379   assert(Child->parent == this && "Child is not a child of this region!");
00380   Child->parent = nullptr;
00381   RegionSet::iterator I = std::find_if(
00382       children.begin(), children.end(),
00383       [&](const std::unique_ptr<Region> &R) { return R.get() == Child; });
00384   assert(I != children.end() && "Region does not exit. Unable to remove.");
00385   children.erase(children.begin()+(I-begin()));
00386   return Child;
00387 }
00388 
00389 unsigned Region::getDepth() const {
00390   unsigned Depth = 0;
00391 
00392   for (Region *R = parent; R != nullptr; R = R->parent)
00393     ++Depth;
00394 
00395   return Depth;
00396 }
00397 
00398 Region *Region::getExpandedRegion() const {
00399   unsigned NumSuccessors = exit->getTerminator()->getNumSuccessors();
00400 
00401   if (NumSuccessors == 0)
00402     return nullptr;
00403 
00404   for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
00405        PI != PE; ++PI)
00406     if (!DT->dominates(getEntry(), *PI))
00407       return nullptr;
00408 
00409   Region *R = RI->getRegionFor(exit);
00410 
00411   if (R->getEntry() != exit) {
00412     if (exit->getTerminator()->getNumSuccessors() == 1)
00413       return new Region(getEntry(), *succ_begin(exit), RI, DT);
00414     else
00415       return nullptr;
00416   }
00417 
00418   while (R->getParent() && R->getParent()->getEntry() == exit)
00419     R = R->getParent();
00420 
00421   if (!DT->dominates(getEntry(), R->getExit()))
00422     for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
00423          PI != PE; ++PI)
00424     if (!DT->dominates(R->getExit(), *PI))
00425       return nullptr;
00426 
00427   return new Region(getEntry(), R->getExit(), RI, DT);
00428 }
00429 
00430 void Region::print(raw_ostream &OS, bool print_tree, unsigned level,
00431                    enum PrintStyle Style) const {
00432   if (print_tree)
00433     OS.indent(level*2) << "[" << level << "] " << getNameStr();
00434   else
00435     OS.indent(level*2) << getNameStr();
00436 
00437   OS << "\n";
00438 
00439 
00440   if (Style != PrintNone) {
00441     OS.indent(level*2) << "{\n";
00442     OS.indent(level*2 + 2);
00443 
00444     if (Style == PrintBB) {
00445       for (const auto &BB : blocks())
00446         OS << BB->getName() << ", "; // TODO: remove the last ","
00447     } else if (Style == PrintRN) {
00448       for (const_element_iterator I = element_begin(), E = element_end(); I!=E; ++I)
00449         OS << **I << ", "; // TODO: remove the last ",
00450     }
00451 
00452     OS << "\n";
00453   }
00454 
00455   if (print_tree)
00456     for (const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
00457       (*RI)->print(OS, print_tree, level+1, Style);
00458 
00459   if (Style != PrintNone)
00460     OS.indent(level*2) << "} \n";
00461 }
00462 
00463 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00464 void Region::dump() const {
00465   print(dbgs(), true, getDepth(), printStyle.getValue());
00466 }
00467 #endif
00468 
00469 void Region::clearNodeCache() {
00470   // Free the cached nodes.
00471   for (BBNodeMapT::iterator I = BBNodeMap.begin(),
00472        IE = BBNodeMap.end(); I != IE; ++I)
00473     delete I->second;
00474 
00475   BBNodeMap.clear();
00476   for (Region::iterator RI = begin(), RE = end(); RI != RE; ++RI)
00477     (*RI)->clearNodeCache();
00478 }
00479 
00480 //===----------------------------------------------------------------------===//
00481 // RegionInfo implementation
00482 //
00483 
00484 bool RegionInfo::isCommonDomFrontier(BasicBlock *BB, BasicBlock *entry,
00485                                      BasicBlock *exit) const {
00486   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
00487     BasicBlock *P = *PI;
00488     if (DT->dominates(entry, P) && !DT->dominates(exit, P))
00489       return false;
00490   }
00491   return true;
00492 }
00493 
00494 bool RegionInfo::isRegion(BasicBlock *entry, BasicBlock *exit) const {
00495   assert(entry && exit && "entry and exit must not be null!");
00496   typedef DominanceFrontier::DomSetType DST;
00497 
00498   DST *entrySuccs = &DF->find(entry)->second;
00499 
00500   // Exit is the header of a loop that contains the entry. In this case,
00501   // the dominance frontier must only contain the exit.
00502   if (!DT->dominates(entry, exit)) {
00503     for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
00504          SI != SE; ++SI)
00505       if (*SI != exit && *SI != entry)
00506         return false;
00507 
00508     return true;
00509   }
00510 
00511   DST *exitSuccs = &DF->find(exit)->second;
00512 
00513   // Do not allow edges leaving the region.
00514   for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
00515        SI != SE; ++SI) {
00516     if (*SI == exit || *SI == entry)
00517       continue;
00518     if (exitSuccs->find(*SI) == exitSuccs->end())
00519       return false;
00520     if (!isCommonDomFrontier(*SI, entry, exit))
00521       return false;
00522   }
00523 
00524   // Do not allow edges pointing into the region.
00525   for (DST::iterator SI = exitSuccs->begin(), SE = exitSuccs->end();
00526        SI != SE; ++SI)
00527     if (DT->properlyDominates(entry, *SI) && *SI != exit)
00528       return false;
00529 
00530 
00531   return true;
00532 }
00533 
00534 void RegionInfo::insertShortCut(BasicBlock *entry, BasicBlock *exit,
00535                              BBtoBBMap *ShortCut) const {
00536   assert(entry && exit && "entry and exit must not be null!");
00537 
00538   BBtoBBMap::iterator e = ShortCut->find(exit);
00539 
00540   if (e == ShortCut->end())
00541     // No further region at exit available.
00542     (*ShortCut)[entry] = exit;
00543   else {
00544     // We found a region e that starts at exit. Therefore (entry, e->second)
00545     // is also a region, that is larger than (entry, exit). Insert the
00546     // larger one.
00547     BasicBlock *BB = e->second;
00548     (*ShortCut)[entry] = BB;
00549   }
00550 }
00551 
00552 DomTreeNode* RegionInfo::getNextPostDom(DomTreeNode* N,
00553                                         BBtoBBMap *ShortCut) const {
00554   BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
00555 
00556   if (e == ShortCut->end())
00557     return N->getIDom();
00558 
00559   return PDT->getNode(e->second)->getIDom();
00560 }
00561 
00562 bool RegionInfo::isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const {
00563   assert(entry && exit && "entry and exit must not be null!");
00564 
00565   unsigned num_successors = succ_end(entry) - succ_begin(entry);
00566 
00567   if (num_successors <= 1 && exit == *(succ_begin(entry)))
00568     return true;
00569 
00570   return false;
00571 }
00572 
00573 void RegionInfo::updateStatistics(Region *R) {
00574   ++numRegions;
00575 
00576   // TODO: Slow. Should only be enabled if -stats is used.
00577   if (R->isSimple()) ++numSimpleRegions;
00578 }
00579 
00580 Region *RegionInfo::createRegion(BasicBlock *entry, BasicBlock *exit) {
00581   assert(entry && exit && "entry and exit must not be null!");
00582 
00583   if (isTrivialRegion(entry, exit))
00584     return nullptr;
00585 
00586   Region *region = new Region(entry, exit, this, DT);
00587   BBtoRegion.insert(std::make_pair(entry, region));
00588 
00589  #ifdef XDEBUG
00590     region->verifyRegion();
00591  #else
00592     DEBUG(region->verifyRegion());
00593  #endif
00594 
00595   updateStatistics(region);
00596   return region;
00597 }
00598 
00599 void RegionInfo::findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut) {
00600   assert(entry);
00601 
00602   DomTreeNode *N = PDT->getNode(entry);
00603 
00604   if (!N)
00605     return;
00606 
00607   Region *lastRegion= nullptr;
00608   BasicBlock *lastExit = entry;
00609 
00610   // As only a BasicBlock that postdominates entry can finish a region, walk the
00611   // post dominance tree upwards.
00612   while ((N = getNextPostDom(N, ShortCut))) {
00613     BasicBlock *exit = N->getBlock();
00614 
00615     if (!exit)
00616       break;
00617 
00618     if (isRegion(entry, exit)) {
00619       Region *newRegion = createRegion(entry, exit);
00620 
00621       if (lastRegion)
00622         newRegion->addSubRegion(lastRegion);
00623 
00624       lastRegion = newRegion;
00625       lastExit = exit;
00626     }
00627 
00628     // This can never be a region, so stop the search.
00629     if (!DT->dominates(entry, exit))
00630       break;
00631   }
00632 
00633   // Tried to create regions from entry to lastExit.  Next time take a
00634   // shortcut from entry to lastExit.
00635   if (lastExit != entry)
00636     insertShortCut(entry, lastExit, ShortCut);
00637 }
00638 
00639 void RegionInfo::scanForRegions(Function &F, BBtoBBMap *ShortCut) {
00640   BasicBlock *entry = &(F.getEntryBlock());
00641   DomTreeNode *N = DT->getNode(entry);
00642 
00643   // Iterate over the dominance tree in post order to start with the small
00644   // regions from the bottom of the dominance tree.  If the small regions are
00645   // detected first, detection of bigger regions is faster, as we can jump
00646   // over the small regions.
00647   for (po_iterator<DomTreeNode*> FI = po_begin(N), FE = po_end(N); FI != FE;
00648     ++FI) {
00649     findRegionsWithEntry(FI->getBlock(), ShortCut);
00650   }
00651 }
00652 
00653 Region *RegionInfo::getTopMostParent(Region *region) {
00654   while (region->parent)
00655     region = region->getParent();
00656 
00657   return region;
00658 }
00659 
00660 void RegionInfo::buildRegionsTree(DomTreeNode *N, Region *region) {
00661   BasicBlock *BB = N->getBlock();
00662 
00663   // Passed region exit
00664   while (BB == region->getExit())
00665     region = region->getParent();
00666 
00667   BBtoRegionMap::iterator it = BBtoRegion.find(BB);
00668 
00669   // This basic block is a start block of a region. It is already in the
00670   // BBtoRegion relation. Only the child basic blocks have to be updated.
00671   if (it != BBtoRegion.end()) {
00672     Region *newRegion = it->second;
00673     region->addSubRegion(getTopMostParent(newRegion));
00674     region = newRegion;
00675   } else {
00676     BBtoRegion[BB] = region;
00677   }
00678 
00679   for (DomTreeNode::iterator CI = N->begin(), CE = N->end(); CI != CE; ++CI)
00680     buildRegionsTree(*CI, region);
00681 }
00682 
00683 void RegionInfo::releaseMemory() {
00684   BBtoRegion.clear();
00685   if (TopLevelRegion)
00686     delete TopLevelRegion;
00687   TopLevelRegion = nullptr;
00688 }
00689 
00690 RegionInfo::RegionInfo() : FunctionPass(ID) {
00691   initializeRegionInfoPass(*PassRegistry::getPassRegistry());
00692   TopLevelRegion = nullptr;
00693 }
00694 
00695 RegionInfo::~RegionInfo() {
00696   releaseMemory();
00697 }
00698 
00699 void RegionInfo::Calculate(Function &F) {
00700   // ShortCut a function where for every BB the exit of the largest region
00701   // starting with BB is stored. These regions can be threated as single BBS.
00702   // This improves performance on linear CFGs.
00703   BBtoBBMap ShortCut;
00704 
00705   scanForRegions(F, &ShortCut);
00706   BasicBlock *BB = &F.getEntryBlock();
00707   buildRegionsTree(DT->getNode(BB), TopLevelRegion);
00708 }
00709 
00710 bool RegionInfo::runOnFunction(Function &F) {
00711   releaseMemory();
00712 
00713   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00714   PDT = &getAnalysis<PostDominatorTree>();
00715   DF = &getAnalysis<DominanceFrontier>();
00716 
00717   TopLevelRegion = new Region(&F.getEntryBlock(), nullptr, this, DT, nullptr);
00718   updateStatistics(TopLevelRegion);
00719 
00720   Calculate(F);
00721 
00722   return false;
00723 }
00724 
00725 void RegionInfo::getAnalysisUsage(AnalysisUsage &AU) const {
00726   AU.setPreservesAll();
00727   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
00728   AU.addRequired<PostDominatorTree>();
00729   AU.addRequired<DominanceFrontier>();
00730 }
00731 
00732 void RegionInfo::print(raw_ostream &OS, const Module *) const {
00733   OS << "Region tree:\n";
00734   TopLevelRegion->print(OS, true, 0, printStyle.getValue());
00735   OS << "End region tree\n";
00736 }
00737 
00738 void RegionInfo::verifyAnalysis() const {
00739   // Only do verification when user wants to, otherwise this expensive check
00740   // will be invoked by PMDataManager::verifyPreservedAnalysis when
00741   // a regionpass (marked PreservedAll) finish.
00742   if (!VerifyRegionInfo) return;
00743 
00744   TopLevelRegion->verifyRegionNest();
00745 }
00746 
00747 // Region pass manager support.
00748 Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
00749   BBtoRegionMap::const_iterator I=
00750     BBtoRegion.find(BB);
00751   return I != BBtoRegion.end() ? I->second : nullptr;
00752 }
00753 
00754 void RegionInfo::setRegionFor(BasicBlock *BB, Region *R) {
00755   BBtoRegion[BB] = R;
00756 }
00757 
00758 Region *RegionInfo::operator[](BasicBlock *BB) const {
00759   return getRegionFor(BB);
00760 }
00761 
00762 BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
00763   BasicBlock *Exit = nullptr;
00764 
00765   while (true) {
00766     // Get largest region that starts at BB.
00767     Region *R = getRegionFor(BB);
00768     while (R && R->getParent() && R->getParent()->getEntry() == BB)
00769       R = R->getParent();
00770 
00771     // Get the single exit of BB.
00772     if (R && R->getEntry() == BB)
00773       Exit = R->getExit();
00774     else if (++succ_begin(BB) == succ_end(BB))
00775       Exit = *succ_begin(BB);
00776     else // No single exit exists.
00777       return Exit;
00778 
00779     // Get largest region that starts at Exit.
00780     Region *ExitR = getRegionFor(Exit);
00781     while (ExitR && ExitR->getParent()
00782            && ExitR->getParent()->getEntry() == Exit)
00783       ExitR = ExitR->getParent();
00784 
00785     for (pred_iterator PI = pred_begin(Exit), PE = pred_end(Exit); PI != PE;
00786          ++PI)
00787       if (!R->contains(*PI) && !ExitR->contains(*PI))
00788         break;
00789 
00790     // This stops infinite cycles.
00791     if (DT->dominates(Exit, BB))
00792       break;
00793 
00794     BB = Exit;
00795   }
00796 
00797   return Exit;
00798 }
00799 
00800 Region*
00801 RegionInfo::getCommonRegion(Region *A, Region *B) const {
00802   assert (A && B && "One of the Regions is NULL");
00803 
00804   if (A->contains(B)) return A;
00805 
00806   while (!B->contains(A))
00807     B = B->getParent();
00808 
00809   return B;
00810 }
00811 
00812 Region*
00813 RegionInfo::getCommonRegion(SmallVectorImpl<Region*> &Regions) const {
00814   Region* ret = Regions.back();
00815   Regions.pop_back();
00816 
00817   for (SmallVectorImpl<Region*>::const_iterator I = Regions.begin(),
00818        E = Regions.end(); I != E; ++I)
00819       ret = getCommonRegion(ret, *I);
00820 
00821   return ret;
00822 }
00823 
00824 Region*
00825 RegionInfo::getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const {
00826   Region* ret = getRegionFor(BBs.back());
00827   BBs.pop_back();
00828 
00829   for (SmallVectorImpl<BasicBlock*>::const_iterator I = BBs.begin(),
00830        E = BBs.end(); I != E; ++I)
00831       ret = getCommonRegion(ret, getRegionFor(*I));
00832 
00833   return ret;
00834 }
00835 
00836 void RegionInfo::splitBlock(BasicBlock* NewBB, BasicBlock *OldBB)
00837 {
00838   Region *R = getRegionFor(OldBB);
00839 
00840   setRegionFor(NewBB, R);
00841 
00842   while (R->getEntry() == OldBB && !R->isTopLevelRegion()) {
00843     R->replaceEntry(NewBB);
00844     R = R->getParent();
00845   }
00846 
00847   setRegionFor(OldBB, R);
00848 }
00849 
00850 char RegionInfo::ID = 0;
00851 INITIALIZE_PASS_BEGIN(RegionInfo, "regions",
00852                 "Detect single entry single exit regions", true, true)
00853 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00854 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
00855 INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
00856 INITIALIZE_PASS_END(RegionInfo, "regions",
00857                 "Detect single entry single exit regions", true, true)
00858 
00859 // Create methods available outside of this file, to use them
00860 // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
00861 // the link time optimization.
00862 
00863 namespace llvm {
00864   FunctionPass *createRegionInfoPass() {
00865     return new RegionInfo();
00866   }
00867 }
00868