LLVM API Documentation

BasicBlockUtils.cpp
Go to the documentation of this file.
00001 //===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This family of functions perform manipulations on basic blocks, and
00011 // instructions contained within basic blocks.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00016 #include "llvm/Analysis/AliasAnalysis.h"
00017 #include "llvm/Analysis/CFG.h"
00018 #include "llvm/Analysis/LoopInfo.h"
00019 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
00020 #include "llvm/IR/Constant.h"
00021 #include "llvm/IR/DataLayout.h"
00022 #include "llvm/IR/Dominators.h"
00023 #include "llvm/IR/Function.h"
00024 #include "llvm/IR/Instructions.h"
00025 #include "llvm/IR/IntrinsicInst.h"
00026 #include "llvm/IR/Type.h"
00027 #include "llvm/IR/ValueHandle.h"
00028 #include "llvm/Support/ErrorHandling.h"
00029 #include "llvm/Transforms/Scalar.h"
00030 #include "llvm/Transforms/Utils/Local.h"
00031 #include <algorithm>
00032 using namespace llvm;
00033 
00034 /// DeleteDeadBlock - Delete the specified block, which must have no
00035 /// predecessors.
00036 void llvm::DeleteDeadBlock(BasicBlock *BB) {
00037   assert((pred_begin(BB) == pred_end(BB) ||
00038          // Can delete self loop.
00039          BB->getSinglePredecessor() == BB) && "Block is not dead!");
00040   TerminatorInst *BBTerm = BB->getTerminator();
00041 
00042   // Loop through all of our successors and make sure they know that one
00043   // of their predecessors is going away.
00044   for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
00045     BBTerm->getSuccessor(i)->removePredecessor(BB);
00046 
00047   // Zap all the instructions in the block.
00048   while (!BB->empty()) {
00049     Instruction &I = BB->back();
00050     // If this instruction is used, replace uses with an arbitrary value.
00051     // Because control flow can't get here, we don't care what we replace the
00052     // value with.  Note that since this block is unreachable, and all values
00053     // contained within it must dominate their uses, that all uses will
00054     // eventually be removed (they are themselves dead).
00055     if (!I.use_empty())
00056       I.replaceAllUsesWith(UndefValue::get(I.getType()));
00057     BB->getInstList().pop_back();
00058   }
00059 
00060   // Zap the block!
00061   BB->eraseFromParent();
00062 }
00063 
00064 /// FoldSingleEntryPHINodes - We know that BB has one predecessor.  If there are
00065 /// any single-entry PHI nodes in it, fold them away.  This handles the case
00066 /// when all entries to the PHI nodes in a block are guaranteed equal, such as
00067 /// when the block has exactly one predecessor.
00068 void llvm::FoldSingleEntryPHINodes(BasicBlock *BB, Pass *P) {
00069   if (!isa<PHINode>(BB->begin())) return;
00070 
00071   AliasAnalysis *AA = nullptr;
00072   MemoryDependenceAnalysis *MemDep = nullptr;
00073   if (P) {
00074     AA = P->getAnalysisIfAvailable<AliasAnalysis>();
00075     MemDep = P->getAnalysisIfAvailable<MemoryDependenceAnalysis>();
00076   }
00077 
00078   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
00079     if (PN->getIncomingValue(0) != PN)
00080       PN->replaceAllUsesWith(PN->getIncomingValue(0));
00081     else
00082       PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
00083 
00084     if (MemDep)
00085       MemDep->removeInstruction(PN);  // Memdep updates AA itself.
00086     else if (AA && isa<PointerType>(PN->getType()))
00087       AA->deleteValue(PN);
00088 
00089     PN->eraseFromParent();
00090   }
00091 }
00092 
00093 
00094 /// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
00095 /// is dead. Also recursively delete any operands that become dead as
00096 /// a result. This includes tracing the def-use list from the PHI to see if
00097 /// it is ultimately unused or if it reaches an unused cycle.
00098 bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
00099   // Recursively deleting a PHI may cause multiple PHIs to be deleted
00100   // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
00101   SmallVector<WeakVH, 8> PHIs;
00102   for (BasicBlock::iterator I = BB->begin();
00103        PHINode *PN = dyn_cast<PHINode>(I); ++I)
00104     PHIs.push_back(PN);
00105 
00106   bool Changed = false;
00107   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
00108     if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
00109       Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
00110 
00111   return Changed;
00112 }
00113 
00114 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
00115 /// if possible.  The return value indicates success or failure.
00116 bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, Pass *P) {
00117   // Don't merge away blocks who have their address taken.
00118   if (BB->hasAddressTaken()) return false;
00119 
00120   // Can't merge if there are multiple predecessors, or no predecessors.
00121   BasicBlock *PredBB = BB->getUniquePredecessor();
00122   if (!PredBB) return false;
00123 
00124   // Don't break self-loops.
00125   if (PredBB == BB) return false;
00126   // Don't break invokes.
00127   if (isa<InvokeInst>(PredBB->getTerminator())) return false;
00128 
00129   succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
00130   BasicBlock *OnlySucc = BB;
00131   for (; SI != SE; ++SI)
00132     if (*SI != OnlySucc) {
00133       OnlySucc = nullptr;     // There are multiple distinct successors!
00134       break;
00135     }
00136 
00137   // Can't merge if there are multiple successors.
00138   if (!OnlySucc) return false;
00139 
00140   // Can't merge if there is PHI loop.
00141   for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
00142     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
00143       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00144         if (PN->getIncomingValue(i) == PN)
00145           return false;
00146     } else
00147       break;
00148   }
00149 
00150   // Begin by getting rid of unneeded PHIs.
00151   if (isa<PHINode>(BB->front()))
00152     FoldSingleEntryPHINodes(BB, P);
00153 
00154   // Delete the unconditional branch from the predecessor...
00155   PredBB->getInstList().pop_back();
00156 
00157   // Make all PHI nodes that referred to BB now refer to Pred as their
00158   // source...
00159   BB->replaceAllUsesWith(PredBB);
00160 
00161   // Move all definitions in the successor to the predecessor...
00162   PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
00163 
00164   // Inherit predecessors name if it exists.
00165   if (!PredBB->hasName())
00166     PredBB->takeName(BB);
00167 
00168   // Finally, erase the old block and update dominator info.
00169   if (P) {
00170     if (DominatorTreeWrapperPass *DTWP =
00171             P->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
00172       DominatorTree &DT = DTWP->getDomTree();
00173       if (DomTreeNode *DTN = DT.getNode(BB)) {
00174         DomTreeNode *PredDTN = DT.getNode(PredBB);
00175         SmallVector<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
00176         for (SmallVectorImpl<DomTreeNode *>::iterator DI = Children.begin(),
00177              DE = Children.end(); DI != DE; ++DI)
00178           DT.changeImmediateDominator(*DI, PredDTN);
00179 
00180         DT.eraseNode(BB);
00181       }
00182 
00183       if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>())
00184         LI->removeBlock(BB);
00185 
00186       if (MemoryDependenceAnalysis *MD =
00187             P->getAnalysisIfAvailable<MemoryDependenceAnalysis>())
00188         MD->invalidateCachedPredecessors();
00189     }
00190   }
00191 
00192   BB->eraseFromParent();
00193   return true;
00194 }
00195 
00196 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
00197 /// with a value, then remove and delete the original instruction.
00198 ///
00199 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
00200                                 BasicBlock::iterator &BI, Value *V) {
00201   Instruction &I = *BI;
00202   // Replaces all of the uses of the instruction with uses of the value
00203   I.replaceAllUsesWith(V);
00204 
00205   // Make sure to propagate a name if there is one already.
00206   if (I.hasName() && !V->hasName())
00207     V->takeName(&I);
00208 
00209   // Delete the unnecessary instruction now...
00210   BI = BIL.erase(BI);
00211 }
00212 
00213 
00214 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
00215 /// instruction specified by I.  The original instruction is deleted and BI is
00216 /// updated to point to the new instruction.
00217 ///
00218 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
00219                                BasicBlock::iterator &BI, Instruction *I) {
00220   assert(I->getParent() == nullptr &&
00221          "ReplaceInstWithInst: Instruction already inserted into basic block!");
00222 
00223   // Insert the new instruction into the basic block...
00224   BasicBlock::iterator New = BIL.insert(BI, I);
00225 
00226   // Replace all uses of the old instruction, and delete it.
00227   ReplaceInstWithValue(BIL, BI, I);
00228 
00229   // Move BI back to point to the newly inserted instruction
00230   BI = New;
00231 }
00232 
00233 /// ReplaceInstWithInst - Replace the instruction specified by From with the
00234 /// instruction specified by To.
00235 ///
00236 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
00237   BasicBlock::iterator BI(From);
00238   ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
00239 }
00240 
00241 /// SplitEdge -  Split the edge connecting specified block. Pass P must
00242 /// not be NULL.
00243 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
00244   unsigned SuccNum = GetSuccessorNumber(BB, Succ);
00245 
00246   // If this is a critical edge, let SplitCriticalEdge do it.
00247   TerminatorInst *LatchTerm = BB->getTerminator();
00248   if (SplitCriticalEdge(LatchTerm, SuccNum, P))
00249     return LatchTerm->getSuccessor(SuccNum);
00250 
00251   // If the edge isn't critical, then BB has a single successor or Succ has a
00252   // single pred.  Split the block.
00253   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
00254     // If the successor only has a single pred, split the top of the successor
00255     // block.
00256     assert(SP == BB && "CFG broken");
00257     SP = nullptr;
00258     return SplitBlock(Succ, Succ->begin(), P);
00259   }
00260 
00261   // Otherwise, if BB has a single successor, split it at the bottom of the
00262   // block.
00263   assert(BB->getTerminator()->getNumSuccessors() == 1 &&
00264          "Should have a single succ!");
00265   return SplitBlock(BB, BB->getTerminator(), P);
00266 }
00267 
00268 /// SplitBlock - Split the specified block at the specified instruction - every
00269 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
00270 /// to a new block.  The two blocks are joined by an unconditional branch and
00271 /// the loop info is updated.
00272 ///
00273 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
00274   BasicBlock::iterator SplitIt = SplitPt;
00275   while (isa<PHINode>(SplitIt) || isa<LandingPadInst>(SplitIt))
00276     ++SplitIt;
00277   BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
00278 
00279   // The new block lives in whichever loop the old one did. This preserves
00280   // LCSSA as well, because we force the split point to be after any PHI nodes.
00281   if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>())
00282     if (Loop *L = LI->getLoopFor(Old))
00283       L->addBasicBlockToLoop(New, LI->getBase());
00284 
00285   if (DominatorTreeWrapperPass *DTWP =
00286           P->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
00287     DominatorTree &DT = DTWP->getDomTree();
00288     // Old dominates New. New node dominates all other nodes dominated by Old.
00289     if (DomTreeNode *OldNode = DT.getNode(Old)) {
00290       std::vector<DomTreeNode *> Children;
00291       for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
00292            I != E; ++I)
00293         Children.push_back(*I);
00294 
00295       DomTreeNode *NewNode = DT.addNewBlock(New, Old);
00296       for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
00297              E = Children.end(); I != E; ++I)
00298         DT.changeImmediateDominator(*I, NewNode);
00299     }
00300   }
00301 
00302   return New;
00303 }
00304 
00305 /// UpdateAnalysisInformation - Update DominatorTree, LoopInfo, and LCCSA
00306 /// analysis information.
00307 static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
00308                                       ArrayRef<BasicBlock *> Preds,
00309                                       Pass *P, bool &HasLoopExit) {
00310   if (!P) return;
00311 
00312   LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>();
00313   Loop *L = LI ? LI->getLoopFor(OldBB) : nullptr;
00314 
00315   // If we need to preserve loop analyses, collect some information about how
00316   // this split will affect loops.
00317   bool IsLoopEntry = !!L;
00318   bool SplitMakesNewLoopHeader = false;
00319   if (LI) {
00320     bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
00321     for (ArrayRef<BasicBlock*>::iterator
00322            i = Preds.begin(), e = Preds.end(); i != e; ++i) {
00323       BasicBlock *Pred = *i;
00324 
00325       // If we need to preserve LCSSA, determine if any of the preds is a loop
00326       // exit.
00327       if (PreserveLCSSA)
00328         if (Loop *PL = LI->getLoopFor(Pred))
00329           if (!PL->contains(OldBB))
00330             HasLoopExit = true;
00331 
00332       // If we need to preserve LoopInfo, note whether any of the preds crosses
00333       // an interesting loop boundary.
00334       if (!L) continue;
00335       if (L->contains(Pred))
00336         IsLoopEntry = false;
00337       else
00338         SplitMakesNewLoopHeader = true;
00339     }
00340   }
00341 
00342   // Update dominator tree if available.
00343   if (DominatorTreeWrapperPass *DTWP =
00344           P->getAnalysisIfAvailable<DominatorTreeWrapperPass>())
00345     DTWP->getDomTree().splitBlock(NewBB);
00346 
00347   if (!L) return;
00348 
00349   if (IsLoopEntry) {
00350     // Add the new block to the nearest enclosing loop (and not an adjacent
00351     // loop). To find this, examine each of the predecessors and determine which
00352     // loops enclose them, and select the most-nested loop which contains the
00353     // loop containing the block being split.
00354     Loop *InnermostPredLoop = nullptr;
00355     for (ArrayRef<BasicBlock*>::iterator
00356            i = Preds.begin(), e = Preds.end(); i != e; ++i) {
00357       BasicBlock *Pred = *i;
00358       if (Loop *PredLoop = LI->getLoopFor(Pred)) {
00359         // Seek a loop which actually contains the block being split (to avoid
00360         // adjacent loops).
00361         while (PredLoop && !PredLoop->contains(OldBB))
00362           PredLoop = PredLoop->getParentLoop();
00363 
00364         // Select the most-nested of these loops which contains the block.
00365         if (PredLoop && PredLoop->contains(OldBB) &&
00366             (!InnermostPredLoop ||
00367              InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
00368           InnermostPredLoop = PredLoop;
00369       }
00370     }
00371 
00372     if (InnermostPredLoop)
00373       InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase());
00374   } else {
00375     L->addBasicBlockToLoop(NewBB, LI->getBase());
00376     if (SplitMakesNewLoopHeader)
00377       L->moveToHeader(NewBB);
00378   }
00379 }
00380 
00381 /// UpdatePHINodes - Update the PHI nodes in OrigBB to include the values coming
00382 /// from NewBB. This also updates AliasAnalysis, if available.
00383 static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
00384                            ArrayRef<BasicBlock*> Preds, BranchInst *BI,
00385                            Pass *P, bool HasLoopExit) {
00386   // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
00387   AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : nullptr;
00388   SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
00389   for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
00390     PHINode *PN = cast<PHINode>(I++);
00391 
00392     // Check to see if all of the values coming in are the same.  If so, we
00393     // don't need to create a new PHI node, unless it's needed for LCSSA.
00394     Value *InVal = nullptr;
00395     if (!HasLoopExit) {
00396       InVal = PN->getIncomingValueForBlock(Preds[0]);
00397       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00398         if (!PredSet.count(PN->getIncomingBlock(i)))
00399           continue;
00400         if (!InVal)
00401           InVal = PN->getIncomingValue(i);
00402         else if (InVal != PN->getIncomingValue(i)) {
00403           InVal = nullptr;
00404           break;
00405         }
00406       }
00407     }
00408 
00409     if (InVal) {
00410       // If all incoming values for the new PHI would be the same, just don't
00411       // make a new PHI.  Instead, just remove the incoming values from the old
00412       // PHI.
00413 
00414       // NOTE! This loop walks backwards for a reason! First off, this minimizes
00415       // the cost of removal if we end up removing a large number of values, and
00416       // second off, this ensures that the indices for the incoming values
00417       // aren't invalidated when we remove one.
00418       for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
00419         if (PredSet.count(PN->getIncomingBlock(i)))
00420           PN->removeIncomingValue(i, false);
00421 
00422       // Add an incoming value to the PHI node in the loop for the preheader
00423       // edge.
00424       PN->addIncoming(InVal, NewBB);
00425       continue;
00426     }
00427 
00428     // If the values coming into the block are not the same, we need a new
00429     // PHI.
00430     // Create the new PHI node, insert it into NewBB at the end of the block
00431     PHINode *NewPHI =
00432         PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
00433     if (AA)
00434       AA->copyValue(PN, NewPHI);
00435 
00436     // NOTE! This loop walks backwards for a reason! First off, this minimizes
00437     // the cost of removal if we end up removing a large number of values, and
00438     // second off, this ensures that the indices for the incoming values aren't
00439     // invalidated when we remove one.
00440     for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
00441       BasicBlock *IncomingBB = PN->getIncomingBlock(i);
00442       if (PredSet.count(IncomingBB)) {
00443         Value *V = PN->removeIncomingValue(i, false);
00444         NewPHI->addIncoming(V, IncomingBB);
00445       }
00446     }
00447 
00448     PN->addIncoming(NewPHI, NewBB);
00449   }
00450 }
00451 
00452 /// SplitBlockPredecessors - This method transforms BB by introducing a new
00453 /// basic block into the function, and moving some of the predecessors of BB to
00454 /// be predecessors of the new block.  The new predecessors are indicated by the
00455 /// Preds array, which has NumPreds elements in it.  The new block is given a
00456 /// suffix of 'Suffix'.
00457 ///
00458 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
00459 /// LoopInfo, and LCCSA but no other analyses. In particular, it does not
00460 /// preserve LoopSimplify (because it's complicated to handle the case where one
00461 /// of the edges being split is an exit of a loop with other exits).
00462 ///
00463 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
00464                                          ArrayRef<BasicBlock*> Preds,
00465                                          const char *Suffix, Pass *P) {
00466   // Create new basic block, insert right before the original block.
00467   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
00468                                          BB->getParent(), BB);
00469 
00470   // The new block unconditionally branches to the old block.
00471   BranchInst *BI = BranchInst::Create(BB, NewBB);
00472 
00473   // Move the edges from Preds to point to NewBB instead of BB.
00474   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
00475     // This is slightly more strict than necessary; the minimum requirement
00476     // is that there be no more than one indirectbr branching to BB. And
00477     // all BlockAddress uses would need to be updated.
00478     assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
00479            "Cannot split an edge from an IndirectBrInst");
00480     Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
00481   }
00482 
00483   // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
00484   // node becomes an incoming value for BB's phi node.  However, if the Preds
00485   // list is empty, we need to insert dummy entries into the PHI nodes in BB to
00486   // account for the newly created predecessor.
00487   if (Preds.size() == 0) {
00488     // Insert dummy values as the incoming value.
00489     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
00490       cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
00491     return NewBB;
00492   }
00493 
00494   // Update DominatorTree, LoopInfo, and LCCSA analysis information.
00495   bool HasLoopExit = false;
00496   UpdateAnalysisInformation(BB, NewBB, Preds, P, HasLoopExit);
00497 
00498   // Update the PHI nodes in BB with the values coming from NewBB.
00499   UpdatePHINodes(BB, NewBB, Preds, BI, P, HasLoopExit);
00500   return NewBB;
00501 }
00502 
00503 /// SplitLandingPadPredecessors - This method transforms the landing pad,
00504 /// OrigBB, by introducing two new basic blocks into the function. One of those
00505 /// new basic blocks gets the predecessors listed in Preds. The other basic
00506 /// block gets the remaining predecessors of OrigBB. The landingpad instruction
00507 /// OrigBB is clone into both of the new basic blocks. The new blocks are given
00508 /// the suffixes 'Suffix1' and 'Suffix2', and are returned in the NewBBs vector.
00509 ///
00510 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
00511 /// DominanceFrontier, LoopInfo, and LCCSA but no other analyses. In particular,
00512 /// it does not preserve LoopSimplify (because it's complicated to handle the
00513 /// case where one of the edges being split is an exit of a loop with other
00514 /// exits).
00515 ///
00516 void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
00517                                        ArrayRef<BasicBlock*> Preds,
00518                                        const char *Suffix1, const char *Suffix2,
00519                                        Pass *P,
00520                                        SmallVectorImpl<BasicBlock*> &NewBBs) {
00521   assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
00522 
00523   // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
00524   // it right before the original block.
00525   BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
00526                                           OrigBB->getName() + Suffix1,
00527                                           OrigBB->getParent(), OrigBB);
00528   NewBBs.push_back(NewBB1);
00529 
00530   // The new block unconditionally branches to the old block.
00531   BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
00532 
00533   // Move the edges from Preds to point to NewBB1 instead of OrigBB.
00534   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
00535     // This is slightly more strict than necessary; the minimum requirement
00536     // is that there be no more than one indirectbr branching to BB. And
00537     // all BlockAddress uses would need to be updated.
00538     assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
00539            "Cannot split an edge from an IndirectBrInst");
00540     Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
00541   }
00542 
00543   // Update DominatorTree, LoopInfo, and LCCSA analysis information.
00544   bool HasLoopExit = false;
00545   UpdateAnalysisInformation(OrigBB, NewBB1, Preds, P, HasLoopExit);
00546 
00547   // Update the PHI nodes in OrigBB with the values coming from NewBB1.
00548   UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, P, HasLoopExit);
00549 
00550   // Move the remaining edges from OrigBB to point to NewBB2.
00551   SmallVector<BasicBlock*, 8> NewBB2Preds;
00552   for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
00553        i != e; ) {
00554     BasicBlock *Pred = *i++;
00555     if (Pred == NewBB1) continue;
00556     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
00557            "Cannot split an edge from an IndirectBrInst");
00558     NewBB2Preds.push_back(Pred);
00559     e = pred_end(OrigBB);
00560   }
00561 
00562   BasicBlock *NewBB2 = nullptr;
00563   if (!NewBB2Preds.empty()) {
00564     // Create another basic block for the rest of OrigBB's predecessors.
00565     NewBB2 = BasicBlock::Create(OrigBB->getContext(),
00566                                 OrigBB->getName() + Suffix2,
00567                                 OrigBB->getParent(), OrigBB);
00568     NewBBs.push_back(NewBB2);
00569 
00570     // The new block unconditionally branches to the old block.
00571     BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
00572 
00573     // Move the remaining edges from OrigBB to point to NewBB2.
00574     for (SmallVectorImpl<BasicBlock*>::iterator
00575            i = NewBB2Preds.begin(), e = NewBB2Preds.end(); i != e; ++i)
00576       (*i)->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
00577 
00578     // Update DominatorTree, LoopInfo, and LCCSA analysis information.
00579     HasLoopExit = false;
00580     UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, P, HasLoopExit);
00581 
00582     // Update the PHI nodes in OrigBB with the values coming from NewBB2.
00583     UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, P, HasLoopExit);
00584   }
00585 
00586   LandingPadInst *LPad = OrigBB->getLandingPadInst();
00587   Instruction *Clone1 = LPad->clone();
00588   Clone1->setName(Twine("lpad") + Suffix1);
00589   NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
00590 
00591   if (NewBB2) {
00592     Instruction *Clone2 = LPad->clone();
00593     Clone2->setName(Twine("lpad") + Suffix2);
00594     NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
00595 
00596     // Create a PHI node for the two cloned landingpad instructions.
00597     PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
00598     PN->addIncoming(Clone1, NewBB1);
00599     PN->addIncoming(Clone2, NewBB2);
00600     LPad->replaceAllUsesWith(PN);
00601     LPad->eraseFromParent();
00602   } else {
00603     // There is no second clone. Just replace the landing pad with the first
00604     // clone.
00605     LPad->replaceAllUsesWith(Clone1);
00606     LPad->eraseFromParent();
00607   }
00608 }
00609 
00610 /// FoldReturnIntoUncondBranch - This method duplicates the specified return
00611 /// instruction into a predecessor which ends in an unconditional branch. If
00612 /// the return instruction returns a value defined by a PHI, propagate the
00613 /// right value into the return. It returns the new return instruction in the
00614 /// predecessor.
00615 ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
00616                                              BasicBlock *Pred) {
00617   Instruction *UncondBranch = Pred->getTerminator();
00618   // Clone the return and add it to the end of the predecessor.
00619   Instruction *NewRet = RI->clone();
00620   Pred->getInstList().push_back(NewRet);
00621 
00622   // If the return instruction returns a value, and if the value was a
00623   // PHI node in "BB", propagate the right value into the return.
00624   for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
00625        i != e; ++i) {
00626     Value *V = *i;
00627     Instruction *NewBC = nullptr;
00628     if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
00629       // Return value might be bitcasted. Clone and insert it before the
00630       // return instruction.
00631       V = BCI->getOperand(0);
00632       NewBC = BCI->clone();
00633       Pred->getInstList().insert(NewRet, NewBC);
00634       *i = NewBC;
00635     }
00636     if (PHINode *PN = dyn_cast<PHINode>(V)) {
00637       if (PN->getParent() == BB) {
00638         if (NewBC)
00639           NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
00640         else
00641           *i = PN->getIncomingValueForBlock(Pred);
00642       }
00643     }
00644   }
00645 
00646   // Update any PHI nodes in the returning block to realize that we no
00647   // longer branch to them.
00648   BB->removePredecessor(Pred);
00649   UncondBranch->eraseFromParent();
00650   return cast<ReturnInst>(NewRet);
00651 }
00652 
00653 /// SplitBlockAndInsertIfThen - Split the containing block at the
00654 /// specified instruction - everything before and including SplitBefore stays
00655 /// in the old basic block, and everything after SplitBefore is moved to a
00656 /// new block. The two blocks are connected by a conditional branch
00657 /// (with value of Cmp being the condition).
00658 /// Before:
00659 ///   Head
00660 ///   SplitBefore
00661 ///   Tail
00662 /// After:
00663 ///   Head
00664 ///   if (Cond)
00665 ///     ThenBlock
00666 ///   SplitBefore
00667 ///   Tail
00668 ///
00669 /// If Unreachable is true, then ThenBlock ends with
00670 /// UnreachableInst, otherwise it branches to Tail.
00671 /// Returns the NewBasicBlock's terminator.
00672 
00673 TerminatorInst *llvm::SplitBlockAndInsertIfThen(Value *Cond,
00674                                                 Instruction *SplitBefore,
00675                                                 bool Unreachable,
00676                                                 MDNode *BranchWeights,
00677                                                 DominatorTree *DT) {
00678   BasicBlock *Head = SplitBefore->getParent();
00679   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
00680   TerminatorInst *HeadOldTerm = Head->getTerminator();
00681   LLVMContext &C = Head->getContext();
00682   BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
00683   TerminatorInst *CheckTerm;
00684   if (Unreachable)
00685     CheckTerm = new UnreachableInst(C, ThenBlock);
00686   else
00687     CheckTerm = BranchInst::Create(Tail, ThenBlock);
00688   CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
00689   BranchInst *HeadNewTerm =
00690     BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
00691   HeadNewTerm->setDebugLoc(SplitBefore->getDebugLoc());
00692   HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
00693   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
00694 
00695   if (DT) {
00696     if (DomTreeNode *OldNode = DT->getNode(Head)) {
00697       std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
00698 
00699       DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
00700       for (auto Child : Children)
00701         DT->changeImmediateDominator(Child, NewNode);
00702 
00703       // Head dominates ThenBlock.
00704       DT->addNewBlock(ThenBlock, Head);
00705     }
00706   }
00707 
00708   return CheckTerm;
00709 }
00710 
00711 /// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
00712 /// but also creates the ElseBlock.
00713 /// Before:
00714 ///   Head
00715 ///   SplitBefore
00716 ///   Tail
00717 /// After:
00718 ///   Head
00719 ///   if (Cond)
00720 ///     ThenBlock
00721 ///   else
00722 ///     ElseBlock
00723 ///   SplitBefore
00724 ///   Tail
00725 void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
00726                                          TerminatorInst **ThenTerm,
00727                                          TerminatorInst **ElseTerm,
00728                                          MDNode *BranchWeights) {
00729   BasicBlock *Head = SplitBefore->getParent();
00730   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
00731   TerminatorInst *HeadOldTerm = Head->getTerminator();
00732   LLVMContext &C = Head->getContext();
00733   BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
00734   BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
00735   *ThenTerm = BranchInst::Create(Tail, ThenBlock);
00736   (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
00737   *ElseTerm = BranchInst::Create(Tail, ElseBlock);
00738   (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
00739   BranchInst *HeadNewTerm =
00740     BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
00741   HeadNewTerm->setDebugLoc(SplitBefore->getDebugLoc());
00742   HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
00743   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
00744 }
00745 
00746 
00747 /// GetIfCondition - Given a basic block (BB) with two predecessors,
00748 /// check to see if the merge at this block is due
00749 /// to an "if condition".  If so, return the boolean condition that determines
00750 /// which entry into BB will be taken.  Also, return by references the block
00751 /// that will be entered from if the condition is true, and the block that will
00752 /// be entered if the condition is false.
00753 ///
00754 /// This does no checking to see if the true/false blocks have large or unsavory
00755 /// instructions in them.
00756 Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
00757                              BasicBlock *&IfFalse) {
00758   PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
00759   BasicBlock *Pred1 = nullptr;
00760   BasicBlock *Pred2 = nullptr;
00761 
00762   if (SomePHI) {
00763     if (SomePHI->getNumIncomingValues() != 2)
00764       return nullptr;
00765     Pred1 = SomePHI->getIncomingBlock(0);
00766     Pred2 = SomePHI->getIncomingBlock(1);
00767   } else {
00768     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
00769     if (PI == PE) // No predecessor
00770       return nullptr;
00771     Pred1 = *PI++;
00772     if (PI == PE) // Only one predecessor
00773       return nullptr;
00774     Pred2 = *PI++;
00775     if (PI != PE) // More than two predecessors
00776       return nullptr;
00777   }
00778 
00779   // We can only handle branches.  Other control flow will be lowered to
00780   // branches if possible anyway.
00781   BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
00782   BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
00783   if (!Pred1Br || !Pred2Br)
00784     return nullptr;
00785 
00786   // Eliminate code duplication by ensuring that Pred1Br is conditional if
00787   // either are.
00788   if (Pred2Br->isConditional()) {
00789     // If both branches are conditional, we don't have an "if statement".  In
00790     // reality, we could transform this case, but since the condition will be
00791     // required anyway, we stand no chance of eliminating it, so the xform is
00792     // probably not profitable.
00793     if (Pred1Br->isConditional())
00794       return nullptr;
00795 
00796     std::swap(Pred1, Pred2);
00797     std::swap(Pred1Br, Pred2Br);
00798   }
00799 
00800   if (Pred1Br->isConditional()) {
00801     // The only thing we have to watch out for here is to make sure that Pred2
00802     // doesn't have incoming edges from other blocks.  If it does, the condition
00803     // doesn't dominate BB.
00804     if (!Pred2->getSinglePredecessor())
00805       return nullptr;
00806 
00807     // If we found a conditional branch predecessor, make sure that it branches
00808     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
00809     if (Pred1Br->getSuccessor(0) == BB &&
00810         Pred1Br->getSuccessor(1) == Pred2) {
00811       IfTrue = Pred1;
00812       IfFalse = Pred2;
00813     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
00814                Pred1Br->getSuccessor(1) == BB) {
00815       IfTrue = Pred2;
00816       IfFalse = Pred1;
00817     } else {
00818       // We know that one arm of the conditional goes to BB, so the other must
00819       // go somewhere unrelated, and this must not be an "if statement".
00820       return nullptr;
00821     }
00822 
00823     return Pred1Br->getCondition();
00824   }
00825 
00826   // Ok, if we got here, both predecessors end with an unconditional branch to
00827   // BB.  Don't panic!  If both blocks only have a single (identical)
00828   // predecessor, and THAT is a conditional branch, then we're all ok!
00829   BasicBlock *CommonPred = Pred1->getSinglePredecessor();
00830   if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
00831     return nullptr;
00832 
00833   // Otherwise, if this is a conditional branch, then we can use it!
00834   BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
00835   if (!BI) return nullptr;
00836 
00837   assert(BI->isConditional() && "Two successors but not conditional?");
00838   if (BI->getSuccessor(0) == Pred1) {
00839     IfTrue = Pred1;
00840     IfFalse = Pred2;
00841   } else {
00842     IfTrue = Pred2;
00843     IfFalse = Pred1;
00844   }
00845   return BI->getCondition();
00846 }