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