BasicBlockUtils.cpp revision 4aebaee0e40f2457f1a6588679655a3c600a553b
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/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor, 28/// if possible. The return value indicates success or failure. 29bool 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; 33 34 BasicBlock *PredBB = *PI++; 35 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same 36 if (*PI != PredBB) { 37 PredBB = 0; // There are multiple different predecessors... 38 break; 39 } 40 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; 47 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! 53 break; 54 } 55 56 // Can't merge if there are multiple successors. 57 if (!OnlySucc) return false; 58 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) 64 return false; 65 } else 66 break; 67 } 68 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... 73 } 74 75 // Delete the unconditional branch from the predecessor... 76 PredBB->getInstList().pop_back(); 77 78 // Move all definitions in the successor to the predecessor... 79 PredBB->getInstList().splice(PredBB->end(), BB->getInstList()); 80 81 // Make all PHI nodes that referred to BB now refer to Pred as their 82 // source... 83 BB->replaceAllUsesWith(PredBB); 84 85 // Inherit predecessors name if it exists. 86 if (!PredBB->hasName()) 87 PredBB->takeName(BB); 88 89 // Finally, erase the old block and update dominator info. 90 if (P) { 91 if (DominatorTree* DT = P->getAnalysisToUpdate<DominatorTree>()) { 92 DomTreeNode* DTN = DT->getNode(BB); 93 DomTreeNode* PredDTN = DT->getNode(PredBB); 94 95 if (DTN) { 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); 100 101 DT->eraseNode(BB); 102 } 103 } 104 } 105 106 BB->eraseFromParent(); 107 108 109 return true; 110} 111 112/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI) 113/// with a value, then remove and delete the original instruction. 114/// 115void 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); 120 121 // Make sure to propagate a name if there is one already. 122 if (I.hasName() && !V->hasName()) 123 V->takeName(&I); 124 125 // Delete the unnecessary instruction now... 126 BI = BIL.erase(BI); 127} 128 129 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. 133/// 134void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL, 135 BasicBlock::iterator &BI, Instruction *I) { 136 assert(I->getParent() == 0 && 137 "ReplaceInstWithInst: Instruction already inserted into basic block!"); 138 139 // Insert the new instruction into the basic block... 140 BasicBlock::iterator New = BIL.insert(BI, I); 141 142 // Replace all uses of the old instruction, and delete it. 143 ReplaceInstWithValue(BIL, BI, I); 144 145 // Move BI back to point to the newly inserted instruction 146 BI = New; 147} 148 149/// ReplaceInstWithInst - Replace the instruction specified by From with the 150/// instruction specified by To. 151/// 152void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) { 153 BasicBlock::iterator BI(From); 154 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To); 155} 156 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. 163/// 164void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) { 165 assert(SuccNum < TI->getNumSuccessors() && 166 "Trying to remove a nonexistant successor!"); 167 168 // If our old successor block contains any PHI nodes, remove the entry in the 169 // PHI nodes that comes from this branch... 170 // 171 BasicBlock *BB = TI->getParent(); 172 TI->getSuccessor(SuccNum)->removePredecessor(BB); 173 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... 181 Value *RetVal = 0; 182 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()); 186 187 // Create the return... 188 NewTI = ReturnInst::Create(RetVal); 189 } 190 break; 191 192 case Instruction::Invoke: // Should convert to call 193 case Instruction::Switch: // Should remove entry 194 default: 195 case Instruction::Ret: // Cannot happen, has no successors! 196 assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!"); 197 abort(); 198 } 199 200 if (NewTI) // If it's a different instruction, replace. 201 ReplaceInstWithInst(TI, NewTI); 202} 203 204/// SplitEdge - Split the edge connecting specified block. Pass P must 205/// not be NULL. 206BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) { 207 TerminatorInst *LatchTerm = BB->getTerminator(); 208 unsigned SuccNum = 0; 209#ifndef NDEBUG 210 unsigned e = LatchTerm->getNumSuccessors(); 211#endif 212 for (unsigned i = 0; ; ++i) { 213 assert(i != e && "Didn't find edge?"); 214 if (LatchTerm->getSuccessor(i) == Succ) { 215 SuccNum = i; 216 break; 217 } 218 } 219 220 // If this is a critical edge, let SplitCriticalEdge do it. 221 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P)) 222 return LatchTerm->getSuccessor(SuccNum); 223 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 229 // block. 230 assert(SP == BB && "CFG broken"); 231 SP = NULL; 232 return SplitBlock(Succ, Succ->begin(), P); 233 } else { 234 // Otherwise, if BB has a single successor, split it at the bottom of the 235 // block. 236 assert(BB->getTerminator()->getNumSuccessors() == 1 && 237 "Should have a single succ!"); 238 return SplitBlock(BB, BB->getTerminator(), P); 239 } 240} 241 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. 246/// 247BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) { 248 BasicBlock::iterator SplitIt = SplitPt; 249 while (isa<PHINode>(SplitIt)) 250 ++SplitIt; 251 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split"); 252 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()); 257 258 if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>()) 259 { 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(); 264 I != E; ++I) 265 Children.push_back(*I); 266 267 DomTreeNode *NewNode = DT->addNewBlock(New,Old); 268 269 for (std::vector<DomTreeNode *>::iterator I = Children.begin(), 270 E = Children.end(); I != E; ++I) 271 DT->changeImmediateDominator(*I, NewNode); 272 } 273 274 if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>()) 275 DF->splitBlock(Old); 276 277 return New; 278} 279 280 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'. 286/// 287/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and 288/// DominanceFrontier, but no other analyses. 289BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB, 290 BasicBlock *const *Preds, 291 unsigned NumPreds, const char *Suffix, 292 Pass *P) { 293 // Create new basic block, insert right before the original block. 294 BasicBlock *NewBB = 295 BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB); 296 297 // The new block unconditionally branches to the old block. 298 BranchInst *BI = BranchInst::Create(BB, NewBB); 299 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); 303 304 // Update dominator tree and dominator frontier if available. 305 DominatorTree *DT = P ? P->getAnalysisToUpdate<DominatorTree>() : 0; 306 if (DT) 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; 311 312 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. 317 if (NumPreds == 0) { 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); 321 return NewBB; 322 } 323 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++); 327 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])) { 333 InVal = 0; 334 break; 335 } 336 337 if (InVal) { 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 340 // PHI. 341 for (unsigned i = 0; i != NumPreds; ++i) 342 PN->removeIncomingValue(Preds[i], false); 343 } else { 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 346 PHINode *NewPHI = 347 PHINode::Create(PN->getType(), PN->getName()+".ph", BI); 348 if (AA) AA->copyValue(PN, NewPHI); 349 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]); 354 } 355 InVal = NewPHI; 356 } 357 358 // Add an incoming value to the PHI node in the loop for the preheader 359 // edge. 360 PN->addIncoming(InVal, NewBB); 361 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(); 369 } 370 } 371 } 372 373 return NewBB; 374} 375 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 383/// 384static bool AreEquivalentAddressValues(const Value *A, const Value *B) { 385 // Test if the values are trivially equivalent. 386 if (A == B) return true; 387 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)) 393 return true; 394 395 // Otherwise they may not be equivalent. 396 return false; 397} 398 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. 403/// 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 408/// 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. 412Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB, 413 BasicBlock::iterator &ScanFrom, 414 unsigned MaxInstsToScan, 415 AliasAnalysis *AA) { 416 if (MaxInstsToScan == 0) MaxInstsToScan = ~0U; 417 418 // If we're using alias analysis to disambiguate get the size of *Ptr. 419 unsigned AccessSize = 0; 420 if (AA) { 421 const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType(); 422 AccessSize = AA->getTargetData().getTypeStoreSizeInBits(AccessTy); 423 } 424 425 while (ScanFrom != ScanBB->begin()) { 426 // Don't scan huge blocks. 427 if (MaxInstsToScan-- == 0) return 0; 428 429 Instruction *Inst = --ScanFrom; 430 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)) 434 return LI; 435 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); 440 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)))) 447 continue; 448 449 // If we have alias analysis and it says the store won't modify the loaded 450 // value, ignore the store. 451 if (AA && 452 (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0) 453 continue; 454 455 // Otherwise the store that may or may not alias the pointer, bail out. 456 ++ScanFrom; 457 return 0; 458 } 459 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, 463 // ignore it. 464 if (AA && 465 (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0) 466 continue; 467 468 // May modify the pointer, bail out. 469 ++ScanFrom; 470 return 0; 471 } 472 } 473 474 // Got to the start of the block, we didn't find it, but are done for this 475 // block. 476 return 0; 477} 478