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