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