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"
21 #define DEBUG_TYPE "region"
22 #include "llvm/Support/Debug.h"
29 // Always verify if expensive checking is enabled.
31 bool VerifyRegionInfo = true;
33 bool VerifyRegionInfo = false;
36 static cl::opt<bool,true>
37 VerifyRegionInfoX("verify-region-info", cl::location(VerifyRegionInfo),
38 cl::desc("Verify region info (time consuming)"));
40 STATISTIC(numRegions, "The # of regions");
41 STATISTIC(numSimpleRegions, "The # of simple regions");
43 //===----------------------------------------------------------------------===//
44 /// PrintStyle - Print region in difference ways.
45 enum PrintStyle { PrintNone, PrintBB, PrintRN };
47 cl::opt<enum PrintStyle> printStyle("print-region-style", cl::Hidden,
48 cl::desc("style of printing regions"),
50 clEnumValN(PrintNone, "none", "print no details"),
51 clEnumValN(PrintBB, "bb", "print regions in detail with block_iterator"),
52 clEnumValN(PrintRN, "rn", "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 // Only clean the cache for this Region. Caches of child Regions will be
62 // cleaned when the child Regions are deleted.
65 for (iterator I = begin(), E = end(); I != E; ++I)
69 bool Region::contains(const BasicBlock *B) const {
70 BasicBlock *BB = const_cast<BasicBlock*>(B);
72 assert(DT->getNode(BB) && "BB not part of the dominance tree");
74 BasicBlock *entry = getEntry(), *exit = getExit();
80 return (DT->dominates(entry, BB)
81 && !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
84 bool Region::isSimple() const {
88 BasicBlock *entry = getEntry(), *exit = getExit();
94 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
106 for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
119 void Region::verifyBBInRegion(BasicBlock *BB) const {
121 llvm_unreachable("Broken region found!");
123 BasicBlock *entry = getEntry(), *exit = getExit();
125 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
126 if (!contains(*SI) && exit != *SI)
127 llvm_unreachable("Broken region found!");
130 for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB); SI != SE; ++SI)
132 llvm_unreachable("Broken region found!");
135 void Region::verifyWalk(BasicBlock *BB, std::set<BasicBlock*> *visited) const {
136 BasicBlock *exit = getExit();
140 verifyBBInRegion(BB);
142 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
143 if (*SI != exit && visited->find(*SI) == visited->end())
144 verifyWalk(*SI, visited);
147 void Region::verifyRegion() const {
148 // Only do verification when user wants to, otherwise this expensive
149 // check will be invoked by PassManager.
150 if (!VerifyRegionInfo) return;
152 std::set<BasicBlock*> visited;
153 verifyWalk(getEntry(), &visited);
156 void Region::verifyRegionNest() const {
157 for (Region::const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
158 (*RI)->verifyRegionNest();
163 Region::block_iterator Region::block_begin() {
164 return GraphTraits<FlatIt<Region*> >::nodes_begin(this);
167 Region::block_iterator Region::block_end() {
168 return GraphTraits<FlatIt<Region*> >::nodes_end(this);
171 Region::const_block_iterator Region::block_begin() const {
172 return GraphTraits<FlatIt<const Region*> >::nodes_begin(this);
175 Region::const_block_iterator Region::block_end() const {
176 return GraphTraits<FlatIt<const Region*> >::nodes_end(this);
179 Region::element_iterator Region::element_begin() {
180 return GraphTraits<Region*>::nodes_begin(this);
183 Region::element_iterator Region::element_end() {
184 return GraphTraits<Region*>::nodes_end(this);
187 Region::const_element_iterator Region::element_begin() const {
188 return GraphTraits<const Region*>::nodes_begin(this);
191 Region::const_element_iterator Region::element_end() const {
192 return GraphTraits<const Region*>::nodes_end(this);
195 Region* Region::getSubRegionNode(BasicBlock *BB) const {
196 Region *R = RI->getRegionFor(BB);
201 // If we pass the BB out of this region, that means our code is broken.
202 assert(contains(R) && "BB not in current region!");
204 while (contains(R->getParent()) && R->getParent() != this)
207 if (R->getEntry() != BB)
213 RegionNode* Region::getBBNode(BasicBlock *BB) const {
214 assert(contains(BB) && "Can get BB node out of this region!");
216 BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
218 if (at != BBNodeMap.end())
221 RegionNode *NewNode = new RegionNode(const_cast<Region*>(this), BB);
222 BBNodeMap.insert(std::make_pair(BB, NewNode));
226 RegionNode* Region::getNode(BasicBlock *BB) const {
227 assert(contains(BB) && "Can get BB node out of this region!");
228 if (Region* Child = getSubRegionNode(BB))
229 return Child->getNode();
231 return getBBNode(BB);
234 void Region::transferChildrenTo(Region *To) {
235 for (iterator I = begin(), E = end(); I != E; ++I) {
237 To->children.push_back(*I);
242 void Region::addSubRegion(Region *SubRegion) {
243 assert(SubRegion->parent == 0 && "SubRegion already has a parent!");
244 SubRegion->parent = this;
245 // Set up the region node.
246 assert(std::find(children.begin(), children.end(), SubRegion) == children.end()
247 && "Node already exist!");
248 children.push_back(SubRegion);
252 Region *Region::removeSubRegion(Region *Child) {
253 assert(Child->parent == this && "Child is not a child of this region!");
255 RegionSet::iterator I = std::find(children.begin(), children.end(), Child);
256 assert(I != children.end() && "Region does not exit. Unable to remove.");
257 children.erase(children.begin()+(I-begin()));
261 unsigned Region::getDepth() const {
264 for (Region *R = parent; R != 0; R = R->parent)
270 void Region::print(raw_ostream &OS, bool print_tree, unsigned level) const {
272 OS.indent(level*2) << "[" << level << "] " << getNameStr();
274 OS.indent(level*2) << getNameStr();
279 if (printStyle != PrintNone) {
280 OS.indent(level*2) << "{\n";
281 OS.indent(level*2 + 2);
283 if (printStyle == PrintBB) {
284 for (const_block_iterator I = block_begin(), E = block_end(); I!=E; ++I)
285 OS << **I << ", "; // TODO: remove the last ","
286 } else if (printStyle == PrintRN) {
287 for (const_element_iterator I = element_begin(), E = element_end(); I!=E; ++I)
288 OS << **I << ", "; // TODO: remove the last ",
295 for (const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
296 (*RI)->print(OS, print_tree, level+1);
298 if (printStyle != PrintNone)
299 OS.indent(level*2) << "} \n";
302 void Region::dump() const {
303 print(dbgs(), true, getDepth());
306 void Region::clearNodeCache() {
308 for (Region::iterator RI = begin(), RE = end(); RI != RE; ++RI)
309 (*RI)->clearNodeCache();
312 //===----------------------------------------------------------------------===//
313 // RegionInfo implementation
316 bool RegionInfo::isCommonDomFrontier(BasicBlock *BB, BasicBlock *entry,
317 BasicBlock *exit) const {
318 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
320 if (DT->dominates(entry, P) && !DT->dominates(exit, P))
326 bool RegionInfo::isRegion(BasicBlock *entry, BasicBlock *exit) const {
327 assert(entry && exit && "entry and exit must not be null!");
328 typedef DominanceFrontier::DomSetType DST;
330 DST *entrySuccs = &DF->find(entry)->second;
332 // Exit is the header of a loop that contains the entry. In this case,
333 // the dominance frontier must only contain the exit.
334 if (!DT->dominates(entry, exit)) {
335 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
337 if (*SI != exit && *SI != entry)
343 DST *exitSuccs = &DF->find(exit)->second;
345 // Do not allow edges leaving the region.
346 for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
348 if (*SI == exit || *SI == entry)
350 if (exitSuccs->find(*SI) == exitSuccs->end())
352 if (!isCommonDomFrontier(*SI, entry, exit))
356 // Do not allow edges pointing into the region.
357 for (DST::iterator SI = exitSuccs->begin(), SE = exitSuccs->end();
359 if (DT->dominates(entry, *SI) && *SI != entry && *SI != exit)
366 void RegionInfo::insertShortCut(BasicBlock *entry, BasicBlock *exit,
367 BBtoBBMap *ShortCut) const {
368 assert(entry && exit && "entry and exit must not be null!");
370 BBtoBBMap::iterator e = ShortCut->find(exit);
372 if (e == ShortCut->end())
373 // No further region at exit available.
374 (*ShortCut)[entry] = exit;
376 // We found a region e that starts at exit. Therefore (entry, e->second)
377 // is also a region, that is larger than (entry, exit). Insert the
379 BasicBlock *BB = e->second;
380 (*ShortCut)[entry] = BB;
384 DomTreeNode* RegionInfo::getNextPostDom(DomTreeNode* N,
385 BBtoBBMap *ShortCut) const {
386 BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
388 if (e == ShortCut->end())
391 return PDT->getNode(e->second)->getIDom();
394 bool RegionInfo::isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const {
395 assert(entry && exit && "entry and exit must not be null!");
397 unsigned num_successors = succ_end(entry) - succ_begin(entry);
399 if (num_successors <= 1 && exit == *(succ_begin(entry)))
405 void RegionInfo::updateStatistics(Region *R) {
408 // TODO: Slow. Should only be enabled if -stats is used.
409 if (R->isSimple()) ++numSimpleRegions;
412 Region *RegionInfo::createRegion(BasicBlock *entry, BasicBlock *exit) {
413 assert(entry && exit && "entry and exit must not be null!");
415 if (isTrivialRegion(entry, exit))
418 Region *region = new Region(entry, exit, this, DT);
419 BBtoRegion.insert(std::make_pair(entry, region));
422 region->verifyRegion();
424 DEBUG(region->verifyRegion());
427 updateStatistics(region);
431 void RegionInfo::findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut) {
434 DomTreeNode *N = PDT->getNode(entry);
439 Region *lastRegion= 0;
440 BasicBlock *lastExit = entry;
442 // As only a BasicBlock that postdominates entry can finish a region, walk the
443 // post dominance tree upwards.
444 while ((N = getNextPostDom(N, ShortCut))) {
445 BasicBlock *exit = N->getBlock();
450 if (isRegion(entry, exit)) {
451 Region *newRegion = createRegion(entry, exit);
454 newRegion->addSubRegion(lastRegion);
456 lastRegion = newRegion;
460 // This can never be a region, so stop the search.
461 if (!DT->dominates(entry, exit))
465 // Tried to create regions from entry to lastExit. Next time take a
466 // shortcut from entry to lastExit.
467 if (lastExit != entry)
468 insertShortCut(entry, lastExit, ShortCut);
471 void RegionInfo::scanForRegions(Function &F, BBtoBBMap *ShortCut) {
472 BasicBlock *entry = &(F.getEntryBlock());
473 DomTreeNode *N = DT->getNode(entry);
475 // Iterate over the dominance tree in post order to start with the small
476 // regions from the bottom of the dominance tree. If the small regions are
477 // detected first, detection of bigger regions is faster, as we can jump
478 // over the small regions.
479 for (po_iterator<DomTreeNode*> FI = po_begin(N), FE = po_end(N); FI != FE;
481 findRegionsWithEntry(FI->getBlock(), ShortCut);
485 Region *RegionInfo::getTopMostParent(Region *region) {
486 while (region->parent)
487 region = region->getParent();
492 void RegionInfo::buildRegionsTree(DomTreeNode *N, Region *region) {
493 BasicBlock *BB = N->getBlock();
495 // Passed region exit
496 while (BB == region->getExit())
497 region = region->getParent();
499 BBtoRegionMap::iterator it = BBtoRegion.find(BB);
501 // This basic block is a start block of a region. It is already in the
502 // BBtoRegion relation. Only the child basic blocks have to be updated.
503 if (it != BBtoRegion.end()) {
504 Region *newRegion = it->second;;
505 region->addSubRegion(getTopMostParent(newRegion));
508 BBtoRegion[BB] = region;
511 for (DomTreeNode::iterator CI = N->begin(), CE = N->end(); CI != CE; ++CI)
512 buildRegionsTree(*CI, region);
515 void RegionInfo::releaseMemory() {
518 delete TopLevelRegion;
522 RegionInfo::RegionInfo() : FunctionPass(&ID) {
526 RegionInfo::~RegionInfo() {
530 void RegionInfo::Calculate(Function &F) {
531 // ShortCut a function where for every BB the exit of the largest region
532 // starting with BB is stored. These regions can be threated as single BBS.
533 // This improves performance on linear CFGs.
536 scanForRegions(F, &ShortCut);
537 BasicBlock *BB = &F.getEntryBlock();
538 buildRegionsTree(DT->getNode(BB), TopLevelRegion);
541 bool RegionInfo::runOnFunction(Function &F) {
544 DT = &getAnalysis<DominatorTree>();
545 PDT = &getAnalysis<PostDominatorTree>();
546 DF = &getAnalysis<DominanceFrontier>();
548 TopLevelRegion = new Region(&F.getEntryBlock(), 0, this, DT, 0);
549 updateStatistics(TopLevelRegion);
556 void RegionInfo::getAnalysisUsage(AnalysisUsage &AU) const {
557 AU.setPreservesAll();
558 AU.addRequiredTransitive<DominatorTree>();
559 AU.addRequired<PostDominatorTree>();
560 AU.addRequired<DominanceFrontier>();
563 void RegionInfo::print(raw_ostream &OS, const Module *) const {
564 OS << "Region tree:\n";
565 TopLevelRegion->print(OS, true, 0);
566 OS << "End region tree\n";
569 void RegionInfo::verifyAnalysis() const {
570 // Only do verification when user wants to, otherwise this expensive check
571 // will be invoked by PMDataManager::verifyPreservedAnalysis when
572 // a regionpass (marked PreservedAll) finish.
573 if (!VerifyRegionInfo) return;
575 TopLevelRegion->verifyRegionNest();
578 // Region pass manager support.
579 Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
580 BBtoRegionMap::const_iterator I=
582 return I != BBtoRegion.end() ? I->second : 0;
585 Region *RegionInfo::operator[](BasicBlock *BB) const {
586 return getRegionFor(BB);
590 RegionInfo::getCommonRegion(Region *A, Region *B) const {
591 assert (A && B && "One of the Regions is NULL");
593 if (A->contains(B)) return A;
595 while (!B->contains(A))
602 RegionInfo::getCommonRegion(SmallVectorImpl<Region*> &Regions) const {
603 Region* ret = Regions.back();
606 for (SmallVectorImpl<Region*>::const_iterator I = Regions.begin(),
607 E = Regions.end(); I != E; ++I)
608 ret = getCommonRegion(ret, *I);
614 RegionInfo::getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const {
615 Region* ret = getRegionFor(BBs.back());
618 for (SmallVectorImpl<BasicBlock*>::const_iterator I = BBs.begin(),
619 E = BBs.end(); I != E; ++I)
620 ret = getCommonRegion(ret, getRegionFor(*I));
625 char RegionInfo::ID = 0;
626 INITIALIZE_PASS(RegionInfo, "regions",
627 "Detect single entry single exit regions", true, true);
629 // Create methods available outside of this file, to use them
630 // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
631 // the link time optimization.
634 FunctionPass *createRegionInfoPass() {
635 return new RegionInfo();