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/ADT/ArrayRef.h" 17 #include "llvm/ADT/SmallPtrSet.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/ADT/Twine.h" 20 #include "llvm/Analysis/CFG.h" 21 #include "llvm/Analysis/LoopInfo.h" 22 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 23 #include "llvm/Transforms/Utils/Local.h" 24 #include "llvm/IR/BasicBlock.h" 25 #include "llvm/IR/CFG.h" 26 #include "llvm/IR/Constants.h" 27 #include "llvm/IR/DebugInfoMetadata.h" 28 #include "llvm/IR/Dominators.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/InstrTypes.h" 31 #include "llvm/IR/Instruction.h" 32 #include "llvm/IR/Instructions.h" 33 #include "llvm/IR/IntrinsicInst.h" 34 #include "llvm/IR/LLVMContext.h" 35 #include "llvm/IR/Type.h" 36 #include "llvm/IR/User.h" 37 #include "llvm/IR/Value.h" 38 #include "llvm/IR/ValueHandle.h" 39 #include "llvm/Support/Casting.h" 40 #include <cassert> 41 #include <cstdint> 42 #include <string> 43 #include <utility> 44 #include <vector> 45 46 using namespace llvm; 47 48 void llvm::DeleteDeadBlock(BasicBlock *BB, DeferredDominance *DDT) { 49 assert((pred_begin(BB) == pred_end(BB) || 50 // Can delete self loop. 51 BB->getSinglePredecessor() == BB) && "Block is not dead!"); 52 TerminatorInst *BBTerm = BB->getTerminator(); 53 std::vector<DominatorTree::UpdateType> Updates; 54 55 // Loop through all of our successors and make sure they know that one 56 // of their predecessors is going away. 57 if (DDT) 58 Updates.reserve(BBTerm->getNumSuccessors()); 59 for (BasicBlock *Succ : BBTerm->successors()) { 60 Succ->removePredecessor(BB); 61 if (DDT) 62 Updates.push_back({DominatorTree::Delete, BB, Succ}); 63 } 64 65 // Zap all the instructions in the block. 66 while (!BB->empty()) { 67 Instruction &I = BB->back(); 68 // If this instruction is used, replace uses with an arbitrary value. 69 // Because control flow can't get here, we don't care what we replace the 70 // value with. Note that since this block is unreachable, and all values 71 // contained within it must dominate their uses, that all uses will 72 // eventually be removed (they are themselves dead). 73 if (!I.use_empty()) 74 I.replaceAllUsesWith(UndefValue::get(I.getType())); 75 BB->getInstList().pop_back(); 76 } 77 78 if (DDT) { 79 DDT->applyUpdates(Updates); 80 DDT->deleteBB(BB); // Deferred deletion of BB. 81 } else { 82 BB->eraseFromParent(); // Zap the block! 83 } 84 } 85 86 void llvm::FoldSingleEntryPHINodes(BasicBlock *BB, 87 MemoryDependenceResults *MemDep) { 88 if (!isa<PHINode>(BB->begin())) return; 89 90 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { 91 if (PN->getIncomingValue(0) != PN) 92 PN->replaceAllUsesWith(PN->getIncomingValue(0)); 93 else 94 PN->replaceAllUsesWith(UndefValue::get(PN->getType())); 95 96 if (MemDep) 97 MemDep->removeInstruction(PN); // Memdep updates AA itself. 98 99 PN->eraseFromParent(); 100 } 101 } 102 103 bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) { 104 // Recursively deleting a PHI may cause multiple PHIs to be deleted 105 // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete. 106 SmallVector<WeakTrackingVH, 8> PHIs; 107 for (PHINode &PN : BB->phis()) 108 PHIs.push_back(&PN); 109 110 bool Changed = false; 111 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) 112 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*())) 113 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI); 114 115 return Changed; 116 } 117 118 bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT, 119 LoopInfo *LI, 120 MemoryDependenceResults *MemDep, 121 DeferredDominance *DDT) { 122 assert(!(DT && DDT) && "Cannot call with both DT and DDT."); 123 124 if (BB->hasAddressTaken()) 125 return false; 126 127 // Can't merge if there are multiple predecessors, or no predecessors. 128 BasicBlock *PredBB = BB->getUniquePredecessor(); 129 if (!PredBB) return false; 130 131 // Don't break self-loops. 132 if (PredBB == BB) return false; 133 // Don't break unwinding instructions. 134 if (PredBB->getTerminator()->isExceptional()) 135 return false; 136 137 // Can't merge if there are multiple distinct successors. 138 if (PredBB->getUniqueSuccessor() != BB) 139 return false; 140 141 // Can't merge if there is PHI loop. 142 for (PHINode &PN : BB->phis()) 143 for (Value *IncValue : PN.incoming_values()) 144 if (IncValue == &PN) 145 return false; 146 147 // Begin by getting rid of unneeded PHIs. 148 SmallVector<AssertingVH<Value>, 4> IncomingValues; 149 if (isa<PHINode>(BB->front())) { 150 for (PHINode &PN : BB->phis()) 151 if (!isa<PHINode>(PN.getIncomingValue(0)) || 152 cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB) 153 IncomingValues.push_back(PN.getIncomingValue(0)); 154 FoldSingleEntryPHINodes(BB, MemDep); 155 } 156 157 // Deferred DT update: Collect all the edges that exit BB. These 158 // dominator edges will be redirected from Pred. 159 std::vector<DominatorTree::UpdateType> Updates; 160 if (DDT) { 161 Updates.reserve(1 + (2 * succ_size(BB))); 162 Updates.push_back({DominatorTree::Delete, PredBB, BB}); 163 for (auto I = succ_begin(BB), E = succ_end(BB); I != E; ++I) { 164 Updates.push_back({DominatorTree::Delete, BB, *I}); 165 Updates.push_back({DominatorTree::Insert, PredBB, *I}); 166 } 167 } 168 169 // Delete the unconditional branch from the predecessor... 170 PredBB->getInstList().pop_back(); 171 172 // Make all PHI nodes that referred to BB now refer to Pred as their 173 // source... 174 BB->replaceAllUsesWith(PredBB); 175 176 // Move all definitions in the successor to the predecessor... 177 PredBB->getInstList().splice(PredBB->end(), BB->getInstList()); 178 179 // Eliminate duplicate dbg.values describing the entry PHI node post-splice. 180 for (auto Incoming : IncomingValues) { 181 if (isa<Instruction>(*Incoming)) { 182 SmallVector<DbgValueInst *, 2> DbgValues; 183 SmallDenseSet<std::pair<DILocalVariable *, DIExpression *>, 2> 184 DbgValueSet; 185 llvm::findDbgValues(DbgValues, Incoming); 186 for (auto &DVI : DbgValues) { 187 auto R = DbgValueSet.insert({DVI->getVariable(), DVI->getExpression()}); 188 if (!R.second) 189 DVI->eraseFromParent(); 190 } 191 } 192 } 193 194 // Inherit predecessors name if it exists. 195 if (!PredBB->hasName()) 196 PredBB->takeName(BB); 197 198 // Finally, erase the old block and update dominator info. 199 if (DT) 200 if (DomTreeNode *DTN = DT->getNode(BB)) { 201 DomTreeNode *PredDTN = DT->getNode(PredBB); 202 SmallVector<DomTreeNode *, 8> Children(DTN->begin(), DTN->end()); 203 for (DomTreeNode *DI : Children) 204 DT->changeImmediateDominator(DI, PredDTN); 205 206 DT->eraseNode(BB); 207 } 208 209 if (LI) 210 LI->removeBlock(BB); 211 212 if (MemDep) 213 MemDep->invalidateCachedPredecessors(); 214 215 if (DDT) { 216 DDT->deleteBB(BB); // Deferred deletion of BB. 217 DDT->applyUpdates(Updates); 218 } else { 219 BB->eraseFromParent(); // Nuke BB. 220 } 221 return true; 222 } 223 224 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL, 225 BasicBlock::iterator &BI, Value *V) { 226 Instruction &I = *BI; 227 // Replaces all of the uses of the instruction with uses of the value 228 I.replaceAllUsesWith(V); 229 230 // Make sure to propagate a name if there is one already. 231 if (I.hasName() && !V->hasName()) 232 V->takeName(&I); 233 234 // Delete the unnecessary instruction now... 235 BI = BIL.erase(BI); 236 } 237 238 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL, 239 BasicBlock::iterator &BI, Instruction *I) { 240 assert(I->getParent() == nullptr && 241 "ReplaceInstWithInst: Instruction already inserted into basic block!"); 242 243 // Copy debug location to newly added instruction, if it wasn't already set 244 // by the caller. 245 if (!I->getDebugLoc()) 246 I->setDebugLoc(BI->getDebugLoc()); 247 248 // Insert the new instruction into the basic block... 249 BasicBlock::iterator New = BIL.insert(BI, I); 250 251 // Replace all uses of the old instruction, and delete it. 252 ReplaceInstWithValue(BIL, BI, I); 253 254 // Move BI back to point to the newly inserted instruction 255 BI = New; 256 } 257 258 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) { 259 BasicBlock::iterator BI(From); 260 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To); 261 } 262 263 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT, 264 LoopInfo *LI) { 265 unsigned SuccNum = GetSuccessorNumber(BB, Succ); 266 267 // If this is a critical edge, let SplitCriticalEdge do it. 268 TerminatorInst *LatchTerm = BB->getTerminator(); 269 if (SplitCriticalEdge(LatchTerm, SuccNum, CriticalEdgeSplittingOptions(DT, LI) 270 .setPreserveLCSSA())) 271 return LatchTerm->getSuccessor(SuccNum); 272 273 // If the edge isn't critical, then BB has a single successor or Succ has a 274 // single pred. Split the block. 275 if (BasicBlock *SP = Succ->getSinglePredecessor()) { 276 // If the successor only has a single pred, split the top of the successor 277 // block. 278 assert(SP == BB && "CFG broken"); 279 SP = nullptr; 280 return SplitBlock(Succ, &Succ->front(), DT, LI); 281 } 282 283 // Otherwise, if BB has a single successor, split it at the bottom of the 284 // block. 285 assert(BB->getTerminator()->getNumSuccessors() == 1 && 286 "Should have a single succ!"); 287 return SplitBlock(BB, BB->getTerminator(), DT, LI); 288 } 289 290 unsigned 291 llvm::SplitAllCriticalEdges(Function &F, 292 const CriticalEdgeSplittingOptions &Options) { 293 unsigned NumBroken = 0; 294 for (BasicBlock &BB : F) { 295 TerminatorInst *TI = BB.getTerminator(); 296 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI)) 297 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 298 if (SplitCriticalEdge(TI, i, Options)) 299 ++NumBroken; 300 } 301 return NumBroken; 302 } 303 304 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, 305 DominatorTree *DT, LoopInfo *LI) { 306 BasicBlock::iterator SplitIt = SplitPt->getIterator(); 307 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) 308 ++SplitIt; 309 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split"); 310 311 // The new block lives in whichever loop the old one did. This preserves 312 // LCSSA as well, because we force the split point to be after any PHI nodes. 313 if (LI) 314 if (Loop *L = LI->getLoopFor(Old)) 315 L->addBasicBlockToLoop(New, *LI); 316 317 if (DT) 318 // Old dominates New. New node dominates all other nodes dominated by Old. 319 if (DomTreeNode *OldNode = DT->getNode(Old)) { 320 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end()); 321 322 DomTreeNode *NewNode = DT->addNewBlock(New, Old); 323 for (DomTreeNode *I : Children) 324 DT->changeImmediateDominator(I, NewNode); 325 } 326 327 return New; 328 } 329 330 /// Update DominatorTree, LoopInfo, and LCCSA analysis information. 331 static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB, 332 ArrayRef<BasicBlock *> Preds, 333 DominatorTree *DT, LoopInfo *LI, 334 bool PreserveLCSSA, bool &HasLoopExit) { 335 // Update dominator tree if available. 336 if (DT) { 337 if (OldBB == DT->getRootNode()->getBlock()) { 338 assert(NewBB == &NewBB->getParent()->getEntryBlock()); 339 DT->setNewRoot(NewBB); 340 } else { 341 // Split block expects NewBB to have a non-empty set of predecessors. 342 DT->splitBlock(NewBB); 343 } 344 } 345 346 // The rest of the logic is only relevant for updating the loop structures. 347 if (!LI) 348 return; 349 350 assert(DT && "DT should be available to update LoopInfo!"); 351 Loop *L = LI->getLoopFor(OldBB); 352 353 // If we need to preserve loop analyses, collect some information about how 354 // this split will affect loops. 355 bool IsLoopEntry = !!L; 356 bool SplitMakesNewLoopHeader = false; 357 for (BasicBlock *Pred : Preds) { 358 // Preds that are not reachable from entry should not be used to identify if 359 // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks 360 // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader 361 // as true and make the NewBB the header of some loop. This breaks LI. 362 if (!DT->isReachableFromEntry(Pred)) 363 continue; 364 // If we need to preserve LCSSA, determine if any of the preds is a loop 365 // exit. 366 if (PreserveLCSSA) 367 if (Loop *PL = LI->getLoopFor(Pred)) 368 if (!PL->contains(OldBB)) 369 HasLoopExit = true; 370 371 // If we need to preserve LoopInfo, note whether any of the preds crosses 372 // an interesting loop boundary. 373 if (!L) 374 continue; 375 if (L->contains(Pred)) 376 IsLoopEntry = false; 377 else 378 SplitMakesNewLoopHeader = true; 379 } 380 381 // Unless we have a loop for OldBB, nothing else to do here. 382 if (!L) 383 return; 384 385 if (IsLoopEntry) { 386 // Add the new block to the nearest enclosing loop (and not an adjacent 387 // loop). To find this, examine each of the predecessors and determine which 388 // loops enclose them, and select the most-nested loop which contains the 389 // loop containing the block being split. 390 Loop *InnermostPredLoop = nullptr; 391 for (BasicBlock *Pred : Preds) { 392 if (Loop *PredLoop = LI->getLoopFor(Pred)) { 393 // Seek a loop which actually contains the block being split (to avoid 394 // adjacent loops). 395 while (PredLoop && !PredLoop->contains(OldBB)) 396 PredLoop = PredLoop->getParentLoop(); 397 398 // Select the most-nested of these loops which contains the block. 399 if (PredLoop && PredLoop->contains(OldBB) && 400 (!InnermostPredLoop || 401 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth())) 402 InnermostPredLoop = PredLoop; 403 } 404 } 405 406 if (InnermostPredLoop) 407 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI); 408 } else { 409 L->addBasicBlockToLoop(NewBB, *LI); 410 if (SplitMakesNewLoopHeader) 411 L->moveToHeader(NewBB); 412 } 413 } 414 415 /// Update the PHI nodes in OrigBB to include the values coming from NewBB. 416 /// This also updates AliasAnalysis, if available. 417 static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB, 418 ArrayRef<BasicBlock *> Preds, BranchInst *BI, 419 bool HasLoopExit) { 420 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB. 421 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end()); 422 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) { 423 PHINode *PN = cast<PHINode>(I++); 424 425 // Check to see if all of the values coming in are the same. If so, we 426 // don't need to create a new PHI node, unless it's needed for LCSSA. 427 Value *InVal = nullptr; 428 if (!HasLoopExit) { 429 InVal = PN->getIncomingValueForBlock(Preds[0]); 430 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 431 if (!PredSet.count(PN->getIncomingBlock(i))) 432 continue; 433 if (!InVal) 434 InVal = PN->getIncomingValue(i); 435 else if (InVal != PN->getIncomingValue(i)) { 436 InVal = nullptr; 437 break; 438 } 439 } 440 } 441 442 if (InVal) { 443 // If all incoming values for the new PHI would be the same, just don't 444 // make a new PHI. Instead, just remove the incoming values from the old 445 // PHI. 446 447 // NOTE! This loop walks backwards for a reason! First off, this minimizes 448 // the cost of removal if we end up removing a large number of values, and 449 // second off, this ensures that the indices for the incoming values 450 // aren't invalidated when we remove one. 451 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) 452 if (PredSet.count(PN->getIncomingBlock(i))) 453 PN->removeIncomingValue(i, false); 454 455 // Add an incoming value to the PHI node in the loop for the preheader 456 // edge. 457 PN->addIncoming(InVal, NewBB); 458 continue; 459 } 460 461 // If the values coming into the block are not the same, we need a new 462 // PHI. 463 // Create the new PHI node, insert it into NewBB at the end of the block 464 PHINode *NewPHI = 465 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI); 466 467 // NOTE! This loop walks backwards for a reason! First off, this minimizes 468 // the cost of removal if we end up removing a large number of values, and 469 // second off, this ensures that the indices for the incoming values aren't 470 // invalidated when we remove one. 471 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) { 472 BasicBlock *IncomingBB = PN->getIncomingBlock(i); 473 if (PredSet.count(IncomingBB)) { 474 Value *V = PN->removeIncomingValue(i, false); 475 NewPHI->addIncoming(V, IncomingBB); 476 } 477 } 478 479 PN->addIncoming(NewPHI, NewBB); 480 } 481 } 482 483 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB, 484 ArrayRef<BasicBlock *> Preds, 485 const char *Suffix, DominatorTree *DT, 486 LoopInfo *LI, bool PreserveLCSSA) { 487 // Do not attempt to split that which cannot be split. 488 if (!BB->canSplitPredecessors()) 489 return nullptr; 490 491 // For the landingpads we need to act a bit differently. 492 // Delegate this work to the SplitLandingPadPredecessors. 493 if (BB->isLandingPad()) { 494 SmallVector<BasicBlock*, 2> NewBBs; 495 std::string NewName = std::string(Suffix) + ".split-lp"; 496 497 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs, DT, 498 LI, PreserveLCSSA); 499 return NewBBs[0]; 500 } 501 502 // Create new basic block, insert right before the original block. 503 BasicBlock *NewBB = BasicBlock::Create( 504 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB); 505 506 // The new block unconditionally branches to the old block. 507 BranchInst *BI = BranchInst::Create(BB, NewBB); 508 BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc()); 509 510 // Move the edges from Preds to point to NewBB instead of BB. 511 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 512 // This is slightly more strict than necessary; the minimum requirement 513 // is that there be no more than one indirectbr branching to BB. And 514 // all BlockAddress uses would need to be updated. 515 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) && 516 "Cannot split an edge from an IndirectBrInst"); 517 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB); 518 } 519 520 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI 521 // node becomes an incoming value for BB's phi node. However, if the Preds 522 // list is empty, we need to insert dummy entries into the PHI nodes in BB to 523 // account for the newly created predecessor. 524 if (Preds.empty()) { 525 // Insert dummy values as the incoming value. 526 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) 527 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB); 528 } 529 530 // Update DominatorTree, LoopInfo, and LCCSA analysis information. 531 bool HasLoopExit = false; 532 UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, PreserveLCSSA, 533 HasLoopExit); 534 535 if (!Preds.empty()) { 536 // Update the PHI nodes in BB with the values coming from NewBB. 537 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit); 538 } 539 540 return NewBB; 541 } 542 543 void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB, 544 ArrayRef<BasicBlock *> Preds, 545 const char *Suffix1, const char *Suffix2, 546 SmallVectorImpl<BasicBlock *> &NewBBs, 547 DominatorTree *DT, LoopInfo *LI, 548 bool PreserveLCSSA) { 549 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!"); 550 551 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert 552 // it right before the original block. 553 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(), 554 OrigBB->getName() + Suffix1, 555 OrigBB->getParent(), OrigBB); 556 NewBBs.push_back(NewBB1); 557 558 // The new block unconditionally branches to the old block. 559 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1); 560 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc()); 561 562 // Move the edges from Preds to point to NewBB1 instead of OrigBB. 563 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 564 // This is slightly more strict than necessary; the minimum requirement 565 // is that there be no more than one indirectbr branching to BB. And 566 // all BlockAddress uses would need to be updated. 567 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) && 568 "Cannot split an edge from an IndirectBrInst"); 569 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1); 570 } 571 572 bool HasLoopExit = false; 573 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, PreserveLCSSA, 574 HasLoopExit); 575 576 // Update the PHI nodes in OrigBB with the values coming from NewBB1. 577 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit); 578 579 // Move the remaining edges from OrigBB to point to NewBB2. 580 SmallVector<BasicBlock*, 8> NewBB2Preds; 581 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB); 582 i != e; ) { 583 BasicBlock *Pred = *i++; 584 if (Pred == NewBB1) continue; 585 assert(!isa<IndirectBrInst>(Pred->getTerminator()) && 586 "Cannot split an edge from an IndirectBrInst"); 587 NewBB2Preds.push_back(Pred); 588 e = pred_end(OrigBB); 589 } 590 591 BasicBlock *NewBB2 = nullptr; 592 if (!NewBB2Preds.empty()) { 593 // Create another basic block for the rest of OrigBB's predecessors. 594 NewBB2 = BasicBlock::Create(OrigBB->getContext(), 595 OrigBB->getName() + Suffix2, 596 OrigBB->getParent(), OrigBB); 597 NewBBs.push_back(NewBB2); 598 599 // The new block unconditionally branches to the old block. 600 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2); 601 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc()); 602 603 // Move the remaining edges from OrigBB to point to NewBB2. 604 for (BasicBlock *NewBB2Pred : NewBB2Preds) 605 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2); 606 607 // Update DominatorTree, LoopInfo, and LCCSA analysis information. 608 HasLoopExit = false; 609 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI, 610 PreserveLCSSA, HasLoopExit); 611 612 // Update the PHI nodes in OrigBB with the values coming from NewBB2. 613 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit); 614 } 615 616 LandingPadInst *LPad = OrigBB->getLandingPadInst(); 617 Instruction *Clone1 = LPad->clone(); 618 Clone1->setName(Twine("lpad") + Suffix1); 619 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1); 620 621 if (NewBB2) { 622 Instruction *Clone2 = LPad->clone(); 623 Clone2->setName(Twine("lpad") + Suffix2); 624 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2); 625 626 // Create a PHI node for the two cloned landingpad instructions only 627 // if the original landingpad instruction has some uses. 628 if (!LPad->use_empty()) { 629 assert(!LPad->getType()->isTokenTy() && 630 "Split cannot be applied if LPad is token type. Otherwise an " 631 "invalid PHINode of token type would be created."); 632 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad); 633 PN->addIncoming(Clone1, NewBB1); 634 PN->addIncoming(Clone2, NewBB2); 635 LPad->replaceAllUsesWith(PN); 636 } 637 LPad->eraseFromParent(); 638 } else { 639 // There is no second clone. Just replace the landing pad with the first 640 // clone. 641 LPad->replaceAllUsesWith(Clone1); 642 LPad->eraseFromParent(); 643 } 644 } 645 646 ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, 647 BasicBlock *Pred) { 648 Instruction *UncondBranch = Pred->getTerminator(); 649 // Clone the return and add it to the end of the predecessor. 650 Instruction *NewRet = RI->clone(); 651 Pred->getInstList().push_back(NewRet); 652 653 // If the return instruction returns a value, and if the value was a 654 // PHI node in "BB", propagate the right value into the return. 655 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end(); 656 i != e; ++i) { 657 Value *V = *i; 658 Instruction *NewBC = nullptr; 659 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) { 660 // Return value might be bitcasted. Clone and insert it before the 661 // return instruction. 662 V = BCI->getOperand(0); 663 NewBC = BCI->clone(); 664 Pred->getInstList().insert(NewRet->getIterator(), NewBC); 665 *i = NewBC; 666 } 667 if (PHINode *PN = dyn_cast<PHINode>(V)) { 668 if (PN->getParent() == BB) { 669 if (NewBC) 670 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred)); 671 else 672 *i = PN->getIncomingValueForBlock(Pred); 673 } 674 } 675 } 676 677 // Update any PHI nodes in the returning block to realize that we no 678 // longer branch to them. 679 BB->removePredecessor(Pred); 680 UncondBranch->eraseFromParent(); 681 return cast<ReturnInst>(NewRet); 682 } 683 684 TerminatorInst * 685 llvm::SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, 686 bool Unreachable, MDNode *BranchWeights, 687 DominatorTree *DT, LoopInfo *LI) { 688 BasicBlock *Head = SplitBefore->getParent(); 689 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator()); 690 TerminatorInst *HeadOldTerm = Head->getTerminator(); 691 LLVMContext &C = Head->getContext(); 692 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 693 TerminatorInst *CheckTerm; 694 if (Unreachable) 695 CheckTerm = new UnreachableInst(C, ThenBlock); 696 else 697 CheckTerm = BranchInst::Create(Tail, ThenBlock); 698 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc()); 699 BranchInst *HeadNewTerm = 700 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond); 701 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights); 702 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm); 703 704 if (DT) { 705 if (DomTreeNode *OldNode = DT->getNode(Head)) { 706 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end()); 707 708 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head); 709 for (DomTreeNode *Child : Children) 710 DT->changeImmediateDominator(Child, NewNode); 711 712 // Head dominates ThenBlock. 713 DT->addNewBlock(ThenBlock, Head); 714 } 715 } 716 717 if (LI) { 718 if (Loop *L = LI->getLoopFor(Head)) { 719 L->addBasicBlockToLoop(ThenBlock, *LI); 720 L->addBasicBlockToLoop(Tail, *LI); 721 } 722 } 723 724 return CheckTerm; 725 } 726 727 void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore, 728 TerminatorInst **ThenTerm, 729 TerminatorInst **ElseTerm, 730 MDNode *BranchWeights) { 731 BasicBlock *Head = SplitBefore->getParent(); 732 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator()); 733 TerminatorInst *HeadOldTerm = Head->getTerminator(); 734 LLVMContext &C = Head->getContext(); 735 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 736 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 737 *ThenTerm = BranchInst::Create(Tail, ThenBlock); 738 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc()); 739 *ElseTerm = BranchInst::Create(Tail, ElseBlock); 740 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc()); 741 BranchInst *HeadNewTerm = 742 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond); 743 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights); 744 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm); 745 } 746 747 Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, 748 BasicBlock *&IfFalse) { 749 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin()); 750 BasicBlock *Pred1 = nullptr; 751 BasicBlock *Pred2 = nullptr; 752 753 if (SomePHI) { 754 if (SomePHI->getNumIncomingValues() != 2) 755 return nullptr; 756 Pred1 = SomePHI->getIncomingBlock(0); 757 Pred2 = SomePHI->getIncomingBlock(1); 758 } else { 759 pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 760 if (PI == PE) // No predecessor 761 return nullptr; 762 Pred1 = *PI++; 763 if (PI == PE) // Only one predecessor 764 return nullptr; 765 Pred2 = *PI++; 766 if (PI != PE) // More than two predecessors 767 return nullptr; 768 } 769 770 // We can only handle branches. Other control flow will be lowered to 771 // branches if possible anyway. 772 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator()); 773 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator()); 774 if (!Pred1Br || !Pred2Br) 775 return nullptr; 776 777 // Eliminate code duplication by ensuring that Pred1Br is conditional if 778 // either are. 779 if (Pred2Br->isConditional()) { 780 // If both branches are conditional, we don't have an "if statement". In 781 // reality, we could transform this case, but since the condition will be 782 // required anyway, we stand no chance of eliminating it, so the xform is 783 // probably not profitable. 784 if (Pred1Br->isConditional()) 785 return nullptr; 786 787 std::swap(Pred1, Pred2); 788 std::swap(Pred1Br, Pred2Br); 789 } 790 791 if (Pred1Br->isConditional()) { 792 // The only thing we have to watch out for here is to make sure that Pred2 793 // doesn't have incoming edges from other blocks. If it does, the condition 794 // doesn't dominate BB. 795 if (!Pred2->getSinglePredecessor()) 796 return nullptr; 797 798 // If we found a conditional branch predecessor, make sure that it branches 799 // to BB and Pred2Br. If it doesn't, this isn't an "if statement". 800 if (Pred1Br->getSuccessor(0) == BB && 801 Pred1Br->getSuccessor(1) == Pred2) { 802 IfTrue = Pred1; 803 IfFalse = Pred2; 804 } else if (Pred1Br->getSuccessor(0) == Pred2 && 805 Pred1Br->getSuccessor(1) == BB) { 806 IfTrue = Pred2; 807 IfFalse = Pred1; 808 } else { 809 // We know that one arm of the conditional goes to BB, so the other must 810 // go somewhere unrelated, and this must not be an "if statement". 811 return nullptr; 812 } 813 814 return Pred1Br->getCondition(); 815 } 816 817 // Ok, if we got here, both predecessors end with an unconditional branch to 818 // BB. Don't panic! If both blocks only have a single (identical) 819 // predecessor, and THAT is a conditional branch, then we're all ok! 820 BasicBlock *CommonPred = Pred1->getSinglePredecessor(); 821 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor()) 822 return nullptr; 823 824 // Otherwise, if this is a conditional branch, then we can use it! 825 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator()); 826 if (!BI) return nullptr; 827 828 assert(BI->isConditional() && "Two successors but not conditional?"); 829 if (BI->getSuccessor(0) == Pred1) { 830 IfTrue = Pred1; 831 IfFalse = Pred2; 832 } else { 833 IfTrue = Pred2; 834 IfFalse = Pred1; 835 } 836 return BI->getCondition(); 837 } 838