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