blob: 8619984f3df726a245e4edde9b7640424804cf92 [file] [log] [blame]
Chris Lattnercf3056d2003-10-13 03:32:08 +00001//===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner0bbe58f2001-11-26 18:41:20 +00009//
10// This file defines the LoopInfo class that is used to identify natural loops
11// and determine the loop depth of various nodes of the CFG. Note that the
12// loops identified may actually be several natural loops that share the same
13// header node... not just a single natural loop.
14//
15//===----------------------------------------------------------------------===//
16
Misha Brukman10d208d2004-01-30 17:26:24 +000017#include "llvm/Analysis/LoopInfo.h"
Chris Lattner92020fa2004-04-15 15:16:02 +000018#include "llvm/Constants.h"
19#include "llvm/Instructions.h"
20#include "llvm/Analysis/Dominators.h"
Chris Lattnera59cbb22002-07-27 01:12:17 +000021#include "llvm/Assembly/Writer.h"
Misha Brukman10d208d2004-01-30 17:26:24 +000022#include "llvm/Support/CFG.h"
Chris Lattnercee8f9a2001-11-27 00:03:19 +000023#include "Support/DepthFirstIterator.h"
Chris Lattner0bbe58f2001-11-26 18:41:20 +000024#include <algorithm>
Chris Lattner46758a82004-04-12 20:26:17 +000025using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000026
Chris Lattner1e435162002-07-26 21:12:44 +000027static RegisterAnalysis<LoopInfo>
Chris Lattner17689df2002-07-30 16:27:52 +000028X("loops", "Natural Loop Construction", true);
Chris Lattner93193f82002-01-31 00:42:27 +000029
30//===----------------------------------------------------------------------===//
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000031// Loop implementation
Chris Lattner93193f82002-01-31 00:42:27 +000032//
Chris Lattner0f995552002-06-03 22:10:52 +000033bool Loop::contains(const BasicBlock *BB) const {
Chris Lattner0bbe58f2001-11-26 18:41:20 +000034 return find(Blocks.begin(), Blocks.end(), BB) != Blocks.end();
35}
36
Misha Brukman6b290a52002-10-11 05:31:10 +000037bool Loop::isLoopExit(const BasicBlock *BB) const {
Chris Lattner03f252f2003-09-24 22:18:35 +000038 for (succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB);
Misha Brukman6b290a52002-10-11 05:31:10 +000039 SI != SE; ++SI) {
Chris Lattner5f82b8a2003-02-27 00:38:34 +000040 if (!contains(*SI))
Misha Brukman6b290a52002-10-11 05:31:10 +000041 return true;
42 }
43 return false;
44}
45
Chris Lattner2ef12362003-10-12 22:14:27 +000046/// getNumBackEdges - Calculate the number of back edges to the loop header.
47///
Misha Brukman6b290a52002-10-11 05:31:10 +000048unsigned Loop::getNumBackEdges() const {
Chris Lattner5f82b8a2003-02-27 00:38:34 +000049 unsigned NumBackEdges = 0;
50 BasicBlock *H = getHeader();
Misha Brukman6b290a52002-10-11 05:31:10 +000051
Chris Lattner2ef12362003-10-12 22:14:27 +000052 for (pred_iterator I = pred_begin(H), E = pred_end(H); I != E; ++I)
53 if (contains(*I))
54 ++NumBackEdges;
55
Chris Lattner5f82b8a2003-02-27 00:38:34 +000056 return NumBackEdges;
Misha Brukman6b290a52002-10-11 05:31:10 +000057}
58
Chris Lattner85661d02004-04-18 22:45:27 +000059/// isLoopInvariant - Return true if the specified value is loop invariant
60///
61bool Loop::isLoopInvariant(Value *V) const {
62 if (Instruction *I = dyn_cast<Instruction>(V))
63 return !contains(I->getParent());
64 return true; // All non-instructions are loop invariant
65}
66
Chris Lattner7dd46b02003-08-16 20:57:16 +000067void Loop::print(std::ostream &OS, unsigned Depth) const {
68 OS << std::string(Depth*2, ' ') << "Loop Containing: ";
Chris Lattnera59cbb22002-07-27 01:12:17 +000069
70 for (unsigned i = 0; i < getBlocks().size(); ++i) {
71 if (i) OS << ",";
Chris Lattner5f82b8a2003-02-27 00:38:34 +000072 WriteAsOperand(OS, getBlocks()[i], false);
Chris Lattnera59cbb22002-07-27 01:12:17 +000073 }
74 OS << "\n";
75
Chris Lattner329c1c62004-01-08 00:09:44 +000076 for (iterator I = begin(), E = end(); I != E; ++I)
77 (*I)->print(OS, Depth+2);
Chris Lattnera59cbb22002-07-27 01:12:17 +000078}
79
Chris Lattnerbb05f1e2003-02-28 16:54:45 +000080void Loop::dump() const {
81 print(std::cerr);
82}
83
Chris Lattner420df9b2003-02-22 21:33:11 +000084
Chris Lattnera59cbb22002-07-27 01:12:17 +000085//===----------------------------------------------------------------------===//
86// LoopInfo implementation
87//
Anand Shuklae0b6b782002-08-26 16:45:19 +000088void LoopInfo::stub() {}
Chris Lattnera59cbb22002-07-27 01:12:17 +000089
90bool LoopInfo::runOnFunction(Function &) {
91 releaseMemory();
92 Calculate(getAnalysis<DominatorSet>()); // Update
93 return false;
94}
95
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000096void LoopInfo::releaseMemory() {
Chris Lattner918c4ec2002-04-09 05:43:19 +000097 for (std::vector<Loop*>::iterator I = TopLevelLoops.begin(),
98 E = TopLevelLoops.end(); I != E; ++I)
99 delete *I; // Delete all of the loops...
100
101 BBMap.clear(); // Reset internal state of analysis
102 TopLevelLoops.clear();
103}
104
Chris Lattner93193f82002-01-31 00:42:27 +0000105
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000106void LoopInfo::Calculate(const DominatorSet &DS) {
Chris Lattnera298d272002-04-28 00:15:57 +0000107 BasicBlock *RootNode = DS.getRoot();
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000108
Chris Lattnera298d272002-04-28 00:15:57 +0000109 for (df_iterator<BasicBlock*> NI = df_begin(RootNode),
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000110 NE = df_end(RootNode); NI != NE; ++NI)
111 if (Loop *L = ConsiderForLoop(*NI, DS))
112 TopLevelLoops.push_back(L);
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000113}
114
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000115void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf57b8452002-04-27 06:56:12 +0000116 AU.setPreservesAll();
Chris Lattnerdd5b4952002-08-08 19:01:28 +0000117 AU.addRequired<DominatorSet>();
Chris Lattner93193f82002-01-31 00:42:27 +0000118}
119
Chris Lattnera59cbb22002-07-27 01:12:17 +0000120void LoopInfo::print(std::ostream &OS) const {
Chris Lattnerfce46ef2002-09-26 16:15:54 +0000121 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
122 TopLevelLoops[i]->print(OS);
Chris Lattner420df9b2003-02-22 21:33:11 +0000123#if 0
124 for (std::map<BasicBlock*, Loop*>::const_iterator I = BBMap.begin(),
125 E = BBMap.end(); I != E; ++I)
126 OS << "BB '" << I->first->getName() << "' level = "
Chris Lattner446b86d2004-04-19 03:02:09 +0000127 << I->second->getLoopDepth() << "\n";
Chris Lattner420df9b2003-02-22 21:33:11 +0000128#endif
Chris Lattnera59cbb22002-07-27 01:12:17 +0000129}
Chris Lattner93193f82002-01-31 00:42:27 +0000130
Chris Lattner39c987a2003-05-15 18:03:51 +0000131static bool isNotAlreadyContainedIn(Loop *SubLoop, Loop *ParentLoop) {
132 if (SubLoop == 0) return true;
133 if (SubLoop == ParentLoop) return false;
134 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
135}
136
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000137Loop *LoopInfo::ConsiderForLoop(BasicBlock *BB, const DominatorSet &DS) {
Chris Lattner699b3052002-09-26 05:32:50 +0000138 if (BBMap.find(BB) != BBMap.end()) return 0; // Haven't processed this node?
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000139
Chris Lattnera298d272002-04-28 00:15:57 +0000140 std::vector<BasicBlock *> TodoStack;
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000141
142 // Scan the predecessors of BB, checking to see if BB dominates any of
Chris Lattner99224ae2003-04-26 19:34:18 +0000143 // them. This identifies backedges which target this node...
Chris Lattnera298d272002-04-28 00:15:57 +0000144 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000145 if (DS.dominates(BB, *I)) // If BB dominates it's predecessor...
146 TodoStack.push_back(*I);
147
Chris Lattner99224ae2003-04-26 19:34:18 +0000148 if (TodoStack.empty()) return 0; // No backedges to this block...
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000149
150 // Create a new loop to represent this basic block...
151 Loop *L = new Loop(BB);
152 BBMap[BB] = L;
153
Chris Lattner59dc1782003-10-22 16:41:21 +0000154 BasicBlock *EntryBlock = &BB->getParent()->getEntryBlock();
155
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000156 while (!TodoStack.empty()) { // Process all the nodes in the loop
Chris Lattnera298d272002-04-28 00:15:57 +0000157 BasicBlock *X = TodoStack.back();
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000158 TodoStack.pop_back();
159
Chris Lattner59dc1782003-10-22 16:41:21 +0000160 if (!L->contains(X) && // As of yet unprocessed??
161 DS.dominates(EntryBlock, X)) { // X is reachable from entry block?
Chris Lattner99224ae2003-04-26 19:34:18 +0000162 // Check to see if this block already belongs to a loop. If this occurs
163 // then we have a case where a loop that is supposed to be a child of the
164 // current loop was processed before the current loop. When this occurs,
165 // this child loop gets added to a part of the current loop, making it a
166 // sibling to the current loop. We have to reparent this loop.
167 if (Loop *SubLoop = const_cast<Loop*>(getLoopFor(X)))
Chris Lattner39c987a2003-05-15 18:03:51 +0000168 if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)) {
Chris Lattner99224ae2003-04-26 19:34:18 +0000169 // Remove the subloop from it's current parent...
170 assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
171 Loop *SLP = SubLoop->ParentLoop; // SubLoopParent
172 std::vector<Loop*>::iterator I =
173 std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
174 assert(I != SLP->SubLoops.end() && "SubLoop not a child of parent?");
175 SLP->SubLoops.erase(I); // Remove from parent...
176
177 // Add the subloop to THIS loop...
178 SubLoop->ParentLoop = L;
179 L->SubLoops.push_back(SubLoop);
180 }
181
182 // Normal case, add the block to our loop...
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000183 L->Blocks.push_back(X);
Chris Lattner99224ae2003-04-26 19:34:18 +0000184
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000185 // Add all of the predecessors of X to the end of the work stack...
Chris Lattner455889a2002-02-12 22:39:50 +0000186 TodoStack.insert(TodoStack.end(), pred_begin(X), pred_end(X));
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000187 }
188 }
189
Chris Lattner420df9b2003-02-22 21:33:11 +0000190 // If there are any loops nested within this loop, create them now!
191 for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(),
192 E = L->Blocks.end(); I != E; ++I)
193 if (Loop *NewLoop = ConsiderForLoop(*I, DS)) {
194 L->SubLoops.push_back(NewLoop);
195 NewLoop->ParentLoop = L;
196 }
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000197
Chris Lattner420df9b2003-02-22 21:33:11 +0000198 // Add the basic blocks that comprise this loop to the BBMap so that this
199 // loop can be found for them.
200 //
201 for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(),
202 E = L->Blocks.end(); I != E; ++I) {
203 std::map<BasicBlock*, Loop*>::iterator BBMI = BBMap.lower_bound(*I);
204 if (BBMI == BBMap.end() || BBMI->first != *I) // Not in map yet...
205 BBMap.insert(BBMI, std::make_pair(*I, L)); // Must be at this level
206 }
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000207
Chris Lattner7dd46b02003-08-16 20:57:16 +0000208 // Now that we have a list of all of the child loops of this loop, check to
209 // see if any of them should actually be nested inside of each other. We can
210 // accidentally pull loops our of their parents, so we must make sure to
211 // organize the loop nests correctly now.
212 {
213 std::map<BasicBlock*, Loop*> ContainingLoops;
214 for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
215 Loop *Child = L->SubLoops[i];
216 assert(Child->getParentLoop() == L && "Not proper child loop?");
217
218 if (Loop *ContainingLoop = ContainingLoops[Child->getHeader()]) {
219 // If there is already a loop which contains this loop, move this loop
220 // into the containing loop.
221 MoveSiblingLoopInto(Child, ContainingLoop);
222 --i; // The loop got removed from the SubLoops list.
223 } else {
224 // This is currently considered to be a top-level loop. Check to see if
225 // any of the contained blocks are loop headers for subloops we have
226 // already processed.
227 for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
228 Loop *&BlockLoop = ContainingLoops[Child->Blocks[b]];
229 if (BlockLoop == 0) { // Child block not processed yet...
230 BlockLoop = Child;
231 } else if (BlockLoop != Child) {
Chris Lattner169db9d2003-08-17 21:47:33 +0000232 Loop *SubLoop = BlockLoop;
233 // Reparent all of the blocks which used to belong to BlockLoops
234 for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
235 ContainingLoops[SubLoop->Blocks[j]] = Child;
236
Chris Lattner7dd46b02003-08-16 20:57:16 +0000237 // There is already a loop which contains this block, that means
238 // that we should reparent the loop which the block is currently
239 // considered to belong to to be a child of this loop.
Chris Lattner169db9d2003-08-17 21:47:33 +0000240 MoveSiblingLoopInto(SubLoop, Child);
Chris Lattner7dd46b02003-08-16 20:57:16 +0000241 --i; // We just shrunk the SubLoops list.
242 }
243 }
244 }
245 }
246 }
247
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000248 return L;
249}
Chris Lattner699b3052002-09-26 05:32:50 +0000250
Chris Lattner7dd46b02003-08-16 20:57:16 +0000251/// MoveSiblingLoopInto - This method moves the NewChild loop to live inside of
252/// the NewParent Loop, instead of being a sibling of it.
253void LoopInfo::MoveSiblingLoopInto(Loop *NewChild, Loop *NewParent) {
254 Loop *OldParent = NewChild->getParentLoop();
255 assert(OldParent && OldParent == NewParent->getParentLoop() &&
256 NewChild != NewParent && "Not sibling loops!");
257
258 // Remove NewChild from being a child of OldParent
259 std::vector<Loop*>::iterator I =
260 std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(), NewChild);
261 assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
262 OldParent->SubLoops.erase(I); // Remove from parent's subloops list
263 NewChild->ParentLoop = 0;
264
265 InsertLoopInto(NewChild, NewParent);
266}
267
268/// InsertLoopInto - This inserts loop L into the specified parent loop. If the
269/// parent loop contains a loop which should contain L, the loop gets inserted
270/// into L instead.
271void LoopInfo::InsertLoopInto(Loop *L, Loop *Parent) {
272 BasicBlock *LHeader = L->getHeader();
273 assert(Parent->contains(LHeader) && "This loop should not be inserted here!");
274
275 // Check to see if it belongs in a child loop...
276 for (unsigned i = 0, e = Parent->SubLoops.size(); i != e; ++i)
277 if (Parent->SubLoops[i]->contains(LHeader)) {
278 InsertLoopInto(L, Parent->SubLoops[i]);
279 return;
280 }
281
282 // If not, insert it here!
283 Parent->SubLoops.push_back(L);
284 L->ParentLoop = Parent;
285}
286
Chris Lattner46758a82004-04-12 20:26:17 +0000287/// changeLoopFor - Change the top-level loop that contains BB to the
288/// specified loop. This should be used by transformations that restructure
289/// the loop hierarchy tree.
290void LoopInfo::changeLoopFor(BasicBlock *BB, Loop *L) {
291 Loop *&OldLoop = BBMap[BB];
292 assert(OldLoop && "Block not in a loop yet!");
293 OldLoop = L;
294}
Chris Lattner7dd46b02003-08-16 20:57:16 +0000295
Chris Lattner46758a82004-04-12 20:26:17 +0000296/// changeTopLevelLoop - Replace the specified loop in the top-level loops
297/// list with the indicated loop.
298void LoopInfo::changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
299 std::vector<Loop*>::iterator I = std::find(TopLevelLoops.begin(),
300 TopLevelLoops.end(), OldLoop);
301 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
302 *I = NewLoop;
303 assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
304 "Loops already embedded into a subloop!");
305}
Chris Lattner7dd46b02003-08-16 20:57:16 +0000306
Chris Lattner24199db2004-04-18 05:38:05 +0000307/// removeLoop - This removes the specified top-level loop from this loop info
308/// object. The loop is not deleted, as it will presumably be inserted into
309/// another loop.
310Loop *LoopInfo::removeLoop(iterator I) {
311 assert(I != end() && "Cannot remove end iterator!");
312 Loop *L = *I;
313 assert(L->getParentLoop() == 0 && "Not a top-level loop!");
314 TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
315 return L;
316}
317
Chris Lattner3048bd12004-04-18 06:54:48 +0000318/// removeBlock - This method completely removes BB from all data structures,
319/// including all of the Loop objects it is nested in and our mapping from
320/// BasicBlocks to loops.
321void LoopInfo::removeBlock(BasicBlock *BB) {
322 std::map<BasicBlock *, Loop*>::iterator I = BBMap.find(BB);
323 if (I != BBMap.end()) {
324 for (Loop *L = I->second; L; L = L->getParentLoop())
325 L->removeBlockFromLoop(BB);
326
327 BBMap.erase(I);
328 }
329}
Chris Lattner24199db2004-04-18 05:38:05 +0000330
331
Chris Lattner92020fa2004-04-15 15:16:02 +0000332//===----------------------------------------------------------------------===//
333// APIs for simple analysis of the loop.
334//
335
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000336/// getExitBlocks - Return all of the successor blocks of this loop. These
337/// are the blocks _outside of the current loop_ which are branched to.
338///
Chris Lattner343c0cf2004-04-18 22:21:41 +0000339void Loop::getExitBlocks(std::vector<BasicBlock*> &ExitBlocks) const {
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000340 for (std::vector<BasicBlock*>::const_iterator BI = Blocks.begin(),
341 BE = Blocks.end(); BI != BE; ++BI)
342 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I)
343 if (!contains(*I)) // Not in current loop?
Chris Lattner343c0cf2004-04-18 22:21:41 +0000344 ExitBlocks.push_back(*I); // It must be an exit block...
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000345}
346
347
Chris Lattner699b3052002-09-26 05:32:50 +0000348/// getLoopPreheader - If there is a preheader for this loop, return it. A
349/// loop has a preheader if there is only one edge to the header of the loop
350/// from outside of the loop. If this is the case, the block branching to the
Chris Lattner92020fa2004-04-15 15:16:02 +0000351/// header of the loop is the preheader node.
Chris Lattner699b3052002-09-26 05:32:50 +0000352///
Chris Lattner92020fa2004-04-15 15:16:02 +0000353/// This method returns null if there is no preheader for the loop.
Chris Lattner699b3052002-09-26 05:32:50 +0000354///
355BasicBlock *Loop::getLoopPreheader() const {
356 // Keep track of nodes outside the loop branching to the header...
357 BasicBlock *Out = 0;
358
359 // Loop over the predecessors of the header node...
360 BasicBlock *Header = getHeader();
361 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
362 PI != PE; ++PI)
Chris Lattnerc8f25d92002-09-29 22:59:29 +0000363 if (!contains(*PI)) { // If the block is not in the loop...
364 if (Out && Out != *PI)
365 return 0; // Multiple predecessors outside the loop
Chris Lattner699b3052002-09-26 05:32:50 +0000366 Out = *PI;
367 }
Chris Lattner5a8a2912003-02-27 21:51:38 +0000368
369 // Make sure there is only one exit out of the preheader...
370 succ_iterator SI = succ_begin(Out);
371 ++SI;
372 if (SI != succ_end(Out))
373 return 0; // Multiple exits from the block, must not be a preheader.
374
Chris Lattner699b3052002-09-26 05:32:50 +0000375
376 // If there is exactly one preheader, return it. If there was zero, then Out
377 // is still null.
378 return Out;
379}
380
Chris Lattner92020fa2004-04-15 15:16:02 +0000381/// getCanonicalInductionVariable - Check to see if the loop has a canonical
382/// induction variable: an integer recurrence that starts at 0 and increments by
383/// one each time through the loop. If so, return the phi node that corresponds
384/// to it.
385///
386PHINode *Loop::getCanonicalInductionVariable() const {
387 BasicBlock *H = getHeader();
388
389 BasicBlock *Incoming = 0, *Backedge = 0;
390 pred_iterator PI = pred_begin(H);
391 assert(PI != pred_end(H) && "Loop must have at least one backedge!");
392 Backedge = *PI++;
393 if (PI == pred_end(H)) return 0; // dead loop
394 Incoming = *PI++;
395 if (PI != pred_end(H)) return 0; // multiple backedges?
396
397 if (contains(Incoming)) {
398 if (contains(Backedge))
399 return 0;
400 std::swap(Incoming, Backedge);
401 } else if (!contains(Backedge))
402 return 0;
403
404 // Loop over all of the PHI nodes, looking for a canonical indvar.
405 for (BasicBlock::iterator I = H->begin();
406 PHINode *PN = dyn_cast<PHINode>(I); ++I)
407 if (Instruction *Inc =
408 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
409 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
410 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
411 if (CI->equalsInt(1))
412 return PN;
413
414 return 0;
415}
416
417/// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
418/// the canonical induction variable value for the "next" iteration of the loop.
419/// This always succeeds if getCanonicalInductionVariable succeeds.
420///
421Instruction *Loop::getCanonicalInductionVariableIncrement() const {
422 if (PHINode *PN = getCanonicalInductionVariable()) {
423 bool P1InLoop = contains(PN->getIncomingBlock(1));
424 return cast<Instruction>(PN->getIncomingValue(P1InLoop));
425 }
426 return 0;
427}
428
429/// getTripCount - Return a loop-invariant LLVM value indicating the number of
430/// times the loop will be executed. Note that this means that the backedge of
431/// the loop executes N-1 times. If the trip-count cannot be determined, this
432/// returns null.
433///
434Value *Loop::getTripCount() const {
435 // Canonical loops will end with a 'setne I, V', where I is the incremented
436 // canonical induction variable and V is the trip count of the loop.
437 Instruction *Inc = getCanonicalInductionVariableIncrement();
Chris Lattner24199db2004-04-18 05:38:05 +0000438 if (Inc == 0) return 0;
Chris Lattner92020fa2004-04-15 15:16:02 +0000439 PHINode *IV = cast<PHINode>(Inc->getOperand(0));
440
441 BasicBlock *BackedgeBlock =
442 IV->getIncomingBlock(contains(IV->getIncomingBlock(1)));
443
444 if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator()))
Chris Lattner47c31a82004-06-08 21:50:30 +0000445 if (BI->isConditional())
446 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition()))
447 if (SCI->getOperand(0) == Inc)
448 if (BI->getSuccessor(0) == getHeader()) {
449 if (SCI->getOpcode() == Instruction::SetNE)
450 return SCI->getOperand(1);
451 } else if (SCI->getOpcode() == Instruction::SetEQ) {
Chris Lattner92020fa2004-04-15 15:16:02 +0000452 return SCI->getOperand(1);
Chris Lattner47c31a82004-06-08 21:50:30 +0000453 }
Chris Lattner92020fa2004-04-15 15:16:02 +0000454
455 return 0;
456}
457
458
459//===-------------------------------------------------------------------===//
460// APIs for updating loop information after changing the CFG
461//
462
Chris Lattner699b3052002-09-26 05:32:50 +0000463/// addBasicBlockToLoop - This function is used by other analyses to update loop
464/// information. NewBB is set to be a new member of the current loop. Because
465/// of this, it is added as a member of all parent loops, and is added to the
466/// specified LoopInfo object as being in the current basic block. It is not
467/// valid to replace the loop header with this method.
468///
469void Loop::addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI) {
Chris Lattner46758a82004-04-12 20:26:17 +0000470 assert((Blocks.empty() || LI[getHeader()] == this) &&
471 "Incorrect LI specified for this loop!");
Chris Lattner699b3052002-09-26 05:32:50 +0000472 assert(NewBB && "Cannot add a null basic block to the loop!");
473 assert(LI[NewBB] == 0 && "BasicBlock already in the loop!");
474
475 // Add the loop mapping to the LoopInfo object...
476 LI.BBMap[NewBB] = this;
477
478 // Add the basic block to this loop and all parent loops...
479 Loop *L = this;
480 while (L) {
481 L->Blocks.push_back(NewBB);
482 L = L->getParentLoop();
483 }
484}
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000485
Chris Lattner46758a82004-04-12 20:26:17 +0000486/// replaceChildLoopWith - This is used when splitting loops up. It replaces
487/// the OldChild entry in our children list with NewChild, and updates the
488/// parent pointers of the two loops as appropriate.
489void Loop::replaceChildLoopWith(Loop *OldChild, Loop *NewChild) {
490 assert(OldChild->ParentLoop == this && "This loop is already broken!");
491 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
492 std::vector<Loop*>::iterator I = std::find(SubLoops.begin(), SubLoops.end(),
493 OldChild);
494 assert(I != SubLoops.end() && "OldChild not in loop!");
495 *I = NewChild;
496 OldChild->ParentLoop = 0;
497 NewChild->ParentLoop = this;
Chris Lattner46758a82004-04-12 20:26:17 +0000498}
499
500/// addChildLoop - Add the specified loop to be a child of this loop.
501///
502void Loop::addChildLoop(Loop *NewChild) {
503 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
504 NewChild->ParentLoop = this;
505 SubLoops.push_back(NewChild);
Chris Lattner46758a82004-04-12 20:26:17 +0000506}
507
508template<typename T>
509static 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!");
512 V.erase(I);
513}
514
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.
518Loop *Loop::removeChildLoop(iterator I) {
519 assert(I != SubLoops.end() && "Cannot remove end iterator!");
520 Loop *Child = *I;
521 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
522 SubLoops.erase(SubLoops.begin()+(I-begin()));
523 Child->ParentLoop = 0;
524 return Child;
525}
526
527
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.
531void Loop::removeBlockFromLoop(BasicBlock *BB) {
532 RemoveFromVector(Blocks, BB);
Chris Lattner46758a82004-04-12 20:26:17 +0000533}