xref: /aosp_15_r20/external/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This family of functions perform manipulations on basic blocks, and
11*9880d681SAndroid Build Coastguard Worker // instructions contained within basic blocks.
12*9880d681SAndroid Build Coastguard Worker //
13*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
14*9880d681SAndroid Build Coastguard Worker 
15*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/BasicBlockUtils.h"
16*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AliasAnalysis.h"
17*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/CFG.h"
18*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopInfo.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/MemoryDependenceAnalysis.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Constant.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Function.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Instructions.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Type.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/ValueHandle.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/ErrorHandling.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Local.h"
31*9880d681SAndroid Build Coastguard Worker #include <algorithm>
32*9880d681SAndroid Build Coastguard Worker using namespace llvm;
33*9880d681SAndroid Build Coastguard Worker 
DeleteDeadBlock(BasicBlock * BB)34*9880d681SAndroid Build Coastguard Worker void llvm::DeleteDeadBlock(BasicBlock *BB) {
35*9880d681SAndroid Build Coastguard Worker   assert((pred_begin(BB) == pred_end(BB) ||
36*9880d681SAndroid Build Coastguard Worker          // Can delete self loop.
37*9880d681SAndroid Build Coastguard Worker          BB->getSinglePredecessor() == BB) && "Block is not dead!");
38*9880d681SAndroid Build Coastguard Worker   TerminatorInst *BBTerm = BB->getTerminator();
39*9880d681SAndroid Build Coastguard Worker 
40*9880d681SAndroid Build Coastguard Worker   // Loop through all of our successors and make sure they know that one
41*9880d681SAndroid Build Coastguard Worker   // of their predecessors is going away.
42*9880d681SAndroid Build Coastguard Worker   for (BasicBlock *Succ : BBTerm->successors())
43*9880d681SAndroid Build Coastguard Worker     Succ->removePredecessor(BB);
44*9880d681SAndroid Build Coastguard Worker 
45*9880d681SAndroid Build Coastguard Worker   // Zap all the instructions in the block.
46*9880d681SAndroid Build Coastguard Worker   while (!BB->empty()) {
47*9880d681SAndroid Build Coastguard Worker     Instruction &I = BB->back();
48*9880d681SAndroid Build Coastguard Worker     // If this instruction is used, replace uses with an arbitrary value.
49*9880d681SAndroid Build Coastguard Worker     // Because control flow can't get here, we don't care what we replace the
50*9880d681SAndroid Build Coastguard Worker     // value with.  Note that since this block is unreachable, and all values
51*9880d681SAndroid Build Coastguard Worker     // contained within it must dominate their uses, that all uses will
52*9880d681SAndroid Build Coastguard Worker     // eventually be removed (they are themselves dead).
53*9880d681SAndroid Build Coastguard Worker     if (!I.use_empty())
54*9880d681SAndroid Build Coastguard Worker       I.replaceAllUsesWith(UndefValue::get(I.getType()));
55*9880d681SAndroid Build Coastguard Worker     BB->getInstList().pop_back();
56*9880d681SAndroid Build Coastguard Worker   }
57*9880d681SAndroid Build Coastguard Worker 
58*9880d681SAndroid Build Coastguard Worker   // Zap the block!
59*9880d681SAndroid Build Coastguard Worker   BB->eraseFromParent();
60*9880d681SAndroid Build Coastguard Worker }
61*9880d681SAndroid Build Coastguard Worker 
FoldSingleEntryPHINodes(BasicBlock * BB,MemoryDependenceResults * MemDep)62*9880d681SAndroid Build Coastguard Worker void llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
63*9880d681SAndroid Build Coastguard Worker                                    MemoryDependenceResults *MemDep) {
64*9880d681SAndroid Build Coastguard Worker   if (!isa<PHINode>(BB->begin())) return;
65*9880d681SAndroid Build Coastguard Worker 
66*9880d681SAndroid Build Coastguard Worker   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
67*9880d681SAndroid Build Coastguard Worker     if (PN->getIncomingValue(0) != PN)
68*9880d681SAndroid Build Coastguard Worker       PN->replaceAllUsesWith(PN->getIncomingValue(0));
69*9880d681SAndroid Build Coastguard Worker     else
70*9880d681SAndroid Build Coastguard Worker       PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
71*9880d681SAndroid Build Coastguard Worker 
72*9880d681SAndroid Build Coastguard Worker     if (MemDep)
73*9880d681SAndroid Build Coastguard Worker       MemDep->removeInstruction(PN);  // Memdep updates AA itself.
74*9880d681SAndroid Build Coastguard Worker 
75*9880d681SAndroid Build Coastguard Worker     PN->eraseFromParent();
76*9880d681SAndroid Build Coastguard Worker   }
77*9880d681SAndroid Build Coastguard Worker }
78*9880d681SAndroid Build Coastguard Worker 
DeleteDeadPHIs(BasicBlock * BB,const TargetLibraryInfo * TLI)79*9880d681SAndroid Build Coastguard Worker bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
80*9880d681SAndroid Build Coastguard Worker   // Recursively deleting a PHI may cause multiple PHIs to be deleted
81*9880d681SAndroid Build Coastguard Worker   // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
82*9880d681SAndroid Build Coastguard Worker   SmallVector<WeakVH, 8> PHIs;
83*9880d681SAndroid Build Coastguard Worker   for (BasicBlock::iterator I = BB->begin();
84*9880d681SAndroid Build Coastguard Worker        PHINode *PN = dyn_cast<PHINode>(I); ++I)
85*9880d681SAndroid Build Coastguard Worker     PHIs.push_back(PN);
86*9880d681SAndroid Build Coastguard Worker 
87*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
88*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
89*9880d681SAndroid Build Coastguard Worker     if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
90*9880d681SAndroid Build Coastguard Worker       Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
91*9880d681SAndroid Build Coastguard Worker 
92*9880d681SAndroid Build Coastguard Worker   return Changed;
93*9880d681SAndroid Build Coastguard Worker }
94*9880d681SAndroid Build Coastguard Worker 
MergeBlockIntoPredecessor(BasicBlock * BB,DominatorTree * DT,LoopInfo * LI,MemoryDependenceResults * MemDep)95*9880d681SAndroid Build Coastguard Worker bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT,
96*9880d681SAndroid Build Coastguard Worker                                      LoopInfo *LI,
97*9880d681SAndroid Build Coastguard Worker                                      MemoryDependenceResults *MemDep) {
98*9880d681SAndroid Build Coastguard Worker   // Don't merge away blocks who have their address taken.
99*9880d681SAndroid Build Coastguard Worker   if (BB->hasAddressTaken()) return false;
100*9880d681SAndroid Build Coastguard Worker 
101*9880d681SAndroid Build Coastguard Worker   // Can't merge if there are multiple predecessors, or no predecessors.
102*9880d681SAndroid Build Coastguard Worker   BasicBlock *PredBB = BB->getUniquePredecessor();
103*9880d681SAndroid Build Coastguard Worker   if (!PredBB) return false;
104*9880d681SAndroid Build Coastguard Worker 
105*9880d681SAndroid Build Coastguard Worker   // Don't break self-loops.
106*9880d681SAndroid Build Coastguard Worker   if (PredBB == BB) return false;
107*9880d681SAndroid Build Coastguard Worker   // Don't break unwinding instructions.
108*9880d681SAndroid Build Coastguard Worker   if (PredBB->getTerminator()->isExceptional())
109*9880d681SAndroid Build Coastguard Worker     return false;
110*9880d681SAndroid Build Coastguard Worker 
111*9880d681SAndroid Build Coastguard Worker   succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
112*9880d681SAndroid Build Coastguard Worker   BasicBlock *OnlySucc = BB;
113*9880d681SAndroid Build Coastguard Worker   for (; SI != SE; ++SI)
114*9880d681SAndroid Build Coastguard Worker     if (*SI != OnlySucc) {
115*9880d681SAndroid Build Coastguard Worker       OnlySucc = nullptr;     // There are multiple distinct successors!
116*9880d681SAndroid Build Coastguard Worker       break;
117*9880d681SAndroid Build Coastguard Worker     }
118*9880d681SAndroid Build Coastguard Worker 
119*9880d681SAndroid Build Coastguard Worker   // Can't merge if there are multiple successors.
120*9880d681SAndroid Build Coastguard Worker   if (!OnlySucc) return false;
121*9880d681SAndroid Build Coastguard Worker 
122*9880d681SAndroid Build Coastguard Worker   // Can't merge if there is PHI loop.
123*9880d681SAndroid Build Coastguard Worker   for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
124*9880d681SAndroid Build Coastguard Worker     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
125*9880d681SAndroid Build Coastguard Worker       for (Value *IncValue : PN->incoming_values())
126*9880d681SAndroid Build Coastguard Worker         if (IncValue == PN)
127*9880d681SAndroid Build Coastguard Worker           return false;
128*9880d681SAndroid Build Coastguard Worker     } else
129*9880d681SAndroid Build Coastguard Worker       break;
130*9880d681SAndroid Build Coastguard Worker   }
131*9880d681SAndroid Build Coastguard Worker 
132*9880d681SAndroid Build Coastguard Worker   // Begin by getting rid of unneeded PHIs.
133*9880d681SAndroid Build Coastguard Worker   if (isa<PHINode>(BB->front()))
134*9880d681SAndroid Build Coastguard Worker     FoldSingleEntryPHINodes(BB, MemDep);
135*9880d681SAndroid Build Coastguard Worker 
136*9880d681SAndroid Build Coastguard Worker   // Delete the unconditional branch from the predecessor...
137*9880d681SAndroid Build Coastguard Worker   PredBB->getInstList().pop_back();
138*9880d681SAndroid Build Coastguard Worker 
139*9880d681SAndroid Build Coastguard Worker   // Make all PHI nodes that referred to BB now refer to Pred as their
140*9880d681SAndroid Build Coastguard Worker   // source...
141*9880d681SAndroid Build Coastguard Worker   BB->replaceAllUsesWith(PredBB);
142*9880d681SAndroid Build Coastguard Worker 
143*9880d681SAndroid Build Coastguard Worker   // Move all definitions in the successor to the predecessor...
144*9880d681SAndroid Build Coastguard Worker   PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
145*9880d681SAndroid Build Coastguard Worker 
146*9880d681SAndroid Build Coastguard Worker   // Inherit predecessors name if it exists.
147*9880d681SAndroid Build Coastguard Worker   if (!PredBB->hasName())
148*9880d681SAndroid Build Coastguard Worker     PredBB->takeName(BB);
149*9880d681SAndroid Build Coastguard Worker 
150*9880d681SAndroid Build Coastguard Worker   // Finally, erase the old block and update dominator info.
151*9880d681SAndroid Build Coastguard Worker   if (DT)
152*9880d681SAndroid Build Coastguard Worker     if (DomTreeNode *DTN = DT->getNode(BB)) {
153*9880d681SAndroid Build Coastguard Worker       DomTreeNode *PredDTN = DT->getNode(PredBB);
154*9880d681SAndroid Build Coastguard Worker       SmallVector<DomTreeNode *, 8> Children(DTN->begin(), DTN->end());
155*9880d681SAndroid Build Coastguard Worker       for (DomTreeNode *DI : Children)
156*9880d681SAndroid Build Coastguard Worker         DT->changeImmediateDominator(DI, PredDTN);
157*9880d681SAndroid Build Coastguard Worker 
158*9880d681SAndroid Build Coastguard Worker       DT->eraseNode(BB);
159*9880d681SAndroid Build Coastguard Worker     }
160*9880d681SAndroid Build Coastguard Worker 
161*9880d681SAndroid Build Coastguard Worker   if (LI)
162*9880d681SAndroid Build Coastguard Worker     LI->removeBlock(BB);
163*9880d681SAndroid Build Coastguard Worker 
164*9880d681SAndroid Build Coastguard Worker   if (MemDep)
165*9880d681SAndroid Build Coastguard Worker     MemDep->invalidateCachedPredecessors();
166*9880d681SAndroid Build Coastguard Worker 
167*9880d681SAndroid Build Coastguard Worker   BB->eraseFromParent();
168*9880d681SAndroid Build Coastguard Worker   return true;
169*9880d681SAndroid Build Coastguard Worker }
170*9880d681SAndroid Build Coastguard Worker 
ReplaceInstWithValue(BasicBlock::InstListType & BIL,BasicBlock::iterator & BI,Value * V)171*9880d681SAndroid Build Coastguard Worker void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
172*9880d681SAndroid Build Coastguard Worker                                 BasicBlock::iterator &BI, Value *V) {
173*9880d681SAndroid Build Coastguard Worker   Instruction &I = *BI;
174*9880d681SAndroid Build Coastguard Worker   // Replaces all of the uses of the instruction with uses of the value
175*9880d681SAndroid Build Coastguard Worker   I.replaceAllUsesWith(V);
176*9880d681SAndroid Build Coastguard Worker 
177*9880d681SAndroid Build Coastguard Worker   // Make sure to propagate a name if there is one already.
178*9880d681SAndroid Build Coastguard Worker   if (I.hasName() && !V->hasName())
179*9880d681SAndroid Build Coastguard Worker     V->takeName(&I);
180*9880d681SAndroid Build Coastguard Worker 
181*9880d681SAndroid Build Coastguard Worker   // Delete the unnecessary instruction now...
182*9880d681SAndroid Build Coastguard Worker   BI = BIL.erase(BI);
183*9880d681SAndroid Build Coastguard Worker }
184*9880d681SAndroid Build Coastguard Worker 
ReplaceInstWithInst(BasicBlock::InstListType & BIL,BasicBlock::iterator & BI,Instruction * I)185*9880d681SAndroid Build Coastguard Worker void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
186*9880d681SAndroid Build Coastguard Worker                                BasicBlock::iterator &BI, Instruction *I) {
187*9880d681SAndroid Build Coastguard Worker   assert(I->getParent() == nullptr &&
188*9880d681SAndroid Build Coastguard Worker          "ReplaceInstWithInst: Instruction already inserted into basic block!");
189*9880d681SAndroid Build Coastguard Worker 
190*9880d681SAndroid Build Coastguard Worker   // Copy debug location to newly added instruction, if it wasn't already set
191*9880d681SAndroid Build Coastguard Worker   // by the caller.
192*9880d681SAndroid Build Coastguard Worker   if (!I->getDebugLoc())
193*9880d681SAndroid Build Coastguard Worker     I->setDebugLoc(BI->getDebugLoc());
194*9880d681SAndroid Build Coastguard Worker 
195*9880d681SAndroid Build Coastguard Worker   // Insert the new instruction into the basic block...
196*9880d681SAndroid Build Coastguard Worker   BasicBlock::iterator New = BIL.insert(BI, I);
197*9880d681SAndroid Build Coastguard Worker 
198*9880d681SAndroid Build Coastguard Worker   // Replace all uses of the old instruction, and delete it.
199*9880d681SAndroid Build Coastguard Worker   ReplaceInstWithValue(BIL, BI, I);
200*9880d681SAndroid Build Coastguard Worker 
201*9880d681SAndroid Build Coastguard Worker   // Move BI back to point to the newly inserted instruction
202*9880d681SAndroid Build Coastguard Worker   BI = New;
203*9880d681SAndroid Build Coastguard Worker }
204*9880d681SAndroid Build Coastguard Worker 
ReplaceInstWithInst(Instruction * From,Instruction * To)205*9880d681SAndroid Build Coastguard Worker void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
206*9880d681SAndroid Build Coastguard Worker   BasicBlock::iterator BI(From);
207*9880d681SAndroid Build Coastguard Worker   ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
208*9880d681SAndroid Build Coastguard Worker }
209*9880d681SAndroid Build Coastguard Worker 
SplitEdge(BasicBlock * BB,BasicBlock * Succ,DominatorTree * DT,LoopInfo * LI)210*9880d681SAndroid Build Coastguard Worker BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
211*9880d681SAndroid Build Coastguard Worker                             LoopInfo *LI) {
212*9880d681SAndroid Build Coastguard Worker   unsigned SuccNum = GetSuccessorNumber(BB, Succ);
213*9880d681SAndroid Build Coastguard Worker 
214*9880d681SAndroid Build Coastguard Worker   // If this is a critical edge, let SplitCriticalEdge do it.
215*9880d681SAndroid Build Coastguard Worker   TerminatorInst *LatchTerm = BB->getTerminator();
216*9880d681SAndroid Build Coastguard Worker   if (SplitCriticalEdge(LatchTerm, SuccNum, CriticalEdgeSplittingOptions(DT, LI)
217*9880d681SAndroid Build Coastguard Worker                                                 .setPreserveLCSSA()))
218*9880d681SAndroid Build Coastguard Worker     return LatchTerm->getSuccessor(SuccNum);
219*9880d681SAndroid Build Coastguard Worker 
220*9880d681SAndroid Build Coastguard Worker   // If the edge isn't critical, then BB has a single successor or Succ has a
221*9880d681SAndroid Build Coastguard Worker   // single pred.  Split the block.
222*9880d681SAndroid Build Coastguard Worker   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
223*9880d681SAndroid Build Coastguard Worker     // If the successor only has a single pred, split the top of the successor
224*9880d681SAndroid Build Coastguard Worker     // block.
225*9880d681SAndroid Build Coastguard Worker     assert(SP == BB && "CFG broken");
226*9880d681SAndroid Build Coastguard Worker     SP = nullptr;
227*9880d681SAndroid Build Coastguard Worker     return SplitBlock(Succ, &Succ->front(), DT, LI);
228*9880d681SAndroid Build Coastguard Worker   }
229*9880d681SAndroid Build Coastguard Worker 
230*9880d681SAndroid Build Coastguard Worker   // Otherwise, if BB has a single successor, split it at the bottom of the
231*9880d681SAndroid Build Coastguard Worker   // block.
232*9880d681SAndroid Build Coastguard Worker   assert(BB->getTerminator()->getNumSuccessors() == 1 &&
233*9880d681SAndroid Build Coastguard Worker          "Should have a single succ!");
234*9880d681SAndroid Build Coastguard Worker   return SplitBlock(BB, BB->getTerminator(), DT, LI);
235*9880d681SAndroid Build Coastguard Worker }
236*9880d681SAndroid Build Coastguard Worker 
237*9880d681SAndroid Build Coastguard Worker unsigned
SplitAllCriticalEdges(Function & F,const CriticalEdgeSplittingOptions & Options)238*9880d681SAndroid Build Coastguard Worker llvm::SplitAllCriticalEdges(Function &F,
239*9880d681SAndroid Build Coastguard Worker                             const CriticalEdgeSplittingOptions &Options) {
240*9880d681SAndroid Build Coastguard Worker   unsigned NumBroken = 0;
241*9880d681SAndroid Build Coastguard Worker   for (BasicBlock &BB : F) {
242*9880d681SAndroid Build Coastguard Worker     TerminatorInst *TI = BB.getTerminator();
243*9880d681SAndroid Build Coastguard Worker     if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
244*9880d681SAndroid Build Coastguard Worker       for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
245*9880d681SAndroid Build Coastguard Worker         if (SplitCriticalEdge(TI, i, Options))
246*9880d681SAndroid Build Coastguard Worker           ++NumBroken;
247*9880d681SAndroid Build Coastguard Worker   }
248*9880d681SAndroid Build Coastguard Worker   return NumBroken;
249*9880d681SAndroid Build Coastguard Worker }
250*9880d681SAndroid Build Coastguard Worker 
SplitBlock(BasicBlock * Old,Instruction * SplitPt,DominatorTree * DT,LoopInfo * LI)251*9880d681SAndroid Build Coastguard Worker BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
252*9880d681SAndroid Build Coastguard Worker                              DominatorTree *DT, LoopInfo *LI) {
253*9880d681SAndroid Build Coastguard Worker   BasicBlock::iterator SplitIt = SplitPt->getIterator();
254*9880d681SAndroid Build Coastguard Worker   while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
255*9880d681SAndroid Build Coastguard Worker     ++SplitIt;
256*9880d681SAndroid Build Coastguard Worker   BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
257*9880d681SAndroid Build Coastguard Worker 
258*9880d681SAndroid Build Coastguard Worker   // The new block lives in whichever loop the old one did. This preserves
259*9880d681SAndroid Build Coastguard Worker   // LCSSA as well, because we force the split point to be after any PHI nodes.
260*9880d681SAndroid Build Coastguard Worker   if (LI)
261*9880d681SAndroid Build Coastguard Worker     if (Loop *L = LI->getLoopFor(Old))
262*9880d681SAndroid Build Coastguard Worker       L->addBasicBlockToLoop(New, *LI);
263*9880d681SAndroid Build Coastguard Worker 
264*9880d681SAndroid Build Coastguard Worker   if (DT)
265*9880d681SAndroid Build Coastguard Worker     // Old dominates New. New node dominates all other nodes dominated by Old.
266*9880d681SAndroid Build Coastguard Worker     if (DomTreeNode *OldNode = DT->getNode(Old)) {
267*9880d681SAndroid Build Coastguard Worker       std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
268*9880d681SAndroid Build Coastguard Worker 
269*9880d681SAndroid Build Coastguard Worker       DomTreeNode *NewNode = DT->addNewBlock(New, Old);
270*9880d681SAndroid Build Coastguard Worker       for (DomTreeNode *I : Children)
271*9880d681SAndroid Build Coastguard Worker         DT->changeImmediateDominator(I, NewNode);
272*9880d681SAndroid Build Coastguard Worker     }
273*9880d681SAndroid Build Coastguard Worker 
274*9880d681SAndroid Build Coastguard Worker   return New;
275*9880d681SAndroid Build Coastguard Worker }
276*9880d681SAndroid Build Coastguard Worker 
277*9880d681SAndroid Build Coastguard Worker /// Update DominatorTree, LoopInfo, and LCCSA analysis information.
UpdateAnalysisInformation(BasicBlock * OldBB,BasicBlock * NewBB,ArrayRef<BasicBlock * > Preds,DominatorTree * DT,LoopInfo * LI,bool PreserveLCSSA,bool & HasLoopExit)278*9880d681SAndroid Build Coastguard Worker static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
279*9880d681SAndroid Build Coastguard Worker                                       ArrayRef<BasicBlock *> Preds,
280*9880d681SAndroid Build Coastguard Worker                                       DominatorTree *DT, LoopInfo *LI,
281*9880d681SAndroid Build Coastguard Worker                                       bool PreserveLCSSA, bool &HasLoopExit) {
282*9880d681SAndroid Build Coastguard Worker   // Update dominator tree if available.
283*9880d681SAndroid Build Coastguard Worker   if (DT)
284*9880d681SAndroid Build Coastguard Worker     DT->splitBlock(NewBB);
285*9880d681SAndroid Build Coastguard Worker 
286*9880d681SAndroid Build Coastguard Worker   // The rest of the logic is only relevant for updating the loop structures.
287*9880d681SAndroid Build Coastguard Worker   if (!LI)
288*9880d681SAndroid Build Coastguard Worker     return;
289*9880d681SAndroid Build Coastguard Worker 
290*9880d681SAndroid Build Coastguard Worker   Loop *L = LI->getLoopFor(OldBB);
291*9880d681SAndroid Build Coastguard Worker 
292*9880d681SAndroid Build Coastguard Worker   // If we need to preserve loop analyses, collect some information about how
293*9880d681SAndroid Build Coastguard Worker   // this split will affect loops.
294*9880d681SAndroid Build Coastguard Worker   bool IsLoopEntry = !!L;
295*9880d681SAndroid Build Coastguard Worker   bool SplitMakesNewLoopHeader = false;
296*9880d681SAndroid Build Coastguard Worker   for (BasicBlock *Pred : Preds) {
297*9880d681SAndroid Build Coastguard Worker     // If we need to preserve LCSSA, determine if any of the preds is a loop
298*9880d681SAndroid Build Coastguard Worker     // exit.
299*9880d681SAndroid Build Coastguard Worker     if (PreserveLCSSA)
300*9880d681SAndroid Build Coastguard Worker       if (Loop *PL = LI->getLoopFor(Pred))
301*9880d681SAndroid Build Coastguard Worker         if (!PL->contains(OldBB))
302*9880d681SAndroid Build Coastguard Worker           HasLoopExit = true;
303*9880d681SAndroid Build Coastguard Worker 
304*9880d681SAndroid Build Coastguard Worker     // If we need to preserve LoopInfo, note whether any of the preds crosses
305*9880d681SAndroid Build Coastguard Worker     // an interesting loop boundary.
306*9880d681SAndroid Build Coastguard Worker     if (!L)
307*9880d681SAndroid Build Coastguard Worker       continue;
308*9880d681SAndroid Build Coastguard Worker     if (L->contains(Pred))
309*9880d681SAndroid Build Coastguard Worker       IsLoopEntry = false;
310*9880d681SAndroid Build Coastguard Worker     else
311*9880d681SAndroid Build Coastguard Worker       SplitMakesNewLoopHeader = true;
312*9880d681SAndroid Build Coastguard Worker   }
313*9880d681SAndroid Build Coastguard Worker 
314*9880d681SAndroid Build Coastguard Worker   // Unless we have a loop for OldBB, nothing else to do here.
315*9880d681SAndroid Build Coastguard Worker   if (!L)
316*9880d681SAndroid Build Coastguard Worker     return;
317*9880d681SAndroid Build Coastguard Worker 
318*9880d681SAndroid Build Coastguard Worker   if (IsLoopEntry) {
319*9880d681SAndroid Build Coastguard Worker     // Add the new block to the nearest enclosing loop (and not an adjacent
320*9880d681SAndroid Build Coastguard Worker     // loop). To find this, examine each of the predecessors and determine which
321*9880d681SAndroid Build Coastguard Worker     // loops enclose them, and select the most-nested loop which contains the
322*9880d681SAndroid Build Coastguard Worker     // loop containing the block being split.
323*9880d681SAndroid Build Coastguard Worker     Loop *InnermostPredLoop = nullptr;
324*9880d681SAndroid Build Coastguard Worker     for (BasicBlock *Pred : Preds) {
325*9880d681SAndroid Build Coastguard Worker       if (Loop *PredLoop = LI->getLoopFor(Pred)) {
326*9880d681SAndroid Build Coastguard Worker         // Seek a loop which actually contains the block being split (to avoid
327*9880d681SAndroid Build Coastguard Worker         // adjacent loops).
328*9880d681SAndroid Build Coastguard Worker         while (PredLoop && !PredLoop->contains(OldBB))
329*9880d681SAndroid Build Coastguard Worker           PredLoop = PredLoop->getParentLoop();
330*9880d681SAndroid Build Coastguard Worker 
331*9880d681SAndroid Build Coastguard Worker         // Select the most-nested of these loops which contains the block.
332*9880d681SAndroid Build Coastguard Worker         if (PredLoop && PredLoop->contains(OldBB) &&
333*9880d681SAndroid Build Coastguard Worker             (!InnermostPredLoop ||
334*9880d681SAndroid Build Coastguard Worker              InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
335*9880d681SAndroid Build Coastguard Worker           InnermostPredLoop = PredLoop;
336*9880d681SAndroid Build Coastguard Worker       }
337*9880d681SAndroid Build Coastguard Worker     }
338*9880d681SAndroid Build Coastguard Worker 
339*9880d681SAndroid Build Coastguard Worker     if (InnermostPredLoop)
340*9880d681SAndroid Build Coastguard Worker       InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
341*9880d681SAndroid Build Coastguard Worker   } else {
342*9880d681SAndroid Build Coastguard Worker     L->addBasicBlockToLoop(NewBB, *LI);
343*9880d681SAndroid Build Coastguard Worker     if (SplitMakesNewLoopHeader)
344*9880d681SAndroid Build Coastguard Worker       L->moveToHeader(NewBB);
345*9880d681SAndroid Build Coastguard Worker   }
346*9880d681SAndroid Build Coastguard Worker }
347*9880d681SAndroid Build Coastguard Worker 
348*9880d681SAndroid Build Coastguard Worker /// Update the PHI nodes in OrigBB to include the values coming from NewBB.
349*9880d681SAndroid Build Coastguard Worker /// This also updates AliasAnalysis, if available.
UpdatePHINodes(BasicBlock * OrigBB,BasicBlock * NewBB,ArrayRef<BasicBlock * > Preds,BranchInst * BI,bool HasLoopExit)350*9880d681SAndroid Build Coastguard Worker static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
351*9880d681SAndroid Build Coastguard Worker                            ArrayRef<BasicBlock *> Preds, BranchInst *BI,
352*9880d681SAndroid Build Coastguard Worker                            bool HasLoopExit) {
353*9880d681SAndroid Build Coastguard Worker   // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
354*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
355*9880d681SAndroid Build Coastguard Worker   for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
356*9880d681SAndroid Build Coastguard Worker     PHINode *PN = cast<PHINode>(I++);
357*9880d681SAndroid Build Coastguard Worker 
358*9880d681SAndroid Build Coastguard Worker     // Check to see if all of the values coming in are the same.  If so, we
359*9880d681SAndroid Build Coastguard Worker     // don't need to create a new PHI node, unless it's needed for LCSSA.
360*9880d681SAndroid Build Coastguard Worker     Value *InVal = nullptr;
361*9880d681SAndroid Build Coastguard Worker     if (!HasLoopExit) {
362*9880d681SAndroid Build Coastguard Worker       InVal = PN->getIncomingValueForBlock(Preds[0]);
363*9880d681SAndroid Build Coastguard Worker       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
364*9880d681SAndroid Build Coastguard Worker         if (!PredSet.count(PN->getIncomingBlock(i)))
365*9880d681SAndroid Build Coastguard Worker           continue;
366*9880d681SAndroid Build Coastguard Worker         if (!InVal)
367*9880d681SAndroid Build Coastguard Worker           InVal = PN->getIncomingValue(i);
368*9880d681SAndroid Build Coastguard Worker         else if (InVal != PN->getIncomingValue(i)) {
369*9880d681SAndroid Build Coastguard Worker           InVal = nullptr;
370*9880d681SAndroid Build Coastguard Worker           break;
371*9880d681SAndroid Build Coastguard Worker         }
372*9880d681SAndroid Build Coastguard Worker       }
373*9880d681SAndroid Build Coastguard Worker     }
374*9880d681SAndroid Build Coastguard Worker 
375*9880d681SAndroid Build Coastguard Worker     if (InVal) {
376*9880d681SAndroid Build Coastguard Worker       // If all incoming values for the new PHI would be the same, just don't
377*9880d681SAndroid Build Coastguard Worker       // make a new PHI.  Instead, just remove the incoming values from the old
378*9880d681SAndroid Build Coastguard Worker       // PHI.
379*9880d681SAndroid Build Coastguard Worker 
380*9880d681SAndroid Build Coastguard Worker       // NOTE! This loop walks backwards for a reason! First off, this minimizes
381*9880d681SAndroid Build Coastguard Worker       // the cost of removal if we end up removing a large number of values, and
382*9880d681SAndroid Build Coastguard Worker       // second off, this ensures that the indices for the incoming values
383*9880d681SAndroid Build Coastguard Worker       // aren't invalidated when we remove one.
384*9880d681SAndroid Build Coastguard Worker       for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
385*9880d681SAndroid Build Coastguard Worker         if (PredSet.count(PN->getIncomingBlock(i)))
386*9880d681SAndroid Build Coastguard Worker           PN->removeIncomingValue(i, false);
387*9880d681SAndroid Build Coastguard Worker 
388*9880d681SAndroid Build Coastguard Worker       // Add an incoming value to the PHI node in the loop for the preheader
389*9880d681SAndroid Build Coastguard Worker       // edge.
390*9880d681SAndroid Build Coastguard Worker       PN->addIncoming(InVal, NewBB);
391*9880d681SAndroid Build Coastguard Worker       continue;
392*9880d681SAndroid Build Coastguard Worker     }
393*9880d681SAndroid Build Coastguard Worker 
394*9880d681SAndroid Build Coastguard Worker     // If the values coming into the block are not the same, we need a new
395*9880d681SAndroid Build Coastguard Worker     // PHI.
396*9880d681SAndroid Build Coastguard Worker     // Create the new PHI node, insert it into NewBB at the end of the block
397*9880d681SAndroid Build Coastguard Worker     PHINode *NewPHI =
398*9880d681SAndroid Build Coastguard Worker         PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
399*9880d681SAndroid Build Coastguard Worker 
400*9880d681SAndroid Build Coastguard Worker     // NOTE! This loop walks backwards for a reason! First off, this minimizes
401*9880d681SAndroid Build Coastguard Worker     // the cost of removal if we end up removing a large number of values, and
402*9880d681SAndroid Build Coastguard Worker     // second off, this ensures that the indices for the incoming values aren't
403*9880d681SAndroid Build Coastguard Worker     // invalidated when we remove one.
404*9880d681SAndroid Build Coastguard Worker     for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
405*9880d681SAndroid Build Coastguard Worker       BasicBlock *IncomingBB = PN->getIncomingBlock(i);
406*9880d681SAndroid Build Coastguard Worker       if (PredSet.count(IncomingBB)) {
407*9880d681SAndroid Build Coastguard Worker         Value *V = PN->removeIncomingValue(i, false);
408*9880d681SAndroid Build Coastguard Worker         NewPHI->addIncoming(V, IncomingBB);
409*9880d681SAndroid Build Coastguard Worker       }
410*9880d681SAndroid Build Coastguard Worker     }
411*9880d681SAndroid Build Coastguard Worker 
412*9880d681SAndroid Build Coastguard Worker     PN->addIncoming(NewPHI, NewBB);
413*9880d681SAndroid Build Coastguard Worker   }
414*9880d681SAndroid Build Coastguard Worker }
415*9880d681SAndroid Build Coastguard Worker 
SplitBlockPredecessors(BasicBlock * BB,ArrayRef<BasicBlock * > Preds,const char * Suffix,DominatorTree * DT,LoopInfo * LI,bool PreserveLCSSA)416*9880d681SAndroid Build Coastguard Worker BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
417*9880d681SAndroid Build Coastguard Worker                                          ArrayRef<BasicBlock *> Preds,
418*9880d681SAndroid Build Coastguard Worker                                          const char *Suffix, DominatorTree *DT,
419*9880d681SAndroid Build Coastguard Worker                                          LoopInfo *LI, bool PreserveLCSSA) {
420*9880d681SAndroid Build Coastguard Worker   // Do not attempt to split that which cannot be split.
421*9880d681SAndroid Build Coastguard Worker   if (!BB->canSplitPredecessors())
422*9880d681SAndroid Build Coastguard Worker     return nullptr;
423*9880d681SAndroid Build Coastguard Worker 
424*9880d681SAndroid Build Coastguard Worker   // For the landingpads we need to act a bit differently.
425*9880d681SAndroid Build Coastguard Worker   // Delegate this work to the SplitLandingPadPredecessors.
426*9880d681SAndroid Build Coastguard Worker   if (BB->isLandingPad()) {
427*9880d681SAndroid Build Coastguard Worker     SmallVector<BasicBlock*, 2> NewBBs;
428*9880d681SAndroid Build Coastguard Worker     std::string NewName = std::string(Suffix) + ".split-lp";
429*9880d681SAndroid Build Coastguard Worker 
430*9880d681SAndroid Build Coastguard Worker     SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs, DT,
431*9880d681SAndroid Build Coastguard Worker                                 LI, PreserveLCSSA);
432*9880d681SAndroid Build Coastguard Worker     return NewBBs[0];
433*9880d681SAndroid Build Coastguard Worker   }
434*9880d681SAndroid Build Coastguard Worker 
435*9880d681SAndroid Build Coastguard Worker   // Create new basic block, insert right before the original block.
436*9880d681SAndroid Build Coastguard Worker   BasicBlock *NewBB = BasicBlock::Create(
437*9880d681SAndroid Build Coastguard Worker       BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
438*9880d681SAndroid Build Coastguard Worker 
439*9880d681SAndroid Build Coastguard Worker   // The new block unconditionally branches to the old block.
440*9880d681SAndroid Build Coastguard Worker   BranchInst *BI = BranchInst::Create(BB, NewBB);
441*9880d681SAndroid Build Coastguard Worker   BI->setDebugLoc(BB->getFirstNonPHI()->getDebugLoc());
442*9880d681SAndroid Build Coastguard Worker 
443*9880d681SAndroid Build Coastguard Worker   // Move the edges from Preds to point to NewBB instead of BB.
444*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
445*9880d681SAndroid Build Coastguard Worker     // This is slightly more strict than necessary; the minimum requirement
446*9880d681SAndroid Build Coastguard Worker     // is that there be no more than one indirectbr branching to BB. And
447*9880d681SAndroid Build Coastguard Worker     // all BlockAddress uses would need to be updated.
448*9880d681SAndroid Build Coastguard Worker     assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
449*9880d681SAndroid Build Coastguard Worker            "Cannot split an edge from an IndirectBrInst");
450*9880d681SAndroid Build Coastguard Worker     Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
451*9880d681SAndroid Build Coastguard Worker   }
452*9880d681SAndroid Build Coastguard Worker 
453*9880d681SAndroid Build Coastguard Worker   // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
454*9880d681SAndroid Build Coastguard Worker   // node becomes an incoming value for BB's phi node.  However, if the Preds
455*9880d681SAndroid Build Coastguard Worker   // list is empty, we need to insert dummy entries into the PHI nodes in BB to
456*9880d681SAndroid Build Coastguard Worker   // account for the newly created predecessor.
457*9880d681SAndroid Build Coastguard Worker   if (Preds.size() == 0) {
458*9880d681SAndroid Build Coastguard Worker     // Insert dummy values as the incoming value.
459*9880d681SAndroid Build Coastguard Worker     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
460*9880d681SAndroid Build Coastguard Worker       cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
461*9880d681SAndroid Build Coastguard Worker     return NewBB;
462*9880d681SAndroid Build Coastguard Worker   }
463*9880d681SAndroid Build Coastguard Worker 
464*9880d681SAndroid Build Coastguard Worker   // Update DominatorTree, LoopInfo, and LCCSA analysis information.
465*9880d681SAndroid Build Coastguard Worker   bool HasLoopExit = false;
466*9880d681SAndroid Build Coastguard Worker   UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, PreserveLCSSA,
467*9880d681SAndroid Build Coastguard Worker                             HasLoopExit);
468*9880d681SAndroid Build Coastguard Worker 
469*9880d681SAndroid Build Coastguard Worker   // Update the PHI nodes in BB with the values coming from NewBB.
470*9880d681SAndroid Build Coastguard Worker   UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
471*9880d681SAndroid Build Coastguard Worker   return NewBB;
472*9880d681SAndroid Build Coastguard Worker }
473*9880d681SAndroid Build Coastguard Worker 
SplitLandingPadPredecessors(BasicBlock * OrigBB,ArrayRef<BasicBlock * > Preds,const char * Suffix1,const char * Suffix2,SmallVectorImpl<BasicBlock * > & NewBBs,DominatorTree * DT,LoopInfo * LI,bool PreserveLCSSA)474*9880d681SAndroid Build Coastguard Worker void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
475*9880d681SAndroid Build Coastguard Worker                                        ArrayRef<BasicBlock *> Preds,
476*9880d681SAndroid Build Coastguard Worker                                        const char *Suffix1, const char *Suffix2,
477*9880d681SAndroid Build Coastguard Worker                                        SmallVectorImpl<BasicBlock *> &NewBBs,
478*9880d681SAndroid Build Coastguard Worker                                        DominatorTree *DT, LoopInfo *LI,
479*9880d681SAndroid Build Coastguard Worker                                        bool PreserveLCSSA) {
480*9880d681SAndroid Build Coastguard Worker   assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
481*9880d681SAndroid Build Coastguard Worker 
482*9880d681SAndroid Build Coastguard Worker   // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
483*9880d681SAndroid Build Coastguard Worker   // it right before the original block.
484*9880d681SAndroid Build Coastguard Worker   BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
485*9880d681SAndroid Build Coastguard Worker                                           OrigBB->getName() + Suffix1,
486*9880d681SAndroid Build Coastguard Worker                                           OrigBB->getParent(), OrigBB);
487*9880d681SAndroid Build Coastguard Worker   NewBBs.push_back(NewBB1);
488*9880d681SAndroid Build Coastguard Worker 
489*9880d681SAndroid Build Coastguard Worker   // The new block unconditionally branches to the old block.
490*9880d681SAndroid Build Coastguard Worker   BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
491*9880d681SAndroid Build Coastguard Worker   BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
492*9880d681SAndroid Build Coastguard Worker 
493*9880d681SAndroid Build Coastguard Worker   // Move the edges from Preds to point to NewBB1 instead of OrigBB.
494*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
495*9880d681SAndroid Build Coastguard Worker     // This is slightly more strict than necessary; the minimum requirement
496*9880d681SAndroid Build Coastguard Worker     // is that there be no more than one indirectbr branching to BB. And
497*9880d681SAndroid Build Coastguard Worker     // all BlockAddress uses would need to be updated.
498*9880d681SAndroid Build Coastguard Worker     assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
499*9880d681SAndroid Build Coastguard Worker            "Cannot split an edge from an IndirectBrInst");
500*9880d681SAndroid Build Coastguard Worker     Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
501*9880d681SAndroid Build Coastguard Worker   }
502*9880d681SAndroid Build Coastguard Worker 
503*9880d681SAndroid Build Coastguard Worker   bool HasLoopExit = false;
504*9880d681SAndroid Build Coastguard Worker   UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, PreserveLCSSA,
505*9880d681SAndroid Build Coastguard Worker                             HasLoopExit);
506*9880d681SAndroid Build Coastguard Worker 
507*9880d681SAndroid Build Coastguard Worker   // Update the PHI nodes in OrigBB with the values coming from NewBB1.
508*9880d681SAndroid Build Coastguard Worker   UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
509*9880d681SAndroid Build Coastguard Worker 
510*9880d681SAndroid Build Coastguard Worker   // Move the remaining edges from OrigBB to point to NewBB2.
511*9880d681SAndroid Build Coastguard Worker   SmallVector<BasicBlock*, 8> NewBB2Preds;
512*9880d681SAndroid Build Coastguard Worker   for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
513*9880d681SAndroid Build Coastguard Worker        i != e; ) {
514*9880d681SAndroid Build Coastguard Worker     BasicBlock *Pred = *i++;
515*9880d681SAndroid Build Coastguard Worker     if (Pred == NewBB1) continue;
516*9880d681SAndroid Build Coastguard Worker     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
517*9880d681SAndroid Build Coastguard Worker            "Cannot split an edge from an IndirectBrInst");
518*9880d681SAndroid Build Coastguard Worker     NewBB2Preds.push_back(Pred);
519*9880d681SAndroid Build Coastguard Worker     e = pred_end(OrigBB);
520*9880d681SAndroid Build Coastguard Worker   }
521*9880d681SAndroid Build Coastguard Worker 
522*9880d681SAndroid Build Coastguard Worker   BasicBlock *NewBB2 = nullptr;
523*9880d681SAndroid Build Coastguard Worker   if (!NewBB2Preds.empty()) {
524*9880d681SAndroid Build Coastguard Worker     // Create another basic block for the rest of OrigBB's predecessors.
525*9880d681SAndroid Build Coastguard Worker     NewBB2 = BasicBlock::Create(OrigBB->getContext(),
526*9880d681SAndroid Build Coastguard Worker                                 OrigBB->getName() + Suffix2,
527*9880d681SAndroid Build Coastguard Worker                                 OrigBB->getParent(), OrigBB);
528*9880d681SAndroid Build Coastguard Worker     NewBBs.push_back(NewBB2);
529*9880d681SAndroid Build Coastguard Worker 
530*9880d681SAndroid Build Coastguard Worker     // The new block unconditionally branches to the old block.
531*9880d681SAndroid Build Coastguard Worker     BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
532*9880d681SAndroid Build Coastguard Worker     BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
533*9880d681SAndroid Build Coastguard Worker 
534*9880d681SAndroid Build Coastguard Worker     // Move the remaining edges from OrigBB to point to NewBB2.
535*9880d681SAndroid Build Coastguard Worker     for (BasicBlock *NewBB2Pred : NewBB2Preds)
536*9880d681SAndroid Build Coastguard Worker       NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
537*9880d681SAndroid Build Coastguard Worker 
538*9880d681SAndroid Build Coastguard Worker     // Update DominatorTree, LoopInfo, and LCCSA analysis information.
539*9880d681SAndroid Build Coastguard Worker     HasLoopExit = false;
540*9880d681SAndroid Build Coastguard Worker     UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI,
541*9880d681SAndroid Build Coastguard Worker                               PreserveLCSSA, HasLoopExit);
542*9880d681SAndroid Build Coastguard Worker 
543*9880d681SAndroid Build Coastguard Worker     // Update the PHI nodes in OrigBB with the values coming from NewBB2.
544*9880d681SAndroid Build Coastguard Worker     UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
545*9880d681SAndroid Build Coastguard Worker   }
546*9880d681SAndroid Build Coastguard Worker 
547*9880d681SAndroid Build Coastguard Worker   LandingPadInst *LPad = OrigBB->getLandingPadInst();
548*9880d681SAndroid Build Coastguard Worker   Instruction *Clone1 = LPad->clone();
549*9880d681SAndroid Build Coastguard Worker   Clone1->setName(Twine("lpad") + Suffix1);
550*9880d681SAndroid Build Coastguard Worker   NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
551*9880d681SAndroid Build Coastguard Worker 
552*9880d681SAndroid Build Coastguard Worker   if (NewBB2) {
553*9880d681SAndroid Build Coastguard Worker     Instruction *Clone2 = LPad->clone();
554*9880d681SAndroid Build Coastguard Worker     Clone2->setName(Twine("lpad") + Suffix2);
555*9880d681SAndroid Build Coastguard Worker     NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
556*9880d681SAndroid Build Coastguard Worker 
557*9880d681SAndroid Build Coastguard Worker     // Create a PHI node for the two cloned landingpad instructions only
558*9880d681SAndroid Build Coastguard Worker     // if the original landingpad instruction has some uses.
559*9880d681SAndroid Build Coastguard Worker     if (!LPad->use_empty()) {
560*9880d681SAndroid Build Coastguard Worker       assert(!LPad->getType()->isTokenTy() &&
561*9880d681SAndroid Build Coastguard Worker              "Split cannot be applied if LPad is token type. Otherwise an "
562*9880d681SAndroid Build Coastguard Worker              "invalid PHINode of token type would be created.");
563*9880d681SAndroid Build Coastguard Worker       PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
564*9880d681SAndroid Build Coastguard Worker       PN->addIncoming(Clone1, NewBB1);
565*9880d681SAndroid Build Coastguard Worker       PN->addIncoming(Clone2, NewBB2);
566*9880d681SAndroid Build Coastguard Worker       LPad->replaceAllUsesWith(PN);
567*9880d681SAndroid Build Coastguard Worker     }
568*9880d681SAndroid Build Coastguard Worker     LPad->eraseFromParent();
569*9880d681SAndroid Build Coastguard Worker   } else {
570*9880d681SAndroid Build Coastguard Worker     // There is no second clone. Just replace the landing pad with the first
571*9880d681SAndroid Build Coastguard Worker     // clone.
572*9880d681SAndroid Build Coastguard Worker     LPad->replaceAllUsesWith(Clone1);
573*9880d681SAndroid Build Coastguard Worker     LPad->eraseFromParent();
574*9880d681SAndroid Build Coastguard Worker   }
575*9880d681SAndroid Build Coastguard Worker }
576*9880d681SAndroid Build Coastguard Worker 
FoldReturnIntoUncondBranch(ReturnInst * RI,BasicBlock * BB,BasicBlock * Pred)577*9880d681SAndroid Build Coastguard Worker ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
578*9880d681SAndroid Build Coastguard Worker                                              BasicBlock *Pred) {
579*9880d681SAndroid Build Coastguard Worker   Instruction *UncondBranch = Pred->getTerminator();
580*9880d681SAndroid Build Coastguard Worker   // Clone the return and add it to the end of the predecessor.
581*9880d681SAndroid Build Coastguard Worker   Instruction *NewRet = RI->clone();
582*9880d681SAndroid Build Coastguard Worker   Pred->getInstList().push_back(NewRet);
583*9880d681SAndroid Build Coastguard Worker 
584*9880d681SAndroid Build Coastguard Worker   // If the return instruction returns a value, and if the value was a
585*9880d681SAndroid Build Coastguard Worker   // PHI node in "BB", propagate the right value into the return.
586*9880d681SAndroid Build Coastguard Worker   for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
587*9880d681SAndroid Build Coastguard Worker        i != e; ++i) {
588*9880d681SAndroid Build Coastguard Worker     Value *V = *i;
589*9880d681SAndroid Build Coastguard Worker     Instruction *NewBC = nullptr;
590*9880d681SAndroid Build Coastguard Worker     if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
591*9880d681SAndroid Build Coastguard Worker       // Return value might be bitcasted. Clone and insert it before the
592*9880d681SAndroid Build Coastguard Worker       // return instruction.
593*9880d681SAndroid Build Coastguard Worker       V = BCI->getOperand(0);
594*9880d681SAndroid Build Coastguard Worker       NewBC = BCI->clone();
595*9880d681SAndroid Build Coastguard Worker       Pred->getInstList().insert(NewRet->getIterator(), NewBC);
596*9880d681SAndroid Build Coastguard Worker       *i = NewBC;
597*9880d681SAndroid Build Coastguard Worker     }
598*9880d681SAndroid Build Coastguard Worker     if (PHINode *PN = dyn_cast<PHINode>(V)) {
599*9880d681SAndroid Build Coastguard Worker       if (PN->getParent() == BB) {
600*9880d681SAndroid Build Coastguard Worker         if (NewBC)
601*9880d681SAndroid Build Coastguard Worker           NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
602*9880d681SAndroid Build Coastguard Worker         else
603*9880d681SAndroid Build Coastguard Worker           *i = PN->getIncomingValueForBlock(Pred);
604*9880d681SAndroid Build Coastguard Worker       }
605*9880d681SAndroid Build Coastguard Worker     }
606*9880d681SAndroid Build Coastguard Worker   }
607*9880d681SAndroid Build Coastguard Worker 
608*9880d681SAndroid Build Coastguard Worker   // Update any PHI nodes in the returning block to realize that we no
609*9880d681SAndroid Build Coastguard Worker   // longer branch to them.
610*9880d681SAndroid Build Coastguard Worker   BB->removePredecessor(Pred);
611*9880d681SAndroid Build Coastguard Worker   UncondBranch->eraseFromParent();
612*9880d681SAndroid Build Coastguard Worker   return cast<ReturnInst>(NewRet);
613*9880d681SAndroid Build Coastguard Worker }
614*9880d681SAndroid Build Coastguard Worker 
615*9880d681SAndroid Build Coastguard Worker TerminatorInst *
SplitBlockAndInsertIfThen(Value * Cond,Instruction * SplitBefore,bool Unreachable,MDNode * BranchWeights,DominatorTree * DT,LoopInfo * LI)616*9880d681SAndroid Build Coastguard Worker llvm::SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
617*9880d681SAndroid Build Coastguard Worker                                 bool Unreachable, MDNode *BranchWeights,
618*9880d681SAndroid Build Coastguard Worker                                 DominatorTree *DT, LoopInfo *LI) {
619*9880d681SAndroid Build Coastguard Worker   BasicBlock *Head = SplitBefore->getParent();
620*9880d681SAndroid Build Coastguard Worker   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
621*9880d681SAndroid Build Coastguard Worker   TerminatorInst *HeadOldTerm = Head->getTerminator();
622*9880d681SAndroid Build Coastguard Worker   LLVMContext &C = Head->getContext();
623*9880d681SAndroid Build Coastguard Worker   BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
624*9880d681SAndroid Build Coastguard Worker   TerminatorInst *CheckTerm;
625*9880d681SAndroid Build Coastguard Worker   if (Unreachable)
626*9880d681SAndroid Build Coastguard Worker     CheckTerm = new UnreachableInst(C, ThenBlock);
627*9880d681SAndroid Build Coastguard Worker   else
628*9880d681SAndroid Build Coastguard Worker     CheckTerm = BranchInst::Create(Tail, ThenBlock);
629*9880d681SAndroid Build Coastguard Worker   CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
630*9880d681SAndroid Build Coastguard Worker   BranchInst *HeadNewTerm =
631*9880d681SAndroid Build Coastguard Worker     BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
632*9880d681SAndroid Build Coastguard Worker   HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
633*9880d681SAndroid Build Coastguard Worker   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
634*9880d681SAndroid Build Coastguard Worker 
635*9880d681SAndroid Build Coastguard Worker   if (DT) {
636*9880d681SAndroid Build Coastguard Worker     if (DomTreeNode *OldNode = DT->getNode(Head)) {
637*9880d681SAndroid Build Coastguard Worker       std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
638*9880d681SAndroid Build Coastguard Worker 
639*9880d681SAndroid Build Coastguard Worker       DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
640*9880d681SAndroid Build Coastguard Worker       for (DomTreeNode *Child : Children)
641*9880d681SAndroid Build Coastguard Worker         DT->changeImmediateDominator(Child, NewNode);
642*9880d681SAndroid Build Coastguard Worker 
643*9880d681SAndroid Build Coastguard Worker       // Head dominates ThenBlock.
644*9880d681SAndroid Build Coastguard Worker       DT->addNewBlock(ThenBlock, Head);
645*9880d681SAndroid Build Coastguard Worker     }
646*9880d681SAndroid Build Coastguard Worker   }
647*9880d681SAndroid Build Coastguard Worker 
648*9880d681SAndroid Build Coastguard Worker   if (LI) {
649*9880d681SAndroid Build Coastguard Worker     Loop *L = LI->getLoopFor(Head);
650*9880d681SAndroid Build Coastguard Worker     L->addBasicBlockToLoop(ThenBlock, *LI);
651*9880d681SAndroid Build Coastguard Worker     L->addBasicBlockToLoop(Tail, *LI);
652*9880d681SAndroid Build Coastguard Worker   }
653*9880d681SAndroid Build Coastguard Worker 
654*9880d681SAndroid Build Coastguard Worker   return CheckTerm;
655*9880d681SAndroid Build Coastguard Worker }
656*9880d681SAndroid Build Coastguard Worker 
SplitBlockAndInsertIfThenElse(Value * Cond,Instruction * SplitBefore,TerminatorInst ** ThenTerm,TerminatorInst ** ElseTerm,MDNode * BranchWeights)657*9880d681SAndroid Build Coastguard Worker void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
658*9880d681SAndroid Build Coastguard Worker                                          TerminatorInst **ThenTerm,
659*9880d681SAndroid Build Coastguard Worker                                          TerminatorInst **ElseTerm,
660*9880d681SAndroid Build Coastguard Worker                                          MDNode *BranchWeights) {
661*9880d681SAndroid Build Coastguard Worker   BasicBlock *Head = SplitBefore->getParent();
662*9880d681SAndroid Build Coastguard Worker   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
663*9880d681SAndroid Build Coastguard Worker   TerminatorInst *HeadOldTerm = Head->getTerminator();
664*9880d681SAndroid Build Coastguard Worker   LLVMContext &C = Head->getContext();
665*9880d681SAndroid Build Coastguard Worker   BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
666*9880d681SAndroid Build Coastguard Worker   BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
667*9880d681SAndroid Build Coastguard Worker   *ThenTerm = BranchInst::Create(Tail, ThenBlock);
668*9880d681SAndroid Build Coastguard Worker   (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
669*9880d681SAndroid Build Coastguard Worker   *ElseTerm = BranchInst::Create(Tail, ElseBlock);
670*9880d681SAndroid Build Coastguard Worker   (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
671*9880d681SAndroid Build Coastguard Worker   BranchInst *HeadNewTerm =
672*9880d681SAndroid Build Coastguard Worker     BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
673*9880d681SAndroid Build Coastguard Worker   HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
674*9880d681SAndroid Build Coastguard Worker   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
675*9880d681SAndroid Build Coastguard Worker }
676*9880d681SAndroid Build Coastguard Worker 
677*9880d681SAndroid Build Coastguard Worker 
GetIfCondition(BasicBlock * BB,BasicBlock * & IfTrue,BasicBlock * & IfFalse)678*9880d681SAndroid Build Coastguard Worker Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
679*9880d681SAndroid Build Coastguard Worker                              BasicBlock *&IfFalse) {
680*9880d681SAndroid Build Coastguard Worker   PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
681*9880d681SAndroid Build Coastguard Worker   BasicBlock *Pred1 = nullptr;
682*9880d681SAndroid Build Coastguard Worker   BasicBlock *Pred2 = nullptr;
683*9880d681SAndroid Build Coastguard Worker 
684*9880d681SAndroid Build Coastguard Worker   if (SomePHI) {
685*9880d681SAndroid Build Coastguard Worker     if (SomePHI->getNumIncomingValues() != 2)
686*9880d681SAndroid Build Coastguard Worker       return nullptr;
687*9880d681SAndroid Build Coastguard Worker     Pred1 = SomePHI->getIncomingBlock(0);
688*9880d681SAndroid Build Coastguard Worker     Pred2 = SomePHI->getIncomingBlock(1);
689*9880d681SAndroid Build Coastguard Worker   } else {
690*9880d681SAndroid Build Coastguard Worker     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
691*9880d681SAndroid Build Coastguard Worker     if (PI == PE) // No predecessor
692*9880d681SAndroid Build Coastguard Worker       return nullptr;
693*9880d681SAndroid Build Coastguard Worker     Pred1 = *PI++;
694*9880d681SAndroid Build Coastguard Worker     if (PI == PE) // Only one predecessor
695*9880d681SAndroid Build Coastguard Worker       return nullptr;
696*9880d681SAndroid Build Coastguard Worker     Pred2 = *PI++;
697*9880d681SAndroid Build Coastguard Worker     if (PI != PE) // More than two predecessors
698*9880d681SAndroid Build Coastguard Worker       return nullptr;
699*9880d681SAndroid Build Coastguard Worker   }
700*9880d681SAndroid Build Coastguard Worker 
701*9880d681SAndroid Build Coastguard Worker   // We can only handle branches.  Other control flow will be lowered to
702*9880d681SAndroid Build Coastguard Worker   // branches if possible anyway.
703*9880d681SAndroid Build Coastguard Worker   BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
704*9880d681SAndroid Build Coastguard Worker   BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
705*9880d681SAndroid Build Coastguard Worker   if (!Pred1Br || !Pred2Br)
706*9880d681SAndroid Build Coastguard Worker     return nullptr;
707*9880d681SAndroid Build Coastguard Worker 
708*9880d681SAndroid Build Coastguard Worker   // Eliminate code duplication by ensuring that Pred1Br is conditional if
709*9880d681SAndroid Build Coastguard Worker   // either are.
710*9880d681SAndroid Build Coastguard Worker   if (Pred2Br->isConditional()) {
711*9880d681SAndroid Build Coastguard Worker     // If both branches are conditional, we don't have an "if statement".  In
712*9880d681SAndroid Build Coastguard Worker     // reality, we could transform this case, but since the condition will be
713*9880d681SAndroid Build Coastguard Worker     // required anyway, we stand no chance of eliminating it, so the xform is
714*9880d681SAndroid Build Coastguard Worker     // probably not profitable.
715*9880d681SAndroid Build Coastguard Worker     if (Pred1Br->isConditional())
716*9880d681SAndroid Build Coastguard Worker       return nullptr;
717*9880d681SAndroid Build Coastguard Worker 
718*9880d681SAndroid Build Coastguard Worker     std::swap(Pred1, Pred2);
719*9880d681SAndroid Build Coastguard Worker     std::swap(Pred1Br, Pred2Br);
720*9880d681SAndroid Build Coastguard Worker   }
721*9880d681SAndroid Build Coastguard Worker 
722*9880d681SAndroid Build Coastguard Worker   if (Pred1Br->isConditional()) {
723*9880d681SAndroid Build Coastguard Worker     // The only thing we have to watch out for here is to make sure that Pred2
724*9880d681SAndroid Build Coastguard Worker     // doesn't have incoming edges from other blocks.  If it does, the condition
725*9880d681SAndroid Build Coastguard Worker     // doesn't dominate BB.
726*9880d681SAndroid Build Coastguard Worker     if (!Pred2->getSinglePredecessor())
727*9880d681SAndroid Build Coastguard Worker       return nullptr;
728*9880d681SAndroid Build Coastguard Worker 
729*9880d681SAndroid Build Coastguard Worker     // If we found a conditional branch predecessor, make sure that it branches
730*9880d681SAndroid Build Coastguard Worker     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
731*9880d681SAndroid Build Coastguard Worker     if (Pred1Br->getSuccessor(0) == BB &&
732*9880d681SAndroid Build Coastguard Worker         Pred1Br->getSuccessor(1) == Pred2) {
733*9880d681SAndroid Build Coastguard Worker       IfTrue = Pred1;
734*9880d681SAndroid Build Coastguard Worker       IfFalse = Pred2;
735*9880d681SAndroid Build Coastguard Worker     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
736*9880d681SAndroid Build Coastguard Worker                Pred1Br->getSuccessor(1) == BB) {
737*9880d681SAndroid Build Coastguard Worker       IfTrue = Pred2;
738*9880d681SAndroid Build Coastguard Worker       IfFalse = Pred1;
739*9880d681SAndroid Build Coastguard Worker     } else {
740*9880d681SAndroid Build Coastguard Worker       // We know that one arm of the conditional goes to BB, so the other must
741*9880d681SAndroid Build Coastguard Worker       // go somewhere unrelated, and this must not be an "if statement".
742*9880d681SAndroid Build Coastguard Worker       return nullptr;
743*9880d681SAndroid Build Coastguard Worker     }
744*9880d681SAndroid Build Coastguard Worker 
745*9880d681SAndroid Build Coastguard Worker     return Pred1Br->getCondition();
746*9880d681SAndroid Build Coastguard Worker   }
747*9880d681SAndroid Build Coastguard Worker 
748*9880d681SAndroid Build Coastguard Worker   // Ok, if we got here, both predecessors end with an unconditional branch to
749*9880d681SAndroid Build Coastguard Worker   // BB.  Don't panic!  If both blocks only have a single (identical)
750*9880d681SAndroid Build Coastguard Worker   // predecessor, and THAT is a conditional branch, then we're all ok!
751*9880d681SAndroid Build Coastguard Worker   BasicBlock *CommonPred = Pred1->getSinglePredecessor();
752*9880d681SAndroid Build Coastguard Worker   if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
753*9880d681SAndroid Build Coastguard Worker     return nullptr;
754*9880d681SAndroid Build Coastguard Worker 
755*9880d681SAndroid Build Coastguard Worker   // Otherwise, if this is a conditional branch, then we can use it!
756*9880d681SAndroid Build Coastguard Worker   BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
757*9880d681SAndroid Build Coastguard Worker   if (!BI) return nullptr;
758*9880d681SAndroid Build Coastguard Worker 
759*9880d681SAndroid Build Coastguard Worker   assert(BI->isConditional() && "Two successors but not conditional?");
760*9880d681SAndroid Build Coastguard Worker   if (BI->getSuccessor(0) == Pred1) {
761*9880d681SAndroid Build Coastguard Worker     IfTrue = Pred1;
762*9880d681SAndroid Build Coastguard Worker     IfFalse = Pred2;
763*9880d681SAndroid Build Coastguard Worker   } else {
764*9880d681SAndroid Build Coastguard Worker     IfTrue = Pred2;
765*9880d681SAndroid Build Coastguard Worker     IfFalse = Pred1;
766*9880d681SAndroid Build Coastguard Worker   }
767*9880d681SAndroid Build Coastguard Worker   return BI->getCondition();
768*9880d681SAndroid Build Coastguard Worker }
769