[IR] Reformulate LLVM's EH funclet IR
[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       // Return false if any loop blocks contain invokes to EH-pads other than
234       // landingpads;  we don't know how to split those edges yet.
235       auto *FirstNonPHI = II->getUnwindDest()->getFirstNonPHI();
236       if (FirstNonPHI->isEHPad() && !isa<LandingPadInst>(FirstNonPHI))
237         return false;
238     }
239
240     for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end(); BI != BE; ++BI) {
241       if (const CallInst *CI = dyn_cast<CallInst>(BI)) {
242         if (CI->cannotDuplicate())
243           return false;
244       }
245       if (BI->getType()->isTokenTy() && BI->isUsedOutsideOfBlock(*I))
246         return false;
247     }
248   }
249   return true;
250 }
251
252 MDNode *Loop::getLoopID() const {
253   MDNode *LoopID = nullptr;
254   if (isLoopSimplifyForm()) {
255     LoopID = getLoopLatch()->getTerminator()->getMetadata(LoopMDName);
256   } else {
257     // Go through each predecessor of the loop header and check the
258     // terminator for the metadata.
259     BasicBlock *H = getHeader();
260     for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
261       TerminatorInst *TI = (*I)->getTerminator();
262       MDNode *MD = nullptr;
263
264       // Check if this terminator branches to the loop header.
265       for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
266         if (TI->getSuccessor(i) == H) {
267           MD = TI->getMetadata(LoopMDName);
268           break;
269         }
270       }
271       if (!MD)
272         return nullptr;
273
274       if (!LoopID)
275         LoopID = MD;
276       else if (MD != LoopID)
277         return nullptr;
278     }
279   }
280   if (!LoopID || LoopID->getNumOperands() == 0 ||
281       LoopID->getOperand(0) != LoopID)
282     return nullptr;
283   return LoopID;
284 }
285
286 void Loop::setLoopID(MDNode *LoopID) const {
287   assert(LoopID && "Loop ID should not be null");
288   assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
289   assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
290
291   if (isLoopSimplifyForm()) {
292     getLoopLatch()->getTerminator()->setMetadata(LoopMDName, LoopID);
293     return;
294   }
295
296   BasicBlock *H = getHeader();
297   for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
298     TerminatorInst *TI = (*I)->getTerminator();
299     for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
300       if (TI->getSuccessor(i) == H)
301         TI->setMetadata(LoopMDName, LoopID);
302     }
303   }
304 }
305
306 bool Loop::isAnnotatedParallel() const {
307   MDNode *desiredLoopIdMetadata = getLoopID();
308
309   if (!desiredLoopIdMetadata)
310       return false;
311
312   // The loop branch contains the parallel loop metadata. In order to ensure
313   // that any parallel-loop-unaware optimization pass hasn't added loop-carried
314   // dependencies (thus converted the loop back to a sequential loop), check
315   // that all the memory instructions in the loop contain parallelism metadata
316   // that point to the same unique "loop id metadata" the loop branch does.
317   for (block_iterator BB = block_begin(), BE = block_end(); BB != BE; ++BB) {
318     for (BasicBlock::iterator II = (*BB)->begin(), EE = (*BB)->end();
319          II != EE; II++) {
320
321       if (!II->mayReadOrWriteMemory())
322         continue;
323
324       // The memory instruction can refer to the loop identifier metadata
325       // directly or indirectly through another list metadata (in case of
326       // nested parallel loops). The loop identifier metadata refers to
327       // itself so we can check both cases with the same routine.
328       MDNode *loopIdMD =
329           II->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
330
331       if (!loopIdMD)
332         return false;
333
334       bool loopIdMDFound = false;
335       for (unsigned i = 0, e = loopIdMD->getNumOperands(); i < e; ++i) {
336         if (loopIdMD->getOperand(i) == desiredLoopIdMetadata) {
337           loopIdMDFound = true;
338           break;
339         }
340       }
341
342       if (!loopIdMDFound)
343         return false;
344     }
345   }
346   return true;
347 }
348
349
350 /// hasDedicatedExits - Return true if no exit block for the loop
351 /// has a predecessor that is outside the loop.
352 bool Loop::hasDedicatedExits() const {
353   // Each predecessor of each exit block of a normal loop is contained
354   // within the loop.
355   SmallVector<BasicBlock *, 4> ExitBlocks;
356   getExitBlocks(ExitBlocks);
357   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
358     for (pred_iterator PI = pred_begin(ExitBlocks[i]),
359          PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
360       if (!contains(*PI))
361         return false;
362   // All the requirements are met.
363   return true;
364 }
365
366 /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
367 /// These are the blocks _outside of the current loop_ which are branched to.
368 /// This assumes that loop exits are in canonical form.
369 ///
370 void
371 Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
372   assert(hasDedicatedExits() &&
373          "getUniqueExitBlocks assumes the loop has canonical form exits!");
374
375   SmallVector<BasicBlock *, 32> switchExitBlocks;
376
377   for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
378
379     BasicBlock *current = *BI;
380     switchExitBlocks.clear();
381
382     for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
383       // If block is inside the loop then it is not a exit block.
384       if (contains(*I))
385         continue;
386
387       pred_iterator PI = pred_begin(*I);
388       BasicBlock *firstPred = *PI;
389
390       // If current basic block is this exit block's first predecessor
391       // then only insert exit block in to the output ExitBlocks vector.
392       // This ensures that same exit block is not inserted twice into
393       // ExitBlocks vector.
394       if (current != firstPred)
395         continue;
396
397       // If a terminator has more then two successors, for example SwitchInst,
398       // then it is possible that there are multiple edges from current block
399       // to one exit block.
400       if (std::distance(succ_begin(current), succ_end(current)) <= 2) {
401         ExitBlocks.push_back(*I);
402         continue;
403       }
404
405       // In case of multiple edges from current block to exit block, collect
406       // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
407       // duplicate edges.
408       if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
409           == switchExitBlocks.end()) {
410         switchExitBlocks.push_back(*I);
411         ExitBlocks.push_back(*I);
412       }
413     }
414   }
415 }
416
417 /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
418 /// block, return that block. Otherwise return null.
419 BasicBlock *Loop::getUniqueExitBlock() const {
420   SmallVector<BasicBlock *, 8> UniqueExitBlocks;
421   getUniqueExitBlocks(UniqueExitBlocks);
422   if (UniqueExitBlocks.size() == 1)
423     return UniqueExitBlocks[0];
424   return nullptr;
425 }
426
427 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
428 void Loop::dump() const {
429   print(dbgs());
430 }
431 #endif
432
433 //===----------------------------------------------------------------------===//
434 // UnloopUpdater implementation
435 //
436
437 namespace {
438 /// Find the new parent loop for all blocks within the "unloop" whose last
439 /// backedges has just been removed.
440 class UnloopUpdater {
441   Loop *Unloop;
442   LoopInfo *LI;
443
444   LoopBlocksDFS DFS;
445
446   // Map unloop's immediate subloops to their nearest reachable parents. Nested
447   // loops within these subloops will not change parents. However, an immediate
448   // subloop's new parent will be the nearest loop reachable from either its own
449   // exits *or* any of its nested loop's exits.
450   DenseMap<Loop*, Loop*> SubloopParents;
451
452   // Flag the presence of an irreducible backedge whose destination is a block
453   // directly contained by the original unloop.
454   bool FoundIB;
455
456 public:
457   UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
458     Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
459
460   void updateBlockParents();
461
462   void removeBlocksFromAncestors();
463
464   void updateSubloopParents();
465
466 protected:
467   Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
468 };
469 } // end anonymous namespace
470
471 /// updateBlockParents - Update the parent loop for all blocks that are directly
472 /// contained within the original "unloop".
473 void UnloopUpdater::updateBlockParents() {
474   if (Unloop->getNumBlocks()) {
475     // Perform a post order CFG traversal of all blocks within this loop,
476     // propagating the nearest loop from sucessors to predecessors.
477     LoopBlocksTraversal Traversal(DFS, LI);
478     for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
479            POE = Traversal.end(); POI != POE; ++POI) {
480
481       Loop *L = LI->getLoopFor(*POI);
482       Loop *NL = getNearestLoop(*POI, L);
483
484       if (NL != L) {
485         // For reducible loops, NL is now an ancestor of Unloop.
486         assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
487                "uninitialized successor");
488         LI->changeLoopFor(*POI, NL);
489       }
490       else {
491         // Or the current block is part of a subloop, in which case its parent
492         // is unchanged.
493         assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
494       }
495     }
496   }
497   // Each irreducible loop within the unloop induces a round of iteration using
498   // the DFS result cached by Traversal.
499   bool Changed = FoundIB;
500   for (unsigned NIters = 0; Changed; ++NIters) {
501     assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
502
503     // Iterate over the postorder list of blocks, propagating the nearest loop
504     // from successors to predecessors as before.
505     Changed = false;
506     for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
507            POE = DFS.endPostorder(); POI != POE; ++POI) {
508
509       Loop *L = LI->getLoopFor(*POI);
510       Loop *NL = getNearestLoop(*POI, L);
511       if (NL != L) {
512         assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
513                "uninitialized successor");
514         LI->changeLoopFor(*POI, NL);
515         Changed = true;
516       }
517     }
518   }
519 }
520
521 /// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors below
522 /// their new parents.
523 void UnloopUpdater::removeBlocksFromAncestors() {
524   // Remove all unloop's blocks (including those in nested subloops) from
525   // ancestors below the new parent loop.
526   for (Loop::block_iterator BI = Unloop->block_begin(),
527          BE = Unloop->block_end(); BI != BE; ++BI) {
528     Loop *OuterParent = LI->getLoopFor(*BI);
529     if (Unloop->contains(OuterParent)) {
530       while (OuterParent->getParentLoop() != Unloop)
531         OuterParent = OuterParent->getParentLoop();
532       OuterParent = SubloopParents[OuterParent];
533     }
534     // Remove blocks from former Ancestors except Unloop itself which will be
535     // deleted.
536     for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent;
537          OldParent = OldParent->getParentLoop()) {
538       assert(OldParent && "new loop is not an ancestor of the original");
539       OldParent->removeBlockFromLoop(*BI);
540     }
541   }
542 }
543
544 /// updateSubloopParents - Update the parent loop for all subloops directly
545 /// nested within unloop.
546 void UnloopUpdater::updateSubloopParents() {
547   while (!Unloop->empty()) {
548     Loop *Subloop = *std::prev(Unloop->end());
549     Unloop->removeChildLoop(std::prev(Unloop->end()));
550
551     assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
552     if (Loop *Parent = SubloopParents[Subloop])
553       Parent->addChildLoop(Subloop);
554     else
555       LI->addTopLevelLoop(Subloop);
556   }
557 }
558
559 /// getNearestLoop - Return the nearest parent loop among this block's
560 /// successors. If a successor is a subloop header, consider its parent to be
561 /// the nearest parent of the subloop's exits.
562 ///
563 /// For subloop blocks, simply update SubloopParents and return NULL.
564 Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
565
566   // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
567   // is considered uninitialized.
568   Loop *NearLoop = BBLoop;
569
570   Loop *Subloop = nullptr;
571   if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
572     Subloop = NearLoop;
573     // Find the subloop ancestor that is directly contained within Unloop.
574     while (Subloop->getParentLoop() != Unloop) {
575       Subloop = Subloop->getParentLoop();
576       assert(Subloop && "subloop is not an ancestor of the original loop");
577     }
578     // Get the current nearest parent of the Subloop exits, initially Unloop.
579     NearLoop =
580       SubloopParents.insert(std::make_pair(Subloop, Unloop)).first->second;
581   }
582
583   succ_iterator I = succ_begin(BB), E = succ_end(BB);
584   if (I == E) {
585     assert(!Subloop && "subloop blocks must have a successor");
586     NearLoop = nullptr; // unloop blocks may now exit the function.
587   }
588   for (; I != E; ++I) {
589     if (*I == BB)
590       continue; // self loops are uninteresting
591
592     Loop *L = LI->getLoopFor(*I);
593     if (L == Unloop) {
594       // This successor has not been processed. This path must lead to an
595       // irreducible backedge.
596       assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
597       FoundIB = true;
598     }
599     if (L != Unloop && Unloop->contains(L)) {
600       // Successor is in a subloop.
601       if (Subloop)
602         continue; // Branching within subloops. Ignore it.
603
604       // BB branches from the original into a subloop header.
605       assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
606
607       // Get the current nearest parent of the Subloop's exits.
608       L = SubloopParents[L];
609       // L could be Unloop if the only exit was an irreducible backedge.
610     }
611     if (L == Unloop) {
612       continue;
613     }
614     // Handle critical edges from Unloop into a sibling loop.
615     if (L && !L->contains(Unloop)) {
616       L = L->getParentLoop();
617     }
618     // Remember the nearest parent loop among successors or subloop exits.
619     if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
620       NearLoop = L;
621   }
622   if (Subloop) {
623     SubloopParents[Subloop] = NearLoop;
624     return BBLoop;
625   }
626   return NearLoop;
627 }
628
629 LoopInfo::LoopInfo(const DominatorTreeBase<BasicBlock> &DomTree) {
630   analyze(DomTree);
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.
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();
647          I != E; ++I) {
648
649       // Don't reparent blocks in subloops.
650       if (getLoopFor(*I) != Unloop)
651         continue;
652
653       // Blocks no longer have a parent but are still referenced by Unloop until
654       // the Unloop object is deleted.
655       changeLoopFor(*I, nullptr);
656     }
657
658     // Remove the loop from the top-level LoopInfo object.
659     for (iterator I = begin();; ++I) {
660       assert(I != end() && "Couldn't find loop");
661       if (*I == Unloop) {
662         removeLoop(I);
663         break;
664       }
665     }
666
667     // Move all of the subloops to the top-level.
668     while (!Unloop->empty())
669       addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
670
671     return;
672   }
673
674   // Update the parent loop for all blocks within the loop. Blocks within
675   // subloops will not change parents.
676   UnloopUpdater Updater(Unloop, this);
677   Updater.updateBlockParents();
678
679   // Remove blocks from former ancestor loops.
680   Updater.removeBlocksFromAncestors();
681
682   // Add direct subloops as children in their new parent loop.
683   Updater.updateSubloopParents();
684
685   // Remove unloop from its parent loop.
686   Loop *ParentLoop = Unloop->getParentLoop();
687   for (Loop::iterator I = ParentLoop->begin();; ++I) {
688     assert(I != ParentLoop->end() && "Couldn't find loop");
689     if (*I == Unloop) {
690       ParentLoop->removeChildLoop(I);
691       break;
692     }
693   }
694 }
695
696 char LoopAnalysis::PassID;
697
698 LoopInfo LoopAnalysis::run(Function &F, AnalysisManager<Function> *AM) {
699   // FIXME: Currently we create a LoopInfo from scratch for every function.
700   // This may prove to be too wasteful due to deallocating and re-allocating
701   // memory each time for the underlying map and vector datastructures. At some
702   // point it may prove worthwhile to use a freelist and recycle LoopInfo
703   // objects. I don't want to add that kind of complexity until the scope of
704   // the problem is better understood.
705   LoopInfo LI;
706   LI.analyze(AM->getResult<DominatorTreeAnalysis>(F));
707   return LI;
708 }
709
710 PreservedAnalyses LoopPrinterPass::run(Function &F,
711                                        AnalysisManager<Function> *AM) {
712   AM->getResult<LoopAnalysis>(F).print(OS);
713   return PreservedAnalyses::all();
714 }
715
716 PrintLoopPass::PrintLoopPass() : OS(dbgs()) {}
717 PrintLoopPass::PrintLoopPass(raw_ostream &OS, const std::string &Banner)
718     : OS(OS), Banner(Banner) {}
719
720 PreservedAnalyses PrintLoopPass::run(Loop &L) {
721   OS << Banner;
722   for (auto *Block : L.blocks())
723     if (Block)
724       Block->print(OS);
725     else
726       OS << "Printing <null> block";
727   return PreservedAnalyses::all();
728 }
729
730 //===----------------------------------------------------------------------===//
731 // LoopInfo implementation
732 //
733
734 char LoopInfoWrapperPass::ID = 0;
735 INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
736                       true, true)
737 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
738 INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
739                     true, true)
740
741 bool LoopInfoWrapperPass::runOnFunction(Function &) {
742   releaseMemory();
743   LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
744   return false;
745 }
746
747 void LoopInfoWrapperPass::verifyAnalysis() const {
748   // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
749   // function each time verifyAnalysis is called is very expensive. The
750   // -verify-loop-info option can enable this. In order to perform some
751   // checking by default, LoopPass has been taught to call verifyLoop manually
752   // during loop pass sequences.
753   if (VerifyLoopInfo)
754     LI.verify();
755 }
756
757 void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
758   AU.setPreservesAll();
759   AU.addRequired<DominatorTreeWrapperPass>();
760 }
761
762 void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
763   LI.print(OS);
764 }
765
766 //===----------------------------------------------------------------------===//
767 // LoopBlocksDFS implementation
768 //
769
770 /// Traverse the loop blocks and store the DFS result.
771 /// Useful for clients that just want the final DFS result and don't need to
772 /// visit blocks during the initial traversal.
773 void LoopBlocksDFS::perform(LoopInfo *LI) {
774   LoopBlocksTraversal Traversal(*this, LI);
775   for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
776          POE = Traversal.end(); POI != POE; ++POI) ;
777 }