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 = 0;
00072   MemoryDependenceAnalysis *MemDep = 0;
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 = 0;     // 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() == 0 &&
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 = NULL;
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) : 0;
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 = 0;
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>() : 0;
00388   for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
00389     PHINode *PN = cast<PHINode>(I++);
00390 
00391     // Check to see if all of the values coming in are the same.  If so, we
00392     // don't need to create a new PHI node, unless it's needed for LCSSA.
00393     Value *InVal = 0;
00394     if (!HasLoopExit) {
00395       InVal = PN->getIncomingValueForBlock(Preds[0]);
00396       for (unsigned i = 1, e = Preds.size(); i != e; ++i)
00397         if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
00398           InVal = 0;
00399           break;
00400         }
00401     }
00402 
00403     if (InVal) {
00404       // If all incoming values for the new PHI would be the same, just don't
00405       // make a new PHI.  Instead, just remove the incoming values from the old
00406       // PHI.
00407       for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
00408         // Explicitly check the BB index here to handle duplicates in Preds.
00409         int Idx = PN->getBasicBlockIndex(Preds[i]);
00410         if (Idx >= 0)
00411           PN->removeIncomingValue(Idx, false);
00412       }
00413     } else {
00414       // If the values coming into the block are not the same, we need a PHI.
00415       // Create the new PHI node, insert it into NewBB at the end of the block
00416       PHINode *NewPHI =
00417         PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
00418       if (AA) AA->copyValue(PN, NewPHI);
00419 
00420       // Move all of the PHI values for 'Preds' to the new PHI.
00421       for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
00422         Value *V = PN->removeIncomingValue(Preds[i], false);
00423         NewPHI->addIncoming(V, Preds[i]);
00424       }
00425 
00426       InVal = NewPHI;
00427     }
00428 
00429     // Add an incoming value to the PHI node in the loop for the preheader
00430     // edge.
00431     PN->addIncoming(InVal, NewBB);
00432   }
00433 }
00434 
00435 /// SplitBlockPredecessors - This method transforms BB by introducing a new
00436 /// basic block into the function, and moving some of the predecessors of BB to
00437 /// be predecessors of the new block.  The new predecessors are indicated by the
00438 /// Preds array, which has NumPreds elements in it.  The new block is given a
00439 /// suffix of 'Suffix'.
00440 ///
00441 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
00442 /// LoopInfo, and LCCSA but no other analyses. In particular, it does not
00443 /// preserve LoopSimplify (because it's complicated to handle the case where one
00444 /// of the edges being split is an exit of a loop with other exits).
00445 ///
00446 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
00447                                          ArrayRef<BasicBlock*> Preds,
00448                                          const char *Suffix, Pass *P) {
00449   // Create new basic block, insert right before the original block.
00450   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
00451                                          BB->getParent(), BB);
00452 
00453   // The new block unconditionally branches to the old block.
00454   BranchInst *BI = BranchInst::Create(BB, NewBB);
00455 
00456   // Move the edges from Preds to point to NewBB instead of BB.
00457   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
00458     // This is slightly more strict than necessary; the minimum requirement
00459     // is that there be no more than one indirectbr branching to BB. And
00460     // all BlockAddress uses would need to be updated.
00461     assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
00462            "Cannot split an edge from an IndirectBrInst");
00463     Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
00464   }
00465 
00466   // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
00467   // node becomes an incoming value for BB's phi node.  However, if the Preds
00468   // list is empty, we need to insert dummy entries into the PHI nodes in BB to
00469   // account for the newly created predecessor.
00470   if (Preds.size() == 0) {
00471     // Insert dummy values as the incoming value.
00472     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
00473       cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
00474     return NewBB;
00475   }
00476 
00477   // Update DominatorTree, LoopInfo, and LCCSA analysis information.
00478   bool HasLoopExit = false;
00479   UpdateAnalysisInformation(BB, NewBB, Preds, P, HasLoopExit);
00480 
00481   // Update the PHI nodes in BB with the values coming from NewBB.
00482   UpdatePHINodes(BB, NewBB, Preds, BI, P, HasLoopExit);
00483   return NewBB;
00484 }
00485 
00486 /// SplitLandingPadPredecessors - This method transforms the landing pad,
00487 /// OrigBB, by introducing two new basic blocks into the function. One of those
00488 /// new basic blocks gets the predecessors listed in Preds. The other basic
00489 /// block gets the remaining predecessors of OrigBB. The landingpad instruction
00490 /// OrigBB is clone into both of the new basic blocks. The new blocks are given
00491 /// the suffixes 'Suffix1' and 'Suffix2', and are returned in the NewBBs vector.
00492 ///
00493 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
00494 /// DominanceFrontier, LoopInfo, and LCCSA but no other analyses. In particular,
00495 /// it does not preserve LoopSimplify (because it's complicated to handle the
00496 /// case where one of the edges being split is an exit of a loop with other
00497 /// exits).
00498 ///
00499 void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
00500                                        ArrayRef<BasicBlock*> Preds,
00501                                        const char *Suffix1, const char *Suffix2,
00502                                        Pass *P,
00503                                        SmallVectorImpl<BasicBlock*> &NewBBs) {
00504   assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
00505 
00506   // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
00507   // it right before the original block.
00508   BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
00509                                           OrigBB->getName() + Suffix1,
00510                                           OrigBB->getParent(), OrigBB);
00511   NewBBs.push_back(NewBB1);
00512 
00513   // The new block unconditionally branches to the old block.
00514   BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
00515 
00516   // Move the edges from Preds to point to NewBB1 instead of OrigBB.
00517   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
00518     // This is slightly more strict than necessary; the minimum requirement
00519     // is that there be no more than one indirectbr branching to BB. And
00520     // all BlockAddress uses would need to be updated.
00521     assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
00522            "Cannot split an edge from an IndirectBrInst");
00523     Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
00524   }
00525 
00526   // Update DominatorTree, LoopInfo, and LCCSA analysis information.
00527   bool HasLoopExit = false;
00528   UpdateAnalysisInformation(OrigBB, NewBB1, Preds, P, HasLoopExit);
00529 
00530   // Update the PHI nodes in OrigBB with the values coming from NewBB1.
00531   UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, P, HasLoopExit);
00532 
00533   // Move the remaining edges from OrigBB to point to NewBB2.
00534   SmallVector<BasicBlock*, 8> NewBB2Preds;
00535   for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
00536        i != e; ) {
00537     BasicBlock *Pred = *i++;
00538     if (Pred == NewBB1) continue;
00539     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
00540            "Cannot split an edge from an IndirectBrInst");
00541     NewBB2Preds.push_back(Pred);
00542     e = pred_end(OrigBB);
00543   }
00544 
00545   BasicBlock *NewBB2 = 0;
00546   if (!NewBB2Preds.empty()) {
00547     // Create another basic block for the rest of OrigBB's predecessors.
00548     NewBB2 = BasicBlock::Create(OrigBB->getContext(),
00549                                 OrigBB->getName() + Suffix2,
00550                                 OrigBB->getParent(), OrigBB);
00551     NewBBs.push_back(NewBB2);
00552 
00553     // The new block unconditionally branches to the old block.
00554     BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
00555 
00556     // Move the remaining edges from OrigBB to point to NewBB2.
00557     for (SmallVectorImpl<BasicBlock*>::iterator
00558            i = NewBB2Preds.begin(), e = NewBB2Preds.end(); i != e; ++i)
00559       (*i)->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
00560 
00561     // Update DominatorTree, LoopInfo, and LCCSA analysis information.
00562     HasLoopExit = false;
00563     UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, P, HasLoopExit);
00564 
00565     // Update the PHI nodes in OrigBB with the values coming from NewBB2.
00566     UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, P, HasLoopExit);
00567   }
00568 
00569   LandingPadInst *LPad = OrigBB->getLandingPadInst();
00570   Instruction *Clone1 = LPad->clone();
00571   Clone1->setName(Twine("lpad") + Suffix1);
00572   NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
00573 
00574   if (NewBB2) {
00575     Instruction *Clone2 = LPad->clone();
00576     Clone2->setName(Twine("lpad") + Suffix2);
00577     NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
00578 
00579     // Create a PHI node for the two cloned landingpad instructions.
00580     PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
00581     PN->addIncoming(Clone1, NewBB1);
00582     PN->addIncoming(Clone2, NewBB2);
00583     LPad->replaceAllUsesWith(PN);
00584     LPad->eraseFromParent();
00585   } else {
00586     // There is no second clone. Just replace the landing pad with the first
00587     // clone.
00588     LPad->replaceAllUsesWith(Clone1);
00589     LPad->eraseFromParent();
00590   }
00591 }
00592 
00593 /// FoldReturnIntoUncondBranch - This method duplicates the specified return
00594 /// instruction into a predecessor which ends in an unconditional branch. If
00595 /// the return instruction returns a value defined by a PHI, propagate the
00596 /// right value into the return. It returns the new return instruction in the
00597 /// predecessor.
00598 ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
00599                                              BasicBlock *Pred) {
00600   Instruction *UncondBranch = Pred->getTerminator();
00601   // Clone the return and add it to the end of the predecessor.
00602   Instruction *NewRet = RI->clone();
00603   Pred->getInstList().push_back(NewRet);
00604 
00605   // If the return instruction returns a value, and if the value was a
00606   // PHI node in "BB", propagate the right value into the return.
00607   for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
00608        i != e; ++i) {
00609     Value *V = *i;
00610     Instruction *NewBC = 0;
00611     if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
00612       // Return value might be bitcasted. Clone and insert it before the
00613       // return instruction.
00614       V = BCI->getOperand(0);
00615       NewBC = BCI->clone();
00616       Pred->getInstList().insert(NewRet, NewBC);
00617       *i = NewBC;
00618     }
00619     if (PHINode *PN = dyn_cast<PHINode>(V)) {
00620       if (PN->getParent() == BB) {
00621         if (NewBC)
00622           NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
00623         else
00624           *i = PN->getIncomingValueForBlock(Pred);
00625       }
00626     }
00627   }
00628 
00629   // Update any PHI nodes in the returning block to realize that we no
00630   // longer branch to them.
00631   BB->removePredecessor(Pred);
00632   UncondBranch->eraseFromParent();
00633   return cast<ReturnInst>(NewRet);
00634 }
00635 
00636 /// SplitBlockAndInsertIfThen - Split the containing block at the
00637 /// specified instruction - everything before and including SplitBefore stays
00638 /// in the old basic block, and everything after SplitBefore is moved to a
00639 /// new block. The two blocks are connected by a conditional branch
00640 /// (with value of Cmp being the condition).
00641 /// Before:
00642 ///   Head
00643 ///   SplitBefore
00644 ///   Tail
00645 /// After:
00646 ///   Head
00647 ///   if (Cond)
00648 ///     ThenBlock
00649 ///   SplitBefore
00650 ///   Tail
00651 ///
00652 /// If Unreachable is true, then ThenBlock ends with
00653 /// UnreachableInst, otherwise it branches to Tail.
00654 /// Returns the NewBasicBlock's terminator.
00655 
00656 TerminatorInst *llvm::SplitBlockAndInsertIfThen(Value *Cond,
00657                                                 Instruction *SplitBefore,
00658                                                 bool Unreachable,
00659                                                 MDNode *BranchWeights) {
00660   BasicBlock *Head = SplitBefore->getParent();
00661   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
00662   TerminatorInst *HeadOldTerm = Head->getTerminator();
00663   LLVMContext &C = Head->getContext();
00664   BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
00665   TerminatorInst *CheckTerm;
00666   if (Unreachable)
00667     CheckTerm = new UnreachableInst(C, ThenBlock);
00668   else
00669     CheckTerm = BranchInst::Create(Tail, ThenBlock);
00670   CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
00671   BranchInst *HeadNewTerm =
00672     BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
00673   HeadNewTerm->setDebugLoc(SplitBefore->getDebugLoc());
00674   HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
00675   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
00676   return CheckTerm;
00677 }
00678 
00679 /// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
00680 /// but also creates the ElseBlock.
00681 /// Before:
00682 ///   Head
00683 ///   SplitBefore
00684 ///   Tail
00685 /// After:
00686 ///   Head
00687 ///   if (Cond)
00688 ///     ThenBlock
00689 ///   else
00690 ///     ElseBlock
00691 ///   SplitBefore
00692 ///   Tail
00693 void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
00694                                          TerminatorInst **ThenTerm,
00695                                          TerminatorInst **ElseTerm,
00696                                          MDNode *BranchWeights) {
00697   BasicBlock *Head = SplitBefore->getParent();
00698   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
00699   TerminatorInst *HeadOldTerm = Head->getTerminator();
00700   LLVMContext &C = Head->getContext();
00701   BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
00702   BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
00703   *ThenTerm = BranchInst::Create(Tail, ThenBlock);
00704   (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
00705   *ElseTerm = BranchInst::Create(Tail, ElseBlock);
00706   (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
00707   BranchInst *HeadNewTerm =
00708     BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
00709   HeadNewTerm->setDebugLoc(SplitBefore->getDebugLoc());
00710   HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
00711   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
00712 }
00713 
00714 
00715 /// GetIfCondition - Given a basic block (BB) with two predecessors,
00716 /// check to see if the merge at this block is due
00717 /// to an "if condition".  If so, return the boolean condition that determines
00718 /// which entry into BB will be taken.  Also, return by references the block
00719 /// that will be entered from if the condition is true, and the block that will
00720 /// be entered if the condition is false.
00721 ///
00722 /// This does no checking to see if the true/false blocks have large or unsavory
00723 /// instructions in them.
00724 Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
00725                              BasicBlock *&IfFalse) {
00726   PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
00727   BasicBlock *Pred1 = NULL;
00728   BasicBlock *Pred2 = NULL;
00729 
00730   if (SomePHI) {
00731     if (SomePHI->getNumIncomingValues() != 2)
00732       return NULL;
00733     Pred1 = SomePHI->getIncomingBlock(0);
00734     Pred2 = SomePHI->getIncomingBlock(1);
00735   } else {
00736     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
00737     if (PI == PE) // No predecessor
00738       return NULL;
00739     Pred1 = *PI++;
00740     if (PI == PE) // Only one predecessor
00741       return NULL;
00742     Pred2 = *PI++;
00743     if (PI != PE) // More than two predecessors
00744       return NULL;
00745   }
00746 
00747   // We can only handle branches.  Other control flow will be lowered to
00748   // branches if possible anyway.
00749   BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
00750   BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
00751   if (Pred1Br == 0 || Pred2Br == 0)
00752     return 0;
00753 
00754   // Eliminate code duplication by ensuring that Pred1Br is conditional if
00755   // either are.
00756   if (Pred2Br->isConditional()) {
00757     // If both branches are conditional, we don't have an "if statement".  In
00758     // reality, we could transform this case, but since the condition will be
00759     // required anyway, we stand no chance of eliminating it, so the xform is
00760     // probably not profitable.
00761     if (Pred1Br->isConditional())
00762       return 0;
00763 
00764     std::swap(Pred1, Pred2);
00765     std::swap(Pred1Br, Pred2Br);
00766   }
00767 
00768   if (Pred1Br->isConditional()) {
00769     // The only thing we have to watch out for here is to make sure that Pred2
00770     // doesn't have incoming edges from other blocks.  If it does, the condition
00771     // doesn't dominate BB.
00772     if (Pred2->getSinglePredecessor() == 0)
00773       return 0;
00774 
00775     // If we found a conditional branch predecessor, make sure that it branches
00776     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
00777     if (Pred1Br->getSuccessor(0) == BB &&
00778         Pred1Br->getSuccessor(1) == Pred2) {
00779       IfTrue = Pred1;
00780       IfFalse = Pred2;
00781     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
00782                Pred1Br->getSuccessor(1) == BB) {
00783       IfTrue = Pred2;
00784       IfFalse = Pred1;
00785     } else {
00786       // We know that one arm of the conditional goes to BB, so the other must
00787       // go somewhere unrelated, and this must not be an "if statement".
00788       return 0;
00789     }
00790 
00791     return Pred1Br->getCondition();
00792   }
00793 
00794   // Ok, if we got here, both predecessors end with an unconditional branch to
00795   // BB.  Don't panic!  If both blocks only have a single (identical)
00796   // predecessor, and THAT is a conditional branch, then we're all ok!
00797   BasicBlock *CommonPred = Pred1->getSinglePredecessor();
00798   if (CommonPred == 0 || CommonPred != Pred2->getSinglePredecessor())
00799     return 0;
00800 
00801   // Otherwise, if this is a conditional branch, then we can use it!
00802   BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
00803   if (BI == 0) return 0;
00804 
00805   assert(BI->isConditional() && "Two successors but not conditional?");
00806   if (BI->getSuccessor(0) == Pred1) {
00807     IfTrue = Pred1;
00808     IfFalse = Pred2;
00809   } else {
00810     IfTrue = Pred2;
00811     IfFalse = Pred1;
00812   }
00813   return BI->getCondition();
00814 }