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