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