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