Add new RegionInfo pass.
[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/Support/raw_ostream.h"
20
21 #define DEBUG_TYPE "region"
22 #include "llvm/Support/Debug.h"
23
24 #include <set>
25 #include <algorithm>
26
27 using namespace llvm;
28
29 // Always verify if expensive checking is enabled.
30 #ifdef XDEBUG
31 bool VerifyRegionInfo = true;
32 #else
33 bool VerifyRegionInfo = false;
34 #endif
35
36 static cl::opt<bool,true>
37 VerifyRegionInfoX("verify-region-info", cl::location(VerifyRegionInfo),
38                 cl::desc("Verify region info (time consuming)"));
39
40 STATISTIC(numRegions,       "The # of regions");
41 STATISTIC(numSimpleRegions, "The # of simple regions");
42
43 //===----------------------------------------------------------------------===//
44 /// PrintStyle - Print region in difference ways.
45 enum PrintStyle { PrintNone, PrintBB, PrintRN  };
46
47 cl::opt<enum PrintStyle> printStyle("print-region-style", cl::Hidden,
48   cl::desc("style of printing regions"),
49   cl::values(
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"),
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   // Only clean the cache for this Region. Caches of child Regions will be
62   // cleaned when the child Regions are deleted.
63   BBNodeMap.clear();
64
65   for (iterator I = begin(), E = end(); I != E; ++I)
66     delete *I;
67 }
68
69 bool Region::contains(const BasicBlock *B) const {
70   BasicBlock *BB = const_cast<BasicBlock*>(B);
71
72   assert(DT->getNode(BB) && "BB not part of the dominance tree");
73
74   BasicBlock *entry = getEntry(), *exit = getExit();
75
76   // Toplevel region.
77   if (!exit)
78     return true;
79
80   return (DT->dominates(entry, BB)
81     && !(DT->dominates(exit, BB) && DT->dominates(entry, exit)));
82 }
83
84 bool Region::isSimple() const {
85   bool isSimple = true;
86   bool found = false;
87
88   BasicBlock *entry = getEntry(), *exit = getExit();
89
90   // TopLevelRegion
91   if (!exit)
92     return false;
93
94   for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
95        ++PI)
96     if (!contains(*PI)) {
97       if (found) {
98         isSimple = false;
99         break;
100       }
101       found = true;
102     }
103
104   found = false;
105
106   for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
107        ++PI)
108     if (contains(*PI)) {
109       if (found) {
110         isSimple = false;
111         break;
112       }
113       found = true;
114     }
115
116   return isSimple;
117 }
118
119 void Region::verifyBBInRegion(BasicBlock *BB) const {
120   if (!contains(BB))
121     llvm_unreachable("Broken region found!");
122
123   BasicBlock *entry = getEntry(), *exit = getExit();
124
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!");
128
129   if (entry != BB)
130     for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB); SI != SE; ++SI)
131       if (!contains(*SI))
132         llvm_unreachable("Broken region found!");
133 }
134
135 void Region::verifyWalk(BasicBlock *BB, std::set<BasicBlock*> *visited) const {
136   BasicBlock *exit = getExit();
137
138   visited->insert(BB);
139
140   verifyBBInRegion(BB);
141
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);
145 }
146
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;
151
152   std::set<BasicBlock*> visited;
153   verifyWalk(getEntry(), &visited);
154 }
155
156 void Region::verifyRegionNest() const {
157   for (Region::const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
158     (*RI)->verifyRegionNest();
159
160   verifyRegion();
161 }
162
163 Region::block_iterator Region::block_begin() {
164   return GraphTraits<FlatIt<Region*> >::nodes_begin(this);
165 }
166
167 Region::block_iterator Region::block_end() {
168   return GraphTraits<FlatIt<Region*> >::nodes_end(this);
169 }
170
171 Region::const_block_iterator Region::block_begin() const {
172   return GraphTraits<FlatIt<const Region*> >::nodes_begin(this);
173 }
174
175 Region::const_block_iterator Region::block_end() const {
176   return GraphTraits<FlatIt<const Region*> >::nodes_end(this);
177 }
178
179 Region::element_iterator Region::element_begin() {
180   return GraphTraits<Region*>::nodes_begin(this);
181 }
182
183 Region::element_iterator Region::element_end() {
184   return GraphTraits<Region*>::nodes_end(this);
185 }
186
187 Region::const_element_iterator Region::element_begin() const {
188   return GraphTraits<const Region*>::nodes_begin(this);
189 }
190
191 Region::const_element_iterator Region::element_end() const {
192   return GraphTraits<const Region*>::nodes_end(this);
193 }
194
195 Region* Region::getSubRegionNode(BasicBlock *BB) const {
196   Region *R = RI->getRegionFor(BB);
197
198   if (!R || R == this)
199     return 0;
200
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!");
203
204   while (contains(R->getParent()) && R->getParent() != this)
205     R = R->getParent();
206
207   if (R->getEntry() != BB)
208     return 0;
209
210   return R;
211 }
212
213 RegionNode* Region::getBBNode(BasicBlock *BB) const {
214   assert(contains(BB) && "Can get BB node out of this region!");
215
216   BBNodeMapT::const_iterator at = BBNodeMap.find(BB);
217
218   if (at != BBNodeMap.end())
219     return at->second;
220
221   RegionNode *NewNode = new RegionNode(const_cast<Region*>(this), BB);
222   BBNodeMap.insert(std::make_pair(BB, NewNode));
223   return NewNode;
224 }
225
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();
230
231   return getBBNode(BB);
232 }
233
234 void Region::transferChildrenTo(Region *To) {
235   for (iterator I = begin(), E = end(); I != E; ++I) {
236     (*I)->parent = To;
237     To->children.push_back(*I);
238   }
239   children.clear();
240 }
241
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);
249 }
250
251
252 Region *Region::removeSubRegion(Region *Child) {
253   assert(Child->parent == this && "Child is not a child of this region!");
254   Child->parent = 0;
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()));
258   return Child;
259 }
260
261 unsigned Region::getDepth() const {
262   unsigned Depth = 0;
263
264   for (Region *R = parent; R != 0; R = R->parent)
265     ++Depth;
266
267   return Depth;
268 }
269
270 void Region::print(raw_ostream &OS, bool print_tree, unsigned level) const {
271   if (print_tree)
272     OS.indent(level*2) << "[" << level << "] " << getNameStr();
273   else
274     OS.indent(level*2) << getNameStr();
275
276   OS << "\n";
277
278
279   if (printStyle != PrintNone) {
280     OS.indent(level*2) << "{\n";
281     OS.indent(level*2 + 2);
282
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 ",
289     }
290
291     OS << "\n";
292   }
293
294   if (print_tree)
295     for (const_iterator RI = begin(), RE = end(); RI != RE; ++RI)
296       (*RI)->print(OS, print_tree, level+1);
297
298   if (printStyle != PrintNone)
299     OS.indent(level*2) << "} \n";
300 }
301
302 void Region::dump() const {
303   print(dbgs(), true, getDepth());
304 }
305
306 void Region::clearNodeCache() {
307   BBNodeMap.clear();
308   for (Region::iterator RI = begin(), RE = end(); RI != RE; ++RI)
309     (*RI)->clearNodeCache();
310 }
311
312 //===----------------------------------------------------------------------===//
313 // RegionInfo implementation
314 //
315
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)
319     if (DT->dominates(entry, *PI) && !DT->dominates(exit, *PI))
320       return false;
321
322   return true;
323 }
324
325 bool RegionInfo::isRegion(BasicBlock *entry, BasicBlock *exit) const {
326   assert(entry && exit && "entry and exit must not be null!");
327   typedef DominanceFrontier::DomSetType DST;
328
329   DST *entrySuccs = &(*DF->find(entry)).second;
330
331   // Exit is the header of a loop that contains the entry. In this case,
332   // the dominance frontier must only contain the exit.
333   if (!DT->dominates(entry, exit)) {
334     for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
335          SI != SE; ++SI)
336       if (*SI != exit && *SI != entry)
337         return false;
338
339     return true;
340   }
341
342   DST *exitSuccs = &(*DF->find(exit)).second;
343
344   // Do not allow edges leaving the region.
345   for (DST::iterator SI = entrySuccs->begin(), SE = entrySuccs->end();
346        SI != SE; ++SI) {
347     if (*SI == exit || *SI == entry)
348       continue;
349     if (exitSuccs->find(*SI) == exitSuccs->end())
350       return false;
351     if (!isCommonDomFrontier(*SI, entry, exit))
352       return false;
353   }
354
355   // Do not allow edges pointing into the region.
356   for (DST::iterator SI = exitSuccs->begin(), SE = exitSuccs->end();
357        SI != SE; ++SI)
358     if (DT->dominates(entry, *SI) && *SI != entry && *SI != exit)
359       return false;
360
361
362   return true;
363 }
364
365 void RegionInfo::insertShortCut(BasicBlock *entry, BasicBlock *exit,
366                              BBtoBBMap *ShortCut) const {
367   assert(entry && exit && "entry and exit must not be null!");
368
369   BBtoBBMap::iterator e = ShortCut->find(exit);
370
371   if (e == ShortCut->end())
372     // No further region at exit available.
373     (*ShortCut)[entry] = exit;
374   else {
375     // We found a region e that starts at exit. Therefore (entry, e->second)
376     // is also a region, that is larger than (entry, exit). Insert the
377     // larger one.
378     BasicBlock *BB = e->second;
379     (*ShortCut)[entry] = BB;
380   }
381 }
382
383 DomTreeNode* RegionInfo::getNextPostDom(DomTreeNode* N,
384                                         BBtoBBMap *ShortCut) const {
385   BBtoBBMap::iterator e = ShortCut->find(N->getBlock());
386
387   if (e == ShortCut->end())
388     return N->getIDom();
389
390   return PDT->getNode(e->second)->getIDom();
391 }
392
393 bool RegionInfo::isTrivialRegion(BasicBlock *entry, BasicBlock *exit) const {
394   assert(entry && exit && "entry and exit must not be null!");
395
396   unsigned num_successors = succ_end(entry) - succ_begin(entry);
397
398   if (num_successors <= 1 && exit == *(succ_begin(entry)))
399     return true;
400
401   return false;
402 }
403
404 void RegionInfo::updateStatistics(Region *R) {
405   ++numRegions;
406
407   // TODO: Slow. Should only be enabled if -stats is used.
408   if (R->isSimple()) ++numSimpleRegions;
409 }
410
411 Region *RegionInfo::createRegion(BasicBlock *entry, BasicBlock *exit) {
412   assert(entry && exit && "entry and exit must not be null!");
413
414   if (isTrivialRegion(entry, exit))
415     return 0;
416
417   Region *region = new Region(entry, exit, this, DT);
418   BBtoRegion.insert(std::make_pair(entry, region));
419
420  #ifdef XDEBUG
421     region->verifyRegion();
422  #else
423     DEBUG(region->verifyRegion());
424  #endif
425
426   updateStatistics(region);
427   return region;
428 }
429
430 void RegionInfo::findRegionsWithEntry(BasicBlock *entry, BBtoBBMap *ShortCut) {
431   assert(entry);
432
433   DomTreeNode *N = PDT->getNode(entry);
434
435   if (!N)
436     return;
437
438   Region *lastRegion= 0;
439   BasicBlock *lastExit = entry;
440
441   // As only a BasicBlock that postdominates entry can finish a region, walk the
442   // post dominance tree upwards.
443   while ((N = getNextPostDom(N, ShortCut))) {
444     BasicBlock *exit = N->getBlock();
445
446     if (!exit)
447       break;
448
449     if (isRegion(entry, exit)) {
450       Region *newRegion = createRegion(entry, exit);
451
452       if (lastRegion)
453         newRegion->addSubRegion(lastRegion);
454
455       lastRegion = newRegion;
456       lastExit = exit;
457     }
458
459     // This can never be a region, so stop the search.
460     if (!DT->dominates(entry, exit))
461       break;
462   }
463
464   // Tried to create regions from entry to lastExit.  Next time take a
465   // shortcut from entry to lastExit.
466   if (lastExit != entry)
467     insertShortCut(entry, lastExit, ShortCut);
468 }
469
470 void RegionInfo::scanForRegions(Function &F, BBtoBBMap *ShortCut) {
471   BasicBlock *entry = &(F.getEntryBlock());
472   DomTreeNode *N = DT->getNode(entry);
473
474   // Iterate over the dominance tree in post order to start with the small
475   // regions from the bottom of the dominance tree.  If the small regions are
476   // detected first, detection of bigger regions is faster, as we can jump
477   // over the small regions.
478   for (po_iterator<DomTreeNode*> FI = po_begin(N), FE = po_end(N); FI != FE;
479     ++FI) {
480     findRegionsWithEntry((*FI)->getBlock(), ShortCut);
481   }
482 }
483
484 Region *RegionInfo::getTopMostParent(Region *region) {
485   while (region->parent)
486     region = region->getParent();
487
488   return region;
489 }
490
491 void RegionInfo::buildRegionsTree(DomTreeNode *N, Region *region) {
492   BasicBlock *BB = N->getBlock();
493
494   // Passed region exit
495   while (BB == region->getExit())
496     region = region->getParent();
497
498   BBtoRegionMap::iterator it = BBtoRegion.find(BB);
499
500   // This basic block is a start block of a region. It is already in the
501   // BBtoRegion relation. Only the child basic blocks have to be updated.
502   if (it != BBtoRegion.end()) {
503     Region *newRegion = it->second;;
504     region->addSubRegion(getTopMostParent(newRegion));
505     region = newRegion;
506   } else {
507     BBtoRegion[BB] = region;
508   }
509
510   for (DomTreeNode::iterator CI = N->begin(), CE = N->end(); CI != CE; ++CI)
511     buildRegionsTree(*CI, region);
512 }
513
514 void RegionInfo::releaseMemory() {
515   BBtoRegion.clear();
516   if (TopLevelRegion)
517     delete TopLevelRegion;
518   TopLevelRegion = 0;
519 }
520
521 RegionInfo::RegionInfo() : FunctionPass(&ID) {
522   TopLevelRegion = 0;
523 }
524
525 RegionInfo::~RegionInfo() {
526   releaseMemory();
527 }
528
529 void RegionInfo::Calculate(Function &F) {
530   // ShortCut a function where for every BB the exit of the largest region
531   // starting with BB is stored. These regions can be threated as single BBS.
532   // This improves performance on linear CFGs.
533   BBtoBBMap ShortCut;
534
535   scanForRegions(F, &ShortCut);
536   BasicBlock *BB = &F.getEntryBlock();
537   buildRegionsTree(DT->getNode(BB), TopLevelRegion);
538 }
539
540 bool RegionInfo::runOnFunction(Function &F) {
541   releaseMemory();
542
543   DT = &getAnalysis<DominatorTree>();
544   PDT = &getAnalysis<PostDominatorTree>();
545   DF = &getAnalysis<DominanceFrontier>();
546
547   TopLevelRegion = new Region(&F.getEntryBlock(), 0, this, DT, 0);
548   updateStatistics(TopLevelRegion);
549
550   Calculate(F);
551
552   return false;
553 }
554
555 void RegionInfo::getAnalysisUsage(AnalysisUsage &AU) const {
556   AU.setPreservesAll();
557   AU.addRequiredTransitive<DominatorTree>();
558   AU.addRequired<PostDominatorTree>();
559   AU.addRequired<DominanceFrontier>();
560 }
561
562 void RegionInfo::print(raw_ostream &OS, const Module *) const {
563   OS << "Region tree:\n";
564   TopLevelRegion->print(OS, true, 0);
565   OS << "End region tree\n";
566 }
567
568 void RegionInfo::verifyAnalysis() const {
569   // Only do verification when user wants to, otherwise this expensive check
570   // will be invoked by PMDataManager::verifyPreservedAnalysis when
571   // a regionpass (marked PreservedAll) finish.
572   if (!VerifyRegionInfo) return;
573
574   TopLevelRegion->verifyRegionNest();
575 }
576
577 // Region pass manager support.
578 Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
579   BBtoRegionMap::const_iterator I=
580     BBtoRegion.find(BB);
581   return I != BBtoRegion.end() ? I->second : 0;
582 }
583
584 Region *RegionInfo::operator[](BasicBlock *BB) const {
585   return getRegionFor(BB);
586 }
587
588 Region*
589 RegionInfo::getCommonRegion(Region *A, Region *B) const {
590   assert (A && B && "One of the Regions is NULL");
591
592   if (A->contains(B)) return A;
593
594   while (!B->contains(A))
595     B = B->getParent();
596
597   return B;
598 }
599
600 Region*
601 RegionInfo::getCommonRegion(SmallVectorImpl<Region*> &Regions) const {
602   Region* ret = Regions.back();
603   Regions.pop_back();
604
605   for (SmallVectorImpl<Region*>::const_iterator I = Regions.begin(),
606        E = Regions.end(); I != E; ++I)
607       ret = getCommonRegion(ret, *I);
608
609   return ret;
610 }
611
612 Region*
613 RegionInfo::getCommonRegion(SmallVectorImpl<BasicBlock*> &BBs) const {
614   Region* ret = getRegionFor(BBs.back());
615   BBs.pop_back();
616
617   for (SmallVectorImpl<BasicBlock*>::const_iterator I = BBs.begin(),
618        E = BBs.end(); I != E; ++I)
619       ret = getCommonRegion(ret, getRegionFor(*I));
620
621   return ret;
622 }
623
624 char RegionInfo::ID = 0;
625 INITIALIZE_PASS(RegionInfo, "regions",
626                 "Detect single entry single exit regions", true, true);
627
628 // Create methods available outside of this file, to use them
629 // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by
630 // the link time optimization.
631
632 namespace llvm {
633   FunctionPass *createRegionInfoPass() {
634     return new RegionInfo();
635   }
636 }
637