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