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::find(successors(PredBB), *I) == succ_end(PredBB)) 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 // Eliminate duplicate/redundant dbg.values. This seems to be a good place to 289 // do that since we might end up with redundant dbg.values describing the 290 // entry PHI node post-splice. 291 RemoveRedundantDbgInstrs(PredBB); 292 293 // Inherit predecessors name if it exists. 294 if (!PredBB->hasName()) 295 PredBB->takeName(BB); 296 297 if (LI) 298 LI->removeBlock(BB); 299 300 if (MemDep) 301 MemDep->invalidateCachedPredecessors(); 302 303 // Finally, erase the old block and update dominator info. 304 if (DTU) { 305 assert(BB->getInstList().size() == 1 && 306 isa<UnreachableInst>(BB->getTerminator()) && 307 "The successor list of BB isn't empty before " 308 "applying corresponding DTU updates."); 309 DTU->applyUpdatesPermissive(Updates); 310 DTU->deleteBB(BB); 311 } else { 312 BB->eraseFromParent(); // Nuke BB if DTU is nullptr. 313 } 314 315 return true; 316 } 317 318 /// Remove redundant instructions within sequences of consecutive dbg.value 319 /// instructions. This is done using a backward scan to keep the last dbg.value 320 /// describing a specific variable/fragment. 321 /// 322 /// BackwardScan strategy: 323 /// ---------------------- 324 /// Given a sequence of consecutive DbgValueInst like this 325 /// 326 /// dbg.value ..., "x", FragmentX1 (*) 327 /// dbg.value ..., "y", FragmentY1 328 /// dbg.value ..., "x", FragmentX2 329 /// dbg.value ..., "x", FragmentX1 (**) 330 /// 331 /// then the instruction marked with (*) can be removed (it is guaranteed to be 332 /// obsoleted by the instruction marked with (**) as the latter instruction is 333 /// describing the same variable using the same fragment info). 334 /// 335 /// Possible improvements: 336 /// - Check fully overlapping fragments and not only identical fragments. 337 /// - Support dbg.addr, dbg.declare. dbg.label, and possibly other meta 338 /// instructions being part of the sequence of consecutive instructions. 339 static bool removeRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB) { 340 SmallVector<DbgValueInst *, 8> ToBeRemoved; 341 SmallDenseSet<DebugVariable> VariableSet; 342 for (auto &I : reverse(*BB)) { 343 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) { 344 DebugVariable Key(DVI->getVariable(), 345 DVI->getExpression(), 346 DVI->getDebugLoc()->getInlinedAt()); 347 auto R = VariableSet.insert(Key); 348 // If the same variable fragment is described more than once it is enough 349 // to keep the last one (i.e. the first found since we for reverse 350 // iteration). 351 if (!R.second) 352 ToBeRemoved.push_back(DVI); 353 continue; 354 } 355 // Sequence with consecutive dbg.value instrs ended. Clear the map to 356 // restart identifying redundant instructions if case we find another 357 // dbg.value sequence. 358 VariableSet.clear(); 359 } 360 361 for (auto &Instr : ToBeRemoved) 362 Instr->eraseFromParent(); 363 364 return !ToBeRemoved.empty(); 365 } 366 367 /// Remove redundant dbg.value instructions using a forward scan. This can 368 /// remove a dbg.value instruction that is redundant due to indicating that a 369 /// variable has the same value as already being indicated by an earlier 370 /// dbg.value. 371 /// 372 /// ForwardScan strategy: 373 /// --------------------- 374 /// Given two identical dbg.value instructions, separated by a block of 375 /// instructions that isn't describing the same variable, like this 376 /// 377 /// dbg.value X1, "x", FragmentX1 (**) 378 /// <block of instructions, none being "dbg.value ..., "x", ..."> 379 /// dbg.value X1, "x", FragmentX1 (*) 380 /// 381 /// then the instruction marked with (*) can be removed. Variable "x" is already 382 /// described as being mapped to the SSA value X1. 383 /// 384 /// Possible improvements: 385 /// - Keep track of non-overlapping fragments. 386 static bool removeRedundantDbgInstrsUsingForwardScan(BasicBlock *BB) { 387 SmallVector<DbgValueInst *, 8> ToBeRemoved; 388 DenseMap<DebugVariable, std::pair<Value *, DIExpression *> > VariableMap; 389 for (auto &I : *BB) { 390 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) { 391 DebugVariable Key(DVI->getVariable(), 392 NoneType(), 393 DVI->getDebugLoc()->getInlinedAt()); 394 auto VMI = VariableMap.find(Key); 395 // Update the map if we found a new value/expression describing the 396 // variable, or if the variable wasn't mapped already. 397 if (VMI == VariableMap.end() || 398 VMI->second.first != DVI->getValue() || 399 VMI->second.second != DVI->getExpression()) { 400 VariableMap[Key] = { DVI->getValue(), DVI->getExpression() }; 401 continue; 402 } 403 // Found an identical mapping. Remember the instruction for later removal. 404 ToBeRemoved.push_back(DVI); 405 } 406 } 407 408 for (auto &Instr : ToBeRemoved) 409 Instr->eraseFromParent(); 410 411 return !ToBeRemoved.empty(); 412 } 413 414 bool llvm::RemoveRedundantDbgInstrs(BasicBlock *BB) { 415 bool MadeChanges = false; 416 // By using the "backward scan" strategy before the "forward scan" strategy we 417 // can remove both dbg.value (2) and (3) in a situation like this: 418 // 419 // (1) dbg.value V1, "x", DIExpression() 420 // ... 421 // (2) dbg.value V2, "x", DIExpression() 422 // (3) dbg.value V1, "x", DIExpression() 423 // 424 // The backward scan will remove (2), it is made obsolete by (3). After 425 // getting (2) out of the way, the foward scan will remove (3) since "x" 426 // already is described as having the value V1 at (1). 427 MadeChanges |= removeRedundantDbgInstrsUsingBackwardScan(BB); 428 MadeChanges |= removeRedundantDbgInstrsUsingForwardScan(BB); 429 430 if (MadeChanges) 431 LLVM_DEBUG(dbgs() << "Removed redundant dbg instrs from: " 432 << BB->getName() << "\n"); 433 return MadeChanges; 434 } 435 436 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL, 437 BasicBlock::iterator &BI, Value *V) { 438 Instruction &I = *BI; 439 // Replaces all of the uses of the instruction with uses of the value 440 I.replaceAllUsesWith(V); 441 442 // Make sure to propagate a name if there is one already. 443 if (I.hasName() && !V->hasName()) 444 V->takeName(&I); 445 446 // Delete the unnecessary instruction now... 447 BI = BIL.erase(BI); 448 } 449 450 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL, 451 BasicBlock::iterator &BI, Instruction *I) { 452 assert(I->getParent() == nullptr && 453 "ReplaceInstWithInst: Instruction already inserted into basic block!"); 454 455 // Copy debug location to newly added instruction, if it wasn't already set 456 // by the caller. 457 if (!I->getDebugLoc()) 458 I->setDebugLoc(BI->getDebugLoc()); 459 460 // Insert the new instruction into the basic block... 461 BasicBlock::iterator New = BIL.insert(BI, I); 462 463 // Replace all uses of the old instruction, and delete it. 464 ReplaceInstWithValue(BIL, BI, I); 465 466 // Move BI back to point to the newly inserted instruction 467 BI = New; 468 } 469 470 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) { 471 BasicBlock::iterator BI(From); 472 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To); 473 } 474 475 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT, 476 LoopInfo *LI, MemorySSAUpdater *MSSAU) { 477 unsigned SuccNum = GetSuccessorNumber(BB, Succ); 478 479 // If this is a critical edge, let SplitCriticalEdge do it. 480 Instruction *LatchTerm = BB->getTerminator(); 481 if (SplitCriticalEdge( 482 LatchTerm, SuccNum, 483 CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA())) 484 return LatchTerm->getSuccessor(SuccNum); 485 486 // If the edge isn't critical, then BB has a single successor or Succ has a 487 // single pred. Split the block. 488 if (BasicBlock *SP = Succ->getSinglePredecessor()) { 489 // If the successor only has a single pred, split the top of the successor 490 // block. 491 assert(SP == BB && "CFG broken"); 492 SP = nullptr; 493 return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU); 494 } 495 496 // Otherwise, if BB has a single successor, split it at the bottom of the 497 // block. 498 assert(BB->getTerminator()->getNumSuccessors() == 1 && 499 "Should have a single succ!"); 500 return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU); 501 } 502 503 unsigned 504 llvm::SplitAllCriticalEdges(Function &F, 505 const CriticalEdgeSplittingOptions &Options) { 506 unsigned NumBroken = 0; 507 for (BasicBlock &BB : F) { 508 Instruction *TI = BB.getTerminator(); 509 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI) && 510 !isa<CallBrInst>(TI)) 511 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 512 if (SplitCriticalEdge(TI, i, Options)) 513 ++NumBroken; 514 } 515 return NumBroken; 516 } 517 518 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, 519 DominatorTree *DT, LoopInfo *LI, 520 MemorySSAUpdater *MSSAU, const Twine &BBName) { 521 BasicBlock::iterator SplitIt = SplitPt->getIterator(); 522 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) 523 ++SplitIt; 524 std::string Name = BBName.str(); 525 BasicBlock *New = Old->splitBasicBlock( 526 SplitIt, Name.empty() ? Old->getName() + ".split" : Name); 527 528 // The new block lives in whichever loop the old one did. This preserves 529 // LCSSA as well, because we force the split point to be after any PHI nodes. 530 if (LI) 531 if (Loop *L = LI->getLoopFor(Old)) 532 L->addBasicBlockToLoop(New, *LI); 533 534 if (DT) 535 // Old dominates New. New node dominates all other nodes dominated by Old. 536 if (DomTreeNode *OldNode = DT->getNode(Old)) { 537 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end()); 538 539 DomTreeNode *NewNode = DT->addNewBlock(New, Old); 540 for (DomTreeNode *I : Children) 541 DT->changeImmediateDominator(I, NewNode); 542 } 543 544 // Move MemoryAccesses still tracked in Old, but part of New now. 545 // Update accesses in successor blocks accordingly. 546 if (MSSAU) 547 MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin())); 548 549 return New; 550 } 551 552 /// Update DominatorTree, LoopInfo, and LCCSA analysis information. 553 static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB, 554 ArrayRef<BasicBlock *> Preds, 555 DominatorTree *DT, LoopInfo *LI, 556 MemorySSAUpdater *MSSAU, 557 bool PreserveLCSSA, bool &HasLoopExit) { 558 // Update dominator tree if available. 559 if (DT) { 560 if (OldBB == DT->getRootNode()->getBlock()) { 561 assert(NewBB == &NewBB->getParent()->getEntryBlock()); 562 DT->setNewRoot(NewBB); 563 } else { 564 // Split block expects NewBB to have a non-empty set of predecessors. 565 DT->splitBlock(NewBB); 566 } 567 } 568 569 // Update MemoryPhis after split if MemorySSA is available 570 if (MSSAU) 571 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds); 572 573 // The rest of the logic is only relevant for updating the loop structures. 574 if (!LI) 575 return; 576 577 assert(DT && "DT should be available to update LoopInfo!"); 578 Loop *L = LI->getLoopFor(OldBB); 579 580 // If we need to preserve loop analyses, collect some information about how 581 // this split will affect loops. 582 bool IsLoopEntry = !!L; 583 bool SplitMakesNewLoopHeader = false; 584 for (BasicBlock *Pred : Preds) { 585 // Preds that are not reachable from entry should not be used to identify if 586 // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks 587 // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader 588 // as true and make the NewBB the header of some loop. This breaks LI. 589 if (!DT->isReachableFromEntry(Pred)) 590 continue; 591 // If we need to preserve LCSSA, determine if any of the preds is a loop 592 // exit. 593 if (PreserveLCSSA) 594 if (Loop *PL = LI->getLoopFor(Pred)) 595 if (!PL->contains(OldBB)) 596 HasLoopExit = true; 597 598 // If we need to preserve LoopInfo, note whether any of the preds crosses 599 // an interesting loop boundary. 600 if (!L) 601 continue; 602 if (L->contains(Pred)) 603 IsLoopEntry = false; 604 else 605 SplitMakesNewLoopHeader = true; 606 } 607 608 // Unless we have a loop for OldBB, nothing else to do here. 609 if (!L) 610 return; 611 612 if (IsLoopEntry) { 613 // Add the new block to the nearest enclosing loop (and not an adjacent 614 // loop). To find this, examine each of the predecessors and determine which 615 // loops enclose them, and select the most-nested loop which contains the 616 // loop containing the block being split. 617 Loop *InnermostPredLoop = nullptr; 618 for (BasicBlock *Pred : Preds) { 619 if (Loop *PredLoop = LI->getLoopFor(Pred)) { 620 // Seek a loop which actually contains the block being split (to avoid 621 // adjacent loops). 622 while (PredLoop && !PredLoop->contains(OldBB)) 623 PredLoop = PredLoop->getParentLoop(); 624 625 // Select the most-nested of these loops which contains the block. 626 if (PredLoop && PredLoop->contains(OldBB) && 627 (!InnermostPredLoop || 628 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth())) 629 InnermostPredLoop = PredLoop; 630 } 631 } 632 633 if (InnermostPredLoop) 634 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI); 635 } else { 636 L->addBasicBlockToLoop(NewBB, *LI); 637 if (SplitMakesNewLoopHeader) 638 L->moveToHeader(NewBB); 639 } 640 } 641 642 /// Update the PHI nodes in OrigBB to include the values coming from NewBB. 643 /// This also updates AliasAnalysis, if available. 644 static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB, 645 ArrayRef<BasicBlock *> Preds, BranchInst *BI, 646 bool HasLoopExit) { 647 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB. 648 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end()); 649 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) { 650 PHINode *PN = cast<PHINode>(I++); 651 652 // Check to see if all of the values coming in are the same. If so, we 653 // don't need to create a new PHI node, unless it's needed for LCSSA. 654 Value *InVal = nullptr; 655 if (!HasLoopExit) { 656 InVal = PN->getIncomingValueForBlock(Preds[0]); 657 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 658 if (!PredSet.count(PN->getIncomingBlock(i))) 659 continue; 660 if (!InVal) 661 InVal = PN->getIncomingValue(i); 662 else if (InVal != PN->getIncomingValue(i)) { 663 InVal = nullptr; 664 break; 665 } 666 } 667 } 668 669 if (InVal) { 670 // If all incoming values for the new PHI would be the same, just don't 671 // make a new PHI. Instead, just remove the incoming values from the old 672 // PHI. 673 674 // NOTE! This loop walks backwards for a reason! First off, this minimizes 675 // the cost of removal if we end up removing a large number of values, and 676 // second off, this ensures that the indices for the incoming values 677 // aren't invalidated when we remove one. 678 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) 679 if (PredSet.count(PN->getIncomingBlock(i))) 680 PN->removeIncomingValue(i, false); 681 682 // Add an incoming value to the PHI node in the loop for the preheader 683 // edge. 684 PN->addIncoming(InVal, NewBB); 685 continue; 686 } 687 688 // If the values coming into the block are not the same, we need a new 689 // PHI. 690 // Create the new PHI node, insert it into NewBB at the end of the block 691 PHINode *NewPHI = 692 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI); 693 694 // NOTE! This loop walks backwards for a reason! First off, this minimizes 695 // the cost of removal if we end up removing a large number of values, and 696 // second off, this ensures that the indices for the incoming values aren't 697 // invalidated when we remove one. 698 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) { 699 BasicBlock *IncomingBB = PN->getIncomingBlock(i); 700 if (PredSet.count(IncomingBB)) { 701 Value *V = PN->removeIncomingValue(i, false); 702 NewPHI->addIncoming(V, IncomingBB); 703 } 704 } 705 706 PN->addIncoming(NewPHI, NewBB); 707 } 708 } 709 710 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB, 711 ArrayRef<BasicBlock *> Preds, 712 const char *Suffix, DominatorTree *DT, 713 LoopInfo *LI, MemorySSAUpdater *MSSAU, 714 bool PreserveLCSSA) { 715 // Do not attempt to split that which cannot be split. 716 if (!BB->canSplitPredecessors()) 717 return nullptr; 718 719 // For the landingpads we need to act a bit differently. 720 // Delegate this work to the SplitLandingPadPredecessors. 721 if (BB->isLandingPad()) { 722 SmallVector<BasicBlock*, 2> NewBBs; 723 std::string NewName = std::string(Suffix) + ".split-lp"; 724 725 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs, DT, 726 LI, MSSAU, PreserveLCSSA); 727 return NewBBs[0]; 728 } 729 730 // Create new basic block, insert right before the original block. 731 BasicBlock *NewBB = BasicBlock::Create( 732 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB); 733 734 // The new block unconditionally branches to the old block. 735 BranchInst *BI = BranchInst::Create(BB, NewBB); 736 // Splitting the predecessors of a loop header creates a preheader block. 737 if (LI && LI->isLoopHeader(BB)) 738 // Using the loop start line number prevents debuggers stepping into the 739 // loop body for this instruction. 740 BI->setDebugLoc(LI->getLoopFor(BB)->getStartLoc()); 741 else 742 BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc()); 743 744 // Move the edges from Preds to point to NewBB instead of BB. 745 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 746 // This is slightly more strict than necessary; the minimum requirement 747 // is that there be no more than one indirectbr branching to BB. And 748 // all BlockAddress uses would need to be updated. 749 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) && 750 "Cannot split an edge from an IndirectBrInst"); 751 assert(!isa<CallBrInst>(Preds[i]->getTerminator()) && 752 "Cannot split an edge from a CallBrInst"); 753 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB); 754 } 755 756 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI 757 // node becomes an incoming value for BB's phi node. However, if the Preds 758 // list is empty, we need to insert dummy entries into the PHI nodes in BB to 759 // account for the newly created predecessor. 760 if (Preds.empty()) { 761 // Insert dummy values as the incoming value. 762 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) 763 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB); 764 } 765 766 // Update DominatorTree, LoopInfo, and LCCSA analysis information. 767 bool HasLoopExit = false; 768 UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, MSSAU, PreserveLCSSA, 769 HasLoopExit); 770 771 if (!Preds.empty()) { 772 // Update the PHI nodes in BB with the values coming from NewBB. 773 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit); 774 } 775 776 return NewBB; 777 } 778 779 void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB, 780 ArrayRef<BasicBlock *> Preds, 781 const char *Suffix1, const char *Suffix2, 782 SmallVectorImpl<BasicBlock *> &NewBBs, 783 DominatorTree *DT, LoopInfo *LI, 784 MemorySSAUpdater *MSSAU, 785 bool PreserveLCSSA) { 786 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!"); 787 788 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert 789 // it right before the original block. 790 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(), 791 OrigBB->getName() + Suffix1, 792 OrigBB->getParent(), OrigBB); 793 NewBBs.push_back(NewBB1); 794 795 // The new block unconditionally branches to the old block. 796 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1); 797 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc()); 798 799 // Move the edges from Preds to point to NewBB1 instead of OrigBB. 800 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 801 // This is slightly more strict than necessary; the minimum requirement 802 // is that there be no more than one indirectbr branching to BB. And 803 // all BlockAddress uses would need to be updated. 804 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) && 805 "Cannot split an edge from an IndirectBrInst"); 806 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1); 807 } 808 809 bool HasLoopExit = false; 810 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, MSSAU, PreserveLCSSA, 811 HasLoopExit); 812 813 // Update the PHI nodes in OrigBB with the values coming from NewBB1. 814 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit); 815 816 // Move the remaining edges from OrigBB to point to NewBB2. 817 SmallVector<BasicBlock*, 8> NewBB2Preds; 818 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB); 819 i != e; ) { 820 BasicBlock *Pred = *i++; 821 if (Pred == NewBB1) continue; 822 assert(!isa<IndirectBrInst>(Pred->getTerminator()) && 823 "Cannot split an edge from an IndirectBrInst"); 824 NewBB2Preds.push_back(Pred); 825 e = pred_end(OrigBB); 826 } 827 828 BasicBlock *NewBB2 = nullptr; 829 if (!NewBB2Preds.empty()) { 830 // Create another basic block for the rest of OrigBB's predecessors. 831 NewBB2 = BasicBlock::Create(OrigBB->getContext(), 832 OrigBB->getName() + Suffix2, 833 OrigBB->getParent(), OrigBB); 834 NewBBs.push_back(NewBB2); 835 836 // The new block unconditionally branches to the old block. 837 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2); 838 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc()); 839 840 // Move the remaining edges from OrigBB to point to NewBB2. 841 for (BasicBlock *NewBB2Pred : NewBB2Preds) 842 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2); 843 844 // Update DominatorTree, LoopInfo, and LCCSA analysis information. 845 HasLoopExit = false; 846 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI, MSSAU, 847 PreserveLCSSA, HasLoopExit); 848 849 // Update the PHI nodes in OrigBB with the values coming from NewBB2. 850 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit); 851 } 852 853 LandingPadInst *LPad = OrigBB->getLandingPadInst(); 854 Instruction *Clone1 = LPad->clone(); 855 Clone1->setName(Twine("lpad") + Suffix1); 856 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1); 857 858 if (NewBB2) { 859 Instruction *Clone2 = LPad->clone(); 860 Clone2->setName(Twine("lpad") + Suffix2); 861 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2); 862 863 // Create a PHI node for the two cloned landingpad instructions only 864 // if the original landingpad instruction has some uses. 865 if (!LPad->use_empty()) { 866 assert(!LPad->getType()->isTokenTy() && 867 "Split cannot be applied if LPad is token type. Otherwise an " 868 "invalid PHINode of token type would be created."); 869 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad); 870 PN->addIncoming(Clone1, NewBB1); 871 PN->addIncoming(Clone2, NewBB2); 872 LPad->replaceAllUsesWith(PN); 873 } 874 LPad->eraseFromParent(); 875 } else { 876 // There is no second clone. Just replace the landing pad with the first 877 // clone. 878 LPad->replaceAllUsesWith(Clone1); 879 LPad->eraseFromParent(); 880 } 881 } 882 883 ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, 884 BasicBlock *Pred, 885 DomTreeUpdater *DTU) { 886 Instruction *UncondBranch = Pred->getTerminator(); 887 // Clone the return and add it to the end of the predecessor. 888 Instruction *NewRet = RI->clone(); 889 Pred->getInstList().push_back(NewRet); 890 891 // If the return instruction returns a value, and if the value was a 892 // PHI node in "BB", propagate the right value into the return. 893 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end(); 894 i != e; ++i) { 895 Value *V = *i; 896 Instruction *NewBC = nullptr; 897 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) { 898 // Return value might be bitcasted. Clone and insert it before the 899 // return instruction. 900 V = BCI->getOperand(0); 901 NewBC = BCI->clone(); 902 Pred->getInstList().insert(NewRet->getIterator(), NewBC); 903 *i = NewBC; 904 } 905 906 Instruction *NewEV = nullptr; 907 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) { 908 V = EVI->getOperand(0); 909 NewEV = EVI->clone(); 910 if (NewBC) { 911 NewBC->setOperand(0, NewEV); 912 Pred->getInstList().insert(NewBC->getIterator(), NewEV); 913 } else { 914 Pred->getInstList().insert(NewRet->getIterator(), NewEV); 915 *i = NewEV; 916 } 917 } 918 919 if (PHINode *PN = dyn_cast<PHINode>(V)) { 920 if (PN->getParent() == BB) { 921 if (NewEV) { 922 NewEV->setOperand(0, PN->getIncomingValueForBlock(Pred)); 923 } else if (NewBC) 924 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred)); 925 else 926 *i = PN->getIncomingValueForBlock(Pred); 927 } 928 } 929 } 930 931 // Update any PHI nodes in the returning block to realize that we no 932 // longer branch to them. 933 BB->removePredecessor(Pred); 934 UncondBranch->eraseFromParent(); 935 936 if (DTU) 937 DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}}); 938 939 return cast<ReturnInst>(NewRet); 940 } 941 942 Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond, 943 Instruction *SplitBefore, 944 bool Unreachable, 945 MDNode *BranchWeights, 946 DominatorTree *DT, LoopInfo *LI, 947 BasicBlock *ThenBlock) { 948 BasicBlock *Head = SplitBefore->getParent(); 949 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator()); 950 Instruction *HeadOldTerm = Head->getTerminator(); 951 LLVMContext &C = Head->getContext(); 952 Instruction *CheckTerm; 953 bool CreateThenBlock = (ThenBlock == nullptr); 954 if (CreateThenBlock) { 955 ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 956 if (Unreachable) 957 CheckTerm = new UnreachableInst(C, ThenBlock); 958 else 959 CheckTerm = BranchInst::Create(Tail, ThenBlock); 960 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc()); 961 } else 962 CheckTerm = ThenBlock->getTerminator(); 963 BranchInst *HeadNewTerm = 964 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond); 965 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights); 966 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm); 967 968 if (DT) { 969 if (DomTreeNode *OldNode = DT->getNode(Head)) { 970 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end()); 971 972 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head); 973 for (DomTreeNode *Child : Children) 974 DT->changeImmediateDominator(Child, NewNode); 975 976 // Head dominates ThenBlock. 977 if (CreateThenBlock) 978 DT->addNewBlock(ThenBlock, Head); 979 else 980 DT->changeImmediateDominator(ThenBlock, Head); 981 } 982 } 983 984 if (LI) { 985 if (Loop *L = LI->getLoopFor(Head)) { 986 L->addBasicBlockToLoop(ThenBlock, *LI); 987 L->addBasicBlockToLoop(Tail, *LI); 988 } 989 } 990 991 return CheckTerm; 992 } 993 994 void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore, 995 Instruction **ThenTerm, 996 Instruction **ElseTerm, 997 MDNode *BranchWeights) { 998 BasicBlock *Head = SplitBefore->getParent(); 999 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator()); 1000 Instruction *HeadOldTerm = Head->getTerminator(); 1001 LLVMContext &C = Head->getContext(); 1002 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 1003 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail); 1004 *ThenTerm = BranchInst::Create(Tail, ThenBlock); 1005 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc()); 1006 *ElseTerm = BranchInst::Create(Tail, ElseBlock); 1007 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc()); 1008 BranchInst *HeadNewTerm = 1009 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond); 1010 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights); 1011 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm); 1012 } 1013 1014 Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, 1015 BasicBlock *&IfFalse) { 1016 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin()); 1017 BasicBlock *Pred1 = nullptr; 1018 BasicBlock *Pred2 = nullptr; 1019 1020 if (SomePHI) { 1021 if (SomePHI->getNumIncomingValues() != 2) 1022 return nullptr; 1023 Pred1 = SomePHI->getIncomingBlock(0); 1024 Pred2 = SomePHI->getIncomingBlock(1); 1025 } else { 1026 pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 1027 if (PI == PE) // No predecessor 1028 return nullptr; 1029 Pred1 = *PI++; 1030 if (PI == PE) // Only one predecessor 1031 return nullptr; 1032 Pred2 = *PI++; 1033 if (PI != PE) // More than two predecessors 1034 return nullptr; 1035 } 1036 1037 // We can only handle branches. Other control flow will be lowered to 1038 // branches if possible anyway. 1039 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator()); 1040 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator()); 1041 if (!Pred1Br || !Pred2Br) 1042 return nullptr; 1043 1044 // Eliminate code duplication by ensuring that Pred1Br is conditional if 1045 // either are. 1046 if (Pred2Br->isConditional()) { 1047 // If both branches are conditional, we don't have an "if statement". In 1048 // reality, we could transform this case, but since the condition will be 1049 // required anyway, we stand no chance of eliminating it, so the xform is 1050 // probably not profitable. 1051 if (Pred1Br->isConditional()) 1052 return nullptr; 1053 1054 std::swap(Pred1, Pred2); 1055 std::swap(Pred1Br, Pred2Br); 1056 } 1057 1058 if (Pred1Br->isConditional()) { 1059 // The only thing we have to watch out for here is to make sure that Pred2 1060 // doesn't have incoming edges from other blocks. If it does, the condition 1061 // doesn't dominate BB. 1062 if (!Pred2->getSinglePredecessor()) 1063 return nullptr; 1064 1065 // If we found a conditional branch predecessor, make sure that it branches 1066 // to BB and Pred2Br. If it doesn't, this isn't an "if statement". 1067 if (Pred1Br->getSuccessor(0) == BB && 1068 Pred1Br->getSuccessor(1) == Pred2) { 1069 IfTrue = Pred1; 1070 IfFalse = Pred2; 1071 } else if (Pred1Br->getSuccessor(0) == Pred2 && 1072 Pred1Br->getSuccessor(1) == BB) { 1073 IfTrue = Pred2; 1074 IfFalse = Pred1; 1075 } else { 1076 // We know that one arm of the conditional goes to BB, so the other must 1077 // go somewhere unrelated, and this must not be an "if statement". 1078 return nullptr; 1079 } 1080 1081 return Pred1Br->getCondition(); 1082 } 1083 1084 // Ok, if we got here, both predecessors end with an unconditional branch to 1085 // BB. Don't panic! If both blocks only have a single (identical) 1086 // predecessor, and THAT is a conditional branch, then we're all ok! 1087 BasicBlock *CommonPred = Pred1->getSinglePredecessor(); 1088 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor()) 1089 return nullptr; 1090 1091 // Otherwise, if this is a conditional branch, then we can use it! 1092 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator()); 1093 if (!BI) return nullptr; 1094 1095 assert(BI->isConditional() && "Two successors but not conditional?"); 1096 if (BI->getSuccessor(0) == Pred1) { 1097 IfTrue = Pred1; 1098 IfFalse = Pred2; 1099 } else { 1100 IfTrue = Pred2; 1101 IfFalse = Pred1; 1102 } 1103 return BI->getCondition(); 1104 } 1105 1106 // After creating a control flow hub, the operands of PHINodes in an outgoing 1107 // block Out no longer match the predecessors of that block. Predecessors of Out 1108 // that are incoming blocks to the hub are now replaced by just one edge from 1109 // the hub. To match this new control flow, the corresponding values from each 1110 // PHINode must now be moved a new PHINode in the first guard block of the hub. 1111 // 1112 // This operation cannot be performed with SSAUpdater, because it involves one 1113 // new use: If the block Out is in the list of Incoming blocks, then the newly 1114 // created PHI in the Hub will use itself along that edge from Out to Hub. 1115 static void reconnectPhis(BasicBlock *Out, BasicBlock *GuardBlock, 1116 const SetVector<BasicBlock *> &Incoming, 1117 BasicBlock *FirstGuardBlock) { 1118 auto I = Out->begin(); 1119 while (I != Out->end() && isa<PHINode>(I)) { 1120 auto Phi = cast<PHINode>(I); 1121 auto NewPhi = 1122 PHINode::Create(Phi->getType(), Incoming.size(), 1123 Phi->getName() + ".moved", &FirstGuardBlock->back()); 1124 for (auto In : Incoming) { 1125 Value *V = UndefValue::get(Phi->getType()); 1126 if (In == Out) { 1127 V = NewPhi; 1128 } else if (Phi->getBasicBlockIndex(In) != -1) { 1129 V = Phi->removeIncomingValue(In, false); 1130 } 1131 NewPhi->addIncoming(V, In); 1132 } 1133 assert(NewPhi->getNumIncomingValues() == Incoming.size()); 1134 if (Phi->getNumOperands() == 0) { 1135 Phi->replaceAllUsesWith(NewPhi); 1136 I = Phi->eraseFromParent(); 1137 continue; 1138 } 1139 Phi->addIncoming(NewPhi, GuardBlock); 1140 ++I; 1141 } 1142 } 1143 1144 using BBPredicates = DenseMap<BasicBlock *, PHINode *>; 1145 using BBSetVector = SetVector<BasicBlock *>; 1146 1147 // Redirects the terminator of the incoming block to the first guard 1148 // block in the hub. The condition of the original terminator (if it 1149 // was conditional) and its original successors are returned as a 1150 // tuple <condition, succ0, succ1>. The function additionally filters 1151 // out successors that are not in the set of outgoing blocks. 1152 // 1153 // - condition is non-null iff the branch is conditional. 1154 // - Succ1 is non-null iff the sole/taken target is an outgoing block. 1155 // - Succ2 is non-null iff condition is non-null and the fallthrough 1156 // target is an outgoing block. 1157 static std::tuple<Value *, BasicBlock *, BasicBlock *> 1158 redirectToHub(BasicBlock *BB, BasicBlock *FirstGuardBlock, 1159 const BBSetVector &Outgoing) { 1160 auto Branch = cast<BranchInst>(BB->getTerminator()); 1161 auto Condition = Branch->isConditional() ? Branch->getCondition() : nullptr; 1162 1163 BasicBlock *Succ0 = Branch->getSuccessor(0); 1164 BasicBlock *Succ1 = nullptr; 1165 Succ0 = Outgoing.count(Succ0) ? Succ0 : nullptr; 1166 1167 if (Branch->isUnconditional()) { 1168 Branch->setSuccessor(0, FirstGuardBlock); 1169 assert(Succ0); 1170 } else { 1171 Succ1 = Branch->getSuccessor(1); 1172 Succ1 = Outgoing.count(Succ1) ? Succ1 : nullptr; 1173 assert(Succ0 || Succ1); 1174 if (Succ0 && !Succ1) { 1175 Branch->setSuccessor(0, FirstGuardBlock); 1176 } else if (Succ1 && !Succ0) { 1177 Branch->setSuccessor(1, FirstGuardBlock); 1178 } else { 1179 Branch->eraseFromParent(); 1180 BranchInst::Create(FirstGuardBlock, BB); 1181 } 1182 } 1183 1184 assert(Succ0 || Succ1); 1185 return std::make_tuple(Condition, Succ0, Succ1); 1186 } 1187 1188 // Capture the existing control flow as guard predicates, and redirect 1189 // control flow from every incoming block to the first guard block in 1190 // the hub. 1191 // 1192 // There is one guard predicate for each outgoing block OutBB. The 1193 // predicate is a PHINode with one input for each InBB which 1194 // represents whether the hub should transfer control flow to OutBB if 1195 // it arrived from InBB. These predicates are NOT ORTHOGONAL. The Hub 1196 // evaluates them in the same order as the Outgoing set-vector, and 1197 // control branches to the first outgoing block whose predicate 1198 // evaluates to true. 1199 static void convertToGuardPredicates( 1200 BasicBlock *FirstGuardBlock, BBPredicates &GuardPredicates, 1201 SmallVectorImpl<WeakVH> &DeletionCandidates, const BBSetVector &Incoming, 1202 const BBSetVector &Outgoing) { 1203 auto &Context = Incoming.front()->getContext(); 1204 auto BoolTrue = ConstantInt::getTrue(Context); 1205 auto BoolFalse = ConstantInt::getFalse(Context); 1206 1207 // The predicate for the last outgoing is trivially true, and so we 1208 // process only the first N-1 successors. 1209 for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) { 1210 auto Out = Outgoing[i]; 1211 LLVM_DEBUG(dbgs() << "Creating guard for " << Out->getName() << "\n"); 1212 auto Phi = 1213 PHINode::Create(Type::getInt1Ty(Context), Incoming.size(), 1214 StringRef("Guard.") + Out->getName(), FirstGuardBlock); 1215 GuardPredicates[Out] = Phi; 1216 } 1217 1218 for (auto In : Incoming) { 1219 Value *Condition; 1220 BasicBlock *Succ0; 1221 BasicBlock *Succ1; 1222 std::tie(Condition, Succ0, Succ1) = 1223 redirectToHub(In, FirstGuardBlock, Outgoing); 1224 1225 // Optimization: Consider an incoming block A with both successors 1226 // Succ0 and Succ1 in the set of outgoing blocks. The predicates 1227 // for Succ0 and Succ1 complement each other. If Succ0 is visited 1228 // first in the loop below, control will branch to Succ0 using the 1229 // corresponding predicate. But if that branch is not taken, then 1230 // control must reach Succ1, which means that the predicate for 1231 // Succ1 is always true. 1232 bool OneSuccessorDone = false; 1233 for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) { 1234 auto Out = Outgoing[i]; 1235 auto Phi = GuardPredicates[Out]; 1236 if (Out != Succ0 && Out != Succ1) { 1237 Phi->addIncoming(BoolFalse, In); 1238 continue; 1239 } 1240 // Optimization: When only one successor is an outgoing block, 1241 // the predicate is always true. 1242 if (!Succ0 || !Succ1 || OneSuccessorDone) { 1243 Phi->addIncoming(BoolTrue, In); 1244 continue; 1245 } 1246 assert(Succ0 && Succ1); 1247 OneSuccessorDone = true; 1248 if (Out == Succ0) { 1249 Phi->addIncoming(Condition, In); 1250 continue; 1251 } 1252 auto Inverted = invertCondition(Condition); 1253 DeletionCandidates.push_back(Condition); 1254 Phi->addIncoming(Inverted, In); 1255 } 1256 } 1257 } 1258 1259 // For each outgoing block OutBB, create a guard block in the Hub. The 1260 // first guard block was already created outside, and available as the 1261 // first element in the vector of guard blocks. 1262 // 1263 // Each guard block terminates in a conditional branch that transfers 1264 // control to the corresponding outgoing block or the next guard 1265 // block. The last guard block has two outgoing blocks as successors 1266 // since the condition for the final outgoing block is trivially 1267 // true. So we create one less block (including the first guard block) 1268 // than the number of outgoing blocks. 1269 static void createGuardBlocks(SmallVectorImpl<BasicBlock *> &GuardBlocks, 1270 Function *F, const BBSetVector &Outgoing, 1271 BBPredicates &GuardPredicates, StringRef Prefix) { 1272 for (int i = 0, e = Outgoing.size() - 2; i != e; ++i) { 1273 GuardBlocks.push_back( 1274 BasicBlock::Create(F->getContext(), Prefix + ".guard", F)); 1275 } 1276 assert(GuardBlocks.size() == GuardPredicates.size()); 1277 1278 // To help keep the loop simple, temporarily append the last 1279 // outgoing block to the list of guard blocks. 1280 GuardBlocks.push_back(Outgoing.back()); 1281 1282 for (int i = 0, e = GuardBlocks.size() - 1; i != e; ++i) { 1283 auto Out = Outgoing[i]; 1284 assert(GuardPredicates.count(Out)); 1285 BranchInst::Create(Out, GuardBlocks[i + 1], GuardPredicates[Out], 1286 GuardBlocks[i]); 1287 } 1288 1289 // Remove the last block from the guard list. 1290 GuardBlocks.pop_back(); 1291 } 1292 1293 BasicBlock *llvm::CreateControlFlowHub( 1294 DomTreeUpdater *DTU, SmallVectorImpl<BasicBlock *> &GuardBlocks, 1295 const BBSetVector &Incoming, const BBSetVector &Outgoing, 1296 const StringRef Prefix) { 1297 auto F = Incoming.front()->getParent(); 1298 auto FirstGuardBlock = 1299 BasicBlock::Create(F->getContext(), Prefix + ".guard", F); 1300 1301 SmallVector<DominatorTree::UpdateType, 16> Updates; 1302 if (DTU) { 1303 for (auto In : Incoming) { 1304 for (auto Succ : successors(In)) { 1305 if (Outgoing.count(Succ)) 1306 Updates.push_back({DominatorTree::Delete, In, Succ}); 1307 } 1308 Updates.push_back({DominatorTree::Insert, In, FirstGuardBlock}); 1309 } 1310 } 1311 1312 BBPredicates GuardPredicates; 1313 SmallVector<WeakVH, 8> DeletionCandidates; 1314 convertToGuardPredicates(FirstGuardBlock, GuardPredicates, DeletionCandidates, 1315 Incoming, Outgoing); 1316 1317 GuardBlocks.push_back(FirstGuardBlock); 1318 createGuardBlocks(GuardBlocks, F, Outgoing, GuardPredicates, Prefix); 1319 1320 // Update the PHINodes in each outgoing block to match the new control flow. 1321 for (int i = 0, e = GuardBlocks.size(); i != e; ++i) { 1322 reconnectPhis(Outgoing[i], GuardBlocks[i], Incoming, FirstGuardBlock); 1323 } 1324 reconnectPhis(Outgoing.back(), GuardBlocks.back(), Incoming, FirstGuardBlock); 1325 1326 if (DTU) { 1327 int NumGuards = GuardBlocks.size(); 1328 assert((int)Outgoing.size() == NumGuards + 1); 1329 for (int i = 0; i != NumGuards - 1; ++i) { 1330 Updates.push_back({DominatorTree::Insert, GuardBlocks[i], Outgoing[i]}); 1331 Updates.push_back( 1332 {DominatorTree::Insert, GuardBlocks[i], GuardBlocks[i + 1]}); 1333 } 1334 Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1], 1335 Outgoing[NumGuards - 1]}); 1336 Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1], 1337 Outgoing[NumGuards]}); 1338 DTU->applyUpdates(Updates); 1339 } 1340 1341 for (auto I : DeletionCandidates) { 1342 if (I->use_empty()) 1343 if (auto Inst = dyn_cast_or_null<Instruction>(I)) 1344 Inst->eraseFromParent(); 1345 } 1346 1347 return FirstGuardBlock; 1348 } 1349