third time is the charm.
[oota-llvm.git] / lib / Transforms / Utils / BasicBlockUtils.cpp
1 //===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
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 family of functions perform manipulations on basic blocks, and
11 // instructions contained within basic blocks.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
16 #include "llvm/Function.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Constant.h"
19 #include "llvm/Type.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Target/TargetData.h"
24 #include <algorithm>
25 using namespace llvm;
26
27 /// DeleteDeadBlock - Delete the specified block, which must have no
28 /// predecessors.
29 void llvm::DeleteDeadBlock(BasicBlock *BB) {
30   assert((pred_begin(BB) == pred_end(BB) ||
31          // Can delete self loop.
32          BB->getSinglePredecessor() == BB) && "Block is not dead!");
33   TerminatorInst *BBTerm = BB->getTerminator();
34   
35   // Loop through all of our successors and make sure they know that one
36   // of their predecessors is going away.
37   for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
38     BBTerm->getSuccessor(i)->removePredecessor(BB);
39   
40   // Zap all the instructions in the block.
41   while (!BB->empty()) {
42     Instruction &I = BB->back();
43     // If this instruction is used, replace uses with an arbitrary value.
44     // Because control flow can't get here, we don't care what we replace the
45     // value with.  Note that since this block is unreachable, and all values
46     // contained within it must dominate their uses, that all uses will
47     // eventually be removed (they are themselves dead).
48     if (!I.use_empty())
49       I.replaceAllUsesWith(UndefValue::get(I.getType()));
50     BB->getInstList().pop_back();
51   }
52   
53   // Zap the block!
54   BB->eraseFromParent();
55 }
56
57 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
58 /// if possible.  The return value indicates success or failure.
59 bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
60   pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
61   // Can't merge the entry block.
62   if (pred_begin(BB) == pred_end(BB)) return false;
63   
64   BasicBlock *PredBB = *PI++;
65   for (; PI != PE; ++PI)  // Search all predecessors, see if they are all same
66     if (*PI != PredBB) {
67       PredBB = 0;       // There are multiple different predecessors...
68       break;
69     }
70   
71   // Can't merge if there are multiple predecessors.
72   if (!PredBB) return false;
73   // Don't break self-loops.
74   if (PredBB == BB) return false;
75   // Don't break invokes.
76   if (isa<InvokeInst>(PredBB->getTerminator())) return false;
77   
78   succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
79   BasicBlock* OnlySucc = BB;
80   for (; SI != SE; ++SI)
81     if (*SI != OnlySucc) {
82       OnlySucc = 0;     // There are multiple distinct successors!
83       break;
84     }
85   
86   // Can't merge if there are multiple successors.
87   if (!OnlySucc) return false;
88
89   // Can't merge if there is PHI loop.
90   for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
91     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
92       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
93         if (PN->getIncomingValue(i) == PN)
94           return false;
95     } else
96       break;
97   }
98
99   // Begin by getting rid of unneeded PHIs.
100   while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
101     PN->replaceAllUsesWith(PN->getIncomingValue(0));
102     BB->getInstList().pop_front();  // Delete the phi node...
103   }
104   
105   // Delete the unconditional branch from the predecessor...
106   PredBB->getInstList().pop_back();
107   
108   // Move all definitions in the successor to the predecessor...
109   PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
110   
111   // Make all PHI nodes that referred to BB now refer to Pred as their
112   // source...
113   BB->replaceAllUsesWith(PredBB);
114   
115   // Inherit predecessors name if it exists.
116   if (!PredBB->hasName())
117     PredBB->takeName(BB);
118   
119   // Finally, erase the old block and update dominator info.
120   if (P) {
121     if (DominatorTree* DT = P->getAnalysisToUpdate<DominatorTree>()) {
122       DomTreeNode* DTN = DT->getNode(BB);
123       DomTreeNode* PredDTN = DT->getNode(PredBB);
124   
125       if (DTN) {
126         SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
127         for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
128              DE = Children.end(); DI != DE; ++DI)
129           DT->changeImmediateDominator(*DI, PredDTN);
130
131         DT->eraseNode(BB);
132       }
133     }
134   }
135   
136   BB->eraseFromParent();
137   
138   
139   return true;
140 }
141
142 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
143 /// with a value, then remove and delete the original instruction.
144 ///
145 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
146                                 BasicBlock::iterator &BI, Value *V) {
147   Instruction &I = *BI;
148   // Replaces all of the uses of the instruction with uses of the value
149   I.replaceAllUsesWith(V);
150
151   // Make sure to propagate a name if there is one already.
152   if (I.hasName() && !V->hasName())
153     V->takeName(&I);
154
155   // Delete the unnecessary instruction now...
156   BI = BIL.erase(BI);
157 }
158
159
160 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
161 /// instruction specified by I.  The original instruction is deleted and BI is
162 /// updated to point to the new instruction.
163 ///
164 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
165                                BasicBlock::iterator &BI, Instruction *I) {
166   assert(I->getParent() == 0 &&
167          "ReplaceInstWithInst: Instruction already inserted into basic block!");
168
169   // Insert the new instruction into the basic block...
170   BasicBlock::iterator New = BIL.insert(BI, I);
171
172   // Replace all uses of the old instruction, and delete it.
173   ReplaceInstWithValue(BIL, BI, I);
174
175   // Move BI back to point to the newly inserted instruction
176   BI = New;
177 }
178
179 /// ReplaceInstWithInst - Replace the instruction specified by From with the
180 /// instruction specified by To.
181 ///
182 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
183   BasicBlock::iterator BI(From);
184   ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
185 }
186
187 /// RemoveSuccessor - Change the specified terminator instruction such that its
188 /// successor SuccNum no longer exists.  Because this reduces the outgoing
189 /// degree of the current basic block, the actual terminator instruction itself
190 /// may have to be changed.  In the case where the last successor of the block 
191 /// is deleted, a return instruction is inserted in its place which can cause a
192 /// surprising change in program behavior if it is not expected.
193 ///
194 void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
195   assert(SuccNum < TI->getNumSuccessors() &&
196          "Trying to remove a nonexistant successor!");
197
198   // If our old successor block contains any PHI nodes, remove the entry in the
199   // PHI nodes that comes from this branch...
200   //
201   BasicBlock *BB = TI->getParent();
202   TI->getSuccessor(SuccNum)->removePredecessor(BB);
203
204   TerminatorInst *NewTI = 0;
205   switch (TI->getOpcode()) {
206   case Instruction::Br:
207     // If this is a conditional branch... convert to unconditional branch.
208     if (TI->getNumSuccessors() == 2) {
209       cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
210     } else {                    // Otherwise convert to a return instruction...
211       Value *RetVal = 0;
212
213       // Create a value to return... if the function doesn't return null...
214       if (BB->getParent()->getReturnType() != Type::VoidTy)
215         RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
216
217       // Create the return...
218       NewTI = ReturnInst::Create(RetVal);
219     }
220     break;
221
222   case Instruction::Invoke:    // Should convert to call
223   case Instruction::Switch:    // Should remove entry
224   default:
225   case Instruction::Ret:       // Cannot happen, has no successors!
226     assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
227     abort();
228   }
229
230   if (NewTI)   // If it's a different instruction, replace.
231     ReplaceInstWithInst(TI, NewTI);
232 }
233
234 /// SplitEdge -  Split the edge connecting specified block. Pass P must 
235 /// not be NULL. 
236 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
237   TerminatorInst *LatchTerm = BB->getTerminator();
238   unsigned SuccNum = 0;
239 #ifndef NDEBUG
240   unsigned e = LatchTerm->getNumSuccessors();
241 #endif
242   for (unsigned i = 0; ; ++i) {
243     assert(i != e && "Didn't find edge?");
244     if (LatchTerm->getSuccessor(i) == Succ) {
245       SuccNum = i;
246       break;
247     }
248   }
249   
250   // If this is a critical edge, let SplitCriticalEdge do it.
251   if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
252     return LatchTerm->getSuccessor(SuccNum);
253
254   // If the edge isn't critical, then BB has a single successor or Succ has a
255   // single pred.  Split the block.
256   BasicBlock::iterator SplitPoint;
257   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
258     // If the successor only has a single pred, split the top of the successor
259     // block.
260     assert(SP == BB && "CFG broken");
261     SP = NULL;
262     return SplitBlock(Succ, Succ->begin(), P);
263   } else {
264     // Otherwise, if BB has a single successor, split it at the bottom of the
265     // block.
266     assert(BB->getTerminator()->getNumSuccessors() == 1 &&
267            "Should have a single succ!"); 
268     return SplitBlock(BB, BB->getTerminator(), P);
269   }
270 }
271
272 /// SplitBlock - Split the specified block at the specified instruction - every
273 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
274 /// to a new block.  The two blocks are joined by an unconditional branch and
275 /// the loop info is updated.
276 ///
277 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
278   BasicBlock::iterator SplitIt = SplitPt;
279   while (isa<PHINode>(SplitIt))
280     ++SplitIt;
281   BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
282
283   // The new block lives in whichever loop the old one did.
284   if (LoopInfo* LI = P->getAnalysisToUpdate<LoopInfo>())
285     if (Loop *L = LI->getLoopFor(Old))
286       L->addBasicBlockToLoop(New, LI->getBase());
287
288   if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>()) 
289     {
290       // Old dominates New. New node domiantes all other nodes dominated by Old.
291       DomTreeNode *OldNode = DT->getNode(Old);
292       std::vector<DomTreeNode *> Children;
293       for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
294            I != E; ++I) 
295         Children.push_back(*I);
296
297       DomTreeNode *NewNode =   DT->addNewBlock(New,Old);
298
299       for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
300              E = Children.end(); I != E; ++I) 
301         DT->changeImmediateDominator(*I, NewNode);
302     }
303
304   if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>())
305     DF->splitBlock(Old);
306     
307   return New;
308 }
309
310
311 /// SplitBlockPredecessors - This method transforms BB by introducing a new
312 /// basic block into the function, and moving some of the predecessors of BB to
313 /// be predecessors of the new block.  The new predecessors are indicated by the
314 /// Preds array, which has NumPreds elements in it.  The new block is given a
315 /// suffix of 'Suffix'.
316 ///
317 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
318 /// DominanceFrontier, but no other analyses.
319 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB, 
320                                          BasicBlock *const *Preds,
321                                          unsigned NumPreds, const char *Suffix,
322                                          Pass *P) {
323   // Create new basic block, insert right before the original block.
324   BasicBlock *NewBB =
325     BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
326   
327   // The new block unconditionally branches to the old block.
328   BranchInst *BI = BranchInst::Create(BB, NewBB);
329   
330   // Move the edges from Preds to point to NewBB instead of BB.
331   for (unsigned i = 0; i != NumPreds; ++i)
332     Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
333   
334   // Update dominator tree and dominator frontier if available.
335   DominatorTree *DT = P ? P->getAnalysisToUpdate<DominatorTree>() : 0;
336   if (DT)
337     DT->splitBlock(NewBB);
338   if (DominanceFrontier *DF = P ? P->getAnalysisToUpdate<DominanceFrontier>():0)
339     DF->splitBlock(NewBB);
340   AliasAnalysis *AA = P ? P->getAnalysisToUpdate<AliasAnalysis>() : 0;
341   
342   
343   // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
344   // node becomes an incoming value for BB's phi node.  However, if the Preds
345   // list is empty, we need to insert dummy entries into the PHI nodes in BB to
346   // account for the newly created predecessor.
347   if (NumPreds == 0) {
348     // Insert dummy values as the incoming value.
349     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
350       cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
351     return NewBB;
352   }
353   
354   // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
355   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
356     PHINode *PN = cast<PHINode>(I++);
357     
358     // Check to see if all of the values coming in are the same.  If so, we
359     // don't need to create a new PHI node.
360     Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
361     for (unsigned i = 1; i != NumPreds; ++i)
362       if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
363         InVal = 0;
364         break;
365       }
366     
367     if (InVal) {
368       // If all incoming values for the new PHI would be the same, just don't
369       // make a new PHI.  Instead, just remove the incoming values from the old
370       // PHI.
371       for (unsigned i = 0; i != NumPreds; ++i)
372         PN->removeIncomingValue(Preds[i], false);
373     } else {
374       // If the values coming into the block are not the same, we need a PHI.
375       // Create the new PHI node, insert it into NewBB at the end of the block
376       PHINode *NewPHI =
377         PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
378       if (AA) AA->copyValue(PN, NewPHI);
379       
380       // Move all of the PHI values for 'Preds' to the new PHI.
381       for (unsigned i = 0; i != NumPreds; ++i) {
382         Value *V = PN->removeIncomingValue(Preds[i], false);
383         NewPHI->addIncoming(V, Preds[i]);
384       }
385       InVal = NewPHI;
386     }
387     
388     // Add an incoming value to the PHI node in the loop for the preheader
389     // edge.
390     PN->addIncoming(InVal, NewBB);
391     
392     // Check to see if we can eliminate this phi node.
393     if (Value *V = PN->hasConstantValue(DT != 0)) {
394       Instruction *I = dyn_cast<Instruction>(V);
395       if (!I || DT == 0 || DT->dominates(I, PN)) {
396         PN->replaceAllUsesWith(V);
397         if (AA) AA->deleteValue(PN);
398         PN->eraseFromParent();
399       }
400     }
401   }
402   
403   return NewBB;
404 }
405
406 /// AreEquivalentAddressValues - Test if A and B will obviously have the same
407 /// value. This includes recognizing that %t0 and %t1 will have the same
408 /// value in code like this:
409 ///   %t0 = getelementptr @a, 0, 3
410 ///   store i32 0, i32* %t0
411 ///   %t1 = getelementptr @a, 0, 3
412 ///   %t2 = load i32* %t1
413 ///
414 static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
415   // Test if the values are trivially equivalent.
416   if (A == B) return true;
417   
418   // Test if the values come form identical arithmetic instructions.
419   if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
420       isa<PHINode>(A) || isa<GetElementPtrInst>(A))
421     if (const Instruction *BI = dyn_cast<Instruction>(B))
422       if (cast<Instruction>(A)->isIdenticalTo(BI))
423         return true;
424   
425   // Otherwise they may not be equivalent.
426   return false;
427 }
428
429 /// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
430 /// instruction before ScanFrom) checking to see if we have the value at the
431 /// memory address *Ptr locally available within a small number of instructions.
432 /// If the value is available, return it.
433 ///
434 /// If not, return the iterator for the last validated instruction that the 
435 /// value would be live through.  If we scanned the entire block and didn't find
436 /// something that invalidates *Ptr or provides it, ScanFrom would be left at
437 /// begin() and this returns null.  ScanFrom could also be left 
438 ///
439 /// MaxInstsToScan specifies the maximum instructions to scan in the block.  If
440 /// it is set to 0, it will scan the whole block. You can also optionally
441 /// specify an alias analysis implementation, which makes this more precise.
442 Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
443                                       BasicBlock::iterator &ScanFrom,
444                                       unsigned MaxInstsToScan,
445                                       AliasAnalysis *AA) {
446   if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
447
448   // If we're using alias analysis to disambiguate get the size of *Ptr.
449   unsigned AccessSize = 0;
450   if (AA) {
451     const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
452     AccessSize = AA->getTargetData().getTypeStoreSizeInBits(AccessTy);
453   }
454   
455   while (ScanFrom != ScanBB->begin()) {
456     // Don't scan huge blocks.
457     if (MaxInstsToScan-- == 0) return 0;
458     
459     Instruction *Inst = --ScanFrom;
460     
461     // If this is a load of Ptr, the loaded value is available.
462     if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
463       if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
464         return LI;
465     
466     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
467       // If this is a store through Ptr, the value is available!
468       if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
469         return SI->getOperand(0);
470       
471       // If Ptr is an alloca and this is a store to a different alloca, ignore
472       // the store.  This is a trivial form of alias analysis that is important
473       // for reg2mem'd code.
474       if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
475           (isa<AllocaInst>(SI->getOperand(1)) ||
476            isa<GlobalVariable>(SI->getOperand(1))))
477         continue;
478       
479       // If we have alias analysis and it says the store won't modify the loaded
480       // value, ignore the store.
481       if (AA &&
482           (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
483         continue;
484       
485       // Otherwise the store that may or may not alias the pointer, bail out.
486       ++ScanFrom;
487       return 0;
488     }
489     
490     // If this is some other instruction that may clobber Ptr, bail out.
491     if (Inst->mayWriteToMemory()) {
492       // If alias analysis claims that it really won't modify the load,
493       // ignore it.
494       if (AA &&
495           (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
496         continue;
497       
498       // May modify the pointer, bail out.
499       ++ScanFrom;
500       return 0;
501     }
502   }
503   
504   // Got to the start of the block, we didn't find it, but are done for this
505   // block.
506   return 0;
507 }