1 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
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 //
10 // This file defines the LoopInfo class that is used to identify natural loops
11 // and determine the loop depth of various nodes of the CFG. Note that the
12 // loops identified may actually be several natural loops that share the same
13 // header node... not just a single natural loop.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/Analysis/LoopInfoImpl.h"
22 #include "llvm/Analysis/LoopIterator.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/Assembly/Writer.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/Metadata.h"
28 #include "llvm/Support/CFG.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include <algorithm>
32 using namespace llvm;
33
34 // Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
35 template class llvm::LoopBase<BasicBlock, Loop>;
36 template class llvm::LoopInfoBase<BasicBlock, Loop>;
37
38 // Always verify loopinfo if expensive checking is enabled.
39 #ifdef XDEBUG
40 static bool VerifyLoopInfo = true;
41 #else
42 static bool VerifyLoopInfo = false;
43 #endif
44 static cl::opt<bool,true>
45 VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
46 cl::desc("Verify loop info (time consuming)"));
47
48 char LoopInfo::ID = 0;
49 INITIALIZE_PASS_BEGIN(LoopInfo, "loops", "Natural Loop Information", true, true)
50 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
51 INITIALIZE_PASS_END(LoopInfo, "loops", "Natural Loop Information", true, true)
52
53 // Loop identifier metadata name.
54 static const char *const LoopMDName = "llvm.loop";
55
56 //===----------------------------------------------------------------------===//
57 // Loop implementation
58 //
59
60 /// isLoopInvariant - Return true if the specified value is loop invariant
61 ///
isLoopInvariant(Value * V) const62 bool Loop::isLoopInvariant(Value *V) const {
63 if (Instruction *I = dyn_cast<Instruction>(V))
64 return !contains(I);
65 return true; // All non-instructions are loop invariant
66 }
67
68 /// hasLoopInvariantOperands - Return true if all the operands of the
69 /// specified instruction are loop invariant.
hasLoopInvariantOperands(Instruction * I) const70 bool Loop::hasLoopInvariantOperands(Instruction *I) const {
71 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
72 if (!isLoopInvariant(I->getOperand(i)))
73 return false;
74
75 return true;
76 }
77
78 /// makeLoopInvariant - If the given value is an instruciton inside of the
79 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
80 /// Return true if the value after any hoisting is loop invariant. This
81 /// function can be used as a slightly more aggressive replacement for
82 /// isLoopInvariant.
83 ///
84 /// If InsertPt is specified, it is the point to hoist instructions to.
85 /// If null, the terminator of the loop preheader is used.
86 ///
makeLoopInvariant(Value * V,bool & Changed,Instruction * InsertPt) const87 bool Loop::makeLoopInvariant(Value *V, bool &Changed,
88 Instruction *InsertPt) const {
89 if (Instruction *I = dyn_cast<Instruction>(V))
90 return makeLoopInvariant(I, Changed, InsertPt);
91 return true; // All non-instructions are loop-invariant.
92 }
93
94 /// makeLoopInvariant - If the given instruction is inside of the
95 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
96 /// Return true if the instruction after any hoisting is loop invariant. This
97 /// function can be used as a slightly more aggressive replacement for
98 /// isLoopInvariant.
99 ///
100 /// If InsertPt is specified, it is the point to hoist instructions to.
101 /// If null, the terminator of the loop preheader is used.
102 ///
makeLoopInvariant(Instruction * I,bool & Changed,Instruction * InsertPt) const103 bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
104 Instruction *InsertPt) const {
105 // Test if the value is already loop-invariant.
106 if (isLoopInvariant(I))
107 return true;
108 if (!isSafeToSpeculativelyExecute(I))
109 return false;
110 if (I->mayReadFromMemory())
111 return false;
112 // The landingpad instruction is immobile.
113 if (isa<LandingPadInst>(I))
114 return false;
115 // Determine the insertion point, unless one was given.
116 if (!InsertPt) {
117 BasicBlock *Preheader = getLoopPreheader();
118 // Without a preheader, hoisting is not feasible.
119 if (!Preheader)
120 return false;
121 InsertPt = Preheader->getTerminator();
122 }
123 // Don't hoist instructions with loop-variant operands.
124 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
125 if (!makeLoopInvariant(I->getOperand(i), Changed, InsertPt))
126 return false;
127
128 // Hoist.
129 I->moveBefore(InsertPt);
130 Changed = true;
131 return true;
132 }
133
134 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
135 /// induction variable: an integer recurrence that starts at 0 and increments
136 /// by one each time through the loop. If so, return the phi node that
137 /// corresponds to it.
138 ///
139 /// The IndVarSimplify pass transforms loops to have a canonical induction
140 /// variable.
141 ///
getCanonicalInductionVariable() const142 PHINode *Loop::getCanonicalInductionVariable() const {
143 BasicBlock *H = getHeader();
144
145 BasicBlock *Incoming = 0, *Backedge = 0;
146 pred_iterator PI = pred_begin(H);
147 assert(PI != pred_end(H) &&
148 "Loop must have at least one backedge!");
149 Backedge = *PI++;
150 if (PI == pred_end(H)) return 0; // dead loop
151 Incoming = *PI++;
152 if (PI != pred_end(H)) return 0; // multiple backedges?
153
154 if (contains(Incoming)) {
155 if (contains(Backedge))
156 return 0;
157 std::swap(Incoming, Backedge);
158 } else if (!contains(Backedge))
159 return 0;
160
161 // Loop over all of the PHI nodes, looking for a canonical indvar.
162 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
163 PHINode *PN = cast<PHINode>(I);
164 if (ConstantInt *CI =
165 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
166 if (CI->isNullValue())
167 if (Instruction *Inc =
168 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
169 if (Inc->getOpcode() == Instruction::Add &&
170 Inc->getOperand(0) == PN)
171 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
172 if (CI->equalsInt(1))
173 return PN;
174 }
175 return 0;
176 }
177
178 /// isLCSSAForm - Return true if the Loop is in LCSSA form
isLCSSAForm(DominatorTree & DT) const179 bool Loop::isLCSSAForm(DominatorTree &DT) const {
180 // Sort the blocks vector so that we can use binary search to do quick
181 // lookups.
182 SmallPtrSet<BasicBlock*, 16> LoopBBs(block_begin(), block_end());
183
184 for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
185 BasicBlock *BB = *BI;
186 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;++I)
187 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
188 ++UI) {
189 User *U = *UI;
190 BasicBlock *UserBB = cast<Instruction>(U)->getParent();
191 if (PHINode *P = dyn_cast<PHINode>(U))
192 UserBB = P->getIncomingBlock(UI);
193
194 // Check the current block, as a fast-path, before checking whether
195 // the use is anywhere in the loop. Most values are used in the same
196 // block they are defined in. Also, blocks not reachable from the
197 // entry are special; uses in them don't need to go through PHIs.
198 if (UserBB != BB &&
199 !LoopBBs.count(UserBB) &&
200 DT.isReachableFromEntry(UserBB))
201 return false;
202 }
203 }
204
205 return true;
206 }
207
208 /// isLoopSimplifyForm - Return true if the Loop is in the form that
209 /// the LoopSimplify form transforms loops to, which is sometimes called
210 /// normal form.
isLoopSimplifyForm() const211 bool Loop::isLoopSimplifyForm() const {
212 // Normal-form loops have a preheader, a single backedge, and all of their
213 // exits have all their predecessors inside the loop.
214 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
215 }
216
217 /// isSafeToClone - Return true if the loop body is safe to clone in practice.
218 /// Routines that reform the loop CFG and split edges often fail on indirectbr.
isSafeToClone() const219 bool Loop::isSafeToClone() const {
220 // Return false if any loop blocks contain indirectbrs, or there are any calls
221 // to noduplicate functions.
222 for (Loop::block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
223 if (isa<IndirectBrInst>((*I)->getTerminator())) {
224 return false;
225 } else if (const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator())) {
226 if (II->hasFnAttr(Attribute::NoDuplicate))
227 return false;
228 }
229
230 for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end(); BI != BE; ++BI) {
231 if (const CallInst *CI = dyn_cast<CallInst>(BI)) {
232 if (CI->hasFnAttr(Attribute::NoDuplicate))
233 return false;
234 }
235 }
236 }
237 return true;
238 }
239
getLoopID() const240 MDNode *Loop::getLoopID() const {
241 MDNode *LoopID = 0;
242 if (isLoopSimplifyForm()) {
243 LoopID = getLoopLatch()->getTerminator()->getMetadata(LoopMDName);
244 } else {
245 // Go through each predecessor of the loop header and check the
246 // terminator for the metadata.
247 BasicBlock *H = getHeader();
248 for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
249 TerminatorInst *TI = (*I)->getTerminator();
250 MDNode *MD = 0;
251
252 // Check if this terminator branches to the loop header.
253 for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
254 if (TI->getSuccessor(i) == H) {
255 MD = TI->getMetadata(LoopMDName);
256 break;
257 }
258 }
259 if (!MD)
260 return 0;
261
262 if (!LoopID)
263 LoopID = MD;
264 else if (MD != LoopID)
265 return 0;
266 }
267 }
268 if (!LoopID || LoopID->getNumOperands() == 0 ||
269 LoopID->getOperand(0) != LoopID)
270 return 0;
271 return LoopID;
272 }
273
setLoopID(MDNode * LoopID) const274 void Loop::setLoopID(MDNode *LoopID) const {
275 assert(LoopID && "Loop ID should not be null");
276 assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
277 assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
278
279 if (isLoopSimplifyForm()) {
280 getLoopLatch()->getTerminator()->setMetadata(LoopMDName, LoopID);
281 return;
282 }
283
284 BasicBlock *H = getHeader();
285 for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
286 TerminatorInst *TI = (*I)->getTerminator();
287 for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
288 if (TI->getSuccessor(i) == H)
289 TI->setMetadata(LoopMDName, LoopID);
290 }
291 }
292 }
293
isAnnotatedParallel() const294 bool Loop::isAnnotatedParallel() const {
295 MDNode *desiredLoopIdMetadata = getLoopID();
296
297 if (!desiredLoopIdMetadata)
298 return false;
299
300 // The loop branch contains the parallel loop metadata. In order to ensure
301 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
302 // dependencies (thus converted the loop back to a sequential loop), check
303 // that all the memory instructions in the loop contain parallelism metadata
304 // that point to the same unique "loop id metadata" the loop branch does.
305 for (block_iterator BB = block_begin(), BE = block_end(); BB != BE; ++BB) {
306 for (BasicBlock::iterator II = (*BB)->begin(), EE = (*BB)->end();
307 II != EE; II++) {
308
309 if (!II->mayReadOrWriteMemory())
310 continue;
311
312 if (!II->getMetadata("llvm.mem.parallel_loop_access"))
313 return false;
314
315 // The memory instruction can refer to the loop identifier metadata
316 // directly or indirectly through another list metadata (in case of
317 // nested parallel loops). The loop identifier metadata refers to
318 // itself so we can check both cases with the same routine.
319 MDNode *loopIdMD =
320 dyn_cast<MDNode>(II->getMetadata("llvm.mem.parallel_loop_access"));
321 bool loopIdMDFound = false;
322 for (unsigned i = 0, e = loopIdMD->getNumOperands(); i < e; ++i) {
323 if (loopIdMD->getOperand(i) == desiredLoopIdMetadata) {
324 loopIdMDFound = true;
325 break;
326 }
327 }
328
329 if (!loopIdMDFound)
330 return false;
331 }
332 }
333 return true;
334 }
335
336
337 /// hasDedicatedExits - Return true if no exit block for the loop
338 /// has a predecessor that is outside the loop.
hasDedicatedExits() const339 bool Loop::hasDedicatedExits() const {
340 // Sort the blocks vector so that we can use binary search to do quick
341 // lookups.
342 SmallPtrSet<BasicBlock *, 16> LoopBBs(block_begin(), block_end());
343 // Each predecessor of each exit block of a normal loop is contained
344 // within the loop.
345 SmallVector<BasicBlock *, 4> ExitBlocks;
346 getExitBlocks(ExitBlocks);
347 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
348 for (pred_iterator PI = pred_begin(ExitBlocks[i]),
349 PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
350 if (!LoopBBs.count(*PI))
351 return false;
352 // All the requirements are met.
353 return true;
354 }
355
356 /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
357 /// These are the blocks _outside of the current loop_ which are branched to.
358 /// This assumes that loop exits are in canonical form.
359 ///
360 void
getUniqueExitBlocks(SmallVectorImpl<BasicBlock * > & ExitBlocks) const361 Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
362 assert(hasDedicatedExits() &&
363 "getUniqueExitBlocks assumes the loop has canonical form exits!");
364
365 // Sort the blocks vector so that we can use binary search to do quick
366 // lookups.
367 SmallVector<BasicBlock *, 128> LoopBBs(block_begin(), block_end());
368 std::sort(LoopBBs.begin(), LoopBBs.end());
369
370 SmallVector<BasicBlock *, 32> switchExitBlocks;
371
372 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
373
374 BasicBlock *current = *BI;
375 switchExitBlocks.clear();
376
377 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
378 // If block is inside the loop then it is not a exit block.
379 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
380 continue;
381
382 pred_iterator PI = pred_begin(*I);
383 BasicBlock *firstPred = *PI;
384
385 // If current basic block is this exit block's first predecessor
386 // then only insert exit block in to the output ExitBlocks vector.
387 // This ensures that same exit block is not inserted twice into
388 // ExitBlocks vector.
389 if (current != firstPred)
390 continue;
391
392 // If a terminator has more then two successors, for example SwitchInst,
393 // then it is possible that there are multiple edges from current block
394 // to one exit block.
395 if (std::distance(succ_begin(current), succ_end(current)) <= 2) {
396 ExitBlocks.push_back(*I);
397 continue;
398 }
399
400 // In case of multiple edges from current block to exit block, collect
401 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
402 // duplicate edges.
403 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
404 == switchExitBlocks.end()) {
405 switchExitBlocks.push_back(*I);
406 ExitBlocks.push_back(*I);
407 }
408 }
409 }
410 }
411
412 /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
413 /// block, return that block. Otherwise return null.
getUniqueExitBlock() const414 BasicBlock *Loop::getUniqueExitBlock() const {
415 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
416 getUniqueExitBlocks(UniqueExitBlocks);
417 if (UniqueExitBlocks.size() == 1)
418 return UniqueExitBlocks[0];
419 return 0;
420 }
421
422 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const423 void Loop::dump() const {
424 print(dbgs());
425 }
426 #endif
427
428 //===----------------------------------------------------------------------===//
429 // UnloopUpdater implementation
430 //
431
432 namespace {
433 /// Find the new parent loop for all blocks within the "unloop" whose last
434 /// backedges has just been removed.
435 class UnloopUpdater {
436 Loop *Unloop;
437 LoopInfo *LI;
438
439 LoopBlocksDFS DFS;
440
441 // Map unloop's immediate subloops to their nearest reachable parents. Nested
442 // loops within these subloops will not change parents. However, an immediate
443 // subloop's new parent will be the nearest loop reachable from either its own
444 // exits *or* any of its nested loop's exits.
445 DenseMap<Loop*, Loop*> SubloopParents;
446
447 // Flag the presence of an irreducible backedge whose destination is a block
448 // directly contained by the original unloop.
449 bool FoundIB;
450
451 public:
UnloopUpdater(Loop * UL,LoopInfo * LInfo)452 UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
453 Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
454
455 void updateBlockParents();
456
457 void removeBlocksFromAncestors();
458
459 void updateSubloopParents();
460
461 protected:
462 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
463 };
464 } // end anonymous namespace
465
466 /// updateBlockParents - Update the parent loop for all blocks that are directly
467 /// contained within the original "unloop".
updateBlockParents()468 void UnloopUpdater::updateBlockParents() {
469 if (Unloop->getNumBlocks()) {
470 // Perform a post order CFG traversal of all blocks within this loop,
471 // propagating the nearest loop from sucessors to predecessors.
472 LoopBlocksTraversal Traversal(DFS, LI);
473 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
474 POE = Traversal.end(); POI != POE; ++POI) {
475
476 Loop *L = LI->getLoopFor(*POI);
477 Loop *NL = getNearestLoop(*POI, L);
478
479 if (NL != L) {
480 // For reducible loops, NL is now an ancestor of Unloop.
481 assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
482 "uninitialized successor");
483 LI->changeLoopFor(*POI, NL);
484 }
485 else {
486 // Or the current block is part of a subloop, in which case its parent
487 // is unchanged.
488 assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
489 }
490 }
491 }
492 // Each irreducible loop within the unloop induces a round of iteration using
493 // the DFS result cached by Traversal.
494 bool Changed = FoundIB;
495 for (unsigned NIters = 0; Changed; ++NIters) {
496 assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
497
498 // Iterate over the postorder list of blocks, propagating the nearest loop
499 // from successors to predecessors as before.
500 Changed = false;
501 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
502 POE = DFS.endPostorder(); POI != POE; ++POI) {
503
504 Loop *L = LI->getLoopFor(*POI);
505 Loop *NL = getNearestLoop(*POI, L);
506 if (NL != L) {
507 assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
508 "uninitialized successor");
509 LI->changeLoopFor(*POI, NL);
510 Changed = true;
511 }
512 }
513 }
514 }
515
516 /// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors below
517 /// their new parents.
removeBlocksFromAncestors()518 void UnloopUpdater::removeBlocksFromAncestors() {
519 // Remove all unloop's blocks (including those in nested subloops) from
520 // ancestors below the new parent loop.
521 for (Loop::block_iterator BI = Unloop->block_begin(),
522 BE = Unloop->block_end(); BI != BE; ++BI) {
523 Loop *OuterParent = LI->getLoopFor(*BI);
524 if (Unloop->contains(OuterParent)) {
525 while (OuterParent->getParentLoop() != Unloop)
526 OuterParent = OuterParent->getParentLoop();
527 OuterParent = SubloopParents[OuterParent];
528 }
529 // Remove blocks from former Ancestors except Unloop itself which will be
530 // deleted.
531 for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent;
532 OldParent = OldParent->getParentLoop()) {
533 assert(OldParent && "new loop is not an ancestor of the original");
534 OldParent->removeBlockFromLoop(*BI);
535 }
536 }
537 }
538
539 /// updateSubloopParents - Update the parent loop for all subloops directly
540 /// nested within unloop.
updateSubloopParents()541 void UnloopUpdater::updateSubloopParents() {
542 while (!Unloop->empty()) {
543 Loop *Subloop = *llvm::prior(Unloop->end());
544 Unloop->removeChildLoop(llvm::prior(Unloop->end()));
545
546 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
547 if (Loop *Parent = SubloopParents[Subloop])
548 Parent->addChildLoop(Subloop);
549 else
550 LI->addTopLevelLoop(Subloop);
551 }
552 }
553
554 /// getNearestLoop - Return the nearest parent loop among this block's
555 /// successors. If a successor is a subloop header, consider its parent to be
556 /// the nearest parent of the subloop's exits.
557 ///
558 /// For subloop blocks, simply update SubloopParents and return NULL.
getNearestLoop(BasicBlock * BB,Loop * BBLoop)559 Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
560
561 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
562 // is considered uninitialized.
563 Loop *NearLoop = BBLoop;
564
565 Loop *Subloop = 0;
566 if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
567 Subloop = NearLoop;
568 // Find the subloop ancestor that is directly contained within Unloop.
569 while (Subloop->getParentLoop() != Unloop) {
570 Subloop = Subloop->getParentLoop();
571 assert(Subloop && "subloop is not an ancestor of the original loop");
572 }
573 // Get the current nearest parent of the Subloop exits, initially Unloop.
574 NearLoop =
575 SubloopParents.insert(std::make_pair(Subloop, Unloop)).first->second;
576 }
577
578 succ_iterator I = succ_begin(BB), E = succ_end(BB);
579 if (I == E) {
580 assert(!Subloop && "subloop blocks must have a successor");
581 NearLoop = 0; // unloop blocks may now exit the function.
582 }
583 for (; I != E; ++I) {
584 if (*I == BB)
585 continue; // self loops are uninteresting
586
587 Loop *L = LI->getLoopFor(*I);
588 if (L == Unloop) {
589 // This successor has not been processed. This path must lead to an
590 // irreducible backedge.
591 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
592 FoundIB = true;
593 }
594 if (L != Unloop && Unloop->contains(L)) {
595 // Successor is in a subloop.
596 if (Subloop)
597 continue; // Branching within subloops. Ignore it.
598
599 // BB branches from the original into a subloop header.
600 assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
601
602 // Get the current nearest parent of the Subloop's exits.
603 L = SubloopParents[L];
604 // L could be Unloop if the only exit was an irreducible backedge.
605 }
606 if (L == Unloop) {
607 continue;
608 }
609 // Handle critical edges from Unloop into a sibling loop.
610 if (L && !L->contains(Unloop)) {
611 L = L->getParentLoop();
612 }
613 // Remember the nearest parent loop among successors or subloop exits.
614 if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
615 NearLoop = L;
616 }
617 if (Subloop) {
618 SubloopParents[Subloop] = NearLoop;
619 return BBLoop;
620 }
621 return NearLoop;
622 }
623
624 //===----------------------------------------------------------------------===//
625 // LoopInfo implementation
626 //
runOnFunction(Function &)627 bool LoopInfo::runOnFunction(Function &) {
628 releaseMemory();
629 LI.Analyze(getAnalysis<DominatorTree>().getBase());
630 return false;
631 }
632
633 /// updateUnloop - The last backedge has been removed from a loop--now the
634 /// "unloop". Find a new parent for the blocks contained within unloop and
635 /// update the loop tree. We don't necessarily have valid dominators at this
636 /// point, but LoopInfo is still valid except for the removal of this loop.
637 ///
638 /// Note that Unloop may now be an empty loop. Calling Loop::getHeader without
639 /// checking first is illegal.
updateUnloop(Loop * Unloop)640 void LoopInfo::updateUnloop(Loop *Unloop) {
641
642 // First handle the special case of no parent loop to simplify the algorithm.
643 if (!Unloop->getParentLoop()) {
644 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
645 for (Loop::block_iterator I = Unloop->block_begin(),
646 E = Unloop->block_end(); I != E; ++I) {
647
648 // Don't reparent blocks in subloops.
649 if (getLoopFor(*I) != Unloop)
650 continue;
651
652 // Blocks no longer have a parent but are still referenced by Unloop until
653 // the Unloop object is deleted.
654 LI.changeLoopFor(*I, 0);
655 }
656
657 // Remove the loop from the top-level LoopInfo object.
658 for (LoopInfo::iterator I = LI.begin();; ++I) {
659 assert(I != LI.end() && "Couldn't find loop");
660 if (*I == Unloop) {
661 LI.removeLoop(I);
662 break;
663 }
664 }
665
666 // Move all of the subloops to the top-level.
667 while (!Unloop->empty())
668 LI.addTopLevelLoop(Unloop->removeChildLoop(llvm::prior(Unloop->end())));
669
670 return;
671 }
672
673 // Update the parent loop for all blocks within the loop. Blocks within
674 // subloops will not change parents.
675 UnloopUpdater Updater(Unloop, this);
676 Updater.updateBlockParents();
677
678 // Remove blocks from former ancestor loops.
679 Updater.removeBlocksFromAncestors();
680
681 // Add direct subloops as children in their new parent loop.
682 Updater.updateSubloopParents();
683
684 // Remove unloop from its parent loop.
685 Loop *ParentLoop = Unloop->getParentLoop();
686 for (Loop::iterator I = ParentLoop->begin();; ++I) {
687 assert(I != ParentLoop->end() && "Couldn't find loop");
688 if (*I == Unloop) {
689 ParentLoop->removeChildLoop(I);
690 break;
691 }
692 }
693 }
694
verifyAnalysis() const695 void LoopInfo::verifyAnalysis() const {
696 // LoopInfo is a FunctionPass, but verifying every loop in the function
697 // each time verifyAnalysis is called is very expensive. The
698 // -verify-loop-info option can enable this. In order to perform some
699 // checking by default, LoopPass has been taught to call verifyLoop
700 // manually during loop pass sequences.
701
702 if (!VerifyLoopInfo) return;
703
704 DenseSet<const Loop*> Loops;
705 for (iterator I = begin(), E = end(); I != E; ++I) {
706 assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
707 (*I)->verifyLoopNest(&Loops);
708 }
709
710 // Verify that blocks are mapped to valid loops.
711 for (DenseMap<BasicBlock*, Loop*>::const_iterator I = LI.BBMap.begin(),
712 E = LI.BBMap.end(); I != E; ++I) {
713 assert(Loops.count(I->second) && "orphaned loop");
714 assert(I->second->contains(I->first) && "orphaned block");
715 }
716 }
717
getAnalysisUsage(AnalysisUsage & AU) const718 void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
719 AU.setPreservesAll();
720 AU.addRequired<DominatorTree>();
721 }
722
print(raw_ostream & OS,const Module *) const723 void LoopInfo::print(raw_ostream &OS, const Module*) const {
724 LI.print(OS);
725 }
726
727 //===----------------------------------------------------------------------===//
728 // LoopBlocksDFS implementation
729 //
730
731 /// Traverse the loop blocks and store the DFS result.
732 /// Useful for clients that just want the final DFS result and don't need to
733 /// visit blocks during the initial traversal.
perform(LoopInfo * LI)734 void LoopBlocksDFS::perform(LoopInfo *LI) {
735 LoopBlocksTraversal Traversal(*this, LI);
736 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
737 POE = Traversal.end(); POI != POE; ++POI) ;
738 }
739