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