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