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