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