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