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