BasicBlockUtils.cpp revision b5b7997fd0765f73b711ea4c72e4433ce3637794
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/IntrinsicInst.h" 19#include "llvm/Constant.h" 20#include "llvm/Type.h" 21#include "llvm/Analysis/AliasAnalysis.h" 22#include "llvm/Analysis/DominanceFrontier.h" 23#include "llvm/Analysis/LoopInfo.h" 24#include "llvm/Analysis/MemoryDependenceAnalysis.h" 25#include "llvm/Target/TargetData.h" 26#include "llvm/Transforms/Utils/Local.h" 27#include "llvm/Transforms/Scalar.h" 28#include "llvm/Support/ErrorHandling.h" 29#include "llvm/Support/ValueHandle.h" 30#include <algorithm> 31using namespace llvm; 32 33/// DeleteDeadBlock - Delete the specified block, which must have no 34/// predecessors. 35void llvm::DeleteDeadBlock(BasicBlock *BB) { 36 assert((pred_begin(BB) == pred_end(BB) || 37 // Can delete self loop. 38 BB->getSinglePredecessor() == BB) && "Block is not dead!"); 39 TerminatorInst *BBTerm = BB->getTerminator(); 40 41 // Loop through all of our successors and make sure they know that one 42 // of their predecessors is going away. 43 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) 44 BBTerm->getSuccessor(i)->removePredecessor(BB); 45 46 // Zap all the instructions in the block. 47 while (!BB->empty()) { 48 Instruction &I = BB->back(); 49 // If this instruction is used, replace uses with an arbitrary value. 50 // Because control flow can't get here, we don't care what we replace the 51 // value with. Note that since this block is unreachable, and all values 52 // contained within it must dominate their uses, that all uses will 53 // eventually be removed (they are themselves dead). 54 if (!I.use_empty()) 55 I.replaceAllUsesWith(UndefValue::get(I.getType())); 56 BB->getInstList().pop_back(); 57 } 58 59 // Zap the block! 60 BB->eraseFromParent(); 61} 62 63/// FoldSingleEntryPHINodes - We know that BB has one predecessor. If there are 64/// any single-entry PHI nodes in it, fold them away. This handles the case 65/// when all entries to the PHI nodes in a block are guaranteed equal, such as 66/// when the block has exactly one predecessor. 67void llvm::FoldSingleEntryPHINodes(BasicBlock *BB, Pass *P) { 68 if (!isa<PHINode>(BB->begin())) return; 69 70 AliasAnalysis *AA = 0; 71 MemoryDependenceAnalysis *MemDep = 0; 72 if (P) { 73 AA = P->getAnalysisIfAvailable<AliasAnalysis>(); 74 MemDep = P->getAnalysisIfAvailable<MemoryDependenceAnalysis>(); 75 } 76 77 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { 78 if (PN->getIncomingValue(0) != PN) 79 PN->replaceAllUsesWith(PN->getIncomingValue(0)); 80 else 81 PN->replaceAllUsesWith(UndefValue::get(PN->getType())); 82 83 if (MemDep) 84 MemDep->removeInstruction(PN); // Memdep updates AA itself. 85 else if (AA && isa<PointerType>(PN->getType())) 86 AA->deleteValue(PN); 87 88 PN->eraseFromParent(); 89 } 90} 91 92 93/// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it 94/// is dead. Also recursively delete any operands that become dead as 95/// a result. This includes tracing the def-use list from the PHI to see if 96/// it is ultimately unused or if it reaches an unused cycle. 97bool llvm::DeleteDeadPHIs(BasicBlock *BB) { 98 // Recursively deleting a PHI may cause multiple PHIs to be deleted 99 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete. 100 SmallVector<WeakVH, 8> PHIs; 101 for (BasicBlock::iterator I = BB->begin(); 102 PHINode *PN = dyn_cast<PHINode>(I); ++I) 103 PHIs.push_back(PN); 104 105 bool Changed = false; 106 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) 107 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*())) 108 Changed |= RecursivelyDeleteDeadPHINode(PN); 109 110 return Changed; 111} 112 113/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor, 114/// if possible. The return value indicates success or failure. 115bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, Pass *P) { 116 // Don't merge away blocks who have their address taken. 117 if (BB->hasAddressTaken()) return false; 118 119 // Can't merge if there are multiple predecessors, or no predecessors. 120 BasicBlock *PredBB = BB->getUniquePredecessor(); 121 if (!PredBB) return false; 122 123 // Don't break self-loops. 124 if (PredBB == BB) return false; 125 // Don't break invokes. 126 if (isa<InvokeInst>(PredBB->getTerminator())) return false; 127 128 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB)); 129 BasicBlock *OnlySucc = BB; 130 for (; SI != SE; ++SI) 131 if (*SI != OnlySucc) { 132 OnlySucc = 0; // There are multiple distinct successors! 133 break; 134 } 135 136 // Can't merge if there are multiple successors. 137 if (!OnlySucc) return false; 138 139 // Can't merge if there is PHI loop. 140 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) { 141 if (PHINode *PN = dyn_cast<PHINode>(BI)) { 142 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 143 if (PN->getIncomingValue(i) == PN) 144 return false; 145 } else 146 break; 147 } 148 149 // Begin by getting rid of unneeded PHIs. 150 if (isa<PHINode>(BB->front())) 151 FoldSingleEntryPHINodes(BB, P); 152 153 // Delete the unconditional branch from the predecessor... 154 PredBB->getInstList().pop_back(); 155 156 // Move all definitions in the successor to the predecessor... 157 PredBB->getInstList().splice(PredBB->end(), BB->getInstList()); 158 159 // Make all PHI nodes that referred to BB now refer to Pred as their 160 // source... 161 BB->replaceAllUsesWith(PredBB); 162 163 // Inherit predecessors name if it exists. 164 if (!PredBB->hasName()) 165 PredBB->takeName(BB); 166 167 // Finally, erase the old block and update dominator info. 168 if (P) { 169 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>()) { 170 if (DomTreeNode *DTN = DT->getNode(BB)) { 171 DomTreeNode *PredDTN = DT->getNode(PredBB); 172 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end()); 173 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(), 174 DE = Children.end(); DI != DE; ++DI) 175 DT->changeImmediateDominator(*DI, PredDTN); 176 177 DT->eraseNode(BB); 178 } 179 180 if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>()) 181 LI->removeBlock(BB); 182 } 183 } 184 185 BB->eraseFromParent(); 186 return true; 187} 188 189/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI) 190/// with a value, then remove and delete the original instruction. 191/// 192void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL, 193 BasicBlock::iterator &BI, Value *V) { 194 Instruction &I = *BI; 195 // Replaces all of the uses of the instruction with uses of the value 196 I.replaceAllUsesWith(V); 197 198 // Make sure to propagate a name if there is one already. 199 if (I.hasName() && !V->hasName()) 200 V->takeName(&I); 201 202 // Delete the unnecessary instruction now... 203 BI = BIL.erase(BI); 204} 205 206 207/// ReplaceInstWithInst - Replace the instruction specified by BI with the 208/// instruction specified by I. The original instruction is deleted and BI is 209/// updated to point to the new instruction. 210/// 211void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL, 212 BasicBlock::iterator &BI, Instruction *I) { 213 assert(I->getParent() == 0 && 214 "ReplaceInstWithInst: Instruction already inserted into basic block!"); 215 216 // Insert the new instruction into the basic block... 217 BasicBlock::iterator New = BIL.insert(BI, I); 218 219 // Replace all uses of the old instruction, and delete it. 220 ReplaceInstWithValue(BIL, BI, I); 221 222 // Move BI back to point to the newly inserted instruction 223 BI = New; 224} 225 226/// ReplaceInstWithInst - Replace the instruction specified by From with the 227/// instruction specified by To. 228/// 229void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) { 230 BasicBlock::iterator BI(From); 231 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To); 232} 233 234/// GetSuccessorNumber - Search for the specified successor of basic block BB 235/// and return its position in the terminator instruction's list of 236/// successors. It is an error to call this with a block that is not a 237/// successor. 238unsigned llvm::GetSuccessorNumber(BasicBlock *BB, BasicBlock *Succ) { 239 TerminatorInst *Term = BB->getTerminator(); 240#ifndef NDEBUG 241 unsigned e = Term->getNumSuccessors(); 242#endif 243 for (unsigned i = 0; ; ++i) { 244 assert(i != e && "Didn't find edge?"); 245 if (Term->getSuccessor(i) == Succ) 246 return i; 247 } 248 return 0; 249} 250 251/// SplitEdge - Split the edge connecting specified block. Pass P must 252/// not be NULL. 253BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) { 254 unsigned SuccNum = GetSuccessorNumber(BB, Succ); 255 256 // If this is a critical edge, let SplitCriticalEdge do it. 257 TerminatorInst *LatchTerm = BB->getTerminator(); 258 if (SplitCriticalEdge(LatchTerm, SuccNum, P)) 259 return LatchTerm->getSuccessor(SuccNum); 260 261 // If the edge isn't critical, then BB has a single successor or Succ has a 262 // single pred. Split the block. 263 BasicBlock::iterator SplitPoint; 264 if (BasicBlock *SP = Succ->getSinglePredecessor()) { 265 // If the successor only has a single pred, split the top of the successor 266 // block. 267 assert(SP == BB && "CFG broken"); 268 SP = NULL; 269 return SplitBlock(Succ, Succ->begin(), P); 270 } 271 272 // Otherwise, if BB has a single successor, split it at the bottom of the 273 // block. 274 assert(BB->getTerminator()->getNumSuccessors() == 1 && 275 "Should have a single succ!"); 276 return SplitBlock(BB, BB->getTerminator(), P); 277} 278 279/// SplitBlock - Split the specified block at the specified instruction - every 280/// thing before SplitPt stays in Old and everything starting with SplitPt moves 281/// to a new block. The two blocks are joined by an unconditional branch and 282/// the loop info is updated. 283/// 284BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) { 285 BasicBlock::iterator SplitIt = SplitPt; 286 while (isa<PHINode>(SplitIt)) 287 ++SplitIt; 288 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split"); 289 290 // The new block lives in whichever loop the old one did. This preserves 291 // LCSSA as well, because we force the split point to be after any PHI nodes. 292 if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>()) 293 if (Loop *L = LI->getLoopFor(Old)) 294 L->addBasicBlockToLoop(New, LI->getBase()); 295 296 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>()) { 297 // Old dominates New. New node dominates all other nodes dominated by Old. 298 DomTreeNode *OldNode = DT->getNode(Old); 299 std::vector<DomTreeNode *> Children; 300 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end(); 301 I != E; ++I) 302 Children.push_back(*I); 303 304 DomTreeNode *NewNode = DT->addNewBlock(New,Old); 305 for (std::vector<DomTreeNode *>::iterator I = Children.begin(), 306 E = Children.end(); I != E; ++I) 307 DT->changeImmediateDominator(*I, NewNode); 308 } 309 310 if (DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>()) 311 DF->splitBlock(Old); 312 313 return New; 314} 315 316 317/// SplitBlockPredecessors - This method transforms BB by introducing a new 318/// basic block into the function, and moving some of the predecessors of BB to 319/// be predecessors of the new block. The new predecessors are indicated by the 320/// Preds array, which has NumPreds elements in it. The new block is given a 321/// suffix of 'Suffix'. 322/// 323/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree, 324/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses. 325/// In particular, it does not preserve LoopSimplify (because it's 326/// complicated to handle the case where one of the edges being split 327/// is an exit of a loop with other exits). 328/// 329BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB, 330 BasicBlock *const *Preds, 331 unsigned NumPreds, const char *Suffix, 332 Pass *P) { 333 // Create new basic block, insert right before the original block. 334 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix, 335 BB->getParent(), BB); 336 337 // The new block unconditionally branches to the old block. 338 BranchInst *BI = BranchInst::Create(BB, NewBB); 339 340 LoopInfo *LI = P ? P->getAnalysisIfAvailable<LoopInfo>() : 0; 341 Loop *L = LI ? LI->getLoopFor(BB) : 0; 342 bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID); 343 344 // Move the edges from Preds to point to NewBB instead of BB. 345 // While here, if we need to preserve loop analyses, collect 346 // some information about how this split will affect loops. 347 bool HasLoopExit = false; 348 bool IsLoopEntry = !!L; 349 bool SplitMakesNewLoopHeader = false; 350 for (unsigned i = 0; i != NumPreds; ++i) { 351 // This is slightly more strict than necessary; the minimum requirement 352 // is that there be no more than one indirectbr branching to BB. And 353 // all BlockAddress uses would need to be updated. 354 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) && 355 "Cannot split an edge from an IndirectBrInst"); 356 357 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB); 358 359 if (LI) { 360 // If we need to preserve LCSSA, determine if any of 361 // the preds is a loop exit. 362 if (PreserveLCSSA) 363 if (Loop *PL = LI->getLoopFor(Preds[i])) 364 if (!PL->contains(BB)) 365 HasLoopExit = true; 366 // If we need to preserve LoopInfo, note whether any of the 367 // preds crosses an interesting loop boundary. 368 if (L) { 369 if (L->contains(Preds[i])) 370 IsLoopEntry = false; 371 else 372 SplitMakesNewLoopHeader = true; 373 } 374 } 375 } 376 377 // Update dominator tree and dominator frontier if available. 378 DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0; 379 if (DT) 380 DT->splitBlock(NewBB); 381 if (DominanceFrontier *DF = 382 P ? P->getAnalysisIfAvailable<DominanceFrontier>() : 0) 383 DF->splitBlock(NewBB); 384 385 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI 386 // node becomes an incoming value for BB's phi node. However, if the Preds 387 // list is empty, we need to insert dummy entries into the PHI nodes in BB to 388 // account for the newly created predecessor. 389 if (NumPreds == 0) { 390 // Insert dummy values as the incoming value. 391 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) 392 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB); 393 return NewBB; 394 } 395 396 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0; 397 398 if (L) { 399 if (IsLoopEntry) { 400 // Add the new block to the nearest enclosing loop (and not an 401 // adjacent loop). To find this, examine each of the predecessors and 402 // determine which loops enclose them, and select the most-nested loop 403 // which contains the loop containing the block being split. 404 Loop *InnermostPredLoop = 0; 405 for (unsigned i = 0; i != NumPreds; ++i) 406 if (Loop *PredLoop = LI->getLoopFor(Preds[i])) { 407 // Seek a loop which actually contains the block being split (to 408 // avoid adjacent loops). 409 while (PredLoop && !PredLoop->contains(BB)) 410 PredLoop = PredLoop->getParentLoop(); 411 // Select the most-nested of these loops which contains the block. 412 if (PredLoop && 413 PredLoop->contains(BB) && 414 (!InnermostPredLoop || 415 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth())) 416 InnermostPredLoop = PredLoop; 417 } 418 if (InnermostPredLoop) 419 InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase()); 420 } else { 421 L->addBasicBlockToLoop(NewBB, LI->getBase()); 422 if (SplitMakesNewLoopHeader) 423 L->moveToHeader(NewBB); 424 } 425 } 426 427 // Otherwise, create a new PHI node in NewBB for each PHI node in BB. 428 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) { 429 PHINode *PN = cast<PHINode>(I++); 430 431 // Check to see if all of the values coming in are the same. If so, we 432 // don't need to create a new PHI node, unless it's needed for LCSSA. 433 Value *InVal = 0; 434 if (!HasLoopExit) { 435 InVal = PN->getIncomingValueForBlock(Preds[0]); 436 for (unsigned i = 1; i != NumPreds; ++i) 437 if (InVal != PN->getIncomingValueForBlock(Preds[i])) { 438 InVal = 0; 439 break; 440 } 441 } 442 443 if (InVal) { 444 // If all incoming values for the new PHI would be the same, just don't 445 // make a new PHI. Instead, just remove the incoming values from the old 446 // PHI. 447 for (unsigned i = 0; i != NumPreds; ++i) 448 PN->removeIncomingValue(Preds[i], false); 449 } else { 450 // If the values coming into the block are not the same, we need a PHI. 451 // Create the new PHI node, insert it into NewBB at the end of the block 452 PHINode *NewPHI = 453 PHINode::Create(PN->getType(), PN->getName()+".ph", BI); 454 if (AA) AA->copyValue(PN, NewPHI); 455 456 // Move all of the PHI values for 'Preds' to the new PHI. 457 for (unsigned i = 0; i != NumPreds; ++i) { 458 Value *V = PN->removeIncomingValue(Preds[i], false); 459 NewPHI->addIncoming(V, Preds[i]); 460 } 461 InVal = NewPHI; 462 } 463 464 // Add an incoming value to the PHI node in the loop for the preheader 465 // edge. 466 PN->addIncoming(InVal, NewBB); 467 } 468 469 return NewBB; 470} 471 472/// FindFunctionBackedges - Analyze the specified function to find all of the 473/// loop backedges in the function and return them. This is a relatively cheap 474/// (compared to computing dominators and loop info) analysis. 475/// 476/// The output is added to Result, as pairs of <from,to> edge info. 477void llvm::FindFunctionBackedges(const Function &F, 478 SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) { 479 const BasicBlock *BB = &F.getEntryBlock(); 480 if (succ_begin(BB) == succ_end(BB)) 481 return; 482 483 SmallPtrSet<const BasicBlock*, 8> Visited; 484 SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack; 485 SmallPtrSet<const BasicBlock*, 8> InStack; 486 487 Visited.insert(BB); 488 VisitStack.push_back(std::make_pair(BB, succ_begin(BB))); 489 InStack.insert(BB); 490 do { 491 std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back(); 492 const BasicBlock *ParentBB = Top.first; 493 succ_const_iterator &I = Top.second; 494 495 bool FoundNew = false; 496 while (I != succ_end(ParentBB)) { 497 BB = *I++; 498 if (Visited.insert(BB)) { 499 FoundNew = true; 500 break; 501 } 502 // Successor is in VisitStack, it's a back edge. 503 if (InStack.count(BB)) 504 Result.push_back(std::make_pair(ParentBB, BB)); 505 } 506 507 if (FoundNew) { 508 // Go down one level if there is a unvisited successor. 509 InStack.insert(BB); 510 VisitStack.push_back(std::make_pair(BB, succ_begin(BB))); 511 } else { 512 // Go up one level. 513 InStack.erase(VisitStack.pop_back_val().first); 514 } 515 } while (!VisitStack.empty()); 516 517 518} 519