xref: /llvm-project/llvm/lib/Analysis/LoopInfo.cpp (revision 51f837a68009c8ae15b828a0c93a744432410ad5)
1 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the LoopInfo class that is used to identify natural loops
10 // and determine the loop depth of various nodes of the CFG.  Note that the
11 // loops identified may actually be several natural loops that share the same
12 // header node... not just a single natural loop.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Analysis/LoopInfo.h"
17 #include "llvm/ADT/ScopeExit.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/Analysis/IVDescriptors.h"
20 #include "llvm/Analysis/LoopInfoImpl.h"
21 #include "llvm/Analysis/LoopIterator.h"
22 #include "llvm/Analysis/LoopNestAnalysis.h"
23 #include "llvm/Analysis/MemorySSA.h"
24 #include "llvm/Analysis/MemorySSAUpdater.h"
25 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/Config/llvm-config.h"
28 #include "llvm/IR/CFG.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DebugLoc.h"
31 #include "llvm/IR/Dominators.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/Metadata.h"
35 #include "llvm/IR/PassManager.h"
36 #include "llvm/IR/PrintPasses.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/raw_ostream.h"
40 using namespace llvm;
41 
42 // Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
43 template class llvm::LoopBase<BasicBlock, Loop>;
44 template class llvm::LoopInfoBase<BasicBlock, Loop>;
45 
46 // Always verify loopinfo if expensive checking is enabled.
47 #ifdef EXPENSIVE_CHECKS
48 bool llvm::VerifyLoopInfo = true;
49 #else
50 bool llvm::VerifyLoopInfo = false;
51 #endif
52 static cl::opt<bool, true>
53     VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
54                     cl::Hidden, cl::desc("Verify loop info (time consuming)"));
55 
56 //===----------------------------------------------------------------------===//
57 // Loop implementation
58 //
59 
60 bool Loop::isLoopInvariant(const Value *V) const {
61   if (const Instruction *I = dyn_cast<Instruction>(V))
62     return !contains(I);
63   return true; // All non-instructions are loop invariant
64 }
65 
66 bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
67   return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
68 }
69 
70 bool Loop::makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt,
71                              MemorySSAUpdater *MSSAU) const {
72   if (Instruction *I = dyn_cast<Instruction>(V))
73     return makeLoopInvariant(I, Changed, InsertPt, MSSAU);
74   return true; // All non-instructions are loop-invariant.
75 }
76 
77 bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
78                              Instruction *InsertPt,
79                              MemorySSAUpdater *MSSAU) const {
80   // Test if the value is already loop-invariant.
81   if (isLoopInvariant(I))
82     return true;
83   if (!isSafeToSpeculativelyExecute(I))
84     return false;
85   if (I->mayReadFromMemory())
86     return false;
87   // EH block instructions are immobile.
88   if (I->isEHPad())
89     return false;
90   // Determine the insertion point, unless one was given.
91   if (!InsertPt) {
92     BasicBlock *Preheader = getLoopPreheader();
93     // Without a preheader, hoisting is not feasible.
94     if (!Preheader)
95       return false;
96     InsertPt = Preheader->getTerminator();
97   }
98   // Don't hoist instructions with loop-variant operands.
99   for (Value *Operand : I->operands())
100     if (!makeLoopInvariant(Operand, Changed, InsertPt, MSSAU))
101       return false;
102 
103   // Hoist.
104   I->moveBefore(InsertPt);
105   if (MSSAU)
106     if (auto *MUD = MSSAU->getMemorySSA()->getMemoryAccess(I))
107       MSSAU->moveToPlace(MUD, InsertPt->getParent(),
108                          MemorySSA::BeforeTerminator);
109 
110   // There is possibility of hoisting this instruction above some arbitrary
111   // condition. Any metadata defined on it can be control dependent on this
112   // condition. Conservatively strip it here so that we don't give any wrong
113   // information to the optimizer.
114   I->dropUnknownNonDebugMetadata();
115 
116   Changed = true;
117   return true;
118 }
119 
120 bool Loop::getIncomingAndBackEdge(BasicBlock *&Incoming,
121                                   BasicBlock *&Backedge) const {
122   BasicBlock *H = getHeader();
123 
124   Incoming = nullptr;
125   Backedge = nullptr;
126   pred_iterator PI = pred_begin(H);
127   assert(PI != pred_end(H) && "Loop must have at least one backedge!");
128   Backedge = *PI++;
129   if (PI == pred_end(H))
130     return false; // dead loop
131   Incoming = *PI++;
132   if (PI != pred_end(H))
133     return false; // multiple backedges?
134 
135   if (contains(Incoming)) {
136     if (contains(Backedge))
137       return false;
138     std::swap(Incoming, Backedge);
139   } else if (!contains(Backedge))
140     return false;
141 
142   assert(Incoming && Backedge && "expected non-null incoming and backedges");
143   return true;
144 }
145 
146 PHINode *Loop::getCanonicalInductionVariable() const {
147   BasicBlock *H = getHeader();
148 
149   BasicBlock *Incoming = nullptr, *Backedge = nullptr;
150   if (!getIncomingAndBackEdge(Incoming, Backedge))
151     return nullptr;
152 
153   // Loop over all of the PHI nodes, looking for a canonical indvar.
154   for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
155     PHINode *PN = cast<PHINode>(I);
156     if (ConstantInt *CI =
157             dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
158       if (CI->isZero())
159         if (Instruction *Inc =
160                 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
161           if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
162             if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
163               if (CI->isOne())
164                 return PN;
165   }
166   return nullptr;
167 }
168 
169 /// Get the latch condition instruction.
170 ICmpInst *Loop::getLatchCmpInst() const {
171   if (BasicBlock *Latch = getLoopLatch())
172     if (BranchInst *BI = dyn_cast_or_null<BranchInst>(Latch->getTerminator()))
173       if (BI->isConditional())
174         return dyn_cast<ICmpInst>(BI->getCondition());
175 
176   return nullptr;
177 }
178 
179 /// Return the final value of the loop induction variable if found.
180 static Value *findFinalIVValue(const Loop &L, const PHINode &IndVar,
181                                const Instruction &StepInst) {
182   ICmpInst *LatchCmpInst = L.getLatchCmpInst();
183   if (!LatchCmpInst)
184     return nullptr;
185 
186   Value *Op0 = LatchCmpInst->getOperand(0);
187   Value *Op1 = LatchCmpInst->getOperand(1);
188   if (Op0 == &IndVar || Op0 == &StepInst)
189     return Op1;
190 
191   if (Op1 == &IndVar || Op1 == &StepInst)
192     return Op0;
193 
194   return nullptr;
195 }
196 
197 Optional<Loop::LoopBounds> Loop::LoopBounds::getBounds(const Loop &L,
198                                                        PHINode &IndVar,
199                                                        ScalarEvolution &SE) {
200   InductionDescriptor IndDesc;
201   if (!InductionDescriptor::isInductionPHI(&IndVar, &L, &SE, IndDesc))
202     return None;
203 
204   Value *InitialIVValue = IndDesc.getStartValue();
205   Instruction *StepInst = IndDesc.getInductionBinOp();
206   if (!InitialIVValue || !StepInst)
207     return None;
208 
209   const SCEV *Step = IndDesc.getStep();
210   Value *StepInstOp1 = StepInst->getOperand(1);
211   Value *StepInstOp0 = StepInst->getOperand(0);
212   Value *StepValue = nullptr;
213   if (SE.getSCEV(StepInstOp1) == Step)
214     StepValue = StepInstOp1;
215   else if (SE.getSCEV(StepInstOp0) == Step)
216     StepValue = StepInstOp0;
217 
218   Value *FinalIVValue = findFinalIVValue(L, IndVar, *StepInst);
219   if (!FinalIVValue)
220     return None;
221 
222   return LoopBounds(L, *InitialIVValue, *StepInst, StepValue, *FinalIVValue,
223                     SE);
224 }
225 
226 using Direction = Loop::LoopBounds::Direction;
227 
228 ICmpInst::Predicate Loop::LoopBounds::getCanonicalPredicate() const {
229   BasicBlock *Latch = L.getLoopLatch();
230   assert(Latch && "Expecting valid latch");
231 
232   BranchInst *BI = dyn_cast_or_null<BranchInst>(Latch->getTerminator());
233   assert(BI && BI->isConditional() && "Expecting conditional latch branch");
234 
235   ICmpInst *LatchCmpInst = dyn_cast<ICmpInst>(BI->getCondition());
236   assert(LatchCmpInst &&
237          "Expecting the latch compare instruction to be a CmpInst");
238 
239   // Need to inverse the predicate when first successor is not the loop
240   // header
241   ICmpInst::Predicate Pred = (BI->getSuccessor(0) == L.getHeader())
242                                  ? LatchCmpInst->getPredicate()
243                                  : LatchCmpInst->getInversePredicate();
244 
245   if (LatchCmpInst->getOperand(0) == &getFinalIVValue())
246     Pred = ICmpInst::getSwappedPredicate(Pred);
247 
248   // Need to flip strictness of the predicate when the latch compare instruction
249   // is not using StepInst
250   if (LatchCmpInst->getOperand(0) == &getStepInst() ||
251       LatchCmpInst->getOperand(1) == &getStepInst())
252     return Pred;
253 
254   // Cannot flip strictness of NE and EQ
255   if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
256     return ICmpInst::getFlippedStrictnessPredicate(Pred);
257 
258   Direction D = getDirection();
259   if (D == Direction::Increasing)
260     return ICmpInst::ICMP_SLT;
261 
262   if (D == Direction::Decreasing)
263     return ICmpInst::ICMP_SGT;
264 
265   // If cannot determine the direction, then unable to find the canonical
266   // predicate
267   return ICmpInst::BAD_ICMP_PREDICATE;
268 }
269 
270 Direction Loop::LoopBounds::getDirection() const {
271   if (const SCEVAddRecExpr *StepAddRecExpr =
272           dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&getStepInst())))
273     if (const SCEV *StepRecur = StepAddRecExpr->getStepRecurrence(SE)) {
274       if (SE.isKnownPositive(StepRecur))
275         return Direction::Increasing;
276       if (SE.isKnownNegative(StepRecur))
277         return Direction::Decreasing;
278     }
279 
280   return Direction::Unknown;
281 }
282 
283 Optional<Loop::LoopBounds> Loop::getBounds(ScalarEvolution &SE) const {
284   if (PHINode *IndVar = getInductionVariable(SE))
285     return LoopBounds::getBounds(*this, *IndVar, SE);
286 
287   return None;
288 }
289 
290 PHINode *Loop::getInductionVariable(ScalarEvolution &SE) const {
291   if (!isLoopSimplifyForm())
292     return nullptr;
293 
294   BasicBlock *Header = getHeader();
295   assert(Header && "Expected a valid loop header");
296   ICmpInst *CmpInst = getLatchCmpInst();
297   if (!CmpInst)
298     return nullptr;
299 
300   Value *LatchCmpOp0 = CmpInst->getOperand(0);
301   Value *LatchCmpOp1 = CmpInst->getOperand(1);
302 
303   for (PHINode &IndVar : Header->phis()) {
304     InductionDescriptor IndDesc;
305     if (!InductionDescriptor::isInductionPHI(&IndVar, this, &SE, IndDesc))
306       continue;
307 
308     BasicBlock *Latch = getLoopLatch();
309     Value *StepInst = IndVar.getIncomingValueForBlock(Latch);
310 
311     // case 1:
312     // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
313     // StepInst = IndVar + step
314     // cmp = StepInst < FinalValue
315     if (StepInst == LatchCmpOp0 || StepInst == LatchCmpOp1)
316       return &IndVar;
317 
318     // case 2:
319     // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
320     // StepInst = IndVar + step
321     // cmp = IndVar < FinalValue
322     if (&IndVar == LatchCmpOp0 || &IndVar == LatchCmpOp1)
323       return &IndVar;
324   }
325 
326   return nullptr;
327 }
328 
329 bool Loop::getInductionDescriptor(ScalarEvolution &SE,
330                                   InductionDescriptor &IndDesc) const {
331   if (PHINode *IndVar = getInductionVariable(SE))
332     return InductionDescriptor::isInductionPHI(IndVar, this, &SE, IndDesc);
333 
334   return false;
335 }
336 
337 bool Loop::isAuxiliaryInductionVariable(PHINode &AuxIndVar,
338                                         ScalarEvolution &SE) const {
339   // Located in the loop header
340   BasicBlock *Header = getHeader();
341   if (AuxIndVar.getParent() != Header)
342     return false;
343 
344   // No uses outside of the loop
345   for (User *U : AuxIndVar.users())
346     if (const Instruction *I = dyn_cast<Instruction>(U))
347       if (!contains(I))
348         return false;
349 
350   InductionDescriptor IndDesc;
351   if (!InductionDescriptor::isInductionPHI(&AuxIndVar, this, &SE, IndDesc))
352     return false;
353 
354   // The step instruction opcode should be add or sub.
355   if (IndDesc.getInductionOpcode() != Instruction::Add &&
356       IndDesc.getInductionOpcode() != Instruction::Sub)
357     return false;
358 
359   // Incremented by a loop invariant step for each loop iteration
360   return SE.isLoopInvariant(IndDesc.getStep(), this);
361 }
362 
363 BranchInst *Loop::getLoopGuardBranch() const {
364   if (!isLoopSimplifyForm())
365     return nullptr;
366 
367   BasicBlock *Preheader = getLoopPreheader();
368   assert(Preheader && getLoopLatch() &&
369          "Expecting a loop with valid preheader and latch");
370 
371   // Loop should be in rotate form.
372   if (!isRotatedForm())
373     return nullptr;
374 
375   // Disallow loops with more than one unique exit block, as we do not verify
376   // that GuardOtherSucc post dominates all exit blocks.
377   BasicBlock *ExitFromLatch = getUniqueExitBlock();
378   if (!ExitFromLatch)
379     return nullptr;
380 
381   BasicBlock *GuardBB = Preheader->getUniquePredecessor();
382   if (!GuardBB)
383     return nullptr;
384 
385   assert(GuardBB->getTerminator() && "Expecting valid guard terminator");
386 
387   BranchInst *GuardBI = dyn_cast<BranchInst>(GuardBB->getTerminator());
388   if (!GuardBI || GuardBI->isUnconditional())
389     return nullptr;
390 
391   BasicBlock *GuardOtherSucc = (GuardBI->getSuccessor(0) == Preheader)
392                                    ? GuardBI->getSuccessor(1)
393                                    : GuardBI->getSuccessor(0);
394 
395   // Check if ExitFromLatch (or any BasicBlock which is an empty unique
396   // successor of ExitFromLatch) is equal to GuardOtherSucc. If
397   // skipEmptyBlockUntil returns GuardOtherSucc, then the guard branch for the
398   // loop is GuardBI (return GuardBI), otherwise return nullptr.
399   if (&LoopNest::skipEmptyBlockUntil(ExitFromLatch, GuardOtherSucc,
400                                      /*CheckUniquePred=*/true) ==
401       GuardOtherSucc)
402     return GuardBI;
403   else
404     return nullptr;
405 }
406 
407 bool Loop::isCanonical(ScalarEvolution &SE) const {
408   InductionDescriptor IndDesc;
409   if (!getInductionDescriptor(SE, IndDesc))
410     return false;
411 
412   ConstantInt *Init = dyn_cast_or_null<ConstantInt>(IndDesc.getStartValue());
413   if (!Init || !Init->isZero())
414     return false;
415 
416   if (IndDesc.getInductionOpcode() != Instruction::Add)
417     return false;
418 
419   ConstantInt *Step = IndDesc.getConstIntStepValue();
420   if (!Step || !Step->isOne())
421     return false;
422 
423   return true;
424 }
425 
426 // Check that 'BB' doesn't have any uses outside of the 'L'
427 static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB,
428                                const DominatorTree &DT, bool IgnoreTokens) {
429   for (const Instruction &I : BB) {
430     // Tokens can't be used in PHI nodes and live-out tokens prevent loop
431     // optimizations, so for the purposes of considered LCSSA form, we
432     // can ignore them.
433     if (IgnoreTokens && I.getType()->isTokenTy())
434       continue;
435 
436     for (const Use &U : I.uses()) {
437       const Instruction *UI = cast<Instruction>(U.getUser());
438       const BasicBlock *UserBB = UI->getParent();
439 
440       // For practical purposes, we consider that the use in a PHI
441       // occurs in the respective predecessor block. For more info,
442       // see the `phi` doc in LangRef and the LCSSA doc.
443       if (const PHINode *P = dyn_cast<PHINode>(UI))
444         UserBB = P->getIncomingBlock(U);
445 
446       // Check the current block, as a fast-path, before checking whether
447       // the use is anywhere in the loop.  Most values are used in the same
448       // block they are defined in.  Also, blocks not reachable from the
449       // entry are special; uses in them don't need to go through PHIs.
450       if (UserBB != &BB && !L.contains(UserBB) &&
451           DT.isReachableFromEntry(UserBB))
452         return false;
453     }
454   }
455   return true;
456 }
457 
458 bool Loop::isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens) const {
459   // For each block we check that it doesn't have any uses outside of this loop.
460   return all_of(this->blocks(), [&](const BasicBlock *BB) {
461     return isBlockInLCSSAForm(*this, *BB, DT, IgnoreTokens);
462   });
463 }
464 
465 bool Loop::isRecursivelyLCSSAForm(const DominatorTree &DT, const LoopInfo &LI,
466                                   bool IgnoreTokens) const {
467   // For each block we check that it doesn't have any uses outside of its
468   // innermost loop. This process will transitively guarantee that the current
469   // loop and all of the nested loops are in LCSSA form.
470   return all_of(this->blocks(), [&](const BasicBlock *BB) {
471     return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT, IgnoreTokens);
472   });
473 }
474 
475 bool Loop::isLoopSimplifyForm() const {
476   // Normal-form loops have a preheader, a single backedge, and all of their
477   // exits have all their predecessors inside the loop.
478   return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
479 }
480 
481 // Routines that reform the loop CFG and split edges often fail on indirectbr.
482 bool Loop::isSafeToClone() const {
483   // Return false if any loop blocks contain indirectbrs, or there are any calls
484   // to noduplicate functions.
485   // FIXME: it should be ok to clone CallBrInst's if we correctly update the
486   // operand list to reflect the newly cloned labels.
487   for (BasicBlock *BB : this->blocks()) {
488     if (isa<IndirectBrInst>(BB->getTerminator()) ||
489         isa<CallBrInst>(BB->getTerminator()))
490       return false;
491 
492     for (Instruction &I : *BB)
493       if (auto *CB = dyn_cast<CallBase>(&I))
494         if (CB->cannotDuplicate())
495           return false;
496   }
497   return true;
498 }
499 
500 MDNode *Loop::getLoopID() const {
501   MDNode *LoopID = nullptr;
502 
503   // Go through the latch blocks and check the terminator for the metadata.
504   SmallVector<BasicBlock *, 4> LatchesBlocks;
505   getLoopLatches(LatchesBlocks);
506   for (BasicBlock *BB : LatchesBlocks) {
507     Instruction *TI = BB->getTerminator();
508     MDNode *MD = TI->getMetadata(LLVMContext::MD_loop);
509 
510     if (!MD)
511       return nullptr;
512 
513     if (!LoopID)
514       LoopID = MD;
515     else if (MD != LoopID)
516       return nullptr;
517   }
518   if (!LoopID || LoopID->getNumOperands() == 0 ||
519       LoopID->getOperand(0) != LoopID)
520     return nullptr;
521   return LoopID;
522 }
523 
524 void Loop::setLoopID(MDNode *LoopID) const {
525   assert((!LoopID || LoopID->getNumOperands() > 0) &&
526          "Loop ID needs at least one operand");
527   assert((!LoopID || LoopID->getOperand(0) == LoopID) &&
528          "Loop ID should refer to itself");
529 
530   SmallVector<BasicBlock *, 4> LoopLatches;
531   getLoopLatches(LoopLatches);
532   for (BasicBlock *BB : LoopLatches)
533     BB->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
534 }
535 
536 void Loop::setLoopAlreadyUnrolled() {
537   LLVMContext &Context = getHeader()->getContext();
538 
539   MDNode *DisableUnrollMD =
540       MDNode::get(Context, MDString::get(Context, "llvm.loop.unroll.disable"));
541   MDNode *LoopID = getLoopID();
542   MDNode *NewLoopID = makePostTransformationMetadata(
543       Context, LoopID, {"llvm.loop.unroll."}, {DisableUnrollMD});
544   setLoopID(NewLoopID);
545 }
546 
547 void Loop::setLoopMustProgress() {
548   LLVMContext &Context = getHeader()->getContext();
549 
550   MDNode *MustProgress = findOptionMDForLoop(this, "llvm.loop.mustprogress");
551 
552   if (MustProgress)
553     return;
554 
555   MDNode *MustProgressMD =
556       MDNode::get(Context, MDString::get(Context, "llvm.loop.mustprogress"));
557   MDNode *LoopID = getLoopID();
558   MDNode *NewLoopID =
559       makePostTransformationMetadata(Context, LoopID, {}, {MustProgressMD});
560   setLoopID(NewLoopID);
561 }
562 
563 bool Loop::isAnnotatedParallel() const {
564   MDNode *DesiredLoopIdMetadata = getLoopID();
565 
566   if (!DesiredLoopIdMetadata)
567     return false;
568 
569   MDNode *ParallelAccesses =
570       findOptionMDForLoop(this, "llvm.loop.parallel_accesses");
571   SmallPtrSet<MDNode *, 4>
572       ParallelAccessGroups; // For scalable 'contains' check.
573   if (ParallelAccesses) {
574     for (const MDOperand &MD : drop_begin(ParallelAccesses->operands())) {
575       MDNode *AccGroup = cast<MDNode>(MD.get());
576       assert(isValidAsAccessGroup(AccGroup) &&
577              "List item must be an access group");
578       ParallelAccessGroups.insert(AccGroup);
579     }
580   }
581 
582   // The loop branch contains the parallel loop metadata. In order to ensure
583   // that any parallel-loop-unaware optimization pass hasn't added loop-carried
584   // dependencies (thus converted the loop back to a sequential loop), check
585   // that all the memory instructions in the loop belong to an access group that
586   // is parallel to this loop.
587   for (BasicBlock *BB : this->blocks()) {
588     for (Instruction &I : *BB) {
589       if (!I.mayReadOrWriteMemory())
590         continue;
591 
592       if (MDNode *AccessGroup = I.getMetadata(LLVMContext::MD_access_group)) {
593         auto ContainsAccessGroup = [&ParallelAccessGroups](MDNode *AG) -> bool {
594           if (AG->getNumOperands() == 0) {
595             assert(isValidAsAccessGroup(AG) && "Item must be an access group");
596             return ParallelAccessGroups.count(AG);
597           }
598 
599           for (const MDOperand &AccessListItem : AG->operands()) {
600             MDNode *AccGroup = cast<MDNode>(AccessListItem.get());
601             assert(isValidAsAccessGroup(AccGroup) &&
602                    "List item must be an access group");
603             if (ParallelAccessGroups.count(AccGroup))
604               return true;
605           }
606           return false;
607         };
608 
609         if (ContainsAccessGroup(AccessGroup))
610           continue;
611       }
612 
613       // The memory instruction can refer to the loop identifier metadata
614       // directly or indirectly through another list metadata (in case of
615       // nested parallel loops). The loop identifier metadata refers to
616       // itself so we can check both cases with the same routine.
617       MDNode *LoopIdMD =
618           I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
619 
620       if (!LoopIdMD)
621         return false;
622 
623       if (!llvm::is_contained(LoopIdMD->operands(), DesiredLoopIdMetadata))
624         return false;
625     }
626   }
627   return true;
628 }
629 
630 DebugLoc Loop::getStartLoc() const { return getLocRange().getStart(); }
631 
632 Loop::LocRange Loop::getLocRange() const {
633   // If we have a debug location in the loop ID, then use it.
634   if (MDNode *LoopID = getLoopID()) {
635     DebugLoc Start;
636     // We use the first DebugLoc in the header as the start location of the loop
637     // and if there is a second DebugLoc in the header we use it as end location
638     // of the loop.
639     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
640       if (DILocation *L = dyn_cast<DILocation>(LoopID->getOperand(i))) {
641         if (!Start)
642           Start = DebugLoc(L);
643         else
644           return LocRange(Start, DebugLoc(L));
645       }
646     }
647 
648     if (Start)
649       return LocRange(Start);
650   }
651 
652   // Try the pre-header first.
653   if (BasicBlock *PHeadBB = getLoopPreheader())
654     if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
655       return LocRange(DL);
656 
657   // If we have no pre-header or there are no instructions with debug
658   // info in it, try the header.
659   if (BasicBlock *HeadBB = getHeader())
660     return LocRange(HeadBB->getTerminator()->getDebugLoc());
661 
662   return LocRange();
663 }
664 
665 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
666 LLVM_DUMP_METHOD void Loop::dump() const { print(dbgs()); }
667 
668 LLVM_DUMP_METHOD void Loop::dumpVerbose() const {
669   print(dbgs(), /*Verbose=*/true);
670 }
671 #endif
672 
673 //===----------------------------------------------------------------------===//
674 // UnloopUpdater implementation
675 //
676 
677 namespace {
678 /// Find the new parent loop for all blocks within the "unloop" whose last
679 /// backedges has just been removed.
680 class UnloopUpdater {
681   Loop &Unloop;
682   LoopInfo *LI;
683 
684   LoopBlocksDFS DFS;
685 
686   // Map unloop's immediate subloops to their nearest reachable parents. Nested
687   // loops within these subloops will not change parents. However, an immediate
688   // subloop's new parent will be the nearest loop reachable from either its own
689   // exits *or* any of its nested loop's exits.
690   DenseMap<Loop *, Loop *> SubloopParents;
691 
692   // Flag the presence of an irreducible backedge whose destination is a block
693   // directly contained by the original unloop.
694   bool FoundIB = false;
695 
696 public:
697   UnloopUpdater(Loop *UL, LoopInfo *LInfo) : Unloop(*UL), LI(LInfo), DFS(UL) {}
698 
699   void updateBlockParents();
700 
701   void removeBlocksFromAncestors();
702 
703   void updateSubloopParents();
704 
705 protected:
706   Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
707 };
708 } // end anonymous namespace
709 
710 /// Update the parent loop for all blocks that are directly contained within the
711 /// original "unloop".
712 void UnloopUpdater::updateBlockParents() {
713   if (Unloop.getNumBlocks()) {
714     // Perform a post order CFG traversal of all blocks within this loop,
715     // propagating the nearest loop from successors to predecessors.
716     LoopBlocksTraversal Traversal(DFS, LI);
717     for (BasicBlock *POI : Traversal) {
718 
719       Loop *L = LI->getLoopFor(POI);
720       Loop *NL = getNearestLoop(POI, L);
721 
722       if (NL != L) {
723         // For reducible loops, NL is now an ancestor of Unloop.
724         assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
725                "uninitialized successor");
726         LI->changeLoopFor(POI, NL);
727       } else {
728         // Or the current block is part of a subloop, in which case its parent
729         // is unchanged.
730         assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
731       }
732     }
733   }
734   // Each irreducible loop within the unloop induces a round of iteration using
735   // the DFS result cached by Traversal.
736   bool Changed = FoundIB;
737   for (unsigned NIters = 0; Changed; ++NIters) {
738     assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
739     (void) NIters;
740 
741     // Iterate over the postorder list of blocks, propagating the nearest loop
742     // from successors to predecessors as before.
743     Changed = false;
744     for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
745                                    POE = DFS.endPostorder();
746          POI != POE; ++POI) {
747 
748       Loop *L = LI->getLoopFor(*POI);
749       Loop *NL = getNearestLoop(*POI, L);
750       if (NL != L) {
751         assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
752                "uninitialized successor");
753         LI->changeLoopFor(*POI, NL);
754         Changed = true;
755       }
756     }
757   }
758 }
759 
760 /// Remove unloop's blocks from all ancestors below their new parents.
761 void UnloopUpdater::removeBlocksFromAncestors() {
762   // Remove all unloop's blocks (including those in nested subloops) from
763   // ancestors below the new parent loop.
764   for (BasicBlock *BB : Unloop.blocks()) {
765     Loop *OuterParent = LI->getLoopFor(BB);
766     if (Unloop.contains(OuterParent)) {
767       while (OuterParent->getParentLoop() != &Unloop)
768         OuterParent = OuterParent->getParentLoop();
769       OuterParent = SubloopParents[OuterParent];
770     }
771     // Remove blocks from former Ancestors except Unloop itself which will be
772     // deleted.
773     for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
774          OldParent = OldParent->getParentLoop()) {
775       assert(OldParent && "new loop is not an ancestor of the original");
776       OldParent->removeBlockFromLoop(BB);
777     }
778   }
779 }
780 
781 /// Update the parent loop for all subloops directly nested within unloop.
782 void UnloopUpdater::updateSubloopParents() {
783   while (!Unloop.isInnermost()) {
784     Loop *Subloop = *std::prev(Unloop.end());
785     Unloop.removeChildLoop(std::prev(Unloop.end()));
786 
787     assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
788     if (Loop *Parent = SubloopParents[Subloop])
789       Parent->addChildLoop(Subloop);
790     else
791       LI->addTopLevelLoop(Subloop);
792   }
793 }
794 
795 /// Return the nearest parent loop among this block's successors. If a successor
796 /// is a subloop header, consider its parent to be the nearest parent of the
797 /// subloop's exits.
798 ///
799 /// For subloop blocks, simply update SubloopParents and return NULL.
800 Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
801 
802   // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
803   // is considered uninitialized.
804   Loop *NearLoop = BBLoop;
805 
806   Loop *Subloop = nullptr;
807   if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
808     Subloop = NearLoop;
809     // Find the subloop ancestor that is directly contained within Unloop.
810     while (Subloop->getParentLoop() != &Unloop) {
811       Subloop = Subloop->getParentLoop();
812       assert(Subloop && "subloop is not an ancestor of the original loop");
813     }
814     // Get the current nearest parent of the Subloop exits, initially Unloop.
815     NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second;
816   }
817 
818   succ_iterator I = succ_begin(BB), E = succ_end(BB);
819   if (I == E) {
820     assert(!Subloop && "subloop blocks must have a successor");
821     NearLoop = nullptr; // unloop blocks may now exit the function.
822   }
823   for (; I != E; ++I) {
824     if (*I == BB)
825       continue; // self loops are uninteresting
826 
827     Loop *L = LI->getLoopFor(*I);
828     if (L == &Unloop) {
829       // This successor has not been processed. This path must lead to an
830       // irreducible backedge.
831       assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
832       FoundIB = true;
833     }
834     if (L != &Unloop && Unloop.contains(L)) {
835       // Successor is in a subloop.
836       if (Subloop)
837         continue; // Branching within subloops. Ignore it.
838 
839       // BB branches from the original into a subloop header.
840       assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
841 
842       // Get the current nearest parent of the Subloop's exits.
843       L = SubloopParents[L];
844       // L could be Unloop if the only exit was an irreducible backedge.
845     }
846     if (L == &Unloop) {
847       continue;
848     }
849     // Handle critical edges from Unloop into a sibling loop.
850     if (L && !L->contains(&Unloop)) {
851       L = L->getParentLoop();
852     }
853     // Remember the nearest parent loop among successors or subloop exits.
854     if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
855       NearLoop = L;
856   }
857   if (Subloop) {
858     SubloopParents[Subloop] = NearLoop;
859     return BBLoop;
860   }
861   return NearLoop;
862 }
863 
864 LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); }
865 
866 bool LoopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
867                           FunctionAnalysisManager::Invalidator &) {
868   // Check whether the analysis, all analyses on functions, or the function's
869   // CFG have been preserved.
870   auto PAC = PA.getChecker<LoopAnalysis>();
871   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
872            PAC.preservedSet<CFGAnalyses>());
873 }
874 
875 void LoopInfo::erase(Loop *Unloop) {
876   assert(!Unloop->isInvalid() && "Loop has already been erased!");
877 
878   auto InvalidateOnExit = make_scope_exit([&]() { destroy(Unloop); });
879 
880   // First handle the special case of no parent loop to simplify the algorithm.
881   if (Unloop->isOutermost()) {
882     // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
883     for (BasicBlock *BB : Unloop->blocks()) {
884       // Don't reparent blocks in subloops.
885       if (getLoopFor(BB) != Unloop)
886         continue;
887 
888       // Blocks no longer have a parent but are still referenced by Unloop until
889       // the Unloop object is deleted.
890       changeLoopFor(BB, nullptr);
891     }
892 
893     // Remove the loop from the top-level LoopInfo object.
894     for (iterator I = begin();; ++I) {
895       assert(I != end() && "Couldn't find loop");
896       if (*I == Unloop) {
897         removeLoop(I);
898         break;
899       }
900     }
901 
902     // Move all of the subloops to the top-level.
903     while (!Unloop->isInnermost())
904       addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
905 
906     return;
907   }
908 
909   // Update the parent loop for all blocks within the loop. Blocks within
910   // subloops will not change parents.
911   UnloopUpdater Updater(Unloop, this);
912   Updater.updateBlockParents();
913 
914   // Remove blocks from former ancestor loops.
915   Updater.removeBlocksFromAncestors();
916 
917   // Add direct subloops as children in their new parent loop.
918   Updater.updateSubloopParents();
919 
920   // Remove unloop from its parent loop.
921   Loop *ParentLoop = Unloop->getParentLoop();
922   for (Loop::iterator I = ParentLoop->begin();; ++I) {
923     assert(I != ParentLoop->end() && "Couldn't find loop");
924     if (*I == Unloop) {
925       ParentLoop->removeChildLoop(I);
926       break;
927     }
928   }
929 }
930 
931 bool
932 LoopInfo::wouldBeOutOfLoopUseRequiringLCSSA(const Value *V,
933                                             const BasicBlock *ExitBB) const {
934   if (V->getType()->isTokenTy())
935     // We can't form PHIs of token type, so the definition of LCSSA excludes
936     // values of that type.
937     return false;
938 
939   const Instruction *I = dyn_cast<Instruction>(V);
940   if (!I)
941     return false;
942   const Loop *L = getLoopFor(I->getParent());
943   if (!L)
944     return false;
945   if (L->contains(ExitBB))
946     // Could be an exit bb of a subloop and contained in defining loop
947     return false;
948 
949   // We found a (new) out-of-loop use location, for a value defined in-loop.
950   // (Note that because of LCSSA, we don't have to account for values defined
951   // in sibling loops.  Such values will have LCSSA phis of their own in the
952   // common parent loop.)
953   return true;
954 }
955 
956 AnalysisKey LoopAnalysis::Key;
957 
958 LoopInfo LoopAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
959   // FIXME: Currently we create a LoopInfo from scratch for every function.
960   // This may prove to be too wasteful due to deallocating and re-allocating
961   // memory each time for the underlying map and vector datastructures. At some
962   // point it may prove worthwhile to use a freelist and recycle LoopInfo
963   // objects. I don't want to add that kind of complexity until the scope of
964   // the problem is better understood.
965   LoopInfo LI;
966   LI.analyze(AM.getResult<DominatorTreeAnalysis>(F));
967   return LI;
968 }
969 
970 PreservedAnalyses LoopPrinterPass::run(Function &F,
971                                        FunctionAnalysisManager &AM) {
972   AM.getResult<LoopAnalysis>(F).print(OS);
973   return PreservedAnalyses::all();
974 }
975 
976 void llvm::printLoop(Loop &L, raw_ostream &OS, const std::string &Banner) {
977 
978   if (forcePrintModuleIR()) {
979     // handling -print-module-scope
980     OS << Banner << " (loop: ";
981     L.getHeader()->printAsOperand(OS, false);
982     OS << ")\n";
983 
984     // printing whole module
985     OS << *L.getHeader()->getModule();
986     return;
987   }
988 
989   OS << Banner;
990 
991   auto *PreHeader = L.getLoopPreheader();
992   if (PreHeader) {
993     OS << "\n; Preheader:";
994     PreHeader->print(OS);
995     OS << "\n; Loop:";
996   }
997 
998   for (auto *Block : L.blocks())
999     if (Block)
1000       Block->print(OS);
1001     else
1002       OS << "Printing <null> block";
1003 
1004   SmallVector<BasicBlock *, 8> ExitBlocks;
1005   L.getExitBlocks(ExitBlocks);
1006   if (!ExitBlocks.empty()) {
1007     OS << "\n; Exit blocks";
1008     for (auto *Block : ExitBlocks)
1009       if (Block)
1010         Block->print(OS);
1011       else
1012         OS << "Printing <null> block";
1013   }
1014 }
1015 
1016 MDNode *llvm::findOptionMDForLoopID(MDNode *LoopID, StringRef Name) {
1017   // No loop metadata node, no loop properties.
1018   if (!LoopID)
1019     return nullptr;
1020 
1021   // First operand should refer to the metadata node itself, for legacy reasons.
1022   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1023   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1024 
1025   // Iterate over the metdata node operands and look for MDString metadata.
1026   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
1027     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1028     if (!MD || MD->getNumOperands() < 1)
1029       continue;
1030     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1031     if (!S)
1032       continue;
1033     // Return the operand node if MDString holds expected metadata.
1034     if (Name.equals(S->getString()))
1035       return MD;
1036   }
1037 
1038   // Loop property not found.
1039   return nullptr;
1040 }
1041 
1042 MDNode *llvm::findOptionMDForLoop(const Loop *TheLoop, StringRef Name) {
1043   return findOptionMDForLoopID(TheLoop->getLoopID(), Name);
1044 }
1045 
1046 /// Find string metadata for loop
1047 ///
1048 /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
1049 /// operand or null otherwise.  If the string metadata is not found return
1050 /// Optional's not-a-value.
1051 Optional<const MDOperand *> llvm::findStringMetadataForLoop(const Loop *TheLoop,
1052                                                             StringRef Name) {
1053   MDNode *MD = findOptionMDForLoop(TheLoop, Name);
1054   if (!MD)
1055     return None;
1056   switch (MD->getNumOperands()) {
1057   case 1:
1058     return nullptr;
1059   case 2:
1060     return &MD->getOperand(1);
1061   default:
1062     llvm_unreachable("loop metadata has 0 or 1 operand");
1063   }
1064 }
1065 
1066 Optional<bool> llvm::getOptionalBoolLoopAttribute(const Loop *TheLoop,
1067                                                   StringRef Name) {
1068   MDNode *MD = findOptionMDForLoop(TheLoop, Name);
1069   if (!MD)
1070     return None;
1071   switch (MD->getNumOperands()) {
1072   case 1:
1073     // When the value is absent it is interpreted as 'attribute set'.
1074     return true;
1075   case 2:
1076     if (ConstantInt *IntMD =
1077             mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get()))
1078       return IntMD->getZExtValue();
1079     return true;
1080   }
1081   llvm_unreachable("unexpected number of options");
1082 }
1083 
1084 bool llvm::getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) {
1085   return getOptionalBoolLoopAttribute(TheLoop, Name).value_or(false);
1086 }
1087 
1088 llvm::Optional<int> llvm::getOptionalIntLoopAttribute(const Loop *TheLoop,
1089                                                       StringRef Name) {
1090   const MDOperand *AttrMD =
1091       findStringMetadataForLoop(TheLoop, Name).value_or(nullptr);
1092   if (!AttrMD)
1093     return None;
1094 
1095   ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
1096   if (!IntMD)
1097     return None;
1098 
1099   return IntMD->getSExtValue();
1100 }
1101 
1102 int llvm::getIntLoopAttribute(const Loop *TheLoop, StringRef Name,
1103                               int Default) {
1104   return getOptionalIntLoopAttribute(TheLoop, Name).value_or(Default);
1105 }
1106 
1107 bool llvm::isFinite(const Loop *L) {
1108   return L->getHeader()->getParent()->willReturn();
1109 }
1110 
1111 static const char *LLVMLoopMustProgress = "llvm.loop.mustprogress";
1112 
1113 bool llvm::hasMustProgress(const Loop *L) {
1114   return getBooleanLoopAttribute(L, LLVMLoopMustProgress);
1115 }
1116 
1117 bool llvm::isMustProgress(const Loop *L) {
1118   return L->getHeader()->getParent()->mustProgress() || hasMustProgress(L);
1119 }
1120 
1121 bool llvm::isValidAsAccessGroup(MDNode *Node) {
1122   return Node->getNumOperands() == 0 && Node->isDistinct();
1123 }
1124 
1125 MDNode *llvm::makePostTransformationMetadata(LLVMContext &Context,
1126                                              MDNode *OrigLoopID,
1127                                              ArrayRef<StringRef> RemovePrefixes,
1128                                              ArrayRef<MDNode *> AddAttrs) {
1129   // First remove any existing loop metadata related to this transformation.
1130   SmallVector<Metadata *, 4> MDs;
1131 
1132   // Reserve first location for self reference to the LoopID metadata node.
1133   MDs.push_back(nullptr);
1134 
1135   // Remove metadata for the transformation that has been applied or that became
1136   // outdated.
1137   if (OrigLoopID) {
1138     for (unsigned i = 1, ie = OrigLoopID->getNumOperands(); i < ie; ++i) {
1139       bool IsVectorMetadata = false;
1140       Metadata *Op = OrigLoopID->getOperand(i);
1141       if (MDNode *MD = dyn_cast<MDNode>(Op)) {
1142         const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1143         if (S)
1144           IsVectorMetadata =
1145               llvm::any_of(RemovePrefixes, [S](StringRef Prefix) -> bool {
1146                 return S->getString().startswith(Prefix);
1147               });
1148       }
1149       if (!IsVectorMetadata)
1150         MDs.push_back(Op);
1151     }
1152   }
1153 
1154   // Add metadata to avoid reapplying a transformation, such as
1155   // llvm.loop.unroll.disable and llvm.loop.isvectorized.
1156   MDs.append(AddAttrs.begin(), AddAttrs.end());
1157 
1158   MDNode *NewLoopID = MDNode::getDistinct(Context, MDs);
1159   // Replace the temporary node with a self-reference.
1160   NewLoopID->replaceOperandWith(0, NewLoopID);
1161   return NewLoopID;
1162 }
1163 
1164 //===----------------------------------------------------------------------===//
1165 // LoopInfo implementation
1166 //
1167 
1168 LoopInfoWrapperPass::LoopInfoWrapperPass() : FunctionPass(ID) {
1169   initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry());
1170 }
1171 
1172 char LoopInfoWrapperPass::ID = 0;
1173 INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
1174                       true, true)
1175 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1176 INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
1177                     true, true)
1178 
1179 bool LoopInfoWrapperPass::runOnFunction(Function &) {
1180   releaseMemory();
1181   LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
1182   return false;
1183 }
1184 
1185 void LoopInfoWrapperPass::verifyAnalysis() const {
1186   // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
1187   // function each time verifyAnalysis is called is very expensive. The
1188   // -verify-loop-info option can enable this. In order to perform some
1189   // checking by default, LoopPass has been taught to call verifyLoop manually
1190   // during loop pass sequences.
1191   if (VerifyLoopInfo) {
1192     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1193     LI.verify(DT);
1194   }
1195 }
1196 
1197 void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1198   AU.setPreservesAll();
1199   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
1200 }
1201 
1202 void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
1203   LI.print(OS);
1204 }
1205 
1206 PreservedAnalyses LoopVerifierPass::run(Function &F,
1207                                         FunctionAnalysisManager &AM) {
1208   LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
1209   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1210   LI.verify(DT);
1211   return PreservedAnalyses::all();
1212 }
1213 
1214 //===----------------------------------------------------------------------===//
1215 // LoopBlocksDFS implementation
1216 //
1217 
1218 /// Traverse the loop blocks and store the DFS result.
1219 /// Useful for clients that just want the final DFS result and don't need to
1220 /// visit blocks during the initial traversal.
1221 void LoopBlocksDFS::perform(LoopInfo *LI) {
1222   LoopBlocksTraversal Traversal(*this, LI);
1223   for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
1224                                         POE = Traversal.end();
1225        POI != POE; ++POI)
1226     ;
1227 }
1228