xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- BasicBlockUtils.cpp - BasicBlock Utilities --------------------------==//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This family of functions perform manipulations on basic blocks, and
100b57cec5SDimitry Andric // instructions contained within basic blocks.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
150b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
160b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
170b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
180b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
190b57cec5SDimitry Andric #include "llvm/Analysis/CFG.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/MemoryDependenceAnalysis.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
240b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
250b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
260b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
27bdd1243dSDimitry Andric #include "llvm/IR/DebugInfo.h"
280b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
290b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
300b57cec5SDimitry Andric #include "llvm/IR/Function.h"
310b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
320b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
330b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
340b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
3506c3fb27SDimitry Andric #include "llvm/IR/IRBuilder.h"
360b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
370b57cec5SDimitry Andric #include "llvm/IR/Type.h"
380b57cec5SDimitry Andric #include "llvm/IR/User.h"
390b57cec5SDimitry Andric #include "llvm/IR/Value.h"
400b57cec5SDimitry Andric #include "llvm/IR/ValueHandle.h"
410b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
42349cc55cSDimitry Andric #include "llvm/Support/CommandLine.h"
430b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
440b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
450b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
460b57cec5SDimitry Andric #include <cassert>
470b57cec5SDimitry Andric #include <cstdint>
480b57cec5SDimitry Andric #include <string>
490b57cec5SDimitry Andric #include <utility>
500b57cec5SDimitry Andric #include <vector>
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric using namespace llvm;
530b57cec5SDimitry Andric 
540b57cec5SDimitry Andric #define DEBUG_TYPE "basicblock-utils"
550b57cec5SDimitry Andric 
56349cc55cSDimitry Andric static cl::opt<unsigned> MaxDeoptOrUnreachableSuccessorCheckDepth(
57349cc55cSDimitry Andric     "max-deopt-or-unreachable-succ-check-depth", cl::init(8), cl::Hidden,
58349cc55cSDimitry Andric     cl::desc("Set the maximum path length when checking whether a basic block "
59349cc55cSDimitry Andric              "is followed by a block that either has a terminating "
60349cc55cSDimitry Andric              "deoptimizing call or is terminated with an unreachable"));
61349cc55cSDimitry Andric 
621fd87a68SDimitry Andric void llvm::detachDeadBlocks(
630b57cec5SDimitry Andric     ArrayRef<BasicBlock *> BBs,
640b57cec5SDimitry Andric     SmallVectorImpl<DominatorTree::UpdateType> *Updates,
650b57cec5SDimitry Andric     bool KeepOneInputPHIs) {
660b57cec5SDimitry Andric   for (auto *BB : BBs) {
670b57cec5SDimitry Andric     // Loop through all of our successors and make sure they know that one
680b57cec5SDimitry Andric     // of their predecessors is going away.
690b57cec5SDimitry Andric     SmallPtrSet<BasicBlock *, 4> UniqueSuccessors;
700b57cec5SDimitry Andric     for (BasicBlock *Succ : successors(BB)) {
710b57cec5SDimitry Andric       Succ->removePredecessor(BB, KeepOneInputPHIs);
720b57cec5SDimitry Andric       if (Updates && UniqueSuccessors.insert(Succ).second)
730b57cec5SDimitry Andric         Updates->push_back({DominatorTree::Delete, BB, Succ});
740b57cec5SDimitry Andric     }
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric     // Zap all the instructions in the block.
770b57cec5SDimitry Andric     while (!BB->empty()) {
780b57cec5SDimitry Andric       Instruction &I = BB->back();
790b57cec5SDimitry Andric       // If this instruction is used, replace uses with an arbitrary value.
800b57cec5SDimitry Andric       // Because control flow can't get here, we don't care what we replace the
810b57cec5SDimitry Andric       // value with.  Note that since this block is unreachable, and all values
820b57cec5SDimitry Andric       // contained within it must dominate their uses, that all uses will
830b57cec5SDimitry Andric       // eventually be removed (they are themselves dead).
840b57cec5SDimitry Andric       if (!I.use_empty())
85fcaf7f86SDimitry Andric         I.replaceAllUsesWith(PoisonValue::get(I.getType()));
86bdd1243dSDimitry Andric       BB->back().eraseFromParent();
870b57cec5SDimitry Andric     }
880b57cec5SDimitry Andric     new UnreachableInst(BB->getContext(), BB);
89bdd1243dSDimitry Andric     assert(BB->size() == 1 &&
900b57cec5SDimitry Andric            isa<UnreachableInst>(BB->getTerminator()) &&
910b57cec5SDimitry Andric            "The successor list of BB isn't empty before "
920b57cec5SDimitry Andric            "applying corresponding DTU updates.");
930b57cec5SDimitry Andric   }
940b57cec5SDimitry Andric }
950b57cec5SDimitry Andric 
960b57cec5SDimitry Andric void llvm::DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU,
970b57cec5SDimitry Andric                            bool KeepOneInputPHIs) {
980b57cec5SDimitry Andric   DeleteDeadBlocks({BB}, DTU, KeepOneInputPHIs);
990b57cec5SDimitry Andric }
1000b57cec5SDimitry Andric 
1010b57cec5SDimitry Andric void llvm::DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs, DomTreeUpdater *DTU,
1020b57cec5SDimitry Andric                             bool KeepOneInputPHIs) {
1030b57cec5SDimitry Andric #ifndef NDEBUG
1040b57cec5SDimitry Andric   // Make sure that all predecessors of each dead block is also dead.
1050b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 4> Dead(BBs.begin(), BBs.end());
1060b57cec5SDimitry Andric   assert(Dead.size() == BBs.size() && "Duplicating blocks?");
1070b57cec5SDimitry Andric   for (auto *BB : Dead)
1080b57cec5SDimitry Andric     for (BasicBlock *Pred : predecessors(BB))
1090b57cec5SDimitry Andric       assert(Dead.count(Pred) && "All predecessors must be dead!");
1100b57cec5SDimitry Andric #endif
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric   SmallVector<DominatorTree::UpdateType, 4> Updates;
1131fd87a68SDimitry Andric   detachDeadBlocks(BBs, DTU ? &Updates : nullptr, KeepOneInputPHIs);
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric   if (DTU)
116e8d8bef9SDimitry Andric     DTU->applyUpdates(Updates);
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric   for (BasicBlock *BB : BBs)
1190b57cec5SDimitry Andric     if (DTU)
1200b57cec5SDimitry Andric       DTU->deleteBB(BB);
1210b57cec5SDimitry Andric     else
1220b57cec5SDimitry Andric       BB->eraseFromParent();
1230b57cec5SDimitry Andric }
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric bool llvm::EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
1260b57cec5SDimitry Andric                                       bool KeepOneInputPHIs) {
1270b57cec5SDimitry Andric   df_iterator_default_set<BasicBlock*> Reachable;
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric   // Mark all reachable blocks.
1300b57cec5SDimitry Andric   for (BasicBlock *BB : depth_first_ext(&F, Reachable))
1310b57cec5SDimitry Andric     (void)BB/* Mark all reachable blocks */;
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   // Collect all dead blocks.
1340b57cec5SDimitry Andric   std::vector<BasicBlock*> DeadBlocks;
135fe6060f1SDimitry Andric   for (BasicBlock &BB : F)
136fe6060f1SDimitry Andric     if (!Reachable.count(&BB))
137fe6060f1SDimitry Andric       DeadBlocks.push_back(&BB);
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric   // Delete the dead blocks.
1400b57cec5SDimitry Andric   DeleteDeadBlocks(DeadBlocks, DTU, KeepOneInputPHIs);
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric   return !DeadBlocks.empty();
1430b57cec5SDimitry Andric }
1440b57cec5SDimitry Andric 
145e8d8bef9SDimitry Andric bool llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
1460b57cec5SDimitry Andric                                    MemoryDependenceResults *MemDep) {
147e8d8bef9SDimitry Andric   if (!isa<PHINode>(BB->begin()))
148e8d8bef9SDimitry Andric     return false;
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1510b57cec5SDimitry Andric     if (PN->getIncomingValue(0) != PN)
1520b57cec5SDimitry Andric       PN->replaceAllUsesWith(PN->getIncomingValue(0));
1530b57cec5SDimitry Andric     else
154bdd1243dSDimitry Andric       PN->replaceAllUsesWith(PoisonValue::get(PN->getType()));
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric     if (MemDep)
1570b57cec5SDimitry Andric       MemDep->removeInstruction(PN);  // Memdep updates AA itself.
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric     PN->eraseFromParent();
1600b57cec5SDimitry Andric   }
161e8d8bef9SDimitry Andric   return true;
1620b57cec5SDimitry Andric }
1630b57cec5SDimitry Andric 
1645ffd83dbSDimitry Andric bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI,
1655ffd83dbSDimitry Andric                           MemorySSAUpdater *MSSAU) {
1660b57cec5SDimitry Andric   // Recursively deleting a PHI may cause multiple PHIs to be deleted
1670b57cec5SDimitry Andric   // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
1680b57cec5SDimitry Andric   SmallVector<WeakTrackingVH, 8> PHIs;
1690b57cec5SDimitry Andric   for (PHINode &PN : BB->phis())
1700b57cec5SDimitry Andric     PHIs.push_back(&PN);
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric   bool Changed = false;
1730b57cec5SDimitry Andric   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
1740b57cec5SDimitry Andric     if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
1755ffd83dbSDimitry Andric       Changed |= RecursivelyDeleteDeadPHINode(PN, TLI, MSSAU);
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric   return Changed;
1780b57cec5SDimitry Andric }
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU,
1810b57cec5SDimitry Andric                                      LoopInfo *LI, MemorySSAUpdater *MSSAU,
1828bcb0991SDimitry Andric                                      MemoryDependenceResults *MemDep,
183bdd1243dSDimitry Andric                                      bool PredecessorWithTwoSuccessors,
184bdd1243dSDimitry Andric                                      DominatorTree *DT) {
1850b57cec5SDimitry Andric   if (BB->hasAddressTaken())
1860b57cec5SDimitry Andric     return false;
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric   // Can't merge if there are multiple predecessors, or no predecessors.
1890b57cec5SDimitry Andric   BasicBlock *PredBB = BB->getUniquePredecessor();
1900b57cec5SDimitry Andric   if (!PredBB) return false;
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   // Don't break self-loops.
1930b57cec5SDimitry Andric   if (PredBB == BB) return false;
194fcaf7f86SDimitry Andric 
195fcaf7f86SDimitry Andric   // Don't break unwinding instructions or terminators with other side-effects.
196fcaf7f86SDimitry Andric   Instruction *PTI = PredBB->getTerminator();
1975f757f3fSDimitry Andric   if (PTI->isSpecialTerminator() || PTI->mayHaveSideEffects())
1980b57cec5SDimitry Andric     return false;
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric   // Can't merge if there are multiple distinct successors.
2018bcb0991SDimitry Andric   if (!PredecessorWithTwoSuccessors && PredBB->getUniqueSuccessor() != BB)
2020b57cec5SDimitry Andric     return false;
2030b57cec5SDimitry Andric 
2048bcb0991SDimitry Andric   // Currently only allow PredBB to have two predecessors, one being BB.
2058bcb0991SDimitry Andric   // Update BI to branch to BB's only successor instead of BB.
2068bcb0991SDimitry Andric   BranchInst *PredBB_BI;
2078bcb0991SDimitry Andric   BasicBlock *NewSucc = nullptr;
2088bcb0991SDimitry Andric   unsigned FallThruPath;
2098bcb0991SDimitry Andric   if (PredecessorWithTwoSuccessors) {
210fcaf7f86SDimitry Andric     if (!(PredBB_BI = dyn_cast<BranchInst>(PTI)))
2118bcb0991SDimitry Andric       return false;
2128bcb0991SDimitry Andric     BranchInst *BB_JmpI = dyn_cast<BranchInst>(BB->getTerminator());
2138bcb0991SDimitry Andric     if (!BB_JmpI || !BB_JmpI->isUnconditional())
2148bcb0991SDimitry Andric       return false;
2158bcb0991SDimitry Andric     NewSucc = BB_JmpI->getSuccessor(0);
2168bcb0991SDimitry Andric     FallThruPath = PredBB_BI->getSuccessor(0) == BB ? 0 : 1;
2178bcb0991SDimitry Andric   }
2188bcb0991SDimitry Andric 
2190b57cec5SDimitry Andric   // Can't merge if there is PHI loop.
2200b57cec5SDimitry Andric   for (PHINode &PN : BB->phis())
221fe6060f1SDimitry Andric     if (llvm::is_contained(PN.incoming_values(), &PN))
2220b57cec5SDimitry Andric       return false;
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Merging: " << BB->getName() << " into "
2250b57cec5SDimitry Andric                     << PredBB->getName() << "\n");
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric   // Begin by getting rid of unneeded PHIs.
2280b57cec5SDimitry Andric   SmallVector<AssertingVH<Value>, 4> IncomingValues;
2290b57cec5SDimitry Andric   if (isa<PHINode>(BB->front())) {
2300b57cec5SDimitry Andric     for (PHINode &PN : BB->phis())
2310b57cec5SDimitry Andric       if (!isa<PHINode>(PN.getIncomingValue(0)) ||
2320b57cec5SDimitry Andric           cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
2330b57cec5SDimitry Andric         IncomingValues.push_back(PN.getIncomingValue(0));
2340b57cec5SDimitry Andric     FoldSingleEntryPHINodes(BB, MemDep);
2350b57cec5SDimitry Andric   }
2360b57cec5SDimitry Andric 
237bdd1243dSDimitry Andric   if (DT) {
238bdd1243dSDimitry Andric     assert(!DTU && "cannot use both DT and DTU for updates");
239bdd1243dSDimitry Andric     DomTreeNode *PredNode = DT->getNode(PredBB);
240bdd1243dSDimitry Andric     DomTreeNode *BBNode = DT->getNode(BB);
241bdd1243dSDimitry Andric     if (PredNode) {
242bdd1243dSDimitry Andric       assert(BBNode && "PredNode unreachable but BBNode reachable?");
243bdd1243dSDimitry Andric       for (DomTreeNode *C : to_vector(BBNode->children()))
244bdd1243dSDimitry Andric         C->setIDom(PredNode);
245bdd1243dSDimitry Andric     }
246bdd1243dSDimitry Andric   }
2470b57cec5SDimitry Andric   // DTU update: Collect all the edges that exit BB.
2480b57cec5SDimitry Andric   // These dominator edges will be redirected from Pred.
2490b57cec5SDimitry Andric   std::vector<DominatorTree::UpdateType> Updates;
2500b57cec5SDimitry Andric   if (DTU) {
251bdd1243dSDimitry Andric     assert(!DT && "cannot use both DT and DTU for updates");
2524824e7fdSDimitry Andric     // To avoid processing the same predecessor more than once.
2534824e7fdSDimitry Andric     SmallPtrSet<BasicBlock *, 8> SeenSuccs;
254fe6060f1SDimitry Andric     SmallPtrSet<BasicBlock *, 2> SuccsOfPredBB(succ_begin(PredBB),
255349cc55cSDimitry Andric                                                succ_end(PredBB));
2564824e7fdSDimitry Andric     Updates.reserve(Updates.size() + 2 * succ_size(BB) + 1);
2570b57cec5SDimitry Andric     // Add insert edges first. Experimentally, for the particular case of two
2580b57cec5SDimitry Andric     // blocks that can be merged, with a single successor and single predecessor
2590b57cec5SDimitry Andric     // respectively, it is beneficial to have all insert updates first. Deleting
2600b57cec5SDimitry Andric     // edges first may lead to unreachable blocks, followed by inserting edges
2610b57cec5SDimitry Andric     // making the blocks reachable again. Such DT updates lead to high compile
2620b57cec5SDimitry Andric     // times. We add inserts before deletes here to reduce compile time.
2634824e7fdSDimitry Andric     for (BasicBlock *SuccOfBB : successors(BB))
264fe6060f1SDimitry Andric       // This successor of BB may already be a PredBB's successor.
265fe6060f1SDimitry Andric       if (!SuccsOfPredBB.contains(SuccOfBB))
2664824e7fdSDimitry Andric         if (SeenSuccs.insert(SuccOfBB).second)
267fe6060f1SDimitry Andric           Updates.push_back({DominatorTree::Insert, PredBB, SuccOfBB});
2684824e7fdSDimitry Andric     SeenSuccs.clear();
2694824e7fdSDimitry Andric     for (BasicBlock *SuccOfBB : successors(BB))
2704824e7fdSDimitry Andric       if (SeenSuccs.insert(SuccOfBB).second)
271fe6060f1SDimitry Andric         Updates.push_back({DominatorTree::Delete, BB, SuccOfBB});
2720b57cec5SDimitry Andric     Updates.push_back({DominatorTree::Delete, PredBB, BB});
2730b57cec5SDimitry Andric   }
2740b57cec5SDimitry Andric 
2758bcb0991SDimitry Andric   Instruction *STI = BB->getTerminator();
2768bcb0991SDimitry Andric   Instruction *Start = &*BB->begin();
2778bcb0991SDimitry Andric   // If there's nothing to move, mark the starting instruction as the last
278480093f4SDimitry Andric   // instruction in the block. Terminator instruction is handled separately.
2798bcb0991SDimitry Andric   if (Start == STI)
2808bcb0991SDimitry Andric     Start = PTI;
2810b57cec5SDimitry Andric 
2828bcb0991SDimitry Andric   // Move all definitions in the successor to the predecessor...
283bdd1243dSDimitry Andric   PredBB->splice(PTI->getIterator(), BB, BB->begin(), STI->getIterator());
2848bcb0991SDimitry Andric 
2858bcb0991SDimitry Andric   if (MSSAU)
2868bcb0991SDimitry Andric     MSSAU->moveAllAfterMergeBlocks(BB, PredBB, Start);
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric   // Make all PHI nodes that referred to BB now refer to Pred as their
2890b57cec5SDimitry Andric   // source...
2900b57cec5SDimitry Andric   BB->replaceAllUsesWith(PredBB);
2910b57cec5SDimitry Andric 
2928bcb0991SDimitry Andric   if (PredecessorWithTwoSuccessors) {
2938bcb0991SDimitry Andric     // Delete the unconditional branch from BB.
294bdd1243dSDimitry Andric     BB->back().eraseFromParent();
2958bcb0991SDimitry Andric 
2968bcb0991SDimitry Andric     // Update branch in the predecessor.
2978bcb0991SDimitry Andric     PredBB_BI->setSuccessor(FallThruPath, NewSucc);
2988bcb0991SDimitry Andric   } else {
2998bcb0991SDimitry Andric     // Delete the unconditional branch from the predecessor.
300bdd1243dSDimitry Andric     PredBB->back().eraseFromParent();
3018bcb0991SDimitry Andric 
3028bcb0991SDimitry Andric     // Move terminator instruction.
3035f757f3fSDimitry Andric     BB->back().moveBeforePreserving(*PredBB, PredBB->end());
304480093f4SDimitry Andric 
305480093f4SDimitry Andric     // Terminator may be a memory accessing instruction too.
306480093f4SDimitry Andric     if (MSSAU)
307480093f4SDimitry Andric       if (MemoryUseOrDef *MUD = cast_or_null<MemoryUseOrDef>(
308480093f4SDimitry Andric               MSSAU->getMemorySSA()->getMemoryAccess(PredBB->getTerminator())))
309480093f4SDimitry Andric         MSSAU->moveToPlace(MUD, PredBB, MemorySSA::End);
3108bcb0991SDimitry Andric   }
3118bcb0991SDimitry Andric   // Add unreachable to now empty BB.
3120b57cec5SDimitry Andric   new UnreachableInst(BB->getContext(), BB);
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric   // Inherit predecessors name if it exists.
3150b57cec5SDimitry Andric   if (!PredBB->hasName())
3160b57cec5SDimitry Andric     PredBB->takeName(BB);
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric   if (LI)
3190b57cec5SDimitry Andric     LI->removeBlock(BB);
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric   if (MemDep)
3220b57cec5SDimitry Andric     MemDep->invalidateCachedPredecessors();
3230b57cec5SDimitry Andric 
324fe6060f1SDimitry Andric   if (DTU)
325e8d8bef9SDimitry Andric     DTU->applyUpdates(Updates);
326fe6060f1SDimitry Andric 
327bdd1243dSDimitry Andric   if (DT) {
328bdd1243dSDimitry Andric     assert(succ_empty(BB) &&
329bdd1243dSDimitry Andric            "successors should have been transferred to PredBB");
330bdd1243dSDimitry Andric     DT->eraseNode(BB);
331bdd1243dSDimitry Andric   }
332bdd1243dSDimitry Andric 
333fe6060f1SDimitry Andric   // Finally, erase the old block and update dominator info.
334fe6060f1SDimitry Andric   DeleteDeadBlock(BB, DTU);
3358bcb0991SDimitry Andric 
3360b57cec5SDimitry Andric   return true;
3370b57cec5SDimitry Andric }
3380b57cec5SDimitry Andric 
3395ffd83dbSDimitry Andric bool llvm::MergeBlockSuccessorsIntoGivenBlocks(
3405ffd83dbSDimitry Andric     SmallPtrSetImpl<BasicBlock *> &MergeBlocks, Loop *L, DomTreeUpdater *DTU,
3415ffd83dbSDimitry Andric     LoopInfo *LI) {
3425ffd83dbSDimitry Andric   assert(!MergeBlocks.empty() && "MergeBlocks should not be empty");
3435ffd83dbSDimitry Andric 
3445ffd83dbSDimitry Andric   bool BlocksHaveBeenMerged = false;
3455ffd83dbSDimitry Andric   while (!MergeBlocks.empty()) {
3465ffd83dbSDimitry Andric     BasicBlock *BB = *MergeBlocks.begin();
3475ffd83dbSDimitry Andric     BasicBlock *Dest = BB->getSingleSuccessor();
3485ffd83dbSDimitry Andric     if (Dest && (!L || L->contains(Dest))) {
3495ffd83dbSDimitry Andric       BasicBlock *Fold = Dest->getUniquePredecessor();
3505ffd83dbSDimitry Andric       (void)Fold;
3515ffd83dbSDimitry Andric       if (MergeBlockIntoPredecessor(Dest, DTU, LI)) {
3525ffd83dbSDimitry Andric         assert(Fold == BB &&
3535ffd83dbSDimitry Andric                "Expecting BB to be unique predecessor of the Dest block");
3545ffd83dbSDimitry Andric         MergeBlocks.erase(Dest);
3555ffd83dbSDimitry Andric         BlocksHaveBeenMerged = true;
3565ffd83dbSDimitry Andric       } else
3575ffd83dbSDimitry Andric         MergeBlocks.erase(BB);
3585ffd83dbSDimitry Andric     } else
3595ffd83dbSDimitry Andric       MergeBlocks.erase(BB);
3605ffd83dbSDimitry Andric   }
3615ffd83dbSDimitry Andric   return BlocksHaveBeenMerged;
3625ffd83dbSDimitry Andric }
3635ffd83dbSDimitry Andric 
364480093f4SDimitry Andric /// Remove redundant instructions within sequences of consecutive dbg.value
365480093f4SDimitry Andric /// instructions. This is done using a backward scan to keep the last dbg.value
366480093f4SDimitry Andric /// describing a specific variable/fragment.
367480093f4SDimitry Andric ///
368480093f4SDimitry Andric /// BackwardScan strategy:
369480093f4SDimitry Andric /// ----------------------
370480093f4SDimitry Andric /// Given a sequence of consecutive DbgValueInst like this
371480093f4SDimitry Andric ///
372480093f4SDimitry Andric ///   dbg.value ..., "x", FragmentX1  (*)
373480093f4SDimitry Andric ///   dbg.value ..., "y", FragmentY1
374480093f4SDimitry Andric ///   dbg.value ..., "x", FragmentX2
375480093f4SDimitry Andric ///   dbg.value ..., "x", FragmentX1  (**)
376480093f4SDimitry Andric ///
377480093f4SDimitry Andric /// then the instruction marked with (*) can be removed (it is guaranteed to be
378480093f4SDimitry Andric /// obsoleted by the instruction marked with (**) as the latter instruction is
379480093f4SDimitry Andric /// describing the same variable using the same fragment info).
380480093f4SDimitry Andric ///
381480093f4SDimitry Andric /// Possible improvements:
382480093f4SDimitry Andric /// - Check fully overlapping fragments and not only identical fragments.
38306c3fb27SDimitry Andric /// - Support dbg.declare. dbg.label, and possibly other meta instructions being
38406c3fb27SDimitry Andric ///   part of the sequence of consecutive instructions.
385*0fca6ea1SDimitry Andric static bool
386*0fca6ea1SDimitry Andric DbgVariableRecordsRemoveRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB) {
387*0fca6ea1SDimitry Andric   SmallVector<DbgVariableRecord *, 8> ToBeRemoved;
3885f757f3fSDimitry Andric   SmallDenseSet<DebugVariable> VariableSet;
3895f757f3fSDimitry Andric   for (auto &I : reverse(*BB)) {
390*0fca6ea1SDimitry Andric     for (DbgRecord &DR : reverse(I.getDbgRecordRange())) {
391*0fca6ea1SDimitry Andric       if (isa<DbgLabelRecord>(DR)) {
392*0fca6ea1SDimitry Andric         // Emulate existing behaviour (see comment below for dbg.declares).
393*0fca6ea1SDimitry Andric         // FIXME: Don't do this.
394*0fca6ea1SDimitry Andric         VariableSet.clear();
395*0fca6ea1SDimitry Andric         continue;
396*0fca6ea1SDimitry Andric       }
397*0fca6ea1SDimitry Andric 
398*0fca6ea1SDimitry Andric       DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
3995f757f3fSDimitry Andric       // Skip declare-type records, as the debug intrinsic method only works
4005f757f3fSDimitry Andric       // on dbg.value intrinsics.
401*0fca6ea1SDimitry Andric       if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
4025f757f3fSDimitry Andric         // The debug intrinsic method treats dbg.declares are "non-debug"
4035f757f3fSDimitry Andric         // instructions (i.e., a break in a consecutive range of debug
4045f757f3fSDimitry Andric         // intrinsics). Emulate that to create identical outputs. See
4055f757f3fSDimitry Andric         // "Possible improvements" above.
4065f757f3fSDimitry Andric         // FIXME: Delete the line below.
4075f757f3fSDimitry Andric         VariableSet.clear();
4085f757f3fSDimitry Andric         continue;
4095f757f3fSDimitry Andric       }
4105f757f3fSDimitry Andric 
411*0fca6ea1SDimitry Andric       DebugVariable Key(DVR.getVariable(), DVR.getExpression(),
412*0fca6ea1SDimitry Andric                         DVR.getDebugLoc()->getInlinedAt());
4135f757f3fSDimitry Andric       auto R = VariableSet.insert(Key);
4145f757f3fSDimitry Andric       // If the same variable fragment is described more than once it is enough
4155f757f3fSDimitry Andric       // to keep the last one (i.e. the first found since we for reverse
4165f757f3fSDimitry Andric       // iteration).
4177a6dacacSDimitry Andric       if (R.second)
4187a6dacacSDimitry Andric         continue;
4197a6dacacSDimitry Andric 
420*0fca6ea1SDimitry Andric       if (DVR.isDbgAssign()) {
4217a6dacacSDimitry Andric         // Don't delete dbg.assign intrinsics that are linked to instructions.
422*0fca6ea1SDimitry Andric         if (!at::getAssignmentInsts(&DVR).empty())
4237a6dacacSDimitry Andric           continue;
4247a6dacacSDimitry Andric         // Unlinked dbg.assign intrinsics can be treated like dbg.values.
4257a6dacacSDimitry Andric       }
4267a6dacacSDimitry Andric 
427*0fca6ea1SDimitry Andric       ToBeRemoved.push_back(&DVR);
4285f757f3fSDimitry Andric       continue;
4295f757f3fSDimitry Andric     }
4305f757f3fSDimitry Andric     // Sequence with consecutive dbg.value instrs ended. Clear the map to
4315f757f3fSDimitry Andric     // restart identifying redundant instructions if case we find another
4325f757f3fSDimitry Andric     // dbg.value sequence.
4335f757f3fSDimitry Andric     VariableSet.clear();
4345f757f3fSDimitry Andric   }
4355f757f3fSDimitry Andric 
436*0fca6ea1SDimitry Andric   for (auto &DVR : ToBeRemoved)
437*0fca6ea1SDimitry Andric     DVR->eraseFromParent();
4385f757f3fSDimitry Andric 
4395f757f3fSDimitry Andric   return !ToBeRemoved.empty();
4405f757f3fSDimitry Andric }
4415f757f3fSDimitry Andric 
442480093f4SDimitry Andric static bool removeRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB) {
4435f757f3fSDimitry Andric   if (BB->IsNewDbgInfoFormat)
444*0fca6ea1SDimitry Andric     return DbgVariableRecordsRemoveRedundantDbgInstrsUsingBackwardScan(BB);
4455f757f3fSDimitry Andric 
446480093f4SDimitry Andric   SmallVector<DbgValueInst *, 8> ToBeRemoved;
447480093f4SDimitry Andric   SmallDenseSet<DebugVariable> VariableSet;
448480093f4SDimitry Andric   for (auto &I : reverse(*BB)) {
449480093f4SDimitry Andric     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) {
450480093f4SDimitry Andric       DebugVariable Key(DVI->getVariable(),
451480093f4SDimitry Andric                         DVI->getExpression(),
452480093f4SDimitry Andric                         DVI->getDebugLoc()->getInlinedAt());
453480093f4SDimitry Andric       auto R = VariableSet.insert(Key);
454bdd1243dSDimitry Andric       // If the variable fragment hasn't been seen before then we don't want
455bdd1243dSDimitry Andric       // to remove this dbg intrinsic.
456bdd1243dSDimitry Andric       if (R.second)
457bdd1243dSDimitry Andric         continue;
458bdd1243dSDimitry Andric 
459bdd1243dSDimitry Andric       if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI)) {
460bdd1243dSDimitry Andric         // Don't delete dbg.assign intrinsics that are linked to instructions.
461bdd1243dSDimitry Andric         if (!at::getAssignmentInsts(DAI).empty())
462bdd1243dSDimitry Andric           continue;
463bdd1243dSDimitry Andric         // Unlinked dbg.assign intrinsics can be treated like dbg.values.
464bdd1243dSDimitry Andric       }
465bdd1243dSDimitry Andric 
466480093f4SDimitry Andric       // If the same variable fragment is described more than once it is enough
467480093f4SDimitry Andric       // to keep the last one (i.e. the first found since we for reverse
468480093f4SDimitry Andric       // iteration).
469480093f4SDimitry Andric       ToBeRemoved.push_back(DVI);
470480093f4SDimitry Andric       continue;
471480093f4SDimitry Andric     }
472480093f4SDimitry Andric     // Sequence with consecutive dbg.value instrs ended. Clear the map to
473480093f4SDimitry Andric     // restart identifying redundant instructions if case we find another
474480093f4SDimitry Andric     // dbg.value sequence.
475480093f4SDimitry Andric     VariableSet.clear();
476480093f4SDimitry Andric   }
477480093f4SDimitry Andric 
478480093f4SDimitry Andric   for (auto &Instr : ToBeRemoved)
479480093f4SDimitry Andric     Instr->eraseFromParent();
480480093f4SDimitry Andric 
481480093f4SDimitry Andric   return !ToBeRemoved.empty();
482480093f4SDimitry Andric }
483480093f4SDimitry Andric 
484480093f4SDimitry Andric /// Remove redundant dbg.value instructions using a forward scan. This can
485480093f4SDimitry Andric /// remove a dbg.value instruction that is redundant due to indicating that a
486480093f4SDimitry Andric /// variable has the same value as already being indicated by an earlier
487480093f4SDimitry Andric /// dbg.value.
488480093f4SDimitry Andric ///
489480093f4SDimitry Andric /// ForwardScan strategy:
490480093f4SDimitry Andric /// ---------------------
491480093f4SDimitry Andric /// Given two identical dbg.value instructions, separated by a block of
492480093f4SDimitry Andric /// instructions that isn't describing the same variable, like this
493480093f4SDimitry Andric ///
494480093f4SDimitry Andric ///   dbg.value X1, "x", FragmentX1  (**)
495480093f4SDimitry Andric ///   <block of instructions, none being "dbg.value ..., "x", ...">
496480093f4SDimitry Andric ///   dbg.value X1, "x", FragmentX1  (*)
497480093f4SDimitry Andric ///
498480093f4SDimitry Andric /// then the instruction marked with (*) can be removed. Variable "x" is already
499480093f4SDimitry Andric /// described as being mapped to the SSA value X1.
500480093f4SDimitry Andric ///
501480093f4SDimitry Andric /// Possible improvements:
502480093f4SDimitry Andric /// - Keep track of non-overlapping fragments.
503*0fca6ea1SDimitry Andric static bool
504*0fca6ea1SDimitry Andric DbgVariableRecordsRemoveRedundantDbgInstrsUsingForwardScan(BasicBlock *BB) {
505*0fca6ea1SDimitry Andric   SmallVector<DbgVariableRecord *, 8> ToBeRemoved;
5065f757f3fSDimitry Andric   DenseMap<DebugVariable, std::pair<SmallVector<Value *, 4>, DIExpression *>>
5075f757f3fSDimitry Andric       VariableMap;
5085f757f3fSDimitry Andric   for (auto &I : *BB) {
509*0fca6ea1SDimitry Andric     for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
510*0fca6ea1SDimitry Andric       if (DVR.getType() == DbgVariableRecord::LocationType::Declare)
5115f757f3fSDimitry Andric         continue;
512*0fca6ea1SDimitry Andric       DebugVariable Key(DVR.getVariable(), std::nullopt,
513*0fca6ea1SDimitry Andric                         DVR.getDebugLoc()->getInlinedAt());
5145f757f3fSDimitry Andric       auto VMI = VariableMap.find(Key);
5157a6dacacSDimitry Andric       // A dbg.assign with no linked instructions can be treated like a
5167a6dacacSDimitry Andric       // dbg.value (i.e. can be deleted).
5177a6dacacSDimitry Andric       bool IsDbgValueKind =
518*0fca6ea1SDimitry Andric           (!DVR.isDbgAssign() || at::getAssignmentInsts(&DVR).empty());
5197a6dacacSDimitry Andric 
5205f757f3fSDimitry Andric       // Update the map if we found a new value/expression describing the
5215f757f3fSDimitry Andric       // variable, or if the variable wasn't mapped already.
522*0fca6ea1SDimitry Andric       SmallVector<Value *, 4> Values(DVR.location_ops());
5235f757f3fSDimitry Andric       if (VMI == VariableMap.end() || VMI->second.first != Values ||
524*0fca6ea1SDimitry Andric           VMI->second.second != DVR.getExpression()) {
5257a6dacacSDimitry Andric         if (IsDbgValueKind)
526*0fca6ea1SDimitry Andric           VariableMap[Key] = {Values, DVR.getExpression()};
5277a6dacacSDimitry Andric         else
5287a6dacacSDimitry Andric           VariableMap[Key] = {Values, nullptr};
5295f757f3fSDimitry Andric         continue;
5305f757f3fSDimitry Andric       }
5317a6dacacSDimitry Andric       // Don't delete dbg.assign intrinsics that are linked to instructions.
5327a6dacacSDimitry Andric       if (!IsDbgValueKind)
5337a6dacacSDimitry Andric         continue;
5345f757f3fSDimitry Andric       // Found an identical mapping. Remember the instruction for later removal.
535*0fca6ea1SDimitry Andric       ToBeRemoved.push_back(&DVR);
5365f757f3fSDimitry Andric     }
5375f757f3fSDimitry Andric   }
5385f757f3fSDimitry Andric 
539*0fca6ea1SDimitry Andric   for (auto *DVR : ToBeRemoved)
540*0fca6ea1SDimitry Andric     DVR->eraseFromParent();
5415f757f3fSDimitry Andric 
5425f757f3fSDimitry Andric   return !ToBeRemoved.empty();
5435f757f3fSDimitry Andric }
5445f757f3fSDimitry Andric 
545*0fca6ea1SDimitry Andric static bool
546*0fca6ea1SDimitry Andric DbgVariableRecordsRemoveUndefDbgAssignsFromEntryBlock(BasicBlock *BB) {
5477a6dacacSDimitry Andric   assert(BB->isEntryBlock() && "expected entry block");
548*0fca6ea1SDimitry Andric   SmallVector<DbgVariableRecord *, 8> ToBeRemoved;
5497a6dacacSDimitry Andric   DenseSet<DebugVariable> SeenDefForAggregate;
5507a6dacacSDimitry Andric   // Returns the DebugVariable for DVI with no fragment info.
551*0fca6ea1SDimitry Andric   auto GetAggregateVariable = [](const DbgVariableRecord &DVR) {
552*0fca6ea1SDimitry Andric     return DebugVariable(DVR.getVariable(), std::nullopt,
553*0fca6ea1SDimitry Andric                          DVR.getDebugLoc().getInlinedAt());
5547a6dacacSDimitry Andric   };
5557a6dacacSDimitry Andric 
5567a6dacacSDimitry Andric   // Remove undef dbg.assign intrinsics that are encountered before
5577a6dacacSDimitry Andric   // any non-undef intrinsics from the entry block.
5587a6dacacSDimitry Andric   for (auto &I : *BB) {
559*0fca6ea1SDimitry Andric     for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
560*0fca6ea1SDimitry Andric       if (!DVR.isDbgValue() && !DVR.isDbgAssign())
5617a6dacacSDimitry Andric         continue;
5627a6dacacSDimitry Andric       bool IsDbgValueKind =
563*0fca6ea1SDimitry Andric           (DVR.isDbgValue() || at::getAssignmentInsts(&DVR).empty());
564*0fca6ea1SDimitry Andric       DebugVariable Aggregate = GetAggregateVariable(DVR);
5657a6dacacSDimitry Andric       if (!SeenDefForAggregate.contains(Aggregate)) {
566*0fca6ea1SDimitry Andric         bool IsKill = DVR.isKillLocation() && IsDbgValueKind;
5677a6dacacSDimitry Andric         if (!IsKill) {
5687a6dacacSDimitry Andric           SeenDefForAggregate.insert(Aggregate);
569*0fca6ea1SDimitry Andric         } else if (DVR.isDbgAssign()) {
570*0fca6ea1SDimitry Andric           ToBeRemoved.push_back(&DVR);
5717a6dacacSDimitry Andric         }
5727a6dacacSDimitry Andric       }
5737a6dacacSDimitry Andric     }
5747a6dacacSDimitry Andric   }
5757a6dacacSDimitry Andric 
576*0fca6ea1SDimitry Andric   for (DbgVariableRecord *DVR : ToBeRemoved)
577*0fca6ea1SDimitry Andric     DVR->eraseFromParent();
5787a6dacacSDimitry Andric 
5797a6dacacSDimitry Andric   return !ToBeRemoved.empty();
5807a6dacacSDimitry Andric }
5817a6dacacSDimitry Andric 
582480093f4SDimitry Andric static bool removeRedundantDbgInstrsUsingForwardScan(BasicBlock *BB) {
5835f757f3fSDimitry Andric   if (BB->IsNewDbgInfoFormat)
584*0fca6ea1SDimitry Andric     return DbgVariableRecordsRemoveRedundantDbgInstrsUsingForwardScan(BB);
5855f757f3fSDimitry Andric 
586480093f4SDimitry Andric   SmallVector<DbgValueInst *, 8> ToBeRemoved;
587fe6060f1SDimitry Andric   DenseMap<DebugVariable, std::pair<SmallVector<Value *, 4>, DIExpression *>>
588fe6060f1SDimitry Andric       VariableMap;
589480093f4SDimitry Andric   for (auto &I : *BB) {
590480093f4SDimitry Andric     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) {
591bdd1243dSDimitry Andric       DebugVariable Key(DVI->getVariable(), std::nullopt,
592480093f4SDimitry Andric                         DVI->getDebugLoc()->getInlinedAt());
593480093f4SDimitry Andric       auto VMI = VariableMap.find(Key);
594bdd1243dSDimitry Andric       auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI);
595bdd1243dSDimitry Andric       // A dbg.assign with no linked instructions can be treated like a
596bdd1243dSDimitry Andric       // dbg.value (i.e. can be deleted).
597bdd1243dSDimitry Andric       bool IsDbgValueKind = (!DAI || at::getAssignmentInsts(DAI).empty());
598bdd1243dSDimitry Andric 
599480093f4SDimitry Andric       // Update the map if we found a new value/expression describing the
600480093f4SDimitry Andric       // variable, or if the variable wasn't mapped already.
601fe6060f1SDimitry Andric       SmallVector<Value *, 4> Values(DVI->getValues());
602fe6060f1SDimitry Andric       if (VMI == VariableMap.end() || VMI->second.first != Values ||
603480093f4SDimitry Andric           VMI->second.second != DVI->getExpression()) {
6047a6dacacSDimitry Andric         // Use a sentinel value (nullptr) for the DIExpression when we see a
605bdd1243dSDimitry Andric         // linked dbg.assign so that the next debug intrinsic will never match
606bdd1243dSDimitry Andric         // it (i.e. always treat linked dbg.assigns as if they're unique).
607bdd1243dSDimitry Andric         if (IsDbgValueKind)
608fe6060f1SDimitry Andric           VariableMap[Key] = {Values, DVI->getExpression()};
609bdd1243dSDimitry Andric         else
610bdd1243dSDimitry Andric           VariableMap[Key] = {Values, nullptr};
611480093f4SDimitry Andric         continue;
612480093f4SDimitry Andric       }
613bdd1243dSDimitry Andric 
614bdd1243dSDimitry Andric       // Don't delete dbg.assign intrinsics that are linked to instructions.
615bdd1243dSDimitry Andric       if (!IsDbgValueKind)
616bdd1243dSDimitry Andric         continue;
617480093f4SDimitry Andric       ToBeRemoved.push_back(DVI);
618480093f4SDimitry Andric     }
619480093f4SDimitry Andric   }
620480093f4SDimitry Andric 
621480093f4SDimitry Andric   for (auto &Instr : ToBeRemoved)
622480093f4SDimitry Andric     Instr->eraseFromParent();
623480093f4SDimitry Andric 
624480093f4SDimitry Andric   return !ToBeRemoved.empty();
625480093f4SDimitry Andric }
626480093f4SDimitry Andric 
627bdd1243dSDimitry Andric /// Remove redundant undef dbg.assign intrinsic from an entry block using a
628bdd1243dSDimitry Andric /// forward scan.
629bdd1243dSDimitry Andric /// Strategy:
630bdd1243dSDimitry Andric /// ---------------------
631bdd1243dSDimitry Andric /// Scanning forward, delete dbg.assign intrinsics iff they are undef, not
632bdd1243dSDimitry Andric /// linked to an intrinsic, and don't share an aggregate variable with a debug
633bdd1243dSDimitry Andric /// intrinsic that didn't meet the criteria. In other words, undef dbg.assigns
634bdd1243dSDimitry Andric /// that come before non-undef debug intrinsics for the variable are
635bdd1243dSDimitry Andric /// deleted. Given:
636bdd1243dSDimitry Andric ///
637bdd1243dSDimitry Andric ///   dbg.assign undef, "x", FragmentX1 (*)
638bdd1243dSDimitry Andric ///   <block of instructions, none being "dbg.value ..., "x", ...">
639bdd1243dSDimitry Andric ///   dbg.value %V, "x", FragmentX2
640bdd1243dSDimitry Andric ///   <block of instructions, none being "dbg.value ..., "x", ...">
641bdd1243dSDimitry Andric ///   dbg.assign undef, "x", FragmentX1
642bdd1243dSDimitry Andric ///
643bdd1243dSDimitry Andric /// then (only) the instruction marked with (*) can be removed.
644bdd1243dSDimitry Andric /// Possible improvements:
645bdd1243dSDimitry Andric /// - Keep track of non-overlapping fragments.
6467a6dacacSDimitry Andric static bool removeUndefDbgAssignsFromEntryBlock(BasicBlock *BB) {
6477a6dacacSDimitry Andric   if (BB->IsNewDbgInfoFormat)
648*0fca6ea1SDimitry Andric     return DbgVariableRecordsRemoveUndefDbgAssignsFromEntryBlock(BB);
6497a6dacacSDimitry Andric 
650bdd1243dSDimitry Andric   assert(BB->isEntryBlock() && "expected entry block");
651bdd1243dSDimitry Andric   SmallVector<DbgAssignIntrinsic *, 8> ToBeRemoved;
652bdd1243dSDimitry Andric   DenseSet<DebugVariable> SeenDefForAggregate;
653bdd1243dSDimitry Andric   // Returns the DebugVariable for DVI with no fragment info.
654bdd1243dSDimitry Andric   auto GetAggregateVariable = [](DbgValueInst *DVI) {
655bdd1243dSDimitry Andric     return DebugVariable(DVI->getVariable(), std::nullopt,
656bdd1243dSDimitry Andric                          DVI->getDebugLoc()->getInlinedAt());
657bdd1243dSDimitry Andric   };
658bdd1243dSDimitry Andric 
659bdd1243dSDimitry Andric   // Remove undef dbg.assign intrinsics that are encountered before
660bdd1243dSDimitry Andric   // any non-undef intrinsics from the entry block.
661bdd1243dSDimitry Andric   for (auto &I : *BB) {
662bdd1243dSDimitry Andric     DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I);
663bdd1243dSDimitry Andric     if (!DVI)
664bdd1243dSDimitry Andric       continue;
665bdd1243dSDimitry Andric     auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI);
666bdd1243dSDimitry Andric     bool IsDbgValueKind = (!DAI || at::getAssignmentInsts(DAI).empty());
667bdd1243dSDimitry Andric     DebugVariable Aggregate = GetAggregateVariable(DVI);
668bdd1243dSDimitry Andric     if (!SeenDefForAggregate.contains(Aggregate)) {
669bdd1243dSDimitry Andric       bool IsKill = DVI->isKillLocation() && IsDbgValueKind;
670bdd1243dSDimitry Andric       if (!IsKill) {
671bdd1243dSDimitry Andric         SeenDefForAggregate.insert(Aggregate);
672bdd1243dSDimitry Andric       } else if (DAI) {
673bdd1243dSDimitry Andric         ToBeRemoved.push_back(DAI);
674bdd1243dSDimitry Andric       }
675bdd1243dSDimitry Andric     }
676bdd1243dSDimitry Andric   }
677bdd1243dSDimitry Andric 
678bdd1243dSDimitry Andric   for (DbgAssignIntrinsic *DAI : ToBeRemoved)
679bdd1243dSDimitry Andric     DAI->eraseFromParent();
680bdd1243dSDimitry Andric 
681bdd1243dSDimitry Andric   return !ToBeRemoved.empty();
682bdd1243dSDimitry Andric }
683bdd1243dSDimitry Andric 
684480093f4SDimitry Andric bool llvm::RemoveRedundantDbgInstrs(BasicBlock *BB) {
685480093f4SDimitry Andric   bool MadeChanges = false;
686480093f4SDimitry Andric   // By using the "backward scan" strategy before the "forward scan" strategy we
687480093f4SDimitry Andric   // can remove both dbg.value (2) and (3) in a situation like this:
688480093f4SDimitry Andric   //
689480093f4SDimitry Andric   //   (1) dbg.value V1, "x", DIExpression()
690480093f4SDimitry Andric   //       ...
691480093f4SDimitry Andric   //   (2) dbg.value V2, "x", DIExpression()
692480093f4SDimitry Andric   //   (3) dbg.value V1, "x", DIExpression()
693480093f4SDimitry Andric   //
694480093f4SDimitry Andric   // The backward scan will remove (2), it is made obsolete by (3). After
695480093f4SDimitry Andric   // getting (2) out of the way, the foward scan will remove (3) since "x"
696480093f4SDimitry Andric   // already is described as having the value V1 at (1).
697480093f4SDimitry Andric   MadeChanges |= removeRedundantDbgInstrsUsingBackwardScan(BB);
698bdd1243dSDimitry Andric   if (BB->isEntryBlock() &&
699bdd1243dSDimitry Andric       isAssignmentTrackingEnabled(*BB->getParent()->getParent()))
7007a6dacacSDimitry Andric     MadeChanges |= removeUndefDbgAssignsFromEntryBlock(BB);
701480093f4SDimitry Andric   MadeChanges |= removeRedundantDbgInstrsUsingForwardScan(BB);
702480093f4SDimitry Andric 
703480093f4SDimitry Andric   if (MadeChanges)
704480093f4SDimitry Andric     LLVM_DEBUG(dbgs() << "Removed redundant dbg instrs from: "
705480093f4SDimitry Andric                       << BB->getName() << "\n");
706480093f4SDimitry Andric   return MadeChanges;
707480093f4SDimitry Andric }
708480093f4SDimitry Andric 
709bdd1243dSDimitry Andric void llvm::ReplaceInstWithValue(BasicBlock::iterator &BI, Value *V) {
7100b57cec5SDimitry Andric   Instruction &I = *BI;
7110b57cec5SDimitry Andric   // Replaces all of the uses of the instruction with uses of the value
7120b57cec5SDimitry Andric   I.replaceAllUsesWith(V);
7130b57cec5SDimitry Andric 
7140b57cec5SDimitry Andric   // Make sure to propagate a name if there is one already.
7150b57cec5SDimitry Andric   if (I.hasName() && !V->hasName())
7160b57cec5SDimitry Andric     V->takeName(&I);
7170b57cec5SDimitry Andric 
7180b57cec5SDimitry Andric   // Delete the unnecessary instruction now...
719bdd1243dSDimitry Andric   BI = BI->eraseFromParent();
7200b57cec5SDimitry Andric }
7210b57cec5SDimitry Andric 
722bdd1243dSDimitry Andric void llvm::ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI,
723bdd1243dSDimitry Andric                                Instruction *I) {
7240b57cec5SDimitry Andric   assert(I->getParent() == nullptr &&
7250b57cec5SDimitry Andric          "ReplaceInstWithInst: Instruction already inserted into basic block!");
7260b57cec5SDimitry Andric 
7270b57cec5SDimitry Andric   // Copy debug location to newly added instruction, if it wasn't already set
7280b57cec5SDimitry Andric   // by the caller.
7290b57cec5SDimitry Andric   if (!I->getDebugLoc())
7300b57cec5SDimitry Andric     I->setDebugLoc(BI->getDebugLoc());
7310b57cec5SDimitry Andric 
7320b57cec5SDimitry Andric   // Insert the new instruction into the basic block...
733bdd1243dSDimitry Andric   BasicBlock::iterator New = I->insertInto(BB, BI);
7340b57cec5SDimitry Andric 
7350b57cec5SDimitry Andric   // Replace all uses of the old instruction, and delete it.
736bdd1243dSDimitry Andric   ReplaceInstWithValue(BI, I);
7370b57cec5SDimitry Andric 
7380b57cec5SDimitry Andric   // Move BI back to point to the newly inserted instruction
7390b57cec5SDimitry Andric   BI = New;
7400b57cec5SDimitry Andric }
7410b57cec5SDimitry Andric 
742349cc55cSDimitry Andric bool llvm::IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB) {
743349cc55cSDimitry Andric   // Remember visited blocks to avoid infinite loop
744349cc55cSDimitry Andric   SmallPtrSet<const BasicBlock *, 8> VisitedBlocks;
745349cc55cSDimitry Andric   unsigned Depth = 0;
746349cc55cSDimitry Andric   while (BB && Depth++ < MaxDeoptOrUnreachableSuccessorCheckDepth &&
747349cc55cSDimitry Andric          VisitedBlocks.insert(BB).second) {
74806c3fb27SDimitry Andric     if (isa<UnreachableInst>(BB->getTerminator()) ||
74906c3fb27SDimitry Andric         BB->getTerminatingDeoptimizeCall())
750349cc55cSDimitry Andric       return true;
751349cc55cSDimitry Andric     BB = BB->getUniqueSuccessor();
752349cc55cSDimitry Andric   }
753349cc55cSDimitry Andric   return false;
754349cc55cSDimitry Andric }
755349cc55cSDimitry Andric 
7560b57cec5SDimitry Andric void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
7570b57cec5SDimitry Andric   BasicBlock::iterator BI(From);
758bdd1243dSDimitry Andric   ReplaceInstWithInst(From->getParent(), BI, To);
7590b57cec5SDimitry Andric }
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
762e8d8bef9SDimitry Andric                             LoopInfo *LI, MemorySSAUpdater *MSSAU,
763e8d8bef9SDimitry Andric                             const Twine &BBName) {
7640b57cec5SDimitry Andric   unsigned SuccNum = GetSuccessorNumber(BB, Succ);
7650b57cec5SDimitry Andric 
7660b57cec5SDimitry Andric   Instruction *LatchTerm = BB->getTerminator();
767fe6060f1SDimitry Andric 
768fe6060f1SDimitry Andric   CriticalEdgeSplittingOptions Options =
769fe6060f1SDimitry Andric       CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA();
770fe6060f1SDimitry Andric 
771fe6060f1SDimitry Andric   if ((isCriticalEdge(LatchTerm, SuccNum, Options.MergeIdenticalEdges))) {
772fe6060f1SDimitry Andric     // If it is a critical edge, and the succesor is an exception block, handle
773fe6060f1SDimitry Andric     // the split edge logic in this specific function
774fe6060f1SDimitry Andric     if (Succ->isEHPad())
775fe6060f1SDimitry Andric       return ehAwareSplitEdge(BB, Succ, nullptr, nullptr, Options, BBName);
776fe6060f1SDimitry Andric 
777fe6060f1SDimitry Andric     // If this is a critical edge, let SplitKnownCriticalEdge do it.
778fe6060f1SDimitry Andric     return SplitKnownCriticalEdge(LatchTerm, SuccNum, Options, BBName);
779fe6060f1SDimitry Andric   }
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric   // If the edge isn't critical, then BB has a single successor or Succ has a
7820b57cec5SDimitry Andric   // single pred.  Split the block.
7830b57cec5SDimitry Andric   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
7840b57cec5SDimitry Andric     // If the successor only has a single pred, split the top of the successor
7850b57cec5SDimitry Andric     // block.
7860b57cec5SDimitry Andric     assert(SP == BB && "CFG broken");
787*0fca6ea1SDimitry Andric     (void)SP;
788e8d8bef9SDimitry Andric     return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU, BBName,
789e8d8bef9SDimitry Andric                       /*Before=*/true);
7900b57cec5SDimitry Andric   }
7910b57cec5SDimitry Andric 
7920b57cec5SDimitry Andric   // Otherwise, if BB has a single successor, split it at the bottom of the
7930b57cec5SDimitry Andric   // block.
7940b57cec5SDimitry Andric   assert(BB->getTerminator()->getNumSuccessors() == 1 &&
7950b57cec5SDimitry Andric          "Should have a single succ!");
796e8d8bef9SDimitry Andric   return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU, BBName);
7970b57cec5SDimitry Andric }
7980b57cec5SDimitry Andric 
799fe6060f1SDimitry Andric void llvm::setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ) {
800fe6060f1SDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(TI))
801fe6060f1SDimitry Andric     II->setUnwindDest(Succ);
802fe6060f1SDimitry Andric   else if (auto *CS = dyn_cast<CatchSwitchInst>(TI))
803fe6060f1SDimitry Andric     CS->setUnwindDest(Succ);
804fe6060f1SDimitry Andric   else if (auto *CR = dyn_cast<CleanupReturnInst>(TI))
805fe6060f1SDimitry Andric     CR->setUnwindDest(Succ);
806fe6060f1SDimitry Andric   else
807fe6060f1SDimitry Andric     llvm_unreachable("unexpected terminator instruction");
808fe6060f1SDimitry Andric }
809fe6060f1SDimitry Andric 
810fe6060f1SDimitry Andric void llvm::updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred,
811fe6060f1SDimitry Andric                           BasicBlock *NewPred, PHINode *Until) {
812fe6060f1SDimitry Andric   int BBIdx = 0;
813fe6060f1SDimitry Andric   for (PHINode &PN : DestBB->phis()) {
814fe6060f1SDimitry Andric     // We manually update the LandingPadReplacement PHINode and it is the last
815fe6060f1SDimitry Andric     // PHI Node. So, if we find it, we are done.
816fe6060f1SDimitry Andric     if (Until == &PN)
817fe6060f1SDimitry Andric       break;
818fe6060f1SDimitry Andric 
819fe6060f1SDimitry Andric     // Reuse the previous value of BBIdx if it lines up.  In cases where we
820fe6060f1SDimitry Andric     // have multiple phi nodes with *lots* of predecessors, this is a speed
821fe6060f1SDimitry Andric     // win because we don't have to scan the PHI looking for TIBB.  This
822fe6060f1SDimitry Andric     // happens because the BB list of PHI nodes are usually in the same
823fe6060f1SDimitry Andric     // order.
824fe6060f1SDimitry Andric     if (PN.getIncomingBlock(BBIdx) != OldPred)
825fe6060f1SDimitry Andric       BBIdx = PN.getBasicBlockIndex(OldPred);
826fe6060f1SDimitry Andric 
827fe6060f1SDimitry Andric     assert(BBIdx != -1 && "Invalid PHI Index!");
828fe6060f1SDimitry Andric     PN.setIncomingBlock(BBIdx, NewPred);
829fe6060f1SDimitry Andric   }
830fe6060f1SDimitry Andric }
831fe6060f1SDimitry Andric 
832fe6060f1SDimitry Andric BasicBlock *llvm::ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
833fe6060f1SDimitry Andric                                    LandingPadInst *OriginalPad,
834fe6060f1SDimitry Andric                                    PHINode *LandingPadReplacement,
835fe6060f1SDimitry Andric                                    const CriticalEdgeSplittingOptions &Options,
836fe6060f1SDimitry Andric                                    const Twine &BBName) {
837fe6060f1SDimitry Andric 
838fe6060f1SDimitry Andric   auto *PadInst = Succ->getFirstNonPHI();
839fe6060f1SDimitry Andric   if (!LandingPadReplacement && !PadInst->isEHPad())
840fe6060f1SDimitry Andric     return SplitEdge(BB, Succ, Options.DT, Options.LI, Options.MSSAU, BBName);
841fe6060f1SDimitry Andric 
842fe6060f1SDimitry Andric   auto *LI = Options.LI;
843fe6060f1SDimitry Andric   SmallVector<BasicBlock *, 4> LoopPreds;
844fe6060f1SDimitry Andric   // Check if extra modifications will be required to preserve loop-simplify
845fe6060f1SDimitry Andric   // form after splitting. If it would require splitting blocks with IndirectBr
846fe6060f1SDimitry Andric   // terminators, bail out if preserving loop-simplify form is requested.
847fe6060f1SDimitry Andric   if (Options.PreserveLoopSimplify && LI) {
848fe6060f1SDimitry Andric     if (Loop *BBLoop = LI->getLoopFor(BB)) {
849fe6060f1SDimitry Andric 
850fe6060f1SDimitry Andric       // The only way that we can break LoopSimplify form by splitting a
851fe6060f1SDimitry Andric       // critical edge is when there exists some edge from BBLoop to Succ *and*
852fe6060f1SDimitry Andric       // the only edge into Succ from outside of BBLoop is that of NewBB after
853fe6060f1SDimitry Andric       // the split. If the first isn't true, then LoopSimplify still holds,
854fe6060f1SDimitry Andric       // NewBB is the new exit block and it has no non-loop predecessors. If the
855fe6060f1SDimitry Andric       // second isn't true, then Succ was not in LoopSimplify form prior to
856fe6060f1SDimitry Andric       // the split as it had a non-loop predecessor. In both of these cases,
857fe6060f1SDimitry Andric       // the predecessor must be directly in BBLoop, not in a subloop, or again
858fe6060f1SDimitry Andric       // LoopSimplify doesn't hold.
859fe6060f1SDimitry Andric       for (BasicBlock *P : predecessors(Succ)) {
860fe6060f1SDimitry Andric         if (P == BB)
861fe6060f1SDimitry Andric           continue; // The new block is known.
862fe6060f1SDimitry Andric         if (LI->getLoopFor(P) != BBLoop) {
863fe6060f1SDimitry Andric           // Loop is not in LoopSimplify form, no need to re simplify after
864fe6060f1SDimitry Andric           // splitting edge.
865fe6060f1SDimitry Andric           LoopPreds.clear();
866fe6060f1SDimitry Andric           break;
867fe6060f1SDimitry Andric         }
868fe6060f1SDimitry Andric         LoopPreds.push_back(P);
869fe6060f1SDimitry Andric       }
870fe6060f1SDimitry Andric       // Loop-simplify form can be preserved, if we can split all in-loop
871fe6060f1SDimitry Andric       // predecessors.
872fe6060f1SDimitry Andric       if (any_of(LoopPreds, [](BasicBlock *Pred) {
873fe6060f1SDimitry Andric             return isa<IndirectBrInst>(Pred->getTerminator());
874fe6060f1SDimitry Andric           })) {
875fe6060f1SDimitry Andric         return nullptr;
876fe6060f1SDimitry Andric       }
877fe6060f1SDimitry Andric     }
878fe6060f1SDimitry Andric   }
879fe6060f1SDimitry Andric 
880fe6060f1SDimitry Andric   auto *NewBB =
881fe6060f1SDimitry Andric       BasicBlock::Create(BB->getContext(), BBName, BB->getParent(), Succ);
882fe6060f1SDimitry Andric   setUnwindEdgeTo(BB->getTerminator(), NewBB);
883fe6060f1SDimitry Andric   updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement);
884fe6060f1SDimitry Andric 
885fe6060f1SDimitry Andric   if (LandingPadReplacement) {
886fe6060f1SDimitry Andric     auto *NewLP = OriginalPad->clone();
887fe6060f1SDimitry Andric     auto *Terminator = BranchInst::Create(Succ, NewBB);
888fe6060f1SDimitry Andric     NewLP->insertBefore(Terminator);
889fe6060f1SDimitry Andric     LandingPadReplacement->addIncoming(NewLP, NewBB);
890fe6060f1SDimitry Andric   } else {
891fe6060f1SDimitry Andric     Value *ParentPad = nullptr;
892fe6060f1SDimitry Andric     if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
893fe6060f1SDimitry Andric       ParentPad = FuncletPad->getParentPad();
894fe6060f1SDimitry Andric     else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
895fe6060f1SDimitry Andric       ParentPad = CatchSwitch->getParentPad();
896fe6060f1SDimitry Andric     else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(PadInst))
897fe6060f1SDimitry Andric       ParentPad = CleanupPad->getParentPad();
898fe6060f1SDimitry Andric     else if (auto *LandingPad = dyn_cast<LandingPadInst>(PadInst))
899fe6060f1SDimitry Andric       ParentPad = LandingPad->getParent();
900fe6060f1SDimitry Andric     else
901fe6060f1SDimitry Andric       llvm_unreachable("handling for other EHPads not implemented yet");
902fe6060f1SDimitry Andric 
903fe6060f1SDimitry Andric     auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, BBName, NewBB);
904fe6060f1SDimitry Andric     CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB);
905fe6060f1SDimitry Andric   }
906fe6060f1SDimitry Andric 
907fe6060f1SDimitry Andric   auto *DT = Options.DT;
908fe6060f1SDimitry Andric   auto *MSSAU = Options.MSSAU;
909fe6060f1SDimitry Andric   if (!DT && !LI)
910fe6060f1SDimitry Andric     return NewBB;
911fe6060f1SDimitry Andric 
912fe6060f1SDimitry Andric   if (DT) {
913fe6060f1SDimitry Andric     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
914fe6060f1SDimitry Andric     SmallVector<DominatorTree::UpdateType, 3> Updates;
915fe6060f1SDimitry Andric 
916fe6060f1SDimitry Andric     Updates.push_back({DominatorTree::Insert, BB, NewBB});
917fe6060f1SDimitry Andric     Updates.push_back({DominatorTree::Insert, NewBB, Succ});
918fe6060f1SDimitry Andric     Updates.push_back({DominatorTree::Delete, BB, Succ});
919fe6060f1SDimitry Andric 
920fe6060f1SDimitry Andric     DTU.applyUpdates(Updates);
921fe6060f1SDimitry Andric     DTU.flush();
922fe6060f1SDimitry Andric 
923fe6060f1SDimitry Andric     if (MSSAU) {
924fe6060f1SDimitry Andric       MSSAU->applyUpdates(Updates, *DT);
925fe6060f1SDimitry Andric       if (VerifyMemorySSA)
926fe6060f1SDimitry Andric         MSSAU->getMemorySSA()->verifyMemorySSA();
927fe6060f1SDimitry Andric     }
928fe6060f1SDimitry Andric   }
929fe6060f1SDimitry Andric 
930fe6060f1SDimitry Andric   if (LI) {
931fe6060f1SDimitry Andric     if (Loop *BBLoop = LI->getLoopFor(BB)) {
932fe6060f1SDimitry Andric       // If one or the other blocks were not in a loop, the new block is not
933fe6060f1SDimitry Andric       // either, and thus LI doesn't need to be updated.
934fe6060f1SDimitry Andric       if (Loop *SuccLoop = LI->getLoopFor(Succ)) {
935fe6060f1SDimitry Andric         if (BBLoop == SuccLoop) {
936fe6060f1SDimitry Andric           // Both in the same loop, the NewBB joins loop.
937fe6060f1SDimitry Andric           SuccLoop->addBasicBlockToLoop(NewBB, *LI);
938fe6060f1SDimitry Andric         } else if (BBLoop->contains(SuccLoop)) {
939fe6060f1SDimitry Andric           // Edge from an outer loop to an inner loop.  Add to the outer loop.
940fe6060f1SDimitry Andric           BBLoop->addBasicBlockToLoop(NewBB, *LI);
941fe6060f1SDimitry Andric         } else if (SuccLoop->contains(BBLoop)) {
942fe6060f1SDimitry Andric           // Edge from an inner loop to an outer loop.  Add to the outer loop.
943fe6060f1SDimitry Andric           SuccLoop->addBasicBlockToLoop(NewBB, *LI);
944fe6060f1SDimitry Andric         } else {
945fe6060f1SDimitry Andric           // Edge from two loops with no containment relation.  Because these
946fe6060f1SDimitry Andric           // are natural loops, we know that the destination block must be the
947fe6060f1SDimitry Andric           // header of its loop (adding a branch into a loop elsewhere would
948fe6060f1SDimitry Andric           // create an irreducible loop).
949fe6060f1SDimitry Andric           assert(SuccLoop->getHeader() == Succ &&
950fe6060f1SDimitry Andric                  "Should not create irreducible loops!");
951fe6060f1SDimitry Andric           if (Loop *P = SuccLoop->getParentLoop())
952fe6060f1SDimitry Andric             P->addBasicBlockToLoop(NewBB, *LI);
953fe6060f1SDimitry Andric         }
954fe6060f1SDimitry Andric       }
955fe6060f1SDimitry Andric 
956fe6060f1SDimitry Andric       // If BB is in a loop and Succ is outside of that loop, we may need to
957fe6060f1SDimitry Andric       // update LoopSimplify form and LCSSA form.
958fe6060f1SDimitry Andric       if (!BBLoop->contains(Succ)) {
959fe6060f1SDimitry Andric         assert(!BBLoop->contains(NewBB) &&
960fe6060f1SDimitry Andric                "Split point for loop exit is contained in loop!");
961fe6060f1SDimitry Andric 
962fe6060f1SDimitry Andric         // Update LCSSA form in the newly created exit block.
963fe6060f1SDimitry Andric         if (Options.PreserveLCSSA) {
964fe6060f1SDimitry Andric           createPHIsForSplitLoopExit(BB, NewBB, Succ);
965fe6060f1SDimitry Andric         }
966fe6060f1SDimitry Andric 
967fe6060f1SDimitry Andric         if (!LoopPreds.empty()) {
968fe6060f1SDimitry Andric           BasicBlock *NewExitBB = SplitBlockPredecessors(
969fe6060f1SDimitry Andric               Succ, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
970fe6060f1SDimitry Andric           if (Options.PreserveLCSSA)
971fe6060f1SDimitry Andric             createPHIsForSplitLoopExit(LoopPreds, NewExitBB, Succ);
972fe6060f1SDimitry Andric         }
973fe6060f1SDimitry Andric       }
974fe6060f1SDimitry Andric     }
975fe6060f1SDimitry Andric   }
976fe6060f1SDimitry Andric 
977fe6060f1SDimitry Andric   return NewBB;
978fe6060f1SDimitry Andric }
979fe6060f1SDimitry Andric 
980fe6060f1SDimitry Andric void llvm::createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
981fe6060f1SDimitry Andric                                       BasicBlock *SplitBB, BasicBlock *DestBB) {
982fe6060f1SDimitry Andric   // SplitBB shouldn't have anything non-trivial in it yet.
983fe6060f1SDimitry Andric   assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
984fe6060f1SDimitry Andric           SplitBB->isLandingPad()) &&
985fe6060f1SDimitry Andric          "SplitBB has non-PHI nodes!");
986fe6060f1SDimitry Andric 
987fe6060f1SDimitry Andric   // For each PHI in the destination block.
988fe6060f1SDimitry Andric   for (PHINode &PN : DestBB->phis()) {
989fe6060f1SDimitry Andric     int Idx = PN.getBasicBlockIndex(SplitBB);
990fe6060f1SDimitry Andric     assert(Idx >= 0 && "Invalid Block Index");
991fe6060f1SDimitry Andric     Value *V = PN.getIncomingValue(Idx);
992fe6060f1SDimitry Andric 
993fe6060f1SDimitry Andric     // If the input is a PHI which already satisfies LCSSA, don't create
994fe6060f1SDimitry Andric     // a new one.
995fe6060f1SDimitry Andric     if (const PHINode *VP = dyn_cast<PHINode>(V))
996fe6060f1SDimitry Andric       if (VP->getParent() == SplitBB)
997fe6060f1SDimitry Andric         continue;
998fe6060f1SDimitry Andric 
999fe6060f1SDimitry Andric     // Otherwise a new PHI is needed. Create one and populate it.
10005f757f3fSDimitry Andric     PHINode *NewPN = PHINode::Create(PN.getType(), Preds.size(), "split");
10015f757f3fSDimitry Andric     BasicBlock::iterator InsertPos =
10025f757f3fSDimitry Andric         SplitBB->isLandingPad() ? SplitBB->begin()
10035f757f3fSDimitry Andric                                 : SplitBB->getTerminator()->getIterator();
10045f757f3fSDimitry Andric     NewPN->insertBefore(InsertPos);
1005fe6060f1SDimitry Andric     for (BasicBlock *BB : Preds)
1006fe6060f1SDimitry Andric       NewPN->addIncoming(V, BB);
1007fe6060f1SDimitry Andric 
1008fe6060f1SDimitry Andric     // Update the original PHI.
1009fe6060f1SDimitry Andric     PN.setIncomingValue(Idx, NewPN);
1010fe6060f1SDimitry Andric   }
1011fe6060f1SDimitry Andric }
1012fe6060f1SDimitry Andric 
10130b57cec5SDimitry Andric unsigned
10140b57cec5SDimitry Andric llvm::SplitAllCriticalEdges(Function &F,
10150b57cec5SDimitry Andric                             const CriticalEdgeSplittingOptions &Options) {
10160b57cec5SDimitry Andric   unsigned NumBroken = 0;
10170b57cec5SDimitry Andric   for (BasicBlock &BB : F) {
10180b57cec5SDimitry Andric     Instruction *TI = BB.getTerminator();
1019753f127fSDimitry Andric     if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
10200b57cec5SDimitry Andric       for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10210b57cec5SDimitry Andric         if (SplitCriticalEdge(TI, i, Options))
10220b57cec5SDimitry Andric           ++NumBroken;
10230b57cec5SDimitry Andric   }
10240b57cec5SDimitry Andric   return NumBroken;
10250b57cec5SDimitry Andric }
10260b57cec5SDimitry Andric 
10275f757f3fSDimitry Andric static BasicBlock *SplitBlockImpl(BasicBlock *Old, BasicBlock::iterator SplitPt,
1028e8d8bef9SDimitry Andric                                   DomTreeUpdater *DTU, DominatorTree *DT,
1029e8d8bef9SDimitry Andric                                   LoopInfo *LI, MemorySSAUpdater *MSSAU,
1030e8d8bef9SDimitry Andric                                   const Twine &BBName, bool Before) {
1031e8d8bef9SDimitry Andric   if (Before) {
1032e8d8bef9SDimitry Andric     DomTreeUpdater LocalDTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1033e8d8bef9SDimitry Andric     return splitBlockBefore(Old, SplitPt,
1034e8d8bef9SDimitry Andric                             DTU ? DTU : (DT ? &LocalDTU : nullptr), LI, MSSAU,
1035e8d8bef9SDimitry Andric                             BBName);
1036e8d8bef9SDimitry Andric   }
10375f757f3fSDimitry Andric   BasicBlock::iterator SplitIt = SplitPt;
1038fe6060f1SDimitry Andric   while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) {
10390b57cec5SDimitry Andric     ++SplitIt;
1040fe6060f1SDimitry Andric     assert(SplitIt != SplitPt->getParent()->end());
1041fe6060f1SDimitry Andric   }
10428bcb0991SDimitry Andric   std::string Name = BBName.str();
10438bcb0991SDimitry Andric   BasicBlock *New = Old->splitBasicBlock(
10448bcb0991SDimitry Andric       SplitIt, Name.empty() ? Old->getName() + ".split" : Name);
10450b57cec5SDimitry Andric 
10460b57cec5SDimitry Andric   // The new block lives in whichever loop the old one did. This preserves
10470b57cec5SDimitry Andric   // LCSSA as well, because we force the split point to be after any PHI nodes.
10480b57cec5SDimitry Andric   if (LI)
10490b57cec5SDimitry Andric     if (Loop *L = LI->getLoopFor(Old))
10500b57cec5SDimitry Andric       L->addBasicBlockToLoop(New, *LI);
10510b57cec5SDimitry Andric 
1052e8d8bef9SDimitry Andric   if (DTU) {
1053e8d8bef9SDimitry Andric     SmallVector<DominatorTree::UpdateType, 8> Updates;
1054e8d8bef9SDimitry Andric     // Old dominates New. New node dominates all other nodes dominated by Old.
10554824e7fdSDimitry Andric     SmallPtrSet<BasicBlock *, 8> UniqueSuccessorsOfOld;
1056e8d8bef9SDimitry Andric     Updates.push_back({DominatorTree::Insert, Old, New});
10574824e7fdSDimitry Andric     Updates.reserve(Updates.size() + 2 * succ_size(New));
10584824e7fdSDimitry Andric     for (BasicBlock *SuccessorOfOld : successors(New))
10594824e7fdSDimitry Andric       if (UniqueSuccessorsOfOld.insert(SuccessorOfOld).second) {
10604824e7fdSDimitry Andric         Updates.push_back({DominatorTree::Insert, New, SuccessorOfOld});
10614824e7fdSDimitry Andric         Updates.push_back({DominatorTree::Delete, Old, SuccessorOfOld});
1062e8d8bef9SDimitry Andric       }
1063e8d8bef9SDimitry Andric 
1064e8d8bef9SDimitry Andric     DTU->applyUpdates(Updates);
1065e8d8bef9SDimitry Andric   } else if (DT)
10660b57cec5SDimitry Andric     // Old dominates New. New node dominates all other nodes dominated by Old.
10670b57cec5SDimitry Andric     if (DomTreeNode *OldNode = DT->getNode(Old)) {
10680b57cec5SDimitry Andric       std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
10690b57cec5SDimitry Andric 
10700b57cec5SDimitry Andric       DomTreeNode *NewNode = DT->addNewBlock(New, Old);
10710b57cec5SDimitry Andric       for (DomTreeNode *I : Children)
10720b57cec5SDimitry Andric         DT->changeImmediateDominator(I, NewNode);
10730b57cec5SDimitry Andric     }
10740b57cec5SDimitry Andric 
10750b57cec5SDimitry Andric   // Move MemoryAccesses still tracked in Old, but part of New now.
10760b57cec5SDimitry Andric   // Update accesses in successor blocks accordingly.
10770b57cec5SDimitry Andric   if (MSSAU)
10780b57cec5SDimitry Andric     MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
10790b57cec5SDimitry Andric 
10800b57cec5SDimitry Andric   return New;
10810b57cec5SDimitry Andric }
10820b57cec5SDimitry Andric 
10835f757f3fSDimitry Andric BasicBlock *llvm::SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt,
1084e8d8bef9SDimitry Andric                              DominatorTree *DT, LoopInfo *LI,
1085e8d8bef9SDimitry Andric                              MemorySSAUpdater *MSSAU, const Twine &BBName,
1086e8d8bef9SDimitry Andric                              bool Before) {
1087e8d8bef9SDimitry Andric   return SplitBlockImpl(Old, SplitPt, /*DTU=*/nullptr, DT, LI, MSSAU, BBName,
1088e8d8bef9SDimitry Andric                         Before);
1089e8d8bef9SDimitry Andric }
10905f757f3fSDimitry Andric BasicBlock *llvm::SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt,
1091e8d8bef9SDimitry Andric                              DomTreeUpdater *DTU, LoopInfo *LI,
1092e8d8bef9SDimitry Andric                              MemorySSAUpdater *MSSAU, const Twine &BBName,
1093e8d8bef9SDimitry Andric                              bool Before) {
1094e8d8bef9SDimitry Andric   return SplitBlockImpl(Old, SplitPt, DTU, /*DT=*/nullptr, LI, MSSAU, BBName,
1095e8d8bef9SDimitry Andric                         Before);
1096e8d8bef9SDimitry Andric }
1097e8d8bef9SDimitry Andric 
10985f757f3fSDimitry Andric BasicBlock *llvm::splitBlockBefore(BasicBlock *Old, BasicBlock::iterator SplitPt,
1099e8d8bef9SDimitry Andric                                    DomTreeUpdater *DTU, LoopInfo *LI,
1100e8d8bef9SDimitry Andric                                    MemorySSAUpdater *MSSAU,
1101e8d8bef9SDimitry Andric                                    const Twine &BBName) {
1102e8d8bef9SDimitry Andric 
11035f757f3fSDimitry Andric   BasicBlock::iterator SplitIt = SplitPt;
1104e8d8bef9SDimitry Andric   while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
1105e8d8bef9SDimitry Andric     ++SplitIt;
1106e8d8bef9SDimitry Andric   std::string Name = BBName.str();
1107e8d8bef9SDimitry Andric   BasicBlock *New = Old->splitBasicBlock(
1108e8d8bef9SDimitry Andric       SplitIt, Name.empty() ? Old->getName() + ".split" : Name,
1109e8d8bef9SDimitry Andric       /* Before=*/true);
1110e8d8bef9SDimitry Andric 
1111e8d8bef9SDimitry Andric   // The new block lives in whichever loop the old one did. This preserves
1112e8d8bef9SDimitry Andric   // LCSSA as well, because we force the split point to be after any PHI nodes.
1113e8d8bef9SDimitry Andric   if (LI)
1114e8d8bef9SDimitry Andric     if (Loop *L = LI->getLoopFor(Old))
1115e8d8bef9SDimitry Andric       L->addBasicBlockToLoop(New, *LI);
1116e8d8bef9SDimitry Andric 
1117e8d8bef9SDimitry Andric   if (DTU) {
1118e8d8bef9SDimitry Andric     SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
1119e8d8bef9SDimitry Andric     // New dominates Old. The predecessor nodes of the Old node dominate
1120e8d8bef9SDimitry Andric     // New node.
11214824e7fdSDimitry Andric     SmallPtrSet<BasicBlock *, 8> UniquePredecessorsOfOld;
1122e8d8bef9SDimitry Andric     DTUpdates.push_back({DominatorTree::Insert, New, Old});
11234824e7fdSDimitry Andric     DTUpdates.reserve(DTUpdates.size() + 2 * pred_size(New));
11244824e7fdSDimitry Andric     for (BasicBlock *PredecessorOfOld : predecessors(New))
11254824e7fdSDimitry Andric       if (UniquePredecessorsOfOld.insert(PredecessorOfOld).second) {
11264824e7fdSDimitry Andric         DTUpdates.push_back({DominatorTree::Insert, PredecessorOfOld, New});
11274824e7fdSDimitry Andric         DTUpdates.push_back({DominatorTree::Delete, PredecessorOfOld, Old});
1128e8d8bef9SDimitry Andric       }
1129e8d8bef9SDimitry Andric 
1130e8d8bef9SDimitry Andric     DTU->applyUpdates(DTUpdates);
1131e8d8bef9SDimitry Andric 
1132e8d8bef9SDimitry Andric     // Move MemoryAccesses still tracked in Old, but part of New now.
1133e8d8bef9SDimitry Andric     // Update accesses in successor blocks accordingly.
1134e8d8bef9SDimitry Andric     if (MSSAU) {
1135e8d8bef9SDimitry Andric       MSSAU->applyUpdates(DTUpdates, DTU->getDomTree());
1136e8d8bef9SDimitry Andric       if (VerifyMemorySSA)
1137e8d8bef9SDimitry Andric         MSSAU->getMemorySSA()->verifyMemorySSA();
1138e8d8bef9SDimitry Andric     }
1139e8d8bef9SDimitry Andric   }
1140e8d8bef9SDimitry Andric   return New;
1141e8d8bef9SDimitry Andric }
1142e8d8bef9SDimitry Andric 
11430b57cec5SDimitry Andric /// Update DominatorTree, LoopInfo, and LCCSA analysis information.
1144*0fca6ea1SDimitry Andric /// Invalidates DFS Numbering when DTU or DT is provided.
11450b57cec5SDimitry Andric static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
11460b57cec5SDimitry Andric                                       ArrayRef<BasicBlock *> Preds,
1147e8d8bef9SDimitry Andric                                       DomTreeUpdater *DTU, DominatorTree *DT,
1148e8d8bef9SDimitry Andric                                       LoopInfo *LI, MemorySSAUpdater *MSSAU,
11490b57cec5SDimitry Andric                                       bool PreserveLCSSA, bool &HasLoopExit) {
11500b57cec5SDimitry Andric   // Update dominator tree if available.
1151e8d8bef9SDimitry Andric   if (DTU) {
1152e8d8bef9SDimitry Andric     // Recalculation of DomTree is needed when updating a forward DomTree and
1153e8d8bef9SDimitry Andric     // the Entry BB is replaced.
1154fe6060f1SDimitry Andric     if (NewBB->isEntryBlock() && DTU->hasDomTree()) {
1155e8d8bef9SDimitry Andric       // The entry block was removed and there is no external interface for
1156e8d8bef9SDimitry Andric       // the dominator tree to be notified of this change. In this corner-case
1157e8d8bef9SDimitry Andric       // we recalculate the entire tree.
1158e8d8bef9SDimitry Andric       DTU->recalculate(*NewBB->getParent());
1159e8d8bef9SDimitry Andric     } else {
1160e8d8bef9SDimitry Andric       // Split block expects NewBB to have a non-empty set of predecessors.
1161e8d8bef9SDimitry Andric       SmallVector<DominatorTree::UpdateType, 8> Updates;
11624824e7fdSDimitry Andric       SmallPtrSet<BasicBlock *, 8> UniquePreds;
1163e8d8bef9SDimitry Andric       Updates.push_back({DominatorTree::Insert, NewBB, OldBB});
11644824e7fdSDimitry Andric       Updates.reserve(Updates.size() + 2 * Preds.size());
11654824e7fdSDimitry Andric       for (auto *Pred : Preds)
11664824e7fdSDimitry Andric         if (UniquePreds.insert(Pred).second) {
11674824e7fdSDimitry Andric           Updates.push_back({DominatorTree::Insert, Pred, NewBB});
11684824e7fdSDimitry Andric           Updates.push_back({DominatorTree::Delete, Pred, OldBB});
1169e8d8bef9SDimitry Andric         }
1170e8d8bef9SDimitry Andric       DTU->applyUpdates(Updates);
1171e8d8bef9SDimitry Andric     }
1172e8d8bef9SDimitry Andric   } else if (DT) {
11730b57cec5SDimitry Andric     if (OldBB == DT->getRootNode()->getBlock()) {
1174fe6060f1SDimitry Andric       assert(NewBB->isEntryBlock());
11750b57cec5SDimitry Andric       DT->setNewRoot(NewBB);
11760b57cec5SDimitry Andric     } else {
11770b57cec5SDimitry Andric       // Split block expects NewBB to have a non-empty set of predecessors.
11780b57cec5SDimitry Andric       DT->splitBlock(NewBB);
11790b57cec5SDimitry Andric     }
11800b57cec5SDimitry Andric   }
11810b57cec5SDimitry Andric 
11820b57cec5SDimitry Andric   // Update MemoryPhis after split if MemorySSA is available
11830b57cec5SDimitry Andric   if (MSSAU)
11840b57cec5SDimitry Andric     MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
11850b57cec5SDimitry Andric 
11860b57cec5SDimitry Andric   // The rest of the logic is only relevant for updating the loop structures.
11870b57cec5SDimitry Andric   if (!LI)
11880b57cec5SDimitry Andric     return;
11890b57cec5SDimitry Andric 
1190e8d8bef9SDimitry Andric   if (DTU && DTU->hasDomTree())
1191e8d8bef9SDimitry Andric     DT = &DTU->getDomTree();
11920b57cec5SDimitry Andric   assert(DT && "DT should be available to update LoopInfo!");
11930b57cec5SDimitry Andric   Loop *L = LI->getLoopFor(OldBB);
11940b57cec5SDimitry Andric 
11950b57cec5SDimitry Andric   // If we need to preserve loop analyses, collect some information about how
11960b57cec5SDimitry Andric   // this split will affect loops.
11970b57cec5SDimitry Andric   bool IsLoopEntry = !!L;
11980b57cec5SDimitry Andric   bool SplitMakesNewLoopHeader = false;
11990b57cec5SDimitry Andric   for (BasicBlock *Pred : Preds) {
12000b57cec5SDimitry Andric     // Preds that are not reachable from entry should not be used to identify if
12010b57cec5SDimitry Andric     // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
12020b57cec5SDimitry Andric     // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
12030b57cec5SDimitry Andric     // as true and make the NewBB the header of some loop. This breaks LI.
12040b57cec5SDimitry Andric     if (!DT->isReachableFromEntry(Pred))
12050b57cec5SDimitry Andric       continue;
12060b57cec5SDimitry Andric     // If we need to preserve LCSSA, determine if any of the preds is a loop
12070b57cec5SDimitry Andric     // exit.
12080b57cec5SDimitry Andric     if (PreserveLCSSA)
12090b57cec5SDimitry Andric       if (Loop *PL = LI->getLoopFor(Pred))
12100b57cec5SDimitry Andric         if (!PL->contains(OldBB))
12110b57cec5SDimitry Andric           HasLoopExit = true;
12120b57cec5SDimitry Andric 
12130b57cec5SDimitry Andric     // If we need to preserve LoopInfo, note whether any of the preds crosses
12140b57cec5SDimitry Andric     // an interesting loop boundary.
12150b57cec5SDimitry Andric     if (!L)
12160b57cec5SDimitry Andric       continue;
12170b57cec5SDimitry Andric     if (L->contains(Pred))
12180b57cec5SDimitry Andric       IsLoopEntry = false;
12190b57cec5SDimitry Andric     else
12200b57cec5SDimitry Andric       SplitMakesNewLoopHeader = true;
12210b57cec5SDimitry Andric   }
12220b57cec5SDimitry Andric 
12230b57cec5SDimitry Andric   // Unless we have a loop for OldBB, nothing else to do here.
12240b57cec5SDimitry Andric   if (!L)
12250b57cec5SDimitry Andric     return;
12260b57cec5SDimitry Andric 
12270b57cec5SDimitry Andric   if (IsLoopEntry) {
12280b57cec5SDimitry Andric     // Add the new block to the nearest enclosing loop (and not an adjacent
12290b57cec5SDimitry Andric     // loop). To find this, examine each of the predecessors and determine which
12300b57cec5SDimitry Andric     // loops enclose them, and select the most-nested loop which contains the
12310b57cec5SDimitry Andric     // loop containing the block being split.
12320b57cec5SDimitry Andric     Loop *InnermostPredLoop = nullptr;
12330b57cec5SDimitry Andric     for (BasicBlock *Pred : Preds) {
12340b57cec5SDimitry Andric       if (Loop *PredLoop = LI->getLoopFor(Pred)) {
12350b57cec5SDimitry Andric         // Seek a loop which actually contains the block being split (to avoid
12360b57cec5SDimitry Andric         // adjacent loops).
12370b57cec5SDimitry Andric         while (PredLoop && !PredLoop->contains(OldBB))
12380b57cec5SDimitry Andric           PredLoop = PredLoop->getParentLoop();
12390b57cec5SDimitry Andric 
12400b57cec5SDimitry Andric         // Select the most-nested of these loops which contains the block.
12410b57cec5SDimitry Andric         if (PredLoop && PredLoop->contains(OldBB) &&
12420b57cec5SDimitry Andric             (!InnermostPredLoop ||
12430b57cec5SDimitry Andric              InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
12440b57cec5SDimitry Andric           InnermostPredLoop = PredLoop;
12450b57cec5SDimitry Andric       }
12460b57cec5SDimitry Andric     }
12470b57cec5SDimitry Andric 
12480b57cec5SDimitry Andric     if (InnermostPredLoop)
12490b57cec5SDimitry Andric       InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
12500b57cec5SDimitry Andric   } else {
12510b57cec5SDimitry Andric     L->addBasicBlockToLoop(NewBB, *LI);
12520b57cec5SDimitry Andric     if (SplitMakesNewLoopHeader)
12530b57cec5SDimitry Andric       L->moveToHeader(NewBB);
12540b57cec5SDimitry Andric   }
12550b57cec5SDimitry Andric }
12560b57cec5SDimitry Andric 
12570b57cec5SDimitry Andric /// Update the PHI nodes in OrigBB to include the values coming from NewBB.
12580b57cec5SDimitry Andric /// This also updates AliasAnalysis, if available.
12590b57cec5SDimitry Andric static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
12600b57cec5SDimitry Andric                            ArrayRef<BasicBlock *> Preds, BranchInst *BI,
12610b57cec5SDimitry Andric                            bool HasLoopExit) {
12620b57cec5SDimitry Andric   // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
12630b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
12640b57cec5SDimitry Andric   for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
12650b57cec5SDimitry Andric     PHINode *PN = cast<PHINode>(I++);
12660b57cec5SDimitry Andric 
12670b57cec5SDimitry Andric     // Check to see if all of the values coming in are the same.  If so, we
12680b57cec5SDimitry Andric     // don't need to create a new PHI node, unless it's needed for LCSSA.
12690b57cec5SDimitry Andric     Value *InVal = nullptr;
12700b57cec5SDimitry Andric     if (!HasLoopExit) {
12710b57cec5SDimitry Andric       InVal = PN->getIncomingValueForBlock(Preds[0]);
12720b57cec5SDimitry Andric       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
12730b57cec5SDimitry Andric         if (!PredSet.count(PN->getIncomingBlock(i)))
12740b57cec5SDimitry Andric           continue;
12750b57cec5SDimitry Andric         if (!InVal)
12760b57cec5SDimitry Andric           InVal = PN->getIncomingValue(i);
12770b57cec5SDimitry Andric         else if (InVal != PN->getIncomingValue(i)) {
12780b57cec5SDimitry Andric           InVal = nullptr;
12790b57cec5SDimitry Andric           break;
12800b57cec5SDimitry Andric         }
12810b57cec5SDimitry Andric       }
12820b57cec5SDimitry Andric     }
12830b57cec5SDimitry Andric 
12840b57cec5SDimitry Andric     if (InVal) {
12850b57cec5SDimitry Andric       // If all incoming values for the new PHI would be the same, just don't
12860b57cec5SDimitry Andric       // make a new PHI.  Instead, just remove the incoming values from the old
12870b57cec5SDimitry Andric       // PHI.
12885f757f3fSDimitry Andric       PN->removeIncomingValueIf(
12895f757f3fSDimitry Andric           [&](unsigned Idx) {
12905f757f3fSDimitry Andric             return PredSet.contains(PN->getIncomingBlock(Idx));
12915f757f3fSDimitry Andric           },
12925f757f3fSDimitry Andric           /* DeletePHIIfEmpty */ false);
12930b57cec5SDimitry Andric 
12940b57cec5SDimitry Andric       // Add an incoming value to the PHI node in the loop for the preheader
12950b57cec5SDimitry Andric       // edge.
12960b57cec5SDimitry Andric       PN->addIncoming(InVal, NewBB);
12970b57cec5SDimitry Andric       continue;
12980b57cec5SDimitry Andric     }
12990b57cec5SDimitry Andric 
13000b57cec5SDimitry Andric     // If the values coming into the block are not the same, we need a new
13010b57cec5SDimitry Andric     // PHI.
13020b57cec5SDimitry Andric     // Create the new PHI node, insert it into NewBB at the end of the block
13030b57cec5SDimitry Andric     PHINode *NewPHI =
1304*0fca6ea1SDimitry Andric         PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI->getIterator());
13050b57cec5SDimitry Andric 
13060b57cec5SDimitry Andric     // NOTE! This loop walks backwards for a reason! First off, this minimizes
13070b57cec5SDimitry Andric     // the cost of removal if we end up removing a large number of values, and
13080b57cec5SDimitry Andric     // second off, this ensures that the indices for the incoming values aren't
13090b57cec5SDimitry Andric     // invalidated when we remove one.
13100b57cec5SDimitry Andric     for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
13110b57cec5SDimitry Andric       BasicBlock *IncomingBB = PN->getIncomingBlock(i);
13120b57cec5SDimitry Andric       if (PredSet.count(IncomingBB)) {
13130b57cec5SDimitry Andric         Value *V = PN->removeIncomingValue(i, false);
13140b57cec5SDimitry Andric         NewPHI->addIncoming(V, IncomingBB);
13150b57cec5SDimitry Andric       }
13160b57cec5SDimitry Andric     }
13170b57cec5SDimitry Andric 
13180b57cec5SDimitry Andric     PN->addIncoming(NewPHI, NewBB);
13190b57cec5SDimitry Andric   }
13200b57cec5SDimitry Andric }
13210b57cec5SDimitry Andric 
1322e8d8bef9SDimitry Andric static void SplitLandingPadPredecessorsImpl(
1323e8d8bef9SDimitry Andric     BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1324e8d8bef9SDimitry Andric     const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1325e8d8bef9SDimitry Andric     DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1326e8d8bef9SDimitry Andric     MemorySSAUpdater *MSSAU, bool PreserveLCSSA);
1327e8d8bef9SDimitry Andric 
1328e8d8bef9SDimitry Andric static BasicBlock *
1329e8d8bef9SDimitry Andric SplitBlockPredecessorsImpl(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
1330e8d8bef9SDimitry Andric                            const char *Suffix, DomTreeUpdater *DTU,
1331e8d8bef9SDimitry Andric                            DominatorTree *DT, LoopInfo *LI,
1332e8d8bef9SDimitry Andric                            MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
13330b57cec5SDimitry Andric   // Do not attempt to split that which cannot be split.
13340b57cec5SDimitry Andric   if (!BB->canSplitPredecessors())
13350b57cec5SDimitry Andric     return nullptr;
13360b57cec5SDimitry Andric 
13370b57cec5SDimitry Andric   // For the landingpads we need to act a bit differently.
13380b57cec5SDimitry Andric   // Delegate this work to the SplitLandingPadPredecessors.
13390b57cec5SDimitry Andric   if (BB->isLandingPad()) {
13400b57cec5SDimitry Andric     SmallVector<BasicBlock*, 2> NewBBs;
13410b57cec5SDimitry Andric     std::string NewName = std::string(Suffix) + ".split-lp";
13420b57cec5SDimitry Andric 
1343e8d8bef9SDimitry Andric     SplitLandingPadPredecessorsImpl(BB, Preds, Suffix, NewName.c_str(), NewBBs,
1344e8d8bef9SDimitry Andric                                     DTU, DT, LI, MSSAU, PreserveLCSSA);
13450b57cec5SDimitry Andric     return NewBBs[0];
13460b57cec5SDimitry Andric   }
13470b57cec5SDimitry Andric 
13480b57cec5SDimitry Andric   // Create new basic block, insert right before the original block.
13490b57cec5SDimitry Andric   BasicBlock *NewBB = BasicBlock::Create(
13500b57cec5SDimitry Andric       BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric   // The new block unconditionally branches to the old block.
13530b57cec5SDimitry Andric   BranchInst *BI = BranchInst::Create(BB, NewBB);
1354e8d8bef9SDimitry Andric 
1355e8d8bef9SDimitry Andric   Loop *L = nullptr;
1356e8d8bef9SDimitry Andric   BasicBlock *OldLatch = nullptr;
13570b57cec5SDimitry Andric   // Splitting the predecessors of a loop header creates a preheader block.
1358e8d8bef9SDimitry Andric   if (LI && LI->isLoopHeader(BB)) {
1359e8d8bef9SDimitry Andric     L = LI->getLoopFor(BB);
13600b57cec5SDimitry Andric     // Using the loop start line number prevents debuggers stepping into the
13610b57cec5SDimitry Andric     // loop body for this instruction.
1362e8d8bef9SDimitry Andric     BI->setDebugLoc(L->getStartLoc());
1363e8d8bef9SDimitry Andric 
1364e8d8bef9SDimitry Andric     // If BB is the header of the Loop, it is possible that the loop is
1365e8d8bef9SDimitry Andric     // modified, such that the current latch does not remain the latch of the
1366e8d8bef9SDimitry Andric     // loop. If that is the case, the loop metadata from the current latch needs
1367e8d8bef9SDimitry Andric     // to be applied to the new latch.
1368e8d8bef9SDimitry Andric     OldLatch = L->getLoopLatch();
1369e8d8bef9SDimitry Andric   } else
13700b57cec5SDimitry Andric     BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
13710b57cec5SDimitry Andric 
13720b57cec5SDimitry Andric   // Move the edges from Preds to point to NewBB instead of BB.
1373bdd1243dSDimitry Andric   for (BasicBlock *Pred : Preds) {
13740b57cec5SDimitry Andric     // This is slightly more strict than necessary; the minimum requirement
13750b57cec5SDimitry Andric     // is that there be no more than one indirectbr branching to BB. And
13760b57cec5SDimitry Andric     // all BlockAddress uses would need to be updated.
1377bdd1243dSDimitry Andric     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
13780b57cec5SDimitry Andric            "Cannot split an edge from an IndirectBrInst");
1379bdd1243dSDimitry Andric     Pred->getTerminator()->replaceSuccessorWith(BB, NewBB);
13800b57cec5SDimitry Andric   }
13810b57cec5SDimitry Andric 
13820b57cec5SDimitry Andric   // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
13830b57cec5SDimitry Andric   // node becomes an incoming value for BB's phi node.  However, if the Preds
13840b57cec5SDimitry Andric   // list is empty, we need to insert dummy entries into the PHI nodes in BB to
13850b57cec5SDimitry Andric   // account for the newly created predecessor.
13860b57cec5SDimitry Andric   if (Preds.empty()) {
13870b57cec5SDimitry Andric     // Insert dummy values as the incoming value.
13880b57cec5SDimitry Andric     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
1389fcaf7f86SDimitry Andric       cast<PHINode>(I)->addIncoming(PoisonValue::get(I->getType()), NewBB);
13900b57cec5SDimitry Andric   }
13910b57cec5SDimitry Andric 
13920b57cec5SDimitry Andric   // Update DominatorTree, LoopInfo, and LCCSA analysis information.
13930b57cec5SDimitry Andric   bool HasLoopExit = false;
1394e8d8bef9SDimitry Andric   UpdateAnalysisInformation(BB, NewBB, Preds, DTU, DT, LI, MSSAU, PreserveLCSSA,
13950b57cec5SDimitry Andric                             HasLoopExit);
13960b57cec5SDimitry Andric 
13970b57cec5SDimitry Andric   if (!Preds.empty()) {
13980b57cec5SDimitry Andric     // Update the PHI nodes in BB with the values coming from NewBB.
13990b57cec5SDimitry Andric     UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
14000b57cec5SDimitry Andric   }
14010b57cec5SDimitry Andric 
1402e8d8bef9SDimitry Andric   if (OldLatch) {
1403e8d8bef9SDimitry Andric     BasicBlock *NewLatch = L->getLoopLatch();
1404e8d8bef9SDimitry Andric     if (NewLatch != OldLatch) {
1405*0fca6ea1SDimitry Andric       MDNode *MD = OldLatch->getTerminator()->getMetadata(LLVMContext::MD_loop);
1406*0fca6ea1SDimitry Andric       NewLatch->getTerminator()->setMetadata(LLVMContext::MD_loop, MD);
140781ad6265SDimitry Andric       // It's still possible that OldLatch is the latch of another inner loop,
140881ad6265SDimitry Andric       // in which case we do not remove the metadata.
140981ad6265SDimitry Andric       Loop *IL = LI->getLoopFor(OldLatch);
141081ad6265SDimitry Andric       if (IL && IL->getLoopLatch() != OldLatch)
1411*0fca6ea1SDimitry Andric         OldLatch->getTerminator()->setMetadata(LLVMContext::MD_loop, nullptr);
1412e8d8bef9SDimitry Andric     }
1413e8d8bef9SDimitry Andric   }
1414e8d8bef9SDimitry Andric 
14150b57cec5SDimitry Andric   return NewBB;
14160b57cec5SDimitry Andric }
14170b57cec5SDimitry Andric 
1418e8d8bef9SDimitry Andric BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
14190b57cec5SDimitry Andric                                          ArrayRef<BasicBlock *> Preds,
1420e8d8bef9SDimitry Andric                                          const char *Suffix, DominatorTree *DT,
1421e8d8bef9SDimitry Andric                                          LoopInfo *LI, MemorySSAUpdater *MSSAU,
1422e8d8bef9SDimitry Andric                                          bool PreserveLCSSA) {
1423e8d8bef9SDimitry Andric   return SplitBlockPredecessorsImpl(BB, Preds, Suffix, /*DTU=*/nullptr, DT, LI,
1424e8d8bef9SDimitry Andric                                     MSSAU, PreserveLCSSA);
1425e8d8bef9SDimitry Andric }
1426e8d8bef9SDimitry Andric BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
1427e8d8bef9SDimitry Andric                                          ArrayRef<BasicBlock *> Preds,
1428e8d8bef9SDimitry Andric                                          const char *Suffix,
1429e8d8bef9SDimitry Andric                                          DomTreeUpdater *DTU, LoopInfo *LI,
14300b57cec5SDimitry Andric                                          MemorySSAUpdater *MSSAU,
14310b57cec5SDimitry Andric                                          bool PreserveLCSSA) {
1432e8d8bef9SDimitry Andric   return SplitBlockPredecessorsImpl(BB, Preds, Suffix, DTU,
1433e8d8bef9SDimitry Andric                                     /*DT=*/nullptr, LI, MSSAU, PreserveLCSSA);
1434e8d8bef9SDimitry Andric }
1435e8d8bef9SDimitry Andric 
1436e8d8bef9SDimitry Andric static void SplitLandingPadPredecessorsImpl(
1437e8d8bef9SDimitry Andric     BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1438e8d8bef9SDimitry Andric     const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1439e8d8bef9SDimitry Andric     DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1440e8d8bef9SDimitry Andric     MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
14410b57cec5SDimitry Andric   assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
14420b57cec5SDimitry Andric 
14430b57cec5SDimitry Andric   // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
14440b57cec5SDimitry Andric   // it right before the original block.
14450b57cec5SDimitry Andric   BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
14460b57cec5SDimitry Andric                                           OrigBB->getName() + Suffix1,
14470b57cec5SDimitry Andric                                           OrigBB->getParent(), OrigBB);
14480b57cec5SDimitry Andric   NewBBs.push_back(NewBB1);
14490b57cec5SDimitry Andric 
14500b57cec5SDimitry Andric   // The new block unconditionally branches to the old block.
14510b57cec5SDimitry Andric   BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
14520b57cec5SDimitry Andric   BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
14530b57cec5SDimitry Andric 
14540b57cec5SDimitry Andric   // Move the edges from Preds to point to NewBB1 instead of OrigBB.
1455bdd1243dSDimitry Andric   for (BasicBlock *Pred : Preds) {
14560b57cec5SDimitry Andric     // This is slightly more strict than necessary; the minimum requirement
14570b57cec5SDimitry Andric     // is that there be no more than one indirectbr branching to BB. And
14580b57cec5SDimitry Andric     // all BlockAddress uses would need to be updated.
1459bdd1243dSDimitry Andric     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
14600b57cec5SDimitry Andric            "Cannot split an edge from an IndirectBrInst");
1461bdd1243dSDimitry Andric     Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
14620b57cec5SDimitry Andric   }
14630b57cec5SDimitry Andric 
14640b57cec5SDimitry Andric   bool HasLoopExit = false;
1465e8d8bef9SDimitry Andric   UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DTU, DT, LI, MSSAU,
1466e8d8bef9SDimitry Andric                             PreserveLCSSA, HasLoopExit);
14670b57cec5SDimitry Andric 
14680b57cec5SDimitry Andric   // Update the PHI nodes in OrigBB with the values coming from NewBB1.
14690b57cec5SDimitry Andric   UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
14700b57cec5SDimitry Andric 
14710b57cec5SDimitry Andric   // Move the remaining edges from OrigBB to point to NewBB2.
14720b57cec5SDimitry Andric   SmallVector<BasicBlock*, 8> NewBB2Preds;
14730b57cec5SDimitry Andric   for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
14740b57cec5SDimitry Andric        i != e; ) {
14750b57cec5SDimitry Andric     BasicBlock *Pred = *i++;
14760b57cec5SDimitry Andric     if (Pred == NewBB1) continue;
14770b57cec5SDimitry Andric     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
14780b57cec5SDimitry Andric            "Cannot split an edge from an IndirectBrInst");
14790b57cec5SDimitry Andric     NewBB2Preds.push_back(Pred);
14800b57cec5SDimitry Andric     e = pred_end(OrigBB);
14810b57cec5SDimitry Andric   }
14820b57cec5SDimitry Andric 
14830b57cec5SDimitry Andric   BasicBlock *NewBB2 = nullptr;
14840b57cec5SDimitry Andric   if (!NewBB2Preds.empty()) {
14850b57cec5SDimitry Andric     // Create another basic block for the rest of OrigBB's predecessors.
14860b57cec5SDimitry Andric     NewBB2 = BasicBlock::Create(OrigBB->getContext(),
14870b57cec5SDimitry Andric                                 OrigBB->getName() + Suffix2,
14880b57cec5SDimitry Andric                                 OrigBB->getParent(), OrigBB);
14890b57cec5SDimitry Andric     NewBBs.push_back(NewBB2);
14900b57cec5SDimitry Andric 
14910b57cec5SDimitry Andric     // The new block unconditionally branches to the old block.
14920b57cec5SDimitry Andric     BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
14930b57cec5SDimitry Andric     BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
14940b57cec5SDimitry Andric 
14950b57cec5SDimitry Andric     // Move the remaining edges from OrigBB to point to NewBB2.
14960b57cec5SDimitry Andric     for (BasicBlock *NewBB2Pred : NewBB2Preds)
14970b57cec5SDimitry Andric       NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
14980b57cec5SDimitry Andric 
14990b57cec5SDimitry Andric     // Update DominatorTree, LoopInfo, and LCCSA analysis information.
15000b57cec5SDimitry Andric     HasLoopExit = false;
1501e8d8bef9SDimitry Andric     UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DTU, DT, LI, MSSAU,
15020b57cec5SDimitry Andric                               PreserveLCSSA, HasLoopExit);
15030b57cec5SDimitry Andric 
15040b57cec5SDimitry Andric     // Update the PHI nodes in OrigBB with the values coming from NewBB2.
15050b57cec5SDimitry Andric     UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
15060b57cec5SDimitry Andric   }
15070b57cec5SDimitry Andric 
15080b57cec5SDimitry Andric   LandingPadInst *LPad = OrigBB->getLandingPadInst();
15090b57cec5SDimitry Andric   Instruction *Clone1 = LPad->clone();
15100b57cec5SDimitry Andric   Clone1->setName(Twine("lpad") + Suffix1);
1511bdd1243dSDimitry Andric   Clone1->insertInto(NewBB1, NewBB1->getFirstInsertionPt());
15120b57cec5SDimitry Andric 
15130b57cec5SDimitry Andric   if (NewBB2) {
15140b57cec5SDimitry Andric     Instruction *Clone2 = LPad->clone();
15150b57cec5SDimitry Andric     Clone2->setName(Twine("lpad") + Suffix2);
1516bdd1243dSDimitry Andric     Clone2->insertInto(NewBB2, NewBB2->getFirstInsertionPt());
15170b57cec5SDimitry Andric 
15180b57cec5SDimitry Andric     // Create a PHI node for the two cloned landingpad instructions only
15190b57cec5SDimitry Andric     // if the original landingpad instruction has some uses.
15200b57cec5SDimitry Andric     if (!LPad->use_empty()) {
15210b57cec5SDimitry Andric       assert(!LPad->getType()->isTokenTy() &&
15220b57cec5SDimitry Andric              "Split cannot be applied if LPad is token type. Otherwise an "
15230b57cec5SDimitry Andric              "invalid PHINode of token type would be created.");
1524*0fca6ea1SDimitry Andric       PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad->getIterator());
15250b57cec5SDimitry Andric       PN->addIncoming(Clone1, NewBB1);
15260b57cec5SDimitry Andric       PN->addIncoming(Clone2, NewBB2);
15270b57cec5SDimitry Andric       LPad->replaceAllUsesWith(PN);
15280b57cec5SDimitry Andric     }
15290b57cec5SDimitry Andric     LPad->eraseFromParent();
15300b57cec5SDimitry Andric   } else {
15310b57cec5SDimitry Andric     // There is no second clone. Just replace the landing pad with the first
15320b57cec5SDimitry Andric     // clone.
15330b57cec5SDimitry Andric     LPad->replaceAllUsesWith(Clone1);
15340b57cec5SDimitry Andric     LPad->eraseFromParent();
15350b57cec5SDimitry Andric   }
15360b57cec5SDimitry Andric }
15370b57cec5SDimitry Andric 
1538e8d8bef9SDimitry Andric void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
1539e8d8bef9SDimitry Andric                                        ArrayRef<BasicBlock *> Preds,
1540e8d8bef9SDimitry Andric                                        const char *Suffix1, const char *Suffix2,
1541e8d8bef9SDimitry Andric                                        SmallVectorImpl<BasicBlock *> &NewBBs,
1542e8d8bef9SDimitry Andric                                        DomTreeUpdater *DTU, LoopInfo *LI,
1543e8d8bef9SDimitry Andric                                        MemorySSAUpdater *MSSAU,
1544e8d8bef9SDimitry Andric                                        bool PreserveLCSSA) {
1545e8d8bef9SDimitry Andric   return SplitLandingPadPredecessorsImpl(OrigBB, Preds, Suffix1, Suffix2,
1546e8d8bef9SDimitry Andric                                          NewBBs, DTU, /*DT=*/nullptr, LI, MSSAU,
1547e8d8bef9SDimitry Andric                                          PreserveLCSSA);
1548e8d8bef9SDimitry Andric }
1549e8d8bef9SDimitry Andric 
15500b57cec5SDimitry Andric ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
15510b57cec5SDimitry Andric                                              BasicBlock *Pred,
15520b57cec5SDimitry Andric                                              DomTreeUpdater *DTU) {
15530b57cec5SDimitry Andric   Instruction *UncondBranch = Pred->getTerminator();
15540b57cec5SDimitry Andric   // Clone the return and add it to the end of the predecessor.
15550b57cec5SDimitry Andric   Instruction *NewRet = RI->clone();
1556bdd1243dSDimitry Andric   NewRet->insertInto(Pred, Pred->end());
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric   // If the return instruction returns a value, and if the value was a
15590b57cec5SDimitry Andric   // PHI node in "BB", propagate the right value into the return.
1560fe6060f1SDimitry Andric   for (Use &Op : NewRet->operands()) {
1561fe6060f1SDimitry Andric     Value *V = Op;
15620b57cec5SDimitry Andric     Instruction *NewBC = nullptr;
15630b57cec5SDimitry Andric     if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
15640b57cec5SDimitry Andric       // Return value might be bitcasted. Clone and insert it before the
15650b57cec5SDimitry Andric       // return instruction.
15660b57cec5SDimitry Andric       V = BCI->getOperand(0);
15670b57cec5SDimitry Andric       NewBC = BCI->clone();
1568bdd1243dSDimitry Andric       NewBC->insertInto(Pred, NewRet->getIterator());
1569fe6060f1SDimitry Andric       Op = NewBC;
15700b57cec5SDimitry Andric     }
15715ffd83dbSDimitry Andric 
15725ffd83dbSDimitry Andric     Instruction *NewEV = nullptr;
15735ffd83dbSDimitry Andric     if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
15745ffd83dbSDimitry Andric       V = EVI->getOperand(0);
15755ffd83dbSDimitry Andric       NewEV = EVI->clone();
15765ffd83dbSDimitry Andric       if (NewBC) {
15775ffd83dbSDimitry Andric         NewBC->setOperand(0, NewEV);
1578bdd1243dSDimitry Andric         NewEV->insertInto(Pred, NewBC->getIterator());
15795ffd83dbSDimitry Andric       } else {
1580bdd1243dSDimitry Andric         NewEV->insertInto(Pred, NewRet->getIterator());
1581fe6060f1SDimitry Andric         Op = NewEV;
15825ffd83dbSDimitry Andric       }
15835ffd83dbSDimitry Andric     }
15845ffd83dbSDimitry Andric 
15850b57cec5SDimitry Andric     if (PHINode *PN = dyn_cast<PHINode>(V)) {
15860b57cec5SDimitry Andric       if (PN->getParent() == BB) {
15875ffd83dbSDimitry Andric         if (NewEV) {
15885ffd83dbSDimitry Andric           NewEV->setOperand(0, PN->getIncomingValueForBlock(Pred));
15895ffd83dbSDimitry Andric         } else if (NewBC)
15900b57cec5SDimitry Andric           NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
15910b57cec5SDimitry Andric         else
1592fe6060f1SDimitry Andric           Op = PN->getIncomingValueForBlock(Pred);
15930b57cec5SDimitry Andric       }
15940b57cec5SDimitry Andric     }
15950b57cec5SDimitry Andric   }
15960b57cec5SDimitry Andric 
15970b57cec5SDimitry Andric   // Update any PHI nodes in the returning block to realize that we no
15980b57cec5SDimitry Andric   // longer branch to them.
15990b57cec5SDimitry Andric   BB->removePredecessor(Pred);
16000b57cec5SDimitry Andric   UncondBranch->eraseFromParent();
16010b57cec5SDimitry Andric 
16020b57cec5SDimitry Andric   if (DTU)
16030b57cec5SDimitry Andric     DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}});
16040b57cec5SDimitry Andric 
16050b57cec5SDimitry Andric   return cast<ReturnInst>(NewRet);
16060b57cec5SDimitry Andric }
16070b57cec5SDimitry Andric 
1608e8d8bef9SDimitry Andric Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond,
16095f757f3fSDimitry Andric                                              BasicBlock::iterator SplitBefore,
1610e8d8bef9SDimitry Andric                                              bool Unreachable,
1611e8d8bef9SDimitry Andric                                              MDNode *BranchWeights,
1612e8d8bef9SDimitry Andric                                              DomTreeUpdater *DTU, LoopInfo *LI,
1613e8d8bef9SDimitry Andric                                              BasicBlock *ThenBlock) {
161406c3fb27SDimitry Andric   SplitBlockAndInsertIfThenElse(
161506c3fb27SDimitry Andric       Cond, SplitBefore, &ThenBlock, /* ElseBlock */ nullptr,
161606c3fb27SDimitry Andric       /* UnreachableThen */ Unreachable,
161706c3fb27SDimitry Andric       /* UnreachableElse */ false, BranchWeights, DTU, LI);
161806c3fb27SDimitry Andric   return ThenBlock->getTerminator();
161906c3fb27SDimitry Andric }
162006c3fb27SDimitry Andric 
162106c3fb27SDimitry Andric Instruction *llvm::SplitBlockAndInsertIfElse(Value *Cond,
16225f757f3fSDimitry Andric                                              BasicBlock::iterator SplitBefore,
162306c3fb27SDimitry Andric                                              bool Unreachable,
162406c3fb27SDimitry Andric                                              MDNode *BranchWeights,
162506c3fb27SDimitry Andric                                              DomTreeUpdater *DTU, LoopInfo *LI,
162606c3fb27SDimitry Andric                                              BasicBlock *ElseBlock) {
162706c3fb27SDimitry Andric   SplitBlockAndInsertIfThenElse(
162806c3fb27SDimitry Andric       Cond, SplitBefore, /* ThenBlock */ nullptr, &ElseBlock,
162906c3fb27SDimitry Andric       /* UnreachableThen */ false,
163006c3fb27SDimitry Andric       /* UnreachableElse */ Unreachable, BranchWeights, DTU, LI);
163106c3fb27SDimitry Andric   return ElseBlock->getTerminator();
1632e8d8bef9SDimitry Andric }
1633e8d8bef9SDimitry Andric 
16345f757f3fSDimitry Andric void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore,
16350b57cec5SDimitry Andric                                          Instruction **ThenTerm,
16360b57cec5SDimitry Andric                                          Instruction **ElseTerm,
1637bdd1243dSDimitry Andric                                          MDNode *BranchWeights,
163806c3fb27SDimitry Andric                                          DomTreeUpdater *DTU, LoopInfo *LI) {
163906c3fb27SDimitry Andric   BasicBlock *ThenBlock = nullptr;
164006c3fb27SDimitry Andric   BasicBlock *ElseBlock = nullptr;
164106c3fb27SDimitry Andric   SplitBlockAndInsertIfThenElse(
164206c3fb27SDimitry Andric       Cond, SplitBefore, &ThenBlock, &ElseBlock, /* UnreachableThen */ false,
164306c3fb27SDimitry Andric       /* UnreachableElse */ false, BranchWeights, DTU, LI);
1644bdd1243dSDimitry Andric 
164506c3fb27SDimitry Andric   *ThenTerm = ThenBlock->getTerminator();
164606c3fb27SDimitry Andric   *ElseTerm = ElseBlock->getTerminator();
164706c3fb27SDimitry Andric }
164806c3fb27SDimitry Andric 
164906c3fb27SDimitry Andric void llvm::SplitBlockAndInsertIfThenElse(
16505f757f3fSDimitry Andric     Value *Cond, BasicBlock::iterator SplitBefore, BasicBlock **ThenBlock,
165106c3fb27SDimitry Andric     BasicBlock **ElseBlock, bool UnreachableThen, bool UnreachableElse,
165206c3fb27SDimitry Andric     MDNode *BranchWeights, DomTreeUpdater *DTU, LoopInfo *LI) {
165306c3fb27SDimitry Andric   assert((ThenBlock || ElseBlock) &&
165406c3fb27SDimitry Andric          "At least one branch block must be created");
165506c3fb27SDimitry Andric   assert((!UnreachableThen || !UnreachableElse) &&
165606c3fb27SDimitry Andric          "Split block tail must be reachable");
165706c3fb27SDimitry Andric 
165806c3fb27SDimitry Andric   SmallVector<DominatorTree::UpdateType, 8> Updates;
1659bdd1243dSDimitry Andric   SmallPtrSet<BasicBlock *, 8> UniqueOrigSuccessors;
166006c3fb27SDimitry Andric   BasicBlock *Head = SplitBefore->getParent();
166106c3fb27SDimitry Andric   if (DTU) {
1662bdd1243dSDimitry Andric     UniqueOrigSuccessors.insert(succ_begin(Head), succ_end(Head));
166306c3fb27SDimitry Andric     Updates.reserve(4 + 2 * UniqueOrigSuccessors.size());
166406c3fb27SDimitry Andric   }
1665bdd1243dSDimitry Andric 
16660b57cec5SDimitry Andric   LLVMContext &C = Head->getContext();
16675f757f3fSDimitry Andric   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
166806c3fb27SDimitry Andric   BasicBlock *TrueBlock = Tail;
166906c3fb27SDimitry Andric   BasicBlock *FalseBlock = Tail;
167006c3fb27SDimitry Andric   bool ThenToTailEdge = false;
167106c3fb27SDimitry Andric   bool ElseToTailEdge = false;
167206c3fb27SDimitry Andric 
167306c3fb27SDimitry Andric   // Encapsulate the logic around creation/insertion/etc of a new block.
167406c3fb27SDimitry Andric   auto handleBlock = [&](BasicBlock **PBB, bool Unreachable, BasicBlock *&BB,
167506c3fb27SDimitry Andric                          bool &ToTailEdge) {
167606c3fb27SDimitry Andric     if (PBB == nullptr)
167706c3fb27SDimitry Andric       return; // Do not create/insert a block.
167806c3fb27SDimitry Andric 
167906c3fb27SDimitry Andric     if (*PBB)
168006c3fb27SDimitry Andric       BB = *PBB; // Caller supplied block, use it.
168106c3fb27SDimitry Andric     else {
168206c3fb27SDimitry Andric       // Create a new block.
168306c3fb27SDimitry Andric       BB = BasicBlock::Create(C, "", Head->getParent(), Tail);
168406c3fb27SDimitry Andric       if (Unreachable)
168506c3fb27SDimitry Andric         (void)new UnreachableInst(C, BB);
168606c3fb27SDimitry Andric       else {
168706c3fb27SDimitry Andric         (void)BranchInst::Create(Tail, BB);
168806c3fb27SDimitry Andric         ToTailEdge = true;
168906c3fb27SDimitry Andric       }
169006c3fb27SDimitry Andric       BB->getTerminator()->setDebugLoc(SplitBefore->getDebugLoc());
169106c3fb27SDimitry Andric       // Pass the new block back to the caller.
169206c3fb27SDimitry Andric       *PBB = BB;
169306c3fb27SDimitry Andric     }
169406c3fb27SDimitry Andric   };
169506c3fb27SDimitry Andric 
169606c3fb27SDimitry Andric   handleBlock(ThenBlock, UnreachableThen, TrueBlock, ThenToTailEdge);
169706c3fb27SDimitry Andric   handleBlock(ElseBlock, UnreachableElse, FalseBlock, ElseToTailEdge);
169806c3fb27SDimitry Andric 
169906c3fb27SDimitry Andric   Instruction *HeadOldTerm = Head->getTerminator();
17000b57cec5SDimitry Andric   BranchInst *HeadNewTerm =
170106c3fb27SDimitry Andric       BranchInst::Create(/*ifTrue*/ TrueBlock, /*ifFalse*/ FalseBlock, Cond);
17020b57cec5SDimitry Andric   HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
17030b57cec5SDimitry Andric   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
170406c3fb27SDimitry Andric 
1705bdd1243dSDimitry Andric   if (DTU) {
170606c3fb27SDimitry Andric     Updates.emplace_back(DominatorTree::Insert, Head, TrueBlock);
170706c3fb27SDimitry Andric     Updates.emplace_back(DominatorTree::Insert, Head, FalseBlock);
170806c3fb27SDimitry Andric     if (ThenToTailEdge)
170906c3fb27SDimitry Andric       Updates.emplace_back(DominatorTree::Insert, TrueBlock, Tail);
171006c3fb27SDimitry Andric     if (ElseToTailEdge)
171106c3fb27SDimitry Andric       Updates.emplace_back(DominatorTree::Insert, FalseBlock, Tail);
1712bdd1243dSDimitry Andric     for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
171306c3fb27SDimitry Andric       Updates.emplace_back(DominatorTree::Insert, Tail, UniqueOrigSuccessor);
1714bdd1243dSDimitry Andric     for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
171506c3fb27SDimitry Andric       Updates.emplace_back(DominatorTree::Delete, Head, UniqueOrigSuccessor);
1716bdd1243dSDimitry Andric     DTU->applyUpdates(Updates);
1717bdd1243dSDimitry Andric   }
171806c3fb27SDimitry Andric 
171906c3fb27SDimitry Andric   if (LI) {
172006c3fb27SDimitry Andric     if (Loop *L = LI->getLoopFor(Head); L) {
172106c3fb27SDimitry Andric       if (ThenToTailEdge)
172206c3fb27SDimitry Andric         L->addBasicBlockToLoop(TrueBlock, *LI);
172306c3fb27SDimitry Andric       if (ElseToTailEdge)
172406c3fb27SDimitry Andric         L->addBasicBlockToLoop(FalseBlock, *LI);
172506c3fb27SDimitry Andric       L->addBasicBlockToLoop(Tail, *LI);
172606c3fb27SDimitry Andric     }
172706c3fb27SDimitry Andric   }
172806c3fb27SDimitry Andric }
172906c3fb27SDimitry Andric 
173006c3fb27SDimitry Andric std::pair<Instruction*, Value*>
173106c3fb27SDimitry Andric llvm::SplitBlockAndInsertSimpleForLoop(Value *End, Instruction *SplitBefore) {
173206c3fb27SDimitry Andric   BasicBlock *LoopPred = SplitBefore->getParent();
173306c3fb27SDimitry Andric   BasicBlock *LoopBody = SplitBlock(SplitBefore->getParent(), SplitBefore);
173406c3fb27SDimitry Andric   BasicBlock *LoopExit = SplitBlock(SplitBefore->getParent(), SplitBefore);
173506c3fb27SDimitry Andric 
173606c3fb27SDimitry Andric   auto *Ty = End->getType();
1737*0fca6ea1SDimitry Andric   auto &DL = SplitBefore->getDataLayout();
173806c3fb27SDimitry Andric   const unsigned Bitwidth = DL.getTypeSizeInBits(Ty);
173906c3fb27SDimitry Andric 
174006c3fb27SDimitry Andric   IRBuilder<> Builder(LoopBody->getTerminator());
174106c3fb27SDimitry Andric   auto *IV = Builder.CreatePHI(Ty, 2, "iv");
174206c3fb27SDimitry Andric   auto *IVNext =
174306c3fb27SDimitry Andric     Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next",
174406c3fb27SDimitry Andric                       /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
174506c3fb27SDimitry Andric   auto *IVCheck = Builder.CreateICmpEQ(IVNext, End,
174606c3fb27SDimitry Andric                                        IV->getName() + ".check");
174706c3fb27SDimitry Andric   Builder.CreateCondBr(IVCheck, LoopExit, LoopBody);
174806c3fb27SDimitry Andric   LoopBody->getTerminator()->eraseFromParent();
174906c3fb27SDimitry Andric 
175006c3fb27SDimitry Andric   // Populate the IV PHI.
175106c3fb27SDimitry Andric   IV->addIncoming(ConstantInt::get(Ty, 0), LoopPred);
175206c3fb27SDimitry Andric   IV->addIncoming(IVNext, LoopBody);
175306c3fb27SDimitry Andric 
175406c3fb27SDimitry Andric   return std::make_pair(LoopBody->getFirstNonPHI(), IV);
175506c3fb27SDimitry Andric }
175606c3fb27SDimitry Andric 
175706c3fb27SDimitry Andric void llvm::SplitBlockAndInsertForEachLane(ElementCount EC,
175806c3fb27SDimitry Andric      Type *IndexTy, Instruction *InsertBefore,
175906c3fb27SDimitry Andric      std::function<void(IRBuilderBase&, Value*)> Func) {
176006c3fb27SDimitry Andric 
176106c3fb27SDimitry Andric   IRBuilder<> IRB(InsertBefore);
176206c3fb27SDimitry Andric 
176306c3fb27SDimitry Andric   if (EC.isScalable()) {
176406c3fb27SDimitry Andric     Value *NumElements = IRB.CreateElementCount(IndexTy, EC);
176506c3fb27SDimitry Andric 
176606c3fb27SDimitry Andric     auto [BodyIP, Index] =
176706c3fb27SDimitry Andric       SplitBlockAndInsertSimpleForLoop(NumElements, InsertBefore);
176806c3fb27SDimitry Andric 
176906c3fb27SDimitry Andric     IRB.SetInsertPoint(BodyIP);
177006c3fb27SDimitry Andric     Func(IRB, Index);
177106c3fb27SDimitry Andric     return;
177206c3fb27SDimitry Andric   }
177306c3fb27SDimitry Andric 
177406c3fb27SDimitry Andric   unsigned Num = EC.getFixedValue();
177506c3fb27SDimitry Andric   for (unsigned Idx = 0; Idx < Num; ++Idx) {
177606c3fb27SDimitry Andric     IRB.SetInsertPoint(InsertBefore);
177706c3fb27SDimitry Andric     Func(IRB, ConstantInt::get(IndexTy, Idx));
177806c3fb27SDimitry Andric   }
177906c3fb27SDimitry Andric }
178006c3fb27SDimitry Andric 
178106c3fb27SDimitry Andric void llvm::SplitBlockAndInsertForEachLane(
178206c3fb27SDimitry Andric     Value *EVL, Instruction *InsertBefore,
178306c3fb27SDimitry Andric     std::function<void(IRBuilderBase &, Value *)> Func) {
178406c3fb27SDimitry Andric 
178506c3fb27SDimitry Andric   IRBuilder<> IRB(InsertBefore);
178606c3fb27SDimitry Andric   Type *Ty = EVL->getType();
178706c3fb27SDimitry Andric 
178806c3fb27SDimitry Andric   if (!isa<ConstantInt>(EVL)) {
178906c3fb27SDimitry Andric     auto [BodyIP, Index] = SplitBlockAndInsertSimpleForLoop(EVL, InsertBefore);
179006c3fb27SDimitry Andric     IRB.SetInsertPoint(BodyIP);
179106c3fb27SDimitry Andric     Func(IRB, Index);
179206c3fb27SDimitry Andric     return;
179306c3fb27SDimitry Andric   }
179406c3fb27SDimitry Andric 
179506c3fb27SDimitry Andric   unsigned Num = cast<ConstantInt>(EVL)->getZExtValue();
179606c3fb27SDimitry Andric   for (unsigned Idx = 0; Idx < Num; ++Idx) {
179706c3fb27SDimitry Andric     IRB.SetInsertPoint(InsertBefore);
179806c3fb27SDimitry Andric     Func(IRB, ConstantInt::get(Ty, Idx));
179906c3fb27SDimitry Andric   }
18000b57cec5SDimitry Andric }
18010b57cec5SDimitry Andric 
1802fe6060f1SDimitry Andric BranchInst *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
18030b57cec5SDimitry Andric                                  BasicBlock *&IfFalse) {
18040b57cec5SDimitry Andric   PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
18050b57cec5SDimitry Andric   BasicBlock *Pred1 = nullptr;
18060b57cec5SDimitry Andric   BasicBlock *Pred2 = nullptr;
18070b57cec5SDimitry Andric 
18080b57cec5SDimitry Andric   if (SomePHI) {
18090b57cec5SDimitry Andric     if (SomePHI->getNumIncomingValues() != 2)
18100b57cec5SDimitry Andric       return nullptr;
18110b57cec5SDimitry Andric     Pred1 = SomePHI->getIncomingBlock(0);
18120b57cec5SDimitry Andric     Pred2 = SomePHI->getIncomingBlock(1);
18130b57cec5SDimitry Andric   } else {
18140b57cec5SDimitry Andric     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
18150b57cec5SDimitry Andric     if (PI == PE) // No predecessor
18160b57cec5SDimitry Andric       return nullptr;
18170b57cec5SDimitry Andric     Pred1 = *PI++;
18180b57cec5SDimitry Andric     if (PI == PE) // Only one predecessor
18190b57cec5SDimitry Andric       return nullptr;
18200b57cec5SDimitry Andric     Pred2 = *PI++;
18210b57cec5SDimitry Andric     if (PI != PE) // More than two predecessors
18220b57cec5SDimitry Andric       return nullptr;
18230b57cec5SDimitry Andric   }
18240b57cec5SDimitry Andric 
18250b57cec5SDimitry Andric   // We can only handle branches.  Other control flow will be lowered to
18260b57cec5SDimitry Andric   // branches if possible anyway.
18270b57cec5SDimitry Andric   BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
18280b57cec5SDimitry Andric   BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
18290b57cec5SDimitry Andric   if (!Pred1Br || !Pred2Br)
18300b57cec5SDimitry Andric     return nullptr;
18310b57cec5SDimitry Andric 
18320b57cec5SDimitry Andric   // Eliminate code duplication by ensuring that Pred1Br is conditional if
18330b57cec5SDimitry Andric   // either are.
18340b57cec5SDimitry Andric   if (Pred2Br->isConditional()) {
18350b57cec5SDimitry Andric     // If both branches are conditional, we don't have an "if statement".  In
18360b57cec5SDimitry Andric     // reality, we could transform this case, but since the condition will be
18370b57cec5SDimitry Andric     // required anyway, we stand no chance of eliminating it, so the xform is
18380b57cec5SDimitry Andric     // probably not profitable.
18390b57cec5SDimitry Andric     if (Pred1Br->isConditional())
18400b57cec5SDimitry Andric       return nullptr;
18410b57cec5SDimitry Andric 
18420b57cec5SDimitry Andric     std::swap(Pred1, Pred2);
18430b57cec5SDimitry Andric     std::swap(Pred1Br, Pred2Br);
18440b57cec5SDimitry Andric   }
18450b57cec5SDimitry Andric 
18460b57cec5SDimitry Andric   if (Pred1Br->isConditional()) {
18470b57cec5SDimitry Andric     // The only thing we have to watch out for here is to make sure that Pred2
18480b57cec5SDimitry Andric     // doesn't have incoming edges from other blocks.  If it does, the condition
18490b57cec5SDimitry Andric     // doesn't dominate BB.
18500b57cec5SDimitry Andric     if (!Pred2->getSinglePredecessor())
18510b57cec5SDimitry Andric       return nullptr;
18520b57cec5SDimitry Andric 
18530b57cec5SDimitry Andric     // If we found a conditional branch predecessor, make sure that it branches
18540b57cec5SDimitry Andric     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
18550b57cec5SDimitry Andric     if (Pred1Br->getSuccessor(0) == BB &&
18560b57cec5SDimitry Andric         Pred1Br->getSuccessor(1) == Pred2) {
18570b57cec5SDimitry Andric       IfTrue = Pred1;
18580b57cec5SDimitry Andric       IfFalse = Pred2;
18590b57cec5SDimitry Andric     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
18600b57cec5SDimitry Andric                Pred1Br->getSuccessor(1) == BB) {
18610b57cec5SDimitry Andric       IfTrue = Pred2;
18620b57cec5SDimitry Andric       IfFalse = Pred1;
18630b57cec5SDimitry Andric     } else {
18640b57cec5SDimitry Andric       // We know that one arm of the conditional goes to BB, so the other must
18650b57cec5SDimitry Andric       // go somewhere unrelated, and this must not be an "if statement".
18660b57cec5SDimitry Andric       return nullptr;
18670b57cec5SDimitry Andric     }
18680b57cec5SDimitry Andric 
1869fe6060f1SDimitry Andric     return Pred1Br;
18700b57cec5SDimitry Andric   }
18710b57cec5SDimitry Andric 
18720b57cec5SDimitry Andric   // Ok, if we got here, both predecessors end with an unconditional branch to
18730b57cec5SDimitry Andric   // BB.  Don't panic!  If both blocks only have a single (identical)
18740b57cec5SDimitry Andric   // predecessor, and THAT is a conditional branch, then we're all ok!
18750b57cec5SDimitry Andric   BasicBlock *CommonPred = Pred1->getSinglePredecessor();
18760b57cec5SDimitry Andric   if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
18770b57cec5SDimitry Andric     return nullptr;
18780b57cec5SDimitry Andric 
18790b57cec5SDimitry Andric   // Otherwise, if this is a conditional branch, then we can use it!
18800b57cec5SDimitry Andric   BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
18810b57cec5SDimitry Andric   if (!BI) return nullptr;
18820b57cec5SDimitry Andric 
18830b57cec5SDimitry Andric   assert(BI->isConditional() && "Two successors but not conditional?");
18840b57cec5SDimitry Andric   if (BI->getSuccessor(0) == Pred1) {
18850b57cec5SDimitry Andric     IfTrue = Pred1;
18860b57cec5SDimitry Andric     IfFalse = Pred2;
18870b57cec5SDimitry Andric   } else {
18880b57cec5SDimitry Andric     IfTrue = Pred2;
18890b57cec5SDimitry Andric     IfFalse = Pred1;
18900b57cec5SDimitry Andric   }
1891fe6060f1SDimitry Andric   return BI;
18920b57cec5SDimitry Andric }
18935ffd83dbSDimitry Andric 
18945ffd83dbSDimitry Andric // After creating a control flow hub, the operands of PHINodes in an outgoing
18955ffd83dbSDimitry Andric // block Out no longer match the predecessors of that block. Predecessors of Out
18965ffd83dbSDimitry Andric // that are incoming blocks to the hub are now replaced by just one edge from
18975ffd83dbSDimitry Andric // the hub. To match this new control flow, the corresponding values from each
18985ffd83dbSDimitry Andric // PHINode must now be moved a new PHINode in the first guard block of the hub.
18995ffd83dbSDimitry Andric //
19005ffd83dbSDimitry Andric // This operation cannot be performed with SSAUpdater, because it involves one
19015ffd83dbSDimitry Andric // new use: If the block Out is in the list of Incoming blocks, then the newly
19025ffd83dbSDimitry Andric // created PHI in the Hub will use itself along that edge from Out to Hub.
19035ffd83dbSDimitry Andric static void reconnectPhis(BasicBlock *Out, BasicBlock *GuardBlock,
19045ffd83dbSDimitry Andric                           const SetVector<BasicBlock *> &Incoming,
19055ffd83dbSDimitry Andric                           BasicBlock *FirstGuardBlock) {
19065ffd83dbSDimitry Andric   auto I = Out->begin();
19075ffd83dbSDimitry Andric   while (I != Out->end() && isa<PHINode>(I)) {
19085ffd83dbSDimitry Andric     auto Phi = cast<PHINode>(I);
19095ffd83dbSDimitry Andric     auto NewPhi =
19105ffd83dbSDimitry Andric         PHINode::Create(Phi->getType(), Incoming.size(),
1911*0fca6ea1SDimitry Andric                         Phi->getName() + ".moved", FirstGuardBlock->begin());
1912bdd1243dSDimitry Andric     for (auto *In : Incoming) {
19135ffd83dbSDimitry Andric       Value *V = UndefValue::get(Phi->getType());
19145ffd83dbSDimitry Andric       if (In == Out) {
19155ffd83dbSDimitry Andric         V = NewPhi;
19165ffd83dbSDimitry Andric       } else if (Phi->getBasicBlockIndex(In) != -1) {
19175ffd83dbSDimitry Andric         V = Phi->removeIncomingValue(In, false);
19185ffd83dbSDimitry Andric       }
19195ffd83dbSDimitry Andric       NewPhi->addIncoming(V, In);
19205ffd83dbSDimitry Andric     }
19215ffd83dbSDimitry Andric     assert(NewPhi->getNumIncomingValues() == Incoming.size());
19225ffd83dbSDimitry Andric     if (Phi->getNumOperands() == 0) {
19235ffd83dbSDimitry Andric       Phi->replaceAllUsesWith(NewPhi);
19245ffd83dbSDimitry Andric       I = Phi->eraseFromParent();
19255ffd83dbSDimitry Andric       continue;
19265ffd83dbSDimitry Andric     }
19275ffd83dbSDimitry Andric     Phi->addIncoming(NewPhi, GuardBlock);
19285ffd83dbSDimitry Andric     ++I;
19295ffd83dbSDimitry Andric   }
19305ffd83dbSDimitry Andric }
19315ffd83dbSDimitry Andric 
1932bdd1243dSDimitry Andric using BBPredicates = DenseMap<BasicBlock *, Instruction *>;
19335ffd83dbSDimitry Andric using BBSetVector = SetVector<BasicBlock *>;
19345ffd83dbSDimitry Andric 
19355ffd83dbSDimitry Andric // Redirects the terminator of the incoming block to the first guard
19365ffd83dbSDimitry Andric // block in the hub. The condition of the original terminator (if it
19375ffd83dbSDimitry Andric // was conditional) and its original successors are returned as a
19385ffd83dbSDimitry Andric // tuple <condition, succ0, succ1>. The function additionally filters
19395ffd83dbSDimitry Andric // out successors that are not in the set of outgoing blocks.
19405ffd83dbSDimitry Andric //
19415ffd83dbSDimitry Andric // - condition is non-null iff the branch is conditional.
19425ffd83dbSDimitry Andric // - Succ1 is non-null iff the sole/taken target is an outgoing block.
19435ffd83dbSDimitry Andric // - Succ2 is non-null iff condition is non-null and the fallthrough
19445ffd83dbSDimitry Andric //         target is an outgoing block.
19455ffd83dbSDimitry Andric static std::tuple<Value *, BasicBlock *, BasicBlock *>
19465ffd83dbSDimitry Andric redirectToHub(BasicBlock *BB, BasicBlock *FirstGuardBlock,
19475ffd83dbSDimitry Andric               const BBSetVector &Outgoing) {
1948bdd1243dSDimitry Andric   assert(isa<BranchInst>(BB->getTerminator()) &&
1949bdd1243dSDimitry Andric          "Only support branch terminator.");
19505ffd83dbSDimitry Andric   auto Branch = cast<BranchInst>(BB->getTerminator());
19515ffd83dbSDimitry Andric   auto Condition = Branch->isConditional() ? Branch->getCondition() : nullptr;
19525ffd83dbSDimitry Andric 
19535ffd83dbSDimitry Andric   BasicBlock *Succ0 = Branch->getSuccessor(0);
19545ffd83dbSDimitry Andric   BasicBlock *Succ1 = nullptr;
19555ffd83dbSDimitry Andric   Succ0 = Outgoing.count(Succ0) ? Succ0 : nullptr;
19565ffd83dbSDimitry Andric 
19575ffd83dbSDimitry Andric   if (Branch->isUnconditional()) {
19585ffd83dbSDimitry Andric     Branch->setSuccessor(0, FirstGuardBlock);
19595ffd83dbSDimitry Andric     assert(Succ0);
19605ffd83dbSDimitry Andric   } else {
19615ffd83dbSDimitry Andric     Succ1 = Branch->getSuccessor(1);
19625ffd83dbSDimitry Andric     Succ1 = Outgoing.count(Succ1) ? Succ1 : nullptr;
19635ffd83dbSDimitry Andric     assert(Succ0 || Succ1);
19645ffd83dbSDimitry Andric     if (Succ0 && !Succ1) {
19655ffd83dbSDimitry Andric       Branch->setSuccessor(0, FirstGuardBlock);
19665ffd83dbSDimitry Andric     } else if (Succ1 && !Succ0) {
19675ffd83dbSDimitry Andric       Branch->setSuccessor(1, FirstGuardBlock);
19685ffd83dbSDimitry Andric     } else {
19695ffd83dbSDimitry Andric       Branch->eraseFromParent();
19705ffd83dbSDimitry Andric       BranchInst::Create(FirstGuardBlock, BB);
19715ffd83dbSDimitry Andric     }
19725ffd83dbSDimitry Andric   }
19735ffd83dbSDimitry Andric 
19745ffd83dbSDimitry Andric   assert(Succ0 || Succ1);
19755ffd83dbSDimitry Andric   return std::make_tuple(Condition, Succ0, Succ1);
19765ffd83dbSDimitry Andric }
1977bdd1243dSDimitry Andric // Setup the branch instructions for guard blocks.
19785ffd83dbSDimitry Andric //
19795ffd83dbSDimitry Andric // Each guard block terminates in a conditional branch that transfers
19805ffd83dbSDimitry Andric // control to the corresponding outgoing block or the next guard
19815ffd83dbSDimitry Andric // block. The last guard block has two outgoing blocks as successors
19825ffd83dbSDimitry Andric // since the condition for the final outgoing block is trivially
19835ffd83dbSDimitry Andric // true. So we create one less block (including the first guard block)
19845ffd83dbSDimitry Andric // than the number of outgoing blocks.
1985bdd1243dSDimitry Andric static void setupBranchForGuard(SmallVectorImpl<BasicBlock *> &GuardBlocks,
1986bdd1243dSDimitry Andric                                 const BBSetVector &Outgoing,
1987bdd1243dSDimitry Andric                                 BBPredicates &GuardPredicates) {
19885ffd83dbSDimitry Andric   // To help keep the loop simple, temporarily append the last
19895ffd83dbSDimitry Andric   // outgoing block to the list of guard blocks.
19905ffd83dbSDimitry Andric   GuardBlocks.push_back(Outgoing.back());
19915ffd83dbSDimitry Andric 
19925ffd83dbSDimitry Andric   for (int i = 0, e = GuardBlocks.size() - 1; i != e; ++i) {
19935ffd83dbSDimitry Andric     auto Out = Outgoing[i];
19945ffd83dbSDimitry Andric     assert(GuardPredicates.count(Out));
19955ffd83dbSDimitry Andric     BranchInst::Create(Out, GuardBlocks[i + 1], GuardPredicates[Out],
19965ffd83dbSDimitry Andric                        GuardBlocks[i]);
19975ffd83dbSDimitry Andric   }
19985ffd83dbSDimitry Andric 
19995ffd83dbSDimitry Andric   // Remove the last block from the guard list.
20005ffd83dbSDimitry Andric   GuardBlocks.pop_back();
20015ffd83dbSDimitry Andric }
20025ffd83dbSDimitry Andric 
2003bdd1243dSDimitry Andric /// We are using one integer to represent the block we are branching to. Then at
2004bdd1243dSDimitry Andric /// each guard block, the predicate was calcuated using a simple `icmp eq`.
2005bdd1243dSDimitry Andric static void calcPredicateUsingInteger(
2006bdd1243dSDimitry Andric     const BBSetVector &Incoming, const BBSetVector &Outgoing,
2007bdd1243dSDimitry Andric     SmallVectorImpl<BasicBlock *> &GuardBlocks, BBPredicates &GuardPredicates) {
2008bdd1243dSDimitry Andric   auto &Context = Incoming.front()->getContext();
2009bdd1243dSDimitry Andric   auto FirstGuardBlock = GuardBlocks.front();
2010bdd1243dSDimitry Andric 
2011bdd1243dSDimitry Andric   auto Phi = PHINode::Create(Type::getInt32Ty(Context), Incoming.size(),
2012bdd1243dSDimitry Andric                              "merged.bb.idx", FirstGuardBlock);
2013bdd1243dSDimitry Andric 
2014bdd1243dSDimitry Andric   for (auto In : Incoming) {
2015bdd1243dSDimitry Andric     Value *Condition;
2016bdd1243dSDimitry Andric     BasicBlock *Succ0;
2017bdd1243dSDimitry Andric     BasicBlock *Succ1;
2018bdd1243dSDimitry Andric     std::tie(Condition, Succ0, Succ1) =
2019bdd1243dSDimitry Andric         redirectToHub(In, FirstGuardBlock, Outgoing);
2020bdd1243dSDimitry Andric     Value *IncomingId = nullptr;
2021bdd1243dSDimitry Andric     if (Succ0 && Succ1) {
2022bdd1243dSDimitry Andric       // target_bb_index = Condition ? index_of_succ0 : index_of_succ1.
2023bdd1243dSDimitry Andric       auto Succ0Iter = find(Outgoing, Succ0);
2024bdd1243dSDimitry Andric       auto Succ1Iter = find(Outgoing, Succ1);
2025bdd1243dSDimitry Andric       Value *Id0 = ConstantInt::get(Type::getInt32Ty(Context),
2026bdd1243dSDimitry Andric                                     std::distance(Outgoing.begin(), Succ0Iter));
2027bdd1243dSDimitry Andric       Value *Id1 = ConstantInt::get(Type::getInt32Ty(Context),
2028bdd1243dSDimitry Andric                                     std::distance(Outgoing.begin(), Succ1Iter));
2029bdd1243dSDimitry Andric       IncomingId = SelectInst::Create(Condition, Id0, Id1, "target.bb.idx",
2030*0fca6ea1SDimitry Andric                                       In->getTerminator()->getIterator());
2031bdd1243dSDimitry Andric     } else {
2032bdd1243dSDimitry Andric       // Get the index of the non-null successor.
2033bdd1243dSDimitry Andric       auto SuccIter = Succ0 ? find(Outgoing, Succ0) : find(Outgoing, Succ1);
2034bdd1243dSDimitry Andric       IncomingId = ConstantInt::get(Type::getInt32Ty(Context),
2035bdd1243dSDimitry Andric                                     std::distance(Outgoing.begin(), SuccIter));
2036bdd1243dSDimitry Andric     }
2037bdd1243dSDimitry Andric     Phi->addIncoming(IncomingId, In);
2038bdd1243dSDimitry Andric   }
2039bdd1243dSDimitry Andric 
2040bdd1243dSDimitry Andric   for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
2041bdd1243dSDimitry Andric     auto Out = Outgoing[i];
2042bdd1243dSDimitry Andric     auto Cmp = ICmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, Phi,
2043bdd1243dSDimitry Andric                                 ConstantInt::get(Type::getInt32Ty(Context), i),
2044bdd1243dSDimitry Andric                                 Out->getName() + ".predicate", GuardBlocks[i]);
2045bdd1243dSDimitry Andric     GuardPredicates[Out] = Cmp;
2046bdd1243dSDimitry Andric   }
2047bdd1243dSDimitry Andric }
2048bdd1243dSDimitry Andric 
2049bdd1243dSDimitry Andric /// We record the predicate of each outgoing block using a phi of boolean.
2050bdd1243dSDimitry Andric static void calcPredicateUsingBooleans(
2051bdd1243dSDimitry Andric     const BBSetVector &Incoming, const BBSetVector &Outgoing,
2052bdd1243dSDimitry Andric     SmallVectorImpl<BasicBlock *> &GuardBlocks, BBPredicates &GuardPredicates,
2053bdd1243dSDimitry Andric     SmallVectorImpl<WeakVH> &DeletionCandidates) {
2054bdd1243dSDimitry Andric   auto &Context = Incoming.front()->getContext();
2055bdd1243dSDimitry Andric   auto BoolTrue = ConstantInt::getTrue(Context);
2056bdd1243dSDimitry Andric   auto BoolFalse = ConstantInt::getFalse(Context);
2057bdd1243dSDimitry Andric   auto FirstGuardBlock = GuardBlocks.front();
2058bdd1243dSDimitry Andric 
2059bdd1243dSDimitry Andric   // The predicate for the last outgoing is trivially true, and so we
2060bdd1243dSDimitry Andric   // process only the first N-1 successors.
2061bdd1243dSDimitry Andric   for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
2062bdd1243dSDimitry Andric     auto Out = Outgoing[i];
2063bdd1243dSDimitry Andric     LLVM_DEBUG(dbgs() << "Creating guard for " << Out->getName() << "\n");
2064bdd1243dSDimitry Andric 
2065bdd1243dSDimitry Andric     auto Phi =
2066bdd1243dSDimitry Andric         PHINode::Create(Type::getInt1Ty(Context), Incoming.size(),
2067bdd1243dSDimitry Andric                         StringRef("Guard.") + Out->getName(), FirstGuardBlock);
2068bdd1243dSDimitry Andric     GuardPredicates[Out] = Phi;
2069bdd1243dSDimitry Andric   }
2070bdd1243dSDimitry Andric 
2071bdd1243dSDimitry Andric   for (auto *In : Incoming) {
2072bdd1243dSDimitry Andric     Value *Condition;
2073bdd1243dSDimitry Andric     BasicBlock *Succ0;
2074bdd1243dSDimitry Andric     BasicBlock *Succ1;
2075bdd1243dSDimitry Andric     std::tie(Condition, Succ0, Succ1) =
2076bdd1243dSDimitry Andric         redirectToHub(In, FirstGuardBlock, Outgoing);
2077bdd1243dSDimitry Andric 
2078bdd1243dSDimitry Andric     // Optimization: Consider an incoming block A with both successors
2079bdd1243dSDimitry Andric     // Succ0 and Succ1 in the set of outgoing blocks. The predicates
2080bdd1243dSDimitry Andric     // for Succ0 and Succ1 complement each other. If Succ0 is visited
2081bdd1243dSDimitry Andric     // first in the loop below, control will branch to Succ0 using the
2082bdd1243dSDimitry Andric     // corresponding predicate. But if that branch is not taken, then
2083bdd1243dSDimitry Andric     // control must reach Succ1, which means that the incoming value of
2084bdd1243dSDimitry Andric     // the predicate from `In` is true for Succ1.
2085bdd1243dSDimitry Andric     bool OneSuccessorDone = false;
2086bdd1243dSDimitry Andric     for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
2087bdd1243dSDimitry Andric       auto Out = Outgoing[i];
2088bdd1243dSDimitry Andric       PHINode *Phi = cast<PHINode>(GuardPredicates[Out]);
2089bdd1243dSDimitry Andric       if (Out != Succ0 && Out != Succ1) {
2090bdd1243dSDimitry Andric         Phi->addIncoming(BoolFalse, In);
2091bdd1243dSDimitry Andric       } else if (!Succ0 || !Succ1 || OneSuccessorDone) {
2092bdd1243dSDimitry Andric         // Optimization: When only one successor is an outgoing block,
2093bdd1243dSDimitry Andric         // the incoming predicate from `In` is always true.
2094bdd1243dSDimitry Andric         Phi->addIncoming(BoolTrue, In);
2095bdd1243dSDimitry Andric       } else {
2096bdd1243dSDimitry Andric         assert(Succ0 && Succ1);
2097bdd1243dSDimitry Andric         if (Out == Succ0) {
2098bdd1243dSDimitry Andric           Phi->addIncoming(Condition, In);
2099bdd1243dSDimitry Andric         } else {
2100bdd1243dSDimitry Andric           auto Inverted = invertCondition(Condition);
2101bdd1243dSDimitry Andric           DeletionCandidates.push_back(Condition);
2102bdd1243dSDimitry Andric           Phi->addIncoming(Inverted, In);
2103bdd1243dSDimitry Andric         }
2104bdd1243dSDimitry Andric         OneSuccessorDone = true;
2105bdd1243dSDimitry Andric       }
2106bdd1243dSDimitry Andric     }
2107bdd1243dSDimitry Andric   }
2108bdd1243dSDimitry Andric }
2109bdd1243dSDimitry Andric 
2110bdd1243dSDimitry Andric // Capture the existing control flow as guard predicates, and redirect
2111bdd1243dSDimitry Andric // control flow from \p Incoming block through the \p GuardBlocks to the
2112bdd1243dSDimitry Andric // \p Outgoing blocks.
2113bdd1243dSDimitry Andric //
2114bdd1243dSDimitry Andric // There is one guard predicate for each outgoing block OutBB. The
2115bdd1243dSDimitry Andric // predicate represents whether the hub should transfer control flow
2116bdd1243dSDimitry Andric // to OutBB. These predicates are NOT ORTHOGONAL. The Hub evaluates
2117bdd1243dSDimitry Andric // them in the same order as the Outgoing set-vector, and control
2118bdd1243dSDimitry Andric // branches to the first outgoing block whose predicate evaluates to true.
2119bdd1243dSDimitry Andric static void
2120bdd1243dSDimitry Andric convertToGuardPredicates(SmallVectorImpl<BasicBlock *> &GuardBlocks,
2121bdd1243dSDimitry Andric                          SmallVectorImpl<WeakVH> &DeletionCandidates,
2122bdd1243dSDimitry Andric                          const BBSetVector &Incoming,
2123bdd1243dSDimitry Andric                          const BBSetVector &Outgoing, const StringRef Prefix,
2124bdd1243dSDimitry Andric                          std::optional<unsigned> MaxControlFlowBooleans) {
2125bdd1243dSDimitry Andric   BBPredicates GuardPredicates;
2126bdd1243dSDimitry Andric   auto F = Incoming.front()->getParent();
2127bdd1243dSDimitry Andric 
2128bdd1243dSDimitry Andric   for (int i = 0, e = Outgoing.size() - 1; i != e; ++i)
2129bdd1243dSDimitry Andric     GuardBlocks.push_back(
2130bdd1243dSDimitry Andric         BasicBlock::Create(F->getContext(), Prefix + ".guard", F));
2131bdd1243dSDimitry Andric 
2132bdd1243dSDimitry Andric   // When we are using an integer to record which target block to jump to, we
2133bdd1243dSDimitry Andric   // are creating less live values, actually we are using one single integer to
2134bdd1243dSDimitry Andric   // store the index of the target block. When we are using booleans to store
2135bdd1243dSDimitry Andric   // the branching information, we need (N-1) boolean values, where N is the
2136bdd1243dSDimitry Andric   // number of outgoing block.
2137bdd1243dSDimitry Andric   if (!MaxControlFlowBooleans || Outgoing.size() <= *MaxControlFlowBooleans)
2138bdd1243dSDimitry Andric     calcPredicateUsingBooleans(Incoming, Outgoing, GuardBlocks, GuardPredicates,
2139bdd1243dSDimitry Andric                                DeletionCandidates);
2140bdd1243dSDimitry Andric   else
2141bdd1243dSDimitry Andric     calcPredicateUsingInteger(Incoming, Outgoing, GuardBlocks, GuardPredicates);
2142bdd1243dSDimitry Andric 
2143bdd1243dSDimitry Andric   setupBranchForGuard(GuardBlocks, Outgoing, GuardPredicates);
2144bdd1243dSDimitry Andric }
2145bdd1243dSDimitry Andric 
21465ffd83dbSDimitry Andric BasicBlock *llvm::CreateControlFlowHub(
21475ffd83dbSDimitry Andric     DomTreeUpdater *DTU, SmallVectorImpl<BasicBlock *> &GuardBlocks,
21485ffd83dbSDimitry Andric     const BBSetVector &Incoming, const BBSetVector &Outgoing,
2149bdd1243dSDimitry Andric     const StringRef Prefix, std::optional<unsigned> MaxControlFlowBooleans) {
2150bdd1243dSDimitry Andric   if (Outgoing.size() < 2)
2151bdd1243dSDimitry Andric     return Outgoing.front();
21525ffd83dbSDimitry Andric 
21535ffd83dbSDimitry Andric   SmallVector<DominatorTree::UpdateType, 16> Updates;
21545ffd83dbSDimitry Andric   if (DTU) {
2155bdd1243dSDimitry Andric     for (auto *In : Incoming) {
2156bdd1243dSDimitry Andric       for (auto Succ : successors(In))
21575ffd83dbSDimitry Andric         if (Outgoing.count(Succ))
21585ffd83dbSDimitry Andric           Updates.push_back({DominatorTree::Delete, In, Succ});
21595ffd83dbSDimitry Andric     }
21605ffd83dbSDimitry Andric   }
21615ffd83dbSDimitry Andric 
21625ffd83dbSDimitry Andric   SmallVector<WeakVH, 8> DeletionCandidates;
2163bdd1243dSDimitry Andric   convertToGuardPredicates(GuardBlocks, DeletionCandidates, Incoming, Outgoing,
2164bdd1243dSDimitry Andric                            Prefix, MaxControlFlowBooleans);
2165bdd1243dSDimitry Andric   auto FirstGuardBlock = GuardBlocks.front();
21665ffd83dbSDimitry Andric 
21675ffd83dbSDimitry Andric   // Update the PHINodes in each outgoing block to match the new control flow.
2168bdd1243dSDimitry Andric   for (int i = 0, e = GuardBlocks.size(); i != e; ++i)
21695ffd83dbSDimitry Andric     reconnectPhis(Outgoing[i], GuardBlocks[i], Incoming, FirstGuardBlock);
2170bdd1243dSDimitry Andric 
21715ffd83dbSDimitry Andric   reconnectPhis(Outgoing.back(), GuardBlocks.back(), Incoming, FirstGuardBlock);
21725ffd83dbSDimitry Andric 
21735ffd83dbSDimitry Andric   if (DTU) {
21745ffd83dbSDimitry Andric     int NumGuards = GuardBlocks.size();
21755ffd83dbSDimitry Andric     assert((int)Outgoing.size() == NumGuards + 1);
2176bdd1243dSDimitry Andric 
2177bdd1243dSDimitry Andric     for (auto In : Incoming)
2178bdd1243dSDimitry Andric       Updates.push_back({DominatorTree::Insert, In, FirstGuardBlock});
2179bdd1243dSDimitry Andric 
21805ffd83dbSDimitry Andric     for (int i = 0; i != NumGuards - 1; ++i) {
21815ffd83dbSDimitry Andric       Updates.push_back({DominatorTree::Insert, GuardBlocks[i], Outgoing[i]});
21825ffd83dbSDimitry Andric       Updates.push_back(
21835ffd83dbSDimitry Andric           {DominatorTree::Insert, GuardBlocks[i], GuardBlocks[i + 1]});
21845ffd83dbSDimitry Andric     }
21855ffd83dbSDimitry Andric     Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1],
21865ffd83dbSDimitry Andric                        Outgoing[NumGuards - 1]});
21875ffd83dbSDimitry Andric     Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1],
21885ffd83dbSDimitry Andric                        Outgoing[NumGuards]});
21895ffd83dbSDimitry Andric     DTU->applyUpdates(Updates);
21905ffd83dbSDimitry Andric   }
21915ffd83dbSDimitry Andric 
21925ffd83dbSDimitry Andric   for (auto I : DeletionCandidates) {
21935ffd83dbSDimitry Andric     if (I->use_empty())
21945ffd83dbSDimitry Andric       if (auto Inst = dyn_cast_or_null<Instruction>(I))
21955ffd83dbSDimitry Andric         Inst->eraseFromParent();
21965ffd83dbSDimitry Andric   }
21975ffd83dbSDimitry Andric 
21985ffd83dbSDimitry Andric   return FirstGuardBlock;
21995ffd83dbSDimitry Andric }
220006c3fb27SDimitry Andric 
220106c3fb27SDimitry Andric void llvm::InvertBranch(BranchInst *PBI, IRBuilderBase &Builder) {
220206c3fb27SDimitry Andric   Value *NewCond = PBI->getCondition();
220306c3fb27SDimitry Andric   // If this is a "cmp" instruction, only used for branching (and nowhere
220406c3fb27SDimitry Andric   // else), then we can simply invert the predicate.
220506c3fb27SDimitry Andric   if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
220606c3fb27SDimitry Andric     CmpInst *CI = cast<CmpInst>(NewCond);
220706c3fb27SDimitry Andric     CI->setPredicate(CI->getInversePredicate());
220806c3fb27SDimitry Andric   } else
220906c3fb27SDimitry Andric     NewCond = Builder.CreateNot(NewCond, NewCond->getName() + ".not");
221006c3fb27SDimitry Andric 
221106c3fb27SDimitry Andric   PBI->setCondition(NewCond);
221206c3fb27SDimitry Andric   PBI->swapSuccessors();
221306c3fb27SDimitry Andric }
22145f757f3fSDimitry Andric 
22155f757f3fSDimitry Andric bool llvm::hasOnlySimpleTerminator(const Function &F) {
22165f757f3fSDimitry Andric   for (auto &BB : F) {
22175f757f3fSDimitry Andric     auto *Term = BB.getTerminator();
22185f757f3fSDimitry Andric     if (!(isa<ReturnInst>(Term) || isa<UnreachableInst>(Term) ||
22195f757f3fSDimitry Andric           isa<BranchInst>(Term)))
22205f757f3fSDimitry Andric       return false;
22215f757f3fSDimitry Andric   }
22225f757f3fSDimitry Andric   return true;
22235f757f3fSDimitry Andric }
22245f757f3fSDimitry Andric 
22255f757f3fSDimitry Andric bool llvm::isPresplitCoroSuspendExitEdge(const BasicBlock &Src,
22265f757f3fSDimitry Andric                                          const BasicBlock &Dest) {
22275f757f3fSDimitry Andric   assert(Src.getParent() == Dest.getParent());
22285f757f3fSDimitry Andric   if (!Src.getParent()->isPresplitCoroutine())
22295f757f3fSDimitry Andric     return false;
22305f757f3fSDimitry Andric   if (auto *SW = dyn_cast<SwitchInst>(Src.getTerminator()))
22315f757f3fSDimitry Andric     if (auto *Intr = dyn_cast<IntrinsicInst>(SW->getCondition()))
22325f757f3fSDimitry Andric       return Intr->getIntrinsicID() == Intrinsic::coro_suspend &&
22335f757f3fSDimitry Andric              SW->getDefaultDest() == &Dest;
22345f757f3fSDimitry Andric   return false;
22355f757f3fSDimitry Andric }
2236