12cab237bSDimitry Andric //===- BasicBlockUtils.cpp - BasicBlock Utilities --------------------------==//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This family of functions perform manipulations on basic blocks, and
11f22ef01cSRoman Divacky // instructions contained within basic blocks.
12f22ef01cSRoman Divacky //
13f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
14f22ef01cSRoman Divacky 
15f22ef01cSRoman Divacky #include "llvm/Transforms/Utils/BasicBlockUtils.h"
162cab237bSDimitry Andric #include "llvm/ADT/ArrayRef.h"
172cab237bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
182cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
192cab237bSDimitry Andric #include "llvm/ADT/Twine.h"
20f785676fSDimitry Andric #include "llvm/Analysis/CFG.h"
212754fe60SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
222754fe60SDimitry Andric #include "llvm/Analysis/MemoryDependenceAnalysis.h"
23*b5893f02SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
24*b5893f02SDimitry Andric #include "llvm/Analysis/PostDominators.h"
252cab237bSDimitry Andric #include "llvm/IR/BasicBlock.h"
262cab237bSDimitry Andric #include "llvm/IR/CFG.h"
272cab237bSDimitry Andric #include "llvm/IR/Constants.h"
282cab237bSDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
29*b5893f02SDimitry Andric #include "llvm/IR/DomTreeUpdater.h"
3091bc56edSDimitry Andric #include "llvm/IR/Dominators.h"
31139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
322cab237bSDimitry Andric #include "llvm/IR/InstrTypes.h"
332cab237bSDimitry Andric #include "llvm/IR/Instruction.h"
34139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
35139f7f9bSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
362cab237bSDimitry Andric #include "llvm/IR/LLVMContext.h"
37139f7f9bSDimitry Andric #include "llvm/IR/Type.h"
382cab237bSDimitry Andric #include "llvm/IR/User.h"
392cab237bSDimitry Andric #include "llvm/IR/Value.h"
4091bc56edSDimitry Andric #include "llvm/IR/ValueHandle.h"
412cab237bSDimitry Andric #include "llvm/Support/Casting.h"
42*b5893f02SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
432cab237bSDimitry Andric #include <cassert>
442cab237bSDimitry Andric #include <cstdint>
452cab237bSDimitry Andric #include <string>
462cab237bSDimitry Andric #include <utility>
472cab237bSDimitry Andric #include <vector>
482cab237bSDimitry Andric 
49f22ef01cSRoman Divacky using namespace llvm;
50f22ef01cSRoman Divacky 
DeleteDeadBlock(BasicBlock * BB,DomTreeUpdater * DTU)51*b5893f02SDimitry Andric void llvm::DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU) {
52*b5893f02SDimitry Andric   SmallVector<BasicBlock *, 1> BBs = {BB};
53*b5893f02SDimitry Andric   DeleteDeadBlocks(BBs, DTU);
54*b5893f02SDimitry Andric }
55f22ef01cSRoman Divacky 
DeleteDeadBlocks(SmallVectorImpl<BasicBlock * > & BBs,DomTreeUpdater * DTU)56*b5893f02SDimitry Andric void llvm::DeleteDeadBlocks(SmallVectorImpl <BasicBlock *> &BBs,
57*b5893f02SDimitry Andric                             DomTreeUpdater *DTU) {
58*b5893f02SDimitry Andric #ifndef NDEBUG
59*b5893f02SDimitry Andric   // Make sure that all predecessors of each dead block is also dead.
60*b5893f02SDimitry Andric   SmallPtrSet<BasicBlock *, 4> Dead(BBs.begin(), BBs.end());
61*b5893f02SDimitry Andric   assert(Dead.size() == BBs.size() && "Duplicating blocks?");
62*b5893f02SDimitry Andric   for (auto *BB : Dead)
63*b5893f02SDimitry Andric     for (BasicBlock *Pred : predecessors(BB))
64*b5893f02SDimitry Andric       assert(Dead.count(Pred) && "All predecessors must be dead!");
65*b5893f02SDimitry Andric #endif
66*b5893f02SDimitry Andric 
67*b5893f02SDimitry Andric   SmallVector<DominatorTree::UpdateType, 4> Updates;
68*b5893f02SDimitry Andric   for (auto *BB : BBs) {
69f22ef01cSRoman Divacky     // Loop through all of our successors and make sure they know that one
70f22ef01cSRoman Divacky     // of their predecessors is going away.
71*b5893f02SDimitry Andric     for (BasicBlock *Succ : successors(BB)) {
727d523365SDimitry Andric       Succ->removePredecessor(BB);
73*b5893f02SDimitry Andric       if (DTU)
744ba319b5SDimitry Andric         Updates.push_back({DominatorTree::Delete, BB, Succ});
754ba319b5SDimitry Andric     }
76f22ef01cSRoman Divacky 
77f22ef01cSRoman Divacky     // Zap all the instructions in the block.
78f22ef01cSRoman Divacky     while (!BB->empty()) {
79f22ef01cSRoman Divacky       Instruction &I = BB->back();
80f22ef01cSRoman Divacky       // If this instruction is used, replace uses with an arbitrary value.
81f22ef01cSRoman Divacky       // Because control flow can't get here, we don't care what we replace the
82f22ef01cSRoman Divacky       // value with.  Note that since this block is unreachable, and all values
83f22ef01cSRoman Divacky       // contained within it must dominate their uses, that all uses will
84f22ef01cSRoman Divacky       // eventually be removed (they are themselves dead).
85f22ef01cSRoman Divacky       if (!I.use_empty())
86f22ef01cSRoman Divacky         I.replaceAllUsesWith(UndefValue::get(I.getType()));
87f22ef01cSRoman Divacky       BB->getInstList().pop_back();
88f22ef01cSRoman Divacky     }
89*b5893f02SDimitry Andric     new UnreachableInst(BB->getContext(), BB);
90*b5893f02SDimitry Andric     assert(BB->getInstList().size() == 1 &&
91*b5893f02SDimitry Andric            isa<UnreachableInst>(BB->getTerminator()) &&
92*b5893f02SDimitry Andric            "The successor list of BB isn't empty before "
93*b5893f02SDimitry Andric            "applying corresponding DTU updates.");
944ba319b5SDimitry Andric   }
95*b5893f02SDimitry Andric   if (DTU)
96*b5893f02SDimitry Andric     DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
97*b5893f02SDimitry Andric 
98*b5893f02SDimitry Andric   for (BasicBlock *BB : BBs)
99*b5893f02SDimitry Andric     if (DTU)
100*b5893f02SDimitry Andric       DTU->deleteBB(BB);
101*b5893f02SDimitry Andric     else
102*b5893f02SDimitry Andric       BB->eraseFromParent();
103f22ef01cSRoman Divacky }
104f22ef01cSRoman Divacky 
FoldSingleEntryPHINodes(BasicBlock * BB,MemoryDependenceResults * MemDep)1057d523365SDimitry Andric void llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
1063ca95b02SDimitry Andric                                    MemoryDependenceResults *MemDep) {
1072754fe60SDimitry Andric   if (!isa<PHINode>(BB->begin())) return;
1082754fe60SDimitry Andric 
109f22ef01cSRoman Divacky   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
110f22ef01cSRoman Divacky     if (PN->getIncomingValue(0) != PN)
111f22ef01cSRoman Divacky       PN->replaceAllUsesWith(PN->getIncomingValue(0));
112f22ef01cSRoman Divacky     else
113f22ef01cSRoman Divacky       PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1142754fe60SDimitry Andric 
1152754fe60SDimitry Andric     if (MemDep)
1162754fe60SDimitry Andric       MemDep->removeInstruction(PN);  // Memdep updates AA itself.
1172754fe60SDimitry Andric 
118f22ef01cSRoman Divacky     PN->eraseFromParent();
119f22ef01cSRoman Divacky   }
120f22ef01cSRoman Divacky }
121f22ef01cSRoman Divacky 
DeleteDeadPHIs(BasicBlock * BB,const TargetLibraryInfo * TLI)1223861d79fSDimitry Andric bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
123f22ef01cSRoman Divacky   // Recursively deleting a PHI may cause multiple PHIs to be deleted
124f37b6182SDimitry Andric   // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
125f37b6182SDimitry Andric   SmallVector<WeakTrackingVH, 8> PHIs;
12630785c0eSDimitry Andric   for (PHINode &PN : BB->phis())
12730785c0eSDimitry Andric     PHIs.push_back(&PN);
128f22ef01cSRoman Divacky 
129f22ef01cSRoman Divacky   bool Changed = false;
130f22ef01cSRoman Divacky   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
131f22ef01cSRoman Divacky     if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
1323861d79fSDimitry Andric       Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
133f22ef01cSRoman Divacky 
134f22ef01cSRoman Divacky   return Changed;
135f22ef01cSRoman Divacky }
136f22ef01cSRoman Divacky 
MergeBlockIntoPredecessor(BasicBlock * BB,DomTreeUpdater * DTU,LoopInfo * LI,MemorySSAUpdater * MSSAU,MemoryDependenceResults * MemDep)137*b5893f02SDimitry Andric bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU,
138*b5893f02SDimitry Andric                                      LoopInfo *LI, MemorySSAUpdater *MSSAU,
139*b5893f02SDimitry Andric                                      MemoryDependenceResults *MemDep) {
1404ba319b5SDimitry Andric   if (BB->hasAddressTaken())
1414ba319b5SDimitry Andric     return false;
142f22ef01cSRoman Divacky 
143e580952dSDimitry Andric   // Can't merge if there are multiple predecessors, or no predecessors.
144e580952dSDimitry Andric   BasicBlock *PredBB = BB->getUniquePredecessor();
145f22ef01cSRoman Divacky   if (!PredBB) return false;
146e580952dSDimitry Andric 
147f22ef01cSRoman Divacky   // Don't break self-loops.
148f22ef01cSRoman Divacky   if (PredBB == BB) return false;
1497d523365SDimitry Andric   // Don't break unwinding instructions.
150*b5893f02SDimitry Andric   if (PredBB->getTerminator()->isExceptionalTerminator())
1517d523365SDimitry Andric     return false;
152f22ef01cSRoman Divacky 
1534ba319b5SDimitry Andric   // Can't merge if there are multiple distinct successors.
1544ba319b5SDimitry Andric   if (PredBB->getUniqueSuccessor() != BB)
1554ba319b5SDimitry Andric     return false;
156f22ef01cSRoman Divacky 
157f22ef01cSRoman Divacky   // Can't merge if there is PHI loop.
15830785c0eSDimitry Andric   for (PHINode &PN : BB->phis())
15930785c0eSDimitry Andric     for (Value *IncValue : PN.incoming_values())
16030785c0eSDimitry Andric       if (IncValue == &PN)
161f22ef01cSRoman Divacky         return false;
162f22ef01cSRoman Divacky 
163f22ef01cSRoman Divacky   // Begin by getting rid of unneeded PHIs.
1644ba319b5SDimitry Andric   SmallVector<AssertingVH<Value>, 4> IncomingValues;
1652cab237bSDimitry Andric   if (isa<PHINode>(BB->front())) {
16630785c0eSDimitry Andric     for (PHINode &PN : BB->phis())
1674ba319b5SDimitry Andric       if (!isa<PHINode>(PN.getIncomingValue(0)) ||
1684ba319b5SDimitry Andric           cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
16930785c0eSDimitry Andric         IncomingValues.push_back(PN.getIncomingValue(0));
1707d523365SDimitry Andric     FoldSingleEntryPHINodes(BB, MemDep);
1712cab237bSDimitry Andric   }
172f22ef01cSRoman Divacky 
173*b5893f02SDimitry Andric   // DTU update: Collect all the edges that exit BB.
174*b5893f02SDimitry Andric   // These dominator edges will be redirected from Pred.
1754ba319b5SDimitry Andric   std::vector<DominatorTree::UpdateType> Updates;
176*b5893f02SDimitry Andric   if (DTU) {
1774ba319b5SDimitry Andric     Updates.reserve(1 + (2 * succ_size(BB)));
1784ba319b5SDimitry Andric     Updates.push_back({DominatorTree::Delete, PredBB, BB});
1794ba319b5SDimitry Andric     for (auto I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
1804ba319b5SDimitry Andric       Updates.push_back({DominatorTree::Delete, BB, *I});
1814ba319b5SDimitry Andric       Updates.push_back({DominatorTree::Insert, PredBB, *I});
1824ba319b5SDimitry Andric     }
1834ba319b5SDimitry Andric   }
1844ba319b5SDimitry Andric 
185*b5893f02SDimitry Andric   if (MSSAU)
186*b5893f02SDimitry Andric     MSSAU->moveAllAfterMergeBlocks(BB, PredBB, &*(BB->begin()));
187*b5893f02SDimitry Andric 
188f22ef01cSRoman Divacky   // Delete the unconditional branch from the predecessor...
189f22ef01cSRoman Divacky   PredBB->getInstList().pop_back();
190f22ef01cSRoman Divacky 
191f22ef01cSRoman Divacky   // Make all PHI nodes that referred to BB now refer to Pred as their
192f22ef01cSRoman Divacky   // source...
193f22ef01cSRoman Divacky   BB->replaceAllUsesWith(PredBB);
194f22ef01cSRoman Divacky 
19517a519f9SDimitry Andric   // Move all definitions in the successor to the predecessor...
19617a519f9SDimitry Andric   PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
197*b5893f02SDimitry Andric   new UnreachableInst(BB->getContext(), BB);
19817a519f9SDimitry Andric 
1992cab237bSDimitry Andric   // Eliminate duplicate dbg.values describing the entry PHI node post-splice.
2004ba319b5SDimitry Andric   for (auto Incoming : IncomingValues) {
2014ba319b5SDimitry Andric     if (isa<Instruction>(*Incoming)) {
2022cab237bSDimitry Andric       SmallVector<DbgValueInst *, 2> DbgValues;
2032cab237bSDimitry Andric       SmallDenseSet<std::pair<DILocalVariable *, DIExpression *>, 2>
2042cab237bSDimitry Andric           DbgValueSet;
2052cab237bSDimitry Andric       llvm::findDbgValues(DbgValues, Incoming);
2062cab237bSDimitry Andric       for (auto &DVI : DbgValues) {
2072cab237bSDimitry Andric         auto R = DbgValueSet.insert({DVI->getVariable(), DVI->getExpression()});
2082cab237bSDimitry Andric         if (!R.second)
2092cab237bSDimitry Andric           DVI->eraseFromParent();
2102cab237bSDimitry Andric       }
2112cab237bSDimitry Andric     }
2122cab237bSDimitry Andric   }
2132cab237bSDimitry Andric 
214f22ef01cSRoman Divacky   // Inherit predecessors name if it exists.
215f22ef01cSRoman Divacky   if (!PredBB->hasName())
216f22ef01cSRoman Divacky     PredBB->takeName(BB);
217f22ef01cSRoman Divacky 
218ff0cc061SDimitry Andric   if (LI)
2192754fe60SDimitry Andric     LI->removeBlock(BB);
2202754fe60SDimitry Andric 
221ff0cc061SDimitry Andric   if (MemDep)
222ff0cc061SDimitry Andric     MemDep->invalidateCachedPredecessors();
223f22ef01cSRoman Divacky 
224*b5893f02SDimitry Andric   // Finally, erase the old block and update dominator info.
225*b5893f02SDimitry Andric   if (DTU) {
226*b5893f02SDimitry Andric     assert(BB->getInstList().size() == 1 &&
227*b5893f02SDimitry Andric            isa<UnreachableInst>(BB->getTerminator()) &&
228*b5893f02SDimitry Andric            "The successor list of BB isn't empty before "
229*b5893f02SDimitry Andric            "applying corresponding DTU updates.");
230*b5893f02SDimitry Andric     DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
231*b5893f02SDimitry Andric     DTU->deleteBB(BB);
232*b5893f02SDimitry Andric   }
233*b5893f02SDimitry Andric 
234*b5893f02SDimitry Andric   else {
235*b5893f02SDimitry Andric     BB->eraseFromParent(); // Nuke BB if DTU is nullptr.
2364ba319b5SDimitry Andric   }
237f22ef01cSRoman Divacky   return true;
238f22ef01cSRoman Divacky }
239f22ef01cSRoman Divacky 
ReplaceInstWithValue(BasicBlock::InstListType & BIL,BasicBlock::iterator & BI,Value * V)240f22ef01cSRoman Divacky void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
241f22ef01cSRoman Divacky                                 BasicBlock::iterator &BI, Value *V) {
242f22ef01cSRoman Divacky   Instruction &I = *BI;
243f22ef01cSRoman Divacky   // Replaces all of the uses of the instruction with uses of the value
244f22ef01cSRoman Divacky   I.replaceAllUsesWith(V);
245f22ef01cSRoman Divacky 
246f22ef01cSRoman Divacky   // Make sure to propagate a name if there is one already.
247f22ef01cSRoman Divacky   if (I.hasName() && !V->hasName())
248f22ef01cSRoman Divacky     V->takeName(&I);
249f22ef01cSRoman Divacky 
250f22ef01cSRoman Divacky   // Delete the unnecessary instruction now...
251f22ef01cSRoman Divacky   BI = BIL.erase(BI);
252f22ef01cSRoman Divacky }
253f22ef01cSRoman Divacky 
ReplaceInstWithInst(BasicBlock::InstListType & BIL,BasicBlock::iterator & BI,Instruction * I)254f22ef01cSRoman Divacky void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
255f22ef01cSRoman Divacky                                BasicBlock::iterator &BI, Instruction *I) {
25691bc56edSDimitry Andric   assert(I->getParent() == nullptr &&
257f22ef01cSRoman Divacky          "ReplaceInstWithInst: Instruction already inserted into basic block!");
258f22ef01cSRoman Divacky 
2593dac3a9bSDimitry Andric   // Copy debug location to newly added instruction, if it wasn't already set
2603dac3a9bSDimitry Andric   // by the caller.
2613dac3a9bSDimitry Andric   if (!I->getDebugLoc())
2623dac3a9bSDimitry Andric     I->setDebugLoc(BI->getDebugLoc());
2633dac3a9bSDimitry Andric 
264f22ef01cSRoman Divacky   // Insert the new instruction into the basic block...
265f22ef01cSRoman Divacky   BasicBlock::iterator New = BIL.insert(BI, I);
266f22ef01cSRoman Divacky 
267f22ef01cSRoman Divacky   // Replace all uses of the old instruction, and delete it.
268f22ef01cSRoman Divacky   ReplaceInstWithValue(BIL, BI, I);
269f22ef01cSRoman Divacky 
270f22ef01cSRoman Divacky   // Move BI back to point to the newly inserted instruction
271f22ef01cSRoman Divacky   BI = New;
272f22ef01cSRoman Divacky }
273f22ef01cSRoman Divacky 
ReplaceInstWithInst(Instruction * From,Instruction * To)274f22ef01cSRoman Divacky void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
275f22ef01cSRoman Divacky   BasicBlock::iterator BI(From);
276f22ef01cSRoman Divacky   ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
277f22ef01cSRoman Divacky }
278f22ef01cSRoman Divacky 
SplitEdge(BasicBlock * BB,BasicBlock * Succ,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU)279ff0cc061SDimitry Andric BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
280*b5893f02SDimitry Andric                             LoopInfo *LI, MemorySSAUpdater *MSSAU) {
281f22ef01cSRoman Divacky   unsigned SuccNum = GetSuccessorNumber(BB, Succ);
282f22ef01cSRoman Divacky 
283f22ef01cSRoman Divacky   // If this is a critical edge, let SplitCriticalEdge do it.
284*b5893f02SDimitry Andric   Instruction *LatchTerm = BB->getTerminator();
285*b5893f02SDimitry Andric   if (SplitCriticalEdge(
286*b5893f02SDimitry Andric           LatchTerm, SuccNum,
287*b5893f02SDimitry Andric           CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA()))
288f22ef01cSRoman Divacky     return LatchTerm->getSuccessor(SuccNum);
289f22ef01cSRoman Divacky 
290f22ef01cSRoman Divacky   // If the edge isn't critical, then BB has a single successor or Succ has a
291f22ef01cSRoman Divacky   // single pred.  Split the block.
292f22ef01cSRoman Divacky   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
293f22ef01cSRoman Divacky     // If the successor only has a single pred, split the top of the successor
294f22ef01cSRoman Divacky     // block.
295f22ef01cSRoman Divacky     assert(SP == BB && "CFG broken");
29691bc56edSDimitry Andric     SP = nullptr;
297*b5893f02SDimitry Andric     return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU);
2982754fe60SDimitry Andric   }
2992754fe60SDimitry Andric 
300f22ef01cSRoman Divacky   // Otherwise, if BB has a single successor, split it at the bottom of the
301f22ef01cSRoman Divacky   // block.
302f22ef01cSRoman Divacky   assert(BB->getTerminator()->getNumSuccessors() == 1 &&
303f22ef01cSRoman Divacky          "Should have a single succ!");
304*b5893f02SDimitry Andric   return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU);
305f22ef01cSRoman Divacky }
306f22ef01cSRoman Divacky 
307ff0cc061SDimitry Andric unsigned
SplitAllCriticalEdges(Function & F,const CriticalEdgeSplittingOptions & Options)308ff0cc061SDimitry Andric llvm::SplitAllCriticalEdges(Function &F,
309ff0cc061SDimitry Andric                             const CriticalEdgeSplittingOptions &Options) {
31039d628a0SDimitry Andric   unsigned NumBroken = 0;
3113ca95b02SDimitry Andric   for (BasicBlock &BB : F) {
312*b5893f02SDimitry Andric     Instruction *TI = BB.getTerminator();
31339d628a0SDimitry Andric     if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
31439d628a0SDimitry Andric       for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
315ff0cc061SDimitry Andric         if (SplitCriticalEdge(TI, i, Options))
31639d628a0SDimitry Andric           ++NumBroken;
31739d628a0SDimitry Andric   }
31839d628a0SDimitry Andric   return NumBroken;
31939d628a0SDimitry Andric }
32039d628a0SDimitry Andric 
SplitBlock(BasicBlock * Old,Instruction * SplitPt,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU)321ff0cc061SDimitry Andric BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
322*b5893f02SDimitry Andric                              DominatorTree *DT, LoopInfo *LI,
323*b5893f02SDimitry Andric                              MemorySSAUpdater *MSSAU) {
3247d523365SDimitry Andric   BasicBlock::iterator SplitIt = SplitPt->getIterator();
3257d523365SDimitry Andric   while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
326f22ef01cSRoman Divacky     ++SplitIt;
327f22ef01cSRoman Divacky   BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
328f22ef01cSRoman Divacky 
329f22ef01cSRoman Divacky   // The new block lives in whichever loop the old one did. This preserves
330f22ef01cSRoman Divacky   // LCSSA as well, because we force the split point to be after any PHI nodes.
331ff0cc061SDimitry Andric   if (LI)
332f22ef01cSRoman Divacky     if (Loop *L = LI->getLoopFor(Old))
333ff0cc061SDimitry Andric       L->addBasicBlockToLoop(New, *LI);
334f22ef01cSRoman Divacky 
335ff0cc061SDimitry Andric   if (DT)
3362754fe60SDimitry Andric     // Old dominates New. New node dominates all other nodes dominated by Old.
337ff0cc061SDimitry Andric     if (DomTreeNode *OldNode = DT->getNode(Old)) {
3383ca95b02SDimitry Andric       std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
339f22ef01cSRoman Divacky 
340ff0cc061SDimitry Andric       DomTreeNode *NewNode = DT->addNewBlock(New, Old);
3413ca95b02SDimitry Andric       for (DomTreeNode *I : Children)
3423ca95b02SDimitry Andric         DT->changeImmediateDominator(I, NewNode);
3436122f3e6SDimitry Andric     }
344f22ef01cSRoman Divacky 
345*b5893f02SDimitry Andric   // Move MemoryAccesses still tracked in Old, but part of New now.
346*b5893f02SDimitry Andric   // Update accesses in successor blocks accordingly.
347*b5893f02SDimitry Andric   if (MSSAU)
348*b5893f02SDimitry Andric     MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
349*b5893f02SDimitry Andric 
350f22ef01cSRoman Divacky   return New;
351f22ef01cSRoman Divacky }
352f22ef01cSRoman Divacky 
3533ca95b02SDimitry Andric /// Update DominatorTree, LoopInfo, and LCCSA analysis information.
UpdateAnalysisInformation(BasicBlock * OldBB,BasicBlock * NewBB,ArrayRef<BasicBlock * > Preds,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA,bool & HasLoopExit)3546122f3e6SDimitry Andric static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
3556122f3e6SDimitry Andric                                       ArrayRef<BasicBlock *> Preds,
356ff0cc061SDimitry Andric                                       DominatorTree *DT, LoopInfo *LI,
357*b5893f02SDimitry Andric                                       MemorySSAUpdater *MSSAU,
358ff0cc061SDimitry Andric                                       bool PreserveLCSSA, bool &HasLoopExit) {
359ff0cc061SDimitry Andric   // Update dominator tree if available.
3604ba319b5SDimitry Andric   if (DT) {
3614ba319b5SDimitry Andric     if (OldBB == DT->getRootNode()->getBlock()) {
3624ba319b5SDimitry Andric       assert(NewBB == &NewBB->getParent()->getEntryBlock());
3634ba319b5SDimitry Andric       DT->setNewRoot(NewBB);
3644ba319b5SDimitry Andric     } else {
3654ba319b5SDimitry Andric       // Split block expects NewBB to have a non-empty set of predecessors.
366ff0cc061SDimitry Andric       DT->splitBlock(NewBB);
3674ba319b5SDimitry Andric     }
3684ba319b5SDimitry Andric   }
3696122f3e6SDimitry Andric 
370*b5893f02SDimitry Andric   // Update MemoryPhis after split if MemorySSA is available
371*b5893f02SDimitry Andric   if (MSSAU)
372*b5893f02SDimitry Andric     MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
373*b5893f02SDimitry Andric 
374ff0cc061SDimitry Andric   // The rest of the logic is only relevant for updating the loop structures.
375ff0cc061SDimitry Andric   if (!LI)
376ff0cc061SDimitry Andric     return;
377ff0cc061SDimitry Andric 
3784ba319b5SDimitry Andric   assert(DT && "DT should be available to update LoopInfo!");
379ff0cc061SDimitry Andric   Loop *L = LI->getLoopFor(OldBB);
3806122f3e6SDimitry Andric 
3816122f3e6SDimitry Andric   // If we need to preserve loop analyses, collect some information about how
3826122f3e6SDimitry Andric   // this split will affect loops.
3836122f3e6SDimitry Andric   bool IsLoopEntry = !!L;
3846122f3e6SDimitry Andric   bool SplitMakesNewLoopHeader = false;
3853ca95b02SDimitry Andric   for (BasicBlock *Pred : Preds) {
38630785c0eSDimitry Andric     // Preds that are not reachable from entry should not be used to identify if
38730785c0eSDimitry Andric     // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
38830785c0eSDimitry Andric     // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
38930785c0eSDimitry Andric     // as true and make the NewBB the header of some loop. This breaks LI.
39030785c0eSDimitry Andric     if (!DT->isReachableFromEntry(Pred))
39130785c0eSDimitry Andric       continue;
3926122f3e6SDimitry Andric     // If we need to preserve LCSSA, determine if any of the preds is a loop
3936122f3e6SDimitry Andric     // exit.
3946122f3e6SDimitry Andric     if (PreserveLCSSA)
3956122f3e6SDimitry Andric       if (Loop *PL = LI->getLoopFor(Pred))
3966122f3e6SDimitry Andric         if (!PL->contains(OldBB))
3976122f3e6SDimitry Andric           HasLoopExit = true;
3986122f3e6SDimitry Andric 
3996122f3e6SDimitry Andric     // If we need to preserve LoopInfo, note whether any of the preds crosses
4006122f3e6SDimitry Andric     // an interesting loop boundary.
401ff0cc061SDimitry Andric     if (!L)
402ff0cc061SDimitry Andric       continue;
4036122f3e6SDimitry Andric     if (L->contains(Pred))
4046122f3e6SDimitry Andric       IsLoopEntry = false;
4056122f3e6SDimitry Andric     else
4066122f3e6SDimitry Andric       SplitMakesNewLoopHeader = true;
4076122f3e6SDimitry Andric   }
4086122f3e6SDimitry Andric 
409ff0cc061SDimitry Andric   // Unless we have a loop for OldBB, nothing else to do here.
410ff0cc061SDimitry Andric   if (!L)
411ff0cc061SDimitry Andric     return;
4126122f3e6SDimitry Andric 
4136122f3e6SDimitry Andric   if (IsLoopEntry) {
4146122f3e6SDimitry Andric     // Add the new block to the nearest enclosing loop (and not an adjacent
4156122f3e6SDimitry Andric     // loop). To find this, examine each of the predecessors and determine which
4166122f3e6SDimitry Andric     // loops enclose them, and select the most-nested loop which contains the
4176122f3e6SDimitry Andric     // loop containing the block being split.
41891bc56edSDimitry Andric     Loop *InnermostPredLoop = nullptr;
4193ca95b02SDimitry Andric     for (BasicBlock *Pred : Preds) {
4206122f3e6SDimitry Andric       if (Loop *PredLoop = LI->getLoopFor(Pred)) {
4216122f3e6SDimitry Andric         // Seek a loop which actually contains the block being split (to avoid
4226122f3e6SDimitry Andric         // adjacent loops).
4236122f3e6SDimitry Andric         while (PredLoop && !PredLoop->contains(OldBB))
4246122f3e6SDimitry Andric           PredLoop = PredLoop->getParentLoop();
4256122f3e6SDimitry Andric 
4266122f3e6SDimitry Andric         // Select the most-nested of these loops which contains the block.
4276122f3e6SDimitry Andric         if (PredLoop && PredLoop->contains(OldBB) &&
4286122f3e6SDimitry Andric             (!InnermostPredLoop ||
4296122f3e6SDimitry Andric              InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
4306122f3e6SDimitry Andric           InnermostPredLoop = PredLoop;
4316122f3e6SDimitry Andric       }
4326122f3e6SDimitry Andric     }
4336122f3e6SDimitry Andric 
4346122f3e6SDimitry Andric     if (InnermostPredLoop)
435ff0cc061SDimitry Andric       InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
4366122f3e6SDimitry Andric   } else {
437ff0cc061SDimitry Andric     L->addBasicBlockToLoop(NewBB, *LI);
4386122f3e6SDimitry Andric     if (SplitMakesNewLoopHeader)
4396122f3e6SDimitry Andric       L->moveToHeader(NewBB);
4406122f3e6SDimitry Andric   }
4416122f3e6SDimitry Andric }
4426122f3e6SDimitry Andric 
4433ca95b02SDimitry Andric /// Update the PHI nodes in OrigBB to include the values coming from NewBB.
4443ca95b02SDimitry Andric /// This also updates AliasAnalysis, if available.
UpdatePHINodes(BasicBlock * OrigBB,BasicBlock * NewBB,ArrayRef<BasicBlock * > Preds,BranchInst * BI,bool HasLoopExit)4456122f3e6SDimitry Andric static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
4466122f3e6SDimitry Andric                            ArrayRef<BasicBlock *> Preds, BranchInst *BI,
4477d523365SDimitry Andric                            bool HasLoopExit) {
4486122f3e6SDimitry Andric   // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
44991bc56edSDimitry Andric   SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
4506122f3e6SDimitry Andric   for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
4516122f3e6SDimitry Andric     PHINode *PN = cast<PHINode>(I++);
4526122f3e6SDimitry Andric 
4536122f3e6SDimitry Andric     // Check to see if all of the values coming in are the same.  If so, we
4546122f3e6SDimitry Andric     // don't need to create a new PHI node, unless it's needed for LCSSA.
45591bc56edSDimitry Andric     Value *InVal = nullptr;
4566122f3e6SDimitry Andric     if (!HasLoopExit) {
4576122f3e6SDimitry Andric       InVal = PN->getIncomingValueForBlock(Preds[0]);
45891bc56edSDimitry Andric       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
45991bc56edSDimitry Andric         if (!PredSet.count(PN->getIncomingBlock(i)))
46091bc56edSDimitry Andric           continue;
46191bc56edSDimitry Andric         if (!InVal)
46291bc56edSDimitry Andric           InVal = PN->getIncomingValue(i);
46391bc56edSDimitry Andric         else if (InVal != PN->getIncomingValue(i)) {
46491bc56edSDimitry Andric           InVal = nullptr;
4656122f3e6SDimitry Andric           break;
4666122f3e6SDimitry Andric         }
4676122f3e6SDimitry Andric       }
46891bc56edSDimitry Andric     }
4696122f3e6SDimitry Andric 
4706122f3e6SDimitry Andric     if (InVal) {
4716122f3e6SDimitry Andric       // If all incoming values for the new PHI would be the same, just don't
4726122f3e6SDimitry Andric       // make a new PHI.  Instead, just remove the incoming values from the old
4736122f3e6SDimitry Andric       // PHI.
4746122f3e6SDimitry Andric 
47591bc56edSDimitry Andric       // NOTE! This loop walks backwards for a reason! First off, this minimizes
47691bc56edSDimitry Andric       // the cost of removal if we end up removing a large number of values, and
47791bc56edSDimitry Andric       // second off, this ensures that the indices for the incoming values
47891bc56edSDimitry Andric       // aren't invalidated when we remove one.
47991bc56edSDimitry Andric       for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
48091bc56edSDimitry Andric         if (PredSet.count(PN->getIncomingBlock(i)))
48191bc56edSDimitry Andric           PN->removeIncomingValue(i, false);
4826122f3e6SDimitry Andric 
4836122f3e6SDimitry Andric       // Add an incoming value to the PHI node in the loop for the preheader
4846122f3e6SDimitry Andric       // edge.
4856122f3e6SDimitry Andric       PN->addIncoming(InVal, NewBB);
48691bc56edSDimitry Andric       continue;
48791bc56edSDimitry Andric     }
48891bc56edSDimitry Andric 
48991bc56edSDimitry Andric     // If the values coming into the block are not the same, we need a new
49091bc56edSDimitry Andric     // PHI.
49191bc56edSDimitry Andric     // Create the new PHI node, insert it into NewBB at the end of the block
49291bc56edSDimitry Andric     PHINode *NewPHI =
49391bc56edSDimitry Andric         PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
49491bc56edSDimitry Andric 
49591bc56edSDimitry Andric     // NOTE! This loop walks backwards for a reason! First off, this minimizes
49691bc56edSDimitry Andric     // the cost of removal if we end up removing a large number of values, and
49791bc56edSDimitry Andric     // second off, this ensures that the indices for the incoming values aren't
49891bc56edSDimitry Andric     // invalidated when we remove one.
49991bc56edSDimitry Andric     for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
50091bc56edSDimitry Andric       BasicBlock *IncomingBB = PN->getIncomingBlock(i);
50191bc56edSDimitry Andric       if (PredSet.count(IncomingBB)) {
50291bc56edSDimitry Andric         Value *V = PN->removeIncomingValue(i, false);
50391bc56edSDimitry Andric         NewPHI->addIncoming(V, IncomingBB);
50491bc56edSDimitry Andric       }
50591bc56edSDimitry Andric     }
50691bc56edSDimitry Andric 
50791bc56edSDimitry Andric     PN->addIncoming(NewPHI, NewBB);
5086122f3e6SDimitry Andric   }
5096122f3e6SDimitry Andric }
510f22ef01cSRoman Divacky 
SplitBlockPredecessors(BasicBlock * BB,ArrayRef<BasicBlock * > Preds,const char * Suffix,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)511f22ef01cSRoman Divacky BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
512dff0c46cSDimitry Andric                                          ArrayRef<BasicBlock *> Preds,
5137d523365SDimitry Andric                                          const char *Suffix, DominatorTree *DT,
514*b5893f02SDimitry Andric                                          LoopInfo *LI, MemorySSAUpdater *MSSAU,
515*b5893f02SDimitry Andric                                          bool PreserveLCSSA) {
5167d523365SDimitry Andric   // Do not attempt to split that which cannot be split.
5177d523365SDimitry Andric   if (!BB->canSplitPredecessors())
5187d523365SDimitry Andric     return nullptr;
5197d523365SDimitry Andric 
520ff0cc061SDimitry Andric   // For the landingpads we need to act a bit differently.
521ff0cc061SDimitry Andric   // Delegate this work to the SplitLandingPadPredecessors.
522ff0cc061SDimitry Andric   if (BB->isLandingPad()) {
523ff0cc061SDimitry Andric     SmallVector<BasicBlock*, 2> NewBBs;
524ff0cc061SDimitry Andric     std::string NewName = std::string(Suffix) + ".split-lp";
525ff0cc061SDimitry Andric 
5267d523365SDimitry Andric     SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs, DT,
527*b5893f02SDimitry Andric                                 LI, MSSAU, PreserveLCSSA);
528ff0cc061SDimitry Andric     return NewBBs[0];
529ff0cc061SDimitry Andric   }
530ff0cc061SDimitry Andric 
531f22ef01cSRoman Divacky   // Create new basic block, insert right before the original block.
5328f0fd8f6SDimitry Andric   BasicBlock *NewBB = BasicBlock::Create(
5338f0fd8f6SDimitry Andric       BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
534f22ef01cSRoman Divacky 
535f22ef01cSRoman Divacky   // The new block unconditionally branches to the old block.
536f22ef01cSRoman Divacky   BranchInst *BI = BranchInst::Create(BB, NewBB);
5377a7e6055SDimitry Andric   BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
538f22ef01cSRoman Divacky 
539f22ef01cSRoman Divacky   // Move the edges from Preds to point to NewBB instead of BB.
540dff0c46cSDimitry Andric   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
541f22ef01cSRoman Divacky     // This is slightly more strict than necessary; the minimum requirement
542f22ef01cSRoman Divacky     // is that there be no more than one indirectbr branching to BB. And
543f22ef01cSRoman Divacky     // all BlockAddress uses would need to be updated.
544f22ef01cSRoman Divacky     assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
545f22ef01cSRoman Divacky            "Cannot split an edge from an IndirectBrInst");
546f22ef01cSRoman Divacky     Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
547f22ef01cSRoman Divacky   }
548f22ef01cSRoman Divacky 
549f22ef01cSRoman Divacky   // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
550f22ef01cSRoman Divacky   // node becomes an incoming value for BB's phi node.  However, if the Preds
551f22ef01cSRoman Divacky   // list is empty, we need to insert dummy entries into the PHI nodes in BB to
552f22ef01cSRoman Divacky   // account for the newly created predecessor.
5532cab237bSDimitry Andric   if (Preds.empty()) {
554f22ef01cSRoman Divacky     // Insert dummy values as the incoming value.
555f22ef01cSRoman Divacky     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
556f22ef01cSRoman Divacky       cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
557f22ef01cSRoman Divacky   }
558f22ef01cSRoman Divacky 
5596122f3e6SDimitry Andric   // Update DominatorTree, LoopInfo, and LCCSA analysis information.
5606122f3e6SDimitry Andric   bool HasLoopExit = false;
561*b5893f02SDimitry Andric   UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, MSSAU, PreserveLCSSA,
562ff0cc061SDimitry Andric                             HasLoopExit);
563f22ef01cSRoman Divacky 
5644ba319b5SDimitry Andric   if (!Preds.empty()) {
5656122f3e6SDimitry Andric     // Update the PHI nodes in BB with the values coming from NewBB.
5667d523365SDimitry Andric     UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
5674ba319b5SDimitry Andric   }
5684ba319b5SDimitry Andric 
569f22ef01cSRoman Divacky   return NewBB;
570f22ef01cSRoman Divacky }
571f22ef01cSRoman Divacky 
SplitLandingPadPredecessors(BasicBlock * OrigBB,ArrayRef<BasicBlock * > Preds,const char * Suffix1,const char * Suffix2,SmallVectorImpl<BasicBlock * > & NewBBs,DominatorTree * DT,LoopInfo * LI,MemorySSAUpdater * MSSAU,bool PreserveLCSSA)5726122f3e6SDimitry Andric void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
5736122f3e6SDimitry Andric                                        ArrayRef<BasicBlock *> Preds,
5746122f3e6SDimitry Andric                                        const char *Suffix1, const char *Suffix2,
575ff0cc061SDimitry Andric                                        SmallVectorImpl<BasicBlock *> &NewBBs,
5767d523365SDimitry Andric                                        DominatorTree *DT, LoopInfo *LI,
577*b5893f02SDimitry Andric                                        MemorySSAUpdater *MSSAU,
5787d523365SDimitry Andric                                        bool PreserveLCSSA) {
5796122f3e6SDimitry Andric   assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
5806122f3e6SDimitry Andric 
5816122f3e6SDimitry Andric   // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
5826122f3e6SDimitry Andric   // it right before the original block.
5836122f3e6SDimitry Andric   BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
5846122f3e6SDimitry Andric                                           OrigBB->getName() + Suffix1,
5856122f3e6SDimitry Andric                                           OrigBB->getParent(), OrigBB);
5866122f3e6SDimitry Andric   NewBBs.push_back(NewBB1);
5876122f3e6SDimitry Andric 
5886122f3e6SDimitry Andric   // The new block unconditionally branches to the old block.
5896122f3e6SDimitry Andric   BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
5908f0fd8f6SDimitry Andric   BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
5916122f3e6SDimitry Andric 
5926122f3e6SDimitry Andric   // Move the edges from Preds to point to NewBB1 instead of OrigBB.
5936122f3e6SDimitry Andric   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
5946122f3e6SDimitry Andric     // This is slightly more strict than necessary; the minimum requirement
5956122f3e6SDimitry Andric     // is that there be no more than one indirectbr branching to BB. And
5966122f3e6SDimitry Andric     // all BlockAddress uses would need to be updated.
5976122f3e6SDimitry Andric     assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
5986122f3e6SDimitry Andric            "Cannot split an edge from an IndirectBrInst");
5996122f3e6SDimitry Andric     Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
6006122f3e6SDimitry Andric   }
6016122f3e6SDimitry Andric 
6026122f3e6SDimitry Andric   bool HasLoopExit = false;
603*b5893f02SDimitry Andric   UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, MSSAU, PreserveLCSSA,
604ff0cc061SDimitry Andric                             HasLoopExit);
6056122f3e6SDimitry Andric 
6066122f3e6SDimitry Andric   // Update the PHI nodes in OrigBB with the values coming from NewBB1.
6077d523365SDimitry Andric   UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
6086122f3e6SDimitry Andric 
6096122f3e6SDimitry Andric   // Move the remaining edges from OrigBB to point to NewBB2.
6106122f3e6SDimitry Andric   SmallVector<BasicBlock*, 8> NewBB2Preds;
6116122f3e6SDimitry Andric   for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
6126122f3e6SDimitry Andric        i != e; ) {
6136122f3e6SDimitry Andric     BasicBlock *Pred = *i++;
6146122f3e6SDimitry Andric     if (Pred == NewBB1) continue;
6156122f3e6SDimitry Andric     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
6166122f3e6SDimitry Andric            "Cannot split an edge from an IndirectBrInst");
6176122f3e6SDimitry Andric     NewBB2Preds.push_back(Pred);
6186122f3e6SDimitry Andric     e = pred_end(OrigBB);
6196122f3e6SDimitry Andric   }
6206122f3e6SDimitry Andric 
62191bc56edSDimitry Andric   BasicBlock *NewBB2 = nullptr;
6226122f3e6SDimitry Andric   if (!NewBB2Preds.empty()) {
6236122f3e6SDimitry Andric     // Create another basic block for the rest of OrigBB's predecessors.
6246122f3e6SDimitry Andric     NewBB2 = BasicBlock::Create(OrigBB->getContext(),
6256122f3e6SDimitry Andric                                 OrigBB->getName() + Suffix2,
6266122f3e6SDimitry Andric                                 OrigBB->getParent(), OrigBB);
6276122f3e6SDimitry Andric     NewBBs.push_back(NewBB2);
6286122f3e6SDimitry Andric 
6296122f3e6SDimitry Andric     // The new block unconditionally branches to the old block.
6306122f3e6SDimitry Andric     BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
6318f0fd8f6SDimitry Andric     BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
6326122f3e6SDimitry Andric 
6336122f3e6SDimitry Andric     // Move the remaining edges from OrigBB to point to NewBB2.
6343ca95b02SDimitry Andric     for (BasicBlock *NewBB2Pred : NewBB2Preds)
6353ca95b02SDimitry Andric       NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
6366122f3e6SDimitry Andric 
6376122f3e6SDimitry Andric     // Update DominatorTree, LoopInfo, and LCCSA analysis information.
6386122f3e6SDimitry Andric     HasLoopExit = false;
639*b5893f02SDimitry Andric     UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI, MSSAU,
640ff0cc061SDimitry Andric                               PreserveLCSSA, HasLoopExit);
6416122f3e6SDimitry Andric 
6426122f3e6SDimitry Andric     // Update the PHI nodes in OrigBB with the values coming from NewBB2.
6437d523365SDimitry Andric     UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
6446122f3e6SDimitry Andric   }
6456122f3e6SDimitry Andric 
6466122f3e6SDimitry Andric   LandingPadInst *LPad = OrigBB->getLandingPadInst();
6476122f3e6SDimitry Andric   Instruction *Clone1 = LPad->clone();
6486122f3e6SDimitry Andric   Clone1->setName(Twine("lpad") + Suffix1);
6496122f3e6SDimitry Andric   NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
6506122f3e6SDimitry Andric 
6516122f3e6SDimitry Andric   if (NewBB2) {
6526122f3e6SDimitry Andric     Instruction *Clone2 = LPad->clone();
6536122f3e6SDimitry Andric     Clone2->setName(Twine("lpad") + Suffix2);
6546122f3e6SDimitry Andric     NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
6556122f3e6SDimitry Andric 
656444ed5c5SDimitry Andric     // Create a PHI node for the two cloned landingpad instructions only
657444ed5c5SDimitry Andric     // if the original landingpad instruction has some uses.
658444ed5c5SDimitry Andric     if (!LPad->use_empty()) {
659444ed5c5SDimitry Andric       assert(!LPad->getType()->isTokenTy() &&
660444ed5c5SDimitry Andric              "Split cannot be applied if LPad is token type. Otherwise an "
661444ed5c5SDimitry Andric              "invalid PHINode of token type would be created.");
6626122f3e6SDimitry Andric       PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
6636122f3e6SDimitry Andric       PN->addIncoming(Clone1, NewBB1);
6646122f3e6SDimitry Andric       PN->addIncoming(Clone2, NewBB2);
6656122f3e6SDimitry Andric       LPad->replaceAllUsesWith(PN);
666444ed5c5SDimitry Andric     }
6676122f3e6SDimitry Andric     LPad->eraseFromParent();
6686122f3e6SDimitry Andric   } else {
6696122f3e6SDimitry Andric     // There is no second clone. Just replace the landing pad with the first
6706122f3e6SDimitry Andric     // clone.
6716122f3e6SDimitry Andric     LPad->replaceAllUsesWith(Clone1);
6726122f3e6SDimitry Andric     LPad->eraseFromParent();
6736122f3e6SDimitry Andric   }
6746122f3e6SDimitry Andric }
6756122f3e6SDimitry Andric 
FoldReturnIntoUncondBranch(ReturnInst * RI,BasicBlock * BB,BasicBlock * Pred,DomTreeUpdater * DTU)6762754fe60SDimitry Andric ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
677*b5893f02SDimitry Andric                                              BasicBlock *Pred,
678*b5893f02SDimitry Andric                                              DomTreeUpdater *DTU) {
6792754fe60SDimitry Andric   Instruction *UncondBranch = Pred->getTerminator();
6802754fe60SDimitry Andric   // Clone the return and add it to the end of the predecessor.
6812754fe60SDimitry Andric   Instruction *NewRet = RI->clone();
6822754fe60SDimitry Andric   Pred->getInstList().push_back(NewRet);
683f22ef01cSRoman Divacky 
6842754fe60SDimitry Andric   // If the return instruction returns a value, and if the value was a
6852754fe60SDimitry Andric   // PHI node in "BB", propagate the right value into the return.
6862754fe60SDimitry Andric   for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
6877ae0e2c9SDimitry Andric        i != e; ++i) {
6887ae0e2c9SDimitry Andric     Value *V = *i;
68991bc56edSDimitry Andric     Instruction *NewBC = nullptr;
6907ae0e2c9SDimitry Andric     if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
6917ae0e2c9SDimitry Andric       // Return value might be bitcasted. Clone and insert it before the
6927ae0e2c9SDimitry Andric       // return instruction.
6937ae0e2c9SDimitry Andric       V = BCI->getOperand(0);
6947ae0e2c9SDimitry Andric       NewBC = BCI->clone();
6957d523365SDimitry Andric       Pred->getInstList().insert(NewRet->getIterator(), NewBC);
6967ae0e2c9SDimitry Andric       *i = NewBC;
6977ae0e2c9SDimitry Andric     }
6987ae0e2c9SDimitry Andric     if (PHINode *PN = dyn_cast<PHINode>(V)) {
6997ae0e2c9SDimitry Andric       if (PN->getParent() == BB) {
7007ae0e2c9SDimitry Andric         if (NewBC)
7017ae0e2c9SDimitry Andric           NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
7027ae0e2c9SDimitry Andric         else
7032754fe60SDimitry Andric           *i = PN->getIncomingValueForBlock(Pred);
7047ae0e2c9SDimitry Andric       }
7057ae0e2c9SDimitry Andric     }
7067ae0e2c9SDimitry Andric   }
7072754fe60SDimitry Andric 
7082754fe60SDimitry Andric   // Update any PHI nodes in the returning block to realize that we no
7092754fe60SDimitry Andric   // longer branch to them.
7102754fe60SDimitry Andric   BB->removePredecessor(Pred);
7112754fe60SDimitry Andric   UncondBranch->eraseFromParent();
712*b5893f02SDimitry Andric 
713*b5893f02SDimitry Andric   if (DTU)
714*b5893f02SDimitry Andric     DTU->deleteEdge(Pred, BB);
715*b5893f02SDimitry Andric 
7162754fe60SDimitry Andric   return cast<ReturnInst>(NewRet);
717f22ef01cSRoman Divacky }
7183b0f4066SDimitry Andric 
SplitBlockAndInsertIfThen(Value * Cond,Instruction * SplitBefore,bool Unreachable,MDNode * BranchWeights,DominatorTree * DT,LoopInfo * LI)719*b5893f02SDimitry Andric Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond,
720*b5893f02SDimitry Andric                                              Instruction *SplitBefore,
721*b5893f02SDimitry Andric                                              bool Unreachable,
722*b5893f02SDimitry Andric                                              MDNode *BranchWeights,
7233ca95b02SDimitry Andric                                              DominatorTree *DT, LoopInfo *LI) {
7243861d79fSDimitry Andric   BasicBlock *Head = SplitBefore->getParent();
7257d523365SDimitry Andric   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
726*b5893f02SDimitry Andric   Instruction *HeadOldTerm = Head->getTerminator();
7273861d79fSDimitry Andric   LLVMContext &C = Head->getContext();
7283861d79fSDimitry Andric   BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
729*b5893f02SDimitry Andric   Instruction *CheckTerm;
7303861d79fSDimitry Andric   if (Unreachable)
7313861d79fSDimitry Andric     CheckTerm = new UnreachableInst(C, ThenBlock);
7323861d79fSDimitry Andric   else
7333861d79fSDimitry Andric     CheckTerm = BranchInst::Create(Tail, ThenBlock);
73491bc56edSDimitry Andric   CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
7353861d79fSDimitry Andric   BranchInst *HeadNewTerm =
73691bc56edSDimitry Andric     BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
7373861d79fSDimitry Andric   HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
7383861d79fSDimitry Andric   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
73991bc56edSDimitry Andric 
74091bc56edSDimitry Andric   if (DT) {
74191bc56edSDimitry Andric     if (DomTreeNode *OldNode = DT->getNode(Head)) {
74291bc56edSDimitry Andric       std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
74391bc56edSDimitry Andric 
74491bc56edSDimitry Andric       DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
7453ca95b02SDimitry Andric       for (DomTreeNode *Child : Children)
74691bc56edSDimitry Andric         DT->changeImmediateDominator(Child, NewNode);
74791bc56edSDimitry Andric 
74891bc56edSDimitry Andric       // Head dominates ThenBlock.
74991bc56edSDimitry Andric       DT->addNewBlock(ThenBlock, Head);
75091bc56edSDimitry Andric     }
75191bc56edSDimitry Andric   }
75291bc56edSDimitry Andric 
7533ca95b02SDimitry Andric   if (LI) {
7547a7e6055SDimitry Andric     if (Loop *L = LI->getLoopFor(Head)) {
7553ca95b02SDimitry Andric       L->addBasicBlockToLoop(ThenBlock, *LI);
7563ca95b02SDimitry Andric       L->addBasicBlockToLoop(Tail, *LI);
7573ca95b02SDimitry Andric     }
7587a7e6055SDimitry Andric   }
7593ca95b02SDimitry Andric 
7603861d79fSDimitry Andric   return CheckTerm;
7613861d79fSDimitry Andric }
762f785676fSDimitry Andric 
SplitBlockAndInsertIfThenElse(Value * Cond,Instruction * SplitBefore,Instruction ** ThenTerm,Instruction ** ElseTerm,MDNode * BranchWeights)76391bc56edSDimitry Andric void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
764*b5893f02SDimitry Andric                                          Instruction **ThenTerm,
765*b5893f02SDimitry Andric                                          Instruction **ElseTerm,
76691bc56edSDimitry Andric                                          MDNode *BranchWeights) {
76791bc56edSDimitry Andric   BasicBlock *Head = SplitBefore->getParent();
7687d523365SDimitry Andric   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
769*b5893f02SDimitry Andric   Instruction *HeadOldTerm = Head->getTerminator();
77091bc56edSDimitry Andric   LLVMContext &C = Head->getContext();
77191bc56edSDimitry Andric   BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
77291bc56edSDimitry Andric   BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
77391bc56edSDimitry Andric   *ThenTerm = BranchInst::Create(Tail, ThenBlock);
77491bc56edSDimitry Andric   (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
77591bc56edSDimitry Andric   *ElseTerm = BranchInst::Create(Tail, ElseBlock);
77691bc56edSDimitry Andric   (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
77791bc56edSDimitry Andric   BranchInst *HeadNewTerm =
77891bc56edSDimitry Andric     BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
77991bc56edSDimitry Andric   HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
78091bc56edSDimitry Andric   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
78191bc56edSDimitry Andric }
78291bc56edSDimitry Andric 
GetIfCondition(BasicBlock * BB,BasicBlock * & IfTrue,BasicBlock * & IfFalse)783f785676fSDimitry Andric Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
784f785676fSDimitry Andric                              BasicBlock *&IfFalse) {
785f785676fSDimitry Andric   PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
78691bc56edSDimitry Andric   BasicBlock *Pred1 = nullptr;
78791bc56edSDimitry Andric   BasicBlock *Pred2 = nullptr;
788f785676fSDimitry Andric 
789f785676fSDimitry Andric   if (SomePHI) {
790f785676fSDimitry Andric     if (SomePHI->getNumIncomingValues() != 2)
79191bc56edSDimitry Andric       return nullptr;
792f785676fSDimitry Andric     Pred1 = SomePHI->getIncomingBlock(0);
793f785676fSDimitry Andric     Pred2 = SomePHI->getIncomingBlock(1);
794f785676fSDimitry Andric   } else {
795f785676fSDimitry Andric     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
796f785676fSDimitry Andric     if (PI == PE) // No predecessor
79791bc56edSDimitry Andric       return nullptr;
798f785676fSDimitry Andric     Pred1 = *PI++;
799f785676fSDimitry Andric     if (PI == PE) // Only one predecessor
80091bc56edSDimitry Andric       return nullptr;
801f785676fSDimitry Andric     Pred2 = *PI++;
802f785676fSDimitry Andric     if (PI != PE) // More than two predecessors
80391bc56edSDimitry Andric       return nullptr;
804f785676fSDimitry Andric   }
805f785676fSDimitry Andric 
806f785676fSDimitry Andric   // We can only handle branches.  Other control flow will be lowered to
807f785676fSDimitry Andric   // branches if possible anyway.
808f785676fSDimitry Andric   BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
809f785676fSDimitry Andric   BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
81091bc56edSDimitry Andric   if (!Pred1Br || !Pred2Br)
81191bc56edSDimitry Andric     return nullptr;
812f785676fSDimitry Andric 
813f785676fSDimitry Andric   // Eliminate code duplication by ensuring that Pred1Br is conditional if
814f785676fSDimitry Andric   // either are.
815f785676fSDimitry Andric   if (Pred2Br->isConditional()) {
816f785676fSDimitry Andric     // If both branches are conditional, we don't have an "if statement".  In
817f785676fSDimitry Andric     // reality, we could transform this case, but since the condition will be
818f785676fSDimitry Andric     // required anyway, we stand no chance of eliminating it, so the xform is
819f785676fSDimitry Andric     // probably not profitable.
820f785676fSDimitry Andric     if (Pred1Br->isConditional())
82191bc56edSDimitry Andric       return nullptr;
822f785676fSDimitry Andric 
823f785676fSDimitry Andric     std::swap(Pred1, Pred2);
824f785676fSDimitry Andric     std::swap(Pred1Br, Pred2Br);
825f785676fSDimitry Andric   }
826f785676fSDimitry Andric 
827f785676fSDimitry Andric   if (Pred1Br->isConditional()) {
828f785676fSDimitry Andric     // The only thing we have to watch out for here is to make sure that Pred2
829f785676fSDimitry Andric     // doesn't have incoming edges from other blocks.  If it does, the condition
830f785676fSDimitry Andric     // doesn't dominate BB.
83191bc56edSDimitry Andric     if (!Pred2->getSinglePredecessor())
83291bc56edSDimitry Andric       return nullptr;
833f785676fSDimitry Andric 
834f785676fSDimitry Andric     // If we found a conditional branch predecessor, make sure that it branches
835f785676fSDimitry Andric     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
836f785676fSDimitry Andric     if (Pred1Br->getSuccessor(0) == BB &&
837f785676fSDimitry Andric         Pred1Br->getSuccessor(1) == Pred2) {
838f785676fSDimitry Andric       IfTrue = Pred1;
839f785676fSDimitry Andric       IfFalse = Pred2;
840f785676fSDimitry Andric     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
841f785676fSDimitry Andric                Pred1Br->getSuccessor(1) == BB) {
842f785676fSDimitry Andric       IfTrue = Pred2;
843f785676fSDimitry Andric       IfFalse = Pred1;
844f785676fSDimitry Andric     } else {
845f785676fSDimitry Andric       // We know that one arm of the conditional goes to BB, so the other must
846f785676fSDimitry Andric       // go somewhere unrelated, and this must not be an "if statement".
84791bc56edSDimitry Andric       return nullptr;
848f785676fSDimitry Andric     }
849f785676fSDimitry Andric 
850f785676fSDimitry Andric     return Pred1Br->getCondition();
851f785676fSDimitry Andric   }
852f785676fSDimitry Andric 
853f785676fSDimitry Andric   // Ok, if we got here, both predecessors end with an unconditional branch to
854f785676fSDimitry Andric   // BB.  Don't panic!  If both blocks only have a single (identical)
855f785676fSDimitry Andric   // predecessor, and THAT is a conditional branch, then we're all ok!
856f785676fSDimitry Andric   BasicBlock *CommonPred = Pred1->getSinglePredecessor();
85791bc56edSDimitry Andric   if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
85891bc56edSDimitry Andric     return nullptr;
859f785676fSDimitry Andric 
860f785676fSDimitry Andric   // Otherwise, if this is a conditional branch, then we can use it!
861f785676fSDimitry Andric   BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
86291bc56edSDimitry Andric   if (!BI) return nullptr;
863f785676fSDimitry Andric 
864f785676fSDimitry Andric   assert(BI->isConditional() && "Two successors but not conditional?");
865f785676fSDimitry Andric   if (BI->getSuccessor(0) == Pred1) {
866f785676fSDimitry Andric     IfTrue = Pred1;
867f785676fSDimitry Andric     IfFalse = Pred2;
868f785676fSDimitry Andric   } else {
869f785676fSDimitry Andric     IfTrue = Pred2;
870f785676fSDimitry Andric     IfFalse = Pred1;
871f785676fSDimitry Andric   }
872f785676fSDimitry Andric   return BI->getCondition();
873f785676fSDimitry Andric }
874