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