1 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the LoopInfo class that is used to identify natural loops
11 // and determine the loop depth of various nodes of the CFG. Note that the
12 // loops identified may actually be several natural loops that share the same
13 // header node... not just a single natural loop.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/Support/CFG.h"
23 #include "Support/DepthFirstIterator.h"
27 static RegisterAnalysis<LoopInfo>
28 X("loops", "Natural Loop Construction", true);
30 //===----------------------------------------------------------------------===//
31 // Loop implementation
33 bool Loop::contains(const BasicBlock *BB) const {
34 return find(Blocks.begin(), Blocks.end(), BB) != Blocks.end();
37 bool Loop::isLoopExit(const BasicBlock *BB) const {
38 for (succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB);
46 /// getNumBackEdges - Calculate the number of back edges to the loop header.
48 unsigned Loop::getNumBackEdges() const {
49 unsigned NumBackEdges = 0;
50 BasicBlock *H = getHeader();
52 for (pred_iterator I = pred_begin(H), E = pred_end(H); I != E; ++I)
59 void Loop::print(std::ostream &OS, unsigned Depth) const {
60 OS << std::string(Depth*2, ' ') << "Loop Containing: ";
62 for (unsigned i = 0; i < getBlocks().size(); ++i) {
64 WriteAsOperand(OS, getBlocks()[i], false);
68 for (iterator I = begin(), E = end(); I != E; ++I)
69 (*I)->print(OS, Depth+2);
72 void Loop::dump() const {
77 //===----------------------------------------------------------------------===//
78 // LoopInfo implementation
80 void LoopInfo::stub() {}
82 bool LoopInfo::runOnFunction(Function &) {
84 Calculate(getAnalysis<DominatorSet>()); // Update
88 void LoopInfo::releaseMemory() {
89 for (std::vector<Loop*>::iterator I = TopLevelLoops.begin(),
90 E = TopLevelLoops.end(); I != E; ++I)
91 delete *I; // Delete all of the loops...
93 BBMap.clear(); // Reset internal state of analysis
94 TopLevelLoops.clear();
98 void LoopInfo::Calculate(const DominatorSet &DS) {
99 BasicBlock *RootNode = DS.getRoot();
101 for (df_iterator<BasicBlock*> NI = df_begin(RootNode),
102 NE = df_end(RootNode); NI != NE; ++NI)
103 if (Loop *L = ConsiderForLoop(*NI, DS))
104 TopLevelLoops.push_back(L);
106 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
107 TopLevelLoops[i]->setLoopDepth(1);
110 void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
111 AU.setPreservesAll();
112 AU.addRequired<DominatorSet>();
115 void LoopInfo::print(std::ostream &OS) const {
116 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
117 TopLevelLoops[i]->print(OS);
119 for (std::map<BasicBlock*, Loop*>::const_iterator I = BBMap.begin(),
120 E = BBMap.end(); I != E; ++I)
121 OS << "BB '" << I->first->getName() << "' level = "
122 << I->second->LoopDepth << "\n";
126 static bool isNotAlreadyContainedIn(Loop *SubLoop, Loop *ParentLoop) {
127 if (SubLoop == 0) return true;
128 if (SubLoop == ParentLoop) return false;
129 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
132 Loop *LoopInfo::ConsiderForLoop(BasicBlock *BB, const DominatorSet &DS) {
133 if (BBMap.find(BB) != BBMap.end()) return 0; // Haven't processed this node?
135 std::vector<BasicBlock *> TodoStack;
137 // Scan the predecessors of BB, checking to see if BB dominates any of
138 // them. This identifies backedges which target this node...
139 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
140 if (DS.dominates(BB, *I)) // If BB dominates it's predecessor...
141 TodoStack.push_back(*I);
143 if (TodoStack.empty()) return 0; // No backedges to this block...
145 // Create a new loop to represent this basic block...
146 Loop *L = new Loop(BB);
149 BasicBlock *EntryBlock = &BB->getParent()->getEntryBlock();
151 while (!TodoStack.empty()) { // Process all the nodes in the loop
152 BasicBlock *X = TodoStack.back();
153 TodoStack.pop_back();
155 if (!L->contains(X) && // As of yet unprocessed??
156 DS.dominates(EntryBlock, X)) { // X is reachable from entry block?
157 // Check to see if this block already belongs to a loop. If this occurs
158 // then we have a case where a loop that is supposed to be a child of the
159 // current loop was processed before the current loop. When this occurs,
160 // this child loop gets added to a part of the current loop, making it a
161 // sibling to the current loop. We have to reparent this loop.
162 if (Loop *SubLoop = const_cast<Loop*>(getLoopFor(X)))
163 if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)) {
164 // Remove the subloop from it's current parent...
165 assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
166 Loop *SLP = SubLoop->ParentLoop; // SubLoopParent
167 std::vector<Loop*>::iterator I =
168 std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
169 assert(I != SLP->SubLoops.end() && "SubLoop not a child of parent?");
170 SLP->SubLoops.erase(I); // Remove from parent...
172 // Add the subloop to THIS loop...
173 SubLoop->ParentLoop = L;
174 L->SubLoops.push_back(SubLoop);
177 // Normal case, add the block to our loop...
178 L->Blocks.push_back(X);
180 // Add all of the predecessors of X to the end of the work stack...
181 TodoStack.insert(TodoStack.end(), pred_begin(X), pred_end(X));
185 // If there are any loops nested within this loop, create them now!
186 for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(),
187 E = L->Blocks.end(); I != E; ++I)
188 if (Loop *NewLoop = ConsiderForLoop(*I, DS)) {
189 L->SubLoops.push_back(NewLoop);
190 NewLoop->ParentLoop = L;
193 // Add the basic blocks that comprise this loop to the BBMap so that this
194 // loop can be found for them.
196 for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(),
197 E = L->Blocks.end(); I != E; ++I) {
198 std::map<BasicBlock*, Loop*>::iterator BBMI = BBMap.lower_bound(*I);
199 if (BBMI == BBMap.end() || BBMI->first != *I) // Not in map yet...
200 BBMap.insert(BBMI, std::make_pair(*I, L)); // Must be at this level
203 // Now that we have a list of all of the child loops of this loop, check to
204 // see if any of them should actually be nested inside of each other. We can
205 // accidentally pull loops our of their parents, so we must make sure to
206 // organize the loop nests correctly now.
208 std::map<BasicBlock*, Loop*> ContainingLoops;
209 for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
210 Loop *Child = L->SubLoops[i];
211 assert(Child->getParentLoop() == L && "Not proper child loop?");
213 if (Loop *ContainingLoop = ContainingLoops[Child->getHeader()]) {
214 // If there is already a loop which contains this loop, move this loop
215 // into the containing loop.
216 MoveSiblingLoopInto(Child, ContainingLoop);
217 --i; // The loop got removed from the SubLoops list.
219 // This is currently considered to be a top-level loop. Check to see if
220 // any of the contained blocks are loop headers for subloops we have
221 // already processed.
222 for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
223 Loop *&BlockLoop = ContainingLoops[Child->Blocks[b]];
224 if (BlockLoop == 0) { // Child block not processed yet...
226 } else if (BlockLoop != Child) {
227 Loop *SubLoop = BlockLoop;
228 // Reparent all of the blocks which used to belong to BlockLoops
229 for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
230 ContainingLoops[SubLoop->Blocks[j]] = Child;
232 // There is already a loop which contains this block, that means
233 // that we should reparent the loop which the block is currently
234 // considered to belong to to be a child of this loop.
235 MoveSiblingLoopInto(SubLoop, Child);
236 --i; // We just shrunk the SubLoops list.
246 /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside of
247 /// the NewParent Loop, instead of being a sibling of it.
248 void LoopInfo::MoveSiblingLoopInto(Loop *NewChild, Loop *NewParent) {
249 Loop *OldParent = NewChild->getParentLoop();
250 assert(OldParent && OldParent == NewParent->getParentLoop() &&
251 NewChild != NewParent && "Not sibling loops!");
253 // Remove NewChild from being a child of OldParent
254 std::vector<Loop*>::iterator I =
255 std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(), NewChild);
256 assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
257 OldParent->SubLoops.erase(I); // Remove from parent's subloops list
258 NewChild->ParentLoop = 0;
260 InsertLoopInto(NewChild, NewParent);
263 /// InsertLoopInto - This inserts loop L into the specified parent loop. If the
264 /// parent loop contains a loop which should contain L, the loop gets inserted
266 void LoopInfo::InsertLoopInto(Loop *L, Loop *Parent) {
267 BasicBlock *LHeader = L->getHeader();
268 assert(Parent->contains(LHeader) && "This loop should not be inserted here!");
270 // Check to see if it belongs in a child loop...
271 for (unsigned i = 0, e = Parent->SubLoops.size(); i != e; ++i)
272 if (Parent->SubLoops[i]->contains(LHeader)) {
273 InsertLoopInto(L, Parent->SubLoops[i]);
277 // If not, insert it here!
278 Parent->SubLoops.push_back(L);
279 L->ParentLoop = Parent;
282 /// changeLoopFor - Change the top-level loop that contains BB to the
283 /// specified loop. This should be used by transformations that restructure
284 /// the loop hierarchy tree.
285 void LoopInfo::changeLoopFor(BasicBlock *BB, Loop *L) {
286 Loop *&OldLoop = BBMap[BB];
287 assert(OldLoop && "Block not in a loop yet!");
291 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
292 /// list with the indicated loop.
293 void LoopInfo::changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
294 std::vector<Loop*>::iterator I = std::find(TopLevelLoops.begin(),
295 TopLevelLoops.end(), OldLoop);
296 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
298 assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
299 "Loops already embedded into a subloop!");
302 /// removeLoop - This removes the specified top-level loop from this loop info
303 /// object. The loop is not deleted, as it will presumably be inserted into
305 Loop *LoopInfo::removeLoop(iterator I) {
306 assert(I != end() && "Cannot remove end iterator!");
308 assert(L->getParentLoop() == 0 && "Not a top-level loop!");
309 TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
313 /// removeBlock - This method completely removes BB from all data structures,
314 /// including all of the Loop objects it is nested in and our mapping from
315 /// BasicBlocks to loops.
316 void LoopInfo::removeBlock(BasicBlock *BB) {
317 std::map<BasicBlock *, Loop*>::iterator I = BBMap.find(BB);
318 if (I != BBMap.end()) {
319 for (Loop *L = I->second; L; L = L->getParentLoop())
320 L->removeBlockFromLoop(BB);
327 //===----------------------------------------------------------------------===//
328 // APIs for simple analysis of the loop.
331 /// getExitBlocks - Return all of the successor blocks of this loop. These
332 /// are the blocks _outside of the current loop_ which are branched to.
334 void Loop::getExitBlocks(std::vector<BasicBlock*> &ExitBlocks) const {
335 for (std::vector<BasicBlock*>::const_iterator BI = Blocks.begin(),
336 BE = Blocks.end(); BI != BE; ++BI)
337 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I)
338 if (!contains(*I)) // Not in current loop?
339 ExitBlocks.push_back(*I); // It must be an exit block...
343 /// getLoopPreheader - If there is a preheader for this loop, return it. A
344 /// loop has a preheader if there is only one edge to the header of the loop
345 /// from outside of the loop. If this is the case, the block branching to the
346 /// header of the loop is the preheader node.
348 /// This method returns null if there is no preheader for the loop.
350 BasicBlock *Loop::getLoopPreheader() const {
351 // Keep track of nodes outside the loop branching to the header...
354 // Loop over the predecessors of the header node...
355 BasicBlock *Header = getHeader();
356 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
358 if (!contains(*PI)) { // If the block is not in the loop...
359 if (Out && Out != *PI)
360 return 0; // Multiple predecessors outside the loop
364 // Make sure there is only one exit out of the preheader...
365 succ_iterator SI = succ_begin(Out);
367 if (SI != succ_end(Out))
368 return 0; // Multiple exits from the block, must not be a preheader.
371 // If there is exactly one preheader, return it. If there was zero, then Out
376 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
377 /// induction variable: an integer recurrence that starts at 0 and increments by
378 /// one each time through the loop. If so, return the phi node that corresponds
381 PHINode *Loop::getCanonicalInductionVariable() const {
382 BasicBlock *H = getHeader();
384 BasicBlock *Incoming = 0, *Backedge = 0;
385 pred_iterator PI = pred_begin(H);
386 assert(PI != pred_end(H) && "Loop must have at least one backedge!");
388 if (PI == pred_end(H)) return 0; // dead loop
390 if (PI != pred_end(H)) return 0; // multiple backedges?
392 if (contains(Incoming)) {
393 if (contains(Backedge))
395 std::swap(Incoming, Backedge);
396 } else if (!contains(Backedge))
399 // Loop over all of the PHI nodes, looking for a canonical indvar.
400 for (BasicBlock::iterator I = H->begin();
401 PHINode *PN = dyn_cast<PHINode>(I); ++I)
402 if (Instruction *Inc =
403 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
404 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
405 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
406 if (CI->equalsInt(1))
412 /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
413 /// the canonical induction variable value for the "next" iteration of the loop.
414 /// This always succeeds if getCanonicalInductionVariable succeeds.
416 Instruction *Loop::getCanonicalInductionVariableIncrement() const {
417 if (PHINode *PN = getCanonicalInductionVariable()) {
418 bool P1InLoop = contains(PN->getIncomingBlock(1));
419 return cast<Instruction>(PN->getIncomingValue(P1InLoop));
424 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
425 /// times the loop will be executed. Note that this means that the backedge of
426 /// the loop executes N-1 times. If the trip-count cannot be determined, this
429 Value *Loop::getTripCount() const {
430 // Canonical loops will end with a 'setne I, V', where I is the incremented
431 // canonical induction variable and V is the trip count of the loop.
432 Instruction *Inc = getCanonicalInductionVariableIncrement();
433 if (Inc == 0) return 0;
434 PHINode *IV = cast<PHINode>(Inc->getOperand(0));
436 BasicBlock *BackedgeBlock =
437 IV->getIncomingBlock(contains(IV->getIncomingBlock(1)));
439 if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator()))
440 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition()))
441 if (SCI->getOperand(0) == Inc)
442 if (BI->getSuccessor(0) == getHeader()) {
443 if (SCI->getOpcode() == Instruction::SetNE)
444 return SCI->getOperand(1);
445 } else if (SCI->getOpcode() == Instruction::SetEQ) {
446 return SCI->getOperand(1);
453 //===-------------------------------------------------------------------===//
454 // APIs for updating loop information after changing the CFG
457 /// addBasicBlockToLoop - This function is used by other analyses to update loop
458 /// information. NewBB is set to be a new member of the current loop. Because
459 /// of this, it is added as a member of all parent loops, and is added to the
460 /// specified LoopInfo object as being in the current basic block. It is not
461 /// valid to replace the loop header with this method.
463 void Loop::addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI) {
464 assert((Blocks.empty() || LI[getHeader()] == this) &&
465 "Incorrect LI specified for this loop!");
466 assert(NewBB && "Cannot add a null basic block to the loop!");
467 assert(LI[NewBB] == 0 && "BasicBlock already in the loop!");
469 // Add the loop mapping to the LoopInfo object...
470 LI.BBMap[NewBB] = this;
472 // Add the basic block to this loop and all parent loops...
475 L->Blocks.push_back(NewBB);
476 L = L->getParentLoop();
480 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
481 /// the OldChild entry in our children list with NewChild, and updates the
482 /// parent pointers of the two loops as appropriate.
483 void Loop::replaceChildLoopWith(Loop *OldChild, Loop *NewChild) {
484 assert(OldChild->ParentLoop == this && "This loop is already broken!");
485 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
486 std::vector<Loop*>::iterator I = std::find(SubLoops.begin(), SubLoops.end(),
488 assert(I != SubLoops.end() && "OldChild not in loop!");
490 OldChild->ParentLoop = 0;
491 NewChild->ParentLoop = this;
493 // Update the loop depth of the new child.
494 NewChild->setLoopDepth(LoopDepth+1);
497 /// addChildLoop - Add the specified loop to be a child of this loop.
499 void Loop::addChildLoop(Loop *NewChild) {
500 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
501 NewChild->ParentLoop = this;
502 SubLoops.push_back(NewChild);
504 // Update the loop depth of the new child.
505 NewChild->setLoopDepth(LoopDepth+1);
509 static void RemoveFromVector(std::vector<T*> &V, T *N) {
510 typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
511 assert(I != V.end() && "N is not in this list!");
515 /// removeChildLoop - This removes the specified child from being a subloop of
516 /// this loop. The loop is not deleted, as it will presumably be inserted
517 /// into another loop.
518 Loop *Loop::removeChildLoop(iterator I) {
519 assert(I != SubLoops.end() && "Cannot remove end iterator!");
521 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
522 SubLoops.erase(SubLoops.begin()+(I-begin()));
523 Child->ParentLoop = 0;
528 /// removeBlockFromLoop - This removes the specified basic block from the
529 /// current loop, updating the Blocks and ExitBlocks lists as appropriate. This
530 /// does not update the mapping in the LoopInfo class.
531 void Loop::removeBlockFromLoop(BasicBlock *BB) {
532 RemoveFromVector(Blocks, BB);