1 //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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. A natural loop
12 // has exactly one entry-point, which is called the header. Note that natural
13 // loops may actually be several loops that share the same header node.
14 //
15 // This analysis calculates the nesting structure of loops in a function. For
16 // each natural loop identified, this analysis identifies natural loops
17 // contained entirely within the loop and the basic blocks the make up the loop.
18 //
19 // It can calculate on the fly various bits of information, for example:
20 //
21 // * whether there is a preheader for the loop
22 // * the number of back edges to the header
23 // * whether or not a particular block branches out of the loop
24 // * the successor blocks of the loop
25 // * the loop depth
26 // * etc...
27 //
28 //===----------------------------------------------------------------------===//
29
30 #ifndef LLVM_ANALYSIS_LOOPINFO_H
31 #define LLVM_ANALYSIS_LOOPINFO_H
32
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/DenseSet.h"
35 #include "llvm/ADT/GraphTraits.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/Analysis/Dominators.h"
38 #include "llvm/Pass.h"
39 #include <algorithm>
40
41 namespace llvm {
42
43 template<typename T>
RemoveFromVector(std::vector<T * > & V,T * N)44 inline void RemoveFromVector(std::vector<T*> &V, T *N) {
45 typename std::vector<T*>::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 }
49
50 class DominatorTree;
51 class LoopInfo;
52 class Loop;
53 class MDNode;
54 class PHINode;
55 class raw_ostream;
56 template<class N, class M> class LoopInfoBase;
57 template<class N, class M> class LoopBase;
58
59 //===----------------------------------------------------------------------===//
60 /// LoopBase class - Instances of this class are used to represent loops that
61 /// are detected in the flow graph
62 ///
63 template<class BlockT, class LoopT>
64 class LoopBase {
65 LoopT *ParentLoop;
66 // SubLoops - Loops contained entirely within this one.
67 std::vector<LoopT *> SubLoops;
68
69 // Blocks - The list of blocks in this loop. First entry is the header node.
70 std::vector<BlockT*> Blocks;
71
72 LoopBase(const LoopBase<BlockT, LoopT> &) LLVM_DELETED_FUNCTION;
73 const LoopBase<BlockT, LoopT>&
74 operator=(const LoopBase<BlockT, LoopT> &) LLVM_DELETED_FUNCTION;
75 public:
76 /// Loop ctor - This creates an empty loop.
LoopBase()77 LoopBase() : ParentLoop(0) {}
~LoopBase()78 ~LoopBase() {
79 for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
80 delete SubLoops[i];
81 }
82
83 /// getLoopDepth - Return the nesting level of this loop. An outer-most
84 /// loop has depth 1, for consistency with loop depth values used for basic
85 /// blocks, where depth 0 is used for blocks not inside any loops.
getLoopDepth()86 unsigned getLoopDepth() const {
87 unsigned D = 1;
88 for (const LoopT *CurLoop = ParentLoop; CurLoop;
89 CurLoop = CurLoop->ParentLoop)
90 ++D;
91 return D;
92 }
getHeader()93 BlockT *getHeader() const { return Blocks.front(); }
getParentLoop()94 LoopT *getParentLoop() const { return ParentLoop; }
95
96 /// setParentLoop is a raw interface for bypassing addChildLoop.
setParentLoop(LoopT * L)97 void setParentLoop(LoopT *L) { ParentLoop = L; }
98
99 /// contains - Return true if the specified loop is contained within in
100 /// this loop.
101 ///
contains(const LoopT * L)102 bool contains(const LoopT *L) const {
103 if (L == this) return true;
104 if (L == 0) return false;
105 return contains(L->getParentLoop());
106 }
107
108 /// contains - Return true if the specified basic block is in this loop.
109 ///
contains(const BlockT * BB)110 bool contains(const BlockT *BB) const {
111 return std::find(block_begin(), block_end(), BB) != block_end();
112 }
113
114 /// contains - Return true if the specified instruction is in this loop.
115 ///
116 template<class InstT>
contains(const InstT * Inst)117 bool contains(const InstT *Inst) const {
118 return contains(Inst->getParent());
119 }
120
121 /// iterator/begin/end - Return the loops contained entirely within this loop.
122 ///
getSubLoops()123 const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
getSubLoopsVector()124 std::vector<LoopT *> &getSubLoopsVector() { return SubLoops; }
125 typedef typename std::vector<LoopT *>::const_iterator iterator;
126 typedef typename std::vector<LoopT *>::const_reverse_iterator
127 reverse_iterator;
begin()128 iterator begin() const { return SubLoops.begin(); }
end()129 iterator end() const { return SubLoops.end(); }
rbegin()130 reverse_iterator rbegin() const { return SubLoops.rbegin(); }
rend()131 reverse_iterator rend() const { return SubLoops.rend(); }
empty()132 bool empty() const { return SubLoops.empty(); }
133
134 /// getBlocks - Get a list of the basic blocks which make up this loop.
135 ///
getBlocks()136 const std::vector<BlockT*> &getBlocks() const { return Blocks; }
getBlocksVector()137 std::vector<BlockT*> &getBlocksVector() { return Blocks; }
138 typedef typename std::vector<BlockT*>::const_iterator block_iterator;
block_begin()139 block_iterator block_begin() const { return Blocks.begin(); }
block_end()140 block_iterator block_end() const { return Blocks.end(); }
141
142 /// getNumBlocks - Get the number of blocks in this loop in constant time.
getNumBlocks()143 unsigned getNumBlocks() const {
144 return Blocks.size();
145 }
146
147 /// isLoopExiting - True if terminator in the block can branch to another
148 /// block that is outside of the current loop.
149 ///
isLoopExiting(const BlockT * BB)150 bool isLoopExiting(const BlockT *BB) const {
151 typedef GraphTraits<const BlockT*> BlockTraits;
152 for (typename BlockTraits::ChildIteratorType SI =
153 BlockTraits::child_begin(BB),
154 SE = BlockTraits::child_end(BB); SI != SE; ++SI) {
155 if (!contains(*SI))
156 return true;
157 }
158 return false;
159 }
160
161 /// getNumBackEdges - Calculate the number of back edges to the loop header
162 ///
getNumBackEdges()163 unsigned getNumBackEdges() const {
164 unsigned NumBackEdges = 0;
165 BlockT *H = getHeader();
166
167 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
168 for (typename InvBlockTraits::ChildIteratorType I =
169 InvBlockTraits::child_begin(H),
170 E = InvBlockTraits::child_end(H); I != E; ++I)
171 if (contains(*I))
172 ++NumBackEdges;
173
174 return NumBackEdges;
175 }
176
177 //===--------------------------------------------------------------------===//
178 // APIs for simple analysis of the loop.
179 //
180 // Note that all of these methods can fail on general loops (ie, there may not
181 // be a preheader, etc). For best success, the loop simplification and
182 // induction variable canonicalization pass should be used to normalize loops
183 // for easy analysis. These methods assume canonical loops.
184
185 /// getExitingBlocks - Return all blocks inside the loop that have successors
186 /// outside of the loop. These are the blocks _inside of the current loop_
187 /// which branch out. The returned list is always unique.
188 ///
189 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
190
191 /// getExitingBlock - If getExitingBlocks would return exactly one block,
192 /// return that block. Otherwise return null.
193 BlockT *getExitingBlock() const;
194
195 /// getExitBlocks - Return all of the successor blocks of this loop. These
196 /// are the blocks _outside of the current loop_ which are branched to.
197 ///
198 void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const;
199
200 /// getExitBlock - If getExitBlocks would return exactly one block,
201 /// return that block. Otherwise return null.
202 BlockT *getExitBlock() const;
203
204 /// Edge type.
205 typedef std::pair<const BlockT*, const BlockT*> Edge;
206
207 /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
208 void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
209
210 /// getLoopPreheader - If there is a preheader for this loop, return it. A
211 /// loop has a preheader if there is only one edge to the header of the loop
212 /// from outside of the loop. If this is the case, the block branching to the
213 /// header of the loop is the preheader node.
214 ///
215 /// This method returns null if there is no preheader for the loop.
216 ///
217 BlockT *getLoopPreheader() const;
218
219 /// getLoopPredecessor - If the given loop's header has exactly one unique
220 /// predecessor outside the loop, return it. Otherwise return null.
221 /// This is less strict that the loop "preheader" concept, which requires
222 /// the predecessor to have exactly one successor.
223 ///
224 BlockT *getLoopPredecessor() const;
225
226 /// getLoopLatch - If there is a single latch block for this loop, return it.
227 /// A latch block is a block that contains a branch back to the header.
228 BlockT *getLoopLatch() const;
229
230 //===--------------------------------------------------------------------===//
231 // APIs for updating loop information after changing the CFG
232 //
233
234 /// addBasicBlockToLoop - This method is used by other analyses to update loop
235 /// information. NewBB is set to be a new member of the current loop.
236 /// Because of this, it is added as a member of all parent loops, and is added
237 /// to the specified LoopInfo object as being in the current basic block. It
238 /// is not valid to replace the loop header with this method.
239 ///
240 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
241
242 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
243 /// the OldChild entry in our children list with NewChild, and updates the
244 /// parent pointer of OldChild to be null and the NewChild to be this loop.
245 /// This updates the loop depth of the new child.
246 void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
247
248 /// addChildLoop - Add the specified loop to be a child of this loop. This
249 /// updates the loop depth of the new child.
250 ///
addChildLoop(LoopT * NewChild)251 void addChildLoop(LoopT *NewChild) {
252 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
253 NewChild->ParentLoop = static_cast<LoopT *>(this);
254 SubLoops.push_back(NewChild);
255 }
256
257 /// removeChildLoop - This removes the specified child from being a subloop of
258 /// this loop. The loop is not deleted, as it will presumably be inserted
259 /// into another loop.
removeChildLoop(iterator I)260 LoopT *removeChildLoop(iterator I) {
261 assert(I != SubLoops.end() && "Cannot remove end iterator!");
262 LoopT *Child = *I;
263 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
264 SubLoops.erase(SubLoops.begin()+(I-begin()));
265 Child->ParentLoop = 0;
266 return Child;
267 }
268
269 /// addBlockEntry - This adds a basic block directly to the basic block list.
270 /// This should only be used by transformations that create new loops. Other
271 /// transformations should use addBasicBlockToLoop.
addBlockEntry(BlockT * BB)272 void addBlockEntry(BlockT *BB) {
273 Blocks.push_back(BB);
274 }
275
276 /// moveToHeader - This method is used to move BB (which must be part of this
277 /// loop) to be the loop header of the loop (the block that dominates all
278 /// others).
moveToHeader(BlockT * BB)279 void moveToHeader(BlockT *BB) {
280 if (Blocks[0] == BB) return;
281 for (unsigned i = 0; ; ++i) {
282 assert(i != Blocks.size() && "Loop does not contain BB!");
283 if (Blocks[i] == BB) {
284 Blocks[i] = Blocks[0];
285 Blocks[0] = BB;
286 return;
287 }
288 }
289 }
290
291 /// removeBlockFromLoop - This removes the specified basic block from the
292 /// current loop, updating the Blocks as appropriate. This does not update
293 /// the mapping in the LoopInfo class.
removeBlockFromLoop(BlockT * BB)294 void removeBlockFromLoop(BlockT *BB) {
295 RemoveFromVector(Blocks, BB);
296 }
297
298 /// verifyLoop - Verify loop structure
299 void verifyLoop() const;
300
301 /// verifyLoop - Verify loop structure of this loop and all nested loops.
302 void verifyLoopNest(DenseSet<const LoopT*> *Loops) const;
303
304 void print(raw_ostream &OS, unsigned Depth = 0) const;
305
306 protected:
307 friend class LoopInfoBase<BlockT, LoopT>;
LoopBase(BlockT * BB)308 explicit LoopBase(BlockT *BB) : ParentLoop(0) {
309 Blocks.push_back(BB);
310 }
311 };
312
313 template<class BlockT, class LoopT>
314 raw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
315 Loop.print(OS);
316 return OS;
317 }
318
319 // Implementation in LoopInfoImpl.h
320 #ifdef __GNUC__
321 __extension__ extern template class LoopBase<BasicBlock, Loop>;
322 #endif
323
324 class Loop : public LoopBase<BasicBlock, Loop> {
325 public:
Loop()326 Loop() {}
327
328 /// isLoopInvariant - Return true if the specified value is loop invariant
329 ///
330 bool isLoopInvariant(Value *V) const;
331
332 /// hasLoopInvariantOperands - Return true if all the operands of the
333 /// specified instruction are loop invariant.
334 bool hasLoopInvariantOperands(Instruction *I) const;
335
336 /// makeLoopInvariant - If the given value is an instruction inside of the
337 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
338 /// Return true if the value after any hoisting is loop invariant. This
339 /// function can be used as a slightly more aggressive replacement for
340 /// isLoopInvariant.
341 ///
342 /// If InsertPt is specified, it is the point to hoist instructions to.
343 /// If null, the terminator of the loop preheader is used.
344 ///
345 bool makeLoopInvariant(Value *V, bool &Changed,
346 Instruction *InsertPt = 0) const;
347
348 /// makeLoopInvariant - If the given instruction is inside of the
349 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
350 /// Return true if the instruction after any hoisting is loop invariant. This
351 /// function can be used as a slightly more aggressive replacement for
352 /// isLoopInvariant.
353 ///
354 /// If InsertPt is specified, it is the point to hoist instructions to.
355 /// If null, the terminator of the loop preheader is used.
356 ///
357 bool makeLoopInvariant(Instruction *I, bool &Changed,
358 Instruction *InsertPt = 0) const;
359
360 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
361 /// induction variable: an integer recurrence that starts at 0 and increments
362 /// by one each time through the loop. If so, return the phi node that
363 /// corresponds to it.
364 ///
365 /// The IndVarSimplify pass transforms loops to have a canonical induction
366 /// variable.
367 ///
368 PHINode *getCanonicalInductionVariable() const;
369
370 /// isLCSSAForm - Return true if the Loop is in LCSSA form
371 bool isLCSSAForm(DominatorTree &DT) const;
372
373 /// isLoopSimplifyForm - Return true if the Loop is in the form that
374 /// the LoopSimplify form transforms loops to, which is sometimes called
375 /// normal form.
376 bool isLoopSimplifyForm() const;
377
378 /// isSafeToClone - Return true if the loop body is safe to clone in practice.
379 bool isSafeToClone() const;
380
381 /// Returns true if the loop is annotated parallel.
382 ///
383 /// A parallel loop can be assumed to not contain any dependencies between
384 /// iterations by the compiler. That is, any loop-carried dependency checking
385 /// can be skipped completely when parallelizing the loop on the target
386 /// machine. Thus, if the parallel loop information originates from the
387 /// programmer, e.g. via the OpenMP parallel for pragma, it is the
388 /// programmer's responsibility to ensure there are no loop-carried
389 /// dependencies. The final execution order of the instructions across
390 /// iterations is not guaranteed, thus, the end result might or might not
391 /// implement actual concurrent execution of instructions across multiple
392 /// iterations.
393 bool isAnnotatedParallel() const;
394
395 /// Return the llvm.loop loop id metadata node for this loop if it is present.
396 ///
397 /// If this loop contains the same llvm.loop metadata on each branch to the
398 /// header then the node is returned. If any latch instruction does not
399 /// contain llvm.loop or or if multiple latches contain different nodes then
400 /// 0 is returned.
401 MDNode *getLoopID() const;
402 /// Set the llvm.loop loop id metadata for this loop.
403 ///
404 /// The LoopID metadata node will be added to each terminator instruction in
405 /// the loop that branches to the loop header.
406 ///
407 /// The LoopID metadata node should have one or more operands and the first
408 /// operand should should be the node itself.
409 void setLoopID(MDNode *LoopID) const;
410
411 /// hasDedicatedExits - Return true if no exit block for the loop
412 /// has a predecessor that is outside the loop.
413 bool hasDedicatedExits() const;
414
415 /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
416 /// These are the blocks _outside of the current loop_ which are branched to.
417 /// This assumes that loop exits are in canonical form.
418 ///
419 void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
420
421 /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
422 /// block, return that block. Otherwise return null.
423 BasicBlock *getUniqueExitBlock() const;
424
425 void dump() const;
426
427 private:
428 friend class LoopInfoBase<BasicBlock, Loop>;
Loop(BasicBlock * BB)429 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
430 };
431
432 //===----------------------------------------------------------------------===//
433 /// LoopInfo - This class builds and contains all of the top level loop
434 /// structures in the specified function.
435 ///
436
437 template<class BlockT, class LoopT>
438 class LoopInfoBase {
439 // BBMap - Mapping of basic blocks to the inner most loop they occur in
440 DenseMap<BlockT *, LoopT *> BBMap;
441 std::vector<LoopT *> TopLevelLoops;
442 friend class LoopBase<BlockT, LoopT>;
443 friend class LoopInfo;
444
445 void operator=(const LoopInfoBase &) LLVM_DELETED_FUNCTION;
446 LoopInfoBase(const LoopInfo &) LLVM_DELETED_FUNCTION;
447 public:
LoopInfoBase()448 LoopInfoBase() { }
~LoopInfoBase()449 ~LoopInfoBase() { releaseMemory(); }
450
releaseMemory()451 void releaseMemory() {
452 for (typename std::vector<LoopT *>::iterator I =
453 TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
454 delete *I; // Delete all of the loops...
455
456 BBMap.clear(); // Reset internal state of analysis
457 TopLevelLoops.clear();
458 }
459
460 /// iterator/begin/end - The interface to the top-level loops in the current
461 /// function.
462 ///
463 typedef typename std::vector<LoopT *>::const_iterator iterator;
464 typedef typename std::vector<LoopT *>::const_reverse_iterator
465 reverse_iterator;
begin()466 iterator begin() const { return TopLevelLoops.begin(); }
end()467 iterator end() const { return TopLevelLoops.end(); }
rbegin()468 reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
rend()469 reverse_iterator rend() const { return TopLevelLoops.rend(); }
empty()470 bool empty() const { return TopLevelLoops.empty(); }
471
472 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
473 /// block is in no loop (for example the entry node), null is returned.
474 ///
getLoopFor(const BlockT * BB)475 LoopT *getLoopFor(const BlockT *BB) const {
476 return BBMap.lookup(const_cast<BlockT*>(BB));
477 }
478
479 /// operator[] - same as getLoopFor...
480 ///
481 const LoopT *operator[](const BlockT *BB) const {
482 return getLoopFor(BB);
483 }
484
485 /// getLoopDepth - Return the loop nesting level of the specified block. A
486 /// depth of 0 means the block is not inside any loop.
487 ///
getLoopDepth(const BlockT * BB)488 unsigned getLoopDepth(const BlockT *BB) const {
489 const LoopT *L = getLoopFor(BB);
490 return L ? L->getLoopDepth() : 0;
491 }
492
493 // isLoopHeader - True if the block is a loop header node
isLoopHeader(BlockT * BB)494 bool isLoopHeader(BlockT *BB) const {
495 const LoopT *L = getLoopFor(BB);
496 return L && L->getHeader() == BB;
497 }
498
499 /// removeLoop - This removes the specified top-level loop from this loop info
500 /// object. The loop is not deleted, as it will presumably be inserted into
501 /// another loop.
removeLoop(iterator I)502 LoopT *removeLoop(iterator I) {
503 assert(I != end() && "Cannot remove end iterator!");
504 LoopT *L = *I;
505 assert(L->getParentLoop() == 0 && "Not a top-level loop!");
506 TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
507 return L;
508 }
509
510 /// changeLoopFor - Change the top-level loop that contains BB to the
511 /// specified loop. This should be used by transformations that restructure
512 /// the loop hierarchy tree.
changeLoopFor(BlockT * BB,LoopT * L)513 void changeLoopFor(BlockT *BB, LoopT *L) {
514 if (!L) {
515 BBMap.erase(BB);
516 return;
517 }
518 BBMap[BB] = L;
519 }
520
521 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
522 /// list with the indicated loop.
changeTopLevelLoop(LoopT * OldLoop,LoopT * NewLoop)523 void changeTopLevelLoop(LoopT *OldLoop,
524 LoopT *NewLoop) {
525 typename std::vector<LoopT *>::iterator I =
526 std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
527 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
528 *I = NewLoop;
529 assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
530 "Loops already embedded into a subloop!");
531 }
532
533 /// addTopLevelLoop - This adds the specified loop to the collection of
534 /// top-level loops.
addTopLevelLoop(LoopT * New)535 void addTopLevelLoop(LoopT *New) {
536 assert(New->getParentLoop() == 0 && "Loop already in subloop!");
537 TopLevelLoops.push_back(New);
538 }
539
540 /// removeBlock - This method completely removes BB from all data structures,
541 /// including all of the Loop objects it is nested in and our mapping from
542 /// BasicBlocks to loops.
removeBlock(BlockT * BB)543 void removeBlock(BlockT *BB) {
544 typename DenseMap<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
545 if (I != BBMap.end()) {
546 for (LoopT *L = I->second; L; L = L->getParentLoop())
547 L->removeBlockFromLoop(BB);
548
549 BBMap.erase(I);
550 }
551 }
552
553 // Internals
554
isNotAlreadyContainedIn(const LoopT * SubLoop,const LoopT * ParentLoop)555 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
556 const LoopT *ParentLoop) {
557 if (SubLoop == 0) return true;
558 if (SubLoop == ParentLoop) return false;
559 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
560 }
561
562 /// Create the loop forest using a stable algorithm.
563 void Analyze(DominatorTreeBase<BlockT> &DomTree);
564
565 // Debugging
566
567 void print(raw_ostream &OS) const;
568 };
569
570 // Implementation in LoopInfoImpl.h
571 #ifdef __GNUC__
572 __extension__ extern template class LoopInfoBase<BasicBlock, Loop>;
573 #endif
574
575 class LoopInfo : public FunctionPass {
576 LoopInfoBase<BasicBlock, Loop> LI;
577 friend class LoopBase<BasicBlock, Loop>;
578
579 void operator=(const LoopInfo &) LLVM_DELETED_FUNCTION;
580 LoopInfo(const LoopInfo &) LLVM_DELETED_FUNCTION;
581 public:
582 static char ID; // Pass identification, replacement for typeid
583
LoopInfo()584 LoopInfo() : FunctionPass(ID) {
585 initializeLoopInfoPass(*PassRegistry::getPassRegistry());
586 }
587
getBase()588 LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; }
589
590 /// iterator/begin/end - The interface to the top-level loops in the current
591 /// function.
592 ///
593 typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator;
594 typedef LoopInfoBase<BasicBlock, Loop>::reverse_iterator reverse_iterator;
begin()595 inline iterator begin() const { return LI.begin(); }
end()596 inline iterator end() const { return LI.end(); }
rbegin()597 inline reverse_iterator rbegin() const { return LI.rbegin(); }
rend()598 inline reverse_iterator rend() const { return LI.rend(); }
empty()599 bool empty() const { return LI.empty(); }
600
601 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
602 /// block is in no loop (for example the entry node), null is returned.
603 ///
getLoopFor(const BasicBlock * BB)604 inline Loop *getLoopFor(const BasicBlock *BB) const {
605 return LI.getLoopFor(BB);
606 }
607
608 /// operator[] - same as getLoopFor...
609 ///
610 inline const Loop *operator[](const BasicBlock *BB) const {
611 return LI.getLoopFor(BB);
612 }
613
614 /// getLoopDepth - Return the loop nesting level of the specified block. A
615 /// depth of 0 means the block is not inside any loop.
616 ///
getLoopDepth(const BasicBlock * BB)617 inline unsigned getLoopDepth(const BasicBlock *BB) const {
618 return LI.getLoopDepth(BB);
619 }
620
621 // isLoopHeader - True if the block is a loop header node
isLoopHeader(BasicBlock * BB)622 inline bool isLoopHeader(BasicBlock *BB) const {
623 return LI.isLoopHeader(BB);
624 }
625
626 /// runOnFunction - Calculate the natural loop information.
627 ///
628 virtual bool runOnFunction(Function &F);
629
630 virtual void verifyAnalysis() const;
631
releaseMemory()632 virtual void releaseMemory() { LI.releaseMemory(); }
633
634 virtual void print(raw_ostream &O, const Module* M = 0) const;
635
636 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
637
638 /// removeLoop - This removes the specified top-level loop from this loop info
639 /// object. The loop is not deleted, as it will presumably be inserted into
640 /// another loop.
removeLoop(iterator I)641 inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); }
642
643 /// changeLoopFor - Change the top-level loop that contains BB to the
644 /// specified loop. This should be used by transformations that restructure
645 /// the loop hierarchy tree.
changeLoopFor(BasicBlock * BB,Loop * L)646 inline void changeLoopFor(BasicBlock *BB, Loop *L) {
647 LI.changeLoopFor(BB, L);
648 }
649
650 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
651 /// list with the indicated loop.
changeTopLevelLoop(Loop * OldLoop,Loop * NewLoop)652 inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
653 LI.changeTopLevelLoop(OldLoop, NewLoop);
654 }
655
656 /// addTopLevelLoop - This adds the specified loop to the collection of
657 /// top-level loops.
addTopLevelLoop(Loop * New)658 inline void addTopLevelLoop(Loop *New) {
659 LI.addTopLevelLoop(New);
660 }
661
662 /// removeBlock - This method completely removes BB from all data structures,
663 /// including all of the Loop objects it is nested in and our mapping from
664 /// BasicBlocks to loops.
removeBlock(BasicBlock * BB)665 void removeBlock(BasicBlock *BB) {
666 LI.removeBlock(BB);
667 }
668
669 /// updateUnloop - Update LoopInfo after removing the last backedge from a
670 /// loop--now the "unloop". This updates the loop forest and parent loops for
671 /// each block so that Unloop is no longer referenced, but the caller must
672 /// actually delete the Unloop object.
673 void updateUnloop(Loop *Unloop);
674
675 /// replacementPreservesLCSSAForm - Returns true if replacing From with To
676 /// everywhere is guaranteed to preserve LCSSA form.
replacementPreservesLCSSAForm(Instruction * From,Value * To)677 bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
678 // Preserving LCSSA form is only problematic if the replacing value is an
679 // instruction.
680 Instruction *I = dyn_cast<Instruction>(To);
681 if (!I) return true;
682 // If both instructions are defined in the same basic block then replacement
683 // cannot break LCSSA form.
684 if (I->getParent() == From->getParent())
685 return true;
686 // If the instruction is not defined in a loop then it can safely replace
687 // anything.
688 Loop *ToLoop = getLoopFor(I->getParent());
689 if (!ToLoop) return true;
690 // If the replacing instruction is defined in the same loop as the original
691 // instruction, or in a loop that contains it as an inner loop, then using
692 // it as a replacement will not break LCSSA form.
693 return ToLoop->contains(getLoopFor(From->getParent()));
694 }
695 };
696
697
698 // Allow clients to walk the list of nested loops...
699 template <> struct GraphTraits<const Loop*> {
700 typedef const Loop NodeType;
701 typedef LoopInfo::iterator ChildIteratorType;
702
703 static NodeType *getEntryNode(const Loop *L) { return L; }
704 static inline ChildIteratorType child_begin(NodeType *N) {
705 return N->begin();
706 }
707 static inline ChildIteratorType child_end(NodeType *N) {
708 return N->end();
709 }
710 };
711
712 template <> struct GraphTraits<Loop*> {
713 typedef Loop NodeType;
714 typedef LoopInfo::iterator ChildIteratorType;
715
716 static NodeType *getEntryNode(Loop *L) { return L; }
717 static inline ChildIteratorType child_begin(NodeType *N) {
718 return N->begin();
719 }
720 static inline ChildIteratorType child_end(NodeType *N) {
721 return N->end();
722 }
723 };
724
725 } // End llvm namespace
726
727 #endif
728