1 //===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This family of functions perform manipulations on basic blocks, and
11 // instructions contained within basic blocks.
13 //===----------------------------------------------------------------------===//
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"
27 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
28 /// if possible. The return value indicates success or failure.
29 bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
30 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
31 // Can't merge the entry block.
32 if (pred_begin(BB) == pred_end(BB)) return false;
34 BasicBlock *PredBB = *PI++;
35 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
37 PredBB = 0; // There are multiple different predecessors...
41 // Can't merge if there are multiple predecessors.
42 if (!PredBB) return false;
43 // Don't break self-loops.
44 if (PredBB == BB) return false;
45 // Don't break invokes.
46 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
48 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
49 BasicBlock* OnlySucc = BB;
50 for (; SI != SE; ++SI)
51 if (*SI != OnlySucc) {
52 OnlySucc = 0; // There are multiple distinct successors!
56 // Can't merge if there are multiple successors.
57 if (!OnlySucc) return false;
59 // Can't merge if there is PHI loop.
60 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
61 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
62 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
63 if (PN->getIncomingValue(i) == PN)
69 // Begin by getting rid of unneeded PHIs.
70 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
71 PN->replaceAllUsesWith(PN->getIncomingValue(0));
72 BB->getInstList().pop_front(); // Delete the phi node...
75 // Delete the unconditional branch from the predecessor...
76 PredBB->getInstList().pop_back();
78 // Move all definitions in the successor to the predecessor...
79 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
81 // Make all PHI nodes that referred to BB now refer to Pred as their
83 BB->replaceAllUsesWith(PredBB);
85 // Inherit predecessors name if it exists.
86 if (!PredBB->hasName())
89 // Finally, erase the old block and update dominator info.
91 if (DominatorTree* DT = P->getAnalysisToUpdate<DominatorTree>()) {
92 DomTreeNode* DTN = DT->getNode(BB);
93 DomTreeNode* PredDTN = DT->getNode(PredBB);
96 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
97 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
98 DE = Children.end(); DI != DE; ++DI)
99 DT->changeImmediateDominator(*DI, PredDTN);
106 BB->eraseFromParent();
112 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
113 /// with a value, then remove and delete the original instruction.
115 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
116 BasicBlock::iterator &BI, Value *V) {
117 Instruction &I = *BI;
118 // Replaces all of the uses of the instruction with uses of the value
119 I.replaceAllUsesWith(V);
121 // Make sure to propagate a name if there is one already.
122 if (I.hasName() && !V->hasName())
125 // Delete the unnecessary instruction now...
130 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
131 /// instruction specified by I. The original instruction is deleted and BI is
132 /// updated to point to the new instruction.
134 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
135 BasicBlock::iterator &BI, Instruction *I) {
136 assert(I->getParent() == 0 &&
137 "ReplaceInstWithInst: Instruction already inserted into basic block!");
139 // Insert the new instruction into the basic block...
140 BasicBlock::iterator New = BIL.insert(BI, I);
142 // Replace all uses of the old instruction, and delete it.
143 ReplaceInstWithValue(BIL, BI, I);
145 // Move BI back to point to the newly inserted instruction
149 /// ReplaceInstWithInst - Replace the instruction specified by From with the
150 /// instruction specified by To.
152 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
153 BasicBlock::iterator BI(From);
154 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
157 /// RemoveSuccessor - Change the specified terminator instruction such that its
158 /// successor SuccNum no longer exists. Because this reduces the outgoing
159 /// degree of the current basic block, the actual terminator instruction itself
160 /// may have to be changed. In the case where the last successor of the block
161 /// is deleted, a return instruction is inserted in its place which can cause a
162 /// surprising change in program behavior if it is not expected.
164 void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
165 assert(SuccNum < TI->getNumSuccessors() &&
166 "Trying to remove a nonexistant successor!");
168 // If our old successor block contains any PHI nodes, remove the entry in the
169 // PHI nodes that comes from this branch...
171 BasicBlock *BB = TI->getParent();
172 TI->getSuccessor(SuccNum)->removePredecessor(BB);
174 TerminatorInst *NewTI = 0;
175 switch (TI->getOpcode()) {
176 case Instruction::Br:
177 // If this is a conditional branch... convert to unconditional branch.
178 if (TI->getNumSuccessors() == 2) {
179 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
180 } else { // Otherwise convert to a return instruction...
183 // Create a value to return... if the function doesn't return null...
184 if (BB->getParent()->getReturnType() != Type::VoidTy)
185 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
187 // Create the return...
188 NewTI = ReturnInst::Create(RetVal);
192 case Instruction::Invoke: // Should convert to call
193 case Instruction::Switch: // Should remove entry
195 case Instruction::Ret: // Cannot happen, has no successors!
196 assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
200 if (NewTI) // If it's a different instruction, replace.
201 ReplaceInstWithInst(TI, NewTI);
204 /// SplitEdge - Split the edge connecting specified block. Pass P must
206 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
207 TerminatorInst *LatchTerm = BB->getTerminator();
208 unsigned SuccNum = 0;
210 unsigned e = LatchTerm->getNumSuccessors();
212 for (unsigned i = 0; ; ++i) {
213 assert(i != e && "Didn't find edge?");
214 if (LatchTerm->getSuccessor(i) == Succ) {
220 // If this is a critical edge, let SplitCriticalEdge do it.
221 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
222 return LatchTerm->getSuccessor(SuccNum);
224 // If the edge isn't critical, then BB has a single successor or Succ has a
225 // single pred. Split the block.
226 BasicBlock::iterator SplitPoint;
227 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
228 // If the successor only has a single pred, split the top of the successor
230 assert(SP == BB && "CFG broken");
232 return SplitBlock(Succ, Succ->begin(), P);
234 // Otherwise, if BB has a single successor, split it at the bottom of the
236 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
237 "Should have a single succ!");
238 return SplitBlock(BB, BB->getTerminator(), P);
242 /// SplitBlock - Split the specified block at the specified instruction - every
243 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
244 /// to a new block. The two blocks are joined by an unconditional branch and
245 /// the loop info is updated.
247 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
248 BasicBlock::iterator SplitIt = SplitPt;
249 while (isa<PHINode>(SplitIt))
251 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
253 // The new block lives in whichever loop the old one did.
254 if (LoopInfo* LI = P->getAnalysisToUpdate<LoopInfo>())
255 if (Loop *L = LI->getLoopFor(Old))
256 L->addBasicBlockToLoop(New, LI->getBase());
258 if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>())
260 // Old dominates New. New node domiantes all other nodes dominated by Old.
261 DomTreeNode *OldNode = DT->getNode(Old);
262 std::vector<DomTreeNode *> Children;
263 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
265 Children.push_back(*I);
267 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
269 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
270 E = Children.end(); I != E; ++I)
271 DT->changeImmediateDominator(*I, NewNode);
274 if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>())
281 /// SplitBlockPredecessors - This method transforms BB by introducing a new
282 /// basic block into the function, and moving some of the predecessors of BB to
283 /// be predecessors of the new block. The new predecessors are indicated by the
284 /// Preds array, which has NumPreds elements in it. The new block is given a
285 /// suffix of 'Suffix'.
287 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
288 /// DominanceFrontier, but no other analyses.
289 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
290 BasicBlock *const *Preds,
291 unsigned NumPreds, const char *Suffix,
293 // Create new basic block, insert right before the original block.
295 BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
297 // The new block unconditionally branches to the old block.
298 BranchInst *BI = BranchInst::Create(BB, NewBB);
300 // Move the edges from Preds to point to NewBB instead of BB.
301 for (unsigned i = 0; i != NumPreds; ++i)
302 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
304 // Update dominator tree and dominator frontier if available.
305 DominatorTree *DT = P ? P->getAnalysisToUpdate<DominatorTree>() : 0;
307 DT->splitBlock(NewBB);
308 if (DominanceFrontier *DF = P ? P->getAnalysisToUpdate<DominanceFrontier>():0)
309 DF->splitBlock(NewBB);
310 AliasAnalysis *AA = P ? P->getAnalysisToUpdate<AliasAnalysis>() : 0;
313 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
314 // node becomes an incoming value for BB's phi node. However, if the Preds
315 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
316 // account for the newly created predecessor.
318 // Insert dummy values as the incoming value.
319 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
320 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
324 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
325 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
326 PHINode *PN = cast<PHINode>(I++);
328 // Check to see if all of the values coming in are the same. If so, we
329 // don't need to create a new PHI node.
330 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
331 for (unsigned i = 1; i != NumPreds; ++i)
332 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
338 // If all incoming values for the new PHI would be the same, just don't
339 // make a new PHI. Instead, just remove the incoming values from the old
341 for (unsigned i = 0; i != NumPreds; ++i)
342 PN->removeIncomingValue(Preds[i], false);
344 // If the values coming into the block are not the same, we need a PHI.
345 // Create the new PHI node, insert it into NewBB at the end of the block
347 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
348 if (AA) AA->copyValue(PN, NewPHI);
350 // Move all of the PHI values for 'Preds' to the new PHI.
351 for (unsigned i = 0; i != NumPreds; ++i) {
352 Value *V = PN->removeIncomingValue(Preds[i], false);
353 NewPHI->addIncoming(V, Preds[i]);
358 // Add an incoming value to the PHI node in the loop for the preheader
360 PN->addIncoming(InVal, NewBB);
362 // Check to see if we can eliminate this phi node.
363 if (Value *V = PN->hasConstantValue(DT != 0)) {
364 Instruction *I = dyn_cast<Instruction>(V);
365 if (!I || DT == 0 || DT->dominates(I, PN)) {
366 PN->replaceAllUsesWith(V);
367 if (AA) AA->deleteValue(PN);
368 PN->eraseFromParent();
376 /// AreEquivalentAddressValues - Test if A and B will obviously have the same
377 /// value. This includes recognizing that %t0 and %t1 will have the same
378 /// value in code like this:
379 /// %t0 = getelementptr @a, 0, 3
380 /// store i32 0, i32* %t0
381 /// %t1 = getelementptr @a, 0, 3
382 /// %t2 = load i32* %t1
384 static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
385 // Test if the values are trivially equivalent.
386 if (A == B) return true;
388 // Test if the values come form identical arithmetic instructions.
389 if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
390 isa<PHINode>(A) || isa<GetElementPtrInst>(A))
391 if (const Instruction *BI = dyn_cast<Instruction>(B))
392 if (cast<Instruction>(A)->isIdenticalTo(BI))
395 // Otherwise they may not be equivalent.
399 /// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
400 /// instruction before ScanFrom) checking to see if we have the value at the
401 /// memory address *Ptr locally available within a small number of instructions.
402 /// If the value is available, return it.
404 /// If not, return the iterator for the last validated instruction that the
405 /// value would be live through. If we scanned the entire block and didn't find
406 /// something that invalidates *Ptr or provides it, ScanFrom would be left at
407 /// begin() and this returns null. ScanFrom could also be left
409 /// MaxInstsToScan specifies the maximum instructions to scan in the block. If
410 /// it is set to 0, it will scan the whole block. You can also optionally
411 /// specify an alias analysis implementation, which makes this more precise.
412 Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
413 BasicBlock::iterator &ScanFrom,
414 unsigned MaxInstsToScan,
416 if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
418 // If we're using alias analysis to disambiguate get the size of *Ptr.
419 unsigned AccessSize = 0;
421 const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
422 AccessSize = AA->getTargetData().getTypeStoreSizeInBits(AccessTy);
425 while (ScanFrom != ScanBB->begin()) {
426 // Don't scan huge blocks.
427 if (MaxInstsToScan-- == 0) return 0;
429 Instruction *Inst = --ScanFrom;
431 // If this is a load of Ptr, the loaded value is available.
432 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
433 if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
436 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
437 // If this is a store through Ptr, the value is available!
438 if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
439 return SI->getOperand(0);
441 // If Ptr is an alloca and this is a store to a different alloca, ignore
442 // the store. This is a trivial form of alias analysis that is important
443 // for reg2mem'd code.
444 if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
445 (isa<AllocaInst>(SI->getOperand(1)) ||
446 isa<GlobalVariable>(SI->getOperand(1))))
449 // If we have alias analysis and it says the store won't modify the loaded
450 // value, ignore the store.
452 (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
455 // Otherwise the store that may or may not alias the pointer, bail out.
460 // If this is some other instruction that may clobber Ptr, bail out.
461 if (Inst->mayWriteToMemory()) {
462 // If alias analysis claims that it really won't modify the load,
465 (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
468 // May modify the pointer, bail out.
474 // Got to the start of the block, we didn't find it, but are done for this