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