BasicBlockUtils.cpp revision a7235ea7245028a0723e8ab7fd011386b3900777
1//===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This family of functions perform manipulations on basic blocks, and
11// instructions contained within basic blocks.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/BasicBlockUtils.h"
16#include "llvm/Function.h"
17#include "llvm/Instructions.h"
18#include "llvm/IntrinsicInst.h"
19#include "llvm/LLVMContext.h"
20#include "llvm/Constant.h"
21#include "llvm/Type.h"
22#include "llvm/Analysis/AliasAnalysis.h"
23#include "llvm/Analysis/LoopInfo.h"
24#include "llvm/Analysis/Dominators.h"
25#include "llvm/Target/TargetData.h"
26#include "llvm/Transforms/Utils/Local.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/ValueHandle.h"
29#include <algorithm>
30using namespace llvm;
31
32/// DeleteDeadBlock - Delete the specified block, which must have no
33/// predecessors.
34void llvm::DeleteDeadBlock(BasicBlock *BB) {
35  assert((pred_begin(BB) == pred_end(BB) ||
36         // Can delete self loop.
37         BB->getSinglePredecessor() == BB) && "Block is not dead!");
38  TerminatorInst *BBTerm = BB->getTerminator();
39
40  // Loop through all of our successors and make sure they know that one
41  // of their predecessors is going away.
42  for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
43    BBTerm->getSuccessor(i)->removePredecessor(BB);
44
45  // Zap all the instructions in the block.
46  while (!BB->empty()) {
47    Instruction &I = BB->back();
48    // If this instruction is used, replace uses with an arbitrary value.
49    // Because control flow can't get here, we don't care what we replace the
50    // value with.  Note that since this block is unreachable, and all values
51    // contained within it must dominate their uses, that all uses will
52    // eventually be removed (they are themselves dead).
53    if (!I.use_empty())
54      I.replaceAllUsesWith(UndefValue::get(I.getType()));
55    BB->getInstList().pop_back();
56  }
57
58  // Zap the block!
59  BB->eraseFromParent();
60}
61
62/// FoldSingleEntryPHINodes - We know that BB has one predecessor.  If there are
63/// any single-entry PHI nodes in it, fold them away.  This handles the case
64/// when all entries to the PHI nodes in a block are guaranteed equal, such as
65/// when the block has exactly one predecessor.
66void llvm::FoldSingleEntryPHINodes(BasicBlock *BB) {
67  if (!isa<PHINode>(BB->begin()))
68    return;
69
70  while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
71    if (PN->getIncomingValue(0) != PN)
72      PN->replaceAllUsesWith(PN->getIncomingValue(0));
73    else
74      PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
75    PN->eraseFromParent();
76  }
77}
78
79
80/// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
81/// is dead. Also recursively delete any operands that become dead as
82/// a result. This includes tracing the def-use list from the PHI to see if
83/// it is ultimately unused or if it reaches an unused cycle.
84void llvm::DeleteDeadPHIs(BasicBlock *BB) {
85  // Recursively deleting a PHI may cause multiple PHIs to be deleted
86  // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
87  SmallVector<WeakVH, 8> PHIs;
88  for (BasicBlock::iterator I = BB->begin();
89       PHINode *PN = dyn_cast<PHINode>(I); ++I)
90    PHIs.push_back(PN);
91
92  for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
93    if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
94      RecursivelyDeleteDeadPHINode(PN);
95}
96
97/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
98/// if possible.  The return value indicates success or failure.
99bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
100  pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
101  // Can't merge the entry block.
102  if (pred_begin(BB) == pred_end(BB)) return false;
103
104  BasicBlock *PredBB = *PI++;
105  for (; PI != PE; ++PI)  // Search all predecessors, see if they are all same
106    if (*PI != PredBB) {
107      PredBB = 0;       // There are multiple different predecessors...
108      break;
109    }
110
111  // Can't merge if there are multiple predecessors.
112  if (!PredBB) return false;
113  // Don't break self-loops.
114  if (PredBB == BB) return false;
115  // Don't break invokes.
116  if (isa<InvokeInst>(PredBB->getTerminator())) return false;
117
118  succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
119  BasicBlock* OnlySucc = BB;
120  for (; SI != SE; ++SI)
121    if (*SI != OnlySucc) {
122      OnlySucc = 0;     // There are multiple distinct successors!
123      break;
124    }
125
126  // Can't merge if there are multiple successors.
127  if (!OnlySucc) return false;
128
129  // Can't merge if there is PHI loop.
130  for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
131    if (PHINode *PN = dyn_cast<PHINode>(BI)) {
132      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
133        if (PN->getIncomingValue(i) == PN)
134          return false;
135    } else
136      break;
137  }
138
139  // Begin by getting rid of unneeded PHIs.
140  while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
141    PN->replaceAllUsesWith(PN->getIncomingValue(0));
142    BB->getInstList().pop_front();  // Delete the phi node...
143  }
144
145  // Delete the unconditional branch from the predecessor...
146  PredBB->getInstList().pop_back();
147
148  // Move all definitions in the successor to the predecessor...
149  PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
150
151  // Make all PHI nodes that referred to BB now refer to Pred as their
152  // source...
153  BB->replaceAllUsesWith(PredBB);
154
155  // Inherit predecessors name if it exists.
156  if (!PredBB->hasName())
157    PredBB->takeName(BB);
158
159  // Finally, erase the old block and update dominator info.
160  if (P) {
161    if (DominatorTree* DT = P->getAnalysisIfAvailable<DominatorTree>()) {
162      DomTreeNode* DTN = DT->getNode(BB);
163      DomTreeNode* PredDTN = DT->getNode(PredBB);
164
165      if (DTN) {
166        SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
167        for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
168             DE = Children.end(); DI != DE; ++DI)
169          DT->changeImmediateDominator(*DI, PredDTN);
170
171        DT->eraseNode(BB);
172      }
173    }
174  }
175
176  BB->eraseFromParent();
177
178
179  return true;
180}
181
182/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
183/// with a value, then remove and delete the original instruction.
184///
185void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
186                                BasicBlock::iterator &BI, Value *V) {
187  Instruction &I = *BI;
188  // Replaces all of the uses of the instruction with uses of the value
189  I.replaceAllUsesWith(V);
190
191  // Make sure to propagate a name if there is one already.
192  if (I.hasName() && !V->hasName())
193    V->takeName(&I);
194
195  // Delete the unnecessary instruction now...
196  BI = BIL.erase(BI);
197}
198
199
200/// ReplaceInstWithInst - Replace the instruction specified by BI with the
201/// instruction specified by I.  The original instruction is deleted and BI is
202/// updated to point to the new instruction.
203///
204void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
205                               BasicBlock::iterator &BI, Instruction *I) {
206  assert(I->getParent() == 0 &&
207         "ReplaceInstWithInst: Instruction already inserted into basic block!");
208
209  // Insert the new instruction into the basic block...
210  BasicBlock::iterator New = BIL.insert(BI, I);
211
212  // Replace all uses of the old instruction, and delete it.
213  ReplaceInstWithValue(BIL, BI, I);
214
215  // Move BI back to point to the newly inserted instruction
216  BI = New;
217}
218
219/// ReplaceInstWithInst - Replace the instruction specified by From with the
220/// instruction specified by To.
221///
222void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
223  BasicBlock::iterator BI(From);
224  ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
225}
226
227/// RemoveSuccessor - Change the specified terminator instruction such that its
228/// successor SuccNum no longer exists.  Because this reduces the outgoing
229/// degree of the current basic block, the actual terminator instruction itself
230/// may have to be changed.  In the case where the last successor of the block
231/// is deleted, a return instruction is inserted in its place which can cause a
232/// surprising change in program behavior if it is not expected.
233///
234void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
235  assert(SuccNum < TI->getNumSuccessors() &&
236         "Trying to remove a nonexistant successor!");
237
238  // If our old successor block contains any PHI nodes, remove the entry in the
239  // PHI nodes that comes from this branch...
240  //
241  BasicBlock *BB = TI->getParent();
242  TI->getSuccessor(SuccNum)->removePredecessor(BB);
243
244  TerminatorInst *NewTI = 0;
245  switch (TI->getOpcode()) {
246  case Instruction::Br:
247    // If this is a conditional branch... convert to unconditional branch.
248    if (TI->getNumSuccessors() == 2) {
249      cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
250    } else {                    // Otherwise convert to a return instruction...
251      Value *RetVal = 0;
252
253      // Create a value to return... if the function doesn't return null...
254      if (BB->getParent()->getReturnType() != Type::VoidTy)
255        RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
256
257      // Create the return...
258      NewTI = ReturnInst::Create(RetVal);
259    }
260    break;
261
262  case Instruction::Invoke:    // Should convert to call
263  case Instruction::Switch:    // Should remove entry
264  default:
265  case Instruction::Ret:       // Cannot happen, has no successors!
266    llvm_unreachable("Unhandled terminator instruction type in RemoveSuccessor!");
267  }
268
269  if (NewTI)   // If it's a different instruction, replace.
270    ReplaceInstWithInst(TI, NewTI);
271}
272
273/// SplitEdge -  Split the edge connecting specified block. Pass P must
274/// not be NULL.
275BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
276  TerminatorInst *LatchTerm = BB->getTerminator();
277  unsigned SuccNum = 0;
278#ifndef NDEBUG
279  unsigned e = LatchTerm->getNumSuccessors();
280#endif
281  for (unsigned i = 0; ; ++i) {
282    assert(i != e && "Didn't find edge?");
283    if (LatchTerm->getSuccessor(i) == Succ) {
284      SuccNum = i;
285      break;
286    }
287  }
288
289  // If this is a critical edge, let SplitCriticalEdge do it.
290  if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
291    return LatchTerm->getSuccessor(SuccNum);
292
293  // If the edge isn't critical, then BB has a single successor or Succ has a
294  // single pred.  Split the block.
295  BasicBlock::iterator SplitPoint;
296  if (BasicBlock *SP = Succ->getSinglePredecessor()) {
297    // If the successor only has a single pred, split the top of the successor
298    // block.
299    assert(SP == BB && "CFG broken");
300    SP = NULL;
301    return SplitBlock(Succ, Succ->begin(), P);
302  } else {
303    // Otherwise, if BB has a single successor, split it at the bottom of the
304    // block.
305    assert(BB->getTerminator()->getNumSuccessors() == 1 &&
306           "Should have a single succ!");
307    return SplitBlock(BB, BB->getTerminator(), P);
308  }
309}
310
311/// SplitBlock - Split the specified block at the specified instruction - every
312/// thing before SplitPt stays in Old and everything starting with SplitPt moves
313/// to a new block.  The two blocks are joined by an unconditional branch and
314/// the loop info is updated.
315///
316BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
317  BasicBlock::iterator SplitIt = SplitPt;
318  while (isa<PHINode>(SplitIt))
319    ++SplitIt;
320  BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
321
322  // The new block lives in whichever loop the old one did.
323  if (LoopInfo* LI = P->getAnalysisIfAvailable<LoopInfo>())
324    if (Loop *L = LI->getLoopFor(Old))
325      L->addBasicBlockToLoop(New, LI->getBase());
326
327  if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>())
328    {
329      // Old dominates New. New node domiantes all other nodes dominated by Old.
330      DomTreeNode *OldNode = DT->getNode(Old);
331      std::vector<DomTreeNode *> Children;
332      for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
333           I != E; ++I)
334        Children.push_back(*I);
335
336      DomTreeNode *NewNode =   DT->addNewBlock(New,Old);
337
338      for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
339             E = Children.end(); I != E; ++I)
340        DT->changeImmediateDominator(*I, NewNode);
341    }
342
343  if (DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>())
344    DF->splitBlock(Old);
345
346  return New;
347}
348
349
350/// SplitBlockPredecessors - This method transforms BB by introducing a new
351/// basic block into the function, and moving some of the predecessors of BB to
352/// be predecessors of the new block.  The new predecessors are indicated by the
353/// Preds array, which has NumPreds elements in it.  The new block is given a
354/// suffix of 'Suffix'.
355///
356/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
357/// DominanceFrontier, but no other analyses.
358BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
359                                         BasicBlock *const *Preds,
360                                         unsigned NumPreds, const char *Suffix,
361                                         Pass *P) {
362  // Create new basic block, insert right before the original block.
363  BasicBlock *NewBB =
364    BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
365
366  // The new block unconditionally branches to the old block.
367  BranchInst *BI = BranchInst::Create(BB, NewBB);
368
369  // Move the edges from Preds to point to NewBB instead of BB.
370  for (unsigned i = 0; i != NumPreds; ++i)
371    Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
372
373  // Update dominator tree and dominator frontier if available.
374  DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0;
375  if (DT)
376    DT->splitBlock(NewBB);
377  if (DominanceFrontier *DF = P ? P->getAnalysisIfAvailable<DominanceFrontier>():0)
378    DF->splitBlock(NewBB);
379  AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
380
381
382  // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
383  // node becomes an incoming value for BB's phi node.  However, if the Preds
384  // list is empty, we need to insert dummy entries into the PHI nodes in BB to
385  // account for the newly created predecessor.
386  if (NumPreds == 0) {
387    // Insert dummy values as the incoming value.
388    for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
389      cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
390    return NewBB;
391  }
392
393  // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
394  for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
395    PHINode *PN = cast<PHINode>(I++);
396
397    // Check to see if all of the values coming in are the same.  If so, we
398    // don't need to create a new PHI node.
399    Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
400    for (unsigned i = 1; i != NumPreds; ++i)
401      if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
402        InVal = 0;
403        break;
404      }
405
406    if (InVal) {
407      // If all incoming values for the new PHI would be the same, just don't
408      // make a new PHI.  Instead, just remove the incoming values from the old
409      // PHI.
410      for (unsigned i = 0; i != NumPreds; ++i)
411        PN->removeIncomingValue(Preds[i], false);
412    } else {
413      // If the values coming into the block are not the same, we need a PHI.
414      // Create the new PHI node, insert it into NewBB at the end of the block
415      PHINode *NewPHI =
416        PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
417      if (AA) AA->copyValue(PN, NewPHI);
418
419      // Move all of the PHI values for 'Preds' to the new PHI.
420      for (unsigned i = 0; i != NumPreds; ++i) {
421        Value *V = PN->removeIncomingValue(Preds[i], false);
422        NewPHI->addIncoming(V, Preds[i]);
423      }
424      InVal = NewPHI;
425    }
426
427    // Add an incoming value to the PHI node in the loop for the preheader
428    // edge.
429    PN->addIncoming(InVal, NewBB);
430
431    // Check to see if we can eliminate this phi node.
432    if (Value *V = PN->hasConstantValue(DT != 0)) {
433      Instruction *I = dyn_cast<Instruction>(V);
434      if (!I || DT == 0 || DT->dominates(I, PN)) {
435        PN->replaceAllUsesWith(V);
436        if (AA) AA->deleteValue(PN);
437        PN->eraseFromParent();
438      }
439    }
440  }
441
442  return NewBB;
443}
444
445/// FindFunctionBackedges - Analyze the specified function to find all of the
446/// loop backedges in the function and return them.  This is a relatively cheap
447/// (compared to computing dominators and loop info) analysis.
448///
449/// The output is added to Result, as pairs of <from,to> edge info.
450void llvm::FindFunctionBackedges(const Function &F,
451     SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
452  const BasicBlock *BB = &F.getEntryBlock();
453  if (succ_begin(BB) == succ_end(BB))
454    return;
455
456  SmallPtrSet<const BasicBlock*, 8> Visited;
457  SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
458  SmallPtrSet<const BasicBlock*, 8> InStack;
459
460  Visited.insert(BB);
461  VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
462  InStack.insert(BB);
463  do {
464    std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
465    const BasicBlock *ParentBB = Top.first;
466    succ_const_iterator &I = Top.second;
467
468    bool FoundNew = false;
469    while (I != succ_end(ParentBB)) {
470      BB = *I++;
471      if (Visited.insert(BB)) {
472        FoundNew = true;
473        break;
474      }
475      // Successor is in VisitStack, it's a back edge.
476      if (InStack.count(BB))
477        Result.push_back(std::make_pair(ParentBB, BB));
478    }
479
480    if (FoundNew) {
481      // Go down one level if there is a unvisited successor.
482      InStack.insert(BB);
483      VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
484    } else {
485      // Go up one level.
486      InStack.erase(VisitStack.pop_back_val().first);
487    }
488  } while (!VisitStack.empty());
489
490
491}
492
493
494
495/// AreEquivalentAddressValues - Test if A and B will obviously have the same
496/// value. This includes recognizing that %t0 and %t1 will have the same
497/// value in code like this:
498///   %t0 = getelementptr \@a, 0, 3
499///   store i32 0, i32* %t0
500///   %t1 = getelementptr \@a, 0, 3
501///   %t2 = load i32* %t1
502///
503static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
504  // Test if the values are trivially equivalent.
505  if (A == B) return true;
506
507  // Test if the values come form identical arithmetic instructions.
508  if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
509      isa<PHINode>(A) || isa<GetElementPtrInst>(A))
510    if (const Instruction *BI = dyn_cast<Instruction>(B))
511      if (cast<Instruction>(A)->isIdenticalTo(BI))
512        return true;
513
514  // Otherwise they may not be equivalent.
515  return false;
516}
517
518/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
519/// instruction before ScanFrom) checking to see if we have the value at the
520/// memory address *Ptr locally available within a small number of instructions.
521/// If the value is available, return it.
522///
523/// If not, return the iterator for the last validated instruction that the
524/// value would be live through.  If we scanned the entire block and didn't find
525/// something that invalidates *Ptr or provides it, ScanFrom would be left at
526/// begin() and this returns null.  ScanFrom could also be left
527///
528/// MaxInstsToScan specifies the maximum instructions to scan in the block.  If
529/// it is set to 0, it will scan the whole block. You can also optionally
530/// specify an alias analysis implementation, which makes this more precise.
531Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
532                                      BasicBlock::iterator &ScanFrom,
533                                      unsigned MaxInstsToScan,
534                                      AliasAnalysis *AA) {
535  if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
536
537  // If we're using alias analysis to disambiguate get the size of *Ptr.
538  unsigned AccessSize = 0;
539  if (AA) {
540    const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
541    AccessSize = AA->getTypeStoreSize(AccessTy);
542  }
543
544  while (ScanFrom != ScanBB->begin()) {
545    // We must ignore debug info directives when counting (otherwise they
546    // would affect codegen).
547    Instruction *Inst = --ScanFrom;
548    if (isa<DbgInfoIntrinsic>(Inst))
549      continue;
550    // We skip pointer-to-pointer bitcasts, which are NOPs.
551    // It is necessary for correctness to skip those that feed into a
552    // llvm.dbg.declare, as these are not present when debugging is off.
553    if (isa<BitCastInst>(Inst) && isa<PointerType>(Inst->getType()))
554      continue;
555
556    // Restore ScanFrom to expected value in case next test succeeds
557    ScanFrom++;
558
559    // Don't scan huge blocks.
560    if (MaxInstsToScan-- == 0) return 0;
561
562    --ScanFrom;
563    // If this is a load of Ptr, the loaded value is available.
564    if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
565      if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
566        return LI;
567
568    if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
569      // If this is a store through Ptr, the value is available!
570      if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
571        return SI->getOperand(0);
572
573      // If Ptr is an alloca and this is a store to a different alloca, ignore
574      // the store.  This is a trivial form of alias analysis that is important
575      // for reg2mem'd code.
576      if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
577          (isa<AllocaInst>(SI->getOperand(1)) ||
578           isa<GlobalVariable>(SI->getOperand(1))))
579        continue;
580
581      // If we have alias analysis and it says the store won't modify the loaded
582      // value, ignore the store.
583      if (AA &&
584          (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
585        continue;
586
587      // Otherwise the store that may or may not alias the pointer, bail out.
588      ++ScanFrom;
589      return 0;
590    }
591
592    // If this is some other instruction that may clobber Ptr, bail out.
593    if (Inst->mayWriteToMemory()) {
594      // If alias analysis claims that it really won't modify the load,
595      // ignore it.
596      if (AA &&
597          (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
598        continue;
599
600      // May modify the pointer, bail out.
601      ++ScanFrom;
602      return 0;
603    }
604  }
605
606  // Got to the start of the block, we didn't find it, but are done for this
607  // block.
608  return 0;
609}
610
611/// CopyPrecedingStopPoint - If I is immediately preceded by a StopPoint,
612/// make a copy of the stoppoint before InsertPos (presumably before copying
613/// or moving I).
614void llvm::CopyPrecedingStopPoint(Instruction *I,
615                                  BasicBlock::iterator InsertPos) {
616  if (I != I->getParent()->begin()) {
617    BasicBlock::iterator BBI = I;  --BBI;
618    if (DbgStopPointInst *DSPI = dyn_cast<DbgStopPointInst>(BBI)) {
619      CallInst *newDSPI = DSPI->clone(I->getContext());
620      newDSPI->insertBefore(InsertPos);
621    }
622  }
623}
624