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/Function.h"
00017 #include "llvm/Instructions.h"
00018 #include "llvm/Constant.h"
00019 #include "llvm/Type.h"
00020 #include "llvm/Analysis/AliasAnalysis.h"
00021 #include "llvm/Analysis/LoopInfo.h"
00022 #include "llvm/Analysis/Dominators.h"
00023 #include "llvm/Target/TargetData.h"
00024 #include <algorithm>
00025 using namespace llvm;
00026 
00027 /// DeleteDeadBlock - Delete the specified block, which must have no
00028 /// predecessors.
00029 void llvm::DeleteDeadBlock(BasicBlock *BB) {
00030   assert((pred_begin(BB) == pred_end(BB) ||
00031          // Can delete self loop.
00032          BB->getSinglePredecessor() == BB) && "Block is not dead!");
00033   TerminatorInst *BBTerm = BB->getTerminator();
00034   
00035   // Loop through all of our successors and make sure they know that one
00036   // of their predecessors is going away.
00037   for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
00038     BBTerm->getSuccessor(i)->removePredecessor(BB);
00039   
00040   // Zap all the instructions in the block.
00041   while (!BB->empty()) {
00042     Instruction &I = BB->back();
00043     // If this instruction is used, replace uses with an arbitrary value.
00044     // Because control flow can't get here, we don't care what we replace the
00045     // value with.  Note that since this block is unreachable, and all values
00046     // contained within it must dominate their uses, that all uses will
00047     // eventually be removed (they are themselves dead).
00048     if (!I.use_empty())
00049       I.replaceAllUsesWith(UndefValue::get(I.getType()));
00050     BB->getInstList().pop_back();
00051   }
00052   
00053   // Zap the block!
00054   BB->eraseFromParent();
00055 }
00056 
00057 /// FoldSingleEntryPHINodes - We know that BB has one predecessor.  If there are
00058 /// any single-entry PHI nodes in it, fold them away.  This handles the case
00059 /// when all entries to the PHI nodes in a block are guaranteed equal, such as
00060 /// when the block has exactly one predecessor.
00061 void llvm::FoldSingleEntryPHINodes(BasicBlock *BB) {
00062   if (!isa<PHINode>(BB->begin()))
00063     return;
00064   
00065   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
00066     if (PN->getIncomingValue(0) != PN)
00067       PN->replaceAllUsesWith(PN->getIncomingValue(0));
00068     else
00069       PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
00070     PN->eraseFromParent();
00071   }
00072 }
00073 
00074 
00075 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
00076 /// if possible.  The return value indicates success or failure.
00077 bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
00078   pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
00079   // Can't merge the entry block.
00080   if (pred_begin(BB) == pred_end(BB)) return false;
00081   
00082   BasicBlock *PredBB = *PI++;
00083   for (; PI != PE; ++PI)  // Search all predecessors, see if they are all same
00084     if (*PI != PredBB) {
00085       PredBB = 0;       // There are multiple different predecessors...
00086       break;
00087     }
00088   
00089   // Can't merge if there are multiple predecessors.
00090   if (!PredBB) return false;
00091   // Don't break self-loops.
00092   if (PredBB == BB) return false;
00093   // Don't break invokes.
00094   if (isa<InvokeInst>(PredBB->getTerminator())) return false;
00095   
00096   succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
00097   BasicBlock* OnlySucc = BB;
00098   for (; SI != SE; ++SI)
00099     if (*SI != OnlySucc) {
00100       OnlySucc = 0;     // There are multiple distinct successors!
00101       break;
00102     }
00103   
00104   // Can't merge if there are multiple successors.
00105   if (!OnlySucc) return false;
00106 
00107   // Can't merge if there is PHI loop.
00108   for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
00109     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
00110       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00111         if (PN->getIncomingValue(i) == PN)
00112           return false;
00113     } else
00114       break;
00115   }
00116 
00117   // Begin by getting rid of unneeded PHIs.
00118   while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
00119     PN->replaceAllUsesWith(PN->getIncomingValue(0));
00120     BB->getInstList().pop_front();  // Delete the phi node...
00121   }
00122   
00123   // Delete the unconditional branch from the predecessor...
00124   PredBB->getInstList().pop_back();
00125   
00126   // Move all definitions in the successor to the predecessor...
00127   PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
00128   
00129   // Make all PHI nodes that referred to BB now refer to Pred as their
00130   // source...
00131   BB->replaceAllUsesWith(PredBB);
00132   
00133   // Inherit predecessors name if it exists.
00134   if (!PredBB->hasName())
00135     PredBB->takeName(BB);
00136   
00137   // Finally, erase the old block and update dominator info.
00138   if (P) {
00139     if (DominatorTree* DT = P->getAnalysisToUpdate<DominatorTree>()) {
00140       DomTreeNode* DTN = DT->getNode(BB);
00141       DomTreeNode* PredDTN = DT->getNode(PredBB);
00142   
00143       if (DTN) {
00144         SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
00145         for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
00146              DE = Children.end(); DI != DE; ++DI)
00147           DT->changeImmediateDominator(*DI, PredDTN);
00148 
00149         DT->eraseNode(BB);
00150       }
00151     }
00152   }
00153   
00154   BB->eraseFromParent();
00155   
00156   
00157   return true;
00158 }
00159 
00160 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
00161 /// with a value, then remove and delete the original instruction.
00162 ///
00163 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
00164                                 BasicBlock::iterator &BI, Value *V) {
00165   Instruction &I = *BI;
00166   // Replaces all of the uses of the instruction with uses of the value
00167   I.replaceAllUsesWith(V);
00168 
00169   // Make sure to propagate a name if there is one already.
00170   if (I.hasName() && !V->hasName())
00171     V->takeName(&I);
00172 
00173   // Delete the unnecessary instruction now...
00174   BI = BIL.erase(BI);
00175 }
00176 
00177 
00178 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
00179 /// instruction specified by I.  The original instruction is deleted and BI is
00180 /// updated to point to the new instruction.
00181 ///
00182 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
00183                                BasicBlock::iterator &BI, Instruction *I) {
00184   assert(I->getParent() == 0 &&
00185          "ReplaceInstWithInst: Instruction already inserted into basic block!");
00186 
00187   // Insert the new instruction into the basic block...
00188   BasicBlock::iterator New = BIL.insert(BI, I);
00189 
00190   // Replace all uses of the old instruction, and delete it.
00191   ReplaceInstWithValue(BIL, BI, I);
00192 
00193   // Move BI back to point to the newly inserted instruction
00194   BI = New;
00195 }
00196 
00197 /// ReplaceInstWithInst - Replace the instruction specified by From with the
00198 /// instruction specified by To.
00199 ///
00200 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
00201   BasicBlock::iterator BI(From);
00202   ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
00203 }
00204 
00205 /// RemoveSuccessor - Change the specified terminator instruction such that its
00206 /// successor SuccNum no longer exists.  Because this reduces the outgoing
00207 /// degree of the current basic block, the actual terminator instruction itself
00208 /// may have to be changed.  In the case where the last successor of the block 
00209 /// is deleted, a return instruction is inserted in its place which can cause a
00210 /// surprising change in program behavior if it is not expected.
00211 ///
00212 void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
00213   assert(SuccNum < TI->getNumSuccessors() &&
00214          "Trying to remove a nonexistant successor!");
00215 
00216   // If our old successor block contains any PHI nodes, remove the entry in the
00217   // PHI nodes that comes from this branch...
00218   //
00219   BasicBlock *BB = TI->getParent();
00220   TI->getSuccessor(SuccNum)->removePredecessor(BB);
00221 
00222   TerminatorInst *NewTI = 0;
00223   switch (TI->getOpcode()) {
00224   case Instruction::Br:
00225     // If this is a conditional branch... convert to unconditional branch.
00226     if (TI->getNumSuccessors() == 2) {
00227       cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
00228     } else {                    // Otherwise convert to a return instruction...
00229       Value *RetVal = 0;
00230 
00231       // Create a value to return... if the function doesn't return null...
00232       if (BB->getParent()->getReturnType() != Type::VoidTy)
00233         RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
00234 
00235       // Create the return...
00236       NewTI = ReturnInst::Create(RetVal);
00237     }
00238     break;
00239 
00240   case Instruction::Invoke:    // Should convert to call
00241   case Instruction::Switch:    // Should remove entry
00242   default:
00243   case Instruction::Ret:       // Cannot happen, has no successors!
00244     assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
00245     abort();
00246   }
00247 
00248   if (NewTI)   // If it's a different instruction, replace.
00249     ReplaceInstWithInst(TI, NewTI);
00250 }
00251 
00252 /// SplitEdge -  Split the edge connecting specified block. Pass P must 
00253 /// not be NULL. 
00254 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
00255   TerminatorInst *LatchTerm = BB->getTerminator();
00256   unsigned SuccNum = 0;
00257 #ifndef NDEBUG
00258   unsigned e = LatchTerm->getNumSuccessors();
00259 #endif
00260   for (unsigned i = 0; ; ++i) {
00261     assert(i != e && "Didn't find edge?");
00262     if (LatchTerm->getSuccessor(i) == Succ) {
00263       SuccNum = i;
00264       break;
00265     }
00266   }
00267   
00268   // If this is a critical edge, let SplitCriticalEdge do it.
00269   if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
00270     return LatchTerm->getSuccessor(SuccNum);
00271 
00272   // If the edge isn't critical, then BB has a single successor or Succ has a
00273   // single pred.  Split the block.
00274   BasicBlock::iterator SplitPoint;
00275   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
00276     // If the successor only has a single pred, split the top of the successor
00277     // block.
00278     assert(SP == BB && "CFG broken");
00279     SP = NULL;
00280     return SplitBlock(Succ, Succ->begin(), P);
00281   } else {
00282     // Otherwise, if BB has a single successor, split it at the bottom of the
00283     // block.
00284     assert(BB->getTerminator()->getNumSuccessors() == 1 &&
00285            "Should have a single succ!"); 
00286     return SplitBlock(BB, BB->getTerminator(), P);
00287   }
00288 }
00289 
00290 /// SplitBlock - Split the specified block at the specified instruction - every
00291 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
00292 /// to a new block.  The two blocks are joined by an unconditional branch and
00293 /// the loop info is updated.
00294 ///
00295 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
00296   BasicBlock::iterator SplitIt = SplitPt;
00297   while (isa<PHINode>(SplitIt))
00298     ++SplitIt;
00299   BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
00300 
00301   // The new block lives in whichever loop the old one did.
00302   if (LoopInfo* LI = P->getAnalysisToUpdate<LoopInfo>())
00303     if (Loop *L = LI->getLoopFor(Old))
00304       L->addBasicBlockToLoop(New, LI->getBase());
00305 
00306   if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>()) 
00307     {
00308       // Old dominates New. New node domiantes all other nodes dominated by Old.
00309       DomTreeNode *OldNode = DT->getNode(Old);
00310       std::vector<DomTreeNode *> Children;
00311       for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
00312            I != E; ++I) 
00313         Children.push_back(*I);
00314 
00315       DomTreeNode *NewNode =   DT->addNewBlock(New,Old);
00316 
00317       for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
00318              E = Children.end(); I != E; ++I) 
00319         DT->changeImmediateDominator(*I, NewNode);
00320     }
00321 
00322   if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>())
00323     DF->splitBlock(Old);
00324     
00325   return New;
00326 }
00327 
00328 
00329 /// SplitBlockPredecessors - This method transforms BB by introducing a new
00330 /// basic block into the function, and moving some of the predecessors of BB to
00331 /// be predecessors of the new block.  The new predecessors are indicated by the
00332 /// Preds array, which has NumPreds elements in it.  The new block is given a
00333 /// suffix of 'Suffix'.
00334 ///
00335 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
00336 /// DominanceFrontier, but no other analyses.
00337 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB, 
00338                                          BasicBlock *const *Preds,
00339                                          unsigned NumPreds, const char *Suffix,
00340                                          Pass *P) {
00341   // Create new basic block, insert right before the original block.
00342   BasicBlock *NewBB =
00343     BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
00344   
00345   // The new block unconditionally branches to the old block.
00346   BranchInst *BI = BranchInst::Create(BB, NewBB);
00347   
00348   // Move the edges from Preds to point to NewBB instead of BB.
00349   for (unsigned i = 0; i != NumPreds; ++i)
00350     Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
00351   
00352   // Update dominator tree and dominator frontier if available.
00353   DominatorTree *DT = P ? P->getAnalysisToUpdate<DominatorTree>() : 0;
00354   if (DT)
00355     DT->splitBlock(NewBB);
00356   if (DominanceFrontier *DF = P ? P->getAnalysisToUpdate<DominanceFrontier>():0)
00357     DF->splitBlock(NewBB);
00358   AliasAnalysis *AA = P ? P->getAnalysisToUpdate<AliasAnalysis>() : 0;
00359   
00360   
00361   // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
00362   // node becomes an incoming value for BB's phi node.  However, if the Preds
00363   // list is empty, we need to insert dummy entries into the PHI nodes in BB to
00364   // account for the newly created predecessor.
00365   if (NumPreds == 0) {
00366     // Insert dummy values as the incoming value.
00367     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
00368       cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
00369     return NewBB;
00370   }
00371   
00372   // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
00373   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
00374     PHINode *PN = cast<PHINode>(I++);
00375     
00376     // Check to see if all of the values coming in are the same.  If so, we
00377     // don't need to create a new PHI node.
00378     Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
00379     for (unsigned i = 1; i != NumPreds; ++i)
00380       if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
00381         InVal = 0;
00382         break;
00383       }
00384     
00385     if (InVal) {
00386       // If all incoming values for the new PHI would be the same, just don't
00387       // make a new PHI.  Instead, just remove the incoming values from the old
00388       // PHI.
00389       for (unsigned i = 0; i != NumPreds; ++i)
00390         PN->removeIncomingValue(Preds[i], false);
00391     } else {
00392       // If the values coming into the block are not the same, we need a PHI.
00393       // Create the new PHI node, insert it into NewBB at the end of the block
00394       PHINode *NewPHI =
00395         PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
00396       if (AA) AA->copyValue(PN, NewPHI);
00397       
00398       // Move all of the PHI values for 'Preds' to the new PHI.
00399       for (unsigned i = 0; i != NumPreds; ++i) {
00400         Value *V = PN->removeIncomingValue(Preds[i], false);
00401         NewPHI->addIncoming(V, Preds[i]);
00402       }
00403       InVal = NewPHI;
00404     }
00405     
00406     // Add an incoming value to the PHI node in the loop for the preheader
00407     // edge.
00408     PN->addIncoming(InVal, NewBB);
00409     
00410     // Check to see if we can eliminate this phi node.
00411     if (Value *V = PN->hasConstantValue(DT != 0)) {
00412       Instruction *I = dyn_cast<Instruction>(V);
00413       if (!I || DT == 0 || DT->dominates(I, PN)) {
00414         PN->replaceAllUsesWith(V);
00415         if (AA) AA->deleteValue(PN);
00416         PN->eraseFromParent();
00417       }
00418     }
00419   }
00420   
00421   return NewBB;
00422 }
00423 
00424 /// AreEquivalentAddressValues - Test if A and B will obviously have the same
00425 /// value. This includes recognizing that %t0 and %t1 will have the same
00426 /// value in code like this:
00427 ///   %t0 = getelementptr @a, 0, 3
00428 ///   store i32 0, i32* %t0
00429 ///   %t1 = getelementptr @a, 0, 3
00430 ///   %t2 = load i32* %t1
00431 ///
00432 static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
00433   // Test if the values are trivially equivalent.
00434   if (A == B) return true;
00435   
00436   // Test if the values come form identical arithmetic instructions.
00437   if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
00438       isa<PHINode>(A) || isa<GetElementPtrInst>(A))
00439     if (const Instruction *BI = dyn_cast<Instruction>(B))
00440       if (cast<Instruction>(A)->isIdenticalTo(BI))
00441         return true;
00442   
00443   // Otherwise they may not be equivalent.
00444   return false;
00445 }
00446 
00447 /// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
00448 /// instruction before ScanFrom) checking to see if we have the value at the
00449 /// memory address *Ptr locally available within a small number of instructions.
00450 /// If the value is available, return it.
00451 ///
00452 /// If not, return the iterator for the last validated instruction that the 
00453 /// value would be live through.  If we scanned the entire block and didn't find
00454 /// something that invalidates *Ptr or provides it, ScanFrom would be left at
00455 /// begin() and this returns null.  ScanFrom could also be left 
00456 ///
00457 /// MaxInstsToScan specifies the maximum instructions to scan in the block.  If
00458 /// it is set to 0, it will scan the whole block. You can also optionally
00459 /// specify an alias analysis implementation, which makes this more precise.
00460 Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
00461                                       BasicBlock::iterator &ScanFrom,
00462                                       unsigned MaxInstsToScan,
00463                                       AliasAnalysis *AA) {
00464   if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
00465 
00466   // If we're using alias analysis to disambiguate get the size of *Ptr.
00467   unsigned AccessSize = 0;
00468   if (AA) {
00469     const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
00470     AccessSize = AA->getTargetData().getTypeStoreSizeInBits(AccessTy);
00471   }
00472   
00473   while (ScanFrom != ScanBB->begin()) {
00474     // Don't scan huge blocks.
00475     if (MaxInstsToScan-- == 0) return 0;
00476     
00477     Instruction *Inst = --ScanFrom;
00478     
00479     // If this is a load of Ptr, the loaded value is available.
00480     if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
00481       if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
00482         return LI;
00483     
00484     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
00485       // If this is a store through Ptr, the value is available!
00486       if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
00487         return SI->getOperand(0);
00488       
00489       // If Ptr is an alloca and this is a store to a different alloca, ignore
00490       // the store.  This is a trivial form of alias analysis that is important
00491       // for reg2mem'd code.
00492       if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
00493           (isa<AllocaInst>(SI->getOperand(1)) ||
00494            isa<GlobalVariable>(SI->getOperand(1))))
00495         continue;
00496       
00497       // If we have alias analysis and it says the store won't modify the loaded
00498       // value, ignore the store.
00499       if (AA &&
00500           (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
00501         continue;
00502       
00503       // Otherwise the store that may or may not alias the pointer, bail out.
00504       ++ScanFrom;
00505       return 0;
00506     }
00507     
00508     // If this is some other instruction that may clobber Ptr, bail out.
00509     if (Inst->mayWriteToMemory()) {
00510       // If alias analysis claims that it really won't modify the load,
00511       // ignore it.
00512       if (AA &&
00513           (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
00514         continue;
00515       
00516       // May modify the pointer, bail out.
00517       ++ScanFrom;
00518       return 0;
00519     }
00520   }
00521   
00522   // Got to the start of the block, we didn't find it, but are done for this
00523   // block.
00524   return 0;
00525 }



This web site is hosted by the Computer Science Department at the University of Illinois at Urbana-Champaign.