llvm.org GIT mirror llvm / 019b92a
Start the process of making MachineLoopInfo possible by templating Loop. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@44097 91177308-0d34-0410-b5e6-96231b3b80d8 Owen Anderson 12 years ago
6 changed file(s) with 351 addition(s) and 446 deletion(s). Raw diff Collapse all Expand all
3030 #define LLVM_ANALYSIS_LOOP_INFO_H
3131
3232 #include "llvm/Pass.h"
33 #include "llvm/Constants.h"
34 #include "llvm/Instructions.h"
3335 #include "llvm/ADT/GraphTraits.h"
36 #include "llvm/ADT/SmallPtrSet.h"
3437 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/Support/CFG.h"
39 #include "llvm/Support/Streams.h"
40 #include
41 #include
42
43 template
44 static void RemoveFromVector(std::vector &V, T *N) {
45 typename std::vector::iterator I = std::find(V.begin(), V.end(), N);
46 assert(I != V.end() && "N is not in this list!");
47 V.erase(I);
48 }
3549
3650 namespace llvm {
3751
4155 class Instruction;
4256
4357 //===----------------------------------------------------------------------===//
44 /// Loop class - Instances of this class are used to represent loops that are
58 /// LoopBase class - Instances of this class are used to represent loops that are
4559 /// detected in the flow graph
4660 ///
47 class Loop {
48 Loop *ParentLoop;
49 std::vector SubLoops; // Loops contained entirely within this one
50 std::vector Blocks; // First entry is the header node
51
52 Loop(const Loop &); // DO NOT IMPLEMENT
53 const Loop &operator=(const Loop &); // DO NOT IMPLEMENT
61 template
62 class LoopBase {
63 LoopBase *ParentLoop;
64 std::vector*> SubLoops; // Loops contained entirely within this one
65 std::vector Blocks; // First entry is the header node
66
67 LoopBase(const LoopBase &); // DO NOT IMPLEMENT
68 const LoopBase &operator=(const LoopBase &); // DO NOT IMPLEMENT
5469 public:
5570 /// Loop ctor - This creates an empty loop.
56 Loop() : ParentLoop(0) {}
57 ~Loop() {
71 LoopBase() : ParentLoop(0) {}
72 ~LoopBase() {
5873 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
5974 delete SubLoops[i];
6075 }
6176
6277 unsigned getLoopDepth() const {
6378 unsigned D = 0;
64 for (const Loop *CurLoop = this; CurLoop; CurLoop = CurLoop->ParentLoop)
79 for (const LoopBase *CurLoop = this; CurLoop;
80 CurLoop = CurLoop->ParentLoop)
6581 ++D;
6682 return D;
6783 }
68 BasicBlock *getHeader() const { return Blocks.front(); }
69 Loop *getParentLoop() const { return ParentLoop; }
84 BlockT *getHeader() const { return Blocks.front(); }
85 LoopBase *getParentLoop() const { return ParentLoop; }
7086
7187 /// contains - Return true of the specified basic block is in this loop
7288 ///
73 bool contains(const BasicBlock *BB) const;
89 bool contains(const BlockT *BB) const {
90 return std::find(Blocks.begin(), Blocks.end(), BB) != Blocks.end();
91 }
7492
7593 /// iterator/begin/end - Return the loops contained entirely within this loop.
7694 ///
77 const std::vector &getSubLoops() const { return SubLoops; }
78 typedef std::vector::const_iterator iterator;
95 const std::vector*> &getSubLoops() const { return SubLoops; }
96 typedef typename std::vector*>::const_iterator iterator;
7997 iterator begin() const { return SubLoops.begin(); }
8098 iterator end() const { return SubLoops.end(); }
8199 bool empty() const { return SubLoops.empty(); }
82100
83101 /// getBlocks - Get a list of the basic blocks which make up this loop.
84102 ///
85 const std::vector &getBlocks() const { return Blocks; }
86 typedef std::vector::const_iterator block_iterator;
103 const std::vector &getBlocks() const { return Blocks; }
104 typedef typename std::vector::const_iterator block_iterator;
87105 block_iterator block_begin() const { return Blocks.begin(); }
88106 block_iterator block_end() const { return Blocks.end(); }
89107
90108 /// isLoopExit - True if terminator in the block can branch to another block
91109 /// that is outside of the current loop.
92110 ///
93 bool isLoopExit(const BasicBlock *BB) const;
111 bool isLoopExit(const BlockT *BB) const {
112 for (succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB);
113 SI != SE; ++SI) {
114 if (!contains(*SI))
115 return true;
116 }
117 return false;
118 }
94119
95120 /// getNumBackEdges - Calculate the number of back edges to the loop header
96121 ///
97 unsigned getNumBackEdges() const;
122 unsigned getNumBackEdges() const {
123 unsigned NumBackEdges = 0;
124 BlockT *H = getHeader();
125
126 for (pred_iterator I = pred_begin(H), E = pred_end(H); I != E; ++I)
127 if (contains(*I))
128 ++NumBackEdges;
129
130 return NumBackEdges;
131 }
98132
99133 /// isLoopInvariant - Return true if the specified value is loop invariant
100134 ///
101 bool isLoopInvariant(Value *V) const;
135 bool isLoopInvariant(Value *V) const {
136 if (Instruction *I = dyn_cast(V))
137 return !contains(I->getParent());
138 return true; // All non-instructions are loop invariant
139 }
102140
103141 //===--------------------------------------------------------------------===//
104142 // APIs for simple analysis of the loop.
112150 /// outside of the loop. These are the blocks _inside of the current loop_
113151 /// which branch out. The returned list is always unique.
114152 ///
115 void getExitingBlocks(SmallVectorImplasicBlock *> &Blocks) const;
153 void getExitingBlocks(SmallVectorImpllockT *> &ExitingBlocks) const {
154 // Sort the blocks vector so that we can use binary search to do quick
155 // lookups.
156 SmallVector LoopBBs(block_begin(), block_end());
157 std::sort(LoopBBs.begin(), LoopBBs.end());
158
159 for (typename std::vector::const_iterator BI = Blocks.begin(),
160 BE = Blocks.end(); BI != BE; ++BI)
161 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I)
162 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
163 // Not in current loop? It must be an exit block.
164 ExitingBlocks.push_back(*BI);
165 break;
166 }
167 }
116168
117169 /// getExitBlocks - Return all of the successor blocks of this loop. These
118170 /// are the blocks _outside of the current loop_ which are branched to.
119171 ///
120 void getExitBlocks(SmallVectorImplasicBlock* > &Blocks) const;
172 void getExitBlocks(SmallVectorImpllockT*> &ExitBlocks) const {
173 // Sort the blocks vector so that we can use binary search to do quick
174 // lookups.
175 SmallVector LoopBBs(block_begin(), block_end());
176 std::sort(LoopBBs.begin(), LoopBBs.end());
177
178 for (typename std::vector::const_iterator BI = Blocks.begin(),
179 BE = Blocks.end(); BI != BE; ++BI)
180 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I)
181 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
182 // Not in current loop? It must be an exit block.
183 ExitBlocks.push_back(*I);
184 }
121185
122186 /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
123187 /// These are the blocks _outside of the current loop_ which are branched to.
124188 /// This assumes that loop is in canonical form.
125189 ///
126 void getUniqueExitBlocks(SmallVectorImplasicBlock*> &ExitBlocks) const;
190 void getUniqueExitBlocks(SmallVectorImpllockT*> &ExitBlocks) const {
191 // Sort the blocks vector so that we can use binary search to do quick
192 // lookups.
193 SmallVector LoopBBs(block_begin(), block_end());
194 std::sort(LoopBBs.begin(), LoopBBs.end());
195
196 std::vector switchExitBlocks;
197
198 for (typename std::vector::const_iterator BI = Blocks.begin(),
199 BE = Blocks.end(); BI != BE; ++BI) {
200
201 BlockT *current = *BI;
202 switchExitBlocks.clear();
203
204 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
205 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
206 // If block is inside the loop then it is not a exit block.
207 continue;
208
209 pred_iterator PI = pred_begin(*I);
210 BlockT *firstPred = *PI;
211
212 // If current basic block is this exit block's first predecessor
213 // then only insert exit block in to the output ExitBlocks vector.
214 // This ensures that same exit block is not inserted twice into
215 // ExitBlocks vector.
216 if (current != firstPred)
217 continue;
218
219 // If a terminator has more then two successors, for example SwitchInst,
220 // then it is possible that there are multiple edges from current block
221 // to one exit block.
222 if (current->getTerminator()->getNumSuccessors() <= 2) {
223 ExitBlocks.push_back(*I);
224 continue;
225 }
226
227 // In case of multiple edges from current block to exit block, collect
228 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
229 // duplicate edges.
230 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
231 == switchExitBlocks.end()) {
232 switchExitBlocks.push_back(*I);
233 ExitBlocks.push_back(*I);
234 }
235 }
236 }
237 }
127238
128239 /// getLoopPreheader - If there is a preheader for this loop, return it. A
129240 /// loop has a preheader if there is only one edge to the header of the loop
132243 ///
133244 /// This method returns null if there is no preheader for the loop.
134245 ///
135 BasicBlock *getLoopPreheader() const;
246 BlockT *getLoopPreheader() const {
247 // Keep track of nodes outside the loop branching to the header...
248 BlockT *Out = 0;
249
250 // Loop over the predecessors of the header node...
251 BlockT *Header = getHeader();
252 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
253 PI != PE; ++PI)
254 if (!contains(*PI)) { // If the block is not in the loop...
255 if (Out && Out != *PI)
256 return 0; // Multiple predecessors outside the loop
257 Out = *PI;
258 }
259
260 // Make sure there is only one exit out of the preheader.
261 assert(Out && "Header of loop has no predecessors from outside loop?");
262 succ_iterator SI = succ_begin(Out);
263 ++SI;
264 if (SI != succ_end(Out))
265 return 0; // Multiple exits from the block, must not be a preheader.
266
267 // If there is exactly one preheader, return it. If there was zero, then Out
268 // is still null.
269 return Out;
270 }
136271
137272 /// getLoopLatch - If there is a latch block for this loop, return it. A
138273 /// latch block is the canonical backedge for a loop. A loop header in normal
139274 /// form has two edges into it: one from a preheader and one from a latch
140275 /// block.
141 BasicBlock *getLoopLatch() const;
276 BlockT *getLoopLatch() const {
277 BlockT *Header = getHeader();
278 pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
279 if (PI == PE) return 0; // no preds?
280
281 BlockT *Latch = 0;
282 if (contains(*PI))
283 Latch = *PI;
284 ++PI;
285 if (PI == PE) return 0; // only one pred?
286
287 if (contains(*PI)) {
288 if (Latch) return 0; // multiple backedges
289 Latch = *PI;
290 }
291 ++PI;
292 if (PI != PE) return 0; // more than two preds
293
294 return Latch;
295 }
142296
143297 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
144298 /// induction variable: an integer recurrence that starts at 0 and increments
145299 /// by one each time through the loop. If so, return the phi node that
146300 /// corresponds to it.
147301 ///
148 PHINode *getCanonicalInductionVariable() const;
302 PHINode *getCanonicalInductionVariable() const {
303 BlockT *H = getHeader();
304
305 BlockT *Incoming = 0, *Backedge = 0;
306 pred_iterator PI = pred_begin(H);
307 assert(PI != pred_end(H) && "Loop must have at least one backedge!");
308 Backedge = *PI++;
309 if (PI == pred_end(H)) return 0; // dead loop
310 Incoming = *PI++;
311 if (PI != pred_end(H)) return 0; // multiple backedges?
312
313 if (contains(Incoming)) {
314 if (contains(Backedge))
315 return 0;
316 std::swap(Incoming, Backedge);
317 } else if (!contains(Backedge))
318 return 0;
319
320 // Loop over all of the PHI nodes, looking for a canonical indvar.
321 for (typename BlockT::iterator I = H->begin(); isa(I); ++I) {
322 PHINode *PN = cast(I);
323 if (Instruction *Inc =
324 dyn_cast(PN->getIncomingValueForBlock(Backedge)))
325 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
326 if (ConstantInt *CI = dyn_cast(Inc->getOperand(1)))
327 if (CI->equalsInt(1))
328 return PN;
329 }
330 return 0;
331 }
149332
150333 /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
151334 /// the canonical induction variable value for the "next" iteration of the
152335 /// loop. This always succeeds if getCanonicalInductionVariable succeeds.
153336 ///
154 Instruction *getCanonicalInductionVariableIncrement() const;
337 Instruction *getCanonicalInductionVariableIncrement() const {
338 if (PHINode *PN = getCanonicalInductionVariable()) {
339 bool P1InLoop = contains(PN->getIncomingBlock(1));
340 return cast(PN->getIncomingValue(P1InLoop));
341 }
342 return 0;
343 }
155344
156345 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
157346 /// times the loop will be executed. Note that this means that the backedge
158347 /// of the loop executes N-1 times. If the trip-count cannot be determined,
159348 /// this returns null.
160349 ///
161 Value *getTripCount() const;
350 Value *getTripCount() const {
351 // Canonical loops will end with a 'cmp ne I, V', where I is the incremented
352 // canonical induction variable and V is the trip count of the loop.
353 Instruction *Inc = getCanonicalInductionVariableIncrement();
354 if (Inc == 0) return 0;
355 PHINode *IV = cast(Inc->getOperand(0));
356
357 BlockT *BackedgeBlock =
358 IV->getIncomingBlock(contains(IV->getIncomingBlock(1)));
359
360 if (BranchInst *BI = dyn_cast(BackedgeBlock->getTerminator()))
361 if (BI->isConditional()) {
362 if (ICmpInst *ICI = dyn_cast(BI->getCondition())) {
363 if (ICI->getOperand(0) == Inc)
364 if (BI->getSuccessor(0) == getHeader()) {
365 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
366 return ICI->getOperand(1);
367 } else if (ICI->getPredicate() == ICmpInst::ICMP_EQ) {
368 return ICI->getOperand(1);
369 }
370 }
371 }
372
373 return 0;
374 }
162375
163376 /// isLCSSAForm - Return true if the Loop is in LCSSA form
164 bool isLCSSAForm() const;
377 bool isLCSSAForm() const {
378 // Sort the blocks vector so that we can use binary search to do quick
379 // lookups.
380 SmallPtrSet LoopBBs(block_begin(), block_end());
381
382 for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
383 BlockT *BB = *BI;
384 for (typename BlockT::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
385 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
386 ++UI) {
387 BlockT *UserBB = cast(*UI)->getParent();
388 if (PHINode *P = dyn_cast(*UI)) {
389 unsigned OperandNo = UI.getOperandNo();
390 UserBB = P->getIncomingBlock(OperandNo/2);
391 }
392
393 // Check the current block, as a fast-path. Most values are used in the
394 // same block they are defined in.
395 if (UserBB != BB && !LoopBBs.count(UserBB))
396 return false;
397 }
398 }
399
400 return true;
401 }
165402
166403 //===--------------------------------------------------------------------===//
167404 // APIs for updating loop information after changing the CFG
173410 /// to the specified LoopInfo object as being in the current basic block. It
174411 /// is not valid to replace the loop header with this method.
175412 ///
176 void addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI);
413 void addBasicBlockToLoop(BlockT *NewBB, LoopInfo &LI);
177414
178415 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
179416 /// the OldChild entry in our children list with NewChild, and updates the
180417 /// parent pointer of OldChild to be null and the NewChild to be this loop.
181418 /// This updates the loop depth of the new child.
182 void replaceChildLoopWith(Loop *OldChild, Loop *NewChild);
419 void replaceChildLoopWith(LoopBase *OldChild,
420 LoopBase *NewChild) {
421 assert(OldChild->ParentLoop == this && "This loop is already broken!");
422 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
423 typename std::vector*>::iterator I =
424 std::find(SubLoops.begin(), SubLoops.end(), OldChild);
425 assert(I != SubLoops.end() && "OldChild not in loop!");
426 *I = NewChild;
427 OldChild->ParentLoop = 0;
428 NewChild->ParentLoop = this;
429 }
183430
184431 /// addChildLoop - Add the specified loop to be a child of this loop. This
185432 /// updates the loop depth of the new child.
186433 ///
187 void addChildLoop(Loop *NewChild);
434 void addChildLoop(LoopBase *NewChild) {
435 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
436 NewChild->ParentLoop = this;
437 SubLoops.push_back(NewChild);
438 }
188439
189440 /// removeChildLoop - This removes the specified child from being a subloop of
190441 /// this loop. The loop is not deleted, as it will presumably be inserted
191442 /// into another loop.
192 Loop *removeChildLoop(iterator OldChild);
443 LoopBase *removeChildLoop(iterator I) {
444 assert(I != SubLoops.end() && "Cannot remove end iterator!");
445 LoopBase *Child = *I;
446 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
447 SubLoops.erase(SubLoops.begin()+(I-begin()));
448 Child->ParentLoop = 0;
449 return Child;
450 }
193451
194452 /// addBlockEntry - This adds a basic block directly to the basic block list.
195453 /// This should only be used by transformations that create new loops. Other
196454 /// transformations should use addBasicBlockToLoop.
197 void addBlockEntry(BasicBlock *BB) {
455 void addBlockEntry(BlockT *BB) {
198456 Blocks.push_back(BB);
199457 }
200458
201459 /// moveToHeader - This method is used to move BB (which must be part of this
202460 /// loop) to be the loop header of the loop (the block that dominates all
203461 /// others).
204 void moveToHeader(BasicBlock *BB) {
462 void moveToHeader(BlockT *BB) {
205463 if (Blocks[0] == BB) return;
206464 for (unsigned i = 0; ; ++i) {
207465 assert(i != Blocks.size() && "Loop does not contain BB!");
216474 /// removeBlockFromLoop - This removes the specified basic block from the
217475 /// current loop, updating the Blocks as appropriate. This does not update
218476 /// the mapping in the LoopInfo class.
219 void removeBlockFromLoop(BasicBlock *BB);
477 void removeBlockFromLoop(BlockT *BB) {
478 RemoveFromVector(Blocks, BB);
479 }
220480
221481 /// verifyLoop - Verify loop structure
222 void verifyLoop() const;
223
224 void print(std::ostream &O, unsigned Depth = 0) const;
482 void verifyLoop() const {
483 #ifndef NDEBUG
484 assert (getHeader() && "Loop header is missing");
485 assert (getLoopPreheader() && "Loop preheader is missing");
486 assert (getLoopLatch() && "Loop latch is missing");
487 for (typename std::vector*>::const_iterator I =
488 SubLoops.begin(), E = SubLoops.end(); I != E; ++I)
489 (*I)->verifyLoop();
490 #endif
491 }
492
493 void print(std::ostream &OS, unsigned Depth = 0) const {
494 OS << std::string(Depth*2, ' ') << "Loop Containing: ";
495
496 for (unsigned i = 0; i < getBlocks().size(); ++i) {
497 if (i) OS << ",";
498 WriteAsOperand(OS, getBlocks()[i], false);
499 }
500 OS << "\n";
501
502 for (iterator I = begin(), E = end(); I != E; ++I)
503 (*I)->print(OS, Depth+2);
504 }
505
225506 void print(std::ostream *O, unsigned Depth = 0) const {
226507 if (O) print(*O, Depth);
227508 }
228 void dump() const;
509
510 void dump() const {
511 print(cerr);
512 }
513
229514 private:
230515 friend class LoopInfo;
231 Loop(BasicBlock *BB) : ParentLoop(0) {
516 LoopBase(BlockT *BB) : ParentLoop(0) {
232517 Blocks.push_back(BB);
233518 }
234519 };
235520
521 typedef LoopBase Loop;
236522
237523
238524 //===----------------------------------------------------------------------===//
243529 // BBMap - Mapping of basic blocks to the inner most loop they occur in
244530 std::map BBMap;
245531 std::vector TopLevelLoops;
246 friend class Loop;
532 friend class LoopBase;
247533 public:
248534 static char ID; // Pass identification, replacement for typeid
249535
359645 }
360646 };
361647
648 template
649 void LoopBase::addBasicBlockToLoop(BlockT *NewBB, LoopInfo &LI) {
650 assert((Blocks.empty() || LI[getHeader()] == this) &&
651 "Incorrect LI specified for this loop!");
652 assert(NewBB && "Cannot add a null basic block to the loop!");
653 assert(LI[NewBB] == 0 && "BasicBlock already in the loop!");
654
655 // Add the loop mapping to the LoopInfo object...
656 LI.BBMap[NewBB] = this;
657
658 // Add the basic block to this loop and all parent loops...
659 LoopBase *L = this;
660 while (L) {
661 L->Blocks.push_back(NewBB);
662 L = L->getParentLoop();
663 }
664 }
665
362666 } // End llvm namespace
363667
364668 // Make sure that any clients of this file link in LoopInfo.cpp
2222 namespace llvm {
2323
2424 class LPPassManager;
25 class Loop;
2625 class Function;
2726
2827 class LoopPass : public Pass {
2121 #define LLVM_ANALYSIS_SCALAREVOLUTION_H
2222
2323 #include "llvm/Pass.h"
24 #include "llvm/Analysis/LoopInfo.h"
2425 #include "llvm/Support/DataTypes.h"
2526 #include "llvm/Support/Streams.h"
2627 #include
3132 class Instruction;
3233 class Type;
3334 class ConstantRange;
34 class Loop;
35 class LoopInfo;
3635 class SCEVHandle;
3736 class ScalarEvolution;
3837
1919
2020 #include
2121 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/Analysis/LoopInfo.h"
2223
2324 namespace llvm {
2425
2526 class Module;
2627 class Function;
27 class Loop;
28 class LoopInfo;
2928 class Pass;
3029 class LPPassManager;
3130 class BasicBlock;
1313 #ifndef LLVM_TRANSFORMS_UTILS_FUNCTION_H
1414 #define LLVM_TRANSFORMS_UTILS_FUNCTION_H
1515
16 #include
16 #include "llvm/Analysis/Dominators.h"
17 #include "llvm/Analysis/LoopInfo.h"
1718 #include
1819
1920 namespace llvm {
2021 class BasicBlock;
2122 class Function;
22 class Loop;
2323
2424 /// ExtractCodeRegion - rip out a sequence of basic blocks into a new function
2525 ///
3333 //===----------------------------------------------------------------------===//
3434 // Loop implementation
3535 //
36 bool Loop::contains(const BasicBlock *BB) const {
37 return std::find(Blocks.begin(), Blocks.end(), BB) != Blocks.end();
38 }
39
40 bool Loop::isLoopExit(const BasicBlock *BB) const {
41 for (succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB);
42 SI != SE; ++SI) {
43 if (!contains(*SI))
44 return true;
45 }
46 return false;
47 }
4836
4937 /// getNumBackEdges - Calculate the number of back edges to the loop header.
5038 ///
51 unsigned Loop::getNumBackEdges() const {
52 unsigned NumBackEdges = 0;
53 BasicBlock *H = getHeader();
54
55 for (pred_iterator I = pred_begin(H), E = pred_end(H); I != E; ++I)
56 if (contains(*I))
57 ++NumBackEdges;
58
59 return NumBackEdges;
60 }
61
62 /// isLoopInvariant - Return true if the specified value is loop invariant
63 ///
64 bool Loop::isLoopInvariant(Value *V) const {
65 if (Instruction *I = dyn_cast(V))
66 return !contains(I->getParent());
67 return true; // All non-instructions are loop invariant
68 }
69
70 void Loop::print(std::ostream &OS, unsigned Depth) const {
71 OS << std::string(Depth*2, ' ') << "Loop Containing: ";
72
73 for (unsigned i = 0; i < getBlocks().size(); ++i) {
74 if (i) OS << ",";
75 WriteAsOperand(OS, getBlocks()[i], false);
76 }
77 OS << "\n";
78
79 for (iterator I = begin(), E = end(); I != E; ++I)
80 (*I)->print(OS, Depth+2);
81 }
82
83 /// verifyLoop - Verify loop structure
84 void Loop::verifyLoop() const {
85 #ifndef NDEBUG
86 assert (getHeader() && "Loop header is missing");
87 assert (getLoopPreheader() && "Loop preheader is missing");
88 assert (getLoopLatch() && "Loop latch is missing");
89 for (std::vector::const_iterator I = SubLoops.begin(), E = SubLoops.end();
90 I != E; ++I)
91 (*I)->verifyLoop();
92 #endif
93 }
94
95 void Loop::dump() const {
96 print(cerr);
97 }
98
9939
10040 //===----------------------------------------------------------------------===//
10141 // LoopInfo implementation
340280 }
341281 }
342282
343
344 //===----------------------------------------------------------------------===//
345 // APIs for simple analysis of the loop.
346 //
347
348 /// getExitingBlocks - Return all blocks inside the loop that have successors
349 /// outside of the loop. These are the blocks _inside of the current loop_
350 /// which branch out. The returned list is always unique.
351 ///
352 void Loop::getExitingBlocks(SmallVectorImpl &ExitingBlocks) const {
353 // Sort the blocks vector so that we can use binary search to do quick
354 // lookups.
355 SmallVector LoopBBs(block_begin(), block_end());
356 std::sort(LoopBBs.begin(), LoopBBs.end());
357
358 for (std::vector::const_iterator BI = Blocks.begin(),
359 BE = Blocks.end(); BI != BE; ++BI)
360 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I)
361 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
362 // Not in current loop? It must be an exit block.
363 ExitingBlocks.push_back(*BI);
364 break;
365 }
366 }
367
368 /// getExitBlocks - Return all of the successor blocks of this loop. These
369 /// are the blocks _outside of the current loop_ which are branched to.
370 ///
371 void Loop::getExitBlocks(SmallVectorImpl &ExitBlocks) const {
372 // Sort the blocks vector so that we can use binary search to do quick
373 // lookups.
374 SmallVector LoopBBs(block_begin(), block_end());
375 std::sort(LoopBBs.begin(), LoopBBs.end());
376
377 for (std::vector::const_iterator BI = Blocks.begin(),
378 BE = Blocks.end(); BI != BE; ++BI)
379 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I)
380 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
381 // Not in current loop? It must be an exit block.
382 ExitBlocks.push_back(*I);
383 }
384
385 /// getUniqueExitBlocks - Return all unique successor blocks of this loop. These
386 /// are the blocks _outside of the current loop_ which are branched to. This
387 /// assumes that loop is in canonical form.
388 //
389 void Loop::getUniqueExitBlocks(SmallVectorImpl &ExitBlocks) const {
390 // Sort the blocks vector so that we can use binary search to do quick
391 // lookups.
392 SmallVector LoopBBs(block_begin(), block_end());
393 std::sort(LoopBBs.begin(), LoopBBs.end());
394
395 std::vector switchExitBlocks;
396
397 for (std::vector::const_iterator BI = Blocks.begin(),
398 BE = Blocks.end(); BI != BE; ++BI) {
399
400 BasicBlock *current = *BI;
401 switchExitBlocks.clear();
402
403 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
404 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
405 // If block is inside the loop then it is not a exit block.
406 continue;
407
408 pred_iterator PI = pred_begin(*I);
409 BasicBlock *firstPred = *PI;
410
411 // If current basic block is this exit block's first predecessor
412 // then only insert exit block in to the output ExitBlocks vector.
413 // This ensures that same exit block is not inserted twice into
414 // ExitBlocks vector.
415 if (current != firstPred)
416 continue;
417
418 // If a terminator has more then two successors, for example SwitchInst,
419 // then it is possible that there are multiple edges from current block
420 // to one exit block.
421 if (current->getTerminator()->getNumSuccessors() <= 2) {
422 ExitBlocks.push_back(*I);
423 continue;
424 }
425
426 // In case of multiple edges from current block to exit block, collect
427 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
428 // duplicate edges.
429 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
430 == switchExitBlocks.end()) {
431 switchExitBlocks.push_back(*I);
432 ExitBlocks.push_back(*I);
433 }
434 }
435 }
436 }
437
438
439 /// getLoopPreheader - If there is a preheader for this loop, return it. A
440 /// loop has a preheader if there is only one edge to the header of the loop
441 /// from outside of the loop. If this is the case, the block branching to the
442 /// header of the loop is the preheader node.
443 ///
444 /// This method returns null if there is no preheader for the loop.
445 ///
446 BasicBlock *Loop::getLoopPreheader() const {
447 // Keep track of nodes outside the loop branching to the header...
448 BasicBlock *Out = 0;
449
450 // Loop over the predecessors of the header node...
451 BasicBlock *Header = getHeader();
452 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
453 PI != PE; ++PI)
454 if (!contains(*PI)) { // If the block is not in the loop...
455 if (Out && Out != *PI)
456 return 0; // Multiple predecessors outside the loop
457 Out = *PI;
458 }
459
460 // Make sure there is only one exit out of the preheader.
461 assert(Out && "Header of loop has no predecessors from outside loop?");
462 succ_iterator SI = succ_begin(Out);
463 ++SI;
464 if (SI != succ_end(Out))
465 return 0; // Multiple exits from the block, must not be a preheader.
466
467 // If there is exactly one preheader, return it. If there was zero, then Out
468 // is still null.
469 return Out;
470 }
471
472 /// getLoopLatch - If there is a latch block for this loop, return it. A
473 /// latch block is the canonical backedge for a loop. A loop header in normal
474 /// form has two edges into it: one from a preheader and one from a latch
475 /// block.
476 BasicBlock *Loop::getLoopLatch() const {
477 BasicBlock *Header = getHeader();
478 pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
479 if (PI == PE) return 0; // no preds?
480
481 BasicBlock *Latch = 0;
482 if (contains(*PI))
483 Latch = *PI;
484 ++PI;
485 if (PI == PE) return 0; // only one pred?
486
487 if (contains(*PI)) {
488 if (Latch) return 0; // multiple backedges
489 Latch = *PI;
490 }
491 ++PI;
492 if (PI != PE) return 0; // more than two preds
493
494 return Latch;
495 }
496
497 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
498 /// induction variable: an integer recurrence that starts at 0 and increments by
499 /// one each time through the loop. If so, return the phi node that corresponds
500 /// to it.
501 ///
502 PHINode *Loop::getCanonicalInductionVariable() const {
503 BasicBlock *H = getHeader();
504
505 BasicBlock *Incoming = 0, *Backedge = 0;
506 pred_iterator PI = pred_begin(H);
507 assert(PI != pred_end(H) && "Loop must have at least one backedge!");
508 Backedge = *PI++;
509 if (PI == pred_end(H)) return 0; // dead loop
510 Incoming = *PI++;
511 if (PI != pred_end(H)) return 0; // multiple backedges?
512
513 if (contains(Incoming)) {
514 if (contains(Backedge))
515 return 0;
516 std::swap(Incoming, Backedge);
517 } else if (!contains(Backedge))
518 return 0;
519
520 // Loop over all of the PHI nodes, looking for a canonical indvar.
521 for (BasicBlock::iterator I = H->begin(); isa(I); ++I) {
522 PHINode *PN = cast(I);
523 if (Instruction *Inc =
524 dyn_cast(PN->getIncomingValueForBlock(Backedge)))
525 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
526 if (ConstantInt *CI = dyn_cast(Inc->getOperand(1)))
527 if (CI->equalsInt(1))
528 return PN;
529 }
530 return 0;
531 }
532
533 /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
534 /// the canonical induction variable value for the "next" iteration of the loop.
535 /// This always succeeds if getCanonicalInductionVariable succeeds.
536 ///
537 Instruction *Loop::getCanonicalInductionVariableIncrement() const {
538 if (PHINode *PN = getCanonicalInductionVariable()) {
539 bool P1InLoop = contains(PN->getIncomingBlock(1));
540 return cast(PN->getIncomingValue(P1InLoop));
541 }
542 return 0;
543 }
544
545 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
546 /// times the loop will be executed. Note that this means that the backedge of
547 /// the loop executes N-1 times. If the trip-count cannot be determined, this
548 /// returns null.
549 ///
550 Value *Loop::getTripCount() const {
551 // Canonical loops will end with a 'cmp ne I, V', where I is the incremented
552 // canonical induction variable and V is the trip count of the loop.
553 Instruction *Inc = getCanonicalInductionVariableIncrement();
554 if (Inc == 0) return 0;
555 PHINode *IV = cast(Inc->getOperand(0));
556
557 BasicBlock *BackedgeBlock =
558 IV->getIncomingBlock(contains(IV->getIncomingBlock(1)));
559
560 if (BranchInst *BI = dyn_cast(BackedgeBlock->getTerminator()))
561 if (BI->isConditional()) {
562 if (ICmpInst *ICI = dyn_cast(BI->getCondition())) {
563 if (ICI->getOperand(0) == Inc)
564 if (BI->getSuccessor(0) == getHeader()) {
565 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
566 return ICI->getOperand(1);
567 } else if (ICI->getPredicate() == ICmpInst::ICMP_EQ) {
568 return ICI->getOperand(1);
569 }
570 }
571 }
572
573 return 0;
574 }
575
576 /// isLCSSAForm - Return true if the Loop is in LCSSA form
577 bool Loop::isLCSSAForm() const {
578 // Sort the blocks vector so that we can use binary search to do quick
579 // lookups.
580 SmallPtrSet LoopBBs(block_begin(), block_end());
581
582 for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
583 BasicBlock *BB = *BI;
584 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
585 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
586 ++UI) {
587 BasicBlock *UserBB = cast(*UI)->getParent();
588 if (PHINode *P = dyn_cast(*UI)) {
589 unsigned OperandNo = UI.getOperandNo();
590 UserBB = P->getIncomingBlock(OperandNo/2);
591 }
592
593 // Check the current block, as a fast-path. Most values are used in the
594 // same block they are defined in.
595 if (UserBB != BB && !LoopBBs.count(UserBB))
596 return false;
597 }
598 }
599
600 return true;
601 }
602
603 //===-------------------------------------------------------------------===//
604 // APIs for updating loop information after changing the CFG
605 //
606
607 /// addBasicBlockToLoop - This function is used by other analyses to update loop
608 /// information. NewBB is set to be a new member of the current loop. Because
609 /// of this, it is added as a member of all parent loops, and is added to the
610 /// specified LoopInfo object as being in the current basic block. It is not
611 /// valid to replace the loop header with this method.
612 ///
613 void Loop::addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI) {
614 assert((Blocks.empty() || LI[getHeader()] == this) &&
615 "Incorrect LI specified for this loop!");
616 assert(NewBB && "Cannot add a null basic block to the loop!");
617 assert(LI[NewBB] == 0 && "BasicBlock already in the loop!");
618
619 // Add the loop mapping to the LoopInfo object...
620 LI.BBMap[NewBB] = this;
621
622 // Add the basic block to this loop and all parent loops...
623 Loop *L = this;
624 while (L) {
625 L->Blocks.push_back(NewBB);
626 L = L->getParentLoop();
627 }
628 }
629
630 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
631 /// the OldChild entry in our children list with NewChild, and updates the
632 /// parent pointers of the two loops as appropriate.
633 void Loop::replaceChildLoopWith(Loop *OldChild, Loop *NewChild) {
634 assert(OldChild->ParentLoop == this && "This loop is already broken!");
635 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
636 std::vector::iterator I = std::find(SubLoops.begin(), SubLoops.end(),
637 OldChild);
638 assert(I != SubLoops.end() && "OldChild not in loop!");
639 *I = NewChild;
640 OldChild->ParentLoop = 0;
641 NewChild->ParentLoop = this;
642 }
643
644 /// addChildLoop - Add the specified loop to be a child of this loop.
645 ///
646 void Loop::addChildLoop(Loop *NewChild) {
647 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
648 NewChild->ParentLoop = this;
649 SubLoops.push_back(NewChild);
650 }
651
652 template
653 static void RemoveFromVector(std::vector &V, T *N) {
654 typename std::vector::iterator I = std::find(V.begin(), V.end(), N);
655 assert(I != V.end() && "N is not in this list!");
656 V.erase(I);
657 }
658
659 /// removeChildLoop - This removes the specified child from being a subloop of
660 /// this loop. The loop is not deleted, as it will presumably be inserted
661 /// into another loop.
662 Loop *Loop::removeChildLoop(iterator I) {
663 assert(I != SubLoops.end() && "Cannot remove end iterator!");
664 Loop *Child = *I;
665 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
666 SubLoops.erase(SubLoops.begin()+(I-begin()));
667 Child->ParentLoop = 0;
668 return Child;
669 }
670
671
672 /// removeBlockFromLoop - This removes the specified basic block from the
673 /// current loop, updating the Blocks and ExitBlocks lists as appropriate. This
674 /// does not update the mapping in the LoopInfo class.
675 void Loop::removeBlockFromLoop(BasicBlock *BB) {
676 RemoveFromVector(Blocks, BB);
677 }
678
679283 // Ensure this file gets linked when LoopInfo.h is used.
680284 DEFINING_FILE_FOR(LoopInfo)