Remove extra semi-colons.
[oota-llvm.git] / lib / Analysis / RegionInfo.cpp
1 //===- RegionInfo.cpp - SESE region detection analysis --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 // Detects single entry single exit regions in the control flow graph.
10 //===----------------------------------------------------------------------===//
11
12 #include "llvm/Analysis/RegionInfo.h"
13 #include "llvm/Analysis/RegionIterator.h"
14
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"
21
22 #define DEBUG_TYPE "region"
23 #include "llvm/Support/Debug.h"
24
25 #include <set>
26 #include <algorithm>
27
28 using namespace llvm;
29
30 // Always verify if expensive checking is enabled.
31 #ifdef XDEBUG
32 static bool VerifyRegionInfo = true;
33 #else
34 static bool VerifyRegionInfo = false;
35 #endif
36
37 static cl::opt<bool,true>
38 VerifyRegionInfoX("verify-region-info", cl::location(VerifyRegionInfo),
39                 cl::desc("Verify region info (time consuming)"));
40
41 STATISTIC(numRegions,       "The # of regions");
42 STATISTIC(numSimpleRegions, "The # of simple regions");
43
44 static cl::opt<enum Region::PrintStyle> printStyle("print-region-style",
45   cl::Hidden,
46   cl::desc("style of printing regions"),
47   cl::values(
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"),
53     clEnumValEnd));
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) {}
59
60 Region::~Region() {
61   // Free the cached nodes.
62   for (BBNodeMapT::iterator it = BBNodeMap.begin(),
63          ie = BBNodeMap.end(); it != ie; ++it)
64     delete it->second;
65
66   // Only clean the cache for this Region. Caches of child Regions will be
67   // cleaned when the child Regions are deleted.
68   BBNodeMap.clear();
69
70   for (iterator I = begin(), E = end(); I != E; ++I)
71     delete *I;
72 }
73
74 void Region::replaceEntry(BasicBlock *BB) {
75   entry.setPointer(BB);
76 }
77
78 void Region::replaceExit(BasicBlock *BB) {
79   assert(exit && "No exit to replace!");
80   exit = BB;
81 }
82
83 bool Region::contains(const BasicBlock *B) const {
84   BasicBlock *BB = const_cast<BasicBlock*>(B);
85
86   assert(DT->getNode(BB) && "BB not part of the dominance tree");
87
88   BasicBlock *entry = getEntry(), *exit = getExit();
89
90   // Toplevel region.
91   if (!exit)
92     return true;
93
94   return (DT->dominates(entry, BB)
95     && !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
96 }
97
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.
102   if (L == 0)
103     return getExit() == 0;
104
105   if (!contains(L->getHeader()))
106     return false;
107
108   SmallVector<BasicBlock *, 8> ExitingBlocks;
109   L->getExitingBlocks(ExitingBlocks);
110
111   for (SmallVectorImpl<BasicBlock*>::iterator BI = ExitingBlocks.begin(),
112        BE = ExitingBlocks.end(); BI != BE; ++BI)
113     if (!contains(*BI))
114       return false;
115
116   return true;
117 }
118
119 Loop *Region::outermostLoopInRegion(Loop *L) const {
120   if (!contains(L))
121     return 0;
122
123   while (L && contains(L->getParentLoop())) {
124     L = L->getParentLoop();
125   }
126
127   return L;
128 }
129
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);
134 }
135
136 BasicBlock *Region::getEnteringBlock() const {
137   BasicBlock *entry = getEntry();
138   BasicBlock *Pred;
139   BasicBlock *enteringBlock = 0;
140
141   for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
142        ++PI) {
143     Pred = *PI;
144     if (DT->getNode(Pred) && !contains(Pred)) {
145       if (enteringBlock)
146         return 0;
147
148       enteringBlock = Pred;
149     }
150   }
151
152   return enteringBlock;
153 }
154
155 BasicBlock *Region::getExitingBlock() const {
156   BasicBlock *exit = getExit();
157   BasicBlock *Pred;
158   BasicBlock *exitingBlock = 0;
159
160   if (!exit)
161     return 0;
162
163   for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
164        ++PI) {
165     Pred = *PI;
166     if (contains(Pred)) {
167       if (exitingBlock)
168         return 0;
169
170       exitingBlock = Pred;
171     }
172   }
173
174   return exitingBlock;
175 }
176
177 bool Region::isSimple() const {
178   return !isTopLevelRegion() && getEnteringBlock() && getExitingBlock();
179 }
180
181 std::string Region::getNameStr() const {
182   std::string exitName;
183   std::string entryName;
184
185   if (getEntry()->getName().empty()) {
186     raw_string_ostream OS(entryName);
187
188     WriteAsOperand(OS, getEntry(), false);
189   } else
190     entryName = getEntry()->getName();
191
192   if (getExit()) {
193     if (getExit()->getName().empty()) {
194       raw_string_ostream OS(exitName);
195
196       WriteAsOperand(OS, getExit(), false);
197     } else
198       exitName = getExit()->getName();
199   } else
200     exitName = "<Function Return>";
201
202   return entryName + " => " + exitName;
203 }
204
205 void Region::verifyBBInRegion(BasicBlock *BB) const {
206   if (!contains(BB))
207     llvm_unreachable("Broken region found!");
208
209   BasicBlock *entry = getEntry(), *exit = getExit();
210
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!");
214
215   if (entry != BB)
216     for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB); SI != SE; ++SI)
217       if (!contains(*SI))
218         llvm_unreachable("Broken region found!");
219 }
220
221 void Region::verifyWalk(BasicBlock *BB, std::set<BasicBlock*> *visited) const {
222   BasicBlock *exit = getExit();
223
224   visited->insert(BB);
225
226   verifyBBInRegion(BB);
227
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);
231 }
232
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;
237
238   std::set<BasicBlock*> visited;
239   verifyWalk(getEntry(), &visited);
240 }
241
242 void Region::verifyRegionNest() const {
243   for (Region::const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
244     (*RI)->verifyRegionNest();
245
246   verifyRegion();
247 }
248
249 Region::block_iterator Region::block_begin() {
250   return GraphTraits<FlatIt<Region*> >::nodes_begin(this);
251 }
252
253 Region::block_iterator Region::block_end() {
254   return GraphTraits<FlatIt<Region*> >::nodes_end(this);
255 }
256
257 Region::const_block_iterator Region::block_begin() const {
258   return GraphTraits<FlatIt<const Region*> >::nodes_begin(this);
259 }
260
261 Region::const_block_iterator Region::block_end() const {
262   return GraphTraits<FlatIt<const Region*> >::nodes_end(this);
263 }
264
265 Region::element_iterator Region::element_begin() {
266   return GraphTraits<Region*>::nodes_begin(this);
267 }
268
269 Region::element_iterator Region::element_end() {
270   return GraphTraits<Region*>::nodes_end(this);
271 }
272
273 Region::const_element_iterator Region::element_begin() const {
274   return GraphTraits<const Region*>::nodes_begin(this);
275 }
276
277 Region::const_element_iterator Region::element_end() const {
278   return GraphTraits<const Region*>::nodes_end(this);
279 }
280
281 Region* Region::getSubRegionNode(BasicBlock *BB) const {
282   Region *R = RI->getRegionFor(BB);
283
284   if (!R || R == this)
285     return 0;
286
287   // If we pass the BB out of this region, that means our code is broken.
288   assert(contains(R) && "BB not in current region!");
289
290   while (contains(R->getParent()) && R->getParent() != this)
291     R = R->getParent();
292
293   if (R->getEntry() != BB)
294     return 0;
295
296   return R;
297 }
298
299 RegionNode* Region::getBBNode(BasicBlock *BB) const {
300   assert(contains(BB) && "Can get BB node out of this region!");
301
302   BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
303
304   if (at != BBNodeMap.end())
305     return at->second;
306
307   RegionNode *NewNode = new RegionNode(const_cast<Region*>(this), BB);
308   BBNodeMap.insert(std::make_pair(BB, NewNode));
309   return NewNode;
310 }
311
312 RegionNode* Region::getNode(BasicBlock *BB) const {
313   assert(contains(BB) && "Can get BB node out of this region!");
314   if (Region* Child = getSubRegionNode(BB))
315     return Child->getNode();
316
317   return getBBNode(BB);
318 }
319
320 void Region::transferChildrenTo(Region *To) {
321   for (iterator I = begin(), E = end(); I != E; ++I) {
322     (*I)->parent = To;
323     To->children.push_back(*I);
324   }
325   children.clear();
326 }
327
328 void Region::addSubRegion(Region *SubRegion, bool moveChildren) {
329   assert(SubRegion->parent == 0 && "SubRegion already has a parent!");
330   assert(std::find(begin(), end(), SubRegion) == children.end()
331          && "Subregion already exists!");
332
333   SubRegion->parent = this;
334   children.push_back(SubRegion);
335
336   if (!moveChildren)
337     return;
338
339   assert(SubRegion->children.size() == 0
340          && "SubRegions that contain children are not supported");
341
342   for (element_iterator I = element_begin(), E = element_end(); I != E; ++I)
343     if (!(*I)->isSubRegion()) {
344       BasicBlock *BB = (*I)->getNodeAs<BasicBlock>();
345
346       if (SubRegion->contains(BB))
347         RI->setRegionFor(BB, SubRegion);
348     }
349
350   std::vector<Region*> Keep;
351   for (iterator I = begin(), E = end(); I != E; ++I)
352     if (SubRegion->contains(*I) && *I != SubRegion) {
353       SubRegion->children.push_back(*I);
354       (*I)->parent = SubRegion;
355     } else
356       Keep.push_back(*I);
357
358   children.clear();
359   children.insert(children.begin(), Keep.begin(), Keep.end());
360 }
361
362
363 Region *Region::removeSubRegion(Region *Child) {
364   assert(Child->parent == this && "Child is not a child of this region!");
365   Child->parent = 0;
366   RegionSet::iterator I = std::find(children.begin(), children.end(), Child);
367   assert(I != children.end() && "Region does not exit. Unable to remove.");
368   children.erase(children.begin()+(I-begin()));
369   return Child;
370 }
371
372 unsigned Region::getDepth() const {
373   unsigned Depth = 0;
374
375   for (Region *R = parent; R != 0; R = R->parent)
376     ++Depth;
377
378   return Depth;
379 }
380
381 Region *Region::getExpandedRegion() const {
382   unsigned NumSuccessors = exit->getTerminator()->getNumSuccessors();
383
384   if (NumSuccessors == 0)
385     return NULL;
386
387   for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
388        PI != PE; ++PI)
389     if (!DT->dominates(getEntry(), *PI))
390       return NULL;
391
392   Region *R = RI->getRegionFor(exit);
393
394   if (R->getEntry() != exit) {
395     if (exit->getTerminator()->getNumSuccessors() == 1)
396       return new Region(getEntry(), *succ_begin(exit), RI, DT);
397     else
398       return NULL;
399   }
400
401   while (R->getParent() && R->getParent()->getEntry() == exit)
402     R = R->getParent();
403
404   if (!DT->dominates(getEntry(), R->getExit()))
405     for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
406          PI != PE; ++PI)
407     if (!DT->dominates(R->getExit(), *PI))
408       return NULL;
409
410   return new Region(getEntry(), R->getExit(), RI, DT);
411 }
412
413 void Region::print(raw_ostream &OS, bool print_tree, unsigned level,
414                    enum PrintStyle Style) const {
415   if (print_tree)
416     OS.indent(level*2) << "[" << level << "] " << getNameStr();
417   else
418     OS.indent(level*2) << getNameStr();
419
420   OS << "\n";
421
422
423   if (Style != PrintNone) {
424     OS.indent(level*2) << "{\n";
425     OS.indent(level*2 + 2);
426
427     if (Style == PrintBB) {
428       for (const_block_iterator I = block_begin(), E = block_end(); I!=E; ++I)
429         OS << **I << ", "; // TODO: remove the last ","
430     } else if (Style == PrintRN) {
431       for (const_element_iterator I = element_begin(), E = element_end(); I!=E; ++I)
432         OS << **I << ", "; // TODO: remove the last ",
433     }
434
435     OS << "\n";
436   }
437
438   if (print_tree)
439     for (const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
440       (*RI)->print(OS, print_tree, level+1, Style);
441
442   if (Style != PrintNone)
443     OS.indent(level*2) << "} \n";
444 }
445
446 void Region::dump() const {
447   print(dbgs(), true, getDepth(), printStyle.getValue());
448 }
449
450 void Region::clearNodeCache() {
451   // Free the cached nodes.
452   for (BBNodeMapT::iterator I = BBNodeMap.begin(),
453        IE = BBNodeMap.end(); I != IE; ++I)
454     delete I->second;
455
456   BBNodeMap.clear();
457   for (Region::iterator RI = begin(), RE = end(); RI != RE; ++RI)
458     (*RI)->clearNodeCache();
459 }
460
461 //===----------------------------------------------------------------------===//
462 // RegionInfo implementation
463 //
464
465 bool RegionInfo::isCommonDomFrontier(BasicBlock *BB, BasicBlock *entry,
466                                      BasicBlock *exit) const {
467   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
468     BasicBlock *P = *PI;
469     if (DT->dominates(entry, P) && !DT->dominates(exit, P))
470       return false;
471   }
472   return true;
473 }
474
475 bool RegionInfo::isRegion(BasicBlock *entry, BasicBlock *exit) const {
476   assert(entry && exit && "entry and exit must not be null!");
477   typedef DominanceFrontier::DomSetType DST;
478
479   DST *entrySuccs = &DF->find(entry)->second;
480
481   // Exit is the header of a loop that contains the entry. In this case,
482   // the dominance frontier must only contain the exit.
483   if (!DT->dominates(entry, exit)) {
484     for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
485          SI != SE; ++SI)
486       if (*SI != exit && *SI != entry)
487         return false;
488
489     return true;
490   }
491
492   DST *exitSuccs = &DF->find(exit)->second;
493
494   // Do not allow edges leaving the region.
495   for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
496        SI != SE; ++SI) {
497     if (*SI == exit || *SI == entry)
498       continue;
499     if (exitSuccs->find(*SI) == exitSuccs->end())
500       return false;
501     if (!isCommonDomFrontier(*SI, entry, exit))
502       return false;
503   }
504
505   // Do not allow edges pointing into the region.
506   for (DST::iterator SI = exitSuccs->begin(), SE = exitSuccs->end();
507        SI != SE; ++SI)
508     if (DT->properlyDominates(entry, *SI) && *SI != exit)
509       return false;
510
511
512   return true;
513 }
514
515 void RegionInfo::insertShortCut(BasicBlock *entry, BasicBlock *exit,
516                              BBtoBBMap *ShortCut) const {
517   assert(entry && exit && "entry and exit must not be null!");
518
519   BBtoBBMap::iterator e = ShortCut->find(exit);
520
521   if (e == ShortCut->end())
522     // No further region at exit available.
523     (*ShortCut)[entry] = exit;
524   else {
525     // We found a region e that starts at exit. Therefore (entry, e->second)
526     // is also a region, that is larger than (entry, exit). Insert the
527     // larger one.
528     BasicBlock *BB = e->second;
529     (*ShortCut)[entry] = BB;
530   }
531 }
532
533 DomTreeNode* RegionInfo::getNextPostDom(DomTreeNode* N,
534                                         BBtoBBMap *ShortCut) const {
535   BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
536
537   if (e == ShortCut->end())
538     return N->getIDom();
539
540   return PDT->getNode(e->second)->getIDom();
541 }
542
543 bool RegionInfo::isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const {
544   assert(entry && exit && "entry and exit must not be null!");
545
546   unsigned num_successors = succ_end(entry) - succ_begin(entry);
547
548   if (num_successors <= 1 && exit == *(succ_begin(entry)))
549     return true;
550
551   return false;
552 }
553
554 void RegionInfo::updateStatistics(Region *R) {
555   ++numRegions;
556
557   // TODO: Slow. Should only be enabled if -stats is used.
558   if (R->isSimple()) ++numSimpleRegions;
559 }
560
561 Region *RegionInfo::createRegion(BasicBlock *entry, BasicBlock *exit) {
562   assert(entry && exit && "entry and exit must not be null!");
563
564   if (isTrivialRegion(entry, exit))
565     return 0;
566
567   Region *region = new Region(entry, exit, this, DT);
568   BBtoRegion.insert(std::make_pair(entry, region));
569
570  #ifdef XDEBUG
571     region->verifyRegion();
572  #else
573     DEBUG(region->verifyRegion());
574  #endif
575
576   updateStatistics(region);
577   return region;
578 }
579
580 void RegionInfo::findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut) {
581   assert(entry);
582
583   DomTreeNode *N = PDT->getNode(entry);
584
585   if (!N)
586     return;
587
588   Region *lastRegion= 0;
589   BasicBlock *lastExit = entry;
590
591   // As only a BasicBlock that postdominates entry can finish a region, walk the
592   // post dominance tree upwards.
593   while ((N = getNextPostDom(N, ShortCut))) {
594     BasicBlock *exit = N->getBlock();
595
596     if (!exit)
597       break;
598
599     if (isRegion(entry, exit)) {
600       Region *newRegion = createRegion(entry, exit);
601
602       if (lastRegion)
603         newRegion->addSubRegion(lastRegion);
604
605       lastRegion = newRegion;
606       lastExit = exit;
607     }
608
609     // This can never be a region, so stop the search.
610     if (!DT->dominates(entry, exit))
611       break;
612   }
613
614   // Tried to create regions from entry to lastExit.  Next time take a
615   // shortcut from entry to lastExit.
616   if (lastExit != entry)
617     insertShortCut(entry, lastExit, ShortCut);
618 }
619
620 void RegionInfo::scanForRegions(Function &F, BBtoBBMap *ShortCut) {
621   BasicBlock *entry = &(F.getEntryBlock());
622   DomTreeNode *N = DT->getNode(entry);
623
624   // Iterate over the dominance tree in post order to start with the small
625   // regions from the bottom of the dominance tree.  If the small regions are
626   // detected first, detection of bigger regions is faster, as we can jump
627   // over the small regions.
628   for (po_iterator<DomTreeNode*> FI = po_begin(N), FE = po_end(N); FI != FE;
629     ++FI) {
630     findRegionsWithEntry(FI->getBlock(), ShortCut);
631   }
632 }
633
634 Region *RegionInfo::getTopMostParent(Region *region) {
635   while (region->parent)
636     region = region->getParent();
637
638   return region;
639 }
640
641 void RegionInfo::buildRegionsTree(DomTreeNode *N, Region *region) {
642   BasicBlock *BB = N->getBlock();
643
644   // Passed region exit
645   while (BB == region->getExit())
646     region = region->getParent();
647
648   BBtoRegionMap::iterator it = BBtoRegion.find(BB);
649
650   // This basic block is a start block of a region. It is already in the
651   // BBtoRegion relation. Only the child basic blocks have to be updated.
652   if (it != BBtoRegion.end()) {
653     Region *newRegion = it->second;
654     region->addSubRegion(getTopMostParent(newRegion));
655     region = newRegion;
656   } else {
657     BBtoRegion[BB] = region;
658   }
659
660   for (DomTreeNode::iterator CI = N->begin(), CE = N->end(); CI != CE; ++CI)
661     buildRegionsTree(*CI, region);
662 }
663
664 void RegionInfo::releaseMemory() {
665   BBtoRegion.clear();
666   if (TopLevelRegion)
667     delete TopLevelRegion;
668   TopLevelRegion = 0;
669 }
670
671 RegionInfo::RegionInfo() : FunctionPass(ID) {
672   initializeRegionInfoPass(*PassRegistry::getPassRegistry());
673   TopLevelRegion = 0;
674 }
675
676 RegionInfo::~RegionInfo() {
677   releaseMemory();
678 }
679
680 void RegionInfo::Calculate(Function &F) {
681   // ShortCut a function where for every BB the exit of the largest region
682   // starting with BB is stored. These regions can be threated as single BBS.
683   // This improves performance on linear CFGs.
684   BBtoBBMap ShortCut;
685
686   scanForRegions(F, &ShortCut);
687   BasicBlock *BB = &F.getEntryBlock();
688   buildRegionsTree(DT->getNode(BB), TopLevelRegion);
689 }
690
691 bool RegionInfo::runOnFunction(Function &F) {
692   releaseMemory();
693
694   DT = &getAnalysis<DominatorTree>();
695   PDT = &getAnalysis<PostDominatorTree>();
696   DF = &getAnalysis<DominanceFrontier>();
697
698   TopLevelRegion = new Region(&F.getEntryBlock(), 0, this, DT, 0);
699   updateStatistics(TopLevelRegion);
700
701   Calculate(F);
702
703   return false;
704 }
705
706 void RegionInfo::getAnalysisUsage(AnalysisUsage &AU) const {
707   AU.setPreservesAll();
708   AU.addRequiredTransitive<DominatorTree>();
709   AU.addRequired<PostDominatorTree>();
710   AU.addRequired<DominanceFrontier>();
711 }
712
713 void RegionInfo::print(raw_ostream &OS, const Module *) const {
714   OS << "Region tree:\n";
715   TopLevelRegion->print(OS, true, 0, printStyle.getValue());
716   OS << "End region tree\n";
717 }
718
719 void RegionInfo::verifyAnalysis() const {
720   // Only do verification when user wants to, otherwise this expensive check
721   // will be invoked by PMDataManager::verifyPreservedAnalysis when
722   // a regionpass (marked PreservedAll) finish.
723   if (!VerifyRegionInfo) return;
724
725   TopLevelRegion->verifyRegionNest();
726 }
727
728 // Region pass manager support.
729 Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
730   BBtoRegionMap::const_iterator I=
731     BBtoRegion.find(BB);
732   return I != BBtoRegion.end() ? I->second : 0;
733 }
734
735 void RegionInfo::setRegionFor(BasicBlock *BB, Region *R) {
736   BBtoRegion[BB] = R;
737 }
738
739 Region *RegionInfo::operator[](BasicBlock *BB) const {
740   return getRegionFor(BB);
741 }
742
743 BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
744   BasicBlock *Exit = NULL;
745
746   while (true) {
747     // Get largest region that starts at BB.
748     Region *R = getRegionFor(BB);
749     while (R && R->getParent() && R->getParent()->getEntry() == BB)
750       R = R->getParent();
751
752     // Get the single exit of BB.
753     if (R && R->getEntry() == BB)
754       Exit = R->getExit();
755     else if (++succ_begin(BB) == succ_end(BB))
756       Exit = *succ_begin(BB);
757     else // No single exit exists.
758       return Exit;
759
760     // Get largest region that starts at Exit.
761     Region *ExitR = getRegionFor(Exit);
762     while (ExitR && ExitR->getParent()
763            && ExitR->getParent()->getEntry() == Exit)
764       ExitR = ExitR->getParent();
765
766     for (pred_iterator PI = pred_begin(Exit), PE = pred_end(Exit); PI != PE;
767          ++PI)
768       if (!R->contains(*PI) && !ExitR->contains(*PI))
769         break;
770
771     // This stops infinite cycles.
772     if (DT->dominates(Exit, BB))
773       break;
774
775     BB = Exit;
776   }
777
778   return Exit;
779 }
780
781 Region*
782 RegionInfo::getCommonRegion(Region *A, Region *B) const {
783   assert (A && B && "One of the Regions is NULL");
784
785   if (A->contains(B)) return A;
786
787   while (!B->contains(A))
788     B = B->getParent();
789
790   return B;
791 }
792
793 Region*
794 RegionInfo::getCommonRegion(SmallVectorImpl<Region*> &Regions) const {
795   Region* ret = Regions.back();
796   Regions.pop_back();
797
798   for (SmallVectorImpl<Region*>::const_iterator I = Regions.begin(),
799        E = Regions.end(); I != E; ++I)
800       ret = getCommonRegion(ret, *I);
801
802   return ret;
803 }
804
805 Region*
806 RegionInfo::getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const {
807   Region* ret = getRegionFor(BBs.back());
808   BBs.pop_back();
809
810   for (SmallVectorImpl<BasicBlock*>::const_iterator I = BBs.begin(),
811        E = BBs.end(); I != E; ++I)
812       ret = getCommonRegion(ret, getRegionFor(*I));
813
814   return ret;
815 }
816
817 void RegionInfo::splitBlock(BasicBlock* NewBB, BasicBlock *OldBB)
818 {
819   Region *R = getRegionFor(OldBB);
820
821   setRegionFor(NewBB, R);
822
823   while (R->getEntry() == OldBB && !R->isTopLevelRegion()) {
824     R->replaceEntry(NewBB);
825     R = R->getParent();
826   }
827
828   setRegionFor(OldBB, R);
829 }
830
831 char RegionInfo::ID = 0;
832 INITIALIZE_PASS_BEGIN(RegionInfo, "regions",
833                 "Detect single entry single exit regions", true, true)
834 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
835 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
836 INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
837 INITIALIZE_PASS_END(RegionInfo, "regions",
838                 "Detect single entry single exit regions", true, true)
839
840 // Create methods available outside of this file, to use them
841 // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
842 // the link time optimization.
843
844 namespace llvm {
845   FunctionPass *createRegionInfoPass() {
846     return new RegionInfo();
847   }
848 }
849