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 unsigned llvm::SplitAllCriticalEdges(Function &F, Pass *P) {
00269   unsigned NumBroken = 0;
00270   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
00271     TerminatorInst *TI = I->getTerminator();
00272     if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
00273       for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
00274         if (SplitCriticalEdge(TI, i, P))
00275           ++NumBroken;
00276   }
00277   return NumBroken;
00278 }
00279 
00280 /// SplitBlock - Split the specified block at the specified instruction - every
00281 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
00282 /// to a new block.  The two blocks are joined by an unconditional branch and
00283 /// the loop info is updated.
00284 ///
00285 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
00286   BasicBlock::iterator SplitIt = SplitPt;
00287   while (isa<PHINode>(SplitIt) || isa<LandingPadInst>(SplitIt))
00288     ++SplitIt;
00289   BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
00290 
00291   // The new block lives in whichever loop the old one did. This preserves
00292   // LCSSA as well, because we force the split point to be after any PHI nodes.
00293   if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>())
00294     if (Loop *L = LI->getLoopFor(Old))
00295       L->addBasicBlockToLoop(New, LI->getBase());
00296 
00297   if (DominatorTreeWrapperPass *DTWP =
00298           P->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
00299     DominatorTree &DT = DTWP->getDomTree();
00300     // Old dominates New. New node dominates all other nodes dominated by Old.
00301     if (DomTreeNode *OldNode = DT.getNode(Old)) {
00302       std::vector<DomTreeNode *> Children;
00303       for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
00304            I != E; ++I)
00305         Children.push_back(*I);
00306 
00307       DomTreeNode *NewNode = DT.addNewBlock(New, Old);
00308       for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
00309              E = Children.end(); I != E; ++I)
00310         DT.changeImmediateDominator(*I, NewNode);
00311     }
00312   }
00313 
00314   return New;
00315 }
00316 
00317 /// UpdateAnalysisInformation - Update DominatorTree, LoopInfo, and LCCSA
00318 /// analysis information.
00319 static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
00320                                       ArrayRef<BasicBlock *> Preds,
00321                                       Pass *P, bool &HasLoopExit) {
00322   if (!P) return;
00323 
00324   LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>();
00325   Loop *L = LI ? LI->getLoopFor(OldBB) : nullptr;
00326 
00327   // If we need to preserve loop analyses, collect some information about how
00328   // this split will affect loops.
00329   bool IsLoopEntry = !!L;
00330   bool SplitMakesNewLoopHeader = false;
00331   if (LI) {
00332     bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
00333     for (ArrayRef<BasicBlock*>::iterator
00334            i = Preds.begin(), e = Preds.end(); i != e; ++i) {
00335       BasicBlock *Pred = *i;
00336 
00337       // If we need to preserve LCSSA, determine if any of the preds is a loop
00338       // exit.
00339       if (PreserveLCSSA)
00340         if (Loop *PL = LI->getLoopFor(Pred))
00341           if (!PL->contains(OldBB))
00342             HasLoopExit = true;
00343 
00344       // If we need to preserve LoopInfo, note whether any of the preds crosses
00345       // an interesting loop boundary.
00346       if (!L) continue;
00347       if (L->contains(Pred))
00348         IsLoopEntry = false;
00349       else
00350         SplitMakesNewLoopHeader = true;
00351     }
00352   }
00353 
00354   // Update dominator tree if available.
00355   if (DominatorTreeWrapperPass *DTWP =
00356           P->getAnalysisIfAvailable<DominatorTreeWrapperPass>())
00357     DTWP->getDomTree().splitBlock(NewBB);
00358 
00359   if (!L) return;
00360 
00361   if (IsLoopEntry) {
00362     // Add the new block to the nearest enclosing loop (and not an adjacent
00363     // loop). To find this, examine each of the predecessors and determine which
00364     // loops enclose them, and select the most-nested loop which contains the
00365     // loop containing the block being split.
00366     Loop *InnermostPredLoop = nullptr;
00367     for (ArrayRef<BasicBlock*>::iterator
00368            i = Preds.begin(), e = Preds.end(); i != e; ++i) {
00369       BasicBlock *Pred = *i;
00370       if (Loop *PredLoop = LI->getLoopFor(Pred)) {
00371         // Seek a loop which actually contains the block being split (to avoid
00372         // adjacent loops).
00373         while (PredLoop && !PredLoop->contains(OldBB))
00374           PredLoop = PredLoop->getParentLoop();
00375 
00376         // Select the most-nested of these loops which contains the block.
00377         if (PredLoop && PredLoop->contains(OldBB) &&
00378             (!InnermostPredLoop ||
00379              InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
00380           InnermostPredLoop = PredLoop;
00381       }
00382     }
00383 
00384     if (InnermostPredLoop)
00385       InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase());
00386   } else {
00387     L->addBasicBlockToLoop(NewBB, LI->getBase());
00388     if (SplitMakesNewLoopHeader)
00389       L->moveToHeader(NewBB);
00390   }
00391 }
00392 
00393 /// UpdatePHINodes - Update the PHI nodes in OrigBB to include the values coming
00394 /// from NewBB. This also updates AliasAnalysis, if available.
00395 static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
00396                            ArrayRef<BasicBlock*> Preds, BranchInst *BI,
00397                            Pass *P, bool HasLoopExit) {
00398   // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
00399   AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : nullptr;
00400   SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
00401   for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
00402     PHINode *PN = cast<PHINode>(I++);
00403 
00404     // Check to see if all of the values coming in are the same.  If so, we
00405     // don't need to create a new PHI node, unless it's needed for LCSSA.
00406     Value *InVal = nullptr;
00407     if (!HasLoopExit) {
00408       InVal = PN->getIncomingValueForBlock(Preds[0]);
00409       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00410         if (!PredSet.count(PN->getIncomingBlock(i)))
00411           continue;
00412         if (!InVal)
00413           InVal = PN->getIncomingValue(i);
00414         else if (InVal != PN->getIncomingValue(i)) {
00415           InVal = nullptr;
00416           break;
00417         }
00418       }
00419     }
00420 
00421     if (InVal) {
00422       // If all incoming values for the new PHI would be the same, just don't
00423       // make a new PHI.  Instead, just remove the incoming values from the old
00424       // PHI.
00425 
00426       // NOTE! This loop walks backwards for a reason! First off, this minimizes
00427       // the cost of removal if we end up removing a large number of values, and
00428       // second off, this ensures that the indices for the incoming values
00429       // aren't invalidated when we remove one.
00430       for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
00431         if (PredSet.count(PN->getIncomingBlock(i)))
00432           PN->removeIncomingValue(i, false);
00433 
00434       // Add an incoming value to the PHI node in the loop for the preheader
00435       // edge.
00436       PN->addIncoming(InVal, NewBB);
00437       continue;
00438     }
00439 
00440     // If the values coming into the block are not the same, we need a new
00441     // PHI.
00442     // Create the new PHI node, insert it into NewBB at the end of the block
00443     PHINode *NewPHI =
00444         PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
00445     if (AA)
00446       AA->copyValue(PN, NewPHI);
00447 
00448     // NOTE! This loop walks backwards for a reason! First off, this minimizes
00449     // the cost of removal if we end up removing a large number of values, and
00450     // second off, this ensures that the indices for the incoming values aren't
00451     // invalidated when we remove one.
00452     for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
00453       BasicBlock *IncomingBB = PN->getIncomingBlock(i);
00454       if (PredSet.count(IncomingBB)) {
00455         Value *V = PN->removeIncomingValue(i, false);
00456         NewPHI->addIncoming(V, IncomingBB);
00457       }
00458     }
00459 
00460     PN->addIncoming(NewPHI, NewBB);
00461   }
00462 }
00463 
00464 /// SplitBlockPredecessors - This method transforms BB by introducing a new
00465 /// basic block into the function, and moving some of the predecessors of BB to
00466 /// be predecessors of the new block.  The new predecessors are indicated by the
00467 /// Preds array, which has NumPreds elements in it.  The new block is given a
00468 /// suffix of 'Suffix'.
00469 ///
00470 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
00471 /// LoopInfo, and LCCSA but no other analyses. In particular, it does not
00472 /// preserve LoopSimplify (because it's complicated to handle the case where one
00473 /// of the edges being split is an exit of a loop with other exits).
00474 ///
00475 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
00476                                          ArrayRef<BasicBlock*> Preds,
00477                                          const char *Suffix, Pass *P) {
00478   // Create new basic block, insert right before the original block.
00479   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
00480                                          BB->getParent(), BB);
00481 
00482   // The new block unconditionally branches to the old block.
00483   BranchInst *BI = BranchInst::Create(BB, NewBB);
00484 
00485   // Move the edges from Preds to point to NewBB instead of BB.
00486   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
00487     // This is slightly more strict than necessary; the minimum requirement
00488     // is that there be no more than one indirectbr branching to BB. And
00489     // all BlockAddress uses would need to be updated.
00490     assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
00491            "Cannot split an edge from an IndirectBrInst");
00492     Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
00493   }
00494 
00495   // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
00496   // node becomes an incoming value for BB's phi node.  However, if the Preds
00497   // list is empty, we need to insert dummy entries into the PHI nodes in BB to
00498   // account for the newly created predecessor.
00499   if (Preds.size() == 0) {
00500     // Insert dummy values as the incoming value.
00501     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
00502       cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
00503     return NewBB;
00504   }
00505 
00506   // Update DominatorTree, LoopInfo, and LCCSA analysis information.
00507   bool HasLoopExit = false;
00508   UpdateAnalysisInformation(BB, NewBB, Preds, P, HasLoopExit);
00509 
00510   // Update the PHI nodes in BB with the values coming from NewBB.
00511   UpdatePHINodes(BB, NewBB, Preds, BI, P, HasLoopExit);
00512   return NewBB;
00513 }
00514 
00515 /// SplitLandingPadPredecessors - This method transforms the landing pad,
00516 /// OrigBB, by introducing two new basic blocks into the function. One of those
00517 /// new basic blocks gets the predecessors listed in Preds. The other basic
00518 /// block gets the remaining predecessors of OrigBB. The landingpad instruction
00519 /// OrigBB is clone into both of the new basic blocks. The new blocks are given
00520 /// the suffixes 'Suffix1' and 'Suffix2', and are returned in the NewBBs vector.
00521 ///
00522 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
00523 /// DominanceFrontier, LoopInfo, and LCCSA but no other analyses. In particular,
00524 /// it does not preserve LoopSimplify (because it's complicated to handle the
00525 /// case where one of the edges being split is an exit of a loop with other
00526 /// exits).
00527 ///
00528 void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
00529                                        ArrayRef<BasicBlock*> Preds,
00530                                        const char *Suffix1, const char *Suffix2,
00531                                        Pass *P,
00532                                        SmallVectorImpl<BasicBlock*> &NewBBs) {
00533   assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
00534 
00535   // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
00536   // it right before the original block.
00537   BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
00538                                           OrigBB->getName() + Suffix1,
00539                                           OrigBB->getParent(), OrigBB);
00540   NewBBs.push_back(NewBB1);
00541 
00542   // The new block unconditionally branches to the old block.
00543   BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
00544 
00545   // Move the edges from Preds to point to NewBB1 instead of OrigBB.
00546   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
00547     // This is slightly more strict than necessary; the minimum requirement
00548     // is that there be no more than one indirectbr branching to BB. And
00549     // all BlockAddress uses would need to be updated.
00550     assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
00551            "Cannot split an edge from an IndirectBrInst");
00552     Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
00553   }
00554 
00555   // Update DominatorTree, LoopInfo, and LCCSA analysis information.
00556   bool HasLoopExit = false;
00557   UpdateAnalysisInformation(OrigBB, NewBB1, Preds, P, HasLoopExit);
00558 
00559   // Update the PHI nodes in OrigBB with the values coming from NewBB1.
00560   UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, P, HasLoopExit);
00561 
00562   // Move the remaining edges from OrigBB to point to NewBB2.
00563   SmallVector<BasicBlock*, 8> NewBB2Preds;
00564   for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
00565        i != e; ) {
00566     BasicBlock *Pred = *i++;
00567     if (Pred == NewBB1) continue;
00568     assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
00569            "Cannot split an edge from an IndirectBrInst");
00570     NewBB2Preds.push_back(Pred);
00571     e = pred_end(OrigBB);
00572   }
00573 
00574   BasicBlock *NewBB2 = nullptr;
00575   if (!NewBB2Preds.empty()) {
00576     // Create another basic block for the rest of OrigBB's predecessors.
00577     NewBB2 = BasicBlock::Create(OrigBB->getContext(),
00578                                 OrigBB->getName() + Suffix2,
00579                                 OrigBB->getParent(), OrigBB);
00580     NewBBs.push_back(NewBB2);
00581 
00582     // The new block unconditionally branches to the old block.
00583     BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
00584 
00585     // Move the remaining edges from OrigBB to point to NewBB2.
00586     for (SmallVectorImpl<BasicBlock*>::iterator
00587            i = NewBB2Preds.begin(), e = NewBB2Preds.end(); i != e; ++i)
00588       (*i)->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
00589 
00590     // Update DominatorTree, LoopInfo, and LCCSA analysis information.
00591     HasLoopExit = false;
00592     UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, P, HasLoopExit);
00593 
00594     // Update the PHI nodes in OrigBB with the values coming from NewBB2.
00595     UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, P, HasLoopExit);
00596   }
00597 
00598   LandingPadInst *LPad = OrigBB->getLandingPadInst();
00599   Instruction *Clone1 = LPad->clone();
00600   Clone1->setName(Twine("lpad") + Suffix1);
00601   NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
00602 
00603   if (NewBB2) {
00604     Instruction *Clone2 = LPad->clone();
00605     Clone2->setName(Twine("lpad") + Suffix2);
00606     NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
00607 
00608     // Create a PHI node for the two cloned landingpad instructions.
00609     PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
00610     PN->addIncoming(Clone1, NewBB1);
00611     PN->addIncoming(Clone2, NewBB2);
00612     LPad->replaceAllUsesWith(PN);
00613     LPad->eraseFromParent();
00614   } else {
00615     // There is no second clone. Just replace the landing pad with the first
00616     // clone.
00617     LPad->replaceAllUsesWith(Clone1);
00618     LPad->eraseFromParent();
00619   }
00620 }
00621 
00622 /// FoldReturnIntoUncondBranch - This method duplicates the specified return
00623 /// instruction into a predecessor which ends in an unconditional branch. If
00624 /// the return instruction returns a value defined by a PHI, propagate the
00625 /// right value into the return. It returns the new return instruction in the
00626 /// predecessor.
00627 ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
00628                                              BasicBlock *Pred) {
00629   Instruction *UncondBranch = Pred->getTerminator();
00630   // Clone the return and add it to the end of the predecessor.
00631   Instruction *NewRet = RI->clone();
00632   Pred->getInstList().push_back(NewRet);
00633 
00634   // If the return instruction returns a value, and if the value was a
00635   // PHI node in "BB", propagate the right value into the return.
00636   for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
00637        i != e; ++i) {
00638     Value *V = *i;
00639     Instruction *NewBC = nullptr;
00640     if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
00641       // Return value might be bitcasted. Clone and insert it before the
00642       // return instruction.
00643       V = BCI->getOperand(0);
00644       NewBC = BCI->clone();
00645       Pred->getInstList().insert(NewRet, NewBC);
00646       *i = NewBC;
00647     }
00648     if (PHINode *PN = dyn_cast<PHINode>(V)) {
00649       if (PN->getParent() == BB) {
00650         if (NewBC)
00651           NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
00652         else
00653           *i = PN->getIncomingValueForBlock(Pred);
00654       }
00655     }
00656   }
00657 
00658   // Update any PHI nodes in the returning block to realize that we no
00659   // longer branch to them.
00660   BB->removePredecessor(Pred);
00661   UncondBranch->eraseFromParent();
00662   return cast<ReturnInst>(NewRet);
00663 }
00664 
00665 /// SplitBlockAndInsertIfThen - Split the containing block at the
00666 /// specified instruction - everything before and including SplitBefore stays
00667 /// in the old basic block, and everything after SplitBefore is moved to a
00668 /// new block. The two blocks are connected by a conditional branch
00669 /// (with value of Cmp being the condition).
00670 /// Before:
00671 ///   Head
00672 ///   SplitBefore
00673 ///   Tail
00674 /// After:
00675 ///   Head
00676 ///   if (Cond)
00677 ///     ThenBlock
00678 ///   SplitBefore
00679 ///   Tail
00680 ///
00681 /// If Unreachable is true, then ThenBlock ends with
00682 /// UnreachableInst, otherwise it branches to Tail.
00683 /// Returns the NewBasicBlock's terminator.
00684 
00685 TerminatorInst *llvm::SplitBlockAndInsertIfThen(Value *Cond,
00686                                                 Instruction *SplitBefore,
00687                                                 bool Unreachable,
00688                                                 MDNode *BranchWeights,
00689                                                 DominatorTree *DT) {
00690   BasicBlock *Head = SplitBefore->getParent();
00691   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
00692   TerminatorInst *HeadOldTerm = Head->getTerminator();
00693   LLVMContext &C = Head->getContext();
00694   BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
00695   TerminatorInst *CheckTerm;
00696   if (Unreachable)
00697     CheckTerm = new UnreachableInst(C, ThenBlock);
00698   else
00699     CheckTerm = BranchInst::Create(Tail, ThenBlock);
00700   CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
00701   BranchInst *HeadNewTerm =
00702     BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
00703   HeadNewTerm->setDebugLoc(SplitBefore->getDebugLoc());
00704   HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
00705   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
00706 
00707   if (DT) {
00708     if (DomTreeNode *OldNode = DT->getNode(Head)) {
00709       std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
00710 
00711       DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
00712       for (auto Child : Children)
00713         DT->changeImmediateDominator(Child, NewNode);
00714 
00715       // Head dominates ThenBlock.
00716       DT->addNewBlock(ThenBlock, Head);
00717     }
00718   }
00719 
00720   return CheckTerm;
00721 }
00722 
00723 /// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
00724 /// but also creates the ElseBlock.
00725 /// Before:
00726 ///   Head
00727 ///   SplitBefore
00728 ///   Tail
00729 /// After:
00730 ///   Head
00731 ///   if (Cond)
00732 ///     ThenBlock
00733 ///   else
00734 ///     ElseBlock
00735 ///   SplitBefore
00736 ///   Tail
00737 void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
00738                                          TerminatorInst **ThenTerm,
00739                                          TerminatorInst **ElseTerm,
00740                                          MDNode *BranchWeights) {
00741   BasicBlock *Head = SplitBefore->getParent();
00742   BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
00743   TerminatorInst *HeadOldTerm = Head->getTerminator();
00744   LLVMContext &C = Head->getContext();
00745   BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
00746   BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
00747   *ThenTerm = BranchInst::Create(Tail, ThenBlock);
00748   (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
00749   *ElseTerm = BranchInst::Create(Tail, ElseBlock);
00750   (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
00751   BranchInst *HeadNewTerm =
00752     BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
00753   HeadNewTerm->setDebugLoc(SplitBefore->getDebugLoc());
00754   HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
00755   ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
00756 }
00757 
00758 
00759 /// GetIfCondition - Given a basic block (BB) with two predecessors,
00760 /// check to see if the merge at this block is due
00761 /// to an "if condition".  If so, return the boolean condition that determines
00762 /// which entry into BB will be taken.  Also, return by references the block
00763 /// that will be entered from if the condition is true, and the block that will
00764 /// be entered if the condition is false.
00765 ///
00766 /// This does no checking to see if the true/false blocks have large or unsavory
00767 /// instructions in them.
00768 Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
00769                              BasicBlock *&IfFalse) {
00770   PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
00771   BasicBlock *Pred1 = nullptr;
00772   BasicBlock *Pred2 = nullptr;
00773 
00774   if (SomePHI) {
00775     if (SomePHI->getNumIncomingValues() != 2)
00776       return nullptr;
00777     Pred1 = SomePHI->getIncomingBlock(0);
00778     Pred2 = SomePHI->getIncomingBlock(1);
00779   } else {
00780     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
00781     if (PI == PE) // No predecessor
00782       return nullptr;
00783     Pred1 = *PI++;
00784     if (PI == PE) // Only one predecessor
00785       return nullptr;
00786     Pred2 = *PI++;
00787     if (PI != PE) // More than two predecessors
00788       return nullptr;
00789   }
00790 
00791   // We can only handle branches.  Other control flow will be lowered to
00792   // branches if possible anyway.
00793   BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
00794   BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
00795   if (!Pred1Br || !Pred2Br)
00796     return nullptr;
00797 
00798   // Eliminate code duplication by ensuring that Pred1Br is conditional if
00799   // either are.
00800   if (Pred2Br->isConditional()) {
00801     // If both branches are conditional, we don't have an "if statement".  In
00802     // reality, we could transform this case, but since the condition will be
00803     // required anyway, we stand no chance of eliminating it, so the xform is
00804     // probably not profitable.
00805     if (Pred1Br->isConditional())
00806       return nullptr;
00807 
00808     std::swap(Pred1, Pred2);
00809     std::swap(Pred1Br, Pred2Br);
00810   }
00811 
00812   if (Pred1Br->isConditional()) {
00813     // The only thing we have to watch out for here is to make sure that Pred2
00814     // doesn't have incoming edges from other blocks.  If it does, the condition
00815     // doesn't dominate BB.
00816     if (!Pred2->getSinglePredecessor())
00817       return nullptr;
00818 
00819     // If we found a conditional branch predecessor, make sure that it branches
00820     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
00821     if (Pred1Br->getSuccessor(0) == BB &&
00822         Pred1Br->getSuccessor(1) == Pred2) {
00823       IfTrue = Pred1;
00824       IfFalse = Pred2;
00825     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
00826                Pred1Br->getSuccessor(1) == BB) {
00827       IfTrue = Pred2;
00828       IfFalse = Pred1;
00829     } else {
00830       // We know that one arm of the conditional goes to BB, so the other must
00831       // go somewhere unrelated, and this must not be an "if statement".
00832       return nullptr;
00833     }
00834 
00835     return Pred1Br->getCondition();
00836   }
00837 
00838   // Ok, if we got here, both predecessors end with an unconditional branch to
00839   // BB.  Don't panic!  If both blocks only have a single (identical)
00840   // predecessor, and THAT is a conditional branch, then we're all ok!
00841   BasicBlock *CommonPred = Pred1->getSinglePredecessor();
00842   if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
00843     return nullptr;
00844 
00845   // Otherwise, if this is a conditional branch, then we can use it!
00846   BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
00847   if (!BI) return nullptr;
00848 
00849   assert(BI->isConditional() && "Two successors but not conditional?");
00850   if (BI->getSuccessor(0) == Pred1) {
00851     IfTrue = Pred1;
00852     IfFalse = Pred2;
00853   } else {
00854     IfTrue = Pred2;
00855     IfFalse = Pred1;
00856   }
00857   return BI->getCondition();
00858 }