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/PseudoProbe.h" 37 #include "llvm/IR/Type.h" 38 #include "llvm/IR/User.h" 39 #include "llvm/IR/Value.h" 40 #include "llvm/IR/ValueHandle.h" 41 #include "llvm/Support/Casting.h" 42 #include "llvm/Support/Debug.h" 43 #include "llvm/Support/raw_ostream.h" 44 #include "llvm/Transforms/Utils/Local.h" 45 #include <cassert> 46 #include <cstdint> 47 #include <string> 48 #include <utility> 49 #include <vector> 50 51 using namespace llvm; 52 53 #define DEBUG_TYPE "basicblock-utils" 54 55 void llvm::DetatchDeadBlocks( 56 ArrayRef<BasicBlock *> BBs, 57 SmallVectorImpl<DominatorTree::UpdateType> *Updates, 58 bool KeepOneInputPHIs) { 59 for (auto *BB : BBs) { 60 // Loop through all of our successors and make sure they know that one 61 // of their predecessors is going away. 62 SmallPtrSet<BasicBlock *, 4> UniqueSuccessors; 63 for (BasicBlock *Succ : successors(BB)) { 64 Succ->removePredecessor(BB, KeepOneInputPHIs); 65 if (Updates && UniqueSuccessors.insert(Succ).second) 66 Updates->push_back({DominatorTree::Delete, BB, Succ}); 67 } 68 69 // Zap all the instructions in the block. 70 while (!BB->empty()) { 71 Instruction &I = BB->back(); 72 // If this instruction is used, replace uses with an arbitrary value. 73 // Because control flow can't get here, we don't care what we replace the 74 // value with. Note that since this block is unreachable, and all values 75 // contained within it must dominate their uses, that all uses will 76 // eventually be removed (they are themselves dead). 77 if (!I.use_empty()) 78 I.replaceAllUsesWith(UndefValue::get(I.getType())); 79 BB->getInstList().pop_back(); 80 } 81 new UnreachableInst(BB->getContext(), BB); 82 assert(BB->getInstList().size() == 1 && 83 isa<UnreachableInst>(BB->getTerminator()) && 84 "The successor list of BB isn't empty before " 85 "applying corresponding DTU updates."); 86 } 87 } 88 89 void llvm::DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU, 90 bool KeepOneInputPHIs) { 91 DeleteDeadBlocks({BB}, DTU, KeepOneInputPHIs); 92 } 93 94 void llvm::DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs, DomTreeUpdater *DTU, 95 bool KeepOneInputPHIs) { 96 #ifndef NDEBUG 97 // Make sure that all predecessors of each dead block is also dead. 98 SmallPtrSet<BasicBlock *, 4> Dead(BBs.begin(), BBs.end()); 99 assert(Dead.size() == BBs.size() && "Duplicating blocks?"); 100 for (auto *BB : Dead) 101 for (BasicBlock *Pred : predecessors(BB)) 102 assert(Dead.count(Pred) && "All predecessors must be dead!"); 103 #endif 104 105 SmallVector<DominatorTree::UpdateType, 4> Updates; 106 DetatchDeadBlocks(BBs, DTU ? &Updates : nullptr, KeepOneInputPHIs); 107 108 if (DTU) 109 DTU->applyUpdates(Updates); 110 111 for (BasicBlock *BB : BBs) 112 if (DTU) 113 DTU->deleteBB(BB); 114 else 115 BB->eraseFromParent(); 116 } 117 118 bool llvm::EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU, 119 bool KeepOneInputPHIs) { 120 df_iterator_default_set<BasicBlock*> Reachable; 121 122 // Mark all reachable blocks. 123 for (BasicBlock *BB : depth_first_ext(&F, Reachable)) 124 (void)BB/* Mark all reachable blocks */; 125 126 // Collect all dead blocks. 127 std::vector<BasicBlock*> DeadBlocks; 128 for (BasicBlock &BB : F) 129 if (!Reachable.count(&BB)) 130 DeadBlocks.push_back(&BB); 131 132 // Delete the dead blocks. 133 DeleteDeadBlocks(DeadBlocks, DTU, KeepOneInputPHIs); 134 135 return !DeadBlocks.empty(); 136 } 137 138 bool llvm::FoldSingleEntryPHINodes(BasicBlock *BB, 139 MemoryDependenceResults *MemDep) { 140 if (!isa<PHINode>(BB->begin())) 141 return false; 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 return true; 155 } 156 157 bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI, 158 MemorySSAUpdater *MSSAU) { 159 // Recursively deleting a PHI may cause multiple PHIs to be deleted 160 // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete. 161 SmallVector<WeakTrackingVH, 8> PHIs; 162 for (PHINode &PN : BB->phis()) 163 PHIs.push_back(&PN); 164 165 bool Changed = false; 166 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) 167 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*())) 168 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI, MSSAU); 169 170 return Changed; 171 } 172 173 bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU, 174 LoopInfo *LI, MemorySSAUpdater *MSSAU, 175 MemoryDependenceResults *MemDep, 176 bool PredecessorWithTwoSuccessors) { 177 if (BB->hasAddressTaken()) 178 return false; 179 180 // Can't merge if there are multiple predecessors, or no predecessors. 181 BasicBlock *PredBB = BB->getUniquePredecessor(); 182 if (!PredBB) return false; 183 184 // Don't break self-loops. 185 if (PredBB == BB) return false; 186 // Don't break unwinding instructions. 187 if (PredBB->getTerminator()->isExceptionalTerminator()) 188 return false; 189 190 // Can't merge if there are multiple distinct successors. 191 if (!PredecessorWithTwoSuccessors && PredBB->getUniqueSuccessor() != BB) 192 return false; 193 194 // Currently only allow PredBB to have two predecessors, one being BB. 195 // Update BI to branch to BB's only successor instead of BB. 196 BranchInst *PredBB_BI; 197 BasicBlock *NewSucc = nullptr; 198 unsigned FallThruPath; 199 if (PredecessorWithTwoSuccessors) { 200 if (!(PredBB_BI = dyn_cast<BranchInst>(PredBB->getTerminator()))) 201 return false; 202 BranchInst *BB_JmpI = dyn_cast<BranchInst>(BB->getTerminator()); 203 if (!BB_JmpI || !BB_JmpI->isUnconditional()) 204 return false; 205 NewSucc = BB_JmpI->getSuccessor(0); 206 FallThruPath = PredBB_BI->getSuccessor(0) == BB ? 0 : 1; 207 } 208 209 // Can't merge if there is PHI loop. 210 for (PHINode &PN : BB->phis()) 211 if (llvm::is_contained(PN.incoming_values(), &PN)) 212 return false; 213 214 LLVM_DEBUG(dbgs() << "Merging: " << BB->getName() << " into " 215 << PredBB->getName() << "\n"); 216 217 // Begin by getting rid of unneeded PHIs. 218 SmallVector<AssertingVH<Value>, 4> IncomingValues; 219 if (isa<PHINode>(BB->front())) { 220 for (PHINode &PN : BB->phis()) 221 if (!isa<PHINode>(PN.getIncomingValue(0)) || 222 cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB) 223 IncomingValues.push_back(PN.getIncomingValue(0)); 224 FoldSingleEntryPHINodes(BB, MemDep); 225 } 226 227 // DTU update: Collect all the edges that exit BB. 228 // These dominator edges will be redirected from Pred. 229 std::vector<DominatorTree::UpdateType> Updates; 230 if (DTU) { 231 SmallSetVector<BasicBlock *, 2> UniqueSuccessors(succ_begin(BB), 232 succ_end(BB)); 233 Updates.reserve(1 + (2 * UniqueSuccessors.size())); 234 // Add insert edges first. Experimentally, for the particular case of two 235 // blocks that can be merged, with a single successor and single predecessor 236 // respectively, it is beneficial to have all insert updates first. Deleting 237 // edges first may lead to unreachable blocks, followed by inserting edges 238 // making the blocks reachable again. Such DT updates lead to high compile 239 // times. We add inserts before deletes here to reduce compile time. 240 for (BasicBlock *UniqueSuccessor : UniqueSuccessors) 241 // This successor of BB may already have PredBB as a predecessor. 242 if (!llvm::is_contained(successors(PredBB), UniqueSuccessor)) 243 Updates.push_back({DominatorTree::Insert, PredBB, UniqueSuccessor}); 244 for (BasicBlock *UniqueSuccessor : UniqueSuccessors) 245 Updates.push_back({DominatorTree::Delete, BB, UniqueSuccessor}); 246 Updates.push_back({DominatorTree::Delete, PredBB, BB}); 247 } 248 249 Instruction *PTI = PredBB->getTerminator(); 250 Instruction *STI = BB->getTerminator(); 251 Instruction *Start = &*BB->begin(); 252 // If there's nothing to move, mark the starting instruction as the last 253 // instruction in the block. Terminator instruction is handled separately. 254 if (Start == STI) 255 Start = PTI; 256 257 // Move all definitions in the successor to the predecessor... 258 PredBB->getInstList().splice(PTI->getIterator(), BB->getInstList(), 259 BB->begin(), STI->getIterator()); 260 261 if (MSSAU) 262 MSSAU->moveAllAfterMergeBlocks(BB, PredBB, Start); 263 264 // Make all PHI nodes that referred to BB now refer to Pred as their 265 // source... 266 BB->replaceAllUsesWith(PredBB); 267 268 if (PredecessorWithTwoSuccessors) { 269 // Delete the unconditional branch from BB. 270 BB->getInstList().pop_back(); 271 272 // Update branch in the predecessor. 273 PredBB_BI->setSuccessor(FallThruPath, NewSucc); 274 } else { 275 // Delete the unconditional branch from the predecessor. 276 PredBB->getInstList().pop_back(); 277 278 // Move terminator instruction. 279 PredBB->getInstList().splice(PredBB->end(), BB->getInstList()); 280 281 // Terminator may be a memory accessing instruction too. 282 if (MSSAU) 283 if (MemoryUseOrDef *MUD = cast_or_null<MemoryUseOrDef>( 284 MSSAU->getMemorySSA()->getMemoryAccess(PredBB->getTerminator()))) 285 MSSAU->moveToPlace(MUD, PredBB, MemorySSA::End); 286 } 287 // Add unreachable to now empty BB. 288 new UnreachableInst(BB->getContext(), BB); 289 290 // Inherit predecessors name if it exists. 291 if (!PredBB->hasName()) 292 PredBB->takeName(BB); 293 294 if (LI) 295 LI->removeBlock(BB); 296 297 if (MemDep) 298 MemDep->invalidateCachedPredecessors(); 299 300 // Finally, erase the old block and update dominator info. 301 if (DTU) { 302 assert(BB->getInstList().size() == 1 && 303 isa<UnreachableInst>(BB->getTerminator()) && 304 "The successor list of BB isn't empty before " 305 "applying corresponding DTU updates."); 306 DTU->applyUpdates(Updates); 307 DTU->deleteBB(BB); 308 } else { 309 BB->eraseFromParent(); // Nuke BB if DTU is nullptr. 310 } 311 312 return true; 313 } 314 315 bool llvm::MergeBlockSuccessorsIntoGivenBlocks( 316 SmallPtrSetImpl<BasicBlock *> &MergeBlocks, Loop *L, DomTreeUpdater *DTU, 317 LoopInfo *LI) { 318 assert(!MergeBlocks.empty() && "MergeBlocks should not be empty"); 319 320 bool BlocksHaveBeenMerged = false; 321 while (!MergeBlocks.empty()) { 322 BasicBlock *BB = *MergeBlocks.begin(); 323 BasicBlock *Dest = BB->getSingleSuccessor(); 324 if (Dest && (!L || L->contains(Dest))) { 325 BasicBlock *Fold = Dest->getUniquePredecessor(); 326 (void)Fold; 327 if (MergeBlockIntoPredecessor(Dest, DTU, LI)) { 328 assert(Fold == BB && 329 "Expecting BB to be unique predecessor of the Dest block"); 330 MergeBlocks.erase(Dest); 331 BlocksHaveBeenMerged = true; 332 } else 333 MergeBlocks.erase(BB); 334 } else 335 MergeBlocks.erase(BB); 336 } 337 return BlocksHaveBeenMerged; 338 } 339 340 /// Remove redundant instructions within sequences of consecutive dbg.value 341 /// instructions. This is done using a backward scan to keep the last dbg.value 342 /// describing a specific variable/fragment. 343 /// 344 /// BackwardScan strategy: 345 /// ---------------------- 346 /// Given a sequence of consecutive DbgValueInst like this 347 /// 348 /// dbg.value ..., "x", FragmentX1 (*) 349 /// dbg.value ..., "y", FragmentY1 350 /// dbg.value ..., "x", FragmentX2 351 /// dbg.value ..., "x", FragmentX1 (**) 352 /// 353 /// then the instruction marked with (*) can be removed (it is guaranteed to be 354 /// obsoleted by the instruction marked with (**) as the latter instruction is 355 /// describing the same variable using the same fragment info). 356 /// 357 /// Possible improvements: 358 /// - Check fully overlapping fragments and not only identical fragments. 359 /// - Support dbg.addr, dbg.declare. dbg.label, and possibly other meta 360 /// instructions being part of the sequence of consecutive instructions. 361 static bool removeRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB) { 362 SmallVector<DbgValueInst *, 8> ToBeRemoved; 363 SmallDenseSet<DebugVariable> VariableSet; 364 for (auto &I : reverse(*BB)) { 365 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) { 366 DebugVariable Key(DVI->getVariable(), 367 DVI->getExpression(), 368 DVI->getDebugLoc()->getInlinedAt()); 369 auto R = VariableSet.insert(Key); 370 // If the same variable fragment is described more than once it is enough 371 // to keep the last one (i.e. the first found since we for reverse 372 // iteration). 373 if (!R.second) 374 ToBeRemoved.push_back(DVI); 375 continue; 376 } 377 // Sequence with consecutive dbg.value instrs ended. Clear the map to 378 // restart identifying redundant instructions if case we find another 379 // dbg.value sequence. 380 VariableSet.clear(); 381 } 382 383 for (auto &Instr : ToBeRemoved) 384 Instr->eraseFromParent(); 385 386 return !ToBeRemoved.empty(); 387 } 388 389 /// Remove redundant dbg.value instructions using a forward scan. This can 390 /// remove a dbg.value instruction that is redundant due to indicating that a 391 /// variable has the same value as already being indicated by an earlier 392 /// dbg.value. 393 /// 394 /// ForwardScan strategy: 395 /// --------------------- 396 /// Given two identical dbg.value instructions, separated by a block of 397 /// instructions that isn't describing the same variable, like this 398 /// 399 /// dbg.value X1, "x", FragmentX1 (**) 400 /// <block of instructions, none being "dbg.value ..., "x", ..."> 401 /// dbg.value X1, "x", FragmentX1 (*) 402 /// 403 /// then the instruction marked with (*) can be removed. Variable "x" is already 404 /// described as being mapped to the SSA value X1. 405 /// 406 /// Possible improvements: 407 /// - Keep track of non-overlapping fragments. 408 static bool removeRedundantDbgInstrsUsingForwardScan(BasicBlock *BB) { 409 SmallVector<DbgValueInst *, 8> ToBeRemoved; 410 DenseMap<DebugVariable, std::pair<Value *, DIExpression *> > VariableMap; 411 for (auto &I : *BB) { 412 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) { 413 DebugVariable Key(DVI->getVariable(), 414 NoneType(), 415 DVI->getDebugLoc()->getInlinedAt()); 416 auto VMI = VariableMap.find(Key); 417 // Update the map if we found a new value/expression describing the 418 // variable, or if the variable wasn't mapped already. 419 if (VMI == VariableMap.end() || 420 VMI->second.first != DVI->getValue() || 421 VMI->second.second != DVI->getExpression()) { 422 VariableMap[Key] = { DVI->getValue(), DVI->getExpression() }; 423 continue; 424 } 425 // Found an identical mapping. Remember the instruction for later removal. 426 ToBeRemoved.push_back(DVI); 427 } 428 } 429 430 for (auto &Instr : ToBeRemoved) 431 Instr->eraseFromParent(); 432 433 return !ToBeRemoved.empty(); 434 } 435 436 bool llvm::RemoveRedundantDbgInstrs(BasicBlock *BB, bool RemovePseudoOp) { 437 bool MadeChanges = false; 438 // By using the "backward scan" strategy before the "forward scan" strategy we 439 // can remove both dbg.value (2) and (3) in a situation like this: 440 // 441 // (1) dbg.value V1, "x", DIExpression() 442 // ... 443 // (2) dbg.value V2, "x", DIExpression() 444 // (3) dbg.value V1, "x", DIExpression() 445 // 446 // The backward scan will remove (2), it is made obsolete by (3). After 447 // getting (2) out of the way, the foward scan will remove (3) since "x" 448 // already is described as having the value V1 at (1). 449 MadeChanges |= removeRedundantDbgInstrsUsingBackwardScan(BB); 450 MadeChanges |= removeRedundantDbgInstrsUsingForwardScan(BB); 451 if (RemovePseudoOp) 452 MadeChanges |= removeRedundantPseudoProbes(BB); 453 454 if (MadeChanges) 455 LLVM_DEBUG(dbgs() << "Removed redundant dbg instrs from: " 456 << BB->getName() << "\n"); 457 return MadeChanges; 458 } 459 460 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL, 461 BasicBlock::iterator &BI, Value *V) { 462 Instruction &I = *BI; 463 // Replaces all of the uses of the instruction with uses of the value 464 I.replaceAllUsesWith(V); 465 466 // Make sure to propagate a name if there is one already. 467 if (I.hasName() && !V->hasName()) 468 V->takeName(&I); 469 470 // Delete the unnecessary instruction now... 471 BI = BIL.erase(BI); 472 } 473 474 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL, 475 BasicBlock::iterator &BI, Instruction *I) { 476 assert(I->getParent() == nullptr && 477 "ReplaceInstWithInst: Instruction already inserted into basic block!"); 478 479 // Copy debug location to newly added instruction, if it wasn't already set 480 // by the caller. 481 if (!I->getDebugLoc()) 482 I->setDebugLoc(BI->getDebugLoc()); 483 484 // Insert the new instruction into the basic block... 485 BasicBlock::iterator New = BIL.insert(BI, I); 486 487 // Replace all uses of the old instruction, and delete it. 488 ReplaceInstWithValue(BIL, BI, I); 489 490 // Move BI back to point to the newly inserted instruction 491 BI = New; 492 } 493 494 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) { 495 BasicBlock::iterator BI(From); 496 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To); 497 } 498 499 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT, 500 LoopInfo *LI, MemorySSAUpdater *MSSAU, 501 const Twine &BBName) { 502 unsigned SuccNum = GetSuccessorNumber(BB, Succ); 503 504 // If this is a critical edge, let SplitCriticalEdge do it. 505 Instruction *LatchTerm = BB->getTerminator(); 506 if (SplitCriticalEdge( 507 LatchTerm, SuccNum, 508 CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA(), 509 BBName)) 510 return LatchTerm->getSuccessor(SuccNum); 511 512 // If the edge isn't critical, then BB has a single successor or Succ has a 513 // single pred. Split the block. 514 if (BasicBlock *SP = Succ->getSinglePredecessor()) { 515 // If the successor only has a single pred, split the top of the successor 516 // block. 517 assert(SP == BB && "CFG broken"); 518 SP = nullptr; 519 return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU, BBName, 520 /*Before=*/true); 521 } 522 523 // Otherwise, if BB has a single successor, split it at the bottom of the 524 // block. 525 assert(BB->getTerminator()->getNumSuccessors() == 1 && 526 "Should have a single succ!"); 527 return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU, BBName); 528 } 529 530 unsigned 531 llvm::SplitAllCriticalEdges(Function &F, 532 const CriticalEdgeSplittingOptions &Options) { 533 unsigned NumBroken = 0; 534 for (BasicBlock &BB : F) { 535 Instruction *TI = BB.getTerminator(); 536 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI) && 537 !isa<CallBrInst>(TI)) 538 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 539 if (SplitCriticalEdge(TI, i, Options)) 540 ++NumBroken; 541 } 542 return NumBroken; 543 } 544 545 static BasicBlock *SplitBlockImpl(BasicBlock *Old, Instruction *SplitPt, 546 DomTreeUpdater *DTU, DominatorTree *DT, 547 LoopInfo *LI, MemorySSAUpdater *MSSAU, 548 const Twine &BBName, bool Before) { 549 if (Before) { 550 DomTreeUpdater LocalDTU(DT, DomTreeUpdater::UpdateStrategy::Lazy); 551 return splitBlockBefore(Old, SplitPt, 552 DTU ? DTU : (DT ? &LocalDTU : nullptr), LI, MSSAU, 553 BBName); 554 } 555 BasicBlock::iterator SplitIt = SplitPt->getIterator(); 556 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) 557 ++SplitIt; 558 std::string Name = BBName.str(); 559 BasicBlock *New = Old->splitBasicBlock( 560 SplitIt, Name.empty() ? Old->getName() + ".split" : Name); 561 562 // The new block lives in whichever loop the old one did. This preserves 563 // LCSSA as well, because we force the split point to be after any PHI nodes. 564 if (LI) 565 if (Loop *L = LI->getLoopFor(Old)) 566 L->addBasicBlockToLoop(New, *LI); 567 568 if (DTU) { 569 SmallVector<DominatorTree::UpdateType, 8> Updates; 570 // Old dominates New. New node dominates all other nodes dominated by Old. 571 SmallSetVector<BasicBlock *, 8> UniqueSuccessorsOfOld(succ_begin(New), 572 succ_end(New)); 573 Updates.push_back({DominatorTree::Insert, Old, New}); 574 Updates.reserve(Updates.size() + 2 * UniqueSuccessorsOfOld.size()); 575 for (BasicBlock *UniqueSuccessorOfOld : UniqueSuccessorsOfOld) { 576 Updates.push_back({DominatorTree::Insert, New, UniqueSuccessorOfOld}); 577 Updates.push_back({DominatorTree::Delete, Old, UniqueSuccessorOfOld}); 578 } 579 580 DTU->applyUpdates(Updates); 581 } else if (DT) 582 // Old dominates New. New node dominates all other nodes dominated by Old. 583 if (DomTreeNode *OldNode = DT->getNode(Old)) { 584 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end()); 585 586 DomTreeNode *NewNode = DT->addNewBlock(New, Old); 587 for (DomTreeNode *I : Children) 588 DT->changeImmediateDominator(I, NewNode); 589 } 590 591 // Move MemoryAccesses still tracked in Old, but part of New now. 592 // Update accesses in successor blocks accordingly. 593 if (MSSAU) 594 MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin())); 595 596 return New; 597 } 598 599 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, 600 DominatorTree *DT, LoopInfo *LI, 601 MemorySSAUpdater *MSSAU, const Twine &BBName, 602 bool Before) { 603 return SplitBlockImpl(Old, SplitPt, /*DTU=*/nullptr, DT, LI, MSSAU, BBName, 604 Before); 605 } 606 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, 607 DomTreeUpdater *DTU, LoopInfo *LI, 608 MemorySSAUpdater *MSSAU, const Twine &BBName, 609 bool Before) { 610 return SplitBlockImpl(Old, SplitPt, DTU, /*DT=*/nullptr, LI, MSSAU, BBName, 611 Before); 612 } 613 614 BasicBlock *llvm::splitBlockBefore(BasicBlock *Old, Instruction *SplitPt, 615 DomTreeUpdater *DTU, LoopInfo *LI, 616 MemorySSAUpdater *MSSAU, 617 const Twine &BBName) { 618 619 BasicBlock::iterator SplitIt = SplitPt->getIterator(); 620 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) 621 ++SplitIt; 622 std::string Name = BBName.str(); 623 BasicBlock *New = Old->splitBasicBlock( 624 SplitIt, Name.empty() ? Old->getName() + ".split" : Name, 625 /* Before=*/true); 626 627 // The new block lives in whichever loop the old one did. This preserves 628 // LCSSA as well, because we force the split point to be after any PHI nodes. 629 if (LI) 630 if (Loop *L = LI->getLoopFor(Old)) 631 L->addBasicBlockToLoop(New, *LI); 632 633 if (DTU) { 634 SmallVector<DominatorTree::UpdateType, 8> DTUpdates; 635 // New dominates Old. The predecessor nodes of the Old node dominate 636 // New node. 637 SmallSetVector<BasicBlock *, 8> UniquePredecessorsOfOld(pred_begin(New), 638 pred_end(New)); 639 DTUpdates.push_back({DominatorTree::Insert, New, Old}); 640 DTUpdates.reserve(DTUpdates.size() + 2 * UniquePredecessorsOfOld.size()); 641 for (BasicBlock *UniquePredecessorOfOld : UniquePredecessorsOfOld) { 642 DTUpdates.push_back({DominatorTree::Insert, UniquePredecessorOfOld, New}); 643 DTUpdates.push_back({DominatorTree::Delete, UniquePredecessorOfOld, Old}); 644 } 645 646 DTU->applyUpdates(DTUpdates); 647 648 // Move MemoryAccesses still tracked in Old, but part of New now. 649 // Update accesses in successor blocks accordingly. 650 if (MSSAU) { 651 MSSAU->applyUpdates(DTUpdates, DTU->getDomTree()); 652 if (VerifyMemorySSA) 653 MSSAU->getMemorySSA()->verifyMemorySSA(); 654 } 655 } 656 return New; 657 } 658 659 /// Update DominatorTree, LoopInfo, and LCCSA analysis information. 660 static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB, 661 ArrayRef<BasicBlock *> Preds, 662 DomTreeUpdater *DTU, DominatorTree *DT, 663 LoopInfo *LI, MemorySSAUpdater *MSSAU, 664 bool PreserveLCSSA, bool &HasLoopExit) { 665 // Update dominator tree if available. 666 if (DTU) { 667 // Recalculation of DomTree is needed when updating a forward DomTree and 668 // the Entry BB is replaced. 669 if (NewBB == &NewBB->getParent()->getEntryBlock() && DTU->hasDomTree()) { 670 // The entry block was removed and there is no external interface for 671 // the dominator tree to be notified of this change. In this corner-case 672 // we recalculate the entire tree. 673 DTU->recalculate(*NewBB->getParent()); 674 } else { 675 // Split block expects NewBB to have a non-empty set of predecessors. 676 SmallVector<DominatorTree::UpdateType, 8> Updates; 677 SmallSetVector<BasicBlock *, 8> UniquePreds(Preds.begin(), Preds.end()); 678 Updates.push_back({DominatorTree::Insert, NewBB, OldBB}); 679 Updates.reserve(Updates.size() + 2 * UniquePreds.size()); 680 for (auto *UniquePred : UniquePreds) { 681 Updates.push_back({DominatorTree::Insert, UniquePred, NewBB}); 682 Updates.push_back({DominatorTree::Delete, UniquePred, OldBB}); 683 } 684 DTU->applyUpdates(Updates); 685 } 686 } else if (DT) { 687 if (OldBB == DT->getRootNode()->getBlock()) { 688 assert(NewBB == &NewBB->getParent()->getEntryBlock()); 689 DT->setNewRoot(NewBB); 690 } else { 691 // Split block expects NewBB to have a non-empty set of predecessors. 692 DT->splitBlock(NewBB); 693 } 694 } 695 696 // Update MemoryPhis after split if MemorySSA is available 697 if (MSSAU) 698 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds); 699 700 // The rest of the logic is only relevant for updating the loop structures. 701 if (!LI) 702 return; 703 704 if (DTU && DTU->hasDomTree()) 705 DT = &DTU->getDomTree(); 706 assert(DT && "DT should be available to update LoopInfo!"); 707 Loop *L = LI->getLoopFor(OldBB); 708 709 // If we need to preserve loop analyses, collect some information about how 710 // this split will affect loops. 711 bool IsLoopEntry = !!L; 712 bool SplitMakesNewLoopHeader = false; 713 for (BasicBlock *Pred : Preds) { 714 // Preds that are not reachable from entry should not be used to identify if 715 // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks 716 // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader 717 // as true and make the NewBB the header of some loop. This breaks LI. 718 if (!DT->isReachableFromEntry(Pred)) 719 continue; 720 // If we need to preserve LCSSA, determine if any of the preds is a loop 721 // exit. 722 if (PreserveLCSSA) 723 if (Loop *PL = LI->getLoopFor(Pred)) 724 if (!PL->contains(OldBB)) 725 HasLoopExit = true; 726 727 // If we need to preserve LoopInfo, note whether any of the preds crosses 728 // an interesting loop boundary. 729 if (!L) 730 continue; 731 if (L->contains(Pred)) 732 IsLoopEntry = false; 733 else 734 SplitMakesNewLoopHeader = true; 735 } 736 737 // Unless we have a loop for OldBB, nothing else to do here. 738 if (!L) 739 return; 740 741 if (IsLoopEntry) { 742 // Add the new block to the nearest enclosing loop (and not an adjacent 743 // loop). To find this, examine each of the predecessors and determine which 744 // loops enclose them, and select the most-nested loop which contains the 745 // loop containing the block being split. 746 Loop *InnermostPredLoop = nullptr; 747 for (BasicBlock *Pred : Preds) { 748 if (Loop *PredLoop = LI->getLoopFor(Pred)) { 749 // Seek a loop which actually contains the block being split (to avoid 750 // adjacent loops). 751 while (PredLoop && !PredLoop->contains(OldBB)) 752 PredLoop = PredLoop->getParentLoop(); 753 754 // Select the most-nested of these loops which contains the block. 755 if (PredLoop && PredLoop->contains(OldBB) && 756 (!InnermostPredLoop || 757 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth())) 758 InnermostPredLoop = PredLoop; 759 } 760 } 761 762 if (InnermostPredLoop) 763 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI); 764 } else { 765 L->addBasicBlockToLoop(NewBB, *LI); 766 if (SplitMakesNewLoopHeader) 767 L->moveToHeader(NewBB); 768 } 769 } 770 771 /// Update the PHI nodes in OrigBB to include the values coming from NewBB. 772 /// This also updates AliasAnalysis, if available. 773 static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB, 774 ArrayRef<BasicBlock *> Preds, BranchInst *BI, 775 bool HasLoopExit) { 776 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB. 777 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end()); 778 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) { 779 PHINode *PN = cast<PHINode>(I++); 780 781 // Check to see if all of the values coming in are the same. If so, we 782 // don't need to create a new PHI node, unless it's needed for LCSSA. 783 Value *InVal = nullptr; 784 if (!HasLoopExit) { 785 InVal = PN->getIncomingValueForBlock(Preds[0]); 786 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 787 if (!PredSet.count(PN->getIncomingBlock(i))) 788 continue; 789 if (!InVal) 790 InVal = PN->getIncomingValue(i); 791 else if (InVal != PN->getIncomingValue(i)) { 792 InVal = nullptr; 793 break; 794 } 795 } 796 } 797 798 if (InVal) { 799 // If all incoming values for the new PHI would be the same, just don't 800 // make a new PHI. Instead, just remove the incoming values from the old 801 // PHI. 802 803 // NOTE! This loop walks backwards for a reason! First off, this minimizes 804 // the cost of removal if we end up removing a large number of values, and 805 // second off, this ensures that the indices for the incoming values 806 // aren't invalidated when we remove one. 807 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) 808 if (PredSet.count(PN->getIncomingBlock(i))) 809 PN->removeIncomingValue(i, false); 810 811 // Add an incoming value to the PHI node in the loop for the preheader 812 // edge. 813 PN->addIncoming(InVal, NewBB); 814 continue; 815 } 816 817 // If the values coming into the block are not the same, we need a new 818 // PHI. 819 // Create the new PHI node, insert it into NewBB at the end of the block 820 PHINode *NewPHI = 821 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI); 822 823 // NOTE! This loop walks backwards for a reason! First off, this minimizes 824 // the cost of removal if we end up removing a large number of values, and 825 // second off, this ensures that the indices for the incoming values aren't 826 // invalidated when we remove one. 827 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) { 828 BasicBlock *IncomingBB = PN->getIncomingBlock(i); 829 if (PredSet.count(IncomingBB)) { 830 Value *V = PN->removeIncomingValue(i, false); 831 NewPHI->addIncoming(V, IncomingBB); 832 } 833 } 834 835 PN->addIncoming(NewPHI, NewBB); 836 } 837 } 838 839 static void SplitLandingPadPredecessorsImpl( 840 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1, 841 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs, 842 DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, 843 MemorySSAUpdater *MSSAU, bool PreserveLCSSA); 844 845 static BasicBlock * 846 SplitBlockPredecessorsImpl(BasicBlock *BB, ArrayRef<BasicBlock *> Preds, 847 const char *Suffix, DomTreeUpdater *DTU, 848 DominatorTree *DT, LoopInfo *LI, 849 MemorySSAUpdater *MSSAU, bool PreserveLCSSA) { 850 // Do not attempt to split that which cannot be split. 851 if (!BB->canSplitPredecessors()) 852 return nullptr; 853 854 // For the landingpads we need to act a bit differently. 855 // Delegate this work to the SplitLandingPadPredecessors. 856 if (BB->isLandingPad()) { 857 SmallVector<BasicBlock*, 2> NewBBs; 858 std::string NewName = std::string(Suffix) + ".split-lp"; 859 860 SplitLandingPadPredecessorsImpl(BB, Preds, Suffix, NewName.c_str(), NewBBs, 861 DTU, DT, LI, MSSAU, PreserveLCSSA); 862 return NewBBs[0]; 863 } 864 865 // Create new basic block, insert right before the original block. 866 BasicBlock *NewBB = BasicBlock::Create( 867 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB); 868 869 // The new block unconditionally branches to the old block. 870 BranchInst *BI = BranchInst::Create(BB, NewBB); 871 872 Loop *L = nullptr; 873 BasicBlock *OldLatch = nullptr; 874 // Splitting the predecessors of a loop header creates a preheader block. 875 if (LI && LI->isLoopHeader(BB)) { 876 L = LI->getLoopFor(BB); 877 // Using the loop start line number prevents debuggers stepping into the 878 // loop body for this instruction. 879 BI->setDebugLoc(L->getStartLoc()); 880 881 // If BB is the header of the Loop, it is possible that the loop is 882 // modified, such that the current latch does not remain the latch of the 883 // loop. If that is the case, the loop metadata from the current latch needs 884 // to be applied to the new latch. 885 OldLatch = L->getLoopLatch(); 886 } else 887 BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc()); 888 889 // Move the edges from Preds to point to NewBB instead of BB. 890 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 891 // This is slightly more strict than necessary; the minimum requirement 892 // is that there be no more than one indirectbr branching to BB. And 893 // all BlockAddress uses would need to be updated. 894 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) && 895 "Cannot split an edge from an IndirectBrInst"); 896 assert(!isa<CallBrInst>(Preds[i]->getTerminator()) && 897 "Cannot split an edge from a CallBrInst"); 898 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB); 899 } 900 901 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI 902 // node becomes an incoming value for BB's phi node. However, if the Preds 903 // list is empty, we need to insert dummy entries into the PHI nodes in BB to 904 // account for the newly created predecessor. 905 if (Preds.empty()) { 906 // Insert dummy values as the incoming value. 907 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) 908 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB); 909 } 910 911 // Update DominatorTree, LoopInfo, and LCCSA analysis information. 912 bool HasLoopExit = false; 913 UpdateAnalysisInformation(BB, NewBB, Preds, DTU, DT, LI, MSSAU, PreserveLCSSA, 914 HasLoopExit); 915 916 if (!Preds.empty()) { 917 // Update the PHI nodes in BB with the values coming from NewBB. 918 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit); 919 } 920 921 if (OldLatch) { 922 BasicBlock *NewLatch = L->getLoopLatch(); 923 if (NewLatch != OldLatch) { 924 MDNode *MD = OldLatch->getTerminator()->getMetadata("llvm.loop"); 925 NewLatch->getTerminator()->setMetadata("llvm.loop", MD); 926 OldLatch->getTerminator()->setMetadata("llvm.loop", nullptr); 927 } 928 } 929 930 return NewBB; 931 } 932 933 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB, 934 ArrayRef<BasicBlock *> Preds, 935 const char *Suffix, DominatorTree *DT, 936 LoopInfo *LI, MemorySSAUpdater *MSSAU, 937 bool PreserveLCSSA) { 938 return SplitBlockPredecessorsImpl(BB, Preds, Suffix, /*DTU=*/nullptr, DT, LI, 939 MSSAU, PreserveLCSSA); 940 } 941 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB, 942 ArrayRef<BasicBlock *> Preds, 943 const char *Suffix, 944 DomTreeUpdater *DTU, LoopInfo *LI, 945 MemorySSAUpdater *MSSAU, 946 bool PreserveLCSSA) { 947 return SplitBlockPredecessorsImpl(BB, Preds, Suffix, DTU, 948 /*DT=*/nullptr, LI, MSSAU, PreserveLCSSA); 949 } 950 951 static void SplitLandingPadPredecessorsImpl( 952 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1, 953 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs, 954 DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, 955 MemorySSAUpdater *MSSAU, bool PreserveLCSSA) { 956 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!"); 957 958 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert 959 // it right before the original block. 960 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(), 961 OrigBB->getName() + Suffix1, 962 OrigBB->getParent(), OrigBB); 963 NewBBs.push_back(NewBB1); 964 965 // The new block unconditionally branches to the old block. 966 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1); 967 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc()); 968 969 // Move the edges from Preds to point to NewBB1 instead of OrigBB. 970 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 971 // This is slightly more strict than necessary; the minimum requirement 972 // is that there be no more than one indirectbr branching to BB. And 973 // all BlockAddress uses would need to be updated. 974 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) && 975 "Cannot split an edge from an IndirectBrInst"); 976 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1); 977 } 978 979 bool HasLoopExit = false; 980 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DTU, DT, LI, MSSAU, 981 PreserveLCSSA, HasLoopExit); 982 983 // Update the PHI nodes in OrigBB with the values coming from NewBB1. 984 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit); 985 986 // Move the remaining edges from OrigBB to point to NewBB2. 987 SmallVector<BasicBlock*, 8> NewBB2Preds; 988 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB); 989 i != e; ) { 990 BasicBlock *Pred = *i++; 991 if (Pred == NewBB1) continue; 992 assert(!isa<IndirectBrInst>(Pred->getTerminator()) && 993 "Cannot split an edge from an IndirectBrInst"); 994 NewBB2Preds.push_back(Pred); 995 e = pred_end(OrigBB); 996 } 997 998 BasicBlock *NewBB2 = nullptr; 999 if (!NewBB2Preds.empty()) { 1000 // Create another basic block for the rest of OrigBB's predecessors. 1001 NewBB2 = BasicBlock::Create(OrigBB->getContext(), 1002 OrigBB->getName() + Suffix2, 1003 OrigBB->getParent(), OrigBB); 1004 NewBBs.push_back(NewBB2); 1005 1006 // The new block unconditionally branches to the old block. 1007 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2); 1008 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc()); 1009 1010 // Move the remaining edges from OrigBB to point to NewBB2. 1011 for (BasicBlock *NewBB2Pred : NewBB2Preds) 1012 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2); 1013 1014 // Update DominatorTree, LoopInfo, and LCCSA analysis information. 1015 HasLoopExit = false; 1016 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DTU, DT, LI, MSSAU, 1017 PreserveLCSSA, HasLoopExit); 1018 1019 // Update the PHI nodes in OrigBB with the values coming from NewBB2. 1020 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit); 1021 } 1022 1023 LandingPadInst *LPad = OrigBB->getLandingPadInst(); 1024 Instruction *Clone1 = LPad->clone(); 1025 Clone1->setName(Twine("lpad") + Suffix1); 1026 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1); 1027 1028 if (NewBB2) { 1029 Instruction *Clone2 = LPad->clone(); 1030 Clone2->setName(Twine("lpad") + Suffix2); 1031 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2); 1032 1033 // Create a PHI node for the two cloned landingpad instructions only 1034 // if the original landingpad instruction has some uses. 1035 if (!LPad->use_empty()) { 1036 assert(!LPad->getType()->isTokenTy() && 1037 "Split cannot be applied if LPad is token type. Otherwise an " 1038 "invalid PHINode of token type would be created."); 1039 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad); 1040 PN->addIncoming(Clone1, NewBB1); 1041 PN->addIncoming(Clone2, NewBB2); 1042 LPad->replaceAllUsesWith(PN); 1043 } 1044 LPad->eraseFromParent(); 1045 } else { 1046 // There is no second clone. Just replace the landing pad with the first 1047 // clone. 1048 LPad->replaceAllUsesWith(Clone1); 1049 LPad->eraseFromParent(); 1050 } 1051 } 1052 1053 void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB, 1054 ArrayRef<BasicBlock *> Preds, 1055 const char *Suffix1, const char *Suffix2, 1056 SmallVectorImpl<BasicBlock *> &NewBBs, 1057 DominatorTree *DT, LoopInfo *LI, 1058 MemorySSAUpdater *MSSAU, 1059 bool PreserveLCSSA) { 1060 return SplitLandingPadPredecessorsImpl( 1061 OrigBB, Preds, Suffix1, Suffix2, NewBBs, 1062 /*DTU=*/nullptr, DT, LI, MSSAU, PreserveLCSSA); 1063 } 1064 void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB, 1065 ArrayRef<BasicBlock *> Preds, 1066 const char *Suffix1, const char *Suffix2, 1067 SmallVectorImpl<BasicBlock *> &NewBBs, 1068 DomTreeUpdater *DTU, LoopInfo *LI, 1069 MemorySSAUpdater *MSSAU, 1070 bool PreserveLCSSA) { 1071 return SplitLandingPadPredecessorsImpl(OrigBB, Preds, Suffix1, Suffix2, 1072 NewBBs, DTU, /*DT=*/nullptr, LI, MSSAU, 1073 PreserveLCSSA); 1074 } 1075 1076 ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, 1077 BasicBlock *Pred, 1078 DomTreeUpdater *DTU) { 1079 Instruction *UncondBranch = Pred->getTerminator(); 1080 // Clone the return and add it to the end of the predecessor. 1081 Instruction *NewRet = RI->clone(); 1082 Pred->getInstList().push_back(NewRet); 1083 1084 // If the return instruction returns a value, and if the value was a 1085 // PHI node in "BB", propagate the right value into the return. 1086 for (Use &Op : NewRet->operands()) { 1087 Value *V = Op; 1088 Instruction *NewBC = nullptr; 1089 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) { 1090 // Return value might be bitcasted. Clone and insert it before the 1091 // return instruction. 1092 V = BCI->getOperand(0); 1093 NewBC = BCI->clone(); 1094 Pred->getInstList().insert(NewRet->getIterator(), NewBC); 1095 Op = NewBC; 1096 } 1097 1098 Instruction *NewEV = nullptr; 1099 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) { 1100 V = EVI->getOperand(0); 1101 NewEV = EVI->clone(); 1102 if (NewBC) { 1103 NewBC->setOperand(0, NewEV); 1104 Pred->getInstList().insert(NewBC->getIterator(), NewEV); 1105 } else { 1106 Pred->getInstList().insert(NewRet->getIterator(), NewEV); 1107 Op = NewEV; 1108 } 1109 } 1110 1111 if (PHINode *PN = dyn_cast<PHINode>(V)) { 1112 if (PN->getParent() == BB) { 1113 if (NewEV) { 1114 NewEV->setOperand(0, PN->getIncomingValueForBlock(Pred)); 1115 } else if (NewBC) 1116 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred)); 1117 else 1118 Op = PN->getIncomingValueForBlock(Pred); 1119 } 1120 } 1121 } 1122 1123 // Update any PHI nodes in the returning block to realize that we no 1124 // longer branch to them. 1125 BB->removePredecessor(Pred); 1126 UncondBranch->eraseFromParent(); 1127 1128 if (DTU) 1129 DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}}); 1130 1131 return cast<ReturnInst>(NewRet); 1132 } 1133 1134 static Instruction * 1135 SplitBlockAndInsertIfThenImpl(Value *Cond, Instruction *SplitBefore, 1136 bool Unreachable, MDNode *BranchWeights, 1137 DomTreeUpdater *DTU, DominatorTree *DT, 1138 LoopInfo *LI, BasicBlock *ThenBlock) { 1139 SmallVector<DominatorTree::UpdateType, 8> Updates; 1140 BasicBlock *Head = SplitBefore->getParent(); 1141 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator()); 1142 if (DTU) { 1143 SmallSetVector<BasicBlock *, 8> UniqueSuccessorsOfHead(succ_begin(Tail), 1144 succ_end(Tail)); 1145 Updates.push_back({DominatorTree::Insert, Head, Tail}); 1146 Updates.reserve(Updates.size() + 2 * UniqueSuccessorsOfHead.size()); 1147 for (BasicBlock *UniqueSuccessorOfHead : UniqueSuccessorsOfHead) { 1148 Updates.push_back({DominatorTree::Insert, Tail, UniqueSuccessorOfHead}); 1149 Updates.push_back({DominatorTree::Delete, Head, UniqueSuccessorOfHead}); 1150 } 1151 } 1152 Instruction *HeadOldTerm = Head->getTerminator(); 1153 LLVMContext &C = Head->getContext(); 1154 Instruction *CheckTerm; 1155 bool CreateThenBlock = (ThenBlock == nullptr); 1156 if (CreateThenBlock) { 1157 ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 1158 if (Unreachable) 1159 CheckTerm = new UnreachableInst(C, ThenBlock); 1160 else { 1161 CheckTerm = BranchInst::Create(Tail, ThenBlock); 1162 if (DTU) 1163 Updates.push_back({DominatorTree::Insert, ThenBlock, Tail}); 1164 } 1165 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc()); 1166 } else 1167 CheckTerm = ThenBlock->getTerminator(); 1168 BranchInst *HeadNewTerm = 1169 BranchInst::Create(/*ifTrue*/ ThenBlock, /*ifFalse*/ Tail, Cond); 1170 if (DTU) 1171 Updates.push_back({DominatorTree::Insert, Head, ThenBlock}); 1172 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights); 1173 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm); 1174 1175 if (DTU) 1176 DTU->applyUpdates(Updates); 1177 else if (DT) { 1178 if (DomTreeNode *OldNode = DT->getNode(Head)) { 1179 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end()); 1180 1181 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head); 1182 for (DomTreeNode *Child : Children) 1183 DT->changeImmediateDominator(Child, NewNode); 1184 1185 // Head dominates ThenBlock. 1186 if (CreateThenBlock) 1187 DT->addNewBlock(ThenBlock, Head); 1188 else 1189 DT->changeImmediateDominator(ThenBlock, Head); 1190 } 1191 } 1192 1193 if (LI) { 1194 if (Loop *L = LI->getLoopFor(Head)) { 1195 L->addBasicBlockToLoop(ThenBlock, *LI); 1196 L->addBasicBlockToLoop(Tail, *LI); 1197 } 1198 } 1199 1200 return CheckTerm; 1201 } 1202 1203 Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond, 1204 Instruction *SplitBefore, 1205 bool Unreachable, 1206 MDNode *BranchWeights, 1207 DominatorTree *DT, LoopInfo *LI, 1208 BasicBlock *ThenBlock) { 1209 return SplitBlockAndInsertIfThenImpl(Cond, SplitBefore, Unreachable, 1210 BranchWeights, 1211 /*DTU=*/nullptr, DT, LI, ThenBlock); 1212 } 1213 Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond, 1214 Instruction *SplitBefore, 1215 bool Unreachable, 1216 MDNode *BranchWeights, 1217 DomTreeUpdater *DTU, LoopInfo *LI, 1218 BasicBlock *ThenBlock) { 1219 return SplitBlockAndInsertIfThenImpl(Cond, SplitBefore, Unreachable, 1220 BranchWeights, DTU, /*DT=*/nullptr, LI, 1221 ThenBlock); 1222 } 1223 1224 void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore, 1225 Instruction **ThenTerm, 1226 Instruction **ElseTerm, 1227 MDNode *BranchWeights) { 1228 BasicBlock *Head = SplitBefore->getParent(); 1229 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator()); 1230 Instruction *HeadOldTerm = Head->getTerminator(); 1231 LLVMContext &C = Head->getContext(); 1232 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 1233 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 1234 *ThenTerm = BranchInst::Create(Tail, ThenBlock); 1235 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc()); 1236 *ElseTerm = BranchInst::Create(Tail, ElseBlock); 1237 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc()); 1238 BranchInst *HeadNewTerm = 1239 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond); 1240 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights); 1241 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm); 1242 } 1243 1244 Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, 1245 BasicBlock *&IfFalse) { 1246 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin()); 1247 BasicBlock *Pred1 = nullptr; 1248 BasicBlock *Pred2 = nullptr; 1249 1250 if (SomePHI) { 1251 if (SomePHI->getNumIncomingValues() != 2) 1252 return nullptr; 1253 Pred1 = SomePHI->getIncomingBlock(0); 1254 Pred2 = SomePHI->getIncomingBlock(1); 1255 } else { 1256 pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 1257 if (PI == PE) // No predecessor 1258 return nullptr; 1259 Pred1 = *PI++; 1260 if (PI == PE) // Only one predecessor 1261 return nullptr; 1262 Pred2 = *PI++; 1263 if (PI != PE) // More than two predecessors 1264 return nullptr; 1265 } 1266 1267 // We can only handle branches. Other control flow will be lowered to 1268 // branches if possible anyway. 1269 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator()); 1270 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator()); 1271 if (!Pred1Br || !Pred2Br) 1272 return nullptr; 1273 1274 // Eliminate code duplication by ensuring that Pred1Br is conditional if 1275 // either are. 1276 if (Pred2Br->isConditional()) { 1277 // If both branches are conditional, we don't have an "if statement". In 1278 // reality, we could transform this case, but since the condition will be 1279 // required anyway, we stand no chance of eliminating it, so the xform is 1280 // probably not profitable. 1281 if (Pred1Br->isConditional()) 1282 return nullptr; 1283 1284 std::swap(Pred1, Pred2); 1285 std::swap(Pred1Br, Pred2Br); 1286 } 1287 1288 if (Pred1Br->isConditional()) { 1289 // The only thing we have to watch out for here is to make sure that Pred2 1290 // doesn't have incoming edges from other blocks. If it does, the condition 1291 // doesn't dominate BB. 1292 if (!Pred2->getSinglePredecessor()) 1293 return nullptr; 1294 1295 // If we found a conditional branch predecessor, make sure that it branches 1296 // to BB and Pred2Br. If it doesn't, this isn't an "if statement". 1297 if (Pred1Br->getSuccessor(0) == BB && 1298 Pred1Br->getSuccessor(1) == Pred2) { 1299 IfTrue = Pred1; 1300 IfFalse = Pred2; 1301 } else if (Pred1Br->getSuccessor(0) == Pred2 && 1302 Pred1Br->getSuccessor(1) == BB) { 1303 IfTrue = Pred2; 1304 IfFalse = Pred1; 1305 } else { 1306 // We know that one arm of the conditional goes to BB, so the other must 1307 // go somewhere unrelated, and this must not be an "if statement". 1308 return nullptr; 1309 } 1310 1311 return Pred1Br->getCondition(); 1312 } 1313 1314 // Ok, if we got here, both predecessors end with an unconditional branch to 1315 // BB. Don't panic! If both blocks only have a single (identical) 1316 // predecessor, and THAT is a conditional branch, then we're all ok! 1317 BasicBlock *CommonPred = Pred1->getSinglePredecessor(); 1318 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor()) 1319 return nullptr; 1320 1321 // Otherwise, if this is a conditional branch, then we can use it! 1322 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator()); 1323 if (!BI) return nullptr; 1324 1325 assert(BI->isConditional() && "Two successors but not conditional?"); 1326 if (BI->getSuccessor(0) == Pred1) { 1327 IfTrue = Pred1; 1328 IfFalse = Pred2; 1329 } else { 1330 IfTrue = Pred2; 1331 IfFalse = Pred1; 1332 } 1333 return BI->getCondition(); 1334 } 1335 1336 // After creating a control flow hub, the operands of PHINodes in an outgoing 1337 // block Out no longer match the predecessors of that block. Predecessors of Out 1338 // that are incoming blocks to the hub are now replaced by just one edge from 1339 // the hub. To match this new control flow, the corresponding values from each 1340 // PHINode must now be moved a new PHINode in the first guard block of the hub. 1341 // 1342 // This operation cannot be performed with SSAUpdater, because it involves one 1343 // new use: If the block Out is in the list of Incoming blocks, then the newly 1344 // created PHI in the Hub will use itself along that edge from Out to Hub. 1345 static void reconnectPhis(BasicBlock *Out, BasicBlock *GuardBlock, 1346 const SetVector<BasicBlock *> &Incoming, 1347 BasicBlock *FirstGuardBlock) { 1348 auto I = Out->begin(); 1349 while (I != Out->end() && isa<PHINode>(I)) { 1350 auto Phi = cast<PHINode>(I); 1351 auto NewPhi = 1352 PHINode::Create(Phi->getType(), Incoming.size(), 1353 Phi->getName() + ".moved", &FirstGuardBlock->back()); 1354 for (auto In : Incoming) { 1355 Value *V = UndefValue::get(Phi->getType()); 1356 if (In == Out) { 1357 V = NewPhi; 1358 } else if (Phi->getBasicBlockIndex(In) != -1) { 1359 V = Phi->removeIncomingValue(In, false); 1360 } 1361 NewPhi->addIncoming(V, In); 1362 } 1363 assert(NewPhi->getNumIncomingValues() == Incoming.size()); 1364 if (Phi->getNumOperands() == 0) { 1365 Phi->replaceAllUsesWith(NewPhi); 1366 I = Phi->eraseFromParent(); 1367 continue; 1368 } 1369 Phi->addIncoming(NewPhi, GuardBlock); 1370 ++I; 1371 } 1372 } 1373 1374 using BBPredicates = DenseMap<BasicBlock *, PHINode *>; 1375 using BBSetVector = SetVector<BasicBlock *>; 1376 1377 // Redirects the terminator of the incoming block to the first guard 1378 // block in the hub. The condition of the original terminator (if it 1379 // was conditional) and its original successors are returned as a 1380 // tuple <condition, succ0, succ1>. The function additionally filters 1381 // out successors that are not in the set of outgoing blocks. 1382 // 1383 // - condition is non-null iff the branch is conditional. 1384 // - Succ1 is non-null iff the sole/taken target is an outgoing block. 1385 // - Succ2 is non-null iff condition is non-null and the fallthrough 1386 // target is an outgoing block. 1387 static std::tuple<Value *, BasicBlock *, BasicBlock *> 1388 redirectToHub(BasicBlock *BB, BasicBlock *FirstGuardBlock, 1389 const BBSetVector &Outgoing) { 1390 auto Branch = cast<BranchInst>(BB->getTerminator()); 1391 auto Condition = Branch->isConditional() ? Branch->getCondition() : nullptr; 1392 1393 BasicBlock *Succ0 = Branch->getSuccessor(0); 1394 BasicBlock *Succ1 = nullptr; 1395 Succ0 = Outgoing.count(Succ0) ? Succ0 : nullptr; 1396 1397 if (Branch->isUnconditional()) { 1398 Branch->setSuccessor(0, FirstGuardBlock); 1399 assert(Succ0); 1400 } else { 1401 Succ1 = Branch->getSuccessor(1); 1402 Succ1 = Outgoing.count(Succ1) ? Succ1 : nullptr; 1403 assert(Succ0 || Succ1); 1404 if (Succ0 && !Succ1) { 1405 Branch->setSuccessor(0, FirstGuardBlock); 1406 } else if (Succ1 && !Succ0) { 1407 Branch->setSuccessor(1, FirstGuardBlock); 1408 } else { 1409 Branch->eraseFromParent(); 1410 BranchInst::Create(FirstGuardBlock, BB); 1411 } 1412 } 1413 1414 assert(Succ0 || Succ1); 1415 return std::make_tuple(Condition, Succ0, Succ1); 1416 } 1417 1418 // Capture the existing control flow as guard predicates, and redirect 1419 // control flow from every incoming block to the first guard block in 1420 // the hub. 1421 // 1422 // There is one guard predicate for each outgoing block OutBB. The 1423 // predicate is a PHINode with one input for each InBB which 1424 // represents whether the hub should transfer control flow to OutBB if 1425 // it arrived from InBB. These predicates are NOT ORTHOGONAL. The Hub 1426 // evaluates them in the same order as the Outgoing set-vector, and 1427 // control branches to the first outgoing block whose predicate 1428 // evaluates to true. 1429 static void convertToGuardPredicates( 1430 BasicBlock *FirstGuardBlock, BBPredicates &GuardPredicates, 1431 SmallVectorImpl<WeakVH> &DeletionCandidates, const BBSetVector &Incoming, 1432 const BBSetVector &Outgoing) { 1433 auto &Context = Incoming.front()->getContext(); 1434 auto BoolTrue = ConstantInt::getTrue(Context); 1435 auto BoolFalse = ConstantInt::getFalse(Context); 1436 1437 // The predicate for the last outgoing is trivially true, and so we 1438 // process only the first N-1 successors. 1439 for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) { 1440 auto Out = Outgoing[i]; 1441 LLVM_DEBUG(dbgs() << "Creating guard for " << Out->getName() << "\n"); 1442 auto Phi = 1443 PHINode::Create(Type::getInt1Ty(Context), Incoming.size(), 1444 StringRef("Guard.") + Out->getName(), FirstGuardBlock); 1445 GuardPredicates[Out] = Phi; 1446 } 1447 1448 for (auto In : Incoming) { 1449 Value *Condition; 1450 BasicBlock *Succ0; 1451 BasicBlock *Succ1; 1452 std::tie(Condition, Succ0, Succ1) = 1453 redirectToHub(In, FirstGuardBlock, Outgoing); 1454 1455 // Optimization: Consider an incoming block A with both successors 1456 // Succ0 and Succ1 in the set of outgoing blocks. The predicates 1457 // for Succ0 and Succ1 complement each other. If Succ0 is visited 1458 // first in the loop below, control will branch to Succ0 using the 1459 // corresponding predicate. But if that branch is not taken, then 1460 // control must reach Succ1, which means that the predicate for 1461 // Succ1 is always true. 1462 bool OneSuccessorDone = false; 1463 for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) { 1464 auto Out = Outgoing[i]; 1465 auto Phi = GuardPredicates[Out]; 1466 if (Out != Succ0 && Out != Succ1) { 1467 Phi->addIncoming(BoolFalse, In); 1468 continue; 1469 } 1470 // Optimization: When only one successor is an outgoing block, 1471 // the predicate is always true. 1472 if (!Succ0 || !Succ1 || OneSuccessorDone) { 1473 Phi->addIncoming(BoolTrue, In); 1474 continue; 1475 } 1476 assert(Succ0 && Succ1); 1477 OneSuccessorDone = true; 1478 if (Out == Succ0) { 1479 Phi->addIncoming(Condition, In); 1480 continue; 1481 } 1482 auto Inverted = invertCondition(Condition); 1483 DeletionCandidates.push_back(Condition); 1484 Phi->addIncoming(Inverted, In); 1485 } 1486 } 1487 } 1488 1489 // For each outgoing block OutBB, create a guard block in the Hub. The 1490 // first guard block was already created outside, and available as the 1491 // first element in the vector of guard blocks. 1492 // 1493 // Each guard block terminates in a conditional branch that transfers 1494 // control to the corresponding outgoing block or the next guard 1495 // block. The last guard block has two outgoing blocks as successors 1496 // since the condition for the final outgoing block is trivially 1497 // true. So we create one less block (including the first guard block) 1498 // than the number of outgoing blocks. 1499 static void createGuardBlocks(SmallVectorImpl<BasicBlock *> &GuardBlocks, 1500 Function *F, const BBSetVector &Outgoing, 1501 BBPredicates &GuardPredicates, StringRef Prefix) { 1502 for (int i = 0, e = Outgoing.size() - 2; i != e; ++i) { 1503 GuardBlocks.push_back( 1504 BasicBlock::Create(F->getContext(), Prefix + ".guard", F)); 1505 } 1506 assert(GuardBlocks.size() == GuardPredicates.size()); 1507 1508 // To help keep the loop simple, temporarily append the last 1509 // outgoing block to the list of guard blocks. 1510 GuardBlocks.push_back(Outgoing.back()); 1511 1512 for (int i = 0, e = GuardBlocks.size() - 1; i != e; ++i) { 1513 auto Out = Outgoing[i]; 1514 assert(GuardPredicates.count(Out)); 1515 BranchInst::Create(Out, GuardBlocks[i + 1], GuardPredicates[Out], 1516 GuardBlocks[i]); 1517 } 1518 1519 // Remove the last block from the guard list. 1520 GuardBlocks.pop_back(); 1521 } 1522 1523 BasicBlock *llvm::CreateControlFlowHub( 1524 DomTreeUpdater *DTU, SmallVectorImpl<BasicBlock *> &GuardBlocks, 1525 const BBSetVector &Incoming, const BBSetVector &Outgoing, 1526 const StringRef Prefix) { 1527 auto F = Incoming.front()->getParent(); 1528 auto FirstGuardBlock = 1529 BasicBlock::Create(F->getContext(), Prefix + ".guard", F); 1530 1531 SmallVector<DominatorTree::UpdateType, 16> Updates; 1532 if (DTU) { 1533 for (auto In : Incoming) { 1534 Updates.push_back({DominatorTree::Insert, In, FirstGuardBlock}); 1535 for (auto Succ : successors(In)) { 1536 if (Outgoing.count(Succ)) 1537 Updates.push_back({DominatorTree::Delete, In, Succ}); 1538 } 1539 } 1540 } 1541 1542 BBPredicates GuardPredicates; 1543 SmallVector<WeakVH, 8> DeletionCandidates; 1544 convertToGuardPredicates(FirstGuardBlock, GuardPredicates, DeletionCandidates, 1545 Incoming, Outgoing); 1546 1547 GuardBlocks.push_back(FirstGuardBlock); 1548 createGuardBlocks(GuardBlocks, F, Outgoing, GuardPredicates, Prefix); 1549 1550 // Update the PHINodes in each outgoing block to match the new control flow. 1551 for (int i = 0, e = GuardBlocks.size(); i != e; ++i) { 1552 reconnectPhis(Outgoing[i], GuardBlocks[i], Incoming, FirstGuardBlock); 1553 } 1554 reconnectPhis(Outgoing.back(), GuardBlocks.back(), Incoming, FirstGuardBlock); 1555 1556 if (DTU) { 1557 int NumGuards = GuardBlocks.size(); 1558 assert((int)Outgoing.size() == NumGuards + 1); 1559 for (int i = 0; i != NumGuards - 1; ++i) { 1560 Updates.push_back({DominatorTree::Insert, GuardBlocks[i], Outgoing[i]}); 1561 Updates.push_back( 1562 {DominatorTree::Insert, GuardBlocks[i], GuardBlocks[i + 1]}); 1563 } 1564 Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1], 1565 Outgoing[NumGuards - 1]}); 1566 Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1], 1567 Outgoing[NumGuards]}); 1568 DTU->applyUpdates(Updates); 1569 } 1570 1571 for (auto I : DeletionCandidates) { 1572 if (I->use_empty()) 1573 if (auto Inst = dyn_cast_or_null<Instruction>(I)) 1574 Inst->eraseFromParent(); 1575 } 1576 1577 return FirstGuardBlock; 1578 } 1579