Removed some of the iostream #includes. Moved towards converting to using
[oota-llvm.git] / lib / Analysis / LoopInfo.cpp
1 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
2 //
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 //===----------------------------------------------------------------------===//
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.  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
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/Support/CFG.h"
23 #include "llvm/Support/Streams.h"
24 #include "llvm/ADT/DepthFirstIterator.h"
25 #include <algorithm>
26 #include <ostream>
27 using namespace llvm;
28
29 static RegisterPass<LoopInfo>
30 X("loops", "Natural Loop Construction", true);
31
32 //===----------------------------------------------------------------------===//
33 // Loop implementation
34 //
35 bool Loop::contains(const BasicBlock *BB) const {
36   return std::find(Blocks.begin(), Blocks.end(), BB) != Blocks.end();
37 }
38
39 bool Loop::isLoopExit(const BasicBlock *BB) const {
40   for (succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB);
41        SI != SE; ++SI) {
42     if (!contains(*SI))
43       return true;
44   }
45   return false;
46 }
47
48 /// getNumBackEdges - Calculate the number of back edges to the loop header.
49 ///
50 unsigned Loop::getNumBackEdges() const {
51   unsigned NumBackEdges = 0;
52   BasicBlock *H = getHeader();
53
54   for (pred_iterator I = pred_begin(H), E = pred_end(H); I != E; ++I)
55     if (contains(*I))
56       ++NumBackEdges;
57
58   return NumBackEdges;
59 }
60
61 /// isLoopInvariant - Return true if the specified value is loop invariant
62 ///
63 bool Loop::isLoopInvariant(Value *V) const {
64   if (Instruction *I = dyn_cast<Instruction>(V))
65     return !contains(I->getParent());
66   return true;  // All non-instructions are loop invariant
67 }
68
69 void Loop::print(std::ostream &OS, unsigned Depth) const {
70   OS << std::string(Depth*2, ' ') << "Loop Containing: ";
71
72   for (unsigned i = 0; i < getBlocks().size(); ++i) {
73     if (i) OS << ",";
74     WriteAsOperand(OS, getBlocks()[i], false);
75   }
76   OS << "\n";
77
78   for (iterator I = begin(), E = end(); I != E; ++I)
79     (*I)->print(OS, Depth+2);
80 }
81
82 void Loop::dump() const {
83   print(llvm_cerr);
84 }
85
86
87 //===----------------------------------------------------------------------===//
88 // LoopInfo implementation
89 //
90 bool LoopInfo::runOnFunction(Function &) {
91   releaseMemory();
92   Calculate(getAnalysis<ETForest>());    // Update
93   return false;
94 }
95
96 void LoopInfo::releaseMemory() {
97   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
105
106 void LoopInfo::Calculate(ETForest &EF) {
107   BasicBlock *RootNode = EF.getRoot();
108
109   for (df_iterator<BasicBlock*> NI = df_begin(RootNode),
110          NE = df_end(RootNode); NI != NE; ++NI)
111     if (Loop *L = ConsiderForLoop(*NI, EF))
112       TopLevelLoops.push_back(L);
113 }
114
115 void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
116   AU.setPreservesAll();
117   AU.addRequired<ETForest>();
118 }
119
120 void LoopInfo::print(std::ostream &OS, const Module* ) const {
121   for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
122     TopLevelLoops[i]->print(OS);
123 #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 = "
127        << I->second->getLoopDepth() << "\n";
128 #endif
129 }
130
131 static 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
137 Loop *LoopInfo::ConsiderForLoop(BasicBlock *BB, ETForest &EF) {
138   if (BBMap.find(BB) != BBMap.end()) return 0;   // Haven't processed this node?
139
140   std::vector<BasicBlock *> TodoStack;
141
142   // Scan the predecessors of BB, checking to see if BB dominates any of
143   // them.  This identifies backedges which target this node...
144   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
145     if (EF.dominates(BB, *I))   // If BB dominates it's predecessor...
146       TodoStack.push_back(*I);
147
148   if (TodoStack.empty()) return 0;  // No backedges to this block...
149
150   // Create a new loop to represent this basic block...
151   Loop *L = new Loop(BB);
152   BBMap[BB] = L;
153
154   BasicBlock *EntryBlock = &BB->getParent()->getEntryBlock();
155
156   while (!TodoStack.empty()) {  // Process all the nodes in the loop
157     BasicBlock *X = TodoStack.back();
158     TodoStack.pop_back();
159
160     if (!L->contains(X) &&         // As of yet unprocessed??
161         EF.dominates(EntryBlock, X)) {   // X is reachable from entry block?
162       // 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)))
168         if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)) {
169           // 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...
183       L->Blocks.push_back(X);
184
185       // Add all of the predecessors of X to the end of the work stack...
186       TodoStack.insert(TodoStack.end(), pred_begin(X), pred_end(X));
187     }
188   }
189
190   // 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, EF)) {
194       L->SubLoops.push_back(NewLoop);
195       NewLoop->ParentLoop = L;
196     }
197
198   // 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   }
207
208   // 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) {
232             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
237             // 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.
240             MoveSiblingLoopInto(SubLoop, Child);
241             --i;  // We just shrunk the SubLoops list.
242           }
243         }
244       }
245     }
246   }
247
248   return L;
249 }
250
251 /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside of
252 /// the NewParent Loop, instead of being a sibling of it.
253 void 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.
271 void 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
287 /// 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.
290 void LoopInfo::changeLoopFor(BasicBlock *BB, Loop *L) {
291   Loop *&OldLoop = BBMap[BB];
292   assert(OldLoop && "Block not in a loop yet!");
293   OldLoop = L;
294 }
295
296 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
297 /// list with the indicated loop.
298 void 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 }
306
307 /// 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.
310 Loop *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
318 /// 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.
321 void 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 }
330
331
332 //===----------------------------------------------------------------------===//
333 // APIs for simple analysis of the loop.
334 //
335
336 /// getExitingBlocks - Return all blocks inside the loop that have successors
337 /// outside of the loop.  These are the blocks _inside of the current loop_
338 /// which branch out.  The returned list is always unique.
339 ///
340 void Loop::getExitingBlocks(std::vector<BasicBlock*> &ExitingBlocks) const {
341   // Sort the blocks vector so that we can use binary search to do quick
342   // lookups.
343   std::vector<BasicBlock*> LoopBBs(block_begin(), block_end());
344   std::sort(LoopBBs.begin(), LoopBBs.end());
345   
346   for (std::vector<BasicBlock*>::const_iterator BI = Blocks.begin(),
347        BE = Blocks.end(); BI != BE; ++BI)
348     for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I)
349       if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
350         // Not in current loop? It must be an exit block.
351         ExitingBlocks.push_back(*BI);
352         break;
353       }
354 }
355
356 /// getExitBlocks - Return all of the successor blocks of this loop.  These
357 /// are the blocks _outside of the current loop_ which are branched to.
358 ///
359 void Loop::getExitBlocks(std::vector<BasicBlock*> &ExitBlocks) const {
360   // Sort the blocks vector so that we can use binary search to do quick
361   // lookups.
362   std::vector<BasicBlock*> LoopBBs(block_begin(), block_end());
363   std::sort(LoopBBs.begin(), LoopBBs.end());
364   
365   for (std::vector<BasicBlock*>::const_iterator BI = Blocks.begin(),
366        BE = Blocks.end(); BI != BE; ++BI)
367     for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I)
368       if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
369         // Not in current loop? It must be an exit block.
370         ExitBlocks.push_back(*I);
371 }
372
373 /// getUniqueExitBlocks - Return all unique successor blocks of this loop. These
374 /// are the blocks _outside of the current loop_ which are branched to. This
375 /// assumes that loop is in canonical form.
376 //
377 void Loop::getUniqueExitBlocks(std::vector<BasicBlock*> &ExitBlocks) const {
378   // Sort the blocks vector so that we can use binary search to do quick
379   // lookups.
380   std::vector<BasicBlock*> LoopBBs(block_begin(), block_end());
381   std::sort(LoopBBs.begin(), LoopBBs.end());
382
383   std::vector<BasicBlock*> switchExitBlocks;  
384   
385   for (std::vector<BasicBlock*>::const_iterator BI = Blocks.begin(),
386     BE = Blocks.end(); BI != BE; ++BI) {
387
388     BasicBlock *current = *BI;
389     switchExitBlocks.clear();
390
391     for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
392       if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
393     // If block is inside the loop then it is not a exit block.
394         continue;
395
396       pred_iterator PI = pred_begin(*I);
397       BasicBlock *firstPred = *PI;
398
399       // If current basic block is this exit block's first predecessor
400       // then only insert exit block in to the output ExitBlocks vector.
401       // This ensures that same exit block is not inserted twice into
402       // ExitBlocks vector.
403       if (current != firstPred) 
404         continue;
405
406       // If a terminator has more then two successors, for example SwitchInst,
407       // then it is possible that there are multiple edges from current block 
408       // to one exit block. 
409       if (current->getTerminator()->getNumSuccessors() <= 2) {
410         ExitBlocks.push_back(*I);
411         continue;
412       }
413       
414       // In case of multiple edges from current block to exit block, collect
415       // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
416       // duplicate edges.
417       if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I) 
418           == switchExitBlocks.end()) {
419         switchExitBlocks.push_back(*I);
420         ExitBlocks.push_back(*I);
421       }
422     }
423   }
424 }
425
426
427 /// getLoopPreheader - If there is a preheader for this loop, return it.  A
428 /// loop has a preheader if there is only one edge to the header of the loop
429 /// from outside of the loop.  If this is the case, the block branching to the
430 /// header of the loop is the preheader node.
431 ///
432 /// This method returns null if there is no preheader for the loop.
433 ///
434 BasicBlock *Loop::getLoopPreheader() const {
435   // Keep track of nodes outside the loop branching to the header...
436   BasicBlock *Out = 0;
437
438   // Loop over the predecessors of the header node...
439   BasicBlock *Header = getHeader();
440   for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
441        PI != PE; ++PI)
442     if (!contains(*PI)) {     // If the block is not in the loop...
443       if (Out && Out != *PI)
444         return 0;             // Multiple predecessors outside the loop
445       Out = *PI;
446     }
447
448   // Make sure there is only one exit out of the preheader.
449   assert(Out && "Header of loop has no predecessors from outside loop?");
450   succ_iterator SI = succ_begin(Out);
451   ++SI;
452   if (SI != succ_end(Out))
453     return 0;  // Multiple exits from the block, must not be a preheader.
454
455   // If there is exactly one preheader, return it.  If there was zero, then Out
456   // is still null.
457   return Out;
458 }
459
460 /// getLoopLatch - If there is a latch block for this loop, return it.  A
461 /// latch block is the canonical backedge for a loop.  A loop header in normal
462 /// form has two edges into it: one from a preheader and one from a latch
463 /// block.
464 BasicBlock *Loop::getLoopLatch() const {
465   BasicBlock *Header = getHeader();
466   pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
467   if (PI == PE) return 0;  // no preds?
468   
469   BasicBlock *Latch = 0;
470   if (contains(*PI))
471     Latch = *PI;
472   ++PI;
473   if (PI == PE) return 0;  // only one pred?
474   
475   if (contains(*PI)) {
476     if (Latch) return 0;  // multiple backedges
477     Latch = *PI;
478   }
479   ++PI;
480   if (PI != PE) return 0;  // more than two preds
481   
482   return Latch;  
483 }
484
485 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
486 /// induction variable: an integer recurrence that starts at 0 and increments by
487 /// one each time through the loop.  If so, return the phi node that corresponds
488 /// to it.
489 ///
490 PHINode *Loop::getCanonicalInductionVariable() const {
491   BasicBlock *H = getHeader();
492
493   BasicBlock *Incoming = 0, *Backedge = 0;
494   pred_iterator PI = pred_begin(H);
495   assert(PI != pred_end(H) && "Loop must have at least one backedge!");
496   Backedge = *PI++;
497   if (PI == pred_end(H)) return 0;  // dead loop
498   Incoming = *PI++;
499   if (PI != pred_end(H)) return 0;  // multiple backedges?
500
501   if (contains(Incoming)) {
502     if (contains(Backedge))
503       return 0;
504     std::swap(Incoming, Backedge);
505   } else if (!contains(Backedge))
506     return 0;
507
508   // Loop over all of the PHI nodes, looking for a canonical indvar.
509   for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
510     PHINode *PN = cast<PHINode>(I);
511     if (Instruction *Inc =
512         dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
513       if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
514         if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
515           if (CI->equalsInt(1))
516             return PN;
517   }
518   return 0;
519 }
520
521 /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
522 /// the canonical induction variable value for the "next" iteration of the loop.
523 /// This always succeeds if getCanonicalInductionVariable succeeds.
524 ///
525 Instruction *Loop::getCanonicalInductionVariableIncrement() const {
526   if (PHINode *PN = getCanonicalInductionVariable()) {
527     bool P1InLoop = contains(PN->getIncomingBlock(1));
528     return cast<Instruction>(PN->getIncomingValue(P1InLoop));
529   }
530   return 0;
531 }
532
533 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
534 /// times the loop will be executed.  Note that this means that the backedge of
535 /// the loop executes N-1 times.  If the trip-count cannot be determined, this
536 /// returns null.
537 ///
538 Value *Loop::getTripCount() const {
539   // Canonical loops will end with a 'setne I, V', where I is the incremented
540   // canonical induction variable and V is the trip count of the loop.
541   Instruction *Inc = getCanonicalInductionVariableIncrement();
542   if (Inc == 0) return 0;
543   PHINode *IV = cast<PHINode>(Inc->getOperand(0));
544
545   BasicBlock *BackedgeBlock =
546     IV->getIncomingBlock(contains(IV->getIncomingBlock(1)));
547
548   if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator()))
549     if (BI->isConditional())
550       if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition()))
551         if (SCI->getOperand(0) == Inc)
552           if (BI->getSuccessor(0) == getHeader()) {
553             if (SCI->getOpcode() == Instruction::SetNE)
554               return SCI->getOperand(1);
555           } else if (SCI->getOpcode() == Instruction::SetEQ) {
556             return SCI->getOperand(1);
557           }
558
559   return 0;
560 }
561
562 /// isLCSSAForm - Return true if the Loop is in LCSSA form
563 bool Loop::isLCSSAForm() const { 
564   // Sort the blocks vector so that we can use binary search to do quick
565   // lookups.
566   std::vector<BasicBlock*> LoopBBs(block_begin(), block_end());
567   std::sort(LoopBBs.begin(), LoopBBs.end());
568   
569   for (unsigned i = 0, e = LoopBBs.size(); i != e; ++i) {
570     BasicBlock *BB = LoopBBs[i];
571     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
572       for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
573            ++UI) {
574         BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
575         if (PHINode* p = dyn_cast<PHINode>(*UI)) {
576           unsigned OperandNo = UI.getOperandNo();
577           UserBB = p->getIncomingBlock(OperandNo/2);
578         }
579         
580         // Check the current block, as a fast-path.  Most values are used in the
581         // same block they are defined in.
582         if (UserBB != BB &&
583             // Otherwise, binary search LoopBBs for this block.
584             !std::binary_search(LoopBBs.begin(), LoopBBs.end(), UserBB))
585           return false;
586       }
587   }
588   
589   return true;
590 }
591
592 //===-------------------------------------------------------------------===//
593 // APIs for updating loop information after changing the CFG
594 //
595
596 /// addBasicBlockToLoop - This function is used by other analyses to update loop
597 /// information.  NewBB is set to be a new member of the current loop.  Because
598 /// of this, it is added as a member of all parent loops, and is added to the
599 /// specified LoopInfo object as being in the current basic block.  It is not
600 /// valid to replace the loop header with this method.
601 ///
602 void Loop::addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI) {
603   assert((Blocks.empty() || LI[getHeader()] == this) &&
604          "Incorrect LI specified for this loop!");
605   assert(NewBB && "Cannot add a null basic block to the loop!");
606   assert(LI[NewBB] == 0 && "BasicBlock already in the loop!");
607
608   // Add the loop mapping to the LoopInfo object...
609   LI.BBMap[NewBB] = this;
610
611   // Add the basic block to this loop and all parent loops...
612   Loop *L = this;
613   while (L) {
614     L->Blocks.push_back(NewBB);
615     L = L->getParentLoop();
616   }
617 }
618
619 /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
620 /// the OldChild entry in our children list with NewChild, and updates the
621 /// parent pointers of the two loops as appropriate.
622 void Loop::replaceChildLoopWith(Loop *OldChild, Loop *NewChild) {
623   assert(OldChild->ParentLoop == this && "This loop is already broken!");
624   assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
625   std::vector<Loop*>::iterator I = std::find(SubLoops.begin(), SubLoops.end(),
626                                              OldChild);
627   assert(I != SubLoops.end() && "OldChild not in loop!");
628   *I = NewChild;
629   OldChild->ParentLoop = 0;
630   NewChild->ParentLoop = this;
631 }
632
633 /// addChildLoop - Add the specified loop to be a child of this loop.
634 ///
635 void Loop::addChildLoop(Loop *NewChild) {
636   assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
637   NewChild->ParentLoop = this;
638   SubLoops.push_back(NewChild);
639 }
640
641 template<typename T>
642 static void RemoveFromVector(std::vector<T*> &V, T *N) {
643   typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
644   assert(I != V.end() && "N is not in this list!");
645   V.erase(I);
646 }
647
648 /// removeChildLoop - This removes the specified child from being a subloop of
649 /// this loop.  The loop is not deleted, as it will presumably be inserted
650 /// into another loop.
651 Loop *Loop::removeChildLoop(iterator I) {
652   assert(I != SubLoops.end() && "Cannot remove end iterator!");
653   Loop *Child = *I;
654   assert(Child->ParentLoop == this && "Child is not a child of this loop!");
655   SubLoops.erase(SubLoops.begin()+(I-begin()));
656   Child->ParentLoop = 0;
657   return Child;
658 }
659
660
661 /// removeBlockFromLoop - This removes the specified basic block from the
662 /// current loop, updating the Blocks and ExitBlocks lists as appropriate.  This
663 /// does not update the mapping in the LoopInfo class.
664 void Loop::removeBlockFromLoop(BasicBlock *BB) {
665   RemoveFromVector(Blocks, BB);
666 }
667
668 // Ensure this file gets linked when LoopInfo.h is used.
669 DEFINING_FILE_FOR(LoopInfo)