1009b1c42SEd Schouten //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This file defines the LoopInfo class that is used to identify natural loops
10009b1c42SEd Schouten // and determine the loop depth of various nodes of the CFG. Note that the
11009b1c42SEd Schouten // loops identified may actually be several natural loops that share the same
12009b1c42SEd Schouten // header node... not just a single natural loop.
13009b1c42SEd Schouten //
14009b1c42SEd Schouten //===----------------------------------------------------------------------===//
15009b1c42SEd Schouten
16009b1c42SEd Schouten #include "llvm/Analysis/LoopInfo.h"
17044eb2f6SDimitry Andric #include "llvm/ADT/ScopeExit.h"
184a16efa3SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
19e6d15924SDimitry Andric #include "llvm/Analysis/IVDescriptors.h"
2030815c53SDimitry Andric #include "llvm/Analysis/LoopIterator.h"
21344a3780SDimitry Andric #include "llvm/Analysis/LoopNestAnalysis.h"
22e6d15924SDimitry Andric #include "llvm/Analysis/MemorySSA.h"
23e6d15924SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
24e6d15924SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
2563faed5bSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
26eb11fae6SDimitry Andric #include "llvm/Config/llvm-config.h"
275ca98fd9SDimitry Andric #include "llvm/IR/CFG.h"
284a16efa3SDimitry Andric #include "llvm/IR/Constants.h"
2901095a5dSDimitry Andric #include "llvm/IR/DebugLoc.h"
305ca98fd9SDimitry Andric #include "llvm/IR/Dominators.h"
314a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
3267c32a98SDimitry Andric #include "llvm/IR/LLVMContext.h"
334a16efa3SDimitry Andric #include "llvm/IR/Metadata.h"
34ac9a064cSDimitry Andric #include "llvm/IR/Module.h"
355a5ac124SDimitry Andric #include "llvm/IR/PassManager.h"
36b60736ecSDimitry Andric #include "llvm/IR/PrintPasses.h"
37706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
3859850d08SRoman Divacky #include "llvm/Support/CommandLine.h"
397fa27ce4SDimitry Andric #include "llvm/Support/GenericLoopInfoImpl.h"
405a5ac124SDimitry Andric #include "llvm/Support/raw_ostream.h"
41009b1c42SEd Schouten using namespace llvm;
42009b1c42SEd Schouten
4358b69754SDimitry Andric // Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
4458b69754SDimitry Andric template class llvm::LoopBase<BasicBlock, Loop>;
4558b69754SDimitry Andric template class llvm::LoopInfoBase<BasicBlock, Loop>;
4658b69754SDimitry Andric
4759850d08SRoman Divacky // Always verify loopinfo if expensive checking is enabled.
4801095a5dSDimitry Andric #ifdef EXPENSIVE_CHECKS
4971d5a254SDimitry Andric bool llvm::VerifyLoopInfo = true;
5059850d08SRoman Divacky #else
5171d5a254SDimitry Andric bool llvm::VerifyLoopInfo = false;
5259850d08SRoman Divacky #endif
5359850d08SRoman Divacky static cl::opt<bool, true>
5459850d08SRoman Divacky VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
55044eb2f6SDimitry Andric cl::Hidden, cl::desc("Verify loop info (time consuming)"));
5659850d08SRoman Divacky
57009b1c42SEd Schouten //===----------------------------------------------------------------------===//
58009b1c42SEd Schouten // Loop implementation
59009b1c42SEd Schouten //
60009b1c42SEd Schouten
isLoopInvariant(const Value * V) const615a5ac124SDimitry Andric bool Loop::isLoopInvariant(const Value *V) const {
625a5ac124SDimitry Andric if (const Instruction *I = dyn_cast<Instruction>(V))
63cf099d11SDimitry Andric return !contains(I);
6459850d08SRoman Divacky return true; // All non-instructions are loop invariant
6559850d08SRoman Divacky }
6659850d08SRoman Divacky
hasLoopInvariantOperands(const Instruction * I) const675a5ac124SDimitry Andric bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
685a5ac124SDimitry Andric return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
6959850d08SRoman Divacky }
7059850d08SRoman Divacky
makeLoopInvariant(Value * V,bool & Changed,Instruction * InsertPt,MemorySSAUpdater * MSSAU,ScalarEvolution * SE) const71e6d15924SDimitry Andric bool Loop::makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt,
72e3b55780SDimitry Andric MemorySSAUpdater *MSSAU,
73e3b55780SDimitry Andric ScalarEvolution *SE) const {
7459850d08SRoman Divacky if (Instruction *I = dyn_cast<Instruction>(V))
75e3b55780SDimitry Andric return makeLoopInvariant(I, Changed, InsertPt, MSSAU, SE);
7659850d08SRoman Divacky return true; // All non-instructions are loop-invariant.
7759850d08SRoman Divacky }
7859850d08SRoman Divacky
makeLoopInvariant(Instruction * I,bool & Changed,Instruction * InsertPt,MemorySSAUpdater * MSSAU,ScalarEvolution * SE) const7959850d08SRoman Divacky bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
80e3b55780SDimitry Andric Instruction *InsertPt, MemorySSAUpdater *MSSAU,
81e3b55780SDimitry Andric ScalarEvolution *SE) const {
8259850d08SRoman Divacky // Test if the value is already loop-invariant.
8359850d08SRoman Divacky if (isLoopInvariant(I))
8459850d08SRoman Divacky return true;
8563faed5bSDimitry Andric if (!isSafeToSpeculativelyExecute(I))
8659850d08SRoman Divacky return false;
8759850d08SRoman Divacky if (I->mayReadFromMemory())
8859850d08SRoman Divacky return false;
89dd58ef01SDimitry Andric // EH block instructions are immobile.
90dd58ef01SDimitry Andric if (I->isEHPad())
9130815c53SDimitry Andric return false;
9259850d08SRoman Divacky // Determine the insertion point, unless one was given.
9359850d08SRoman Divacky if (!InsertPt) {
9459850d08SRoman Divacky BasicBlock *Preheader = getLoopPreheader();
9559850d08SRoman Divacky // Without a preheader, hoisting is not feasible.
9659850d08SRoman Divacky if (!Preheader)
9759850d08SRoman Divacky return false;
9859850d08SRoman Divacky InsertPt = Preheader->getTerminator();
9959850d08SRoman Divacky }
10059850d08SRoman Divacky // Don't hoist instructions with loop-variant operands.
10101095a5dSDimitry Andric for (Value *Operand : I->operands())
102e3b55780SDimitry Andric if (!makeLoopInvariant(Operand, Changed, InsertPt, MSSAU, SE))
10359850d08SRoman Divacky return false;
104cf099d11SDimitry Andric
10559850d08SRoman Divacky // Hoist.
10659850d08SRoman Divacky I->moveBefore(InsertPt);
107e6d15924SDimitry Andric if (MSSAU)
108e6d15924SDimitry Andric if (auto *MUD = MSSAU->getMemorySSA()->getMemoryAccess(I))
109706b4fc4SDimitry Andric MSSAU->moveToPlace(MUD, InsertPt->getParent(),
110706b4fc4SDimitry Andric MemorySSA::BeforeTerminator);
111dd58ef01SDimitry Andric
112dd58ef01SDimitry Andric // There is possibility of hoisting this instruction above some arbitrary
113dd58ef01SDimitry Andric // condition. Any metadata defined on it can be control dependent on this
114dd58ef01SDimitry Andric // condition. Conservatively strip it here so that we don't give any wrong
115dd58ef01SDimitry Andric // information to the optimizer.
116dd58ef01SDimitry Andric I->dropUnknownNonDebugMetadata();
117dd58ef01SDimitry Andric
118e3b55780SDimitry Andric if (SE)
119e3b55780SDimitry Andric SE->forgetBlockAndLoopDispositions(I);
120e3b55780SDimitry Andric
12159850d08SRoman Divacky Changed = true;
12259850d08SRoman Divacky return true;
12359850d08SRoman Divacky }
12459850d08SRoman Divacky
getIncomingAndBackEdge(BasicBlock * & Incoming,BasicBlock * & Backedge) const125e6d15924SDimitry Andric bool Loop::getIncomingAndBackEdge(BasicBlock *&Incoming,
126e6d15924SDimitry Andric BasicBlock *&Backedge) const {
12759850d08SRoman Divacky BasicBlock *H = getHeader();
12859850d08SRoman Divacky
129e6d15924SDimitry Andric Incoming = nullptr;
130e6d15924SDimitry Andric Backedge = nullptr;
131d39c594dSDimitry Andric pred_iterator PI = pred_begin(H);
132044eb2f6SDimitry Andric assert(PI != pred_end(H) && "Loop must have at least one backedge!");
13359850d08SRoman Divacky Backedge = *PI++;
134044eb2f6SDimitry Andric if (PI == pred_end(H))
135e6d15924SDimitry Andric return false; // dead loop
13659850d08SRoman Divacky Incoming = *PI++;
137044eb2f6SDimitry Andric if (PI != pred_end(H))
138e6d15924SDimitry Andric return false; // multiple backedges?
13959850d08SRoman Divacky
14059850d08SRoman Divacky if (contains(Incoming)) {
14159850d08SRoman Divacky if (contains(Backedge))
142e6d15924SDimitry Andric return false;
14359850d08SRoman Divacky std::swap(Incoming, Backedge);
14459850d08SRoman Divacky } else if (!contains(Backedge))
145e6d15924SDimitry Andric return false;
146e6d15924SDimitry Andric
147e6d15924SDimitry Andric assert(Incoming && Backedge && "expected non-null incoming and backedges");
148e6d15924SDimitry Andric return true;
149e6d15924SDimitry Andric }
150e6d15924SDimitry Andric
getCanonicalInductionVariable() const151e6d15924SDimitry Andric PHINode *Loop::getCanonicalInductionVariable() const {
152e6d15924SDimitry Andric BasicBlock *H = getHeader();
153e6d15924SDimitry Andric
154e6d15924SDimitry Andric BasicBlock *Incoming = nullptr, *Backedge = nullptr;
155e6d15924SDimitry Andric if (!getIncomingAndBackEdge(Incoming, Backedge))
1565ca98fd9SDimitry Andric return nullptr;
15759850d08SRoman Divacky
15859850d08SRoman Divacky // Loop over all of the PHI nodes, looking for a canonical indvar.
15959850d08SRoman Divacky for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
16059850d08SRoman Divacky PHINode *PN = cast<PHINode>(I);
16159850d08SRoman Divacky if (ConstantInt *CI =
16259850d08SRoman Divacky dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
163ca089b24SDimitry Andric if (CI->isZero())
16459850d08SRoman Divacky if (Instruction *Inc =
16559850d08SRoman Divacky dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
166044eb2f6SDimitry Andric if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
16759850d08SRoman Divacky if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
168ca089b24SDimitry Andric if (CI->isOne())
16959850d08SRoman Divacky return PN;
17059850d08SRoman Divacky }
1715ca98fd9SDimitry Andric return nullptr;
17259850d08SRoman Divacky }
17359850d08SRoman Divacky
174e6d15924SDimitry Andric /// Get the latch condition instruction.
getLatchCmpInst() const175344a3780SDimitry Andric ICmpInst *Loop::getLatchCmpInst() const {
176344a3780SDimitry Andric if (BasicBlock *Latch = getLoopLatch())
177e6d15924SDimitry Andric if (BranchInst *BI = dyn_cast_or_null<BranchInst>(Latch->getTerminator()))
178e6d15924SDimitry Andric if (BI->isConditional())
179e6d15924SDimitry Andric return dyn_cast<ICmpInst>(BI->getCondition());
180e6d15924SDimitry Andric
181e6d15924SDimitry Andric return nullptr;
182e6d15924SDimitry Andric }
183e6d15924SDimitry Andric
184e6d15924SDimitry Andric /// Return the final value of the loop induction variable if found.
findFinalIVValue(const Loop & L,const PHINode & IndVar,const Instruction & StepInst)185e6d15924SDimitry Andric static Value *findFinalIVValue(const Loop &L, const PHINode &IndVar,
186e6d15924SDimitry Andric const Instruction &StepInst) {
187344a3780SDimitry Andric ICmpInst *LatchCmpInst = L.getLatchCmpInst();
188e6d15924SDimitry Andric if (!LatchCmpInst)
189e6d15924SDimitry Andric return nullptr;
190e6d15924SDimitry Andric
191e6d15924SDimitry Andric Value *Op0 = LatchCmpInst->getOperand(0);
192e6d15924SDimitry Andric Value *Op1 = LatchCmpInst->getOperand(1);
193e6d15924SDimitry Andric if (Op0 == &IndVar || Op0 == &StepInst)
194e6d15924SDimitry Andric return Op1;
195e6d15924SDimitry Andric
196e6d15924SDimitry Andric if (Op1 == &IndVar || Op1 == &StepInst)
197e6d15924SDimitry Andric return Op0;
198e6d15924SDimitry Andric
199e6d15924SDimitry Andric return nullptr;
200e6d15924SDimitry Andric }
201e6d15924SDimitry Andric
202e3b55780SDimitry Andric std::optional<Loop::LoopBounds>
getBounds(const Loop & L,PHINode & IndVar,ScalarEvolution & SE)203e3b55780SDimitry Andric Loop::LoopBounds::getBounds(const Loop &L, PHINode &IndVar,
204e6d15924SDimitry Andric ScalarEvolution &SE) {
205e6d15924SDimitry Andric InductionDescriptor IndDesc;
206e6d15924SDimitry Andric if (!InductionDescriptor::isInductionPHI(&IndVar, &L, &SE, IndDesc))
207e3b55780SDimitry Andric return std::nullopt;
208e6d15924SDimitry Andric
209e6d15924SDimitry Andric Value *InitialIVValue = IndDesc.getStartValue();
210e6d15924SDimitry Andric Instruction *StepInst = IndDesc.getInductionBinOp();
211e6d15924SDimitry Andric if (!InitialIVValue || !StepInst)
212e3b55780SDimitry Andric return std::nullopt;
213e6d15924SDimitry Andric
214e6d15924SDimitry Andric const SCEV *Step = IndDesc.getStep();
215e6d15924SDimitry Andric Value *StepInstOp1 = StepInst->getOperand(1);
216e6d15924SDimitry Andric Value *StepInstOp0 = StepInst->getOperand(0);
217e6d15924SDimitry Andric Value *StepValue = nullptr;
218e6d15924SDimitry Andric if (SE.getSCEV(StepInstOp1) == Step)
219e6d15924SDimitry Andric StepValue = StepInstOp1;
220e6d15924SDimitry Andric else if (SE.getSCEV(StepInstOp0) == Step)
221e6d15924SDimitry Andric StepValue = StepInstOp0;
222e6d15924SDimitry Andric
223e6d15924SDimitry Andric Value *FinalIVValue = findFinalIVValue(L, IndVar, *StepInst);
224e6d15924SDimitry Andric if (!FinalIVValue)
225e3b55780SDimitry Andric return std::nullopt;
226e6d15924SDimitry Andric
227e6d15924SDimitry Andric return LoopBounds(L, *InitialIVValue, *StepInst, StepValue, *FinalIVValue,
228e6d15924SDimitry Andric SE);
229e6d15924SDimitry Andric }
230e6d15924SDimitry Andric
231e6d15924SDimitry Andric using Direction = Loop::LoopBounds::Direction;
232e6d15924SDimitry Andric
getCanonicalPredicate() const233e6d15924SDimitry Andric ICmpInst::Predicate Loop::LoopBounds::getCanonicalPredicate() const {
234e6d15924SDimitry Andric BasicBlock *Latch = L.getLoopLatch();
235e6d15924SDimitry Andric assert(Latch && "Expecting valid latch");
236e6d15924SDimitry Andric
237e6d15924SDimitry Andric BranchInst *BI = dyn_cast_or_null<BranchInst>(Latch->getTerminator());
238e6d15924SDimitry Andric assert(BI && BI->isConditional() && "Expecting conditional latch branch");
239e6d15924SDimitry Andric
240e6d15924SDimitry Andric ICmpInst *LatchCmpInst = dyn_cast<ICmpInst>(BI->getCondition());
241e6d15924SDimitry Andric assert(LatchCmpInst &&
242e6d15924SDimitry Andric "Expecting the latch compare instruction to be a CmpInst");
243e6d15924SDimitry Andric
244e6d15924SDimitry Andric // Need to inverse the predicate when first successor is not the loop
245e6d15924SDimitry Andric // header
246e6d15924SDimitry Andric ICmpInst::Predicate Pred = (BI->getSuccessor(0) == L.getHeader())
247e6d15924SDimitry Andric ? LatchCmpInst->getPredicate()
248e6d15924SDimitry Andric : LatchCmpInst->getInversePredicate();
249e6d15924SDimitry Andric
250e6d15924SDimitry Andric if (LatchCmpInst->getOperand(0) == &getFinalIVValue())
251e6d15924SDimitry Andric Pred = ICmpInst::getSwappedPredicate(Pred);
252e6d15924SDimitry Andric
253e6d15924SDimitry Andric // Need to flip strictness of the predicate when the latch compare instruction
254e6d15924SDimitry Andric // is not using StepInst
255e6d15924SDimitry Andric if (LatchCmpInst->getOperand(0) == &getStepInst() ||
256e6d15924SDimitry Andric LatchCmpInst->getOperand(1) == &getStepInst())
257e6d15924SDimitry Andric return Pred;
258e6d15924SDimitry Andric
259e6d15924SDimitry Andric // Cannot flip strictness of NE and EQ
260e6d15924SDimitry Andric if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
261e6d15924SDimitry Andric return ICmpInst::getFlippedStrictnessPredicate(Pred);
262e6d15924SDimitry Andric
263e6d15924SDimitry Andric Direction D = getDirection();
264e6d15924SDimitry Andric if (D == Direction::Increasing)
265e6d15924SDimitry Andric return ICmpInst::ICMP_SLT;
266e6d15924SDimitry Andric
267e6d15924SDimitry Andric if (D == Direction::Decreasing)
268e6d15924SDimitry Andric return ICmpInst::ICMP_SGT;
269e6d15924SDimitry Andric
270e6d15924SDimitry Andric // If cannot determine the direction, then unable to find the canonical
271e6d15924SDimitry Andric // predicate
272e6d15924SDimitry Andric return ICmpInst::BAD_ICMP_PREDICATE;
273e6d15924SDimitry Andric }
274e6d15924SDimitry Andric
getDirection() const275e6d15924SDimitry Andric Direction Loop::LoopBounds::getDirection() const {
276e6d15924SDimitry Andric if (const SCEVAddRecExpr *StepAddRecExpr =
277e6d15924SDimitry Andric dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&getStepInst())))
278e6d15924SDimitry Andric if (const SCEV *StepRecur = StepAddRecExpr->getStepRecurrence(SE)) {
279e6d15924SDimitry Andric if (SE.isKnownPositive(StepRecur))
280e6d15924SDimitry Andric return Direction::Increasing;
281e6d15924SDimitry Andric if (SE.isKnownNegative(StepRecur))
282e6d15924SDimitry Andric return Direction::Decreasing;
283e6d15924SDimitry Andric }
284e6d15924SDimitry Andric
285e6d15924SDimitry Andric return Direction::Unknown;
286e6d15924SDimitry Andric }
287e6d15924SDimitry Andric
getBounds(ScalarEvolution & SE) const288e3b55780SDimitry Andric std::optional<Loop::LoopBounds> Loop::getBounds(ScalarEvolution &SE) const {
289e6d15924SDimitry Andric if (PHINode *IndVar = getInductionVariable(SE))
290e6d15924SDimitry Andric return LoopBounds::getBounds(*this, *IndVar, SE);
291e6d15924SDimitry Andric
292e3b55780SDimitry Andric return std::nullopt;
293e6d15924SDimitry Andric }
294e6d15924SDimitry Andric
getInductionVariable(ScalarEvolution & SE) const295e6d15924SDimitry Andric PHINode *Loop::getInductionVariable(ScalarEvolution &SE) const {
296e6d15924SDimitry Andric if (!isLoopSimplifyForm())
297e6d15924SDimitry Andric return nullptr;
298e6d15924SDimitry Andric
299e6d15924SDimitry Andric BasicBlock *Header = getHeader();
300e6d15924SDimitry Andric assert(Header && "Expected a valid loop header");
301344a3780SDimitry Andric ICmpInst *CmpInst = getLatchCmpInst();
302e6d15924SDimitry Andric if (!CmpInst)
303e6d15924SDimitry Andric return nullptr;
304e6d15924SDimitry Andric
305c0981da4SDimitry Andric Value *LatchCmpOp0 = CmpInst->getOperand(0);
306c0981da4SDimitry Andric Value *LatchCmpOp1 = CmpInst->getOperand(1);
307e6d15924SDimitry Andric
308e6d15924SDimitry Andric for (PHINode &IndVar : Header->phis()) {
309e6d15924SDimitry Andric InductionDescriptor IndDesc;
310e6d15924SDimitry Andric if (!InductionDescriptor::isInductionPHI(&IndVar, this, &SE, IndDesc))
311e6d15924SDimitry Andric continue;
312e6d15924SDimitry Andric
313c0981da4SDimitry Andric BasicBlock *Latch = getLoopLatch();
314c0981da4SDimitry Andric Value *StepInst = IndVar.getIncomingValueForBlock(Latch);
315e6d15924SDimitry Andric
316e6d15924SDimitry Andric // case 1:
317e6d15924SDimitry Andric // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
318e6d15924SDimitry Andric // StepInst = IndVar + step
319e6d15924SDimitry Andric // cmp = StepInst < FinalValue
320e6d15924SDimitry Andric if (StepInst == LatchCmpOp0 || StepInst == LatchCmpOp1)
321e6d15924SDimitry Andric return &IndVar;
322e6d15924SDimitry Andric
323e6d15924SDimitry Andric // case 2:
324e6d15924SDimitry Andric // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}]
325e6d15924SDimitry Andric // StepInst = IndVar + step
326e6d15924SDimitry Andric // cmp = IndVar < FinalValue
327e6d15924SDimitry Andric if (&IndVar == LatchCmpOp0 || &IndVar == LatchCmpOp1)
328e6d15924SDimitry Andric return &IndVar;
329e6d15924SDimitry Andric }
330e6d15924SDimitry Andric
331e6d15924SDimitry Andric return nullptr;
332e6d15924SDimitry Andric }
333e6d15924SDimitry Andric
getInductionDescriptor(ScalarEvolution & SE,InductionDescriptor & IndDesc) const334e6d15924SDimitry Andric bool Loop::getInductionDescriptor(ScalarEvolution &SE,
335e6d15924SDimitry Andric InductionDescriptor &IndDesc) const {
336e6d15924SDimitry Andric if (PHINode *IndVar = getInductionVariable(SE))
337e6d15924SDimitry Andric return InductionDescriptor::isInductionPHI(IndVar, this, &SE, IndDesc);
338e6d15924SDimitry Andric
339e6d15924SDimitry Andric return false;
340e6d15924SDimitry Andric }
341e6d15924SDimitry Andric
isAuxiliaryInductionVariable(PHINode & AuxIndVar,ScalarEvolution & SE) const342e6d15924SDimitry Andric bool Loop::isAuxiliaryInductionVariable(PHINode &AuxIndVar,
343e6d15924SDimitry Andric ScalarEvolution &SE) const {
344e6d15924SDimitry Andric // Located in the loop header
345e6d15924SDimitry Andric BasicBlock *Header = getHeader();
346e6d15924SDimitry Andric if (AuxIndVar.getParent() != Header)
347e6d15924SDimitry Andric return false;
348e6d15924SDimitry Andric
349e6d15924SDimitry Andric // No uses outside of the loop
350e6d15924SDimitry Andric for (User *U : AuxIndVar.users())
351e6d15924SDimitry Andric if (const Instruction *I = dyn_cast<Instruction>(U))
352e6d15924SDimitry Andric if (!contains(I))
353e6d15924SDimitry Andric return false;
354e6d15924SDimitry Andric
355e6d15924SDimitry Andric InductionDescriptor IndDesc;
356e6d15924SDimitry Andric if (!InductionDescriptor::isInductionPHI(&AuxIndVar, this, &SE, IndDesc))
357e6d15924SDimitry Andric return false;
358e6d15924SDimitry Andric
359e6d15924SDimitry Andric // The step instruction opcode should be add or sub.
360e6d15924SDimitry Andric if (IndDesc.getInductionOpcode() != Instruction::Add &&
361e6d15924SDimitry Andric IndDesc.getInductionOpcode() != Instruction::Sub)
362e6d15924SDimitry Andric return false;
363e6d15924SDimitry Andric
364e6d15924SDimitry Andric // Incremented by a loop invariant step for each loop iteration
365e6d15924SDimitry Andric return SE.isLoopInvariant(IndDesc.getStep(), this);
366e6d15924SDimitry Andric }
367e6d15924SDimitry Andric
getLoopGuardBranch() const3681d5ae102SDimitry Andric BranchInst *Loop::getLoopGuardBranch() const {
3691d5ae102SDimitry Andric if (!isLoopSimplifyForm())
3701d5ae102SDimitry Andric return nullptr;
3711d5ae102SDimitry Andric
3721d5ae102SDimitry Andric BasicBlock *Preheader = getLoopPreheader();
373706b4fc4SDimitry Andric assert(Preheader && getLoopLatch() &&
3741d5ae102SDimitry Andric "Expecting a loop with valid preheader and latch");
3751d5ae102SDimitry Andric
3761d5ae102SDimitry Andric // Loop should be in rotate form.
377706b4fc4SDimitry Andric if (!isRotatedForm())
3781d5ae102SDimitry Andric return nullptr;
3791d5ae102SDimitry Andric
3801d5ae102SDimitry Andric // Disallow loops with more than one unique exit block, as we do not verify
3811d5ae102SDimitry Andric // that GuardOtherSucc post dominates all exit blocks.
3821d5ae102SDimitry Andric BasicBlock *ExitFromLatch = getUniqueExitBlock();
3831d5ae102SDimitry Andric if (!ExitFromLatch)
3841d5ae102SDimitry Andric return nullptr;
3851d5ae102SDimitry Andric
3861d5ae102SDimitry Andric BasicBlock *GuardBB = Preheader->getUniquePredecessor();
3871d5ae102SDimitry Andric if (!GuardBB)
3881d5ae102SDimitry Andric return nullptr;
3891d5ae102SDimitry Andric
3901d5ae102SDimitry Andric assert(GuardBB->getTerminator() && "Expecting valid guard terminator");
3911d5ae102SDimitry Andric
3921d5ae102SDimitry Andric BranchInst *GuardBI = dyn_cast<BranchInst>(GuardBB->getTerminator());
3931d5ae102SDimitry Andric if (!GuardBI || GuardBI->isUnconditional())
3941d5ae102SDimitry Andric return nullptr;
3951d5ae102SDimitry Andric
3961d5ae102SDimitry Andric BasicBlock *GuardOtherSucc = (GuardBI->getSuccessor(0) == Preheader)
3971d5ae102SDimitry Andric ? GuardBI->getSuccessor(1)
3981d5ae102SDimitry Andric : GuardBI->getSuccessor(0);
399344a3780SDimitry Andric
400344a3780SDimitry Andric // Check if ExitFromLatch (or any BasicBlock which is an empty unique
401344a3780SDimitry Andric // successor of ExitFromLatch) is equal to GuardOtherSucc. If
402344a3780SDimitry Andric // skipEmptyBlockUntil returns GuardOtherSucc, then the guard branch for the
403344a3780SDimitry Andric // loop is GuardBI (return GuardBI), otherwise return nullptr.
404344a3780SDimitry Andric if (&LoopNest::skipEmptyBlockUntil(ExitFromLatch, GuardOtherSucc,
405344a3780SDimitry Andric /*CheckUniquePred=*/true) ==
406344a3780SDimitry Andric GuardOtherSucc)
407344a3780SDimitry Andric return GuardBI;
408344a3780SDimitry Andric else
409344a3780SDimitry Andric return nullptr;
4101d5ae102SDimitry Andric }
4111d5ae102SDimitry Andric
isCanonical(ScalarEvolution & SE) const412e6d15924SDimitry Andric bool Loop::isCanonical(ScalarEvolution &SE) const {
413e6d15924SDimitry Andric InductionDescriptor IndDesc;
414e6d15924SDimitry Andric if (!getInductionDescriptor(SE, IndDesc))
415e6d15924SDimitry Andric return false;
416e6d15924SDimitry Andric
417e6d15924SDimitry Andric ConstantInt *Init = dyn_cast_or_null<ConstantInt>(IndDesc.getStartValue());
418e6d15924SDimitry Andric if (!Init || !Init->isZero())
419e6d15924SDimitry Andric return false;
420e6d15924SDimitry Andric
421e6d15924SDimitry Andric if (IndDesc.getInductionOpcode() != Instruction::Add)
422e6d15924SDimitry Andric return false;
423e6d15924SDimitry Andric
424e6d15924SDimitry Andric ConstantInt *Step = IndDesc.getConstIntStepValue();
425e6d15924SDimitry Andric if (!Step || !Step->isOne())
426e6d15924SDimitry Andric return false;
427e6d15924SDimitry Andric
428e6d15924SDimitry Andric return true;
429e6d15924SDimitry Andric }
430e6d15924SDimitry Andric
431b915e9e0SDimitry Andric // Check that 'BB' doesn't have any uses outside of the 'L'
isBlockInLCSSAForm(const Loop & L,const BasicBlock & BB,const DominatorTree & DT,bool IgnoreTokens)432b915e9e0SDimitry Andric static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB,
4334b4fe385SDimitry Andric const DominatorTree &DT, bool IgnoreTokens) {
434b915e9e0SDimitry Andric for (const Instruction &I : BB) {
435dd58ef01SDimitry Andric // Tokens can't be used in PHI nodes and live-out tokens prevent loop
436dd58ef01SDimitry Andric // optimizations, so for the purposes of considered LCSSA form, we
437dd58ef01SDimitry Andric // can ignore them.
4384b4fe385SDimitry Andric if (IgnoreTokens && I.getType()->isTokenTy())
439dd58ef01SDimitry Andric continue;
440dd58ef01SDimitry Andric
441b915e9e0SDimitry Andric for (const Use &U : I.uses()) {
442b915e9e0SDimitry Andric const Instruction *UI = cast<Instruction>(U.getUser());
443b915e9e0SDimitry Andric const BasicBlock *UserBB = UI->getParent();
444b60736ecSDimitry Andric
445b60736ecSDimitry Andric // For practical purposes, we consider that the use in a PHI
446b60736ecSDimitry Andric // occurs in the respective predecessor block. For more info,
447b60736ecSDimitry Andric // see the `phi` doc in LangRef and the LCSSA doc.
448b915e9e0SDimitry Andric if (const PHINode *P = dyn_cast<PHINode>(UI))
4495ca98fd9SDimitry Andric UserBB = P->getIncomingBlock(U);
45059850d08SRoman Divacky
451ea5b2dd1SRoman Divacky // Check the current block, as a fast-path, before checking whether
452ea5b2dd1SRoman Divacky // the use is anywhere in the loop. Most values are used in the same
453ea5b2dd1SRoman Divacky // block they are defined in. Also, blocks not reachable from the
454ea5b2dd1SRoman Divacky // entry are special; uses in them don't need to go through PHIs.
455b915e9e0SDimitry Andric if (UserBB != &BB && !L.contains(UserBB) &&
456c6910277SRoman Divacky DT.isReachableFromEntry(UserBB))
45759850d08SRoman Divacky return false;
45859850d08SRoman Divacky }
45959850d08SRoman Divacky }
46059850d08SRoman Divacky return true;
46159850d08SRoman Divacky }
46259850d08SRoman Divacky
isLCSSAForm(const DominatorTree & DT,bool IgnoreTokens) const4634b4fe385SDimitry Andric bool Loop::isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens) const {
464b915e9e0SDimitry Andric // For each block we check that it doesn't have any uses outside of this loop.
465b915e9e0SDimitry Andric return all_of(this->blocks(), [&](const BasicBlock *BB) {
4664b4fe385SDimitry Andric return isBlockInLCSSAForm(*this, *BB, DT, IgnoreTokens);
467b915e9e0SDimitry Andric });
468b915e9e0SDimitry Andric }
469dd58ef01SDimitry Andric
isRecursivelyLCSSAForm(const DominatorTree & DT,const LoopInfo & LI,bool IgnoreTokens) const4704b4fe385SDimitry Andric bool Loop::isRecursivelyLCSSAForm(const DominatorTree &DT, const LoopInfo &LI,
4714b4fe385SDimitry Andric bool IgnoreTokens) const {
472909545a8SDimitry Andric // For each block we check that it doesn't have any uses outside of its
473909545a8SDimitry Andric // innermost loop. This process will transitively guarantee that the current
474909545a8SDimitry Andric // loop and all of the nested loops are in LCSSA form.
475b915e9e0SDimitry Andric return all_of(this->blocks(), [&](const BasicBlock *BB) {
4764b4fe385SDimitry Andric return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT, IgnoreTokens);
477dd58ef01SDimitry Andric });
478dd58ef01SDimitry Andric }
479dd58ef01SDimitry Andric
isLoopSimplifyForm() const48059850d08SRoman Divacky bool Loop::isLoopSimplifyForm() const {
481907da171SRoman Divacky // Normal-form loops have a preheader, a single backedge, and all of their
482907da171SRoman Divacky // exits have all their predecessors inside the loop.
483907da171SRoman Divacky return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
484907da171SRoman Divacky }
485907da171SRoman Divacky
48601095a5dSDimitry Andric // Routines that reform the loop CFG and split edges often fail on indirectbr.
isSafeToClone() const48763faed5bSDimitry Andric bool Loop::isSafeToClone() const {
4884a16efa3SDimitry Andric // Return false if any loop blocks contain indirectbrs, or there are any calls
4894a16efa3SDimitry Andric // to noduplicate functions.
49001095a5dSDimitry Andric for (BasicBlock *BB : this->blocks()) {
4914b4fe385SDimitry Andric if (isa<IndirectBrInst>(BB->getTerminator()))
49263faed5bSDimitry Andric return false;
493f8af5cf6SDimitry Andric
49401095a5dSDimitry Andric for (Instruction &I : *BB)
495cfca06d7SDimitry Andric if (auto *CB = dyn_cast<CallBase>(&I))
496cfca06d7SDimitry Andric if (CB->cannotDuplicate())
4974a16efa3SDimitry Andric return false;
49863faed5bSDimitry Andric }
49963faed5bSDimitry Andric return true;
50063faed5bSDimitry Andric }
50163faed5bSDimitry Andric
getLoopID() const502f8af5cf6SDimitry Andric MDNode *Loop::getLoopID() const {
5035ca98fd9SDimitry Andric MDNode *LoopID = nullptr;
504f8af5cf6SDimitry Andric
505d8e91e46SDimitry Andric // Go through the latch blocks and check the terminator for the metadata.
506d8e91e46SDimitry Andric SmallVector<BasicBlock *, 4> LatchesBlocks;
507d8e91e46SDimitry Andric getLoopLatches(LatchesBlocks);
508d8e91e46SDimitry Andric for (BasicBlock *BB : LatchesBlocks) {
509d8e91e46SDimitry Andric Instruction *TI = BB->getTerminator();
510d8e91e46SDimitry Andric MDNode *MD = TI->getMetadata(LLVMContext::MD_loop);
511d8e91e46SDimitry Andric
512f8af5cf6SDimitry Andric if (!MD)
5135ca98fd9SDimitry Andric return nullptr;
514f8af5cf6SDimitry Andric
515f8af5cf6SDimitry Andric if (!LoopID)
516f8af5cf6SDimitry Andric LoopID = MD;
517f8af5cf6SDimitry Andric else if (MD != LoopID)
5185ca98fd9SDimitry Andric return nullptr;
519f8af5cf6SDimitry Andric }
520f8af5cf6SDimitry Andric if (!LoopID || LoopID->getNumOperands() == 0 ||
521f8af5cf6SDimitry Andric LoopID->getOperand(0) != LoopID)
5225ca98fd9SDimitry Andric return nullptr;
523f8af5cf6SDimitry Andric return LoopID;
524f8af5cf6SDimitry Andric }
525f8af5cf6SDimitry Andric
setLoopID(MDNode * LoopID) const526f8af5cf6SDimitry Andric void Loop::setLoopID(MDNode *LoopID) const {
527d8e91e46SDimitry Andric assert((!LoopID || LoopID->getNumOperands() > 0) &&
528d8e91e46SDimitry Andric "Loop ID needs at least one operand");
529d8e91e46SDimitry Andric assert((!LoopID || LoopID->getOperand(0) == LoopID) &&
530d8e91e46SDimitry Andric "Loop ID should refer to itself");
531f8af5cf6SDimitry Andric
532e6d15924SDimitry Andric SmallVector<BasicBlock *, 4> LoopLatches;
533e6d15924SDimitry Andric getLoopLatches(LoopLatches);
534e6d15924SDimitry Andric for (BasicBlock *BB : LoopLatches)
535e6d15924SDimitry Andric BB->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
536f8af5cf6SDimitry Andric }
537f8af5cf6SDimitry Andric
setLoopAlreadyUnrolled()538044eb2f6SDimitry Andric void Loop::setLoopAlreadyUnrolled() {
539044eb2f6SDimitry Andric LLVMContext &Context = getHeader()->getContext();
540044eb2f6SDimitry Andric
541e6d15924SDimitry Andric MDNode *DisableUnrollMD =
542e6d15924SDimitry Andric MDNode::get(Context, MDString::get(Context, "llvm.loop.unroll.disable"));
543e6d15924SDimitry Andric MDNode *LoopID = getLoopID();
544e6d15924SDimitry Andric MDNode *NewLoopID = makePostTransformationMetadata(
545e6d15924SDimitry Andric Context, LoopID, {"llvm.loop.unroll."}, {DisableUnrollMD});
546044eb2f6SDimitry Andric setLoopID(NewLoopID);
547044eb2f6SDimitry Andric }
548044eb2f6SDimitry Andric
setLoopMustProgress()549b60736ecSDimitry Andric void Loop::setLoopMustProgress() {
550b60736ecSDimitry Andric LLVMContext &Context = getHeader()->getContext();
551b60736ecSDimitry Andric
552b60736ecSDimitry Andric MDNode *MustProgress = findOptionMDForLoop(this, "llvm.loop.mustprogress");
553b60736ecSDimitry Andric
554b60736ecSDimitry Andric if (MustProgress)
555b60736ecSDimitry Andric return;
556b60736ecSDimitry Andric
557b60736ecSDimitry Andric MDNode *MustProgressMD =
558b60736ecSDimitry Andric MDNode::get(Context, MDString::get(Context, "llvm.loop.mustprogress"));
559b60736ecSDimitry Andric MDNode *LoopID = getLoopID();
560b60736ecSDimitry Andric MDNode *NewLoopID =
561b60736ecSDimitry Andric makePostTransformationMetadata(Context, LoopID, {}, {MustProgressMD});
562b60736ecSDimitry Andric setLoopID(NewLoopID);
563b60736ecSDimitry Andric }
564b60736ecSDimitry Andric
isAnnotatedParallel() const5654a16efa3SDimitry Andric bool Loop::isAnnotatedParallel() const {
56601095a5dSDimitry Andric MDNode *DesiredLoopIdMetadata = getLoopID();
5674a16efa3SDimitry Andric
56801095a5dSDimitry Andric if (!DesiredLoopIdMetadata)
5694a16efa3SDimitry Andric return false;
5704a16efa3SDimitry Andric
571d8e91e46SDimitry Andric MDNode *ParallelAccesses =
572d8e91e46SDimitry Andric findOptionMDForLoop(this, "llvm.loop.parallel_accesses");
573d8e91e46SDimitry Andric SmallPtrSet<MDNode *, 4>
574d8e91e46SDimitry Andric ParallelAccessGroups; // For scalable 'contains' check.
575d8e91e46SDimitry Andric if (ParallelAccesses) {
576b60736ecSDimitry Andric for (const MDOperand &MD : drop_begin(ParallelAccesses->operands())) {
577d8e91e46SDimitry Andric MDNode *AccGroup = cast<MDNode>(MD.get());
578d8e91e46SDimitry Andric assert(isValidAsAccessGroup(AccGroup) &&
579d8e91e46SDimitry Andric "List item must be an access group");
580d8e91e46SDimitry Andric ParallelAccessGroups.insert(AccGroup);
581d8e91e46SDimitry Andric }
582d8e91e46SDimitry Andric }
583d8e91e46SDimitry Andric
5844a16efa3SDimitry Andric // The loop branch contains the parallel loop metadata. In order to ensure
5854a16efa3SDimitry Andric // that any parallel-loop-unaware optimization pass hasn't added loop-carried
5864a16efa3SDimitry Andric // dependencies (thus converted the loop back to a sequential loop), check
587d8e91e46SDimitry Andric // that all the memory instructions in the loop belong to an access group that
588d8e91e46SDimitry Andric // is parallel to this loop.
58901095a5dSDimitry Andric for (BasicBlock *BB : this->blocks()) {
59001095a5dSDimitry Andric for (Instruction &I : *BB) {
59101095a5dSDimitry Andric if (!I.mayReadOrWriteMemory())
5924a16efa3SDimitry Andric continue;
5934a16efa3SDimitry Andric
594d8e91e46SDimitry Andric if (MDNode *AccessGroup = I.getMetadata(LLVMContext::MD_access_group)) {
595d8e91e46SDimitry Andric auto ContainsAccessGroup = [&ParallelAccessGroups](MDNode *AG) -> bool {
596d8e91e46SDimitry Andric if (AG->getNumOperands() == 0) {
597d8e91e46SDimitry Andric assert(isValidAsAccessGroup(AG) && "Item must be an access group");
598d8e91e46SDimitry Andric return ParallelAccessGroups.count(AG);
599d8e91e46SDimitry Andric }
600d8e91e46SDimitry Andric
601d8e91e46SDimitry Andric for (const MDOperand &AccessListItem : AG->operands()) {
602d8e91e46SDimitry Andric MDNode *AccGroup = cast<MDNode>(AccessListItem.get());
603d8e91e46SDimitry Andric assert(isValidAsAccessGroup(AccGroup) &&
604d8e91e46SDimitry Andric "List item must be an access group");
605d8e91e46SDimitry Andric if (ParallelAccessGroups.count(AccGroup))
606d8e91e46SDimitry Andric return true;
607d8e91e46SDimitry Andric }
608d8e91e46SDimitry Andric return false;
609d8e91e46SDimitry Andric };
610d8e91e46SDimitry Andric
611d8e91e46SDimitry Andric if (ContainsAccessGroup(AccessGroup))
612d8e91e46SDimitry Andric continue;
613d8e91e46SDimitry Andric }
614d8e91e46SDimitry Andric
6154a16efa3SDimitry Andric // The memory instruction can refer to the loop identifier metadata
6164a16efa3SDimitry Andric // directly or indirectly through another list metadata (in case of
6174a16efa3SDimitry Andric // nested parallel loops). The loop identifier metadata refers to
6184a16efa3SDimitry Andric // itself so we can check both cases with the same routine.
61901095a5dSDimitry Andric MDNode *LoopIdMD =
62001095a5dSDimitry Andric I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
621f8af5cf6SDimitry Andric
62201095a5dSDimitry Andric if (!LoopIdMD)
623f8af5cf6SDimitry Andric return false;
624f8af5cf6SDimitry Andric
625344a3780SDimitry Andric if (!llvm::is_contained(LoopIdMD->operands(), DesiredLoopIdMetadata))
6264a16efa3SDimitry Andric return false;
6274a16efa3SDimitry Andric }
6284a16efa3SDimitry Andric }
6294a16efa3SDimitry Andric return true;
6304a16efa3SDimitry Andric }
6314a16efa3SDimitry Andric
getStartLoc() const632044eb2f6SDimitry Andric DebugLoc Loop::getStartLoc() const { return getLocRange().getStart(); }
633b915e9e0SDimitry Andric
getLocRange() const634b915e9e0SDimitry Andric Loop::LocRange Loop::getLocRange() const {
63501095a5dSDimitry Andric // If we have a debug location in the loop ID, then use it.
636b915e9e0SDimitry Andric if (MDNode *LoopID = getLoopID()) {
637b915e9e0SDimitry Andric DebugLoc Start;
638b915e9e0SDimitry Andric // We use the first DebugLoc in the header as the start location of the loop
639b915e9e0SDimitry Andric // and if there is a second DebugLoc in the header we use it as end location
640b915e9e0SDimitry Andric // of the loop.
641ac9a064cSDimitry Andric for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
642ac9a064cSDimitry Andric if (DILocation *L = dyn_cast<DILocation>(MDO)) {
643b915e9e0SDimitry Andric if (!Start)
644b915e9e0SDimitry Andric Start = DebugLoc(L);
645b915e9e0SDimitry Andric else
646b915e9e0SDimitry Andric return LocRange(Start, DebugLoc(L));
647b915e9e0SDimitry Andric }
648b915e9e0SDimitry Andric }
649b915e9e0SDimitry Andric
650b915e9e0SDimitry Andric if (Start)
651b915e9e0SDimitry Andric return LocRange(Start);
652b915e9e0SDimitry Andric }
6534a16efa3SDimitry Andric
65401095a5dSDimitry Andric // Try the pre-header first.
65501095a5dSDimitry Andric if (BasicBlock *PHeadBB = getLoopPreheader())
65601095a5dSDimitry Andric if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
657b915e9e0SDimitry Andric return LocRange(DL);
65801095a5dSDimitry Andric
65901095a5dSDimitry Andric // If we have no pre-header or there are no instructions with debug
66001095a5dSDimitry Andric // info in it, try the header.
66101095a5dSDimitry Andric if (BasicBlock *HeadBB = getHeader())
662b915e9e0SDimitry Andric return LocRange(HeadBB->getTerminator()->getDebugLoc());
66301095a5dSDimitry Andric
664b915e9e0SDimitry Andric return LocRange();
66501095a5dSDimitry Andric }
66601095a5dSDimitry Andric
getLocStr() const667ac9a064cSDimitry Andric std::string Loop::getLocStr() const {
668ac9a064cSDimitry Andric std::string Result;
669ac9a064cSDimitry Andric raw_string_ostream OS(Result);
670ac9a064cSDimitry Andric if (const DebugLoc LoopDbgLoc = getStartLoc())
671ac9a064cSDimitry Andric LoopDbgLoc.print(OS);
672ac9a064cSDimitry Andric else
673ac9a064cSDimitry Andric // Just print the module name.
674ac9a064cSDimitry Andric OS << getHeader()->getParent()->getParent()->getModuleIdentifier();
675ac9a064cSDimitry Andric return Result;
676ac9a064cSDimitry Andric }
677ac9a064cSDimitry Andric
678522600a2SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const679044eb2f6SDimitry Andric LLVM_DUMP_METHOD void Loop::dump() const { print(dbgs()); }
680b915e9e0SDimitry Andric
dumpVerbose() const681b915e9e0SDimitry Andric LLVM_DUMP_METHOD void Loop::dumpVerbose() const {
682344a3780SDimitry Andric print(dbgs(), /*Verbose=*/true);
683b915e9e0SDimitry Andric }
684522600a2SDimitry Andric #endif
685829000e0SRoman Divacky
686009b1c42SEd Schouten //===----------------------------------------------------------------------===//
68730815c53SDimitry Andric // UnloopUpdater implementation
68830815c53SDimitry Andric //
68930815c53SDimitry Andric
69030815c53SDimitry Andric namespace {
69130815c53SDimitry Andric /// Find the new parent loop for all blocks within the "unloop" whose last
69230815c53SDimitry Andric /// backedges has just been removed.
69330815c53SDimitry Andric class UnloopUpdater {
69401095a5dSDimitry Andric Loop &Unloop;
69530815c53SDimitry Andric LoopInfo *LI;
69630815c53SDimitry Andric
69730815c53SDimitry Andric LoopBlocksDFS DFS;
69830815c53SDimitry Andric
69930815c53SDimitry Andric // Map unloop's immediate subloops to their nearest reachable parents. Nested
70030815c53SDimitry Andric // loops within these subloops will not change parents. However, an immediate
70130815c53SDimitry Andric // subloop's new parent will be the nearest loop reachable from either its own
70230815c53SDimitry Andric // exits *or* any of its nested loop's exits.
70330815c53SDimitry Andric DenseMap<Loop *, Loop *> SubloopParents;
70430815c53SDimitry Andric
70530815c53SDimitry Andric // Flag the presence of an irreducible backedge whose destination is a block
70630815c53SDimitry Andric // directly contained by the original unloop.
7076f8fc217SDimitry Andric bool FoundIB = false;
70830815c53SDimitry Andric
70930815c53SDimitry Andric public:
UnloopUpdater(Loop * UL,LoopInfo * LInfo)7106f8fc217SDimitry Andric UnloopUpdater(Loop *UL, LoopInfo *LInfo) : Unloop(*UL), LI(LInfo), DFS(UL) {}
71130815c53SDimitry Andric
71230815c53SDimitry Andric void updateBlockParents();
71330815c53SDimitry Andric
71430815c53SDimitry Andric void removeBlocksFromAncestors();
71530815c53SDimitry Andric
71630815c53SDimitry Andric void updateSubloopParents();
71730815c53SDimitry Andric
71830815c53SDimitry Andric protected:
71930815c53SDimitry Andric Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
72030815c53SDimitry Andric };
72130815c53SDimitry Andric } // end anonymous namespace
72230815c53SDimitry Andric
72301095a5dSDimitry Andric /// Update the parent loop for all blocks that are directly contained within the
72401095a5dSDimitry Andric /// original "unloop".
updateBlockParents()72530815c53SDimitry Andric void UnloopUpdater::updateBlockParents() {
72601095a5dSDimitry Andric if (Unloop.getNumBlocks()) {
72730815c53SDimitry Andric // Perform a post order CFG traversal of all blocks within this loop,
728ca089b24SDimitry Andric // propagating the nearest loop from successors to predecessors.
72930815c53SDimitry Andric LoopBlocksTraversal Traversal(DFS, LI);
73001095a5dSDimitry Andric for (BasicBlock *POI : Traversal) {
73130815c53SDimitry Andric
73201095a5dSDimitry Andric Loop *L = LI->getLoopFor(POI);
73301095a5dSDimitry Andric Loop *NL = getNearestLoop(POI, L);
73430815c53SDimitry Andric
73530815c53SDimitry Andric if (NL != L) {
73630815c53SDimitry Andric // For reducible loops, NL is now an ancestor of Unloop.
73701095a5dSDimitry Andric assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
73830815c53SDimitry Andric "uninitialized successor");
73901095a5dSDimitry Andric LI->changeLoopFor(POI, NL);
740044eb2f6SDimitry Andric } else {
74130815c53SDimitry Andric // Or the current block is part of a subloop, in which case its parent
74230815c53SDimitry Andric // is unchanged.
74301095a5dSDimitry Andric assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
74430815c53SDimitry Andric }
74530815c53SDimitry Andric }
74630815c53SDimitry Andric }
74730815c53SDimitry Andric // Each irreducible loop within the unloop induces a round of iteration using
74830815c53SDimitry Andric // the DFS result cached by Traversal.
74930815c53SDimitry Andric bool Changed = FoundIB;
75030815c53SDimitry Andric for (unsigned NIters = 0; Changed; ++NIters) {
75101095a5dSDimitry Andric assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
752145449b1SDimitry Andric (void)NIters;
75330815c53SDimitry Andric
75430815c53SDimitry Andric // Iterate over the postorder list of blocks, propagating the nearest loop
75530815c53SDimitry Andric // from successors to predecessors as before.
75630815c53SDimitry Andric Changed = false;
75730815c53SDimitry Andric for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
758044eb2f6SDimitry Andric POE = DFS.endPostorder();
759044eb2f6SDimitry Andric POI != POE; ++POI) {
76030815c53SDimitry Andric
76130815c53SDimitry Andric Loop *L = LI->getLoopFor(*POI);
76230815c53SDimitry Andric Loop *NL = getNearestLoop(*POI, L);
76330815c53SDimitry Andric if (NL != L) {
76401095a5dSDimitry Andric assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
76530815c53SDimitry Andric "uninitialized successor");
76630815c53SDimitry Andric LI->changeLoopFor(*POI, NL);
76730815c53SDimitry Andric Changed = true;
76830815c53SDimitry Andric }
76930815c53SDimitry Andric }
77030815c53SDimitry Andric }
77130815c53SDimitry Andric }
77230815c53SDimitry Andric
77301095a5dSDimitry Andric /// Remove unloop's blocks from all ancestors below their new parents.
removeBlocksFromAncestors()77430815c53SDimitry Andric void UnloopUpdater::removeBlocksFromAncestors() {
77563faed5bSDimitry Andric // Remove all unloop's blocks (including those in nested subloops) from
77663faed5bSDimitry Andric // ancestors below the new parent loop.
777344a3780SDimitry Andric for (BasicBlock *BB : Unloop.blocks()) {
778344a3780SDimitry Andric Loop *OuterParent = LI->getLoopFor(BB);
77901095a5dSDimitry Andric if (Unloop.contains(OuterParent)) {
78001095a5dSDimitry Andric while (OuterParent->getParentLoop() != &Unloop)
78163faed5bSDimitry Andric OuterParent = OuterParent->getParentLoop();
78263faed5bSDimitry Andric OuterParent = SubloopParents[OuterParent];
78363faed5bSDimitry Andric }
78430815c53SDimitry Andric // Remove blocks from former Ancestors except Unloop itself which will be
78530815c53SDimitry Andric // deleted.
78601095a5dSDimitry Andric for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
78730815c53SDimitry Andric OldParent = OldParent->getParentLoop()) {
78830815c53SDimitry Andric assert(OldParent && "new loop is not an ancestor of the original");
789344a3780SDimitry Andric OldParent->removeBlockFromLoop(BB);
79030815c53SDimitry Andric }
79130815c53SDimitry Andric }
79230815c53SDimitry Andric }
79330815c53SDimitry Andric
79401095a5dSDimitry Andric /// Update the parent loop for all subloops directly nested within unloop.
updateSubloopParents()79530815c53SDimitry Andric void UnloopUpdater::updateSubloopParents() {
796b60736ecSDimitry Andric while (!Unloop.isInnermost()) {
79701095a5dSDimitry Andric Loop *Subloop = *std::prev(Unloop.end());
79801095a5dSDimitry Andric Unloop.removeChildLoop(std::prev(Unloop.end()));
79930815c53SDimitry Andric
80030815c53SDimitry Andric assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
801522600a2SDimitry Andric if (Loop *Parent = SubloopParents[Subloop])
802522600a2SDimitry Andric Parent->addChildLoop(Subloop);
80330815c53SDimitry Andric else
80430815c53SDimitry Andric LI->addTopLevelLoop(Subloop);
80530815c53SDimitry Andric }
80630815c53SDimitry Andric }
80730815c53SDimitry Andric
80801095a5dSDimitry Andric /// Return the nearest parent loop among this block's successors. If a successor
80901095a5dSDimitry Andric /// is a subloop header, consider its parent to be the nearest parent of the
81001095a5dSDimitry Andric /// subloop's exits.
81130815c53SDimitry Andric ///
81230815c53SDimitry Andric /// For subloop blocks, simply update SubloopParents and return NULL.
getNearestLoop(BasicBlock * BB,Loop * BBLoop)81330815c53SDimitry Andric Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
81430815c53SDimitry Andric
81530815c53SDimitry Andric // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
81630815c53SDimitry Andric // is considered uninitialized.
81730815c53SDimitry Andric Loop *NearLoop = BBLoop;
81830815c53SDimitry Andric
8195ca98fd9SDimitry Andric Loop *Subloop = nullptr;
82001095a5dSDimitry Andric if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
82130815c53SDimitry Andric Subloop = NearLoop;
82230815c53SDimitry Andric // Find the subloop ancestor that is directly contained within Unloop.
82301095a5dSDimitry Andric while (Subloop->getParentLoop() != &Unloop) {
82430815c53SDimitry Andric Subloop = Subloop->getParentLoop();
82530815c53SDimitry Andric assert(Subloop && "subloop is not an ancestor of the original loop");
82630815c53SDimitry Andric }
82730815c53SDimitry Andric // Get the current nearest parent of the Subloop exits, initially Unloop.
828b915e9e0SDimitry Andric NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second;
82930815c53SDimitry Andric }
83030815c53SDimitry Andric
831ac9a064cSDimitry Andric if (succ_empty(BB)) {
83230815c53SDimitry Andric assert(!Subloop && "subloop blocks must have a successor");
8335ca98fd9SDimitry Andric NearLoop = nullptr; // unloop blocks may now exit the function.
83430815c53SDimitry Andric }
835ac9a064cSDimitry Andric for (BasicBlock *Succ : successors(BB)) {
836ac9a064cSDimitry Andric if (Succ == BB)
83730815c53SDimitry Andric continue; // self loops are uninteresting
83830815c53SDimitry Andric
839ac9a064cSDimitry Andric Loop *L = LI->getLoopFor(Succ);
84001095a5dSDimitry Andric if (L == &Unloop) {
84130815c53SDimitry Andric // This successor has not been processed. This path must lead to an
84230815c53SDimitry Andric // irreducible backedge.
843ac9a064cSDimitry Andric assert((FoundIB || !DFS.hasPostorder(Succ)) && "should have seen IB");
84430815c53SDimitry Andric FoundIB = true;
84530815c53SDimitry Andric }
84601095a5dSDimitry Andric if (L != &Unloop && Unloop.contains(L)) {
84730815c53SDimitry Andric // Successor is in a subloop.
84830815c53SDimitry Andric if (Subloop)
84930815c53SDimitry Andric continue; // Branching within subloops. Ignore it.
85030815c53SDimitry Andric
85130815c53SDimitry Andric // BB branches from the original into a subloop header.
85201095a5dSDimitry Andric assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
85330815c53SDimitry Andric
85430815c53SDimitry Andric // Get the current nearest parent of the Subloop's exits.
85530815c53SDimitry Andric L = SubloopParents[L];
85630815c53SDimitry Andric // L could be Unloop if the only exit was an irreducible backedge.
85730815c53SDimitry Andric }
85801095a5dSDimitry Andric if (L == &Unloop) {
85930815c53SDimitry Andric continue;
86030815c53SDimitry Andric }
86130815c53SDimitry Andric // Handle critical edges from Unloop into a sibling loop.
86201095a5dSDimitry Andric if (L && !L->contains(&Unloop)) {
86330815c53SDimitry Andric L = L->getParentLoop();
86430815c53SDimitry Andric }
86530815c53SDimitry Andric // Remember the nearest parent loop among successors or subloop exits.
86601095a5dSDimitry Andric if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
86730815c53SDimitry Andric NearLoop = L;
86830815c53SDimitry Andric }
86930815c53SDimitry Andric if (Subloop) {
87030815c53SDimitry Andric SubloopParents[Subloop] = NearLoop;
87130815c53SDimitry Andric return BBLoop;
87230815c53SDimitry Andric }
87330815c53SDimitry Andric return NearLoop;
87430815c53SDimitry Andric }
87530815c53SDimitry Andric
LoopInfo(const DomTreeBase<BasicBlock> & DomTree)876044eb2f6SDimitry Andric LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); }
877dd58ef01SDimitry Andric
invalidate(Function & F,const PreservedAnalyses & PA,FunctionAnalysisManager::Invalidator &)87871d5a254SDimitry Andric bool LoopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
87971d5a254SDimitry Andric FunctionAnalysisManager::Invalidator &) {
88071d5a254SDimitry Andric // Check whether the analysis, all analyses on functions, or the function's
88171d5a254SDimitry Andric // CFG have been preserved.
88271d5a254SDimitry Andric auto PAC = PA.getChecker<LoopAnalysis>();
88371d5a254SDimitry Andric return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
88471d5a254SDimitry Andric PAC.preservedSet<CFGAnalyses>());
88571d5a254SDimitry Andric }
88671d5a254SDimitry Andric
erase(Loop * Unloop)887044eb2f6SDimitry Andric void LoopInfo::erase(Loop *Unloop) {
888044eb2f6SDimitry Andric assert(!Unloop->isInvalid() && "Loop has already been erased!");
889044eb2f6SDimitry Andric
890044eb2f6SDimitry Andric auto InvalidateOnExit = make_scope_exit([&]() { destroy(Unloop); });
89130815c53SDimitry Andric
89230815c53SDimitry Andric // First handle the special case of no parent loop to simplify the algorithm.
893b60736ecSDimitry Andric if (Unloop->isOutermost()) {
89430815c53SDimitry Andric // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
895344a3780SDimitry Andric for (BasicBlock *BB : Unloop->blocks()) {
89630815c53SDimitry Andric // Don't reparent blocks in subloops.
897344a3780SDimitry Andric if (getLoopFor(BB) != Unloop)
89830815c53SDimitry Andric continue;
89930815c53SDimitry Andric
90030815c53SDimitry Andric // Blocks no longer have a parent but are still referenced by Unloop until
90130815c53SDimitry Andric // the Unloop object is deleted.
902344a3780SDimitry Andric changeLoopFor(BB, nullptr);
90330815c53SDimitry Andric }
90430815c53SDimitry Andric
90530815c53SDimitry Andric // Remove the loop from the top-level LoopInfo object.
9065a5ac124SDimitry Andric for (iterator I = begin();; ++I) {
9075a5ac124SDimitry Andric assert(I != end() && "Couldn't find loop");
90830815c53SDimitry Andric if (*I == Unloop) {
9095a5ac124SDimitry Andric removeLoop(I);
91030815c53SDimitry Andric break;
91130815c53SDimitry Andric }
91230815c53SDimitry Andric }
91330815c53SDimitry Andric
91430815c53SDimitry Andric // Move all of the subloops to the top-level.
915b60736ecSDimitry Andric while (!Unloop->isInnermost())
9165a5ac124SDimitry Andric addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
91730815c53SDimitry Andric
91830815c53SDimitry Andric return;
91930815c53SDimitry Andric }
92030815c53SDimitry Andric
92130815c53SDimitry Andric // Update the parent loop for all blocks within the loop. Blocks within
92230815c53SDimitry Andric // subloops will not change parents.
92330815c53SDimitry Andric UnloopUpdater Updater(Unloop, this);
92430815c53SDimitry Andric Updater.updateBlockParents();
92530815c53SDimitry Andric
92630815c53SDimitry Andric // Remove blocks from former ancestor loops.
92730815c53SDimitry Andric Updater.removeBlocksFromAncestors();
92830815c53SDimitry Andric
92930815c53SDimitry Andric // Add direct subloops as children in their new parent loop.
93030815c53SDimitry Andric Updater.updateSubloopParents();
93130815c53SDimitry Andric
93230815c53SDimitry Andric // Remove unloop from its parent loop.
93330815c53SDimitry Andric Loop *ParentLoop = Unloop->getParentLoop();
93430815c53SDimitry Andric for (Loop::iterator I = ParentLoop->begin();; ++I) {
93530815c53SDimitry Andric assert(I != ParentLoop->end() && "Couldn't find loop");
93630815c53SDimitry Andric if (*I == Unloop) {
93730815c53SDimitry Andric ParentLoop->removeChildLoop(I);
93830815c53SDimitry Andric break;
93930815c53SDimitry Andric }
94030815c53SDimitry Andric }
94130815c53SDimitry Andric }
94230815c53SDimitry Andric
wouldBeOutOfLoopUseRequiringLCSSA(const Value * V,const BasicBlock * ExitBB) const9437fa27ce4SDimitry Andric bool LoopInfo::wouldBeOutOfLoopUseRequiringLCSSA(
9447fa27ce4SDimitry Andric const Value *V, const BasicBlock *ExitBB) const {
945344a3780SDimitry Andric if (V->getType()->isTokenTy())
946344a3780SDimitry Andric // We can't form PHIs of token type, so the definition of LCSSA excludes
947344a3780SDimitry Andric // values of that type.
948344a3780SDimitry Andric return false;
949344a3780SDimitry Andric
950344a3780SDimitry Andric const Instruction *I = dyn_cast<Instruction>(V);
951344a3780SDimitry Andric if (!I)
952344a3780SDimitry Andric return false;
953344a3780SDimitry Andric const Loop *L = getLoopFor(I->getParent());
954344a3780SDimitry Andric if (!L)
955344a3780SDimitry Andric return false;
956344a3780SDimitry Andric if (L->contains(ExitBB))
957344a3780SDimitry Andric // Could be an exit bb of a subloop and contained in defining loop
958344a3780SDimitry Andric return false;
959344a3780SDimitry Andric
960344a3780SDimitry Andric // We found a (new) out-of-loop use location, for a value defined in-loop.
961344a3780SDimitry Andric // (Note that because of LCSSA, we don't have to account for values defined
962344a3780SDimitry Andric // in sibling loops. Such values will have LCSSA phis of their own in the
963344a3780SDimitry Andric // common parent loop.)
964344a3780SDimitry Andric return true;
965344a3780SDimitry Andric }
966344a3780SDimitry Andric
967b915e9e0SDimitry Andric AnalysisKey LoopAnalysis::Key;
9685a5ac124SDimitry Andric
run(Function & F,FunctionAnalysisManager & AM)969b915e9e0SDimitry Andric LoopInfo LoopAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
9705a5ac124SDimitry Andric // FIXME: Currently we create a LoopInfo from scratch for every function.
9715a5ac124SDimitry Andric // This may prove to be too wasteful due to deallocating and re-allocating
9725a5ac124SDimitry Andric // memory each time for the underlying map and vector datastructures. At some
9735a5ac124SDimitry Andric // point it may prove worthwhile to use a freelist and recycle LoopInfo
9745a5ac124SDimitry Andric // objects. I don't want to add that kind of complexity until the scope of
9755a5ac124SDimitry Andric // the problem is better understood.
9765a5ac124SDimitry Andric LoopInfo LI;
97701095a5dSDimitry Andric LI.analyze(AM.getResult<DominatorTreeAnalysis>(F));
9785a5ac124SDimitry Andric return LI;
9795a5ac124SDimitry Andric }
9805a5ac124SDimitry Andric
run(Function & F,FunctionAnalysisManager & AM)9815a5ac124SDimitry Andric PreservedAnalyses LoopPrinterPass::run(Function &F,
982b915e9e0SDimitry Andric FunctionAnalysisManager &AM) {
983aca2e42cSDimitry Andric auto &LI = AM.getResult<LoopAnalysis>(F);
984aca2e42cSDimitry Andric OS << "Loop info for function '" << F.getName() << "':\n";
985aca2e42cSDimitry Andric LI.print(OS);
9865a5ac124SDimitry Andric return PreservedAnalyses::all();
9875a5ac124SDimitry Andric }
9885a5ac124SDimitry Andric
printLoop(Loop & L,raw_ostream & OS,const std::string & Banner)989581a6d85SDimitry Andric void llvm::printLoop(Loop &L, raw_ostream &OS, const std::string &Banner) {
990044eb2f6SDimitry Andric
991044eb2f6SDimitry Andric if (forcePrintModuleIR()) {
992044eb2f6SDimitry Andric // handling -print-module-scope
993044eb2f6SDimitry Andric OS << Banner << " (loop: ";
994044eb2f6SDimitry Andric L.getHeader()->printAsOperand(OS, false);
995044eb2f6SDimitry Andric OS << ")\n";
996044eb2f6SDimitry Andric
997044eb2f6SDimitry Andric // printing whole module
998044eb2f6SDimitry Andric OS << *L.getHeader()->getModule();
999044eb2f6SDimitry Andric return;
1000044eb2f6SDimitry Andric }
1001044eb2f6SDimitry Andric
1002dd58ef01SDimitry Andric OS << Banner;
1003044eb2f6SDimitry Andric
1004044eb2f6SDimitry Andric auto *PreHeader = L.getLoopPreheader();
1005044eb2f6SDimitry Andric if (PreHeader) {
1006044eb2f6SDimitry Andric OS << "\n; Preheader:";
1007044eb2f6SDimitry Andric PreHeader->print(OS);
1008044eb2f6SDimitry Andric OS << "\n; Loop:";
1009044eb2f6SDimitry Andric }
1010044eb2f6SDimitry Andric
1011dd58ef01SDimitry Andric for (auto *Block : L.blocks())
1012dd58ef01SDimitry Andric if (Block)
1013dd58ef01SDimitry Andric Block->print(OS);
1014dd58ef01SDimitry Andric else
1015dd58ef01SDimitry Andric OS << "Printing <null> block";
1016044eb2f6SDimitry Andric
1017044eb2f6SDimitry Andric SmallVector<BasicBlock *, 8> ExitBlocks;
1018044eb2f6SDimitry Andric L.getExitBlocks(ExitBlocks);
1019044eb2f6SDimitry Andric if (!ExitBlocks.empty()) {
1020044eb2f6SDimitry Andric OS << "\n; Exit blocks";
1021044eb2f6SDimitry Andric for (auto *Block : ExitBlocks)
1022044eb2f6SDimitry Andric if (Block)
1023044eb2f6SDimitry Andric Block->print(OS);
1024044eb2f6SDimitry Andric else
1025044eb2f6SDimitry Andric OS << "Printing <null> block";
1026044eb2f6SDimitry Andric }
1027dd58ef01SDimitry Andric }
1028dd58ef01SDimitry Andric
findOptionMDForLoopID(MDNode * LoopID,StringRef Name)1029d8e91e46SDimitry Andric MDNode *llvm::findOptionMDForLoopID(MDNode *LoopID, StringRef Name) {
1030d8e91e46SDimitry Andric // No loop metadata node, no loop properties.
1031d8e91e46SDimitry Andric if (!LoopID)
1032d8e91e46SDimitry Andric return nullptr;
1033d8e91e46SDimitry Andric
1034d8e91e46SDimitry Andric // First operand should refer to the metadata node itself, for legacy reasons.
1035d8e91e46SDimitry Andric assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1036d8e91e46SDimitry Andric assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1037d8e91e46SDimitry Andric
1038d8e91e46SDimitry Andric // Iterate over the metdata node operands and look for MDString metadata.
1039ac9a064cSDimitry Andric for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
1040ac9a064cSDimitry Andric MDNode *MD = dyn_cast<MDNode>(MDO);
1041d8e91e46SDimitry Andric if (!MD || MD->getNumOperands() < 1)
1042d8e91e46SDimitry Andric continue;
1043d8e91e46SDimitry Andric MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1044d8e91e46SDimitry Andric if (!S)
1045d8e91e46SDimitry Andric continue;
1046d8e91e46SDimitry Andric // Return the operand node if MDString holds expected metadata.
1047ac9a064cSDimitry Andric if (Name == S->getString())
1048d8e91e46SDimitry Andric return MD;
1049d8e91e46SDimitry Andric }
1050d8e91e46SDimitry Andric
1051d8e91e46SDimitry Andric // Loop property not found.
1052d8e91e46SDimitry Andric return nullptr;
1053d8e91e46SDimitry Andric }
1054d8e91e46SDimitry Andric
findOptionMDForLoop(const Loop * TheLoop,StringRef Name)1055d8e91e46SDimitry Andric MDNode *llvm::findOptionMDForLoop(const Loop *TheLoop, StringRef Name) {
1056d8e91e46SDimitry Andric return findOptionMDForLoopID(TheLoop->getLoopID(), Name);
1057d8e91e46SDimitry Andric }
1058d8e91e46SDimitry Andric
1059344a3780SDimitry Andric /// Find string metadata for loop
1060344a3780SDimitry Andric ///
1061344a3780SDimitry Andric /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
1062344a3780SDimitry Andric /// operand or null otherwise. If the string metadata is not found return
1063344a3780SDimitry Andric /// Optional's not-a-value.
1064e3b55780SDimitry Andric std::optional<const MDOperand *>
findStringMetadataForLoop(const Loop * TheLoop,StringRef Name)1065e3b55780SDimitry Andric llvm::findStringMetadataForLoop(const Loop *TheLoop, StringRef Name) {
1066344a3780SDimitry Andric MDNode *MD = findOptionMDForLoop(TheLoop, Name);
1067344a3780SDimitry Andric if (!MD)
1068e3b55780SDimitry Andric return std::nullopt;
1069344a3780SDimitry Andric switch (MD->getNumOperands()) {
1070344a3780SDimitry Andric case 1:
1071344a3780SDimitry Andric return nullptr;
1072344a3780SDimitry Andric case 2:
1073344a3780SDimitry Andric return &MD->getOperand(1);
1074344a3780SDimitry Andric default:
1075344a3780SDimitry Andric llvm_unreachable("loop metadata has 0 or 1 operand");
1076344a3780SDimitry Andric }
1077344a3780SDimitry Andric }
1078344a3780SDimitry Andric
getOptionalBoolLoopAttribute(const Loop * TheLoop,StringRef Name)1079e3b55780SDimitry Andric std::optional<bool> llvm::getOptionalBoolLoopAttribute(const Loop *TheLoop,
1080344a3780SDimitry Andric StringRef Name) {
1081344a3780SDimitry Andric MDNode *MD = findOptionMDForLoop(TheLoop, Name);
1082344a3780SDimitry Andric if (!MD)
1083e3b55780SDimitry Andric return std::nullopt;
1084344a3780SDimitry Andric switch (MD->getNumOperands()) {
1085344a3780SDimitry Andric case 1:
1086344a3780SDimitry Andric // When the value is absent it is interpreted as 'attribute set'.
1087344a3780SDimitry Andric return true;
1088344a3780SDimitry Andric case 2:
1089344a3780SDimitry Andric if (ConstantInt *IntMD =
1090344a3780SDimitry Andric mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get()))
1091344a3780SDimitry Andric return IntMD->getZExtValue();
1092344a3780SDimitry Andric return true;
1093344a3780SDimitry Andric }
1094344a3780SDimitry Andric llvm_unreachable("unexpected number of options");
1095344a3780SDimitry Andric }
1096344a3780SDimitry Andric
getBooleanLoopAttribute(const Loop * TheLoop,StringRef Name)1097344a3780SDimitry Andric bool llvm::getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) {
1098145449b1SDimitry Andric return getOptionalBoolLoopAttribute(TheLoop, Name).value_or(false);
1099344a3780SDimitry Andric }
1100344a3780SDimitry Andric
getOptionalIntLoopAttribute(const Loop * TheLoop,StringRef Name)1101e3b55780SDimitry Andric std::optional<int> llvm::getOptionalIntLoopAttribute(const Loop *TheLoop,
1102344a3780SDimitry Andric StringRef Name) {
1103344a3780SDimitry Andric const MDOperand *AttrMD =
1104145449b1SDimitry Andric findStringMetadataForLoop(TheLoop, Name).value_or(nullptr);
1105344a3780SDimitry Andric if (!AttrMD)
1106e3b55780SDimitry Andric return std::nullopt;
1107344a3780SDimitry Andric
1108344a3780SDimitry Andric ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
1109344a3780SDimitry Andric if (!IntMD)
1110e3b55780SDimitry Andric return std::nullopt;
1111344a3780SDimitry Andric
1112344a3780SDimitry Andric return IntMD->getSExtValue();
1113344a3780SDimitry Andric }
1114344a3780SDimitry Andric
getIntLoopAttribute(const Loop * TheLoop,StringRef Name,int Default)1115c0981da4SDimitry Andric int llvm::getIntLoopAttribute(const Loop *TheLoop, StringRef Name,
1116c0981da4SDimitry Andric int Default) {
1117145449b1SDimitry Andric return getOptionalIntLoopAttribute(TheLoop, Name).value_or(Default);
1118c0981da4SDimitry Andric }
1119c0981da4SDimitry Andric
getLoopConvergenceHeart(const Loop * TheLoop)1120ac9a064cSDimitry Andric CallBase *llvm::getLoopConvergenceHeart(const Loop *TheLoop) {
1121ac9a064cSDimitry Andric BasicBlock *H = TheLoop->getHeader();
1122ac9a064cSDimitry Andric for (Instruction &II : *H) {
1123ac9a064cSDimitry Andric if (auto *CB = dyn_cast<CallBase>(&II)) {
1124ac9a064cSDimitry Andric if (!CB->isConvergent())
1125ac9a064cSDimitry Andric continue;
1126ac9a064cSDimitry Andric // This is the heart if it uses a token defined outside the loop. The
1127ac9a064cSDimitry Andric // verifier has already checked that only the loop intrinsic can use such
1128ac9a064cSDimitry Andric // a token.
1129ac9a064cSDimitry Andric if (auto *Token = CB->getConvergenceControlToken()) {
1130ac9a064cSDimitry Andric auto *TokenDef = cast<Instruction>(Token);
1131ac9a064cSDimitry Andric if (!TheLoop->contains(TokenDef->getParent()))
1132ac9a064cSDimitry Andric return CB;
1133ac9a064cSDimitry Andric }
1134ac9a064cSDimitry Andric return nullptr;
1135ac9a064cSDimitry Andric }
1136ac9a064cSDimitry Andric }
1137ac9a064cSDimitry Andric return nullptr;
1138ac9a064cSDimitry Andric }
1139ac9a064cSDimitry Andric
isFinite(const Loop * L)1140ecbca9f5SDimitry Andric bool llvm::isFinite(const Loop *L) {
1141ecbca9f5SDimitry Andric return L->getHeader()->getParent()->willReturn();
1142ecbca9f5SDimitry Andric }
1143ecbca9f5SDimitry Andric
1144344a3780SDimitry Andric static const char *LLVMLoopMustProgress = "llvm.loop.mustprogress";
1145344a3780SDimitry Andric
hasMustProgress(const Loop * L)1146344a3780SDimitry Andric bool llvm::hasMustProgress(const Loop *L) {
1147344a3780SDimitry Andric return getBooleanLoopAttribute(L, LLVMLoopMustProgress);
1148344a3780SDimitry Andric }
1149344a3780SDimitry Andric
isMustProgress(const Loop * L)1150344a3780SDimitry Andric bool llvm::isMustProgress(const Loop *L) {
1151344a3780SDimitry Andric return L->getHeader()->getParent()->mustProgress() || hasMustProgress(L);
1152344a3780SDimitry Andric }
1153344a3780SDimitry Andric
isValidAsAccessGroup(MDNode * Node)1154d8e91e46SDimitry Andric bool llvm::isValidAsAccessGroup(MDNode *Node) {
1155d8e91e46SDimitry Andric return Node->getNumOperands() == 0 && Node->isDistinct();
1156d8e91e46SDimitry Andric }
1157d8e91e46SDimitry Andric
makePostTransformationMetadata(LLVMContext & Context,MDNode * OrigLoopID,ArrayRef<StringRef> RemovePrefixes,ArrayRef<MDNode * > AddAttrs)1158e6d15924SDimitry Andric MDNode *llvm::makePostTransformationMetadata(LLVMContext &Context,
1159e6d15924SDimitry Andric MDNode *OrigLoopID,
1160e6d15924SDimitry Andric ArrayRef<StringRef> RemovePrefixes,
1161e6d15924SDimitry Andric ArrayRef<MDNode *> AddAttrs) {
1162e6d15924SDimitry Andric // First remove any existing loop metadata related to this transformation.
1163e6d15924SDimitry Andric SmallVector<Metadata *, 4> MDs;
1164e6d15924SDimitry Andric
1165e6d15924SDimitry Andric // Reserve first location for self reference to the LoopID metadata node.
1166b60736ecSDimitry Andric MDs.push_back(nullptr);
1167e6d15924SDimitry Andric
1168e6d15924SDimitry Andric // Remove metadata for the transformation that has been applied or that became
1169e6d15924SDimitry Andric // outdated.
1170e6d15924SDimitry Andric if (OrigLoopID) {
1171ac9a064cSDimitry Andric for (const MDOperand &MDO : llvm::drop_begin(OrigLoopID->operands())) {
1172e6d15924SDimitry Andric bool IsVectorMetadata = false;
1173ac9a064cSDimitry Andric Metadata *Op = MDO;
1174e6d15924SDimitry Andric if (MDNode *MD = dyn_cast<MDNode>(Op)) {
1175e6d15924SDimitry Andric const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1176e6d15924SDimitry Andric if (S)
1177e6d15924SDimitry Andric IsVectorMetadata =
1178e6d15924SDimitry Andric llvm::any_of(RemovePrefixes, [S](StringRef Prefix) -> bool {
1179312c0ed1SDimitry Andric return S->getString().starts_with(Prefix);
1180e6d15924SDimitry Andric });
1181e6d15924SDimitry Andric }
1182e6d15924SDimitry Andric if (!IsVectorMetadata)
1183e6d15924SDimitry Andric MDs.push_back(Op);
1184e6d15924SDimitry Andric }
1185e6d15924SDimitry Andric }
1186e6d15924SDimitry Andric
1187e6d15924SDimitry Andric // Add metadata to avoid reapplying a transformation, such as
1188e6d15924SDimitry Andric // llvm.loop.unroll.disable and llvm.loop.isvectorized.
1189e6d15924SDimitry Andric MDs.append(AddAttrs.begin(), AddAttrs.end());
1190e6d15924SDimitry Andric
1191e6d15924SDimitry Andric MDNode *NewLoopID = MDNode::getDistinct(Context, MDs);
1192e6d15924SDimitry Andric // Replace the temporary node with a self-reference.
1193e6d15924SDimitry Andric NewLoopID->replaceOperandWith(0, NewLoopID);
1194e6d15924SDimitry Andric return NewLoopID;
1195e6d15924SDimitry Andric }
1196e6d15924SDimitry Andric
11975a5ac124SDimitry Andric //===----------------------------------------------------------------------===//
11985a5ac124SDimitry Andric // LoopInfo implementation
11995a5ac124SDimitry Andric //
12005a5ac124SDimitry Andric
LoopInfoWrapperPass()1201706b4fc4SDimitry Andric LoopInfoWrapperPass::LoopInfoWrapperPass() : FunctionPass(ID) {
1202706b4fc4SDimitry Andric initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry());
1203706b4fc4SDimitry Andric }
1204706b4fc4SDimitry Andric
12055a5ac124SDimitry Andric char LoopInfoWrapperPass::ID = 0;
12065a5ac124SDimitry Andric INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
12075a5ac124SDimitry Andric true, true)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)12085a5ac124SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
12095a5ac124SDimitry Andric INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
12105a5ac124SDimitry Andric true, true)
12115a5ac124SDimitry Andric
12125a5ac124SDimitry Andric bool LoopInfoWrapperPass::runOnFunction(Function &) {
12135a5ac124SDimitry Andric releaseMemory();
1214dd58ef01SDimitry Andric LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
12155a5ac124SDimitry Andric return false;
12165a5ac124SDimitry Andric }
12175a5ac124SDimitry Andric
verifyAnalysis() const12185a5ac124SDimitry Andric void LoopInfoWrapperPass::verifyAnalysis() const {
12195a5ac124SDimitry Andric // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
12205a5ac124SDimitry Andric // function each time verifyAnalysis is called is very expensive. The
122159850d08SRoman Divacky // -verify-loop-info option can enable this. In order to perform some
12225a5ac124SDimitry Andric // checking by default, LoopPass has been taught to call verifyLoop manually
12235a5ac124SDimitry Andric // during loop pass sequences.
1224b915e9e0SDimitry Andric if (VerifyLoopInfo) {
1225b915e9e0SDimitry Andric auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1226b915e9e0SDimitry Andric LI.verify(DT);
1227b915e9e0SDimitry Andric }
122859850d08SRoman Divacky }
122959850d08SRoman Divacky
getAnalysisUsage(AnalysisUsage & AU) const12305a5ac124SDimitry Andric void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1231009b1c42SEd Schouten AU.setPreservesAll();
1232e6d15924SDimitry Andric AU.addRequiredTransitive<DominatorTreeWrapperPass>();
1233009b1c42SEd Schouten }
123459850d08SRoman Divacky
print(raw_ostream & OS,const Module *) const12355a5ac124SDimitry Andric void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
123659850d08SRoman Divacky LI.print(OS);
123759850d08SRoman Divacky }
123859850d08SRoman Divacky
run(Function & F,FunctionAnalysisManager & AM)1239b915e9e0SDimitry Andric PreservedAnalyses LoopVerifierPass::run(Function &F,
1240b915e9e0SDimitry Andric FunctionAnalysisManager &AM) {
1241b915e9e0SDimitry Andric LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
1242b915e9e0SDimitry Andric auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1243b915e9e0SDimitry Andric LI.verify(DT);
1244b915e9e0SDimitry Andric return PreservedAnalyses::all();
1245b915e9e0SDimitry Andric }
1246b915e9e0SDimitry Andric
124730815c53SDimitry Andric //===----------------------------------------------------------------------===//
124830815c53SDimitry Andric // LoopBlocksDFS implementation
124930815c53SDimitry Andric //
125030815c53SDimitry Andric
125130815c53SDimitry Andric /// Traverse the loop blocks and store the DFS result.
125230815c53SDimitry Andric /// Useful for clients that just want the final DFS result and don't need to
125330815c53SDimitry Andric /// visit blocks during the initial traversal.
perform(const LoopInfo * LI)1254b1c73532SDimitry Andric void LoopBlocksDFS::perform(const LoopInfo *LI) {
125530815c53SDimitry Andric LoopBlocksTraversal Traversal(*this, LI);
125630815c53SDimitry Andric for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
1257044eb2f6SDimitry Andric POE = Traversal.end();
1258044eb2f6SDimitry Andric POI != POE; ++POI)
1259044eb2f6SDimitry Andric ;
126030815c53SDimitry Andric }
1261