1f22ef01cSRoman Divacky //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This file defines the LoopInfo class that is used to identify natural loops
11f22ef01cSRoman Divacky // and determine the loop depth of various nodes of the CFG.  Note that the
12f22ef01cSRoman Divacky // loops identified may actually be several natural loops that share the same
13f22ef01cSRoman Divacky // header node... not just a single natural loop.
14f22ef01cSRoman Divacky //
15f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
16f22ef01cSRoman Divacky 
17f22ef01cSRoman Divacky #include "llvm/Analysis/LoopInfo.h"
18139f7f9bSDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
192cab237bSDimitry Andric #include "llvm/ADT/ScopeExit.h"
20139f7f9bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
217ae0e2c9SDimitry Andric #include "llvm/Analysis/LoopInfoImpl.h"
226122f3e6SDimitry Andric #include "llvm/Analysis/LoopIterator.h"
23dff0c46cSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
244ba319b5SDimitry Andric #include "llvm/Config/llvm-config.h"
2591bc56edSDimitry Andric #include "llvm/IR/CFG.h"
26139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
273ca95b02SDimitry Andric #include "llvm/IR/DebugLoc.h"
2891bc56edSDimitry Andric #include "llvm/IR/Dominators.h"
29*b5893f02SDimitry Andric #include "llvm/IR/IRPrintingPasses.h"
30139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
3139d628a0SDimitry Andric #include "llvm/IR/LLVMContext.h"
32139f7f9bSDimitry Andric #include "llvm/IR/Metadata.h"
33ff0cc061SDimitry Andric #include "llvm/IR/PassManager.h"
34f22ef01cSRoman Divacky #include "llvm/Support/CommandLine.h"
35f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
36ff0cc061SDimitry Andric #include "llvm/Support/raw_ostream.h"
37f22ef01cSRoman Divacky #include <algorithm>
38f22ef01cSRoman Divacky using namespace llvm;
39f22ef01cSRoman Divacky 
407ae0e2c9SDimitry Andric // Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
417ae0e2c9SDimitry Andric template class llvm::LoopBase<BasicBlock, Loop>;
427ae0e2c9SDimitry Andric template class llvm::LoopInfoBase<BasicBlock, Loop>;
437ae0e2c9SDimitry Andric 
44f22ef01cSRoman Divacky // Always verify loopinfo if expensive checking is enabled.
453ca95b02SDimitry Andric #ifdef EXPENSIVE_CHECKS
467a7e6055SDimitry Andric bool llvm::VerifyLoopInfo = true;
47f22ef01cSRoman Divacky #else
487a7e6055SDimitry Andric bool llvm::VerifyLoopInfo = false;
49f22ef01cSRoman Divacky #endif
50f22ef01cSRoman Divacky static cl::opt<bool, true>
51f22ef01cSRoman Divacky     VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
522cab237bSDimitry Andric                     cl::Hidden, cl::desc("Verify loop info (time consuming)"));
53f22ef01cSRoman Divacky 
54f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
55f22ef01cSRoman Divacky // Loop implementation
56f22ef01cSRoman Divacky //
57f22ef01cSRoman Divacky 
isLoopInvariant(const Value * V) const58ff0cc061SDimitry Andric bool Loop::isLoopInvariant(const Value *V) const {
59ff0cc061SDimitry Andric   if (const Instruction *I = dyn_cast<Instruction>(V))
602754fe60SDimitry Andric     return !contains(I);
61f22ef01cSRoman Divacky   return true; // All non-instructions are loop invariant
62f22ef01cSRoman Divacky }
63f22ef01cSRoman Divacky 
hasLoopInvariantOperands(const Instruction * I) const64ff0cc061SDimitry Andric bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
65ff0cc061SDimitry Andric   return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
66f22ef01cSRoman Divacky }
67f22ef01cSRoman Divacky 
makeLoopInvariant(Value * V,bool & Changed,Instruction * InsertPt) const68f22ef01cSRoman Divacky bool Loop::makeLoopInvariant(Value *V, bool &Changed,
69f22ef01cSRoman Divacky                              Instruction *InsertPt) const {
70f22ef01cSRoman Divacky   if (Instruction *I = dyn_cast<Instruction>(V))
71f22ef01cSRoman Divacky     return makeLoopInvariant(I, Changed, InsertPt);
72f22ef01cSRoman Divacky   return true; // All non-instructions are loop-invariant.
73f22ef01cSRoman Divacky }
74f22ef01cSRoman Divacky 
makeLoopInvariant(Instruction * I,bool & Changed,Instruction * InsertPt) const75f22ef01cSRoman Divacky bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
76f22ef01cSRoman Divacky                              Instruction *InsertPt) const {
77f22ef01cSRoman Divacky   // Test if the value is already loop-invariant.
78f22ef01cSRoman Divacky   if (isLoopInvariant(I))
79f22ef01cSRoman Divacky     return true;
80dff0c46cSDimitry Andric   if (!isSafeToSpeculativelyExecute(I))
81f22ef01cSRoman Divacky     return false;
82f22ef01cSRoman Divacky   if (I->mayReadFromMemory())
83f22ef01cSRoman Divacky     return false;
847d523365SDimitry Andric   // EH block instructions are immobile.
857d523365SDimitry Andric   if (I->isEHPad())
866122f3e6SDimitry Andric     return false;
87f22ef01cSRoman Divacky   // Determine the insertion point, unless one was given.
88f22ef01cSRoman Divacky   if (!InsertPt) {
89f22ef01cSRoman Divacky     BasicBlock *Preheader = getLoopPreheader();
90f22ef01cSRoman Divacky     // Without a preheader, hoisting is not feasible.
91f22ef01cSRoman Divacky     if (!Preheader)
92f22ef01cSRoman Divacky       return false;
93f22ef01cSRoman Divacky     InsertPt = Preheader->getTerminator();
94f22ef01cSRoman Divacky   }
95f22ef01cSRoman Divacky   // Don't hoist instructions with loop-variant operands.
963ca95b02SDimitry Andric   for (Value *Operand : I->operands())
973ca95b02SDimitry Andric     if (!makeLoopInvariant(Operand, Changed, InsertPt))
98f22ef01cSRoman Divacky       return false;
992754fe60SDimitry Andric 
100f22ef01cSRoman Divacky   // Hoist.
101f22ef01cSRoman Divacky   I->moveBefore(InsertPt);
1027d523365SDimitry Andric 
1037d523365SDimitry Andric   // There is possibility of hoisting this instruction above some arbitrary
1047d523365SDimitry Andric   // condition. Any metadata defined on it can be control dependent on this
1057d523365SDimitry Andric   // condition. Conservatively strip it here so that we don't give any wrong
1067d523365SDimitry Andric   // information to the optimizer.
1077d523365SDimitry Andric   I->dropUnknownNonDebugMetadata();
1087d523365SDimitry Andric 
109f22ef01cSRoman Divacky   Changed = true;
110f22ef01cSRoman Divacky   return true;
111f22ef01cSRoman Divacky }
112f22ef01cSRoman Divacky 
getCanonicalInductionVariable() const113f22ef01cSRoman Divacky PHINode *Loop::getCanonicalInductionVariable() const {
114f22ef01cSRoman Divacky   BasicBlock *H = getHeader();
115f22ef01cSRoman Divacky 
11691bc56edSDimitry Andric   BasicBlock *Incoming = nullptr, *Backedge = nullptr;
117e580952dSDimitry Andric   pred_iterator PI = pred_begin(H);
1182cab237bSDimitry Andric   assert(PI != pred_end(H) && "Loop must have at least one backedge!");
119f22ef01cSRoman Divacky   Backedge = *PI++;
1202cab237bSDimitry Andric   if (PI == pred_end(H))
1212cab237bSDimitry Andric     return nullptr; // dead loop
122f22ef01cSRoman Divacky   Incoming = *PI++;
1232cab237bSDimitry Andric   if (PI != pred_end(H))
1242cab237bSDimitry Andric     return nullptr; // multiple backedges?
125f22ef01cSRoman Divacky 
126f22ef01cSRoman Divacky   if (contains(Incoming)) {
127f22ef01cSRoman Divacky     if (contains(Backedge))
12891bc56edSDimitry Andric       return nullptr;
129f22ef01cSRoman Divacky     std::swap(Incoming, Backedge);
130f22ef01cSRoman Divacky   } else if (!contains(Backedge))
13191bc56edSDimitry Andric     return nullptr;
132f22ef01cSRoman Divacky 
133f22ef01cSRoman Divacky   // Loop over all of the PHI nodes, looking for a canonical indvar.
134f22ef01cSRoman Divacky   for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
135f22ef01cSRoman Divacky     PHINode *PN = cast<PHINode>(I);
136f22ef01cSRoman Divacky     if (ConstantInt *CI =
137f22ef01cSRoman Divacky             dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
138c4394386SDimitry Andric       if (CI->isZero())
139f22ef01cSRoman Divacky         if (Instruction *Inc =
140f22ef01cSRoman Divacky                 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
1412cab237bSDimitry Andric           if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
142f22ef01cSRoman Divacky             if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
143c4394386SDimitry Andric               if (CI->isOne())
144f22ef01cSRoman Divacky                 return PN;
145f22ef01cSRoman Divacky   }
14691bc56edSDimitry Andric   return nullptr;
147f22ef01cSRoman Divacky }
148f22ef01cSRoman Divacky 
149d88c1a5aSDimitry Andric // Check that 'BB' doesn't have any uses outside of the 'L'
isBlockInLCSSAForm(const Loop & L,const BasicBlock & BB,DominatorTree & DT)150d88c1a5aSDimitry Andric static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB,
151d88c1a5aSDimitry Andric                                DominatorTree &DT) {
152d88c1a5aSDimitry Andric   for (const Instruction &I : BB) {
1537d523365SDimitry Andric     // Tokens can't be used in PHI nodes and live-out tokens prevent loop
1547d523365SDimitry Andric     // optimizations, so for the purposes of considered LCSSA form, we
1557d523365SDimitry Andric     // can ignore them.
1563ca95b02SDimitry Andric     if (I.getType()->isTokenTy())
1577d523365SDimitry Andric       continue;
1587d523365SDimitry Andric 
159d88c1a5aSDimitry Andric     for (const Use &U : I.uses()) {
160d88c1a5aSDimitry Andric       const Instruction *UI = cast<Instruction>(U.getUser());
161d88c1a5aSDimitry Andric       const BasicBlock *UserBB = UI->getParent();
162d88c1a5aSDimitry Andric       if (const PHINode *P = dyn_cast<PHINode>(UI))
16391bc56edSDimitry Andric         UserBB = P->getIncomingBlock(U);
164f22ef01cSRoman Divacky 
165f22ef01cSRoman Divacky       // Check the current block, as a fast-path, before checking whether
166f22ef01cSRoman Divacky       // the use is anywhere in the loop.  Most values are used in the same
167f22ef01cSRoman Divacky       // block they are defined in.  Also, blocks not reachable from the
168f22ef01cSRoman Divacky       // entry are special; uses in them don't need to go through PHIs.
169d88c1a5aSDimitry Andric       if (UserBB != &BB && !L.contains(UserBB) &&
170f22ef01cSRoman Divacky           DT.isReachableFromEntry(UserBB))
171f22ef01cSRoman Divacky         return false;
172f22ef01cSRoman Divacky     }
173f22ef01cSRoman Divacky   }
174f22ef01cSRoman Divacky   return true;
175f22ef01cSRoman Divacky }
176f22ef01cSRoman Divacky 
isLCSSAForm(DominatorTree & DT) const177d88c1a5aSDimitry Andric bool Loop::isLCSSAForm(DominatorTree &DT) const {
178d88c1a5aSDimitry Andric   // For each block we check that it doesn't have any uses outside of this loop.
179d88c1a5aSDimitry Andric   return all_of(this->blocks(), [&](const BasicBlock *BB) {
180d88c1a5aSDimitry Andric     return isBlockInLCSSAForm(*this, *BB, DT);
181d88c1a5aSDimitry Andric   });
182d88c1a5aSDimitry Andric }
1837d523365SDimitry Andric 
isRecursivelyLCSSAForm(DominatorTree & DT,const LoopInfo & LI) const184d88c1a5aSDimitry Andric bool Loop::isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const {
18524e2fe98SDimitry Andric   // For each block we check that it doesn't have any uses outside of its
18624e2fe98SDimitry Andric   // innermost loop. This process will transitively guarantee that the current
18724e2fe98SDimitry Andric   // loop and all of the nested loops are in LCSSA form.
188d88c1a5aSDimitry Andric   return all_of(this->blocks(), [&](const BasicBlock *BB) {
189d88c1a5aSDimitry Andric     return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT);
1907d523365SDimitry Andric   });
1917d523365SDimitry Andric }
1927d523365SDimitry Andric 
isLoopSimplifyForm() const193f22ef01cSRoman Divacky bool Loop::isLoopSimplifyForm() const {
194f22ef01cSRoman Divacky   // Normal-form loops have a preheader, a single backedge, and all of their
195f22ef01cSRoman Divacky   // exits have all their predecessors inside the loop.
196f22ef01cSRoman Divacky   return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
197f22ef01cSRoman Divacky }
198f22ef01cSRoman Divacky 
1993ca95b02SDimitry Andric // Routines that reform the loop CFG and split edges often fail on indirectbr.
isSafeToClone() const200dff0c46cSDimitry Andric bool Loop::isSafeToClone() const {
201139f7f9bSDimitry Andric   // Return false if any loop blocks contain indirectbrs, or there are any calls
202139f7f9bSDimitry Andric   // to noduplicate functions.
2033ca95b02SDimitry Andric   for (BasicBlock *BB : this->blocks()) {
2043ca95b02SDimitry Andric     if (isa<IndirectBrInst>(BB->getTerminator()))
205dff0c46cSDimitry Andric       return false;
206f785676fSDimitry Andric 
2073ca95b02SDimitry Andric     for (Instruction &I : *BB)
2083ca95b02SDimitry Andric       if (auto CS = CallSite(&I))
2093ca95b02SDimitry Andric         if (CS.cannotDuplicate())
210139f7f9bSDimitry Andric           return false;
211dff0c46cSDimitry Andric   }
212dff0c46cSDimitry Andric   return true;
213dff0c46cSDimitry Andric }
214dff0c46cSDimitry Andric 
getLoopID() const215f785676fSDimitry Andric MDNode *Loop::getLoopID() const {
21691bc56edSDimitry Andric   MDNode *LoopID = nullptr;
217f785676fSDimitry Andric 
218*b5893f02SDimitry Andric   // Go through the latch blocks and check the terminator for the metadata.
219*b5893f02SDimitry Andric   SmallVector<BasicBlock *, 4> LatchesBlocks;
220*b5893f02SDimitry Andric   getLoopLatches(LatchesBlocks);
221*b5893f02SDimitry Andric   for (BasicBlock *BB : LatchesBlocks) {
222*b5893f02SDimitry Andric     Instruction *TI = BB->getTerminator();
223*b5893f02SDimitry Andric     MDNode *MD = TI->getMetadata(LLVMContext::MD_loop);
224*b5893f02SDimitry Andric 
225f785676fSDimitry Andric     if (!MD)
22691bc56edSDimitry Andric       return nullptr;
227f785676fSDimitry Andric 
228f785676fSDimitry Andric     if (!LoopID)
229f785676fSDimitry Andric       LoopID = MD;
230f785676fSDimitry Andric     else if (MD != LoopID)
23191bc56edSDimitry Andric       return nullptr;
232f785676fSDimitry Andric   }
233f785676fSDimitry Andric   if (!LoopID || LoopID->getNumOperands() == 0 ||
234f785676fSDimitry Andric       LoopID->getOperand(0) != LoopID)
23591bc56edSDimitry Andric     return nullptr;
236f785676fSDimitry Andric   return LoopID;
237f785676fSDimitry Andric }
238f785676fSDimitry Andric 
setLoopID(MDNode * LoopID) const239f785676fSDimitry Andric void Loop::setLoopID(MDNode *LoopID) const {
240*b5893f02SDimitry Andric   assert((!LoopID || LoopID->getNumOperands() > 0) &&
241*b5893f02SDimitry Andric          "Loop ID needs at least one operand");
242*b5893f02SDimitry Andric   assert((!LoopID || LoopID->getOperand(0) == LoopID) &&
243*b5893f02SDimitry Andric          "Loop ID should refer to itself");
244f785676fSDimitry Andric 
245f785676fSDimitry Andric   BasicBlock *H = getHeader();
2463ca95b02SDimitry Andric   for (BasicBlock *BB : this->blocks()) {
247*b5893f02SDimitry Andric     Instruction *TI = BB->getTerminator();
248*b5893f02SDimitry Andric     for (BasicBlock *Successor : successors(TI)) {
249*b5893f02SDimitry Andric       if (Successor == H) {
2503ca95b02SDimitry Andric         TI->setMetadata(LLVMContext::MD_loop, LoopID);
251*b5893f02SDimitry Andric         break;
252*b5893f02SDimitry Andric       }
253f785676fSDimitry Andric     }
254f785676fSDimitry Andric   }
255f785676fSDimitry Andric }
256f785676fSDimitry Andric 
setLoopAlreadyUnrolled()2572cab237bSDimitry Andric void Loop::setLoopAlreadyUnrolled() {
2582cab237bSDimitry Andric   MDNode *LoopID = getLoopID();
2592cab237bSDimitry Andric   // First remove any existing loop unrolling metadata.
2602cab237bSDimitry Andric   SmallVector<Metadata *, 4> MDs;
2612cab237bSDimitry Andric   // Reserve first location for self reference to the LoopID metadata node.
2622cab237bSDimitry Andric   MDs.push_back(nullptr);
2632cab237bSDimitry Andric 
2642cab237bSDimitry Andric   if (LoopID) {
2652cab237bSDimitry Andric     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
2662cab237bSDimitry Andric       bool IsUnrollMetadata = false;
2672cab237bSDimitry Andric       MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
2682cab237bSDimitry Andric       if (MD) {
2692cab237bSDimitry Andric         const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
2702cab237bSDimitry Andric         IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
2712cab237bSDimitry Andric       }
2722cab237bSDimitry Andric       if (!IsUnrollMetadata)
2732cab237bSDimitry Andric         MDs.push_back(LoopID->getOperand(i));
2742cab237bSDimitry Andric     }
2752cab237bSDimitry Andric   }
2762cab237bSDimitry Andric 
2772cab237bSDimitry Andric   // Add unroll(disable) metadata to disable future unrolling.
2782cab237bSDimitry Andric   LLVMContext &Context = getHeader()->getContext();
2792cab237bSDimitry Andric   SmallVector<Metadata *, 1> DisableOperands;
2802cab237bSDimitry Andric   DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
2812cab237bSDimitry Andric   MDNode *DisableNode = MDNode::get(Context, DisableOperands);
2822cab237bSDimitry Andric   MDs.push_back(DisableNode);
2832cab237bSDimitry Andric 
2842cab237bSDimitry Andric   MDNode *NewLoopID = MDNode::get(Context, MDs);
2852cab237bSDimitry Andric   // Set operand 0 to refer to the loop id itself.
2862cab237bSDimitry Andric   NewLoopID->replaceOperandWith(0, NewLoopID);
2872cab237bSDimitry Andric   setLoopID(NewLoopID);
2882cab237bSDimitry Andric }
2892cab237bSDimitry Andric 
isAnnotatedParallel() const290139f7f9bSDimitry Andric bool Loop::isAnnotatedParallel() const {
2913ca95b02SDimitry Andric   MDNode *DesiredLoopIdMetadata = getLoopID();
292139f7f9bSDimitry Andric 
2933ca95b02SDimitry Andric   if (!DesiredLoopIdMetadata)
294139f7f9bSDimitry Andric     return false;
295139f7f9bSDimitry Andric 
296*b5893f02SDimitry Andric   MDNode *ParallelAccesses =
297*b5893f02SDimitry Andric       findOptionMDForLoop(this, "llvm.loop.parallel_accesses");
298*b5893f02SDimitry Andric   SmallPtrSet<MDNode *, 4>
299*b5893f02SDimitry Andric       ParallelAccessGroups; // For scalable 'contains' check.
300*b5893f02SDimitry Andric   if (ParallelAccesses) {
301*b5893f02SDimitry Andric     for (const MDOperand &MD : drop_begin(ParallelAccesses->operands(), 1)) {
302*b5893f02SDimitry Andric       MDNode *AccGroup = cast<MDNode>(MD.get());
303*b5893f02SDimitry Andric       assert(isValidAsAccessGroup(AccGroup) &&
304*b5893f02SDimitry Andric              "List item must be an access group");
305*b5893f02SDimitry Andric       ParallelAccessGroups.insert(AccGroup);
306*b5893f02SDimitry Andric     }
307*b5893f02SDimitry Andric   }
308*b5893f02SDimitry Andric 
309139f7f9bSDimitry Andric   // The loop branch contains the parallel loop metadata. In order to ensure
310139f7f9bSDimitry Andric   // that any parallel-loop-unaware optimization pass hasn't added loop-carried
311139f7f9bSDimitry Andric   // dependencies (thus converted the loop back to a sequential loop), check
312*b5893f02SDimitry Andric   // that all the memory instructions in the loop belong to an access group that
313*b5893f02SDimitry Andric   // is parallel to this loop.
3143ca95b02SDimitry Andric   for (BasicBlock *BB : this->blocks()) {
3153ca95b02SDimitry Andric     for (Instruction &I : *BB) {
3163ca95b02SDimitry Andric       if (!I.mayReadOrWriteMemory())
317139f7f9bSDimitry Andric         continue;
318139f7f9bSDimitry Andric 
319*b5893f02SDimitry Andric       if (MDNode *AccessGroup = I.getMetadata(LLVMContext::MD_access_group)) {
320*b5893f02SDimitry Andric         auto ContainsAccessGroup = [&ParallelAccessGroups](MDNode *AG) -> bool {
321*b5893f02SDimitry Andric           if (AG->getNumOperands() == 0) {
322*b5893f02SDimitry Andric             assert(isValidAsAccessGroup(AG) && "Item must be an access group");
323*b5893f02SDimitry Andric             return ParallelAccessGroups.count(AG);
324*b5893f02SDimitry Andric           }
325*b5893f02SDimitry Andric 
326*b5893f02SDimitry Andric           for (const MDOperand &AccessListItem : AG->operands()) {
327*b5893f02SDimitry Andric             MDNode *AccGroup = cast<MDNode>(AccessListItem.get());
328*b5893f02SDimitry Andric             assert(isValidAsAccessGroup(AccGroup) &&
329*b5893f02SDimitry Andric                    "List item must be an access group");
330*b5893f02SDimitry Andric             if (ParallelAccessGroups.count(AccGroup))
331*b5893f02SDimitry Andric               return true;
332*b5893f02SDimitry Andric           }
333*b5893f02SDimitry Andric           return false;
334*b5893f02SDimitry Andric         };
335*b5893f02SDimitry Andric 
336*b5893f02SDimitry Andric         if (ContainsAccessGroup(AccessGroup))
337*b5893f02SDimitry Andric           continue;
338*b5893f02SDimitry Andric       }
339*b5893f02SDimitry Andric 
340139f7f9bSDimitry Andric       // The memory instruction can refer to the loop identifier metadata
341139f7f9bSDimitry Andric       // directly or indirectly through another list metadata (in case of
342139f7f9bSDimitry Andric       // nested parallel loops). The loop identifier metadata refers to
343139f7f9bSDimitry Andric       // itself so we can check both cases with the same routine.
3443ca95b02SDimitry Andric       MDNode *LoopIdMD =
3453ca95b02SDimitry Andric           I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
346f785676fSDimitry Andric 
3473ca95b02SDimitry Andric       if (!LoopIdMD)
348f785676fSDimitry Andric         return false;
349f785676fSDimitry Andric 
3503ca95b02SDimitry Andric       bool LoopIdMDFound = false;
3513ca95b02SDimitry Andric       for (const MDOperand &MDOp : LoopIdMD->operands()) {
3523ca95b02SDimitry Andric         if (MDOp == DesiredLoopIdMetadata) {
3533ca95b02SDimitry Andric           LoopIdMDFound = true;
354139f7f9bSDimitry Andric           break;
355139f7f9bSDimitry Andric         }
356139f7f9bSDimitry Andric       }
357139f7f9bSDimitry Andric 
3583ca95b02SDimitry Andric       if (!LoopIdMDFound)
359139f7f9bSDimitry Andric         return false;
360139f7f9bSDimitry Andric     }
361139f7f9bSDimitry Andric   }
362139f7f9bSDimitry Andric   return true;
363139f7f9bSDimitry Andric }
364139f7f9bSDimitry Andric 
getStartLoc() const3652cab237bSDimitry Andric DebugLoc Loop::getStartLoc() const { return getLocRange().getStart(); }
366d88c1a5aSDimitry Andric 
getLocRange() const367d88c1a5aSDimitry Andric Loop::LocRange Loop::getLocRange() const {
3683ca95b02SDimitry Andric   // If we have a debug location in the loop ID, then use it.
369d88c1a5aSDimitry Andric   if (MDNode *LoopID = getLoopID()) {
370d88c1a5aSDimitry Andric     DebugLoc Start;
371d88c1a5aSDimitry Andric     // We use the first DebugLoc in the header as the start location of the loop
372d88c1a5aSDimitry Andric     // and if there is a second DebugLoc in the header we use it as end location
373d88c1a5aSDimitry Andric     // of the loop.
374d88c1a5aSDimitry Andric     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
375d88c1a5aSDimitry Andric       if (DILocation *L = dyn_cast<DILocation>(LoopID->getOperand(i))) {
376d88c1a5aSDimitry Andric         if (!Start)
377d88c1a5aSDimitry Andric           Start = DebugLoc(L);
378d88c1a5aSDimitry Andric         else
379d88c1a5aSDimitry Andric           return LocRange(Start, DebugLoc(L));
380d88c1a5aSDimitry Andric       }
381d88c1a5aSDimitry Andric     }
382d88c1a5aSDimitry Andric 
383d88c1a5aSDimitry Andric     if (Start)
384d88c1a5aSDimitry Andric       return LocRange(Start);
385d88c1a5aSDimitry Andric   }
386139f7f9bSDimitry Andric 
3873ca95b02SDimitry Andric   // Try the pre-header first.
3883ca95b02SDimitry Andric   if (BasicBlock *PHeadBB = getLoopPreheader())
3893ca95b02SDimitry Andric     if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
390d88c1a5aSDimitry Andric       return LocRange(DL);
3913ca95b02SDimitry Andric 
3923ca95b02SDimitry Andric   // If we have no pre-header or there are no instructions with debug
3933ca95b02SDimitry Andric   // info in it, try the header.
3943ca95b02SDimitry Andric   if (BasicBlock *HeadBB = getHeader())
395d88c1a5aSDimitry Andric     return LocRange(HeadBB->getTerminator()->getDebugLoc());
3963ca95b02SDimitry Andric 
397d88c1a5aSDimitry Andric   return LocRange();
3983ca95b02SDimitry Andric }
3993ca95b02SDimitry Andric 
4003861d79fSDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const4012cab237bSDimitry Andric LLVM_DUMP_METHOD void Loop::dump() const { print(dbgs()); }
402d88c1a5aSDimitry Andric 
dumpVerbose() const403d88c1a5aSDimitry Andric LLVM_DUMP_METHOD void Loop::dumpVerbose() const {
404d88c1a5aSDimitry Andric   print(dbgs(), /*Depth=*/0, /*Verbose=*/true);
405d88c1a5aSDimitry Andric }
4063861d79fSDimitry Andric #endif
407f22ef01cSRoman Divacky 
408f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
4096122f3e6SDimitry Andric // UnloopUpdater implementation
4106122f3e6SDimitry Andric //
4116122f3e6SDimitry Andric 
4126122f3e6SDimitry Andric namespace {
4136122f3e6SDimitry Andric /// Find the new parent loop for all blocks within the "unloop" whose last
4146122f3e6SDimitry Andric /// backedges has just been removed.
4156122f3e6SDimitry Andric class UnloopUpdater {
4163ca95b02SDimitry Andric   Loop &Unloop;
4176122f3e6SDimitry Andric   LoopInfo *LI;
4186122f3e6SDimitry Andric 
4196122f3e6SDimitry Andric   LoopBlocksDFS DFS;
4206122f3e6SDimitry Andric 
4216122f3e6SDimitry Andric   // Map unloop's immediate subloops to their nearest reachable parents. Nested
4226122f3e6SDimitry Andric   // loops within these subloops will not change parents. However, an immediate
4236122f3e6SDimitry Andric   // subloop's new parent will be the nearest loop reachable from either its own
4246122f3e6SDimitry Andric   // exits *or* any of its nested loop's exits.
4256122f3e6SDimitry Andric   DenseMap<Loop *, Loop *> SubloopParents;
4266122f3e6SDimitry Andric 
4276122f3e6SDimitry Andric   // Flag the presence of an irreducible backedge whose destination is a block
4286122f3e6SDimitry Andric   // directly contained by the original unloop.
4296122f3e6SDimitry Andric   bool FoundIB;
4306122f3e6SDimitry Andric 
4316122f3e6SDimitry Andric public:
UnloopUpdater(Loop * UL,LoopInfo * LInfo)4322cab237bSDimitry Andric   UnloopUpdater(Loop *UL, LoopInfo *LInfo)
4332cab237bSDimitry Andric       : Unloop(*UL), LI(LInfo), DFS(UL), FoundIB(false) {}
4346122f3e6SDimitry Andric 
4356122f3e6SDimitry Andric   void updateBlockParents();
4366122f3e6SDimitry Andric 
4376122f3e6SDimitry Andric   void removeBlocksFromAncestors();
4386122f3e6SDimitry Andric 
4396122f3e6SDimitry Andric   void updateSubloopParents();
4406122f3e6SDimitry Andric 
4416122f3e6SDimitry Andric protected:
4426122f3e6SDimitry Andric   Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
4436122f3e6SDimitry Andric };
4446122f3e6SDimitry Andric } // end anonymous namespace
4456122f3e6SDimitry Andric 
4463ca95b02SDimitry Andric /// Update the parent loop for all blocks that are directly contained within the
4473ca95b02SDimitry Andric /// original "unloop".
updateBlockParents()4486122f3e6SDimitry Andric void UnloopUpdater::updateBlockParents() {
4493ca95b02SDimitry Andric   if (Unloop.getNumBlocks()) {
4506122f3e6SDimitry Andric     // Perform a post order CFG traversal of all blocks within this loop,
451c4394386SDimitry Andric     // propagating the nearest loop from successors to predecessors.
4526122f3e6SDimitry Andric     LoopBlocksTraversal Traversal(DFS, LI);
4533ca95b02SDimitry Andric     for (BasicBlock *POI : Traversal) {
4546122f3e6SDimitry Andric 
4553ca95b02SDimitry Andric       Loop *L = LI->getLoopFor(POI);
4563ca95b02SDimitry Andric       Loop *NL = getNearestLoop(POI, L);
4576122f3e6SDimitry Andric 
4586122f3e6SDimitry Andric       if (NL != L) {
4596122f3e6SDimitry Andric         // For reducible loops, NL is now an ancestor of Unloop.
4603ca95b02SDimitry Andric         assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
4616122f3e6SDimitry Andric                "uninitialized successor");
4623ca95b02SDimitry Andric         LI->changeLoopFor(POI, NL);
4632cab237bSDimitry Andric       } else {
4646122f3e6SDimitry Andric         // Or the current block is part of a subloop, in which case its parent
4656122f3e6SDimitry Andric         // is unchanged.
4663ca95b02SDimitry Andric         assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
4676122f3e6SDimitry Andric       }
4686122f3e6SDimitry Andric     }
4696122f3e6SDimitry Andric   }
4706122f3e6SDimitry Andric   // Each irreducible loop within the unloop induces a round of iteration using
4716122f3e6SDimitry Andric   // the DFS result cached by Traversal.
4726122f3e6SDimitry Andric   bool Changed = FoundIB;
4736122f3e6SDimitry Andric   for (unsigned NIters = 0; Changed; ++NIters) {
4743ca95b02SDimitry Andric     assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
4756122f3e6SDimitry Andric 
4766122f3e6SDimitry Andric     // Iterate over the postorder list of blocks, propagating the nearest loop
4776122f3e6SDimitry Andric     // from successors to predecessors as before.
4786122f3e6SDimitry Andric     Changed = false;
4796122f3e6SDimitry Andric     for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
4802cab237bSDimitry Andric                                    POE = DFS.endPostorder();
4812cab237bSDimitry Andric          POI != POE; ++POI) {
4826122f3e6SDimitry Andric 
4836122f3e6SDimitry Andric       Loop *L = LI->getLoopFor(*POI);
4846122f3e6SDimitry Andric       Loop *NL = getNearestLoop(*POI, L);
4856122f3e6SDimitry Andric       if (NL != L) {
4863ca95b02SDimitry Andric         assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
4876122f3e6SDimitry Andric                "uninitialized successor");
4886122f3e6SDimitry Andric         LI->changeLoopFor(*POI, NL);
4896122f3e6SDimitry Andric         Changed = true;
4906122f3e6SDimitry Andric       }
4916122f3e6SDimitry Andric     }
4926122f3e6SDimitry Andric   }
4936122f3e6SDimitry Andric }
4946122f3e6SDimitry Andric 
4953ca95b02SDimitry Andric /// Remove unloop's blocks from all ancestors below their new parents.
removeBlocksFromAncestors()4966122f3e6SDimitry Andric void UnloopUpdater::removeBlocksFromAncestors() {
497dff0c46cSDimitry Andric   // Remove all unloop's blocks (including those in nested subloops) from
498dff0c46cSDimitry Andric   // ancestors below the new parent loop.
4992cab237bSDimitry Andric   for (Loop::block_iterator BI = Unloop.block_begin(), BE = Unloop.block_end();
5002cab237bSDimitry Andric        BI != BE; ++BI) {
501dff0c46cSDimitry Andric     Loop *OuterParent = LI->getLoopFor(*BI);
5023ca95b02SDimitry Andric     if (Unloop.contains(OuterParent)) {
5033ca95b02SDimitry Andric       while (OuterParent->getParentLoop() != &Unloop)
504dff0c46cSDimitry Andric         OuterParent = OuterParent->getParentLoop();
505dff0c46cSDimitry Andric       OuterParent = SubloopParents[OuterParent];
506dff0c46cSDimitry Andric     }
5076122f3e6SDimitry Andric     // Remove blocks from former Ancestors except Unloop itself which will be
5086122f3e6SDimitry Andric     // deleted.
5093ca95b02SDimitry Andric     for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
5106122f3e6SDimitry Andric          OldParent = OldParent->getParentLoop()) {
5116122f3e6SDimitry Andric       assert(OldParent && "new loop is not an ancestor of the original");
5126122f3e6SDimitry Andric       OldParent->removeBlockFromLoop(*BI);
5136122f3e6SDimitry Andric     }
5146122f3e6SDimitry Andric   }
5156122f3e6SDimitry Andric }
5166122f3e6SDimitry Andric 
5173ca95b02SDimitry Andric /// Update the parent loop for all subloops directly nested within unloop.
updateSubloopParents()5186122f3e6SDimitry Andric void UnloopUpdater::updateSubloopParents() {
5193ca95b02SDimitry Andric   while (!Unloop.empty()) {
5203ca95b02SDimitry Andric     Loop *Subloop = *std::prev(Unloop.end());
5213ca95b02SDimitry Andric     Unloop.removeChildLoop(std::prev(Unloop.end()));
5226122f3e6SDimitry Andric 
5236122f3e6SDimitry Andric     assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
5243861d79fSDimitry Andric     if (Loop *Parent = SubloopParents[Subloop])
5253861d79fSDimitry Andric       Parent->addChildLoop(Subloop);
5266122f3e6SDimitry Andric     else
5276122f3e6SDimitry Andric       LI->addTopLevelLoop(Subloop);
5286122f3e6SDimitry Andric   }
5296122f3e6SDimitry Andric }
5306122f3e6SDimitry Andric 
5313ca95b02SDimitry Andric /// Return the nearest parent loop among this block's successors. If a successor
5323ca95b02SDimitry Andric /// is a subloop header, consider its parent to be the nearest parent of the
5333ca95b02SDimitry Andric /// subloop's exits.
5346122f3e6SDimitry Andric ///
5356122f3e6SDimitry Andric /// For subloop blocks, simply update SubloopParents and return NULL.
getNearestLoop(BasicBlock * BB,Loop * BBLoop)5366122f3e6SDimitry Andric Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
5376122f3e6SDimitry Andric 
5386122f3e6SDimitry Andric   // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
5396122f3e6SDimitry Andric   // is considered uninitialized.
5406122f3e6SDimitry Andric   Loop *NearLoop = BBLoop;
5416122f3e6SDimitry Andric 
54291bc56edSDimitry Andric   Loop *Subloop = nullptr;
5433ca95b02SDimitry Andric   if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
5446122f3e6SDimitry Andric     Subloop = NearLoop;
5456122f3e6SDimitry Andric     // Find the subloop ancestor that is directly contained within Unloop.
5463ca95b02SDimitry Andric     while (Subloop->getParentLoop() != &Unloop) {
5476122f3e6SDimitry Andric       Subloop = Subloop->getParentLoop();
5486122f3e6SDimitry Andric       assert(Subloop && "subloop is not an ancestor of the original loop");
5496122f3e6SDimitry Andric     }
5506122f3e6SDimitry Andric     // Get the current nearest parent of the Subloop exits, initially Unloop.
551d88c1a5aSDimitry Andric     NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second;
5526122f3e6SDimitry Andric   }
5536122f3e6SDimitry Andric 
5546122f3e6SDimitry Andric   succ_iterator I = succ_begin(BB), E = succ_end(BB);
5556122f3e6SDimitry Andric   if (I == E) {
5566122f3e6SDimitry Andric     assert(!Subloop && "subloop blocks must have a successor");
55791bc56edSDimitry Andric     NearLoop = nullptr; // unloop blocks may now exit the function.
5586122f3e6SDimitry Andric   }
5596122f3e6SDimitry Andric   for (; I != E; ++I) {
5606122f3e6SDimitry Andric     if (*I == BB)
5616122f3e6SDimitry Andric       continue; // self loops are uninteresting
5626122f3e6SDimitry Andric 
5636122f3e6SDimitry Andric     Loop *L = LI->getLoopFor(*I);
5643ca95b02SDimitry Andric     if (L == &Unloop) {
5656122f3e6SDimitry Andric       // This successor has not been processed. This path must lead to an
5666122f3e6SDimitry Andric       // irreducible backedge.
5676122f3e6SDimitry Andric       assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
5686122f3e6SDimitry Andric       FoundIB = true;
5696122f3e6SDimitry Andric     }
5703ca95b02SDimitry Andric     if (L != &Unloop && Unloop.contains(L)) {
5716122f3e6SDimitry Andric       // Successor is in a subloop.
5726122f3e6SDimitry Andric       if (Subloop)
5736122f3e6SDimitry Andric         continue; // Branching within subloops. Ignore it.
5746122f3e6SDimitry Andric 
5756122f3e6SDimitry Andric       // BB branches from the original into a subloop header.
5763ca95b02SDimitry Andric       assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
5776122f3e6SDimitry Andric 
5786122f3e6SDimitry Andric       // Get the current nearest parent of the Subloop's exits.
5796122f3e6SDimitry Andric       L = SubloopParents[L];
5806122f3e6SDimitry Andric       // L could be Unloop if the only exit was an irreducible backedge.
5816122f3e6SDimitry Andric     }
5823ca95b02SDimitry Andric     if (L == &Unloop) {
5836122f3e6SDimitry Andric       continue;
5846122f3e6SDimitry Andric     }
5856122f3e6SDimitry Andric     // Handle critical edges from Unloop into a sibling loop.
5863ca95b02SDimitry Andric     if (L && !L->contains(&Unloop)) {
5876122f3e6SDimitry Andric       L = L->getParentLoop();
5886122f3e6SDimitry Andric     }
5896122f3e6SDimitry Andric     // Remember the nearest parent loop among successors or subloop exits.
5903ca95b02SDimitry Andric     if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
5916122f3e6SDimitry Andric       NearLoop = L;
5926122f3e6SDimitry Andric   }
5936122f3e6SDimitry Andric   if (Subloop) {
5946122f3e6SDimitry Andric     SubloopParents[Subloop] = NearLoop;
5956122f3e6SDimitry Andric     return BBLoop;
5966122f3e6SDimitry Andric   }
5976122f3e6SDimitry Andric   return NearLoop;
5986122f3e6SDimitry Andric }
5996122f3e6SDimitry Andric 
LoopInfo(const DomTreeBase<BasicBlock> & DomTree)6002cab237bSDimitry Andric LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); }
6017d523365SDimitry Andric 
invalidate(Function & F,const PreservedAnalyses & PA,FunctionAnalysisManager::Invalidator &)6027a7e6055SDimitry Andric bool LoopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
6037a7e6055SDimitry Andric                           FunctionAnalysisManager::Invalidator &) {
6047a7e6055SDimitry Andric   // Check whether the analysis, all analyses on functions, or the function's
6057a7e6055SDimitry Andric   // CFG have been preserved.
6067a7e6055SDimitry Andric   auto PAC = PA.getChecker<LoopAnalysis>();
6077a7e6055SDimitry Andric   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
6087a7e6055SDimitry Andric            PAC.preservedSet<CFGAnalyses>());
6097a7e6055SDimitry Andric }
6107a7e6055SDimitry Andric 
erase(Loop * Unloop)6112cab237bSDimitry Andric void LoopInfo::erase(Loop *Unloop) {
6122cab237bSDimitry Andric   assert(!Unloop->isInvalid() && "Loop has already been erased!");
6132cab237bSDimitry Andric 
6142cab237bSDimitry Andric   auto InvalidateOnExit = make_scope_exit([&]() { destroy(Unloop); });
6156122f3e6SDimitry Andric 
6166122f3e6SDimitry Andric   // First handle the special case of no parent loop to simplify the algorithm.
6176122f3e6SDimitry Andric   if (!Unloop->getParentLoop()) {
6186122f3e6SDimitry Andric     // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
6196122f3e6SDimitry Andric     for (Loop::block_iterator I = Unloop->block_begin(),
620ff0cc061SDimitry Andric                               E = Unloop->block_end();
621ff0cc061SDimitry Andric          I != E; ++I) {
6226122f3e6SDimitry Andric 
6236122f3e6SDimitry Andric       // Don't reparent blocks in subloops.
6246122f3e6SDimitry Andric       if (getLoopFor(*I) != Unloop)
6256122f3e6SDimitry Andric         continue;
6266122f3e6SDimitry Andric 
6276122f3e6SDimitry Andric       // Blocks no longer have a parent but are still referenced by Unloop until
6286122f3e6SDimitry Andric       // the Unloop object is deleted.
629ff0cc061SDimitry Andric       changeLoopFor(*I, nullptr);
6306122f3e6SDimitry Andric     }
6316122f3e6SDimitry Andric 
6326122f3e6SDimitry Andric     // Remove the loop from the top-level LoopInfo object.
633ff0cc061SDimitry Andric     for (iterator I = begin();; ++I) {
634ff0cc061SDimitry Andric       assert(I != end() && "Couldn't find loop");
6356122f3e6SDimitry Andric       if (*I == Unloop) {
636ff0cc061SDimitry Andric         removeLoop(I);
6376122f3e6SDimitry Andric         break;
6386122f3e6SDimitry Andric       }
6396122f3e6SDimitry Andric     }
6406122f3e6SDimitry Andric 
6416122f3e6SDimitry Andric     // Move all of the subloops to the top-level.
6426122f3e6SDimitry Andric     while (!Unloop->empty())
643ff0cc061SDimitry Andric       addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
6446122f3e6SDimitry Andric 
6456122f3e6SDimitry Andric     return;
6466122f3e6SDimitry Andric   }
6476122f3e6SDimitry Andric 
6486122f3e6SDimitry Andric   // Update the parent loop for all blocks within the loop. Blocks within
6496122f3e6SDimitry Andric   // subloops will not change parents.
6506122f3e6SDimitry Andric   UnloopUpdater Updater(Unloop, this);
6516122f3e6SDimitry Andric   Updater.updateBlockParents();
6526122f3e6SDimitry Andric 
6536122f3e6SDimitry Andric   // Remove blocks from former ancestor loops.
6546122f3e6SDimitry Andric   Updater.removeBlocksFromAncestors();
6556122f3e6SDimitry Andric 
6566122f3e6SDimitry Andric   // Add direct subloops as children in their new parent loop.
6576122f3e6SDimitry Andric   Updater.updateSubloopParents();
6586122f3e6SDimitry Andric 
6596122f3e6SDimitry Andric   // Remove unloop from its parent loop.
6606122f3e6SDimitry Andric   Loop *ParentLoop = Unloop->getParentLoop();
6616122f3e6SDimitry Andric   for (Loop::iterator I = ParentLoop->begin();; ++I) {
6626122f3e6SDimitry Andric     assert(I != ParentLoop->end() && "Couldn't find loop");
6636122f3e6SDimitry Andric     if (*I == Unloop) {
6646122f3e6SDimitry Andric       ParentLoop->removeChildLoop(I);
6656122f3e6SDimitry Andric       break;
6666122f3e6SDimitry Andric     }
6676122f3e6SDimitry Andric   }
6686122f3e6SDimitry Andric }
6696122f3e6SDimitry Andric 
670d88c1a5aSDimitry Andric AnalysisKey LoopAnalysis::Key;
671ff0cc061SDimitry Andric 
run(Function & F,FunctionAnalysisManager & AM)672d88c1a5aSDimitry Andric LoopInfo LoopAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
673ff0cc061SDimitry Andric   // FIXME: Currently we create a LoopInfo from scratch for every function.
674ff0cc061SDimitry Andric   // This may prove to be too wasteful due to deallocating and re-allocating
675ff0cc061SDimitry Andric   // memory each time for the underlying map and vector datastructures. At some
676ff0cc061SDimitry Andric   // point it may prove worthwhile to use a freelist and recycle LoopInfo
677ff0cc061SDimitry Andric   // objects. I don't want to add that kind of complexity until the scope of
678ff0cc061SDimitry Andric   // the problem is better understood.
679ff0cc061SDimitry Andric   LoopInfo LI;
6803ca95b02SDimitry Andric   LI.analyze(AM.getResult<DominatorTreeAnalysis>(F));
681ff0cc061SDimitry Andric   return LI;
682ff0cc061SDimitry Andric }
683ff0cc061SDimitry Andric 
run(Function & F,FunctionAnalysisManager & AM)684ff0cc061SDimitry Andric PreservedAnalyses LoopPrinterPass::run(Function &F,
685d88c1a5aSDimitry Andric                                        FunctionAnalysisManager &AM) {
6863ca95b02SDimitry Andric   AM.getResult<LoopAnalysis>(F).print(OS);
687ff0cc061SDimitry Andric   return PreservedAnalyses::all();
688ff0cc061SDimitry Andric }
689ff0cc061SDimitry Andric 
printLoop(Loop & L,raw_ostream & OS,const std::string & Banner)690f1a29dd3SDimitry Andric void llvm::printLoop(Loop &L, raw_ostream &OS, const std::string &Banner) {
6912cab237bSDimitry Andric 
6922cab237bSDimitry Andric   if (forcePrintModuleIR()) {
6932cab237bSDimitry Andric     // handling -print-module-scope
6942cab237bSDimitry Andric     OS << Banner << " (loop: ";
6952cab237bSDimitry Andric     L.getHeader()->printAsOperand(OS, false);
6962cab237bSDimitry Andric     OS << ")\n";
6972cab237bSDimitry Andric 
6982cab237bSDimitry Andric     // printing whole module
6992cab237bSDimitry Andric     OS << *L.getHeader()->getModule();
7002cab237bSDimitry Andric     return;
7012cab237bSDimitry Andric   }
7022cab237bSDimitry Andric 
7037d523365SDimitry Andric   OS << Banner;
7042cab237bSDimitry Andric 
7052cab237bSDimitry Andric   auto *PreHeader = L.getLoopPreheader();
7062cab237bSDimitry Andric   if (PreHeader) {
7072cab237bSDimitry Andric     OS << "\n; Preheader:";
7082cab237bSDimitry Andric     PreHeader->print(OS);
7092cab237bSDimitry Andric     OS << "\n; Loop:";
7102cab237bSDimitry Andric   }
7112cab237bSDimitry Andric 
7127d523365SDimitry Andric   for (auto *Block : L.blocks())
7137d523365SDimitry Andric     if (Block)
7147d523365SDimitry Andric       Block->print(OS);
7157d523365SDimitry Andric     else
7167d523365SDimitry Andric       OS << "Printing <null> block";
7172cab237bSDimitry Andric 
7182cab237bSDimitry Andric   SmallVector<BasicBlock *, 8> ExitBlocks;
7192cab237bSDimitry Andric   L.getExitBlocks(ExitBlocks);
7202cab237bSDimitry Andric   if (!ExitBlocks.empty()) {
7212cab237bSDimitry Andric     OS << "\n; Exit blocks";
7222cab237bSDimitry Andric     for (auto *Block : ExitBlocks)
7232cab237bSDimitry Andric       if (Block)
7242cab237bSDimitry Andric         Block->print(OS);
7252cab237bSDimitry Andric       else
7262cab237bSDimitry Andric         OS << "Printing <null> block";
7272cab237bSDimitry Andric   }
7287d523365SDimitry Andric }
7297d523365SDimitry Andric 
findOptionMDForLoopID(MDNode * LoopID,StringRef Name)730*b5893f02SDimitry Andric MDNode *llvm::findOptionMDForLoopID(MDNode *LoopID, StringRef Name) {
731*b5893f02SDimitry Andric   // No loop metadata node, no loop properties.
732*b5893f02SDimitry Andric   if (!LoopID)
733*b5893f02SDimitry Andric     return nullptr;
734*b5893f02SDimitry Andric 
735*b5893f02SDimitry Andric   // First operand should refer to the metadata node itself, for legacy reasons.
736*b5893f02SDimitry Andric   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
737*b5893f02SDimitry Andric   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
738*b5893f02SDimitry Andric 
739*b5893f02SDimitry Andric   // Iterate over the metdata node operands and look for MDString metadata.
740*b5893f02SDimitry Andric   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
741*b5893f02SDimitry Andric     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
742*b5893f02SDimitry Andric     if (!MD || MD->getNumOperands() < 1)
743*b5893f02SDimitry Andric       continue;
744*b5893f02SDimitry Andric     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
745*b5893f02SDimitry Andric     if (!S)
746*b5893f02SDimitry Andric       continue;
747*b5893f02SDimitry Andric     // Return the operand node if MDString holds expected metadata.
748*b5893f02SDimitry Andric     if (Name.equals(S->getString()))
749*b5893f02SDimitry Andric       return MD;
750*b5893f02SDimitry Andric   }
751*b5893f02SDimitry Andric 
752*b5893f02SDimitry Andric   // Loop property not found.
753*b5893f02SDimitry Andric   return nullptr;
754*b5893f02SDimitry Andric }
755*b5893f02SDimitry Andric 
findOptionMDForLoop(const Loop * TheLoop,StringRef Name)756*b5893f02SDimitry Andric MDNode *llvm::findOptionMDForLoop(const Loop *TheLoop, StringRef Name) {
757*b5893f02SDimitry Andric   return findOptionMDForLoopID(TheLoop->getLoopID(), Name);
758*b5893f02SDimitry Andric }
759*b5893f02SDimitry Andric 
isValidAsAccessGroup(MDNode * Node)760*b5893f02SDimitry Andric bool llvm::isValidAsAccessGroup(MDNode *Node) {
761*b5893f02SDimitry Andric   return Node->getNumOperands() == 0 && Node->isDistinct();
762*b5893f02SDimitry Andric }
763*b5893f02SDimitry Andric 
764ff0cc061SDimitry Andric //===----------------------------------------------------------------------===//
765ff0cc061SDimitry Andric // LoopInfo implementation
766ff0cc061SDimitry Andric //
767ff0cc061SDimitry Andric 
768ff0cc061SDimitry Andric char LoopInfoWrapperPass::ID = 0;
769ff0cc061SDimitry Andric INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
770ff0cc061SDimitry Andric                       true, true)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)771ff0cc061SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
772ff0cc061SDimitry Andric INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
773ff0cc061SDimitry Andric                     true, true)
774ff0cc061SDimitry Andric 
775ff0cc061SDimitry Andric bool LoopInfoWrapperPass::runOnFunction(Function &) {
776ff0cc061SDimitry Andric   releaseMemory();
7777d523365SDimitry Andric   LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
778ff0cc061SDimitry Andric   return false;
779ff0cc061SDimitry Andric }
780ff0cc061SDimitry Andric 
verifyAnalysis() const781ff0cc061SDimitry Andric void LoopInfoWrapperPass::verifyAnalysis() const {
782ff0cc061SDimitry Andric   // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
783ff0cc061SDimitry Andric   // function each time verifyAnalysis is called is very expensive. The
784f22ef01cSRoman Divacky   // -verify-loop-info option can enable this. In order to perform some
785ff0cc061SDimitry Andric   // checking by default, LoopPass has been taught to call verifyLoop manually
786ff0cc061SDimitry Andric   // during loop pass sequences.
787d88c1a5aSDimitry Andric   if (VerifyLoopInfo) {
788d88c1a5aSDimitry Andric     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
789d88c1a5aSDimitry Andric     LI.verify(DT);
790d88c1a5aSDimitry Andric   }
791f22ef01cSRoman Divacky }
792f22ef01cSRoman Divacky 
getAnalysisUsage(AnalysisUsage & AU) const793ff0cc061SDimitry Andric void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
794f22ef01cSRoman Divacky   AU.setPreservesAll();
79591bc56edSDimitry Andric   AU.addRequired<DominatorTreeWrapperPass>();
796f22ef01cSRoman Divacky }
797f22ef01cSRoman Divacky 
print(raw_ostream & OS,const Module *) const798ff0cc061SDimitry Andric void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
799f22ef01cSRoman Divacky   LI.print(OS);
800f22ef01cSRoman Divacky }
801f22ef01cSRoman Divacky 
run(Function & F,FunctionAnalysisManager & AM)802d88c1a5aSDimitry Andric PreservedAnalyses LoopVerifierPass::run(Function &F,
803d88c1a5aSDimitry Andric                                         FunctionAnalysisManager &AM) {
804d88c1a5aSDimitry Andric   LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
805d88c1a5aSDimitry Andric   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
806d88c1a5aSDimitry Andric   LI.verify(DT);
807d88c1a5aSDimitry Andric   return PreservedAnalyses::all();
808d88c1a5aSDimitry Andric }
809d88c1a5aSDimitry Andric 
8106122f3e6SDimitry Andric //===----------------------------------------------------------------------===//
8116122f3e6SDimitry Andric // LoopBlocksDFS implementation
8126122f3e6SDimitry Andric //
8136122f3e6SDimitry Andric 
8146122f3e6SDimitry Andric /// Traverse the loop blocks and store the DFS result.
8156122f3e6SDimitry Andric /// Useful for clients that just want the final DFS result and don't need to
8166122f3e6SDimitry Andric /// visit blocks during the initial traversal.
perform(LoopInfo * LI)8176122f3e6SDimitry Andric void LoopBlocksDFS::perform(LoopInfo *LI) {
8186122f3e6SDimitry Andric   LoopBlocksTraversal Traversal(*this, LI);
8196122f3e6SDimitry Andric   for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
8202cab237bSDimitry Andric                                         POE = Traversal.end();
8212cab237bSDimitry Andric        POI != POE; ++POI)
8222cab237bSDimitry Andric     ;
8236122f3e6SDimitry Andric }
824