GlobalsModRef.cpp revision 204642
1193323Sed//===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This simple pass provides alias and mod/ref information for global values
11193323Sed// that do not have their address taken, and keeps track of whether functions
12193323Sed// read or write memory (are "pure").  For this simple (but very common) case,
13193323Sed// we can provide pretty accurate and useful information.
14193323Sed//
15193323Sed//===----------------------------------------------------------------------===//
16193323Sed
17193323Sed#define DEBUG_TYPE "globalsmodref-aa"
18193323Sed#include "llvm/Analysis/Passes.h"
19193323Sed#include "llvm/Module.h"
20193323Sed#include "llvm/Pass.h"
21193323Sed#include "llvm/Instructions.h"
22193323Sed#include "llvm/Constants.h"
23193323Sed#include "llvm/DerivedTypes.h"
24193323Sed#include "llvm/Analysis/AliasAnalysis.h"
25193323Sed#include "llvm/Analysis/CallGraph.h"
26198892Srdivacky#include "llvm/Analysis/MemoryBuiltins.h"
27193323Sed#include "llvm/Support/CommandLine.h"
28193323Sed#include "llvm/Support/InstIterator.h"
29193323Sed#include "llvm/ADT/Statistic.h"
30193323Sed#include "llvm/ADT/SCCIterator.h"
31193323Sed#include <set>
32193323Sedusing namespace llvm;
33193323Sed
34193323SedSTATISTIC(NumNonAddrTakenGlobalVars,
35193323Sed          "Number of global vars without address taken");
36193323SedSTATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken");
37193323SedSTATISTIC(NumNoMemFunctions, "Number of functions that do not access memory");
38193323SedSTATISTIC(NumReadMemFunctions, "Number of functions that only read memory");
39193323SedSTATISTIC(NumIndirectGlobalVars, "Number of indirect global objects");
40193323Sed
41193323Sednamespace {
42193323Sed  /// FunctionRecord - One instance of this structure is stored for every
43193323Sed  /// function in the program.  Later, the entries for these functions are
44193323Sed  /// removed if the function is found to call an external function (in which
45193323Sed  /// case we know nothing about it.
46198892Srdivacky  struct FunctionRecord {
47193323Sed    /// GlobalInfo - Maintain mod/ref info for all of the globals without
48193323Sed    /// addresses taken that are read or written (transitively) by this
49193323Sed    /// function.
50193323Sed    std::map<GlobalValue*, unsigned> GlobalInfo;
51193323Sed
52193323Sed    /// MayReadAnyGlobal - May read global variables, but it is not known which.
53193323Sed    bool MayReadAnyGlobal;
54193323Sed
55193323Sed    unsigned getInfoForGlobal(GlobalValue *GV) const {
56193323Sed      unsigned Effect = MayReadAnyGlobal ? AliasAnalysis::Ref : 0;
57193323Sed      std::map<GlobalValue*, unsigned>::const_iterator I = GlobalInfo.find(GV);
58193323Sed      if (I != GlobalInfo.end())
59193323Sed        Effect |= I->second;
60193323Sed      return Effect;
61193323Sed    }
62193323Sed
63193323Sed    /// FunctionEffect - Capture whether or not this function reads or writes to
64193323Sed    /// ANY memory.  If not, we can do a lot of aggressive analysis on it.
65193323Sed    unsigned FunctionEffect;
66193323Sed
67193323Sed    FunctionRecord() : MayReadAnyGlobal (false), FunctionEffect(0) {}
68193323Sed  };
69193323Sed
70193323Sed  /// GlobalsModRef - The actual analysis pass.
71198892Srdivacky  class GlobalsModRef : public ModulePass, public AliasAnalysis {
72193323Sed    /// NonAddressTakenGlobals - The globals that do not have their addresses
73193323Sed    /// taken.
74193323Sed    std::set<GlobalValue*> NonAddressTakenGlobals;
75193323Sed
76193323Sed    /// IndirectGlobals - The memory pointed to by this global is known to be
77193323Sed    /// 'owned' by the global.
78193323Sed    std::set<GlobalValue*> IndirectGlobals;
79193323Sed
80193323Sed    /// AllocsForIndirectGlobals - If an instruction allocates memory for an
81193323Sed    /// indirect global, this map indicates which one.
82193323Sed    std::map<Value*, GlobalValue*> AllocsForIndirectGlobals;
83193323Sed
84193323Sed    /// FunctionInfo - For each function, keep track of what globals are
85193323Sed    /// modified or read.
86193323Sed    std::map<Function*, FunctionRecord> FunctionInfo;
87193323Sed
88193323Sed  public:
89193323Sed    static char ID;
90193323Sed    GlobalsModRef() : ModulePass(&ID) {}
91193323Sed
92193323Sed    bool runOnModule(Module &M) {
93193323Sed      InitializeAliasAnalysis(this);                 // set up super class
94193323Sed      AnalyzeGlobals(M);                          // find non-addr taken globals
95193323Sed      AnalyzeCallGraph(getAnalysis<CallGraph>(), M); // Propagate on CG
96193323Sed      return false;
97193323Sed    }
98193323Sed
99193323Sed    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
100193323Sed      AliasAnalysis::getAnalysisUsage(AU);
101193323Sed      AU.addRequired<CallGraph>();
102193323Sed      AU.setPreservesAll();                         // Does not transform code
103193323Sed    }
104193323Sed
105193323Sed    //------------------------------------------------
106193323Sed    // Implement the AliasAnalysis API
107193323Sed    //
108193323Sed    AliasResult alias(const Value *V1, unsigned V1Size,
109193323Sed                      const Value *V2, unsigned V2Size);
110193323Sed    ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
111193323Sed    ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
112193323Sed      return AliasAnalysis::getModRefInfo(CS1,CS2);
113193323Sed    }
114193323Sed
115193323Sed    /// getModRefBehavior - Return the behavior of the specified function if
116193323Sed    /// called from the specified call site.  The call site may be null in which
117193323Sed    /// case the most generic behavior of this function should be returned.
118193323Sed    ModRefBehavior getModRefBehavior(Function *F,
119193323Sed                                         std::vector<PointerAccessInfo> *Info) {
120193323Sed      if (FunctionRecord *FR = getFunctionInfo(F)) {
121193323Sed        if (FR->FunctionEffect == 0)
122193323Sed          return DoesNotAccessMemory;
123193323Sed        else if ((FR->FunctionEffect & Mod) == 0)
124193323Sed          return OnlyReadsMemory;
125193323Sed      }
126193323Sed      return AliasAnalysis::getModRefBehavior(F, Info);
127193323Sed    }
128193323Sed
129193323Sed    /// getModRefBehavior - Return the behavior of the specified function if
130193323Sed    /// called from the specified call site.  The call site may be null in which
131193323Sed    /// case the most generic behavior of this function should be returned.
132193323Sed    ModRefBehavior getModRefBehavior(CallSite CS,
133193323Sed                                         std::vector<PointerAccessInfo> *Info) {
134193323Sed      Function* F = CS.getCalledFunction();
135193323Sed      if (!F) return AliasAnalysis::getModRefBehavior(CS, Info);
136193323Sed      if (FunctionRecord *FR = getFunctionInfo(F)) {
137193323Sed        if (FR->FunctionEffect == 0)
138193323Sed          return DoesNotAccessMemory;
139193323Sed        else if ((FR->FunctionEffect & Mod) == 0)
140193323Sed          return OnlyReadsMemory;
141193323Sed      }
142193323Sed      return AliasAnalysis::getModRefBehavior(CS, Info);
143193323Sed    }
144193323Sed
145193323Sed    virtual void deleteValue(Value *V);
146193323Sed    virtual void copyValue(Value *From, Value *To);
147193323Sed
148202878Srdivacky    /// getAdjustedAnalysisPointer - This method is used when a pass implements
149202878Srdivacky    /// an analysis interface through multiple inheritance.  If needed, it
150202878Srdivacky    /// should override this to adjust the this pointer as needed for the
151202878Srdivacky    /// specified pass info.
152202878Srdivacky    virtual void *getAdjustedAnalysisPointer(const PassInfo *PI) {
153202878Srdivacky      if (PI->isPassID(&AliasAnalysis::ID))
154202878Srdivacky        return (AliasAnalysis*)this;
155202878Srdivacky      return this;
156202878Srdivacky    }
157202878Srdivacky
158193323Sed  private:
159193323Sed    /// getFunctionInfo - Return the function info for the function, or null if
160193323Sed    /// we don't have anything useful to say about it.
161193323Sed    FunctionRecord *getFunctionInfo(Function *F) {
162193323Sed      std::map<Function*, FunctionRecord>::iterator I = FunctionInfo.find(F);
163193323Sed      if (I != FunctionInfo.end())
164193323Sed        return &I->second;
165193323Sed      return 0;
166193323Sed    }
167193323Sed
168193323Sed    void AnalyzeGlobals(Module &M);
169193323Sed    void AnalyzeCallGraph(CallGraph &CG, Module &M);
170193323Sed    bool AnalyzeUsesOfPointer(Value *V, std::vector<Function*> &Readers,
171193323Sed                              std::vector<Function*> &Writers,
172193323Sed                              GlobalValue *OkayStoreDest = 0);
173193323Sed    bool AnalyzeIndirectGlobalMemory(GlobalValue *GV);
174193323Sed  };
175193323Sed}
176193323Sed
177193323Sedchar GlobalsModRef::ID = 0;
178193323Sedstatic RegisterPass<GlobalsModRef>
179193323SedX("globalsmodref-aa", "Simple mod/ref analysis for globals", false, true);
180193323Sedstatic RegisterAnalysisGroup<AliasAnalysis> Y(X);
181193323Sed
182193323SedPass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); }
183193323Sed
184193323Sed/// AnalyzeGlobals - Scan through the users of all of the internal
185193323Sed/// GlobalValue's in the program.  If none of them have their "address taken"
186193323Sed/// (really, their address passed to something nontrivial), record this fact,
187193323Sed/// and record the functions that they are used directly in.
188193323Sedvoid GlobalsModRef::AnalyzeGlobals(Module &M) {
189193323Sed  std::vector<Function*> Readers, Writers;
190193323Sed  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
191193323Sed    if (I->hasLocalLinkage()) {
192193323Sed      if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
193193323Sed        // Remember that we are tracking this global.
194193323Sed        NonAddressTakenGlobals.insert(I);
195193323Sed        ++NumNonAddrTakenFunctions;
196193323Sed      }
197193323Sed      Readers.clear(); Writers.clear();
198193323Sed    }
199193323Sed
200193323Sed  for (Module::global_iterator I = M.global_begin(), E = M.global_end();
201193323Sed       I != E; ++I)
202193323Sed    if (I->hasLocalLinkage()) {
203193323Sed      if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
204193323Sed        // Remember that we are tracking this global, and the mod/ref fns
205193323Sed        NonAddressTakenGlobals.insert(I);
206193323Sed
207193323Sed        for (unsigned i = 0, e = Readers.size(); i != e; ++i)
208193323Sed          FunctionInfo[Readers[i]].GlobalInfo[I] |= Ref;
209193323Sed
210193323Sed        if (!I->isConstant())  // No need to keep track of writers to constants
211193323Sed          for (unsigned i = 0, e = Writers.size(); i != e; ++i)
212193323Sed            FunctionInfo[Writers[i]].GlobalInfo[I] |= Mod;
213193323Sed        ++NumNonAddrTakenGlobalVars;
214193323Sed
215193323Sed        // If this global holds a pointer type, see if it is an indirect global.
216204642Srdivacky        if (I->getType()->getElementType()->isPointerTy() &&
217193323Sed            AnalyzeIndirectGlobalMemory(I))
218193323Sed          ++NumIndirectGlobalVars;
219193323Sed      }
220193323Sed      Readers.clear(); Writers.clear();
221193323Sed    }
222193323Sed}
223193323Sed
224193323Sed/// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer.
225193323Sed/// If this is used by anything complex (i.e., the address escapes), return
226193323Sed/// true.  Also, while we are at it, keep track of those functions that read and
227193323Sed/// write to the value.
228193323Sed///
229193323Sed/// If OkayStoreDest is non-null, stores into this global are allowed.
230193323Sedbool GlobalsModRef::AnalyzeUsesOfPointer(Value *V,
231193323Sed                                         std::vector<Function*> &Readers,
232193323Sed                                         std::vector<Function*> &Writers,
233193323Sed                                         GlobalValue *OkayStoreDest) {
234204642Srdivacky  if (!V->getType()->isPointerTy()) return true;
235193323Sed
236193323Sed  for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
237193323Sed    if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
238193323Sed      Readers.push_back(LI->getParent()->getParent());
239193323Sed    } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
240193323Sed      if (V == SI->getOperand(1)) {
241193323Sed        Writers.push_back(SI->getParent()->getParent());
242193323Sed      } else if (SI->getOperand(1) != OkayStoreDest) {
243193323Sed        return true;  // Storing the pointer
244193323Sed      }
245193323Sed    } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
246193323Sed      if (AnalyzeUsesOfPointer(GEP, Readers, Writers)) return true;
247198090Srdivacky    } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
248198090Srdivacky      if (AnalyzeUsesOfPointer(BCI, Readers, Writers, OkayStoreDest))
249198090Srdivacky        return true;
250198892Srdivacky    } else if (isFreeCall(*UI)) {
251198892Srdivacky      Writers.push_back(cast<Instruction>(*UI)->getParent()->getParent());
252193323Sed    } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
253193323Sed      // Make sure that this is just the function being called, not that it is
254193323Sed      // passing into the function.
255193323Sed      for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
256193323Sed        if (CI->getOperand(i) == V) return true;
257193323Sed    } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
258193323Sed      // Make sure that this is just the function being called, not that it is
259193323Sed      // passing into the function.
260193323Sed      for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
261193323Sed        if (II->getOperand(i) == V) return true;
262193323Sed    } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
263193323Sed      if (CE->getOpcode() == Instruction::GetElementPtr ||
264193323Sed          CE->getOpcode() == Instruction::BitCast) {
265193323Sed        if (AnalyzeUsesOfPointer(CE, Readers, Writers))
266193323Sed          return true;
267193323Sed      } else {
268193323Sed        return true;
269193323Sed      }
270193323Sed    } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
271193323Sed      if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
272193323Sed        return true;  // Allow comparison against null.
273193323Sed    } else {
274193323Sed      return true;
275193323Sed    }
276193323Sed  return false;
277193323Sed}
278193323Sed
279193323Sed/// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable
280193323Sed/// which holds a pointer type.  See if the global always points to non-aliased
281193323Sed/// heap memory: that is, all initializers of the globals are allocations, and
282193323Sed/// those allocations have no use other than initialization of the global.
283193323Sed/// Further, all loads out of GV must directly use the memory, not store the
284193323Sed/// pointer somewhere.  If this is true, we consider the memory pointed to by
285193323Sed/// GV to be owned by GV and can disambiguate other pointers from it.
286193323Sedbool GlobalsModRef::AnalyzeIndirectGlobalMemory(GlobalValue *GV) {
287193323Sed  // Keep track of values related to the allocation of the memory, f.e. the
288193323Sed  // value produced by the malloc call and any casts.
289193323Sed  std::vector<Value*> AllocRelatedValues;
290193323Sed
291193323Sed  // Walk the user list of the global.  If we find anything other than a direct
292193323Sed  // load or store, bail out.
293193323Sed  for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
294193323Sed    if (LoadInst *LI = dyn_cast<LoadInst>(*I)) {
295193323Sed      // The pointer loaded from the global can only be used in simple ways:
296193323Sed      // we allow addressing of it and loading storing to it.  We do *not* allow
297193323Sed      // storing the loaded pointer somewhere else or passing to a function.
298193323Sed      std::vector<Function*> ReadersWriters;
299193323Sed      if (AnalyzeUsesOfPointer(LI, ReadersWriters, ReadersWriters))
300193323Sed        return false;  // Loaded pointer escapes.
301193323Sed      // TODO: Could try some IP mod/ref of the loaded pointer.
302193323Sed    } else if (StoreInst *SI = dyn_cast<StoreInst>(*I)) {
303193323Sed      // Storing the global itself.
304193323Sed      if (SI->getOperand(0) == GV) return false;
305193323Sed
306193323Sed      // If storing the null pointer, ignore it.
307193323Sed      if (isa<ConstantPointerNull>(SI->getOperand(0)))
308193323Sed        continue;
309193323Sed
310193323Sed      // Check the value being stored.
311193323Sed      Value *Ptr = SI->getOperand(0)->getUnderlyingObject();
312193323Sed
313198396Srdivacky      if (isMalloc(Ptr)) {
314193323Sed        // Okay, easy case.
315193323Sed      } else if (CallInst *CI = dyn_cast<CallInst>(Ptr)) {
316193323Sed        Function *F = CI->getCalledFunction();
317193323Sed        if (!F || !F->isDeclaration()) return false;     // Too hard to analyze.
318193323Sed        if (F->getName() != "calloc") return false;   // Not calloc.
319193323Sed      } else {
320193323Sed        return false;  // Too hard to analyze.
321193323Sed      }
322193323Sed
323193323Sed      // Analyze all uses of the allocation.  If any of them are used in a
324193323Sed      // non-simple way (e.g. stored to another global) bail out.
325193323Sed      std::vector<Function*> ReadersWriters;
326193323Sed      if (AnalyzeUsesOfPointer(Ptr, ReadersWriters, ReadersWriters, GV))
327193323Sed        return false;  // Loaded pointer escapes.
328193323Sed
329193323Sed      // Remember that this allocation is related to the indirect global.
330193323Sed      AllocRelatedValues.push_back(Ptr);
331193323Sed    } else {
332193323Sed      // Something complex, bail out.
333193323Sed      return false;
334193323Sed    }
335193323Sed  }
336193323Sed
337193323Sed  // Okay, this is an indirect global.  Remember all of the allocations for
338193323Sed  // this global in AllocsForIndirectGlobals.
339193323Sed  while (!AllocRelatedValues.empty()) {
340193323Sed    AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV;
341193323Sed    AllocRelatedValues.pop_back();
342193323Sed  }
343193323Sed  IndirectGlobals.insert(GV);
344193323Sed  return true;
345193323Sed}
346193323Sed
347193323Sed/// AnalyzeCallGraph - At this point, we know the functions where globals are
348193323Sed/// immediately stored to and read from.  Propagate this information up the call
349193323Sed/// graph to all callers and compute the mod/ref info for all memory for each
350193323Sed/// function.
351193323Sedvoid GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) {
352193323Sed  // We do a bottom-up SCC traversal of the call graph.  In other words, we
353193323Sed  // visit all callees before callers (leaf-first).
354193323Sed  for (scc_iterator<CallGraph*> I = scc_begin(&CG), E = scc_end(&CG); I != E;
355193323Sed       ++I) {
356193323Sed    std::vector<CallGraphNode *> &SCC = *I;
357193323Sed    assert(!SCC.empty() && "SCC with no functions?");
358193323Sed
359193323Sed    if (!SCC[0]->getFunction()) {
360193323Sed      // Calls externally - can't say anything useful.  Remove any existing
361193323Sed      // function records (may have been created when scanning globals).
362193323Sed      for (unsigned i = 0, e = SCC.size(); i != e; ++i)
363193323Sed        FunctionInfo.erase(SCC[i]->getFunction());
364193323Sed      continue;
365193323Sed    }
366193323Sed
367193323Sed    FunctionRecord &FR = FunctionInfo[SCC[0]->getFunction()];
368193323Sed
369193323Sed    bool KnowNothing = false;
370193323Sed    unsigned FunctionEffect = 0;
371193323Sed
372193323Sed    // Collect the mod/ref properties due to called functions.  We only compute
373193323Sed    // one mod-ref set.
374193323Sed    for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
375193323Sed      Function *F = SCC[i]->getFunction();
376193323Sed      if (!F) {
377193323Sed        KnowNothing = true;
378193323Sed        break;
379193323Sed      }
380193323Sed
381193323Sed      if (F->isDeclaration()) {
382193323Sed        // Try to get mod/ref behaviour from function attributes.
383193323Sed        if (F->doesNotAccessMemory()) {
384193323Sed          // Can't do better than that!
385193323Sed        } else if (F->onlyReadsMemory()) {
386193323Sed          FunctionEffect |= Ref;
387193323Sed          if (!F->isIntrinsic())
388193323Sed            // This function might call back into the module and read a global -
389193323Sed            // consider every global as possibly being read by this function.
390193323Sed            FR.MayReadAnyGlobal = true;
391193323Sed        } else {
392193323Sed          FunctionEffect |= ModRef;
393193323Sed          // Can't say anything useful unless it's an intrinsic - they don't
394193323Sed          // read or write global variables of the kind considered here.
395193323Sed          KnowNothing = !F->isIntrinsic();
396193323Sed        }
397193323Sed        continue;
398193323Sed      }
399193323Sed
400193323Sed      for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
401193323Sed           CI != E && !KnowNothing; ++CI)
402193323Sed        if (Function *Callee = CI->second->getFunction()) {
403193323Sed          if (FunctionRecord *CalleeFR = getFunctionInfo(Callee)) {
404193323Sed            // Propagate function effect up.
405193323Sed            FunctionEffect |= CalleeFR->FunctionEffect;
406193323Sed
407193323Sed            // Incorporate callee's effects on globals into our info.
408193323Sed            for (std::map<GlobalValue*, unsigned>::iterator GI =
409193323Sed                   CalleeFR->GlobalInfo.begin(), E = CalleeFR->GlobalInfo.end();
410193323Sed                 GI != E; ++GI)
411193323Sed              FR.GlobalInfo[GI->first] |= GI->second;
412193323Sed            FR.MayReadAnyGlobal |= CalleeFR->MayReadAnyGlobal;
413193323Sed          } else {
414193323Sed            // Can't say anything about it.  However, if it is inside our SCC,
415193323Sed            // then nothing needs to be done.
416193323Sed            CallGraphNode *CalleeNode = CG[Callee];
417193323Sed            if (std::find(SCC.begin(), SCC.end(), CalleeNode) == SCC.end())
418193323Sed              KnowNothing = true;
419193323Sed          }
420193323Sed        } else {
421193323Sed          KnowNothing = true;
422193323Sed        }
423193323Sed    }
424193323Sed
425193323Sed    // If we can't say anything useful about this SCC, remove all SCC functions
426193323Sed    // from the FunctionInfo map.
427193323Sed    if (KnowNothing) {
428193323Sed      for (unsigned i = 0, e = SCC.size(); i != e; ++i)
429193323Sed        FunctionInfo.erase(SCC[i]->getFunction());
430193323Sed      continue;
431193323Sed    }
432193323Sed
433193323Sed    // Scan the function bodies for explicit loads or stores.
434193323Sed    for (unsigned i = 0, e = SCC.size(); i != e && FunctionEffect != ModRef;++i)
435193323Sed      for (inst_iterator II = inst_begin(SCC[i]->getFunction()),
436193323Sed             E = inst_end(SCC[i]->getFunction());
437193323Sed           II != E && FunctionEffect != ModRef; ++II)
438193323Sed        if (isa<LoadInst>(*II)) {
439193323Sed          FunctionEffect |= Ref;
440193323Sed          if (cast<LoadInst>(*II).isVolatile())
441193323Sed            // Volatile loads may have side-effects, so mark them as writing
442193323Sed            // memory (for example, a flag inside the processor).
443193323Sed            FunctionEffect |= Mod;
444193323Sed        } else if (isa<StoreInst>(*II)) {
445193323Sed          FunctionEffect |= Mod;
446193323Sed          if (cast<StoreInst>(*II).isVolatile())
447193323Sed            // Treat volatile stores as reading memory somewhere.
448193323Sed            FunctionEffect |= Ref;
449198892Srdivacky        } else if (isMalloc(&cast<Instruction>(*II)) ||
450198892Srdivacky                   isFreeCall(&cast<Instruction>(*II))) {
451193323Sed          FunctionEffect |= ModRef;
452193323Sed        }
453193323Sed
454193323Sed    if ((FunctionEffect & Mod) == 0)
455193323Sed      ++NumReadMemFunctions;
456193323Sed    if (FunctionEffect == 0)
457193323Sed      ++NumNoMemFunctions;
458193323Sed    FR.FunctionEffect = FunctionEffect;
459193323Sed
460193323Sed    // Finally, now that we know the full effect on this SCC, clone the
461193323Sed    // information to each function in the SCC.
462193323Sed    for (unsigned i = 1, e = SCC.size(); i != e; ++i)
463193323Sed      FunctionInfo[SCC[i]->getFunction()] = FR;
464193323Sed  }
465193323Sed}
466193323Sed
467193323Sed
468193323Sed
469193323Sed/// alias - If one of the pointers is to a global that we are tracking, and the
470193323Sed/// other is some random pointer, we know there cannot be an alias, because the
471193323Sed/// address of the global isn't taken.
472193323SedAliasAnalysis::AliasResult
473193323SedGlobalsModRef::alias(const Value *V1, unsigned V1Size,
474193323Sed                     const Value *V2, unsigned V2Size) {
475193323Sed  // Get the base object these pointers point to.
476193323Sed  Value *UV1 = const_cast<Value*>(V1->getUnderlyingObject());
477193323Sed  Value *UV2 = const_cast<Value*>(V2->getUnderlyingObject());
478193323Sed
479193323Sed  // If either of the underlying values is a global, they may be non-addr-taken
480193323Sed  // globals, which we can answer queries about.
481193323Sed  GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1);
482193323Sed  GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2);
483193323Sed  if (GV1 || GV2) {
484193323Sed    // If the global's address is taken, pretend we don't know it's a pointer to
485193323Sed    // the global.
486193323Sed    if (GV1 && !NonAddressTakenGlobals.count(GV1)) GV1 = 0;
487193323Sed    if (GV2 && !NonAddressTakenGlobals.count(GV2)) GV2 = 0;
488193323Sed
489203954Srdivacky    // If the two pointers are derived from two different non-addr-taken
490193323Sed    // globals, or if one is and the other isn't, we know these can't alias.
491193323Sed    if ((GV1 || GV2) && GV1 != GV2)
492193323Sed      return NoAlias;
493193323Sed
494193323Sed    // Otherwise if they are both derived from the same addr-taken global, we
495193323Sed    // can't know the two accesses don't overlap.
496193323Sed  }
497193323Sed
498193323Sed  // These pointers may be based on the memory owned by an indirect global.  If
499193323Sed  // so, we may be able to handle this.  First check to see if the base pointer
500193323Sed  // is a direct load from an indirect global.
501193323Sed  GV1 = GV2 = 0;
502193323Sed  if (LoadInst *LI = dyn_cast<LoadInst>(UV1))
503193323Sed    if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
504193323Sed      if (IndirectGlobals.count(GV))
505193323Sed        GV1 = GV;
506193323Sed  if (LoadInst *LI = dyn_cast<LoadInst>(UV2))
507193323Sed    if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
508193323Sed      if (IndirectGlobals.count(GV))
509193323Sed        GV2 = GV;
510193323Sed
511193323Sed  // These pointers may also be from an allocation for the indirect global.  If
512193323Sed  // so, also handle them.
513193323Sed  if (AllocsForIndirectGlobals.count(UV1))
514193323Sed    GV1 = AllocsForIndirectGlobals[UV1];
515193323Sed  if (AllocsForIndirectGlobals.count(UV2))
516193323Sed    GV2 = AllocsForIndirectGlobals[UV2];
517193323Sed
518193323Sed  // Now that we know whether the two pointers are related to indirect globals,
519193323Sed  // use this to disambiguate the pointers.  If either pointer is based on an
520193323Sed  // indirect global and if they are not both based on the same indirect global,
521193323Sed  // they cannot alias.
522193323Sed  if ((GV1 || GV2) && GV1 != GV2)
523193323Sed    return NoAlias;
524193323Sed
525193323Sed  return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
526193323Sed}
527193323Sed
528193323SedAliasAnalysis::ModRefResult
529193323SedGlobalsModRef::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
530193323Sed  unsigned Known = ModRef;
531193323Sed
532193323Sed  // If we are asking for mod/ref info of a direct call with a pointer to a
533193323Sed  // global we are tracking, return information if we have it.
534193323Sed  if (GlobalValue *GV = dyn_cast<GlobalValue>(P->getUnderlyingObject()))
535193323Sed    if (GV->hasLocalLinkage())
536193323Sed      if (Function *F = CS.getCalledFunction())
537193323Sed        if (NonAddressTakenGlobals.count(GV))
538193323Sed          if (FunctionRecord *FR = getFunctionInfo(F))
539193323Sed            Known = FR->getInfoForGlobal(GV);
540193323Sed
541193323Sed  if (Known == NoModRef)
542193323Sed    return NoModRef; // No need to query other mod/ref analyses
543193323Sed  return ModRefResult(Known & AliasAnalysis::getModRefInfo(CS, P, Size));
544193323Sed}
545193323Sed
546193323Sed
547193323Sed//===----------------------------------------------------------------------===//
548193323Sed// Methods to update the analysis as a result of the client transformation.
549193323Sed//
550193323Sedvoid GlobalsModRef::deleteValue(Value *V) {
551193323Sed  if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
552193323Sed    if (NonAddressTakenGlobals.erase(GV)) {
553193323Sed      // This global might be an indirect global.  If so, remove it and remove
554193323Sed      // any AllocRelatedValues for it.
555193323Sed      if (IndirectGlobals.erase(GV)) {
556193323Sed        // Remove any entries in AllocsForIndirectGlobals for this global.
557193323Sed        for (std::map<Value*, GlobalValue*>::iterator
558193323Sed             I = AllocsForIndirectGlobals.begin(),
559193323Sed             E = AllocsForIndirectGlobals.end(); I != E; ) {
560193323Sed          if (I->second == GV) {
561193323Sed            AllocsForIndirectGlobals.erase(I++);
562193323Sed          } else {
563193323Sed            ++I;
564193323Sed          }
565193323Sed        }
566193323Sed      }
567193323Sed    }
568193323Sed  }
569193323Sed
570193323Sed  // Otherwise, if this is an allocation related to an indirect global, remove
571193323Sed  // it.
572193323Sed  AllocsForIndirectGlobals.erase(V);
573193323Sed
574193323Sed  AliasAnalysis::deleteValue(V);
575193323Sed}
576193323Sed
577193323Sedvoid GlobalsModRef::copyValue(Value *From, Value *To) {
578193323Sed  AliasAnalysis::copyValue(From, To);
579193323Sed}
580