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