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