xref: /src/contrib/llvm-project/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1044eb2f6SDimitry Andric //===- BasicBlockUtils.cpp - BasicBlock Utilities --------------------------==//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This family of functions perform manipulations on basic blocks, and
10009b1c42SEd Schouten // instructions contained within basic blocks.
11009b1c42SEd Schouten //
12009b1c42SEd Schouten //===----------------------------------------------------------------------===//
13009b1c42SEd Schouten 
14009b1c42SEd Schouten #include "llvm/Transforms/Utils/BasicBlockUtils.h"
15044eb2f6SDimitry Andric #include "llvm/ADT/ArrayRef.h"
16044eb2f6SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
17044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
18044eb2f6SDimitry Andric #include "llvm/ADT/Twine.h"
19f8af5cf6SDimitry Andric #include "llvm/Analysis/CFG.h"
20e6d15924SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
21cf099d11SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
22cf099d11SDimitry Andric #include "llvm/Analysis/MemoryDependenceAnalysis.h"
23d8e91e46SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
24044eb2f6SDimitry Andric #include "llvm/IR/BasicBlock.h"
25044eb2f6SDimitry Andric #include "llvm/IR/CFG.h"
26044eb2f6SDimitry Andric #include "llvm/IR/Constants.h"
27e3b55780SDimitry Andric #include "llvm/IR/DebugInfo.h"
28044eb2f6SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
295ca98fd9SDimitry Andric #include "llvm/IR/Dominators.h"
304a16efa3SDimitry Andric #include "llvm/IR/Function.h"
31044eb2f6SDimitry Andric #include "llvm/IR/InstrTypes.h"
32044eb2f6SDimitry Andric #include "llvm/IR/Instruction.h"
334a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
344a16efa3SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
357fa27ce4SDimitry Andric #include "llvm/IR/IRBuilder.h"
36044eb2f6SDimitry Andric #include "llvm/IR/LLVMContext.h"
374a16efa3SDimitry Andric #include "llvm/IR/Type.h"
38044eb2f6SDimitry Andric #include "llvm/IR/User.h"
39044eb2f6SDimitry Andric #include "llvm/IR/Value.h"
405ca98fd9SDimitry Andric #include "llvm/IR/ValueHandle.h"
41044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
42c0981da4SDimitry Andric #include "llvm/Support/CommandLine.h"
43e6d15924SDimitry Andric #include "llvm/Support/Debug.h"
44e6d15924SDimitry Andric #include "llvm/Support/raw_ostream.h"
45d8e91e46SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
46044eb2f6SDimitry Andric #include <cassert>
47044eb2f6SDimitry Andric #include <cstdint>
48044eb2f6SDimitry Andric #include <string>
49044eb2f6SDimitry Andric #include <utility>
50044eb2f6SDimitry Andric #include <vector>
51044eb2f6SDimitry Andric 
52009b1c42SEd Schouten using namespace llvm;
53009b1c42SEd Schouten 
54e6d15924SDimitry Andric #define DEBUG_TYPE "basicblock-utils"
55009b1c42SEd Schouten 
56c0981da4SDimitry Andric static cl::opt<unsigned> MaxDeoptOrUnreachableSuccessorCheckDepth(
57c0981da4SDimitry Andric     "max-deopt-or-unreachable-succ-check-depth", cl::init(8), cl::Hidden,
58c0981da4SDimitry Andric     cl::desc("Set the maximum path length when checking whether a basic block "
59c0981da4SDimitry Andric              "is followed by a block that either has a terminating "
60c0981da4SDimitry Andric              "deoptimizing call or is terminated with an unreachable"));
61c0981da4SDimitry Andric 
detachDeadBlocks(ArrayRef<BasicBlock * > BBs,SmallVectorImpl<DominatorTree::UpdateType> * Updates,bool KeepOneInputPHIs)62ecbca9f5SDimitry Andric void llvm::detachDeadBlocks(
63e6d15924SDimitry Andric     ArrayRef<BasicBlock *> BBs,
64e6d15924SDimitry Andric     SmallVectorImpl<DominatorTree::UpdateType> *Updates,
65e6d15924SDimitry Andric     bool KeepOneInputPHIs) {
66d8e91e46SDimitry Andric   for (auto *BB : BBs) {
67009b1c42SEd Schouten     // Loop through all of our successors and make sure they know that one
68009b1c42SEd Schouten     // of their predecessors is going away.
69e6d15924SDimitry Andric     SmallPtrSet<BasicBlock *, 4> UniqueSuccessors;
70d8e91e46SDimitry Andric     for (BasicBlock *Succ : successors(BB)) {
71e6d15924SDimitry Andric       Succ->removePredecessor(BB, KeepOneInputPHIs);
72e6d15924SDimitry Andric       if (Updates && UniqueSuccessors.insert(Succ).second)
73e6d15924SDimitry Andric         Updates->push_back({DominatorTree::Delete, BB, Succ});
74eb11fae6SDimitry Andric     }
75009b1c42SEd Schouten 
76009b1c42SEd Schouten     // Zap all the instructions in the block.
77009b1c42SEd Schouten     while (!BB->empty()) {
78009b1c42SEd Schouten       Instruction &I = BB->back();
79009b1c42SEd Schouten       // If this instruction is used, replace uses with an arbitrary value.
80009b1c42SEd Schouten       // Because control flow can't get here, we don't care what we replace the
81009b1c42SEd Schouten       // value with.  Note that since this block is unreachable, and all values
82009b1c42SEd Schouten       // contained within it must dominate their uses, that all uses will
83009b1c42SEd Schouten       // eventually be removed (they are themselves dead).
84009b1c42SEd Schouten       if (!I.use_empty())
854b4fe385SDimitry Andric         I.replaceAllUsesWith(PoisonValue::get(I.getType()));
86e3b55780SDimitry Andric       BB->back().eraseFromParent();
87009b1c42SEd Schouten     }
88d8e91e46SDimitry Andric     new UnreachableInst(BB->getContext(), BB);
89e3b55780SDimitry Andric     assert(BB->size() == 1 &&
90d8e91e46SDimitry Andric            isa<UnreachableInst>(BB->getTerminator()) &&
91d8e91e46SDimitry Andric            "The successor list of BB isn't empty before "
92d8e91e46SDimitry Andric            "applying corresponding DTU updates.");
93eb11fae6SDimitry Andric   }
94e6d15924SDimitry Andric }
95e6d15924SDimitry Andric 
DeleteDeadBlock(BasicBlock * BB,DomTreeUpdater * DTU,bool KeepOneInputPHIs)96e6d15924SDimitry Andric void llvm::DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU,
97e6d15924SDimitry Andric                            bool KeepOneInputPHIs) {
98e6d15924SDimitry Andric   DeleteDeadBlocks({BB}, DTU, KeepOneInputPHIs);
99e6d15924SDimitry Andric }
100e6d15924SDimitry Andric 
DeleteDeadBlocks(ArrayRef<BasicBlock * > BBs,DomTreeUpdater * DTU,bool KeepOneInputPHIs)101e6d15924SDimitry Andric void llvm::DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs, DomTreeUpdater *DTU,
102e6d15924SDimitry Andric                             bool KeepOneInputPHIs) {
103e6d15924SDimitry Andric #ifndef NDEBUG
104e6d15924SDimitry Andric   // Make sure that all predecessors of each dead block is also dead.
105e6d15924SDimitry Andric   SmallPtrSet<BasicBlock *, 4> Dead(BBs.begin(), BBs.end());
106e6d15924SDimitry Andric   assert(Dead.size() == BBs.size() && "Duplicating blocks?");
107e6d15924SDimitry Andric   for (auto *BB : Dead)
108e6d15924SDimitry Andric     for (BasicBlock *Pred : predecessors(BB))
109e6d15924SDimitry Andric       assert(Dead.count(Pred) && "All predecessors must be dead!");
110e6d15924SDimitry Andric #endif
111e6d15924SDimitry Andric 
112e6d15924SDimitry Andric   SmallVector<DominatorTree::UpdateType, 4> Updates;
113ecbca9f5SDimitry Andric   detachDeadBlocks(BBs, DTU ? &Updates : nullptr, KeepOneInputPHIs);
114e6d15924SDimitry Andric 
115d8e91e46SDimitry Andric   if (DTU)
116b60736ecSDimitry Andric     DTU->applyUpdates(Updates);
117d8e91e46SDimitry Andric 
118d8e91e46SDimitry Andric   for (BasicBlock *BB : BBs)
119d8e91e46SDimitry Andric     if (DTU)
120d8e91e46SDimitry Andric       DTU->deleteBB(BB);
121d8e91e46SDimitry Andric     else
122d8e91e46SDimitry Andric       BB->eraseFromParent();
123009b1c42SEd Schouten }
124009b1c42SEd Schouten 
EliminateUnreachableBlocks(Function & F,DomTreeUpdater * DTU,bool KeepOneInputPHIs)125e6d15924SDimitry Andric bool llvm::EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
126e6d15924SDimitry Andric                                       bool KeepOneInputPHIs) {
127e6d15924SDimitry Andric   df_iterator_default_set<BasicBlock*> Reachable;
128e6d15924SDimitry Andric 
129e6d15924SDimitry Andric   // Mark all reachable blocks.
130e6d15924SDimitry Andric   for (BasicBlock *BB : depth_first_ext(&F, Reachable))
131e6d15924SDimitry Andric     (void)BB/* Mark all reachable blocks */;
132e6d15924SDimitry Andric 
133e6d15924SDimitry Andric   // Collect all dead blocks.
134e6d15924SDimitry Andric   std::vector<BasicBlock*> DeadBlocks;
135344a3780SDimitry Andric   for (BasicBlock &BB : F)
136344a3780SDimitry Andric     if (!Reachable.count(&BB))
137344a3780SDimitry Andric       DeadBlocks.push_back(&BB);
138e6d15924SDimitry Andric 
139e6d15924SDimitry Andric   // Delete the dead blocks.
140e6d15924SDimitry Andric   DeleteDeadBlocks(DeadBlocks, DTU, KeepOneInputPHIs);
141e6d15924SDimitry Andric 
142e6d15924SDimitry Andric   return !DeadBlocks.empty();
143e6d15924SDimitry Andric }
144e6d15924SDimitry Andric 
FoldSingleEntryPHINodes(BasicBlock * BB,MemoryDependenceResults * MemDep)145b60736ecSDimitry Andric bool llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
14601095a5dSDimitry Andric                                    MemoryDependenceResults *MemDep) {
147b60736ecSDimitry Andric   if (!isa<PHINode>(BB->begin()))
148b60736ecSDimitry Andric     return false;
149cf099d11SDimitry Andric 
150009b1c42SEd Schouten   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
151009b1c42SEd Schouten     if (PN->getIncomingValue(0) != PN)
152009b1c42SEd Schouten       PN->replaceAllUsesWith(PN->getIncomingValue(0));
153009b1c42SEd Schouten     else
154e3b55780SDimitry Andric       PN->replaceAllUsesWith(PoisonValue::get(PN->getType()));
155cf099d11SDimitry Andric 
156cf099d11SDimitry Andric     if (MemDep)
157cf099d11SDimitry Andric       MemDep->removeInstruction(PN);  // Memdep updates AA itself.
158cf099d11SDimitry Andric 
159009b1c42SEd Schouten     PN->eraseFromParent();
160009b1c42SEd Schouten   }
161b60736ecSDimitry Andric   return true;
162009b1c42SEd Schouten }
163009b1c42SEd Schouten 
DeleteDeadPHIs(BasicBlock * BB,const TargetLibraryInfo * TLI,MemorySSAUpdater * MSSAU)164cfca06d7SDimitry Andric bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI,
165cfca06d7SDimitry Andric                           MemorySSAUpdater *MSSAU) {
166009b1c42SEd Schouten   // Recursively deleting a PHI may cause multiple PHIs to be deleted
167a303c417SDimitry Andric   // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
168a303c417SDimitry Andric   SmallVector<WeakTrackingVH, 8> PHIs;
169eb11fae6SDimitry Andric   for (PHINode &PN : BB->phis())
170eb11fae6SDimitry Andric     PHIs.push_back(&PN);
171009b1c42SEd Schouten 
172829000e0SRoman Divacky   bool Changed = false;
173009b1c42SEd Schouten   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
174009b1c42SEd Schouten     if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
175cfca06d7SDimitry Andric       Changed |= RecursivelyDeleteDeadPHINode(PN, TLI, MSSAU);
176829000e0SRoman Divacky 
177829000e0SRoman Divacky   return Changed;
178009b1c42SEd Schouten }
179009b1c42SEd Schouten 
MergeBlockIntoPredecessor(BasicBlock * BB,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,MemoryDependenceResults * MemDep,bool PredecessorWithTwoSuccessors,DominatorTree * DT)180d8e91e46SDimitry Andric bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU,
181d8e91e46SDimitry Andric                                      LoopInfo *LI, MemorySSAUpdater *MSSAU,
1821d5ae102SDimitry Andric                                      MemoryDependenceResults *MemDep,
183e3b55780SDimitry Andric                                      bool PredecessorWithTwoSuccessors,
184e3b55780SDimitry Andric                                      DominatorTree *DT) {
185eb11fae6SDimitry Andric   if (BB->hasAddressTaken())
186eb11fae6SDimitry Andric     return false;
187009b1c42SEd Schouten 
188d39c594dSDimitry Andric   // Can't merge if there are multiple predecessors, or no predecessors.
189d39c594dSDimitry Andric   BasicBlock *PredBB = BB->getUniquePredecessor();
190009b1c42SEd Schouten   if (!PredBB) return false;
191d39c594dSDimitry Andric 
192009b1c42SEd Schouten   // Don't break self-loops.
193009b1c42SEd Schouten   if (PredBB == BB) return false;
1944b4fe385SDimitry Andric 
1954b4fe385SDimitry Andric   // Don't break unwinding instructions or terminators with other side-effects.
1964b4fe385SDimitry Andric   Instruction *PTI = PredBB->getTerminator();
197b1c73532SDimitry Andric   if (PTI->isSpecialTerminator() || PTI->mayHaveSideEffects())
198dd58ef01SDimitry Andric     return false;
199009b1c42SEd Schouten 
200eb11fae6SDimitry Andric   // Can't merge if there are multiple distinct successors.
2011d5ae102SDimitry Andric   if (!PredecessorWithTwoSuccessors && PredBB->getUniqueSuccessor() != BB)
202eb11fae6SDimitry Andric     return false;
203009b1c42SEd Schouten 
2041d5ae102SDimitry Andric   // Currently only allow PredBB to have two predecessors, one being BB.
2051d5ae102SDimitry Andric   // Update BI to branch to BB's only successor instead of BB.
2061d5ae102SDimitry Andric   BranchInst *PredBB_BI;
2071d5ae102SDimitry Andric   BasicBlock *NewSucc = nullptr;
2081d5ae102SDimitry Andric   unsigned FallThruPath;
2091d5ae102SDimitry Andric   if (PredecessorWithTwoSuccessors) {
2104b4fe385SDimitry Andric     if (!(PredBB_BI = dyn_cast<BranchInst>(PTI)))
2111d5ae102SDimitry Andric       return false;
2121d5ae102SDimitry Andric     BranchInst *BB_JmpI = dyn_cast<BranchInst>(BB->getTerminator());
2131d5ae102SDimitry Andric     if (!BB_JmpI || !BB_JmpI->isUnconditional())
2141d5ae102SDimitry Andric       return false;
2151d5ae102SDimitry Andric     NewSucc = BB_JmpI->getSuccessor(0);
2161d5ae102SDimitry Andric     FallThruPath = PredBB_BI->getSuccessor(0) == BB ? 0 : 1;
2171d5ae102SDimitry Andric   }
2181d5ae102SDimitry Andric 
219009b1c42SEd Schouten   // Can't merge if there is PHI loop.
220eb11fae6SDimitry Andric   for (PHINode &PN : BB->phis())
221344a3780SDimitry Andric     if (llvm::is_contained(PN.incoming_values(), &PN))
222009b1c42SEd Schouten       return false;
223009b1c42SEd Schouten 
224e6d15924SDimitry Andric   LLVM_DEBUG(dbgs() << "Merging: " << BB->getName() << " into "
225e6d15924SDimitry Andric                     << PredBB->getName() << "\n");
226e6d15924SDimitry Andric 
227009b1c42SEd Schouten   // Begin by getting rid of unneeded PHIs.
228eb11fae6SDimitry Andric   SmallVector<AssertingVH<Value>, 4> IncomingValues;
229044eb2f6SDimitry Andric   if (isa<PHINode>(BB->front())) {
230eb11fae6SDimitry Andric     for (PHINode &PN : BB->phis())
231eb11fae6SDimitry Andric       if (!isa<PHINode>(PN.getIncomingValue(0)) ||
232eb11fae6SDimitry Andric           cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
233eb11fae6SDimitry Andric         IncomingValues.push_back(PN.getIncomingValue(0));
234dd58ef01SDimitry Andric     FoldSingleEntryPHINodes(BB, MemDep);
235044eb2f6SDimitry Andric   }
236009b1c42SEd Schouten 
237e3b55780SDimitry Andric   if (DT) {
238e3b55780SDimitry Andric     assert(!DTU && "cannot use both DT and DTU for updates");
239e3b55780SDimitry Andric     DomTreeNode *PredNode = DT->getNode(PredBB);
240e3b55780SDimitry Andric     DomTreeNode *BBNode = DT->getNode(BB);
241e3b55780SDimitry Andric     if (PredNode) {
242e3b55780SDimitry Andric       assert(BBNode && "PredNode unreachable but BBNode reachable?");
243e3b55780SDimitry Andric       for (DomTreeNode *C : to_vector(BBNode->children()))
244e3b55780SDimitry Andric         C->setIDom(PredNode);
245e3b55780SDimitry Andric     }
246e3b55780SDimitry Andric   }
247d8e91e46SDimitry Andric   // DTU update: Collect all the edges that exit BB.
248d8e91e46SDimitry Andric   // These dominator edges will be redirected from Pred.
249eb11fae6SDimitry Andric   std::vector<DominatorTree::UpdateType> Updates;
250d8e91e46SDimitry Andric   if (DTU) {
251e3b55780SDimitry Andric     assert(!DT && "cannot use both DT and DTU for updates");
252f65dcba8SDimitry Andric     // To avoid processing the same predecessor more than once.
253f65dcba8SDimitry Andric     SmallPtrSet<BasicBlock *, 8> SeenSuccs;
254344a3780SDimitry Andric     SmallPtrSet<BasicBlock *, 2> SuccsOfPredBB(succ_begin(PredBB),
255c0981da4SDimitry Andric                                                succ_end(PredBB));
256f65dcba8SDimitry Andric     Updates.reserve(Updates.size() + 2 * succ_size(BB) + 1);
257e6d15924SDimitry Andric     // Add insert edges first. Experimentally, for the particular case of two
258e6d15924SDimitry Andric     // blocks that can be merged, with a single successor and single predecessor
259e6d15924SDimitry Andric     // respectively, it is beneficial to have all insert updates first. Deleting
260e6d15924SDimitry Andric     // edges first may lead to unreachable blocks, followed by inserting edges
261e6d15924SDimitry Andric     // making the blocks reachable again. Such DT updates lead to high compile
262e6d15924SDimitry Andric     // times. We add inserts before deletes here to reduce compile time.
263f65dcba8SDimitry Andric     for (BasicBlock *SuccOfBB : successors(BB))
264344a3780SDimitry Andric       // This successor of BB may already be a PredBB's successor.
265344a3780SDimitry Andric       if (!SuccsOfPredBB.contains(SuccOfBB))
266f65dcba8SDimitry Andric         if (SeenSuccs.insert(SuccOfBB).second)
267344a3780SDimitry Andric           Updates.push_back({DominatorTree::Insert, PredBB, SuccOfBB});
268f65dcba8SDimitry Andric     SeenSuccs.clear();
269f65dcba8SDimitry Andric     for (BasicBlock *SuccOfBB : successors(BB))
270f65dcba8SDimitry Andric       if (SeenSuccs.insert(SuccOfBB).second)
271344a3780SDimitry Andric         Updates.push_back({DominatorTree::Delete, BB, SuccOfBB});
272e6d15924SDimitry Andric     Updates.push_back({DominatorTree::Delete, PredBB, BB});
273eb11fae6SDimitry Andric   }
274eb11fae6SDimitry Andric 
2751d5ae102SDimitry Andric   Instruction *STI = BB->getTerminator();
2761d5ae102SDimitry Andric   Instruction *Start = &*BB->begin();
2771d5ae102SDimitry Andric   // If there's nothing to move, mark the starting instruction as the last
278706b4fc4SDimitry Andric   // instruction in the block. Terminator instruction is handled separately.
2791d5ae102SDimitry Andric   if (Start == STI)
2801d5ae102SDimitry Andric     Start = PTI;
281d8e91e46SDimitry Andric 
2821d5ae102SDimitry Andric   // Move all definitions in the successor to the predecessor...
283e3b55780SDimitry Andric   PredBB->splice(PTI->getIterator(), BB, BB->begin(), STI->getIterator());
2841d5ae102SDimitry Andric 
2851d5ae102SDimitry Andric   if (MSSAU)
2861d5ae102SDimitry Andric     MSSAU->moveAllAfterMergeBlocks(BB, PredBB, Start);
287009b1c42SEd Schouten 
288009b1c42SEd Schouten   // Make all PHI nodes that referred to BB now refer to Pred as their
289009b1c42SEd Schouten   // source...
290009b1c42SEd Schouten   BB->replaceAllUsesWith(PredBB);
291009b1c42SEd Schouten 
2921d5ae102SDimitry Andric   if (PredecessorWithTwoSuccessors) {
2931d5ae102SDimitry Andric     // Delete the unconditional branch from BB.
294e3b55780SDimitry Andric     BB->back().eraseFromParent();
2951d5ae102SDimitry Andric 
2961d5ae102SDimitry Andric     // Update branch in the predecessor.
2971d5ae102SDimitry Andric     PredBB_BI->setSuccessor(FallThruPath, NewSucc);
2981d5ae102SDimitry Andric   } else {
2991d5ae102SDimitry Andric     // Delete the unconditional branch from the predecessor.
300e3b55780SDimitry Andric     PredBB->back().eraseFromParent();
3011d5ae102SDimitry Andric 
3021d5ae102SDimitry Andric     // Move terminator instruction.
303b1c73532SDimitry Andric     BB->back().moveBeforePreserving(*PredBB, PredBB->end());
304706b4fc4SDimitry Andric 
305706b4fc4SDimitry Andric     // Terminator may be a memory accessing instruction too.
306706b4fc4SDimitry Andric     if (MSSAU)
307706b4fc4SDimitry Andric       if (MemoryUseOrDef *MUD = cast_or_null<MemoryUseOrDef>(
308706b4fc4SDimitry Andric               MSSAU->getMemorySSA()->getMemoryAccess(PredBB->getTerminator())))
309706b4fc4SDimitry Andric         MSSAU->moveToPlace(MUD, PredBB, MemorySSA::End);
3101d5ae102SDimitry Andric   }
3111d5ae102SDimitry Andric   // Add unreachable to now empty BB.
312d8e91e46SDimitry Andric   new UnreachableInst(BB->getContext(), BB);
313411bd29eSDimitry Andric 
314009b1c42SEd Schouten   // Inherit predecessors name if it exists.
315009b1c42SEd Schouten   if (!PredBB->hasName())
316009b1c42SEd Schouten     PredBB->takeName(BB);
317009b1c42SEd Schouten 
3185a5ac124SDimitry Andric   if (LI)
319cf099d11SDimitry Andric     LI->removeBlock(BB);
320cf099d11SDimitry Andric 
3215a5ac124SDimitry Andric   if (MemDep)
3225a5ac124SDimitry Andric     MemDep->invalidateCachedPredecessors();
323009b1c42SEd Schouten 
324344a3780SDimitry Andric   if (DTU)
325b60736ecSDimitry Andric     DTU->applyUpdates(Updates);
326344a3780SDimitry Andric 
327e3b55780SDimitry Andric   if (DT) {
328e3b55780SDimitry Andric     assert(succ_empty(BB) &&
329e3b55780SDimitry Andric            "successors should have been transferred to PredBB");
330e3b55780SDimitry Andric     DT->eraseNode(BB);
331e3b55780SDimitry Andric   }
332e3b55780SDimitry Andric 
333344a3780SDimitry Andric   // Finally, erase the old block and update dominator info.
334344a3780SDimitry Andric   DeleteDeadBlock(BB, DTU);
3351d5ae102SDimitry Andric 
336009b1c42SEd Schouten   return true;
337009b1c42SEd Schouten }
338009b1c42SEd Schouten 
MergeBlockSuccessorsIntoGivenBlocks(SmallPtrSetImpl<BasicBlock * > & MergeBlocks,Loop * L,DomTreeUpdater * DTU,LoopInfo * LI)339cfca06d7SDimitry Andric bool llvm::MergeBlockSuccessorsIntoGivenBlocks(
340cfca06d7SDimitry Andric     SmallPtrSetImpl<BasicBlock *> &MergeBlocks, Loop *L, DomTreeUpdater *DTU,
341cfca06d7SDimitry Andric     LoopInfo *LI) {
342cfca06d7SDimitry Andric   assert(!MergeBlocks.empty() && "MergeBlocks should not be empty");
343cfca06d7SDimitry Andric 
344cfca06d7SDimitry Andric   bool BlocksHaveBeenMerged = false;
345cfca06d7SDimitry Andric   while (!MergeBlocks.empty()) {
346cfca06d7SDimitry Andric     BasicBlock *BB = *MergeBlocks.begin();
347cfca06d7SDimitry Andric     BasicBlock *Dest = BB->getSingleSuccessor();
348cfca06d7SDimitry Andric     if (Dest && (!L || L->contains(Dest))) {
349cfca06d7SDimitry Andric       BasicBlock *Fold = Dest->getUniquePredecessor();
350cfca06d7SDimitry Andric       (void)Fold;
351cfca06d7SDimitry Andric       if (MergeBlockIntoPredecessor(Dest, DTU, LI)) {
352cfca06d7SDimitry Andric         assert(Fold == BB &&
353cfca06d7SDimitry Andric                "Expecting BB to be unique predecessor of the Dest block");
354cfca06d7SDimitry Andric         MergeBlocks.erase(Dest);
355cfca06d7SDimitry Andric         BlocksHaveBeenMerged = true;
356cfca06d7SDimitry Andric       } else
357cfca06d7SDimitry Andric         MergeBlocks.erase(BB);
358cfca06d7SDimitry Andric     } else
359cfca06d7SDimitry Andric       MergeBlocks.erase(BB);
360cfca06d7SDimitry Andric   }
361cfca06d7SDimitry Andric   return BlocksHaveBeenMerged;
362cfca06d7SDimitry Andric }
363cfca06d7SDimitry Andric 
364706b4fc4SDimitry Andric /// Remove redundant instructions within sequences of consecutive dbg.value
365706b4fc4SDimitry Andric /// instructions. This is done using a backward scan to keep the last dbg.value
366706b4fc4SDimitry Andric /// describing a specific variable/fragment.
367706b4fc4SDimitry Andric ///
368706b4fc4SDimitry Andric /// BackwardScan strategy:
369706b4fc4SDimitry Andric /// ----------------------
370706b4fc4SDimitry Andric /// Given a sequence of consecutive DbgValueInst like this
371706b4fc4SDimitry Andric ///
372706b4fc4SDimitry Andric ///   dbg.value ..., "x", FragmentX1  (*)
373706b4fc4SDimitry Andric ///   dbg.value ..., "y", FragmentY1
374706b4fc4SDimitry Andric ///   dbg.value ..., "x", FragmentX2
375706b4fc4SDimitry Andric ///   dbg.value ..., "x", FragmentX1  (**)
376706b4fc4SDimitry Andric ///
377706b4fc4SDimitry Andric /// then the instruction marked with (*) can be removed (it is guaranteed to be
378706b4fc4SDimitry Andric /// obsoleted by the instruction marked with (**) as the latter instruction is
379706b4fc4SDimitry Andric /// describing the same variable using the same fragment info).
380706b4fc4SDimitry Andric ///
381706b4fc4SDimitry Andric /// Possible improvements:
382706b4fc4SDimitry Andric /// - Check fully overlapping fragments and not only identical fragments.
3837fa27ce4SDimitry Andric /// - Support dbg.declare. dbg.label, and possibly other meta instructions being
3847fa27ce4SDimitry Andric ///   part of the sequence of consecutive instructions.
385ac9a064cSDimitry Andric static bool
DbgVariableRecordsRemoveRedundantDbgInstrsUsingBackwardScan(BasicBlock * BB)386ac9a064cSDimitry Andric DbgVariableRecordsRemoveRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB) {
387ac9a064cSDimitry Andric   SmallVector<DbgVariableRecord *, 8> ToBeRemoved;
388b1c73532SDimitry Andric   SmallDenseSet<DebugVariable> VariableSet;
389b1c73532SDimitry Andric   for (auto &I : reverse(*BB)) {
390ac9a064cSDimitry Andric     for (DbgRecord &DR : reverse(I.getDbgRecordRange())) {
391ac9a064cSDimitry Andric       if (isa<DbgLabelRecord>(DR)) {
392ac9a064cSDimitry Andric         // Emulate existing behaviour (see comment below for dbg.declares).
393ac9a064cSDimitry Andric         // FIXME: Don't do this.
394ac9a064cSDimitry Andric         VariableSet.clear();
395ac9a064cSDimitry Andric         continue;
396ac9a064cSDimitry Andric       }
397ac9a064cSDimitry Andric 
398ac9a064cSDimitry Andric       DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
399312c0ed1SDimitry Andric       // Skip declare-type records, as the debug intrinsic method only works
400312c0ed1SDimitry Andric       // on dbg.value intrinsics.
401ac9a064cSDimitry Andric       if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
402312c0ed1SDimitry Andric         // The debug intrinsic method treats dbg.declares are "non-debug"
403312c0ed1SDimitry Andric         // instructions (i.e., a break in a consecutive range of debug
404312c0ed1SDimitry Andric         // intrinsics). Emulate that to create identical outputs. See
405312c0ed1SDimitry Andric         // "Possible improvements" above.
406312c0ed1SDimitry Andric         // FIXME: Delete the line below.
407312c0ed1SDimitry Andric         VariableSet.clear();
408312c0ed1SDimitry Andric         continue;
409312c0ed1SDimitry Andric       }
410312c0ed1SDimitry Andric 
411ac9a064cSDimitry Andric       DebugVariable Key(DVR.getVariable(), DVR.getExpression(),
412ac9a064cSDimitry Andric                         DVR.getDebugLoc()->getInlinedAt());
413b1c73532SDimitry Andric       auto R = VariableSet.insert(Key);
414b1c73532SDimitry Andric       // If the same variable fragment is described more than once it is enough
415b1c73532SDimitry Andric       // to keep the last one (i.e. the first found since we for reverse
416b1c73532SDimitry Andric       // iteration).
4174df029ccSDimitry Andric       if (R.second)
4184df029ccSDimitry Andric         continue;
4194df029ccSDimitry Andric 
420ac9a064cSDimitry Andric       if (DVR.isDbgAssign()) {
4214df029ccSDimitry Andric         // Don't delete dbg.assign intrinsics that are linked to instructions.
422ac9a064cSDimitry Andric         if (!at::getAssignmentInsts(&DVR).empty())
4234df029ccSDimitry Andric           continue;
4244df029ccSDimitry Andric         // Unlinked dbg.assign intrinsics can be treated like dbg.values.
4254df029ccSDimitry Andric       }
4264df029ccSDimitry Andric 
427ac9a064cSDimitry Andric       ToBeRemoved.push_back(&DVR);
428b1c73532SDimitry Andric       continue;
429b1c73532SDimitry Andric     }
430b1c73532SDimitry Andric     // Sequence with consecutive dbg.value instrs ended. Clear the map to
431b1c73532SDimitry Andric     // restart identifying redundant instructions if case we find another
432b1c73532SDimitry Andric     // dbg.value sequence.
433b1c73532SDimitry Andric     VariableSet.clear();
434b1c73532SDimitry Andric   }
435b1c73532SDimitry Andric 
436ac9a064cSDimitry Andric   for (auto &DVR : ToBeRemoved)
437ac9a064cSDimitry Andric     DVR->eraseFromParent();
438b1c73532SDimitry Andric 
439b1c73532SDimitry Andric   return !ToBeRemoved.empty();
440b1c73532SDimitry Andric }
441b1c73532SDimitry Andric 
removeRedundantDbgInstrsUsingBackwardScan(BasicBlock * BB)442706b4fc4SDimitry Andric static bool removeRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB) {
443b1c73532SDimitry Andric   if (BB->IsNewDbgInfoFormat)
444ac9a064cSDimitry Andric     return DbgVariableRecordsRemoveRedundantDbgInstrsUsingBackwardScan(BB);
445b1c73532SDimitry Andric 
446706b4fc4SDimitry Andric   SmallVector<DbgValueInst *, 8> ToBeRemoved;
447706b4fc4SDimitry Andric   SmallDenseSet<DebugVariable> VariableSet;
448706b4fc4SDimitry Andric   for (auto &I : reverse(*BB)) {
449706b4fc4SDimitry Andric     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) {
450706b4fc4SDimitry Andric       DebugVariable Key(DVI->getVariable(),
451706b4fc4SDimitry Andric                         DVI->getExpression(),
452706b4fc4SDimitry Andric                         DVI->getDebugLoc()->getInlinedAt());
453706b4fc4SDimitry Andric       auto R = VariableSet.insert(Key);
454e3b55780SDimitry Andric       // If the variable fragment hasn't been seen before then we don't want
455e3b55780SDimitry Andric       // to remove this dbg intrinsic.
456e3b55780SDimitry Andric       if (R.second)
457e3b55780SDimitry Andric         continue;
458e3b55780SDimitry Andric 
459e3b55780SDimitry Andric       if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI)) {
460e3b55780SDimitry Andric         // Don't delete dbg.assign intrinsics that are linked to instructions.
461e3b55780SDimitry Andric         if (!at::getAssignmentInsts(DAI).empty())
462e3b55780SDimitry Andric           continue;
463e3b55780SDimitry Andric         // Unlinked dbg.assign intrinsics can be treated like dbg.values.
464e3b55780SDimitry Andric       }
465e3b55780SDimitry Andric 
466706b4fc4SDimitry Andric       // If the same variable fragment is described more than once it is enough
467706b4fc4SDimitry Andric       // to keep the last one (i.e. the first found since we for reverse
468706b4fc4SDimitry Andric       // iteration).
469706b4fc4SDimitry Andric       ToBeRemoved.push_back(DVI);
470706b4fc4SDimitry Andric       continue;
471706b4fc4SDimitry Andric     }
472706b4fc4SDimitry Andric     // Sequence with consecutive dbg.value instrs ended. Clear the map to
473706b4fc4SDimitry Andric     // restart identifying redundant instructions if case we find another
474706b4fc4SDimitry Andric     // dbg.value sequence.
475706b4fc4SDimitry Andric     VariableSet.clear();
476706b4fc4SDimitry Andric   }
477706b4fc4SDimitry Andric 
478706b4fc4SDimitry Andric   for (auto &Instr : ToBeRemoved)
479706b4fc4SDimitry Andric     Instr->eraseFromParent();
480706b4fc4SDimitry Andric 
481706b4fc4SDimitry Andric   return !ToBeRemoved.empty();
482706b4fc4SDimitry Andric }
483706b4fc4SDimitry Andric 
484706b4fc4SDimitry Andric /// Remove redundant dbg.value instructions using a forward scan. This can
485706b4fc4SDimitry Andric /// remove a dbg.value instruction that is redundant due to indicating that a
486706b4fc4SDimitry Andric /// variable has the same value as already being indicated by an earlier
487706b4fc4SDimitry Andric /// dbg.value.
488706b4fc4SDimitry Andric ///
489706b4fc4SDimitry Andric /// ForwardScan strategy:
490706b4fc4SDimitry Andric /// ---------------------
491706b4fc4SDimitry Andric /// Given two identical dbg.value instructions, separated by a block of
492706b4fc4SDimitry Andric /// instructions that isn't describing the same variable, like this
493706b4fc4SDimitry Andric ///
494706b4fc4SDimitry Andric ///   dbg.value X1, "x", FragmentX1  (**)
495706b4fc4SDimitry Andric ///   <block of instructions, none being "dbg.value ..., "x", ...">
496706b4fc4SDimitry Andric ///   dbg.value X1, "x", FragmentX1  (*)
497706b4fc4SDimitry Andric ///
498706b4fc4SDimitry Andric /// then the instruction marked with (*) can be removed. Variable "x" is already
499706b4fc4SDimitry Andric /// described as being mapped to the SSA value X1.
500706b4fc4SDimitry Andric ///
501706b4fc4SDimitry Andric /// Possible improvements:
502706b4fc4SDimitry Andric /// - Keep track of non-overlapping fragments.
503ac9a064cSDimitry Andric static bool
DbgVariableRecordsRemoveRedundantDbgInstrsUsingForwardScan(BasicBlock * BB)504ac9a064cSDimitry Andric DbgVariableRecordsRemoveRedundantDbgInstrsUsingForwardScan(BasicBlock *BB) {
505ac9a064cSDimitry Andric   SmallVector<DbgVariableRecord *, 8> ToBeRemoved;
506b1c73532SDimitry Andric   DenseMap<DebugVariable, std::pair<SmallVector<Value *, 4>, DIExpression *>>
507b1c73532SDimitry Andric       VariableMap;
508b1c73532SDimitry Andric   for (auto &I : *BB) {
509ac9a064cSDimitry Andric     for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
510ac9a064cSDimitry Andric       if (DVR.getType() == DbgVariableRecord::LocationType::Declare)
511312c0ed1SDimitry Andric         continue;
512ac9a064cSDimitry Andric       DebugVariable Key(DVR.getVariable(), std::nullopt,
513ac9a064cSDimitry Andric                         DVR.getDebugLoc()->getInlinedAt());
514b1c73532SDimitry Andric       auto VMI = VariableMap.find(Key);
5154df029ccSDimitry Andric       // A dbg.assign with no linked instructions can be treated like a
5164df029ccSDimitry Andric       // dbg.value (i.e. can be deleted).
5174df029ccSDimitry Andric       bool IsDbgValueKind =
518ac9a064cSDimitry Andric           (!DVR.isDbgAssign() || at::getAssignmentInsts(&DVR).empty());
5194df029ccSDimitry Andric 
520b1c73532SDimitry Andric       // Update the map if we found a new value/expression describing the
521b1c73532SDimitry Andric       // variable, or if the variable wasn't mapped already.
522ac9a064cSDimitry Andric       SmallVector<Value *, 4> Values(DVR.location_ops());
523b1c73532SDimitry Andric       if (VMI == VariableMap.end() || VMI->second.first != Values ||
524ac9a064cSDimitry Andric           VMI->second.second != DVR.getExpression()) {
5254df029ccSDimitry Andric         if (IsDbgValueKind)
526ac9a064cSDimitry Andric           VariableMap[Key] = {Values, DVR.getExpression()};
5274df029ccSDimitry Andric         else
5284df029ccSDimitry Andric           VariableMap[Key] = {Values, nullptr};
529b1c73532SDimitry Andric         continue;
530b1c73532SDimitry Andric       }
5314df029ccSDimitry Andric       // Don't delete dbg.assign intrinsics that are linked to instructions.
5324df029ccSDimitry Andric       if (!IsDbgValueKind)
5334df029ccSDimitry Andric         continue;
534b1c73532SDimitry Andric       // Found an identical mapping. Remember the instruction for later removal.
535ac9a064cSDimitry Andric       ToBeRemoved.push_back(&DVR);
536b1c73532SDimitry Andric     }
537b1c73532SDimitry Andric   }
538b1c73532SDimitry Andric 
539ac9a064cSDimitry Andric   for (auto *DVR : ToBeRemoved)
540ac9a064cSDimitry Andric     DVR->eraseFromParent();
541b1c73532SDimitry Andric 
542b1c73532SDimitry Andric   return !ToBeRemoved.empty();
543b1c73532SDimitry Andric }
544b1c73532SDimitry Andric 
545ac9a064cSDimitry Andric static bool
DbgVariableRecordsRemoveUndefDbgAssignsFromEntryBlock(BasicBlock * BB)546ac9a064cSDimitry Andric DbgVariableRecordsRemoveUndefDbgAssignsFromEntryBlock(BasicBlock *BB) {
5474df029ccSDimitry Andric   assert(BB->isEntryBlock() && "expected entry block");
548ac9a064cSDimitry Andric   SmallVector<DbgVariableRecord *, 8> ToBeRemoved;
5494df029ccSDimitry Andric   DenseSet<DebugVariable> SeenDefForAggregate;
5504df029ccSDimitry Andric   // Returns the DebugVariable for DVI with no fragment info.
551ac9a064cSDimitry Andric   auto GetAggregateVariable = [](const DbgVariableRecord &DVR) {
552ac9a064cSDimitry Andric     return DebugVariable(DVR.getVariable(), std::nullopt,
553ac9a064cSDimitry Andric                          DVR.getDebugLoc().getInlinedAt());
5544df029ccSDimitry Andric   };
5554df029ccSDimitry Andric 
5564df029ccSDimitry Andric   // Remove undef dbg.assign intrinsics that are encountered before
5574df029ccSDimitry Andric   // any non-undef intrinsics from the entry block.
5584df029ccSDimitry Andric   for (auto &I : *BB) {
559ac9a064cSDimitry Andric     for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
560ac9a064cSDimitry Andric       if (!DVR.isDbgValue() && !DVR.isDbgAssign())
5614df029ccSDimitry Andric         continue;
5624df029ccSDimitry Andric       bool IsDbgValueKind =
563ac9a064cSDimitry Andric           (DVR.isDbgValue() || at::getAssignmentInsts(&DVR).empty());
564ac9a064cSDimitry Andric       DebugVariable Aggregate = GetAggregateVariable(DVR);
5654df029ccSDimitry Andric       if (!SeenDefForAggregate.contains(Aggregate)) {
566ac9a064cSDimitry Andric         bool IsKill = DVR.isKillLocation() && IsDbgValueKind;
5674df029ccSDimitry Andric         if (!IsKill) {
5684df029ccSDimitry Andric           SeenDefForAggregate.insert(Aggregate);
569ac9a064cSDimitry Andric         } else if (DVR.isDbgAssign()) {
570ac9a064cSDimitry Andric           ToBeRemoved.push_back(&DVR);
5714df029ccSDimitry Andric         }
5724df029ccSDimitry Andric       }
5734df029ccSDimitry Andric     }
5744df029ccSDimitry Andric   }
5754df029ccSDimitry Andric 
576ac9a064cSDimitry Andric   for (DbgVariableRecord *DVR : ToBeRemoved)
577ac9a064cSDimitry Andric     DVR->eraseFromParent();
5784df029ccSDimitry Andric 
5794df029ccSDimitry Andric   return !ToBeRemoved.empty();
5804df029ccSDimitry Andric }
5814df029ccSDimitry Andric 
removeRedundantDbgInstrsUsingForwardScan(BasicBlock * BB)582706b4fc4SDimitry Andric static bool removeRedundantDbgInstrsUsingForwardScan(BasicBlock *BB) {
583b1c73532SDimitry Andric   if (BB->IsNewDbgInfoFormat)
584ac9a064cSDimitry Andric     return DbgVariableRecordsRemoveRedundantDbgInstrsUsingForwardScan(BB);
585b1c73532SDimitry Andric 
586706b4fc4SDimitry Andric   SmallVector<DbgValueInst *, 8> ToBeRemoved;
587344a3780SDimitry Andric   DenseMap<DebugVariable, std::pair<SmallVector<Value *, 4>, DIExpression *>>
588344a3780SDimitry Andric       VariableMap;
589706b4fc4SDimitry Andric   for (auto &I : *BB) {
590706b4fc4SDimitry Andric     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I)) {
591e3b55780SDimitry Andric       DebugVariable Key(DVI->getVariable(), std::nullopt,
592706b4fc4SDimitry Andric                         DVI->getDebugLoc()->getInlinedAt());
593706b4fc4SDimitry Andric       auto VMI = VariableMap.find(Key);
594e3b55780SDimitry Andric       auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI);
595e3b55780SDimitry Andric       // A dbg.assign with no linked instructions can be treated like a
596e3b55780SDimitry Andric       // dbg.value (i.e. can be deleted).
597e3b55780SDimitry Andric       bool IsDbgValueKind = (!DAI || at::getAssignmentInsts(DAI).empty());
598e3b55780SDimitry Andric 
599706b4fc4SDimitry Andric       // Update the map if we found a new value/expression describing the
600706b4fc4SDimitry Andric       // variable, or if the variable wasn't mapped already.
601344a3780SDimitry Andric       SmallVector<Value *, 4> Values(DVI->getValues());
602344a3780SDimitry Andric       if (VMI == VariableMap.end() || VMI->second.first != Values ||
603706b4fc4SDimitry Andric           VMI->second.second != DVI->getExpression()) {
6044df029ccSDimitry Andric         // Use a sentinel value (nullptr) for the DIExpression when we see a
605e3b55780SDimitry Andric         // linked dbg.assign so that the next debug intrinsic will never match
606e3b55780SDimitry Andric         // it (i.e. always treat linked dbg.assigns as if they're unique).
607e3b55780SDimitry Andric         if (IsDbgValueKind)
608344a3780SDimitry Andric           VariableMap[Key] = {Values, DVI->getExpression()};
609e3b55780SDimitry Andric         else
610e3b55780SDimitry Andric           VariableMap[Key] = {Values, nullptr};
611706b4fc4SDimitry Andric         continue;
612706b4fc4SDimitry Andric       }
613e3b55780SDimitry Andric 
614e3b55780SDimitry Andric       // Don't delete dbg.assign intrinsics that are linked to instructions.
615e3b55780SDimitry Andric       if (!IsDbgValueKind)
616e3b55780SDimitry Andric         continue;
617706b4fc4SDimitry Andric       ToBeRemoved.push_back(DVI);
618706b4fc4SDimitry Andric     }
619706b4fc4SDimitry Andric   }
620706b4fc4SDimitry Andric 
621706b4fc4SDimitry Andric   for (auto &Instr : ToBeRemoved)
622706b4fc4SDimitry Andric     Instr->eraseFromParent();
623706b4fc4SDimitry Andric 
624706b4fc4SDimitry Andric   return !ToBeRemoved.empty();
625706b4fc4SDimitry Andric }
626706b4fc4SDimitry Andric 
627e3b55780SDimitry Andric /// Remove redundant undef dbg.assign intrinsic from an entry block using a
628e3b55780SDimitry Andric /// forward scan.
629e3b55780SDimitry Andric /// Strategy:
630e3b55780SDimitry Andric /// ---------------------
631e3b55780SDimitry Andric /// Scanning forward, delete dbg.assign intrinsics iff they are undef, not
632e3b55780SDimitry Andric /// linked to an intrinsic, and don't share an aggregate variable with a debug
633e3b55780SDimitry Andric /// intrinsic that didn't meet the criteria. In other words, undef dbg.assigns
634e3b55780SDimitry Andric /// that come before non-undef debug intrinsics for the variable are
635e3b55780SDimitry Andric /// deleted. Given:
636e3b55780SDimitry Andric ///
637e3b55780SDimitry Andric ///   dbg.assign undef, "x", FragmentX1 (*)
638e3b55780SDimitry Andric ///   <block of instructions, none being "dbg.value ..., "x", ...">
639e3b55780SDimitry Andric ///   dbg.value %V, "x", FragmentX2
640e3b55780SDimitry Andric ///   <block of instructions, none being "dbg.value ..., "x", ...">
641e3b55780SDimitry Andric ///   dbg.assign undef, "x", FragmentX1
642e3b55780SDimitry Andric ///
643e3b55780SDimitry Andric /// then (only) the instruction marked with (*) can be removed.
644e3b55780SDimitry Andric /// Possible improvements:
645e3b55780SDimitry Andric /// - Keep track of non-overlapping fragments.
removeUndefDbgAssignsFromEntryBlock(BasicBlock * BB)6464df029ccSDimitry Andric static bool removeUndefDbgAssignsFromEntryBlock(BasicBlock *BB) {
6474df029ccSDimitry Andric   if (BB->IsNewDbgInfoFormat)
648ac9a064cSDimitry Andric     return DbgVariableRecordsRemoveUndefDbgAssignsFromEntryBlock(BB);
6494df029ccSDimitry Andric 
650e3b55780SDimitry Andric   assert(BB->isEntryBlock() && "expected entry block");
651e3b55780SDimitry Andric   SmallVector<DbgAssignIntrinsic *, 8> ToBeRemoved;
652e3b55780SDimitry Andric   DenseSet<DebugVariable> SeenDefForAggregate;
653e3b55780SDimitry Andric   // Returns the DebugVariable for DVI with no fragment info.
654e3b55780SDimitry Andric   auto GetAggregateVariable = [](DbgValueInst *DVI) {
655e3b55780SDimitry Andric     return DebugVariable(DVI->getVariable(), std::nullopt,
656e3b55780SDimitry Andric                          DVI->getDebugLoc()->getInlinedAt());
657e3b55780SDimitry Andric   };
658e3b55780SDimitry Andric 
659e3b55780SDimitry Andric   // Remove undef dbg.assign intrinsics that are encountered before
660e3b55780SDimitry Andric   // any non-undef intrinsics from the entry block.
661e3b55780SDimitry Andric   for (auto &I : *BB) {
662e3b55780SDimitry Andric     DbgValueInst *DVI = dyn_cast<DbgValueInst>(&I);
663e3b55780SDimitry Andric     if (!DVI)
664e3b55780SDimitry Andric       continue;
665e3b55780SDimitry Andric     auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI);
666e3b55780SDimitry Andric     bool IsDbgValueKind = (!DAI || at::getAssignmentInsts(DAI).empty());
667e3b55780SDimitry Andric     DebugVariable Aggregate = GetAggregateVariable(DVI);
668e3b55780SDimitry Andric     if (!SeenDefForAggregate.contains(Aggregate)) {
669e3b55780SDimitry Andric       bool IsKill = DVI->isKillLocation() && IsDbgValueKind;
670e3b55780SDimitry Andric       if (!IsKill) {
671e3b55780SDimitry Andric         SeenDefForAggregate.insert(Aggregate);
672e3b55780SDimitry Andric       } else if (DAI) {
673e3b55780SDimitry Andric         ToBeRemoved.push_back(DAI);
674e3b55780SDimitry Andric       }
675e3b55780SDimitry Andric     }
676e3b55780SDimitry Andric   }
677e3b55780SDimitry Andric 
678e3b55780SDimitry Andric   for (DbgAssignIntrinsic *DAI : ToBeRemoved)
679e3b55780SDimitry Andric     DAI->eraseFromParent();
680e3b55780SDimitry Andric 
681e3b55780SDimitry Andric   return !ToBeRemoved.empty();
682e3b55780SDimitry Andric }
683e3b55780SDimitry Andric 
RemoveRedundantDbgInstrs(BasicBlock * BB)684706b4fc4SDimitry Andric bool llvm::RemoveRedundantDbgInstrs(BasicBlock *BB) {
685706b4fc4SDimitry Andric   bool MadeChanges = false;
686706b4fc4SDimitry Andric   // By using the "backward scan" strategy before the "forward scan" strategy we
687706b4fc4SDimitry Andric   // can remove both dbg.value (2) and (3) in a situation like this:
688706b4fc4SDimitry Andric   //
689706b4fc4SDimitry Andric   //   (1) dbg.value V1, "x", DIExpression()
690706b4fc4SDimitry Andric   //       ...
691706b4fc4SDimitry Andric   //   (2) dbg.value V2, "x", DIExpression()
692706b4fc4SDimitry Andric   //   (3) dbg.value V1, "x", DIExpression()
693706b4fc4SDimitry Andric   //
694706b4fc4SDimitry Andric   // The backward scan will remove (2), it is made obsolete by (3). After
695706b4fc4SDimitry Andric   // getting (2) out of the way, the foward scan will remove (3) since "x"
696706b4fc4SDimitry Andric   // already is described as having the value V1 at (1).
697706b4fc4SDimitry Andric   MadeChanges |= removeRedundantDbgInstrsUsingBackwardScan(BB);
698e3b55780SDimitry Andric   if (BB->isEntryBlock() &&
699e3b55780SDimitry Andric       isAssignmentTrackingEnabled(*BB->getParent()->getParent()))
7004df029ccSDimitry Andric     MadeChanges |= removeUndefDbgAssignsFromEntryBlock(BB);
701706b4fc4SDimitry Andric   MadeChanges |= removeRedundantDbgInstrsUsingForwardScan(BB);
702706b4fc4SDimitry Andric 
703706b4fc4SDimitry Andric   if (MadeChanges)
704706b4fc4SDimitry Andric     LLVM_DEBUG(dbgs() << "Removed redundant dbg instrs from: "
705706b4fc4SDimitry Andric                       << BB->getName() << "\n");
706706b4fc4SDimitry Andric   return MadeChanges;
707706b4fc4SDimitry Andric }
708706b4fc4SDimitry Andric 
ReplaceInstWithValue(BasicBlock::iterator & BI,Value * V)709e3b55780SDimitry Andric void llvm::ReplaceInstWithValue(BasicBlock::iterator &BI, Value *V) {
710009b1c42SEd Schouten   Instruction &I = *BI;
711009b1c42SEd Schouten   // Replaces all of the uses of the instruction with uses of the value
712009b1c42SEd Schouten   I.replaceAllUsesWith(V);
713009b1c42SEd Schouten 
714009b1c42SEd Schouten   // Make sure to propagate a name if there is one already.
715009b1c42SEd Schouten   if (I.hasName() && !V->hasName())
716009b1c42SEd Schouten     V->takeName(&I);
717009b1c42SEd Schouten 
718009b1c42SEd Schouten   // Delete the unnecessary instruction now...
719e3b55780SDimitry Andric   BI = BI->eraseFromParent();
720009b1c42SEd Schouten }
721009b1c42SEd Schouten 
ReplaceInstWithInst(BasicBlock * BB,BasicBlock::iterator & BI,Instruction * I)722e3b55780SDimitry Andric void llvm::ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI,
723e3b55780SDimitry Andric                                Instruction *I) {
7245ca98fd9SDimitry Andric   assert(I->getParent() == nullptr &&
725009b1c42SEd Schouten          "ReplaceInstWithInst: Instruction already inserted into basic block!");
726009b1c42SEd Schouten 
7271a82d4c0SDimitry Andric   // Copy debug location to newly added instruction, if it wasn't already set
7281a82d4c0SDimitry Andric   // by the caller.
7291a82d4c0SDimitry Andric   if (!I->getDebugLoc())
7301a82d4c0SDimitry Andric     I->setDebugLoc(BI->getDebugLoc());
7311a82d4c0SDimitry Andric 
732009b1c42SEd Schouten   // Insert the new instruction into the basic block...
733e3b55780SDimitry Andric   BasicBlock::iterator New = I->insertInto(BB, BI);
734009b1c42SEd Schouten 
735009b1c42SEd Schouten   // Replace all uses of the old instruction, and delete it.
736e3b55780SDimitry Andric   ReplaceInstWithValue(BI, I);
737009b1c42SEd Schouten 
738009b1c42SEd Schouten   // Move BI back to point to the newly inserted instruction
739009b1c42SEd Schouten   BI = New;
740009b1c42SEd Schouten }
741009b1c42SEd Schouten 
IsBlockFollowedByDeoptOrUnreachable(const BasicBlock * BB)742c0981da4SDimitry Andric bool llvm::IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB) {
743c0981da4SDimitry Andric   // Remember visited blocks to avoid infinite loop
744c0981da4SDimitry Andric   SmallPtrSet<const BasicBlock *, 8> VisitedBlocks;
745c0981da4SDimitry Andric   unsigned Depth = 0;
746c0981da4SDimitry Andric   while (BB && Depth++ < MaxDeoptOrUnreachableSuccessorCheckDepth &&
747c0981da4SDimitry Andric          VisitedBlocks.insert(BB).second) {
7487fa27ce4SDimitry Andric     if (isa<UnreachableInst>(BB->getTerminator()) ||
7497fa27ce4SDimitry Andric         BB->getTerminatingDeoptimizeCall())
750c0981da4SDimitry Andric       return true;
751c0981da4SDimitry Andric     BB = BB->getUniqueSuccessor();
752c0981da4SDimitry Andric   }
753c0981da4SDimitry Andric   return false;
754c0981da4SDimitry Andric }
755c0981da4SDimitry Andric 
ReplaceInstWithInst(Instruction * From,Instruction * To)756009b1c42SEd Schouten void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
757009b1c42SEd Schouten   BasicBlock::iterator BI(From);
758e3b55780SDimitry Andric   ReplaceInstWithInst(From->getParent(), BI, To);
759009b1c42SEd Schouten }
760009b1c42SEd Schouten 
SplitEdge(BasicBlock * BB,BasicBlock * Succ,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName)7615a5ac124SDimitry Andric BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
762b60736ecSDimitry Andric                             LoopInfo *LI, MemorySSAUpdater *MSSAU,
763b60736ecSDimitry Andric                             const Twine &BBName) {
76467a71b31SRoman Divacky   unsigned SuccNum = GetSuccessorNumber(BB, Succ);
76567a71b31SRoman Divacky 
766d8e91e46SDimitry Andric   Instruction *LatchTerm = BB->getTerminator();
767344a3780SDimitry Andric 
768344a3780SDimitry Andric   CriticalEdgeSplittingOptions Options =
769344a3780SDimitry Andric       CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA();
770344a3780SDimitry Andric 
771344a3780SDimitry Andric   if ((isCriticalEdge(LatchTerm, SuccNum, Options.MergeIdenticalEdges))) {
772344a3780SDimitry Andric     // If it is a critical edge, and the succesor is an exception block, handle
773344a3780SDimitry Andric     // the split edge logic in this specific function
774344a3780SDimitry Andric     if (Succ->isEHPad())
775344a3780SDimitry Andric       return ehAwareSplitEdge(BB, Succ, nullptr, nullptr, Options, BBName);
776344a3780SDimitry Andric 
777344a3780SDimitry Andric     // If this is a critical edge, let SplitKnownCriticalEdge do it.
778344a3780SDimitry Andric     return SplitKnownCriticalEdge(LatchTerm, SuccNum, Options, BBName);
779344a3780SDimitry Andric   }
780009b1c42SEd Schouten 
781009b1c42SEd Schouten   // If the edge isn't critical, then BB has a single successor or Succ has a
782009b1c42SEd Schouten   // single pred.  Split the block.
783009b1c42SEd Schouten   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
784009b1c42SEd Schouten     // If the successor only has a single pred, split the top of the successor
785009b1c42SEd Schouten     // block.
786009b1c42SEd Schouten     assert(SP == BB && "CFG broken");
787ac9a064cSDimitry Andric     (void)SP;
788b60736ecSDimitry Andric     return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU, BBName,
789b60736ecSDimitry Andric                       /*Before=*/true);
790cf099d11SDimitry Andric   }
791cf099d11SDimitry Andric 
792009b1c42SEd Schouten   // Otherwise, if BB has a single successor, split it at the bottom of the
793009b1c42SEd Schouten   // block.
794009b1c42SEd Schouten   assert(BB->getTerminator()->getNumSuccessors() == 1 &&
795009b1c42SEd Schouten          "Should have a single succ!");
796b60736ecSDimitry Andric   return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU, BBName);
797009b1c42SEd Schouten }
798009b1c42SEd Schouten 
setUnwindEdgeTo(Instruction * TI,BasicBlock * Succ)799344a3780SDimitry Andric void llvm::setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ) {
800344a3780SDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(TI))
801344a3780SDimitry Andric     II->setUnwindDest(Succ);
802344a3780SDimitry Andric   else if (auto *CS = dyn_cast<CatchSwitchInst>(TI))
803344a3780SDimitry Andric     CS->setUnwindDest(Succ);
804344a3780SDimitry Andric   else if (auto *CR = dyn_cast<CleanupReturnInst>(TI))
805344a3780SDimitry Andric     CR->setUnwindDest(Succ);
806344a3780SDimitry Andric   else
807344a3780SDimitry Andric     llvm_unreachable("unexpected terminator instruction");
808344a3780SDimitry Andric }
809344a3780SDimitry Andric 
updatePhiNodes(BasicBlock * DestBB,BasicBlock * OldPred,BasicBlock * NewPred,PHINode * Until)810344a3780SDimitry Andric void llvm::updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred,
811344a3780SDimitry Andric                           BasicBlock *NewPred, PHINode *Until) {
812344a3780SDimitry Andric   int BBIdx = 0;
813344a3780SDimitry Andric   for (PHINode &PN : DestBB->phis()) {
814344a3780SDimitry Andric     // We manually update the LandingPadReplacement PHINode and it is the last
815344a3780SDimitry Andric     // PHI Node. So, if we find it, we are done.
816344a3780SDimitry Andric     if (Until == &PN)
817344a3780SDimitry Andric       break;
818344a3780SDimitry Andric 
819344a3780SDimitry Andric     // Reuse the previous value of BBIdx if it lines up.  In cases where we
820344a3780SDimitry Andric     // have multiple phi nodes with *lots* of predecessors, this is a speed
821344a3780SDimitry Andric     // win because we don't have to scan the PHI looking for TIBB.  This
822344a3780SDimitry Andric     // happens because the BB list of PHI nodes are usually in the same
823344a3780SDimitry Andric     // order.
824344a3780SDimitry Andric     if (PN.getIncomingBlock(BBIdx) != OldPred)
825344a3780SDimitry Andric       BBIdx = PN.getBasicBlockIndex(OldPred);
826344a3780SDimitry Andric 
827344a3780SDimitry Andric     assert(BBIdx != -1 && "Invalid PHI Index!");
828344a3780SDimitry Andric     PN.setIncomingBlock(BBIdx, NewPred);
829344a3780SDimitry Andric   }
830344a3780SDimitry Andric }
831344a3780SDimitry Andric 
ehAwareSplitEdge(BasicBlock * BB,BasicBlock * Succ,LandingPadInst * OriginalPad,PHINode * LandingPadReplacement,const CriticalEdgeSplittingOptions & Options,const Twine & BBName)832344a3780SDimitry Andric BasicBlock *llvm::ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
833344a3780SDimitry Andric                                    LandingPadInst *OriginalPad,
834344a3780SDimitry Andric                                    PHINode *LandingPadReplacement,
835344a3780SDimitry Andric                                    const CriticalEdgeSplittingOptions &Options,
836344a3780SDimitry Andric                                    const Twine &BBName) {
837344a3780SDimitry Andric 
838344a3780SDimitry Andric   auto *PadInst = Succ->getFirstNonPHI();
839344a3780SDimitry Andric   if (!LandingPadReplacement && !PadInst->isEHPad())
840344a3780SDimitry Andric     return SplitEdge(BB, Succ, Options.DT, Options.LI, Options.MSSAU, BBName);
841344a3780SDimitry Andric 
842344a3780SDimitry Andric   auto *LI = Options.LI;
843344a3780SDimitry Andric   SmallVector<BasicBlock *, 4> LoopPreds;
844344a3780SDimitry Andric   // Check if extra modifications will be required to preserve loop-simplify
845344a3780SDimitry Andric   // form after splitting. If it would require splitting blocks with IndirectBr
846344a3780SDimitry Andric   // terminators, bail out if preserving loop-simplify form is requested.
847344a3780SDimitry Andric   if (Options.PreserveLoopSimplify && LI) {
848344a3780SDimitry Andric     if (Loop *BBLoop = LI->getLoopFor(BB)) {
849344a3780SDimitry Andric 
850344a3780SDimitry Andric       // The only way that we can break LoopSimplify form by splitting a
851344a3780SDimitry Andric       // critical edge is when there exists some edge from BBLoop to Succ *and*
852344a3780SDimitry Andric       // the only edge into Succ from outside of BBLoop is that of NewBB after
853344a3780SDimitry Andric       // the split. If the first isn't true, then LoopSimplify still holds,
854344a3780SDimitry Andric       // NewBB is the new exit block and it has no non-loop predecessors. If the
855344a3780SDimitry Andric       // second isn't true, then Succ was not in LoopSimplify form prior to
856344a3780SDimitry Andric       // the split as it had a non-loop predecessor. In both of these cases,
857344a3780SDimitry Andric       // the predecessor must be directly in BBLoop, not in a subloop, or again
858344a3780SDimitry Andric       // LoopSimplify doesn't hold.
859344a3780SDimitry Andric       for (BasicBlock *P : predecessors(Succ)) {
860344a3780SDimitry Andric         if (P == BB)
861344a3780SDimitry Andric           continue; // The new block is known.
862344a3780SDimitry Andric         if (LI->getLoopFor(P) != BBLoop) {
863344a3780SDimitry Andric           // Loop is not in LoopSimplify form, no need to re simplify after
864344a3780SDimitry Andric           // splitting edge.
865344a3780SDimitry Andric           LoopPreds.clear();
866344a3780SDimitry Andric           break;
867344a3780SDimitry Andric         }
868344a3780SDimitry Andric         LoopPreds.push_back(P);
869344a3780SDimitry Andric       }
870344a3780SDimitry Andric       // Loop-simplify form can be preserved, if we can split all in-loop
871344a3780SDimitry Andric       // predecessors.
872344a3780SDimitry Andric       if (any_of(LoopPreds, [](BasicBlock *Pred) {
873344a3780SDimitry Andric             return isa<IndirectBrInst>(Pred->getTerminator());
874344a3780SDimitry Andric           })) {
875344a3780SDimitry Andric         return nullptr;
876344a3780SDimitry Andric       }
877344a3780SDimitry Andric     }
878344a3780SDimitry Andric   }
879344a3780SDimitry Andric 
880344a3780SDimitry Andric   auto *NewBB =
881344a3780SDimitry Andric       BasicBlock::Create(BB->getContext(), BBName, BB->getParent(), Succ);
882344a3780SDimitry Andric   setUnwindEdgeTo(BB->getTerminator(), NewBB);
883344a3780SDimitry Andric   updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement);
884344a3780SDimitry Andric 
885344a3780SDimitry Andric   if (LandingPadReplacement) {
886344a3780SDimitry Andric     auto *NewLP = OriginalPad->clone();
887344a3780SDimitry Andric     auto *Terminator = BranchInst::Create(Succ, NewBB);
888344a3780SDimitry Andric     NewLP->insertBefore(Terminator);
889344a3780SDimitry Andric     LandingPadReplacement->addIncoming(NewLP, NewBB);
890344a3780SDimitry Andric   } else {
891344a3780SDimitry Andric     Value *ParentPad = nullptr;
892344a3780SDimitry Andric     if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
893344a3780SDimitry Andric       ParentPad = FuncletPad->getParentPad();
894344a3780SDimitry Andric     else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
895344a3780SDimitry Andric       ParentPad = CatchSwitch->getParentPad();
896344a3780SDimitry Andric     else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(PadInst))
897344a3780SDimitry Andric       ParentPad = CleanupPad->getParentPad();
898344a3780SDimitry Andric     else if (auto *LandingPad = dyn_cast<LandingPadInst>(PadInst))
899344a3780SDimitry Andric       ParentPad = LandingPad->getParent();
900344a3780SDimitry Andric     else
901344a3780SDimitry Andric       llvm_unreachable("handling for other EHPads not implemented yet");
902344a3780SDimitry Andric 
903344a3780SDimitry Andric     auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, BBName, NewBB);
904344a3780SDimitry Andric     CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB);
905344a3780SDimitry Andric   }
906344a3780SDimitry Andric 
907344a3780SDimitry Andric   auto *DT = Options.DT;
908344a3780SDimitry Andric   auto *MSSAU = Options.MSSAU;
909344a3780SDimitry Andric   if (!DT && !LI)
910344a3780SDimitry Andric     return NewBB;
911344a3780SDimitry Andric 
912344a3780SDimitry Andric   if (DT) {
913344a3780SDimitry Andric     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
914344a3780SDimitry Andric     SmallVector<DominatorTree::UpdateType, 3> Updates;
915344a3780SDimitry Andric 
916344a3780SDimitry Andric     Updates.push_back({DominatorTree::Insert, BB, NewBB});
917344a3780SDimitry Andric     Updates.push_back({DominatorTree::Insert, NewBB, Succ});
918344a3780SDimitry Andric     Updates.push_back({DominatorTree::Delete, BB, Succ});
919344a3780SDimitry Andric 
920344a3780SDimitry Andric     DTU.applyUpdates(Updates);
921344a3780SDimitry Andric     DTU.flush();
922344a3780SDimitry Andric 
923344a3780SDimitry Andric     if (MSSAU) {
924344a3780SDimitry Andric       MSSAU->applyUpdates(Updates, *DT);
925344a3780SDimitry Andric       if (VerifyMemorySSA)
926344a3780SDimitry Andric         MSSAU->getMemorySSA()->verifyMemorySSA();
927344a3780SDimitry Andric     }
928344a3780SDimitry Andric   }
929344a3780SDimitry Andric 
930344a3780SDimitry Andric   if (LI) {
931344a3780SDimitry Andric     if (Loop *BBLoop = LI->getLoopFor(BB)) {
932344a3780SDimitry Andric       // If one or the other blocks were not in a loop, the new block is not
933344a3780SDimitry Andric       // either, and thus LI doesn't need to be updated.
934344a3780SDimitry Andric       if (Loop *SuccLoop = LI->getLoopFor(Succ)) {
935344a3780SDimitry Andric         if (BBLoop == SuccLoop) {
936344a3780SDimitry Andric           // Both in the same loop, the NewBB joins loop.
937344a3780SDimitry Andric           SuccLoop->addBasicBlockToLoop(NewBB, *LI);
938344a3780SDimitry Andric         } else if (BBLoop->contains(SuccLoop)) {
939344a3780SDimitry Andric           // Edge from an outer loop to an inner loop.  Add to the outer loop.
940344a3780SDimitry Andric           BBLoop->addBasicBlockToLoop(NewBB, *LI);
941344a3780SDimitry Andric         } else if (SuccLoop->contains(BBLoop)) {
942344a3780SDimitry Andric           // Edge from an inner loop to an outer loop.  Add to the outer loop.
943344a3780SDimitry Andric           SuccLoop->addBasicBlockToLoop(NewBB, *LI);
944344a3780SDimitry Andric         } else {
945344a3780SDimitry Andric           // Edge from two loops with no containment relation.  Because these
946344a3780SDimitry Andric           // are natural loops, we know that the destination block must be the
947344a3780SDimitry Andric           // header of its loop (adding a branch into a loop elsewhere would
948344a3780SDimitry Andric           // create an irreducible loop).
949344a3780SDimitry Andric           assert(SuccLoop->getHeader() == Succ &&
950344a3780SDimitry Andric                  "Should not create irreducible loops!");
951344a3780SDimitry Andric           if (Loop *P = SuccLoop->getParentLoop())
952344a3780SDimitry Andric             P->addBasicBlockToLoop(NewBB, *LI);
953344a3780SDimitry Andric         }
954344a3780SDimitry Andric       }
955344a3780SDimitry Andric 
956344a3780SDimitry Andric       // If BB is in a loop and Succ is outside of that loop, we may need to
957344a3780SDimitry Andric       // update LoopSimplify form and LCSSA form.
958344a3780SDimitry Andric       if (!BBLoop->contains(Succ)) {
959344a3780SDimitry Andric         assert(!BBLoop->contains(NewBB) &&
960344a3780SDimitry Andric                "Split point for loop exit is contained in loop!");
961344a3780SDimitry Andric 
962344a3780SDimitry Andric         // Update LCSSA form in the newly created exit block.
963344a3780SDimitry Andric         if (Options.PreserveLCSSA) {
964344a3780SDimitry Andric           createPHIsForSplitLoopExit(BB, NewBB, Succ);
965344a3780SDimitry Andric         }
966344a3780SDimitry Andric 
967344a3780SDimitry Andric         if (!LoopPreds.empty()) {
968344a3780SDimitry Andric           BasicBlock *NewExitBB = SplitBlockPredecessors(
969344a3780SDimitry Andric               Succ, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
970344a3780SDimitry Andric           if (Options.PreserveLCSSA)
971344a3780SDimitry Andric             createPHIsForSplitLoopExit(LoopPreds, NewExitBB, Succ);
972344a3780SDimitry Andric         }
973344a3780SDimitry Andric       }
974344a3780SDimitry Andric     }
975344a3780SDimitry Andric   }
976344a3780SDimitry Andric 
977344a3780SDimitry Andric   return NewBB;
978344a3780SDimitry Andric }
979344a3780SDimitry Andric 
createPHIsForSplitLoopExit(ArrayRef<BasicBlock * > Preds,BasicBlock * SplitBB,BasicBlock * DestBB)980344a3780SDimitry Andric void llvm::createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
981344a3780SDimitry Andric                                       BasicBlock *SplitBB, BasicBlock *DestBB) {
982344a3780SDimitry Andric   // SplitBB shouldn't have anything non-trivial in it yet.
983344a3780SDimitry Andric   assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
984344a3780SDimitry Andric           SplitBB->isLandingPad()) &&
985344a3780SDimitry Andric          "SplitBB has non-PHI nodes!");
986344a3780SDimitry Andric 
987344a3780SDimitry Andric   // For each PHI in the destination block.
988344a3780SDimitry Andric   for (PHINode &PN : DestBB->phis()) {
989344a3780SDimitry Andric     int Idx = PN.getBasicBlockIndex(SplitBB);
990344a3780SDimitry Andric     assert(Idx >= 0 && "Invalid Block Index");
991344a3780SDimitry Andric     Value *V = PN.getIncomingValue(Idx);
992344a3780SDimitry Andric 
993344a3780SDimitry Andric     // If the input is a PHI which already satisfies LCSSA, don't create
994344a3780SDimitry Andric     // a new one.
995344a3780SDimitry Andric     if (const PHINode *VP = dyn_cast<PHINode>(V))
996344a3780SDimitry Andric       if (VP->getParent() == SplitBB)
997344a3780SDimitry Andric         continue;
998344a3780SDimitry Andric 
999344a3780SDimitry Andric     // Otherwise a new PHI is needed. Create one and populate it.
1000b1c73532SDimitry Andric     PHINode *NewPN = PHINode::Create(PN.getType(), Preds.size(), "split");
1001b1c73532SDimitry Andric     BasicBlock::iterator InsertPos =
1002b1c73532SDimitry Andric         SplitBB->isLandingPad() ? SplitBB->begin()
1003b1c73532SDimitry Andric                                 : SplitBB->getTerminator()->getIterator();
1004b1c73532SDimitry Andric     NewPN->insertBefore(InsertPos);
1005344a3780SDimitry Andric     for (BasicBlock *BB : Preds)
1006344a3780SDimitry Andric       NewPN->addIncoming(V, BB);
1007344a3780SDimitry Andric 
1008344a3780SDimitry Andric     // Update the original PHI.
1009344a3780SDimitry Andric     PN.setIncomingValue(Idx, NewPN);
1010344a3780SDimitry Andric   }
1011344a3780SDimitry Andric }
1012344a3780SDimitry Andric 
10135a5ac124SDimitry Andric unsigned
SplitAllCriticalEdges(Function & F,const CriticalEdgeSplittingOptions & Options)10145a5ac124SDimitry Andric llvm::SplitAllCriticalEdges(Function &F,
10155a5ac124SDimitry Andric                             const CriticalEdgeSplittingOptions &Options) {
101667c32a98SDimitry Andric   unsigned NumBroken = 0;
101701095a5dSDimitry Andric   for (BasicBlock &BB : F) {
1018d8e91e46SDimitry Andric     Instruction *TI = BB.getTerminator();
10191f917f69SDimitry Andric     if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
102067c32a98SDimitry Andric       for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10215a5ac124SDimitry Andric         if (SplitCriticalEdge(TI, i, Options))
102267c32a98SDimitry Andric           ++NumBroken;
102367c32a98SDimitry Andric   }
102467c32a98SDimitry Andric   return NumBroken;
102567c32a98SDimitry Andric }
102667c32a98SDimitry Andric 
SplitBlockImpl(BasicBlock * Old,BasicBlock::iterator SplitPt,DomTreeUpdater * DTU,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName,bool Before)1027b1c73532SDimitry Andric static BasicBlock *SplitBlockImpl(BasicBlock *Old, BasicBlock::iterator SplitPt,
1028b60736ecSDimitry Andric                                   DomTreeUpdater *DTU, DominatorTree *DT,
1029b60736ecSDimitry Andric                                   LoopInfo *LI, MemorySSAUpdater *MSSAU,
1030b60736ecSDimitry Andric                                   const Twine &BBName, bool Before) {
1031b60736ecSDimitry Andric   if (Before) {
1032b60736ecSDimitry Andric     DomTreeUpdater LocalDTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1033b60736ecSDimitry Andric     return splitBlockBefore(Old, SplitPt,
1034b60736ecSDimitry Andric                             DTU ? DTU : (DT ? &LocalDTU : nullptr), LI, MSSAU,
1035b60736ecSDimitry Andric                             BBName);
1036b60736ecSDimitry Andric   }
1037b1c73532SDimitry Andric   BasicBlock::iterator SplitIt = SplitPt;
1038344a3780SDimitry Andric   while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) {
1039009b1c42SEd Schouten     ++SplitIt;
1040344a3780SDimitry Andric     assert(SplitIt != SplitPt->getParent()->end());
1041344a3780SDimitry Andric   }
10421d5ae102SDimitry Andric   std::string Name = BBName.str();
10431d5ae102SDimitry Andric   BasicBlock *New = Old->splitBasicBlock(
10441d5ae102SDimitry Andric       SplitIt, Name.empty() ? Old->getName() + ".split" : Name);
1045009b1c42SEd Schouten 
104659850d08SRoman Divacky   // The new block lives in whichever loop the old one did. This preserves
104759850d08SRoman Divacky   // LCSSA as well, because we force the split point to be after any PHI nodes.
10485a5ac124SDimitry Andric   if (LI)
1049009b1c42SEd Schouten     if (Loop *L = LI->getLoopFor(Old))
10505a5ac124SDimitry Andric       L->addBasicBlockToLoop(New, *LI);
1051009b1c42SEd Schouten 
1052b60736ecSDimitry Andric   if (DTU) {
1053b60736ecSDimitry Andric     SmallVector<DominatorTree::UpdateType, 8> Updates;
1054b60736ecSDimitry Andric     // Old dominates New. New node dominates all other nodes dominated by Old.
1055f65dcba8SDimitry Andric     SmallPtrSet<BasicBlock *, 8> UniqueSuccessorsOfOld;
1056b60736ecSDimitry Andric     Updates.push_back({DominatorTree::Insert, Old, New});
1057f65dcba8SDimitry Andric     Updates.reserve(Updates.size() + 2 * succ_size(New));
1058f65dcba8SDimitry Andric     for (BasicBlock *SuccessorOfOld : successors(New))
1059f65dcba8SDimitry Andric       if (UniqueSuccessorsOfOld.insert(SuccessorOfOld).second) {
1060f65dcba8SDimitry Andric         Updates.push_back({DominatorTree::Insert, New, SuccessorOfOld});
1061f65dcba8SDimitry Andric         Updates.push_back({DominatorTree::Delete, Old, SuccessorOfOld});
1062b60736ecSDimitry Andric       }
1063b60736ecSDimitry Andric 
1064b60736ecSDimitry Andric     DTU->applyUpdates(Updates);
1065b60736ecSDimitry Andric   } else if (DT)
1066cf099d11SDimitry Andric     // Old dominates New. New node dominates all other nodes dominated by Old.
10675a5ac124SDimitry Andric     if (DomTreeNode *OldNode = DT->getNode(Old)) {
106801095a5dSDimitry Andric       std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1069009b1c42SEd Schouten 
10705a5ac124SDimitry Andric       DomTreeNode *NewNode = DT->addNewBlock(New, Old);
107101095a5dSDimitry Andric       for (DomTreeNode *I : Children)
107201095a5dSDimitry Andric         DT->changeImmediateDominator(I, NewNode);
107330815c53SDimitry Andric     }
1074009b1c42SEd Schouten 
1075d8e91e46SDimitry Andric   // Move MemoryAccesses still tracked in Old, but part of New now.
1076d8e91e46SDimitry Andric   // Update accesses in successor blocks accordingly.
1077d8e91e46SDimitry Andric   if (MSSAU)
1078d8e91e46SDimitry Andric     MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
1079d8e91e46SDimitry Andric 
1080009b1c42SEd Schouten   return New;
1081009b1c42SEd Schouten }
1082009b1c42SEd Schouten 
SplitBlock(BasicBlock * Old,BasicBlock::iterator SplitPt,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName,bool Before)1083b1c73532SDimitry Andric BasicBlock *llvm::SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt,
1084b60736ecSDimitry Andric                              DominatorTree *DT, LoopInfo *LI,
1085b60736ecSDimitry Andric                              MemorySSAUpdater *MSSAU, const Twine &BBName,
1086b60736ecSDimitry Andric                              bool Before) {
1087b60736ecSDimitry Andric   return SplitBlockImpl(Old, SplitPt, /*DTU=*/nullptr, DT, LI, MSSAU, BBName,
1088b60736ecSDimitry Andric                         Before);
1089b60736ecSDimitry Andric }
SplitBlock(BasicBlock * Old,BasicBlock::iterator SplitPt,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName,bool Before)1090b1c73532SDimitry Andric BasicBlock *llvm::SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt,
1091b60736ecSDimitry Andric                              DomTreeUpdater *DTU, LoopInfo *LI,
1092b60736ecSDimitry Andric                              MemorySSAUpdater *MSSAU, const Twine &BBName,
1093b60736ecSDimitry Andric                              bool Before) {
1094b60736ecSDimitry Andric   return SplitBlockImpl(Old, SplitPt, DTU, /*DT=*/nullptr, LI, MSSAU, BBName,
1095b60736ecSDimitry Andric                         Before);
1096b60736ecSDimitry Andric }
1097b60736ecSDimitry Andric 
splitBlockBefore(BasicBlock * Old,BasicBlock::iterator SplitPt,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,const Twine & BBName)1098b1c73532SDimitry Andric BasicBlock *llvm::splitBlockBefore(BasicBlock *Old, BasicBlock::iterator SplitPt,
1099b60736ecSDimitry Andric                                    DomTreeUpdater *DTU, LoopInfo *LI,
1100b60736ecSDimitry Andric                                    MemorySSAUpdater *MSSAU,
1101b60736ecSDimitry Andric                                    const Twine &BBName) {
1102b60736ecSDimitry Andric 
1103b1c73532SDimitry Andric   BasicBlock::iterator SplitIt = SplitPt;
1104b60736ecSDimitry Andric   while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
1105b60736ecSDimitry Andric     ++SplitIt;
1106b60736ecSDimitry Andric   std::string Name = BBName.str();
1107b60736ecSDimitry Andric   BasicBlock *New = Old->splitBasicBlock(
1108b60736ecSDimitry Andric       SplitIt, Name.empty() ? Old->getName() + ".split" : Name,
1109b60736ecSDimitry Andric       /* Before=*/true);
1110b60736ecSDimitry Andric 
1111b60736ecSDimitry Andric   // The new block lives in whichever loop the old one did. This preserves
1112b60736ecSDimitry Andric   // LCSSA as well, because we force the split point to be after any PHI nodes.
1113b60736ecSDimitry Andric   if (LI)
1114b60736ecSDimitry Andric     if (Loop *L = LI->getLoopFor(Old))
1115b60736ecSDimitry Andric       L->addBasicBlockToLoop(New, *LI);
1116b60736ecSDimitry Andric 
1117b60736ecSDimitry Andric   if (DTU) {
1118b60736ecSDimitry Andric     SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
1119b60736ecSDimitry Andric     // New dominates Old. The predecessor nodes of the Old node dominate
1120b60736ecSDimitry Andric     // New node.
1121f65dcba8SDimitry Andric     SmallPtrSet<BasicBlock *, 8> UniquePredecessorsOfOld;
1122b60736ecSDimitry Andric     DTUpdates.push_back({DominatorTree::Insert, New, Old});
1123f65dcba8SDimitry Andric     DTUpdates.reserve(DTUpdates.size() + 2 * pred_size(New));
1124f65dcba8SDimitry Andric     for (BasicBlock *PredecessorOfOld : predecessors(New))
1125f65dcba8SDimitry Andric       if (UniquePredecessorsOfOld.insert(PredecessorOfOld).second) {
1126f65dcba8SDimitry Andric         DTUpdates.push_back({DominatorTree::Insert, PredecessorOfOld, New});
1127f65dcba8SDimitry Andric         DTUpdates.push_back({DominatorTree::Delete, PredecessorOfOld, Old});
1128b60736ecSDimitry Andric       }
1129b60736ecSDimitry Andric 
1130b60736ecSDimitry Andric     DTU->applyUpdates(DTUpdates);
1131b60736ecSDimitry Andric 
1132b60736ecSDimitry Andric     // Move MemoryAccesses still tracked in Old, but part of New now.
1133b60736ecSDimitry Andric     // Update accesses in successor blocks accordingly.
1134b60736ecSDimitry Andric     if (MSSAU) {
1135b60736ecSDimitry Andric       MSSAU->applyUpdates(DTUpdates, DTU->getDomTree());
1136b60736ecSDimitry Andric       if (VerifyMemorySSA)
1137b60736ecSDimitry Andric         MSSAU->getMemorySSA()->verifyMemorySSA();
1138b60736ecSDimitry Andric     }
1139b60736ecSDimitry Andric   }
1140b60736ecSDimitry Andric   return New;
1141b60736ecSDimitry Andric }
1142b60736ecSDimitry Andric 
114301095a5dSDimitry Andric /// Update DominatorTree, LoopInfo, and LCCSA analysis information.
1144ac9a064cSDimitry Andric /// Invalidates DFS Numbering when DTU or DT is provided.
UpdateAnalysisInformation(BasicBlock * OldBB,BasicBlock * NewBB,ArrayRef<BasicBlock * > Preds,DomTreeUpdater * DTU,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA,bool & HasLoopExit)114530815c53SDimitry Andric static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
114630815c53SDimitry Andric                                       ArrayRef<BasicBlock *> Preds,
1147b60736ecSDimitry Andric                                       DomTreeUpdater *DTU, DominatorTree *DT,
1148b60736ecSDimitry Andric                                       LoopInfo *LI, MemorySSAUpdater *MSSAU,
11495a5ac124SDimitry Andric                                       bool PreserveLCSSA, bool &HasLoopExit) {
11505a5ac124SDimitry Andric   // Update dominator tree if available.
1151b60736ecSDimitry Andric   if (DTU) {
1152b60736ecSDimitry Andric     // Recalculation of DomTree is needed when updating a forward DomTree and
1153b60736ecSDimitry Andric     // the Entry BB is replaced.
1154344a3780SDimitry Andric     if (NewBB->isEntryBlock() && DTU->hasDomTree()) {
1155b60736ecSDimitry Andric       // The entry block was removed and there is no external interface for
1156b60736ecSDimitry Andric       // the dominator tree to be notified of this change. In this corner-case
1157b60736ecSDimitry Andric       // we recalculate the entire tree.
1158b60736ecSDimitry Andric       DTU->recalculate(*NewBB->getParent());
1159b60736ecSDimitry Andric     } else {
1160b60736ecSDimitry Andric       // Split block expects NewBB to have a non-empty set of predecessors.
1161b60736ecSDimitry Andric       SmallVector<DominatorTree::UpdateType, 8> Updates;
1162f65dcba8SDimitry Andric       SmallPtrSet<BasicBlock *, 8> UniquePreds;
1163b60736ecSDimitry Andric       Updates.push_back({DominatorTree::Insert, NewBB, OldBB});
1164f65dcba8SDimitry Andric       Updates.reserve(Updates.size() + 2 * Preds.size());
1165f65dcba8SDimitry Andric       for (auto *Pred : Preds)
1166f65dcba8SDimitry Andric         if (UniquePreds.insert(Pred).second) {
1167f65dcba8SDimitry Andric           Updates.push_back({DominatorTree::Insert, Pred, NewBB});
1168f65dcba8SDimitry Andric           Updates.push_back({DominatorTree::Delete, Pred, OldBB});
1169b60736ecSDimitry Andric         }
1170b60736ecSDimitry Andric       DTU->applyUpdates(Updates);
1171b60736ecSDimitry Andric     }
1172b60736ecSDimitry Andric   } else if (DT) {
1173eb11fae6SDimitry Andric     if (OldBB == DT->getRootNode()->getBlock()) {
1174344a3780SDimitry Andric       assert(NewBB->isEntryBlock());
1175eb11fae6SDimitry Andric       DT->setNewRoot(NewBB);
1176eb11fae6SDimitry Andric     } else {
1177eb11fae6SDimitry Andric       // Split block expects NewBB to have a non-empty set of predecessors.
11785a5ac124SDimitry Andric       DT->splitBlock(NewBB);
1179eb11fae6SDimitry Andric     }
1180eb11fae6SDimitry Andric   }
118130815c53SDimitry Andric 
1182d8e91e46SDimitry Andric   // Update MemoryPhis after split if MemorySSA is available
1183d8e91e46SDimitry Andric   if (MSSAU)
1184d8e91e46SDimitry Andric     MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
1185d8e91e46SDimitry Andric 
11865a5ac124SDimitry Andric   // The rest of the logic is only relevant for updating the loop structures.
11875a5ac124SDimitry Andric   if (!LI)
11885a5ac124SDimitry Andric     return;
11895a5ac124SDimitry Andric 
1190b60736ecSDimitry Andric   if (DTU && DTU->hasDomTree())
1191b60736ecSDimitry Andric     DT = &DTU->getDomTree();
1192eb11fae6SDimitry Andric   assert(DT && "DT should be available to update LoopInfo!");
11935a5ac124SDimitry Andric   Loop *L = LI->getLoopFor(OldBB);
119430815c53SDimitry Andric 
119530815c53SDimitry Andric   // If we need to preserve loop analyses, collect some information about how
119630815c53SDimitry Andric   // this split will affect loops.
119730815c53SDimitry Andric   bool IsLoopEntry = !!L;
119830815c53SDimitry Andric   bool SplitMakesNewLoopHeader = false;
119901095a5dSDimitry Andric   for (BasicBlock *Pred : Preds) {
1200eb11fae6SDimitry Andric     // Preds that are not reachable from entry should not be used to identify if
1201eb11fae6SDimitry Andric     // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
1202eb11fae6SDimitry Andric     // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
1203eb11fae6SDimitry Andric     // as true and make the NewBB the header of some loop. This breaks LI.
1204eb11fae6SDimitry Andric     if (!DT->isReachableFromEntry(Pred))
1205eb11fae6SDimitry Andric       continue;
120630815c53SDimitry Andric     // If we need to preserve LCSSA, determine if any of the preds is a loop
120730815c53SDimitry Andric     // exit.
120830815c53SDimitry Andric     if (PreserveLCSSA)
120930815c53SDimitry Andric       if (Loop *PL = LI->getLoopFor(Pred))
121030815c53SDimitry Andric         if (!PL->contains(OldBB))
121130815c53SDimitry Andric           HasLoopExit = true;
121230815c53SDimitry Andric 
121330815c53SDimitry Andric     // If we need to preserve LoopInfo, note whether any of the preds crosses
121430815c53SDimitry Andric     // an interesting loop boundary.
12155a5ac124SDimitry Andric     if (!L)
12165a5ac124SDimitry Andric       continue;
121730815c53SDimitry Andric     if (L->contains(Pred))
121830815c53SDimitry Andric       IsLoopEntry = false;
121930815c53SDimitry Andric     else
122030815c53SDimitry Andric       SplitMakesNewLoopHeader = true;
122130815c53SDimitry Andric   }
122230815c53SDimitry Andric 
12235a5ac124SDimitry Andric   // Unless we have a loop for OldBB, nothing else to do here.
12245a5ac124SDimitry Andric   if (!L)
12255a5ac124SDimitry Andric     return;
122630815c53SDimitry Andric 
122730815c53SDimitry Andric   if (IsLoopEntry) {
122830815c53SDimitry Andric     // Add the new block to the nearest enclosing loop (and not an adjacent
122930815c53SDimitry Andric     // loop). To find this, examine each of the predecessors and determine which
123030815c53SDimitry Andric     // loops enclose them, and select the most-nested loop which contains the
123130815c53SDimitry Andric     // loop containing the block being split.
12325ca98fd9SDimitry Andric     Loop *InnermostPredLoop = nullptr;
123301095a5dSDimitry Andric     for (BasicBlock *Pred : Preds) {
123430815c53SDimitry Andric       if (Loop *PredLoop = LI->getLoopFor(Pred)) {
123530815c53SDimitry Andric         // Seek a loop which actually contains the block being split (to avoid
123630815c53SDimitry Andric         // adjacent loops).
123730815c53SDimitry Andric         while (PredLoop && !PredLoop->contains(OldBB))
123830815c53SDimitry Andric           PredLoop = PredLoop->getParentLoop();
123930815c53SDimitry Andric 
124030815c53SDimitry Andric         // Select the most-nested of these loops which contains the block.
124130815c53SDimitry Andric         if (PredLoop && PredLoop->contains(OldBB) &&
124230815c53SDimitry Andric             (!InnermostPredLoop ||
124330815c53SDimitry Andric              InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
124430815c53SDimitry Andric           InnermostPredLoop = PredLoop;
124530815c53SDimitry Andric       }
124630815c53SDimitry Andric     }
124730815c53SDimitry Andric 
124830815c53SDimitry Andric     if (InnermostPredLoop)
12495a5ac124SDimitry Andric       InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
125030815c53SDimitry Andric   } else {
12515a5ac124SDimitry Andric     L->addBasicBlockToLoop(NewBB, *LI);
125230815c53SDimitry Andric     if (SplitMakesNewLoopHeader)
125330815c53SDimitry Andric       L->moveToHeader(NewBB);
125430815c53SDimitry Andric   }
125530815c53SDimitry Andric }
125630815c53SDimitry Andric 
125701095a5dSDimitry Andric /// Update the PHI nodes in OrigBB to include the values coming from NewBB.
125801095a5dSDimitry Andric /// This also updates AliasAnalysis, if available.
UpdatePHINodes(BasicBlock * OrigBB,BasicBlock * NewBB,ArrayRef<BasicBlock * > Preds,BranchInst * BI,bool HasLoopExit)125930815c53SDimitry Andric static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
126030815c53SDimitry Andric                            ArrayRef<BasicBlock *> Preds, BranchInst *BI,
1261dd58ef01SDimitry Andric                            bool HasLoopExit) {
126230815c53SDimitry Andric   // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
12635ca98fd9SDimitry Andric   SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
126430815c53SDimitry Andric   for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
126530815c53SDimitry Andric     PHINode *PN = cast<PHINode>(I++);
126630815c53SDimitry Andric 
126730815c53SDimitry Andric     // Check to see if all of the values coming in are the same.  If so, we
126830815c53SDimitry Andric     // don't need to create a new PHI node, unless it's needed for LCSSA.
12695ca98fd9SDimitry Andric     Value *InVal = nullptr;
127030815c53SDimitry Andric     if (!HasLoopExit) {
127130815c53SDimitry Andric       InVal = PN->getIncomingValueForBlock(Preds[0]);
12725ca98fd9SDimitry Andric       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
12735ca98fd9SDimitry Andric         if (!PredSet.count(PN->getIncomingBlock(i)))
12745ca98fd9SDimitry Andric           continue;
12755ca98fd9SDimitry Andric         if (!InVal)
12765ca98fd9SDimitry Andric           InVal = PN->getIncomingValue(i);
12775ca98fd9SDimitry Andric         else if (InVal != PN->getIncomingValue(i)) {
12785ca98fd9SDimitry Andric           InVal = nullptr;
127930815c53SDimitry Andric           break;
128030815c53SDimitry Andric         }
128130815c53SDimitry Andric       }
12825ca98fd9SDimitry Andric     }
128330815c53SDimitry Andric 
128430815c53SDimitry Andric     if (InVal) {
128530815c53SDimitry Andric       // If all incoming values for the new PHI would be the same, just don't
128630815c53SDimitry Andric       // make a new PHI.  Instead, just remove the incoming values from the old
128730815c53SDimitry Andric       // PHI.
1288b1c73532SDimitry Andric       PN->removeIncomingValueIf(
1289b1c73532SDimitry Andric           [&](unsigned Idx) {
1290b1c73532SDimitry Andric             return PredSet.contains(PN->getIncomingBlock(Idx));
1291b1c73532SDimitry Andric           },
1292b1c73532SDimitry Andric           /* DeletePHIIfEmpty */ false);
129330815c53SDimitry Andric 
129430815c53SDimitry Andric       // Add an incoming value to the PHI node in the loop for the preheader
129530815c53SDimitry Andric       // edge.
129630815c53SDimitry Andric       PN->addIncoming(InVal, NewBB);
12975ca98fd9SDimitry Andric       continue;
12985ca98fd9SDimitry Andric     }
12995ca98fd9SDimitry Andric 
13005ca98fd9SDimitry Andric     // If the values coming into the block are not the same, we need a new
13015ca98fd9SDimitry Andric     // PHI.
13025ca98fd9SDimitry Andric     // Create the new PHI node, insert it into NewBB at the end of the block
13035ca98fd9SDimitry Andric     PHINode *NewPHI =
1304ac9a064cSDimitry Andric         PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI->getIterator());
13055ca98fd9SDimitry Andric 
13065ca98fd9SDimitry Andric     // NOTE! This loop walks backwards for a reason! First off, this minimizes
13075ca98fd9SDimitry Andric     // the cost of removal if we end up removing a large number of values, and
13085ca98fd9SDimitry Andric     // second off, this ensures that the indices for the incoming values aren't
13095ca98fd9SDimitry Andric     // invalidated when we remove one.
13105ca98fd9SDimitry Andric     for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
13115ca98fd9SDimitry Andric       BasicBlock *IncomingBB = PN->getIncomingBlock(i);
13125ca98fd9SDimitry Andric       if (PredSet.count(IncomingBB)) {
13135ca98fd9SDimitry Andric         Value *V = PN->removeIncomingValue(i, false);
13145ca98fd9SDimitry Andric         NewPHI->addIncoming(V, IncomingBB);
13155ca98fd9SDimitry Andric       }
13165ca98fd9SDimitry Andric     }
13175ca98fd9SDimitry Andric 
13185ca98fd9SDimitry Andric     PN->addIncoming(NewPHI, NewBB);
131930815c53SDimitry Andric   }
132030815c53SDimitry Andric }
1321009b1c42SEd Schouten 
1322b60736ecSDimitry Andric static void SplitLandingPadPredecessorsImpl(
1323b60736ecSDimitry Andric     BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1324b60736ecSDimitry Andric     const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1325b60736ecSDimitry Andric     DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1326b60736ecSDimitry Andric     MemorySSAUpdater *MSSAU, bool PreserveLCSSA);
1327b60736ecSDimitry Andric 
1328b60736ecSDimitry Andric static BasicBlock *
SplitBlockPredecessorsImpl(BasicBlock * BB,ArrayRef<BasicBlock * > Preds,const char * Suffix,DomTreeUpdater * DTU,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)1329b60736ecSDimitry Andric SplitBlockPredecessorsImpl(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
1330b60736ecSDimitry Andric                            const char *Suffix, DomTreeUpdater *DTU,
1331b60736ecSDimitry Andric                            DominatorTree *DT, LoopInfo *LI,
1332b60736ecSDimitry Andric                            MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
1333dd58ef01SDimitry Andric   // Do not attempt to split that which cannot be split.
1334dd58ef01SDimitry Andric   if (!BB->canSplitPredecessors())
1335dd58ef01SDimitry Andric     return nullptr;
1336dd58ef01SDimitry Andric 
13375a5ac124SDimitry Andric   // For the landingpads we need to act a bit differently.
13385a5ac124SDimitry Andric   // Delegate this work to the SplitLandingPadPredecessors.
13395a5ac124SDimitry Andric   if (BB->isLandingPad()) {
13405a5ac124SDimitry Andric     SmallVector<BasicBlock*, 2> NewBBs;
13415a5ac124SDimitry Andric     std::string NewName = std::string(Suffix) + ".split-lp";
13425a5ac124SDimitry Andric 
1343b60736ecSDimitry Andric     SplitLandingPadPredecessorsImpl(BB, Preds, Suffix, NewName.c_str(), NewBBs,
1344b60736ecSDimitry Andric                                     DTU, DT, LI, MSSAU, PreserveLCSSA);
13455a5ac124SDimitry Andric     return NewBBs[0];
13465a5ac124SDimitry Andric   }
13475a5ac124SDimitry Andric 
1348009b1c42SEd Schouten   // Create new basic block, insert right before the original block.
13493a0822f0SDimitry Andric   BasicBlock *NewBB = BasicBlock::Create(
13503a0822f0SDimitry Andric       BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
1351009b1c42SEd Schouten 
1352009b1c42SEd Schouten   // The new block unconditionally branches to the old block.
1353009b1c42SEd Schouten   BranchInst *BI = BranchInst::Create(BB, NewBB);
1354b60736ecSDimitry Andric 
1355b60736ecSDimitry Andric   Loop *L = nullptr;
1356b60736ecSDimitry Andric   BasicBlock *OldLatch = nullptr;
1357e6d15924SDimitry Andric   // Splitting the predecessors of a loop header creates a preheader block.
1358b60736ecSDimitry Andric   if (LI && LI->isLoopHeader(BB)) {
1359b60736ecSDimitry Andric     L = LI->getLoopFor(BB);
1360e6d15924SDimitry Andric     // Using the loop start line number prevents debuggers stepping into the
1361e6d15924SDimitry Andric     // loop body for this instruction.
1362b60736ecSDimitry Andric     BI->setDebugLoc(L->getStartLoc());
1363b60736ecSDimitry Andric 
1364b60736ecSDimitry Andric     // If BB is the header of the Loop, it is possible that the loop is
1365b60736ecSDimitry Andric     // modified, such that the current latch does not remain the latch of the
1366b60736ecSDimitry Andric     // loop. If that is the case, the loop metadata from the current latch needs
1367b60736ecSDimitry Andric     // to be applied to the new latch.
1368b60736ecSDimitry Andric     OldLatch = L->getLoopLatch();
1369b60736ecSDimitry Andric   } else
137071d5a254SDimitry Andric     BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
1371009b1c42SEd Schouten 
1372009b1c42SEd Schouten   // Move the edges from Preds to point to NewBB instead of BB.
1373e3b55780SDimitry Andric   for (BasicBlock *Pred : Preds) {
1374907da171SRoman Divacky     // This is slightly more strict than necessary; the minimum requirement
1375907da171SRoman Divacky     // is that there be no more than one indirectbr branching to BB. And
1376907da171SRoman Divacky     // all BlockAddress uses would need to be updated.
1377e3b55780SDimitry Andric     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1378907da171SRoman Divacky            "Cannot split an edge from an IndirectBrInst");
1379e3b55780SDimitry Andric     Pred->getTerminator()->replaceSuccessorWith(BB, NewBB);
138059850d08SRoman Divacky   }
1381009b1c42SEd Schouten 
1382009b1c42SEd Schouten   // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
1383009b1c42SEd Schouten   // node becomes an incoming value for BB's phi node.  However, if the Preds
1384009b1c42SEd Schouten   // list is empty, we need to insert dummy entries into the PHI nodes in BB to
1385009b1c42SEd Schouten   // account for the newly created predecessor.
1386044eb2f6SDimitry Andric   if (Preds.empty()) {
1387009b1c42SEd Schouten     // Insert dummy values as the incoming value.
1388009b1c42SEd Schouten     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
13894b4fe385SDimitry Andric       cast<PHINode>(I)->addIncoming(PoisonValue::get(I->getType()), NewBB);
1390009b1c42SEd Schouten   }
1391009b1c42SEd Schouten 
139230815c53SDimitry Andric   // Update DominatorTree, LoopInfo, and LCCSA analysis information.
139330815c53SDimitry Andric   bool HasLoopExit = false;
1394b60736ecSDimitry Andric   UpdateAnalysisInformation(BB, NewBB, Preds, DTU, DT, LI, MSSAU, PreserveLCSSA,
13955a5ac124SDimitry Andric                             HasLoopExit);
139659850d08SRoman Divacky 
1397eb11fae6SDimitry Andric   if (!Preds.empty()) {
139830815c53SDimitry Andric     // Update the PHI nodes in BB with the values coming from NewBB.
1399dd58ef01SDimitry Andric     UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
1400eb11fae6SDimitry Andric   }
1401eb11fae6SDimitry Andric 
1402b60736ecSDimitry Andric   if (OldLatch) {
1403b60736ecSDimitry Andric     BasicBlock *NewLatch = L->getLoopLatch();
1404b60736ecSDimitry Andric     if (NewLatch != OldLatch) {
1405ac9a064cSDimitry Andric       MDNode *MD = OldLatch->getTerminator()->getMetadata(LLVMContext::MD_loop);
1406ac9a064cSDimitry Andric       NewLatch->getTerminator()->setMetadata(LLVMContext::MD_loop, MD);
1407145449b1SDimitry Andric       // It's still possible that OldLatch is the latch of another inner loop,
1408145449b1SDimitry Andric       // in which case we do not remove the metadata.
1409145449b1SDimitry Andric       Loop *IL = LI->getLoopFor(OldLatch);
1410145449b1SDimitry Andric       if (IL && IL->getLoopLatch() != OldLatch)
1411ac9a064cSDimitry Andric         OldLatch->getTerminator()->setMetadata(LLVMContext::MD_loop, nullptr);
1412b60736ecSDimitry Andric     }
1413b60736ecSDimitry Andric   }
1414b60736ecSDimitry Andric 
1415009b1c42SEd Schouten   return NewBB;
1416009b1c42SEd Schouten }
1417009b1c42SEd Schouten 
SplitBlockPredecessors(BasicBlock * BB,ArrayRef<BasicBlock * > Preds,const char * Suffix,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)1418b60736ecSDimitry Andric BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
141930815c53SDimitry Andric                                          ArrayRef<BasicBlock *> Preds,
1420b60736ecSDimitry Andric                                          const char *Suffix, DominatorTree *DT,
1421b60736ecSDimitry Andric                                          LoopInfo *LI, MemorySSAUpdater *MSSAU,
1422b60736ecSDimitry Andric                                          bool PreserveLCSSA) {
1423b60736ecSDimitry Andric   return SplitBlockPredecessorsImpl(BB, Preds, Suffix, /*DTU=*/nullptr, DT, LI,
1424b60736ecSDimitry Andric                                     MSSAU, PreserveLCSSA);
1425b60736ecSDimitry Andric }
SplitBlockPredecessors(BasicBlock * BB,ArrayRef<BasicBlock * > Preds,const char * Suffix,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)1426b60736ecSDimitry Andric BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
1427b60736ecSDimitry Andric                                          ArrayRef<BasicBlock *> Preds,
1428b60736ecSDimitry Andric                                          const char *Suffix,
1429b60736ecSDimitry Andric                                          DomTreeUpdater *DTU, LoopInfo *LI,
1430d8e91e46SDimitry Andric                                          MemorySSAUpdater *MSSAU,
1431dd58ef01SDimitry Andric                                          bool PreserveLCSSA) {
1432b60736ecSDimitry Andric   return SplitBlockPredecessorsImpl(BB, Preds, Suffix, DTU,
1433b60736ecSDimitry Andric                                     /*DT=*/nullptr, LI, MSSAU, PreserveLCSSA);
1434b60736ecSDimitry Andric }
1435b60736ecSDimitry Andric 
SplitLandingPadPredecessorsImpl(BasicBlock * OrigBB,ArrayRef<BasicBlock * > Preds,const char * Suffix1,const char * Suffix2,SmallVectorImpl<BasicBlock * > & NewBBs,DomTreeUpdater * DTU,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)1436b60736ecSDimitry Andric static void SplitLandingPadPredecessorsImpl(
1437b60736ecSDimitry Andric     BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix1,
1438b60736ecSDimitry Andric     const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
1439b60736ecSDimitry Andric     DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI,
1440b60736ecSDimitry Andric     MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
144130815c53SDimitry Andric   assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
144230815c53SDimitry Andric 
144330815c53SDimitry Andric   // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
144430815c53SDimitry Andric   // it right before the original block.
144530815c53SDimitry Andric   BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
144630815c53SDimitry Andric                                           OrigBB->getName() + Suffix1,
144730815c53SDimitry Andric                                           OrigBB->getParent(), OrigBB);
144830815c53SDimitry Andric   NewBBs.push_back(NewBB1);
144930815c53SDimitry Andric 
145030815c53SDimitry Andric   // The new block unconditionally branches to the old block.
145130815c53SDimitry Andric   BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
14523a0822f0SDimitry Andric   BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
145330815c53SDimitry Andric 
145430815c53SDimitry Andric   // Move the edges from Preds to point to NewBB1 instead of OrigBB.
1455e3b55780SDimitry Andric   for (BasicBlock *Pred : Preds) {
145630815c53SDimitry Andric     // This is slightly more strict than necessary; the minimum requirement
145730815c53SDimitry Andric     // is that there be no more than one indirectbr branching to BB. And
145830815c53SDimitry Andric     // all BlockAddress uses would need to be updated.
1459e3b55780SDimitry Andric     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
146030815c53SDimitry Andric            "Cannot split an edge from an IndirectBrInst");
1461e3b55780SDimitry Andric     Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
146230815c53SDimitry Andric   }
146330815c53SDimitry Andric 
146430815c53SDimitry Andric   bool HasLoopExit = false;
1465b60736ecSDimitry Andric   UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DTU, DT, LI, MSSAU,
1466b60736ecSDimitry Andric                             PreserveLCSSA, HasLoopExit);
146730815c53SDimitry Andric 
146830815c53SDimitry Andric   // Update the PHI nodes in OrigBB with the values coming from NewBB1.
1469dd58ef01SDimitry Andric   UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
147030815c53SDimitry Andric 
147130815c53SDimitry Andric   // Move the remaining edges from OrigBB to point to NewBB2.
147230815c53SDimitry Andric   SmallVector<BasicBlock*, 8> NewBB2Preds;
147330815c53SDimitry Andric   for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
147430815c53SDimitry Andric        i != e; ) {
147530815c53SDimitry Andric     BasicBlock *Pred = *i++;
147630815c53SDimitry Andric     if (Pred == NewBB1) continue;
147730815c53SDimitry Andric     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
147830815c53SDimitry Andric            "Cannot split an edge from an IndirectBrInst");
147930815c53SDimitry Andric     NewBB2Preds.push_back(Pred);
148030815c53SDimitry Andric     e = pred_end(OrigBB);
148130815c53SDimitry Andric   }
148230815c53SDimitry Andric 
14835ca98fd9SDimitry Andric   BasicBlock *NewBB2 = nullptr;
148430815c53SDimitry Andric   if (!NewBB2Preds.empty()) {
148530815c53SDimitry Andric     // Create another basic block for the rest of OrigBB's predecessors.
148630815c53SDimitry Andric     NewBB2 = BasicBlock::Create(OrigBB->getContext(),
148730815c53SDimitry Andric                                 OrigBB->getName() + Suffix2,
148830815c53SDimitry Andric                                 OrigBB->getParent(), OrigBB);
148930815c53SDimitry Andric     NewBBs.push_back(NewBB2);
149030815c53SDimitry Andric 
149130815c53SDimitry Andric     // The new block unconditionally branches to the old block.
149230815c53SDimitry Andric     BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
14933a0822f0SDimitry Andric     BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
149430815c53SDimitry Andric 
149530815c53SDimitry Andric     // Move the remaining edges from OrigBB to point to NewBB2.
149601095a5dSDimitry Andric     for (BasicBlock *NewBB2Pred : NewBB2Preds)
149701095a5dSDimitry Andric       NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
149830815c53SDimitry Andric 
149930815c53SDimitry Andric     // Update DominatorTree, LoopInfo, and LCCSA analysis information.
150030815c53SDimitry Andric     HasLoopExit = false;
1501b60736ecSDimitry Andric     UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DTU, DT, LI, MSSAU,
15025a5ac124SDimitry Andric                               PreserveLCSSA, HasLoopExit);
150330815c53SDimitry Andric 
150430815c53SDimitry Andric     // Update the PHI nodes in OrigBB with the values coming from NewBB2.
1505dd58ef01SDimitry Andric     UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
150630815c53SDimitry Andric   }
150730815c53SDimitry Andric 
150830815c53SDimitry Andric   LandingPadInst *LPad = OrigBB->getLandingPadInst();
150930815c53SDimitry Andric   Instruction *Clone1 = LPad->clone();
151030815c53SDimitry Andric   Clone1->setName(Twine("lpad") + Suffix1);
1511e3b55780SDimitry Andric   Clone1->insertInto(NewBB1, NewBB1->getFirstInsertionPt());
151230815c53SDimitry Andric 
151330815c53SDimitry Andric   if (NewBB2) {
151430815c53SDimitry Andric     Instruction *Clone2 = LPad->clone();
151530815c53SDimitry Andric     Clone2->setName(Twine("lpad") + Suffix2);
1516e3b55780SDimitry Andric     Clone2->insertInto(NewBB2, NewBB2->getFirstInsertionPt());
151730815c53SDimitry Andric 
1518050e163aSDimitry Andric     // Create a PHI node for the two cloned landingpad instructions only
1519050e163aSDimitry Andric     // if the original landingpad instruction has some uses.
1520050e163aSDimitry Andric     if (!LPad->use_empty()) {
1521050e163aSDimitry Andric       assert(!LPad->getType()->isTokenTy() &&
1522050e163aSDimitry Andric              "Split cannot be applied if LPad is token type. Otherwise an "
1523050e163aSDimitry Andric              "invalid PHINode of token type would be created.");
1524ac9a064cSDimitry Andric       PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad->getIterator());
152530815c53SDimitry Andric       PN->addIncoming(Clone1, NewBB1);
152630815c53SDimitry Andric       PN->addIncoming(Clone2, NewBB2);
152730815c53SDimitry Andric       LPad->replaceAllUsesWith(PN);
1528050e163aSDimitry Andric     }
152930815c53SDimitry Andric     LPad->eraseFromParent();
153030815c53SDimitry Andric   } else {
153130815c53SDimitry Andric     // There is no second clone. Just replace the landing pad with the first
153230815c53SDimitry Andric     // clone.
153330815c53SDimitry Andric     LPad->replaceAllUsesWith(Clone1);
153430815c53SDimitry Andric     LPad->eraseFromParent();
153530815c53SDimitry Andric   }
153630815c53SDimitry Andric }
153730815c53SDimitry Andric 
SplitLandingPadPredecessors(BasicBlock * OrigBB,ArrayRef<BasicBlock * > Preds,const char * Suffix1,const char * Suffix2,SmallVectorImpl<BasicBlock * > & NewBBs,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)1538b60736ecSDimitry Andric void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
1539b60736ecSDimitry Andric                                        ArrayRef<BasicBlock *> Preds,
1540b60736ecSDimitry Andric                                        const char *Suffix1, const char *Suffix2,
1541b60736ecSDimitry Andric                                        SmallVectorImpl<BasicBlock *> &NewBBs,
1542b60736ecSDimitry Andric                                        DomTreeUpdater *DTU, LoopInfo *LI,
1543b60736ecSDimitry Andric                                        MemorySSAUpdater *MSSAU,
1544b60736ecSDimitry Andric                                        bool PreserveLCSSA) {
1545b60736ecSDimitry Andric   return SplitLandingPadPredecessorsImpl(OrigBB, Preds, Suffix1, Suffix2,
1546b60736ecSDimitry Andric                                          NewBBs, DTU, /*DT=*/nullptr, LI, MSSAU,
1547b60736ecSDimitry Andric                                          PreserveLCSSA);
1548b60736ecSDimitry Andric }
1549b60736ecSDimitry Andric 
FoldReturnIntoUncondBranch(ReturnInst * RI,BasicBlock * BB,BasicBlock * Pred,DomTreeUpdater * DTU)1550cf099d11SDimitry Andric ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
1551d8e91e46SDimitry Andric                                              BasicBlock *Pred,
1552d8e91e46SDimitry Andric                                              DomTreeUpdater *DTU) {
1553cf099d11SDimitry Andric   Instruction *UncondBranch = Pred->getTerminator();
1554cf099d11SDimitry Andric   // Clone the return and add it to the end of the predecessor.
1555cf099d11SDimitry Andric   Instruction *NewRet = RI->clone();
1556e3b55780SDimitry Andric   NewRet->insertInto(Pred, Pred->end());
1557009b1c42SEd Schouten 
1558cf099d11SDimitry Andric   // If the return instruction returns a value, and if the value was a
1559cf099d11SDimitry Andric   // PHI node in "BB", propagate the right value into the return.
1560344a3780SDimitry Andric   for (Use &Op : NewRet->operands()) {
1561344a3780SDimitry Andric     Value *V = Op;
15625ca98fd9SDimitry Andric     Instruction *NewBC = nullptr;
156358b69754SDimitry Andric     if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
156458b69754SDimitry Andric       // Return value might be bitcasted. Clone and insert it before the
156558b69754SDimitry Andric       // return instruction.
156658b69754SDimitry Andric       V = BCI->getOperand(0);
156758b69754SDimitry Andric       NewBC = BCI->clone();
1568e3b55780SDimitry Andric       NewBC->insertInto(Pred, NewRet->getIterator());
1569344a3780SDimitry Andric       Op = NewBC;
157058b69754SDimitry Andric     }
1571cfca06d7SDimitry Andric 
1572cfca06d7SDimitry Andric     Instruction *NewEV = nullptr;
1573cfca06d7SDimitry Andric     if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
1574cfca06d7SDimitry Andric       V = EVI->getOperand(0);
1575cfca06d7SDimitry Andric       NewEV = EVI->clone();
1576cfca06d7SDimitry Andric       if (NewBC) {
1577cfca06d7SDimitry Andric         NewBC->setOperand(0, NewEV);
1578e3b55780SDimitry Andric         NewEV->insertInto(Pred, NewBC->getIterator());
1579cfca06d7SDimitry Andric       } else {
1580e3b55780SDimitry Andric         NewEV->insertInto(Pred, NewRet->getIterator());
1581344a3780SDimitry Andric         Op = NewEV;
1582cfca06d7SDimitry Andric       }
1583cfca06d7SDimitry Andric     }
1584cfca06d7SDimitry Andric 
158558b69754SDimitry Andric     if (PHINode *PN = dyn_cast<PHINode>(V)) {
158658b69754SDimitry Andric       if (PN->getParent() == BB) {
1587cfca06d7SDimitry Andric         if (NewEV) {
1588cfca06d7SDimitry Andric           NewEV->setOperand(0, PN->getIncomingValueForBlock(Pred));
1589cfca06d7SDimitry Andric         } else if (NewBC)
159058b69754SDimitry Andric           NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
159158b69754SDimitry Andric         else
1592344a3780SDimitry Andric           Op = PN->getIncomingValueForBlock(Pred);
159358b69754SDimitry Andric       }
159458b69754SDimitry Andric     }
159558b69754SDimitry Andric   }
1596cf099d11SDimitry Andric 
1597cf099d11SDimitry Andric   // Update any PHI nodes in the returning block to realize that we no
1598cf099d11SDimitry Andric   // longer branch to them.
1599cf099d11SDimitry Andric   BB->removePredecessor(Pred);
1600cf099d11SDimitry Andric   UncondBranch->eraseFromParent();
1601d8e91e46SDimitry Andric 
1602d8e91e46SDimitry Andric   if (DTU)
1603e6d15924SDimitry Andric     DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}});
1604d8e91e46SDimitry Andric 
1605cf099d11SDimitry Andric   return cast<ReturnInst>(NewRet);
1606009b1c42SEd Schouten }
16076b943ff3SDimitry Andric 
SplitBlockAndInsertIfThen(Value * Cond,BasicBlock::iterator SplitBefore,bool Unreachable,MDNode * BranchWeights,DomTreeUpdater * DTU,LoopInfo * LI,BasicBlock * ThenBlock)1608b60736ecSDimitry Andric Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond,
1609b1c73532SDimitry Andric                                              BasicBlock::iterator SplitBefore,
1610b60736ecSDimitry Andric                                              bool Unreachable,
1611b60736ecSDimitry Andric                                              MDNode *BranchWeights,
1612b60736ecSDimitry Andric                                              DomTreeUpdater *DTU, LoopInfo *LI,
1613b60736ecSDimitry Andric                                              BasicBlock *ThenBlock) {
16147fa27ce4SDimitry Andric   SplitBlockAndInsertIfThenElse(
16157fa27ce4SDimitry Andric       Cond, SplitBefore, &ThenBlock, /* ElseBlock */ nullptr,
16167fa27ce4SDimitry Andric       /* UnreachableThen */ Unreachable,
16177fa27ce4SDimitry Andric       /* UnreachableElse */ false, BranchWeights, DTU, LI);
16187fa27ce4SDimitry Andric   return ThenBlock->getTerminator();
16197fa27ce4SDimitry Andric }
16207fa27ce4SDimitry Andric 
SplitBlockAndInsertIfElse(Value * Cond,BasicBlock::iterator SplitBefore,bool Unreachable,MDNode * BranchWeights,DomTreeUpdater * DTU,LoopInfo * LI,BasicBlock * ElseBlock)16217fa27ce4SDimitry Andric Instruction *llvm::SplitBlockAndInsertIfElse(Value *Cond,
1622b1c73532SDimitry Andric                                              BasicBlock::iterator SplitBefore,
16237fa27ce4SDimitry Andric                                              bool Unreachable,
16247fa27ce4SDimitry Andric                                              MDNode *BranchWeights,
16257fa27ce4SDimitry Andric                                              DomTreeUpdater *DTU, LoopInfo *LI,
16267fa27ce4SDimitry Andric                                              BasicBlock *ElseBlock) {
16277fa27ce4SDimitry Andric   SplitBlockAndInsertIfThenElse(
16287fa27ce4SDimitry Andric       Cond, SplitBefore, /* ThenBlock */ nullptr, &ElseBlock,
16297fa27ce4SDimitry Andric       /* UnreachableThen */ false,
16307fa27ce4SDimitry Andric       /* UnreachableElse */ Unreachable, BranchWeights, DTU, LI);
16317fa27ce4SDimitry Andric   return ElseBlock->getTerminator();
1632b60736ecSDimitry Andric }
1633b60736ecSDimitry Andric 
SplitBlockAndInsertIfThenElse(Value * Cond,BasicBlock::iterator SplitBefore,Instruction ** ThenTerm,Instruction ** ElseTerm,MDNode * BranchWeights,DomTreeUpdater * DTU,LoopInfo * LI)1634b1c73532SDimitry Andric void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore,
1635d8e91e46SDimitry Andric                                          Instruction **ThenTerm,
1636d8e91e46SDimitry Andric                                          Instruction **ElseTerm,
1637e3b55780SDimitry Andric                                          MDNode *BranchWeights,
16387fa27ce4SDimitry Andric                                          DomTreeUpdater *DTU, LoopInfo *LI) {
16397fa27ce4SDimitry Andric   BasicBlock *ThenBlock = nullptr;
16407fa27ce4SDimitry Andric   BasicBlock *ElseBlock = nullptr;
16417fa27ce4SDimitry Andric   SplitBlockAndInsertIfThenElse(
16427fa27ce4SDimitry Andric       Cond, SplitBefore, &ThenBlock, &ElseBlock, /* UnreachableThen */ false,
16437fa27ce4SDimitry Andric       /* UnreachableElse */ false, BranchWeights, DTU, LI);
1644e3b55780SDimitry Andric 
16457fa27ce4SDimitry Andric   *ThenTerm = ThenBlock->getTerminator();
16467fa27ce4SDimitry Andric   *ElseTerm = ElseBlock->getTerminator();
16477fa27ce4SDimitry Andric }
16487fa27ce4SDimitry Andric 
SplitBlockAndInsertIfThenElse(Value * Cond,BasicBlock::iterator SplitBefore,BasicBlock ** ThenBlock,BasicBlock ** ElseBlock,bool UnreachableThen,bool UnreachableElse,MDNode * BranchWeights,DomTreeUpdater * DTU,LoopInfo * LI)16497fa27ce4SDimitry Andric void llvm::SplitBlockAndInsertIfThenElse(
1650b1c73532SDimitry Andric     Value *Cond, BasicBlock::iterator SplitBefore, BasicBlock **ThenBlock,
16517fa27ce4SDimitry Andric     BasicBlock **ElseBlock, bool UnreachableThen, bool UnreachableElse,
16527fa27ce4SDimitry Andric     MDNode *BranchWeights, DomTreeUpdater *DTU, LoopInfo *LI) {
16537fa27ce4SDimitry Andric   assert((ThenBlock || ElseBlock) &&
16547fa27ce4SDimitry Andric          "At least one branch block must be created");
16557fa27ce4SDimitry Andric   assert((!UnreachableThen || !UnreachableElse) &&
16567fa27ce4SDimitry Andric          "Split block tail must be reachable");
16577fa27ce4SDimitry Andric 
16587fa27ce4SDimitry Andric   SmallVector<DominatorTree::UpdateType, 8> Updates;
1659e3b55780SDimitry Andric   SmallPtrSet<BasicBlock *, 8> UniqueOrigSuccessors;
16607fa27ce4SDimitry Andric   BasicBlock *Head = SplitBefore->getParent();
16617fa27ce4SDimitry Andric   if (DTU) {
1662e3b55780SDimitry Andric     UniqueOrigSuccessors.insert(succ_begin(Head), succ_end(Head));
16637fa27ce4SDimitry Andric     Updates.reserve(4 + 2 * UniqueOrigSuccessors.size());
16647fa27ce4SDimitry Andric   }
1665e3b55780SDimitry Andric 
16665ca98fd9SDimitry Andric   LLVMContext &C = Head->getContext();
1667b1c73532SDimitry Andric   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
16687fa27ce4SDimitry Andric   BasicBlock *TrueBlock = Tail;
16697fa27ce4SDimitry Andric   BasicBlock *FalseBlock = Tail;
16707fa27ce4SDimitry Andric   bool ThenToTailEdge = false;
16717fa27ce4SDimitry Andric   bool ElseToTailEdge = false;
16727fa27ce4SDimitry Andric 
16737fa27ce4SDimitry Andric   // Encapsulate the logic around creation/insertion/etc of a new block.
16747fa27ce4SDimitry Andric   auto handleBlock = [&](BasicBlock **PBB, bool Unreachable, BasicBlock *&BB,
16757fa27ce4SDimitry Andric                          bool &ToTailEdge) {
16767fa27ce4SDimitry Andric     if (PBB == nullptr)
16777fa27ce4SDimitry Andric       return; // Do not create/insert a block.
16787fa27ce4SDimitry Andric 
16797fa27ce4SDimitry Andric     if (*PBB)
16807fa27ce4SDimitry Andric       BB = *PBB; // Caller supplied block, use it.
16817fa27ce4SDimitry Andric     else {
16827fa27ce4SDimitry Andric       // Create a new block.
16837fa27ce4SDimitry Andric       BB = BasicBlock::Create(C, "", Head->getParent(), Tail);
16847fa27ce4SDimitry Andric       if (Unreachable)
16857fa27ce4SDimitry Andric         (void)new UnreachableInst(C, BB);
16867fa27ce4SDimitry Andric       else {
16877fa27ce4SDimitry Andric         (void)BranchInst::Create(Tail, BB);
16887fa27ce4SDimitry Andric         ToTailEdge = true;
16897fa27ce4SDimitry Andric       }
16907fa27ce4SDimitry Andric       BB->getTerminator()->setDebugLoc(SplitBefore->getDebugLoc());
16917fa27ce4SDimitry Andric       // Pass the new block back to the caller.
16927fa27ce4SDimitry Andric       *PBB = BB;
16937fa27ce4SDimitry Andric     }
16947fa27ce4SDimitry Andric   };
16957fa27ce4SDimitry Andric 
16967fa27ce4SDimitry Andric   handleBlock(ThenBlock, UnreachableThen, TrueBlock, ThenToTailEdge);
16977fa27ce4SDimitry Andric   handleBlock(ElseBlock, UnreachableElse, FalseBlock, ElseToTailEdge);
16987fa27ce4SDimitry Andric 
16997fa27ce4SDimitry Andric   Instruction *HeadOldTerm = Head->getTerminator();
17005ca98fd9SDimitry Andric   BranchInst *HeadNewTerm =
17017fa27ce4SDimitry Andric       BranchInst::Create(/*ifTrue*/ TrueBlock, /*ifFalse*/ FalseBlock, Cond);
17025ca98fd9SDimitry Andric   HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
17035ca98fd9SDimitry Andric   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
17047fa27ce4SDimitry Andric 
1705e3b55780SDimitry Andric   if (DTU) {
17067fa27ce4SDimitry Andric     Updates.emplace_back(DominatorTree::Insert, Head, TrueBlock);
17077fa27ce4SDimitry Andric     Updates.emplace_back(DominatorTree::Insert, Head, FalseBlock);
17087fa27ce4SDimitry Andric     if (ThenToTailEdge)
17097fa27ce4SDimitry Andric       Updates.emplace_back(DominatorTree::Insert, TrueBlock, Tail);
17107fa27ce4SDimitry Andric     if (ElseToTailEdge)
17117fa27ce4SDimitry Andric       Updates.emplace_back(DominatorTree::Insert, FalseBlock, Tail);
1712e3b55780SDimitry Andric     for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
17137fa27ce4SDimitry Andric       Updates.emplace_back(DominatorTree::Insert, Tail, UniqueOrigSuccessor);
1714e3b55780SDimitry Andric     for (BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
17157fa27ce4SDimitry Andric       Updates.emplace_back(DominatorTree::Delete, Head, UniqueOrigSuccessor);
1716e3b55780SDimitry Andric     DTU->applyUpdates(Updates);
1717e3b55780SDimitry Andric   }
17187fa27ce4SDimitry Andric 
17197fa27ce4SDimitry Andric   if (LI) {
17207fa27ce4SDimitry Andric     if (Loop *L = LI->getLoopFor(Head); L) {
17217fa27ce4SDimitry Andric       if (ThenToTailEdge)
17227fa27ce4SDimitry Andric         L->addBasicBlockToLoop(TrueBlock, *LI);
17237fa27ce4SDimitry Andric       if (ElseToTailEdge)
17247fa27ce4SDimitry Andric         L->addBasicBlockToLoop(FalseBlock, *LI);
17257fa27ce4SDimitry Andric       L->addBasicBlockToLoop(Tail, *LI);
17267fa27ce4SDimitry Andric     }
17277fa27ce4SDimitry Andric   }
17287fa27ce4SDimitry Andric }
17297fa27ce4SDimitry Andric 
17307fa27ce4SDimitry Andric std::pair<Instruction*, Value*>
SplitBlockAndInsertSimpleForLoop(Value * End,Instruction * SplitBefore)17317fa27ce4SDimitry Andric llvm::SplitBlockAndInsertSimpleForLoop(Value *End, Instruction *SplitBefore) {
17327fa27ce4SDimitry Andric   BasicBlock *LoopPred = SplitBefore->getParent();
17337fa27ce4SDimitry Andric   BasicBlock *LoopBody = SplitBlock(SplitBefore->getParent(), SplitBefore);
17347fa27ce4SDimitry Andric   BasicBlock *LoopExit = SplitBlock(SplitBefore->getParent(), SplitBefore);
17357fa27ce4SDimitry Andric 
17367fa27ce4SDimitry Andric   auto *Ty = End->getType();
1737ac9a064cSDimitry Andric   auto &DL = SplitBefore->getDataLayout();
17387fa27ce4SDimitry Andric   const unsigned Bitwidth = DL.getTypeSizeInBits(Ty);
17397fa27ce4SDimitry Andric 
17407fa27ce4SDimitry Andric   IRBuilder<> Builder(LoopBody->getTerminator());
17417fa27ce4SDimitry Andric   auto *IV = Builder.CreatePHI(Ty, 2, "iv");
17427fa27ce4SDimitry Andric   auto *IVNext =
17437fa27ce4SDimitry Andric     Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next",
17447fa27ce4SDimitry Andric                       /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
17457fa27ce4SDimitry Andric   auto *IVCheck = Builder.CreateICmpEQ(IVNext, End,
17467fa27ce4SDimitry Andric                                        IV->getName() + ".check");
17477fa27ce4SDimitry Andric   Builder.CreateCondBr(IVCheck, LoopExit, LoopBody);
17487fa27ce4SDimitry Andric   LoopBody->getTerminator()->eraseFromParent();
17497fa27ce4SDimitry Andric 
17507fa27ce4SDimitry Andric   // Populate the IV PHI.
17517fa27ce4SDimitry Andric   IV->addIncoming(ConstantInt::get(Ty, 0), LoopPred);
17527fa27ce4SDimitry Andric   IV->addIncoming(IVNext, LoopBody);
17537fa27ce4SDimitry Andric 
17547fa27ce4SDimitry Andric   return std::make_pair(LoopBody->getFirstNonPHI(), IV);
17557fa27ce4SDimitry Andric }
17567fa27ce4SDimitry Andric 
SplitBlockAndInsertForEachLane(ElementCount EC,Type * IndexTy,Instruction * InsertBefore,std::function<void (IRBuilderBase &,Value *)> Func)17577fa27ce4SDimitry Andric void llvm::SplitBlockAndInsertForEachLane(ElementCount EC,
17587fa27ce4SDimitry Andric      Type *IndexTy, Instruction *InsertBefore,
17597fa27ce4SDimitry Andric      std::function<void(IRBuilderBase&, Value*)> Func) {
17607fa27ce4SDimitry Andric 
17617fa27ce4SDimitry Andric   IRBuilder<> IRB(InsertBefore);
17627fa27ce4SDimitry Andric 
17637fa27ce4SDimitry Andric   if (EC.isScalable()) {
17647fa27ce4SDimitry Andric     Value *NumElements = IRB.CreateElementCount(IndexTy, EC);
17657fa27ce4SDimitry Andric 
17667fa27ce4SDimitry Andric     auto [BodyIP, Index] =
17677fa27ce4SDimitry Andric       SplitBlockAndInsertSimpleForLoop(NumElements, InsertBefore);
17687fa27ce4SDimitry Andric 
17697fa27ce4SDimitry Andric     IRB.SetInsertPoint(BodyIP);
17707fa27ce4SDimitry Andric     Func(IRB, Index);
17717fa27ce4SDimitry Andric     return;
17727fa27ce4SDimitry Andric   }
17737fa27ce4SDimitry Andric 
17747fa27ce4SDimitry Andric   unsigned Num = EC.getFixedValue();
17757fa27ce4SDimitry Andric   for (unsigned Idx = 0; Idx < Num; ++Idx) {
17767fa27ce4SDimitry Andric     IRB.SetInsertPoint(InsertBefore);
17777fa27ce4SDimitry Andric     Func(IRB, ConstantInt::get(IndexTy, Idx));
17787fa27ce4SDimitry Andric   }
17797fa27ce4SDimitry Andric }
17807fa27ce4SDimitry Andric 
SplitBlockAndInsertForEachLane(Value * EVL,Instruction * InsertBefore,std::function<void (IRBuilderBase &,Value *)> Func)17817fa27ce4SDimitry Andric void llvm::SplitBlockAndInsertForEachLane(
17827fa27ce4SDimitry Andric     Value *EVL, Instruction *InsertBefore,
17837fa27ce4SDimitry Andric     std::function<void(IRBuilderBase &, Value *)> Func) {
17847fa27ce4SDimitry Andric 
17857fa27ce4SDimitry Andric   IRBuilder<> IRB(InsertBefore);
17867fa27ce4SDimitry Andric   Type *Ty = EVL->getType();
17877fa27ce4SDimitry Andric 
17887fa27ce4SDimitry Andric   if (!isa<ConstantInt>(EVL)) {
17897fa27ce4SDimitry Andric     auto [BodyIP, Index] = SplitBlockAndInsertSimpleForLoop(EVL, InsertBefore);
17907fa27ce4SDimitry Andric     IRB.SetInsertPoint(BodyIP);
17917fa27ce4SDimitry Andric     Func(IRB, Index);
17927fa27ce4SDimitry Andric     return;
17937fa27ce4SDimitry Andric   }
17947fa27ce4SDimitry Andric 
17957fa27ce4SDimitry Andric   unsigned Num = cast<ConstantInt>(EVL)->getZExtValue();
17967fa27ce4SDimitry Andric   for (unsigned Idx = 0; Idx < Num; ++Idx) {
17977fa27ce4SDimitry Andric     IRB.SetInsertPoint(InsertBefore);
17987fa27ce4SDimitry Andric     Func(IRB, ConstantInt::get(Ty, Idx));
17997fa27ce4SDimitry Andric   }
18005ca98fd9SDimitry Andric }
18015ca98fd9SDimitry Andric 
GetIfCondition(BasicBlock * BB,BasicBlock * & IfTrue,BasicBlock * & IfFalse)1802344a3780SDimitry Andric BranchInst *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
1803f8af5cf6SDimitry Andric                                  BasicBlock *&IfFalse) {
1804f8af5cf6SDimitry Andric   PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
18055ca98fd9SDimitry Andric   BasicBlock *Pred1 = nullptr;
18065ca98fd9SDimitry Andric   BasicBlock *Pred2 = nullptr;
1807f8af5cf6SDimitry Andric 
1808f8af5cf6SDimitry Andric   if (SomePHI) {
1809f8af5cf6SDimitry Andric     if (SomePHI->getNumIncomingValues() != 2)
18105ca98fd9SDimitry Andric       return nullptr;
1811f8af5cf6SDimitry Andric     Pred1 = SomePHI->getIncomingBlock(0);
1812f8af5cf6SDimitry Andric     Pred2 = SomePHI->getIncomingBlock(1);
1813f8af5cf6SDimitry Andric   } else {
1814f8af5cf6SDimitry Andric     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1815f8af5cf6SDimitry Andric     if (PI == PE) // No predecessor
18165ca98fd9SDimitry Andric       return nullptr;
1817f8af5cf6SDimitry Andric     Pred1 = *PI++;
1818f8af5cf6SDimitry Andric     if (PI == PE) // Only one predecessor
18195ca98fd9SDimitry Andric       return nullptr;
1820f8af5cf6SDimitry Andric     Pred2 = *PI++;
1821f8af5cf6SDimitry Andric     if (PI != PE) // More than two predecessors
18225ca98fd9SDimitry Andric       return nullptr;
1823f8af5cf6SDimitry Andric   }
1824f8af5cf6SDimitry Andric 
1825f8af5cf6SDimitry Andric   // We can only handle branches.  Other control flow will be lowered to
1826f8af5cf6SDimitry Andric   // branches if possible anyway.
1827f8af5cf6SDimitry Andric   BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
1828f8af5cf6SDimitry Andric   BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
18295ca98fd9SDimitry Andric   if (!Pred1Br || !Pred2Br)
18305ca98fd9SDimitry Andric     return nullptr;
1831f8af5cf6SDimitry Andric 
1832f8af5cf6SDimitry Andric   // Eliminate code duplication by ensuring that Pred1Br is conditional if
1833f8af5cf6SDimitry Andric   // either are.
1834f8af5cf6SDimitry Andric   if (Pred2Br->isConditional()) {
1835f8af5cf6SDimitry Andric     // If both branches are conditional, we don't have an "if statement".  In
1836f8af5cf6SDimitry Andric     // reality, we could transform this case, but since the condition will be
1837f8af5cf6SDimitry Andric     // required anyway, we stand no chance of eliminating it, so the xform is
1838f8af5cf6SDimitry Andric     // probably not profitable.
1839f8af5cf6SDimitry Andric     if (Pred1Br->isConditional())
18405ca98fd9SDimitry Andric       return nullptr;
1841f8af5cf6SDimitry Andric 
1842f8af5cf6SDimitry Andric     std::swap(Pred1, Pred2);
1843f8af5cf6SDimitry Andric     std::swap(Pred1Br, Pred2Br);
1844f8af5cf6SDimitry Andric   }
1845f8af5cf6SDimitry Andric 
1846f8af5cf6SDimitry Andric   if (Pred1Br->isConditional()) {
1847f8af5cf6SDimitry Andric     // The only thing we have to watch out for here is to make sure that Pred2
1848f8af5cf6SDimitry Andric     // doesn't have incoming edges from other blocks.  If it does, the condition
1849f8af5cf6SDimitry Andric     // doesn't dominate BB.
18505ca98fd9SDimitry Andric     if (!Pred2->getSinglePredecessor())
18515ca98fd9SDimitry Andric       return nullptr;
1852f8af5cf6SDimitry Andric 
1853f8af5cf6SDimitry Andric     // If we found a conditional branch predecessor, make sure that it branches
1854f8af5cf6SDimitry Andric     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
1855f8af5cf6SDimitry Andric     if (Pred1Br->getSuccessor(0) == BB &&
1856f8af5cf6SDimitry Andric         Pred1Br->getSuccessor(1) == Pred2) {
1857f8af5cf6SDimitry Andric       IfTrue = Pred1;
1858f8af5cf6SDimitry Andric       IfFalse = Pred2;
1859f8af5cf6SDimitry Andric     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
1860f8af5cf6SDimitry Andric                Pred1Br->getSuccessor(1) == BB) {
1861f8af5cf6SDimitry Andric       IfTrue = Pred2;
1862f8af5cf6SDimitry Andric       IfFalse = Pred1;
1863f8af5cf6SDimitry Andric     } else {
1864f8af5cf6SDimitry Andric       // We know that one arm of the conditional goes to BB, so the other must
1865f8af5cf6SDimitry Andric       // go somewhere unrelated, and this must not be an "if statement".
18665ca98fd9SDimitry Andric       return nullptr;
1867f8af5cf6SDimitry Andric     }
1868f8af5cf6SDimitry Andric 
1869344a3780SDimitry Andric     return Pred1Br;
1870f8af5cf6SDimitry Andric   }
1871f8af5cf6SDimitry Andric 
1872f8af5cf6SDimitry Andric   // Ok, if we got here, both predecessors end with an unconditional branch to
1873f8af5cf6SDimitry Andric   // BB.  Don't panic!  If both blocks only have a single (identical)
1874f8af5cf6SDimitry Andric   // predecessor, and THAT is a conditional branch, then we're all ok!
1875f8af5cf6SDimitry Andric   BasicBlock *CommonPred = Pred1->getSinglePredecessor();
18765ca98fd9SDimitry Andric   if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
18775ca98fd9SDimitry Andric     return nullptr;
1878f8af5cf6SDimitry Andric 
1879f8af5cf6SDimitry Andric   // Otherwise, if this is a conditional branch, then we can use it!
1880f8af5cf6SDimitry Andric   BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
18815ca98fd9SDimitry Andric   if (!BI) return nullptr;
1882f8af5cf6SDimitry Andric 
1883f8af5cf6SDimitry Andric   assert(BI->isConditional() && "Two successors but not conditional?");
1884f8af5cf6SDimitry Andric   if (BI->getSuccessor(0) == Pred1) {
1885f8af5cf6SDimitry Andric     IfTrue = Pred1;
1886f8af5cf6SDimitry Andric     IfFalse = Pred2;
1887f8af5cf6SDimitry Andric   } else {
1888f8af5cf6SDimitry Andric     IfTrue = Pred2;
1889f8af5cf6SDimitry Andric     IfFalse = Pred1;
1890f8af5cf6SDimitry Andric   }
1891344a3780SDimitry Andric   return BI;
1892f8af5cf6SDimitry Andric }
1893cfca06d7SDimitry Andric 
1894cfca06d7SDimitry Andric // After creating a control flow hub, the operands of PHINodes in an outgoing
1895cfca06d7SDimitry Andric // block Out no longer match the predecessors of that block. Predecessors of Out
1896cfca06d7SDimitry Andric // that are incoming blocks to the hub are now replaced by just one edge from
1897cfca06d7SDimitry Andric // the hub. To match this new control flow, the corresponding values from each
1898cfca06d7SDimitry Andric // PHINode must now be moved a new PHINode in the first guard block of the hub.
1899cfca06d7SDimitry Andric //
1900cfca06d7SDimitry Andric // This operation cannot be performed with SSAUpdater, because it involves one
1901cfca06d7SDimitry Andric // new use: If the block Out is in the list of Incoming blocks, then the newly
1902cfca06d7SDimitry Andric // created PHI in the Hub will use itself along that edge from Out to Hub.
reconnectPhis(BasicBlock * Out,BasicBlock * GuardBlock,const SetVector<BasicBlock * > & Incoming,BasicBlock * FirstGuardBlock)1903cfca06d7SDimitry Andric static void reconnectPhis(BasicBlock *Out, BasicBlock *GuardBlock,
1904cfca06d7SDimitry Andric                           const SetVector<BasicBlock *> &Incoming,
1905cfca06d7SDimitry Andric                           BasicBlock *FirstGuardBlock) {
1906cfca06d7SDimitry Andric   auto I = Out->begin();
1907cfca06d7SDimitry Andric   while (I != Out->end() && isa<PHINode>(I)) {
1908cfca06d7SDimitry Andric     auto Phi = cast<PHINode>(I);
1909cfca06d7SDimitry Andric     auto NewPhi =
1910cfca06d7SDimitry Andric         PHINode::Create(Phi->getType(), Incoming.size(),
1911ac9a064cSDimitry Andric                         Phi->getName() + ".moved", FirstGuardBlock->begin());
1912e3b55780SDimitry Andric     for (auto *In : Incoming) {
1913cfca06d7SDimitry Andric       Value *V = UndefValue::get(Phi->getType());
1914cfca06d7SDimitry Andric       if (In == Out) {
1915cfca06d7SDimitry Andric         V = NewPhi;
1916cfca06d7SDimitry Andric       } else if (Phi->getBasicBlockIndex(In) != -1) {
1917cfca06d7SDimitry Andric         V = Phi->removeIncomingValue(In, false);
1918cfca06d7SDimitry Andric       }
1919cfca06d7SDimitry Andric       NewPhi->addIncoming(V, In);
1920cfca06d7SDimitry Andric     }
1921cfca06d7SDimitry Andric     assert(NewPhi->getNumIncomingValues() == Incoming.size());
1922cfca06d7SDimitry Andric     if (Phi->getNumOperands() == 0) {
1923cfca06d7SDimitry Andric       Phi->replaceAllUsesWith(NewPhi);
1924cfca06d7SDimitry Andric       I = Phi->eraseFromParent();
1925cfca06d7SDimitry Andric       continue;
1926cfca06d7SDimitry Andric     }
1927cfca06d7SDimitry Andric     Phi->addIncoming(NewPhi, GuardBlock);
1928cfca06d7SDimitry Andric     ++I;
1929cfca06d7SDimitry Andric   }
1930cfca06d7SDimitry Andric }
1931cfca06d7SDimitry Andric 
1932e3b55780SDimitry Andric using BBPredicates = DenseMap<BasicBlock *, Instruction *>;
1933cfca06d7SDimitry Andric using BBSetVector = SetVector<BasicBlock *>;
1934cfca06d7SDimitry Andric 
1935cfca06d7SDimitry Andric // Redirects the terminator of the incoming block to the first guard
1936cfca06d7SDimitry Andric // block in the hub. The condition of the original terminator (if it
1937cfca06d7SDimitry Andric // was conditional) and its original successors are returned as a
1938cfca06d7SDimitry Andric // tuple <condition, succ0, succ1>. The function additionally filters
1939cfca06d7SDimitry Andric // out successors that are not in the set of outgoing blocks.
1940cfca06d7SDimitry Andric //
1941cfca06d7SDimitry Andric // - condition is non-null iff the branch is conditional.
1942cfca06d7SDimitry Andric // - Succ1 is non-null iff the sole/taken target is an outgoing block.
1943cfca06d7SDimitry Andric // - Succ2 is non-null iff condition is non-null and the fallthrough
1944cfca06d7SDimitry Andric //         target is an outgoing block.
1945cfca06d7SDimitry Andric static std::tuple<Value *, BasicBlock *, BasicBlock *>
redirectToHub(BasicBlock * BB,BasicBlock * FirstGuardBlock,const BBSetVector & Outgoing)1946cfca06d7SDimitry Andric redirectToHub(BasicBlock *BB, BasicBlock *FirstGuardBlock,
1947cfca06d7SDimitry Andric               const BBSetVector &Outgoing) {
1948e3b55780SDimitry Andric   assert(isa<BranchInst>(BB->getTerminator()) &&
1949e3b55780SDimitry Andric          "Only support branch terminator.");
1950cfca06d7SDimitry Andric   auto Branch = cast<BranchInst>(BB->getTerminator());
1951cfca06d7SDimitry Andric   auto Condition = Branch->isConditional() ? Branch->getCondition() : nullptr;
1952cfca06d7SDimitry Andric 
1953cfca06d7SDimitry Andric   BasicBlock *Succ0 = Branch->getSuccessor(0);
1954cfca06d7SDimitry Andric   BasicBlock *Succ1 = nullptr;
1955cfca06d7SDimitry Andric   Succ0 = Outgoing.count(Succ0) ? Succ0 : nullptr;
1956cfca06d7SDimitry Andric 
1957cfca06d7SDimitry Andric   if (Branch->isUnconditional()) {
1958cfca06d7SDimitry Andric     Branch->setSuccessor(0, FirstGuardBlock);
1959cfca06d7SDimitry Andric     assert(Succ0);
1960cfca06d7SDimitry Andric   } else {
1961cfca06d7SDimitry Andric     Succ1 = Branch->getSuccessor(1);
1962cfca06d7SDimitry Andric     Succ1 = Outgoing.count(Succ1) ? Succ1 : nullptr;
1963cfca06d7SDimitry Andric     assert(Succ0 || Succ1);
1964cfca06d7SDimitry Andric     if (Succ0 && !Succ1) {
1965cfca06d7SDimitry Andric       Branch->setSuccessor(0, FirstGuardBlock);
1966cfca06d7SDimitry Andric     } else if (Succ1 && !Succ0) {
1967cfca06d7SDimitry Andric       Branch->setSuccessor(1, FirstGuardBlock);
1968cfca06d7SDimitry Andric     } else {
1969cfca06d7SDimitry Andric       Branch->eraseFromParent();
1970cfca06d7SDimitry Andric       BranchInst::Create(FirstGuardBlock, BB);
1971cfca06d7SDimitry Andric     }
1972cfca06d7SDimitry Andric   }
1973cfca06d7SDimitry Andric 
1974cfca06d7SDimitry Andric   assert(Succ0 || Succ1);
1975cfca06d7SDimitry Andric   return std::make_tuple(Condition, Succ0, Succ1);
1976cfca06d7SDimitry Andric }
1977e3b55780SDimitry Andric // Setup the branch instructions for guard blocks.
1978cfca06d7SDimitry Andric //
1979cfca06d7SDimitry Andric // Each guard block terminates in a conditional branch that transfers
1980cfca06d7SDimitry Andric // control to the corresponding outgoing block or the next guard
1981cfca06d7SDimitry Andric // block. The last guard block has two outgoing blocks as successors
1982cfca06d7SDimitry Andric // since the condition for the final outgoing block is trivially
1983cfca06d7SDimitry Andric // true. So we create one less block (including the first guard block)
1984cfca06d7SDimitry Andric // than the number of outgoing blocks.
setupBranchForGuard(SmallVectorImpl<BasicBlock * > & GuardBlocks,const BBSetVector & Outgoing,BBPredicates & GuardPredicates)1985e3b55780SDimitry Andric static void setupBranchForGuard(SmallVectorImpl<BasicBlock *> &GuardBlocks,
1986e3b55780SDimitry Andric                                 const BBSetVector &Outgoing,
1987e3b55780SDimitry Andric                                 BBPredicates &GuardPredicates) {
1988cfca06d7SDimitry Andric   // To help keep the loop simple, temporarily append the last
1989cfca06d7SDimitry Andric   // outgoing block to the list of guard blocks.
1990cfca06d7SDimitry Andric   GuardBlocks.push_back(Outgoing.back());
1991cfca06d7SDimitry Andric 
1992cfca06d7SDimitry Andric   for (int i = 0, e = GuardBlocks.size() - 1; i != e; ++i) {
1993cfca06d7SDimitry Andric     auto Out = Outgoing[i];
1994cfca06d7SDimitry Andric     assert(GuardPredicates.count(Out));
1995cfca06d7SDimitry Andric     BranchInst::Create(Out, GuardBlocks[i + 1], GuardPredicates[Out],
1996cfca06d7SDimitry Andric                        GuardBlocks[i]);
1997cfca06d7SDimitry Andric   }
1998cfca06d7SDimitry Andric 
1999cfca06d7SDimitry Andric   // Remove the last block from the guard list.
2000cfca06d7SDimitry Andric   GuardBlocks.pop_back();
2001cfca06d7SDimitry Andric }
2002cfca06d7SDimitry Andric 
2003e3b55780SDimitry Andric /// We are using one integer to represent the block we are branching to. Then at
2004e3b55780SDimitry Andric /// each guard block, the predicate was calcuated using a simple `icmp eq`.
calcPredicateUsingInteger(const BBSetVector & Incoming,const BBSetVector & Outgoing,SmallVectorImpl<BasicBlock * > & GuardBlocks,BBPredicates & GuardPredicates)2005e3b55780SDimitry Andric static void calcPredicateUsingInteger(
2006e3b55780SDimitry Andric     const BBSetVector &Incoming, const BBSetVector &Outgoing,
2007e3b55780SDimitry Andric     SmallVectorImpl<BasicBlock *> &GuardBlocks, BBPredicates &GuardPredicates) {
2008e3b55780SDimitry Andric   auto &Context = Incoming.front()->getContext();
2009e3b55780SDimitry Andric   auto FirstGuardBlock = GuardBlocks.front();
2010e3b55780SDimitry Andric 
2011e3b55780SDimitry Andric   auto Phi = PHINode::Create(Type::getInt32Ty(Context), Incoming.size(),
2012e3b55780SDimitry Andric                              "merged.bb.idx", FirstGuardBlock);
2013e3b55780SDimitry Andric 
2014e3b55780SDimitry Andric   for (auto In : Incoming) {
2015e3b55780SDimitry Andric     Value *Condition;
2016e3b55780SDimitry Andric     BasicBlock *Succ0;
2017e3b55780SDimitry Andric     BasicBlock *Succ1;
2018e3b55780SDimitry Andric     std::tie(Condition, Succ0, Succ1) =
2019e3b55780SDimitry Andric         redirectToHub(In, FirstGuardBlock, Outgoing);
2020e3b55780SDimitry Andric     Value *IncomingId = nullptr;
2021e3b55780SDimitry Andric     if (Succ0 && Succ1) {
2022e3b55780SDimitry Andric       // target_bb_index = Condition ? index_of_succ0 : index_of_succ1.
2023e3b55780SDimitry Andric       auto Succ0Iter = find(Outgoing, Succ0);
2024e3b55780SDimitry Andric       auto Succ1Iter = find(Outgoing, Succ1);
2025e3b55780SDimitry Andric       Value *Id0 = ConstantInt::get(Type::getInt32Ty(Context),
2026e3b55780SDimitry Andric                                     std::distance(Outgoing.begin(), Succ0Iter));
2027e3b55780SDimitry Andric       Value *Id1 = ConstantInt::get(Type::getInt32Ty(Context),
2028e3b55780SDimitry Andric                                     std::distance(Outgoing.begin(), Succ1Iter));
2029e3b55780SDimitry Andric       IncomingId = SelectInst::Create(Condition, Id0, Id1, "target.bb.idx",
2030ac9a064cSDimitry Andric                                       In->getTerminator()->getIterator());
2031e3b55780SDimitry Andric     } else {
2032e3b55780SDimitry Andric       // Get the index of the non-null successor.
2033e3b55780SDimitry Andric       auto SuccIter = Succ0 ? find(Outgoing, Succ0) : find(Outgoing, Succ1);
2034e3b55780SDimitry Andric       IncomingId = ConstantInt::get(Type::getInt32Ty(Context),
2035e3b55780SDimitry Andric                                     std::distance(Outgoing.begin(), SuccIter));
2036e3b55780SDimitry Andric     }
2037e3b55780SDimitry Andric     Phi->addIncoming(IncomingId, In);
2038e3b55780SDimitry Andric   }
2039e3b55780SDimitry Andric 
2040e3b55780SDimitry Andric   for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
2041e3b55780SDimitry Andric     auto Out = Outgoing[i];
2042e3b55780SDimitry Andric     auto Cmp = ICmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, Phi,
2043e3b55780SDimitry Andric                                 ConstantInt::get(Type::getInt32Ty(Context), i),
2044e3b55780SDimitry Andric                                 Out->getName() + ".predicate", GuardBlocks[i]);
2045e3b55780SDimitry Andric     GuardPredicates[Out] = Cmp;
2046e3b55780SDimitry Andric   }
2047e3b55780SDimitry Andric }
2048e3b55780SDimitry Andric 
2049e3b55780SDimitry Andric /// We record the predicate of each outgoing block using a phi of boolean.
calcPredicateUsingBooleans(const BBSetVector & Incoming,const BBSetVector & Outgoing,SmallVectorImpl<BasicBlock * > & GuardBlocks,BBPredicates & GuardPredicates,SmallVectorImpl<WeakVH> & DeletionCandidates)2050e3b55780SDimitry Andric static void calcPredicateUsingBooleans(
2051e3b55780SDimitry Andric     const BBSetVector &Incoming, const BBSetVector &Outgoing,
2052e3b55780SDimitry Andric     SmallVectorImpl<BasicBlock *> &GuardBlocks, BBPredicates &GuardPredicates,
2053e3b55780SDimitry Andric     SmallVectorImpl<WeakVH> &DeletionCandidates) {
2054e3b55780SDimitry Andric   auto &Context = Incoming.front()->getContext();
2055e3b55780SDimitry Andric   auto BoolTrue = ConstantInt::getTrue(Context);
2056e3b55780SDimitry Andric   auto BoolFalse = ConstantInt::getFalse(Context);
2057e3b55780SDimitry Andric   auto FirstGuardBlock = GuardBlocks.front();
2058e3b55780SDimitry Andric 
2059e3b55780SDimitry Andric   // The predicate for the last outgoing is trivially true, and so we
2060e3b55780SDimitry Andric   // process only the first N-1 successors.
2061e3b55780SDimitry Andric   for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
2062e3b55780SDimitry Andric     auto Out = Outgoing[i];
2063e3b55780SDimitry Andric     LLVM_DEBUG(dbgs() << "Creating guard for " << Out->getName() << "\n");
2064e3b55780SDimitry Andric 
2065e3b55780SDimitry Andric     auto Phi =
2066e3b55780SDimitry Andric         PHINode::Create(Type::getInt1Ty(Context), Incoming.size(),
2067e3b55780SDimitry Andric                         StringRef("Guard.") + Out->getName(), FirstGuardBlock);
2068e3b55780SDimitry Andric     GuardPredicates[Out] = Phi;
2069e3b55780SDimitry Andric   }
2070e3b55780SDimitry Andric 
2071e3b55780SDimitry Andric   for (auto *In : Incoming) {
2072e3b55780SDimitry Andric     Value *Condition;
2073e3b55780SDimitry Andric     BasicBlock *Succ0;
2074e3b55780SDimitry Andric     BasicBlock *Succ1;
2075e3b55780SDimitry Andric     std::tie(Condition, Succ0, Succ1) =
2076e3b55780SDimitry Andric         redirectToHub(In, FirstGuardBlock, Outgoing);
2077e3b55780SDimitry Andric 
2078e3b55780SDimitry Andric     // Optimization: Consider an incoming block A with both successors
2079e3b55780SDimitry Andric     // Succ0 and Succ1 in the set of outgoing blocks. The predicates
2080e3b55780SDimitry Andric     // for Succ0 and Succ1 complement each other. If Succ0 is visited
2081e3b55780SDimitry Andric     // first in the loop below, control will branch to Succ0 using the
2082e3b55780SDimitry Andric     // corresponding predicate. But if that branch is not taken, then
2083e3b55780SDimitry Andric     // control must reach Succ1, which means that the incoming value of
2084e3b55780SDimitry Andric     // the predicate from `In` is true for Succ1.
2085e3b55780SDimitry Andric     bool OneSuccessorDone = false;
2086e3b55780SDimitry Andric     for (int i = 0, e = Outgoing.size() - 1; i != e; ++i) {
2087e3b55780SDimitry Andric       auto Out = Outgoing[i];
2088e3b55780SDimitry Andric       PHINode *Phi = cast<PHINode>(GuardPredicates[Out]);
2089e3b55780SDimitry Andric       if (Out != Succ0 && Out != Succ1) {
2090e3b55780SDimitry Andric         Phi->addIncoming(BoolFalse, In);
2091e3b55780SDimitry Andric       } else if (!Succ0 || !Succ1 || OneSuccessorDone) {
2092e3b55780SDimitry Andric         // Optimization: When only one successor is an outgoing block,
2093e3b55780SDimitry Andric         // the incoming predicate from `In` is always true.
2094e3b55780SDimitry Andric         Phi->addIncoming(BoolTrue, In);
2095e3b55780SDimitry Andric       } else {
2096e3b55780SDimitry Andric         assert(Succ0 && Succ1);
2097e3b55780SDimitry Andric         if (Out == Succ0) {
2098e3b55780SDimitry Andric           Phi->addIncoming(Condition, In);
2099e3b55780SDimitry Andric         } else {
2100e3b55780SDimitry Andric           auto Inverted = invertCondition(Condition);
2101e3b55780SDimitry Andric           DeletionCandidates.push_back(Condition);
2102e3b55780SDimitry Andric           Phi->addIncoming(Inverted, In);
2103e3b55780SDimitry Andric         }
2104e3b55780SDimitry Andric         OneSuccessorDone = true;
2105e3b55780SDimitry Andric       }
2106e3b55780SDimitry Andric     }
2107e3b55780SDimitry Andric   }
2108e3b55780SDimitry Andric }
2109e3b55780SDimitry Andric 
2110e3b55780SDimitry Andric // Capture the existing control flow as guard predicates, and redirect
2111e3b55780SDimitry Andric // control flow from \p Incoming block through the \p GuardBlocks to the
2112e3b55780SDimitry Andric // \p Outgoing blocks.
2113e3b55780SDimitry Andric //
2114e3b55780SDimitry Andric // There is one guard predicate for each outgoing block OutBB. The
2115e3b55780SDimitry Andric // predicate represents whether the hub should transfer control flow
2116e3b55780SDimitry Andric // to OutBB. These predicates are NOT ORTHOGONAL. The Hub evaluates
2117e3b55780SDimitry Andric // them in the same order as the Outgoing set-vector, and control
2118e3b55780SDimitry Andric // branches to the first outgoing block whose predicate evaluates to true.
2119e3b55780SDimitry Andric static void
convertToGuardPredicates(SmallVectorImpl<BasicBlock * > & GuardBlocks,SmallVectorImpl<WeakVH> & DeletionCandidates,const BBSetVector & Incoming,const BBSetVector & Outgoing,const StringRef Prefix,std::optional<unsigned> MaxControlFlowBooleans)2120e3b55780SDimitry Andric convertToGuardPredicates(SmallVectorImpl<BasicBlock *> &GuardBlocks,
2121e3b55780SDimitry Andric                          SmallVectorImpl<WeakVH> &DeletionCandidates,
2122e3b55780SDimitry Andric                          const BBSetVector &Incoming,
2123e3b55780SDimitry Andric                          const BBSetVector &Outgoing, const StringRef Prefix,
2124e3b55780SDimitry Andric                          std::optional<unsigned> MaxControlFlowBooleans) {
2125e3b55780SDimitry Andric   BBPredicates GuardPredicates;
2126e3b55780SDimitry Andric   auto F = Incoming.front()->getParent();
2127e3b55780SDimitry Andric 
2128e3b55780SDimitry Andric   for (int i = 0, e = Outgoing.size() - 1; i != e; ++i)
2129e3b55780SDimitry Andric     GuardBlocks.push_back(
2130e3b55780SDimitry Andric         BasicBlock::Create(F->getContext(), Prefix + ".guard", F));
2131e3b55780SDimitry Andric 
2132e3b55780SDimitry Andric   // When we are using an integer to record which target block to jump to, we
2133e3b55780SDimitry Andric   // are creating less live values, actually we are using one single integer to
2134e3b55780SDimitry Andric   // store the index of the target block. When we are using booleans to store
2135e3b55780SDimitry Andric   // the branching information, we need (N-1) boolean values, where N is the
2136e3b55780SDimitry Andric   // number of outgoing block.
2137e3b55780SDimitry Andric   if (!MaxControlFlowBooleans || Outgoing.size() <= *MaxControlFlowBooleans)
2138e3b55780SDimitry Andric     calcPredicateUsingBooleans(Incoming, Outgoing, GuardBlocks, GuardPredicates,
2139e3b55780SDimitry Andric                                DeletionCandidates);
2140e3b55780SDimitry Andric   else
2141e3b55780SDimitry Andric     calcPredicateUsingInteger(Incoming, Outgoing, GuardBlocks, GuardPredicates);
2142e3b55780SDimitry Andric 
2143e3b55780SDimitry Andric   setupBranchForGuard(GuardBlocks, Outgoing, GuardPredicates);
2144e3b55780SDimitry Andric }
2145e3b55780SDimitry Andric 
CreateControlFlowHub(DomTreeUpdater * DTU,SmallVectorImpl<BasicBlock * > & GuardBlocks,const BBSetVector & Incoming,const BBSetVector & Outgoing,const StringRef Prefix,std::optional<unsigned> MaxControlFlowBooleans)2146cfca06d7SDimitry Andric BasicBlock *llvm::CreateControlFlowHub(
2147cfca06d7SDimitry Andric     DomTreeUpdater *DTU, SmallVectorImpl<BasicBlock *> &GuardBlocks,
2148cfca06d7SDimitry Andric     const BBSetVector &Incoming, const BBSetVector &Outgoing,
2149e3b55780SDimitry Andric     const StringRef Prefix, std::optional<unsigned> MaxControlFlowBooleans) {
2150e3b55780SDimitry Andric   if (Outgoing.size() < 2)
2151e3b55780SDimitry Andric     return Outgoing.front();
2152cfca06d7SDimitry Andric 
2153cfca06d7SDimitry Andric   SmallVector<DominatorTree::UpdateType, 16> Updates;
2154cfca06d7SDimitry Andric   if (DTU) {
2155e3b55780SDimitry Andric     for (auto *In : Incoming) {
2156e3b55780SDimitry Andric       for (auto Succ : successors(In))
2157cfca06d7SDimitry Andric         if (Outgoing.count(Succ))
2158cfca06d7SDimitry Andric           Updates.push_back({DominatorTree::Delete, In, Succ});
2159cfca06d7SDimitry Andric     }
2160cfca06d7SDimitry Andric   }
2161cfca06d7SDimitry Andric 
2162cfca06d7SDimitry Andric   SmallVector<WeakVH, 8> DeletionCandidates;
2163e3b55780SDimitry Andric   convertToGuardPredicates(GuardBlocks, DeletionCandidates, Incoming, Outgoing,
2164e3b55780SDimitry Andric                            Prefix, MaxControlFlowBooleans);
2165e3b55780SDimitry Andric   auto FirstGuardBlock = GuardBlocks.front();
2166cfca06d7SDimitry Andric 
2167cfca06d7SDimitry Andric   // Update the PHINodes in each outgoing block to match the new control flow.
2168e3b55780SDimitry Andric   for (int i = 0, e = GuardBlocks.size(); i != e; ++i)
2169cfca06d7SDimitry Andric     reconnectPhis(Outgoing[i], GuardBlocks[i], Incoming, FirstGuardBlock);
2170e3b55780SDimitry Andric 
2171cfca06d7SDimitry Andric   reconnectPhis(Outgoing.back(), GuardBlocks.back(), Incoming, FirstGuardBlock);
2172cfca06d7SDimitry Andric 
2173cfca06d7SDimitry Andric   if (DTU) {
2174cfca06d7SDimitry Andric     int NumGuards = GuardBlocks.size();
2175cfca06d7SDimitry Andric     assert((int)Outgoing.size() == NumGuards + 1);
2176e3b55780SDimitry Andric 
2177e3b55780SDimitry Andric     for (auto In : Incoming)
2178e3b55780SDimitry Andric       Updates.push_back({DominatorTree::Insert, In, FirstGuardBlock});
2179e3b55780SDimitry Andric 
2180cfca06d7SDimitry Andric     for (int i = 0; i != NumGuards - 1; ++i) {
2181cfca06d7SDimitry Andric       Updates.push_back({DominatorTree::Insert, GuardBlocks[i], Outgoing[i]});
2182cfca06d7SDimitry Andric       Updates.push_back(
2183cfca06d7SDimitry Andric           {DominatorTree::Insert, GuardBlocks[i], GuardBlocks[i + 1]});
2184cfca06d7SDimitry Andric     }
2185cfca06d7SDimitry Andric     Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1],
2186cfca06d7SDimitry Andric                        Outgoing[NumGuards - 1]});
2187cfca06d7SDimitry Andric     Updates.push_back({DominatorTree::Insert, GuardBlocks[NumGuards - 1],
2188cfca06d7SDimitry Andric                        Outgoing[NumGuards]});
2189cfca06d7SDimitry Andric     DTU->applyUpdates(Updates);
2190cfca06d7SDimitry Andric   }
2191cfca06d7SDimitry Andric 
2192cfca06d7SDimitry Andric   for (auto I : DeletionCandidates) {
2193cfca06d7SDimitry Andric     if (I->use_empty())
2194cfca06d7SDimitry Andric       if (auto Inst = dyn_cast_or_null<Instruction>(I))
2195cfca06d7SDimitry Andric         Inst->eraseFromParent();
2196cfca06d7SDimitry Andric   }
2197cfca06d7SDimitry Andric 
2198cfca06d7SDimitry Andric   return FirstGuardBlock;
2199cfca06d7SDimitry Andric }
22007fa27ce4SDimitry Andric 
InvertBranch(BranchInst * PBI,IRBuilderBase & Builder)22017fa27ce4SDimitry Andric void llvm::InvertBranch(BranchInst *PBI, IRBuilderBase &Builder) {
22027fa27ce4SDimitry Andric   Value *NewCond = PBI->getCondition();
22037fa27ce4SDimitry Andric   // If this is a "cmp" instruction, only used for branching (and nowhere
22047fa27ce4SDimitry Andric   // else), then we can simply invert the predicate.
22057fa27ce4SDimitry Andric   if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
22067fa27ce4SDimitry Andric     CmpInst *CI = cast<CmpInst>(NewCond);
22077fa27ce4SDimitry Andric     CI->setPredicate(CI->getInversePredicate());
22087fa27ce4SDimitry Andric   } else
22097fa27ce4SDimitry Andric     NewCond = Builder.CreateNot(NewCond, NewCond->getName() + ".not");
22107fa27ce4SDimitry Andric 
22117fa27ce4SDimitry Andric   PBI->setCondition(NewCond);
22127fa27ce4SDimitry Andric   PBI->swapSuccessors();
22137fa27ce4SDimitry Andric }
2214b1c73532SDimitry Andric 
hasOnlySimpleTerminator(const Function & F)2215b1c73532SDimitry Andric bool llvm::hasOnlySimpleTerminator(const Function &F) {
2216b1c73532SDimitry Andric   for (auto &BB : F) {
2217b1c73532SDimitry Andric     auto *Term = BB.getTerminator();
2218b1c73532SDimitry Andric     if (!(isa<ReturnInst>(Term) || isa<UnreachableInst>(Term) ||
2219b1c73532SDimitry Andric           isa<BranchInst>(Term)))
2220b1c73532SDimitry Andric       return false;
2221b1c73532SDimitry Andric   }
2222b1c73532SDimitry Andric   return true;
2223b1c73532SDimitry Andric }
2224b1c73532SDimitry Andric 
isPresplitCoroSuspendExitEdge(const BasicBlock & Src,const BasicBlock & Dest)2225b1c73532SDimitry Andric bool llvm::isPresplitCoroSuspendExitEdge(const BasicBlock &Src,
2226b1c73532SDimitry Andric                                          const BasicBlock &Dest) {
2227b1c73532SDimitry Andric   assert(Src.getParent() == Dest.getParent());
2228b1c73532SDimitry Andric   if (!Src.getParent()->isPresplitCoroutine())
2229b1c73532SDimitry Andric     return false;
2230b1c73532SDimitry Andric   if (auto *SW = dyn_cast<SwitchInst>(Src.getTerminator()))
2231b1c73532SDimitry Andric     if (auto *Intr = dyn_cast<IntrinsicInst>(SW->getCondition()))
2232b1c73532SDimitry Andric       return Intr->getIntrinsicID() == Intrinsic::coro_suspend &&
2233b1c73532SDimitry Andric              SW->getDefaultDest() == &Dest;
2234b1c73532SDimitry Andric   return false;
2235b1c73532SDimitry Andric }
2236